@vellumai/assistant 0.10.7-dev.202607100313.fffdfea → 0.10.7-dev.202607100720.fba456e

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 (99) hide show
  1. package/openapi.yaml +846 -27
  2. package/package.json +1 -1
  3. package/src/__tests__/config-watcher-skill-reseed.test.ts +1 -0
  4. package/src/__tests__/config-watcher.test.ts +22 -4
  5. package/src/__tests__/credential-security-invariants.test.ts +1 -1
  6. package/src/__tests__/plugin-import-boundary-guard.test.ts +6 -9
  7. package/src/__tests__/plugin-import-boundary-reverse-guard.test.ts +0 -2
  8. package/src/cli/commands/__tests__/inference-models.test.ts +86 -0
  9. package/src/cli/commands/__tests__/inference-profiles.test.ts +254 -0
  10. package/src/cli/commands/__tests__/inference-providers.test.ts +171 -0
  11. package/src/cli/commands/__tests__/schedules.test.ts +133 -1
  12. package/src/cli/commands/__tests__/usage.test.ts +131 -0
  13. package/src/cli/commands/inference-callsites.ts +158 -0
  14. package/src/cli/commands/inference-models.ts +84 -0
  15. package/src/cli/commands/inference-profiles.ts +371 -0
  16. package/src/cli/commands/inference-providers-default.ts +89 -0
  17. package/src/cli/commands/inference-providers.ts +87 -16
  18. package/src/cli/commands/inference.ts +6 -0
  19. package/src/cli/commands/memory/nodes.ts +90 -50
  20. package/src/cli/commands/schedules.ts +17 -2
  21. package/src/cli/commands/usage.ts +59 -21
  22. package/src/cli/lib/__tests__/cli-output.test.ts +20 -0
  23. package/src/cli/lib/cli-output.ts +55 -0
  24. package/src/config/__tests__/loader-last-known-good.test.ts +229 -0
  25. package/src/config/__tests__/loader-sparse-array-cleanup.test.ts +166 -0
  26. package/src/config/default-profile-catalog.ts +28 -0
  27. package/src/config/loader.ts +276 -46
  28. package/src/daemon/config-watcher.ts +65 -20
  29. package/src/daemon/message-types/sync.ts +1 -0
  30. package/src/oauth/byo-connection.test.ts +1 -1
  31. package/src/oauth/connection-resolver.test.ts +140 -0
  32. package/src/oauth/connection-resolver.ts +48 -12
  33. package/src/plugins/defaults/memory/anisotropy.ts +1 -1
  34. package/src/plugins/defaults/memory/config.ts +1 -1
  35. package/src/plugins/defaults/memory/context-search/agent-protocol.ts +1 -1
  36. package/src/plugins/defaults/memory/context-search/search.ts +1 -1
  37. package/src/plugins/defaults/memory/graph/bootstrap.ts +1 -1
  38. package/src/plugins/defaults/memory/graph/consolidation.ts +1 -1
  39. package/src/plugins/defaults/memory/graph/conversation-graph-memory.ts +11 -1
  40. package/src/plugins/defaults/memory/graph/extraction.ts +1 -1
  41. package/src/plugins/defaults/memory/graph/narrative.ts +1 -1
  42. package/src/plugins/defaults/memory/graph/pattern-scan.ts +1 -1
  43. package/src/plugins/defaults/memory/graph/tool-handlers.ts +1 -1
  44. package/src/plugins/defaults/memory/graph/tools.ts +1 -1
  45. package/src/plugins/defaults/memory/graph-topology/build-memory-graph.ts +43 -16
  46. package/src/plugins/defaults/memory/hooks/user-prompt-submit.ts +1 -1
  47. package/src/plugins/defaults/memory/host-utils.ts +80 -0
  48. package/src/plugins/defaults/memory/identity-context.ts +1 -1
  49. package/src/plugins/defaults/memory/injectors.ts +1 -1
  50. package/src/plugins/defaults/memory/jobs/embed-concept-page.ts +2 -2
  51. package/src/plugins/defaults/memory/jobs-worker.ts +2 -9
  52. package/src/plugins/defaults/memory/memory-retrospective-state.ts +1 -1
  53. package/src/plugins/defaults/memory/paths.ts +48 -0
  54. package/src/plugins/defaults/memory/pkb/autoinject.ts +1 -1
  55. package/src/plugins/defaults/memory/pkb/context.ts +2 -2
  56. package/src/plugins/defaults/memory/pkb/types.ts +1 -1
  57. package/src/plugins/defaults/memory/pkb-schedule.ts +2 -2
  58. package/src/plugins/defaults/memory/rerank-local.ts +2 -3
  59. package/src/plugins/defaults/memory/routes/memory-eval-routes.ts +1 -1
  60. package/src/plugins/defaults/memory/routes/memory-item-routes.test.ts +149 -1
  61. package/src/plugins/defaults/memory/routes/memory-item-routes.ts +144 -1
  62. package/src/plugins/defaults/memory/routes/memory-v2-routes.ts +1 -1
  63. package/src/plugins/defaults/memory/startup.ts +1 -1
  64. package/src/plugins/defaults/memory/v2/backfill-jobs.ts +1 -1
  65. package/src/plugins/defaults/memory/v2/consolidation-job.ts +2 -2
  66. package/src/plugins/defaults/memory/v2/injection.ts +1 -1
  67. package/src/plugins/defaults/memory/v2/memory-v2-startup.ts +1 -1
  68. package/src/plugins/defaults/memory/v2/prompts/consolidation.ts +1 -1
  69. package/src/plugins/defaults/memory/v2/qdrant.ts +1 -1
  70. package/src/plugins/defaults/memory/v2/reranker.ts +1 -1
  71. package/src/plugins/defaults/memory/v2/static-context.ts +1 -1
  72. package/src/plugins/defaults/memory/v2/sweep-job.ts +1 -1
  73. package/src/plugins/defaults/memory/v3/candidate-match.ts +1 -1
  74. package/src/plugins/defaults/memory/v3/maintain-job.ts +1 -1
  75. package/src/plugins/defaults/memory/v3/page-content.ts +1 -1
  76. package/src/plugins/defaults/memory/v3/pool-select.ts +1 -2
  77. package/src/plugins/defaults/memory/v3/selection-log-store.ts +1 -1
  78. package/src/plugins/defaults/memory/v3/shadow-plugin.ts +2 -5
  79. package/src/plugins/defaults/memory/worker.ts +1 -1
  80. package/src/plugins/defaults/workspace/injectors.ts +17 -15
  81. package/src/plugins/types.ts +9 -14
  82. package/src/providers/inference/connection-availability.ts +193 -0
  83. package/src/runtime/routes/__tests__/inference-callsites-routes.test.ts +54 -0
  84. package/src/runtime/routes/__tests__/inference-models-routes.test.ts +54 -0
  85. package/src/runtime/routes/__tests__/inference-profiles-routes.test.ts +405 -0
  86. package/src/runtime/routes/__tests__/inference-routes-registration.test.ts +42 -0
  87. package/src/runtime/routes/__tests__/theme-routes.test.ts +66 -0
  88. package/src/runtime/routes/conversation-query-routes.ts +5 -3
  89. package/src/runtime/routes/default-provider-routes.ts +5 -152
  90. package/src/runtime/routes/index.ts +8 -0
  91. package/src/runtime/routes/inference-callsites-routes.ts +211 -0
  92. package/src/runtime/routes/inference-models-routes.ts +104 -0
  93. package/src/runtime/routes/inference-profiles-routes.ts +717 -0
  94. package/src/runtime/routes/theme-routes.ts +36 -0
  95. package/src/runtime/sync/resource-sync-events.ts +4 -0
  96. package/src/theme/workspace-theme.test.ts +269 -0
  97. package/src/theme/workspace-theme.ts +304 -0
  98. package/src/watcher/__tests__/engine-auth-notify.test.ts +316 -0
  99. package/src/watcher/engine.ts +87 -2
@@ -0,0 +1,717 @@
1
+ /**
2
+ * Route definitions for inference-profile CRUD with write-time validation.
3
+ *
4
+ * GET /v1/inference/profiles — effective profile catalog (managed defaults + user profiles)
5
+ * GET /v1/inference/profiles/:name — single effective profile
6
+ * POST /v1/inference/profiles — create a validated custom profile
7
+ * PATCH /v1/inference/profiles/:name — partial update of a custom profile
8
+ * DELETE /v1/inference/profiles/:name — delete a custom profile (managed defaults are protected)
9
+ *
10
+ * Unlike the generic `config set llm.profiles.<name> '<json>'` path, these
11
+ * routes validate at write time: the provider must be a known `LLMProvider`,
12
+ * the model must be in the catalog (unless `allowUnlisted`), and a referenced
13
+ * connection must exist. Writes reuse the shared config-write plumbing
14
+ * (`commitConfigWrite` + the managed-profile guards), so a CLI-created profile
15
+ * is completed/materialized identically to a UI-created one.
16
+ */
17
+
18
+ import { z } from "zod";
19
+
20
+ import {
21
+ getEffectiveProfile,
22
+ getEffectiveProfilesForProvider,
23
+ MANAGED_PROFILE_NAMES,
24
+ resolveDefaultProfileForProvider,
25
+ } from "../../config/default-profile-catalog.js";
26
+ import {
27
+ getConfig,
28
+ getConfigReadOnly,
29
+ loadRawConfig,
30
+ } from "../../config/loader.js";
31
+ import { LLMProvider, ProfileEntry } from "../../config/schemas/llm.js";
32
+ import { getDb } from "../../persistence/db-connection.js";
33
+ import { computeConnectionAvailability } from "../../providers/inference/connection-availability.js";
34
+ import { getConnection } from "../../providers/inference/connections.js";
35
+ import { isModelInCatalog } from "../../providers/model-catalog.js";
36
+ import { ACTOR_PRINCIPALS } from "../auth/route-policy.js";
37
+ import {
38
+ commitConfigWrite,
39
+ normalizeManagedProfileWrites,
40
+ rejectManagedProfileDeletion,
41
+ } from "./conversation-query-routes.js";
42
+ import { BadRequestError, ConflictError, NotFoundError } from "./errors.js";
43
+ import type { RouteDefinition, RouteHandlerArgs } from "./types.js";
44
+
45
+ // Prototype-pollution guards — a profile name may never be one of these.
46
+ const RESERVED_PROFILE_NAMES = new Set([
47
+ "__proto__",
48
+ "constructor",
49
+ "prototype",
50
+ ]);
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Wire schemas
54
+ // ---------------------------------------------------------------------------
55
+
56
+ const availabilitySchema = z
57
+ .object({
58
+ status: z.enum([
59
+ "ok",
60
+ "missing_connection",
61
+ "missing_credential",
62
+ "provider_mismatch",
63
+ "unsupported_auth",
64
+ "vellum_unauthenticated",
65
+ "unknown",
66
+ ]),
67
+ message: z.string().optional(),
68
+ })
69
+ .meta({ id: "ProfileConnectionAvailability" });
70
+
71
+ const profileSummarySchema = z
72
+ .object({
73
+ name: z.string(),
74
+ label: z.string().nullable(),
75
+ provider: z.string().nullable(),
76
+ model: z.string().nullable(),
77
+ status: z.enum(["active", "disabled"]),
78
+ source: z.enum(["managed", "user"]),
79
+ provider_connection: z.string().optional(),
80
+ /** Null when the profile has no connection to judge (e.g. mix profiles). */
81
+ availability: availabilitySchema.nullable(),
82
+ })
83
+ .meta({ id: "InferenceProfileSummary" });
84
+
85
+ const profileDetailSchema = z
86
+ .object({
87
+ name: z.string(),
88
+ entry: z.record(z.string(), z.unknown()),
89
+ availability: availabilitySchema.nullable(),
90
+ })
91
+ .meta({ id: "InferenceProfileDetail" });
92
+
93
+ const profileWriteResultSchema = z
94
+ .object({
95
+ ok: z.literal(true),
96
+ name: z.string(),
97
+ entry: z.record(z.string(), z.unknown()),
98
+ warnings: z.array(z.string()),
99
+ })
100
+ .meta({ id: "InferenceProfileWriteResult" });
101
+
102
+ const createRequestSchema = z.object({
103
+ name: z.string().min(1),
104
+ provider: z.string().min(1),
105
+ model: z.string().min(1),
106
+ connection: z.string().min(1).optional(),
107
+ label: z.string().min(1).optional(),
108
+ effort: z.string().optional(),
109
+ maxTokens: z.number().int().positive().optional(),
110
+ temperature: z.number().optional(),
111
+ thinking: z.boolean().optional(),
112
+ description: z.string().optional(),
113
+ allowUnlisted: z.boolean().optional(),
114
+ });
115
+
116
+ const updateRequestSchema = z.object({
117
+ provider: z.string().min(1).optional(),
118
+ model: z.string().min(1).optional(),
119
+ connection: z.string().min(1).optional(),
120
+ label: z.string().min(1).optional(),
121
+ effort: z.string().optional(),
122
+ maxTokens: z.number().int().positive().optional(),
123
+ temperature: z.number().optional(),
124
+ thinking: z.boolean().optional(),
125
+ description: z.string().optional(),
126
+ allowUnlisted: z.boolean().optional(),
127
+ });
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // Validation helpers (daemon is the authority — clients only shape-parse args)
131
+ // ---------------------------------------------------------------------------
132
+
133
+ function assertValidProvider(provider: string): void {
134
+ if (!LLMProvider.safeParse(provider).success) {
135
+ throw new BadRequestError(
136
+ `Invalid provider "${provider}". Valid providers: ${LLMProvider.options.join(", ")}.`,
137
+ );
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Validate a (provider, model) pair against the catalog. Returns warnings
143
+ * (never throws) when `allowUnlisted`; throws otherwise for an uncataloged
144
+ * model. An uncataloged model always warns, whether or not it is allowed.
145
+ */
146
+ function validateModel(
147
+ provider: string,
148
+ model: string,
149
+ allowUnlisted: boolean,
150
+ ): string[] {
151
+ if (isModelInCatalog(provider, model)) {
152
+ return [];
153
+ }
154
+ if (!allowUnlisted) {
155
+ throw new BadRequestError(
156
+ `Model "${model}" is not in the catalog for provider "${provider}". ` +
157
+ `Pass allowUnlisted to create it anyway, or run ` +
158
+ `"assistant inference models list --provider ${provider}" to see valid ids.`,
159
+ );
160
+ }
161
+ return [
162
+ `Model "${model}" is not in the catalog for provider "${provider}" — created anyway (allowUnlisted).`,
163
+ ];
164
+ }
165
+
166
+ function assertConnectionExists(name: string): void {
167
+ if (!getConnection(getDb(), name)) {
168
+ throw new BadRequestError(
169
+ `Connection "${name}" does not exist. Create it first with ` +
170
+ `"assistant inference providers connections create", or omit --connection.`,
171
+ );
172
+ }
173
+ }
174
+
175
+ function asPlainObject(value: unknown): Record<string, unknown> | null {
176
+ if (value == null || typeof value !== "object" || Array.isArray(value)) {
177
+ return null;
178
+ }
179
+ return value as Record<string, unknown>;
180
+ }
181
+
182
+ /**
183
+ * Compute connection availability for an effective profile entry — null when
184
+ * there is nothing to judge (no connection or no provider, e.g. mix profiles).
185
+ */
186
+ async function profileAvailability(
187
+ entry: Record<string, unknown>,
188
+ ): Promise<Awaited<ReturnType<typeof computeConnectionAvailability>> | null> {
189
+ const provider = entry.provider;
190
+ const connection = entry.provider_connection;
191
+ if (typeof provider !== "string" || typeof connection !== "string") {
192
+ return null;
193
+ }
194
+ return computeConnectionAvailability(provider, connection);
195
+ }
196
+
197
+ function ensureRawProfiles(
198
+ raw: Record<string, unknown>,
199
+ ): Record<string, unknown> {
200
+ const existingLlm = asPlainObject(raw.llm);
201
+ const llm = existingLlm ?? {};
202
+ if (!existingLlm) {
203
+ raw.llm = llm;
204
+ }
205
+ const existingProfiles = asPlainObject(llm.profiles);
206
+ const profiles = existingProfiles ?? {};
207
+ if (!existingProfiles) {
208
+ llm.profiles = profiles;
209
+ }
210
+ return profiles;
211
+ }
212
+
213
+ /**
214
+ * Build the fragment of profile fields carried by the create/update request
215
+ * body, converting the CLI's flat `thinking` boolean into the schema shape.
216
+ * Only keys present in `body` are set — absent keys are left for the caller
217
+ * to merge (update) or default (create).
218
+ */
219
+ function fragmentFromBody(
220
+ body: Record<string, unknown>,
221
+ ): Record<string, unknown> {
222
+ const fragment: Record<string, unknown> = {};
223
+ if (typeof body.label === "string") {
224
+ fragment.label = body.label;
225
+ }
226
+ if (typeof body.effort === "string") {
227
+ fragment.effort = body.effort;
228
+ }
229
+ if (typeof body.maxTokens === "number") {
230
+ fragment.maxTokens = body.maxTokens;
231
+ }
232
+ if (typeof body.temperature === "number") {
233
+ fragment.temperature = body.temperature;
234
+ }
235
+ if (typeof body.thinking === "boolean") {
236
+ fragment.thinking = { enabled: body.thinking };
237
+ }
238
+ if (typeof body.description === "string") {
239
+ fragment.description = body.description;
240
+ }
241
+ if (typeof body.connection === "string") {
242
+ fragment.provider_connection = body.connection;
243
+ }
244
+ return fragment;
245
+ }
246
+
247
+ /**
248
+ * Enumerate every live reference to profile `name` in the raw `llm` config
249
+ * block: `activeProfile`, `advisorProfile`, each `callSites.<id>.profile`, and
250
+ * every mix arm (`profiles.<mix>.mix[].profile`). Deleting a profile while any
251
+ * of these point at it would leave a dangling reference that `LLMSchema`'s
252
+ * superRefine rejects on the next load — silently resetting the user's chat
253
+ * model or call-site pins. The delete handler rejects instead.
254
+ */
255
+ export function collectProfileReferences(
256
+ llm: Record<string, unknown> | null,
257
+ name: string,
258
+ ): string[] {
259
+ if (!llm) {
260
+ return [];
261
+ }
262
+ const refs: string[] = [];
263
+ if (llm.activeProfile === name) {
264
+ refs.push("llm.activeProfile");
265
+ }
266
+ if (llm.advisorProfile === name) {
267
+ refs.push("llm.advisorProfile");
268
+ }
269
+ const callSites = asPlainObject(llm.callSites);
270
+ if (callSites) {
271
+ for (const [siteId, siteConfig] of Object.entries(callSites)) {
272
+ if (asPlainObject(siteConfig)?.profile === name) {
273
+ refs.push(`llm.callSites.${siteId}`);
274
+ }
275
+ }
276
+ }
277
+ const profiles = asPlainObject(llm.profiles);
278
+ if (profiles) {
279
+ for (const [profileName, profileEntry] of Object.entries(profiles)) {
280
+ const mix = asPlainObject(profileEntry)?.mix;
281
+ if (
282
+ Array.isArray(mix) &&
283
+ mix.some((arm) => asPlainObject(arm)?.profile === name)
284
+ ) {
285
+ refs.push(`llm.profiles.${profileName}.mix`);
286
+ }
287
+ }
288
+ }
289
+ return refs;
290
+ }
291
+
292
+ function validateProfileEntry(entry: Record<string, unknown>): void {
293
+ const parsed = ProfileEntry.safeParse(entry);
294
+ if (!parsed.success) {
295
+ const detail = parsed.error.issues.map((issue) => issue.message).join("; ");
296
+ throw new BadRequestError(`Invalid profile: ${detail}`);
297
+ }
298
+ }
299
+
300
+ // ---------------------------------------------------------------------------
301
+ // Handlers
302
+ // ---------------------------------------------------------------------------
303
+
304
+ async function handleListProfiles() {
305
+ const config = getConfigReadOnly();
306
+ const effective = getEffectiveProfilesForProvider(
307
+ config.llm.profiles,
308
+ config.llm.defaultProvider ?? null,
309
+ );
310
+ const profiles = await Promise.all(
311
+ Object.entries(effective).map(async ([name, entry]) => {
312
+ const record = entry as Record<string, unknown>;
313
+ return {
314
+ name,
315
+ label: typeof record.label === "string" ? record.label : null,
316
+ provider: typeof record.provider === "string" ? record.provider : null,
317
+ model: typeof record.model === "string" ? record.model : null,
318
+ status: record.status === "disabled" ? "disabled" : "active",
319
+ source: record.source === "managed" ? "managed" : "user",
320
+ ...(typeof record.provider_connection === "string"
321
+ ? { provider_connection: record.provider_connection }
322
+ : {}),
323
+ availability: await profileAvailability(record),
324
+ };
325
+ }),
326
+ );
327
+ return { profiles };
328
+ }
329
+
330
+ async function handleGetProfile({ pathParams = {} }: RouteHandlerArgs) {
331
+ const name = (pathParams.name ?? "").trim();
332
+ if (!name) {
333
+ throw new BadRequestError("Profile name must be a non-empty string");
334
+ }
335
+ const config = getConfigReadOnly();
336
+ const entry = resolveDefaultProfileForProvider(
337
+ config.llm.profiles,
338
+ name,
339
+ config.llm.defaultProvider ?? null,
340
+ );
341
+ if (!entry) {
342
+ throw new NotFoundError(`Profile "${name}" not found.`);
343
+ }
344
+ const record = entry as Record<string, unknown>;
345
+ return {
346
+ name,
347
+ entry: record,
348
+ availability: await profileAvailability(record),
349
+ };
350
+ }
351
+
352
+ async function handleCreateProfile({ body = {} }: RouteHandlerArgs) {
353
+ const parsed = createRequestSchema.safeParse(body);
354
+ if (!parsed.success) {
355
+ throw new BadRequestError(
356
+ `Invalid request: ${parsed.error.issues.map((i) => i.message).join("; ")}`,
357
+ );
358
+ }
359
+ const input = parsed.data;
360
+ const name = input.name.trim();
361
+ if (!name) {
362
+ throw new BadRequestError("Profile name must be a non-empty string");
363
+ }
364
+ if (RESERVED_PROFILE_NAMES.has(name)) {
365
+ throw new BadRequestError(`Profile name "${name}" is reserved.`);
366
+ }
367
+ if (MANAGED_PROFILE_NAMES.has(name)) {
368
+ throw new BadRequestError(
369
+ `Cannot create profile "${name}" — the name is reserved for a code-defined default profile. Pick a different name.`,
370
+ );
371
+ }
372
+
373
+ assertValidProvider(input.provider);
374
+ const warnings = validateModel(
375
+ input.provider,
376
+ input.model,
377
+ input.allowUnlisted ?? false,
378
+ );
379
+ if (input.connection) {
380
+ assertConnectionExists(input.connection);
381
+ }
382
+
383
+ const entry: Record<string, unknown> = {
384
+ ...fragmentFromBody(body as Record<string, unknown>),
385
+ provider: input.provider,
386
+ model: input.model,
387
+ source: "user",
388
+ };
389
+ validateProfileEntry(entry);
390
+
391
+ const raw = loadRawConfig();
392
+ const profiles = ensureRawProfiles(raw);
393
+ if (profiles[name] !== undefined) {
394
+ throw new ConflictError(
395
+ `Profile "${name}" already exists. Use update to modify it.`,
396
+ );
397
+ }
398
+ profiles[name] = entry;
399
+ // Defensive: for a user-owned name this is a no-op; it re-asserts the
400
+ // managed-name protection at the shared write choke point.
401
+ normalizeManagedProfileWrites({ llm: { profiles: { [name]: entry } } });
402
+
403
+ await commitConfigWrite(raw, "create inference profile");
404
+
405
+ return {
406
+ ok: true as const,
407
+ name,
408
+ entry: (getEffectiveProfile(getConfig().llm.profiles, name) ??
409
+ entry) as Record<string, unknown>,
410
+ warnings,
411
+ };
412
+ }
413
+
414
+ async function handleUpdateProfile({
415
+ pathParams = {},
416
+ body = {},
417
+ }: RouteHandlerArgs) {
418
+ const name = (pathParams.name ?? "").trim();
419
+ if (!name) {
420
+ throw new BadRequestError("Profile name must be a non-empty string");
421
+ }
422
+ if (RESERVED_PROFILE_NAMES.has(name)) {
423
+ throw new BadRequestError(`Profile name "${name}" is reserved.`);
424
+ }
425
+ const parsed = updateRequestSchema.safeParse(body);
426
+ if (!parsed.success) {
427
+ throw new BadRequestError(
428
+ `Invalid request: ${parsed.error.issues.map((i) => i.message).join("; ")}`,
429
+ );
430
+ }
431
+ const input = parsed.data;
432
+
433
+ const raw = loadRawConfig();
434
+ const profiles = ensureRawProfiles(raw);
435
+ const existing = asPlainObject(profiles[name]);
436
+ if (!existing) {
437
+ if (MANAGED_PROFILE_NAMES.has(name)) {
438
+ throw new BadRequestError(
439
+ `Cannot edit managed profile "${name}". Managed profiles are read-only; duplicate to a custom profile to customize.`,
440
+ );
441
+ }
442
+ throw new NotFoundError(`Profile "${name}" not found.`);
443
+ }
444
+ if (MANAGED_PROFILE_NAMES.has(name) && existing.source === "managed") {
445
+ throw new BadRequestError(
446
+ `Cannot edit managed profile "${name}". Managed profiles are read-only; duplicate to a custom profile to customize.`,
447
+ );
448
+ }
449
+
450
+ const nextProvider =
451
+ input.provider ??
452
+ (typeof existing.provider === "string" ? existing.provider : undefined);
453
+ const nextModel =
454
+ input.model ??
455
+ (typeof existing.model === "string" ? existing.model : undefined);
456
+
457
+ if (input.provider) {
458
+ assertValidProvider(input.provider);
459
+ }
460
+ let warnings: string[] = [];
461
+ if (
462
+ (input.provider !== undefined || input.model !== undefined) &&
463
+ typeof nextProvider === "string" &&
464
+ typeof nextModel === "string"
465
+ ) {
466
+ warnings = validateModel(
467
+ nextProvider,
468
+ nextModel,
469
+ input.allowUnlisted ?? false,
470
+ );
471
+ }
472
+ if (input.connection) {
473
+ assertConnectionExists(input.connection);
474
+ }
475
+
476
+ const merged: Record<string, unknown> = {
477
+ ...existing,
478
+ ...fragmentFromBody(body as Record<string, unknown>),
479
+ ...(input.provider !== undefined ? { provider: input.provider } : {}),
480
+ ...(input.model !== undefined ? { model: input.model } : {}),
481
+ source:
482
+ existing.source === "managed" ? "user" : (existing.source ?? "user"),
483
+ };
484
+ validateProfileEntry(merged);
485
+
486
+ profiles[name] = merged;
487
+ normalizeManagedProfileWrites({ llm: { profiles: { [name]: merged } } });
488
+
489
+ await commitConfigWrite(raw, "update inference profile");
490
+
491
+ return {
492
+ ok: true as const,
493
+ name,
494
+ entry: (getEffectiveProfile(getConfig().llm.profiles, name) ??
495
+ merged) as Record<string, unknown>,
496
+ warnings,
497
+ };
498
+ }
499
+
500
+ async function handleDeleteProfile({ pathParams = {} }: RouteHandlerArgs) {
501
+ const name = (pathParams.name ?? "").trim();
502
+ if (!name) {
503
+ throw new BadRequestError("Profile name must be a non-empty string");
504
+ }
505
+
506
+ const raw = loadRawConfig();
507
+ const llm = asPlainObject(raw.llm);
508
+ const profiles = asPlainObject(llm?.profiles);
509
+
510
+ // Reject deletion of a managed default with a clear message before the
511
+ // existence check, so `delete balanced` explains itself even when the
512
+ // managed stub is on disk.
513
+ rejectManagedProfileDeletion({ llm: { profiles: { [name]: null } } });
514
+
515
+ if (!profiles || profiles[name] === undefined) {
516
+ throw new NotFoundError(`Profile "${name}" not found.`);
517
+ }
518
+
519
+ // Refuse deletion while the profile is still referenced. Cascade-deleting the
520
+ // references would silently reset the user's chat model / call-site pins; make
521
+ // the user clear them explicitly instead.
522
+ const references = collectProfileReferences(llm, name);
523
+ if (references.length > 0) {
524
+ throw new ConflictError(
525
+ `Cannot delete profile "${name}" — it is referenced by ${references.join(", ")}. ` +
526
+ `Clear or repoint ${references.length === 1 ? "that reference" : "those references"} first.`,
527
+ { referencedBy: references },
528
+ );
529
+ }
530
+
531
+ delete profiles[name];
532
+
533
+ await commitConfigWrite(raw, "delete inference profile");
534
+
535
+ return { ok: true as const, name };
536
+ }
537
+
538
+ const setActiveRequestSchema = z.object({ name: z.string().min(1) });
539
+
540
+ async function handleSetActiveProfile({ body = {} }: RouteHandlerArgs) {
541
+ const parsed = setActiveRequestSchema.safeParse(body);
542
+ if (!parsed.success) {
543
+ throw new BadRequestError("name must be a non-empty string");
544
+ }
545
+ const name = parsed.data.name.trim();
546
+ if (!name) {
547
+ throw new BadRequestError("Profile name must be a non-empty string");
548
+ }
549
+
550
+ // Validate against the same effective catalog the resolver selects from
551
+ // (provider-aware default expansion included), so a typo or a removed name
552
+ // is rejected here instead of silently stripped on the next config load —
553
+ // which would reset the user's chat-model selection.
554
+ const config = getConfigReadOnly();
555
+ const effective = getEffectiveProfilesForProvider(
556
+ config.llm.profiles,
557
+ config.llm.defaultProvider ?? null,
558
+ );
559
+ const entry = effective[name] as Record<string, unknown> | undefined;
560
+ if (!entry) {
561
+ const valid = Object.keys(effective).sort().join(", ");
562
+ throw new BadRequestError(
563
+ `Profile "${name}" does not exist. Valid profiles: ${valid}.`,
564
+ );
565
+ }
566
+ if (entry.status === "disabled") {
567
+ throw new BadRequestError(
568
+ `Profile "${name}" is disabled and cannot be set as the active profile. Enable it first, or pick another.`,
569
+ );
570
+ }
571
+
572
+ const raw = loadRawConfig();
573
+ const existingLlm = asPlainObject(raw.llm);
574
+ const llm = existingLlm ?? {};
575
+ if (!existingLlm) {
576
+ raw.llm = llm;
577
+ }
578
+ llm.activeProfile = name;
579
+
580
+ await commitConfigWrite(raw, "set active inference profile");
581
+
582
+ return { ok: true as const, activeProfile: name };
583
+ }
584
+
585
+ // ---------------------------------------------------------------------------
586
+ // Route definitions
587
+ // ---------------------------------------------------------------------------
588
+
589
+ export const ROUTES: RouteDefinition[] = [
590
+ {
591
+ operationId: "inference_profiles_list",
592
+ endpoint: "inference/profiles",
593
+ method: "GET",
594
+ policy: {
595
+ requiredScopes: ["settings.read"],
596
+ allowedPrincipalTypes: ACTOR_PRINCIPALS,
597
+ },
598
+ summary: "List effective inference profiles",
599
+ description:
600
+ "Return the effective profile catalog: code-defined managed defaults merged with user profiles, each annotated with source and (when it has a connection) availability.",
601
+ tags: ["inference"],
602
+ responseBody: z.object({ profiles: z.array(profileSummarySchema) }),
603
+ handler: handleListProfiles,
604
+ },
605
+ {
606
+ operationId: "inference_profiles_get",
607
+ endpoint: "inference/profiles/:name",
608
+ method: "GET",
609
+ policy: {
610
+ requiredScopes: ["settings.read"],
611
+ allowedPrincipalTypes: ACTOR_PRINCIPALS,
612
+ },
613
+ summary: "Get an effective inference profile",
614
+ description:
615
+ "Return a single effective profile by name, with availability.",
616
+ tags: ["inference"],
617
+ pathParams: [{ name: "name", description: "Profile name" }],
618
+ responseBody: profileDetailSchema,
619
+ additionalResponses: { "404": { description: "Profile not found" } },
620
+ handler: handleGetProfile,
621
+ },
622
+ {
623
+ operationId: "inference_profiles_create",
624
+ endpoint: "inference/profiles",
625
+ method: "POST",
626
+ policy: {
627
+ requiredScopes: ["settings.write"],
628
+ allowedPrincipalTypes: ACTOR_PRINCIPALS,
629
+ },
630
+ summary: "Create an inference profile",
631
+ description:
632
+ "Create a validated custom profile. The provider must be a known LLM provider, the model must be in the catalog (unless allowUnlisted), and a referenced connection must exist. Managed default names cannot be created.",
633
+ tags: ["inference"],
634
+ requestBody: createRequestSchema,
635
+ responseBody: profileWriteResultSchema,
636
+ responseStatus: "201",
637
+ additionalResponses: {
638
+ "400": {
639
+ description:
640
+ "Invalid provider, uncataloged model, or missing connection",
641
+ },
642
+ "409": { description: "A profile with this name already exists" },
643
+ },
644
+ handler: handleCreateProfile,
645
+ },
646
+ {
647
+ operationId: "inference_profiles_update",
648
+ endpoint: "inference/profiles/:name",
649
+ method: "PATCH",
650
+ policy: {
651
+ requiredScopes: ["settings.write"],
652
+ allowedPrincipalTypes: ACTOR_PRINCIPALS,
653
+ },
654
+ summary: "Update an inference profile",
655
+ description:
656
+ "Partial update of a custom profile with the same write-time validation as create. Managed default profiles are read-only.",
657
+ tags: ["inference"],
658
+ pathParams: [{ name: "name", description: "Profile name" }],
659
+ requestBody: updateRequestSchema,
660
+ responseBody: profileWriteResultSchema,
661
+ additionalResponses: {
662
+ "400": {
663
+ description: "Invalid fields, or attempt to edit a managed profile",
664
+ },
665
+ "404": { description: "Profile not found" },
666
+ },
667
+ handler: handleUpdateProfile,
668
+ },
669
+ {
670
+ operationId: "inference_profiles_delete",
671
+ endpoint: "inference/profiles/:name",
672
+ method: "DELETE",
673
+ policy: {
674
+ requiredScopes: ["settings.write"],
675
+ allowedPrincipalTypes: ACTOR_PRINCIPALS,
676
+ },
677
+ summary: "Delete an inference profile",
678
+ description:
679
+ "Delete a custom profile. Managed default profiles cannot be deleted (they are re-seeded on boot).",
680
+ tags: ["inference"],
681
+ pathParams: [{ name: "name", description: "Profile name" }],
682
+ responseBody: z.object({ ok: z.literal(true), name: z.string() }),
683
+ additionalResponses: {
684
+ "400": { description: "Attempt to delete a managed profile" },
685
+ "404": { description: "Profile not found" },
686
+ "409": {
687
+ description:
688
+ "Profile is still referenced by activeProfile, advisorProfile, a call site, or a mix arm",
689
+ },
690
+ },
691
+ handler: handleDeleteProfile,
692
+ },
693
+ {
694
+ operationId: "inference_profiles_set_active",
695
+ endpoint: "inference/active-profile",
696
+ method: "PUT",
697
+ policy: {
698
+ requiredScopes: ["settings.write"],
699
+ allowedPrincipalTypes: ACTOR_PRINCIPALS,
700
+ },
701
+ summary: "Set the active (chat) inference profile",
702
+ description:
703
+ "Set llm.activeProfile after validating the name against the effective profile catalog (provider-aware default expansion included). Unknown or disabled profiles are rejected so the chat-model selection cannot be silently stripped on the next config load.",
704
+ tags: ["inference"],
705
+ requestBody: setActiveRequestSchema,
706
+ responseBody: z.object({
707
+ ok: z.literal(true),
708
+ activeProfile: z.string(),
709
+ }),
710
+ additionalResponses: {
711
+ "400": {
712
+ description: "Unknown or disabled profile name",
713
+ },
714
+ },
715
+ handler: handleSetActiveProfile,
716
+ },
717
+ ];