@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,23 @@
1
+ import { optimizeImageForTransport } from "../agent/image-optimize.js";
2
+ import { parseImageDimensions } from "../context/image-dimensions.js";
3
+ import type { CuObservationResult } from "./host-cu-proxy.js";
4
+
5
+ /** Keep coordinate metadata aligned with the image sent to the model. */
6
+ export async function prepareComputerUseObservation(
7
+ observation: CuObservationResult,
8
+ ): Promise<CuObservationResult> {
9
+ if (!observation.screenshot) {
10
+ return observation;
11
+ }
12
+ const image = await optimizeImageForTransport(
13
+ observation.screenshot,
14
+ "image/jpeg",
15
+ );
16
+ const dimensions = parseImageDimensions(image.data, image.mediaType);
17
+ return {
18
+ ...observation,
19
+ screenshot: image.data,
20
+ screenshotWidthPx: dimensions?.width,
21
+ screenshotHeightPx: dimensions?.height,
22
+ };
23
+ }
@@ -53,6 +53,7 @@ import {
53
53
  updateMessageContent,
54
54
  } from "../persistence/conversation-crud.js";
55
55
  import { syncMessageToDisk } from "../persistence/conversation-disk-view.js";
56
+ import { AUTO_ROUTED_PROFILE_METADATA_KEY } from "../persistence/conversation-types.js";
56
57
  import { enqueueLexicalIndexForMessage } from "../persistence/job-handlers/message-lexical.js";
57
58
  import {
58
59
  backfillMessageIdOnLogs,
@@ -275,6 +276,12 @@ export interface EventHandlerState {
275
276
  * the model ever having seen it.
276
277
  */
277
278
  pendingNotifiedInferenceProfile: string | null;
279
+ /**
280
+ * The default profile the Auto profile routed this turn to, stamped on the
281
+ * turn's assistant rows and carried on `message_complete` so clients can
282
+ * show which profile answered. `undefined` on every turn not run on Auto.
283
+ */
284
+ autoRoutedProfile: string | undefined;
278
285
  pendingDirectiveDisplayBuffer: string;
279
286
  firstAssistantText: string;
280
287
  /** Most recent resolved provider for the current exchange's usage accounting. */
@@ -698,6 +705,7 @@ export interface EventHandlerDeps {
698
705
  export function createEventHandlerState(): EventHandlerState {
699
706
  return {
700
707
  pendingNotifiedInferenceProfile: null,
708
+ autoRoutedProfile: undefined,
701
709
  pendingDirectiveDisplayBuffer: "",
702
710
  firstAssistantText: "",
703
711
  exchangeProviderName: undefined,
@@ -3305,6 +3313,9 @@ export async function handleMessageComplete(
3305
3313
  ...(event.assistantTextVisibility
3306
3314
  ? { [ASSISTANT_TEXT_VISIBILITY_KEY]: event.assistantTextVisibility }
3307
3315
  : {}),
3316
+ ...(state.autoRoutedProfile
3317
+ ? { [AUTO_ROUTED_PROFILE_METADATA_KEY]: state.autoRoutedProfile }
3318
+ : {}),
3308
3319
  };
3309
3320
  state.lastAssistantTextVisibility = event.assistantTextVisibility;
3310
3321
  const persisted = await finalizeInflightContent(
@@ -25,6 +25,8 @@ import type {
25
25
  TurnChannelContext,
26
26
  TurnInterfaceContext,
27
27
  } from "../channels/types.js";
28
+ import { getConversationProfilesForProvider } from "../config/default-profile-catalog.js";
29
+ import { AUTO_PROFILE_KEY } from "../config/default-profile-names.js";
28
30
  import {
29
31
  contextWindowConfigFromEffective,
30
32
  type EffectiveContextWindow,
@@ -99,6 +101,12 @@ import {
99
101
  DEFAULT_TURN_COMMIT_MAX_WAIT_MS,
100
102
  } from "./abort-watchdog.js";
101
103
  import { cleanAssistantContent } from "./assistant-attachments.js";
104
+ import {
105
+ type AutoProfileRoute,
106
+ plainTextOf,
107
+ routeAutoProfile,
108
+ takeAutoProfilePreview,
109
+ } from "./auto-profile-router.js";
102
110
  import { conversationSupportsDynamicUi } from "./channel-ui-capability.js";
103
111
  import type { Conversation } from "./conversation.js";
104
112
  import {
@@ -203,6 +211,13 @@ const OUT_OF_CREDITS_ASSISTANT_REPLY =
203
211
  const DAILY_LIMIT_REACHED_ASSISTANT_REPLY =
204
212
  "I had to stop because you hit your daily credit limit. Raise the limit in Settings → Billing and we can pick up where we left off, or I can continue once it resets.";
205
213
 
214
+ /**
215
+ * The free-tier counterpart: the cap is the platform's, not a setting, so the
216
+ * ways forward are the UTC reset, an upgrade, or extra credits.
217
+ */
218
+ const FREE_TIER_DAILY_LIMIT_REACHED_ASSISTANT_REPLY =
219
+ "I had to stop because you've used today's free usage. It resets at midnight UTC, or you can upgrade or add credits in Settings → Billing and we can pick up where we left off.";
220
+
206
221
  /**
207
222
  * The assistant-voice text a managed-billing failure persists in place of the
208
223
  * classification's own `userMessage`, or `null` when the classification copy is
@@ -220,6 +235,8 @@ function managedBillingAssistantReply(
220
235
  return OUT_OF_CREDITS_ASSISTANT_REPLY;
221
236
  case "daily_limit_reached":
222
237
  return DAILY_LIMIT_REACHED_ASSISTANT_REPLY;
238
+ case "free_tier_daily_limit_reached":
239
+ return FREE_TIER_DAILY_LIMIT_REACHED_ASSISTANT_REPLY;
223
240
  default:
224
241
  return null;
225
242
  }
@@ -483,6 +500,8 @@ export async function runAgentLoopImpl(
483
500
  * loop defaults to `'mainAgent'` for user-initiated turns.
484
501
  */
485
502
  callSite?: LLMCallSite;
503
+ /** Skip fresh retrieval while keeping resident memory and static context. */
504
+ skipMemoryRetrieval?: boolean;
486
505
  /**
487
506
  * Provider configuration source when it differs from the turn's semantic
488
507
  * call site. The semantic call site still controls tools and UI behavior.
@@ -575,6 +594,7 @@ export async function runAgentLoopImpl(
575
594
  // before the prompt sync below: the tool-gated reply section and the tool
576
595
  // surface both scope on the turn's call site.
577
596
  ctx.currentCallSite = turnCallSite;
597
+ ctx.currentTurnSkipMemoryRetrieval = options?.skipMemoryRetrieval === true;
578
598
 
579
599
  // Whether this turn routes its user-facing text through `send_user_message`:
580
600
  // the flag is on and the turn is a main-agent turn. Resolved once and pinned
@@ -632,10 +652,9 @@ export async function runAgentLoopImpl(
632
652
  // internal background origin. Unset for normal user turns.
633
653
  ctx.currentTurnRequestOrigin = options?.requestOrigin;
634
654
 
635
- // Firing's run id for this turn's usage attribution. Kept local (not on the
636
- // conversation) so a reused conversation attributes each turn to its own
637
- // firing.
655
+ // Ownership covers asynchronous setup as well as the loop and its tools.
638
656
  const turnCronRunId = options?.cronRunId ?? null;
657
+ ctx.currentTurnCronRunId = turnCronRunId;
639
658
 
640
659
  // Optional per-turn inference-profile override. Plumbed through to every
641
660
  // LLM call the loop emits and inherited by any subagents spawned during
@@ -647,16 +666,94 @@ export async function runAgentLoopImpl(
647
666
  // live conversation (hydrated on load, kept current by the HTTP setters and
648
667
  // the expiry reaper), so the derivation reads `ctx` rather than re-fetching
649
668
  // the row.
650
- const userExplicitOverride =
651
- options?.overrideProfile ?? resolveOverrideProfile(ctx);
652
-
653
669
  const config = getConfig();
654
670
 
671
+ // With no explicit override, the resolver's own chain (the active profile
672
+ // for the main agent, then the call site's pin) may still select the Auto
673
+ // profile. That winner is named here so the router below covers every path
674
+ // that would otherwise dispatch the Auto body.
675
+ const readRequestedOverrideProfile = (): string | undefined => {
676
+ const explicit = options?.overrideProfile ?? resolveOverrideProfile(ctx);
677
+ if (explicit !== undefined) {
678
+ return explicit;
679
+ }
680
+ const winner = selectWinningProfile(inferenceCallSite, config.llm, {
681
+ selectionSeed: ctx.conversationId,
682
+ }).profileName;
683
+ return winner === AUTO_PROFILE_KEY ? AUTO_PROFILE_KEY : undefined;
684
+ };
685
+
686
+ // The Auto profile is a selection over the default profiles, made once per
687
+ // turn: the routed profile stands in for the Auto name on every read, so
688
+ // the whole turn (and any subagent inheriting the override) runs on one
689
+ // profile. A user profile that shadows the managed name is a profile of
690
+ // its own and is not routed. Nothing here may throw: the turn's processing
691
+ // state is already held and its release lives in the loop's `finally`
692
+ // further down, so a routing failure degrades to the Auto body instead.
693
+ const routeAutoProfileForTurn =
694
+ async (): Promise<AutoProfileRoute | null> => {
695
+ try {
696
+ const profiles = getConversationProfilesForProvider(
697
+ config.llm.profiles,
698
+ config.llm.defaultProvider ?? null,
699
+ );
700
+ if (profiles[AUTO_PROFILE_KEY]?.source !== "managed") {
701
+ return null;
702
+ }
703
+ const userMessage = plainTextOf(
704
+ getMessageById(userMessageId)?.content ?? [],
705
+ );
706
+ // A draft the composer already previewed carries its pick over, so
707
+ // the reply lands on the profile the pill showed with no second call.
708
+ const previewed = takeAutoProfilePreview({
709
+ conversationId: ctx.conversationId,
710
+ text: userMessage,
711
+ history: ctx.messages,
712
+ profiles,
713
+ });
714
+ const route =
715
+ previewed ??
716
+ (await routeAutoProfile({
717
+ conversationId: ctx.conversationId,
718
+ history: ctx.messages,
719
+ userMessage,
720
+ profiles,
721
+ signal: abortController.signal,
722
+ }));
723
+ rlog.info(
724
+ {
725
+ outcome: route.outcome,
726
+ profile: route.profile,
727
+ confidence: route.confidence ?? null,
728
+ latencyMs: route.latencyMs,
729
+ reusedPreview: previewed !== undefined,
730
+ },
731
+ "Auto profile routed the turn",
732
+ );
733
+ return route;
734
+ } catch (err) {
735
+ rlog.warn(
736
+ { err },
737
+ "Auto profile routing failed; running the Auto body",
738
+ );
739
+ return null;
740
+ }
741
+ };
742
+ const requestedOverrideProfile = readRequestedOverrideProfile();
743
+ const autoRoute =
744
+ requestedOverrideProfile === AUTO_PROFILE_KEY
745
+ ? await routeAutoProfileForTurn()
746
+ : null;
747
+ const withAutoRoute = (profile: string | undefined): string | undefined =>
748
+ profile === AUTO_PROFILE_KEY && autoRoute ? autoRoute.profile : profile;
749
+
750
+ const userExplicitOverride = withAutoRoute(requestedOverrideProfile);
751
+
655
752
  const turnOverrideProfile = userExplicitOverride;
656
753
  const forceOverrideProfile = options?.forceOverrideProfile === true;
657
754
 
658
755
  const readCurrentOverrideProfile = (): string | undefined =>
659
- options?.overrideProfile ?? resolveOverrideProfile(ctx);
756
+ withAutoRoute(readRequestedOverrideProfile());
660
757
 
661
758
  // Best-effort attribution for error classification: names the resolved
662
759
  // connection and profile so credential/connection errors point at the
@@ -803,11 +900,6 @@ export async function runAgentLoopImpl(
803
900
  // applies to later tool executions and nested subagents in the same turn.
804
901
  ctx.currentTurnOverrideProfile = turnOverrideProfile;
805
902
 
806
- // Mirrored onto the live conversation for `createToolExecutor` to read into
807
- // `ToolContext.cronRunId`, so a tool that delegates LLM work (subagent spawn
808
- // or message) stamps the delegated usage with this firing.
809
- ctx.currentTurnCronRunId = turnCronRunId;
810
-
811
903
  // Capture the turn channel context *before* any awaits so a second
812
904
  // message from a different channel can't overwrite it mid-flight.
813
905
  // When context is unavailable (e.g. regenerate after daemon restart),
@@ -890,6 +982,7 @@ export async function runAgentLoopImpl(
890
982
  startToolProfilingRequest(ctx.conversationId);
891
983
  let turnStarted = false;
892
984
  const state = createEventHandlerState();
985
+ state.autoRoutedProfile = autoRoute?.profile;
893
986
  // Publish this turn's flushed-content watermark so the worker → daemon
894
987
  // persist hand-off can cap a snapshot anchor at flushed content rather than
895
988
  // the live seq counter, which runs ahead while the turn streams. Cleared in
@@ -948,6 +1041,7 @@ export async function runAgentLoopImpl(
948
1041
  // provider-error turn's only assistant row is the synthetic error text, so
949
1042
  // the deferred tail must not treat either as a final reply.
950
1043
  let turnCompleted = false;
1044
+ let failedTurnAt: number | undefined;
951
1045
  // Files this turn attached that survived resolution and persistence, in
952
1046
  // the shape the activation hook records as artifacts. Rejected directives
953
1047
  // never reach it, so a checklist card can never point at a file the turn
@@ -966,6 +1060,30 @@ export async function runAgentLoopImpl(
966
1060
  // prevents.
967
1061
  const ownedReactionRecords: QueuedReactionRecord[] = [];
968
1062
 
1063
+ const queueDeferredTurnTail = (
1064
+ completed: boolean,
1065
+ criticalSectionMs: number,
1066
+ ready?: Promise<void>,
1067
+ ): void => {
1068
+ chainTurnTail(ctx.conversationId, async () => {
1069
+ if (ready) {
1070
+ await ready;
1071
+ }
1072
+ await runDeferredTurnTail({
1073
+ conversationId: ctx.conversationId,
1074
+ state,
1075
+ rlog,
1076
+ criticalSectionMs,
1077
+ turnCompleted: completed,
1078
+ userMessageId: options?.notifyUserMessageId ?? userMessageId,
1079
+ cronRunId: turnCronRunId,
1080
+ ...(options?.replyDeliveredInAppOnly
1081
+ ? { replyDeliveredInAppOnly: true }
1082
+ : {}),
1083
+ });
1084
+ });
1085
+ };
1086
+
969
1087
  /**
970
1088
  * Free the conversation for its next turn.
971
1089
  *
@@ -1029,12 +1147,14 @@ export async function runAgentLoopImpl(
1029
1147
  ctx.preactivatedSkillIds = undefined;
1030
1148
  ctx.currentTurnOverrideProfile = undefined;
1031
1149
  ctx.currentTurnCronRunId = undefined;
1150
+ ctx.currentTurnWorkOrigins = undefined;
1032
1151
  ctx.currentTurnModelProfileNoticeKey = undefined;
1033
1152
  // Turn-scoped interactivity. Clear it so paths that bypass this loop
1034
1153
  // (e.g. opportunity wakes calling `agentLoop.run` directly) don't inherit
1035
1154
  // a stale value and instead fall back to live client state in the tool
1036
1155
  // context.
1037
1156
  ctx.currentTurnIsNonInteractive = undefined;
1157
+ ctx.currentTurnSkipMemoryRetrieval = undefined;
1038
1158
  // Turn-scoped request origin. Clear so a later turn on a reused
1039
1159
  // conversation cannot inherit a stale origin-scoped permission grant.
1040
1160
  ctx.currentTurnRequestOrigin = undefined;
@@ -1603,6 +1723,7 @@ export async function runAgentLoopImpl(
1603
1723
  supportsDynamicUi: conversationSupportsDynamicUi(ctx),
1604
1724
  trust: loopTrust,
1605
1725
  overrideProfile: turnOverrideProfile,
1726
+ ...(autoRoute ? { overrideProfileOrigin: "auto" as const } : {}),
1606
1727
  ...(forceOverrideProfile ? { forceOverrideProfile: true } : {}),
1607
1728
  resolveOverrideProfile: refreshCurrentProfileState,
1608
1729
  ...(onModelCallPrepared !== undefined ? { onModelCallPrepared } : {}),
@@ -2027,6 +2148,9 @@ export async function runAgentLoopImpl(
2027
2148
  // path to the terminal SSE that re-enables the composer.
2028
2149
  ctx.messages = restoredHistory;
2029
2150
 
2151
+ // The row's override is whichever profile served the last call.
2152
+ const mainRowOverrideProfile =
2153
+ state.exchangeInferenceProfile ?? refreshCurrentProfileState() ?? null;
2030
2154
  emitUsage(
2031
2155
  ctx,
2032
2156
  state.exchangeInputTokens,
@@ -2051,16 +2175,17 @@ export async function runAgentLoopImpl(
2051
2175
  // backup (via `state.exchangeProviderName` / `state.model`), so
2052
2176
  // attributing the profile from the primary would write a row that
2053
2177
  // contradicts itself. `forceOverrideProfile` floats it above the
2054
- // call-site profile exactly as the fallback dispatch did.
2178
+ // call-site profile exactly as the fallback dispatch did. The Auto
2179
+ // origin applies only while the row's override is still the router's
2180
+ // pick: a profile switched in mid-turn is the user's.
2055
2181
  {
2056
2182
  callSite: inferenceCallSite,
2057
- overrideProfile:
2058
- state.exchangeInferenceProfile ??
2059
- refreshCurrentProfileState() ??
2060
- null,
2183
+ overrideProfile: mainRowOverrideProfile,
2061
2184
  ...(state.exchangeInferenceProfile !== undefined
2062
2185
  ? { forceOverrideProfile: true }
2063
- : {}),
2186
+ : autoRoute && mainRowOverrideProfile === autoRoute.profile
2187
+ ? { overrideProfileOrigin: "auto" as const }
2188
+ : {}),
2064
2189
  },
2065
2190
  turnCronRunId,
2066
2191
  );
@@ -2167,6 +2292,9 @@ export async function runAgentLoopImpl(
2167
2292
  ...(state.lastAssistantMessageId
2168
2293
  ? { messageId: state.lastAssistantMessageId }
2169
2294
  : {}),
2295
+ ...(state.autoRoutedProfile
2296
+ ? { autoRoutedProfile: state.autoRoutedProfile }
2297
+ : {}),
2170
2298
  modeSession: ctx.modeSessions.getTurnOwner(reqId),
2171
2299
  });
2172
2300
  publishLoopMessagesChanged();
@@ -2195,6 +2323,9 @@ export async function runAgentLoopImpl(
2195
2323
  ...(state.lastAssistantTextVisibility
2196
2324
  ? { assistantTextVisibility: state.lastAssistantTextVisibility }
2197
2325
  : {}),
2326
+ ...(state.autoRoutedProfile
2327
+ ? { autoRoutedProfile: state.autoRoutedProfile }
2328
+ : {}),
2198
2329
  });
2199
2330
  if (shouldEmitQueuedConversationNotices) {
2200
2331
  for (const notice of drainConversationNotices(ctx.conversationId)) {
@@ -2252,20 +2383,9 @@ export async function runAgentLoopImpl(
2252
2383
  // conversation id rather than held on this instance, because the tail runs
2253
2384
  // while the conversation reads idle and can therefore outlive the instance
2254
2385
  // that scheduled it.
2255
- chainTurnTail(ctx.conversationId, () =>
2256
- runDeferredTurnTail({
2257
- conversationId: ctx.conversationId,
2258
- state,
2259
- rlog,
2260
- criticalSectionMs,
2261
- turnCompleted,
2262
- userMessageId: options?.notifyUserMessageId ?? userMessageId,
2263
- ...(options?.replyDeliveredInAppOnly
2264
- ? { replyDeliveredInAppOnly: true }
2265
- : {}),
2266
- }),
2267
- );
2386
+ queueDeferredTurnTail(turnCompleted, criticalSectionMs);
2268
2387
  } catch (err) {
2388
+ failedTurnAt = Date.now();
2269
2389
  clearConversationNotices(ctx.conversationId);
2270
2390
  // A turn that threw out of the loop is over too; see the happy path.
2271
2391
  if (!isPreemptedByNewMessage(abortController.signal.reason)) {
@@ -2467,10 +2587,15 @@ export async function runAgentLoopImpl(
2467
2587
  // kickDrainQueue never rejects: a drain failure here would otherwise be
2468
2588
  // an unhandled rejection that strands the queue with nothing left to
2469
2589
  // re-trigger it.
2470
- void ctx.kickDrainQueue(
2590
+ const queueDrain = ctx.kickDrainQueue(
2471
2591
  yieldedForHandoff ? "checkpoint_handoff" : "loop_complete",
2472
2592
  "agent_loop_finally",
2473
2593
  );
2594
+ if (failedTurnAt !== undefined) {
2595
+ // A terminal failure can release an earlier successful sibling result.
2596
+ // Recovery waits for queued continuations to settle and stays detached.
2597
+ queueDeferredTurnTail(false, Date.now() - failedTurnAt, queueDrain);
2598
+ }
2474
2599
  }
2475
2600
  }
2476
2601
  }
@@ -659,6 +659,10 @@ function reasonToClassification(
659
659
  // own — the global routing map can lag per-connection platform-auth
660
660
  // routes and must not downgrade this to the generic billing surface.
661
661
  return dailyLimitClassification();
662
+ case "free_tier_daily_limit_reached":
663
+ // Same provenance as `daily_limit_reached`: only the platform proxy's
664
+ // `"code":"free_tier_daily_limit_reached"` body stamps it.
665
+ return freeTierDailyLimitClassification();
662
666
  case "overloaded":
663
667
  return providerOverloadedClassification();
664
668
  case "server_error":
@@ -817,6 +821,21 @@ function dailyLimitClassification(): Omit<
817
821
  };
818
822
  }
819
823
 
824
+ function freeTierDailyLimitClassification(): Omit<
825
+ ClassifiedConversationError,
826
+ "debugDetails"
827
+ > {
828
+ return {
829
+ code: "PROVIDER_BILLING",
830
+ // Unlike the user-configured daily limit there is nothing to raise: the
831
+ // free-tier cap lifts at the UTC reset, on upgrade, or with extra credits.
832
+ userMessage:
833
+ "You've used today's free usage. It resets at midnight UTC. Upgrade or add credits to keep going.",
834
+ retryable: false,
835
+ errorCategory: "free_tier_daily_limit_reached",
836
+ };
837
+ }
838
+
820
839
  // Shared classification producers — single source of `code`+`errorCategory`
821
840
  // for both the reason short-circuit and the reason-less fallback.
822
841
 
@@ -34,6 +34,8 @@ import { getLogger } from "../util/logger.js";
34
34
  import { unregisterCallNotifiers } from "./conversation-notifiers.js";
35
35
  import type {
36
36
  MessageQueue,
37
+ QueuedDispatch,
38
+ QueuedMessage,
37
39
  QueueDrainReason,
38
40
  } from "./conversation-queue-manager.js";
39
41
  import { resetSkillToolProjection } from "./conversation-skill-tools.js";
@@ -131,6 +133,9 @@ export function reinjectInterruptTurnNote(
131
133
 
132
134
  export interface AbortContext {
133
135
  readonly conversationId: string;
136
+ readonly currentTurnCronRunId?: string | null;
137
+ readonly currentRequestId?: string;
138
+ readonly pendingQueuedDispatches?: Map<string | null, Set<QueuedDispatch>>;
134
139
  isProcessing(): boolean;
135
140
  setProcessing(value: boolean): void;
136
141
  abortController: AbortController | null;
@@ -269,8 +274,17 @@ function preserveQueueAcrossInterrupt(
269
274
  * suppressed for the same reason they get no queued ack: they have no client
270
275
  * row to close.
271
276
  */
272
- function discardQueueOnAbort(ctx: AbortContext): void {
273
- for (const queued of ctx.queue) {
277
+ export function discardQueueOnAbort(
278
+ ctx: AbortContext,
279
+ shouldDiscard?: (queued: QueuedMessage) => boolean,
280
+ ): void {
281
+ for (const queued of [...ctx.queue]) {
282
+ if (shouldDiscard && !shouldDiscard(queued)) {
283
+ continue;
284
+ }
285
+ if (shouldDiscard) {
286
+ ctx.queue.removeByRequestId(queued.requestId);
287
+ }
274
288
  queued.onEvent({
275
289
  type: "generation_cancelled",
276
290
  conversationId: ctx.conversationId,
@@ -287,7 +301,25 @@ function discardQueueOnAbort(ctx: AbortContext): void {
287
301
  : {}),
288
302
  });
289
303
  }
290
- ctx.queue.clear();
304
+ if (!shouldDiscard) {
305
+ ctx.queue.clear();
306
+ }
307
+ }
308
+
309
+ /** Cancel only the scheduled firing's queued continuations and active turn. */
310
+ export function abortScheduledRun(ctx: AbortContext, runId: string): void {
311
+ for (const dispatch of ctx.pendingQueuedDispatches?.get(runId) ?? []) {
312
+ dispatch.controller.abort(
313
+ createAbortReason("schedule_timeout", "scheduler", ctx.conversationId),
314
+ );
315
+ }
316
+ discardQueueOnAbort(ctx, (queued) => queued.cronRunId === runId);
317
+ if (ctx.currentTurnCronRunId === runId) {
318
+ abortConversation(
319
+ ctx,
320
+ createAbortReason("schedule_timeout", "scheduler", ctx.conversationId),
321
+ );
322
+ }
291
323
  }
292
324
 
293
325
  export function abortConversation(
@@ -301,6 +333,36 @@ export function abortConversation(
301
333
  "abortConversation:default",
302
334
  ctx.conversationId,
303
335
  );
336
+ const preservedDispatches = isUserInterruptAbort(effectiveReason)
337
+ ? new Set(
338
+ [...(ctx.pendingQueuedDispatches?.get(null) ?? [])].filter((dispatch) =>
339
+ dispatch.messages.some(
340
+ (message) =>
341
+ message.metadata?.automated !== true &&
342
+ !isSuppressedQueuedMessage(message.metadata),
343
+ ),
344
+ ),
345
+ )
346
+ : new Set<QueuedDispatch>();
347
+ if (effectiveReason.kind !== "schedule_timeout") {
348
+ for (const dispatches of ctx.pendingQueuedDispatches?.values() ?? []) {
349
+ for (const dispatch of dispatches) {
350
+ if (!preservedDispatches.has(dispatch)) {
351
+ dispatch.controller.abort(effectiveReason);
352
+ }
353
+ }
354
+ }
355
+ }
356
+ // A dequeued user prompt stays queued work until its dispatch starts the loop.
357
+ if (
358
+ [...preservedDispatches].some((dispatch) =>
359
+ dispatch.messages.some(
360
+ (message) => message.requestId === ctx.currentRequestId,
361
+ ),
362
+ )
363
+ ) {
364
+ return;
365
+ }
304
366
  const hasLiveTurn = ctx.abortController !== null;
305
367
  const wasProcessing = ctx.isProcessing();
306
368
  if (wasProcessing) {
@@ -344,10 +406,11 @@ export function abortConversation(
344
406
  ctx.setProcessing(false);
345
407
  }
346
408
 
347
- // The queue decision is independent of the processing flag: an interrupt
348
- // hands its queue to the drain, and every other abort kind is a teardown
349
- // that must take the queue with it even when the flag already reads idle.
350
- if (isUserInterruptAbort(effectiveReason)) {
409
+ // Interrupts and run-scoped timeouts preserve the remaining queue for the drain.
410
+ if (
411
+ isUserInterruptAbort(effectiveReason) ||
412
+ effectiveReason.kind === "schedule_timeout"
413
+ ) {
351
414
  // An idle conversation counts as having a live turn for drain purposes:
352
415
  // either a turn is unwinding toward its own `kickDrainQueue`, or the queue
353
416
  // is empty. Kicking a second drain here would race the first.
@@ -294,7 +294,7 @@ export async function raceWithTimeout<T>(
294
294
  ): Promise<"completed" | "timed_out"> {
295
295
  let timer: ReturnType<typeof setTimeout> | undefined;
296
296
  try {
297
- const result = await Promise.race([
297
+ return await Promise.race([
298
298
  promise.then(
299
299
  () => "completed" as const,
300
300
  () => "completed" as const,
@@ -303,7 +303,6 @@ export async function raceWithTimeout<T>(
303
303
  timer = setTimeout(() => resolve("timed_out"), timeoutMs);
304
304
  }),
305
305
  ]);
306
- return result;
307
306
  } finally {
308
307
  if (timer !== undefined) {
309
308
  clearTimeout(timer);
@@ -76,7 +76,10 @@ import type { AuthContext } from "../runtime/auth/types.js";
76
76
  import { INTERRUPTED_TURN_NOTE_TEXT } from "../util/abort-reasons.js";
77
77
  import { getLogger } from "../util/logger.js";
78
78
  import type { ConversationModeSessionCoordinator } from "./conversation-mode-session.js";
79
- import type { MessageQueue } from "./conversation-queue-manager.js";
79
+ import type {
80
+ MessageQueue,
81
+ TurnWorkOrigin,
82
+ } from "./conversation-queue-manager.js";
80
83
  import type { SlackInboundMessageMetadata } from "./handlers/shared.js";
81
84
  import type { UserMessageAttachment } from "./message-protocol.js";
82
85
  import { actorAuthorProvenance } from "./message-provenance.js";
@@ -235,6 +238,8 @@ export interface MessagingConversationContext {
235
238
  acquireProcessingFenced(): Promise<number | null>;
236
239
  releaseProcessing(owner: number): boolean;
237
240
  abortController: AbortController | null;
241
+ currentTurnCronRunId?: string | null;
242
+ currentTurnWorkOrigins?: readonly TurnWorkOrigin[];
238
243
  currentRequestId?: string;
239
244
  currentActiveSurfaceId?: string;
240
245
  readonly modeSessions?: Pick<
@@ -954,6 +959,8 @@ export function enqueueMessage(
954
959
 
955
960
  /** Shared options for `persistUserMessage` and `persistQueuedMessageBody`. */
956
961
  export interface PersistMessageOptions {
962
+ cronRunId?: string | null;
963
+ signal?: AbortSignal;
957
964
  content: string;
958
965
  attachments?: UserMessageAttachment[];
959
966
  requestId?: string;
@@ -1112,13 +1119,27 @@ export async function persistUserMessage(
1112
1119
  throw new Error("Message content or attachments are required");
1113
1120
  }
1114
1121
 
1122
+ options.signal?.throwIfAborted();
1115
1123
  const reqId = options.requestId ?? uuidv7();
1116
1124
  ctx.currentRequestId = reqId;
1117
1125
  // Recorded in the same synchronous step as the abort controller and the lock
1118
1126
  // below, so a retransmission of this very send can never find the turn armed
1119
1127
  // but unattributed and abort it.
1120
1128
  ctx.currentTurnClientMessageId = options.clientMessageId;
1121
- ctx.abortController = new AbortController();
1129
+ const controller = new AbortController();
1130
+ ctx.abortController = controller;
1131
+ ctx.currentTurnCronRunId = options.cronRunId ?? null;
1132
+ ctx.currentTurnWorkOrigins = [
1133
+ {
1134
+ sentAt:
1135
+ typeof options.metadata?.sentAt === "number"
1136
+ ? options.metadata.sentAt
1137
+ : Date.now(),
1138
+ metadata: options.metadata,
1139
+ },
1140
+ ];
1141
+ const abort = () => controller.abort(options.signal?.reason);
1142
+ options.signal?.addEventListener("abort", abort, { once: true });
1122
1143
 
1123
1144
  let owner: number | null = null;
1124
1145
  try {
@@ -1140,16 +1161,20 @@ export async function persistUserMessage(
1140
1161
  if (owner === null) {
1141
1162
  throw new Error(CONVERSATION_BUSY_MESSAGE);
1142
1163
  }
1164
+ options.signal?.throwIfAborted();
1143
1165
  const result = await persistQueuedMessageBody(ctx, {
1144
1166
  ...options,
1145
1167
  attachments,
1146
1168
  requestId: reqId,
1147
1169
  });
1170
+ options.signal?.throwIfAborted();
1148
1171
  if (result.deduplicated) {
1149
1172
  ctx.releaseProcessing(owner);
1150
1173
  ctx.abortController = null;
1151
1174
  ctx.currentRequestId = undefined;
1152
1175
  ctx.currentTurnClientMessageId = undefined;
1176
+ ctx.currentTurnCronRunId = undefined;
1177
+ ctx.currentTurnWorkOrigins = undefined;
1153
1178
  }
1154
1179
  return result;
1155
1180
  } catch (err) {
@@ -1170,7 +1195,11 @@ export async function persistUserMessage(
1170
1195
  ctx.abortController = null;
1171
1196
  ctx.currentRequestId = undefined;
1172
1197
  ctx.currentTurnClientMessageId = undefined;
1198
+ ctx.currentTurnCronRunId = undefined;
1199
+ ctx.currentTurnWorkOrigins = undefined;
1173
1200
  throw err;
1201
+ } finally {
1202
+ options.signal?.removeEventListener("abort", abort);
1174
1203
  }
1175
1204
  }
1176
1205