@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,1945 @@
1
+ 'use strict';
2
+
3
+ var dotenv = require('dotenv');
4
+ var $Devs = require('@alicloud/devs20230714');
5
+ var $OpenApi = require('@alicloud/openapi-client');
6
+ var $Util = require('@alicloud/tea-util');
7
+ var YAML = require('js-yaml');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ function _interopNamespace(e) {
12
+ if (e && e.__esModule) return e;
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
30
+ var $Devs__namespace = /*#__PURE__*/_interopNamespace($Devs);
31
+ var $OpenApi__namespace = /*#__PURE__*/_interopNamespace($OpenApi);
32
+ var $Util__namespace = /*#__PURE__*/_interopNamespace($Util);
33
+ var YAML__default = /*#__PURE__*/_interopDefault(YAML);
34
+
35
+ var __defProp = Object.defineProperty;
36
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
37
+ var __getOwnPropNames = Object.getOwnPropertyNames;
38
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
39
+ var __esm = (fn, res) => function __init() {
40
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
41
+ };
42
+ var __export = (target, all) => {
43
+ for (var name in all)
44
+ __defProp(target, name, { get: all[name], enumerable: true });
45
+ };
46
+ var __copyProps = (to, from, except, desc) => {
47
+ if (from && typeof from === "object" || typeof from === "function") {
48
+ for (let key of __getOwnPropNames(from))
49
+ if (!__hasOwnProp.call(to, key) && key !== except)
50
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
51
+ }
52
+ return to;
53
+ };
54
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
55
+
56
+ // src/utils/log.ts
57
+ var LOG_LEVELS, COLORS, Logger, logger;
58
+ var init_log = __esm({
59
+ "src/utils/log.ts"() {
60
+ LOG_LEVELS = {
61
+ debug: 0,
62
+ info: 1,
63
+ warn: 2,
64
+ error: 3
65
+ };
66
+ COLORS = {
67
+ reset: "\x1B[0m",
68
+ bright: "\x1B[1m",
69
+ dim: "\x1B[2m",
70
+ italic: "\x1B[3m",
71
+ blue: "\x1B[34m",
72
+ cyan: "\x1B[36m",
73
+ yellow: "\x1B[33m",
74
+ red: "\x1B[31m"
75
+ };
76
+ Logger = class {
77
+ level = "info";
78
+ // match Python logger name
79
+ prefix = "agentrun-logger";
80
+ setLevel(level) {
81
+ this.level = level;
82
+ }
83
+ shouldLog(level) {
84
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
85
+ }
86
+ getColor(level) {
87
+ switch (level) {
88
+ case "debug":
89
+ return COLORS.cyan;
90
+ case "info":
91
+ return COLORS.blue;
92
+ case "warn":
93
+ return COLORS.yellow;
94
+ case "error":
95
+ return COLORS.red;
96
+ default:
97
+ return COLORS.reset;
98
+ }
99
+ }
100
+ // format timestamp like Python: YYYY-MM-DD HH:mm:ss,SSS
101
+ formatTimestamp(d = /* @__PURE__ */ new Date()) {
102
+ const pad = (n, sz = 2) => n.toString().padStart(sz, "0");
103
+ const year = d.getFullYear();
104
+ const month = pad(d.getMonth() + 1);
105
+ const day = pad(d.getDate());
106
+ const hour = pad(d.getHours());
107
+ const minute = pad(d.getMinutes());
108
+ const second = pad(d.getSeconds());
109
+ const ms = pad(d.getMilliseconds(), 3);
110
+ return `${year}-${month}-${day} ${hour}:${minute}:${second},${ms}`;
111
+ }
112
+ // attempt to infer caller file and line by parsing Error.stack
113
+ // helper: parse a single stack frame into {filepath, line, functionName}
114
+ parseFrame(frame) {
115
+ const m = frame.match(/^(?:at\s+)?(?:(.+?)\s+\()?(.*?):(\d+):(\d+)\)?$/);
116
+ if (!m) return null;
117
+ return {
118
+ functionName: m[1] ? m[1].trim() : void 0,
119
+ filepath: m[2],
120
+ line: parseInt(m[3], 10)
121
+ };
122
+ }
123
+ // get caller by fixed stack offset (used in public log methods)
124
+ getCallerByOffset() {
125
+ const err = new Error();
126
+ const stack = err.stack;
127
+ if (!stack) return {};
128
+ const lines = stack.split("\n").map((l) => l.trim());
129
+ for (let i = 3; i < lines.length; i++) {
130
+ let parsed = this.parseFrame(lines[i]);
131
+ if (!parsed) {
132
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
133
+ if (m) {
134
+ const parts = m[1].split(":");
135
+ parts.pop();
136
+ const ln = Number(parts.pop());
137
+ const fp2 = parts.join(":");
138
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
139
+ }
140
+ }
141
+ if (!parsed) continue;
142
+ const fp = parsed.filepath;
143
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
144
+ continue;
145
+ return { filepath: parsed.filepath, line: parsed.line };
146
+ }
147
+ const cwd = process.cwd();
148
+ for (let i = 0; i < lines.length; i++) {
149
+ let parsed = this.parseFrame(lines[i]);
150
+ if (!parsed) {
151
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
152
+ if (m) {
153
+ const parts = m[1].split(":");
154
+ parts.pop();
155
+ const ln = Number(parts.pop());
156
+ const fp2 = parts.join(":");
157
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
158
+ }
159
+ }
160
+ if (!parsed) continue;
161
+ const fp = parsed.filepath;
162
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
163
+ continue;
164
+ if (fp.includes("/src/utils/log.ts")) continue;
165
+ if (fp.startsWith(cwd)) return { filepath: parsed.filepath, line: parsed.line };
166
+ }
167
+ for (let i = 0; i < lines.length; i++) {
168
+ let parsed = this.parseFrame(lines[i]);
169
+ if (!parsed) {
170
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
171
+ if (m) {
172
+ const parts = m[1].split(":");
173
+ parts.pop();
174
+ const ln = Number(parts.pop());
175
+ const fp2 = parts.join(":");
176
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
177
+ }
178
+ }
179
+ if (!parsed) continue;
180
+ const fp = parsed.filepath;
181
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
182
+ continue;
183
+ if (fp.includes("/src/utils/log.ts")) continue;
184
+ return { filepath: parsed.filepath, line: parsed.line };
185
+ }
186
+ return {};
187
+ }
188
+ formatMessage(level, message, filepath, line) {
189
+ const timestamp = this.formatTimestamp();
190
+ const color = this.getColor(level);
191
+ const reset = COLORS.reset;
192
+ const levelName = level === "warn" ? "WARNING" : level.toUpperCase();
193
+ const levelStr = `${COLORS.bright}${color}${levelName}${reset}`;
194
+ const nameStr = `${color}[${this.prefix}]${reset}`;
195
+ const tsStr = `${color} ${timestamp}${reset}`;
196
+ const pathInfo = filepath && line !== void 0 ? ` ${COLORS.dim}${COLORS.italic}${filepath}:${line}${reset}` : "";
197
+ const msg = level === "debug" ? `${COLORS.dim}${message}${reset}` : message;
198
+ return `
199
+ ${levelStr} ${nameStr}${tsStr}${pathInfo}
200
+ ${msg}
201
+ `;
202
+ }
203
+ debug(message, ...args) {
204
+ if (this.shouldLog("debug")) {
205
+ const caller = this.getCallerByOffset();
206
+ console.debug(this.formatMessage("debug", message, caller.filepath, caller.line), ...args);
207
+ }
208
+ }
209
+ info(message, ...args) {
210
+ if (this.shouldLog("info")) {
211
+ const caller = this.getCallerByOffset();
212
+ console.info(this.formatMessage("info", message, caller.filepath, caller.line), ...args);
213
+ }
214
+ }
215
+ warn(message, ...args) {
216
+ if (this.shouldLog("warn")) {
217
+ const caller = this.getCallerByOffset();
218
+ console.warn(this.formatMessage("warn", message, caller.filepath, caller.line), ...args);
219
+ }
220
+ }
221
+ error(message, ...args) {
222
+ if (this.shouldLog("error")) {
223
+ const caller = this.getCallerByOffset();
224
+ console.error(this.formatMessage("error", message, caller.filepath, caller.line), ...args);
225
+ }
226
+ }
227
+ };
228
+ logger = new Logger();
229
+ if (![void 0, null, "", "False", "FALSE", "false", "0"].includes(process.env["AGENTRUN_SDK_DEBUG"])) {
230
+ logger.setLevel("debug");
231
+ if (!globalThis._AGENTRUN_DEBUG_LOGGED) {
232
+ logger.warn("\u542F\u7528 AgentRun SDK \u8C03\u8BD5\u65E5\u5FD7\uFF0C \u79FB\u9664 AGENTRUN_SDK_DEBUG \u73AF\u5883\u53D8\u91CF\u4EE5\u5173\u95ED");
233
+ globalThis._AGENTRUN_DEBUG_LOGGED = true;
234
+ }
235
+ } else {
236
+ logger.setLevel("info");
237
+ }
238
+ }
239
+ });
240
+
241
+ // src/utils/version-check.ts
242
+ var VERSION;
243
+ var init_version_check = __esm({
244
+ "src/utils/version-check.ts"() {
245
+ init_log();
246
+ VERSION = "0.0.4" ;
247
+ if (!process.env.DISABLE_BREAKING_CHANGES_WARNING && !globalThis._AGENTRUN_VERSION_WARNING_SHOWN) {
248
+ globalThis._AGENTRUN_VERSION_WARNING_SHOWN = true;
249
+ logger.warn(
250
+ `\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
251
+ 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.
252
+ \x1B[2;3m pip install 'agentrun-sdk==${VERSION}' \x1B[0m
253
+
254
+ \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
255
+ Add\x1B[2;3m DISABLE_BREAKING_CHANGES_WARNING=1 \x1B[0mto your environment variables to disable this warning.
256
+
257
+ Releases:\x1B[2;3m https://github.com/Serverless-Devs/agentrun-sdk-python/releases\x1B[0m`
258
+ );
259
+ }
260
+ }
261
+ });
262
+ function getEnvWithDefault(defaultValue, ...keys) {
263
+ for (const key of keys) {
264
+ const value = process.env[key];
265
+ if (value !== void 0 && value !== "") {
266
+ return value;
267
+ }
268
+ }
269
+ return defaultValue;
270
+ }
271
+ var Config;
272
+ var init_config = __esm({
273
+ "src/utils/config.ts"() {
274
+ dotenv__namespace.config();
275
+ Config = class _Config {
276
+ _accessKeyId;
277
+ _accessKeySecret;
278
+ _securityToken;
279
+ _accountId;
280
+ _token;
281
+ _regionId;
282
+ _timeout;
283
+ _readTimeout;
284
+ _controlEndpoint;
285
+ _dataEndpoint;
286
+ _devsEndpoint;
287
+ _headers;
288
+ constructor(options = {}) {
289
+ this._accessKeyId = options.accessKeyId ?? getEnvWithDefault("", "AGENTRUN_ACCESS_KEY_ID", "ALIBABA_CLOUD_ACCESS_KEY_ID");
290
+ this._accessKeySecret = options.accessKeySecret ?? getEnvWithDefault("", "AGENTRUN_ACCESS_KEY_SECRET", "ALIBABA_CLOUD_ACCESS_KEY_SECRET");
291
+ this._securityToken = options.securityToken ?? getEnvWithDefault("", "AGENTRUN_SECURITY_TOKEN", "ALIBABA_CLOUD_SECURITY_TOKEN");
292
+ this._accountId = options.accountId ?? getEnvWithDefault("", "AGENTRUN_ACCOUNT_ID", "FC_ACCOUNT_ID");
293
+ this._token = options.token;
294
+ this._regionId = options.regionId ?? getEnvWithDefault("cn-hangzhou", "AGENTRUN_REGION", "FC_REGION");
295
+ this._timeout = options.timeout ?? 6e5;
296
+ this._readTimeout = options.readTimeout ?? 1e8;
297
+ this._controlEndpoint = options.controlEndpoint ?? getEnvWithDefault("", "AGENTRUN_CONTROL_ENDPOINT");
298
+ this._dataEndpoint = options.dataEndpoint ?? getEnvWithDefault("", "AGENTRUN_DATA_ENDPOINT");
299
+ this._devsEndpoint = options.devsEndpoint ?? getEnvWithDefault("", "DEVS_ENDPOINT");
300
+ this._headers = options.headers ?? {};
301
+ }
302
+ /**
303
+ * Create a new Config by merging multiple configs.
304
+ * Later configs take precedence.
305
+ */
306
+ static withConfigs(...configs) {
307
+ return new _Config().update(...configs);
308
+ }
309
+ /**
310
+ * Update this config with values from other configs.
311
+ * Non-undefined values from later configs take precedence.
312
+ */
313
+ update(...configs) {
314
+ for (const config2 of configs) {
315
+ if (!config2) continue;
316
+ if (config2._accessKeyId) this._accessKeyId = config2._accessKeyId;
317
+ if (config2._accessKeySecret) this._accessKeySecret = config2._accessKeySecret;
318
+ if (config2._securityToken) this._securityToken = config2._securityToken;
319
+ if (config2._accountId) this._accountId = config2._accountId;
320
+ if (config2._token) this._token = config2._token;
321
+ if (config2._regionId) this._regionId = config2._regionId;
322
+ if (config2._timeout) this._timeout = config2._timeout;
323
+ if (config2._readTimeout) this._readTimeout = config2._readTimeout;
324
+ if (config2._controlEndpoint) this._controlEndpoint = config2._controlEndpoint;
325
+ if (config2._dataEndpoint) this._dataEndpoint = config2._dataEndpoint;
326
+ if (config2._devsEndpoint) this._devsEndpoint = config2._devsEndpoint;
327
+ if (config2._headers && Object.keys(config2._headers).length > 0) {
328
+ this._headers = { ...this._headers, ...config2._headers };
329
+ }
330
+ }
331
+ return this;
332
+ }
333
+ get accessKeyId() {
334
+ return this._accessKeyId;
335
+ }
336
+ get accessKeySecret() {
337
+ return this._accessKeySecret;
338
+ }
339
+ get securityToken() {
340
+ return this._securityToken;
341
+ }
342
+ get accountId() {
343
+ if (!this._accountId) {
344
+ throw new Error(
345
+ "Account ID is not set. Please add AGENTRUN_ACCOUNT_ID environment variable or set it in code."
346
+ );
347
+ }
348
+ return this._accountId;
349
+ }
350
+ get token() {
351
+ return this._token;
352
+ }
353
+ get regionId() {
354
+ return this._regionId || "cn-hangzhou";
355
+ }
356
+ get timeout() {
357
+ return this._timeout || 6e5;
358
+ }
359
+ get readTimeout() {
360
+ return this._readTimeout || 1e8;
361
+ }
362
+ get controlEndpoint() {
363
+ if (this._controlEndpoint) {
364
+ return this._controlEndpoint;
365
+ }
366
+ return `https://agentrun.${this.regionId}.aliyuncs.com`;
367
+ }
368
+ get dataEndpoint() {
369
+ if (this._dataEndpoint) {
370
+ return this._dataEndpoint;
371
+ }
372
+ return `https://${this.accountId}.agentrun-data.${this.regionId}.aliyuncs.com`;
373
+ }
374
+ get devsEndpoint() {
375
+ if (this._devsEndpoint) {
376
+ return this._devsEndpoint;
377
+ }
378
+ return `https://devs.${this.regionId}.aliyuncs.com`;
379
+ }
380
+ get headers() {
381
+ return this._headers;
382
+ }
383
+ };
384
+ }
385
+ });
386
+
387
+ // src/utils/exception.ts
388
+ var AgentRunError, HTTPError, ClientError, ServerError, ResourceNotExistError, ResourceAlreadyExistError;
389
+ var init_exception = __esm({
390
+ "src/utils/exception.ts"() {
391
+ AgentRunError = class _AgentRunError extends Error {
392
+ constructor(message) {
393
+ super(message);
394
+ this.name = "AgentRunError";
395
+ Object.setPrototypeOf(this, _AgentRunError.prototype);
396
+ }
397
+ };
398
+ HTTPError = class _HTTPError extends AgentRunError {
399
+ statusCode;
400
+ requestId;
401
+ errorCode;
402
+ constructor(statusCode, message, options) {
403
+ super(message);
404
+ this.name = "HTTPError";
405
+ this.statusCode = statusCode;
406
+ this.requestId = options?.requestId;
407
+ this.errorCode = options?.errorCode;
408
+ Object.setPrototypeOf(this, _HTTPError.prototype);
409
+ }
410
+ /**
411
+ * Convert HTTP error to resource-specific error based on status code
412
+ */
413
+ toResourceError(resourceType, resourceId) {
414
+ if (this.statusCode == 404) return new ResourceNotExistError(resourceType, resourceId);
415
+ else if (this.statusCode == 409) return new ResourceAlreadyExistError(resourceType, resourceId);
416
+ else if ((this.statusCode == 400 || this.statusCode == 500) && this.message.includes("already exists"))
417
+ return new ResourceAlreadyExistError(resourceType, resourceId);
418
+ else return this;
419
+ }
420
+ };
421
+ ClientError = class _ClientError extends HTTPError {
422
+ constructor(statusCode, message, options) {
423
+ super(statusCode, message, options);
424
+ this.name = "ClientError";
425
+ Object.setPrototypeOf(this, _ClientError.prototype);
426
+ }
427
+ };
428
+ ServerError = class _ServerError extends HTTPError {
429
+ constructor(statusCode, message, options) {
430
+ super(statusCode, message, options);
431
+ this.name = "ServerError";
432
+ Object.setPrototypeOf(this, _ServerError.prototype);
433
+ }
434
+ };
435
+ ResourceNotExistError = class _ResourceNotExistError extends ClientError {
436
+ resourceType;
437
+ resourceId;
438
+ constructor(resourceType, resourceId, options) {
439
+ const message = resourceId ? `${resourceType} '${resourceId}' does not exist` : `${resourceType} does not exist`;
440
+ super(404, message, options);
441
+ this.name = "ResourceNotExistError";
442
+ this.resourceType = resourceType;
443
+ this.resourceId = resourceId;
444
+ Object.setPrototypeOf(this, _ResourceNotExistError.prototype);
445
+ }
446
+ };
447
+ ResourceAlreadyExistError = class _ResourceAlreadyExistError extends ClientError {
448
+ resourceType;
449
+ resourceId;
450
+ constructor(resourceType, resourceId, options) {
451
+ const message = resourceId ? `${resourceType} '${resourceId}' already exists` : `${resourceType} already exists`;
452
+ super(409, message, options);
453
+ this.name = "ResourceAlreadyExistError";
454
+ this.resourceType = resourceType;
455
+ this.resourceId = resourceId;
456
+ Object.setPrototypeOf(this, _ResourceAlreadyExistError.prototype);
457
+ }
458
+ };
459
+ }
460
+ });
461
+ var $DevsClient; exports.ToolControlAPI = void 0;
462
+ var init_control = __esm({
463
+ "src/toolset/api/control.ts"() {
464
+ init_config();
465
+ init_exception();
466
+ init_log();
467
+ $DevsClient = // @ts-expect-error - ESM interop: default.default exists when imported as ESM namespace
468
+ $Devs__namespace.default?.default ?? $Devs__namespace.default ?? $Devs__namespace;
469
+ exports.ToolControlAPI = class {
470
+ config;
471
+ /**
472
+ * Initialize API client
473
+ * 初始化 API 客户端
474
+ *
475
+ * @param config - Global configuration object / 全局配置对象
476
+ */
477
+ constructor(config2) {
478
+ this.config = config2;
479
+ }
480
+ /**
481
+ * Get DevS client
482
+ * 获取 DevS 客户端
483
+ */
484
+ getDevsClient(config2) {
485
+ const cfg = Config.withConfigs(this.config, config2);
486
+ let endpoint = cfg.devsEndpoint;
487
+ if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
488
+ endpoint = endpoint.split("://")[1];
489
+ }
490
+ const openApiConfig = new $OpenApi__namespace.Config({
491
+ accessKeyId: cfg.accessKeyId,
492
+ accessKeySecret: cfg.accessKeySecret,
493
+ securityToken: cfg.securityToken || void 0,
494
+ regionId: cfg.regionId,
495
+ endpoint,
496
+ connectTimeout: cfg.timeout
497
+ });
498
+ return new $DevsClient(openApiConfig);
499
+ }
500
+ /**
501
+ * Get toolset
502
+ * 获取工具
503
+ *
504
+ * @param name - Tool name / Tool 名称
505
+ * @param headers - Request headers / 请求头
506
+ * @param config - Configuration / 配置
507
+ * @returns Toolset object / ToolSet 对象
508
+ * @throws AgentRuntimeError - Throws on call failure / 调用失败时抛出
509
+ * @throws ClientError - Client error / 客户端错误
510
+ * @throws ServerError - Server error / 服务器错误
511
+ */
512
+ getToolset = async (params) => {
513
+ const { name, headers, config: config2 } = params;
514
+ try {
515
+ const client = this.getDevsClient(config2);
516
+ const runtime = new $Util__namespace.RuntimeOptions({});
517
+ const response = await client.getToolsetWithOptions(name, headers || {}, runtime);
518
+ logger.debug(`API getToolset called, Request ID: ${response.body?.requestId}`);
519
+ if (!response.body) {
520
+ throw new Error("Empty response body");
521
+ }
522
+ return response.body;
523
+ } catch (error) {
524
+ if (error instanceof HTTPError) {
525
+ throw error.toResourceError("ToolSet", name);
526
+ }
527
+ this.handleError(error, name);
528
+ }
529
+ };
530
+ /**
531
+ * List toolsets
532
+ * 枚举 ToolSets
533
+ *
534
+ * @param input - List configuration / 枚举的配置
535
+ * @param headers - Request headers / 请求头
536
+ * @param config - Configuration / 配置
537
+ * @returns ToolSet list / ToolSet 列表
538
+ * @throws AgentRuntimeError - Throws on call failure / 调用失败时抛出
539
+ * @throws ClientError - Client error / 客户端错误
540
+ * @throws ServerError - Server error / 服务器错误
541
+ */
542
+ listToolsets = async (params) => {
543
+ const { input, headers, config: config2 } = params;
544
+ try {
545
+ const client = this.getDevsClient(config2);
546
+ const runtime = new $Util__namespace.RuntimeOptions({});
547
+ const response = await client.listToolsetsWithOptions(input, headers || {}, runtime);
548
+ logger.debug(
549
+ `API listToolsets called, Request ID: ${response?.headers?.["x-acs-request-id"]}`
550
+ );
551
+ if (!response.body) {
552
+ throw new Error("Empty response body");
553
+ }
554
+ return response.body;
555
+ } catch (error) {
556
+ this.handleError(error);
557
+ }
558
+ };
559
+ /**
560
+ * Create toolset
561
+ * 创建工具集
562
+ *
563
+ * @param input - Toolset input / ToolSet 输入
564
+ * @param headers - Request headers / 请求头
565
+ * @param config - Configuration / 配置
566
+ * @returns Toolset object / ToolSet 对象
567
+ */
568
+ createToolset = async (params) => {
569
+ const { input, headers, config: config2 } = params;
570
+ try {
571
+ const client = this.getDevsClient(config2);
572
+ const runtime = new $Util__namespace.RuntimeOptions({});
573
+ const response = await client.createToolsetWithOptions(
574
+ new $Devs__namespace.CreateToolsetRequest({ body: input }),
575
+ headers || {},
576
+ runtime
577
+ );
578
+ logger.debug(`API createToolset called, Request ID: ${response.body?.requestId}`);
579
+ if (!response.body) {
580
+ throw new Error("Empty response body");
581
+ }
582
+ return response.body;
583
+ } catch (error) {
584
+ this.handleError(error, input?.name);
585
+ }
586
+ };
587
+ /**
588
+ * Update toolset
589
+ * 更新工具集
590
+ *
591
+ * @param name - Toolset name / ToolSet 名称
592
+ * @param input - Toolset input / ToolSet 输入
593
+ * @param headers - Request headers / 请求头
594
+ * @param config - Configuration / 配置
595
+ * @returns Toolset object / ToolSet 对象
596
+ */
597
+ updateToolset = async (params) => {
598
+ const { name, input, headers, config: config2 } = params;
599
+ try {
600
+ const client = this.getDevsClient(config2);
601
+ const runtime = new $Util__namespace.RuntimeOptions({});
602
+ const response = await client.updateToolsetWithOptions(
603
+ name,
604
+ new $Devs__namespace.UpdateToolsetRequest({ body: input }),
605
+ headers || {},
606
+ runtime
607
+ );
608
+ logger.debug(`API updateToolset called, Request ID: ${response.body?.requestId}`);
609
+ if (!response.body) {
610
+ throw new Error("Empty response body");
611
+ }
612
+ return response.body;
613
+ } catch (error) {
614
+ this.handleError(error, name);
615
+ }
616
+ };
617
+ /**
618
+ * Delete toolset
619
+ * 删除工具集
620
+ *
621
+ * @param name - Toolset name / ToolSet 名称
622
+ * @param headers - Request headers / 请求头
623
+ * @param config - Configuration / 配置
624
+ * @returns Toolset object / ToolSet 对象
625
+ */
626
+ deleteToolset = async (params) => {
627
+ const { name, headers, config: config2 } = params;
628
+ try {
629
+ const client = this.getDevsClient(config2);
630
+ const runtime = new $Util__namespace.RuntimeOptions({});
631
+ const response = await client.deleteToolsetWithOptions(name, headers || {}, runtime);
632
+ logger.debug(`API deleteToolset called, Request ID: ${response.body?.requestId}`);
633
+ if (!response.body) {
634
+ throw new Error("Empty response body");
635
+ }
636
+ return response.body;
637
+ } catch (error) {
638
+ this.handleError(error, name);
639
+ }
640
+ };
641
+ /**
642
+ * Handle API errors
643
+ * 处理 API 错误
644
+ */
645
+ handleError(error, _resourceName) {
646
+ if (error && typeof error === "object" && "statusCode" in error) {
647
+ const e = error;
648
+ const statusCode = e.statusCode;
649
+ const message = e.message || "Unknown error";
650
+ const requestId = e.data?.requestId;
651
+ if (statusCode >= 400 && statusCode < 500) {
652
+ throw new ClientError(statusCode, message, { requestId });
653
+ } else if (statusCode >= 500) {
654
+ throw new ServerError(statusCode, message, { requestId });
655
+ }
656
+ }
657
+ throw error;
658
+ }
659
+ };
660
+ }
661
+ });
662
+
663
+ // src/toolset/api/mcp.ts
664
+ var mcp_exports = {};
665
+ __export(mcp_exports, {
666
+ MCPSession: () => exports.MCPSession,
667
+ MCPToolSet: () => exports.MCPToolSet
668
+ });
669
+ exports.MCPSession = void 0; exports.MCPToolSet = void 0;
670
+ var init_mcp = __esm({
671
+ "src/toolset/api/mcp.ts"() {
672
+ init_config();
673
+ init_log();
674
+ exports.MCPSession = class {
675
+ url;
676
+ config;
677
+ client;
678
+ // Will be typed when @modelcontextprotocol/sdk is installed
679
+ clientSession;
680
+ constructor(url, config2) {
681
+ this.url = url;
682
+ this.config = Config.withConfigs(config2);
683
+ }
684
+ /**
685
+ * Create and initialize the session
686
+ * 创建并初始化会话
687
+ */
688
+ connect = async (_params) => {
689
+ try {
690
+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
691
+ const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js');
692
+ const transport = new SSEClientTransport(new URL(this.url));
693
+ this.client = new Client(
694
+ {
695
+ name: "agentrun-nodejs-client",
696
+ version: "1.0.0"
697
+ },
698
+ {
699
+ capabilities: {}
700
+ }
701
+ );
702
+ await this.client.connect(transport);
703
+ return this.client;
704
+ } catch (error) {
705
+ logger.error("Failed to create MCP session:", error);
706
+ throw error;
707
+ }
708
+ };
709
+ /**
710
+ * Close the session
711
+ * 关闭会话
712
+ */
713
+ close = async (_params) => {
714
+ if (this.client) {
715
+ try {
716
+ await this.client.close();
717
+ } catch (error) {
718
+ logger.error("Failed to close MCP session:", error);
719
+ }
720
+ }
721
+ };
722
+ /**
723
+ * Get toolsets
724
+ * 获取工具集
725
+ */
726
+ toolsets(config2) {
727
+ const cfg = Config.withConfigs(this.config, config2);
728
+ return new exports.MCPToolSet(this.url + "/toolsets", cfg);
729
+ }
730
+ };
731
+ exports.MCPToolSet = class {
732
+ url;
733
+ config;
734
+ constructor(url, config2) {
735
+ this.url = url;
736
+ this.config = Config.withConfigs(config2);
737
+ }
738
+ /**
739
+ * Create a new session
740
+ * 创建新会话
741
+ */
742
+ newSession(config2) {
743
+ const cfg = Config.withConfigs(this.config, config2);
744
+ return new exports.MCPSession(this.url, cfg);
745
+ }
746
+ /**
747
+ * List available tools (async)
748
+ * 列出可用工具(异步)
749
+ */
750
+ toolsAsync = async (params) => {
751
+ const session = this.newSession(params?.config);
752
+ try {
753
+ const client = await session.connect();
754
+ const result = await client.listTools();
755
+ return result.tools || [];
756
+ } finally {
757
+ await session.close();
758
+ }
759
+ };
760
+ /**
761
+ * List available tools (sync wrapper)
762
+ * 列出可用工具(同步包装)
763
+ *
764
+ * Note: This is a convenience method that wraps the async version.
765
+ * In Node.js, prefer using toolsAsync() directly.
766
+ */
767
+ tools(config2) {
768
+ return this.toolsAsync({ config: config2 });
769
+ }
770
+ /**
771
+ * Call a tool (async)
772
+ * 调用工具(异步)
773
+ */
774
+ callToolAsync = async (name, args, config2) => {
775
+ const session = this.newSession(config2);
776
+ try {
777
+ const client = await session.connect();
778
+ const result = await client.callTool({
779
+ name,
780
+ arguments: args || {}
781
+ });
782
+ if (result.content && Array.isArray(result.content)) {
783
+ return result.content.map((item) => {
784
+ if (typeof item === "object" && item !== null) {
785
+ if (typeof item.toJSON === "function") {
786
+ return item.toJSON();
787
+ }
788
+ return { ...item };
789
+ }
790
+ return item;
791
+ });
792
+ }
793
+ return result.content || [];
794
+ } finally {
795
+ await session.close();
796
+ }
797
+ };
798
+ /**
799
+ * Call a tool (sync wrapper)
800
+ * 调用工具(同步包装)
801
+ *
802
+ * Note: This is a convenience method that wraps the async version.
803
+ * In Node.js, prefer using callToolAsync() directly.
804
+ */
805
+ callTool(name, args, config2) {
806
+ return this.callToolAsync(name, args, config2);
807
+ }
808
+ };
809
+ }
810
+ });
811
+
812
+ // src/toolset/api/index.ts
813
+ var init_api = __esm({
814
+ "src/toolset/api/index.ts"() {
815
+ init_version_check();
816
+ init_control();
817
+ init_mcp();
818
+ }
819
+ });
820
+
821
+ // src/utils/model.ts
822
+ var init_model = __esm({
823
+ "src/utils/model.ts"() {
824
+ }
825
+ });
826
+
827
+ // src/utils/resource.ts
828
+ function updateObjectProperties(target, source) {
829
+ for (const key in source) {
830
+ if (Object.prototype.hasOwnProperty.call(source, key) && typeof source[key] !== "function" && !key.startsWith("_")) {
831
+ target[key] = source[key];
832
+ }
833
+ }
834
+ }
835
+ function listAllResourcesFunction(list) {
836
+ return async (params) => {
837
+ const { config: config2, ...restParams } = params ?? {};
838
+ const allResults = [];
839
+ let page = 1;
840
+ const pageSize = 50;
841
+ while (true) {
842
+ const pageResults = await list({
843
+ input: {
844
+ ...restParams,
845
+ pageNumber: page,
846
+ pageSize
847
+ },
848
+ config: config2
849
+ });
850
+ page += 1;
851
+ allResults.push(...pageResults);
852
+ if (pageResults.length < pageSize) break;
853
+ }
854
+ const resultSet = /* @__PURE__ */ new Set();
855
+ const results = [];
856
+ for (const item of allResults) {
857
+ const uniqId = item.uniqIdCallback() || "";
858
+ if (!resultSet.has(uniqId) && uniqId) {
859
+ resultSet.add(uniqId);
860
+ results.push(item);
861
+ }
862
+ }
863
+ return results;
864
+ };
865
+ }
866
+ var init_resource = __esm({
867
+ "src/utils/resource.ts"() {
868
+ init_exception();
869
+ init_log();
870
+ init_model();
871
+ }
872
+ });
873
+
874
+ // src/toolset/model.ts
875
+ var model_exports = {};
876
+ __export(model_exports, {
877
+ ToolInfo: () => exports.ToolInfo,
878
+ ToolSchema: () => exports.ToolSchema,
879
+ ToolSetSchemaType: () => exports.ToolSetSchemaType
880
+ });
881
+ exports.ToolSetSchemaType = void 0; exports.ToolSchema = void 0; exports.ToolInfo = void 0;
882
+ var init_model2 = __esm({
883
+ "src/toolset/model.ts"() {
884
+ exports.ToolSetSchemaType = /* @__PURE__ */ ((ToolSetSchemaType2) => {
885
+ ToolSetSchemaType2["OPENAPI"] = "OpenAPI";
886
+ ToolSetSchemaType2["MCP"] = "MCP";
887
+ return ToolSetSchemaType2;
888
+ })(exports.ToolSetSchemaType || {});
889
+ exports.ToolSchema = class _ToolSchema {
890
+ // Basic fields / 基本字段
891
+ type;
892
+ description;
893
+ title;
894
+ // Object type fields / 对象类型字段
895
+ properties;
896
+ required;
897
+ additionalProperties;
898
+ // Array type fields / 数组类型字段
899
+ items;
900
+ minItems;
901
+ maxItems;
902
+ // String type fields / 字符串类型字段
903
+ pattern;
904
+ minLength;
905
+ maxLength;
906
+ format;
907
+ // date, date-time, email, uri, etc.
908
+ enum;
909
+ // Number type fields / 数值类型字段
910
+ minimum;
911
+ maximum;
912
+ exclusiveMinimum;
913
+ exclusiveMaximum;
914
+ // Union types / 联合类型
915
+ anyOf;
916
+ oneOf;
917
+ allOf;
918
+ // Default value / 默认值
919
+ default;
920
+ constructor(data) {
921
+ if (data) {
922
+ Object.assign(this, data);
923
+ }
924
+ }
925
+ /**
926
+ * Create ToolSchema from any OpenAPI/JSON Schema
927
+ * 从任意 OpenAPI/JSON Schema 创建 ToolSchema
928
+ *
929
+ * Recursively parses all nested structures, preserving complete schema information.
930
+ * 递归解析所有嵌套结构,保留完整的 schema 信息。
931
+ */
932
+ static fromAnyOpenAPISchema(schema) {
933
+ if (!schema || typeof schema !== "object") {
934
+ return new _ToolSchema({ type: "string" });
935
+ }
936
+ const s = schema;
937
+ const propertiesRaw = s.properties;
938
+ const properties = propertiesRaw ? Object.fromEntries(
939
+ Object.entries(propertiesRaw).map(([key, value]) => [
940
+ key,
941
+ _ToolSchema.fromAnyOpenAPISchema(value)
942
+ ])
943
+ ) : void 0;
944
+ const itemsRaw = s.items;
945
+ const items = itemsRaw ? _ToolSchema.fromAnyOpenAPISchema(itemsRaw) : void 0;
946
+ const anyOfRaw = s.anyOf;
947
+ const anyOf = anyOfRaw ? anyOfRaw.map(_ToolSchema.fromAnyOpenAPISchema) : void 0;
948
+ const oneOfRaw = s.oneOf;
949
+ const oneOf = oneOfRaw ? oneOfRaw.map(_ToolSchema.fromAnyOpenAPISchema) : void 0;
950
+ const allOfRaw = s.allOf;
951
+ const allOf = allOfRaw ? allOfRaw.map(_ToolSchema.fromAnyOpenAPISchema) : void 0;
952
+ return new _ToolSchema({
953
+ // Basic fields
954
+ type: s.type,
955
+ description: s.description,
956
+ title: s.title,
957
+ // Object type
958
+ properties,
959
+ required: s.required,
960
+ additionalProperties: s.additionalProperties,
961
+ // Array type
962
+ items,
963
+ minItems: s.minItems,
964
+ maxItems: s.maxItems,
965
+ // String type
966
+ pattern: s.pattern,
967
+ minLength: s.minLength,
968
+ maxLength: s.maxLength,
969
+ format: s.format,
970
+ enum: s.enum,
971
+ // Number type
972
+ minimum: s.minimum,
973
+ maximum: s.maximum,
974
+ exclusiveMinimum: s.exclusiveMinimum,
975
+ exclusiveMaximum: s.exclusiveMaximum,
976
+ // Union types
977
+ anyOf,
978
+ oneOf,
979
+ allOf,
980
+ // Default value
981
+ default: s.default
982
+ });
983
+ }
984
+ /**
985
+ * Convert to standard JSON Schema format
986
+ * 转换为标准 JSON Schema 格式
987
+ */
988
+ toJSONSchema() {
989
+ const result = {};
990
+ if (this.type !== void 0) result.type = this.type;
991
+ if (this.description !== void 0) result.description = this.description;
992
+ if (this.title !== void 0) result.title = this.title;
993
+ if (this.properties) {
994
+ result.properties = Object.fromEntries(
995
+ Object.entries(this.properties).map(([k, v]) => [k, v.toJSONSchema()])
996
+ );
997
+ }
998
+ if (this.required) result.required = this.required;
999
+ if (this.additionalProperties !== void 0) {
1000
+ result.additionalProperties = this.additionalProperties;
1001
+ }
1002
+ if (this.items) result.items = this.items.toJSONSchema();
1003
+ if (this.minItems !== void 0) result.minItems = this.minItems;
1004
+ if (this.maxItems !== void 0) result.maxItems = this.maxItems;
1005
+ if (this.pattern) result.pattern = this.pattern;
1006
+ if (this.minLength !== void 0) result.minLength = this.minLength;
1007
+ if (this.maxLength !== void 0) result.maxLength = this.maxLength;
1008
+ if (this.format) result.format = this.format;
1009
+ if (this.enum) result.enum = this.enum;
1010
+ if (this.minimum !== void 0) result.minimum = this.minimum;
1011
+ if (this.maximum !== void 0) result.maximum = this.maximum;
1012
+ if (this.exclusiveMinimum !== void 0) {
1013
+ result.exclusiveMinimum = this.exclusiveMinimum;
1014
+ }
1015
+ if (this.exclusiveMaximum !== void 0) {
1016
+ result.exclusiveMaximum = this.exclusiveMaximum;
1017
+ }
1018
+ if (this.anyOf) result.anyOf = this.anyOf.map((s) => s.toJSONSchema());
1019
+ if (this.oneOf) result.oneOf = this.oneOf.map((s) => s.toJSONSchema());
1020
+ if (this.allOf) result.allOf = this.allOf.map((s) => s.toJSONSchema());
1021
+ if (this.default !== void 0) result.default = this.default;
1022
+ return result;
1023
+ }
1024
+ };
1025
+ exports.ToolInfo = class _ToolInfo {
1026
+ name;
1027
+ description;
1028
+ parameters;
1029
+ constructor(data) {
1030
+ if (data) {
1031
+ this.name = data.name;
1032
+ this.description = data.description;
1033
+ this.parameters = data.parameters;
1034
+ }
1035
+ }
1036
+ /**
1037
+ * Create ToolInfo from MCP tool
1038
+ * 从 MCP tool 创建 ToolInfo
1039
+ */
1040
+ static fromMCPTool(tool) {
1041
+ if (!tool) {
1042
+ throw new Error("MCP tool is required");
1043
+ }
1044
+ let toolName;
1045
+ let toolDescription;
1046
+ let inputSchema;
1047
+ if (typeof tool === "object" && tool !== null) {
1048
+ const t = tool;
1049
+ if ("name" in t) {
1050
+ toolName = t.name;
1051
+ toolDescription = t.description;
1052
+ inputSchema = t.inputSchema || t.input_schema;
1053
+ } else {
1054
+ throw new Error(`Unsupported MCP tool format: ${typeof tool}`);
1055
+ }
1056
+ } else {
1057
+ throw new Error(`Unsupported MCP tool format: ${typeof tool}`);
1058
+ }
1059
+ if (!toolName) {
1060
+ throw new Error("MCP tool must have a name");
1061
+ }
1062
+ let parameters;
1063
+ if (inputSchema) {
1064
+ parameters = exports.ToolSchema.fromAnyOpenAPISchema(inputSchema);
1065
+ }
1066
+ return new _ToolInfo({
1067
+ name: toolName,
1068
+ description: toolDescription,
1069
+ parameters: parameters || new exports.ToolSchema({ type: "object", properties: {} })
1070
+ });
1071
+ }
1072
+ };
1073
+ }
1074
+ });
1075
+
1076
+ // src/toolset/openapi.ts
1077
+ var openapi_exports = {};
1078
+ __export(openapi_exports, {
1079
+ ApiSet: () => exports.ApiSet,
1080
+ OpenAPI: () => exports.OpenAPI
1081
+ });
1082
+ exports.OpenAPI = void 0; exports.ApiSet = void 0;
1083
+ var init_openapi = __esm({
1084
+ "src/toolset/openapi.ts"() {
1085
+ init_config();
1086
+ init_log();
1087
+ exports.OpenAPI = class {
1088
+ _schema;
1089
+ _baseUrl;
1090
+ _defaultHeaders;
1091
+ _defaultQueryParams;
1092
+ _config;
1093
+ _tools = /* @__PURE__ */ new Map();
1094
+ constructor(options) {
1095
+ if (typeof options.schema === "string") {
1096
+ try {
1097
+ this._schema = YAML__default.default.load(options.schema);
1098
+ } catch {
1099
+ this._schema = JSON.parse(options.schema);
1100
+ }
1101
+ } else {
1102
+ this._schema = JSON.parse(JSON.stringify(options.schema));
1103
+ }
1104
+ this._resolveAllRefs();
1105
+ this._baseUrl = options.baseUrl || this._extractBaseUrl();
1106
+ this._defaultHeaders = options.headers ? { ...options.headers } : {};
1107
+ this._defaultQueryParams = options.queryParams ? { ...options.queryParams } : {};
1108
+ this._config = options.config;
1109
+ this._parseTools();
1110
+ }
1111
+ /**
1112
+ * Get the parsed schema
1113
+ */
1114
+ get schema() {
1115
+ return this._schema;
1116
+ }
1117
+ /**
1118
+ * Get all parsed tools
1119
+ */
1120
+ get tools() {
1121
+ return Array.from(this._tools.values());
1122
+ }
1123
+ /**
1124
+ * Get a specific tool by name
1125
+ */
1126
+ getTool(name) {
1127
+ return this._tools.get(name);
1128
+ }
1129
+ /**
1130
+ * Invoke a tool
1131
+ */
1132
+ invokeToolAsync = async (name, args = {}, _config) => {
1133
+ const tool = this._tools.get(name);
1134
+ if (!tool) {
1135
+ throw new Error(`Tool '${name}' not found.`);
1136
+ }
1137
+ const method = (tool.method || "get").toUpperCase();
1138
+ let path = tool.path || "/";
1139
+ const queryParams = {
1140
+ ...this._defaultQueryParams
1141
+ };
1142
+ const headerParams = { ...this._defaultHeaders };
1143
+ let bodyContent = void 0;
1144
+ for (const [key, value] of Object.entries(args)) {
1145
+ if (key === "body") {
1146
+ bodyContent = value;
1147
+ } else if (path.includes(`{${key}}`)) {
1148
+ path = path.replace(`{${key}}`, String(value));
1149
+ } else if (typeof value === "string" && key.startsWith("X-")) {
1150
+ headerParams[key] = value;
1151
+ } else {
1152
+ queryParams[key] = value;
1153
+ }
1154
+ }
1155
+ const url = new URL(path, this._baseUrl);
1156
+ for (const [key, value] of Object.entries(queryParams)) {
1157
+ if (value !== void 0 && value !== null) {
1158
+ url.searchParams.set(key, String(value));
1159
+ }
1160
+ }
1161
+ try {
1162
+ const fetchOptions = {
1163
+ method,
1164
+ headers: {
1165
+ "Content-Type": "application/json",
1166
+ ...headerParams
1167
+ }
1168
+ };
1169
+ if (bodyContent && ["POST", "PUT", "PATCH"].includes(method)) {
1170
+ fetchOptions.body = JSON.stringify(bodyContent);
1171
+ }
1172
+ const response = await fetch(url.toString(), fetchOptions);
1173
+ const responseClone = response.clone();
1174
+ let responseBody;
1175
+ try {
1176
+ responseBody = await response.json();
1177
+ } catch {
1178
+ responseBody = await responseClone.text();
1179
+ }
1180
+ return {
1181
+ status_code: response.status,
1182
+ headers: Object.fromEntries(response.headers.entries()),
1183
+ body: responseBody
1184
+ };
1185
+ } catch (error) {
1186
+ return {
1187
+ status_code: 0,
1188
+ error: error instanceof Error ? error.message : String(error)
1189
+ };
1190
+ }
1191
+ };
1192
+ /**
1193
+ * Synchronous invoke (wrapper for async)
1194
+ */
1195
+ invokeToolSync(_name, _args = {}) {
1196
+ throw new Error(
1197
+ "Synchronous invocation is not supported in Node.js. Use invokeToolAsync instead."
1198
+ );
1199
+ }
1200
+ // Alias for Python compatibility
1201
+ invoke_tool = (name, args = {}, _config) => {
1202
+ return this.invokeToolAsync(name, args);
1203
+ };
1204
+ /**
1205
+ * Extract base URL from schema
1206
+ */
1207
+ _extractBaseUrl() {
1208
+ const servers = this._schema.servers;
1209
+ if (servers && servers.length > 0) {
1210
+ return servers[0].url;
1211
+ }
1212
+ return "";
1213
+ }
1214
+ /**
1215
+ * Resolve all $ref references in the schema
1216
+ */
1217
+ _resolveAllRefs() {
1218
+ this._schema = this._resolveRefs(this._schema, this._schema);
1219
+ }
1220
+ /**
1221
+ * Recursively resolve $ref references
1222
+ */
1223
+ _resolveRefs(obj, root) {
1224
+ if (obj === null || obj === void 0) {
1225
+ return obj;
1226
+ }
1227
+ if (Array.isArray(obj)) {
1228
+ return obj.map((item) => this._resolveRefs(item, root));
1229
+ }
1230
+ if (typeof obj === "object") {
1231
+ const result = {};
1232
+ const objRecord = obj;
1233
+ if ("$ref" in objRecord && typeof objRecord.$ref === "string") {
1234
+ const refPath = objRecord.$ref;
1235
+ const resolved = this._resolveRef(refPath, root);
1236
+ const resolvedDeep = this._resolveRefs(resolved, root);
1237
+ if (typeof resolvedDeep === "object" && resolvedDeep !== null) {
1238
+ Object.assign(result, resolvedDeep);
1239
+ }
1240
+ for (const [key, value] of Object.entries(objRecord)) {
1241
+ if (key !== "$ref") {
1242
+ result[key] = this._resolveRefs(value, root);
1243
+ }
1244
+ }
1245
+ return result;
1246
+ }
1247
+ for (const [key, value] of Object.entries(objRecord)) {
1248
+ result[key] = this._resolveRefs(value, root);
1249
+ }
1250
+ return result;
1251
+ }
1252
+ return obj;
1253
+ }
1254
+ /**
1255
+ * Resolve a single $ref path
1256
+ */
1257
+ _resolveRef(refPath, root) {
1258
+ if (!refPath.startsWith("#/")) {
1259
+ logger.warn(`External $ref not supported: ${refPath}`);
1260
+ return {};
1261
+ }
1262
+ const path = refPath.substring(2).split("/");
1263
+ let current = root;
1264
+ for (const part of path) {
1265
+ if (current === null || current === void 0) {
1266
+ return {};
1267
+ }
1268
+ if (typeof current === "object" && !Array.isArray(current)) {
1269
+ current = current[part];
1270
+ } else {
1271
+ return {};
1272
+ }
1273
+ }
1274
+ return current;
1275
+ }
1276
+ /**
1277
+ * Parse tools from OpenAPI paths
1278
+ */
1279
+ _parseTools() {
1280
+ const paths = this._schema.paths;
1281
+ if (!paths) {
1282
+ return;
1283
+ }
1284
+ for (const [path, pathItem] of Object.entries(paths)) {
1285
+ if (typeof pathItem !== "object" || pathItem === null) {
1286
+ continue;
1287
+ }
1288
+ for (const [method, operation] of Object.entries(pathItem)) {
1289
+ if (!["get", "post", "put", "patch", "delete", "options", "head"].includes(method)) {
1290
+ continue;
1291
+ }
1292
+ if (typeof operation !== "object" || operation === null) {
1293
+ continue;
1294
+ }
1295
+ const op = operation;
1296
+ const operationId = op.operationId;
1297
+ if (!operationId) {
1298
+ continue;
1299
+ }
1300
+ const parameters = this._parseParameters(op, path);
1301
+ const tool = {
1302
+ name: operationId,
1303
+ description: op.summary || op.description,
1304
+ parameters,
1305
+ operationId,
1306
+ method,
1307
+ path
1308
+ };
1309
+ this._tools.set(operationId, tool);
1310
+ }
1311
+ }
1312
+ }
1313
+ /**
1314
+ * Parse operation parameters into a schema
1315
+ */
1316
+ _parseParameters(operation, _path) {
1317
+ const result = {
1318
+ type: "object",
1319
+ properties: {},
1320
+ required: []
1321
+ };
1322
+ const params = operation.parameters;
1323
+ if (params && Array.isArray(params)) {
1324
+ for (const param of params) {
1325
+ const name = param.name;
1326
+ const schema = param.schema;
1327
+ const required = param.required;
1328
+ if (!name) continue;
1329
+ result.properties[name] = {
1330
+ type: schema?.type || "string",
1331
+ description: param.description || void 0,
1332
+ ...schema
1333
+ };
1334
+ if (required) {
1335
+ result.required.push(name);
1336
+ }
1337
+ }
1338
+ }
1339
+ const requestBody = operation.requestBody;
1340
+ if (requestBody) {
1341
+ const content = requestBody.content;
1342
+ if (content) {
1343
+ const jsonContent = content["application/json"];
1344
+ if (jsonContent && jsonContent.schema) {
1345
+ result.properties["body"] = jsonContent.schema;
1346
+ if (requestBody.required) {
1347
+ result.required.push("body");
1348
+ }
1349
+ }
1350
+ }
1351
+ }
1352
+ return result;
1353
+ }
1354
+ };
1355
+ exports.ApiSet = class _ApiSet {
1356
+ _tools;
1357
+ _invoker;
1358
+ // Can be OpenAPI or MCP invoker
1359
+ _baseUrl;
1360
+ _defaultHeaders;
1361
+ _defaultQueryParams;
1362
+ _baseConfig;
1363
+ constructor(tools, invoker, baseUrl, headers, queryParams, config2) {
1364
+ this._tools = new Map(tools.filter((t) => t.name).map((t) => [t.name, t]));
1365
+ this._invoker = invoker;
1366
+ this._baseUrl = baseUrl;
1367
+ this._defaultHeaders = headers ? { ...headers } : {};
1368
+ this._defaultQueryParams = queryParams ? { ...queryParams } : {};
1369
+ this._baseConfig = config2;
1370
+ }
1371
+ /**
1372
+ * Invoke a tool by name
1373
+ * 调用指定的工具
1374
+ */
1375
+ invoke = async (name, args = {}, config2) => {
1376
+ if (!this._tools.has(name)) {
1377
+ throw new Error(`Tool '${name}' not found.`);
1378
+ }
1379
+ const convertedArgs = this._convertArguments(args);
1380
+ const effectiveConfig = Config.withConfigs(this._baseConfig, config2);
1381
+ if (typeof this._invoker.invokeToolAsync === "function") {
1382
+ return await this._invoker.invokeToolAsync(name, convertedArgs, effectiveConfig);
1383
+ } else if (typeof this._invoker.invoke_tool === "function") {
1384
+ return await this._invoker.invoke_tool(name, convertedArgs, effectiveConfig);
1385
+ } else if (typeof this._invoker === "function") {
1386
+ return await this._invoker(name, convertedArgs);
1387
+ } else {
1388
+ throw new Error("Invalid invoker provided.");
1389
+ }
1390
+ };
1391
+ /**
1392
+ * Get all tools
1393
+ * 返回所有工具列表
1394
+ */
1395
+ get tools() {
1396
+ return Array.from(this._tools.values());
1397
+ }
1398
+ /**
1399
+ * Get a specific tool
1400
+ * 获取指定名称的工具
1401
+ */
1402
+ getTool(name) {
1403
+ return this._tools.get(name);
1404
+ }
1405
+ /**
1406
+ * Convert arguments from framework-specific types to native JavaScript types
1407
+ * 将常见框架类型转换为 JavaScript 原生类型
1408
+ *
1409
+ * Purpose: Ensure we send JSON-serializable data to OpenAPI
1410
+ * 目的:确保我们发送到 OpenAPI 的 JSON body 是可以被序列化的
1411
+ */
1412
+ _convertToNative(value) {
1413
+ if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1414
+ return value;
1415
+ }
1416
+ if (Array.isArray(value)) {
1417
+ return value.map((item) => this._convertToNative(item));
1418
+ }
1419
+ if (typeof value === "object") {
1420
+ const obj = value;
1421
+ if (typeof obj.toJSON === "function") {
1422
+ try {
1423
+ return this._convertToNative(obj.toJSON());
1424
+ } catch {
1425
+ }
1426
+ }
1427
+ const result = {};
1428
+ for (const [k, v] of Object.entries(obj)) {
1429
+ result[k] = this._convertToNative(v);
1430
+ }
1431
+ return result;
1432
+ }
1433
+ return value;
1434
+ }
1435
+ /**
1436
+ * Convert arguments dictionary
1437
+ * 转换参数字典
1438
+ */
1439
+ _convertArguments(args) {
1440
+ if (!args || typeof args !== "object") {
1441
+ return args;
1442
+ }
1443
+ const result = {};
1444
+ for (const [k, v] of Object.entries(args)) {
1445
+ result[k] = this._convertToNative(v);
1446
+ }
1447
+ return result;
1448
+ }
1449
+ /**
1450
+ * Create ApiSet from MCP tools
1451
+ * 从 MCP tools 创建 ApiSet
1452
+ *
1453
+ * @param tools - MCP tools list or single tool / MCP tools 列表或单个工具
1454
+ * @param mcpClient - MCP client (MCPToolSet instance) / MCP 客户端(MCPToolSet 实例)
1455
+ * @param config - Configuration object / 配置对象
1456
+ */
1457
+ static fromMCPTools(params) {
1458
+ const { tools, mcpClient, config: config2 } = params;
1459
+ const toolInfos = [];
1460
+ let toolArray;
1461
+ if (Array.isArray(tools)) {
1462
+ toolArray = tools;
1463
+ } else if (tools) {
1464
+ toolArray = [tools];
1465
+ } else {
1466
+ toolArray = [];
1467
+ }
1468
+ for (const tool of toolArray) {
1469
+ if (!tool) {
1470
+ continue;
1471
+ }
1472
+ try {
1473
+ const { ToolInfo: ToolInfo2 } = (init_model2(), __toCommonJS(model_exports));
1474
+ const toolInfo = ToolInfo2.fromMCPTool(tool);
1475
+ toolInfos.push(toolInfo);
1476
+ } catch (error) {
1477
+ logger.warn(`Failed to parse MCP tool:`, error);
1478
+ continue;
1479
+ }
1480
+ }
1481
+ class MCPInvoker {
1482
+ constructor(mcpClient2, config3) {
1483
+ this.mcpClient = mcpClient2;
1484
+ this.config = config3;
1485
+ }
1486
+ invokeToolAsync = async (name, args, config3) => {
1487
+ const cfg = Config.withConfigs(this.config, config3);
1488
+ return await this.mcpClient.callToolAsync(name, args, cfg);
1489
+ };
1490
+ }
1491
+ const invoker = new MCPInvoker(mcpClient, config2);
1492
+ return new _ApiSet(toolInfos, invoker, void 0, void 0, void 0, config2);
1493
+ }
1494
+ };
1495
+ }
1496
+ });
1497
+
1498
+ // src/toolset/toolset.ts
1499
+ exports.ToolSet = void 0;
1500
+ var init_toolset = __esm({
1501
+ "src/toolset/toolset.ts"() {
1502
+ init_config();
1503
+ init_log();
1504
+ init_resource();
1505
+ exports.ToolSet = class _ToolSet {
1506
+ name;
1507
+ uid;
1508
+ kind;
1509
+ description;
1510
+ createdTime;
1511
+ generation;
1512
+ labels;
1513
+ spec;
1514
+ status;
1515
+ _config;
1516
+ constructor(data, config2) {
1517
+ if (data) {
1518
+ updateObjectProperties(this, data);
1519
+ }
1520
+ this._config = config2;
1521
+ }
1522
+ /**
1523
+ * Get DevS client
1524
+ */
1525
+ static getClient() {
1526
+ const { ToolSetClient: ToolSetClient2 } = (init_client(), __toCommonJS(client_exports));
1527
+ return new ToolSetClient2();
1528
+ }
1529
+ uniqIdCallback = () => this.name;
1530
+ /**
1531
+ * Create a new ToolSet
1532
+ */
1533
+ static async create(params) {
1534
+ const { input, config: config2 } = params;
1535
+ return await _ToolSet.getClient().create({ input, config: config2 });
1536
+ }
1537
+ /**
1538
+ * Delete a ToolSet by Name
1539
+ */
1540
+ static async delete(params) {
1541
+ const { name, config: config2 } = params;
1542
+ return await _ToolSet.getClient().delete({ name, config: config2 });
1543
+ }
1544
+ /**
1545
+ * Get a ToolSet by Name
1546
+ */
1547
+ static async get(params) {
1548
+ const { name, config: config2 } = params;
1549
+ return await _ToolSet.getClient().get({ name, config: config2 });
1550
+ }
1551
+ /**
1552
+ * List ToolSets
1553
+ */
1554
+ static list = async (...args) => {
1555
+ let input;
1556
+ let config2;
1557
+ if (args.length >= 1 && "input" in args[0]) {
1558
+ input = args[0].input;
1559
+ } else {
1560
+ input = args[0];
1561
+ }
1562
+ if (args.length >= 1 && "config" in args[0]) {
1563
+ config2 = args[0].config;
1564
+ } else if (args.length > 1 && args[1] instanceof Config) {
1565
+ config2 = args[1];
1566
+ }
1567
+ return await this.getClient().list({
1568
+ input: {
1569
+ ...input
1570
+ },
1571
+ config: config2
1572
+ });
1573
+ };
1574
+ static listAll = async (...args) => {
1575
+ let input;
1576
+ let config2;
1577
+ if (args.length >= 1 && "input" in args[0]) {
1578
+ input = args[0].input;
1579
+ } else {
1580
+ input = args[0];
1581
+ }
1582
+ if (args.length >= 1 && "config" in args[0]) {
1583
+ config2 = args[0].config;
1584
+ } else if (args.length > 1 && args[1] instanceof Config) {
1585
+ config2 = args[1];
1586
+ }
1587
+ return await listAllResourcesFunction(this.list)({ ...input, config: config2 });
1588
+ };
1589
+ /**
1590
+ * Update a ToolSet by Name
1591
+ */
1592
+ static async update(params) {
1593
+ const { name, input, config: config2 } = params;
1594
+ return await _ToolSet.getClient().update({ name, input, config: config2 });
1595
+ }
1596
+ /**
1597
+ * Delete this toolset
1598
+ */
1599
+ delete = async (params) => {
1600
+ const config2 = params?.config;
1601
+ if (!this.name) {
1602
+ throw new Error("name is required to delete a ToolSet");
1603
+ }
1604
+ const result = await _ToolSet.delete({
1605
+ name: this.name,
1606
+ config: config2 ?? this._config
1607
+ });
1608
+ updateObjectProperties(this, result);
1609
+ return this;
1610
+ };
1611
+ /**
1612
+ * Update this toolset
1613
+ */
1614
+ update = async (params) => {
1615
+ const { input, config: config2 } = params;
1616
+ if (!this.name) {
1617
+ throw new Error("name is required to update a ToolSet");
1618
+ }
1619
+ const result = await _ToolSet.update({
1620
+ name: this.name,
1621
+ input,
1622
+ config: config2 ?? this._config
1623
+ });
1624
+ updateObjectProperties(this, result);
1625
+ return this;
1626
+ };
1627
+ /**
1628
+ * Refresh this toolset's data
1629
+ */
1630
+ refresh = async (params) => {
1631
+ const config2 = params?.config;
1632
+ if (!this.name) {
1633
+ throw new Error("name is required to refresh a ToolSet");
1634
+ }
1635
+ const result = await _ToolSet.get({
1636
+ name: this.name,
1637
+ config: config2 ?? this._config
1638
+ });
1639
+ updateObjectProperties(this, result);
1640
+ return this;
1641
+ };
1642
+ /**
1643
+ * Get toolset type
1644
+ * 获取工具集类型
1645
+ */
1646
+ type() {
1647
+ return this.spec?.schema?.type;
1648
+ }
1649
+ /**
1650
+ * List tools (async)
1651
+ * 异步获取工具列表,返回统一的 ToolInfo 列表
1652
+ */
1653
+ listToolsAsync = async (params) => {
1654
+ const { ToolSetSchemaType: ToolSetSchemaType2 } = (init_model2(), __toCommonJS(model_exports));
1655
+ const { ToolInfo: ToolInfo2 } = (init_model2(), __toCommonJS(model_exports));
1656
+ if (this.type() === ToolSetSchemaType2.MCP) {
1657
+ const mcpTools = this.status?.outputs?.tools || [];
1658
+ return mcpTools.map((tool) => ToolInfo2.fromMCPTool(tool));
1659
+ } else if (this.type() === ToolSetSchemaType2.OPENAPI) {
1660
+ const apiset = await this.toApiSet(params);
1661
+ return apiset.tools;
1662
+ }
1663
+ return [];
1664
+ };
1665
+ /**
1666
+ * List tools (sync wrapper)
1667
+ * 同步获取工具列表,返回统一的 ToolInfo 列表
1668
+ */
1669
+ listTools = (config2) => {
1670
+ return this.listToolsAsync({ config: config2 });
1671
+ };
1672
+ /**
1673
+ * Call tool (async)
1674
+ * 异步调用工具,统一使用 ApiSet 实现
1675
+ */
1676
+ callToolAsync = async (name, args, config2) => {
1677
+ const apiset = await this.toApiSet({ config: config2 });
1678
+ const { ToolSetSchemaType: ToolSetSchemaType2 } = (init_model2(), __toCommonJS(model_exports));
1679
+ if (this.type() === ToolSetSchemaType2.OPENAPI) {
1680
+ const tool = apiset.getTool(name);
1681
+ if (!tool) {
1682
+ const openApiTools = this.status?.outputs?.openApiTools || [];
1683
+ for (const toolMeta of openApiTools) {
1684
+ if (!toolMeta) continue;
1685
+ if (toolMeta.toolId === name || toolMeta.tool_id === name) {
1686
+ name = toolMeta.toolName || toolMeta.tool_name || name;
1687
+ break;
1688
+ }
1689
+ }
1690
+ }
1691
+ }
1692
+ logger.debug(`Invoke tool ${name} with arguments`, args);
1693
+ const result = await apiset.invoke(name, args, config2);
1694
+ logger.debug(`Invoke tool ${name} got result`, result);
1695
+ return result;
1696
+ };
1697
+ /**
1698
+ * Call tool (sync wrapper)
1699
+ * 同步调用工具,统一使用 ApiSet 实现
1700
+ */
1701
+ callTool = (name, args, config2) => {
1702
+ return this.callToolAsync(name, args, config2);
1703
+ };
1704
+ /**
1705
+ * Convert ToolSet to unified ApiSet object
1706
+ * 将 ToolSet 转换为统一的 ApiSet 对象
1707
+ */
1708
+ toApiSet = async (params) => {
1709
+ const { ApiSet: ApiSet2 } = (init_openapi(), __toCommonJS(openapi_exports));
1710
+ const { ToolSetSchemaType: ToolSetSchemaType2 } = (init_model2(), __toCommonJS(model_exports));
1711
+ if (this.type() === ToolSetSchemaType2.MCP) {
1712
+ const { MCPToolSet: MCPToolSet2 } = (init_mcp(), __toCommonJS(mcp_exports));
1713
+ const mcpServerConfig = this.status?.outputs?.mcpServerConfig;
1714
+ if (!mcpServerConfig?.url) {
1715
+ throw new Error("MCP server URL is missing.");
1716
+ }
1717
+ const cfg = Config.withConfigs(
1718
+ params?.config,
1719
+ new Config({ headers: mcpServerConfig.headers })
1720
+ );
1721
+ const mcpClient = new MCPToolSet2(mcpServerConfig.url, cfg);
1722
+ const mcpTools = this.status?.outputs?.tools || [];
1723
+ return ApiSet2.fromMCPTools({
1724
+ tools: mcpTools,
1725
+ mcpClient,
1726
+ config: cfg
1727
+ });
1728
+ } else if (this.type() === ToolSetSchemaType2.OPENAPI) {
1729
+ const headers = this._getOpenAPIAuthDefaults().headers;
1730
+ const query = this._getOpenAPIAuthDefaults().query;
1731
+ const { OpenAPI: OpenAPI2 } = (init_openapi(), __toCommonJS(openapi_exports));
1732
+ const openapi = new OpenAPI2({
1733
+ schema: this.spec?.schema?.detail || "{}",
1734
+ baseUrl: this._getOpenAPIBaseUrl(),
1735
+ headers,
1736
+ queryParams: query,
1737
+ config: params?.config
1738
+ });
1739
+ const { ToolInfo: ToolInfo2 } = (init_model2(), __toCommonJS(model_exports));
1740
+ const tools = openapi.tools.map(
1741
+ (t) => new ToolInfo2({
1742
+ name: t.name,
1743
+ description: t.description,
1744
+ parameters: t.parameters
1745
+ })
1746
+ );
1747
+ return new ApiSet2(tools, openapi, void 0, headers, query, params?.config);
1748
+ }
1749
+ throw new Error(`Unsupported ToolSet type: ${this.type()}`);
1750
+ };
1751
+ /**
1752
+ * Get OpenAPI authentication defaults
1753
+ * 获取 OpenAPI 认证默认值
1754
+ */
1755
+ _getOpenAPIAuthDefaults() {
1756
+ const headers = {};
1757
+ const query = {};
1758
+ const authConfig = this.spec?.authConfig;
1759
+ const authType = authConfig?.type;
1760
+ if (authType === "APIKey") {
1761
+ const key = authConfig?.apiKeyHeaderName;
1762
+ const value = authConfig?.apiKeyValue;
1763
+ if (key && value) {
1764
+ {
1765
+ headers[key] = value;
1766
+ }
1767
+ }
1768
+ }
1769
+ return { headers, query };
1770
+ }
1771
+ /**
1772
+ * Get OpenAPI base URL
1773
+ * 获取 OpenAPI 基础 URL
1774
+ */
1775
+ _getOpenAPIBaseUrl() {
1776
+ const outputs = this.status?.outputs;
1777
+ return outputs?.urls?.internetUrl || outputs?.urls?.intranetUrl;
1778
+ }
1779
+ };
1780
+ }
1781
+ });
1782
+
1783
+ // src/toolset/client.ts
1784
+ var client_exports = {};
1785
+ __export(client_exports, {
1786
+ ToolSetClient: () => exports.ToolSetClient
1787
+ });
1788
+ exports.ToolSetClient = void 0;
1789
+ var init_client = __esm({
1790
+ "src/toolset/client.ts"() {
1791
+ init_config();
1792
+ init_exception();
1793
+ init_api();
1794
+ init_toolset();
1795
+ exports.ToolSetClient = class {
1796
+ config;
1797
+ controlApi;
1798
+ constructor(config2) {
1799
+ this.config = config2;
1800
+ this.controlApi = new exports.ToolControlAPI(config2);
1801
+ }
1802
+ /**
1803
+ * Create a ToolSet
1804
+ */
1805
+ create = async (params) => {
1806
+ const { input, config: config2 } = params;
1807
+ const cfg = Config.withConfigs(this.config, config2);
1808
+ try {
1809
+ const authConfig = input.spec?.authConfig ? new $Devs.Authorization({
1810
+ type: input.spec.authConfig.type,
1811
+ parameters: new $Devs.AuthorizationParameters({
1812
+ apiKeyParameter: new $Devs.APIKeyAuthParameter({
1813
+ key: input.spec.authConfig.apiKeyHeaderName,
1814
+ value: input.spec.authConfig.apiKeyValue,
1815
+ in: "header"
1816
+ })
1817
+ })
1818
+ }) : void 0;
1819
+ const request = new $Devs.Toolset({
1820
+ ...input,
1821
+ spec: input.spec ? new $Devs.ToolsetSpec({
1822
+ ...input.spec,
1823
+ schema: input.spec.schema ? new $Devs.ToolsetSchema({
1824
+ ...input.spec.schema
1825
+ }) : void 0,
1826
+ authConfig
1827
+ }) : void 0
1828
+ });
1829
+ const result = await this.controlApi.createToolset({
1830
+ input: request,
1831
+ config: cfg
1832
+ });
1833
+ return new exports.ToolSet(result, cfg);
1834
+ } catch (error) {
1835
+ if (error instanceof HTTPError) {
1836
+ throw error.toResourceError("ToolSet", input.name);
1837
+ }
1838
+ throw error;
1839
+ }
1840
+ };
1841
+ /**
1842
+ * Delete a ToolSet by name
1843
+ */
1844
+ delete = async (params) => {
1845
+ const { name, config: config2 } = params;
1846
+ const cfg = Config.withConfigs(this.config, config2);
1847
+ try {
1848
+ const result = await this.controlApi.deleteToolset({
1849
+ name,
1850
+ config: cfg
1851
+ });
1852
+ return new exports.ToolSet(result, cfg);
1853
+ } catch (error) {
1854
+ if (error instanceof HTTPError) {
1855
+ throw error.toResourceError("ToolSet", name);
1856
+ }
1857
+ throw error;
1858
+ }
1859
+ };
1860
+ /**
1861
+ * Update a ToolSet by name
1862
+ */
1863
+ update = async (params) => {
1864
+ const { name, input, config: config2 } = params;
1865
+ const cfg = Config.withConfigs(this.config, config2);
1866
+ try {
1867
+ const authConfig = input.spec?.authConfig ? new $Devs.Authorization({
1868
+ type: input.spec.authConfig.type,
1869
+ parameters: new $Devs.AuthorizationParameters({
1870
+ apiKeyParameter: new $Devs.APIKeyAuthParameter({
1871
+ key: input.spec.authConfig.apiKeyHeaderName,
1872
+ value: input.spec.authConfig.apiKeyValue,
1873
+ in: "header"
1874
+ })
1875
+ })
1876
+ }) : void 0;
1877
+ const request = new $Devs.Toolset({
1878
+ name,
1879
+ ...input,
1880
+ spec: input.spec ? new $Devs.ToolsetSpec({
1881
+ ...input.spec,
1882
+ schema: input.spec.schema ? new $Devs.ToolsetSchema({
1883
+ ...input.spec.schema
1884
+ }) : void 0,
1885
+ authConfig
1886
+ }) : void 0
1887
+ });
1888
+ const result = await this.controlApi.updateToolset({
1889
+ name,
1890
+ input: request,
1891
+ config: cfg
1892
+ });
1893
+ return new exports.ToolSet(result, cfg);
1894
+ } catch (error) {
1895
+ if (error instanceof HTTPError) {
1896
+ throw error.toResourceError("ToolSet", name);
1897
+ }
1898
+ throw error;
1899
+ }
1900
+ };
1901
+ /**
1902
+ * Get a ToolSet by name
1903
+ */
1904
+ get = async (params) => {
1905
+ const { name, config: config2 } = params;
1906
+ const cfg = Config.withConfigs(this.config, config2);
1907
+ try {
1908
+ const result = await this.controlApi.getToolset({
1909
+ name,
1910
+ config: cfg
1911
+ });
1912
+ return new exports.ToolSet(result, cfg);
1913
+ } catch (error) {
1914
+ if (error instanceof HTTPError) {
1915
+ throw error.toResourceError("ToolSet", name);
1916
+ }
1917
+ throw error;
1918
+ }
1919
+ };
1920
+ /**
1921
+ * List ToolSets
1922
+ */
1923
+ list = async (params) => {
1924
+ const { input, config: config2 } = params ?? {};
1925
+ const cfg = Config.withConfigs(this.config, config2);
1926
+ const results = await this.controlApi.listToolsets({
1927
+ input: new $Devs.ListToolsetsRequest({ ...input }),
1928
+ config: cfg
1929
+ });
1930
+ return results.data?.map((result) => new exports.ToolSet(result, cfg)) || [];
1931
+ };
1932
+ };
1933
+ }
1934
+ });
1935
+
1936
+ // src/toolset/index.ts
1937
+ init_version_check();
1938
+ init_client();
1939
+ init_toolset();
1940
+ init_openapi();
1941
+ init_model2();
1942
+ init_control();
1943
+ init_mcp();
1944
+ //# sourceMappingURL=index.cjs.map
1945
+ //# sourceMappingURL=index.cjs.map