@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,951 @@
1
+ import * as dotenv from 'dotenv';
2
+ import * as $AgentRun from '@alicloud/agentrun20250910';
3
+ import * as $OpenApi from '@alicloud/openapi-client';
4
+ import * as http from 'http';
5
+ import * as https from 'https';
6
+ import * as fs from 'fs';
7
+ import * as nodePath from 'path';
8
+ import { URL } from 'url';
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __esm = (fn, res) => function __init() {
13
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
14
+ };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+ function getEnvWithDefault(defaultValue, ...keys) {
20
+ for (const key of keys) {
21
+ const value = process.env[key];
22
+ if (value !== void 0 && value !== "") {
23
+ return value;
24
+ }
25
+ }
26
+ return defaultValue;
27
+ }
28
+ var Config;
29
+ var init_config = __esm({
30
+ "src/utils/config.ts"() {
31
+ dotenv.config();
32
+ Config = class _Config {
33
+ _accessKeyId;
34
+ _accessKeySecret;
35
+ _securityToken;
36
+ _accountId;
37
+ _token;
38
+ _regionId;
39
+ _timeout;
40
+ _readTimeout;
41
+ _controlEndpoint;
42
+ _dataEndpoint;
43
+ _devsEndpoint;
44
+ _headers;
45
+ constructor(options = {}) {
46
+ this._accessKeyId = options.accessKeyId ?? getEnvWithDefault("", "AGENTRUN_ACCESS_KEY_ID", "ALIBABA_CLOUD_ACCESS_KEY_ID");
47
+ this._accessKeySecret = options.accessKeySecret ?? getEnvWithDefault("", "AGENTRUN_ACCESS_KEY_SECRET", "ALIBABA_CLOUD_ACCESS_KEY_SECRET");
48
+ this._securityToken = options.securityToken ?? getEnvWithDefault("", "AGENTRUN_SECURITY_TOKEN", "ALIBABA_CLOUD_SECURITY_TOKEN");
49
+ this._accountId = options.accountId ?? getEnvWithDefault("", "AGENTRUN_ACCOUNT_ID", "FC_ACCOUNT_ID");
50
+ this._token = options.token;
51
+ this._regionId = options.regionId ?? getEnvWithDefault("cn-hangzhou", "AGENTRUN_REGION", "FC_REGION");
52
+ this._timeout = options.timeout ?? 6e5;
53
+ this._readTimeout = options.readTimeout ?? 1e8;
54
+ this._controlEndpoint = options.controlEndpoint ?? getEnvWithDefault("", "AGENTRUN_CONTROL_ENDPOINT");
55
+ this._dataEndpoint = options.dataEndpoint ?? getEnvWithDefault("", "AGENTRUN_DATA_ENDPOINT");
56
+ this._devsEndpoint = options.devsEndpoint ?? getEnvWithDefault("", "DEVS_ENDPOINT");
57
+ this._headers = options.headers ?? {};
58
+ }
59
+ /**
60
+ * Create a new Config by merging multiple configs.
61
+ * Later configs take precedence.
62
+ */
63
+ static withConfigs(...configs) {
64
+ return new _Config().update(...configs);
65
+ }
66
+ /**
67
+ * Update this config with values from other configs.
68
+ * Non-undefined values from later configs take precedence.
69
+ */
70
+ update(...configs) {
71
+ for (const config2 of configs) {
72
+ if (!config2) continue;
73
+ if (config2._accessKeyId) this._accessKeyId = config2._accessKeyId;
74
+ if (config2._accessKeySecret) this._accessKeySecret = config2._accessKeySecret;
75
+ if (config2._securityToken) this._securityToken = config2._securityToken;
76
+ if (config2._accountId) this._accountId = config2._accountId;
77
+ if (config2._token) this._token = config2._token;
78
+ if (config2._regionId) this._regionId = config2._regionId;
79
+ if (config2._timeout) this._timeout = config2._timeout;
80
+ if (config2._readTimeout) this._readTimeout = config2._readTimeout;
81
+ if (config2._controlEndpoint) this._controlEndpoint = config2._controlEndpoint;
82
+ if (config2._dataEndpoint) this._dataEndpoint = config2._dataEndpoint;
83
+ if (config2._devsEndpoint) this._devsEndpoint = config2._devsEndpoint;
84
+ if (config2._headers && Object.keys(config2._headers).length > 0) {
85
+ this._headers = { ...this._headers, ...config2._headers };
86
+ }
87
+ }
88
+ return this;
89
+ }
90
+ get accessKeyId() {
91
+ return this._accessKeyId;
92
+ }
93
+ get accessKeySecret() {
94
+ return this._accessKeySecret;
95
+ }
96
+ get securityToken() {
97
+ return this._securityToken;
98
+ }
99
+ get accountId() {
100
+ if (!this._accountId) {
101
+ throw new Error(
102
+ "Account ID is not set. Please add AGENTRUN_ACCOUNT_ID environment variable or set it in code."
103
+ );
104
+ }
105
+ return this._accountId;
106
+ }
107
+ get token() {
108
+ return this._token;
109
+ }
110
+ get regionId() {
111
+ return this._regionId || "cn-hangzhou";
112
+ }
113
+ get timeout() {
114
+ return this._timeout || 6e5;
115
+ }
116
+ get readTimeout() {
117
+ return this._readTimeout || 1e8;
118
+ }
119
+ get controlEndpoint() {
120
+ if (this._controlEndpoint) {
121
+ return this._controlEndpoint;
122
+ }
123
+ return `https://agentrun.${this.regionId}.aliyuncs.com`;
124
+ }
125
+ get dataEndpoint() {
126
+ if (this._dataEndpoint) {
127
+ return this._dataEndpoint;
128
+ }
129
+ return `https://${this.accountId}.agentrun-data.${this.regionId}.aliyuncs.com`;
130
+ }
131
+ get devsEndpoint() {
132
+ if (this._devsEndpoint) {
133
+ return this._devsEndpoint;
134
+ }
135
+ return `https://devs.${this.regionId}.aliyuncs.com`;
136
+ }
137
+ get headers() {
138
+ return this._headers;
139
+ }
140
+ };
141
+ }
142
+ });
143
+
144
+ // src/utils/control-api.ts
145
+ var control_api_exports = {};
146
+ __export(control_api_exports, {
147
+ $AgentRun: () => $AgentRun,
148
+ ControlAPI: () => ControlAPI
149
+ });
150
+ var $AgentRunClient, ControlAPI;
151
+ var init_control_api = __esm({
152
+ "src/utils/control-api.ts"() {
153
+ init_config();
154
+ $AgentRunClient = // @ts-expect-error - ESM interop: default.default exists when imported as ESM namespace
155
+ $AgentRun.default?.default ?? $AgentRun.default ?? $AgentRun;
156
+ ControlAPI = class {
157
+ config;
158
+ constructor(config2) {
159
+ this.config = config2;
160
+ }
161
+ /**
162
+ * Get the underlying AgentRun client instance
163
+ */
164
+ getClient(config2) {
165
+ const cfg = Config.withConfigs(this.config, config2);
166
+ let endpoint = cfg.controlEndpoint;
167
+ if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
168
+ endpoint = endpoint.split("://")[1];
169
+ }
170
+ const openApiConfig = new $OpenApi.Config({
171
+ accessKeyId: cfg.accessKeyId,
172
+ accessKeySecret: cfg.accessKeySecret,
173
+ securityToken: cfg.securityToken || void 0,
174
+ regionId: cfg.regionId,
175
+ endpoint,
176
+ connectTimeout: cfg.timeout,
177
+ readTimeout: cfg.readTimeout
178
+ });
179
+ return new $AgentRunClient(openApiConfig);
180
+ }
181
+ };
182
+ }
183
+ });
184
+
185
+ // src/utils/log.ts
186
+ var LOG_LEVELS = {
187
+ debug: 0,
188
+ info: 1,
189
+ warn: 2,
190
+ error: 3
191
+ };
192
+ var COLORS = {
193
+ reset: "\x1B[0m",
194
+ bright: "\x1B[1m",
195
+ dim: "\x1B[2m",
196
+ italic: "\x1B[3m",
197
+ blue: "\x1B[34m",
198
+ cyan: "\x1B[36m",
199
+ yellow: "\x1B[33m",
200
+ red: "\x1B[31m"
201
+ };
202
+ var Logger = class {
203
+ level = "info";
204
+ // match Python logger name
205
+ prefix = "agentrun-logger";
206
+ setLevel(level) {
207
+ this.level = level;
208
+ }
209
+ shouldLog(level) {
210
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
211
+ }
212
+ getColor(level) {
213
+ switch (level) {
214
+ case "debug":
215
+ return COLORS.cyan;
216
+ case "info":
217
+ return COLORS.blue;
218
+ case "warn":
219
+ return COLORS.yellow;
220
+ case "error":
221
+ return COLORS.red;
222
+ default:
223
+ return COLORS.reset;
224
+ }
225
+ }
226
+ // format timestamp like Python: YYYY-MM-DD HH:mm:ss,SSS
227
+ formatTimestamp(d = /* @__PURE__ */ new Date()) {
228
+ const pad = (n, sz = 2) => n.toString().padStart(sz, "0");
229
+ const year = d.getFullYear();
230
+ const month = pad(d.getMonth() + 1);
231
+ const day = pad(d.getDate());
232
+ const hour = pad(d.getHours());
233
+ const minute = pad(d.getMinutes());
234
+ const second = pad(d.getSeconds());
235
+ const ms = pad(d.getMilliseconds(), 3);
236
+ return `${year}-${month}-${day} ${hour}:${minute}:${second},${ms}`;
237
+ }
238
+ // attempt to infer caller file and line by parsing Error.stack
239
+ // helper: parse a single stack frame into {filepath, line, functionName}
240
+ parseFrame(frame) {
241
+ const m = frame.match(/^(?:at\s+)?(?:(.+?)\s+\()?(.*?):(\d+):(\d+)\)?$/);
242
+ if (!m) return null;
243
+ return {
244
+ functionName: m[1] ? m[1].trim() : void 0,
245
+ filepath: m[2],
246
+ line: parseInt(m[3], 10)
247
+ };
248
+ }
249
+ // get caller by fixed stack offset (used in public log methods)
250
+ getCallerByOffset() {
251
+ const err = new Error();
252
+ const stack = err.stack;
253
+ if (!stack) return {};
254
+ const lines = stack.split("\n").map((l) => l.trim());
255
+ for (let i = 3; i < lines.length; i++) {
256
+ let parsed = this.parseFrame(lines[i]);
257
+ if (!parsed) {
258
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
259
+ if (m) {
260
+ const parts = m[1].split(":");
261
+ parts.pop();
262
+ const ln = Number(parts.pop());
263
+ const fp2 = parts.join(":");
264
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
265
+ }
266
+ }
267
+ if (!parsed) continue;
268
+ const fp = parsed.filepath;
269
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
270
+ continue;
271
+ return { filepath: parsed.filepath, line: parsed.line };
272
+ }
273
+ const cwd = process.cwd();
274
+ for (let i = 0; i < lines.length; i++) {
275
+ let parsed = this.parseFrame(lines[i]);
276
+ if (!parsed) {
277
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
278
+ if (m) {
279
+ const parts = m[1].split(":");
280
+ parts.pop();
281
+ const ln = Number(parts.pop());
282
+ const fp2 = parts.join(":");
283
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
284
+ }
285
+ }
286
+ if (!parsed) continue;
287
+ const fp = parsed.filepath;
288
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
289
+ continue;
290
+ if (fp.includes("/src/utils/log.ts")) continue;
291
+ if (fp.startsWith(cwd)) return { filepath: parsed.filepath, line: parsed.line };
292
+ }
293
+ for (let i = 0; i < lines.length; i++) {
294
+ let parsed = this.parseFrame(lines[i]);
295
+ if (!parsed) {
296
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
297
+ if (m) {
298
+ const parts = m[1].split(":");
299
+ parts.pop();
300
+ const ln = Number(parts.pop());
301
+ const fp2 = parts.join(":");
302
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
303
+ }
304
+ }
305
+ if (!parsed) continue;
306
+ const fp = parsed.filepath;
307
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
308
+ continue;
309
+ if (fp.includes("/src/utils/log.ts")) continue;
310
+ return { filepath: parsed.filepath, line: parsed.line };
311
+ }
312
+ return {};
313
+ }
314
+ formatMessage(level, message, filepath, line) {
315
+ const timestamp = this.formatTimestamp();
316
+ const color = this.getColor(level);
317
+ const reset = COLORS.reset;
318
+ const levelName = level === "warn" ? "WARNING" : level.toUpperCase();
319
+ const levelStr = `${COLORS.bright}${color}${levelName}${reset}`;
320
+ const nameStr = `${color}[${this.prefix}]${reset}`;
321
+ const tsStr = `${color} ${timestamp}${reset}`;
322
+ const pathInfo = filepath && line !== void 0 ? ` ${COLORS.dim}${COLORS.italic}${filepath}:${line}${reset}` : "";
323
+ const msg = level === "debug" ? `${COLORS.dim}${message}${reset}` : message;
324
+ return `
325
+ ${levelStr} ${nameStr}${tsStr}${pathInfo}
326
+ ${msg}
327
+ `;
328
+ }
329
+ debug(message, ...args) {
330
+ if (this.shouldLog("debug")) {
331
+ const caller = this.getCallerByOffset();
332
+ console.debug(this.formatMessage("debug", message, caller.filepath, caller.line), ...args);
333
+ }
334
+ }
335
+ info(message, ...args) {
336
+ if (this.shouldLog("info")) {
337
+ const caller = this.getCallerByOffset();
338
+ console.info(this.formatMessage("info", message, caller.filepath, caller.line), ...args);
339
+ }
340
+ }
341
+ warn(message, ...args) {
342
+ if (this.shouldLog("warn")) {
343
+ const caller = this.getCallerByOffset();
344
+ console.warn(this.formatMessage("warn", message, caller.filepath, caller.line), ...args);
345
+ }
346
+ }
347
+ error(message, ...args) {
348
+ if (this.shouldLog("error")) {
349
+ const caller = this.getCallerByOffset();
350
+ console.error(this.formatMessage("error", message, caller.filepath, caller.line), ...args);
351
+ }
352
+ }
353
+ };
354
+ var logger = new Logger();
355
+ if (![void 0, null, "", "False", "FALSE", "false", "0"].includes(process.env["AGENTRUN_SDK_DEBUG"])) {
356
+ logger.setLevel("debug");
357
+ if (!globalThis._AGENTRUN_DEBUG_LOGGED) {
358
+ logger.warn("\u542F\u7528 AgentRun SDK \u8C03\u8BD5\u65E5\u5FD7\uFF0C \u79FB\u9664 AGENTRUN_SDK_DEBUG \u73AF\u5883\u53D8\u91CF\u4EE5\u5173\u95ED");
359
+ globalThis._AGENTRUN_DEBUG_LOGGED = true;
360
+ }
361
+ } else {
362
+ logger.setLevel("info");
363
+ }
364
+
365
+ // src/utils/version-check.ts
366
+ var VERSION = "0.0.4" ;
367
+ if (!process.env.DISABLE_BREAKING_CHANGES_WARNING && !globalThis._AGENTRUN_VERSION_WARNING_SHOWN) {
368
+ globalThis._AGENTRUN_VERSION_WARNING_SHOWN = true;
369
+ logger.warn(
370
+ `\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
371
+ 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.
372
+ \x1B[2;3m pip install 'agentrun-sdk==${VERSION}' \x1B[0m
373
+
374
+ \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
375
+ Add\x1B[2;3m DISABLE_BREAKING_CHANGES_WARNING=1 \x1B[0mto your environment variables to disable this warning.
376
+
377
+ Releases:\x1B[2;3m https://github.com/Serverless-Devs/agentrun-sdk-python/releases\x1B[0m`
378
+ );
379
+ }
380
+
381
+ // src/utils/index.ts
382
+ init_config();
383
+
384
+ // src/utils/data-api.ts
385
+ init_config();
386
+
387
+ // src/utils/exception.ts
388
+ var AgentRunError = class _AgentRunError extends Error {
389
+ constructor(message) {
390
+ super(message);
391
+ this.name = "AgentRunError";
392
+ Object.setPrototypeOf(this, _AgentRunError.prototype);
393
+ }
394
+ };
395
+ var HTTPError = class _HTTPError extends AgentRunError {
396
+ statusCode;
397
+ requestId;
398
+ errorCode;
399
+ constructor(statusCode, message, options) {
400
+ super(message);
401
+ this.name = "HTTPError";
402
+ this.statusCode = statusCode;
403
+ this.requestId = options?.requestId;
404
+ this.errorCode = options?.errorCode;
405
+ Object.setPrototypeOf(this, _HTTPError.prototype);
406
+ }
407
+ /**
408
+ * Convert HTTP error to resource-specific error based on status code
409
+ */
410
+ toResourceError(resourceType, resourceId) {
411
+ if (this.statusCode == 404) return new ResourceNotExistError(resourceType, resourceId);
412
+ else if (this.statusCode == 409) return new ResourceAlreadyExistError(resourceType, resourceId);
413
+ else if ((this.statusCode == 400 || this.statusCode == 500) && this.message.includes("already exists"))
414
+ return new ResourceAlreadyExistError(resourceType, resourceId);
415
+ else return this;
416
+ }
417
+ };
418
+ var ClientError = class _ClientError extends HTTPError {
419
+ constructor(statusCode, message, options) {
420
+ super(statusCode, message, options);
421
+ this.name = "ClientError";
422
+ Object.setPrototypeOf(this, _ClientError.prototype);
423
+ }
424
+ };
425
+ var ServerError = class _ServerError extends HTTPError {
426
+ constructor(statusCode, message, options) {
427
+ super(statusCode, message, options);
428
+ this.name = "ServerError";
429
+ Object.setPrototypeOf(this, _ServerError.prototype);
430
+ }
431
+ };
432
+ var ResourceNotExistError = class _ResourceNotExistError extends ClientError {
433
+ resourceType;
434
+ resourceId;
435
+ constructor(resourceType, resourceId, options) {
436
+ const message = resourceId ? `${resourceType} '${resourceId}' does not exist` : `${resourceType} does not exist`;
437
+ super(404, message, options);
438
+ this.name = "ResourceNotExistError";
439
+ this.resourceType = resourceType;
440
+ this.resourceId = resourceId;
441
+ Object.setPrototypeOf(this, _ResourceNotExistError.prototype);
442
+ }
443
+ };
444
+ var ResourceAlreadyExistError = class _ResourceAlreadyExistError extends ClientError {
445
+ resourceType;
446
+ resourceId;
447
+ constructor(resourceType, resourceId, options) {
448
+ const message = resourceId ? `${resourceType} '${resourceId}' already exists` : `${resourceType} already exists`;
449
+ super(409, message, options);
450
+ this.name = "ResourceAlreadyExistError";
451
+ this.resourceType = resourceType;
452
+ this.resourceId = resourceId;
453
+ Object.setPrototypeOf(this, _ResourceAlreadyExistError.prototype);
454
+ }
455
+ };
456
+
457
+ // src/utils/data-api.ts
458
+ var ResourceType = /* @__PURE__ */ ((ResourceType2) => {
459
+ ResourceType2["Runtime"] = "runtime";
460
+ ResourceType2["LiteLLM"] = "litellm";
461
+ ResourceType2["Tool"] = "tool";
462
+ ResourceType2["Template"] = "template";
463
+ ResourceType2["Sandbox"] = "sandbox";
464
+ return ResourceType2;
465
+ })(ResourceType || {});
466
+ var DataAPI = class {
467
+ resourceName;
468
+ resourceType;
469
+ accessToken = null;
470
+ config;
471
+ namespace;
472
+ /**
473
+ * Initialize the Data API Client.
474
+ *
475
+ * @param resourceName - Resource name for access token
476
+ * @param resourceType - Resource type for access token
477
+ * @param config - Configuration options
478
+ * @param namespace - API namespace (default: "agents")
479
+ */
480
+ constructor(resourceName, resourceType, config2, namespace = "agents") {
481
+ this.resourceName = resourceName;
482
+ this.resourceType = resourceType;
483
+ this.config = Config.withConfigs(config2);
484
+ this.namespace = namespace;
485
+ const token = this.config.token;
486
+ if (token) {
487
+ logger.debug(`Using provided access token from config`);
488
+ this.accessToken = token;
489
+ }
490
+ }
491
+ /**
492
+ * Get the base URL for API requests.
493
+ */
494
+ getBaseUrl() {
495
+ return this.config.dataEndpoint;
496
+ }
497
+ /**
498
+ * Construct full URL with the given path and query parameters.
499
+ *
500
+ * @param path - API path (may include query string)
501
+ * @param query - Query parameters to add/merge
502
+ * @returns Complete URL string with query parameters
503
+ */
504
+ withPath(path, query) {
505
+ path = path.replace(/^\//, "");
506
+ const parts = [this.getBaseUrl(), this.namespace, path].filter(Boolean).map((part) => part.replace(/^\/|\/$/g, ""));
507
+ const baseUrl = parts.join("/");
508
+ if (!query || Object.keys(query).length === 0) {
509
+ return baseUrl;
510
+ }
511
+ const urlObj = new URL(baseUrl);
512
+ const existingParams = urlObj.searchParams;
513
+ for (const key in query) {
514
+ if (Object.prototype.hasOwnProperty.call(query, key)) {
515
+ const value = query[key];
516
+ if (Array.isArray(value)) {
517
+ value.forEach((v) => existingParams.append(key, String(v)));
518
+ } else if (value !== void 0 && value !== null) {
519
+ existingParams.set(key, String(value));
520
+ }
521
+ }
522
+ }
523
+ urlObj.search = existingParams.toString();
524
+ return urlObj.toString();
525
+ }
526
+ /**
527
+ * Authenticate and prepare headers for the request.
528
+ *
529
+ * @param url - Request URL
530
+ * @param headers - Request headers
531
+ * @param query - Query parameters
532
+ * @param config - Optional config override
533
+ * @returns Tuple of [url, headers, query]
534
+ */
535
+ async auth(url, headers, query, config2) {
536
+ const cfg = Config.withConfigs(this.config, config2);
537
+ if (this.accessToken === null && this.resourceName && this.resourceType && !cfg.token) {
538
+ try {
539
+ const { ControlAPI: ControlAPI2 } = await Promise.resolve().then(() => (init_control_api(), control_api_exports));
540
+ const $AgentRun2 = await import('@alicloud/agentrun20250910');
541
+ const cli = new ControlAPI2(this.config).getClient();
542
+ const input = this.resourceType === "sandbox" /* Sandbox */ ? new $AgentRun2.GetAccessTokenRequest({
543
+ resourceId: this.resourceName,
544
+ resourceType: this.resourceType
545
+ }) : new $AgentRun2.GetAccessTokenRequest({
546
+ resourceName: this.resourceName,
547
+ resourceType: this.resourceType
548
+ });
549
+ const resp = await cli.getAccessToken(input);
550
+ this.accessToken = resp.body?.data?.accessToken || null;
551
+ logger.debug(
552
+ `Fetched access token for resource ${this.resourceName} of type ${this.resourceType}`
553
+ );
554
+ } catch (e) {
555
+ logger.warn(
556
+ `Failed to get access token for ${this.resourceType}(${this.resourceName}): ${e}`
557
+ );
558
+ }
559
+ }
560
+ const authHeaders = {
561
+ "Agentrun-Access-Token": cfg.token || this.accessToken || "",
562
+ ...cfg.headers,
563
+ ...headers
564
+ };
565
+ return [url, authHeaders, query];
566
+ }
567
+ /**
568
+ * Prepare the HTTP request.
569
+ */
570
+ async prepareRequest(method, url, data, headers, query, config2) {
571
+ const reqHeaders = {
572
+ "Content-Type": "application/json",
573
+ "User-Agent": "AgentRunDataClient/1.0"
574
+ };
575
+ const cfg = Config.withConfigs(this.config, config2);
576
+ Object.assign(reqHeaders, cfg.headers);
577
+ if (headers) {
578
+ Object.assign(reqHeaders, headers);
579
+ }
580
+ const [authUrl, authHeaders, authQuery] = await this.auth(url, reqHeaders, query, cfg);
581
+ let finalUrl = authUrl;
582
+ if (authQuery && Object.keys(authQuery).length > 0) {
583
+ const urlObj = new URL(authUrl);
584
+ for (const key in authQuery) {
585
+ if (Object.prototype.hasOwnProperty.call(authQuery, key)) {
586
+ const value = authQuery[key];
587
+ if (value !== void 0 && value !== null) {
588
+ urlObj.searchParams.set(key, String(value));
589
+ }
590
+ }
591
+ }
592
+ finalUrl = urlObj.toString();
593
+ }
594
+ let body;
595
+ if (data !== void 0) {
596
+ if (Buffer.isBuffer(data)) {
597
+ body = data;
598
+ } else if (typeof data === "object") {
599
+ body = JSON.stringify(data);
600
+ } else {
601
+ body = data;
602
+ }
603
+ }
604
+ logger.debug(`${method} ${finalUrl} headers=${JSON.stringify(authHeaders)}`);
605
+ return { method, url: finalUrl, headers: authHeaders, body };
606
+ }
607
+ /**
608
+ * Make an HTTP request.
609
+ */
610
+ async makeRequest(method, path, data, query, headers, config2) {
611
+ const fullUrl = this.withPath(path, query);
612
+ const {
613
+ method: reqMethod,
614
+ url: reqUrl,
615
+ headers: reqHeaders,
616
+ body: reqBody
617
+ } = await this.prepareRequest(method, fullUrl, data, headers, void 0, config2);
618
+ const client = reqUrl.startsWith("https") ? https : http;
619
+ const urlObj = new URL(reqUrl);
620
+ const options = {
621
+ hostname: urlObj.hostname,
622
+ port: urlObj.port || (reqUrl.startsWith("https") ? 443 : 80),
623
+ path: urlObj.pathname + urlObj.search,
624
+ method: reqMethod,
625
+ headers: reqHeaders,
626
+ timeout: this.config.timeout
627
+ };
628
+ return new Promise((resolve, reject) => {
629
+ const req = client.request(options, (res) => {
630
+ let responseData = "";
631
+ res.on("data", (chunk) => responseData += chunk);
632
+ res.on("end", () => {
633
+ logger.debug(`Response: ${responseData}`);
634
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
635
+ try {
636
+ resolve(responseData ? JSON.parse(responseData) : {});
637
+ } catch (e) {
638
+ const errorMsg = `Failed to parse JSON response: ${e}`;
639
+ logger.error(errorMsg);
640
+ reject(new ClientError(res.statusCode || 0, errorMsg));
641
+ }
642
+ } else {
643
+ const errorMsg = responseData || res.statusMessage || "Unknown error";
644
+ reject(new ClientError(res.statusCode || 0, errorMsg));
645
+ }
646
+ });
647
+ });
648
+ req.on("error", (e) => {
649
+ reject(new ClientError(0, `Request error: ${e.message}`));
650
+ });
651
+ req.on("timeout", () => {
652
+ req.destroy();
653
+ reject(new ClientError(0, "Request timeout"));
654
+ });
655
+ if (reqBody) {
656
+ req.write(reqBody);
657
+ }
658
+ req.end();
659
+ });
660
+ }
661
+ /**
662
+ * Make a GET request.
663
+ *
664
+ * @param path - API path
665
+ * @param query - Query parameters
666
+ * @param headers - Additional headers
667
+ * @param config - Optional config override
668
+ */
669
+ async get(path, query, headers, config2) {
670
+ return this.makeRequest("GET", path, void 0, query, headers, config2);
671
+ }
672
+ /**
673
+ * Make a POST request.
674
+ *
675
+ * @param path - API path
676
+ * @param data - Request body
677
+ * @param query - Query parameters
678
+ * @param headers - Additional headers
679
+ * @param config - Optional config override
680
+ */
681
+ async post(path, data, query, headers, config2) {
682
+ return this.makeRequest("POST", path, data, query, headers, config2);
683
+ }
684
+ /**
685
+ * Make a PUT request.
686
+ *
687
+ * @param path - API path
688
+ * @param data - Request body
689
+ * @param query - Query parameters
690
+ * @param headers - Additional headers
691
+ * @param config - Optional config override
692
+ */
693
+ async put(path, data, query, headers, config2) {
694
+ return this.makeRequest("PUT", path, data, query, headers, config2);
695
+ }
696
+ /**
697
+ * Make a PATCH request.
698
+ *
699
+ * @param path - API path
700
+ * @param data - Request body
701
+ * @param query - Query parameters
702
+ * @param headers - Additional headers
703
+ * @param config - Optional config override
704
+ */
705
+ async patch(path, data, query, headers, config2) {
706
+ return this.makeRequest("PATCH", path, data, query, headers, config2);
707
+ }
708
+ /**
709
+ * Make a DELETE request.
710
+ *
711
+ * @param path - API path
712
+ * @param query - Query parameters
713
+ * @param headers - Additional headers
714
+ * @param config - Optional config override
715
+ */
716
+ async delete(path, query, headers, config2) {
717
+ return this.makeRequest("DELETE", path, void 0, query, headers, config2);
718
+ }
719
+ /**
720
+ * Upload a file using multipart/form-data.
721
+ *
722
+ * @param path - API path
723
+ * @param localFilePath - Local file path to upload
724
+ * @param targetFilePath - Target file path on the server
725
+ * @param formData - Additional form data fields
726
+ * @param query - Query parameters
727
+ * @param headers - Additional headers
728
+ * @param config - Optional config override
729
+ */
730
+ async postFile(path, localFilePath, targetFilePath, formData, query, headers, config2) {
731
+ const fullUrl = this.withPath(path, query);
732
+ const { url: reqUrl, headers: reqHeaders } = await this.prepareRequest(
733
+ "POST",
734
+ fullUrl,
735
+ void 0,
736
+ headers,
737
+ void 0,
738
+ config2
739
+ );
740
+ const client = reqUrl.startsWith("https") ? https : http;
741
+ const urlObj = new URL(reqUrl);
742
+ return new Promise((resolve, reject) => {
743
+ const boundary = `----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;
744
+ const contentHeaders = {
745
+ ...reqHeaders,
746
+ "Content-Type": `multipart/form-data; boundary=${boundary}`
747
+ };
748
+ const options = {
749
+ hostname: urlObj.hostname,
750
+ port: urlObj.port || (reqUrl.startsWith("https") ? 443 : 80),
751
+ path: urlObj.pathname + urlObj.search,
752
+ method: "POST",
753
+ headers: contentHeaders,
754
+ timeout: this.config.timeout
755
+ };
756
+ const req = client.request(options, (res) => {
757
+ let responseData = "";
758
+ res.on("data", (chunk) => responseData += chunk);
759
+ res.on("end", () => {
760
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
761
+ try {
762
+ resolve(responseData ? JSON.parse(responseData) : {});
763
+ } catch (e) {
764
+ logger.error(`Failed to parse JSON response: ${e}`);
765
+ reject(new ClientError(res.statusCode || 0, `Failed to parse JSON: ${e}`));
766
+ }
767
+ } else {
768
+ reject(new ClientError(res.statusCode || 0, responseData || "Unknown error"));
769
+ }
770
+ });
771
+ });
772
+ req.on("error", (e) => {
773
+ reject(new ClientError(0, `Request error: ${e.message}`));
774
+ });
775
+ const appendField = (name, value) => {
776
+ req.write(`--${boundary}\r
777
+ `);
778
+ req.write(`Content-Disposition: form-data; name="${name}"\r
779
+ `);
780
+ req.write("\r\n");
781
+ req.write(`${value}\r
782
+ `);
783
+ };
784
+ if (formData) {
785
+ for (const key in formData) {
786
+ if (Object.prototype.hasOwnProperty.call(formData, key)) {
787
+ appendField(key, formData[key]);
788
+ }
789
+ }
790
+ }
791
+ appendField("path", targetFilePath);
792
+ const filename = nodePath.basename(localFilePath);
793
+ req.write(`--${boundary}\r
794
+ `);
795
+ req.write(`Content-Disposition: form-data; name="file"; filename="${filename}"\r
796
+ `);
797
+ req.write("Content-Type: application/octet-stream\r\n");
798
+ req.write("\r\n");
799
+ const fileStream = fs.createReadStream(localFilePath);
800
+ fileStream.pipe(req, { end: false });
801
+ fileStream.on("end", () => {
802
+ req.write(`\r
803
+ --${boundary}--\r
804
+ `);
805
+ req.end();
806
+ });
807
+ fileStream.on("error", (e) => {
808
+ reject(new ClientError(0, `File stream error: ${e.message}`));
809
+ });
810
+ });
811
+ }
812
+ /**
813
+ * Download a file and save it to local path.
814
+ *
815
+ * @param path - API path
816
+ * @param savePath - Local file path to save the downloaded file
817
+ * @param query - Query parameters
818
+ * @param headers - Additional headers
819
+ * @param config - Optional config override
820
+ */
821
+ async getFile(path, savePath, query, headers, config2) {
822
+ const fullUrl = this.withPath(path, query);
823
+ const { url: reqUrl, headers: reqHeaders } = await this.prepareRequest(
824
+ "GET",
825
+ fullUrl,
826
+ void 0,
827
+ headers,
828
+ void 0,
829
+ config2
830
+ );
831
+ const client = reqUrl.startsWith("https") ? https : http;
832
+ const urlObj = new URL(reqUrl);
833
+ return new Promise((resolve, reject) => {
834
+ const options = {
835
+ hostname: urlObj.hostname,
836
+ port: urlObj.port || (reqUrl.startsWith("https") ? 443 : 80),
837
+ path: urlObj.pathname + urlObj.search,
838
+ method: "GET",
839
+ headers: reqHeaders,
840
+ timeout: this.config.timeout
841
+ };
842
+ const req = client.request(options, (res) => {
843
+ if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
844
+ const fileStream = fs.createWriteStream(savePath);
845
+ let downloadedSize = 0;
846
+ res.on("data", (chunk) => {
847
+ fileStream.write(chunk);
848
+ downloadedSize += chunk.length;
849
+ });
850
+ res.on("end", () => {
851
+ fileStream.end();
852
+ resolve({ savedPath: savePath, size: downloadedSize });
853
+ });
854
+ res.on("error", (e) => {
855
+ fileStream.end();
856
+ reject(new ClientError(0, `Response error: ${e.message}`));
857
+ });
858
+ } else {
859
+ let errorData = "";
860
+ res.on("data", (chunk) => errorData += chunk);
861
+ res.on("end", () => {
862
+ reject(new ClientError(res.statusCode || 0, errorData || "Download failed"));
863
+ });
864
+ }
865
+ });
866
+ req.on("error", (e) => {
867
+ reject(new ClientError(0, `Request error: ${e.message}`));
868
+ });
869
+ req.end();
870
+ });
871
+ }
872
+ /**
873
+ * Download a video file and save it to local path.
874
+ *
875
+ * @param path - API path
876
+ * @param savePath - Local file path to save the downloaded video
877
+ * @param query - Query parameters
878
+ * @param headers - Additional headers
879
+ * @param config - Optional config override
880
+ */
881
+ async getVideo(path, savePath, query, headers, config2) {
882
+ return this.getFile(path, savePath, query, headers, config2);
883
+ }
884
+ };
885
+
886
+ // src/utils/model.ts
887
+ var Status = {
888
+ CREATING: "CREATING",
889
+ CREATE_FAILED: "CREATE_FAILED",
890
+ READY: "READY",
891
+ UPDATING: "UPDATING",
892
+ UPDATE_FAILED: "UPDATE_FAILED",
893
+ DELETING: "DELETING",
894
+ DELETE_FAILED: "DELETE_FAILED"
895
+ };
896
+ var NetworkMode = {
897
+ PUBLIC: "PUBLIC",
898
+ PRIVATE: "PRIVATE",
899
+ PUBLIC_AND_PRIVATE: "PUBLIC_AND_PRIVATE"
900
+ };
901
+ function toSnakeCase(str) {
902
+ return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
903
+ }
904
+ function toCamelCase(str) {
905
+ return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
906
+ }
907
+ function toSnakeCaseKeys(obj) {
908
+ const result = {};
909
+ for (const [key, value] of Object.entries(obj)) {
910
+ const snakeKey = toSnakeCase(key);
911
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
912
+ result[snakeKey] = toSnakeCaseKeys(value);
913
+ } else if (Array.isArray(value)) {
914
+ result[snakeKey] = value.map(
915
+ (item) => typeof item === "object" && item !== null ? toSnakeCaseKeys(item) : item
916
+ );
917
+ } else {
918
+ result[snakeKey] = value;
919
+ }
920
+ }
921
+ return result;
922
+ }
923
+ function toCamelCaseKeys(obj) {
924
+ const result = {};
925
+ for (const [key, value] of Object.entries(obj)) {
926
+ const camelKey = toCamelCase(key);
927
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
928
+ result[camelKey] = toCamelCaseKeys(value);
929
+ } else if (Array.isArray(value)) {
930
+ result[camelKey] = value.map(
931
+ (item) => typeof item === "object" && item !== null ? toCamelCaseKeys(item) : item
932
+ );
933
+ } else {
934
+ result[camelKey] = value;
935
+ }
936
+ }
937
+ return result;
938
+ }
939
+ function removeUndefined(obj) {
940
+ const result = {};
941
+ for (const [key, value] of Object.entries(obj)) {
942
+ if (value !== void 0) {
943
+ result[key] = value;
944
+ }
945
+ }
946
+ return result;
947
+ }
948
+
949
+ export { AgentRunError, ClientError, Config, DataAPI, HTTPError, NetworkMode, ResourceAlreadyExistError, ResourceNotExistError, ResourceType, ServerError, Status, logger, removeUndefined, toCamelCase, toCamelCaseKeys, toSnakeCase, toSnakeCaseKeys };
950
+ //# sourceMappingURL=index.js.map
951
+ //# sourceMappingURL=index.js.map