Просмотр исходного кода

fix: negotiate missing tools with bounded compatibility recovery

hetaoBackend 2 месяцев назад
Родитель
Сommit
9099391692

+ 18 - 0
docs/examples.md

@@ -68,6 +68,24 @@ pnpm mcode provider list --json
 
 
 [Live acceptance](verification.md) separately verified MiniMax Token Plan and one configured BYOK provider. This is not a guarantee for every compatible service.
 [Live acceptance](verification.md) separately verified MiniMax Token Plan and one configured BYOK provider. This is not a guarantee for every compatible service.
 
 
+### OpenAI-compatible gateways and tool history
+
+Checkpoint requests retain historical tool calls/results without offering new tools. Some gateways reject `tools: []`, while others require it for that history. With no override, MCode omits the field and retries with an empty array once only after a recognized missing-tools HTTP 400. Recognition is limited to a structured missing-required-parameter/argument code for `tools` or the known LiteLLM Anthropic missing-tools error. Other errors and failures after a response stream begins do not trigger this recovery.
+
+For a gateway with a known requirement, set `compat.requiresToolsForToolHistory` on the existing model entry in your active profile's `config.yaml`:
+
+```yaml
+custom_provider:
+  my-provider:
+    # Preserve this provider's existing API, options, and other model settings.
+    models:
+      my-model:
+        compat:
+          requiresToolsForToolHistory: true
+```
+
+`true` sends empty tools proactively when history contains tools but no current definitions are supplied. `false` omits the field and disables automatic recovery in that case. Leaving the field unset enables the bounded recovery above. Nonempty tool definitions are preserved in all modes. This setting is independent of `cacheControlFormat`; prompt-cache support does not determine the tools requirement. These behaviors are covered by offline HTTP fixtures, not a guarantee for every live gateway/version.
+
 ## 3. Search and image input
 ## 3. Search and image input
 
 
 After signing in to MiniMax, try a task that explicitly requires search:
 After signing in to MiniMax, try a task that explicitly requires search:

+ 1 - 0
packages/local-runtime-v2/src/service/model-system/contracts.ts

@@ -35,6 +35,7 @@ export interface LocalModelCompatOverrides {
   supportsReasoningEffort?: boolean;
   supportsReasoningEffort?: boolean;
   supportsUsageInStreaming?: boolean;
   supportsUsageInStreaming?: boolean;
   requiresToolResultName?: boolean;
   requiresToolResultName?: boolean;
+  requiresToolsForToolHistory?: boolean;
   requiresAssistantAfterToolResult?: boolean;
   requiresAssistantAfterToolResult?: boolean;
   requiresThinkingAsText?: boolean;
   requiresThinkingAsText?: boolean;
   requiresReasoningContentOnAssistantMessages?: boolean;
   requiresReasoningContentOnAssistantMessages?: boolean;

+ 5 - 0
packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.test.ts

@@ -1383,6 +1383,11 @@ describe('LocalModelResolver custom provider compat overrides', () => {
     expect(resolved.model.compat).toBeUndefined();
     expect(resolved.model.compat).toBeUndefined();
   });
   });
 
 
+  it.each([true, false])('forwards requiresToolsForToolHistory=%s to the provider model', async (value) => {
+    const resolved = await resolveWithCompat({ requiresToolsForToolHistory: value });
+    expect(resolved.model.compat).toMatchObject({ requiresToolsForToolHistory: value });
+  });
+
   // The incident was a wire-level symptom: pi chooses the system prompt role from the
   // The incident was a wire-level symptom: pi chooses the system prompt role from the
   // resolved compat, so these two cases pin the request pi would actually send.
   // resolved compat, so these two cases pin the request pi would actually send.
   const reasoningModelConfig: LocalModelConfig = {
   const reasoningModelConfig: LocalModelConfig = {

+ 9 - 0
packages/local-runtime-v2/src/service/model-system/resolution/model-resolver-byok.test.ts

@@ -281,6 +281,15 @@ describe('custom BYOK compat overrides', () => {
     });
     });
   });
   });
 
 
+  it.each([true, false])('preserves requiresToolsForToolHistory=%s independently of caching', (value) => {
+    expect(planWithCompat(JSON.stringify({ compat: { requiresToolsForToolHistory: value } })))
+      .toEqual({ requiresToolsForToolHistory: value });
+  });
+
+  it('rejects a string-valued tools-history compatibility flag', () => {
+    expect(planWithCompat('{"compat":{"requiresToolsForToolHistory":"false"}}')).toBeUndefined();
+  });
+
   it('drops a boolean field carrying a truthy string instead of a boolean', () => {
   it('drops a boolean field carrying a truthy string instead of a boolean', () => {
     expect(planWithCompat('{"compat":{"supportsDeveloperRole":"false"}}')).toBeUndefined();
     expect(planWithCompat('{"compat":{"supportsDeveloperRole":"false"}}')).toBeUndefined();
   });
   });

+ 1 - 0
packages/local-runtime-v2/src/service/model-system/resolution/model-resolver-byok.ts

@@ -183,6 +183,7 @@ const BOOLEAN_COMPAT_KEYS = [
   'supportsReasoningEffort',
   'supportsReasoningEffort',
   'supportsUsageInStreaming',
   'supportsUsageInStreaming',
   'requiresToolResultName',
   'requiresToolResultName',
+  'requiresToolsForToolHistory',
   'requiresAssistantAfterToolResult',
   'requiresAssistantAfterToolResult',
   'requiresThinkingAsText',
   'requiresThinkingAsText',
   'requiresReasoningContentOnAssistantMessages',
   'requiresReasoningContentOnAssistantMessages',

+ 279 - 14
packages/local-runtime-v2/test/integration/compaction-openai-transport.integration.test.ts

@@ -3,13 +3,21 @@ import type { AddressInfo } from "node:net";
 
 
 import { streamSimple, type Context, type Model } from "@earendil-works/pi-ai";
 import { streamSimple, type Context, type Model } from "@earendil-works/pi-ai";
 import { Type } from "typebox";
 import { Type } from "typebox";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
 
 
 import { compactContext } from "../../src/service/turn-system/compaction/algorithm/compact-context.js";
 import { compactContext } from "../../src/service/turn-system/compaction/algorithm/compact-context.js";
 import { createCheckpointSession } from "../../src/service/turn-system/compaction/execution/checkpoint-provider.js";
 import { createCheckpointSession } from "../../src/service/turn-system/compaction/execution/checkpoint-provider.js";
 
 
 const summary =
 const summary =
   "The synthetic file was read. Continue with the pending user request.";
   "The synthetic file was read. Continue with the pending user request.";
+const missingTools =
+  "litellm.UnsupportedParamsError: Anthropic doesn't support tool calling without `tools=` param specified";
+interface Rejection {
+  status: number;
+  message: string;
+  param?: string;
+  code?: string;
+}
 
 
 function history(model: Model<"openai-completions">): Context["messages"] {
 function history(model: Model<"openai-completions">): Context["messages"] {
   return [
   return [
@@ -54,10 +62,14 @@ describe("OpenAI compaction HTTP transport", () => {
   let model: Model<"openai-completions">;
   let model: Model<"openai-completions">;
   let requests: Record<string, unknown>[];
   let requests: Record<string, unknown>[];
   let allowEmptyTools: boolean;
   let allowEmptyTools: boolean;
+  let rejectRequest: (body: Record<string, unknown>) => Rejection | undefined;
+  let incompleteStream: boolean;
 
 
   beforeEach(async () => {
   beforeEach(async () => {
     requests = [];
     requests = [];
     allowEmptyTools = false;
     allowEmptyTools = false;
+    rejectRequest = () => undefined;
+    incompleteStream = false;
     // Exercise the real SDK serializer and stream parser with a local fixture.
     // Exercise the real SDK serializer and stream parser with a local fixture.
     // This models the reported validation rule, not acceptance by a live service.
     // This models the reported validation rule, not acceptance by a live service.
     server = createServer(async (request, response) => {
     server = createServer(async (request, response) => {
@@ -65,6 +77,14 @@ describe("OpenAI compaction HTTP transport", () => {
       for await (const chunk of request) raw += chunk;
       for await (const chunk of request) raw += chunk;
       const body = JSON.parse(raw);
       const body = JSON.parse(raw);
       requests.push(body);
       requests.push(body);
+      const rejection = rejectRequest(body);
+      if (rejection) {
+        const { status, ...error } = rejection;
+        response
+          .writeHead(status, { "content-type": "application/json" })
+          .end(JSON.stringify({ error }));
+        return;
+      }
       if (
       if (
         !allowEmptyTools &&
         !allowEmptyTools &&
         Array.isArray(body.tools) &&
         Array.isArray(body.tools) &&
@@ -92,6 +112,10 @@ describe("OpenAI compaction HTTP transport", () => {
           ],
           ],
         })}\n\n`,
         })}\n\n`,
       );
       );
+      if (incompleteStream) {
+        response.end();
+        return;
+      }
       response.end(
       response.end(
         `data: ${JSON.stringify({
         `data: ${JSON.stringify({
           choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
           choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
@@ -129,10 +153,21 @@ describe("OpenAI compaction HTTP transport", () => {
     );
     );
   });
   });
 
 
-  it.each(["custom", "openai"])(
-    "compacts tool history through the %s provider without empty tools",
-    async (provider) => {
+  it.each([
+    { provider: "custom", requiresTools: false },
+    { provider: "openai", requiresTools: false },
+    { provider: "custom", requiresTools: true },
+  ])(
+    "compacts tool history through $provider (backend requires tools: $requiresTools)",
+    async ({ provider, requiresTools }) => {
       model = { ...model, provider };
       model = { ...model, provider };
+      if (requiresTools) {
+        allowEmptyTools = true;
+        rejectRequest = (body) =>
+          body.tools === undefined
+            ? { status: 400, message: missingTools }
+            : undefined;
+      }
       const result = await compactContext({
       const result = await compactContext({
         history: history(model),
         history: history(model),
         allowLegacyToolTrim: false,
         allowLegacyToolTrim: false,
@@ -159,8 +194,10 @@ describe("OpenAI compaction HTTP transport", () => {
             }),
             }),
         },
         },
       });
       });
-      expect(requests).toHaveLength(1);
+      expect(requests).toHaveLength(requiresTools ? 2 : 1);
       expect(requests[0]).not.toHaveProperty("tools");
       expect(requests[0]).not.toHaveProperty("tools");
+      if (requiresTools)
+        expect(requests[1]).toEqual({ ...requests[0], tools: [] });
       expect(requests[0]).not.toHaveProperty("tool_choice");
       expect(requests[0]).not.toHaveProperty("tool_choice");
       expect(requests[0].messages).toEqual(
       expect(requests[0].messages).toEqual(
         expect.arrayContaining([
         expect.arrayContaining([
@@ -200,23 +237,26 @@ describe("OpenAI compaction HTTP transport", () => {
     expect(result.stopReason).toBe("stop");
     expect(result.stopReason).toBe("stop");
   });
   });
 
 
-  it.each(["explicit", "detected"])(
-    "preserves the %s Anthropic proxy workaround even with caching disabled",
-    async (mode) => {
+  it.each(["short", "none"] as const)(
+    "honors the independent tools requirement with cache retention %s",
+    async (cacheRetention) => {
       allowEmptyTools = true;
       allowEmptyTools = true;
-      model =
-        mode === "explicit"
-          ? { ...model, compat: { cacheControlFormat: "anthropic" } }
-          : { ...model, provider: "openrouter", id: "anthropic/fixture-model" };
+      model = { ...model, compat: { requiresToolsForToolHistory: true } };
+      rejectRequest = (body) =>
+        body.tools === undefined &&
+        JSON.stringify(body.messages).includes("tool_calls")
+          ? { status: 400, message: missingTools }
+          : undefined;
       const result = await streamSimple(
       const result = await streamSimple(
         model,
         model,
         { messages: history(model) },
         { messages: history(model) },
         {
         {
           apiKey: "synthetic-key",
           apiKey: "synthetic-key",
-          cacheRetention: "none",
+          cacheRetention,
         },
         },
       ).result();
       ).result();
       expect(result.stopReason).toBe("stop");
       expect(result.stopReason).toBe("stop");
+      expect(requests).toHaveLength(1);
       expect(requests[0].tools).toEqual([]);
       expect(requests[0].tools).toEqual([]);
 
 
       await streamSimple(
       await streamSimple(
@@ -227,13 +267,238 @@ describe("OpenAI compaction HTTP transport", () => {
         },
         },
         {
         {
           apiKey: "synthetic-key",
           apiKey: "synthetic-key",
-          cacheRetention: "none",
+          cacheRetention,
         },
         },
       ).result();
       ).result();
       expect(requests[1]).not.toHaveProperty("tools");
       expect(requests[1]).not.toHaveProperty("tools");
     },
     },
   );
   );
 
 
+  it.each(["explicit", "detected"])(
+    "does not infer a tools requirement from %s Anthropic caching",
+    async (mode) => {
+      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" },
+      ).result();
+      expect(result.stopReason).toBe("stop");
+      expect(requests).toHaveLength(1);
+      expect(requests[0]).not.toHaveProperty("tools");
+    },
+  );
+
+  it.each(["missing_required_parameter", "missing_required_argument"])(
+    "recovers once from structured %s for tools",
+    async (code) => {
+      allowEmptyTools = true;
+      rejectRequest = (body) =>
+        body.tools === undefined
+          ? {
+              status: 400,
+              message: "Required field missing",
+              param: "tools",
+              code,
+            }
+          : undefined;
+      const onPayload = vi.fn((payload: unknown) => ({
+        ...(payload as Record<string, unknown>),
+        user: "synthetic-user",
+      }));
+      const result = await streamSimple(
+        model,
+        { messages: history(model) },
+        { apiKey: "synthetic-key", onPayload },
+      ).result();
+      expect(result.stopReason).toBe("stop");
+      expect(requests).toHaveLength(2);
+      expect(onPayload).toHaveBeenCalledTimes(2);
+      expect(requests[1]).toEqual({ ...requests[0], tools: [] });
+    },
+  );
+
+  it("does not retry again if the recovery request also fails", async () => {
+    rejectRequest = () => ({ status: 400, message: missingTools });
+    const result = await streamSimple(
+      model,
+      { messages: history(model) },
+      { apiKey: "synthetic-key" },
+    ).result();
+    expect(requests).toHaveLength(2);
+    expect(requests[1].tools).toEqual([]);
+    expect(result.stopReason).toBe("error");
+  });
+
+  it("disables SDK retries on the recovery request", async () => {
+    rejectRequest = (body) =>
+      body.tools === undefined
+        ? { status: 400, message: missingTools }
+        : { status: 500, message: "Synthetic server failure" };
+    const result = await streamSimple(
+      model,
+      { messages: history(model) },
+      {
+        apiKey: "synthetic-key",
+        maxRetries: 3,
+      },
+    ).result();
+    expect(requests).toHaveLength(2);
+    expect(result.stopReason).toBe("error");
+  });
+
+  it.each([
+    "no history",
+    "nonempty definitions",
+    "explicit true",
+    "hook tools",
+  ])("does not recover with %s", async (mode) => {
+    rejectRequest = () => ({ status: 400, message: missingTools });
+    if (mode === "explicit true")
+      model = { ...model, compat: { requiresToolsForToolHistory: true } };
+    const context: Context = {
+      messages:
+        mode === "no history"
+          ? [{ role: "user", content: "Hello", timestamp: 1 }]
+          : history(model),
+    };
+    if (mode === "nonempty definitions")
+      context.tools = [
+        {
+          name: "read",
+          description: "Read a file",
+          parameters: Type.Object({}),
+        },
+      ];
+    const result = await streamSimple(model, context, {
+      apiKey: "synthetic-key",
+      onPayload:
+        mode === "hook tools"
+          ? (payload) => ({
+              ...(payload as Record<string, unknown>),
+              tools: [],
+            })
+          : undefined,
+    }).result();
+    expect(requests).toHaveLength(1);
+    expect(result.stopReason).toBe("error");
+  });
+
+  it.each([
+    {
+      status: 400,
+      message: "tools must not be an empty array",
+      param: "tools",
+    },
+    { status: 400, message: "invalid tool schema", param: "tools" },
+    { status: 400, message: `Invalid user content: ${missingTools}` },
+    {
+      status: 400,
+      message: "Required field missing",
+      param: "messages",
+      code: "missing_required_parameter",
+    },
+    ...[401, 403, 429, 500].map((status) => ({
+      status,
+      message: missingTools,
+    })),
+  ])(
+    "does not recover unrelated error $status: $message ($param)",
+    async (rejection) => {
+      rejectRequest = () => rejection;
+      const result = await streamSimple(
+        model,
+        { messages: history(model) },
+        { apiKey: "synthetic-key" },
+      ).result();
+      expect(requests).toHaveLength(1);
+      expect(result.stopReason).toBe("error");
+    },
+  );
+
+  it("honors explicit false even when the backend requires tools", async () => {
+    model = { ...model, compat: { requiresToolsForToolHistory: false } };
+    rejectRequest = () => ({ status: 400, message: missingTools });
+    const result = await streamSimple(
+      model,
+      { messages: history(model) },
+      { apiKey: "synthetic-key" },
+    ).result();
+    expect(requests).toHaveLength(1);
+    expect(result.stopReason).toBe("error");
+  });
+
+  it("does not recover without tool history in the final payload", async () => {
+    rejectRequest = () => ({ status: 400, message: missingTools });
+    const result = await streamSimple(
+      model,
+      { messages: history(model) },
+      {
+        apiKey: "synthetic-key",
+        onPayload: (payload) => ({
+          ...(payload as Record<string, unknown>),
+          messages: [{ role: "user", content: "Hello" }],
+        }),
+      },
+    ).result();
+    expect(requests).toHaveLength(1);
+    expect(result.stopReason).toBe("error");
+  });
+
+  it("does not resend when a payload hook removes the recovery tools", async () => {
+    rejectRequest = () => ({ status: 400, message: missingTools });
+    const onPayload = vi.fn((payload: unknown) => {
+      const { tools: _tools, ...rest } = payload as Record<string, unknown>;
+      return rest;
+    });
+    const result = await streamSimple(
+      model,
+      { messages: history(model) },
+      { apiKey: "synthetic-key", onPayload },
+    ).result();
+    expect(onPayload).toHaveBeenCalledTimes(2);
+    expect(requests).toHaveLength(1);
+    expect(result.stopReason).toBe("error");
+  });
+
+  it("honors cancellation during the recovery payload hook", async () => {
+    rejectRequest = () => ({ status: 400, message: missingTools });
+    const controller = new AbortController();
+    const onPayload = vi.fn((payload: unknown) => {
+      if (Array.isArray((payload as Record<string, unknown>).tools))
+        controller.abort();
+    });
+    const result = await streamSimple(
+      model,
+      { messages: history(model) },
+      {
+        apiKey: "synthetic-key",
+        signal: controller.signal,
+        onPayload,
+      },
+    ).result();
+    expect(onPayload).toHaveBeenCalledTimes(2);
+    expect(requests).toHaveLength(1);
+    expect(result.stopReason).toBe("aborted");
+  });
+
+  it("does not restart a response stream that ended without a finish reason", async () => {
+    incompleteStream = true;
+    const result = await streamSimple(
+      model,
+      { messages: history(model) },
+      { apiKey: "synthetic-key" },
+    ).result();
+    expect(requests).toHaveLength(1);
+    expect(result.content).toEqual([
+      expect.objectContaining({ type: "text", text: summary }),
+    ]);
+    expect(result.stopReason).toBe("error");
+  });
+
   it("preserves nonempty tool definitions on ordinary agent requests", async () => {
   it("preserves nonempty tool definitions on ordinary agent requests", async () => {
     const result = await streamSimple(
     const result = await streamSimple(
       model,
       model,

+ 1 - 0
packages/local-runtime/src/context/token-counter-adapters/openai-chat-tokenizers.ts

@@ -30,6 +30,7 @@ const BASE_CHAT_COMPAT: OpenAICompletionsCompat = {
   supportsUsageInStreaming: true,
   supportsUsageInStreaming: true,
   maxTokensField: 'max_tokens',
   maxTokensField: 'max_tokens',
   requiresToolResultName: false,
   requiresToolResultName: false,
+  requiresToolsForToolHistory: false,
   requiresAssistantAfterToolResult: false,
   requiresAssistantAfterToolResult: false,
   requiresThinkingAsText: false,
   requiresThinkingAsText: false,
   requiresReasoningContentOnAssistantMessages: false,
   requiresReasoningContentOnAssistantMessages: false,

+ 3 - 3
third_party/pi-mono/MINIMAX_CHANGES.md

@@ -16,9 +16,9 @@ No upstream source files are changed in the baseline import.
 ### 2026-09-19 — omit empty tools for ordinary OpenAI-compatible checkpoint requests
 ### 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).
 - 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.
+- Affected package: `packages/ai` (`@earendil-works/pi-ai`), `src/providers/openai-completions.ts`, `src/types.ts`, and its existing empty-tools regression fixture. The distribution's BYOK model resolver forwards the new compatibility field.
+- Change type: generic, upstreamable compatibility fix. `compat.requiresToolsForToolHistory` is independent of caching and provider/model naming: `true` proactively sends empty tools for tool history, `false` suppresses the field and automatic recovery when definitions are absent, and unset omits initially but permits one recovery request after a recognized missing-tools HTTP 400. Recognition requires either a structured missing-required-parameter/argument code for `tools` or the known LiteLLM Anthropic missing-tools message (upstream issue earendil-works/pi#149). Nonempty tools are unchanged. Recovery reruns payload hooks, honors cancellation, disables SDK retries for the recovery request, and never restarts a response stream or handles unrelated failures. No endpoint-wide capability cache is introduced.
+- 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 local HTTP fixtures that reject empty tools or require tools. Regressions also cover independent compatibility overrides, BYOK resolution, payload hooks, cancellation, terminal errors, and bounded recovery. Run with `pnpm exec vitest run --config vitest.oss.config.mjs packages/local-runtime-v2/test/integration/compaction-openai-transport.integration.test.ts packages/local-runtime-v2/src/service/model-system/resolution/model-resolver-byok.test.ts packages/local-runtime-v2/src/service/model-system/resolution/local-model-resolver.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.
 - Upstream PR: not created.
 
 
 ### 2026-08-31 — Windows PowerShell ConstrainedLanguage compatibility
 ### 2026-08-31 — Windows PowerShell ConstrainedLanguage compatibility

+ 54 - 9
third_party/pi-mono/packages/ai/src/providers/openai-completions.ts

@@ -59,6 +59,24 @@ function hasToolHistory(messages: Message[]): boolean {
 	return false;
 	return false;
 }
 }
 
 
+/** Recognize missing tools, never generic tool-validation or empty-array errors. */
+function isMissingToolsError(error: unknown): boolean {
+	if (!error || typeof error !== "object" || Reflect.get(error, "status") !== 400) return false;
+	const detail = Reflect.get(error, "error");
+	if (!detail || typeof detail !== "object") return false;
+	if (
+		Reflect.get(detail, "param") === "tools" &&
+		["missing_required_parameter", "missing_required_argument"].includes(Reflect.get(detail, "code"))
+	) {
+		return true;
+	}
+	const message = Reflect.get(detail, "message");
+	return (
+		typeof message === "string" &&
+		/^(?:litellm\.UnsupportedParamsError:\s*)?Anthropic doesn't support tool calling without `?tools=`? param specified\b/i.test(message)
+	);
+}
+
 function isTextContentBlock(block: { type: string }): block is TextContent {
 function isTextContentBlock(block: { type: string }): block is TextContent {
 	return block.type === "text";
 	return block.type === "text";
 }
 }
@@ -144,11 +162,14 @@ export const streamOpenAICompletions: StreamFunction<"openai-completions", OpenA
 			const cacheRetention = resolveCacheRetention(options?.cacheRetention);
 			const cacheRetention = resolveCacheRetention(options?.cacheRetention);
 			const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;
 			const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;
 			const client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat, options?.fetch);
 			const client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat, options?.fetch);
-			let params = buildParams(model, context, options, compat, cacheRetention);
-			const nextParams = await options?.onPayload?.(params, model);
-			if (nextParams !== undefined) {
-				params = nextParams as OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming;
-			}
+			const prepareParams = async (includeEmptyTools = false) => {
+				const params = buildParams(model, context, options, compat, cacheRetention);
+				if (includeEmptyTools) params.tools = [];
+				const nextParams = await options?.onPayload?.(params, model);
+				options?.signal?.throwIfAborted();
+				return nextParams === undefined ? params : (nextParams as typeof params);
+			};
+			const params = await prepareParams();
 			const requestOptions = {
 			const requestOptions = {
 				...(options?.signal ? { signal: options.signal } : {}),
 				...(options?.signal ? { signal: options.signal } : {}),
 				...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
 				...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
@@ -156,7 +177,29 @@ export const streamOpenAICompletions: StreamFunction<"openai-completions", OpenA
 			};
 			};
 			const { data: openaiStream, response } = await client.chat.completions
 			const { data: openaiStream, response } = await client.chat.completions
 				.create(params, requestOptions)
 				.create(params, requestOptions)
-				.withResponse();
+				.withResponse()
+				.catch(async (error: unknown) => {
+					// Recover only before any response stream starts. Explicit false, real
+					// tool definitions, and payload transforms that remove history take precedence.
+					if (
+						model.compat?.requiresToolsForToolHistory === false ||
+						context.tools?.length ||
+						params.tools !== undefined ||
+						!params.messages.some(
+							(message) => message.role === "tool" || (message.role === "assistant" && message.tool_calls?.length),
+						) ||
+						!isMissingToolsError(error)
+					) {
+						throw error;
+					}
+					options?.signal?.throwIfAborted();
+					const retryParams = await prepareParams(true);
+					if (!Array.isArray(retryParams.tools) || retryParams.tools.length !== 0) throw error;
+					// No loop and no SDK retries: at most one compatibility recovery request.
+					return client.chat.completions
+						.create(retryParams, { ...requestOptions, maxRetries: 0 })
+						.withResponse();
+				});
 			await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
 			await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
 			stream.push({ type: "start", partial: output });
 			stream.push({ type: "start", partial: output });
 
 
@@ -545,9 +588,9 @@ function buildParams(
 		if (compat.zaiToolStream) {
 		if (compat.zaiToolStream) {
 			(params as any).tool_stream = true;
 			(params as any).tool_stream = true;
 		}
 		}
-	} 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.
+	} else if (compat.requiresToolsForToolHistory && hasToolHistory(context.messages)) {
+		// Some proxies require this field; others reject empty arrays. Do not infer
+		// the requirement from prompt-cache support or a model/provider name.
 		params.tools = [];
 		params.tools = [];
 	}
 	}
 
 
@@ -1131,6 +1174,7 @@ function detectCompat(model: Model<"openai-completions">): ResolvedOpenAIComplet
 		supportsUsageInStreaming: true,
 		supportsUsageInStreaming: true,
 		maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens",
 		maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens",
 		requiresToolResultName: false,
 		requiresToolResultName: false,
+		requiresToolsForToolHistory: false,
 		requiresAssistantAfterToolResult: false,
 		requiresAssistantAfterToolResult: false,
 		requiresThinkingAsText: false,
 		requiresThinkingAsText: false,
 		requiresReasoningContentOnAssistantMessages: isDeepSeek,
 		requiresReasoningContentOnAssistantMessages: isDeepSeek,
@@ -1176,6 +1220,7 @@ function getCompat(model: Model<"openai-completions">): ResolvedOpenAICompletion
 		supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,
 		supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,
 		maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,
 		maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,
 		requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,
 		requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,
+		requiresToolsForToolHistory: model.compat.requiresToolsForToolHistory ?? detected.requiresToolsForToolHistory,
 		requiresAssistantAfterToolResult:
 		requiresAssistantAfterToolResult:
 			model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,
 			model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,
 		requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,
 		requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,

+ 2 - 0
third_party/pi-mono/packages/ai/src/types.ts

@@ -411,6 +411,8 @@ export interface OpenAICompletionsCompat {
 	maxTokensField?: "max_completion_tokens" | "max_tokens";
 	maxTokensField?: "max_completion_tokens" | "max_tokens";
 	/** Whether tool results require the `name` field. Default: auto-detected from URL. */
 	/** Whether tool results require the `name` field. Default: auto-detected from URL. */
 	requiresToolResultName?: boolean;
 	requiresToolResultName?: boolean;
+	/** Send `tools: []` for tool history without current definitions. True: always; false: never (including automatic recovery). Unset: omit initially, retry once only on a recognized missing-tools HTTP 400. Independent of prompt caching. */
+	requiresToolsForToolHistory?: boolean;
 	/** Whether a user message after tool results requires an assistant message in between. Default: auto-detected from URL. */
 	/** Whether a user message after tool results requires an assistant message in between. Default: auto-detected from URL. */
 	requiresAssistantAfterToolResult?: boolean;
 	requiresAssistantAfterToolResult?: boolean;
 	/** Whether thinking blocks must be converted to text blocks with <thinking> delimiters. Default: auto-detected from URL. */
 	/** Whether thinking blocks must be converted to text blocks with <thinking> delimiters. Default: auto-detected from URL. */

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