@vellumai/assistant 0.11.2-dev.202608051734.355dff7 → 0.11.2-dev.202608051933.deffc0f

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 (60) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/ingress.ts +10 -0
  3. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/ingress.ts +10 -0
  4. package/node_modules/@vellumai/service-contracts/src/ingress.ts +10 -0
  5. package/openapi.yaml +22 -0
  6. package/package.json +1 -1
  7. package/src/__tests__/agent-loop-override-profile.test.ts +38 -48
  8. package/src/__tests__/assistant-feature-flags-integration.test.ts +0 -10
  9. package/src/__tests__/conversation-tool-setup-app-refresh.test.ts +1 -0
  10. package/src/__tests__/conversation-tool-setup-attribution.test.ts +61 -0
  11. package/src/__tests__/cu-unified-flow.test.ts +2 -6
  12. package/src/__tests__/file-ops-service.test.ts +75 -4
  13. package/src/__tests__/host-bash-proxy.test.ts +10 -5
  14. package/src/__tests__/host-browser-proxy.test.ts +2 -2
  15. package/src/__tests__/host-cu-proxy.test.ts +3 -7
  16. package/src/__tests__/host-file-proxy.test.ts +3 -7
  17. package/src/__tests__/host-file-read-tool.test.ts +5 -1
  18. package/src/__tests__/host-transfer-proxy-targeted.test.ts +6 -4
  19. package/src/__tests__/llm-resolver-override-or-default.test.ts +141 -0
  20. package/src/__tests__/media-stream-server-integration.test.ts +36 -0
  21. package/src/__tests__/stt-language-catalog-parity.test.ts +38 -0
  22. package/src/__tests__/subagent-tool-gate-mode.test.ts +1 -0
  23. package/src/__tests__/subagent-tools.test.ts +48 -92
  24. package/src/__tests__/tool-result-spool.test.ts +74 -18
  25. package/src/agent/loop.ts +6 -3
  26. package/src/calls/media-stream-server.ts +9 -1
  27. package/src/config/bundled-skills/settings/TOOLS.json +2 -2
  28. package/src/config/bundled-skills/settings/tools/voice-config-update.ts +1 -0
  29. package/src/config/bundled-skills/subagent/SKILL.md +3 -3
  30. package/src/config/bundled-skills/subagent/TOOLS.json +1 -1
  31. package/src/config/feature-flag-registry.json +0 -16
  32. package/src/config/llm-resolver.ts +41 -12
  33. package/src/config/schemas/stt.ts +10 -4
  34. package/src/context/post-turn-tool-result-truncation.ts +32 -16
  35. package/src/context/tool-result-spool.ts +32 -18
  36. package/src/daemon/conversation-tool-setup.ts +1 -1
  37. package/src/persistence/conversation-attention-store.ts +30 -10
  38. package/src/persistence/conversation-queries.ts +74 -1
  39. package/src/platform/managed-speech.test.ts +20 -0
  40. package/src/platform/managed-speech.ts +9 -0
  41. package/src/providers/speech-to-text/__tests__/resolve.test.ts +164 -6
  42. package/src/providers/speech-to-text/deepgram.ts +1 -0
  43. package/src/providers/speech-to-text/resolve.ts +80 -10
  44. package/src/providers/speech-to-text/vellum-managed.ts +7 -1
  45. package/src/providers/speech-to-text/vellum-speech-relay-connection.ts +3 -1
  46. package/src/runtime/auth/__tests__/guard-tests.test.ts +2 -0
  47. package/src/runtime/auth/__tests__/scopes.test.ts +20 -0
  48. package/src/runtime/auth/same-actor.ts +38 -7
  49. package/src/runtime/auth/scopes.ts +12 -0
  50. package/src/runtime/auth/types.ts +2 -0
  51. package/src/runtime/routes/__tests__/conversation-list-routes.test.ts +279 -1
  52. package/src/runtime/routes/__tests__/conversation-query-routes.test.ts +14 -10
  53. package/src/runtime/routes/conversation-list-routes.ts +25 -0
  54. package/src/runtime/routes/conversation-query-routes.ts +0 -50
  55. package/src/stt/daemon-batch-transcriber.ts +8 -6
  56. package/src/tools/filesystem/read.ts +2 -2
  57. package/src/tools/host-filesystem/read.ts +14 -6
  58. package/src/tools/shared/filesystem/file-ops-service.ts +36 -3
  59. package/src/tools/subagent/spawn.ts +26 -78
  60. package/src/tools/types.ts +5 -3
@@ -119,11 +119,11 @@ Either way it is advisory, not a block: pass `confirm_repeat: true` to spawn any
119
119
 
120
120
  Set `inference_profile` to an `llm.profiles` key when a subagent should run under a specific model profile.
121
121
 
122
- When it is omitted, one of two things happens. Normally the subagent inherits the parent turn's active profile if one exists, and otherwise uses the `subagentSpawn` call site's default model selection. When profile isolation is enabled, the subagent always takes the `subagentSpawn` default rather than the parent's profile, and an explicit `inference_profile` the model catalog does not report as tool-capable is replaced by that default with a note on the spawn result.
122
+ When it is omitted, the subagent takes the `subagentSpawn` call site's default model selection. It does not pick up the profile the spawning turn is running on: a profile pinned on a conversation is a choice about that conversation, and it does not follow the work that conversation delegates.
123
123
 
124
- An `advisor` consult is the exception to that second half: it carries read-only tools whether or not profile isolation is on, so a profile the catalog does not report as tool-capable is always replaced by the `subagentSpawn` default, with a note alongside the guidance.
124
+ An `inference_profile` you name explicitly wins, unless the model catalog does not report it as tool-capable, in which case it is replaced by the `subagentSpawn` default with a note on the spawn result. An `advisor` consult applies that same fallback, with the note alongside its guidance.
125
125
 
126
- `output_contract: "verdict"` takes a cheaper profile ahead of either path, so a verdict runs cheap unless you name an `inference_profile` yourself. A profile pinned on the `subagentSpawn` call site in config also beats the cheap preset, so an operator can decide what checks run on.
126
+ `output_contract: "verdict"` takes a cheaper profile, so a verdict runs cheap unless you name an `inference_profile` yourself. A profile pinned on the `subagentSpawn` call site in config also beats the cheap preset, so an operator can decide what checks run on.
127
127
 
128
128
  ## Fork Mode
129
129
 
@@ -35,7 +35,7 @@
35
35
  },
36
36
  "inference_profile": {
37
37
  "type": "string",
38
- "description": "Optional llm.profiles key this subagent should run under. When omitted, the subagent normally inherits the parent turn's profile if one is active, and otherwise uses the subagentSpawn call site's default model selection. When profile isolation is enabled, the subagent always takes the subagentSpawn default instead of the parent's profile, and a profile the model catalog does not report as tool-capable is replaced by that default with a note on the result. An advisor consult applies that tool-capability fallback whether or not profile isolation is enabled, since it carries read-only tools either way. An output_contract of 'verdict' takes a cheaper profile ahead of either path unless you name a profile here, or unless the subagentSpawn call site has its own profile pinned in config, which also beats the cheaper preset."
38
+ "description": "Optional llm.profiles key this subagent should run under. When omitted, the subagent takes the subagentSpawn call site's default model selection, never the profile your own turn is running on: a profile pinned on this conversation is a choice about this conversation and does not follow the work you delegate. A profile you name here that the model catalog does not report as tool-capable is replaced by that same default, with a note on the result. An output_contract of 'verdict' takes a cheaper profile unless you name a profile here, or unless the subagentSpawn call site has its own profile pinned in config, which also beats the cheaper preset."
39
39
  },
40
40
  "confirm_repeat": {
41
41
  "type": "boolean",
@@ -364,22 +364,6 @@
364
364
  "label": "Desktop Presence Suppression",
365
365
  "description": "Gates whether a `chat.assistant_reply` push is suppressed while a Mac desktop client reports itself attended. On by default; turn it off to restore unconditional reply pushes.",
366
366
  "defaultEnabled": true
367
- },
368
- {
369
- "id": "subagent-profile-isolation",
370
- "scope": "assistant",
371
- "key": "subagent-profile-isolation",
372
- "label": "Subagent Profile Isolation",
373
- "description": "Subagents resolve the subagentSpawn call site's own default model profile instead of inheriting the conversation's active profile, and an explicitly requested profile the model catalog does not report as tool-capable falls back to that same default. Both halves cover background spawns only: an advisor consult carries read-only tools with or without this flag, so it applies the tool-capability fallback either way. Applies to forks too: a fork otherwise stays on the parent's model and reuses its cached context, so under isolation a fork can run on a different model and re-prefill the transcript it inherits.",
374
- "defaultEnabled": false
375
- },
376
- {
377
- "id": "subagent-loop-guard",
378
- "scope": "assistant",
379
- "key": "subagent-loop-guard",
380
- "label": "Subagent Loop Guard",
381
- "description": "Rate-limit near-identical repeat subagent spawns and require explicit confirmation to continue.",
382
- "defaultEnabled": false
383
367
  }
384
368
  ]
385
369
  }
@@ -157,9 +157,11 @@ export function resolveCallSiteConfig(
157
157
  //
158
158
  // The request config is the base + winner + site-tweak composition:
159
159
  // code-owned schema defaults, then the single winning profile, then the call
160
- // site's own tuning fragment. Selection is pure either/or — no profile ever
161
- // contributes a field to another profile; `deepMerge` here only makes nested
162
- // tweaks (`thinking.enabled`) combine leaf-wise instead of wiping siblings.
160
+ // site's own tuning fragment (its shipped `CALL_SITE_DEFAULTS` tuning with
161
+ // the workspace `llm.callSites` entry layered over it, field by field).
162
+ // Selection is pure either/or: no profile ever contributes a field to
163
+ // another profile, and `deepMerge` only makes nested tweaks
164
+ // (`thinking.enabled`) combine leaf-wise instead of wiping siblings.
163
165
  // `temperature`/`topP` come from the winner (or an explicit tweak);
164
166
  // `logitBias` only ever from the winner.
165
167
  // `forceOverrideProfile` is a no-op here (the override is already first).
@@ -381,15 +383,10 @@ function resolveOverrideOrDefault(
381
383
  const winnerFragment: Mergeable =
382
384
  selection.entry == null ? {} : winnerConfigFragment(selection.entry);
383
385
 
384
- // The call site's own tweak fragment: the workspace override replaces the
385
- // code default wholesale. `profile` is the selection discriminator and
386
- // `logitBias` is winner-owned, so neither enters the merge.
387
- const site = llm.callSites?.[callSite] ?? CALL_SITE_DEFAULTS[callSite];
388
- const {
389
- profile: _siteProfile,
390
- logitBias: _siteBias,
391
- ...tweak
392
- } = (site ?? {}) as Record<string, unknown>;
386
+ const tweak = composeCallSiteTweak(
387
+ CALL_SITE_DEFAULTS[callSite] as Mergeable | undefined,
388
+ llm.callSites?.[callSite] as Mergeable | undefined,
389
+ );
393
390
 
394
391
  // Direct call-site model overrides are fragments by design: when the tweak
395
392
  // pins a model the winner's provider does not serve, stamp the catalog
@@ -472,6 +469,38 @@ function winnerConfigFragment(entry: ProfileEntry): Mergeable {
472
469
 
473
470
  type Mergeable = Record<string, unknown>;
474
471
 
472
+ /**
473
+ * The call site's tuning fragment: its shipped `CALL_SITE_DEFAULTS` tuning
474
+ * with the workspace `llm.callSites` entry layered over it, field by field.
475
+ * An entry that only names a profile therefore repoints the selection while
476
+ * the tuning the call site ships with still applies, and a field the entry
477
+ * sets wins for that field alone.
478
+ *
479
+ * `profile` is the selection discriminator and `logitBias` is winner-owned,
480
+ * so neither survives into the fragment. A workspace entry also owns the
481
+ * selection for its own call site: when one exists the shipped layer
482
+ * contributes tuning only, so a shipped `provider`/`model` pin can never
483
+ * override the profile or the custom model the user chose there. With no
484
+ * workspace entry the shipped fragment applies whole, pin included.
485
+ */
486
+ export function composeCallSiteTweak(
487
+ shipped: Mergeable | undefined,
488
+ workspace: Mergeable | undefined,
489
+ ): Mergeable {
490
+ const {
491
+ provider: _shippedProvider,
492
+ model: _shippedModel,
493
+ ...shippedTuning
494
+ } = shipped ?? {};
495
+ const shippedLayer = workspace == null ? (shipped ?? {}) : shippedTuning;
496
+ const {
497
+ profile: _siteProfile,
498
+ logitBias: _siteBias,
499
+ ...tweak
500
+ } = deepMerge(shippedLayer, workspace ?? {});
501
+ return tweak;
502
+ }
503
+
475
504
  /**
476
505
  * FNV-1a 32-bit string hash → unit float in [0, 1). Deterministic and stable
477
506
  * across runtimes — the mix-pick contract depends on identical output for
@@ -67,14 +67,20 @@ export const SttServiceSchema = z
67
67
  .describe("Active STT provider used for speech-to-text transcription"),
68
68
  /**
69
69
  * Spoken-language selection, forwarded to providers whose adapters accept
70
- * a language (Deepgram, xAI, and the managed relay). Left unset the
71
- * provider applies its own default, which for Deepgram (and therefore
72
- * for the managed relay) is English, NOT auto-detection.
70
+ * a language (Deepgram, xAI, and the managed relay).
73
71
  *
74
72
  * `"multi"` selects Deepgram's nova-3 code-switching mode, which follows
75
73
  * a speaker moving between languages inside a single utterance (e.g.
76
74
  * Hinglish). Providers that auto-detect natively and take no language
77
75
  * option (Gemini, Whisper) ignore this field.
76
+ *
77
+ * Left unset, the resolver fills in the provider's default rather than
78
+ * sending nothing: `"multi"` on Deepgram and the managed relay, where
79
+ * sending nothing would mean English rather than detection, and nothing
80
+ * at all on providers that detect natively. See `effectiveSttLanguage` in
81
+ * `providers/speech-to-text/resolve.ts`. Unset is kept meaningful here on
82
+ * purpose: it records that the user has not chosen, which is what lets
83
+ * the settings surfaces label a row "default".
78
84
  */
79
85
  language: z
80
86
  .string({ error: "services.stt.language must be a string" })
@@ -82,7 +88,7 @@ export const SttServiceSchema = z
82
88
  .min(1, { error: "services.stt.language must not be empty" })
83
89
  .optional()
84
90
  .describe(
85
- "BCP-47 language code (e.g. 'en-US', 'hi') or 'multi' for code-switching across languages. Unset uses the provider default (English on Deepgram/managed, not auto-detect)",
91
+ "BCP-47 language code (e.g. 'en-US', 'hi') or 'multi' for code-switching across languages. Unset resolves to 'multi' on Deepgram/managed and to native auto-detection elsewhere",
86
92
  ),
87
93
  providers: SttProvidersSchema.default({}),
88
94
  })
@@ -37,20 +37,43 @@ export const TRUNCATION_MARKER = "\u2014 full result:";
37
37
  export const TRUNCATION_EXEMPT_TOOLS = new Set<string>(["skill_load"]);
38
38
 
39
39
  /**
40
- * File-read tools that page spooled `.tool-results/` content back into context.
41
- * `file_read` reads inside the workspace; `host_file_read` reads anywhere on the
42
- * host. Both are (a) exempt from the result-time spool pass — re-stubbing a read
43
- * of a spooled file would hand back another stub, so the content could never be
44
- * paged back at all — and (b) recognized by {@link derefToolResultReReads}, so a
45
- * re-read of a spooled file collapses to a stub instead of duplicating content
46
- * already in context. Sharing one set keeps the two passes from drifting if a
47
- * new file-read tool is added.
40
+ * File-read tools that can page spooled `.tool-results/` content back into
41
+ * context. `file_read` reads inside the workspace; `host_file_read` reads
42
+ * anywhere on the host. A new file-read tool belongs here so
43
+ * {@link isSpooledToolResultRead} recognizes it.
48
44
  */
49
45
  export const FILE_READ_TOOL_NAMES = new Set<string>([
50
46
  "file_read",
51
47
  "host_file_read",
52
48
  ]);
53
49
 
50
+ /**
51
+ * Whether a tool call is a file read aimed at a spooled `.tool-results/` file.
52
+ *
53
+ * Such a read is the model paging content back in, so both passes treat it
54
+ * specially: the result-time spool pass leaves it alone (re-stubbing it would
55
+ * write a fresh copy and hand back another stub, putting the content out of
56
+ * reach for good), and {@link derefToolResultReReads} collapses it at turn end
57
+ * (its prefix and suffix are already in context above). A file read aimed
58
+ * anywhere else is ordinary tool output and gets no such treatment.
59
+ */
60
+ export function isSpooledToolResultRead(
61
+ toolName: string | undefined,
62
+ input: Record<string, unknown> | undefined,
63
+ ): boolean {
64
+ if (toolName === undefined || !FILE_READ_TOOL_NAMES.has(toolName)) {
65
+ return false;
66
+ }
67
+ const filePath = input?.path ?? input?.file_path;
68
+ if (typeof filePath !== "string") {
69
+ return false;
70
+ }
71
+ // The path in the stub comes from `join`, so it is backslash-separated on
72
+ // Windows. Compare on a normalized form: a missed match would let the spool
73
+ // pass stub this read and put the saved content permanently out of reach.
74
+ return filePath.replace(/\\/g, "/").includes(`/${TOOL_RESULT_DIR}/`);
75
+ }
76
+
54
77
  /**
55
78
  * Build a map of tool_use_id -> originating tool name by walking the tool_use
56
79
  * blocks in assistant messages. A tool_result only carries `tool_use_id`, so
@@ -329,14 +352,7 @@ export function derefToolResultReReads(messages: Message[]): {
329
352
  continue;
330
353
  }
331
354
  const tu = block as ToolUseContent;
332
- if (!FILE_READ_TOOL_NAMES.has(tu.name)) {
333
- continue;
334
- }
335
- const filePath = tu.input.path ?? tu.input.file_path;
336
- if (typeof filePath !== "string") {
337
- continue;
338
- }
339
- if (filePath.includes(`/${TOOL_RESULT_DIR}/`)) {
355
+ if (isSpooledToolResultRead(tu.name, tu.input)) {
340
356
  reReadToolUseIds.add(tu.id);
341
357
  }
342
358
  }
@@ -4,8 +4,8 @@ import { join } from "node:path";
4
4
  import type { ContentBlock, ToolResultContent } from "../providers/types.js";
5
5
  import {
6
6
  buildTruncatedContent,
7
- FILE_READ_TOOL_NAMES,
8
7
  getToolResultFilePath,
8
+ isSpooledToolResultRead,
9
9
  isTruncationEligible,
10
10
  TOOL_RESULT_DIR,
11
11
  } from "./post-turn-tool-result-truncation.js";
@@ -32,27 +32,32 @@ export const RESULT_TIME_SPOOL_EXEMPT_TOOLS = new Set<string>(["web_fetch"]);
32
32
 
33
33
  /**
34
34
  * Whether a tool result is eligible for the result-time spool/stub pass: the
35
- * post-turn pass's shared rules plus the AX-tree exemption, minus the file-read
36
- * tools ({@link FILE_READ_TOOL_NAMES}) and the explicit self-sized reads
37
- * ({@link RESULT_TIME_SPOOL_EXEMPT_TOOLS}). The file-read tools are the model's
38
- * only way to page spooled content back into context: stubbing a read of a
39
- * `.tool-results/` file would spool a fresh copy and hand back another stub, so
40
- * oversized content could never be read at all. Explicit reads are therefore
41
- * honored in full; the post-turn pass still truncates them at turn end, after
42
- * the model has consumed the content.
35
+ * post-turn pass's shared rules plus the AX-tree exemption, minus reads of
36
+ * already-spooled `.tool-results/` files ({@link isSpooledToolResultRead}) and
37
+ * the explicit self-sized reads ({@link RESULT_TIME_SPOOL_EXEMPT_TOOLS}).
38
+ *
39
+ * The spooled-read exemption is what keeps paging possible: a file read is the
40
+ * model's only way to pull spooled content back into context, so stubbing a
41
+ * read of a `.tool-results/` file would write a fresh copy and hand back
42
+ * another stub, putting that content out of reach for good. It is scoped by
43
+ * target path rather than by tool name, because a file read aimed anywhere
44
+ * else is ordinary oversized output with no such circularity, and exempting it
45
+ * keeps a whole file inline on every LLM call for the rest of the turn.
46
+ * Explicit self-sized reads are honored in full; the post-turn pass still
47
+ * truncates them at turn end, after the model has consumed the content.
43
48
  */
44
49
  function isSpoolEligible(
45
50
  tr: ToolResultContent,
46
51
  toolName: string | undefined,
52
+ toolInput: Record<string, unknown> | undefined,
47
53
  ): boolean {
48
54
  if (!isTruncationEligible(tr, toolName)) {
49
55
  return false;
50
56
  }
51
- if (
52
- toolName !== undefined &&
53
- (FILE_READ_TOOL_NAMES.has(toolName) ||
54
- RESULT_TIME_SPOOL_EXEMPT_TOOLS.has(toolName))
55
- ) {
57
+ if (isSpooledToolResultRead(toolName, toolInput)) {
58
+ return false;
59
+ }
60
+ if (toolName !== undefined && RESULT_TIME_SPOOL_EXEMPT_TOOLS.has(toolName)) {
56
61
  return false;
57
62
  }
58
63
  if (tr.content.includes(AX_TREE_TAG)) {
@@ -72,8 +77,8 @@ function isSpoolEligible(
72
77
  * rewriting an earlier message between calls would invalidate the cache from
73
78
  * that point on every iteration. The model still gets the head/tail preview
74
79
  * plus the on-disk path, so it can page the full content back in with
75
- * `file_read` or `host_file_read` (whose results are exempt from this pass)
76
- * when it actually needs it.
80
+ * `file_read` or `host_file_read` (a read of a `.tool-results/` path is exempt
81
+ * from this pass) when it actually needs it.
77
82
  *
78
83
  * Uses the same file paths, stub bytes, and eligibility rules as
79
84
  * `postTurnTruncateToolResults`, whose `TRUNCATION_MARKER` guard then skips
@@ -89,7 +94,15 @@ export function spoolAndStubOversizedToolResults(
89
94
  blocks: ContentBlock[],
90
95
  options: {
91
96
  conversationDir: string;
92
- toolNameById: (toolUseId: string) => string | undefined;
97
+ /**
98
+ * The originating call for a `tool_use_id`. A `tool_result` carries only
99
+ * the id, and eligibility turns on both the tool's name and the path it
100
+ * was pointed at, so the two travel together rather than as separate
101
+ * lookups that could disagree.
102
+ */
103
+ toolCallById: (
104
+ toolUseId: string,
105
+ ) => { name: string; input: Record<string, unknown> } | undefined;
93
106
  },
94
107
  ): number {
95
108
  let stubbedCount = 0;
@@ -98,7 +111,8 @@ export function spoolAndStubOversizedToolResults(
98
111
  if (block.type !== "tool_result") {
99
112
  continue;
100
113
  }
101
- if (!isSpoolEligible(block, options.toolNameById(block.tool_use_id))) {
114
+ const toolCall = options.toolCallById(block.tool_use_id);
115
+ if (!isSpoolEligible(block, toolCall?.name, toolCall?.input)) {
102
116
  continue;
103
117
  }
104
118
 
@@ -401,7 +401,7 @@ export function createToolExecutor(
401
401
  trustClass: resolveTrustClass(turnTrust),
402
402
  executionChannel: turnTrust.sourceChannel,
403
403
  requestOrigin: ctx.currentTurnRequestOrigin,
404
- sourceActorPrincipalId: turnTrust.guardianPrincipalId,
404
+ sourceActorPrincipalId: ctx.getTurnActorPrincipalId(),
405
405
  callSessionId: ctx.callSessionId,
406
406
  triggeredBySurfaceAction:
407
407
  ctx.surfaceActionRequestIds?.has(ctx.currentRequestId ?? "") ?? false,
@@ -6,7 +6,17 @@
6
6
  * single-row projection per conversation (conversation_assistant_attention_state).
7
7
  */
8
8
 
9
- import { and, desc, eq, inArray, isNull, lt, or, sql } from "drizzle-orm";
9
+ import {
10
+ and,
11
+ desc,
12
+ eq,
13
+ inArray,
14
+ isNull,
15
+ lt,
16
+ or,
17
+ type SQL,
18
+ sql,
19
+ } from "drizzle-orm";
10
20
  import { v4 as uuid } from "uuid";
11
21
 
12
22
  import { UserError } from "../util/errors.js";
@@ -87,6 +97,24 @@ export function hasUnseenLatestAssistantMessage(
87
97
  );
88
98
  }
89
99
 
100
+ /**
101
+ * SQL twin of {@link hasUnseenLatestAssistantMessage}: conditions over
102
+ * `conversation_assistant_attention_state` selecting rows whose latest
103
+ * assistant cursor is ahead of the last-seen cursor. Shared by
104
+ * {@link listConversationAttention} and `countUnreadConversations`
105
+ * (`conversation-queries.ts`) so every SQL reader of "unseen" agrees with
106
+ * the TS predicate.
107
+ */
108
+ export function unseenAttentionStateConditions(): SQL[] {
109
+ return [
110
+ sql`${conversationAssistantAttentionState.latestAssistantMessageAt} IS NOT NULL`,
111
+ or(
112
+ isNull(conversationAssistantAttentionState.lastSeenAssistantMessageAt),
113
+ sql`${conversationAssistantAttentionState.lastSeenAssistantMessageAt} < ${conversationAssistantAttentionState.latestAssistantMessageAt}`,
114
+ )!,
115
+ ];
116
+ }
117
+
90
118
  // ── Row mappers ──────────────────────────────────────────────────────
91
119
 
92
120
  function rowToEvent(
@@ -654,15 +682,7 @@ export function listConversationAttention(
654
682
 
655
683
  if (filterState === "unseen") {
656
684
  // Unseen: latest assistant message exists but no seen cursor, or seen cursor is behind latest
657
- conditions.push(
658
- sql`${conversationAssistantAttentionState.latestAssistantMessageAt} IS NOT NULL`,
659
- );
660
- conditions.push(
661
- or(
662
- isNull(conversationAssistantAttentionState.lastSeenAssistantMessageAt),
663
- sql`${conversationAssistantAttentionState.lastSeenAssistantMessageAt} < ${conversationAssistantAttentionState.latestAssistantMessageAt}`,
664
- )!,
665
- );
685
+ conditions.push(...unseenAttentionStateConditions());
666
686
  } else if (filterState === "seen") {
667
687
  // Seen: seen cursor equals latest assistant message
668
688
  conditions.push(
@@ -8,6 +8,7 @@ import {
8
8
  } from "../security/untrusted-content.js";
9
9
  import { getLogger } from "../util/logger.js";
10
10
  import { isLexicalBackfillComplete } from "./checkpoints.js";
11
+ import { unseenAttentionStateConditions } from "./conversation-attention-store.js";
11
12
  import type { ConversationRow } from "./conversation-crud.js";
12
13
  import { parseConversation } from "./conversation-crud.js";
13
14
  import { ensureDisplayOrderMigration } from "./conversation-display-order-migration.js";
@@ -21,7 +22,11 @@ import {
21
22
  resolveMessageContentBlocks,
22
23
  } from "./message-content-file.js";
23
24
  import { rawAll } from "./raw-query.js";
24
- import { conversations, messages } from "./schema/index.js";
25
+ import {
26
+ conversationAssistantAttentionState,
27
+ conversations,
28
+ messages,
29
+ } from "./schema/index.js";
25
30
 
26
31
  const log = getLogger("conversation-store");
27
32
 
@@ -169,6 +174,26 @@ function surfacedVisibilitySql(alias = "conversations"): string {
169
174
  );
170
175
  }
171
176
 
177
+ /**
178
+ * Raw SQL predicate for "not an automated background/scheduled row".
179
+ *
180
+ * A background or scheduled row counts as foreground only once it has been
181
+ * explicitly surfaced. {@link standardListingVisibilitySql} already admits
182
+ * such rows through its surfaced and custom-group arms, so a caller that
183
+ * must distinguish "visible in the listing" from "user-facing foreground"
184
+ * (unread counting) applies this on top.
185
+ *
186
+ * The SQL twin of `isBackgroundConversation` in the web client's
187
+ * `utils/conversation-predicates.ts`.
188
+ */
189
+ function notBackgroundVisibilitySql(alias = "conversations"): string {
190
+ return (
191
+ `NOT ((${alias}.conversation_type IN ('background', 'scheduled')` +
192
+ ` OR COALESCE(${alias}.group_id, 'system:all') IN ('system:background', 'system:scheduled'))` +
193
+ ` AND ${alias}.surfaced_at IS NULL)`
194
+ );
195
+ }
196
+
172
197
  /**
173
198
  * SQL predicate selecting which bucket {@link listConversations} and
174
199
  * {@link countConversations} return, keyed by the canonical
@@ -443,6 +468,54 @@ export function countConversations(
443
468
  return total;
444
469
  }
445
470
 
471
+ /**
472
+ * Count of foreground conversations whose latest assistant message is unseen.
473
+ *
474
+ * The server-side twin of the web client's `contributesToUnreadCount`
475
+ * predicate (`clients/web/src/utils/conversation-predicates.ts`), so the
476
+ * count returned by `GET /v1/conversations/unread-count` always matches what
477
+ * the sidebar's unread indicators would sum to over the full list.
478
+ *
479
+ * **Two definitions of one rule.** Changing what counts here means changing
480
+ * the client predicate too. Both sides assert the same named scenario matrix
481
+ * ("unread-count contract") so a one-sided change is visible in review: see
482
+ * `__tests__/conversation-list-routes.test.ts` here and
483
+ * `conversation-predicates.test.ts` there. The duplication exists only to
484
+ * keep a fallback for assistants without this route, and goes away with it.
485
+ *
486
+ * The rules:
487
+ *
488
+ * - visible in the standard (Recents) listing ({@link conversationTypeClause}),
489
+ * - not archived,
490
+ * - not an unsurfaced background/scheduled row
491
+ * ({@link notBackgroundVisibilitySql}), which excludes automated rows the
492
+ * listing admits through its custom-group arm,
493
+ * - unseen per the attention projection
494
+ * ({@link unseenAttentionStateConditions}); conversations without a
495
+ * projection row read as seen, hence the inner join.
496
+ */
497
+ export function countUnreadConversations(): number {
498
+ ensureGroupMigration();
499
+ const db = getDb();
500
+ const [{ total }] = db
501
+ .select({ total: count() })
502
+ .from(conversations)
503
+ .innerJoin(
504
+ conversationAssistantAttentionState,
505
+ eq(conversationAssistantAttentionState.conversationId, conversations.id),
506
+ )
507
+ .where(
508
+ and(
509
+ conversationTypeClause("standard"),
510
+ isNull(conversations.archivedAt),
511
+ sql.raw(notBackgroundVisibilitySql()),
512
+ ...unseenAttentionStateConditions(),
513
+ ),
514
+ )
515
+ .all();
516
+ return total;
517
+ }
518
+
446
519
  /**
447
520
  * Check whether the last user message in a conversation is a tool_result-only
448
521
  * message (i.e., not a real user-typed message). This is used by undo() to
@@ -75,6 +75,26 @@ describe("managedSpeechTranscribe", () => {
75
75
  expect(JSON.parse(init.body as string)).not.toHaveProperty("source");
76
76
  });
77
77
 
78
+ test("sends the spoken language when one is given", async () => {
79
+ // The platform forwards this to Deepgram, which otherwise decodes the
80
+ // audio as English rather than detecting its language.
81
+ await managedSpeechTranscribe({
82
+ audio: AUDIO,
83
+ mimeType: "audio/wav",
84
+ language: "multi",
85
+ });
86
+ const [, init] = mockClient!.fetch.mock.calls[0] as [string, RequestInit];
87
+ expect(JSON.parse(init.body as string).language).toBe("multi");
88
+ });
89
+
90
+ test("omits language when not provided", async () => {
91
+ // An absent field and an empty one are different requests upstream, and
92
+ // the empty one fails the platform serializer.
93
+ await managedSpeechTranscribe({ audio: AUDIO, mimeType: "audio/wav" });
94
+ const [, init] = mockClient!.fetch.mock.calls[0] as [string, RequestInit];
95
+ expect(JSON.parse(init.body as string)).not.toHaveProperty("language");
96
+ });
97
+
78
98
  test("returns unavailable when no platform client resolves", async () => {
79
99
  mockClient = null;
80
100
  const result = await managedSpeechTranscribe({
@@ -90,6 +90,14 @@ export async function managedSpeechTranscribe(input: {
90
90
  audio: Buffer;
91
91
  mimeType: string;
92
92
  source?: string;
93
+ /**
94
+ * Spoken language to decode: a BCP-47 code, or `"multi"` for nova-3
95
+ * code-switching. Omitted means the platform sends none, which Deepgram
96
+ * decodes as English rather than detecting the language. Older platform
97
+ * builds that predate the field ignore it, so sending one is safe before
98
+ * the platform side deploys.
99
+ */
100
+ language?: string;
93
101
  signal?: AbortSignal;
94
102
  }): Promise<ManagedSpeechResult<ManagedSpeechTranscription>> {
95
103
  const resolved = await resolveClient();
@@ -107,6 +115,7 @@ export async function managedSpeechTranscribe(input: {
107
115
  audioBase64: input.audio.toString("base64"),
108
116
  mimeType: input.mimeType,
109
117
  ...(input.source !== undefined ? { source: input.source } : {}),
118
+ ...(input.language ? { language: input.language } : {}),
110
119
  }),
111
120
  signal: input.signal,
112
121
  },