@vellumai/assistant 0.11.2-dev.202608071620.8afd4b3 → 0.11.2-dev.202608071820.0d9e564

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.202608071820.0d9e564",
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,174 @@ 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
+
651
+ test("a processMessage turn keeps its turn-start trust when the slot moves before the loop opens", async () => {
652
+ // processMessage is the third turn entry point, and the one a web turn
653
+ // takes on an idle conversation (the route only enqueues while
654
+ // isProcessing). It captures trust at turn start, then awaits several
655
+ // times before the agent loop opens. The conversation slot is writable
656
+ // throughout that window by paths that do not own this turn: live-voice
657
+ // hydration stamp-and-restore, pointer elevation, the voice bridge.
658
+ //
659
+ // Driving a real Conversation with only AgentLoop.run mocked is what makes
660
+ // this observable. A double that stubs runAgentLoop itself would skip the
661
+ // re-read entirely and pass either way.
662
+ const conversation = makeConversation();
663
+ await conversation.loadFromDb();
664
+
665
+ conversation.setTrustContext({
666
+ trustClass: "trusted_contact",
667
+ sourceChannel: "slack",
668
+ requesterExternalUserId: "U-contact",
669
+ });
670
+
671
+ // Land another actor's slot write inside the window, after the turn-start
672
+ // capture and before the loop opens. persistUserMessage is awaited there.
673
+ const originalPersist = conversation.persistUserMessage.bind(conversation);
674
+ let slotMoved = false;
675
+ (
676
+ conversation as unknown as {
677
+ persistUserMessage: typeof conversation.persistUserMessage;
678
+ }
679
+ ).persistUserMessage = async (opts) => {
680
+ const result = await originalPersist(opts);
681
+ conversation.setTrustContext({
682
+ trustClass: "guardian",
683
+ sourceChannel: "vellum",
684
+ requesterExternalUserId: "guardian-principal",
685
+ });
686
+ // Also move the per-turn field, which is writable out-of-band: a wake
687
+ // that settles inside this window restores its prior value there
688
+ // (agent-wake stamps at :1470 and restores in a `finally` at :1554).
689
+ // Covers both writers, so a fix that reads either one back at the agent
690
+ // loop call still fails this test.
691
+ conversation.currentTurnTrustContext = {
692
+ trustClass: "guardian",
693
+ sourceChannel: "vellum",
694
+ requesterExternalUserId: "guardian-principal",
695
+ };
696
+ slotMoved = true;
697
+ return result;
698
+ };
699
+
700
+ const p1 = conversation.processMessage({
701
+ content: "msg-1",
702
+ attachments: [],
703
+ onEvent: () => {},
704
+ requestId: "req-1",
705
+ });
706
+ await waitForPendingRun(1);
707
+
708
+ // Guard the test itself: if the injection stopped running, the assertions
709
+ // below would pass for the wrong reason.
710
+ expect(slotMoved).toBe(true);
711
+ expect(conversation.trustContext?.trustClass).toBe("guardian");
712
+
713
+ // Read mid-run: this is what tool setup and the guardian-request producers
714
+ // resolve against while the turn executes.
715
+ expect(conversation.currentTurnTrustContext?.trustClass).toBe(
716
+ "trusted_contact",
717
+ );
718
+ expect(conversation.currentTurnTrustContext?.requesterExternalUserId).toBe(
719
+ "U-contact",
720
+ );
721
+
722
+ await resolveRun(0);
723
+ await p1;
724
+ await new Promise((r) => setTimeout(r, 10));
725
+ });
726
+
559
727
  test("[experimental] queued passthrough siblings drain as a single batched run", async () => {
560
728
  const conversation = makeConversation();
561
729
  await conversation.loadFromDb();
@@ -164,7 +164,11 @@ function makeConversationWithPendingConfirmation(
164
164
  promoteToHead: (requestId: string) => ({ requestId }),
165
165
  },
166
166
  pendingSteerRepair: false,
167
- setTrustContext: () => {},
167
+ // Stores rather than discarding, so a test can observe which trust the
168
+ // route resolved and move the slot afterwards.
169
+ setTrustContext(this: { trustContext: unknown }, ctx: unknown) {
170
+ this.trustContext = ctx;
171
+ },
168
172
  updateClient: () => {},
169
173
  emitConfirmationStateChanged: () => {},
170
174
  emitActivityState: () => {},
@@ -354,3 +358,62 @@ describe("hidden sends to an idle conversation with a pending confirmation", ()
354
358
  expect(spies.agentLoopOptions()?.isHiddenPrompt).toBeUndefined();
355
359
  });
356
360
  });
361
+
362
+ describe("POST /messages turn trust", () => {
363
+ test("the idle send path runs its turn under the trust resolved for the request", async () => {
364
+ // The idle web path does not go through `processMessage`; it persists and
365
+ // calls `runAgentLoop` directly. Without the captured trust travelling
366
+ // with that call, the loop re-reads the conversation slot when it opens,
367
+ // and the slot is writable in between by paths that do not own this turn
368
+ // (channel ingress for another actor, live-voice hydration, pointer
369
+ // elevation, the voice bridge).
370
+ //
371
+ // The defect here is at the call site, not inside the loop, so observing
372
+ // the options the route passes is sufficient. The re-read *inside* the
373
+ // loop is covered separately against a real Conversation, since a stub
374
+ // like this one cannot see it.
375
+ const spies = makeConversationWithPendingConfirmation(false);
376
+ setConversation(CONV_ID, spies.conversation);
377
+
378
+ const conversation = spies.conversation as unknown as {
379
+ trustContext: unknown;
380
+ persistUserMessage: () => Promise<{ id: string; deduplicated: boolean }>;
381
+ };
382
+
383
+ // Another actor writes the slot inside the window, after the route
384
+ // resolves this request's trust and before the loop call.
385
+ let slotMoved = false;
386
+ conversation.persistUserMessage = async () => {
387
+ conversation.trustContext = {
388
+ trustClass: "trusted_contact",
389
+ sourceChannel: "slack",
390
+ requesterExternalUserId: "U-other-actor",
391
+ };
392
+ slotMoved = true;
393
+ return { id: "persisted-user-id", deduplicated: false };
394
+ };
395
+
396
+ const res = await callHandler(
397
+ (args) => handleSendMessage(args, makeDeps(spies.conversation)),
398
+ makeRequest({ content: "run a command" }),
399
+ undefined,
400
+ 202,
401
+ );
402
+
403
+ expect(res.status).toBe(202);
404
+ // Guard the test itself: if the injection stopped running the assertion
405
+ // below would pass for the wrong reason.
406
+ expect(slotMoved).toBe(true);
407
+ expect(
408
+ (conversation.trustContext as { trustClass?: string } | undefined)
409
+ ?.trustClass,
410
+ ).toBe("trusted_contact");
411
+
412
+ // The turn carries the trust this request resolved, not the moved slot.
413
+ const turnTrust = spies.agentLoopOptions()?.turnTrustContext as
414
+ | { trustClass?: string }
415
+ | undefined;
416
+ expect(turnTrust).toBeDefined();
417
+ expect(turnTrust?.trustClass).toBe("guardian");
418
+ });
419
+ });
@@ -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,21 @@ 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
+ // The invariant: a turn runs under the trust captured when that turn
388
+ // started, never under whatever the slot holds when the loop happens to
389
+ // open. Awaits sit between capture and this line, and the slot is writable
390
+ // throughout by paths that do not own the turn (channel ingress for another
391
+ // actor, live-voice hydration, pointer elevation, the voice bridge).
392
+ //
393
+ // Callers that own a turn are expected to capture at turn start and pass
394
+ // `turnTrustContext`. This has not been swept across all 13 call sites, so
395
+ // the fallback below is load-bearing for two different populations: callers
396
+ // that legitimately have no turn to capture (subagent manager, voice
397
+ // bridge, regenerate), and callers that should pass it and do not yet.
398
+ // Treat a caller reaching the fallback as unverified, not as correct.
399
+ // LUM-3148 removes the ambiguity by making trust ride the turn.
400
+ ctx.currentTurnTrustContext = options?.turnTrustContext ?? ctx.trustContext;
382
401
  ctx.currentTurnChannelCapabilities = ctx.channelCapabilities;
383
402
 
384
403
  // 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