Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(agent): keep compacted search results valid JSON

Sidwebworks9ffc20612955
diff --git a/apps/erp/app/modules/agent/agent.history.test.ts b/apps/erp/app/modules/agent/agent.history.test.ts
index 2068fd813e..a6ce3aecb9 100644
--- a/apps/erp/app/modules/agent/agent.history.test.ts
+++ b/apps/erp/app/modules/agent/agent.history.test.ts
@@ -1,4 +1,4 @@
-import type { UIMessage } from "ai";
+import { convertToModelMessages, modelMessageSchema, type UIMessage } from "ai";
import { describe, expect, it } from "vitest";
import { compactEarlierToolOutputs } from "./agent.history";
@@ -21,6 +21,11 @@ const assistantThatRead = (id: string): UIMessage =>
state: "output-available",
input: { query: "batching" },
output: [
+ {
+ title: "Operation batching",
+ url: "https://docs.carbon.ms/docs/reference/batching",
+ snippet: "Operation batching groups unstarted operations…"
+ },
{
title: "Operation batching",
section: "Building a batch",
@@ -60,6 +65,10 @@ describe("compactEarlierToolOutputs", () => {
note: "Read in an earlier turn; read_doc again for the text."
});
expect(search!.output).toEqual([
+ {
+ title: "Operation batching",
+ url: "https://docs.carbon.ms/docs/reference/batching"
+ },
{
title: "Operation batching",
section: "Building a batch",
@@ -70,6 +79,16 @@ describe("compactEarlierToolOutputs", () => {
expect(JSON.stringify(earlier).length).toBeLessThan(1_000);
});
+ it("produces a prompt the AI SDK accepts, including an intro hit with no section", () => {
+ const compacted = compactEarlierToolOutputs([
+ user("what is batching"),
+ assistantThatRead("a1"),
+ user("and how do I start one")
+ ]);
+ const prompt = convertToModelMessages(compacted);
+ expect(modelMessageSchema.array().safeParse(prompt).success).toBe(true);
+ });
+
it("leaves the current turn untouched", () => {
const messages = [user("what is batching"), assistantThatRead("a1")];
expect(compactEarlierToolOutputs(messages)).toEqual(messages);
diff --git a/apps/erp/app/modules/agent/agent.history.ts b/apps/erp/app/modules/agent/agent.history.ts
index b2f9eac9c3..2bdf49bed2 100644
--- a/apps/erp/app/modules/agent/agent.history.ts
+++ b/apps/erp/app/modules/agent/agent.history.ts
@@ -29,7 +29,13 @@ function compactToolOutput(toolName: string, output: unknown): unknown {
: output;
}
if (toolName === "search_docs" && Array.isArray(output)) {
- return output.map(({ title, section, url }) => ({ title, section, url }));
+ // A tool result must be a JSON value: an intro hit has no section, and a key set to
+ // `undefined` fails the SDK's prompt validation for the whole request.
+ return output.map(({ title, section, url }) => ({
+ title,
+ url,
+ ...(section ? { section } : {})
+ }));
}
return output;
}