@vite-hub/runtime 0.4.1 → 0.5.1

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 (57) hide show
  1. package/dist/core-Crv8CV_r.js +1103 -0
  2. package/dist/core-auTkK4iZ.d.ts +298 -0
  3. package/dist/durability.d.ts +3 -5
  4. package/dist/durability.js +5 -3
  5. package/dist/{error-diagnostics-BM9W4pBg.js → error-diagnostics-Dj98U7ch.js} +1 -2
  6. package/dist/{error-diagnostics-0sYgKTT8.d.ts → error-diagnostics-DuusexaK.d.ts} +0 -2
  7. package/dist/{errors-BQ0ofIL4.js → errors-D2ixvqv3.js} +2 -3
  8. package/dist/{execution-budget-BPXbISEt.d.ts → execution-budget-Bv7h0-5V.d.ts} +0 -2
  9. package/dist/hosted-console-DTh9zwNz.d.ts +28 -0
  10. package/dist/index-hFKl7B_y.d.ts +345 -0
  11. package/dist/index.d.ts +7 -5
  12. package/dist/index.js +6 -5
  13. package/dist/internal/console.d.ts +5 -0
  14. package/dist/internal/console.js +1 -0
  15. package/dist/internal/context.d.ts +2 -0
  16. package/dist/internal/context.js +1 -0
  17. package/dist/internal/drain.d.ts +1 -3
  18. package/dist/internal/drain.js +3 -5
  19. package/dist/internal/error-diagnostics.d.ts +2 -0
  20. package/dist/internal/error-diagnostics.js +1 -0
  21. package/dist/internal/execution-budget.d.ts +2 -3
  22. package/dist/internal/execution-budget.js +226 -3
  23. package/dist/internal/grant.d.ts +1 -2
  24. package/dist/internal/grant.js +3 -4
  25. package/dist/internal/h3.d.ts +2 -4
  26. package/dist/internal/h3.js +4 -12
  27. package/dist/internal/node.d.ts +2 -3
  28. package/dist/internal/node.js +2 -3
  29. package/dist/internal/public-url.d.ts +2 -2
  30. package/dist/internal/public-url.js +1 -2
  31. package/dist/internal/response.d.ts +2 -0
  32. package/dist/internal/response.js +1 -0
  33. package/dist/internal/run-failed.d.ts +1 -3
  34. package/dist/internal/run-failed.js +1 -3
  35. package/dist/internal/run-scope.d.ts +1 -3
  36. package/dist/internal/run-scope.js +1 -2
  37. package/dist/internal/runtime-type.d.ts +1 -3
  38. package/dist/internal/runtime-type.js +2 -2
  39. package/dist/internal/shutdown.d.ts +1 -3
  40. package/dist/internal/shutdown.js +18 -21
  41. package/dist/internal/test-mode-setup.d.ts +1 -3
  42. package/dist/internal/test-mode-setup.js +1 -6
  43. package/dist/internal/test-mode.d.ts +1 -3
  44. package/dist/internal/test-mode.js +1 -2
  45. package/dist/internal/trace.d.ts +4 -0
  46. package/dist/internal/trace.js +1 -0
  47. package/dist/operations.d.ts +7 -4
  48. package/dist/operations.js +14 -11
  49. package/dist/{public-url-1WeOw54Z.d.ts → public-url-B4p8EOqr.d.ts} +6 -3
  50. package/dist/{public-url-ByAmAjbP.js → public-url-DDh_BHz3.js} +27 -22
  51. package/dist/request-context-Ci5FjuUY.js +680 -0
  52. package/dist/response-ClQ9ZSS_.d.ts +31 -0
  53. package/dist/response-DEyMvEBF.js +430 -0
  54. package/dist/{runtime-type-BftydMAf.js → runtime-type-EgaBGoVU.js} +2 -11
  55. package/package.json +29 -4
  56. package/dist/index-C1DoYfCf.d.ts +0 -733
  57. package/dist/request-context-uRQpodgl.js +0 -2433
@@ -0,0 +1,1103 @@
1
+ import { r as isRuntimeObject } from "./runtime-type-EgaBGoVU.js";
2
+ import { t as ViteHubError } from "./errors-D2ixvqv3.js";
3
+ import { t as runtimeErrorDiagnostics } from "./error-diagnostics-Dj98U7ch.js";
4
+ // src/internal/trace-attributes.ts
5
+ const contentAttributeKeys = /* @__PURE__ */ new Set([
6
+ "args",
7
+ "body",
8
+ "content",
9
+ "data",
10
+ "input",
11
+ "message",
12
+ "messages",
13
+ "output",
14
+ "payload",
15
+ "progress",
16
+ "prompt",
17
+ "raw",
18
+ "request",
19
+ "response",
20
+ "result",
21
+ "text",
22
+ "title"
23
+ ]);
24
+ const canonicalAttributeKeys = /* @__PURE__ */ new Set([
25
+ "vitehub.activity.owner",
26
+ "vitehub.activity.phase",
27
+ "vitehub.payload.summary",
28
+ "vitehub.payload.value",
29
+ "vitehub.payload.visibility"
30
+ ]);
31
+ function isTraceContentAttributeKey(key) {
32
+ if (key === "error.message") return false;
33
+ if (contentAttributeKeys.has(key)) return true;
34
+ return key.split(".").some((part, index) => index > 0 && contentAttributeKeys.has(part));
35
+ }
36
+ function ownProperties(value) {
37
+ if (!isRuntimeObject(value)) return [];
38
+ return Reflect.ownKeys(value).flatMap((key) => {
39
+ if (typeof key !== "string") return [];
40
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
41
+ return descriptor?.enumerable ? [[key, descriptor]] : [];
42
+ });
43
+ }
44
+ function mapArray(value, map) {
45
+ const length = Object.getOwnPropertyDescriptor(value, "length").value;
46
+ const next = [];
47
+ next.length = length;
48
+ for (let index = 0; index < length; index += 1) {
49
+ const descriptor = Object.getOwnPropertyDescriptor(value, index);
50
+ if (descriptor && "value" in descriptor) next[index] = map(descriptor.value);
51
+ }
52
+ return next;
53
+ }
54
+ function metadataValue(value, seen) {
55
+ if (!value || typeof value !== "object") return value;
56
+ if (seen.has(value)) return "[Circular]";
57
+ seen.add(value);
58
+ try {
59
+ if (Array.isArray(value)) return mapArray(value, (child) => metadataValue(child, seen));
60
+ return projectProperties(ownProperties(value), "metadata", seen);
61
+ } catch {
62
+ return;
63
+ } finally {
64
+ seen.delete(value);
65
+ }
66
+ }
67
+ function projectProperties(properties, content, seen) {
68
+ const omitted = [];
69
+ const next = Object.fromEntries(properties.flatMap(([key, descriptor]) => {
70
+ if (content === "metadata" && isTraceContentAttributeKey(key)) {
71
+ omitted.push(key);
72
+ return [];
73
+ }
74
+ if (!("value" in descriptor)) return [];
75
+ return [[key, content === "metadata" ? metadataValue(descriptor.value, seen) : descriptor.value]];
76
+ }));
77
+ if (omitted.length) next["content.omitted"] = omitted;
78
+ return next;
79
+ }
80
+ /** Project ordinary attributes; canonical activity and payload fields belong to the event. */
81
+ function normalizeTraceAttributes(attributes, content) {
82
+ let properties;
83
+ try {
84
+ properties = ownProperties(attributes || {}).filter(([key]) => !canonicalAttributeKeys.has(key));
85
+ } catch {
86
+ return;
87
+ }
88
+ const source = projectProperties(properties, "content", /* @__PURE__ */ new WeakSet());
89
+ try {
90
+ if (Array.isArray(source["content.omitted"])) {
91
+ const omitted = mapArray(source["content.omitted"], (value) => value).filter((key) => typeof key === "string" && !canonicalAttributeKeys.has(key));
92
+ if (omitted.length) source["content.omitted"] = omitted;
93
+ else delete source["content.omitted"];
94
+ }
95
+ } catch {
96
+ delete source["content.omitted"];
97
+ }
98
+ if (content === "metadata") {
99
+ const accessors = properties.filter(([key, descriptor]) => !("value" in descriptor) && isTraceContentAttributeKey(key));
100
+ if (accessors.length) {
101
+ const omitted = new Set(Array.isArray(source["content.omitted"]) ? source["content.omitted"] : []);
102
+ for (const [key] of accessors) omitted.add(key);
103
+ source["content.omitted"] = [...omitted];
104
+ }
105
+ const next = projectProperties(ownProperties(source), content, /* @__PURE__ */ new WeakSet());
106
+ return Object.keys(next).length ? next : void 0;
107
+ }
108
+ return Object.keys(source).length ? source : void 0;
109
+ }
110
+ // src/core.ts
111
+ function captureWebAssemblyModule() {
112
+ const namespace = Object.getOwnPropertyDescriptor(globalThis, "WebAssembly")?.value;
113
+ const constructor = typeof namespace === "object" ? Object.getOwnPropertyDescriptor(namespace, "Module")?.value : void 0;
114
+ return {
115
+ constructor,
116
+ exports: typeof constructor === "function" ? Object.getOwnPropertyDescriptor(constructor, "exports")?.value : void 0
117
+ };
118
+ }
119
+ const webAssemblyModule = /* @__PURE__ */ captureWebAssemblyModule();
120
+ const noExecutionAuthority = /* @__PURE__ */ Object.freeze({
121
+ credentials: "none",
122
+ environment: "none",
123
+ filesystem: /* @__PURE__ */ Object.freeze({
124
+ access: "none",
125
+ scope: "none"
126
+ }),
127
+ isolation: "none",
128
+ network: "none",
129
+ processes: "none"
130
+ });
131
+ const unknownExecutionAuthority = /* @__PURE__ */ Object.freeze({
132
+ credentials: "unknown",
133
+ environment: "unknown",
134
+ filesystem: /* @__PURE__ */ Object.freeze({
135
+ access: "unknown",
136
+ scope: "unknown"
137
+ }),
138
+ isolation: "unknown",
139
+ network: "unknown",
140
+ processes: "unknown"
141
+ });
142
+ function isExecutionAuthority(value) {
143
+ return inspectExecutionAuthority(value) !== void 0;
144
+ }
145
+ function inspectExecutionAuthority(value) {
146
+ try {
147
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
148
+ const authority = value;
149
+ const filesystem = authority.filesystem;
150
+ if (!filesystem || typeof filesystem !== "object" || Array.isArray(filesystem)) return void 0;
151
+ const files = filesystem;
152
+ const credentials = authority.credentials;
153
+ const environment = authority.environment;
154
+ const access = files.access;
155
+ const scope = files.scope;
156
+ const isolation = authority.isolation;
157
+ const network = authority.network;
158
+ const processes = authority.processes;
159
+ if (!(typeof credentials === "string" && [
160
+ "ambient",
161
+ "none",
162
+ "provisioned",
163
+ "unknown"
164
+ ].includes(credentials) && typeof environment === "string" && [
165
+ "ambient",
166
+ "none",
167
+ "selected",
168
+ "unknown"
169
+ ].includes(environment) && typeof access === "string" && [
170
+ "none",
171
+ "read-only",
172
+ "read-write",
173
+ "unknown"
174
+ ].includes(access) && typeof scope === "string" && [
175
+ "host",
176
+ "none",
177
+ "sandbox",
178
+ "unknown",
179
+ "workspace"
180
+ ].includes(scope) && typeof isolation === "string" && [
181
+ "container",
182
+ "microvm",
183
+ "none",
184
+ "process",
185
+ "unknown"
186
+ ].includes(isolation) && typeof network === "string" && [
187
+ "none",
188
+ "restricted",
189
+ "unrestricted",
190
+ "unknown"
191
+ ].includes(network) && typeof processes === "string" && [
192
+ "arbitrary",
193
+ "none",
194
+ "restricted",
195
+ "unknown"
196
+ ].includes(processes))) return void 0;
197
+ return {
198
+ authority: {
199
+ credentials,
200
+ environment,
201
+ filesystem: {
202
+ access,
203
+ scope
204
+ },
205
+ isolation,
206
+ network,
207
+ processes
208
+ },
209
+ filesystem
210
+ };
211
+ } catch {
212
+ return;
213
+ }
214
+ }
215
+ const canonicalExecutionAuthorities = /* @__PURE__ */ new WeakSet([noExecutionAuthority, unknownExecutionAuthority]);
216
+ function normalizeExecutionAuthority(value) {
217
+ if (isRuntimeObject(value) && canonicalExecutionAuthorities.has(value)) return value;
218
+ const inspected = inspectExecutionAuthority(value);
219
+ if (!inspected) throw runtimeErrorDiagnostics.RUNTIME_R0007({ message: "[vitehub] Invalid execution authority descriptor." });
220
+ const authority = Object.freeze({
221
+ ...inspected.authority,
222
+ filesystem: Object.freeze({ ...inspected.authority.filesystem })
223
+ });
224
+ canonicalExecutionAuthorities.add(authority);
225
+ return authority;
226
+ }
227
+ function timestamp(value) {
228
+ if (value instanceof Date) return value.toISOString();
229
+ if (typeof value === "string") return value;
230
+ if (isRuntimeObject(value)) try {
231
+ return Reflect.apply(Date.prototype.toISOString, value, []);
232
+ } catch (error) {
233
+ if (!(error instanceof TypeError)) throw error;
234
+ }
235
+ return (/* @__PURE__ */ new Date()).toISOString();
236
+ }
237
+ function normalizedTraceActivity(activity) {
238
+ if (!activity || typeof activity !== "object") return;
239
+ try {
240
+ if (Array.isArray(activity)) return;
241
+ const owner = Object.getOwnPropertyDescriptor(activity, "owner");
242
+ const phase = Object.getOwnPropertyDescriptor(activity, "phase");
243
+ if (!owner || !("value" in owner) || !phase || !("value" in phase)) return;
244
+ if (owner.value !== "agent" && owner.value !== "vitehub") return;
245
+ if (![
246
+ "delivery",
247
+ "execution",
248
+ "setup",
249
+ "teardown"
250
+ ].includes(phase.value)) return;
251
+ return {
252
+ owner: owner.value,
253
+ phase: phase.value
254
+ };
255
+ } catch {
256
+ return;
257
+ }
258
+ }
259
+ function reflectedMapEntries(value) {
260
+ if (!value || typeof value !== "object") return;
261
+ try {
262
+ return Array.from(Map.prototype.entries.call(value));
263
+ } catch {
264
+ return;
265
+ }
266
+ }
267
+ function reflectedSetValues(value) {
268
+ if (!value || typeof value !== "object") return;
269
+ try {
270
+ return Array.from(Set.prototype.values.call(value));
271
+ } catch {
272
+ return;
273
+ }
274
+ }
275
+ function isCryptoKey(value) {
276
+ if (!value || typeof value !== "object") return false;
277
+ const CryptoKeyConstructor = Object.getOwnPropertyDescriptor(globalThis, "CryptoKey")?.value;
278
+ return typeof CryptoKeyConstructor === "function" && value instanceof CryptoKeyConstructor;
279
+ }
280
+ function isWebAssemblyModule(value) {
281
+ if (!value || typeof value !== "object") return false;
282
+ const { constructor, exports } = webAssemblyModule;
283
+ if (typeof constructor !== "function") return false;
284
+ if (value instanceof constructor) return true;
285
+ try {
286
+ if (typeof exports !== "function") return false;
287
+ Reflect.apply(exports, constructor, [value]);
288
+ return true;
289
+ } catch {
290
+ return false;
291
+ }
292
+ }
293
+ function captureFunctionToString() {
294
+ return Function.prototype.toString;
295
+ }
296
+ const intrinsicFunctionToString = /* @__PURE__ */ captureFunctionToString();
297
+ function checkNativeFunctionToString() {
298
+ try {
299
+ if (Object.prototype.hasOwnProperty.call(intrinsicFunctionToString, "prototype")) return false;
300
+ if (intrinsicFunctionToString.name !== "toString" || intrinsicFunctionToString.length !== 1) return false;
301
+ if (intrinsicFunctionToString.call(intrinsicFunctionToString).replace(/\s+/g, " ") !== "function toString() { [native code] }") return false;
302
+ function probe() {
303
+ return 1;
304
+ }
305
+ if (intrinsicFunctionToString.call(probe) !== "function probe() { return 1 }") return false;
306
+ const namedProbes = [
307
+ function ArrayBuffer() {},
308
+ function SharedArrayBuffer() {},
309
+ function DataView() {},
310
+ function Memory() {}
311
+ ];
312
+ for (const namedProbe of namedProbes) if (intrinsicFunctionToString.call(namedProbe).includes("[native code]")) return false;
313
+ const getterProbe = Object.getOwnPropertyDescriptor({ get byteLength() {
314
+ return 0;
315
+ } }, "byteLength")?.get;
316
+ if (!getterProbe || intrinsicFunctionToString.call(getterProbe).includes("[native code]")) return false;
317
+ try {
318
+ intrinsicFunctionToString.call(null);
319
+ return false;
320
+ } catch {
321
+ return true;
322
+ }
323
+ } catch {
324
+ return false;
325
+ }
326
+ }
327
+ const nativeFunctionToString = /* @__PURE__ */ checkNativeFunctionToString();
328
+ function isNativeBufferOperation(value, name) {
329
+ if (!nativeFunctionToString || typeof value !== "function") return false;
330
+ try {
331
+ return intrinsicFunctionToString.call(value).replace(/\s+/g, " ") === `function ${name}() { [native code] }`;
332
+ } catch {
333
+ return false;
334
+ }
335
+ }
336
+ function captureSharedBufferByteLength() {
337
+ try {
338
+ let sample;
339
+ const constructor = Object.getOwnPropertyDescriptor(globalThis, "SharedArrayBuffer")?.value;
340
+ if (isNativeBufferOperation(constructor, "SharedArrayBuffer")) sample = Reflect.construct(constructor, [0]);
341
+ else {
342
+ const namespace = Object.getOwnPropertyDescriptor(globalThis, "WebAssembly")?.value;
343
+ if (!isRuntimeObject(namespace)) return;
344
+ const memoryConstructor = Object.getOwnPropertyDescriptor(namespace, "Memory")?.value;
345
+ if (!isNativeBufferOperation(memoryConstructor, "Memory")) return;
346
+ const memory = Reflect.construct(memoryConstructor, [{
347
+ initial: 0,
348
+ maximum: 1,
349
+ shared: true
350
+ }]);
351
+ const memoryBuffer = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(memory), "buffer")?.get;
352
+ if (!isNativeBufferOperation(memoryBuffer, "get buffer")) return;
353
+ sample = memoryBuffer.call(memory);
354
+ }
355
+ if (!isRuntimeObject(sample)) return;
356
+ const getter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(sample), "byteLength")?.get;
357
+ if (!isNativeBufferOperation(getter, "get byteLength")) return;
358
+ if (getter.call(sample) !== 0) return;
359
+ const receiverProbes = [{}, Object.create(null)];
360
+ for (const receiver of receiverProbes) try {
361
+ getter.call(receiver);
362
+ return;
363
+ } catch {}
364
+ return getter;
365
+ } catch {
366
+ return;
367
+ }
368
+ }
369
+ function captureOrdinaryBufferOperations() {
370
+ try {
371
+ const arrayBuffer = Object.getOwnPropertyDescriptor(globalThis, "ArrayBuffer")?.value;
372
+ const dataView = Object.getOwnPropertyDescriptor(globalThis, "DataView")?.value;
373
+ if (!isNativeBufferOperation(arrayBuffer, "ArrayBuffer") || !isNativeBufferOperation(dataView, "DataView")) return;
374
+ const sample = Reflect.construct(arrayBuffer, [0]);
375
+ const byteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(sample), "byteLength")?.get;
376
+ if (!isNativeBufferOperation(byteLength, "get byteLength") || byteLength.call(sample) !== 0) return;
377
+ Reflect.construct(dataView, [
378
+ sample,
379
+ 0,
380
+ 0
381
+ ]);
382
+ try {
383
+ Reflect.construct(dataView, [
384
+ {},
385
+ 0,
386
+ 0
387
+ ]);
388
+ return;
389
+ } catch {
390
+ return {
391
+ byteLength,
392
+ dataView
393
+ };
394
+ }
395
+ } catch {
396
+ return;
397
+ }
398
+ }
399
+ const sharedBufferByteLength = /* @__PURE__ */ captureSharedBufferByteLength();
400
+ const ordinaryBufferOperations = /* @__PURE__ */ captureOrdinaryBufferOperations();
401
+ function isSharedArrayBuffer(value) {
402
+ if (!value || typeof value !== "object") return false;
403
+ if (sharedBufferByteLength) try {
404
+ if (ordinaryBufferOperations) Reflect.construct(ordinaryBufferOperations.dataView, [
405
+ value,
406
+ 0,
407
+ 0
408
+ ]);
409
+ return typeof sharedBufferByteLength.call(value) === "number";
410
+ } catch {
411
+ return false;
412
+ }
413
+ if (!ordinaryBufferOperations) try {
414
+ const prototype = Object.getPrototypeOf(value);
415
+ if (prototype === Object.prototype) return false;
416
+ const tag = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag)?.value;
417
+ const byteLength = Object.getOwnPropertyDescriptor(prototype, "byteLength")?.get;
418
+ return tag === "SharedArrayBuffer" && typeof byteLength === "function";
419
+ } catch {
420
+ return true;
421
+ }
422
+ try {
423
+ Reflect.construct(ordinaryBufferOperations.dataView, [
424
+ value,
425
+ 0,
426
+ 0
427
+ ]);
428
+ try {
429
+ ordinaryBufferOperations.byteLength.call(value);
430
+ return false;
431
+ } catch {
432
+ return true;
433
+ }
434
+ } catch {
435
+ return false;
436
+ }
437
+ }
438
+ function containsSharedArrayBuffer(value, seen = /* @__PURE__ */ new Set()) {
439
+ if (!value || typeof value !== "object") return false;
440
+ if (isSharedArrayBuffer(value)) return true;
441
+ const WebAssemblyMemory = globalThis.WebAssembly?.Memory;
442
+ if (WebAssemblyMemory && value instanceof WebAssemblyMemory) return isSharedArrayBuffer(value.buffer);
443
+ if (seen.has(value)) return false;
444
+ seen.add(value);
445
+ if (ArrayBuffer.isView(value)) return containsSharedArrayBuffer(value.buffer, seen);
446
+ const mapEntries = reflectedMapEntries(value);
447
+ if (mapEntries) return mapEntries.some(([key, entry]) => containsSharedArrayBuffer(key, seen) || containsSharedArrayBuffer(entry, seen));
448
+ const setValues = reflectedSetValues(value);
449
+ if (setValues) return setValues.some((entry) => containsSharedArrayBuffer(entry, seen));
450
+ return Reflect.ownKeys(value).some((key) => {
451
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
452
+ return descriptor !== void 0 && "value" in descriptor && containsSharedArrayBuffer(descriptor.value, seen);
453
+ });
454
+ }
455
+ function reflectedRegExpState(value) {
456
+ if (!value || typeof value !== "object") return;
457
+ try {
458
+ const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get?.call(value);
459
+ const flags = Object.getOwnPropertyDescriptor(RegExp.prototype, "flags")?.get?.call(value);
460
+ const lastIndex = Reflect.get(value, "lastIndex");
461
+ if (typeof source !== "string" || typeof flags !== "string" || typeof lastIndex !== "number") return;
462
+ return {
463
+ flags,
464
+ lastIndex,
465
+ source
466
+ };
467
+ } catch {
468
+ return;
469
+ }
470
+ }
471
+ function reflectedArrayBufferViewState(value) {
472
+ if (!ArrayBuffer.isView(value)) return;
473
+ try {
474
+ const bufferConstructor = Object.getOwnPropertyDescriptor(globalThis, "Buffer")?.value ?? globalThis.Buffer;
475
+ const isBuffer = typeof bufferConstructor === "function" ? Object.getOwnPropertyDescriptor(bufferConstructor, "isBuffer")?.value : void 0;
476
+ const isNodeBuffer = typeof isBuffer === "function" && Reflect.apply(isBuffer, bufferConstructor, [value]) === true;
477
+ const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
478
+ if (isNodeBuffer) {
479
+ const byteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength")?.get?.call(value);
480
+ return typeof byteLength === "number" ? {
481
+ byteLength,
482
+ kind: "Buffer"
483
+ } : void 0;
484
+ }
485
+ const typedArrayTag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get?.call(value);
486
+ if (typeof typedArrayTag === "string") {
487
+ const byteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength")?.get?.call(value);
488
+ return typeof byteLength === "number" ? {
489
+ byteLength,
490
+ kind: typedArrayTag
491
+ } : void 0;
492
+ }
493
+ const dataViewByteLength = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength")?.get?.call(value);
494
+ return typeof dataViewByteLength === "number" ? {
495
+ byteLength: dataViewByteLength,
496
+ kind: "DataView"
497
+ } : void 0;
498
+ } catch {
499
+ return;
500
+ }
501
+ }
502
+ function reflectedBlobState(value) {
503
+ const BlobConstructor = globalThis.Blob;
504
+ if (typeof BlobConstructor !== "function" || !(value instanceof BlobConstructor)) return;
505
+ try {
506
+ const FileConstructor = globalThis.File;
507
+ const file = typeof FileConstructor === "function" && value instanceof FileConstructor ? value : void 0;
508
+ const intrinsic = file ? new FileConstructor([], "") : new BlobConstructor([]);
509
+ const size = Object.getOwnPropertyDescriptor(BlobConstructor.prototype, "size")?.get?.call(value);
510
+ const type = Object.getOwnPropertyDescriptor(BlobConstructor.prototype, "type")?.get?.call(value);
511
+ if (typeof size !== "number" || typeof type !== "string") return;
512
+ const state = {
513
+ intrinsicSymbols: new Set(Reflect.ownKeys(intrinsic).filter((key) => typeof key === "symbol" && Object.getOwnPropertyDescriptor(intrinsic, key)?.enumerable === true)),
514
+ size,
515
+ type
516
+ };
517
+ if (file) {
518
+ const lastModified = Object.getOwnPropertyDescriptor(FileConstructor.prototype, "lastModified")?.get?.call(file);
519
+ const name = Object.getOwnPropertyDescriptor(FileConstructor.prototype, "name")?.get?.call(file);
520
+ if (typeof lastModified !== "number" || typeof name !== "string") return;
521
+ state.lastModified = lastModified;
522
+ state.name = name;
523
+ }
524
+ return state;
525
+ } catch {
526
+ return;
527
+ }
528
+ }
529
+ function containsUnsafeStructuredCloneState(value, seen = /* @__PURE__ */ new Set()) {
530
+ if (!value || typeof value !== "object" || seen.has(value)) return false;
531
+ if (isCryptoKey(value) || isWebAssemblyModule(value)) return true;
532
+ seen.add(value);
533
+ for (const key of Reflect.ownKeys(value)) {
534
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
535
+ if (!descriptor?.enumerable) continue;
536
+ if (!("value" in descriptor) || containsUnsafeStructuredCloneState(descriptor.value, seen)) return true;
537
+ }
538
+ for (const key of ["cause", "errors"]) {
539
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
540
+ if (descriptor && (!("value" in descriptor) || containsUnsafeStructuredCloneState(descriptor.value, seen))) return true;
541
+ }
542
+ const mapEntries = reflectedMapEntries(value);
543
+ if (mapEntries) {
544
+ for (const [key, entry] of mapEntries) if (containsUnsafeStructuredCloneState(key, seen) || containsUnsafeStructuredCloneState(entry, seen)) return true;
545
+ } else {
546
+ const setValues = reflectedSetValues(value);
547
+ if (setValues) {
548
+ for (const entry of setValues) if (containsUnsafeStructuredCloneState(entry, seen)) return true;
549
+ }
550
+ }
551
+ return false;
552
+ }
553
+ function preservesEnumerableFields(source, snapshot, seen = /* @__PURE__ */ new Map()) {
554
+ if (!source || typeof source !== "object") return true;
555
+ if (!snapshot || typeof snapshot !== "object") return false;
556
+ if (seen.has(source)) return seen.get(source) === snapshot;
557
+ seen.set(source, snapshot);
558
+ const sourceView = reflectedArrayBufferViewState(source);
559
+ if (sourceView) {
560
+ const snapshotView = reflectedArrayBufferViewState(snapshot);
561
+ if (!snapshotView || sourceView.kind !== snapshotView.kind || sourceView.byteLength !== snapshotView.byteLength) return false;
562
+ }
563
+ if (source instanceof Date && (!(snapshot instanceof Date) || !Object.is(source.getTime(), snapshot.getTime()))) return false;
564
+ const sourceRegExp = reflectedRegExpState(source);
565
+ if (sourceRegExp) {
566
+ const snapshotRegExp = reflectedRegExpState(snapshot);
567
+ if (!snapshotRegExp || sourceRegExp.source !== snapshotRegExp.source || sourceRegExp.flags !== snapshotRegExp.flags || sourceRegExp.lastIndex !== snapshotRegExp.lastIndex) return false;
568
+ }
569
+ const sourceBlob = reflectedBlobState(source);
570
+ if (sourceBlob) {
571
+ const snapshotBlob = reflectedBlobState(snapshot);
572
+ if (!snapshotBlob || sourceBlob.size !== snapshotBlob.size || sourceBlob.type !== snapshotBlob.type || sourceBlob.name !== snapshotBlob.name || sourceBlob.lastModified !== snapshotBlob.lastModified) return false;
573
+ }
574
+ const sourceAggregateErrors = Object.getOwnPropertyDescriptor(source, "errors");
575
+ if (sourceAggregateErrors && "value" in sourceAggregateErrors) {
576
+ const snapshotAggregateErrors = Object.getOwnPropertyDescriptor(snapshot, "errors");
577
+ if (!snapshotAggregateErrors || !("value" in snapshotAggregateErrors) || !preservesEnumerableFields(sourceAggregateErrors.value, snapshotAggregateErrors.value, seen)) return false;
578
+ }
579
+ if (source instanceof AggregateError) {
580
+ if (!(snapshot instanceof AggregateError) || source.name !== snapshot.name || source.message !== snapshot.message || !preservesEnumerableFields(source.errors, snapshot.errors, seen) || !preservesEnumerableFields(source.cause, snapshot.cause, seen)) return false;
581
+ } else if (source instanceof DOMException) {
582
+ if (!(snapshot instanceof DOMException) || source.name !== snapshot.name || source.message !== snapshot.message || source.code !== snapshot.code) return false;
583
+ } else if (source instanceof Error) {
584
+ if (!(snapshot instanceof Error) || source.name !== snapshot.name || source.message !== snapshot.message || !preservesEnumerableFields(source.cause, snapshot.cause, seen)) return false;
585
+ }
586
+ for (const key of Reflect.ownKeys(source)) {
587
+ const sourceDescriptor = Object.getOwnPropertyDescriptor(source, key);
588
+ if (!sourceDescriptor?.enumerable) continue;
589
+ if (typeof key === "symbol") {
590
+ if (sourceBlob?.intrinsicSymbols.has(key)) continue;
591
+ return false;
592
+ }
593
+ if (!("value" in sourceDescriptor)) return false;
594
+ const snapshotDescriptor = Object.getOwnPropertyDescriptor(snapshot, key);
595
+ if (!snapshotDescriptor || !("value" in snapshotDescriptor)) return false;
596
+ if (!preservesEnumerableFields(sourceDescriptor.value, snapshotDescriptor.value, seen)) return false;
597
+ }
598
+ const sourceMapEntries = reflectedMapEntries(source);
599
+ if (sourceMapEntries) {
600
+ const snapshotEntries = reflectedMapEntries(snapshot);
601
+ if (!snapshotEntries || sourceMapEntries.length !== snapshotEntries.length) return false;
602
+ return sourceMapEntries.every(([key, value], index) => {
603
+ const snapshotEntry = snapshotEntries[index];
604
+ return snapshotEntry !== void 0 && preservesEnumerableFields(key, snapshotEntry[0], seen) && preservesEnumerableFields(value, snapshotEntry[1], seen);
605
+ });
606
+ }
607
+ const sourceSetValues = reflectedSetValues(source);
608
+ if (sourceSetValues) {
609
+ const snapshotValues = reflectedSetValues(snapshot);
610
+ if (!snapshotValues || sourceSetValues.length !== snapshotValues.length) return false;
611
+ return sourceSetValues.every((value, index) => preservesEnumerableFields(value, snapshotValues[index], seen));
612
+ }
613
+ return true;
614
+ }
615
+ function normalizedTracePayload(payload) {
616
+ if (payload === void 0) return;
617
+ if (!payload || typeof payload !== "object") return { visibility: "private" };
618
+ try {
619
+ if (Array.isArray(payload)) return { visibility: "private" };
620
+ const visibility = Object.getOwnPropertyDescriptor(payload, "visibility");
621
+ if (!visibility || !("value" in visibility)) return { visibility: "private" };
622
+ if (visibility.value === "public") {
623
+ const value = Object.getOwnPropertyDescriptor(payload, "value");
624
+ if (value && "value" in value && !containsUnsafeStructuredCloneState(value.value)) {
625
+ const snapshot = structuredClone(value.value);
626
+ if (preservesEnumerableFields(value.value, snapshot) && !containsSharedArrayBuffer(snapshot)) return {
627
+ value: snapshot,
628
+ visibility: "public"
629
+ };
630
+ }
631
+ }
632
+ if (visibility.value === "summary") {
633
+ const summary = Object.getOwnPropertyDescriptor(payload, "summary");
634
+ if (summary && "value" in summary && typeof summary.value === "string") return {
635
+ summary: summary.value,
636
+ visibility: "summary"
637
+ };
638
+ }
639
+ if (visibility.value === "redacted") return { visibility: "redacted" };
640
+ } catch {
641
+ return { visibility: "private" };
642
+ }
643
+ return { visibility: "private" };
644
+ }
645
+ function traceEventAttributes(event, content, normalized = false) {
646
+ const activity = normalized ? event.activity : normalizedTraceActivity(event.activity);
647
+ const payload = normalized ? event.payload : normalizedTracePayload(event.payload);
648
+ const next = { ...normalizeTraceAttributes(event.attributes, content) };
649
+ if (activity) {
650
+ next["vitehub.activity.owner"] = activity.owner;
651
+ next["vitehub.activity.phase"] = activity.phase;
652
+ }
653
+ if (payload) {
654
+ next["vitehub.payload.visibility"] = payload.visibility;
655
+ if (payload.visibility === "public") next["vitehub.payload.value"] = payload.value;
656
+ if (payload.visibility === "summary") next["vitehub.payload.summary"] = payload.summary;
657
+ }
658
+ return Object.keys(next).length ? next : void 0;
659
+ }
660
+ function aggregateTraceAttributes(attributes) {
661
+ if (!attributes) return void 0;
662
+ const next = { ...attributes };
663
+ delete next["vitehub.activity.owner"];
664
+ delete next["vitehub.activity.phase"];
665
+ delete next["vitehub.payload.summary"];
666
+ delete next["vitehub.payload.value"];
667
+ delete next["vitehub.payload.visibility"];
668
+ return Object.keys(next).length ? next : void 0;
669
+ }
670
+ function stepTraceAttributes(attributes) {
671
+ if (!attributes) return void 0;
672
+ const next = { ...attributes };
673
+ delete next["vitehub.activity.owner"];
674
+ delete next["vitehub.activity.phase"];
675
+ return Object.keys(next).length ? next : void 0;
676
+ }
677
+ function normalizeTraceEvent(event, sequence, content) {
678
+ const { activity: rawActivity, attributes: _attributes, payload: rawPayload, ...rest } = event;
679
+ const activity = normalizedTraceActivity(rawActivity);
680
+ const payload = normalizedTracePayload(rawPayload);
681
+ const attributes = traceEventAttributes({
682
+ activity,
683
+ attributes: event.attributes,
684
+ payload
685
+ }, content, true);
686
+ return {
687
+ ...rest,
688
+ ...activity ? { activity } : {},
689
+ ...attributes ? { attributes } : {},
690
+ ...payload ? { payload } : {},
691
+ sequence,
692
+ timestamp: timestamp(event.timestamp)
693
+ };
694
+ }
695
+ async function emitTraceEvent(context, event) {
696
+ return await context.traceLog?.append({
697
+ ...event,
698
+ trace: event.trace || context.trace
699
+ });
700
+ }
701
+ function createTraceEventLog(options = {}) {
702
+ const content = options.content || "metadata";
703
+ const entries = [];
704
+ const cloneAttributes = (attributes) => {
705
+ if (!attributes) return void 0;
706
+ return { ...attributes };
707
+ };
708
+ const cloneEntry = (entry) => {
709
+ const publicValue = entry.attributes?.["vitehub.payload.value"];
710
+ const cloneable = structuredClone({
711
+ activity: entry.activity,
712
+ payload: entry.payload,
713
+ publicValue
714
+ });
715
+ const attributes = cloneAttributes(entry.attributes);
716
+ if (attributes && "vitehub.payload.value" in attributes) attributes["vitehub.payload.value"] = cloneable.publicValue;
717
+ return {
718
+ ...entry,
719
+ ...cloneable.activity ? { activity: cloneable.activity } : {},
720
+ ...attributes ? { attributes } : {},
721
+ ...cloneable.payload ? { payload: cloneable.payload } : {}
722
+ };
723
+ };
724
+ return {
725
+ async append(event) {
726
+ const entry = normalizeTraceEvent(event, entries.length + 1, content);
727
+ entries.push(entry);
728
+ await options.onEntry?.(cloneEntry(entry));
729
+ return cloneEntry(entry);
730
+ },
731
+ entries() {
732
+ return entries.map(cloneEntry);
733
+ }
734
+ };
735
+ }
736
+ function millis(value) {
737
+ const parsed = Date.parse(value);
738
+ return Number.isFinite(parsed) ? parsed : 0;
739
+ }
740
+ function durationMs(startTime, endTime) {
741
+ if (!endTime) return void 0;
742
+ const duration = millis(endTime) - millis(startTime);
743
+ return Number.isFinite(duration) && duration >= 0 ? duration : void 0;
744
+ }
745
+ function firstString(...values) {
746
+ return values.find((value) => typeof value === "string" && value.length > 0);
747
+ }
748
+ function runId(event) {
749
+ return firstString(event.attributes?.["agent.run.id"], event.attributes?.["run.id"], event.attributes?.runId, event.trace?.id) || "default";
750
+ }
751
+ function stepId(event) {
752
+ return firstString(event.attributes?.["step.id"], event.attributes?.["tool.id"], event.attributes?.["approval.id"], event.attributes?.["model.call.id"]);
753
+ }
754
+ function stepStatus(event) {
755
+ return event.type === "error" || /\.(?:cancelled|error|failed)$/.test(event.name) ? "failed" : /\.(?:output|progress|request|start|started|summary|updated)$/.test(event.name) ? "running" : "completed";
756
+ }
757
+ function isTraceRunFinish(event) {
758
+ return event.name === "agent.invocation.cancelled" || event.name === "agent.invocation.finish" || event.name === "run.finish";
759
+ }
760
+ function isTraceRunError(event) {
761
+ return event.name === "agent.invocation.error" || event.name === "agent.stream.error" && event.attributes?.["error.recoverable"] !== true || event.name === "run.error";
762
+ }
763
+ function isTraceRunTerminal(event) {
764
+ return isTraceRunFinish(event) || isTraceRunError(event);
765
+ }
766
+ function isTraceRunFailureEvidence(event) {
767
+ return event.name === "run.error" || event.name === "agent.stream.error" && event.attributes?.["error.recoverable"] !== true;
768
+ }
769
+ function deriveTraceRuns(events) {
770
+ const groups = /* @__PURE__ */ new Map();
771
+ for (const event of events) {
772
+ const id = runId(event);
773
+ const group = groups.get(id);
774
+ if (group) group.push(event);
775
+ else groups.set(id, [event]);
776
+ }
777
+ return [...groups.entries()].map(([id, group]) => {
778
+ const sorted = group.sort((a, b) => a.sequence - b.sequence);
779
+ const first = sorted[0];
780
+ const steps = /* @__PURE__ */ new Map();
781
+ for (const event of sorted) {
782
+ const id = stepId(event);
783
+ if (!id) continue;
784
+ const existing = steps.get(id);
785
+ const status = stepStatus(event);
786
+ if (!existing) {
787
+ steps.set(id, {
788
+ attributes: stepTraceAttributes(event.attributes),
789
+ endTime: status === "running" ? void 0 : event.timestamp,
790
+ events: [event],
791
+ id,
792
+ name: event.name.replace(/\.(start|started|progress|finish|completed|failed|cancelled|end|error|request|decision|recorded)$/, ""),
793
+ startTime: event.timestamp,
794
+ status,
795
+ type: event.type
796
+ });
797
+ continue;
798
+ }
799
+ existing.events.push(event);
800
+ const attributes = { ...existing.attributes };
801
+ if (event.attributes?.["vitehub.payload.visibility"] !== void 0) {
802
+ delete attributes["vitehub.payload.summary"];
803
+ delete attributes["vitehub.payload.value"];
804
+ delete attributes["vitehub.payload.visibility"];
805
+ }
806
+ existing.attributes = stepTraceAttributes({
807
+ ...attributes,
808
+ ...event.attributes
809
+ });
810
+ if (status !== "running") {
811
+ existing.endTime = event.timestamp;
812
+ existing.status = status;
813
+ existing.durationMs = durationMs(existing.startTime, existing.endTime);
814
+ }
815
+ }
816
+ const terminal = sorted.slice().reverse().find(isTraceRunTerminal);
817
+ const status = sorted.some(isTraceRunFailureEvidence) || terminal && isTraceRunError(terminal) ? "failed" : terminal?.name === "agent.invocation.cancelled" ? "cancelled" : terminal ? "completed" : "running";
818
+ const endTime = status === "running" ? void 0 : terminal?.timestamp;
819
+ return {
820
+ durationMs: durationMs(first.timestamp, endTime),
821
+ endTime,
822
+ events: sorted,
823
+ id,
824
+ startTime: first.timestamp,
825
+ status,
826
+ steps: [...steps.values()]
827
+ };
828
+ });
829
+ }
830
+ function traceRunTraceId(run) {
831
+ return firstString(...run.events.map((event) => event.trace?.id), run.id) || run.id;
832
+ }
833
+ function traceRunParentId(run) {
834
+ return firstString(...run.events.map((event) => event.trace?.parentId));
835
+ }
836
+ function traceRunSpanId(run) {
837
+ return firstString(...run.events.map((event) => event.attributes?.["agent.invocation.id"]), run.id) || run.id;
838
+ }
839
+ function isOpenTelemetryId(value, length) {
840
+ return value.length === length && /^[0-9a-f]+$/.test(value);
841
+ }
842
+ function openTelemetryId(value, length) {
843
+ const normalized = value.toLowerCase();
844
+ if (isOpenTelemetryId(normalized, length)) return normalized;
845
+ let output = "";
846
+ for (let seed = 0; output.length < length; seed += 1) {
847
+ let hash = 2166136261;
848
+ const input = `${value}:${seed}`;
849
+ for (let index = 0; index < input.length; index += 1) {
850
+ hash ^= input.charCodeAt(index);
851
+ hash = Math.imul(hash, 16777619);
852
+ }
853
+ output += (hash >>> 0).toString(16).padStart(8, "0");
854
+ }
855
+ const id = output.slice(0, length);
856
+ return /^0+$/.test(id) ? `1${id.slice(1)}` : id;
857
+ }
858
+ function traceEventsToOpenTelemetryLogRecords(events, options = {}) {
859
+ return deriveTraceRuns([...events]).flatMap((run) => {
860
+ const spanId = openTelemetryId(traceRunSpanId(run), 16);
861
+ const traceId = openTelemetryId(traceRunTraceId(run), 32);
862
+ return run.events.map((event) => {
863
+ const id = stepId(event);
864
+ const attributes = traceEventAttributes(event, options.content === "metadata" ? "metadata" : "content");
865
+ const warning = event.name === "agent.stream.error" && event.attributes?.["error.recoverable"] === true;
866
+ const error = !warning && (event.type === "error" || /\.(?:cancelled|error|failed)$/.test(event.name));
867
+ return {
868
+ attributes: {
869
+ ...attributes,
870
+ "vitehub.event.sequence": event.sequence,
871
+ "vitehub.event.type": event.type,
872
+ "vitehub.run.id": run.id,
873
+ ...id ? { "vitehub.step.id": id } : {}
874
+ },
875
+ eventName: event.name,
876
+ ...warning ? {
877
+ severityNumber: 13,
878
+ severityText: "WARN"
879
+ } : error ? {
880
+ severityNumber: 17,
881
+ severityText: "ERROR"
882
+ } : {},
883
+ spanId: id ? openTelemetryId(`${spanId}:${id}`, 16) : spanId,
884
+ time: event.timestamp,
885
+ traceId
886
+ };
887
+ });
888
+ });
889
+ }
890
+ function traceEventsToOpenTelemetrySpans(events, options = {}) {
891
+ const maxEntries = 1024;
892
+ const firstEntries = maxEntries / 2;
893
+ const tailEntries = maxEntries / 2;
894
+ const entriesByRun = /* @__PURE__ */ new Map();
895
+ for (const entry of events) {
896
+ const id = runId(entry);
897
+ let run = entriesByRun.get(id);
898
+ if (!run) {
899
+ run = {
900
+ count: 0,
901
+ first: [],
902
+ tail: Array.from({ length: tailEntries })
903
+ };
904
+ entriesByRun.set(id, run);
905
+ }
906
+ const indexed = {
907
+ entry,
908
+ index: run.count
909
+ };
910
+ if (run.count < firstEntries) run.first.push(indexed);
911
+ else run.tail[(run.count - firstEntries) % tailEntries] = indexed;
912
+ if (isTraceRunFailureEvidence(entry)) run.failure = indexed;
913
+ if (isTraceRunTerminal(entry)) run.terminal = indexed;
914
+ run.count += 1;
915
+ }
916
+ return deriveTraceRuns([...entriesByRun.values()].flatMap((run) => {
917
+ const tail = run.tail.filter((entry) => entry !== void 0).sort((left, right) => left.index - right.index);
918
+ const evidence = [run.failure, run.terminal].filter((entry) => entry !== void 0);
919
+ const indexed = run.count <= maxEntries ? [...run.first, ...tail] : [
920
+ ...run.first,
921
+ ...tail.slice(evidence.length),
922
+ ...evidence
923
+ ];
924
+ const entries = [...new Map(indexed.map((value) => [value.index, value])).values()].sort((left, right) => left.index - right.index).map((value) => value.entry);
925
+ if (run.count <= maxEntries) return entries;
926
+ return entries.map((entry, index) => index === 0 ? {
927
+ ...entry,
928
+ attributes: {
929
+ ...entry.attributes,
930
+ "vitehub.trace.originalEventCount": run.count,
931
+ "vitehub.trace.truncated": true
932
+ }
933
+ } : entry);
934
+ }).map((entry) => ({
935
+ ...entry,
936
+ attributes: traceEventAttributes(entry, options.content === "metadata" ? "metadata" : "content")
937
+ }))).flatMap((run) => {
938
+ const rawParentSpanId = traceRunParentId(run);
939
+ const rawTraceId = traceRunTraceId(run);
940
+ const parentSpanId = rawParentSpanId ? openTelemetryId(rawParentSpanId, 16) : void 0;
941
+ const spanId = openTelemetryId(traceRunSpanId(run), 16);
942
+ const traceId = openTelemetryId(rawTraceId, 32);
943
+ const attributes = aggregateTraceAttributes(Object.assign({}, ...run.events.filter((event) => !stepId(event)).map((event) => event.attributes || {})));
944
+ const spanEvents = (events) => events.map((event) => ({
945
+ ...event.attributes ? { attributes: event.attributes } : {},
946
+ name: event.name,
947
+ time: event.timestamp
948
+ }));
949
+ const errorMessage = firstString(...run.events.slice().reverse().map((event) => event.attributes?.["error.message"]));
950
+ return [{
951
+ attributes: {
952
+ ...attributes,
953
+ "vitehub.run.id": run.id,
954
+ ...rawParentSpanId ? { "vitehub.trace.parentId": rawParentSpanId } : {},
955
+ "vitehub.trace.id": rawTraceId
956
+ },
957
+ endTime: run.endTime,
958
+ events: spanEvents(run.events.filter((event) => !stepId(event))),
959
+ name: "vitehub.run",
960
+ ...parentSpanId ? { parentSpanId } : {},
961
+ spanId,
962
+ startTime: run.startTime,
963
+ status: {
964
+ code: run.status === "failed" ? "ERROR" : run.status === "completed" ? "OK" : "UNSET",
965
+ ...run.status === "failed" && errorMessage ? { message: errorMessage } : {}
966
+ },
967
+ traceId
968
+ }, ...run.steps.map((step) => ({
969
+ attributes: {
970
+ ...aggregateTraceAttributes(step.attributes),
971
+ "vitehub.run.id": run.id,
972
+ "vitehub.step.id": step.id
973
+ },
974
+ endTime: step.endTime || run.endTime,
975
+ events: spanEvents(step.events),
976
+ name: step.name,
977
+ parentSpanId: spanId,
978
+ spanId: openTelemetryId(`${spanId}:${step.id}`, 16),
979
+ startTime: step.startTime,
980
+ status: {
981
+ code: step.status === "failed" || !step.endTime && run.status === "failed" ? "ERROR" : step.endTime || run.status === "completed" ? "OK" : "UNSET",
982
+ ...typeof step.attributes?.["error.message"] === "string" ? { message: step.attributes["error.message"] } : {}
983
+ },
984
+ traceId
985
+ }))];
986
+ });
987
+ }
988
+ function createExecutionContext(context) {
989
+ const capabilities = context.capabilities ?? {};
990
+ const runtimeConfig = context.runtimeConfig ?? {};
991
+ return {
992
+ ...context,
993
+ capabilities,
994
+ runtimeConfig
995
+ };
996
+ }
997
+ /** Create one operation's context. Without a host waitUntil, drain work before returning. */
998
+ function createRuntimeContext(input) {
999
+ const values = /* @__PURE__ */ new Map();
1000
+ const memo = input.memo ?? ((key, create) => {
1001
+ if (!values.has(key)) values.set(key, create());
1002
+ return values.get(key);
1003
+ });
1004
+ const controller = createRuntimeWaitUntilController({ forward: input.waitUntil?.bind(input) });
1005
+ return createExecutionContext({
1006
+ ...input,
1007
+ ...controller,
1008
+ memo
1009
+ });
1010
+ }
1011
+ function defineCapability(kind, value, options = {}) {
1012
+ const handle = {
1013
+ kind,
1014
+ name: options.name,
1015
+ value
1016
+ };
1017
+ capabilityHandles.add(handle);
1018
+ return handle;
1019
+ }
1020
+ function createRuntimeWaitUntilController(options = {}) {
1021
+ const pending = [];
1022
+ let flushing;
1023
+ return {
1024
+ flushWaitUntil() {
1025
+ flushing ??= Promise.resolve().then(async () => {
1026
+ try {
1027
+ let error;
1028
+ let failed = false;
1029
+ while (pending.length > 0) await Promise.all(pending.splice(0).map(async (task) => {
1030
+ try {
1031
+ await task;
1032
+ } catch (reason) {
1033
+ if (failed) return;
1034
+ error = reason;
1035
+ failed = true;
1036
+ }
1037
+ }));
1038
+ if (failed) throw error;
1039
+ } finally {
1040
+ flushing = void 0;
1041
+ }
1042
+ });
1043
+ return flushing;
1044
+ },
1045
+ waitUntil(task) {
1046
+ task.catch(() => {});
1047
+ pending.push(task);
1048
+ options.forward?.(task);
1049
+ }
1050
+ };
1051
+ }
1052
+ const capabilityHandles = /* @__PURE__ */ new WeakSet();
1053
+ function isProxy(value) {
1054
+ try {
1055
+ const getBuiltinModule = globalThis.process?.getBuiltinModule;
1056
+ const detector = getBuiltinModule?.("node:util")?.types?.isProxy;
1057
+ return detector ? detector(value) : void 0;
1058
+ } catch {
1059
+ return;
1060
+ }
1061
+ }
1062
+ function isCapabilityHandle(value) {
1063
+ if (typeof value !== "object" || value === null) return false;
1064
+ if (capabilityHandles.has(value)) return true;
1065
+ if (isProxy(value) === true) return false;
1066
+ try {
1067
+ const descriptors = Object.getOwnPropertyDescriptors(value);
1068
+ const kind = descriptors.kind;
1069
+ const implementation = descriptors.value;
1070
+ if (!kind || !Object.hasOwn(kind, "value") || typeof kind.value !== "string" || !implementation || !Object.hasOwn(implementation, "value")) return false;
1071
+ if (Object.getPrototypeOf(value) === null) return false;
1072
+ let prototype = Object.getPrototypeOf(value);
1073
+ while (prototype !== null) {
1074
+ if (Object.getOwnPropertyDescriptor(prototype, "kind") || Object.getOwnPropertyDescriptor(prototype, "value")) return false;
1075
+ prototype = Object.getPrototypeOf(prototype);
1076
+ }
1077
+ return true;
1078
+ } catch {
1079
+ return false;
1080
+ }
1081
+ }
1082
+ function hasCapability(context, name) {
1083
+ return !!context.capabilities && Object.hasOwn(context.capabilities, name);
1084
+ }
1085
+ function getCapability(context, name) {
1086
+ const value = hasCapability(context, name) ? context.capabilities?.[name] : void 0;
1087
+ if (value === void 0) throw new ViteHubError("CAPABILITY_NOT_FOUND", `[vitehub:runtime] Capability "${name}" was not found.`, { details: { capability: name } });
1088
+ if (isCapabilityHandle(value)) return value;
1089
+ return defineCapability(name, value, { name });
1090
+ }
1091
+ function isResolvable(value) {
1092
+ return typeof value === "object" && value !== null && "resolve" in value && typeof value.resolve === "function";
1093
+ }
1094
+ async function resolveRuntimeValue(value, context) {
1095
+ if (isResolvable(value)) return await value.resolve(context);
1096
+ if (typeof value === "function") return await value(context);
1097
+ return value;
1098
+ }
1099
+ async function resolveCapabilityPolicy(policy, context) {
1100
+ if (!policy) return "allow";
1101
+ return typeof policy === "function" ? await policy(context) : policy;
1102
+ }
1103
+ export { traceEventsToOpenTelemetrySpans as _, defineCapability as a, getCapability as c, isResolvable as d, noExecutionAuthority as f, traceEventsToOpenTelemetryLogRecords as g, resolveRuntimeValue as h, createTraceEventLog as i, hasCapability as l, resolveCapabilityPolicy as m, createRuntimeContext as n, deriveTraceRuns as o, normalizeExecutionAuthority as p, createRuntimeWaitUntilController as r, emitTraceEvent as s, createExecutionContext as t, isExecutionAuthority as u, unknownExecutionAuthority as v, isTraceContentAttributeKey as y };