Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix: align Codex Auto permission review with Claude Auto (#306)

JiangJiahaoe7e39ff16422
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeAutoPermissionFallback.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeAutoPermissionFallback.test.ts
index 128d2469aa..b94284478c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeAutoPermissionFallback.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeAutoPermissionFallback.test.ts
@@ -119,11 +119,11 @@ describe('createClaudeAutoClassifierFailureObserver', () => {
),
).toBeUndefined();
expect(signals).toEqual([
- { sessionId: 'session-1', status: 429 },
- { sessionId: 'session-1', status: 400 },
- { sessionId: 'session-1', status: 401 },
- { sessionId: 'session-1', status: 404 },
- { sessionId: 'session-1', status: 503 },
+ { sessionId: 'session-1', agentKind: 'claude-code', status: 429 },
+ { sessionId: 'session-1', agentKind: 'claude-code', status: 400 },
+ { sessionId: 'session-1', agentKind: 'claude-code', status: 401 },
+ { sessionId: 'session-1', agentKind: 'claude-code', status: 404 },
+ { sessionId: 'session-1', agentKind: 'claude-code', status: 503 },
]);
});
@@ -276,6 +276,22 @@ describe('createClaudeAutoPermissionFallbackCoordinator', () => {
expect(codex.deps.persistPermissionModeIfAuto).not.toHaveBeenCalled();
});
+ it('downgrades a Codex Auto session when the signal identifies Codex', async () => {
+ const setPermissionMode = vi.fn(async () => {});
+ const { deps } = createDeps({
+ getSession: vi.fn(() => ({ agentKind: 'codex', setPermissionMode })),
+ });
+ const fallback = createClaudeAutoPermissionFallbackCoordinator(deps);
+
+ await expect(fallback({
+ sessionId: 'session-codex',
+ agentKind: 'codex',
+ status: 408,
+ })).resolves.toBe(true);
+ expect(setPermissionMode).toHaveBeenCalledWith('ask');
+ expect(deps.persistPermissionModeIfAuto).toHaveBeenCalledWith('session-codex');
+ });
+
it('rolls runtime back to persisted mode when persistence fails', async () => {
const { deps, setPermissionMode } = createDeps({
getSessionMeta: vi.fn(async () => ({ permissionMode: 'auto' as const })),
diff --git a/apps/desktop/src/main/maker-host/claude-auto-permission-fallback.ts b/apps/desktop/src/main/maker-host/claude-auto-permission-fallback.ts
index 57cae2327d..65b23f9bbf 100644
--- a/apps/desktop/src/main/maker-host/claude-auto-permission-fallback.ts
+++ b/apps/desktop/src/main/maker-host/claude-auto-permission-fallback.ts
@@ -1,5 +1,5 @@
/**
- * Claude Code Auto 权限分类器故障检测与会话降级。
+ * Auto 权限分类器故障检测与会话降级。
*
* 观察器只读 proxy 响应元数据,不改写响应;coordinator 在确认持久态仍为 auto 后,
* 把单个活跃 Claude 会话切到 ask。分类器不可用时 fail-to-prompt,而不是让所有工具
@@ -14,6 +14,8 @@ const CLASSIFIER_SYSTEM_PREFIX = 'You are a security monitor for autonomous AI c
/** Proxy 识别出的单次分类器故障。 */
export interface ClaudeAutoClassifierUnavailableSignal {
sessionId: string;
+ /** Legacy proxy signals omit this and default to Claude. */
+ agentKind?: 'claude-code' | 'codex';
status: number;
}
@@ -57,6 +59,13 @@ export function setClaudeAutoClassifierUnavailableListener(listener: Unavailable
unavailableListener = listener;
}
+/** Vendor adapters use the same host-owned persistence/broadcast coordinator. */
+export function notifyAutoPermissionClassifierUnavailable(
+ signal: ClaudeAutoClassifierUnavailableSignal,
+): void {
+ unavailableListener(signal);
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
@@ -128,7 +137,11 @@ export function createClaudeAutoClassifierFailureObserver(
if (!sessionId || !isClaudeAutoClassifierRequest(ctx.requestBody)) return undefined;
try {
- unavailableListener({ sessionId, status: ctx.status });
+ notifyAutoPermissionClassifierUnavailable({
+ sessionId,
+ agentKind: 'claude-code',
+ status: ctx.status,
+ });
} catch {
// observer 只能旁路通知;listener 异常不得影响上游响应 pipe。
}
@@ -171,6 +184,7 @@ export function createClaudeAutoPermissionFallbackCoordinator(
};
return async (signal) => {
+ const signalAgentKind = signal.agentKind ?? 'claude-code';
counters.detected += 1;
if (inFlight.has(signal.sessionId)) {
counters.dedupedRetries += 1;
@@ -186,7 +200,7 @@ export function createClaudeAutoPermissionFallbackCoordinator(
}
session = deps.getSession(signal.sessionId);
- if (!session || session.agentKind !== 'claude-code') {
+ if (!session || session.agentKind !== signalAgentKind) {
counters.skippedNonClaude += 1;
return false;
}
@@ -215,6 +229,7 @@ export function createClaudeAutoPermissionFallbackCoordinator(
deps.broadcast(event);
deps.logger.info('auto permission classifier unavailable; session downgraded to ask', {
sessionId: signal.sessionId,
+ agentKind: signalAgentKind,
status: signal.status,
counters: { ...counters },
});
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 93289c768a..3bb35c4260 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -76,6 +76,7 @@ import {
} from './runtime-configs.js';
import { getClaudeEndpoint, setClaudeProxyGatewayKeyReader, setClaudeProxyOAuthSpawnChecker } from './anthropic-compat-proxy-host.js';
import { claudeSubagentUsageBridge } from './claude-subagent-usage-bridge.js';
+import { notifyAutoPermissionClassifierUnavailable } from './claude-auto-permission-fallback.js';
import { hasClaudeAiOAuth } from './claude-credentials-store.js';
import {
clearCodexProxyAuthInjection,
@@ -430,6 +431,7 @@ export function getMaker(): Maker {
onCodexLocalModelsListed: (models) => {
setDiscoveredCodexModels(mapCodexAppServerModelsToCatalog(models));
},
+ onAutoPermissionClassifierUnavailable: notifyAutoPermissionClassifierUnavailable,
prepareCodexLocalCredentialModeSwitch: async (ctx) => {
const maker = _maker;
if (!maker) throw new Error('Maker is not initialized for Codex credential mode switch');
diff --git a/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts b/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
index d6d06256ca..1348e01978 100644
--- a/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
@@ -14,6 +14,7 @@ import { describe, it, expect } from 'vitest';
import { makerChatStore } from '@/lib/makerChatStore';
import type { Message } from '@/lib/ccAgent.types';
+import { ERROR_REASON_I18N_KEYS } from '@/components/chat/ErrorMessageCard';
const SESSION_ID = 's-err';
@@ -29,6 +30,12 @@ function errorRow(clientId: string, content: unknown): Message {
}
describe('mapServerMessages — persisted terminal error rows', () => {
+ it('maps Codex Auto reviewer failures to the stable localized reason key', () => {
+ expect(ERROR_REASON_I18N_KEYS['codex-auto-review-unavailable']).toBe(
+ 'logic.errors.codexAutoReviewUnavailable',
+ );
+ });
+
it('restores message text and errorReason from structured content', () => {
const mapped = makerChatStore.__mapServerMessagesForTest([
errorRow('e1', {
diff --git a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
index de11fa6919..f2f4a98487 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx
@@ -28,6 +28,7 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {
'turn-failed': 'logic.errors.turnFailed',
'silent-stop-exhausted': 'logic.errors.silentStopExhausted',
'permission-tighten-interrupt-failed': 'logic.errors.permissionTightenInterruptFailed',
+ 'codex-auto-review-unavailable': 'logic.errors.codexAutoReviewUnavailable',
};
export function ErrorMessageCard({ message, reason }: { message: string; reason?: string }) {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 9f28fc3e46..d237fcfb7e 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6501,7 +6501,8 @@
"qrExpired": "QR code expired, please start again",
"registrationFailed": "Creation failed, please retry later",
"silentStopExhausted": "The model returned empty responses repeatedly; auto-resume is paused. Click \"Continue\" to resume the task.",
- "permissionTightenInterruptFailed": "Failed to stop the running task while tightening permissions; it may keep running without approval prompts until it finishes. Stop it manually if needed."
+ "permissionTightenInterruptFailed": "Failed to stop the running task while tightening permissions; it may keep running without approval prompts until it finishes. Stop it manually if needed.",
+ "codexAutoReviewUnavailable": "Auto-review is temporarily unavailable. The current action was blocked and permissions switched to Default. Retry the request; Cindy will ask when needed."
},
"validation": {
"feishuFieldsRequired": "App ID and App Secret are both required",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 7d6154f931..e89c8aa583 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6491,7 +6491,8 @@
"qrExpired": "QR コードが期限切れです。最初からやり直してください",
"registrationFailed": "作成に失敗しました。後でもう一度お試しください",
"silentStopExhausted": "モデルが空の応答を繰り返し返したため、自動再開を一時停止しました。「続行」をクリックしてタスクを再開してください。",
- "permissionTightenInterruptFailed": "権限を厳格化する際に実行中のタスクを停止できませんでした。タスクは終了まで確認なしで実行され続ける可能性があります。必要に応じて手動で停止してください。"
+ "permissionTightenInterruptFailed": "権限を厳格化する際に実行中のタスクを停止できませんでした。タスクは終了まで確認なしで実行され続ける可能性があります。必要に応じて手動で停止してください。",
+ "codexAutoReviewUnavailable": "自動レビューは一時的に利用できません。現在の操作をブロックし、デフォルト権限に切り替えました。もう一度実行してください。必要な場合は確認します。"
},
"validation": {
"feishuFieldsRequired": "App ID と App Secret の両方を入力してください",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e8cf1b3c4c..1c194273cb 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6491,7 +6491,8 @@
"qrExpired": "QR 코드가 만료됨. 다시 시작하세요",
"registrationFailed": "생성 실패. 잠시 후 다시 시도하세요",
"silentStopExhausted": "모델이 빈 응답을 반복해서 반환하여 자동 재개가 일시 중지되었습니다. \"계속\"을 클릭하여 작업을 재개하세요.",
- "permissionTightenInterruptFailed": "권한을 강화하는 동안 실행 중인 작업을 중지하지 못했습니다. 작업이 끝날 때까지 확인 없이 계속 실행될 수 있습니다. 필요하면 수동으로 중지하세요."
+ "permissionTightenInterruptFailed": "권한을 강화하는 동안 실행 중인 작업을 중지하지 못했습니다. 작업이 끝날 때까지 확인 없이 계속 실행될 수 있습니다. 필요하면 수동으로 중지하세요.",
+ "codexAutoReviewUnavailable": "자동 리뷰를 일시적으로 사용할 수 없습니다. 현재 작업을 차단하고 기본 권한으로 전환했습니다. 다시 시도하세요. 필요한 경우 확인을 요청합니다."
},
"validation": {
"feishuFieldsRequired": "App ID와 App Secret 둘 다 입력해야 합니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 7574c2c686..175b1e772c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6491,7 +6491,8 @@
"qrExpired": "二维码已过期,请重新开始",
"registrationFailed": "创建失败,请稍后重试",
"silentStopExhausted": "模型连续多次返回空响应,自动续跑已暂停。点击「继续」恢复任务。",
- "permissionTightenInterruptFailed": "收紧权限时未能停止正在运行的任务,它可能会继续免确认执行直到结束;如有需要请手动停止。"
+ "permissionTightenInterruptFailed": "收紧权限时未能停止正在运行的任务,它可能会继续免确认执行直到结束;如有需要请手动停止。",
+ "codexAutoReviewUnavailable": "自动审批暂时不可用,当前操作已阻止并切换为默认权限。请重试,需要时会询问你。"
},
"validation": {
"feishuFieldsRequired": "App ID 和 App Secret 都需要填写",
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index b9818055bb..d5ed36c17e 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -2322,7 +2322,9 @@ export function handleStreamEvent(
? i18n.t('logic.errors.turnFailed')
: reason === 'silent-stop-exhausted'
? i18n.t('logic.errors.silentStopExhausted')
- : decodeRemoteErrorMessage(safeErrMsg);
+ : reason === 'codex-auto-review-unavailable'
+ ? i18n.t('logic.errors.codexAutoReviewUnavailable')
+ : decodeRemoteErrorMessage(safeErrMsg);
const isTerminalError = isTerminalErrorData(event.data);
if (!isTerminalError) {
return {
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 794d2ea98f..16b1b64f64 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -210,6 +210,19 @@ export interface AgentDeps {
models: readonly CodexModelListItem[],
) => void | Promise<void>;
+ /**
+ * Host-owned Auto permission fallback. A vendor reviewer timeout/unavailable
+ * result has already blocked the current action; the host persists this session
+ * from Auto to Ask and broadcasts the selector/toast update. Fire-and-forget:
+ * classifier failure handling must never hold the vendor notification loop.
+ */
+ onAutoPermissionClassifierUnavailable?: (args: {
+ sessionId: string;
+ agentKind: 'claude-code' | 'codex';
+ /** HTTP status when available; Codex reviewer timeout/failure use synthetic 408/500. */
+ status: number;
+ }) => void;
+
/**
* Codex-only: bind app-server thread ids back to xdt-maker session context
* for host-owned HTTP MCP bridges. Missing hooks keep the old no-session
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index 26a6cda2d5..5916ce64bd 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -62,6 +62,9 @@ import {
type AccountRateLimitsUpdatedNotification,
type ThreadStatusChangedNotification,
type ThreadSettingsUpdatedNotification,
+ type ItemGuardianApprovalReviewStartedNotification,
+ type ItemGuardianApprovalReviewCompletedNotification,
+ type GuardianWarningNotification,
} from './protocol.js';
/**
@@ -88,6 +91,9 @@ const SUBSCRIBED_METHODS = [
'thread/status/changed', // 线程级 active_flags (waiting on approval / user input) — turn lifecycle 部分我们自己拼
'thread/settings/updated', // 中途 thread/settings/update 后 server 回带的权威设置快照 (serviceTier / model / effort)
'serverRequest/resolved', // 原生 requestUserInput / approval 请求被 server 端自动清理
+ 'item/autoApprovalReview/started',
+ 'item/autoApprovalReview/completed',
+ 'guardianWarning',
'error',
] as const;
@@ -147,6 +153,10 @@ export interface ThreadEventHandlers {
*/
threadSettingsUpdated?: (params: ThreadSettingsUpdatedNotification['params']) => void;
serverRequestResolved?: (params: ServerRequestResolvedNotification['params']) => void;
+ /** Codex built-in Guardian auto-review lifecycle (Auto permission mode). */
+ autoApprovalReviewStarted?: (params: ItemGuardianApprovalReviewStartedNotification) => void;
+ autoApprovalReviewCompleted?: (params: ItemGuardianApprovalReviewCompletedNotification) => void;
+ guardianWarning?: (params: GuardianWarningNotification) => void;
error?: (params: ErrorNotification['params']) => void;
// ── ServerRequest (Phase 2 approval) ─────────────────────────────────────
@@ -647,6 +657,9 @@ export class AppServerHost {
case 'thread/status/changed': fn = handlers.threadStatusChanged as (p: never) => void; break;
case 'thread/settings/updated': fn = handlers.threadSettingsUpdated as (p: never) => void; break;
case 'serverRequest/resolved': fn = handlers.serverRequestResolved as (p: never) => void; break;
+ case 'item/autoApprovalReview/started': fn = handlers.autoApprovalReviewStarted as (p: never) => void; break;
+ case 'item/autoApprovalReview/completed': fn = handlers.autoApprovalReviewCompleted as (p: never) => void; break;
+ case 'guardianWarning': fn = handlers.guardianWarning as (p: never) => void; break;
case 'error': fn = handlers.error as (p: never) => void; break;
}
if (!fn) {
diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.ts
index a2734755a2..e67053331f 100644
--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts
+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts
@@ -944,6 +944,85 @@ export interface ErrorNotification {
};
}
+/** Codex 0.144.x automatic Guardian approval review lifecycle. */
+export type GuardianApprovalReviewStatus =
+ | 'inProgress'
+ | 'approved'
+ | 'denied'
+ | 'timedOut'
+ | 'aborted';
+export type GuardianRiskLevel = 'low' | 'medium' | 'high' | 'critical';
+export type GuardianUserAuthorization = 'unknown' | 'low' | 'medium' | 'high';
+
+export type GuardianCommandSource = 'shell' | 'unifiedExec';
+export type GuardianNetworkProtocol = string;
+
+/** The action shape emitted by item/autoApprovalReview/* notifications. */
+export type GuardianApprovalReviewAction =
+ | { type: 'command'; source: GuardianCommandSource; command: string; cwd: string }
+ | { type: 'execve'; source: GuardianCommandSource; program: string; argv: string[]; cwd: string }
+ | { type: 'applyPatch'; cwd: string; files: string[] }
+ | { type: 'networkAccess'; target: string; host: string; protocol: GuardianNetworkProtocol; port: number }
+ | {
+ type: 'mcpToolCall';
+ server: string;
+ toolName: string;
+ connectorId: string | null;
+ connectorName: string | null;
+ toolTitle: string | null;
+ }
+ | { type: 'requestPermissions'; reason: string | null; permissions: Record<string, unknown> };
+
+export interface GuardianApprovalReview {
+ status: GuardianApprovalReviewStatus;
+ riskLevel: GuardianRiskLevel | null;
+ userAuthorization: GuardianUserAuthorization | null;
+ rationale: string | null;
+}
+
+export interface ItemGuardianApprovalReviewStartedNotification {
+ threadId: string;
+ turnId: string;
+ startedAtMs: number;
+ reviewId: string;
+ targetItemId: string | null;
+ review: GuardianApprovalReview;
+ action: GuardianApprovalReviewAction;
+}
+
+export interface ItemGuardianApprovalReviewCompletedNotification {
+ threadId: string;
+ turnId: string;
+ startedAtMs: number;
+ completedAtMs: number;
+ reviewId: string;
+ targetItemId: string | null;
+ decisionSource: 'agent';
+ review: GuardianApprovalReview;
+ action: GuardianApprovalReviewAction;
+}
+
+export interface GuardianWarningNotification {
+ threadId: string;
+ message: string;
+}
+
+/** JSON-RPC envelopes for the Guardian notification params above. */
+export interface ItemGuardianApprovalReviewStartedServerNotification {
+ method: 'item/autoApprovalReview/started';
+ params: ItemGuardianApprovalReviewStartedNotification;
+}
+
+export interface ItemGuardianApprovalReviewCompletedServerNotification {
+ method: 'item/autoApprovalReview/completed';
+ params: ItemGuardianApprovalReviewCompletedNotification;
+}
+
+export interface GuardianWarningServerNotification {
+ method: 'guardianWarning';
+ params: GuardianWarningNotification;
+}
+
/**
* v2 ThreadItem 的 envelope — 至少有 id / type, 余字段按 type narrow。
* 完整 union 在 v2.rs ThreadItem (太大, 不在 Phase 1 全列)。translator 用
@@ -970,6 +1049,9 @@ export type ServerNotification =
| ThreadStatusChangedNotification
| ThreadSettingsUpdatedNotification
| ServerRequestResolvedNotification
+ | ItemGuardianApprovalReviewStartedServerNotification
+ | ItemGuardianApprovalReviewCompletedServerNotification
+ | GuardianWarningServerNotification
| ErrorNotification;
// ── 方法名常量 (避免 string typo) ────────────────────────────────────────────
@@ -1000,6 +1082,9 @@ export const Method = {
PermissionsRequestApproval: 'item/permissions/requestApproval',
ToolRequestUserInput: 'item/tool/requestUserInput',
DynamicToolCall: 'item/tool/call',
+ ItemGuardianApprovalReviewStarted: 'item/autoApprovalReview/started',
+ ItemGuardianApprovalReviewCompleted: 'item/autoApprovalReview/completed',
+ GuardianWarning: 'guardianWarning',
} as const;
export type {
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 811af9c45b..810f0229f8 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -3286,6 +3286,227 @@ describe('CodexAgent MCP thread context hooks', () => {
await handle.close();
});
+ it('keeps a denied Guardian auto-review fail-closed without opening a user override prompt', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-guardian-denial-fail-closed',
+ model: 'gpt-5.5',
+ workingDir: '/repo',
+ permissionMode: 'auto',
+ });
+ const resolver = vi.fn(async () => ({ kind: 'permission' as const, behavior: 'allow' as const }));
+ handle.setInteractionResolver(resolver);
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.autoApprovalReviewCompleted) throw new Error('expected autoApprovalReviewCompleted');
+
+ handlers.autoApprovalReviewCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-guardian',
+ startedAtMs: 1_000,
+ completedAtMs: 1_042,
+ reviewId: 'review-denied-1',
+ targetItemId: 'item-command-1',
+ decisionSource: 'agent',
+ review: {
+ status: 'denied',
+ riskLevel: 'high',
+ userAuthorization: 'low',
+ rationale: 'The command removes persistent data.',
+ },
+ action: {
+ type: 'command',
+ source: 'shell',
+ command: 'rm -f /tmp/data.db',
+ cwd: '/repo',
+ },
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(resolver).not.toHaveBeenCalled();
+ expect(host.request.mock.calls.some(([method]) => method === 'thread/approveGuardianDeniedAction')).toBe(false);
+ await handle.close();
+ });
+
+ it('surfaces Guardian auto-review timeouts as visible non-terminal errors', async () => {
+ const classifierUnavailable = vi.fn();
+ const agent = new CodexAgent(createDeps({}, {
+ onAutoPermissionClassifierUnavailable: classifierUnavailable,
+ }));
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-guardian-timeout',
+ model: 'gpt-5.5',
+ workingDir: '/repo',
+ permissionMode: 'auto',
+ });
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.autoApprovalReviewCompleted) throw new Error('expected autoApprovalReviewCompleted');
+ handlers.autoApprovalReviewCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-guardian',
+ startedAtMs: 1,
+ completedAtMs: 2,
+ reviewId: 'review-timeout-1',
+ targetItemId: 'item-network-1',
+ decisionSource: 'agent',
+ review: { status: 'timedOut', riskLevel: null, userAuthorization: null, rationale: 'review timed out' },
+ action: { type: 'networkAccess', target: 'https://example.com', host: 'example.com', protocol: 'https', port: 443 },
+ });
+ expect(classifierUnavailable).not.toHaveBeenCalled();
+ await expect(nextEvent(iterator)).resolves.toMatchObject({
+ type: 'error',
+ data: {
+ reason: 'codex-auto-review-unavailable',
+ isTerminal: false,
+ reviewRationale: 'review timed out',
+ },
+ });
+ await Promise.resolve();
+ expect(classifierUnavailable).toHaveBeenCalledWith({
+ sessionId: 'session-guardian-timeout',
+ agentKind: 'codex',
+ status: 408,
+ });
+ await handle.close();
+ });
+
+ it('switches the local runtime to Ask before notifying the host about a Guardian timeout', async () => {
+ const classifierUnavailable = vi.fn();
+ const agent = new CodexAgent(createDeps({}, {
+ onAutoPermissionClassifierUnavailable: classifierUnavailable,
+ }));
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-after-guardian-timeout' } };
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-guardian-timeout-runtime',
+ model: 'gpt-5.5',
+ workingDir: '/repo',
+ permissionMode: 'auto',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.autoApprovalReviewCompleted) throw new Error('expected autoApprovalReviewCompleted');
+
+ handlers.autoApprovalReviewCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-guardian',
+ startedAtMs: 1,
+ completedAtMs: 2,
+ reviewId: 'review-timeout-runtime',
+ targetItemId: 'item-network-runtime',
+ decisionSource: 'agent',
+ review: { status: 'timedOut', riskLevel: null, userAuthorization: null, rationale: null },
+ action: { type: 'networkAccess', target: 'https://example.com', host: 'example.com', protocol: 'https', port: 443 },
+ });
+
+ expect(classifierUnavailable).not.toHaveBeenCalled();
+ await handle.send({ type: 'user', content: 'retry after fallback' });
+ const turnParams = host.request.mock.calls.find(([method]) => method === Method.TurnStart)?.[1] as {
+ approvalPolicy?: string;
+ approvalsReviewer?: string;
+ };
+ expect(turnParams.approvalPolicy).toBe('on-request');
+ expect(turnParams).not.toHaveProperty('approvalsReviewer');
+ expect(classifierUnavailable).toHaveBeenCalledWith({
+ sessionId: 'session-guardian-timeout-runtime',
+ agentKind: 'codex',
+ status: 408,
+ });
+ await handle.close();
+ });
+
+ it('treats Guardian reviewer failures as unavailable and contains host callback errors', async () => {
+ const classifierUnavailable = vi.fn(() => {
+ throw new Error('host callback failed');
+ });
+ const agent = new CodexAgent(createDeps({}, {
+ onAutoPermissionClassifierUnavailable: classifierUnavailable,
+ }));
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-guardian-reviewer-failure',
+ model: 'gpt-5.5',
+ workingDir: '/repo',
+ permissionMode: 'auto',
+ });
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.autoApprovalReviewCompleted) throw new Error('expected autoApprovalReviewCompleted');
+
+ handlers.autoApprovalReviewCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-guardian',
+ startedAtMs: 1,
+ completedAtMs: 2,
+ reviewId: 'review-failed-1',
+ targetItemId: 'item-command-failed',
+ decisionSource: 'agent',
+ review: {
+ status: 'denied',
+ riskLevel: 'high',
+ userAuthorization: 'unknown',
+ rationale: 'Automatic approval review failed: invalid reviewer response',
+ },
+ action: { type: 'command', source: 'shell', command: 'pwd', cwd: '/repo' },
+ });
+ expect(classifierUnavailable).not.toHaveBeenCalled();
+
+ await expect(nextEvent(iterator)).resolves.toMatchObject({
+ type: 'error',
+ data: { reason: 'codex-auto-review-unavailable', isTerminal: false },
+ });
+ await Promise.resolve();
+ expect(classifierUnavailable).toHaveBeenCalledWith({
+ sessionId: 'session-guardian-reviewer-failure',
+ agentKind: 'codex',
+ status: 500,
+ });
+ await handle.close();
+ });
+
+ it('ignores a stale Guardian timeout from a previous turn', async () => {
+ const classifierUnavailable = vi.fn();
+ const agent = new CodexAgent(createDeps({}, {
+ onAutoPermissionClassifierUnavailable: classifierUnavailable,
+ }));
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-current' } };
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-guardian-stale-timeout',
+ model: 'gpt-5.5',
+ workingDir: '/repo',
+ permissionMode: 'auto',
+ });
+ await handle.send({ type: 'user', content: 'current turn' });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.autoApprovalReviewCompleted) throw new Error('expected autoApprovalReviewCompleted');
+
+ handlers.autoApprovalReviewCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-previous',
+ startedAtMs: 1,
+ completedAtMs: 2,
+ reviewId: 'review-stale-timeout',
+ targetItemId: 'item-stale',
+ decisionSource: 'agent',
+ review: { status: 'timedOut', riskLevel: null, userAuthorization: null, rationale: null },
+ action: { type: 'command', source: 'shell', command: 'pwd', cwd: '/repo' },
+ });
+
+ await Promise.resolve();
+ expect(classifierUnavailable).not.toHaveBeenCalled();
+ const turnParams = host.request.mock.calls.find(([method]) => method === Method.TurnStart)?.[1] as {
+ approvalsReviewer?: string;
+ };
+ expect(turnParams.approvalsReviewer).toBe('auto_review');
+ await handle.close();
+ });
+
it('interrupts an active Auto-review turn when switching back to Ask', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent, (method) => {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 131c62f2cc..84a0c4b65b 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -104,6 +104,9 @@ import {
type AskForApproval,
type ApprovalsReviewer,
type ApprovalDecision,
+ type ItemGuardianApprovalReviewCompletedNotification,
+ type ItemGuardianApprovalReviewStartedNotification,
+ type GuardianWarningNotification,
type CodexModelListResponse,
type CommandExecutionRequestApprovalParams,
type CommandExecutionRequestApprovalResponse,
@@ -2472,6 +2475,7 @@ export class CodexAgent extends BaseAgent {
forcePrompt?: boolean;
}
const pendingApprovals = new Map<string, PendingEntry>();
+ const seenGuardianReviewIds = new Set<string>();
const userInputBroker = new CodexInteractionBroker<ToolRequestUserInputResponse>();
const dynamicToolBroker = new CodexInteractionBroker<DynamicToolCallResponse>();
const activeToolContexts = new Map<string, ActiveToolContext>();
@@ -3539,6 +3543,97 @@ export class CodexAgent extends BaseAgent {
flushDeferredTerminalTurnCompletionsIfIdle();
}
+ const GUARDIAN_REVIEW_FAILURE_PREFIX = 'Automatic approval review failed:';
+
+ const emitGuardianUnavailable = (params: ItemGuardianApprovalReviewCompletedNotification): void => {
+ const timedOut = params.review.status === 'timedOut';
+ eventQueue.push({
+ type: 'error',
+ data: {
+ // Renderer uses reason for localized copy. Keep an English fallback for
+ // non-renderer consumers while always stating the blocked action + downgrade.
+ message: timedOut
+ ? 'Codex automatic approval review timed out. The action was blocked and this session is switching to Ask mode.'
+ : 'Codex automatic approval review failed. The action was blocked and this session is switching to Ask mode.',
+ isTerminal: false,
+ reason: 'codex-auto-review-unavailable',
+ reviewId: params.reviewId,
+ reviewRationale: params.review.rationale,
+ },
+ source: 'codex',
+ });
+ };
+
+ /**
+ * Close the race between a Guardian failure notification and the async host
+ * persistence coordinator. The current action is already blocked; changing the
+ * local mode synchronously ensures a message sent immediately afterwards starts
+ * in Ask instead of launching another auto_review turn that is then interrupted.
+ */
+ const switchAutoRuntimeToAskImmediately = (): boolean => {
+ if (mutablePermissionMode !== 'auto') return false;
+ dismissAllPending('permission_mode_changed_to_ask', 'deny');
+ mutablePermissionMode = 'ask';
+ if (!closed && turnLaunchedUnattended) {
+ if (currentTurnId !== null) {
+ void interruptTurnForPermissionTighten(currentTurnId);
+ } else if (isTurnStartPending) {
+ pendingTightenInterrupt = true;
+ }
+ }
+ return true;
+ };
+
+ const notifyAutoPermissionClassifierUnavailable = (
+ params: ItemGuardianApprovalReviewCompletedNotification,
+ ): void => {
+ if (!switchAutoRuntimeToAskImmediately() || typeof opts.sessionId !== 'string') return;
+ const notify = this.deps.onAutoPermissionClassifierUnavailable;
+ if (!notify) return;
+ const status = params.review.status === 'timedOut' ? 408 : 500;
+ queueMicrotask(() => {
+ try {
+ notify({
+ sessionId: opts.sessionId as string,
+ agentKind: 'codex',
+ status,
+ });
+ } catch (error) {
+ log.warn('Codex Auto fallback notification threw', {
+ reviewId: params.reviewId,
+ error: String(error),
+ });
+ }
+ });
+ };
+
+ const handleGuardianReviewCompleted = (params: ItemGuardianApprovalReviewCompletedNotification): void => {
+ if (seenGuardianReviewIds.has(params.reviewId)) return;
+ seenGuardianReviewIds.add(params.reviewId);
+ const rationale = params.review.rationale?.trim();
+ const failedClosedBecauseReviewerUnavailable =
+ params.review.status === 'denied' &&
+ rationale?.startsWith(GUARDIAN_REVIEW_FAILURE_PREFIX) === true;
+ if (params.review.status === 'timedOut' || failedClosedBecauseReviewerUnavailable) {
+ emitGuardianUnavailable(params);
+ notifyAutoPermissionClassifierUnavailable(params);
+ return;
+ }
+ if (params.review.status === 'denied') {
+ // Match Claude Auto: a real classifier verdict is authoritative. Codex has
+ // already blocked the action and returned the denial to the model; do not
+ // weaken Auto by offering a user override prompt.
+ log.info('Codex automatic approval review denied action', {
+ reviewId: params.reviewId,
+ turnId: params.turnId,
+ targetItemId: params.targetItemId,
+ actionType: params.action.type,
+ riskLevel: params.review.riskLevel,
+ rationale: params.review.rationale,
+ });
+ }
+ };
+
// ── subscribeThread: notification 路由 + approval handlers ─────────────
const handlers: ThreadEventHandlers = {
threadStarted: (params) => {
@@ -3695,6 +3790,24 @@ export class CodexAgent extends BaseAgent {
});
}
},
+ autoApprovalReviewStarted: (params: ItemGuardianApprovalReviewStartedNotification) => {
+ if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
+ log.debug('Codex automatic approval review started', {
+ reviewId: params.reviewId,
+ turnId: params.turnId,
+ targetItemId: params.targetItemId,
+ actionType: params.action.type,
+ });
+ },
+ autoApprovalReviewCompleted: (params) => {
+ if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
+ handleGuardianReviewCompleted(params);
+ },
+ guardianWarning: (params: GuardianWarningNotification) => {
+ // The completed review carries the actionable denial/timeout details. Keep the
+ // warning for diagnostics to avoid rendering a duplicate error card.
+ log.warn('Codex Guardian warning', { threadId: params.threadId, message: params.message });
+ },
error: (params) => {
if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
const isTerminalError = params.willRetry !== true;