@vellumai/assistant 0.10.11-dev.202607222029.495c516 → 0.10.11-dev.202607222129.31c06e5

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 (32) hide show
  1. package/package.json +1 -1
  2. package/src/__tests__/approval-source-link.test.ts +208 -0
  3. package/src/__tests__/plugin-import-boundary-guard.test.ts +1 -1
  4. package/src/__tests__/slack-notification-approval-card.test.ts +103 -20
  5. package/src/__tests__/tool-approval-seed-content-blocks.test.ts +179 -96
  6. package/src/api/events/memory-recalled.ts +59 -0
  7. package/src/api/events/memory-status.ts +29 -0
  8. package/src/api/index.ts +16 -0
  9. package/src/calls/__tests__/voice-triage-escalate.test.ts +58 -3
  10. package/src/calls/voice-session-bridge.ts +6 -2
  11. package/src/calls/voice-triage-escalate.ts +30 -1
  12. package/src/config/feature-flag-registry.json +9 -0
  13. package/src/daemon/conversation-tool-setup.ts +7 -3
  14. package/src/daemon/message-types/memory.ts +8 -46
  15. package/src/daemon/trust-context-types.ts +8 -0
  16. package/src/messaging/providers/slack/approval-source.ts +87 -0
  17. package/src/notifications/AGENTS.md +2 -0
  18. package/src/notifications/adapters/slack.ts +67 -13
  19. package/src/notifications/approval-card-data.ts +58 -16
  20. package/src/notifications/broadcaster.ts +41 -19
  21. package/src/notifications/guardian-question-mode.ts +81 -0
  22. package/src/notifications/types.ts +5 -0
  23. package/src/persistence/delivery-crud.ts +48 -1
  24. package/src/plugins/defaults/memory/hooks/user-prompt-submit.ts +2 -2
  25. package/src/plugins/mtime-cache.ts +21 -10
  26. package/src/runtime/approval-source-link.ts +107 -0
  27. package/src/runtime/confirmation-request-guardian-bridge.ts +9 -0
  28. package/src/runtime/routes/inbound-message-handler.ts +4 -0
  29. package/src/runtime/tool-grant-request-helper.ts +14 -0
  30. package/src/tools/registry.ts +26 -17
  31. package/src/tools/tool-approval-handler.ts +2 -0
  32. package/src/tools/types.ts +8 -0
@@ -5,7 +5,7 @@
5
5
  * finding messages by source identifiers, and managing raw payload storage.
6
6
  */
7
7
 
8
- import { and, eq, isNotNull, ne, or } from "drizzle-orm";
8
+ import { and, desc, eq, isNotNull, ne, or, sql } from "drizzle-orm";
9
9
  import { v4 as uuid } from "uuid";
10
10
 
11
11
  import { readSlackMetadataFromMessageMetadata } from "../messaging/providers/slack/message-metadata.js";
@@ -300,6 +300,53 @@ export function findMessageBySourceId(
300
300
  return { messageId: row.messageId, conversationId: row.conversationId };
301
301
  }
302
302
 
303
+ /**
304
+ * Reference to the most recent inbound channel event for a conversation:
305
+ * the external chat plus the channel-native message identifiers needed to
306
+ * point back at the triggering message (for Slack, `sourceMessageId` is the
307
+ * message `ts` and `externalMessageId` is the dedupe id, which may also be
308
+ * a `ts`).
309
+ */
310
+ export interface LatestInboundEventReference {
311
+ externalChatId: string;
312
+ externalMessageId: string;
313
+ sourceMessageId: string | null;
314
+ }
315
+
316
+ /**
317
+ * Find the most recent inbound event for a conversation on a channel.
318
+ * Used to anchor guardian-facing approval cards to the channel message
319
+ * that triggered the request.
320
+ *
321
+ * Orders by `rowid` rather than `created_at`: rows are insert-only so the
322
+ * two orderings agree, and the conversation-id index stores equal keys in
323
+ * rowid order — a backward index scan finds the newest row without sorting
324
+ * the conversation's full event history.
325
+ */
326
+ export function getLatestInboundEventReference(
327
+ conversationId: string,
328
+ sourceChannel: string,
329
+ ): LatestInboundEventReference | null {
330
+ const db = getDb();
331
+ const row = db
332
+ .select({
333
+ externalChatId: channelInboundEvents.externalChatId,
334
+ externalMessageId: channelInboundEvents.externalMessageId,
335
+ sourceMessageId: channelInboundEvents.sourceMessageId,
336
+ })
337
+ .from(channelInboundEvents)
338
+ .where(
339
+ and(
340
+ eq(channelInboundEvents.conversationId, conversationId),
341
+ eq(channelInboundEvents.sourceChannel, sourceChannel),
342
+ ),
343
+ )
344
+ .orderBy(desc(sql`rowid`))
345
+ .limit(1)
346
+ .get();
347
+ return row ?? null;
348
+ }
349
+
303
350
  /**
304
351
  * Store the raw request payload on an inbound event so it can be
305
352
  * replayed later if processing fails.
@@ -33,6 +33,7 @@ import type {
33
33
  } from "@vellumai/plugin-api";
34
34
  import { updateMessageMetadata } from "@vellumai/plugin-api";
35
35
 
36
+ import type { MemoryRecalledEvent } from "../../../../api/events/memory-recalled.js";
36
37
  import { getConfig } from "../../../../config/loader.js";
37
38
  import { isMemoryV3Live } from "../../../../config/memory-v3-gate.js";
38
39
  import { findConversationOrSubagent } from "../../../../daemon/conversation-registry.js";
@@ -42,7 +43,6 @@ import {
42
43
  resolveTurnModelProfileLabel,
43
44
  type RuntimeInjectionResult,
44
45
  } from "../../../../daemon/conversation-runtime-assembly.js";
45
- import type { MemoryRecalled } from "../../../../daemon/message-types/memory.js";
46
46
  import { resolveTrustClass } from "../../../../daemon/trust-context.js";
47
47
  import { timeLatencySubSpan } from "../../../../daemon/turn-latency-sub-spans.js";
48
48
  import { broadcastMessage } from "../../../../runtime/assistant-event-hub.js";
@@ -134,7 +134,7 @@ async function recordRecallSideEffects(
134
134
  }
135
135
 
136
136
  if (m) {
137
- const memoryRecalledEvent: MemoryRecalled = {
137
+ const memoryRecalledEvent: MemoryRecalledEvent = {
138
138
  type: "memory_recalled",
139
139
  provider: m.embeddingProvider ?? "unknown",
140
140
  model: m.embeddingModel ?? "unknown",
@@ -712,20 +712,31 @@ export interface ActivePluginTools {
712
712
  }
713
713
 
714
714
  /**
715
- * Sync the plugin caches with the source-versions sentinel, then return the
716
- * tool contributions of every *active* (discovered, enabled, activated)
717
- * user plugin, keyed by plugin name in install-date order.
715
+ * Return the tool contributions of every *active* (discovered, enabled,
716
+ * activated) user plugin, keyed by plugin name in install-date order.
717
+ *
718
+ * This is a pure read of the already-reconciled caches — it never scans disk,
719
+ * activates a plugin, or runs an `init` hook. Reconciliation (which activates
720
+ * plugins and is the only thing that runs `init`) is owned exclusively by the
721
+ * three paths that legitimately change the plugin set: the boot scan
722
+ * ({@link populateCacheAtBoot}), the source-versions gate on the hook-dispatch
723
+ * path ({@link getUserHookEntriesFor} → {@link maybeReconcileFromSentinel}), and
724
+ * the imperative install/uninstall poke ({@link reconcilePluginSourcesNow}).
725
+ * Pulling tools must not be a fourth: the tool registry is populated from
726
+ * processes that never run plugin lifecycle (sidecar workers call
727
+ * `initializeTools()` for their own tool surface), so folding activation into
728
+ * this read would run `init` in a worker against daemon-owned plugin storage.
718
729
  *
719
730
  * This is the pull half of the tool-registry relationship: the registry's
720
731
  * `loadPluginTools()` reconcile calls this and diffs the result into its own
721
- * maps — this module never writes to the registry. Mirrors how hook reads
722
- * pull through {@link getUserHookEntriesFor}.
732
+ * maps — this module never writes to the registry. Because a runtime plugin
733
+ * change lands in the cache via the hook-dispatch reconcile that runs each turn
734
+ * (or the explicit install poke), the very next `loadPluginTools()` reads the
735
+ * updated set, so live install/remove/edit is still picked up without recreating
736
+ * the conversation. Mirrors how hook reads pull through
737
+ * {@link getUserHookEntriesFor}.
723
738
  */
724
- export async function getActiveUserPluginTools(): Promise<
725
- Map<string, ActivePluginTools>
726
- > {
727
- await maybeReconcileFromSentinel();
728
-
739
+ export function getActiveUserPluginTools(): Map<string, ActivePluginTools> {
729
740
  const byPlugin = new Map<string, CachedTool[]>();
730
741
  for (const cached of toolCache.values()) {
731
742
  if (!activatedNames.has(cached.pluginName)) {
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Channel-neutral source references for guardian approval cards.
3
+ *
4
+ * When a channel actor triggers a tool that needs guardian approval, the
5
+ * approval card should link the guardian back to the originating
6
+ * conversation. The mechanism is split into four layers with strict
7
+ * ownership, mirroring the `sourceLink` contract on conversation channel
8
+ * bindings:
9
+ *
10
+ * 1. **Contract + registry (this module).** Owns the neutral shapes
11
+ * ({@link ApprovalSourceReference}, {@link ApprovalSourceHint}) and
12
+ * dispatches by source channel. Knows which channels have resolvers;
13
+ * knows nothing about any channel's id or URL formats.
14
+ * 2. **Per-channel resolvers** (`messaging/providers/<channel>/
15
+ * approval-source.ts`). Own all channel-format knowledge — how to turn
16
+ * the hint and/or persisted rows into a chat id and deep link. Called
17
+ * only through this registry.
18
+ * 3. **Neutral projection** (`buildToolApprovalSourceView` in
19
+ * `notifications/guardian-question-mode.ts`). Shapes the payload fields
20
+ * into display-ready facts once per broadcast. Channel-scoped display
21
+ * facts it carries are explicitly named as such (`isSlackDm`).
22
+ * 4. **Per-destination renderers** (`notifications/approval-card-data.ts`
23
+ * for the in-app Surface card, `notifications/adapters/<channel>` for
24
+ * channel cards). Format the projected view for their surface; they
25
+ * never parse channel-native ids or build URLs.
26
+ *
27
+ * Producers spread the resolved reference into the `guardian.question`
28
+ * context payload with a single call. Channels without a registered
29
+ * resolver contribute no reference — their cards render without a link. To
30
+ * light up a new channel (e.g. Discord): implement layer 2 in
31
+ * `messaging/providers/<channel>/approval-source.ts` and register it in
32
+ * {@link SOURCE_RESOLVERS}; layers 1, 3, and 4 need no changes.
33
+ */
34
+
35
+ import type { ExternalSourceLink } from "../messaging/channel-binding-schema.js";
36
+ import { resolveSlackApprovalSource } from "../messaging/providers/slack/approval-source.js";
37
+ import { getLogger } from "../util/logger.js";
38
+
39
+ const log = getLogger("approval-source-link");
40
+
41
+ /**
42
+ * Reference to the channel message/conversation that triggered an approval,
43
+ * shaped as the `guardian.question` context-payload fields it becomes.
44
+ */
45
+ export interface ApprovalSourceReference {
46
+ /** Channel-native chat/conversation id the request originated from. */
47
+ sourceChatId: string;
48
+ /** Deep link to the originating message/thread, when derivable. */
49
+ sourceLink?: ExternalSourceLink;
50
+ }
51
+
52
+ /**
53
+ * Exact provenance of the triggering message, stamped onto the trust
54
+ * context at ingress and threaded through the turn to the producer. When
55
+ * present, resolvers use it directly instead of reconstructing the
56
+ * reference from persisted rows — reconstruction is the fallback for
57
+ * turns without a stamped ingress context (voice, retries).
58
+ *
59
+ * Field names match `TrustContext` / `ToolContext`, so producers pass
60
+ * their context object (or a shorthand literal) straight through.
61
+ */
62
+ export interface ApprovalSourceHint {
63
+ /** Chat/conversation id the requester is interacting through. */
64
+ requesterChatId?: string | null;
65
+ /** Channel-native id of the message that started the turn. */
66
+ sourceMessageId?: string;
67
+ /** Channel-native thread id of that message, when threaded. */
68
+ sourceThreadId?: string;
69
+ }
70
+
71
+ const SOURCE_RESOLVERS: Partial<
72
+ Record<
73
+ string,
74
+ (
75
+ conversationId: string,
76
+ hint: ApprovalSourceHint | undefined,
77
+ ) => ApprovalSourceReference | null
78
+ >
79
+ > = {
80
+ slack: resolveSlackApprovalSource,
81
+ };
82
+
83
+ /**
84
+ * Best-effort lookup of the source reference for an approval originating
85
+ * from `sourceChannel`. Returns `null` for channels without a resolver or
86
+ * when the resolver cannot derive a reference. Never throws — approval
87
+ * creation must not fail because a card link could not be built.
88
+ */
89
+ export function resolveApprovalSourceReference(
90
+ sourceChannel: string,
91
+ conversationId: string,
92
+ hint?: ApprovalSourceHint,
93
+ ): ApprovalSourceReference | null {
94
+ const resolver = SOURCE_RESOLVERS[sourceChannel];
95
+ if (!resolver) {
96
+ return null;
97
+ }
98
+ try {
99
+ return resolver(conversationId, hint);
100
+ } catch (err) {
101
+ log.warn(
102
+ { err, sourceChannel, conversationId },
103
+ "Failed to resolve approval source reference",
104
+ );
105
+ return null;
106
+ }
107
+ }
@@ -21,6 +21,7 @@ import {
21
21
  } from "../notifications/guardian-delivery-recorder.js";
22
22
  import { canonicalizeInboundIdentity } from "../util/canonicalize-identity.js";
23
23
  import { getLogger } from "../util/logger.js";
24
+ import { resolveApprovalSourceReference } from "./approval-source-link.js";
24
25
  import { DAEMON_INTERNAL_ASSISTANT_ID } from "./assistant-scope.js";
25
26
  import { resolveCapabilities } from "./capabilities.js";
26
27
  import { getGuardianBinding } from "./channel-verification-service.js";
@@ -185,6 +186,14 @@ export async function bridgeConfirmationRequestToGuardian(
185
186
  questionText,
186
187
  riskLevel: guardianRequest.riskLevel ?? undefined,
187
188
  commandPreview: guardianRequest.commandPreview ?? undefined,
189
+ // Reference to the channel message that triggered the confirmation, so
190
+ // approval cards can link the guardian back to the source conversation.
191
+ // The hint's field names match TrustContext, so it passes straight through.
192
+ ...resolveApprovalSourceReference(
193
+ sourceChannel,
194
+ conversationId,
195
+ trustContext,
196
+ ),
188
197
  },
189
198
  dedupeKey: `tc-confirmation-request:${guardianRequest.id}`,
190
199
  // The broadcaster awaits the returned promise, so the delivery row is
@@ -751,6 +751,10 @@ export async function handleChannelInbound({
751
751
  },
752
752
  slackActorTimezone,
753
753
  );
754
+ // Exact provenance for this turn's triggering message, read back by
755
+ // guardian-approval producers to link approval cards to their source.
756
+ trustCtx.sourceMessageId = sourceMessageId;
757
+ trustCtx.sourceThreadId = slackThreadTs;
754
758
 
755
759
  // ── Admission policy floor ──
756
760
  // Sits between trust resolution and the agent loop. The gateway attaches
@@ -22,6 +22,7 @@ import {
22
22
  recordGuardianRequestDeliveries,
23
23
  } from "../notifications/guardian-delivery-recorder.js";
24
24
  import { getLogger } from "../util/logger.js";
25
+ import { resolveApprovalSourceReference } from "./approval-source-link.js";
25
26
  import { getGuardianBinding } from "./channel-verification-service.js";
26
27
  import { resolveDecidableGuardianPrincipalId } from "./local-actor-identity.js";
27
28
  import { GUARDIAN_APPROVAL_TTL_MS } from "./routes/channel-route-shared.js";
@@ -42,6 +43,10 @@ export interface ToolGrantRequestParams {
42
43
  toolName: string;
43
44
  inputDigest: string;
44
45
  questionText: string;
46
+ /** Channel-native id of the inbound message that triggered the escalation. */
47
+ sourceMessageId?: string;
48
+ /** Channel-native thread id of that message, when threaded. */
49
+ sourceThreadId?: string;
45
50
  }
46
51
 
47
52
  export type ToolGrantRequestResult =
@@ -73,6 +78,8 @@ export async function createOrReuseToolGrantRequest(
73
78
  toolName,
74
79
  inputDigest,
75
80
  questionText,
81
+ sourceMessageId,
82
+ sourceThreadId,
76
83
  } = params;
77
84
 
78
85
  if (!requesterExternalUserId) {
@@ -186,6 +193,13 @@ export async function createOrReuseToolGrantRequest(
186
193
  requesterIdentifier: senderLabel,
187
194
  toolName,
188
195
  questionText,
196
+ // Reference to the channel message that triggered the escalation, so
197
+ // approval cards can link the guardian back to the source conversation.
198
+ ...resolveApprovalSourceReference(sourceChannel, conversationId, {
199
+ requesterChatId,
200
+ sourceMessageId,
201
+ sourceThreadId,
202
+ }),
189
203
  },
190
204
  dedupeKey: `tool-grant-request:${guardianRequest.id}`,
191
205
  // The broadcaster awaits the returned promise, so the delivery row is
@@ -428,18 +428,25 @@ export function unregisterPluginTools(pluginName: string): void {
428
428
  * Pull the active user-plugin tool set from the plugin mtime-cache into the
429
429
  * registry. This is the pull half of the plugin-tool relationship — the
430
430
  * mtime-cache never writes to the registry; instead this reconcile reads
431
- * {@link import("../plugins/mtime-cache.js").getActiveUserPluginTools} (which
432
- * syncs against the source-versions sentinel first) and diffs the result into
433
- * the registry: plugins that vanished are unregistered, new plugins register,
434
- * and a plugin whose per-tool source mtimes moved is re-registered. Mirrors
435
- * how hooks resolve through `getUserHookEntriesFor`.
431
+ * {@link import("../plugins/mtime-cache.js").getActiveUserPluginTools} and diffs
432
+ * the result into the registry: plugins that vanished are unregistered, new
433
+ * plugins register, and a plugin whose per-tool source mtimes moved is
434
+ * re-registered. Mirrors how hooks resolve through `getUserHookEntriesFor`.
436
435
  *
437
- * Idempotent, cheap when nothing changed (one sentinel stat + fingerprint
438
- * compares), and concurrency-safe (concurrent callers coalesce onto one
439
- * in-flight reconcile). Runs as the final step of `initializeTools()` (at
440
- * daemon boot the plugin cache is already populated by then), and
441
- * fire-and-forget from the per-turn conversation tool resolver — the same
442
- * cadence `loadWorkspaceTools` runs on.
436
+ * This is a pure read of the plugin cache — it does NOT reconcile the cache
437
+ * against the source-versions sentinel, so it never activates a plugin or runs
438
+ * an `init` hook. Cache reconciliation is owned by the hook-dispatch gate and
439
+ * the boot/install paths (see `getActiveUserPluginTools`); this pull picks up
440
+ * whatever they last landed. That keeps tool registration decoupled from plugin
441
+ * lifecycle: sidecar workers call `initializeTools()` for their own tool
442
+ * surface and must never run a plugin's `init` as a side effect.
443
+ *
444
+ * Idempotent, cheap when nothing changed (a fingerprint compare per plugin),
445
+ * and concurrency-safe (concurrent callers coalesce onto one in-flight
446
+ * reconcile). Runs as the final step of `initializeTools()` (at daemon boot the
447
+ * plugin cache is already populated by then), and fire-and-forget from the
448
+ * per-turn conversation tool resolver — the same cadence `loadWorkspaceTools`
449
+ * runs on.
443
450
  */
444
451
  export function loadPluginTools(): Promise<void> {
445
452
  if (pluginToolsReconcileInFlight) {
@@ -462,7 +469,7 @@ async function reconcilePluginToolsFromCache(): Promise<void> {
462
469
  try {
463
470
  const { getActiveUserPluginTools } =
464
471
  await import("../plugins/mtime-cache.js");
465
- active = await getActiveUserPluginTools();
472
+ active = getActiveUserPluginTools();
466
473
  } catch (err) {
467
474
  log.warn(
468
475
  { err },
@@ -1091,11 +1098,13 @@ async function runToolInitialization(): Promise<void> {
1091
1098
 
1092
1099
  // Pull the active user-plugin tool set last, so core and workspace
1093
1100
  // registrations already own their names when plugin conflicts resolve.
1094
- // At daemon boot the plugin mtime-cache is populated before this runs
1095
- // (`initializePlugins()` precedes `initializeTools()` in the lifecycle);
1096
- // in worker/standalone processes the cache is empty and this is a no-op.
1097
- // Runtime changes keep flowing through the same reconcile, re-fired by
1098
- // the per-turn conversation tool resolver.
1101
+ // This is a pure cache read (it never activates a plugin or runs `init`):
1102
+ // at daemon boot the plugin mtime-cache is already populated by
1103
+ // `initializePlugins()`, which precedes `initializeTools()` in the lifecycle;
1104
+ // in worker/standalone processes the cache is empty, so this registers no
1105
+ // plugin tools and — critically — runs no plugin lifecycle. Runtime changes
1106
+ // reach the cache via the hook-dispatch reconcile and are re-pulled by the
1107
+ // per-turn conversation tool resolver.
1099
1108
  await loadPluginTools();
1100
1109
  }
1101
1110
 
@@ -672,6 +672,8 @@ export class ToolApprovalHandler {
672
672
  conversationId: context.conversationId,
673
673
  requesterExternalUserId: context.requesterExternalUserId,
674
674
  requesterChatId: context.requesterChatId,
675
+ sourceMessageId: context.sourceMessageId,
676
+ sourceThreadId: context.sourceThreadId,
675
677
  toolName: name,
676
678
  inputDigest,
677
679
  questionText: buildToolGrantQuestionText(name, input, context),
@@ -327,6 +327,14 @@ export interface ToolContext {
327
327
  * @legacy
328
328
  */
329
329
  requesterChatId?: string;
330
+ /**
331
+ * Channel-native id (`ts` for Slack) of the inbound message that started
332
+ * the current turn. Lets tool-grant escalations link approval cards to
333
+ * the exact triggering message.
334
+ */
335
+ sourceMessageId?: string;
336
+ /** Channel-native thread id of that message, when it arrived in a thread. */
337
+ sourceThreadId?: string;
330
338
  /**
331
339
  * Human-readable identifier for the requester (e.g., @username).
332
340
  * @legacy