agents 0.0.0-2f82f51 → 0.0.0-328cf82

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 (70) hide show
  1. package/README.md +255 -27
  2. package/dist/ai-chat-agent.d.ts +59 -10
  3. package/dist/ai-chat-agent.js +532 -159
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration-gdyLiTd8.js +155 -0
  6. package/dist/ai-chat-v5-migration-gdyLiTd8.js.map +1 -0
  7. package/dist/ai-chat-v5-migration.d.ts +155 -0
  8. package/dist/ai-chat-v5-migration.js +3 -0
  9. package/dist/ai-react.d.ts +73 -72
  10. package/dist/ai-react.js +261 -185
  11. package/dist/ai-react.js.map +1 -1
  12. package/dist/ai-types-BWW4umHY.d.ts +95 -0
  13. package/dist/ai-types-UZlfLOYP.js +20 -0
  14. package/dist/ai-types-UZlfLOYP.js.map +1 -0
  15. package/dist/ai-types.d.ts +6 -69
  16. package/dist/ai-types.js +3 -1
  17. package/dist/client-CZBVDDoO.js +786 -0
  18. package/dist/client-CZBVDDoO.js.map +1 -0
  19. package/dist/client-CmMi85Sj.d.ts +104 -0
  20. package/dist/client-CrWcaPgn.d.ts +5313 -0
  21. package/dist/client-DjR-lC16.js +117 -0
  22. package/dist/client-DjR-lC16.js.map +1 -0
  23. package/dist/client.d.ts +12 -79
  24. package/dist/client.js +3 -137
  25. package/dist/codemode/ai.d.ts +27 -0
  26. package/dist/codemode/ai.js +151 -0
  27. package/dist/codemode/ai.js.map +1 -0
  28. package/dist/do-oauth-client-provider-B2jr6UNq.js +93 -0
  29. package/dist/do-oauth-client-provider-B2jr6UNq.js.map +1 -0
  30. package/dist/do-oauth-client-provider-CCwGwnrA.d.ts +55 -0
  31. package/dist/index-C8tKy5Ek.d.ts +736 -0
  32. package/dist/index-W4JUkafc.d.ts +54 -0
  33. package/dist/index.d.ts +77 -295
  34. package/dist/index.js +7 -20
  35. package/dist/mcp/client.d.ts +4 -0
  36. package/dist/mcp/client.js +3 -0
  37. package/dist/mcp/do-oauth-client-provider.d.ts +2 -0
  38. package/dist/mcp/do-oauth-client-provider.js +3 -0
  39. package/dist/mcp/index.d.ts +7 -0
  40. package/dist/mcp/index.js +7 -0
  41. package/dist/mcp/x402.d.ts +34 -0
  42. package/dist/mcp/x402.js +194 -0
  43. package/dist/mcp/x402.js.map +1 -0
  44. package/dist/mcp-BEwaCsxO.d.ts +61 -0
  45. package/dist/observability/index.d.ts +3 -0
  46. package/dist/observability/index.js +7 -0
  47. package/dist/react-CY7QkxbG.d.ts +113 -0
  48. package/dist/react.d.ts +10 -39
  49. package/dist/react.js +185 -93
  50. package/dist/react.js.map +1 -1
  51. package/dist/schedule.d.ts +89 -12
  52. package/dist/schedule.js +46 -23
  53. package/dist/schedule.js.map +1 -1
  54. package/dist/serializable-gtr9YMhp.d.ts +34 -0
  55. package/dist/serializable.d.ts +7 -0
  56. package/dist/serializable.js +1 -0
  57. package/dist/src-tpG9NtHy.js +2457 -0
  58. package/dist/src-tpG9NtHy.js.map +1 -0
  59. package/package.json +117 -50
  60. package/dist/ai-types.js.map +0 -1
  61. package/dist/chunk-HMLY7DHA.js +0 -16
  62. package/dist/chunk-HMLY7DHA.js.map +0 -1
  63. package/dist/chunk-X6BBKLSC.js +0 -568
  64. package/dist/chunk-X6BBKLSC.js.map +0 -1
  65. package/dist/client.js.map +0 -1
  66. package/dist/index.js.map +0 -1
  67. package/dist/mcp.d.ts +0 -58
  68. package/dist/mcp.js +0 -945
  69. package/dist/mcp.js.map +0 -1
  70. package/src/index.ts +0 -888
@@ -0,0 +1,117 @@
1
+ import { MessageType } from "./ai-types-UZlfLOYP.js";
2
+ import { PartySocket } from "partysocket";
3
+
4
+ //#region src/client.ts
5
+ /**
6
+ * Convert a camelCase string to a kebab-case string
7
+ * @param str The string to convert
8
+ * @returns The kebab-case string
9
+ */
10
+ function camelCaseToKebabCase(str) {
11
+ if (str === str.toUpperCase() && str !== str.toLowerCase()) return str.toLowerCase().replace(/_/g, "-");
12
+ let kebabified = str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
13
+ kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
14
+ return kebabified.replace(/_/g, "-").replace(/-$/, "");
15
+ }
16
+ /**
17
+ * WebSocket client for connecting to an Agent
18
+ */
19
+ var AgentClient = class extends PartySocket {
20
+ /**
21
+ * @deprecated Use agentFetch instead
22
+ */
23
+ static fetch(_opts) {
24
+ throw new Error("AgentClient.fetch is not implemented, use agentFetch instead");
25
+ }
26
+ constructor(options) {
27
+ const agentNamespace = camelCaseToKebabCase(options.agent);
28
+ super({
29
+ party: agentNamespace,
30
+ prefix: "agents",
31
+ room: options.name || "default",
32
+ ...options
33
+ });
34
+ this._pendingCalls = /* @__PURE__ */ new Map();
35
+ this.agent = agentNamespace;
36
+ this.name = options.name || "default";
37
+ this.options = options;
38
+ this.addEventListener("message", (event) => {
39
+ if (typeof event.data === "string") {
40
+ let parsedMessage;
41
+ try {
42
+ parsedMessage = JSON.parse(event.data);
43
+ } catch (_error) {
44
+ return;
45
+ }
46
+ if (parsedMessage.type === MessageType.CF_AGENT_STATE) {
47
+ this.options.onStateUpdate?.(parsedMessage.state, "server");
48
+ return;
49
+ }
50
+ if (parsedMessage.type === MessageType.RPC) {
51
+ const response = parsedMessage;
52
+ const pending = this._pendingCalls.get(response.id);
53
+ if (!pending) return;
54
+ if (!response.success) {
55
+ pending.reject(new Error(response.error));
56
+ this._pendingCalls.delete(response.id);
57
+ pending.stream?.onError?.(response.error);
58
+ return;
59
+ }
60
+ if ("done" in response) if (response.done) {
61
+ pending.resolve(response.result);
62
+ this._pendingCalls.delete(response.id);
63
+ pending.stream?.onDone?.(response.result);
64
+ } else pending.stream?.onChunk?.(response.result);
65
+ else {
66
+ pending.resolve(response.result);
67
+ this._pendingCalls.delete(response.id);
68
+ }
69
+ }
70
+ }
71
+ });
72
+ }
73
+ setState(state) {
74
+ this.send(JSON.stringify({
75
+ state,
76
+ type: MessageType.CF_AGENT_STATE
77
+ }));
78
+ this.options.onStateUpdate?.(state, "client");
79
+ }
80
+ async call(method, args = [], streamOptions) {
81
+ return new Promise((resolve, reject) => {
82
+ const id = Math.random().toString(36).slice(2);
83
+ this._pendingCalls.set(id, {
84
+ reject,
85
+ resolve: (value) => resolve(value),
86
+ stream: streamOptions,
87
+ type: null
88
+ });
89
+ const request = {
90
+ args,
91
+ id,
92
+ method,
93
+ type: MessageType.RPC
94
+ };
95
+ this.send(JSON.stringify(request));
96
+ });
97
+ }
98
+ };
99
+ /**
100
+ * Make an HTTP request to an Agent
101
+ * @param opts Connection options
102
+ * @param init Request initialization options
103
+ * @returns Promise resolving to a Response
104
+ */
105
+ function agentFetch(opts, init) {
106
+ const agentNamespace = camelCaseToKebabCase(opts.agent);
107
+ return PartySocket.fetch({
108
+ party: agentNamespace,
109
+ prefix: "agents",
110
+ room: opts.name || "default",
111
+ ...opts
112
+ }, init);
113
+ }
114
+
115
+ //#endregion
116
+ export { AgentClient, agentFetch, camelCaseToKebabCase };
117
+ //# sourceMappingURL=client-DjR-lC16.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-DjR-lC16.js","names":["parsedMessage: Record<string, unknown>","request: RPCRequest"],"sources":["../src/client.ts"],"sourcesContent":["import {\n type PartyFetchOptions,\n PartySocket,\n type PartySocketOptions\n} from \"partysocket\";\nimport type { RPCRequest, RPCResponse } from \"./\";\nimport type {\n SerializableReturnValue,\n SerializableValue\n} from \"./serializable\";\nimport { MessageType } from \"./ai-types\";\n\n/**\n * Options for creating an AgentClient\n */\nexport type AgentClientOptions<State = unknown> = Omit<\n PartySocketOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n};\n\n/**\n * Options for streaming RPC calls\n */\nexport type StreamOptions = {\n /** Called when a chunk of data is received */\n onChunk?: (chunk: unknown) => void;\n /** Called when the stream ends */\n onDone?: (finalChunk: unknown) => void;\n /** Called when an error occurs */\n onError?: (error: string) => void;\n};\n\n/**\n * Options for the agentFetch function\n */\nexport type AgentClientFetchOptions = Omit<\n PartyFetchOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n};\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nexport function camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/**\n * WebSocket client for connecting to an Agent\n */\nexport class AgentClient<State = unknown> extends PartySocket {\n /**\n * @deprecated Use agentFetch instead\n */\n static fetch(_opts: PartyFetchOptions): Promise<Response> {\n throw new Error(\n \"AgentClient.fetch is not implemented, use agentFetch instead\"\n );\n }\n agent: string;\n name: string;\n private options: AgentClientOptions<State>;\n private _pendingCalls = new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n type?: unknown;\n }\n >();\n\n constructor(options: AgentClientOptions<State>) {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n super({\n party: agentNamespace,\n prefix: \"agents\",\n room: options.name || \"default\",\n ...options\n });\n this.agent = agentNamespace;\n this.name = options.name || \"default\";\n this.options = options;\n\n this.addEventListener(\"message\", (event) => {\n if (typeof event.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(event.data);\n } catch (_error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (parsedMessage.type === MessageType.CF_AGENT_STATE) {\n this.options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === MessageType.RPC) {\n const response = parsedMessage as RPCResponse;\n const pending = this._pendingCalls.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n this._pendingCalls.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n }\n }\n }\n });\n }\n\n setState(state: State) {\n this.send(JSON.stringify({ state, type: MessageType.CF_AGENT_STATE }));\n this.options.onStateUpdate?.(state, \"client\");\n }\n\n /**\n * Call a method on the Agent\n * @param method Name of the method to call\n * @param args Arguments to pass to the method\n * @param streamOptions Options for handling streaming responses\n * @returns Promise that resolves with the method's return value\n */\n call<T extends SerializableReturnValue>(\n method: string,\n args?: SerializableValue[],\n streamOptions?: StreamOptions\n ): Promise<T>;\n call<T = unknown>(\n method: string,\n args?: unknown[],\n streamOptions?: StreamOptions\n ): Promise<T>;\n async call<T>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n this._pendingCalls.set(id, {\n reject,\n resolve: (value: unknown) => resolve(value as T),\n stream: streamOptions,\n type: null as T\n });\n\n const request: RPCRequest = {\n args,\n id,\n method,\n type: MessageType.RPC\n };\n\n this.send(JSON.stringify(request));\n });\n }\n}\n\n/**\n * Make an HTTP request to an Agent\n * @param opts Connection options\n * @param init Request initialization options\n * @returns Promise resolving to a Response\n */\nexport function agentFetch(opts: AgentClientFetchOptions, init?: RequestInit) {\n const agentNamespace = camelCaseToKebabCase(opts.agent);\n\n return PartySocket.fetch(\n {\n party: agentNamespace,\n prefix: \"agents\",\n room: opts.name || \"default\",\n ...opts\n },\n init\n );\n}\n"],"mappings":";;;;;;;;;AAyDA,SAAgB,qBAAqB,KAAqB;AAExD,KAAI,QAAQ,IAAI,aAAa,IAAI,QAAQ,IAAI,aAAa,CACxD,QAAO,IAAI,aAAa,CAAC,QAAQ,MAAM,IAAI;CAI7C,IAAI,aAAa,IAAI,QACnB,WACC,WAAW,IAAI,OAAO,aAAa,GACrC;AACD,cAAa,WAAW,WAAW,IAAI,GAAG,WAAW,MAAM,EAAE,GAAG;AAEhE,QAAO,WAAW,QAAQ,MAAM,IAAI,CAAC,QAAQ,MAAM,GAAG;;;;;AAMxD,IAAa,cAAb,cAAkD,YAAY;;;;CAI5D,OAAO,MAAM,OAA6C;AACxD,QAAM,IAAI,MACR,+DACD;;CAeH,YAAY,SAAoC;EAC9C,MAAM,iBAAiB,qBAAqB,QAAQ,MAAM;AAC1D,QAAM;GACJ,OAAO;GACP,QAAQ;GACR,MAAM,QAAQ,QAAQ;GACtB,GAAG;GACJ,CAAC;uCAjBoB,IAAI,KAQzB;AAUD,OAAK,QAAQ;AACb,OAAK,OAAO,QAAQ,QAAQ;AAC5B,OAAK,UAAU;AAEf,OAAK,iBAAiB,YAAY,UAAU;AAC1C,OAAI,OAAO,MAAM,SAAS,UAAU;IAClC,IAAIA;AACJ,QAAI;AACF,qBAAgB,KAAK,MAAM,MAAM,KAAK;aAC/B,QAAQ;AAGf;;AAEF,QAAI,cAAc,SAAS,YAAY,gBAAgB;AACrD,UAAK,QAAQ,gBAAgB,cAAc,OAAgB,SAAS;AACpE;;AAEF,QAAI,cAAc,SAAS,YAAY,KAAK;KAC1C,MAAM,WAAW;KACjB,MAAM,UAAU,KAAK,cAAc,IAAI,SAAS,GAAG;AACnD,SAAI,CAAC,QAAS;AAEd,SAAI,CAAC,SAAS,SAAS;AACrB,cAAQ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- * Options for creating an AgentClient
9
- */
10
- type AgentClientOptions<State = unknown> = Omit<
11
- PartySocketOptions,
12
- "party" | "room"
13
- > & {
14
- /** Name of the agent to connect to */
15
- agent: string;
16
- /** Name of the specific Agent instance */
17
- name?: string;
18
- /** Called when the Agent's state is updated */
19
- onStateUpdate?: (state: State, source: "server" | "client") => void;
20
- };
21
- /**
22
- * Options for streaming RPC calls
23
- */
24
- type StreamOptions = {
25
- /** Called when a chunk of data is received */
26
- onChunk?: (chunk: unknown) => void;
27
- /** Called when the stream ends */
28
- onDone?: (finalChunk: unknown) => void;
29
- /** Called when an error occurs */
30
- onError?: (error: string) => void;
31
- };
32
- /**
33
- * Options for the agentFetch function
34
- */
35
- type AgentClientFetchOptions = Omit<PartyFetchOptions, "party" | "room"> & {
36
- /** Name of the agent to connect to */
37
- agent: string;
38
- /** Name of the specific Agent instance */
39
- name?: string;
40
- };
41
- /**
42
- * WebSocket client for connecting to an Agent
43
- */
44
- declare class AgentClient<State = unknown> extends PartySocket {
45
- #private;
46
- /**
47
- * @deprecated Use agentFetch instead
48
- */
49
- static fetch(_opts: PartyFetchOptions): Promise<Response>;
50
- agent: string;
51
- name: string;
52
- constructor(options: AgentClientOptions<State>);
53
- setState(state: State): void;
54
- /**
55
- * Call a method on the Agent
56
- * @param method Name of the method to call
57
- * @param args Arguments to pass to the method
58
- * @param streamOptions Options for handling streaming responses
59
- * @returns Promise that resolves with the method's return value
60
- */
61
- call<T = unknown>(
62
- method: string,
63
- args?: unknown[],
64
- streamOptions?: StreamOptions
65
- ): Promise<T>;
66
- }
67
- /**
68
- * Make an HTTP request to an Agent
69
- * @param opts Connection options
70
- * @param init Request initialization options
71
- * @returns Promise resolving to a Response
72
- */
73
- declare function agentFetch(
74
- opts: AgentClientFetchOptions,
75
- init?: RequestInit
76
- ): Promise<Response>;
77
-
3
+ AgentClient,
4
+ AgentClientFetchOptions,
5
+ AgentClientOptions,
6
+ StreamOptions,
7
+ agentFetch,
8
+ camelCaseToKebabCase
9
+ } from "./client-CmMi85Sj.js";
78
10
  export {
79
11
  AgentClient,
80
- type AgentClientFetchOptions,
81
- type AgentClientOptions,
82
- type StreamOptions,
12
+ AgentClientFetchOptions,
13
+ AgentClientOptions,
14
+ StreamOptions,
83
15
  agentFetch,
16
+ camelCaseToKebabCase
84
17
  };
package/dist/client.js CHANGED
@@ -1,138 +1,4 @@
1
- import {
2
- __privateAdd,
3
- __privateGet,
4
- __privateSet
5
- } from "./chunk-HMLY7DHA.js";
1
+ import "./ai-types-UZlfLOYP.js";
2
+ import { AgentClient, agentFetch, camelCaseToKebabCase } from "./client-DjR-lC16.js";
6
3
 
7
- // src/client.ts
8
- import {
9
- PartySocket
10
- } from "partysocket";
11
- var _options, _pendingCalls;
12
- var AgentClient = class extends PartySocket {
13
- constructor(options) {
14
- super({
15
- prefix: "agents",
16
- party: options.agent,
17
- room: options.name || "default",
18
- ...options
19
- });
20
- __privateAdd(this, _options);
21
- __privateAdd(this, _pendingCalls, /* @__PURE__ */ new Map());
22
- this.agent = options.agent;
23
- this.name = options.name || "default";
24
- __privateSet(this, _options, options);
25
- if (this.agent !== this.agent.toLowerCase()) {
26
- console.warn(
27
- `Agent name: ${this.agent} should probably be in lowercase. Received: ${this.agent}`
28
- );
29
- }
30
- if (this.name !== this.name.toLowerCase()) {
31
- console.warn(
32
- `Agent instance name: ${this.name} should probably be in lowercase. Received: ${this.name}`
33
- );
34
- }
35
- this.addEventListener("message", (event) => {
36
- if (typeof event.data === "string") {
37
- let parsedMessage;
38
- try {
39
- parsedMessage = JSON.parse(event.data);
40
- } catch (error) {
41
- return;
42
- }
43
- if (parsedMessage.type === "cf_agent_state") {
44
- __privateGet(this, _options).onStateUpdate?.(parsedMessage.state, "server");
45
- return;
46
- }
47
- if (parsedMessage.type === "rpc") {
48
- const response = parsedMessage;
49
- const pending = __privateGet(this, _pendingCalls).get(response.id);
50
- if (!pending) return;
51
- if (!response.success) {
52
- pending.reject(new Error(response.error));
53
- __privateGet(this, _pendingCalls).delete(response.id);
54
- pending.stream?.onError?.(response.error);
55
- return;
56
- }
57
- if ("done" in response) {
58
- if (response.done) {
59
- pending.resolve(response.result);
60
- __privateGet(this, _pendingCalls).delete(response.id);
61
- pending.stream?.onDone?.(response.result);
62
- } else {
63
- pending.stream?.onChunk?.(response.result);
64
- }
65
- } else {
66
- pending.resolve(response.result);
67
- __privateGet(this, _pendingCalls).delete(response.id);
68
- }
69
- }
70
- }
71
- });
72
- }
73
- /**
74
- * @deprecated Use agentFetch instead
75
- */
76
- static fetch(_opts) {
77
- throw new Error(
78
- "AgentClient.fetch is not implemented, use agentFetch instead"
79
- );
80
- }
81
- setState(state) {
82
- this.send(JSON.stringify({ type: "cf_agent_state", state }));
83
- __privateGet(this, _options).onStateUpdate?.(state, "client");
84
- }
85
- /**
86
- * Call a method on the Agent
87
- * @param method Name of the method to call
88
- * @param args Arguments to pass to the method
89
- * @param streamOptions Options for handling streaming responses
90
- * @returns Promise that resolves with the method's return value
91
- */
92
- async call(method, args = [], streamOptions) {
93
- return new Promise((resolve, reject) => {
94
- const id = Math.random().toString(36).slice(2);
95
- __privateGet(this, _pendingCalls).set(id, {
96
- resolve: (value) => resolve(value),
97
- reject,
98
- stream: streamOptions,
99
- type: null
100
- });
101
- const request = {
102
- type: "rpc",
103
- id,
104
- method,
105
- args
106
- };
107
- this.send(JSON.stringify(request));
108
- });
109
- }
110
- };
111
- _options = new WeakMap();
112
- _pendingCalls = new WeakMap();
113
- function agentFetch(opts, init) {
114
- if (opts.agent !== opts.agent.toLowerCase()) {
115
- console.warn(
116
- `Agent name: ${opts.agent} should probably be in lowercase. Received: ${opts.agent}`
117
- );
118
- }
119
- if (opts.name && opts.name !== opts.name.toLowerCase()) {
120
- console.warn(
121
- `Agent instance name: ${opts.name} should probably be in lowercase. Received: ${opts.name}`
122
- );
123
- }
124
- return PartySocket.fetch(
125
- {
126
- prefix: "agents",
127
- party: opts.agent,
128
- room: opts.name || "default",
129
- ...opts
130
- },
131
- init
132
- );
133
- }
134
- export {
135
- AgentClient,
136
- agentFetch
137
- };
138
- //# sourceMappingURL=client.js.map
4
+ export { AgentClient, agentFetch, camelCaseToKebabCase };
@@ -0,0 +1,27 @@
1
+ import { ToolSet } from "ai";
2
+ import { WorkerEntrypoint } from "cloudflare:workers";
3
+
4
+ //#region src/codemode/ai.d.ts
5
+ declare class CodeModeProxy extends WorkerEntrypoint<Cloudflare.Env, {
6
+ binding: string;
7
+ name: string;
8
+ callback: string;
9
+ }> {
10
+ callFunction(options: {
11
+ functionName: string;
12
+ args: unknown[];
13
+ }): Promise<any>;
14
+ }
15
+ declare function experimental_codemode(options: {
16
+ tools: ToolSet;
17
+ prompt: string;
18
+ globalOutbound: Fetcher;
19
+ loader: WorkerLoader;
20
+ proxy: Fetcher<CodeModeProxy>;
21
+ }): Promise<{
22
+ prompt: string;
23
+ tools: ToolSet;
24
+ }>;
25
+ //#endregion
26
+ export { CodeModeProxy, experimental_codemode };
27
+ //# sourceMappingURL=ai.d.ts.map
@@ -0,0 +1,151 @@
1
+ import "../ai-types-UZlfLOYP.js";
2
+ import "../client-DjR-lC16.js";
3
+ import "../client-CZBVDDoO.js";
4
+ import "../do-oauth-client-provider-B2jr6UNq.js";
5
+ import { getAgentByName } from "../src-tpG9NtHy.js";
6
+ import { generateObject, tool } from "ai";
7
+ import { openai } from "@ai-sdk/openai";
8
+ import { z } from "zod/v3";
9
+ import { compile } from "json-schema-to-typescript";
10
+ import { createTypeAlias, printNode, zodToTs } from "zod-to-ts";
11
+ import { WorkerEntrypoint, env } from "cloudflare:workers";
12
+
13
+ //#region src/codemode/ai.ts
14
+ function toCamelCase(str) {
15
+ return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/^[a-z]/, (letter) => letter.toUpperCase());
16
+ }
17
+ var CodeModeProxy = class extends WorkerEntrypoint {
18
+ async callFunction(options) {
19
+ return (await getAgentByName(env[this.ctx.props.binding], this.ctx.props.name))[this.ctx.props.callback](options.functionName, options.args);
20
+ }
21
+ };
22
+ async function experimental_codemode(options) {
23
+ const generatedTypes = await generateTypes(options.tools);
24
+ return {
25
+ prompt: `You are a helpful assistant. You have access to the "codemode" tool that can do different things:
26
+
27
+ ${getToolDescriptions(options.tools)}
28
+
29
+ If the user asks to do anything that be achieveable by the codemode tool, then simply pass over control to it by giving it a simple function description. Don't be too verbose.
30
+
31
+ `,
32
+ tools: { codemode: tool({
33
+ description: "codemode: a tool that can generate code to achieve a goal",
34
+ inputSchema: z.object({ functionDescription: z.string() }),
35
+ outputSchema: z.object({
36
+ code: z.string(),
37
+ result: z.any()
38
+ }),
39
+ execute: async ({ functionDescription }) => {
40
+ try {
41
+ const response = await generateObject({
42
+ model: openai("gpt-4.1"),
43
+ schema: z.object({ code: z.string() }),
44
+ prompt: `You are a code generating machine.
45
+
46
+ In addition to regular javascript, you can also use the following functions:
47
+
48
+ ${generatedTypes}
49
+
50
+ Respond only with the code, nothing else. Output javascript code.
51
+
52
+ Generate an async function that achieves the goal. This async function doesn't accept any arguments.
53
+
54
+ Here is user input: ${functionDescription}`
55
+ });
56
+ const result = await createEvaluator(response.object.code, {
57
+ proxy: options.proxy,
58
+ loader: options.loader
59
+ })();
60
+ return {
61
+ code: response.object.code,
62
+ result
63
+ };
64
+ } catch (error) {
65
+ console.error("error", error);
66
+ throw error;
67
+ }
68
+ }
69
+ }) }
70
+ };
71
+ }
72
+ function createEvaluator(code, options) {
73
+ return async () => {
74
+ return await options.loader.get(`code-${Math.random()}`, () => {
75
+ return {
76
+ compatibilityDate: "2025-06-01",
77
+ compatibilityFlags: ["nodejs_compat"],
78
+ mainModule: "foo.js",
79
+ modules: { "foo.js": `
80
+ import { env, WorkerEntrypoint } from "cloudflare:workers";
81
+
82
+ export default class CodeModeWorker extends WorkerEntrypoint {
83
+ async evaluate() {
84
+ try {
85
+ const { CodeModeProxy } = env;
86
+ const codemode = new Proxy(
87
+ {},
88
+ {
89
+ get: (target, prop) => {
90
+ return (args) => {
91
+ return CodeModeProxy.callFunction({
92
+ functionName: prop,
93
+ args: args,
94
+ });
95
+ };
96
+ }
97
+ }
98
+ );
99
+
100
+ return await ${code}();
101
+ } catch (err) {
102
+ return {
103
+ err: err.message,
104
+ stack: err.stack
105
+ };
106
+ }
107
+ }
108
+ }
109
+
110
+ ` },
111
+ env: { CodeModeProxy: options.proxy },
112
+ globalOutbound: null
113
+ };
114
+ }).getEntrypoint().evaluate();
115
+ };
116
+ }
117
+ async function generateTypes(tools) {
118
+ let availableTools = "";
119
+ let availableTypes = "";
120
+ for (const [toolName, tool$1] of Object.entries(tools)) {
121
+ const inputJsonType = tool$1.inputSchema.jsonSchema ? await compile(tool$1.inputSchema.jsonSchema, `${toCamelCase(toolName)}Input`, {
122
+ format: false,
123
+ bannerComment: " "
124
+ }) : printNode(createTypeAlias(zodToTs(tool$1.inputSchema, `${toCamelCase(toolName)}Input`).node, `${toCamelCase(toolName)}Input`));
125
+ const outputJsonType = tool$1.outputSchema?.jsonSchema ? await compile(tool$1.outputSchema?.jsonSchema, `${toCamelCase(toolName)}Output`, {
126
+ format: false,
127
+ bannerComment: " "
128
+ }) : tool$1.outputSchema ? printNode(createTypeAlias(zodToTs(tool$1.outputSchema, `${toCamelCase(toolName)}Output`).node, `${toCamelCase(toolName)}Output`)) : `interface ${toCamelCase(toolName)}Output { [key: string]: any }`;
129
+ const InputType = inputJsonType.trim().replace("export interface", "interface");
130
+ const OutputType = outputJsonType.trim().replace("export interface", "interface");
131
+ availableTypes += `\n${InputType}`;
132
+ availableTypes += `\n${OutputType}`;
133
+ availableTools += `\n\t/*\n\t${tool$1.description?.trim()}\n\t*/`;
134
+ availableTools += `\n\t${toolName}: (input: ${toCamelCase(toolName)}Input) => Promise<${toCamelCase(toolName)}Output>;`;
135
+ availableTools += "\n";
136
+ }
137
+ availableTools = `\ndeclare const codemode: {${availableTools}}`;
138
+ return `
139
+ ${availableTypes}
140
+ ${availableTools}
141
+ `;
142
+ }
143
+ function getToolDescriptions(tools) {
144
+ return Object.entries(tools).map(([_toolName, tool$1]) => {
145
+ return `\n- ${tool$1.description?.trim()}`;
146
+ }).join("");
147
+ }
148
+
149
+ //#endregion
150
+ export { CodeModeProxy, experimental_codemode };
151
+ //# sourceMappingURL=ai.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai.js","names":["tool","compileJsonSchemaToTs","printNodeZodToTs"],"sources":["../../src/codemode/ai.ts"],"sourcesContent":["import { generateObject, tool, type ToolSet } from \"ai\";\nimport { openai } from \"@ai-sdk/openai\";\nimport { z } from \"zod/v3\";\nimport { compile as compileJsonSchemaToTs } from \"json-schema-to-typescript\";\nimport {\n zodToTs,\n printNode as printNodeZodToTs,\n createTypeAlias\n} from \"zod-to-ts\";\nimport { getAgentByName } from \"..\";\nimport { env, WorkerEntrypoint } from \"cloudflare:workers\";\n\nfunction toCamelCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\nexport class CodeModeProxy extends WorkerEntrypoint<\n Cloudflare.Env,\n {\n binding: string;\n name: string;\n callback: string;\n }\n> {\n async callFunction(options: { functionName: string; args: unknown[] }) {\n const stub = (await getAgentByName(\n // @ts-expect-error\n env[this.ctx.props.binding] as AgentNamespace<T>,\n this.ctx.props.name\n )) as DurableObjectStub;\n // @ts-expect-error\n return stub[this.ctx.props.callback](options.functionName, options.args);\n }\n}\n\nexport async function experimental_codemode(options: {\n tools: ToolSet;\n prompt: string;\n globalOutbound: Fetcher;\n loader: WorkerLoader;\n proxy: Fetcher<CodeModeProxy>;\n}): Promise<{\n prompt: string;\n tools: ToolSet;\n}> {\n const generatedTypes = await generateTypes(options.tools);\n const prompt = `You are a helpful assistant. You have access to the \"codemode\" tool that can do different things: \n \n ${getToolDescriptions(options.tools)} \n \n If the user asks to do anything that be achieveable by the codemode tool, then simply pass over control to it by giving it a simple function description. Don't be too verbose.\n \n `;\n\n const codemodeTool = tool({\n description: \"codemode: a tool that can generate code to achieve a goal\",\n inputSchema: z.object({\n functionDescription: z.string()\n }),\n outputSchema: z.object({\n code: z.string(),\n result: z.any()\n }),\n execute: async ({ functionDescription }) => {\n try {\n const response = await generateObject({\n model: openai(\"gpt-4.1\"),\n schema: z.object({\n code: z.string()\n }),\n prompt: `You are a code generating machine.\n\n In addition to regular javascript, you can also use the following functions:\n\n ${generatedTypes} \n\n Respond only with the code, nothing else. Output javascript code.\n\n Generate an async function that achieves the goal. This async function doesn't accept any arguments.\n\n Here is user input: ${functionDescription}` // insert ts types for the tools here\n });\n\n // console.log(\"args\", response.object.args);\n const evaluator = createEvaluator(response.object.code, {\n proxy: options.proxy,\n loader: options.loader\n });\n const result = await evaluator();\n return { code: response.object.code, result: result };\n } catch (error) {\n console.error(\"error\", error);\n throw error;\n // return { code: \"\", result: error };\n }\n }\n });\n\n return { prompt, tools: { codemode: codemodeTool } };\n}\n\nfunction createEvaluator(\n code: string,\n options: {\n loader: WorkerLoader;\n proxy: Fetcher<CodeModeProxy>;\n }\n) {\n return async () => {\n const worker = options.loader.get(`code-${Math.random()}`, () => {\n return {\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"foo.js\",\n modules: {\n \"foo.js\": `\nimport { env, WorkerEntrypoint } from \"cloudflare:workers\";\n\nexport default class CodeModeWorker extends WorkerEntrypoint {\n async evaluate() {\n try {\n const { CodeModeProxy } = env;\n const codemode = new Proxy(\n {},\n {\n get: (target, prop) => {\n return (args) => {\n return CodeModeProxy.callFunction({\n functionName: prop,\n args: args, \n });\n };\n }\n }\n );\n\n return await ${code}();\n } catch (err) {\n return {\n err: err.message,\n stack: err.stack\n };\n }\n }\n}\n \n `\n },\n env: {\n // insert keys and bindings to tools/ts functions here\n CodeModeProxy: options.proxy\n },\n globalOutbound: null\n };\n });\n\n // @ts-expect-error TODO: fix this\n return await worker.getEntrypoint().evaluate();\n };\n}\n\nasync function generateTypes(tools: ToolSet) {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n // @ts-expect-error TODO: fix this\n const inputJsonType = tool.inputSchema.jsonSchema\n ? await compileJsonSchemaToTs(\n // @ts-expect-error TODO: fix this\n tool.inputSchema.jsonSchema,\n `${toCamelCase(toolName)}Input`,\n {\n format: false,\n bannerComment: \" \"\n }\n )\n : printNodeZodToTs(\n createTypeAlias(\n zodToTs(\n // @ts-expect-error TODO: fix this\n tool.inputSchema,\n `${toCamelCase(toolName)}Input`\n ).node,\n `${toCamelCase(toolName)}Input`\n )\n );\n\n const outputJsonType =\n // @ts-expect-error TODO: fix this\n tool.outputSchema?.jsonSchema\n ? await compileJsonSchemaToTs(\n // @ts-expect-error TODO: fix this\n tool.outputSchema?.jsonSchema,\n `${toCamelCase(toolName)}Output`,\n {\n format: false,\n bannerComment: \" \"\n }\n )\n : tool.outputSchema\n ? printNodeZodToTs(\n createTypeAlias(\n zodToTs(\n // @ts-expect-error TODO: fix this\n tool.outputSchema,\n `${toCamelCase(toolName)}Output`\n ).node,\n `${toCamelCase(toolName)}Output`\n )\n )\n : `interface ${toCamelCase(toolName)}Output { [key: string]: any }`;\n\n const InputType = inputJsonType\n .trim()\n .replace(\"export interface\", \"interface\");\n\n const OutputType = outputJsonType\n .trim()\n .replace(\"export interface\", \"interface\");\n\n availableTypes += `\\n${InputType}`;\n availableTypes += `\\n${OutputType}`;\n availableTools += `\\n\\t/*\\n\\t${tool.description?.trim()}\\n\\t*/`;\n availableTools += `\\n\\t${toolName}: (input: ${toCamelCase(toolName)}Input) => Promise<${toCamelCase(toolName)}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `;\n}\n\nfunction getToolDescriptions(tools: ToolSet) {\n return Object.entries(tools)\n .map(([_toolName, tool]) => {\n return `\\n- ${tool.description?.trim()}`;\n })\n .join(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAS,YAAY,K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;EACf,eAAe;;;AAIjB,SAAS,oBAAoB,OAAgB;AAC3C,QAAO,OAAO,QAAQ,MAAM,CACzB,KAAK,CAAC,WAAWA,YAAU;AAC1B,SAAO,OAAOA,OAAK,aAAa,MAAM;GACtC,CACD,KAAK,GAAG"}
@@ -0,0 +1,93 @@
1
+ import { nanoid } from "nanoid";
2
+
3
+ //#region src/mcp/do-oauth-client-provider.ts
4
+ var DurableObjectOAuthClientProvider = class {
5
+ constructor(storage, clientName, baseRedirectUrl) {
6
+ this.storage = storage;
7
+ this.clientName = clientName;
8
+ this.baseRedirectUrl = baseRedirectUrl;
9
+ }
10
+ get clientMetadata() {
11
+ return {
12
+ client_name: this.clientName,
13
+ client_uri: this.clientUri,
14
+ grant_types: ["authorization_code", "refresh_token"],
15
+ redirect_uris: [this.redirectUrl],
16
+ response_types: ["code"],
17
+ token_endpoint_auth_method: "none"
18
+ };
19
+ }
20
+ get clientUri() {
21
+ return new URL(this.redirectUrl).origin;
22
+ }
23
+ get redirectUrl() {
24
+ return `${this.baseRedirectUrl}/${this.serverId}`;
25
+ }
26
+ get clientId() {
27
+ if (!this._clientId_) throw new Error("Trying to access clientId before it was set");
28
+ return this._clientId_;
29
+ }
30
+ set clientId(clientId_) {
31
+ this._clientId_ = clientId_;
32
+ }
33
+ get serverId() {
34
+ if (!this._serverId_) throw new Error("Trying to access serverId before it was set");
35
+ return this._serverId_;
36
+ }
37
+ set serverId(serverId_) {
38
+ this._serverId_ = serverId_;
39
+ }
40
+ keyPrefix(clientId) {
41
+ return `/${this.clientName}/${this.serverId}/${clientId}`;
42
+ }
43
+ clientInfoKey(clientId) {
44
+ return `${this.keyPrefix(clientId)}/client_info/`;
45
+ }
46
+ async clientInformation() {
47
+ if (!this._clientId_) return;
48
+ return await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;
49
+ }
50
+ async saveClientInformation(clientInformation) {
51
+ await this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);
52
+ this.clientId = clientInformation.client_id;
53
+ }
54
+ tokenKey(clientId) {
55
+ return `${this.keyPrefix(clientId)}/token`;
56
+ }
57
+ async tokens() {
58
+ if (!this._clientId_) return;
59
+ return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
60
+ }
61
+ async saveTokens(tokens) {
62
+ await this.storage.put(this.tokenKey(this.clientId), tokens);
63
+ }
64
+ get authUrl() {
65
+ return this._authUrl_;
66
+ }
67
+ /**
68
+ * Because this operates on the server side (but we need browser auth), we send this url back to the user
69
+ * and require user interact to initiate the redirect flow
70
+ */
71
+ async redirectToAuthorization(authUrl) {
72
+ const stateToken = nanoid();
73
+ authUrl.searchParams.set("state", stateToken);
74
+ this._authUrl_ = authUrl.toString();
75
+ }
76
+ codeVerifierKey(clientId) {
77
+ return `${this.keyPrefix(clientId)}/code_verifier`;
78
+ }
79
+ async saveCodeVerifier(verifier) {
80
+ const key = this.codeVerifierKey(this.clientId);
81
+ if (await this.storage.get(key)) return;
82
+ await this.storage.put(key, verifier);
83
+ }
84
+ async codeVerifier() {
85
+ const codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));
86
+ if (!codeVerifier) throw new Error("No code verifier found");
87
+ return codeVerifier;
88
+ }
89
+ };
90
+
91
+ //#endregion
92
+ export { DurableObjectOAuthClientProvider };
93
+ //# sourceMappingURL=do-oauth-client-provider-B2jr6UNq.js.map