@bytesbrains/cruise-worker 0.14.1 → 0.16.0

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/worker/index.js CHANGED
@@ -8725,10 +8725,6 @@ function parseFrame(payload) {
8725
8725
  }
8726
8726
  __name(parseFrame, "parseFrame");
8727
8727
  var Translation = class {
8728
- constructor(model) {
8729
- this.model = model;
8730
- }
8731
- model;
8732
8728
  static {
8733
8729
  __name(this, "Translation");
8734
8730
  }
@@ -8740,6 +8736,10 @@ var Translation = class {
8740
8736
  usage = null;
8741
8737
  calledTool = false;
8742
8738
  done = false;
8739
+ model;
8740
+ constructor(model) {
8741
+ this.model = model;
8742
+ }
8743
8743
  start() {
8744
8744
  return [
8745
8745
  frame("message_start", {
@@ -11101,15 +11101,15 @@ var compressionRoutes = /* @__PURE__ */ __name(async ({ request, env, path, call
11101
11101
  if (typeof body?.enabled !== "boolean") {
11102
11102
  return errorResponse(400, "invalid_request_error", "'enabled' is required and must be true or false.", { headers: cors });
11103
11103
  }
11104
- const written2 = await setProjectCompression(
11104
+ const written = await setProjectCompression(
11105
11105
  env.DB,
11106
11106
  projectId,
11107
11107
  body.enabled,
11108
11108
  // The person, never the credential — the rule `tiers.ts` states.
11109
11109
  caller.identity.email ?? caller.identity.uid
11110
11110
  );
11111
- if (written2 === null) return noSuchProject(env.DB, caller.tenantId, projectId, cors);
11112
- return json({ project: projectId, compression: compressionView({ enabled: written2.enabled, modeInForce: compressModeOf(env) }) }, cors);
11111
+ if (written === null) return noSuchProject(env.DB, caller.tenantId, projectId, cors);
11112
+ return json({ project: projectId, compression: compressionView({ enabled: written.enabled, modeInForce: compressModeOf(env) }) }, cors);
11113
11113
  }, "compressionRoutes");
11114
11114
 
11115
11115
  // src/admin-fallbacks.ts
@@ -11387,18 +11387,244 @@ var keyRoutes = /* @__PURE__ */ __name(async ({ request, env, path, caller, cors
11387
11387
  return null;
11388
11388
  }, "keyRoutes");
11389
11389
 
11390
+ // src/lanes-warnings.ts
11391
+ var DEAR_FACTOR = 10;
11392
+ var JOB_IMPLIES = {
11393
+ "code-review": ["tools"],
11394
+ "agentic-coding": ["tools"],
11395
+ hunter: ["tools"],
11396
+ builder: ["tools"],
11397
+ "computer-use": ["tools", "vision"],
11398
+ "document-understanding": ["vision"],
11399
+ extraction: ["json_schema"],
11400
+ "rag-grounded-answers": ["json_schema"],
11401
+ "web-search": ["web_search"]
11402
+ };
11403
+ function worstCaseRate(price) {
11404
+ let input = price.input_micros_per_mtok;
11405
+ let output = price.output_micros_per_mtok;
11406
+ for (const v of price.variants) {
11407
+ input = Math.max(input, v.input_micros_per_mtok);
11408
+ output = Math.max(output, v.output_micros_per_mtok);
11409
+ }
11410
+ return input + output;
11411
+ }
11412
+ __name(worstCaseRate, "worstCaseRate");
11413
+ var perMillion = /* @__PURE__ */ __name((micros) => `$${(micros / 1e6).toFixed(2)}/M`, "perMillion");
11414
+ function laneWarnings(lane, members, routable, prices, reliability = /* @__PURE__ */ new Map(), billable = false) {
11415
+ const warnings = [];
11416
+ for (const id of lane.memberIds) {
11417
+ const r = reliability.get(id);
11418
+ if (unreliable(r)) {
11419
+ warnings.push({
11420
+ code: "unreliable_member",
11421
+ member: id,
11422
+ message: `'${id}' was refused by its provider on ${Math.round(r.failure_share * 100)}% of ${r.requests} requests in the last ${r.window_days} days (${r.rate_limited} rate-limited, ${r.upstream_errors} errored, ${r.refused} refused a lane's request); on this lane it will be tried after every member that was not, and a pinned request to it will fail that often.`
11423
+ });
11424
+ }
11425
+ }
11426
+ const present2 = lane.memberIds.map((id) => members.get(id)).filter((m) => m !== void 0);
11427
+ const serving = present2.filter(
11428
+ (m) => routable.has(m.id) && unmetRequirements(m, lane).length === 0 && !excludedByNamespace(m, lane)
11429
+ );
11430
+ const hosts = new Set(serving.map((m) => m.upstreamId));
11431
+ if (hosts.size === 1 && serving.length > 1) {
11432
+ warnings.push({
11433
+ code: "one_upstream",
11434
+ message: `Every member this lane can allocate to is on '${[...hosts][0]}'. A provider that rate-limits per organisation, or whose credential expires, refuses all of them at once \u2014 so the fallback chain has one point of failure whatever its depth. A member on another host is what makes falling over mean anything.`
11435
+ });
11436
+ }
11437
+ for (const id of lane.memberIds) {
11438
+ const member = members.get(id);
11439
+ if (member !== void 0 && routable.has(id)) {
11440
+ const unmet = unmetRequirements(member, lane);
11441
+ if (unmet.length > 0) {
11442
+ warnings.push({
11443
+ code: "unroutable_member",
11444
+ member: id,
11445
+ message: `'${id}' fails the lane's requirement${unmet.length > 1 ? "s" : ""} ${unmet.map((u) => `'${u}'`).join(", ")} and will not serve on it.`
11446
+ });
11447
+ } else if (excludedByNamespace(member, lane)) {
11448
+ warnings.push({
11449
+ code: "unroutable_member",
11450
+ member: id,
11451
+ message: `'${id}' no longer trains on the traffic it serves and will not serve on this contributor lane.`
11452
+ });
11453
+ }
11454
+ continue;
11455
+ }
11456
+ if (routable.has(id)) continue;
11457
+ const block = member === void 0 ? null : billingBlockOf(member, prices.has(id));
11458
+ const why = member === void 0 ? "is not in the routing table" : !member.enabled ? "is disabled" : member.measuredAt === null ? "has not been measured; it will not serve until the next conformance run" : verificationOf(member, /* @__PURE__ */ new Date()) === "stale" ? "has a stale measurement; it will not serve until measured again" : billable && block === "unpriced" ? "has no price in force; this tenant is billed, so it will not serve until one is" : billable && block === "usage_unreported" ? "does not report token usage; this tenant is billed, so it cannot serve" : "is not routable";
11459
+ warnings.push({ code: "unroutable_member", member: id, message: `'${id}' ${why}.` });
11460
+ }
11461
+ const priced = present2.map((m) => ({ id: m.id, rate: prices.get(m.id) })).filter((p) => p.rate !== void 0).map((p) => ({ id: p.id, worst: worstCaseRate(p.rate) }));
11462
+ if (priced.length > 1) {
11463
+ const cheapest = priced.reduce((a, b) => b.worst < a.worst ? b : a);
11464
+ if (cheapest.worst > 0) {
11465
+ for (const p of priced) {
11466
+ const factor = p.worst / cheapest.worst;
11467
+ if (factor >= DEAR_FACTOR) {
11468
+ warnings.push({
11469
+ code: "dear_member",
11470
+ member: p.id,
11471
+ message: `'${p.id}' is ${Math.round(factor)}\xD7 '${cheapest.id}' at worst case (${perMillion(p.worst)} against ${perMillion(cheapest.worst)}, input and output); ` + (lane.selection === "cheap" ? `it will serve only when every cheaper member is rejected by a gate.` : `under '${lane.selection}' selection it serves its share of requests, not only when every cheaper member is rejected.`)
11472
+ });
11473
+ }
11474
+ }
11475
+ }
11476
+ }
11477
+ const windows = present2.filter((m) => m.maxContext !== null).map((m) => ({ id: m.id, window: m.maxContext }));
11478
+ if (windows.length > 1) {
11479
+ const largest = Math.max(...windows.map((w) => w.window));
11480
+ const smallest = Math.min(...windows.map((w) => w.window));
11481
+ if (smallest < largest) {
11482
+ for (const w of windows.filter((w2) => w2.window === smallest)) {
11483
+ warnings.push({
11484
+ code: "narrow_member",
11485
+ member: w.id,
11486
+ message: `Including '${w.id}' caps the lane's context window at ${w.window.toLocaleString("en-US")} tokens; the largest member takes ${largest.toLocaleString("en-US")}.`
11487
+ });
11488
+ }
11489
+ }
11490
+ }
11491
+ const outputs = present2.filter((m) => m.maxOutput !== null).map((m) => ({ id: m.id, cap: m.maxOutput }));
11492
+ if (outputs.length > 1) {
11493
+ const largest = Math.max(...outputs.map((o) => o.cap));
11494
+ const smallest = Math.min(...outputs.map((o) => o.cap));
11495
+ if (smallest < largest) {
11496
+ for (const o of outputs.filter((o2) => o2.cap === smallest)) {
11497
+ warnings.push({
11498
+ code: "narrow_member",
11499
+ member: o.id,
11500
+ message: `Including '${o.id}' caps the lane's output at ${o.cap.toLocaleString("en-US")} tokens; the largest member allows ${largest.toLocaleString("en-US")}.`
11501
+ });
11502
+ }
11503
+ }
11504
+ }
11505
+ const implied = Object.hasOwn(JOB_IMPLIES, lane.job) ? JOB_IMPLIES[lane.job] : [];
11506
+ const routableMembers = present2.filter(
11507
+ (m) => routable.has(m.id) && unmetRequirements(m, lane).length === 0 && !excludedByNamespace(m, lane)
11508
+ );
11509
+ for (const capability of implied) {
11510
+ const cannot = routableMembers.filter((m) => {
11511
+ const flag2 = { tools: m.tools, vision: m.vision, json_schema: m.jsonSchema, web_search: m.webSearch }[capability];
11512
+ return flag2 === false;
11513
+ });
11514
+ if (cannot.length > 0) {
11515
+ const all = cannot.length === routableMembers.length;
11516
+ warnings.push({
11517
+ code: "job_capability",
11518
+ message: `A '${lane.job}' lane implies ${capability}, and ` + (all ? `none of its routable members supports it: ${cannot.map((m) => `'${m.id}'`).join(", ")}.` : `${cannot.map((m) => `'${m.id}'`).join(", ")} cannot; a request needing it will never be allocated there.`)
11519
+ });
11520
+ }
11521
+ }
11522
+ if (lane.selection === "graduated" && lane.weights.some((weight) => weight !== DEFAULT_WEIGHT)) {
11523
+ warnings.push({
11524
+ code: "weights_ignored",
11525
+ message: `This lane is 'graduated', which works each member's share out from its quality_rank (or allocator position when unranked), so the weights it stores are not read. They are kept, so switching back to 'weighted' restores them.`
11526
+ });
11527
+ }
11528
+ return warnings;
11529
+ }
11530
+ __name(laneWarnings, "laneWarnings");
11531
+
11532
+ // src/lanes-describe.ts
11533
+ async function describeLane(db, lane, billable, now) {
11534
+ const routable = await listRoutableModels(db, now);
11535
+ const prices = await pricesInForce(
11536
+ db,
11537
+ lane.memberIds,
11538
+ tokenlessOf(routable.filter((m) => lane.memberIds.includes(m.id)))
11539
+ );
11540
+ const listed = new Map(
11541
+ routable.filter((m) => !billable || billingBlockOf(m, prices.has(m.id)) === null).map((m) => [m.id, m])
11542
+ );
11543
+ const summary = summariseLane(lane, listed, prices);
11544
+ const members = /* @__PURE__ */ new Map();
11545
+ for (const id of lane.memberIds) {
11546
+ const member = listed.get(id) ?? await lookupModel(db, id);
11547
+ if (member !== null && member !== void 0) members.set(id, member);
11548
+ }
11549
+ return {
11550
+ id: lane.id,
11551
+ tenant: lane.tenantId,
11552
+ global: lane.tenantId === null,
11553
+ job: lane.job,
11554
+ description: lane.description,
11555
+ enabled: lane.enabled,
11556
+ archived_at: lane.archivedAt,
11557
+ members: lane.memberIds,
11558
+ weights: lane.weights,
11559
+ quality_ranks: lane.qualityRanks,
11560
+ selection: lane.selection,
11561
+ cache_ttl_seconds: lane.cacheTtlSeconds,
11562
+ cache_scope: lane.cacheScope,
11563
+ compress: lane.compress,
11564
+ max_chain: lane.maxChain,
11565
+ // What the lane's depth resolves to, so a reader never has to know the
11566
+ // platform constant to render "Platform default (3)" — the same courtesy
11567
+ // `selection_in_force` pays on `GET /admin/settings` (#288). Null above
11568
+ // is "nothing chosen"; this is what nothing-chosen means today, and it
11569
+ // moves when `MAX_CHAIN` does without anybody editing a lane.
11570
+ max_chain_in_force: lane.maxChain ?? MAX_CHAIN,
11571
+ router: lane.router,
11572
+ router_input: lane.routerInput,
11573
+ requires: lane.requires,
11574
+ created_by: lane.createdBy,
11575
+ created_at: lane.createdAt,
11576
+ updated_at: lane.updatedAt,
11577
+ // What the lane will actually do, said here rather than on the invoice
11578
+ // (#70). Never a refusal; computed from the same inputs as `catalog`.
11579
+ warnings: laneWarnings(lane, members, new Set(listed.keys()), prices, await reliabilityOf(db, lane.memberIds, now), billable),
11580
+ // Null when no member is routable: the lane exists and will list nothing
11581
+ // until conformance measures one of them.
11582
+ catalog: summary === null ? null : {
11583
+ routable_members: summary.members,
11584
+ modality: summary.modality,
11585
+ tools: summary.tools,
11586
+ parallel_tool_calls: summary.parallelToolCalls,
11587
+ tool_choice_forced: summary.toolChoiceForced,
11588
+ web_search: summary.webSearch,
11589
+ streaming: summary.streaming,
11590
+ json_schema: summary.jsonSchema,
11591
+ vision: summary.vision,
11592
+ // Omitted here while `/v1/models` reported it and the schema
11593
+ // declared it, so a client typing `Lane.catalog` got a field that
11594
+ // was permanently undefined on the control plane and present on the
11595
+ // data plane. The two describe the same lane and must not disagree
11596
+ // about which fields exist (#85).
11597
+ usage_reported: summary.usageReported,
11598
+ max_context: summary.maxContext,
11599
+ max_output: summary.maxOutput,
11600
+ output_limit: summary.outputLimit,
11601
+ any_member: anyMemberJson(summary.anyMember),
11602
+ data_retention: summary.dataRetention,
11603
+ pricing: summary.pricing
11604
+ }
11605
+ };
11606
+ }
11607
+ __name(describeLane, "describeLane");
11608
+ async function describeWritten(db, lane, tenantId, billable, now) {
11609
+ const described = await describeLane(db, lane, billable, now);
11610
+ if (lane.tenantId === null) return described;
11611
+ const warning = quotaWarning(await tierOf(db, tenantId), await lanesUsed(db, tenantId));
11612
+ return warning === null ? described : { ...described, warnings: [...described.warnings, warning] };
11613
+ }
11614
+ __name(describeWritten, "describeWritten");
11615
+
11390
11616
  // src/lanes-validate.ts
11391
11617
  var LaneWriteError = class extends Error {
11618
+ static {
11619
+ __name(this, "LaneWriteError");
11620
+ }
11621
+ status;
11622
+ code;
11392
11623
  constructor(status, message, code = null) {
11393
11624
  super(message);
11394
11625
  this.status = status;
11395
11626
  this.code = code;
11396
11627
  }
11397
- status;
11398
- code;
11399
- static {
11400
- __name(this, "LaneWriteError");
11401
- }
11402
11628
  };
11403
11629
  var JOBS = [
11404
11630
  "chat-assistant",
@@ -11621,14 +11847,16 @@ __name(validQualityRanks, "validQualityRanks");
11621
11847
 
11622
11848
  // src/tenant-settings.ts
11623
11849
  var SettingsError = class extends Error {
11850
+ static {
11851
+ __name(this, "SettingsError");
11852
+ }
11853
+ // Assigned, not a parameter property: `lane:create` reaches this file
11854
+ // under plain `node`, which refuses that syntax (see LaneWriteError).
11855
+ status;
11624
11856
  constructor(status, message) {
11625
11857
  super(message);
11626
11858
  this.status = status;
11627
11859
  }
11628
- status;
11629
- static {
11630
- __name(this, "SettingsError");
11631
- }
11632
11860
  };
11633
11861
  function selectionInForce(settings2) {
11634
11862
  return settings2.defaultSelection ?? DEFAULT_SELECTION;
@@ -11823,263 +12051,46 @@ async function updateLane(db, request) {
11823
12051
  updated_at = datetime('now')
11824
12052
  WHERE id = ?4`
11825
12053
  ).bind(job2, description, enabled ? 1 : 0, id, archived ? 1 : 0, selection, cacheTtlSeconds, cacheScope, maxChain, router, routerInput, compress ? 1 : 0)
11826
- ];
11827
- if (request.members !== void 0 || request.weights !== void 0 || request.qualityRanks !== void 0) {
11828
- statements.push(db.prepare(`DELETE FROM lane_members WHERE lane_id = ?`).bind(id), ...memberInserts(db, id, members, weights, qualityRanks));
11829
- }
11830
- if (requires !== null) {
11831
- statements.push(db.prepare(`DELETE FROM lane_requires WHERE lane_id = ?`).bind(id), ...requireInserts(db, id, requires));
11832
- }
11833
- const action = archived !== wasArchived ? archived ? "lane.archive" : "lane.unarchive" : enabled === before.enabled ? "lane.update" : enabled ? "lane.enable" : "lane.disable";
11834
- statements.push(
11835
- await audit(db, request.actor, action, id, {
11836
- before: { job: before.job, description: before.description, members: before.memberIds, weights: before.weights, qualityRanks: before.qualityRanks, selection: before.selection, requires: before.requires, enabled: before.enabled, archived: wasArchived, cacheTtlSeconds: before.cacheTtlSeconds, cacheScope: before.cacheScope, compress: before.compress, maxChain: before.maxChain, router: before.router, routerInput: before.routerInput },
11837
- after: { job: job2, description, members, weights, qualityRanks, selection, requires: request.requires ?? before.requires, enabled, archived, cacheTtlSeconds, cacheScope, compress, maxChain, router, routerInput }
11838
- }, false, global2 ? request.tenantId : null)
11839
- );
11840
- await db.batch(statements);
11841
- return await lookupLane(db, id, request.tenantId);
11842
- }
11843
- __name(updateLane, "updateLane");
11844
- function globalEditProblem(request, before) {
11845
- if (request.job !== void 0 && request.job !== before.job) {
11846
- throw new LaneWriteError(400, `'${before.id}' is a global lane, and its id is its job. A global lane for another job is a migration.`);
11847
- }
11848
- if (request.archived !== void 0) {
11849
- throw new LaneWriteError(400, `'${before.id}' is a global lane and cannot be archived. Send 'enabled: false' to take it out of service.`);
11850
- }
11851
- if (request.compress !== void 0 && validCompress(request.compress)) {
11852
- throw new LaneWriteError(
11853
- 400,
11854
- `'${before.id}' is a global lane and serves every tenant, so it cannot compress their requests. Switch compression on for a project, or on a lane of your own.`,
11855
- "platform_lane_compress"
11856
- );
11857
- }
11858
- }
11859
- __name(globalEditProblem, "globalEditProblem");
11860
- async function disableLane(db, request) {
11861
- return updateLane(db, { ...request, enabled: false });
11862
- }
11863
- __name(disableLane, "disableLane");
11864
-
11865
- // src/lanes-warnings.ts
11866
- var DEAR_FACTOR = 10;
11867
- var JOB_IMPLIES = {
11868
- "code-review": ["tools"],
11869
- "agentic-coding": ["tools"],
11870
- hunter: ["tools"],
11871
- builder: ["tools"],
11872
- "computer-use": ["tools", "vision"],
11873
- "document-understanding": ["vision"],
11874
- extraction: ["json_schema"],
11875
- "rag-grounded-answers": ["json_schema"],
11876
- "web-search": ["web_search"]
11877
- };
11878
- function worstCaseRate(price) {
11879
- let input = price.input_micros_per_mtok;
11880
- let output = price.output_micros_per_mtok;
11881
- for (const v of price.variants) {
11882
- input = Math.max(input, v.input_micros_per_mtok);
11883
- output = Math.max(output, v.output_micros_per_mtok);
11884
- }
11885
- return input + output;
11886
- }
11887
- __name(worstCaseRate, "worstCaseRate");
11888
- var perMillion = /* @__PURE__ */ __name((micros) => `$${(micros / 1e6).toFixed(2)}/M`, "perMillion");
11889
- function laneWarnings(lane, members, routable, prices, reliability = /* @__PURE__ */ new Map(), billable = false) {
11890
- const warnings = [];
11891
- for (const id of lane.memberIds) {
11892
- const r = reliability.get(id);
11893
- if (unreliable(r)) {
11894
- warnings.push({
11895
- code: "unreliable_member",
11896
- member: id,
11897
- message: `'${id}' was refused by its provider on ${Math.round(r.failure_share * 100)}% of ${r.requests} requests in the last ${r.window_days} days (${r.rate_limited} rate-limited, ${r.upstream_errors} errored, ${r.refused} refused a lane's request); on this lane it will be tried after every member that was not, and a pinned request to it will fail that often.`
11898
- });
11899
- }
11900
- }
11901
- const present2 = lane.memberIds.map((id) => members.get(id)).filter((m) => m !== void 0);
11902
- const serving = present2.filter(
11903
- (m) => routable.has(m.id) && unmetRequirements(m, lane).length === 0 && !excludedByNamespace(m, lane)
11904
- );
11905
- const hosts = new Set(serving.map((m) => m.upstreamId));
11906
- if (hosts.size === 1 && serving.length > 1) {
11907
- warnings.push({
11908
- code: "one_upstream",
11909
- message: `Every member this lane can allocate to is on '${[...hosts][0]}'. A provider that rate-limits per organisation, or whose credential expires, refuses all of them at once \u2014 so the fallback chain has one point of failure whatever its depth. A member on another host is what makes falling over mean anything.`
11910
- });
11911
- }
11912
- for (const id of lane.memberIds) {
11913
- const member = members.get(id);
11914
- if (member !== void 0 && routable.has(id)) {
11915
- const unmet = unmetRequirements(member, lane);
11916
- if (unmet.length > 0) {
11917
- warnings.push({
11918
- code: "unroutable_member",
11919
- member: id,
11920
- message: `'${id}' fails the lane's requirement${unmet.length > 1 ? "s" : ""} ${unmet.map((u) => `'${u}'`).join(", ")} and will not serve on it.`
11921
- });
11922
- } else if (excludedByNamespace(member, lane)) {
11923
- warnings.push({
11924
- code: "unroutable_member",
11925
- member: id,
11926
- message: `'${id}' no longer trains on the traffic it serves and will not serve on this contributor lane.`
11927
- });
11928
- }
11929
- continue;
11930
- }
11931
- if (routable.has(id)) continue;
11932
- const block = member === void 0 ? null : billingBlockOf(member, prices.has(id));
11933
- const why = member === void 0 ? "is not in the routing table" : !member.enabled ? "is disabled" : member.measuredAt === null ? "has not been measured; it will not serve until the next conformance run" : verificationOf(member, /* @__PURE__ */ new Date()) === "stale" ? "has a stale measurement; it will not serve until measured again" : billable && block === "unpriced" ? "has no price in force; this tenant is billed, so it will not serve until one is" : billable && block === "usage_unreported" ? "does not report token usage; this tenant is billed, so it cannot serve" : "is not routable";
11934
- warnings.push({ code: "unroutable_member", member: id, message: `'${id}' ${why}.` });
11935
- }
11936
- const priced = present2.map((m) => ({ id: m.id, rate: prices.get(m.id) })).filter((p) => p.rate !== void 0).map((p) => ({ id: p.id, worst: worstCaseRate(p.rate) }));
11937
- if (priced.length > 1) {
11938
- const cheapest = priced.reduce((a, b) => b.worst < a.worst ? b : a);
11939
- if (cheapest.worst > 0) {
11940
- for (const p of priced) {
11941
- const factor = p.worst / cheapest.worst;
11942
- if (factor >= DEAR_FACTOR) {
11943
- warnings.push({
11944
- code: "dear_member",
11945
- member: p.id,
11946
- message: `'${p.id}' is ${Math.round(factor)}\xD7 '${cheapest.id}' at worst case (${perMillion(p.worst)} against ${perMillion(cheapest.worst)}, input and output); ` + (lane.selection === "cheap" ? `it will serve only when every cheaper member is rejected by a gate.` : `under '${lane.selection}' selection it serves its share of requests, not only when every cheaper member is rejected.`)
11947
- });
11948
- }
11949
- }
11950
- }
11951
- }
11952
- const windows = present2.filter((m) => m.maxContext !== null).map((m) => ({ id: m.id, window: m.maxContext }));
11953
- if (windows.length > 1) {
11954
- const largest = Math.max(...windows.map((w) => w.window));
11955
- const smallest = Math.min(...windows.map((w) => w.window));
11956
- if (smallest < largest) {
11957
- for (const w of windows.filter((w2) => w2.window === smallest)) {
11958
- warnings.push({
11959
- code: "narrow_member",
11960
- member: w.id,
11961
- message: `Including '${w.id}' caps the lane's context window at ${w.window.toLocaleString("en-US")} tokens; the largest member takes ${largest.toLocaleString("en-US")}.`
11962
- });
11963
- }
11964
- }
11965
- }
11966
- const outputs = present2.filter((m) => m.maxOutput !== null).map((m) => ({ id: m.id, cap: m.maxOutput }));
11967
- if (outputs.length > 1) {
11968
- const largest = Math.max(...outputs.map((o) => o.cap));
11969
- const smallest = Math.min(...outputs.map((o) => o.cap));
11970
- if (smallest < largest) {
11971
- for (const o of outputs.filter((o2) => o2.cap === smallest)) {
11972
- warnings.push({
11973
- code: "narrow_member",
11974
- member: o.id,
11975
- message: `Including '${o.id}' caps the lane's output at ${o.cap.toLocaleString("en-US")} tokens; the largest member allows ${largest.toLocaleString("en-US")}.`
11976
- });
11977
- }
11978
- }
12054
+ ];
12055
+ if (request.members !== void 0 || request.weights !== void 0 || request.qualityRanks !== void 0) {
12056
+ statements.push(db.prepare(`DELETE FROM lane_members WHERE lane_id = ?`).bind(id), ...memberInserts(db, id, members, weights, qualityRanks));
11979
12057
  }
11980
- const implied = Object.hasOwn(JOB_IMPLIES, lane.job) ? JOB_IMPLIES[lane.job] : [];
11981
- const routableMembers = present2.filter(
11982
- (m) => routable.has(m.id) && unmetRequirements(m, lane).length === 0 && !excludedByNamespace(m, lane)
12058
+ if (requires !== null) {
12059
+ statements.push(db.prepare(`DELETE FROM lane_requires WHERE lane_id = ?`).bind(id), ...requireInserts(db, id, requires));
12060
+ }
12061
+ const action = archived !== wasArchived ? archived ? "lane.archive" : "lane.unarchive" : enabled === before.enabled ? "lane.update" : enabled ? "lane.enable" : "lane.disable";
12062
+ statements.push(
12063
+ await audit(db, request.actor, action, id, {
12064
+ before: { job: before.job, description: before.description, members: before.memberIds, weights: before.weights, qualityRanks: before.qualityRanks, selection: before.selection, requires: before.requires, enabled: before.enabled, archived: wasArchived, cacheTtlSeconds: before.cacheTtlSeconds, cacheScope: before.cacheScope, compress: before.compress, maxChain: before.maxChain, router: before.router, routerInput: before.routerInput },
12065
+ after: { job: job2, description, members, weights, qualityRanks, selection, requires: request.requires ?? before.requires, enabled, archived, cacheTtlSeconds, cacheScope, compress, maxChain, router, routerInput }
12066
+ }, false, global2 ? request.tenantId : null)
11983
12067
  );
11984
- for (const capability of implied) {
11985
- const cannot = routableMembers.filter((m) => {
11986
- const flag2 = { tools: m.tools, vision: m.vision, json_schema: m.jsonSchema, web_search: m.webSearch }[capability];
11987
- return flag2 === false;
11988
- });
11989
- if (cannot.length > 0) {
11990
- const all = cannot.length === routableMembers.length;
11991
- warnings.push({
11992
- code: "job_capability",
11993
- message: `A '${lane.job}' lane implies ${capability}, and ` + (all ? `none of its routable members supports it: ${cannot.map((m) => `'${m.id}'`).join(", ")}.` : `${cannot.map((m) => `'${m.id}'`).join(", ")} cannot; a request needing it will never be allocated there.`)
11994
- });
11995
- }
12068
+ await db.batch(statements);
12069
+ return await lookupLane(db, id, request.tenantId);
12070
+ }
12071
+ __name(updateLane, "updateLane");
12072
+ function globalEditProblem(request, before) {
12073
+ if (request.job !== void 0 && request.job !== before.job) {
12074
+ throw new LaneWriteError(400, `'${before.id}' is a global lane, and its id is its job. A global lane for another job is a migration.`);
11996
12075
  }
11997
- if (lane.selection === "graduated" && lane.weights.some((weight) => weight !== DEFAULT_WEIGHT)) {
11998
- warnings.push({
11999
- code: "weights_ignored",
12000
- message: `This lane is 'graduated', which works each member's share out from its quality_rank (or allocator position when unranked), so the weights it stores are not read. They are kept, so switching back to 'weighted' restores them.`
12001
- });
12076
+ if (request.archived !== void 0) {
12077
+ throw new LaneWriteError(400, `'${before.id}' is a global lane and cannot be archived. Send 'enabled: false' to take it out of service.`);
12078
+ }
12079
+ if (request.compress !== void 0 && validCompress(request.compress)) {
12080
+ throw new LaneWriteError(
12081
+ 400,
12082
+ `'${before.id}' is a global lane and serves every tenant, so it cannot compress their requests. Switch compression on for a project, or on a lane of your own.`,
12083
+ "platform_lane_compress"
12084
+ );
12002
12085
  }
12003
- return warnings;
12004
12086
  }
12005
- __name(laneWarnings, "laneWarnings");
12087
+ __name(globalEditProblem, "globalEditProblem");
12088
+ async function disableLane(db, request) {
12089
+ return updateLane(db, { ...request, enabled: false });
12090
+ }
12091
+ __name(disableLane, "disableLane");
12006
12092
 
12007
12093
  // src/admin-lanes.ts
12008
- async function describe(env, lane, caller, now) {
12009
- const routable = await listRoutableModels(env.DB, now);
12010
- const prices = await pricesInForce(
12011
- env.DB,
12012
- lane.memberIds,
12013
- tokenlessOf(routable.filter((m) => lane.memberIds.includes(m.id)))
12014
- );
12015
- const listed = new Map(
12016
- routable.filter((m) => !caller.billable || billingBlockOf(m, prices.has(m.id)) === null).map((m) => [m.id, m])
12017
- );
12018
- const summary = summariseLane(lane, listed, prices);
12019
- const members = /* @__PURE__ */ new Map();
12020
- for (const id of lane.memberIds) {
12021
- const member = listed.get(id) ?? await lookupModel(env.DB, id);
12022
- if (member !== null && member !== void 0) members.set(id, member);
12023
- }
12024
- return {
12025
- id: lane.id,
12026
- tenant: lane.tenantId,
12027
- global: lane.tenantId === null,
12028
- job: lane.job,
12029
- description: lane.description,
12030
- enabled: lane.enabled,
12031
- archived_at: lane.archivedAt,
12032
- members: lane.memberIds,
12033
- weights: lane.weights,
12034
- quality_ranks: lane.qualityRanks,
12035
- selection: lane.selection,
12036
- cache_ttl_seconds: lane.cacheTtlSeconds,
12037
- cache_scope: lane.cacheScope,
12038
- compress: lane.compress,
12039
- max_chain: lane.maxChain,
12040
- // What the lane's depth resolves to, so a reader never has to know the
12041
- // platform constant to render "Platform default (3)" — the same courtesy
12042
- // `selection_in_force` pays on `GET /admin/settings` (#288). Null above
12043
- // is "nothing chosen"; this is what nothing-chosen means today, and it
12044
- // moves when `MAX_CHAIN` does without anybody editing a lane.
12045
- max_chain_in_force: lane.maxChain ?? MAX_CHAIN,
12046
- router: lane.router,
12047
- router_input: lane.routerInput,
12048
- requires: lane.requires,
12049
- created_by: lane.createdBy,
12050
- created_at: lane.createdAt,
12051
- updated_at: lane.updatedAt,
12052
- // What the lane will actually do, said here rather than on the invoice
12053
- // (#70). Never a refusal; computed from the same inputs as `catalog`.
12054
- warnings: laneWarnings(lane, members, new Set(listed.keys()), prices, await reliabilityOf(env.DB, lane.memberIds, now), caller.billable),
12055
- // Null when no member is routable: the lane exists and will list nothing
12056
- // until conformance measures one of them.
12057
- catalog: summary === null ? null : {
12058
- routable_members: summary.members,
12059
- modality: summary.modality,
12060
- tools: summary.tools,
12061
- parallel_tool_calls: summary.parallelToolCalls,
12062
- tool_choice_forced: summary.toolChoiceForced,
12063
- web_search: summary.webSearch,
12064
- streaming: summary.streaming,
12065
- json_schema: summary.jsonSchema,
12066
- vision: summary.vision,
12067
- // Omitted here while `/v1/models` reported it and the schema
12068
- // declared it, so a client typing `Lane.catalog` got a field that
12069
- // was permanently undefined on the control plane and present on the
12070
- // data plane. The two describe the same lane and must not disagree
12071
- // about which fields exist (#85).
12072
- usage_reported: summary.usageReported,
12073
- max_context: summary.maxContext,
12074
- max_output: summary.maxOutput,
12075
- output_limit: summary.outputLimit,
12076
- any_member: anyMemberJson(summary.anyMember),
12077
- data_retention: summary.dataRetention,
12078
- pricing: summary.pricing
12079
- }
12080
- };
12081
- }
12082
- __name(describe, "describe");
12083
12094
  function refused2(error2, cors) {
12084
12095
  if (error2 instanceof LaneWriteError) {
12085
12096
  const type = error2.status === 403 ? "permission_error" : "invalid_request_error";
@@ -12091,20 +12102,13 @@ function refused2(error2, cors) {
12091
12102
  return null;
12092
12103
  }
12093
12104
  __name(refused2, "refused");
12094
- async function written(env, lane, caller, now) {
12095
- const described = await describe(env, lane, caller, now);
12096
- if (lane.tenantId === null) return described;
12097
- const warning = quotaWarning(await tierOf(env.DB, caller.tenantId), await lanesUsed(env.DB, caller.tenantId));
12098
- return warning === null ? described : { ...described, warnings: [...described.warnings, warning] };
12099
- }
12100
- __name(written, "written");
12101
12105
  var laneRoutes = /* @__PURE__ */ __name(async ({ request, env, url, path, caller, cors, now, mustWrite }) => {
12102
12106
  if (path === "/lanes" && request.method === "GET") {
12103
12107
  const lanes = await listLanes(env.DB, caller.tenantId, {
12104
12108
  includeDisabled: true,
12105
12109
  includeArchived: url.searchParams.get("archived") !== null
12106
12110
  });
12107
- return json({ lanes: await Promise.all(lanes.map((lane) => describe(env, lane, caller, now))) }, cors);
12111
+ return json({ lanes: await Promise.all(lanes.map((lane) => describeLane(env.DB, lane, caller.billable, now))) }, cors);
12108
12112
  }
12109
12113
  if (path === "/lanes" && request.method === "POST") {
12110
12114
  const refusal = mustWrite();
@@ -12137,7 +12141,7 @@ var laneRoutes = /* @__PURE__ */ __name(async ({ request, env, url, path, caller
12137
12141
  // Passed as sent, not coerced: `validCompress` refuses anything but a boolean.
12138
12142
  ...body.compress !== void 0 ? { compress: body.compress } : {}
12139
12143
  });
12140
- return json(await written(env, lane, caller, now), cors, 201);
12144
+ return json(await describeWritten(env.DB, lane, caller.tenantId, caller.billable, now), cors, 201);
12141
12145
  } catch (error2) {
12142
12146
  return refused2(error2, cors) ?? Promise.reject(error2);
12143
12147
  }
@@ -12191,7 +12195,7 @@ var laneRoutes = /* @__PURE__ */ __name(async ({ request, env, url, path, caller
12191
12195
  if (request.method === "GET") {
12192
12196
  const lane = await lookupLane(env.DB, id, caller.tenantId);
12193
12197
  if (lane === null) return errorResponse(404, "invalid_request_error", "No such lane.", { headers: cors });
12194
- return json(await describe(env, lane, caller, now), cors);
12198
+ return json(await describeLane(env.DB, lane, caller.billable, now), cors);
12195
12199
  }
12196
12200
  if (request.method === "PUT" || request.method === "DELETE") {
12197
12201
  const refusal = mustWrite();
@@ -12200,7 +12204,7 @@ var laneRoutes = /* @__PURE__ */ __name(async ({ request, env, url, path, caller
12200
12204
  const actor = caller.identity.email ?? caller.identity.uid;
12201
12205
  try {
12202
12206
  if (request.method === "DELETE") {
12203
- return json(await written(env, await disableLane(env.DB, { tenantId: caller.tenantId, actor, id, global: global2 }), caller, now), cors);
12207
+ return json(await describeWritten(env.DB, await disableLane(env.DB, { tenantId: caller.tenantId, actor, id, global: global2 }), caller.tenantId, caller.billable, now), cors);
12204
12208
  }
12205
12209
  const body = await request.json().catch(() => null);
12206
12210
  if (body === null) {
@@ -12232,7 +12236,7 @@ var laneRoutes = /* @__PURE__ */ __name(async ({ request, env, url, path, caller
12232
12236
  ...body.enabled !== void 0 ? { enabled: body.enabled === true } : {},
12233
12237
  ...body.archived !== void 0 ? { archived: body.archived === true } : {}
12234
12238
  });
12235
- return json(await written(env, lane, caller, now), cors);
12239
+ return json(await describeWritten(env.DB, lane, caller.tenantId, caller.billable, now), cors);
12236
12240
  } catch (error2) {
12237
12241
  return refused2(error2, cors) ?? Promise.reject(error2);
12238
12242
  }
@@ -12362,14 +12366,14 @@ var ledgerRoutes = /* @__PURE__ */ __name(async ({ request, env, path, url, call
12362
12366
 
12363
12367
  // src/project-sentry.ts
12364
12368
  var SentryDsnError = class extends Error {
12369
+ static {
12370
+ __name(this, "SentryDsnError");
12371
+ }
12372
+ status;
12365
12373
  constructor(status, message) {
12366
12374
  super(message);
12367
12375
  this.status = status;
12368
12376
  }
12369
- status;
12370
- static {
12371
- __name(this, "SentryDsnError");
12372
- }
12373
12377
  };
12374
12378
  var SHAPE = "a Sentry DSN: https://<public key>@<host>/<project id>, as Sentry \u2192 Project Settings \u2192 Client Keys shows it";
12375
12379
  function parseDsn(value) {
@@ -14199,16 +14203,17 @@ __name(paymentsEconomics, "paymentsEconomics");
14199
14203
 
14200
14204
  // src/tiers.ts
14201
14205
  var TierRefused = class extends Error {
14206
+ static {
14207
+ __name(this, "TierRefused");
14208
+ }
14209
+ code;
14210
+ /** Empty except on `tier_quota_exceeded`, where it names every limit that is over. */
14211
+ over;
14202
14212
  constructor(code, message, over = []) {
14203
14213
  super(message);
14214
+ this.name = "TierRefused";
14204
14215
  this.code = code;
14205
14216
  this.over = over;
14206
- this.name = "TierRefused";
14207
- }
14208
- code;
14209
- over;
14210
- static {
14211
- __name(this, "TierRefused");
14212
14217
  }
14213
14218
  };
14214
14219
  async function usageOf2(db, tenantId) {
@@ -14601,14 +14606,14 @@ __name(paymentsTenantsOfUid, "paymentsTenantsOfUid");
14601
14606
  // src/markups.ts
14602
14607
  var MARKUP_CEILING_BASIS_POINTS = 2e3;
14603
14608
  var MarkupRefused = class extends Error {
14609
+ static {
14610
+ __name(this, "MarkupRefused");
14611
+ }
14612
+ code;
14604
14613
  constructor(code, message) {
14605
14614
  super(message);
14606
- this.code = code;
14607
14615
  this.name = "MarkupRefused";
14608
- }
14609
- code;
14610
- static {
14611
- __name(this, "MarkupRefused");
14616
+ this.code = code;
14612
14617
  }
14613
14618
  };
14614
14619
  function earliestEffectiveFrom(now) {
@@ -16646,7 +16651,7 @@ var controlPlanePaths = {
16646
16651
  summary: "Set a model's fallback chain \u2014 owner or admin of the operating tenant",
16647
16652
  description: "**What happens when this model's upstream refuses.** A 429, a 408, a 401, a 402 or a 5xx makes the router try the next candidate in the chain; anything else, and any failure once bytes have started arriving, reaches the caller unchanged. A model with an empty chain has nowhere to go, which is what every row but two was in until #237 \u2014 so a provider throttling us was answered with its own 429 and a customer read it as ours.\n\n**Replaced wholesale, in order.** Send the full list; `[]` clears the chain. At most two fallbacks: candidates are tried **in turn**, each against the full upstream deadline, so a longer chain is a longer wait rather than more redundancy. The same three-candidate bound applies to a lane's chain on every request (#244), so a hand-written chain and a lane are held to one rule. Duplicates, the model itself, an unknown or disabled model, and a model of another modality are all 400 \u2014 the last because the request path rejects a cross-modality candidate on every request, which is redundancy in name only.\n\n**`warnings` is advice, not a refusal.** A chain whose every member is on the primary's own upstream warns: where that host rate-limits per organisation rather than per model, the chain answers the same 429 a deadline later. Clearing a chain warns too, because the state it leaves is the one this route exists to end.\n\nGated like `/admin/upstreams`: a chain is platform configuration and changing it redirects **every** tenant's traffic for that model, so one customer's `owner` is refused with `not_operator`. Which models chain to which is readable by everyone on `GET /admin/models`, since it is made of ids that listing already carries. Every write is an audit row naming the person, the model and the new chain.",
16648
16653
  parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" }, description: "The model id, which contains slashes. Send it URL-encoded (`workers-ai%2F@cf%2F\u2026`) or raw; both work." }],
16649
- requestBody: { required: true, content: { "application/json": { schema: { type: "object", required: ["fallbacks"], properties: { fallbacks: { type: "array", items: { type: "string" }, maxItems: 2, description: "Model ids, in the order they should be tried after the primary." } } }, example: { fallbacks: ["mistral/mistral-large-2512"] } } } },
16654
+ requestBody: { required: true, content: { "application/json": { schema: { type: "object", required: ["fallbacks"], properties: { fallbacks: { type: "array", items: { type: "string" }, maxItems: 2, description: "Model ids, in the order they should be tried after the primary." } } }, example: { fallbacks: ["mistral/mistral-large-4-0"] } } } },
16650
16655
  responses: { 200: { description: "The chain as written, with any warnings.", content: { "application/json": { schema: { $ref: "#/components/schemas/ModelFallbacks" } } } }, ...errorResponses(400, 401, 403, 404) }
16651
16656
  }
16652
16657
  }
@@ -17011,7 +17016,7 @@ var lanePaths = {
17011
17016
  security: bearerFirebase,
17012
17017
  summary: "Create a lane \u2014 admin or owner",
17013
17018
  description: `\`id\` must be \`<your tenant id>/<slug>\`, slug \`[a-z0-9][a-z0-9-]{0,63}\`. A global id (\`bb/\u2026\` or \`oss/\u2026\`) is refused with a 403 whose message says what to do instead \u2014 create your own under your namespace with the same members; offer that as the action. Members must exist and be enabled on an enabled upstream (400 naming the bad ids); duplicates, an empty list, or a lane id as a member are 400. **Unmeasured members are allowed**: conformance admits them later, and the response's \`warnings\` and \`catalog.routable_members\` say what will serve today. A lane whose members are all unmeasured is valid, \`catalog\` is \`null\`, and it lists nothing until a conformance run \u2014 say so rather than hiding the lane. An id that already exists, disabled included, is 409. The tier's quota is the last check: one lane too many is 403 \`lane_quota_exceeded\`, one member too many is 403 \`lane_members_exceeded\`, and a successful create at four in five of the quota carries a \`lane_quota\` warning \u2014 archive a lane to free a slot. Every write is an audit row with the members before and after. Omitting \`selection\` takes the tenant's \`default_selection\` (\`GET /admin/settings\`, where \`selection_in_force\` says what that resolves to today), and omitting \`weights\` gives every member 1 \u2014 send either only to allocate some other way. Omitting \`qualityRanks\` leaves every member unranked, which is what a lane starts as: \`cache_scope: lane\` then serves nothing, because the tier rule refuses an unranked member on either side. **Sending \`selection: cheap\` is not the same as omitting it**: it opts this lane out of the tenant's setting, permanently and by name. Omitting \`maxChain\`, or sending \`null\`, leaves the lane on the platform's fallback-chain bound \u2014 \`max_chain_in_force\` on \`GET /admin/settings\` is that figure; send a number from 1 to it to try fewer candidates, never more. \`cacheTtlSeconds\` defaults to 0, which is this lane's cache off, and \`cacheScope\` to \`model\`. Omitting \`compress\` takes the tenant's \`default_compress\` (\`GET /admin/settings\`), \`false\` unless the tenant has turned it on; \`true\` compresses tool outputs for every request through the lane (\`docs/compression.md\`).`,
17014
- requestBody: { required: true, content: { "application/json": { schema: { type: "object", required: ["id", "job", "description", "members"], properties: { id: { type: "string" }, job: { $ref: "#/components/schemas/Lane/properties/job" }, description: { type: "string", maxLength: 500 }, members: { type: "array", items: { type: "string" }, minItems: 1 }, requires: { $ref: "#/components/schemas/Lane/properties/requires" }, selection: { $ref: "#/components/schemas/Lane/properties/selection" }, weights: { $ref: "#/components/schemas/Lane/properties/weights" }, qualityRanks: { $ref: "#/components/schemas/Lane/properties/quality_ranks" }, cacheTtlSeconds: { $ref: "#/components/schemas/Lane/properties/cache_ttl_seconds" }, cacheScope: { $ref: "#/components/schemas/Lane/properties/cache_scope" }, compress: { $ref: "#/components/schemas/Lane/properties/compress" }, maxChain: { $ref: "#/components/schemas/Lane/properties/max_chain" }, router: { $ref: "#/components/schemas/Lane/properties/router" }, routerInput: { $ref: "#/components/schemas/Lane/properties/router_input" } } }, example: { id: "acme/review", job: "code-review", description: "Reads a diff and reasons about it.", members: ["deepseek/deepseek-v4-pro", "mistral/mistral-large-2512"], requires: ["tools-required", "long-context:200000"], selection: "weighted", weights: [0.9, 0.1] } } } },
17019
+ requestBody: { required: true, content: { "application/json": { schema: { type: "object", required: ["id", "job", "description", "members"], properties: { id: { type: "string" }, job: { $ref: "#/components/schemas/Lane/properties/job" }, description: { type: "string", maxLength: 500 }, members: { type: "array", items: { type: "string" }, minItems: 1 }, requires: { $ref: "#/components/schemas/Lane/properties/requires" }, selection: { $ref: "#/components/schemas/Lane/properties/selection" }, weights: { $ref: "#/components/schemas/Lane/properties/weights" }, qualityRanks: { $ref: "#/components/schemas/Lane/properties/quality_ranks" }, cacheTtlSeconds: { $ref: "#/components/schemas/Lane/properties/cache_ttl_seconds" }, cacheScope: { $ref: "#/components/schemas/Lane/properties/cache_scope" }, compress: { $ref: "#/components/schemas/Lane/properties/compress" }, maxChain: { $ref: "#/components/schemas/Lane/properties/max_chain" }, router: { $ref: "#/components/schemas/Lane/properties/router" }, routerInput: { $ref: "#/components/schemas/Lane/properties/router_input" } } }, example: { id: "acme/review", job: "code-review", description: "Reads a diff and reasons about it.", members: ["deepseek/deepseek-v4-pro", "mistral/mistral-large-4-0"], requires: ["tools-required", "long-context:200000"], selection: "weighted", weights: [0.9, 0.1] } } } },
17015
17020
  responses: { 201: { description: "The lane, with `warnings` and `catalog`. `selection` is resolved here: omit it and the lane takes the tenant's `default_selection` (`GET /admin/settings`), stamped into the row rather than followed.", content: { "application/json": { schema: { $ref: "#/components/schemas/Lane" } } } }, ...errorResponses(400, 401, 403, 409) }
17016
17021
  }
17017
17022
  },
@@ -19220,7 +19225,7 @@ var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
19220
19225
  var GLOBAL_OBJ = globalThis;
19221
19226
 
19222
19227
  // node_modules/@sentry/core/build/esm/utils/version.js
19223
- var SDK_VERSION = "10.75.0";
19228
+ var SDK_VERSION = "10.78.0";
19224
19229
 
19225
19230
  // node_modules/@sentry/core/build/esm/carrier.js
19226
19231
  function getMainCarrier() {
@@ -20492,7 +20497,6 @@ var Scope = class _Scope {
20492
20497
  this._breadcrumbs.push(mergedBreadcrumb);
20493
20498
  if (this._breadcrumbs.length > maxCrumbs) {
20494
20499
  this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);
20495
- this._client?.recordDroppedEvent("buffer_overflow", "log_item");
20496
20500
  }
20497
20501
  this._notifyScopeListeners();
20498
20502
  return this;
@@ -22027,7 +22031,7 @@ var DATA_CATEGORY_OVERRIDES = {
22027
22031
  check_in: "monitor",
22028
22032
  raw_security: "security",
22029
22033
  log: "log_item",
22030
- trace_metric: "metric"
22034
+ metric: "trace_metric"
22031
22035
  };
22032
22036
  function _isOverriddenType(type) {
22033
22037
  return type in DATA_CATEGORY_OVERRIDES;
@@ -22507,17 +22511,28 @@ var SentrySpan = class {
22507
22511
  }
22508
22512
  options.onSpanCaptured?.(this);
22509
22513
  const spans = [];
22514
+ let droppedUnfinishedSpanCount = 0;
22510
22515
  for (const descendant of getSpanDescendants(this)) {
22511
22516
  if (descendant === this || isStandaloneSpan(descendant) || options.isSpanAlreadyCaptured?.(descendant)) {
22512
22517
  continue;
22513
22518
  }
22514
22519
  const spanJSON = spanToJSON(descendant);
22515
22520
  if (!isFullFinishedSpan(spanJSON)) {
22521
+ if (!options.onSpanCaptured) {
22522
+ droppedUnfinishedSpanCount++;
22523
+ }
22516
22524
  continue;
22517
22525
  }
22518
22526
  options.onSpanCaptured?.(descendant);
22519
22527
  spans.push(spanJSON);
22520
22528
  }
22529
+ const client = capturedSpanScope?.getClient() || getClient();
22530
+ if (droppedUnfinishedSpanCount) {
22531
+ client?.recordDroppedEvent("invalid", "span", droppedUnfinishedSpanCount);
22532
+ }
22533
+ if (spans.length > MAX_SPAN_COUNT) {
22534
+ client?.recordDroppedEvent("buffer_overflow", "span", spans.length - MAX_SPAN_COUNT);
22535
+ }
22521
22536
  const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
22522
22537
  delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
22523
22538
  let hasGenAiSpans = false;
@@ -23274,6 +23289,9 @@ var na = "gen_ai.request.temperature";
23274
23289
  var ra = "gen_ai.request.top_k";
23275
23290
  var aa = "gen_ai.request.top_p";
23276
23291
  var ya = "gen_ai.system_instructions";
23292
+ var Aa = "gen_ai.usage.cache_creation.input_tokens";
23293
+ var xa = "gen_ai.usage.cache_read.input_tokens";
23294
+ var Ua = "gen_ai.usage.reasoning.output_tokens";
23277
23295
  var ws = "http.url";
23278
23296
  var Nc = "sentry.sdk.name";
23279
23297
  var Cc = "sentry.sdk.version";
@@ -23580,6 +23598,30 @@ function getFilenameToDebugIdMap(stackParser) {
23580
23598
  }
23581
23599
  __name(getFilenameToDebugIdMap, "getFilenameToDebugIdMap");
23582
23600
 
23601
+ // node_modules/@sentry/core/build/esm/utils/eventUtils.js
23602
+ function isInternalException(hint) {
23603
+ return hint.data?.__sentry__ === true;
23604
+ }
23605
+ __name(isInternalException, "isInternalException");
23606
+ function getPossibleEventMessages(event) {
23607
+ const possibleMessages = [];
23608
+ if (event.message) {
23609
+ possibleMessages.push(event.message);
23610
+ }
23611
+ try {
23612
+ const lastException = event.exception.values[event.exception.values.length - 1];
23613
+ if (lastException?.value) {
23614
+ possibleMessages.push(lastException.value);
23615
+ if (lastException.type) {
23616
+ possibleMessages.push(`${lastException.type}: ${lastException.value}`);
23617
+ }
23618
+ }
23619
+ } catch {
23620
+ }
23621
+ return possibleMessages;
23622
+ }
23623
+ __name(getPossibleEventMessages, "getPossibleEventMessages");
23624
+
23583
23625
  // node_modules/@sentry/core/build/esm/utils/prepareEvent.js
23584
23626
  function prepareEvent(options, event, hint, scope, client, isolationScope) {
23585
23627
  const { normalizeDepth = 3, normalizeMaxBreadth = 1e3 } = options;
@@ -23613,8 +23655,7 @@ function prepareEvent(options, event, hint, scope, client, isolationScope) {
23613
23655
  // Run scope event processors _after_ all other processors
23614
23656
  ...data.eventProcessors
23615
23657
  ];
23616
- const isInternalException = hint.data && hint.data.__sentry__ === true;
23617
- const result2 = isInternalException ? resolvedSyncPromise(prepared) : notifyEventProcessors(eventProcessors, prepared, hint);
23658
+ const result2 = isInternalException(hint) ? resolvedSyncPromise(prepared) : notifyEventProcessors(eventProcessors, prepared, hint);
23618
23659
  return result2.then((evt) => {
23619
23660
  if (evt) {
23620
23661
  applyDebugMeta(evt);
@@ -24352,26 +24393,6 @@ function createClientReportEnvelope(discarded_events, dsn, timestamp) {
24352
24393
  }
24353
24394
  __name(createClientReportEnvelope, "createClientReportEnvelope");
24354
24395
 
24355
- // node_modules/@sentry/core/build/esm/utils/eventUtils.js
24356
- function getPossibleEventMessages(event) {
24357
- const possibleMessages = [];
24358
- if (event.message) {
24359
- possibleMessages.push(event.message);
24360
- }
24361
- try {
24362
- const lastException = event.exception.values[event.exception.values.length - 1];
24363
- if (lastException?.value) {
24364
- possibleMessages.push(lastException.value);
24365
- if (lastException.type) {
24366
- possibleMessages.push(`${lastException.type}: ${lastException.value}`);
24367
- }
24368
- }
24369
- } catch {
24370
- }
24371
- return possibleMessages;
24372
- }
24373
- __name(getPossibleEventMessages, "getPossibleEventMessages");
24374
-
24375
24396
  // node_modules/@sentry/core/build/esm/utils/transactionEvent.js
24376
24397
  function convertTransactionEventToSpanJson(event) {
24377
24398
  const { trace_id, parent_span_id, span_id, status, origin: origin2, data, op } = event.contexts?.trace ?? {};
@@ -24583,6 +24604,12 @@ function _makeDoNotSendEventError(message) {
24583
24604
  };
24584
24605
  }
24585
24606
  __name(_makeDoNotSendEventError, "_makeDoNotSendEventError");
24607
+ function _makeSampledOutError(sampleRate) {
24608
+ return _makeDoNotSendEventError(
24609
+ `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`
24610
+ );
24611
+ }
24612
+ __name(_makeSampledOutError, "_makeSampledOutError");
24586
24613
  function _isInternalError(error2) {
24587
24614
  return isObjectLike(error2) && INTERNAL_ERROR_SYMBOL in error2;
24588
24615
  }
@@ -24874,8 +24901,10 @@ var Client = class {
24874
24901
  this.emit("beforeSendEvent", event, hint);
24875
24902
  const genAiSpanItem = extractGenAiSpansFromEvent(event, this);
24876
24903
  let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);
24877
- for (const attachment of hint.attachments || []) {
24878
- env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment));
24904
+ if (!isInternalException(hint)) {
24905
+ for (const attachment of hint.attachments || []) {
24906
+ env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment));
24907
+ }
24879
24908
  }
24880
24909
  if (genAiSpanItem) {
24881
24910
  env = addItemToEnvelope(env, genAiSpanItem);
@@ -25123,14 +25152,19 @@ var Client = class {
25123
25152
  const eventType = event.type || "error";
25124
25153
  const beforeSendLabel = `before send for type \`${eventType}\``;
25125
25154
  const parsedSampleRate = typeof sampleRate === "undefined" ? void 0 : parseSampleRate(sampleRate);
25155
+ const isSampledOut = isError2 && typeof parsedSampleRate === "number" && safeMathRandom() > parsedSampleRate;
25126
25156
  const dataCategory = getDataCategoryByType(event.type);
25157
+ const session = currentScope.getSession() || isolationScope.getSession();
25158
+ if (isSampledOut && session?.status !== "ok") {
25159
+ this.recordDroppedEvent("sample_rate", "error");
25160
+ return rejectedSyncPromise(_makeSampledOutError(sampleRate));
25161
+ }
25127
25162
  return this._prepareEvent(event, hint, currentScope, isolationScope).then((prepared) => {
25128
25163
  if (prepared === null) {
25129
25164
  this.recordDroppedEvent("event_processor", dataCategory);
25130
25165
  throw _makeDoNotSendEventError("An event processor returned `null`, will not send event.");
25131
25166
  }
25132
- const isInternalException = hint.data?.__sentry__ === true;
25133
- if (isInternalException) {
25167
+ if (isInternalException(hint)) {
25134
25168
  return prepared;
25135
25169
  }
25136
25170
  const result2 = processBeforeSend(this, options, prepared, hint);
@@ -25145,15 +25179,12 @@ var Client = class {
25145
25179
  }
25146
25180
  throw _makeDoNotSendEventError(`${beforeSendLabel} returned \`null\`, will not send event.`);
25147
25181
  }
25148
- const session = currentScope.getSession() || isolationScope.getSession();
25149
25182
  if (isError2 && session) {
25150
25183
  this._updateSessionFromEvent(session, processedEvent);
25151
25184
  }
25152
- if (isError2 && typeof parsedSampleRate === "number" && safeMathRandom() > parsedSampleRate) {
25185
+ if (isSampledOut) {
25153
25186
  this.recordDroppedEvent("sample_rate", "error");
25154
- throw _makeDoNotSendEventError(
25155
- `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`
25156
- );
25187
+ throw _makeSampledOutError(sampleRate);
25157
25188
  }
25158
25189
  if (isTransaction) {
25159
25190
  const spanCountBefore = processedEvent.sdkProcessingMetadata?.spanCountBeforeProcessing || 0;
@@ -25430,36 +25461,30 @@ function isSensitiveKey(lower, denySnippets) {
25430
25461
  return denySnippets.some((snippet) => lower.includes(snippet));
25431
25462
  }
25432
25463
  __name(isSensitiveKey, "isSensitiveKey");
25433
- function filterKeyValueData(data, behavior, additionalDenyTerms) {
25464
+ function shouldFilterDataKey(key, behavior, additionalDenyTerms) {
25434
25465
  if (behavior === false) {
25435
- return {};
25466
+ return true;
25436
25467
  }
25468
+ const lowerKey = key.toLowerCase();
25437
25469
  const denySnippets = additionalDenyTerms != null ? [...SENSITIVE_KEY_SNIPPETS, ...additionalDenyTerms] : SENSITIVE_KEY_SNIPPETS;
25438
- const result2 = {};
25470
+ if (isSensitiveKey(lowerKey, denySnippets)) {
25471
+ return true;
25472
+ }
25439
25473
  if (behavior === true) {
25440
- for (const key of Object.keys(data)) {
25441
- result2[key] = isSensitiveKey(key.toLowerCase(), denySnippets) ? FILTERED_VALUE : data[key];
25442
- }
25443
- return result2;
25474
+ return false;
25444
25475
  }
25445
- if ("deny" in behavior) {
25446
- const lowerTerms2 = behavior.deny.map((t) => t.toLowerCase());
25447
- for (const key of Object.keys(data)) {
25448
- const lower = key.toLowerCase();
25449
- const isDenied = isSensitiveKey(lower, denySnippets) || lowerTerms2.some((term) => lower.includes(term));
25450
- result2[key] = isDenied ? FILTERED_VALUE : data[key];
25451
- }
25452
- return result2;
25476
+ const terms = "deny" in behavior ? behavior.deny : behavior.allow;
25477
+ const matchesConfiguredTerm = terms.some((term) => lowerKey.includes(term.toLowerCase()));
25478
+ return "deny" in behavior ? matchesConfiguredTerm : !matchesConfiguredTerm;
25479
+ }
25480
+ __name(shouldFilterDataKey, "shouldFilterDataKey");
25481
+ function filterKeyValueData(data, behavior, additionalDenyTerms) {
25482
+ if (behavior === false) {
25483
+ return {};
25453
25484
  }
25454
- const lowerTerms = behavior.allow.map((t) => t.toLowerCase());
25485
+ const result2 = {};
25455
25486
  for (const key of Object.keys(data)) {
25456
- const lower = key.toLowerCase();
25457
- if (isSensitiveKey(lower, denySnippets)) {
25458
- result2[key] = FILTERED_VALUE;
25459
- } else {
25460
- const isAllowed = lowerTerms.some((term) => lower.includes(term));
25461
- result2[key] = isAllowed ? data[key] : FILTERED_VALUE;
25462
- }
25487
+ result2[key] = shouldFilterDataKey(key, behavior, additionalDenyTerms) ? FILTERED_VALUE : data[key];
25463
25488
  }
25464
25489
  return result2;
25465
25490
  }
@@ -25499,6 +25524,55 @@ function parseCookie(str) {
25499
25524
  }
25500
25525
  __name(parseCookie, "parseCookie");
25501
25526
 
25527
+ // node_modules/@sentry/core/build/esm/utils/data-collection/filterQueryParams.js
25528
+ function filterQueryParams(queryString, behavior) {
25529
+ if (!queryString || behavior === false) {
25530
+ return void 0;
25531
+ }
25532
+ return queryString.split("&").map((pair) => {
25533
+ const separatorIndex = pair.indexOf("=");
25534
+ const encodedKey = separatorIndex === -1 ? pair : pair.slice(0, separatorIndex);
25535
+ const key = new URLSearchParams(`${encodedKey}=`).keys().next().value;
25536
+ return key !== void 0 && shouldFilterDataKey(key, behavior) ? `${encodedKey}=${FILTERED_VALUE}` : pair;
25537
+ }).join("&");
25538
+ }
25539
+ __name(filterQueryParams, "filterQueryParams");
25540
+
25541
+ // node_modules/@sentry/core/build/esm/utils/data-collection/filterUrlQuery.js
25542
+ function filterUrlQuery(url, behavior) {
25543
+ const fragmentStart = url.indexOf("#");
25544
+ const queryEnd = fragmentStart === -1 ? url.length : fragmentStart;
25545
+ const queryStart = url.indexOf("?");
25546
+ if (queryStart === -1 || queryStart > queryEnd) {
25547
+ return url;
25548
+ }
25549
+ const prefix = url.slice(0, queryStart);
25550
+ const query = url.slice(queryStart + 1, queryEnd);
25551
+ const suffix = url.slice(queryEnd);
25552
+ const filtered = filterQueryParams(query, behavior);
25553
+ return filtered ? `${prefix}?${filtered}${suffix}` : `${prefix}${suffix}`;
25554
+ }
25555
+ __name(filterUrlQuery, "filterUrlQuery");
25556
+
25557
+ // node_modules/@sentry/core/build/esm/utils/data-collection/filterCollectedUrl.js
25558
+ function urlQueryParamsBehavior(client) {
25559
+ return (client ?? getClient())?.getDataCollectionOptions().urlQueryParams ?? true;
25560
+ }
25561
+ __name(urlQueryParamsBehavior, "urlQueryParamsBehavior");
25562
+ function filterCollectedUrl(url, client) {
25563
+ return url === void 0 ? void 0 : filterUrlQuery(url, urlQueryParamsBehavior(client));
25564
+ }
25565
+ __name(filterCollectedUrl, "filterCollectedUrl");
25566
+ function filterCollectedUrlQuery(query, client) {
25567
+ if (!query) {
25568
+ return query;
25569
+ }
25570
+ const hasPrefix = query.startsWith("?");
25571
+ const filtered = filterQueryParams(hasPrefix ? query.slice(1) : query, urlQueryParamsBehavior(client));
25572
+ return filtered && hasPrefix ? `?${filtered}` : filtered;
25573
+ }
25574
+ __name(filterCollectedUrlQuery, "filterCollectedUrlQuery");
25575
+
25502
25576
  // node_modules/@sentry/core/build/esm/utils/envToBool.js
25503
25577
  var FALSY_ENV_VALUES = /* @__PURE__ */ new Set(["false", "f", "n", "no", "off", "0"]);
25504
25578
  var TRUTHY_ENV_VALUES = /* @__PURE__ */ new Set(["true", "t", "y", "yes", "on", "1"]);
@@ -25596,7 +25670,7 @@ function getHttpSpanNameFromUrlObject(urlObject, kind, request, routeName) {
25596
25670
  return `${method} ${route2}`;
25597
25671
  }
25598
25672
  __name(getHttpSpanNameFromUrlObject, "getHttpSpanNameFromUrlObject");
25599
- function getHttpSpanDetailsFromUrlObject(urlObject, kind, spanOrigin, request, routeName) {
25673
+ function getHttpSpanDetailsFromUrlObject(urlObject, kind, spanOrigin, request, routeName, client) {
25600
25674
  const attributes = {
25601
25675
  [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,
25602
25676
  [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url"
@@ -25610,7 +25684,7 @@ function getHttpSpanDetailsFromUrlObject(urlObject, kind, spanOrigin, request, r
25610
25684
  }
25611
25685
  if (urlObject) {
25612
25686
  if (urlObject.search) {
25613
- attributes["url.query"] = urlObject.search;
25687
+ attributes["url.query"] = filterCollectedUrlQuery(urlObject.search, client);
25614
25688
  }
25615
25689
  if (urlObject.hash) {
25616
25690
  attributes["url.fragment"] = urlObject.hash;
@@ -25622,7 +25696,7 @@ function getHttpSpanDetailsFromUrlObject(urlObject, kind, spanOrigin, request, r
25622
25696
  }
25623
25697
  }
25624
25698
  if (!isURLObjectRelative(urlObject)) {
25625
- attributes[Yu] = urlObject.href;
25699
+ attributes[Yu] = filterCollectedUrl(urlObject.href, client);
25626
25700
  if (urlObject.port) {
25627
25701
  attributes["url.port"] = urlObject.port;
25628
25702
  }
@@ -26465,7 +26539,8 @@ var _requestDataIntegration = /* @__PURE__ */ __name(((options = {}) => {
26465
26539
  ...options.include?.cookies === true && dc.cookies === false && { cookies: true },
26466
26540
  ...options.include?.headers === true && dc.httpHeaders.request === false && {
26467
26541
  httpHeaders: { ...dc.httpHeaders, request: true }
26468
- }
26542
+ },
26543
+ ...options.include?.query_string === true && dc.urlQueryParams === false && { urlQueryParams: true }
26469
26544
  };
26470
26545
  return {
26471
26546
  dataCollection,
@@ -26488,9 +26563,9 @@ var _requestDataIntegration = /* @__PURE__ */ __name(((options = {}) => {
26488
26563
  processEvent(event, _hint, client) {
26489
26564
  const { sdkProcessingMetadata = {} } = event;
26490
26565
  const { normalizedRequest, ipAddress } = sdkProcessingMetadata;
26491
- const { include } = resolveIncludeAndDataCollection(client);
26566
+ const { include, dataCollection } = resolveIncludeAndDataCollection(client);
26492
26567
  if (normalizedRequest) {
26493
- addNormalizedRequestDataToEvent(event, normalizedRequest, { ipAddress }, include);
26568
+ addNormalizedRequestDataToEvent(event, normalizedRequest, { ipAddress }, include, dataCollection);
26494
26569
  }
26495
26570
  return event;
26496
26571
  },
@@ -26506,10 +26581,17 @@ var _requestDataIntegration = /* @__PURE__ */ __name(((options = {}) => {
26506
26581
  };
26507
26582
  }), "_requestDataIntegration");
26508
26583
  var requestDataIntegration = defineIntegration(_requestDataIntegration);
26509
- function addNormalizedRequestDataToEvent(event, req, additionalData, include) {
26584
+ function addNormalizedRequestDataToEvent(event, req, additionalData, include, dataCollection) {
26585
+ const requestData = extractNormalizedRequestData(req, include);
26586
+ if (requestData.query_string) {
26587
+ requestData.query_string = normalizeAndFilterQueryString(requestData.query_string, dataCollection.urlQueryParams);
26588
+ }
26589
+ if (requestData.url) {
26590
+ requestData.url = filterUrlQuery(requestData.url, dataCollection.urlQueryParams);
26591
+ }
26510
26592
  event.request = {
26511
26593
  ...event.request,
26512
- ...extractNormalizedRequestData(req, include)
26594
+ ...requestData
26513
26595
  };
26514
26596
  if (include.ip) {
26515
26597
  const ip = req.headers && getClientIPAddress(req.headers) || additionalData.ipAddress;
@@ -26526,13 +26608,13 @@ function addNormalizedRequestDataToSpan(span, normalizedRequest, ipAddress, incl
26526
26608
  const requestData = extractNormalizedRequestData(normalizedRequest, include);
26527
26609
  const attributes = {};
26528
26610
  if (requestData.url) {
26529
- attributes[Yu] = requestData.url;
26611
+ attributes[Yu] = filterUrlQuery(requestData.url, dataCollection.urlQueryParams);
26530
26612
  }
26531
26613
  if (requestData.method) {
26532
26614
  attributes["http.request.method"] = requestData.method;
26533
26615
  }
26534
26616
  if (requestData.query_string) {
26535
- attributes[Hu] = normalizeQueryString(requestData.query_string);
26617
+ attributes[Hu] = normalizeAndFilterQueryString(requestData.query_string, dataCollection.urlQueryParams);
26536
26618
  }
26537
26619
  safeSetSpanJSONAttributes(span, attributes);
26538
26620
  if (requestData.cookies && Object.keys(requestData.cookies).length > 0) {
@@ -26592,13 +26674,18 @@ function extractNormalizedRequestData(normalizedRequest, include) {
26592
26674
  return requestData;
26593
26675
  }
26594
26676
  __name(extractNormalizedRequestData, "extractNormalizedRequestData");
26677
+ function normalizeAndFilterQueryString(queryString, behavior) {
26678
+ const normalized = normalizeQueryString(queryString);
26679
+ return normalized ? filterQueryParams(normalized, behavior) : void 0;
26680
+ }
26681
+ __name(normalizeAndFilterQueryString, "normalizeAndFilterQueryString");
26595
26682
  function normalizeQueryString(queryString) {
26596
26683
  if (typeof queryString === "string") {
26597
26684
  return queryString || void 0;
26598
26685
  }
26599
26686
  const pairs = Array.isArray(queryString) ? queryString : Object.entries(queryString);
26600
- const result2 = pairs.map(([key, value]) => `${key}=${value}`).join("&");
26601
- return result2 || void 0;
26687
+ const normalized = new URLSearchParams(pairs).toString();
26688
+ return normalized || void 0;
26602
26689
  }
26603
26690
  __name(normalizeQueryString, "normalizeQueryString");
26604
26691
 
@@ -26892,7 +26979,7 @@ function instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeade
26892
26979
  const client = getClient();
26893
26980
  const hasParent = !!getActiveSpan();
26894
26981
  const shouldEmitSpan = hasParent || !!client && hasSpanStreamingEnabled(client);
26895
- const span = shouldCreateSpanResult && shouldEmitSpan ? startInactiveSpan(getSpanStartOptions(url, method, spanOrigin)) : new SentryNonRecordingSpan();
26982
+ const span = shouldCreateSpanResult && shouldEmitSpan ? startInactiveSpan(getSpanStartOptions(url, method, spanOrigin, client)) : new SentryNonRecordingSpan();
26896
26983
  const spanForTraceHeaders = spanIsIgnored(span) && hasParent ? void 0 : span;
26897
26984
  if (shouldCreateSpanResult && !shouldEmitSpan) {
26898
26985
  client?.recordDroppedEvent("no_parent_span", "span");
@@ -27039,25 +27126,25 @@ function isHeadersInitTupleArray(headers) {
27039
27126
  );
27040
27127
  }
27041
27128
  __name(isHeadersInitTupleArray, "isHeadersInitTupleArray");
27042
- function getSpanStartOptions(url, method, spanOrigin) {
27129
+ function getSpanStartOptions(url, method, spanOrigin, client) {
27043
27130
  if (url.startsWith("data:")) {
27044
27131
  const sanitizedUrl2 = stripDataUrlContent(url);
27045
27132
  return {
27046
27133
  name: `${method} ${sanitizedUrl2}`,
27047
- attributes: getFetchSpanAttributes(url, void 0, method, spanOrigin)
27134
+ attributes: getFetchSpanAttributes(url, void 0, method, spanOrigin, client)
27048
27135
  };
27049
27136
  }
27050
27137
  const parsedUrl = parseStringToURLObject(url);
27051
27138
  const sanitizedUrl = parsedUrl ? getSanitizedUrlStringFromUrlObject(parsedUrl) : url;
27052
27139
  return {
27053
27140
  name: `${method} ${sanitizedUrl}`,
27054
- attributes: getFetchSpanAttributes(url, parsedUrl, method, spanOrigin)
27141
+ attributes: getFetchSpanAttributes(url, parsedUrl, method, spanOrigin, client)
27055
27142
  };
27056
27143
  }
27057
27144
  __name(getSpanStartOptions, "getSpanStartOptions");
27058
- function getFetchSpanAttributes(url, parsedUrl, method, spanOrigin) {
27145
+ function getFetchSpanAttributes(url, parsedUrl, method, spanOrigin, client) {
27059
27146
  const attributes = {
27060
- url: stripDataUrlContent(url),
27147
+ url: filterCollectedUrl(stripDataUrlContent(url), client),
27061
27148
  type: "fetch",
27062
27149
  "http.method": method,
27063
27150
  [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,
@@ -27065,12 +27152,12 @@ function getFetchSpanAttributes(url, parsedUrl, method, spanOrigin) {
27065
27152
  };
27066
27153
  if (parsedUrl) {
27067
27154
  if (!isURLObjectRelative(parsedUrl)) {
27068
- attributes[ws] = stripDataUrlContent(parsedUrl.href);
27069
- attributes[Yu] = stripDataUrlContent(parsedUrl.href);
27155
+ attributes[ws] = filterCollectedUrl(stripDataUrlContent(parsedUrl.href), client);
27156
+ attributes[Yu] = filterCollectedUrl(stripDataUrlContent(parsedUrl.href), client);
27070
27157
  attributes["server.address"] = parsedUrl.host;
27071
27158
  }
27072
27159
  if (parsedUrl.search) {
27073
- attributes["http.query"] = parsedUrl.search;
27160
+ attributes["http.query"] = filterCollectedUrlQuery(parsedUrl.search, client);
27074
27161
  }
27075
27162
  if (parsedUrl.hash) {
27076
27163
  attributes["http.fragment"] = parsedUrl.hash;
@@ -27392,25 +27479,28 @@ function shouldEnableTruncation(enableTruncation) {
27392
27479
  return !hasSpanStreamingEnabled(client) && client.getOptions().streamGenAiSpans === false;
27393
27480
  }
27394
27481
  __name(shouldEnableTruncation, "shouldEnableTruncation");
27395
- function setTokenUsageAttributes(span, promptTokens, completionTokens, cachedInputTokens, cachedOutputTokens) {
27396
- if (promptTokens !== void 0) {
27397
- span.setAttributes({
27398
- [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens
27399
- });
27482
+ function getTokenUsageAttributes(promptTokens, completionTokens, cacheCreationInputTokens, cacheReadInputTokens, totalTokens) {
27483
+ const attributes = {};
27484
+ if (typeof promptTokens === "number") {
27485
+ attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = promptTokens;
27400
27486
  }
27401
- if (completionTokens !== void 0) {
27402
- span.setAttributes({
27403
- [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens
27404
- });
27487
+ if (typeof cacheCreationInputTokens === "number") {
27488
+ attributes[Aa] = cacheCreationInputTokens;
27405
27489
  }
27406
- if (promptTokens !== void 0 || completionTokens !== void 0 || cachedInputTokens !== void 0 || cachedOutputTokens !== void 0) {
27407
- const totalTokens = (promptTokens ?? 0) + (completionTokens ?? 0) + (cachedInputTokens ?? 0) + (cachedOutputTokens ?? 0);
27408
- span.setAttributes({
27409
- [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens
27410
- });
27490
+ if (typeof cacheReadInputTokens === "number") {
27491
+ attributes[xa] = cacheReadInputTokens;
27492
+ }
27493
+ if (typeof completionTokens === "number") {
27494
+ attributes[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = completionTokens;
27495
+ }
27496
+ if (typeof totalTokens === "number") {
27497
+ attributes[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = totalTokens;
27498
+ } else if (typeof promptTokens === "number" || typeof completionTokens === "number") {
27499
+ attributes[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = (typeof promptTokens === "number" ? promptTokens : 0) + (typeof completionTokens === "number" ? completionTokens : 0);
27411
27500
  }
27501
+ return attributes;
27412
27502
  }
27413
- __name(setTokenUsageAttributes, "setTokenUsageAttributes");
27503
+ __name(getTokenUsageAttributes, "getTokenUsageAttributes");
27414
27504
  function endStreamSpan(span, state, recordOutputs) {
27415
27505
  if (!span.isRecording()) {
27416
27506
  return;
@@ -27420,12 +27510,18 @@ function endStreamSpan(span, state, recordOutputs) {
27420
27510
  };
27421
27511
  if (state.responseId) attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = state.responseId;
27422
27512
  if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = state.responseModel;
27423
- if (state.promptTokens !== void 0) attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = state.promptTokens;
27424
- if (state.completionTokens !== void 0) attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = state.completionTokens;
27425
- if (state.totalTokens !== void 0) {
27426
- attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = state.totalTokens;
27427
- } else if (state.promptTokens !== void 0 || state.completionTokens !== void 0 || state.cacheCreationInputTokens !== void 0 || state.cacheReadInputTokens !== void 0) {
27428
- attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = (state.promptTokens ?? 0) + (state.completionTokens ?? 0) + (state.cacheCreationInputTokens ?? 0) + (state.cacheReadInputTokens ?? 0);
27513
+ Object.assign(
27514
+ attrs,
27515
+ getTokenUsageAttributes(
27516
+ state.promptTokens,
27517
+ state.completionTokens,
27518
+ state.cacheCreationInputTokens,
27519
+ state.cacheReadInputTokens,
27520
+ state.totalTokens
27521
+ )
27522
+ );
27523
+ if (typeof state.reasoningOutputTokens === "number") {
27524
+ attrs[Ua] = state.reasoningOutputTokens;
27429
27525
  }
27430
27526
  if (state.finishReasons.length) {
27431
27527
  attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(state.finishReasons);
@@ -27588,7 +27684,7 @@ function addResponseAttributes(span, result2, recordOutputs) {
27588
27684
  }
27589
27685
  const response = result2;
27590
27686
  if (response.usage) {
27591
- setTokenUsageAttributes(span, response.usage.prompt_tokens, response.usage.completion_tokens);
27687
+ span.setAttributes(getTokenUsageAttributes(response.usage.prompt_tokens, response.usage.completion_tokens));
27592
27688
  }
27593
27689
  if (recordOutputs) {
27594
27690
  let responseText;
@@ -28586,7 +28682,7 @@ var UPDATE_RE = new RegExp(
28586
28682
  "i"
28587
28683
  );
28588
28684
  var DELETE_RE = new RegExp(`^\\s*(?<operation>DELETE)\\s+FROM\\s+(?<table>${TABLE_NAME})`, "i");
28589
- var SELECT_RE = /^\s*\(?\s*(?<operation>SELECT)\b/i;
28685
+ var SELECT_RE = /^\s*(?:\(\s*)?(?<operation>SELECT)\b/i;
28590
28686
  var PRAGMA_RE = /^\s*(?<operation>PRAGMA)\s+(?<command>\S+)/i;
28591
28687
  var TOKEN_RE = /\b(?:FROM|JOIN)\s+|\(\s*(SELECT)\b|\b(?:UNION|INTERSECT|EXCEPT|MINUS)\s+(?:ALL\s+)?(SELECT)\b/gi;
28592
28688
  var QUOTED_OR_PLAIN_TABLE_RE = /^(?:"[^"]*"|'[^']*'|[^\s(,;)]+)/;
@@ -28998,16 +29094,23 @@ var CloudflareClient = class extends ServerRuntimeClient {
28998
29094
  }
28999
29095
  /**
29000
29096
  * Flushes pending operations and ensures all data is processed.
29001
- * If a timeout is provided, the operation will be completed within the specified time limit.
29002
29097
  *
29003
- * It will wait for all pending spans to complete before flushing.
29098
+ * Each phase waits at most `timeout`: the flush lock of a per-invocation client, pending spans, event
29099
+ * processing and the transport drain. So a flush can take a small multiple of `timeout`, which stays well
29100
+ * below Cloudflare's 30 second `waitUntil` limit for the timeouts the SDK uses. Sends still pending when
29101
+ * the drain times out are aborted.
29004
29102
  *
29005
- * @param {number} [timeout] - Optional timeout in milliseconds to force the completion of the flush operation.
29103
+ * @param {number} [timeout] - Maximum time in milliseconds for each phase of the flush.
29006
29104
  * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.
29007
29105
  */
29008
29106
  async flush(timeout) {
29009
29107
  if (this._flushLock) {
29010
- await this._flushLock.finalize();
29108
+ let timer;
29109
+ await Promise.race([
29110
+ this._flushLock.finalize(),
29111
+ ...timeout ? [new Promise((resolve3) => timer = setTimeout(resolve3, timeout))] : []
29112
+ ]);
29113
+ clearTimeout(timer);
29011
29114
  }
29012
29115
  if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {
29013
29116
  DEBUG_BUILD2 && debug.log("[CloudflareClient] Waiting for", this._pendingSpans.size, "pending spans to complete...");
@@ -29395,15 +29498,24 @@ var IsolatedPromiseBuffer = class {
29395
29498
  drain(timeout) {
29396
29499
  const oldTaskProducers = [...this._taskProducers];
29397
29500
  this._taskProducers = [];
29501
+ const drainController = new AbortController();
29502
+ this.drainSignal = drainController.signal;
29503
+ let tasks;
29504
+ try {
29505
+ tasks = oldTaskProducers.map((taskProducer) => taskProducer());
29506
+ } finally {
29507
+ this.drainSignal = void 0;
29508
+ }
29398
29509
  return new Promise((resolve3) => {
29399
29510
  const timer = setTimeout(() => {
29400
29511
  if (timeout && timeout > 0) {
29512
+ drainController.abort();
29401
29513
  resolve3(false);
29402
29514
  }
29403
29515
  }, timeout);
29404
29516
  Promise.all(
29405
- oldTaskProducers.map(
29406
- (taskProducer) => taskProducer().then(null, () => {
29517
+ tasks.map(
29518
+ (task) => task.then(null, () => {
29407
29519
  })
29408
29520
  )
29409
29521
  ).then(() => {
@@ -29414,12 +29526,17 @@ var IsolatedPromiseBuffer = class {
29414
29526
  }
29415
29527
  };
29416
29528
  function makeCloudflareTransport(options) {
29529
+ const buffer = new IsolatedPromiseBuffer(options.bufferSize);
29417
29530
  function makeRequest(request) {
29531
+ const drainSignal = buffer.drainSignal;
29532
+ const callerSignal = options.fetchOptions?.signal ?? void 0;
29533
+ const signal = drainSignal && callerSignal ? AbortSignal.any([drainSignal, callerSignal]) : drainSignal ?? callerSignal;
29418
29534
  const requestOptions = {
29419
29535
  body: request.body,
29420
29536
  method: "POST",
29421
29537
  headers: options.headers,
29422
- ...options.fetchOptions
29538
+ ...options.fetchOptions,
29539
+ ...signal ? { signal } : {}
29423
29540
  };
29424
29541
  return suppressTracing(() => {
29425
29542
  return (options.fetch ?? fetch)(options.url, requestOptions).then(async (response) => {
@@ -29438,7 +29555,7 @@ function makeCloudflareTransport(options) {
29438
29555
  });
29439
29556
  }
29440
29557
  __name(makeRequest, "makeRequest");
29441
- return createTransport(options, makeRequest, new IsolatedPromiseBuffer(options.bufferSize));
29558
+ return createTransport(options, makeRequest, buffer);
29442
29559
  }
29443
29560
  __name(makeCloudflareTransport, "makeCloudflareTransport");
29444
29561
 
@@ -30144,6 +30261,12 @@ function instrumentDurableObjectNamespace(namespace, propagateRpcTrace = false)
30144
30261
  return instrumentDurableObjectStub(stub, propagateRpcTrace);
30145
30262
  };
30146
30263
  }
30264
+ if (prop === "jurisdiction") {
30265
+ return function(...args) {
30266
+ const subnamespace = Reflect.apply(value, target, args);
30267
+ return instrumentDurableObjectNamespace(subnamespace, propagateRpcTrace);
30268
+ };
30269
+ }
30147
30270
  return value.bind(target);
30148
30271
  }
30149
30272
  });
@@ -30555,7 +30678,14 @@ function wrapRequestHandler(wrapperOptions, handler) {
30555
30678
  const client = init({ ...options, ctx: context });
30556
30679
  isolationScope.setClient(client);
30557
30680
  const urlObject = parseStringToURLObject(request.url);
30558
- const [name2, attributes] = getHttpSpanDetailsFromUrlObject(urlObject, "server", "auto.http.cloudflare", request);
30681
+ const [name2, attributes] = getHttpSpanDetailsFromUrlObject(
30682
+ urlObject,
30683
+ "server",
30684
+ "auto.http.cloudflare",
30685
+ request,
30686
+ void 0,
30687
+ client
30688
+ );
30559
30689
  const contentLength = request.headers.get("content-length");
30560
30690
  if (contentLength) {
30561
30691
  attributes["http.request.body.size"] = parseInt(contentLength, 10);
@@ -30929,6 +31059,7 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
30929
31059
  args = extracted.args;
30930
31060
  rpcMeta = extracted.rpcMeta;
30931
31061
  }
31062
+ const spanName = typeof wrapperOptions.spanName === "function" ? wrapperOptions.spanName(rpcMeta) : wrapperOptions.spanName;
30932
31063
  const wrappedFunction = /* @__PURE__ */ __name((scope) => {
30933
31064
  const context = wrapperOptions.context;
30934
31065
  const waitUntil = context ? getOriginalWaitUntil(context)?.bind(context) : void 0;
@@ -30943,7 +31074,7 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
30943
31074
  scopeClient = client;
30944
31075
  }
30945
31076
  const clientToDispose = scopeClient;
30946
- const methodName = wrapperOptions.spanName || "unknown";
31077
+ const methodName = spanName || "unknown";
30947
31078
  const teardown = /* @__PURE__ */ __name(async () => {
30948
31079
  if (startNewTrace$1 && storage) {
30949
31080
  storeSpanContext(storage, methodName);
@@ -30964,7 +31095,7 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
30964
31095
  waitUntil?.(teardown());
30965
31096
  throw e;
30966
31097
  }, "onRejected");
30967
- if (!wrapperOptions.spanName) {
31098
+ if (!spanName) {
30968
31099
  try {
30969
31100
  if (callback) {
30970
31101
  callback(...args);