bitfab 0.38.1 → 0.38.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -51,7 +51,7 @@ var __version__, __packageName__;
51
51
  var init_version_generated = __esm({
52
52
  "src/version.generated.ts"() {
53
53
  "use strict";
54
- __version__ = "0.38.1";
54
+ __version__ = "0.38.3";
55
55
  __packageName__ = "bitfab";
56
56
  }
57
57
  });
@@ -821,7 +821,7 @@ var init_otel = __esm({
821
821
  EXPORT_CONCURRENCY_ENV = "BITFAB_OTEL_EXPORT_CONCURRENCY";
822
822
  MAX_QUEUE_SIZE = 8192;
823
823
  DIRECT_MAX_EXPORT_BATCH_SIZE = 512;
824
- DIRECT_MAX_REQUEST_BATCH_SIZE = 8;
824
+ DIRECT_MAX_REQUEST_BATCH_SIZE = 128;
825
825
  DEFAULT_EXPORT_CONCURRENCY = 32;
826
826
  MAX_EXPORT_CONCURRENCY = 64;
827
827
  SCHEDULE_DELAY_MILLIS = 5e3;
@@ -1713,6 +1713,12 @@ var init_http = __esm({
1713
1713
  async lookupFunction(name) {
1714
1714
  return this.request("/api/sdk/functions/lookup", { name });
1715
1715
  }
1716
+ async getAutoTracePolicy(traceFunctionKey, protocol) {
1717
+ return this.request("/api/sdk/auto-trace/policy", {
1718
+ traceFunctionKey,
1719
+ protocol
1720
+ });
1721
+ }
1716
1722
  async getTraceSpan(traceId, lookup) {
1717
1723
  const searchParams = new URLSearchParams();
1718
1724
  if (lookup.id !== void 0) {
@@ -2807,6 +2813,11 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options, reg
2807
2813
  );
2808
2814
  }
2809
2815
  }
2816
+ if (options?.traceIds !== void 0 && options?.datasetId !== void 0) {
2817
+ throw new BitfabError(
2818
+ "traceIds and datasetId select different replay sources and cannot be used together."
2819
+ );
2820
+ }
2810
2821
  if (options?.limit !== void 0 && options?.traceIds !== void 0) {
2811
2822
  try {
2812
2823
  console.warn(
@@ -3134,6 +3145,7 @@ __export(index_exports, {
3134
3145
  ReplayError: () => ReplayError,
3135
3146
  SUPPORTED_PROVIDERS: () => SUPPORTED_PROVIDERS,
3136
3147
  __version__: () => __version__,
3148
+ defineReplayRegistry: () => defineReplayRegistry,
3137
3149
  finalizers: () => finalizers,
3138
3150
  flushTraces: () => flushTraces,
3139
3151
  getCurrentReplayBranch: () => getCurrentReplayBranch,
@@ -3758,6 +3770,80 @@ var BitfabClaudeAgentHandler = class {
3758
3770
  // src/client.ts
3759
3771
  init_asyncStorage();
3760
3772
 
3773
+ // src/autoTrace.ts
3774
+ init_asyncStorage();
3775
+ var autoTraceGlobal = globalThis;
3776
+ var autoTraceState = autoTraceGlobal.__bitfabAutoTraceStateV3 ?? {
3777
+ storage: null,
3778
+ browserScope: void 0,
3779
+ capturePolicies: /* @__PURE__ */ new WeakMap(),
3780
+ activeRoots: 0
3781
+ };
3782
+ autoTraceGlobal.__bitfabAutoTraceStateV3 = autoTraceState;
3783
+ function initializeAutoTraceStorage() {
3784
+ autoTraceState.storage ?? (autoTraceState.storage = createAsyncLocalStorage());
3785
+ }
3786
+ function runWithAutoTraceContext(context, fn, depth = 0) {
3787
+ initializeAutoTraceStorage();
3788
+ const scope = { context, depth };
3789
+ if (autoTraceState.storage) {
3790
+ return autoTraceState.storage.run(scope, fn);
3791
+ }
3792
+ const previous = autoTraceState.browserScope;
3793
+ autoTraceState.browserScope = scope;
3794
+ try {
3795
+ return fn();
3796
+ } finally {
3797
+ autoTraceState.browserScope = previous;
3798
+ }
3799
+ }
3800
+ function runWithAutoTraceRootContext(context, fn) {
3801
+ autoTraceState.activeRoots += 1;
3802
+ let result;
3803
+ try {
3804
+ result = runWithAutoTraceContext(context, fn);
3805
+ } catch (error) {
3806
+ autoTraceState.activeRoots -= 1;
3807
+ throw error;
3808
+ }
3809
+ if (isAutoTraceAsyncGenerator(result)) {
3810
+ autoTraceState.activeRoots -= 1;
3811
+ return wrapAutoTraceAsyncGenerator(context, result);
3812
+ }
3813
+ if (result instanceof Promise) {
3814
+ return result.finally(() => {
3815
+ autoTraceState.activeRoots -= 1;
3816
+ });
3817
+ }
3818
+ autoTraceState.activeRoots -= 1;
3819
+ return result;
3820
+ }
3821
+ function isAutoTraceAsyncGenerator(value) {
3822
+ if (value === null || typeof value !== "object") {
3823
+ return false;
3824
+ }
3825
+ const candidate = value;
3826
+ return typeof candidate.next === "function" && typeof candidate.return === "function" && typeof candidate.throw === "function" && typeof candidate[Symbol.asyncIterator] === "function";
3827
+ }
3828
+ function wrapAutoTraceAsyncGenerator(context, source) {
3829
+ const step = (method, value) => runWithAutoTraceRootContext(context, () => source[method](value));
3830
+ const wrapped = {
3831
+ next: (value) => step("next", value),
3832
+ return: (value) => step("return", value),
3833
+ throw: (error) => step("throw", error),
3834
+ [Symbol.asyncIterator]: () => wrapped
3835
+ };
3836
+ return wrapped;
3837
+ }
3838
+ function __setBitfabAutoTraceCapturePolicy(client, traceFunctionKey, functionIds) {
3839
+ const policies = autoTraceState.capturePolicies.get(client) ?? /* @__PURE__ */ new Map();
3840
+ policies.set(traceFunctionKey, new Set(functionIds));
3841
+ autoTraceState.capturePolicies.set(client, policies);
3842
+ }
3843
+ function getAutoTraceCapturePolicy(client, traceFunctionKey) {
3844
+ return autoTraceState.capturePolicies.get(client)?.get(traceFunctionKey) ?? /* @__PURE__ */ new Set();
3845
+ }
3846
+
3761
3847
  // src/optionalPeer.ts
3762
3848
  function importOptionalPeer(specifierParts) {
3763
3849
  const specifier = specifierParts.join("/");
@@ -5499,6 +5585,14 @@ function readEnv2(name) {
5499
5585
  }
5500
5586
  return void 0;
5501
5587
  }
5588
+ var DEFAULT_AUTO_TRACE_MAX_DEPTH = 30;
5589
+ var DEFAULT_AUTO_TRACE_MAX_SPANS = 500;
5590
+ var AUTO_TRACE_PROTOCOL = "ts-auto-v1";
5591
+ var AUTO_TRACE_POLICY_REFRESH_MS = 6e4;
5592
+ var AUTO_TRACE_POLICY_RETRY_MS = 1e4;
5593
+ function autoTraceLimit(value, fallback) {
5594
+ return value !== void 0 && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
5595
+ }
5502
5596
  var Bitfab = class {
5503
5597
  /**
5504
5598
  * Initialize the Bitfab client.
@@ -5508,6 +5602,7 @@ var Bitfab = class {
5508
5602
  constructor(config) {
5509
5603
  /** Gate the empty-key warning to fire at most once. */
5510
5604
  this.apiKeyWarned = false;
5605
+ this.autoTracePolicyRefreshes = /* @__PURE__ */ new Map();
5511
5606
  /**
5512
5607
  * Mock overrides registered via {@link Bitfab.registerMockOverride}, applied
5513
5608
  * to every `replay` on this client (after any per-call `mockOverride`). In
@@ -5531,6 +5626,178 @@ var Bitfab = class {
5531
5626
  timeout: this.timeout
5532
5627
  });
5533
5628
  }
5629
+ /**
5630
+ * Decorate a class method as an automatically expanded trace root.
5631
+ *
5632
+ * Build instrumentation turns repository functions called beneath this
5633
+ * method into nested spans. Every generated span preserves structure; only
5634
+ * function IDs selected by the capture policy include inputs and output.
5635
+ * Without a compatible build transform, this still records the decorated
5636
+ * method as a normal rich root span but cannot discover child calls.
5637
+ *
5638
+ * @param traceFunctionKey - Groups traces and their capture policy.
5639
+ * @param options - Root presentation, subtree bounds, and exclusions.
5640
+ * @experimental Automatic child-call instrumentation is experimental.
5641
+ */
5642
+ trace(traceFunctionKey, options = {}) {
5643
+ const decorator = (...args) => {
5644
+ if (args.length === 3) {
5645
+ const propertyKey = args[1];
5646
+ const descriptor = args[2];
5647
+ if (!descriptor || typeof descriptor.value !== "function") {
5648
+ throw new BitfabError("@bitfab.trace can only decorate methods");
5649
+ }
5650
+ if (!this.explicitlyEnabled) {
5651
+ return;
5652
+ }
5653
+ descriptor.value = this.createAutoTraceRoot(
5654
+ traceFunctionKey,
5655
+ String(propertyKey),
5656
+ options,
5657
+ descriptor.value
5658
+ );
5659
+ return;
5660
+ }
5661
+ const method = args[0];
5662
+ const context = args[1];
5663
+ if (typeof method !== "function" || context?.kind !== "method" || context.name === void 0) {
5664
+ throw new BitfabError("@bitfab.trace can only decorate methods");
5665
+ }
5666
+ if (!this.explicitlyEnabled) {
5667
+ return method;
5668
+ }
5669
+ return this.createAutoTraceRoot(
5670
+ traceFunctionKey,
5671
+ String(context.name),
5672
+ options,
5673
+ method
5674
+ );
5675
+ };
5676
+ return decorator;
5677
+ }
5678
+ withTrace(traceFunctionKey, optionsOrFn, maybeFn) {
5679
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
5680
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
5681
+ if (!fn) {
5682
+ throw new BitfabError("bitfab.withTrace requires a function");
5683
+ }
5684
+ if (!this.explicitlyEnabled) {
5685
+ return fn;
5686
+ }
5687
+ const name = fn.name !== "" ? fn.name : traceFunctionKey;
5688
+ return this.createAutoTraceRoot(traceFunctionKey, name, options, fn);
5689
+ }
5690
+ createAutoTraceRoot(traceFunctionKey, name, options, fn) {
5691
+ const self = this;
5692
+ const maxDepth = autoTraceLimit(
5693
+ options.maxDepth,
5694
+ DEFAULT_AUTO_TRACE_MAX_DEPTH
5695
+ );
5696
+ const maxSpans = autoTraceLimit(
5697
+ options.maxSpans,
5698
+ DEFAULT_AUTO_TRACE_MAX_SPANS
5699
+ );
5700
+ const excluded = new Set(options.exclude ?? []);
5701
+ const includeWrappers = options.includeWrappers ?? false;
5702
+ const tracedRoot = this.withSpan(
5703
+ traceFunctionKey,
5704
+ { name: options.name ?? name, type: options.type ?? "custom" },
5705
+ function(...args) {
5706
+ const capturePolicy = getAutoTraceCapturePolicy(self, traceFunctionKey);
5707
+ self.refreshAutoTraceCapturePolicy(traceFunctionKey);
5708
+ let spansUsed = 0;
5709
+ let truncated = false;
5710
+ const warnTruncated = () => {
5711
+ if (!truncated) {
5712
+ truncated = true;
5713
+ getCurrentTrace().setMetadata({
5714
+ bitfabAutoTrace: {
5715
+ protocol: AUTO_TRACE_PROTOCOL,
5716
+ truncated: true,
5717
+ maxDepth,
5718
+ maxSpans
5719
+ }
5720
+ });
5721
+ }
5722
+ warnOnce(
5723
+ `auto-trace-truncated:${traceFunctionKey}`,
5724
+ `"${traceFunctionKey}" hit an automatic subtree capture limit (maxDepth=${maxDepth}, maxSpans=${maxSpans}); its trace is incomplete. Raise the limits or narrow the subtree with exclude.`
5725
+ );
5726
+ };
5727
+ const autoTraceContext = {
5728
+ invoke(definition, inputs, invokeFn, depth) {
5729
+ const nameParts = definition.name.split(".");
5730
+ const simpleName = nameParts[nameParts.length - 1];
5731
+ if (excluded.has(definition.name) || simpleName !== void 0 && excluded.has(simpleName) || definition.wrapper === true && !includeWrappers) {
5732
+ return invokeFn();
5733
+ }
5734
+ if (depth >= maxDepth || spansUsed >= maxSpans) {
5735
+ warnTruncated();
5736
+ return invokeFn();
5737
+ }
5738
+ spansUsed += 1;
5739
+ const childOptions = {
5740
+ name: definition.name,
5741
+ type: "function",
5742
+ captureWhen: "nested",
5743
+ functionId: definition.id,
5744
+ captureContent: capturePolicy.has(definition.id),
5745
+ autoTraceDefinition: definition
5746
+ };
5747
+ const tracedChild = self.withSpan(
5748
+ traceFunctionKey,
5749
+ childOptions,
5750
+ (..._inputs) => runWithAutoTraceContext(autoTraceContext, invokeFn, depth + 1)
5751
+ );
5752
+ return tracedChild(...inputs);
5753
+ }
5754
+ };
5755
+ return runWithAutoTraceRootContext(
5756
+ autoTraceContext,
5757
+ () => fn.apply(this, args)
5758
+ );
5759
+ }
5760
+ );
5761
+ const autoTraceRoot = function(...args) {
5762
+ if (!self.isTracingEnabled()) {
5763
+ return fn.apply(this, args);
5764
+ }
5765
+ return tracedRoot.apply(this, args);
5766
+ };
5767
+ Object.defineProperty(autoTraceRoot, "_bitfabTraceFunctionKey", {
5768
+ value: traceFunctionKey
5769
+ });
5770
+ return autoTraceRoot;
5771
+ }
5772
+ refreshAutoTraceCapturePolicy(traceFunctionKey) {
5773
+ const now = Date.now();
5774
+ const state = this.autoTracePolicyRefreshes.get(traceFunctionKey) ?? {
5775
+ refreshAfter: 0
5776
+ };
5777
+ if (state.inFlight || now < state.refreshAfter) {
5778
+ return;
5779
+ }
5780
+ const request = this.httpClient.getAutoTracePolicy(
5781
+ traceFunctionKey,
5782
+ AUTO_TRACE_PROTOCOL
5783
+ ).then((policy) => {
5784
+ if (policy.protocol !== AUTO_TRACE_PROTOCOL) {
5785
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS;
5786
+ return;
5787
+ }
5788
+ const functionIds = Array.isArray(policy.functionIds) ? policy.functionIds.filter(
5789
+ (id) => typeof id === "string" && id.startsWith(`${AUTO_TRACE_PROTOCOL}:`)
5790
+ ).slice(0, DEFAULT_AUTO_TRACE_MAX_SPANS) : [];
5791
+ __setBitfabAutoTraceCapturePolicy(this, traceFunctionKey, functionIds);
5792
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_REFRESH_MS;
5793
+ }).catch(() => {
5794
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS;
5795
+ }).finally(() => {
5796
+ state.inFlight = void 0;
5797
+ });
5798
+ state.inFlight = request;
5799
+ this.autoTracePolicyRefreshes.set(traceFunctionKey, state);
5800
+ }
5534
5801
  /**
5535
5802
  * Flush and permanently close this client's tracing resources: its pending
5536
5803
  * requests and the single span-transport worker shared by its decorators and
@@ -6077,7 +6344,10 @@ var Bitfab = class {
6077
6344
  parentSpanId,
6078
6345
  inputs,
6079
6346
  startedAt,
6080
- spanType: options.type ?? "custom"
6347
+ spanType: options.type ?? "custom",
6348
+ functionId: options.functionId,
6349
+ captureContent: options.captureContent ?? true,
6350
+ autoTraceDefinition: options.autoTraceDefinition
6081
6351
  };
6082
6352
  const sendSpan = async (params) => {
6083
6353
  const replayCtx = getReplayContext();
@@ -6242,7 +6512,16 @@ var Bitfab = class {
6242
6512
  }
6243
6513
  };
6244
6514
  executeWithContext = () => {
6245
- const result = fn.apply(this, args);
6515
+ let result;
6516
+ try {
6517
+ result = fn.apply(this, args);
6518
+ } catch (error) {
6519
+ void sendSpan({
6520
+ result: void 0,
6521
+ error: error instanceof Error ? error.message : String(error)
6522
+ });
6523
+ throw error;
6524
+ }
6246
6525
  if (result instanceof Promise) {
6247
6526
  return result.then((resolvedResult) => {
6248
6527
  recordSpan(resolvedResult);
@@ -6483,8 +6762,8 @@ var Bitfab = class {
6483
6762
  * Queued on the client's span transport; delivery is the transport's job.
6484
6763
  */
6485
6764
  sendWrapperSpan(params) {
6486
- const serializedInputs = serializeValue(params.inputs);
6487
- const serializedResult = serializeValue(params.result);
6765
+ const serializedInputs = params.captureContent ? serializeValue(params.inputs) : void 0;
6766
+ const serializedResult = params.captureContent ? serializeValue(params.result) : void 0;
6488
6767
  const externalSpan = {
6489
6768
  id: params.spanId,
6490
6769
  trace_id: params.traceId,
@@ -6493,26 +6772,38 @@ var Bitfab = class {
6493
6772
  span_data: {
6494
6773
  name: params.spanName,
6495
6774
  type: params.spanType,
6496
- input: serializedInputs.json,
6497
- output: serializedResult.json,
6498
- // Include superjson meta for type preservation
6499
- ...serializedInputs.meta !== void 0 && {
6500
- input_meta: serializedInputs.meta
6775
+ ...params.functionId !== void 0 && {
6776
+ function_id: params.functionId,
6777
+ content_captured: params.captureContent
6778
+ },
6779
+ ...params.autoTraceDefinition !== void 0 && {
6780
+ function_file: params.autoTraceDefinition.file,
6781
+ function_line: params.autoTraceDefinition.line,
6782
+ function_column: params.autoTraceDefinition.column
6501
6783
  },
6502
- ...serializedResult.meta !== void 0 && {
6503
- output_meta: serializedResult.meta
6784
+ ...serializedInputs !== void 0 && {
6785
+ input: serializedInputs.json,
6786
+ ...serializedInputs.meta !== void 0 && {
6787
+ input_meta: serializedInputs.meta
6788
+ }
6789
+ },
6790
+ ...serializedResult !== void 0 && {
6791
+ output: serializedResult.json,
6792
+ ...serializedResult.meta !== void 0 && {
6793
+ output_meta: serializedResult.meta
6794
+ }
6504
6795
  },
6505
6796
  ...params.functionName !== void 0 && {
6506
6797
  function_name: params.functionName
6507
6798
  },
6508
- ...params.error !== void 0 && {
6799
+ ...params.captureContent && params.error !== void 0 && {
6509
6800
  error: params.error,
6510
6801
  error_source: "code"
6511
6802
  },
6512
- ...params.contexts && params.contexts.length > 0 && {
6803
+ ...params.captureContent && params.contexts && params.contexts.length > 0 && {
6513
6804
  contexts: params.contexts
6514
6805
  },
6515
- ...params.prompt !== void 0 && { prompt: params.prompt }
6806
+ ...params.captureContent && params.prompt !== void 0 && { prompt: params.prompt }
6516
6807
  }
6517
6808
  };
6518
6809
  if (params.parentSpanId) {
@@ -6787,6 +7078,13 @@ var finalizers = {
6787
7078
  // src/index.ts
6788
7079
  init_http();
6789
7080
  init_replay();
7081
+
7082
+ // src/replayRegistry.ts
7083
+ init_errors();
7084
+ init_replay();
7085
+ function defineReplayRegistry(registry) {
7086
+ return registry;
7087
+ }
6790
7088
  // Annotate the CommonJS export names for ESM import in node:
6791
7089
  0 && (module.exports = {
6792
7090
  BITFAB_PROGRESS_PREFIX,
@@ -6805,6 +7103,7 @@ init_replay();
6805
7103
  ReplayError,
6806
7104
  SUPPORTED_PROVIDERS,
6807
7105
  __version__,
7106
+ defineReplayRegistry,
6808
7107
  finalizers,
6809
7108
  flushTraces,
6810
7109
  getCurrentReplayBranch,