@bitfab/sdk 0.38.1 → 0.38.2

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.d.cts CHANGED
@@ -523,6 +523,7 @@ declare class HttpClient {
523
523
  * Blocks until complete - needed for function execution.
524
524
  */
525
525
  lookupFunction<T>(name: string): Promise<T>;
526
+ getAutoTracePolicy<T>(traceFunctionKey: string, protocol: string): Promise<T>;
526
527
  getTraceSpan(traceId: string, lookup: SpanLookup): Promise<CapturedSpan | null>;
527
528
  private get;
528
529
  /**
@@ -2098,6 +2099,27 @@ interface SpanMethodDecoratorContext<TThis, TValue> {
2098
2099
  }
2099
2100
  /** A standard ECMAScript method decorator produced by {@link Bitfab.span}. */
2100
2101
  type SpanMethodDecorator = <TThis, TArgs extends unknown[], TReturn>(originalMethod: (this: TThis, ...args: TArgs) => TReturn, context: SpanMethodDecoratorContext<TThis, (this: TThis, ...args: TArgs) => TReturn>) => (this: TThis, ...args: TArgs) => TReturn;
2102
+ /** Options for experimental automatic subtree tracing. */
2103
+ interface TraceOptions {
2104
+ /** Root span name. Defaults to the decorated or wrapped function name. */
2105
+ name?: string;
2106
+ /** Root span type. Descendants are always `function` spans. */
2107
+ type?: SpanType;
2108
+ /** Maximum number of recorded descendant levels. Defaults to 30. */
2109
+ maxDepth?: number;
2110
+ /** Maximum descendant spans recorded per root invocation. Defaults to 500. */
2111
+ maxSpans?: number;
2112
+ /** Qualified or simple function names to leave out of the subtree. */
2113
+ exclude?: readonly string[] | ReadonlySet<string>;
2114
+ /** Record rest-argument wrapper functions. Defaults to false. */
2115
+ includeWrappers?: boolean;
2116
+ }
2117
+ type StandardTraceMethodDecorator = <This, TArgs extends unknown[], TReturn>(method: (this: This, ...args: TArgs) => TReturn, context: {
2118
+ kind: "method";
2119
+ name: string | symbol;
2120
+ }) => (this: This, ...args: TArgs) => TReturn;
2121
+ type LegacyTraceMethodDecorator = <This, TArgs extends unknown[], TReturn>(target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<(this: This, ...args: TArgs) => TReturn>) => void;
2122
+ type TraceMethodDecorator = StandardTraceMethodDecorator & LegacyTraceMethodDecorator;
2101
2123
 
2102
2124
  /**
2103
2125
  * Client for making provider-based API calls via BAML.
@@ -2117,6 +2139,7 @@ declare class Bitfab {
2117
2139
  private readonly httpClient;
2118
2140
  private readonly bamlClient;
2119
2141
  private readonly dbSnapshot;
2142
+ private readonly autoTracePolicyRefreshes;
2120
2143
  /**
2121
2144
  * Mock overrides registered via {@link Bitfab.registerMockOverride}, applied
2122
2145
  * to every `replay` on this client (after any per-call `mockOverride`). In
@@ -2129,6 +2152,37 @@ declare class Bitfab {
2129
2152
  * @param config - Configuration options for the client
2130
2153
  */
2131
2154
  constructor(config: BitfabConfig);
2155
+ /**
2156
+ * Decorate a class method as an automatically expanded trace root.
2157
+ *
2158
+ * Build instrumentation turns repository functions called beneath this
2159
+ * method into nested spans. Every generated span preserves structure; only
2160
+ * function IDs selected by the capture policy include inputs and output.
2161
+ * Without a compatible build transform, this still records the decorated
2162
+ * method as a normal rich root span but cannot discover child calls.
2163
+ *
2164
+ * @param traceFunctionKey - Groups traces and their capture policy.
2165
+ * @param options - Root presentation, subtree bounds, and exclusions.
2166
+ * @experimental Automatic child-call instrumentation is experimental.
2167
+ */
2168
+ trace(traceFunctionKey: string, options?: TraceOptions): TraceMethodDecorator;
2169
+ /**
2170
+ * Wrap a function as an automatically expanded trace root.
2171
+ *
2172
+ * This is the function-oriented equivalent of {@link Bitfab.trace}. Build
2173
+ * instrumentation turns repository functions called beneath the wrapped
2174
+ * function into nested spans. Without a compatible transform, this still
2175
+ * records one normal rich root span and runs the function unchanged.
2176
+ *
2177
+ * @param traceFunctionKey - Groups traces and their capture policy.
2178
+ * @param optionsOrFn - Options or the workflow entrypoint to wrap.
2179
+ * @param maybeFn - Workflow entrypoint when options are provided.
2180
+ * @experimental Automatic child-call instrumentation is experimental.
2181
+ */
2182
+ withTrace<This, TArgs extends unknown[], TReturn>(traceFunctionKey: string, fn: (this: This, ...args: TArgs) => TReturn): (this: This, ...args: TArgs) => TReturn;
2183
+ withTrace<This, TArgs extends unknown[], TReturn>(traceFunctionKey: string, options: TraceOptions, fn: (this: This, ...args: TArgs) => TReturn): (this: This, ...args: TArgs) => TReturn;
2184
+ private createAutoTraceRoot;
2185
+ private refreshAutoTraceCapturePolicy;
2132
2186
  /**
2133
2187
  * Flush and permanently close this client's tracing resources: its pending
2134
2188
  * requests and the single span-transport worker shared by its decorators and
@@ -2663,7 +2717,7 @@ declare class BitfabFunction {
2663
2717
  /**
2664
2718
  * SDK version from package.json (injected at build time)
2665
2719
  */
2666
- declare const __version__ = "0.38.1";
2720
+ declare const __version__ = "0.38.2";
2667
2721
 
2668
2722
  /**
2669
2723
  * Constants for the Bitfab SDK.
package/dist/index.d.ts CHANGED
@@ -523,6 +523,7 @@ declare class HttpClient {
523
523
  * Blocks until complete - needed for function execution.
524
524
  */
525
525
  lookupFunction<T>(name: string): Promise<T>;
526
+ getAutoTracePolicy<T>(traceFunctionKey: string, protocol: string): Promise<T>;
526
527
  getTraceSpan(traceId: string, lookup: SpanLookup): Promise<CapturedSpan | null>;
527
528
  private get;
528
529
  /**
@@ -2098,6 +2099,27 @@ interface SpanMethodDecoratorContext<TThis, TValue> {
2098
2099
  }
2099
2100
  /** A standard ECMAScript method decorator produced by {@link Bitfab.span}. */
2100
2101
  type SpanMethodDecorator = <TThis, TArgs extends unknown[], TReturn>(originalMethod: (this: TThis, ...args: TArgs) => TReturn, context: SpanMethodDecoratorContext<TThis, (this: TThis, ...args: TArgs) => TReturn>) => (this: TThis, ...args: TArgs) => TReturn;
2102
+ /** Options for experimental automatic subtree tracing. */
2103
+ interface TraceOptions {
2104
+ /** Root span name. Defaults to the decorated or wrapped function name. */
2105
+ name?: string;
2106
+ /** Root span type. Descendants are always `function` spans. */
2107
+ type?: SpanType;
2108
+ /** Maximum number of recorded descendant levels. Defaults to 30. */
2109
+ maxDepth?: number;
2110
+ /** Maximum descendant spans recorded per root invocation. Defaults to 500. */
2111
+ maxSpans?: number;
2112
+ /** Qualified or simple function names to leave out of the subtree. */
2113
+ exclude?: readonly string[] | ReadonlySet<string>;
2114
+ /** Record rest-argument wrapper functions. Defaults to false. */
2115
+ includeWrappers?: boolean;
2116
+ }
2117
+ type StandardTraceMethodDecorator = <This, TArgs extends unknown[], TReturn>(method: (this: This, ...args: TArgs) => TReturn, context: {
2118
+ kind: "method";
2119
+ name: string | symbol;
2120
+ }) => (this: This, ...args: TArgs) => TReturn;
2121
+ type LegacyTraceMethodDecorator = <This, TArgs extends unknown[], TReturn>(target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<(this: This, ...args: TArgs) => TReturn>) => void;
2122
+ type TraceMethodDecorator = StandardTraceMethodDecorator & LegacyTraceMethodDecorator;
2101
2123
 
2102
2124
  /**
2103
2125
  * Client for making provider-based API calls via BAML.
@@ -2117,6 +2139,7 @@ declare class Bitfab {
2117
2139
  private readonly httpClient;
2118
2140
  private readonly bamlClient;
2119
2141
  private readonly dbSnapshot;
2142
+ private readonly autoTracePolicyRefreshes;
2120
2143
  /**
2121
2144
  * Mock overrides registered via {@link Bitfab.registerMockOverride}, applied
2122
2145
  * to every `replay` on this client (after any per-call `mockOverride`). In
@@ -2129,6 +2152,37 @@ declare class Bitfab {
2129
2152
  * @param config - Configuration options for the client
2130
2153
  */
2131
2154
  constructor(config: BitfabConfig);
2155
+ /**
2156
+ * Decorate a class method as an automatically expanded trace root.
2157
+ *
2158
+ * Build instrumentation turns repository functions called beneath this
2159
+ * method into nested spans. Every generated span preserves structure; only
2160
+ * function IDs selected by the capture policy include inputs and output.
2161
+ * Without a compatible build transform, this still records the decorated
2162
+ * method as a normal rich root span but cannot discover child calls.
2163
+ *
2164
+ * @param traceFunctionKey - Groups traces and their capture policy.
2165
+ * @param options - Root presentation, subtree bounds, and exclusions.
2166
+ * @experimental Automatic child-call instrumentation is experimental.
2167
+ */
2168
+ trace(traceFunctionKey: string, options?: TraceOptions): TraceMethodDecorator;
2169
+ /**
2170
+ * Wrap a function as an automatically expanded trace root.
2171
+ *
2172
+ * This is the function-oriented equivalent of {@link Bitfab.trace}. Build
2173
+ * instrumentation turns repository functions called beneath the wrapped
2174
+ * function into nested spans. Without a compatible transform, this still
2175
+ * records one normal rich root span and runs the function unchanged.
2176
+ *
2177
+ * @param traceFunctionKey - Groups traces and their capture policy.
2178
+ * @param optionsOrFn - Options or the workflow entrypoint to wrap.
2179
+ * @param maybeFn - Workflow entrypoint when options are provided.
2180
+ * @experimental Automatic child-call instrumentation is experimental.
2181
+ */
2182
+ withTrace<This, TArgs extends unknown[], TReturn>(traceFunctionKey: string, fn: (this: This, ...args: TArgs) => TReturn): (this: This, ...args: TArgs) => TReturn;
2183
+ withTrace<This, TArgs extends unknown[], TReturn>(traceFunctionKey: string, options: TraceOptions, fn: (this: This, ...args: TArgs) => TReturn): (this: This, ...args: TArgs) => TReturn;
2184
+ private createAutoTraceRoot;
2185
+ private refreshAutoTraceCapturePolicy;
2132
2186
  /**
2133
2187
  * Flush and permanently close this client's tracing resources: its pending
2134
2188
  * requests and the single span-transport worker shared by its decorators and
@@ -2663,7 +2717,7 @@ declare class BitfabFunction {
2663
2717
  /**
2664
2718
  * SDK version from package.json (injected at build time)
2665
2719
  */
2666
- declare const __version__ = "0.38.1";
2720
+ declare const __version__ = "0.38.2";
2667
2721
 
2668
2722
  /**
2669
2723
  * Constants for the Bitfab SDK.
package/dist/index.js CHANGED
@@ -11,7 +11,8 @@ import {
11
11
  getCurrentReplayBranch,
12
12
  getCurrentSpan,
13
13
  getCurrentTrace
14
- } from "./chunk-WD4AO3BK.js";
14
+ } from "./chunk-CWXCVY75.js";
15
+ import "./chunk-GFBQ2AMO.js";
15
16
  import {
16
17
  BITFAB_PROGRESS_PREFIX,
17
18
  BitfabError,
@@ -23,7 +24,8 @@ import {
23
24
  flushTraces,
24
25
  reportReplayProgress,
25
26
  serializeReplayResult
26
- } from "./chunk-MGA7ROIK.js";
27
+ } from "./chunk-SU7EAKOV.js";
28
+ import "./chunk-H6LZRFMN.js";
27
29
  export {
28
30
  BITFAB_PROGRESS_PREFIX,
29
31
  Bitfab,
package/dist/node.cjs CHANGED
@@ -88,7 +88,7 @@ var __version__, __packageName__;
88
88
  var init_version_generated = __esm({
89
89
  "src/version.generated.ts"() {
90
90
  "use strict";
91
- __version__ = "0.38.1";
91
+ __version__ = "0.38.2";
92
92
  __packageName__ = "@bitfab/sdk";
93
93
  }
94
94
  });
@@ -819,7 +819,7 @@ var init_otel = __esm({
819
819
  EXPORT_CONCURRENCY_ENV = "BITFAB_OTEL_EXPORT_CONCURRENCY";
820
820
  MAX_QUEUE_SIZE = 8192;
821
821
  DIRECT_MAX_EXPORT_BATCH_SIZE = 512;
822
- DIRECT_MAX_REQUEST_BATCH_SIZE = 8;
822
+ DIRECT_MAX_REQUEST_BATCH_SIZE = 128;
823
823
  DEFAULT_EXPORT_CONCURRENCY = 32;
824
824
  MAX_EXPORT_CONCURRENCY = 64;
825
825
  SCHEDULE_DELAY_MILLIS = 5e3;
@@ -1711,6 +1711,12 @@ var init_http = __esm({
1711
1711
  async lookupFunction(name) {
1712
1712
  return this.request("/api/sdk/functions/lookup", { name });
1713
1713
  }
1714
+ async getAutoTracePolicy(traceFunctionKey, protocol) {
1715
+ return this.request("/api/sdk/auto-trace/policy", {
1716
+ traceFunctionKey,
1717
+ protocol
1718
+ });
1719
+ }
1714
1720
  async getTraceSpan(traceId, lookup) {
1715
1721
  const searchParams = new URLSearchParams();
1716
1722
  if (lookup.id !== void 0) {
@@ -3763,6 +3769,80 @@ var BitfabClaudeAgentHandler = class {
3763
3769
  // src/client.ts
3764
3770
  init_asyncStorage();
3765
3771
 
3772
+ // src/autoTrace.ts
3773
+ init_asyncStorage();
3774
+ var autoTraceGlobal = globalThis;
3775
+ var autoTraceState = autoTraceGlobal.__bitfabAutoTraceStateV3 ?? {
3776
+ storage: null,
3777
+ browserScope: void 0,
3778
+ capturePolicies: /* @__PURE__ */ new WeakMap(),
3779
+ activeRoots: 0
3780
+ };
3781
+ autoTraceGlobal.__bitfabAutoTraceStateV3 = autoTraceState;
3782
+ function initializeAutoTraceStorage() {
3783
+ autoTraceState.storage ?? (autoTraceState.storage = createAsyncLocalStorage());
3784
+ }
3785
+ function runWithAutoTraceContext(context, fn, depth = 0) {
3786
+ initializeAutoTraceStorage();
3787
+ const scope = { context, depth };
3788
+ if (autoTraceState.storage) {
3789
+ return autoTraceState.storage.run(scope, fn);
3790
+ }
3791
+ const previous = autoTraceState.browserScope;
3792
+ autoTraceState.browserScope = scope;
3793
+ try {
3794
+ return fn();
3795
+ } finally {
3796
+ autoTraceState.browserScope = previous;
3797
+ }
3798
+ }
3799
+ function runWithAutoTraceRootContext(context, fn) {
3800
+ autoTraceState.activeRoots += 1;
3801
+ let result;
3802
+ try {
3803
+ result = runWithAutoTraceContext(context, fn);
3804
+ } catch (error) {
3805
+ autoTraceState.activeRoots -= 1;
3806
+ throw error;
3807
+ }
3808
+ if (isAutoTraceAsyncGenerator(result)) {
3809
+ autoTraceState.activeRoots -= 1;
3810
+ return wrapAutoTraceAsyncGenerator(context, result);
3811
+ }
3812
+ if (result instanceof Promise) {
3813
+ return result.finally(() => {
3814
+ autoTraceState.activeRoots -= 1;
3815
+ });
3816
+ }
3817
+ autoTraceState.activeRoots -= 1;
3818
+ return result;
3819
+ }
3820
+ function isAutoTraceAsyncGenerator(value) {
3821
+ if (value === null || typeof value !== "object") {
3822
+ return false;
3823
+ }
3824
+ const candidate = value;
3825
+ return typeof candidate.next === "function" && typeof candidate.return === "function" && typeof candidate.throw === "function" && typeof candidate[Symbol.asyncIterator] === "function";
3826
+ }
3827
+ function wrapAutoTraceAsyncGenerator(context, source) {
3828
+ const step = (method, value) => runWithAutoTraceRootContext(context, () => source[method](value));
3829
+ const wrapped = {
3830
+ next: (value) => step("next", value),
3831
+ return: (value) => step("return", value),
3832
+ throw: (error) => step("throw", error),
3833
+ [Symbol.asyncIterator]: () => wrapped
3834
+ };
3835
+ return wrapped;
3836
+ }
3837
+ function __setBitfabAutoTraceCapturePolicy(client, traceFunctionKey, functionIds) {
3838
+ const policies = autoTraceState.capturePolicies.get(client) ?? /* @__PURE__ */ new Map();
3839
+ policies.set(traceFunctionKey, new Set(functionIds));
3840
+ autoTraceState.capturePolicies.set(client, policies);
3841
+ }
3842
+ function getAutoTraceCapturePolicy(client, traceFunctionKey) {
3843
+ return autoTraceState.capturePolicies.get(client)?.get(traceFunctionKey) ?? /* @__PURE__ */ new Set();
3844
+ }
3845
+
3766
3846
  // src/optionalPeer.ts
3767
3847
  function importOptionalPeer(specifierParts) {
3768
3848
  const specifier = specifierParts.join("/");
@@ -5504,6 +5584,14 @@ function readEnv2(name) {
5504
5584
  }
5505
5585
  return void 0;
5506
5586
  }
5587
+ var DEFAULT_AUTO_TRACE_MAX_DEPTH = 30;
5588
+ var DEFAULT_AUTO_TRACE_MAX_SPANS = 500;
5589
+ var AUTO_TRACE_PROTOCOL = "ts-auto-v1";
5590
+ var AUTO_TRACE_POLICY_REFRESH_MS = 6e4;
5591
+ var AUTO_TRACE_POLICY_RETRY_MS = 1e4;
5592
+ function autoTraceLimit(value, fallback) {
5593
+ return value !== void 0 && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
5594
+ }
5507
5595
  var Bitfab = class {
5508
5596
  /**
5509
5597
  * Initialize the Bitfab client.
@@ -5513,6 +5601,7 @@ var Bitfab = class {
5513
5601
  constructor(config) {
5514
5602
  /** Gate the empty-key warning to fire at most once. */
5515
5603
  this.apiKeyWarned = false;
5604
+ this.autoTracePolicyRefreshes = /* @__PURE__ */ new Map();
5516
5605
  /**
5517
5606
  * Mock overrides registered via {@link Bitfab.registerMockOverride}, applied
5518
5607
  * to every `replay` on this client (after any per-call `mockOverride`). In
@@ -5536,6 +5625,178 @@ var Bitfab = class {
5536
5625
  timeout: this.timeout
5537
5626
  });
5538
5627
  }
5628
+ /**
5629
+ * Decorate a class method as an automatically expanded trace root.
5630
+ *
5631
+ * Build instrumentation turns repository functions called beneath this
5632
+ * method into nested spans. Every generated span preserves structure; only
5633
+ * function IDs selected by the capture policy include inputs and output.
5634
+ * Without a compatible build transform, this still records the decorated
5635
+ * method as a normal rich root span but cannot discover child calls.
5636
+ *
5637
+ * @param traceFunctionKey - Groups traces and their capture policy.
5638
+ * @param options - Root presentation, subtree bounds, and exclusions.
5639
+ * @experimental Automatic child-call instrumentation is experimental.
5640
+ */
5641
+ trace(traceFunctionKey, options = {}) {
5642
+ const decorator = (...args) => {
5643
+ if (args.length === 3) {
5644
+ const propertyKey = args[1];
5645
+ const descriptor = args[2];
5646
+ if (!descriptor || typeof descriptor.value !== "function") {
5647
+ throw new BitfabError("@bitfab.trace can only decorate methods");
5648
+ }
5649
+ if (!this.explicitlyEnabled) {
5650
+ return;
5651
+ }
5652
+ descriptor.value = this.createAutoTraceRoot(
5653
+ traceFunctionKey,
5654
+ String(propertyKey),
5655
+ options,
5656
+ descriptor.value
5657
+ );
5658
+ return;
5659
+ }
5660
+ const method = args[0];
5661
+ const context = args[1];
5662
+ if (typeof method !== "function" || context?.kind !== "method" || context.name === void 0) {
5663
+ throw new BitfabError("@bitfab.trace can only decorate methods");
5664
+ }
5665
+ if (!this.explicitlyEnabled) {
5666
+ return method;
5667
+ }
5668
+ return this.createAutoTraceRoot(
5669
+ traceFunctionKey,
5670
+ String(context.name),
5671
+ options,
5672
+ method
5673
+ );
5674
+ };
5675
+ return decorator;
5676
+ }
5677
+ withTrace(traceFunctionKey, optionsOrFn, maybeFn) {
5678
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
5679
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
5680
+ if (!fn) {
5681
+ throw new BitfabError("bitfab.withTrace requires a function");
5682
+ }
5683
+ if (!this.explicitlyEnabled) {
5684
+ return fn;
5685
+ }
5686
+ const name = fn.name !== "" ? fn.name : traceFunctionKey;
5687
+ return this.createAutoTraceRoot(traceFunctionKey, name, options, fn);
5688
+ }
5689
+ createAutoTraceRoot(traceFunctionKey, name, options, fn) {
5690
+ const self = this;
5691
+ const maxDepth = autoTraceLimit(
5692
+ options.maxDepth,
5693
+ DEFAULT_AUTO_TRACE_MAX_DEPTH
5694
+ );
5695
+ const maxSpans = autoTraceLimit(
5696
+ options.maxSpans,
5697
+ DEFAULT_AUTO_TRACE_MAX_SPANS
5698
+ );
5699
+ const excluded = new Set(options.exclude ?? []);
5700
+ const includeWrappers = options.includeWrappers ?? false;
5701
+ const tracedRoot = this.withSpan(
5702
+ traceFunctionKey,
5703
+ { name: options.name ?? name, type: options.type ?? "custom" },
5704
+ function(...args) {
5705
+ const capturePolicy = getAutoTraceCapturePolicy(self, traceFunctionKey);
5706
+ self.refreshAutoTraceCapturePolicy(traceFunctionKey);
5707
+ let spansUsed = 0;
5708
+ let truncated = false;
5709
+ const warnTruncated = () => {
5710
+ if (!truncated) {
5711
+ truncated = true;
5712
+ getCurrentTrace().setMetadata({
5713
+ bitfabAutoTrace: {
5714
+ protocol: AUTO_TRACE_PROTOCOL,
5715
+ truncated: true,
5716
+ maxDepth,
5717
+ maxSpans
5718
+ }
5719
+ });
5720
+ }
5721
+ warnOnce(
5722
+ `auto-trace-truncated:${traceFunctionKey}`,
5723
+ `"${traceFunctionKey}" hit an automatic subtree capture limit (maxDepth=${maxDepth}, maxSpans=${maxSpans}); its trace is incomplete. Raise the limits or narrow the subtree with exclude.`
5724
+ );
5725
+ };
5726
+ const autoTraceContext = {
5727
+ invoke(definition, inputs, invokeFn, depth) {
5728
+ const nameParts = definition.name.split(".");
5729
+ const simpleName = nameParts[nameParts.length - 1];
5730
+ if (excluded.has(definition.name) || simpleName !== void 0 && excluded.has(simpleName) || definition.wrapper === true && !includeWrappers) {
5731
+ return invokeFn();
5732
+ }
5733
+ if (depth >= maxDepth || spansUsed >= maxSpans) {
5734
+ warnTruncated();
5735
+ return invokeFn();
5736
+ }
5737
+ spansUsed += 1;
5738
+ const childOptions = {
5739
+ name: definition.name,
5740
+ type: "function",
5741
+ captureWhen: "nested",
5742
+ functionId: definition.id,
5743
+ captureContent: capturePolicy.has(definition.id),
5744
+ autoTraceDefinition: definition
5745
+ };
5746
+ const tracedChild = self.withSpan(
5747
+ traceFunctionKey,
5748
+ childOptions,
5749
+ (..._inputs) => runWithAutoTraceContext(autoTraceContext, invokeFn, depth + 1)
5750
+ );
5751
+ return tracedChild(...inputs);
5752
+ }
5753
+ };
5754
+ return runWithAutoTraceRootContext(
5755
+ autoTraceContext,
5756
+ () => fn.apply(this, args)
5757
+ );
5758
+ }
5759
+ );
5760
+ const autoTraceRoot = function(...args) {
5761
+ if (!self.isTracingEnabled()) {
5762
+ return fn.apply(this, args);
5763
+ }
5764
+ return tracedRoot.apply(this, args);
5765
+ };
5766
+ Object.defineProperty(autoTraceRoot, "_bitfabTraceFunctionKey", {
5767
+ value: traceFunctionKey
5768
+ });
5769
+ return autoTraceRoot;
5770
+ }
5771
+ refreshAutoTraceCapturePolicy(traceFunctionKey) {
5772
+ const now = Date.now();
5773
+ const state = this.autoTracePolicyRefreshes.get(traceFunctionKey) ?? {
5774
+ refreshAfter: 0
5775
+ };
5776
+ if (state.inFlight || now < state.refreshAfter) {
5777
+ return;
5778
+ }
5779
+ const request = this.httpClient.getAutoTracePolicy(
5780
+ traceFunctionKey,
5781
+ AUTO_TRACE_PROTOCOL
5782
+ ).then((policy) => {
5783
+ if (policy.protocol !== AUTO_TRACE_PROTOCOL) {
5784
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS;
5785
+ return;
5786
+ }
5787
+ const functionIds = Array.isArray(policy.functionIds) ? policy.functionIds.filter(
5788
+ (id) => typeof id === "string" && id.startsWith(`${AUTO_TRACE_PROTOCOL}:`)
5789
+ ).slice(0, DEFAULT_AUTO_TRACE_MAX_SPANS) : [];
5790
+ __setBitfabAutoTraceCapturePolicy(this, traceFunctionKey, functionIds);
5791
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_REFRESH_MS;
5792
+ }).catch(() => {
5793
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS;
5794
+ }).finally(() => {
5795
+ state.inFlight = void 0;
5796
+ });
5797
+ state.inFlight = request;
5798
+ this.autoTracePolicyRefreshes.set(traceFunctionKey, state);
5799
+ }
5539
5800
  /**
5540
5801
  * Flush and permanently close this client's tracing resources: its pending
5541
5802
  * requests and the single span-transport worker shared by its decorators and
@@ -6082,7 +6343,10 @@ var Bitfab = class {
6082
6343
  parentSpanId,
6083
6344
  inputs,
6084
6345
  startedAt,
6085
- spanType: options.type ?? "custom"
6346
+ spanType: options.type ?? "custom",
6347
+ functionId: options.functionId,
6348
+ captureContent: options.captureContent ?? true,
6349
+ autoTraceDefinition: options.autoTraceDefinition
6086
6350
  };
6087
6351
  const sendSpan = async (params) => {
6088
6352
  const replayCtx = getReplayContext();
@@ -6247,7 +6511,16 @@ var Bitfab = class {
6247
6511
  }
6248
6512
  };
6249
6513
  executeWithContext = () => {
6250
- const result = fn.apply(this, args);
6514
+ let result;
6515
+ try {
6516
+ result = fn.apply(this, args);
6517
+ } catch (error) {
6518
+ void sendSpan({
6519
+ result: void 0,
6520
+ error: error instanceof Error ? error.message : String(error)
6521
+ });
6522
+ throw error;
6523
+ }
6251
6524
  if (result instanceof Promise) {
6252
6525
  return result.then((resolvedResult) => {
6253
6526
  recordSpan(resolvedResult);
@@ -6488,8 +6761,8 @@ var Bitfab = class {
6488
6761
  * Queued on the client's span transport; delivery is the transport's job.
6489
6762
  */
6490
6763
  sendWrapperSpan(params) {
6491
- const serializedInputs = serializeValue(params.inputs);
6492
- const serializedResult = serializeValue(params.result);
6764
+ const serializedInputs = params.captureContent ? serializeValue(params.inputs) : void 0;
6765
+ const serializedResult = params.captureContent ? serializeValue(params.result) : void 0;
6493
6766
  const externalSpan = {
6494
6767
  id: params.spanId,
6495
6768
  trace_id: params.traceId,
@@ -6498,26 +6771,38 @@ var Bitfab = class {
6498
6771
  span_data: {
6499
6772
  name: params.spanName,
6500
6773
  type: params.spanType,
6501
- input: serializedInputs.json,
6502
- output: serializedResult.json,
6503
- // Include superjson meta for type preservation
6504
- ...serializedInputs.meta !== void 0 && {
6505
- input_meta: serializedInputs.meta
6774
+ ...params.functionId !== void 0 && {
6775
+ function_id: params.functionId,
6776
+ content_captured: params.captureContent
6777
+ },
6778
+ ...params.autoTraceDefinition !== void 0 && {
6779
+ function_file: params.autoTraceDefinition.file,
6780
+ function_line: params.autoTraceDefinition.line,
6781
+ function_column: params.autoTraceDefinition.column
6506
6782
  },
6507
- ...serializedResult.meta !== void 0 && {
6508
- output_meta: serializedResult.meta
6783
+ ...serializedInputs !== void 0 && {
6784
+ input: serializedInputs.json,
6785
+ ...serializedInputs.meta !== void 0 && {
6786
+ input_meta: serializedInputs.meta
6787
+ }
6788
+ },
6789
+ ...serializedResult !== void 0 && {
6790
+ output: serializedResult.json,
6791
+ ...serializedResult.meta !== void 0 && {
6792
+ output_meta: serializedResult.meta
6793
+ }
6509
6794
  },
6510
6795
  ...params.functionName !== void 0 && {
6511
6796
  function_name: params.functionName
6512
6797
  },
6513
- ...params.error !== void 0 && {
6798
+ ...params.captureContent && params.error !== void 0 && {
6514
6799
  error: params.error,
6515
6800
  error_source: "code"
6516
6801
  },
6517
- ...params.contexts && params.contexts.length > 0 && {
6802
+ ...params.captureContent && params.contexts && params.contexts.length > 0 && {
6518
6803
  contexts: params.contexts
6519
6804
  },
6520
- ...params.prompt !== void 0 && { prompt: params.prompt }
6805
+ ...params.captureContent && params.prompt !== void 0 && { prompt: params.prompt }
6521
6806
  }
6522
6807
  };
6523
6808
  if (params.parentSpanId) {