@agentscope-ai/agentscope 0.0.2

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 (136) hide show
  1. package/dist/agent/index.d.mts +234 -0
  2. package/dist/agent/index.d.ts +234 -0
  3. package/dist/agent/index.js +1412 -0
  4. package/dist/agent/index.js.map +1 -0
  5. package/dist/agent/index.mjs +1375 -0
  6. package/dist/agent/index.mjs.map +1 -0
  7. package/dist/base-BOx3UzOl.d.mts +41 -0
  8. package/dist/base-BoIps2RL.d.ts +41 -0
  9. package/dist/base-C7jwyH4Z.d.mts +52 -0
  10. package/dist/base-Cwi4bjze.d.ts +127 -0
  11. package/dist/base-DYlBMCy_.d.mts +127 -0
  12. package/dist/base-NX-knWOv.d.ts +52 -0
  13. package/dist/block-VsnHrllL.d.mts +48 -0
  14. package/dist/block-VsnHrllL.d.ts +48 -0
  15. package/dist/event/index.d.mts +181 -0
  16. package/dist/event/index.d.ts +181 -0
  17. package/dist/event/index.js +58 -0
  18. package/dist/event/index.js.map +1 -0
  19. package/dist/event/index.mjs +33 -0
  20. package/dist/event/index.mjs.map +1 -0
  21. package/dist/formatter/index.d.mts +187 -0
  22. package/dist/formatter/index.d.ts +187 -0
  23. package/dist/formatter/index.js +647 -0
  24. package/dist/formatter/index.js.map +1 -0
  25. package/dist/formatter/index.mjs +616 -0
  26. package/dist/formatter/index.mjs.map +1 -0
  27. package/dist/index-BTJDlKvQ.d.mts +195 -0
  28. package/dist/index-BcatlwXQ.d.ts +195 -0
  29. package/dist/index-CAxQAkiP.d.mts +21 -0
  30. package/dist/index-CAxQAkiP.d.ts +21 -0
  31. package/dist/mcp/index.d.mts +9 -0
  32. package/dist/mcp/index.d.ts +9 -0
  33. package/dist/mcp/index.js +432 -0
  34. package/dist/mcp/index.js.map +1 -0
  35. package/dist/mcp/index.mjs +408 -0
  36. package/dist/mcp/index.mjs.map +1 -0
  37. package/dist/message/index.d.mts +10 -0
  38. package/dist/message/index.d.ts +10 -0
  39. package/dist/message/index.js +67 -0
  40. package/dist/message/index.js.map +1 -0
  41. package/dist/message/index.mjs +37 -0
  42. package/dist/message/index.mjs.map +1 -0
  43. package/dist/message-CkN21KaY.d.mts +99 -0
  44. package/dist/message-CzLeTlua.d.ts +99 -0
  45. package/dist/model/index.d.mts +377 -0
  46. package/dist/model/index.d.ts +377 -0
  47. package/dist/model/index.js +1880 -0
  48. package/dist/model/index.js.map +1 -0
  49. package/dist/model/index.mjs +1849 -0
  50. package/dist/model/index.mjs.map +1 -0
  51. package/dist/storage/index.d.mts +68 -0
  52. package/dist/storage/index.d.ts +68 -0
  53. package/dist/storage/index.js +250 -0
  54. package/dist/storage/index.js.map +1 -0
  55. package/dist/storage/index.mjs +212 -0
  56. package/dist/storage/index.mjs.map +1 -0
  57. package/dist/tool/index.d.mts +311 -0
  58. package/dist/tool/index.d.ts +311 -0
  59. package/dist/tool/index.js +1494 -0
  60. package/dist/tool/index.js.map +1 -0
  61. package/dist/tool/index.mjs +1447 -0
  62. package/dist/tool/index.mjs.map +1 -0
  63. package/dist/toolkit-CEpulFi0.d.ts +99 -0
  64. package/dist/toolkit-CGEZSZPa.d.mts +99 -0
  65. package/jest.config.js +11 -0
  66. package/package.json +92 -0
  67. package/src/_utils/common.ts +104 -0
  68. package/src/_utils/index.ts +1 -0
  69. package/src/agent/agent-base.ts +0 -0
  70. package/src/agent/agent.test.ts +1028 -0
  71. package/src/agent/agent.ts +1032 -0
  72. package/src/agent/index.ts +2 -0
  73. package/src/agent/interfaces.ts +23 -0
  74. package/src/agent/test-compression.ts +72 -0
  75. package/src/event/index.ts +250 -0
  76. package/src/formatter/base.ts +133 -0
  77. package/src/formatter/dashscope-chat-formatter.test.ts +372 -0
  78. package/src/formatter/dashscope-chat-formatter.ts +163 -0
  79. package/src/formatter/deepseek-chat-formatter.ts +130 -0
  80. package/src/formatter/index.ts +5 -0
  81. package/src/formatter/ollama-chat-formatter.ts +67 -0
  82. package/src/formatter/openai-chat-formatter.test.ts +263 -0
  83. package/src/formatter/openai-chat-formatter.ts +301 -0
  84. package/src/formatter/openai.md +767 -0
  85. package/src/mcp/base.ts +114 -0
  86. package/src/mcp/http.test.ts +303 -0
  87. package/src/mcp/http.ts +224 -0
  88. package/src/mcp/index.ts +2 -0
  89. package/src/mcp/stdio.test.ts +91 -0
  90. package/src/mcp/stdio.ts +119 -0
  91. package/src/message/block.ts +60 -0
  92. package/src/message/enums.ts +4 -0
  93. package/src/message/index.ts +12 -0
  94. package/src/message/message.test.ts +80 -0
  95. package/src/message/message.ts +131 -0
  96. package/src/model/base.ts +226 -0
  97. package/src/model/dashscope-model.test.ts +335 -0
  98. package/src/model/dashscope-model.ts +441 -0
  99. package/src/model/deepseek-model.test.ts +279 -0
  100. package/src/model/deepseek-model.ts +401 -0
  101. package/src/model/index.ts +7 -0
  102. package/src/model/ollama-model.test.ts +307 -0
  103. package/src/model/ollama-model.ts +356 -0
  104. package/src/model/openai-model.ts +327 -0
  105. package/src/model/response.ts +22 -0
  106. package/src/model/usage.ts +12 -0
  107. package/src/storage/base.ts +52 -0
  108. package/src/storage/file-system.test.ts +587 -0
  109. package/src/storage/file-system.ts +269 -0
  110. package/src/storage/index.ts +2 -0
  111. package/src/tool/base.ts +23 -0
  112. package/src/tool/bash.test.ts +174 -0
  113. package/src/tool/bash.ts +152 -0
  114. package/src/tool/edit.test.ts +83 -0
  115. package/src/tool/edit.ts +95 -0
  116. package/src/tool/glob.test.ts +63 -0
  117. package/src/tool/glob.ts +166 -0
  118. package/src/tool/grep.test.ts +74 -0
  119. package/src/tool/grep.ts +256 -0
  120. package/src/tool/index.ts +10 -0
  121. package/src/tool/read.test.ts +77 -0
  122. package/src/tool/read.ts +117 -0
  123. package/src/tool/response.ts +82 -0
  124. package/src/tool/task.test.ts +299 -0
  125. package/src/tool/task.ts +399 -0
  126. package/src/tool/toolkit.test.ts +636 -0
  127. package/src/tool/toolkit.ts +601 -0
  128. package/src/tool/write.test.ts +52 -0
  129. package/src/tool/write.ts +57 -0
  130. package/src/type/index.ts +52 -0
  131. package/tsconfig.build.json +4 -0
  132. package/tsconfig.cjs.json +11 -0
  133. package/tsconfig.esm.json +10 -0
  134. package/tsconfig.json +14 -0
  135. package/tsup.config.ts +20 -0
  136. package/typedoc.json +52 -0
@@ -0,0 +1,408 @@
1
+ // src/mcp/http.ts
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import {
4
+ SSEClientTransport
5
+ } from "@modelcontextprotocol/sdk/client/sse.js";
6
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
7
+ import { ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
8
+
9
+ // src/mcp/base.ts
10
+ import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
11
+
12
+ // src/tool/response.ts
13
+ function createToolResponse({
14
+ content,
15
+ state,
16
+ id = crypto.randomUUID(),
17
+ createdAt = (/* @__PURE__ */ new Date()).toISOString(),
18
+ metadata = {},
19
+ stream = false,
20
+ isLast = true,
21
+ isInterrupted = false
22
+ }) {
23
+ return {
24
+ content,
25
+ id,
26
+ createdAt,
27
+ metadata,
28
+ state,
29
+ stream,
30
+ isLast,
31
+ isInterrupted
32
+ };
33
+ }
34
+
35
+ // src/mcp/base.ts
36
+ var MCPTool = class {
37
+ name;
38
+ description;
39
+ inputSchema;
40
+ requireUserConfirm = false;
41
+ call;
42
+ getClient;
43
+ releaseClient;
44
+ /**
45
+ * Initialize an MCPTool instance
46
+ * @param root0
47
+ * @param root0.name
48
+ * @param root0.description
49
+ * @param root0.inputSchema
50
+ * @param root0.getClient
51
+ * @param root0.releaseClient
52
+ */
53
+ constructor({
54
+ name,
55
+ description,
56
+ inputSchema,
57
+ getClient,
58
+ releaseClient
59
+ }) {
60
+ this.name = name;
61
+ this.description = description;
62
+ this.inputSchema = inputSchema;
63
+ this.getClient = getClient;
64
+ this.releaseClient = releaseClient;
65
+ this.call = this._call.bind(this);
66
+ }
67
+ /**
68
+ * Call the MCP tool with the specified input arguments. This method sends a request to the MCP server to execute
69
+ * the tool and returns the result as a ToolResponse.
70
+ *
71
+ * @param arguments
72
+ * @param input
73
+ * @returns A ToolResponse object containing the result of the tool execution, or an error message if the call fails.
74
+ */
75
+ async _call(input) {
76
+ const client = await this.getClient();
77
+ try {
78
+ const request = {
79
+ method: "tools/call",
80
+ params: {
81
+ name: this.name,
82
+ arguments: input
83
+ }
84
+ };
85
+ const result = await client.request(request, CallToolResultSchema);
86
+ const content = [];
87
+ result.content.forEach((item) => {
88
+ if (item.type === "text") {
89
+ content.push({ type: "text", text: item.text, id: crypto.randomUUID() });
90
+ } else if (item.type === "image" || item.type === "audio") {
91
+ content.push({
92
+ id: crypto.randomUUID(),
93
+ type: "data",
94
+ source: { type: "base64", mediaType: item.mimeType, data: item.data }
95
+ });
96
+ } else {
97
+ console.warn(
98
+ `Unsupported content type '${item.type}' in tool result, skipping...`
99
+ );
100
+ }
101
+ });
102
+ return createToolResponse({ content, state: "success" });
103
+ } catch (error) {
104
+ return createToolResponse({
105
+ content: [
106
+ {
107
+ id: crypto.randomUUID(),
108
+ type: "text",
109
+ text: `Error calling tool '${this.name}': ${error}`
110
+ }
111
+ ],
112
+ state: "error"
113
+ });
114
+ } finally {
115
+ await this.releaseClient(client);
116
+ }
117
+ }
118
+ };
119
+
120
+ // src/mcp/http.ts
121
+ var HTTPMCPClient = class {
122
+ name;
123
+ requestOptions;
124
+ client;
125
+ transport;
126
+ transportType;
127
+ url;
128
+ transportOpts;
129
+ stateful;
130
+ /**
131
+ * Initialize the HTTPStatefulMCPClient with the specified transport type, URL, and options.
132
+ *
133
+ * @param root0
134
+ * @param root0.name
135
+ * @param root0.transportType
136
+ * @param root0.url
137
+ * @param root0.stateful
138
+ * @param root0.transportOpts
139
+ * @param root0.requestOptions
140
+ */
141
+ constructor({
142
+ name,
143
+ transportType,
144
+ url,
145
+ stateful = true,
146
+ transportOpts,
147
+ requestOptions
148
+ }) {
149
+ this.name = name;
150
+ this.transportType = transportType;
151
+ this.transportOpts = transportOpts;
152
+ this.requestOptions = requestOptions;
153
+ this.url = url;
154
+ this.stateful = stateful;
155
+ }
156
+ /**
157
+ * Connect to the MCP server with the specified transport and URL. This method must be called before making any
158
+ * requests to the server.
159
+ */
160
+ async connect() {
161
+ if (!this.stateful) {
162
+ console.log(
163
+ `MCP client '${this.name}' initialized with stateful=false will connect and close the connection automatically for each request, no need to call 'connect()' method explicitly.`
164
+ );
165
+ } else {
166
+ await this._connect();
167
+ }
168
+ }
169
+ /**
170
+ * The internal method to establish the connection to the MCP server. It initializes the appropriate transport
171
+ * based on the specified transport type and creates a new Client instance to manage the connection and requests.
172
+ */
173
+ async _connect() {
174
+ const baseUrl = new URL(this.url);
175
+ if (this.transportType === "streamable-http") {
176
+ this.transport = new StreamableHTTPClientTransport(baseUrl, this.transportOpts);
177
+ } else {
178
+ this.transport = new SSEClientTransport(baseUrl, this.transportOpts);
179
+ }
180
+ this.client = new Client({
181
+ name: this.name,
182
+ version: "1.0.0"
183
+ });
184
+ await this.client.connect(this.transport, this.requestOptions);
185
+ console.log(`MCP client '${this.name}' is connected`);
186
+ }
187
+ /**
188
+ * List all tools available on the MCP server.
189
+ *
190
+ * @returns An array of MCPTool instances representing the tools available on the server.
191
+ */
192
+ async listTools() {
193
+ let listClient;
194
+ if (this.stateful) {
195
+ if (!this.client) {
196
+ throw new Error(
197
+ `Client not initialized, call 'connect()' method first for the MCP client named '${this.name}'`
198
+ );
199
+ }
200
+ listClient = this.client;
201
+ } else {
202
+ listClient = await this._createClient();
203
+ }
204
+ try {
205
+ const toolsRequest = {
206
+ method: "tools/list",
207
+ params: {}
208
+ };
209
+ const toolsResult = await listClient.request(toolsRequest, ListToolsResultSchema);
210
+ if (toolsResult.tools === void 0) {
211
+ return [];
212
+ }
213
+ return toolsResult.tools.map((tool) => {
214
+ if (this.stateful) {
215
+ return new MCPTool({
216
+ name: tool.name,
217
+ description: tool.description || "",
218
+ inputSchema: tool.inputSchema,
219
+ getClient: async () => this.client,
220
+ releaseClient: async () => {
221
+ }
222
+ });
223
+ } else {
224
+ return new MCPTool({
225
+ name: tool.name,
226
+ description: tool.description || "",
227
+ inputSchema: tool.inputSchema,
228
+ getClient: () => this._createClient(),
229
+ releaseClient: async (c) => {
230
+ await c.close();
231
+ }
232
+ });
233
+ }
234
+ });
235
+ } finally {
236
+ if (!this.stateful) {
237
+ await listClient.close();
238
+ }
239
+ }
240
+ }
241
+ /**
242
+ * Close the connection to the MCP server and clean up any resources used by the client.
243
+ */
244
+ async close() {
245
+ if (!this.stateful) {
246
+ console.log(
247
+ `MCP client '${this.name}' initialized with stateful=false will connect and close the connection automatically for each request, no need to call 'close()' method explicitly.`
248
+ );
249
+ } else {
250
+ await this._close();
251
+ }
252
+ }
253
+ /**
254
+ * The internal method to close the connection to the MCP server.
255
+ */
256
+ async _close() {
257
+ try {
258
+ await this.client?.close();
259
+ } finally {
260
+ console.log(`MCP client '${this.name} is closed.'`);
261
+ this.client = void 0;
262
+ this.transport = void 0;
263
+ }
264
+ }
265
+ /**
266
+ * Create a new client instance without storing it in this.client.
267
+ * Used for stateless operations where each request needs its own client.
268
+ * @returns A new connected Client instance
269
+ */
270
+ async _createClient() {
271
+ const baseUrl = new URL(this.url);
272
+ const transport = this.transportType === "streamable-http" ? new StreamableHTTPClientTransport(baseUrl, this.transportOpts) : new SSEClientTransport(baseUrl, this.transportOpts);
273
+ const client = new Client({
274
+ name: this.name,
275
+ version: "1.0.0"
276
+ });
277
+ await client.connect(transport, this.requestOptions);
278
+ return client;
279
+ }
280
+ /**
281
+ * Get a callable function for a specific tool by its name.
282
+ * @param root0
283
+ * @param root0.name
284
+ * @returns An instance of MCPTool that can be called to execute the tool's functionality.
285
+ */
286
+ async getCallableFunction({ name }) {
287
+ if (this.stateful && !this.client) {
288
+ throw new Error(
289
+ `Client not initialized, call 'connect()' method first for the MCP client named '${this.name}'`
290
+ );
291
+ }
292
+ const tools = await this.listTools();
293
+ const targetTool = tools.find((tool) => tool.name === name);
294
+ if (!targetTool) {
295
+ throw new Error(
296
+ `Tool '${name}' not found in MCP server '${this.name}'. Available tools: ${tools.map((t) => t.name).join(", ")}`
297
+ );
298
+ }
299
+ return targetTool;
300
+ }
301
+ };
302
+
303
+ // src/mcp/stdio.ts
304
+ import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
305
+ import {
306
+ StdioClientTransport
307
+ } from "@modelcontextprotocol/sdk/client/stdio.js";
308
+ import { ListToolsResultSchema as ListToolsResultSchema2 } from "@modelcontextprotocol/sdk/types.js";
309
+ var StdioMCPClient = class {
310
+ name;
311
+ stdioServerParameters;
312
+ transport;
313
+ client;
314
+ /**
315
+ * Initialize the StdioMCPClient with the given Stdio parameters.
316
+ *
317
+ * @param root0
318
+ * @param root0.name
319
+ */
320
+ constructor({
321
+ name,
322
+ ...rest
323
+ }) {
324
+ this.name = name;
325
+ this.stdioServerParameters = rest;
326
+ }
327
+ /**
328
+ * Connect to the MCP server using Stdio transport. Note the Stdio client will start an
329
+ * MCP server process under the hood.
330
+ */
331
+ async connect() {
332
+ this.transport = new StdioClientTransport(this.stdioServerParameters);
333
+ this.client = new Client2({
334
+ name: this.name,
335
+ version: "1.0.0"
336
+ });
337
+ await this.client.connect(this.transport);
338
+ }
339
+ /**
340
+ * Close the connection and stop the MCP server process.
341
+ */
342
+ async close() {
343
+ try {
344
+ if (this.client) {
345
+ await this.client.close();
346
+ }
347
+ } finally {
348
+ this.client = void 0;
349
+ this.transport = void 0;
350
+ }
351
+ }
352
+ /**
353
+ * List all tools available on the MCP server.
354
+ *
355
+ * @returns An array of MCPTool instances representing the tools available on the server.
356
+ */
357
+ async listTools() {
358
+ if (!this.client) {
359
+ throw new Error(
360
+ `Client not initialized, call 'connect()' method first for the MCP client named '${this.name}'`
361
+ );
362
+ }
363
+ const toolsRequest = {
364
+ method: "tools/list",
365
+ params: {}
366
+ };
367
+ const toolsResult = await this.client.request(toolsRequest, ListToolsResultSchema2);
368
+ if (toolsResult.tools === void 0) {
369
+ return [];
370
+ }
371
+ return toolsResult.tools.map((tool) => {
372
+ return new MCPTool({
373
+ name: tool.name,
374
+ description: tool.description || "",
375
+ inputSchema: tool.inputSchema,
376
+ getClient: async () => this.client,
377
+ releaseClient: async () => {
378
+ }
379
+ });
380
+ });
381
+ }
382
+ /**
383
+ * Get a callable function for a specific tool by its name.
384
+ * @param root0
385
+ * @param root0.name
386
+ * @returns An instance of MCPTool that can be called to execute the tool's functionality.
387
+ */
388
+ async getCallableFunction({ name }) {
389
+ if (!this.client) {
390
+ throw new Error(
391
+ `Client not initialized, call 'connect()' method first for the MCP client named '${this.name}'`
392
+ );
393
+ }
394
+ const tools = await this.listTools();
395
+ const targetTool = tools.find((tool) => tool.name === name);
396
+ if (!targetTool) {
397
+ throw new Error(
398
+ `Tool '${name}' not found in MCP server '${this.name}'. Available tools: ${tools.map((t) => t.name).join(", ")}`
399
+ );
400
+ }
401
+ return targetTool;
402
+ }
403
+ };
404
+ export {
405
+ HTTPMCPClient,
406
+ StdioMCPClient
407
+ };
408
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/mcp/http.ts","../../src/mcp/base.ts","../../src/tool/response.ts","../../src/mcp/stdio.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport {\n SSEClientTransport,\n SSEClientTransportOptions,\n} from '@modelcontextprotocol/sdk/client/sse.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport { StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport { ListToolsRequest, ListToolsResultSchema, Tool } from '@modelcontextprotocol/sdk/types.js';\n\nimport { MCPTool } from './base';\n\n/**\n * The HTTP MCP client class that connects to an MCP server using either Streamable HTTP or Server-Sent Events (SSE)\n * transport.\n * Note the client is stateful, meaning that developers should manually call the `connect()` and `close()` methods to\n * manage the connection lifecycle.\n */\nexport class HTTPMCPClient {\n name: string;\n private requestOptions?: RequestOptions;\n private client?: Client;\n private transport?: StreamableHTTPClientTransport | SSEClientTransport;\n private transportType: 'streamable-http' | 'sse';\n private url: string;\n private transportOpts?: StreamableHTTPClientTransportOptions | SSEClientTransportOptions;\n private stateful: boolean;\n\n /**\n * Initialize the HTTPStatefulMCPClient with the specified transport type, URL, and options.\n *\n * @param root0\n * @param root0.name\n * @param root0.transportType\n * @param root0.url\n * @param root0.stateful\n * @param root0.transportOpts\n * @param root0.requestOptions\n */\n constructor({\n name,\n transportType,\n url,\n stateful = true,\n transportOpts,\n requestOptions,\n }: {\n name: string;\n transportType: 'streamable-http' | 'sse';\n url: string;\n stateful?: boolean;\n transportOpts?: StreamableHTTPClientTransportOptions | SSEClientTransportOptions;\n requestOptions?: RequestOptions;\n }) {\n this.name = name;\n this.transportType = transportType;\n this.transportOpts = transportOpts;\n this.requestOptions = requestOptions;\n this.url = url;\n this.stateful = stateful;\n }\n\n /**\n * Connect to the MCP server with the specified transport and URL. This method must be called before making any\n * requests to the server.\n */\n async connect() {\n if (!this.stateful) {\n console.log(\n `MCP client '${this.name}' initialized with stateful=false will connect and close the connection automatically for each request, no need to call 'connect()' method explicitly.`\n );\n } else {\n await this._connect();\n }\n }\n\n /**\n * The internal method to establish the connection to the MCP server. It initializes the appropriate transport\n * based on the specified transport type and creates a new Client instance to manage the connection and requests.\n */\n protected async _connect() {\n const baseUrl = new URL(this.url);\n if (this.transportType === 'streamable-http') {\n this.transport = new StreamableHTTPClientTransport(baseUrl, this.transportOpts);\n } else {\n this.transport = new SSEClientTransport(baseUrl, this.transportOpts);\n }\n this.client = new Client({\n name: this.name,\n version: '1.0.0',\n });\n await this.client.connect(this.transport, this.requestOptions);\n console.log(`MCP client '${this.name}' is connected`);\n }\n\n /**\n * List all tools available on the MCP server.\n *\n * @returns An array of MCPTool instances representing the tools available on the server.\n */\n async listTools(): Promise<MCPTool[]> {\n let listClient: Client;\n\n if (this.stateful) {\n if (!this.client) {\n throw new Error(\n `Client not initialized, call 'connect()' method first for the MCP client named '${this.name}'`\n );\n }\n listClient = this.client;\n } else {\n listClient = await this._createClient();\n }\n\n try {\n const toolsRequest: ListToolsRequest = {\n method: 'tools/list',\n params: {},\n };\n\n const toolsResult = await listClient.request(toolsRequest, ListToolsResultSchema);\n if (toolsResult.tools === undefined) {\n return [];\n }\n\n return toolsResult.tools.map((tool: Tool) => {\n if (this.stateful) {\n return new MCPTool({\n name: tool.name,\n description: tool.description || '',\n inputSchema: tool.inputSchema,\n getClient: async () => this.client!,\n releaseClient: async () => {},\n });\n } else {\n return new MCPTool({\n name: tool.name,\n description: tool.description || '',\n inputSchema: tool.inputSchema,\n getClient: () => this._createClient(),\n releaseClient: async (c: Client) => {\n await c.close();\n },\n });\n }\n });\n } finally {\n if (!this.stateful) {\n await listClient.close();\n }\n }\n }\n\n /**\n * Close the connection to the MCP server and clean up any resources used by the client.\n */\n async close() {\n if (!this.stateful) {\n console.log(\n `MCP client '${this.name}' initialized with stateful=false will connect and close the connection automatically for each request, no need to call 'close()' method explicitly.`\n );\n } else {\n await this._close();\n }\n }\n\n /**\n * The internal method to close the connection to the MCP server.\n */\n protected async _close() {\n try {\n await this.client?.close();\n } finally {\n console.log(`MCP client '${this.name} is closed.'`);\n this.client = undefined;\n this.transport = undefined;\n }\n }\n\n /**\n * Create a new client instance without storing it in this.client.\n * Used for stateless operations where each request needs its own client.\n * @returns A new connected Client instance\n */\n protected async _createClient(): Promise<Client> {\n const baseUrl = new URL(this.url);\n const transport =\n this.transportType === 'streamable-http'\n ? new StreamableHTTPClientTransport(baseUrl, this.transportOpts)\n : new SSEClientTransport(baseUrl, this.transportOpts);\n\n const client = new Client({\n name: this.name,\n version: '1.0.0',\n });\n await client.connect(transport, this.requestOptions);\n return client;\n }\n\n /**\n * Get a callable function for a specific tool by its name.\n * @param root0\n * @param root0.name\n * @returns An instance of MCPTool that can be called to execute the tool's functionality.\n */\n async getCallableFunction({ name }: { name: string }) {\n if (this.stateful && !this.client) {\n throw new Error(\n `Client not initialized, call 'connect()' method first for the MCP client named '${this.name}'`\n );\n }\n\n const tools = await this.listTools();\n const targetTool = tools.find(tool => tool.name === name);\n\n if (!targetTool) {\n throw new Error(\n `Tool '${name}' not found in MCP server '${this.name}'. Available tools: ${tools.map(t => t.name).join(', ')}`\n );\n }\n\n return targetTool;\n }\n}\n","import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport { CallToolRequest, CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';\nimport z from 'zod';\n\nimport { Tool, ToolResponse } from '../tool';\nimport { createToolResponse } from '../tool/response';\nimport { ToolInputSchema } from '../type';\n\n/**\n * Type definition for getting a client instance\n */\ntype GetClient = () => Promise<Client>;\n\n/**\n * Type definition for releasing a client instance\n */\ntype ReleaseClient = (client: Client) => Promise<void>;\n\n/**\n * MCPTool class that wraps an MCP tool and provides a callable interface\n */\nexport class MCPTool implements Tool {\n name: string;\n description: string;\n inputSchema: z.ZodObject | ToolInputSchema;\n requireUserConfirm = false;\n call: (input: Record<string, unknown>) => Promise<ToolResponse>;\n\n private getClient: GetClient;\n private releaseClient: ReleaseClient;\n\n /**\n * Initialize an MCPTool instance\n * @param root0\n * @param root0.name\n * @param root0.description\n * @param root0.inputSchema\n * @param root0.getClient\n * @param root0.releaseClient\n */\n constructor({\n name,\n description,\n inputSchema,\n getClient,\n releaseClient,\n }: {\n name: string;\n description: string;\n inputSchema: z.ZodObject | ToolInputSchema;\n getClient: GetClient;\n releaseClient: ReleaseClient;\n }) {\n this.name = name;\n this.description = description;\n this.inputSchema = inputSchema;\n this.getClient = getClient;\n this.releaseClient = releaseClient;\n this.call = this._call.bind(this);\n }\n\n /**\n * Call the MCP tool with the specified input arguments. This method sends a request to the MCP server to execute\n * the tool and returns the result as a ToolResponse.\n *\n * @param arguments\n * @param input\n * @returns A ToolResponse object containing the result of the tool execution, or an error message if the call fails.\n */\n async _call(input: Record<string, unknown>) {\n const client = await this.getClient();\n try {\n const request: CallToolRequest = {\n method: 'tools/call',\n params: {\n name: this.name,\n arguments: input,\n },\n };\n const result = await client.request(request, CallToolResultSchema);\n\n const content: ToolResponse['content'] = [];\n result.content.forEach(item => {\n if (item.type === 'text') {\n content.push({ type: 'text', text: item.text, id: crypto.randomUUID() });\n } else if (item.type === 'image' || item.type === 'audio') {\n content.push({\n id: crypto.randomUUID(),\n type: 'data',\n source: { type: 'base64', mediaType: item.mimeType, data: item.data },\n });\n } else {\n console.warn(\n `Unsupported content type '${item.type}' in tool result, skipping...`\n );\n }\n });\n return createToolResponse({ content, state: 'success' });\n } catch (error) {\n return createToolResponse({\n content: [\n {\n id: crypto.randomUUID(),\n type: 'text',\n text: `Error calling tool '${this.name}': ${error}`,\n },\n ],\n state: 'error',\n });\n } finally {\n await this.releaseClient(client);\n }\n }\n}\n","import { DataBlock, TextBlock } from '../message';\nimport { JSONSerializableObject } from '../type';\n\n/**\n * The tool response structure.\n */\nexport interface ToolResponse {\n content: Array<TextBlock | DataBlock>;\n id: string;\n createdAt: string;\n metadata: Record<string, JSONSerializableObject>;\n state: 'success' | 'error' | 'interrupted' | 'running';\n isLast: boolean;\n isInterrupted: boolean;\n}\n\n/**\n * Create a tool response object with the given parameters.\n *\n * @param root0\n * @param root0.content\n * @param root0.state\n * @param root0.id\n * @param root0.createdAt\n * @param root0.metadata\n * @param root0.stream\n * @param root0.isLast\n * @param root0.isInterrupted\n * @returns A ToolResponse object\n */\nexport function createToolResponse({\n content,\n state,\n id = crypto.randomUUID(),\n createdAt = new Date().toISOString(),\n metadata = {},\n stream = false,\n isLast = true,\n isInterrupted = false,\n}: {\n content: Array<TextBlock | DataBlock>;\n state: 'success' | 'error' | 'interrupted' | 'running';\n id?: string;\n createdAt?: string;\n metadata?: Record<string, JSONSerializableObject>;\n stream?: boolean;\n isLast?: boolean;\n isInterrupted?: boolean;\n}) {\n return {\n content,\n id,\n createdAt,\n metadata,\n state,\n stream,\n isLast,\n isInterrupted,\n } as ToolResponse;\n}\n\n/**\n * If the given object conforms to the ToolResponse structure.\n *\n * @param obj\n * @returns True if the object is a ToolResponse, false otherwise\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function isToolResponse(obj: any): boolean {\n return (\n obj &&\n typeof obj === 'object' &&\n typeof obj.id === 'string' &&\n typeof obj.createdAt === 'string' &&\n Array.isArray(obj.content) &&\n typeof obj.metadata === 'object' &&\n typeof obj.stream === 'boolean' &&\n typeof obj.isLast === 'boolean' &&\n typeof obj.isInterrupted === 'boolean' &&\n ['success', 'error', 'interrupted', 'running'].includes(obj.state)\n );\n}\n","import { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport {\n StdioClientTransport,\n StdioServerParameters,\n} from '@modelcontextprotocol/sdk/client/stdio.js';\nimport { ListToolsRequest, ListToolsResultSchema, Tool } from '@modelcontextprotocol/sdk/types.js';\n\nimport { MCPTool } from './base';\n\n/**\n * The STDIO MCP client class.\n */\nexport class StdioMCPClient {\n name: string;\n private stdioServerParameters: StdioServerParameters;\n private transport?: StdioClientTransport;\n private client?: Client;\n\n /**\n * Initialize the StdioMCPClient with the given Stdio parameters.\n *\n * @param root0\n * @param root0.name\n */\n constructor({\n name,\n ...rest\n }: {\n name: string;\n } & StdioServerParameters) {\n this.name = name;\n this.stdioServerParameters = rest;\n }\n\n /**\n * Connect to the MCP server using Stdio transport. Note the Stdio client will start an\n * MCP server process under the hood.\n */\n async connect() {\n this.transport = new StdioClientTransport(this.stdioServerParameters);\n this.client = new Client({\n name: this.name,\n version: '1.0.0',\n });\n await this.client.connect(this.transport);\n }\n\n /**\n * Close the connection and stop the MCP server process.\n */\n async close() {\n try {\n if (this.client) {\n await this.client.close();\n }\n } finally {\n this.client = undefined;\n this.transport = undefined;\n }\n }\n\n /**\n * List all tools available on the MCP server.\n *\n * @returns An array of MCPTool instances representing the tools available on the server.\n */\n async listTools(): Promise<MCPTool[]> {\n if (!this.client) {\n throw new Error(\n `Client not initialized, call 'connect()' method first for the MCP client named '${this.name}'`\n );\n }\n\n const toolsRequest: ListToolsRequest = {\n method: 'tools/list',\n params: {},\n };\n\n const toolsResult = await this.client.request(toolsRequest, ListToolsResultSchema);\n if (toolsResult.tools === undefined) {\n return [];\n }\n\n return toolsResult.tools.map((tool: Tool) => {\n return new MCPTool({\n name: tool.name,\n description: tool.description || '',\n inputSchema: tool.inputSchema,\n getClient: async () => this.client!,\n releaseClient: async () => {},\n });\n });\n }\n\n /**\n * Get a callable function for a specific tool by its name.\n * @param root0\n * @param root0.name\n * @returns An instance of MCPTool that can be called to execute the tool's functionality.\n */\n async getCallableFunction({ name }: { name: string }) {\n if (!this.client) {\n throw new Error(\n `Client not initialized, call 'connect()' method first for the MCP client named '${this.name}'`\n );\n }\n\n const tools = await this.listTools();\n const targetTool = tools.find(tool => tool.name === name);\n\n if (!targetTool) {\n throw new Error(\n `Tool '${name}' not found in MCP server '${this.name}'. Available tools: ${tools.map(t => t.name).join(', ')}`\n );\n }\n\n return targetTool;\n }\n}\n"],"mappings":";AAAA,SAAS,cAAc;AACvB;AAAA,EACI;AAAA,OAEG;AACP,SAAS,qCAAqC;AAG9C,SAA2B,6BAAmC;;;ACP9D,SAA0B,4BAA4B;;;AC6B/C,SAAS,mBAAmB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA,KAAK,OAAO,WAAW;AAAA,EACvB,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,EACnC,WAAW,CAAC;AAAA,EACZ,SAAS;AAAA,EACT,SAAS;AAAA,EACT,gBAAgB;AACpB,GASG;AACC,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AACJ;;;ADtCO,IAAM,UAAN,MAA8B;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAAqB;AAAA,EACrB;AAAA,EAEQ;AAAA,EACA;AAAA;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Y;AAAA,QAAC;AAAA,MAChC,CAAC;AAAA,IACL,CAAC;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,oBAAoB,EAAE,KAAK,GAAqB;AAClD,QAAI,CAAC,KAAK,QAAQ;AACd,YAAM,IAAI;AAAA,QACN,mFAAmF,KAAK,IAAI;AAAA,MAChG;AAAA,IACJ;AAEA,UAAM,QAAQ,MAAM,KAAK,UAAU;AACnC,UAAM,aAAa,MAAM,KAAK,UAAQ,KAAK,SAAS,IAAI;AAExD,QAAI,CAAC,YAAY;AACb,YAAM,IAAI;AAAA,QACN,SAAS,IAAI,8BAA8B,KAAK,IAAI,uBAAuB,MAAM,IAAI,OAAK,EAAE,IAAI,EAAE,KAAK,IAAI,CAAC;AAAA,MAChH;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;","names":["Client","ListToolsResultSchema","Client","ListToolsResultSchema"]}
@@ -0,0 +1,10 @@
1
+ export { M as Msg, c as createMsg, g as getContentBlocks, a as getTextContent } from '../message-CkN21KaY.mjs';
2
+ export { B as Base64Source, C as ContentBlock, D as DataBlock, T as TextBlock, a as ThinkingBlock, b as ToolCallBlock, c as ToolResultBlock, U as URLSource } from '../block-VsnHrllL.mjs';
3
+ import '../index-CAxQAkiP.mjs';
4
+
5
+ declare enum GenerateReason {
6
+ AWAITING_TOOL_RESULT = "AWAITING_TOOL_RESULT",
7
+ AWAITING_USER_CONFIRMATION = "AWAITING_USER_CONFIRMATION"
8
+ }
9
+
10
+ export { GenerateReason };
@@ -0,0 +1,10 @@
1
+ export { M as Msg, c as createMsg, g as getContentBlocks, a as getTextContent } from '../message-CzLeTlua.js';
2
+ export { B as Base64Source, C as ContentBlock, D as DataBlock, T as TextBlock, a as ThinkingBlock, b as ToolCallBlock, c as ToolResultBlock, U as URLSource } from '../block-VsnHrllL.js';
3
+ import '../index-CAxQAkiP.js';
4
+
5
+ declare enum GenerateReason {
6
+ AWAITING_TOOL_RESULT = "AWAITING_TOOL_RESULT",
7
+ AWAITING_USER_CONFIRMATION = "AWAITING_USER_CONFIRMATION"
8
+ }
9
+
10
+ export { GenerateReason };
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/message/index.ts
21
+ var message_exports = {};
22
+ __export(message_exports, {
23
+ GenerateReason: () => GenerateReason,
24
+ createMsg: () => createMsg,
25
+ getContentBlocks: () => getContentBlocks,
26
+ getTextContent: () => getTextContent
27
+ });
28
+ module.exports = __toCommonJS(message_exports);
29
+
30
+ // src/message/message.ts
31
+ function createMsg({
32
+ name,
33
+ content,
34
+ role,
35
+ metadata = {},
36
+ id = crypto.randomUUID(),
37
+ timestamp = (/* @__PURE__ */ new Date()).toISOString(),
38
+ usage
39
+ }) {
40
+ return { id, name, role, content, metadata, timestamp, usage };
41
+ }
42
+ function getTextContent(msg, separator = "\n") {
43
+ const textBlocks = msg.content.filter((block) => block.type === "text");
44
+ if (textBlocks.length === 0) {
45
+ return null;
46
+ }
47
+ return textBlocks.map((block) => block.text).join(separator);
48
+ }
49
+ function getContentBlocks(msg, blockType) {
50
+ if (!blockType) return msg.content;
51
+ return msg.content.filter((block) => block.type === blockType);
52
+ }
53
+
54
+ // src/message/enums.ts
55
+ var GenerateReason = /* @__PURE__ */ ((GenerateReason2) => {
56
+ GenerateReason2["AWAITING_TOOL_RESULT"] = "AWAITING_TOOL_RESULT";
57
+ GenerateReason2["AWAITING_USER_CONFIRMATION"] = "AWAITING_USER_CONFIRMATION";
58
+ return GenerateReason2;
59
+ })(GenerateReason || {});
60
+ // Annotate the CommonJS export names for ESM import in node:
61
+ 0 && (module.exports = {
62
+ GenerateReason,
63
+ createMsg,
64
+ getContentBlocks,
65
+ getTextContent
66
+ });
67
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/message/index.ts","../../src/message/message.ts","../../src/message/enums.ts"],"sourcesContent":["export { Msg, createMsg, getTextContent, getContentBlocks } from './message';\nexport {\n TextBlock,\n ThinkingBlock,\n ToolCallBlock,\n ToolResultBlock,\n ContentBlock,\n Base64Source,\n URLSource,\n DataBlock,\n} from './block';\nexport { GenerateReason } from './enums';\n","import { JSONSerializableObject } from '../type';\nimport {\n ContentBlock,\n TextBlock,\n ThinkingBlock,\n ToolResultBlock,\n ToolCallBlock,\n DataBlock,\n} from './block';\n\n/** A chat message exchanged between agents or between an agent and a model. */\nexport interface Msg {\n /** Unique identifier for the message. */\n id: string;\n /** Display name of the message sender. */\n name: string;\n /** Conversation role of the sender. */\n role: 'user' | 'assistant' | 'system';\n /** Message body. */\n content: ContentBlock[];\n /** Arbitrary key-value metadata attached to the message. */\n metadata: Record<string, JSONSerializableObject>;\n /** ISO-8601 creation timestamp. */\n timestamp: string;\n /** Usage information for the message, such as token counts. */\n usage?: {\n inputTokens: number;\n outputTokens: number;\n };\n}\n\n/**\n * Create a new {@link Msg} object, filling in `id` and `timestamp` when omitted.\n *\n * @param root0\n * @param root0.name\n * @param root0.content\n * @param root0.role\n * @param root0.metadata\n * @param root0.id\n * @param root0.timestamp\n * @param root0.usage\n * @returns A fully-populated {@link Msg} object.\n */\nexport function createMsg({\n name,\n content,\n role,\n metadata = {},\n id = crypto.randomUUID(),\n timestamp = new Date().toISOString(),\n usage,\n}: Omit<Msg, 'id' | 'timestamp' | 'metadata'> &\n Partial<Pick<Msg, 'id' | 'timestamp' | 'metadata'>>): Msg {\n return { id, name, role, content, metadata, timestamp, usage } as Msg;\n}\n\n/**\n * Extract the plain-text content from a message.\n *\n * When `content` is a string it is returned as-is. When it is an array of\n * content blocks, all {@link TextBlock} texts are joined with `separator`.\n *\n * @param msg - The message to read.\n * @param separator - String inserted between consecutive text blocks. Defaults to `'\\n'`.\n * @returns The concatenated text, or `null` when no text blocks are present.\n */\nexport function getTextContent(msg: Msg, separator: string = '\\n'): string | null {\n const textBlocks = msg.content.filter(block => block.type === 'text');\n if (textBlocks.length === 0) {\n return null;\n }\n return textBlocks.map(block => (block as TextBlock).text).join(separator);\n}\n\n/**\n * Return all content blocks from a message, regardless of type.\n *\n * When `content` is a plain string it is wrapped in a single {@link TextBlock}.\n *\n * @param msg - The message to read.\n * @returns An array of all {@link ContentBlock} objects.\n */\nexport function getContentBlocks(msg: Msg): ContentBlock[];\n/**\n * Return all {@link TextBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'text'`\n * @returns An array of {@link TextBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'text'): TextBlock[];\n/**\n * Return all {@link ThinkingBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'thinking'`\n * @returns An array of {@link ThinkingBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'thinking'): ThinkingBlock[];\n/**\n * Return all {@link DataBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'video'`\n * @returns An array of {@link DataBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'data'): DataBlock[];\n/**\n * Return all {@link ToolCallBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'tool_call'`\n * @returns An array of {@link ToolCallBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'tool_call'): ToolCallBlock[];\n/**\n * Return all {@link ToolResultBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'tool_result'`\n * @returns An array of {@link ToolResultBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'tool_result'): ToolResultBlock[];\nexport function getContentBlocks(\n msg: Msg,\n blockType?: 'text' | 'thinking' | 'data' | 'tool_call' | 'tool_result'\n): ContentBlock[] {\n if (!blockType) return msg.content;\n return msg.content.filter(block => block.type === blockType);\n}\n","export enum GenerateReason {\n AWAITING_TOOL_RESULT = 'AWAITING_TOOL_RESULT',\n AWAITING_USER_CONFIRMATION = 'AWAITING_USER_CONFIRMATION',\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC4CO,SAAS,UAAU;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW,CAAC;AAAA,EACZ,KAAK,OAAO,WAAW;AAAA,EACvB,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,EACnC;AACJ,GAC8D;AAC1D,SAAO,EAAE,IAAI,MAAM,MAAM,SAAS,UAAU,WAAW,MAAM;AACjE;AAYO,SAAS,eAAe,KAAU,YAAoB,MAAqB;AAC9E,QAAM,aAAa,IAAI,QAAQ,OAAO,WAAS,MAAM,SAAS,MAAM;AACpE,MAAI,WAAW,WAAW,GAAG;AACzB,WAAO;AAAA,EACX;AACA,SAAO,WAAW,IAAI,WAAU,MAAoB,IAAI,EAAE,KAAK,SAAS;AAC5E;AAmDO,SAAS,iBACZ,KACA,WACc;AACd,MAAI,CAAC,UAAW,QAAO,IAAI;AAC3B,SAAO,IAAI,QAAQ,OAAO,WAAS,MAAM,SAAS,SAAS;AAC/D;;;AClIO,IAAK,iBAAL,kBAAKA,oBAAL;AACH,EAAAA,gBAAA,0BAAuB;AACvB,EAAAA,gBAAA,gCAA6B;AAFrB,SAAAA;AAAA,GAAA;","names":["GenerateReason"]}
@@ -0,0 +1,37 @@
1
+ // src/message/message.ts
2
+ function createMsg({
3
+ name,
4
+ content,
5
+ role,
6
+ metadata = {},
7
+ id = crypto.randomUUID(),
8
+ timestamp = (/* @__PURE__ */ new Date()).toISOString(),
9
+ usage
10
+ }) {
11
+ return { id, name, role, content, metadata, timestamp, usage };
12
+ }
13
+ function getTextContent(msg, separator = "\n") {
14
+ const textBlocks = msg.content.filter((block) => block.type === "text");
15
+ if (textBlocks.length === 0) {
16
+ return null;
17
+ }
18
+ return textBlocks.map((block) => block.text).join(separator);
19
+ }
20
+ function getContentBlocks(msg, blockType) {
21
+ if (!blockType) return msg.content;
22
+ return msg.content.filter((block) => block.type === blockType);
23
+ }
24
+
25
+ // src/message/enums.ts
26
+ var GenerateReason = /* @__PURE__ */ ((GenerateReason2) => {
27
+ GenerateReason2["AWAITING_TOOL_RESULT"] = "AWAITING_TOOL_RESULT";
28
+ GenerateReason2["AWAITING_USER_CONFIRMATION"] = "AWAITING_USER_CONFIRMATION";
29
+ return GenerateReason2;
30
+ })(GenerateReason || {});
31
+ export {
32
+ GenerateReason,
33
+ createMsg,
34
+ getContentBlocks,
35
+ getTextContent
36
+ };
37
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/message/message.ts","../../src/message/enums.ts"],"sourcesContent":["import { JSONSerializableObject } from '../type';\nimport {\n ContentBlock,\n TextBlock,\n ThinkingBlock,\n ToolResultBlock,\n ToolCallBlock,\n DataBlock,\n} from './block';\n\n/** A chat message exchanged between agents or between an agent and a model. */\nexport interface Msg {\n /** Unique identifier for the message. */\n id: string;\n /** Display name of the message sender. */\n name: string;\n /** Conversation role of the sender. */\n role: 'user' | 'assistant' | 'system';\n /** Message body. */\n content: ContentBlock[];\n /** Arbitrary key-value metadata attached to the message. */\n metadata: Record<string, JSONSerializableObject>;\n /** ISO-8601 creation timestamp. */\n timestamp: string;\n /** Usage information for the message, such as token counts. */\n usage?: {\n inputTokens: number;\n outputTokens: number;\n };\n}\n\n/**\n * Create a new {@link Msg} object, filling in `id` and `timestamp` when omitted.\n *\n * @param root0\n * @param root0.name\n * @param root0.content\n * @param root0.role\n * @param root0.metadata\n * @param root0.id\n * @param root0.timestamp\n * @param root0.usage\n * @returns A fully-populated {@link Msg} object.\n */\nexport function createMsg({\n name,\n content,\n role,\n metadata = {},\n id = crypto.randomUUID(),\n timestamp = new Date().toISOString(),\n usage,\n}: Omit<Msg, 'id' | 'timestamp' | 'metadata'> &\n Partial<Pick<Msg, 'id' | 'timestamp' | 'metadata'>>): Msg {\n return { id, name, role, content, metadata, timestamp, usage } as Msg;\n}\n\n/**\n * Extract the plain-text content from a message.\n *\n * When `content` is a string it is returned as-is. When it is an array of\n * content blocks, all {@link TextBlock} texts are joined with `separator`.\n *\n * @param msg - The message to read.\n * @param separator - String inserted between consecutive text blocks. Defaults to `'\\n'`.\n * @returns The concatenated text, or `null` when no text blocks are present.\n */\nexport function getTextContent(msg: Msg, separator: string = '\\n'): string | null {\n const textBlocks = msg.content.filter(block => block.type === 'text');\n if (textBlocks.length === 0) {\n return null;\n }\n return textBlocks.map(block => (block as TextBlock).text).join(separator);\n}\n\n/**\n * Return all content blocks from a message, regardless of type.\n *\n * When `content` is a plain string it is wrapped in a single {@link TextBlock}.\n *\n * @param msg - The message to read.\n * @returns An array of all {@link ContentBlock} objects.\n */\nexport function getContentBlocks(msg: Msg): ContentBlock[];\n/**\n * Return all {@link TextBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'text'`\n * @returns An array of {@link TextBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'text'): TextBlock[];\n/**\n * Return all {@link ThinkingBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'thinking'`\n * @returns An array of {@link ThinkingBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'thinking'): ThinkingBlock[];\n/**\n * Return all {@link DataBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'video'`\n * @returns An array of {@link DataBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'data'): DataBlock[];\n/**\n * Return all {@link ToolCallBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'tool_call'`\n * @returns An array of {@link ToolCallBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'tool_call'): ToolCallBlock[];\n/**\n * Return all {@link ToolResultBlock} objects from a message.\n *\n * @param msg - The message to read.\n * @param blockType - `'tool_result'`\n * @returns An array of {@link ToolResultBlock} objects.\n */\nexport function getContentBlocks(msg: Msg, blockType: 'tool_result'): ToolResultBlock[];\nexport function getContentBlocks(\n msg: Msg,\n blockType?: 'text' | 'thinking' | 'data' | 'tool_call' | 'tool_result'\n): ContentBlock[] {\n if (!blockType) return msg.content;\n return msg.content.filter(block => block.type === blockType);\n}\n","export enum GenerateReason {\n AWAITING_TOOL_RESULT = 'AWAITING_TOOL_RESULT',\n AWAITING_USER_CONFIRMATION = 'AWAITING_USER_CONFIRMATION',\n}\n"],"mappings":";AA4CO,SAAS,UAAU;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW,CAAC;AAAA,EACZ,KAAK,OAAO,WAAW;AAAA,EACvB,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,EACnC;AACJ,GAC8D;AAC1D,SAAO,EAAE,IAAI,MAAM,MAAM,SAAS,UAAU,WAAW,MAAM;AACjE;AAYO,SAAS,eAAe,KAAU,YAAoB,MAAqB;AAC9E,QAAM,aAAa,IAAI,QAAQ,OAAO,WAAS,MAAM,SAAS,MAAM;AACpE,MAAI,WAAW,WAAW,GAAG;AACzB,WAAO;AAAA,EACX;AACA,SAAO,WAAW,IAAI,WAAU,MAAoB,IAAI,EAAE,KAAK,SAAS;AAC5E;AAmDO,SAAS,iBACZ,KACA,WACc;AACd,MAAI,CAAC,UAAW,QAAO,IAAI;AAC3B,SAAO,IAAI,QAAQ,OAAO,WAAS,MAAM,SAAS,SAAS;AAC/D;;;AClIO,IAAK,iBAAL,kBAAKA,oBAAL;AACH,EAAAA,gBAAA,0BAAuB;AACvB,EAAAA,gBAAA,gCAA6B;AAFrB,SAAAA;AAAA,GAAA;","names":["GenerateReason"]}