@tanstack/ai-code-mode
Version:
Code Mode for TanStack AI - LLM-driven code execution in secure sandboxes
79 lines (78 loc) • 2.46 kB
JavaScript
import { convertSchemaToJsonSchema } from "@tanstack/ai";
function toolsToBindings(tools, prefix = "") {
const bindings = {};
for (const tool of tools) {
const bindingName = `${prefix}${tool.name}`;
bindings[bindingName] = toolToBinding(tool, prefix);
}
return bindings;
}
function toolToBinding(tool, prefix = "") {
const inputSchema = convertSchemaToJsonSchema(tool.inputSchema) || {
type: "object",
properties: {}
};
const outputSchema = tool.outputSchema ? convertSchemaToJsonSchema(tool.outputSchema) : void 0;
let execute;
if ("execute" in tool && typeof tool.execute === "function") {
const toolExecute = tool.execute;
execute = (args, context) => {
return Promise.resolve(toolExecute(args, context));
};
} else if ("__toolSide" in tool && tool.__toolSide === "definition") {
throw new Error(
`Tool "${tool.name}" is a ToolDefinition without an execute function. Call .server(fn) to provide an implementation before using with Code Mode.`
);
} else {
throw new Error(
`Tool "${tool.name}" does not have an execute function. Code Mode requires tools with implementations.`
);
}
return {
name: `${prefix}${tool.name}`,
description: tool.description,
inputSchema,
outputSchema,
execute
};
}
function createEventAwareBindings(bindings, emitCustomEvent) {
const wrapped = {};
for (const [name, binding] of Object.entries(bindings)) {
wrapped[name] = {
...binding,
execute: async (args) => {
emitCustomEvent("code_mode:external_call", {
function: name,
args,
timestamp: Date.now()
});
const startTime = Date.now();
try {
const toolContext = { emitCustomEvent };
const result = await binding.execute(args, toolContext);
emitCustomEvent("code_mode:external_result", {
function: name,
result,
duration: Date.now() - startTime
});
return result;
} catch (error) {
emitCustomEvent("code_mode:external_error", {
function: name,
error: error instanceof Error ? error.message : String(error),
duration: Date.now() - startTime
});
throw error;
}
}
};
}
return wrapped;
}
export {
createEventAwareBindings,
toolToBinding,
toolsToBindings
};
//# sourceMappingURL=tool-to-binding.js.map