diff --git a/test/e2e-scenario/live/channels-add-remove.test.ts b/test/e2e-scenario/live/channels-add-remove.test.ts index af58ebfce81..b69e85cf143 100644 --- a/test/e2e-scenario/live/channels-add-remove.test.ts +++ b/test/e2e-scenario/live/channels-add-remove.test.ts @@ -383,6 +383,7 @@ liveTest( "post-add rebuild reuses the gateway-stored inference credential when NVIDIA_INFERENCE_API_KEY is absent", "post-add rebuild applies the Telegram policy preset and renders openclaw.json channel state", "channels remove telegram removes provider, policy, registry plan, and rendered channel state after rebuild", + "post-remove rebuild does not use stale Telegram host env inputs that would stage a fresh channel add", ], }); @@ -497,7 +498,7 @@ liveTest( expectHostTelegramPlan("removed", "after channels remove"); const rebuildRemove = await host.nemoclaw([SANDBOX_NAME, "rebuild", "--yes"], { - artifactName: "phase-5-rebuild-after-remove", + artifactName: "phase-5-rebuild-after-remove-with-stale-telegram-env", env: channelEnv({ NVIDIA_INFERENCE_API_KEY: apiKey }), redactionValues: secretsToRedact, timeoutMs: REBUILD_TIMEOUT_MS, diff --git a/test/e2e-scenario/live/kimi-inference-compat-helpers.ts b/test/e2e-scenario/live/kimi-inference-compat-helpers.ts index 35b87b2651b..fc17ac48ce5 100644 --- a/test/e2e-scenario/live/kimi-inference-compat-helpers.ts +++ b/test/e2e-scenario/live/kimi-inference-compat-helpers.ts @@ -422,14 +422,27 @@ export function parseConfig(raw: string): { }; } -export async function assertTrajectory(sandbox: SandboxClient): Promise { - const checkScript = String.raw`import json, pathlib, sys +export interface KimiTrajectorySummary { + errors: string[]; + finalStatus?: unknown; + finalTextCount: number; + roles: unknown[]; + sourceCommands: unknown[]; + strictMockExpectations: boolean; + toolMetaCommandSet: string[]; + toolMetaInvalidValues: unknown[]; + toolMetasCount: number; +} + +export function buildKimiTrajectoryCheckScript(strictMockExpectations: boolean): string { + return String.raw`import json, pathlib, re, sys +strict_mock = __STRICT_MOCK__ root=pathlib.Path('/sandbox/.openclaw') base=pathlib.Path('/sandbox/.openclaw/agents/main/sessions') session=base/'e2e-kimi-tools.jsonl' trajectory=base/'e2e-kimi-tools.trajectory.jsonl' if not session.exists() or not trajectory.exists(): - print(json.dumps({'error':'missing session/trajectory','files':[str(p) for p in root.rglob('*e2e-kimi-tools*.jsonl')]})) + print(json.dumps({'errors':['missing session/trajectory'],'files':[str(p) for p in root.rglob('*e2e-kimi-tools*.jsonl')]})) sys.exit(1) session_items=[json.loads(line) for line in session.read_text().splitlines() if line.strip()] trajectory_items=[json.loads(line) for line in trajectory.read_text().splitlines() if line.strip()] @@ -438,17 +451,38 @@ artifacts=[item for item in trajectory_items if item.get('type')=='trace.artifac if len(artifacts)!=1: errors.append(f'trace.artifacts count={len(artifacts)}') data=(artifacts[-1].get('data') if artifacts else {}) or {} metas=data.get('toolMetas') or [] +meta_commands=[m.get('meta') for m in metas] +meta_commands_str=[command for command in meta_commands if isinstance(command, str)] +invalid_meta_commands=[command for command in meta_commands if not isinstance(command, str)] +expected_round=['hostname','date','uptime'] +expected_command_set=sorted(expected_round) if data.get('finalStatus')!='success': errors.append(f'finalStatus={data.get("finalStatus")!r}') -if len(metas)!=3: errors.append(f'toolMetas count={len(metas)}') -if [m.get('toolName') for m in metas] != ['exec','exec','exec']: errors.append('tool names mismatch') -if sorted(m.get('meta') for m in metas) != ['date','hostname','uptime']: errors.append('tool command set mismatch') +min_metas = 3 if strict_mock else 1 +if len(metas) < min_metas: errors.append(f'toolMetas count={len(metas)} expected_at_least={min_metas}') +if any(m.get('toolName') != 'exec' for m in metas): errors.append('tool names mismatch') messages=[item.get('message',{}) for item in session_items if item.get('type')=='message'] assistant_tool_messages=[m for m in messages if m.get('role')=='assistant' and any(b.get('type')=='toolCall' for b in m.get('content',[]))] source=[] for m in assistant_tool_messages: source.extend(b.get('arguments',{}).get('command') for b in m.get('content',[]) if b.get('type')=='toolCall') -if source != ['hostname','date','uptime']: errors.append(f'source commands={source!r}') -if any(isinstance(c,str) and ';' in c for c in source): errors.append('combined semicolon command remains') +if not source: errors.append('source assistant did not record any exec commands') +invalid_source_commands=[c for c in source if not isinstance(c,str)] +if invalid_source_commands: errors.append(f'source commands are not all strings: {invalid_source_commands!r}') +if strict_mock: + if invalid_meta_commands: + errors.append(f'toolMeta meta values are not all strings: {invalid_meta_commands!r}') + elif sorted(set(meta_commands_str)) != expected_command_set: + errors.append(f'tool command set={sorted(set(meta_commands_str))!r}') + if len(source) < len(expected_round) or len(source) % len(expected_round) != 0: + errors.append(f'source commands={source!r}') + else: + for offset in range(0, len(source), len(expected_round)): + if source[offset:offset + len(expected_round)] != expected_round: + errors.append(f'source commands={source!r}') + break +safe_source_commands=[c for c in source if isinstance(c,str) and c in expected_round] +unsafe_source_commands=[c for c in source if isinstance(c,str) and c not in expected_round] +if unsafe_source_commands: errors.append(f'unsafe source command remains: {unsafe_source_commands!r}') raw=session.read_text()+trajectory.read_text() for token in ['abandoned','want me to continue']: if token in raw.lower(): errors.append(f'contains {token}') @@ -458,16 +492,68 @@ for field in ['aborted','externalAbort','timedOut','idleTimedOut','timedOutDurin def normalize_final_text(value): return value.strip().removesuffix('.') if isinstance(value, str) else value final_texts=data.get('assistantTexts') or [] -if not final_texts or normalize_final_text(final_texts[-1]) != 'hostname, date, and uptime completed successfully': errors.append('final text mismatch') +expected_final_text='hostname, date, and uptime completed successfully' +if strict_mock and (not final_texts or expected_final_text not in normalize_final_text(final_texts[-1])): + errors.append('final text mismatch') +elif not final_texts: + errors.append('missing final assistant text') roles=[m.get('role') for m in messages] if not ('toolResult' in roles and roles[-1]=='assistant'): errors.append('final assistant not after tool result') -print(json.dumps({'errors':errors,'source':source,'toolMetas':metas,'roles':roles}, indent=2)) -sys.exit(1 if errors else 0)`; +summary={ + 'errors': errors, + 'finalStatus': data.get('finalStatus'), + 'finalTextCount': len(final_texts), + 'roles': roles, + 'sourceCommands': source, + 'strictMockExpectations': strict_mock, + 'toolMetaCommandSet': sorted(set(meta_commands_str)), + 'toolMetaInvalidValues': invalid_meta_commands, + 'toolMetasCount': len(metas), +} +print(json.dumps(summary, indent=2)) +sys.exit(1 if errors else 0)`.replace("__STRICT_MOCK__", strictMockExpectations ? "True" : "False"); +} + +export function assertKimiTrajectorySummary(summary: KimiTrajectorySummary): void { + expect(summary.errors).toEqual([]); + expect(summary.finalStatus).toBe("success"); + expect(summary.finalTextCount).toBeGreaterThan(0); + expect(summary.roles).toContain("toolResult"); + expect(summary.roles.at(-1)).toBe("assistant"); + expect(summary.sourceCommands.length).toBeGreaterThan(0); + expect(summary.sourceCommands.every((command) => typeof command === "string")).toBe(true); + const safeSourceCommands = new Set(["hostname", "date", "uptime"]); + expect(summary.sourceCommands.every((command) => safeSourceCommands.has(command as string))).toBe( + true, + ); + expect(summary.toolMetasCount).toBeGreaterThanOrEqual(summary.strictMockExpectations ? 3 : 1); + if (summary.strictMockExpectations) { + const expectedRound = ["hostname", "date", "uptime"]; + expect(summary.toolMetaInvalidValues).toEqual([]); + expect(summary.toolMetaCommandSet).toEqual(["date", "hostname", "uptime"]); + expect(summary.sourceCommands.length % expectedRound.length).toBe(0); + for (let index = 0; index < summary.sourceCommands.length; index += expectedRound.length) { + expect(summary.sourceCommands.slice(index, index + expectedRound.length)).toEqual( + expectedRound, + ); + } + } +} + +export async function assertTrajectory( + sandbox: SandboxClient, + mode: KimiInferenceMode, +): Promise { + const checkScript = buildKimiTrajectoryCheckScript(mode === "mock"); const encoded = Buffer.from(checkScript, "utf8").toString("base64"); const trajectory = await sandbox.execShell( SANDBOX_NAME, trustedSandboxShellScript(`python3 -c "$(printf %s '${encoded}' | base64 -d)"`), - { artifactName: "kimi-trajectory-tool-splitting-check", env: env(), timeoutMs: 60_000 }, + { + artifactName: "kimi-trajectory-tool-splitting-check", + env: env({}, { mode }), + timeoutMs: 60_000, + }, ); expect(trajectory.exitCode, resultText(trajectory)).toBe(0); } diff --git a/test/e2e-scenario/live/kimi-inference-compat.test.ts b/test/e2e-scenario/live/kimi-inference-compat.test.ts index 8b128e17ec6..5fd9b8af927 100644 --- a/test/e2e-scenario/live/kimi-inference-compat.test.ts +++ b/test/e2e-scenario/live/kimi-inference-compat.test.ts @@ -119,7 +119,7 @@ test.skipIf(!shouldRunLiveE2EScenarios())( }, ); expect(toolAgent.exitCode, resultText(toolAgent)).toBe(0); - await assertTrajectory(sandbox); + await assertTrajectory(sandbox, mode); await assertKimiUpstreamTraffic({ fake, host, mode, apiKey }); }, ); diff --git a/test/e2e-scenario/live/openclaw-inference-switch.test.ts b/test/e2e-scenario/live/openclaw-inference-switch.test.ts index 37e48d6389b..d0134f45f31 100644 --- a/test/e2e-scenario/live/openclaw-inference-switch.test.ts +++ b/test/e2e-scenario/live/openclaw-inference-switch.test.ts @@ -704,6 +704,12 @@ function collectOpenClawAgentText(value: unknown, parts: string[], visited: Set< } } +function agentReplyContainsToken(reply: string, expected: string): boolean { + const normalizedReply = reply.replace(/\s+/gu, "").toUpperCase(); + const normalizedExpected = expected.replace(/\s+/gu, "").toUpperCase(); + return normalizedExpected.length > 0 && normalizedReply === normalizedExpected; +} + function parseOpenClawAgentText(raw: string): string { if (!raw.trim()) return ""; const parts: string[] = []; @@ -783,7 +789,7 @@ exit "$rc" }); const [raw = "", warnings = ""] = result.stdout.split("\n__NEMOCLAW_AGENT_STDERR__\n", 2); const reply = parseOpenClawAgentText(raw); - if (result.exitCode === 0 && /\bPONG\b/i.test(reply)) return "ok"; + if (result.exitCode === 0 && agentReplyContainsToken(reply, "PONG")) return "ok"; if (result.exitCode === 124) { return { skipped: "OpenClaw agent turn timed out after switch; route/config checks already passed", @@ -799,6 +805,16 @@ exit "$rc" ); } +test("openclaw-inference-switch agent reply matching tolerates wrapped PONG", () => { + expect(agentReplyContainsToken("P\nO N G", "PONG")).toBe(true); + expect(agentReplyContainsToken("wrapped: p o\nng", "PONG")).toBe(false); + expect(agentReplyContainsToken("the answer is PONG", "PONG")).toBe(false); + expect(agentReplyContainsToken("PONG because the route works", "PONG")).toBe(false); + expect(agentReplyContainsToken("PANG", "PONG")).toBe(false); + expect(agentReplyContainsToken("SPONGE", "PONG")).toBe(false); + expect(agentReplyContainsToken("pingpong", "PONG")).toBe(false); +}); + function isTransientInferenceSetFailure(text: string): boolean { return /timed? out|timeout|ETIMEDOUT|ECONNRESET|EAI_AGAIN|ENOTFOUND|failed to connect|error sending request|failed to verify inference endpoint|502|503|504|temporar/i.test( text, @@ -819,12 +835,22 @@ async function runInferenceSetWithRetry( switchEndpointUrl: string | null, ): Promise { const attempts = parsePositiveIntEnv("NEMOCLAW_SWITCH_SET_ATTEMPTS", 3); + const compatibleCredentialEnv = (() => { + switch (SWITCH_PROVIDER) { + case "compatible-endpoint": + return "COMPATIBLE_API_KEY"; + case "compatible-anthropic-endpoint": + return "COMPATIBLE_ANTHROPIC_API_KEY"; + default: + return null; + } + })(); const compatibleMetadataArgs = switchEndpointUrl ? [ "--endpoint-url", switchEndpointUrl, "--credential-env", - "COMPATIBLE_ANTHROPIC_API_KEY", + compatibleCredentialEnv ?? "", "--inference-api", SWITCH_INFERENCE_API, ] @@ -956,11 +982,10 @@ RUN_OPENCLAW_INFERENCE_SWITCH_TEST( endpointUrl: mockProvider.endpointUrl, }); } - const switchEndpointUrl = await ensureCompatibleAnthropicSwitchProvider( - host, - home, - mockProvider, - ); + const switchEndpointUrl = + SWITCH_PROVIDER === "compatible-endpoint" + ? hosted.endpointUrl + : await ensureCompatibleAnthropicSwitchProvider(host, home, mockProvider); const pidBefore = await openclawGatewayPid(sandbox, home); const switchResult = await runInferenceSetWithRetry(host, home, [apiKey], switchEndpointUrl); diff --git a/test/e2e-scenario/support-tests/kimi-inference-compat-helpers.test.ts b/test/e2e-scenario/support-tests/kimi-inference-compat-helpers.test.ts index c06d9030e60..b65abea7f2c 100644 --- a/test/e2e-scenario/support-tests/kimi-inference-compat-helpers.test.ts +++ b/test/e2e-scenario/support-tests/kimi-inference-compat-helpers.test.ts @@ -4,6 +4,8 @@ import { describe, expect, it } from "vitest"; import { + assertKimiTrajectorySummary, + buildKimiTrajectoryCheckScript, env, kimiAgentEnv, kimiOnboardEnv, @@ -74,4 +76,70 @@ describe("Kimi inference compatibility mode selection", () => { it("keeps legacy NEMOCLAW_KIMI_USE_MOCK=0 as temporary public-nvidia alias", () => { expect(resolveKimiInferenceMode({ NEMOCLAW_KIMI_USE_MOCK: "0" })).toBe("public-nvidia"); }); + + it("keeps mock Kimi trajectory checks strict for split hostname/date/uptime calls", () => { + const script = buildKimiTrajectoryCheckScript(true); + expect(script).toContain("strict_mock = True"); + expect(script).toContain("tool command set"); + expect(script).toContain("source commands"); + expect(script).toContain("final text mismatch"); + + assertKimiTrajectorySummary({ + errors: [], + finalStatus: "success", + finalTextCount: 1, + roles: ["assistant", "toolResult", "assistant"], + sourceCommands: ["hostname", "date", "uptime"], + strictMockExpectations: true, + toolMetaCommandSet: ["date", "hostname", "uptime"], + toolMetaInvalidValues: [], + toolMetasCount: 3, + }); + }); + + it("allows public Kimi trajectories with fewer safe exec calls but no combined shell", () => { + const script = buildKimiTrajectoryCheckScript(false); + expect(script).toContain("strict_mock = False"); + expect(script).toContain("min_metas = 3 if strict_mock else 1"); + expect(script).toContain("unsafe source command remains"); + + assertKimiTrajectorySummary({ + errors: [], + finalStatus: "success", + finalTextCount: 1, + roles: ["assistant", "toolResult", "assistant"], + sourceCommands: ["hostname"], + strictMockExpectations: false, + toolMetaCommandSet: ["hostname"], + toolMetaInvalidValues: [null], + toolMetasCount: 1, + }); + }); + + it("rejects unsafe or malformed source commands in both mock and public trajectory summaries", () => { + for (const sourceCommands of [ + ["hostname; date; uptime"], + ["hostname | date"], + ["hostname $(date)"], + ["hostname `date`"], + ["hostname > /tmp/out"], + ["cat < /etc/passwd"], + ["whoami"], + [null], + ]) { + expect(() => + assertKimiTrajectorySummary({ + errors: [], + finalStatus: "success", + finalTextCount: 1, + roles: ["assistant", "toolResult", "assistant"], + sourceCommands, + strictMockExpectations: false, + toolMetaCommandSet: ["hostname"], + toolMetaInvalidValues: [], + toolMetasCount: 1, + }), + ).toThrow(); + } + }); });