import "../context-BkKbAa1R.js";
import "../ai-types-DEtF_8Km.js";
import "../client-DjTPRM8-.js";
import "../client-QZa2Rq0l.js";
import "../do-oauth-client-provider-B1fVIshX.js";
import { s as getAgentByName } from "../src-BZDh910Z.js";
import { generateObject, tool } from "ai";
import { openai } from "@ai-sdk/openai";
import { z } from "zod/v3";
import { compile } from "json-schema-to-typescript";
import { createTypeAlias, printNode, zodToTs } from "zod-to-ts";
import { WorkerEntrypoint, env } from "cloudflare:workers";
//#region src/codemode/ai.ts
function toCamelCase(str) {
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/^[a-z]/, (letter) => letter.toUpperCase());
}
var CodeModeProxy = class extends WorkerEntrypoint {
async callFunction(options) {
return (await getAgentByName(env[this.ctx.props.binding], this.ctx.props.name))[this.ctx.props.callback](options.functionName, options.args);
}
};
async function experimental_codemode(options) {
const generatedTypes = await generateTypes(options.tools);
return {
prompt: `You are a helpful assistant. You have access to the "codemode" tool that can do different things:
${getToolDescriptions(options.tools)}
If the user asks to do anything that be achieveable by the codemode tool, then simply pass over control to it by giving it a simple function description. Don't be too verbose.
`,
tools: { codemode: tool({
description: "codemode: a tool that can generate code to achieve a goal",
inputSchema: z.object({ functionDescription: z.string() }),
outputSchema: z.object({
code: z.string(),
result: z.any()
}),
execute: async ({ functionDescription }) => {
try {
const response = await generateObject({
model: openai("gpt-4.1"),
schema: z.object({ code: z.string() }),
prompt: `You are a code generating machine.
In addition to regular javascript, you can also use the following functions:
${generatedTypes}
Respond only with the code, nothing else. Output javascript code.
Generate an async function that achieves the goal. This async function doesn't accept any arguments.
Here is user input: ${functionDescription}`
});
const result = await createEvaluator(response.object.code, {
proxy: options.proxy,
loader: options.loader
})();
return {
code: response.object.code,
result
};
} catch (error) {
console.error("error", error);
throw error;
}
}
}) }
};
}
function createEvaluator(code, options) {
return async () => {
return await options.loader.get(`code-${Math.random()}`, () => {
return {
compatibilityDate: "2025-06-01",
compatibilityFlags: ["nodejs_compat"],
mainModule: "foo.js",
modules: { "foo.js": `
import { env, WorkerEntrypoint } from "cloudflare:workers";
export default class CodeModeWorker extends WorkerEntrypoint {
async evaluate() {
try {
const { CodeModeProxy } = env;
const codemode = new Proxy(
{},
{
get: (target, prop) => {
return (args) => {
return CodeModeProxy.callFunction({
functionName: prop,
args: args,
});
};
}
}
);
return await ${code}();
} catch (err) {
return {
err: err.message,
stack: err.stack
};
}
}
}
` },
env: { CodeModeProxy: options.proxy },
globalOutbound: null
};
}).getEntrypoint().evaluate();
};
}
async function generateTypes(tools) {
let availableTools = "";
let availableTypes = "";
for (const [toolName, tool$1] of Object.entries(tools)) {
const inputJsonType = tool$1.inputSchema.jsonSchema ? await compile(tool$1.inputSchema.jsonSchema, `${toCamelCase(toolName)}Input`, {
format: false,
bannerComment: " "
}) : printNode(createTypeAlias(zodToTs(tool$1.inputSchema, `${toCamelCase(toolName)}Input`).node, `${toCamelCase(toolName)}Input`));
const outputJsonType = tool$1.outputSchema?.jsonSchema ? await compile(tool$1.outputSchema?.jsonSchema, `${toCamelCase(toolName)}Output`, {
format: false,
bannerComment: " "
}) : tool$1.outputSchema ? printNode(createTypeAlias(zodToTs(tool$1.outputSchema, `${toCamelCase(toolName)}Output`).node, `${toCamelCase(toolName)}Output`)) : `interface ${toCamelCase(toolName)}Output { [key: string]: any }`;
const InputType = inputJsonType.trim().replace("export interface", "interface");
const OutputType = outputJsonType.trim().replace("export interface", "interface");
availableTypes += `\n${InputType}`;
availableTypes += `\n${OutputType}`;
availableTools += `\n\t/*\n\t${tool$1.description?.trim()}\n\t*/`;
availableTools += `\n\t${toolName}: (input: ${toCamelCase(toolName)}Input) => Promise<${toCamelCase(toolName)}Output>;`;
availableTools += "\n";
}
availableTools = `\ndeclare const codemode: {${availableTools}}`;
return `
${availableTypes}
${availableTools}
`;
}
function getToolDescriptions(tools) {
return Object.entries(tools).map(([_toolName, tool$1]) => {
return `\n- ${tool$1.description?.trim()}`;
}).join("");
}
//#endregion
export { CodeModeProxy, experimental_codemode };
//# sourceMappingURL=ai.js.map