@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
@@ -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.
@@ -0,0 +1,46 @@
1
+ import { type DrizzleDb, getSqliteFrom } from "../db-connection.js";
2
+
3
+ /**
4
+ * The web empty-state greeting posts to `/v1/btw` with `conversationKey`
5
+ * "greeting". That side-chain is ephemeral and persists nothing, so its id is
6
+ * a literal string rather than a minted uuid.
7
+ */
8
+ const STRAY_GREETING_CONVERSATION_ID = "greeting";
9
+
10
+ /**
11
+ * Delete the stray `greeting` conversations row when it carries no messages.
12
+ *
13
+ * A message-less row with this id is an artifact of the ephemeral empty-state
14
+ * greeting side-chain and renders as an "Untitled" conversation in every
15
+ * client's sidebar. A row carrying messages means the user opened it and
16
+ * chatted, so it is user data and is left untouched.
17
+ *
18
+ * The ephemeral greeting path persists no messages, tool invocations, request
19
+ * logs, or telemetry, so the conversations row is the only artifact to remove.
20
+ * `tool_invocations` is cleared defensively — it is the sole conversation-
21
+ * scoped table a message-less conversation delete touches on the main
22
+ * database, and clearing it keeps the migration self-contained if some other
23
+ * path ever attached one.
24
+ *
25
+ * Idempotent: once the row is gone (or when the user has chatted in it) a
26
+ * re-run matches nothing and no-ops.
27
+ */
28
+ export function migrateDeleteStrayGreetingConversation(
29
+ database: DrizzleDb,
30
+ ): void {
31
+ const raw = getSqliteFrom(database);
32
+
33
+ const hasMessages = raw
34
+ .query(/*sql*/ `SELECT 1 FROM messages WHERE conversation_id = ? LIMIT 1`)
35
+ .get(STRAY_GREETING_CONVERSATION_ID);
36
+ if (hasMessages) {
37
+ return;
38
+ }
39
+
40
+ raw
41
+ .query(/*sql*/ `DELETE FROM tool_invocations WHERE conversation_id = ?`)
42
+ .run(STRAY_GREETING_CONVERSATION_ID);
43
+ raw
44
+ .query(/*sql*/ `DELETE FROM conversations WHERE id = ?`)
45
+ .run(STRAY_GREETING_CONVERSATION_ID);
46
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Tests for migration 347 — deleting the leaked ephemeral `greeting`
3
+ * conversations row from the sidebar.
4
+ *
5
+ * A message-less `greeting` row is an ephemeral empty-state greeting persisted
6
+ * by mistake and is removed; a `greeting` row carrying messages means the user
7
+ * chatted in it and is preserved as user data. Unrelated conversations are
8
+ * never touched, and the migration is idempotent.
9
+ */
10
+ import { describe, expect, test } from "bun:test";
11
+
12
+ const { getDb, getSqlite } = await import("../../db-connection.js");
13
+ const { initializeDb } = await import("../../db-init.js");
14
+ const { migrateDeleteStrayGreetingConversation } =
15
+ await import("../347-delete-stray-greeting-conversation.js");
16
+
17
+ await initializeDb();
18
+
19
+ function reset(): void {
20
+ const db = getSqlite();
21
+ db.query(`DELETE FROM messages`).run();
22
+ db.query(`DELETE FROM conversations`).run();
23
+ }
24
+
25
+ function insertConversation(id: string): void {
26
+ getSqlite()
27
+ .query(
28
+ `INSERT OR IGNORE INTO conversations (id, created_at, updated_at) VALUES (?, ?, ?)`,
29
+ )
30
+ .run(id, Date.now(), Date.now());
31
+ }
32
+
33
+ let seq = 0;
34
+ function insertMessage(conversationId: string): void {
35
+ getSqlite()
36
+ .query(
37
+ `INSERT INTO messages (id, conversation_id, role, content, created_at) VALUES (?, ?, ?, ?, ?)`,
38
+ )
39
+ .run(`m347-${seq++}`, conversationId, "user", "hello", Date.now());
40
+ }
41
+
42
+ function conversationExists(id: string): boolean {
43
+ return (
44
+ getSqlite()
45
+ .query(`SELECT 1 AS present FROM conversations WHERE id = ?`)
46
+ .get(id) != null
47
+ );
48
+ }
49
+
50
+ describe("migration 347 — delete stray greeting conversation", () => {
51
+ test("deletes an empty greeting row", () => {
52
+ reset();
53
+ insertConversation("greeting");
54
+
55
+ migrateDeleteStrayGreetingConversation(getDb());
56
+
57
+ expect(conversationExists("greeting")).toBe(false);
58
+ });
59
+
60
+ test("preserves a greeting row that carries messages", () => {
61
+ reset();
62
+ insertConversation("greeting");
63
+ insertMessage("greeting");
64
+
65
+ migrateDeleteStrayGreetingConversation(getDb());
66
+
67
+ expect(conversationExists("greeting")).toBe(true);
68
+ });
69
+
70
+ test("never touches unrelated conversations", () => {
71
+ reset();
72
+ insertConversation("greeting");
73
+ insertConversation("real-conversation");
74
+
75
+ migrateDeleteStrayGreetingConversation(getDb());
76
+
77
+ expect(conversationExists("greeting")).toBe(false);
78
+ expect(conversationExists("real-conversation")).toBe(true);
79
+ });
80
+
81
+ test("is idempotent across repeated runs", () => {
82
+ reset();
83
+ insertConversation("greeting");
84
+
85
+ migrateDeleteStrayGreetingConversation(getDb());
86
+ // A second run finds no matching row and must not throw.
87
+ migrateDeleteStrayGreetingConversation(getDb());
88
+
89
+ expect(conversationExists("greeting")).toBe(false);
90
+ });
91
+
92
+ test("no-ops cleanly when there is no greeting row at all", () => {
93
+ reset();
94
+ insertConversation("real-conversation");
95
+
96
+ migrateDeleteStrayGreetingConversation(getDb());
97
+
98
+ expect(conversationExists("real-conversation")).toBe(true);
99
+ });
100
+ });
@@ -454,6 +454,7 @@ import { migrateMoveActivationStateToMemoryDb } from "./migrations/343-move-acti
454
454
  import { migrateMoveConversationGraphMemoryStateToMemoryDb } from "./migrations/344-move-conversation-graph-memory-state-to-memory-db.js";
455
455
  import { migrateMoveMemoryV3EverInjectedToMemoryDb } from "./migrations/345-move-memory-v3-ever-injected-to-memory-db.js";
456
456
  import { migrateMoveMemoryRetrospectiveStateToMemoryDb } from "./migrations/346-move-memory-retrospective-state-to-memory-db.js";
457
+ import { migrateDeleteStrayGreetingConversation } from "./migrations/347-delete-stray-greeting-conversation.js";
457
458
  import type { MigrationStep } from "./migrations/run-migrations.js";
458
459
 
459
460
  export const migrationSteps: MigrationStep[] = [
@@ -1439,4 +1440,5 @@ export const migrationSteps: MigrationStep[] = [
1439
1440
  "migrateMemoryRetrospectiveRememberedLog",
1440
1441
  ],
1441
1442
  },
1443
+ migrateDeleteStrayGreetingConversation,
1442
1444
  ];
@@ -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
@@ -17,13 +17,21 @@
17
17
  *
18
18
  * This module is the single source of truth for:
19
19
  * - the requester identity signals persisted on guardian access requests,
20
- * - the binding-strength ladder derived from `verifiedVia` provenance,
21
20
  * - the signal-driven action list every card surface renders.
22
21
  *
23
- * Binding strength is provenance/audit only — it never enters the capability
24
- * layer (`trusted_contact` ≡ `unverified_contact` on capabilities).
22
+ * The binding-strength ladder and `verified_via` constants are re-exported from
23
+ * `@vellumai/gateway-client` (their canonical home, shared with the gateway ACL
24
+ * write path that enforces demotion refusal — LUM-2505). Binding strength never
25
+ * enters the capability layer — `trusted_contact` ≡ `unverified_contact` on
26
+ * capabilities.
25
27
  */
26
28
 
29
+ import type { BindingStrength } from "@vellumai/gateway-client";
30
+ import {
31
+ VERIFIED_VIA_CHANNEL_CLAIM,
32
+ VERIFIED_VIA_MANUAL,
33
+ } from "@vellumai/gateway-client";
34
+
27
35
  import type { ApprovalAction } from "./channel-approval-types.js";
28
36
 
29
37
  // ---------------------------------------------------------------------------
@@ -110,59 +118,20 @@ export function parseRequesterSignals(
110
118
  }
111
119
 
112
120
  // ---------------------------------------------------------------------------
113
- // Binding strength ladder
121
+ // Binding strength ladder (shared, gateway-owned)
114
122
  // ---------------------------------------------------------------------------
115
123
 
116
- /**
117
- * Binding-strength ladder: how strongly the contact's channel identity is
118
- * bound to the person/agent the guardian believes they are.
119
- *
120
- * verified_handshake > internal_workspace_match > inbound_channel_claim
121
- *
122
- * - `verified_handshake` — the contact proved control of the channel by
123
- * returning a verification code (`verifiedVia: "challenge"`).
124
- * - `internal_workspace_match` — the platform already authenticated the
125
- * identity inside the guardian's own workspace (Slack member or workspace
126
- * app); the guardian vouches directly (`verifiedVia: "manual"`).
127
- * - `inbound_channel_claim` — the guardian trusts an identity the platform is
128
- * NOT vouching for (external / Slack-Connect / restricted guest / channels
129
- * without workspace identity). Recorded as
130
- * `verifiedVia: "manual_channel_claim"` so a trusted-anyway external never
131
- * carries the same provenance as a code-verified contact.
132
- */
133
- export type BindingStrength =
134
- | "verified_handshake"
135
- | "internal_workspace_match"
136
- | "inbound_channel_claim";
137
-
138
- /** verifiedVia written when the guardian direct-trusts a workspace-vouched identity. */
139
- export const VERIFIED_VIA_MANUAL = "manual";
140
-
141
- /** verifiedVia written when the guardian trusts an identity the platform is not vouching for. */
142
- export const VERIFIED_VIA_CHANNEL_CLAIM = "manual_channel_claim";
143
-
144
- /** verifiedVia written by the gateway when a verification code is redeemed. */
145
- export const VERIFIED_VIA_CHALLENGE = "challenge";
146
-
147
- /**
148
- * Derive the binding strength recorded by a `verifiedVia` provenance value.
149
- * Returns null for provenance outside the introduction ladder (e.g. "invite",
150
- * "bootstrap"), which predate it and keep their own audit meaning.
151
- */
152
- export function bindingStrengthForVerifiedVia(
153
- verifiedVia: string | null | undefined,
154
- ): BindingStrength | null {
155
- switch (verifiedVia) {
156
- case VERIFIED_VIA_CHALLENGE:
157
- return "verified_handshake";
158
- case VERIFIED_VIA_MANUAL:
159
- return "internal_workspace_match";
160
- case VERIFIED_VIA_CHANNEL_CLAIM:
161
- return "inbound_channel_claim";
162
- default:
163
- return null;
164
- }
165
- }
124
+ // The binding-strength ladder and `verified_via` provenance constants are the
125
+ // canonical vocabulary in `@vellumai/gateway-client`
126
+ // (`binding-strength-contract.ts`); the gateway ACL write path enforces
127
+ // demotion refusal on the same values (LUM-2505). Re-exported here so
128
+ // introduction-card call sites keep importing them from this module.
129
+ export {
130
+ bindingStrengthForVerifiedVia,
131
+ VERIFIED_VIA_CHALLENGE,
132
+ } from "@vellumai/gateway-client";
133
+ export { VERIFIED_VIA_CHANNEL_CLAIM, VERIFIED_VIA_MANUAL };
134
+ export type { BindingStrength };
166
135
 
167
136
  /**
168
137
  * Whether the platform itself vouches for the requester's identity inside the
@@ -119,13 +119,20 @@ async function handleBtw({
119
119
  }
120
120
  }
121
121
 
122
- // Look up an existing conversation or create an ephemeral one.
122
+ // Look up an existing conversation or create an ephemeral one. An unmapped
123
+ // key (e.g. "greeting") does not correspond to a real conversation, so the
124
+ // side-chain runs against an ephemeral in-memory conversation with no
125
+ // persisted row — keeping the "no messages are persisted" contract and off
126
+ // the sidebar. A mapped key targets a real conversation and reuses its row.
123
127
  const mapping = getConversationByKey(conversationKey);
124
128
  const conversationId = mapping?.conversationId ?? conversationKey;
125
129
 
126
130
  let conversation;
127
131
  try {
128
- conversation = await getOrCreateConversation(conversationId);
132
+ conversation = await getOrCreateConversation(
133
+ conversationId,
134
+ mapping ? undefined : { ephemeral: true },
135
+ );
129
136
  } catch {
130
137
  throw new ServiceUnavailableError("Message processing is not available");
131
138
  }
@@ -55,6 +55,7 @@ import { downloadSlackFile } from "../../messaging/providers/slack/download.js";
55
55
  import {
56
56
  buildSlackTimezoneMetadata,
57
57
  formatSlackTimezoneLabel,
58
+ isSlackTs,
58
59
  mergeSlackMetadata,
59
60
  readSlackMetadataFromMessageMetadata,
60
61
  type SlackFileMetadata,
@@ -750,6 +751,10 @@ export async function handleChannelInbound({
750
751
  },
751
752
  slackActorTimezone,
752
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;
753
758
 
754
759
  // ── Admission policy floor ──
755
760
  // Sits between trust resolution and the agent loop. The gateway attaches
@@ -1459,19 +1464,6 @@ export async function handleChannelInbound({
1459
1464
  */
1460
1465
  const SLACK_DM_BACKFILL_WARM_THRESHOLD = 3;
1461
1466
 
1462
- /**
1463
- * Shape-check for a Slack `ts` value. Slack IDs messages by `<seconds>.<micros>`
1464
- * strings (e.g. `"1700000000.000100"`). The daemon also stores an
1465
- * `externalMessageId` derived from the gateway's dedupe key which follows a
1466
- * different format, so any path that feeds a ts to Slack's API
1467
- * (`conversations.history`'s `latest`, etc.) must shape-check first — Slack
1468
- * rejects non-ts arguments with `invalid_arguments`, and passing a malformed
1469
- * bound silently disables the intended history window.
1470
- */
1471
- function isSlackTs(value: string | null | undefined): value is string {
1472
- return typeof value === "string" && /^\d+\.\d+$/.test(value);
1473
- }
1474
-
1475
1467
  /**
1476
1468
  * Batch size used when pulling candidate rows from SQL. A bare
1477
1469
  * `LIKE '%"slackMeta"%'` match can include rows whose metadata JSON is
@@ -5,11 +5,9 @@
5
5
 
6
6
  import { z } from "zod";
7
7
 
8
- import type {
9
- ServiceGroupUpdateComplete,
10
- ServiceGroupUpdateProgress,
11
- ServiceGroupUpdateStarting,
12
- } from "../../daemon/message-types/upgrades.js";
8
+ import type { ServiceGroupUpdateCompleteEvent } from "../../api/events/service-group-update-complete.js";
9
+ import type { ServiceGroupUpdateProgressEvent } from "../../api/events/service-group-update-progress.js";
10
+ import type { ServiceGroupUpdateStartingEvent } from "../../api/events/service-group-update-starting.js";
13
11
  import { buildAssistantEvent } from "../assistant-event.js";
14
12
  import { assistantEventHub } from "../assistant-event-hub.js";
15
13
  import { GATEWAY_PRINCIPALS } from "../auth/route-policy.js";
@@ -44,7 +42,7 @@ async function handleUpgradeBroadcast({ body }: RouteHandlerArgs) {
44
42
  );
45
43
  }
46
44
 
47
- const message: ServiceGroupUpdateStarting = {
45
+ const message: ServiceGroupUpdateStartingEvent = {
48
46
  type: "service_group_update_starting",
49
47
  targetVersion,
50
48
  expectedDowntimeSeconds: downtime,
@@ -64,7 +62,7 @@ async function handleUpgradeBroadcast({ body }: RouteHandlerArgs) {
64
62
  );
65
63
  }
66
64
 
67
- const message: ServiceGroupUpdateProgress = {
65
+ const message: ServiceGroupUpdateProgressEvent = {
68
66
  type: "service_group_update_progress",
69
67
  statusMessage,
70
68
  };
@@ -101,7 +99,7 @@ async function handleUpgradeBroadcast({ body }: RouteHandlerArgs) {
101
99
  );
102
100
  }
103
101
 
104
- const message: ServiceGroupUpdateComplete = {
102
+ const message: ServiceGroupUpdateCompleteEvent = {
105
103
  type: "service_group_update_complete",
106
104
  installedVersion,
107
105
  success,
@@ -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