@vellumai/assistant 0.11.1-dev.202608032034.aebd2da → 0.11.1-dev.202608032226.351a4e2

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.
Files changed (47) hide show
  1. package/openapi.yaml +1 -0
  2. package/package.json +1 -1
  3. package/src/__tests__/agent-loop-resume-interrupted.test.ts +223 -0
  4. package/src/__tests__/conversation-agent-loop.test.ts +16 -7
  5. package/src/__tests__/conversation-error.test.ts +106 -0
  6. package/src/__tests__/llm-resolver.test.ts +16 -0
  7. package/src/__tests__/provider-send-message-override-profile.test.ts +95 -0
  8. package/src/__tests__/workspace-migration-137-repair-retired-fireworks-minimax-model-id.test.ts +6 -6
  9. package/src/__tests__/workspace-migration-138-backfill-home-feed-titles.test.ts +373 -0
  10. package/src/agent/loop.ts +36 -7
  11. package/src/cli/commands/notifications.help.ts +3 -2
  12. package/src/config/llm-resolver.ts +19 -3
  13. package/src/daemon/conversation-agent-loop-handlers.ts +15 -6
  14. package/src/daemon/conversation-agent-loop.ts +31 -18
  15. package/src/daemon/conversation-error.ts +40 -24
  16. package/src/home/__tests__/feed-types.test.ts +43 -8
  17. package/src/home/__tests__/feed-writer.test.ts +59 -0
  18. package/src/home/feed-types.ts +34 -7
  19. package/src/home/feed-writer.ts +15 -6
  20. package/src/live-voice/__tests__/activity-label.test.ts +68 -0
  21. package/src/live-voice/__tests__/live-activity-reporter.test.ts +86 -5
  22. package/src/live-voice/__tests__/live-voice-agent-turn.test.ts +14 -5
  23. package/src/live-voice/activity-label.ts +106 -0
  24. package/src/live-voice/live-activity-reporter.ts +35 -6
  25. package/src/live-voice/live-voice-session.ts +58 -0
  26. package/src/live-voice/protocol.ts +23 -0
  27. package/src/notifications/__tests__/copy-composer.test.ts +53 -3
  28. package/src/notifications/__tests__/decision-engine.test.ts +150 -20
  29. package/src/notifications/__tests__/edit-notification.test.ts +330 -0
  30. package/src/notifications/__tests__/home-feed-side-effect.test.ts +170 -12
  31. package/src/notifications/copy-composer.ts +23 -3
  32. package/src/notifications/decision-engine.ts +29 -7
  33. package/src/notifications/edit-notification.ts +8 -4
  34. package/src/notifications/home-feed-side-effect.ts +43 -6
  35. package/src/notifications/notification-utils.ts +8 -2
  36. package/src/persistence/conversation-title-service.ts +5 -170
  37. package/src/providers/__tests__/dispatch-connection-routing.test.ts +43 -2
  38. package/src/providers/__tests__/vellum-mismatch-routing.test.ts +8 -0
  39. package/src/providers/call-site-routing.ts +77 -14
  40. package/src/providers/connection-resolution.ts +42 -2
  41. package/src/providers/types.ts +7 -1
  42. package/src/runtime/routes/notification-routes.ts +4 -1
  43. package/src/util/__tests__/short-title.test.ts +229 -0
  44. package/src/util/errors.ts +15 -0
  45. package/src/util/short-title.ts +189 -0
  46. package/src/workspace/migrations/138-backfill-home-feed-titles.ts +179 -0
  47. package/src/workspace/migrations/registry.ts +2 -0
@@ -22,6 +22,7 @@ import {
22
22
  updateDeliveryRenderedCopy,
23
23
  } from "./deliveries-store.js";
24
24
  import { getBroadcaster } from "./emit-signal.js";
25
+ import { nonEmpty } from "./notification-utils.js";
25
26
  import type { NotificationChannel } from "./types.js";
26
27
 
27
28
  const log = getLogger("edit-notification");
@@ -88,8 +89,12 @@ export async function editNotification(
88
89
  ): Promise<EditNotificationResult | null> {
89
90
  const feedItemId = normalizeFeedItemId(params.id);
90
91
 
92
+ // Titles are never cleared, so a blank one is dropped before it can
93
+ // reach the feed patch or a channel update.
94
+ const title = nonEmpty(params.title);
95
+
91
96
  const feedItem = await patchFeedItemContent(feedItemId, {
92
- title: params.title,
97
+ title,
93
98
  summary: params.body,
94
99
  urgency: params.urgency,
95
100
  status: params.status,
@@ -102,8 +107,7 @@ export async function editNotification(
102
107
  // Only edit channel messages when the user-visible text changed.
103
108
  // Urgency/status are feed-only — pushing a channel update for those
104
109
  // alone would re-deliver the same body and confuse the recipient.
105
- const shouldUpdateChannels =
106
- params.title !== undefined || params.body !== undefined;
110
+ const shouldUpdateChannels = title !== undefined || params.body !== undefined;
107
111
  if (!shouldUpdateChannels) {
108
112
  return { feedItem, channels: [] };
109
113
  }
@@ -120,7 +124,7 @@ export async function editNotification(
120
124
 
121
125
  const deliveries = findDeliveriesByDecisionId(decision.id);
122
126
  const channels = await updateChannelDeliveries(deliveries, {
123
- title: params.title,
127
+ title,
124
128
  body: params.body,
125
129
  });
126
130
 
@@ -20,7 +20,9 @@ import { appendFeedItem } from "../home/feed-writer.js";
20
20
  import { getConversation } from "../persistence/conversation-crud.js";
21
21
  import { isBackgroundConversationType } from "../persistence/conversation-types.js";
22
22
  import { getLogger } from "../util/logger.js";
23
+ import { normalizeTitle, stripMarkdown } from "../util/short-title.js";
23
24
  import { isConversationSeedSane } from "./conversation-seed-composer.js";
25
+ import { deriveTitle } from "./copy-composer.js";
24
26
  import { readPayloadString } from "./notification-utils.js";
25
27
  import type { NotificationSignal } from "./signal.js";
26
28
  import type { NotificationDecision, RenderedChannelCopy } from "./types.js";
@@ -66,11 +68,6 @@ export async function writeHomeFeedItemForSignal(
66
68
  readPayloadString(signal.contextPayload, "body") ??
67
69
  readPayloadString(signal.contextPayload, "requestedMessage");
68
70
 
69
- // Source the title from the payload only. The LLM's `renderedCopy.title`
70
- // often echoes the body when no explicit title was passed, which stutters
71
- // against `summary` in the row. Leave undefined when absent; renderers
72
- // fall back to `summary`.
73
- const resolvedTitle = payloadTitle?.trim() || undefined;
74
71
  // Prefer conversationSeedMessage over body for the home feed: the seed
75
72
  // message is richer and may contain structured markdown (lists, headers,
76
73
  // bold) that the detail panel renders. The popup-oriented `body` is
@@ -91,6 +88,15 @@ export async function writeHomeFeedItemForSignal(
91
88
  return null;
92
89
  }
93
90
 
91
+ // Title order: payload, then the rendered copy, then a headline derived
92
+ // from the summary. `normalizeTitle` returns "" for empty, prose-shaped, and
93
+ // meta-failure candidates; the derivation always yields something, so every
94
+ // feed item lands with a title.
95
+ const resolvedTitle =
96
+ normalizeTitle(payloadTitle ?? "") ||
97
+ normalizeTitle(renderedCopy?.title ?? "") ||
98
+ deriveFallbackTitle(resolvedSummary);
99
+
94
100
  const urgency = signal.attentionHints.urgency;
95
101
  const now = new Date().toISOString();
96
102
 
@@ -122,7 +128,7 @@ export async function writeHomeFeedItemForSignal(
122
128
  id: `notif:${signal.signalId}`,
123
129
  type: "notification",
124
130
  priority: 50,
125
- ...(resolvedTitle ? { title: resolvedTitle } : {}),
131
+ title: resolvedTitle,
126
132
  summary: resolvedSummary,
127
133
  timestamp: now,
128
134
  createdAt: now,
@@ -150,6 +156,37 @@ export async function writeHomeFeedItemForSignal(
150
156
  return item;
151
157
  }
152
158
 
159
+ /**
160
+ * Derive the terminal fallback headline from the summary.
161
+ *
162
+ * The summary is preferentially a conversation seed, which carries structured
163
+ * markdown and hard line breaks, so flatten it to plain single-line text
164
+ * before slicing a headline off the front. A non-empty summary always yields a
165
+ * non-empty title.
166
+ */
167
+ function deriveFallbackTitle(summary: string): string {
168
+ // Block markers are line-anchored, so they have to go before the whitespace
169
+ // collapse, and before `stripMarkdown` (whose inline-code rule would chew a
170
+ // fence into a stray backtick). Ordered markers matter most: the seed prompt
171
+ // asks the model for numbered lists, and a leading `1.` also reads as a
172
+ // sentence terminator, which would truncate the title to the first digit.
173
+ // The leading-space allowance and rule set mirror `flattenToPlainText` in
174
+ // workspace migration 138, which must stay self-contained and so cannot share
175
+ // this code. A backfilled title and a freshly written one have to match.
176
+ const deblocked = summary
177
+ .replace(/^\s{0,3}(?:```|~~~).*$/gm, "")
178
+ .replace(/^\s{0,3}#{1,6}\s+/gm, "")
179
+ .replace(/^\s{0,3}>\s?/gm, "")
180
+ .replace(/^\s{0,3}(?:[-*+]|\d+[.)])\s+/gm, "");
181
+ const plain = flattenWhitespace(stripMarkdown(deblocked));
182
+ return deriveTitle(plain || flattenWhitespace(summary));
183
+ }
184
+
185
+ /** Collapse whitespace runs, including hard line breaks, into single spaces. */
186
+ function flattenWhitespace(text: string): string {
187
+ return text.replace(/\s+/g, " ").trim();
188
+ }
189
+
153
190
  // ── Category & detail-panel derivation ────────────────────────────────
154
191
 
155
192
  const EVENT_CATEGORY_MAP: Record<string, FeedItemCategory> = {
@@ -91,8 +91,14 @@ export function sanitizeMessagePreview(value: string): string {
91
91
  export const NOTIFICATION_TITLE_MAX_LENGTH = 60;
92
92
 
93
93
  /**
94
- * Sanitize an untrusted notification title for inclusion in notification copy.
95
- * Strips control characters and clamps to `NOTIFICATION_TITLE_MAX_LENGTH`.
94
+ * Flatten an untrusted notification title onto a single line, stripping control
95
+ * characters and newlines and bounding it at `NOTIFICATION_TITLE_MAX_LENGTH`.
96
+ *
97
+ * The newline flattening is the load-bearing part: downstream consumers re-run
98
+ * the value through `normalizeTitle`, whose prose guard discards any string
99
+ * containing a newline outright, so a multi-line conversation title would be
100
+ * thrown away wholesale instead of salvaged. The length bound is a backstop;
101
+ * `normalizeTitle`'s tighter 40-character budget is what callers observe.
96
102
  */
97
103
  export function sanitizeNotificationTitle(value: string): string {
98
104
  return sanitize(value, NOTIFICATION_TITLE_MAX_LENGTH);
@@ -18,6 +18,11 @@ import type { Provider, ToolDefinition } from "../providers/types.js";
18
18
  import { publishConversationTitleChanged } from "../runtime/sync/resource-sync-events.js";
19
19
  import { getLogger } from "../util/logger.js";
20
20
  import { Mutex } from "../util/mutex.js";
21
+ import {
22
+ normalizeTitle,
23
+ stripThinkingTags,
24
+ truncateTitle,
25
+ } from "../util/short-title.js";
21
26
  import {
22
27
  getConversation,
23
28
  getMessages,
@@ -577,176 +582,6 @@ function logRetryableFallback(
577
582
  );
578
583
  }
579
584
 
580
- const META_FAILURE_TITLES = new Set([
581
- "missing context",
582
- "no context",
583
- "insufficient context",
584
- "unclear context",
585
- "empty context",
586
- "no topic",
587
- "unclear topic",
588
- "unclear request",
589
- "unclear message",
590
- "empty conversation",
591
- "empty message",
592
- "no content",
593
- ]);
594
-
595
- const MAX_TITLE_LENGTH = 40;
596
- const MAX_TITLE_WORDS = 7;
597
-
598
- function truncateTitle(title: string): string {
599
- if (title.length <= MAX_TITLE_LENGTH) {
600
- return title;
601
- }
602
- const words = title.split(/\s+/);
603
- if (words.length <= MAX_TITLE_WORDS) {
604
- // Long words but few of them — truncate to char limit at word boundary
605
- let result = "";
606
- for (const word of words) {
607
- const candidate = result ? result + " " + word : word;
608
- if (candidate.length > MAX_TITLE_LENGTH) {
609
- break;
610
- }
611
- result = candidate;
612
- }
613
- return result || title.slice(0, MAX_TITLE_LENGTH);
614
- }
615
- // Too many words — trim to 5 words
616
- return words.slice(0, 5).join(" ");
617
- }
618
-
619
- function normalizeTitle(raw: string): string {
620
- let title = raw.trim().replace(/^["']|["']$/g, "");
621
- title = stripMarkdown(title);
622
- title = stripThinkingTags(title).trim();
623
- if (!title) {
624
- return "";
625
- }
626
- // Reject outputs that are the model reasoning aloud or continuing the
627
- // conversation instead of naming it (e.g. "I need to generate a…", "I'll
628
- // work through these files…"). Callers fall back to a deterministic title.
629
- if (looksLikeLeakedProse(title)) {
630
- return "";
631
- }
632
- if (META_FAILURE_TITLES.has(title.toLowerCase())) {
633
- return "";
634
- }
635
- return truncateTitle(title);
636
- }
637
-
638
- /** Reasoning/sentence openers that never start a legitimate topic title. */
639
- const LEAKED_PROSE_PREFIXES = [
640
- "i need to",
641
- "i needed to",
642
- "i should",
643
- "i will",
644
- "i'll",
645
- "i can ",
646
- "i can't",
647
- "i cannot",
648
- "i'm ",
649
- "i am ",
650
- "i've ",
651
- "i have ",
652
- "i'd ",
653
- "i would",
654
- "let me",
655
- "looking at",
656
- "based on",
657
- "given the",
658
- "to generate",
659
- "to summarize",
660
- "to title",
661
- // Subject-led reasoning openers. A bare noun phrase ("The User Interface
662
- // Redesign", "The Conversation API") is a valid title, so each subject only
663
- // counts as leaked prose when a verb or possessive follows it — marking the
664
- // output as a sentence rather than a topic.
665
- "the user wants",
666
- "the user asked",
667
- "the user is",
668
- "the user wanted",
669
- "the user needs",
670
- "the user said",
671
- "the user has",
672
- "the user would",
673
- "the user's request",
674
- "the conversation is",
675
- "this conversation is",
676
- "the conversation appears",
677
- "the conversation seems",
678
- "the conversation covers",
679
- "the conversation discusses",
680
- "the assistant should",
681
- "the assistant is",
682
- "the assistant wants",
683
- "the assistant needs",
684
- "the title should",
685
- "the title is",
686
- "the title would",
687
- "the title for",
688
- "here's ",
689
- "here is ",
690
- "here are ",
691
- "sure,",
692
- "okay,",
693
- "ok,",
694
- ];
695
-
696
- /**
697
- * Heuristic guard for title outputs that are clearly prose — the model
698
- * reasoning aloud or replying to the conversation rather than naming it. A real
699
- * title is a single-line short noun phrase, so we reject multi-line output,
700
- * embedded transcript markers, leading reasoning openers, and sentence-shaped
701
- * clauses. Deliberately tight: a false reject only costs a deterministic
702
- * fallback title, while a false accept persists a broken one.
703
- */
704
- function looksLikeLeakedProse(title: string): boolean {
705
- if (/\n/.test(title)) {
706
- return true;
707
- }
708
- if (/\b(?:user|assistant)\s*:/i.test(title)) {
709
- return true;
710
- }
711
- const lower = title.toLowerCase();
712
- if (LEAKED_PROSE_PREFIXES.some((prefix) => lower.startsWith(prefix))) {
713
- return true;
714
- }
715
- // Sentence-shaped: terminal punctuation on a multi-word clause.
716
- if (/[.?!]$/.test(title) && title.split(/\s+/).length > 5) {
717
- return true;
718
- }
719
- return false;
720
- }
721
-
722
- /** Strip thinking tags so they don't bleed into generated titles. */
723
- function stripThinkingTags(text: string): string {
724
- return text
725
- .replace(/<thinking>[\s\S]*?<\/thinking>/gi, "")
726
- .replace(/<thought>[\s\S]*?<\/thought>/gi, "")
727
- .replace(/<think>[\s\S]*?<\/think>/gi, "")
728
- .replace(/<thought>/gi, "")
729
- .replace(/<\/thought>/gi, "")
730
- .replace(/<thinking>/gi, "")
731
- .replace(/<\/thinking>/gi, "")
732
- .replace(/<think>/gi, "")
733
- .replace(/<\/think>/gi, "")
734
- .replace(/<:[^>]*>/gi, "");
735
- }
736
-
737
- /** Strip common markdown formatting so titles render as plain text. */
738
- function stripMarkdown(text: string): string {
739
- return text
740
- .replace(/\*\*(.+?)\*\*/g, "$1") // **bold**
741
- .replace(/__(.+?)__/g, "$1") // __bold__
742
- .replace(/\*(.+?)\*/g, "$1") // *italic*
743
- .replace(/(?<!\w)_(.+?)_(?!\w)/g, "$1") // _italic_ (word-boundary-aware to preserve snake_case)
744
- .replace(/~~(.+?)~~/g, "$1") // ~~strikethrough~~
745
- .replace(/`(.+?)`/g, "$1") // `code`
746
- .replace(/\[(.+?)\]\(.+?\)/g, "$1") // [link](url)
747
- .replace(/^#{1,6}\s+/gm, ""); // # headings
748
- }
749
-
750
585
  function deriveFallbackTitle(context?: TitleContext): string | null {
751
586
  if (!context) {
752
587
  return null;
@@ -407,7 +407,14 @@ describe("routing identities", () => {
407
407
  "claude-opus-4-8",
408
408
  );
409
409
 
410
- expect(provider).toEqual({ name: "anthropic", tag: "managed" } as never);
410
+ expect(provider).toEqual({
411
+ name: "anthropic",
412
+ tag: "managed",
413
+ routeAttribution: {
414
+ connectionName: "vellum",
415
+ isManagedRoute: true,
416
+ },
417
+ } as never);
411
418
  expect(resolveProviderCalls[0]?.name).toBe("vellum");
412
419
  expect(resolveProviderOpts[0]?.providerOverride).toBe("anthropic");
413
420
  });
@@ -433,13 +440,47 @@ describe("routing identities", () => {
433
440
  "gpt-5.5",
434
441
  );
435
442
 
436
- expect(provider).toEqual({ name: "openai", tag: "subscription" } as never);
443
+ expect(provider).toEqual({
444
+ name: "openai",
445
+ tag: "subscription",
446
+ routeAttribution: {
447
+ connectionName: "chatgpt-subscription",
448
+ isManagedRoute: false,
449
+ },
450
+ } as never);
437
451
  expect(resolveProviderCalls[0]?.name).toBe("chatgpt-subscription");
438
452
  // No override needed: the subscription row itself carries provider
439
453
  // "openai", so the adapter resolves from the row.
440
454
  expect(resolveProviderCalls[0]?.provider).toBe("openai");
441
455
  });
442
456
 
457
+ // A second managed row is creatable under any non-reserved name: only the
458
+ // canonical name is refused at the create route, and `provider: "vellum"`
459
+ // derives platform auth. Managed-ness is the row, never its name.
460
+ test("a managed row under a non-canonical name carries managed route attribution", async () => {
461
+ fakeConnections.set("managed-openai", {
462
+ name: "managed-openai",
463
+ provider: "vellum",
464
+ auth: { type: "platform" },
465
+ });
466
+ fakeProviders.set("conn:managed-openai", {
467
+ name: "openai",
468
+ tag: "managed",
469
+ });
470
+
471
+ const provider = await tryResolveProviderForConnectionName(
472
+ "managed-openai",
473
+ { llm: {} } as never,
474
+ "openai",
475
+ "gpt-5.5",
476
+ );
477
+
478
+ expect(provider?.routeAttribution).toEqual({
479
+ connectionName: "managed-openai",
480
+ isManagedRoute: true,
481
+ });
482
+ });
483
+
443
484
  test("chatgpt identity with no subscription row throws not_found (never a silent fallback)", async () => {
444
485
  await expect(
445
486
  tryResolveProviderForConnectionName(
@@ -86,6 +86,10 @@ describe("vellum connection mismatch handling", () => {
86
86
  "accounts/fireworks/models/kimi-k2p5",
87
87
  );
88
88
  expect(provider).not.toBeNull();
89
+ expect(provider?.routeAttribution).toEqual({
90
+ connectionName: "vellum",
91
+ isManagedRoute: true,
92
+ });
89
93
  expect(resolveCalls).toHaveLength(1);
90
94
  expect(resolveCalls[0].connection.name).toBe("vellum");
91
95
  expect(resolveCalls[0].opts.providerOverride).toBe("fireworks");
@@ -129,6 +133,10 @@ describe("vellum connection mismatch handling", () => {
129
133
  "anthropic/claude-fable-5",
130
134
  );
131
135
  expect(provider).not.toBeNull();
136
+ expect(provider?.routeAttribution).toEqual({
137
+ connectionName: "openrouter-personal",
138
+ isManagedRoute: false,
139
+ });
132
140
  expect(resolveCalls).toHaveLength(1);
133
141
  expect(resolveCalls[0].connection.name).toBe("openrouter-personal");
134
142
  expect(resolveCalls[0].opts.providerOverride).toBeUndefined();
@@ -21,9 +21,16 @@
21
21
 
22
22
  import { AsyncLocalStorage } from "node:async_hooks";
23
23
 
24
- import { resolveCallSiteConfig } from "../config/llm-resolver.js";
24
+ import {
25
+ resolveCallSiteConfig,
26
+ resolveCallSiteConfigWithProfile,
27
+ } from "../config/llm-resolver.js";
25
28
  import { getConfig } from "../config/loader.js";
26
29
  import { getDb } from "../persistence/db-connection.js";
30
+ import {
31
+ ProviderError,
32
+ type ProviderRouteAttribution,
33
+ } from "../util/errors.js";
27
34
  import { getLogger } from "../util/logger.js";
28
35
  import {
29
36
  describeSubscriptionModelIncompatibility,
@@ -31,6 +38,7 @@ import {
31
38
  } from "./connection-model-compat.js";
32
39
  import {
33
40
  ConnectionResolutionError,
41
+ isManagedConnectionRoute,
34
42
  resolveRoutingIdentity,
35
43
  tryResolveProviderForConnectionName,
36
44
  } from "./connection-resolution.js";
@@ -46,6 +54,14 @@ import type {
46
54
  } from "./types.js";
47
55
 
48
56
  const log = getLogger("providers/call-site-routing");
57
+
58
+ interface SelectedProviderRoute {
59
+ provider: Provider;
60
+ connectionName?: string;
61
+ profileName?: string;
62
+ isManagedRoute?: boolean;
63
+ }
64
+
49
65
  export class CallSiteRoutingProvider implements Provider {
50
66
  public readonly tokenEstimationProvider?: string;
51
67
  // Forward native web-search capability so it survives the wrapper chain
@@ -99,6 +115,7 @@ export class CallSiteRoutingProvider implements Provider {
99
115
  expectedProvider: string,
100
116
  model: string | undefined,
101
117
  ) => Promise<Provider | null>,
118
+ private readonly defaultRouteAttribution?: ProviderRouteAttribution,
102
119
  ) {
103
120
  this.tokenEstimationProvider = defaultProvider.tokenEstimationProvider;
104
121
  this.supportsNativeWebSearch = defaultProvider.supportsNativeWebSearch;
@@ -112,11 +129,30 @@ export class CallSiteRoutingProvider implements Provider {
112
129
  messages: Message[],
113
130
  options?: SendMessageOptions,
114
131
  ): Promise<ProviderResponse> {
115
- const target = await this.selectProvider(options);
132
+ const selectedRoute = await this.selectProvider(options);
133
+ const target = selectedRoute.provider;
116
134
  const isRouted = target !== this.defaultProvider;
117
135
 
118
136
  const doSend = async (): Promise<ProviderResponse> => {
119
- const response = await target.sendMessage(messages, options);
137
+ let response: ProviderResponse;
138
+ try {
139
+ response = await target.sendMessage(messages, options);
140
+ } catch (error) {
141
+ if (error instanceof ProviderError) {
142
+ error.attachRouteAttribution({
143
+ ...(selectedRoute.connectionName
144
+ ? { connectionName: selectedRoute.connectionName }
145
+ : {}),
146
+ ...(selectedRoute.profileName
147
+ ? { profileName: selectedRoute.profileName }
148
+ : {}),
149
+ ...(selectedRoute.isManagedRoute !== undefined
150
+ ? { isManagedRoute: selectedRoute.isManagedRoute }
151
+ : {}),
152
+ });
153
+ }
154
+ throw error;
155
+ }
120
156
  // Also stamp actualProvider on the response so that handleUsage
121
157
  // (which reads event.actualProvider, not provider.name) attributes
122
158
  // the call to the right provider.
@@ -199,10 +235,10 @@ export class CallSiteRoutingProvider implements Provider {
199
235
  */
200
236
  private async selectProvider(
201
237
  options?: SendMessageOptions,
202
- ): Promise<Provider> {
238
+ ): Promise<SelectedProviderRoute> {
203
239
  const callSite = options?.config?.callSite;
204
240
  if (!callSite) {
205
- return this.defaultProvider;
241
+ return this.defaultRoute();
206
242
  }
207
243
 
208
244
  const overrideProfile = options?.config?.overrideProfile;
@@ -213,11 +249,15 @@ export class CallSiteRoutingProvider implements Provider {
213
249
  // request params.
214
250
  const forceOverrideProfile = options?.config?.forceOverrideProfile;
215
251
  const selectionSeed = options?.config?.selectionSeed;
216
- const resolved = resolveCallSiteConfig(callSite, getConfig().llm, {
217
- overrideProfile,
218
- forceOverrideProfile,
219
- selectionSeed,
220
- });
252
+ const { config: resolved, profileName } = resolveCallSiteConfigWithProfile(
253
+ callSite,
254
+ getConfig().llm,
255
+ {
256
+ overrideProfile,
257
+ forceOverrideProfile,
258
+ selectionSeed,
259
+ },
260
+ );
221
261
 
222
262
  let connectionName = resolved.provider_connection;
223
263
 
@@ -267,13 +307,27 @@ export class CallSiteRoutingProvider implements Provider {
267
307
  resolved.model,
268
308
  );
269
309
  if (connectionProvider) {
310
+ const actualRoute = {
311
+ connectionName:
312
+ connectionProvider.routeAttribution?.connectionName ??
313
+ connectionName,
314
+ isManagedRoute:
315
+ connectionProvider.routeAttribution?.isManagedRoute ??
316
+ isManagedConnectionRoute(connectionName),
317
+ };
270
318
  // The connection whose credential the call authenticates with is only
271
319
  // known here, and diagnostics for a failed request are unactionable
272
320
  // without it ("which key was this?"). Recorded once the adapter exists,
273
321
  // so a connection that fell back to the default transport is not
274
322
  // reported as the one that signed the request.
275
- recordProviderRequestDiagnostics({ connection_name: connectionName });
276
- return connectionProvider;
323
+ recordProviderRequestDiagnostics({
324
+ connection_name: actualRoute.connectionName,
325
+ });
326
+ return {
327
+ provider: connectionProvider,
328
+ ...actualRoute,
329
+ ...(profileName ? { profileName } : {}),
330
+ };
277
331
  }
278
332
  // Soft credential failure: the routed connection yielded no usable
279
333
  // adapter and dispatch is landing on the default transport, which may
@@ -289,11 +343,11 @@ export class CallSiteRoutingProvider implements Provider {
289
343
  },
290
344
  "Routed connection yielded no adapter — falling back to the default transport",
291
345
  );
292
- return this.defaultProvider;
346
+ return this.defaultRoute(profileName);
293
347
  }
294
348
 
295
349
  if (resolved.provider === this.defaultProvider.name) {
296
- return this.defaultProvider;
350
+ return this.defaultRoute(profileName);
297
351
  }
298
352
 
299
353
  if (autoResolveCandidates) {
@@ -317,6 +371,14 @@ export class CallSiteRoutingProvider implements Provider {
317
371
  `call-site "${callSite}" resolves to provider "${resolved.provider}" but no provider_connection is set — alternate-provider routing requires a connection`,
318
372
  );
319
373
  }
374
+
375
+ private defaultRoute(profileName?: string): SelectedProviderRoute {
376
+ return {
377
+ provider: this.defaultProvider,
378
+ ...this.defaultRouteAttribution,
379
+ ...(profileName ? { profileName } : {}),
380
+ };
381
+ }
320
382
  }
321
383
 
322
384
  /**
@@ -341,5 +403,6 @@ export function wrapWithCallSiteRouting(
341
403
  expectedProvider,
342
404
  model,
343
405
  ),
406
+ base.routeAttribution,
344
407
  );
345
408
  }
@@ -132,11 +132,12 @@ export async function tryResolveProviderForConnectionName(
132
132
  connectionName === VELLUM_MANAGED_CONNECTION_NAME &&
133
133
  !isVellumManagedConnection(connection)
134
134
  ) {
135
- return resolveThroughPlatform(
135
+ const provider = await resolveThroughPlatform(
136
136
  config,
137
137
  expectedProvider ?? declaredProvider,
138
138
  model,
139
139
  );
140
+ return attachProviderRoute(provider, canonicalVellumConnection());
140
141
  }
141
142
  // The provider-agnostic Vellum-managed connection carries only the `vellum`
142
143
  // sentinel, so the usual `connection.provider === expectedProvider` equality
@@ -221,10 +222,11 @@ export async function tryResolveProviderForConnectionName(
221
222
  // catch is specifically for in-flight failures that should not take
222
223
  // dispatch offline.
223
224
  try {
224
- return await resolveProviderFromConnection(connection, config, {
225
+ const provider = await resolveProviderFromConnection(connection, config, {
225
226
  model,
226
227
  providerOverride: isVellumRoute ? expectedProvider : undefined,
227
228
  });
229
+ return attachProviderRoute(provider, connection);
228
230
  } catch (err) {
229
231
  log.warn(
230
232
  { err, connectionName },
@@ -234,6 +236,44 @@ export async function tryResolveProviderForConnectionName(
234
236
  }
235
237
  }
236
238
 
239
+ function attachProviderRoute(
240
+ provider: Provider | null,
241
+ connection: { name: string; provider: string; auth: { type: string } },
242
+ ): Provider | null {
243
+ if (provider) {
244
+ provider.routeAttribution = {
245
+ connectionName: connection.name,
246
+ isManagedRoute: isVellumManagedConnection(connection),
247
+ };
248
+ }
249
+ return provider;
250
+ }
251
+
252
+ /**
253
+ * Whether a route through this connection name is Vellum-managed
254
+ * (platform-billed), for callers that hold only the name. Returns undefined
255
+ * when the row can't be read, so the caller can fall back rather than assert
256
+ * a BYOK route it never confirmed.
257
+ *
258
+ * The canonical name is always managed: a user-owned row claiming it is
259
+ * ignored and the route resolves through platform auth regardless (see
260
+ * `tryResolveProviderForConnectionName`).
261
+ */
262
+ export function isManagedConnectionRoute(
263
+ connectionName: string,
264
+ ): boolean | undefined {
265
+ if (connectionName === VELLUM_MANAGED_CONNECTION_NAME) {
266
+ return true;
267
+ }
268
+ let connection;
269
+ try {
270
+ connection = getConnection(getDb(), connectionName);
271
+ } catch {
272
+ return undefined;
273
+ }
274
+ return connection ? isVellumManagedConnection(connection) : undefined;
275
+ }
276
+
237
277
  /**
238
278
  * Resolve a managed route through platform auth without reading a connection
239
279
  * row. Used when the canonical `vellum` row is claimed by a user-owned