afyx-engineering-kit 0.1.0-alpha.7 → 0.1.0-alpha.8
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/.afyx-source-revision +1 -1
- package/afyx-context/src/budget.js +39 -153
- package/afyx-context/src/documentation.js +116 -0
- package/afyx-context/src/index.js +2 -0
- package/afyx-context/src/memory.js +122 -229
- package/afyx-context/src/usage.js +91 -0
- package/afyx-forge/src/cli.js +14 -1
- package/afyx-forge/src/index.js +3 -0
- package/afyx-forge/src/workflow-refiner.js +48 -15
- package/afyx-forge/src/workflow.js +226 -0
- package/afyx-graph/engine/release/RELEASE-MANIFEST.json +16 -6
- package/afyx-graph/engine/release/SHA256SUMS +4 -2
- package/afyx-graph/engine/release/afyx-graph-darwin-arm64.tar.gz +0 -0
- package/afyx-graph/engine/release/afyx-graph-darwin-x64.tar.gz +0 -0
- package/afyx-graph/engine/release/afyx-graph-linux-x64.tar.gz +0 -0
- package/afyx-graph/engine/release/afyx-graph-win32-x64.zip +0 -0
- package/bin/afyx-engineering-kit.mjs +14 -6
- package/install.ps1 +52 -6
- package/install.sh +11 -7
- package/package.json +3 -1
- package/scripts/afyx-capability-orchestrator.mjs +159 -41
- package/scripts/afyx-graph-artifact.mjs +1 -1
- package/scripts/afyx-graph-targets.mjs +8 -0
- package/scripts/afyx-host-adapters.mjs +52 -0
- package/scripts/afyx-host-bridge-lifecycle.mjs +4 -0
- package/scripts/afyx-host-bridge.mjs +25 -0
- package/scripts/afyx-install-backend.mjs +34 -13
- package/scripts/afyx-install-contract.mjs +5 -2
- package/scripts/afyx-install-progress.mjs +88 -0
- package/scripts/afyx-installer-environment.mjs +150 -0
- package/scripts/afyx-local-link-ownership.mjs +16 -0
- package/scripts/afyx-midnight-circuit.mjs +322 -79
- package/scripts/afyx-modular-integration.mjs +3 -0
- package/scripts/afyx-modular-runtime.mjs +3 -0
- package/scripts/afyx-native-execution.mjs +168 -0
- package/scripts/afyx-native-github.mjs +155 -0
- package/scripts/afyx-npm-installer.mjs +56 -28
- package/scripts/afyx-provider-inventory.mjs +6 -3
- package/scripts/afyx-security-auditor.mjs +61 -64
- package/scripts/afyx-skill-catalog.mjs +83 -0
- package/scripts/afyx-skill-engineering.mjs +2 -0
- package/scripts/afyx-universal-runtime.mjs +74 -12
- package/scripts/install-afyx-graph.sh +4 -4
- package/scripts/lib/AfyxInstallerProgress.psm1 +11 -0
- package/scripts/lib/AfyxSkillLifecycle.psm1 +42 -6
- package/scripts/lib/afyx-installer-progress.sh +30 -0
- package/scripts/link-global-dev.ps1 +10 -3
- package/scripts/link-global-dev.sh +10 -8
- package/scripts/prepare-g6-package.mjs +13 -28
- package/scripts/resolve-git-release-artifacts.mjs +5 -4
- package/scripts/stage-npm-release.mjs +3 -1
- package/scripts/validate-release-zip-graph.mjs +2 -2
- package/uninstall.ps1 +2 -0
- package/verify.ps1 +7 -1
- package/verify.sh +5 -3
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { lstatSync, realpathSync, statSync } from 'node:fs';
|
|
4
|
+
import { basename, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
5
|
+
|
|
6
|
+
export const NATIVE_EXECUTION_CONTRACT = 'AfyxNativeExecution/v1';
|
|
7
|
+
const NAME = /^[a-z][a-z0-9-]{0,63}$/;
|
|
8
|
+
const ENV_KEYS = ['PATH', 'SystemRoot', 'WINDIR', 'TEMP', 'TMP'];
|
|
9
|
+
const SECRET_KEY = /token|secret|password|credential|authorization|api.?key/i;
|
|
10
|
+
const sha = (value) => createHash('sha256').update(value).digest('hex');
|
|
11
|
+
const plain = (value) => value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
|
|
12
|
+
function inside(root, target) {
|
|
13
|
+
const rel = relative(root, target);
|
|
14
|
+
return !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`);
|
|
15
|
+
}
|
|
16
|
+
function bounded(value, fallback, ceiling) {
|
|
17
|
+
const selected = value ?? fallback;
|
|
18
|
+
if (!Number.isSafeInteger(selected) || selected < 1 || selected > ceiling) throw new Error('INVALID_LIMIT');
|
|
19
|
+
return selected;
|
|
20
|
+
}
|
|
21
|
+
function compile(spec) {
|
|
22
|
+
if (!plain(spec) || !NAME.test(spec.id) || !isAbsolute(spec.executable)
|
|
23
|
+
|| !['read', 'mutation'].includes(spec.effect) || !Array.isArray(spec.argv) || spec.argv.length > 64
|
|
24
|
+
|| (spec.privileged !== undefined && typeof spec.privileged !== 'boolean')) throw new Error('INVALID_CATALOG');
|
|
25
|
+
const allowed = ['id', 'executable', 'effect', 'argv', 'parameters', 'privileged', 'timeoutMs', 'maxOutputBytes', 'environmentKeys'];
|
|
26
|
+
if (Object.keys(spec).some((key) => !allowed.includes(key))) throw new Error('INVALID_CATALOG');
|
|
27
|
+
const executable = realpathSync(spec.executable);
|
|
28
|
+
if (!statSync(executable).isFile() || /\.(?:cmd|bat|ps1|sh)$/i.test(executable)) throw new Error('NATIVE_EXECUTABLE_REQUIRED');
|
|
29
|
+
const parameters = spec.parameters ?? {};
|
|
30
|
+
if (!plain(parameters) || Object.keys(parameters).length > 32) throw new Error('INVALID_PARAMETERS');
|
|
31
|
+
const validated = {};
|
|
32
|
+
for (const [name, rule] of Object.entries(parameters)) {
|
|
33
|
+
if (!NAME.test(name) || !plain(rule) || !['string', 'integer', 'enum'].includes(rule.type)
|
|
34
|
+
|| Object.keys(rule).some((key) => !['type', 'required', 'values', 'min', 'max', 'maxLength', 'flag'].includes(key))
|
|
35
|
+
|| (rule.flag !== undefined && !/^--[a-z][a-z0-9-]{0,63}$/.test(rule.flag))
|
|
36
|
+
|| (rule.required !== undefined && typeof rule.required !== 'boolean')) throw new Error('INVALID_PARAMETERS');
|
|
37
|
+
if (rule.type === 'enum' && (!Array.isArray(rule.values) || !rule.values.length || rule.values.length > 64
|
|
38
|
+
|| rule.values.some((value) => typeof value !== 'string' || value.length > 256 || /[\0\r\n]/.test(value)))) throw new Error('INVALID_ENUM');
|
|
39
|
+
if (rule.type === 'integer' && ((rule.min !== undefined && !Number.isSafeInteger(rule.min))
|
|
40
|
+
|| (rule.max !== undefined && !Number.isSafeInteger(rule.max)) || (rule.min ?? 0) > (rule.max ?? Number.MAX_SAFE_INTEGER))) throw new Error('INVALID_RANGE');
|
|
41
|
+
validated[name] = Object.freeze({ ...rule, maxLength: bounded(rule.maxLength, 256, 4096), values: rule.values ? Object.freeze([...rule.values]) : undefined });
|
|
42
|
+
}
|
|
43
|
+
const argv = spec.argv.map((part) => {
|
|
44
|
+
if (typeof part === 'string' && part.length <= 4096 && !/[\0\r\n]/.test(part)) return part;
|
|
45
|
+
if (!plain(part) || Object.keys(part).length !== 1 || !Object.hasOwn(validated, part.parameter)) throw new Error('INVALID_ARGV');
|
|
46
|
+
return Object.freeze({ parameter: part.parameter });
|
|
47
|
+
});
|
|
48
|
+
// Interpreter command strings are deliberately outside this adapter contract.
|
|
49
|
+
const interpreter = /^(?:node|python(?:\d+(?:\.\d+)*)?|ruby|perl|sh|bash|zsh|cmd|pwsh|powershell)(?:\.exe)?$/i.test(basename(executable));
|
|
50
|
+
if (interpreter && argv.some((arg) => typeof arg === 'string'
|
|
51
|
+
&& /^(?:--(?:eval|print|require|import|loader|experimental-loader)(?:=|$)|-[eprc](?:$|[^a-z])|\/c(?:$|[ :=])|-(?:command|encodedcommand)(?:$|[ :=]))/i.test(arg))) throw new Error('INTERPRETER_COMMAND_DENIED');
|
|
52
|
+
if (interpreter) {
|
|
53
|
+
const inspection = argv.length === 1 && ['--version', '-v', '--help'].includes(argv[0]);
|
|
54
|
+
// A model may supply arguments to a host-pinned script, never its entrypoint or interpreter flags.
|
|
55
|
+
const pinnedScript = typeof argv[0] === 'string' && isAbsolute(argv[0]) && statSync(argv[0]).isFile();
|
|
56
|
+
if (!inspection && !pinnedScript) throw new Error('INTERPRETER_ENTRYPOINT_REQUIRED');
|
|
57
|
+
}
|
|
58
|
+
const environmentKeys = spec.environmentKeys ?? ENV_KEYS;
|
|
59
|
+
if (!Array.isArray(environmentKeys) || environmentKeys.length > 32
|
|
60
|
+
|| environmentKeys.some((key) => typeof key !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || SECRET_KEY.test(key) || /^NODE_OPTIONS$/i.test(key))) throw new Error('UNSAFE_ENVIRONMENT');
|
|
61
|
+
return Object.freeze({ id: spec.id, executable, effect: spec.effect, privileged: spec.privileged === true,
|
|
62
|
+
argv: Object.freeze(argv), parameters: Object.freeze(validated), environmentKeys: Object.freeze([...environmentKeys]),
|
|
63
|
+
timeoutMs: bounded(spec.timeoutMs, 5000, 60_000), maxOutputBytes: bounded(spec.maxOutputBytes, 65_536, 1_048_576) });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Trusted host configuration compiles adapters; task JSON can only select validated parameters. */
|
|
67
|
+
export function createNativeExecution({ projectRoot, catalog, authorize, environment = process.env } = {}) {
|
|
68
|
+
if (typeof projectRoot !== 'string' || !isAbsolute(projectRoot) || lstatSync(projectRoot).isSymbolicLink()
|
|
69
|
+
|| !statSync(projectRoot).isDirectory()) throw new Error('TRUSTED_PROJECT_ROOT_REQUIRED');
|
|
70
|
+
const root = realpathSync(projectRoot);
|
|
71
|
+
const specs = catalog ?? [{ id: 'node-version', executable: process.execPath, argv: ['--version'], effect: 'read' }];
|
|
72
|
+
if (!Array.isArray(specs) || specs.length > 64) throw new Error('INVALID_CATALOG');
|
|
73
|
+
const entries = new Map();
|
|
74
|
+
for (const spec of specs) {
|
|
75
|
+
const entry = compile(spec);
|
|
76
|
+
if (entries.has(entry.id)) throw new Error('DUPLICATE_CAPABILITY');
|
|
77
|
+
entries.set(entry.id, entry);
|
|
78
|
+
}
|
|
79
|
+
const hostEnvironment = Object.freeze({ ...environment });
|
|
80
|
+
const discover = () => [...entries.values()].map(({ id, effect, privileged, parameters }) => ({ id, effect, privileged, parameters: Object.keys(parameters) }));
|
|
81
|
+
async function execute(request, { signal } = {}) {
|
|
82
|
+
const started = performance.now();
|
|
83
|
+
const receipt = { contract: NATIVE_EXECUTION_CONTRACT, capabilityId: request?.capabilityId ?? null, status: 'DENIED',
|
|
84
|
+
exitCode: null, stdoutBytes: 0, stderrBytes: 0, durationMs: 0 };
|
|
85
|
+
const finish = (status, reason, stdout = '', stderr = '') => Object.freeze({ status, reason, output: { stdout, stderr },
|
|
86
|
+
receipt: Object.freeze({ ...receipt, status, durationMs: performance.now() - started }) });
|
|
87
|
+
if (!plain(request) || Object.keys(request).some((key) => !['capabilityId', 'arguments', 'cwd'].includes(key))) return finish('DENIED', 'INVALID_REQUEST');
|
|
88
|
+
const entry = entries.get(request.capabilityId);
|
|
89
|
+
if (!entry) return finish('DENIED', 'CAPABILITY_UNAVAILABLE');
|
|
90
|
+
const input = request.arguments ?? {};
|
|
91
|
+
if (!plain(input) || Object.keys(input).some((name) => !Object.hasOwn(entry.parameters, name))) return finish('DENIED', 'INVALID_ARGUMENTS');
|
|
92
|
+
const values = {};
|
|
93
|
+
for (const [name, rule] of Object.entries(entry.parameters)) {
|
|
94
|
+
const value = input[name];
|
|
95
|
+
if (value === undefined && rule.required !== false) return finish('DENIED', 'MISSING_ARGUMENT');
|
|
96
|
+
if (value === undefined) continue;
|
|
97
|
+
const valid = rule.type === 'integer' ? Number.isSafeInteger(value) && value >= (rule.min ?? 0) && value <= (rule.max ?? Number.MAX_SAFE_INTEGER)
|
|
98
|
+
: typeof value === 'string' && value.length <= rule.maxLength && !/[\0\r\n]/.test(value) && (rule.type !== 'enum' || rule.values.includes(value));
|
|
99
|
+
if (!valid) return finish('DENIED', 'INVALID_ARGUMENTS');
|
|
100
|
+
if (typeof value === 'string' && /^[-/]/.test(value) && rule.type !== 'enum') return finish('DENIED', 'DYNAMIC_OPTION_DENIED');
|
|
101
|
+
values[name] = String(value);
|
|
102
|
+
}
|
|
103
|
+
let cwd;
|
|
104
|
+
try {
|
|
105
|
+
if (request.cwd !== undefined && typeof request.cwd !== 'string') return finish('DENIED', 'INVALID_CWD');
|
|
106
|
+
cwd = realpathSync(resolve(root, request.cwd ?? '.'));
|
|
107
|
+
if (!inside(root, cwd) || !statSync(cwd).isDirectory()) return finish('DENIED', 'CWD_OUTSIDE_ROOT');
|
|
108
|
+
} catch { return finish('DENIED', 'INVALID_CWD'); }
|
|
109
|
+
const argv = entry.argv.flatMap((part) => typeof part === 'string' ? [part] : values[part.parameter] === undefined ? []
|
|
110
|
+
: [...(entry.parameters[part.parameter].flag ? [entry.parameters[part.parameter].flag] : []), values[part.parameter]]);
|
|
111
|
+
receipt.argvDigest = sha(JSON.stringify(argv));
|
|
112
|
+
receipt.executable = entry.executable;
|
|
113
|
+
const approval = Object.freeze({ capabilityId: entry.id, effect: entry.effect, privileged: entry.privileged, cwd, argvDigest: receipt.argvDigest });
|
|
114
|
+
if (entry.effect === 'mutation' || entry.privileged) {
|
|
115
|
+
try { if (typeof authorize !== 'function' || authorize(approval) !== true) return finish('DENIED', 'HOST_APPROVAL_REQUIRED'); }
|
|
116
|
+
catch { return finish('DENIED', 'HOST_APPROVAL_REQUIRED'); }
|
|
117
|
+
}
|
|
118
|
+
if (signal?.aborted) return finish('CANCELLED', 'HOST_CANCELLED');
|
|
119
|
+
const env = {};
|
|
120
|
+
for (const key of entry.environmentKeys) {
|
|
121
|
+
const actual = Object.keys(hostEnvironment).find((candidate) => candidate.toLowerCase() === key.toLowerCase());
|
|
122
|
+
if (actual && typeof hostEnvironment[actual] === 'string') env[actual] = hostEnvironment[actual];
|
|
123
|
+
}
|
|
124
|
+
const secrets = Object.entries(hostEnvironment).filter(([key, value]) => SECRET_KEY.test(key) && typeof value === 'string' && value.length >= 4).map(([, value]) => value);
|
|
125
|
+
const redact = (value) => secrets.reduce((text, secret) => text.split(secret).join('[REDACTED]'), value);
|
|
126
|
+
return await new Promise((resolveResult) => {
|
|
127
|
+
let child;
|
|
128
|
+
try { child = spawn(entry.executable, argv, { cwd, env, shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); }
|
|
129
|
+
catch { resolveResult(finish('FAILED', 'SPAWN_FAILED')); return; }
|
|
130
|
+
const stdout = []; const stderr = []; let kept = 0; let forced = null; let settled = false;
|
|
131
|
+
let killTimer; let settleTimer;
|
|
132
|
+
const stop = (status) => {
|
|
133
|
+
if (forced || settled) return;
|
|
134
|
+
forced = status;
|
|
135
|
+
try { child.kill(); } catch { /* hard cleanup remains bounded */ }
|
|
136
|
+
killTimer = setTimeout(() => {
|
|
137
|
+
try { child.kill('SIGKILL'); } catch { /* child may already have exited */ }
|
|
138
|
+
// Descendants holding inherited pipes cannot extend the owned command deadline.
|
|
139
|
+
child.stdout.destroy(); child.stderr.destroy();
|
|
140
|
+
settleTimer = setTimeout(() => done(null), 50);
|
|
141
|
+
}, 100);
|
|
142
|
+
};
|
|
143
|
+
const abort = () => stop('CANCELLED');
|
|
144
|
+
const timer = setTimeout(() => stop('TIMEOUT'), entry.timeoutMs);
|
|
145
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
146
|
+
if (signal?.aborted) abort();
|
|
147
|
+
const collect = (chunks, key) => (chunk) => {
|
|
148
|
+
receipt[key] += chunk.length;
|
|
149
|
+
const remaining = entry.maxOutputBytes - kept;
|
|
150
|
+
if (remaining > 0) { const part = chunk.subarray(0, remaining); chunks.push(part); kept += part.length; }
|
|
151
|
+
if (receipt.stdoutBytes + receipt.stderrBytes > entry.maxOutputBytes) stop('OUTPUT_LIMIT');
|
|
152
|
+
};
|
|
153
|
+
child.stdout.on('data', collect(stdout, 'stdoutBytes'));
|
|
154
|
+
child.stderr.on('data', collect(stderr, 'stderrBytes'));
|
|
155
|
+
const done = (code, spawnError = false) => {
|
|
156
|
+
if (settled) return;
|
|
157
|
+
settled = true; clearTimeout(timer); clearTimeout(killTimer); clearTimeout(settleTimer);
|
|
158
|
+
signal?.removeEventListener('abort', abort); receipt.exitCode = code;
|
|
159
|
+
receipt.truncated = forced === 'OUTPUT_LIMIT'; receipt.terminationGraceMs = forced ? 150 : 0;
|
|
160
|
+
if (forced) { child.stdout.destroy(); child.stderr.destroy(); }
|
|
161
|
+
resolveResult(finish(forced ?? (code === 0 && !spawnError ? 'SUCCESS' : 'FAILED'), forced ?? (spawnError ? 'SPAWN_FAILED' : code === 0 ? 'COMPLETED' : 'NONZERO_EXIT'),
|
|
162
|
+
forced ? '' : redact(Buffer.concat(stdout).toString('utf8')), forced ? '' : redact(Buffer.concat(stderr).toString('utf8'))));
|
|
163
|
+
};
|
|
164
|
+
child.once('error', () => done(null, true)); child.once('close', (code) => done(code));
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return Object.freeze({ contract: NATIVE_EXECUTION_CONTRACT, discover, execute });
|
|
168
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/** AFYX scoped read-only GitHub API/MCP. Host configuration owns scope and credentials. */
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { createNativeExecution } from './afyx-native-execution.mjs';
|
|
7
|
+
|
|
8
|
+
export const GITHUB_CONTRACT = 'AfyxGitHub/v1';
|
|
9
|
+
const OPERATIONS = ['repository', 'branches', 'commits', 'file', 'issues', 'pulls', 'pull', 'workflow-runs', 'workflow-jobs', 'job-log'];
|
|
10
|
+
const LISTS = new Set(['branches', 'commits', 'issues', 'pulls', 'workflow-runs', 'workflow-jobs']);
|
|
11
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
|
|
12
|
+
const KEYS = new Set(['operation', 'owner', 'repo', 'number', 'path', 'ref', 'page', 'perPage']);
|
|
13
|
+
function endpoint(args) {
|
|
14
|
+
if (!args || Object.keys(args).some((key) => !KEYS.has(key)) || !OPERATIONS.includes(args.operation)
|
|
15
|
+
|| !NAME.test(args.owner || '') || !NAME.test(args.repo || '') || [args.owner, args.repo].some((s) => s.includes('..'))) throw new Error('INVALID_REQUEST');
|
|
16
|
+
const base = `repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}`;
|
|
17
|
+
const number = () => { if (!Number.isSafeInteger(args.number) || args.number < 1) throw new Error('INVALID_NUMBER'); return args.number; };
|
|
18
|
+
const paths = { repository: '', branches: '/branches', commits: '/commits', issues: '/issues', pulls: '/pulls', 'workflow-runs': '/actions/runs' };
|
|
19
|
+
let suffix = paths[args.operation];
|
|
20
|
+
if (args.operation === 'pull') suffix = `/pulls/${number()}`;
|
|
21
|
+
if (args.operation === 'workflow-jobs') suffix = `/actions/runs/${number()}/jobs`;
|
|
22
|
+
if (args.operation === 'job-log') suffix = `/actions/jobs/${number()}/logs`;
|
|
23
|
+
if (args.operation === 'file') {
|
|
24
|
+
if (typeof args.path !== 'string' || args.path.length > 1024 || args.path.split('/').some((p) => !p || p === '..' || p === '.') || /[\\\x00-\x1f]/.test(args.path)) throw new Error('INVALID_PATH');
|
|
25
|
+
suffix = '/contents/' + args.path.split('/').map(encodeURIComponent).join('/');
|
|
26
|
+
}
|
|
27
|
+
const query = new URLSearchParams();
|
|
28
|
+
if (args.ref !== undefined) { if (!['file', 'commits'].includes(args.operation) || typeof args.ref !== 'string' || !args.ref || args.ref.length > 256 || /[\x00-\x1f]/.test(args.ref)) throw new Error('INVALID_REF'); query.set(args.operation === 'commits' ? 'sha' : 'ref', args.ref); }
|
|
29
|
+
if (LISTS.has(args.operation)) {
|
|
30
|
+
for (const [key, fallback, max] of [['page', 1, 10000], ['perPage', 30, 100]]) {
|
|
31
|
+
const value = args[key] ?? fallback; if (!Number.isSafeInteger(value) || value < 1 || value > max) throw new Error('INVALID_PAGINATION');
|
|
32
|
+
query.set(key === 'perPage' ? 'per_page' : key, value);
|
|
33
|
+
}
|
|
34
|
+
} else if (args.page !== undefined || args.perPage !== undefined) throw new Error('INVALID_PAGINATION');
|
|
35
|
+
return base + suffix + (query.size ? '?' + query.toString() : '');
|
|
36
|
+
}
|
|
37
|
+
function redact(value, secrets) {
|
|
38
|
+
let text = typeof value === 'string' ? value : JSON.stringify(value);
|
|
39
|
+
for (const secret of secrets) if (typeof secret === 'string' && secret.length > 3) text = text.split(secret).join('[REDACTED]');
|
|
40
|
+
return text.replace(/\b(?:gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,})\b/g, '[REDACTED]')
|
|
41
|
+
.replace(/((?:api[_-]?key|secret[_-]?token|password)\s*[:=]\s*["'])([^"'\r\n]{8,})(["'])/gi, '$1[REDACTED]$3');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createGitHubReader({ allowedRepositories = [], authorize = () => true, request, maxBytes = 262144,
|
|
45
|
+
maxItems = 100, timeoutMs = 5000, secrets = [], authMode = 'PUBLIC' } = {}) {
|
|
46
|
+
if (!Array.isArray(allowedRepositories) || !allowedRepositories.length || allowedRepositories.length > 100
|
|
47
|
+
|| allowedRepositories.some((r) => typeof r !== 'string' || r.split('/').length !== 2 || r.split('/').some((n) => !NAME.test(n) || n.includes('..')))
|
|
48
|
+
|| !Number.isSafeInteger(maxBytes) || maxBytes < 128 || maxBytes > 1048576 || !Number.isSafeInteger(maxItems) || maxItems < 1 || maxItems > 100
|
|
49
|
+
|| !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000 || typeof authorize !== 'function') throw new Error('INVALID_HOST_CONFIGURATION');
|
|
50
|
+
const allowed = new Set(allowedRepositories.map((s) => s.toLowerCase()));
|
|
51
|
+
async function read(args, { signal } = {}) {
|
|
52
|
+
const started = performance.now(); let route;
|
|
53
|
+
const result = (status, code, data = null, extra = {}) => ({ contract: GITHUB_CONTRACT, status, code, data,
|
|
54
|
+
receipt: { operation: args?.operation || null, authMode, durationMs: performance.now() - started, ...extra } });
|
|
55
|
+
try { route = endpoint(args); } catch { return result('DENIED', 'INVALID_REQUEST'); }
|
|
56
|
+
if (!allowed.has(`${args.owner}/${args.repo}`.toLowerCase())) return result('DENIED', 'REPOSITORY_OUTSIDE_SCOPE');
|
|
57
|
+
try { if (authorize(Object.freeze({ repository: `${args.owner}/${args.repo}`, operation: args.operation, method: 'GET' })) !== true) return result('DENIED', 'HOST_AUTHORIZATION_REQUIRED'); }
|
|
58
|
+
catch { return result('DENIED', 'HOST_AUTHORIZATION_REQUIRED'); }
|
|
59
|
+
const controller = new AbortController(); const abort = () => controller.abort();
|
|
60
|
+
if (signal?.aborted) return result('CANCELLED', 'HOST_CANCELLED');
|
|
61
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
62
|
+
const timer = setTimeout(abort, timeoutMs);
|
|
63
|
+
try {
|
|
64
|
+
let response;
|
|
65
|
+
const operation = async () => {
|
|
66
|
+
if (request) return request(Object.freeze({ endpoint: route, method: 'GET', signal: controller.signal, maxBytes }));
|
|
67
|
+
const raw = await fetch(`https://api.github.com/${route}`, { method: 'GET', redirect: 'manual', signal: controller.signal,
|
|
68
|
+
headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'AFYX-Native-GitHub', 'X-GitHub-Api-Version': '2022-11-28' } });
|
|
69
|
+
if (raw.status >= 300 && raw.status < 400) { await raw.body?.cancel(); return { status: raw.status, body: '', headers: {} }; }
|
|
70
|
+
let bytes = 0; const chunks = [];
|
|
71
|
+
for await (const chunk of raw.body ?? []) { bytes += chunk.length; if (bytes > maxBytes) throw new Error('OUTPUT_LIMIT'); chunks.push(chunk); }
|
|
72
|
+
return { status: raw.status, body: Buffer.concat(chunks).toString('utf8'), headers: Object.fromEntries(raw.headers) };
|
|
73
|
+
};
|
|
74
|
+
const deadline = new Promise((_, reject) => controller.signal.addEventListener('abort', () => reject(new Error('ABORTED')), { once: true }));
|
|
75
|
+
response = await Promise.race([operation(), deadline]);
|
|
76
|
+
if (!response || !Number.isInteger(response.status)) return result('FAILED', 'INVALID_HOST_RESPONSE');
|
|
77
|
+
const rate = { remaining: response.headers?.['x-ratelimit-remaining'] ?? null, reset: response.headers?.['x-ratelimit-reset'] ?? null };
|
|
78
|
+
if ([403, 429].includes(response.status)) return result('FAILED', 'RATE_LIMIT_OR_PERMISSION', null, { rate, retryAfter: response.headers?.['retry-after'] ?? null });
|
|
79
|
+
if (response.status >= 300 && response.status < 400) return result('BLOCKED', 'LOG_REDIRECT_REQUIRES_TRUSTED_HOST');
|
|
80
|
+
if (response.status !== 200) return result('FAILED', 'GITHUB_HTTP_ERROR', null, { httpStatus: response.status });
|
|
81
|
+
const raw = typeof response.body === 'string' ? response.body : JSON.stringify(response.body);
|
|
82
|
+
if (Buffer.byteLength(raw) > maxBytes) return result('FAILED', 'OUTPUT_LIMIT');
|
|
83
|
+
const safe = redact(raw, secrets); let data;
|
|
84
|
+
try { data = JSON.parse(safe); } catch { if (args.operation !== 'job-log') return result('FAILED', 'INVALID_GITHUB_JSON'); data = safe; }
|
|
85
|
+
let contentRedacted = false;
|
|
86
|
+
if (args.operation === 'file' && data?.encoding === 'base64' && typeof data.content === 'string') {
|
|
87
|
+
const decoded = Buffer.from(data.content, 'base64');
|
|
88
|
+
if (decoded.length > maxBytes) return result('FAILED', 'OUTPUT_LIMIT');
|
|
89
|
+
const source = decoded.toString('utf8'), sanitized = redact(source, secrets);
|
|
90
|
+
if (sanitized !== source) {
|
|
91
|
+
data = { ...data, content: Buffer.from(sanitized).toString('base64'), afyxContentDisposition: 'REDACTED_SOURCE_NOT_BYTE_EXACT' };
|
|
92
|
+
contentRedacted = true;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const list = Array.isArray(data) ? data : data?.workflow_runs ?? data?.jobs;
|
|
96
|
+
const received = Array.isArray(list) ? list.length : null;
|
|
97
|
+
if (Array.isArray(list)) {
|
|
98
|
+
const bounded = list.slice(0, maxItems);
|
|
99
|
+
if (Array.isArray(data)) data = bounded;
|
|
100
|
+
else data = { ...data, [data.workflow_runs ? 'workflow_runs' : 'jobs']: bounded };
|
|
101
|
+
}
|
|
102
|
+
return result('SUCCESS', 'READ_ONLY', data, { endpoint: route, bytes: Buffer.byteLength(safe), sha256: createHash('sha256').update(JSON.stringify(data)).digest('hex'), contentRedacted, rate,
|
|
103
|
+
pagination: LISTS.has(args.operation) ? { page: args.page ?? 1, perPage: args.perPage ?? 30, returned: Math.min(received ?? 0, maxItems),
|
|
104
|
+
nextPageCandidate: received === (args.perPage ?? 30) ? (args.page ?? 1) + 1 : null, truncated: received > maxItems, automaticFollow: false } : null });
|
|
105
|
+
} catch (error) { return result(controller.signal.aborted ? signal?.aborted ? 'CANCELLED' : 'TIMEOUT' : 'FAILED', error.message === 'OUTPUT_LIMIT' ? 'OUTPUT_LIMIT' : 'REQUEST_FAILED'); }
|
|
106
|
+
finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
|
|
107
|
+
}
|
|
108
|
+
return Object.freeze({ read, inventory: () => ({ contract: GITHUB_CONTRACT, operations: [...OPERATIONS], repositories: [...allowed], authMode, readOnly: true }) });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Uses an existing native gh credential session; credentials never enter task JSON or results. */
|
|
112
|
+
export function createGhRequest({ executable, projectRoot, environment = process.env } = {}) {
|
|
113
|
+
const executor = createNativeExecution({ projectRoot, environment, catalog: [{ id: 'github-get', executable, effect: 'read',
|
|
114
|
+
argv: ['api', { parameter: 'endpoint' }, '--method', 'GET'], parameters: { endpoint: { type: 'string', maxLength: 4096 } },
|
|
115
|
+
environmentKeys: ['PATH', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'SystemRoot', 'GH_CONFIG_DIR'], maxOutputBytes: 1048576, timeoutMs: 10000 }] });
|
|
116
|
+
return async ({ endpoint: route, signal, maxBytes }) => {
|
|
117
|
+
if (typeof route !== 'string' || !route.startsWith('repos/') || route.includes('\0')) throw new Error('INVALID_ENDPOINT');
|
|
118
|
+
const result = await executor.execute({ capabilityId: 'github-get', arguments: { endpoint: route } }, { signal });
|
|
119
|
+
if (result.status !== 'SUCCESS') return { status: 502, body: '', headers: {} };
|
|
120
|
+
if (Buffer.byteLength(result.output.stdout) > maxBytes) throw new Error('OUTPUT_LIMIT');
|
|
121
|
+
return { status: 200, body: result.output.stdout, headers: {} };
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function serveGitHubMcp({ reader, input = process.stdin, output = process.stdout } = {}) {
|
|
126
|
+
if (!reader?.read) throw new Error('GITHUB_READER_REQUIRED');
|
|
127
|
+
const send = (x) => output.write(JSON.stringify(x) + '\n');
|
|
128
|
+
const lines = createInterface({ input, crlfDelay: Infinity }); let chain = Promise.resolve(), queued = 0;
|
|
129
|
+
lines.on('line', (line) => {
|
|
130
|
+
if (Buffer.byteLength(line) > 65536 || queued >= 8) { send({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'INPUT_LIMIT' } }); return; }
|
|
131
|
+
queued++;
|
|
132
|
+
chain = chain.then(async () => {
|
|
133
|
+
let req; try { req = JSON.parse(line); } catch { send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'INVALID_JSON' } }); return; }
|
|
134
|
+
if (req.id === undefined) return;
|
|
135
|
+
let result;
|
|
136
|
+
if (req.method === 'initialize') result = { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'afyx-native-github', version: '1.0.0' } };
|
|
137
|
+
else if (req.method === 'ping') result = {};
|
|
138
|
+
else if (req.method === 'tools/list') result = { tools: [{ name: 'afyx_github_read', description: 'Scoped, read-only GitHub evidence; host owns repository authorization.', annotations: { readOnlyHint: true, destructiveHint: false },
|
|
139
|
+
inputSchema: { type: 'object', additionalProperties: false, properties: { operation: { enum: OPERATIONS }, owner: { type: 'string' }, repo: { type: 'string' }, number: { type: 'integer' }, path: { type: 'string' }, ref: { type: 'string' }, page: { type: 'integer' }, perPage: { type: 'integer' } }, required: ['operation', 'owner', 'repo'] } }] };
|
|
140
|
+
else if (req.method === 'tools/call' && req.params?.name === 'afyx_github_read') { const value = await reader.read(req.params.arguments); result = { content: [{ type: 'text', text: JSON.stringify(value) }], isError: value.status !== 'SUCCESS' }; }
|
|
141
|
+
else { send({ jsonrpc: '2.0', id: req.id, error: { code: -32601, message: 'READ_ONLY_SERVER_UNKNOWN_METHOD' } }); return; }
|
|
142
|
+
send({ jsonrpc: '2.0', id: req.id, result });
|
|
143
|
+
}).catch(() => send({ jsonrpc: '2.0', id: null, error: { code: -32603, message: 'SAFE_INTERNAL_ERROR' } })).finally(() => queued--);
|
|
144
|
+
});
|
|
145
|
+
return { close: () => lines.close(), drained: () => chain };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
149
|
+
const value = (flag) => { const at = process.argv.indexOf(flag); return at < 0 ? null : process.argv[at + 1]; };
|
|
150
|
+
const allowedRepositories = (value('--repositories') || '').split(',').filter(Boolean);
|
|
151
|
+
const gh = value('--gh-executable');
|
|
152
|
+
const reader = createGitHubReader({ allowedRepositories, ...(gh ? { request: createGhRequest({ executable: gh, projectRoot: resolve(value('--project-root') || process.cwd()) }), authMode: 'HOST_GH_SESSION' } : {}) });
|
|
153
|
+
if (process.argv.includes('--mcp')) serveGitHubMcp({ reader });
|
|
154
|
+
else process.stdout.write(JSON.stringify(reader.inventory()) + '\n');
|
|
155
|
+
}
|
|
@@ -13,18 +13,35 @@ import { existsSync, readFileSync } from 'node:fs';
|
|
|
13
13
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
14
14
|
import { fileURLToPath } from 'node:url';
|
|
15
15
|
import { spawn } from 'node:child_process';
|
|
16
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
16
17
|
|
|
17
18
|
const __filename = fileURLToPath(import.meta.url);
|
|
18
19
|
const __dirname = dirname(__filename);
|
|
19
20
|
export const PACKAGE_ROOT = resolve(__dirname, '..');
|
|
21
|
+
const componentIds = new Set(JSON.parse(readFileSync(join(__dirname, 'components.json'), 'utf8')).components.map((entry) => entry.id));
|
|
22
|
+
|
|
23
|
+
function checkedComponents(values, actions = false) {
|
|
24
|
+
if (!Array.isArray(values)) throw new Error('Component selections must be an array.');
|
|
25
|
+
for (const value of values) {
|
|
26
|
+
const match = typeof value === 'string' && (actions
|
|
27
|
+
? /^([a-z][a-z0-9-]*)=(skip|install|update|repair|adopt)$/.exec(value)
|
|
28
|
+
: /^([a-z][a-z0-9-]*)$/.exec(value));
|
|
29
|
+
if (!match || !componentIds.has(match[1])) throw new Error(`Unknown or malformed component selection: ${String(value)}`);
|
|
30
|
+
}
|
|
31
|
+
return values;
|
|
32
|
+
}
|
|
20
33
|
|
|
21
34
|
export function subprocessEnvironment(executable, env = process.env) {
|
|
22
35
|
if (!/^powershell(?:\.exe)?$/i.test(basename(executable))) return env;
|
|
23
36
|
const windowsRoot = env.SystemRoot || env.SYSTEMROOT || env.windir || env.WINDIR;
|
|
24
37
|
if (!windowsRoot) return env;
|
|
25
38
|
const nativeModules = join(windowsRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'Modules');
|
|
26
|
-
|
|
27
|
-
|
|
39
|
+
// Windows names are case-insensitive, but a spread object is not. Node sends
|
|
40
|
+
// only the first case variant to the child (some hosts use PSMODULEPATH).
|
|
41
|
+
const moduleEntries = Object.entries(env).filter(([key]) => key.toLowerCase() === 'psmodulepath');
|
|
42
|
+
const modulePaths = [nativeModules, ...moduleEntries.flatMap(([, value]) => (value || '').split(';').filter(Boolean))];
|
|
43
|
+
const childEnvironment = Object.fromEntries(Object.entries(env).filter(([key]) => key.toLowerCase() !== 'psmodulepath'));
|
|
44
|
+
return { ...childEnvironment, PSModulePath: [...new Set(modulePaths)].join(';') };
|
|
28
45
|
}
|
|
29
46
|
|
|
30
47
|
let cachedVersion = null;
|
|
@@ -57,7 +74,7 @@ export const COMMAND_ALLOWED_OPTIONS = {
|
|
|
57
74
|
verify: new Set([
|
|
58
75
|
'preset', 'provider', 'providerScope', 'workspaceRoot', 'skillsRoot',
|
|
59
76
|
'contextRuntimeRoot', 'forgeRuntimeRoot', 'graphRuntimeRoot',
|
|
60
|
-
'customComponents'
|
|
77
|
+
'customComponents', 'skipProviderConfiguration'
|
|
61
78
|
]),
|
|
62
79
|
doctor: new Set([
|
|
63
80
|
'skillsRoot', 'project'
|
|
@@ -220,51 +237,51 @@ export function parseCliArgs(rawArgs) {
|
|
|
220
237
|
} else if (arg === '--non-interactive' || arg === '-y' || arg === '--yes') {
|
|
221
238
|
if (recordOption('nonInteractive', arg)) result.options.nonInteractive = true;
|
|
222
239
|
} else if (arg === '--ui' || arg.startsWith('--ui=')) {
|
|
223
|
-
const val = arg.includes('=') ? arg.
|
|
240
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
224
241
|
if (!['auto', 'tui', 'plain'].includes(val)) result.errors.push('--ui requires auto, tui, or plain');
|
|
225
242
|
else if (recordOption('ui', '--ui')) result.options.ui = val;
|
|
226
243
|
} else if (arg === '--preset' || arg.startsWith('--preset=')) {
|
|
227
|
-
const val = arg.includes('=') ? arg.
|
|
244
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
228
245
|
if (!val) result.errors.push('--preset requires a value');
|
|
229
246
|
else if (recordOption('preset', '--preset')) result.options.preset = val;
|
|
230
247
|
} else if (arg === '--provider' || arg.startsWith('--provider=')) {
|
|
231
|
-
const val = arg.includes('=') ? arg.
|
|
248
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
232
249
|
if (!val) result.errors.push('--provider requires a value');
|
|
233
250
|
else if (recordOption('provider', '--provider')) result.options.provider = val;
|
|
234
251
|
} else if (arg === '--provider-scope' || arg.startsWith('--provider-scope=')) {
|
|
235
|
-
const val = arg.includes('=') ? arg.
|
|
252
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
236
253
|
if (!val) result.errors.push('--provider-scope requires a value');
|
|
237
254
|
else if (recordOption('providerScope', '--provider-scope')) result.options.providerScope = val;
|
|
238
255
|
} else if (arg === '--workspace-root' || arg.startsWith('--workspace-root=')) {
|
|
239
|
-
const val = arg.includes('=') ? arg.
|
|
256
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
240
257
|
if (!val) result.errors.push('--workspace-root requires a value');
|
|
241
258
|
else if (recordOption('workspaceRoot', '--workspace-root')) result.options.workspaceRoot = val;
|
|
242
259
|
} else if (arg === '--skills-root' || arg.startsWith('--skills-root=')) {
|
|
243
|
-
const val = arg.includes('=') ? arg.
|
|
260
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
244
261
|
if (!val) result.errors.push('--skills-root requires a value');
|
|
245
262
|
else if (recordOption('skillsRoot', '--skills-root')) result.options.skillsRoot = val;
|
|
246
263
|
} else if (arg === '--context-runtime-root' || arg.startsWith('--context-runtime-root=')) {
|
|
247
|
-
const val = arg.includes('=') ? arg.
|
|
264
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
248
265
|
if (!val) result.errors.push('--context-runtime-root requires a value');
|
|
249
266
|
else if (recordOption('contextRuntimeRoot', '--context-runtime-root')) result.options.contextRuntimeRoot = val;
|
|
250
267
|
} else if (arg === '--forge-runtime-root' || arg.startsWith('--forge-runtime-root=')) {
|
|
251
|
-
const val = arg.includes('=') ? arg.
|
|
268
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
252
269
|
if (!val) result.errors.push('--forge-runtime-root requires a value');
|
|
253
270
|
else if (recordOption('forgeRuntimeRoot', '--forge-runtime-root')) result.options.forgeRuntimeRoot = val;
|
|
254
271
|
} else if (arg === '--graph-runtime-root' || arg.startsWith('--graph-runtime-root=')) {
|
|
255
|
-
const val = arg.includes('=') ? arg.
|
|
272
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
256
273
|
if (!val) result.errors.push('--graph-runtime-root requires a value');
|
|
257
274
|
else if (recordOption('graphRuntimeRoot', '--graph-runtime-root')) result.options.graphRuntimeRoot = val;
|
|
258
275
|
} else if (arg === '--project' || arg.startsWith('--project=')) {
|
|
259
|
-
const val = arg.includes('=') ? arg.
|
|
276
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
260
277
|
if (!val) result.errors.push('--project requires a value');
|
|
261
278
|
else if (recordOption('project', '--project')) result.options.project = val;
|
|
262
279
|
} else if (arg === '--custom-component' || arg.startsWith('--custom-component=')) {
|
|
263
|
-
const val = arg.includes('=') ? arg.
|
|
280
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
264
281
|
if (!val) result.errors.push('--custom-component requires a value');
|
|
265
282
|
else if (recordOption('customComponents', '--custom-component')) result.options.customComponents.push(val);
|
|
266
283
|
} else if (arg === '--component' || arg.startsWith('--component=')) {
|
|
267
|
-
const val = arg.includes('=') ? arg.
|
|
284
|
+
const val = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++i];
|
|
268
285
|
if (!val) result.errors.push('--component requires a value');
|
|
269
286
|
else if (recordOption('componentActions', '--component')) result.options.componentActions.push(val);
|
|
270
287
|
} else {
|
|
@@ -297,6 +314,8 @@ export function buildSubprocessCall(command, options = {}, platform = process.pl
|
|
|
297
314
|
isGitRepo = false;
|
|
298
315
|
}
|
|
299
316
|
const effectiveOptions = { ...options };
|
|
317
|
+
if (effectiveOptions.customComponents) checkedComponents(effectiveOptions.customComponents);
|
|
318
|
+
if (effectiveOptions.componentActions) checkedComponents(effectiveOptions.componentActions, command !== 'uninstall');
|
|
300
319
|
if (command === 'update' && !isGitRepo && !effectiveOptions.skipSelfUpdate) {
|
|
301
320
|
effectiveOptions.skipSelfUpdate = true;
|
|
302
321
|
}
|
|
@@ -328,18 +347,12 @@ export function buildSubprocessCall(command, options = {}, platform = process.pl
|
|
|
328
347
|
if (effectiveOptions.project) psArgs.push('-ProjectPath', effectiveOptions.project);
|
|
329
348
|
|
|
330
349
|
if (effectiveOptions.customComponents && effectiveOptions.customComponents.length > 0) {
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
350
|
+
// -File binds one string per named parameter on both Windows PS 5.1 and
|
|
351
|
+
// PS 7. The native entrypoints expand this validated comma-separated list.
|
|
352
|
+
psArgs.push('-CustomComponent', effectiveOptions.customComponents.join(','));
|
|
334
353
|
}
|
|
335
354
|
if (effectiveOptions.componentActions && effectiveOptions.componentActions.length > 0) {
|
|
336
|
-
|
|
337
|
-
if (command === 'uninstall') {
|
|
338
|
-
psArgs.push('-Component', act);
|
|
339
|
-
} else {
|
|
340
|
-
psArgs.push('-ComponentAction', act);
|
|
341
|
-
}
|
|
342
|
-
}
|
|
355
|
+
psArgs.push(command === 'uninstall' ? '-Component' : '-ComponentAction', effectiveOptions.componentActions.join(','));
|
|
343
356
|
}
|
|
344
357
|
|
|
345
358
|
// SupportsShouldProcess commands (install, update, uninstall)
|
|
@@ -426,7 +439,7 @@ export function buildSubprocessCall(command, options = {}, platform = process.pl
|
|
|
426
439
|
if (effectiveOptions.allowDowngrade && (command === 'install' || command === 'update')) shArgs.push('--allow-downgrade');
|
|
427
440
|
if (effectiveOptions.offline && (command === 'install' || command === 'update')) shArgs.push('--offline');
|
|
428
441
|
if (effectiveOptions.noBuildFallback && (command === 'install' || command === 'update')) shArgs.push('--no-build-fallback');
|
|
429
|
-
if (effectiveOptions.skipProviderConfiguration && (command === 'install' || command === 'update')) shArgs.push('--skip-provider-configuration');
|
|
442
|
+
if (effectiveOptions.skipProviderConfiguration && (command === 'install' || command === 'update' || command === 'verify')) shArgs.push('--skip-provider-configuration');
|
|
430
443
|
if (effectiveOptions.skipSelfUpdate && command === 'update' && isGitRepo) shArgs.push('--skip-self-update');
|
|
431
444
|
if (effectiveOptions.removeProviderConfiguration && command === 'uninstall') shArgs.push('--remove-provider-configuration');
|
|
432
445
|
if (effectiveOptions.removeAfyxGraph && command === 'uninstall') shArgs.push('--remove-afyx-graph');
|
|
@@ -441,7 +454,7 @@ export function buildSubprocessCall(command, options = {}, platform = process.pl
|
|
|
441
454
|
};
|
|
442
455
|
}
|
|
443
456
|
|
|
444
|
-
export function executeSubprocess(callInfo, { onExit = null } = {}) {
|
|
457
|
+
export function executeSubprocess(callInfo, { onExit = null, onOutput = null } = {}) {
|
|
445
458
|
return new Promise((resolvePromise, rejectPromise) => {
|
|
446
459
|
let currentChild = null;
|
|
447
460
|
let resolved = false;
|
|
@@ -465,7 +478,7 @@ export function executeSubprocess(callInfo, { onExit = null } = {}) {
|
|
|
465
478
|
let child;
|
|
466
479
|
try {
|
|
467
480
|
child = spawn(exe, args, {
|
|
468
|
-
stdio: 'inherit',
|
|
481
|
+
stdio: onOutput ? ['inherit', 'pipe', 'pipe'] : 'inherit',
|
|
469
482
|
cwd: process.cwd(),
|
|
470
483
|
env: subprocessEnvironment(exe, callInfo.env || process.env),
|
|
471
484
|
});
|
|
@@ -481,6 +494,21 @@ export function executeSubprocess(callInfo, { onExit = null } = {}) {
|
|
|
481
494
|
|
|
482
495
|
currentChild = child;
|
|
483
496
|
let hasErrored = false;
|
|
497
|
+
if (onOutput) {
|
|
498
|
+
for (const [name, stream] of [['stdout', child.stdout], ['stderr', child.stderr]]) {
|
|
499
|
+
const decoder = new StringDecoder('utf8');
|
|
500
|
+
const deliver = (text) => {
|
|
501
|
+
if (!text || hasErrored) return;
|
|
502
|
+
try { onOutput(text, name); }
|
|
503
|
+
catch (error) {
|
|
504
|
+
hasErrored = true;
|
|
505
|
+
child.kill('SIGTERM'); cleanupSignalHandlers(); rejectPromise(error);
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
stream.on('data', (bytes) => deliver(decoder.write(bytes)));
|
|
509
|
+
stream.on('end', () => deliver(decoder.end()));
|
|
510
|
+
}
|
|
511
|
+
}
|
|
484
512
|
|
|
485
513
|
child.on('error', (err) => {
|
|
486
514
|
hasErrored = true;
|
|
@@ -17,7 +17,7 @@ const catalog = [
|
|
|
17
17
|
|
|
18
18
|
function commandPath(name, env, platform) {
|
|
19
19
|
const suffixes = platform === 'win32' ? ['.exe', '.cmd', '.bat'] : [''];
|
|
20
|
-
for (const directory of (env.PATH || '').split(delimiter).filter(Boolean)) {
|
|
20
|
+
for (const directory of (env.PATH || '').split(delimiter).filter(Boolean).slice(0, 128)) {
|
|
21
21
|
for (const suffix of suffixes) {
|
|
22
22
|
const candidate = join(directory, name + suffix);
|
|
23
23
|
try {
|
|
@@ -39,11 +39,13 @@ function extensionProducts(home, platform) {
|
|
|
39
39
|
const directory = join(home, root, 'extensions');
|
|
40
40
|
let names;
|
|
41
41
|
try { names = readdirSync(directory); } catch { continue; }
|
|
42
|
-
for (const name of names) {
|
|
42
|
+
for (const name of names.sort().slice(0, 512)) {
|
|
43
43
|
if (!/^(openai\.chatgpt|anthropic\.claude-code)-/i.test(name)) continue;
|
|
44
44
|
const location = join(directory, name);
|
|
45
45
|
try {
|
|
46
|
-
const
|
|
46
|
+
const manifestPath = join(location, 'package.json');
|
|
47
|
+
if (statSync(manifestPath).size > 65536) continue;
|
|
48
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
47
49
|
const id = `${manifest.publisher}.${manifest.name}`.toLowerCase();
|
|
48
50
|
if (!['openai.chatgpt', 'anthropic.claude-code'].includes(id)) continue;
|
|
49
51
|
found.push({ id, path: location, version: String(manifest.version || '') });
|
|
@@ -54,6 +56,7 @@ function extensionProducts(home, platform) {
|
|
|
54
56
|
}
|
|
55
57
|
|
|
56
58
|
function knownDesktopPaths(env, platform) {
|
|
59
|
+
if (platform === 'darwin') return { antigravity: ['/Applications/Antigravity.app/Contents/MacOS/Antigravity', join(env.HOME || homedir(), 'Applications/Antigravity.app/Contents/MacOS/Antigravity')], cursor: ['/Applications/Cursor.app/Contents/MacOS/Cursor'] };
|
|
57
60
|
if (platform !== 'win32') return { antigravity: [], cursor: [] };
|
|
58
61
|
const appPath = (executable) => {
|
|
59
62
|
const reg = join(env.SystemRoot || 'C:\\Windows', 'System32', 'reg.exe');
|