@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,754 @@
1
+ 'use strict';
2
+
3
+ var $Devs = require('@alicloud/devs20230714');
4
+ var $OpenApi = require('@alicloud/openapi-client');
5
+ var $Util = require('@alicloud/tea-util');
6
+ var dotenv = require('dotenv');
7
+
8
+ function _interopNamespace(e) {
9
+ if (e && e.__esModule) return e;
10
+ var n = Object.create(null);
11
+ if (e) {
12
+ Object.keys(e).forEach(function (k) {
13
+ if (k !== 'default') {
14
+ var d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: function () { return e[k]; }
18
+ });
19
+ }
20
+ });
21
+ }
22
+ n.default = e;
23
+ return Object.freeze(n);
24
+ }
25
+
26
+ var $Devs__namespace = /*#__PURE__*/_interopNamespace($Devs);
27
+ var $OpenApi__namespace = /*#__PURE__*/_interopNamespace($OpenApi);
28
+ var $Util__namespace = /*#__PURE__*/_interopNamespace($Util);
29
+ var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
30
+
31
+ // src/utils/log.ts
32
+ var LOG_LEVELS = {
33
+ debug: 0,
34
+ info: 1,
35
+ warn: 2,
36
+ error: 3
37
+ };
38
+ var COLORS = {
39
+ reset: "\x1B[0m",
40
+ bright: "\x1B[1m",
41
+ dim: "\x1B[2m",
42
+ italic: "\x1B[3m",
43
+ blue: "\x1B[34m",
44
+ cyan: "\x1B[36m",
45
+ yellow: "\x1B[33m",
46
+ red: "\x1B[31m"
47
+ };
48
+ var Logger = class {
49
+ level = "info";
50
+ // match Python logger name
51
+ prefix = "agentrun-logger";
52
+ setLevel(level) {
53
+ this.level = level;
54
+ }
55
+ shouldLog(level) {
56
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
57
+ }
58
+ getColor(level) {
59
+ switch (level) {
60
+ case "debug":
61
+ return COLORS.cyan;
62
+ case "info":
63
+ return COLORS.blue;
64
+ case "warn":
65
+ return COLORS.yellow;
66
+ case "error":
67
+ return COLORS.red;
68
+ default:
69
+ return COLORS.reset;
70
+ }
71
+ }
72
+ // format timestamp like Python: YYYY-MM-DD HH:mm:ss,SSS
73
+ formatTimestamp(d = /* @__PURE__ */ new Date()) {
74
+ const pad = (n, sz = 2) => n.toString().padStart(sz, "0");
75
+ const year = d.getFullYear();
76
+ const month = pad(d.getMonth() + 1);
77
+ const day = pad(d.getDate());
78
+ const hour = pad(d.getHours());
79
+ const minute = pad(d.getMinutes());
80
+ const second = pad(d.getSeconds());
81
+ const ms = pad(d.getMilliseconds(), 3);
82
+ return `${year}-${month}-${day} ${hour}:${minute}:${second},${ms}`;
83
+ }
84
+ // attempt to infer caller file and line by parsing Error.stack
85
+ // helper: parse a single stack frame into {filepath, line, functionName}
86
+ parseFrame(frame) {
87
+ const m = frame.match(/^(?:at\s+)?(?:(.+?)\s+\()?(.*?):(\d+):(\d+)\)?$/);
88
+ if (!m) return null;
89
+ return {
90
+ functionName: m[1] ? m[1].trim() : void 0,
91
+ filepath: m[2],
92
+ line: parseInt(m[3], 10)
93
+ };
94
+ }
95
+ // get caller by fixed stack offset (used in public log methods)
96
+ getCallerByOffset() {
97
+ const err = new Error();
98
+ const stack = err.stack;
99
+ if (!stack) return {};
100
+ const lines = stack.split("\n").map((l) => l.trim());
101
+ for (let i = 3; i < lines.length; i++) {
102
+ let parsed = this.parseFrame(lines[i]);
103
+ if (!parsed) {
104
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
105
+ if (m) {
106
+ const parts = m[1].split(":");
107
+ parts.pop();
108
+ const ln = Number(parts.pop());
109
+ const fp2 = parts.join(":");
110
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
111
+ }
112
+ }
113
+ if (!parsed) continue;
114
+ const fp = parsed.filepath;
115
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
116
+ continue;
117
+ return { filepath: parsed.filepath, line: parsed.line };
118
+ }
119
+ const cwd = process.cwd();
120
+ for (let i = 0; i < lines.length; i++) {
121
+ let parsed = this.parseFrame(lines[i]);
122
+ if (!parsed) {
123
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
124
+ if (m) {
125
+ const parts = m[1].split(":");
126
+ parts.pop();
127
+ const ln = Number(parts.pop());
128
+ const fp2 = parts.join(":");
129
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
130
+ }
131
+ }
132
+ if (!parsed) continue;
133
+ const fp = parsed.filepath;
134
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
135
+ continue;
136
+ if (fp.includes("/src/utils/log.ts")) continue;
137
+ if (fp.startsWith(cwd)) return { filepath: parsed.filepath, line: parsed.line };
138
+ }
139
+ for (let i = 0; i < lines.length; i++) {
140
+ let parsed = this.parseFrame(lines[i]);
141
+ if (!parsed) {
142
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
143
+ if (m) {
144
+ const parts = m[1].split(":");
145
+ parts.pop();
146
+ const ln = Number(parts.pop());
147
+ const fp2 = parts.join(":");
148
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
149
+ }
150
+ }
151
+ if (!parsed) continue;
152
+ const fp = parsed.filepath;
153
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
154
+ continue;
155
+ if (fp.includes("/src/utils/log.ts")) continue;
156
+ return { filepath: parsed.filepath, line: parsed.line };
157
+ }
158
+ return {};
159
+ }
160
+ formatMessage(level, message, filepath, line) {
161
+ const timestamp = this.formatTimestamp();
162
+ const color = this.getColor(level);
163
+ const reset = COLORS.reset;
164
+ const levelName = level === "warn" ? "WARNING" : level.toUpperCase();
165
+ const levelStr = `${COLORS.bright}${color}${levelName}${reset}`;
166
+ const nameStr = `${color}[${this.prefix}]${reset}`;
167
+ const tsStr = `${color} ${timestamp}${reset}`;
168
+ const pathInfo = filepath && line !== void 0 ? ` ${COLORS.dim}${COLORS.italic}${filepath}:${line}${reset}` : "";
169
+ const msg = level === "debug" ? `${COLORS.dim}${message}${reset}` : message;
170
+ return `
171
+ ${levelStr} ${nameStr}${tsStr}${pathInfo}
172
+ ${msg}
173
+ `;
174
+ }
175
+ debug(message, ...args) {
176
+ if (this.shouldLog("debug")) {
177
+ const caller = this.getCallerByOffset();
178
+ console.debug(this.formatMessage("debug", message, caller.filepath, caller.line), ...args);
179
+ }
180
+ }
181
+ info(message, ...args) {
182
+ if (this.shouldLog("info")) {
183
+ const caller = this.getCallerByOffset();
184
+ console.info(this.formatMessage("info", message, caller.filepath, caller.line), ...args);
185
+ }
186
+ }
187
+ warn(message, ...args) {
188
+ if (this.shouldLog("warn")) {
189
+ const caller = this.getCallerByOffset();
190
+ console.warn(this.formatMessage("warn", message, caller.filepath, caller.line), ...args);
191
+ }
192
+ }
193
+ error(message, ...args) {
194
+ if (this.shouldLog("error")) {
195
+ const caller = this.getCallerByOffset();
196
+ console.error(this.formatMessage("error", message, caller.filepath, caller.line), ...args);
197
+ }
198
+ }
199
+ };
200
+ var logger = new Logger();
201
+ if (![void 0, null, "", "False", "FALSE", "false", "0"].includes(process.env["AGENTRUN_SDK_DEBUG"])) {
202
+ logger.setLevel("debug");
203
+ if (!globalThis._AGENTRUN_DEBUG_LOGGED) {
204
+ logger.warn("\u542F\u7528 AgentRun SDK \u8C03\u8BD5\u65E5\u5FD7\uFF0C \u79FB\u9664 AGENTRUN_SDK_DEBUG \u73AF\u5883\u53D8\u91CF\u4EE5\u5173\u95ED");
205
+ globalThis._AGENTRUN_DEBUG_LOGGED = true;
206
+ }
207
+ } else {
208
+ logger.setLevel("info");
209
+ }
210
+
211
+ // src/utils/version-check.ts
212
+ var VERSION = "0.0.4" ;
213
+ if (!process.env.DISABLE_BREAKING_CHANGES_WARNING && !globalThis._AGENTRUN_VERSION_WARNING_SHOWN) {
214
+ globalThis._AGENTRUN_VERSION_WARNING_SHOWN = true;
215
+ logger.warn(
216
+ `\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
217
+ 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.
218
+ \x1B[2;3m pip install 'agentrun-sdk==${VERSION}' \x1B[0m
219
+
220
+ \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
221
+ Add\x1B[2;3m DISABLE_BREAKING_CHANGES_WARNING=1 \x1B[0mto your environment variables to disable this warning.
222
+
223
+ Releases:\x1B[2;3m https://github.com/Serverless-Devs/agentrun-sdk-python/releases\x1B[0m`
224
+ );
225
+ }
226
+ dotenv__namespace.config();
227
+ function getEnvWithDefault(defaultValue, ...keys) {
228
+ for (const key of keys) {
229
+ const value = process.env[key];
230
+ if (value !== void 0 && value !== "") {
231
+ return value;
232
+ }
233
+ }
234
+ return defaultValue;
235
+ }
236
+ var Config = class _Config {
237
+ _accessKeyId;
238
+ _accessKeySecret;
239
+ _securityToken;
240
+ _accountId;
241
+ _token;
242
+ _regionId;
243
+ _timeout;
244
+ _readTimeout;
245
+ _controlEndpoint;
246
+ _dataEndpoint;
247
+ _devsEndpoint;
248
+ _headers;
249
+ constructor(options = {}) {
250
+ this._accessKeyId = options.accessKeyId ?? getEnvWithDefault("", "AGENTRUN_ACCESS_KEY_ID", "ALIBABA_CLOUD_ACCESS_KEY_ID");
251
+ this._accessKeySecret = options.accessKeySecret ?? getEnvWithDefault("", "AGENTRUN_ACCESS_KEY_SECRET", "ALIBABA_CLOUD_ACCESS_KEY_SECRET");
252
+ this._securityToken = options.securityToken ?? getEnvWithDefault("", "AGENTRUN_SECURITY_TOKEN", "ALIBABA_CLOUD_SECURITY_TOKEN");
253
+ this._accountId = options.accountId ?? getEnvWithDefault("", "AGENTRUN_ACCOUNT_ID", "FC_ACCOUNT_ID");
254
+ this._token = options.token;
255
+ this._regionId = options.regionId ?? getEnvWithDefault("cn-hangzhou", "AGENTRUN_REGION", "FC_REGION");
256
+ this._timeout = options.timeout ?? 6e5;
257
+ this._readTimeout = options.readTimeout ?? 1e8;
258
+ this._controlEndpoint = options.controlEndpoint ?? getEnvWithDefault("", "AGENTRUN_CONTROL_ENDPOINT");
259
+ this._dataEndpoint = options.dataEndpoint ?? getEnvWithDefault("", "AGENTRUN_DATA_ENDPOINT");
260
+ this._devsEndpoint = options.devsEndpoint ?? getEnvWithDefault("", "DEVS_ENDPOINT");
261
+ this._headers = options.headers ?? {};
262
+ }
263
+ /**
264
+ * Create a new Config by merging multiple configs.
265
+ * Later configs take precedence.
266
+ */
267
+ static withConfigs(...configs) {
268
+ return new _Config().update(...configs);
269
+ }
270
+ /**
271
+ * Update this config with values from other configs.
272
+ * Non-undefined values from later configs take precedence.
273
+ */
274
+ update(...configs) {
275
+ for (const config2 of configs) {
276
+ if (!config2) continue;
277
+ if (config2._accessKeyId) this._accessKeyId = config2._accessKeyId;
278
+ if (config2._accessKeySecret) this._accessKeySecret = config2._accessKeySecret;
279
+ if (config2._securityToken) this._securityToken = config2._securityToken;
280
+ if (config2._accountId) this._accountId = config2._accountId;
281
+ if (config2._token) this._token = config2._token;
282
+ if (config2._regionId) this._regionId = config2._regionId;
283
+ if (config2._timeout) this._timeout = config2._timeout;
284
+ if (config2._readTimeout) this._readTimeout = config2._readTimeout;
285
+ if (config2._controlEndpoint) this._controlEndpoint = config2._controlEndpoint;
286
+ if (config2._dataEndpoint) this._dataEndpoint = config2._dataEndpoint;
287
+ if (config2._devsEndpoint) this._devsEndpoint = config2._devsEndpoint;
288
+ if (config2._headers && Object.keys(config2._headers).length > 0) {
289
+ this._headers = { ...this._headers, ...config2._headers };
290
+ }
291
+ }
292
+ return this;
293
+ }
294
+ get accessKeyId() {
295
+ return this._accessKeyId;
296
+ }
297
+ get accessKeySecret() {
298
+ return this._accessKeySecret;
299
+ }
300
+ get securityToken() {
301
+ return this._securityToken;
302
+ }
303
+ get accountId() {
304
+ if (!this._accountId) {
305
+ throw new Error(
306
+ "Account ID is not set. Please add AGENTRUN_ACCOUNT_ID environment variable or set it in code."
307
+ );
308
+ }
309
+ return this._accountId;
310
+ }
311
+ get token() {
312
+ return this._token;
313
+ }
314
+ get regionId() {
315
+ return this._regionId || "cn-hangzhou";
316
+ }
317
+ get timeout() {
318
+ return this._timeout || 6e5;
319
+ }
320
+ get readTimeout() {
321
+ return this._readTimeout || 1e8;
322
+ }
323
+ get controlEndpoint() {
324
+ if (this._controlEndpoint) {
325
+ return this._controlEndpoint;
326
+ }
327
+ return `https://agentrun.${this.regionId}.aliyuncs.com`;
328
+ }
329
+ get dataEndpoint() {
330
+ if (this._dataEndpoint) {
331
+ return this._dataEndpoint;
332
+ }
333
+ return `https://${this.accountId}.agentrun-data.${this.regionId}.aliyuncs.com`;
334
+ }
335
+ get devsEndpoint() {
336
+ if (this._devsEndpoint) {
337
+ return this._devsEndpoint;
338
+ }
339
+ return `https://devs.${this.regionId}.aliyuncs.com`;
340
+ }
341
+ get headers() {
342
+ return this._headers;
343
+ }
344
+ };
345
+
346
+ // src/utils/exception.ts
347
+ var AgentRunError = class _AgentRunError extends Error {
348
+ constructor(message) {
349
+ super(message);
350
+ this.name = "AgentRunError";
351
+ Object.setPrototypeOf(this, _AgentRunError.prototype);
352
+ }
353
+ };
354
+ var HTTPError = class _HTTPError extends AgentRunError {
355
+ statusCode;
356
+ requestId;
357
+ errorCode;
358
+ constructor(statusCode, message, options) {
359
+ super(message);
360
+ this.name = "HTTPError";
361
+ this.statusCode = statusCode;
362
+ this.requestId = options?.requestId;
363
+ this.errorCode = options?.errorCode;
364
+ Object.setPrototypeOf(this, _HTTPError.prototype);
365
+ }
366
+ /**
367
+ * Convert HTTP error to resource-specific error based on status code
368
+ */
369
+ toResourceError(resourceType, resourceId) {
370
+ if (this.statusCode == 404) return new ResourceNotExistError(resourceType, resourceId);
371
+ else if (this.statusCode == 409) return new ResourceAlreadyExistError(resourceType, resourceId);
372
+ else if ((this.statusCode == 400 || this.statusCode == 500) && this.message.includes("already exists"))
373
+ return new ResourceAlreadyExistError(resourceType, resourceId);
374
+ else return this;
375
+ }
376
+ };
377
+ var ClientError = class _ClientError extends HTTPError {
378
+ constructor(statusCode, message, options) {
379
+ super(statusCode, message, options);
380
+ this.name = "ClientError";
381
+ Object.setPrototypeOf(this, _ClientError.prototype);
382
+ }
383
+ };
384
+ var ServerError = class _ServerError extends HTTPError {
385
+ constructor(statusCode, message, options) {
386
+ super(statusCode, message, options);
387
+ this.name = "ServerError";
388
+ Object.setPrototypeOf(this, _ServerError.prototype);
389
+ }
390
+ };
391
+ var ResourceNotExistError = class _ResourceNotExistError extends ClientError {
392
+ resourceType;
393
+ resourceId;
394
+ constructor(resourceType, resourceId, options) {
395
+ const message = resourceId ? `${resourceType} '${resourceId}' does not exist` : `${resourceType} does not exist`;
396
+ super(404, message, options);
397
+ this.name = "ResourceNotExistError";
398
+ this.resourceType = resourceType;
399
+ this.resourceId = resourceId;
400
+ Object.setPrototypeOf(this, _ResourceNotExistError.prototype);
401
+ }
402
+ };
403
+ var ResourceAlreadyExistError = class _ResourceAlreadyExistError extends ClientError {
404
+ resourceType;
405
+ resourceId;
406
+ constructor(resourceType, resourceId, options) {
407
+ const message = resourceId ? `${resourceType} '${resourceId}' already exists` : `${resourceType} already exists`;
408
+ super(409, message, options);
409
+ this.name = "ResourceAlreadyExistError";
410
+ this.resourceType = resourceType;
411
+ this.resourceId = resourceId;
412
+ Object.setPrototypeOf(this, _ResourceAlreadyExistError.prototype);
413
+ }
414
+ };
415
+
416
+ // src/toolset/api/control.ts
417
+ var $DevsClient = (
418
+ // @ts-expect-error - ESM interop: default.default exists when imported as ESM namespace
419
+ $Devs__namespace.default?.default ?? $Devs__namespace.default ?? $Devs__namespace
420
+ );
421
+ var ToolControlAPI = class {
422
+ config;
423
+ /**
424
+ * Initialize API client
425
+ * 初始化 API 客户端
426
+ *
427
+ * @param config - Global configuration object / 全局配置对象
428
+ */
429
+ constructor(config2) {
430
+ this.config = config2;
431
+ }
432
+ /**
433
+ * Get DevS client
434
+ * 获取 DevS 客户端
435
+ */
436
+ getDevsClient(config2) {
437
+ const cfg = Config.withConfigs(this.config, config2);
438
+ let endpoint = cfg.devsEndpoint;
439
+ if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
440
+ endpoint = endpoint.split("://")[1];
441
+ }
442
+ const openApiConfig = new $OpenApi__namespace.Config({
443
+ accessKeyId: cfg.accessKeyId,
444
+ accessKeySecret: cfg.accessKeySecret,
445
+ securityToken: cfg.securityToken || void 0,
446
+ regionId: cfg.regionId,
447
+ endpoint,
448
+ connectTimeout: cfg.timeout
449
+ });
450
+ return new $DevsClient(openApiConfig);
451
+ }
452
+ /**
453
+ * Get toolset
454
+ * 获取工具
455
+ *
456
+ * @param name - Tool name / Tool 名称
457
+ * @param headers - Request headers / 请求头
458
+ * @param config - Configuration / 配置
459
+ * @returns Toolset object / ToolSet 对象
460
+ * @throws AgentRuntimeError - Throws on call failure / 调用失败时抛出
461
+ * @throws ClientError - Client error / 客户端错误
462
+ * @throws ServerError - Server error / 服务器错误
463
+ */
464
+ getToolset = async (params) => {
465
+ const { name, headers, config: config2 } = params;
466
+ try {
467
+ const client = this.getDevsClient(config2);
468
+ const runtime = new $Util__namespace.RuntimeOptions({});
469
+ const response = await client.getToolsetWithOptions(name, headers || {}, runtime);
470
+ logger.debug(`API getToolset called, Request ID: ${response.body?.requestId}`);
471
+ if (!response.body) {
472
+ throw new Error("Empty response body");
473
+ }
474
+ return response.body;
475
+ } catch (error) {
476
+ if (error instanceof HTTPError) {
477
+ throw error.toResourceError("ToolSet", name);
478
+ }
479
+ this.handleError(error, name);
480
+ }
481
+ };
482
+ /**
483
+ * List toolsets
484
+ * 枚举 ToolSets
485
+ *
486
+ * @param input - List configuration / 枚举的配置
487
+ * @param headers - Request headers / 请求头
488
+ * @param config - Configuration / 配置
489
+ * @returns ToolSet list / ToolSet 列表
490
+ * @throws AgentRuntimeError - Throws on call failure / 调用失败时抛出
491
+ * @throws ClientError - Client error / 客户端错误
492
+ * @throws ServerError - Server error / 服务器错误
493
+ */
494
+ listToolsets = async (params) => {
495
+ const { input, headers, config: config2 } = params;
496
+ try {
497
+ const client = this.getDevsClient(config2);
498
+ const runtime = new $Util__namespace.RuntimeOptions({});
499
+ const response = await client.listToolsetsWithOptions(input, headers || {}, runtime);
500
+ logger.debug(
501
+ `API listToolsets called, Request ID: ${response?.headers?.["x-acs-request-id"]}`
502
+ );
503
+ if (!response.body) {
504
+ throw new Error("Empty response body");
505
+ }
506
+ return response.body;
507
+ } catch (error) {
508
+ this.handleError(error);
509
+ }
510
+ };
511
+ /**
512
+ * Create toolset
513
+ * 创建工具集
514
+ *
515
+ * @param input - Toolset input / ToolSet 输入
516
+ * @param headers - Request headers / 请求头
517
+ * @param config - Configuration / 配置
518
+ * @returns Toolset object / ToolSet 对象
519
+ */
520
+ createToolset = async (params) => {
521
+ const { input, headers, config: config2 } = params;
522
+ try {
523
+ const client = this.getDevsClient(config2);
524
+ const runtime = new $Util__namespace.RuntimeOptions({});
525
+ const response = await client.createToolsetWithOptions(
526
+ new $Devs__namespace.CreateToolsetRequest({ body: input }),
527
+ headers || {},
528
+ runtime
529
+ );
530
+ logger.debug(`API createToolset called, Request ID: ${response.body?.requestId}`);
531
+ if (!response.body) {
532
+ throw new Error("Empty response body");
533
+ }
534
+ return response.body;
535
+ } catch (error) {
536
+ this.handleError(error, input?.name);
537
+ }
538
+ };
539
+ /**
540
+ * Update toolset
541
+ * 更新工具集
542
+ *
543
+ * @param name - Toolset name / ToolSet 名称
544
+ * @param input - Toolset input / ToolSet 输入
545
+ * @param headers - Request headers / 请求头
546
+ * @param config - Configuration / 配置
547
+ * @returns Toolset object / ToolSet 对象
548
+ */
549
+ updateToolset = async (params) => {
550
+ const { name, input, headers, config: config2 } = params;
551
+ try {
552
+ const client = this.getDevsClient(config2);
553
+ const runtime = new $Util__namespace.RuntimeOptions({});
554
+ const response = await client.updateToolsetWithOptions(
555
+ name,
556
+ new $Devs__namespace.UpdateToolsetRequest({ body: input }),
557
+ headers || {},
558
+ runtime
559
+ );
560
+ logger.debug(`API updateToolset called, Request ID: ${response.body?.requestId}`);
561
+ if (!response.body) {
562
+ throw new Error("Empty response body");
563
+ }
564
+ return response.body;
565
+ } catch (error) {
566
+ this.handleError(error, name);
567
+ }
568
+ };
569
+ /**
570
+ * Delete toolset
571
+ * 删除工具集
572
+ *
573
+ * @param name - Toolset name / ToolSet 名称
574
+ * @param headers - Request headers / 请求头
575
+ * @param config - Configuration / 配置
576
+ * @returns Toolset object / ToolSet 对象
577
+ */
578
+ deleteToolset = async (params) => {
579
+ const { name, headers, config: config2 } = params;
580
+ try {
581
+ const client = this.getDevsClient(config2);
582
+ const runtime = new $Util__namespace.RuntimeOptions({});
583
+ const response = await client.deleteToolsetWithOptions(name, headers || {}, runtime);
584
+ logger.debug(`API deleteToolset called, Request ID: ${response.body?.requestId}`);
585
+ if (!response.body) {
586
+ throw new Error("Empty response body");
587
+ }
588
+ return response.body;
589
+ } catch (error) {
590
+ this.handleError(error, name);
591
+ }
592
+ };
593
+ /**
594
+ * Handle API errors
595
+ * 处理 API 错误
596
+ */
597
+ handleError(error, _resourceName) {
598
+ if (error && typeof error === "object" && "statusCode" in error) {
599
+ const e = error;
600
+ const statusCode = e.statusCode;
601
+ const message = e.message || "Unknown error";
602
+ const requestId = e.data?.requestId;
603
+ if (statusCode >= 400 && statusCode < 500) {
604
+ throw new ClientError(statusCode, message, { requestId });
605
+ } else if (statusCode >= 500) {
606
+ throw new ServerError(statusCode, message, { requestId });
607
+ }
608
+ }
609
+ throw error;
610
+ }
611
+ };
612
+
613
+ // src/toolset/api/mcp.ts
614
+ var MCPSession = class {
615
+ url;
616
+ config;
617
+ client;
618
+ // Will be typed when @modelcontextprotocol/sdk is installed
619
+ clientSession;
620
+ constructor(url, config2) {
621
+ this.url = url;
622
+ this.config = Config.withConfigs(config2);
623
+ }
624
+ /**
625
+ * Create and initialize the session
626
+ * 创建并初始化会话
627
+ */
628
+ connect = async (_params) => {
629
+ try {
630
+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
631
+ const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js');
632
+ const transport = new SSEClientTransport(new URL(this.url));
633
+ this.client = new Client(
634
+ {
635
+ name: "agentrun-nodejs-client",
636
+ version: "1.0.0"
637
+ },
638
+ {
639
+ capabilities: {}
640
+ }
641
+ );
642
+ await this.client.connect(transport);
643
+ return this.client;
644
+ } catch (error) {
645
+ logger.error("Failed to create MCP session:", error);
646
+ throw error;
647
+ }
648
+ };
649
+ /**
650
+ * Close the session
651
+ * 关闭会话
652
+ */
653
+ close = async (_params) => {
654
+ if (this.client) {
655
+ try {
656
+ await this.client.close();
657
+ } catch (error) {
658
+ logger.error("Failed to close MCP session:", error);
659
+ }
660
+ }
661
+ };
662
+ /**
663
+ * Get toolsets
664
+ * 获取工具集
665
+ */
666
+ toolsets(config2) {
667
+ const cfg = Config.withConfigs(this.config, config2);
668
+ return new MCPToolSet(this.url + "/toolsets", cfg);
669
+ }
670
+ };
671
+ var MCPToolSet = class {
672
+ url;
673
+ config;
674
+ constructor(url, config2) {
675
+ this.url = url;
676
+ this.config = Config.withConfigs(config2);
677
+ }
678
+ /**
679
+ * Create a new session
680
+ * 创建新会话
681
+ */
682
+ newSession(config2) {
683
+ const cfg = Config.withConfigs(this.config, config2);
684
+ return new MCPSession(this.url, cfg);
685
+ }
686
+ /**
687
+ * List available tools (async)
688
+ * 列出可用工具(异步)
689
+ */
690
+ toolsAsync = async (params) => {
691
+ const session = this.newSession(params?.config);
692
+ try {
693
+ const client = await session.connect();
694
+ const result = await client.listTools();
695
+ return result.tools || [];
696
+ } finally {
697
+ await session.close();
698
+ }
699
+ };
700
+ /**
701
+ * List available tools (sync wrapper)
702
+ * 列出可用工具(同步包装)
703
+ *
704
+ * Note: This is a convenience method that wraps the async version.
705
+ * In Node.js, prefer using toolsAsync() directly.
706
+ */
707
+ tools(config2) {
708
+ return this.toolsAsync({ config: config2 });
709
+ }
710
+ /**
711
+ * Call a tool (async)
712
+ * 调用工具(异步)
713
+ */
714
+ callToolAsync = async (name, args, config2) => {
715
+ const session = this.newSession(config2);
716
+ try {
717
+ const client = await session.connect();
718
+ const result = await client.callTool({
719
+ name,
720
+ arguments: args || {}
721
+ });
722
+ if (result.content && Array.isArray(result.content)) {
723
+ return result.content.map((item) => {
724
+ if (typeof item === "object" && item !== null) {
725
+ if (typeof item.toJSON === "function") {
726
+ return item.toJSON();
727
+ }
728
+ return { ...item };
729
+ }
730
+ return item;
731
+ });
732
+ }
733
+ return result.content || [];
734
+ } finally {
735
+ await session.close();
736
+ }
737
+ };
738
+ /**
739
+ * Call a tool (sync wrapper)
740
+ * 调用工具(同步包装)
741
+ *
742
+ * Note: This is a convenience method that wraps the async version.
743
+ * In Node.js, prefer using callToolAsync() directly.
744
+ */
745
+ callTool(name, args, config2) {
746
+ return this.callToolAsync(name, args, config2);
747
+ }
748
+ };
749
+
750
+ exports.MCPSession = MCPSession;
751
+ exports.MCPToolSet = MCPToolSet;
752
+ exports.ToolControlAPI = ToolControlAPI;
753
+ //# sourceMappingURL=index.cjs.map
754
+ //# sourceMappingURL=index.cjs.map