@fitlab-ai/agent-infra 0.9.3 → 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 +3 -1
- package/README.zh-CN.md +3 -1
- package/bin/cli.ts +12 -0
- package/dist/bin/cli.js +14 -0
- package/dist/bin/internal-cli.js +144 -123
- package/dist/lib/agent-clients/adapter.js +94 -4
- package/dist/lib/{sandbox/credentials.js → agent-clients/adapters/claude-code-credentials.js} +4 -14
- package/dist/lib/agent-clients/adapters/claude-code-refresh.js +85 -0
- package/dist/lib/agent-clients/adapters/claude-code-sandbox.js +247 -0
- package/dist/lib/agent-clients/adapters/claude-code.js +17 -3
- 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/agent-clients/adapters/opencode-sandbox.js +108 -0
- package/dist/lib/agent-clients/adapters/opencode.js +15 -3
- package/dist/lib/agent-clients/adapters/runtimes/claude-code.dockerfile +65 -0
- package/dist/lib/agent-clients/registry.js +9 -1
- package/dist/lib/git/worktree-identity.js +64 -0
- package/dist/lib/internal/codex-lifecycle.js +202 -0
- package/dist/lib/internal/sandbox-control.js +24 -0
- package/dist/lib/internal/task-activity.js +45 -13
- package/dist/lib/internal/task-create.js +48 -0
- package/dist/lib/internal/task-ledger.js +12 -3
- package/dist/lib/internal/task-lifecycle.js +19 -1
- package/dist/lib/internal/task-orchestration.js +170 -27
- package/dist/lib/platform/github-client.js +19 -2
- package/dist/lib/platform/pr-checks.js +1 -1
- package/dist/lib/platform/pull-requests.js +47 -1
- package/dist/lib/platform/releases.js +13 -5
- package/dist/lib/process-data/index.js +239 -0
- package/dist/lib/process-data/normalize.js +198 -0
- package/dist/lib/process-data/privacy.js +33 -0
- package/dist/lib/process-data/reconcile.js +95 -0
- package/dist/lib/process-data/repair.js +58 -0
- package/dist/lib/process-data/sources.js +345 -0
- package/dist/lib/process-data/store.js +282 -0
- package/dist/lib/process-data/types.js +2 -0
- package/dist/lib/run/index.js +4 -3
- package/dist/lib/run/tui.js +7 -8
- package/dist/lib/sandbox/agent-client-reconciler.js +26 -2
- package/dist/lib/sandbox/capture.js +7 -2
- package/dist/lib/sandbox/commands/create.js +110 -228
- package/dist/lib/sandbox/commands/enter.js +15 -47
- package/dist/lib/sandbox/commands/list-running.js +16 -6
- package/dist/lib/sandbox/commands/ls.js +10 -6
- package/dist/lib/sandbox/commands/rebuild.js +4 -3
- package/dist/lib/sandbox/commands/refresh.js +4 -84
- package/dist/lib/sandbox/commands/rm.js +24 -3
- package/dist/lib/sandbox/commands/show.js +12 -3
- package/dist/lib/sandbox/commands/start.js +7 -4
- package/dist/lib/sandbox/config.js +2 -0
- package/dist/lib/sandbox/constants.js +6 -0
- package/dist/lib/sandbox/control/client.js +58 -0
- package/dist/lib/sandbox/control/protocol.js +54 -0
- package/dist/lib/sandbox/control/server.js +144 -0
- package/dist/lib/sandbox/dockerfile.js +36 -13
- package/dist/lib/sandbox/mounts.js +17 -4
- package/dist/lib/sandbox/recovery.js +128 -5
- package/dist/lib/sandbox/redaction.js +12 -0
- package/dist/lib/sandbox/runtimes/base.dockerfile +24 -74
- package/dist/lib/sandbox/workspace-identity.js +95 -0
- package/dist/lib/sandbox/workspace-view.js +109 -0
- package/dist/lib/task/activity-intent.js +257 -51
- package/dist/lib/task/activity-log.js +32 -5
- package/dist/lib/task/commit-finalization.js +278 -0
- package/dist/lib/task/commit-intent.js +165 -0
- package/dist/lib/task/create-service.js +137 -0
- package/dist/lib/task/create.js +333 -0
- package/dist/lib/task/decision-intents.js +31 -17
- package/dist/lib/task/delegation-receipts.js +2 -2
- package/dist/lib/task/implementation-inputs.js +54 -7
- package/dist/lib/task/ledger-intents.js +35 -1
- package/dist/lib/task/orchestration.js +505 -34
- package/dist/lib/task/resolve-ref.js +41 -1
- package/dist/lib/task/review-fingerprint.js +4 -0
- package/dist/lib/task/workspace-snapshot.js +78 -3
- package/lib/agent-clients/adapter.ts +130 -6
- package/lib/{sandbox/credentials.ts → agent-clients/adapters/claude-code-credentials.ts} +3 -18
- package/lib/agent-clients/adapters/claude-code-refresh.ts +128 -0
- package/lib/agent-clients/adapters/claude-code-sandbox.ts +295 -0
- package/lib/agent-clients/adapters/claude-code.ts +21 -3
- 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/agent-clients/adapters/opencode-sandbox.ts +136 -0
- package/lib/agent-clients/adapters/opencode.ts +18 -3
- package/lib/agent-clients/adapters/runtimes/claude-code.dockerfile +65 -0
- package/lib/agent-clients/registry.ts +9 -1
- package/lib/git/worktree-identity.ts +86 -0
- package/lib/internal/codex-lifecycle.ts +204 -0
- package/lib/internal/sandbox-control.ts +24 -0
- package/lib/internal/task-activity.ts +50 -14
- package/lib/internal/task-create.ts +49 -0
- package/lib/internal/task-ledger.ts +12 -3
- package/lib/internal/task-lifecycle.ts +22 -1
- package/lib/internal/task-orchestration.ts +117 -21
- package/lib/platform/github-client.ts +20 -2
- package/lib/platform/pr-checks.ts +1 -1
- package/lib/platform/pull-requests.ts +49 -1
- package/lib/platform/releases.ts +16 -4
- package/lib/process-data/index.ts +224 -0
- package/lib/process-data/normalize.ts +202 -0
- package/lib/process-data/privacy.ts +41 -0
- package/lib/process-data/reconcile.ts +110 -0
- package/lib/process-data/repair.ts +64 -0
- package/lib/process-data/sources.ts +354 -0
- package/lib/process-data/store.ts +315 -0
- package/lib/process-data/types.ts +135 -0
- package/lib/run/index.ts +5 -3
- package/lib/run/tui.ts +11 -8
- package/lib/sandbox/agent-client-reconciler.ts +44 -2
- package/lib/sandbox/capture.ts +9 -2
- package/lib/sandbox/commands/create.ts +127 -260
- package/lib/sandbox/commands/enter.ts +13 -59
- package/lib/sandbox/commands/list-running.ts +23 -6
- package/lib/sandbox/commands/ls.ts +22 -6
- package/lib/sandbox/commands/rebuild.ts +4 -3
- package/lib/sandbox/commands/refresh.ts +4 -126
- package/lib/sandbox/commands/rm.ts +24 -3
- package/lib/sandbox/commands/show.ts +29 -3
- package/lib/sandbox/commands/start.ts +6 -4
- package/lib/sandbox/config.ts +4 -0
- package/lib/sandbox/constants.ts +8 -0
- package/lib/sandbox/control/client.ts +79 -0
- package/lib/sandbox/control/protocol.ts +110 -0
- package/lib/sandbox/control/server.ts +155 -0
- package/lib/sandbox/dockerfile.ts +66 -13
- package/lib/sandbox/mounts.ts +24 -4
- package/lib/sandbox/recovery.ts +163 -6
- package/lib/sandbox/redaction.ts +14 -0
- package/lib/sandbox/runtimes/base.dockerfile +24 -74
- package/lib/sandbox/tool-types.ts +16 -0
- package/lib/sandbox/workspace-identity.ts +123 -0
- package/lib/sandbox/workspace-view.ts +150 -0
- package/lib/task/activity-intent.ts +350 -61
- package/lib/task/activity-log.ts +46 -7
- package/lib/task/commit-finalization.ts +376 -0
- package/lib/task/commit-intent.ts +230 -0
- package/lib/task/create-service.ts +171 -0
- package/lib/task/create.ts +372 -0
- package/lib/task/decision-intents.ts +32 -12
- package/lib/task/delegation-receipts.ts +2 -2
- package/lib/task/implementation-inputs.ts +62 -8
- package/lib/task/ledger-intents.ts +43 -3
- package/lib/task/orchestration.ts +673 -41
- package/lib/task/resolve-ref.ts +46 -1
- 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/README.en.md +1 -1
- package/templates/.agents/rules/README.zh-CN.md +1 -1
- package/templates/.agents/rules/human-decision-context.en.md +11 -2
- package/templates/.agents/rules/human-decision-context.zh-CN.md +11 -2
- package/templates/.agents/rules/pr-checks-commands.en.md +1 -1
- package/templates/.agents/rules/pr-checks-commands.github.en.md +1 -1
- package/templates/.agents/rules/pr-checks-commands.github.zh-CN.md +2 -2
- package/templates/.agents/rules/pr-checks-commands.zh-CN.md +1 -1
- package/templates/.agents/rules/review-handshake.zh-CN.md +1 -1
- package/templates/.agents/rules/task-management.en.md +3 -0
- package/templates/.agents/rules/task-management.zh-CN.md +3 -0
- 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/commit/SKILL.en.md +21 -17
- package/templates/.agents/skills/commit/SKILL.zh-CN.md +28 -16
- package/templates/.agents/skills/commit/reference/commit-orchestration.en.md +50 -0
- package/templates/.agents/skills/commit/reference/commit-orchestration.zh-CN.md +56 -0
- package/templates/.agents/skills/commit/reference/task-status-update.en.md +4 -4
- package/templates/.agents/skills/commit/reference/task-status-update.zh-CN.md +4 -4
- package/templates/.agents/skills/complete-task/SKILL.en.md +1 -1
- package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +1 -1
- package/templates/.agents/skills/create-pr/SKILL.en.md +4 -4
- package/templates/.agents/skills/create-pr/SKILL.zh-CN.md +4 -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/.agents/skills/create-task/reference/context-capture.en.md +34 -0
- package/templates/.agents/skills/create-task/reference/context-capture.zh-CN.md +34 -0
- package/templates/.agents/skills/review-code/SKILL.en.md +2 -2
- package/templates/.agents/skills/review-code/SKILL.zh-CN.md +2 -2
- package/templates/.agents/skills/review-code/reference/output-templates.en.md +1 -1
- package/templates/.agents/skills/review-code/reference/output-templates.zh-CN.md +1 -1
- package/templates/.agents/skills/review-pr/SKILL.en.md +36 -8
- package/templates/.agents/skills/review-pr/SKILL.zh-CN.md +36 -8
- package/templates/.agents/skills/review-pr/reference/report-template.en.md +1 -1
- package/templates/.agents/skills/review-pr/reference/report-template.zh-CN.md +1 -1
- package/templates/.agents/skills/update-agent-infra/scripts/sync-templates.js +67 -50
- package/templates/.agents/skills/watch-pr/SKILL.en.md +4 -4
- package/templates/.agents/skills/watch-pr/SKILL.zh-CN.md +4 -4
- package/templates/.agents/skills/watch-pr/reference/monitor-and-heal.en.md +2 -2
- package/templates/.agents/skills/watch-pr/reference/monitor-and-heal.zh-CN.md +2 -2
- package/templates/.agents/templates/task.en.md +1 -1
- package/templates/.agents/templates/task.zh-CN.md +1 -1
- package/templates/.claude/commands/watch-pr.en.md +1 -1
- package/templates/.claude/commands/watch-pr.zh-CN.md +1 -1
- package/templates/.claude/rules/tool-preferences.en.md +20 -0
- package/templates/.claude/rules/tool-preferences.zh-CN.md +20 -0
- package/templates/.codex/hooks.json +50 -0
- package/templates/.opencode/commands/watch-pr.en.md +1 -1
- package/templates/.opencode/commands/watch-pr.zh-CN.md +1 -1
- package/templates/.gemini/commands/_project_/review-pr.en.toml +0 -10
- package/templates/.gemini/commands/_project_/review-pr.zh-CN.toml +0 -10
|
@@ -0,0 +1,442 @@
|
|
|
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
|
+
|
|
8
|
+
import type { ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
9
|
+
import type { CodexLifecycleEvent } from './evidence.ts';
|
|
10
|
+
|
|
11
|
+
type JsonObject = Record<string, unknown>;
|
|
12
|
+
type ThreadResolution = Readonly<{
|
|
13
|
+
thread: Extract<CodexLifecycleEvent, { type: 'app-thread' }>;
|
|
14
|
+
settings: Extract<CodexLifecycleEvent, { type: 'app-settings' }>;
|
|
15
|
+
}>;
|
|
16
|
+
|
|
17
|
+
type DiscoveredHook = Readonly<{
|
|
18
|
+
eventName: string;
|
|
19
|
+
matcher: string | null;
|
|
20
|
+
command: string;
|
|
21
|
+
enabled: boolean;
|
|
22
|
+
}>;
|
|
23
|
+
|
|
24
|
+
type AppServerTransportOptions = Readonly<{
|
|
25
|
+
command?: string;
|
|
26
|
+
args?: readonly string[];
|
|
27
|
+
cwd?: string;
|
|
28
|
+
env?: NodeJS.ProcessEnv;
|
|
29
|
+
timeoutMs?: number;
|
|
30
|
+
}>;
|
|
31
|
+
|
|
32
|
+
type CodexRuntimeIdentity = Readonly<{
|
|
33
|
+
sessionId: string;
|
|
34
|
+
turnId: string;
|
|
35
|
+
toolUseId: string;
|
|
36
|
+
}>;
|
|
37
|
+
|
|
38
|
+
const LIFECYCLE_HOOKS = Object.freeze([
|
|
39
|
+
Object.freeze({ event: 'PreToolUse', matcher: '^collaborationspawn_agent$', phase: 'pre-tool' }),
|
|
40
|
+
Object.freeze({ event: 'PostToolUse', matcher: '^collaborationspawn_agent$', phase: 'post-tool' }),
|
|
41
|
+
Object.freeze({ event: 'SubagentStart', matcher: '^agent-infra-lifecycle-(executor|reviewer)$', phase: 'subagent-start' }),
|
|
42
|
+
Object.freeze({ event: 'SubagentStop', matcher: '^agent-infra-lifecycle-(executor|reviewer)$', phase: 'subagent-stop' })
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
function object(value: unknown): JsonObject | null {
|
|
46
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
47
|
+
? value as JsonObject
|
|
48
|
+
: null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function nonEmpty(value: unknown): string | null {
|
|
52
|
+
return typeof value === 'string' && value.trim() ? value : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function validateCodexLifecycleHookConfig(value: unknown): void {
|
|
56
|
+
const hooks = object(object(value)?.hooks);
|
|
57
|
+
const valid = hooks && LIFECYCLE_HOOKS.every(({ event, matcher, phase }) => {
|
|
58
|
+
const entries = hooks[event];
|
|
59
|
+
if (!Array.isArray(entries)) return false;
|
|
60
|
+
return entries.some((entryValue) => {
|
|
61
|
+
const entry = object(entryValue);
|
|
62
|
+
if (entry?.matcher !== matcher || !Array.isArray(entry.hooks)) return false;
|
|
63
|
+
return entry.hooks.some((hookValue) => {
|
|
64
|
+
const hook = object(hookValue);
|
|
65
|
+
return hook?.type === 'command'
|
|
66
|
+
&& hook.timeout === 5
|
|
67
|
+
&& hook.command === `node "$(git rev-parse --show-toplevel)/.agents/hooks/lifecycle-delegation.js" --client codex --event ${phase}`;
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
if (!valid) throw new Error('CODEX_PREFLIGHT_HOOKS_INVALID: lifecycle hooks are invalid');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function parseCodexHooksList(value: unknown, repoRoot: string): readonly DiscoveredHook[] {
|
|
75
|
+
const root = object(value);
|
|
76
|
+
const entries = Array.isArray(root?.data) ? root.data : [];
|
|
77
|
+
const entry = entries.map(object).find((candidate) => candidate?.cwd === repoRoot);
|
|
78
|
+
const errors = Array.isArray(entry?.errors) ? entry.errors : [];
|
|
79
|
+
if (errors.length) throw new Error(`CODEX_PREFLIGHT_HOOK_DISCOVERY_FAILED: ${errors.map(String).join('; ')}`);
|
|
80
|
+
const hooks = (Array.isArray(entry?.hooks) ? entry.hooks : [])
|
|
81
|
+
.map(object)
|
|
82
|
+
.filter((hook): hook is JsonObject => hook !== null)
|
|
83
|
+
.map((hook) => Object.freeze({
|
|
84
|
+
eventName: String(hook.eventName ?? ''),
|
|
85
|
+
matcher: typeof hook.matcher === 'string' ? hook.matcher : null,
|
|
86
|
+
command: String(hook.command ?? ''),
|
|
87
|
+
enabled: hook.enabled === true
|
|
88
|
+
}));
|
|
89
|
+
const valid = LIFECYCLE_HOOKS.every(({ event, matcher, phase }) => hooks.some((hook) =>
|
|
90
|
+
hook.eventName === event.replace(/^./, (character) => character.toLowerCase())
|
|
91
|
+
&& hook.matcher === matcher
|
|
92
|
+
&& hook.command === `node "$(git rev-parse --show-toplevel)/.agents/hooks/lifecycle-delegation.js" --client codex --event ${phase}`
|
|
93
|
+
&& hook.enabled
|
|
94
|
+
));
|
|
95
|
+
if (!valid) throw new Error('CODEX_PREFLIGHT_HOOKS_NOT_LOADED: lifecycle hooks are not loaded for this workspace');
|
|
96
|
+
return Object.freeze(hooks);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function hasCodexRuntimeLiveness(
|
|
100
|
+
runtimeRoot: string,
|
|
101
|
+
hookDefinitionHash: string,
|
|
102
|
+
identity?: CodexRuntimeIdentity
|
|
103
|
+
): boolean {
|
|
104
|
+
if (!identity || !fs.existsSync(runtimeRoot)) return false;
|
|
105
|
+
return fs.readdirSync(runtimeRoot)
|
|
106
|
+
.filter((name) => /^[a-f0-9]{64}\.json$/.test(name))
|
|
107
|
+
.some((name) => {
|
|
108
|
+
try {
|
|
109
|
+
const record = object(JSON.parse(fs.readFileSync(path.join(runtimeRoot, name), 'utf8')));
|
|
110
|
+
const state = object(record?.state);
|
|
111
|
+
const spawnEvent = object(state?.spawn);
|
|
112
|
+
return !['invalid', 'expired'].includes(String(state?.status))
|
|
113
|
+
&& spawnEvent?.hookDefinitionHash === hookDefinitionHash
|
|
114
|
+
&& spawnEvent.sessionId === identity.sessionId
|
|
115
|
+
&& spawnEvent.turnId === identity.turnId
|
|
116
|
+
&& spawnEvent.toolUseId === identity.toolUseId;
|
|
117
|
+
} catch {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function parseCodexThreadResolution(readValue: unknown, resumeValue: unknown): ThreadResolution {
|
|
124
|
+
const readRoot = object(readValue);
|
|
125
|
+
const resumeRoot = object(resumeValue);
|
|
126
|
+
const thread = object(readRoot?.thread);
|
|
127
|
+
const resumedThread = object(resumeRoot?.thread);
|
|
128
|
+
const source = object(thread?.source);
|
|
129
|
+
const subAgent = object(source?.subAgent);
|
|
130
|
+
const threadSpawn = object(subAgent?.thread_spawn);
|
|
131
|
+
const childThreadId = nonEmpty(thread?.id);
|
|
132
|
+
const parentThreadId = nonEmpty(thread?.parentThreadId);
|
|
133
|
+
const sourceParentThreadId = nonEmpty(threadSpawn?.parent_thread_id);
|
|
134
|
+
const resumedChildThreadId = nonEmpty(resumedThread?.id);
|
|
135
|
+
const model = nonEmpty(resumeRoot?.model);
|
|
136
|
+
const reasoningEffort = nonEmpty(resumeRoot?.reasoningEffort ?? object(resumeRoot?.settings)?.effort);
|
|
137
|
+
const forkedFromId = thread?.forkedFromId;
|
|
138
|
+
if (
|
|
139
|
+
!childThreadId
|
|
140
|
+
|| resumedChildThreadId !== childThreadId
|
|
141
|
+
|| !parentThreadId
|
|
142
|
+
|| !sourceParentThreadId
|
|
143
|
+
|| !model
|
|
144
|
+
|| !reasoningEffort
|
|
145
|
+
|| (forkedFromId !== null && typeof forkedFromId !== 'string')
|
|
146
|
+
) {
|
|
147
|
+
throw new Error('Codex App Server thread resolution is invalid');
|
|
148
|
+
}
|
|
149
|
+
return Object.freeze({
|
|
150
|
+
thread: Object.freeze({
|
|
151
|
+
type: 'app-thread',
|
|
152
|
+
childThreadId,
|
|
153
|
+
parentThreadId,
|
|
154
|
+
forkedFromId,
|
|
155
|
+
sourceParentThreadId
|
|
156
|
+
}),
|
|
157
|
+
settings: Object.freeze({
|
|
158
|
+
type: 'app-settings',
|
|
159
|
+
childThreadId,
|
|
160
|
+
model,
|
|
161
|
+
reasoningEffort
|
|
162
|
+
})
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function parseCodexTurnCompleted(value: unknown): Extract<CodexLifecycleEvent, { type: 'app-terminal' }> {
|
|
167
|
+
const root = object(value);
|
|
168
|
+
const turn = object(root?.turn);
|
|
169
|
+
const childThreadId = nonEmpty(root?.threadId);
|
|
170
|
+
const turnId = nonEmpty(turn?.id);
|
|
171
|
+
const status = turn?.status;
|
|
172
|
+
if (!childThreadId || !turnId || !['completed', 'interrupted', 'failed'].includes(String(status))) {
|
|
173
|
+
throw new Error('Codex App Server turn completion is invalid');
|
|
174
|
+
}
|
|
175
|
+
return Object.freeze({
|
|
176
|
+
type: 'app-terminal',
|
|
177
|
+
childThreadId,
|
|
178
|
+
turnId,
|
|
179
|
+
status: status as 'completed' | 'interrupted' | 'failed'
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function parseCodexModelReroute(value: unknown): Extract<CodexLifecycleEvent, { type: 'app-reroute' }> {
|
|
184
|
+
const root = object(value);
|
|
185
|
+
const childThreadId = nonEmpty(root?.threadId);
|
|
186
|
+
const turnId = nonEmpty(root?.turnId);
|
|
187
|
+
const fromModel = nonEmpty(root?.fromModel);
|
|
188
|
+
const toModel = nonEmpty(root?.toModel);
|
|
189
|
+
const reasonValue = root?.reason;
|
|
190
|
+
const reason = nonEmpty(reasonValue) ?? (object(reasonValue) ? JSON.stringify(reasonValue) : null);
|
|
191
|
+
if (!childThreadId || !turnId || !fromModel || !toModel || !reason) {
|
|
192
|
+
throw new Error('Codex App Server model reroute is invalid');
|
|
193
|
+
}
|
|
194
|
+
return Object.freeze({ type: 'app-reroute', childThreadId, turnId, fromModel, toModel, reason });
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
class CodexAppServerTransport {
|
|
198
|
+
readonly #options: Required<Pick<AppServerTransportOptions, 'command' | 'args' | 'timeoutMs'>> & AppServerTransportOptions;
|
|
199
|
+
#child: ChildProcessWithoutNullStreams | null = null;
|
|
200
|
+
#buffer = '';
|
|
201
|
+
#stderr = '';
|
|
202
|
+
#nextId = 1;
|
|
203
|
+
#pending = new Map<number, Readonly<{
|
|
204
|
+
resolve: (value: unknown) => void;
|
|
205
|
+
reject: (error: Error) => void;
|
|
206
|
+
timer: NodeJS.Timeout;
|
|
207
|
+
}>>();
|
|
208
|
+
#notifications: Readonly<{ method: string; params: unknown }>[] = [];
|
|
209
|
+
|
|
210
|
+
constructor(options: AppServerTransportOptions = {}) {
|
|
211
|
+
this.#options = {
|
|
212
|
+
...options,
|
|
213
|
+
command: options.command ?? 'codex',
|
|
214
|
+
args: options.args ?? ['app-server', '--stdio'],
|
|
215
|
+
timeoutMs: options.timeoutMs ?? 5_000
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
get diagnostics(): readonly string[] {
|
|
220
|
+
return Object.freeze(this.#stderr.split(/\r?\n/).filter(Boolean));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
get notifications(): readonly Readonly<{ method: string; params: unknown }>[] {
|
|
224
|
+
return Object.freeze([...this.#notifications]);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
start(): void {
|
|
228
|
+
if (this.#child) throw new Error('Codex App Server transport is already started');
|
|
229
|
+
const child = spawn(this.#options.command, [...this.#options.args], {
|
|
230
|
+
cwd: this.#options.cwd,
|
|
231
|
+
env: this.#options.env,
|
|
232
|
+
stdio: ['pipe', 'pipe', 'pipe']
|
|
233
|
+
});
|
|
234
|
+
this.#child = child;
|
|
235
|
+
child.stdout.setEncoding('utf8');
|
|
236
|
+
child.stderr.setEncoding('utf8');
|
|
237
|
+
child.stdout.on('data', (chunk: string) => this.#onData(chunk));
|
|
238
|
+
child.stderr.on('data', (chunk: string) => {
|
|
239
|
+
this.#stderr = `${this.#stderr}${chunk}`.slice(-32 * 1024);
|
|
240
|
+
});
|
|
241
|
+
child.on('error', (error) => this.#rejectAll(error));
|
|
242
|
+
child.on('exit', (code, signal) => {
|
|
243
|
+
if (this.#pending.size) {
|
|
244
|
+
this.#rejectAll(new Error(`Codex App Server exited before responding (code=${code}, signal=${signal})`));
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
#onData(chunk: string): void {
|
|
250
|
+
this.#buffer += chunk;
|
|
251
|
+
for (;;) {
|
|
252
|
+
const newline = this.#buffer.indexOf('\n');
|
|
253
|
+
if (newline < 0) return;
|
|
254
|
+
const line = this.#buffer.slice(0, newline).trim();
|
|
255
|
+
this.#buffer = this.#buffer.slice(newline + 1);
|
|
256
|
+
if (!line) continue;
|
|
257
|
+
let message: JsonObject;
|
|
258
|
+
try {
|
|
259
|
+
const parsed = object(JSON.parse(line));
|
|
260
|
+
if (!parsed) throw new Error('message is not an object');
|
|
261
|
+
message = parsed;
|
|
262
|
+
} catch (error) {
|
|
263
|
+
this.#rejectAll(new Error(`Codex App Server returned invalid JSON: ${String(error)}`));
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (typeof message.id === 'number') {
|
|
267
|
+
const pending = this.#pending.get(message.id);
|
|
268
|
+
if (!pending) continue;
|
|
269
|
+
clearTimeout(pending.timer);
|
|
270
|
+
this.#pending.delete(message.id);
|
|
271
|
+
if (message.error) pending.reject(new Error(`Codex App Server request failed: ${JSON.stringify(message.error)}`));
|
|
272
|
+
else pending.resolve(message.result);
|
|
273
|
+
} else if (typeof message.method === 'string') {
|
|
274
|
+
this.#notifications.push(Object.freeze({ method: message.method, params: message.params }));
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
#rejectAll(error: Error): void {
|
|
280
|
+
for (const [id, pending] of this.#pending) {
|
|
281
|
+
clearTimeout(pending.timer);
|
|
282
|
+
this.#pending.delete(id);
|
|
283
|
+
pending.reject(error);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
request(method: string, params: JsonObject): Promise<unknown> {
|
|
288
|
+
if (!this.#child || !this.#child.stdin.writable) {
|
|
289
|
+
return Promise.reject(new Error('Codex App Server transport is not running'));
|
|
290
|
+
}
|
|
291
|
+
const id = this.#nextId++;
|
|
292
|
+
return new Promise((resolve, reject) => {
|
|
293
|
+
const timer = setTimeout(() => {
|
|
294
|
+
this.#pending.delete(id);
|
|
295
|
+
reject(new Error(`Codex App Server request '${method}' timed out`));
|
|
296
|
+
}, this.#options.timeoutMs);
|
|
297
|
+
this.#pending.set(id, { resolve, reject, timer });
|
|
298
|
+
this.#child!.stdin.write(`${JSON.stringify({ id, method, params })}\n`);
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
notify(method: string, params: JsonObject = {}): void {
|
|
303
|
+
if (!this.#child || !this.#child.stdin.writable) throw new Error('Codex App Server transport is not running');
|
|
304
|
+
this.#child.stdin.write(`${JSON.stringify({ method, params })}\n`);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
async initialize(): Promise<unknown> {
|
|
308
|
+
const result = await this.request('initialize', {
|
|
309
|
+
clientInfo: { name: 'agent-infra', title: 'agent-infra', version: '0.9.5' },
|
|
310
|
+
capabilities: null
|
|
311
|
+
});
|
|
312
|
+
this.notify('initialized');
|
|
313
|
+
return result;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
close(): void {
|
|
317
|
+
if (!this.#child) return;
|
|
318
|
+
this.#child.stdin.end();
|
|
319
|
+
this.#child.kill();
|
|
320
|
+
this.#child = null;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
async function resolveCodexThread(
|
|
325
|
+
childThreadId: string,
|
|
326
|
+
options: AppServerTransportOptions = {}
|
|
327
|
+
): Promise<Readonly<{ resolution: ThreadResolution; reroutes: readonly Extract<CodexLifecycleEvent, { type: 'app-reroute' }>[]; diagnostics: readonly string[] }>> {
|
|
328
|
+
if (!nonEmpty(childThreadId)) throw new Error('Codex child thread id is required');
|
|
329
|
+
const transport = new CodexAppServerTransport(options);
|
|
330
|
+
transport.start();
|
|
331
|
+
try {
|
|
332
|
+
await transport.initialize();
|
|
333
|
+
const readResult = object(await transport.request('thread/read', { threadId: childThreadId, includeTurns: false }));
|
|
334
|
+
const readThread = object(readResult?.thread);
|
|
335
|
+
if (nonEmpty(readThread?.id) !== childThreadId) throw new Error('Codex App Server returned the wrong child thread');
|
|
336
|
+
const resumeResult = await transport.request('thread/resume', { threadId: childThreadId });
|
|
337
|
+
let resolution: ThreadResolution;
|
|
338
|
+
try {
|
|
339
|
+
resolution = parseCodexThreadResolution(readResult, resumeResult);
|
|
340
|
+
} catch {
|
|
341
|
+
throw new Error('Codex App Server resumed settings are unavailable');
|
|
342
|
+
}
|
|
343
|
+
const reroutes = transport.notifications
|
|
344
|
+
.filter((entry) => entry.method === 'model/rerouted')
|
|
345
|
+
.map((entry) => parseCodexModelReroute(entry.params))
|
|
346
|
+
.filter((event) => event.childThreadId === childThreadId);
|
|
347
|
+
return Object.freeze({ resolution, reroutes: Object.freeze(reroutes), diagnostics: transport.diagnostics });
|
|
348
|
+
} finally {
|
|
349
|
+
try {
|
|
350
|
+
await transport.request('thread/unsubscribe', { threadId: childThreadId });
|
|
351
|
+
} catch {
|
|
352
|
+
// Closing the short-lived transport still removes the subscription.
|
|
353
|
+
}
|
|
354
|
+
transport.close();
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
async function resolveCodexTerminal(
|
|
359
|
+
childThreadId: string,
|
|
360
|
+
options: AppServerTransportOptions = {}
|
|
361
|
+
): Promise<Extract<CodexLifecycleEvent, { type: 'app-terminal' }>> {
|
|
362
|
+
const transport = new CodexAppServerTransport(options);
|
|
363
|
+
transport.start();
|
|
364
|
+
try {
|
|
365
|
+
await transport.initialize();
|
|
366
|
+
const result = object(await transport.request('thread/read', { threadId: childThreadId, includeTurns: true }));
|
|
367
|
+
const thread = object(result?.thread);
|
|
368
|
+
if (nonEmpty(thread?.id) !== childThreadId) throw new Error('Codex App Server returned the wrong child thread');
|
|
369
|
+
const turns = Array.isArray(thread?.turns) ? thread.turns : [];
|
|
370
|
+
const turn = turns.at(-1);
|
|
371
|
+
return parseCodexTurnCompleted({ threadId: childThreadId, turn });
|
|
372
|
+
} finally {
|
|
373
|
+
transport.close();
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async function preflightCodexLifecycleEvidence(
|
|
378
|
+
repoRoot: string = process.cwd(),
|
|
379
|
+
runtimeIdentity?: CodexRuntimeIdentity
|
|
380
|
+
) {
|
|
381
|
+
const versionRun = spawnSync('codex', ['--version'], { encoding: 'utf8' });
|
|
382
|
+
const match = /codex-cli\s+(\d+\.\d+\.\d+)/.exec(versionRun.stdout ?? '');
|
|
383
|
+
if (versionRun.status !== 0 || !match?.[1] || !semver.gte(match[1], '0.147.0')) {
|
|
384
|
+
throw new Error('CODEX_PREFLIGHT_VERSION_UNSUPPORTED');
|
|
385
|
+
}
|
|
386
|
+
const featuresRun = spawnSync('codex', ['features', 'list'], { encoding: 'utf8' });
|
|
387
|
+
if (
|
|
388
|
+
featuresRun.status !== 0
|
|
389
|
+
|| !/^hooks\s+\S+\s+true$/m.test(featuresRun.stdout)
|
|
390
|
+
|| !/^multi_agent\s+\S+\s+true$/m.test(featuresRun.stdout)
|
|
391
|
+
) throw new Error('CODEX_PREFLIGHT_FEATURE_DISABLED');
|
|
392
|
+
|
|
393
|
+
const hooksPath = path.join(repoRoot, '.codex', 'hooks.json');
|
|
394
|
+
const hooksRaw = fs.readFileSync(hooksPath, 'utf8');
|
|
395
|
+
validateCodexLifecycleHookConfig(JSON.parse(hooksRaw));
|
|
396
|
+
|
|
397
|
+
const schemaDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-infra-codex-schema-'));
|
|
398
|
+
try {
|
|
399
|
+
const schemaRun = spawnSync('codex', ['app-server', 'generate-json-schema', '--out', schemaDir], { encoding: 'utf8' });
|
|
400
|
+
if (schemaRun.status !== 0) throw new Error('CODEX_PREFLIGHT_SCHEMA_UNAVAILABLE');
|
|
401
|
+
const schema = fs.readFileSync(path.join(schemaDir, 'codex_app_server_protocol.v2.schemas.json'), 'utf8');
|
|
402
|
+
for (const field of ['parentThreadId', 'forkedFromId', 'ThreadSettings', 'turn/completed', 'model/rerouted']) {
|
|
403
|
+
if (!schema.includes(field)) throw new Error(`CODEX_PREFLIGHT_SCHEMA_MISSING:${field}`);
|
|
404
|
+
}
|
|
405
|
+
} finally {
|
|
406
|
+
fs.rmSync(schemaDir, { recursive: true, force: true });
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
const hookDefinitionHash = crypto.createHash('sha256').update(hooksRaw).digest('hex');
|
|
410
|
+
const runtimeRoot = path.join(repoRoot, '.agents', 'workspace', '.runtime', 'codex-lifecycle');
|
|
411
|
+
const runtimeLiveness = hasCodexRuntimeLiveness(runtimeRoot, hookDefinitionHash, runtimeIdentity);
|
|
412
|
+
|
|
413
|
+
const transport = new CodexAppServerTransport();
|
|
414
|
+
transport.start();
|
|
415
|
+
let discoveredHooks: readonly DiscoveredHook[];
|
|
416
|
+
try {
|
|
417
|
+
await transport.initialize();
|
|
418
|
+
discoveredHooks = parseCodexHooksList(await transport.request('hooks/list', { cwds: [repoRoot] }), repoRoot);
|
|
419
|
+
} finally { transport.close(); }
|
|
420
|
+
return Object.freeze({
|
|
421
|
+
cliVersion: match[1],
|
|
422
|
+
hookDefinitionHash,
|
|
423
|
+
staticReady: true,
|
|
424
|
+
discoveredHooks,
|
|
425
|
+
runtimeLiveness,
|
|
426
|
+
diagnostics: transport.diagnostics
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export {
|
|
431
|
+
CodexAppServerTransport,
|
|
432
|
+
hasCodexRuntimeLiveness,
|
|
433
|
+
parseCodexModelReroute,
|
|
434
|
+
parseCodexHooksList,
|
|
435
|
+
parseCodexThreadResolution,
|
|
436
|
+
parseCodexTurnCompleted,
|
|
437
|
+
preflightCodexLifecycleEvidence,
|
|
438
|
+
resolveCodexTerminal,
|
|
439
|
+
resolveCodexThread,
|
|
440
|
+
validateCodexLifecycleHookConfig
|
|
441
|
+
};
|
|
442
|
+
export type { AppServerTransportOptions, CodexRuntimeIdentity, ThreadResolution };
|