@cloudflare/codemode 0.3.8 → 0.4.1
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/LICENSE +21 -0
- package/README.md +251 -7
- package/dist/ai.d.ts +50 -7
- package/dist/ai.js +93 -5
- package/dist/ai.js.map +1 -1
- package/dist/base-B2amchZA.d.ts +239 -0
- package/dist/base-CHRR_a5j.js +156 -0
- package/dist/base-CHRR_a5j.js.map +1 -0
- package/dist/browser.d.ts +6 -6
- package/dist/browser.js +2 -2
- package/dist/browser.js.map +1 -1
- package/dist/{executor-BRm90XJT.d.ts → executor-BIs2dr7X.d.ts} +48 -10
- package/dist/index.d.ts +608 -8
- package/dist/index.js +1690 -17
- package/dist/index.js.map +1 -1
- package/dist/{json-schema-types-CVt4X9cw.js → json-schema-types-BGjW4KPy.js} +1 -1
- package/dist/{json-schema-types-CVt4X9cw.js.map → json-schema-types-BGjW4KPy.js.map} +1 -1
- package/dist/{json-schema-types-1OL3uao0.d.ts → json-schema-types-Cb2wClAd.d.ts} +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +2 -2
- package/dist/mcp.js.map +1 -1
- package/dist/{resolve-DdyeEp3l.js → resolve-34dC47Il.js} +1 -1
- package/dist/{resolve-DdyeEp3l.js.map → resolve-34dC47Il.js.map} +1 -1
- package/dist/{resolve-DtfaKmms.d.ts → resolve-CBr_VoPl.d.ts} +4 -4
- package/dist/{run-code-5x8S5YWt.js → run-code-aKHcTgf9.js} +4 -4
- package/dist/run-code-aKHcTgf9.js.map +1 -0
- package/dist/{shared-TyFN6W7_.d.ts → shared-Ce-zCEBP.d.ts} +3 -3
- package/dist/{shared-xjl2irqK.js → shared-SMjV5yN4.js} +1 -1
- package/dist/{shared-xjl2irqK.js.map → shared-SMjV5yN4.js.map} +1 -1
- package/dist/tanstack-ai.d.ts +3 -3
- package/dist/tanstack-ai.js +4 -4
- package/dist/tanstack-ai.js.map +1 -1
- package/dist/vite.d.ts +7 -0
- package/dist/vite.js +122 -0
- package/dist/vite.js.map +1 -0
- package/package.json +19 -14
- package/dist/run-code-5x8S5YWt.js.map +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License Copyright (c) 2025 Cloudflare, Inc.
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of
|
|
4
|
+
charge, to any person obtaining a copy of this software and associated
|
|
5
|
+
documentation files (the "Software"), to deal in the Software without
|
|
6
|
+
restriction, including without limitation the rights to use, copy, modify, merge,
|
|
7
|
+
publish, distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to the
|
|
9
|
+
following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice
|
|
12
|
+
(including the next paragraph) shall be included in all copies or substantial
|
|
13
|
+
portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
|
16
|
+
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
17
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
18
|
+
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
|
19
|
+
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
20
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -191,6 +191,249 @@ import { resolveProvider } from "@cloudflare/codemode";
|
|
|
191
191
|
await executor.execute(code, [resolveProvider(dbProvider)]);
|
|
192
192
|
```
|
|
193
193
|
|
|
194
|
+
## Connectors
|
|
195
|
+
|
|
196
|
+
Connectors are class-based integrations that bridge external services into the codemode sandbox. Each connector extends `WorkerEntrypoint`, making it serializable, RPC-callable, and available as `ctx.exports.ConnectorName`.
|
|
197
|
+
|
|
198
|
+
Create a runtime with an executor and connectors, then expose `runtime.tool()` to the model:
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
import {
|
|
202
|
+
createCodemodeRuntime,
|
|
203
|
+
DynamicWorkerExecutor
|
|
204
|
+
} from "@cloudflare/codemode";
|
|
205
|
+
|
|
206
|
+
const runtime = createCodemodeRuntime({
|
|
207
|
+
ctx: this.ctx,
|
|
208
|
+
executor: new DynamicWorkerExecutor({ loader: this.env.LOADER }),
|
|
209
|
+
connectors: [github, repoApi]
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const result = streamText({
|
|
213
|
+
model,
|
|
214
|
+
messages,
|
|
215
|
+
tools: {
|
|
216
|
+
codemode: runtime.tool()
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
Inside the sandbox, each connector is available as a global named after the connector. The `codemode` platform SDK provides discovery:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
// discover
|
|
225
|
+
const matches = await codemode.search("pull request");
|
|
226
|
+
const docs = await codemode.describe("github.list_pull_requests");
|
|
227
|
+
|
|
228
|
+
// call
|
|
229
|
+
const prs = await github.list_pull_requests({
|
|
230
|
+
owner: "cloudflare",
|
|
231
|
+
repo: "agents"
|
|
232
|
+
});
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
### `McpConnector`
|
|
236
|
+
|
|
237
|
+
Wraps an MCP server. Each MCP tool becomes a method on the connector namespace.
|
|
238
|
+
|
|
239
|
+
Under the hood: fetches tools from the MCP connection via `listTools()`, creates a descriptor per tool for search/describe, and dispatches calls through `connection.client.callTool()`. Tool names are sanitized into valid JS identifiers.
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
// github.codemode.ts
|
|
243
|
+
import {
|
|
244
|
+
McpConnector,
|
|
245
|
+
type McpConnectionLike,
|
|
246
|
+
type ConnectorTool
|
|
247
|
+
} from "@cloudflare/codemode";
|
|
248
|
+
|
|
249
|
+
export class GithubConnector extends McpConnector<Env> {
|
|
250
|
+
constructor(
|
|
251
|
+
ctx: ExecutionContext,
|
|
252
|
+
env: Env,
|
|
253
|
+
private conn: McpConnectionLike
|
|
254
|
+
) {
|
|
255
|
+
super(ctx, env);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
name() {
|
|
259
|
+
return "github";
|
|
260
|
+
}
|
|
261
|
+
protected instructions() {
|
|
262
|
+
return "Use for GitHub operations.";
|
|
263
|
+
}
|
|
264
|
+
protected createConnection() {
|
|
265
|
+
return this.conn;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// Override to customize tool naming
|
|
269
|
+
// protected toolName(tool: McpTool) { return sanitizeToolName(tool.name); }
|
|
270
|
+
|
|
271
|
+
// Decorate derived tools: mark approvals, attach reverts
|
|
272
|
+
protected tool(name: string, t: ConnectorTool): ConnectorTool {
|
|
273
|
+
return name === "create_issue" ? { ...t, requiresApproval: true } : t;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
Sandbox sees:
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
github.list_pull_requests({ owner, repo, state });
|
|
282
|
+
github.search_issues({ query });
|
|
283
|
+
// ... one method per MCP tool
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
### `OpenApiConnector`
|
|
287
|
+
|
|
288
|
+
Wraps an OpenAPI spec. The base reads the spec **once, host-side** and derives one typed tool **per operation**, so the model calls operations directly — `stripe.CreatePaymentIntent({ amount, currency })` — discoverable through `codemode.search`/`describe` with real input types (deriving on the host costs zero prompt tokens). Override two methods: `spec()` returns the OpenAPI document (operations are derived from it), and `request()` performs an authenticated request. A low-level `request` tool stays available as an escape hatch.
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
// stripe.codemode.ts
|
|
292
|
+
import {
|
|
293
|
+
OpenApiConnector,
|
|
294
|
+
type OpenApiRequestOptions
|
|
295
|
+
} from "@cloudflare/codemode";
|
|
296
|
+
|
|
297
|
+
export class StripeConnector extends OpenApiConnector<Env> {
|
|
298
|
+
name() {
|
|
299
|
+
return "stripe";
|
|
300
|
+
}
|
|
301
|
+
protected instructions() {
|
|
302
|
+
return "Use for Stripe payments. Call the per-operation tools directly.";
|
|
303
|
+
}
|
|
304
|
+
protected spec() {
|
|
305
|
+
return stripeOpenApiSpec;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
protected request(options: OpenApiRequestOptions) {
|
|
309
|
+
return fetch(`https://api.stripe.com${options.path}`, {
|
|
310
|
+
method: options.method ?? "GET",
|
|
311
|
+
headers: { Authorization: `Bearer ${this.env.STRIPE_KEY}` },
|
|
312
|
+
body: options.body ? JSON.stringify(options.body) : undefined
|
|
313
|
+
}).then((r) => r.json());
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
Sandbox sees:
|
|
319
|
+
|
|
320
|
+
```ts
|
|
321
|
+
// Per-operation tool, derived from the spec (path params substituted for you).
|
|
322
|
+
const intent = await stripe.CreatePaymentIntent({
|
|
323
|
+
amount: 2000,
|
|
324
|
+
currency: "usd"
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
// Escape hatch, if an operation isn't reachable via a derived tool:
|
|
328
|
+
const raw = await stripe.request({ path: "/v1/charges", method: "GET" });
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
### `CodemodeConnector` (base class)
|
|
332
|
+
|
|
333
|
+
All connectors extend `CodemodeConnector`, which extends `WorkerEntrypoint`. A connector is three things — `name()`, optional `instructions()`, and `tools()`. Each tool carries its own docs, schema, approval requirement, execution, and optional revert, so everything about a tool lives in one place:
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
import { CodemodeConnector } from "@cloudflare/codemode";
|
|
337
|
+
|
|
338
|
+
export class MyConnector extends CodemodeConnector<Env> {
|
|
339
|
+
name() {
|
|
340
|
+
return "myService";
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
protected tools() {
|
|
344
|
+
return {
|
|
345
|
+
listThings: {
|
|
346
|
+
description: "List things.",
|
|
347
|
+
inputSchema: { type: "object" },
|
|
348
|
+
execute: (args) => this.env.MY_SERVICE.list(args)
|
|
349
|
+
},
|
|
350
|
+
createThing: {
|
|
351
|
+
description: "Create a thing.",
|
|
352
|
+
inputSchema: {
|
|
353
|
+
type: "object",
|
|
354
|
+
properties: { title: { type: "string" } },
|
|
355
|
+
required: ["title"]
|
|
356
|
+
},
|
|
357
|
+
requiresApproval: true, // pauses the run for user approval
|
|
358
|
+
execute: (args) => this.env.MY_SERVICE.create(args),
|
|
359
|
+
revert: (_args, result) => this.env.MY_SERVICE.delete(result.id) // enables rollback
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
An existing AI SDK `ToolSet` is shape-compatible and can be returned from `tools()` directly:
|
|
367
|
+
|
|
368
|
+
```ts
|
|
369
|
+
export class LinearConnector extends CodemodeConnector<Env> {
|
|
370
|
+
name() {
|
|
371
|
+
return "linear";
|
|
372
|
+
}
|
|
373
|
+
protected tools() {
|
|
374
|
+
return linearTools; // AI SDK ToolSet
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
The `tool(name, t)` decoration hook adjusts tools you didn't author inline (used with MCP/OpenAPI-derived tools). The RPC wire surface (`describe()`, `executeTool()`, `revertAction()`, `getTypeScriptTypes()`) is derived from the tools record — you don't implement it.
|
|
380
|
+
|
|
381
|
+
The agent drives approvals through the runtime: `runtime.pending()`, `runtime.approve({ executionId })`, `runtime.reject({ seq, executionId })`, `runtime.rollback({ executionId })` (see [docs/codemode/approvals.md](../../docs/codemode/approvals.md)).
|
|
382
|
+
|
|
383
|
+
### Snippets
|
|
384
|
+
|
|
385
|
+
Snippets are durable, addressable saved scripts. The model writes and runs scripts; the developer promotes the ones worth keeping (`runtime.saveSnippet`), and the model reuses them (`codemode.run`). No authoring step, no skill-source interface.
|
|
386
|
+
|
|
387
|
+
```ts
|
|
388
|
+
// host side: review runs, promote one
|
|
389
|
+
const runs = await runtime.executions();
|
|
390
|
+
await runtime.saveSnippet("list-open-prs", {
|
|
391
|
+
executionId: runs[0].id,
|
|
392
|
+
description: "List open PRs for a repo."
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
// sandbox side: the model runs it by name
|
|
396
|
+
const prs = await codemode.run("list-open-prs");
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
Snippets appear in `codemode.search` results (with `kind: "snippet"`) and are documented via `codemode.describe(name)`. They live on the runtime facet, whose identity is derived from the connector set — so a snippet is always run against exactly the connectors it was written with. See [docs/codemode/snippets.md](../../docs/codemode/snippets.md).
|
|
400
|
+
|
|
401
|
+
### Vite plugin
|
|
402
|
+
|
|
403
|
+
The `@cloudflare/codemode/vite` plugin discovers `*.codemode.ts` files and auto-exports connector classes from the worker entry module, making them available as `ctx.exports.ConnectorName`:
|
|
404
|
+
|
|
405
|
+
```ts
|
|
406
|
+
// vite.config.ts
|
|
407
|
+
import codemode from "@cloudflare/codemode/vite";
|
|
408
|
+
export default { plugins: [codemode()] };
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
Import connectors with the `type: "connectors"` attribute:
|
|
412
|
+
|
|
413
|
+
```ts
|
|
414
|
+
import { GithubConnector } from "./github.codemode" with { type: "connectors" };
|
|
415
|
+
import { StripeConnector } from "./stripe.codemode" with { type: "connectors" };
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
### How connector calls work
|
|
419
|
+
|
|
420
|
+
```
|
|
421
|
+
┌─────────────────────┐ ┌─────────────────────────────────────────────┐
|
|
422
|
+
│ │ │ Dynamic Worker (isolated sandbox) │
|
|
423
|
+
│ Host Worker │ RPC │ │
|
|
424
|
+
│ │◄──────►│ github.list_pull_requests(args) │
|
|
425
|
+
│ Connectors are │ │ → env.__connectors.github.callTool(...) │
|
|
426
|
+
│ env bindings │ │ → Workers RPC │
|
|
427
|
+
│ (WorkerEntrypoint) │ │ │
|
|
428
|
+
│ │ │ codemode.search("query") │
|
|
429
|
+
│ Platform SDK uses │ │ → __dispatchers.codemode.call(...) │
|
|
430
|
+
│ ToolDispatcher │ │ → host-side search │
|
|
431
|
+
│ │ │ │
|
|
432
|
+
└─────────────────────┘ └─────────────────────────────────────────────┘
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
Connector calls go via **Workers RPC** directly to the connector's `callTool()` method — no JSON serialization through ToolDispatcher. The platform SDK (`codemode.search`, `codemode.describe`, etc.) uses the traditional ToolDispatcher path since it's host-created.
|
|
436
|
+
|
|
194
437
|
## Architecture
|
|
195
438
|
|
|
196
439
|
### How it works
|
|
@@ -439,22 +682,23 @@ const types = generateTypes(myAiSdkTools);
|
|
|
439
682
|
|
|
440
683
|
## Module Structure
|
|
441
684
|
|
|
442
|
-
| Module | Peer deps | Exports
|
|
443
|
-
| ---------------------------------- | --------------------- |
|
|
444
|
-
| `@cloudflare/codemode` | None | `
|
|
445
|
-
| `@cloudflare/codemode/ai` | `ai`, `zod` | `createCodeTool`, `generateTypes`, `aiTools`, `resolveProvider`, `ToolDescriptor`, `ToolDescriptors`
|
|
446
|
-
| `@cloudflare/codemode/tanstack-ai` | `@tanstack/ai`, `zod` | `createCodeTool`, `generateTypes`, `tanstackTools`, `resolveProvider`
|
|
447
|
-
| `@cloudflare/codemode/browser` | None | `createBrowserCodeTool`, `IframeSandboxExecutor`, `Executor`, `ExecuteResult`, `ResolvedProvider`, JSON Schema tool descriptor types
|
|
685
|
+
| Module | Peer deps | Exports |
|
|
686
|
+
| ---------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
|
687
|
+
| `@cloudflare/codemode` | None | `createCodemodeRuntime`, connector base classes, `DynamicWorkerExecutor`, executor utilities, JSON Schema type helpers |
|
|
688
|
+
| `@cloudflare/codemode/ai` | `ai`, `zod` | `createCodeTool`, `generateTypes`, `aiTools`, `resolveProvider`, `ToolDescriptor`, `ToolDescriptors` |
|
|
689
|
+
| `@cloudflare/codemode/tanstack-ai` | `@tanstack/ai`, `zod` | `createCodeTool`, `generateTypes`, `tanstackTools`, `resolveProvider` |
|
|
690
|
+
| `@cloudflare/codemode/browser` | None | `createBrowserCodeTool`, `IframeSandboxExecutor`, `Executor`, `ExecuteResult`, `ResolvedProvider`, JSON Schema tool descriptor types |
|
|
448
691
|
|
|
449
692
|
## Limitations
|
|
450
693
|
|
|
451
|
-
-
|
|
694
|
+
- Runtime approval support applies to connector annotations. Legacy `createCodeTool` still excludes tools with `needsApproval: true` instead of pausing execution.
|
|
452
695
|
- Browser iframe execution uses nonce-scoped internal messages, but its timeout cannot preempt tight synchronous loops like `while (true) {}` because those block the browser event loop.
|
|
453
696
|
- Requires Cloudflare Workers environment for `DynamicWorkerExecutor`
|
|
454
697
|
- Limited to JavaScript execution
|
|
455
698
|
|
|
456
699
|
## Examples
|
|
457
700
|
|
|
701
|
+
- [`examples/codemode-connectors/`](../../examples/codemode-connectors/) — Runtime and connector example with MCP and OpenAPI connectors
|
|
458
702
|
- [`examples/codemode/`](../../examples/codemode/) — Full working example with task management tools
|
|
459
703
|
- [`examples/codemode-browser/`](../../examples/codemode-browser/) — Browser iframe executor example with dynamic client tools
|
|
460
704
|
|
package/dist/ai.d.ts
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
d as ToolDescriptor,
|
|
3
|
+
f as ToolDescriptors,
|
|
4
4
|
i as ToolProvider,
|
|
5
|
-
|
|
6
|
-
u as
|
|
7
|
-
} from "./executor-
|
|
5
|
+
p as generateTypes,
|
|
6
|
+
u as ResolvedProvider
|
|
7
|
+
} from "./executor-BIs2dr7X.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-Ce-zCEBP.js";
|
|
13
|
+
import {
|
|
14
|
+
r as ConnectorTools,
|
|
15
|
+
t as CodemodeConnector
|
|
16
|
+
} from "./base-B2amchZA.js";
|
|
13
17
|
import { Tool, ToolSet } from "ai";
|
|
14
18
|
|
|
15
19
|
//#region src/tool.d.ts
|
|
@@ -34,15 +38,54 @@ declare function createCodeTool(
|
|
|
34
38
|
options: CreateCodeToolOptions
|
|
35
39
|
): Tool<CodeInput, CodeOutput>;
|
|
36
40
|
//#endregion
|
|
41
|
+
//#region src/connectors/toolset.d.ts
|
|
42
|
+
interface ToolSetConnectorOptions {
|
|
43
|
+
/**
|
|
44
|
+
* The namespace the sandbox sees, e.g. `"tools"` → `tools.getWeather(...)`.
|
|
45
|
+
* Defaults to `"tools"`. (`"codemode"` is reserved for the platform SDK.)
|
|
46
|
+
*/
|
|
47
|
+
name?: string;
|
|
48
|
+
/** Extra model guidance, surfaced with the connector's type block. */
|
|
49
|
+
instructions?: string;
|
|
50
|
+
/** The AI SDK tools to expose. */
|
|
51
|
+
tools: ToolSet;
|
|
52
|
+
}
|
|
53
|
+
declare class ToolSetConnector extends CodemodeConnector {
|
|
54
|
+
#private;
|
|
55
|
+
constructor(
|
|
56
|
+
ctx: DurableObjectState | ExecutionContext,
|
|
57
|
+
options: ToolSetConnectorOptions
|
|
58
|
+
);
|
|
59
|
+
name(): string;
|
|
60
|
+
protected instructions(): string | undefined;
|
|
61
|
+
protected tools(): ConnectorTools;
|
|
62
|
+
/**
|
|
63
|
+
* Generate the sandbox type block from the original AI SDK schemas (Zod or
|
|
64
|
+
* `jsonSchema()` wrappers) rather than the converted JSON Schema, preserving
|
|
65
|
+
* field descriptions as `@param` lines. Restricted to the same executable
|
|
66
|
+
* subset that `tools()` exposes, so the types never advertise a method the
|
|
67
|
+
* sandbox can't call.
|
|
68
|
+
*/
|
|
69
|
+
getTypeScriptTypes(): Promise<string>;
|
|
70
|
+
}
|
|
71
|
+
/** Convenience constructor mirroring `stateConnector` / `new BrowserConnector`. */
|
|
72
|
+
declare function toolSetConnector(
|
|
73
|
+
ctx: DurableObjectState | ExecutionContext,
|
|
74
|
+
options: ToolSetConnectorOptions
|
|
75
|
+
): ToolSetConnector;
|
|
76
|
+
//#endregion
|
|
37
77
|
export {
|
|
38
78
|
type CodeInput,
|
|
39
79
|
type CodeOutput,
|
|
40
80
|
type CreateCodeToolOptions,
|
|
41
81
|
type ToolDescriptor,
|
|
42
82
|
type ToolDescriptors,
|
|
83
|
+
ToolSetConnector,
|
|
84
|
+
type ToolSetConnectorOptions,
|
|
43
85
|
aiTools,
|
|
44
86
|
createCodeTool,
|
|
45
87
|
generateTypes,
|
|
46
|
-
resolveProvider
|
|
88
|
+
resolveProvider,
|
|
89
|
+
toolSetConnector
|
|
47
90
|
};
|
|
48
91
|
//# sourceMappingURL=ai.d.ts.map
|
package/dist/ai.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-BGjW4KPy.js";
|
|
2
|
+
import { t as runCode } from "./run-code-aKHcTgf9.js";
|
|
3
|
+
import { n as filterTools } from "./resolve-34dC47Il.js";
|
|
4
|
+
import { t as CodemodeConnector } from "./base-CHRR_a5j.js";
|
|
5
|
+
import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-SMjV5yN4.js";
|
|
5
6
|
import { asSchema, tool } from "ai";
|
|
6
7
|
import { z } from "zod";
|
|
7
8
|
//#region src/tool-types.ts
|
|
@@ -228,6 +229,93 @@ function createCodeTool(options) {
|
|
|
228
229
|
});
|
|
229
230
|
}
|
|
230
231
|
//#endregion
|
|
231
|
-
|
|
232
|
+
//#region src/connectors/toolset.ts
|
|
233
|
+
/**
|
|
234
|
+
* ToolSetConnector — adapt an AI SDK `ToolSet` to the connector model.
|
|
235
|
+
*
|
|
236
|
+
* Each tool in the set becomes one connector tool under a single namespace
|
|
237
|
+
* (default `"tools"`). Tools with `needsApproval` map to `requiresApproval`:
|
|
238
|
+
* calling one pauses the run durably until the host approves
|
|
239
|
+
* (`runtime.approve()`), then the run resumes where it stopped — the
|
|
240
|
+
* runtime's pause/approve/resume flow, not the AI SDK's per-call approval.
|
|
241
|
+
* A function-valued `needsApproval` cannot be evaluated against sandbox
|
|
242
|
+
* arguments ahead of time, so it conservatively always requires approval.
|
|
243
|
+
*
|
|
244
|
+
* Lives in the `/ai` entry because schema handling (`asSchema`) needs the
|
|
245
|
+
* `ai` peer dependency.
|
|
246
|
+
*/
|
|
247
|
+
var ToolSetConnector = class extends CodemodeConnector {
|
|
248
|
+
#options;
|
|
249
|
+
#warnedSkipped = false;
|
|
250
|
+
constructor(ctx, options) {
|
|
251
|
+
super(ctx, {});
|
|
252
|
+
this.#options = options;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Only tools with an `execute` function can run inside the sandbox.
|
|
256
|
+
* Execute-less tools (client-side / provider-executed) are excluded from
|
|
257
|
+
* both the runtime bindings and the generated types — advertising a method
|
|
258
|
+
* the sandbox can't call would send the model down a dead end.
|
|
259
|
+
*/
|
|
260
|
+
#executableTools() {
|
|
261
|
+
const executable = {};
|
|
262
|
+
const skipped = [];
|
|
263
|
+
for (const [toolName, t] of Object.entries(this.#options.tools)) if ("execute" in t && typeof t.execute === "function") executable[toolName] = t;
|
|
264
|
+
else skipped.push(toolName);
|
|
265
|
+
if (skipped.length > 0 && !this.#warnedSkipped) {
|
|
266
|
+
this.#warnedSkipped = true;
|
|
267
|
+
console.warn(`[codemode] ToolSetConnector "${this.name()}" skipped tools without an execute function (client-side or provider-executed): ${skipped.join(", ")}. They are not callable from sandboxed code.`);
|
|
268
|
+
}
|
|
269
|
+
return executable;
|
|
270
|
+
}
|
|
271
|
+
name() {
|
|
272
|
+
return this.#options.name ?? "tools";
|
|
273
|
+
}
|
|
274
|
+
instructions() {
|
|
275
|
+
return this.#options.instructions;
|
|
276
|
+
}
|
|
277
|
+
tools() {
|
|
278
|
+
const out = {};
|
|
279
|
+
const sources = /* @__PURE__ */ new Map();
|
|
280
|
+
for (const [toolName, t] of Object.entries(this.#executableTools())) {
|
|
281
|
+
const execute = t.execute;
|
|
282
|
+
const name = sanitizeToolName(toolName);
|
|
283
|
+
const existing = sources.get(name);
|
|
284
|
+
if (existing !== void 0) throw new Error(`Tools "${existing}" and "${toolName}" on ${this.name()} both map to "${name}" — rename one of them.`);
|
|
285
|
+
sources.set(name, toolName);
|
|
286
|
+
const rawSchema = "inputSchema" in t ? t.inputSchema : t.parameters;
|
|
287
|
+
const schema = rawSchema != null ? asSchema(rawSchema) : void 0;
|
|
288
|
+
const needsApproval = t.needsApproval;
|
|
289
|
+
const requiresApproval = needsApproval !== void 0 && needsApproval !== false;
|
|
290
|
+
out[name] = {
|
|
291
|
+
description: t.description,
|
|
292
|
+
inputSchema: schema?.jsonSchema,
|
|
293
|
+
...requiresApproval ? { requiresApproval: true } : {},
|
|
294
|
+
execute: schema?.validate ? async (args) => {
|
|
295
|
+
const result = await schema.validate(args);
|
|
296
|
+
if (!result.success) throw result.error;
|
|
297
|
+
return execute(result.value);
|
|
298
|
+
} : (args) => execute(args)
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
return out;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Generate the sandbox type block from the original AI SDK schemas (Zod or
|
|
305
|
+
* `jsonSchema()` wrappers) rather than the converted JSON Schema, preserving
|
|
306
|
+
* field descriptions as `@param` lines. Restricted to the same executable
|
|
307
|
+
* subset that `tools()` exposes, so the types never advertise a method the
|
|
308
|
+
* sandbox can't call.
|
|
309
|
+
*/
|
|
310
|
+
async getTypeScriptTypes() {
|
|
311
|
+
return generateTypes(this.#executableTools(), this.name());
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
/** Convenience constructor mirroring `stateConnector` / `new BrowserConnector`. */
|
|
315
|
+
function toolSetConnector(ctx, options) {
|
|
316
|
+
return new ToolSetConnector(ctx, options);
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
export { ToolSetConnector, aiTools, createCodeTool, generateTypes, resolveProvider, toolSetConnector };
|
|
232
320
|
|
|
233
321
|
//# sourceMappingURL=ai.js.map
|
package/dist/ai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.js","names":[],"sources":["../src/tool-types.ts","../src/tool.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"],"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,SAAyC;CAErD;CAEA,OAAO;AACT;;;;;AAMA,SAAS,oBAAoB,QAAy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KAAK;EACrB,kBAAkB,KAAK;GAAE;GAAM,KAAK,WAAW,QAAQ;EAAE,CAAC;CAC5D;CAEA,MAAM,YAAY,WAAW,OAAO,OAAO,EAAE,KAAK,MAAM;CAExD,MAAM,WAAW,QAAQ;CAOzB,OAAO,KAAK;EACV,cANmB,QAAQ,eAAe,qBAAqB,QAC/D,aACA,SAIU;EACV,aAAa;EACb,SAAS,OAAO,EAAE,WAChB,QAAQ;GAAE;GAAM;GAAU,WAAW;EAAkB,CAAC;CAC5D,CAAC;AACH"}
|
|
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,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,UAC9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