@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
@@ -357,6 +357,8 @@ export function createToolExecutor(
357
357
  batchAuthorizedByTask: false,
358
358
  requesterExternalUserId: turnTrust.requesterExternalUserId,
359
359
  requesterChatId: turnTrust.requesterChatId,
360
+ sourceMessageId: turnTrust.sourceMessageId,
361
+ sourceThreadId: turnTrust.sourceThreadId,
360
362
  requesterIdentifier: turnTrust.requesterIdentifier,
361
363
  requesterDisplayName: turnTrust.requesterDisplayName,
362
364
  channelConversationType: turnTrust.conversationType,
@@ -858,9 +860,11 @@ export function createResolveToolsCallback(
858
860
  void loadWorkspaceTools();
859
861
 
860
862
  // Same treatment for user-plugin tools: pull the plugin mtime-cache's
861
- // active tool set into the registry (a no-op costs one sentinel stat +
862
- // fingerprint compares), so a plugin installed/removed/edited at runtime
863
- // is picked up without recreating the conversation.
863
+ // active tool set into the registry (a no-op costs a fingerprint compare
864
+ // per plugin). This pull is a pure cache read — the sentinel reconcile that
865
+ // activates plugins runs on the hook-dispatch path that precedes tool
866
+ // resolution each turn — so a plugin installed/removed/edited at runtime is
867
+ // still picked up here without recreating the conversation.
864
868
  void loadPluginTools();
865
869
 
866
870
  // Read every registered plugin tool each turn (so runtime installs/edits
@@ -1,48 +1,10 @@
1
- // Memory recall and status types.
1
+ // Memory recall and status events.
2
+ //
3
+ // Server→client events are single-sourced from their canonical `api/events`
4
+ // wire schemas; this file only composes them into the domain union consumed by
5
+ // `message-protocol.ts`. Memory has no client messages.
2
6
 
3
- export interface MemoryRecalledDegradation {
4
- semanticUnavailable: boolean;
5
- reason: string;
6
- fallbackSources: string[];
7
- }
7
+ import type { MemoryRecalledEvent } from "../../api/events/memory-recalled.js";
8
+ import type { MemoryStatusEvent } from "../../api/events/memory-status.js";
8
9
 
9
- export interface MemoryRecalledCandidateDebug {
10
- key: string;
11
- type: string;
12
- kind: string;
13
- finalScore: number;
14
- semantic: number;
15
- recency: number;
16
- }
17
-
18
- export interface MemoryRecalled {
19
- type: "memory_recalled";
20
- provider: string;
21
- model: string;
22
- degradation?: MemoryRecalledDegradation;
23
- semanticHits: number;
24
- tier1Count: number;
25
- tier2Count: number;
26
- hybridSearchLatencyMs: number;
27
- sparseVectorUsed: boolean;
28
- mergedCount: number;
29
- selectedCount: number;
30
- injectedTokens: number;
31
- latencyMs: number;
32
- topCandidates: MemoryRecalledCandidateDebug[];
33
- }
34
-
35
- export interface MemoryStatus {
36
- type: "memory_status";
37
- enabled: boolean;
38
- degraded: boolean;
39
- degradation?: MemoryRecalledDegradation;
40
- reason?: string;
41
- provider?: string;
42
- model?: string;
43
- }
44
-
45
- // --- Domain-level union aliases (consumed by the barrel file) ---
46
- // Memory has no client messages.
47
-
48
- export type _MemoryServerMessages = MemoryRecalled | MemoryStatus;
10
+ export type _MemoryServerMessages = MemoryRecalledEvent | MemoryStatusEvent;
@@ -38,6 +38,14 @@ export interface TrustContext {
38
38
  requesterExternalUserId?: string;
39
39
  /** Chat/conversation ID the requester is interacting through. */
40
40
  requesterChatId?: string;
41
+ /**
42
+ * Channel-native id (`ts` for Slack) of the inbound message that started
43
+ * the current turn. Stamped at ingress so guardian-approval producers can
44
+ * link approval cards to the exact triggering message.
45
+ */
46
+ sourceMessageId?: string;
47
+ /** Channel-native thread id of that message, when it arrived in a thread. */
48
+ sourceThreadId?: string;
41
49
  /**
42
50
  * Conversation type of the inbound chat mapped onto the permission-matrix
43
51
  * axis (`dm | private | public`). Undefined when the channel's chat type is
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Slack's resolver for guardian approval source references.
3
+ *
4
+ * The exact provenance stamped at ingress (chat id + message `ts` on the
5
+ * turn's trust context) identifies the precise triggering message and wins
6
+ * outright when present. Turns without a stamped context (voice, retries)
7
+ * fall back to reconstruction from persisted rows: `channel_inbound_events`
8
+ * records each inbound message's chat id and `ts`, and the conversation's
9
+ * channel binding carries the thread `ts` for threaded conversations.
10
+ * Best-effort by design — a miss degrades to a card without a link, never a
11
+ * failed approval.
12
+ *
13
+ * Registered under `"slack"` in the channel-neutral resolver registry in
14
+ * `runtime/approval-source-link.ts`; only that registry should call this
15
+ * directly.
16
+ */
17
+
18
+ import { getLatestInboundEventReference } from "../../../persistence/delivery-crud.js";
19
+ import { getBindingByConversation } from "../../../persistence/external-conversation-store.js";
20
+ import type {
21
+ ApprovalSourceHint,
22
+ ApprovalSourceReference,
23
+ } from "../../../runtime/approval-source-link.js";
24
+ import { buildSlackPermalink } from "./deep-link.js";
25
+ import { isSlackTs } from "./message-metadata.js";
26
+
27
+ function toReference(
28
+ chatId: string,
29
+ messageTs: string | undefined,
30
+ threadTs: string | undefined,
31
+ ): ApprovalSourceReference {
32
+ // Without a message ts, the thread root is still a valid anchor.
33
+ const anchorTs = messageTs ?? threadTs;
34
+ if (!anchorTs) {
35
+ return { sourceChatId: chatId };
36
+ }
37
+ return {
38
+ sourceChatId: chatId,
39
+ sourceLink: {
40
+ webUrl: buildSlackPermalink({
41
+ channelId: chatId,
42
+ messageTs: anchorTs,
43
+ threadTs,
44
+ }),
45
+ },
46
+ };
47
+ }
48
+
49
+ export function resolveSlackApprovalSource(
50
+ conversationId: string,
51
+ hint: ApprovalSourceHint | undefined,
52
+ ): ApprovalSourceReference | null {
53
+ // Exact provenance from the turn's trust context. An absent thread id here
54
+ // is authoritative (the message arrived at the chat root), so no binding
55
+ // lookup is needed.
56
+ if (hint?.requesterChatId && isSlackTs(hint.sourceMessageId)) {
57
+ return toReference(
58
+ hint.requesterChatId,
59
+ hint.sourceMessageId,
60
+ isSlackTs(hint.sourceThreadId) ? hint.sourceThreadId : undefined,
61
+ );
62
+ }
63
+
64
+ const inbound = getLatestInboundEventReference(conversationId, "slack");
65
+ const rawBinding = getBindingByConversation(conversationId);
66
+ const binding = rawBinding?.sourceChannel === "slack" ? rawBinding : null;
67
+
68
+ const chatId =
69
+ hint?.requesterChatId ?? inbound?.externalChatId ?? binding?.externalChatId;
70
+ if (!chatId) {
71
+ return null;
72
+ }
73
+
74
+ // `sourceMessageId` records the ts explicitly; the dedupe id is a usable
75
+ // fallback only when it is itself ts-shaped (mirrors the slackMeta write in
76
+ // `inbound-message-handler.ts`).
77
+ const messageTs = isSlackTs(inbound?.sourceMessageId)
78
+ ? inbound.sourceMessageId
79
+ : isSlackTs(inbound?.externalMessageId)
80
+ ? inbound.externalMessageId
81
+ : undefined;
82
+ const threadTs = isSlackTs(binding?.externalThreadId)
83
+ ? binding.externalThreadId
84
+ : undefined;
85
+
86
+ return toReference(chatId, messageTs, threadTs);
87
+ }
@@ -5,3 +5,5 @@ All notification producers **MUST** go through `emitNotificationSignal()` in `no
5
5
  When a notification flow creates a server-side conversation (e.g. guardian question conversations, task run conversations), the conversation and initial message **MUST** be persisted before the conversation-created event is emitted. This ensures the macOS/iOS client can immediately fetch the conversation contents when it receives the event.
6
6
 
7
7
  Guardian-request producers (access requests, tool approvals, tool-grant escalations, voice questions, trusted-contact confirmations) **MUST** record approval-card deliveries through `recordApprovalCardDelivery` / `recordGuardianRequestDeliveries` in `guardian-delivery-recorder.ts` -- never by calling the gateway client's `createGuardianRequestDelivery` directly. That sink is the single place the card-to-request addressing convention lives (conversation id for the in-app card; chat + channel-native `ts` for channel cards), so the path that writes a delivery row cannot drift from the paths that read it back to withdraw a card or resolve an emoji reaction -- the drift that previously fanned this logic into four divergent copies. (Tests may seed delivery rows directly for fixtures.)
8
+
9
+ Approval-card **source references** (the link back to the channel message that triggered a request) resolve only through `resolveApprovalSourceReference()` in `runtime/approval-source-link.ts` -- producers spread the result into the `guardian.question` context payload and never hand-build links. Channel-format knowledge (id shapes, permalinks, mrkdwn) lives only in `messaging/providers/<channel>/` and `notifications/adapters/<channel>`; the four-layer ownership map is documented at the top of `approval-source-link.ts`. Exception: access-request cards predate the registry and still derive their Slack permalink from payload `messageTs` in `access-request-copy.ts` -- converge them onto the registry rather than adding a third resolution path.
@@ -24,6 +24,7 @@ import {
24
24
  buildAccessRequestCardView,
25
25
  buildAccessRequestInviteDirective,
26
26
  } from "../access-request-copy.js";
27
+ import type { ToolApprovalSourceView } from "../guardian-question-mode.js";
27
28
  import { truncate } from "../notification-utils.js";
28
29
  import type {
29
30
  ChannelAdapter,
@@ -110,6 +111,29 @@ function buildAccessRequestBody(view: AccessRequestCardView): string {
110
111
  return accessRequestCardSubtitle(view.admitted);
111
112
  }
112
113
 
114
+ /**
115
+ * Slack source context block: channel/DM label with a permalink to the
116
+ * originating message when one is available. Shared by the access-request
117
+ * and tool-approval cards so the source line renders identically on both.
118
+ */
119
+ function buildSlackSourceContextBlock(params: {
120
+ isDm: boolean;
121
+ chatId: string;
122
+ permalink: string | undefined;
123
+ }): ContextBlock {
124
+ const label = params.isDm
125
+ ? "Source: Slack — Direct message"
126
+ : `Source: Slack — <#${params.chatId}>`;
127
+ const sourceText = params.permalink
128
+ ? `${label} · <${params.permalink}|View message>`
129
+ : label;
130
+
131
+ return {
132
+ type: "context",
133
+ elements: [{ type: "mrkdwn", text: sourceText }],
134
+ };
135
+ }
136
+
113
137
  /** Source-channel context block with Slack permalink when available. */
114
138
  function buildSourceContextBlock(
115
139
  view: AccessRequestCardView,
@@ -118,22 +142,43 @@ function buildSourceContextBlock(
118
142
  return undefined;
119
143
  }
120
144
 
121
- const permalink = view.messagePermalink;
122
-
123
- let sourceText: string;
124
- if (view.isSlackDm) {
125
- sourceText = permalink
126
- ? `Source: Slack — Direct message · <${permalink}|View message>`
127
- : "Source: Slack — Direct message";
128
- } else {
129
- sourceText = permalink
130
- ? `Source: Slack — <#${view.conversationExternalId}> · <${permalink}|View message>`
131
- : `Source: Slack — <#${view.conversationExternalId}>`;
132
- }
145
+ return buildSlackSourceContextBlock({
146
+ isDm: view.isSlackDm,
147
+ chatId: view.conversationExternalId,
148
+ permalink: view.messagePermalink,
149
+ });
150
+ }
133
151
 
152
+ /**
153
+ * Source context block for a tool-approval card. Slack-originated requests
154
+ * get the channel/DM-aware label; any other source channel renders its
155
+ * channel id with the resolved link, so a new channel's approvals link back
156
+ * to their source as soon as its resolver is registered.
157
+ */
158
+ function buildToolApprovalSourceContextBlock(
159
+ view: ToolApprovalSourceView | undefined,
160
+ ): ContextBlock | undefined {
161
+ if (!view) {
162
+ return undefined;
163
+ }
164
+ if (view.channel === "slack" && view.chatId) {
165
+ return buildSlackSourceContextBlock({
166
+ isDm: view.isSlackDm,
167
+ chatId: view.chatId,
168
+ permalink: view.permalink,
169
+ });
170
+ }
171
+ if (!view.permalink) {
172
+ return undefined;
173
+ }
134
174
  return {
135
175
  type: "context",
136
- elements: [{ type: "mrkdwn", text: sourceText }],
176
+ elements: [
177
+ {
178
+ type: "mrkdwn",
179
+ text: `Source: ${view.channel} · <${view.permalink}|View message>`,
180
+ },
181
+ ],
137
182
  };
138
183
  }
139
184
 
@@ -320,6 +365,15 @@ function buildToolApprovalCardBlocks(
320
365
  });
321
366
  }
322
367
 
368
+ // Link the guardian back to the conversation that triggered the request,
369
+ // when the broadcaster resolved a source reference.
370
+ const sourceBlock = buildToolApprovalSourceContextBlock(
371
+ payload.toolApprovalSource,
372
+ );
373
+ if (sourceBlock) {
374
+ blocks.push(sourceBlock);
375
+ }
376
+
323
377
  return blocks;
324
378
  }
325
379
 
@@ -29,6 +29,7 @@ import {
29
29
  } from "./approval-card-builder.js";
30
30
  import {
31
31
  buildGuardianRequestCodeInstruction,
32
+ buildToolApprovalSourceView,
32
33
  type GuardianQuestionPayload,
33
34
  type LenientToolApprovalPayload,
34
35
  LenientToolApprovalPayloadSchema,
@@ -95,6 +96,35 @@ export interface ToolApprovalCardData {
95
96
  */
96
97
  export type ApprovalCardData = AccessRequestCardData | ToolApprovalCardData;
97
98
 
99
+ // ── Shared source rendering ──────────────────────────────────────────────────
100
+
101
+ /**
102
+ * "Source" metadata row shared by the access-request and tool-approval
103
+ * cards: Slack sources with a known chat get a channel/DM-aware label,
104
+ * every other channel falls back to its raw channel id.
105
+ */
106
+ function sourceMetadataRow(
107
+ channel: string | undefined,
108
+ slackChatId: string | undefined,
109
+ isSlackDm: boolean,
110
+ ): { label: string; value: string } | undefined {
111
+ if (channel === "slack" && slackChatId) {
112
+ return {
113
+ label: "Source",
114
+ value: isSlackDm ? "Slack — Direct message" : `Slack — #${slackChatId}`,
115
+ };
116
+ }
117
+ if (channel) {
118
+ return { label: "Source", value: channel };
119
+ }
120
+ return undefined;
121
+ }
122
+
123
+ /** Card-body link back to the originating message, shared by both cards. */
124
+ function viewMessageLine(permalink: string): string {
125
+ return `[View message](${permalink})`;
126
+ }
127
+
98
128
  // ── Access-request resolution ────────────────────────────────────────────────
99
129
 
100
130
  /** Shape the parsed access-request payload into card params via the view model. */
@@ -123,15 +153,13 @@ function resolveAccessRequestCard(
123
153
  });
124
154
  }
125
155
 
126
- if (view.sourceChannel === "slack" && view.conversationExternalId) {
127
- metadata.push({
128
- label: "Source",
129
- value: view.isSlackDm
130
- ? "Slack — Direct message"
131
- : `Slack — #${view.conversationExternalId}`,
132
- });
133
- } else if (view.sourceChannel) {
134
- metadata.push({ label: "Source", value: view.sourceChannel });
156
+ const sourceRow = sourceMetadataRow(
157
+ view.sourceChannel,
158
+ view.conversationExternalId,
159
+ view.isSlackDm,
160
+ );
161
+ if (sourceRow) {
162
+ metadata.push(sourceRow);
135
163
  }
136
164
 
137
165
  const bodyParts: string[] = [];
@@ -143,7 +171,7 @@ function resolveAccessRequestCard(
143
171
  bodyParts.push(`⚠️ ${w}`);
144
172
  }
145
173
  if (view.messagePermalink) {
146
- bodyParts.push(`[View message](${view.messagePermalink})`);
174
+ bodyParts.push(viewMessageLine(view.messagePermalink));
147
175
  }
148
176
 
149
177
  const body =
@@ -220,14 +248,28 @@ function extractToolApprovalCard(
220
248
  // channel user ID — this placeholder covers defensive/lenient parses.
221
249
  const metadata: Array<{ label: string; value: string }> = [];
222
250
  metadata.push({ label: "Requested by", value: requester ?? "Unknown" });
223
- const sourceChannel = nonEmpty(p.sourceChannel);
224
- if (sourceChannel) {
225
- metadata.push({ label: "Source", value: sourceChannel });
251
+
252
+ const sourceView = buildToolApprovalSourceView(p);
253
+ const sourceRow = sourceMetadataRow(
254
+ nonEmpty(p.sourceChannel),
255
+ sourceView?.chatId,
256
+ sourceView?.isSlackDm ?? false,
257
+ );
258
+ if (sourceRow) {
259
+ metadata.push(sourceRow);
226
260
  }
227
261
 
228
- const body = p.questionText
229
- ? `> ${p.questionText}`
230
- : "No additional context available.";
262
+ const bodyParts: string[] = [];
263
+ if (p.questionText) {
264
+ bodyParts.push(`> ${p.questionText}`);
265
+ }
266
+ if (sourceView?.permalink) {
267
+ bodyParts.push(viewMessageLine(sourceView.permalink));
268
+ }
269
+ const body =
270
+ bodyParts.length > 0
271
+ ? bodyParts.join("\n\n")
272
+ : "No additional context available.";
231
273
 
232
274
  // Fallback text with request-code instructions for older clients.
233
275
  const baseFallback =
@@ -29,7 +29,11 @@ import {
29
29
  updateDeliveryStatus,
30
30
  } from "./deliveries-store.js";
31
31
  import { resolveDestinations } from "./destination-resolver.js";
32
- import { parseInteractiveApprovalPayload } from "./guardian-question-mode.js";
32
+ import {
33
+ buildToolApprovalSourceView,
34
+ parseInteractiveApprovalPayload,
35
+ type ToolApprovalSourceView,
36
+ } from "./guardian-question-mode.js";
33
37
  import { nonEmpty } from "./notification-utils.js";
34
38
  import type { NotificationSignal } from "./signal.js";
35
39
  import type {
@@ -49,13 +53,23 @@ const APPROVAL_ACTIONS: ApprovalUIMetadata["actions"] = [
49
53
  { id: "reject", label: "Reject" },
50
54
  ];
51
55
 
56
+ /**
57
+ * Structured approval data resolved once per broadcast, so channel adapters
58
+ * render approval cards without re-parsing `contextPayload`.
59
+ */
60
+ interface ResolvedApprovalContext {
61
+ approval: ApprovalUIMetadata;
62
+ /** Source reference for tool-approval cards (guardian.question only). */
63
+ toolApprovalSource?: ToolApprovalSourceView;
64
+ }
65
+
52
66
  /**
53
67
  * Resolve structured approval context from a notification signal.
54
68
  * Returns `undefined` when the signal does not represent an approval flow.
55
69
  */
56
70
  function resolveApprovalContext(
57
71
  signal: NotificationSignal,
58
- ): ApprovalUIMetadata | undefined {
72
+ ): ResolvedApprovalContext | undefined {
59
73
  const payload = signal.contextPayload;
60
74
  if (!payload) {
61
75
  return undefined;
@@ -69,11 +83,13 @@ function resolveApprovalContext(
69
83
  return undefined;
70
84
  }
71
85
  return {
72
- requestId,
73
- actions: buildIntroductionActionsForPayload(
74
- parseAccessRequestPayload(payload),
75
- ),
76
- plainTextFallback: buildAccessRequestContractText(payload),
86
+ approval: {
87
+ requestId,
88
+ actions: buildIntroductionActionsForPayload(
89
+ parseAccessRequestPayload(payload),
90
+ ),
91
+ plainTextFallback: buildAccessRequestContractText(payload),
92
+ },
77
93
  };
78
94
  }
79
95
 
@@ -101,17 +117,20 @@ function resolveApprovalContext(
101
117
  }
102
118
 
103
119
  return {
104
- requestId,
105
- actions: APPROVAL_ACTIONS,
106
- plainTextFallback: `Reply "${parsed.requestCode?.toUpperCase() ?? requestId} approve" or "${parsed.requestCode?.toUpperCase() ?? requestId} reject"`,
107
- permissionDetails: toolName
108
- ? {
109
- toolName,
110
- riskLevel: riskLevel ?? "medium",
111
- toolInput: commandPreview ? { _summary: commandPreview } : {},
112
- requesterIdentifier: nonEmpty(parsed.requesterIdentifier),
113
- }
114
- : undefined,
120
+ approval: {
121
+ requestId,
122
+ actions: APPROVAL_ACTIONS,
123
+ plainTextFallback: `Reply "${parsed.requestCode?.toUpperCase() ?? requestId} approve" or "${parsed.requestCode?.toUpperCase() ?? requestId} reject"`,
124
+ permissionDetails: toolName
125
+ ? {
126
+ toolName,
127
+ riskLevel: riskLevel ?? "medium",
128
+ toolInput: commandPreview ? { _summary: commandPreview } : {},
129
+ requesterIdentifier: nonEmpty(parsed.requesterIdentifier),
130
+ }
131
+ : undefined,
132
+ },
133
+ toolApprovalSource: buildToolApprovalSourceView(parsed),
115
134
  };
116
135
  }
117
136
 
@@ -208,7 +227,9 @@ export class NotificationBroadcaster {
208
227
  Record<NotificationChannel, RenderedChannelCopy>
209
228
  > | null = null;
210
229
 
211
- const approvalContext = resolveApprovalContext(signal);
230
+ const resolvedApproval = resolveApprovalContext(signal);
231
+ const approvalContext = resolvedApproval?.approval;
232
+ const toolApprovalSource = resolvedApproval?.toolApprovalSource;
212
233
  const accessRequestContext =
213
234
  signal.sourceEventName === "ingress.access_request" &&
214
235
  signal.contextPayload
@@ -476,6 +497,7 @@ export class NotificationBroadcaster {
476
497
  urgency: signal.attentionHints.urgency,
477
498
  approvalContext,
478
499
  accessRequestContext,
500
+ toolApprovalSource,
479
501
  };
480
502
 
481
503
  // Compute conversation decision audit fields for the delivery record
@@ -12,6 +12,8 @@
12
12
 
13
13
  import { z } from "zod";
14
14
 
15
+ import { externalSourceLinkSchema } from "../messaging/channel-binding-schema.js";
16
+ import { isSlackDmConversation } from "../messaging/providers/slack/message-metadata.js";
15
17
  import { nonEmpty } from "./notification-utils.js";
16
18
 
17
19
  // ── Schema primitives ──────────────────────────────────────────────────
@@ -78,6 +80,19 @@ export const PendingQuestionPayloadSchema =
78
80
  toolName: z.string().optional(),
79
81
  });
80
82
 
83
+ /**
84
+ * Channel-neutral reference to the message that triggered the approval,
85
+ * resolved per-channel by `runtime/approval-source-link.ts` (currently only
86
+ * Slack registers a resolver). Card renderers consume it via
87
+ * {@link buildToolApprovalSourceView} without channel-format knowledge.
88
+ */
89
+ const sourceReferenceFields = {
90
+ /** Channel-native chat/conversation id the request originated from. */
91
+ sourceChatId: z.string().optional(),
92
+ /** Deep link to the originating message/thread, when derivable. */
93
+ sourceLink: externalSourceLinkSchema.optional(),
94
+ };
95
+
81
96
  export const ToolApprovalPayloadSchema =
82
97
  GuardianQuestionPayloadBaseSchema.extend({
83
98
  requestKind: z.literal("tool_approval"),
@@ -86,6 +101,7 @@ export const ToolApprovalPayloadSchema =
86
101
  riskLevel: z.string().optional(),
87
102
  /** Secret-redacted summary of the tool invocation arguments. */
88
103
  commandPreview: z.string().optional(),
104
+ ...sourceReferenceFields,
89
105
  });
90
106
 
91
107
  export const ToolGrantPayloadSchema = GuardianQuestionPayloadBaseSchema.extend({
@@ -95,6 +111,7 @@ export const ToolGrantPayloadSchema = GuardianQuestionPayloadBaseSchema.extend({
95
111
  riskLevel: z.string().optional(),
96
112
  /** Secret-redacted summary of the tool invocation arguments. */
97
113
  commandPreview: z.string().optional(),
114
+ ...sourceReferenceFields,
98
115
  });
99
116
 
100
117
  export const AccessRequestGuardianPayloadSchema =
@@ -134,12 +151,76 @@ export const LenientToolApprovalPayloadSchema = z.object({
134
151
  requesterChatId: z.string().nullable().optional(),
135
152
  riskLevel: z.string().nullable().optional(),
136
153
  commandPreview: z.string().nullable().optional(),
154
+ sourceChatId: z.string().nullable().optional(),
155
+ sourceLink: sourceReferenceFields.sourceLink.nullable(),
137
156
  });
138
157
 
139
158
  export type LenientToolApprovalPayload = z.infer<
140
159
  typeof LenientToolApprovalPayloadSchema
141
160
  >;
142
161
 
162
+ // ── Source reference projection ─────────────────────────────────────────
163
+
164
+ /**
165
+ * Display-ready source reference for a tool-approval card, shared by every
166
+ * renderer (the Vellum Surface card and the channel adapters) so the
167
+ * chat-id/permalink derivation lives in exactly one place. Declared as a
168
+ * Zod schema because the broadcaster carries the projected view on
169
+ * `ChannelDeliveryPayload` (computed once per broadcast, never re-derived
170
+ * per channel).
171
+ *
172
+ * Core fields (`channel`, `chatId`, `permalink`) are channel-neutral.
173
+ * Channel-scoped display facts are named for their channel (`isSlackDm`)
174
+ * and gated on `channel` — renderers branch on them for richer labels but
175
+ * must degrade to the neutral fields for every other channel, so a new
176
+ * channel renders correctly with no projection changes.
177
+ */
178
+ export const ToolApprovalSourceViewSchema = z.object({
179
+ /** Channel the request originated from (e.g. `"slack"`). */
180
+ channel: z.string(),
181
+ /** Channel-native chat id, when the payload carries one. */
182
+ chatId: z.string().optional(),
183
+ /** Whether the source chat is a Slack direct message (`false` for other channels). */
184
+ isSlackDm: z.boolean(),
185
+ /** Link to the originating message/thread, when derivable. */
186
+ permalink: z.string().optional(),
187
+ });
188
+
189
+ export type ToolApprovalSourceView = z.infer<
190
+ typeof ToolApprovalSourceViewSchema
191
+ >;
192
+
193
+ /**
194
+ * Project a tool-approval payload's source reference into display-ready
195
+ * facts. Returns `undefined` when the payload names no chat and carries no
196
+ * link — renderers then fall back to the plain channel label.
197
+ */
198
+ export function buildToolApprovalSourceView(
199
+ p: Pick<
200
+ LenientToolApprovalPayload,
201
+ "sourceChannel" | "sourceChatId" | "sourceLink" | "requesterChatId"
202
+ >,
203
+ ): ToolApprovalSourceView | undefined {
204
+ const channel = nonEmpty(p.sourceChannel);
205
+ if (!channel) {
206
+ return undefined;
207
+ }
208
+ const chatId = nonEmpty(p.sourceChatId) ?? nonEmpty(p.requesterChatId);
209
+ const permalink =
210
+ nonEmpty(p.sourceLink?.webUrl) ?? nonEmpty(p.sourceLink?.appUrl);
211
+ if (!chatId && !permalink) {
212
+ return undefined;
213
+ }
214
+
215
+ return {
216
+ channel,
217
+ chatId,
218
+ isSlackDm:
219
+ channel === "slack" && chatId != null && isSlackDmConversation(chatId),
220
+ permalink,
221
+ };
222
+ }
223
+
143
224
  interface GuardianRequestModeInput {
144
225
  kind: unknown;
145
226
  toolName?: unknown;
@@ -13,6 +13,7 @@ import { z } from "zod";
13
13
  import type { ChannelPolicies } from "../channels/config.js";
14
14
  import type { ChannelId } from "../channels/types.js";
15
15
  import { AccessRequestPayloadSchema } from "./access-request-copy.js";
16
+ import { ToolApprovalSourceViewSchema } from "./guardian-question-mode.js";
16
17
  import { UrgencySchema } from "./urgency.js";
17
18
 
18
19
  /**
@@ -101,6 +102,10 @@ export const ChannelDeliveryPayloadSchema = z.object({
101
102
  urgency: UrgencySchema,
102
103
  approvalContext: ApprovalUIMetadataSchema.optional(),
103
104
  accessRequestContext: AccessRequestPayloadSchema.optional(),
105
+ /** Source reference for a tool-approval card, projected once by the
106
+ * broadcaster so channel adapters render it without re-parsing
107
+ * `contextPayload`. */
108
+ toolApprovalSource: ToolApprovalSourceViewSchema.optional(),
104
109
  });
105
110
  export type ChannelDeliveryPayload = z.infer<
106
111
  typeof ChannelDeliveryPayloadSchema