Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 13 additions & 30 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 3 additions & 6 deletions packages/aisdk-executor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,11 @@
"@ai-sdk/anthropic": "catalog:",
"@ai-sdk/openai": "catalog:",
"ai": "catalog:",
"@projectors/core": "workspace:*"
"@projectors/core": "workspace:*",
"zod": "catalog:"
},
"devDependencies": {
"@types/bun": "latest",
"vitest": "^4.0.17",
"zod": "^4.0.0"
},
"peerDependencies": {
"zod": "catalog:"
"vitest": "^4.0.17"
}
}
18 changes: 18 additions & 0 deletions packages/aisdk-executor/src/__tests__/executor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,24 @@ describe("AI SDK prompt rendering", () => {
]);
});

it("preserves tool call arguments, results and errors across continuation history", () => {
expect(buildAiSdkMessages(inference({ history: [
{ ...textUserMessage("remember this") },
{ type: "action", kind: "request", action: "tool", name: "remember", callId: "save-1", input: { note: "already saved" } },
{ type: "action", kind: "result", action: "tool", name: "remember", callId: "save-1", success: true, value: "saved" },
{ type: "action", kind: "request", action: "tool", name: "check", callId: "check-1", input: {} },
{ type: "action", kind: "result", action: "tool", name: "check", callId: "check-1", success: false, error: "offline" },
{ type: "action", kind: "request", action: "tool", name: "unfinished", callId: "pending-1", input: { path: "work" } },
] }))).toEqual([
{ role: "user", content: "remember this" },
{ role: "assistant", content: [{ type: "tool-call", toolCallId: "save-1", toolName: "remember", input: { note: "already saved" } }] },
{ role: "tool", content: [{ type: "tool-result", toolCallId: "save-1", toolName: "remember", output: { type: "text", value: "saved" } }] },
{ role: "assistant", content: [{ type: "tool-call", toolCallId: "check-1", toolName: "check", input: {} }] },
{ role: "tool", content: [{ type: "tool-result", toolCallId: "check-1", toolName: "check", output: { type: "error-text", value: "offline" } }] },
{ role: "assistant", content: 'Tool call unfinished (pending-1) with {"path":"work"}; no result recorded.' },
]);
});

it("inserts dynamic context before the latest user request", () => {
expect(
buildAiSdkMessages(
Expand Down
71 changes: 50 additions & 21 deletions packages/aisdk-executor/src/executor.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
Output,
asSchema,
generateText,
jsonSchema,
streamText,
Expand All @@ -21,6 +20,8 @@ import {
executeActionInvocation,
hasActionOutputMessages,
isActorMessage,
normalizeSchema,
SchemaError,
} from "@projectors/core";
import type {
ActionContext,
Expand All @@ -38,6 +39,7 @@ import type {
FrameDraft,
FrameMessage,
ProjectorExecutor,
Schema,
} from "@projectors/core";
import { z } from "zod";
import type {
Expand Down Expand Up @@ -520,7 +522,7 @@ function buildAiSdkInput<TDataContent = never>(
frequencyPenalty: config.frequencyPenalty,
seed: config.seed,
experimental_output: request.output?.schema
? Output.object({ schema: request.output.schema })
? Output.object({ schema: aiSdkSchema(request.output.schema) })
: undefined,
providerOptions: config.providerOptions as never,
toolChoice: respondNow ? undefined : (config.toolChoice as never),
Expand All @@ -530,7 +532,9 @@ function buildAiSdkInput<TDataContent = never>(

function parseNodeConfig(config: unknown): AiSdkExecutorNodeConfig {
if (config === undefined) return {};
return nodeConfigSchema.parse(config);
const schema = normalizeSchema(nodeConfigSchema);
schema.assert(config);
return config as AiSdkExecutorNodeConfig;
}

function normalizeTurnPolicy<TDataContent>(
Expand Down Expand Up @@ -864,10 +868,17 @@ export function buildAiSdkMessages<TDataContent = never>(
message: ActorMessage<TDataContent>,
) => ModelMessage | undefined,
): ModelMessage[] {
// Preserve completed tool exchanges as calls/results, including their inputs.
// A horizon or interrupted action can leave only one half; keep that as text
// rather than sending an invalid, unmatched tool exchange to the provider.
const requests = new Set(inference.history.flatMap((message) =>
message.type === "action" && message.action === "tool" && message.kind === "request" ? [message.callId] : []));
const completedCalls = new Set(inference.history.flatMap((message) =>
message.type === "action" && message.action === "tool" && message.kind === "result" && requests.has(message.callId) ? [message.callId] : []));
const entries = inference.history
.map((source) => ({
source,
message: frameMessageToModelMessage(source, messageToModelMessage),
message: frameMessageToModelMessage(source, messageToModelMessage, completedCalls),
}))
.filter(
(
Expand Down Expand Up @@ -972,20 +983,28 @@ export function buildAiSdkTools<TDataContent = never>(
return tools;
}

const EMPTY_OBJECT_SCHEMA = { type: "object", properties: {}, additionalProperties: false };

function compactToolInputSchema(schema: AnyAction["inputSchema"]) {
return schema ? aiSdkSchema(schema) : jsonSchema(EMPTY_OBJECT_SCHEMA as never);
}

/**
* The provider already knows the function-tool JSON Schema dialect. Zod's
* standard conversion adds the same `$schema` URI to every tool, so strip only
* that redundant marker while preserving the AI SDK validator unchanged.
* An AI SDK schema over projector's normalized schema: its JSON Schema
* document minus the `$schema` dialect marker (the provider already knows the
* function-tool dialect), validated by Projector's canonical validator.
*/
function compactToolInputSchema(schema: AnyAction["inputSchema"]) {
const normalized = asSchema(schema ?? z.object({}));
return jsonSchema(
Promise.resolve(normalized.jsonSchema).then((value) => {
const { $schema: _dialect, ...compact } = value;
return compact;
}),
{ validate: normalized.validate },
);
function aiSdkSchema<T>(schema: Schema<T>) {
const normalized = normalizeSchema(schema);
const { $schema: _dialect, ...compact } = normalized.jsonSchema();
return jsonSchema<T>(compact as never, {
validate: (value) => {
const result = normalized.check(value);
return result.issues
? { success: false, error: new SchemaError(result.issues) }
: { success: true, value: value as T };
},
});
}

function executorOwnedAction<TDataContent>(
Expand Down Expand Up @@ -1291,17 +1310,27 @@ function frameMessageToModelMessage<TDataContent>(
messageToModelMessage?: (
message: ActorMessage<TDataContent>,
) => ModelMessage | undefined,
completedCalls: ReadonlySet<string> = new Set(),
): ModelMessage | undefined {
if (isActorMessage<TDataContent>(message)) {
return (
messageToModelMessage?.(message) ?? actorMessageToModelMessage(message)
);
}
if (
message.type === "action" &&
message.kind === "result" &&
message.action === "tool"
) {
if (message.type === "action" && message.action === "tool") {
if (message.kind === "request") {
return completedCalls.has(message.callId)
? { role: "assistant", content: [{ type: "tool-call", toolCallId: message.callId, toolName: message.name, input: message.input }] }
: { role: "assistant", content: `Tool call ${message.name} (${message.callId}) with ${stringifyValue(message.input)}; no result recorded.` };
}
if (completedCalls.has(message.callId)) {
return { role: "tool", content: [{
type: "tool-result", toolCallId: message.callId, toolName: message.name,
output: message.success
? { type: "text", value: stringifyValue(message.value) }
: { type: "error-text", value: message.error ?? "tool failed" },
}] };
}
return { role: "user", content: renderToolResult(message.name, message) };
}
return undefined;
Expand Down
3 changes: 0 additions & 3 deletions packages/livekit-cascade-executor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@
"devDependencies": {
"@types/bun": "latest",
"vitest": "^4.0.17",
"zod": "^4.0.0"
},
"peerDependencies": {
"zod": "catalog:"
}
}
21 changes: 16 additions & 5 deletions packages/livekit-cascade-executor/src/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {
hasActionOutputMessages,
ROOT_GENERATOR_ID,
isActorMessage,
normalizeSchema,
SchemaError,
textContent,
} from "@projectors/core";
import type {
Expand All @@ -21,7 +23,6 @@ import type {
ExecutorRealizePromptRequest,
RuntimeSyncContext,
} from "@projectors/core";
import { z } from "zod";
import type {
ExecutorRunRequest,
ExecutorRunResult,
Expand Down Expand Up @@ -212,6 +213,11 @@ export class LiveKitCascadeConnection<TDataContent = never> {
throw new Error(`No LiveKit tool named "${name}" is registered in the current projection`);
}

if (action.inputSchema) {
const checked = normalizeSchema(action.inputSchema).check(input);
if (checked.issues) throw new SchemaError(checked.issues);
}

const callId = crypto.randomUUID();
const actionRequest = {
...createToolActionRequest(name, input, callId),
Expand Down Expand Up @@ -726,15 +732,20 @@ export function buildLiveKitToolDefinitions(
type: "function",
name: action.name,
description: action.description ?? "",
parameters: action.inputSchema
? z.toJSONSchema(action.inputSchema)
: { type: "object", properties: {}, additionalProperties: false },
parameters: liveKitToolParameters(action),
});
}

return [...definitions.values()];
}

/** Raw JSON Schema for LiveKit; the executor validates input itself (executeTool). */
function liveKitToolParameters(action: AnyAction): Record<string, unknown> {
return action.inputSchema
? normalizeSchema(action.inputSchema).jsonSchema()
: { type: "object", properties: {}, additionalProperties: false };
}

export function buildLiveKitToolContext<TDataContent = never>(
inference: CompiledInference<TDataContent>,
connection: LiveKitCascadeConnection<TDataContent>,
Expand All @@ -744,7 +755,7 @@ export function buildLiveKitToolContext<TDataContent = never>(
for (const action of inference.tools) {
tools[action.name] = createLiveKitTool({
description: action.description ?? "",
parameters: action.inputSchema ?? z.object({}),
parameters: liveKitToolParameters(action) as never,
execute: (input, liveKitContext) => connection.executeTool(action.name, input, liveKitContext),
});
}
Expand Down
3 changes: 0 additions & 3 deletions packages/livekit-realtime-executor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@
"devDependencies": {
"@types/bun": "latest",
"vitest": "^4.0.17",
"zod": "^4.0.0"
},
"peerDependencies": {
"zod": "catalog:"
}
}
Loading
Loading