@cloudflare/codemode 0.5.4 → 0.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -14
- package/dist/ai.d.ts +3 -3
- package/dist/ai.js +1 -1
- package/dist/ai.js.map +1 -1
- package/dist/browser.d.ts +2 -2
- package/dist/{executor-DLwvEPC7.d.ts → executor-xSJFaECq.d.ts} +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +65 -2
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/{resolve-BFB4vzhC.d.ts → resolve-ClRJA8iy.d.ts} +2 -2
- package/dist/{shared-B1Rs0ONk.d.ts → shared-D5qepsss.d.ts} +2 -2
- package/dist/tanstack-ai.d.ts +3 -3
- package/docs/runtime.md +4 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -135,28 +135,34 @@ Tool providers let you compose capabilities from different packages into a singl
|
|
|
135
135
|
```ts
|
|
136
136
|
import { createCodeTool } from "@cloudflare/codemode/ai";
|
|
137
137
|
import { DynamicWorkerExecutor } from "@cloudflare/codemode";
|
|
138
|
-
import {
|
|
138
|
+
import { createAITools } from "@cloudflare/computer/tools/ai-sdk";
|
|
139
139
|
|
|
140
140
|
const executor = new DynamicWorkerExecutor({ loader: env.LOADER });
|
|
141
141
|
|
|
142
142
|
const codemode = createCodeTool({
|
|
143
143
|
tools: [
|
|
144
144
|
{ tools: myTools }, // codemode.myTool({ query: "test" })
|
|
145
|
-
|
|
145
|
+
{ name: "workspace", tools: createAITools({ workspace }) } // workspace.read({ path })
|
|
146
146
|
],
|
|
147
147
|
executor
|
|
148
148
|
});
|
|
149
149
|
```
|
|
150
150
|
|
|
151
|
-
The sandbox has both `codemode.*` and `
|
|
151
|
+
The sandbox has both `codemode.*` and `workspace.*`:
|
|
152
152
|
|
|
153
153
|
```js
|
|
154
154
|
async () => {
|
|
155
|
-
const
|
|
155
|
+
const { entries } = await workspace.find({
|
|
156
|
+
path: "/workspace/src",
|
|
157
|
+
pattern: "**/*.ts"
|
|
158
|
+
});
|
|
156
159
|
const results = await Promise.all(
|
|
157
|
-
|
|
160
|
+
entries.map((entry) => codemode.analyzeFile({ path: entry.path }))
|
|
158
161
|
);
|
|
159
|
-
await
|
|
162
|
+
await workspace.write({
|
|
163
|
+
path: "/workspace/report.json",
|
|
164
|
+
content: JSON.stringify(results)
|
|
165
|
+
});
|
|
160
166
|
return results.length;
|
|
161
167
|
};
|
|
162
168
|
```
|
|
@@ -165,7 +171,7 @@ async () => {
|
|
|
165
171
|
|
|
166
172
|
Any package can provide tools to the sandbox. A `ToolProvider` describes:
|
|
167
173
|
|
|
168
|
-
- an optional **name** (the namespace in the sandbox, e.g. `"
|
|
174
|
+
- an optional **name** (the namespace in the sandbox, e.g. `"workspace"`, `"db"` — defaults to `"codemode"`)
|
|
169
175
|
- **tools** — AI SDK tools, tool descriptors, or simple `{ execute }` records
|
|
170
176
|
- optional **types** for LLM context (auto-generated from tools if omitted)
|
|
171
177
|
- optional **positionalArgs** flag (e.g. `state.readFile("/path")` vs `codemode.search({ query })`)
|
|
@@ -466,7 +472,7 @@ Connector calls go via **Workers RPC** directly to the host-side connector bindi
|
|
|
466
472
|
```
|
|
467
473
|
|
|
468
474
|
1. `createCodeTool` generates TypeScript type definitions from your tool providers and builds a description the LLM can read
|
|
469
|
-
2. The LLM writes an async arrow function that calls `codemode.toolName(args)` and any provider namespaces (`
|
|
475
|
+
2. The LLM writes an async arrow function that calls `codemode.toolName(args)` and any provider namespaces (`workspace.*`, `db.*`, etc.)
|
|
470
476
|
3. Code is normalized via AST parsing (acorn) and sent to the executor
|
|
471
477
|
4. `DynamicWorkerExecutor` spins up an isolated Worker via `WorkerLoader`, with one `ToolDispatcher` per namespace
|
|
472
478
|
5. Inside the sandbox, a `Proxy` per namespace intercepts calls and routes them back via Workers RPC
|
|
@@ -598,23 +604,29 @@ export class MyAgent extends Agent<Env, State> {
|
|
|
598
604
|
}
|
|
599
605
|
```
|
|
600
606
|
|
|
601
|
-
### With filesystem access (via `@cloudflare/
|
|
607
|
+
### With filesystem access (via `@cloudflare/computer`)
|
|
602
608
|
|
|
603
|
-
Combine `codemode.*` tools with `
|
|
609
|
+
Combine `codemode.*` tools with the `@cloudflare/computer` workspace tools:
|
|
604
610
|
|
|
605
611
|
```ts
|
|
606
612
|
import { createCodeTool } from "@cloudflare/codemode/ai";
|
|
607
613
|
import { DynamicWorkerExecutor } from "@cloudflare/codemode";
|
|
608
|
-
import { Workspace } from "@cloudflare/
|
|
609
|
-
import {
|
|
614
|
+
import { Workspace } from "@cloudflare/computer";
|
|
615
|
+
import { createAITools } from "@cloudflare/computer/tools/ai-sdk";
|
|
610
616
|
|
|
611
617
|
export class MyAgent extends Agent<Env> {
|
|
612
|
-
workspace = new Workspace({
|
|
618
|
+
workspace = new Workspace({ storage: this.ctx.storage });
|
|
613
619
|
|
|
614
620
|
getCodemodeTool() {
|
|
615
621
|
const executor = new DynamicWorkerExecutor({ loader: this.env.LOADER });
|
|
616
622
|
return createCodeTool({
|
|
617
|
-
tools: [
|
|
623
|
+
tools: [
|
|
624
|
+
{ tools: myDomainTools },
|
|
625
|
+
{
|
|
626
|
+
name: "workspace",
|
|
627
|
+
tools: createAITools({ workspace: this.workspace })
|
|
628
|
+
}
|
|
629
|
+
],
|
|
618
630
|
executor
|
|
619
631
|
});
|
|
620
632
|
}
|
package/dist/ai.d.ts
CHANGED
|
@@ -4,12 +4,12 @@ import {
|
|
|
4
4
|
i as ToolProvider,
|
|
5
5
|
p as generateTypes,
|
|
6
6
|
u as ResolvedProvider
|
|
7
|
-
} from "./executor-
|
|
7
|
+
} from "./executor-xSJFaECq.js";
|
|
8
8
|
import {
|
|
9
9
|
n as CodeOutput,
|
|
10
10
|
r as CreateCodeToolOptions,
|
|
11
11
|
t as CodeInput
|
|
12
|
-
} from "./shared-
|
|
12
|
+
} from "./shared-D5qepsss.js";
|
|
13
13
|
import {
|
|
14
14
|
r as ConnectorTools,
|
|
15
15
|
t as CodemodeConnector
|
|
@@ -23,7 +23,7 @@ import { Tool, ToolSet } from "ai";
|
|
|
23
23
|
* @example
|
|
24
24
|
* ```ts
|
|
25
25
|
* createCodeTool({
|
|
26
|
-
* tools: [
|
|
26
|
+
* tools: [aiTools(myTools), { name: "db", tools: dbTools }],
|
|
27
27
|
* executor,
|
|
28
28
|
* });
|
|
29
29
|
* ```
|
package/dist/ai.js
CHANGED
package/dist/ai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.js","names":["#options","#warnedSkipped","#executableTools"],"sources":["../src/tool-types.ts","../src/tool.ts","../src/connectors/toolset.ts"],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\nimport {\n jsonSchemaToTypeString,\n type ConversionContext\n} from \"./json-schema-types\";\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value conforms to the Standard Schema protocol (~standard).\n * This catches Zod v3 schemas (which expose ~standard but not _zod).\n */\nfunction isStandardSchema(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"~standard\" in value &&\n (value as Record<string, unknown>)[\"~standard\"] !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n let s = fieldSchema as { description?: string; unwrap?: () => unknown };\n while (!s.description && typeof s.unwrap === \"function\") {\n s = s.unwrap() as typeof s;\n }\n if (s.description) {\n descriptions[fieldName] = s.description;\n }\n }\n return descriptions;\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\nfunction jsonSchemaToTypeDecl(jsonSchema: JSONSchema7, typeName: string) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, \"\", ctx)}`;\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\n if (isZodSchema(schema) || isStandardSchema(schema)) {\n const wrapped = asSchema(schema as ZodType);\n const jsonSchema = wrapped.jsonSchema as JSONSchema7;\n if (jsonSchema) return jsonSchemaToTypeDecl(jsonSchema, typeName);\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) return jsonSchemaToTypeDecl(jsonSchema, typeName);\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n return `type ${typeName} = unknown`;\n }\n}\n\ninterface StandardJsonSchemaConverter {\n output?: (options: { target: \"draft-07\" }) => unknown;\n}\n\n/**\n * JSON Schema for the value a schema *produces*, from its Standard JSON\n * Schema converter (Zod 4, Valibot, ArkType, ...). AI SDK's `asSchema`\n * always converts the input side, which is wrong for a tool's output:\n * `.default()` fields come out optional and `.pipe()` keeps the pre-pipe\n * type.\n *\n * Returns `undefined` when the schema has no such converter (Zod 3,\n * `jsonSchema()` wrappers, whose input and output are the same). Throws when\n * the output can't be represented in JSON Schema (e.g. `.transform()`);\n * callers treat that as `unknown` rather than falling back to the input type.\n */\nexport function standardOutputJsonSchema(\n schema: unknown\n): JSONSchema7 | undefined {\n if (!isStandardSchema(schema)) return undefined;\n const converter = (\n schema as { \"~standard\": { jsonSchema?: StandardJsonSchemaConverter } }\n )[\"~standard\"].jsonSchema;\n if (typeof converter?.output !== \"function\") return undefined;\n return converter.output({ target: \"draft-07\" }) as JSONSchema7;\n}\n\n/** Like `safeSchemaToTs`, but types the value the schema produces. */\nfunction safeOutputSchemaToTs(schema: unknown, typeName: string): string {\n let jsonSchema: JSONSchema7 | undefined;\n try {\n jsonSchema = standardOutputJsonSchema(schema);\n } catch {\n return `type ${typeName} = unknown`;\n }\n return jsonSchema\n ? jsonSchemaToTypeDecl(jsonSchema, typeName)\n : safeSchemaToTs(schema, typeName);\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n *\n * Requires the `ai` peer dependency. For a version that works with plain JSON Schema\n * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.\n */\nexport function generateTypes(\n tools: ToolDescriptors | ToolSet,\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);\n\n const outputType = outputSchema\n ? safeOutputSchemaToTs(outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n return inputSchema ? extractParamDescriptions(inputSchema) : [];\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, type ToolDescriptors } from \"./tool-types\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\nimport { runCode } from \"./run-code\";\nimport { filterTools } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeInput,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\n/**\n * Extract execute functions from tools, keyed by name.\n * Wraps each with schema validation via AI SDK's `asSchema` when available.\n */\nfunction extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[name] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Wrap raw AI SDK tools into a ToolProvider under the default \"codemode\" namespace.\n *\n * @example\n * ```ts\n * createCodeTool({\n * tools: [stateTools(workspace), aiTools(myTools)],\n * executor,\n * });\n * ```\n */\nexport function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider {\n return { tools };\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n return resolved;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const providers = normalizeProviders(options.tools);\n\n // Build type block and resolved providers for each provider.\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const types =\n provider.types ?? generateTypes(filtered as ToolDescriptors, name);\n typeBlocks.push(types);\n resolvedProviders.push({ name, fns: extractFns(filtered) });\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n });\n}\n","/**\n * ToolSetConnector — adapt an AI SDK `ToolSet` to the connector model.\n *\n * Each tool in the set becomes one connector tool under a single namespace\n * (default `\"tools\"`). Tools with `needsApproval` map to `requiresApproval`:\n * calling one pauses the run durably until the host approves\n * (`runtime.approve()`), then the run resumes where it stopped — the\n * runtime's pause/approve/resume flow, not the AI SDK's per-call approval.\n * A function-valued `needsApproval` cannot be evaluated against sandbox\n * arguments ahead of time, so it conservatively always requires approval.\n *\n * Lives in the `/ai` entry because schema handling (`asSchema`) needs the\n * `ai` peer dependency.\n */\nimport { asSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { generateTypes, standardOutputJsonSchema } from \"../tool-types\";\nimport { sanitizeToolName } from \"../utils\";\nimport { CodemodeConnector, type ConnectorTools } from \"./base\";\n\nexport interface ToolSetConnectorOptions {\n /**\n * The namespace the sandbox sees, e.g. `\"tools\"` → `tools.getWeather(...)`.\n * Defaults to `\"tools\"`. (`\"codemode\"` is reserved for the platform SDK.)\n */\n name?: string;\n /** Extra model guidance, surfaced with the connector's type block. */\n instructions?: string;\n /** The AI SDK tools to expose. */\n tools: ToolSet;\n}\n\nexport class ToolSetConnector extends CodemodeConnector {\n #options: ToolSetConnectorOptions;\n #warnedSkipped = false;\n\n constructor(\n ctx: DurableObjectState | ExecutionContext,\n options: ToolSetConnectorOptions\n ) {\n super(ctx, {});\n this.#options = options;\n }\n\n /**\n * Only tools with an `execute` function can run inside the sandbox.\n * Execute-less tools (client-side / provider-executed) are excluded from\n * both the runtime bindings and the generated types — advertising a method\n * the sandbox can't call would send the model down a dead end.\n */\n #executableTools(): ToolSet {\n const executable: ToolSet = {};\n const skipped: string[] = [];\n for (const [toolName, t] of Object.entries(this.#options.tools)) {\n if (\"execute\" in t && typeof t.execute === \"function\") {\n executable[toolName] = t;\n } else {\n skipped.push(toolName);\n }\n }\n if (skipped.length > 0 && !this.#warnedSkipped) {\n this.#warnedSkipped = true;\n console.warn(\n `[codemode] ToolSetConnector \"${this.name()}\" skipped tools without ` +\n `an execute function (client-side or provider-executed): ` +\n `${skipped.join(\", \")}. They are not callable from sandboxed code.`\n );\n }\n return executable;\n }\n\n override name(): string {\n return this.#options.name ?? \"tools\";\n }\n\n protected override instructions(): string | undefined {\n return this.#options.instructions;\n }\n\n protected override async tools(): Promise<ConnectorTools> {\n const out: ConnectorTools = {};\n const sources = new Map<string, string>();\n for (const [toolName, t] of Object.entries(this.#executableTools())) {\n const execute = t.execute as (args: unknown) => Promise<unknown>;\n\n const name = sanitizeToolName(toolName);\n const existing = sources.get(name);\n if (existing !== undefined) {\n throw new Error(\n `Tools \"${existing}\" and \"${toolName}\" on ${this.name()} both ` +\n `map to \"${name}\" — rename one of them.`\n );\n }\n sources.set(name, toolName);\n\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : (t as Record<string, unknown>).parameters;\n const schema =\n rawSchema != null\n ? asSchema(rawSchema as Parameters<typeof asSchema>[0])\n : undefined;\n // `jsonSchema` may be a promise (`jsonSchema(promise)` or a lazy\n // loader), so await it rather than passing a Promise through as a schema.\n const inputSchema = schema ? await schema.jsonSchema : undefined;\n const outputSchema = await outputJsonSchema(\n (t as { outputSchema?: unknown }).outputSchema\n );\n\n // boolean `false` means no approval; `true` or a function (which can't\n // be pre-evaluated against sandbox args) gates the call behind the\n // runtime's durable pause/approve/resume flow.\n const needsApproval = (t as { needsApproval?: unknown }).needsApproval;\n const requiresApproval =\n needsApproval !== undefined && needsApproval !== false;\n\n out[name] = {\n description:\n typeof t.description === \"function\" ? undefined : t.description,\n inputSchema: inputSchema as JSONSchema7 | undefined,\n ...(outputSchema ? { outputSchema } : {}),\n ...(requiresApproval ? { requiresApproval: true } : {}),\n execute: schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : (args: unknown) => execute(args)\n };\n }\n return out;\n }\n\n /**\n * Generate the sandbox type block from the original AI SDK schemas (Zod or\n * `jsonSchema()` wrappers) rather than the converted JSON Schema, preserving\n * field descriptions as `@param` lines. Restricted to the same executable\n * subset that `tools()` exposes, so the types never advertise a method the\n * sandbox can't call.\n */\n override async getTypeScriptTypes(): Promise<string> {\n return generateTypes(this.#executableTools(), this.name());\n }\n}\n\n/**\n * Convert a tool's output schema to JSON Schema for its descriptor, using\n * the output side of the schema where the library exposes it (see\n * `standardOutputJsonSchema`). The output type is advisory, so a schema that\n * cannot be converted (it throws or its promise rejects) is left out and\n * shows as `unknown`, matching `generateTypes`, instead of failing the whole\n * toolset.\n */\nasync function outputJsonSchema(\n raw: unknown\n): Promise<JSONSchema7 | undefined> {\n if (raw == null) return undefined;\n try {\n return (\n standardOutputJsonSchema(raw) ??\n ((await asSchema(raw as Parameters<typeof asSchema>[0])\n .jsonSchema) as JSONSchema7)\n );\n } catch {\n return undefined;\n }\n}\n\n/** Convenience constructor mirroring `stateConnector` / `new BrowserConnector`. */\nexport function toolSetConnector(\n ctx: DurableObjectState | ExecutionContext,\n options: ToolSetConnectorOptions\n): ToolSetConnector {\n return new ToolSetConnector(ctx, options);\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,YAAY,OAAkC;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;AAE3C;;;;;AAMA,SAAS,iBAAiB,OAAyB;CACjD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;AAExD;;;;;AAMA,SAAS,oBACP,OACsC;CACtC,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CAExD,IAAI,gBAAgB,OAClB,OAAO;CAGT,MAAM,UAAU,OAAO,sBAAsB,KAAK;CAClD,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,MAAkC;EACpD,IAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,UAC9D,OAAO;CAEX;CAEA,OAAO;AACT;;;;AAKA,SAAS,kBAAkB,SAAsC;CAC/D,IAAI,YAAY,QAAQ,OAAO,YAAY,UAAU,OAAO;CAE5D,IAAI,gBAAgB,SAClB,OAAQ,QAAwC;CAGlD,M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vC,GAAI,mBAAmB,EAAE,kBAAkB,KAAK,IAAI,CAAC;IACrD,SAAS,QAAQ,WACb,OAAO,SAAkB;KACvB,MAAM,SAAS,MAAM,OAAO,SAAU,IAAI;KAC1C,IAAI,CAAC,OAAO,SAAS,MAAM,OAAO;KAClC,OAAO,QAAQ,OAAO,KAAK;IAC7B,KACC,SAAkB,QAAQ,IAAI;GACrC;EACF;EACA,OAAO;CACT;;;;;;;;CASA,MAAe,qBAAsC;EACnD,OAAO,cAAc,KAAKA,iBAAiB,GAAG,KAAK,KAAK,CAAC;CAC3D;AACF;;;;;;;;;AAUA,eAAe,iBACb,KACkC;CAClC,IAAI,OAAO,MAAM,OAAO,KAAA;CACxB,IAAI;EACF,OACE,yBAAyB,GAAG,KAC1B,MAAM,SAAS,GAAqC,CAAC,CACpD;CAEP,QAAQ;EACN;CACF;AACF;;AAGA,SAAgB,iBACd,KACA,SACkB;CAClB,OAAO,IAAI,iBAAiB,KAAK,OAAO;AAC1C"}
|
|
1
|
+
{"version":3,"file":"ai.js","names":["#options","#warnedSkipped","#executableTools"],"sources":["../src/tool-types.ts","../src/tool.ts","../src/connectors/toolset.ts"],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\nimport {\n jsonSchemaToTypeString,\n type ConversionContext\n} from \"./json-schema-types\";\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value conforms to the Standard Schema protocol (~standard).\n * This catches Zod v3 schemas (which expose ~standard but not _zod).\n */\nfunction isStandardSchema(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"~standard\" in value &&\n (value as Record<string, unknown>)[\"~standard\"] !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n let s = fieldSchema as { description?: string; unwrap?: () => unknown };\n while (!s.description && typeof s.unwrap === \"function\") {\n s = s.unwrap() as typeof s;\n }\n if (s.description) {\n descriptions[fieldName] = s.description;\n }\n }\n return descriptions;\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\nfunction jsonSchemaToTypeDecl(jsonSchema: JSONSchema7, typeName: string) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n return `type ${typeName} = ${jsonSchemaToTypeString(jsonSchema, \"\", ctx)}`;\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\n if (isZodSchema(schema) || isStandardSchema(schema)) {\n const wrapped = asSchema(schema as ZodType);\n const jsonSchema = wrapped.jsonSchema as JSONSchema7;\n if (jsonSchema) return jsonSchemaToTypeDecl(jsonSchema, typeName);\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) return jsonSchemaToTypeDecl(jsonSchema, typeName);\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n return `type ${typeName} = unknown`;\n }\n}\n\ninterface StandardJsonSchemaConverter {\n output?: (options: { target: \"draft-07\" }) => unknown;\n}\n\n/**\n * JSON Schema for the value a schema *produces*, from its Standard JSON\n * Schema converter (Zod 4, Valibot, ArkType, ...). AI SDK's `asSchema`\n * always converts the input side, which is wrong for a tool's output:\n * `.default()` fields come out optional and `.pipe()` keeps the pre-pipe\n * type.\n *\n * Returns `undefined` when the schema has no such converter (Zod 3,\n * `jsonSchema()` wrappers, whose input and output are the same). Throws when\n * the output can't be represented in JSON Schema (e.g. `.transform()`);\n * callers treat that as `unknown` rather than falling back to the input type.\n */\nexport function standardOutputJsonSchema(\n schema: unknown\n): JSONSchema7 | undefined {\n if (!isStandardSchema(schema)) return undefined;\n const converter = (\n schema as { \"~standard\": { jsonSchema?: StandardJsonSchemaConverter } }\n )[\"~standard\"].jsonSchema;\n if (typeof converter?.output !== \"function\") return undefined;\n return converter.output({ target: \"draft-07\" }) as JSONSchema7;\n}\n\n/** Like `safeSchemaToTs`, but types the value the schema produces. */\nfunction safeOutputSchemaToTs(schema: unknown, typeName: string): string {\n let jsonSchema: JSONSchema7 | undefined;\n try {\n jsonSchema = standardOutputJsonSchema(schema);\n } catch {\n return `type ${typeName} = unknown`;\n }\n return jsonSchema\n ? jsonSchemaToTypeDecl(jsonSchema, typeName)\n : safeSchemaToTs(schema, typeName);\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n *\n * Requires the `ai` peer dependency. For a version that works with plain JSON Schema\n * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.\n */\nexport function generateTypes(\n tools: ToolDescriptors | ToolSet,\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);\n\n const outputType = outputSchema\n ? safeOutputSchemaToTs(outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n return inputSchema ? extractParamDescriptions(inputSchema) : [];\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, type ToolDescriptors } from \"./tool-types\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\nimport { runCode } from \"./run-code\";\nimport { filterTools } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeInput,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\n/**\n * Extract execute functions from tools, keyed by name.\n * Wraps each with schema validation via AI SDK's `asSchema` when available.\n */\nfunction extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[name] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Wrap raw AI SDK tools into a ToolProvider under the default \"codemode\" namespace.\n *\n * @example\n * ```ts\n * createCodeTool({\n * tools: [aiTools(myTools), { name: \"db\", tools: dbTools }],\n * executor,\n * });\n * ```\n */\nexport function aiTools(tools: ToolDescriptors | ToolSet): ToolProvider {\n return { tools };\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval` and validates inputs via AI SDK's `asSchema`.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n return resolved;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const providers = normalizeProviders(options.tools);\n\n // Build type block and resolved providers for each provider.\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const types =\n provider.types ?? generateTypes(filtered as ToolDescriptors, name);\n typeBlocks.push(types);\n resolvedProviders.push({ name, fns: extractFns(filtered) });\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n });\n}\n","/**\n * ToolSetConnector — adapt an AI SDK `ToolSet` to the connector model.\n *\n * Each tool in the set becomes one connector tool under a single namespace\n * (default `\"tools\"`). Tools with `needsApproval` map to `requiresApproval`:\n * calling one pauses the run durably until the host approves\n * (`runtime.approve()`), then the run resumes where it stopped — the\n * runtime's pause/approve/resume flow, not the AI SDK's per-call approval.\n * A function-valued `needsApproval` cannot be evaluated against sandbox\n * arguments ahead of time, so it conservatively always requires approval.\n *\n * Lives in the `/ai` entry because schema handling (`asSchema`) needs the\n * `ai` peer dependency.\n */\nimport { asSchema } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { generateTypes, standardOutputJsonSchema } from \"../tool-types\";\nimport { sanitizeToolName } from \"../utils\";\nimport { CodemodeConnector, type ConnectorTools } from \"./base\";\n\nexport interface ToolSetConnectorOptions {\n /**\n * The namespace the sandbox sees, e.g. `\"tools\"` → `tools.getWeather(...)`.\n * Defaults to `\"tools\"`. (`\"codemode\"` is reserved for the platform SDK.)\n */\n name?: string;\n /** Extra model guidance, surfaced with the connector's type block. */\n instructions?: string;\n /** The AI SDK tools to expose. */\n tools: ToolSet;\n}\n\nexport class ToolSetConnector extends CodemodeConnector {\n #options: ToolSetConnectorOptions;\n #warnedSkipped = false;\n\n constructor(\n ctx: DurableObjectState | ExecutionContext,\n options: ToolSetConnectorOptions\n ) {\n super(ctx, {});\n this.#options = options;\n }\n\n /**\n * Only tools with an `execute` function can run inside the sandbox.\n * Execute-less tools (client-side / provider-executed) are excluded from\n * both the runtime bindings and the generated types — advertising a method\n * the sandbox can't call would send the model down a dead end.\n */\n #executableTools(): ToolSet {\n const executable: ToolSet = {};\n const skipped: string[] = [];\n for (const [toolName, t] of Object.entries(this.#options.tools)) {\n if (\"execute\" in t && typeof t.execute === \"function\") {\n executable[toolName] = t;\n } else {\n skipped.push(toolName);\n }\n }\n if (skipped.length > 0 && !this.#warnedSkipped) {\n this.#warnedSkipped = true;\n console.warn(\n `[codemode] ToolSetConnector \"${this.name()}\" skipped tools without ` +\n `an execute function (client-side or provider-executed): ` +\n `${skipped.join(\", \")}. They are not callable from sandboxed code.`\n );\n }\n return executable;\n }\n\n override name(): string {\n return this.#options.name ?? \"tools\";\n }\n\n protected override instructions(): string | undefined {\n return this.#options.instructions;\n }\n\n protected override async tools(): Promise<ConnectorTools> {\n const out: ConnectorTools = {};\n const sources = new Map<string, string>();\n for (const [toolName, t] of Object.entries(this.#executableTools())) {\n const execute = t.execute as (args: unknown) => Promise<unknown>;\n\n const name = sanitizeToolName(toolName);\n const existing = sources.get(name);\n if (existing !== undefined) {\n throw new Error(\n `Tools \"${existing}\" and \"${toolName}\" on ${this.name()} both ` +\n `map to \"${name}\" — rename one of them.`\n );\n }\n sources.set(name, toolName);\n\n const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : (t as Record<string, unknown>).parameters;\n const schema =\n rawSchema != null\n ? asSchema(rawSchema as Parameters<typeof asSchema>[0])\n : undefined;\n // `jsonSchema` may be a promise (`jsonSchema(promise)` or a lazy\n // loader), so await it rather than passing a Promise through as a schema.\n const inputSchema = schema ? await schema.jsonSchema : undefined;\n const outputSchema = await outputJsonSchema(\n (t as { outputSchema?: unknown }).outputSchema\n );\n\n // boolean `false` means no approval; `true` or a function (which can't\n // be pre-evaluated against sandbox args) gates the call behind the\n // runtime's durable pause/approve/resume flow.\n const needsApproval = (t as { needsApproval?: unknown }).needsApproval;\n const requiresApproval =\n needsApproval !== undefined && needsApproval !== false;\n\n out[name] = {\n description:\n typeof t.description === \"function\" ? undefined : t.description,\n inputSchema: inputSchema as JSONSchema7 | undefined,\n ...(outputSchema ? { outputSchema } : {}),\n ...(requiresApproval ? { requiresApproval: true } : {}),\n execute: schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : (args: unknown) => execute(args)\n };\n }\n return out;\n }\n\n /**\n * Generate the sandbox type block from the original AI SDK schemas (Zod or\n * `jsonSchema()` wrappers) rather than the converted JSON Schema, preserving\n * field descriptions as `@param` lines. Restricted to the same executable\n * subset that `tools()` exposes, so the types never advertise a method the\n * sandbox can't call.\n */\n override async getTypeScriptTypes(): Promise<string> {\n return generateTypes(this.#executableTools(), this.name());\n }\n}\n\n/**\n * Convert a tool's output schema to JSON Schema for its descriptor, using\n * the output side of the schema where the library exposes it (see\n * `standardOutputJsonSchema`). The output type is advisory, so a schema that\n * cannot be converted (it throws or its promise rejects) is left out and\n * shows as `unknown`, matching `generateTypes`, instead of failing the whole\n * toolset.\n */\nasync function outputJsonSchema(\n raw: unknown\n): Promise<JSONSchema7 | undefined> {\n if (raw == null) return undefined;\n try {\n return (\n standardOutputJsonSchema(raw) ??\n ((await asSchema(raw as Parameters<typeof asSchema>[0])\n .jsonSchema) as JSONSchema7)\n );\n } catch {\n return undefined;\n }\n}\n\n/** Convenience constructor mirroring `stateConnector` / `new BrowserConnector`. */\nexport function toolSetConnector(\n ctx: DurableObjectState | ExecutionContext,\n options: ToolSetConnectorOptions\n): ToolSetConnector {\n return new ToolSetConnector(ctx, options);\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,YAAY,OAAkC;CACrD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;AAE3C;;;;;AAMA,SAAS,iBAAiB,OAAyB;CACjD,OACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;AAExD;;;;;AAMA,SAAS,oBACP,OACsC;CACtC,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CAExD,IAAI,gBAAgB,OAClB,OAAO;CAGT,M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,KAAA;GAGN,MAAM,cAAc,SAAS,MAAM,OAAO,aAAa,KAAA;GACvD,MAAM,eAAe,MAAM,iBACxB,EAAiC,YACpC;GAKA,MAAM,gBAAiB,EAAkC;GACzD,MAAM,mBACJ,kBAAkB,KAAA,KAAa,kBAAkB;GAEnD,IAAI,QAAQ;IACV,aACE,OAAO,EAAE,gBAAgB,aAAa,KAAA,IAAY,EAAE;IACzC;IACb,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;IACvC,GAAI,mBAAmB,EAAE,kBAAkB,KAAK,IAAI,CAAC;IACrD,SAAS,QAAQ,WACb,OAAO,SAAkB;KACvB,MAAM,SAAS,MAAM,OAAO,SAAU,IAAI;KAC1C,IAAI,CAAC,OAAO,SAAS,MAAM,OAAO;KAClC,OAAO,QAAQ,OAAO,KAAK;IAC7B,KACC,SAAkB,QAAQ,IAAI;GACrC;EACF;EACA,OAAO;CACT;;;;;;;;CASA,MAAe,qBAAsC;EACnD,OAAO,cAAc,KAAKA,iBAAiB,GAAG,KAAK,KAAK,CAAC;CAC3D;AACF;;;;;;;;;AAUA,eAAe,iBACb,KACkC;CAClC,IAAI,OAAO,MAAM,OAAO,KAAA;CACxB,IAAI;EACF,OACE,yBAAyB,GAAG,KAC1B,MAAM,SAAS,GAAqC,CAAC,CACpD;CAEP,QAAQ;EACN;CACF;AACF;;AAGA,SAAgB,iBACd,KACA,SACkB;CAClB,OAAO,IAAI,iBAAiB,KAAK,OAAO;AAC1C"}
|
package/dist/browser.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ import {
|
|
|
2
2
|
c as ExecuteResult,
|
|
3
3
|
l as Executor,
|
|
4
4
|
u as ResolvedProvider
|
|
5
|
-
} from "./executor-
|
|
6
|
-
import { n as CodeOutput, t as CodeInput } from "./shared-
|
|
5
|
+
} from "./executor-xSJFaECq.js";
|
|
6
|
+
import { n as CodeOutput, t as CodeInput } from "./shared-D5qepsss.js";
|
|
7
7
|
import {
|
|
8
8
|
n as JsonSchemaToolDescriptors,
|
|
9
9
|
t as JsonSchemaToolDescriptor
|
|
@@ -87,7 +87,7 @@ interface Executor {
|
|
|
87
87
|
/**
|
|
88
88
|
* A minimal tool record — just a description and an execute function.
|
|
89
89
|
* Use this for providers that supply their own `types` and don't need
|
|
90
|
-
* schema-based type generation
|
|
90
|
+
* schema-based type generation.
|
|
91
91
|
*/
|
|
92
92
|
type SimpleToolRecord = Record<
|
|
93
93
|
string,
|
|
@@ -211,4 +211,4 @@ export {
|
|
|
211
211
|
DynamicWorkerExecutor as t,
|
|
212
212
|
ResolvedProvider as u
|
|
213
213
|
};
|
|
214
|
-
//# sourceMappingURL=executor-
|
|
214
|
+
//# sourceMappingURL=executor-xSJFaECq.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -8,8 +8,8 @@ import {
|
|
|
8
8
|
s as ExecuteOptions,
|
|
9
9
|
t as DynamicWorkerExecutor,
|
|
10
10
|
u as ResolvedProvider
|
|
11
|
-
} from "./executor-
|
|
12
|
-
import { n as CodeOutput } from "./shared-
|
|
11
|
+
} from "./executor-xSJFaECq.js";
|
|
12
|
+
import { n as CodeOutput } from "./shared-D5qepsss.js";
|
|
13
13
|
import {
|
|
14
14
|
i as jsonSchemaToType,
|
|
15
15
|
n as JsonSchemaToolDescriptors,
|
|
@@ -29,7 +29,7 @@ import {
|
|
|
29
29
|
t as CodemodeConnector,
|
|
30
30
|
u as ToolAnnotations
|
|
31
31
|
} from "./base-DiFD41JY.js";
|
|
32
|
-
import { t as resolveProvider } from "./resolve-
|
|
32
|
+
import { t as resolveProvider } from "./resolve-ClRJA8iy.js";
|
|
33
33
|
import { DurableObject } from "cloudflare:workers";
|
|
34
34
|
|
|
35
35
|
//#region src/run-code.d.ts
|
package/dist/index.js
CHANGED
|
@@ -161,6 +161,63 @@ const SANDBOX_CODEC = String.raw`
|
|
|
161
161
|
return JSON.parse(json, (_key, nested) => __decodeCodemodeValue(nested));
|
|
162
162
|
}
|
|
163
163
|
`;
|
|
164
|
+
const LATE_CALL_MESSAGE = "The code execution finished before this tool call settled. Await every tool call before returning.";
|
|
165
|
+
const LATE_CALL = Symbol("codemode.lateCall");
|
|
166
|
+
/**
|
|
167
|
+
* Bounds every sandbox→host call to the lifetime of one `execute()`.
|
|
168
|
+
*
|
|
169
|
+
* A Dynamic Worker stays counted as in-flight while it has an outstanding
|
|
170
|
+
* RPC call to the host. If sandbox code returns without awaiting a tool call
|
|
171
|
+
* (`async () => { conn.ping(); return 1 }`), that call would otherwise keep
|
|
172
|
+
* the sandbox's request open until the host settles it — possibly never —
|
|
173
|
+
* and the Durable Object runs into the Dynamic Worker concurrency limit after
|
|
174
|
+
* a handful of executions.
|
|
175
|
+
*
|
|
176
|
+
* Once the execution settles the gate closes: calls still in flight — and
|
|
177
|
+
* calls that only reach the host afterwards — are answered immediately with a
|
|
178
|
+
* "late" value. The host-side work itself is not cancelled (a fire-and-forget
|
|
179
|
+
* call still runs, as before); the sandbox just no longer waits on it, and
|
|
180
|
+
* any sandbox continuation chained on the call sees the "late" error.
|
|
181
|
+
*/
|
|
182
|
+
var ExecutionGate = class {
|
|
183
|
+
#closed = false;
|
|
184
|
+
#resolveClosed;
|
|
185
|
+
#whenClosed = new Promise((resolve) => {
|
|
186
|
+
this.#resolveClosed = resolve;
|
|
187
|
+
});
|
|
188
|
+
close() {
|
|
189
|
+
if (this.#closed) return;
|
|
190
|
+
this.#closed = true;
|
|
191
|
+
this.#resolveClosed();
|
|
192
|
+
}
|
|
193
|
+
run(work, late) {
|
|
194
|
+
const pending = Promise.resolve().then(work);
|
|
195
|
+
pending.catch(() => {});
|
|
196
|
+
if (this.#closed) return Promise.resolve(late());
|
|
197
|
+
return Promise.race([pending, this.#whenClosed.then(late)]);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
/**
|
|
201
|
+
* Host-side wrapper around a connector binding, passed to the sandbox in its
|
|
202
|
+
* place so pending calls can be released when the execution settles (see
|
|
203
|
+
* `ExecutionGate`). Forwards to the real binding — an RpcTarget or a service
|
|
204
|
+
* stub — while the execution is live.
|
|
205
|
+
*/
|
|
206
|
+
var GatedConnectorBinding = class extends RpcTarget {
|
|
207
|
+
#binding;
|
|
208
|
+
#gate;
|
|
209
|
+
constructor(binding, gate) {
|
|
210
|
+
super();
|
|
211
|
+
this.#binding = binding;
|
|
212
|
+
this.#gate = gate;
|
|
213
|
+
}
|
|
214
|
+
callTool(method, args) {
|
|
215
|
+
return this.#gate.run(() => this.#binding.callTool(method, args), () => ({
|
|
216
|
+
[CONNECTOR_CONTROL_KEY]: "error",
|
|
217
|
+
message: LATE_CALL_MESSAGE
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
};
|
|
164
221
|
/**
|
|
165
222
|
* An RpcTarget that dispatches tool calls from the sandboxed Worker
|
|
166
223
|
* back to the host. Passed via Workers RPC to the dynamic Worker's
|
|
@@ -310,6 +367,7 @@ var DynamicWorkerExecutor = class {
|
|
|
310
367
|
" }",
|
|
311
368
|
"}"
|
|
312
369
|
]).join("\n");
|
|
370
|
+
const gate = new ExecutionGate();
|
|
313
371
|
const dispatchers = {};
|
|
314
372
|
for (const provider of providers) {
|
|
315
373
|
const sanitizedFns = {};
|
|
@@ -322,12 +380,16 @@ var DynamicWorkerExecutor = class {
|
|
|
322
380
|
error: `Tool names "${existingName}" and "${name}" both sanitize to "${sanitizedName}" in provider "${provider.name}"`
|
|
323
381
|
};
|
|
324
382
|
sanitizedNames.set(sanitizedName, name);
|
|
325
|
-
sanitizedFns[sanitizedName] =
|
|
383
|
+
sanitizedFns[sanitizedName] = async (...args) => {
|
|
384
|
+
const result = await gate.run(() => fn(...args), () => LATE_CALL);
|
|
385
|
+
if (result === LATE_CALL) throw new Error(LATE_CALL_MESSAGE);
|
|
386
|
+
return result;
|
|
387
|
+
};
|
|
326
388
|
}
|
|
327
389
|
dispatchers[provider.name] = new ToolDispatcher(sanitizedFns);
|
|
328
390
|
}
|
|
329
391
|
const connectorBindings = {};
|
|
330
|
-
for (const connector of connectors) connectorBindings[connector.name] = connector.binding;
|
|
392
|
+
for (const connector of connectors) connectorBindings[connector.name] = new GatedConnectorBinding(connector.binding, gate);
|
|
331
393
|
const env = { ...this.#bindings };
|
|
332
394
|
const hasEnv = Object.keys(env).length > 0;
|
|
333
395
|
const worker = this.#loader.load({
|
|
@@ -358,6 +420,7 @@ var DynamicWorkerExecutor = class {
|
|
|
358
420
|
disposeQuietly(entrypoint);
|
|
359
421
|
}
|
|
360
422
|
} finally {
|
|
423
|
+
gate.close();
|
|
361
424
|
disposeQuietly(worker);
|
|
362
425
|
}
|
|
363
426
|
}
|