@vellumai/assistant 0.11.2-dev.202608071620.8afd4b3 → 0.11.2-dev.202608071719.8f7a9f1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.2-dev.202608071620.8afd4b3",
3
+ "version": "0.11.2-dev.202608071719.8f7a9f1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -86,6 +86,7 @@ import {
86
86
  MessageQueue,
87
87
  type QueuedMessage,
88
88
  } from "../daemon/conversation-queue-manager.js";
89
+ import type { TrustContext } from "../daemon/trust-context-types.js";
89
90
 
90
91
  // ---------------------------------------------------------------------------
91
92
  // Fake context — captures preactivation calls, satisfies the bare minimum
@@ -172,6 +173,7 @@ function makeQueuedMessage(opts: {
172
173
  content?: string;
173
174
  turnInterfaceContext?: TurnInterfaceContext;
174
175
  sourceActorPrincipalId?: string;
176
+ trustContext?: TrustContext;
175
177
  }): QueuedMessage {
176
178
  return {
177
179
  content: opts.content ?? "follow up",
@@ -185,6 +187,7 @@ function makeQueuedMessage(opts: {
185
187
  authContext: opts.sourceActorPrincipalId
186
188
  ? ({ actorPrincipalId: opts.sourceActorPrincipalId } as never)
187
189
  : undefined,
190
+ trustContext: opts.trustContext,
188
191
  };
189
192
  }
190
193
 
@@ -371,6 +374,126 @@ describe("drainQueue preactivation re-add for host-proxy interfaces", () => {
371
374
  expect(ctx.currentTurnSourceActorPrincipalId).toBe("trusted-contact-user");
372
375
  });
373
376
 
377
+ test("drainSingleMessage runs the turn under the queued sender's trust, not the live slot", async () => {
378
+ // The conversation-level slot holds whichever actor sent most recently.
379
+ // A message that waited while someone else sent must still run as its own
380
+ // sender: trust decides `trustClass`, `executionChannel`, and
381
+ // `requesterExternalUserId`, so reading the slot hands the whole
382
+ // tool-approval path the wrong identity in both directions -- a contact
383
+ // inheriting guardian self-approval, or a guardian's own call escalating
384
+ // back to her as a contact's grant request.
385
+ const contactTrust: TrustContext = {
386
+ trustClass: "trusted_contact",
387
+ sourceChannel: "slack",
388
+ requesterExternalUserId: "U-contact",
389
+ };
390
+ const queue = new MessageQueue();
391
+ queue.push(
392
+ makeQueuedMessage({
393
+ requestId: "req-contact",
394
+ trustContext: contactTrust,
395
+ }),
396
+ );
397
+ const ctx = makeFakeContext({ queue });
398
+ // Someone else sent after this message was queued, moving the slot.
399
+ ctx.trustContext = {
400
+ trustClass: "guardian",
401
+ sourceChannel: "vellum",
402
+ requesterExternalUserId: "guardian-principal",
403
+ };
404
+
405
+ await drainQueue(ctx);
406
+
407
+ expect(ctx.currentTurnTrustContext?.trustClass).toBe("trusted_contact");
408
+ expect(ctx.currentTurnTrustContext?.requesterExternalUserId).toBe(
409
+ "U-contact",
410
+ );
411
+ expect(ctx.currentTurnTrustContext?.sourceChannel).toBe("slack");
412
+ // The slot itself is left alone; only the turn's view is corrected.
413
+ expect(ctx.trustContext?.trustClass).toBe("guardian");
414
+ });
415
+
416
+ test("buildPassthroughBatch refuses to coalesce two channel senders", async () => {
417
+ // Channel senders carry no principal, so the `sourceActorPrincipalId`
418
+ // boundary sees `undefined === undefined` and would batch two different
419
+ // Slack contacts into one turn running under the head's trust. The batch
420
+ // must split on the sender's trust identity instead.
421
+ const ifCtx: TurnInterfaceContext = {
422
+ userMessageInterface: "web",
423
+ assistantMessageInterface: "web",
424
+ };
425
+ const queue = new MessageQueue();
426
+ queue.push(
427
+ makeQueuedMessage({
428
+ requestId: "req-contact-a",
429
+ content: "from A",
430
+ turnInterfaceContext: ifCtx,
431
+ trustContext: {
432
+ trustClass: "trusted_contact",
433
+ sourceChannel: "slack",
434
+ requesterExternalUserId: "U-alex",
435
+ },
436
+ }),
437
+ );
438
+ queue.push(
439
+ makeQueuedMessage({
440
+ requestId: "req-contact-b",
441
+ content: "from B",
442
+ turnInterfaceContext: ifCtx,
443
+ trustContext: {
444
+ trustClass: "trusted_contact",
445
+ sourceChannel: "slack",
446
+ requesterExternalUserId: "U-blake",
447
+ },
448
+ }),
449
+ );
450
+ const ctx = makeFakeContext({ queue, turnInterfaceContext: ifCtx });
451
+
452
+ await drainQueue(ctx);
453
+
454
+ // B stays queued: it gets its own turn under its own trust.
455
+ expect(queue.length).toBe(1);
456
+ expect(queue.peek(0)?.requestId).toBe("req-contact-b");
457
+ expect(ctx.currentTurnTrustContext?.requesterExternalUserId).toBe("U-alex");
458
+ });
459
+
460
+ test("buildPassthroughBatch still coalesces two messages from the same sender", async () => {
461
+ // Sensitivity check on the split above: identical trust must still batch,
462
+ // otherwise the boundary would be splitting on something incidental and
463
+ // the test above would pass for the wrong reason.
464
+ const ifCtx: TurnInterfaceContext = {
465
+ userMessageInterface: "web",
466
+ assistantMessageInterface: "web",
467
+ };
468
+ const sameTrust: TrustContext = {
469
+ trustClass: "trusted_contact",
470
+ sourceChannel: "slack",
471
+ requesterExternalUserId: "U-alex",
472
+ };
473
+ const queue = new MessageQueue();
474
+ queue.push(
475
+ makeQueuedMessage({
476
+ requestId: "req-a1",
477
+ content: "first",
478
+ turnInterfaceContext: ifCtx,
479
+ trustContext: { ...sameTrust },
480
+ }),
481
+ );
482
+ queue.push(
483
+ makeQueuedMessage({
484
+ requestId: "req-a2",
485
+ content: "second",
486
+ turnInterfaceContext: ifCtx,
487
+ trustContext: { ...sameTrust },
488
+ }),
489
+ );
490
+ const ctx = makeFakeContext({ queue, turnInterfaceContext: ifCtx });
491
+
492
+ await drainQueue(ctx);
493
+
494
+ expect(queue.length).toBe(0);
495
+ });
496
+
374
497
  test("drainSingleMessage does NOT re-add 'app-control' for web-sourced message when no capable client is connected", async () => {
375
498
  // mockCapabilityClients remains [] (reset by afterEach from prior test)
376
499
  const queue = new MessageQueue();
@@ -556,6 +556,98 @@ describe("Conversation message queue", () => {
556
556
  await new Promise((r) => setTimeout(r, 10));
557
557
  });
558
558
 
559
+ test("enqueueMessage captures the sender's trust, immune to a later slot change", async () => {
560
+ // Trust must ride with the queued message. The conversation-level slot is
561
+ // rewritten by whoever sends next, so a message that reads it at drain time
562
+ // would run as the wrong actor. Capturing at enqueue is what makes the
563
+ // drain's identity independent of who sent afterwards.
564
+ const conversation = makeConversation();
565
+ await conversation.loadFromDb();
566
+
567
+ conversation.setTrustContext({
568
+ trustClass: "trusted_contact",
569
+ sourceChannel: "slack",
570
+ requesterExternalUserId: "U-contact",
571
+ });
572
+
573
+ const p1 = conversation.processMessage({
574
+ content: "msg-1",
575
+ attachments: [],
576
+ onEvent: () => {},
577
+ requestId: "req-1",
578
+ });
579
+ await waitForPendingRun(1);
580
+
581
+ conversation.enqueueMessage({ content: "msg-2", requestId: "req-2" });
582
+
583
+ // A different actor sends while the message waits, moving the slot.
584
+ conversation.setTrustContext({
585
+ trustClass: "guardian",
586
+ sourceChannel: "vellum",
587
+ requesterExternalUserId: "guardian-principal",
588
+ });
589
+
590
+ const queued = conversation.queue.peek(0);
591
+ expect(queued?.requestId).toBe("req-2");
592
+ expect(queued?.trustContext?.trustClass).toBe("trusted_contact");
593
+ expect(queued?.trustContext?.requesterExternalUserId).toBe("U-contact");
594
+
595
+ await resolveRun(0);
596
+ await p1;
597
+ await new Promise((r) => setTimeout(r, 10));
598
+ });
599
+
600
+ test("a drained turn keeps its sender's trust once the agent loop is running", async () => {
601
+ // Exercises the real drain -> runAgentLoop ordering against a live
602
+ // Conversation. The loop re-initializes the per-turn trust snapshot on
603
+ // entry, so a drain that only stamped the field before calling it would
604
+ // have that stamp silently undone and the turn would execute as whoever
605
+ // sent most recently. Asserting inside the run is the point: checking
606
+ // before the loop starts passes either way.
607
+ const conversation = makeConversation();
608
+ await conversation.loadFromDb();
609
+
610
+ conversation.setTrustContext({
611
+ trustClass: "trusted_contact",
612
+ sourceChannel: "slack",
613
+ requesterExternalUserId: "U-contact",
614
+ });
615
+
616
+ const p1 = conversation.processMessage({
617
+ content: "msg-1",
618
+ attachments: [],
619
+ onEvent: () => {},
620
+ requestId: "req-1",
621
+ });
622
+ await waitForPendingRun(1);
623
+
624
+ conversation.enqueueMessage({ content: "msg-2", requestId: "req-2" });
625
+
626
+ // The guardian sends while the contact's message waits, moving the slot.
627
+ conversation.setTrustContext({
628
+ trustClass: "guardian",
629
+ sourceChannel: "vellum",
630
+ requesterExternalUserId: "guardian-principal",
631
+ });
632
+
633
+ // Finish the first turn so the queue drains into a second run.
634
+ await resolveRun(0);
635
+ await p1;
636
+ await waitForPendingRun(2);
637
+
638
+ // Read while run 2 is in flight: this is what tool setup and the
639
+ // guardian-request producers resolve against.
640
+ expect(conversation.currentTurnTrustContext?.trustClass).toBe(
641
+ "trusted_contact",
642
+ );
643
+ expect(conversation.currentTurnTrustContext?.requesterExternalUserId).toBe(
644
+ "U-contact",
645
+ );
646
+
647
+ await resolveRun(1);
648
+ await new Promise((r) => setTimeout(r, 10));
649
+ });
650
+
559
651
  test("[experimental] queued passthrough siblings drain as a single batched run", async () => {
560
652
  const conversation = makeConversation();
561
653
  await conversation.loadFromDb();
@@ -1,7 +1,44 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
1
3
  import { describe, expect, test } from "bun:test";
2
4
 
3
5
  import { PROVIDER_SEED_DATA } from "../oauth/seed-providers.js";
4
6
 
7
+ const REPO_ROOT = dirname(dirname(dirname(import.meta.dir)));
8
+ const WEB_PUBLIC_DIR = join(REPO_ROOT, "clients/web/public");
9
+ const INTEGRATION_ICON_SOURCE = join(
10
+ REPO_ROOT,
11
+ "clients/web/src/components/integrations/integration-icon.tsx",
12
+ );
13
+
14
+ /**
15
+ * Provider keys the web client draws without a `BUNDLED_LOGO_URLS` entry.
16
+ * Google's mark is multi-colour, so it ships as the `GoogleLogo` component
17
+ * and is returned before the bundled-asset lookup runs.
18
+ */
19
+ const COMPONENT_RENDERED_PROVIDERS = new Set(["google"]);
20
+
21
+ /** `publicAsset("/images/...")` paths from `BUNDLED_LOGO_URLS`, by key. */
22
+ function readBundledLogoMap(): Map<string, string> {
23
+ const source = readFileSync(INTEGRATION_ICON_SOURCE, "utf8");
24
+ const block = source.match(
25
+ /const BUNDLED_LOGO_URLS: Record<string, string> = \{([\s\S]*?)\n\};/,
26
+ );
27
+ if (!block) {
28
+ throw new Error(
29
+ `Could not find BUNDLED_LOGO_URLS in ${INTEGRATION_ICON_SOURCE}. If it ` +
30
+ `was renamed or restructured, update this test rather than deleting it.`,
31
+ );
32
+ }
33
+ const entries = new Map<string, string>();
34
+ for (const [, key, path] of block[1]!.matchAll(
35
+ /(\w+):\s*publicAsset\("([^"]+)"\)/g,
36
+ )) {
37
+ entries.set(key!, path!);
38
+ }
39
+ return entries;
40
+ }
41
+
5
42
  /**
6
43
  * Allowed CDN prefixes for the ``logoUrl`` field on ``PROVIDER_SEED_DATA``
7
44
  * (``assistant/src/oauth/seed-providers.ts``):
@@ -41,3 +78,31 @@ describe("PROVIDER_SEED_DATA logo URLs", () => {
41
78
  expect(invalid).toEqual([]);
42
79
  });
43
80
  });
81
+
82
+ /**
83
+ * The `logoUrl` above is a fallback for providers registered at runtime. Every
84
+ * provider we seed ourselves must draw from an asset we ship, because an icon
85
+ * CDN can drop a brand at any time and the client then degrades to an initials
86
+ * avatar with nothing in CI to notice: the prefix check above passes just as
87
+ * happily for a URL that 404s. Simple Icons hosts no Microsoft mark and no
88
+ * Slack mark, so the seeded URLs for those brands do not resolve there.
89
+ */
90
+ describe("PROVIDER_SEED_DATA bundled logo coverage", () => {
91
+ test("every seeded provider renders from a bundled asset", () => {
92
+ const bundled = readBundledLogoMap();
93
+ const uncovered = Object.keys(PROVIDER_SEED_DATA).filter(
94
+ (provider) =>
95
+ !bundled.has(provider) && !COMPONENT_RENDERED_PROVIDERS.has(provider),
96
+ );
97
+
98
+ expect(uncovered).toEqual([]);
99
+ });
100
+
101
+ test("every bundled logo path resolves to a file on disk", () => {
102
+ const missingFiles = [...readBundledLogoMap()]
103
+ .filter(([, path]) => !existsSync(join(WEB_PUBLIC_DIR, path)))
104
+ .map(([provider, path]) => ({ provider, path }));
105
+
106
+ expect(missingFiles).toEqual([]);
107
+ });
108
+ });
@@ -366,6 +366,13 @@ export async function runAgentLoopImpl(
366
366
  * scheduled execute turn attributes its LLM spend to that firing.
367
367
  */
368
368
  cronRunId?: string | null;
369
+ /**
370
+ * Trust this turn runs under. Queue drains pass the trust captured from
371
+ * the sender at enqueue; without it the initialization below would reset
372
+ * the turn to the conversation slot, which holds whichever actor sent
373
+ * most recently rather than the one this turn belongs to.
374
+ */
375
+ turnTrustContext?: TrustContext;
369
376
  },
370
377
  ): Promise<void> {
371
378
  if (!ctx.abortController) {
@@ -376,9 +383,12 @@ export async function runAgentLoopImpl(
376
383
  // voice-session-bridge, regenerate, etc.) that invoke runAgentLoop directly
377
384
  // without going through processMessage/drainQueue. This ensures the system
378
385
  // prompt callback always reads a valid snapshot rather than undefined.
379
- // processMessage/drainQueue set these fields before calling runAgentLoop;
380
- // those existing assignments remain correct and are merely redundant here.
381
- ctx.currentTurnTrustContext = ctx.trustContext;
386
+ //
387
+ // A queue drain runs a message whose sender may not be the conversation's
388
+ // most recent one, so it passes that sender's trust explicitly. Falling back
389
+ // to the slot here would undo the drain's stamp and hand the turn back to
390
+ // whoever sent last.
391
+ ctx.currentTurnTrustContext = options?.turnTrustContext ?? ctx.trustContext;
382
392
  ctx.currentTurnChannelCapabilities = ctx.channelCapabilities;
383
393
 
384
394
  // Re-resolve the system prompt under the snapshots just set and push it into
@@ -565,6 +565,12 @@ export interface EnqueueMessageOptions {
565
565
  sourceActorPrincipalId?: string;
566
566
  /** Auth context snapshot captured for queued turn-scoped authorization. */
567
567
  authContext?: AuthContext;
568
+ /**
569
+ * Sender's trust, for the drain to run this message under. Defaults to the
570
+ * conversation's trust at enqueue time, which the sending route has just
571
+ * set to this sender.
572
+ */
573
+ trustContext?: TrustContext;
568
574
  }
569
575
 
570
576
  // ── enqueueMessage ───────────────────────────────────────────────────
@@ -593,6 +599,9 @@ export function enqueueMessage(
593
599
  options.sourceActorPrincipalId ??
594
600
  ctx.currentTurnSourceActorPrincipalId ??
595
601
  queuedAuthContext?.actorPrincipalId;
602
+ // Deliberately not falling back to `currentTurnTrustContext`: that is the
603
+ // in-flight turn's actor, which is precisely who this message is not from.
604
+ const queuedTrustContext = options.trustContext ?? ctx.trustContext;
596
605
 
597
606
  if (!ctx.isProcessing()) {
598
607
  return { queued: false, requestId };
@@ -619,6 +628,7 @@ export function enqueueMessage(
619
628
  isInteractive,
620
629
  sourceActorPrincipalId,
621
630
  authContext: queuedAuthContext,
631
+ trustContext: queuedTrustContext,
622
632
  transport,
623
633
  displayContent,
624
634
  sentAt: Date.now(),
@@ -668,6 +678,14 @@ export interface PersistMessageOptions {
668
678
  metadata?: Record<string, unknown>;
669
679
  displayContent?: string;
670
680
  clientMessageId?: string;
681
+ /**
682
+ * Trust to attribute the stored row to. Queue drains pass the sender's
683
+ * captured trust so persisted provenance names the same actor the turn
684
+ * executes as; the conversation slot may by then hold someone else.
685
+ * Defaults to the conversation's trust, which is correct for callers
686
+ * persisting a message the current actor just sent.
687
+ */
688
+ trustContext?: TrustContext;
671
689
  /**
672
690
  * Persist the row without indexing it (no memory segments, embeddings, or
673
691
  * lexical-index entry). For machine-authored prompts that must not enter
@@ -844,7 +862,9 @@ export async function persistQueuedMessageBody(
844
862
  extractTurnChannelContext(metadata) ?? ctx.getTurnChannelContext();
845
863
  const turnIfCtx =
846
864
  extractTurnInterfaceContext(metadata) ?? ctx.getTurnInterfaceContext();
847
- const provenance = provenanceFromTrustContext(ctx.trustContext);
865
+ const provenance = provenanceFromTrustContext(
866
+ options.trustContext ?? ctx.trustContext,
867
+ );
848
868
  const imageSourcePaths = extractImageSourcePaths(attachments);
849
869
 
850
870
  // Strip the transient `slackInbound` carrier key from the persisted
@@ -62,6 +62,7 @@ import { getModelInfo } from "./handlers/config-model.js";
62
62
  import { preactivateHostProxySkills } from "./host-proxy-preactivation.js";
63
63
  import type { UserMessageAttachment } from "./message-protocol.js";
64
64
  import { buildTransportHints } from "./transport-hints.js";
65
+ import { sameTrustIdentity, type TrustContext } from "./trust-context-types.js";
65
66
  import { resolveVerificationSessionIntent } from "./verification-session-intent.js";
66
67
 
67
68
  const log = getLogger("conversation-process");
@@ -301,6 +302,13 @@ async function buildPassthroughBatch(
301
302
  if (candidate.sourceActorPrincipalId !== head.sourceActorPrincipalId) {
302
303
  break;
303
304
  }
305
+ // Channel senders carry no principal, so the check above leaves two
306
+ // different Slack contacts looking identical (`undefined === undefined`).
307
+ // The batch runs under a single trust context, so split on the sender's
308
+ // trust identity too or a tail executes with the head's privileges.
309
+ if (!sameTrustIdentity(candidate.trustContext, head.trustContext)) {
310
+ break;
311
+ }
304
312
  if (classifySlash(candidate.content) !== "passthrough") {
305
313
  break;
306
314
  }
@@ -795,7 +803,11 @@ async function drainSingleMessage(
795
803
 
796
804
  // Snapshot persona context at turn start so later tool turns can't pick up
797
805
  // a different actor's context if a concurrent request mutates the live fields.
798
- conversation.currentTurnTrustContext = conversation.trustContext;
806
+ // Trust comes from the queued message, not the live slot: the slot holds
807
+ // whichever actor sent most recently, which is this sender only when nobody
808
+ // else sent while this message waited.
809
+ conversation.currentTurnTrustContext =
810
+ next.trustContext ?? conversation.trustContext;
799
811
  conversation.currentTurnChannelCapabilities =
800
812
  conversation.channelCapabilities;
801
813
 
@@ -1135,6 +1147,9 @@ async function drainSingleMessage(
1135
1147
  metadata: { ...next.metadata, sentAt: next.sentAt },
1136
1148
  displayContent: next.displayContent,
1137
1149
  clientMessageId: next.clientMessageId,
1150
+ // Attribute the stored row to the sender this turn runs as, not to
1151
+ // whoever happens to occupy the conversation slot at drain time.
1152
+ trustContext: next.trustContext,
1138
1153
  ...(next.transport?.clientOs
1139
1154
  ? { requestClientOs: next.transport.clientOs }
1140
1155
  : {}),
@@ -1258,7 +1273,14 @@ async function drainSingleMessage(
1258
1273
  isUserMessage?: boolean;
1259
1274
  titleText?: string;
1260
1275
  isHiddenPrompt?: boolean;
1261
- } = { isUserMessage: true };
1276
+ turnTrustContext?: TrustContext;
1277
+ } = {
1278
+ isUserMessage: true,
1279
+ // Carry the sender's trust into the run. The loop re-initializes the
1280
+ // per-turn snapshot on entry, so without this the stamp above is undone
1281
+ // and the turn reverts to the conversation's most recent actor.
1282
+ turnTrustContext: conversation.currentTurnTrustContext,
1283
+ };
1262
1284
  if (next.isInteractive !== undefined) {
1263
1285
  drainLoopOptions.isInteractive = next.isInteractive;
1264
1286
  }
@@ -1383,7 +1405,12 @@ async function drainBatch(
1383
1405
 
1384
1406
  // Snapshot persona context at turn start so later tool turns can't pick up
1385
1407
  // a different actor's context if a concurrent request mutates the live fields.
1386
- conversation.currentTurnTrustContext = conversation.trustContext;
1408
+ // The head's trust governs the batch, which is sound only because
1409
+ // `buildPassthroughBatch` refuses to coalesce messages from different
1410
+ // actors; without that boundary this would run a tail under the head's
1411
+ // trust.
1412
+ conversation.currentTurnTrustContext =
1413
+ head.trustContext ?? conversation.trustContext;
1387
1414
  conversation.currentTurnChannelCapabilities =
1388
1415
  conversation.channelCapabilities;
1389
1416
 
@@ -1488,6 +1515,9 @@ async function drainBatch(
1488
1515
  metadata: { ...qm.metadata, sentAt: qm.sentAt },
1489
1516
  displayContent: qm.displayContent,
1490
1517
  clientMessageId: qm.clientMessageId,
1518
+ // Same attribution rule as the single-message drain. Batch members
1519
+ // share one sender, so every row here names that sender.
1520
+ trustContext: qm.trustContext,
1491
1521
  ...(qm.transport?.clientOs
1492
1522
  ? { requestClientOs: qm.transport.clientOs }
1493
1523
  : {}),
@@ -1719,8 +1749,12 @@ async function drainBatch(
1719
1749
  titleText?: string;
1720
1750
  isHiddenPrompt?: boolean;
1721
1751
  notifyUserMessageId?: string;
1752
+ turnTrustContext?: TrustContext;
1722
1753
  } = {
1723
1754
  isUserMessage: true,
1755
+ // Same reason as the single-message drain: the loop re-initializes the
1756
+ // per-turn snapshot, so the head's trust has to travel with the call.
1757
+ turnTrustContext: conversation.currentTurnTrustContext,
1724
1758
  };
1725
1759
  if (lastPushEligibleUserMessageId !== undefined) {
1726
1760
  drainLoopOptions.notifyUserMessageId = lastPushEligibleUserMessageId;
@@ -14,6 +14,7 @@ import type { AuthContext } from "../runtime/auth/types.js";
14
14
  import { getLogger } from "../util/logger.js";
15
15
  import type { UserMessageAttachment } from "./message-protocol.js";
16
16
  import type { ConversationTransportMetadata } from "./message-types/conversations.js";
17
+ import type { TrustContext } from "./trust-context-types.js";
17
18
 
18
19
  const log = getLogger("conversation-queue");
19
20
 
@@ -33,6 +34,15 @@ export interface QueuedMessage {
33
34
  sourceActorPrincipalId?: string;
34
35
  /** Full auth snapshot captured at enqueue time for turn-scoped authorization decisions. */
35
36
  authContext?: AuthContext;
37
+ /**
38
+ * Sender's trust captured at enqueue time. The conversation-level
39
+ * `trustContext` is a single mutable slot holding whichever actor last sent
40
+ * a message, so a drain that read it would run this message under a
41
+ * different actor's trust whenever another actor sent in between. Trust
42
+ * governs `trustClass`, `executionChannel`, and `requesterExternalUserId`,
43
+ * so reading the wrong one misroutes the whole tool-approval path.
44
+ */
45
+ trustContext?: TrustContext;
36
46
  /** Transport metadata snapshot captured at enqueue time, applied when this message becomes active. */
37
47
  transport?: ConversationTransportMetadata;
38
48
  /** Original user message text to persist to DB when recording intent stripping produced a different `content`. */
@@ -2661,6 +2661,12 @@ export class Conversation {
2661
2661
  * forwarded into {@link runAgentLoopImpl} and threaded to `recordUsage`.
2662
2662
  */
2663
2663
  cronRunId?: string | null;
2664
+ /**
2665
+ * See {@link runAgentLoopImpl}: trust this turn runs under. Queue
2666
+ * drains pass the sender's trust captured at enqueue so the run is not
2667
+ * reset to the conversation's most recent actor.
2668
+ */
2669
+ turnTrustContext?: TrustContext;
2664
2670
  },
2665
2671
  ): Promise<void> {
2666
2672
  const { onEvent, ...rest } = options ?? {};
@@ -67,3 +67,42 @@ export interface TrustContext {
67
67
  */
68
68
  requesterInteractionCount?: number;
69
69
  }
70
+
71
+ /**
72
+ * Whether two trust contexts describe the same acting identity at the same
73
+ * privilege, for callers that may only run work under one of them (batched
74
+ * turns being the case that matters).
75
+ *
76
+ * Compares the privilege (`trustClass`), the channel a grant is scoped to
77
+ * (`sourceChannel`), and every field that can carry who the actor is. The
78
+ * identity fields are covered exhaustively rather than by picking the usual
79
+ * ones: an ingress that populates only `requesterIdentifier` or
80
+ * `requesterContactId` would otherwise leave two distinct senders comparing
81
+ * equal on a pair of undefineds, which is the exact case this guards.
82
+ *
83
+ * Deliberately conservative: an absent field never matches a present one, so
84
+ * unknown identities are treated as distinct. Answering "different" when they
85
+ * match only costs a batching opportunity; answering "same" when they differ
86
+ * runs one actor's work under another's privileges.
87
+ */
88
+ export function sameTrustIdentity(
89
+ a: TrustContext | undefined,
90
+ b: TrustContext | undefined,
91
+ ): boolean {
92
+ if (a === b) {
93
+ return true;
94
+ }
95
+ if (!a || !b) {
96
+ return false;
97
+ }
98
+ return (
99
+ a.trustClass === b.trustClass &&
100
+ a.sourceChannel === b.sourceChannel &&
101
+ a.requesterExternalUserId === b.requesterExternalUserId &&
102
+ a.requesterChatId === b.requesterChatId &&
103
+ a.requesterIdentifier === b.requesterIdentifier &&
104
+ a.requesterContactId === b.requesterContactId &&
105
+ a.guardianExternalUserId === b.guardianExternalUserId &&
106
+ a.guardianPrincipalId === b.guardianPrincipalId
107
+ );
108
+ }