@vellumai/assistant 0.10.10-dev.202607202325.d24b0a4 → 0.10.10-dev.202607210140.cb3a413

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 (39) hide show
  1. package/package.json +1 -1
  2. package/src/__tests__/anthropic-error-formatting.test.ts +9 -0
  3. package/src/__tests__/conversation-error.test.ts +53 -0
  4. package/src/__tests__/conversation-retry-route.test.ts +36 -2
  5. package/src/__tests__/conversation-runtime-assembly.test.ts +116 -0
  6. package/src/__tests__/empty-response-hook.test.ts +61 -0
  7. package/src/__tests__/gemini-provider.test.ts +9 -0
  8. package/src/__tests__/jobs-store-qdrant-breaker.test.ts +14 -1
  9. package/src/__tests__/worker-entrypoint-guards.test.ts +32 -0
  10. package/src/__tests__/worker-pid-file-guard.test.ts +24 -0
  11. package/src/context/refusal-quarantine.ts +87 -27
  12. package/src/daemon/conversation-error.ts +19 -0
  13. package/src/daemon/conversation-process.ts +13 -1
  14. package/src/ipc/assistant-server.ts +2 -0
  15. package/src/ipc/routes/__tests__/conversation-sync-ipc-routes.test.ts +96 -0
  16. package/src/ipc/routes/conversation-sync-ipc-routes.ts +65 -0
  17. package/src/monitoring/worker.ts +42 -33
  18. package/src/persistence/delivery-crud.ts +54 -15
  19. package/src/persistence/migrations/341-sweep-cacheless-graph-node-vectors.test.ts +7 -1
  20. package/src/plugins/defaults/memory/worker.ts +16 -9
  21. package/src/providers/anthropic/client.ts +9 -1
  22. package/src/providers/gemini/client.ts +7 -3
  23. package/src/providers/openai/__tests__/api-error-normalization.test.ts +11 -0
  24. package/src/providers/openai/api-error-normalization.ts +7 -0
  25. package/src/runtime/assistant-stream-state.ts +11 -0
  26. package/src/runtime/routes/__tests__/inference-send-routes.test.ts +51 -0
  27. package/src/runtime/routes/conversation-management-routes.ts +11 -4
  28. package/src/runtime/routes/conversation-routes.ts +2 -1
  29. package/src/runtime/routes/inbound-stages/background-dispatch.test.ts +51 -0
  30. package/src/runtime/routes/inbound-stages/background-dispatch.ts +32 -12
  31. package/src/runtime/routes/inference-send-routes.ts +30 -1
  32. package/src/runtime/slack-reply-session.ts +9 -0
  33. package/src/runtime/sync/resource-sync-events.ts +12 -0
  34. package/src/runtime/sync/worker-daemon-notify.test.ts +69 -0
  35. package/src/runtime/sync/worker-daemon-notify.ts +63 -0
  36. package/src/schedule/worker.ts +33 -25
  37. package/src/util/errors.ts +1 -0
  38. package/src/util/provider-error-patterns.ts +6 -0
  39. package/src/util/worker-process.ts +19 -8
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.10.10-dev.202607202325.d24b0a4",
3
+ "version": "0.10.10-dev.202607210140.cb3a413",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -205,6 +205,15 @@ describe("AnthropicProvider — semantic reason stamping", () => {
205
205
  ),
206
206
  reason: "insufficient_credits",
207
207
  },
208
+ {
209
+ name: "daily-limit body code → daily_limit_reached (before insufficient_credits)",
210
+ error: new FakeAPIError(
211
+ 402,
212
+ '{"code":"daily_limit_reached","detail":"Daily credit limit reached"}',
213
+ anthropicBody("invalid_request_error"),
214
+ ),
215
+ reason: "daily_limit_reached",
216
+ },
208
217
  {
209
218
  name: "5xx → server_error",
210
219
  error: new FakeAPIError(503, "internal", anthropicBody("api_error")),
@@ -1015,6 +1015,59 @@ describe("classifyConversationError", () => {
1015
1015
  expect(result.errorCategory).toBe("context_too_large");
1016
1016
  });
1017
1017
 
1018
+ it("routes reason=daily_limit_reached to PROVIDER_BILLING/daily_limit_reached under managed-proxy", () => {
1019
+ providerRoutingSources["vercel-ai-gateway"] = "managed-proxy";
1020
+ const err = new ProviderError(
1021
+ 'Vercel AI Gateway API error (402): {"code":"daily_limit_reached","detail":"Daily credit limit reached"}',
1022
+ "vercel-ai-gateway",
1023
+ 402,
1024
+ { reason: "daily_limit_reached" },
1025
+ );
1026
+
1027
+ const result = classifyConversationError(err, baseCtx);
1028
+
1029
+ expect(result.code).toBe("PROVIDER_BILLING");
1030
+ expect(result.errorCategory).toBe("daily_limit_reached");
1031
+ expect(result.retryable).toBe(false);
1032
+ expect(result.userMessage).toContain("daily credit limit");
1033
+ expect(result.userMessage).toContain("Billing settings");
1034
+ });
1035
+
1036
+ it("classifies reason=daily_limit_reached as daily_limit_reached even when the routing map says user-key", () => {
1037
+ // Per-connection platform-auth routes can leave the global routing map
1038
+ // at user-key; the stamped reason comes only from the platform proxy's
1039
+ // body code, so it must win regardless of the map.
1040
+ providerRoutingSources.openai = "user-key";
1041
+ const err = new ProviderError(
1042
+ 'OpenAI API error (402): {"code":"daily_limit_reached","detail":"Daily credit limit reached"}',
1043
+ "openai",
1044
+ 402,
1045
+ { reason: "daily_limit_reached" },
1046
+ );
1047
+
1048
+ const result = classifyConversationError(err, baseCtx);
1049
+
1050
+ expect(result.code).toBe("PROVIDER_BILLING");
1051
+ expect(result.errorCategory).toBe("daily_limit_reached");
1052
+ expect(result.retryable).toBe(false);
1053
+ });
1054
+
1055
+ it("keeps a plain managed-proxy 402 without the daily-limit code as credits_exhausted", () => {
1056
+ providerRoutingSources.openrouter = "managed-proxy";
1057
+ const err = new ProviderError(
1058
+ "OpenRouter API error (402): Payment Required",
1059
+ "openrouter",
1060
+ 402,
1061
+ { reason: "insufficient_credits" },
1062
+ );
1063
+
1064
+ const result = classifyConversationError(err, baseCtx);
1065
+
1066
+ expect(result.code).toBe("PROVIDER_BILLING");
1067
+ expect(result.errorCategory).toBe("credits_exhausted");
1068
+ expect(result.retryable).toBe(false);
1069
+ });
1070
+
1018
1071
  it("honors a stamped reason on a statusless ProviderError (no HTTP status)", () => {
1019
1072
  // SDK streaming failures throw with statusCode undefined but can still
1020
1073
  // carry a reason; it must classify semantically, not fall to the fallback.
@@ -29,6 +29,8 @@ mock.module("../daemon/conversation-process.js", () => ({
29
29
  ) =>
30
30
  metadata?.hidden === true ||
31
31
  typeof metadata?.backgroundEventSource === "string",
32
+ isBackgroundEventMetadata: (metadata: Record<string, unknown> | undefined) =>
33
+ typeof metadata?.backgroundEventSource === "string",
32
34
  }));
33
35
 
34
36
  mock.module("../daemon/handlers/conversations.js", () => ({
@@ -314,7 +316,7 @@ describe("POST /v1/conversations/:id/retry", () => {
314
316
  expect(typeof (options as { onEvent?: unknown }).onEvent).toBe("function");
315
317
  });
316
318
 
317
- test("hidden machine-signal anchor re-runs as a hidden prompt", async () => {
319
+ test("background-event anchor re-runs hidden AND non-interactive", async () => {
318
320
  discardResult = {
319
321
  anchor: anchorRow({
320
322
  metadata: JSON.stringify({ backgroundEventSource: "schedule" }),
@@ -333,8 +335,40 @@ describe("POST /v1/conversations/:id/retry", () => {
333
335
  expect(res.status).toBe(202);
334
336
  await settle();
335
337
 
338
+ // A scheduled/wake anchor was dispatched non-interactively, so the retry
339
+ // reproduces that background permission mode instead of a foreground chat.
340
+ const [, , options] = ctx.runAgentLoop.mock.calls[0];
341
+ expect(options).toMatchObject({
342
+ isHiddenPrompt: true,
343
+ isInteractive: false,
344
+ });
345
+ });
346
+
347
+ test("hidden non-background anchor re-runs hidden but stays interactive", async () => {
348
+ // A hidden `POST /messages` send (e.g. a proactive greeting from the web
349
+ // client) is echo-suppressed but was dispatched interactively — only the
350
+ // background-event marker flips a retry to non-interactive.
351
+ discardResult = {
352
+ anchor: anchorRow({ metadata: JSON.stringify({ hidden: true }) }),
353
+ deletedMessageIds: ["assistant-msg-1"],
354
+ };
355
+ const ctx = makeConversation();
356
+ activeConversation = ctx.conversation;
357
+
358
+ const res = await callHandler(
359
+ retryHandler,
360
+ makeRequest(),
361
+ { id: "conv-retry-test" },
362
+ 202,
363
+ );
364
+ expect(res.status).toBe(202);
365
+ await settle();
366
+
336
367
  const [, , options] = ctx.runAgentLoop.mock.calls[0];
337
- expect(options).toMatchObject({ isHiddenPrompt: true });
368
+ expect(options).toMatchObject({
369
+ isHiddenPrompt: true,
370
+ isInteractive: true,
371
+ });
338
372
  });
339
373
 
340
374
  test("busy conversation → 409 without claiming processing", async () => {
@@ -6400,6 +6400,122 @@ describe("assembleSlackChronologicalMessages", () => {
6400
6400
  expect(serialized).toContain("hi assistant");
6401
6401
  expect(serialized).toContain("back to normal");
6402
6402
  });
6403
+
6404
+ test("keeps a sibling thread's tool pair interleaved inside a refused exchange", () => {
6405
+ // @alice's flagged prompt roots her thread and the refusal fallback lands
6406
+ // back in it. In between, @bob's own thread runs a tool call: the assistant
6407
+ // posts a Slack-visible interim + `tool_use` (keyed to @bob's thread) and
6408
+ // the tool returns a synthetic `tool_result` with no Slack provenance (keys
6409
+ // `null`).
6410
+ //
6411
+ // The null-keyed result must be tied back to its @bob `tool_use` and kept —
6412
+ // dropping it as refused-exchange churn would orphan the sibling `tool_use`
6413
+ // the walk-back leaves in place, and orphan-tool pruning already ran during
6414
+ // rendering, so that half-pair would ship to the provider and hard-fail.
6415
+ const CHANNEL_ID = "C0MULTI03";
6416
+ const SLACK_CAPS_CHANNEL: ChannelCapabilities = {
6417
+ channel: "slack",
6418
+ dashboardCapable: false,
6419
+ supportsDynamicUi: false,
6420
+ supportsVoiceInput: false,
6421
+ chatType: "channel",
6422
+ };
6423
+ const T_HI = "1699971900.000100";
6424
+ const T_PROMPT = "1699972000.000200"; // roots @alice's thread (refused)
6425
+ const T_BOB_PROMPT = "1699972010.000250"; // roots @bob's sibling thread
6426
+ const T_BOB_TOOLUSE = "1699972020.000300"; // assistant interim + tool_use, @bob's thread
6427
+ const T_FALLBACK = "1699972060.000400"; // assistant refusal, in @alice's thread
6428
+ const T_LATER = "1699972200.000500";
6429
+ const meta = (
6430
+ channelTs: string,
6431
+ displayName: string,
6432
+ threadTs?: string,
6433
+ ): SlackMessageMetadata => ({
6434
+ source: "slack",
6435
+ channelId: CHANNEL_ID,
6436
+ channelTs,
6437
+ ...(threadTs ? { threadTs } : {}),
6438
+ eventKind: "message",
6439
+ displayName,
6440
+ });
6441
+ const rows: SlackTranscriptInputRow[] = [
6442
+ row(
6443
+ "user",
6444
+ "hi assistant",
6445
+ 1699971900_000,
6446
+ metadataEnvelope(meta(T_HI, "@alice")),
6447
+ ),
6448
+ row(
6449
+ "user",
6450
+ "disallowed question",
6451
+ 1699972000_000,
6452
+ metadataEnvelope(meta(T_PROMPT, "@alice")),
6453
+ ),
6454
+ // @bob opens a sibling thread with a request that runs a tool.
6455
+ row(
6456
+ "user",
6457
+ "bob needs help",
6458
+ 1699972010_000,
6459
+ metadataEnvelope(meta(T_BOB_PROMPT, "@bob")),
6460
+ ),
6461
+ // Assistant interim reply + tool_use for @bob — Slack-visible, threaded
6462
+ // under @bob's prompt, so it keys to @bob's thread.
6463
+ {
6464
+ role: "assistant",
6465
+ content: JSON.stringify([
6466
+ { type: "text", text: "checking for bob" },
6467
+ { type: "tool_use", id: "tu_sib", name: "search", input: { q: "y" } },
6468
+ ]),
6469
+ createdAt: 1699972020_000,
6470
+ metadata: metadataEnvelope(
6471
+ meta(T_BOB_TOOLUSE, "@assistant", T_BOB_PROMPT),
6472
+ ),
6473
+ },
6474
+ // @bob's synthetic tool_result — NOT sent to Slack, so no slackMeta.
6475
+ {
6476
+ role: "user",
6477
+ content: JSON.stringify([
6478
+ { type: "tool_result", tool_use_id: "tu_sib", content: "for bob" },
6479
+ ]),
6480
+ createdAt: 1699972030_000,
6481
+ metadata: metadataEnvelope(null),
6482
+ },
6483
+ row(
6484
+ "assistant",
6485
+ REFUSAL_FALLBACK_TEXT,
6486
+ 1699972060_000,
6487
+ metadataEnvelope(meta(T_FALLBACK, "@assistant", T_PROMPT)),
6488
+ ),
6489
+ row(
6490
+ "user",
6491
+ "back to normal",
6492
+ 1699972200_000,
6493
+ metadataEnvelope(meta(T_LATER, "@alice")),
6494
+ ),
6495
+ ];
6496
+
6497
+ const result = assembleSlackChronologicalMessages(rows, SLACK_CAPS_CHANNEL);
6498
+ expect(result).not.toBeNull();
6499
+ const blocks = result!.flatMap((m) => m.content);
6500
+ // @bob's tool pair survives intact — both halves, same id, no orphan.
6501
+ const toolUseIds = blocks.flatMap((b) =>
6502
+ b.type === "tool_use" ? [b.id] : [],
6503
+ );
6504
+ const toolResultIds = blocks.flatMap((b) =>
6505
+ b.type === "tool_result" ? [b.tool_use_id] : [],
6506
+ );
6507
+ expect(toolUseIds).toEqual(["tu_sib"]);
6508
+ expect(toolResultIds).toEqual(["tu_sib"]);
6509
+ const serialized = JSON.stringify(result);
6510
+ // The refusal and the prompt that tripped it are both gone …
6511
+ expect(serialized).not.toContain(REFUSAL_FALLBACK_TEXT);
6512
+ expect(serialized).not.toContain("disallowed question");
6513
+ // … @bob's whole sibling exchange and the benign turns are untouched.
6514
+ expect(serialized).toContain("bob needs help");
6515
+ expect(serialized).toContain("checking for bob");
6516
+ expect(serialized).toContain("hi assistant");
6517
+ expect(serialized).toContain("back to normal");
6518
+ });
6403
6519
  });
6404
6520
 
6405
6521
  // ---------------------------------------------------------------------------
@@ -634,6 +634,31 @@ describe("quarantineRefusedExchanges", () => {
634
634
  ).toBe(false);
635
635
  });
636
636
 
637
+ test("walks back over a web-search run to the genuine prompt", () => {
638
+ const serverToolUseTurn: Message = {
639
+ role: "assistant",
640
+ content: [
641
+ { type: "server_tool_use", id: "stu_1", name: "web_search", input: {} },
642
+ ],
643
+ };
644
+ const webSearchResultTurn: Message = {
645
+ role: "user",
646
+ content: [
647
+ { type: "web_search_tool_result", tool_use_id: "stu_1", content: [] },
648
+ ],
649
+ };
650
+ const history = [
651
+ userPrompt("flagged prompt"),
652
+ serverToolUseTurn,
653
+ webSearchResultTurn,
654
+ refusalFallbackTurn,
655
+ userPrompt("follow-up"),
656
+ ];
657
+ const { messages, droppedExchanges } = quarantineRefusedExchanges(history);
658
+ expect(droppedExchanges).toBe(1);
659
+ expect(messages).toEqual([userPrompt("follow-up")]);
660
+ });
661
+
637
662
  test("handles a marker at index 0 with no preceding prompt", () => {
638
663
  const history = [refusalFallbackTurn, userPrompt("next")];
639
664
  const { messages, droppedExchanges } = quarantineRefusedExchanges(history);
@@ -720,6 +745,42 @@ describe("computeRefusedExchangeDrops — thread-scoped pairing", () => {
720
745
  const kept = messages.filter((_, i) => !dropIndices.has(i));
721
746
  expect(kept).toEqual([userPrompt("legacy provenance-less prompt")]);
722
747
  });
748
+
749
+ test("keeps a sibling thread's intact tool pair interleaved before the fallback", () => {
750
+ // A sibling thread's exchange lands between the refused prompt and the
751
+ // fallback: its assistant `tool_use` is Slack-visible (keyed to the sibling
752
+ // thread B) but its synthetic `tool_result` has no provenance (keyed null).
753
+ // The null-keyed result must be tied back to its sibling `tool_use` and left
754
+ // in place — dropping it as generic churn would orphan the kept `tool_use`
755
+ // (the transcript's orphan-tool prune has already run) and hard-fail the
756
+ // provider, the exact failure this pairing guards against.
757
+ const messages = [
758
+ userPrompt("flagged prompt"), // 0, thread P (refused)
759
+ toolUseTurn("tu_sib"), // 1, thread B (sibling, Slack-visible)
760
+ toolResultTurn("tu_sib"), // 2, null (sibling synthetic result)
761
+ refusalFallbackTurn, // 3, thread P
762
+ ];
763
+ const threadKeys = ["P", "B", null, "P"];
764
+ const { dropIndices, droppedExchanges } = computeRefusedExchangeDrops(
765
+ messages,
766
+ { threadKeys },
767
+ );
768
+ expect(droppedExchanges).toBe(1);
769
+ // Only the refused prompt and its fallback go; the sibling pair is intact.
770
+ expect([...dropIndices].sort((a, b) => a - b)).toEqual([0, 3]);
771
+ const kept = messages.filter((_, i) => !dropIndices.has(i));
772
+ expect(kept).toEqual([toolUseTurn("tu_sib"), toolResultTurn("tu_sib")]);
773
+ // No half-pair: every surviving tool_use is matched by its tool_result.
774
+ const producedIds = kept.flatMap((m) =>
775
+ m.content.flatMap((b) => (b.type === "tool_use" ? [b.id] : [])),
776
+ );
777
+ const consumedIds = kept.flatMap((m) =>
778
+ m.content.flatMap((b) =>
779
+ b.type === "tool_result" ? [b.tool_use_id] : [],
780
+ ),
781
+ );
782
+ expect(consumedIds).toEqual(producedIds);
783
+ });
723
784
  });
724
785
 
725
786
  describe("empty-response user-prompt-submit hook", () => {
@@ -1457,6 +1457,15 @@ describe("GeminiProvider", () => {
1457
1457
  }
1458
1458
  });
1459
1459
 
1460
+ test("maps a daily-limit 402 body code to daily_limit_reached", async () => {
1461
+ expect(
1462
+ await reasonForApiError(
1463
+ 402,
1464
+ '{"code":"daily_limit_reached","detail":"Daily credit limit reached"}',
1465
+ ),
1466
+ ).toBe("daily_limit_reached");
1467
+ });
1468
+
1460
1469
  test("maps 404 / NOT_FOUND to model_not_found", async () => {
1461
1470
  expect(
1462
1471
  await reasonForApiError(404, "NOT_FOUND: model does not exist"),
@@ -1,4 +1,11 @@
1
- import { beforeAll, beforeEach, describe, expect, test } from "bun:test";
1
+ import {
2
+ afterEach,
3
+ beforeAll,
4
+ beforeEach,
5
+ describe,
6
+ expect,
7
+ test,
8
+ } from "bun:test";
2
9
 
3
10
  import { eq } from "drizzle-orm";
4
11
 
@@ -26,6 +33,12 @@ describe("claimMemoryJobs with Qdrant circuit breaker", () => {
26
33
  _resetQdrantBreaker();
27
34
  });
28
35
 
36
+ // bun shares module state across a run, so a breaker left open by these cases
37
+ // (the last one leaves it open) would leak into later test files — reset here.
38
+ afterEach(() => {
39
+ _resetQdrantBreaker();
40
+ });
41
+
29
42
  test("claims embed jobs when circuit breaker is closed (healthy)", () => {
30
43
  enqueueMemoryJob("embed_segment", { segmentId: "seg-1" });
31
44
  enqueueMemoryJob("embed_graph_node", { nodeId: "node-1" });
@@ -23,6 +23,19 @@ import { Glob } from "bun";
23
23
  const DISABLE_CALL = "disableStreamSeqStamping()";
24
24
  const PID_GUARD_CALL = "startWorkerPidFileGuard(";
25
25
 
26
+ /**
27
+ * The first call each entrypoint makes that can run orphaned schedule/job
28
+ * work. The PID guard must be armed before this — its on-arm identity check
29
+ * evicts a worker superseded at startup before the call runs. Every discovered
30
+ * entrypoint must have an entry here, so a new worker forces its author to
31
+ * declare (and order) its work-start.
32
+ */
33
+ const WORK_START_MARKERS: Record<string, string> = {
34
+ "schedule/worker.ts": "void tick()",
35
+ "monitoring/worker.ts": "startResourceSampler(",
36
+ "plugins/defaults/memory/worker.ts": "startMemoryJobsWorkerLoop(",
37
+ };
38
+
26
39
  function findWorkerEntrypoints(): string[] {
27
40
  const srcRoot = join(process.cwd(), "src");
28
41
  const glob = new Glob("**/worker.ts");
@@ -64,4 +77,23 @@ describe("worker entrypoint guards", () => {
64
77
  "worker (one its PID file stops naming) evicts itself.",
65
78
  ).toEqual([]);
66
79
  });
80
+
81
+ test("every worker entrypoint arms the PID guard before starting work", () => {
82
+ const offenders = findWorkerEntrypoints().filter((file) => {
83
+ const marker = WORK_START_MARKERS[file];
84
+ if (marker == null) {
85
+ return true; // unregistered entrypoint — force a marker to be added
86
+ }
87
+ const source = readFileSync(join(process.cwd(), "src", file), "utf8");
88
+ const guardAt = source.indexOf(PID_GUARD_CALL);
89
+ const workAt = source.indexOf(marker);
90
+ return guardAt < 0 || workAt < 0 || guardAt > workAt;
91
+ });
92
+ expect(
93
+ offenders,
94
+ "Each worker must arm the PID guard before its work-start call " +
95
+ `(see WORK_START_MARKERS) so the guard's on-arm check evicts a ` +
96
+ "worker superseded at startup before it runs orphaned work.",
97
+ ).toEqual([]);
98
+ });
67
99
  });
@@ -73,6 +73,30 @@ describe("startWorkerPidFileGuard", () => {
73
73
  expect(evictions).toEqual([]);
74
74
  });
75
75
 
76
+ test("evicts synchronously on arm when the file already names a successor", () => {
77
+ const path = mkPidFile(String(process.pid + 1));
78
+ const { evictions } = startGuard(path);
79
+ // No await: the on-arm check runs synchronously inside the guard, so a
80
+ // worker superseded before it starts work evicts without any interval
81
+ // elapsing. This is the property the workers rely on when they arm the
82
+ // guard right before their first tick.
83
+ expect(evictions.length).toBe(1);
84
+ expect(evictions[0]).toContain(String(process.pid + 1));
85
+ });
86
+
87
+ test("evicts synchronously on arm when the file is already missing", () => {
88
+ const path = mkPidFile(String(process.pid));
89
+ rmSync(path);
90
+ const { evictions } = startGuard(path);
91
+ expect(evictions.length).toBe(1);
92
+ });
93
+
94
+ test("does not evict on arm while the file names this process", () => {
95
+ const path = mkPidFile(String(process.pid));
96
+ const { evictions } = startGuard(path);
97
+ expect(evictions).toEqual([]);
98
+ });
99
+
76
100
  test("evicts exactly once when the file names a successor", async () => {
77
101
  const path = mkPidFile(String(process.pid));
78
102
  const { evictions } = startGuard(path);
@@ -37,12 +37,18 @@ import type { ContentBlock, Message } from "../providers/types.js";
37
37
  export const REFUSAL_FALLBACK_TEXT =
38
38
  "Sorry — I wasn't able to generate a response to that. Please try rephrasing or asking in a different way.";
39
39
 
40
- /** A user-role message carrying only tool results, not a fresh prompt. */
40
+ /**
41
+ * A user-role message carrying only tool results — local `tool_result` or
42
+ * server `web_search_tool_result` — not a fresh prompt.
43
+ */
41
44
  export function isToolResultMessage(message: Message): boolean {
42
45
  return (
43
46
  message.role === "user" &&
44
47
  message.content.length > 0 &&
45
- message.content.every((block) => block.type === "tool_result")
48
+ message.content.every(
49
+ (block) =>
50
+ block.type === "tool_result" || block.type === "web_search_tool_result",
51
+ )
46
52
  );
47
53
  }
48
54
 
@@ -63,6 +69,36 @@ export function isRefusalFallbackMessage(message: Message): boolean {
63
69
  );
64
70
  }
65
71
 
72
+ /**
73
+ * Whether a synthetic (always null-keyed) tool-result row pairs with a
74
+ * `tool_use` / `server_tool_use` produced in a *sibling* Slack thread — a
75
+ * non-null thread other than the refused fallback's. Such a result belongs to
76
+ * that sibling exchange, so the thread-scoped walk-back must leave it in place:
77
+ * it keeps the sibling use block, and dropping only the result would strand a
78
+ * half-pair past the transcript's earlier orphan-tool prune. Returns false for
79
+ * a result whose use block is same-thread, itself null-keyed, or absent — that
80
+ * churn is the refused exchange's and is dropped.
81
+ */
82
+ function pairsWithSiblingThreadToolUse(
83
+ message: Message,
84
+ toolUseThreadKey: ReadonlyMap<string, string | null>,
85
+ fallbackThreadKey: string | null,
86
+ ): boolean {
87
+ if (!isToolResultMessage(message)) {
88
+ return false;
89
+ }
90
+ return message.content.some((block) => {
91
+ if (
92
+ block.type !== "tool_result" &&
93
+ block.type !== "web_search_tool_result"
94
+ ) {
95
+ return false;
96
+ }
97
+ const toolUseKey = toolUseThreadKey.get(block.tool_use_id);
98
+ return toolUseKey != null && toolUseKey !== fallbackThreadKey;
99
+ });
100
+ }
101
+
66
102
  /**
67
103
  * Indices of every message belonging to a previously-refused exchange: for each
68
104
  * assistant message that is exactly the refusal fallback, its own index plus the
@@ -84,13 +120,16 @@ export function isRefusalFallbackMessage(message: Message): boolean {
84
120
  * walk-back keeps only the refused exchange and leaves the rest in place:
85
121
  * - a row in another (non-null) thread is a genuine interleaved post —
86
122
  * left in place;
87
- * - a null-keyed row has no Slack provenance. Synthetic tool churn
88
- * (assistant `tool_use` turns and their `tool_result` rows) is never
89
- * Slack-visible, so it always keys `null` even mid-thread; it belongs to
90
- * the refused exchange and is dropped. Leaving it behind would strand
91
- * half a tool pair, and the Slack transcript's orphan-tool prune runs
92
- * *before* this sweep, so nothing would repair the resulting invalid
93
- * history. A null-keyed genuine user prompt is a different turn
123
+ * - a null-keyed row has no Slack provenance. A synthetic `tool_result`
124
+ * (never Slack-visible, so always null-keyed) is tied back to its
125
+ * `tool_use` by id: if that `tool_use` sits in another (non-null) thread,
126
+ * the pair is a sibling exchange's — the walk-back keeps the `tool_use`,
127
+ * so its result is kept too rather than stranded as a half-pair. Any other
128
+ * null-keyed tool churn (its `tool_use` is same-thread or itself
129
+ * null-keyed) belongs to the refused exchange and is dropped; the Slack
130
+ * transcript's orphan-tool prune runs *before* this sweep, so a stranded
131
+ * half-pair would otherwise reach the provider as invalid history. A
132
+ * null-keyed genuine user prompt is a different turn
94
133
  * (legacy/provenance-less), so it is left in place and the walk continues
95
134
  * to the same-thread prompt.
96
135
  * A `null` fallback key (non-Slack / legacy) always uses adjacency.
@@ -108,21 +147,32 @@ export function computeRefusedExchangeDrops(
108
147
  droppedExchanges: number;
109
148
  } {
110
149
  const { threadKeys } = opts;
111
- // A thread key only carries pairing signal when it is shared: a lone
112
- // top-level or DM row has its own `channelTs` as its key, so treating it as a
113
- // one-message "thread" would strand the prompt. Count keys once so each
114
- // fallback can tell whether it sits in a real (multi-row) thread.
150
+ // Two lookups derived from the per-message thread keys (aligned 1:1 with
151
+ // `messages`):
152
+ // - `sharedThreadKeys`: keys appearing on more than one row. A thread key
153
+ // only carries pairing signal when it is shared — a lone top-level/DM row
154
+ // keys by its own `channelTs`, so treating it as a one-message "thread"
155
+ // would strand the prompt.
156
+ // - `toolUseThreadKey`: each `tool_use` / `server_tool_use` id → the thread
157
+ // key of the row that produced it, so a synthetic (always null-keyed)
158
+ // result row can be tied back to the thread its use block belongs to.
115
159
  const sharedThreadKeys = new Set<string>();
160
+ const toolUseThreadKey = new Map<string, string | null>();
116
161
  if (threadKeys) {
117
162
  const seen = new Set<string>();
118
- for (const key of threadKeys) {
119
- if (key === null) {
120
- continue;
163
+ for (let i = 0; i < messages.length; i++) {
164
+ const key = threadKeys[i] ?? null;
165
+ if (key !== null) {
166
+ if (seen.has(key)) {
167
+ sharedThreadKeys.add(key);
168
+ } else {
169
+ seen.add(key);
170
+ }
121
171
  }
122
- if (seen.has(key)) {
123
- sharedThreadKeys.add(key);
124
- } else {
125
- seen.add(key);
172
+ for (const block of messages[i].content) {
173
+ if (block.type === "tool_use" || block.type === "server_tool_use") {
174
+ toolUseThreadKey.set(block.id, key);
175
+ }
126
176
  }
127
177
  }
128
178
  }
@@ -145,15 +195,25 @@ export function computeRefusedExchangeDrops(
145
195
  for (let s = r - 1; s >= 0; s--) {
146
196
  const isGenuinePrompt =
147
197
  messages[s].role === "user" && !isToolResultMessage(messages[s]);
148
- // Under thread scope, leave rows outside the fallback's thread in place —
149
- // genuine interleaved posts from other (non-null) threads, and
150
- // provenance-less genuine prompts (someone else's turn). Drop only
151
- // null-keyed tool churn: this refused exchange's own synthetic
152
- // tool_use / tool_result rows, which would otherwise strand half a tool
153
- // pair past the earlier orphan prune.
198
+ // Under thread scope, leave rows outside the fallback's thread in place:
199
+ // - a genuine interleaved post from another (non-null) thread;
200
+ // - a provenance-less genuine prompt (someone else's turn);
201
+ // - a synthetic `tool_result` whose `tool_use` sits in a sibling thread —
202
+ // dropping it would orphan that kept sibling `tool_use`.
203
+ // Everything else outside the thread is this refused exchange's own
204
+ // null-keyed tool churn, dropped so it can't strand half a tool pair past
205
+ // the earlier orphan prune.
154
206
  if (threadScope) {
155
207
  const key = threadScope[s] ?? null;
156
- if (key !== fallbackThreadKey && (key !== null || isGenuinePrompt)) {
208
+ const keepOutsideThread =
209
+ key !== null ||
210
+ isGenuinePrompt ||
211
+ pairsWithSiblingThreadToolUse(
212
+ messages[s],
213
+ toolUseThreadKey,
214
+ fallbackThreadKey,
215
+ );
216
+ if (key !== fallbackThreadKey && keepOutsideThread) {
157
217
  continue;
158
218
  }
159
219
  }
@@ -562,6 +562,12 @@ function reasonToClassification(
562
562
  return managed
563
563
  ? managedBalanceClassification()
564
564
  : providerBillingClassification();
565
+ case "daily_limit_reached":
566
+ // The reason is stamped only from the platform proxy's
567
+ // `"code":"daily_limit_reached"` body, so it is authoritative on its
568
+ // own — the global routing map can lag per-connection platform-auth
569
+ // routes and must not downgrade this to the generic billing surface.
570
+ return dailyLimitClassification();
565
571
  case "overloaded":
566
572
  return providerOverloadedClassification();
567
573
  case "server_error":
@@ -698,6 +704,19 @@ function providerBillingClassification(): Omit<
698
704
  };
699
705
  }
700
706
 
707
+ function dailyLimitClassification(): Omit<
708
+ ClassifiedConversationError,
709
+ "debugDetails"
710
+ > {
711
+ return {
712
+ code: "PROVIDER_BILLING",
713
+ userMessage:
714
+ "You've hit your daily credit limit. Raise the limit in Billing settings to keep going today.",
715
+ retryable: false,
716
+ errorCategory: "daily_limit_reached",
717
+ };
718
+ }
719
+
701
720
  // Shared classification producers — single source of `code`+`errorCategory`
702
721
  // for both the reason short-circuit and the reason-less fallback.
703
722