@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,3532 @@
1
+ import * as dotenv from 'dotenv';
2
+ import * as $AgentRun4 from '@alicloud/agentrun20250910';
3
+ import * as $OpenApi from '@alicloud/openapi-client';
4
+ import * as $Util from '@alicloud/tea-util';
5
+ import * as fs2 from 'fs';
6
+ import * as path from 'path';
7
+
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
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
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/utils/log.ts
30
+ var LOG_LEVELS, COLORS, Logger, logger;
31
+ var init_log = __esm({
32
+ "src/utils/log.ts"() {
33
+ LOG_LEVELS = {
34
+ debug: 0,
35
+ info: 1,
36
+ warn: 2,
37
+ error: 3
38
+ };
39
+ COLORS = {
40
+ reset: "\x1B[0m",
41
+ bright: "\x1B[1m",
42
+ dim: "\x1B[2m",
43
+ italic: "\x1B[3m",
44
+ blue: "\x1B[34m",
45
+ cyan: "\x1B[36m",
46
+ yellow: "\x1B[33m",
47
+ red: "\x1B[31m"
48
+ };
49
+ Logger = class {
50
+ level = "info";
51
+ // match Python logger name
52
+ prefix = "agentrun-logger";
53
+ setLevel(level) {
54
+ this.level = level;
55
+ }
56
+ shouldLog(level) {
57
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.level];
58
+ }
59
+ getColor(level) {
60
+ switch (level) {
61
+ case "debug":
62
+ return COLORS.cyan;
63
+ case "info":
64
+ return COLORS.blue;
65
+ case "warn":
66
+ return COLORS.yellow;
67
+ case "error":
68
+ return COLORS.red;
69
+ default:
70
+ return COLORS.reset;
71
+ }
72
+ }
73
+ // format timestamp like Python: YYYY-MM-DD HH:mm:ss,SSS
74
+ formatTimestamp(d = /* @__PURE__ */ new Date()) {
75
+ const pad = (n, sz = 2) => n.toString().padStart(sz, "0");
76
+ const year = d.getFullYear();
77
+ const month = pad(d.getMonth() + 1);
78
+ const day = pad(d.getDate());
79
+ const hour = pad(d.getHours());
80
+ const minute = pad(d.getMinutes());
81
+ const second = pad(d.getSeconds());
82
+ const ms = pad(d.getMilliseconds(), 3);
83
+ return `${year}-${month}-${day} ${hour}:${minute}:${second},${ms}`;
84
+ }
85
+ // attempt to infer caller file and line by parsing Error.stack
86
+ // helper: parse a single stack frame into {filepath, line, functionName}
87
+ parseFrame(frame) {
88
+ const m = frame.match(/^(?:at\s+)?(?:(.+?)\s+\()?(.*?):(\d+):(\d+)\)?$/);
89
+ if (!m) return null;
90
+ return {
91
+ functionName: m[1] ? m[1].trim() : void 0,
92
+ filepath: m[2],
93
+ line: parseInt(m[3], 10)
94
+ };
95
+ }
96
+ // get caller by fixed stack offset (used in public log methods)
97
+ getCallerByOffset() {
98
+ const err = new Error();
99
+ const stack = err.stack;
100
+ if (!stack) return {};
101
+ const lines = stack.split("\n").map((l) => l.trim());
102
+ for (let i = 3; i < lines.length; i++) {
103
+ let parsed = this.parseFrame(lines[i]);
104
+ if (!parsed) {
105
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
106
+ if (m) {
107
+ const parts = m[1].split(":");
108
+ parts.pop();
109
+ const ln = Number(parts.pop());
110
+ const fp2 = parts.join(":");
111
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
112
+ }
113
+ }
114
+ if (!parsed) continue;
115
+ const fp = parsed.filepath;
116
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
117
+ continue;
118
+ return { filepath: parsed.filepath, line: parsed.line };
119
+ }
120
+ const cwd = process.cwd();
121
+ for (let i = 0; i < lines.length; i++) {
122
+ let parsed = this.parseFrame(lines[i]);
123
+ if (!parsed) {
124
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
125
+ if (m) {
126
+ const parts = m[1].split(":");
127
+ parts.pop();
128
+ const ln = Number(parts.pop());
129
+ const fp2 = parts.join(":");
130
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
131
+ }
132
+ }
133
+ if (!parsed) continue;
134
+ const fp = parsed.filepath;
135
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
136
+ continue;
137
+ if (fp.includes("/src/utils/log.ts")) continue;
138
+ if (fp.startsWith(cwd)) return { filepath: parsed.filepath, line: parsed.line };
139
+ }
140
+ for (let i = 0; i < lines.length; i++) {
141
+ let parsed = this.parseFrame(lines[i]);
142
+ if (!parsed) {
143
+ const m = lines[i].match(/(\/[^:\s]+:\d+:\d+)/);
144
+ if (m) {
145
+ const parts = m[1].split(":");
146
+ parts.pop();
147
+ const ln = Number(parts.pop());
148
+ const fp2 = parts.join(":");
149
+ parsed = { filepath: fp2, line: ln, functionName: void 0 };
150
+ }
151
+ }
152
+ if (!parsed) continue;
153
+ const fp = parsed.filepath;
154
+ if (fp.includes("node_modules") || fp.includes("internal") || fp.includes("<anonymous>") || fp.includes("native"))
155
+ continue;
156
+ if (fp.includes("/src/utils/log.ts")) continue;
157
+ return { filepath: parsed.filepath, line: parsed.line };
158
+ }
159
+ return {};
160
+ }
161
+ formatMessage(level, message, filepath, line) {
162
+ const timestamp = this.formatTimestamp();
163
+ const color = this.getColor(level);
164
+ const reset = COLORS.reset;
165
+ const levelName = level === "warn" ? "WARNING" : level.toUpperCase();
166
+ const levelStr = `${COLORS.bright}${color}${levelName}${reset}`;
167
+ const nameStr = `${color}[${this.prefix}]${reset}`;
168
+ const tsStr = `${color} ${timestamp}${reset}`;
169
+ const pathInfo = filepath && line !== void 0 ? ` ${COLORS.dim}${COLORS.italic}${filepath}:${line}${reset}` : "";
170
+ const msg = level === "debug" ? `${COLORS.dim}${message}${reset}` : message;
171
+ return `
172
+ ${levelStr} ${nameStr}${tsStr}${pathInfo}
173
+ ${msg}
174
+ `;
175
+ }
176
+ debug(message, ...args) {
177
+ if (this.shouldLog("debug")) {
178
+ const caller = this.getCallerByOffset();
179
+ console.debug(this.formatMessage("debug", message, caller.filepath, caller.line), ...args);
180
+ }
181
+ }
182
+ info(message, ...args) {
183
+ if (this.shouldLog("info")) {
184
+ const caller = this.getCallerByOffset();
185
+ console.info(this.formatMessage("info", message, caller.filepath, caller.line), ...args);
186
+ }
187
+ }
188
+ warn(message, ...args) {
189
+ if (this.shouldLog("warn")) {
190
+ const caller = this.getCallerByOffset();
191
+ console.warn(this.formatMessage("warn", message, caller.filepath, caller.line), ...args);
192
+ }
193
+ }
194
+ error(message, ...args) {
195
+ if (this.shouldLog("error")) {
196
+ const caller = this.getCallerByOffset();
197
+ console.error(this.formatMessage("error", message, caller.filepath, caller.line), ...args);
198
+ }
199
+ }
200
+ };
201
+ logger = new Logger();
202
+ if (![void 0, null, "", "False", "FALSE", "false", "0"].includes(process.env["AGENTRUN_SDK_DEBUG"])) {
203
+ logger.setLevel("debug");
204
+ if (!globalThis._AGENTRUN_DEBUG_LOGGED) {
205
+ logger.warn("\u542F\u7528 AgentRun SDK \u8C03\u8BD5\u65E5\u5FD7\uFF0C \u79FB\u9664 AGENTRUN_SDK_DEBUG \u73AF\u5883\u53D8\u91CF\u4EE5\u5173\u95ED");
206
+ globalThis._AGENTRUN_DEBUG_LOGGED = true;
207
+ }
208
+ } else {
209
+ logger.setLevel("info");
210
+ }
211
+ }
212
+ });
213
+
214
+ // src/utils/version-check.ts
215
+ var VERSION;
216
+ var init_version_check = __esm({
217
+ "src/utils/version-check.ts"() {
218
+ init_log();
219
+ VERSION = "0.0.4" ;
220
+ if (!process.env.DISABLE_BREAKING_CHANGES_WARNING && !globalThis._AGENTRUN_VERSION_WARNING_SHOWN) {
221
+ globalThis._AGENTRUN_VERSION_WARNING_SHOWN = true;
222
+ logger.warn(
223
+ `\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
224
+ 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.
225
+ \x1B[2;3m pip install 'agentrun-sdk==${VERSION}' \x1B[0m
226
+
227
+ \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
228
+ Add\x1B[2;3m DISABLE_BREAKING_CHANGES_WARNING=1 \x1B[0mto your environment variables to disable this warning.
229
+
230
+ Releases:\x1B[2;3m https://github.com/Serverless-Devs/agentrun-sdk-python/releases\x1B[0m`
231
+ );
232
+ }
233
+ }
234
+ });
235
+ function getEnvWithDefault(defaultValue, ...keys) {
236
+ for (const key of keys) {
237
+ const value = process.env[key];
238
+ if (value !== void 0 && value !== "") {
239
+ return value;
240
+ }
241
+ }
242
+ return defaultValue;
243
+ }
244
+ var Config;
245
+ var init_config = __esm({
246
+ "src/utils/config.ts"() {
247
+ dotenv.config();
248
+ Config = class _Config {
249
+ _accessKeyId;
250
+ _accessKeySecret;
251
+ _securityToken;
252
+ _accountId;
253
+ _token;
254
+ _regionId;
255
+ _timeout;
256
+ _readTimeout;
257
+ _controlEndpoint;
258
+ _dataEndpoint;
259
+ _devsEndpoint;
260
+ _headers;
261
+ constructor(options = {}) {
262
+ this._accessKeyId = options.accessKeyId ?? getEnvWithDefault("", "AGENTRUN_ACCESS_KEY_ID", "ALIBABA_CLOUD_ACCESS_KEY_ID");
263
+ this._accessKeySecret = options.accessKeySecret ?? getEnvWithDefault("", "AGENTRUN_ACCESS_KEY_SECRET", "ALIBABA_CLOUD_ACCESS_KEY_SECRET");
264
+ this._securityToken = options.securityToken ?? getEnvWithDefault("", "AGENTRUN_SECURITY_TOKEN", "ALIBABA_CLOUD_SECURITY_TOKEN");
265
+ this._accountId = options.accountId ?? getEnvWithDefault("", "AGENTRUN_ACCOUNT_ID", "FC_ACCOUNT_ID");
266
+ this._token = options.token;
267
+ this._regionId = options.regionId ?? getEnvWithDefault("cn-hangzhou", "AGENTRUN_REGION", "FC_REGION");
268
+ this._timeout = options.timeout ?? 6e5;
269
+ this._readTimeout = options.readTimeout ?? 1e8;
270
+ this._controlEndpoint = options.controlEndpoint ?? getEnvWithDefault("", "AGENTRUN_CONTROL_ENDPOINT");
271
+ this._dataEndpoint = options.dataEndpoint ?? getEnvWithDefault("", "AGENTRUN_DATA_ENDPOINT");
272
+ this._devsEndpoint = options.devsEndpoint ?? getEnvWithDefault("", "DEVS_ENDPOINT");
273
+ this._headers = options.headers ?? {};
274
+ }
275
+ /**
276
+ * Create a new Config by merging multiple configs.
277
+ * Later configs take precedence.
278
+ */
279
+ static withConfigs(...configs) {
280
+ return new _Config().update(...configs);
281
+ }
282
+ /**
283
+ * Update this config with values from other configs.
284
+ * Non-undefined values from later configs take precedence.
285
+ */
286
+ update(...configs) {
287
+ for (const config2 of configs) {
288
+ if (!config2) continue;
289
+ if (config2._accessKeyId) this._accessKeyId = config2._accessKeyId;
290
+ if (config2._accessKeySecret) this._accessKeySecret = config2._accessKeySecret;
291
+ if (config2._securityToken) this._securityToken = config2._securityToken;
292
+ if (config2._accountId) this._accountId = config2._accountId;
293
+ if (config2._token) this._token = config2._token;
294
+ if (config2._regionId) this._regionId = config2._regionId;
295
+ if (config2._timeout) this._timeout = config2._timeout;
296
+ if (config2._readTimeout) this._readTimeout = config2._readTimeout;
297
+ if (config2._controlEndpoint) this._controlEndpoint = config2._controlEndpoint;
298
+ if (config2._dataEndpoint) this._dataEndpoint = config2._dataEndpoint;
299
+ if (config2._devsEndpoint) this._devsEndpoint = config2._devsEndpoint;
300
+ if (config2._headers && Object.keys(config2._headers).length > 0) {
301
+ this._headers = { ...this._headers, ...config2._headers };
302
+ }
303
+ }
304
+ return this;
305
+ }
306
+ get accessKeyId() {
307
+ return this._accessKeyId;
308
+ }
309
+ get accessKeySecret() {
310
+ return this._accessKeySecret;
311
+ }
312
+ get securityToken() {
313
+ return this._securityToken;
314
+ }
315
+ get accountId() {
316
+ if (!this._accountId) {
317
+ throw new Error(
318
+ "Account ID is not set. Please add AGENTRUN_ACCOUNT_ID environment variable or set it in code."
319
+ );
320
+ }
321
+ return this._accountId;
322
+ }
323
+ get token() {
324
+ return this._token;
325
+ }
326
+ get regionId() {
327
+ return this._regionId || "cn-hangzhou";
328
+ }
329
+ get timeout() {
330
+ return this._timeout || 6e5;
331
+ }
332
+ get readTimeout() {
333
+ return this._readTimeout || 1e8;
334
+ }
335
+ get controlEndpoint() {
336
+ if (this._controlEndpoint) {
337
+ return this._controlEndpoint;
338
+ }
339
+ return `https://agentrun.${this.regionId}.aliyuncs.com`;
340
+ }
341
+ get dataEndpoint() {
342
+ if (this._dataEndpoint) {
343
+ return this._dataEndpoint;
344
+ }
345
+ return `https://${this.accountId}.agentrun-data.${this.regionId}.aliyuncs.com`;
346
+ }
347
+ get devsEndpoint() {
348
+ if (this._devsEndpoint) {
349
+ return this._devsEndpoint;
350
+ }
351
+ return `https://devs.${this.regionId}.aliyuncs.com`;
352
+ }
353
+ get headers() {
354
+ return this._headers;
355
+ }
356
+ };
357
+ }
358
+ });
359
+
360
+ // src/utils/exception.ts
361
+ var AgentRunError, HTTPError, ClientError, ServerError, ResourceNotExistError, ResourceAlreadyExistError;
362
+ var init_exception = __esm({
363
+ "src/utils/exception.ts"() {
364
+ AgentRunError = class _AgentRunError extends Error {
365
+ constructor(message) {
366
+ super(message);
367
+ this.name = "AgentRunError";
368
+ Object.setPrototypeOf(this, _AgentRunError.prototype);
369
+ }
370
+ };
371
+ HTTPError = class _HTTPError extends AgentRunError {
372
+ statusCode;
373
+ requestId;
374
+ errorCode;
375
+ constructor(statusCode, message, options) {
376
+ super(message);
377
+ this.name = "HTTPError";
378
+ this.statusCode = statusCode;
379
+ this.requestId = options?.requestId;
380
+ this.errorCode = options?.errorCode;
381
+ Object.setPrototypeOf(this, _HTTPError.prototype);
382
+ }
383
+ /**
384
+ * Convert HTTP error to resource-specific error based on status code
385
+ */
386
+ toResourceError(resourceType, resourceId) {
387
+ if (this.statusCode == 404) return new ResourceNotExistError(resourceType, resourceId);
388
+ else if (this.statusCode == 409) return new ResourceAlreadyExistError(resourceType, resourceId);
389
+ else if ((this.statusCode == 400 || this.statusCode == 500) && this.message.includes("already exists"))
390
+ return new ResourceAlreadyExistError(resourceType, resourceId);
391
+ else return this;
392
+ }
393
+ };
394
+ ClientError = class _ClientError extends HTTPError {
395
+ constructor(statusCode, message, options) {
396
+ super(statusCode, message, options);
397
+ this.name = "ClientError";
398
+ Object.setPrototypeOf(this, _ClientError.prototype);
399
+ }
400
+ };
401
+ ServerError = class _ServerError extends HTTPError {
402
+ constructor(statusCode, message, options) {
403
+ super(statusCode, message, options);
404
+ this.name = "ServerError";
405
+ Object.setPrototypeOf(this, _ServerError.prototype);
406
+ }
407
+ };
408
+ ResourceNotExistError = class _ResourceNotExistError extends ClientError {
409
+ resourceType;
410
+ resourceId;
411
+ constructor(resourceType, resourceId, options) {
412
+ const message = resourceId ? `${resourceType} '${resourceId}' does not exist` : `${resourceType} does not exist`;
413
+ super(404, message, options);
414
+ this.name = "ResourceNotExistError";
415
+ this.resourceType = resourceType;
416
+ this.resourceId = resourceId;
417
+ Object.setPrototypeOf(this, _ResourceNotExistError.prototype);
418
+ }
419
+ };
420
+ ResourceAlreadyExistError = class _ResourceAlreadyExistError extends ClientError {
421
+ resourceType;
422
+ resourceId;
423
+ constructor(resourceType, resourceId, options) {
424
+ const message = resourceId ? `${resourceType} '${resourceId}' already exists` : `${resourceType} already exists`;
425
+ super(409, message, options);
426
+ this.name = "ResourceAlreadyExistError";
427
+ this.resourceType = resourceType;
428
+ this.resourceId = resourceId;
429
+ Object.setPrototypeOf(this, _ResourceAlreadyExistError.prototype);
430
+ }
431
+ };
432
+ }
433
+ });
434
+ var $AgentRunClient, ControlAPI;
435
+ var init_control_api = __esm({
436
+ "src/utils/control-api.ts"() {
437
+ init_config();
438
+ $AgentRunClient = // @ts-expect-error - ESM interop: default.default exists when imported as ESM namespace
439
+ $AgentRun4.default?.default ?? $AgentRun4.default ?? $AgentRun4;
440
+ ControlAPI = class {
441
+ config;
442
+ constructor(config2) {
443
+ this.config = config2;
444
+ }
445
+ /**
446
+ * Get the underlying AgentRun client instance
447
+ */
448
+ getClient(config2) {
449
+ const cfg = Config.withConfigs(this.config, config2);
450
+ let endpoint = cfg.controlEndpoint;
451
+ if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
452
+ endpoint = endpoint.split("://")[1];
453
+ }
454
+ const openApiConfig = new $OpenApi.Config({
455
+ accessKeyId: cfg.accessKeyId,
456
+ accessKeySecret: cfg.accessKeySecret,
457
+ securityToken: cfg.securityToken || void 0,
458
+ regionId: cfg.regionId,
459
+ endpoint,
460
+ connectTimeout: cfg.timeout,
461
+ readTimeout: cfg.readTimeout
462
+ });
463
+ return new $AgentRunClient(openApiConfig);
464
+ }
465
+ };
466
+ }
467
+ });
468
+ var SandboxControlAPI;
469
+ var init_control = __esm({
470
+ "src/sandbox/api/control.ts"() {
471
+ init_control_api();
472
+ init_exception();
473
+ init_log();
474
+ SandboxControlAPI = class extends ControlAPI {
475
+ constructor(config2) {
476
+ super(config2);
477
+ }
478
+ /**
479
+ * Create Sandbox Template
480
+ *
481
+ * @param params - Method parameters
482
+ * @param params.input - Template configuration
483
+ * @param params.headers - Custom request headers
484
+ * @param params.config - Optional config override
485
+ * @returns Created Template object
486
+ */
487
+ createTemplate = async (params) => {
488
+ const { input, headers, config: config2 } = params;
489
+ try {
490
+ const client = this.getClient(config2);
491
+ const runtime = new $Util.RuntimeOptions({});
492
+ const response = await client.createTemplateWithOptions(
493
+ new $AgentRun4.CreateTemplateRequest({ body: input }),
494
+ headers ?? {},
495
+ runtime
496
+ );
497
+ logger.debug(
498
+ `request api createTemplate, request Request ID: ${response.body?.requestId}
499
+ request: ${JSON.stringify([input])}
500
+ response: ${JSON.stringify(response.body?.data)}`
501
+ );
502
+ return response.body?.data;
503
+ } catch (error) {
504
+ if (error && typeof error === "object" && "statusCode" in error) {
505
+ const e = error;
506
+ const statusCode = e.statusCode;
507
+ const message = e.message || "Unknown error";
508
+ const requestId = e.data?.requestId;
509
+ if (statusCode >= 400 && statusCode < 500) {
510
+ throw new ClientError(statusCode, message, { requestId });
511
+ } else if (statusCode >= 500) {
512
+ throw new ServerError(statusCode, message, { requestId });
513
+ }
514
+ }
515
+ throw error;
516
+ }
517
+ };
518
+ /**
519
+ * Delete Sandbox Template
520
+ *
521
+ * @param params - Method parameters
522
+ * @param params.templateName - Template name
523
+ * @param params.headers - Custom request headers
524
+ * @param params.config - Optional config override
525
+ * @returns Deleted Template object
526
+ */
527
+ deleteTemplate = async (params) => {
528
+ const { templateName, headers, config: config2 } = params;
529
+ try {
530
+ const client = this.getClient(config2);
531
+ const runtime = new $Util.RuntimeOptions({});
532
+ const response = await client.deleteTemplateWithOptions(templateName, headers ?? {}, runtime);
533
+ logger.debug(
534
+ `request api deleteTemplate, request Request ID: ${response.body?.requestId}
535
+ request: ${JSON.stringify([templateName])}
536
+ response: ${JSON.stringify(response.body?.data)}`
537
+ );
538
+ return response.body?.data;
539
+ } catch (error) {
540
+ if (error && typeof error === "object" && "statusCode" in error) {
541
+ const e = error;
542
+ const statusCode = e.statusCode;
543
+ const message = e.message || "Unknown error";
544
+ const requestId = e.data?.requestId;
545
+ if (statusCode >= 400 && statusCode < 500) {
546
+ throw new ClientError(statusCode, message, { requestId });
547
+ } else if (statusCode >= 500) {
548
+ throw new ServerError(statusCode, message, { requestId });
549
+ }
550
+ }
551
+ throw error;
552
+ }
553
+ };
554
+ /**
555
+ * Update Sandbox Template
556
+ *
557
+ * @param params - Method parameters
558
+ * @param params.templateName - Template name
559
+ * @param params.input - Template configuration
560
+ * @param params.headers - Custom request headers
561
+ * @param params.config - Optional config override
562
+ * @returns Updated Template object
563
+ */
564
+ updateTemplate = async (params) => {
565
+ const { templateName, input, headers, config: config2 } = params;
566
+ try {
567
+ const client = this.getClient(config2);
568
+ const runtime = new $Util.RuntimeOptions({});
569
+ const response = await client.updateTemplateWithOptions(
570
+ templateName,
571
+ new $AgentRun4.UpdateTemplateRequest({ body: input }),
572
+ headers ?? {},
573
+ runtime
574
+ );
575
+ logger.debug(
576
+ `request api updateTemplate, request Request ID: ${response.body?.requestId}
577
+ request: ${JSON.stringify([templateName, input])}
578
+ response: ${JSON.stringify(response.body?.data)}`
579
+ );
580
+ return response.body?.data;
581
+ } catch (error) {
582
+ if (error && typeof error === "object" && "statusCode" in error) {
583
+ const e = error;
584
+ const statusCode = e.statusCode;
585
+ const message = e.message || "Unknown error";
586
+ const requestId = e.data?.requestId;
587
+ if (statusCode >= 400 && statusCode < 500) {
588
+ throw new ClientError(statusCode, message, { requestId });
589
+ } else if (statusCode >= 500) {
590
+ throw new ServerError(statusCode, message, { requestId });
591
+ }
592
+ }
593
+ throw error;
594
+ }
595
+ };
596
+ /**
597
+ * Get Sandbox Template
598
+ *
599
+ * @param params - Method parameters
600
+ * @param params.templateName - Template name
601
+ * @param params.headers - Custom request headers
602
+ * @param params.config - Optional config override
603
+ * @returns Template object
604
+ */
605
+ getTemplate = async (params) => {
606
+ const { templateName, headers, config: config2 } = params;
607
+ try {
608
+ const client = this.getClient(config2);
609
+ const runtime = new $Util.RuntimeOptions({});
610
+ const response = await client.getTemplateWithOptions(templateName, headers ?? {}, runtime);
611
+ logger.debug(
612
+ `request api getTemplate, request Request ID: ${response.body?.requestId}
613
+ request: ${JSON.stringify([templateName])}
614
+ response: ${JSON.stringify(response.body?.data)}`
615
+ );
616
+ return response.body?.data;
617
+ } catch (error) {
618
+ if (error && typeof error === "object" && "statusCode" in error) {
619
+ const e = error;
620
+ const statusCode = e.statusCode;
621
+ const message = e.message || "Unknown error";
622
+ const requestId = e.data?.requestId;
623
+ if (statusCode >= 400 && statusCode < 500) {
624
+ throw new ClientError(statusCode, message, { requestId });
625
+ } else if (statusCode >= 500) {
626
+ throw new ServerError(statusCode, message, { requestId });
627
+ }
628
+ }
629
+ throw error;
630
+ }
631
+ };
632
+ /**
633
+ * List Sandbox Templates
634
+ *
635
+ * @param params - Method parameters
636
+ * @param params.input - List options
637
+ * @param params.headers - Custom request headers
638
+ * @param params.config - Optional config override
639
+ * @returns List of Template objects
640
+ */
641
+ listTemplates = async (params) => {
642
+ const { input, headers, config: config2 } = params;
643
+ try {
644
+ const client = this.getClient(config2);
645
+ const runtime = new $Util.RuntimeOptions({});
646
+ const response = await client.listTemplatesWithOptions(input, headers ?? {}, runtime);
647
+ logger.debug(
648
+ `request api listTemplates, request Request ID: ${response.body?.requestId}
649
+ request: ${JSON.stringify([input])}
650
+ response: ${JSON.stringify(response.body?.data)}`
651
+ );
652
+ return response.body?.data;
653
+ } catch (error) {
654
+ if (error && typeof error === "object" && "statusCode" in error) {
655
+ const e = error;
656
+ const statusCode = e.statusCode;
657
+ const message = e.message || "Unknown error";
658
+ const requestId = e.data?.requestId;
659
+ if (statusCode >= 400 && statusCode < 500) {
660
+ throw new ClientError(statusCode, message, { requestId });
661
+ } else if (statusCode >= 500) {
662
+ throw new ServerError(statusCode, message, { requestId });
663
+ }
664
+ }
665
+ throw error;
666
+ }
667
+ };
668
+ /**
669
+ * Create Sandbox
670
+ *
671
+ * @param params - Method parameters
672
+ * @param params.input - Sandbox configuration
673
+ * @param params.headers - Custom request headers
674
+ * @param params.config - Optional config override
675
+ * @returns Created Sandbox object
676
+ */
677
+ createSandbox = async (params) => {
678
+ const { input, headers, config: config2 } = params;
679
+ try {
680
+ const client = this.getClient(config2);
681
+ const runtime = new $Util.RuntimeOptions({
682
+ readTimeout: 3e4
683
+ });
684
+ const response = await client.createSandboxWithOptions(
685
+ new $AgentRun4.CreateSandboxRequest({ body: input }),
686
+ headers ?? {},
687
+ runtime
688
+ );
689
+ logger.debug(
690
+ `request api createSandbox, request Request ID: ${response.body?.requestId}
691
+ request: ${JSON.stringify([input])}
692
+ response: ${JSON.stringify(response.body?.data)}`
693
+ );
694
+ return response.body?.data;
695
+ } catch (error) {
696
+ if (error && typeof error === "object" && "statusCode" in error) {
697
+ const e = error;
698
+ const statusCode = e.statusCode;
699
+ const message = e.message || "Unknown error";
700
+ const requestId = e.data?.requestId;
701
+ if (statusCode >= 400 && statusCode < 500) {
702
+ throw new ClientError(statusCode, message, { requestId });
703
+ } else if (statusCode >= 500) {
704
+ throw new ServerError(statusCode, message, { requestId });
705
+ }
706
+ }
707
+ throw error;
708
+ }
709
+ };
710
+ /**
711
+ * Delete Sandbox
712
+ *
713
+ * @param params - Method parameters
714
+ * @param params.sandboxId - Sandbox ID
715
+ * @param params.headers - Custom request headers
716
+ * @param params.config - Optional config override
717
+ * @returns Deleted Sandbox object
718
+ */
719
+ deleteSandbox = async (params) => {
720
+ const { sandboxId, headers, config: config2 } = params;
721
+ try {
722
+ const client = this.getClient(config2);
723
+ const runtime = new $Util.RuntimeOptions({});
724
+ const response = await client.deleteSandboxWithOptions(sandboxId, headers ?? {}, runtime);
725
+ logger.debug(
726
+ `request api deleteSandbox, request Request ID: ${response.body?.requestId}
727
+ request: ${JSON.stringify([sandboxId])}
728
+ response: ${JSON.stringify(response.body?.data)}`
729
+ );
730
+ return response.body?.data;
731
+ } catch (error) {
732
+ if (error && typeof error === "object" && "statusCode" in error) {
733
+ const e = error;
734
+ const statusCode = e.statusCode;
735
+ const message = e.message || "Unknown error";
736
+ const requestId = e.data?.requestId;
737
+ if (statusCode >= 400 && statusCode < 500) {
738
+ throw new ClientError(statusCode, message, { requestId });
739
+ } else if (statusCode >= 500) {
740
+ throw new ServerError(statusCode, message, { requestId });
741
+ }
742
+ }
743
+ throw error;
744
+ }
745
+ };
746
+ /**
747
+ * Stop Sandbox
748
+ *
749
+ * @param params - Method parameters
750
+ * @param params.sandboxId - Sandbox ID
751
+ * @param params.headers - Custom request headers
752
+ * @param params.config - Optional config override
753
+ * @returns Stopped Sandbox object
754
+ */
755
+ stopSandbox = async (params) => {
756
+ const { sandboxId, headers, config: config2 } = params;
757
+ try {
758
+ const client = this.getClient(config2);
759
+ const runtime = new $Util.RuntimeOptions({});
760
+ const response = await client.stopSandboxWithOptions(sandboxId, headers ?? {}, runtime);
761
+ logger.debug(
762
+ `request api stopSandbox, request Request ID: ${response.body?.requestId}
763
+ request: ${JSON.stringify([sandboxId])}
764
+ response: ${JSON.stringify(response.body?.data)}`
765
+ );
766
+ return response.body?.data;
767
+ } catch (error) {
768
+ if (error && typeof error === "object" && "statusCode" in error) {
769
+ const e = error;
770
+ const statusCode = e.statusCode;
771
+ const message = e.message || "Unknown error";
772
+ const requestId = e.data?.requestId;
773
+ if (statusCode >= 400 && statusCode < 500) {
774
+ throw new ClientError(statusCode, message, { requestId });
775
+ } else if (statusCode >= 500) {
776
+ throw new ServerError(statusCode, message, { requestId });
777
+ }
778
+ }
779
+ throw error;
780
+ }
781
+ };
782
+ /**
783
+ * Get Sandbox
784
+ *
785
+ * @param params - Method parameters
786
+ * @param params.sandboxId - Sandbox ID
787
+ * @param params.headers - Custom request headers
788
+ * @param params.config - Optional config override
789
+ * @returns Sandbox object
790
+ */
791
+ getSandbox = async (params) => {
792
+ const { sandboxId, headers, config: config2 } = params;
793
+ try {
794
+ const client = this.getClient(config2);
795
+ const runtime = new $Util.RuntimeOptions({});
796
+ const response = await client.getSandboxWithOptions(sandboxId, headers ?? {}, runtime);
797
+ logger.debug(
798
+ `request api getSandbox, request Request ID: ${response.body?.requestId}
799
+ request: ${JSON.stringify([sandboxId])}
800
+ response: ${JSON.stringify(response.body?.data)}`
801
+ );
802
+ return response.body?.data;
803
+ } catch (error) {
804
+ if (error && typeof error === "object" && "statusCode" in error) {
805
+ const e = error;
806
+ const statusCode = e.statusCode;
807
+ const message = e.message || "Unknown error";
808
+ const requestId = e.data?.requestId;
809
+ if (statusCode >= 400 && statusCode < 500) {
810
+ throw new ClientError(statusCode, message, { requestId });
811
+ } else if (statusCode >= 500) {
812
+ throw new ServerError(statusCode, message, { requestId });
813
+ }
814
+ }
815
+ throw error;
816
+ }
817
+ };
818
+ /**
819
+ * List Sandboxes
820
+ *
821
+ * @param params - Method parameters
822
+ * @param params.input - List options
823
+ * @param params.headers - Custom request headers
824
+ * @param params.config - Optional config override
825
+ * @returns List of Sandbox objects
826
+ */
827
+ listSandboxes = async (params) => {
828
+ const { input, headers, config: config2 } = params;
829
+ try {
830
+ const client = this.getClient(config2);
831
+ const runtime = new $Util.RuntimeOptions({});
832
+ const response = await client.listSandboxesWithOptions(input, headers ?? {}, runtime);
833
+ logger.debug(
834
+ `request api listSandboxes, request Request ID: ${response.body?.requestId}
835
+ request: ${JSON.stringify([input])}
836
+ response: ${JSON.stringify(response.body?.data)}`
837
+ );
838
+ return response.body?.data;
839
+ } catch (error) {
840
+ if (error && typeof error === "object" && "statusCode" in error) {
841
+ const e = error;
842
+ const statusCode = e.statusCode;
843
+ const message = e.message || "Unknown error";
844
+ const requestId = e.data?.requestId;
845
+ if (statusCode >= 400 && statusCode < 500) {
846
+ throw new ClientError(statusCode, message, { requestId });
847
+ } else if (statusCode >= 500) {
848
+ throw new ServerError(statusCode, message, { requestId });
849
+ }
850
+ }
851
+ throw error;
852
+ }
853
+ };
854
+ };
855
+ }
856
+ });
857
+ var SandboxDataAPI;
858
+ var init_sandbox_data = __esm({
859
+ "src/sandbox/api/sandbox-data.ts"() {
860
+ init_config();
861
+ init_control_api();
862
+ init_exception();
863
+ init_log();
864
+ SandboxDataAPI = class {
865
+ resourceName;
866
+ resourceType;
867
+ namespace;
868
+ config;
869
+ accessToken;
870
+ accessTokenMap = /* @__PURE__ */ new Map();
871
+ constructor(params) {
872
+ const { config: config2, namespace = "sandboxes" } = params;
873
+ this.resourceName = "";
874
+ this.resourceType = "template" /* Template */;
875
+ this.namespace = namespace;
876
+ this.config = config2 || new Config();
877
+ }
878
+ /**
879
+ * Refresh access token for the resource
880
+ */
881
+ async refreshAccessToken(params) {
882
+ const { sandboxId, templateName, config: config2 } = params;
883
+ const cfg = Config.withConfigs(config2, this.config);
884
+ const cacheKey = sandboxId || templateName;
885
+ const cachedToken = this.accessTokenMap.get(cacheKey);
886
+ if (sandboxId) {
887
+ this.resourceName = sandboxId;
888
+ this.resourceType = "sandbox" /* Sandbox */;
889
+ this.namespace = `sandboxes/${sandboxId}`;
890
+ } else if (templateName) {
891
+ this.resourceName = templateName;
892
+ this.resourceType = "template" /* Template */;
893
+ this.namespace = "sandboxes";
894
+ }
895
+ if (cachedToken) {
896
+ this.accessToken = cachedToken;
897
+ return;
898
+ }
899
+ this.accessToken = void 0;
900
+ await this.auth({ config: cfg });
901
+ if (this.accessToken) {
902
+ this.accessTokenMap.set(cacheKey, this.accessToken);
903
+ }
904
+ }
905
+ /**
906
+ * Get base URL for data API
907
+ */
908
+ getBaseUrl() {
909
+ return this.config.dataEndpoint;
910
+ }
911
+ /**
912
+ * Construct full URL with path and query parameters
913
+ */
914
+ withPath(path2, query) {
915
+ path2 = path2.replace(/^\//, "");
916
+ const parts = [this.getBaseUrl(), this.namespace, path2].filter((p) => p && p.length > 0);
917
+ let url = parts.join("/").replace(/\/+/g, "/").replace(/:\//g, "://");
918
+ if (query && Object.keys(query).length > 0) {
919
+ const urlObj = new URL(url);
920
+ Object.entries(query).forEach(([key, value]) => {
921
+ if (Array.isArray(value)) {
922
+ value.forEach((v) => urlObj.searchParams.append(key, String(v)));
923
+ } else if (value !== void 0 && value !== null) {
924
+ urlObj.searchParams.append(key, String(value));
925
+ }
926
+ });
927
+ url = urlObj.toString();
928
+ }
929
+ return url;
930
+ }
931
+ /**
932
+ * Authentication hook - gets access token for the resource
933
+ */
934
+ async auth(params) {
935
+ const cfg = Config.withConfigs(this.config, params.config);
936
+ if (cfg.token) {
937
+ logger.debug(`Using provided access token from config: ${this.maskToken(cfg.token)}`);
938
+ this.accessToken = cfg.token;
939
+ return;
940
+ }
941
+ if (!this.accessToken && this.resourceName && this.resourceType && !cfg.token) {
942
+ try {
943
+ const controlApi = new ControlAPI(cfg);
944
+ const client = controlApi.getClient(cfg);
945
+ const request = this.resourceType === "sandbox" /* Sandbox */ ? new $AgentRun4.GetAccessTokenRequest({
946
+ resourceId: this.resourceName,
947
+ resourceType: this.resourceType
948
+ }) : new $AgentRun4.GetAccessTokenRequest({
949
+ resourceName: this.resourceName,
950
+ resourceType: this.resourceType
951
+ });
952
+ const runtime = new $Util.RuntimeOptions({});
953
+ const response = await client.getAccessTokenWithOptions(request, {}, runtime);
954
+ this.accessToken = response.body?.data?.accessToken;
955
+ logger.debug(
956
+ `Fetched access token for resource ${this.resourceName} of type ${this.resourceType}: ${this.maskToken(this.accessToken || "")}`
957
+ );
958
+ } catch (error) {
959
+ logger.warn(
960
+ `Failed to get access token for ${this.resourceType}(${this.resourceName}): ${error}`
961
+ );
962
+ }
963
+ }
964
+ }
965
+ /**
966
+ * Mask token for logging
967
+ */
968
+ maskToken(token) {
969
+ if (!token || token.length <= 8) {
970
+ return "***";
971
+ }
972
+ return `${token.substring(0, 4)}...${token.substring(token.length - 4)}`;
973
+ }
974
+ /**
975
+ * Prepare request headers
976
+ */
977
+ prepareHeaders(params) {
978
+ const cfg = Config.withConfigs(this.config, params.config);
979
+ const reqHeaders = {
980
+ "Content-Type": "application/json",
981
+ "User-Agent": "AgentRunDataClient-Node/1.0",
982
+ "Agentrun-Access-Token": cfg.token || this.accessToken || "",
983
+ ...cfg.headers,
984
+ ...params.headers || {}
985
+ };
986
+ return reqHeaders;
987
+ }
988
+ /**
989
+ * Make an HTTP request
990
+ */
991
+ async makeRequest(params) {
992
+ const { method, url, data, headers, query, config: config2 } = params;
993
+ const reqHeaders = this.prepareHeaders({ headers, config: config2 });
994
+ let finalUrl = url;
995
+ if (query && Object.keys(query).length > 0) {
996
+ const urlObj = new URL(url);
997
+ Object.entries(query).forEach(([key, value]) => {
998
+ if (value !== void 0 && value !== null) {
999
+ if (Array.isArray(value)) {
1000
+ value.forEach((v) => urlObj.searchParams.append(key, String(v)));
1001
+ } else {
1002
+ urlObj.searchParams.append(key, String(value));
1003
+ }
1004
+ }
1005
+ });
1006
+ finalUrl = urlObj.toString();
1007
+ }
1008
+ logger.debug(
1009
+ `${method} ${finalUrl} headers=${JSON.stringify(reqHeaders)} data=${JSON.stringify(data)}`
1010
+ );
1011
+ try {
1012
+ const cfg = Config.withConfigs(this.config, config2);
1013
+ const response = await fetch(finalUrl, {
1014
+ method,
1015
+ headers: reqHeaders,
1016
+ body: data ? JSON.stringify(data) : void 0,
1017
+ signal: AbortSignal.timeout(cfg.timeout)
1018
+ });
1019
+ const responseText = await response.text();
1020
+ logger.debug(`Response: ${responseText}`);
1021
+ if (responseText) {
1022
+ try {
1023
+ return JSON.parse(responseText);
1024
+ } catch (error) {
1025
+ const errorMsg = `Failed to parse JSON response: ${error}`;
1026
+ logger.error(errorMsg);
1027
+ if (response.status === 502 && responseText.includes("502 Bad Gateway")) {
1028
+ throw new ClientError(response.status, "502 Bad Gateway");
1029
+ }
1030
+ throw new ClientError(response.status, errorMsg);
1031
+ }
1032
+ }
1033
+ return {};
1034
+ } catch (error) {
1035
+ if (error instanceof ClientError) {
1036
+ throw error;
1037
+ }
1038
+ const errorMsg = `Request error: ${error}`;
1039
+ throw new ClientError(0, errorMsg);
1040
+ }
1041
+ }
1042
+ /**
1043
+ * GET request
1044
+ */
1045
+ async get(params) {
1046
+ const url = this.withPath(params.path, params.query);
1047
+ return this.makeRequest({
1048
+ method: "GET",
1049
+ url,
1050
+ headers: params.headers,
1051
+ config: params.config
1052
+ });
1053
+ }
1054
+ /**
1055
+ * POST request
1056
+ */
1057
+ async post(params) {
1058
+ const url = this.withPath(params.path, params.query);
1059
+ return this.makeRequest({
1060
+ method: "POST",
1061
+ url,
1062
+ data: params.data,
1063
+ headers: params.headers,
1064
+ config: params.config
1065
+ });
1066
+ }
1067
+ /**
1068
+ * PUT request
1069
+ */
1070
+ async put(params) {
1071
+ const url = this.withPath(params.path, params.query);
1072
+ return this.makeRequest({
1073
+ method: "PUT",
1074
+ url,
1075
+ data: params.data,
1076
+ headers: params.headers,
1077
+ config: params.config
1078
+ });
1079
+ }
1080
+ /**
1081
+ * PATCH request
1082
+ */
1083
+ async patch(params) {
1084
+ const url = this.withPath(params.path, params.query);
1085
+ return this.makeRequest({
1086
+ method: "PATCH",
1087
+ url,
1088
+ data: params.data,
1089
+ headers: params.headers,
1090
+ config: params.config
1091
+ });
1092
+ }
1093
+ /**
1094
+ * DELETE request
1095
+ */
1096
+ async delete(params) {
1097
+ const url = this.withPath(params.path, params.query);
1098
+ return this.makeRequest({
1099
+ method: "DELETE",
1100
+ url,
1101
+ headers: params.headers,
1102
+ config: params.config
1103
+ });
1104
+ }
1105
+ /**
1106
+ * Check sandbox health
1107
+ */
1108
+ checkHealth = async (params) => {
1109
+ await this.refreshAccessToken({
1110
+ sandboxId: params.sandboxId,
1111
+ config: params.config
1112
+ });
1113
+ return this.get({ path: "/health", config: params.config });
1114
+ };
1115
+ /**
1116
+ * Create sandbox from template
1117
+ * 从模板创建沙箱 / Create Sandbox from Template
1118
+ */
1119
+ createSandbox = async (params) => {
1120
+ await this.refreshAccessToken({
1121
+ templateName: params.templateName,
1122
+ config: params.config
1123
+ });
1124
+ const data = {
1125
+ templateName: params.templateName,
1126
+ sandboxIdleTimeoutSeconds: params.sandboxIdleTimeoutSeconds || 600
1127
+ };
1128
+ if (params.nasConfig !== void 0) {
1129
+ data.nasConfig = params.nasConfig;
1130
+ }
1131
+ if (params.ossMountConfig !== void 0) {
1132
+ data.ossMountConfig = params.ossMountConfig;
1133
+ }
1134
+ if (params.polarFsConfig !== void 0) {
1135
+ data.polarFsConfig = params.polarFsConfig;
1136
+ }
1137
+ return this.post({
1138
+ path: "/",
1139
+ data
1140
+ });
1141
+ };
1142
+ /**
1143
+ * Delete sandbox
1144
+ */
1145
+ deleteSandbox = async (params) => {
1146
+ await this.refreshAccessToken({
1147
+ sandboxId: params.sandboxId,
1148
+ config: params.config
1149
+ });
1150
+ return this.delete({ path: "/" });
1151
+ };
1152
+ /**
1153
+ * Stop sandbox
1154
+ */
1155
+ stopSandbox = async (params) => {
1156
+ await this.refreshAccessToken({
1157
+ sandboxId: params.sandboxId,
1158
+ config: params.config
1159
+ });
1160
+ return this.post({ path: "/stop" });
1161
+ };
1162
+ /**
1163
+ * Get sandbox info
1164
+ */
1165
+ getSandbox = async (params) => {
1166
+ await this.refreshAccessToken({
1167
+ sandboxId: params.sandboxId,
1168
+ config: params.config
1169
+ });
1170
+ return this.get({ path: "/" });
1171
+ };
1172
+ };
1173
+ }
1174
+ });
1175
+ var BrowserDataAPI;
1176
+ var init_browser_data = __esm({
1177
+ "src/sandbox/api/browser-data.ts"() {
1178
+ init_config();
1179
+ init_exception();
1180
+ init_log();
1181
+ init_sandbox_data();
1182
+ BrowserDataAPI = class extends SandboxDataAPI {
1183
+ sandboxId;
1184
+ constructor(params) {
1185
+ super({
1186
+ sandboxId: params.sandboxId,
1187
+ config: params.config,
1188
+ // Set namespace to include sandboxId for CDP/VNC URL generation
1189
+ namespace: `sandboxes/${params.sandboxId}`
1190
+ });
1191
+ this.sandboxId = params.sandboxId;
1192
+ }
1193
+ /**
1194
+ * Generate the WebSocket URL for Chrome DevTools Protocol (CDP) connection
1195
+ */
1196
+ getCdpUrl(record) {
1197
+ const cdpUrl = this.withPath("/ws/automation").replace("http", "ws");
1198
+ const url = new URL(cdpUrl);
1199
+ url.searchParams.set("tenantId", this.config.accountId);
1200
+ if (record) {
1201
+ url.searchParams.set("recording", "true");
1202
+ }
1203
+ return url.toString();
1204
+ }
1205
+ /**
1206
+ * Generate the WebSocket URL for VNC (Virtual Network Computing) live view connection
1207
+ */
1208
+ getVncUrl(record) {
1209
+ const vncUrl = this.withPath("/ws/liveview").replace("http", "ws");
1210
+ const url = new URL(vncUrl);
1211
+ url.searchParams.set("tenantId", this.config.accountId);
1212
+ if (record) {
1213
+ url.searchParams.set("recording", "true");
1214
+ }
1215
+ return url.toString();
1216
+ }
1217
+ /**
1218
+ * List all recordings
1219
+ */
1220
+ listRecordings = async (params) => {
1221
+ return this.get({ path: "/recordings", config: params?.config });
1222
+ };
1223
+ /**
1224
+ * Delete a recording
1225
+ */
1226
+ deleteRecording = async (params) => {
1227
+ return this.delete({ path: `/recordings/${params.filename}`, config: params.config });
1228
+ };
1229
+ /**
1230
+ * Download a recording video file
1231
+ */
1232
+ downloadRecording = async (params) => {
1233
+ return this.getVideo({
1234
+ path: `/recordings/${params.filename}`,
1235
+ savePath: params.savePath
1236
+ });
1237
+ };
1238
+ /**
1239
+ * Helper method to download video file
1240
+ */
1241
+ async getVideo(params) {
1242
+ const url = this.withPath(params.path, params.query);
1243
+ const cfg = Config.withConfigs(this.config, params.config);
1244
+ const reqHeaders = this.prepareHeaders({ headers: params.headers, config: cfg });
1245
+ try {
1246
+ const response = await fetch(url, {
1247
+ method: "GET",
1248
+ headers: reqHeaders,
1249
+ signal: AbortSignal.timeout(cfg.timeout)
1250
+ });
1251
+ if (!response.ok) {
1252
+ const errorText = await response.text();
1253
+ throw new ClientError(response.status, errorText);
1254
+ }
1255
+ const arrayBuffer = await response.arrayBuffer();
1256
+ const buffer = Buffer.from(arrayBuffer);
1257
+ await fs2.promises.writeFile(params.savePath, buffer);
1258
+ return {
1259
+ savedPath: params.savePath,
1260
+ size: buffer.length
1261
+ };
1262
+ } catch (error) {
1263
+ if (error instanceof ClientError) {
1264
+ throw error;
1265
+ }
1266
+ logger.error(`Download video error: ${error}`);
1267
+ throw new ClientError(0, `Download video error: ${error}`);
1268
+ }
1269
+ }
1270
+ };
1271
+ }
1272
+ });
1273
+
1274
+ // src/utils/model.ts
1275
+ function isFinalStatus(status) {
1276
+ return [
1277
+ void 0,
1278
+ null,
1279
+ "",
1280
+ ...["READY", "CREATE_FAILED", "UPDATE_FAILED", "DELETE_FAILED"]
1281
+ ].includes(status);
1282
+ }
1283
+ var Status;
1284
+ var init_model = __esm({
1285
+ "src/utils/model.ts"() {
1286
+ Status = {
1287
+ CREATING: "CREATING",
1288
+ CREATE_FAILED: "CREATE_FAILED",
1289
+ READY: "READY",
1290
+ UPDATING: "UPDATING",
1291
+ UPDATE_FAILED: "UPDATE_FAILED",
1292
+ DELETING: "DELETING",
1293
+ DELETE_FAILED: "DELETE_FAILED"
1294
+ };
1295
+ }
1296
+ });
1297
+
1298
+ // src/sandbox/model.ts
1299
+ var TemplateType, SandboxState, TemplateNetworkMode, TemplateOSSPermission, CodeLanguage;
1300
+ var init_model2 = __esm({
1301
+ "src/sandbox/model.ts"() {
1302
+ init_model();
1303
+ TemplateType = /* @__PURE__ */ ((TemplateType2) => {
1304
+ TemplateType2["CODE_INTERPRETER"] = "CodeInterpreter";
1305
+ TemplateType2["BROWSER"] = "Browser";
1306
+ TemplateType2["AIO"] = "AllInOne";
1307
+ TemplateType2["CUSTOM"] = "CustomImage";
1308
+ return TemplateType2;
1309
+ })(TemplateType || {});
1310
+ SandboxState = /* @__PURE__ */ ((SandboxState3) => {
1311
+ SandboxState3["CREATING"] = "Creating";
1312
+ SandboxState3["RUNNING"] = "Running";
1313
+ SandboxState3["READY"] = "READY";
1314
+ SandboxState3["STOPPED"] = "Stopped";
1315
+ SandboxState3["FAILED"] = "Failed";
1316
+ SandboxState3["DELETING"] = "Deleting";
1317
+ return SandboxState3;
1318
+ })(SandboxState || {});
1319
+ TemplateNetworkMode = /* @__PURE__ */ ((TemplateNetworkMode2) => {
1320
+ TemplateNetworkMode2["PUBLIC"] = "PUBLIC";
1321
+ TemplateNetworkMode2["PRIVATE"] = "PRIVATE";
1322
+ TemplateNetworkMode2["PUBLIC_AND_PRIVATE"] = "PUBLIC_AND_PRIVATE";
1323
+ return TemplateNetworkMode2;
1324
+ })(TemplateNetworkMode || {});
1325
+ TemplateOSSPermission = /* @__PURE__ */ ((TemplateOSSPermission2) => {
1326
+ TemplateOSSPermission2["READ_WRITE"] = "READ_WRITE";
1327
+ TemplateOSSPermission2["READ_ONLY"] = "READ_ONLY";
1328
+ return TemplateOSSPermission2;
1329
+ })(TemplateOSSPermission || {});
1330
+ CodeLanguage = /* @__PURE__ */ ((CodeLanguage2) => {
1331
+ CodeLanguage2["PYTHON"] = "python";
1332
+ CodeLanguage2["JAVASCRIPT"] = "javascript";
1333
+ return CodeLanguage2;
1334
+ })(CodeLanguage || {});
1335
+ }
1336
+ });
1337
+ var CodeInterpreterDataAPI;
1338
+ var init_code_interpreter_data = __esm({
1339
+ "src/sandbox/api/code-interpreter-data.ts"() {
1340
+ init_config();
1341
+ init_exception();
1342
+ init_log();
1343
+ init_model2();
1344
+ init_sandbox_data();
1345
+ CodeInterpreterDataAPI = class extends SandboxDataAPI {
1346
+ constructor(params) {
1347
+ super({
1348
+ sandboxId: params.sandboxId,
1349
+ config: params.config,
1350
+ // Set namespace to include sandboxId for correct API path generation
1351
+ namespace: `sandboxes/${params.sandboxId}`
1352
+ });
1353
+ }
1354
+ /**
1355
+ * List directory contents
1356
+ */
1357
+ async listDirectory(params) {
1358
+ const query = {};
1359
+ if (params?.path !== void 0) {
1360
+ query.path = params.path;
1361
+ }
1362
+ if (params?.depth !== void 0) {
1363
+ query.depth = params.depth;
1364
+ }
1365
+ return this.get({ path: "/filesystem", query, config: params?.config });
1366
+ }
1367
+ /**
1368
+ * Get file/directory stats
1369
+ */
1370
+ async stat(params) {
1371
+ const query = {
1372
+ path: params.path
1373
+ };
1374
+ return this.get({ path: "/filesystem/stat", query, config: params.config });
1375
+ }
1376
+ /**
1377
+ * Create directory
1378
+ */
1379
+ async mkdir(params) {
1380
+ const data = {
1381
+ path: params.path,
1382
+ parents: params.parents !== void 0 ? params.parents : true,
1383
+ mode: params.mode || "0755"
1384
+ };
1385
+ return this.post({ path: "/filesystem/mkdir", data, config: params.config });
1386
+ }
1387
+ /**
1388
+ * Move file or directory
1389
+ */
1390
+ async moveFile(params) {
1391
+ const data = {
1392
+ source: params.source,
1393
+ destination: params.destination
1394
+ };
1395
+ return this.post({ path: "/filesystem/move", data, config: params.config });
1396
+ }
1397
+ /**
1398
+ * Remove file or directory
1399
+ */
1400
+ async removeFile(params) {
1401
+ const data = {
1402
+ path: params.path
1403
+ };
1404
+ return this.post({ path: "/filesystem/remove", data, config: params.config });
1405
+ }
1406
+ /**
1407
+ * List code execution contexts
1408
+ */
1409
+ async listContexts(params) {
1410
+ return this.get({ path: "/contexts", config: params?.config });
1411
+ }
1412
+ /**
1413
+ * Create a new code execution context
1414
+ */
1415
+ async createContext(params) {
1416
+ const language = params?.language || "python" /* PYTHON */;
1417
+ const cwd = params?.cwd || "/home/user";
1418
+ if (language !== "python" && language !== "javascript") {
1419
+ throw new Error(`language must be 'python' or 'javascript', got: ${language}`);
1420
+ }
1421
+ const data = {
1422
+ cwd,
1423
+ language
1424
+ };
1425
+ return this.post({ path: "/contexts", data, config: params?.config });
1426
+ }
1427
+ /**
1428
+ * Get context details
1429
+ */
1430
+ async getContext(params) {
1431
+ return this.get({ path: `/contexts/${params.contextId}`, config: params.config });
1432
+ }
1433
+ /**
1434
+ * Execute code in a context
1435
+ */
1436
+ async executeCode(params) {
1437
+ const { code, contextId, language, timeout = 30, config: config2 } = params;
1438
+ if (language && language !== "python" && language !== "javascript") {
1439
+ throw new Error(`language must be 'python' or 'javascript', got: ${language}`);
1440
+ }
1441
+ const data = {
1442
+ code
1443
+ };
1444
+ if (timeout !== void 0) {
1445
+ data.timeout = timeout;
1446
+ }
1447
+ if (language !== void 0) {
1448
+ data.language = language;
1449
+ }
1450
+ if (contextId !== void 0) {
1451
+ data.contextId = contextId;
1452
+ }
1453
+ return this.post({ path: "/contexts/execute", data, config: config2 });
1454
+ }
1455
+ /**
1456
+ * Delete a context
1457
+ */
1458
+ async deleteContext(params) {
1459
+ return this.delete({ path: `/contexts/${params.contextId}`, config: params.config });
1460
+ }
1461
+ /**
1462
+ * Read file contents
1463
+ */
1464
+ async readFile(params) {
1465
+ const query = {
1466
+ path: params.path
1467
+ };
1468
+ return this.get({ path: "/files", query, config: params.config });
1469
+ }
1470
+ /**
1471
+ * Write file contents
1472
+ */
1473
+ async writeFile(params) {
1474
+ const data = {
1475
+ path: params.path,
1476
+ content: params.content,
1477
+ mode: params.mode || "644",
1478
+ encoding: params.encoding || "utf-8",
1479
+ createDir: params.createDir !== void 0 ? params.createDir : true
1480
+ };
1481
+ return this.post({ path: "/files", data, config: params.config });
1482
+ }
1483
+ /**
1484
+ * Upload file to sandbox
1485
+ */
1486
+ async uploadFile(params) {
1487
+ return this.postFile({
1488
+ path: "/filesystem/upload",
1489
+ localFilePath: params.localFilePath,
1490
+ targetFilePath: params.targetFilePath,
1491
+ config: params.config
1492
+ });
1493
+ }
1494
+ /**
1495
+ * Download file from sandbox
1496
+ */
1497
+ async downloadFile(params) {
1498
+ const query = { path: params.path };
1499
+ return this.getFile({
1500
+ path: "/filesystem/download",
1501
+ savePath: params.savePath,
1502
+ query,
1503
+ config: params.config
1504
+ });
1505
+ }
1506
+ /**
1507
+ * Execute shell command
1508
+ */
1509
+ async cmd(params) {
1510
+ const data = {
1511
+ command: params.command,
1512
+ cwd: params.cwd
1513
+ };
1514
+ if (params.timeout !== void 0) {
1515
+ data.timeout = params.timeout;
1516
+ }
1517
+ return this.post({ path: "/processes/cmd", data, config: params.config });
1518
+ }
1519
+ /**
1520
+ * List running processes
1521
+ */
1522
+ async listProcesses(params) {
1523
+ return this.get({ path: "/processes", config: params?.config });
1524
+ }
1525
+ /**
1526
+ * Get process details
1527
+ */
1528
+ async getProcess(params) {
1529
+ return this.get({ path: `/processes/${params.pid}`, config: params.config });
1530
+ }
1531
+ /**
1532
+ * Kill a process
1533
+ */
1534
+ async killProcess(params) {
1535
+ return this.delete({ path: `/processes/${params.pid}`, config: params.config });
1536
+ }
1537
+ /**
1538
+ * Helper method to upload file using multipart/form-data
1539
+ */
1540
+ async postFile(params) {
1541
+ const filename = path.basename(params.localFilePath);
1542
+ const url = this.withPath(params.path, params.query);
1543
+ const reqHeaders = this.prepareHeaders({ headers: params.headers, config: params.config });
1544
+ delete reqHeaders["Content-Type"];
1545
+ try {
1546
+ const fileContent = await fs2.promises.readFile(params.localFilePath);
1547
+ const formData = new FormData();
1548
+ formData.append("file", new Blob([fileContent]), filename);
1549
+ const data = params.formData || {};
1550
+ data.path = params.targetFilePath;
1551
+ Object.entries(data).forEach(([key, value]) => {
1552
+ formData.append(key, String(value));
1553
+ });
1554
+ const cfg = Config.withConfigs(this.config, params.config);
1555
+ const response = await fetch(url, {
1556
+ method: "POST",
1557
+ headers: reqHeaders,
1558
+ body: formData,
1559
+ signal: AbortSignal.timeout(cfg.timeout)
1560
+ });
1561
+ if (!response.ok) {
1562
+ const errorText = await response.text();
1563
+ throw new ClientError(response.status, errorText);
1564
+ }
1565
+ return response.json();
1566
+ } catch (error) {
1567
+ if (error instanceof ClientError) {
1568
+ throw error;
1569
+ }
1570
+ logger.error(`Upload file error: ${error}`);
1571
+ throw new ClientError(0, `Upload file error: ${error}`);
1572
+ }
1573
+ }
1574
+ /**
1575
+ * Helper method to download file
1576
+ */
1577
+ async getFile(params) {
1578
+ const url = this.withPath(params.path, params.query);
1579
+ const reqHeaders = this.prepareHeaders({ headers: params.headers, config: params.config });
1580
+ try {
1581
+ const cfg = Config.withConfigs(this.config, params.config);
1582
+ const response = await fetch(url, {
1583
+ method: "GET",
1584
+ headers: reqHeaders,
1585
+ signal: AbortSignal.timeout(cfg.timeout)
1586
+ });
1587
+ if (!response.ok) {
1588
+ const errorText = await response.text();
1589
+ throw new ClientError(response.status, errorText);
1590
+ }
1591
+ const arrayBuffer = await response.arrayBuffer();
1592
+ const buffer = Buffer.from(arrayBuffer);
1593
+ await fs2.promises.writeFile(params.savePath, buffer);
1594
+ return {
1595
+ savedPath: params.savePath,
1596
+ size: buffer.length
1597
+ };
1598
+ } catch (error) {
1599
+ if (error instanceof ClientError) {
1600
+ throw error;
1601
+ }
1602
+ logger.error(`Download file error: ${error}`);
1603
+ throw new ClientError(0, `Download file error: ${error}`);
1604
+ }
1605
+ }
1606
+ };
1607
+ }
1608
+ });
1609
+
1610
+ // src/sandbox/api/aio-data.ts
1611
+ var AioDataAPI;
1612
+ var init_aio_data = __esm({
1613
+ "src/sandbox/api/aio-data.ts"() {
1614
+ init_browser_data();
1615
+ init_code_interpreter_data();
1616
+ AioDataAPI = class extends CodeInterpreterDataAPI {
1617
+ browserAPI;
1618
+ constructor(params) {
1619
+ super({
1620
+ sandboxId: params.sandboxId,
1621
+ config: params.config
1622
+ });
1623
+ this.browserAPI = new BrowserDataAPI({
1624
+ sandboxId: params.sandboxId,
1625
+ config: params.config
1626
+ });
1627
+ }
1628
+ // Browser API methods - delegate to browserAPI
1629
+ /**
1630
+ * Get CDP WebSocket URL for browser automation
1631
+ */
1632
+ getCdpUrl(record) {
1633
+ return this.browserAPI.getCdpUrl(record);
1634
+ }
1635
+ /**
1636
+ * Get VNC WebSocket URL for live view
1637
+ */
1638
+ getVncUrl(record) {
1639
+ return this.browserAPI.getVncUrl(record);
1640
+ }
1641
+ /**
1642
+ * List browser recordings
1643
+ */
1644
+ listRecordings = async (params) => {
1645
+ return this.browserAPI.listRecordings(params);
1646
+ };
1647
+ /**
1648
+ * Delete a recording
1649
+ */
1650
+ deleteRecording = async (params) => {
1651
+ return this.browserAPI.deleteRecording(params);
1652
+ };
1653
+ /**
1654
+ * Download a recording
1655
+ */
1656
+ downloadRecording = async (params) => {
1657
+ return this.browserAPI.downloadRecording(params);
1658
+ };
1659
+ };
1660
+ }
1661
+ });
1662
+
1663
+ // src/utils/data-api.ts
1664
+ var init_data_api = __esm({
1665
+ "src/utils/data-api.ts"() {
1666
+ init_config();
1667
+ init_exception();
1668
+ init_log();
1669
+ }
1670
+ });
1671
+
1672
+ // src/utils/index.ts
1673
+ var init_utils = __esm({
1674
+ "src/utils/index.ts"() {
1675
+ init_version_check();
1676
+ init_config();
1677
+ init_data_api();
1678
+ init_exception();
1679
+ init_log();
1680
+ init_model();
1681
+ }
1682
+ });
1683
+
1684
+ // src/utils/resource.ts
1685
+ function updateObjectProperties(target, source) {
1686
+ for (const key in source) {
1687
+ if (Object.prototype.hasOwnProperty.call(source, key) && typeof source[key] !== "function" && !key.startsWith("_")) {
1688
+ target[key] = source[key];
1689
+ }
1690
+ }
1691
+ }
1692
+ function listAllResourcesFunction(list) {
1693
+ return async (params) => {
1694
+ const { config: config2, ...restParams } = params ?? {};
1695
+ const allResults = [];
1696
+ let page = 1;
1697
+ const pageSize = 50;
1698
+ while (true) {
1699
+ const pageResults = await list({
1700
+ input: {
1701
+ ...restParams,
1702
+ pageNumber: page,
1703
+ pageSize
1704
+ },
1705
+ config: config2
1706
+ });
1707
+ page += 1;
1708
+ allResults.push(...pageResults);
1709
+ if (pageResults.length < pageSize) break;
1710
+ }
1711
+ const resultSet = /* @__PURE__ */ new Set();
1712
+ const results = [];
1713
+ for (const item of allResults) {
1714
+ const uniqId = item.uniqIdCallback() || "";
1715
+ if (!resultSet.has(uniqId) && uniqId) {
1716
+ resultSet.add(uniqId);
1717
+ results.push(item);
1718
+ }
1719
+ }
1720
+ return results;
1721
+ };
1722
+ }
1723
+ var ResourceBase;
1724
+ var init_resource = __esm({
1725
+ "src/utils/resource.ts"() {
1726
+ init_exception();
1727
+ init_log();
1728
+ init_model();
1729
+ ResourceBase = class {
1730
+ status;
1731
+ _config;
1732
+ // static async list(params?: {
1733
+ // input?: PageableInput;
1734
+ // config?: Config;
1735
+ // }): Promise<WithUniqIdCallback[]> {
1736
+ // return [];
1737
+ // }
1738
+ waitUntil = async (params) => {
1739
+ const { checkFinishedCallback, intervalSeconds = 5, timeoutSeconds = 300 } = params;
1740
+ const startTime = Date.now();
1741
+ while (true) {
1742
+ if (await checkFinishedCallback(this)) return this;
1743
+ if (Date.now() - startTime >= timeoutSeconds * 1e3) {
1744
+ throw new Error("Timeout waiting for resource to reach desired state");
1745
+ }
1746
+ await new Promise((resolve) => setTimeout(resolve, intervalSeconds * 1e3));
1747
+ }
1748
+ };
1749
+ waitUntilReadyOrFailed = async (params) => {
1750
+ const { callback, intervalSeconds = 5, timeoutSeconds = 300 } = params ?? {};
1751
+ async function checkFinishedCallback(resource) {
1752
+ await resource.refresh();
1753
+ if (callback) await callback(resource);
1754
+ logger.debug(`Resource status: ${resource.status}`);
1755
+ return isFinalStatus(resource.status);
1756
+ }
1757
+ return await this.waitUntil({
1758
+ checkFinishedCallback,
1759
+ intervalSeconds,
1760
+ timeoutSeconds
1761
+ });
1762
+ };
1763
+ deleteAndWaitUntilFinished = async (params) => {
1764
+ const { callback, intervalSeconds = 5, timeoutSeconds = 300 } = params ?? {};
1765
+ try {
1766
+ await this.delete();
1767
+ } catch (error) {
1768
+ if (error instanceof ResourceNotExistError) return;
1769
+ }
1770
+ async function checkFinishedCallback(resource) {
1771
+ try {
1772
+ await resource.refresh();
1773
+ if (callback) await callback(resource);
1774
+ } catch (error) {
1775
+ if (error instanceof ResourceNotExistError) return true;
1776
+ if (resource.status === Status.DELETING) return false;
1777
+ throw Error(`Resource status is ${resource.status}`);
1778
+ }
1779
+ return false;
1780
+ }
1781
+ return await this.waitUntil({
1782
+ checkFinishedCallback,
1783
+ intervalSeconds,
1784
+ timeoutSeconds
1785
+ });
1786
+ };
1787
+ refresh = async (params) => await this.get(params);
1788
+ /**
1789
+ * 更新实例自身的属性 / Update instance properties
1790
+ *
1791
+ * @param source - 源对象 / Source object
1792
+ */
1793
+ updateSelf(source) {
1794
+ updateObjectProperties(this, source);
1795
+ }
1796
+ setConfig = (config2) => {
1797
+ this._config = config2;
1798
+ return this;
1799
+ };
1800
+ };
1801
+ }
1802
+ });
1803
+
1804
+ // src/sandbox/code-interpreter-sandbox.ts
1805
+ var code_interpreter_sandbox_exports = {};
1806
+ __export(code_interpreter_sandbox_exports, {
1807
+ CodeInterpreterSandbox: () => CodeInterpreterSandbox,
1808
+ ContextOperations: () => ContextOperations,
1809
+ FileOperations: () => FileOperations,
1810
+ FileSystemOperations: () => FileSystemOperations,
1811
+ ProcessOperations: () => ProcessOperations
1812
+ });
1813
+ var FileOperations, FileSystemOperations, ProcessOperations, ContextOperations, CodeInterpreterSandbox;
1814
+ var init_code_interpreter_sandbox = __esm({
1815
+ "src/sandbox/code-interpreter-sandbox.ts"() {
1816
+ init_log();
1817
+ init_exception();
1818
+ init_code_interpreter_data();
1819
+ init_model2();
1820
+ init_sandbox();
1821
+ FileOperations = class {
1822
+ sandbox;
1823
+ constructor(sandbox) {
1824
+ this.sandbox = sandbox;
1825
+ }
1826
+ /**
1827
+ * Read a file from the code interpreter
1828
+ */
1829
+ read = async (params) => {
1830
+ return this.sandbox.dataApi.readFile(params);
1831
+ };
1832
+ /**
1833
+ * Write a file to the code interpreter
1834
+ */
1835
+ write = async (params) => {
1836
+ return this.sandbox.dataApi.writeFile(params);
1837
+ };
1838
+ };
1839
+ FileSystemOperations = class {
1840
+ sandbox;
1841
+ constructor(sandbox) {
1842
+ this.sandbox = sandbox;
1843
+ }
1844
+ /**
1845
+ * List directory contents
1846
+ */
1847
+ list = async (params) => {
1848
+ return this.sandbox.dataApi.listDirectory(params);
1849
+ };
1850
+ /**
1851
+ * Move a file or directory
1852
+ */
1853
+ move = async (params) => {
1854
+ return this.sandbox.dataApi.moveFile(params);
1855
+ };
1856
+ /**
1857
+ * Remove a file or directory
1858
+ */
1859
+ remove = async (params) => {
1860
+ return this.sandbox.dataApi.removeFile(params);
1861
+ };
1862
+ /**
1863
+ * Get file or directory statistics
1864
+ */
1865
+ stat = async (params) => {
1866
+ return this.sandbox.dataApi.stat(params);
1867
+ };
1868
+ /**
1869
+ * Create a directory
1870
+ */
1871
+ mkdir = async (params) => {
1872
+ return this.sandbox.dataApi.mkdir(params);
1873
+ };
1874
+ /**
1875
+ * Upload a file to the code interpreter
1876
+ */
1877
+ upload = async (params) => {
1878
+ return this.sandbox.dataApi.uploadFile(params);
1879
+ };
1880
+ /**
1881
+ * Download a file from the code interpreter
1882
+ */
1883
+ download = async (params) => {
1884
+ return this.sandbox.dataApi.downloadFile(params);
1885
+ };
1886
+ };
1887
+ ProcessOperations = class {
1888
+ sandbox;
1889
+ constructor(sandbox) {
1890
+ this.sandbox = sandbox;
1891
+ }
1892
+ /**
1893
+ * Execute a command in the code interpreter
1894
+ */
1895
+ cmd = async (params) => {
1896
+ return this.sandbox.dataApi.cmd(params);
1897
+ };
1898
+ /**
1899
+ * List all processes
1900
+ */
1901
+ list = async (params) => {
1902
+ return this.sandbox.dataApi.listProcesses(params);
1903
+ };
1904
+ /**
1905
+ * Get a specific process by PID
1906
+ */
1907
+ get = async (params) => {
1908
+ return this.sandbox.dataApi.getProcess(params);
1909
+ };
1910
+ /**
1911
+ * Kill a specific process by PID
1912
+ */
1913
+ kill = async (params) => {
1914
+ return this.sandbox.dataApi.killProcess(params);
1915
+ };
1916
+ };
1917
+ ContextOperations = class {
1918
+ sandbox;
1919
+ _contextId;
1920
+ _language;
1921
+ _cwd;
1922
+ constructor(sandbox) {
1923
+ this.sandbox = sandbox;
1924
+ }
1925
+ /**
1926
+ * Get the current context ID
1927
+ */
1928
+ get contextId() {
1929
+ return this._contextId;
1930
+ }
1931
+ /**
1932
+ * List all contexts
1933
+ */
1934
+ list = async (params) => {
1935
+ return this.sandbox.dataApi.listContexts(params);
1936
+ };
1937
+ /**
1938
+ * Create a new context and save its ID
1939
+ */
1940
+ create = async (params) => {
1941
+ const language = params?.language || "python" /* PYTHON */;
1942
+ const cwd = params?.cwd || "/home/user";
1943
+ const result = await this.sandbox.dataApi.createContext({
1944
+ language,
1945
+ cwd
1946
+ });
1947
+ if (result?.id && result?.cwd && result?.language) {
1948
+ this._contextId = result.id;
1949
+ this._language = result.language;
1950
+ this._cwd = result.cwd;
1951
+ return this;
1952
+ }
1953
+ throw new ServerError(500, "Failed to create context");
1954
+ };
1955
+ /**
1956
+ * Get a specific context by ID
1957
+ */
1958
+ get = async (params) => {
1959
+ const id = params?.contextId || this._contextId;
1960
+ if (!id) {
1961
+ logger.error("context id is not set");
1962
+ throw new Error("context id is not set");
1963
+ }
1964
+ const result = await this.sandbox.dataApi.getContext({ contextId: id });
1965
+ if (result?.id && result?.cwd && result?.language) {
1966
+ this._contextId = result.id;
1967
+ this._language = result.language;
1968
+ this._cwd = result.cwd;
1969
+ return this;
1970
+ }
1971
+ throw new ServerError(500, "Failed to get context");
1972
+ };
1973
+ /**
1974
+ * Execute code in a context
1975
+ */
1976
+ execute = async (params) => {
1977
+ const { code, timeout = 30 } = params;
1978
+ let { contextId, language } = params;
1979
+ if (!contextId) {
1980
+ contextId = this._contextId;
1981
+ }
1982
+ if (!contextId && !language) {
1983
+ logger.debug("context id is not set, use default language: python");
1984
+ language = "python" /* PYTHON */;
1985
+ }
1986
+ return this.sandbox.dataApi.executeCode({
1987
+ code,
1988
+ contextId,
1989
+ language,
1990
+ timeout
1991
+ });
1992
+ };
1993
+ /**
1994
+ * Delete a context
1995
+ */
1996
+ delete = async (params) => {
1997
+ const id = params?.contextId || this._contextId;
1998
+ if (!id) {
1999
+ throw new Error(
2000
+ "context_id is required. Either pass it as parameter or create a context first."
2001
+ );
2002
+ }
2003
+ const result = await this.sandbox.dataApi.deleteContext({ contextId: id });
2004
+ this._contextId = void 0;
2005
+ return result;
2006
+ };
2007
+ };
2008
+ CodeInterpreterSandbox = class extends Sandbox {
2009
+ static templateType = "CodeInterpreter" /* CODE_INTERPRETER */;
2010
+ /**
2011
+ * Create a Code Interpreter Sandbox from template
2012
+ * 从模板创建代码解释器沙箱 / Create Code Interpreter Sandbox from Template
2013
+ */
2014
+ static async createFromTemplate(templateName, options, config2) {
2015
+ const sandbox = await Sandbox.create({
2016
+ input: {
2017
+ templateName,
2018
+ sandboxIdleTimeoutSeconds: options?.sandboxIdleTimeoutSeconds,
2019
+ nasConfig: options?.nasConfig,
2020
+ ossMountConfig: options?.ossMountConfig,
2021
+ polarFsConfig: options?.polarFsConfig
2022
+ },
2023
+ templateType: "CodeInterpreter" /* CODE_INTERPRETER */,
2024
+ config: config2
2025
+ });
2026
+ return sandbox;
2027
+ }
2028
+ constructor(sandbox, config2) {
2029
+ super(sandbox, config2);
2030
+ }
2031
+ _dataApi;
2032
+ _file;
2033
+ _fileSystem;
2034
+ _context;
2035
+ _process;
2036
+ /**
2037
+ * Get data API client
2038
+ */
2039
+ get dataApi() {
2040
+ if (!this._dataApi) {
2041
+ this._dataApi = new CodeInterpreterDataAPI({
2042
+ sandboxId: this.sandboxId || "",
2043
+ config: this._config
2044
+ });
2045
+ }
2046
+ return this._dataApi;
2047
+ }
2048
+ /**
2049
+ * Access file upload/download operations
2050
+ */
2051
+ get file() {
2052
+ if (!this._file) {
2053
+ this._file = new FileOperations(this);
2054
+ }
2055
+ return this._file;
2056
+ }
2057
+ /**
2058
+ * Access file system operations
2059
+ */
2060
+ get fileSystem() {
2061
+ if (!this._fileSystem) {
2062
+ this._fileSystem = new FileSystemOperations(this);
2063
+ }
2064
+ return this._fileSystem;
2065
+ }
2066
+ /**
2067
+ * Access context management operations
2068
+ */
2069
+ get context() {
2070
+ if (!this._context) {
2071
+ this._context = new ContextOperations(this);
2072
+ }
2073
+ return this._context;
2074
+ }
2075
+ /**
2076
+ * Access process management operations
2077
+ */
2078
+ get process() {
2079
+ if (!this._process) {
2080
+ this._process = new ProcessOperations(this);
2081
+ }
2082
+ return this._process;
2083
+ }
2084
+ /**
2085
+ * Check sandbox health
2086
+ */
2087
+ checkHealth = async (params) => {
2088
+ return this.dataApi.checkHealth({
2089
+ sandboxId: this.sandboxId,
2090
+ config: params?.config
2091
+ });
2092
+ };
2093
+ /**
2094
+ * Execute code (convenience method delegating to context.execute)
2095
+ */
2096
+ execute = async (params) => {
2097
+ return this.context.execute(params);
2098
+ };
2099
+ };
2100
+ }
2101
+ });
2102
+
2103
+ // src/sandbox/browser-sandbox.ts
2104
+ var browser_sandbox_exports = {};
2105
+ __export(browser_sandbox_exports, {
2106
+ BrowserSandbox: () => BrowserSandbox
2107
+ });
2108
+ var BrowserSandbox;
2109
+ var init_browser_sandbox = __esm({
2110
+ "src/sandbox/browser-sandbox.ts"() {
2111
+ init_browser_data();
2112
+ init_model2();
2113
+ init_sandbox();
2114
+ BrowserSandbox = class extends Sandbox {
2115
+ static templateType = "Browser" /* BROWSER */;
2116
+ /**
2117
+ * Create a Browser Sandbox from template
2118
+ * 从模板创建浏览器沙箱 / Create Browser Sandbox from Template
2119
+ */
2120
+ static async createFromTemplate(templateName, options, config2) {
2121
+ const sandbox = await Sandbox.create({
2122
+ input: {
2123
+ templateName,
2124
+ sandboxIdleTimeoutSeconds: options?.sandboxIdleTimeoutSeconds,
2125
+ nasConfig: options?.nasConfig,
2126
+ ossMountConfig: options?.ossMountConfig,
2127
+ polarFsConfig: options?.polarFsConfig
2128
+ },
2129
+ templateType: "Browser" /* BROWSER */,
2130
+ config: config2
2131
+ });
2132
+ return sandbox;
2133
+ }
2134
+ constructor(sandbox, config2) {
2135
+ super(sandbox, config2);
2136
+ }
2137
+ _dataApi;
2138
+ /**
2139
+ * Get data API client
2140
+ */
2141
+ get dataApi() {
2142
+ if (!this._dataApi) {
2143
+ if (!this.sandboxId) {
2144
+ throw new Error("Sandbox ID is not set");
2145
+ }
2146
+ this._dataApi = new BrowserDataAPI({
2147
+ sandboxId: this.sandboxId,
2148
+ config: this._config
2149
+ });
2150
+ }
2151
+ return this._dataApi;
2152
+ }
2153
+ /**
2154
+ * Check sandbox health
2155
+ */
2156
+ checkHealth = async (params) => {
2157
+ return this.dataApi.checkHealth({
2158
+ sandboxId: this.sandboxId,
2159
+ config: params?.config
2160
+ });
2161
+ };
2162
+ /**
2163
+ * Get CDP WebSocket URL for browser automation
2164
+ */
2165
+ getCdpUrl(record) {
2166
+ return this.dataApi.getCdpUrl(record);
2167
+ }
2168
+ /**
2169
+ * Get VNC WebSocket URL for live view
2170
+ */
2171
+ getVncUrl(record) {
2172
+ return this.dataApi.getVncUrl(record);
2173
+ }
2174
+ /**
2175
+ * List all recordings
2176
+ */
2177
+ listRecordings = async (params) => {
2178
+ return this.dataApi.listRecordings(params);
2179
+ };
2180
+ /**
2181
+ * Download a recording video file
2182
+ */
2183
+ downloadRecording = async (params) => {
2184
+ return this.dataApi.downloadRecording(params);
2185
+ };
2186
+ /**
2187
+ * Delete a recording
2188
+ */
2189
+ deleteRecording = async (params) => {
2190
+ return this.dataApi.deleteRecording(params);
2191
+ };
2192
+ };
2193
+ }
2194
+ });
2195
+
2196
+ // src/sandbox/custom-sandbox.ts
2197
+ var custom_sandbox_exports = {};
2198
+ __export(custom_sandbox_exports, {
2199
+ CustomSandbox: () => CustomSandbox
2200
+ });
2201
+ var CustomSandbox;
2202
+ var init_custom_sandbox = __esm({
2203
+ "src/sandbox/custom-sandbox.ts"() {
2204
+ init_config();
2205
+ init_model2();
2206
+ init_sandbox();
2207
+ init_sandbox_data();
2208
+ CustomSandbox = class extends Sandbox {
2209
+ static templateType = "CustomImage" /* CUSTOM */;
2210
+ /**
2211
+ * Create a Custom Sandbox from template
2212
+ * 从模板创建自定义沙箱 / Create Custom Sandbox from Template
2213
+ */
2214
+ static async createFromTemplate(templateName, options, config2) {
2215
+ return await Sandbox.create({
2216
+ input: {
2217
+ templateName,
2218
+ sandboxIdleTimeoutSeconds: options?.sandboxIdleTimeoutSeconds,
2219
+ nasConfig: options?.nasConfig,
2220
+ ossMountConfig: options?.ossMountConfig,
2221
+ polarFsConfig: options?.polarFsConfig
2222
+ },
2223
+ templateType: "CustomImage" /* CUSTOM */,
2224
+ config: config2
2225
+ });
2226
+ }
2227
+ constructor(sandbox, config2) {
2228
+ super(sandbox, config2);
2229
+ }
2230
+ _dataApi;
2231
+ /**
2232
+ * Get data API client
2233
+ */
2234
+ get dataApi() {
2235
+ if (!this._dataApi) {
2236
+ this._dataApi = new SandboxDataAPI({
2237
+ sandboxId: this.sandboxId || "",
2238
+ config: this._config
2239
+ });
2240
+ }
2241
+ return this._dataApi;
2242
+ }
2243
+ /**
2244
+ * Get base URL for the sandbox
2245
+ * 获取沙箱的基础 URL / Get base URL for the sandbox
2246
+ *
2247
+ * @returns 基础 URL / Base URL
2248
+ */
2249
+ getBaseUrl() {
2250
+ const cfg = Config.withConfigs(this._config);
2251
+ return `${cfg.dataEndpoint}/sandboxes/${this.sandboxId}`;
2252
+ }
2253
+ };
2254
+ }
2255
+ });
2256
+
2257
+ // src/sandbox/sandbox.ts
2258
+ var Sandbox;
2259
+ var init_sandbox = __esm({
2260
+ "src/sandbox/sandbox.ts"() {
2261
+ init_utils();
2262
+ init_log();
2263
+ init_config();
2264
+ init_resource();
2265
+ init_model2();
2266
+ init_sandbox_data();
2267
+ Sandbox = class _Sandbox extends ResourceBase {
2268
+ templateType;
2269
+ /**
2270
+ * 沙箱 ID / Sandbox ID
2271
+ */
2272
+ sandboxId;
2273
+ /**
2274
+ * 沙箱名称 / Sandbox Name
2275
+ */
2276
+ sandboxName;
2277
+ /**
2278
+ * 模板 ID / Template ID
2279
+ */
2280
+ templateId;
2281
+ /**
2282
+ * 模板名称 / Template Name
2283
+ */
2284
+ templateName;
2285
+ /**
2286
+ * 沙箱状态 / Sandbox State
2287
+ */
2288
+ state;
2289
+ /**
2290
+ * 状态原因 / State Reason
2291
+ */
2292
+ stateReason;
2293
+ /**
2294
+ * 沙箱创建时间 / Sandbox Creation Time
2295
+ */
2296
+ createdAt;
2297
+ /**
2298
+ * 最后更新时间 / Last Updated Time
2299
+ */
2300
+ lastUpdatedAt;
2301
+ /**
2302
+ * 沙箱空闲超时时间(秒) / Sandbox Idle Timeout (seconds)
2303
+ */
2304
+ sandboxIdleTimeoutSeconds;
2305
+ /**
2306
+ * 沙箱结束时间 / Sandbox End Time
2307
+ */
2308
+ endedAt;
2309
+ /**
2310
+ * 元数据 / Metadata
2311
+ */
2312
+ metadata;
2313
+ /**
2314
+ * 沙箱全局唯一资源名称 / Sandbox ARN
2315
+ */
2316
+ sandboxArn;
2317
+ /**
2318
+ * 沙箱空闲 TTL(秒) / Sandbox Idle TTL (seconds)
2319
+ */
2320
+ sandboxIdleTTLInSeconds;
2321
+ _config;
2322
+ constructor(data, config2) {
2323
+ super();
2324
+ if (data) {
2325
+ updateObjectProperties(this, data);
2326
+ }
2327
+ this._config = config2;
2328
+ }
2329
+ /**
2330
+ * Create sandbox from SDK response object
2331
+ * 从 SDK 响应对象创建沙箱 / Create Sandbox from SDK Response Object
2332
+ */
2333
+ static fromInnerObject(obj, config2) {
2334
+ return new _Sandbox(
2335
+ {
2336
+ sandboxId: obj.sandboxId,
2337
+ sandboxName: obj.sandboxName,
2338
+ templateId: obj.templateId,
2339
+ templateName: obj.templateName,
2340
+ // API returns "status" field, map it to "state"
2341
+ state: obj.status || obj.state,
2342
+ stateReason: obj.stateReason,
2343
+ createdAt: obj.createdAt,
2344
+ lastUpdatedAt: obj.lastUpdatedAt,
2345
+ sandboxIdleTimeoutSeconds: obj.sandboxIdleTimeoutSeconds,
2346
+ // New fields / 新增字段
2347
+ endedAt: obj.endedAt,
2348
+ metadata: obj.metadata,
2349
+ sandboxArn: obj.sandboxArn,
2350
+ sandboxIdleTTLInSeconds: obj.sandboxIdleTTLInSeconds
2351
+ },
2352
+ config2
2353
+ );
2354
+ }
2355
+ static getClient() {
2356
+ const { SandboxClient: SandboxClient2 } = (init_client(), __toCommonJS(client_exports));
2357
+ return new SandboxClient2();
2358
+ }
2359
+ static async create(arg1, arg2) {
2360
+ if (typeof arg1 === "object" && arg1 !== null && "input" in arg1) {
2361
+ return await _Sandbox.getClient().createSandbox(arg1);
2362
+ }
2363
+ logger.warn(
2364
+ "Deprecated: Sandbox.create(input, config) is deprecated. Use Sandbox.create({ input, config }) instead."
2365
+ );
2366
+ return await _Sandbox.getClient().createSandbox(arg1, arg2);
2367
+ }
2368
+ static async delete(arg1, arg2) {
2369
+ if (typeof arg1 === "string") {
2370
+ logger.warn(
2371
+ "Sandbox.delete(id, config) is deprecated. Use Sandbox.delete({ id, config }) instead."
2372
+ );
2373
+ return await _Sandbox.getClient().deleteSandbox(arg1, arg2);
2374
+ }
2375
+ return await _Sandbox.getClient().deleteSandbox(arg1);
2376
+ }
2377
+ static async stop(arg1, arg2) {
2378
+ if (typeof arg1 === "string") {
2379
+ logger.warn(
2380
+ "Sandbox.stop(id, config) is deprecated. Use Sandbox.stop({ id, config }) instead."
2381
+ );
2382
+ return await _Sandbox.getClient().stopSandbox(arg1, arg2);
2383
+ }
2384
+ return await _Sandbox.getClient().stopSandbox(arg1);
2385
+ }
2386
+ static async get(arg1, arg2, arg3) {
2387
+ let id;
2388
+ let templateType;
2389
+ let config2;
2390
+ if (typeof arg1 === "string") {
2391
+ logger.warn(
2392
+ "Deprecated: Sandbox.get(id, templateType?, config?) is deprecated. Use Sandbox.get({ id, templateType, config }) instead."
2393
+ );
2394
+ id = arg1;
2395
+ if (arg2 && typeof arg2 === "string") {
2396
+ templateType = arg2;
2397
+ config2 = arg3;
2398
+ } else {
2399
+ config2 = arg2;
2400
+ }
2401
+ } else {
2402
+ id = arg1.id;
2403
+ templateType = arg1.templateType;
2404
+ config2 = arg1.config;
2405
+ }
2406
+ try {
2407
+ const cfg = Config.withConfigs(config2);
2408
+ const dataApi = new SandboxDataAPI({
2409
+ sandboxId: id,
2410
+ config: cfg
2411
+ });
2412
+ const result = await dataApi.getSandbox({
2413
+ sandboxId: id,
2414
+ config: cfg
2415
+ });
2416
+ if (result.code !== "SUCCESS") {
2417
+ throw new ClientError(0, `Failed to get sandbox: ${result.message || "Unknown error"}`);
2418
+ }
2419
+ const data = result.data || {};
2420
+ const baseSandbox = _Sandbox.fromInnerObject(data, config2);
2421
+ if (templateType) {
2422
+ switch (templateType) {
2423
+ case "CodeInterpreter" /* CODE_INTERPRETER */: {
2424
+ const { CodeInterpreterSandbox: CodeInterpreterSandbox2 } = await Promise.resolve().then(() => (init_code_interpreter_sandbox(), code_interpreter_sandbox_exports));
2425
+ const sandbox = new CodeInterpreterSandbox2(baseSandbox, config2);
2426
+ return sandbox;
2427
+ }
2428
+ case "Browser" /* BROWSER */: {
2429
+ const { BrowserSandbox: BrowserSandbox2 } = await Promise.resolve().then(() => (init_browser_sandbox(), browser_sandbox_exports));
2430
+ const sandbox = new BrowserSandbox2(baseSandbox, config2);
2431
+ return sandbox;
2432
+ }
2433
+ case "AllInOne" /* AIO */: {
2434
+ const { AioSandbox: AioSandbox2 } = await Promise.resolve().then(() => (init_aio_sandbox(), aio_sandbox_exports));
2435
+ const sandbox = new AioSandbox2(baseSandbox, config2);
2436
+ return sandbox;
2437
+ }
2438
+ case "CustomImage" /* CUSTOM */: {
2439
+ const { CustomSandbox: CustomSandbox2 } = await Promise.resolve().then(() => (init_custom_sandbox(), custom_sandbox_exports));
2440
+ const sandbox = new CustomSandbox2(baseSandbox, config2);
2441
+ return sandbox;
2442
+ }
2443
+ }
2444
+ }
2445
+ return baseSandbox;
2446
+ } catch (error) {
2447
+ if (error instanceof HTTPError) {
2448
+ throw error.toResourceError("Sandbox", id);
2449
+ }
2450
+ throw error;
2451
+ }
2452
+ }
2453
+ static async list(arg1, arg2) {
2454
+ if (arg2 !== void 0 || arg1 && ("maxResults" in arg1 || "nextToken" in arg1 || "status" in arg1 || "templateName" in arg1 || "templateType" in arg1)) {
2455
+ logger.warn(
2456
+ "Deprecated: Sandbox.list(input, config) is deprecated. Use Sandbox.list({ input, config }) instead."
2457
+ );
2458
+ return await _Sandbox.getClient().listSandboxes(arg1, arg2);
2459
+ }
2460
+ return await _Sandbox.getClient().listSandboxes(
2461
+ arg1
2462
+ );
2463
+ }
2464
+ get = async (params) => {
2465
+ const { config: config2 } = params ?? {};
2466
+ return await _Sandbox.get({
2467
+ id: this.sandboxId,
2468
+ templateType: this.templateType,
2469
+ config: Config.withConfigs(this._config, config2)
2470
+ });
2471
+ };
2472
+ /**
2473
+ * Delete this sandbox
2474
+ */
2475
+ delete = async (params) => {
2476
+ const config2 = params?.config;
2477
+ if (!this.sandboxId) {
2478
+ throw new Error("sandboxId is required to delete a Sandbox");
2479
+ }
2480
+ const result = await _Sandbox.delete({
2481
+ id: this.sandboxId,
2482
+ config: config2 ?? this._config
2483
+ });
2484
+ updateObjectProperties(this, result);
2485
+ return this;
2486
+ };
2487
+ /**
2488
+ * Stop this sandbox
2489
+ */
2490
+ stop = async (params) => {
2491
+ const config2 = params?.config;
2492
+ if (!this.sandboxId) {
2493
+ throw new Error("sandboxId is required to stop a Sandbox");
2494
+ }
2495
+ const result = await _Sandbox.stop({
2496
+ id: this.sandboxId,
2497
+ config: config2 ?? this._config
2498
+ });
2499
+ updateObjectProperties(this, result);
2500
+ return this;
2501
+ };
2502
+ /**
2503
+ * Refresh this sandbox's data
2504
+ */
2505
+ refresh = async (params) => {
2506
+ const config2 = params?.config;
2507
+ if (!this.sandboxId) {
2508
+ throw new Error("sandboxId is required to refresh a Sandbox");
2509
+ }
2510
+ const result = await _Sandbox.get({
2511
+ id: this.sandboxId,
2512
+ config: config2 ?? this._config
2513
+ });
2514
+ updateObjectProperties(this, result);
2515
+ return this;
2516
+ };
2517
+ /**
2518
+ * Wait until the sandbox is running
2519
+ */
2520
+ waitUntilRunning = async (options, config2) => {
2521
+ const timeout = (options?.timeoutSeconds ?? 300) * 1e3;
2522
+ const interval = (options?.intervalSeconds ?? 5) * 1e3;
2523
+ const startTime = Date.now();
2524
+ while (Date.now() - startTime < timeout) {
2525
+ await this.refresh({ config: config2 });
2526
+ if (options?.beforeCheck) {
2527
+ options.beforeCheck(this);
2528
+ }
2529
+ if (this.state === "Running" /* RUNNING */ || this.state === "READY" /* READY */) {
2530
+ return this;
2531
+ }
2532
+ if (this.state === "Failed" /* FAILED */) {
2533
+ throw new Error(`Sandbox failed: ${this.stateReason}`);
2534
+ }
2535
+ await new Promise((resolve) => setTimeout(resolve, interval));
2536
+ }
2537
+ throw new Error(
2538
+ `Timeout waiting for Sandbox to be running after ${options?.timeoutSeconds ?? 300} seconds`
2539
+ );
2540
+ };
2541
+ };
2542
+ }
2543
+ });
2544
+
2545
+ // src/sandbox/aio-sandbox.ts
2546
+ var aio_sandbox_exports = {};
2547
+ __export(aio_sandbox_exports, {
2548
+ AioContextOperations: () => AioContextOperations,
2549
+ AioFileOperations: () => AioFileOperations,
2550
+ AioFileSystemOperations: () => AioFileSystemOperations,
2551
+ AioProcessOperations: () => AioProcessOperations,
2552
+ AioSandbox: () => AioSandbox
2553
+ });
2554
+ var AioFileOperations, AioFileSystemOperations, AioProcessOperations, AioContextOperations, AioSandbox;
2555
+ var init_aio_sandbox = __esm({
2556
+ "src/sandbox/aio-sandbox.ts"() {
2557
+ init_log();
2558
+ init_exception();
2559
+ init_aio_data();
2560
+ init_model2();
2561
+ init_sandbox();
2562
+ AioFileOperations = class {
2563
+ sandbox;
2564
+ constructor(sandbox) {
2565
+ this.sandbox = sandbox;
2566
+ }
2567
+ /**
2568
+ * Read a file from the sandbox
2569
+ */
2570
+ read = async (path2) => {
2571
+ return this.sandbox.dataApi.readFile({ path: path2 });
2572
+ };
2573
+ /**
2574
+ * Write a file to the sandbox
2575
+ */
2576
+ write = async (params) => {
2577
+ return this.sandbox.dataApi.writeFile(params);
2578
+ };
2579
+ };
2580
+ AioFileSystemOperations = class {
2581
+ sandbox;
2582
+ constructor(sandbox) {
2583
+ this.sandbox = sandbox;
2584
+ }
2585
+ /**
2586
+ * List directory contents
2587
+ */
2588
+ list = async (params) => {
2589
+ return this.sandbox.dataApi.listDirectory(params);
2590
+ };
2591
+ /**
2592
+ * Move a file or directory
2593
+ */
2594
+ move = async (params) => {
2595
+ return this.sandbox.dataApi.moveFile(params);
2596
+ };
2597
+ /**
2598
+ * Remove a file or directory
2599
+ */
2600
+ remove = async (params) => {
2601
+ return this.sandbox.dataApi.removeFile(params);
2602
+ };
2603
+ /**
2604
+ * Get file or directory statistics
2605
+ */
2606
+ stat = async (params) => {
2607
+ return this.sandbox.dataApi.stat(params);
2608
+ };
2609
+ /**
2610
+ * Create a directory
2611
+ */
2612
+ mkdir = async (params) => {
2613
+ return this.sandbox.dataApi.mkdir(params);
2614
+ };
2615
+ /**
2616
+ * Upload a file to the sandbox
2617
+ */
2618
+ upload = async (params) => {
2619
+ return this.sandbox.dataApi.uploadFile(params);
2620
+ };
2621
+ /**
2622
+ * Download a file from the sandbox
2623
+ */
2624
+ download = async (params) => {
2625
+ return this.sandbox.dataApi.downloadFile(params);
2626
+ };
2627
+ };
2628
+ AioProcessOperations = class {
2629
+ sandbox;
2630
+ constructor(sandbox) {
2631
+ this.sandbox = sandbox;
2632
+ }
2633
+ /**
2634
+ * Execute a command in the sandbox
2635
+ */
2636
+ cmd = async (params) => {
2637
+ return this.sandbox.dataApi.cmd(params);
2638
+ };
2639
+ /**
2640
+ * List all processes
2641
+ */
2642
+ list = async (params) => {
2643
+ return this.sandbox.dataApi.listProcesses(params);
2644
+ };
2645
+ /**
2646
+ * Get a specific process by PID
2647
+ */
2648
+ get = async (params) => {
2649
+ return this.sandbox.dataApi.getProcess(params);
2650
+ };
2651
+ /**
2652
+ * Kill a specific process by PID
2653
+ */
2654
+ kill = async (params) => {
2655
+ return this.sandbox.dataApi.killProcess(params);
2656
+ };
2657
+ };
2658
+ AioContextOperations = class {
2659
+ sandbox;
2660
+ _contextId;
2661
+ _language;
2662
+ _cwd;
2663
+ constructor(sandbox) {
2664
+ this.sandbox = sandbox;
2665
+ }
2666
+ /**
2667
+ * Get the current context ID
2668
+ */
2669
+ get contextId() {
2670
+ return this._contextId;
2671
+ }
2672
+ /**
2673
+ * List all contexts
2674
+ */
2675
+ list = async (params) => {
2676
+ return this.sandbox.dataApi.listContexts(params);
2677
+ };
2678
+ /**
2679
+ * Create a new context and save its ID
2680
+ */
2681
+ create = async (params) => {
2682
+ const language = params?.language || "python" /* PYTHON */;
2683
+ const cwd = params?.cwd || "/home/user";
2684
+ const result = await this.sandbox.dataApi.createContext({
2685
+ language,
2686
+ cwd
2687
+ });
2688
+ if (result?.id && result?.cwd && result?.language) {
2689
+ this._contextId = result.id;
2690
+ this._language = result.language;
2691
+ this._cwd = result.cwd;
2692
+ return this;
2693
+ }
2694
+ throw new ServerError(500, "Failed to create context");
2695
+ };
2696
+ /**
2697
+ * Get a specific context by ID
2698
+ */
2699
+ get = async (params) => {
2700
+ const id = params?.contextId || this._contextId;
2701
+ if (!id) {
2702
+ logger.error("context id is not set");
2703
+ throw new Error("context id is not set");
2704
+ }
2705
+ const result = await this.sandbox.dataApi.getContext({ contextId: id });
2706
+ if (result?.id && result?.cwd && result?.language) {
2707
+ this._contextId = result.id;
2708
+ this._language = result.language;
2709
+ this._cwd = result.cwd;
2710
+ return this;
2711
+ }
2712
+ throw new ServerError(500, "Failed to get context");
2713
+ };
2714
+ /**
2715
+ * Execute code in a context
2716
+ */
2717
+ execute = async (params) => {
2718
+ const { code, timeout = 30 } = params;
2719
+ let { contextId, language } = params;
2720
+ if (!contextId) {
2721
+ contextId = this._contextId;
2722
+ }
2723
+ if (!contextId && !language) {
2724
+ logger.debug("context id is not set, use default language: python");
2725
+ language = "python" /* PYTHON */;
2726
+ }
2727
+ return this.sandbox.dataApi.executeCode({
2728
+ code,
2729
+ contextId,
2730
+ language,
2731
+ timeout
2732
+ });
2733
+ };
2734
+ /**
2735
+ * Delete a context
2736
+ */
2737
+ delete = async (params) => {
2738
+ const id = params?.contextId || this._contextId;
2739
+ if (!id) {
2740
+ throw new Error(
2741
+ "context_id is required. Either pass it as parameter or create a context first."
2742
+ );
2743
+ }
2744
+ const result = await this.sandbox.dataApi.deleteContext({ contextId: id });
2745
+ this._contextId = void 0;
2746
+ return result;
2747
+ };
2748
+ };
2749
+ AioSandbox = class extends Sandbox {
2750
+ static templateType = "AllInOne" /* AIO */;
2751
+ /**
2752
+ * Create an AIO Sandbox from template
2753
+ * 从模板创建 AIO 沙箱 / Create AIO Sandbox from Template
2754
+ */
2755
+ static async createFromTemplate(templateName, options, config2) {
2756
+ const sandbox = await Sandbox.create({
2757
+ input: {
2758
+ templateName,
2759
+ sandboxIdleTimeoutSeconds: options?.sandboxIdleTimeoutSeconds,
2760
+ nasConfig: options?.nasConfig,
2761
+ ossMountConfig: options?.ossMountConfig,
2762
+ polarFsConfig: options?.polarFsConfig
2763
+ },
2764
+ templateType: "AllInOne" /* AIO */,
2765
+ config: config2
2766
+ });
2767
+ return sandbox;
2768
+ }
2769
+ constructor(sandbox, config2) {
2770
+ super(sandbox, config2);
2771
+ }
2772
+ _dataApi;
2773
+ _file;
2774
+ _fileSystem;
2775
+ _context;
2776
+ _process;
2777
+ /**
2778
+ * Get data API client
2779
+ */
2780
+ get dataApi() {
2781
+ if (!this._dataApi) {
2782
+ this._dataApi = new AioDataAPI({
2783
+ sandboxId: this.sandboxId || "",
2784
+ config: this._config
2785
+ });
2786
+ }
2787
+ return this._dataApi;
2788
+ }
2789
+ /**
2790
+ * Access file upload/download operations
2791
+ */
2792
+ get file() {
2793
+ if (!this._file) {
2794
+ this._file = new AioFileOperations(this);
2795
+ }
2796
+ return this._file;
2797
+ }
2798
+ /**
2799
+ * Access file system operations
2800
+ */
2801
+ get fileSystem() {
2802
+ if (!this._fileSystem) {
2803
+ this._fileSystem = new AioFileSystemOperations(this);
2804
+ }
2805
+ return this._fileSystem;
2806
+ }
2807
+ /**
2808
+ * Access context management operations
2809
+ */
2810
+ get context() {
2811
+ if (!this._context) {
2812
+ this._context = new AioContextOperations(this);
2813
+ }
2814
+ return this._context;
2815
+ }
2816
+ /**
2817
+ * Access process management operations
2818
+ */
2819
+ get process() {
2820
+ if (!this._process) {
2821
+ this._process = new AioProcessOperations(this);
2822
+ }
2823
+ return this._process;
2824
+ }
2825
+ /**
2826
+ * Check sandbox health
2827
+ */
2828
+ checkHealth = async (params) => {
2829
+ return this.dataApi.checkHealth({
2830
+ sandboxId: this.sandboxId,
2831
+ config: params?.config
2832
+ });
2833
+ };
2834
+ // ========================================
2835
+ // Browser API Methods
2836
+ // ========================================
2837
+ /**
2838
+ * Get CDP WebSocket URL for browser automation
2839
+ */
2840
+ getCdpUrl(record) {
2841
+ return this.dataApi.getCdpUrl(record);
2842
+ }
2843
+ /**
2844
+ * Get VNC WebSocket URL for live view
2845
+ */
2846
+ getVncUrl(record) {
2847
+ return this.dataApi.getVncUrl(record);
2848
+ }
2849
+ /**
2850
+ * List all browser recordings
2851
+ */
2852
+ listRecordings = async (params) => {
2853
+ return this.dataApi.listRecordings(params);
2854
+ };
2855
+ /**
2856
+ * Download a recording video file
2857
+ */
2858
+ downloadRecording = async (params) => {
2859
+ return this.dataApi.downloadRecording(params);
2860
+ };
2861
+ /**
2862
+ * Delete a recording
2863
+ */
2864
+ deleteRecording = async (params) => {
2865
+ return this.dataApi.deleteRecording(params);
2866
+ };
2867
+ // ========================================
2868
+ // Code Interpreter API Methods
2869
+ // ========================================
2870
+ /**
2871
+ * Execute code (convenience method delegating to context.execute)
2872
+ */
2873
+ execute = async (params) => {
2874
+ return this.context.execute(params);
2875
+ };
2876
+ };
2877
+ }
2878
+ });
2879
+
2880
+ // src/sandbox/template.ts
2881
+ var Template;
2882
+ var init_template = __esm({
2883
+ "src/sandbox/template.ts"() {
2884
+ init_resource();
2885
+ Template = class _Template extends ResourceBase {
2886
+ /**
2887
+ * 模板 ARN / Template ARN
2888
+ */
2889
+ templateArn;
2890
+ /**
2891
+ * 模板 ID / Template ID
2892
+ */
2893
+ templateId;
2894
+ /**
2895
+ * 模板名称 / Template Name
2896
+ */
2897
+ templateName;
2898
+ /**
2899
+ * 模板类型 / Template Type
2900
+ */
2901
+ templateType;
2902
+ /**
2903
+ * CPU 核数 / CPU Cores
2904
+ */
2905
+ cpu;
2906
+ /**
2907
+ * 内存大小(MB) / Memory Size (MB)
2908
+ */
2909
+ memory;
2910
+ /**
2911
+ * 创建时间 / Creation Time
2912
+ */
2913
+ createdAt;
2914
+ /**
2915
+ * 描述 / Description
2916
+ */
2917
+ description;
2918
+ /**
2919
+ * 执行角色 ARN / Execution Role ARN
2920
+ */
2921
+ executionRoleArn;
2922
+ /**
2923
+ * 最后更新时间 / Last Updated Time
2924
+ */
2925
+ lastUpdatedAt;
2926
+ /**
2927
+ * 资源名称 / Resource Name
2928
+ */
2929
+ resourceName;
2930
+ /**
2931
+ * 沙箱空闲超时时间(秒) / Sandbox Idle Timeout (seconds)
2932
+ */
2933
+ sandboxIdleTimeoutInSeconds;
2934
+ /**
2935
+ * 沙箱存活时间(秒) / Sandbox TTL (seconds)
2936
+ */
2937
+ sandboxTtlInSeconds;
2938
+ /**
2939
+ * 每个沙箱的最大并发会话数 / Max Concurrency Limit Per Sandbox
2940
+ */
2941
+ shareConcurrencyLimitPerSandbox;
2942
+ /**
2943
+ * 状态原因 / Status Reason
2944
+ */
2945
+ statusReason;
2946
+ /**
2947
+ * 磁盘大小(GB) / Disk Size (GB)
2948
+ */
2949
+ diskSize;
2950
+ /**
2951
+ * 是否允许匿名管理 / Whether to allow anonymous management
2952
+ */
2953
+ allowAnonymousManage;
2954
+ _config;
2955
+ constructor(data, config2) {
2956
+ super();
2957
+ if (data) {
2958
+ updateObjectProperties(this, data);
2959
+ this.normalizeNumericFields();
2960
+ }
2961
+ this._config = config2;
2962
+ }
2963
+ uniqIdCallback = () => this.templateId;
2964
+ static getClient() {
2965
+ const { SandboxClient: SandboxClient2 } = (init_client(), __toCommonJS(client_exports));
2966
+ return new SandboxClient2();
2967
+ }
2968
+ /**
2969
+ * Create a new Template
2970
+ */
2971
+ static async create(params) {
2972
+ return await _Template.getClient().createTemplate(params);
2973
+ }
2974
+ /**
2975
+ * Delete a Template by name
2976
+ */
2977
+ static async delete(params) {
2978
+ return await _Template.getClient().deleteTemplate(params);
2979
+ }
2980
+ /**
2981
+ * Update a Template by name
2982
+ */
2983
+ static async update(params) {
2984
+ return await _Template.getClient().updateTemplate(params);
2985
+ }
2986
+ /**
2987
+ * Get a Template by name
2988
+ */
2989
+ static async get(params) {
2990
+ return await _Template.getClient().getTemplate(params);
2991
+ }
2992
+ /**
2993
+ * List Templates
2994
+ */
2995
+ static async list(params) {
2996
+ return await _Template.getClient().listTemplates(params);
2997
+ }
2998
+ /**
2999
+ * List all Templates (with pagination)
3000
+ */
3001
+ static listAll = listAllResourcesFunction(this.list);
3002
+ get = async (params = {}) => {
3003
+ return await _Template.get({
3004
+ name: this.templateName,
3005
+ config: params.config
3006
+ });
3007
+ };
3008
+ /**
3009
+ * Delete this template
3010
+ */
3011
+ delete = async (params) => {
3012
+ const config2 = params?.config;
3013
+ if (!this.templateName) {
3014
+ throw new Error("templateName is required to delete a Template");
3015
+ }
3016
+ const result = await _Template.delete({
3017
+ name: this.templateName,
3018
+ config: config2 ?? this._config
3019
+ });
3020
+ updateObjectProperties(this, result);
3021
+ this.normalizeNumericFields();
3022
+ return this;
3023
+ };
3024
+ /**
3025
+ * Update this template
3026
+ */
3027
+ update = async (params) => {
3028
+ const { input, config: config2 } = params;
3029
+ if (!this.templateName) {
3030
+ throw new Error("templateName is required to update a Template");
3031
+ }
3032
+ const result = await _Template.update({
3033
+ name: this.templateName,
3034
+ input,
3035
+ config: config2 ?? this._config
3036
+ });
3037
+ updateObjectProperties(this, result);
3038
+ this.normalizeNumericFields();
3039
+ return this;
3040
+ };
3041
+ /**
3042
+ * Refresh this template's data
3043
+ */
3044
+ refresh = async (params) => {
3045
+ const config2 = params?.config;
3046
+ if (!this.templateName) {
3047
+ throw new Error("templateName is required to refresh a Template");
3048
+ }
3049
+ const result = await _Template.get({
3050
+ name: this.templateName,
3051
+ config: config2 ?? this._config
3052
+ });
3053
+ updateObjectProperties(this, result);
3054
+ this.normalizeNumericFields();
3055
+ return this;
3056
+ };
3057
+ normalizeNumericFields() {
3058
+ const toNumber = (value) => {
3059
+ if (typeof value === "number") return value;
3060
+ if (typeof value === "string") {
3061
+ const parsed = Number(value);
3062
+ return Number.isNaN(parsed) ? void 0 : parsed;
3063
+ }
3064
+ return void 0;
3065
+ };
3066
+ this.sandboxIdleTimeoutInSeconds = toNumber(this.sandboxIdleTimeoutInSeconds);
3067
+ this.sandboxTtlInSeconds = toNumber(this.sandboxTtlInSeconds);
3068
+ this.shareConcurrencyLimitPerSandbox = toNumber(this.shareConcurrencyLimitPerSandbox);
3069
+ this.cpu = toNumber(this.cpu);
3070
+ this.memory = toNumber(this.memory);
3071
+ this.diskSize = toNumber(this.diskSize);
3072
+ }
3073
+ };
3074
+ }
3075
+ });
3076
+
3077
+ // src/sandbox/client.ts
3078
+ var client_exports = {};
3079
+ __export(client_exports, {
3080
+ SandboxClient: () => SandboxClient
3081
+ });
3082
+ var SandboxClient;
3083
+ var init_client = __esm({
3084
+ "src/sandbox/client.ts"() {
3085
+ init_config();
3086
+ init_exception();
3087
+ init_log();
3088
+ init_control();
3089
+ init_aio_sandbox();
3090
+ init_browser_sandbox();
3091
+ init_code_interpreter_sandbox();
3092
+ init_custom_sandbox();
3093
+ init_model2();
3094
+ init_sandbox();
3095
+ init_template();
3096
+ SandboxClient = class {
3097
+ config;
3098
+ controlApi;
3099
+ constructor(config2) {
3100
+ this.config = config2;
3101
+ this.controlApi = new SandboxControlAPI(config2);
3102
+ }
3103
+ // ============ Template Operations ============
3104
+ /**
3105
+ * Create a Template
3106
+ */
3107
+ createTemplate = async (arg1, arg2) => {
3108
+ let input;
3109
+ let config2;
3110
+ if ("input" in arg1) {
3111
+ input = arg1.input;
3112
+ config2 = arg1.config;
3113
+ } else {
3114
+ logger.warn(
3115
+ "Deprecated: createTemplate(input, config) is deprecated. Use createTemplate({ input, config }) instead."
3116
+ );
3117
+ input = arg1;
3118
+ config2 = arg2;
3119
+ }
3120
+ const cfg = Config.withConfigs(this.config, config2);
3121
+ try {
3122
+ const finalInput = this.prepareTemplateCreateInput(input);
3123
+ const result = await this.controlApi.createTemplate({
3124
+ input: new $AgentRun4.CreateTemplateInput({
3125
+ ...finalInput,
3126
+ networkConfiguration: finalInput.networkConfiguration ? new $AgentRun4.NetworkConfiguration({
3127
+ ...finalInput.networkConfiguration
3128
+ }) : void 0
3129
+ }),
3130
+ config: cfg
3131
+ });
3132
+ return new Template(result, cfg);
3133
+ } catch (error) {
3134
+ if (error instanceof HTTPError) {
3135
+ throw error.toResourceError("Template", input.templateName);
3136
+ }
3137
+ throw error;
3138
+ }
3139
+ };
3140
+ /**
3141
+ * Delete a Template
3142
+ */
3143
+ deleteTemplate = async (arg1, arg2) => {
3144
+ let name;
3145
+ let config2;
3146
+ if (typeof arg1 === "string") {
3147
+ logger.warn(
3148
+ "Deprecated: deleteTemplate(name, config) is deprecated. Use deleteTemplate({ name, config }) instead."
3149
+ );
3150
+ name = arg1;
3151
+ config2 = arg2;
3152
+ } else {
3153
+ name = arg1.name;
3154
+ config2 = arg1.config;
3155
+ }
3156
+ const cfg = Config.withConfigs(this.config, config2);
3157
+ try {
3158
+ const result = await this.controlApi.deleteTemplate({
3159
+ templateName: name,
3160
+ config: cfg
3161
+ });
3162
+ return new Template(result, cfg);
3163
+ } catch (error) {
3164
+ if (error instanceof HTTPError) {
3165
+ throw error.toResourceError("Template", name);
3166
+ }
3167
+ throw error;
3168
+ }
3169
+ };
3170
+ /**
3171
+ * Update a Template
3172
+ */
3173
+ updateTemplate = async (arg1, arg2, arg3) => {
3174
+ let name;
3175
+ let input;
3176
+ let config2;
3177
+ if (typeof arg1 === "string") {
3178
+ logger.warn(
3179
+ "Deprecated: updateTemplate(name, input, config) is deprecated. Use updateTemplate({ name, input, config }) instead."
3180
+ );
3181
+ name = arg1;
3182
+ input = arg2;
3183
+ config2 = arg3;
3184
+ } else {
3185
+ name = arg1.name;
3186
+ input = arg1.input;
3187
+ config2 = arg1.config;
3188
+ }
3189
+ const cfg = Config.withConfigs(this.config, config2);
3190
+ try {
3191
+ const result = await this.controlApi.updateTemplate({
3192
+ templateName: name,
3193
+ input: new $AgentRun4.UpdateTemplateInput({
3194
+ ...input,
3195
+ networkConfiguration: input.networkConfiguration ? new $AgentRun4.NetworkConfiguration({
3196
+ ...input.networkConfiguration
3197
+ }) : void 0
3198
+ }),
3199
+ config: cfg
3200
+ });
3201
+ return new Template(result, cfg);
3202
+ } catch (error) {
3203
+ if (error instanceof HTTPError) {
3204
+ throw error.toResourceError("Template", name);
3205
+ }
3206
+ throw error;
3207
+ }
3208
+ };
3209
+ /**
3210
+ * Get a Template
3211
+ */
3212
+ getTemplate = async (arg1, arg2) => {
3213
+ let name;
3214
+ let config2;
3215
+ if (typeof arg1 === "string") {
3216
+ logger.warn(
3217
+ "Deprecated: getTemplate(name, config) is deprecated. Use getTemplate({ name, config }) instead."
3218
+ );
3219
+ name = arg1;
3220
+ config2 = arg2;
3221
+ } else {
3222
+ name = arg1.name;
3223
+ config2 = arg1.config;
3224
+ }
3225
+ const cfg = Config.withConfigs(this.config, config2);
3226
+ try {
3227
+ const result = await this.controlApi.getTemplate({
3228
+ templateName: name,
3229
+ config: cfg
3230
+ });
3231
+ return new Template(result, cfg);
3232
+ } catch (error) {
3233
+ if (error instanceof HTTPError) {
3234
+ throw error.toResourceError("Template", name);
3235
+ }
3236
+ throw error;
3237
+ }
3238
+ };
3239
+ /**
3240
+ * List Templates
3241
+ */
3242
+ listTemplates = async (arg1, arg2) => {
3243
+ let input;
3244
+ let config2;
3245
+ if (arg2 || arg1 && ("pageNumber" in arg1 || "pageSize" in arg1 || "templateType" in arg1)) {
3246
+ logger.warn(
3247
+ "Deprecated: listTemplates(input, config) is deprecated. Use listTemplates({ input, config }) instead."
3248
+ );
3249
+ input = arg1;
3250
+ config2 = arg2;
3251
+ } else {
3252
+ const params = arg1 ?? {};
3253
+ input = params.input;
3254
+ config2 = params.config;
3255
+ }
3256
+ const cfg = Config.withConfigs(this.config, config2);
3257
+ const request = new $AgentRun4.ListTemplatesRequest({
3258
+ ...input
3259
+ });
3260
+ const result = await this.controlApi.listTemplates({
3261
+ input: request,
3262
+ config: cfg
3263
+ });
3264
+ return (result?.items || []).map((item) => new Template(item, cfg));
3265
+ };
3266
+ // ============ Sandbox Operations ============
3267
+ /**
3268
+ * Create a Sandbox
3269
+ */
3270
+ createSandbox = async (arg1, arg2) => {
3271
+ let input;
3272
+ let templateType;
3273
+ let config2;
3274
+ if ("input" in arg1) {
3275
+ const params = arg1;
3276
+ input = params.input;
3277
+ templateType = params.templateType;
3278
+ config2 = params.config;
3279
+ } else {
3280
+ logger.warn(
3281
+ "Deprecated: createSandbox(input, config) is deprecated. Use createSandbox({ input, config }) instead."
3282
+ );
3283
+ input = arg1;
3284
+ config2 = arg2;
3285
+ }
3286
+ const cfg = Config.withConfigs(this.config, config2);
3287
+ try {
3288
+ const result = await this.controlApi.createSandbox({
3289
+ input: new $AgentRun4.CreateSandboxInput({
3290
+ ...input
3291
+ }),
3292
+ config: cfg
3293
+ });
3294
+ const state = result.status ?? result.state;
3295
+ const sb = new Sandbox({ ...result, state }, cfg);
3296
+ if (templateType === "CodeInterpreter" /* CODE_INTERPRETER */)
3297
+ return new CodeInterpreterSandbox(sb, cfg);
3298
+ else if (templateType === "Browser" /* BROWSER */) return new BrowserSandbox(sb, cfg);
3299
+ else if (templateType === "AllInOne" /* AIO */) return new AioSandbox(sb, cfg);
3300
+ else if (templateType === "CustomImage" /* CUSTOM */) return new CustomSandbox(sb, cfg);
3301
+ return sb;
3302
+ } catch (error) {
3303
+ if (error instanceof HTTPError) {
3304
+ throw error.toResourceError("Sandbox", input.templateName);
3305
+ }
3306
+ throw error;
3307
+ }
3308
+ };
3309
+ /**
3310
+ * Create a Code Interpreter Sandbox
3311
+ * 创建代码解释器沙箱 / Create Code Interpreter Sandbox
3312
+ */
3313
+ createCodeInterpreterSandbox = async (params) => {
3314
+ const { templateName, options, config: config2 } = params;
3315
+ return CodeInterpreterSandbox.createFromTemplate(templateName, options, config2 ?? this.config);
3316
+ };
3317
+ /**
3318
+ * Create a Browser Sandbox
3319
+ * 创建浏览器沙箱 / Create Browser Sandbox
3320
+ */
3321
+ createBrowserSandbox = async (params) => {
3322
+ const { templateName, options, config: config2 } = params;
3323
+ return BrowserSandbox.createFromTemplate(templateName, options, config2 ?? this.config);
3324
+ };
3325
+ /**
3326
+ * Delete a Sandbox
3327
+ */
3328
+ deleteSandbox = async (arg1, arg2) => {
3329
+ let id;
3330
+ let config2;
3331
+ if (typeof arg1 === "string") {
3332
+ logger.warn(
3333
+ "Deprecated: deleteSandbox(id, config) is deprecated. Use deleteSandbox({ id, config }) instead."
3334
+ );
3335
+ id = arg1;
3336
+ config2 = arg2;
3337
+ } else {
3338
+ id = arg1.id;
3339
+ config2 = arg1.config;
3340
+ }
3341
+ const cfg = Config.withConfigs(this.config, config2);
3342
+ try {
3343
+ const result = await this.controlApi.deleteSandbox({
3344
+ sandboxId: id,
3345
+ config: cfg
3346
+ });
3347
+ return Sandbox.fromInnerObject(result, cfg);
3348
+ } catch (error) {
3349
+ if (error instanceof HTTPError) {
3350
+ throw error.toResourceError("Sandbox", id);
3351
+ }
3352
+ throw error;
3353
+ }
3354
+ };
3355
+ /**
3356
+ * Stop a Sandbox
3357
+ */
3358
+ stopSandbox = async (arg1, arg2) => {
3359
+ let id;
3360
+ let config2;
3361
+ if (typeof arg1 === "string") {
3362
+ logger.warn(
3363
+ "Deprecated: stopSandbox(id, config) is deprecated. Use stopSandbox({ id, config }) instead."
3364
+ );
3365
+ id = arg1;
3366
+ config2 = arg2;
3367
+ } else {
3368
+ id = arg1.id;
3369
+ config2 = arg1.config;
3370
+ }
3371
+ const cfg = Config.withConfigs(this.config, config2);
3372
+ try {
3373
+ const result = await this.controlApi.stopSandbox({
3374
+ sandboxId: id,
3375
+ config: cfg
3376
+ });
3377
+ return Sandbox.fromInnerObject(result, cfg);
3378
+ } catch (error) {
3379
+ if (error instanceof HTTPError) {
3380
+ throw error.toResourceError("Sandbox", id);
3381
+ }
3382
+ throw error;
3383
+ }
3384
+ };
3385
+ /**
3386
+ * Get a Sandbox
3387
+ *
3388
+ * @param params.id - Sandbox ID
3389
+ * @param params.templateType - Template type to cast the result to the appropriate subclass
3390
+ * @param params.config - Configuration
3391
+ */
3392
+ getSandbox = async (arg1, arg2, arg3) => {
3393
+ let id;
3394
+ let templateType;
3395
+ let config2;
3396
+ if (typeof arg1 === "string") {
3397
+ logger.warn(
3398
+ "Deprecated: getSandbox(id, templateType, config?) is deprecated. Use getSandbox({ id, templateType, config }) instead."
3399
+ );
3400
+ id = arg1;
3401
+ if (arg2 && typeof arg2 === "string") {
3402
+ templateType = arg2;
3403
+ config2 = arg3;
3404
+ } else {
3405
+ config2 = arg2;
3406
+ }
3407
+ } else {
3408
+ id = arg1.id;
3409
+ templateType = arg1.templateType;
3410
+ config2 = arg1.config;
3411
+ }
3412
+ const cfg = Config.withConfigs(this.config, config2);
3413
+ try {
3414
+ const result = await this.controlApi.getSandbox({
3415
+ sandboxId: id,
3416
+ config: cfg
3417
+ });
3418
+ const baseSandbox = Sandbox.fromInnerObject(result, cfg);
3419
+ if (templateType) {
3420
+ switch (templateType) {
3421
+ case "CodeInterpreter" /* CODE_INTERPRETER */: {
3422
+ return new CodeInterpreterSandbox(baseSandbox, cfg);
3423
+ }
3424
+ case "Browser" /* BROWSER */: {
3425
+ return new BrowserSandbox(baseSandbox, cfg);
3426
+ }
3427
+ case "AllInOne" /* AIO */: {
3428
+ const { AioSandbox: AioSandbox2 } = await Promise.resolve().then(() => (init_aio_sandbox(), aio_sandbox_exports));
3429
+ return new AioSandbox2(baseSandbox, cfg);
3430
+ }
3431
+ }
3432
+ }
3433
+ return baseSandbox;
3434
+ } catch (error) {
3435
+ if (error instanceof HTTPError) {
3436
+ throw error.toResourceError("Sandbox", id);
3437
+ }
3438
+ throw error;
3439
+ }
3440
+ };
3441
+ /**
3442
+ * List Sandboxes
3443
+ */
3444
+ listSandboxes = async (arg1, arg2) => {
3445
+ let input;
3446
+ let config2;
3447
+ if (arg2 || arg1 && ("maxResults" in arg1 || "nextToken" in arg1 || "status" in arg1 || "templateName" in arg1 || "templateType" in arg1)) {
3448
+ logger.warn(
3449
+ "Deprecated: listSandboxes(input, config) is deprecated. Use listSandboxes({ input, config }) instead."
3450
+ );
3451
+ input = arg1;
3452
+ config2 = arg2;
3453
+ } else {
3454
+ const params = arg1 ?? {};
3455
+ input = params.input;
3456
+ config2 = params.config;
3457
+ }
3458
+ const cfg = Config.withConfigs(this.config, config2);
3459
+ const request = new $AgentRun4.ListSandboxesRequest({
3460
+ ...input
3461
+ });
3462
+ const result = await this.controlApi.listSandboxes({
3463
+ input: request,
3464
+ config: cfg
3465
+ });
3466
+ return (result.sandboxes || []).map(
3467
+ (item) => Sandbox.fromInnerObject(item, cfg)
3468
+ );
3469
+ };
3470
+ prepareTemplateCreateInput(input) {
3471
+ const defaults = this.getTemplateDefaults(input.templateType);
3472
+ const finalInput = { ...defaults, ...input };
3473
+ if (!finalInput.networkConfiguration) {
3474
+ finalInput.networkConfiguration = {
3475
+ networkMode: "PUBLIC" /* PUBLIC */
3476
+ };
3477
+ }
3478
+ this.validateTemplateCreateInput(finalInput);
3479
+ return finalInput;
3480
+ }
3481
+ getTemplateDefaults(templateType) {
3482
+ const base = {
3483
+ cpu: 2,
3484
+ memory: 4096,
3485
+ sandboxIdleTimeoutInSeconds: 1800,
3486
+ sandboxTtlInSeconds: 21600,
3487
+ shareConcurrencyLimitPerSandbox: 200
3488
+ };
3489
+ switch (templateType) {
3490
+ case "CodeInterpreter" /* CODE_INTERPRETER */:
3491
+ return { ...base, diskSize: 512 };
3492
+ case "Browser" /* BROWSER */:
3493
+ case "AllInOne" /* AIO */:
3494
+ return { ...base, cpu: 4, memory: 8192, diskSize: 10240 };
3495
+ default:
3496
+ return { ...base, diskSize: 512 };
3497
+ }
3498
+ }
3499
+ validateTemplateCreateInput(input) {
3500
+ if ((input.templateType === "Browser" /* BROWSER */ || input.templateType === "AllInOne" /* AIO */) && input.diskSize !== 10240) {
3501
+ throw new Error(
3502
+ `When templateType is BROWSER or AIO, diskSize must be 10240, got ${input.diskSize}`
3503
+ );
3504
+ }
3505
+ if ((input.templateType === "CodeInterpreter" /* CODE_INTERPRETER */ || input.templateType === "AllInOne" /* AIO */) && input.networkConfiguration?.networkMode === "PRIVATE" /* PRIVATE */) {
3506
+ throw new Error(
3507
+ `When templateType is CODE_INTERPRETER or AIO, networkMode cannot be PRIVATE`
3508
+ );
3509
+ }
3510
+ }
3511
+ };
3512
+ }
3513
+ });
3514
+
3515
+ // src/sandbox/index.ts
3516
+ init_version_check();
3517
+ init_client();
3518
+ init_sandbox();
3519
+ init_template();
3520
+ init_code_interpreter_sandbox();
3521
+ init_browser_sandbox();
3522
+ init_aio_sandbox();
3523
+ init_custom_sandbox();
3524
+ init_sandbox_data();
3525
+ init_code_interpreter_data();
3526
+ init_browser_data();
3527
+ init_aio_data();
3528
+ init_model2();
3529
+
3530
+ export { AioDataAPI, AioSandbox, BrowserDataAPI, BrowserSandbox, CodeInterpreterDataAPI, CodeInterpreterSandbox, CodeLanguage, CustomSandbox, Sandbox, SandboxClient, SandboxDataAPI, SandboxState, Template, TemplateNetworkMode, TemplateOSSPermission, TemplateType };
3531
+ //# sourceMappingURL=index.js.map
3532
+ //# sourceMappingURL=index.js.map