@vellumai/assistant 0.12.4 → 0.12.5-dev.202609251017.e467a6c

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 (281) hide show
  1. package/docs/architecture/memory.md +9 -1
  2. package/docs/architecture/scheduling.md +13 -5
  3. package/docs/desktop-browser-cli.md +3 -2
  4. package/docs/guardian-request-flow.md +1 -1
  5. package/node_modules/@vellumai/avatar-manifest/src/__tests__/notification-avatar.test.ts +48 -4
  6. package/node_modules/@vellumai/avatar-manifest/src/notification-avatar.ts +12 -8
  7. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/__tests__/guardian-requests.test.ts +26 -0
  8. package/node_modules/@vellumai/ces-client/node_modules/@vellumai/service-contracts/src/guardian-requests.ts +77 -3
  9. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/__tests__/guardian-requests.test.ts +26 -0
  10. package/node_modules/@vellumai/gateway-client/node_modules/@vellumai/service-contracts/src/guardian-requests.ts +77 -3
  11. package/node_modules/@vellumai/gateway-client/src/outbound-contract.ts +2 -4
  12. package/node_modules/@vellumai/service-contracts/src/__tests__/guardian-requests.test.ts +26 -0
  13. package/node_modules/@vellumai/service-contracts/src/guardian-requests.ts +77 -3
  14. package/openapi.yaml +152 -3
  15. package/package.json +1 -1
  16. package/src/__tests__/agent-loop.test.ts +76 -0
  17. package/src/__tests__/anthropic-error-formatting.test.ts +9 -0
  18. package/src/__tests__/background-shell-bash.test.ts +34 -0
  19. package/src/__tests__/background-shell-host-bash.test.ts +98 -1
  20. package/src/__tests__/background-tool-registry.test.ts +39 -0
  21. package/src/__tests__/channel-readiness-discord.test.ts +8 -0
  22. package/src/__tests__/channel-readiness-slack-remote.test.ts +8 -0
  23. package/src/__tests__/client-os-metadata-persistence.test.ts +4 -20
  24. package/src/__tests__/conversation-agent-loop.test.ts +529 -1
  25. package/src/__tests__/conversation-error.test.ts +18 -0
  26. package/src/__tests__/conversation-pairing.test.ts +69 -0
  27. package/src/__tests__/conversation-queue.test.ts +257 -4
  28. package/src/__tests__/conversation-runtime-assembly.test.ts +27 -0
  29. package/src/__tests__/emit-signal-routing-intent.test.ts +62 -0
  30. package/src/__tests__/evict-conversations-for-reload.test.ts +21 -0
  31. package/src/__tests__/gemini-provider.test.ts +9 -0
  32. package/src/__tests__/host-cu-proxy.test.ts +79 -0
  33. package/src/__tests__/host-cu-routes-targeted.test.ts +14 -5
  34. package/src/__tests__/introduction-card-resolver.test.ts +53 -8
  35. package/src/__tests__/job-handler-registration-guard.test.ts +1 -0
  36. package/src/__tests__/non-member-access-request.test.ts +48 -0
  37. package/src/__tests__/notification-events-source-context-probe.test.ts +48 -1
  38. package/src/__tests__/notification-platform-adapter.test.ts +97 -0
  39. package/src/__tests__/notification-vellum-adapter.test.ts +103 -3
  40. package/src/__tests__/platform-callback-registration.test.ts +46 -1
  41. package/src/__tests__/plugin-import-boundary-guard.test.ts +3 -0
  42. package/src/__tests__/scaffold-managed-skill-tool.test.ts +116 -66
  43. package/src/__tests__/scheduler-disk-pressure.test.ts +1 -0
  44. package/src/__tests__/scheduler-result-notification.test.ts +521 -7
  45. package/src/__tests__/scheduler-wake.test.ts +1 -0
  46. package/src/__tests__/skill-load-inline-command.test.ts +35 -0
  47. package/src/__tests__/subagent-cron-run-attribution.test.ts +41 -2
  48. package/src/__tests__/subagent-manager-notify.test.ts +48 -0
  49. package/src/__tests__/trusted-contact-inline-approval-integration.test.ts +6 -6
  50. package/src/__tests__/usage-attribution.test.ts +31 -0
  51. package/src/__tests__/wake-schedule-escalation.test.ts +1 -0
  52. package/src/agent/loop.ts +23 -0
  53. package/src/api/ask-question-tool.ts +50 -0
  54. package/src/api/events/generation-handoff.ts +4 -0
  55. package/src/api/events/message-complete.ts +4 -0
  56. package/src/api/events/tool-result.ts +11 -0
  57. package/src/api/index.ts +11 -0
  58. package/src/api/requests/guardian-actions.test.ts +45 -0
  59. package/src/api/requests/guardian-actions.ts +20 -0
  60. package/src/api/responses/conversation-message.ts +4 -0
  61. package/src/api/responses/home.ts +27 -0
  62. package/src/approvals/guardian-decision-primitive.ts +6 -4
  63. package/src/approvals/guardian-request-resolvers.ts +35 -30
  64. package/src/avatar/notification-avatar.test.ts +42 -34
  65. package/src/avatar/notification-avatar.ts +1 -0
  66. package/src/calls/__tests__/call-controller.test.ts +18 -0
  67. package/src/calls/__tests__/voice-control-protocol.test.ts +6 -1
  68. package/src/calls/__tests__/voice-leg-coordinator.test.ts +70 -0
  69. package/src/calls/__tests__/voice-session-bridge.test.ts +116 -4
  70. package/src/calls/__tests__/voice-triage-escalate.test.ts +77 -11
  71. package/src/calls/call-controller.ts +3 -1
  72. package/src/calls/voice-control-protocol.ts +12 -4
  73. package/src/calls/voice-escalation-judge.ts +2 -2
  74. package/src/calls/voice-leg-coordinator.ts +23 -5
  75. package/src/calls/voice-screen-annotation.ts +44 -0
  76. package/src/calls/voice-session-bridge.ts +63 -20
  77. package/src/calls/voice-triage-escalate.ts +82 -27
  78. package/src/cli/commands/__tests__/conversations-clear.test.ts +156 -0
  79. package/src/cli/commands/conversations.help.ts +7 -2
  80. package/src/cli/commands/conversations.ts +36 -30
  81. package/src/cli/commands/oauth/index.help.ts +8 -2
  82. package/src/cli/commands/oauth/request.test.ts +32 -0
  83. package/src/cli/commands/platform/index.help.ts +2 -1
  84. package/src/cli/commands/platform/index.ts +8 -2
  85. package/src/cli/lib/__tests__/plugin-catalog-cache.test.ts +60 -0
  86. package/src/cli/lib/__tests__/plugin-catalog-platform.test.ts +66 -2
  87. package/src/cli/lib/bundled-marketplace.json +35 -0
  88. package/src/cli/lib/bundled-plugin-packages.json +21 -0
  89. package/src/cli/lib/plugin-catalog-cache.ts +17 -2
  90. package/src/cli/lib/plugin-catalog-platform.ts +48 -9
  91. package/src/config/__tests__/default-profile-catalog.test.ts +28 -0
  92. package/src/config/__tests__/platform-identity.test.ts +59 -0
  93. package/src/config/__tests__/profile-order.test.ts +19 -0
  94. package/src/config/__tests__/sync-gated-profiles.test.ts +71 -0
  95. package/src/config/bundled-skills/computer-use/SKILL.md +20 -0
  96. package/src/config/bundled-skills/computer-use/TOOLS.json +11 -11
  97. package/src/config/bundled-skills/screen-annotation/SKILL.md +41 -29
  98. package/src/config/bundled-skills/screen-annotation/TOOLS.json +5 -5
  99. package/src/config/call-site-defaults.ts +6 -0
  100. package/src/config/default-profile-catalog.ts +30 -1
  101. package/src/config/default-profile-names.ts +36 -2
  102. package/src/config/feature-flag-registry.json +9 -1
  103. package/src/config/platform-identity.ts +22 -5
  104. package/src/config/profile-order.ts +7 -1
  105. package/src/config/schemas/call-site-catalog.ts +7 -0
  106. package/src/config/schemas/llm.ts +21 -5
  107. package/src/config/sync-gated-profiles.ts +96 -44
  108. package/src/daemon/__tests__/abort-null-controller.test.ts +135 -1
  109. package/src/daemon/__tests__/auto-profile-router.test.ts +380 -0
  110. package/src/daemon/__tests__/turn-tail-assistant-reply-notify.test.ts +16 -0
  111. package/src/daemon/activity-trail.test.ts +206 -0
  112. package/src/daemon/activity-trail.ts +190 -0
  113. package/src/daemon/auto-profile-router.ts +431 -0
  114. package/src/daemon/computer-use-observation.test.ts +81 -0
  115. package/src/daemon/computer-use-observation.ts +23 -0
  116. package/src/daemon/conversation-agent-loop-handlers.ts +11 -0
  117. package/src/daemon/conversation-agent-loop.ts +157 -32
  118. package/src/daemon/conversation-error.ts +19 -0
  119. package/src/daemon/conversation-lifecycle.ts +70 -7
  120. package/src/daemon/conversation-media-retry.ts +1 -2
  121. package/src/daemon/conversation-messaging.ts +31 -2
  122. package/src/daemon/conversation-process.ts +107 -16
  123. package/src/daemon/conversation-queue-manager.ts +7 -0
  124. package/src/daemon/conversation-runtime-assembly.ts +1 -0
  125. package/src/daemon/conversation-turn-finalize.ts +14 -0
  126. package/src/daemon/conversation.ts +25 -6
  127. package/src/daemon/event-loop-watchdog.test.ts +201 -2
  128. package/src/daemon/event-loop-watchdog.ts +182 -6
  129. package/src/daemon/host-cu-proxy.ts +34 -3
  130. package/src/daemon/pkb-reminder-builder.test.ts +10 -3
  131. package/src/daemon/pkb-reminder-builder.ts +1 -1
  132. package/src/daemon/wake-conversation-ops.ts +4 -2
  133. package/src/desktop/desktop-computer-use.test.ts +14 -4
  134. package/src/home/feed-types.ts +2 -0
  135. package/src/inbound/platform-callback-registration.ts +19 -6
  136. package/src/live-voice/__tests__/live-voice-agent-turn.test.ts +27 -0
  137. package/src/live-voice/__tests__/live-voice-flux-turn-end.test.ts +83 -0
  138. package/src/live-voice/__tests__/live-voice-triage-escalate.test.ts +48 -1
  139. package/src/live-voice/__tests__/live-voice-vad.test.ts +34 -2
  140. package/src/live-voice/__tests__/protocol.test.ts +22 -0
  141. package/src/live-voice/continuation-judge.ts +1 -1
  142. package/src/live-voice/live-voice-session.ts +25 -19
  143. package/src/live-voice/protocol.ts +16 -5
  144. package/src/messaging/providers/discord/withdraw.ts +4 -5
  145. package/src/messaging/providers/gmail/client.ts +4 -0
  146. package/src/messaging/providers/slack/withdraw.ts +5 -5
  147. package/src/messaging/providers/telegram-bot/withdraw.ts +4 -5
  148. package/src/monitoring/__tests__/proc-fixtures.ts +28 -0
  149. package/src/monitoring/__tests__/proc-wait-state.test.ts +232 -0
  150. package/src/monitoring/__tests__/process-usage.test.ts +243 -0
  151. package/src/monitoring/proc-wait-state.ts +366 -0
  152. package/src/monitoring/process-memory.ts +4 -3
  153. package/src/monitoring/process-usage.ts +215 -0
  154. package/src/monitoring/resource-sample-types.ts +8 -0
  155. package/src/monitoring/resource-sampler.ts +17 -2
  156. package/src/monitoring/stall-capture.ts +12 -0
  157. package/src/notifications/README.md +88 -9
  158. package/src/notifications/__tests__/assistant-reply-producer.test.ts +390 -119
  159. package/src/notifications/__tests__/background-result-producer.test.ts +1272 -0
  160. package/src/notifications/__tests__/broadcaster.test.ts +292 -1
  161. package/src/notifications/__tests__/completion-policy.test.ts +243 -0
  162. package/src/notifications/__tests__/decision-engine.test.ts +51 -4
  163. package/src/notifications/__tests__/has-pending-background-work.test.ts +281 -0
  164. package/src/notifications/__tests__/home-feed-side-effect.test.ts +161 -3
  165. package/src/notifications/__tests__/resolve-visible-in-source.test.ts +110 -1
  166. package/src/notifications/__tests__/schedule-result-producer.test.ts +11 -4
  167. package/src/notifications/adapters/macos.ts +24 -12
  168. package/src/notifications/adapters/platform.ts +16 -5
  169. package/src/notifications/assistant-reply-producer.ts +96 -71
  170. package/src/notifications/background-result-producer.ts +369 -0
  171. package/src/notifications/broadcaster.ts +28 -8
  172. package/src/notifications/completion-policy.ts +115 -0
  173. package/src/notifications/completion-work.ts +46 -0
  174. package/src/notifications/conversation-pairing.ts +32 -13
  175. package/src/notifications/decision-engine.ts +18 -24
  176. package/src/notifications/emit-signal.ts +16 -1
  177. package/src/notifications/events-store.ts +4 -0
  178. package/src/notifications/has-pending-background-work.ts +91 -0
  179. package/src/notifications/home-feed-mirror.ts +44 -0
  180. package/src/notifications/home-feed-side-effect.ts +54 -28
  181. package/src/notifications/resolve-visible-in-source.ts +56 -2
  182. package/src/notifications/result-output.ts +154 -0
  183. package/src/notifications/schedule-result-producer.ts +6 -187
  184. package/src/notifications/types.ts +2 -0
  185. package/src/oauth/AGENTS.md +9 -1
  186. package/src/oauth/byo-connection.test.ts +28 -0
  187. package/src/persistence/__tests__/recent-conversation-messages.test.ts +41 -0
  188. package/src/persistence/conversation-crud.ts +26 -0
  189. package/src/persistence/conversation-types.ts +15 -37
  190. package/src/persistence/embeddings/__tests__/embedding-local-lifecycle.test.ts +85 -14
  191. package/src/persistence/jobs-store.ts +229 -0
  192. package/src/persistence/migrations/383-normalize-opencode-host-connections.ts +44 -0
  193. package/src/persistence/migrations/__tests__/383-normalize-opencode-host-connections.test.ts +102 -0
  194. package/src/persistence/steps.ts +12 -0
  195. package/src/platform/sync-avatar.test.ts +29 -0
  196. package/src/plugins/defaults/memory/AGENTS.md +5 -3
  197. package/src/plugins/defaults/memory/__tests__/skill-update-receipt-boundary-guard.test.ts +45 -0
  198. package/src/plugins/defaults/memory/__tests__/skill-update-receipt-job.test.ts +580 -0
  199. package/src/plugins/defaults/memory/__tests__/turn-retrieval.test.ts +21 -0
  200. package/src/plugins/defaults/memory/graph/tools.ts +9 -5
  201. package/src/plugins/defaults/memory/hooks/conversation-deleted.ts +4 -0
  202. package/src/plugins/defaults/memory/hooks/user-prompt-submit.ts +7 -3
  203. package/src/plugins/defaults/memory/job-handlers.ts +8 -2
  204. package/src/plugins/defaults/memory/skill-update-receipt-job.ts +334 -0
  205. package/src/plugins/defaults/memory/tools.test.ts +17 -0
  206. package/src/plugins/defaults/memory/turn-retrieval.ts +8 -0
  207. package/src/plugins/defaults/memory/v3/__tests__/injection.test.ts +24 -0
  208. package/src/plugins/defaults/memory/v3/injector.ts +4 -4
  209. package/src/plugins/types.ts +2 -0
  210. package/src/providers/__tests__/search-provider-catalog.test.ts +8 -0
  211. package/src/providers/anthropic/client.ts +4 -0
  212. package/src/providers/gemini/client.ts +7 -1
  213. package/src/providers/inference/auth.ts +25 -0
  214. package/src/providers/inference/profile-probe.ts +1 -0
  215. package/src/{calls/__tests__/typesafe-noul.test.ts → providers/jev/ask.test.ts} +4 -4
  216. package/src/{calls/typesafe-noul.ts → providers/jev/ask.ts} +67 -34
  217. package/src/providers/openai/__tests__/api-error-normalization.test.ts +12 -0
  218. package/src/providers/openai/api-error-normalization.ts +4 -0
  219. package/src/providers/retry.ts +2 -0
  220. package/src/providers/search-provider-catalog.ts +10 -0
  221. package/src/providers/types.ts +7 -0
  222. package/src/providers/usage-tracking.ts +5 -3
  223. package/src/runtime/__tests__/agent-wake.test.ts +308 -0
  224. package/src/runtime/access-request-helper.ts +16 -9
  225. package/src/runtime/agent-wake-queue.ts +52 -0
  226. package/src/runtime/agent-wake.ts +111 -18
  227. package/src/runtime/channel-approval-types.ts +6 -38
  228. package/src/runtime/channel-approvals.ts +4 -5
  229. package/src/runtime/http-server.ts +4 -1
  230. package/src/runtime/introduction-policy.test.ts +17 -1
  231. package/src/runtime/introduction-policy.ts +25 -7
  232. package/src/runtime/migrations/vbundle-builder.ts +9 -0
  233. package/src/runtime/routes/__tests__/inference-profiles-routes.test.ts +21 -1
  234. package/src/runtime/routes/__tests__/inference-provider-connection-routes.test.ts +60 -0
  235. package/src/runtime/routes/__tests__/oauth-proxy-routes.test.ts +61 -3
  236. package/src/runtime/routes/auto-profile-routes.ts +83 -0
  237. package/src/runtime/routes/conversation-management-routes.ts +1 -3
  238. package/src/runtime/routes/conversation-routes.ts +9 -0
  239. package/src/runtime/routes/guardian-action-routes.ts +8 -23
  240. package/src/runtime/routes/host-cu-routes.ts +3 -1
  241. package/src/runtime/routes/index.ts +2 -0
  242. package/src/runtime/routes/inference-profiles-routes.ts +5 -2
  243. package/src/runtime/routes/inference-provider-connection-routes.ts +25 -8
  244. package/src/runtime/routes/migration-routes.ts +8 -2
  245. package/src/runtime/routes/oauth-proxy-passthrough.test.ts +32 -0
  246. package/src/runtime/routes/platform-routes.ts +6 -1
  247. package/src/runtime/routes/user-route-dispatcher.ts +1 -2
  248. package/src/runtime/web-presence.ts +3 -4
  249. package/src/schedule/schedule-store.ts +10 -0
  250. package/src/schedule/scheduler.ts +92 -24
  251. package/src/subagent/manager.ts +32 -12
  252. package/src/telegram/__tests__/webhook-health.test.ts +8 -0
  253. package/src/telemetry/telemetry-wire-source.json +1 -1
  254. package/src/telemetry/telemetry-wire.generated.ts +1 -0
  255. package/src/tools/background-tool-registry.ts +30 -3
  256. package/src/tools/browser/cdp-client/local-cdp-client.ts +1 -2
  257. package/src/tools/host-terminal/host-shell.ts +7 -0
  258. package/src/tools/network/__tests__/web-fetch-firecrawl.test.ts +28 -1
  259. package/src/tools/network/__tests__/web-fetch-metadata.test.ts +34 -0
  260. package/src/tools/network/__tests__/web-fetch-tinyfish.test.ts +35 -1
  261. package/src/tools/network/__tests__/web-search.test.ts +96 -0
  262. package/src/tools/network/web-fetch.ts +30 -9
  263. package/src/tools/network/web-search.ts +235 -4
  264. package/src/tools/skills/load.ts +13 -17
  265. package/src/tools/skills/scaffold-managed.ts +86 -71
  266. package/src/tools/terminal/shell-launch.test.ts +27 -1
  267. package/src/tools/terminal/shell.ts +4 -0
  268. package/src/tools/workspace-tools/loader.ts +1 -2
  269. package/src/usage/attribution.ts +18 -1
  270. package/src/util/abort-reasons.ts +2 -0
  271. package/src/util/errors.ts +1 -0
  272. package/src/util/oauth-request-body.test.ts +5 -1
  273. package/src/util/provider-error-patterns.ts +11 -0
  274. package/src/util/single-flight.test.ts +6 -0
  275. package/src/util/single-flight.ts +2 -0
  276. package/src/util/worker-pipe.test.ts +56 -10
  277. package/src/util/worker-pipe.ts +9 -4
  278. package/src/workspace/git-service.ts +6 -1
  279. package/src/workspace/migrations/158-repoint-opencode-host-provider-fragments.ts +163 -0
  280. package/src/workspace/migrations/__tests__/158-repoint-opencode-host-provider-fragments.test.ts +188 -0
  281. package/src/workspace/migrations/registry.ts +2 -0
@@ -0,0 +1,369 @@
1
+ import type pino from "pino";
2
+
3
+ import { isToolResultOnlyUserMessage } from "../conversations/message-consolidation.js";
4
+ import {
5
+ getAttentionStateByConversationIds,
6
+ hasUnseenLatestAssistantMessage,
7
+ } from "../persistence/conversation-attention-store.js";
8
+ import {
9
+ type ConversationRow,
10
+ getConversation,
11
+ getMessageById,
12
+ getRecentConversationMessages,
13
+ isStandaloneAssistantMessage,
14
+ type MessageRow,
15
+ parseMessageMetadata,
16
+ } from "../persistence/conversation-crud.js";
17
+ import { isReplaceableTitle } from "../persistence/conversation-title-placeholders.js";
18
+ import {
19
+ isEchoSuppressedUserMessage,
20
+ resolveConversationKind,
21
+ } from "../persistence/conversation-types.js";
22
+ import { getSubagentRecordById } from "../persistence/subagent-store.js";
23
+ import type { CompletionContext } from "./completion-policy.js";
24
+ import { isUserFacingSubagent } from "./completion-work.js";
25
+ import { emitNotificationSignal } from "./emit-signal.js";
26
+ import { hasNotifiedSourceContextSince } from "./events-store.js";
27
+ import { hasPendingBackgroundWork } from "./has-pending-background-work.js";
28
+ import { sanitizeNotificationTitle } from "./notification-utils.js";
29
+ import {
30
+ resolveCompletionRecipientPrincipalId,
31
+ resolveCompletionVisibleInSourceNow,
32
+ } from "./resolve-visible-in-source.js";
33
+ import {
34
+ collectRunRows,
35
+ deliveredThroughMessagingTool,
36
+ resolveLatestRunRow,
37
+ resolveRunResult,
38
+ } from "./result-output.js";
39
+
40
+ const RESULT_EVENT_NAMES = ["assistant.share", "activity.complete"] as const;
41
+ const COMPLETION_HISTORY_LIMIT = 200;
42
+
43
+ interface CompletedWork {
44
+ workId: string;
45
+ childConversationId?: string;
46
+ startedAt: number;
47
+ }
48
+
49
+ /** Existing terminal records opt parent continuations into completion delivery. */
50
+ function resolveCompletedWork(
51
+ conversationId: string,
52
+ trigger: MessageRow,
53
+ turnTrigger: MessageRow,
54
+ ): CompletedWork | undefined {
55
+ const metadata = parseMessageMetadata(trigger.metadata);
56
+ const turnMetadata =
57
+ trigger.id === turnTrigger.id
58
+ ? metadata
59
+ : parseMessageMetadata(turnTrigger.metadata);
60
+ if (
61
+ !metadata ||
62
+ !turnMetadata ||
63
+ turnMetadata.turnOutcome !== undefined ||
64
+ (trigger.id !== turnTrigger.id &&
65
+ (metadata.turnOutcome !== "batched" ||
66
+ metadata.turnBatchedInto !== turnTrigger.id)) ||
67
+ metadata.voiceSessionTurn === true ||
68
+ turnMetadata.voiceSessionTurn === true
69
+ ) {
70
+ return undefined;
71
+ }
72
+ const terminal = metadata.subagentNotification;
73
+ if (terminal?.status === "completed") {
74
+ const task = getSubagentRecordById(terminal.subagentId);
75
+ if (
76
+ !task ||
77
+ task.status !== "completed" ||
78
+ task.parentConversationId !== conversationId ||
79
+ task.conversationId !== terminal.conversationId ||
80
+ !isUserFacingSubagent(task)
81
+ ) {
82
+ return undefined;
83
+ }
84
+ return {
85
+ workId: `subagent:${task.id}`,
86
+ childConversationId: task.conversationId,
87
+ startedAt: task.startedAt ?? task.createdAt,
88
+ };
89
+ }
90
+ const tool = metadata.backgroundToolCompletion;
91
+ if (
92
+ metadata.backgroundEventSource === "background-tool" &&
93
+ tool?.status === "completed" &&
94
+ tool.conversationId === conversationId
95
+ ) {
96
+ return { workId: `tool:${tool.id}`, startedAt: tool.startedAt };
97
+ }
98
+ return undefined;
99
+ }
100
+
101
+ function isInternalTurnTrigger(row: MessageRow): boolean {
102
+ const metadata = parseMessageMetadata(row.metadata);
103
+ return metadata?.automated === true || isEchoSuppressedUserMessage(metadata);
104
+ }
105
+
106
+ function* completionCandidates(
107
+ conversationId: string,
108
+ trigger: MessageRow,
109
+ result: MessageRow | undefined,
110
+ ): Generator<{
111
+ trigger: MessageRow;
112
+ turnTrigger: MessageRow;
113
+ result: MessageRow;
114
+ work: CompletedWork;
115
+ }> {
116
+ if (!isInternalTurnTrigger(trigger)) {
117
+ return;
118
+ }
119
+ let beforeMessageId: string | undefined;
120
+ let foundTrigger = false;
121
+ let resultInCurrentTurn = false;
122
+ let previousResult: MessageRow | undefined;
123
+ let sharedTurn: { trigger: MessageRow; result: MessageRow } | undefined;
124
+ while (true) {
125
+ const history = getRecentConversationMessages(
126
+ conversationId,
127
+ COMPLETION_HISTORY_LIMIT,
128
+ beforeMessageId,
129
+ );
130
+ for (let index = history.length - 1; index >= 0; index--) {
131
+ const row = history[index];
132
+ if (!foundTrigger) {
133
+ if (row.id === trigger.id) {
134
+ foundTrigger = true;
135
+ previousResult = resultInCurrentTurn ? result : undefined;
136
+ } else {
137
+ if (row.role === "user" && !isToolResultOnlyUserMessage(row)) {
138
+ return;
139
+ }
140
+ if (row.id === result?.id) {
141
+ resultInCurrentTurn = true;
142
+ }
143
+ continue;
144
+ }
145
+ }
146
+ if (
147
+ row.role === "assistant" &&
148
+ !isStandaloneAssistantMessage(row.role, row.metadata)
149
+ ) {
150
+ previousResult ??= row;
151
+ sharedTurn = undefined;
152
+ } else if (row.role === "user" && !isToolResultOnlyUserMessage(row)) {
153
+ if (!isInternalTurnTrigger(row)) {
154
+ return;
155
+ }
156
+ const metadata = parseMessageMetadata(row.metadata);
157
+ if (metadata?.turnOutcome !== "batched") {
158
+ sharedTurn = previousResult
159
+ ? { trigger: row, result: previousResult }
160
+ : undefined;
161
+ } else if (metadata.turnBatchedInto !== sharedTurn?.trigger.id) {
162
+ sharedTurn = undefined;
163
+ }
164
+ if (sharedTurn) {
165
+ const work = resolveCompletedWork(
166
+ conversationId,
167
+ row,
168
+ sharedTurn.trigger,
169
+ );
170
+ if (work) {
171
+ yield {
172
+ trigger: row,
173
+ turnTrigger: sharedTurn.trigger,
174
+ result: sharedTurn.result,
175
+ work,
176
+ };
177
+ }
178
+ }
179
+ previousResult = undefined;
180
+ }
181
+ }
182
+ if (history.length < COMPLETION_HISTORY_LIMIT) {
183
+ return;
184
+ }
185
+ beforeMessageId = history[0].id;
186
+ }
187
+ }
188
+
189
+ function childDeliveredResult(work: CompletedWork): boolean {
190
+ const childId = work.childConversationId;
191
+ if (!childId) {
192
+ return false;
193
+ }
194
+ if (
195
+ hasNotifiedSourceContextSince(childId, work.startedAt, RESULT_EVENT_NAMES)
196
+ ) {
197
+ return true;
198
+ }
199
+ const latest = resolveLatestRunRow(childId, work.startedAt);
200
+ return (
201
+ latest !== undefined &&
202
+ deliveredThroughMessagingTool(
203
+ childId,
204
+ collectRunRows(latest, childId, work.startedAt),
205
+ )
206
+ );
207
+ }
208
+
209
+ function canNotifyConversation(
210
+ conversation: ConversationRow | null | undefined,
211
+ ): conversation is ConversationRow {
212
+ return (
213
+ conversation != null &&
214
+ conversation.archivedAt == null &&
215
+ resolveConversationKind(
216
+ conversation.source,
217
+ conversation.conversationType,
218
+ ) === "user"
219
+ );
220
+ }
221
+
222
+ /** Notify only after a successful parent turn persists the requested result. */
223
+ export async function emitBackgroundResultNotification(params: {
224
+ conversationId: string;
225
+ assistantMessageId?: string;
226
+ userMessageId: string | undefined;
227
+ recoverOnly?: boolean;
228
+ cronRunId?: string | null;
229
+ conversation?: ConversationRow | null;
230
+ rlog: pino.Logger;
231
+ }): Promise<void> {
232
+ const { conversationId, assistantMessageId, userMessageId, rlog } = params;
233
+ try {
234
+ if (!userMessageId || params.cronRunId) {
235
+ return;
236
+ }
237
+ if (
238
+ !canNotifyConversation(
239
+ params.conversation ?? getConversation(conversationId),
240
+ )
241
+ ) {
242
+ return;
243
+ }
244
+ const recipientPrincipalId =
245
+ await resolveCompletionRecipientPrincipalId(rlog);
246
+ if (!recipientPrincipalId) {
247
+ return;
248
+ }
249
+ const visibleInSourceNow = await resolveCompletionVisibleInSourceNow({
250
+ conversationId,
251
+ actorPrincipalId: recipientPrincipalId,
252
+ logger: rlog,
253
+ });
254
+ // Eligibility reads stay together after all asynchronous lookups.
255
+ const conversation = getConversation(conversationId);
256
+ if (!canNotifyConversation(conversation)) {
257
+ return;
258
+ }
259
+ const trigger = getMessageById(userMessageId, conversationId);
260
+ if (!trigger) {
261
+ return;
262
+ }
263
+ // A parent that only launched more work has not produced the final result.
264
+ if (hasPendingBackgroundWork(conversationId)) {
265
+ return;
266
+ }
267
+ const attention = getAttentionStateByConversationIds([conversationId]).get(
268
+ conversationId,
269
+ );
270
+ if (
271
+ !hasUnseenLatestAssistantMessage(attention) ||
272
+ (assistantMessageId !== undefined &&
273
+ attention?.latestAssistantMessageId !== assistantMessageId)
274
+ ) {
275
+ return;
276
+ }
277
+ const latestId = assistantMessageId ?? attention?.latestAssistantMessageId;
278
+ const latestResult = latestId
279
+ ? (getMessageById(latestId, conversationId) ?? undefined)
280
+ : undefined;
281
+ for (const candidate of completionCandidates(
282
+ conversationId,
283
+ trigger,
284
+ params.recoverOnly ? undefined : latestResult,
285
+ )) {
286
+ const {
287
+ work,
288
+ result,
289
+ trigger: successfulTrigger,
290
+ turnTrigger,
291
+ } = candidate;
292
+ if (
293
+ result.role !== "assistant" ||
294
+ result.finalized !== 1 ||
295
+ isStandaloneAssistantMessage(result.role, result.metadata)
296
+ ) {
297
+ continue;
298
+ }
299
+ if (
300
+ result.createdAt <= (attention?.lastSeenAssistantMessageAt ?? -Infinity)
301
+ ) {
302
+ return;
303
+ }
304
+ if (
305
+ hasNotifiedSourceContextSince(
306
+ conversationId,
307
+ successfulTrigger.createdAt,
308
+ RESULT_EVENT_NAMES,
309
+ )
310
+ ) {
311
+ return;
312
+ }
313
+ if (childDeliveredResult(work)) {
314
+ continue;
315
+ }
316
+ const rows = collectRunRows(
317
+ result,
318
+ conversationId,
319
+ turnTrigger.createdAt,
320
+ );
321
+ if (deliveredThroughMessagingTool(conversationId, rows)) {
322
+ return;
323
+ }
324
+ const output = resolveRunResult(rows);
325
+ if (!output) {
326
+ continue;
327
+ }
328
+ if (
329
+ output.row.createdAt <=
330
+ (attention?.lastSeenAssistantMessageAt ?? -Infinity)
331
+ ) {
332
+ return;
333
+ }
334
+ const completion: CompletionContext = {
335
+ workId: work.workId,
336
+ conversationId,
337
+ recipientPrincipalId,
338
+ owner: "parent_continuation",
339
+ };
340
+ const storedTitle = conversation.title?.trim() ?? "";
341
+ const requestedTitle = isReplaceableTitle(storedTitle)
342
+ ? undefined
343
+ : sanitizeNotificationTitle(storedTitle.replace(/\s+/g, " "));
344
+ await emitNotificationSignal({
345
+ sourceEventName: "activity.complete",
346
+ sourceChannel: "assistant_tool",
347
+ sourceContextId: conversationId,
348
+ attentionHints: {
349
+ requiresAction: false,
350
+ urgency: "medium",
351
+ isAsyncBackground: true,
352
+ visibleInSourceNow,
353
+ },
354
+ contextPayload: {
355
+ completion,
356
+ ...(requestedTitle ? { requestedTitle } : {}),
357
+ requestedMessage: output.body,
358
+ },
359
+ dedupeKey: `activity.complete:${conversationId}:${work.workId}`,
360
+ });
361
+ return;
362
+ }
363
+ } catch (err) {
364
+ rlog.warn(
365
+ { err, conversationId, assistantMessageId },
366
+ "Failed to emit background result notification (non-fatal)",
367
+ );
368
+ }
369
+ }
@@ -23,6 +23,13 @@ import {
23
23
  } from "./access-request-copy.js";
24
24
  import { isGuardianSensitiveEvent } from "./adapters/macos.js";
25
25
  import { resolveMessageText } from "./adapters/shared.js";
26
+ import {
27
+ isCompletionNotification,
28
+ isCompletionRecipientUnavailable,
29
+ isLocalNotificationSilent,
30
+ notificationConversationId,
31
+ resolveCompletionRecipient,
32
+ } from "./completion-policy.js";
26
33
  import {
27
34
  pairDeliveryWithConversation,
28
35
  type PairingResult,
@@ -351,6 +358,10 @@ export class NotificationBroadcaster {
351
358
  decision.selectedChannels,
352
359
  guardians,
353
360
  );
361
+ const silent = isLocalNotificationSilent({
362
+ ...signal,
363
+ urgency: signal.attentionHints.urgency,
364
+ });
354
365
 
355
366
  // Ensure vellum is processed first so the notification_conversation_created
356
367
  // event fires immediately, before slower channel sends (e.g. Telegram 30s
@@ -457,6 +468,16 @@ export class NotificationBroadcaster {
457
468
  continue;
458
469
  }
459
470
 
471
+ if (isCompletionRecipientUnavailable(signal, destination)) {
472
+ results.push({
473
+ channel,
474
+ destination: destination.endpoint ?? channel,
475
+ status: "failed",
476
+ errorMessage: "completion recipient unavailable",
477
+ });
478
+ continue;
479
+ }
480
+
460
481
  // Pull rendered copy from the decision; fall back to copy-composer if
461
482
  // missing or effectively blank. The decision engine's LLM occasionally
462
483
  // returns empty title/body strings that pass type-only validation, so
@@ -601,7 +622,7 @@ export class NotificationBroadcaster {
601
622
  : pairing;
602
623
  const deepLinkConversationId =
603
624
  deepLinkPairing.conversationId ??
604
- resolveSourceConversationId(signal.sourceContextId) ??
625
+ resolveSourceConversationId(notificationConversationId(signal)) ??
605
626
  resolveDeepLinkConversationId(signal.contextPayload);
606
627
  if (deepLinkConversationId) {
607
628
  deepLinkTarget = {
@@ -625,17 +646,15 @@ export class NotificationBroadcaster {
625
646
  typeof destination.metadata?.guardianPrincipalId === "string"
626
647
  ? destination.metadata.guardianPrincipalId
627
648
  : undefined;
628
- const targetGuardianPrincipalId =
629
- guardianPrincipalId &&
630
- isGuardianSensitiveEvent(signal.sourceEventName)
649
+ const targetGuardianPrincipalId = isCompletionNotification(signal)
650
+ ? resolveCompletionRecipient(signal, destination)
651
+ : guardianPrincipalId &&
652
+ isGuardianSensitiveEvent(signal.sourceEventName)
631
653
  ? guardianPrincipalId
632
654
  : undefined;
633
655
 
634
656
  const conversationTitle =
635
657
  copy.conversationTitle ?? copy.title ?? signal.sourceEventName;
636
- const conversationSilent =
637
- signal.attentionHints.urgency !== "high" &&
638
- signal.attentionHints.urgency !== "critical";
639
658
  const info: ConversationCreatedInfo = {
640
659
  conversationId: pairing.conversationId,
641
660
  title: conversationTitle,
@@ -643,7 +662,7 @@ export class NotificationBroadcaster {
643
662
  targetGuardianPrincipalId,
644
663
  groupId: signal.conversationMetadata?.groupId,
645
664
  source: signal.conversationMetadata?.source,
646
- silent: conversationSilent,
665
+ silent,
647
666
  };
648
667
 
649
668
  // The per-dispatch onConversationCreated callback fires whenever a vellum
@@ -695,6 +714,7 @@ export class NotificationBroadcaster {
695
714
  deepLinkTarget,
696
715
  contextPayload: signal.contextPayload,
697
716
  urgency: signal.attentionHints.urgency,
717
+ silent,
698
718
  approvalContext,
699
719
  accessRequestContext,
700
720
  toolApprovalSource,
@@ -0,0 +1,115 @@
1
+ import { z } from "zod";
2
+
3
+ import type { ChannelDestination } from "./types.js";
4
+ import type { Urgency } from "./urgency.js";
5
+
6
+ export const CompletionContextSchema = z.object({
7
+ workId: z.string().trim().min(1),
8
+ conversationId: z.string().trim().min(1),
9
+ recipientPrincipalId: z.string().trim().min(1),
10
+ owner: z.literal("parent_continuation"),
11
+ });
12
+
13
+ export type CompletionContext = z.infer<typeof CompletionContextSchema>;
14
+
15
+ interface CompletionEvent {
16
+ sourceEventName: string;
17
+ contextPayload?: Record<string, unknown>;
18
+ }
19
+
20
+ /** Declared ownership stays private even when the completion payload is malformed. */
21
+ export function hasCompletionOwnership(event: CompletionEvent): boolean {
22
+ return (
23
+ event.sourceEventName === "activity.complete" &&
24
+ Object.prototype.hasOwnProperty.call(
25
+ event.contextPayload ?? {},
26
+ "completion",
27
+ )
28
+ );
29
+ }
30
+
31
+ export function readCompletionContext(
32
+ event: CompletionEvent,
33
+ ): CompletionContext | undefined {
34
+ if (!hasCompletionOwnership(event)) {
35
+ return undefined;
36
+ }
37
+ const parsed = CompletionContextSchema.safeParse(
38
+ event.contextPayload?.completion,
39
+ );
40
+ return parsed.success ? parsed.data : undefined;
41
+ }
42
+
43
+ export function isCompletionNotification(event: CompletionEvent): boolean {
44
+ return (
45
+ event.sourceEventName === "chat.assistant_reply" ||
46
+ event.sourceEventName === "schedule.result" ||
47
+ readCompletionContext(event) !== undefined
48
+ );
49
+ }
50
+
51
+ export function hasPersistedCompletionResult(event: CompletionEvent): boolean {
52
+ return (
53
+ event.sourceEventName === "chat.assistant_reply" ||
54
+ readCompletionContext(event) !== undefined
55
+ );
56
+ }
57
+
58
+ export function notificationConversationId(
59
+ event: CompletionEvent & { sourceContextId?: string },
60
+ ): string | undefined {
61
+ return readCompletionContext(event)?.conversationId ?? event.sourceContextId;
62
+ }
63
+
64
+ /** Completion presentation is independent of urgency and channel routing. */
65
+ export function isLocalNotificationSilent(
66
+ event: CompletionEvent & { urgency: Urgency },
67
+ ): boolean {
68
+ if (event.contextPayload?.quiet === true) {
69
+ return true;
70
+ }
71
+ return (
72
+ !isCompletionNotification(event) &&
73
+ event.urgency !== "high" &&
74
+ event.urgency !== "critical"
75
+ );
76
+ }
77
+
78
+ /** A completion preview may only reach the currently bound recipient. */
79
+ export function resolveCompletionRecipient(
80
+ event: CompletionEvent,
81
+ destination: ChannelDestination,
82
+ ): string | undefined {
83
+ const raw = destination.metadata?.guardianPrincipalId;
84
+ const guardianPrincipalId = typeof raw === "string" ? raw.trim() : "";
85
+ if (!guardianPrincipalId) {
86
+ return undefined;
87
+ }
88
+ const completion = readCompletionContext(event);
89
+ if (
90
+ hasCompletionOwnership(event) &&
91
+ completion?.recipientPrincipalId !== guardianPrincipalId
92
+ ) {
93
+ return undefined;
94
+ }
95
+ return guardianPrincipalId;
96
+ }
97
+
98
+ /** Owned completions require a matching local/mobile recipient; local previews require a recipient. */
99
+ export function isCompletionRecipientUnavailable(
100
+ event: CompletionEvent,
101
+ destination: ChannelDestination,
102
+ ): boolean {
103
+ const ownedCompletion = hasCompletionOwnership(event);
104
+ if (
105
+ ownedCompletion &&
106
+ destination.channel !== "vellum" &&
107
+ destination.channel !== "platform"
108
+ ) {
109
+ return true;
110
+ }
111
+ const requiresRecipient =
112
+ ownedCompletion ||
113
+ (destination.channel === "vellum" && isCompletionNotification(event));
114
+ return requiresRecipient && !resolveCompletionRecipient(event, destination);
115
+ }
@@ -0,0 +1,46 @@
1
+ import type { TurnWorkOrigin } from "../daemon/conversation-queue-manager.js";
2
+ import {
3
+ getSubagentRecordById,
4
+ type SubagentRecord,
5
+ } from "../persistence/subagent-store.js";
6
+
7
+ /** Match the parent delivery contract: advisors and silent forks stay internal. */
8
+ export function isUserFacingSubagent(
9
+ task: Pick<SubagentRecord, "role" | "isFork" | "sendResultToUser">,
10
+ ): boolean {
11
+ return (
12
+ task.role !== "advisor" &&
13
+ (task.isFork
14
+ ? task.sendResultToUser === true
15
+ : task.sendResultToUser !== false)
16
+ );
17
+ }
18
+
19
+ export function workStartedAfter(
20
+ message: TurnWorkOrigin,
21
+ cutoff: number,
22
+ ): boolean {
23
+ const taskNotification = message.metadata?.subagentNotification;
24
+ if (
25
+ taskNotification &&
26
+ typeof taskNotification === "object" &&
27
+ "subagentId" in taskNotification &&
28
+ typeof taskNotification.subagentId === "string"
29
+ ) {
30
+ const task = getSubagentRecordById(taskNotification.subagentId);
31
+ if (task) {
32
+ return isUserFacingSubagent(task) && task.createdAt >= cutoff;
33
+ }
34
+ }
35
+ const command = message.metadata?.backgroundToolCompletion;
36
+ if (
37
+ message.metadata?.backgroundEventSource === "background-tool" &&
38
+ command &&
39
+ typeof command === "object" &&
40
+ "startedAt" in command &&
41
+ typeof command.startedAt === "number"
42
+ ) {
43
+ return command.startedAt >= cutoff;
44
+ }
45
+ return message.sentAt >= cutoff;
46
+ }