@bitfab/sdk 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.
@@ -1,22 +1,30 @@
1
+ import {
2
+ __setBitfabAutoTraceCapturePolicy,
3
+ getAutoTraceCapturePolicy,
4
+ runWithAutoTraceContext,
5
+ runWithAutoTraceRootContext
6
+ } from "./chunk-GFBQ2AMO.js";
1
7
  import {
2
8
  BitfabError,
3
9
  DEFAULT_SERVICE_URL,
4
10
  HttpClient,
5
- __privateAdd,
6
- __privateGet,
7
- __privateSet,
8
- asyncStorageReady,
9
- createAsyncLocalStorage,
10
11
  deserializeValue,
11
12
  getReplayContext,
12
- isAsyncStorageInitDone,
13
13
  randomUuid,
14
14
  resolveMockValue,
15
15
  serializeValue,
16
16
  toJsonSafe,
17
17
  toJsonSafeReport,
18
18
  warnOnce
19
- } from "./chunk-MGA7ROIK.js";
19
+ } from "./chunk-WX6AEFCP.js";
20
+ import {
21
+ __privateAdd,
22
+ __privateGet,
23
+ __privateSet,
24
+ asyncStorageReady,
25
+ createAsyncLocalStorage,
26
+ isAsyncStorageInitDone
27
+ } from "./chunk-H6LZRFMN.js";
20
28
 
21
29
  // src/processorPayload.ts
22
30
  var SERIALIZATION_DEGRADED_STEP = "serialization_degraded";
@@ -2337,6 +2345,14 @@ function readEnv(name) {
2337
2345
  }
2338
2346
  return void 0;
2339
2347
  }
2348
+ var DEFAULT_AUTO_TRACE_MAX_DEPTH = 30;
2349
+ var DEFAULT_AUTO_TRACE_MAX_SPANS = 500;
2350
+ var AUTO_TRACE_PROTOCOL = "ts-auto-v1";
2351
+ var AUTO_TRACE_POLICY_REFRESH_MS = 6e4;
2352
+ var AUTO_TRACE_POLICY_RETRY_MS = 1e4;
2353
+ function autoTraceLimit(value, fallback) {
2354
+ return value !== void 0 && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
2355
+ }
2340
2356
  var Bitfab = class {
2341
2357
  /**
2342
2358
  * Initialize the Bitfab client.
@@ -2346,6 +2362,7 @@ var Bitfab = class {
2346
2362
  constructor(config) {
2347
2363
  /** Gate the empty-key warning to fire at most once. */
2348
2364
  this.apiKeyWarned = false;
2365
+ this.autoTracePolicyRefreshes = /* @__PURE__ */ new Map();
2349
2366
  /**
2350
2367
  * Mock overrides registered via {@link Bitfab.registerMockOverride}, applied
2351
2368
  * to every `replay` on this client (after any per-call `mockOverride`). In
@@ -2369,6 +2386,178 @@ var Bitfab = class {
2369
2386
  timeout: this.timeout
2370
2387
  });
2371
2388
  }
2389
+ /**
2390
+ * Decorate a class method as an automatically expanded trace root.
2391
+ *
2392
+ * Build instrumentation turns repository functions called beneath this
2393
+ * method into nested spans. Every generated span preserves structure; only
2394
+ * function IDs selected by the capture policy include inputs and output.
2395
+ * Without a compatible build transform, this still records the decorated
2396
+ * method as a normal rich root span but cannot discover child calls.
2397
+ *
2398
+ * @param traceFunctionKey - Groups traces and their capture policy.
2399
+ * @param options - Root presentation, subtree bounds, and exclusions.
2400
+ * @experimental Automatic child-call instrumentation is experimental.
2401
+ */
2402
+ trace(traceFunctionKey, options = {}) {
2403
+ const decorator = (...args) => {
2404
+ if (args.length === 3) {
2405
+ const propertyKey = args[1];
2406
+ const descriptor = args[2];
2407
+ if (!descriptor || typeof descriptor.value !== "function") {
2408
+ throw new BitfabError("@bitfab.trace can only decorate methods");
2409
+ }
2410
+ if (!this.explicitlyEnabled) {
2411
+ return;
2412
+ }
2413
+ descriptor.value = this.createAutoTraceRoot(
2414
+ traceFunctionKey,
2415
+ String(propertyKey),
2416
+ options,
2417
+ descriptor.value
2418
+ );
2419
+ return;
2420
+ }
2421
+ const method = args[0];
2422
+ const context = args[1];
2423
+ if (typeof method !== "function" || context?.kind !== "method" || context.name === void 0) {
2424
+ throw new BitfabError("@bitfab.trace can only decorate methods");
2425
+ }
2426
+ if (!this.explicitlyEnabled) {
2427
+ return method;
2428
+ }
2429
+ return this.createAutoTraceRoot(
2430
+ traceFunctionKey,
2431
+ String(context.name),
2432
+ options,
2433
+ method
2434
+ );
2435
+ };
2436
+ return decorator;
2437
+ }
2438
+ withTrace(traceFunctionKey, optionsOrFn, maybeFn) {
2439
+ const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
2440
+ const fn = typeof optionsOrFn === "function" ? optionsOrFn : maybeFn;
2441
+ if (!fn) {
2442
+ throw new BitfabError("bitfab.withTrace requires a function");
2443
+ }
2444
+ if (!this.explicitlyEnabled) {
2445
+ return fn;
2446
+ }
2447
+ const name = fn.name !== "" ? fn.name : traceFunctionKey;
2448
+ return this.createAutoTraceRoot(traceFunctionKey, name, options, fn);
2449
+ }
2450
+ createAutoTraceRoot(traceFunctionKey, name, options, fn) {
2451
+ const self = this;
2452
+ const maxDepth = autoTraceLimit(
2453
+ options.maxDepth,
2454
+ DEFAULT_AUTO_TRACE_MAX_DEPTH
2455
+ );
2456
+ const maxSpans = autoTraceLimit(
2457
+ options.maxSpans,
2458
+ DEFAULT_AUTO_TRACE_MAX_SPANS
2459
+ );
2460
+ const excluded = new Set(options.exclude ?? []);
2461
+ const includeWrappers = options.includeWrappers ?? false;
2462
+ const tracedRoot = this.withSpan(
2463
+ traceFunctionKey,
2464
+ { name: options.name ?? name, type: options.type ?? "custom" },
2465
+ function(...args) {
2466
+ const capturePolicy = getAutoTraceCapturePolicy(self, traceFunctionKey);
2467
+ self.refreshAutoTraceCapturePolicy(traceFunctionKey);
2468
+ let spansUsed = 0;
2469
+ let truncated = false;
2470
+ const warnTruncated = () => {
2471
+ if (!truncated) {
2472
+ truncated = true;
2473
+ getCurrentTrace().setMetadata({
2474
+ bitfabAutoTrace: {
2475
+ protocol: AUTO_TRACE_PROTOCOL,
2476
+ truncated: true,
2477
+ maxDepth,
2478
+ maxSpans
2479
+ }
2480
+ });
2481
+ }
2482
+ warnOnce(
2483
+ `auto-trace-truncated:${traceFunctionKey}`,
2484
+ `"${traceFunctionKey}" hit an automatic subtree capture limit (maxDepth=${maxDepth}, maxSpans=${maxSpans}); its trace is incomplete. Raise the limits or narrow the subtree with exclude.`
2485
+ );
2486
+ };
2487
+ const autoTraceContext = {
2488
+ invoke(definition, inputs, invokeFn, depth) {
2489
+ const nameParts = definition.name.split(".");
2490
+ const simpleName = nameParts[nameParts.length - 1];
2491
+ if (excluded.has(definition.name) || simpleName !== void 0 && excluded.has(simpleName) || definition.wrapper === true && !includeWrappers) {
2492
+ return invokeFn();
2493
+ }
2494
+ if (depth >= maxDepth || spansUsed >= maxSpans) {
2495
+ warnTruncated();
2496
+ return invokeFn();
2497
+ }
2498
+ spansUsed += 1;
2499
+ const childOptions = {
2500
+ name: definition.name,
2501
+ type: "function",
2502
+ captureWhen: "nested",
2503
+ functionId: definition.id,
2504
+ captureContent: capturePolicy.has(definition.id),
2505
+ autoTraceDefinition: definition
2506
+ };
2507
+ const tracedChild = self.withSpan(
2508
+ traceFunctionKey,
2509
+ childOptions,
2510
+ (..._inputs) => runWithAutoTraceContext(autoTraceContext, invokeFn, depth + 1)
2511
+ );
2512
+ return tracedChild(...inputs);
2513
+ }
2514
+ };
2515
+ return runWithAutoTraceRootContext(
2516
+ autoTraceContext,
2517
+ () => fn.apply(this, args)
2518
+ );
2519
+ }
2520
+ );
2521
+ const autoTraceRoot = function(...args) {
2522
+ if (!self.isTracingEnabled()) {
2523
+ return fn.apply(this, args);
2524
+ }
2525
+ return tracedRoot.apply(this, args);
2526
+ };
2527
+ Object.defineProperty(autoTraceRoot, "_bitfabTraceFunctionKey", {
2528
+ value: traceFunctionKey
2529
+ });
2530
+ return autoTraceRoot;
2531
+ }
2532
+ refreshAutoTraceCapturePolicy(traceFunctionKey) {
2533
+ const now = Date.now();
2534
+ const state = this.autoTracePolicyRefreshes.get(traceFunctionKey) ?? {
2535
+ refreshAfter: 0
2536
+ };
2537
+ if (state.inFlight || now < state.refreshAfter) {
2538
+ return;
2539
+ }
2540
+ const request = this.httpClient.getAutoTracePolicy(
2541
+ traceFunctionKey,
2542
+ AUTO_TRACE_PROTOCOL
2543
+ ).then((policy) => {
2544
+ if (policy.protocol !== AUTO_TRACE_PROTOCOL) {
2545
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS;
2546
+ return;
2547
+ }
2548
+ const functionIds = Array.isArray(policy.functionIds) ? policy.functionIds.filter(
2549
+ (id) => typeof id === "string" && id.startsWith(`${AUTO_TRACE_PROTOCOL}:`)
2550
+ ).slice(0, DEFAULT_AUTO_TRACE_MAX_SPANS) : [];
2551
+ __setBitfabAutoTraceCapturePolicy(this, traceFunctionKey, functionIds);
2552
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_REFRESH_MS;
2553
+ }).catch(() => {
2554
+ state.refreshAfter = Date.now() + AUTO_TRACE_POLICY_RETRY_MS;
2555
+ }).finally(() => {
2556
+ state.inFlight = void 0;
2557
+ });
2558
+ state.inFlight = request;
2559
+ this.autoTracePolicyRefreshes.set(traceFunctionKey, state);
2560
+ }
2372
2561
  /**
2373
2562
  * Flush and permanently close this client's tracing resources: its pending
2374
2563
  * requests and the single span-transport worker shared by its decorators and
@@ -2915,7 +3104,10 @@ var Bitfab = class {
2915
3104
  parentSpanId,
2916
3105
  inputs,
2917
3106
  startedAt,
2918
- spanType: options.type ?? "custom"
3107
+ spanType: options.type ?? "custom",
3108
+ functionId: options.functionId,
3109
+ captureContent: options.captureContent ?? true,
3110
+ autoTraceDefinition: options.autoTraceDefinition
2919
3111
  };
2920
3112
  const sendSpan = async (params) => {
2921
3113
  const replayCtx = getReplayContext();
@@ -3080,7 +3272,16 @@ var Bitfab = class {
3080
3272
  }
3081
3273
  };
3082
3274
  executeWithContext = () => {
3083
- const result = fn.apply(this, args);
3275
+ let result;
3276
+ try {
3277
+ result = fn.apply(this, args);
3278
+ } catch (error) {
3279
+ void sendSpan({
3280
+ result: void 0,
3281
+ error: error instanceof Error ? error.message : String(error)
3282
+ });
3283
+ throw error;
3284
+ }
3084
3285
  if (result instanceof Promise) {
3085
3286
  return result.then((resolvedResult) => {
3086
3287
  recordSpan(resolvedResult);
@@ -3321,8 +3522,8 @@ var Bitfab = class {
3321
3522
  * Queued on the client's span transport; delivery is the transport's job.
3322
3523
  */
3323
3524
  sendWrapperSpan(params) {
3324
- const serializedInputs = serializeValue(params.inputs);
3325
- const serializedResult = serializeValue(params.result);
3525
+ const serializedInputs = params.captureContent ? serializeValue(params.inputs) : void 0;
3526
+ const serializedResult = params.captureContent ? serializeValue(params.result) : void 0;
3326
3527
  const externalSpan = {
3327
3528
  id: params.spanId,
3328
3529
  trace_id: params.traceId,
@@ -3331,26 +3532,38 @@ var Bitfab = class {
3331
3532
  span_data: {
3332
3533
  name: params.spanName,
3333
3534
  type: params.spanType,
3334
- input: serializedInputs.json,
3335
- output: serializedResult.json,
3336
- // Include superjson meta for type preservation
3337
- ...serializedInputs.meta !== void 0 && {
3338
- input_meta: serializedInputs.meta
3535
+ ...params.functionId !== void 0 && {
3536
+ function_id: params.functionId,
3537
+ content_captured: params.captureContent
3538
+ },
3539
+ ...params.autoTraceDefinition !== void 0 && {
3540
+ function_file: params.autoTraceDefinition.file,
3541
+ function_line: params.autoTraceDefinition.line,
3542
+ function_column: params.autoTraceDefinition.column
3339
3543
  },
3340
- ...serializedResult.meta !== void 0 && {
3341
- output_meta: serializedResult.meta
3544
+ ...serializedInputs !== void 0 && {
3545
+ input: serializedInputs.json,
3546
+ ...serializedInputs.meta !== void 0 && {
3547
+ input_meta: serializedInputs.meta
3548
+ }
3549
+ },
3550
+ ...serializedResult !== void 0 && {
3551
+ output: serializedResult.json,
3552
+ ...serializedResult.meta !== void 0 && {
3553
+ output_meta: serializedResult.meta
3554
+ }
3342
3555
  },
3343
3556
  ...params.functionName !== void 0 && {
3344
3557
  function_name: params.functionName
3345
3558
  },
3346
- ...params.error !== void 0 && {
3559
+ ...params.captureContent && params.error !== void 0 && {
3347
3560
  error: params.error,
3348
3561
  error_source: "code"
3349
3562
  },
3350
- ...params.contexts && params.contexts.length > 0 && {
3563
+ ...params.captureContent && params.contexts && params.contexts.length > 0 && {
3351
3564
  contexts: params.contexts
3352
3565
  },
3353
- ...params.prompt !== void 0 && { prompt: params.prompt }
3566
+ ...params.captureContent && params.prompt !== void 0 && { prompt: params.prompt }
3354
3567
  }
3355
3568
  };
3356
3569
  if (params.parentSpanId) {
@@ -3395,7 +3608,7 @@ var Bitfab = class {
3395
3608
  `Function is wrapped with trace function key '${wrappedKey}' but replay was called with '${traceFunctionKey}'. Pass matching keys, or pass the unwrapped function to replay it under the explicit key.`
3396
3609
  );
3397
3610
  }
3398
- const { replay: doReplay } = await import("./replay-WSFDZ2UV.js");
3611
+ const { replay: doReplay } = await import("./replay-FAO7D7CG.js");
3399
3612
  return doReplay(
3400
3613
  this.httpClient,
3401
3614
  this.serviceUrl,
@@ -3619,6 +3832,11 @@ var finalizers = {
3619
3832
  readableStream
3620
3833
  };
3621
3834
 
3835
+ // src/replayRegistry.ts
3836
+ function defineReplayRegistry(registry) {
3837
+ return registry;
3838
+ }
3839
+
3622
3840
  export {
3623
3841
  BitfabClaudeAgentHandler,
3624
3842
  SUPPORTED_PROVIDERS,
@@ -3631,6 +3849,7 @@ export {
3631
3849
  getCurrentTrace,
3632
3850
  Bitfab,
3633
3851
  BitfabFunction,
3634
- finalizers
3852
+ finalizers,
3853
+ defineReplayRegistry
3635
3854
  };
3636
- //# sourceMappingURL=chunk-WD4AO3BK.js.map
3855
+ //# sourceMappingURL=chunk-RJPHMJWO.js.map