bitfab 0.38.0 → 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
@@ -2656,14 +2710,14 @@ declare class BitfabFunction {
2656
2710
  }
2657
2711
 
2658
2712
  /**
2659
- * Auto-generated version file.
2713
+ * Auto-generated package metadata.
2660
2714
  * This file is generated by scripts/generate-version.ts during build.
2661
2715
  * DO NOT EDIT MANUALLY.
2662
2716
  */
2663
2717
  /**
2664
2718
  * SDK version from package.json (injected at build time)
2665
2719
  */
2666
- declare const __version__ = "0.38.0";
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
@@ -2656,14 +2710,14 @@ declare class BitfabFunction {
2656
2710
  }
2657
2711
 
2658
2712
  /**
2659
- * Auto-generated version file.
2713
+ * Auto-generated package metadata.
2660
2714
  * This file is generated by scripts/generate-version.ts during build.
2661
2715
  * DO NOT EDIT MANUALLY.
2662
2716
  */
2663
2717
  /**
2664
2718
  * SDK version from package.json (injected at build time)
2665
2719
  */
2666
- declare const __version__ = "0.38.0";
2720
+ declare const __version__ = "0.38.2";
2667
2721
 
2668
2722
  /**
2669
2723
  * Constants for the Bitfab SDK.
package/dist/index.js CHANGED
@@ -20,7 +20,8 @@ import {
20
20
  getCurrentReplayBranch,
21
21
  getCurrentSpan,
22
22
  getCurrentTrace
23
- } from "./chunk-LCGQUVKR.js";
23
+ } from "./chunk-JSU2Z2Z7.js";
24
+ import "./chunk-GFBQ2AMO.js";
24
25
  import {
25
26
  BITFAB_PROGRESS_PREFIX,
26
27
  BitfabError,
@@ -32,7 +33,8 @@ import {
32
33
  flushTraces,
33
34
  reportReplayProgress,
34
35
  serializeReplayResult
35
- } from "./chunk-SSNTMROV.js";
36
+ } from "./chunk-QWV7JDLQ.js";
37
+ import "./chunk-H6LZRFMN.js";
36
38
  export {
37
39
  BITFAB_PROGRESS_PREFIX,
38
40
  Bitfab,
package/dist/node.cjs CHANGED
@@ -93,11 +93,12 @@ var init_asyncStorage = __esm({
93
93
  });
94
94
 
95
95
  // src/version.generated.ts
96
- var __version__;
96
+ var __version__, __packageName__;
97
97
  var init_version_generated = __esm({
98
98
  "src/version.generated.ts"() {
99
99
  "use strict";
100
- __version__ = "0.38.0";
100
+ __version__ = "0.38.2";
101
+ __packageName__ = "bitfab";
101
102
  }
102
103
  });
103
104
 
@@ -827,7 +828,7 @@ var init_otel = __esm({
827
828
  EXPORT_CONCURRENCY_ENV = "BITFAB_OTEL_EXPORT_CONCURRENCY";
828
829
  MAX_QUEUE_SIZE = 8192;
829
830
  DIRECT_MAX_EXPORT_BATCH_SIZE = 512;
830
- DIRECT_MAX_REQUEST_BATCH_SIZE = 8;
831
+ DIRECT_MAX_REQUEST_BATCH_SIZE = 128;
831
832
  DEFAULT_EXPORT_CONCURRENCY = 32;
832
833
  MAX_EXPORT_CONCURRENCY = 64;
833
834
  SCHEDULE_DELAY_MILLIS = 5e3;
@@ -1719,6 +1720,12 @@ var init_http = __esm({
1719
1720
  async lookupFunction(name) {
1720
1721
  return this.request("/api/sdk/functions/lookup", { name });
1721
1722
  }
1723
+ async getAutoTracePolicy(traceFunctionKey, protocol) {
1724
+ return this.request("/api/sdk/auto-trace/policy", {
1725
+ traceFunctionKey,
1726
+ protocol
1727
+ });
1728
+ }
1722
1729
  async getTraceSpan(traceId, lookup) {
1723
1730
  const searchParams = new URLSearchParams();
1724
1731
  if (lookup.id !== void 0) {
@@ -1769,7 +1776,12 @@ var init_http = __esm({
1769
1776
  * the OTLP carrier has no path to carry it.
1770
1777
  */
1771
1778
  sendInternalTrace(functionId, payload) {
1772
- const body = { ...payload, functionId, sdkVersion: __version__ };
1779
+ const body = {
1780
+ ...payload,
1781
+ functionId,
1782
+ sdkPackage: __packageName__,
1783
+ sdkVersion: __version__
1784
+ };
1773
1785
  this.getTraceTransport()?.submit(
1774
1786
  "internal_trace",
1775
1787
  body,
@@ -1798,7 +1810,11 @@ var init_http = __esm({
1798
1810
  sendExternalTrace(payload) {
1799
1811
  this.getTraceTransport()?.submit(
1800
1812
  "external_trace",
1801
- { ...payload, sdkVersion: __version__ },
1813
+ {
1814
+ ...payload,
1815
+ sdkPackage: __packageName__,
1816
+ sdkVersion: __version__
1817
+ },
1802
1818
  this.recordedMeta(
1803
1819
  "external_trace",
1804
1820
  payload,
@@ -3762,6 +3778,80 @@ var BitfabClaudeAgentHandler = class {
3762
3778
  // src/client.ts
3763
3779
  init_asyncStorage();
3764
3780
 
3781
+ // src/autoTrace.ts
3782
+ init_asyncStorage();
3783
+ var autoTraceGlobal = globalThis;
3784
+ var autoTraceState = autoTraceGlobal.__bitfabAutoTraceStateV3 ?? {
3785
+ storage: null,
3786
+ browserScope: void 0,
3787
+ capturePolicies: /* @__PURE__ */ new WeakMap(),
3788
+ activeRoots: 0
3789
+ };
3790
+ autoTraceGlobal.__bitfabAutoTraceStateV3 = autoTraceState;
3791
+ function initializeAutoTraceStorage() {
3792
+ autoTraceState.storage ?? (autoTraceState.storage = createAsyncLocalStorage());
3793
+ }
3794
+ function runWithAutoTraceContext(context, fn, depth = 0) {
3795
+ initializeAutoTraceStorage();
3796
+ const scope = { context, depth };
3797
+ if (autoTraceState.storage) {
3798
+ return autoTraceState.storage.run(scope, fn);
3799
+ }
3800
+ const previous = autoTraceState.browserScope;
3801
+ autoTraceState.browserScope = scope;
3802
+ try {
3803
+ return fn();
3804
+ } finally {
3805
+ autoTraceState.browserScope = previous;
3806
+ }
3807
+ }
3808
+ function runWithAutoTraceRootContext(context, fn) {
3809
+ autoTraceState.activeRoots += 1;
3810
+ let result;
3811
+ try {
3812
+ result = runWithAutoTraceContext(context, fn);
3813
+ } catch (error) {
3814
+ autoTraceState.activeRoots -= 1;
3815
+ throw error;
3816
+ }
3817
+ if (isAutoTraceAsyncGenerator(result)) {
3818
+ autoTraceState.activeRoots -= 1;
3819
+ return wrapAutoTraceAsyncGenerator(context, result);
3820
+ }
3821
+ if (result instanceof Promise) {
3822
+ return result.finally(() => {
3823
+ autoTraceState.activeRoots -= 1;
3824
+ });
3825
+ }
3826
+ autoTraceState.activeRoots -= 1;
3827
+ return result;
3828
+ }
3829
+ function isAutoTraceAsyncGenerator(value) {
3830
+ if (value === null || typeof value !== "object") {
3831
+ return false;
3832
+ }
3833
+ const candidate = value;
3834
+ return typeof candidate.next === "function" && typeof candidate.return === "function" && typeof candidate.throw === "function" && typeof candidate[Symbol.asyncIterator] === "function";
3835
+ }
3836
+ function wrapAutoTraceAsyncGenerator(context, source) {
3837
+ const step = (method, value) => runWithAutoTraceRootContext(context, () => source[method](value));
3838
+ const wrapped = {
3839
+ next: (value) => step("next", value),
3840
+ return: (value) => step("return", value),
3841
+ throw: (error) => step("throw", error),
3842
+ [Symbol.asyncIterator]: () => wrapped
3843
+ };
3844
+ return wrapped;
3845
+ }
3846
+ function __setBitfabAutoTraceCapturePolicy(client, traceFunctionKey, functionIds) {
3847
+ const policies = autoTraceState.capturePolicies.get(client) ?? /* @__PURE__ */ new Map();
3848
+ policies.set(traceFunctionKey, new Set(functionIds));
3849
+ autoTraceState.capturePolicies.set(client, policies);
3850
+ }
3851
+ function getAutoTraceCapturePolicy(client, traceFunctionKey) {
3852
+ return autoTraceState.capturePolicies.get(client)?.get(traceFunctionKey) ?? /* @__PURE__ */ new Set();
3853
+ }
3854
+
3765
3855
  // src/optionalPeer.ts
3766
3856
  function importOptionalPeer(specifierParts) {
3767
3857
  const specifier = specifierParts.join("/");
@@ -5503,6 +5593,14 @@ function readEnv2(name) {
5503
5593
  }
5504
5594
  return void 0;
5505
5595
  }
5596
+ var DEFAULT_AUTO_TRACE_MAX_DEPTH = 30;
5597
+ var DEFAULT_AUTO_TRACE_MAX_SPANS = 500;
5598
+ var AUTO_TRACE_PROTOCOL = "ts-auto-v1";
5599
+ var AUTO_TRACE_POLICY_REFRESH_MS = 6e4;
5600
+ var AUTO_TRACE_POLICY_RETRY_MS = 1e4;
5601
+ function autoTraceLimit(value, fallback) {
5602
+ return value !== void 0 && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
5603
+ }
5506
5604
  var Bitfab = class {
5507
5605
  /**
5508
5606
  * Initialize the Bitfab client.
@@ -5512,6 +5610,7 @@ var Bitfab = class {
5512
5610
  constructor(config) {
5513
5611
  /** Gate the empty-key warning to fire at most once. */
5514
5612
  this.apiKeyWarned = false;
5613
+ this.autoTracePolicyRefreshes = /* @__PURE__ */ new Map();
5515
5614
  /**
5516
5615
  * Mock overrides registered via {@link Bitfab.registerMockOverride}, applied
5517
5616
  * to every `replay` on this client (after any per-call `mockOverride`). In
@@ -5535,6 +5634,178 @@ var Bitfab = class {
5535
5634
  timeout: this.timeout
5536
5635
  });
5537
5636
  }
5637
+ /**
5638
+ * Decorate a class method as an automatically expanded trace root.
5639
+ *
5640
+ * Build instrumentation turns repository functions called beneath this
5641
+ * method into nested spans. Every generated span preserves structure; only
5642
+ * function IDs selected by the capture policy include inputs and output.
5643
+ * Without a compatible build transform, this still records the decorated
5644
+ * method as a normal rich root span but cannot discover child calls.
5645
+ *
5646
+ * @param traceFunctionKey - Groups traces and their capture policy.
5647
+ * @param options - Root presentation, subtree bounds, and exclusions.
5648
+ * @experimental Automatic child-call instrumentation is experimental.
5649
+ */
5650
+ trace(traceFunctionKey, options = {}) {
5651
+ const decorator = (...args) => {
5652
+ if (args.length === 3) {
5653
+ const propertyKey = args[1];
5654
+ const descriptor = args[2];
5655
+ if (!descriptor || typeof descriptor.value !== "function") {
5656
+ throw new BitfabError("@bitfab.trace can only decorate methods");
5657
+ }
5658
+ if (!this.explicitlyEnabled) {
5659
+ return;
5660
+ }
5661
+ descriptor.value = this.createAutoTraceRoot(
5662
+ traceFunctionKey,
5663
+ String(propertyKey),
5664
+ options,
5665
+ descriptor.value
5666
+ );
5667
+ return;
5668
+ }
5669
+ const method = args[0];
5670
+ const context = args[1];
5671
+ if (typeof method !== "function" || context?.kind !== "method" || context.name === void 0) {
5672
+ throw new BitfabError("@bitfab.trace can only decorate methods");
5673
+ }
5674
+ if (!this.explicitlyEnabled) {
5675
+ return method;
5676
+ }
5677
+ return this.createAutoTraceRoot(
5678
+ traceFunctionKey,
5679
+ String(context.name),
5680
+ options,
5681
+ method
5682
+ );
5683
+ };
5684
+ return decorator;
5685
+ }
5686
+ withTrace(traceFunctionKey, optionsOrFn, maybeFn) {
5687
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
5688
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
5689
+ if (!fn) {
5690
+ throw new BitfabError("bitfab.withTrace requires a function");
5691
+ }
5692
+ if (!this.explicitlyEnabled) {
5693
+ return fn;
5694
+ }
5695
+ const name = fn.name !== "" ? fn.name : traceFunctionKey;
5696
+ return this.createAutoTraceRoot(traceFunctionKey, name, options, fn);
5697
+ }
5698
+ createAutoTraceRoot(traceFunctionKey, name, options, fn) {
5699
+ const self = this;
5700
+ const maxDepth = autoTraceLimit(
5701
+ options.maxDepth,
5702
+ DEFAULT_AUTO_TRACE_MAX_DEPTH
5703
+ );
5704
+ const maxSpans = autoTraceLimit(
5705
+ options.maxSpans,
5706
+ DEFAULT_AUTO_TRACE_MAX_SPANS
5707
+ );
5708
+ const excluded = new Set(options.exclude ?? []);
5709
+ const includeWrappers = options.includeWrappers ?? false;
5710
+ const tracedRoot = this.withSpan(
5711
+ traceFunctionKey,
5712
+ { name: options.name ?? name, type: options.type ?? "custom" },
5713
+ function(...args) {
5714
+ const capturePolicy = getAutoTraceCapturePolicy(self, traceFunctionKey);
5715
+ self.refreshAutoTraceCapturePolicy(traceFunctionKey);
5716
+ let spansUsed = 0;
5717
+ let truncated = false;
5718
+ const warnTruncated = () => {
5719
+ if (!truncated) {
5720
+ truncated = true;
5721
+ getCurrentTrace().setMetadata({
5722
+ bitfabAutoTrace: {
5723
+ protocol: AUTO_TRACE_PROTOCOL,
5724
+ truncated: true,
5725
+ maxDepth,
5726
+ maxSpans
5727
+ }
5728
+ });
5729
+ }
5730
+ warnOnce(
5731
+ `auto-trace-truncated:${traceFunctionKey}`,
5732
+ `"${traceFunctionKey}" hit an automatic subtree capture limit (maxDepth=${maxDepth}, maxSpans=${maxSpans}); its trace is incomplete. Raise the limits or narrow the subtree with exclude.`
5733
+ );
5734
+ };
5735
+ const autoTraceContext = {
5736
+ invoke(definition, inputs, invokeFn, depth) {
5737
+ const nameParts = definition.name.split(".");
5738
+ const simpleName = nameParts[nameParts.length - 1];
5739
+ if (excluded.has(definition.name) || simpleName !== void 0 && excluded.has(simpleName) || definition.wrapper === true && !includeWrappers) {
5740
+ return invokeFn();
5741
+ }
5742
+ if (depth >= maxDepth || spansUsed >= maxSpans) {
5743
+ warnTruncated();
5744
+ return invokeFn();
5745
+ }
5746
+ spansUsed += 1;
5747
+ const childOptions = {
5748
+ name: definition.name,
5749
+ type: "function",
5750
+ captureWhen: "nested",
5751
+ functionId: definition.id,
5752
+ captureContent: capturePolicy.has(definition.id),
5753
+ autoTraceDefinition: definition
5754
+ };
5755
+ const tracedChild = self.withSpan(
5756
+ traceFunctionKey,
5757
+ childOptions,
5758
+ (..._inputs) => runWithAutoTraceContext(autoTraceContext, invokeFn, depth + 1)
5759
+ );
5760
+ return tracedChild(...inputs);
5761
+ }
5762
+ };
5763
+ return runWithAutoTraceRootContext(
5764
+ autoTraceContext,
5765
+ () => fn.apply(this, args)
5766
+ );
5767
+ }
5768
+ );
5769
+ const autoTraceRoot = function(...args) {
5770
+ if (!self.isTracingEnabled()) {
5771
+ return fn.apply(this, args);
5772
+ }
5773
+ return tracedRoot.apply(this, args);
5774
+ };
5775
+ Object.defineProperty(autoTraceRoot, "_bitfabTraceFunctionKey", {
5776
+ value: traceFunctionKey
5777
+ });
5778
+ return autoTraceRoot;
5779
+ }
5780
+ refreshAutoTraceCapturePolicy(traceFunctionKey) {
5781
+ const now = Date.now();
5782
+ const state = this.autoTracePolicyRefreshes.get(traceFunctionKey) ?? {
5783
+ refreshAfter: 0
5784
+ };
5785
+ if (state.inFlight || now < state.refreshAfter) {
5786
+ return;
5787
+ }
5788
+ const request = this.httpClient.getAutoTracePolicy(
5789
+ traceFunctionKey,
5790
+ AUTO_TRACE_PROTOCOL
5791
+ ).then((policy) => {
5792
+ if (policy.protocol !== AUTO_TRACE_PROTOCOL) {
5793
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS;
5794
+ return;
5795
+ }
5796
+ const functionIds = Array.isArray(policy.functionIds) ? policy.functionIds.filter(
5797
+ (id) => typeof id === "string" && id.startsWith(`${AUTO_TRACE_PROTOCOL}:`)
5798
+ ).slice(0, DEFAULT_AUTO_TRACE_MAX_SPANS) : [];
5799
+ __setBitfabAutoTraceCapturePolicy(this, traceFunctionKey, functionIds);
5800
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_REFRESH_MS;
5801
+ }).catch(() => {
5802
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS;
5803
+ }).finally(() => {
5804
+ state.inFlight = void 0;
5805
+ });
5806
+ state.inFlight = request;
5807
+ this.autoTracePolicyRefreshes.set(traceFunctionKey, state);
5808
+ }
5538
5809
  /**
5539
5810
  * Flush and permanently close this client's tracing resources: its pending
5540
5811
  * requests and the single span-transport worker shared by its decorators and
@@ -6081,7 +6352,10 @@ var Bitfab = class {
6081
6352
  parentSpanId,
6082
6353
  inputs,
6083
6354
  startedAt,
6084
- spanType: options.type ?? "custom"
6355
+ spanType: options.type ?? "custom",
6356
+ functionId: options.functionId,
6357
+ captureContent: options.captureContent ?? true,
6358
+ autoTraceDefinition: options.autoTraceDefinition
6085
6359
  };
6086
6360
  const sendSpan = async (params) => {
6087
6361
  const replayCtx = getReplayContext();
@@ -6246,7 +6520,16 @@ var Bitfab = class {
6246
6520
  }
6247
6521
  };
6248
6522
  executeWithContext = () => {
6249
- const result = fn.apply(this, args);
6523
+ let result;
6524
+ try {
6525
+ result = fn.apply(this, args);
6526
+ } catch (error) {
6527
+ void sendSpan({
6528
+ result: void 0,
6529
+ error: error instanceof Error ? error.message : String(error)
6530
+ });
6531
+ throw error;
6532
+ }
6250
6533
  if (result instanceof Promise) {
6251
6534
  return result.then((resolvedResult) => {
6252
6535
  recordSpan(resolvedResult);
@@ -6487,8 +6770,8 @@ var Bitfab = class {
6487
6770
  * Queued on the client's span transport; delivery is the transport's job.
6488
6771
  */
6489
6772
  sendWrapperSpan(params) {
6490
- const serializedInputs = serializeValue(params.inputs);
6491
- const serializedResult = serializeValue(params.result);
6773
+ const serializedInputs = params.captureContent ? serializeValue(params.inputs) : void 0;
6774
+ const serializedResult = params.captureContent ? serializeValue(params.result) : void 0;
6492
6775
  const externalSpan = {
6493
6776
  id: params.spanId,
6494
6777
  trace_id: params.traceId,
@@ -6497,26 +6780,38 @@ var Bitfab = class {
6497
6780
  span_data: {
6498
6781
  name: params.spanName,
6499
6782
  type: params.spanType,
6500
- input: serializedInputs.json,
6501
- output: serializedResult.json,
6502
- // Include superjson meta for type preservation
6503
- ...serializedInputs.meta !== void 0 && {
6504
- input_meta: serializedInputs.meta
6783
+ ...params.functionId !== void 0 && {
6784
+ function_id: params.functionId,
6785
+ content_captured: params.captureContent
6786
+ },
6787
+ ...params.autoTraceDefinition !== void 0 && {
6788
+ function_file: params.autoTraceDefinition.file,
6789
+ function_line: params.autoTraceDefinition.line,
6790
+ function_column: params.autoTraceDefinition.column
6505
6791
  },
6506
- ...serializedResult.meta !== void 0 && {
6507
- output_meta: serializedResult.meta
6792
+ ...serializedInputs !== void 0 && {
6793
+ input: serializedInputs.json,
6794
+ ...serializedInputs.meta !== void 0 && {
6795
+ input_meta: serializedInputs.meta
6796
+ }
6797
+ },
6798
+ ...serializedResult !== void 0 && {
6799
+ output: serializedResult.json,
6800
+ ...serializedResult.meta !== void 0 && {
6801
+ output_meta: serializedResult.meta
6802
+ }
6508
6803
  },
6509
6804
  ...params.functionName !== void 0 && {
6510
6805
  function_name: params.functionName
6511
6806
  },
6512
- ...params.error !== void 0 && {
6807
+ ...params.captureContent && params.error !== void 0 && {
6513
6808
  error: params.error,
6514
6809
  error_source: "code"
6515
6810
  },
6516
- ...params.contexts && params.contexts.length > 0 && {
6811
+ ...params.captureContent && params.contexts && params.contexts.length > 0 && {
6517
6812
  contexts: params.contexts
6518
6813
  },
6519
- ...params.prompt !== void 0 && { prompt: params.prompt }
6814
+ ...params.captureContent && params.prompt !== void 0 && { prompt: params.prompt }
6520
6815
  }
6521
6816
  };
6522
6817
  if (params.parentSpanId) {