@withgateway/sdk 0.2.9 → 0.3.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 (58) hide show
  1. package/README.md +5 -1
  2. package/dist/cli.js +3812 -1158
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +3796 -1142
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.d.mts +1 -0
  7. package/dist/files/index.d.ts +1 -0
  8. package/dist/files/index.js +1358 -21
  9. package/dist/files/index.js.map +1 -1
  10. package/dist/files/index.mjs +1356 -13
  11. package/dist/files/index.mjs.map +1 -1
  12. package/dist/{index-BO2SNSgy.d.ts → index-CBqbB_0J.d.ts} +95 -46
  13. package/dist/{index-Cz8Q6Keo.d.mts → index-D-AMnAMa.d.mts} +95 -46
  14. package/dist/index.d.mts +4 -3
  15. package/dist/index.d.ts +4 -3
  16. package/dist/index.js +1942 -177
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +1890 -146
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/media-CbcAfQvd.d.mts +83 -0
  21. package/dist/media-CbcAfQvd.d.ts +83 -0
  22. package/dist/traces/index.d.mts +1 -0
  23. package/dist/traces/index.d.ts +1 -0
  24. package/dist/traces/index.js +1355 -18
  25. package/dist/traces/index.js.map +1 -1
  26. package/dist/traces/index.mjs +1353 -10
  27. package/dist/traces/index.mjs.map +1 -1
  28. package/dist/tracing/index.d.mts +2 -1
  29. package/dist/tracing/index.d.ts +2 -1
  30. package/dist/tracing/index.js +550 -30
  31. package/dist/tracing/index.js.map +1 -1
  32. package/dist/tracing/index.mjs +539 -29
  33. package/dist/tracing/index.mjs.map +1 -1
  34. package/dist/worlds/index.d.mts +648 -80
  35. package/dist/worlds/index.d.ts +648 -80
  36. package/dist/worlds/index.js +1875 -145
  37. package/dist/worlds/index.js.map +1 -1
  38. package/dist/worlds/index.mjs +1861 -131
  39. package/dist/worlds/index.mjs.map +1 -1
  40. package/package.json +1 -1
  41. package/runtime/gatewaysdk/environment/schema/api.py +43 -62
  42. package/runtime/gatewaysdk/environment/schema/cast.py +31 -4
  43. package/runtime/gatewaysdk/environment/schema/grading.py +1 -5
  44. package/runtime/gatewaysdk/environment/schema/host.py +53 -90
  45. package/runtime/gatewaysdk/environment/schema/local.py +15 -7
  46. package/runtime/gatewaysdk/environment/schema/platform.py +1 -7
  47. package/runtime/gatewaysdk/environment/schema/runtime.py +9 -9
  48. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +3 -3
  49. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +2 -2
  50. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +13 -13
  51. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +2 -1
  52. package/runtime/gatewaysdk/environment/schema/tasks.py +25 -1
  53. package/skills/connector-schema-authoring/SKILL.md +3 -3
  54. package/skills/connector-schema-authoring/connector-worlds.md +12 -5
  55. package/skills/connector-schema-authoring/world-schema.md +8 -0
  56. package/skills/world-data-ingestion/SKILL.md +2 -2
  57. package/skills/worlds-getting-started/SKILL.md +13 -13
  58. package/skills/worlds-getting-started/references/cli-mcp-map.md +2 -1
@@ -20,7 +20,7 @@ var require_package = __commonJS({
20
20
  "package.json"(exports, module) {
21
21
  module.exports = {
22
22
  name: "@withgateway/sdk",
23
- version: "0.2.9",
23
+ version: "0.3.1",
24
24
  description: "Gateway SDK for TypeScript - A/B experiments, tracing, and observability",
25
25
  main: "./dist/index.js",
26
26
  module: "./dist/index.mjs",
@@ -486,26 +486,267 @@ function debugLog(message, ...args) {
486
486
  }
487
487
  }
488
488
 
489
+ // src/tracing/secrets.ts
490
+ var SECRET_KEYS = /* @__PURE__ */ new Set([
491
+ "authorization_token",
492
+ "authorizationToken"
493
+ ]);
494
+ var REDACTED = "[redacted: holds a credential]";
495
+ var MIN_SECRET_LENGTH = 8;
496
+ var SpanSecrets = class {
497
+ constructor(keys = SECRET_KEYS) {
498
+ this.keys = keys;
499
+ }
500
+ keys;
501
+ isSecret(key) {
502
+ return this.keys.has(key);
503
+ }
504
+ drops(attribute) {
505
+ return this.mentions(attribute);
506
+ }
507
+ strip(value) {
508
+ if (typeof value === "string") return this.stripNested(value);
509
+ if (Array.isArray(value)) return value.map((item) => this.strip(item));
510
+ if (value === null || typeof value !== "object") return value;
511
+ return Object.fromEntries(
512
+ Object.entries(value).filter(([key]) => !this.isSecret(key)).map(([key, item]) => [key, this.strip(item)])
513
+ );
514
+ }
515
+ scrubAttribute(value) {
516
+ try {
517
+ return this.scrubbedValue(value);
518
+ } catch {
519
+ return Array.isArray(value) ? [REDACTED] : REDACTED;
520
+ }
521
+ }
522
+ scrubbedValue(value) {
523
+ if (typeof value === "string") return this.scrubbedText(value);
524
+ if (!Array.isArray(value)) return value;
525
+ const results = value.map(
526
+ (item) => typeof item === "string" ? this.cleaned(item) : { text: item, removed: /* @__PURE__ */ new Set() }
527
+ );
528
+ const removed = new Set(results.flatMap((r) => [...r.removed]));
529
+ const scrubbed = results.map((r) => r.text);
530
+ const withheld = scrubbed.some(
531
+ (item) => typeof item === "string" && this.carries(item, removed)
532
+ );
533
+ return withheld ? [REDACTED] : scrubbed;
534
+ }
535
+ scrubAttributes(attributes) {
536
+ return Object.fromEntries(
537
+ Object.entries(attributes).filter(([key]) => !this.drops(key)).map(([key, value]) => [key, this.scrubAttribute(value)])
538
+ );
539
+ }
540
+ mentions(text) {
541
+ return [...this.keys].some((key) => text.includes(key));
542
+ }
543
+ scrubbedText(text) {
544
+ const { text: cleaned, removed } = this.cleaned(text);
545
+ return this.carries(cleaned, removed) ? REDACTED : cleaned;
546
+ }
547
+ cleaned(text) {
548
+ if (!this.mentions(text)) return { text, removed: /* @__PURE__ */ new Set() };
549
+ const parsed = jsonOrUndefined(text);
550
+ if (parsed === void 0) return { text: REDACTED, removed: /* @__PURE__ */ new Set() };
551
+ return {
552
+ text: JSON.stringify(this.strip(parsed)),
553
+ removed: this.removed(parsed)
554
+ };
555
+ }
556
+ carries(text, removed) {
557
+ if (text === REDACTED || this.mentions(text)) return true;
558
+ return [...removed].some(
559
+ (value) => encodings(value).some((form) => text.includes(form))
560
+ );
561
+ }
562
+ removed(value) {
563
+ if (typeof value === "string") {
564
+ const nested = this.mentions(value) ? jsonOrUndefined(value) : void 0;
565
+ return nested === void 0 ? /* @__PURE__ */ new Set() : this.removed(nested);
566
+ }
567
+ if (Array.isArray(value)) return union(value.map((v) => this.removed(v)));
568
+ if (value === null || typeof value !== "object") return /* @__PURE__ */ new Set();
569
+ return union(
570
+ Object.entries(value).map(
571
+ ([key, item]) => this.isSecret(key) ? leaves(item) : this.removed(item)
572
+ )
573
+ );
574
+ }
575
+ stripNested(text) {
576
+ if (!this.mentions(text)) return text;
577
+ const parsed = jsonOrUndefined(text);
578
+ if (parsed === void 0) return text;
579
+ return JSON.stringify(this.strip(parsed));
580
+ }
581
+ };
582
+ function jsonOrUndefined(text) {
583
+ let parsed;
584
+ try {
585
+ parsed = JSON.parse(text);
586
+ } catch {
587
+ return void 0;
588
+ }
589
+ if (typeof parsed === "string") return parsed;
590
+ return parsed !== null && typeof parsed === "object" ? parsed : void 0;
591
+ }
592
+ function encodings(value) {
593
+ return [value, percentEncoded(value), JSON.stringify(value).slice(1, -1)];
594
+ }
595
+ function percentEncoded(value) {
596
+ try {
597
+ return encodeURIComponent(value);
598
+ } catch {
599
+ return value;
600
+ }
601
+ }
602
+ function union(sets) {
603
+ return new Set(sets.flatMap((set) => [...set]));
604
+ }
605
+ function leaves(value) {
606
+ if (typeof value === "string") {
607
+ return [...value].length >= MIN_SECRET_LENGTH ? /* @__PURE__ */ new Set([value]) : /* @__PURE__ */ new Set();
608
+ }
609
+ if (Array.isArray(value)) return union(value.map(leaves));
610
+ if (value === null || typeof value !== "object") return /* @__PURE__ */ new Set();
611
+ return union(Object.values(value).map(leaves));
612
+ }
613
+ var SPAN_SECRETS = new SpanSecrets();
614
+ function sameAttributes(before, after) {
615
+ const keys = Object.keys(before);
616
+ if (keys.length !== Object.keys(after).length) return false;
617
+ return keys.every(
618
+ (key) => before[key] === after[key] || sameArray(before[key], after[key])
619
+ );
620
+ }
621
+ function sameArray(before, after) {
622
+ if (!Array.isArray(before) || !Array.isArray(after)) return false;
623
+ return before.length === after.length && before.every((item, i) => item === after[i]);
624
+ }
625
+ var SecretRedactingSpanProcessor = class {
626
+ constructor(inner, secrets = SPAN_SECRETS) {
627
+ this.inner = inner;
628
+ this.secrets = secrets;
629
+ }
630
+ inner;
631
+ secrets;
632
+ views = /* @__PURE__ */ new WeakMap();
633
+ onStart(span, parentContext) {
634
+ this.inner.onStart(this.viewFor(span), parentContext);
635
+ }
636
+ onEnd(span) {
637
+ const view = this.viewFor(span);
638
+ try {
639
+ void [view.attributes, view.events, view.status];
640
+ } catch (error) {
641
+ console.warn(
642
+ `[gatewaysdk.tracing] Dropped span "${span.name}": could not redact it: ${error?.name}`
643
+ );
644
+ return;
645
+ }
646
+ this.inner.onEnd(view);
647
+ }
648
+ viewFor(span) {
649
+ const known = this.views.get(span);
650
+ if (known) return known;
651
+ const view = viewOf(span, {
652
+ attributes: () => this.scrubbedAttributes(span.attributes),
653
+ events: () => span.events.map((event) => this.scrubbedEvent(event)),
654
+ status: () => this.scrubbedStatus(span.status)
655
+ });
656
+ this.views.set(span, view);
657
+ return view;
658
+ }
659
+ forceFlush() {
660
+ return this.inner.forceFlush();
661
+ }
662
+ shutdown() {
663
+ return this.inner.shutdown();
664
+ }
665
+ scrubbedAttributes(attributes) {
666
+ const clean = this.secrets.scrubAttributes(attributes);
667
+ return sameAttributes(attributes, clean) ? attributes : clean;
668
+ }
669
+ scrubbedStatus(status) {
670
+ if (!status.message) return status;
671
+ const message = this.secrets.scrubAttribute(status.message);
672
+ return message === status.message ? status : { ...status, message };
673
+ }
674
+ scrubbedEvent(event) {
675
+ if (!event.attributes) return event;
676
+ const attributes = this.scrubbedAttributes(event.attributes);
677
+ if (attributes === event.attributes) return event;
678
+ return { ...event, attributes };
679
+ }
680
+ };
681
+ function scrubbedRead(reads, property) {
682
+ return typeof property === "string" && property in reads ? reads[property] : void 0;
683
+ }
684
+ function viewOf(span, reads) {
685
+ const view = new Proxy(span, {
686
+ get(target, property) {
687
+ const read = scrubbedRead(reads, property);
688
+ if (read) return read();
689
+ const value = Reflect.get(target, property, target);
690
+ if (typeof value !== "function") return value;
691
+ return (...args) => {
692
+ const result = value.apply(target, args);
693
+ return result === target ? view : result;
694
+ };
695
+ },
696
+ getOwnPropertyDescriptor(target, property) {
697
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, property);
698
+ const read = scrubbedRead(reads, property);
699
+ if (!read || !descriptor || !("value" in descriptor)) return descriptor;
700
+ return { ...descriptor, value: read() };
701
+ }
702
+ });
703
+ return view;
704
+ }
705
+
489
706
  // src/tracing/session.ts
490
707
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
491
708
  var SESSION_ID_ATTRIBUTE = "gateway.session.id";
492
- var currentSessionStorage = new AsyncLocalStorage2();
709
+ var WORLD_SESSION_ID_ATTRIBUTE = "gateway.trace.metadata.world_session_id";
710
+ var processStorage = (name) => {
711
+ const key = /* @__PURE__ */ Symbol.for(`@withgateway/sdk/${name}`);
712
+ const slots = globalThis;
713
+ slots[key] ??= new AsyncLocalStorage2();
714
+ return slots[key];
715
+ };
716
+ var currentSessionStorage = processStorage("session-storage");
717
+ var currentWorldSessionStorage = processStorage("world-session-storage");
493
718
  function getAmbientSessionId() {
494
719
  return currentSessionStorage.getStore();
495
720
  }
496
- function withSession(sessionId, fn) {
721
+ function getCurrentWorldSessionId() {
722
+ return currentWorldSessionStorage.getStore();
723
+ }
724
+ function runIn(storage, value, fn) {
497
725
  return new Promise((resolve, reject) => {
498
- currentSessionStorage.run(sessionId, () => {
726
+ storage.run(value, () => {
499
727
  Promise.resolve().then(fn).then(resolve, reject);
500
728
  });
501
729
  });
502
730
  }
731
+ function withSession(sessionId, fn) {
732
+ return runIn(currentSessionStorage, sessionId, fn);
733
+ }
734
+ function withWorldSession(worldSessionId, fn) {
735
+ return runIn(
736
+ currentWorldSessionStorage,
737
+ worldSessionId,
738
+ () => withSession(worldSessionId, fn)
739
+ );
740
+ }
503
741
  var SessionSpanProcessor = class {
504
742
  onStart(span, _parentContext) {
743
+ const worldSessionId = getCurrentWorldSessionId();
744
+ if (worldSessionId)
745
+ span.setAttribute(WORLD_SESSION_ID_ATTRIBUTE, worldSessionId);
505
746
  const sessionId = getAmbientSessionId();
506
- if (sessionId) {
507
- span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);
508
- }
747
+ if (!sessionId || span.attributes?.[SESSION_ID_ATTRIBUTE] !== void 0)
748
+ return;
749
+ span.setAttribute(SESSION_ID_ATTRIBUTE, sessionId);
509
750
  }
510
751
  onEnd(_span) {
511
752
  }
@@ -919,22 +1160,49 @@ async function registerBuild(params) {
919
1160
  }
920
1161
  }
921
1162
 
922
- // src/tracing/init.ts
923
- var ENV_VARS = {
1163
+ // src/tracing/prerequisites.ts
1164
+ var GATEWAY_ENV = {
924
1165
  HOST: "GATEWAY_HOST",
925
1166
  PUBLIC_KEY: "GATEWAY_PUBLIC_KEY",
926
1167
  SECRET_KEY: "GATEWAY_SECRET_KEY",
927
1168
  ENDPOINT: "GATEWAY_OTLP_ENDPOINT"
928
1169
  };
1170
+ var OPENTELEMETRY_PEERS = [
1171
+ "@opentelemetry/api",
1172
+ "@opentelemetry/exporter-trace-otlp-http",
1173
+ "@opentelemetry/resources",
1174
+ "@opentelemetry/sdk-trace-base",
1175
+ "@opentelemetry/sdk-trace-node"
1176
+ ];
1177
+ var MODULE_NOT_FOUND = /* @__PURE__ */ new Set(["MODULE_NOT_FOUND", "ERR_MODULE_NOT_FOUND"]);
1178
+ function getEnv(key) {
1179
+ const value = process.env[key];
1180
+ return value ? value : void 0;
1181
+ }
1182
+ function isGatewayConfigured() {
1183
+ return !!(getEnv(GATEWAY_ENV.HOST) && getEnv(GATEWAY_ENV.PUBLIC_KEY) && getEnv(GATEWAY_ENV.SECRET_KEY));
1184
+ }
1185
+ var OpenTelemetryMissing = class _OpenTelemetryMissing extends Error {
1186
+ constructor() {
1187
+ super(
1188
+ `OpenTelemetry packages not found. Install them with:
1189
+ npm install ${OPENTELEMETRY_PEERS.join(" ")}`
1190
+ );
1191
+ this.name = "OpenTelemetryMissing";
1192
+ }
1193
+ static explains(error) {
1194
+ if (error instanceof _OpenTelemetryMissing) return true;
1195
+ const { code, message } = error ?? {};
1196
+ return MODULE_NOT_FOUND.has(String(code)) && String(message).includes("@opentelemetry/");
1197
+ }
1198
+ };
1199
+
1200
+ // src/tracing/init.ts
929
1201
  var DEFAULT_OTLP_PATH = "/api/public/otel/v1/traces";
930
1202
  var state = {
931
1203
  initialized: false,
932
1204
  provider: null
933
1205
  };
934
- function getEnv(key) {
935
- const value = process.env[key];
936
- return value ? value : void 0;
937
- }
938
1206
  function log(message, ...args) {
939
1207
  if (state.debug) {
940
1208
  console.log(`[gatewaysdk.tracing] ${message}`, ...args);
@@ -944,10 +1212,10 @@ function warn(message, ...args) {
944
1212
  console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
945
1213
  }
946
1214
  function buildProvider(config, logFn) {
947
- const host = config.host ?? getEnv(ENV_VARS.HOST);
948
- const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);
949
- const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);
950
- const endpoint = config.endpoint ?? getEnv(ENV_VARS.ENDPOINT) ?? (host ? `${host.replace(/\/$/, "")}${DEFAULT_OTLP_PATH}` : void 0);
1215
+ const host = config.host ?? getEnv(GATEWAY_ENV.HOST);
1216
+ const publicKey = config.publicKey ?? getEnv(GATEWAY_ENV.PUBLIC_KEY);
1217
+ const secretKey = config.secretKey ?? getEnv(GATEWAY_ENV.SECRET_KEY);
1218
+ const endpoint = config.endpoint ?? getEnv(GATEWAY_ENV.ENDPOINT) ?? (host ? `${host.replace(/\/$/, "")}${DEFAULT_OTLP_PATH}` : void 0);
951
1219
  const missing = [];
952
1220
  if (!host) missing.push("host (or GATEWAY_HOST env var)");
953
1221
  if (!publicKey) missing.push("publicKey (or GATEWAY_PUBLIC_KEY env var)");
@@ -984,9 +1252,7 @@ function buildProvider(config, logFn) {
984
1252
  ATTR_SERVICE_NAME = "service.name";
985
1253
  }
986
1254
  } catch {
987
- throw new Error(
988
- "OpenTelemetry packages not found. Install them with:\nnpm install @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources"
989
- );
1255
+ throw new OpenTelemetryMissing();
990
1256
  }
991
1257
  const resourceAttrs = {
992
1258
  [ATTR_SERVICE_NAME]: config.serviceName ?? "gatewaysdk-tracing"
@@ -1042,7 +1308,7 @@ function buildProvider(config, logFn) {
1042
1308
  const spanProcessors = [];
1043
1309
  if (config.customSpanProcessors) {
1044
1310
  for (const sp of config.customSpanProcessors) {
1045
- spanProcessors.push(sp);
1311
+ spanProcessors.push(new SecretRedactingSpanProcessor(sp));
1046
1312
  logFn(
1047
1313
  "Added custom span processor: %s",
1048
1314
  sp.constructor?.name ?? "unknown"
@@ -1061,7 +1327,11 @@ function buildProvider(config, logFn) {
1061
1327
  if (config.batch?.maxExportBatchSize) {
1062
1328
  batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;
1063
1329
  }
1064
- spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));
1330
+ spanProcessors.push(
1331
+ new SecretRedactingSpanProcessor(
1332
+ new BatchSpanProcessor(exporter, batchConfig)
1333
+ )
1334
+ );
1065
1335
  let provider = new NodeTracerProvider({
1066
1336
  resource: createResource(resourceAttrs)
1067
1337
  });
@@ -1188,12 +1458,6 @@ async function shutdown() {
1188
1458
  function isInitialized() {
1189
1459
  return state.initialized;
1190
1460
  }
1191
- function isGatewayConfigured() {
1192
- const host = getEnv(ENV_VARS.HOST);
1193
- const publicKey = getEnv(ENV_VARS.PUBLIC_KEY);
1194
- const secretKey = getEnv(ENV_VARS.SECRET_KEY);
1195
- return !!(host && publicKey && secretKey);
1196
- }
1197
1461
 
1198
1462
  // src/tracing/observe.ts
1199
1463
  import { trace as trace3, context, SpanStatusCode } from "@opentelemetry/api";
@@ -1455,13 +1719,258 @@ async function* observeClaude(stream, options) {
1455
1719
  }
1456
1720
  }
1457
1721
  }
1722
+
1723
+ // src/tracing/media.ts
1724
+ import { createHash as createHash2 } from "crypto";
1725
+
1726
+ // src/worlds/transport.ts
1727
+ var PLATFORM_TIMEOUT_ENV = "GATEWAY_TIMEOUT_MS";
1728
+ var PLATFORM_TIMEOUT_DEFAULT_MS = 12e4;
1729
+ function platformTimeoutMs(env = process.env) {
1730
+ const raw = env[PLATFORM_TIMEOUT_ENV];
1731
+ if (raw === void 0 || raw === "") return PLATFORM_TIMEOUT_DEFAULT_MS;
1732
+ const value = Number(raw);
1733
+ if (Number.isInteger(value) && value > 0) return value;
1734
+ throw new Error(`${PLATFORM_TIMEOUT_ENV} must be a positive whole number of milliseconds, not \`${raw}\`.`);
1735
+ }
1736
+ var CHECK_HOST = "Check GATEWAY_HOST (or --host) points at a running platform, then retry.";
1737
+ var RETRY = "Retry; if it repeats, check the network between here and the platform.";
1738
+ var CAUSES = {
1739
+ ECONNREFUSED: { reason: "connection refused", next: CHECK_HOST },
1740
+ ENOTFOUND: { reason: "DNS lookup failed", next: CHECK_HOST },
1741
+ EAI_AGAIN: { reason: "DNS lookup failed", next: CHECK_HOST },
1742
+ ETIMEDOUT: { reason: "connect timed out", next: CHECK_HOST },
1743
+ UND_ERR_CONNECT_TIMEOUT: { reason: "connect timed out", next: CHECK_HOST },
1744
+ EHOSTUNREACH: { reason: "host unreachable", next: CHECK_HOST },
1745
+ ENETUNREACH: { reason: "network unreachable", next: RETRY },
1746
+ ECONNRESET: { reason: "connection dropped", next: RETRY },
1747
+ UND_ERR_SOCKET: { reason: "connection dropped", next: RETRY },
1748
+ EPIPE: { reason: "connection dropped", next: RETRY }
1749
+ };
1750
+ var UNKNOWN_CAUSE = { reason: "network error", next: CHECK_HOST };
1751
+ var TransportCause = class _TransportCause {
1752
+ constructor(reason, detail, next) {
1753
+ this.reason = reason;
1754
+ this.detail = detail;
1755
+ this.next = next;
1756
+ }
1757
+ reason;
1758
+ detail;
1759
+ next;
1760
+ static timeout(timeoutMs) {
1761
+ return new _TransportCause(
1762
+ `timed out after ${timeoutMs / 1e3}s`,
1763
+ null,
1764
+ `Retry; if the platform is slow, raise ${PLATFORM_TIMEOUT_ENV} (milliseconds per request).`
1765
+ );
1766
+ }
1767
+ static of(error) {
1768
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : void 0;
1769
+ const code = cause && "code" in cause && typeof cause.code === "string" ? cause.code : null;
1770
+ const message = cause?.message ?? (error instanceof Error ? error.message : String(error));
1771
+ const known = code && CAUSES[code] || UNKNOWN_CAUSE;
1772
+ return new _TransportCause(known.reason, code ? `${code}: ${message}` : message, known.next);
1773
+ }
1774
+ describe() {
1775
+ return this.detail === null ? this.reason : `${this.reason} (${this.detail})`;
1776
+ }
1777
+ };
1778
+ var UnreachableError = class extends Error {
1779
+ constructor(host, method, route, failure) {
1780
+ super(`${method} ${route}: no answer from ${host}: ${failure.describe()}. ${failure.next}`);
1781
+ this.host = host;
1782
+ this.method = method;
1783
+ this.route = route;
1784
+ this.failure = failure;
1785
+ this.name = "UnreachableError";
1786
+ }
1787
+ host;
1788
+ method;
1789
+ route;
1790
+ failure;
1791
+ };
1792
+ var PlatformTransport = class {
1793
+ constructor(endpoint, timeoutMs = platformTimeoutMs()) {
1794
+ this.endpoint = endpoint;
1795
+ this.timeoutMs = timeoutMs;
1796
+ }
1797
+ endpoint;
1798
+ timeoutMs;
1799
+ /** A request that legitimately takes longer (a sandbox exec, a world create) waits its own budget; every other one waits the default. */
1800
+ budget(ownMs) {
1801
+ return Math.max(ownMs ?? 0, this.timeoutMs);
1802
+ }
1803
+ async send(method, route, body, opts = {}) {
1804
+ const timeoutMs = this.budget(opts.timeoutMs);
1805
+ const payload = body === void 0 ? {} : { body: JSON.stringify(body) };
1806
+ const controller = new AbortController();
1807
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1808
+ try {
1809
+ const res = await fetch(`${this.endpoint.host}${route}`, {
1810
+ method,
1811
+ headers: {
1812
+ "content-type": "application/json",
1813
+ accept: "application/json",
1814
+ authorization: "Basic " + Buffer.from(`${this.endpoint.publicKey}:${this.endpoint.secretKey}`).toString("base64")
1815
+ },
1816
+ ...payload,
1817
+ signal: controller.signal
1818
+ });
1819
+ return { status: res.status, ok: res.ok, text: await res.text() };
1820
+ } catch (error) {
1821
+ const cause = controller.signal.aborted ? TransportCause.timeout(timeoutMs) : TransportCause.of(error);
1822
+ throw new UnreachableError(this.endpoint.host, method, route, cause);
1823
+ } finally {
1824
+ clearTimeout(timer);
1825
+ }
1826
+ }
1827
+ };
1828
+
1829
+ // src/tracing/media.ts
1830
+ var MEDIA_PATH = "/api/public/media";
1831
+ var MAX_MEDIA_BYTES = 5 * 1024 * 1024;
1832
+ var PUT_TIMEOUT_MS = 3e4;
1833
+ var MAX_UPLOAD_ERROR = 500;
1834
+ var NETWORK_FAILURE_STATUS = 599;
1835
+ var MediaUploadError = class extends Error {
1836
+ constructor(message, status) {
1837
+ super(message);
1838
+ this.status = status;
1839
+ this.name = "MediaUploadError";
1840
+ }
1841
+ status;
1842
+ };
1843
+ var MediaReference = class {
1844
+ constructor(mediaId, contentType) {
1845
+ this.mediaId = mediaId;
1846
+ this.contentType = contentType;
1847
+ }
1848
+ mediaId;
1849
+ contentType;
1850
+ toString() {
1851
+ return `@@@langfuseMedia:type=${this.contentType}|id=${this.mediaId}|source=bytes@@@`;
1852
+ }
1853
+ };
1854
+ async function putBytes(url, data, headers) {
1855
+ const controller = new AbortController();
1856
+ const timer = setTimeout(() => controller.abort(), PUT_TIMEOUT_MS);
1857
+ try {
1858
+ const res = await fetch(url, {
1859
+ method: "PUT",
1860
+ body: new Uint8Array(data),
1861
+ headers,
1862
+ signal: controller.signal
1863
+ });
1864
+ return {
1865
+ status: res.status,
1866
+ error: res.ok ? null : (await res.text()).slice(0, MAX_UPLOAD_ERROR)
1867
+ };
1868
+ } catch (error) {
1869
+ return {
1870
+ status: NETWORK_FAILURE_STATUS,
1871
+ error: error instanceof Error ? error.name : "Error"
1872
+ };
1873
+ } finally {
1874
+ clearTimeout(timer);
1875
+ }
1876
+ }
1877
+ var MediaUploader = class _MediaUploader {
1878
+ constructor(transport, put = putBytes, maxBytes = MAX_MEDIA_BYTES) {
1879
+ this.transport = transport;
1880
+ this.put = put;
1881
+ this.maxBytes = maxBytes;
1882
+ }
1883
+ transport;
1884
+ put;
1885
+ maxBytes;
1886
+ /** The uploader for `GATEWAY_HOST` / `GATEWAY_PUBLIC_KEY` /
1887
+ * `GATEWAY_SECRET_KEY` (the keys tracing exports with); null when any is unset. */
1888
+ static fromEnv(env = process.env) {
1889
+ const host = env.GATEWAY_HOST;
1890
+ const publicKey = env.GATEWAY_PUBLIC_KEY;
1891
+ const secretKey = env.GATEWAY_SECRET_KEY;
1892
+ if (!host || !publicKey || !secretKey) return null;
1893
+ return new _MediaUploader(
1894
+ new PlatformTransport({
1895
+ host: host.replace(/\/$/, ""),
1896
+ publicKey,
1897
+ secretKey
1898
+ })
1899
+ );
1900
+ }
1901
+ /** Store `data` linked to the trace (and observation) and return its reference. */
1902
+ async upload(data, link) {
1903
+ if (data.length > this.maxBytes)
1904
+ throw new MediaUploadError(
1905
+ `media is ${data.length} bytes, over the ${this.maxBytes}-byte cap`
1906
+ );
1907
+ const sha256Hash = createHash2("sha256").update(data).digest("base64");
1908
+ const answer = await this.send("POST", MEDIA_PATH, {
1909
+ traceId: link.traceId,
1910
+ observationId: link.observationId,
1911
+ contentType: link.contentType,
1912
+ contentLength: data.length,
1913
+ sha256Hash,
1914
+ field: link.field
1915
+ });
1916
+ if (typeof answer.mediaId !== "string" || !answer.mediaId)
1917
+ throw new MediaUploadError(
1918
+ "POST /api/public/media answered without a mediaId"
1919
+ );
1920
+ const reference = new MediaReference(answer.mediaId, link.contentType);
1921
+ if (answer.uploadUrl)
1922
+ await this.store(reference, answer.uploadUrl, data, sha256Hash);
1923
+ return reference;
1924
+ }
1925
+ async store(reference, url, data, sha256Hash) {
1926
+ const started = Date.now();
1927
+ const { status, error } = await this.put(url, data, {
1928
+ "Content-Type": reference.contentType,
1929
+ "x-amz-checksum-sha256": sha256Hash,
1930
+ "x-ms-blob-type": "BlockBlob"
1931
+ });
1932
+ await this.send(
1933
+ "PATCH",
1934
+ `${MEDIA_PATH}/${encodeURIComponent(reference.mediaId)}`,
1935
+ {
1936
+ uploadedAt: (/* @__PURE__ */ new Date()).toISOString(),
1937
+ uploadHttpStatus: status,
1938
+ uploadHttpError: error,
1939
+ uploadTimeMs: Date.now() - started
1940
+ }
1941
+ );
1942
+ if (status < 200 || status >= 300)
1943
+ throw new MediaUploadError(
1944
+ `media storage refused the upload (HTTP ${status})`,
1945
+ status
1946
+ );
1947
+ }
1948
+ async send(method, route, body) {
1949
+ const reply = await this.transport.send(method, route, body);
1950
+ if (!reply.ok)
1951
+ throw new MediaUploadError(
1952
+ `${method} ${route} -> ${reply.status}`,
1953
+ reply.status
1954
+ );
1955
+ return reply.text ? JSON.parse(reply.text) : {};
1956
+ }
1957
+ };
1458
1958
  export {
1459
1959
  IdentitySpanProcessor,
1960
+ MAX_MEDIA_BYTES,
1961
+ MediaReference,
1962
+ MediaUploadError,
1963
+ MediaUploader,
1964
+ SECRET_KEYS,
1460
1965
  SESSION_ID_ATTRIBUTE,
1966
+ SecretRedactingSpanProcessor,
1461
1967
  SessionSpanProcessor,
1968
+ SpanSecrets,
1462
1969
  USER_ID_ATTRIBUTE,
1970
+ WORLD_SESSION_ID_ATTRIBUTE,
1463
1971
  flush,
1464
1972
  getAmbientSessionId,
1973
+ getCurrentWorldSessionId,
1465
1974
  identify,
1466
1975
  init,
1467
1976
  initIsolated,
@@ -1474,6 +1983,7 @@ export {
1474
1983
  resetAmbientUser,
1475
1984
  resolveUserId,
1476
1985
  shutdown,
1477
- withSession
1986
+ withSession,
1987
+ withWorldSession
1478
1988
  };
1479
1989
  //# sourceMappingURL=index.mjs.map