@ai-sdk/code-mode 1.0.20 → 1.0.22

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 (50) hide show
  1. package/README.md +1 -1
  2. package/dist/continuation-capability.js +5 -0
  3. package/dist/continuation-capability.js.map +1 -1
  4. package/dist/errors.js +1 -136
  5. package/dist/errors.js.map +1 -1
  6. package/dist/host-interrupt.js +2 -14
  7. package/dist/host-interrupt.js.map +1 -1
  8. package/dist/index.d.ts +14 -44
  9. package/dist/index.js +1 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/interrupt-continuation.js +3 -8
  12. package/dist/interrupt-continuation.js.map +1 -1
  13. package/dist/run-code-mode.js +543 -2
  14. package/dist/run-code-mode.js.map +1 -1
  15. package/dist/tool-invocation.js +9 -23
  16. package/dist/tool-invocation.js.map +1 -1
  17. package/dist/utils/serialization.js +4 -0
  18. package/dist/utils/serialization.js.map +1 -1
  19. package/package.json +8 -7
  20. package/src/continuation-capability.ts +18 -0
  21. package/src/errors.ts +0 -190
  22. package/src/host-interrupt.ts +2 -31
  23. package/src/index.ts +1 -1
  24. package/src/interrupt-continuation.ts +13 -15
  25. package/src/run-code-mode.ts +706 -3
  26. package/src/tool-invocation.ts +9 -23
  27. package/src/types.ts +38 -68
  28. package/src/utils/serialization.ts +4 -0
  29. package/dist/runtime/guest-sources.js +0 -350
  30. package/dist/runtime/guest-sources.js.map +0 -1
  31. package/dist/runtime/manager.js +0 -794
  32. package/dist/runtime/manager.js.map +0 -1
  33. package/dist/runtime/max-workers.js +0 -40
  34. package/dist/runtime/max-workers.js.map +0 -1
  35. package/dist/runtime/protocol.js +0 -1
  36. package/dist/runtime/protocol.js.map +0 -1
  37. package/dist/runtime/worker-source.d.ts +0 -11
  38. package/dist/runtime/worker-source.js +0 -2
  39. package/dist/utils/options.js +0 -76
  40. package/dist/utils/options.js.map +0 -1
  41. package/dist/utils/source-cache.js +0 -77
  42. package/dist/utils/source-cache.js.map +0 -1
  43. package/src/runtime/guest-sources.ts +0 -351
  44. package/src/runtime/manager.ts +0 -963
  45. package/src/runtime/max-workers.ts +0 -65
  46. package/src/runtime/protocol.ts +0 -74
  47. package/src/runtime/worker-source.ts +0 -10
  48. package/src/runtime/worker.ts +0 -607
  49. package/src/utils/options.ts +0 -83
  50. package/src/utils/source-cache.ts +0 -91
@@ -6,7 +6,6 @@ import {
6
6
  CodeModeToolApprovalRequiredError,
7
7
  CodeModeToolError,
8
8
  } from './errors.js';
9
- import { isCodeModeHostInterruptSignal } from './host-interrupt.js';
10
9
  import type {
11
10
  CodeModeInterruptExecutionContext,
12
11
  CodeModeInterruptPayload,
@@ -16,6 +15,7 @@ import type {
16
15
  } from './types.js';
17
16
  import {
18
17
  assertJsonSerializable,
18
+ fromJsonPayload,
19
19
  toJsonPayload,
20
20
  } from './utils/serialization.js';
21
21
 
@@ -67,7 +67,7 @@ export async function invokeHostTool({
67
67
  });
68
68
  }
69
69
 
70
- const input = inputJson === '' ? undefined : JSON.parse(inputJson);
70
+ const input = fromJsonPayload(inputJson);
71
71
  assertJsonSerializable(input, maxToolInputBytes, `Tool "${toolName}" input`);
72
72
 
73
73
  const validation = await raceAgainstAbort(
@@ -149,27 +149,13 @@ export async function invokeHostTool({
149
149
  }
150
150
  }
151
151
 
152
- let output: unknown;
153
- try {
154
- output = await raceAgainstAbort(
155
- executeHostTool(hostTool.execute.bind(hostTool), {
156
- input: validation.value,
157
- options: executionOptions,
158
- }),
159
- executionOptions.abortSignal,
160
- );
161
- } catch (error) {
162
- if (isCodeModeHostInterruptSignal(error)) {
163
- return {
164
- type: 'interrupted',
165
- toolName,
166
- input: validation.value,
167
- toolCallId,
168
- payload: error.payload,
169
- };
170
- }
171
- throw error;
172
- }
152
+ const output = await raceAgainstAbort(
153
+ executeHostTool(hostTool.execute.bind(hostTool), {
154
+ input: validation.value,
155
+ options: executionOptions,
156
+ }),
157
+ executionOptions.abortSignal,
158
+ );
173
159
  return {
174
160
  type: 'success',
175
161
  valueJson: toJsonPayload(
package/src/types.ts CHANGED
@@ -78,40 +78,6 @@ export interface CodeModeInterruptExecutionContext<
78
78
  resolution: TResolution;
79
79
  }
80
80
 
81
- export type CodeModeContinuationLedgerEntry =
82
- | {
83
- kind: 'tool';
84
- name: string;
85
- inputJson: string;
86
- toolCallId: string;
87
- status: 'fulfilled';
88
- dateNowMs: number;
89
- valueJson: string;
90
- }
91
- | {
92
- kind: 'tool';
93
- name: string;
94
- inputJson: string;
95
- toolCallId: string;
96
- status: 'rejected';
97
- dateNowMs: number;
98
- error: SerializableError;
99
- }
100
- | {
101
- kind: 'tool';
102
- name: string;
103
- inputJson: string;
104
- toolCallId: string;
105
- interruptId: string;
106
- interruptPayload: CodeModeInterruptPayload;
107
- status: 'interrupted';
108
- };
109
-
110
- export interface CodeModeDeterminismState {
111
- dateNowMs: number;
112
- randomSeed: string;
113
- }
114
-
115
81
  export interface CodeModeContinuationAuth {
116
82
  alg: 'HMAC-SHA256';
117
83
  nonce: string;
@@ -120,17 +86,52 @@ export interface CodeModeContinuationAuth {
120
86
  signature: string;
121
87
  }
122
88
 
89
+ /**
90
+ * Opaque continuation state for an interrupted code-mode invocation.
91
+ *
92
+ * @remarks
93
+ * The token and compatibility metadata are authenticated. Applications should
94
+ * persist this value without reading or modifying its fields.
95
+ */
123
96
  export interface CodeModeContinuation {
124
- version: 1;
97
+ version: 2;
125
98
  js: string;
126
99
  outerToolCallId: string;
127
- determinism: CodeModeDeterminismState;
128
- ledger: CodeModeContinuationLedgerEntry[];
100
+ toolNames: string[];
101
+ token: string;
102
+ pendingInterruptions: CodeModePendingInterruption[];
103
+ resolutions: CodeModePendingResolution[];
129
104
  auth: CodeModeContinuationAuth;
130
105
  }
131
106
 
132
107
  export type UnsignedCodeModeContinuation = Omit<CodeModeContinuation, 'auth'>;
133
108
 
109
+ /**
110
+ * Authenticated compatibility metadata for one interruption returned by
111
+ * `run`.
112
+ *
113
+ * @internal
114
+ */
115
+ export interface CodeModePendingInterruption {
116
+ runInterruptionId: string;
117
+ interruptId: string;
118
+ toolName: string;
119
+ toolCallId: string;
120
+ input: unknown;
121
+ payload: CodeModeInterruptPayload;
122
+ }
123
+
124
+ /**
125
+ * A resolution collected while exposing a batched `run` interruption through
126
+ * code mode's one-at-a-time continuation API.
127
+ *
128
+ * @internal
129
+ */
130
+ export interface CodeModePendingResolution {
131
+ runInterruptionId: string;
132
+ value: unknown;
133
+ }
134
+
134
135
  export interface CodeModeInterrupt<
135
136
  TPayload extends CodeModeInterruptPayload = CodeModeInterruptPayload,
136
137
  > {
@@ -217,34 +218,3 @@ export interface RunCodeModeInput {
217
218
  continuation?: CodeModeContinuation;
218
219
  interruptResolution?: CodeModeInterruptResolution;
219
220
  }
220
-
221
- /**
222
- * Fully normalized runtime options.
223
- *
224
- * @internal
225
- */
226
- export interface NormalizedCodeModeOptions {
227
- timeoutMs: number;
228
- memoryLimitBytes: number;
229
- maxStackSizeBytes: number;
230
- maxResultBytes: number;
231
- maxConsoleOutputBytes: number;
232
- maxSourceBytes: number;
233
- maxToolInputBytes: number;
234
- maxToolOutputBytes: number;
235
- maxBridgeRequests: number;
236
- maxInFlightBridgeRequests: number;
237
- }
238
-
239
- /**
240
- * Serializable representation of an error crossing the worker boundary.
241
- *
242
- * @internal
243
- */
244
- export interface SerializableError {
245
- name: string;
246
- message: string;
247
- stack?: string;
248
- code?: string;
249
- details?: unknown;
250
- }
@@ -20,6 +20,10 @@ export function toJsonPayload(
20
20
  return toStrictJsonPayload(value, maxBytes, label);
21
21
  }
22
22
 
23
+ export function fromJsonPayload(valueJson: string): unknown {
24
+ return valueJson === '' ? undefined : JSON.parse(valueJson);
25
+ }
26
+
23
27
  export function toStrictJsonPayload(
24
28
  value: unknown,
25
29
  maxBytes: number,
@@ -1,350 +0,0 @@
1
- const HARDENING_SOURCE = `
2
- (function() {
3
- try { delete globalThis.crypto; } catch {}
4
- if ('crypto' in globalThis) {
5
- Object.defineProperty(globalThis, 'crypto', {
6
- value: undefined,
7
- writable: false,
8
- configurable: false,
9
- });
10
- }
11
- try { delete globalThis.performance; } catch {}
12
- if ('performance' in globalThis) {
13
- Object.defineProperty(globalThis, 'performance', {
14
- value: undefined,
15
- writable: false,
16
- configurable: false,
17
- });
18
- }
19
-
20
- Object.defineProperty(globalThis, 'eval', {
21
- value: undefined,
22
- writable: false,
23
- configurable: false,
24
- });
25
-
26
- const OriginalFunction = Function;
27
- const BlockedFunction = function() {
28
- throw new TypeError('Function constructor is not allowed');
29
- };
30
- BlockedFunction.prototype = OriginalFunction.prototype;
31
-
32
- const AsyncFunction = (async function(){}).constructor;
33
- const GeneratorFunction = (function*(){}).constructor;
34
- const AsyncGeneratorFunction = (async function*(){}).constructor;
35
- for (const proto of [
36
- OriginalFunction.prototype,
37
- AsyncFunction.prototype,
38
- GeneratorFunction.prototype,
39
- AsyncGeneratorFunction.prototype,
40
- ]) {
41
- Object.defineProperty(proto, 'constructor', {
42
- value: BlockedFunction,
43
- writable: false,
44
- configurable: false,
45
- });
46
- }
47
- Object.defineProperty(globalThis, 'Function', {
48
- value: BlockedFunction,
49
- writable: false,
50
- configurable: false,
51
- });
52
-
53
- const g = globalThis;
54
- const toFreeze = [
55
- Object, Object.prototype,
56
- OriginalFunction, OriginalFunction.prototype,
57
- AsyncFunction, AsyncFunction.prototype,
58
- GeneratorFunction, GeneratorFunction.prototype,
59
- AsyncGeneratorFunction, AsyncGeneratorFunction.prototype,
60
- Array, Array.prototype,
61
- String, String.prototype,
62
- Number, Number.prototype,
63
- g.BigInt, g.BigInt && g.BigInt.prototype,
64
- Boolean, Boolean.prototype,
65
- g.Symbol, g.Symbol && g.Symbol.prototype,
66
- RegExp, RegExp.prototype,
67
- Date, Date.prototype,
68
- Map, Map.prototype,
69
- Set, Set.prototype,
70
- WeakMap, WeakMap.prototype,
71
- WeakSet, WeakSet.prototype,
72
- Promise, Promise.prototype,
73
- ArrayBuffer, ArrayBuffer.prototype,
74
- g.DataView, g.DataView && g.DataView.prototype,
75
- JSON, Math, g.Reflect, g.Proxy,
76
- ];
77
- for (const name of [
78
- 'Int8Array','Uint8Array','Uint8ClampedArray',
79
- 'Int16Array','Uint16Array','Int32Array','Uint32Array',
80
- 'Float32Array','Float64Array',
81
- 'BigInt64Array','BigUint64Array',
82
- ]) {
83
- if (g[name]) toFreeze.push(g[name], g[name].prototype);
84
- }
85
- for (const obj of toFreeze) {
86
- if (obj != null) {
87
- try { Object.freeze(obj); } catch {}
88
- }
89
- }
90
- })();
91
- `;
92
- const DETERMINISTIC_APIS_SOURCE = `
93
- var __codeModeResetDateNow = (function(config) {
94
- var OriginalDate = Date;
95
- var dateNowMs = Number(config && config.dateNowMs);
96
- if (!Number.isFinite(dateNowMs)) dateNowMs = 0;
97
-
98
- function resetDateNow(value) {
99
- var next = Number(value);
100
- if (Number.isFinite(next)) dateNowMs = Math.trunc(next);
101
- }
102
-
103
- function nextDateMs() {
104
- var value = dateNowMs;
105
- dateNowMs += 1;
106
- return value;
107
- }
108
-
109
- function CodeModeDate() {
110
- if (new.target) {
111
- if (arguments.length === 0) return new OriginalDate(nextDateMs());
112
- return Reflect.construct(OriginalDate, arguments, new.target);
113
- }
114
- return new OriginalDate(nextDateMs()).toString();
115
- }
116
-
117
- Object.defineProperty(CodeModeDate, 'prototype', {
118
- value: OriginalDate.prototype,
119
- writable: false,
120
- configurable: false,
121
- });
122
- Object.defineProperty(OriginalDate.prototype, 'constructor', {
123
- value: CodeModeDate,
124
- writable: false,
125
- configurable: false,
126
- });
127
- Object.defineProperty(CodeModeDate, 'now', {
128
- value: nextDateMs,
129
- writable: false,
130
- configurable: false,
131
- });
132
- Object.defineProperty(CodeModeDate, 'parse', {
133
- value: OriginalDate.parse,
134
- writable: false,
135
- configurable: false,
136
- });
137
- Object.defineProperty(CodeModeDate, 'UTC', {
138
- value: OriginalDate.UTC,
139
- writable: false,
140
- configurable: false,
141
- });
142
- Object.defineProperty(globalThis, 'Date', {
143
- value: CodeModeDate,
144
- writable: false,
145
- configurable: false,
146
- });
147
-
148
- var randomSeed = String(config && config.randomSeed || '');
149
- var mask64 = (1n << 64n) - 1n;
150
- function readSeedPart(offset, fallback) {
151
- var part = randomSeed.slice(offset, offset + 16);
152
- return /^[0-9a-fA-F]{16}$/.test(part) ? BigInt('0x' + part) : fallback;
153
- }
154
- var randomState0 = readSeedPart(0, 0x243f6a8885a308d3n);
155
- var randomState1 = readSeedPart(16, 0x13198a2e03707344n);
156
- if ((randomState0 | randomState1) === 0n) {
157
- randomState1 = 0x9e3779b97f4a7c15n;
158
- }
159
- function nextRandom64() {
160
- var s1 = randomState0;
161
- var s0 = randomState1;
162
- randomState0 = s0;
163
- s1 = (s1 ^ ((s1 << 23n) & mask64)) & mask64;
164
- randomState1 = (s1 ^ s0 ^ (s1 >> 17n) ^ (s0 >> 26n)) & mask64;
165
- return (randomState1 + s0) & mask64;
166
- }
167
- Object.defineProperty(Math, 'random', {
168
- value: function() {
169
- return Number(nextRandom64() >> 11n) / 9007199254740992;
170
- },
171
- writable: false,
172
- configurable: false,
173
- });
174
-
175
- return resetDateNow;
176
- })(__codeModeDeterminism);
177
- `;
178
- const BRIDGE_TRACKING_SOURCE = `
179
- (function() {
180
- var nextRecordId = 0;
181
- var records = [];
182
-
183
- function detachedError(message, record) {
184
- var error = new Error(message);
185
- error.name = 'CodeModeDetachedBridgeRequestError';
186
- error.code = 'CODE_MODE_DETACHED_BRIDGE_REQUEST';
187
- error.details = {
188
- id: record.id,
189
- kind: record.kind,
190
- name: record.name,
191
- status: record.status
192
- };
193
- return error;
194
- }
195
-
196
- Object.defineProperty(globalThis, '__codeModeCreateBridgePromise', {
197
- value: function(kind, name, start) {
198
- var record = {
199
- id: ++nextRecordId,
200
- kind: String(kind),
201
- name: String(name || ''),
202
- observed: false,
203
- status: 'idle'
204
- };
205
- var promise;
206
- records.push(record);
207
-
208
- function getPromise() {
209
- record.observed = true;
210
- if (!promise) {
211
- record.status = 'pending';
212
- promise = Promise.resolve().then(start).then(
213
- function(value) {
214
- record.status = 'fulfilled';
215
- return value;
216
- },
217
- function(error) {
218
- record.status = 'rejected';
219
- throw error;
220
- }
221
- );
222
- }
223
- return promise;
224
- }
225
-
226
- return Object.freeze({
227
- then: function(onFulfilled, onRejected) {
228
- return getPromise().then(onFulfilled, onRejected);
229
- },
230
- catch: function(onRejected) {
231
- return getPromise().catch(onRejected);
232
- },
233
- finally: function(onFinally) {
234
- return getPromise().finally(onFinally);
235
- },
236
- get [Symbol.toStringTag]() {
237
- return 'Promise';
238
- }
239
- });
240
- },
241
- writable: false,
242
- configurable: false
243
- });
244
-
245
- Object.defineProperty(globalThis, '__codeModeAssertNoDetachedBridgeCalls', {
246
- value: function() {
247
- for (var i = 0; i < records.length; i++) {
248
- var record = records[i];
249
- if (!record.observed) {
250
- throw detachedError(
251
- 'Code mode created an unawaited ' + record.kind + ' bridge request: ' + record.name + '.',
252
- record
253
- );
254
- }
255
- if (record.status === 'pending') {
256
- throw detachedError(
257
- 'Code mode returned while a ' + record.kind + ' bridge request was still pending: ' + record.name + '.',
258
- record
259
- );
260
- }
261
- }
262
- },
263
- writable: false,
264
- configurable: false
265
- });
266
- })();
267
- `;
268
- const TOOLS_PROXY_SOURCE = `
269
- (function(invokeTool) {
270
- globalThis.tools = (function makeProxy(path) {
271
- return new Proxy(function(){}, {
272
- get: function(_target, prop) {
273
- if (prop === 'then' || typeof prop === 'symbol') return undefined;
274
- return makeProxy(path.concat([String(prop)]));
275
- },
276
- apply: function(_target, _thisArg, args) {
277
- var toolPath = path.join('.');
278
- if (!toolPath) throw new Error('Tool path missing in invocation');
279
- var inputJson = args.length > 0 ? JSON.stringify(args[0]) : '';
280
- if (inputJson === undefined) {
281
- throw new Error('Tool input must be JSON-serializable');
282
- }
283
- return globalThis.__codeModeCreateBridgePromise('tool', toolPath, async function() {
284
- var resultJson = await invokeTool(toolPath, inputJson);
285
- return resultJson === '' ? undefined : JSON.parse(resultJson);
286
- });
287
- }
288
- });
289
- })([]);
290
- })(__codeModeInvokeTool);
291
- `;
292
- const SERIALIZATION_GUARD_SOURCE = `
293
- (function() {
294
- function serializeJsonPayload(value) {
295
- if (typeof globalThis.__codeModeAssertNoDetachedBridgeCalls === 'function') {
296
- globalThis.__codeModeAssertNoDetachedBridgeCalls();
297
- }
298
-
299
- if (value === undefined) {
300
- return '';
301
- }
302
-
303
- var encoded;
304
- try {
305
- encoded = JSON.stringify(value);
306
- } catch (error) {
307
- var message = error && error.message ? String(error.message) : String(error);
308
- throw new TypeError('Code mode result is not JSON-serializable: ' + message);
309
- }
310
-
311
- if (encoded === undefined) {
312
- throw new TypeError('Code mode result is not JSON-serializable.');
313
- }
314
-
315
- return encoded;
316
- }
317
-
318
- Object.defineProperty(globalThis, '__codeModeSerializeJsonPayload', {
319
- value: serializeJsonPayload,
320
- writable: false,
321
- configurable: false,
322
- });
323
- })();
324
- `;
325
- function buildGuestRuntimeSetupSource() {
326
- return `
327
- (function(__codeModeInvokeTool, __codeModeDeterminism) {
328
- ${DETERMINISTIC_APIS_SOURCE}
329
- ${HARDENING_SOURCE}
330
- ${BRIDGE_TRACKING_SOURCE}
331
- ${TOOLS_PROXY_SOURCE}
332
- ${SERIALIZATION_GUARD_SOURCE}
333
- return Object.freeze({
334
- resetDateNow: __codeModeResetDateNow,
335
- });
336
- })
337
- `;
338
- }
339
- function wrapUserCode(js) {
340
- return `
341
- globalThis.__codeModeResult = (async () => {
342
- ${js}
343
- })();
344
- `;
345
- }
346
- export {
347
- buildGuestRuntimeSetupSource,
348
- wrapUserCode
349
- };
350
- //# sourceMappingURL=guest-sources.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/runtime/guest-sources.ts"],"sourcesContent":["const HARDENING_SOURCE = `\n(function() {\n try { delete globalThis.crypto; } catch {}\n if ('crypto' in globalThis) {\n Object.defineProperty(globalThis, 'crypto', {\n value: undefined,\n writable: false,\n configurable: false,\n });\n }\n try { delete globalThis.performance; } catch {}\n if ('performance' in globalThis) {\n Object.defineProperty(globalThis, 'performance', {\n value: undefined,\n writable: false,\n configurable: false,\n });\n }\n\n Object.defineProperty(globalThis, 'eval', {\n value: undefined,\n writable: false,\n configurable: false,\n });\n\n const OriginalFunction = Function;\n const BlockedFunction = function() {\n throw new TypeError('Function constructor is not allowed');\n };\n BlockedFunction.prototype = OriginalFunction.prototype;\n\n const AsyncFunction = (async function(){}).constructor;\n const GeneratorFunction = (function*(){}).constructor;\n const AsyncGeneratorFunction = (async function*(){}).constructor;\n for (const proto of [\n OriginalFunction.prototype,\n AsyncFunction.prototype,\n GeneratorFunction.prototype,\n AsyncGeneratorFunction.prototype,\n ]) {\n Object.defineProperty(proto, 'constructor', {\n value: BlockedFunction,\n writable: false,\n configurable: false,\n });\n }\n Object.defineProperty(globalThis, 'Function', {\n value: BlockedFunction,\n writable: false,\n configurable: false,\n });\n\n const g = globalThis;\n const toFreeze = [\n Object, Object.prototype,\n OriginalFunction, OriginalFunction.prototype,\n AsyncFunction, AsyncFunction.prototype,\n GeneratorFunction, GeneratorFunction.prototype,\n AsyncGeneratorFunction, AsyncGeneratorFunction.prototype,\n Array, Array.prototype,\n String, String.prototype,\n Number, Number.prototype,\n g.BigInt, g.BigInt && g.BigInt.prototype,\n Boolean, Boolean.prototype,\n g.Symbol, g.Symbol && g.Symbol.prototype,\n RegExp, RegExp.prototype,\n Date, Date.prototype,\n Map, Map.prototype,\n Set, Set.prototype,\n WeakMap, WeakMap.prototype,\n WeakSet, WeakSet.prototype,\n Promise, Promise.prototype,\n ArrayBuffer, ArrayBuffer.prototype,\n g.DataView, g.DataView && g.DataView.prototype,\n JSON, Math, g.Reflect, g.Proxy,\n ];\n for (const name of [\n 'Int8Array','Uint8Array','Uint8ClampedArray',\n 'Int16Array','Uint16Array','Int32Array','Uint32Array',\n 'Float32Array','Float64Array',\n 'BigInt64Array','BigUint64Array',\n ]) {\n if (g[name]) toFreeze.push(g[name], g[name].prototype);\n }\n for (const obj of toFreeze) {\n if (obj != null) {\n try { Object.freeze(obj); } catch {}\n }\n }\n})();\n`;\n\nconst DETERMINISTIC_APIS_SOURCE = `\nvar __codeModeResetDateNow = (function(config) {\n var OriginalDate = Date;\n var dateNowMs = Number(config && config.dateNowMs);\n if (!Number.isFinite(dateNowMs)) dateNowMs = 0;\n\n function resetDateNow(value) {\n var next = Number(value);\n if (Number.isFinite(next)) dateNowMs = Math.trunc(next);\n }\n\n function nextDateMs() {\n var value = dateNowMs;\n dateNowMs += 1;\n return value;\n }\n\n function CodeModeDate() {\n if (new.target) {\n if (arguments.length === 0) return new OriginalDate(nextDateMs());\n return Reflect.construct(OriginalDate, arguments, new.target);\n }\n return new OriginalDate(nextDateMs()).toString();\n }\n\n Object.defineProperty(CodeModeDate, 'prototype', {\n value: OriginalDate.prototype,\n writable: false,\n configurable: false,\n });\n Object.defineProperty(OriginalDate.prototype, 'constructor', {\n value: CodeModeDate,\n writable: false,\n configurable: false,\n });\n Object.defineProperty(CodeModeDate, 'now', {\n value: nextDateMs,\n writable: false,\n configurable: false,\n });\n Object.defineProperty(CodeModeDate, 'parse', {\n value: OriginalDate.parse,\n writable: false,\n configurable: false,\n });\n Object.defineProperty(CodeModeDate, 'UTC', {\n value: OriginalDate.UTC,\n writable: false,\n configurable: false,\n });\n Object.defineProperty(globalThis, 'Date', {\n value: CodeModeDate,\n writable: false,\n configurable: false,\n });\n\n var randomSeed = String(config && config.randomSeed || '');\n var mask64 = (1n << 64n) - 1n;\n function readSeedPart(offset, fallback) {\n var part = randomSeed.slice(offset, offset + 16);\n return /^[0-9a-fA-F]{16}$/.test(part) ? BigInt('0x' + part) : fallback;\n }\n var randomState0 = readSeedPart(0, 0x243f6a8885a308d3n);\n var randomState1 = readSeedPart(16, 0x13198a2e03707344n);\n if ((randomState0 | randomState1) === 0n) {\n randomState1 = 0x9e3779b97f4a7c15n;\n }\n function nextRandom64() {\n var s1 = randomState0;\n var s0 = randomState1;\n randomState0 = s0;\n s1 = (s1 ^ ((s1 << 23n) & mask64)) & mask64;\n randomState1 = (s1 ^ s0 ^ (s1 >> 17n) ^ (s0 >> 26n)) & mask64;\n return (randomState1 + s0) & mask64;\n }\n Object.defineProperty(Math, 'random', {\n value: function() {\n return Number(nextRandom64() >> 11n) / 9007199254740992;\n },\n writable: false,\n configurable: false,\n });\n\n return resetDateNow;\n})(__codeModeDeterminism);\n`;\n\nconst BRIDGE_TRACKING_SOURCE = `\n(function() {\n var nextRecordId = 0;\n var records = [];\n\n function detachedError(message, record) {\n var error = new Error(message);\n error.name = 'CodeModeDetachedBridgeRequestError';\n error.code = 'CODE_MODE_DETACHED_BRIDGE_REQUEST';\n error.details = {\n id: record.id,\n kind: record.kind,\n name: record.name,\n status: record.status\n };\n return error;\n }\n\n Object.defineProperty(globalThis, '__codeModeCreateBridgePromise', {\n value: function(kind, name, start) {\n var record = {\n id: ++nextRecordId,\n kind: String(kind),\n name: String(name || ''),\n observed: false,\n status: 'idle'\n };\n var promise;\n records.push(record);\n\n function getPromise() {\n record.observed = true;\n if (!promise) {\n record.status = 'pending';\n promise = Promise.resolve().then(start).then(\n function(value) {\n record.status = 'fulfilled';\n return value;\n },\n function(error) {\n record.status = 'rejected';\n throw error;\n }\n );\n }\n return promise;\n }\n\n return Object.freeze({\n then: function(onFulfilled, onRejected) {\n return getPromise().then(onFulfilled, onRejected);\n },\n catch: function(onRejected) {\n return getPromise().catch(onRejected);\n },\n finally: function(onFinally) {\n return getPromise().finally(onFinally);\n },\n get [Symbol.toStringTag]() {\n return 'Promise';\n }\n });\n },\n writable: false,\n configurable: false\n });\n\n Object.defineProperty(globalThis, '__codeModeAssertNoDetachedBridgeCalls', {\n value: function() {\n for (var i = 0; i < records.length; i++) {\n var record = records[i];\n if (!record.observed) {\n throw detachedError(\n 'Code mode created an unawaited ' + record.kind + ' bridge request: ' + record.name + '.',\n record\n );\n }\n if (record.status === 'pending') {\n throw detachedError(\n 'Code mode returned while a ' + record.kind + ' bridge request was still pending: ' + record.name + '.',\n record\n );\n }\n }\n },\n writable: false,\n configurable: false\n });\n})();\n`;\n\nconst TOOLS_PROXY_SOURCE = `\n(function(invokeTool) {\n globalThis.tools = (function makeProxy(path) {\n return new Proxy(function(){}, {\n get: function(_target, prop) {\n if (prop === 'then' || typeof prop === 'symbol') return undefined;\n return makeProxy(path.concat([String(prop)]));\n },\n apply: function(_target, _thisArg, args) {\n var toolPath = path.join('.');\n if (!toolPath) throw new Error('Tool path missing in invocation');\n var inputJson = args.length > 0 ? JSON.stringify(args[0]) : '';\n if (inputJson === undefined) {\n throw new Error('Tool input must be JSON-serializable');\n }\n return globalThis.__codeModeCreateBridgePromise('tool', toolPath, async function() {\n var resultJson = await invokeTool(toolPath, inputJson);\n return resultJson === '' ? undefined : JSON.parse(resultJson);\n });\n }\n });\n })([]);\n})(__codeModeInvokeTool);\n`;\n\nconst SERIALIZATION_GUARD_SOURCE = `\n(function() {\n function serializeJsonPayload(value) {\n if (typeof globalThis.__codeModeAssertNoDetachedBridgeCalls === 'function') {\n globalThis.__codeModeAssertNoDetachedBridgeCalls();\n }\n\n if (value === undefined) {\n return '';\n }\n\n var encoded;\n try {\n encoded = JSON.stringify(value);\n } catch (error) {\n var message = error && error.message ? String(error.message) : String(error);\n throw new TypeError('Code mode result is not JSON-serializable: ' + message);\n }\n\n if (encoded === undefined) {\n throw new TypeError('Code mode result is not JSON-serializable.');\n }\n\n return encoded;\n }\n\n Object.defineProperty(globalThis, '__codeModeSerializeJsonPayload', {\n value: serializeJsonPayload,\n writable: false,\n configurable: false,\n });\n})();\n`;\n\nexport function buildGuestRuntimeSetupSource(): string {\n return `\n(function(__codeModeInvokeTool, __codeModeDeterminism) {\n${DETERMINISTIC_APIS_SOURCE}\n${HARDENING_SOURCE}\n${BRIDGE_TRACKING_SOURCE}\n${TOOLS_PROXY_SOURCE}\n${SERIALIZATION_GUARD_SOURCE}\nreturn Object.freeze({\n resetDateNow: __codeModeResetDateNow,\n});\n})\n`;\n}\n\nexport function wrapUserCode(js: string): string {\n return `\nglobalThis.__codeModeResult = (async () => {\n${js}\n})();\n`;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