@vellumai/assistant 0.10.10-staging.1 → 0.10.10-staging.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,54 @@
1
+ export interface OAuthConnectSurfaceNextAction {
2
+ type: "ui_show";
3
+ surfaceType: "oauth_connect";
4
+ data: { providerKey: string };
5
+ }
6
+
7
+ export interface OAuthConnectSurfaceRedirect {
8
+ ok: false;
9
+ code: "use_oauth_connect_surface";
10
+ provider: string;
11
+ hint: string;
12
+ nextAction: OAuthConnectSurfaceNextAction;
13
+ }
14
+
15
+ export function oauthConnectSurfaceHint(provider: string): string {
16
+ return (
17
+ `To let the user connect, render the connect button: call ` +
18
+ `\`ui_show\` with surface_type "oauth_connect" and ` +
19
+ `data.providerKey "${provider}". That surface is always available — do ` +
20
+ `not run further \`oauth\`/\`channels\` commands, paste an OAuth URL, or ` +
21
+ `load a setup skill just to display it.`
22
+ );
23
+ }
24
+
25
+ export function buildOAuthConnectSurfaceNextAction(
26
+ provider: string,
27
+ ): OAuthConnectSurfaceNextAction {
28
+ return {
29
+ type: "ui_show",
30
+ surfaceType: "oauth_connect",
31
+ data: { providerKey: provider },
32
+ };
33
+ }
34
+
35
+ export function buildOAuthConnectSurfaceRedirect(
36
+ provider: string,
37
+ ): OAuthConnectSurfaceRedirect {
38
+ return {
39
+ ok: false,
40
+ code: "use_oauth_connect_surface",
41
+ provider,
42
+ hint: oauthConnectSurfaceHint(provider),
43
+ nextAction: buildOAuthConnectSurfaceNextAction(provider),
44
+ };
45
+ }
46
+
47
+ export function isModelSpawnedConversationShell(
48
+ env: NodeJS.ProcessEnv = process.env,
49
+ ): boolean {
50
+ return (
51
+ typeof env.__CONVERSATION_ID === "string" &&
52
+ env.__CONVERSATION_ID.trim().length > 0
53
+ );
54
+ }
@@ -0,0 +1,126 @@
1
+ import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
2
+
3
+ const ipcCalls: Array<{ method: string; params?: Record<string, unknown> }> =
4
+ [];
5
+ const openedUrls: string[] = [];
6
+
7
+ mock.module("../../../ipc/cli-client.js", () => ({
8
+ cliIpcCall: async (method: string, params?: Record<string, unknown>) => {
9
+ ipcCalls.push({ method, params });
10
+ if (method === "oauth_providers_by_providerKey_get") {
11
+ return {
12
+ ok: true,
13
+ result: {
14
+ provider: { authUrl: "https://accounts.example.com/oauth" },
15
+ },
16
+ };
17
+ }
18
+ if (method === "oauth_mode_get") {
19
+ return { ok: true, result: { ok: true, mode: "managed" } };
20
+ }
21
+ if (method === "oauth_managed_connect_start") {
22
+ return {
23
+ ok: true,
24
+ result: { ok: true, connect_url: "https://connect.example.com" },
25
+ };
26
+ }
27
+ return { ok: false, error: `Unexpected IPC method ${method}` };
28
+ },
29
+ exitFromIpcResult: (r: { error?: string }) => {
30
+ throw new Error(r.error ?? "IPC error");
31
+ },
32
+ }));
33
+
34
+ mock.module("../../lib/open-browser.js", () => ({
35
+ openInHostBrowser: (url: string) => {
36
+ openedUrls.push(url);
37
+ },
38
+ }));
39
+
40
+ mock.module("../../logger.js", () => ({
41
+ getCliLogger: () => ({
42
+ info: () => {},
43
+ warn: () => {},
44
+ error: () => {},
45
+ debug: () => {},
46
+ }),
47
+ }));
48
+
49
+ import { Command } from "commander";
50
+
51
+ import { applyCommandHelp } from "../../lib/cli-command-help.js";
52
+ import { registerConnectCommand } from "./connect.js";
53
+ import { oauthHelp } from "./index.help.js";
54
+
55
+ const originalConversationId = process.env.__CONVERSATION_ID;
56
+
57
+ beforeEach(() => {
58
+ ipcCalls.length = 0;
59
+ openedUrls.length = 0;
60
+ process.exitCode = 0;
61
+ process.env.__CONVERSATION_ID = "conv-123";
62
+ });
63
+
64
+ afterEach(() => {
65
+ if (originalConversationId === undefined) {
66
+ delete process.env.__CONVERSATION_ID;
67
+ } else {
68
+ process.env.__CONVERSATION_ID = originalConversationId;
69
+ }
70
+ process.exitCode = 0;
71
+ });
72
+
73
+ async function runConnectCommand(): Promise<{
74
+ stdout: string;
75
+ exitCode: number;
76
+ }> {
77
+ const chunks: string[] = [];
78
+ const originalWrite = process.stdout.write;
79
+ process.stdout.write = ((chunk: string | Buffer) => {
80
+ chunks.push(typeof chunk === "string" ? chunk : chunk.toString());
81
+ return true;
82
+ }) as typeof process.stdout.write;
83
+
84
+ try {
85
+ const program = new Command();
86
+ program.exitOverride();
87
+ const oauth = program.command("oauth").description(oauthHelp.description);
88
+ applyCommandHelp(oauth, oauthHelp);
89
+ registerConnectCommand(oauth);
90
+ await program.parseAsync([
91
+ "node",
92
+ "test",
93
+ "oauth",
94
+ "--json",
95
+ "connect",
96
+ "google",
97
+ ]);
98
+ } catch {
99
+ // Commander may throw under exitOverride for parse errors; the assertions
100
+ // below verify the command behavior we care about.
101
+ } finally {
102
+ process.stdout.write = originalWrite;
103
+ }
104
+
105
+ return { stdout: chunks.join(""), exitCode: Number(process.exitCode ?? 0) };
106
+ }
107
+
108
+ describe("oauth connect", () => {
109
+ test("managed provider in a conversation shell returns oauth_connect guidance without opening a browser", async () => {
110
+ const { stdout, exitCode } = await runConnectCommand();
111
+
112
+ expect(exitCode).toBe(1);
113
+ const parsed = JSON.parse(stdout) as Record<string, unknown>;
114
+ expect(parsed.code).toBe("use_oauth_connect_surface");
115
+ expect(parsed.nextAction).toEqual({
116
+ type: "ui_show",
117
+ surfaceType: "oauth_connect",
118
+ data: { providerKey: "google" },
119
+ });
120
+ expect(openedUrls).toEqual([]);
121
+ expect(ipcCalls.map((call) => call.method)).toEqual([
122
+ "oauth_providers_by_providerKey_get",
123
+ "oauth_mode_get",
124
+ ]);
125
+ });
126
+ });
@@ -5,6 +5,10 @@ import { subcommand } from "../../lib/cli-command-help.js";
5
5
  import { openInHostBrowser } from "../../lib/open-browser.js";
6
6
  import { getCliLogger } from "../../logger.js";
7
7
  import { shouldOutputJson, writeOutput } from "../../output.js";
8
+ import {
9
+ buildOAuthConnectSurfaceRedirect,
10
+ isModelSpawnedConversationShell,
11
+ } from "./connect-surface-guidance.js";
8
12
 
9
13
  const log = getCliLogger("cli");
10
14
 
@@ -125,7 +129,9 @@ export function registerConnectCommand(oauth: Command): void {
125
129
  queryParams: { provider },
126
130
  });
127
131
 
128
- if (!modeResult.ok) return exitFromIpcResult(modeResult);
132
+ if (!modeResult.ok) {
133
+ return exitFromIpcResult(modeResult);
134
+ }
129
135
 
130
136
  const managed = modeResult.result?.mode === "managed";
131
137
 
@@ -134,6 +140,13 @@ export function registerConnectCommand(oauth: Command): void {
134
140
  // MANAGED PATH
135
141
  // =============================================================
136
142
 
143
+ if (isModelSpawnedConversationShell()) {
144
+ const redirect = buildOAuthConnectSurfaceRedirect(provider);
145
+ writeOutput(cmd, redirect);
146
+ process.exitCode = 1;
147
+ return;
148
+ }
149
+
137
150
  if (opts.clientId) {
138
151
  log.info(
139
152
  `Warning: --client-id is ignored for platform-managed providers. The platform manages OAuth apps for "${provider}".`,
@@ -152,7 +165,9 @@ export function registerConnectCommand(oauth: Command): void {
152
165
  body: startBody,
153
166
  });
154
167
 
155
- if (!startResult.ok) return exitFromIpcResult(startResult);
168
+ if (!startResult.ok) {
169
+ return exitFromIpcResult(startResult);
170
+ }
156
171
 
157
172
  const connectUrl = startResult.result!.connect_url;
158
173
 
@@ -169,7 +184,9 @@ export function registerConnectCommand(oauth: Command): void {
169
184
  queryParams: { provider },
170
185
  });
171
186
 
172
- if (!snapshotResult.ok) return exitFromIpcResult(snapshotResult);
187
+ if (!snapshotResult.ok) {
188
+ return exitFromIpcResult(snapshotResult);
189
+ }
173
190
 
174
191
  const snapshotIds = new Set(
175
192
  (snapshotResult.result?.connections ?? []).map((e) => e.id),
@@ -207,7 +224,9 @@ export function registerConnectCommand(oauth: Command): void {
207
224
  queryParams: { provider },
208
225
  });
209
226
 
210
- if (!currentResult.ok || !currentResult.result) continue;
227
+ if (!currentResult.ok || !currentResult.result) {
228
+ continue;
229
+ }
211
230
 
212
231
  const found = currentResult.result.connections.find(
213
232
  (e) => !snapshotIds.has(e.id),
@@ -282,8 +301,12 @@ export function registerConnectCommand(oauth: Command): void {
282
301
  service: provider,
283
302
  callbackTransport: opts.callbackTransport,
284
303
  };
285
- if (opts.clientId) startBody.clientId = opts.clientId;
286
- if (opts.scopes) startBody.requestedScopes = opts.scopes;
304
+ if (opts.clientId) {
305
+ startBody.clientId = opts.clientId;
306
+ }
307
+ if (opts.scopes) {
308
+ startBody.requestedScopes = opts.scopes;
309
+ }
287
310
 
288
311
  const startResult = await cliIpcCall<{
289
312
  auth_url: string;
@@ -655,7 +655,7 @@ Examples:
655
655
  name: "connect",
656
656
  args: "<provider>",
657
657
  description:
658
- "Initiate an OAuth authorization flow for a specified provider",
658
+ "Initiate a terminal/headless OAuth authorization flow for a specified provider",
659
659
  options: [
660
660
  {
661
661
  flags: "--scopes <scopes...>",
@@ -687,6 +687,12 @@ By default, the browser opens automatically and the command waits for
687
687
  completion. Use --no-browser to print the URL instead (useful for headless
688
688
  or SSH sessions).
689
689
 
690
+ Important for chat/UI turns: do not run this command just to let the user
691
+ connect a managed provider. Render the first-class connect surface instead:
692
+ call \`ui_show\` with surface_type "oauth_connect" and data.providerKey set to
693
+ the provider (for example, "google"). That surface starts the managed OAuth UI
694
+ and avoids pasting raw authorization links into the conversation.
695
+
690
696
  Examples:
691
697
  $ assistant oauth connect google
692
698
  $ assistant oauth connect google --no-browser
@@ -1,12 +1,16 @@
1
1
  import { afterEach, describe, expect, test } from "bun:test";
2
2
 
3
- import { noConnectionsMessage } from "./status.js";
3
+ import { oauthHelp } from "./index.help.js";
4
+ import { decorateStatusJsonForModel, noConnectionsMessage } from "./status.js";
4
5
 
5
6
  const original = process.env.__RESOLVED_MODEL;
6
7
 
7
8
  afterEach(() => {
8
- if (original === undefined) delete process.env.__RESOLVED_MODEL;
9
- else process.env.__RESOLVED_MODEL = original;
9
+ if (original === undefined) {
10
+ delete process.env.__RESOLVED_MODEL;
11
+ } else {
12
+ process.env.__RESOLVED_MODEL = original;
13
+ }
10
14
  });
11
15
 
12
16
  describe("noConnectionsMessage", () => {
@@ -31,6 +35,68 @@ describe("noConnectionsMessage", () => {
31
35
  const msg = await noConnectionsMessage("google");
32
36
  expect(msg).toContain('surface_type "oauth_connect"');
33
37
  expect(msg).toContain('data.providerKey "google"');
38
+ expect(msg).toContain("paste an OAuth URL");
34
39
  expect(msg).not.toContain("assistant oauth connect google");
35
40
  });
41
+
42
+ test("weak open models are not steered to oauth_connect for BYO mode", async () => {
43
+ process.env.__RESOLVED_MODEL = "accounts/fireworks/models/minimax-m3";
44
+ const msg = await noConnectionsMessage("google", "byo");
45
+ expect(msg).not.toContain('surface_type "oauth_connect"');
46
+ expect(msg).toContain("assistant oauth connect google");
47
+ });
48
+
49
+ test("weak open model JSON status includes oauth_connect next action", async () => {
50
+ process.env.__RESOLVED_MODEL = "accounts/fireworks/models/glm-5p2";
51
+ const result = await decorateStatusJsonForModel({
52
+ ok: true,
53
+ provider: "google",
54
+ mode: "managed",
55
+ connections: [],
56
+ });
57
+ expect(result.hint).toContain('surface_type "oauth_connect"');
58
+ expect(result.hint).toContain("paste an OAuth URL");
59
+ expect(result.nextAction).toEqual({
60
+ type: "ui_show",
61
+ surfaceType: "oauth_connect",
62
+ data: { providerKey: "google" },
63
+ });
64
+ });
65
+
66
+ test("weak open model JSON status stays compact for BYO mode", async () => {
67
+ process.env.__RESOLVED_MODEL = "accounts/fireworks/models/glm-5p2";
68
+ const result = await decorateStatusJsonForModel({
69
+ ok: true,
70
+ provider: "google",
71
+ mode: "byo",
72
+ connections: [],
73
+ });
74
+ expect(result.hint).toBeUndefined();
75
+ expect(result.nextAction).toBeUndefined();
76
+ });
77
+
78
+ test("capable model JSON status stays compact", async () => {
79
+ process.env.__RESOLVED_MODEL = "claude-opus-4-8";
80
+ const result = await decorateStatusJsonForModel({
81
+ ok: true,
82
+ provider: "google",
83
+ mode: "managed",
84
+ connections: [],
85
+ });
86
+ expect(result.hint).toBeUndefined();
87
+ expect(result.nextAction).toBeUndefined();
88
+ });
89
+ });
90
+
91
+ describe("oauth connect help", () => {
92
+ test("steers chat turns to the oauth_connect surface", () => {
93
+ const connectHelp = oauthHelp.subcommands?.find(
94
+ (command) => command.name === "connect",
95
+ );
96
+ expect(connectHelp?.description).toContain("terminal/headless");
97
+ expect(connectHelp?.helpText).toContain('surface_type "oauth_connect"');
98
+ expect(connectHelp?.helpText).toContain(
99
+ "avoids pasting raw authorization links",
100
+ );
101
+ });
36
102
  });
@@ -3,6 +3,11 @@ import type { Command } from "commander";
3
3
  import { cliIpcCall, exitFromIpcResult } from "../../../ipc/cli-client.js";
4
4
  import { subcommand } from "../../lib/cli-command-help.js";
5
5
  import { shouldOutputJson, writeOutput } from "../../output.js";
6
+ import {
7
+ buildOAuthConnectSurfaceNextAction,
8
+ oauthConnectSurfaceHint,
9
+ type OAuthConnectSurfaceNextAction,
10
+ } from "./connect-surface-guidance.js";
6
11
 
7
12
  /**
8
13
  * Message shown when a provider has no active connections. Weak open models
@@ -11,18 +16,15 @@ import { shouldOutputJson, writeOutput } from "../../output.js";
11
16
  * they get an explicit single next action: render the core `oauth_connect`
12
17
  * surface directly. Capable models keep the terse default.
13
18
  */
14
- export async function noConnectionsMessage(provider: string): Promise<string> {
19
+ export async function noConnectionsMessage(
20
+ provider: string,
21
+ mode = "managed",
22
+ ): Promise<string> {
15
23
  const base = `No active connections for ${provider}.`;
16
24
  const { isWeakOpenModel } =
17
25
  await import("../../../providers/weak-open-model.js");
18
- if (isWeakOpenModel(process.env.__RESOLVED_MODEL)) {
19
- return (
20
- `${base}\nTo let the user connect, render the connect button: call ` +
21
- `\`ui_show\` with surface_type "oauth_connect" and ` +
22
- `data.providerKey "${provider}". That surface is always available — do ` +
23
- `not run further \`oauth\`/\`channels\` commands or load a setup skill ` +
24
- `just to display it.\n`
25
- );
26
+ if (mode === "managed" && isWeakOpenModel(process.env.__RESOLVED_MODEL)) {
27
+ return `${base}\n${oauthConnectSurfaceHint(provider)}\n`;
26
28
  }
27
29
  return `${base}\nConnect with \`assistant oauth connect ${provider}\`.\n`;
28
30
  }
@@ -40,6 +42,42 @@ interface ConnectionSummary {
40
42
  hasRefreshToken?: boolean;
41
43
  }
42
44
 
45
+ interface OAuthStatusResponse {
46
+ ok: boolean;
47
+ provider: string;
48
+ mode: string;
49
+ connections: ConnectionSummary[];
50
+ hint?: string;
51
+ nextAction?: OAuthConnectSurfaceNextAction;
52
+ }
53
+
54
+ /**
55
+ * JSON status output is often fed back to the model. For weak open models,
56
+ * include the same next-action steering as the human text path so a follow-up
57
+ * "yes" renders the first-class OAuth surface instead of a raw CLI URL.
58
+ */
59
+ export async function decorateStatusJsonForModel(
60
+ result: OAuthStatusResponse,
61
+ ): Promise<OAuthStatusResponse> {
62
+ if (result.connections.length > 0) {
63
+ return result;
64
+ }
65
+ if (result.mode !== "managed") {
66
+ return result;
67
+ }
68
+ const { isWeakOpenModel } =
69
+ await import("../../../providers/weak-open-model.js");
70
+ if (!isWeakOpenModel(process.env.__RESOLVED_MODEL)) {
71
+ return result;
72
+ }
73
+ return {
74
+ ...result,
75
+ hint: result.hint ?? oauthConnectSurfaceHint(result.provider),
76
+ nextAction:
77
+ result.nextAction ?? buildOAuthConnectSurfaceNextAction(result.provider),
78
+ };
79
+ }
80
+
43
81
  // ---------------------------------------------------------------------------
44
82
  // Text formatting helpers
45
83
  // ---------------------------------------------------------------------------
@@ -86,17 +124,17 @@ export function registerStatusCommand(oauth: Command): void {
86
124
  return exitFromIpcResult(r);
87
125
  }
88
126
 
89
- const result = r.result!;
127
+ const result = r.result! as OAuthStatusResponse;
90
128
  const { connections, mode } = result;
91
129
 
92
130
  if (shouldOutputJson(cmd)) {
93
- writeOutput(cmd, result);
131
+ writeOutput(cmd, await decorateStatusJsonForModel(result));
94
132
  return;
95
133
  }
96
134
 
97
135
  // Text output
98
136
  if (connections.length === 0) {
99
- process.stdout.write(await noConnectionsMessage(provider));
137
+ process.stdout.write(await noConnectionsMessage(provider, mode));
100
138
  return;
101
139
  }
102
140
 
@@ -181,11 +181,16 @@ export class CallSiteRoutingProvider implements Provider {
181
181
  * Soft credential failures fall back to the default Provider so
182
182
  * a transient credential blip does not take a conversation
183
183
  * offline.
184
- * 3. Resolved profile's `provider` matches the default's name → reuse
185
- * the default provider instance (no connection-aware lookup
186
- * needed; the default IS the connection-aware route).
187
- * 4. Resolved profile's `provider` differs from the default but no
188
- * `provider_connection` is set → throw. This is a configuration
184
+ * 3. No `provider_connection` → auto-resolve a connection for the
185
+ * resolved provider and route through it. This runs even when the
186
+ * provider matches the default's name: the default transport may
187
+ * ride the managed (platform-billed) connection while the profile's
188
+ * intent is the user's own key, so a bare name match must not stand
189
+ * in for connection resolution.
190
+ * 4. No connection exists for the provider and it matches the
191
+ * default's name → reuse the default provider instance.
192
+ * 5. Resolved profile's `provider` differs from the default but no
193
+ * connection could be resolved → throw. This is a configuration
189
194
  * bug: alternate-provider routing requires a connection.
190
195
  */
191
196
  private async selectProvider(
@@ -212,14 +217,18 @@ export class CallSiteRoutingProvider implements Provider {
212
217
 
213
218
  let connectionName = resolved.provider_connection;
214
219
 
215
- // When no connection is set and the provider differs from the default,
216
- // auto-resolve a connection for the provider (handles the case where the
217
- // profile set provider but not provider_connection, and the merge didn't
218
- // inherit one).
220
+ // When no connection is set, auto-resolve one for the resolved provider —
221
+ // including when the provider matches the default's name. The default
222
+ // transport may ride the managed (platform-billed) connection, so reusing
223
+ // it on a bare name match would silently bill managed credits for a
224
+ // profile whose intent is the user's own key. Mirrors
225
+ // `resolveConfiguredProvider`, which never takes a name shortcut; when no
226
+ // connection exists for the provider, the same-name fallthrough below
227
+ // still reuses the default transport.
219
228
  let autoResolveCandidates:
220
229
  | import("./inference/auth.js").ProviderConnection[]
221
230
  | undefined;
222
- if (!connectionName && resolved.provider !== this.defaultProvider.name) {
231
+ if (!connectionName) {
223
232
  try {
224
233
  autoResolveCandidates = listConnections(getDb(), {
225
234
  provider: resolved.provider,
@@ -17,15 +17,18 @@
17
17
  * default profile and on any legacy bare-`provider` callsite override.
18
18
  */
19
19
 
20
+ import { MANAGED_PROFILE_NAMES } from "../../config/default-profile-catalog.js";
20
21
  import { loadRawConfig, saveRawConfig } from "../../config/loader.js";
21
22
  import type { DrizzleDb } from "../../persistence/db-connection.js";
22
23
  import { credentialKey } from "../../security/credential-key.js";
23
24
  import { getLogger } from "../../util/logger.js";
25
+ import { isConnectionCompatibleWithModel } from "../connection-model-compat.js";
24
26
  import { MANAGED_ROUTABLE_PROVIDERS } from "../vellum-model-routing.js";
25
27
  import { PROVIDERS_REQUIRING_BASE_URL_AND_MODELS } from "./auth.js";
26
28
  import {
27
29
  createConnection,
28
30
  getConnection,
31
+ listConnections,
29
32
  seedCanonicalConnections,
30
33
  VELLUM_MANAGED_CONNECTION_NAME,
31
34
  } from "./connections.js";
@@ -183,7 +186,39 @@ function ensureProviderConnection(
183
186
 
184
187
  let connectionName: string;
185
188
 
186
- if (globalMode === "managed" && MANAGED_ROUTABLE_PROVIDERS.has(provider)) {
189
+ // For user-owned entries, an existing connection for the entry's provider
190
+ // wins over the mode-derived default. Only user-brought connections can
191
+ // match — the canonical `vellum` row carries the `vellum` sentinel
192
+ // provider, never a concrete upstream. Without this, the managed branch
193
+ // would silently switch a connection-less BYOK-intent profile onto the
194
+ // billed managed connection, and the your-own branch would create a
195
+ // parallel `-personal` row (pointing at an empty credential slot) when a
196
+ // custom-named connection already exists.
197
+ //
198
+ // Managed-owned entries are excluded: a managed preset must stay on the
199
+ // platform-managed route, not start dispatching against a key the user
200
+ // brought for their own profiles. Managed-owned means `source: "managed"`
201
+ // or a canonical managed name without an explicit `source: "user"` —
202
+ // legacy seeders wrote canonical entries source-less, and only an explicit
203
+ // user source marks a shadow the user took ownership of (mirrors
204
+ // workspace migration 109). `entryLabel` is the profile name for the
205
+ // `llm.profiles.*` walk; the other walks pass bracketed labels that never
206
+ // collide with canonical names.
207
+ const isManagedOwned =
208
+ entry.source === "managed" ||
209
+ (entry.source !== "user" && MANAGED_PROFILE_NAMES.has(entryLabel));
210
+ const entryModel = typeof entry.model === "string" ? entry.model : undefined;
211
+ const existingForProvider = isManagedOwned
212
+ ? undefined
213
+ : listConnections(db, { provider }).find((c) =>
214
+ isConnectionCompatibleWithModel(c, entryModel),
215
+ );
216
+ if (existingForProvider) {
217
+ connectionName = existingForProvider.name;
218
+ } else if (
219
+ globalMode === "managed" &&
220
+ MANAGED_ROUTABLE_PROVIDERS.has(provider)
221
+ ) {
187
222
  // All managed-routable providers share the single provider-agnostic
188
223
  // `vellum` connection; the upstream is recovered per-request from the
189
224
  // profile's `provider` field.
@@ -1399,6 +1399,88 @@ describe("custom profile write normalization (complete overrides)", () => {
1399
1399
  });
1400
1400
  });
1401
1401
 
1402
+ describe("call-site override tuning backfill", () => {
1403
+ const configPatchRoute = ROUTES.find(
1404
+ (r) => r.operationId === "config_patch",
1405
+ )!;
1406
+
1407
+ const savedCallSites = () =>
1408
+ (
1409
+ loadRawConfig().llm as {
1410
+ callSites?: Record<string, Record<string, unknown>>;
1411
+ }
1412
+ ).callSites ?? {};
1413
+
1414
+ beforeEach(() => {
1415
+ rawConfigFixture = { llm: {} };
1416
+ seedRawConfig();
1417
+ });
1418
+
1419
+ test("PATCH creating a bare { profile } entry backfills shipped tuning", async () => {
1420
+ await configPatchRoute.handler({
1421
+ body: {
1422
+ llm: {
1423
+ callSites: {
1424
+ memoryRouter: { profile: "mine", provider: null, model: null },
1425
+ commitMessage: { profile: "mine", provider: null, model: null },
1426
+ },
1427
+ },
1428
+ },
1429
+ });
1430
+ const memoryRouter = savedCallSites().memoryRouter!;
1431
+ expect(memoryRouter.profile).toBe("mine");
1432
+ expect(memoryRouter.contextWindow).toEqual({ maxInputTokens: 1_000_000 });
1433
+ const commitMessage = savedCallSites().commitMessage!;
1434
+ expect(commitMessage.profile).toBe("mine");
1435
+ expect(commitMessage.maxTokens).toBe(120);
1436
+ expect(commitMessage.effort).toBe("low");
1437
+ });
1438
+
1439
+ test("explicit patch values win over shipped tuning on a new entry", async () => {
1440
+ await configPatchRoute.handler({
1441
+ body: {
1442
+ llm: {
1443
+ callSites: { commitMessage: { profile: "mine", maxTokens: 500 } },
1444
+ },
1445
+ },
1446
+ });
1447
+ const saved = savedCallSites().commitMessage!;
1448
+ expect(saved.maxTokens).toBe(500);
1449
+ expect(saved.temperature).toBe(0.2);
1450
+ });
1451
+
1452
+ test("existing entries are never backfilled — customization is preserved", async () => {
1453
+ rawConfigFixture = {
1454
+ llm: { callSites: { recall: { profile: "old", maxTokens: 200 } } },
1455
+ };
1456
+ seedRawConfig();
1457
+ await configPatchRoute.handler({
1458
+ body: {
1459
+ llm: {
1460
+ callSites: {
1461
+ recall: { profile: "mine", provider: null, model: null },
1462
+ },
1463
+ },
1464
+ },
1465
+ });
1466
+ const saved = savedCallSites().recall!;
1467
+ expect(saved.profile).toBe("mine");
1468
+ expect(saved.maxTokens).toBe(200);
1469
+ expect(saved.disableCache).toBeUndefined();
1470
+ });
1471
+
1472
+ test("deleting an entry (null) is untouched by the backfill", async () => {
1473
+ rawConfigFixture = {
1474
+ llm: { callSites: { recall: { profile: "old" } } },
1475
+ };
1476
+ seedRawConfig();
1477
+ await configPatchRoute.handler({
1478
+ body: { llm: { callSites: { recall: null } } },
1479
+ });
1480
+ expect(savedCallSites().recall).toBeUndefined();
1481
+ });
1482
+ });
1483
+
1402
1484
  describe("config invariant flag enrichment", () => {
1403
1485
  const configGetRoute = ROUTES.find((r) => r.operationId === "config_get")!;
1404
1486
  const configPatchRoute = ROUTES.find(