afyx-engineering-kit 0.0.0-stage → 0.1.0-alpha.4
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 -0
- package/LICENSE +21 -0
- package/README.md +377 -2
- package/SECURITY.md +74 -0
- package/afyx-context/LICENSE +21 -0
- package/afyx-context/README.md +155 -0
- package/afyx-context/afyx-context.json +30 -0
- package/afyx-context/contracts/integration-v1.schema.json +34 -0
- package/afyx-context/package-lock.json +53 -0
- package/afyx-context/package.json +34 -0
- package/afyx-context/scripts/benchmark.mjs +39 -0
- package/afyx-context/scripts/build.mjs +15 -0
- package/afyx-context/scripts/comparative-benchmark.mjs +342 -0
- package/afyx-context/scripts/comparative-worker.mjs +74 -0
- package/afyx-context/scripts/graph-integration-e2e.mjs +188 -0
- package/afyx-context/scripts/integrated-dogfood.mjs +309 -0
- package/afyx-context/src/budget.js +166 -0
- package/afyx-context/src/cli.js +110 -0
- package/afyx-context/src/coordination.js +343 -0
- package/afyx-context/src/engine.js +198 -0
- package/afyx-context/src/errors.js +14 -0
- package/afyx-context/src/graph-integration-worker.js +70 -0
- package/afyx-context/src/graph-integration.js +373 -0
- package/afyx-context/src/graph-mcp-bridge.js +103 -0
- package/afyx-context/src/index.js +25 -0
- package/afyx-context/src/integrations.js +87 -0
- package/afyx-context/src/memory.js +255 -0
- package/afyx-context/src/storage.js +364 -0
- package/afyx-context/test-fixtures/coordination-worker.mjs +52 -0
- package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__init__.py +1 -0
- package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__manifest__.py +4 -0
- package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/__init__.py +1 -0
- package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/sale_order.py +5 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__init__.py +1 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__manifest__.py +10 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/__init__.py +2 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order.py +20 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order_audit.py +11 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/security/ir.model.access.csv +2 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/views/sale_order_views.xml +14 -0
- package/afyx-forge/LICENSE +55 -0
- package/afyx-forge/README.md +126 -0
- package/afyx-forge/afyx-forge.json +28 -0
- package/afyx-forge/bin/afyx-forge +4 -0
- package/afyx-forge/bin/afyx-forge.cmd +3 -0
- package/afyx-forge/bin/afyx-forge.js +16 -0
- package/afyx-forge/contracts/forge-plan-v1.schema.json +172 -0
- package/afyx-forge/package.json +26 -0
- package/afyx-forge/src/classifier.js +190 -0
- package/afyx-forge/src/cli.js +111 -0
- package/afyx-forge/src/doctor.js +105 -0
- package/afyx-forge/src/guidance.js +120 -0
- package/afyx-forge/src/index.js +273 -0
- package/afyx-forge/src/planning.js +107 -0
- package/afyx-forge/src/policy.js +109 -0
- package/afyx-forge/src/workflow-refiner.js +151 -0
- package/afyx-graph/afyx-graph.json +20 -0
- package/afyx-graph/engine/LICENSE +21 -0
- package/afyx-graph/engine/README.md +104 -0
- package/afyx-graph/engine/release/RELEASE-MANIFEST.json +21 -0
- package/afyx-graph/engine/release/SHA256SUMS +2 -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/afyx-graph/engine/scripts/distribution-contract.mjs +212 -0
- package/afyx-graph/engine/scripts/distribution-product.json +33 -0
- package/bin/afyx-engineering-kit.mjs +61 -0
- package/install.ps1 +1053 -0
- package/install.sh +617 -0
- package/package.json +66 -4
- package/scripts/afyx-capability-orchestrator.mjs +752 -0
- package/scripts/afyx-claude-integration.mjs +547 -0
- package/scripts/afyx-context-artifact.mjs +105 -0
- package/scripts/afyx-credential-broker.mjs +75 -0
- package/scripts/afyx-doctor.ps1 +152 -0
- package/scripts/afyx-doctor.sh +146 -0
- package/scripts/afyx-forge-artifact.mjs +183 -0
- package/scripts/afyx-global-routing-policy.md +12 -0
- package/scripts/afyx-global-routing.mjs +168 -0
- package/scripts/afyx-graph-artifact.mjs +178 -0
- package/scripts/afyx-host-adapters.mjs +543 -0
- package/scripts/afyx-host-bridge-lifecycle.mjs +174 -0
- package/scripts/afyx-host-bridge.mjs +288 -0
- package/scripts/afyx-integration-contracts.mjs +825 -0
- package/scripts/afyx-mcp-integration.mjs +528 -0
- package/scripts/afyx-modular-integration.mjs +361 -0
- package/scripts/afyx-modular-runtime.mjs +451 -0
- package/scripts/afyx-native-skill-host.mjs +124 -0
- package/scripts/afyx-npm-installer.mjs +486 -0
- package/scripts/afyx-project.ps1 +205 -0
- package/scripts/afyx-project.sh +207 -0
- package/scripts/afyx-provider-backup.mjs +1206 -0
- package/scripts/afyx-provider-integration.mjs +724 -0
- package/scripts/afyx-provider-inventory.mjs +147 -0
- package/scripts/afyx-security-auditor.mjs +224 -0
- package/scripts/afyx-skill-engineering.mjs +354 -0
- package/scripts/afyx-tool-family-routing.mjs +64 -0
- package/scripts/afyx-universal-runtime.mjs +530 -0
- package/scripts/alpha_acceptance_preflight.py +240 -0
- package/scripts/benchmark-graph-memory.mjs +96 -0
- package/scripts/benchmark_capability_orchestrator.mjs +64 -0
- package/scripts/build-windows-installer.ps1 +259 -0
- package/scripts/build_forge_synthetic_image.py +328 -0
- package/scripts/check-reference-staleness.py +71 -0
- package/scripts/components.json +254 -0
- package/scripts/contracts/afyx-capability-request-v1.schema.json +189 -0
- package/scripts/contracts/afyx-capability-result-v1.schema.json +32 -0
- package/scripts/dogfood_engineering_comparison.mjs +303 -0
- package/scripts/engineering-assurance.json +28 -0
- package/scripts/install-afyx-context.ps1 +142 -0
- package/scripts/install-afyx-context.sh +126 -0
- package/scripts/install-afyx-forge.ps1 +265 -0
- package/scripts/install-afyx-forge.sh +273 -0
- package/scripts/install-afyx-graph.ps1 +571 -0
- package/scripts/install-afyx-graph.sh +438 -0
- package/scripts/install-codex-usage-tracker.ps1 +172 -0
- package/scripts/lib/AfyxComponents.psm1 +399 -0
- package/scripts/lib/AfyxSkillLifecycle.psm1 +289 -0
- package/scripts/lib/AfyxTerminal.psm1 +838 -0
- package/scripts/lib/afyx-components.sh +256 -0
- package/scripts/lib/afyx-skill-lifecycle.sh +271 -0
- package/scripts/link-global-dev.ps1 +193 -0
- package/scripts/link-global-dev.sh +130 -0
- package/scripts/phase8-paired-evidence.mjs +195 -0
- package/scripts/phase8-representative-workload.mjs +771 -0
- package/scripts/phase8-session-recorder.mjs +157 -0
- package/scripts/phase8_event_ledger.py +248 -0
- package/scripts/phase8_evidence_discovery.py +189 -0
- package/scripts/prepare-g6-package.mjs +349 -0
- package/scripts/resolve-git-release-artifacts.mjs +321 -0
- package/scripts/stage-npm-release.mjs +94 -0
- package/scripts/validate-afyx-graph.py +203 -0
- package/scripts/validate-components.py +194 -0
- package/scripts/validate-engineering-assurance.py +281 -0
- package/scripts/verify-graph-archive.mjs +64 -0
- package/skills/afyx-context/SKILL.md +26 -0
- package/skills/afyx-engineering-expert/README.md +42 -0
- package/skills/afyx-engineering-expert/SKILL.md +70 -0
- package/skills/afyx-engineering-expert/assets/result-template.md +15 -0
- package/skills/afyx-engineering-expert/references/ai-ml-engineer.md +17 -0
- package/skills/afyx-engineering-expert/references/business-analyst.md +17 -0
- package/skills/afyx-engineering-expert/references/clean-code-engineer.md +26 -0
- package/skills/afyx-engineering-expert/references/code-reviewer.md +24 -0
- package/skills/afyx-engineering-expert/references/cybersecurity-devsecops.md +17 -0
- package/skills/afyx-engineering-expert/references/data-analyst-bi.md +24 -0
- package/skills/afyx-engineering-expert/references/data-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/database-administrator.md +17 -0
- package/skills/afyx-engineering-expert/references/debugging-specialist.md +24 -0
- package/skills/afyx-engineering-expert/references/embedded-iot-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/erp-technical-specialist.md +17 -0
- package/skills/afyx-engineering-expert/references/hardware-diagnostics-auditor.md +24 -0
- package/skills/afyx-engineering-expert/references/hardware-electronics-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/integration-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/legacy-modernization-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/llmops-prompt-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/network-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/performance-benchmark-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/platform-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/product-manager.md +17 -0
- package/skills/afyx-engineering-expert/references/qa-engineer.md +17 -0
- package/skills/afyx-engineering-expert/references/site-reliability-engineer.md +17 -0
- package/skills/afyx-engineering-expert/references/software-engineer.md +17 -0
- package/skills/afyx-engineering-expert/references/solutions-architect.md +17 -0
- package/skills/afyx-engineering-expert/references/specialists-index.md +33 -0
- package/skills/afyx-engineering-expert/references/subject-matter-expert.md +17 -0
- package/skills/afyx-engineering-expert/references/system-analyst.md +17 -0
- package/skills/afyx-engineering-expert/references/technical-project-manager.md +24 -0
- package/skills/afyx-engineering-expert/references/technical-writer.md +24 -0
- package/skills/afyx-engineering-expert/references/ui-ux-designer.md +17 -0
- package/skills/afyx-engineering-expert/workflows/ai-data-erp.md +20 -0
- package/skills/afyx-engineering-expert/workflows/debugging.md +10 -0
- package/skills/afyx-engineering-expert/workflows/discovery-design.md +11 -0
- package/skills/afyx-engineering-expert/workflows/implementation.md +12 -0
- package/skills/afyx-engineering-expert/workflows/incident-reliability.md +12 -0
- package/skills/afyx-engineering-expert/workflows/review-audit.md +13 -0
- package/skills/afyx-forge/SKILL.md +43 -0
- package/skills/afyx-forge/references/adaptive-policy.md +19 -0
- package/skills/efficient-coding/SKILL.md +33 -0
- package/skills/efficient-coding/references/investigation.md +27 -0
- package/skills/efficient-coding/references/token-efficiency.md +25 -0
- package/skills/efficient-coding/references/tool-routing.md +13 -0
- package/skills/odoo-engineering/SKILL.md +33 -0
- package/skills/odoo-engineering/references/common.md +9 -0
- package/skills/odoo-engineering/references/odoo-10.md +32 -0
- package/skills/odoo-engineering/references/odoo-11.md +26 -0
- package/skills/odoo-engineering/references/odoo-12.md +31 -0
- package/skills/odoo-engineering/references/odoo-13.md +27 -0
- package/skills/odoo-engineering/references/odoo-14.md +31 -0
- package/skills/odoo-engineering/references/odoo-15.md +34 -0
- package/skills/odoo-engineering/references/odoo-16.md +37 -0
- package/skills/odoo-engineering/references/odoo-17.md +37 -0
- package/skills/odoo-engineering/references/odoo-18.md +48 -0
- package/skills/odoo-engineering/references/odoo-19.md +43 -0
- package/skills/odoo-engineering/references/odoo-20.md +39 -0
- package/skills/odoo-engineering/references/reference-schema.md +16 -0
- package/skills/odoo-engineering/references/version-detection.md +13 -0
- package/tools/codex-usage/CodexUsage.psm1 +496 -0
- package/tools/codex-usage/codex-usage-doctor.ps1 +150 -0
- package/tools/codex-usage/codex-usage-pricing.json +25 -0
- package/tools/codex-usage/codex-usage-stop.ps1 +167 -0
- package/tools/codex-usage/codex-usage-watch.ps1 +250 -0
- package/tools/codex-usage/vscode-user-task.json +31 -0
- package/tools/windows-setup/SetupBootstrapper.cs +258 -0
- package/uninstall.ps1 +189 -0
- package/uninstall.sh +167 -0
- package/update.ps1 +95 -0
- package/update.sh +67 -0
- package/verify.ps1 +411 -0
- package/verify.sh +265 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { AfyxContextEngine } from './engine.js';
|
|
4
|
+
import { createOptionalIntegrationAdapter } from './integrations.js';
|
|
5
|
+
|
|
6
|
+
if (typeof process.send !== 'function') throw new Error('Graph–ACE integration worker requires an IPC parent');
|
|
7
|
+
|
|
8
|
+
const checkpointSleeper = new Int32Array(new SharedArrayBuffer(4));
|
|
9
|
+
|
|
10
|
+
function installTestCheckpoint(control) {
|
|
11
|
+
if (control === undefined) return () => {};
|
|
12
|
+
if (!control || typeof control !== 'object'
|
|
13
|
+
|| !['after-lock-acquired', 'before-session-commit', 'after-session-commit'].includes(control.phase)
|
|
14
|
+
|| typeof control.readyPath !== 'string' || !control.readyPath) {
|
|
15
|
+
throw new Error('invalid native-worker test checkpoint');
|
|
16
|
+
}
|
|
17
|
+
const renameSync = fs.renameSync;
|
|
18
|
+
fs.renameSync = (source, destination) => {
|
|
19
|
+
const lockCommit = control.phase === 'after-lock-acquired'
|
|
20
|
+
&& path.basename(destination) === 'owner.json'
|
|
21
|
+
&& path.basename(path.dirname(destination)) === '.ace-lock';
|
|
22
|
+
const sessionCommit = path.basename(destination) === 'session.json';
|
|
23
|
+
const before = control.phase === 'before-session-commit' && sessionCommit;
|
|
24
|
+
const after = (control.phase === 'after-session-commit' && sessionCommit) || lockCommit;
|
|
25
|
+
if (before) {
|
|
26
|
+
fs.writeFileSync(control.readyPath, `${process.pid}\n`, { flag: 'wx' });
|
|
27
|
+
Atomics.wait(checkpointSleeper, 0, 0);
|
|
28
|
+
}
|
|
29
|
+
const result = renameSync(source, destination);
|
|
30
|
+
if (after) {
|
|
31
|
+
fs.writeFileSync(control.readyPath, `${process.pid}\n`, { flag: 'wx' });
|
|
32
|
+
Atomics.wait(checkpointSleeper, 0, 0);
|
|
33
|
+
}
|
|
34
|
+
return result;
|
|
35
|
+
};
|
|
36
|
+
return () => { fs.renameSync = renameSync; };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function reply(value) {
|
|
40
|
+
process.send(value, () => process.disconnect());
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
process.once('message', (message) => {
|
|
44
|
+
const restore = installTestCheckpoint(message?.testControl);
|
|
45
|
+
try {
|
|
46
|
+
if (message?.operation === 'reduce') {
|
|
47
|
+
const adapter = createOptionalIntegrationAdapter({ component: 'graph' });
|
|
48
|
+
reply(adapter.process(message.request));
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (message?.operation === 'retrieve') {
|
|
52
|
+
const engine = new AfyxContextEngine({
|
|
53
|
+
stateDir: message.stateDir,
|
|
54
|
+
ownerId: message.ownerId,
|
|
55
|
+
sessionId: message.sessionId,
|
|
56
|
+
});
|
|
57
|
+
reply({ status: 'recovered', record: engine.retrieveRecord(message.reference) });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
reply({ status: 'error', failureCode: 'INVALID_INTEGRATION', message: 'unknown worker operation' });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
reply({
|
|
63
|
+
status: 'error',
|
|
64
|
+
failureCode: typeof error?.code === 'string' ? error.code : 'ACE_UNAVAILABLE',
|
|
65
|
+
message: error instanceof Error ? error.message : String(error),
|
|
66
|
+
});
|
|
67
|
+
} finally {
|
|
68
|
+
restore();
|
|
69
|
+
}
|
|
70
|
+
});
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { AceError } from './errors.js';
|
|
7
|
+
import { ACE_INTEGRATION_CONTRACT } from './integrations.js';
|
|
8
|
+
|
|
9
|
+
export const GRAPH_ACE_CONSUMER_CONTRACT = 'graph.ace.consumer/v1';
|
|
10
|
+
|
|
11
|
+
const DEFAULT_TIMEOUT_MS = 5_000;
|
|
12
|
+
const MAX_TIMEOUT_MS = 60_000;
|
|
13
|
+
const TERMINATION_GRACE_MS = 5_000;
|
|
14
|
+
const SOURCE_TOOLS = new Set(['afyx_graph_explore', 'afyx_graph_files', 'afyx_graph_node']);
|
|
15
|
+
const DIAGNOSTIC_TOOLS = new Set(['afyx_graph_status']);
|
|
16
|
+
|
|
17
|
+
function digest(value) {
|
|
18
|
+
return crypto.createHash('sha256').update(value).digest('hex');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function assertString(value, name, maxBytes = undefined) {
|
|
22
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
23
|
+
throw new AceError('INVALID_INTEGRATION', `${name} must be a non-empty string`);
|
|
24
|
+
}
|
|
25
|
+
if (maxBytes !== undefined && Buffer.byteLength(value, 'utf8') > maxBytes) {
|
|
26
|
+
throw new AceError('RESOURCE_LIMIT', `${name} exceeds the ${maxBytes} byte limit`);
|
|
27
|
+
}
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function canonicalProjectRoot(value) {
|
|
32
|
+
const resolved = path.resolve(assertString(value, 'projectRoot', 32_767));
|
|
33
|
+
let canonical;
|
|
34
|
+
try {
|
|
35
|
+
canonical = fs.realpathSync.native(resolved);
|
|
36
|
+
} catch {
|
|
37
|
+
throw new AceError('INVALID_INTEGRATION', 'projectRoot must be an accessible directory');
|
|
38
|
+
}
|
|
39
|
+
if (!fs.statSync(canonical).isDirectory()) {
|
|
40
|
+
throw new AceError('INVALID_INTEGRATION', 'projectRoot must be a directory');
|
|
41
|
+
}
|
|
42
|
+
return canonical;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function cloneGraphResult(value) {
|
|
46
|
+
if (!value || typeof value !== 'object' || !Array.isArray(value.content)) {
|
|
47
|
+
throw new AceError('INVALID_INTEGRATION', 'Graph result must contain a content array');
|
|
48
|
+
}
|
|
49
|
+
if (!value.content.every((item) => item && item.type === 'text' && typeof item.text === 'string')) {
|
|
50
|
+
throw new AceError('INVALID_INTEGRATION', 'Graph result contains an unsupported content block');
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
return structuredClone(value);
|
|
54
|
+
} catch {
|
|
55
|
+
throw new AceError('INVALID_INTEGRATION', 'Graph result must be cloneable');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function classificationFor(toolName) {
|
|
60
|
+
if (SOURCE_TOOLS.has(toolName)) return 'source-evidence';
|
|
61
|
+
if (DIAGNOSTIC_TOOLS.has(toolName)) return 'diagnostic';
|
|
62
|
+
return 'normal';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function pathKey(value) {
|
|
66
|
+
// Compare canonical paths even when the state directory is not created yet.
|
|
67
|
+
// macOS /var -> /private/var and Windows junction/reparse-point ancestors
|
|
68
|
+
// otherwise defeat a purely lexical project/state overlap check.
|
|
69
|
+
let existing = path.resolve(value);
|
|
70
|
+
const missing = [];
|
|
71
|
+
while (!fs.existsSync(existing)) {
|
|
72
|
+
const parent = path.dirname(existing);
|
|
73
|
+
if (parent === existing) break;
|
|
74
|
+
missing.unshift(path.basename(existing));
|
|
75
|
+
existing = parent;
|
|
76
|
+
}
|
|
77
|
+
let resolved;
|
|
78
|
+
try { resolved = path.join(fs.realpathSync.native(existing), ...missing); }
|
|
79
|
+
catch { resolved = path.resolve(value); }
|
|
80
|
+
return process.platform === 'win32' || process.platform === 'darwin' ? resolved.toLowerCase() : resolved;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function pathsOverlap(left, right) {
|
|
84
|
+
const a = pathKey(left);
|
|
85
|
+
const b = pathKey(right);
|
|
86
|
+
const aToB = path.relative(a, b);
|
|
87
|
+
const bToA = path.relative(b, a);
|
|
88
|
+
return a === b
|
|
89
|
+
|| (aToB !== '' && aToB !== '..' && !aToB.startsWith(`..${path.sep}`) && !path.isAbsolute(aToB))
|
|
90
|
+
|| (bToA !== '' && bToA !== '..' && !bToA.startsWith(`..${path.sep}`) && !path.isAbsolute(bToA));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function exactGraphFallback(graphResult, status, failureCode = undefined) {
|
|
94
|
+
return {
|
|
95
|
+
contract: GRAPH_ACE_CONSUMER_CONTRACT,
|
|
96
|
+
status,
|
|
97
|
+
...(failureCode ? { failureCode } : {}),
|
|
98
|
+
consumerResult: cloneGraphResult(graphResult),
|
|
99
|
+
ace: null,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function publicAceResult(result) {
|
|
104
|
+
return {
|
|
105
|
+
contract: result.contract,
|
|
106
|
+
mode: result.mode,
|
|
107
|
+
...(result.reason ? { reason: result.reason } : {}),
|
|
108
|
+
metrics: result.metrics,
|
|
109
|
+
items: result.items.map((item) => ({
|
|
110
|
+
id: item.id,
|
|
111
|
+
classification: item.classification,
|
|
112
|
+
disposition: item.disposition,
|
|
113
|
+
digest: item.digest,
|
|
114
|
+
reference: item.reference,
|
|
115
|
+
provenance: item.provenance,
|
|
116
|
+
...(item.reason ? { reason: item.reason } : {}),
|
|
117
|
+
})),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function nativeAceRunner(message, { signal, spawnChild = spawn } = {}) {
|
|
122
|
+
return new Promise((resolve, reject) => {
|
|
123
|
+
const child = spawnChild(process.execPath, [fileURLToPath(new URL('./graph-integration-worker.js', import.meta.url))], {
|
|
124
|
+
shell: false,
|
|
125
|
+
windowsHide: true,
|
|
126
|
+
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
|
127
|
+
});
|
|
128
|
+
let settled = false;
|
|
129
|
+
let response;
|
|
130
|
+
let terminalError;
|
|
131
|
+
let terminationTimer;
|
|
132
|
+
const finish = (action, value) => {
|
|
133
|
+
if (settled) return;
|
|
134
|
+
settled = true;
|
|
135
|
+
signal?.removeEventListener('abort', abort);
|
|
136
|
+
clearTimeout(terminationTimer);
|
|
137
|
+
action(value);
|
|
138
|
+
};
|
|
139
|
+
const terminate = (error) => {
|
|
140
|
+
if (settled) return;
|
|
141
|
+
terminalError ??= error;
|
|
142
|
+
if (terminationTimer === undefined) {
|
|
143
|
+
terminationTimer = setTimeout(() => {
|
|
144
|
+
finish(reject, new AceError(
|
|
145
|
+
'ACE_TERMINATION_UNCONFIRMED',
|
|
146
|
+
'optional ACE child did not confirm termination within the bounded grace period',
|
|
147
|
+
));
|
|
148
|
+
}, TERMINATION_GRACE_MS);
|
|
149
|
+
}
|
|
150
|
+
if (child.pid !== undefined && child.exitCode === null && child.signalCode === null) {
|
|
151
|
+
try { child.kill('SIGKILL'); } catch { /* bounded timer remains authoritative */ }
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const abort = () => terminate(new AceError('ACE_TIMEOUT', 'optional ACE operation timed out'));
|
|
155
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
156
|
+
child.once('message', (value) => { response = value; });
|
|
157
|
+
child.once('error', terminate);
|
|
158
|
+
child.once('close', (code, exitSignal) => {
|
|
159
|
+
if (terminalError) {
|
|
160
|
+
finish(reject, terminalError);
|
|
161
|
+
} else if (code === 0 && response !== undefined) {
|
|
162
|
+
finish(resolve, response);
|
|
163
|
+
} else {
|
|
164
|
+
finish(reject, new Error(`ACE worker exited with code ${code ?? 'null'} (${exitSignal ?? 'no signal'})`));
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
if (signal?.aborted) {
|
|
168
|
+
abort();
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
child.send(message, (error) => {
|
|
173
|
+
if (error) terminate(error);
|
|
174
|
+
});
|
|
175
|
+
} catch (error) {
|
|
176
|
+
terminate(error);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function invokeBounded(runner, message, timeoutMs) {
|
|
182
|
+
const controller = new AbortController();
|
|
183
|
+
let timer;
|
|
184
|
+
let terminationTimer;
|
|
185
|
+
const termination = new Promise((_, reject) => {
|
|
186
|
+
controller.signal.addEventListener('abort', () => {
|
|
187
|
+
terminationTimer = setTimeout(() => {
|
|
188
|
+
reject(new AceError(
|
|
189
|
+
'ACE_TERMINATION_UNCONFIRMED',
|
|
190
|
+
'optional ACE operation did not confirm termination within the bounded grace period',
|
|
191
|
+
));
|
|
192
|
+
}, TERMINATION_GRACE_MS);
|
|
193
|
+
}, { once: true });
|
|
194
|
+
});
|
|
195
|
+
timer = setTimeout(() => {
|
|
196
|
+
controller.abort();
|
|
197
|
+
}, timeoutMs);
|
|
198
|
+
try {
|
|
199
|
+
return await Promise.race([
|
|
200
|
+
Promise.resolve().then(() => runner(message, { signal: controller.signal })),
|
|
201
|
+
termination,
|
|
202
|
+
]);
|
|
203
|
+
} finally {
|
|
204
|
+
clearTimeout(timer);
|
|
205
|
+
clearTimeout(terminationTimer);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function deriveGraphAceIdentity({ projectRoot, sourceIdentity, consumerId } = {}) {
|
|
210
|
+
const canonicalRoot = canonicalProjectRoot(projectRoot);
|
|
211
|
+
const source = assertString(sourceIdentity, 'sourceIdentity', 512);
|
|
212
|
+
const consumer = assertString(consumerId, 'consumerId', 512);
|
|
213
|
+
return Object.freeze({
|
|
214
|
+
ownerId: `graph-owner:${digest(`${canonicalRoot}\0${consumer}`)}`,
|
|
215
|
+
sessionId: `graph-session:${digest(source)}`,
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Optional Graph consumer. It never changes Graph itself: the caller supplies a
|
|
221
|
+
* normal Graph executor, and the exact Graph result is the authoritative
|
|
222
|
+
* fallback whenever ACE is disabled, unavailable, invalid, or timed out.
|
|
223
|
+
*/
|
|
224
|
+
export function createGraphAceConsumer(options = {}) {
|
|
225
|
+
const enabled = options.enabled === true;
|
|
226
|
+
if (options.enabled !== undefined && typeof options.enabled !== 'boolean') {
|
|
227
|
+
throw new AceError('INVALID_INTEGRATION', 'enabled must be boolean');
|
|
228
|
+
}
|
|
229
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
230
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_TIMEOUT_MS) {
|
|
231
|
+
throw new AceError('INVALID_INTEGRATION', `timeoutMs must be an integer from 1 to ${MAX_TIMEOUT_MS}`);
|
|
232
|
+
}
|
|
233
|
+
const runner = options.aceRunner ?? nativeAceRunner;
|
|
234
|
+
if (typeof runner !== 'function') throw new AceError('INVALID_INTEGRATION', 'aceRunner must be a function');
|
|
235
|
+
|
|
236
|
+
let stateDir;
|
|
237
|
+
let ownerId;
|
|
238
|
+
let sessionId;
|
|
239
|
+
if (enabled) {
|
|
240
|
+
stateDir = path.resolve(assertString(options.stateDir, 'stateDir', 32_767));
|
|
241
|
+
if (!path.isAbsolute(options.stateDir)) {
|
|
242
|
+
throw new AceError('UNSAFE_STATE_PATH', 'stateDir must be absolute');
|
|
243
|
+
}
|
|
244
|
+
ownerId = assertString(options.ownerId, 'ownerId', 512);
|
|
245
|
+
sessionId = assertString(options.sessionId, 'sessionId', 512);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function execute({ executeGraph, toolName, args = {}, projectRoot, sourceIdentity, budgetChars } = {}) {
|
|
249
|
+
if (typeof executeGraph !== 'function') {
|
|
250
|
+
throw new AceError('INVALID_INTEGRATION', 'executeGraph must be a function');
|
|
251
|
+
}
|
|
252
|
+
const tool = assertString(toolName, 'toolName', 256);
|
|
253
|
+
const graphResult = cloneGraphResult(await executeGraph(tool, args));
|
|
254
|
+
|
|
255
|
+
if (!enabled) return exactGraphFallback(graphResult, 'disabled');
|
|
256
|
+
if (graphResult.isError === true) return exactGraphFallback(graphResult, 'graph-error');
|
|
257
|
+
let root;
|
|
258
|
+
let source;
|
|
259
|
+
try {
|
|
260
|
+
root = canonicalProjectRoot(projectRoot);
|
|
261
|
+
source = assertString(sourceIdentity, 'sourceIdentity', 512);
|
|
262
|
+
} catch (error) {
|
|
263
|
+
return exactGraphFallback(
|
|
264
|
+
graphResult,
|
|
265
|
+
'fallback',
|
|
266
|
+
error instanceof AceError ? error.code : 'INVALID_INTEGRATION',
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
if (pathsOverlap(root, stateDir)) {
|
|
270
|
+
return exactGraphFallback(graphResult, 'fallback', 'UNSAFE_STATE_PATH');
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const classification = classificationFor(tool);
|
|
274
|
+
// ACE deliberately preserves protected Graph output byte-for-byte. Starting
|
|
275
|
+
// a worker for those tools can only add latency/state and cannot reduce the
|
|
276
|
+
// returned context, so keep the authoritative Graph result inline.
|
|
277
|
+
if (classification !== 'normal') {
|
|
278
|
+
return exactGraphFallback(graphResult, 'bypassed');
|
|
279
|
+
}
|
|
280
|
+
let queryIdentity;
|
|
281
|
+
try {
|
|
282
|
+
const encodedQuery = JSON.stringify({ toolName: tool, args });
|
|
283
|
+
if (encodedQuery === undefined || Buffer.byteLength(encodedQuery, 'utf8') > 1_048_576) {
|
|
284
|
+
return exactGraphFallback(graphResult, 'fallback', 'INVALID_INTEGRATION');
|
|
285
|
+
}
|
|
286
|
+
queryIdentity = digest(encodedQuery);
|
|
287
|
+
} catch {
|
|
288
|
+
return exactGraphFallback(graphResult, 'fallback', 'INVALID_INTEGRATION');
|
|
289
|
+
}
|
|
290
|
+
const request = {
|
|
291
|
+
contract: ACE_INTEGRATION_CONTRACT,
|
|
292
|
+
component: 'graph',
|
|
293
|
+
stateDir,
|
|
294
|
+
ownerId,
|
|
295
|
+
sessionId,
|
|
296
|
+
...(budgetChars === undefined ? {} : { budgetChars }),
|
|
297
|
+
segments: graphResult.content.map((item, index) => ({
|
|
298
|
+
id: `graph-${index + 1}`,
|
|
299
|
+
content: item.text,
|
|
300
|
+
classification,
|
|
301
|
+
provenance: {
|
|
302
|
+
contract: GRAPH_ACE_CONSUMER_CONTRACT,
|
|
303
|
+
toolName: tool,
|
|
304
|
+
projectRoot: root,
|
|
305
|
+
sourceIdentity: source,
|
|
306
|
+
queryIdentity,
|
|
307
|
+
contentIndex: index,
|
|
308
|
+
graphResultComplete: true,
|
|
309
|
+
...(classification === 'source-evidence' ? { exactSource: true } : {}),
|
|
310
|
+
},
|
|
311
|
+
})),
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
let response;
|
|
315
|
+
try {
|
|
316
|
+
response = await invokeBounded(runner, { operation: 'reduce', request }, timeoutMs);
|
|
317
|
+
} catch (error) {
|
|
318
|
+
if (error instanceof AceError && error.code === 'ACE_TERMINATION_UNCONFIRMED') throw error;
|
|
319
|
+
const code = error instanceof AceError ? error.code : 'ACE_UNAVAILABLE';
|
|
320
|
+
return exactGraphFallback(graphResult, 'fallback', code);
|
|
321
|
+
}
|
|
322
|
+
if (!response || typeof response !== 'object') {
|
|
323
|
+
return exactGraphFallback(graphResult, 'fallback', 'INVALID_ACE_RESULT');
|
|
324
|
+
}
|
|
325
|
+
if (response.status === 'fallback') {
|
|
326
|
+
// This request was constructed from a validated, complete Graph result.
|
|
327
|
+
// If ACE cannot prove its fallback complete, use that retained result;
|
|
328
|
+
// never expose the adapter's partial or empty rendering.
|
|
329
|
+
return exactGraphFallback(graphResult, 'fallback', response.failureCode ?? 'ACE_UNAVAILABLE');
|
|
330
|
+
}
|
|
331
|
+
if (response.status !== 'optimized') {
|
|
332
|
+
return exactGraphFallback(graphResult, 'fallback', 'INVALID_ACE_RESULT');
|
|
333
|
+
}
|
|
334
|
+
const result = response.result;
|
|
335
|
+
if (!result || result.contract !== 'ace.result/v1' || typeof result.renderedContext !== 'string' || !Array.isArray(result.items)
|
|
336
|
+
|| !result.items.every((item) => item && typeof item === 'object' && typeof item.id === 'string'
|
|
337
|
+
&& typeof item.classification === 'string' && typeof item.disposition === 'string' && typeof item.digest === 'string')) {
|
|
338
|
+
return exactGraphFallback(graphResult, 'fallback', 'INVALID_ACE_RESULT');
|
|
339
|
+
}
|
|
340
|
+
try {
|
|
341
|
+
return {
|
|
342
|
+
contract: GRAPH_ACE_CONSUMER_CONTRACT,
|
|
343
|
+
status: 'optimized',
|
|
344
|
+
consumerResult: { ...graphResult, content: [{ type: 'text', text: result.renderedContext }] },
|
|
345
|
+
ace: publicAceResult(result),
|
|
346
|
+
};
|
|
347
|
+
} catch {
|
|
348
|
+
return exactGraphFallback(graphResult, 'fallback', 'INVALID_ACE_RESULT');
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async function recover(reference) {
|
|
353
|
+
if (!enabled) throw new AceError('ACE_DISABLED', 'ACE recovery is unavailable while integration is disabled');
|
|
354
|
+
const value = assertString(reference, 'reference');
|
|
355
|
+
const response = await invokeBounded(runner, {
|
|
356
|
+
operation: 'retrieve',
|
|
357
|
+
stateDir,
|
|
358
|
+
ownerId,
|
|
359
|
+
sessionId,
|
|
360
|
+
reference: value,
|
|
361
|
+
}, timeoutMs);
|
|
362
|
+
if (!response || response.status !== 'recovered' || !response.record || typeof response.record.content !== 'string') {
|
|
363
|
+
const error = new AceError(response?.failureCode ?? 'RECOVERY_FAILED', response?.message ?? 'ACE recovery failed closed');
|
|
364
|
+
throw error;
|
|
365
|
+
}
|
|
366
|
+
if (digest(response.record.content) !== response.record.digest) {
|
|
367
|
+
throw new AceError('CONTENT_INTEGRITY', 'recovered original digest mismatch');
|
|
368
|
+
}
|
|
369
|
+
return response.record;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return Object.freeze({ contract: GRAPH_ACE_CONSUMER_CONTRACT, enabled, execute, recover });
|
|
373
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Installed ACE runtime entrypoint for an optional Graph MCP consumer.
|
|
3
|
+
// It is invoked only for substantial reducible output or explicit recovery.
|
|
4
|
+
// No network, provider, shell, or Graph code is loaded by this process.
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import { createGraphAceConsumer, deriveGraphAceIdentity } from './graph-integration.js';
|
|
8
|
+
import { createOptionalIntegrationAdapter } from './integrations.js';
|
|
9
|
+
import { AfyxContextEngine } from './engine.js';
|
|
10
|
+
|
|
11
|
+
const MAX_INPUT_BYTES = 1_100_000;
|
|
12
|
+
const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
|
|
13
|
+
|
|
14
|
+
function readInput() {
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
const parts = [];
|
|
17
|
+
let size = 0;
|
|
18
|
+
process.stdin.on('data', (part) => {
|
|
19
|
+
size += part.length;
|
|
20
|
+
if (size > MAX_INPUT_BYTES) {
|
|
21
|
+
reject(new Error('input too large'));
|
|
22
|
+
process.stdin.destroy();
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
parts.push(part);
|
|
26
|
+
});
|
|
27
|
+
process.stdin.once('end', () => {
|
|
28
|
+
try { resolve(JSON.parse(Buffer.concat(parts).toString('utf8'))); }
|
|
29
|
+
catch { reject(new Error('invalid request')); }
|
|
30
|
+
});
|
|
31
|
+
process.stdin.once('error', reject);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function verifyShape(message) {
|
|
36
|
+
if (!message || typeof message !== 'object' || !['reduce', 'recover'].includes(message.operation)
|
|
37
|
+
|| typeof message.projectRoot !== 'string' || typeof message.sourceIdentity !== 'string'
|
|
38
|
+
|| typeof message.stateDir !== 'string') throw new Error('invalid bridge identity');
|
|
39
|
+
if (message.operation === 'reduce' && (
|
|
40
|
+
typeof message.toolName !== 'string' || !message.graphResult
|
|
41
|
+
|| !Array.isArray(message.graphResult.content))) throw new Error('invalid Graph result');
|
|
42
|
+
if (message.operation === 'recover'
|
|
43
|
+
&& (typeof message.reference !== 'string' || !/^ace:v1:[0-9a-f]{16}:[0-9a-f]{16}:[0-9a-f]{64}$/.test(message.reference))) {
|
|
44
|
+
throw new Error('invalid ACE reference');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function inlineRunner(message) {
|
|
49
|
+
if (message.operation === 'reduce') {
|
|
50
|
+
return Promise.resolve(createOptionalIntegrationAdapter({ component: 'graph' }).process(message.request));
|
|
51
|
+
}
|
|
52
|
+
if (message.operation === 'retrieve') {
|
|
53
|
+
const engine = new AfyxContextEngine({
|
|
54
|
+
stateDir: message.stateDir,
|
|
55
|
+
ownerId: message.ownerId,
|
|
56
|
+
sessionId: message.sessionId,
|
|
57
|
+
});
|
|
58
|
+
return Promise.resolve({ status: 'recovered', record: engine.retrieveRecord(message.reference) });
|
|
59
|
+
}
|
|
60
|
+
throw new Error('unsupported operation');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function main() {
|
|
64
|
+
const request = await readInput();
|
|
65
|
+
verifyShape(request);
|
|
66
|
+
const identity = deriveGraphAceIdentity({
|
|
67
|
+
projectRoot: request.projectRoot,
|
|
68
|
+
sourceIdentity: request.sourceIdentity,
|
|
69
|
+
consumerId: 'afyx-graph-native-mcp',
|
|
70
|
+
});
|
|
71
|
+
const consumer = createGraphAceConsumer({
|
|
72
|
+
enabled: true, stateDir: request.stateDir,
|
|
73
|
+
ownerId: identity.ownerId, sessionId: identity.sessionId,
|
|
74
|
+
aceRunner: inlineRunner, timeoutMs: 3_000,
|
|
75
|
+
});
|
|
76
|
+
if (request.operation === 'recover') {
|
|
77
|
+
const record = await consumer.recover(request.reference);
|
|
78
|
+
if (sha256(record.content) !== record.digest) throw new Error('recovery integrity mismatch');
|
|
79
|
+
return { status: 'recovered', content: record.content };
|
|
80
|
+
}
|
|
81
|
+
const result = await consumer.execute({
|
|
82
|
+
executeGraph: async () => request.graphResult,
|
|
83
|
+
toolName: request.toolName,
|
|
84
|
+
args: {},
|
|
85
|
+
projectRoot: request.projectRoot,
|
|
86
|
+
sourceIdentity: request.sourceIdentity,
|
|
87
|
+
budgetChars: 12_000,
|
|
88
|
+
});
|
|
89
|
+
if (result.status !== 'optimized' || !result.ace || result.ace.mode !== 'optimized') {
|
|
90
|
+
return { status: 'fallback' };
|
|
91
|
+
}
|
|
92
|
+
const savedChars = result.ace.metrics?.savedChars;
|
|
93
|
+
if (!Number.isSafeInteger(savedChars) || savedChars <= 0) return { status: 'fallback' };
|
|
94
|
+
return { status: 'optimized', savedChars, result: result.consumerResult };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
try {
|
|
98
|
+
const output = await main();
|
|
99
|
+
process.stdout.write(JSON.stringify(output));
|
|
100
|
+
} catch {
|
|
101
|
+
// Do not leak project-root paths, state paths, original contents or internals.
|
|
102
|
+
process.stdout.write(JSON.stringify({ status: 'fallback' }));
|
|
103
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export { AceError } from './errors.js';
|
|
2
|
+
export { ACE_LIMITS, AfyxContextEngine, classifications, classifyContent, validateContextRequest } from './engine.js';
|
|
3
|
+
export {
|
|
4
|
+
ACE_INTEGRATION_CONTRACT,
|
|
5
|
+
SUPPORTED_COMPONENTS,
|
|
6
|
+
createOptionalIntegrationAdapter,
|
|
7
|
+
} from './integrations.js';
|
|
8
|
+
export {
|
|
9
|
+
GRAPH_ACE_CONSUMER_CONTRACT,
|
|
10
|
+
createGraphAceConsumer,
|
|
11
|
+
deriveGraphAceIdentity,
|
|
12
|
+
} from './graph-integration.js';
|
|
13
|
+
export {
|
|
14
|
+
AfyxEngineeringMemory,
|
|
15
|
+
createEngineeringMemory,
|
|
16
|
+
MEMORY_CONTRACT_VERSION,
|
|
17
|
+
MEMORY_CATEGORIES,
|
|
18
|
+
} from './memory.js';
|
|
19
|
+
export {
|
|
20
|
+
DEFAULT_CONTEXT_BUDGET,
|
|
21
|
+
estimateTokens,
|
|
22
|
+
estimateBytes,
|
|
23
|
+
compressContextItems,
|
|
24
|
+
detectRedundancy,
|
|
25
|
+
} from './budget.js';
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { ACE_LIMITS, AfyxContextEngine, validateContextRequest } from './engine.js';
|
|
2
|
+
import { AceError } from './errors.js';
|
|
3
|
+
|
|
4
|
+
export const ACE_INTEGRATION_CONTRACT = 'ace.integration/v1';
|
|
5
|
+
export const SUPPORTED_COMPONENTS = Object.freeze(['graph', 'engineering-expert', 'forge', 'kit']);
|
|
6
|
+
|
|
7
|
+
function readOriginalInput(request) {
|
|
8
|
+
try {
|
|
9
|
+
return request && typeof request === 'object' ? request.segments : undefined;
|
|
10
|
+
} catch {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function renderOriginal(input) {
|
|
16
|
+
if (typeof input === 'string') return { renderedContext: input, complete: true };
|
|
17
|
+
if (!Array.isArray(input)) return { renderedContext: '', complete: input === undefined };
|
|
18
|
+
const rendered = [];
|
|
19
|
+
let renderedBytes = 0;
|
|
20
|
+
let complete = true;
|
|
21
|
+
try {
|
|
22
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
23
|
+
const segment = input[index];
|
|
24
|
+
let value;
|
|
25
|
+
if (typeof segment === 'string') {
|
|
26
|
+
value = `[segment-${index + 1}] normal\n${segment}`;
|
|
27
|
+
} else if (segment && typeof segment === 'object' && typeof segment.content === 'string') {
|
|
28
|
+
const id = typeof segment.id === 'string' && segment.id.length > 0 ? segment.id : `segment-${index + 1}`;
|
|
29
|
+
const classification = typeof segment.classification === 'string' ? segment.classification : 'normal';
|
|
30
|
+
value = `[${id}] ${classification}\n${segment.content}`;
|
|
31
|
+
} else {
|
|
32
|
+
complete = false;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
renderedBytes += Buffer.byteLength(value, 'utf8') + (rendered.length === 0 ? 0 : 2);
|
|
36
|
+
if (renderedBytes > ACE_LIMITS.maxRequestBytes) {
|
|
37
|
+
return { renderedContext: '', complete: false };
|
|
38
|
+
}
|
|
39
|
+
rendered.push(value);
|
|
40
|
+
}
|
|
41
|
+
} catch {
|
|
42
|
+
return { renderedContext: '', complete: false };
|
|
43
|
+
}
|
|
44
|
+
return { renderedContext: rendered.join('\n\n'), complete };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function fallback(request, failureCode) {
|
|
48
|
+
const originalInput = readOriginalInput(request);
|
|
49
|
+
const rendered = renderOriginal(originalInput);
|
|
50
|
+
return {
|
|
51
|
+
status: 'fallback',
|
|
52
|
+
failureCode,
|
|
53
|
+
renderedContext: rendered.renderedContext,
|
|
54
|
+
originalInput,
|
|
55
|
+
originalComplete: rendered.complete,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Optional, dependency-inverted adapter. The caller owns lifecycle and can
|
|
61
|
+
* continue with `renderedContext` even when ACE is absent or fails.
|
|
62
|
+
*/
|
|
63
|
+
export function createOptionalIntegrationAdapter({ component, createEngine = (options) => new AfyxContextEngine(options) } = {}) {
|
|
64
|
+
if (!SUPPORTED_COMPONENTS.includes(component)) {
|
|
65
|
+
throw new AceError('INVALID_INTEGRATION', `unsupported optional component: ${component}`);
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
contract: ACE_INTEGRATION_CONTRACT,
|
|
69
|
+
component,
|
|
70
|
+
process(request) {
|
|
71
|
+
try {
|
|
72
|
+
if (!request || typeof request !== 'object' || request.contract !== ACE_INTEGRATION_CONTRACT) {
|
|
73
|
+
throw new AceError('INVALID_INTEGRATION', `request contract must be ${ACE_INTEGRATION_CONTRACT}`);
|
|
74
|
+
}
|
|
75
|
+
if (request.component !== component) {
|
|
76
|
+
throw new AceError('INVALID_INTEGRATION', `request component must be ${component}`);
|
|
77
|
+
}
|
|
78
|
+
validateContextRequest(request);
|
|
79
|
+
const engine = createEngine({ stateDir: request.stateDir, ownerId: request.ownerId, sessionId: request.sessionId });
|
|
80
|
+
const result = engine.reduce(request);
|
|
81
|
+
return { status: 'optimized', result, renderedContext: result.renderedContext };
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return fallback(request, error instanceof AceError ? error.code : 'ACE_UNAVAILABLE');
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|