|
| 1 | +// Live end-to-end checks for AgentSession turns, compaction, and follow-up delivery. |
| 2 | +import { mkdir, mkdtemp, rm } from "node:fs/promises"; |
| 3 | +import { tmpdir } from "node:os"; |
| 4 | +import { join } from "node:path"; |
| 5 | +import type { Model } from "openclaw/plugin-sdk/llm"; |
| 6 | +import { Type } from "typebox"; |
| 7 | +import { afterEach, describe, expect, it } from "vitest"; |
| 8 | +import { getRuntimeConfig } from "../../config/config.js"; |
| 9 | +import { discoverModels } from "../agent-model-discovery.js"; |
| 10 | +import { isLiveTestEnabled } from "../live-test-helpers.js"; |
| 11 | +import { ensureOpenClawModelsJson } from "../models-config.js"; |
| 12 | +import type { AgentMessage } from "../runtime/index.js"; |
| 13 | +import { AgentSession } from "./agent-session.js"; |
| 14 | +import { AuthStorage } from "./auth-storage.js"; |
| 15 | +import { createExtensionRuntime } from "./extensions/loader.js"; |
| 16 | +import type { LoadExtensionsResult, ToolDefinition } from "./extensions/types.js"; |
| 17 | +import type { ModelRegistry } from "./model-registry.js"; |
| 18 | +import type { ResourceLoader } from "./resource-loader.js"; |
| 19 | +import { createAgentSession } from "./sdk.js"; |
| 20 | +import { SessionManager } from "./session-manager.js"; |
| 21 | +import { SettingsManager } from "./settings-manager.js"; |
| 22 | +import { createSyntheticSourceInfo } from "./source-info.js"; |
| 23 | + |
| 24 | +const API_KEY = process.env.ANTHROPIC_API_KEY?.trim() ?? ""; |
| 25 | +const LIVE = isLiveTestEnabled() && API_KEY.length > 0; |
| 26 | +const describeLive = LIVE ? describe : describe.skip; |
| 27 | +const TEST_TIMEOUT_MS = 120_000; |
| 28 | +const PROVIDER_TIMEOUT_MS = 30_000; |
| 29 | +const DEFAULT_MODEL_ID = "claude-haiku-4-5"; |
| 30 | + |
| 31 | +const sessions: AgentSession[] = []; |
| 32 | +const tempRoots: string[] = []; |
| 33 | + |
| 34 | +type ExtensionHandlers = Map<string, Array<(...args: unknown[]) => Promise<unknown>>>; |
| 35 | + |
| 36 | +function createResourceLoader(handlers: ExtensionHandlers = new Map()): ResourceLoader { |
| 37 | + const extensionsResult: LoadExtensionsResult = { |
| 38 | + extensions: |
| 39 | + handlers.size > 0 |
| 40 | + ? [ |
| 41 | + { |
| 42 | + path: "<live-test-extension>", |
| 43 | + resolvedPath: "<live-test-extension>", |
| 44 | + sourceInfo: createSyntheticSourceInfo("<live-test-extension>", { |
| 45 | + source: "temporary", |
| 46 | + }), |
| 47 | + handlers, |
| 48 | + tools: new Map(), |
| 49 | + messageRenderers: new Map(), |
| 50 | + commands: new Map(), |
| 51 | + flags: new Map(), |
| 52 | + shortcuts: new Map(), |
| 53 | + }, |
| 54 | + ] |
| 55 | + : [], |
| 56 | + errors: [], |
| 57 | + runtime: createExtensionRuntime(), |
| 58 | + }; |
| 59 | + return { |
| 60 | + getExtensions: () => extensionsResult, |
| 61 | + getSkills: () => ({ skills: [], diagnostics: [] }), |
| 62 | + getPrompts: () => ({ prompts: [], diagnostics: [] }), |
| 63 | + getThemes: () => ({ themes: [], diagnostics: [] }), |
| 64 | + getAgentsFiles: () => ({ agentsFiles: [] }), |
| 65 | + getSystemPrompt: () => undefined, |
| 66 | + getAppendSystemPrompt: () => [], |
| 67 | + extendResources: () => {}, |
| 68 | + reload: async () => {}, |
| 69 | + }; |
| 70 | +} |
| 71 | + |
| 72 | +async function resolveLiveModel( |
| 73 | + agentDir: string, |
| 74 | + authStorage: AuthStorage, |
| 75 | +): Promise<{ model: Model; modelRegistry: ModelRegistry }> { |
| 76 | + await ensureOpenClawModelsJson(getRuntimeConfig(), agentDir, { |
| 77 | + providerDiscoveryProviderIds: ["anthropic"], |
| 78 | + }); |
| 79 | + const modelRegistry = discoverModels(authStorage, agentDir, { providerFilter: "anthropic" }); |
| 80 | + const requestedModelId = |
| 81 | + process.env.OPENCLAW_LIVE_AGENT_SESSION_MODEL?.trim() || DEFAULT_MODEL_ID; |
| 82 | + const model = |
| 83 | + modelRegistry.find("anthropic", requestedModelId) ?? |
| 84 | + modelRegistry |
| 85 | + .getAll() |
| 86 | + .find((candidate) => candidate.provider === "anthropic" && /haiku/i.test(candidate.id)); |
| 87 | + if (!model) { |
| 88 | + throw new Error(`No Anthropic Haiku model found for ${requestedModelId}`); |
| 89 | + } |
| 90 | + return { |
| 91 | + model: { ...model, maxTokens: Math.min(model.maxTokens, 128) }, |
| 92 | + modelRegistry, |
| 93 | + }; |
| 94 | +} |
| 95 | + |
| 96 | +async function createLiveSession( |
| 97 | + options: { |
| 98 | + customTools?: ToolDefinition[]; |
| 99 | + handlers?: ExtensionHandlers; |
| 100 | + } = {}, |
| 101 | +) { |
| 102 | + const root = await mkdtemp(join(tmpdir(), "openclaw-agent-session-live-")); |
| 103 | + tempRoots.push(root); |
| 104 | + const cwd = join(root, "workspace"); |
| 105 | + const agentDir = join(root, "agent"); |
| 106 | + await mkdir(cwd, { recursive: true }); |
| 107 | + const authStorage = AuthStorage.inMemory(); |
| 108 | + authStorage.setRuntimeApiKey("anthropic", API_KEY); |
| 109 | + const { model, modelRegistry } = await resolveLiveModel(agentDir, authStorage); |
| 110 | + const sessionManager = SessionManager.inMemory(); |
| 111 | + const settingsManager = SettingsManager.inMemory({ |
| 112 | + defaultThinkingLevel: "off", |
| 113 | + compaction: { enabled: true, reserveTokens: 128, keepRecentTokens: 0 }, |
| 114 | + retry: { |
| 115 | + enabled: false, |
| 116 | + provider: { timeoutMs: PROVIDER_TIMEOUT_MS, maxRetries: 0, maxRetryDelayMs: 0 }, |
| 117 | + }, |
| 118 | + }); |
| 119 | + const { session } = await createAgentSession({ |
| 120 | + cwd, |
| 121 | + agentDir, |
| 122 | + model, |
| 123 | + thinkingLevel: "off", |
| 124 | + noTools: "builtin", |
| 125 | + customTools: options.customTools, |
| 126 | + resourceLoader: createResourceLoader(options.handlers), |
| 127 | + authStorage, |
| 128 | + modelRegistry, |
| 129 | + sessionManager, |
| 130 | + settingsManager, |
| 131 | + }); |
| 132 | + sessions.push(session); |
| 133 | + return { session, sessionManager }; |
| 134 | +} |
| 135 | + |
| 136 | +function assistantText(message: AgentMessage): string { |
| 137 | + if (message.role !== "assistant") { |
| 138 | + return ""; |
| 139 | + } |
| 140 | + return message.content |
| 141 | + .filter((block) => block.type === "text") |
| 142 | + .map((block) => block.text) |
| 143 | + .join("") |
| 144 | + .trim(); |
| 145 | +} |
| 146 | + |
| 147 | +afterEach(async () => { |
| 148 | + for (const session of sessions.splice(0)) { |
| 149 | + session.dispose(); |
| 150 | + } |
| 151 | + await Promise.all( |
| 152 | + tempRoots.splice(0).map(async (root) => { |
| 153 | + await rm(root, { recursive: true, force: true }); |
| 154 | + }), |
| 155 | + ); |
| 156 | +}); |
| 157 | + |
| 158 | +describeLive("AgentSession live", () => { |
| 159 | + it( |
| 160 | + "completes a real tool turn", |
| 161 | + async () => { |
| 162 | + let toolExecutions = 0; |
| 163 | + const echoParameters = Type.Object({ text: Type.String() }); |
| 164 | + const echoTool: ToolDefinition<typeof echoParameters> = { |
| 165 | + name: "live_echo", |
| 166 | + label: "Live echo", |
| 167 | + description: |
| 168 | + "Return the supplied text unchanged. Use when the user explicitly requests it.", |
| 169 | + parameters: echoParameters, |
| 170 | + execute: async (_toolCallId, params) => { |
| 171 | + toolExecutions += 1; |
| 172 | + return { |
| 173 | + content: [{ type: "text", text: params.text }], |
| 174 | + details: {}, |
| 175 | + }; |
| 176 | + }, |
| 177 | + }; |
| 178 | + const { session } = await createLiveSession({ customTools: [echoTool] }); |
| 179 | + |
| 180 | + await session.prompt( |
| 181 | + "Call live_echo exactly once with text OK. After its result, reply with exactly OK.", |
| 182 | + ); |
| 183 | + |
| 184 | + const finalAssistant = session.messages.findLast( |
| 185 | + (message) => message.role === "assistant" && message.stopReason === "stop", |
| 186 | + ); |
| 187 | + expect(toolExecutions).toBe(1); |
| 188 | + expect(finalAssistant).toBeDefined(); |
| 189 | + if (finalAssistant?.role !== "assistant") { |
| 190 | + throw new Error("missing final assistant message"); |
| 191 | + } |
| 192 | + expect(finalAssistant.usage.output).toBeGreaterThan(0); |
| 193 | + expect(assistantText(finalAssistant)).not.toBe(""); |
| 194 | + }, |
| 195 | + TEST_TIMEOUT_MS, |
| 196 | + ); |
| 197 | + |
| 198 | + it( |
| 199 | + "manually compacts a completed turn and remains usable", |
| 200 | + async () => { |
| 201 | + const { session, sessionManager } = await createLiveSession(); |
| 202 | + await session.prompt("Reply with exactly OK."); |
| 203 | + |
| 204 | + const result = await session.compact(); |
| 205 | + const compaction = sessionManager |
| 206 | + .getBranch() |
| 207 | + .findLast((entry) => entry.type === "compaction"); |
| 208 | + |
| 209 | + expect(result.summary.trim().length).toBeGreaterThan(0); |
| 210 | + expect(compaction?.type).toBe("compaction"); |
| 211 | + if (compaction?.type !== "compaction") { |
| 212 | + throw new Error("missing compaction entry"); |
| 213 | + } |
| 214 | + expect(compaction.summary.trim().length).toBeGreaterThan(0); |
| 215 | + |
| 216 | + await session.prompt("Reply with exactly STILL_OK."); |
| 217 | + expect((session.getLastAssistantText() ?? "").trim().length).toBeGreaterThan(0); |
| 218 | + }, |
| 219 | + TEST_TIMEOUT_MS, |
| 220 | + ); |
| 221 | + |
| 222 | + it( |
| 223 | + "drains a follow-up queued by an agent-end handler", |
| 224 | + async () => { |
| 225 | + const sessionRef: { current?: AgentSession } = {}; |
| 226 | + let queued = false; |
| 227 | + const handlers: ExtensionHandlers = new Map([ |
| 228 | + [ |
| 229 | + "agent_end", |
| 230 | + [ |
| 231 | + async () => { |
| 232 | + if (!queued) { |
| 233 | + queued = true; |
| 234 | + await sessionRef.current?.followUp("Reply with exactly SECOND."); |
| 235 | + } |
| 236 | + return undefined; |
| 237 | + }, |
| 238 | + ], |
| 239 | + ], |
| 240 | + ]); |
| 241 | + const { session } = await createLiveSession({ handlers }); |
| 242 | + sessionRef.current = session; |
| 243 | + |
| 244 | + await session.prompt("Reply with exactly FIRST."); |
| 245 | + |
| 246 | + const assistants = session.messages.filter( |
| 247 | + (message) => message.role === "assistant" && message.stopReason === "stop", |
| 248 | + ); |
| 249 | + const deliveredFollowUp = session.messages.some( |
| 250 | + (message) => |
| 251 | + message.role === "user" && |
| 252 | + Array.isArray(message.content) && |
| 253 | + message.content.some( |
| 254 | + (block) => block.type === "text" && block.text === "Reply with exactly SECOND.", |
| 255 | + ), |
| 256 | + ); |
| 257 | + expect(deliveredFollowUp).toBe(true); |
| 258 | + expect(assistants).toHaveLength(2); |
| 259 | + expect(assistants.every((message) => assistantText(message).length > 0)).toBe(true); |
| 260 | + }, |
| 261 | + TEST_TIMEOUT_MS, |
| 262 | + ); |
| 263 | +}); |
0 commit comments