@cloudflare/codemode 0.4.3 → 0.5.0
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 +16 -4
- package/dist/ai.d.ts +1 -1
- package/dist/ai.js +1 -1
- package/dist/ai.js.map +1 -1
- package/dist/{base-B2amchZA.d.ts → base-DiFD41JY.d.ts} +5 -3
- package/dist/index.d.ts +8 -1
- package/dist/index.js +20 -0
- package/dist/index.js.map +1 -1
- package/docs/runtime.md +16 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -60,7 +60,7 @@ const codemode = createCodeTool({ tools, executor });
|
|
|
60
60
|
// 4. Use it with streamText — the LLM writes code that calls your tools
|
|
61
61
|
const result = streamText({
|
|
62
62
|
model,
|
|
63
|
-
|
|
63
|
+
instructions: "You are a helpful assistant.",
|
|
64
64
|
messages,
|
|
65
65
|
tools: { codemode }
|
|
66
66
|
});
|
|
@@ -220,6 +220,18 @@ const result = streamText({
|
|
|
220
220
|
});
|
|
221
221
|
```
|
|
222
222
|
|
|
223
|
+
For non-AI-SDK hosts such as MCP servers, use the same runtime directly:
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
const matches = await runtime.search("create issue");
|
|
227
|
+
const docs = await runtime.describe(matches.results[0].path);
|
|
228
|
+
const outcome = await runtime.execute({
|
|
229
|
+
code: `async () => github.create_issue({ title: "Bug" })`
|
|
230
|
+
});
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Search and describe results include `requiresApproval: true` for protected connector methods. A paused `execute()` outcome can be resolved with the same `approve()` and `reject()` methods used by an approval UI.
|
|
234
|
+
|
|
223
235
|
Inside the sandbox, each connector is available as a global named after the connector. The `codemode` platform SDK provides discovery:
|
|
224
236
|
|
|
225
237
|
```ts
|
|
@@ -565,7 +577,7 @@ The user sends a message, the agent passes it to an LLM with the codemode tool,
|
|
|
565
577
|
import { Agent } from "agents";
|
|
566
578
|
import { createCodeTool } from "@cloudflare/codemode/ai";
|
|
567
579
|
import { DynamicWorkerExecutor } from "@cloudflare/codemode";
|
|
568
|
-
import { streamText, convertToModelMessages,
|
|
580
|
+
import { streamText, convertToModelMessages, isStepCount } from "ai";
|
|
569
581
|
|
|
570
582
|
export class MyAgent extends Agent<Env, State> {
|
|
571
583
|
async onChatMessage() {
|
|
@@ -575,10 +587,10 @@ export class MyAgent extends Agent<Env, State> {
|
|
|
575
587
|
|
|
576
588
|
const result = streamText({
|
|
577
589
|
model,
|
|
578
|
-
|
|
590
|
+
instructions: "You are a helpful assistant.",
|
|
579
591
|
messages: await convertToModelMessages(this.state.messages),
|
|
580
592
|
tools: { codemode },
|
|
581
|
-
stopWhen:
|
|
593
|
+
stopWhen: isStepCount(10)
|
|
582
594
|
});
|
|
583
595
|
|
|
584
596
|
// Stream response back to client...
|
package/dist/ai.d.ts
CHANGED
package/dist/ai.js
CHANGED
|
@@ -288,7 +288,7 @@ var ToolSetConnector = class extends CodemodeConnector {
|
|
|
288
288
|
const needsApproval = t.needsApproval;
|
|
289
289
|
const requiresApproval = needsApproval !== void 0 && needsApproval !== false;
|
|
290
290
|
out[name] = {
|
|
291
|
-
description: t.description,
|
|
291
|
+
description: typeof t.description === "function" ? void 0 : t.description,
|
|
292
292
|
inputSchema: schema?.jsonSchema,
|
|
293
293
|
...requiresApproval ? { requiresApproval: true } : {},
|
|
294
294
|
execute: schema?.validate ? async (args) => {
|
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\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) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n return `type ${typeName} = unknown`;\n }\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 ? safeSchemaToTs(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 } 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 tools(): 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\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: t.description,\n inputSchema: schema?.jsonSchema as JSONSchema7 | undefined,\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/** 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,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,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;;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\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) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n return `type ${typeName} = unknown`;\n }\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 ? safeSchemaToTs(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 } 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 tools(): 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\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: schema?.jsonSchema as JSONSchema7 | undefined,\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/** 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,MAAM,UAAU,OAAO,sBAAsB,OAAO;CACpD,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,QAAoC;EACtD,IAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,UAC9D,OAAQ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BAAiB,CAAC,GAAG;GACnE,MAAM,UAAU,EAAE;GAElB,MAAM,OAAO,iBAAiB,QAAQ;GACtC,MAAM,WAAW,QAAQ,IAAI,IAAI;GACjC,IAAI,aAAa,KAAA,GACf,MAAM,IAAI,MACR,UAAU,SAAS,SAAS,SAAS,OAAO,KAAK,KAAK,EAAE,gBAC3C,KAAK,wBACpB;GAEF,QAAQ,IAAI,MAAM,QAAQ;GAE1B,MAAM,YACJ,iBAAiB,IACb,EAAE,cACD,EAA8B;GACrC,MAAM,SACJ,aAAa,OACT,SAAS,SAA2C,IACpD,KAAA;GAKN,MAAM,gBAAiB,EAAkC;GACzD,MAAM,mBACJ,kBAAkB,KAAA,KAAa,kBAAkB;GAEnD,IAAI,QAAQ;IACV,aACE,OAAO,EAAE,gBAAgB,aAAa,KAAA,IAAY,EAAE;IACtD,aAAa,QAAQ;IACrB,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;;AAGA,SAAgB,iBACd,KACA,SACkB;CAClB,OAAO,IAAI,iBAAiB,KAAK,OAAO;AAC1C"}
|
|
@@ -54,7 +54,8 @@ type SearchResult = {
|
|
|
54
54
|
path: string;
|
|
55
55
|
connector: string;
|
|
56
56
|
method: string;
|
|
57
|
-
description?: string
|
|
57
|
+
description?: string /** Whether invoking this method pauses for approval. */;
|
|
58
|
+
requiresApproval?: boolean;
|
|
58
59
|
kind: "method" | "snippet";
|
|
59
60
|
score: number;
|
|
60
61
|
};
|
|
@@ -65,7 +66,8 @@ type SearchOutput = {
|
|
|
65
66
|
};
|
|
66
67
|
type DescribeOutput = {
|
|
67
68
|
path: string;
|
|
68
|
-
description?: string
|
|
69
|
+
description?: string /** Whether invoking this method pauses for approval. */;
|
|
70
|
+
requiresApproval?: boolean;
|
|
69
71
|
types: string;
|
|
70
72
|
kind: "connector" | "method" | "snippet";
|
|
71
73
|
};
|
|
@@ -236,4 +238,4 @@ export {
|
|
|
236
238
|
CodemodeConnector as t,
|
|
237
239
|
ToolAnnotations as u
|
|
238
240
|
};
|
|
239
|
-
//# sourceMappingURL=base-
|
|
241
|
+
//# sourceMappingURL=base-DiFD41JY.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -28,7 +28,7 @@ import {
|
|
|
28
28
|
s as PassEndStatus,
|
|
29
29
|
t as CodemodeConnector,
|
|
30
30
|
u as ToolAnnotations
|
|
31
|
-
} from "./base-
|
|
31
|
+
} from "./base-DiFD41JY.js";
|
|
32
32
|
import { t as resolveProvider } from "./resolve-tqDt6Djo.js";
|
|
33
33
|
import { DurableObject } from "cloudflare:workers";
|
|
34
34
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
@@ -589,7 +589,14 @@ type CodemodeExpireOptions = {
|
|
|
589
589
|
maxAgeMs?: number;
|
|
590
590
|
};
|
|
591
591
|
interface CodemodeRuntimeHandle {
|
|
592
|
+
/** Create the AI SDK-compatible model-facing Code Mode tool. */
|
|
592
593
|
tool(options?: CodemodeRuntimeToolOptions): CodemodeTool;
|
|
594
|
+
/** Execute code directly, without adapting the runtime to an AI SDK tool. */
|
|
595
|
+
execute(input: ProxyToolInput): Promise<ProxyToolOutput>;
|
|
596
|
+
/** Search connector methods and saved snippets. */
|
|
597
|
+
search(query: string): Promise<SearchOutput>;
|
|
598
|
+
/** Get on-demand TypeScript documentation for a connector method or snippet. */
|
|
599
|
+
describe(target: string): Promise<DescribeOutput>;
|
|
593
600
|
approve(options: CodemodeApproveOptions): Promise<ProxyToolOutput>;
|
|
594
601
|
/**
|
|
595
602
|
* Reject a pending action, ending the run. Returns whether the reject
|
package/dist/index.js
CHANGED
|
@@ -1360,6 +1360,7 @@ function scoreMatch(item, query) {
|
|
|
1360
1360
|
connector: item.connector,
|
|
1361
1361
|
method: item.method,
|
|
1362
1362
|
description: item.description,
|
|
1363
|
+
...item.requiresApproval ? { requiresApproval: true } : {},
|
|
1363
1364
|
kind: item.kind,
|
|
1364
1365
|
score
|
|
1365
1366
|
};
|
|
@@ -1371,6 +1372,7 @@ function searchConnectors(query, descriptions, snippets) {
|
|
|
1371
1372
|
connector: desc.name,
|
|
1372
1373
|
method: methodName,
|
|
1373
1374
|
description: descriptor?.description,
|
|
1375
|
+
...desc.annotations?.[methodName]?.requiresApproval ? { requiresApproval: true } : {},
|
|
1374
1376
|
kind: "method"
|
|
1375
1377
|
});
|
|
1376
1378
|
if (snippets) for (const snippet of snippets) items.push({
|
|
@@ -1430,6 +1432,7 @@ function describeTarget(target, descriptions, snippets) {
|
|
|
1430
1432
|
for (const candidate of candidates) if (candidate.descriptors[methodName]) return {
|
|
1431
1433
|
path: `${candidate.name}.${methodName}`,
|
|
1432
1434
|
description: candidate.descriptors[methodName]?.description,
|
|
1435
|
+
...candidate.annotations?.[methodName]?.requiresApproval ? { requiresApproval: true } : {},
|
|
1433
1436
|
types: renderMethodTypes(methodName, candidate.descriptors),
|
|
1434
1437
|
kind: "method"
|
|
1435
1438
|
};
|
|
@@ -1890,6 +1893,8 @@ function createCodemodeRuntime(options) {
|
|
|
1890
1893
|
}
|
|
1891
1894
|
var DefaultCodemodeRuntimeHandle = class {
|
|
1892
1895
|
#options;
|
|
1896
|
+
#executionTool;
|
|
1897
|
+
#descriptionsPromise;
|
|
1893
1898
|
constructor(options) {
|
|
1894
1899
|
validateConnectorNames(options.connectors);
|
|
1895
1900
|
this.#options = options;
|
|
@@ -1906,6 +1911,18 @@ var DefaultCodemodeRuntimeHandle = class {
|
|
|
1906
1911
|
transformResult: this.#options.transformResult
|
|
1907
1912
|
});
|
|
1908
1913
|
}
|
|
1914
|
+
execute(input) {
|
|
1915
|
+
this.#executionTool ??= this.tool();
|
|
1916
|
+
return this.#executionTool.execute(input, void 0);
|
|
1917
|
+
}
|
|
1918
|
+
async search(query) {
|
|
1919
|
+
const [descriptions, snippets] = await Promise.all([this.#descriptions(), this.snippets()]);
|
|
1920
|
+
return searchConnectors(query, descriptions, snippets);
|
|
1921
|
+
}
|
|
1922
|
+
async describe(target) {
|
|
1923
|
+
const [descriptions, snippets] = await Promise.all([this.#descriptions(), this.snippets()]);
|
|
1924
|
+
return describeTarget(target, descriptions, snippets);
|
|
1925
|
+
}
|
|
1909
1926
|
approve(options) {
|
|
1910
1927
|
return resumeCodemode({
|
|
1911
1928
|
ctx: this.#options.ctx,
|
|
@@ -1971,6 +1988,9 @@ var DefaultCodemodeRuntimeHandle = class {
|
|
|
1971
1988
|
deleteSnippet(name) {
|
|
1972
1989
|
return this.#runtime().deleteSnippet(name);
|
|
1973
1990
|
}
|
|
1991
|
+
#descriptions() {
|
|
1992
|
+
return this.#descriptionsPromise ??= Promise.all(this.#options.connectors.map((connector) => connector.describe()));
|
|
1993
|
+
}
|
|
1974
1994
|
#runtime() {
|
|
1975
1995
|
return getCodemodeRuntime(this.#options.ctx, this.#options.name);
|
|
1976
1996
|
}
|