@vellumai/assistant 0.11.1-dev.202608032034.aebd2da → 0.11.1-dev.202608032226.351a4e2

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 (47) hide show
  1. package/openapi.yaml +1 -0
  2. package/package.json +1 -1
  3. package/src/__tests__/agent-loop-resume-interrupted.test.ts +223 -0
  4. package/src/__tests__/conversation-agent-loop.test.ts +16 -7
  5. package/src/__tests__/conversation-error.test.ts +106 -0
  6. package/src/__tests__/llm-resolver.test.ts +16 -0
  7. package/src/__tests__/provider-send-message-override-profile.test.ts +95 -0
  8. package/src/__tests__/workspace-migration-137-repair-retired-fireworks-minimax-model-id.test.ts +6 -6
  9. package/src/__tests__/workspace-migration-138-backfill-home-feed-titles.test.ts +373 -0
  10. package/src/agent/loop.ts +36 -7
  11. package/src/cli/commands/notifications.help.ts +3 -2
  12. package/src/config/llm-resolver.ts +19 -3
  13. package/src/daemon/conversation-agent-loop-handlers.ts +15 -6
  14. package/src/daemon/conversation-agent-loop.ts +31 -18
  15. package/src/daemon/conversation-error.ts +40 -24
  16. package/src/home/__tests__/feed-types.test.ts +43 -8
  17. package/src/home/__tests__/feed-writer.test.ts +59 -0
  18. package/src/home/feed-types.ts +34 -7
  19. package/src/home/feed-writer.ts +15 -6
  20. package/src/live-voice/__tests__/activity-label.test.ts +68 -0
  21. package/src/live-voice/__tests__/live-activity-reporter.test.ts +86 -5
  22. package/src/live-voice/__tests__/live-voice-agent-turn.test.ts +14 -5
  23. package/src/live-voice/activity-label.ts +106 -0
  24. package/src/live-voice/live-activity-reporter.ts +35 -6
  25. package/src/live-voice/live-voice-session.ts +58 -0
  26. package/src/live-voice/protocol.ts +23 -0
  27. package/src/notifications/__tests__/copy-composer.test.ts +53 -3
  28. package/src/notifications/__tests__/decision-engine.test.ts +150 -20
  29. package/src/notifications/__tests__/edit-notification.test.ts +330 -0
  30. package/src/notifications/__tests__/home-feed-side-effect.test.ts +170 -12
  31. package/src/notifications/copy-composer.ts +23 -3
  32. package/src/notifications/decision-engine.ts +29 -7
  33. package/src/notifications/edit-notification.ts +8 -4
  34. package/src/notifications/home-feed-side-effect.ts +43 -6
  35. package/src/notifications/notification-utils.ts +8 -2
  36. package/src/persistence/conversation-title-service.ts +5 -170
  37. package/src/providers/__tests__/dispatch-connection-routing.test.ts +43 -2
  38. package/src/providers/__tests__/vellum-mismatch-routing.test.ts +8 -0
  39. package/src/providers/call-site-routing.ts +77 -14
  40. package/src/providers/connection-resolution.ts +42 -2
  41. package/src/providers/types.ts +7 -1
  42. package/src/runtime/routes/notification-routes.ts +4 -1
  43. package/src/util/__tests__/short-title.test.ts +229 -0
  44. package/src/util/errors.ts +15 -0
  45. package/src/util/short-title.ts +189 -0
  46. package/src/workspace/migrations/138-backfill-home-feed-titles.ts +179 -0
  47. package/src/workspace/migrations/registry.ts +2 -0
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Turns a tool call into one short user-facing line for the surfaces that show
3
+ * a running voice session.
4
+ *
5
+ * ## Why the copy lives here
6
+ *
7
+ * The iOS Live Activity has two drivers that must carry identical content: the
8
+ * live-voice socket, and an APNs push the daemon dispatches when the app is
9
+ * backgrounded and the web layer is suspended. Only one of them runs web code,
10
+ * so a label composed client-side could not be reproduced by the other. Both
11
+ * are therefore handed the same string, and this is where it is made.
12
+ *
13
+ * That does not contradict the rule that phase wording belongs to the web
14
+ * layer. The reason phase copy lives there is cadence: the iOS shell ships on
15
+ * App Store review while the web bundle deploys continuously, so a native
16
+ * `switch` would fossilize. This module deploys with the daemon, i.e.
17
+ * continuously, and it is the only layer that knows a tool ran at all.
18
+ *
19
+ * ## What makes a good label
20
+ *
21
+ * It is read on a Lock Screen, in a glance, by someone who is mid-conversation
22
+ * and not looking for detail. So: a present-participle phrase, no tool names,
23
+ * no arguments, no punctuation, and short enough to survive one line. Arguments
24
+ * are deliberately absent even though {@link summarizeToolInput} could supply
25
+ * them: a path or a URL on a Lock Screen is unreadable at a glance and can
26
+ * carry content the user would not choose to show a passer-by.
27
+ */
28
+
29
+ /**
30
+ * Present-participle phrases for the built-in tools, by exact name.
31
+ *
32
+ * Grouped by what the user would say is happening, not by how the tool is
33
+ * implemented: `bash` and `host_bash` differ in where they run, which is not a
34
+ * distinction anyone glancing at a Lock Screen is making.
35
+ */
36
+ const TOOL_ACTIVITY_LABELS: Readonly<Record<string, string>> = {
37
+ bash: "Running a command",
38
+ terminal: "Running a command",
39
+ host_bash: "Running a command",
40
+ file_read: "Reading a file",
41
+ host_file_read: "Reading a file",
42
+ file_write: "Writing a file",
43
+ host_file_write: "Writing a file",
44
+ file_edit: "Editing a file",
45
+ host_file_edit: "Editing a file",
46
+ host_file_transfer: "Moving a file",
47
+ file_search: "Searching files",
48
+ web_search: "Searching the web",
49
+ web_fetch: "Reading a page",
50
+ network_request: "Making a request",
51
+ browser: "Using the browser",
52
+ computer_use: "Using the computer",
53
+ memory: "Checking memory",
54
+ schedule: "Checking the schedule",
55
+ ui_show: "Putting something on screen",
56
+ ui_update: "Putting something on screen",
57
+ };
58
+
59
+ /**
60
+ * Prefix-matched fallbacks, tried in order when a tool has no exact entry.
61
+ *
62
+ * The tool vocabulary is open: plugins, MCP servers, and skills all contribute
63
+ * names this module has never seen, and a new built-in should not have to be
64
+ * registered here to avoid a blank island. Prefixes cover the families whose
65
+ * names are structured; {@link GENERIC_ACTIVITY_LABEL} covers the rest.
66
+ */
67
+ const TOOL_ACTIVITY_LABEL_PREFIXES: ReadonlyArray<readonly [string, string]> = [
68
+ ["browser_", "Using the browser"],
69
+ ["computer_", "Using the computer"],
70
+ ["file_", "Working with files"],
71
+ ["host_file_", "Working with files"],
72
+ ["web_", "Looking something up"],
73
+ ["mcp_", "Using a connected app"],
74
+ ["skill_", "Running a skill"],
75
+ ["subagent", "Working on it"],
76
+ ];
77
+
78
+ /**
79
+ * What an unrecognized tool reads as.
80
+ *
81
+ * Deliberately vague rather than derived from the tool's name. A humanized
82
+ * `slack_conversations_history` is worse than "Working on it": it is longer
83
+ * than the slot, it leaks an internal vocabulary, and it reads like an error
84
+ * message. The label's job is to show the turn is alive and doing something,
85
+ * and this does that job for every tool that will ever exist.
86
+ */
87
+ export const GENERIC_ACTIVITY_LABEL = "Working on it";
88
+
89
+ /**
90
+ * The line to show while `toolName` runs.
91
+ *
92
+ * Total, by construction: every tool gets a label, because the alternative is
93
+ * a surface that goes blank precisely when the assistant is busiest.
94
+ */
95
+ export function activityLabelForTool(toolName: string): string {
96
+ const exact = TOOL_ACTIVITY_LABELS[toolName];
97
+ if (exact !== undefined) {
98
+ return exact;
99
+ }
100
+ for (const [prefix, label] of TOOL_ACTIVITY_LABEL_PREFIXES) {
101
+ if (toolName.startsWith(prefix)) {
102
+ return label;
103
+ }
104
+ }
105
+ return GENERIC_ACTIVITY_LABEL;
106
+ }
@@ -109,21 +109,45 @@ export function phaseForFrame(
109
109
  */
110
110
  export class LiveActivityReporter {
111
111
  private lastPhase: LiveActivityPhase | null = null;
112
+ private lastDetail = "";
112
113
  private ended = false;
113
114
 
114
115
  constructor(private readonly conversationId: string) {}
115
116
 
116
117
  /**
117
- * Report the phase a frame implies, if it changed. Fire-and-forget: callers
118
- * are on the session's send path and must not await this.
118
+ * Report what a frame implies about the phase or the activity line, if
119
+ * either changed. Fire-and-forget: callers are on the session's send path
120
+ * and must not await this.
121
+ *
122
+ * Both travel in one dispatch because they are two fields of one content
123
+ * state: ActivityKit replaces the whole thing per push, so a dispatch that
124
+ * carried only the field that moved would blank the other.
119
125
  */
120
126
  report(frame: LiveVoiceServerFramePayload): void {
127
+ if (this.ended) {
128
+ return;
129
+ }
121
130
  const phase = phaseForFrame(frame, this.lastPhase);
122
- if (phase === null || phase === this.lastPhase || this.ended) {
131
+ // The session sends this frame only on a change it wants surfaced, and
132
+ // sends an empty label when the turn stops working, so it is taken
133
+ // verbatim rather than derived.
134
+ const detail = frame.type === "activity" ? frame.label : this.lastDetail;
135
+ const phaseMoved = phase !== null && phase !== this.lastPhase;
136
+ if (!phaseMoved && detail === this.lastDetail) {
137
+ return;
138
+ }
139
+ if (phase !== null) {
140
+ this.lastPhase = phase;
141
+ }
142
+ this.lastDetail = detail;
143
+ // An activity line can arrive before any phase has been established (a
144
+ // turn whose first tool starts before the phase-bearing frame lands).
145
+ // There is no content state to attach it to yet, and the phase the next
146
+ // frame sets will carry it.
147
+ if (this.lastPhase === null) {
123
148
  return;
124
149
  }
125
- this.lastPhase = phase;
126
- void this.dispatch(phase, "update");
150
+ void this.dispatch(this.lastPhase, "update", this.lastDetail);
127
151
  }
128
152
 
129
153
  /**
@@ -139,13 +163,17 @@ export class LiveActivityReporter {
139
163
  return;
140
164
  }
141
165
  this.ended = true;
142
- void this.dispatch("ending", "end");
166
+ // No detail on the way out: whatever the turn was doing, it is not doing
167
+ // it any more, and this state is the one that lingers on the Lock Screen
168
+ // through the dismissal window.
169
+ void this.dispatch("ending", "end", "");
143
170
  }
144
171
 
145
172
  /** `protected` so a test can observe what would be sent without sending it. */
146
173
  protected async dispatch(
147
174
  phase: LiveActivityPhase,
148
175
  event: "update" | "end",
176
+ detail: string,
149
177
  ): Promise<void> {
150
178
  try {
151
179
  const client = await VellumPlatformClient.create();
@@ -162,6 +190,7 @@ export class LiveActivityReporter {
162
190
  conversation_id: this.conversationId,
163
191
  phase,
164
192
  event,
193
+ detail,
165
194
  }),
166
195
  });
167
196
  if (!response.ok) {
@@ -59,6 +59,7 @@ import { getToolOwner } from "../tools/registry.js";
59
59
  import { extractSpeakableSegments } from "../tts/speakable-segments.js";
60
60
  import { createAbortReason } from "../util/abort-reasons.js";
61
61
  import { getLogger } from "../util/logger.js";
62
+ import { activityLabelForTool } from "./activity-label.js";
62
63
  import {
63
64
  createVoiceFrontDecider,
64
65
  type VoiceFrontDecider,
@@ -481,6 +482,10 @@ interface ActiveAssistantTurn {
481
482
  // Latched when the leg's stream contains MINIMIZE_ROOM_MARKER; consumed
482
483
  // once at TTS drain, where the minimize_room frame goes out after tts_done.
483
484
  minimizeRequested: boolean;
485
+ // The activity label the client was last told about, so a run of tools that
486
+ // map to the same line sends one frame rather than one per call. Empty means
487
+ // the client believes nothing is running, which is also where a turn ends.
488
+ activityLabel: string;
484
489
  // A tts_audio frame actually went out to the client — latches on the first
485
490
  // forwarded chunk so the firstTtsAudio metric is marked exactly once per turn.
486
491
  ttsAudioStarted: boolean;
@@ -1920,6 +1925,9 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
1920
1925
  "barge_in",
1921
1926
  turn.turnId,
1922
1927
  );
1928
+ // A cancelled turn's tools are abandoned, not finished, so nothing will
1929
+ // arrive to clear the line it left behind.
1930
+ this.publishActivity(turn, "");
1923
1931
  await this.sendFrame({ type: "turn_cancelled", turnId: turn.turnId });
1924
1932
  await this.cancelAssistantTurn("barge_in");
1925
1933
  // Keep the interrupted turn's work alive on a background subagent; the
@@ -2317,6 +2325,47 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
2317
2325
  }, drainMs + this.continuationAnnounceSilenceMs);
2318
2326
  }
2319
2327
 
2328
+ /**
2329
+ * The line describing what this turn is doing right now: the newest tool
2330
+ * still running, or nothing when none is.
2331
+ *
2332
+ * Newest-first because parallel ops are the interesting case. A turn that
2333
+ * starts a search and a file read, then finishes the search, is still
2334
+ * reading a file, and a surface that went blank there would claim the turn
2335
+ * had gone idle while it plainly has not.
2336
+ */
2337
+ private currentActivityLabel(turn: ActiveAssistantTurn): string {
2338
+ for (let i = turn.progress.ops.length - 1; i >= 0; i -= 1) {
2339
+ const op = turn.progress.ops[i];
2340
+ if (op !== undefined && op.completedAtMs === undefined) {
2341
+ return activityLabelForTool(op.toolName);
2342
+ }
2343
+ }
2344
+ return "";
2345
+ }
2346
+
2347
+ /**
2348
+ * Tell the client what the turn is doing, if it changed.
2349
+ *
2350
+ * De-duplicated for the same reason the Live Activity reporter de-duplicates
2351
+ * phases: this frame reaches ActivityKit, whose update budget is finite and
2352
+ * whose overflow is dropped silently, and a turn that runs four file reads in
2353
+ * a row would otherwise spend that budget restating one line.
2354
+ *
2355
+ * Fire-and-forget. An activity label is a flourish, and nothing about the
2356
+ * conversation may wait on one.
2357
+ */
2358
+ private publishActivity(turn: ActiveAssistantTurn, label: string): void {
2359
+ if (turn.activityLabel === label) {
2360
+ return;
2361
+ }
2362
+ turn.activityLabel = label;
2363
+ void this.sendFrame(
2364
+ { type: "activity", turnId: turn.turnId, label },
2365
+ () => !this.isClosed,
2366
+ );
2367
+ }
2368
+
2320
2369
  private clearActiveAssistantTurn(token: symbol): void {
2321
2370
  if (this.activeAssistantTurn?.token !== token) {
2322
2371
  return;
@@ -3409,6 +3458,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
3409
3458
  assistantCompleted: false,
3410
3459
  ttsDone: false,
3411
3460
  minimizeRequested: false,
3461
+ activityLabel: "",
3412
3462
  ttsAudioStarted: false,
3413
3463
  finalized: false,
3414
3464
  speculativePending: opts?.speculative === true,
@@ -3835,6 +3885,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
3835
3885
  });
3836
3886
  current.progress.opsSinceNarration += 1;
3837
3887
  current.progress.stateEpoch += 1;
3888
+ this.publishActivity(current, this.currentActivityLabel(current));
3838
3889
  log.debug({ turnId, toolName }, "Live voice turn started tool use");
3839
3890
  // Definitive tool use means the turn is guaranteed slow: speak
3840
3891
  // the floor-holding ack now instead of waiting out the
@@ -3888,6 +3939,7 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
3888
3939
  }
3889
3940
  }
3890
3941
  current.progress.stateEpoch += 1;
3942
+ this.publishActivity(current, this.currentActivityLabel(current));
3891
3943
  this.maybeNarrateProgress(current, trigger);
3892
3944
  },
3893
3945
  },
@@ -4569,6 +4621,12 @@ export class LiveVoiceSession implements LiveVoiceSessionContract {
4569
4621
  !this.isClosed,
4570
4622
  );
4571
4623
 
4624
+ // The turn is over, so nothing is running. Ordinarily the line is
4625
+ // already clear (the last tool_result cleared it); this is the net
4626
+ // for a turn that ends with an op still open, which would otherwise
4627
+ // leave the last tool it touched on screen through the next silence.
4628
+ this.publishActivity(currentTurn, "");
4629
+
4572
4630
  // Drain-scoped minimize: the latched marker is consumed here, after
4573
4631
  // the turn's speech has fully drained — never mid-speech, never for
4574
4632
  // a barged-in turn, at most once per turn.
@@ -18,6 +18,7 @@ const _LIVE_VOICE_SERVER_FRAME_TYPES = [
18
18
  "stt_partial",
19
19
  "stt_final",
20
20
  "thinking",
21
+ "activity",
21
22
  "assistant_text_delta",
22
23
  "tts_audio",
23
24
  "tts_done",
@@ -217,6 +218,26 @@ export interface LiveVoiceThinkingServerFrame extends LiveVoiceServerFrameBase {
217
218
  readonly turnId: string;
218
219
  }
219
220
 
221
+ /**
222
+ * What the assistant is doing inside a turn, as one short user-facing line.
223
+ *
224
+ * Exists because a live-voice turn can go silent for a long time while it
225
+ * works, and the surfaces that show the session (the iOS Live Activity, and
226
+ * the room) can otherwise only say "Thinking...". The label is composed here
227
+ * rather than by each surface for the same reason phase wording is composed
228
+ * once: the Live Activity has two independent drivers (this socket and an APNs
229
+ * push the daemon dispatches), they must carry identical content, and the only
230
+ * way to guarantee that is for both to be handed the same string.
231
+ *
232
+ * An empty `label` means "no current activity", which is what a turn's end
233
+ * sends. Emitted only on change, never per tool result.
234
+ */
235
+ export interface LiveVoiceActivityServerFrame extends LiveVoiceServerFrameBase {
236
+ readonly type: "activity";
237
+ readonly turnId: string;
238
+ readonly label: string;
239
+ }
240
+
220
241
  export interface LiveVoiceAssistantTextDeltaServerFrame extends LiveVoiceServerFrameBase {
221
242
  readonly type: "assistant_text_delta";
222
243
  readonly text: string;
@@ -321,6 +342,7 @@ export type LiveVoiceServerFrame =
321
342
  | LiveVoiceSttPartialServerFrame
322
343
  | LiveVoiceSttFinalServerFrame
323
344
  | LiveVoiceThinkingServerFrame
345
+ | LiveVoiceActivityServerFrame
324
346
  | LiveVoiceAssistantTextDeltaServerFrame
325
347
  | LiveVoiceTtsAudioServerFrame
326
348
  | LiveVoiceTtsDoneServerFrame
@@ -341,6 +363,7 @@ export type LiveVoiceServerFramePayload =
341
363
  | WithoutSeq<LiveVoiceSttPartialServerFrame>
342
364
  | WithoutSeq<LiveVoiceSttFinalServerFrame>
343
365
  | WithoutSeq<LiveVoiceThinkingServerFrame>
366
+ | WithoutSeq<LiveVoiceActivityServerFrame>
344
367
  | WithoutSeq<LiveVoiceAssistantTextDeltaServerFrame>
345
368
  | WithoutSeq<LiveVoiceTtsAudioServerFrame>
346
369
  | WithoutSeq<LiveVoiceTtsDoneServerFrame>
@@ -1,7 +1,8 @@
1
1
  /**
2
- * Tests for the notification copy-composer — specifically the fallback
3
- * path that composeFallbackCopy uses when the LLM is unavailable, and
4
- * the shared deriveTitle utility.
2
+ * Tests for the notification copy-composer: the fallback path that
3
+ * composeFallbackCopy uses when the LLM is unavailable, the normalization
4
+ * it applies to producer-supplied titles, and the shared deriveTitle
5
+ * utility.
5
6
  */
6
7
 
7
8
  import { describe, expect, test } from "bun:test";
@@ -190,6 +191,55 @@ describe("composeFallbackCopy honors requestedMessage / requestedTitle", () => {
190
191
  expect(copy.vellum?.title).toBe("User Title");
191
192
  });
192
193
 
194
+ test("strips markdown and quotes from a producer-supplied title", () => {
195
+ const signal = makeSignal({
196
+ contextPayload: {
197
+ requestedMessage: "The deploy finished cleanly.",
198
+ requestedTitle: '"**Deploy** finished"',
199
+ },
200
+ });
201
+ const copy = composeFallbackCopy(signal, CHANNELS);
202
+
203
+ expect(copy.vellum?.title).toBe("Deploy finished");
204
+ });
205
+
206
+ test("derives the title when requestedTitle reads as leaked prose", () => {
207
+ const signal = makeSignal({
208
+ contextPayload: {
209
+ requestedMessage: "Backup finished. Nothing needs your attention.",
210
+ requestedTitle: "I need to generate a title for this notification",
211
+ },
212
+ });
213
+ const copy = composeFallbackCopy(signal, CHANNELS);
214
+
215
+ expect(copy.vellum?.title).toBe("Backup finished.");
216
+ });
217
+
218
+ test("derives the title when requestedTitle spans multiple lines", () => {
219
+ const signal = makeSignal({
220
+ contextPayload: {
221
+ requestedMessage: "The nightly job is done.",
222
+ requestedTitle: "Nightly job\nsecond line",
223
+ },
224
+ });
225
+ const copy = composeFallbackCopy(signal, CHANNELS);
226
+
227
+ expect(copy.vellum?.title).toBe("The nightly job is done.");
228
+ });
229
+
230
+ test("truncates an over-long requestedTitle to the shared title budget", () => {
231
+ const signal = makeSignal({
232
+ contextPayload: {
233
+ requestedMessage: "Body text",
234
+ requestedTitle:
235
+ "Alpha bravo charlie delta echo foxtrot golf hotel india juliett",
236
+ },
237
+ });
238
+ const copy = composeFallbackCopy(signal, CHANNELS);
239
+
240
+ expect(copy.vellum?.title).toBe("Alpha bravo charlie delta echo");
241
+ });
242
+
193
243
  test("works with non-assistant_tool source channels", () => {
194
244
  for (const sourceChannel of ["scheduler", "watcher", "slack"] as const) {
195
245
  const signal = makeSignal({
@@ -55,25 +55,31 @@ mock.module("../../contacts/contact-store.js", () => ({
55
55
  // Provider mock. By default `sendMessage` throws so the pass-through paths
56
56
  // (which must skip the LLM) fail loudly if they reach the provider. LLM-path
57
57
  // tests override `providerSendMessage` to capture inputs.
58
+ type ProviderSendOptions = { systemPrompt?: string; tools?: unknown[] };
59
+
58
60
  let providerSendMessage: (
59
61
  messages: unknown[],
60
- opts: { systemPrompt?: string },
62
+ opts: ProviderSendOptions,
61
63
  ) => Promise<unknown> = () => {
62
64
  throw new Error(
63
65
  "provider.sendMessage should NOT be invoked for pass-through decisions",
64
66
  );
65
67
  };
66
68
 
69
+ // Tool block the engine reads back from a provider response. Null drives the
70
+ // deterministic fallback, so LLM-path tests set it before calling in.
71
+ let toolUseBlock: { input: Record<string, unknown> } | null = null;
72
+
67
73
  mock.module("../../providers/provider-send-message.js", () => ({
68
74
  getConfiguredProvider: async () => ({
69
- sendMessage: (messages: unknown[], opts: { systemPrompt?: string }) =>
75
+ sendMessage: (messages: unknown[], opts: ProviderSendOptions) =>
70
76
  providerSendMessage(messages, opts),
71
77
  }),
72
78
  createTimeout: () => ({
73
79
  signal: new AbortController().signal,
74
80
  cleanup: () => {},
75
81
  }),
76
- extractToolUse: () => null,
82
+ extractToolUse: () => toolUseBlock,
77
83
  userMessage: (text: string) => ({ role: "user", content: text }),
78
84
  }));
79
85
 
@@ -131,6 +137,24 @@ function makeAssistantReplySignal(
131
137
  };
132
138
  }
133
139
 
140
+ /** A signal with no verbatim copy, so the engine takes the LLM path. */
141
+ function makeLlmSignal(): NotificationSignal {
142
+ return {
143
+ signalId: "sig-llm-1",
144
+ createdAt: Date.now(),
145
+ sourceChannel: "scheduler",
146
+ sourceContextId: "schedule-1",
147
+ sourceEventName: "schedule.notify",
148
+ contextPayload: {},
149
+ attentionHints: {
150
+ requiresAction: false,
151
+ urgency: "low",
152
+ isAsyncBackground: false,
153
+ visibleInSourceNow: false,
154
+ },
155
+ };
156
+ }
157
+
134
158
  // ── Tests ─────────────────────────────────────────────────────────────
135
159
 
136
160
  describe("assistant_tool pass-through in notification decision engine", () => {
@@ -485,23 +509,6 @@ describe("chat.assistant_reply pass-through in notification decision engine", ()
485
509
  });
486
510
 
487
511
  describe("recipient notes injection (ACL from gateway, notes joined locally)", () => {
488
- function makeLlmSignal(): NotificationSignal {
489
- return {
490
- signalId: "sig-llm-notes-1",
491
- createdAt: Date.now(),
492
- sourceChannel: "scheduler",
493
- sourceContextId: "schedule-1",
494
- sourceEventName: "schedule.notify",
495
- contextPayload: {},
496
- attentionHints: {
497
- requiresAction: false,
498
- urgency: "low",
499
- isAsyncBackground: false,
500
- visibleInSourceNow: false,
501
- },
502
- };
503
- }
504
-
505
512
  test("injects the guardian's local notes, resolved via the gateway contactId", async () => {
506
513
  guardianDeliveryFixture = [{ contactId: "contact-42" }];
507
514
  contactInfoFixture = { "contact-42": { notes: "Prefers terse updates." } };
@@ -533,3 +540,126 @@ describe("recipient notes injection (ACL from gateway, notes joined locally)", (
533
540
  expect(capturedSystemPrompt).not.toContain("<recipient-context>");
534
541
  });
535
542
  });
543
+
544
+ describe("decision tool title field specification", () => {
545
+ test("pins the length, form, and no-echo constraints in the tool schema", async () => {
546
+ guardianDeliveryFixture = [];
547
+ contactInfoFixture = {};
548
+
549
+ let capturedTools: unknown[] | undefined;
550
+ providerSendMessage = async (_messages, opts) => {
551
+ capturedTools = opts.tools;
552
+ return {};
553
+ };
554
+
555
+ await evaluateSignal(makeLlmSignal(), ["vellum"] as NotificationChannel[]);
556
+
557
+ const tool = capturedTools?.[0] as {
558
+ input_schema: {
559
+ properties: {
560
+ renderedCopy: {
561
+ properties: Record<
562
+ string,
563
+ { properties: { title: { description: string } } }
564
+ >;
565
+ };
566
+ };
567
+ };
568
+ };
569
+ const description =
570
+ tool.input_schema.properties.renderedCopy.properties.vellum.properties
571
+ .title.description;
572
+
573
+ expect(description).toContain("2 to 5 words");
574
+ expect(description).toContain("40 characters");
575
+ expect(description).toContain("noun phrase");
576
+ expect(description).toContain(
577
+ "Do NOT restate, summarize, or echo the body",
578
+ );
579
+ expect(description).toContain("no markdown");
580
+ expect(description).toContain("Missing Context");
581
+ expect(description.match(/NOT '/g)?.length ?? 0).toBeGreaterThanOrEqual(2);
582
+ });
583
+ });
584
+
585
+ describe("title normalization", () => {
586
+ /** Run the LLM path with the given channel copy and return the kept title. */
587
+ async function titleFromModelCopy(
588
+ title: string,
589
+ body: string,
590
+ ): Promise<string | undefined> {
591
+ guardianDeliveryFixture = [];
592
+ contactInfoFixture = {};
593
+ const previousSendMessage = providerSendMessage;
594
+ providerSendMessage = async () => ({});
595
+ toolUseBlock = {
596
+ input: {
597
+ shouldNotify: true,
598
+ selectedChannels: ["vellum"],
599
+ reasoningSummary: "model decision",
600
+ dedupeKey: "title-normalization-test",
601
+ renderedCopy: { vellum: { title, body } },
602
+ },
603
+ };
604
+
605
+ try {
606
+ const decision = await evaluateSignal(makeLlmSignal(), [
607
+ "vellum",
608
+ ] as NotificationChannel[]);
609
+ return decision.renderedCopy.vellum?.title;
610
+ } finally {
611
+ toolUseBlock = null;
612
+ providerSendMessage = previousSendMessage;
613
+ }
614
+ }
615
+
616
+ test("replaces a model title that restates the body with a derived one", async () => {
617
+ const title = "The staging deploy finished and the build is live.";
618
+ const body = `Deploy complete. ${title}`;
619
+
620
+ expect(await titleFromModelCopy(title, body)).toBe("Deploy complete.");
621
+ });
622
+
623
+ test("keeps a clean model title verbatim", async () => {
624
+ expect(
625
+ await titleFromModelCopy(
626
+ "Staging Deploy Status",
627
+ "The staging deploy finished.",
628
+ ),
629
+ ).toBe("Staging Deploy Status");
630
+ });
631
+
632
+ test("truncates a model title longer than 40 characters", async () => {
633
+ const kept = await titleFromModelCopy(
634
+ "Quarterly Infrastructure Migration Status Report",
635
+ "The migration is on track for the quarter.",
636
+ );
637
+
638
+ expect(kept).toBe("Quarterly Infrastructure Migration");
639
+ expect(kept?.length).toBeLessThanOrEqual(40);
640
+ });
641
+
642
+ test("strips markdown from a model title", async () => {
643
+ expect(
644
+ await titleFromModelCopy(
645
+ "**Deploy Status**",
646
+ "The staging deploy finished.",
647
+ ),
648
+ ).toBe("Deploy Status");
649
+ });
650
+
651
+ test("replaces a pass-through requestedTitle that stutters against the body", async () => {
652
+ const requestedTitle = "The nightly backup finished without any errors.";
653
+ const signal = makeAssistantToolSignal({
654
+ contextPayload: {
655
+ requestedMessage: `Backup finished. ${requestedTitle}`,
656
+ requestedTitle,
657
+ },
658
+ });
659
+ const decision = await evaluateSignal(signal, [
660
+ "vellum",
661
+ ] as NotificationChannel[]);
662
+
663
+ expect(decision.renderedCopy.vellum?.title).toBe("Backup finished.");
664
+ });
665
+ });