mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-28 05:57:13 +00:00
feat(codex): import and resume sessions from runners (#1088)
* fix codex import resume flow * fix hub restart session active state * fix codex transcript workspace scoping * Address Codex import review findings * Fix Codex import machine selection * Update Codex sessions error test * Address Codex import review findings * Preserve forked Codex session id on sync * Make Codex duplicate cleanup source-aware * Handle Codex archive failures * Limit existing session flag to Codex * Preserve Codex import machine binding * fix: rebase runner Codex import onto current main * fix: preserve runner-scoped Codex import behavior --------- Co-authored-by: syy <815728149@qq.com>
This commit is contained in:
@@ -127,11 +127,24 @@ export interface ThreadResumeParams {
|
||||
export interface ThreadResumeResponse {
|
||||
thread: {
|
||||
id: string;
|
||||
turns?: Array<{ items?: ResponseItem[] }>;
|
||||
};
|
||||
model: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface ThreadForkParams extends Omit<ThreadResumeParams, 'history' | 'path'> {
|
||||
}
|
||||
|
||||
export interface ThreadForkResponse {
|
||||
thread: {
|
||||
id: string;
|
||||
turns?: Array<{ items?: ResponseItem[] }>;
|
||||
};
|
||||
model?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export type UserInput =
|
||||
| {
|
||||
type: 'text';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
||||
import { execFileSync, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { logger } from '@/ui/logger';
|
||||
import { JsonLineParser } from '@/utils/jsonLineParser';
|
||||
import { killProcessByChildProcess } from '@/utils/process';
|
||||
@@ -12,6 +13,8 @@ import type {
|
||||
ThreadStartResponse,
|
||||
ThreadResumeParams,
|
||||
ThreadResumeResponse,
|
||||
ThreadForkParams,
|
||||
ThreadForkResponse,
|
||||
TurnStartParams,
|
||||
TurnStartResponse,
|
||||
TurnInterruptParams,
|
||||
@@ -72,6 +75,84 @@ function createAbortError(): Error {
|
||||
return error;
|
||||
}
|
||||
|
||||
type CodexCommandCandidate = {
|
||||
command: string;
|
||||
source: 'desktop' | 'path';
|
||||
version: number[] | null;
|
||||
};
|
||||
|
||||
function parseCodexVersion(output: string): number[] | null {
|
||||
const match = /(\d+)\.(\d+)\.(\d+)(?:[-+][^\s]+)?/u.exec(output);
|
||||
if (!match) return null;
|
||||
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
||||
}
|
||||
|
||||
function getCodexVersion(command: string): number[] | null {
|
||||
try {
|
||||
const output = execFileSync(command, ['--version'], {
|
||||
encoding: 'utf8',
|
||||
timeout: 3_000,
|
||||
stdio: ['ignore', 'pipe', 'ignore']
|
||||
});
|
||||
return parseCodexVersion(output);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function compareVersion(a: number[] | null, b: number[] | null): number {
|
||||
if (!a && !b) return 0;
|
||||
if (a && !b) return 1;
|
||||
if (!a && b) return -1;
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
const diff = (a?.[index] ?? 0) - (b?.[index] ?? 0);
|
||||
if (diff !== 0) return diff;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function resolveCodexAppServerCommand(): string {
|
||||
if (process.env.HAPI_CODEX_APP_SERVER_BIN) {
|
||||
return process.env.HAPI_CODEX_APP_SERVER_BIN;
|
||||
}
|
||||
|
||||
const candidates: CodexCommandCandidate[] = [{
|
||||
command: 'codex',
|
||||
source: 'path',
|
||||
version: getCodexVersion('codex')
|
||||
}];
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
const desktopCodex = '/Applications/Codex.app/Contents/Resources/codex';
|
||||
if (existsSync(desktopCodex)) {
|
||||
candidates.push({
|
||||
command: desktopCodex,
|
||||
source: 'desktop',
|
||||
version: getCodexVersion(desktopCodex)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 中文注释:Codex Desktop 与 npm CLI 都可能写 thread-store;恢复时选择版本更新的 app-server,
|
||||
// 避免旧 CLI 读取新 rollout 格式失败。版本相同优先 Desktop,和用户看到的 Codex.app 保持一致。
|
||||
const best = candidates.sort((left, right) => {
|
||||
const versionDiff = compareVersion(right.version, left.version);
|
||||
if (versionDiff !== 0) return versionDiff;
|
||||
if (left.source === right.source) return 0;
|
||||
return left.source === 'desktop' ? -1 : 1;
|
||||
})[0];
|
||||
|
||||
logger.debug('[CodexAppServer] Resolved codex command', {
|
||||
selected: best.command,
|
||||
candidates: candidates.map((candidate) => ({
|
||||
command: candidate.command,
|
||||
source: candidate.source,
|
||||
version: candidate.version?.join('.') ?? null
|
||||
}))
|
||||
});
|
||||
return best.command;
|
||||
}
|
||||
|
||||
export class CodexAppServerClient extends JsonLineParser {
|
||||
private process: ChildProcessWithoutNullStreams | null = null;
|
||||
private connected = false;
|
||||
@@ -93,7 +174,9 @@ export class CodexAppServerClient extends JsonLineParser {
|
||||
return;
|
||||
}
|
||||
|
||||
this.process = spawn('codex', ['app-server'], {
|
||||
const codexCommand = resolveCodexAppServerCommand();
|
||||
logger.debug(`[CodexAppServer] Starting ${codexCommand} app-server`);
|
||||
this.process = spawn(codexCommand, ['app-server'], {
|
||||
env: Object.keys(process.env).reduce((acc, key) => {
|
||||
const value = process.env[key];
|
||||
if (typeof value === 'string') acc[key] = value;
|
||||
@@ -194,6 +277,14 @@ export class CodexAppServerClient extends JsonLineParser {
|
||||
return response as ThreadResumeResponse;
|
||||
}
|
||||
|
||||
async forkThread(params: ThreadForkParams, options?: { signal?: AbortSignal }): Promise<ThreadForkResponse> {
|
||||
const response = await this.sendRequest('thread/fork', params, {
|
||||
signal: options?.signal,
|
||||
timeoutMs: CodexAppServerClient.DEFAULT_TIMEOUT_MS
|
||||
});
|
||||
return response as ThreadForkResponse;
|
||||
}
|
||||
|
||||
async startTurn(params: TurnStartParams, options?: { signal?: AbortSignal }): Promise<TurnStartResponse> {
|
||||
const response = await this.sendRequest('turn/start', params, {
|
||||
signal: options?.signal,
|
||||
|
||||
@@ -1984,7 +1984,7 @@ describe('codexRemoteLauncher', () => {
|
||||
expect(session.sessionId).toBe('thread-old');
|
||||
expect(sessionEvents).toContainEqual({
|
||||
type: 'message',
|
||||
message: 'Task failed: Codex conversation thread-old could not be resumed; no new conversation was created'
|
||||
message: 'Task failed: Codex conversation thread-old could not be resumed; no new conversation was created. Reason: resume failed'
|
||||
});
|
||||
expect(session.thinking).toBe(false);
|
||||
});
|
||||
|
||||
@@ -20,6 +20,7 @@ import { buildThreadStartParams, buildTurnStartParams } from './utils/appServerC
|
||||
import type { ThreadGoal, ThreadGoalStatus } from './appServerTypes';
|
||||
import { shouldIgnoreTerminalEvent } from './utils/terminalEventGuard';
|
||||
import { parseCodexSpecialCommand } from './codexSpecialCommands';
|
||||
import { extractErrorInfo } from '@/utils/errorUtils';
|
||||
import {
|
||||
RemoteLauncherBase,
|
||||
type RemoteLauncherDisplayContext,
|
||||
@@ -80,6 +81,17 @@ const CODEX_SPAWN_AGENT_FULL_HISTORY_ARGUMENT_ERROR =
|
||||
'Full-history forked agents inherit the parent agent type, model, and reasoning effort; ' +
|
||||
'omit agent_type, model, and reasoning_effort, or spawn without a full-history fork.';
|
||||
|
||||
function formatCodexResumeError(error: unknown): string {
|
||||
const info = extractErrorInfo(error);
|
||||
const message = info.message && info.message !== 'Unknown error' ? info.message : '';
|
||||
const record = error && typeof error === 'object' ? error as Record<string, unknown> : null;
|
||||
const name = error instanceof Error && error.name && error.name !== 'Error' ? error.name : '';
|
||||
const cause = record?.cause instanceof Error ? record.cause.message : typeof record?.cause === 'string' ? record.cause : '';
|
||||
const code = typeof record?.code === 'string' ? record.code : '';
|
||||
const parts = [name, code, message, cause].filter((part) => part.trim().length > 0);
|
||||
return parts.length > 0 ? Array.from(new Set(parts)).join(': ') : 'unknown resume error';
|
||||
}
|
||||
|
||||
const SAME_THREAD_RETRYABLE_ERROR_PATTERNS = [
|
||||
'selected model is at capacity',
|
||||
'codex thread entered systemerror'
|
||||
@@ -3513,10 +3525,19 @@ class CodexRemoteLauncher extends RemoteLauncherBase {
|
||||
|
||||
while (!this.shouldExit) {
|
||||
logActiveHandles('loop-top');
|
||||
if (!pending && (recoveryInFlight || (turnInFlight && session.queue.size() === 0))) {
|
||||
if (!pending && recoveryInFlight) {
|
||||
await waitForTurnOrRecovery(this.abortController.signal);
|
||||
if (this.abortController.signal.aborted && !this.shouldExit) {
|
||||
logger.debug('[codex]: Internal wait aborted while turn/recovery was active; continuing');
|
||||
logger.debug('[codex]: Internal wait aborted while recovery was active; continuing');
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!pending && turnInFlight && session.queue.size() === 0) {
|
||||
await waitForTurnOrRecovery(this.abortController.signal);
|
||||
if (this.abortController.signal.aborted && !this.shouldExit) {
|
||||
logger.debug('[codex]: Internal wait aborted while turn was active; continuing');
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
@@ -3579,20 +3600,34 @@ class CodexRemoteLauncher extends RemoteLauncherBase {
|
||||
|
||||
if (resumeCandidate) {
|
||||
try {
|
||||
const resumeResponse = await appServerClient.resumeThread({
|
||||
threadId: resumeCandidate,
|
||||
...threadParams
|
||||
}, {
|
||||
signal: this.abortController.signal
|
||||
});
|
||||
const resumeRecord = asRecord(resumeResponse);
|
||||
const resumeThread = resumeRecord ? asRecord(resumeRecord.thread) : null;
|
||||
threadId = asString(resumeThread?.id) ?? resumeCandidate;
|
||||
applyResolvedModel(resumeRecord?.model);
|
||||
logger.debug(`[Codex] Resumed app-server thread ${threadId}`);
|
||||
const shouldForkImportedSource = Boolean(
|
||||
session.sourceSessionId
|
||||
&& resumeCandidate === session.sourceSessionId
|
||||
);
|
||||
const response = shouldForkImportedSource
|
||||
? await appServerClient.forkThread({
|
||||
threadId: resumeCandidate,
|
||||
...threadParams
|
||||
}, {
|
||||
signal: this.abortController.signal
|
||||
})
|
||||
: await appServerClient.resumeThread({
|
||||
threadId: resumeCandidate,
|
||||
...threadParams
|
||||
}, {
|
||||
signal: this.abortController.signal
|
||||
});
|
||||
const responseRecord = asRecord(response);
|
||||
const responseThread = responseRecord ? asRecord(responseRecord.thread) : null;
|
||||
threadId = asString(responseThread?.id) ?? resumeCandidate;
|
||||
applyResolvedModel(responseRecord?.model);
|
||||
logger.debug(shouldForkImportedSource
|
||||
? `[Codex] Forked imported app-server thread ${resumeCandidate} -> ${threadId}`
|
||||
: `[Codex] Resumed app-server thread ${threadId}`);
|
||||
} catch (error) {
|
||||
logger.warn(`[Codex] Failed to resume app-server thread ${resumeCandidate}; preserving old conversation boundary`, error);
|
||||
const failureMessage = `Task failed: Codex conversation ${resumeCandidate} could not be resumed; no new conversation was created`;
|
||||
const resumeError = formatCodexResumeError(error);
|
||||
logger.warn(`[Codex] Failed to resume app-server thread ${resumeCandidate}; preserving old conversation boundary: ${resumeError}`, error);
|
||||
const failureMessage = `Task failed: Codex conversation ${resumeCandidate} could not be resumed; no new conversation was created. Reason: ${resumeError}`;
|
||||
messageBuffer.addMessage(failureMessage, 'status');
|
||||
session.sendSessionEvent({ type: 'message', message: failureMessage });
|
||||
pending = null;
|
||||
|
||||
@@ -38,6 +38,7 @@ interface LoopOptions {
|
||||
modelReasoningEffort?: ReasoningEffort;
|
||||
collaborationMode?: CodexCollaborationMode;
|
||||
resumeSessionId?: string;
|
||||
sourceSessionId?: string;
|
||||
replayTranscriptHistoryOnStart?: boolean;
|
||||
onSessionReady?: (session: CodexSession) => void;
|
||||
}
|
||||
@@ -63,6 +64,7 @@ export async function loop(opts: LoopOptions): Promise<void> {
|
||||
model: opts.model,
|
||||
modelReasoningEffort: opts.modelReasoningEffort,
|
||||
collaborationMode: opts.collaborationMode ?? 'default',
|
||||
sourceSessionId: opts.sourceSessionId,
|
||||
replayTranscriptHistoryOnStart: opts.replayTranscriptHistoryOnStart ?? false
|
||||
});
|
||||
|
||||
|
||||
@@ -60,6 +60,9 @@ export async function runCodex(opts: {
|
||||
modelReasoningEffort: opts.modelReasoningEffort
|
||||
});
|
||||
const { api, session, sessionInfo } = bootstrap;
|
||||
const codexSourceSessionId = typeof sessionInfo.metadata?.codexSourceSessionId === 'string'
|
||||
? sessionInfo.metadata.codexSourceSessionId
|
||||
: undefined;
|
||||
|
||||
const startingMode: 'local' | 'remote' = startedBy === 'runner' ? 'remote' : 'local';
|
||||
|
||||
@@ -79,7 +82,10 @@ export async function runCodex(opts: {
|
||||
// 需要在首次附着 transcript 时回放已有历史;恢复已有 Hapi 会话时则保持原来的增量模式,避免重复灌入旧消息。
|
||||
const replayTranscriptHistoryOnStart = useLazyBootstrap || Boolean(opts.resumeSessionId && !opts.existingSessionId);
|
||||
|
||||
let currentPermissionMode: PermissionMode = opts.permissionMode ?? 'default';
|
||||
const persistedPermissionMode = sessionInfo.permissionMode ?? sessionInfo.metadata?.preferredPermissionMode;
|
||||
let currentPermissionMode: PermissionMode = opts.permissionMode
|
||||
?? (persistedPermissionMode && isPermissionModeAllowedForFlavor(persistedPermissionMode, 'codex') ? persistedPermissionMode as PermissionMode : undefined)
|
||||
?? 'default';
|
||||
let currentModel = opts.model;
|
||||
let currentModelReasoningEffort: ReasoningEffort | undefined = opts.modelReasoningEffort;
|
||||
let currentCollaborationMode: EnhancedMode['collaborationMode'] = opts.collaborationMode ?? 'default';
|
||||
@@ -401,6 +407,7 @@ export async function runCodex(opts: {
|
||||
modelReasoningEffort: currentModelReasoningEffort,
|
||||
collaborationMode: currentCollaborationMode,
|
||||
resumeSessionId: opts.resumeSessionId,
|
||||
sourceSessionId: codexSourceSessionId,
|
||||
replayTranscriptHistoryOnStart,
|
||||
onModeChange: createModeChangeHandler(session),
|
||||
onSessionReady: (instance) => {
|
||||
|
||||
@@ -18,6 +18,7 @@ export class CodexSession extends AgentSessionBase<EnhancedMode> {
|
||||
readonly startedBy: 'runner' | 'terminal';
|
||||
readonly startingMode: 'local' | 'remote';
|
||||
readonly replayTranscriptHistoryOnStart: boolean;
|
||||
readonly sourceSessionId?: string;
|
||||
localLaunchFailure: LocalLaunchFailure | null = null;
|
||||
|
||||
private transcriptPathCallbacks: Array<(path: string) => void> = [];
|
||||
@@ -40,6 +41,7 @@ export class CodexSession extends AgentSessionBase<EnhancedMode> {
|
||||
modelReasoningEffort?: SessionModelReasoningEffort;
|
||||
collaborationMode?: EnhancedMode['collaborationMode'];
|
||||
replayTranscriptHistoryOnStart?: boolean;
|
||||
sourceSessionId?: string;
|
||||
}) {
|
||||
super({
|
||||
api: opts.api,
|
||||
@@ -67,6 +69,7 @@ export class CodexSession extends AgentSessionBase<EnhancedMode> {
|
||||
this.startedBy = opts.startedBy;
|
||||
this.startingMode = opts.startingMode;
|
||||
this.replayTranscriptHistoryOnStart = opts.replayTranscriptHistoryOnStart ?? false;
|
||||
this.sourceSessionId = opts.sourceSessionId;
|
||||
this.permissionMode = opts.permissionMode;
|
||||
this.model = opts.model;
|
||||
this.modelReasoningEffort = opts.modelReasoningEffort;
|
||||
|
||||
Reference in New Issue
Block a user