@vellumai/assistant 0.10.0-dev.202606200318.c052d10 → 0.10.0-dev.202606201453.1417592

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 (49) hide show
  1. package/package.json +1 -1
  2. package/src/__tests__/agent-loop-callsite-precedence.test.ts +1 -40
  3. package/src/__tests__/agent-wake-override-profile.test.ts +2 -0
  4. package/src/__tests__/app-source-watcher.test.ts +30 -10
  5. package/src/__tests__/config-schema.test.ts +34 -0
  6. package/src/__tests__/conversation-agent-loop-disk-pressure.test.ts +3 -0
  7. package/src/__tests__/conversation-agent-loop-inference-profile.test.ts +3 -0
  8. package/src/__tests__/conversation-agent-loop-overflow.test.ts +3 -0
  9. package/src/__tests__/conversation-agent-loop.test.ts +3 -0
  10. package/src/__tests__/conversation-process-callsite.test.ts +0 -14
  11. package/src/__tests__/db-llm-request-log-provider-migration.test.ts +6 -1
  12. package/src/__tests__/heartbeat-disk-pressure.test.ts +3 -0
  13. package/src/__tests__/heartbeat-service.test.ts +6 -0
  14. package/src/__tests__/list-messages-attachments.test.ts +41 -0
  15. package/src/__tests__/plugin-source-watcher.test.ts +33 -1
  16. package/src/__tests__/usage-cache-backfill-migration.test.ts +17 -2
  17. package/src/acp/__tests__/session-manager.test.ts +72 -1
  18. package/src/acp/index.ts +10 -0
  19. package/src/acp/session-manager.ts +35 -0
  20. package/src/agent/loop.ts +28 -22
  21. package/src/config/schemas/memory-lifecycle.ts +5 -3
  22. package/src/config/schemas/timeouts.ts +24 -0
  23. package/src/daemon/app-source-watcher.ts +31 -18
  24. package/src/daemon/conversation-agent-loop.ts +8 -5
  25. package/src/daemon/conversation.ts +30 -41
  26. package/src/daemon/handlers/conversations.ts +7 -0
  27. package/src/daemon/plugin-source-watcher.ts +5 -0
  28. package/src/daemon/workspace-tools-watcher.ts +4 -0
  29. package/src/heartbeat/__tests__/heartbeat-service.test.ts +6 -0
  30. package/src/heartbeat/heartbeat-service.ts +3 -4
  31. package/src/memory/__tests__/db-maintenance.test.ts +27 -35
  32. package/src/memory/conversation-crud.ts +9 -3
  33. package/src/memory/db-init.ts +33 -5
  34. package/src/memory/db-maintenance.ts +43 -38
  35. package/src/memory/job-handlers/cleanup.ts +6 -0
  36. package/src/memory/migrations/297-move-llm-request-logs-to-logs-db.ts +130 -0
  37. package/src/memory/migrations/__tests__/297-move-llm-request-logs.test.ts +159 -0
  38. package/src/memory/migrations/index.ts +1 -0
  39. package/src/plugin-api/index.ts +7 -0
  40. package/src/plugin-api/vision-support.ts +75 -0
  41. package/src/prompts/system-prompt.ts +1 -1
  42. package/src/runtime/__tests__/agent-wake.test.ts +6 -4
  43. package/src/runtime/agent-wake.ts +15 -7
  44. package/src/runtime/routes/conversation-routes.ts +24 -3
  45. package/src/runtime/routes/migration-routes.ts +35 -39
  46. package/src/schedule/scheduler.ts +5 -9
  47. package/src/tools/ask-question/ask-question-tool.test.ts +60 -52
  48. package/src/tools/ask-question/ask-question-tool.ts +14 -73
  49. package/src/util/fs-watcher-error.ts +36 -0
@@ -597,13 +597,14 @@ export async function wakeAgentForOpportunity(
597
597
  });
598
598
 
599
599
  // Apply the caller's persona override for the duration of the run. The
600
- // wake's agent loop builds the system prompt through the conversation's
601
- // resolveSystemPrompt callback, which reads this field; cleared (below,
602
- // before drainQueue) so a queued user turn never builds its prompt under
603
- // the wake's override. Assigned only AFTER the profile/config reads above
604
- // — those can throw, and they run before the try/finally that clears the
605
- // override, so an earlier assignment would strand the override on the
606
- // cached Conversation and corrupt every later prompt build on it.
600
+ // prompt is built once before `agentLoop.run()` (via
601
+ // `conversation.buildCurrentSystemPrompt()`), which reads this field;
602
+ // cleared (below, before drainQueue) so a queued user turn never builds
603
+ // its prompt under the wake's override. Assigned only AFTER the
604
+ // profile/config reads above — those can throw, and they run before the
605
+ // try/finally that clears the override, so an earlier assignment would
606
+ // strand the override on the cached Conversation and corrupt every later
607
+ // prompt build on it.
607
608
  if (opts.personaOverride) {
608
609
  conversation.wakePersonaOverride = opts.personaOverride;
609
610
  }
@@ -1146,6 +1147,13 @@ export async function wakeAgentForOpportunity(
1146
1147
  maxInputTokens: effectiveContextWindow.maxInputTokens,
1147
1148
  overflowRecovery: { enabled: false, safetyMarginRatio: 0 },
1148
1149
  }),
1150
+ // Resolve the system prompt once before the run — the loop does
1151
+ // not re-resolve mid-loop. `wakePersonaOverride` (if set above)
1152
+ // is baked into the prompt at this point.
1153
+ systemPrompt: conversation.buildCurrentSystemPrompt(),
1154
+ ...(conversation.modelOverride
1155
+ ? { model: conversation.modelOverride }
1156
+ : {}),
1149
1157
  }));
1150
1158
  } catch (err) {
1151
1159
  // An over-window throw on a compaction-suppressed wake is the
@@ -10,7 +10,10 @@ import {
10
10
  createAssistantMessage,
11
11
  createUserMessage,
12
12
  } from "../../agent/message-types.js";
13
- import { ConversationMessageSchema } from "../../api/responses/conversation-message.js";
13
+ import {
14
+ type ConversationContentBlock,
15
+ ConversationMessageSchema,
16
+ } from "../../api/responses/conversation-message.js";
14
17
  import {
15
18
  CHANNEL_IDS,
16
19
  INTERFACE_IDS,
@@ -943,7 +946,25 @@ export function handleListMessages({
943
946
  .filter((block) => block.type !== "text" || block.text.length > 0);
944
947
  }
945
948
 
946
- const alignedContentOrder = aligned.rewriteContentOrder(contentOrder);
949
+ // Ensure every hydrated attachment has a corresponding content block.
950
+ // renderHistoryContent inlines attachment blocks only when it has
951
+ // file-block refs with matching DB rows; directives (assistant-authored
952
+ // <vellum-attachment/> tags) don't leave a file block after stripping,
953
+ // so their attachments end up in the flat `attachments` array but not in
954
+ // `contentBlocks`. Append any that are missing so the canonical
955
+ // projection is complete.
956
+ const existingAttachmentIds = new Set(
957
+ contentBlocks
958
+ .filter((b): b is Extract<ConversationContentBlock, { type: "attachment" }> => b.type === "attachment")
959
+ .map((b) => b.attachment.id),
960
+ );
961
+ for (const att of msgAttachments) {
962
+ if (!existingAttachmentIds.has(att.id)) {
963
+ contentBlocks.push({ type: "attachment", attachment: att });
964
+ }
965
+ }
966
+
967
+ const alignedContentOrder = aligned.rewriteContentOrder(contentOrder);
947
968
 
948
969
  // Use sentAt (actual event time) for the display timestamp when available,
949
970
  // falling back to createdAt (persistence time). Clients use this display
@@ -971,7 +992,7 @@ export function handleListMessages({
971
992
  ...(alignedContentOrder.length > 0
972
993
  ? { contentOrder: alignedContentOrder }
973
994
  : {}),
974
- ...(contentBlocks.length > 0 ? { contentBlocks } : {}),
995
+ contentBlocks,
975
996
  ...(m.subagentNotification
976
997
  ? { subagentNotification: m.subagentNotification }
977
998
  : {}),
@@ -38,6 +38,7 @@ import {
38
38
  upsertCredentialMetadata,
39
39
  } from "../../tools/credentials/metadata-store.js";
40
40
  import { getLogger } from "../../util/logger.js";
41
+ import { getLogsDbPath } from "../../util/logs-db-path.js";
41
42
  import { getWorkspaceDir, getWorkspaceHooksDir } from "../../util/platform.js";
42
43
  import { APP_VERSION } from "../../version.js";
43
44
  import { DAEMON_INTERNAL_ASSISTANT_ID } from "../assistant-scope.js";
@@ -151,6 +152,38 @@ export async function reconcileVellumMetadataFromCes(warningSink: {
151
152
 
152
153
  const log = getLogger("migration-routes");
153
154
 
155
+ /**
156
+ * Flush both database files' WALs before an export copies them. The bundle
157
+ * walker includes `*.db` but skips `*.db-wal`, so committed frames still sitting
158
+ * in a WAL would be missing from the bundle.
159
+ *
160
+ * Dispatched through `runAsyncSqlite` so the flush runs in a sqlite3 subprocess
161
+ * where available — a multi-GB WAL flush would otherwise stall the event loop.
162
+ * The in-process fallback runs on the daemon connection, where one unqualified
163
+ * checkpoint already covers every attached database; the subprocess opens a
164
+ * single file, so we issue a second checkpoint targeting the logs file. FULL
165
+ * (not TRUNCATE) writes committed frames back to the main file, which is all the
166
+ * copy needs.
167
+ */
168
+ async function checkpointDbsForExport(): Promise<void> {
169
+ const targets: Array<{ label: string; dbPath?: string }> = [
170
+ { label: "main" },
171
+ { label: "logs", dbPath: getLogsDbPath() },
172
+ ];
173
+ for (const { label, dbPath } of targets) {
174
+ const result = await runAsyncSqlite(
175
+ "PRAGMA wal_checkpoint(FULL)",
176
+ dbPath ? { dbPath } : undefined,
177
+ );
178
+ if (!result.ok) {
179
+ log.warn(
180
+ { error: result.error, backend: result.backend, db: label },
181
+ "WAL checkpoint failed — exporting without checkpoint",
182
+ );
183
+ }
184
+ }
185
+ }
186
+
154
187
  /**
155
188
  * Fields the export pipeline must populate on the v1 manifest.
156
189
  *
@@ -353,28 +386,7 @@ export async function handleMigrationExport(
353
386
  ...manifestInputs,
354
387
  secretsRedacted,
355
388
  credentials,
356
- checkpoint: async () => {
357
- // Dispatch through `runAsyncSqlite` so the WAL checkpoint runs
358
- // in a sqlite3 subprocess on hosts where it's available. A WAL
359
- // flush on a multi-GB WAL file can otherwise stall the daemon's
360
- // event loop for the full duration of the flush.
361
- //
362
- // FULL (not TRUNCATE): FULL blocks until every committed frame is
363
- // written back to the main `.db` file, which is all the export
364
- // needs since it copies that file. TRUNCATE additionally restarts
365
- // the WAL and truncates it to zero bytes — extra work and blocking
366
- // this path does not need.
367
- const result = await runAsyncSqlite("PRAGMA wal_checkpoint(FULL)");
368
- if (!result.ok) {
369
- // Best-effort: if the DB can't be checkpointed (e.g. not a valid
370
- // SQLite file, missing WAL, etc.) we still proceed with the export
371
- // using whatever is on disk.
372
- log.warn(
373
- { error: result.error, backend: result.backend },
374
- "WAL checkpoint failed — exporting without checkpoint",
375
- );
376
- }
377
- },
389
+ checkpoint: checkpointDbsForExport,
378
390
  });
379
391
 
380
392
  cleanup = result.cleanup;
@@ -582,23 +594,7 @@ export async function handleMigrationExportToGcs({ body }: RouteHandlerArgs) {
582
594
  ...manifestInputs,
583
595
  secretsRedacted,
584
596
  credentials: collected.credentials,
585
- checkpoint: async () => {
586
- // Dispatch through `runAsyncSqlite` so the WAL checkpoint runs
587
- // in a sqlite3 subprocess on hosts where it's available. A
588
- // WAL flush on a multi-GB WAL file can otherwise stall the
589
- // daemon's event loop for the full duration of the flush.
590
- //
591
- // FULL (not TRUNCATE): see the disk-export checkpoint above
592
- // for rationale. assistant/AGENTS.md "SQLite WAL
593
- // checkpointing".
594
- const result = await runAsyncSqlite("PRAGMA wal_checkpoint(FULL)");
595
- if (!result.ok) {
596
- log.warn(
597
- { error: result.error, backend: result.backend },
598
- "WAL checkpoint failed — exporting without checkpoint",
599
- );
600
- }
601
- },
597
+ checkpoint: checkpointDbsForExport,
602
598
  });
603
599
 
604
600
  cleanup = result.cleanup;
@@ -1,3 +1,4 @@
1
+ import { getConfig } from "../config/loader.js";
1
2
  import {
2
3
  checkDiskPressureBackgroundGate,
3
4
  diskPressureBackgroundSkipLogFields,
@@ -85,14 +86,6 @@ const TICK_INTERVAL_MS = 15_000;
85
86
  */
86
87
  const WAKE_MAX_RETRIES = 20;
87
88
 
88
- /**
89
- * Hard timeout for `talk`-mode scheduled jobs. Schedules can do
90
- * non-trivial work (research, summarize the day, etc.), so the cap is
91
- * generous; it exists primarily so a wedged turn cannot block the next
92
- * scheduler tick indefinitely. Mirrors the heartbeat/filing budgets.
93
- */
94
- const SCHEDULE_TALK_TIMEOUT_MS = 30 * 60 * 1000;
95
-
96
89
  /**
97
90
  * Apply retry policy on schedule-execution failure. Retries are scheduled by
98
91
  * `applyRetryDecision`; once retries are exhausted, the `emitAlert` callback
@@ -718,7 +711,10 @@ export async function runScheduleDueWorkOnce(
718
711
  ...(job.inferenceProfile
719
712
  ? { overrideProfile: job.inferenceProfile }
720
713
  : {}),
721
- timeoutMs: SCHEDULE_TALK_TIMEOUT_MS,
714
+ // Hard timeout for talk-mode scheduled turns: bounds a wedged turn so
715
+ // it cannot block the next scheduler tick. Configurable via
716
+ // timeouts.scheduleTurnTimeoutSec (default 1800s).
717
+ timeoutMs: getConfig().timeouts.scheduleTurnTimeoutSec * 1000,
722
718
  origin: "schedule",
723
719
  groupId: "system:scheduled",
724
720
  conversationType: "scheduled",
@@ -59,7 +59,9 @@ beforeEach(() => {
59
59
  };
60
60
  });
61
61
 
62
- const validInput = {
62
+ // A single question used to build batches. The tool only accepts the
63
+ // batched `{ questions: [...] }` shape.
64
+ const singleQ = {
63
65
  question: "Which fruit?",
64
66
  description: "Pick one to add to the smoothie.",
65
67
  options: [
@@ -69,12 +71,7 @@ const validInput = {
69
71
  freeTextPlaceholder: "Type a fruit",
70
72
  };
71
73
 
72
- const singleQ = {
73
- question: validInput.question,
74
- description: validInput.description,
75
- options: validInput.options,
76
- freeTextPlaceholder: validInput.freeTextPlaceholder,
77
- };
74
+ const validInput = { questions: [singleQ] };
78
75
 
79
76
  describe("askQuestionTool definition", () => {
80
77
  test("exposes the expected schema shape and description language", () => {
@@ -91,7 +88,6 @@ describe("askQuestionTool definition", () => {
91
88
  expect(def.description).toContain("remove guessing");
92
89
  expect(def.description).toContain("a question is skipped");
93
90
  expect(def.description).toContain("every question in the batch is skipped");
94
- // Batching language is back now that the prompter handles batches.
95
91
  expect(def.description).toContain("Batch related clarifications");
96
92
  expect(def.description).toContain("up to 5");
97
93
  expect(def.description).toContain("Skip button");
@@ -99,13 +95,23 @@ describe("askQuestionTool definition", () => {
99
95
  const schema = def.input_schema as {
100
96
  properties: Record<
101
97
  string,
102
- { type?: string; minItems?: number; maxItems?: number }
98
+ {
99
+ type?: string;
100
+ items?: {
101
+ properties?: Record<
102
+ string,
103
+ { type?: string; minItems?: number; maxItems?: number }
104
+ >;
105
+ };
106
+ }
103
107
  >;
104
108
  required?: string[];
105
109
  };
106
- expect(schema.properties.options?.type).toBe("array");
107
- expect(schema.properties.options?.minItems).toBe(2);
108
- expect(schema.properties.options?.maxItems).toBe(4);
110
+ const optionsSchema =
111
+ schema.properties.questions?.items?.properties?.options;
112
+ expect(optionsSchema?.type).toBe("array");
113
+ expect(optionsSchema?.minItems).toBe(2);
114
+ expect(optionsSchema?.maxItems).toBe(4);
109
115
  });
110
116
  });
111
117
 
@@ -132,17 +138,17 @@ describe("AskQuestionTool.execute", () => {
132
138
  expect(calls).toHaveLength(1);
133
139
  expect(calls[0]?.conversationId).toBe("conv-1");
134
140
  expect(calls[0]?.questions).toHaveLength(1);
135
- expect(calls[0]?.questions[0]?.question).toBe(validInput.question);
136
- expect(calls[0]?.questions[0]?.description).toBe(validInput.description);
137
- expect(calls[0]?.questions[0]?.options).toEqual(validInput.options);
141
+ expect(calls[0]?.questions[0]?.question).toBe(singleQ.question);
142
+ expect(calls[0]?.questions[0]?.description).toBe(singleQ.description);
143
+ expect(calls[0]?.questions[0]?.options).toEqual(singleQ.options);
138
144
  expect(calls[0]?.questions[0]?.freeTextPlaceholder).toBe(
139
- validInput.freeTextPlaceholder,
145
+ singleQ.freeTextPlaceholder,
140
146
  );
141
147
  expect(calls[0]?.toolUseId).toBe("tu-1");
142
148
 
143
149
  expect(result.isError).toBe(false);
144
150
  expect(result.content).toBe(
145
- `Question "${validInput.question}" → Option: a (Apple)`,
151
+ `Question "${singleQ.question}" → Option: a (Apple)`,
146
152
  );
147
153
  });
148
154
 
@@ -150,7 +156,7 @@ describe("AskQuestionTool.execute", () => {
150
156
  setNextResult(singleCompleted({ decision: "option", optionId: "b" }));
151
157
  const result = await askQuestionTool.execute(validInput, makeContext());
152
158
  expect(result.content).toBe(
153
- `Question "${validInput.question}" → Option: b (Banana)`,
159
+ `Question "${singleQ.question}" → Option: b (Banana)`,
154
160
  );
155
161
  expect(result.isError).toBe(false);
156
162
  });
@@ -159,7 +165,7 @@ describe("AskQuestionTool.execute", () => {
159
165
  setNextResult(singleCompleted({ decision: "option", optionId: "ghost" }));
160
166
  const result = await askQuestionTool.execute(validInput, makeContext());
161
167
  expect(result.content).toBe(
162
- `Question "${validInput.question}" → Option: ghost ((unknown))`,
168
+ `Question "${singleQ.question}" → Option: ghost ((unknown))`,
163
169
  );
164
170
  expect(result.isError).toBe(false);
165
171
  });
@@ -168,7 +174,7 @@ describe("AskQuestionTool.execute", () => {
168
174
  setNextResult(singleCompleted({ decision: "free_text", text: "Cherry" }));
169
175
  const result = await askQuestionTool.execute(validInput, makeContext());
170
176
  expect(result.content).toBe(
171
- `Question "${validInput.question}" → Free text: Cherry`,
177
+ `Question "${singleQ.question}" → Free text: Cherry`,
172
178
  );
173
179
  expect(result.isError).toBe(false);
174
180
  });
@@ -176,7 +182,7 @@ describe("AskQuestionTool.execute", () => {
176
182
  test("formats skipped result", async () => {
177
183
  setNextResult(singleCompleted({ decision: "skipped" }));
178
184
  const result = await askQuestionTool.execute(validInput, makeContext());
179
- expect(result.content).toBe(`Question "${validInput.question}" → Skipped`);
185
+ expect(result.content).toBe(`Question "${singleQ.question}" → Skipped`);
180
186
  expect(result.isError).toBe(false);
181
187
  });
182
188
 
@@ -200,10 +206,10 @@ describe("AskQuestionTool.execute", () => {
200
206
  expect(result.content).toBe("Question aborted");
201
207
  });
202
208
 
203
- test("rejects input with fewer than 2 options", async () => {
209
+ test("rejects a question with fewer than 2 options", async () => {
204
210
  setNextResult(singleCompleted({ decision: "option", optionId: "a" }));
205
211
  const result = await askQuestionTool.execute(
206
- { ...validInput, options: [{ id: "a", label: "Apple" }] },
212
+ { questions: [{ ...singleQ, options: [{ id: "a", label: "Apple" }] }] },
207
213
  makeContext(),
208
214
  );
209
215
  expect(result.isError).toBe(true);
@@ -211,17 +217,21 @@ describe("AskQuestionTool.execute", () => {
211
217
  expect(calls).toHaveLength(0);
212
218
  });
213
219
 
214
- test("rejects input with more than 4 options", async () => {
220
+ test("rejects a question with more than 4 options", async () => {
215
221
  setNextResult(singleCompleted({ decision: "option", optionId: "a" }));
216
222
  const result = await askQuestionTool.execute(
217
223
  {
218
- ...validInput,
219
- options: [
220
- { id: "a", label: "A" },
221
- { id: "b", label: "B" },
222
- { id: "c", label: "C" },
223
- { id: "d", label: "D" },
224
- { id: "e", label: "E" },
224
+ questions: [
225
+ {
226
+ ...singleQ,
227
+ options: [
228
+ { id: "a", label: "A" },
229
+ { id: "b", label: "B" },
230
+ { id: "c", label: "C" },
231
+ { id: "d", label: "D" },
232
+ { id: "e", label: "E" },
233
+ ],
234
+ },
225
235
  ],
226
236
  },
227
237
  makeContext(),
@@ -230,10 +240,10 @@ describe("AskQuestionTool.execute", () => {
230
240
  expect(calls).toHaveLength(0);
231
241
  });
232
242
 
233
- test("rejects input with empty question", async () => {
243
+ test("rejects a question with empty text", async () => {
234
244
  setNextResult(singleCompleted({ decision: "option", optionId: "a" }));
235
245
  const result = await askQuestionTool.execute(
236
- { ...validInput, question: "" },
246
+ { questions: [{ ...singleQ, question: "" }] },
237
247
  makeContext(),
238
248
  );
239
249
  expect(result.isError).toBe(true);
@@ -254,18 +264,6 @@ describe("AskQuestionTool.execute", () => {
254
264
  // ── Batched input ───────────────────────────────────────────────────
255
265
 
256
266
  describe("AskQuestionTool batched input", () => {
257
- test("normalizes legacy flat input into a one-element batch forwarded to the prompter", async () => {
258
- setNextResult(singleCompleted({ decision: "option", optionId: "a" }));
259
-
260
- const result = await askQuestionTool.execute(validInput, makeContext());
261
-
262
- expect(calls).toHaveLength(1);
263
- expect(calls[0]?.questions).toHaveLength(1);
264
- expect(calls[0]?.questions[0]?.question).toBe(validInput.question);
265
- expect(calls[0]?.questions[0]?.options).toEqual(validInput.options);
266
- expect(result.isError).toBe(false);
267
- });
268
-
269
267
  test("accepts a single-element `questions` batch", async () => {
270
268
  setNextResult(singleCompleted({ decision: "option", optionId: "a" }));
271
269
 
@@ -454,7 +452,7 @@ describe("AskQuestionTool batched input", () => {
454
452
  expect(calls).toHaveLength(0);
455
453
  });
456
454
 
457
- test("rejects input missing both `questions` and flat fields", async () => {
455
+ test("rejects input missing `questions`", async () => {
458
456
  setNextResult(singleCompleted({ decision: "option", optionId: "a" }));
459
457
 
460
458
  const result = await askQuestionTool.execute({}, makeContext());
@@ -464,11 +462,17 @@ describe("AskQuestionTool batched input", () => {
464
462
  expect(calls).toHaveLength(0);
465
463
  });
466
464
 
467
- test("rejects legacy `question` without `options`", async () => {
465
+ test("rejects the dropped flat single-question shape", async () => {
468
466
  setNextResult(singleCompleted({ decision: "option", optionId: "a" }));
469
467
 
470
468
  const result = await askQuestionTool.execute(
471
- { question: "Hi?" },
469
+ {
470
+ question: "Hi?",
471
+ options: [
472
+ { id: "a", label: "A" },
473
+ { id: "b", label: "B" },
474
+ ],
475
+ },
472
476
  makeContext(),
473
477
  );
474
478
 
@@ -479,7 +483,7 @@ describe("AskQuestionTool batched input", () => {
479
483
  });
480
484
 
481
485
  describe("askQuestionTool definition (batched schema)", () => {
482
- test("exposes `questions[]` shape, keeps legacy fields, omits per-question id", () => {
486
+ test("exposes `questions[]` shape, requires it, and drops the flat fields", () => {
483
487
  const def = askQuestionTool;
484
488
  const schema = def.input_schema as unknown as {
485
489
  properties: Record<
@@ -517,8 +521,12 @@ describe("askQuestionTool definition (batched schema)", () => {
517
521
 
518
522
  expect(questions?.items?.required).toEqual(["question", "options"]);
519
523
 
520
- // Legacy fields still present.
521
- expect(schema.properties.question).toBeDefined();
522
- expect(schema.properties.options).toBeDefined();
524
+ // `questions` is the only top-level input now.
525
+ expect(schema.required).toEqual(["questions"]);
526
+ expect(Object.keys(schema.properties)).toEqual(["questions"]);
527
+
528
+ // The legacy flat fields are gone.
529
+ expect(schema.properties.question).toBeUndefined();
530
+ expect(schema.properties.options).toBeUndefined();
523
531
  });
524
532
  });
@@ -40,35 +40,16 @@ const SingleQuestionSchema = z.object({
40
40
  // input with ≥6 entries is rejected with a clear Zod error.
41
41
  const MAX_QUESTIONS_PER_BATCH = 5;
42
42
 
43
- // Both the new batched shape (`questions[]`) and the legacy flat shape are
44
- // accepted. `execute()` normalizes legacy callers into a one-element
45
- // `questions` array before forwarding to the prompter.
46
- const InputSchema = z
47
- .object({
48
- questions: z
49
- .array(SingleQuestionSchema)
50
- .min(1)
51
- .max(MAX_QUESTIONS_PER_BATCH, {
52
- message: `At most ${MAX_QUESTIONS_PER_BATCH} questions per batch; split into multiple turns if you need more.`,
53
- })
54
- .optional(),
55
- // Legacy flat fields. Optional so batched callers can omit them; when
56
- // present and `questions` is absent, they are normalized into a
57
- // one-element batch in `execute()`.
58
- question: z.string().min(1).optional(),
59
- description: z.string().optional(),
60
- options: z.array(OptionSchema).min(2).max(4).optional(),
61
- freeTextPlaceholder: z.string().optional(),
62
- })
63
- .refine(
64
- (v) =>
65
- v.questions !== undefined ||
66
- (v.question !== undefined && v.options !== undefined),
67
- {
68
- message:
69
- "Provide `questions` (preferred) or the legacy flat fields (`question` + `options`).",
70
- },
71
- );
43
+ // Callers pass a (possibly single-element) batch of questions. `execute()`
44
+ // forwards them straight to the prompter.
45
+ const InputSchema = z.object({
46
+ questions: z
47
+ .array(SingleQuestionSchema)
48
+ .min(1)
49
+ .max(MAX_QUESTIONS_PER_BATCH, {
50
+ message: `At most ${MAX_QUESTIONS_PER_BATCH} questions per batch; split into multiple turns if you need more.`,
51
+ }),
52
+ });
72
53
 
73
54
  export type SingleQuestion = z.infer<typeof SingleQuestionSchema>;
74
55
  export type AskQuestionInput = z.infer<typeof InputSchema>;
@@ -111,8 +92,7 @@ const DESCRIPTION = [
111
92
  "context shown beneath the label.",
112
93
  ].join("\n");
113
94
 
114
- // Shared option-schema fragment used by both the batched `questions[]`
115
- // shape and the legacy flat `options` field.
95
+ // Option-schema fragment for the items in `questions[].options`.
116
96
  const OPTION_ITEMS_SCHEMA = {
117
97
  type: "object",
118
98
  properties: {
@@ -150,12 +130,11 @@ export const askQuestionTool = {
150
130
  input_schema: {
151
131
  type: "object",
152
132
  properties: {
153
- // ── Recommended shape ─────────────────────────────────────
154
133
  questions: {
155
134
  type: "array",
156
135
  minItems: 1,
157
136
  maxItems: MAX_QUESTIONS_PER_BATCH,
158
- description: `Recommended shape. 1–${MAX_QUESTIONS_PER_BATCH} clarifying questions to ask in a single turn. Use a batch when several independent ambiguities block progress; ask one at a time when they're sequentially dependent. Past ${MAX_QUESTIONS_PER_BATCH} questions you should be implementing, not asking.`,
137
+ description: `1–${MAX_QUESTIONS_PER_BATCH} clarifying questions to ask in a single turn. Use a batch when several independent ambiguities block progress; ask one at a time when they're sequentially dependent. Past ${MAX_QUESTIONS_PER_BATCH} questions you should be implementing, not asking.`,
159
138
  items: {
160
139
  type: "object",
161
140
  properties: {
@@ -185,35 +164,8 @@ export const askQuestionTool = {
185
164
  required: ["question", "options"],
186
165
  },
187
166
  },
188
- // ── Legacy single-question fields ─────────────────────────
189
- // Kept optional so existing prompt caches and any single-question
190
- // callers continue to work. New callers should use `questions`.
191
- question: {
192
- type: "string",
193
- description:
194
- "Legacy: the single clarifying question. Prefer `questions[]` for new code.",
195
- },
196
- description: {
197
- type: "string",
198
- description:
199
- "Legacy: optional one-line context shown beneath the question. Prefer `questions[].description`.",
200
- },
201
- options: {
202
- type: "array",
203
- minItems: 2,
204
- maxItems: 4,
205
- description:
206
- "Legacy: 2–4 structured options. Prefer `questions[].options`. The UI always appends a free-text fallback slot, so do not include a 'something else' option here.",
207
- items: OPTION_ITEMS_SCHEMA,
208
- },
209
- freeTextPlaceholder: {
210
- type: "string",
211
- description:
212
- "Legacy: optional placeholder text for the free-text fallback input. Prefer `questions[].freeTextPlaceholder`.",
213
- },
214
167
  },
215
- // No top-level `required` — caller must supply either `questions`
216
- // or the legacy flat trio (`question` + `options`). Enforced in Zod.
168
+ required: ["questions"],
217
169
  },
218
170
 
219
171
  async execute(
@@ -228,18 +180,7 @@ export const askQuestionTool = {
228
180
  };
229
181
  }
230
182
 
231
- // Normalize legacy flat input into a one-element `questions` batch so
232
- // downstream code only has to deal with the batched shape. The refine
233
- // above guarantees `question` and `options` are present whenever
234
- // `questions` is absent.
235
- const questions: SingleQuestion[] = parsed.data.questions ?? [
236
- {
237
- question: parsed.data.question!,
238
- description: parsed.data.description,
239
- options: parsed.data.options!,
240
- freeTextPlaceholder: parsed.data.freeTextPlaceholder,
241
- },
242
- ];
183
+ const questions: SingleQuestion[] = parsed.data.questions;
243
184
 
244
185
  const prompter = new QuestionPrompter();
245
186
  const result = await prompter.prompt({
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Shared `'error'`-event handler for `fs.watch()` FSWatchers.
3
+ *
4
+ * An `FSWatcher` is an EventEmitter. When the underlying inotify/FSEvents
5
+ * backend fails *after* the watch was established — e.g. ENOSPC when the
6
+ * kernel's `fs.inotify.max_user_watches` limit is exhausted while walking a
7
+ * recursive watch into a large subtree (a plugin's `node_modules`), or ENXIO
8
+ * when a Unix socket file appears in a watched directory — the failure is
9
+ * delivered asynchronously as an `'error'` event rather than a synchronous
10
+ * throw from `watch()`. An emitter with no `'error'` listener rethrows, which
11
+ * surfaces as an `uncaughtException` and takes the whole daemon down (→
12
+ * CrashLoopBackOff).
13
+ *
14
+ * Attaching this handler degrades the failure to "this watcher stops
15
+ * delivering events", in line with the daemon startup philosophy: a subsystem
16
+ * failure must never crash the process.
17
+ */
18
+
19
+ import type { FSWatcher } from "node:fs";
20
+
21
+ import type { Logger } from "pino";
22
+
23
+ /**
24
+ * Attach a resilient `'error'` listener so async FSWatcher failures are logged
25
+ * instead of crashing the process. Pass the owning module's logger and the
26
+ * watched directory for diagnostic context.
27
+ */
28
+ export function attachFsWatcherErrorHandler(
29
+ watcher: FSWatcher,
30
+ log: Logger,
31
+ dir: string,
32
+ ): void {
33
+ watcher.on("error", (err) => {
34
+ log.warn({ err, dir }, "FSWatcher error (non-fatal, continuing)");
35
+ });
36
+ }