|
| 1 | +/** |
| 2 | + * Fail-closed before_agent_run gate for Codex native app-server attempts. |
| 3 | + * |
| 4 | + * Runs once per admitted turn after the final turn prompt, developer |
| 5 | + * instructions, and history projection are settled, and before any |
| 6 | + * `thread/start`, `turn/start`, or `llm_input` emission, so a block starts no |
| 7 | + * Codex work at all. The core gate records its decision in the run-scoped |
| 8 | + * admission memo, so outer attempt re-dispatch replays it instead of charging |
| 9 | + * the gate again. |
| 10 | + */ |
| 11 | +import { |
| 12 | + embeddedAgentLog, |
| 13 | + formatErrorMessage, |
| 14 | + runAgentHarnessBeforeAgentRunHook, |
| 15 | + type EmbeddedRunAttemptParamsV2 as EmbeddedRunAttemptParams, |
| 16 | +} from "openclaw/plugin-sdk/agent-harness-runtime"; |
| 17 | +import { buildCodexTurnStartFailureResult } from "./attempt-results.js"; |
| 18 | +import type { EmbeddedRunAttemptResult } from "./attempt-terminal.js"; |
| 19 | +import { emitCodexAppServerEvent, runCodexAgentEndHook } from "./run-attempt-lifecycle.js"; |
| 20 | +import type { CodexAttemptResources } from "./run-attempt-resources.js"; |
| 21 | + |
| 22 | +type CodexBeforeAgentRunBlock = { blockedBy: string; message: string }; |
| 23 | + |
| 24 | +type CodexUserTurnRecorder = NonNullable<EmbeddedRunAttemptParams["userTurnTranscriptRecorder"]>; |
| 25 | +type CodexBlockedUserTurnMessage = Parameters<CodexUserTurnRecorder["persistBlocked"]>[0] & { |
| 26 | + idempotencyKey: string; |
| 27 | +}; |
| 28 | + |
| 29 | +/** |
| 30 | + * Returns a blocked attempt result when a plugin gate rejects this turn, or |
| 31 | + * `undefined` when the attempt may proceed to Codex startup. |
| 32 | + */ |
| 33 | +export async function runCodexAttemptBeforeAgentRunGate( |
| 34 | + resources: CodexAttemptResources, |
| 35 | +): Promise<{ result: EmbeddedRunAttemptResult } | undefined> { |
| 36 | + const { prompt, trajectoryRecorder, markTrajectoryEndRecorded, runCleanupStep } = resources; |
| 37 | + const { context, turnState, systemPromptReport, buildRenderedCodexDeveloperInstructions } = |
| 38 | + prompt; |
| 39 | + const { runtime, attemptTools, historyState, hookContext, hookRunner } = context; |
| 40 | + const { connection } = runtime; |
| 41 | + const { params, attemptStartedAt, abortFromUpstream } = connection; |
| 42 | + const outcome = await runAgentHarnessBeforeAgentRunHook({ |
| 43 | + event: { |
| 44 | + prompt: turnState.codexTurnPromptText, |
| 45 | + systemPrompt: buildRenderedCodexDeveloperInstructions(), |
| 46 | + messages: historyState.messages, |
| 47 | + channelId: hookContext.channelId, |
| 48 | + // Trusted attempt identity is hook-only evidence; it never becomes model |
| 49 | + // or tool input and grants no additional privilege to the turn. |
| 50 | + accountId: params.agentAccountId ?? undefined, |
| 51 | + senderId: params.senderId ?? undefined, |
| 52 | + senderIsOwner: params.senderIsOwner ?? undefined, |
| 53 | + }, |
| 54 | + ctx: hookContext, |
| 55 | + hookRunner, |
| 56 | + // Run-scoped memo owned by the outer run loop: outer re-dispatch of this |
| 57 | + // same admitted run replays its decision instead of recharging the gate. |
| 58 | + ...(params.beforeAgentRunAdmission ? { admission: params.beforeAgentRunAdmission } : {}), |
| 59 | + }); |
| 60 | + if (outcome.action !== "blocked") { |
| 61 | + return undefined; |
| 62 | + } |
| 63 | + |
| 64 | + const blockedUserMessage = buildCodexBlockedUserTurnMessage(params, outcome); |
| 65 | + await persistCodexBlockedUserTurn(params, blockedUserMessage); |
| 66 | + void emitCodexAppServerEvent(params, { |
| 67 | + stream: "codex_app_server.lifecycle", |
| 68 | + data: { phase: "before_agent_run_blocked", blockedBy: outcome.blockedBy }, |
| 69 | + }); |
| 70 | + trajectoryRecorder?.recordEvent("session.ended", { |
| 71 | + status: "error", |
| 72 | + promptError: outcome.message, |
| 73 | + }); |
| 74 | + markTrajectoryEndRecorded(); |
| 75 | + // agent_end carries the redacted blocked turn as evidence; the plugin-local |
| 76 | + // block reason stays inside the gate decision and never reaches consumers. |
| 77 | + const blockedMessagesSnapshot = [...historyState.messages, blockedUserMessage]; |
| 78 | + await runCodexAgentEndHook(params, { |
| 79 | + event: { |
| 80 | + messages: blockedMessagesSnapshot, |
| 81 | + success: false, |
| 82 | + error: outcome.message, |
| 83 | + durationMs: Date.now() - attemptStartedAt, |
| 84 | + }, |
| 85 | + ctx: hookContext, |
| 86 | + hookRunner, |
| 87 | + }); |
| 88 | + // Startup never ran, so no client lease, thread, route, relay, or sandbox |
| 89 | + // environment exists; only the surfaces materialized during tool preparation |
| 90 | + // and the upstream abort listener need releasing here. |
| 91 | + await runCleanupStep("codex-before-agent-run-scoped-mcp-dispose", () => |
| 92 | + attemptTools.scopedMcpTools?.dispose(), |
| 93 | + ); |
| 94 | + await runCleanupStep("codex-before-agent-run-scheduled-mcp-dispose", () => |
| 95 | + attemptTools.scheduledConfiguredMcp?.dispose(), |
| 96 | + ); |
| 97 | + await runCleanupStep("codex-before-agent-run-trajectory-flush", () => |
| 98 | + trajectoryRecorder?.flush(), |
| 99 | + ); |
| 100 | + await runCleanupStep("codex-before-agent-run-abort-listener", () => { |
| 101 | + params.abortSignal?.removeEventListener("abort", abortFromUpstream); |
| 102 | + }); |
| 103 | + return { |
| 104 | + result: buildCodexTurnStartFailureResult({ |
| 105 | + params, |
| 106 | + message: outcome.message, |
| 107 | + promptError: new Error(outcome.message), |
| 108 | + promptErrorSource: "hook:before_agent_run", |
| 109 | + messagesSnapshot: blockedMessagesSnapshot, |
| 110 | + systemPromptReport, |
| 111 | + }), |
| 112 | + }; |
| 113 | +} |
| 114 | + |
| 115 | +/** |
| 116 | + * Builds the redacted blocked user turn. Only the rendered block text is |
| 117 | + * retained; the idempotency key gives the canonical recorder a stable identity |
| 118 | + * for the blocked turn while its self-persistence guard owns re-dispatch dedupe. |
| 119 | + */ |
| 120 | +function buildCodexBlockedUserTurnMessage( |
| 121 | + params: EmbeddedRunAttemptParams, |
| 122 | + block: CodexBeforeAgentRunBlock, |
| 123 | +): CodexBlockedUserTurnMessage { |
| 124 | + const nowMs = Date.now(); |
| 125 | + return { |
| 126 | + role: "user", |
| 127 | + content: [{ type: "text", text: block.message }], |
| 128 | + timestamp: nowMs, |
| 129 | + idempotencyKey: `hook-block:before_agent_run:user:${params.runId}`, |
| 130 | + __openclaw: { |
| 131 | + beforeAgentRunBlocked: { blockedBy: block.blockedBy, blockedAt: nowMs }, |
| 132 | + }, |
| 133 | + }; |
| 134 | +} |
| 135 | + |
| 136 | +/** |
| 137 | + * Commits the blocked turn through the canonical user-turn recorder so blocked |
| 138 | + * bookkeeping and the persistence notification stay owned by that boundary. |
| 139 | + */ |
| 140 | +async function persistCodexBlockedUserTurn( |
| 141 | + params: EmbeddedRunAttemptParams, |
| 142 | + blockedUserMessage: CodexBlockedUserTurnMessage, |
| 143 | +): Promise<void> { |
| 144 | + const recorder = params.userTurnTranscriptRecorder; |
| 145 | + if (!recorder) { |
| 146 | + return; |
| 147 | + } |
| 148 | + try { |
| 149 | + const persisted = await recorder.persistBlocked(blockedUserMessage); |
| 150 | + if (!persisted) { |
| 151 | + return; |
| 152 | + } |
| 153 | + params.onUserMessagePersisted?.(persisted.message); |
| 154 | + } catch (error) { |
| 155 | + embeddedAgentLog.warn( |
| 156 | + `before_agent_run block: failed to persist redacted Codex user message: ${formatErrorMessage( |
| 157 | + error, |
| 158 | + )}`, |
| 159 | + ); |
| 160 | + } |
| 161 | +} |
0 commit comments