@fastgpt-sdk/sandbox-adapter 0.0.29 → 0.0.30

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.
@@ -0,0 +1,826 @@
1
+ import {
2
+ CommandsAdapter,
3
+ ExecutionEventDispatcher,
4
+ FilesystemAdapter,
5
+ HealthAdapter,
6
+ InvalidArgumentException,
7
+ MetricsAdapter,
8
+ SandboxApiException,
9
+ SandboxError,
10
+ SandboxException,
11
+ SandboxInternalException,
12
+ SandboxReadyTimeoutException,
13
+ SandboxUnhealthyException,
14
+ SandboxesAdapter,
15
+ createExecdClient,
16
+ createLifecycleClient,
17
+ throwOnOpenApiFetchError
18
+ } from "./chunk-PHJSF3IJ.js";
19
+
20
+ // src/openapi/egressClient.ts
21
+ import createClient from "openapi-fetch";
22
+ function createEgressClient(opts) {
23
+ const createClientFn = createClient.default ?? createClient;
24
+ return createClientFn({
25
+ baseUrl: opts.baseUrl,
26
+ headers: opts.headers,
27
+ fetch: opts.fetch
28
+ });
29
+ }
30
+
31
+ // src/adapters/egressAdapter.ts
32
+ var EgressAdapter = class {
33
+ constructor(client) {
34
+ this.client = client;
35
+ }
36
+ async getPolicy() {
37
+ const { data, error, response } = await this.client.GET("/policy");
38
+ throwOnOpenApiFetchError({ error, response }, "Get sandbox egress policy failed");
39
+ const raw = data;
40
+ if (!raw || typeof raw !== "object" || !raw.policy || typeof raw.policy !== "object") {
41
+ throw new Error("Get sandbox egress policy failed: unexpected response shape");
42
+ }
43
+ return raw.policy;
44
+ }
45
+ async patchRules(rules) {
46
+ const body = rules;
47
+ const { error, response } = await this.client.PATCH("/policy", {
48
+ body
49
+ });
50
+ throwOnOpenApiFetchError({ error, response }, "Patch sandbox egress rules failed");
51
+ }
52
+ };
53
+
54
+ // src/factory/defaultAdapterFactory.ts
55
+ var DefaultAdapterFactory = class {
56
+ createLifecycleStack(opts) {
57
+ const lifecycleClient = createLifecycleClient({
58
+ baseUrl: opts.lifecycleBaseUrl,
59
+ apiKey: opts.connectionConfig.apiKey,
60
+ headers: opts.connectionConfig.headers,
61
+ fetch: opts.connectionConfig.fetch
62
+ });
63
+ const sandboxes = new SandboxesAdapter(lifecycleClient);
64
+ return { sandboxes };
65
+ }
66
+ createExecdStack(opts) {
67
+ const headers = {
68
+ ...opts.connectionConfig.headers ?? {},
69
+ ...opts.endpointHeaders ?? {}
70
+ };
71
+ const execdClient = createExecdClient({
72
+ baseUrl: opts.execdBaseUrl,
73
+ headers,
74
+ fetch: opts.connectionConfig.fetch
75
+ });
76
+ const health = new HealthAdapter(execdClient);
77
+ const metrics = new MetricsAdapter(execdClient);
78
+ const files = new FilesystemAdapter(execdClient, {
79
+ baseUrl: opts.execdBaseUrl,
80
+ fetch: opts.connectionConfig.fetch,
81
+ headers
82
+ });
83
+ const commands = new CommandsAdapter(execdClient, {
84
+ baseUrl: opts.execdBaseUrl,
85
+ fetch: opts.connectionConfig.sseFetch,
86
+ headers
87
+ });
88
+ return {
89
+ commands,
90
+ files,
91
+ health,
92
+ metrics
93
+ };
94
+ }
95
+ createEgressStack(opts) {
96
+ const headers = {
97
+ ...opts.connectionConfig.headers ?? {},
98
+ ...opts.endpointHeaders ?? {}
99
+ };
100
+ const egressClient = createEgressClient({
101
+ baseUrl: opts.egressBaseUrl,
102
+ headers,
103
+ fetch: opts.connectionConfig.fetch
104
+ });
105
+ return {
106
+ egress: new EgressAdapter(egressClient)
107
+ };
108
+ }
109
+ };
110
+ function createDefaultAdapterFactory() {
111
+ return new DefaultAdapterFactory();
112
+ }
113
+
114
+ // src/core/constants.ts
115
+ var DEFAULT_EXECD_PORT = 44772;
116
+ var DEFAULT_EGRESS_PORT = 18080;
117
+ var DEFAULT_ENTRYPOINT = ["tail", "-f", "/dev/null"];
118
+ var DEFAULT_RESOURCE_LIMITS = {
119
+ cpu: "1",
120
+ memory: "2Gi"
121
+ };
122
+ var DEFAULT_TIMEOUT_SECONDS = 600;
123
+ var DEFAULT_READY_TIMEOUT_SECONDS = 30;
124
+ var DEFAULT_HEALTH_CHECK_POLLING_INTERVAL_MILLIS = 200;
125
+ var DEFAULT_REQUEST_TIMEOUT_SECONDS = 30;
126
+ var DEFAULT_USER_AGENT = "OpenSandbox-JS-SDK/0.1.5";
127
+
128
+ // src/config/connection.ts
129
+ function isNodeRuntime() {
130
+ const p = globalThis?.process;
131
+ return !!p?.versions?.node;
132
+ }
133
+ function redactHeaders(headers) {
134
+ const out = { ...headers };
135
+ for (const k of Object.keys(out)) {
136
+ if (k.toLowerCase() === "open-sandbox-api-key") out[k] = "***";
137
+ }
138
+ return out;
139
+ }
140
+ function readEnv(name) {
141
+ const env = globalThis?.process?.env;
142
+ const v = env?.[name];
143
+ return typeof v === "string" && v.length ? v : void 0;
144
+ }
145
+ function stripTrailingSlashes(s) {
146
+ return s.replace(/\/+$/, "");
147
+ }
148
+ function stripV1Suffix(s) {
149
+ const trimmed = stripTrailingSlashes(s);
150
+ return trimmed.endsWith("/v1") ? trimmed.slice(0, -3) : trimmed;
151
+ }
152
+ var DEFAULT_KEEPALIVE_TIMEOUT_MS = 3e4;
153
+ function normalizeDomainBase(input) {
154
+ if (input.startsWith("http://") || input.startsWith("https://")) {
155
+ const u = new URL(input);
156
+ const proto = u.protocol === "https:" ? "https" : "http";
157
+ const base = `${u.origin}${u.pathname}`;
158
+ return { protocol: proto, domainBase: stripV1Suffix(base) };
159
+ }
160
+ return { domainBase: stripV1Suffix(input) };
161
+ }
162
+ function createNodeFetch() {
163
+ if (!isNodeRuntime()) {
164
+ return {
165
+ fetch,
166
+ close: async () => {
167
+ }
168
+ };
169
+ }
170
+ const baseFetch = fetch;
171
+ let dispatcher;
172
+ let dispatcherPromise = null;
173
+ const nodeFetch = async (input, init) => {
174
+ dispatcherPromise ??= (async () => {
175
+ try {
176
+ const mod = await import("undici");
177
+ const Agent = mod.Agent;
178
+ if (!Agent) {
179
+ return void 0;
180
+ }
181
+ dispatcher = new Agent({
182
+ keepAliveTimeout: DEFAULT_KEEPALIVE_TIMEOUT_MS,
183
+ keepAliveMaxTimeout: DEFAULT_KEEPALIVE_TIMEOUT_MS
184
+ });
185
+ return dispatcher;
186
+ } catch {
187
+ return void 0;
188
+ }
189
+ })();
190
+ if (dispatcherPromise) {
191
+ await dispatcherPromise;
192
+ }
193
+ if (dispatcher) {
194
+ const mergedInit = { ...init ?? {}, dispatcher };
195
+ return baseFetch(input, mergedInit);
196
+ }
197
+ return baseFetch(input, init);
198
+ };
199
+ return {
200
+ fetch: nodeFetch,
201
+ close: async () => {
202
+ if (dispatcherPromise) {
203
+ await dispatcherPromise.catch(() => void 0);
204
+ }
205
+ if (dispatcher && typeof dispatcher === "object" && typeof dispatcher.close === "function") {
206
+ try {
207
+ await dispatcher.close();
208
+ } catch {
209
+ }
210
+ }
211
+ }
212
+ };
213
+ }
214
+ function createTimedFetch(opts) {
215
+ const baseFetch = opts.baseFetch;
216
+ const timeoutSeconds = opts.timeoutSeconds;
217
+ const debug = opts.debug;
218
+ const defaultHeaders = opts.defaultHeaders ?? {};
219
+ const label = opts.label;
220
+ return async (input, init) => {
221
+ const method = init?.method ?? "GET";
222
+ const url = typeof input === "string" ? input : input?.toString?.() ?? String(input);
223
+ const ac = new AbortController();
224
+ const timeoutMs = Math.floor(timeoutSeconds * 1e3);
225
+ const t = Number.isFinite(timeoutMs) && timeoutMs > 0 ? setTimeout(
226
+ () => ac.abort(
227
+ new Error(
228
+ `[${label}] Request timed out (timeoutSeconds=${timeoutSeconds})`
229
+ )
230
+ ),
231
+ timeoutMs
232
+ ) : void 0;
233
+ const onAbort = () => ac.abort(init?.signal?.reason ?? new Error("Aborted"));
234
+ if (init?.signal) {
235
+ if (init.signal.aborted) onAbort();
236
+ else
237
+ init.signal.addEventListener("abort", onAbort, { once: true });
238
+ }
239
+ const mergedInit = {
240
+ ...init,
241
+ signal: ac.signal
242
+ };
243
+ if (debug) {
244
+ const mergedHeaders = {
245
+ ...defaultHeaders,
246
+ ...init?.headers ?? {}
247
+ };
248
+ console.log(
249
+ `[opensandbox:${label}] ->`,
250
+ method,
251
+ url,
252
+ redactHeaders(mergedHeaders)
253
+ );
254
+ }
255
+ try {
256
+ const res = await baseFetch(input, mergedInit);
257
+ if (debug) {
258
+ console.log(`[opensandbox:${label}] <-`, method, url, res.status);
259
+ }
260
+ return res;
261
+ } finally {
262
+ if (t) clearTimeout(t);
263
+ if (init?.signal)
264
+ init.signal.removeEventListener("abort", onAbort);
265
+ }
266
+ };
267
+ }
268
+ var ConnectionConfig = class _ConnectionConfig {
269
+ protocol;
270
+ domain;
271
+ apiKey;
272
+ headers;
273
+ _fetch;
274
+ _sseFetch;
275
+ requestTimeoutSeconds;
276
+ debug;
277
+ userAgent = DEFAULT_USER_AGENT;
278
+ /**
279
+ * Use sandbox server as proxy for endpoint requests (default false).
280
+ */
281
+ useServerProxy;
282
+ _closeTransport;
283
+ _closePromise = null;
284
+ _transportInitialized = false;
285
+ /**
286
+ * Create a connection configuration.
287
+ *
288
+ * Environment variables (optional):
289
+ * - `OPEN_SANDBOX_DOMAIN` (default: `localhost:8080`)
290
+ * - `OPEN_SANDBOX_API_KEY`
291
+ */
292
+ constructor(opts = {}) {
293
+ const envDomain = readEnv("OPEN_SANDBOX_DOMAIN");
294
+ const envApiKey = readEnv("OPEN_SANDBOX_API_KEY");
295
+ const rawDomain = opts.domain ?? envDomain ?? "localhost:8080";
296
+ const normalized = normalizeDomainBase(rawDomain);
297
+ this.protocol = normalized.protocol ?? opts.protocol ?? "http";
298
+ this.domain = normalized.domainBase;
299
+ this.apiKey = opts.apiKey ?? envApiKey;
300
+ this.requestTimeoutSeconds = typeof opts.requestTimeoutSeconds === "number" ? opts.requestTimeoutSeconds : 30;
301
+ this.debug = !!opts.debug;
302
+ this.useServerProxy = !!opts.useServerProxy;
303
+ const headers = { ...opts.headers ?? {} };
304
+ if (this.apiKey && !headers["OPEN-SANDBOX-API-KEY"]) {
305
+ headers["OPEN-SANDBOX-API-KEY"] = this.apiKey;
306
+ }
307
+ if (isNodeRuntime() && this.userAgent && !headers["user-agent"] && !headers["User-Agent"]) {
308
+ headers["user-agent"] = this.userAgent;
309
+ }
310
+ this.headers = headers;
311
+ this._fetch = null;
312
+ this._sseFetch = null;
313
+ this._closeTransport = async () => {
314
+ };
315
+ this._transportInitialized = false;
316
+ }
317
+ get fetch() {
318
+ return this._fetch ?? fetch;
319
+ }
320
+ get sseFetch() {
321
+ return this._sseFetch ?? fetch;
322
+ }
323
+ getBaseUrl() {
324
+ if (this.domain.startsWith("http://") || this.domain.startsWith("https://")) {
325
+ return `${stripV1Suffix(this.domain)}/v1`;
326
+ }
327
+ return `${this.protocol}://${stripV1Suffix(this.domain)}/v1`;
328
+ }
329
+ initializeTransport() {
330
+ if (this._transportInitialized) return;
331
+ const { fetch: baseFetch, close } = createNodeFetch();
332
+ this._fetch = createTimedFetch({
333
+ baseFetch,
334
+ timeoutSeconds: this.requestTimeoutSeconds,
335
+ debug: this.debug,
336
+ defaultHeaders: this.headers,
337
+ label: "http"
338
+ });
339
+ this._sseFetch = createTimedFetch({
340
+ baseFetch,
341
+ timeoutSeconds: 0,
342
+ debug: this.debug,
343
+ defaultHeaders: this.headers,
344
+ label: "sse"
345
+ });
346
+ this._closeTransport = close;
347
+ this._transportInitialized = true;
348
+ }
349
+ /**
350
+ * Ensure this configuration has transport helpers (fetch/SSE) allocated.
351
+ *
352
+ * On Node.js this creates a dedicated `undici` dispatcher; on browsers it
353
+ * simply reuses the global fetch. Returns either `this` or a cloned config
354
+ * with the transport initialized.
355
+ */
356
+ withTransportIfMissing() {
357
+ if (this._transportInitialized) {
358
+ return this;
359
+ }
360
+ const clone = new _ConnectionConfig({
361
+ domain: this.domain,
362
+ protocol: this.protocol,
363
+ apiKey: this.apiKey,
364
+ headers: { ...this.headers },
365
+ requestTimeoutSeconds: this.requestTimeoutSeconds,
366
+ debug: this.debug,
367
+ useServerProxy: this.useServerProxy
368
+ });
369
+ clone.initializeTransport();
370
+ return clone;
371
+ }
372
+ /**
373
+ * Close the Node.js agent owned by this configuration.
374
+ */
375
+ async closeTransport() {
376
+ if (!this._transportInitialized) return;
377
+ this._closePromise ??= this._closeTransport();
378
+ await this._closePromise;
379
+ }
380
+ };
381
+
382
+ // src/manager.ts
383
+ var SandboxManager = class _SandboxManager {
384
+ sandboxes;
385
+ connectionConfig;
386
+ constructor(opts) {
387
+ this.sandboxes = opts.sandboxes;
388
+ this.connectionConfig = opts.connectionConfig;
389
+ }
390
+ static create(opts = {}) {
391
+ const baseConnectionConfig = opts.connectionConfig instanceof ConnectionConfig ? opts.connectionConfig : new ConnectionConfig(opts.connectionConfig);
392
+ const connectionConfig = baseConnectionConfig.withTransportIfMissing();
393
+ const lifecycleBaseUrl = connectionConfig.getBaseUrl();
394
+ const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
395
+ let sandboxes;
396
+ try {
397
+ sandboxes = adapterFactory.createLifecycleStack({
398
+ connectionConfig,
399
+ lifecycleBaseUrl
400
+ }).sandboxes;
401
+ } catch (err) {
402
+ void connectionConfig.closeTransport().catch(() => void 0);
403
+ throw err;
404
+ }
405
+ return new _SandboxManager({ sandboxes, connectionConfig });
406
+ }
407
+ listSandboxInfos(filter = {}) {
408
+ return this.sandboxes.listSandboxes({
409
+ states: filter.states,
410
+ metadata: filter.metadata,
411
+ page: filter.page,
412
+ pageSize: filter.pageSize
413
+ });
414
+ }
415
+ getSandboxInfo(sandboxId) {
416
+ return this.sandboxes.getSandbox(sandboxId);
417
+ }
418
+ killSandbox(sandboxId) {
419
+ return this.sandboxes.deleteSandbox(sandboxId);
420
+ }
421
+ pauseSandbox(sandboxId) {
422
+ return this.sandboxes.pauseSandbox(sandboxId);
423
+ }
424
+ resumeSandbox(sandboxId) {
425
+ return this.sandboxes.resumeSandbox(sandboxId);
426
+ }
427
+ /**
428
+ * Renew expiration by setting expiresAt to now + timeoutSeconds.
429
+ */
430
+ async renewSandbox(sandboxId, timeoutSeconds) {
431
+ const expiresAt = new Date(Date.now() + timeoutSeconds * 1e3).toISOString();
432
+ await this.sandboxes.renewSandboxExpiration(sandboxId, { expiresAt });
433
+ }
434
+ /**
435
+ * Release the HTTP agent resources allocated for this manager instance.
436
+ *
437
+ * Each manager clone owns a scoped `ConnectionConfig` clone.
438
+ *
439
+ * This mirrors the Python SDK's default transport lifecycle.
440
+ */
441
+ async close() {
442
+ await this.connectionConfig.closeTransport();
443
+ }
444
+ };
445
+
446
+ // src/sandbox.ts
447
+ function sleep(ms) {
448
+ return new Promise((r) => setTimeout(r, ms));
449
+ }
450
+ function toImageSpec(image) {
451
+ if (typeof image === "string") return { uri: image };
452
+ return { uri: image.uri, auth: image.auth };
453
+ }
454
+ var Sandbox = class _Sandbox {
455
+ id;
456
+ connectionConfig;
457
+ /**
458
+ * Lifecycle (sandbox management) service.
459
+ */
460
+ sandboxes;
461
+ /**
462
+ * Execd services.
463
+ */
464
+ commands;
465
+ /**
466
+ * High-level filesystem facade (JS-friendly).
467
+ */
468
+ files;
469
+ health;
470
+ metrics;
471
+ /**
472
+ * Internal state kept out of the public instance shape.
473
+ *
474
+ * This avoids nominal typing issues when multiple copies of the SDK exist in a dependency graph.
475
+ */
476
+ static _priv = /* @__PURE__ */ new WeakMap();
477
+ constructor(opts) {
478
+ this.id = opts.id;
479
+ this.connectionConfig = opts.connectionConfig;
480
+ _Sandbox._priv.set(this, {
481
+ adapterFactory: opts.adapterFactory,
482
+ lifecycleBaseUrl: opts.lifecycleBaseUrl,
483
+ execdBaseUrl: opts.execdBaseUrl,
484
+ egress: opts.egress
485
+ });
486
+ this.sandboxes = opts.sandboxes;
487
+ this.commands = opts.commands;
488
+ this.files = opts.files;
489
+ this.health = opts.health;
490
+ this.metrics = opts.metrics;
491
+ }
492
+ static async create(opts) {
493
+ const baseConnectionConfig = opts.connectionConfig instanceof ConnectionConfig ? opts.connectionConfig : new ConnectionConfig(opts.connectionConfig);
494
+ const connectionConfig = baseConnectionConfig.withTransportIfMissing();
495
+ const lifecycleBaseUrl = connectionConfig.getBaseUrl();
496
+ const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
497
+ let sandboxes;
498
+ try {
499
+ sandboxes = adapterFactory.createLifecycleStack({
500
+ connectionConfig,
501
+ lifecycleBaseUrl
502
+ }).sandboxes;
503
+ } catch (err) {
504
+ await connectionConfig.closeTransport();
505
+ throw err;
506
+ }
507
+ if (opts.volumes) {
508
+ for (const vol of opts.volumes) {
509
+ const backendsSpecified = [vol.host, vol.pvc].filter((b) => b !== void 0).length;
510
+ if (backendsSpecified === 0) {
511
+ throw new Error(
512
+ `Volume '${vol.name}' must specify exactly one backend (host, pvc), but none was provided.`
513
+ );
514
+ }
515
+ if (backendsSpecified > 1) {
516
+ throw new Error(
517
+ `Volume '${vol.name}' must specify exactly one backend (host, pvc), but multiple were provided.`
518
+ );
519
+ }
520
+ }
521
+ }
522
+ const rawTimeout = opts.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
523
+ const timeoutSeconds = opts.timeoutSeconds === null ? null : Math.floor(rawTimeout);
524
+ if (timeoutSeconds !== null && !Number.isFinite(timeoutSeconds)) {
525
+ throw new Error(
526
+ `timeoutSeconds must be a finite number, got ${opts.timeoutSeconds}`
527
+ );
528
+ }
529
+ const req = {
530
+ image: toImageSpec(opts.image),
531
+ entrypoint: opts.entrypoint ?? DEFAULT_ENTRYPOINT,
532
+ resourceLimits: opts.resource ?? DEFAULT_RESOURCE_LIMITS,
533
+ env: opts.env ?? {},
534
+ metadata: opts.metadata ?? {},
535
+ networkPolicy: opts.networkPolicy ? {
536
+ ...opts.networkPolicy,
537
+ defaultAction: opts.networkPolicy.defaultAction ?? "deny"
538
+ } : void 0,
539
+ volumes: opts.volumes,
540
+ extensions: opts.extensions ?? {}
541
+ };
542
+ if (timeoutSeconds !== null) {
543
+ req.timeout = timeoutSeconds;
544
+ }
545
+ let sandboxId;
546
+ try {
547
+ const created = await sandboxes.createSandbox(req);
548
+ sandboxId = created.id;
549
+ const endpoint = await sandboxes.getSandboxEndpoint(
550
+ sandboxId,
551
+ DEFAULT_EXECD_PORT,
552
+ connectionConfig.useServerProxy
553
+ );
554
+ const egressEndpoint = await sandboxes.getSandboxEndpoint(
555
+ sandboxId,
556
+ DEFAULT_EGRESS_PORT,
557
+ connectionConfig.useServerProxy
558
+ );
559
+ const execdBaseUrl = `${connectionConfig.protocol}://${endpoint.endpoint}`;
560
+ const egressBaseUrl = `${connectionConfig.protocol}://${egressEndpoint.endpoint}`;
561
+ const { commands, files, health, metrics } = adapterFactory.createExecdStack({
562
+ connectionConfig,
563
+ execdBaseUrl,
564
+ endpointHeaders: endpoint.headers
565
+ });
566
+ const { egress } = adapterFactory.createEgressStack({
567
+ connectionConfig,
568
+ egressBaseUrl,
569
+ endpointHeaders: egressEndpoint.headers
570
+ });
571
+ const sbx = new _Sandbox({
572
+ id: sandboxId,
573
+ connectionConfig,
574
+ adapterFactory,
575
+ lifecycleBaseUrl,
576
+ execdBaseUrl,
577
+ sandboxes,
578
+ commands,
579
+ files,
580
+ health,
581
+ metrics,
582
+ egress
583
+ });
584
+ if (!(opts.skipHealthCheck ?? false)) {
585
+ await sbx.waitUntilReady({
586
+ readyTimeoutSeconds: opts.readyTimeoutSeconds ?? DEFAULT_READY_TIMEOUT_SECONDS,
587
+ pollingIntervalMillis: opts.healthCheckPollingInterval ?? DEFAULT_HEALTH_CHECK_POLLING_INTERVAL_MILLIS,
588
+ healthCheck: opts.healthCheck
589
+ });
590
+ }
591
+ return sbx;
592
+ } catch (err) {
593
+ if (sandboxId) {
594
+ try {
595
+ await sandboxes.deleteSandbox(sandboxId);
596
+ } catch {
597
+ }
598
+ }
599
+ await connectionConfig.closeTransport();
600
+ throw err;
601
+ }
602
+ }
603
+ static async connect(opts) {
604
+ const baseConnectionConfig = opts.connectionConfig instanceof ConnectionConfig ? opts.connectionConfig : new ConnectionConfig(opts.connectionConfig);
605
+ const connectionConfig = baseConnectionConfig.withTransportIfMissing();
606
+ const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
607
+ const lifecycleBaseUrl = connectionConfig.getBaseUrl();
608
+ let sandboxes;
609
+ try {
610
+ sandboxes = adapterFactory.createLifecycleStack({
611
+ connectionConfig,
612
+ lifecycleBaseUrl
613
+ }).sandboxes;
614
+ } catch (err) {
615
+ await connectionConfig.closeTransport();
616
+ throw err;
617
+ }
618
+ try {
619
+ const endpoint = await sandboxes.getSandboxEndpoint(
620
+ opts.sandboxId,
621
+ DEFAULT_EXECD_PORT,
622
+ connectionConfig.useServerProxy
623
+ );
624
+ const egressEndpoint = await sandboxes.getSandboxEndpoint(
625
+ opts.sandboxId,
626
+ DEFAULT_EGRESS_PORT,
627
+ connectionConfig.useServerProxy
628
+ );
629
+ const execdBaseUrl = `${connectionConfig.protocol}://${endpoint.endpoint}`;
630
+ const egressBaseUrl = `${connectionConfig.protocol}://${egressEndpoint.endpoint}`;
631
+ const { commands, files, health, metrics } = adapterFactory.createExecdStack({
632
+ connectionConfig,
633
+ execdBaseUrl,
634
+ endpointHeaders: endpoint.headers
635
+ });
636
+ const { egress } = adapterFactory.createEgressStack({
637
+ connectionConfig,
638
+ egressBaseUrl,
639
+ endpointHeaders: egressEndpoint.headers
640
+ });
641
+ const sbx = new _Sandbox({
642
+ id: opts.sandboxId,
643
+ connectionConfig,
644
+ adapterFactory,
645
+ lifecycleBaseUrl,
646
+ execdBaseUrl,
647
+ sandboxes,
648
+ commands,
649
+ files,
650
+ health,
651
+ metrics,
652
+ egress
653
+ });
654
+ if (!(opts.skipHealthCheck ?? false)) {
655
+ await sbx.waitUntilReady({
656
+ readyTimeoutSeconds: opts.readyTimeoutSeconds ?? DEFAULT_READY_TIMEOUT_SECONDS,
657
+ pollingIntervalMillis: opts.healthCheckPollingInterval ?? DEFAULT_HEALTH_CHECK_POLLING_INTERVAL_MILLIS,
658
+ healthCheck: opts.healthCheck
659
+ });
660
+ }
661
+ return sbx;
662
+ } catch (err) {
663
+ await connectionConfig.closeTransport();
664
+ throw err;
665
+ }
666
+ }
667
+ async getInfo() {
668
+ return await this.sandboxes.getSandbox(this.id);
669
+ }
670
+ async isHealthy() {
671
+ try {
672
+ return await this.health.ping();
673
+ } catch {
674
+ return false;
675
+ }
676
+ }
677
+ async getMetrics() {
678
+ return await this.metrics.getMetrics();
679
+ }
680
+ async pause() {
681
+ await this.sandboxes.pauseSandbox(this.id);
682
+ }
683
+ /**
684
+ * Resume a paused sandbox and return a fresh, connected Sandbox instance.
685
+ *
686
+ * After resume, the execd endpoint may change, so this method returns a new
687
+ * {@link Sandbox} instance with a refreshed execd base URL.
688
+ */
689
+ async resume(opts = {}) {
690
+ await this.sandboxes.resumeSandbox(this.id);
691
+ return await _Sandbox.connect({
692
+ sandboxId: this.id,
693
+ connectionConfig: this.connectionConfig,
694
+ adapterFactory: _Sandbox._priv.get(this).adapterFactory,
695
+ skipHealthCheck: opts.skipHealthCheck ?? false,
696
+ readyTimeoutSeconds: opts.readyTimeoutSeconds,
697
+ healthCheckPollingInterval: opts.healthCheckPollingInterval
698
+ });
699
+ }
700
+ /**
701
+ * Resume a paused sandbox by id, then connect to its execd endpoint.
702
+ */
703
+ static async resume(opts) {
704
+ const baseConnectionConfig = opts.connectionConfig instanceof ConnectionConfig ? opts.connectionConfig : new ConnectionConfig(opts.connectionConfig);
705
+ const adapterFactory = opts.adapterFactory ?? createDefaultAdapterFactory();
706
+ const resumeConnectionConfig = baseConnectionConfig.withTransportIfMissing();
707
+ const lifecycleBaseUrl = resumeConnectionConfig.getBaseUrl();
708
+ let sandboxes;
709
+ try {
710
+ sandboxes = adapterFactory.createLifecycleStack({
711
+ connectionConfig: resumeConnectionConfig,
712
+ lifecycleBaseUrl
713
+ }).sandboxes;
714
+ await sandboxes.resumeSandbox(opts.sandboxId);
715
+ } catch (err) {
716
+ await resumeConnectionConfig.closeTransport();
717
+ throw err;
718
+ }
719
+ await resumeConnectionConfig.closeTransport();
720
+ return await _Sandbox.connect({ ...opts, connectionConfig: baseConnectionConfig, adapterFactory });
721
+ }
722
+ async kill() {
723
+ await this.sandboxes.deleteSandbox(this.id);
724
+ }
725
+ /**
726
+ * Release any client-side resources (e.g. Node.js HTTP agents) owned by this Sandbox instance.
727
+ */
728
+ async close() {
729
+ await this.connectionConfig.closeTransport();
730
+ }
731
+ /**
732
+ * Renew expiration by setting expiresAt to now + timeoutSeconds.
733
+ */
734
+ async renew(timeoutSeconds) {
735
+ const expiresAt = new Date(
736
+ Date.now() + timeoutSeconds * 1e3
737
+ ).toISOString();
738
+ return await this.sandboxes.renewSandboxExpiration(this.id, { expiresAt });
739
+ }
740
+ async getEgressPolicy() {
741
+ return await _Sandbox._priv.get(this).egress.getPolicy();
742
+ }
743
+ async patchEgressRules(rules) {
744
+ await _Sandbox._priv.get(this).egress.patchRules(rules);
745
+ }
746
+ /**
747
+ * Get sandbox endpoint for a port (STRICT: no scheme), e.g. "localhost:44772" or "domain/route/.../44772".
748
+ */
749
+ async getEndpoint(port) {
750
+ return await this.sandboxes.getSandboxEndpoint(
751
+ this.id,
752
+ port,
753
+ this.connectionConfig.useServerProxy
754
+ );
755
+ }
756
+ /**
757
+ * Get absolute endpoint URL with scheme (convenience for HTTP clients).
758
+ */
759
+ async getEndpointUrl(port) {
760
+ const ep = await this.getEndpoint(port);
761
+ return `${this.connectionConfig.protocol}://${ep.endpoint}`;
762
+ }
763
+ async waitUntilReady(opts) {
764
+ const deadline = Date.now() + opts.readyTimeoutSeconds * 1e3;
765
+ let attempt = 0;
766
+ let errorDetail = "Health check returned false continuously.";
767
+ const buildTimeoutMessage = () => {
768
+ const context = `domain=${this.connectionConfig.domain}, useServerProxy=${this.connectionConfig.useServerProxy}`;
769
+ let suggestion = "If this sandbox runs in Docker bridge or remote-network mode, consider enabling useServerProxy=true.";
770
+ if (!this.connectionConfig.useServerProxy) {
771
+ suggestion += " You can also configure server-side [docker].host_ip for direct endpoint access.";
772
+ }
773
+ return `Sandbox health check timed out after ${opts.readyTimeoutSeconds}s (${attempt} attempts). ${errorDetail} Connection context: ${context}. ${suggestion}`;
774
+ };
775
+ while (true) {
776
+ if (Date.now() > deadline) {
777
+ throw new SandboxReadyTimeoutException({
778
+ message: buildTimeoutMessage()
779
+ });
780
+ }
781
+ attempt++;
782
+ try {
783
+ if (opts.healthCheck) {
784
+ const ok = await opts.healthCheck(this);
785
+ if (ok) {
786
+ return;
787
+ }
788
+ } else {
789
+ const ok = await this.health.ping();
790
+ if (ok) {
791
+ return;
792
+ }
793
+ }
794
+ errorDetail = "Health check returned false continuously.";
795
+ } catch (err) {
796
+ const message = err instanceof Error ? err.message : String(err);
797
+ errorDetail = `Last health check error: ${message}`;
798
+ }
799
+ await sleep(opts.pollingIntervalMillis);
800
+ }
801
+ }
802
+ };
803
+ export {
804
+ ConnectionConfig,
805
+ DEFAULT_EGRESS_PORT,
806
+ DEFAULT_ENTRYPOINT,
807
+ DEFAULT_EXECD_PORT,
808
+ DEFAULT_HEALTH_CHECK_POLLING_INTERVAL_MILLIS,
809
+ DEFAULT_READY_TIMEOUT_SECONDS,
810
+ DEFAULT_REQUEST_TIMEOUT_SECONDS,
811
+ DEFAULT_RESOURCE_LIMITS,
812
+ DEFAULT_TIMEOUT_SECONDS,
813
+ DefaultAdapterFactory,
814
+ ExecutionEventDispatcher,
815
+ InvalidArgumentException,
816
+ Sandbox,
817
+ SandboxApiException,
818
+ SandboxError,
819
+ SandboxException,
820
+ SandboxInternalException,
821
+ SandboxManager,
822
+ SandboxReadyTimeoutException,
823
+ SandboxUnhealthyException,
824
+ createDefaultAdapterFactory
825
+ };
826
+ //# sourceMappingURL=index.js.map