@ai-sdk/sandbox-vercel 1.0.124 → 1.0.126

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.
package/dist/index.js CHANGED
@@ -1,17 +1,5 @@
1
- var __typeError = (msg) => {
2
- throw TypeError(msg);
3
- };
4
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
-
10
- // src/vercel-sandbox.ts
11
- import {
12
- HarnessSandboxAuthenticationError
13
- } from "@ai-sdk/harness";
14
- import { Sandbox } from "@vercel/sandbox";
1
+ // src/vercel-legacy-sandbox-provider.ts
2
+ import { Sandbox as Sandbox2 } from "@vercel/sandbox";
15
3
 
16
4
  // src/vercel-network-sandbox-session.ts
17
5
  import {
@@ -23,36 +11,33 @@ import {
23
11
  HarnessCapabilityUnsupportedError
24
12
  } from "@ai-sdk/harness";
25
13
  var VERCEL_PROVIDER_ID = "vercel-sandbox";
26
- var _sandbox, _state, _mutationQueue, _VercelNetworkPolicyManager_instances, enqueueMutation_fn, inspectPolicy_fn, applyState_fn;
27
14
  var VercelNetworkPolicyManager = class {
15
+ #sandbox;
16
+ #state;
17
+ #mutationQueue = Promise.resolve();
28
18
  constructor({ sandbox }) {
29
- __privateAdd(this, _VercelNetworkPolicyManager_instances);
30
- __privateAdd(this, _sandbox);
31
- __privateAdd(this, _state);
32
- __privateAdd(this, _mutationQueue, Promise.resolve());
33
- __privateSet(this, _sandbox, sandbox);
19
+ this.#sandbox = sandbox;
34
20
  }
35
21
  setNetworkPolicy(policy) {
36
- return __privateMethod(this, _VercelNetworkPolicyManager_instances, enqueueMutation_fn).call(this, async () => {
37
- var _a, _b;
38
- const inspection = __privateMethod(this, _VercelNetworkPolicyManager_instances, inspectPolicy_fn).call(this);
39
- if (__privateGet(this, _state) == null && inspection.requestTransformationHosts.length > 0) {
22
+ return this.#enqueueMutation(async () => {
23
+ const inspection = this.#inspectPolicy();
24
+ if (this.#state == null && inspection.requestTransformationHosts.length > 0) {
40
25
  throw createPolicyConflictError(
41
26
  "Cannot set the network policy because the current Vercel Sandbox policy contains request transformations whose redacted values cannot be preserved safely. Replace them explicitly with setRequestTransformations() or rehydrate them with addRequestTransformations() first."
42
27
  );
43
28
  }
44
- await __privateMethod(this, _VercelNetworkPolicyManager_instances, applyState_fn).call(this, {
29
+ await this.#applyState({
45
30
  accessPolicy: toNetworkAccessPolicy(policy),
46
- requestTransformations: (_b = (_a = __privateGet(this, _state)) == null ? void 0 : _a.requestTransformations.map(cloneRequestTransformation)) != null ? _b : [],
31
+ requestTransformations: this.#state?.requestTransformations.map(cloneRequestTransformation) ?? [],
47
32
  forwardRules: inspection.forwardRules.map(cloneForwardRule),
48
33
  currentPolicy: inspection.currentPolicy
49
34
  });
50
35
  });
51
36
  }
52
37
  setRequestTransformations(transformations) {
53
- return __privateMethod(this, _VercelNetworkPolicyManager_instances, enqueueMutation_fn).call(this, async () => {
54
- const inspection = __privateMethod(this, _VercelNetworkPolicyManager_instances, inspectPolicy_fn).call(this);
55
- await __privateMethod(this, _VercelNetworkPolicyManager_instances, applyState_fn).call(this, {
38
+ return this.#enqueueMutation(async () => {
39
+ const inspection = this.#inspectPolicy();
40
+ await this.#applyState({
56
41
  accessPolicy: inspection.accessPolicy,
57
42
  requestTransformations: transformations.map(cloneRequestTransformation),
58
43
  forwardRules: inspection.forwardRules.map(cloneForwardRule),
@@ -61,12 +46,12 @@ var VercelNetworkPolicyManager = class {
61
46
  });
62
47
  }
63
48
  addRequestTransformations(transformations) {
64
- return __privateMethod(this, _VercelNetworkPolicyManager_instances, enqueueMutation_fn).call(this, async () => {
65
- const inspection = __privateMethod(this, _VercelNetworkPolicyManager_instances, inspectPolicy_fn).call(this);
49
+ return this.#enqueueMutation(async () => {
50
+ const inspection = this.#inspectPolicy();
66
51
  const incomingTransformations = transformations.map(
67
52
  cloneRequestTransformation
68
53
  );
69
- if (__privateGet(this, _state) == null) {
54
+ if (this.#state == null) {
70
55
  const incomingPolicy = composeNetworkPolicy({
71
56
  accessPolicy: inspection.accessPolicy,
72
57
  requestTransformations: incomingTransformations,
@@ -82,10 +67,10 @@ var VercelNetworkPolicyManager = class {
82
67
  );
83
68
  }
84
69
  }
85
- await __privateMethod(this, _VercelNetworkPolicyManager_instances, applyState_fn).call(this, {
70
+ await this.#applyState({
86
71
  accessPolicy: inspection.accessPolicy,
87
- requestTransformations: __privateGet(this, _state) == null ? incomingTransformations : mergeRequestTransformations({
88
- existing: __privateGet(this, _state).requestTransformations,
72
+ requestTransformations: this.#state == null ? incomingTransformations : mergeRequestTransformations({
73
+ existing: this.#state.requestTransformations,
89
74
  incoming: incomingTransformations
90
75
  }),
91
76
  forwardRules: inspection.forwardRules.map(cloneForwardRule),
@@ -93,61 +78,55 @@ var VercelNetworkPolicyManager = class {
93
78
  });
94
79
  });
95
80
  }
96
- };
97
- _sandbox = new WeakMap();
98
- _state = new WeakMap();
99
- _mutationQueue = new WeakMap();
100
- _VercelNetworkPolicyManager_instances = new WeakSet();
101
- enqueueMutation_fn = function(operation) {
102
- const result = __privateGet(this, _mutationQueue).then(operation);
103
- __privateSet(this, _mutationQueue, result.then(
104
- () => void 0,
105
- () => void 0
106
- ));
107
- return result;
108
- };
109
- inspectPolicy_fn = function() {
110
- var _a;
111
- if (__privateGet(this, _state) != null) {
112
- return {
113
- accessPolicy: __privateGet(this, _state).accessPolicy,
114
- forwardRules: __privateGet(this, _state).forwardRules,
115
- requestTransformationHosts: [],
116
- currentPolicy: __privateGet(this, _state).effectivePolicy
117
- };
81
+ #enqueueMutation(operation) {
82
+ const result = this.#mutationQueue.then(operation);
83
+ this.#mutationQueue = result.then(
84
+ () => void 0,
85
+ () => void 0
86
+ );
87
+ return result;
118
88
  }
119
- return inspectCurrentPolicy(
120
- (_a = __privateGet(this, _sandbox).currentSession().networkPolicy) != null ? _a : "allow-all"
121
- );
122
- };
123
- applyState_fn = async function({
124
- accessPolicy,
125
- requestTransformations,
126
- forwardRules,
127
- currentPolicy
128
- }) {
129
- const effectivePolicy = composeNetworkPolicy({
89
+ #inspectPolicy() {
90
+ if (this.#state != null) {
91
+ return {
92
+ accessPolicy: this.#state.accessPolicy,
93
+ forwardRules: this.#state.forwardRules,
94
+ requestTransformationHosts: [],
95
+ currentPolicy: this.#state.effectivePolicy
96
+ };
97
+ }
98
+ return inspectCurrentPolicy(
99
+ this.#sandbox.currentSession().networkPolicy ?? "allow-all"
100
+ );
101
+ }
102
+ async #applyState({
130
103
  accessPolicy,
131
104
  requestTransformations,
132
- forwardRules
133
- });
134
- if (!areNetworkPoliciesEqual({
135
- first: currentPolicy,
136
- second: effectivePolicy
137
- })) {
138
- await __privateGet(this, _sandbox).update({ networkPolicy: effectivePolicy });
105
+ forwardRules,
106
+ currentPolicy
107
+ }) {
108
+ const effectivePolicy = composeNetworkPolicy({
109
+ accessPolicy,
110
+ requestTransformations,
111
+ forwardRules
112
+ });
113
+ if (!areNetworkPoliciesEqual({
114
+ first: currentPolicy,
115
+ second: effectivePolicy
116
+ })) {
117
+ await this.#sandbox.update({ networkPolicy: effectivePolicy });
118
+ }
119
+ this.#state = {
120
+ accessPolicy: cloneNetworkAccessPolicy(accessPolicy),
121
+ requestTransformations: requestTransformations.map(
122
+ cloneRequestTransformation
123
+ ),
124
+ forwardRules: forwardRules.map(cloneForwardRule),
125
+ effectivePolicy
126
+ };
139
127
  }
140
- __privateSet(this, _state, {
141
- accessPolicy: cloneNetworkAccessPolicy(accessPolicy),
142
- requestTransformations: requestTransformations.map(
143
- cloneRequestTransformation
144
- ),
145
- forwardRules: forwardRules.map(cloneForwardRule),
146
- effectivePolicy
147
- });
148
128
  };
149
129
  function inspectCurrentPolicy(policy) {
150
- var _a, _b, _c, _d, _e;
151
130
  if (policy === "allow-all" || policy === "deny-all") {
152
131
  return {
153
132
  accessPolicy: { mode: policy },
@@ -156,7 +135,7 @@ function inspectCurrentPolicy(policy) {
156
135
  currentPolicy: policy
157
136
  };
158
137
  }
159
- const allowedHosts = Array.isArray(policy.allow) ? [...policy.allow] : Object.keys((_a = policy.allow) != null ? _a : {});
138
+ const allowedHosts = Array.isArray(policy.allow) ? [...policy.allow] : Object.keys(policy.allow ?? {});
160
139
  const forwardRules = [];
161
140
  const requestTransformationHosts = /* @__PURE__ */ new Set();
162
141
  if (policy.allow != null && !Array.isArray(policy.allow)) {
@@ -179,8 +158,8 @@ function inspectCurrentPolicy(policy) {
179
158
  accessPolicy: {
180
159
  mode: "custom",
181
160
  allowedHosts: minimizeHostPatterns(allowedHosts),
182
- allowedCIDRs: [...(_c = (_b = policy.subnets) == null ? void 0 : _b.allow) != null ? _c : []],
183
- deniedCIDRs: [...(_e = (_d = policy.subnets) == null ? void 0 : _d.deny) != null ? _e : []]
161
+ allowedCIDRs: [...policy.subnets?.allow ?? []],
162
+ deniedCIDRs: [...policy.subnets?.deny ?? []]
184
163
  },
185
164
  forwardRules,
186
165
  requestTransformationHosts: [...requestTransformationHosts],
@@ -188,16 +167,15 @@ function inspectCurrentPolicy(policy) {
188
167
  };
189
168
  }
190
169
  function toNetworkAccessPolicy(policy) {
191
- var _a, _b, _c;
192
170
  switch (policy.mode) {
193
171
  case "allow-all":
194
172
  return { mode: "allow-all" };
195
173
  case "deny-all":
196
174
  return { mode: "deny-all" };
197
175
  case "custom": {
198
- const allowedHosts = [...(_a = policy.allowedHosts) != null ? _a : []];
199
- const allowedCIDRs = [...(_b = policy.allowedCIDRs) != null ? _b : []];
200
- const deniedCIDRs = [...(_c = policy.deniedCIDRs) != null ? _c : []];
176
+ const allowedHosts = [...policy.allowedHosts ?? []];
177
+ const allowedCIDRs = [...policy.allowedCIDRs ?? []];
178
+ const deniedCIDRs = [...policy.deniedCIDRs ?? []];
201
179
  if (allowedHosts.length === 0 && allowedCIDRs.length === 0 && deniedCIDRs.length === 0) {
202
180
  throw createPolicyConflictError(
203
181
  "Custom network policy requires at least one of allowedHosts, allowedCIDRs, or deniedCIDRs to be non-empty."
@@ -336,8 +314,7 @@ function appendRule({
336
314
  host,
337
315
  rule
338
316
  }) {
339
- var _a;
340
- const rules = (_a = rulesByHost.get(host)) != null ? _a : [];
317
+ const rules = rulesByHost.get(host) ?? [];
341
318
  rules.push(rule);
342
319
  rulesByHost.set(host, rules);
343
320
  }
@@ -361,10 +338,9 @@ function toVercelRequestTransformationRule(transformation) {
361
338
  };
362
339
  }
363
340
  function hasRequestTransformation(rule) {
364
- var _a, _b;
365
- return (_b = (_a = rule.transform) == null ? void 0 : _a.some(
341
+ return rule.transform?.some(
366
342
  (transformation) => transformation.headers != null && Object.keys(transformation.headers).length > 0
367
- )) != null ? _b : false;
343
+ ) ?? false;
368
344
  }
369
345
  function getRequestTransformationHosts(policy) {
370
346
  if (policy === "allow-all" || policy === "deny-all" || policy.allow == null || Array.isArray(policy.allow)) {
@@ -535,7 +511,7 @@ var VercelSandboxSession = class {
535
511
  env,
536
512
  abortSignal
537
513
  }) {
538
- abortSignal == null ? void 0 : abortSignal.throwIfAborted();
514
+ abortSignal?.throwIfAborted();
539
515
  const finished = await this.sandbox.runCommand({
540
516
  cmd: "bash",
541
517
  args: ["-c", command],
@@ -559,7 +535,7 @@ var VercelSandboxSession = class {
559
535
  env,
560
536
  abortSignal
561
537
  }) {
562
- abortSignal == null ? void 0 : abortSignal.throwIfAborted();
538
+ abortSignal?.throwIfAborted();
563
539
  const live = await this.sandbox.runCommand({
564
540
  cmd: "bash",
565
541
  args: ["-c", command],
@@ -582,7 +558,7 @@ var VercelSandboxSession = class {
582
558
  path,
583
559
  abortSignal
584
560
  }) {
585
- abortSignal == null ? void 0 : abortSignal.throwIfAborted();
561
+ abortSignal?.throwIfAborted();
586
562
  try {
587
563
  const buffer = await this.sandbox.readFileToBuffer(
588
564
  { path },
@@ -624,7 +600,7 @@ var VercelSandboxSession = class {
624
600
  content,
625
601
  abortSignal
626
602
  }) {
627
- abortSignal == null ? void 0 : abortSignal.throwIfAborted();
603
+ abortSignal?.throwIfAborted();
628
604
  const parent = posix.dirname(path);
629
605
  if (parent && parent !== "." && parent !== "/") {
630
606
  await this.sandbox.runCommand({
@@ -670,29 +646,27 @@ function createSandboxProcess(command, abortSignal) {
670
646
  }
671
647
  });
672
648
  const drained = (async () => {
673
- var _a, _b, _c, _d;
674
649
  try {
675
650
  const iterator = abortSignal ? command.logs({ signal: abortSignal }) : command.logs();
676
651
  for await (const message of iterator) {
677
652
  const target = message.stream === "stdout" ? controllers.stdout : controllers.stderr;
678
- target == null ? void 0 : target.enqueue(encoder.encode(message.data));
653
+ target?.enqueue(encoder.encode(message.data));
679
654
  }
680
- (_a = controllers.stdout) == null ? void 0 : _a.close();
681
- (_b = controllers.stderr) == null ? void 0 : _b.close();
655
+ controllers.stdout?.close();
656
+ controllers.stderr?.close();
682
657
  } catch (error) {
683
- (_c = controllers.stdout) == null ? void 0 : _c.error(error);
684
- (_d = controllers.stderr) == null ? void 0 : _d.error(error);
658
+ controllers.stdout?.error(error);
659
+ controllers.stderr?.error(error);
685
660
  }
686
661
  })();
687
662
  return {
688
663
  stdout,
689
664
  stderr,
690
665
  async wait() {
691
- var _a;
692
666
  const finished = await command.wait();
693
667
  await drained;
694
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
695
- throw (_a = abortSignal.reason) != null ? _a : new DOMException("Aborted", "AbortError");
668
+ if (abortSignal?.aborted) {
669
+ throw abortSignal.reason ?? new DOMException("Aborted", "AbortError");
696
670
  }
697
671
  return { exitCode: finished.exitCode };
698
672
  },
@@ -739,13 +713,10 @@ function isFileNotFoundError(error) {
739
713
 
740
714
  // src/vercel-network-sandbox-session.ts
741
715
  var VERCEL_PROVIDER_ID2 = "vercel-sandbox";
742
- var _networkPolicyManager;
743
716
  var VercelNetworkSandboxSession = class extends VercelSandboxSession {
744
717
  constructor(input) {
745
718
  super(input.sandbox);
746
- __privateAdd(this, _networkPolicyManager);
747
719
  this.getPortEndpoint = async (options) => {
748
- var _a;
749
720
  const exposedPorts = this.ports;
750
721
  if (!exposedPorts.includes(options.port)) {
751
722
  throw new HarnessCapabilityUnsupportedError2({
@@ -753,7 +724,7 @@ var VercelNetworkSandboxSession = class extends VercelSandboxSession {
753
724
  message: `Port ${options.port} is not exposed on this sandbox. Exposed ports: [${exposedPorts.join(", ")}].`
754
725
  });
755
726
  }
756
- const protocol = (_a = options.protocol) != null ? _a : "https";
727
+ const protocol = options.protocol ?? "https";
757
728
  const url = new URL(this.sandbox.domain(options.port));
758
729
  const isSecure = url.protocol === "https:";
759
730
  switch (protocol) {
@@ -776,18 +747,18 @@ var VercelNetworkSandboxSession = class extends VercelSandboxSession {
776
747
  return (await this.getPortEndpoint(options)).url;
777
748
  };
778
749
  this.setNetworkPolicy = async (policy) => {
779
- await __privateGet(this, _networkPolicyManager).setNetworkPolicy(policy);
750
+ await this.#networkPolicyManager.setNetworkPolicy(policy);
780
751
  };
781
752
  this.setRequestTransformations = async (transformations) => {
782
- await __privateGet(this, _networkPolicyManager).setRequestTransformations(transformations);
753
+ await this.#networkPolicyManager.setRequestTransformations(transformations);
783
754
  };
784
755
  this.addRequestTransformations = async (transformations) => {
785
- await __privateGet(this, _networkPolicyManager).addRequestTransformations(transformations);
756
+ await this.#networkPolicyManager.addRequestTransformations(transformations);
786
757
  };
787
758
  this.setPorts = async (ports, options) => {
788
759
  await this.sandbox.update(
789
760
  { ports: [...ports] },
790
- (options == null ? void 0 : options.abortSignal) ? { signal: options.abortSignal } : void 0
761
+ options?.abortSignal ? { signal: options.abortSignal } : void 0
791
762
  );
792
763
  };
793
764
  this.stop = async () => {
@@ -803,10 +774,11 @@ var VercelNetworkSandboxSession = class extends VercelSandboxSession {
803
774
  this.ownsLifecycle = input.ownsLifecycle;
804
775
  this.id = input.sandbox.name;
805
776
  this.defaultWorkingDirectory = input.sandbox.currentSession().cwd;
806
- __privateSet(this, _networkPolicyManager, new VercelNetworkPolicyManager({
777
+ this.#networkPolicyManager = new VercelNetworkPolicyManager({
807
778
  sandbox: input.sandbox
808
- }));
779
+ });
809
780
  }
781
+ #networkPolicyManager;
810
782
  get ports() {
811
783
  return this.sandbox.routes.map((route) => route.port);
812
784
  }
@@ -814,154 +786,15 @@ var VercelNetworkSandboxSession = class extends VercelSandboxSession {
814
786
  return new VercelSandboxSession(this.sandbox);
815
787
  }
816
788
  };
817
- _networkPolicyManager = new WeakMap();
818
789
 
819
- // src/vercel-sandbox.ts
790
+ // src/utils.ts
791
+ import { HarnessSandboxAuthenticationError } from "@ai-sdk/harness";
792
+ import { Sandbox } from "@vercel/sandbox";
793
+ var VERCEL_PROVIDER_ID3 = "vercel-sandbox";
820
794
  var DEFAULT_SANDBOX_TIMEOUT_MS = 30 * 60 * 1e3;
821
795
  var DEFAULT_SANDBOX_RUNTIME = "node24";
822
- var VERCEL_PROVIDER_ID3 = "vercel-sandbox";
823
- var TEMPLATE_NAME_PREFIX = "ai-sdk-harness";
824
- var SESSION_NAME_PREFIX = "ai-sdk-harness-session";
825
796
  var SNAPSHOT_POLL_INTERVAL_MS = 500;
826
797
  var SNAPSHOT_POLL_TIMEOUT_MS = 3e4;
827
- function sessionSandboxName(sessionId) {
828
- return `${SESSION_NAME_PREFIX}-${sessionId}`;
829
- }
830
- function hasExplicitSandboxEnvironment(params) {
831
- return "runtime" in params && params.runtime != null || "image" in params && params.image != null || "source" in params && typeof params.source === "object" && params.source != null && "type" in params.source && params.source.type === "snapshot";
832
- }
833
- function createVercelSandbox(settings = {}) {
834
- return new VercelSandboxProvider(settings);
835
- }
836
- var VercelSandboxProvider = class {
837
- constructor(settings) {
838
- this.settings = settings;
839
- this.specificationVersion = "harness-sandbox-v1";
840
- this.providerId = VERCEL_PROVIDER_ID3;
841
- this.createSession = async (options) => {
842
- var _a, _b, _c;
843
- (_a = options == null ? void 0 : options.abortSignal) == null ? void 0 : _a.throwIfAborted();
844
- if ("sandbox" in this.settings && this.settings.sandbox != null) {
845
- return new VercelNetworkSandboxSession({
846
- sandbox: this.settings.sandbox,
847
- ownsLifecycle: false
848
- });
849
- }
850
- const settings = this.settings;
851
- const {
852
- sandbox: _ignoredSandbox,
853
- name: explicitName,
854
- ...createParams
855
- } = settings;
856
- const baseParams = {
857
- ...hasExplicitSandboxEnvironment(createParams) ? {} : { runtime: DEFAULT_SANDBOX_RUNTIME },
858
- ...createParams,
859
- timeout: (_b = createParams.timeout) != null ? _b : DEFAULT_SANDBOX_TIMEOUT_MS
860
- };
861
- const identity = options == null ? void 0 : options.identity;
862
- const onFirstCreate = options == null ? void 0 : options.onFirstCreate;
863
- const sessionNameOverride = (options == null ? void 0 : options.sessionId) ? { name: sessionSandboxName(options.sessionId) } : {};
864
- if (identity == null || onFirstCreate == null) {
865
- const sandbox = await withVercelSandboxAuthenticationError({
866
- settings: this.settings,
867
- operation: () => Sandbox.create({
868
- ...baseParams,
869
- ...sessionNameOverride,
870
- ...(options == null ? void 0 : options.abortSignal) ? { signal: options.abortSignal } : {}
871
- })
872
- });
873
- return new VercelNetworkSandboxSession({ sandbox, ownsLifecycle: true });
874
- }
875
- const templateName = explicitName != null ? explicitName : `${TEMPLATE_NAME_PREFIX}-${identity}`;
876
- const cache = getSnapshotCache();
877
- let snapshotId = cache.get(templateName);
878
- if (snapshotId == null) {
879
- const template = await withVercelSandboxAuthenticationError({
880
- settings: this.settings,
881
- operation: () => {
882
- var _a2;
883
- return Sandbox.getOrCreate({
884
- ...baseParams,
885
- name: templateName,
886
- persistent: true,
887
- snapshotExpiration: (_a2 = baseParams.snapshotExpiration) != null ? _a2 : 0,
888
- onCreate: async (sbx) => {
889
- await onFirstCreate(new VercelSandboxSession(sbx), {
890
- abortSignal: options == null ? void 0 : options.abortSignal
891
- });
892
- },
893
- ...(options == null ? void 0 : options.abortSignal) ? { signal: options.abortSignal } : {}
894
- });
895
- }
896
- });
897
- let resolvedId = template.currentSnapshotId;
898
- if (resolvedId == null) {
899
- const stopResult = await withVercelSandboxAuthenticationError({
900
- settings: this.settings,
901
- operation: () => template.stop(
902
- (options == null ? void 0 : options.abortSignal) ? { signal: options.abortSignal } : void 0
903
- )
904
- });
905
- resolvedId = (_c = stopResult.snapshot) == null ? void 0 : _c.id;
906
- if (resolvedId == null) {
907
- resolvedId = await withVercelSandboxAuthenticationError({
908
- settings: this.settings,
909
- operation: () => pollForTemplateSnapshot({
910
- name: templateName,
911
- lookupParams: getSandboxLookupParams(baseParams),
912
- abortSignal: options == null ? void 0 : options.abortSignal
913
- })
914
- });
915
- }
916
- }
917
- cache.set(templateName, resolvedId);
918
- snapshotId = resolvedId;
919
- }
920
- const {
921
- runtime: _ignoredRuntime,
922
- image: _ignoredImage,
923
- source: _ignoredSource,
924
- persistent: _ignoredPersistent,
925
- ...forkParams
926
- } = baseParams;
927
- const fork = await withVercelSandboxAuthenticationError({
928
- settings: this.settings,
929
- operation: () => Sandbox.create({
930
- ...forkParams,
931
- source: { type: "snapshot", snapshotId },
932
- ...sessionNameOverride,
933
- ...(options == null ? void 0 : options.abortSignal) ? { signal: options.abortSignal } : {}
934
- })
935
- });
936
- return new VercelNetworkSandboxSession({
937
- sandbox: fork,
938
- ownsLifecycle: true
939
- });
940
- };
941
- this.resumeSession = async (options) => {
942
- var _a;
943
- (_a = options.abortSignal) == null ? void 0 : _a.throwIfAborted();
944
- if ("sandbox" in this.settings && this.settings.sandbox != null) {
945
- return new VercelNetworkSandboxSession({
946
- sandbox: this.settings.sandbox,
947
- ownsLifecycle: false
948
- });
949
- }
950
- const sandbox = await withVercelSandboxAuthenticationError({
951
- settings: this.settings,
952
- operation: () => Sandbox.get({
953
- ...getSandboxLookupParams(this.settings),
954
- name: sessionSandboxName(options.sessionId),
955
- ...options.abortSignal ? { signal: options.abortSignal } : {}
956
- })
957
- });
958
- return new VercelNetworkSandboxSession({ sandbox, ownsLifecycle: true });
959
- };
960
- }
961
- };
962
- var SNAPSHOT_CACHE_KEY = /* @__PURE__ */ Symbol.for(
963
- "ai-sdk.harness.vercel-template-snapshots"
964
- );
965
798
  function getSandboxLookupParams(settings) {
966
799
  if ("sandbox" in settings && settings.sandbox != null) {
967
800
  return {};
@@ -974,15 +807,6 @@ function getSandboxLookupParams(settings) {
974
807
  ...token ? { token } : {}
975
808
  };
976
809
  }
977
- function getSnapshotCache() {
978
- const globals = globalThis;
979
- let cache = globals[SNAPSHOT_CACHE_KEY];
980
- if (cache == null) {
981
- cache = /* @__PURE__ */ new Map();
982
- globals[SNAPSHOT_CACHE_KEY] = cache;
983
- }
984
- return cache;
985
- }
986
810
  var VERCEL_SANDBOX_AUTHENTICATION_MESSAGE = "Vercel Sandbox authentication failed. Set VERCEL_OIDC_TOKEN, or pass token, teamId, and projectId to createVercelSandbox(), then verify that they can access Vercel Sandbox.";
987
811
  async function withVercelSandboxAuthenticationError({
988
812
  settings,
@@ -1014,14 +838,13 @@ function isVercelSandboxAuthenticationFailure({
1014
838
  error,
1015
839
  hasConfiguredCredentials: hasConfiguredCredentials2
1016
840
  }) {
1017
- var _a, _b, _c, _d;
1018
841
  const seen = /* @__PURE__ */ new Set();
1019
842
  let current = error;
1020
843
  while (current != null && !seen.has(current)) {
1021
844
  seen.add(current);
1022
845
  if (typeof current === "object") {
1023
846
  const candidate = current;
1024
- if (((_a = candidate.response) == null ? void 0 : _a.status) === 401 || ((_b = candidate.response) == null ? void 0 : _b.status) === 403 || ((_c = candidate.response) == null ? void 0 : _c.statusCode) === 401 || ((_d = candidate.response) == null ? void 0 : _d.statusCode) === 403) {
847
+ if (candidate.response?.status === 401 || candidate.response?.status === 403 || candidate.response?.statusCode === 401 || candidate.response?.statusCode === 403) {
1025
848
  return true;
1026
849
  }
1027
850
  if (typeof candidate.name === "string" && VERCEL_AUTHENTICATION_ERROR_NAMES.has(candidate.name)) {
@@ -1049,6 +872,70 @@ var VERCEL_AUTHENTICATION_ERROR_NAMES = /* @__PURE__ */ new Set([
1049
872
  "VercelOidcTokenError"
1050
873
  ]);
1051
874
  var VERCEL_AUTHENTICATION_ERROR_MESSAGE = /Could not get credentials from OIDC context|No authentication found|Failed to (?:retrieve|refresh) authentication token|Missing credentials parameters to access the Vercel API|Authentication failed/i;
875
+ function hasExplicitSandboxEnvironment(params) {
876
+ return "runtime" in params && params.runtime != null || "image" in params && params.image != null || "source" in params && typeof params.source === "object" && params.source != null && "type" in params.source && params.source.type === "snapshot";
877
+ }
878
+ function withDefaultSandboxSettings(createParams) {
879
+ return {
880
+ ...hasExplicitSandboxEnvironment(createParams) ? {} : { runtime: DEFAULT_SANDBOX_RUNTIME },
881
+ ...createParams,
882
+ timeout: createParams.timeout ?? DEFAULT_SANDBOX_TIMEOUT_MS
883
+ };
884
+ }
885
+ async function ensureTemplateSnapshot({
886
+ baseParams,
887
+ templateName,
888
+ onCreate,
889
+ lookupParams,
890
+ abortSignal,
891
+ snapshotCache
892
+ }) {
893
+ const cachedSnapshotId = snapshotCache?.get(templateName);
894
+ if (cachedSnapshotId != null) {
895
+ return cachedSnapshotId;
896
+ }
897
+ const prepared = await Sandbox.getOrCreate({
898
+ ...baseParams,
899
+ name: templateName,
900
+ persistent: true,
901
+ snapshotExpiration: baseParams.snapshotExpiration ?? 0,
902
+ onCreate,
903
+ ...abortSignal ? { signal: abortSignal } : {}
904
+ });
905
+ let snapshotId = prepared.currentSnapshotId;
906
+ if (snapshotId == null) {
907
+ const stopped = await prepared.stop(
908
+ abortSignal ? { signal: abortSignal } : void 0
909
+ );
910
+ snapshotId = stopped.snapshot?.id ?? await pollForTemplateSnapshot({
911
+ name: templateName,
912
+ lookupParams,
913
+ abortSignal
914
+ });
915
+ }
916
+ snapshotCache?.set(templateName, snapshotId);
917
+ return snapshotId;
918
+ }
919
+ function createLiveSandboxFromSnapshot({
920
+ baseParams,
921
+ snapshotId,
922
+ liveName,
923
+ abortSignal
924
+ }) {
925
+ const {
926
+ runtime: _runtime,
927
+ image: _image,
928
+ source: _source,
929
+ persistent: _persistent,
930
+ ...forkParams
931
+ } = baseParams;
932
+ return Sandbox.create({
933
+ ...forkParams,
934
+ source: { type: "snapshot", snapshotId },
935
+ ...liveName != null ? { name: liveName } : {},
936
+ ...abortSignal ? { signal: abortSignal } : {}
937
+ });
938
+ }
1052
939
  async function pollForTemplateSnapshot({
1053
940
  name,
1054
941
  lookupParams,
@@ -1056,7 +943,7 @@ async function pollForTemplateSnapshot({
1056
943
  }) {
1057
944
  const deadline = Date.now() + SNAPSHOT_POLL_TIMEOUT_MS;
1058
945
  while (Date.now() < deadline) {
1059
- abortSignal == null ? void 0 : abortSignal.throwIfAborted();
946
+ abortSignal?.throwIfAborted();
1060
947
  const refreshed = await Sandbox.get({
1061
948
  ...lookupParams,
1062
949
  name,
@@ -1074,8 +961,227 @@ async function pollForTemplateSnapshot({
1074
961
  `Timed out waiting for snapshot of template "${name}" to publish.`
1075
962
  );
1076
963
  }
964
+
965
+ // src/vercel-legacy-sandbox-provider.ts
966
+ var SESSION_NAME_PREFIX = "ai-sdk-harness-session";
967
+ function sessionSandboxName(sessionId) {
968
+ return `${SESSION_NAME_PREFIX}-${sessionId}`;
969
+ }
970
+ function createVercelSandbox(settings = {}) {
971
+ console.warn(
972
+ "createVercelSandbox is deprecated. Use createVercelNetworkSandboxSession and HarnessAgent.createSession({ sandboxSession }) instead."
973
+ );
974
+ return new VercelSandboxProvider(settings);
975
+ }
976
+ var VercelSandboxProvider = class {
977
+ constructor(settings) {
978
+ this.settings = settings;
979
+ this.specificationVersion = "harness-sandbox-v1";
980
+ this.providerId = VERCEL_PROVIDER_ID3;
981
+ this.createSession = async (options) => {
982
+ options?.abortSignal?.throwIfAborted();
983
+ if ("sandbox" in this.settings && this.settings.sandbox != null) {
984
+ return new VercelNetworkSandboxSession({
985
+ sandbox: this.settings.sandbox,
986
+ ownsLifecycle: false
987
+ });
988
+ }
989
+ const settings = this.settings;
990
+ const {
991
+ sandbox: _ignoredSandbox,
992
+ name: explicitName,
993
+ ...createParams
994
+ } = settings;
995
+ const baseParams = withDefaultSandboxSettings(
996
+ createParams
997
+ );
998
+ const identity = options?.identity;
999
+ const onFirstCreate = options?.onFirstCreate;
1000
+ const sessionNameOverride = options?.sessionId ? { name: sessionSandboxName(options.sessionId) } : {};
1001
+ if (identity == null || onFirstCreate == null) {
1002
+ const sandbox = await withVercelSandboxAuthenticationError({
1003
+ settings: this.settings,
1004
+ operation: () => Sandbox2.create({
1005
+ ...baseParams,
1006
+ ...sessionNameOverride,
1007
+ ...options?.abortSignal ? { signal: options.abortSignal } : {}
1008
+ })
1009
+ });
1010
+ return new VercelNetworkSandboxSession({ sandbox, ownsLifecycle: true });
1011
+ }
1012
+ const templateName = explicitName ?? `ai-sdk-harness-${identity}`;
1013
+ const snapshotId = await withVercelSandboxAuthenticationError({
1014
+ settings: this.settings,
1015
+ operation: () => ensureTemplateSnapshot({
1016
+ baseParams,
1017
+ templateName,
1018
+ lookupParams: getSandboxLookupParams(baseParams),
1019
+ abortSignal: options?.abortSignal,
1020
+ snapshotCache: getSnapshotCache(),
1021
+ onCreate: async (sbx) => {
1022
+ await onFirstCreate(new VercelSandboxSession(sbx), {
1023
+ abortSignal: options?.abortSignal
1024
+ });
1025
+ }
1026
+ })
1027
+ });
1028
+ const fork = await withVercelSandboxAuthenticationError({
1029
+ settings: this.settings,
1030
+ operation: () => createLiveSandboxFromSnapshot({
1031
+ baseParams,
1032
+ snapshotId,
1033
+ liveName: sessionNameOverride.name,
1034
+ abortSignal: options?.abortSignal
1035
+ })
1036
+ });
1037
+ return new VercelNetworkSandboxSession({
1038
+ sandbox: fork,
1039
+ ownsLifecycle: true
1040
+ });
1041
+ };
1042
+ this.resumeSession = async (options) => {
1043
+ options.abortSignal?.throwIfAborted();
1044
+ if ("sandbox" in this.settings && this.settings.sandbox != null) {
1045
+ return new VercelNetworkSandboxSession({
1046
+ sandbox: this.settings.sandbox,
1047
+ ownsLifecycle: false
1048
+ });
1049
+ }
1050
+ const sandbox = await withVercelSandboxAuthenticationError({
1051
+ settings: this.settings,
1052
+ operation: () => Sandbox2.get({
1053
+ ...getSandboxLookupParams(this.settings),
1054
+ name: sessionSandboxName(options.sessionId),
1055
+ ...options.abortSignal ? { signal: options.abortSignal } : {}
1056
+ })
1057
+ });
1058
+ return new VercelNetworkSandboxSession({ sandbox, ownsLifecycle: true });
1059
+ };
1060
+ console.warn(
1061
+ "VercelSandboxProvider is deprecated. Use createVercelNetworkSandboxSession instead."
1062
+ );
1063
+ }
1064
+ };
1065
+ var SNAPSHOT_CACHE_KEY = /* @__PURE__ */ Symbol.for(
1066
+ "ai-sdk.harness.vercel-template-snapshots"
1067
+ );
1068
+ function getSnapshotCache() {
1069
+ const globals = globalThis;
1070
+ let cache = globals[SNAPSHOT_CACHE_KEY];
1071
+ if (cache == null) {
1072
+ cache = /* @__PURE__ */ new Map();
1073
+ globals[SNAPSHOT_CACHE_KEY] = cache;
1074
+ }
1075
+ return cache;
1076
+ }
1077
+
1078
+ // src/vercel-sandbox.ts
1079
+ import { Sandbox as Sandbox3 } from "@vercel/sandbox";
1080
+ async function createVercelNetworkSandboxSession(options = {}) {
1081
+ if ("sandbox" in options) {
1082
+ throw new Error(
1083
+ "createVercelNetworkSandboxSession: use createVercelNetworkSandboxSessionFromNativeSandbox for an existing sandbox."
1084
+ );
1085
+ }
1086
+ const {
1087
+ template,
1088
+ abortSignal,
1089
+ sandboxId,
1090
+ sandbox: _sandbox,
1091
+ ...nativeOptions
1092
+ } = options;
1093
+ const effectiveSignal = abortSignal ?? nativeOptions.signal;
1094
+ effectiveSignal?.throwIfAborted();
1095
+ const { name, ...creationOptions } = nativeOptions;
1096
+ if (sandboxId != null && name != null && sandboxId !== name) {
1097
+ throw new Error(
1098
+ "createVercelNetworkSandboxSession: sandboxId and name must match when both are provided."
1099
+ );
1100
+ }
1101
+ const liveName = sandboxId ?? name;
1102
+ const baseParams = withDefaultSandboxSettings({
1103
+ ...creationOptions,
1104
+ ...effectiveSignal ? { signal: effectiveSignal } : {}
1105
+ });
1106
+ const settings = options;
1107
+ if (template == null) {
1108
+ const sandbox = await withVercelSandboxAuthenticationError({
1109
+ settings,
1110
+ operation: () => Sandbox3.create({
1111
+ ...baseParams,
1112
+ ...liveName != null ? { name: liveName } : {}
1113
+ })
1114
+ });
1115
+ return createVercelNetworkSandboxSessionFromNativeSandbox(sandbox);
1116
+ }
1117
+ const selection = "source" in baseParams && baseParams.source != null ? baseParams.source : "image" in baseParams && baseParams.image != null ? { image: baseParams.image } : { runtime: baseParams.runtime };
1118
+ const material = JSON.stringify([2, template.identity, selection]);
1119
+ const digest = new Uint8Array(
1120
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(material))
1121
+ );
1122
+ const templateName = `ai-sdk-harness-v2-${Array.from(digest.slice(0, 12), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
1123
+ const snapshotId = await withVercelSandboxAuthenticationError({
1124
+ settings,
1125
+ operation: () => ensureTemplateSnapshot({
1126
+ baseParams,
1127
+ templateName,
1128
+ lookupParams: getSandboxLookupParams(baseParams),
1129
+ abortSignal: effectiveSignal,
1130
+ onCreate: async (sandbox) => {
1131
+ await template.prepare({
1132
+ session: createVercelSandboxSessionFromNativeSandbox(sandbox),
1133
+ abortSignal: effectiveSignal
1134
+ });
1135
+ }
1136
+ })
1137
+ });
1138
+ const liveSandbox = await withVercelSandboxAuthenticationError({
1139
+ settings,
1140
+ operation: () => createLiveSandboxFromSnapshot({
1141
+ baseParams,
1142
+ snapshotId,
1143
+ liveName
1144
+ })
1145
+ });
1146
+ return createVercelNetworkSandboxSessionFromNativeSandbox(liveSandbox);
1147
+ }
1148
+ async function resumeVercelNetworkSandboxSession(options) {
1149
+ const {
1150
+ sandboxId,
1151
+ abortSignal,
1152
+ signal,
1153
+ name: _name,
1154
+ resume: _resume,
1155
+ ...lookupOptions
1156
+ } = options;
1157
+ const effectiveSignal = abortSignal ?? signal;
1158
+ effectiveSignal?.throwIfAborted();
1159
+ const sandbox = await withVercelSandboxAuthenticationError({
1160
+ settings: options,
1161
+ operation: () => Sandbox3.get({
1162
+ ...lookupOptions,
1163
+ name: sandboxId,
1164
+ resume: true,
1165
+ ...effectiveSignal ? { signal: effectiveSignal } : {}
1166
+ })
1167
+ });
1168
+ return createVercelNetworkSandboxSessionFromNativeSandbox(sandbox);
1169
+ }
1170
+ function createVercelSandboxSessionFromNativeSandbox(nativeSandbox) {
1171
+ return new VercelSandboxSession(nativeSandbox);
1172
+ }
1173
+ function createVercelNetworkSandboxSessionFromNativeSandbox(nativeSandbox) {
1174
+ return new VercelNetworkSandboxSession({
1175
+ sandbox: nativeSandbox,
1176
+ ownsLifecycle: true
1177
+ });
1178
+ }
1077
1179
  export {
1078
1180
  VercelSandboxProvider,
1079
- createVercelSandbox
1181
+ createVercelNetworkSandboxSession,
1182
+ createVercelNetworkSandboxSessionFromNativeSandbox,
1183
+ createVercelSandbox,
1184
+ createVercelSandboxSessionFromNativeSandbox,
1185
+ resumeVercelNetworkSandboxSession
1080
1186
  };
1081
1187
  //# sourceMappingURL=index.js.map