@draht/codemode 2026.10.20-1 → 2026.10.23-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.
Files changed (54) hide show
  1. package/dist/cloudflare.d.ts +53 -0
  2. package/dist/cloudflare.d.ts.map +1 -0
  3. package/dist/cloudflare.js +64 -0
  4. package/dist/cloudflare.js.map +1 -0
  5. package/dist/declarations.d.ts +7 -17
  6. package/dist/declarations.d.ts.map +1 -1
  7. package/dist/declarations.js +115 -125
  8. package/dist/declarations.js.map +1 -1
  9. package/dist/index.d.ts +6 -3
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +5 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/portable.d.ts +15 -0
  14. package/dist/portable.d.ts.map +1 -0
  15. package/dist/portable.js +12 -0
  16. package/dist/portable.js.map +1 -0
  17. package/dist/runtime/execution.d.ts +68 -0
  18. package/dist/runtime/execution.d.ts.map +1 -0
  19. package/dist/runtime/execution.js +513 -0
  20. package/dist/runtime/execution.js.map +1 -0
  21. package/dist/runtime/host.d.ts +8 -31
  22. package/dist/runtime/host.d.ts.map +1 -1
  23. package/dist/runtime/host.js +52 -296
  24. package/dist/runtime/host.js.map +1 -1
  25. package/dist/runtime/inline.d.ts +63 -0
  26. package/dist/runtime/inline.d.ts.map +1 -0
  27. package/dist/runtime/inline.js +80 -0
  28. package/dist/runtime/inline.js.map +1 -0
  29. package/dist/runtime/prelude-source.d.ts +18 -4
  30. package/dist/runtime/prelude-source.d.ts.map +1 -1
  31. package/dist/runtime/prelude-source.js +202 -21
  32. package/dist/runtime/prelude-source.js.map +1 -1
  33. package/dist/runtime/protocol.d.ts +49 -6
  34. package/dist/runtime/protocol.d.ts.map +1 -1
  35. package/dist/runtime/protocol.js +6 -1
  36. package/dist/runtime/protocol.js.map +1 -1
  37. package/dist/runtime/remote.d.ts +102 -0
  38. package/dist/runtime/remote.d.ts.map +1 -0
  39. package/dist/runtime/remote.js +175 -0
  40. package/dist/runtime/remote.js.map +1 -0
  41. package/dist/runtime/vm.d.ts +24 -0
  42. package/dist/runtime/vm.d.ts.map +1 -0
  43. package/dist/runtime/vm.js +297 -0
  44. package/dist/runtime/vm.js.map +1 -0
  45. package/dist/runtime/worker.js +11 -110
  46. package/dist/runtime/worker.js.map +1 -1
  47. package/dist/source.d.ts +2 -1
  48. package/dist/source.d.ts.map +1 -1
  49. package/dist/source.js +8 -2
  50. package/dist/source.js.map +1 -1
  51. package/dist/types.d.ts +129 -15
  52. package/dist/types.d.ts.map +1 -1
  53. package/dist/types.js.map +1 -1
  54. package/package.json +16 -4
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Cloudflare Workers entry, for Workers built with Wrangler.
3
+ *
4
+ * Wrangler's default `CompiledWasm` rule turns the `.wasm` import below into a
5
+ * `WebAssembly.Module`; Workers cannot compile WebAssembly from bytes at runtime. Other bundlers
6
+ * do not support the import: use `@draht/codemode/portable` with your own module there.
7
+ *
8
+ * Two ways to run codemode on Cloudflare:
9
+ * - `RemoteCodemodeSandbox` with a {@link CodemodeSandboxDurableObject} deployed as its own
10
+ * Worker: scripts run in a separate isolate and never block the caller. Use this from a Durable
11
+ * Object that serves a session.
12
+ * - {@link createInlineCodemodeSandbox}: scripts run on the caller's thread. Simplest; a script
13
+ * that computes blocks the caller until it awaits a tool or uses up its interrupt budget.
14
+ */
15
+ import { DurableObject } from "cloudflare:workers";
16
+ import { InlineCodemodeSandbox, type InlineCodemodeSandboxOptions } from "./runtime/inline.ts";
17
+ import { type CodemodeRemoteExchange, type CodemodeRemoteRequest } from "./runtime/remote.ts";
18
+ import type { CodemodeWasmModule } from "./wasm.ts";
19
+ export * from "./portable.ts";
20
+ /** Default VM memory limit of {@link CodemodeSandboxDurableObject}. Isolates have 128 MB in total. */
21
+ export declare const DEFAULT_REMOTE_MEMORY_LIMIT_BYTES: number;
22
+ /** `quickjs-wasi/quickjs.wasm`, compiled by Wrangler. */
23
+ export declare const cloudflareQuickJSWasm: CodemodeWasmModule;
24
+ /** `InlineCodemodeSandbox` with the QuickJS module Wrangler bundled. */
25
+ export declare function createInlineCodemodeSandbox(options?: Omit<InlineCodemodeSandboxOptions, "wasm">): InlineCodemodeSandbox;
26
+ /**
27
+ * The remote end of `RemoteCodemodeSandbox`: a Durable Object whose one RPC method runs a script's
28
+ * VM and calls back into the client for every tool call.
29
+ *
30
+ * Deploy it as its own Worker and bind it from the Worker that runs your agent with `script_name`.
31
+ * A separate Worker is what keeps scripts off the agent's thread: a class in the same Worker can
32
+ * share an isolate, and therefore a thread, with the objects that call it.
33
+ *
34
+ * The object keeps no state between executions and never touches storage. Executions that reach
35
+ * the same instance share its thread: they interleave while they wait on tools, and a script that
36
+ * computes delays the others. Name instances per session (`getByName(sessionId)`) to keep one
37
+ * session's scripts together, or per execution for full independence.
38
+ *
39
+ * Limits apply to every request, whatever the client asks for. Override the fields in a subclass:
40
+ *
41
+ * export class CodemodeSandbox extends CodemodeSandboxDurableObject {
42
+ * protected maxInterruptBudget = 200_000;
43
+ * }
44
+ */
45
+ export declare class CodemodeSandboxDurableObject<Env = unknown> extends DurableObject<Env> {
46
+ /** Interrupt polls per execution; the client may only ask for less. See `InlineCodemodeSandboxOptions`. */
47
+ protected maxInterruptBudget: number;
48
+ /** VM memory per execution; the client may only ask for less. */
49
+ protected maxMemoryLimitBytes: number;
50
+ /** Called by `RemoteCodemodeSandbox` over RPC. Resolves when the script has settled or was stopped. */
51
+ execute(request: CodemodeRemoteRequest, exchange: CodemodeRemoteExchange): Promise<void>;
52
+ }
53
+ //# sourceMappingURL=cloudflare.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare.d.ts","sourceRoot":"","sources":["../src/cloudflare.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD,OAAO,EAEN,qBAAqB,EACrB,KAAK,4BAA4B,EACjC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,KAAK,sBAAsB,EAAE,KAAK,qBAAqB,EAAuB,MAAM,qBAAqB,CAAC;AACnH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAEpD,cAAc,eAAe,CAAC;AAM9B,sGAAsG;AACtG,eAAO,MAAM,iCAAiC,QAAmB,CAAC;AAElE,yDAAyD;AACzD,eAAO,MAAM,qBAAqB,EAAE,kBAAgC,CAAC;AAErE,wEAAwE;AACxE,wBAAgB,2BAA2B,CAAC,OAAO,GAAE,IAAI,CAAC,4BAA4B,EAAE,MAAM,CAAM,yBAEnG;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,4BAA4B,CAAC,GAAG,GAAG,OAAO,CAAE,SAAQ,aAAa,CAAC,GAAG,CAAC;IAClF,2GAA2G;IAC3G,SAAS,CAAC,kBAAkB,EAAE,MAAM,CAA4B;IAChE,iEAAiE;IACjE,SAAS,CAAC,mBAAmB,EAAE,MAAM,CAAqC;IAE1E,uGAAuG;IACvG,OAAO,CAAC,OAAO,EAAE,qBAAqB,EAAE,QAAQ,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC,CAMvF;CACD"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Cloudflare Workers entry, for Workers built with Wrangler.
3
+ *
4
+ * Wrangler's default `CompiledWasm` rule turns the `.wasm` import below into a
5
+ * `WebAssembly.Module`; Workers cannot compile WebAssembly from bytes at runtime. Other bundlers
6
+ * do not support the import: use `@draht/codemode/portable` with your own module there.
7
+ *
8
+ * Two ways to run codemode on Cloudflare:
9
+ * - `RemoteCodemodeSandbox` with a {@link CodemodeSandboxDurableObject} deployed as its own
10
+ * Worker: scripts run in a separate isolate and never block the caller. Use this from a Durable
11
+ * Object that serves a session.
12
+ * - {@link createInlineCodemodeSandbox}: scripts run on the caller's thread. Simplest; a script
13
+ * that computes blocks the caller until it awaits a tool or uses up its interrupt budget.
14
+ */
15
+ import { DurableObject } from "cloudflare:workers";
16
+ import quickjsWasmImport from "quickjs-wasi/quickjs.wasm";
17
+ import { DEFAULT_INTERRUPT_BUDGET, InlineCodemodeSandbox, } from "./runtime/inline.js";
18
+ import { serveCodemodeRemote } from "./runtime/remote.js";
19
+ export * from "./portable.js";
20
+ // Wrangler's `CompiledWasm` rule makes this a compiled module; the declaration cannot say so (see
21
+ // cloudflare-modules.d.ts).
22
+ const quickjsWasm = quickjsWasmImport;
23
+ /** Default VM memory limit of {@link CodemodeSandboxDurableObject}. Isolates have 128 MB in total. */
24
+ export const DEFAULT_REMOTE_MEMORY_LIMIT_BYTES = 32 * 1024 * 1024;
25
+ /** `quickjs-wasi/quickjs.wasm`, compiled by Wrangler. */
26
+ export const cloudflareQuickJSWasm = quickjsWasm;
27
+ /** `InlineCodemodeSandbox` with the QuickJS module Wrangler bundled. */
28
+ export function createInlineCodemodeSandbox(options = {}) {
29
+ return new InlineCodemodeSandbox({ ...options, wasm: quickjsWasm });
30
+ }
31
+ /**
32
+ * The remote end of `RemoteCodemodeSandbox`: a Durable Object whose one RPC method runs a script's
33
+ * VM and calls back into the client for every tool call.
34
+ *
35
+ * Deploy it as its own Worker and bind it from the Worker that runs your agent with `script_name`.
36
+ * A separate Worker is what keeps scripts off the agent's thread: a class in the same Worker can
37
+ * share an isolate, and therefore a thread, with the objects that call it.
38
+ *
39
+ * The object keeps no state between executions and never touches storage. Executions that reach
40
+ * the same instance share its thread: they interleave while they wait on tools, and a script that
41
+ * computes delays the others. Name instances per session (`getByName(sessionId)`) to keep one
42
+ * session's scripts together, or per execution for full independence.
43
+ *
44
+ * Limits apply to every request, whatever the client asks for. Override the fields in a subclass:
45
+ *
46
+ * export class CodemodeSandbox extends CodemodeSandboxDurableObject {
47
+ * protected maxInterruptBudget = 200_000;
48
+ * }
49
+ */
50
+ export class CodemodeSandboxDurableObject extends DurableObject {
51
+ /** Interrupt polls per execution; the client may only ask for less. See `InlineCodemodeSandboxOptions`. */
52
+ maxInterruptBudget = DEFAULT_INTERRUPT_BUDGET;
53
+ /** VM memory per execution; the client may only ask for less. */
54
+ maxMemoryLimitBytes = DEFAULT_REMOTE_MEMORY_LIMIT_BYTES;
55
+ /** Called by `RemoteCodemodeSandbox` over RPC. Resolves when the script has settled or was stopped. */
56
+ execute(request, exchange) {
57
+ return serveCodemodeRemote(request, exchange, {
58
+ wasm: quickjsWasm,
59
+ maxInterruptBudget: this.maxInterruptBudget,
60
+ maxMemoryLimitBytes: this.maxMemoryLimitBytes,
61
+ });
62
+ }
63
+ }
64
+ //# sourceMappingURL=cloudflare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare.js","sourceRoot":"","sources":["../src/cloudflare.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,iBAAiB,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EACN,wBAAwB,EACxB,qBAAqB,GAErB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAA2D,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAGnH,cAAc,eAAe,CAAC;AAE9B,kGAAkG;AAClG,4BAA4B;AAC5B,MAAM,WAAW,GAAG,iBAAkD,CAAC;AAEvE,sGAAsG;AACtG,MAAM,CAAC,MAAM,iCAAiC,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAElE,yDAAyD;AACzD,MAAM,CAAC,MAAM,qBAAqB,GAAuB,WAAW,CAAC;AAErE,wEAAwE;AACxE,MAAM,UAAU,2BAA2B,CAAC,OAAO,GAA+C,EAAE;IACnG,OAAO,IAAI,qBAAqB,CAAC,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;AACrE,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,OAAO,4BAA4C,SAAQ,aAAkB;IAClF,2GAA2G;IACjG,kBAAkB,GAAW,wBAAwB,CAAC;IAChE,iEAAiE;IACvD,mBAAmB,GAAW,iCAAiC,CAAC;IAE1E,uGAAuG;IACvG,OAAO,CAAC,OAA8B,EAAE,QAAgC;QACvE,OAAO,mBAAmB,CAAC,OAAO,EAAE,QAAQ,EAAE;YAC7C,IAAI,EAAE,WAAW;YACjB,kBAAkB,EAAE,IAAI,CAAC,kBAAkB;YAC3C,mBAAmB,EAAE,IAAI,CAAC,mBAAmB;SAC7C,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["/**\n * Cloudflare Workers entry, for Workers built with Wrangler.\n *\n * Wrangler's default `CompiledWasm` rule turns the `.wasm` import below into a\n * `WebAssembly.Module`; Workers cannot compile WebAssembly from bytes at runtime. Other bundlers\n * do not support the import: use `@draht/codemode/portable` with your own module there.\n *\n * Two ways to run codemode on Cloudflare:\n * - `RemoteCodemodeSandbox` with a {@link CodemodeSandboxDurableObject} deployed as its own\n * Worker: scripts run in a separate isolate and never block the caller. Use this from a Durable\n * Object that serves a session.\n * - {@link createInlineCodemodeSandbox}: scripts run on the caller's thread. Simplest; a script\n * that computes blocks the caller until it awaits a tool or uses up its interrupt budget.\n */\nimport { DurableObject } from \"cloudflare:workers\";\nimport quickjsWasmImport from \"quickjs-wasi/quickjs.wasm\";\nimport {\n\tDEFAULT_INTERRUPT_BUDGET,\n\tInlineCodemodeSandbox,\n\ttype InlineCodemodeSandboxOptions,\n} from \"./runtime/inline.ts\";\nimport { type CodemodeRemoteExchange, type CodemodeRemoteRequest, serveCodemodeRemote } from \"./runtime/remote.ts\";\nimport type { CodemodeWasmModule } from \"./wasm.ts\";\n\nexport * from \"./portable.ts\";\n\n// Wrangler's `CompiledWasm` rule makes this a compiled module; the declaration cannot say so (see\n// cloudflare-modules.d.ts).\nconst quickjsWasm = quickjsWasmImport as unknown as CodemodeWasmModule;\n\n/** Default VM memory limit of {@link CodemodeSandboxDurableObject}. Isolates have 128 MB in total. */\nexport const DEFAULT_REMOTE_MEMORY_LIMIT_BYTES = 32 * 1024 * 1024;\n\n/** `quickjs-wasi/quickjs.wasm`, compiled by Wrangler. */\nexport const cloudflareQuickJSWasm: CodemodeWasmModule = quickjsWasm;\n\n/** `InlineCodemodeSandbox` with the QuickJS module Wrangler bundled. */\nexport function createInlineCodemodeSandbox(options: Omit<InlineCodemodeSandboxOptions, \"wasm\"> = {}) {\n\treturn new InlineCodemodeSandbox({ ...options, wasm: quickjsWasm });\n}\n\n/**\n * The remote end of `RemoteCodemodeSandbox`: a Durable Object whose one RPC method runs a script's\n * VM and calls back into the client for every tool call.\n *\n * Deploy it as its own Worker and bind it from the Worker that runs your agent with `script_name`.\n * A separate Worker is what keeps scripts off the agent's thread: a class in the same Worker can\n * share an isolate, and therefore a thread, with the objects that call it.\n *\n * The object keeps no state between executions and never touches storage. Executions that reach\n * the same instance share its thread: they interleave while they wait on tools, and a script that\n * computes delays the others. Name instances per session (`getByName(sessionId)`) to keep one\n * session's scripts together, or per execution for full independence.\n *\n * Limits apply to every request, whatever the client asks for. Override the fields in a subclass:\n *\n * export class CodemodeSandbox extends CodemodeSandboxDurableObject {\n * protected maxInterruptBudget = 200_000;\n * }\n */\nexport class CodemodeSandboxDurableObject<Env = unknown> extends DurableObject<Env> {\n\t/** Interrupt polls per execution; the client may only ask for less. See `InlineCodemodeSandboxOptions`. */\n\tprotected maxInterruptBudget: number = DEFAULT_INTERRUPT_BUDGET;\n\t/** VM memory per execution; the client may only ask for less. */\n\tprotected maxMemoryLimitBytes: number = DEFAULT_REMOTE_MEMORY_LIMIT_BYTES;\n\n\t/** Called by `RemoteCodemodeSandbox` over RPC. Resolves when the script has settled or was stopped. */\n\texecute(request: CodemodeRemoteRequest, exchange: CodemodeRemoteExchange): Promise<void> {\n\t\treturn serveCodemodeRemote(request, exchange, {\n\t\t\twasm: quickjsWasm,\n\t\t\tmaxInterruptBudget: this.maxInterruptBudget,\n\t\t\tmaxMemoryLimitBytes: this.maxMemoryLimitBytes,\n\t\t});\n\t}\n}\n"]}
@@ -3,11 +3,6 @@ export { toCodemodeIdentifier };
3
3
  import type { CodemodeJsonSchema, CodemodeTool } from "./types.ts";
4
4
  /** Largest rendered input type, in characters, before it becomes `unknown`. */
5
5
  export declare const DEFAULT_INPUT_SCHEMA_MAX_CHARS = 16000;
6
- /**
7
- * TypeScript types for MCP results, from the MCP `CallToolResult` schema, so `CallToolResult<T>`
8
- * declarations can refer to them.
9
- */
10
- export declare const MCP_TYPESCRIPT_PREAMBLE = "type Role = \"user\" | \"assistant\";\ntype MetaObject = Record<string, unknown>;\ntype Annotations = {\n audience?: Role[];\n priority?: number;\n lastModified?: string;\n};\ntype Icon = {\n src: string;\n mimeType?: string;\n sizes?: string[];\n theme?: \"light\" | \"dark\";\n};\ntype TextResourceContents = {\n uri: string;\n mimeType?: string;\n _meta?: MetaObject;\n text: string;\n};\ntype BlobResourceContents = {\n uri: string;\n mimeType?: string;\n _meta?: MetaObject;\n blob: string;\n};\ntype TextContent = {\n type: \"text\";\n text: string;\n annotations?: Annotations;\n _meta?: MetaObject;\n};\ntype ImageContent = {\n type: \"image\";\n data: string;\n mimeType: string;\n annotations?: Annotations;\n _meta?: MetaObject;\n};\ntype AudioContent = {\n type: \"audio\";\n data: string;\n mimeType: string;\n annotations?: Annotations;\n _meta?: MetaObject;\n};\ntype ResourceLink = {\n icons?: Icon[];\n name: string;\n title?: string;\n uri: string;\n description?: string;\n mimeType?: string;\n annotations?: Annotations;\n size?: number;\n _meta?: MetaObject;\n type: \"resource_link\";\n};\ntype EmbeddedResource = {\n type: \"resource\";\n resource: TextResourceContents | BlobResourceContents;\n annotations?: Annotations;\n _meta?: MetaObject;\n};\ntype ContentBlock =\n | TextContent\n | ImageContent\n | AudioContent\n | ResourceLink\n | EmbeddedResource;\ntype CallToolResult<TStructured = { [key: string]: unknown }> = {\n _meta?: MetaObject;\n content: ContentBlock[];\n isError?: boolean;\n structuredContent?: TStructured;\n [key: string]: unknown;\n};";
11
6
  export interface RenderDeclarationsOptions {
12
7
  tools?: readonly CodemodeTool[];
13
8
  globals?: readonly CodemodeTool[];
@@ -21,8 +16,6 @@ export declare function renderDeclarations(options: RenderDeclarationsOptions):
21
16
  /**
22
17
  * One tool as a member of the `tools` object: `name(args: T): Promise<R>;` with the
23
18
  * name as the identifier scripts use. Input types longer than `inputMaxChars` render as `unknown`.
24
- * Tools whose output schema is an MCP `CallToolResult` render as `Promise<CallToolResult<T>>`,
25
- * which needs {@link MCP_TYPESCRIPT_PREAMBLE}.
26
19
  */
27
20
  export declare function renderToolSignature(tool: Pick<CodemodeTool, "name" | "inputSchema" | "outputSchema">, options?: {
28
21
  inputMaxChars?: number;
@@ -34,18 +27,15 @@ export declare function renderToolSignature(tool: Pick<CodemodeTool, "name" | "i
34
27
  export declare function renderToolSample(tool: Pick<CodemodeTool, "name" | "description" | "inputSchema" | "outputSchema">, options?: {
35
28
  inputMaxChars?: number;
36
29
  }): string;
37
- /**
38
- * The `structuredContent` schema of an MCP `CallToolResult` output schema (detected by a
39
- * `content` array of objects, boolean `isError`, and object `_meta`), `true` when it declares none, or
40
- * `undefined` when the schema is not a `CallToolResult`.
41
- */
42
- export declare function mcpStructuredContentSchema(schema: CodemodeJsonSchema | undefined): CodemodeJsonSchema | undefined;
30
+ /** The type a tool call resolves to: the output schema's type, and `unknown` without a schema. */
31
+ export declare function renderToolOutputType(schema: CodemodeJsonSchema | undefined): string;
43
32
  /**
44
33
  * Convert a JSON Schema to a TypeScript type expression: objects on one line (`{ a: string; b?: number; }`) with properties sorted by name,
45
- * or one property per line with `//` comments when a property has a description; `Array<T>` for
46
- * arrays. Local references (`#/$defs/...`, `#/definitions/...`) resolve against `schema`;
47
- * recursive and remote references render as `unknown`. A result longer than `maxChars` renders as
48
- * `unknown`.
34
+ * or one property per line with `//` comments when a property has a description or constraints the
35
+ * type cannot express (`// @integer @minimum 1 @default 20`); `Array<T>` for arrays. Local references
36
+ * (`#/$defs/...`, `#/definitions/...`) resolve against `schema`; recursive and remote references
37
+ * render as `unknown`. A result longer than `maxChars` is rendered again without the constraint tags,
38
+ * and renders as `unknown` if it is still too long.
49
39
  */
50
40
  export declare function schemaToType(schema: CodemodeJsonSchema, options?: {
51
41
  maxChars?: number;
@@ -1 +1 @@
1
- {"version":3,"file":"declarations.d.ts","sourceRoot":"","sources":["../src/declarations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAEvD,OAAO,EAAE,oBAAoB,EAAE,CAAC;AAEhC,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAInE,+EAA+E;AAC/E,eAAO,MAAM,8BAA8B,QAAS,CAAC;AAIrD;;;GAGG;AACH,eAAO,MAAM,uBAAuB,ymDA2EjC,CAAC;AAEJ,MAAM,WAAW,yBAAyB;IACzC,KAAK,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;IAChC,OAAO,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;CAClC;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,yBAAyB,GAAG,MAAM,CAyB7E;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAClC,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,aAAa,GAAG,cAAc,CAAC,EACjE,OAAO,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,GACtC,MAAM,CAMR;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC/B,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,aAAa,GAAG,aAAa,GAAG,cAAc,CAAC,EACjF,OAAO,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,GACtC,MAAM,CAGR;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,kBAAkB,GAAG,SAAS,GAAG,kBAAkB,GAAG,SAAS,CASjH;AA0CD;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,kBAAkB,EAAE,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,MAAM,CAGpG"}
1
+ {"version":3,"file":"declarations.d.ts","sourceRoot":"","sources":["../src/declarations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAEvD,OAAO,EAAE,oBAAoB,EAAE,CAAC;AAEhC,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAInE,+EAA+E;AAC/E,eAAO,MAAM,8BAA8B,QAAS,CAAC;AAyBrD,MAAM,WAAW,yBAAyB;IACzC,KAAK,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;IAChC,OAAO,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;CAClC;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,yBAAyB,GAAG,MAAM,CAyB7E;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAClC,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,aAAa,GAAG,cAAc,CAAC,EACjE,OAAO,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,GACtC,MAAM,CAMR;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC/B,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,aAAa,GAAG,aAAa,GAAG,cAAc,CAAC,EACjF,OAAO,GAAE;IAAE,aAAa,CAAC,EAAE,MAAM,CAAA;CAAO,GACtC,MAAM,CAGR;AAED,kGAAkG;AAClG,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,kBAAkB,GAAG,SAAS,GAAG,MAAM,CAEnF;AA6BD;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,kBAAkB,EAAE,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,MAAM,CAMpG"}
@@ -6,86 +6,27 @@ const INDENT = " ";
6
6
  export const DEFAULT_INPUT_SCHEMA_MAX_CHARS = 16_000;
7
7
  /** Local `$ref` expansions per rendered schema, so shared definitions cannot blow up the output. */
8
8
  const MAX_REF_EXPANSIONS = 32;
9
- /**
10
- * TypeScript types for MCP results, from the MCP `CallToolResult` schema, so `CallToolResult<T>`
11
- * declarations can refer to them.
12
- */
13
- export const MCP_TYPESCRIPT_PREAMBLE = `type Role = "user" | "assistant";
14
- type MetaObject = Record<string, unknown>;
15
- type Annotations = {
16
- audience?: Role[];
17
- priority?: number;
18
- lastModified?: string;
19
- };
20
- type Icon = {
21
- src: string;
22
- mimeType?: string;
23
- sizes?: string[];
24
- theme?: "light" | "dark";
25
- };
26
- type TextResourceContents = {
27
- uri: string;
28
- mimeType?: string;
29
- _meta?: MetaObject;
30
- text: string;
31
- };
32
- type BlobResourceContents = {
33
- uri: string;
34
- mimeType?: string;
35
- _meta?: MetaObject;
36
- blob: string;
37
- };
38
- type TextContent = {
39
- type: "text";
40
- text: string;
41
- annotations?: Annotations;
42
- _meta?: MetaObject;
43
- };
44
- type ImageContent = {
45
- type: "image";
46
- data: string;
47
- mimeType: string;
48
- annotations?: Annotations;
49
- _meta?: MetaObject;
50
- };
51
- type AudioContent = {
52
- type: "audio";
53
- data: string;
54
- mimeType: string;
55
- annotations?: Annotations;
56
- _meta?: MetaObject;
57
- };
58
- type ResourceLink = {
59
- icons?: Icon[];
60
- name: string;
61
- title?: string;
62
- uri: string;
63
- description?: string;
64
- mimeType?: string;
65
- annotations?: Annotations;
66
- size?: number;
67
- _meta?: MetaObject;
68
- type: "resource_link";
69
- };
70
- type EmbeddedResource = {
71
- type: "resource";
72
- resource: TextResourceContents | BlobResourceContents;
73
- annotations?: Annotations;
74
- _meta?: MetaObject;
75
- };
76
- type ContentBlock =
77
- | TextContent
78
- | ImageContent
79
- | AudioContent
80
- | ResourceLink
81
- | EmbeddedResource;
82
- type CallToolResult<TStructured = { [key: string]: unknown }> = {
83
- _meta?: MetaObject;
84
- content: ContentBlock[];
85
- isError?: boolean;
86
- structuredContent?: TStructured;
87
- [key: string]: unknown;
88
- };`;
9
+ /** JSON Schema keywords with a number or string value shown as `@keyword value` property tags. */
10
+ const TAG_KEYWORDS = [
11
+ "minimum",
12
+ "exclusiveMinimum",
13
+ "maximum",
14
+ "exclusiveMaximum",
15
+ "multipleOf",
16
+ "minLength",
17
+ "maxLength",
18
+ "pattern",
19
+ "format",
20
+ "minItems",
21
+ "maxItems",
22
+ ];
23
+ /** Tag keywords whose values all hold at once, so only the largest (lower) or smallest (upper) matters. */
24
+ const LOWER_BOUNDS = new Set(["minimum", "exclusiveMinimum", "minLength", "minItems"]);
25
+ const UPPER_BOUNDS = new Set(["maximum", "exclusiveMaximum", "maxLength", "maxItems"]);
26
+ /** Longest property tag; longer ones (large defaults, long patterns) are left out. */
27
+ const MAX_TAG_CHARS = 80;
28
+ /** Characters that end a `//` comment. */
29
+ const LINE_TERMINATORS = /[\r\n\u2028\u2029]/g;
89
30
  /**
90
31
  * Render TypeScript declarations for the script-visible API. Tools become members of
91
32
  * `declare const tools`, globals become `declare function` statements, and `ns.member` globals
@@ -119,14 +60,12 @@ export function renderDeclarations(options) {
119
60
  /**
120
61
  * One tool as a member of the `tools` object: `name(args: T): Promise<R>;` with the
121
62
  * name as the identifier scripts use. Input types longer than `inputMaxChars` render as `unknown`.
122
- * Tools whose output schema is an MCP `CallToolResult` render as `Promise<CallToolResult<T>>`,
123
- * which needs {@link MCP_TYPESCRIPT_PREAMBLE}.
124
63
  */
125
64
  export function renderToolSignature(tool, options = {}) {
126
65
  const input = tool.inputSchema === undefined
127
66
  ? "unknown"
128
67
  : schemaToType(tool.inputSchema, { maxChars: options.inputMaxChars ?? DEFAULT_INPUT_SCHEMA_MAX_CHARS });
129
- return `${toCodemodeIdentifier(tool.name)}(args: ${input}): Promise<${outputType(tool.outputSchema)}>;`;
68
+ return `${toCodemodeIdentifier(tool.name)}(args: ${input}): Promise<${renderToolOutputType(tool.outputSchema)}>;`;
130
69
  }
131
70
  /**
132
71
  * A tool's sample: the description followed by the tool's declaration. Used for tool
@@ -136,28 +75,8 @@ export function renderToolSample(tool, options = {}) {
136
75
  const declaration = `declare const tools: { ${renderToolSignature(tool, options)} };`;
137
76
  return `${tool.description?.trim() ?? ""}\n\ncodemode tool declaration:\n\`\`\`ts\n${declaration}\n\`\`\``;
138
77
  }
139
- /**
140
- * The `structuredContent` schema of an MCP `CallToolResult` output schema (detected by a
141
- * `content` array of objects, boolean `isError`, and object `_meta`), `true` when it declares none, or
142
- * `undefined` when the schema is not a `CallToolResult`.
143
- */
144
- export function mcpStructuredContentSchema(schema) {
145
- if (!isObject(schema) || !isObject(schema.properties))
146
- return undefined;
147
- const { content, isError, _meta, structuredContent } = schema.properties;
148
- if (!isObject(content) || content.type !== "array" || !isObject(content.items) || content.items.type !== "object") {
149
- return undefined;
150
- }
151
- if (!isObject(isError) || isError.type !== "boolean" || !isObject(_meta) || _meta.type !== "object")
152
- return undefined;
153
- return isObject(structuredContent) || typeof structuredContent === "boolean" ? structuredContent : true;
154
- }
155
- function outputType(schema) {
156
- const structured = mcpStructuredContentSchema(schema);
157
- if (structured !== undefined) {
158
- const type = schemaToType(structured);
159
- return type === "unknown" ? "CallToolResult" : `CallToolResult<${type}>`;
160
- }
78
+ /** The type a tool call resolves to: the output schema's type, and `unknown` without a schema. */
79
+ export function renderToolOutputType(schema) {
161
80
  return schema === undefined ? "unknown" : schemaToType(schema);
162
81
  }
163
82
  function renderGlobal(head, global, indent) {
@@ -180,9 +99,6 @@ function docComment(description, indent) {
180
99
  function propertyKey(name) {
181
100
  return IDENTIFIER.test(name) ? name : JSON.stringify(name);
182
101
  }
183
- function isObject(value) {
184
- return typeof value === "object" && value !== null && !Array.isArray(value);
185
- }
186
102
  function union(types) {
187
103
  const unique = [...new Set(types)];
188
104
  if (unique.includes("unknown"))
@@ -191,14 +107,19 @@ function union(types) {
191
107
  }
192
108
  /**
193
109
  * Convert a JSON Schema to a TypeScript type expression: objects on one line (`{ a: string; b?: number; }`) with properties sorted by name,
194
- * or one property per line with `//` comments when a property has a description; `Array<T>` for
195
- * arrays. Local references (`#/$defs/...`, `#/definitions/...`) resolve against `schema`;
196
- * recursive and remote references render as `unknown`. A result longer than `maxChars` renders as
197
- * `unknown`.
110
+ * or one property per line with `//` comments when a property has a description or constraints the
111
+ * type cannot express (`// @integer @minimum 1 @default 20`); `Array<T>` for arrays. Local references
112
+ * (`#/$defs/...`, `#/definitions/...`) resolve against `schema`; recursive and remote references
113
+ * render as `unknown`. A result longer than `maxChars` is rendered again without the constraint tags,
114
+ * and renders as `unknown` if it is still too long.
198
115
  */
199
116
  export function schemaToType(schema, options = {}) {
200
- const type = toType(schema, { root: schema, resolving: new Set(), expansions: 0 });
201
- return options.maxChars !== undefined && type.length > options.maxChars ? "unknown" : type;
117
+ const render = (tags) => toType(schema, { root: schema, resolving: new Set(), expansions: 0, tags });
118
+ const type = render(true);
119
+ if (options.maxChars === undefined || type.length <= options.maxChars)
120
+ return type;
121
+ const untagged = render(false);
122
+ return untagged.length <= options.maxChars ? untagged : "unknown";
202
123
  }
203
124
  function resolveRef(ref, root) {
204
125
  if (ref !== "#" && !ref.startsWith("#/"))
@@ -206,18 +127,23 @@ function resolveRef(ref, root) {
206
127
  let current = root;
207
128
  for (const segment of ref.slice(2).split("/").filter(Boolean)) {
208
129
  const key = decodeURIComponent(segment).replaceAll("~1", "/").replaceAll("~0", "~");
209
- if (!isObject(current) || !(key in current))
130
+ if (typeof current !== "object" || current === null || Array.isArray(current) || !(key in current)) {
210
131
  return undefined;
132
+ }
211
133
  current = current[key];
212
134
  }
213
- return typeof current === "boolean" || isObject(current) ? current : undefined;
135
+ if (typeof current === "boolean")
136
+ return current;
137
+ return typeof current === "object" && current !== null && !Array.isArray(current)
138
+ ? current
139
+ : undefined;
214
140
  }
215
141
  function toType(schema, context) {
216
142
  if (schema === true)
217
143
  return "unknown";
218
144
  if (schema === false)
219
145
  return "never";
220
- if (!isObject(schema))
146
+ if (typeof schema !== "object" || schema === null || Array.isArray(schema))
221
147
  return "unknown";
222
148
  if (typeof schema.$ref === "string") {
223
149
  const ref = schema.$ref;
@@ -292,10 +218,68 @@ function arrayType(schema, context) {
292
218
  return "unknown[]";
293
219
  }
294
220
  function descriptionOf(property) {
295
- return isObject(property) && typeof property.description === "string" ? property.description.trim() : "";
221
+ const description = property?.description;
222
+ return typeof description === "string" ? description.trim() : "";
223
+ }
224
+ /**
225
+ * Constraints of a property that its TypeScript type cannot express, as JSDoc-style tags:
226
+ * `@integer @minimum 1 @maximum 100 @default 20`. Empty when there are none.
227
+ */
228
+ function constraintTags(schema) {
229
+ if (typeof schema !== "object" || schema === null || Array.isArray(schema))
230
+ return "";
231
+ const property = schema;
232
+ // Optional fields such as Pydantic's `int | None` keep their constraints in the non-null branch.
233
+ // The branch's constraints apply together with the property's, so both are read.
234
+ const variants = Array.isArray(property.anyOf) ? property.anyOf : property.oneOf;
235
+ const nonNull = Array.isArray(variants)
236
+ ? variants.filter((variant) => variant?.type !== "null")
237
+ : [];
238
+ const branch = nonNull.length === 1 ? nonNull[0] : undefined;
239
+ const branches = typeof branch === "object" && branch !== null && !Array.isArray(branch)
240
+ ? [property, branch]
241
+ : [property];
242
+ // Draft-04 and OpenAPI 3.0 make `minimum`/`maximum` exclusive with a boolean `exclusiveMinimum`/`exclusiveMaximum`.
243
+ const schemas = branches.map((schema) => ({
244
+ ...schema,
245
+ ...(schema.exclusiveMinimum === true ? { minimum: undefined, exclusiveMinimum: schema.minimum } : {}),
246
+ ...(schema.exclusiveMaximum === true ? { maximum: undefined, exclusiveMaximum: schema.maximum } : {}),
247
+ }));
248
+ const tags = [];
249
+ const isInteger = (type) => type === "integer" || (Array.isArray(type) && type.includes("integer"));
250
+ if (schemas.some((schema) => isInteger(schema.type)))
251
+ tags.push("@integer");
252
+ for (const keyword of TAG_KEYWORDS) {
253
+ const values = schemas.map((schema) => schema[keyword]);
254
+ if (LOWER_BOUNDS.has(keyword) || UPPER_BOUNDS.has(keyword)) {
255
+ const numbers = values.filter((value) => typeof value === "number");
256
+ if (numbers.length === 0)
257
+ continue;
258
+ tags.push(`@${keyword} ${LOWER_BOUNDS.has(keyword) ? Math.max(...numbers) : Math.min(...numbers)}`);
259
+ continue;
260
+ }
261
+ for (const value of new Set(values)) {
262
+ if (typeof value === "number" || typeof value === "string")
263
+ tags.push(`@${keyword} ${value}`);
264
+ }
265
+ }
266
+ if (schemas.some((schema) => schema.uniqueItems === true))
267
+ tags.push("@uniqueItems");
268
+ // Annotations, unlike constraints, come from the property itself.
269
+ if (property.default !== undefined && property.default !== null) {
270
+ tags.push(`@default ${JSON.stringify(property.default)}`);
271
+ }
272
+ if (property.deprecated === true)
273
+ tags.push("@deprecated");
274
+ return tags
275
+ .filter((tag) => tag.length <= MAX_TAG_CHARS)
276
+ .map((tag) => tag.replace(LINE_TERMINATORS, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`))
277
+ .join(" ");
296
278
  }
297
279
  function objectType(schema, context) {
298
- const properties = isObject(schema.properties) ? schema.properties : {};
280
+ const properties = typeof schema.properties === "object" && schema.properties !== null && !Array.isArray(schema.properties)
281
+ ? schema.properties
282
+ : {};
299
283
  const required = new Set(Array.isArray(schema.required) ? schema.required : []);
300
284
  const names = Object.keys(properties).sort();
301
285
  const members = names.map((name) => {
@@ -312,14 +296,20 @@ function objectType(schema, context) {
312
296
  }
313
297
  if (members.length === 0)
314
298
  return "{}";
315
- if (!names.some((name) => descriptionOf(properties[name])))
299
+ const comments = names.map((name) => {
300
+ const lines = descriptionOf(properties[name])
301
+ .split(LINE_TERMINATORS)
302
+ .map((line) => line.trim())
303
+ .filter(Boolean);
304
+ const tags = context.tags ? constraintTags(properties[name]) : "";
305
+ return tags ? [...lines, tags] : lines;
306
+ });
307
+ if (!comments.some((comment) => comment.length > 0))
316
308
  return `{ ${members.join(" ")} }`;
317
309
  const lines = ["{"];
318
- names.forEach((name, index) => {
319
- for (const line of descriptionOf(properties[name]).split(/\r?\n/)) {
320
- if (line.trim())
321
- lines.push(`${INDENT}// ${line.trim()}`);
322
- }
310
+ comments.forEach((comment, index) => {
311
+ for (const line of comment)
312
+ lines.push(`${INDENT}// ${line}`);
323
313
  lines.push(`${INDENT}${members[index].replaceAll("\n", `\n${INDENT}`)}`);
324
314
  });
325
315
  for (const member of members.slice(names.length))