@tanstack/ai
Version:
Core TanStack AI library - Open source AI SDK
97 lines (96 loc) • 2.67 kB
JavaScript
import { RunAgentInputSchema, AGUIError } from "@ag-ui/core";
const KNOWN_PART_TYPES = /* @__PURE__ */ new Set([
"text",
"image",
"audio",
"video",
"document",
"tool-call",
"tool-result",
"thinking"
]);
function isValidParts(value) {
if (!Array.isArray(value)) return false;
for (const p of value) {
if (!p || typeof p !== "object") return false;
const type = p.type;
if (typeof type !== "string" || !KNOWN_PART_TYPES.has(type)) return false;
}
return true;
}
function chatParamsFromRequestBody(body) {
const parseResult = RunAgentInputSchema.safeParse(body);
if (!parseResult.success) {
return Promise.reject(
new AGUIError(
`Request body is not a valid AG-UI RunAgentInput. If you're upgrading from a previous @tanstack/ai-client release, see docs/migration/ag-ui-compliance.md. Validation errors: ${parseResult.error.message}`
)
);
}
const parsed = parseResult.data;
const rawMessages = body.messages ?? [];
const messages = parsed.messages.map((m, i) => {
const raw = rawMessages[i];
if (raw && typeof raw === "object" && "parts" in raw && isValidParts(raw.parts)) {
return { ...m, parts: raw.parts };
}
return m;
});
return Promise.resolve({
messages,
threadId: parsed.threadId,
runId: parsed.runId,
parentRunId: parsed.parentRunId,
tools: parsed.tools,
forwardedProps: parsed.forwardedProps ?? {},
state: parsed.state,
context: parsed.context
});
}
async function chatParamsFromRequest(req) {
let body;
try {
body = await req.json();
} catch (cause) {
const res = new Response(
"Invalid AG-UI request body. See docs/migration/ag-ui-compliance.md.",
{ status: 400 }
);
res.cause = cause;
throw res;
}
try {
return await chatParamsFromRequestBody(body);
} catch (cause) {
const res = new Response(
"Invalid AG-UI request body. See docs/migration/ag-ui-compliance.md.",
{ status: 400 }
);
res.cause = cause;
throw res;
}
}
function mergeAgentTools(serverTools, clientTools) {
const seen = new Set(serverTools.map((t) => t.name));
const merged = [...serverTools];
for (const ct of clientTools) {
if (seen.has(ct.name)) {
continue;
}
seen.add(ct.name);
merged.push({
name: ct.name,
description: ct.description,
inputSchema: ct.parameters
// No `execute` — runtime treats this as a client-side tool and
// emits ClientToolRequest events.
});
}
return merged;
}
export {
chatParamsFromRequest,
chatParamsFromRequestBody,
mergeAgentTools
};
//# sourceMappingURL=chat-params.js.map