@vellumai/assistant 0.8.9 → 0.8.10-dev.202606092238.d04fd59

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 (147) hide show
  1. package/AGENTS.md +1 -1
  2. package/examples/plugins/echo/README.md +3 -3
  3. package/node_modules/@vellumai/skill-host-contracts/src/tool-types.ts +2 -0
  4. package/openapi.yaml +38 -12
  5. package/package.json +1 -1
  6. package/scripts/sync-llm-catalog.ts +2 -0
  7. package/src/__tests__/agent-loop-exit-reason.test.ts +19 -14
  8. package/src/__tests__/build-persisted-content.test.ts +75 -1
  9. package/src/__tests__/config-managed-gemini-defaults.test.ts +2 -46
  10. package/src/__tests__/context-overflow-reducer.test.ts +264 -124
  11. package/src/__tests__/context-window-manager-overflow-rung.test.ts +289 -0
  12. package/src/__tests__/conversation-agent-loop-overflow.test.ts +22 -22
  13. package/src/__tests__/conversation-agent-loop.test.ts +45 -37
  14. package/src/__tests__/conversation-fork-crud.test.ts +110 -0
  15. package/src/__tests__/conversation-provider-retry-repair.test.ts +16 -20
  16. package/src/__tests__/conversation-runtime-assembly.test.ts +118 -5
  17. package/src/__tests__/conversation-surfaces-app-control.test.ts +4 -1
  18. package/src/__tests__/conversation-tool-setup-app-refresh.test.ts +91 -142
  19. package/src/__tests__/conversation-tool-setup-skill-attribution.test.ts +116 -0
  20. package/src/__tests__/conversation-tool-setup-test-helpers.ts +98 -0
  21. package/src/__tests__/corrected-target.test.ts +93 -0
  22. package/src/__tests__/credential-execution-feature-gates.test.ts +3 -5
  23. package/src/__tests__/credential-security-invariants.test.ts +1 -0
  24. package/src/__tests__/embedding-managed-proxy-selection.test.ts +6 -40
  25. package/src/__tests__/external-plugin-loader.test.ts +0 -1
  26. package/src/__tests__/guardian-routing-invariants.test.ts +91 -0
  27. package/src/__tests__/history-repair-hook.test.ts +2 -0
  28. package/src/__tests__/host-app-control-proxy.test.ts +45 -0
  29. package/src/__tests__/llm-catalog-parity.test.ts +4 -0
  30. package/src/__tests__/memory-retrieval-hook.test.ts +29 -15
  31. package/src/__tests__/notification-decision-strategy.test.ts +3 -3
  32. package/src/__tests__/persistence-secret-redaction.test.ts +78 -0
  33. package/src/__tests__/plugin-bootstrap.test.ts +82 -73
  34. package/src/__tests__/plugin-tool-contribution.test.ts +7 -4
  35. package/src/__tests__/plugin-types.test.ts +0 -8
  36. package/src/__tests__/provider-catalog-visibility.test.ts +1 -9
  37. package/src/__tests__/retry-thinking-adaptive-only.test.ts +245 -0
  38. package/src/__tests__/server-history-render.test.ts +39 -0
  39. package/src/__tests__/skills.test.ts +123 -0
  40. package/src/__tests__/title-generate-hook.test.ts +2 -0
  41. package/src/__tests__/tool-audit-listener.test.ts +51 -0
  42. package/src/__tests__/tool-executor-lifecycle-events.test.ts +32 -0
  43. package/src/__tests__/tool-start-timestamp.test.ts +218 -0
  44. package/src/agent/loop.ts +26 -23
  45. package/src/api/events/tool-result.ts +9 -0
  46. package/src/api/events/tool-use-start.ts +7 -0
  47. package/src/api/responses/conversation-message.ts +91 -14
  48. package/src/approvals/guardian-request-resolvers.ts +26 -0
  49. package/src/cli/commands/channel-verification-sessions.ts +6 -6
  50. package/src/cli/commands/inference-providers.ts +0 -8
  51. package/src/cli/commands/plugins.ts +2 -2
  52. package/src/cli/lib/__tests__/install-from-github.test.ts +174 -18
  53. package/src/cli/lib/__tests__/plugin-catalog-cache.test.ts +1 -1
  54. package/src/cli/lib/__tests__/plugin-details.test.ts +1 -1
  55. package/src/cli/lib/__tests__/plugin-marketplace.test.ts +1 -1
  56. package/src/cli/lib/__tests__/search-plugins.test.ts +11 -11
  57. package/src/cli/lib/install-from-github.ts +130 -19
  58. package/src/cli/lib/plugin-catalog-cache.ts +1 -1
  59. package/src/cli/lib/plugin-details.ts +4 -4
  60. package/src/cli/lib/plugin-marketplace.ts +2 -2
  61. package/src/cli/lib/search-plugins.ts +6 -6
  62. package/src/config/bundled-skills/skill-management/SKILL.md +89 -1
  63. package/src/config/env-registry.ts +12 -0
  64. package/src/config/feature-flag-registry.json +0 -80
  65. package/src/config/loader.ts +5 -22
  66. package/src/config/seed-inference-profiles.ts +1 -1
  67. package/src/config/skills.ts +101 -47
  68. package/src/context/strip-injections.ts +7 -4
  69. package/src/daemon/conversation-agent-loop-handlers.ts +102 -6
  70. package/src/daemon/conversation-agent-loop.ts +134 -232
  71. package/src/daemon/conversation-runtime-assembly.ts +44 -8
  72. package/src/daemon/conversation-tool-setup.ts +9 -1
  73. package/src/daemon/external-plugins-bootstrap.ts +33 -87
  74. package/src/daemon/handlers/config-channels.ts +11 -2
  75. package/src/daemon/handlers/shared.ts +9 -1
  76. package/src/daemon/handlers/skills.ts +6 -2
  77. package/src/daemon/host-app-control-proxy.ts +72 -57
  78. package/src/daemon/message-protocol.ts +0 -7
  79. package/src/daemon/message-types/skills.ts +4 -0
  80. package/src/events/tool-audit-listener.ts +7 -1
  81. package/src/memory/__tests__/tool-invocation-test-helpers.ts +69 -0
  82. package/src/memory/conversation-crud.ts +44 -1
  83. package/src/memory/db-init.ts +4 -0
  84. package/src/memory/embedding-backend.ts +5 -22
  85. package/src/memory/memory-retrospective-startup-cleanup.ts +1 -1
  86. package/src/memory/migrations/275-tool-invocations-add-skill-id.test.ts +81 -0
  87. package/src/memory/migrations/275-tool-invocations-add-skill-id.ts +20 -0
  88. package/src/memory/migrations/276-tool-invocations-created-at-id-index.test.ts +68 -0
  89. package/src/memory/migrations/276-tool-invocations-created-at-id-index.ts +20 -0
  90. package/src/memory/migrations/index.ts +2 -0
  91. package/src/memory/schema/conversations.ts +3 -0
  92. package/src/memory/tool-execution-events-store.test.ts +162 -0
  93. package/src/memory/tool-execution-events-store.ts +73 -0
  94. package/src/memory/tool-usage-store.ts +4 -3
  95. package/src/memory/v2/__tests__/injected-block-slugs.test.ts +51 -0
  96. package/src/memory/v2/activation-store.ts +50 -1
  97. package/src/memory/v2/injected-block-slugs.ts +30 -0
  98. package/src/notifications/__tests__/copy-composer.test.ts +244 -0
  99. package/src/notifications/access-request-copy.ts +298 -0
  100. package/src/notifications/adapters/slack.ts +3 -3
  101. package/src/notifications/adapters/telegram.ts +2 -1
  102. package/src/notifications/copy-composer.ts +49 -267
  103. package/src/notifications/decision-engine.ts +16 -35
  104. package/src/notifications/home-feed-side-effect.ts +1 -6
  105. package/src/platform/client.ts +1 -3
  106. package/src/platform/feature-gate.ts +3 -12
  107. package/src/plugin-api/constants.ts +2 -0
  108. package/src/plugin-api/index.ts +34 -6
  109. package/src/plugin-api/types.ts +19 -0
  110. package/src/plugins/defaults/compaction/compact.ts +39 -1
  111. package/src/plugins/defaults/compaction/context-overflow-reducer.ts +240 -32
  112. package/src/plugins/defaults/compaction/corrected-target.ts +53 -0
  113. package/src/plugins/defaults/compaction/window-manager.ts +136 -0
  114. package/src/plugins/defaults/index.ts +24 -0
  115. package/src/plugins/defaults/memory-retrieval/hooks/post-compact.ts +68 -43
  116. package/src/plugins/defaults/memory-retrieval/hooks/{user-prompt-submit-temp.ts → user-prompt-submit.ts} +36 -67
  117. package/src/plugins/defaults/memory-retrieval/package.json +14 -0
  118. package/src/plugins/external-api.ts +1 -1
  119. package/src/plugins/types.ts +5 -51
  120. package/src/providers/inference/__tests__/base-url-route-validation.test.ts +1 -2
  121. package/src/providers/model-catalog.ts +57 -1
  122. package/src/providers/registry.ts +0 -8
  123. package/src/providers/retry.ts +35 -7
  124. package/src/runtime/routes/__tests__/acp-routes.test.ts +151 -0
  125. package/src/runtime/routes/__tests__/inference-provider-connection-routes.test.ts +0 -62
  126. package/src/runtime/routes/__tests__/plugins-routes.test.ts +4 -4
  127. package/src/runtime/routes/acp-routes.test.ts +106 -0
  128. package/src/runtime/routes/acp-routes.ts +248 -2
  129. package/src/runtime/routes/browser-tabs-routes.ts +1 -1
  130. package/src/runtime/routes/channel-verification-routes.ts +14 -5
  131. package/src/runtime/routes/chatgpt-subscription-auth-routes.ts +0 -14
  132. package/src/runtime/routes/inbound-stages/acl-enforcement.ts +33 -34
  133. package/src/runtime/routes/inference-provider-connection-routes.ts +0 -45
  134. package/src/runtime/routes/plugins-routes.ts +3 -3
  135. package/src/runtime/verification-outbound-actions.ts +147 -2
  136. package/src/runtime/verification-templates.ts +29 -3
  137. package/src/telemetry/types.ts +25 -1
  138. package/src/telemetry/usage-telemetry-reporter.test.ts +141 -7
  139. package/src/telemetry/usage-telemetry-reporter.ts +63 -7
  140. package/src/tools/executor.ts +4 -1
  141. package/src/tools/skills/load.ts +11 -6
  142. package/src/tools/terminal/safe-env.ts +1 -0
  143. package/src/tools/types.ts +10 -0
  144. package/src/__tests__/plugin-skill-contribution.test.ts +0 -355
  145. package/src/daemon/message-types/browser.ts +0 -10
  146. package/src/notifications/__tests__/emit-signal-home-feed.test.ts +0 -187
  147. package/src/plugins/plugin-skill-contributions.ts +0 -292
@@ -10,7 +10,6 @@
10
10
 
11
11
  import { z } from "zod";
12
12
 
13
- import { isAssistantFeatureFlagEnabled } from "../../config/assistant-feature-flags.js";
14
13
  import { getConfigReadOnly } from "../../config/loader.js";
15
14
  import { getDb } from "../../memory/db-connection.js";
16
15
  import {
@@ -44,22 +43,6 @@ import type { RouteDefinition, RouteHandlerArgs } from "./types.js";
44
43
  // ---------------------------------------------------------------------------
45
44
 
46
45
  const providerConnectionResponseSchema = ProviderConnectionSchema;
47
- const OPENAI_COMPATIBLE_ENDPOINTS_FLAG = "openai-compatible-endpoints";
48
-
49
- function openAICompatibleEndpointsEnabled(): boolean {
50
- return isAssistantFeatureFlagEnabled(
51
- OPENAI_COMPATIBLE_ENDPOINTS_FLAG,
52
- getConfigReadOnly(),
53
- );
54
- }
55
-
56
- function rejectDisabledOpenAICompatibleProvider(provider: string): void {
57
- if (provider !== "openai-compatible") return;
58
- if (openAICompatibleEndpointsEnabled()) return;
59
- throw new BadRequestError(
60
- "OpenAI-compatible endpoints are disabled. Enable the openai-compatible-endpoints feature flag to configure this provider.",
61
- );
62
- }
63
46
 
64
47
  // ---------------------------------------------------------------------------
65
48
  // Custom provider field parsing (openai-compatible base_url + models)
@@ -170,18 +153,10 @@ async function parseCustomProviderFields(
170
153
 
171
154
  function handleListConnections({ queryParams = {} }: RouteHandlerArgs) {
172
155
  const provider = queryParams.provider;
173
- if (provider) rejectDisabledOpenAICompatibleProvider(provider);
174
156
  const connections = listConnections(
175
157
  getDb(),
176
158
  provider ? { provider } : undefined,
177
159
  );
178
- if (!openAICompatibleEndpointsEnabled()) {
179
- return {
180
- connections: connections.filter(
181
- (conn) => conn.provider !== "openai-compatible",
182
- ),
183
- };
184
- }
185
160
  return { connections };
186
161
  }
187
162
 
@@ -191,12 +166,6 @@ function handleGetConnection({ pathParams = {} }: RouteHandlerArgs) {
191
166
 
192
167
  const conn = getConnection(getDb(), name);
193
168
  if (!conn) throw new NotFoundError(`Connection "${name}" not found.`);
194
- if (
195
- conn.provider === "openai-compatible" &&
196
- !openAICompatibleEndpointsEnabled()
197
- ) {
198
- throw new NotFoundError(`Connection "${name}" not found.`);
199
- }
200
169
 
201
170
  return conn;
202
171
  }
@@ -216,8 +185,6 @@ async function handleCreateConnection({ body = {} }: RouteHandlerArgs) {
216
185
  `Invalid provider "${String(provider)}". Valid: ${VALID_CONNECTION_PROVIDERS.join(", ")}`,
217
186
  );
218
187
  }
219
- rejectDisabledOpenAICompatibleProvider(providerResult.data);
220
-
221
188
  const authResult = AuthSchema.safeParse(auth);
222
189
  if (!authResult.success) {
223
190
  throw new BadRequestError(`Invalid auth: ${authResult.error.message}`);
@@ -280,12 +247,6 @@ async function handleUpdateConnection({
280
247
 
281
248
  const existing = getConnection(getDb(), name);
282
249
  if (!existing) throw new NotFoundError(`Connection "${name}" not found.`);
283
- if (
284
- existing.provider === "openai-compatible" &&
285
- !openAICompatibleEndpointsEnabled()
286
- ) {
287
- throw new NotFoundError(`Connection "${name}" not found.`);
288
- }
289
250
 
290
251
  const auth = body.auth;
291
252
  const authResult = AuthSchema.safeParse(auth);
@@ -355,12 +316,6 @@ function handleDeleteConnection({ pathParams = {} }: RouteHandlerArgs) {
355
316
  if (!existing) {
356
317
  throw new NotFoundError(`Connection "${name}" not found.`);
357
318
  }
358
- if (
359
- existing.provider === "openai-compatible" &&
360
- !openAICompatibleEndpointsEnabled()
361
- ) {
362
- throw new NotFoundError(`Connection "${name}" not found.`);
363
- }
364
319
 
365
320
  // Managed connections are write-protected: `seedCanonicalConnections` would
366
321
  // re-upsert them on the next daemon boot anyway, so a successful delete here
@@ -128,7 +128,7 @@ const pluginSearchMatchSchema = z.object({
128
128
  path: z
129
129
  .string()
130
130
  .describe(
131
- "Human-readable origin: a repo-relative path (`experimental/plugins/<name>`) for first-party plugins or a `github:owner/repo@ref` locator for external ones.",
131
+ "Human-readable origin: a repo-relative path (`plugins/<name>`) for first-party plugins or a `github:owner/repo@ref` locator for external ones.",
132
132
  ),
133
133
  description: z
134
134
  .string()
@@ -517,7 +517,7 @@ export const ROUTES: RouteDefinition[] = [
517
517
  },
518
518
  summary: "Search the plugin catalog",
519
519
  description:
520
- "List installable plugins from the canonical `vellum-ai/vellum-assistant` catalog at `experimental/plugins/`. The query is an ECMAScript regex matched case-insensitively against the directory name (e.g. `memory`, `^simple`). Empty query returns every entry. Mirrors the CLI's `assistant plugins search`.",
520
+ "List installable plugins from the canonical `vellum-ai/vellum-assistant` catalog at `plugins/`. The query is an ECMAScript regex matched case-insensitively against the directory name (e.g. `memory`, `^simple`). Empty query returns every entry. Mirrors the CLI's `assistant plugins search`.",
521
521
  tags: ["plugins"],
522
522
  queryParams: [
523
523
  {
@@ -546,7 +546,7 @@ export const ROUTES: RouteDefinition[] = [
546
546
  },
547
547
  summary: "Install a plugin",
548
548
  description:
549
- "Install a plugin by name from the canonical source — a whitelisted `experimental/plugins/marketplace.json` entry, else the first-party `experimental/plugins/<name>/` convention. Always resolves against the curated default git ref (no caller-supplied ref): installing from an unreviewed revision would bypass the marketplace/first-party curation boundary and let attacker-controlled code be loaded. Materializes the plugin under `<workspaceDir>/plugins/<name>/`; the assistant must be restarted to load it. Mirrors the CLI's `assistant plugins install <name>`. An already-installed name without `force` returns 409; a name that resolves to nothing returns 404. Sibling to `POST /v1/skills/install`.",
549
+ "Install a plugin by name from the canonical source — a whitelisted `plugins/marketplace.json` entry, else the first-party `plugins/<name>/` convention. Always resolves against the curated default git ref (no caller-supplied ref): installing from an unreviewed revision would bypass the marketplace/first-party curation boundary and let attacker-controlled code be loaded. Materializes the plugin under `<workspaceDir>/plugins/<name>/`; the assistant must be restarted to load it. Mirrors the CLI's `assistant plugins install <name>`. An already-installed name without `force` returns 409; a name that resolves to nothing returns 404. Sibling to `POST /v1/skills/install`.",
550
550
  tags: ["plugins"],
551
551
  requestBody: pluginInstallRequestSchema,
552
552
  responseBody: pluginInstallResponseSchema,
@@ -2,7 +2,7 @@
2
2
  * Shared outbound verification action logic.
3
3
  *
4
4
  * These pure functions encapsulate the business logic for starting, resending,
5
- * and cancelling outbound verification flows (Telegram, voice, Slack).
5
+ * and cancelling outbound verification flows (Telegram, voice, Slack, email).
6
6
  * They return transport-agnostic result objects and are consumed by both the
7
7
  * message handler (config-channels.ts) and the HTTP route layer (channel-verification-routes.ts).
8
8
  */
@@ -26,6 +26,7 @@ import {
26
26
  updateSessionStatus,
27
27
  } from "./channel-verification-service.js";
28
28
  import {
29
+ composeVerificationEmail,
29
30
  composeVerificationSlack,
30
31
  composeVerificationTelegram,
31
32
  GUARDIAN_VERIFY_TEMPLATE_KEYS,
@@ -52,6 +53,8 @@ export const DESTINATION_RATE_WINDOW_MS = 3_600_000;
52
53
  /** Session TTL in seconds (matches challenge TTL of 10 minutes). */
53
54
  const SESSION_TTL_SECONDS = 600;
54
55
 
56
+ const EMAIL_VERIFICATION_SUBJECT = "Vellum Assistant Guardian Verification";
57
+
55
58
  // ---------------------------------------------------------------------------
56
59
  // Telegram destination classification
57
60
  // ---------------------------------------------------------------------------
@@ -122,6 +125,8 @@ interface OutboundActionResult {
122
125
  * reach the gateway. The daemon HTTP route handler calls
123
126
  * deliverVerificationSlack() after receiving this payload. */
124
127
  _pendingSlackDm?: { userId: string; text: string; assistantId: string };
128
+ /** Internal: email delivery payload for the caller to dispatch (same pattern as Slack). */
129
+ _pendingEmail?: { to: string; text: string; subject: string; assistantId: string };
125
130
  }
126
131
 
127
132
  // ---------------------------------------------------------------------------
@@ -512,6 +517,80 @@ export function deliverVerificationSlack(
512
517
  deliverVerificationSlackAsync(userId, text, assistantId);
513
518
  }
514
519
 
520
+ // ---------------------------------------------------------------------------
521
+ // Email delivery helper
522
+ // ---------------------------------------------------------------------------
523
+
524
+ /**
525
+ * Deliver a verification email via the platform email send API.
526
+ * Fire-and-forget wrapper for use in the daemon process (HTTP route handlers).
527
+ */
528
+ export function deliverVerificationEmail(
529
+ to: string,
530
+ text: string,
531
+ subject: string,
532
+ _assistantId: string,
533
+ ): void {
534
+ (async () => {
535
+ try {
536
+ const { VellumPlatformClient } = await import(
537
+ "../platform/client.js"
538
+ );
539
+ const client = await VellumPlatformClient.create();
540
+ if (!client?.platformAssistantId) {
541
+ log.error("Cannot deliver verification email: platform client not configured");
542
+ return;
543
+ }
544
+
545
+ const listResponse = await client.fetch(
546
+ `/v1/assistants/${client.platformAssistantId}/email-addresses/`,
547
+ );
548
+ if (!listResponse.ok) {
549
+ log.error({ status: listResponse.status }, "Failed to list email addresses for verification");
550
+ return;
551
+ }
552
+ const listData = (await listResponse.json()) as {
553
+ results: { address: string }[];
554
+ };
555
+ const addresses = listData.results ?? [];
556
+ if (addresses.length === 0) {
557
+ log.error("No email address registered — cannot deliver verification email");
558
+ return;
559
+ }
560
+ const fromAddress = addresses[0].address;
561
+
562
+ const { markdownToEmailHtml } = await import(
563
+ "../email/html-renderer.js"
564
+ );
565
+ const html = markdownToEmailHtml(text);
566
+
567
+ const response = await client.fetch("/v1/runtime-proxy/email/send/", {
568
+ method: "POST",
569
+ headers: { "Content-Type": "application/json" },
570
+ body: JSON.stringify({
571
+ to: [to],
572
+ from_address: fromAddress,
573
+ text,
574
+ subject,
575
+ html,
576
+ }),
577
+ });
578
+
579
+ if (response.ok) {
580
+ log.info({ to }, "Verification email delivered");
581
+ } else {
582
+ const respBody = await response.json().catch(() => ({}));
583
+ log.error(
584
+ { to, status: response.status, respBody },
585
+ "Failed to deliver verification email",
586
+ );
587
+ }
588
+ } catch (err) {
589
+ log.error({ err, to }, "Failed to deliver verification email");
590
+ }
591
+ })();
592
+ }
593
+
515
594
  function startOutboundSlack(
516
595
  destination: string | undefined,
517
596
  assistantId: string,
@@ -644,13 +723,35 @@ function startOutboundEmail(
644
723
  verificationPurpose: "guardian",
645
724
  });
646
725
 
726
+ const emailBody = composeVerificationEmail(
727
+ GUARDIAN_VERIFY_TEMPLATE_KEYS.EMAIL_CHALLENGE_REQUEST,
728
+ {
729
+ code: sessionResult.secret,
730
+ expiresInMinutes: Math.floor(SESSION_TTL_SECONDS / 60),
731
+ },
732
+ );
733
+
734
+ const now = Date.now();
735
+ const nextResendAt = now + RESEND_COOLDOWN_MS;
736
+ const sendCount = 1;
737
+
738
+ updateSessionDelivery(sessionResult.sessionId, now, sendCount, nextResendAt);
739
+
647
740
  return {
648
741
  success: true,
649
742
  verificationSessionId: sessionResult.sessionId,
650
743
  secret: sessionResult.secret,
651
744
  expiresAt: sessionResult.expiresAt,
745
+ nextResendAt,
746
+ sendCount,
652
747
  channel,
653
748
  originConversationId,
749
+ _pendingEmail: {
750
+ to: normalizedEmail,
751
+ text: emailBody,
752
+ subject: EMAIL_VERIFICATION_SUBJECT,
753
+ assistantId,
754
+ },
654
755
  };
655
756
  }
656
757
 
@@ -851,12 +952,56 @@ export function resendOutbound(
851
952
  originConversationId,
852
953
  _pendingSlackDm: { userId: destination, text: slackBody, assistantId },
853
954
  };
955
+ } else if (channel === "email") {
956
+ const newSession = createOutboundSession({
957
+ channel,
958
+ expectedExternalUserId: destination,
959
+ expectedChatId: destination,
960
+ identityBindingStatus: "bound",
961
+ destinationAddress: destination,
962
+ verificationPurpose: "guardian",
963
+ });
964
+
965
+ const emailBody = composeVerificationEmail(
966
+ GUARDIAN_VERIFY_TEMPLATE_KEYS.EMAIL_RESEND,
967
+ {
968
+ code: newSession.secret,
969
+ expiresInMinutes: Math.floor(SESSION_TTL_SECONDS / 60),
970
+ },
971
+ );
972
+
973
+ const now = Date.now();
974
+ const newSendCount = currentSendCount + 1;
975
+ const nextResendAt = now + RESEND_COOLDOWN_MS;
976
+
977
+ updateSessionDelivery(
978
+ newSession.sessionId,
979
+ now,
980
+ newSendCount,
981
+ nextResendAt,
982
+ );
983
+
984
+ return {
985
+ success: true,
986
+ verificationSessionId: newSession.sessionId,
987
+ secret: newSession.secret,
988
+ nextResendAt,
989
+ sendCount: newSendCount,
990
+ channel,
991
+ originConversationId,
992
+ _pendingEmail: {
993
+ to: destination,
994
+ text: emailBody,
995
+ subject: EMAIL_VERIFICATION_SUBJECT,
996
+ assistantId,
997
+ },
998
+ };
854
999
  }
855
1000
 
856
1001
  return {
857
1002
  success: false,
858
1003
  error: "unsupported_channel",
859
- message: `Resend is only supported for Telegram, phone, and Slack. Got: ${channel}`,
1004
+ message: `Resend is only supported for Telegram, phone, Slack, and email. Got: ${channel}`,
860
1005
  channel,
861
1006
  };
862
1007
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Template-only copy for outbound guardian verification messages (Telegram, Slack, and voice).
2
+ * Template-only copy for outbound guardian verification messages (Telegram, Slack, email, and voice).
3
3
  *
4
4
  * All outbound verification messages are composed from these templates
5
5
  * to prevent free-form caller/user text injection. Only typed variables
@@ -26,6 +26,10 @@ export const GUARDIAN_VERIFY_TEMPLATE_KEYS = {
26
26
  "guardian_verify.slack.trusted_contact_challenge",
27
27
  /** Resend Slack DM verification for inbound trusted contact (includes the code). */
28
28
  SLACK_TRUSTED_CONTACT_RESEND: "guardian_verify.slack.trusted_contact_resend",
29
+ /** Initial outbound email verification prompt (includes the code). */
30
+ EMAIL_CHALLENGE_REQUEST: "guardian_verify.email.challenge_request",
31
+ /** Resend email verification prompt (includes the code). */
32
+ EMAIL_RESEND: "guardian_verify.email.resend",
29
33
  /** Outbound voice call intro prompt: asks guardian to enter verification code via keypad. */
30
34
  VOICE_CALL_INTRO: "guardian_verify.voice.call_intro",
31
35
  /** Voice retry prompt after an incorrect code entry. */
@@ -42,7 +46,7 @@ export const GUARDIAN_VERIFY_TEMPLATE_KEYS = {
42
46
  CHANNEL_BOOTSTRAP_BOUND: "guardian_verify.channel.bootstrap_bound",
43
47
  } as const;
44
48
 
45
- /** Template keys for Telegram/Slack text-based verification messages. */
49
+ /** Template keys for Telegram/Slack/email text-based verification messages. */
46
50
  type TextVerifyTemplateKey =
47
51
  | typeof GUARDIAN_VERIFY_TEMPLATE_KEYS.ALREADY_VERIFIED
48
52
  | typeof GUARDIAN_VERIFY_TEMPLATE_KEYS.TELEGRAM_CHALLENGE_REQUEST
@@ -50,7 +54,9 @@ type TextVerifyTemplateKey =
50
54
  | typeof GUARDIAN_VERIFY_TEMPLATE_KEYS.SLACK_CHALLENGE_REQUEST
51
55
  | typeof GUARDIAN_VERIFY_TEMPLATE_KEYS.SLACK_RESEND
52
56
  | typeof GUARDIAN_VERIFY_TEMPLATE_KEYS.SLACK_TRUSTED_CONTACT_CHALLENGE
53
- | typeof GUARDIAN_VERIFY_TEMPLATE_KEYS.SLACK_TRUSTED_CONTACT_RESEND;
57
+ | typeof GUARDIAN_VERIFY_TEMPLATE_KEYS.SLACK_TRUSTED_CONTACT_RESEND
58
+ | typeof GUARDIAN_VERIFY_TEMPLATE_KEYS.EMAIL_CHALLENGE_REQUEST
59
+ | typeof GUARDIAN_VERIFY_TEMPLATE_KEYS.EMAIL_RESEND;
54
60
 
55
61
  /** Template keys for deterministic channel verification reply messages. */
56
62
  type ChannelVerifyReplyTemplateKey =
@@ -115,6 +121,14 @@ const templates: Record<
115
121
  [GUARDIAN_VERIFY_TEMPLATE_KEYS.SLACK_TRUSTED_CONTACT_RESEND]: (vars) => {
116
122
  return `Vellum assistant verification: your code is ${vars.code}. Reply with this code to verify your identity. It expires in ${vars.expiresInMinutes} minutes. (resent)`;
117
123
  },
124
+
125
+ [GUARDIAN_VERIFY_TEMPLATE_KEYS.EMAIL_CHALLENGE_REQUEST]: (vars) => {
126
+ return `Vellum assistant guardian verification requested.\n\nYour verification code is: ${vars.code}\n\nReply to this email with only the 6-digit code above to complete verification. This code expires in ${vars.expiresInMinutes} minutes.`;
127
+ },
128
+
129
+ [GUARDIAN_VERIFY_TEMPLATE_KEYS.EMAIL_RESEND]: (vars) => {
130
+ return `Vellum assistant guardian verification requested.\n\nYour new verification code is: ${vars.code}\n\nReply to this email with only the 6-digit code above to complete verification. This code expires in ${vars.expiresInMinutes} minutes. (resent)`;
131
+ },
118
132
  };
119
133
 
120
134
  /**
@@ -129,6 +143,18 @@ export function composeVerificationSlack(
129
143
  return composer(vars);
130
144
  }
131
145
 
146
+ /**
147
+ * Compose an outbound verification email from a template key and typed variables.
148
+ * Returns plain string content suitable for email delivery.
149
+ */
150
+ export function composeVerificationEmail(
151
+ templateKey: TextVerifyTemplateKey,
152
+ vars: GuardianVerifyTemplateVars,
153
+ ): string {
154
+ const composer = templates[templateKey];
155
+ return composer(vars);
156
+ }
157
+
132
158
  /**
133
159
  * Compose an outbound verification Telegram message from a template key and typed variables.
134
160
  * Returns plain string content suitable for Telegram delivery.
@@ -225,10 +225,34 @@ export interface AuthFallbackTelemetryEvent extends TelemetryEventBase {
225
225
  window_end: number;
226
226
  }
227
227
 
228
+ /**
229
+ * Tool execution event — one per tool invocation, sourced from the
230
+ * `tool_invocations` audit table. Skill-routed calls appear under their
231
+ * underlying tool name; `skill_id` identifies the triggering skill.
232
+ * Carries NO raw input/output — only tool identity, permission
233
+ * outcome, risk class, duration, and parent conversation.
234
+ */
235
+ export interface ToolExecutionTelemetryEvent extends TelemetryEventBase {
236
+ type: "tool_execution";
237
+ tool_name: string;
238
+ /**
239
+ * Triggering skill id for skill-routed calls. Null for direct tool
240
+ * calls and for rows recorded before the `skill_id` column existed.
241
+ */
242
+ skill_id: string | null;
243
+ /** Permission outcome: "allow" | "error" | "denied". */
244
+ decision: string;
245
+ /** Executor risk classification. */
246
+ risk_level: string;
247
+ duration_ms: number;
248
+ conversation_id: string;
249
+ }
250
+
228
251
  /** Discriminated union of all telemetry event types. */
229
252
  export type TelemetryEvent =
230
253
  | LlmUsageTelemetryEvent
231
254
  | TurnTelemetryEvent
232
255
  | LifecycleTelemetryEvent
233
256
  | OnboardingTelemetryEvent
234
- | AuthFallbackTelemetryEvent;
257
+ | AuthFallbackTelemetryEvent
258
+ | ToolExecutionTelemetryEvent;
@@ -143,19 +143,29 @@ mock.module("../memory/onboarding-events-store.js", () => ({
143
143
  queryUnreportedOnboardingEvents: mockQueryUnreportedOnboardingEvents,
144
144
  }));
145
145
 
146
- // The auth-fallback store is intentionally NOT mocked — it has its own
147
- // DB-backed tests, and Bun's `mock.module` is process-global, so mocking it
148
- // here would leak into those tests when files share an invocation. We seed the
149
- // real DB instead so every auth-fallback test stays order-independent.
146
+ // The auth-fallback and tool-execution stores are intentionally NOT mocked —
147
+ // they have their own DB-backed tests, and Bun's `mock.module` is
148
+ // process-global, so mocking them here would leak into those tests when files
149
+ // share an invocation. We seed the real DB instead so every auth-fallback /
150
+ // tool-execution test stays order-independent.
150
151
 
151
152
  // ---------------------------------------------------------------------------
152
153
  // Production import (after mocks)
153
154
  // ---------------------------------------------------------------------------
154
155
 
156
+ import {
157
+ seedToolInvocation,
158
+ type SeedToolInvocationSpec,
159
+ TOOL_INVOCATION_PII_SENTINEL,
160
+ } from "../memory/__tests__/tool-invocation-test-helpers.js";
155
161
  import { recordAuthFallbackCounts } from "../memory/auth-fallback-events-store.js";
156
162
  import { getDb } from "../memory/db-connection.js";
157
163
  import { initializeDb } from "../memory/db-init.js";
158
- import { authFallbackEvents } from "../memory/schema.js";
164
+ import {
165
+ authFallbackEvents,
166
+ conversations,
167
+ toolInvocations,
168
+ } from "../memory/schema.js";
159
169
  import type { UsageEvent } from "../usage/types.js";
160
170
  import {
161
171
  ACTIVATION_FUNNEL_VERSION,
@@ -238,6 +248,17 @@ function makeOnboardingEvent(
238
248
  };
239
249
  }
240
250
 
251
+ const TOOL_EXEC_CONVERSATION_ID = "conv-tool-exec-reporter-test";
252
+
253
+ function insertInvocation(
254
+ spec: Omit<SeedToolInvocationSpec, "conversationId">,
255
+ ): void {
256
+ seedToolInvocation(
257
+ { db: getDb(), conversations, toolInvocations },
258
+ { ...spec, conversationId: TOOL_EXEC_CONVERSATION_ID },
259
+ );
260
+ }
261
+
241
262
  const originalFetch = globalThis.fetch;
242
263
  let mockFetch: ReturnType<typeof mock>;
243
264
 
@@ -258,6 +279,7 @@ beforeEach(() => {
258
279
  mockQueryUnreportedOnboardingEvents.mockReset();
259
280
  mockQueryUnreportedOnboardingEvents.mockReturnValue([]);
260
281
  getDb().delete(authFallbackEvents).run();
282
+ getDb().delete(toolInvocations).run();
261
283
  mockPlatformClient = null;
262
284
  mockGetPlatformBaseUrl.mockReset();
263
285
  mockGetDeviceId.mockReset();
@@ -956,6 +978,7 @@ describe("UsageTelemetryReporter", () => {
956
978
  mockCollectUsageData = false;
957
979
  const events = [makeUsageEvent()];
958
980
  mockQueryUnreportedUsageEvents.mockReturnValue(events);
981
+ insertInvocation({ id: "ti-opt-out", createdAt: 1700000000000 });
959
982
  mockFetch.mockImplementation(() =>
960
983
  Promise.resolve(new Response('{"accepted":1}', { status: 200 })),
961
984
  );
@@ -966,9 +989,9 @@ describe("UsageTelemetryReporter", () => {
966
989
  // No HTTP call should have been made
967
990
  expect(mockFetch).not.toHaveBeenCalled();
968
991
 
969
- // All 5 timestamp watermarks should have been advanced (IDs left untouched
992
+ // All 6 timestamp watermarks should have been advanced (IDs left untouched
970
993
  // so the compound-cursor branch stays active)
971
- expect(mockSetMemoryCheckpoint).toHaveBeenCalledTimes(5);
994
+ expect(mockSetMemoryCheckpoint).toHaveBeenCalledTimes(6);
972
995
 
973
996
  const calls = mockSetMemoryCheckpoint.mock.calls;
974
997
  const keys = calls.map((c) => c[0]);
@@ -977,6 +1000,7 @@ describe("UsageTelemetryReporter", () => {
977
1000
  expect(keys).toContain("telemetry:lifecycle:last_reported_at");
978
1001
  expect(keys).toContain("telemetry:onboarding:last_reported_at");
979
1002
  expect(keys).toContain("telemetry:auth_fallback:last_reported_at");
1003
+ expect(keys).toContain("telemetry:tool_execution:last_reported_at");
980
1004
  });
981
1005
 
982
1006
  test("events sent normally after re-enabling collectUsageData", async () => {
@@ -1222,6 +1246,116 @@ describe("UsageTelemetryReporter", () => {
1222
1246
  expect(idCalls[idCalls.length - 1][1]).toBe(lastRow.id);
1223
1247
  });
1224
1248
 
1249
+ // -------------------------------------------------------------------------
1250
+ // Tool-execution events
1251
+ // -------------------------------------------------------------------------
1252
+
1253
+ test("tool_invocations rows flush as tool_execution events with mapped fields and no raw input/result", async () => {
1254
+ mockQueryUnreportedUsageEvents.mockReturnValue([]);
1255
+ insertInvocation({
1256
+ id: "ti-flush-direct",
1257
+ createdAt: 1700000900000,
1258
+ toolName: "calendar_list_events",
1259
+ decision: "denied",
1260
+ riskLevel: "high",
1261
+ durationMs: 137,
1262
+ });
1263
+ insertInvocation({
1264
+ id: "ti-flush-skill",
1265
+ createdAt: 1700000950000,
1266
+ toolName: "task_create",
1267
+ skillId: "tasks-skill",
1268
+ });
1269
+ mockFetch.mockImplementation(() =>
1270
+ Promise.resolve(new Response('{"accepted":2}', { status: 200 })),
1271
+ );
1272
+
1273
+ const reporter = new UsageTelemetryReporter();
1274
+ await reporter.flush();
1275
+
1276
+ expect(mockFetch).toHaveBeenCalledTimes(1);
1277
+ const body = JSON.parse(
1278
+ (mockFetch.mock.calls[0] as [string, RequestInit])[1].body as string,
1279
+ );
1280
+ expect(body.events.length).toBe(2);
1281
+
1282
+ const direct = body.events.find(
1283
+ (e: { daemon_event_id: string }) =>
1284
+ e.daemon_event_id === "ti-flush-direct",
1285
+ );
1286
+ expect(direct).toMatchObject({
1287
+ type: "tool_execution",
1288
+ daemon_event_id: "ti-flush-direct",
1289
+ recorded_at: 1700000900000,
1290
+ tool_name: "calendar_list_events",
1291
+ // Direct (non-skill) tool call — skill_id stays null on the wire.
1292
+ skill_id: null,
1293
+ decision: "denied",
1294
+ risk_level: "high",
1295
+ duration_ms: 137,
1296
+ conversation_id: TOOL_EXEC_CONVERSATION_ID,
1297
+ assistant_version: "1.2.3-test",
1298
+ });
1299
+
1300
+ const skillRouted = body.events.find(
1301
+ (e: { daemon_event_id: string }) =>
1302
+ e.daemon_event_id === "ti-flush-skill",
1303
+ );
1304
+ expect(skillRouted).toMatchObject({
1305
+ type: "tool_execution",
1306
+ tool_name: "task_create",
1307
+ skill_id: "tasks-skill",
1308
+ });
1309
+
1310
+ // The raw tool args/outputs persisted in the audit rows are potentially
1311
+ // PII and must NEVER appear anywhere in the payload.
1312
+ expect(JSON.stringify(body)).not.toContain(TOOL_INVOCATION_PII_SENTINEL);
1313
+ expect(direct.input).toBeUndefined();
1314
+ expect(direct.result).toBeUndefined();
1315
+ });
1316
+
1317
+ test("tool_execution watermark advances to the last reported row on success", async () => {
1318
+ mockQueryUnreportedUsageEvents.mockReturnValue([]);
1319
+ insertInvocation({ id: "ti-wm-1", createdAt: 1700001000000 });
1320
+ insertInvocation({ id: "ti-wm-2", createdAt: 1700001001000 });
1321
+ mockFetch.mockImplementation(() =>
1322
+ Promise.resolve(new Response('{"accepted":2}', { status: 200 })),
1323
+ );
1324
+
1325
+ const reporter = new UsageTelemetryReporter();
1326
+ await reporter.flush();
1327
+
1328
+ const watermarkCalls = mockSetMemoryCheckpoint.mock.calls.filter(
1329
+ (c) => c[0] === "telemetry:tool_execution:last_reported_at",
1330
+ );
1331
+ expect(watermarkCalls.length).toBeGreaterThanOrEqual(1);
1332
+ expect(watermarkCalls[watermarkCalls.length - 1][1]).toBe(
1333
+ String(1700001001000),
1334
+ );
1335
+
1336
+ const idCalls = mockSetMemoryCheckpoint.mock.calls.filter(
1337
+ (c) => c[0] === "telemetry:tool_execution:last_reported_id",
1338
+ );
1339
+ expect(idCalls.length).toBeGreaterThanOrEqual(1);
1340
+ expect(idCalls[idCalls.length - 1][1]).toBe("ti-wm-2");
1341
+ });
1342
+
1343
+ test("tool_execution watermark stays on failed upload", async () => {
1344
+ mockQueryUnreportedUsageEvents.mockReturnValue([]);
1345
+ insertInvocation({ id: "ti-fail-1", createdAt: 1700001100000 });
1346
+ mockFetch.mockImplementation(() =>
1347
+ Promise.resolve(new Response("error", { status: 500 })),
1348
+ );
1349
+
1350
+ const reporter = new UsageTelemetryReporter();
1351
+ await reporter.flush();
1352
+
1353
+ const watermarkCalls = mockSetMemoryCheckpoint.mock.calls.filter((c) =>
1354
+ c[0].startsWith("telemetry:tool_execution:"),
1355
+ );
1356
+ expect(watermarkCalls.length).toBe(0);
1357
+ });
1358
+
1225
1359
  // -------------------------------------------------------------------------
1226
1360
  // Onboarding / activation funnel events
1227
1361
  // -------------------------------------------------------------------------