@fitlab-ai/agent-infra 0.9.6 → 0.9.7
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/dist/bin/internal-cli.js +5 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/app-server.js +45 -4
- package/dist/lib/agent-clients/adapters/codex-lifecycle/build-identity.js +162 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/capability-store.js +244 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.js +370 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/store.js +21 -5
- package/dist/lib/defaults.json +10 -2
- package/dist/lib/git/workflow.js +30 -3
- package/dist/lib/internal/codex-lifecycle.js +69 -1
- package/dist/lib/internal/codex-sandbox-controller.js +106 -0
- package/dist/lib/internal/task-orchestration.js +37 -5
- package/dist/lib/platform/context.js +6 -4
- package/dist/lib/platform/github-client.js +55 -2
- package/dist/lib/process-data/checkpoint.js +319 -0
- package/dist/lib/process-data/index.js +128 -60
- package/dist/lib/process-data/materialize.js +84 -0
- package/dist/lib/process-data/normalize.js +34 -1
- package/dist/lib/process-data/reconcile.js +55 -1
- package/dist/lib/process-data/sources.js +422 -1
- package/dist/lib/process-data/store.js +341 -11
- package/dist/lib/sandbox/commands/create.js +103 -51
- package/dist/lib/sandbox/commands/rm.js +64 -15
- package/dist/lib/sandbox/commands/start.js +4 -3
- package/dist/lib/sandbox/control/container-identity.js +64 -0
- package/dist/lib/sandbox/control/executor.js +13 -7
- package/dist/lib/sandbox/control/lifecycle.js +238 -29
- package/dist/lib/sandbox/control/protocol.js +7 -0
- package/dist/lib/sandbox/control/server.js +202 -26
- package/dist/lib/sandbox/control/state.js +25 -15
- package/dist/lib/sandbox/control/timing.js +8 -0
- package/dist/lib/sandbox/mounts.js +5 -13
- package/dist/lib/sandbox/recovery.js +59 -42
- package/dist/lib/sandbox/workspace-view.js +57 -40
- package/dist/lib/server/daemon.js +1 -1
- package/dist/lib/server/process-control.js +11 -1
- package/dist/lib/server/process-state.js +57 -20
- package/dist/lib/task/artifact-lifecycle.js +82 -11
- package/dist/lib/task/artifact-receipts.js +128 -0
- package/dist/lib/task/codex-orchestration.js +81 -6
- package/dist/lib/task/commands/validate.js +1 -1
- package/dist/lib/task/create.js +10 -2
- package/dist/lib/task/delegation-receipts.js +84 -2
- package/dist/lib/task/events.js +139 -2
- package/dist/lib/task/ledger.js +13 -1
- package/dist/lib/task/orchestration.js +235 -14
- package/dist/lib/task/sections.js +5 -1
- package/dist/lib/task/task-execution-lock.js +5 -4
- package/dist/lib/task/verification-engine.js +40 -8
- package/dist/lifecycle-build-manifest.json +6 -0
- package/lib/agent-clients/adapters/codex-lifecycle/app-server.ts +60 -3
- package/lib/agent-clients/adapters/codex-lifecycle/build-identity.ts +227 -0
- package/lib/agent-clients/adapters/codex-lifecycle/capability-store.ts +321 -0
- package/lib/agent-clients/adapters/codex-lifecycle/manifest-files.json +26 -0
- package/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.ts +453 -0
- package/lib/agent-clients/adapters/codex-lifecycle/store.ts +33 -4
- package/lib/defaults.json +10 -2
- package/lib/git/workflow.ts +25 -2
- package/lib/internal/codex-lifecycle.ts +68 -1
- package/lib/internal/codex-sandbox-controller.ts +109 -0
- package/lib/internal/task-orchestration.ts +31 -4
- package/lib/platform/context.ts +8 -5
- package/lib/platform/github-client.ts +61 -3
- package/lib/process-data/checkpoint.ts +335 -0
- package/lib/process-data/index.ts +112 -60
- package/lib/process-data/materialize.ts +83 -0
- package/lib/process-data/normalize.ts +29 -1
- package/lib/process-data/reconcile.ts +64 -2
- package/lib/process-data/sources.ts +449 -2
- package/lib/process-data/store.ts +304 -11
- package/lib/process-data/types.ts +124 -2
- package/lib/sandbox/commands/create.ts +56 -7
- package/lib/sandbox/commands/rm.ts +64 -14
- package/lib/sandbox/commands/start.ts +4 -3
- package/lib/sandbox/control/container-identity.ts +93 -0
- package/lib/sandbox/control/executor.ts +14 -10
- package/lib/sandbox/control/lifecycle.ts +264 -33
- package/lib/sandbox/control/protocol.ts +31 -5
- package/lib/sandbox/control/server.ts +184 -24
- package/lib/sandbox/control/state.ts +34 -17
- package/lib/sandbox/control/timing.ts +12 -0
- package/lib/sandbox/mounts.ts +5 -15
- package/lib/sandbox/recovery.ts +71 -42
- package/lib/sandbox/workspace-view.ts +61 -40
- package/lib/server/daemon.ts +1 -1
- package/lib/server/process-control.ts +13 -3
- package/lib/server/process-state.ts +82 -27
- package/lib/task/artifact-lifecycle.ts +73 -10
- package/lib/task/artifact-receipts.ts +161 -0
- package/lib/task/codex-orchestration.ts +91 -5
- package/lib/task/commands/validate.ts +1 -1
- package/lib/task/create.ts +11 -2
- package/lib/task/delegation-receipts.ts +160 -8
- package/lib/task/events.ts +122 -1
- package/lib/task/ledger.ts +16 -1
- package/lib/task/orchestration.ts +356 -17
- package/lib/task/sections.ts +6 -2
- package/lib/task/task-execution-lock.ts +11 -9
- package/lib/task/verification-engine.ts +51 -16
- package/package.json +1 -1
- package/templates/.agents/README.en.md +7 -0
- package/templates/.agents/README.zh-CN.md +5 -0
- package/templates/.agents/hooks/lifecycle-delegation.js +25 -1
- package/templates/.agents/rules/lifecycle-orchestration.en.md +8 -2
- package/templates/.agents/rules/lifecycle-orchestration.zh-CN.md +8 -2
- package/templates/.agents/rules/pr-checks-commands.github.en.md +1 -1
- package/templates/.agents/rules/pr-checks-commands.github.zh-CN.md +1 -1
- package/templates/.agents/rules/review-handshake.en.md +3 -1
- package/templates/.agents/rules/review-handshake.zh-CN.md +3 -1
- package/templates/.agents/skills/code-task/reference/dual-mode.en.md +3 -1
- package/templates/.agents/skills/code-task/reference/dual-mode.zh-CN.md +3 -1
- package/templates/.agents/skills/complete-task/SKILL.en.md +4 -0
- package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +4 -0
- package/templates/.agents/skills/run-manual-validation/SKILL.en.md +6 -6
- package/templates/.agents/skills/run-manual-validation/SKILL.zh-CN.md +6 -6
- package/templates/.agents/skills/run-manual-validation/config/verify.en.json +14 -3
- package/templates/.agents/skills/run-manual-validation/config/verify.zh-CN.json +14 -3
- package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.en.md +67 -0
- package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.zh-CN.md +67 -0
- package/templates/.agents/skills/run-manual-validation/reference/report-template.en.md +25 -0
- package/templates/.agents/skills/run-manual-validation/reference/report-template.zh-CN.md +25 -0
- package/templates/.agents/skills/run-task/SKILL.en.md +9 -7
- package/templates/.agents/skills/run-task/SKILL.zh-CN.md +9 -7
- package/templates/.agents/skills/run-task/reference/host-validation.en.md +2 -0
- package/templates/.agents/skills/run-task/reference/host-validation.zh-CN.md +2 -0
- package/templates/.agents/skills/update-agent-infra/scripts/sync-templates.js +75 -3
- package/templates/.agents/workspace/README.en.md +0 -26
- package/templates/.agents/workspace/README.zh-CN.md +0 -26
package/dist/bin/internal-cli.js
CHANGED
|
@@ -32,6 +32,11 @@ else
|
|
|
32
32
|
await codexLifecycle(process.argv.slice(3));
|
|
33
33
|
break;
|
|
34
34
|
}
|
|
35
|
+
case 'codex-sandbox-controller': {
|
|
36
|
+
const { codexSandboxController } = await import('../lib/internal/codex-sandbox-controller.js');
|
|
37
|
+
await codexSandboxController(process.argv.slice(3));
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
35
40
|
case 'git-workflow': {
|
|
36
41
|
const { gitWorkflow } = await import('../lib/internal/git-workflow.js');
|
|
37
42
|
gitWorkflow(process.argv.slice(3));
|
|
@@ -93,7 +93,7 @@ function validateCodexLifecycleHookConfig(value) {
|
|
|
93
93
|
if (!valid)
|
|
94
94
|
throw new Error('CODEX_PREFLIGHT_HOOKS_INVALID: lifecycle hooks are invalid');
|
|
95
95
|
}
|
|
96
|
-
function parseCodexHooksList(value, repoRoot) {
|
|
96
|
+
function parseCodexHooksList(value, repoRoot, expectedSource = 'direct-host') {
|
|
97
97
|
const root = object(value);
|
|
98
98
|
const entries = Array.isArray(root?.data) ? root.data : [];
|
|
99
99
|
const entry = entries.map(object).find((candidate) => candidate?.cwd === repoRoot);
|
|
@@ -107,12 +107,27 @@ function parseCodexHooksList(value, repoRoot) {
|
|
|
107
107
|
eventName: String(hook.eventName ?? ''),
|
|
108
108
|
matcher: typeof hook.matcher === 'string' ? hook.matcher : null,
|
|
109
109
|
command: String(hook.command ?? ''),
|
|
110
|
-
enabled: hook.enabled === true
|
|
110
|
+
enabled: hook.enabled === true,
|
|
111
|
+
source: String(hook.source ?? ''),
|
|
112
|
+
sourcePathDigest: typeof hook.sourcePath === 'string' && path.isAbsolute(hook.sourcePath)
|
|
113
|
+
? crypto.createHash('sha256').update(hook.sourcePath).digest('hex')
|
|
114
|
+
: '',
|
|
115
|
+
trustStatus: String(hook.trustStatus ?? ''),
|
|
116
|
+
currentHash: String(hook.currentHash ?? ''),
|
|
117
|
+
isManaged: hook.isManaged === true,
|
|
118
|
+
pluginId: typeof hook.pluginId === 'string' ? hook.pluginId : null
|
|
111
119
|
}));
|
|
112
120
|
const valid = LIFECYCLE_HOOKS.every(({ event, matcher, phase }) => hooks.some((hook) => hook.eventName === event.replace(/^./, (character) => character.toLowerCase())
|
|
113
121
|
&& hook.matcher === matcher
|
|
114
122
|
&& hook.command === `node "$(git rev-parse --show-toplevel)/.agents/hooks/lifecycle-delegation.js" --client codex --event ${phase}`
|
|
115
|
-
&& hook.enabled
|
|
123
|
+
&& hook.enabled
|
|
124
|
+
&& hook.currentHash.length > 0
|
|
125
|
+
&& hook.sourcePathDigest.length === 64
|
|
126
|
+
&& hook.pluginId === null
|
|
127
|
+
&& (expectedSource === 'isolated-user'
|
|
128
|
+
? hook.source === 'user' && hook.trustStatus !== 'modified'
|
|
129
|
+
: (hook.source === 'project' && hook.trustStatus === 'trusted')
|
|
130
|
+
|| hook.isManaged && hook.trustStatus === 'managed')));
|
|
116
131
|
if (!valid)
|
|
117
132
|
throw new Error('CODEX_PREFLIGHT_HOOKS_NOT_LOADED: lifecycle hooks are not loaded for this workspace');
|
|
118
133
|
return Object.freeze(hooks);
|
|
@@ -474,16 +489,42 @@ async function preflightCodexLifecycleEvidence(repoRoot = process.cwd(), runtime
|
|
|
474
489
|
let discoveredHooks;
|
|
475
490
|
try {
|
|
476
491
|
await transport.initialize();
|
|
477
|
-
discoveredHooks = parseCodexHooksList(await transport.request('hooks/list', { cwds: [repoRoot] }), repoRoot);
|
|
492
|
+
discoveredHooks = parseCodexHooksList(await transport.request('hooks/list', { cwds: [repoRoot] }), repoRoot, process.env.AGENT_INFRA_CODEX_CONTROLLER_CONTEXT ? 'isolated-user' : 'direct-host');
|
|
478
493
|
}
|
|
479
494
|
finally {
|
|
480
495
|
transport.close();
|
|
481
496
|
}
|
|
497
|
+
const lifecycleHooks = LIFECYCLE_HOOKS.map(({ event, matcher, phase }) => discoveredHooks.filter((hook) => hook.eventName === event.replace(/^./, (character) => character.toLowerCase())
|
|
498
|
+
&& hook.matcher === matcher
|
|
499
|
+
&& hook.command === `node "$(git rev-parse --show-toplevel)/.agents/hooks/lifecycle-delegation.js" --client codex --event ${phase}`));
|
|
500
|
+
if (lifecycleHooks.some((matches) => matches.length !== 1)) {
|
|
501
|
+
throw new Error('CODEX_PREFLIGHT_HOOK_SOURCE_AMBIGUOUS: lifecycle hook source is not unique');
|
|
502
|
+
}
|
|
503
|
+
const matchedHooks = lifecycleHooks.flat();
|
|
504
|
+
const sources = new Set(matchedHooks.map((hook) => hook.isManaged ? 'managed' : hook.source));
|
|
505
|
+
const sourcePathDigests = new Set(matchedHooks.map((hook) => hook.sourcePathDigest));
|
|
506
|
+
if (sources.size !== 1 || sourcePathDigests.size !== 1) {
|
|
507
|
+
throw new Error('CODEX_PREFLIGHT_HOOK_SOURCE_AMBIGUOUS: lifecycle hooks do not share one exact source');
|
|
508
|
+
}
|
|
509
|
+
const source = [...sources][0];
|
|
510
|
+
const hookSource = process.env.AGENT_INFRA_CODEX_CONTROLLER_CONTEXT
|
|
511
|
+
? 'isolated-user'
|
|
512
|
+
: source === 'managed' ? 'managed' : 'project';
|
|
482
513
|
return Object.freeze({
|
|
483
514
|
cliVersion: match[1],
|
|
484
515
|
hookDefinitionHash,
|
|
485
516
|
staticReady: true,
|
|
486
517
|
discoveredHooks,
|
|
518
|
+
hookProvenance: Object.freeze({
|
|
519
|
+
hookSource,
|
|
520
|
+
hookSourcePathDigest: [...sourcePathDigests][0],
|
|
521
|
+
hookSourceHash: crypto.createHash('sha256').update(JSON.stringify(matchedHooks.map((hook) => ({
|
|
522
|
+
eventName: hook.eventName,
|
|
523
|
+
matcher: hook.matcher,
|
|
524
|
+
command: hook.command,
|
|
525
|
+
currentHash: hook.currentHash
|
|
526
|
+
})))).digest('hex')
|
|
527
|
+
}),
|
|
487
528
|
runtimeLiveness,
|
|
488
529
|
diagnostics: transport.diagnostics
|
|
489
530
|
});
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
const LIFECYCLE_PROTOCOL_VERSION = 3;
|
|
6
|
+
function exactText(value) {
|
|
7
|
+
return typeof value === 'string' && value.trim() === value && value.length > 0;
|
|
8
|
+
}
|
|
9
|
+
function normalizeRelativePath(value) {
|
|
10
|
+
return value.replaceAll('\\', '/');
|
|
11
|
+
}
|
|
12
|
+
function readLifecycleManifestFiles(packageRoot) {
|
|
13
|
+
const file = path.join(packageRoot, 'lib', 'agent-clients', 'adapters', 'codex-lifecycle', 'manifest-files.json');
|
|
14
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
15
|
+
if (!Array.isArray(value.executableFiles)
|
|
16
|
+
|| !Array.isArray(value.contractFiles)
|
|
17
|
+
|| !value.executableFiles.every(exactText)
|
|
18
|
+
|| !value.contractFiles.every(exactText)
|
|
19
|
+
|| new Set(value.executableFiles).size !== value.executableFiles.length
|
|
20
|
+
|| new Set(value.contractFiles).size !== value.contractFiles.length) {
|
|
21
|
+
throw new Error('Lifecycle manifest file list is invalid');
|
|
22
|
+
}
|
|
23
|
+
return Object.freeze({
|
|
24
|
+
executableFiles: Object.freeze([...value.executableFiles]),
|
|
25
|
+
contractFiles: Object.freeze([...value.contractFiles])
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function executablePackageRoot() {
|
|
29
|
+
let current = path.dirname(fileURLToPath(import.meta.url));
|
|
30
|
+
while (true) {
|
|
31
|
+
const candidate = path.join(current, 'package.json');
|
|
32
|
+
if (fs.existsSync(candidate)) {
|
|
33
|
+
const value = JSON.parse(fs.readFileSync(candidate, 'utf8'));
|
|
34
|
+
if (value.name === '@fitlab-ai/agent-infra')
|
|
35
|
+
return current;
|
|
36
|
+
}
|
|
37
|
+
const parent = path.dirname(current);
|
|
38
|
+
if (parent === current)
|
|
39
|
+
throw new Error('Lifecycle executable package root is unavailable');
|
|
40
|
+
current = parent;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function hashFiles(root, files) {
|
|
44
|
+
const hash = crypto.createHash('sha256');
|
|
45
|
+
for (const relative of [...new Set(files.map(normalizeRelativePath))].sort()) {
|
|
46
|
+
if (path.isAbsolute(relative) || relative.split(/[\\/]/u).includes('..')) {
|
|
47
|
+
throw new Error(`Lifecycle manifest path '${relative}' is unsafe`);
|
|
48
|
+
}
|
|
49
|
+
const file = path.join(root, relative);
|
|
50
|
+
const stat = fs.lstatSync(file);
|
|
51
|
+
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
52
|
+
throw new Error(`Lifecycle manifest entry '${relative}' must be a regular file`);
|
|
53
|
+
}
|
|
54
|
+
hash.update(relative);
|
|
55
|
+
hash.update('\0');
|
|
56
|
+
hash.update(fs.readFileSync(file));
|
|
57
|
+
hash.update('\0');
|
|
58
|
+
}
|
|
59
|
+
return hash.digest('hex');
|
|
60
|
+
}
|
|
61
|
+
function resolveLifecycleExecutableFiles(root, entries) {
|
|
62
|
+
const pending = [...entries];
|
|
63
|
+
const resolved = new Set();
|
|
64
|
+
while (pending.length > 0) {
|
|
65
|
+
const relative = normalizeRelativePath(pending.pop());
|
|
66
|
+
if (resolved.has(relative))
|
|
67
|
+
continue;
|
|
68
|
+
resolved.add(relative);
|
|
69
|
+
if (!/\.[cm]?[jt]s$/u.test(relative))
|
|
70
|
+
continue;
|
|
71
|
+
const file = path.join(root, relative);
|
|
72
|
+
const source = fs.readFileSync(file, 'utf8');
|
|
73
|
+
const imports = source.matchAll(/(?:\bfrom\s*|\bimport\s*(?:\(\s*)?)["'](\.[^"']+)["']/gu);
|
|
74
|
+
for (const match of imports) {
|
|
75
|
+
const requested = match[1];
|
|
76
|
+
const base = path.resolve(path.dirname(file), requested);
|
|
77
|
+
const candidates = [
|
|
78
|
+
base,
|
|
79
|
+
`${base}.ts`, `${base}.js`,
|
|
80
|
+
path.join(base, 'index.ts'), path.join(base, 'index.js')
|
|
81
|
+
];
|
|
82
|
+
const dependency = candidates.find((candidate) => fs.existsSync(candidate) && fs.lstatSync(candidate).isFile());
|
|
83
|
+
if (!dependency)
|
|
84
|
+
throw new Error(`Lifecycle executable dependency '${requested}' from '${relative}' is unavailable`);
|
|
85
|
+
const dependencyRelative = path.relative(root, dependency);
|
|
86
|
+
if (dependencyRelative.startsWith('..') || path.isAbsolute(dependencyRelative)) {
|
|
87
|
+
throw new Error(`Lifecycle executable dependency '${requested}' escapes the package root`);
|
|
88
|
+
}
|
|
89
|
+
pending.push(normalizeRelativePath(dependencyRelative));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return [...resolved].sort();
|
|
93
|
+
}
|
|
94
|
+
function computeLifecycleBuildIdentity(repoRoot, options = {}) {
|
|
95
|
+
const packageRoot = executablePackageRoot();
|
|
96
|
+
const executableRoot = options.executableFiles ? repoRoot : packageRoot;
|
|
97
|
+
const defaults = readLifecycleManifestFiles(packageRoot);
|
|
98
|
+
const packageJson = JSON.parse(fs.readFileSync(path.join(executableRoot, 'package.json'), 'utf8'));
|
|
99
|
+
if (!exactText(packageJson.version))
|
|
100
|
+
throw new Error('Lifecycle package version is invalid');
|
|
101
|
+
let internalExecutableBuildHash;
|
|
102
|
+
if (options.executableFiles) {
|
|
103
|
+
internalExecutableBuildHash = hashFiles(repoRoot, options.executableFiles);
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
const manifestFile = path.join(executableRoot, 'dist', 'lifecycle-build-manifest.json');
|
|
107
|
+
if (fs.existsSync(manifestFile)) {
|
|
108
|
+
const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
|
|
109
|
+
if (manifest.protocolVersion !== LIFECYCLE_PROTOCOL_VERSION
|
|
110
|
+
|| manifest.packageVersion !== packageJson.version
|
|
111
|
+
|| !exactText(manifest.sourceInputHash)
|
|
112
|
+
|| !exactText(manifest.internalExecutableBuildHash)) {
|
|
113
|
+
throw new Error('Lifecycle executable build manifest is stale or invalid');
|
|
114
|
+
}
|
|
115
|
+
if (fileURLToPath(import.meta.url).split(path.sep).includes('dist')) {
|
|
116
|
+
const compiledFiles = defaults.executableFiles.map((file) => file.endsWith('.ts') ? path.join('dist', file.replace(/\.ts$/u, '.js')) : file);
|
|
117
|
+
if (hashFiles(executableRoot, resolveLifecycleExecutableFiles(executableRoot, compiledFiles)) !== manifest.internalExecutableBuildHash) {
|
|
118
|
+
throw new Error('Lifecycle compiled executable build does not match its manifest');
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
else if (hashFiles(executableRoot, resolveLifecycleExecutableFiles(executableRoot, defaults.executableFiles)) !== manifest.sourceInputHash) {
|
|
122
|
+
throw new Error('Lifecycle executable build manifest is stale or invalid');
|
|
123
|
+
}
|
|
124
|
+
internalExecutableBuildHash = manifest.internalExecutableBuildHash;
|
|
125
|
+
}
|
|
126
|
+
else
|
|
127
|
+
internalExecutableBuildHash = hashFiles(executableRoot, resolveLifecycleExecutableFiles(executableRoot, defaults.executableFiles));
|
|
128
|
+
}
|
|
129
|
+
return Object.freeze({
|
|
130
|
+
protocolVersion: LIFECYCLE_PROTOCOL_VERSION,
|
|
131
|
+
packageVersion: packageJson.version,
|
|
132
|
+
internalExecutableBuildHash,
|
|
133
|
+
lifecycleContractHash: hashFiles(repoRoot, options.contractFiles ?? defaults.contractFiles)
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
function verifyLifecycleBuildIdentity(expected, actual) {
|
|
137
|
+
if (actual.protocolVersion !== expected.protocolVersion) {
|
|
138
|
+
return {
|
|
139
|
+
ok: false,
|
|
140
|
+
code: 'CODEX_LIFECYCLE_PROTOCOL_MISMATCH',
|
|
141
|
+
message: 'Codex lifecycle protocol version does not match'
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
if (actual.packageVersion !== expected.packageVersion
|
|
145
|
+
|| actual.internalExecutableBuildHash !== expected.internalExecutableBuildHash) {
|
|
146
|
+
return {
|
|
147
|
+
ok: false,
|
|
148
|
+
code: 'CODEX_LIFECYCLE_BUILD_MISMATCH',
|
|
149
|
+
message: 'Codex lifecycle executable build identity does not match'
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
if (actual.lifecycleContractHash !== expected.lifecycleContractHash) {
|
|
153
|
+
return {
|
|
154
|
+
ok: false,
|
|
155
|
+
code: 'CODEX_LIFECYCLE_CONTRACT_MISMATCH',
|
|
156
|
+
message: 'Codex lifecycle contract identity does not match'
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
return { ok: true, code: null, message: null };
|
|
160
|
+
}
|
|
161
|
+
export { LIFECYCLE_PROTOCOL_VERSION, computeLifecycleBuildIdentity, readLifecycleManifestFiles, resolveLifecycleExecutableFiles, verifyLifecycleBuildIdentity };
|
|
162
|
+
//# sourceMappingURL=build-identity.js.map
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { verifyLifecycleBuildIdentity } from './build-identity.js';
|
|
5
|
+
const DEFAULT_TTL_MS = 30_000;
|
|
6
|
+
const DEFAULT_TOMBSTONE_MS = 86_400_000;
|
|
7
|
+
const DEFAULT_MAX_RECORDS = 128;
|
|
8
|
+
const LOCK_RETRY_MS = 10;
|
|
9
|
+
const LOCK_TIMEOUT_MS = 1_000;
|
|
10
|
+
const LOCK_STALE_MS = 30_000;
|
|
11
|
+
function digest(value) {
|
|
12
|
+
return crypto.createHash('sha256').update(value).digest('hex');
|
|
13
|
+
}
|
|
14
|
+
function capabilityError(code, message) {
|
|
15
|
+
const error = new Error(`${code}: ${message}`);
|
|
16
|
+
error.name = code;
|
|
17
|
+
return error;
|
|
18
|
+
}
|
|
19
|
+
function sameController(left, right) {
|
|
20
|
+
return left?.instanceDigest === right?.instanceDigest
|
|
21
|
+
&& left?.controlGeneration === right?.controlGeneration;
|
|
22
|
+
}
|
|
23
|
+
function createCodexCapabilityStore(options = {}) {
|
|
24
|
+
const root = options.root
|
|
25
|
+
?? path.join(process.cwd(), '.agents', 'workspace', '.runtime', 'codex-capabilities');
|
|
26
|
+
const now = options.now ?? Date.now;
|
|
27
|
+
const createToken = options.token ?? (() => crypto.randomBytes(32).toString('base64url'));
|
|
28
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
29
|
+
const tombstoneMs = options.tombstoneMs ?? DEFAULT_TOMBSTONE_MS;
|
|
30
|
+
const maxRecords = options.maxRecords ?? DEFAULT_MAX_RECORDS;
|
|
31
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
32
|
+
fs.chmodSync(root, 0o700);
|
|
33
|
+
function fileFor(token) {
|
|
34
|
+
return path.join(root, `${digest(token)}.json`);
|
|
35
|
+
}
|
|
36
|
+
function read(file) {
|
|
37
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
38
|
+
if (value.schemaVersion !== 1 || !Number.isSafeInteger(value.revision) || value.revision < 1) {
|
|
39
|
+
throw capabilityError('CODEX_CAPABILITY_STATE_INVALID', 'capability record schema is invalid');
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function withWriteLock(operation) {
|
|
44
|
+
const lock = path.join(root, '.write.lock');
|
|
45
|
+
const deadline = Date.now() + LOCK_TIMEOUT_MS;
|
|
46
|
+
let descriptor = null;
|
|
47
|
+
while (descriptor === null) {
|
|
48
|
+
try {
|
|
49
|
+
descriptor = fs.openSync(lock, 'wx', 0o600);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (error.code !== 'EEXIST')
|
|
53
|
+
throw error;
|
|
54
|
+
try {
|
|
55
|
+
if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) {
|
|
56
|
+
fs.unlinkSync(lock);
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
catch (lockError) {
|
|
61
|
+
if (lockError.code === 'ENOENT')
|
|
62
|
+
continue;
|
|
63
|
+
throw lockError;
|
|
64
|
+
}
|
|
65
|
+
if (Date.now() >= deadline) {
|
|
66
|
+
throw capabilityError('CODEX_CAPABILITY_STORE_BUSY', 'capability store is busy');
|
|
67
|
+
}
|
|
68
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_RETRY_MS);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return operation();
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
fs.closeSync(descriptor);
|
|
76
|
+
fs.unlinkSync(lock);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function write(file, value, expectedRevision) {
|
|
80
|
+
const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
81
|
+
fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, {
|
|
82
|
+
encoding: 'utf8',
|
|
83
|
+
flag: 'wx',
|
|
84
|
+
mode: 0o600
|
|
85
|
+
});
|
|
86
|
+
try {
|
|
87
|
+
withWriteLock(() => {
|
|
88
|
+
options.beforeCompareAndSwap?.({ path: file, expectedRevision });
|
|
89
|
+
const actualRevision = fs.existsSync(file) ? read(file).revision : 0;
|
|
90
|
+
if (actualRevision !== expectedRevision) {
|
|
91
|
+
throw capabilityError('CODEX_CAPABILITY_REVISION_CONFLICT', `capability revision changed from ${expectedRevision} to ${actualRevision}`);
|
|
92
|
+
}
|
|
93
|
+
fs.renameSync(temporary, file);
|
|
94
|
+
fs.chmodSync(file, 0o600);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
if (fs.existsSync(temporary))
|
|
99
|
+
fs.unlinkSync(temporary);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function files() {
|
|
103
|
+
return fs.readdirSync(root)
|
|
104
|
+
.filter((name) => /^[a-f0-9]{64}\.json$/u.test(name))
|
|
105
|
+
.map((name) => path.join(root, name));
|
|
106
|
+
}
|
|
107
|
+
function expire(record, file, timestamp) {
|
|
108
|
+
if ((record.status === 'armed' || record.status === 'attested') && timestamp > record.expiresAt) {
|
|
109
|
+
const expired = Object.freeze({
|
|
110
|
+
...record,
|
|
111
|
+
revision: record.revision + 1,
|
|
112
|
+
status: 'expired'
|
|
113
|
+
});
|
|
114
|
+
write(file, expired, record.revision);
|
|
115
|
+
return expired;
|
|
116
|
+
}
|
|
117
|
+
return record;
|
|
118
|
+
}
|
|
119
|
+
function sweep() {
|
|
120
|
+
const timestamp = now();
|
|
121
|
+
const records = files().map((file) => ({ file, record: expire(read(file), file, timestamp) }));
|
|
122
|
+
for (const entry of records) {
|
|
123
|
+
const terminalAt = entry.record.consumedAt ?? entry.record.expiresAt;
|
|
124
|
+
if (['consumed', 'expired'].includes(entry.record.status)
|
|
125
|
+
&& timestamp - terminalAt > tombstoneMs) {
|
|
126
|
+
fs.unlinkSync(entry.file);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const remaining = files().map((file) => ({ file, record: read(file) }));
|
|
130
|
+
if (remaining.length <= maxRecords)
|
|
131
|
+
return;
|
|
132
|
+
const removable = remaining
|
|
133
|
+
.filter(({ record }) => ['consumed', 'expired'].includes(record.status))
|
|
134
|
+
.sort((left, right) => (left.record.consumedAt ?? left.record.expiresAt)
|
|
135
|
+
- (right.record.consumedAt ?? right.record.expiresAt));
|
|
136
|
+
while (files().length > maxRecords && removable.length > 0) {
|
|
137
|
+
fs.unlinkSync(removable.shift().file);
|
|
138
|
+
}
|
|
139
|
+
if (files().length > maxRecords) {
|
|
140
|
+
throw capabilityError('CODEX_CAPABILITY_CAPACITY_EXCEEDED', 'capability store has too many active records');
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function arm(input) {
|
|
144
|
+
sweep();
|
|
145
|
+
const token = createToken();
|
|
146
|
+
const file = fileFor(token);
|
|
147
|
+
if (fs.existsSync(file))
|
|
148
|
+
throw capabilityError('CODEX_CAPABILITY_TOKEN_COLLISION', 'capability token already exists');
|
|
149
|
+
const timestamp = now();
|
|
150
|
+
const record = Object.freeze({
|
|
151
|
+
schemaVersion: 1,
|
|
152
|
+
revision: 1,
|
|
153
|
+
tokenDigest: digest(token),
|
|
154
|
+
taskId: input.taskId,
|
|
155
|
+
status: 'armed',
|
|
156
|
+
buildIdentity: input.buildIdentity,
|
|
157
|
+
controller: input.controller ?? null,
|
|
158
|
+
sessionId: null,
|
|
159
|
+
turnId: null,
|
|
160
|
+
toolUseId: null,
|
|
161
|
+
hookDefinitionHash: null,
|
|
162
|
+
armedAt: timestamp,
|
|
163
|
+
expiresAt: timestamp + ttlMs,
|
|
164
|
+
attestedAt: null,
|
|
165
|
+
consumedAt: null
|
|
166
|
+
});
|
|
167
|
+
write(file, record, 0);
|
|
168
|
+
return Object.freeze({
|
|
169
|
+
...record,
|
|
170
|
+
token,
|
|
171
|
+
path: file,
|
|
172
|
+
marker: `agent-infra-codex-capability:${token}`
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
function loadActive(token) {
|
|
176
|
+
const file = fileFor(token);
|
|
177
|
+
if (!fs.existsSync(file)) {
|
|
178
|
+
throw capabilityError('CODEX_CAPABILITY_MISSING', 'capability token was not found');
|
|
179
|
+
}
|
|
180
|
+
const record = expire(read(file), file, now());
|
|
181
|
+
if (record.status === 'expired') {
|
|
182
|
+
throw capabilityError('CODEX_CAPABILITY_EXPIRED', 'capability token expired');
|
|
183
|
+
}
|
|
184
|
+
return { file, record };
|
|
185
|
+
}
|
|
186
|
+
function attest(input) {
|
|
187
|
+
const { file, record } = loadActive(input.token);
|
|
188
|
+
if (record.status !== 'armed') {
|
|
189
|
+
throw capabilityError(record.status === 'consumed' ? 'CODEX_CAPABILITY_REPLAY' : 'CODEX_CAPABILITY_STATE_INVALID', `capability is ${record.status}, expected armed`);
|
|
190
|
+
}
|
|
191
|
+
const identity = verifyLifecycleBuildIdentity(record.buildIdentity, input.buildIdentity);
|
|
192
|
+
if (!identity.ok || !sameController(record.controller, input.controller ?? null)) {
|
|
193
|
+
throw capabilityError('CODEX_CAPABILITY_PROVENANCE_MISMATCH', 'capability build or controller identity does not match');
|
|
194
|
+
}
|
|
195
|
+
if (![input.sessionId, input.turnId, input.toolUseId, input.hookDefinitionHash]
|
|
196
|
+
.every((value) => value.trim().length > 0)) {
|
|
197
|
+
throw capabilityError('CODEX_CAPABILITY_IDENTITY_INVALID', 'hook identity is incomplete');
|
|
198
|
+
}
|
|
199
|
+
const timestamp = now();
|
|
200
|
+
const next = Object.freeze({
|
|
201
|
+
...record,
|
|
202
|
+
revision: record.revision + 1,
|
|
203
|
+
status: 'attested',
|
|
204
|
+
sessionId: input.sessionId,
|
|
205
|
+
turnId: input.turnId,
|
|
206
|
+
toolUseId: input.toolUseId,
|
|
207
|
+
hookDefinitionHash: input.hookDefinitionHash,
|
|
208
|
+
attestedAt: timestamp
|
|
209
|
+
});
|
|
210
|
+
write(file, next, record.revision);
|
|
211
|
+
return next;
|
|
212
|
+
}
|
|
213
|
+
function consume(token, expected) {
|
|
214
|
+
sweep();
|
|
215
|
+
const { file, record } = loadActive(token);
|
|
216
|
+
if (record.status === 'consumed') {
|
|
217
|
+
throw capabilityError('CODEX_CAPABILITY_REPLAY', 'capability token was already consumed');
|
|
218
|
+
}
|
|
219
|
+
if (record.status !== 'attested') {
|
|
220
|
+
throw capabilityError('CODEX_CAPABILITY_NOT_ATTESTED', 'capability token has no current-session hook attestation');
|
|
221
|
+
}
|
|
222
|
+
const identity = verifyLifecycleBuildIdentity(record.buildIdentity, expected.buildIdentity);
|
|
223
|
+
if (!identity.ok
|
|
224
|
+
|| record.taskId !== expected.taskId
|
|
225
|
+
|| record.hookDefinitionHash !== expected.hookDefinitionHash
|
|
226
|
+
|| !sameController(record.controller, expected.controller ?? null)) {
|
|
227
|
+
throw capabilityError('CODEX_CAPABILITY_PROVENANCE_MISMATCH', 'capability consumption identity does not match');
|
|
228
|
+
}
|
|
229
|
+
const next = Object.freeze({
|
|
230
|
+
...record,
|
|
231
|
+
revision: record.revision + 1,
|
|
232
|
+
status: 'consumed',
|
|
233
|
+
consumedAt: now()
|
|
234
|
+
});
|
|
235
|
+
write(file, next, record.revision);
|
|
236
|
+
return next;
|
|
237
|
+
}
|
|
238
|
+
function inspect(token) {
|
|
239
|
+
return loadActive(token).record;
|
|
240
|
+
}
|
|
241
|
+
return Object.freeze({ arm, attest, consume, inspect, sweep });
|
|
242
|
+
}
|
|
243
|
+
export { createCodexCapabilityStore };
|
|
244
|
+
//# sourceMappingURL=capability-store.js.map
|