@vellumai/assistant 0.10.11-dev.202607221933.baa2119 → 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 (59) hide show
  1. package/node_modules/@vellumai/gateway-client/src/__tests__/binding-strength-contract.test.ts +122 -0
  2. package/node_modules/@vellumai/gateway-client/src/binding-strength-contract.ts +155 -0
  3. package/node_modules/@vellumai/gateway-client/src/index.ts +14 -0
  4. package/package.json +1 -1
  5. package/src/__tests__/approval-source-link.test.ts +208 -0
  6. package/src/__tests__/btw-routes.test.ts +13 -2
  7. package/src/__tests__/conversation-store-ephemeral.test.ts +182 -0
  8. package/src/__tests__/plugin-import-boundary-guard.test.ts +1 -1
  9. package/src/__tests__/slack-notification-approval-card.test.ts +103 -20
  10. package/src/__tests__/tool-approval-seed-content-blocks.test.ts +179 -96
  11. package/src/__tests__/ui-choice-copy-surfaces.test.ts +144 -3
  12. package/src/api/events/memory-recalled.ts +59 -0
  13. package/src/api/events/memory-status.ts +29 -0
  14. package/src/api/events/service-group-update-complete.ts +29 -0
  15. package/src/api/events/service-group-update-progress.ts +23 -0
  16. package/src/api/events/service-group-update-starting.ts +26 -0
  17. package/src/api/index.ts +36 -1
  18. package/src/api/surfaces.ts +77 -21
  19. package/src/calls/__tests__/voice-triage-escalate.test.ts +58 -3
  20. package/src/calls/voice-session-bridge.ts +6 -2
  21. package/src/calls/voice-triage-escalate.ts +30 -1
  22. package/src/config/feature-flag-registry.json +9 -0
  23. package/src/daemon/conversation-store.ts +14 -2
  24. package/src/daemon/conversation-surfaces.ts +78 -168
  25. package/src/daemon/conversation-tool-setup.ts +7 -3
  26. package/src/daemon/handlers/shared.ts +11 -1
  27. package/src/daemon/message-types/memory.ts +8 -46
  28. package/src/daemon/message-types/surfaces.ts +1 -1
  29. package/src/daemon/message-types/upgrades.ts +11 -28
  30. package/src/daemon/trust-context-types.ts +8 -0
  31. package/src/messaging/channel-binding-schema.ts +6 -2
  32. package/src/messaging/providers/slack/approval-source.ts +87 -0
  33. package/src/messaging/providers/slack/deep-link.ts +45 -8
  34. package/src/messaging/providers/slack/message-metadata.ts +16 -0
  35. package/src/notifications/AGENTS.md +2 -0
  36. package/src/notifications/access-request-copy.ts +10 -21
  37. package/src/notifications/adapters/slack.ts +67 -13
  38. package/src/notifications/approval-card-data.ts +58 -16
  39. package/src/notifications/broadcaster.ts +41 -19
  40. package/src/notifications/guardian-question-mode.ts +81 -0
  41. package/src/notifications/types.ts +5 -0
  42. package/src/persistence/delivery-crud.ts +48 -1
  43. package/src/persistence/migrations/347-delete-stray-greeting-conversation.ts +46 -0
  44. package/src/persistence/migrations/__tests__/347-delete-stray-greeting-conversation.test.ts +100 -0
  45. package/src/persistence/steps.ts +2 -0
  46. package/src/plugins/defaults/memory/hooks/user-prompt-submit.ts +2 -2
  47. package/src/plugins/mtime-cache.ts +21 -10
  48. package/src/runtime/approval-source-link.ts +107 -0
  49. package/src/runtime/confirmation-request-guardian-bridge.ts +9 -0
  50. package/src/runtime/introduction-policy.ts +23 -54
  51. package/src/runtime/routes/btw-routes.ts +9 -2
  52. package/src/runtime/routes/inbound-message-handler.ts +5 -13
  53. package/src/runtime/routes/upgrade-broadcast-routes.ts +6 -8
  54. package/src/runtime/tool-grant-request-helper.ts +14 -0
  55. package/src/tools/registry.ts +26 -17
  56. package/src/tools/tool-approval-handler.ts +2 -0
  57. package/src/tools/types.ts +8 -0
  58. package/src/tools/ui-surface/definitions.ts +20 -16
  59. package/src/tools/ui-surface/surface-shape-docs.ts +21 -6
@@ -36,6 +36,24 @@ function normalizeSlackTeamUrl(teamUrl?: string | null): string | undefined {
36
36
  }
37
37
  }
38
38
 
39
+ function buildArchivesMessageUrl(
40
+ teamUrl: string,
41
+ channelId: string,
42
+ messageTs: string,
43
+ threadTs?: string,
44
+ ): string {
45
+ const baseUrl = `${teamUrl}/archives/${encodeURIComponent(
46
+ channelId,
47
+ )}/p${formatSlackPermalinkTimestamp(messageTs)}`;
48
+ if (!threadTs) return baseUrl;
49
+
50
+ const search = new URLSearchParams({
51
+ thread_ts: threadTs,
52
+ cid: channelId,
53
+ });
54
+ return `${baseUrl}?${search.toString()}`;
55
+ }
56
+
39
57
  export function buildSlackWebMessageUrl(params: {
40
58
  teamUrl?: string | null;
41
59
  channelId: string;
@@ -45,16 +63,35 @@ export function buildSlackWebMessageUrl(params: {
45
63
  const teamUrl = normalizeSlackTeamUrl(params.teamUrl);
46
64
  if (!teamUrl) return undefined;
47
65
 
48
- const baseUrl = `${teamUrl}/archives/${encodeURIComponent(
66
+ return buildArchivesMessageUrl(
67
+ teamUrl,
49
68
  params.channelId,
50
- )}/p${formatSlackPermalinkTimestamp(params.messageTs)}`;
51
- if (!params.threadTs) return baseUrl;
69
+ params.messageTs,
70
+ params.threadTs,
71
+ );
72
+ }
52
73
 
53
- const search = new URLSearchParams({
54
- thread_ts: params.threadTs,
55
- cid: params.channelId,
56
- });
57
- return `${baseUrl}?${search.toString()}`;
74
+ /**
75
+ * Workspace-agnostic message permalink: `https://slack.com/archives/…`
76
+ * resolves for any authenticated Slack viewer, so no per-workspace team URL
77
+ * is needed. When `threadTs` marks an enclosing thread (and the message is
78
+ * not itself the thread root), `thread_ts`/`cid` params make Slack open the
79
+ * message inside its thread view instead of failing to locate a threaded
80
+ * reply at the channel root.
81
+ */
82
+ export function buildSlackPermalink(params: {
83
+ channelId: string;
84
+ messageTs: string;
85
+ threadTs?: string;
86
+ }): string {
87
+ const threadTs =
88
+ params.threadTs !== params.messageTs ? params.threadTs : undefined;
89
+ return buildArchivesMessageUrl(
90
+ "https://slack.com",
91
+ params.channelId,
92
+ params.messageTs,
93
+ threadTs,
94
+ );
58
95
  }
59
96
 
60
97
  export function buildSlackWebChannelUrl(params: {
@@ -19,6 +19,22 @@ import { z } from "zod";
19
19
 
20
20
  export type SlackEventKind = "message" | "reaction";
21
21
 
22
+ /**
23
+ * Shape-check for a Slack `ts` value. Slack IDs messages by `<seconds>.<micros>`
24
+ * strings (e.g. `"1700000000.000100"`). The daemon also stores identifiers in
25
+ * other formats (gateway dedupe keys, UUIDs), so any path that treats a stored
26
+ * id as a ts — Slack API history bounds, permalink construction — must
27
+ * shape-check first; Slack rejects non-ts arguments with `invalid_arguments`.
28
+ */
29
+ export function isSlackTs(value: string | null | undefined): value is string {
30
+ return typeof value === "string" && /^\d+\.\d+$/.test(value);
31
+ }
32
+
33
+ /** Slack DM conversation IDs start with `D` followed by alphanumeric chars. */
34
+ export function isSlackDmConversation(conversationExternalId: string): boolean {
35
+ return /^D[A-Z0-9]+$/i.test(conversationExternalId);
36
+ }
37
+
22
38
  const slackReactionMetadataSchema = z.object({
23
39
  emoji: z.string(),
24
40
  actorDisplayName: z.string().optional(),
@@ -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.
@@ -7,6 +7,8 @@
7
7
 
8
8
  import { z } from "zod";
9
9
 
10
+ import { buildSlackPermalink } from "../messaging/providers/slack/deep-link.js";
11
+ import { isSlackDmConversation } from "../messaging/providers/slack/message-metadata.js";
10
12
  import {
11
13
  buildIntroductionActions,
12
14
  coerceSignalBoolean,
@@ -147,25 +149,6 @@ export function isHandshakeOfferedForPayload(
147
149
  });
148
150
  }
149
151
 
150
- // ── Slack conversation helpers ───────────────────────────────────────────────
151
-
152
- /** Slack DM conversation IDs start with `D` followed by alphanumeric chars. */
153
- export function isSlackDmConversation(conversationExternalId: string): boolean {
154
- return /^D[A-Z0-9]+$/i.test(conversationExternalId);
155
- }
156
-
157
- /**
158
- * Build a Slack message permalink from a channel ID and message timestamp.
159
- * Format: https://slack.com/archives/{channelId}/p{ts_without_dot}
160
- * Workspace-agnostic — resolves for any authenticated Slack viewer.
161
- */
162
- export function buildSlackMessagePermalink(
163
- conversationExternalId: string,
164
- messageTs: string,
165
- ): string {
166
- return `https://slack.com/archives/${conversationExternalId}/p${messageTs.replace(".", "")}`;
167
- }
168
-
169
152
  /** Internal typed implementation — avoids re-parsing when called from
170
153
  * buildAccessRequestContractText which has already parsed the payload. */
171
154
  function buildIdentityLineFromParsed(p: ParsedAccessRequestPayload): string {
@@ -375,7 +358,10 @@ export function buildAccessRequestContractText(
375
358
  // Conversation context: source channel + permalink when available.
376
359
  if (p.sourceChannel === "slack" && p.conversationExternalId) {
377
360
  const permalink = p.messageTs
378
- ? buildSlackMessagePermalink(p.conversationExternalId, p.messageTs)
361
+ ? buildSlackPermalink({
362
+ channelId: p.conversationExternalId,
363
+ messageTs: p.messageTs,
364
+ })
379
365
  : undefined;
380
366
  const isDm = isSlackDmConversation(p.conversationExternalId);
381
367
  const channelLabel = isDm ? "Direct message" : p.conversationExternalId;
@@ -476,7 +462,10 @@ export function buildAccessRequestCardView(
476
462
 
477
463
  const messagePermalink =
478
464
  sourceChannel === "slack" && conversationExternalId && messageTs
479
- ? buildSlackMessagePermalink(conversationExternalId, messageTs)
465
+ ? buildSlackPermalink({
466
+ channelId: conversationExternalId,
467
+ messageTs,
468
+ })
480
469
  : undefined;
481
470
 
482
471
  const rawPreview = nonEmpty(p.messagePreview);
@@ -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