@fitlab-ai/agent-infra 0.9.4 → 0.9.5
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/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/dist/bin/internal-cli.js +10 -0
- package/dist/lib/agent-clients/adapter.js +2 -2
- package/dist/lib/agent-clients/adapters/codex-lifecycle/app-server.js +382 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/evidence.js +163 -0
- package/dist/lib/agent-clients/adapters/codex-lifecycle/store.js +211 -0
- package/dist/lib/agent-clients/adapters/codex.js +2 -2
- package/dist/lib/git/worktree-identity.js +64 -0
- package/dist/lib/internal/codex-lifecycle.js +202 -0
- package/dist/lib/internal/task-create.js +48 -0
- package/dist/lib/internal/task-orchestration.js +68 -29
- package/dist/lib/sandbox/commands/create.js +1 -0
- package/dist/lib/sandbox/control/client.js +29 -15
- package/dist/lib/sandbox/control/protocol.js +23 -4
- package/dist/lib/sandbox/control/server.js +53 -18
- package/dist/lib/sandbox/workspace-view.js +8 -2
- package/dist/lib/task/activity-log.js +32 -5
- package/dist/lib/task/commit-finalization.js +14 -3
- package/dist/lib/task/create-service.js +137 -0
- package/dist/lib/task/create.js +333 -0
- package/dist/lib/task/orchestration.js +151 -15
- package/dist/lib/task/review-fingerprint.js +4 -0
- package/dist/lib/task/workspace-snapshot.js +78 -3
- package/lib/agent-clients/adapter.ts +4 -4
- package/lib/agent-clients/adapters/codex-lifecycle/app-server.ts +442 -0
- package/lib/agent-clients/adapters/codex-lifecycle/evidence.ts +307 -0
- package/lib/agent-clients/adapters/codex-lifecycle/store.ts +250 -0
- package/lib/agent-clients/adapters/codex.ts +2 -2
- package/lib/git/worktree-identity.ts +86 -0
- package/lib/internal/codex-lifecycle.ts +204 -0
- package/lib/internal/task-create.ts +49 -0
- package/lib/internal/task-orchestration.ts +54 -28
- package/lib/sandbox/commands/create.ts +1 -0
- package/lib/sandbox/control/client.ts +42 -18
- package/lib/sandbox/control/protocol.ts +43 -8
- package/lib/sandbox/control/server.ts +60 -22
- package/lib/sandbox/workspace-view.ts +9 -2
- package/lib/task/activity-log.ts +46 -7
- package/lib/task/commit-finalization.ts +23 -3
- package/lib/task/create-service.ts +171 -0
- package/lib/task/create.ts +372 -0
- package/lib/task/orchestration.ts +182 -18
- package/lib/task/review-fingerprint.ts +9 -0
- package/lib/task/workspace-snapshot.ts +98 -4
- package/package.json +7 -7
- package/templates/.agents/hooks/lifecycle-delegation.js +47 -3
- package/templates/.agents/rules/task-management.en.md +1 -0
- package/templates/.agents/rules/task-management.zh-CN.md +1 -0
- package/templates/.agents/skills/commit/SKILL.en.md +3 -9
- package/templates/.agents/skills/commit/SKILL.zh-CN.md +6 -10
- package/templates/.agents/skills/commit/reference/commit-orchestration.en.md +4 -3
- package/templates/.agents/skills/commit/reference/commit-orchestration.zh-CN.md +5 -4
- package/templates/.agents/skills/create-task/SKILL.en.md +26 -43
- package/templates/.agents/skills/create-task/SKILL.zh-CN.md +26 -43
- package/templates/.codex/hooks.json +50 -0
package/README.md
CHANGED
|
@@ -176,7 +176,7 @@ The most-used lifecycle commands, in delivery order. The command prefix varies b
|
|
|
176
176
|
| Command | Purpose |
|
|
177
177
|
|---------|---------|
|
|
178
178
|
| `create-task` / `import-issue` | Start a task from a description or a GitHub Issue |
|
|
179
|
-
| `run-task` | Resume the lifecycle with fresh isolated executors/reviewers when the selected client exposes verified actual model/effort evidence;
|
|
179
|
+
| `run-task` | Resume the lifecycle with fresh isolated executors/reviewers when the selected client exposes verified actual model/effort evidence; Codex now has an experimental Hooks + App Server evidence channel, but orchestration remains disabled until that channel is connected to delegation receipts |
|
|
180
180
|
| `analyze-task` → `review-analysis` | Capture scope and risks, then review the analysis |
|
|
181
181
|
| `plan-task` → `review-plan` | Design the approach, then review the plan |
|
|
182
182
|
| `code-task` → `review-code` | Implement and test, then run a structured code review |
|
package/README.zh-CN.md
CHANGED
|
@@ -175,7 +175,7 @@ ai agent-client configure
|
|
|
175
175
|
| 命令 | 用途 |
|
|
176
176
|
|------|------|
|
|
177
177
|
| `create-task` / `import-issue` | 从描述或 GitHub Issue 创建任务 |
|
|
178
|
-
| `run-task` | 当所选客户端能提供已验证的 actual model/effort 证据时,用 fresh 隔离 executor/reviewer
|
|
178
|
+
| `run-task` | 当所选客户端能提供已验证的 actual model/effort 证据时,用 fresh 隔离 executor/reviewer 续跑生命周期;Codex 现已具备实验性的 Hooks + App Server 证据通道,但在该通道接入 delegation receipt 前仍不会启用 orchestration |
|
|
179
179
|
| `analyze-task` → `review-analysis` | 明确范围与风险,再审查分析 |
|
|
180
180
|
| `plan-task` → `review-plan` | 设计实现路径,再审查方案 |
|
|
181
181
|
| `code-task` → `review-code` | 实现并测试,再执行结构化代码审查 |
|
package/dist/bin/internal-cli.js
CHANGED
|
@@ -12,6 +12,11 @@ if (process.env.AGENT_INFRA_CONTROL_TOKEN
|
|
|
12
12
|
}
|
|
13
13
|
else
|
|
14
14
|
switch (command) {
|
|
15
|
+
case 'task-create': {
|
|
16
|
+
const { taskCreate } = await import('../lib/internal/task-create.js');
|
|
17
|
+
taskCreate(process.argv.slice(3));
|
|
18
|
+
break;
|
|
19
|
+
}
|
|
15
20
|
case 'sandbox-control': {
|
|
16
21
|
const { sandboxControl } = await import('../lib/internal/sandbox-control.js');
|
|
17
22
|
sandboxControl(process.argv.slice(3));
|
|
@@ -22,6 +27,11 @@ else
|
|
|
22
27
|
agentClient(process.argv.slice(3));
|
|
23
28
|
break;
|
|
24
29
|
}
|
|
30
|
+
case 'codex-lifecycle': {
|
|
31
|
+
const { codexLifecycle } = await import('../lib/internal/codex-lifecycle.js');
|
|
32
|
+
await codexLifecycle(process.argv.slice(3));
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
25
35
|
case 'git-workflow': {
|
|
26
36
|
const { gitWorkflow } = await import('../lib/internal/git-workflow.js');
|
|
27
37
|
gitWorkflow(process.argv.slice(3));
|
|
@@ -190,8 +190,8 @@ function defineAgentClientAdapter(candidate) {
|
|
|
190
190
|
}
|
|
191
191
|
const evidence = candidate.delegationEvidence;
|
|
192
192
|
if (!evidence
|
|
193
|
-
|| !['host-event', 'unavailable'].includes(evidence.actualModel)
|
|
194
|
-
|| !['host-event', 'spawn-ack', 'unavailable'].includes(evidence.actualReasoningEffort)) {
|
|
193
|
+
|| !['host-event', 'app-server', 'unavailable'].includes(evidence.actualModel)
|
|
194
|
+
|| !['host-event', 'app-server', 'spawn-ack', 'unavailable'].includes(evidence.actualReasoningEffort)) {
|
|
195
195
|
throw new Error(`Agent Client '${candidate.id}' has invalid delegation evidence`);
|
|
196
196
|
}
|
|
197
197
|
if (typeof candidate.project !== 'object'
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import semver from 'semver';
|
|
7
|
+
const LIFECYCLE_HOOKS = Object.freeze([
|
|
8
|
+
Object.freeze({ event: 'PreToolUse', matcher: '^collaborationspawn_agent$', phase: 'pre-tool' }),
|
|
9
|
+
Object.freeze({ event: 'PostToolUse', matcher: '^collaborationspawn_agent$', phase: 'post-tool' }),
|
|
10
|
+
Object.freeze({ event: 'SubagentStart', matcher: '^agent-infra-lifecycle-(executor|reviewer)$', phase: 'subagent-start' }),
|
|
11
|
+
Object.freeze({ event: 'SubagentStop', matcher: '^agent-infra-lifecycle-(executor|reviewer)$', phase: 'subagent-stop' })
|
|
12
|
+
]);
|
|
13
|
+
function object(value) {
|
|
14
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
15
|
+
? value
|
|
16
|
+
: null;
|
|
17
|
+
}
|
|
18
|
+
function nonEmpty(value) {
|
|
19
|
+
return typeof value === 'string' && value.trim() ? value : null;
|
|
20
|
+
}
|
|
21
|
+
function validateCodexLifecycleHookConfig(value) {
|
|
22
|
+
const hooks = object(object(value)?.hooks);
|
|
23
|
+
const valid = hooks && LIFECYCLE_HOOKS.every(({ event, matcher, phase }) => {
|
|
24
|
+
const entries = hooks[event];
|
|
25
|
+
if (!Array.isArray(entries))
|
|
26
|
+
return false;
|
|
27
|
+
return entries.some((entryValue) => {
|
|
28
|
+
const entry = object(entryValue);
|
|
29
|
+
if (entry?.matcher !== matcher || !Array.isArray(entry.hooks))
|
|
30
|
+
return false;
|
|
31
|
+
return entry.hooks.some((hookValue) => {
|
|
32
|
+
const hook = object(hookValue);
|
|
33
|
+
return hook?.type === 'command'
|
|
34
|
+
&& hook.timeout === 5
|
|
35
|
+
&& hook.command === `node "$(git rev-parse --show-toplevel)/.agents/hooks/lifecycle-delegation.js" --client codex --event ${phase}`;
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
if (!valid)
|
|
40
|
+
throw new Error('CODEX_PREFLIGHT_HOOKS_INVALID: lifecycle hooks are invalid');
|
|
41
|
+
}
|
|
42
|
+
function parseCodexHooksList(value, repoRoot) {
|
|
43
|
+
const root = object(value);
|
|
44
|
+
const entries = Array.isArray(root?.data) ? root.data : [];
|
|
45
|
+
const entry = entries.map(object).find((candidate) => candidate?.cwd === repoRoot);
|
|
46
|
+
const errors = Array.isArray(entry?.errors) ? entry.errors : [];
|
|
47
|
+
if (errors.length)
|
|
48
|
+
throw new Error(`CODEX_PREFLIGHT_HOOK_DISCOVERY_FAILED: ${errors.map(String).join('; ')}`);
|
|
49
|
+
const hooks = (Array.isArray(entry?.hooks) ? entry.hooks : [])
|
|
50
|
+
.map(object)
|
|
51
|
+
.filter((hook) => hook !== null)
|
|
52
|
+
.map((hook) => Object.freeze({
|
|
53
|
+
eventName: String(hook.eventName ?? ''),
|
|
54
|
+
matcher: typeof hook.matcher === 'string' ? hook.matcher : null,
|
|
55
|
+
command: String(hook.command ?? ''),
|
|
56
|
+
enabled: hook.enabled === true
|
|
57
|
+
}));
|
|
58
|
+
const valid = LIFECYCLE_HOOKS.every(({ event, matcher, phase }) => hooks.some((hook) => hook.eventName === event.replace(/^./, (character) => character.toLowerCase())
|
|
59
|
+
&& hook.matcher === matcher
|
|
60
|
+
&& hook.command === `node "$(git rev-parse --show-toplevel)/.agents/hooks/lifecycle-delegation.js" --client codex --event ${phase}`
|
|
61
|
+
&& hook.enabled));
|
|
62
|
+
if (!valid)
|
|
63
|
+
throw new Error('CODEX_PREFLIGHT_HOOKS_NOT_LOADED: lifecycle hooks are not loaded for this workspace');
|
|
64
|
+
return Object.freeze(hooks);
|
|
65
|
+
}
|
|
66
|
+
function hasCodexRuntimeLiveness(runtimeRoot, hookDefinitionHash, identity) {
|
|
67
|
+
if (!identity || !fs.existsSync(runtimeRoot))
|
|
68
|
+
return false;
|
|
69
|
+
return fs.readdirSync(runtimeRoot)
|
|
70
|
+
.filter((name) => /^[a-f0-9]{64}\.json$/.test(name))
|
|
71
|
+
.some((name) => {
|
|
72
|
+
try {
|
|
73
|
+
const record = object(JSON.parse(fs.readFileSync(path.join(runtimeRoot, name), 'utf8')));
|
|
74
|
+
const state = object(record?.state);
|
|
75
|
+
const spawnEvent = object(state?.spawn);
|
|
76
|
+
return !['invalid', 'expired'].includes(String(state?.status))
|
|
77
|
+
&& spawnEvent?.hookDefinitionHash === hookDefinitionHash
|
|
78
|
+
&& spawnEvent.sessionId === identity.sessionId
|
|
79
|
+
&& spawnEvent.turnId === identity.turnId
|
|
80
|
+
&& spawnEvent.toolUseId === identity.toolUseId;
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
function parseCodexThreadResolution(readValue, resumeValue) {
|
|
88
|
+
const readRoot = object(readValue);
|
|
89
|
+
const resumeRoot = object(resumeValue);
|
|
90
|
+
const thread = object(readRoot?.thread);
|
|
91
|
+
const resumedThread = object(resumeRoot?.thread);
|
|
92
|
+
const source = object(thread?.source);
|
|
93
|
+
const subAgent = object(source?.subAgent);
|
|
94
|
+
const threadSpawn = object(subAgent?.thread_spawn);
|
|
95
|
+
const childThreadId = nonEmpty(thread?.id);
|
|
96
|
+
const parentThreadId = nonEmpty(thread?.parentThreadId);
|
|
97
|
+
const sourceParentThreadId = nonEmpty(threadSpawn?.parent_thread_id);
|
|
98
|
+
const resumedChildThreadId = nonEmpty(resumedThread?.id);
|
|
99
|
+
const model = nonEmpty(resumeRoot?.model);
|
|
100
|
+
const reasoningEffort = nonEmpty(resumeRoot?.reasoningEffort ?? object(resumeRoot?.settings)?.effort);
|
|
101
|
+
const forkedFromId = thread?.forkedFromId;
|
|
102
|
+
if (!childThreadId
|
|
103
|
+
|| resumedChildThreadId !== childThreadId
|
|
104
|
+
|| !parentThreadId
|
|
105
|
+
|| !sourceParentThreadId
|
|
106
|
+
|| !model
|
|
107
|
+
|| !reasoningEffort
|
|
108
|
+
|| (forkedFromId !== null && typeof forkedFromId !== 'string')) {
|
|
109
|
+
throw new Error('Codex App Server thread resolution is invalid');
|
|
110
|
+
}
|
|
111
|
+
return Object.freeze({
|
|
112
|
+
thread: Object.freeze({
|
|
113
|
+
type: 'app-thread',
|
|
114
|
+
childThreadId,
|
|
115
|
+
parentThreadId,
|
|
116
|
+
forkedFromId,
|
|
117
|
+
sourceParentThreadId
|
|
118
|
+
}),
|
|
119
|
+
settings: Object.freeze({
|
|
120
|
+
type: 'app-settings',
|
|
121
|
+
childThreadId,
|
|
122
|
+
model,
|
|
123
|
+
reasoningEffort
|
|
124
|
+
})
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
function parseCodexTurnCompleted(value) {
|
|
128
|
+
const root = object(value);
|
|
129
|
+
const turn = object(root?.turn);
|
|
130
|
+
const childThreadId = nonEmpty(root?.threadId);
|
|
131
|
+
const turnId = nonEmpty(turn?.id);
|
|
132
|
+
const status = turn?.status;
|
|
133
|
+
if (!childThreadId || !turnId || !['completed', 'interrupted', 'failed'].includes(String(status))) {
|
|
134
|
+
throw new Error('Codex App Server turn completion is invalid');
|
|
135
|
+
}
|
|
136
|
+
return Object.freeze({
|
|
137
|
+
type: 'app-terminal',
|
|
138
|
+
childThreadId,
|
|
139
|
+
turnId,
|
|
140
|
+
status: status
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function parseCodexModelReroute(value) {
|
|
144
|
+
const root = object(value);
|
|
145
|
+
const childThreadId = nonEmpty(root?.threadId);
|
|
146
|
+
const turnId = nonEmpty(root?.turnId);
|
|
147
|
+
const fromModel = nonEmpty(root?.fromModel);
|
|
148
|
+
const toModel = nonEmpty(root?.toModel);
|
|
149
|
+
const reasonValue = root?.reason;
|
|
150
|
+
const reason = nonEmpty(reasonValue) ?? (object(reasonValue) ? JSON.stringify(reasonValue) : null);
|
|
151
|
+
if (!childThreadId || !turnId || !fromModel || !toModel || !reason) {
|
|
152
|
+
throw new Error('Codex App Server model reroute is invalid');
|
|
153
|
+
}
|
|
154
|
+
return Object.freeze({ type: 'app-reroute', childThreadId, turnId, fromModel, toModel, reason });
|
|
155
|
+
}
|
|
156
|
+
class CodexAppServerTransport {
|
|
157
|
+
#options;
|
|
158
|
+
#child = null;
|
|
159
|
+
#buffer = '';
|
|
160
|
+
#stderr = '';
|
|
161
|
+
#nextId = 1;
|
|
162
|
+
#pending = new Map();
|
|
163
|
+
#notifications = [];
|
|
164
|
+
constructor(options = {}) {
|
|
165
|
+
this.#options = {
|
|
166
|
+
...options,
|
|
167
|
+
command: options.command ?? 'codex',
|
|
168
|
+
args: options.args ?? ['app-server', '--stdio'],
|
|
169
|
+
timeoutMs: options.timeoutMs ?? 5_000
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
get diagnostics() {
|
|
173
|
+
return Object.freeze(this.#stderr.split(/\r?\n/).filter(Boolean));
|
|
174
|
+
}
|
|
175
|
+
get notifications() {
|
|
176
|
+
return Object.freeze([...this.#notifications]);
|
|
177
|
+
}
|
|
178
|
+
start() {
|
|
179
|
+
if (this.#child)
|
|
180
|
+
throw new Error('Codex App Server transport is already started');
|
|
181
|
+
const child = spawn(this.#options.command, [...this.#options.args], {
|
|
182
|
+
cwd: this.#options.cwd,
|
|
183
|
+
env: this.#options.env,
|
|
184
|
+
stdio: ['pipe', 'pipe', 'pipe']
|
|
185
|
+
});
|
|
186
|
+
this.#child = child;
|
|
187
|
+
child.stdout.setEncoding('utf8');
|
|
188
|
+
child.stderr.setEncoding('utf8');
|
|
189
|
+
child.stdout.on('data', (chunk) => this.#onData(chunk));
|
|
190
|
+
child.stderr.on('data', (chunk) => {
|
|
191
|
+
this.#stderr = `${this.#stderr}${chunk}`.slice(-32 * 1024);
|
|
192
|
+
});
|
|
193
|
+
child.on('error', (error) => this.#rejectAll(error));
|
|
194
|
+
child.on('exit', (code, signal) => {
|
|
195
|
+
if (this.#pending.size) {
|
|
196
|
+
this.#rejectAll(new Error(`Codex App Server exited before responding (code=${code}, signal=${signal})`));
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
#onData(chunk) {
|
|
201
|
+
this.#buffer += chunk;
|
|
202
|
+
for (;;) {
|
|
203
|
+
const newline = this.#buffer.indexOf('\n');
|
|
204
|
+
if (newline < 0)
|
|
205
|
+
return;
|
|
206
|
+
const line = this.#buffer.slice(0, newline).trim();
|
|
207
|
+
this.#buffer = this.#buffer.slice(newline + 1);
|
|
208
|
+
if (!line)
|
|
209
|
+
continue;
|
|
210
|
+
let message;
|
|
211
|
+
try {
|
|
212
|
+
const parsed = object(JSON.parse(line));
|
|
213
|
+
if (!parsed)
|
|
214
|
+
throw new Error('message is not an object');
|
|
215
|
+
message = parsed;
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
this.#rejectAll(new Error(`Codex App Server returned invalid JSON: ${String(error)}`));
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (typeof message.id === 'number') {
|
|
222
|
+
const pending = this.#pending.get(message.id);
|
|
223
|
+
if (!pending)
|
|
224
|
+
continue;
|
|
225
|
+
clearTimeout(pending.timer);
|
|
226
|
+
this.#pending.delete(message.id);
|
|
227
|
+
if (message.error)
|
|
228
|
+
pending.reject(new Error(`Codex App Server request failed: ${JSON.stringify(message.error)}`));
|
|
229
|
+
else
|
|
230
|
+
pending.resolve(message.result);
|
|
231
|
+
}
|
|
232
|
+
else if (typeof message.method === 'string') {
|
|
233
|
+
this.#notifications.push(Object.freeze({ method: message.method, params: message.params }));
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
#rejectAll(error) {
|
|
238
|
+
for (const [id, pending] of this.#pending) {
|
|
239
|
+
clearTimeout(pending.timer);
|
|
240
|
+
this.#pending.delete(id);
|
|
241
|
+
pending.reject(error);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
request(method, params) {
|
|
245
|
+
if (!this.#child || !this.#child.stdin.writable) {
|
|
246
|
+
return Promise.reject(new Error('Codex App Server transport is not running'));
|
|
247
|
+
}
|
|
248
|
+
const id = this.#nextId++;
|
|
249
|
+
return new Promise((resolve, reject) => {
|
|
250
|
+
const timer = setTimeout(() => {
|
|
251
|
+
this.#pending.delete(id);
|
|
252
|
+
reject(new Error(`Codex App Server request '${method}' timed out`));
|
|
253
|
+
}, this.#options.timeoutMs);
|
|
254
|
+
this.#pending.set(id, { resolve, reject, timer });
|
|
255
|
+
this.#child.stdin.write(`${JSON.stringify({ id, method, params })}\n`);
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
notify(method, params = {}) {
|
|
259
|
+
if (!this.#child || !this.#child.stdin.writable)
|
|
260
|
+
throw new Error('Codex App Server transport is not running');
|
|
261
|
+
this.#child.stdin.write(`${JSON.stringify({ method, params })}\n`);
|
|
262
|
+
}
|
|
263
|
+
async initialize() {
|
|
264
|
+
const result = await this.request('initialize', {
|
|
265
|
+
clientInfo: { name: 'agent-infra', title: 'agent-infra', version: '0.9.5' },
|
|
266
|
+
capabilities: null
|
|
267
|
+
});
|
|
268
|
+
this.notify('initialized');
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
271
|
+
close() {
|
|
272
|
+
if (!this.#child)
|
|
273
|
+
return;
|
|
274
|
+
this.#child.stdin.end();
|
|
275
|
+
this.#child.kill();
|
|
276
|
+
this.#child = null;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
async function resolveCodexThread(childThreadId, options = {}) {
|
|
280
|
+
if (!nonEmpty(childThreadId))
|
|
281
|
+
throw new Error('Codex child thread id is required');
|
|
282
|
+
const transport = new CodexAppServerTransport(options);
|
|
283
|
+
transport.start();
|
|
284
|
+
try {
|
|
285
|
+
await transport.initialize();
|
|
286
|
+
const readResult = object(await transport.request('thread/read', { threadId: childThreadId, includeTurns: false }));
|
|
287
|
+
const readThread = object(readResult?.thread);
|
|
288
|
+
if (nonEmpty(readThread?.id) !== childThreadId)
|
|
289
|
+
throw new Error('Codex App Server returned the wrong child thread');
|
|
290
|
+
const resumeResult = await transport.request('thread/resume', { threadId: childThreadId });
|
|
291
|
+
let resolution;
|
|
292
|
+
try {
|
|
293
|
+
resolution = parseCodexThreadResolution(readResult, resumeResult);
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
throw new Error('Codex App Server resumed settings are unavailable');
|
|
297
|
+
}
|
|
298
|
+
const reroutes = transport.notifications
|
|
299
|
+
.filter((entry) => entry.method === 'model/rerouted')
|
|
300
|
+
.map((entry) => parseCodexModelReroute(entry.params))
|
|
301
|
+
.filter((event) => event.childThreadId === childThreadId);
|
|
302
|
+
return Object.freeze({ resolution, reroutes: Object.freeze(reroutes), diagnostics: transport.diagnostics });
|
|
303
|
+
}
|
|
304
|
+
finally {
|
|
305
|
+
try {
|
|
306
|
+
await transport.request('thread/unsubscribe', { threadId: childThreadId });
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
// Closing the short-lived transport still removes the subscription.
|
|
310
|
+
}
|
|
311
|
+
transport.close();
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
async function resolveCodexTerminal(childThreadId, options = {}) {
|
|
315
|
+
const transport = new CodexAppServerTransport(options);
|
|
316
|
+
transport.start();
|
|
317
|
+
try {
|
|
318
|
+
await transport.initialize();
|
|
319
|
+
const result = object(await transport.request('thread/read', { threadId: childThreadId, includeTurns: true }));
|
|
320
|
+
const thread = object(result?.thread);
|
|
321
|
+
if (nonEmpty(thread?.id) !== childThreadId)
|
|
322
|
+
throw new Error('Codex App Server returned the wrong child thread');
|
|
323
|
+
const turns = Array.isArray(thread?.turns) ? thread.turns : [];
|
|
324
|
+
const turn = turns.at(-1);
|
|
325
|
+
return parseCodexTurnCompleted({ threadId: childThreadId, turn });
|
|
326
|
+
}
|
|
327
|
+
finally {
|
|
328
|
+
transport.close();
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
async function preflightCodexLifecycleEvidence(repoRoot = process.cwd(), runtimeIdentity) {
|
|
332
|
+
const versionRun = spawnSync('codex', ['--version'], { encoding: 'utf8' });
|
|
333
|
+
const match = /codex-cli\s+(\d+\.\d+\.\d+)/.exec(versionRun.stdout ?? '');
|
|
334
|
+
if (versionRun.status !== 0 || !match?.[1] || !semver.gte(match[1], '0.147.0')) {
|
|
335
|
+
throw new Error('CODEX_PREFLIGHT_VERSION_UNSUPPORTED');
|
|
336
|
+
}
|
|
337
|
+
const featuresRun = spawnSync('codex', ['features', 'list'], { encoding: 'utf8' });
|
|
338
|
+
if (featuresRun.status !== 0
|
|
339
|
+
|| !/^hooks\s+\S+\s+true$/m.test(featuresRun.stdout)
|
|
340
|
+
|| !/^multi_agent\s+\S+\s+true$/m.test(featuresRun.stdout))
|
|
341
|
+
throw new Error('CODEX_PREFLIGHT_FEATURE_DISABLED');
|
|
342
|
+
const hooksPath = path.join(repoRoot, '.codex', 'hooks.json');
|
|
343
|
+
const hooksRaw = fs.readFileSync(hooksPath, 'utf8');
|
|
344
|
+
validateCodexLifecycleHookConfig(JSON.parse(hooksRaw));
|
|
345
|
+
const schemaDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-infra-codex-schema-'));
|
|
346
|
+
try {
|
|
347
|
+
const schemaRun = spawnSync('codex', ['app-server', 'generate-json-schema', '--out', schemaDir], { encoding: 'utf8' });
|
|
348
|
+
if (schemaRun.status !== 0)
|
|
349
|
+
throw new Error('CODEX_PREFLIGHT_SCHEMA_UNAVAILABLE');
|
|
350
|
+
const schema = fs.readFileSync(path.join(schemaDir, 'codex_app_server_protocol.v2.schemas.json'), 'utf8');
|
|
351
|
+
for (const field of ['parentThreadId', 'forkedFromId', 'ThreadSettings', 'turn/completed', 'model/rerouted']) {
|
|
352
|
+
if (!schema.includes(field))
|
|
353
|
+
throw new Error(`CODEX_PREFLIGHT_SCHEMA_MISSING:${field}`);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
finally {
|
|
357
|
+
fs.rmSync(schemaDir, { recursive: true, force: true });
|
|
358
|
+
}
|
|
359
|
+
const hookDefinitionHash = crypto.createHash('sha256').update(hooksRaw).digest('hex');
|
|
360
|
+
const runtimeRoot = path.join(repoRoot, '.agents', 'workspace', '.runtime', 'codex-lifecycle');
|
|
361
|
+
const runtimeLiveness = hasCodexRuntimeLiveness(runtimeRoot, hookDefinitionHash, runtimeIdentity);
|
|
362
|
+
const transport = new CodexAppServerTransport();
|
|
363
|
+
transport.start();
|
|
364
|
+
let discoveredHooks;
|
|
365
|
+
try {
|
|
366
|
+
await transport.initialize();
|
|
367
|
+
discoveredHooks = parseCodexHooksList(await transport.request('hooks/list', { cwds: [repoRoot] }), repoRoot);
|
|
368
|
+
}
|
|
369
|
+
finally {
|
|
370
|
+
transport.close();
|
|
371
|
+
}
|
|
372
|
+
return Object.freeze({
|
|
373
|
+
cliVersion: match[1],
|
|
374
|
+
hookDefinitionHash,
|
|
375
|
+
staticReady: true,
|
|
376
|
+
discoveredHooks,
|
|
377
|
+
runtimeLiveness,
|
|
378
|
+
diagnostics: transport.diagnostics
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
export { CodexAppServerTransport, hasCodexRuntimeLiveness, parseCodexModelReroute, parseCodexHooksList, parseCodexThreadResolution, parseCodexTurnCompleted, preflightCodexLifecycleEvidence, resolveCodexTerminal, resolveCodexThread, validateCodexLifecycleHookConfig };
|
|
382
|
+
//# sourceMappingURL=app-server.js.map
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
function createCodexLifecycleState(cliVersion) {
|
|
2
|
+
if (!cliVersion.trim())
|
|
3
|
+
throw new Error('Codex CLI version is required');
|
|
4
|
+
return Object.freeze({
|
|
5
|
+
schemaVersion: 1,
|
|
6
|
+
cliVersion,
|
|
7
|
+
status: 'empty',
|
|
8
|
+
spawn: null,
|
|
9
|
+
child: null,
|
|
10
|
+
thread: null,
|
|
11
|
+
settings: null,
|
|
12
|
+
reroute: null,
|
|
13
|
+
terminal: null,
|
|
14
|
+
stop: null,
|
|
15
|
+
startEvidence: null,
|
|
16
|
+
stopEvidence: null,
|
|
17
|
+
error: null
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
function invalid(state, code, message) {
|
|
21
|
+
return Object.freeze({
|
|
22
|
+
...state,
|
|
23
|
+
status: 'invalid',
|
|
24
|
+
startEvidence: null,
|
|
25
|
+
stopEvidence: null,
|
|
26
|
+
error: Object.freeze({ code, message })
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
function same(left, right) {
|
|
30
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
31
|
+
}
|
|
32
|
+
function requiredStrings(event) {
|
|
33
|
+
return Object.entries(event).every(([key, value]) => key === 'forkedFromId'
|
|
34
|
+
|| (typeof value !== 'string' || value.trim() !== ''));
|
|
35
|
+
}
|
|
36
|
+
function derive(state) {
|
|
37
|
+
const { spawn, child, thread, settings, reroute, terminal, stop } = state;
|
|
38
|
+
if (spawn && child && (spawn.sessionId !== child.sessionId
|
|
39
|
+
|| spawn.nativeAgent !== child.nativeAgent)) {
|
|
40
|
+
return invalid(state, 'CODEX_EVIDENCE_IDENTITY_MISMATCH', 'hook spawn and child identity do not match');
|
|
41
|
+
}
|
|
42
|
+
if (child && thread && child.childThreadId !== thread.childThreadId) {
|
|
43
|
+
return invalid(state, 'CODEX_EVIDENCE_IDENTITY_MISMATCH', 'hook and App Server child identity do not match');
|
|
44
|
+
}
|
|
45
|
+
if (spawn && thread && (thread.parentThreadId !== spawn.sessionId
|
|
46
|
+
|| thread.sourceParentThreadId !== spawn.sessionId)) {
|
|
47
|
+
return invalid(state, 'CODEX_EVIDENCE_PARENT_MISMATCH', 'App Server parent identity does not match the spawning session');
|
|
48
|
+
}
|
|
49
|
+
if (thread?.forkedFromId !== null && thread?.forkedFromId !== undefined) {
|
|
50
|
+
return invalid(state, 'CODEX_EVIDENCE_FORK_FORBIDDEN', 'forked child threads are not fresh lifecycle evidence');
|
|
51
|
+
}
|
|
52
|
+
if (settings && child && settings.childThreadId !== child.childThreadId) {
|
|
53
|
+
return invalid(state, 'CODEX_EVIDENCE_IDENTITY_MISMATCH', 'resolved settings belong to a different child');
|
|
54
|
+
}
|
|
55
|
+
if (reroute && child && reroute.childThreadId !== child.childThreadId) {
|
|
56
|
+
return invalid(state, 'CODEX_EVIDENCE_IDENTITY_MISMATCH', 'model reroute belongs to a different child');
|
|
57
|
+
}
|
|
58
|
+
if (spawn?.requestedModel && settings && spawn.requestedModel !== settings.model) {
|
|
59
|
+
if (!reroute
|
|
60
|
+
|| reroute.fromModel !== spawn.requestedModel
|
|
61
|
+
|| reroute.toModel !== settings.model
|
|
62
|
+
|| !reroute.reason.trim()) {
|
|
63
|
+
return invalid(state, 'CODEX_EVIDENCE_MODEL_UNEXPLAINED', 'resolved model differs without a matching host reroute');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (spawn?.requestedReasoningEffort
|
|
67
|
+
&& settings
|
|
68
|
+
&& spawn.requestedReasoningEffort !== settings.reasoningEffort) {
|
|
69
|
+
return invalid(state, 'CODEX_EVIDENCE_EFFORT_UNEXPLAINED', 'resolved reasoning effort differs without structured host evidence');
|
|
70
|
+
}
|
|
71
|
+
if (terminal && terminal.status !== 'completed') {
|
|
72
|
+
return invalid(state, 'CODEX_EVIDENCE_TERMINAL_INVALID', `child turn ended as '${terminal.status}'`);
|
|
73
|
+
}
|
|
74
|
+
if (terminal && child && terminal.childThreadId !== child.childThreadId) {
|
|
75
|
+
return invalid(state, 'CODEX_EVIDENCE_IDENTITY_MISMATCH', 'terminal event belongs to a different child');
|
|
76
|
+
}
|
|
77
|
+
if (stop && child && (stop.sessionId !== child.sessionId
|
|
78
|
+
|| stop.turnId !== child.turnId
|
|
79
|
+
|| stop.childThreadId !== child.childThreadId
|
|
80
|
+
|| stop.nativeAgent !== child.nativeAgent)) {
|
|
81
|
+
return invalid(state, 'CODEX_EVIDENCE_IDENTITY_MISMATCH', 'hook stop identity does not match the child');
|
|
82
|
+
}
|
|
83
|
+
let startEvidence = null;
|
|
84
|
+
if (spawn && child && thread && settings) {
|
|
85
|
+
startEvidence = Object.freeze({
|
|
86
|
+
schemaVersion: 1,
|
|
87
|
+
cliVersion: state.cliVersion,
|
|
88
|
+
parentThreadId: spawn.sessionId,
|
|
89
|
+
parentTurnId: spawn.turnId,
|
|
90
|
+
spawnToolUseId: spawn.toolUseId,
|
|
91
|
+
childThreadId: child.childThreadId,
|
|
92
|
+
nativeAgent: child.nativeAgent,
|
|
93
|
+
spawnMode: 'fresh',
|
|
94
|
+
actualModel: Object.freeze({ value: settings.model, source: 'codex-app-server-settings' }),
|
|
95
|
+
actualReasoningEffort: Object.freeze({ value: settings.reasoningEffort, source: 'codex-app-server-settings' }),
|
|
96
|
+
modelFallbackReason: reroute?.reason ?? null,
|
|
97
|
+
reasoningEffortFallbackReason: null,
|
|
98
|
+
hookDefinitionHash: spawn.hookDefinitionHash
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
let stopEvidence = null;
|
|
102
|
+
if (startEvidence && terminal?.status === 'completed' && stop) {
|
|
103
|
+
stopEvidence = Object.freeze({
|
|
104
|
+
schemaVersion: 1,
|
|
105
|
+
childThreadId: startEvidence.childThreadId,
|
|
106
|
+
turnId: terminal.turnId,
|
|
107
|
+
terminalStatus: 'completed',
|
|
108
|
+
hookStopObserved: true
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
const status = stopEvidence
|
|
112
|
+
? 'stop-ready'
|
|
113
|
+
: terminal
|
|
114
|
+
? 'observed-terminal'
|
|
115
|
+
: startEvidence
|
|
116
|
+
? 'start-ready'
|
|
117
|
+
: child
|
|
118
|
+
? 'observed-child'
|
|
119
|
+
: spawn
|
|
120
|
+
? 'observed-spawn'
|
|
121
|
+
: 'empty';
|
|
122
|
+
return Object.freeze({ ...state, status, startEvidence, stopEvidence, error: null });
|
|
123
|
+
}
|
|
124
|
+
function reduceCodexLifecycleEvent(state, event) {
|
|
125
|
+
if (state.status === 'invalid' || state.status === 'expired')
|
|
126
|
+
return state;
|
|
127
|
+
if (!requiredStrings(event)) {
|
|
128
|
+
return invalid(state, 'CODEX_EVIDENCE_FIELD_MISSING', 'lifecycle event contains an empty required field');
|
|
129
|
+
}
|
|
130
|
+
const key = {
|
|
131
|
+
'hook-spawn': 'spawn',
|
|
132
|
+
'hook-child': 'child',
|
|
133
|
+
'app-thread': 'thread',
|
|
134
|
+
'app-settings': 'settings',
|
|
135
|
+
'app-reroute': 'reroute',
|
|
136
|
+
'app-terminal': 'terminal',
|
|
137
|
+
'hook-stop': 'stop'
|
|
138
|
+
}[event.type];
|
|
139
|
+
const existing = state[key];
|
|
140
|
+
if (existing) {
|
|
141
|
+
if (same(existing, event))
|
|
142
|
+
return state;
|
|
143
|
+
return invalid(state, 'CODEX_EVIDENCE_REPLAY_CONFLICT', `conflicting '${event.type}' event`);
|
|
144
|
+
}
|
|
145
|
+
return derive(Object.freeze({ ...state, [key]: Object.freeze({ ...event }) }));
|
|
146
|
+
}
|
|
147
|
+
function expireCodexLifecycleState(state) {
|
|
148
|
+
if (!['observed-spawn', 'observed-child', 'start-ready', 'observed-terminal'].includes(state.status)) {
|
|
149
|
+
return state;
|
|
150
|
+
}
|
|
151
|
+
return Object.freeze({
|
|
152
|
+
...state,
|
|
153
|
+
status: 'expired',
|
|
154
|
+
startEvidence: null,
|
|
155
|
+
stopEvidence: null,
|
|
156
|
+
error: Object.freeze({
|
|
157
|
+
code: 'CODEX_EVIDENCE_EXPIRED',
|
|
158
|
+
message: 'Codex lifecycle evidence expired before completion'
|
|
159
|
+
})
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
export { createCodexLifecycleState, expireCodexLifecycleState, reduceCodexLifecycleEvent };
|
|
163
|
+
//# sourceMappingURL=evidence.js.map
|