@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
@@ -4,7 +4,14 @@ import { z } from "zod";
4
4
  import { SurfaceActionSchema } from "../api/events/ui-surface-show.js";
5
5
  import {
6
6
  CardSurfaceDataSchema,
7
- FileUploadSurfaceDataSchema,
7
+ ChoiceSurfaceDataSchema,
8
+ coerceSurfaceDataRecord,
9
+ DynamicPageSurfaceDataSchema,
10
+ normalizeCopyBlockShowData,
11
+ OAuthConnectSurfaceDataSchema,
12
+ safeParseSurfaceData,
13
+ SURFACE_TYPES,
14
+ SurfaceTypeSchema,
8
15
  } from "../api/surfaces.js";
9
16
  import {
10
17
  addAppConversationId,
@@ -55,12 +62,9 @@ import type {
55
62
  CardSurfaceData,
56
63
  ChoiceSurfaceData,
57
64
  ConfirmationSurfaceData,
58
- CopyBlockSurfaceData,
59
65
  DynamicPageSurfaceData,
60
- FileUploadSurfaceData,
61
66
  FormSurfaceData,
62
67
  ListSurfaceData,
63
- OAuthConnectSurfaceData,
64
68
  ServerMessage,
65
69
  SurfaceData,
66
70
  SurfaceType,
@@ -475,7 +479,7 @@ function normalizeDynamicPageShowData(
475
479
  normalized.preview = input.preview;
476
480
  }
477
481
 
478
- return normalized as unknown as DynamicPageSurfaceData;
482
+ return DynamicPageSurfaceDataSchema.parse(normalized);
479
483
  }
480
484
 
481
485
  /** First entry that is a non-empty (trimmed) string, else undefined. */
@@ -714,105 +718,6 @@ function normalizeTaskProgressCardPatch(
714
718
  return normalizedPatch;
715
719
  }
716
720
 
717
- function normalizeChoiceShowData(
718
- rawData: Record<string, unknown>,
719
- ): ChoiceSurfaceData {
720
- const options = Array.isArray(rawData.options)
721
- ? rawData.options
722
- .filter((option): option is Record<string, unknown> =>
723
- isPlainObject(option),
724
- )
725
- .map((option) => {
726
- const id = typeof option.id === "string" ? option.id.trim() : "";
727
- const title =
728
- typeof option.title === "string"
729
- ? option.title.trim()
730
- : typeof option.label === "string"
731
- ? option.label.trim()
732
- : "";
733
- if (!id || !title) {
734
- return null;
735
- }
736
- return {
737
- id,
738
- title,
739
- ...(typeof option.description === "string"
740
- ? { description: option.description }
741
- : {}),
742
- ...(option.recommended === true ? { recommended: true } : {}),
743
- ...(isPlainObject(option.data)
744
- ? { data: option.data as Record<string, unknown> }
745
- : {}),
746
- };
747
- })
748
- .filter(
749
- (option): option is NonNullable<typeof option> => option !== null,
750
- )
751
- : [];
752
-
753
- return {
754
- ...(typeof rawData.description === "string"
755
- ? { description: rawData.description }
756
- : {}),
757
- options,
758
- selectionMode: rawData.selectionMode === "multiple" ? "multiple" : "single",
759
- ...(typeof rawData.submitLabel === "string"
760
- ? { submitLabel: rawData.submitLabel }
761
- : {}),
762
- ...(typeof rawData.commitOnSelect === "boolean"
763
- ? { commitOnSelect: rawData.commitOnSelect }
764
- : {}),
765
- };
766
- }
767
-
768
- function normalizeCopyBlockShowData(
769
- rawData: Record<string, unknown>,
770
- ): CopyBlockSurfaceData {
771
- return {
772
- text: typeof rawData.text === "string" ? rawData.text : "",
773
- ...(typeof rawData.label === "string" ? { label: rawData.label } : {}),
774
- ...(typeof rawData.language === "string"
775
- ? { language: rawData.language }
776
- : {}),
777
- };
778
- }
779
-
780
- function normalizeOAuthConnectShowData(
781
- rawData: Record<string, unknown>,
782
- ): OAuthConnectSurfaceData {
783
- return {
784
- providerKey:
785
- typeof rawData.providerKey === "string" ? rawData.providerKey.trim() : "",
786
- ...(typeof rawData.displayName === "string"
787
- ? { displayName: rawData.displayName }
788
- : {}),
789
- ...(typeof rawData.description === "string"
790
- ? { description: rawData.description }
791
- : {}),
792
- ...(typeof rawData.logoUrl === "string" || rawData.logoUrl === null
793
- ? { logoUrl: rawData.logoUrl }
794
- : {}),
795
- };
796
- }
797
-
798
- function normalizeFileUploadShowData(
799
- rawData: Record<string, unknown>,
800
- ): FileUploadSurfaceData {
801
- // Parse against the canonical schema so the surface carries the shape the
802
- // renderer expects. The schema is tolerant (every field optional and coerced)
803
- // and recovers the common malformed `acceptedTypes` shapes — a comma-joined or
804
- // bare string — into the `string[]` the renderer requires.
805
- const parsed = FileUploadSurfaceDataSchema.safeParse(rawData);
806
- if (parsed.success) {
807
- return parsed.data;
808
- }
809
- log.warn(
810
- { issues: parsed.error.issues },
811
- "ui_show file_upload data failed FileUploadSurfaceDataSchema; rendering an empty file_upload surface",
812
- );
813
- return {};
814
- }
815
-
816
721
  function buildChoiceActions(data: ChoiceSurfaceData): Array<{
817
722
  id: string;
818
723
  label: string;
@@ -848,12 +753,13 @@ function isSlackTaskProgressUiException(
848
753
  return false;
849
754
  }
850
755
  if (toolName === "ui_show") {
851
- const surfaceType = input.surface_type as SurfaceType;
852
- if (surfaceType !== "card") {
756
+ if (input.surface_type !== "card") {
853
757
  return false;
854
758
  }
855
- const rawData = isPlainObject(input.data) ? input.data : {};
856
- const data = normalizeCardShowData(input, rawData);
759
+ const data = normalizeCardShowData(
760
+ input,
761
+ coerceSurfaceDataRecord(input.data),
762
+ );
857
763
  return isTaskProgressCardData(data);
858
764
  }
859
765
  if (toolName === "ui_update") {
@@ -868,13 +774,12 @@ function isSlackTaskProgressUiException(
868
774
  if (!isTaskProgressCardData(stored.data)) {
869
775
  return false;
870
776
  }
871
- const rawPatch = isPlainObject(input.data) ? input.data : {};
777
+ const rawPatch = coerceSurfaceDataRecord(input.data);
872
778
  const patch = normalizeTaskProgressCardPatch(
873
779
  stored.data as CardSurfaceData,
874
780
  rawPatch,
875
781
  );
876
- const mergedData = { ...stored.data, ...patch } as SurfaceData;
877
- return isTaskProgressCardData(mergedData);
782
+ return isTaskProgressCardData({ ...stored.data, ...patch });
878
783
  }
879
784
  return false;
880
785
  }
@@ -1123,7 +1028,7 @@ export function showStandaloneSurface(
1123
1028
  const timeoutMs = request.timeoutMs ?? DEFAULT_STANDALONE_TIMEOUT_MS;
1124
1029
 
1125
1030
  // Build surface data from the request payload.
1126
- const surfaceType = request.surfaceType as SurfaceType;
1031
+ const surfaceType: SurfaceType = request.surfaceType;
1127
1032
  const data = buildStandaloneSurfaceData(request);
1128
1033
  const actions = request.actions?.map((a) => ({
1129
1034
  id: a.id,
@@ -1249,8 +1154,8 @@ function buildStandaloneSurfaceData(
1249
1154
  } as FormSurfaceData;
1250
1155
  }
1251
1156
 
1252
- // Fallback: pass through opaque data
1253
- return request.data as unknown as SurfaceData;
1157
+ // Any other surface type: parse through its canonical schema.
1158
+ return safeParseSurfaceData(request.surfaceType, request.data) ?? {};
1254
1159
  }
1255
1160
 
1256
1161
  /**
@@ -1394,7 +1299,7 @@ export function openChannelSetupPanel(
1394
1299
  // conversationId. Cleared by cleanupStandaloneSurface on all outcomes.
1395
1300
  ctx.surfaceState.set(surfaceId, {
1396
1301
  surfaceType: "channel_setup",
1397
- data: data as SurfaceData,
1302
+ data: safeParseSurfaceData("channel_setup", data) ?? {},
1398
1303
  });
1399
1304
 
1400
1305
  ctx.sendToClient({
@@ -3028,9 +2933,24 @@ export async function surfaceProxyResolver(
3028
2933
 
3029
2934
  if (toolName === "ui_show") {
3030
2935
  const surfaceId = uuid();
3031
- const surfaceType = input.surface_type as SurfaceType;
2936
+ // Parse, don't cast: an unrecognized surface_type used to be asserted
2937
+ // into the union and fall through to an opaque passthrough the client
2938
+ // silently dropped. Reject it with the valid values instead.
2939
+ const parsedSurfaceType = SurfaceTypeSchema.safeParse(input.surface_type);
2940
+ if (!parsedSurfaceType.success) {
2941
+ const got =
2942
+ typeof input.surface_type === "string" &&
2943
+ input.surface_type.trim().length > 0
2944
+ ? `"${input.surface_type}" is not a valid surface_type`
2945
+ : "`surface_type` is missing";
2946
+ return {
2947
+ content: `Error: ui_show was not displayed — ${got}. Valid surface_type values: ${SURFACE_TYPES.join(", ")}. Resend ui_show with one of these values.`,
2948
+ isError: true,
2949
+ };
2950
+ }
2951
+ const surfaceType = parsedSurfaceType.data;
3032
2952
  const title = typeof input.title === "string" ? input.title : undefined;
3033
- const rawData = isPlainObject(input.data) ? input.data : {};
2953
+ const rawData = coerceSurfaceDataRecord(input.data);
3034
2954
 
3035
2955
  // channel_setup is a side-effect-only command: it opens the channel setup
3036
2956
  // drawer on the client. Emitted as `open_panel` (not `ui_surface_show`)
@@ -3081,28 +3001,33 @@ export async function surfaceProxyResolver(
3081
3001
  };
3082
3002
  }
3083
3003
 
3084
- // Each surface type that has a canonical Zod schema gets parsed through it;
3085
- // the rest pass through raw until migrated (LUM-2134 scope). The per-type
3086
- // normalizers validate+recover; the union cast at the end is only for the
3087
- // unmigrated branches that still return hand-written interfaces.
3004
+ // Every surface type parses through its canonical schema. Card,
3005
+ // copy_block, and dynamic_page first run bespoke normalizers that
3006
+ // recover fields the model placed at the top level of the tool input;
3007
+ // the rest go straight through `safeParseSurfaceData`. Choice and
3008
+ // oauth_connect parse into named bindings so their content guards below
3009
+ // read typed data instead of re-narrowing the union.
3088
3010
  const cardData =
3089
3011
  surfaceType === "card"
3090
3012
  ? normalizeCardShowData(input, rawData)
3091
3013
  : undefined;
3014
+ const choiceData =
3015
+ surfaceType === "choice"
3016
+ ? ChoiceSurfaceDataSchema.parse(rawData)
3017
+ : undefined;
3018
+ const oauthData =
3019
+ surfaceType === "oauth_connect"
3020
+ ? OAuthConnectSurfaceDataSchema.parse(rawData)
3021
+ : undefined;
3092
3022
  const data: SurfaceData =
3093
- cardData !== undefined
3094
- ? cardData
3095
- : surfaceType === "choice"
3096
- ? normalizeChoiceShowData(rawData)
3097
- : surfaceType === "copy_block"
3098
- ? normalizeCopyBlockShowData(rawData)
3099
- : surfaceType === "oauth_connect"
3100
- ? normalizeOAuthConnectShowData(rawData)
3101
- : surfaceType === "dynamic_page"
3102
- ? normalizeDynamicPageShowData(input, rawData)
3103
- : surfaceType === "file_upload"
3104
- ? normalizeFileUploadShowData(rawData)
3105
- : (rawData as SurfaceData);
3023
+ cardData ??
3024
+ choiceData ??
3025
+ oauthData ??
3026
+ (surfaceType === "copy_block"
3027
+ ? normalizeCopyBlockShowData(input, rawData)
3028
+ : surfaceType === "dynamic_page"
3029
+ ? normalizeDynamicPageShowData(input, rawData)
3030
+ : (safeParseSurfaceData(surfaceType, rawData) ?? {}));
3106
3031
  // Parse actions through the schema instead of typecasting raw model output.
3107
3032
  // The model may place actions inside `data` instead of the top-level
3108
3033
  // `actions` param — recover them so they aren't silently dropped.
@@ -3123,9 +3048,7 @@ export async function surfaceProxyResolver(
3123
3048
  inputActions = valid.length > 0 ? valid : undefined;
3124
3049
  }
3125
3050
  const actions =
3126
- surfaceType === "choice"
3127
- ? buildChoiceActions(data as ChoiceSurfaceData)
3128
- : inputActions;
3051
+ choiceData !== undefined ? buildChoiceActions(choiceData) : inputActions;
3129
3052
  const hasActions = Array.isArray(actions) && actions.length > 0;
3130
3053
  if (surfaceType === "choice" && !hasActions) {
3131
3054
  return {
@@ -3162,15 +3085,7 @@ export async function surfaceProxyResolver(
3162
3085
  };
3163
3086
  }
3164
3087
  }
3165
- const oauthProviderKey =
3166
- surfaceType === "oauth_connect"
3167
- ? (data as unknown as Record<string, unknown>).providerKey
3168
- : undefined;
3169
- if (
3170
- surfaceType === "oauth_connect" &&
3171
- (typeof oauthProviderKey !== "string" ||
3172
- oauthProviderKey.trim().length === 0)
3173
- ) {
3088
+ if (oauthData !== undefined && oauthData.providerKey.length === 0) {
3174
3089
  return {
3175
3090
  content: "oauth_connect surfaces require data.providerKey.",
3176
3091
  isError: true,
@@ -3309,10 +3224,7 @@ export async function surfaceProxyResolver(
3309
3224
 
3310
3225
  if (toolName === "ui_update") {
3311
3226
  const surfaceId = input.surface_id as string;
3312
- let patch = (isPlainObject(input.data) ? input.data : {}) as Record<
3313
- string,
3314
- unknown
3315
- >;
3227
+ let patch = coerceSurfaceDataRecord(input.data);
3316
3228
 
3317
3229
  // Merge the partial patch into the stored full surface data
3318
3230
  const stored = ctx.surfaceState.get(surfaceId);
@@ -3330,28 +3242,26 @@ export async function surfaceProxyResolver(
3330
3242
  pushUndoState(ctx.surfaceUndoStacks, surfaceId, currentHtml);
3331
3243
  }
3332
3244
  const rawMerged = { ...stored.data, ...patch };
3333
- if (stored.surfaceType === "card") {
3334
- // Validate the merged card data through the canonical schema so
3335
- // malformed patches (e.g. metadata as a string) are caught here
3336
- // instead of crashing the client's safeParse.
3337
- const parsed = CardSurfaceDataSchema.safeParse(rawMerged);
3338
- mergedData = parsed.success
3339
- ? parsed.data
3340
- : (CardSurfaceDataSchema.safeParse(stored.data).data ?? {});
3341
- if (!parsed.success) {
3342
- log.warn(
3343
- { surfaceId, issues: parsed.error.issues },
3344
- "ui_update card patch produced invalid merged data; reverting to stored data",
3345
- );
3346
- }
3245
+ // Validate the merged data through the surface type's canonical schema
3246
+ // so malformed patches (e.g. metadata as a string) are caught here
3247
+ // instead of crashing the client's safeParse.
3248
+ const parsed = safeParseSurfaceData(stored.surfaceType, rawMerged);
3249
+ if (parsed !== undefined) {
3250
+ mergedData = parsed;
3347
3251
  } else {
3348
- // Other surface types lack canonical Zod schemas (LUM-2134 scope).
3349
- // The raw merge is the best we can do until they're migrated.
3350
- mergedData = rawMerged as SurfaceData;
3252
+ log.warn(
3253
+ { surfaceId, surfaceType: stored.surfaceType },
3254
+ "ui_update patch produced invalid merged data; reverting to stored data",
3255
+ );
3256
+ mergedData =
3257
+ safeParseSurfaceData(stored.surfaceType, stored.data) ?? stored.data;
3351
3258
  }
3352
3259
  stored.data = mergedData;
3353
3260
  } else {
3354
- mergedData = patch as unknown as SurfaceData;
3261
+ // No stored state for this surfaceId, so its surface type — and
3262
+ // therefore its canonical schema — is unknown; forward the patch
3263
+ // opaquely rather than dropping the update.
3264
+ mergedData = patch as SurfaceData;
3355
3265
  }
3356
3266
 
3357
3267
  ctx.sendToClient({
@@ -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
@@ -147,6 +147,14 @@ export interface ConversationCreateOptions {
147
147
  * task permissions do not leak into later turns on a reused conversation.
148
148
  */
149
149
  taskRunId?: string;
150
+ /**
151
+ * Skip persisting a `conversations` row for this call. The in-memory
152
+ * {@link Conversation} is still built and hydrated from whatever rows
153
+ * already exist, but no sidebar-visible row is created — used by ephemeral
154
+ * side-chains (e.g. the empty-state greeting) whose contract persists
155
+ * nothing. Per-call only: never merged into stored conversation metadata.
156
+ */
157
+ ephemeral?: boolean;
150
158
  /** Normalized auth context for the conversation. */
151
159
  authContext?: AuthContext;
152
160
  /** Whether this turn can block on interactive approval prompts. */
@@ -704,7 +712,9 @@ export function renderHistoryContent(
704
712
  continue;
705
713
  }
706
714
  const resolved = resolveMediaSourceData(source);
707
- if (resolved) {imageDataList.push(resolved.data);}
715
+ if (resolved) {
716
+ imageDataList.push(resolved.data);
717
+ }
708
718
  }
709
719
  }
710
720
  }
@@ -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,7 +38,7 @@ export {
38
38
  type ListItem,
39
39
  ListSurfaceDataSchema,
40
40
  OAuthConnectSurfaceDataSchema,
41
- SURFACE_DATA_SCHEMAS,
41
+ safeParseSurfaceData,
42
42
  SURFACE_TYPES,
43
43
  SurfaceTypeSchema,
44
44
  type TableCellValue,
@@ -1,31 +1,14 @@
1
- /** Broadcast to connected clients when a service group update is about to begin. */
2
- export interface ServiceGroupUpdateStarting {
3
- type: "service_group_update_starting";
4
- /** The version being upgraded to. */
5
- targetVersion: string;
6
- /** Estimated seconds of downtime. */
7
- expectedDowntimeSeconds: number;
8
- }
1
+ // Service-group upgrade lifecycle 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`.
9
6
 
10
- /** Broadcast to connected clients with a progress update during an upgrade or rollback. */
11
- export interface ServiceGroupUpdateProgress {
12
- type: "service_group_update_progress";
13
- /** A short, user-friendly status message describing what's happening right now. */
14
- statusMessage: string;
15
- }
16
-
17
- /** Broadcast to connected clients when a service group update has completed. */
18
- export interface ServiceGroupUpdateComplete {
19
- type: "service_group_update_complete";
20
- /** The version that was installed (may differ from target if rolled back). */
21
- installedVersion: string;
22
- /** Whether the update succeeded or rolled back. */
23
- success: boolean;
24
- /** If rolled back, the version reverted to. */
25
- rolledBackToVersion?: string;
26
- }
7
+ import type { ServiceGroupUpdateCompleteEvent } from "../../api/events/service-group-update-complete.js";
8
+ import type { ServiceGroupUpdateProgressEvent } from "../../api/events/service-group-update-progress.js";
9
+ import type { ServiceGroupUpdateStartingEvent } from "../../api/events/service-group-update-starting.js";
27
10
 
28
11
  export type _UpgradesServerMessages =
29
- | ServiceGroupUpdateStarting
30
- | ServiceGroupUpdateProgress
31
- | ServiceGroupUpdateComplete;
12
+ | ServiceGroupUpdateStartingEvent
13
+ | ServiceGroupUpdateProgressEvent
14
+ | ServiceGroupUpdateCompleteEvent;
@@ -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
@@ -1,12 +1,16 @@
1
1
  import { z } from "zod";
2
2
 
3
3
  /** Channel-neutral deep-link pair into an external client: a native app URL
4
- * (e.g. `slack://…`) and/or a browser URL. */
5
- const externalSourceLinkSchema = z.object({
4
+ * (e.g. `slack://…`) and/or a browser URL. Exported as the single source of
5
+ * truth for this shape — consumers (binding metadata, approval source
6
+ * references) reuse it rather than re-declaring the pair. */
7
+ export const externalSourceLinkSchema = z.object({
6
8
  appUrl: z.string().optional(),
7
9
  webUrl: z.string().optional(),
8
10
  });
9
11
 
12
+ export type ExternalSourceLink = z.infer<typeof externalSourceLinkSchema>;
13
+
10
14
  const slackThreadSchema = z.object({
11
15
  channelId: z.string(),
12
16
  threadTs: z.string(),
@@ -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
+ }