@vellumai/assistant 0.9.0-dev.202606171623.2899a34 → 0.9.0-dev.202606171903.06eea08

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.
package/openapi.yaml CHANGED
@@ -17918,7 +17918,11 @@ paths:
17918
17918
  - vellum
17919
17919
  - phone
17920
17920
  - telegram
17921
+ - whatsapp
17921
17922
  - slack
17923
+ - email
17924
+ - platform
17925
+ - a2a
17922
17926
  - scheduler
17923
17927
  - watcher
17924
17928
  sourceContextId:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.9.0-dev.202606171623.2899a34",
3
+ "version": "0.9.0-dev.202606171903.06eea08",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -552,3 +552,104 @@ describe("loadFromDb history repair", () => {
552
552
  ]);
553
553
  });
554
554
  });
555
+
556
+ describe("loadFromDb turn-count rehydration", () => {
557
+ beforeEach(() => {
558
+ nextMockMessageId = 1;
559
+ mockConversation = {
560
+ id: "conv-1",
561
+ contextSummary: null,
562
+ contextCompactedMessageCount: 0,
563
+ totalInputTokens: 0,
564
+ totalOutputTokens: 0,
565
+ totalEstimatedCost: 0,
566
+ };
567
+ });
568
+
569
+ const userText = (text: string) => ({
570
+ role: "user",
571
+ content: JSON.stringify([{ type: "text", text }]),
572
+ });
573
+ const assistantText = (text: string) => ({
574
+ role: "assistant",
575
+ content: JSON.stringify([{ type: "text", text }]),
576
+ });
577
+ const assistantToolUse = (id: string) => ({
578
+ role: "assistant",
579
+ content: JSON.stringify([
580
+ { type: "tool_use", id, name: "bash", input: { cmd: "ls" } },
581
+ ]),
582
+ });
583
+ const toolResult = (id: string) => ({
584
+ role: "user",
585
+ content: JSON.stringify([
586
+ { type: "tool_result", tool_use_id: id, content: "ok" },
587
+ ]),
588
+ });
589
+ const withIds = (msgs: Array<{ role: string; content: string }>) =>
590
+ msgs.map((m, i) => ({ id: `m${i}`, ...m }));
591
+
592
+ test("restores turnCount from persisted history rather than resetting to 0", async () => {
593
+ // Three completed human turns persisted before this conversation object
594
+ // was (re)created — e.g. after an idle eviction or daemon restart.
595
+ mockDbMessages = withIds([
596
+ userText("Hello"),
597
+ assistantText("Hi"),
598
+ userText("How are you?"),
599
+ assistantText("Good"),
600
+ userText("Bye"),
601
+ assistantText("Later"),
602
+ ]);
603
+
604
+ const conversation = makeConversation();
605
+ // Fresh object starts at 0 (the bug: it would stay 0 after reload).
606
+ expect(conversation.turnCount).toBe(0);
607
+
608
+ await conversation.loadFromDb();
609
+
610
+ expect(conversation.turnCount).toBe(3);
611
+ });
612
+
613
+ test("counts a multi-iteration tool-use turn as a single turn", async () => {
614
+ // One real user message; the tool_result user messages are continuations
615
+ // within the same turn, not new turns.
616
+ mockDbMessages = withIds([
617
+ userText("convert the voice memo"),
618
+ assistantToolUse("tu_1"),
619
+ toolResult("tu_1"),
620
+ assistantToolUse("tu_2"),
621
+ toolResult("tu_2"),
622
+ assistantText("done"),
623
+ ]);
624
+
625
+ const conversation = makeConversation();
626
+ await conversation.loadFromDb();
627
+
628
+ expect(conversation.turnCount).toBe(1);
629
+ });
630
+
631
+ test("counts only real user turns when tool iterations are interleaved", async () => {
632
+ mockDbMessages = withIds([
633
+ userText("q1"),
634
+ assistantToolUse("tu_1"),
635
+ toolResult("tu_1"),
636
+ assistantText("a1"),
637
+ userText("q2"),
638
+ assistantText("a2"),
639
+ ]);
640
+
641
+ const conversation = makeConversation();
642
+ await conversation.loadFromDb();
643
+
644
+ expect(conversation.turnCount).toBe(2);
645
+ });
646
+
647
+ test("empty history yields turnCount 0", async () => {
648
+ mockDbMessages = [];
649
+
650
+ const conversation = makeConversation();
651
+ await conversation.loadFromDb();
652
+
653
+ expect(conversation.turnCount).toBe(0);
654
+ });
655
+ });
@@ -151,6 +151,57 @@ describe("ui_show dynamic_page app substitute guard", () => {
151
151
  expect(proxied).toBe(false);
152
152
  });
153
153
 
154
+ test("redirects a weak open model to a declarative surface, not 'resend HTML'", async () => {
155
+ let proxied = false;
156
+
157
+ const result = await uiShowTool.execute(
158
+ {
159
+ surface_type: "dynamic_page",
160
+ title: "Fable 5 vs MiniMax M3",
161
+ data: {},
162
+ },
163
+ {
164
+ conversationId: "conversation-123",
165
+ workingDir: "/tmp",
166
+ trustClass: "guardian",
167
+ attribution: {
168
+ resolvedModel: "accounts/fireworks/models/minimax-m3",
169
+ } as never,
170
+ proxyToolResolver: async () => {
171
+ proxied = true;
172
+ return { content: "proxied", isError: false };
173
+ },
174
+ },
175
+ );
176
+
177
+ expect(result.isError).toBe(true);
178
+ expect(result.content).toContain('surface_type: "table"');
179
+ expect(result.content).toContain("work_result");
180
+ expect(result.content).not.toContain("Resend ui_show with the full HTML");
181
+ expect(proxied).toBe(false);
182
+ });
183
+
184
+ test("keeps the resend-HTML hint for a capable model", async () => {
185
+ const result = await uiShowTool.execute(
186
+ {
187
+ surface_type: "dynamic_page",
188
+ title: "Fable 5 vs MiniMax M3",
189
+ data: {},
190
+ },
191
+ {
192
+ conversationId: "conversation-123",
193
+ workingDir: "/tmp",
194
+ trustClass: "guardian",
195
+ attribution: { resolvedModel: "claude-opus-4-8" } as never,
196
+ proxyToolResolver: async () => ({ content: "proxied", isError: false }),
197
+ },
198
+ );
199
+
200
+ expect(result.isError).toBe(true);
201
+ expect(result.content).toContain("Resend ui_show with the full HTML");
202
+ expect(result.content).not.toContain('surface_type: "table"');
203
+ });
204
+
154
205
  test("rejects dynamic_page with whitespace-only html and does not proxy", async () => {
155
206
  let proxied = false;
156
207
 
@@ -104,7 +104,7 @@ function currentResponse(toolUseId: string): ToolResultContent {
104
104
  };
105
105
  }
106
106
 
107
- /** A weak-model id that matches WEAK_MODEL_PATTERN (the gated population). */
107
+ /** A weak-model id that matches WEAK_OPEN_MODEL_PATTERN (the gated population). */
108
108
  const WEAK_MODEL = "minimax/minimax-m3";
109
109
 
110
110
  function makeCtx(
@@ -0,0 +1,29 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import { isWeakOpenModel } from "../providers/weak-open-model.js";
4
+
5
+ describe("isWeakOpenModel", () => {
6
+ test("matches weak open models across provider naming conventions", () => {
7
+ for (const model of [
8
+ "accounts/fireworks/models/minimax-m3",
9
+ "minimax/minimax-m3",
10
+ "moonshotai/kimi-k2.6",
11
+ "accounts/fireworks/models/kimi-k2p6",
12
+ "deepseek/deepseek-chat",
13
+ ]) {
14
+ expect(isWeakOpenModel(model)).toBe(true);
15
+ }
16
+ });
17
+
18
+ test("does not match capable models", () => {
19
+ for (const model of ["claude-opus-4-8", "claude-sonnet-4-6", "gpt-5.5"]) {
20
+ expect(isWeakOpenModel(model)).toBe(false);
21
+ }
22
+ });
23
+
24
+ test("is false for null/undefined/empty", () => {
25
+ expect(isWeakOpenModel(null)).toBe(false);
26
+ expect(isWeakOpenModel(undefined)).toBe(false);
27
+ expect(isWeakOpenModel("")).toBe(false);
28
+ });
29
+ });
@@ -23,7 +23,7 @@ const log = getLogger("conversation-history");
23
23
 
24
24
  // ── Helpers ──────────────────────────────────────────────────────────
25
25
 
26
- function isToolResultBlock(
26
+ export function isToolResultBlock(
27
27
  block: ContentBlock | Record<string, unknown>,
28
28
  ): boolean {
29
29
  return (
@@ -107,7 +107,7 @@ import {
107
107
  runAgentLoopImpl,
108
108
  } from "./conversation-agent-loop.js";
109
109
  import type { HistoryConversationContext } from "./conversation-history.js";
110
- import { undo as undoImpl } from "./conversation-history.js";
110
+ import { isToolResultBlock, undo as undoImpl } from "./conversation-history.js";
111
111
  import {
112
112
  abortConversation,
113
113
  disposeConversation,
@@ -175,6 +175,36 @@ import { TraceEmitter } from "./trace-emitter.js";
175
175
 
176
176
  const log = getLogger("conversation");
177
177
 
178
+ /**
179
+ * Whether a persisted message starts a new conversation turn. A turn is
180
+ * delimited by a "real" user message; a user message whose content is entirely
181
+ * tool_result blocks is a continuation within the current turn, and assistant
182
+ * messages never start one. Mirrors the turn-boundary definition used by
183
+ * `getAssistantMessageIdsInTurn`/`getTurnTimeBounds` and the agent loop's
184
+ * per-turn `turnCount++`, so counting these reconstructs `turnCount` on load.
185
+ */
186
+ function startsNewTurn(role: string, content: string): boolean {
187
+ if (role !== "user") return false;
188
+ try {
189
+ const parsed = JSON.parse(content);
190
+ if (
191
+ Array.isArray(parsed) &&
192
+ parsed.length > 0 &&
193
+ parsed.every(
194
+ (block: unknown) =>
195
+ block != null &&
196
+ typeof block === "object" &&
197
+ isToolResultBlock(block as Record<string, unknown>),
198
+ )
199
+ ) {
200
+ return false;
201
+ }
202
+ } catch {
203
+ // Non-JSON content is a plain user message — a turn boundary.
204
+ }
205
+ return true;
206
+ }
207
+
178
208
  export interface CleanResult {
179
209
  previousEstimatedInputTokens: number;
180
210
  estimatedInputTokens: number;
@@ -829,6 +859,20 @@ export class Conversation {
829
859
  ? filterMessagesForUntrustedActor(allDbMessages)
830
860
  : allDbMessages;
831
861
 
862
+ // Rehydrate the in-memory turn counter from persisted history. `turnCount`
863
+ // is otherwise a fresh-zero field, so a reloaded conversation (eviction,
864
+ // restart, fork) would restart its turn numbering at 0 and the next turn
865
+ // would reuse `turnIndex` 0 — colliding with the conversation's first turn.
866
+ // The memory-v3 selector memoizes per (conversationId, turnIndex) for the
867
+ // life of the daemon process, so a collided turnIndex serves a stale
868
+ // selection and skips retrieval. One turn per real (turn-starting) user
869
+ // message, matching the agent loop's per-turn `turnCount++`. Counted from
870
+ // the full unsliced history so it survives compaction and is independent of
871
+ // the viewer's trust class.
872
+ this.turnCount = allDbMessages.filter((m) =>
873
+ startsNewTurn(m.role, m.content),
874
+ ).length;
875
+
832
876
  const conv = getConversation(this.conversationId);
833
877
  this.conversationType = conv?.conversationType ?? undefined;
834
878
  this.originInterface = parseInterfaceId(conv?.originInterface) ?? undefined;
@@ -83,11 +83,15 @@ function resolveApprovalContext(
83
83
  // Extract tool context so channel adapters can render structured
84
84
  // approval cards without re-parsing contextPayload.
85
85
  let toolName: string | undefined;
86
+ let riskLevel: string | undefined;
87
+ let commandPreview: string | undefined;
86
88
  if (
87
89
  parsed.requestKind === "tool_approval" ||
88
90
  parsed.requestKind === "tool_grant_request"
89
91
  ) {
90
92
  toolName = nonEmpty(parsed.toolName);
93
+ riskLevel = nonEmpty(parsed.riskLevel);
94
+ commandPreview = nonEmpty(parsed.commandPreview);
91
95
  } else if (parsed.requestKind === "pending_question") {
92
96
  toolName = nonEmpty(parsed.toolName);
93
97
  }
@@ -99,8 +103,8 @@ function resolveApprovalContext(
99
103
  permissionDetails: toolName
100
104
  ? {
101
105
  toolName,
102
- riskLevel: "medium",
103
- toolInput: {},
106
+ riskLevel: riskLevel ?? "medium",
107
+ toolInput: commandPreview ? { _summary: commandPreview } : {},
104
108
  requesterIdentifier: nonEmpty(parsed.requesterIdentifier),
105
109
  }
106
110
  : undefined,
@@ -82,11 +82,19 @@ export const ToolApprovalPayloadSchema =
82
82
  GuardianQuestionPayloadBaseSchema.extend({
83
83
  requestKind: z.literal("tool_approval"),
84
84
  toolName: z.string().min(1),
85
+ /** Risk classification from the permission checker (e.g. "low", "medium", "high"). */
86
+ riskLevel: z.string().optional(),
87
+ /** Secret-redacted summary of the tool invocation arguments. */
88
+ commandPreview: z.string().optional(),
85
89
  });
86
90
 
87
91
  export const ToolGrantPayloadSchema = GuardianQuestionPayloadBaseSchema.extend({
88
92
  requestKind: z.literal("tool_grant_request"),
89
93
  toolName: z.string().min(1),
94
+ /** Risk classification from the permission checker (e.g. "low", "medium", "high"). */
95
+ riskLevel: z.string().optional(),
96
+ /** Secret-redacted summary of the tool invocation arguments. */
97
+ commandPreview: z.string().optional(),
90
98
  });
91
99
 
92
100
  export const AccessRequestGuardianPayloadSchema =
@@ -124,6 +132,8 @@ export const LenientToolApprovalPayloadSchema = z.object({
124
132
  requesterIdentifier: z.string().nullable().optional(),
125
133
  requesterExternalUserId: z.string().nullable().optional(),
126
134
  requesterChatId: z.string().nullable().optional(),
135
+ riskLevel: z.string().nullable().optional(),
136
+ commandPreview: z.string().nullable().optional(),
127
137
  });
128
138
 
129
139
  export type LenientToolApprovalPayload = z.infer<
@@ -19,7 +19,11 @@ export const NOTIFICATION_SOURCE_CHANNELS = [
19
19
  { id: "vellum", description: "Vellum native client (macOS/iOS)" },
20
20
  { id: "phone", description: "Phone call pipeline" },
21
21
  { id: "telegram", description: "Telegram channel" },
22
+ { id: "whatsapp", description: "WhatsApp channel" },
22
23
  { id: "slack", description: "Slack channel" },
24
+ { id: "email", description: "Email channel" },
25
+ { id: "platform", description: "Platform-managed channel" },
26
+ { id: "a2a", description: "Agent-to-agent protocol channel" },
23
27
  { id: "scheduler", description: "Scheduled task runner (reminders, cron)" },
24
28
  { id: "watcher", description: "File/event watcher subsystem" },
25
29
  ] as const;
@@ -48,6 +48,7 @@
48
48
  import type { PluginHookFn, PostToolUseContext } from "@vellumai/plugin-api";
49
49
 
50
50
  import type { ContentBlock, Message } from "../../../../providers/types.js";
51
+ import { isWeakOpenModel } from "../../../../providers/weak-open-model.js";
51
52
 
52
53
  /**
53
54
  * Canonical nudge notice. Module-level constant so tests and wrapping plugins
@@ -66,17 +67,6 @@ export const TASK_PROGRESS_NUDGE_TEXT =
66
67
  */
67
68
  export const TASK_PROGRESS_NUDGE_ROUND_THRESHOLD = 3;
68
69
 
69
- /**
70
- * Weaker open models that disregard the static progress-card instruction and
71
- * so get the mid-turn nudge: Kimi, DeepSeek, and MiniMax. Family-level matching
72
- * spans provider naming conventions (OpenRouter `moonshotai/kimi-k2.6`,
73
- * `deepseek/deepseek-chat`, `minimax/minimax-m3`; Fireworks
74
- * `accounts/fireworks/models/minimax-m3`, `kimi-k2p6`). Extend as other models
75
- * show the same gap. Capable models (Claude, GPT) follow the prompt and are
76
- * intentionally excluded.
77
- */
78
- const WEAK_MODEL_PATTERN = /kimi|deepseek|minimax/i;
79
-
80
70
  /**
81
71
  * Round count at the last nudge, per conversation. A non-zero entry means the
82
72
  * turn has already been nudged; it resets when the round count drops below the
@@ -145,7 +135,7 @@ function scanTurn(messages: ReadonlyArray<Message>): {
145
135
  }
146
136
 
147
137
  const postToolUse: PluginHookFn<PostToolUseContext> = async (ctx) => {
148
- if (!WEAK_MODEL_PATTERN.test(ctx.model)) return;
138
+ if (!isWeakOpenModel(ctx.model)) return;
149
139
 
150
140
  const { rounds, taskProgressShown } = scanTurn(ctx.messages);
151
141
 
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Family-level classification of "weak open models" — open-weight models
3
+ * (Kimi, DeepSeek, MiniMax) that disregard static instructions and have
4
+ * capability gaps that capable models (Claude, GPT) do not. Used by harness
5
+ * levers that coach or redirect these models without touching capable-model
6
+ * behavior: the task-progress-nudge plugin and the empty-dynamic_page surface
7
+ * redirect.
8
+ *
9
+ * Family-level matching spans provider naming conventions: OpenRouter
10
+ * `moonshotai/kimi-k2.6`, `deepseek/deepseek-chat`, `minimax/minimax-m3`;
11
+ * Fireworks `accounts/fireworks/models/minimax-m3`, `kimi-k2p6`. Extend the
12
+ * pattern as other open models show the same gaps.
13
+ *
14
+ * Distinct from exploration-drift's narrower `LOOP_PRONE_MODEL_PATTERN`, which
15
+ * targets specific loop-prone versions rather than the whole capability family.
16
+ */
17
+ export const WEAK_OPEN_MODEL_PATTERN = /kimi|deepseek|minimax/i;
18
+
19
+ /** True when `model` is a weak open model (see {@link WEAK_OPEN_MODEL_PATTERN}). */
20
+ export function isWeakOpenModel(model: string | null | undefined): boolean {
21
+ return typeof model === "string" && WEAK_OPEN_MODEL_PATTERN.test(model);
22
+ }
@@ -244,6 +244,55 @@ const recordRequestLogCalls: Array<{
244
244
  provider?: string;
245
245
  callSite?: string;
246
246
  }> = [];
247
+ const recordUsageCalls: Array<{
248
+ conversationId: string;
249
+ inputTokens: number;
250
+ outputTokens: number;
251
+ model: string;
252
+ actor: string;
253
+ cacheCreationInputTokens: number;
254
+ cacheReadInputTokens: number;
255
+ callSite: unknown;
256
+ overrideProfile: unknown;
257
+ forceOverrideProfile: unknown;
258
+ selectionSeed: unknown;
259
+ }> = [];
260
+ mock.module("../../daemon/conversation-usage.js", () => ({
261
+ recordUsage: (
262
+ ctx: { conversationId: string },
263
+ inputTokens: number,
264
+ outputTokens: number,
265
+ model: string,
266
+ _onEvent: unknown,
267
+ actor: string,
268
+ _requestId: unknown,
269
+ cacheCreationInputTokens = 0,
270
+ cacheReadInputTokens = 0,
271
+ _rawResponse?: unknown,
272
+ _llmCallCount?: number,
273
+ _contextWindow?: unknown,
274
+ attribution?: {
275
+ callSite?: unknown;
276
+ overrideProfile?: unknown;
277
+ forceOverrideProfile?: unknown;
278
+ selectionSeed?: unknown;
279
+ },
280
+ ) => {
281
+ recordUsageCalls.push({
282
+ conversationId: ctx.conversationId,
283
+ inputTokens,
284
+ outputTokens,
285
+ model,
286
+ actor,
287
+ cacheCreationInputTokens,
288
+ cacheReadInputTokens,
289
+ callSite: attribution?.callSite ?? null,
290
+ overrideProfile: attribution?.overrideProfile ?? null,
291
+ forceOverrideProfile: attribution?.forceOverrideProfile,
292
+ selectionSeed: attribution?.selectionSeed,
293
+ });
294
+ },
295
+ }));
247
296
  mock.module("../../memory/llm-request-log-store.js", () => ({
248
297
  recordRequestLog: (
249
298
  conversationId: string,
@@ -464,6 +513,7 @@ beforeEach(() => {
464
513
  __resetWakeChainForTests();
465
514
  wakeConvRegistry.clear();
466
515
  recordRequestLogCalls.length = 0;
516
+ recordUsageCalls.length = 0;
467
517
  mockGetOrCreateConversationCalls.length = 0;
468
518
  mockResolverTarget = null;
469
519
  mockGetConversationOverrideProfile = () => undefined;
@@ -1896,6 +1946,137 @@ describe("wakeAgentForOpportunity", () => {
1896
1946
  expect(recordRequestLogCalls[0]?.callSite).toBe("memoryRetrospective");
1897
1947
  });
1898
1948
 
1949
+ test("wake records LLM usage to the cost ledger, attributed to its call site", async () => {
1950
+ const usageEvent: AgentEvent = {
1951
+ type: "usage",
1952
+ inputTokens: 100,
1953
+ outputTokens: 5,
1954
+ model: "test-model",
1955
+ actualProvider: "test-provider",
1956
+ providerDurationMs: 10,
1957
+ cacheCreationInputTokens: 7,
1958
+ cacheReadInputTokens: 11,
1959
+ rawRequest: { request: "retrospective wake" },
1960
+ rawResponse: { response: "real reply" },
1961
+ };
1962
+ const conversation = makeWakeConversation({
1963
+ baseline: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
1964
+ scriptedEvents: [usageEvent],
1965
+ scriptedAssistant: {
1966
+ role: "assistant",
1967
+ content: [{ type: "text", text: "real reply" }],
1968
+ },
1969
+ });
1970
+
1971
+ await wakeAgentForOpportunity(
1972
+ {
1973
+ conversationId: conversation.conversationId,
1974
+ hint: "do reply",
1975
+ source: "unit-test",
1976
+ callSite: "memoryRetrospective",
1977
+ },
1978
+ { resolveTarget: async () => conversation },
1979
+ );
1980
+
1981
+ // A wake-driven LLM call records a usage row attributed to its
1982
+ // conversation, so its cost reaches the ledger.
1983
+ expect(recordUsageCalls).toHaveLength(1);
1984
+ expect(recordUsageCalls[0]).toMatchObject({
1985
+ conversationId: conversation.conversationId,
1986
+ inputTokens: 100,
1987
+ outputTokens: 5,
1988
+ model: "test-model",
1989
+ actor: "main_agent",
1990
+ cacheCreationInputTokens: 7,
1991
+ cacheReadInputTokens: 11,
1992
+ callSite: "memoryRetrospective",
1993
+ // Seed the dispatch path used for mix-arm resolution.
1994
+ selectionSeed: conversation.conversationId,
1995
+ });
1996
+ });
1997
+
1998
+ test("forced-profile wake records usage under the forced profile, not the call site", async () => {
1999
+ const usageEvent: AgentEvent = {
2000
+ type: "usage",
2001
+ inputTokens: 100,
2002
+ outputTokens: 5,
2003
+ model: "test-model",
2004
+ actualProvider: "test-provider",
2005
+ providerDurationMs: 10,
2006
+ rawRequest: { request: "forced wake" },
2007
+ rawResponse: { response: "real reply" },
2008
+ };
2009
+ const conversation = makeWakeConversation({
2010
+ baseline: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
2011
+ scriptedEvents: [usageEvent],
2012
+ scriptedAssistant: {
2013
+ role: "assistant",
2014
+ content: [{ type: "text", text: "real reply" }],
2015
+ },
2016
+ });
2017
+
2018
+ await wakeAgentForOpportunity(
2019
+ {
2020
+ conversationId: conversation.conversationId,
2021
+ hint: "do reply",
2022
+ source: "unit-test",
2023
+ callSite: "memoryRetrospective",
2024
+ // Stand-in for the source conversation's profile, floated above the
2025
+ // call-site profile (fork retrospectives). `recordUsage` is mocked, so
2026
+ // this value is only threaded through and asserted — not resolved.
2027
+ forceOverrideProfile: "source-profile",
2028
+ },
2029
+ { resolveTarget: async () => conversation },
2030
+ );
2031
+
2032
+ expect(recordUsageCalls).toHaveLength(1);
2033
+ expect(recordUsageCalls[0]).toMatchObject({
2034
+ overrideProfile: "source-profile",
2035
+ forceOverrideProfile: true,
2036
+ selectionSeed: conversation.conversationId,
2037
+ });
2038
+ });
2039
+
2040
+ test("silent no-op wake still records usage even though its request log is dropped", async () => {
2041
+ const usageEvent: AgentEvent = {
2042
+ type: "usage",
2043
+ inputTokens: 100,
2044
+ outputTokens: 5,
2045
+ model: "test-model",
2046
+ actualProvider: "test-provider",
2047
+ providerDurationMs: 10,
2048
+ rawRequest: { request: "no-op wake" },
2049
+ rawResponse: { response: "no output" },
2050
+ };
2051
+ const conversation = makeWakeConversation({
2052
+ baseline: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
2053
+ scriptedEvents: [usageEvent],
2054
+ // Empty assistant text → silent no-op, so the request log is dropped.
2055
+ scriptedAssistant: {
2056
+ role: "assistant",
2057
+ content: [{ type: "text", text: "" }],
2058
+ },
2059
+ });
2060
+
2061
+ await wakeAgentForOpportunity(
2062
+ {
2063
+ conversationId: conversation.conversationId,
2064
+ hint: "consider doing nothing",
2065
+ source: "unit-test",
2066
+ },
2067
+ { resolveTarget: async () => conversation },
2068
+ );
2069
+
2070
+ // Silent wake drops its request log, but the call still cost money.
2071
+ expect(recordRequestLogCalls).toHaveLength(0);
2072
+ expect(recordUsageCalls).toHaveLength(1);
2073
+ expect(recordUsageCalls[0]).toMatchObject({
2074
+ conversationId: conversation.conversationId,
2075
+ inputTokens: 100,
2076
+ outputTokens: 5,
2077
+ });
2078
+ });
2079
+
1899
2080
  test("non-serializable usage payload does not abort the wake", async () => {
1900
2081
  // Circular reference in rawRequest — JSON.stringify throws on this.
1901
2082
  // Serialization must happen inside persistLog's try/catch so the
@@ -21,10 +21,7 @@ import {
21
21
  updateCanonicalGuardianDelivery,
22
22
  } from "../memory/canonical-guardian-store.js";
23
23
  import { emitNotificationSignal } from "../notifications/emit-signal.js";
24
- import type {
25
- GuardianResolutionSource,
26
- NotificationSourceChannel,
27
- } from "../notifications/signal.js";
24
+ import type { GuardianResolutionSource } from "../notifications/signal.js";
28
25
  import type { NotificationDeliveryResult } from "../notifications/types.js";
29
26
  import { getLogger } from "../util/logger.js";
30
27
  import { GUARDIAN_APPROVAL_TTL_MS } from "./routes/channel-route-shared.js";
@@ -219,7 +216,7 @@ export function notifyGuardianOfAccessRequest(
219
216
 
220
217
  void emitNotificationSignal({
221
218
  sourceEventName: "ingress.access_request",
222
- sourceChannel: sourceChannel as NotificationSourceChannel,
219
+ sourceChannel,
223
220
  sourceContextId: `access-req-${sourceChannel}-${actorExternalId}`,
224
221
  requiresConversation: true,
225
222
  ...(sameChannelOnly ? { routingIntent: "single_channel" as const } : {}),
@@ -58,6 +58,7 @@ import { resolveEffectiveContextWindow } from "../config/llm-context-resolution.
58
58
  import { getConfig } from "../config/loader.js";
59
59
  import type { LLMCallSite } from "../config/schemas/llm.js";
60
60
  import type { Conversation } from "../daemon/conversation.js";
61
+ import { recordUsage } from "../daemon/conversation-usage.js";
61
62
  import { getDiskPressureStatus } from "../daemon/disk-pressure-guard.js";
62
63
  import {
63
64
  classifyDiskPressureTurnPolicy,
@@ -784,6 +785,47 @@ export async function wakeAgentForOpportunity(
784
785
  if (event.type === "compaction_completed") {
785
786
  recordCompactionEndBestEffort(conversationId, event);
786
787
  }
788
+ // Normal user turns record usage via the `dispatchAgentEvent` event handler)
789
+ // Wakes run their own onEvent and bypass it, so record here.
790
+ if (event.type === "usage") {
791
+ try {
792
+ recordUsage(
793
+ {
794
+ conversationId,
795
+ providerName: event.actualProvider ?? conversation.provider.name,
796
+ usageStats: conversation.usageStats,
797
+ },
798
+ event.inputTokens,
799
+ event.outputTokens,
800
+ event.model,
801
+ () => {},
802
+ "main_agent",
803
+ `wake:${source}`,
804
+ event.cacheCreationInputTokens ?? 0,
805
+ event.cacheReadInputTokens ?? 0,
806
+ event.rawResponse,
807
+ 1,
808
+ undefined,
809
+ // Mirror the profile state the request actually ran under:
810
+ // `forceOverrideProfile` floats the override above the call-site
811
+ // profile (fork retrospectives with matchConversationProfile), and
812
+ // the conversation-id seed resolves the same mix arm the dispatch
813
+ // path chose. Without these, attribution credits the call-site
814
+ // profile/arm instead of the one that ran.
815
+ {
816
+ callSite,
817
+ overrideProfile: overrideProfile ?? null,
818
+ forceOverrideProfile,
819
+ selectionSeed: conversationId,
820
+ },
821
+ );
822
+ } catch (err) {
823
+ log.warn(
824
+ { conversationId, source, err },
825
+ "agent-wake: usage recording failed (non-fatal)",
826
+ );
827
+ }
828
+ }
787
829
  // Replicates the recordRequestLog side-effect in `handleUsage` because
788
830
  // wakes own their own onEvent and never reach `dispatchAgentEvent`.
789
831
  // Defer persistence while buffering — see `pendingLogs` above.
@@ -18,7 +18,6 @@ import {
18
18
  createCanonicalGuardianDelivery,
19
19
  } from "../memory/canonical-guardian-store.js";
20
20
  import { emitNotificationSignal } from "../notifications/emit-signal.js";
21
- import type { NotificationSourceChannel } from "../notifications/signal.js";
22
21
  import { canonicalizeInboundIdentity } from "../util/canonicalize-identity.js";
23
22
  import { getLogger } from "../util/logger.js";
24
23
  import { DAEMON_INTERNAL_ASSISTANT_ID } from "./assistant-scope.js";
@@ -147,7 +146,7 @@ export function bridgeConfirmationRequestToGuardian(
147
146
  // Emit guardian.question notification so the guardian is alerted.
148
147
  const signalPromise = emitNotificationSignal({
149
148
  sourceEventName: "guardian.question",
150
- sourceChannel: sourceChannel as NotificationSourceChannel,
149
+ sourceChannel,
151
150
  sourceContextId: conversationId,
152
151
  requiresConversation: true,
153
152
  attentionHints: {
@@ -157,7 +156,7 @@ export function bridgeConfirmationRequestToGuardian(
157
156
  visibleInSourceNow: false,
158
157
  },
159
158
  contextPayload: {
160
- requestKind: "tool_approval" as const,
159
+ requestKind: "tool_approval",
161
160
  requestId: canonicalRequest.id,
162
161
  requestCode:
163
162
  canonicalRequest.requestCode ??
@@ -168,6 +167,8 @@ export function bridgeConfirmationRequestToGuardian(
168
167
  requesterIdentifier: senderLabel,
169
168
  toolName,
170
169
  questionText,
170
+ riskLevel: canonicalRequest.riskLevel ?? undefined,
171
+ commandPreview: canonicalRequest.commandPreview ?? undefined,
171
172
  },
172
173
  dedupeKey: `tc-confirmation-request:${canonicalRequest.id}`,
173
174
  onConversationCreated: (info) => {
@@ -11,7 +11,6 @@ import type { ChannelId, InterfaceId } from "../../../channels/types.js";
11
11
  import { createCanonicalGuardianRequest } from "../../../memory/canonical-guardian-store.js";
12
12
  import { storePayload } from "../../../memory/delivery-crud.js";
13
13
  import { emitNotificationSignal } from "../../../notifications/emit-signal.js";
14
- import type { NotificationSourceChannel } from "../../../notifications/signal.js";
15
14
  import { getLogger } from "../../../util/logger.js";
16
15
  import { getGuardianBinding } from "../../channel-verification-service.js";
17
16
  import { GUARDIAN_APPROVAL_TTL_MS } from "../channel-route-shared.js";
@@ -133,7 +132,7 @@ export function handleEscalationIntercept(
133
132
  // channels, supplementing the direct guardian notification below.
134
133
  void emitNotificationSignal({
135
134
  sourceEventName: "ingress.escalation",
136
- sourceChannel: sourceChannel as NotificationSourceChannel,
135
+ sourceChannel,
137
136
  sourceContextId: conversationId,
138
137
  attentionHints: {
139
138
  requiresAction: true,
@@ -11,7 +11,6 @@
11
11
  import type { ChannelId } from "../../../channels/types.js";
12
12
  import { findGuardianForChannel } from "../../../contacts/contact-store.js";
13
13
  import { emitNotificationSignal } from "../../../notifications/emit-signal.js";
14
- import type { NotificationSourceChannel } from "../../../notifications/signal.js";
15
14
  import { getLogger } from "../../../util/logger.js";
16
15
  import {
17
16
  createOutboundSession,
@@ -164,7 +163,7 @@ export async function handleGuardianActivationIntercept(
164
163
  // ── Emit notification signal to deliver code to macOS app ──
165
164
  void emitNotificationSignal({
166
165
  sourceEventName: "guardian.channel_activation",
167
- sourceChannel: sourceChannel as NotificationSourceChannel,
166
+ sourceChannel,
168
167
  sourceContextId: `guardian-activation-${sourceChannel}-${rawSenderId}`,
169
168
  attentionHints: {
170
169
  requiresAction: true,
@@ -18,7 +18,6 @@ import {
18
18
  listCanonicalGuardianRequests,
19
19
  } from "../memory/canonical-guardian-store.js";
20
20
  import { emitNotificationSignal } from "../notifications/emit-signal.js";
21
- import type { NotificationSourceChannel } from "../notifications/signal.js";
22
21
  import { getLogger } from "../util/logger.js";
23
22
  import { getGuardianBinding } from "./channel-verification-service.js";
24
23
  import { GUARDIAN_APPROVAL_TTL_MS } from "./routes/channel-route-shared.js";
@@ -145,7 +144,7 @@ export function createOrReuseToolGrantRequest(
145
144
  // pipeline is preserved.
146
145
  const signalPromise = emitNotificationSignal({
147
146
  sourceEventName: "guardian.question",
148
- sourceChannel: sourceChannel as NotificationSourceChannel,
147
+ sourceChannel,
149
148
  sourceContextId: conversationId,
150
149
  requiresConversation: true,
151
150
  attentionHints: {
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import { RiskLevel } from "../../permissions/types.js";
11
+ import { isWeakOpenModel } from "../../providers/weak-open-model.js";
11
12
  import { ACTIVATION_MOMENT_PARAMS } from "../../telemetry/activation-funnel.js";
12
13
  import type {
13
14
  ToolContext,
@@ -37,8 +38,9 @@ function proxyExecute(toolName: string) {
37
38
  ): Promise<ToolExecutionResult> => {
38
39
  if (toolName === "ui_show" && isEmptyDynamicPage(input)) {
39
40
  return {
40
- content:
41
- "Error: ui_show dynamic_page requires non-empty HTML in `data.html`. The surface was not displayed because no content was provided — the user would see a blank box. Resend ui_show with the full HTML markup in `data.html`.",
41
+ content: isWeakOpenModel(context.attribution?.resolvedModel)
42
+ ? EMPTY_DYNAMIC_PAGE_DECLARATIVE_REDIRECT
43
+ : EMPTY_DYNAMIC_PAGE_HTML_HINT,
42
44
  isError: true,
43
45
  };
44
46
  }
@@ -89,6 +91,27 @@ function proxyExecute(toolName: string) {
89
91
  };
90
92
  }
91
93
 
94
+ /**
95
+ * Rejection envelope for an empty `dynamic_page` ui_show from a capable model:
96
+ * the surface carried no `data.html`, so it would render as a blank box. These
97
+ * models reliably author HTML, so the fix is simply to resend it inline.
98
+ */
99
+ const EMPTY_DYNAMIC_PAGE_HTML_HINT =
100
+ "Error: ui_show dynamic_page requires non-empty HTML in `data.html`. The surface was not displayed because no content was provided — the user would see a blank box. Resend ui_show with the full HTML markup in `data.html`.";
101
+
102
+ /**
103
+ * Rejection envelope for an empty `dynamic_page` ui_show from a weak open model.
104
+ * Authoring full HTML inline is the generation task these models fail at (an
105
+ * empty `data: {}` here, or broken markup otherwise), so steering them to
106
+ * "resend the HTML" just repeats the failure. Most widget requests are really
107
+ * structured data — comparisons, results, metrics — which render reliably via a
108
+ * field-based surface the model populates without writing any HTML, and which
109
+ * cannot render blank. dynamic_page stays available for genuinely custom visual
110
+ * HTML.
111
+ */
112
+ const EMPTY_DYNAMIC_PAGE_DECLARATIVE_REDIRECT =
113
+ 'Error: ui_show dynamic_page was not displayed — `data.html` was empty, so the user would see a blank box. Authoring full HTML inline is error-prone; for data, comparisons, results, or metrics prefer a structured surface, which you fill with fields (no HTML) and which never renders blank. Re-show the content as one of: a `table` (ui_show { surface_type: "table", data: { columns: [{ id, label }], rows: [{ id, cells: { <columnId>: "<value>" } }] } }), a `card` ({ title, body, metadata: [{ label, value }] }), or `work_result` ({ summary, metrics: [{ label, value }] }). Only use dynamic_page when you genuinely need custom visual HTML, in which case include the complete markup in `data.html` now.';
114
+
92
115
  /**
93
116
  * Worked ui_update example, appended to a successful task_progress `ui_show`
94
117
  * result so the model learns the update pattern at the point of use (with the