Parcourir la source

fix: omit empty tools on OpenAI compaction requests

hetaoBackend il y a 2 mois
Parent
commit
58fab782f7

+ 260 - 0
packages/local-runtime-v2/test/integration/compaction-openai-transport.integration.test.ts

@@ -0,0 +1,260 @@
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+
+import { streamSimple, type Context, type Model } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { compactContext } from "../../src/service/turn-system/compaction/algorithm/compact-context.js";
+import { createCheckpointSession } from "../../src/service/turn-system/compaction/execution/checkpoint-provider.js";
+
+const summary =
+  "The synthetic file was read. Continue with the pending user request.";
+
+function history(model: Model<"openai-completions">): Context["messages"] {
+  return [
+    { role: "user", content: "Read the synthetic file.", timestamp: 1 },
+    {
+      role: "assistant",
+      content: [
+        {
+          type: "toolCall",
+          id: "read-1",
+          name: "read",
+          arguments: { path: "fixture.txt" },
+        },
+      ],
+      api: model.api,
+      provider: model.provider,
+      model: model.id,
+      stopReason: "toolUse",
+      timestamp: 2,
+      usage: {
+        input: 100,
+        output: 10,
+        cacheRead: 0,
+        cacheWrite: 0,
+        totalTokens: 110,
+        cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+      },
+    },
+    {
+      role: "toolResult",
+      toolCallId: "read-1",
+      toolName: "read",
+      content: [{ type: "text", text: "Synthetic file contents." }],
+      isError: false,
+      timestamp: 3,
+    },
+  ];
+}
+
+describe("OpenAI compaction HTTP transport", () => {
+  let server: ReturnType<typeof createServer>;
+  let model: Model<"openai-completions">;
+  let requests: Record<string, unknown>[];
+  let allowEmptyTools: boolean;
+
+  beforeEach(async () => {
+    requests = [];
+    allowEmptyTools = false;
+    // Exercise the real SDK serializer and stream parser with a local fixture.
+    // This models the reported validation rule, not acceptance by a live service.
+    server = createServer(async (request, response) => {
+      let raw = "";
+      for await (const chunk of request) raw += chunk;
+      const body = JSON.parse(raw);
+      requests.push(body);
+      if (
+        !allowEmptyTools &&
+        Array.isArray(body.tools) &&
+        body.tools.length === 0
+      ) {
+        response.writeHead(400, { "content-type": "application/json" }).end(
+          JSON.stringify({
+            error: {
+              message: "tools must not be an empty array",
+              type: "invalid_request_error",
+              param: "tools",
+            },
+          }),
+        );
+        return;
+      }
+      response.writeHead(200, { "content-type": "text/event-stream" });
+      response.write(
+        `data: ${JSON.stringify({
+          id: "synthetic-checkpoint",
+          object: "chat.completion.chunk",
+          model: body.model,
+          choices: [
+            { index: 0, delta: { content: summary }, finish_reason: null },
+          ],
+        })}\n\n`,
+      );
+      response.end(
+        `data: ${JSON.stringify({
+          choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
+          usage: {
+            prompt_tokens: 100,
+            completion_tokens: 15,
+            total_tokens: 115,
+          },
+        })}\n\ndata: [DONE]\n\n`,
+      );
+    });
+    await new Promise<void>((resolve, reject) => {
+      server.once("error", reject);
+      server.listen(0, "127.0.0.1", resolve);
+    });
+    model = {
+      id: "fixture-model",
+      name: "Fixture model",
+      api: "openai-completions",
+      provider: "custom",
+      baseUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`,
+      reasoning: false,
+      input: ["text"],
+      contextWindow: 32_768,
+      maxTokens: 4096,
+      cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+    };
+  });
+
+  afterEach(async () => {
+    if (!server?.listening) return;
+    server.closeAllConnections();
+    await new Promise<void>((resolve, reject) =>
+      server.close((error) => (error ? reject(error) : resolve())),
+    );
+  });
+
+  it.each(["custom", "openai"])(
+    "compacts tool history through the %s provider without empty tools",
+    async (provider) => {
+      model = { ...model, provider };
+      const result = await compactContext({
+        history: history(model),
+        allowLegacyToolTrim: false,
+        limits: {
+          providerInputLimit: 20_000,
+          maxSerializedInputBytes: 100_000,
+        },
+        // Admission is synthetic; checkpoint generation and HTTP transport are real.
+        measurePair: async () => ({
+          before: { inputTokens: 1000, serializedBytes: 10_000 },
+          after: { inputTokens: 100, serializedBytes: 1000 },
+        }),
+        checkpoint: {
+          tokensBefore: 1000,
+          timestamp: 4,
+          open: () =>
+            createCheckpointSession({
+              model,
+              streamFn: streamSimple,
+              thinkingLevel: "off",
+              apiKey: "synthetic-key",
+              maxOutputTokens: 1024,
+              providerInputLimit: 20_000,
+            }),
+        },
+      });
+      expect(requests).toHaveLength(1);
+      expect(requests[0]).not.toHaveProperty("tools");
+      expect(requests[0]).not.toHaveProperty("tool_choice");
+      expect(requests[0].messages).toEqual(
+        expect.arrayContaining([
+          expect.objectContaining({
+            role: "assistant",
+            tool_calls: [expect.objectContaining({ id: "read-1" })],
+          }),
+          expect.objectContaining({
+            role: "tool",
+            tool_call_id: "read-1",
+            content: "Synthetic file contents.",
+          }),
+        ]),
+      );
+      expect(result).toMatchObject({
+        method: "llm_checkpoint",
+        summary,
+        generationAttempts: 1,
+      });
+      expect(result.replacementMessages[0]).toMatchObject({
+        role: "compactionSummary",
+      });
+    },
+  );
+
+  it.each([
+    { label: "absent", tools: undefined },
+    { label: "empty", tools: [] },
+  ])("omits $label tool definitions with tool history", async ({ tools }) => {
+    const result = await streamSimple(
+      model,
+      { messages: history(model), tools },
+      { apiKey: "synthetic-key" },
+    ).result();
+    expect(requests).toHaveLength(1);
+    expect(requests[0]).not.toHaveProperty("tools");
+    expect(result.stopReason).toBe("stop");
+  });
+
+  it.each(["explicit", "detected"])(
+    "preserves the %s Anthropic proxy workaround even with caching disabled",
+    async (mode) => {
+      allowEmptyTools = true;
+      model =
+        mode === "explicit"
+          ? { ...model, compat: { cacheControlFormat: "anthropic" } }
+          : { ...model, provider: "openrouter", id: "anthropic/fixture-model" };
+      const result = await streamSimple(
+        model,
+        { messages: history(model) },
+        {
+          apiKey: "synthetic-key",
+          cacheRetention: "none",
+        },
+      ).result();
+      expect(result.stopReason).toBe("stop");
+      expect(requests[0].tools).toEqual([]);
+
+      await streamSimple(
+        model,
+        {
+          messages: [{ role: "user", content: "Hello", timestamp: 1 }],
+          tools: [],
+        },
+        {
+          apiKey: "synthetic-key",
+          cacheRetention: "none",
+        },
+      ).result();
+      expect(requests[1]).not.toHaveProperty("tools");
+    },
+  );
+
+  it("preserves nonempty tool definitions on ordinary agent requests", async () => {
+    const result = await streamSimple(
+      model,
+      {
+        messages: history(model),
+        tools: [
+          {
+            name: "read",
+            description: "Read a synthetic file",
+            parameters: Type.Object({ path: Type.String() }),
+          },
+        ],
+      },
+      { apiKey: "synthetic-key" },
+    ).result();
+    expect(result.stopReason).toBe("stop");
+    expect(requests[0].tools).toEqual([
+      expect.objectContaining({
+        type: "function",
+        function: expect.objectContaining({ name: "read" }),
+      }),
+    ]);
+  });
+});

+ 1 - 0
release/public-source.json

@@ -1443,6 +1443,7 @@
     "packages/local-runtime-v2/src/services.ts",
     "packages/local-runtime-v2/test/helpers/agent-service.ts",
     "packages/local-runtime-v2/test/helpers/plugin-database.ts",
+    "packages/local-runtime-v2/test/integration/compaction-openai-transport.integration.test.ts",
     "packages/local-runtime-v2/test/integration/mcp/local-mcp-public-facade.integration.test.ts",
     "packages/local-runtime-v2/test/integration/mcp/project-mcp.integration.test.ts",
     "packages/local-runtime-v2/test/integration/session-system-queue-repository.integration.test.ts",

+ 1 - 0
test/vitest-suites.json

@@ -2,6 +2,7 @@
   "comment": "Vitest suites for the standalone distribution, grouped by the gate that runs them. `vitest.oss.config.mjs` includes every group; `scripts/run-vitest-suite.mjs <group>` runs one. Add a test file here rather than in package.json or the Vitest config.",
   "suites": {
     "capability": [
+      "packages/local-runtime-v2/test/integration/compaction-openai-transport.integration.test.ts",
       "packages/agent-core/test/unit/bash-subprocess-env.test.ts",
       "packages/agent-modules/permission/test/unit/permission/bash-policy-regressions.test.ts",
       "packages/agent-tools/src/shared/replace-all-edit.test.ts",

+ 8 - 0
third_party/pi-mono/MINIMAX_CHANGES.md

@@ -13,6 +13,14 @@ This directory vendors `pi-mono` as source so MiniMax can patch, validate, and s
 
 No upstream source files are changed in the baseline import.
 
+### 2026-09-19 — omit empty tools for ordinary OpenAI-compatible checkpoint requests
+
+- Reason: checkpoint requests retain tool-call history but omit tool definitions. The OpenAI Completions provider unconditionally added `tools: []` for that history, which can cause a backend to reject compaction with HTTP 400 (public issue MiniMax-AI/minimax-code#194).
+- Affected package: `packages/ai` (`@earendil-works/pi-ai`), `src/providers/openai-completions.ts` and its existing empty-tools regression fixture.
+- Change type: generic, upstreamable compatibility fix. Scope the existing Anthropic proxy workaround to resolved `cacheControlFormat: "anthropic"`, including explicit custom-provider overrides and detected OpenRouter Anthropic models. The workaround remains independent of cache retention; ordinary models omit empty tools while nonempty tool definitions are preserved. Custom Anthropic proxies that need the workaround must declare that compatibility mode.
+- Validation: the distribution-owned `packages/local-runtime-v2/test/integration/compaction-openai-transport.integration.test.ts` exercises `compactContext` through checkpoint generation and the real SDK against a local HTTP fixture. It also covers absent/empty definitions, explicit/detected Anthropic compatibility with caching disabled, and ordinary requests with tools. Run with `pnpm exec vitest run --config vitest.oss.config.mjs packages/local-runtime-v2/test/integration/compaction-openai-transport.integration.test.ts` and the full `pnpm verify` profile. Offline fixtures do not establish live LiteLLM/vLLM, OpenAI, or Anthropic proxy acceptance.
+- Upstream PR: not created.
+
 ### 2026-08-31 — Windows PowerShell ConstrainedLanguage compatibility
 
 - Reason: the Windows PowerShell 5.1 stdin wrapper called `Parser.ParseInput`, `ScriptBlock.Create`, and other restricted .NET APIs before user commands. Under enterprise App Control / AppLocker `ConstrainedLanguage`, the wrapper therefore failed before commands such as Python could run.

+ 3 - 2
third_party/pi-mono/packages/ai/src/providers/openai-completions.ts

@@ -545,8 +545,9 @@ function buildParams(
 		if (compat.zaiToolStream) {
 			(params as any).tool_stream = true;
 		}
-	} else if (hasToolHistory(context.messages)) {
-		// Anthropic (via LiteLLM/proxy) requires tools param when conversation has tool_calls/tool_results
+	} else if (compat.cacheControlFormat === "anthropic" && hasToolHistory(context.messages)) {
+		// Keep the Anthropic proxy workaround scoped to Anthropic-compatible models.
+		// Other OpenAI-compatible backends may reject an empty tools array.
 		params.tools = [];
 	}
 

+ 1 - 1
third_party/pi-mono/packages/ai/test/openai-completions-empty-tools.test.ts

@@ -202,7 +202,7 @@ describe("openai-completions empty tools handling", () => {
 
 	it("still emits tools: [] for Anthropic/LiteLLM proxy when conversation has tool history", async () => {
 		const { compat: _compat, ...baseModel } = getModel("openai", "gpt-4o-mini")!;
-		const model = { ...baseModel, api: "openai-completions" } as const;
+		const model = { ...baseModel, api: "openai-completions", compat: { cacheControlFormat: "anthropic" } } as const;
 
 		await streamSimple(
 			model,