|
| 1 | +/** |
| 2 | + * Prepares stream subscription, tool execution, and the active run queue. |
| 3 | + */ |
| 4 | +import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce"; |
| 5 | +import { isSilentReplyText, SILENT_REPLY_TOKEN } from "../../../auto-reply/tokens.js"; |
| 6 | +import { |
| 7 | + freezeDiagnosticTraceContext, |
| 8 | + type DiagnosticTraceContext, |
| 9 | +} from "../../../infra/diagnostic-trace-context.js"; |
| 10 | +import { formatErrorMessage } from "../../../infra/errors.js"; |
| 11 | +import type { AssistantMessage } from "../../../llm/types.js"; |
| 12 | +import { |
| 13 | + buildAgentHookContextChannelFields, |
| 14 | + buildAgentHookContextIdentityFields, |
| 15 | +} from "../../../plugins/hook-agent-context.js"; |
| 16 | +import { getGlobalHookRunner } from "../../../plugins/hook-runner-global.js"; |
| 17 | +import { recordStructuredReplayTrustForToolCall } from "../../agent-tools.before-tool-call.js"; |
| 18 | +import { subscribeEmbeddedAgentSession } from "../../embedded-agent-subscribe.js"; |
| 19 | +import { runAgentHarnessBeforeAgentFinalizeHook } from "../../harness/lifecycle-hook-helpers.js"; |
| 20 | +import { |
| 21 | + AGENT_RUN_RESTART_ABORT_STOP_REASON, |
| 22 | + createAgentRunRestartAbortError, |
| 23 | + isAgentRunRestartAbortReason, |
| 24 | +} from "../../run-termination.js"; |
| 25 | +import type { AgentMessage } from "../../runtime/index.js"; |
| 26 | +import type { AgentSession } from "../../sessions/index.js"; |
| 27 | +import { |
| 28 | + projectToolSearchTargetTranscriptMessages, |
| 29 | + type ToolSearchCatalogToolExecutor, |
| 30 | + type ToolSearchTargetTranscriptProjection, |
| 31 | +} from "../../tool-search.js"; |
| 32 | +import { log } from "../logger.js"; |
| 33 | +import { |
| 34 | + clearActiveEmbeddedRun, |
| 35 | + type EmbeddedAgentQueueHandle, |
| 36 | + setActiveEmbeddedRun, |
| 37 | +} from "../runs.js"; |
| 38 | +import type { EmbeddedAttemptClientToolCallSlot } from "./attempt-result.js"; |
| 39 | +import { |
| 40 | + requiresCompletionRequiredAsyncTaskWait, |
| 41 | + type AsyncStartedToolMeta, |
| 42 | +} from "./attempt.async-tasks.js"; |
| 43 | +import { steerActiveSessionWithOptionalDeliveryWait } from "./attempt.queue-message.js"; |
| 44 | +import { buildEmbeddedSubscriptionParams } from "./attempt.subscription-cleanup.js"; |
| 45 | +import { |
| 46 | + resolveFinalAssistantRawText, |
| 47 | + resolveFinalAssistantVisibleText, |
| 48 | + resolveReportedModelRef, |
| 49 | +} from "./helpers.js"; |
| 50 | +import { notifyToolActivity } from "./tool-activity-heartbeat.js"; |
| 51 | +import type { EmbeddedRunAttemptParams } from "./types.js"; |
| 52 | + |
| 53 | +type HookRunner = ReturnType<typeof getGlobalHookRunner>; |
| 54 | +type StreamRunState = { |
| 55 | + aborted: boolean; |
| 56 | + promptError: unknown; |
| 57 | + timedOut: boolean; |
| 58 | + yieldDetected: boolean; |
| 59 | +}; |
| 60 | + |
| 61 | +type AttemptStreamQueueHandle = EmbeddedAgentQueueHandle & { |
| 62 | + kind: "embedded"; |
| 63 | + cancel: (reason?: "user_abort" | "restart" | "superseded") => void; |
| 64 | +}; |
| 65 | + |
| 66 | +export function prepareEmbeddedAttemptStream(input: { |
| 67 | + attempt: EmbeddedRunAttemptParams; |
| 68 | + activeSession: AgentSession; |
| 69 | + runtimeChannel?: string; |
| 70 | + hookRunner: HookRunner; |
| 71 | + hookAgentId: string; |
| 72 | + diagnosticTrace: DiagnosticTraceContext; |
| 73 | + clientToolCallSlots: readonly EmbeddedAttemptClientToolCallSlot[]; |
| 74 | + toolSearchTargetTranscriptProjections: ToolSearchTargetTranscriptProjection[]; |
| 75 | + isReplaySafeTool: (tool: Parameters<ToolSearchCatalogToolExecutor>[0]["tool"]) => boolean; |
| 76 | + runAbortController: AbortController; |
| 77 | + abortRun: (isTimeout?: boolean, reason?: unknown) => void; |
| 78 | + markExternalAbort: () => void; |
| 79 | + getRunState: () => StreamRunState; |
| 80 | + hasDeliveredSourceReply: () => boolean; |
| 81 | + markSourceReplyDelivered: () => void; |
| 82 | + onBlockReply: EmbeddedRunAttemptParams["onBlockReply"]; |
| 83 | + onBlockReplyFlush: EmbeddedRunAttemptParams["onBlockReplyFlush"]; |
| 84 | + sandboxSessionKey: string; |
| 85 | + builtinToolNames: ReadonlySet<string>; |
| 86 | + replaySafeToolNames: ReadonlySet<string>; |
| 87 | +}) { |
| 88 | + const attempt = input.attempt; |
| 89 | + const hookRunner = input.hookRunner; |
| 90 | + let beforeAgentFinalizeRevisionReason: string | undefined; |
| 91 | + const onBeforeTerminalDelivery = hookRunner?.hasHooks("before_agent_finalize") |
| 92 | + ? async (event: { |
| 93 | + messages: AgentMessage[]; |
| 94 | + willRetry: boolean; |
| 95 | + lastAssistant?: AgentMessage; |
| 96 | + assistantTexts: readonly string[]; |
| 97 | + hasAssistantVisibleText: boolean; |
| 98 | + isError: boolean; |
| 99 | + incompleteTerminalAssistant: boolean; |
| 100 | + hadDeterministicSideEffect: boolean; |
| 101 | + }): Promise<void | { suppressTerminalDelivery: true }> => { |
| 102 | + if ( |
| 103 | + beforeAgentFinalizeRevisionReason || |
| 104 | + event.willRetry || |
| 105 | + event.isError || |
| 106 | + event.incompleteTerminalAssistant || |
| 107 | + !event.hasAssistantVisibleText |
| 108 | + ) { |
| 109 | + return; |
| 110 | + } |
| 111 | + const lastAssistant = event.lastAssistant as AssistantMessage | undefined; |
| 112 | + const lastAssistantMessage = |
| 113 | + normalizeOptionalString(resolveFinalAssistantVisibleText(lastAssistant)) ?? |
| 114 | + normalizeOptionalString(resolveFinalAssistantRawText(lastAssistant)) ?? |
| 115 | + normalizeOptionalString(event.assistantTexts.join("\n\n")); |
| 116 | + if (!lastAssistantMessage) { |
| 117 | + return; |
| 118 | + } |
| 119 | + const state = input.getRunState(); |
| 120 | + const hasCompletedClientToolCall = input.clientToolCallSlots.some((slot) => slot.completed); |
| 121 | + const silentFinalReply = |
| 122 | + attempt.silentExpected && isSilentReplyText(lastAssistantMessage, SILENT_REPLY_TOKEN); |
| 123 | + if ( |
| 124 | + state.aborted || |
| 125 | + state.promptError || |
| 126 | + state.timedOut || |
| 127 | + hasCompletedClientToolCall || |
| 128 | + state.yieldDetected || |
| 129 | + silentFinalReply |
| 130 | + ) { |
| 131 | + return; |
| 132 | + } |
| 133 | + const hookMessages = projectToolSearchTargetTranscriptMessages( |
| 134 | + input.activeSession.messages.slice(), |
| 135 | + input.toolSearchTargetTranscriptProjections, |
| 136 | + ); |
| 137 | + const reportedModelRef = resolveReportedModelRef({ |
| 138 | + provider: attempt.provider, |
| 139 | + model: attempt.modelId, |
| 140 | + assistant: lastAssistant, |
| 141 | + }); |
| 142 | + const maxRevisionAttempts = attempt.maxBeforeAgentFinalizeRevisions ?? 0; |
| 143 | + if ( |
| 144 | + maxRevisionAttempts > 0 && |
| 145 | + (attempt.beforeAgentFinalizeRevisionAttempts ?? 0) >= maxRevisionAttempts |
| 146 | + ) { |
| 147 | + log.warn( |
| 148 | + `before_agent_finalize revision limit reached; finalizing ` + |
| 149 | + `runId=${attempt.runId} sessionId=${attempt.sessionId} ` + |
| 150 | + `attempts=${attempt.beforeAgentFinalizeRevisionAttempts ?? 0}/${maxRevisionAttempts}`, |
| 151 | + ); |
| 152 | + return; |
| 153 | + } |
| 154 | + const outcome = await runAgentHarnessBeforeAgentFinalizeHook({ |
| 155 | + event: { |
| 156 | + runId: attempt.runId, |
| 157 | + sessionId: attempt.sessionId, |
| 158 | + ...(attempt.sessionKey ? { sessionKey: attempt.sessionKey } : {}), |
| 159 | + provider: reportedModelRef.provider, |
| 160 | + model: reportedModelRef.model, |
| 161 | + ...((attempt.cwd ?? attempt.workspaceDir) |
| 162 | + ? { cwd: attempt.cwd ?? attempt.workspaceDir } |
| 163 | + : {}), |
| 164 | + ...(attempt.sessionFile ? { transcriptPath: attempt.sessionFile } : {}), |
| 165 | + stopHookActive: false, |
| 166 | + lastAssistantMessage, |
| 167 | + messages: hookMessages, |
| 168 | + }, |
| 169 | + ctx: { |
| 170 | + runId: attempt.runId, |
| 171 | + trace: freezeDiagnosticTraceContext(input.diagnosticTrace), |
| 172 | + agentId: input.hookAgentId, |
| 173 | + sessionKey: attempt.sessionKey, |
| 174 | + sessionId: attempt.sessionId, |
| 175 | + workspaceDir: attempt.workspaceDir, |
| 176 | + modelProviderId: reportedModelRef.provider, |
| 177 | + modelId: reportedModelRef.model, |
| 178 | + trigger: attempt.trigger, |
| 179 | + ...buildAgentHookContextChannelFields(attempt), |
| 180 | + ...buildAgentHookContextIdentityFields({ |
| 181 | + trigger: attempt.trigger, |
| 182 | + senderId: attempt.senderId, |
| 183 | + chatId: attempt.chatId, |
| 184 | + channelContext: attempt.channelContext, |
| 185 | + }), |
| 186 | + }, |
| 187 | + hookRunner, |
| 188 | + }); |
| 189 | + if (outcome.action !== "revise") { |
| 190 | + return; |
| 191 | + } |
| 192 | + if (event.hadDeterministicSideEffect) { |
| 193 | + log.warn( |
| 194 | + `before_agent_finalize requested revision after potential side effects; finalizing ` + |
| 195 | + `runId=${attempt.runId} sessionId=${attempt.sessionId}`, |
| 196 | + ); |
| 197 | + return; |
| 198 | + } |
| 199 | + beforeAgentFinalizeRevisionReason = outcome.reason; |
| 200 | + return { suppressTerminalDelivery: true }; |
| 201 | + } |
| 202 | + : undefined; |
| 203 | + |
| 204 | + let toolMetasForTerminal: readonly AsyncStartedToolMeta[] = []; |
| 205 | + // Terminal callbacks run after queue construction; keep the queue in this |
| 206 | + // phase so active-run clearing and subscription teardown share one owner. |
| 207 | + const getQueueHandle = (): AttemptStreamQueueHandle => queueHandle; |
| 208 | + const subscription = subscribeEmbeddedAgentSession( |
| 209 | + buildEmbeddedSubscriptionParams({ |
| 210 | + session: input.activeSession, |
| 211 | + runId: attempt.runId, |
| 212 | + lifecycleGeneration: attempt.lifecycleGeneration, |
| 213 | + messageChannel: input.runtimeChannel, |
| 214 | + initialReplayState: attempt.initialReplayState, |
| 215 | + hookRunner: getGlobalHookRunner() ?? undefined, |
| 216 | + verboseLevel: attempt.verboseLevel, |
| 217 | + reasoningMode: attempt.reasoningLevel ?? "off", |
| 218 | + thinkingLevel: attempt.thinkLevel, |
| 219 | + toolResultFormat: attempt.toolResultFormat, |
| 220 | + shouldEmitToolResult: attempt.shouldEmitToolResult, |
| 221 | + shouldEmitToolOutput: attempt.shouldEmitToolOutput, |
| 222 | + sourceReplyDeliveryMode: attempt.sourceReplyDeliveryMode, |
| 223 | + hasDeliveredMessageToolOnlySourceReply: input.hasDeliveredSourceReply, |
| 224 | + onDeliveredMessageToolOnlySourceReply: input.markSourceReplyDelivered, |
| 225 | + onAgentToolResult: attempt.onAgentToolResult, |
| 226 | + onToolResult: attempt.onToolResult, |
| 227 | + onReasoningStream: attempt.onReasoningStream, |
| 228 | + streamReasoningInNonStreamModes: attempt.streamReasoningInNonStreamModes, |
| 229 | + onReasoningEnd: attempt.onReasoningEnd, |
| 230 | + onBlockReply: input.onBlockReply, |
| 231 | + onBlockReplyFlush: input.onBlockReplyFlush, |
| 232 | + onBeforeTerminalDelivery, |
| 233 | + blockReplyBreak: attempt.blockReplyBreak, |
| 234 | + blockReplyChunking: attempt.blockReplyChunking, |
| 235 | + onPartialReply: attempt.onPartialReply, |
| 236 | + onAssistantMessageStart: attempt.onAssistantMessageStart, |
| 237 | + onExecutionPhase: attempt.onExecutionPhase, |
| 238 | + onAgentEvent: attempt.onAgentEvent, |
| 239 | + terminalLifecyclePhase: |
| 240 | + (attempt.deferTerminalLifecycle ?? attempt.deferTerminalLifecycleEnd) ? "finishing" : "end", |
| 241 | + onToolStreamBoundary: attempt.onToolStreamBoundary, |
| 242 | + isTerminalAborted: () => input.getRunState().aborted, |
| 243 | + resolveTerminalStopReason: () => |
| 244 | + isAgentRunRestartAbortReason(input.runAbortController.signal.reason) |
| 245 | + ? AGENT_RUN_RESTART_ABORT_STOP_REASON |
| 246 | + : undefined, |
| 247 | + onBeforeLifecycleTerminal: () => { |
| 248 | + if ( |
| 249 | + requiresCompletionRequiredAsyncTaskWait({ |
| 250 | + sessionKey: attempt.sessionKey, |
| 251 | + toolMetas: toolMetasForTerminal, |
| 252 | + }) |
| 253 | + ) { |
| 254 | + return; |
| 255 | + } |
| 256 | + // Clear embedded-run activity before emitting terminal lifecycle events so |
| 257 | + // post-completion cleanup does not observe a logically finished run as active. |
| 258 | + clearActiveEmbeddedRun( |
| 259 | + attempt.sessionId, |
| 260 | + getQueueHandle(), |
| 261 | + attempt.sessionKey, |
| 262 | + attempt.sessionFile, |
| 263 | + ); |
| 264 | + }, |
| 265 | + enforceFinalTag: attempt.enforceFinalTag, |
| 266 | + silentExpected: attempt.silentExpected, |
| 267 | + suppressLiveStreamOutput: attempt.suppressLiveStreamOutput, |
| 268 | + config: attempt.config, |
| 269 | + sessionKey: input.sandboxSessionKey, |
| 270 | + currentChannelId: attempt.currentChannelId, |
| 271 | + currentMessagingTarget: attempt.currentMessagingTarget, |
| 272 | + currentThreadId: attempt.currentThreadTs, |
| 273 | + currentMessageId: attempt.currentMessageId, |
| 274 | + replyToMode: attempt.replyToMode, |
| 275 | + hasRepliedRef: attempt.hasRepliedRef, |
| 276 | + sessionId: attempt.sessionId, |
| 277 | + agentId: input.hookAgentId, |
| 278 | + builtinToolNames: input.builtinToolNames, |
| 279 | + replaySafeToolNames: input.replaySafeToolNames, |
| 280 | + internalEvents: attempt.internalEvents, |
| 281 | + }), |
| 282 | + ); |
| 283 | + toolMetasForTerminal = subscription.toolMetas; |
| 284 | + |
| 285 | + const toolSearchCatalogExecutor: ToolSearchCatalogToolExecutor = async (toolParams) => { |
| 286 | + try { |
| 287 | + if (toolParams.source === "openclaw" && toolParams.sourceName === "core") { |
| 288 | + recordStructuredReplayTrustForToolCall( |
| 289 | + toolParams.toolCallId, |
| 290 | + toolParams.tool as never, |
| 291 | + attempt.runId, |
| 292 | + ); |
| 293 | + } |
| 294 | + const result = await subscription.runToolLifecycle({ |
| 295 | + toolName: toolParams.toolName, |
| 296 | + toolCallId: toolParams.toolCallId, |
| 297 | + args: toolParams.input, |
| 298 | + replaySafe: input.isReplaySafeTool(toolParams.tool), |
| 299 | + hideFromChannelProgress: |
| 300 | + "hideFromChannelProgress" in toolParams.tool && |
| 301 | + toolParams.tool.hideFromChannelProgress === true, |
| 302 | + execute: async () => |
| 303 | + await toolParams.tool.execute( |
| 304 | + toolParams.toolCallId, |
| 305 | + toolParams.input, |
| 306 | + toolParams.signal ?? input.runAbortController.signal, |
| 307 | + toolParams.onUpdate, |
| 308 | + undefined as never, |
| 309 | + ), |
| 310 | + }); |
| 311 | + input.toolSearchTargetTranscriptProjections.push({ |
| 312 | + parentToolCallId: toolParams.parentToolCallId, |
| 313 | + toolCallId: toolParams.toolCallId, |
| 314 | + toolName: toolParams.toolName, |
| 315 | + input: toolParams.input, |
| 316 | + result, |
| 317 | + timestamp: Date.now(), |
| 318 | + }); |
| 319 | + notifyToolActivity(attempt.runId); |
| 320 | + return result; |
| 321 | + } catch (error) { |
| 322 | + const message = formatErrorMessage(error); |
| 323 | + input.toolSearchTargetTranscriptProjections.push({ |
| 324 | + parentToolCallId: toolParams.parentToolCallId, |
| 325 | + toolCallId: toolParams.toolCallId, |
| 326 | + toolName: toolParams.toolName, |
| 327 | + input: toolParams.input, |
| 328 | + result: { |
| 329 | + content: [{ type: "text", text: message }], |
| 330 | + details: { status: "error", error: message }, |
| 331 | + }, |
| 332 | + isError: true, |
| 333 | + timestamp: Date.now(), |
| 334 | + }); |
| 335 | + notifyToolActivity(attempt.runId); |
| 336 | + throw error; |
| 337 | + } |
| 338 | + }; |
| 339 | + |
| 340 | + const abortActiveRunExternally = (reason?: "user_abort" | "restart" | "superseded") => { |
| 341 | + input.markExternalAbort(); |
| 342 | + attempt.onAttemptAbort?.(); |
| 343 | + input.abortRun(false, reason === "restart" ? createAgentRunRestartAbortError() : undefined); |
| 344 | + }; |
| 345 | + let acceptingSteerMessages = true; |
| 346 | + const queueHandle: AttemptStreamQueueHandle = { |
| 347 | + kind: "embedded", |
| 348 | + runId: attempt.runId, |
| 349 | + queueMessage: async (text: string, options) => { |
| 350 | + if (options?.steeringMode) { |
| 351 | + input.activeSession.agent.steeringMode = options.steeringMode; |
| 352 | + } |
| 353 | + await steerActiveSessionWithOptionalDeliveryWait(input.activeSession, text, options); |
| 354 | + }, |
| 355 | + isStreaming: () => input.activeSession.isStreaming, |
| 356 | + isStopped: () => |
| 357 | + !acceptingSteerMessages || |
| 358 | + input.getRunState().aborted || |
| 359 | + input.runAbortController.signal.aborted, |
| 360 | + isCompacting: () => subscription.isCompacting(), |
| 361 | + supportsTranscriptCommitWait: true, |
| 362 | + sourceReplyDeliveryMode: attempt.sourceReplyDeliveryMode, |
| 363 | + taskSuggestionDeliveryMode: attempt.taskSuggestionDeliveryMode, |
| 364 | + cancel: abortActiveRunExternally, |
| 365 | + abort: (reason) => abortActiveRunExternally(reason), |
| 366 | + }; |
| 367 | + attempt.replyOperation?.attachBackend(queueHandle); |
| 368 | + setActiveEmbeddedRun(attempt.sessionId, queueHandle, attempt.sessionKey, attempt.sessionFile); |
| 369 | + |
| 370 | + return { |
| 371 | + subscription, |
| 372 | + queueHandle, |
| 373 | + toolSearchCatalogExecutor, |
| 374 | + getBeforeAgentFinalizeRevisionReason: () => beforeAgentFinalizeRevisionReason, |
| 375 | + stopAcceptingSteerMessages: () => { |
| 376 | + acceptingSteerMessages = false; |
| 377 | + }, |
| 378 | + }; |
| 379 | +} |
0 commit comments