mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-31 09:08:35 +00:00
* refactor: extract agent core package Introduce packages/agent-core as the OpenClaw-owned home for reusable agent loop, harness, session, prompt, and runtime dependency contracts. * refactor: extract shared llm runtime Move provider model registries, stream wrappers, OAuth helpers, and LLM utilities into src/llm with plugin-sdk barrels instead of depending on the old embedded runtime layout. * refactor: remove pi runtime internals Rename remaining Pi-shaped agent surfaces to OpenClaw agent runtime names, delete obsolete Pi docs and package graph checks, and add the third-party notice for incorporated code. * refactor: tighten agent session runtime Make agent-core/runtime dependencies explicit, consolidate compaction and session transcript helpers, and move model/session helpers behind OpenClaw-owned contracts. * refactor: remove static model and pi auth paths Drop static model catalogs and Pi auth bridges, move model/provider facts to manifest-owned runtime contracts, and harden internal embedded-agent utilities. * refactor: remove legacy provider compat paths * docs: remove agent parity notes * fix: skip provider wildcard metadata parsing * refactor: share session extension sdk loading * refactor: inline acpx proxy error formatter * refactor: fold edit recovery into edit tool * fix: accept extension batch separator * test: align startup provider plugin expectations * fix: restore provider-scoped release discovery * test: align static asset packaging expectations * fix: run static provider catalogs during scoped discovery * fix: add provider entry catalogs for scoped live discovery * fix: load lightweight provider catalog entries * fix: refresh provider-scoped plugin metadata * fix: keep provider catalog entries on release live path * fix: keep static manifest models in release live checks * fix: harden release model discovery * fix: reduce OpenAI live cache probe reasoning * fix: disable OpenAI cache probe reasoning * ci: extend OpenAI gateway live timeout * fix: extend live gateway model budget * fix: stabilize release validation regressions * fix: honor provider aliases in model rows * fix: stabilize release validation lanes * fix: stabilize release memory qa * ci: stabilize release validation lanes * ci: prefer ipv4 for live docker node calls * fix: restore shared tool-call stream wrapper * ci: remove legacy pi test shard alias * fix: clean up embedded agent test drift * fix: stabilize runtime alias status * fix: clean up embedded agent ci drift * fix: restore release ci invariants * fix: clean up post-rebase runtime drift * fix: restore release ci checks * fix: restore release ci after rebase * fix: remove stale pi runtime path * test: align compaction runtime expectations * test: update plugin prerelease expectations * fix: handle claude live tool approvals * fix: stabilize release validation gates * fix: finish agent runtime import * test: finish post-rebase agent runtime mocks * fix: keep codex compaction native * fix: stabilize codex app-server hook tests * test: isolate codex diagnostic active run * test: remove codex diagnostic completion race # Conflicts: # extensions/codex/src/app-server/run-attempt.test.ts * ci: fix full release manifest performance run id * refactor: narrow llm plugin sdk boundary * chore: drop generated google boundary stamps * fix: repair rebase fallout * fix: clean up rebased runtime references * fix: decode codex jwt payloads as base64url * fix: preserve shipped pi runtime alias * fix: add scoped sdk virtual modules * fix: decode llm codex oauth jwt as base64url * fix: avoid stale vertex adc negative cache * fix: harden tool arg decoding and codeql path * fix: keep vertex adc negative checks live * refactor: consolidate codex jwt and edit helpers * fix: await codex oauth node runtime imports * fix: preserve sdk tool and notice contracts * fix: preserve shipped compat config boundaries * fix: align codex oauth callback host * fix: terminate agent-core loop streams on failure * fix: keep codex oauth callback alive during fallback * ci: include session tools in critical codeql scans * fix: keep Cloudflare Anthropic provider auth header * docs: redirect legacy pi runtime pages * fix: honor bundled web provider compat discovery * fix: protect session output spill files * fix: keep legacy agent dir env blocked * fix: contain auto-discovered skill symlinks * fix: harden agent core sdk proxy surfaces * fix: restore approval reaction sdk compat * fix: keep live docker runs bounded * fix: keep codex oauth redirect host aligned * fix: resolve post-rebase agent runtime drift * fix: redact anthropic oauth parse failures * fix: preserve responses strict tool shaping * fix: repair agent runtime rebase cleanup * docs: redirect retired parity pages * fix: bound auto-discovered resources to roots * fix: repair post-rebase agent test drift * fix: preserve bundled provider allowlist migration * fix: preserve manifest-owned provider aliases * fix: declare photon image dependency * fix: keep provider headers out of proxy body * fix: preserve shipped env aliases * fix: refresh control ui i18n generated state * fix: quote read fallback paths * fix: preview edits through configured backend * test: satisfy core test typecheck * fix: preserve ZAI usage auth fallback * test: repair codex diagnostic test * fix: repair agent runtime rebase drift * test: finish embedded runner import rename * fix: repair agent runtime rebase integrations * test: align compaction oauth fallback expectations * fix: allow sdk-auth session models * fix: update doctor tool schema import * fix: preserve bedrock plugin region * fix: stream harmony-like prose immediately * ci: include session runtime in codeql shards * fix: repair latest rebase integrations * fix: honor explicit codex websocket transport * fix: keep openai-compatible credentials provider-scoped * fix: refresh sdk api baseline after rebase * fix: route cli runtime aliases through openclaw harness * test: rename stale harness mock expectation * test: rename embedded agent overflow calls * test: clean embedded auth test wording * test: use openclaw stream types in deepinfra cache test * fix: refresh sdk api baseline on latest main * fix: honor bundled discovery compat allowlists * fix: refresh sdk api baseline after latest rebase * fix: remove stale rebase imports * test: rename stale model catalog mock * test: mock renamed doctor runtime modules * fix: map canonical kimi env auth * fix: use internal model registry in bench script * fix: migrate deepinfra provider catalog entry * fix: enforce builtin tool suppression * fix: route compaction auth and proxy payloads safely * refactor: prune unused llm registry leftovers * test: update codex hooks session import * test: fix model picker ci coverage * test: align model picker auth mock types
486 lines
18 KiB
TypeScript
486 lines
18 KiB
TypeScript
import type { AgentMessage } from "openclaw/plugin-sdk/agent-core";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { ContextEngine } from "../context-engine/types.js";
|
|
import type { PreparedCliRunContext } from "./cli-runner/types.js";
|
|
|
|
const {
|
|
executePreparedCliRunMock,
|
|
loadCliSessionContextEngineMessagesMock,
|
|
loadCliSessionHistoryMessagesMock,
|
|
getGlobalHookRunnerMock,
|
|
} = vi.hoisted(() => ({
|
|
executePreparedCliRunMock: vi.fn(),
|
|
loadCliSessionContextEngineMessagesMock: vi.fn(),
|
|
loadCliSessionHistoryMessagesMock: vi.fn(),
|
|
getGlobalHookRunnerMock: vi.fn(() => null),
|
|
}));
|
|
|
|
vi.mock("./cli-runner/execute.runtime.js", () => ({
|
|
executePreparedCliRun: executePreparedCliRunMock,
|
|
}));
|
|
|
|
vi.mock("./cli-runner/session-history.js", () => ({
|
|
loadCliSessionContextEngineMessages: loadCliSessionContextEngineMessagesMock,
|
|
loadCliSessionHistoryMessages: loadCliSessionHistoryMessagesMock,
|
|
}));
|
|
|
|
vi.mock("../plugins/hook-runner-global.js", () => ({
|
|
getGlobalHookRunner: getGlobalHookRunnerMock,
|
|
}));
|
|
|
|
function textMessage(role: "user" | "assistant", text: string, timestamp: number): AgentMessage {
|
|
return {
|
|
role,
|
|
content: [{ type: "text", text }],
|
|
timestamp,
|
|
} as AgentMessage;
|
|
}
|
|
|
|
function createContextEngine(overrides: Partial<ContextEngine> = {}): ContextEngine {
|
|
return {
|
|
info: { id: "test-context-engine", name: "Test context engine" },
|
|
ingest: vi.fn(async () => ({ ingested: true })),
|
|
assemble: vi.fn(async (params) => ({
|
|
messages: params.messages,
|
|
estimatedTokens: 0,
|
|
})),
|
|
compact: vi.fn(async () => ({ ok: true, compacted: false })),
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function createMaintenanceResult() {
|
|
return {
|
|
changed: false,
|
|
bytesFreed: 0,
|
|
rewrittenEntries: 0,
|
|
};
|
|
}
|
|
|
|
function buildPreparedContext(contextEngine: ContextEngine): PreparedCliRunContext {
|
|
const backend = {
|
|
command: "claude",
|
|
args: ["--print"],
|
|
output: "text" as const,
|
|
input: "arg" as const,
|
|
sessionMode: "existing" as const,
|
|
serialize: true,
|
|
};
|
|
|
|
return {
|
|
params: {
|
|
sessionId: "openclaw-session-1",
|
|
sessionKey: "agent:main:main",
|
|
agentId: "main",
|
|
sessionFile: "session.jsonl",
|
|
workspaceDir: "/tmp/openclaw-cli-context-engine-test",
|
|
prompt: "visible ask",
|
|
transcriptPrompt: "transcript visible ask",
|
|
provider: "claude-cli",
|
|
model: "sonnet-4.6",
|
|
thinkLevel: "low",
|
|
timeoutMs: 1_000,
|
|
runId: "run-1",
|
|
},
|
|
started: Date.now(),
|
|
workspaceDir: "/tmp/openclaw-cli-context-engine-test",
|
|
backendResolved: {
|
|
id: "claude-cli",
|
|
config: backend,
|
|
bundleMcp: false,
|
|
pluginId: "anthropic",
|
|
},
|
|
preparedBackend: {
|
|
backend,
|
|
env: {},
|
|
},
|
|
reusableCliSession: {
|
|
sessionId: "existing-external-cli-session",
|
|
},
|
|
hadSessionFile: true,
|
|
contextEngineConfig: {},
|
|
contextEngine,
|
|
contextEngineTurnPrompt: "transcript visible ask",
|
|
modelId: "sonnet-4.6",
|
|
normalizedModel: "sonnet-4.6",
|
|
systemPrompt: "You are a helpful assistant.",
|
|
systemPromptReport: {} as PreparedCliRunContext["systemPromptReport"],
|
|
bootstrapPromptWarningLines: [],
|
|
authEpochVersion: 2,
|
|
};
|
|
}
|
|
|
|
function expectMessageText(message: AgentMessage | undefined, expected: string): void {
|
|
expect(message).toBeDefined();
|
|
const content = (message as { content?: unknown } | undefined)?.content;
|
|
if (typeof content === "string") {
|
|
expect(content).toBe(expected);
|
|
return;
|
|
}
|
|
expect(Array.isArray(content)).toBe(true);
|
|
expect((content as unknown[] | undefined)?.[0]).toMatchObject({ type: "text", text: expected });
|
|
}
|
|
|
|
describe("runPreparedCliAgent context engine lifecycle", () => {
|
|
beforeEach(() => {
|
|
executePreparedCliRunMock.mockReset();
|
|
executePreparedCliRunMock.mockResolvedValue({
|
|
text: " final answer ",
|
|
rawText: " final answer ",
|
|
sessionId: "external-cli-session-1",
|
|
usage: { input: 11, output: 7, total: 18 },
|
|
finalPromptText: "prompt sent to cli",
|
|
});
|
|
loadCliSessionContextEngineMessagesMock.mockReset();
|
|
loadCliSessionContextEngineMessagesMock.mockResolvedValue([
|
|
textMessage("user", "old ask", 1),
|
|
textMessage("assistant", "old answer", 2),
|
|
]);
|
|
loadCliSessionHistoryMessagesMock.mockReset();
|
|
loadCliSessionHistoryMessagesMock.mockResolvedValue([]);
|
|
getGlobalHookRunnerMock.mockReset();
|
|
getGlobalHookRunnerMock.mockReturnValue(null);
|
|
});
|
|
|
|
it("finalizes successful CLI turns with the active context engine", async () => {
|
|
const bootstrap = vi.fn<NonNullable<ContextEngine["bootstrap"]>>(async () => ({
|
|
bootstrapped: true,
|
|
}));
|
|
const afterTurn = vi.fn<NonNullable<ContextEngine["afterTurn"]>>(async () => {});
|
|
const maintain = vi.fn<NonNullable<ContextEngine["maintain"]>>(async () =>
|
|
createMaintenanceResult(),
|
|
);
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({ bootstrap, afterTurn, maintain, dispose });
|
|
const context = buildPreparedContext(contextEngine);
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
const result = await runPreparedCliAgent(context);
|
|
|
|
expect(result.meta.agentMeta?.sessionId).toBe("external-cli-session-1");
|
|
expect(loadCliSessionContextEngineMessagesMock).toHaveBeenCalledWith({
|
|
sessionId: "openclaw-session-1",
|
|
sessionFile: "session.jsonl",
|
|
sessionKey: "agent:main:main",
|
|
agentId: "main",
|
|
config: undefined,
|
|
});
|
|
expect(loadCliSessionHistoryMessagesMock).not.toHaveBeenCalled();
|
|
expect(bootstrap).toHaveBeenCalledWith({
|
|
sessionId: "openclaw-session-1",
|
|
sessionKey: "agent:main:main",
|
|
sessionFile: "session.jsonl",
|
|
});
|
|
expect(afterTurn).toHaveBeenCalledTimes(1);
|
|
const afterTurnParams = afterTurn.mock.calls[0]?.[0];
|
|
expect(afterTurnParams).toMatchObject({
|
|
sessionId: "openclaw-session-1",
|
|
sessionKey: "agent:main:main",
|
|
sessionFile: "session.jsonl",
|
|
prePromptMessageCount: 2,
|
|
tokenBudget: undefined,
|
|
runtimeContext: undefined,
|
|
});
|
|
expect(afterTurnParams?.messages).toHaveLength(4);
|
|
expect(afterTurnParams?.messages.slice(0, 2)).toEqual([
|
|
textMessage("user", "old ask", 1),
|
|
textMessage("assistant", "old answer", 2),
|
|
]);
|
|
expectMessageText(afterTurnParams?.messages[2], "transcript visible ask");
|
|
expectMessageText(afterTurnParams?.messages[3], "final answer");
|
|
expect(afterTurnParams?.messages[3]).toMatchObject({
|
|
role: "assistant",
|
|
provider: "claude-cli",
|
|
model: "sonnet-4.6",
|
|
usage: { input: 11, output: 7, total: 18 },
|
|
});
|
|
expect(maintain).toHaveBeenCalledTimes(2);
|
|
expect(maintain.mock.calls[1]?.[0]).toMatchObject({
|
|
sessionId: "openclaw-session-1",
|
|
sessionKey: "agent:main:main",
|
|
sessionFile: "session.jsonl",
|
|
runtimeContext: {
|
|
rewriteTranscriptEntries: expect.any(Function),
|
|
llm: { complete: expect.any(Function) },
|
|
},
|
|
});
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not synthesize a context-engine user turn for empty transcript prompts", async () => {
|
|
const afterTurn = vi.fn<NonNullable<ContextEngine["afterTurn"]>>(async () => {});
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({ afterTurn, dispose });
|
|
const context = buildPreparedContext(contextEngine);
|
|
context.params.transcriptPrompt = "";
|
|
context.contextEngineTurnPrompt = "";
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await runPreparedCliAgent(context);
|
|
|
|
const afterTurnParams = afterTurn.mock.calls[0]?.[0];
|
|
expect(afterTurnParams?.messages).toHaveLength(3);
|
|
expect(afterTurnParams?.prePromptMessageCount).toBe(2);
|
|
expect(afterTurnParams?.messages.slice(0, 2)).toEqual([
|
|
textMessage("user", "old ask", 1),
|
|
textMessage("assistant", "old answer", 2),
|
|
]);
|
|
const turnMessages = afterTurnParams?.messages.slice(afterTurnParams.prePromptMessageCount);
|
|
expect(turnMessages).toHaveLength(1);
|
|
expectMessageText(turnMessages?.[0], "final answer");
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not finalize prepared model prompt as transcript turn text", async () => {
|
|
const afterTurn = vi.fn<NonNullable<ContextEngine["afterTurn"]>>(async () => {});
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({ afterTurn, dispose });
|
|
const context = buildPreparedContext(contextEngine);
|
|
context.params.prompt = "runtime context\n\noriginal user ask";
|
|
delete context.params.transcriptPrompt;
|
|
context.contextEngineTurnPrompt = "original user ask";
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await runPreparedCliAgent(context);
|
|
|
|
const afterTurnParams = afterTurn.mock.calls[0]?.[0];
|
|
expect(afterTurnParams?.messages).toHaveLength(4);
|
|
expect(afterTurnParams?.prePromptMessageCount).toBe(2);
|
|
const turnMessages = afterTurnParams?.messages.slice(afterTurnParams.prePromptMessageCount);
|
|
expect(turnMessages).toHaveLength(2);
|
|
expectMessageText(turnMessages?.[0], "original user ask");
|
|
expectMessageText(turnMessages?.[1], "final answer");
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("loads unbounded context-engine history separately from hook history", async () => {
|
|
const afterTurn = vi.fn<NonNullable<ContextEngine["afterTurn"]>>(async () => {});
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({ afterTurn, dispose });
|
|
const context = buildPreparedContext(contextEngine);
|
|
const fullHistory = Array.from({ length: 101 }, (_, index) =>
|
|
textMessage("user", `old ask ${index}`, index),
|
|
);
|
|
loadCliSessionContextEngineMessagesMock.mockResolvedValueOnce(fullHistory);
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await runPreparedCliAgent(context);
|
|
|
|
const afterTurnParams = afterTurn.mock.calls[0]?.[0];
|
|
expect(loadCliSessionContextEngineMessagesMock).toHaveBeenCalledTimes(1);
|
|
expect(loadCliSessionHistoryMessagesMock).not.toHaveBeenCalled();
|
|
expect(afterTurnParams?.prePromptMessageCount).toBe(101);
|
|
expect(afterTurnParams?.messages.slice(0, 101)).toEqual(fullHistory);
|
|
});
|
|
|
|
it("loads context-engine history after bootstrap lifecycle runs", async () => {
|
|
const postBootstrapHistory = [textMessage("user", "post-bootstrap history", 9)];
|
|
const bootstrap = vi.fn<NonNullable<ContextEngine["bootstrap"]>>(async () => {
|
|
loadCliSessionContextEngineMessagesMock.mockResolvedValueOnce(postBootstrapHistory);
|
|
return { bootstrapped: true };
|
|
});
|
|
const afterTurn = vi.fn<NonNullable<ContextEngine["afterTurn"]>>(async () => {});
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({ bootstrap, afterTurn, dispose });
|
|
const context = buildPreparedContext(contextEngine);
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await runPreparedCliAgent(context);
|
|
|
|
expect(bootstrap).toHaveBeenCalledTimes(1);
|
|
expect(loadCliSessionContextEngineMessagesMock).toHaveBeenCalledTimes(1);
|
|
const bootstrapOrder = bootstrap.mock.invocationCallOrder[0];
|
|
const loadHistoryOrder = loadCliSessionContextEngineMessagesMock.mock.invocationCallOrder[0];
|
|
if (typeof bootstrapOrder !== "number" || typeof loadHistoryOrder !== "number") {
|
|
throw new Error("Expected bootstrap and history load invocation order");
|
|
}
|
|
expect(bootstrapOrder).toBeLessThan(loadHistoryOrder);
|
|
const afterTurnParams = afterTurn.mock.calls[0]?.[0];
|
|
expect(afterTurnParams?.prePromptMessageCount).toBe(1);
|
|
expect(afterTurnParams?.messages[0]).toEqual(postBootstrapHistory[0]);
|
|
});
|
|
|
|
it("falls back to ingestBatch and still runs turn maintenance", async () => {
|
|
const ingestBatch = vi.fn<NonNullable<ContextEngine["ingestBatch"]>>(async () => ({
|
|
ingestedCount: 2,
|
|
}));
|
|
const maintain = vi.fn<NonNullable<ContextEngine["maintain"]>>(async () =>
|
|
createMaintenanceResult(),
|
|
);
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({ ingestBatch, maintain, dispose });
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await runPreparedCliAgent(buildPreparedContext(contextEngine));
|
|
|
|
expect(ingestBatch).toHaveBeenCalledTimes(1);
|
|
const ingestBatchParams = ingestBatch.mock.calls[0]?.[0];
|
|
expect(ingestBatchParams).toMatchObject({
|
|
sessionId: "openclaw-session-1",
|
|
sessionKey: "agent:main:main",
|
|
});
|
|
expect(ingestBatchParams?.messages).toHaveLength(2);
|
|
expectMessageText(ingestBatchParams?.messages[0], "transcript visible ask");
|
|
expectMessageText(ingestBatchParams?.messages[1], "final answer");
|
|
expect(maintain).toHaveBeenCalledTimes(2);
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("preserves deferred maintenance ownership for background engines", async () => {
|
|
const maintain = vi.fn<NonNullable<ContextEngine["maintain"]>>(async () =>
|
|
createMaintenanceResult(),
|
|
);
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({
|
|
info: {
|
|
id: "test-background-context-engine",
|
|
name: "Test background context engine",
|
|
turnMaintenanceMode: "background",
|
|
},
|
|
maintain,
|
|
dispose,
|
|
});
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
const context = buildPreparedContext(contextEngine);
|
|
|
|
await runPreparedCliAgent(context);
|
|
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
expect(context.contextEngineDeferredTurnMaintenance).toBeDefined();
|
|
await context.contextEngineDeferredTurnMaintenance;
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not dispose background engines when no deferred turn maintenance is queued", async () => {
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({
|
|
info: {
|
|
id: "test-background-context-engine",
|
|
name: "Test background context engine",
|
|
turnMaintenanceMode: "background",
|
|
},
|
|
dispose,
|
|
});
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await runPreparedCliAgent(buildPreparedContext(contextEngine));
|
|
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not dispose background engines after failed CLI attempts", async () => {
|
|
executePreparedCliRunMock.mockRejectedValue(new Error("cli boom"));
|
|
const maintain = vi.fn<NonNullable<ContextEngine["maintain"]>>(async () =>
|
|
createMaintenanceResult(),
|
|
);
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({
|
|
info: {
|
|
id: "test-background-context-engine",
|
|
name: "Test background context engine",
|
|
turnMaintenanceMode: "background",
|
|
},
|
|
maintain,
|
|
dispose,
|
|
});
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await expect(runPreparedCliAgent(buildPreparedContext(contextEngine))).rejects.toThrow(
|
|
"cli boom",
|
|
);
|
|
|
|
expect(maintain).toHaveBeenCalledTimes(1);
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not finalize or run turn maintenance on failed CLI attempts", async () => {
|
|
executePreparedCliRunMock.mockRejectedValue(new Error("cli boom"));
|
|
const bootstrap = vi.fn<NonNullable<ContextEngine["bootstrap"]>>(async () => ({
|
|
bootstrapped: true,
|
|
}));
|
|
const afterTurn = vi.fn<NonNullable<ContextEngine["afterTurn"]>>(async () => {});
|
|
const ingestBatch = vi.fn<NonNullable<ContextEngine["ingestBatch"]>>(async () => ({
|
|
ingestedCount: 0,
|
|
}));
|
|
const maintain = vi.fn<NonNullable<ContextEngine["maintain"]>>(async () =>
|
|
createMaintenanceResult(),
|
|
);
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({
|
|
bootstrap,
|
|
afterTurn,
|
|
ingestBatch,
|
|
maintain,
|
|
dispose,
|
|
});
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await expect(runPreparedCliAgent(buildPreparedContext(contextEngine))).rejects.toThrow(
|
|
"cli boom",
|
|
);
|
|
|
|
expect(bootstrap).toHaveBeenCalledTimes(1);
|
|
expect(afterTurn).not.toHaveBeenCalled();
|
|
expect(ingestBatch).not.toHaveBeenCalled();
|
|
expect(maintain).toHaveBeenCalledTimes(1);
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not finalize context-engine turns for empty successful CLI output", async () => {
|
|
executePreparedCliRunMock.mockResolvedValue({
|
|
text: " ",
|
|
rawText: " ",
|
|
sessionId: "external-cli-session-empty",
|
|
usage: { input: 11, output: 0, total: 11 },
|
|
});
|
|
const bootstrap = vi.fn<NonNullable<ContextEngine["bootstrap"]>>(async () => ({
|
|
bootstrapped: true,
|
|
}));
|
|
const afterTurn = vi.fn<NonNullable<ContextEngine["afterTurn"]>>(async () => {});
|
|
const ingestBatch = vi.fn<NonNullable<ContextEngine["ingestBatch"]>>(async () => ({
|
|
ingestedCount: 0,
|
|
}));
|
|
const maintain = vi.fn<NonNullable<ContextEngine["maintain"]>>(async () =>
|
|
createMaintenanceResult(),
|
|
);
|
|
const dispose = vi.fn(async () => {});
|
|
const contextEngine = createContextEngine({
|
|
bootstrap,
|
|
afterTurn,
|
|
ingestBatch,
|
|
maintain,
|
|
dispose,
|
|
});
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await expect(runPreparedCliAgent(buildPreparedContext(contextEngine))).rejects.toMatchObject({
|
|
name: "FailoverError",
|
|
reason: "empty_response",
|
|
provider: "claude-cli",
|
|
model: "sonnet-4.6",
|
|
sessionId: "openclaw-session-1",
|
|
});
|
|
|
|
expect(bootstrap).toHaveBeenCalledTimes(1);
|
|
expect(afterTurn).not.toHaveBeenCalled();
|
|
expect(ingestBatch).not.toHaveBeenCalled();
|
|
expect(maintain).toHaveBeenCalledTimes(1);
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not dispose context engines when CLI attempts fail", async () => {
|
|
executePreparedCliRunMock.mockRejectedValue(new Error("cli boom"));
|
|
const dispose = vi.fn(async () => {
|
|
throw new Error("dispose boom");
|
|
});
|
|
const contextEngine = createContextEngine({ dispose });
|
|
const { runPreparedCliAgent } = await import("./cli-runner.js");
|
|
|
|
await expect(runPreparedCliAgent(buildPreparedContext(contextEngine))).rejects.toThrow(
|
|
"cli boom",
|
|
);
|
|
|
|
expect(dispose).not.toHaveBeenCalled();
|
|
});
|
|
});
|