@agentrun/sdk 0.0.3 → 0.0.4

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 (130) hide show
  1. package/README.md +20 -15
  2. package/dist/agent-runtime/api/index.cjs +907 -0
  3. package/dist/agent-runtime/api/index.cjs.map +1 -0
  4. package/dist/agent-runtime/api/index.d.cts +193 -0
  5. package/dist/agent-runtime/api/index.d.ts +193 -0
  6. package/dist/agent-runtime/api/index.js +882 -0
  7. package/dist/agent-runtime/api/index.js.map +1 -0
  8. package/dist/agent-runtime/index.cjs +2528 -0
  9. package/dist/agent-runtime/index.cjs.map +1 -0
  10. package/dist/agent-runtime/index.d.cts +778 -0
  11. package/dist/agent-runtime/index.d.ts +778 -0
  12. package/dist/agent-runtime/index.js +2496 -0
  13. package/dist/agent-runtime/index.js.map +1 -0
  14. package/dist/base-K1GMfJbH.d.ts +59 -0
  15. package/dist/base-xcWt5bua.d.cts +59 -0
  16. package/dist/client-DHXxjuo3.d.ts +58 -0
  17. package/dist/client-DPUTs69s.d.cts +58 -0
  18. package/dist/config-07gMelJP.d.cts +125 -0
  19. package/dist/config-07gMelJP.d.ts +125 -0
  20. package/dist/control-api-BWD4eua5.d.cts +27 -0
  21. package/dist/control-api-d-82Sgpr.d.ts +27 -0
  22. package/dist/credential/api/index.cjs +655 -0
  23. package/dist/credential/api/index.cjs.map +1 -0
  24. package/dist/credential/api/index.d.cts +93 -0
  25. package/dist/credential/api/index.d.ts +93 -0
  26. package/dist/credential/api/index.js +630 -0
  27. package/dist/credential/api/index.js.map +1 -0
  28. package/dist/credential/index.cjs +1286 -0
  29. package/dist/credential/index.cjs.map +1 -0
  30. package/dist/credential/index.d.cts +246 -0
  31. package/dist/credential/index.d.ts +246 -0
  32. package/dist/credential/index.js +1263 -0
  33. package/dist/credential/index.js.map +1 -0
  34. package/dist/data-api-B-4h9_Vf.d.ts +166 -0
  35. package/dist/data-api-DsG-8JRQ.d.cts +166 -0
  36. package/dist/exception-DM9H2Rpo.d.cts +68 -0
  37. package/dist/exception-DM9H2Rpo.d.ts +68 -0
  38. package/dist/index.cjs +29281 -1427
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.cts +38 -4485
  41. package/dist/index.d.ts +38 -4485
  42. package/dist/index.js +29259 -1426
  43. package/dist/index.js.map +1 -1
  44. package/dist/integration/builtin/index.cjs +9399 -0
  45. package/dist/integration/builtin/index.cjs.map +1 -0
  46. package/dist/integration/builtin/index.d.cts +692 -0
  47. package/dist/integration/builtin/index.d.ts +692 -0
  48. package/dist/integration/builtin/index.js +9363 -0
  49. package/dist/integration/builtin/index.js.map +1 -0
  50. package/dist/integration/index.cjs +9524 -0
  51. package/dist/integration/index.cjs.map +1 -0
  52. package/dist/integration/index.d.cts +98 -0
  53. package/dist/integration/index.d.ts +98 -0
  54. package/dist/integration/index.js +9481 -0
  55. package/dist/integration/index.js.map +1 -0
  56. package/dist/integration/mastra/index.cjs +9383 -0
  57. package/dist/integration/mastra/index.cjs.map +1 -0
  58. package/dist/integration/mastra/index.d.cts +186 -0
  59. package/dist/integration/mastra/index.d.ts +186 -0
  60. package/dist/integration/mastra/index.js +9348 -0
  61. package/dist/integration/mastra/index.js.map +1 -0
  62. package/dist/model/index.cjs +2392 -0
  63. package/dist/model/index.cjs.map +1 -0
  64. package/dist/model/index.d.cts +97 -0
  65. package/dist/model/index.d.ts +97 -0
  66. package/dist/model/index.js +2368 -0
  67. package/dist/model/index.js.map +1 -0
  68. package/dist/model--I90nCqy.d.cts +66 -0
  69. package/dist/model--I90nCqy.d.ts +66 -0
  70. package/dist/model-BV7A6Trb.d.cts +512 -0
  71. package/dist/model-DGBy-o_L.d.cts +176 -0
  72. package/dist/model-DGBy-o_L.d.ts +176 -0
  73. package/dist/model-RiiiZnou.d.ts +512 -0
  74. package/dist/model-service-D-P2FZNi.d.ts +540 -0
  75. package/dist/model-service-VpzBb7rV.d.cts +540 -0
  76. package/dist/resource-CQovFUeh.d.cts +44 -0
  77. package/dist/resource-DnE_DEka.d.ts +44 -0
  78. package/dist/sandbox/index.cjs +3557 -0
  79. package/dist/sandbox/index.cjs.map +1 -0
  80. package/dist/sandbox/index.d.cts +1598 -0
  81. package/dist/sandbox/index.d.ts +1598 -0
  82. package/dist/sandbox/index.js +3532 -0
  83. package/dist/sandbox/index.js.map +1 -0
  84. package/dist/server/adapter/index.cjs +24886 -0
  85. package/dist/server/adapter/index.cjs.map +1 -0
  86. package/dist/server/adapter/index.d.cts +68 -0
  87. package/dist/server/adapter/index.d.ts +68 -0
  88. package/dist/server/adapter/index.js +24883 -0
  89. package/dist/server/adapter/index.js.map +1 -0
  90. package/dist/server/core/index.cjs +313 -0
  91. package/dist/server/core/index.cjs.map +1 -0
  92. package/dist/server/core/index.d.cts +58 -0
  93. package/dist/server/core/index.d.ts +58 -0
  94. package/dist/server/core/index.js +309 -0
  95. package/dist/server/core/index.js.map +1 -0
  96. package/dist/server/index.cjs +25098 -0
  97. package/dist/server/index.cjs.map +1 -0
  98. package/dist/server/index.d.cts +73 -0
  99. package/dist/server/index.d.ts +73 -0
  100. package/dist/server/index.js +25067 -0
  101. package/dist/server/index.js.map +1 -0
  102. package/dist/server/protocol/index.cjs +1057 -0
  103. package/dist/server/protocol/index.cjs.map +1 -0
  104. package/dist/server/protocol/index.d.cts +135 -0
  105. package/dist/server/protocol/index.d.ts +135 -0
  106. package/dist/server/protocol/index.js +1053 -0
  107. package/dist/server/protocol/index.js.map +1 -0
  108. package/dist/tool-CG0LY-ov.d.cts +155 -0
  109. package/dist/tool-JJHam0ms.d.ts +155 -0
  110. package/dist/toolset/api/index.cjs +754 -0
  111. package/dist/toolset/api/index.cjs.map +1 -0
  112. package/dist/toolset/api/index.d.cts +207 -0
  113. package/dist/toolset/api/index.d.ts +207 -0
  114. package/dist/toolset/api/index.js +727 -0
  115. package/dist/toolset/api/index.js.map +1 -0
  116. package/dist/toolset/index.cjs +1945 -0
  117. package/dist/toolset/index.cjs.map +1 -0
  118. package/dist/toolset/index.d.cts +182 -0
  119. package/dist/toolset/index.d.ts +182 -0
  120. package/dist/toolset/index.js +1920 -0
  121. package/dist/toolset/index.js.map +1 -0
  122. package/dist/toolset-BYDvhwRp.d.cts +394 -0
  123. package/dist/toolset-CSRsJxCb.d.ts +394 -0
  124. package/dist/utils/index.cjs +994 -0
  125. package/dist/utils/index.cjs.map +1 -0
  126. package/dist/utils/index.d.cts +30 -0
  127. package/dist/utils/index.d.ts +30 -0
  128. package/dist/utils/index.js +951 -0
  129. package/dist/utils/index.js.map +1 -0
  130. package/package.json +65 -13
@@ -0,0 +1,1057 @@
1
+ 'use strict';
2
+
3
+ var uuid = require('uuid');
4
+
5
+ // src/utils/log.ts
6
+ var LOG_LEVELS = {
7
+ debug: 0,
8
+ info: 1,
9
+ warn: 2,
10
+ error: 3
11
+ };
12
+ var COLORS = {
13
+ reset: "\x1B[0m",
14
+ bright: "\x1B[1m",
15
+ dim: "\x1B[2m",
16
+ italic: "\x1B[3m",
17
+ blue: "\x1B[34m",
18
+ cyan: "\x1B[36m",
19
+ yellow: "\x1B[33m",
20
+ red: "\x1B[31m"
21
+ };
22
+ var Logger = class {
23
+ level = "info";
24
+ // match Python logger name
25
+ prefix = "agentrun-logger";
26
+ setLevel(level) {
27
+ this.level = level;
28
+ }
29
+ shouldLog(level) {
30
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
31
+ }
32
+ getColor(level) {
33
+ switch (level) {
34
+ case "debug":
35
+ return COLORS.cyan;
36
+ case "info":
37
+ return COLORS.blue;
38
+ case "warn":
39
+ return COLORS.yellow;
40
+ case "error":
41
+ return COLORS.red;
42
+ default:
43
+ return COLORS.reset;
44
+ }
45
+ }
46
+ // format timestamp like Python: YYYY-MM-DD HH:mm:ss,SSS
47
+ formatTimestamp(d = /* @__PURE__ */ new Date()) {
48
+ const pad = (n, sz = 2) => n.toString().padStart(sz, "0");
49
+ const year = d.getFullYear();
50
+ const month = pad(d.getMonth() + 1);
51
+ const day = pad(d.getDate());
52
+ const hour = pad(d.getHours());
53
+ const minute = pad(d.getMinutes());
54
+ const second = pad(d.getSeconds());
55
+ const ms = pad(d.getMilliseconds(), 3);
56
+ return `${year}-${month}-${day} ${hour}:${minute}:${second},${ms}`;
57
+ }
58
+ // attempt to infer caller file and line by parsing Error.stack
59
+ // helper: parse a single stack frame into {filepath, line, functionName}
60
+ parseFrame(frame) {
61
+ const m = frame.match(/^(?:at\s+)?(?:(.+?)\s+\()?(.*?):(\d+):(\d+)\)?$/);
62
+ if (!m) return null;
63
+ return {
64
+ functionName: m[1] ? m[1].trim() : void 0,
65
+ filepath: m[2],
66
+ line: parseInt(m[3], 10)
67
+ };
68
+ }
69
+ // get caller by fixed stack offset (used in public log methods)
70
+ getCallerByOffset() {
71
+ const err = new Error();
72
+ const stack = err.stack;
73
+ if (!stack) return {};
74
+ const lines = stack.split("\n").map((l) => l.trim());
75
+ for (let i = 3; i < lines.length; i++) {
76
+ let parsed = this.parseFrame(lines[i]);
77
+ if (!parsed) {
78
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
79
+ if (m) {
80
+ const parts = m[1].split(":");
81
+ parts.pop();
82
+ const ln = Number(parts.pop());
83
+ const fp2 = parts.join(":");
84
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
85
+ }
86
+ }
87
+ if (!parsed) continue;
88
+ const fp = parsed.filepath;
89
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
90
+ continue;
91
+ return { filepath: parsed.filepath, line: parsed.line };
92
+ }
93
+ const cwd = process.cwd();
94
+ for (let i = 0; i < lines.length; i++) {
95
+ let parsed = this.parseFrame(lines[i]);
96
+ if (!parsed) {
97
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
98
+ if (m) {
99
+ const parts = m[1].split(":");
100
+ parts.pop();
101
+ const ln = Number(parts.pop());
102
+ const fp2 = parts.join(":");
103
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
104
+ }
105
+ }
106
+ if (!parsed) continue;
107
+ const fp = parsed.filepath;
108
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
109
+ continue;
110
+ if (fp.includes("/src/utils/log.ts")) continue;
111
+ if (fp.startsWith(cwd)) return { filepath: parsed.filepath, line: parsed.line };
112
+ }
113
+ for (let i = 0; i < lines.length; i++) {
114
+ let parsed = this.parseFrame(lines[i]);
115
+ if (!parsed) {
116
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
117
+ if (m) {
118
+ const parts = m[1].split(":");
119
+ parts.pop();
120
+ const ln = Number(parts.pop());
121
+ const fp2 = parts.join(":");
122
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
123
+ }
124
+ }
125
+ if (!parsed) continue;
126
+ const fp = parsed.filepath;
127
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
128
+ continue;
129
+ if (fp.includes("/src/utils/log.ts")) continue;
130
+ return { filepath: parsed.filepath, line: parsed.line };
131
+ }
132
+ return {};
133
+ }
134
+ formatMessage(level, message, filepath, line) {
135
+ const timestamp = this.formatTimestamp();
136
+ const color = this.getColor(level);
137
+ const reset = COLORS.reset;
138
+ const levelName = level === "warn" ? "WARNING" : level.toUpperCase();
139
+ const levelStr = `${COLORS.bright}${color}${levelName}${reset}`;
140
+ const nameStr = `${color}[${this.prefix}]${reset}`;
141
+ const tsStr = `${color} ${timestamp}${reset}`;
142
+ const pathInfo = filepath && line !== void 0 ? ` ${COLORS.dim}${COLORS.italic}${filepath}:${line}${reset}` : "";
143
+ const msg = level === "debug" ? `${COLORS.dim}${message}${reset}` : message;
144
+ return `
145
+ ${levelStr} ${nameStr}${tsStr}${pathInfo}
146
+ ${msg}
147
+ `;
148
+ }
149
+ debug(message, ...args) {
150
+ if (this.shouldLog("debug")) {
151
+ const caller = this.getCallerByOffset();
152
+ console.debug(this.formatMessage("debug", message, caller.filepath, caller.line), ...args);
153
+ }
154
+ }
155
+ info(message, ...args) {
156
+ if (this.shouldLog("info")) {
157
+ const caller = this.getCallerByOffset();
158
+ console.info(this.formatMessage("info", message, caller.filepath, caller.line), ...args);
159
+ }
160
+ }
161
+ warn(message, ...args) {
162
+ if (this.shouldLog("warn")) {
163
+ const caller = this.getCallerByOffset();
164
+ console.warn(this.formatMessage("warn", message, caller.filepath, caller.line), ...args);
165
+ }
166
+ }
167
+ error(message, ...args) {
168
+ if (this.shouldLog("error")) {
169
+ const caller = this.getCallerByOffset();
170
+ console.error(this.formatMessage("error", message, caller.filepath, caller.line), ...args);
171
+ }
172
+ }
173
+ };
174
+ var logger = new Logger();
175
+ if (![void 0, null, "", "False", "FALSE", "false", "0"].includes(process.env["AGENTRUN_SDK_DEBUG"])) {
176
+ logger.setLevel("debug");
177
+ if (!globalThis._AGENTRUN_DEBUG_LOGGED) {
178
+ logger.warn("\u542F\u7528 AgentRun SDK \u8C03\u8BD5\u65E5\u5FD7\uFF0C \u79FB\u9664 AGENTRUN_SDK_DEBUG \u73AF\u5883\u53D8\u91CF\u4EE5\u5173\u95ED");
179
+ globalThis._AGENTRUN_DEBUG_LOGGED = true;
180
+ }
181
+ } else {
182
+ logger.setLevel("info");
183
+ }
184
+
185
+ // src/utils/version-check.ts
186
+ var VERSION = "0.0.4" ;
187
+ if (!process.env.DISABLE_BREAKING_CHANGES_WARNING && !globalThis._AGENTRUN_VERSION_WARNING_SHOWN) {
188
+ globalThis._AGENTRUN_VERSION_WARNING_SHOWN = true;
189
+ logger.warn(
190
+ `\u5F53\u524D\u60A8\u6B63\u5728\u4F7F\u7528 AgentRun Python SDK \u7248\u672C ${VERSION}\u3002\u65E9\u671F\u7248\u672C\u901A\u5E38\u5305\u542B\u8BB8\u591A\u65B0\u529F\u80FD\uFF0C\u8FD9\u4E9B\u529F\u80FD\x1B[1;33m \u53EF\u80FD\u5F15\u5165\u4E0D\u517C\u5BB9\u7684\u53D8\u66F4 \x1B[0m\u3002\u4E3A\u907F\u514D\u6F5C\u5728\u95EE\u9898\uFF0C\u6211\u4EEC\u5F3A\u70C8\u5EFA\u8BAE\x1B[1;32m \u5C06\u4F9D\u8D56\u9501\u5B9A\u4E3A\u6B64\u7248\u672C \x1B[0m\u3002
191
+ You are currently using AgentRun Python SDK version ${VERSION}. Early versions often include many new features, which\x1B[1;33m may introduce breaking changes\x1B[0m. To avoid potential issues, we strongly recommend \x1B[1;32mpinning the dependency to this version\x1B[0m.
192
+ \x1B[2;3m pip install 'agentrun-sdk==${VERSION}' \x1B[0m
193
+
194
+ \u589E\u52A0\x1B[2;3m DISABLE_BREAKING_CHANGES_WARNING=1 \x1B[0m\u5230\u60A8\u7684\u73AF\u5883\u53D8\u91CF\u4EE5\u5173\u95ED\u6B64\u8B66\u544A\u3002
195
+ Add\x1B[2;3m DISABLE_BREAKING_CHANGES_WARNING=1 \x1B[0mto your environment variables to disable this warning.
196
+
197
+ Releases:\x1B[2;3m https://github.com/Serverless-Devs/agentrun-sdk-python/releases\x1B[0m`
198
+ );
199
+ }
200
+
201
+ // src/server/core/model.ts
202
+ var MessageRole = /* @__PURE__ */ ((MessageRole3) => {
203
+ MessageRole3["SYSTEM"] = "system";
204
+ MessageRole3["USER"] = "user";
205
+ MessageRole3["ASSISTANT"] = "assistant";
206
+ MessageRole3["TOOL"] = "tool";
207
+ return MessageRole3;
208
+ })(MessageRole || {});
209
+
210
+ // src/server/protocol/base.ts
211
+ var ProtocolHandler = class {
212
+ /**
213
+ * Check if a request matches this protocol
214
+ */
215
+ matches(req) {
216
+ const prefix = this.getPrefix();
217
+ return this.getRoutes().some(
218
+ (route) => route.method === req.method && this.matchPath(prefix + route.path, req.url)
219
+ );
220
+ }
221
+ /**
222
+ * Handle a request
223
+ */
224
+ async handle(req, invoker) {
225
+ const prefix = this.getPrefix();
226
+ const route = this.getRoutes().find(
227
+ (r) => r.method === req.method && this.matchPath(prefix + r.path, req.url)
228
+ );
229
+ if (!route) {
230
+ return {
231
+ status: 404,
232
+ headers: { "Content-Type": "application/json" },
233
+ body: JSON.stringify({ error: "Not Found" })
234
+ };
235
+ }
236
+ try {
237
+ return await route.handler(req, invoker);
238
+ } catch (error) {
239
+ return this.createErrorResponse(error, 500);
240
+ }
241
+ }
242
+ /**
243
+ * Create error response
244
+ */
245
+ createErrorResponse(error, status = 500) {
246
+ const message = error instanceof Error ? error.message : String(error);
247
+ return {
248
+ status,
249
+ headers: { "Content-Type": "application/json" },
250
+ body: JSON.stringify({
251
+ error: {
252
+ message,
253
+ type: "server_error"
254
+ }
255
+ })
256
+ };
257
+ }
258
+ /**
259
+ * Match path with simple pattern matching
260
+ * Supports exact match and prefix match with trailing slash
261
+ */
262
+ matchPath(pattern, path) {
263
+ const normalizedPattern = pattern.replace(/\/+$/, "");
264
+ const normalizedPath = path.replace(/\/+$/, "").split("?")[0];
265
+ return normalizedPattern === normalizedPath;
266
+ }
267
+ };
268
+
269
+ // src/server/protocol/openai.ts
270
+ var OpenAIProtocolHandler = class extends ProtocolHandler {
271
+ constructor(config) {
272
+ super();
273
+ this.config = config;
274
+ }
275
+ name = "openai";
276
+ getPrefix() {
277
+ return this.config?.prefix ?? "/openai/v1";
278
+ }
279
+ getRoutes() {
280
+ return [
281
+ {
282
+ method: "POST",
283
+ path: "/chat/completions",
284
+ handler: this.handleChatCompletions.bind(this)
285
+ },
286
+ {
287
+ method: "GET",
288
+ path: "/models",
289
+ handler: this.handleListModels.bind(this)
290
+ }
291
+ ];
292
+ }
293
+ /**
294
+ * Handle POST /chat/completions
295
+ */
296
+ async handleChatCompletions(req, invoker) {
297
+ try {
298
+ const { agentRequest, context } = this.parseRequest(req.body);
299
+ if (agentRequest.stream) {
300
+ return {
301
+ status: 200,
302
+ headers: {
303
+ "Content-Type": "text/event-stream",
304
+ "Cache-Control": "no-cache",
305
+ Connection: "keep-alive"
306
+ },
307
+ body: this.formatStream(invoker.invoke(agentRequest), context)
308
+ };
309
+ }
310
+ const events = [];
311
+ for await (const event of invoker.invoke(agentRequest)) {
312
+ events.push(event);
313
+ }
314
+ return {
315
+ status: 200,
316
+ headers: { "Content-Type": "application/json" },
317
+ body: JSON.stringify(this.formatNonStream(events, context))
318
+ };
319
+ } catch (error) {
320
+ return this.createErrorResponse(error, 400);
321
+ }
322
+ }
323
+ /**
324
+ * Handle GET /models
325
+ */
326
+ async handleListModels() {
327
+ const modelName = this.config?.modelName ?? "agentrun";
328
+ return {
329
+ status: 200,
330
+ headers: { "Content-Type": "application/json" },
331
+ body: JSON.stringify({
332
+ object: "list",
333
+ data: [
334
+ {
335
+ id: modelName,
336
+ object: "model",
337
+ created: Math.floor(Date.now() / 1e3),
338
+ owned_by: "agentrun"
339
+ }
340
+ ]
341
+ })
342
+ };
343
+ }
344
+ /**
345
+ * Parse OpenAI format request to AgentRequest
346
+ */
347
+ parseRequest(body) {
348
+ if (!body.messages || !Array.isArray(body.messages)) {
349
+ throw new Error("Missing required field: messages");
350
+ }
351
+ const context = {
352
+ id: `chatcmpl-${this.generateId()}`,
353
+ model: body.model || this.config?.modelName || "agentrun",
354
+ created: Math.floor(Date.now() / 1e3)
355
+ };
356
+ const messages = this.parseMessages(body.messages);
357
+ const tools = this.parseTools(body.tools);
358
+ const agentRequest = {
359
+ protocol: "openai",
360
+ messages,
361
+ stream: body.stream ?? false,
362
+ model: context.model,
363
+ tools: tools || void 0,
364
+ metadata: body.metadata
365
+ };
366
+ return { agentRequest, context };
367
+ }
368
+ /**
369
+ * Parse OpenAI messages to internal Message format
370
+ */
371
+ parseMessages(messages) {
372
+ return messages.map((m) => {
373
+ const msg = m;
374
+ return {
375
+ id: msg.id,
376
+ role: msg.role,
377
+ content: msg.content,
378
+ name: msg.name,
379
+ toolCallId: msg.tool_call_id,
380
+ toolCalls: msg.tool_calls ? msg.tool_calls.map((tc) => {
381
+ const call = tc;
382
+ return {
383
+ id: call.id,
384
+ type: call.type,
385
+ function: call.function
386
+ };
387
+ }) : void 0
388
+ };
389
+ });
390
+ }
391
+ /**
392
+ * Parse OpenAI tools format
393
+ */
394
+ parseTools(tools) {
395
+ if (!tools || !Array.isArray(tools)) {
396
+ return null;
397
+ }
398
+ return tools.map((t) => {
399
+ const tool = t;
400
+ return {
401
+ type: tool.type || "function",
402
+ function: tool.function
403
+ };
404
+ });
405
+ }
406
+ /**
407
+ * Format streaming response (SSE)
408
+ */
409
+ async *formatStream(events, context) {
410
+ let sentRole = false;
411
+ let hasText = false;
412
+ let toolCallIndex = -1;
413
+ const toolCallStates = /* @__PURE__ */ new Map();
414
+ let hasToolCalls = false;
415
+ for await (const event of events) {
416
+ if (event.event === "RAW" /* RAW */) {
417
+ const raw = event.data?.raw;
418
+ if (raw) {
419
+ yield raw.endsWith("\n\n") ? raw : raw.replace(/\n+$/, "") + "\n\n";
420
+ }
421
+ continue;
422
+ }
423
+ if (event.event === "TEXT" /* TEXT */) {
424
+ const delta = {};
425
+ if (!sentRole) {
426
+ delta.role = "assistant";
427
+ sentRole = true;
428
+ }
429
+ const content = event.data?.delta;
430
+ if (content) {
431
+ delta.content = content;
432
+ hasText = true;
433
+ }
434
+ yield this.buildChunk(context, { delta });
435
+ continue;
436
+ }
437
+ if (event.event === "TOOL_CALL_CHUNK" /* TOOL_CALL_CHUNK */) {
438
+ const toolId = event.data?.id;
439
+ const toolName = event.data?.name;
440
+ const argsDelta = event.data?.args_delta || event.data?.argsDelta;
441
+ if (toolId && !toolCallStates.has(toolId)) {
442
+ toolCallIndex++;
443
+ toolCallStates.set(toolId, { index: toolCallIndex, started: true });
444
+ hasToolCalls = true;
445
+ yield this.buildChunk(context, {
446
+ delta: {
447
+ tool_calls: [
448
+ {
449
+ index: toolCallIndex,
450
+ id: toolId,
451
+ type: "function",
452
+ function: { name: toolName || "", arguments: "" }
453
+ }
454
+ ]
455
+ }
456
+ });
457
+ }
458
+ if (argsDelta) {
459
+ const state = toolCallStates.get(toolId);
460
+ const currentIndex = state?.index ?? toolCallIndex;
461
+ yield this.buildChunk(context, {
462
+ delta: {
463
+ tool_calls: [
464
+ {
465
+ index: currentIndex,
466
+ function: { arguments: argsDelta }
467
+ }
468
+ ]
469
+ }
470
+ });
471
+ }
472
+ continue;
473
+ }
474
+ if (event.event === "ERROR" /* ERROR */) {
475
+ yield this.buildChunk(context, {
476
+ delta: {},
477
+ finish_reason: "error"
478
+ });
479
+ continue;
480
+ }
481
+ }
482
+ const finishReason = hasToolCalls ? "tool_calls" : hasText ? "stop" : "stop";
483
+ yield this.buildChunk(context, { delta: {}, finish_reason: finishReason });
484
+ yield "data: [DONE]\n\n";
485
+ }
486
+ /**
487
+ * Build SSE chunk
488
+ */
489
+ buildChunk(context, choice) {
490
+ const chunk = {
491
+ id: context.id,
492
+ object: "chat.completion.chunk",
493
+ created: context.created,
494
+ model: context.model,
495
+ choices: [
496
+ {
497
+ index: 0,
498
+ delta: choice.delta || {},
499
+ finish_reason: choice.finish_reason ?? null
500
+ }
501
+ ]
502
+ };
503
+ return `data: ${JSON.stringify(chunk)}
504
+
505
+ `;
506
+ }
507
+ /**
508
+ * Format non-streaming response
509
+ */
510
+ formatNonStream(events, context) {
511
+ let content = "";
512
+ const toolCalls = [];
513
+ for (const event of events) {
514
+ if (event.event === "TEXT" /* TEXT */) {
515
+ content += event.data?.delta || "";
516
+ } else if (event.event === "TOOL_CALL_CHUNK" /* TOOL_CALL_CHUNK */) {
517
+ const toolId = event.data?.id;
518
+ const toolName = event.data?.name;
519
+ const argsDelta = event.data?.args_delta || event.data?.argsDelta;
520
+ let toolCall = toolCalls.find((tc) => tc.id === toolId);
521
+ if (!toolCall && toolId) {
522
+ toolCall = {
523
+ id: toolId,
524
+ type: "function",
525
+ function: { name: toolName || "", arguments: "" }
526
+ };
527
+ toolCalls.push(toolCall);
528
+ }
529
+ if (toolCall && argsDelta) {
530
+ toolCall.function.arguments += argsDelta;
531
+ }
532
+ }
533
+ }
534
+ const message = {
535
+ role: "assistant",
536
+ content: content || null
537
+ };
538
+ if (toolCalls.length > 0) {
539
+ message.tool_calls = toolCalls.map((tc, idx) => ({
540
+ index: idx,
541
+ id: tc.id,
542
+ type: tc.type,
543
+ function: tc.function
544
+ }));
545
+ }
546
+ return {
547
+ id: context.id,
548
+ object: "chat.completion",
549
+ created: context.created,
550
+ model: context.model,
551
+ choices: [
552
+ {
553
+ index: 0,
554
+ message,
555
+ finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop"
556
+ }
557
+ ],
558
+ usage: {
559
+ prompt_tokens: 0,
560
+ completion_tokens: 0,
561
+ total_tokens: 0
562
+ }
563
+ };
564
+ }
565
+ /**
566
+ * Generate unique ID
567
+ */
568
+ generateId() {
569
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
570
+ }
571
+ };
572
+ var AGUI_EVENT_TYPES = {
573
+ RUN_STARTED: "RUN_STARTED",
574
+ RUN_FINISHED: "RUN_FINISHED",
575
+ RUN_ERROR: "RUN_ERROR",
576
+ TEXT_MESSAGE_START: "TEXT_MESSAGE_START",
577
+ TEXT_MESSAGE_CONTENT: "TEXT_MESSAGE_CONTENT",
578
+ TEXT_MESSAGE_END: "TEXT_MESSAGE_END",
579
+ TOOL_CALL_START: "TOOL_CALL_START",
580
+ TOOL_CALL_ARGS: "TOOL_CALL_ARGS",
581
+ TOOL_CALL_END: "TOOL_CALL_END",
582
+ TOOL_CALL_RESULT: "TOOL_CALL_RESULT",
583
+ STATE_SNAPSHOT: "STATE_SNAPSHOT",
584
+ STATE_DELTA: "STATE_DELTA",
585
+ MESSAGES_SNAPSHOT: "MESSAGES_SNAPSHOT",
586
+ STEP_STARTED: "STEP_STARTED",
587
+ STEP_FINISHED: "STEP_FINISHED",
588
+ CUSTOM: "CUSTOM",
589
+ RAW: "RAW"
590
+ };
591
+ var StreamState = class {
592
+ text = {
593
+ started: false,
594
+ ended: false,
595
+ messageId: uuid.v4()
596
+ };
597
+ toolCalls = /* @__PURE__ */ new Map();
598
+ toolResultChunks = /* @__PURE__ */ new Map();
599
+ hasError = false;
600
+ /**
601
+ * End all open tool calls
602
+ */
603
+ *endAllToolCalls(exclude) {
604
+ for (const [toolId, state] of this.toolCalls) {
605
+ if (exclude && toolId === exclude) continue;
606
+ if (state.started && !state.ended) {
607
+ yield { type: AGUI_EVENT_TYPES.TOOL_CALL_END, toolCallId: toolId };
608
+ state.ended = true;
609
+ }
610
+ }
611
+ }
612
+ /**
613
+ * Ensure text message has started
614
+ */
615
+ *ensureTextStarted() {
616
+ if (!this.text.started || this.text.ended) {
617
+ if (this.text.ended) {
618
+ this.text = { started: false, ended: false, messageId: uuid.v4() };
619
+ }
620
+ yield {
621
+ type: AGUI_EVENT_TYPES.TEXT_MESSAGE_START,
622
+ messageId: this.text.messageId,
623
+ role: "assistant"
624
+ };
625
+ this.text.started = true;
626
+ this.text.ended = false;
627
+ }
628
+ }
629
+ /**
630
+ * End text message if open
631
+ */
632
+ *endTextIfOpen() {
633
+ if (this.text.started && !this.text.ended) {
634
+ yield {
635
+ type: AGUI_EVENT_TYPES.TEXT_MESSAGE_END,
636
+ messageId: this.text.messageId
637
+ };
638
+ this.text.ended = true;
639
+ }
640
+ }
641
+ /**
642
+ * Cache tool result chunk
643
+ */
644
+ cacheToolResultChunk(toolId, delta) {
645
+ if (!toolId || delta === null || delta === void 0) return;
646
+ if (delta) {
647
+ const chunks = this.toolResultChunks.get(toolId) || [];
648
+ chunks.push(delta);
649
+ this.toolResultChunks.set(toolId, chunks);
650
+ }
651
+ }
652
+ /**
653
+ * Pop and concatenate cached tool result chunks
654
+ */
655
+ popToolResultChunks(toolId) {
656
+ const chunks = this.toolResultChunks.get(toolId) || [];
657
+ this.toolResultChunks.delete(toolId);
658
+ return chunks.join("");
659
+ }
660
+ };
661
+ var DEFAULT_PREFIX = "/ag-ui";
662
+ var AGUIProtocolHandler = class extends ProtocolHandler {
663
+ constructor(config) {
664
+ super();
665
+ this.config = config;
666
+ }
667
+ name = "agui";
668
+ getPrefix() {
669
+ return this.config?.prefix ?? DEFAULT_PREFIX;
670
+ }
671
+ getRoutes() {
672
+ return [
673
+ {
674
+ method: "POST",
675
+ path: "/agent",
676
+ handler: this.handleAgent.bind(this)
677
+ }
678
+ ];
679
+ }
680
+ /**
681
+ * Handle POST /agent
682
+ */
683
+ async handleAgent(req, invoker) {
684
+ try {
685
+ const { agentRequest, context } = this.parseRequest(req.body);
686
+ return {
687
+ status: 200,
688
+ headers: {
689
+ "Content-Type": "text/event-stream",
690
+ "Cache-Control": "no-cache",
691
+ Connection: "keep-alive"
692
+ },
693
+ body: this.formatStream(invoker.invoke(agentRequest), context)
694
+ };
695
+ } catch (error) {
696
+ return {
697
+ status: 200,
698
+ headers: {
699
+ "Content-Type": "text/event-stream",
700
+ "Cache-Control": "no-cache",
701
+ Connection: "keep-alive"
702
+ },
703
+ body: this.errorStream(error instanceof Error ? error.message : String(error))
704
+ };
705
+ }
706
+ }
707
+ /**
708
+ * Parse AG-UI request
709
+ */
710
+ parseRequest(body) {
711
+ const context = {
712
+ threadId: body.threadId || uuid.v4(),
713
+ runId: body.runId || uuid.v4()
714
+ };
715
+ const messages = this.parseMessages(body.messages || []);
716
+ const tools = this.parseTools(body.tools);
717
+ const agentRequest = {
718
+ protocol: "agui",
719
+ messages,
720
+ stream: true,
721
+ // AG-UI always streams
722
+ tools: tools || void 0,
723
+ model: body.model,
724
+ metadata: body.metadata
725
+ };
726
+ return { agentRequest, context };
727
+ }
728
+ /**
729
+ * Parse messages list
730
+ */
731
+ parseMessages(rawMessages) {
732
+ const messages = [];
733
+ for (const msg of rawMessages) {
734
+ if (typeof msg !== "object" || msg === null) continue;
735
+ const roleStr = msg.role || "user";
736
+ let role;
737
+ if (Object.values(MessageRole).includes(roleStr)) {
738
+ role = roleStr;
739
+ } else {
740
+ role = "user" /* USER */;
741
+ }
742
+ let toolCalls;
743
+ const rawToolCalls = msg.toolCalls;
744
+ if (rawToolCalls && Array.isArray(rawToolCalls)) {
745
+ toolCalls = rawToolCalls.map((tc) => ({
746
+ id: tc.id || "",
747
+ type: tc.type || "function",
748
+ function: tc.function || {
749
+ name: "",
750
+ arguments: ""
751
+ }
752
+ }));
753
+ }
754
+ messages.push({
755
+ id: msg.id,
756
+ role,
757
+ content: msg.content,
758
+ name: msg.name,
759
+ toolCalls,
760
+ toolCallId: msg.toolCallId
761
+ });
762
+ }
763
+ return messages;
764
+ }
765
+ /**
766
+ * Parse tools list
767
+ */
768
+ parseTools(rawTools) {
769
+ if (!rawTools || !Array.isArray(rawTools)) return null;
770
+ const tools = [];
771
+ for (const tool of rawTools) {
772
+ if (typeof tool !== "object" || tool === null) continue;
773
+ tools.push({
774
+ type: tool.type || "function",
775
+ function: tool.function || { name: "" }
776
+ });
777
+ }
778
+ return tools.length > 0 ? tools : null;
779
+ }
780
+ /**
781
+ * Format event stream as AG-UI SSE format
782
+ */
783
+ async *formatStream(events, context) {
784
+ const state = new StreamState();
785
+ yield this.encode({ type: AGUI_EVENT_TYPES.RUN_STARTED, ...context });
786
+ for await (const event of events) {
787
+ if (state.hasError) continue;
788
+ if (event.event === "ERROR" /* ERROR */) {
789
+ state.hasError = true;
790
+ }
791
+ for (const aguiEvent of this.processEvent(event, context, state)) {
792
+ yield this.encode(aguiEvent);
793
+ }
794
+ }
795
+ if (state.hasError) return;
796
+ for (const event of state.endAllToolCalls()) {
797
+ yield this.encode(event);
798
+ }
799
+ for (const event of state.endTextIfOpen()) {
800
+ yield this.encode(event);
801
+ }
802
+ yield this.encode({ type: AGUI_EVENT_TYPES.RUN_FINISHED, ...context });
803
+ }
804
+ /**
805
+ * Process single event and yield AG-UI events
806
+ */
807
+ *processEvent(event, context, state) {
808
+ if (event.event === "RAW" /* RAW */) {
809
+ const raw = event.data?.raw;
810
+ if (raw) {
811
+ yield { __raw: raw };
812
+ }
813
+ return;
814
+ }
815
+ if (event.event === "TEXT" /* TEXT */) {
816
+ yield* state.endAllToolCalls();
817
+ yield* state.ensureTextStarted();
818
+ const aguiEvent = {
819
+ type: AGUI_EVENT_TYPES.TEXT_MESSAGE_CONTENT,
820
+ messageId: state.text.messageId,
821
+ delta: event.data?.delta || ""
822
+ };
823
+ if (event.addition) {
824
+ yield this.applyAddition(aguiEvent, event.addition, event.additionMergeOptions);
825
+ } else {
826
+ yield aguiEvent;
827
+ }
828
+ return;
829
+ }
830
+ if (event.event === "TOOL_CALL_CHUNK" /* TOOL_CALL_CHUNK */) {
831
+ const toolId = event.data?.id || "";
832
+ const toolName = event.data?.name || "";
833
+ yield* state.endTextIfOpen();
834
+ const currentState = state.toolCalls.get(toolId);
835
+ if (toolId && (!currentState || currentState.ended)) {
836
+ yield {
837
+ type: AGUI_EVENT_TYPES.TOOL_CALL_START,
838
+ toolCallId: toolId,
839
+ toolCallName: toolName
840
+ };
841
+ state.toolCalls.set(toolId, {
842
+ name: toolName,
843
+ started: true,
844
+ ended: false,
845
+ hasResult: false,
846
+ isHitl: false
847
+ });
848
+ }
849
+ yield {
850
+ type: AGUI_EVENT_TYPES.TOOL_CALL_ARGS,
851
+ toolCallId: toolId,
852
+ delta: event.data?.args_delta || event.data?.argsDelta || ""
853
+ };
854
+ return;
855
+ }
856
+ if (event.event === "TOOL_CALL" /* TOOL_CALL */) {
857
+ const toolId = event.data?.id || "";
858
+ const toolName = event.data?.name || "";
859
+ const toolArgs = event.data?.args || "";
860
+ yield* state.endTextIfOpen();
861
+ const currentState = state.toolCalls.get(toolId);
862
+ if (toolId && (!currentState || currentState.ended)) {
863
+ yield {
864
+ type: AGUI_EVENT_TYPES.TOOL_CALL_START,
865
+ toolCallId: toolId,
866
+ toolCallName: toolName
867
+ };
868
+ state.toolCalls.set(toolId, {
869
+ name: toolName,
870
+ started: true,
871
+ ended: false,
872
+ hasResult: false,
873
+ isHitl: false
874
+ });
875
+ }
876
+ if (toolArgs) {
877
+ yield {
878
+ type: AGUI_EVENT_TYPES.TOOL_CALL_ARGS,
879
+ toolCallId: toolId,
880
+ delta: toolArgs
881
+ };
882
+ }
883
+ return;
884
+ }
885
+ if (event.event === "TOOL_RESULT_CHUNK" /* TOOL_RESULT_CHUNK */) {
886
+ const toolId = event.data?.id || "";
887
+ const delta = event.data?.delta || "";
888
+ state.cacheToolResultChunk(toolId, delta);
889
+ return;
890
+ }
891
+ if (event.event === "HITL" /* HITL */) {
892
+ const hitlId = event.data?.id || "";
893
+ const toolCallId = event.data?.tool_call_id || event.data?.toolCallId || "";
894
+ const hitlType = event.data?.type || "confirmation";
895
+ const prompt = event.data?.prompt || "";
896
+ yield* state.endTextIfOpen();
897
+ if (toolCallId && state.toolCalls.has(toolCallId)) {
898
+ const toolState = state.toolCalls.get(toolCallId);
899
+ if (toolState.started && !toolState.ended) {
900
+ yield { type: AGUI_EVENT_TYPES.TOOL_CALL_END, toolCallId };
901
+ toolState.ended = true;
902
+ }
903
+ toolState.isHitl = true;
904
+ toolState.hasResult = false;
905
+ return;
906
+ }
907
+ const argsDict = { type: hitlType, prompt };
908
+ if (event.data?.options) argsDict.options = event.data.options;
909
+ if (event.data?.default !== void 0) argsDict.default = event.data.default;
910
+ if (event.data?.timeout !== void 0) argsDict.timeout = event.data.timeout;
911
+ if (event.data?.schema) argsDict.schema = event.data.schema;
912
+ const actualId = toolCallId || hitlId;
913
+ yield {
914
+ type: AGUI_EVENT_TYPES.TOOL_CALL_START,
915
+ toolCallId: actualId,
916
+ toolCallName: `hitl_${hitlType}`
917
+ };
918
+ yield {
919
+ type: AGUI_EVENT_TYPES.TOOL_CALL_ARGS,
920
+ toolCallId: actualId,
921
+ delta: JSON.stringify(argsDict)
922
+ };
923
+ yield { type: AGUI_EVENT_TYPES.TOOL_CALL_END, toolCallId: actualId };
924
+ state.toolCalls.set(actualId, {
925
+ name: `hitl_${hitlType}`,
926
+ started: true,
927
+ ended: true,
928
+ hasResult: false,
929
+ isHitl: true
930
+ });
931
+ return;
932
+ }
933
+ if (event.event === "TOOL_RESULT" /* TOOL_RESULT */) {
934
+ const toolId = event.data?.id || "";
935
+ const toolName = event.data?.name || "";
936
+ yield* state.endTextIfOpen();
937
+ let toolState = state.toolCalls.get(toolId);
938
+ if (toolId && !toolState) {
939
+ yield {
940
+ type: AGUI_EVENT_TYPES.TOOL_CALL_START,
941
+ toolCallId: toolId,
942
+ toolCallName: toolName
943
+ };
944
+ toolState = {
945
+ name: toolName,
946
+ started: true,
947
+ ended: false,
948
+ hasResult: false,
949
+ isHitl: false
950
+ };
951
+ state.toolCalls.set(toolId, toolState);
952
+ }
953
+ if (toolState && toolState.started && !toolState.ended) {
954
+ yield { type: AGUI_EVENT_TYPES.TOOL_CALL_END, toolCallId: toolId };
955
+ toolState.ended = true;
956
+ }
957
+ let finalResult = (event.data?.content || event.data?.result) ?? "";
958
+ if (toolId) {
959
+ const cachedChunks = state.popToolResultChunks(toolId);
960
+ if (cachedChunks) {
961
+ finalResult = cachedChunks + finalResult;
962
+ }
963
+ }
964
+ yield {
965
+ type: AGUI_EVENT_TYPES.TOOL_CALL_RESULT,
966
+ messageId: event.data?.message_id || event.data?.messageId || `tool-result-${toolId}`,
967
+ toolCallId: toolId,
968
+ content: finalResult,
969
+ role: "tool"
970
+ };
971
+ return;
972
+ }
973
+ if (event.event === "ERROR" /* ERROR */) {
974
+ yield {
975
+ type: AGUI_EVENT_TYPES.RUN_ERROR,
976
+ message: event.data?.message || "",
977
+ code: event.data?.code
978
+ };
979
+ return;
980
+ }
981
+ if (event.event === "STATE" /* STATE */) {
982
+ if ("snapshot" in (event.data || {})) {
983
+ yield {
984
+ type: AGUI_EVENT_TYPES.STATE_SNAPSHOT,
985
+ snapshot: event.data?.snapshot || {}
986
+ };
987
+ } else if ("delta" in (event.data || {})) {
988
+ yield {
989
+ type: AGUI_EVENT_TYPES.STATE_DELTA,
990
+ delta: event.data?.delta || []
991
+ };
992
+ } else {
993
+ yield {
994
+ type: AGUI_EVENT_TYPES.STATE_SNAPSHOT,
995
+ snapshot: event.data || {}
996
+ };
997
+ }
998
+ return;
999
+ }
1000
+ if (event.event === "CUSTOM" /* CUSTOM */) {
1001
+ yield {
1002
+ type: AGUI_EVENT_TYPES.CUSTOM,
1003
+ name: event.data?.name || "custom",
1004
+ value: event.data?.value
1005
+ };
1006
+ return;
1007
+ }
1008
+ yield {
1009
+ type: AGUI_EVENT_TYPES.CUSTOM,
1010
+ name: event.event || "unknown",
1011
+ value: event.data
1012
+ };
1013
+ }
1014
+ /**
1015
+ * Encode event to SSE format
1016
+ */
1017
+ encode(event) {
1018
+ if ("__raw" in event) {
1019
+ const raw = event.__raw;
1020
+ return raw.endsWith("\n\n") ? raw : raw.replace(/\n+$/, "") + "\n\n";
1021
+ }
1022
+ return `data: ${JSON.stringify(event)}
1023
+
1024
+ `;
1025
+ }
1026
+ /**
1027
+ * Apply addition fields
1028
+ */
1029
+ applyAddition(eventData, addition, mergeOptions) {
1030
+ if (!addition) return eventData;
1031
+ const result = { ...eventData };
1032
+ for (const [key, value] of Object.entries(addition)) {
1033
+ if (mergeOptions?.noNewField && !(key in eventData)) continue;
1034
+ result[key] = value;
1035
+ }
1036
+ return result;
1037
+ }
1038
+ /**
1039
+ * Generate error stream
1040
+ */
1041
+ async *errorStream(message) {
1042
+ const threadId = uuid.v4();
1043
+ const runId = uuid.v4();
1044
+ yield this.encode({ type: AGUI_EVENT_TYPES.RUN_STARTED, threadId, runId });
1045
+ yield this.encode({
1046
+ type: AGUI_EVENT_TYPES.RUN_ERROR,
1047
+ message,
1048
+ code: "REQUEST_ERROR"
1049
+ });
1050
+ }
1051
+ };
1052
+
1053
+ exports.AGUIProtocolHandler = AGUIProtocolHandler;
1054
+ exports.AGUI_EVENT_TYPES = AGUI_EVENT_TYPES;
1055
+ exports.OpenAIProtocolHandler = OpenAIProtocolHandler;
1056
+ //# sourceMappingURL=index.cjs.map
1057
+ //# sourceMappingURL=index.cjs.map