@fitlab-ai/agent-infra 0.11.11 → 0.11.13
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 +2 -2
- package/dist/lib/agent-clients/adapter.js +7 -1
- package/dist/lib/agent-clients/adapters/claude-code.js +5 -1
- package/dist/lib/agent-clients/adapters/codex-lifecycle/app-server.js +78 -63
- package/dist/lib/agent-clients/adapters/codex-lifecycle/binding.js +114 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/cli.js +447 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/controller-client.js +130 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/controller-operation.js +131 -0
- package/dist/lib/{sandbox/control → agent-clients/adapters/codex-lifecycle}/controller-registration.js +2 -2
- package/dist/lib/agent-clients/adapters/codex-lifecycle/evidence.js +48 -1
- package/dist/lib/agent-clients/adapters/codex-lifecycle/recovery.js +124 -62
- package/dist/lib/{internal/codex-sandbox-controller.js → agent-clients/adapters/codex-lifecycle/sandbox-controller-cli.js} +3 -3
- package/dist/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.js +3 -5
- package/dist/lib/agent-clients/adapters/codex-lifecycle/store.js +211 -213
- package/dist/lib/agent-clients/adapters/codex-orchestration.js +468 -0
- package/dist/lib/agent-clients/adapters/codex.js +40 -1
- package/dist/lib/agent-clients/adapters/index.js +2 -10
- package/dist/lib/agent-clients/tokens.js +3 -2
- package/dist/lib/internal/agent-client.js +132 -72
- package/dist/lib/internal/cli-route-inventory.js +2 -2
- package/dist/lib/internal/sandbox-control.js +1 -81
- package/dist/lib/internal/task-finalization.js +26 -19
- package/dist/lib/internal/task-lifecycle.js +1 -1
- package/dist/lib/internal/task-operation-registry.js +1 -1
- package/dist/lib/internal/task-validate.js +1 -1
- package/dist/lib/platform/github-client.js +33 -3
- package/dist/lib/platform/issues.js +18 -6
- package/dist/lib/runtime/agent-runtime.js +6 -29
- package/dist/lib/sandbox/commands/control-status.js +1 -0
- package/dist/lib/sandbox/commands/create.js +7 -2
- package/dist/lib/sandbox/commands/ls.js +4 -5
- package/dist/lib/sandbox/commands/rm.js +1 -1
- package/dist/lib/sandbox/control/agent-operation.js +34 -0
- package/dist/lib/sandbox/control/client.js +14 -201
- package/dist/lib/sandbox/control/executor.js +12 -125
- package/dist/lib/sandbox/control/lifecycle.js +66 -4
- package/dist/lib/sandbox/control/protocol.js +15 -54
- package/dist/lib/sandbox/control/server.js +216 -281
- package/dist/lib/sandbox/control/task-view.js +0 -13
- package/dist/lib/sandbox/mounts.js +9 -1
- package/dist/lib/sandbox/recovery.js +31 -10
- package/dist/lib/sandbox/removal.js +28 -5
- package/dist/lib/sandbox/workspace-identity.js +18 -6
- package/dist/lib/sandbox/workspace-view.js +56 -19
- package/dist/lib/task/commands/ls.js +3 -3
- package/dist/lib/task/control-authority.js +56 -264
- package/dist/lib/task/control-recovery.js +2 -3
- package/dist/lib/task/create.js +2 -2
- package/dist/lib/task/delegation-receipts.js +74 -161
- package/dist/lib/task/events.js +88 -44
- package/dist/lib/task/finalization.js +35 -6
- package/dist/lib/task/lifecycle.js +274 -115
- package/dist/lib/task/orchestration.js +201 -194
- package/dist/lib/task/runtime-paths.js +10 -0
- package/dist/lib/task/short-id.js +37 -27
- package/dist/lib/task/verification-engine.js +32 -26
- package/dist/lib/task/workspace-snapshot.js +1 -1
- package/dist/lifecycle-build-manifest.json +3 -3
- package/lib/agent-clients/adapter.ts +39 -0
- package/lib/agent-clients/adapters/claude-code.ts +5 -1
- package/lib/agent-clients/adapters/codex-lifecycle/app-server.ts +105 -80
- package/lib/agent-clients/adapters/codex-lifecycle/binding.ts +147 -0
- package/lib/agent-clients/adapters/codex-lifecycle/cli.ts +510 -0
- package/lib/agent-clients/adapters/codex-lifecycle/controller-client.ts +158 -0
- package/lib/agent-clients/adapters/codex-lifecycle/controller-context.ts +1 -1
- package/lib/agent-clients/adapters/codex-lifecycle/controller-operation.ts +151 -0
- package/lib/{sandbox/control → agent-clients/adapters/codex-lifecycle}/controller-registration.ts +4 -4
- package/lib/agent-clients/adapters/codex-lifecycle/evidence.ts +43 -0
- package/lib/agent-clients/adapters/codex-lifecycle/manifest-files.json +8 -5
- package/lib/agent-clients/adapters/codex-lifecycle/recovery.ts +190 -65
- package/lib/{internal/codex-sandbox-controller.ts → agent-clients/adapters/codex-lifecycle/sandbox-controller-cli.ts} +2 -2
- package/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.ts +3 -5
- package/lib/agent-clients/adapters/codex-lifecycle/store.ts +270 -224
- package/lib/agent-clients/adapters/codex-orchestration.ts +632 -0
- package/lib/agent-clients/adapters/codex.ts +44 -1
- package/lib/agent-clients/adapters/index.ts +7 -20
- package/lib/agent-clients/tokens.ts +4 -3
- package/lib/internal/agent-client.ts +142 -73
- package/lib/internal/cli-route-inventory.ts +2 -2
- package/lib/internal/sandbox-control.ts +0 -97
- package/lib/internal/task-finalization.ts +30 -18
- package/lib/internal/task-lifecycle.ts +1 -1
- package/lib/internal/task-operation-registry.ts +1 -1
- package/lib/internal/task-validate.ts +1 -1
- package/lib/platform/github-client.ts +34 -3
- package/lib/platform/issues.ts +18 -6
- package/lib/runtime/agent-runtime.ts +6 -41
- package/lib/sandbox/commands/control-status.ts +1 -0
- package/lib/sandbox/commands/create.ts +7 -1
- package/lib/sandbox/commands/ls.ts +4 -5
- package/lib/sandbox/commands/rm.ts +1 -1
- package/lib/sandbox/control/agent-operation.ts +49 -0
- package/lib/sandbox/control/client.ts +20 -254
- package/lib/sandbox/control/executor.ts +13 -136
- package/lib/sandbox/control/lifecycle.ts +67 -4
- package/lib/sandbox/control/protocol.ts +22 -66
- package/lib/sandbox/control/server.ts +21 -95
- package/lib/sandbox/control/task-view.ts +0 -19
- package/lib/sandbox/mounts.ts +10 -1
- package/lib/sandbox/recovery.ts +38 -17
- package/lib/sandbox/removal.ts +33 -7
- package/lib/sandbox/workspace-identity.ts +16 -6
- package/lib/sandbox/workspace-view.ts +50 -18
- package/lib/task/commands/ls.ts +3 -3
- package/lib/task/control-authority.ts +66 -378
- package/lib/task/control-recovery.ts +3 -4
- package/lib/task/create.ts +3 -3
- package/lib/task/delegation-receipts.ts +87 -231
- package/lib/task/events.ts +100 -42
- package/lib/task/finalization.ts +37 -7
- package/lib/task/lifecycle.ts +257 -109
- package/lib/task/orchestration.ts +260 -237
- package/lib/task/runtime-paths.ts +12 -0
- package/lib/task/short-id.ts +33 -40
- package/lib/task/verification-engine.ts +30 -25
- package/lib/task/workspace-snapshot.ts +1 -1
- package/package.json +1 -1
- package/templates/.agents/hooks/lifecycle-delegation.js +1 -25
- package/templates/.agents/rules/README.en.md +2 -1
- package/templates/.agents/rules/README.zh-CN.md +2 -1
- package/templates/.agents/rules/next-step-output.en.md +6 -19
- package/templates/.agents/rules/next-step-output.zh-CN.md +6 -19
- package/templates/.agents/rules/strategy-pattern.en.md +25 -0
- package/templates/.agents/rules/strategy-pattern.zh-CN.md +25 -0
- package/templates/.agents/skills/analyze-task/SKILL.en.md +1 -1
- package/templates/.agents/skills/analyze-task/SKILL.zh-CN.md +1 -1
- package/templates/.agents/skills/check-task/SKILL.en.md +1 -1
- package/templates/.agents/skills/check-task/SKILL.zh-CN.md +1 -1
- package/templates/.agents/skills/code-task/SKILL.en.md +1 -1
- package/templates/.agents/skills/code-task/SKILL.zh-CN.md +1 -1
- package/templates/.agents/skills/code-task/reference/code-rules.en.md +4 -0
- package/templates/.agents/skills/code-task/reference/code-rules.zh-CN.md +4 -0
- package/templates/.agents/skills/complete-manual-validation/SKILL.en.md +0 -1
- package/templates/.agents/skills/complete-manual-validation/SKILL.zh-CN.md +0 -1
- package/templates/.agents/skills/complete-task/SKILL.en.md +5 -29
- package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +5 -26
- package/templates/.agents/skills/plan-task/SKILL.en.md +7 -4
- package/templates/.agents/skills/plan-task/SKILL.zh-CN.md +7 -4
- package/templates/.agents/skills/review-analysis/SKILL.en.md +1 -1
- package/templates/.agents/skills/review-analysis/SKILL.zh-CN.md +1 -1
- package/templates/.agents/skills/review-code/SKILL.en.md +1 -1
- package/templates/.agents/skills/review-code/SKILL.zh-CN.md +1 -1
- package/templates/.agents/skills/review-plan/SKILL.en.md +1 -1
- package/templates/.agents/skills/review-plan/SKILL.zh-CN.md +1 -1
- package/templates/.agents/skills/run-manual-validation/SKILL.en.md +1 -1
- package/templates/.agents/skills/run-manual-validation/SKILL.zh-CN.md +1 -1
- package/templates/.agents/skills/run-task/SKILL.en.md +1 -1
- package/templates/.agents/skills/run-task/SKILL.zh-CN.md +1 -1
- package/dist/lib/agent-clients/adapters/codex-lifecycle/capability-store.js +0 -546
- package/dist/lib/internal/codex-lifecycle.js +0 -385
- package/dist/lib/task/codex-orchestration.js +0 -206
- package/lib/agent-clients/adapters/codex-lifecycle/capability-store.ts +0 -776
- package/lib/internal/codex-lifecycle.ts +0 -390
- package/lib/task/codex-orchestration.ts +0 -276
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { managedDelegationRole } from '../../../task/delegation-receipts.ts';
|
|
2
|
+
|
|
3
|
+
const MARKER_PREFIX = '__agent_infra_binding_';
|
|
4
|
+
const BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';
|
|
5
|
+
const TASK_ID_PATTERN = /^TASK-[0-9]{8}-[0-9]{6}$/u;
|
|
6
|
+
const SAFE_LABEL_PATTERN = /^[a-z0-9_]{1,80}$/u;
|
|
7
|
+
const SAFE_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
|
|
8
|
+
|
|
9
|
+
type CodexLifecycleTaskBinding = Readonly<{
|
|
10
|
+
taskId: string;
|
|
11
|
+
runId: string;
|
|
12
|
+
receiptId: string;
|
|
13
|
+
}>;
|
|
14
|
+
|
|
15
|
+
function assertSafeTaskName(taskName: string): void {
|
|
16
|
+
if (Buffer.byteLength(taskName, 'utf8') > 255 || !/^[a-z0-9_]+$/u.test(taskName)) {
|
|
17
|
+
throw new Error('Codex task_name must use lowercase letters, digits, and underscores within 255 bytes');
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function encodeTaskNamePayload(value: string): string {
|
|
22
|
+
let buffer = 0;
|
|
23
|
+
let bits = 0;
|
|
24
|
+
let encoded = '';
|
|
25
|
+
for (const byte of Buffer.from(value, 'utf8')) {
|
|
26
|
+
buffer = (buffer << 8) | byte;
|
|
27
|
+
bits += 8;
|
|
28
|
+
while (bits >= 5) {
|
|
29
|
+
encoded += BASE32_ALPHABET[(buffer >>> (bits - 5)) & 31];
|
|
30
|
+
bits -= 5;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (bits) encoded += BASE32_ALPHABET[(buffer << (5 - bits)) & 31];
|
|
34
|
+
return encoded;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function decodeTaskNamePayload(encoded: string): string | null {
|
|
38
|
+
let buffer = 0;
|
|
39
|
+
let bits = 0;
|
|
40
|
+
const bytes: number[] = [];
|
|
41
|
+
for (const character of encoded) {
|
|
42
|
+
const value = BASE32_ALPHABET.indexOf(character);
|
|
43
|
+
if (value < 0) return null;
|
|
44
|
+
buffer = (buffer << 5) | value;
|
|
45
|
+
bits += 5;
|
|
46
|
+
if (bits >= 8) {
|
|
47
|
+
bytes.push((buffer >>> (bits - 8)) & 255);
|
|
48
|
+
bits -= 8;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (bits && (buffer & ((1 << bits) - 1)) !== 0) return null;
|
|
52
|
+
const decoded = Buffer.from(bytes).toString('utf8');
|
|
53
|
+
return encodeTaskNamePayload(decoded) === encoded ? decoded : null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function encodeCodexLifecycleBinding(binding: CodexLifecycleTaskBinding): string {
|
|
57
|
+
if (!TASK_ID_PATTERN.test(binding.taskId)
|
|
58
|
+
|| !SAFE_ID_PATTERN.test(binding.runId)
|
|
59
|
+
|| !SAFE_ID_PATTERN.test(binding.receiptId)) {
|
|
60
|
+
throw new Error('Codex lifecycle task binding is invalid');
|
|
61
|
+
}
|
|
62
|
+
return `${MARKER_PREFIX}${encodeTaskNamePayload(JSON.stringify(binding))}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function appendCodexLifecycleBinding(label: string, binding: CodexLifecycleTaskBinding): string {
|
|
66
|
+
if (!SAFE_LABEL_PATTERN.test(label)) throw new Error('Codex task_name label is invalid');
|
|
67
|
+
const taskName = `${label}${encodeCodexLifecycleBinding(binding)}`;
|
|
68
|
+
assertSafeTaskName(taskName);
|
|
69
|
+
return taskName;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseCodexLifecycleBinding(taskName: string): Readonly<{
|
|
73
|
+
taskName: string;
|
|
74
|
+
label: string;
|
|
75
|
+
binding: CodexLifecycleTaskBinding;
|
|
76
|
+
}> | null {
|
|
77
|
+
assertSafeTaskName(taskName);
|
|
78
|
+
const markerIndex = taskName.lastIndexOf(MARKER_PREFIX);
|
|
79
|
+
if (markerIndex < 1) return null;
|
|
80
|
+
const label = taskName.slice(0, markerIndex);
|
|
81
|
+
const encoded = taskName.slice(markerIndex + MARKER_PREFIX.length);
|
|
82
|
+
if (!SAFE_LABEL_PATTERN.test(label) || !/^[a-z2-7]+$/u.test(encoded)) return null;
|
|
83
|
+
try {
|
|
84
|
+
const decoded = decodeTaskNamePayload(encoded);
|
|
85
|
+
if (!decoded) return null;
|
|
86
|
+
const value = JSON.parse(decoded) as Record<string, unknown>;
|
|
87
|
+
if (Object.keys(value).sort().join(',') !== 'receiptId,runId,taskId'
|
|
88
|
+
|| typeof value.taskId !== 'string' || !TASK_ID_PATTERN.test(value.taskId)
|
|
89
|
+
|| typeof value.runId !== 'string' || !SAFE_ID_PATTERN.test(value.runId)
|
|
90
|
+
|| typeof value.receiptId !== 'string' || !SAFE_ID_PATTERN.test(value.receiptId)) return null;
|
|
91
|
+
return Object.freeze({
|
|
92
|
+
taskName,
|
|
93
|
+
label,
|
|
94
|
+
binding: Object.freeze({ taskId: value.taskId, runId: value.runId, receiptId: value.receiptId })
|
|
95
|
+
});
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function verifyCodexLifecycleTaskBinding(
|
|
102
|
+
binding: CodexLifecycleTaskBinding,
|
|
103
|
+
run: Readonly<{ taskId: string; runId: string; status: string; pendingDelegation: Readonly<{
|
|
104
|
+
id: string; taskId: string; runId: string; client: string; role: string; status: string;
|
|
105
|
+
requestedModel: string | null; requestedReasoningEffort: string | null;
|
|
106
|
+
}> | null }>,
|
|
107
|
+
nativeAgent: string,
|
|
108
|
+
expected: Readonly<{ requestedModel?: string; requestedReasoningEffort?: string }> = {}
|
|
109
|
+
): void {
|
|
110
|
+
if (!codexReceiptMatchesBinding(binding, run, nativeAgent, expected)) {
|
|
111
|
+
throw new Error('Codex lifecycle task binding does not match the current pending receipt');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function codexReceiptMatchesBinding(
|
|
116
|
+
binding: CodexLifecycleTaskBinding,
|
|
117
|
+
run: Parameters<typeof verifyCodexLifecycleTaskBinding>[1],
|
|
118
|
+
nativeAgent: string,
|
|
119
|
+
expected: Readonly<{ requestedModel?: string; requestedReasoningEffort?: string }>
|
|
120
|
+
): boolean {
|
|
121
|
+
const receipt = run.pendingDelegation;
|
|
122
|
+
return Boolean(receipt)
|
|
123
|
+
&& run.status === 'running'
|
|
124
|
+
&& run.runId === binding.runId
|
|
125
|
+
&& receipt!.runId === binding.runId
|
|
126
|
+
&& receipt!.id === binding.receiptId
|
|
127
|
+
&& receipt!.client === 'codex'
|
|
128
|
+
&& receipt!.status === 'prepared'
|
|
129
|
+
&& managedDelegationRole(nativeAgent) === receipt!.role
|
|
130
|
+
&& requestedBindingMatches(receipt!, expected);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function requestedBindingMatches(
|
|
134
|
+
receipt: NonNullable<Parameters<typeof verifyCodexLifecycleTaskBinding>[1]['pendingDelegation']>,
|
|
135
|
+
expected: Readonly<{ requestedModel?: string; requestedReasoningEffort?: string }>
|
|
136
|
+
): boolean {
|
|
137
|
+
return (!expected.requestedModel || receipt.requestedModel === expected.requestedModel)
|
|
138
|
+
&& (!expected.requestedReasoningEffort || receipt.requestedReasoningEffort === expected.requestedReasoningEffort);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export {
|
|
142
|
+
appendCodexLifecycleBinding,
|
|
143
|
+
encodeCodexLifecycleBinding,
|
|
144
|
+
parseCodexLifecycleBinding,
|
|
145
|
+
verifyCodexLifecycleTaskBinding
|
|
146
|
+
};
|
|
147
|
+
export type { CodexLifecycleTaskBinding };
|
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
preflightCodexLifecycleEvidence,
|
|
8
|
+
resolveCodexTerminal,
|
|
9
|
+
resolveCodexThread
|
|
10
|
+
} from './app-server.ts';
|
|
11
|
+
import { createCodexLifecycleStore } from './store.ts';
|
|
12
|
+
import { verifyCodexSandboxControllerContextWithWarnings } from './sandbox-controller.ts';
|
|
13
|
+
import type { CodexLifecycleEvent } from './evidence.ts';
|
|
14
|
+
import { resolveTaskRef } from '../../../task/resolve-ref.ts';
|
|
15
|
+
import { resolveTaskContext } from '../../../task/resolve-ref.ts';
|
|
16
|
+
import { hasSealableOrchestrationDelegation, readRun } from '../../../task/orchestration.ts';
|
|
17
|
+
import {
|
|
18
|
+
parseCodexLifecycleBinding,
|
|
19
|
+
verifyCodexLifecycleTaskBinding
|
|
20
|
+
} from './binding.ts';
|
|
21
|
+
import type { CodexLifecycleTaskBinding } from './binding.ts';
|
|
22
|
+
import {
|
|
23
|
+
activateCodexOrchestrationDelegation,
|
|
24
|
+
activateCodexSpawnDelegation,
|
|
25
|
+
reconcileCodexOrchestrationDelegation,
|
|
26
|
+
sealCodexOrchestrationDelegation,
|
|
27
|
+
sealCodexParentDelegation
|
|
28
|
+
} from '../codex-orchestration.ts';
|
|
29
|
+
import { ensureInternalHandlerRoute, internalHandlerRoute } from '../../../internal/cli-route-inventory.ts';
|
|
30
|
+
|
|
31
|
+
const USAGE = 'Usage: agent-infra-internal codex-lifecycle <hook-event|resolve-start|resolve-stop|preflight|consume> [options]\n';
|
|
32
|
+
const MANAGED_AGENT = /^agent-infra-lifecycle-(executor|reviewer)$/;
|
|
33
|
+
|
|
34
|
+
type Parsed = Readonly<{ operation: string; values: Readonly<Record<string, string>> }>;
|
|
35
|
+
type UnresolvedHookChild = Omit<Extract<CodexLifecycleEvent, { type: 'hook-child' }>, 'parentThreadId'>;
|
|
36
|
+
|
|
37
|
+
function output(value: unknown): void {
|
|
38
|
+
process.stdout.write(`${JSON.stringify(value)}\n`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function failure(code: string, message: string): void {
|
|
42
|
+
output({ status: 'failed', changed: false, evidence: null, diagnostics: [], error: { code, message } });
|
|
43
|
+
process.exitCode = 1;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function outputBridgeResult(result: Awaited<ReturnType<typeof activateCodexOrchestrationDelegation>>): void {
|
|
47
|
+
if (result.error?.code === 'ORCHESTRATION_DELEGATION_MISSING') {
|
|
48
|
+
output({ status: 'ignored', changed: false, evidence: null, diagnostics: [], error: null });
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
output(result);
|
|
52
|
+
if (result.status !== 'running') process.exitCode = 1;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parse(args: string[]): Parsed | null {
|
|
56
|
+
if (args[0] === '--help' || args[0] === '-h') {
|
|
57
|
+
process.stdout.write(USAGE);
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
const operation = args[0];
|
|
61
|
+
if (!operation) {
|
|
62
|
+
failure('CODEX_LIFECYCLE_PAYLOAD_INVALID', 'operation is required');
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
const allowed = {
|
|
66
|
+
'hook-event': ['--event', '--bridge'],
|
|
67
|
+
'resolve-start': ['--child-id'],
|
|
68
|
+
'resolve-stop': ['--child-id'],
|
|
69
|
+
preflight: ['--format', '--session-id', '--turn-id', '--tool-use-id'],
|
|
70
|
+
consume: ['--child-id', '--consumer']
|
|
71
|
+
}[operation];
|
|
72
|
+
if (!allowed) {
|
|
73
|
+
failure('CODEX_LIFECYCLE_PAYLOAD_INVALID', 'unknown operation');
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
const values: Record<string, string> = {};
|
|
77
|
+
for (let index = 1; index < args.length; index += 1) {
|
|
78
|
+
const flag = args[index]!;
|
|
79
|
+
if (!allowed.includes(flag) || Object.hasOwn(values, flag)) {
|
|
80
|
+
failure('CODEX_LIFECYCLE_PAYLOAD_INVALID', `invalid or duplicate option '${flag}'`);
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
const value = args[++index];
|
|
84
|
+
if (!value || value.startsWith('--')) {
|
|
85
|
+
failure('CODEX_LIFECYCLE_PAYLOAD_INVALID', `option '${flag}' requires a value`);
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
values[flag] = value;
|
|
89
|
+
}
|
|
90
|
+
return Object.freeze({ operation, values: Object.freeze(values) });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function cliVersion(): string {
|
|
94
|
+
const result = spawnSync('codex', ['--version'], { encoding: 'utf8' });
|
|
95
|
+
const version = /codex-cli\s+(\d+\.\d+\.\d+)/.exec(result.stdout ?? '')?.[1];
|
|
96
|
+
if (result.status !== 0 || !version) throw new Error('Codex CLI version is unavailable');
|
|
97
|
+
return version;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function hookDefinitionHash(): string {
|
|
101
|
+
const file = path.join(process.cwd(), '.codex', 'hooks.json');
|
|
102
|
+
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function resolveLifecycleTaskContext() {
|
|
106
|
+
const controllerPath = process.env.AGENT_INFRA_CODEX_CONTROLLER_CONTEXT;
|
|
107
|
+
const taskId = controllerPath
|
|
108
|
+
? verifyCodexSandboxControllerContextWithWarnings(controllerPath, { repoRoot: process.cwd() }).context.taskId
|
|
109
|
+
: process.env.AGENT_INFRA_TASK_ID;
|
|
110
|
+
const context = taskId
|
|
111
|
+
? resolveTaskRef(taskId, { repoRoot: process.cwd() })
|
|
112
|
+
: resolveTaskContext(undefined, { repoRoot: process.cwd() });
|
|
113
|
+
if (!context.ok) throw new Error(`${context.code}: ${context.message}`);
|
|
114
|
+
return context;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function verifyPendingBinding(
|
|
118
|
+
binding: CodexLifecycleTaskBinding,
|
|
119
|
+
nativeAgent: string,
|
|
120
|
+
expected: Readonly<{ requestedModel?: string; requestedReasoningEffort?: string }> = {}
|
|
121
|
+
) {
|
|
122
|
+
const resolved = resolveLifecycleTaskContext();
|
|
123
|
+
const run = readRun(resolved.taskDir);
|
|
124
|
+
if (!run) throw new Error('Codex lifecycle task binding has no current orchestration run');
|
|
125
|
+
verifyCodexLifecycleTaskBinding(binding, run, nativeAgent, expected);
|
|
126
|
+
return { resolved, run };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function verifyStoredBinding(
|
|
130
|
+
taskId: string,
|
|
131
|
+
binding: CodexLifecycleTaskBinding,
|
|
132
|
+
nativeAgent: string
|
|
133
|
+
): void {
|
|
134
|
+
const resolved = resolveTaskRef(taskId, { repoRoot: process.cwd() });
|
|
135
|
+
if (!resolved.ok) throw new Error(`${resolved.code}: ${resolved.message}`);
|
|
136
|
+
const run = readRun(resolved.taskDir);
|
|
137
|
+
const receipt = run?.pendingDelegation;
|
|
138
|
+
if (!receipt || run?.status !== 'running'
|
|
139
|
+
|| receipt.id !== binding.receiptId
|
|
140
|
+
|| receipt.runId !== binding.runId
|
|
141
|
+
|| receipt.client !== 'codex'
|
|
142
|
+
|| receipt.role !== nativeRole(nativeAgent)) {
|
|
143
|
+
throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISMATCH: stored task receipt is not the current pending lifecycle event');
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function sameTaskBinding(left: CodexLifecycleTaskBinding | null | undefined, right: CodexLifecycleTaskBinding): boolean {
|
|
148
|
+
return left?.runId === right.runId && left.receiptId === right.receiptId;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function nativeRole(nativeAgent: string): string | null {
|
|
152
|
+
const match = /^agent-infra-lifecycle-(executor|reviewer)$/u.exec(nativeAgent);
|
|
153
|
+
return match?.[1] ?? null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function taskScopedStore(taskId: string) {
|
|
157
|
+
return createCodexLifecycleStore({
|
|
158
|
+
repoRoot: process.cwd(),
|
|
159
|
+
taskId,
|
|
160
|
+
cliVersion: cliVersion()
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async function readStdin(): Promise<unknown> {
|
|
165
|
+
let input = '';
|
|
166
|
+
process.stdin.setEncoding('utf8');
|
|
167
|
+
for await (const chunk of process.stdin) {
|
|
168
|
+
input += chunk;
|
|
169
|
+
if (Buffer.byteLength(input) > 64 * 1024) throw new Error('Codex lifecycle input exceeds 64 KiB');
|
|
170
|
+
}
|
|
171
|
+
return JSON.parse(input || '{}') as unknown;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function recordFromPayload(phase: string, payload: unknown, taskBinding?: CodexLifecycleTaskBinding): CodexLifecycleEvent | UnresolvedHookChild | null {
|
|
175
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
176
|
+
throw new Error('Codex lifecycle hook payload must be an object');
|
|
177
|
+
}
|
|
178
|
+
const value = payload as Record<string, unknown>;
|
|
179
|
+
const text = (key: string) => typeof value[key] === 'string' ? value[key] as string : '';
|
|
180
|
+
if (!MANAGED_AGENT.test(text('nativeAgent'))) return null;
|
|
181
|
+
if (phase === 'pre-tool') return {
|
|
182
|
+
type: 'hook-spawn',
|
|
183
|
+
sessionId: text('sessionId'),
|
|
184
|
+
turnId: text('turnId'),
|
|
185
|
+
toolUseId: text('toolUseId'),
|
|
186
|
+
nativeAgent: text('nativeAgent'),
|
|
187
|
+
...(text('requestedModel') ? { requestedModel: text('requestedModel') } : {}),
|
|
188
|
+
...(text('requestedReasoningEffort') ? { requestedReasoningEffort: text('requestedReasoningEffort') } : {}),
|
|
189
|
+
hookDefinitionHash: text('hookDefinitionHash'),
|
|
190
|
+
...(taskBinding ? { taskBinding } : {})
|
|
191
|
+
};
|
|
192
|
+
if (phase === 'subagent-start') return {
|
|
193
|
+
type: 'hook-child',
|
|
194
|
+
sessionId: text('sessionId'),
|
|
195
|
+
turnId: text('turnId'),
|
|
196
|
+
childThreadId: text('childThreadId'),
|
|
197
|
+
nativeAgent: text('nativeAgent'),
|
|
198
|
+
source: 'hook'
|
|
199
|
+
};
|
|
200
|
+
if (phase === 'subagent-stop') return {
|
|
201
|
+
type: 'hook-stop',
|
|
202
|
+
sessionId: text('sessionId'),
|
|
203
|
+
turnId: text('turnId'),
|
|
204
|
+
childThreadId: text('childThreadId'),
|
|
205
|
+
nativeAgent: text('nativeAgent')
|
|
206
|
+
};
|
|
207
|
+
if (phase === 'post-tool') return null;
|
|
208
|
+
throw new Error(`unknown Codex lifecycle hook phase '${phase}'`);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function payloadText(payload: unknown, key: string): string {
|
|
212
|
+
return payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
213
|
+
&& typeof (payload as Record<string, unknown>)[key] === 'string'
|
|
214
|
+
? (payload as Record<string, string>)[key]!
|
|
215
|
+
: '';
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function resolveHookTaskContext(phase: string, toolName: string, payload: unknown) {
|
|
219
|
+
const spawnName = payloadText(payload, 'taskName');
|
|
220
|
+
const needsSpawnBinding = phase === 'pre-tool' || (phase === 'post-tool' && toolName === 'collaborationspawn_agent');
|
|
221
|
+
const spawnBinding = needsSpawnBinding ? parseCodexLifecycleBinding(spawnName) : null;
|
|
222
|
+
if (needsSpawnBinding && !spawnBinding) {
|
|
223
|
+
throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISSING: task_name must carry the prepared task binding');
|
|
224
|
+
}
|
|
225
|
+
const nativeAgent = payloadText(payload, 'nativeAgent');
|
|
226
|
+
const taskContext = spawnBinding
|
|
227
|
+
? verifyPendingBinding(spawnBinding.binding, nativeAgent, {
|
|
228
|
+
requestedModel: payloadText(payload, 'requestedModel') || undefined,
|
|
229
|
+
requestedReasoningEffort: payloadText(payload, 'requestedReasoningEffort') || undefined
|
|
230
|
+
}).resolved
|
|
231
|
+
: resolveLifecycleTaskContext();
|
|
232
|
+
const store = taskScopedStore(taskContext.taskId);
|
|
233
|
+
if (spawnBinding) verifyStoredBinding(taskContext.taskId, spawnBinding.binding, nativeAgent);
|
|
234
|
+
return { spawnBinding, nativeAgent, taskContext, store };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function currentHookTaskBinding(
|
|
238
|
+
taskDir: string,
|
|
239
|
+
taskId: string,
|
|
240
|
+
spawnBinding: ReturnType<typeof parseCodexLifecycleBinding>,
|
|
241
|
+
nativeAgent: string
|
|
242
|
+
) {
|
|
243
|
+
if (!spawnBinding) {
|
|
244
|
+
const run = readRun(taskDir);
|
|
245
|
+
const receipt = run?.pendingDelegation;
|
|
246
|
+
if (!receipt || receipt.client !== 'codex' || receipt.role !== nativeRole(nativeAgent)) {
|
|
247
|
+
throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISMATCH: no matching pending task receipt');
|
|
248
|
+
}
|
|
249
|
+
verifyStoredBinding(taskId, { taskId: receipt.taskId, runId: receipt.runId, receiptId: receipt.id }, nativeAgent);
|
|
250
|
+
}
|
|
251
|
+
const receipt = readRun(taskDir)?.pendingDelegation;
|
|
252
|
+
return receipt && { taskId: receipt.taskId, runId: receipt.runId, receiptId: receipt.id };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function validateHookStopIdentity(
|
|
256
|
+
store: ReturnType<typeof taskScopedStore>,
|
|
257
|
+
event: Extract<CodexLifecycleEvent, { type: 'hook-stop' }>,
|
|
258
|
+
currentBinding: ReturnType<typeof currentHookTaskBinding>
|
|
259
|
+
): void {
|
|
260
|
+
const record = store.read(event.childThreadId);
|
|
261
|
+
const child = record.state.child;
|
|
262
|
+
if (!currentBinding || !sameTaskBinding(record.taskBinding, currentBinding)
|
|
263
|
+
|| !child
|
|
264
|
+
|| child.sessionId !== event.sessionId
|
|
265
|
+
|| child.turnId !== event.turnId
|
|
266
|
+
|| child.childThreadId !== event.childThreadId
|
|
267
|
+
|| child.nativeAgent !== event.nativeAgent) {
|
|
268
|
+
throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISMATCH: stop event does not match the current task receipt and child');
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function matchingHookChildSpawns(
|
|
273
|
+
store: ReturnType<typeof taskScopedStore>,
|
|
274
|
+
binding: ReturnType<typeof currentHookTaskBinding>,
|
|
275
|
+
event: UnresolvedHookChild
|
|
276
|
+
) {
|
|
277
|
+
return binding ? store.findByTaskBinding(binding).filter((record) =>
|
|
278
|
+
record.state.spawn?.sessionId === event.sessionId
|
|
279
|
+
&& record.state.spawn?.nativeAgent === event.nativeAgent
|
|
280
|
+
) : [];
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function applyHookChildEvent(
|
|
284
|
+
event: UnresolvedHookChild,
|
|
285
|
+
currentBinding: NonNullable<ReturnType<typeof currentHookTaskBinding>>,
|
|
286
|
+
taskContext: ReturnType<typeof resolveLifecycleTaskContext>,
|
|
287
|
+
store: ReturnType<typeof taskScopedStore>,
|
|
288
|
+
bridge: boolean,
|
|
289
|
+
resolved?: Awaited<ReturnType<typeof resolveCodexThread>>
|
|
290
|
+
): Promise<void> {
|
|
291
|
+
const candidates = matchingHookChildSpawns(store, currentBinding, event);
|
|
292
|
+
if (candidates.length !== 1) {
|
|
293
|
+
throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISMATCH: child event has no unique spawn for the current task receipt');
|
|
294
|
+
}
|
|
295
|
+
const childResolution = resolved ?? await resolveCodexThread(event.childThreadId);
|
|
296
|
+
verifyStoredBinding(taskContext.taskId, currentBinding, event.nativeAgent);
|
|
297
|
+
const latestCandidates = matchingHookChildSpawns(store, currentBinding, event);
|
|
298
|
+
if (latestCandidates.length !== 1 || latestCandidates[0]!.revision !== candidates[0]!.revision) {
|
|
299
|
+
throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISMATCH: task receipt spawn became ambiguous during child resolution');
|
|
300
|
+
}
|
|
301
|
+
if (childResolution.resolution.thread.childThreadId !== event.childThreadId
|
|
302
|
+
|| childResolution.resolution.thread.parentThreadId !== event.sessionId
|
|
303
|
+
|| childResolution.resolution.thread.nativeAgent !== event.nativeAgent) {
|
|
304
|
+
throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISMATCH: resolved child does not match the current spawn');
|
|
305
|
+
}
|
|
306
|
+
verifyStoredBinding(taskContext.taskId, currentBinding, event.nativeAgent);
|
|
307
|
+
const spawn = latestCandidates[0]!.state.spawn;
|
|
308
|
+
if (!spawn) throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISMATCH: current spawn record is missing');
|
|
309
|
+
const result = store.applyToSpawn({
|
|
310
|
+
sessionId: spawn.sessionId, turnId: spawn.turnId, toolUseId: spawn.toolUseId, taskBinding: currentBinding
|
|
311
|
+
}, { ...event, parentThreadId: childResolution.resolution.thread.parentThreadId }, latestCandidates[0]!.revision);
|
|
312
|
+
if (bridge) {
|
|
313
|
+
outputBridgeResult(await activateCodexOrchestrationDelegation(event.childThreadId, {
|
|
314
|
+
store, orchestrationOptions: { repoRoot: process.cwd(), taskId: taskContext.taskId },
|
|
315
|
+
resolveThread: async () => childResolution
|
|
316
|
+
}));
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
output({ status: result.state.status, changed: true, evidence: result.state, diagnostics: childResolution.diagnostics, error: result.state.error });
|
|
320
|
+
if (result.state.status === 'invalid') process.exitCode = 1;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async function handleBridgePostTool(
|
|
324
|
+
toolName: string,
|
|
325
|
+
payload: unknown,
|
|
326
|
+
nativeAgent: string,
|
|
327
|
+
taskId: string,
|
|
328
|
+
store: ReturnType<typeof taskScopedStore>
|
|
329
|
+
): Promise<void> {
|
|
330
|
+
const orchestrationOptions = { repoRoot: process.cwd(), taskId };
|
|
331
|
+
if (toolName === 'collaborationspawn_agent') {
|
|
332
|
+
if (!MANAGED_AGENT.test(nativeAgent)) {
|
|
333
|
+
output({ status: 'ignored', changed: false, evidence: null, diagnostics: [], error: null });
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const requestedModel = payloadText(payload, 'requestedModel');
|
|
337
|
+
const requestedReasoningEffort = payloadText(payload, 'requestedReasoningEffort');
|
|
338
|
+
const bridged = await activateCodexSpawnDelegation({
|
|
339
|
+
sessionId: payloadText(payload, 'sessionId'), turnId: payloadText(payload, 'turnId'),
|
|
340
|
+
toolUseId: payloadText(payload, 'toolUseId'), transcriptPath: payloadText(payload, 'transcriptPath'),
|
|
341
|
+
nativeAgent, taskName: payloadText(payload, 'taskName'),
|
|
342
|
+
...(requestedModel ? { requestedModel } : {}),
|
|
343
|
+
...(requestedReasoningEffort ? { requestedReasoningEffort } : {})
|
|
344
|
+
}, { store, orchestrationOptions });
|
|
345
|
+
outputBridgeResult(bridged);
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
if (toolName === 'collaborationwait_agent') {
|
|
349
|
+
outputBridgeResult(await sealCodexParentDelegation(payloadText(payload, 'sessionId'), { store, orchestrationOptions }));
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
output({ status: 'ignored', changed: false, evidence: null, diagnostics: [], error: null });
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function sealConsumedHookStop(
|
|
356
|
+
event: Extract<CodexLifecycleEvent, { type: 'hook-stop' }>,
|
|
357
|
+
store: ReturnType<typeof taskScopedStore>,
|
|
358
|
+
taskId: string
|
|
359
|
+
): Promise<void> {
|
|
360
|
+
const result = await sealCodexOrchestrationDelegation(event.childThreadId, {
|
|
361
|
+
store, orchestrationOptions: { repoRoot: process.cwd(), taskId }
|
|
362
|
+
});
|
|
363
|
+
outputBridgeResult(result);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function handleMissingHookEvent(phase: string, bridge: boolean, payload: unknown, taskId: string): void {
|
|
367
|
+
if (phase === 'post-tool' && bridge) {
|
|
368
|
+
const value = payload as Record<string, unknown>;
|
|
369
|
+
outputBridgeResult(reconcileCodexOrchestrationDelegation(String(value.childThreadId ?? ''), {
|
|
370
|
+
orchestrationOptions: { repoRoot: process.cwd(), taskId }
|
|
371
|
+
}));
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
output({ status: 'ignored', changed: false, evidence: null, diagnostics: [], error: null });
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async function handlePreflight(parsed: Parsed): Promise<void> {
|
|
378
|
+
const format = parsed.values['--format'] ?? 'json';
|
|
379
|
+
if (!['text', 'json'].includes(format)) throw new Error("format must be 'text' or 'json'");
|
|
380
|
+
const runtimeFields = [parsed.values['--session-id'], parsed.values['--turn-id'], parsed.values['--tool-use-id']];
|
|
381
|
+
if (runtimeFields.some(Boolean) && !runtimeFields.every(Boolean)) {
|
|
382
|
+
throw new Error('preflight runtime identity requires --session-id, --turn-id, and --tool-use-id together');
|
|
383
|
+
}
|
|
384
|
+
const runtimeIdentity = runtimeFields.every(Boolean)
|
|
385
|
+
? { sessionId: runtimeFields[0]!, turnId: runtimeFields[1]!, toolUseId: runtimeFields[2]! }
|
|
386
|
+
: undefined;
|
|
387
|
+
const result = await preflightCodexLifecycleEvidence(process.cwd(), runtimeIdentity);
|
|
388
|
+
if (format === 'text') {
|
|
389
|
+
process.stdout.write(`Codex lifecycle static preflight: ready\nCLI: ${result.cliVersion}\nRuntime hook liveness: ${result.runtimeLiveness ? 'observed' : 'not-yet-observed'}\n`);
|
|
390
|
+
} else output({ status: 'ready', changed: false, evidence: result, diagnostics: result.diagnostics, error: null });
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
async function codexLifecycle(args: string[] = []): Promise<void> {
|
|
394
|
+
if (!ensureInternalHandlerRoute('codex-lifecycle', args)) return;
|
|
395
|
+
const parsed = parse(args);
|
|
396
|
+
if (!parsed || process.exitCode) return;
|
|
397
|
+
try {
|
|
398
|
+
if (internalHandlerRoute('codex-lifecycle', 'preflight', parsed.operation)) {
|
|
399
|
+
await handlePreflight(parsed);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
if (internalHandlerRoute('codex-lifecycle', 'hook-event', parsed.operation)) {
|
|
404
|
+
const phase = parsed.values['--event'];
|
|
405
|
+
if (!phase || !['pre-tool', 'subagent-start', 'post-tool', 'subagent-stop'].includes(phase)) {
|
|
406
|
+
throw new Error('hook-event requires a known --event');
|
|
407
|
+
}
|
|
408
|
+
if (parsed.values['--bridge'] !== undefined && parsed.values['--bridge'] !== 'true') {
|
|
409
|
+
throw new Error("hook-event --bridge must be 'true'");
|
|
410
|
+
}
|
|
411
|
+
const payload = await readStdin();
|
|
412
|
+
const toolName = payloadText(payload, 'toolName');
|
|
413
|
+
const hookContext = resolveHookTaskContext(phase, toolName, payload);
|
|
414
|
+
const { spawnBinding, nativeAgent, taskContext, store } = hookContext;
|
|
415
|
+
if (phase === 'post-tool' && parsed.values['--bridge'] === 'true') {
|
|
416
|
+
await handleBridgePostTool(toolName, payload, nativeAgent, taskContext.taskId, store);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
const event = recordFromPayload(phase, payload, spawnBinding?.binding);
|
|
420
|
+
if (!event) {
|
|
421
|
+
handleMissingHookEvent(phase, parsed.values['--bridge'] === 'true', payload, taskContext.taskId);
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
const currentBinding = currentHookTaskBinding(taskContext.taskDir, taskContext.taskId, spawnBinding, nativeAgent);
|
|
425
|
+
if (event.type === 'hook-stop') {
|
|
426
|
+
validateHookStopIdentity(store, event, currentBinding);
|
|
427
|
+
}
|
|
428
|
+
if (parsed.values['--bridge'] === 'true' && event.type === 'hook-stop'
|
|
429
|
+
&& store.read(event.childThreadId).consumer) {
|
|
430
|
+
await sealConsumedHookStop(event, store, taskContext.taskId);
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
if (event.type === 'hook-child') {
|
|
434
|
+
await applyHookChildEvent(event, currentBinding!, taskContext, store, parsed.values['--bridge'] === 'true');
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
if (!currentBinding) throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISMATCH: current task receipt is missing');
|
|
438
|
+
verifyStoredBinding(taskContext.taskId, currentBinding, nativeAgent);
|
|
439
|
+
const result = store.apply(event);
|
|
440
|
+
if (parsed.values['--bridge'] === 'true' && event.type === 'hook-stop') {
|
|
441
|
+
if (!hasSealableOrchestrationDelegation('codex', event.childThreadId, { repoRoot: process.cwd(), taskId: taskContext.taskId })) {
|
|
442
|
+
output({ status: 'ignored', changed: false, evidence: null, diagnostics: [], error: null });
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
output({
|
|
446
|
+
status: result.state.status,
|
|
447
|
+
changed: true,
|
|
448
|
+
evidence: result.state,
|
|
449
|
+
diagnostics: [],
|
|
450
|
+
error: result.state.error
|
|
451
|
+
});
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
output({ status: result.state.status, changed: true, evidence: result.state, diagnostics: [], error: result.state.error });
|
|
455
|
+
if (result.state.status === 'invalid') process.exitCode = 1;
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const childThreadId = parsed.values['--child-id'];
|
|
460
|
+
if (!childThreadId) throw new Error(`operation '${parsed.operation}' requires --child-id`);
|
|
461
|
+
const taskContext = resolveLifecycleTaskContext();
|
|
462
|
+
const store = taskScopedStore(taskContext.taskId);
|
|
463
|
+
const existing = store.read(childThreadId);
|
|
464
|
+
if (!existing.taskBinding) throw new Error('CODEX_LIFECYCLE_TASK_BINDING_MISSING: stored lifecycle identity has no task binding');
|
|
465
|
+
verifyStoredBinding(
|
|
466
|
+
taskContext.taskId,
|
|
467
|
+
existing.taskBinding,
|
|
468
|
+
existing.state.startEvidence?.nativeAgent ?? existing.state.spawn?.nativeAgent ?? ''
|
|
469
|
+
);
|
|
470
|
+
if (internalHandlerRoute('codex-lifecycle', 'resolve-start', parsed.operation)) {
|
|
471
|
+
if (store.read(childThreadId).state.spawn?.hookDefinitionHash !== hookDefinitionHash()) {
|
|
472
|
+
throw new Error('Codex lifecycle hook definition hash is stale');
|
|
473
|
+
}
|
|
474
|
+
const resolved = await resolveCodexThread(childThreadId);
|
|
475
|
+
verifyStoredBinding(taskContext.taskId, existing.taskBinding, existing.state.startEvidence?.nativeAgent ?? existing.state.spawn?.nativeAgent ?? '');
|
|
476
|
+
let latest = store.apply(resolved.resolution.thread);
|
|
477
|
+
for (const reroute of resolved.reroutes) latest = store.apply(reroute);
|
|
478
|
+
latest = store.apply(resolved.resolution.settings);
|
|
479
|
+
output({ status: latest.state.status, changed: true, evidence: latest.state.startEvidence, diagnostics: resolved.diagnostics, error: latest.state.error });
|
|
480
|
+
if (latest.state.status !== 'start-ready') process.exitCode = 1;
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
if (internalHandlerRoute('codex-lifecycle', 'resolve-stop', parsed.operation)) {
|
|
484
|
+
const stopTurnId = store.read(childThreadId).state.stop?.turnId;
|
|
485
|
+
if (!stopTurnId) throw new Error('Codex lifecycle stop hook is not available');
|
|
486
|
+
const terminal = await resolveCodexTerminal(childThreadId, stopTurnId);
|
|
487
|
+
verifyStoredBinding(taskContext.taskId, existing.taskBinding, existing.state.startEvidence?.nativeAgent ?? existing.state.spawn?.nativeAgent ?? '');
|
|
488
|
+
const latest = store.apply(terminal);
|
|
489
|
+
if (latest.state.status !== 'stop-ready') {
|
|
490
|
+
throw new Error(`Codex lifecycle stop evidence is not ready (status=${latest.state.status})`);
|
|
491
|
+
}
|
|
492
|
+
output({ status: latest.state.status, changed: true, evidence: latest.state.stopEvidence, diagnostics: [], error: latest.state.error });
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
if (internalHandlerRoute('codex-lifecycle', 'consume', parsed.operation)) {
|
|
496
|
+
const consumer = parsed.values['--consumer'];
|
|
497
|
+
if (!consumer) throw new Error('consume requires --consumer');
|
|
498
|
+
verifyStoredBinding(taskContext.taskId, existing.taskBinding, existing.state.startEvidence?.nativeAgent ?? existing.state.spawn?.nativeAgent ?? '');
|
|
499
|
+
const consumed = store.consume(childThreadId, consumer, hookDefinitionHash());
|
|
500
|
+
output({ status: 'consumed', changed: true, evidence: {
|
|
501
|
+
start: consumed.state.startEvidence,
|
|
502
|
+
stop: consumed.state.stopEvidence
|
|
503
|
+
}, diagnostics: [], error: null });
|
|
504
|
+
}
|
|
505
|
+
} catch (error) {
|
|
506
|
+
failure('CODEX_LIFECYCLE_FAILED', error instanceof Error ? error.message : String(error));
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
export { codexLifecycle };
|