@cortexkit/opencode-magic-context 0.49.86 → 0.49.87

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 (142) hide show
  1. package/dist/auto-search-worker.js +13 -7
  2. package/dist/chunk-embedding-write-worker.js +4 -4
  3. package/dist/{compartment-chunk-embedding-ymc9mtwv.js → compartment-chunk-embedding-fey2bsyf.js} +3 -1
  4. package/dist/{conflict-warning-hook-a0wrnzch.js → conflict-warning-hook-kbq6ppjf.js} +2 -2
  5. package/dist/{context-xesm7rj3.js → context-gnk68pyy.js} +126 -46
  6. package/dist/{embedding-backfill-v6sw58m8.js → embedding-backfill-9khxv6a9.js} +4 -4
  7. package/dist/{embedding-cache-mgyr73ef.js → embedding-cache-zn4r1c31.js} +5 -1
  8. package/dist/features/magic-context/compartment-chunk-embedding.d.ts +1 -0
  9. package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
  10. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  11. package/dist/features/magic-context/dreamer/token-budget.d.ts +8 -3
  12. package/dist/features/magic-context/dreamer/token-budget.d.ts.map +1 -1
  13. package/dist/features/magic-context/memory/embedding-cache.d.ts +7 -0
  14. package/dist/features/magic-context/memory/embedding-cache.d.ts.map +1 -1
  15. package/dist/features/magic-context/search.d.ts +6 -0
  16. package/dist/features/magic-context/search.d.ts.map +1 -1
  17. package/dist/features/magic-context/tool-definition-tokens.d.ts +2 -0
  18. package/dist/features/magic-context/tool-definition-tokens.d.ts.map +1 -1
  19. package/dist/hooks/magic-context/auto-search-worker-client.d.ts.map +1 -1
  20. package/dist/hooks/magic-context/auto-search-worker-probe.fixture.d.ts +2 -0
  21. package/dist/hooks/magic-context/auto-search-worker-probe.fixture.d.ts.map +1 -0
  22. package/dist/hooks/magic-context/dropped-input-guard.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/emergency-fail-closed.d.ts +2 -0
  24. package/dist/hooks/magic-context/emergency-fail-closed.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/send-session-notification.d.ts +11 -1
  26. package/dist/hooks/magic-context/send-session-notification.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/transform.d.ts +1 -0
  28. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  29. package/dist/{index-7j2zv9nm.js → index-2qsca7h7.js} +47 -11
  30. package/dist/{index-25nktq8n.js → index-3jgzd7nz.js} +7 -7
  31. package/dist/{index-snbpdpa3.js → index-3pdknr07.js} +4 -4
  32. package/dist/{index-k0tb2z28.js → index-3x4qvp29.js} +2 -2
  33. package/dist/{index-d0rtbv0f.js → index-5nmqgvz2.js} +21 -14
  34. package/dist/{index-xrnhxkz7.js → index-60wnwcwz.js} +1 -1
  35. package/dist/{index-g6hfh4h4.js → index-6zewd2n5.js} +14 -8
  36. package/dist/{index-nny4gm06.js → index-74sh122g.js} +2 -2
  37. package/dist/{index-70cv85b0.js → index-78t37mcq.js} +2 -2
  38. package/dist/{index-stx8zd81.js → index-83qd3n7s.js} +2 -2
  39. package/dist/{index-jjvbk92s.js → index-9emdjcb5.js} +1 -1
  40. package/dist/{index-gxdc95cp.js → index-awyqqnd8.js} +585 -82
  41. package/dist/{index-022w6314.js → index-b364vr04.js} +109 -505
  42. package/dist/{index-4w5rx7de.js → index-bxrfq3mv.js} +1 -1
  43. package/dist/{index-1bqkqde0.js → index-c1s40xmj.js} +3 -3
  44. package/dist/{index-05bm2ndp.js → index-chpzb6xy.js} +1 -1
  45. package/dist/{index-ttk3trse.js → index-csztadkj.js} +46 -17
  46. package/dist/{index-798s7c8s.js → index-hdyfvdag.js} +1 -1
  47. package/dist/{index-4ntnt8ee.js → index-jka4y6mv.js} +1 -1
  48. package/dist/{index-w6v4dw5f.js → index-kmrv1fw3.js} +4 -4
  49. package/dist/{index-jrj95cce.js → index-m6dnydf8.js} +9 -2
  50. package/dist/{index-e32b3x4n.js → index-pmcvg3k1.js} +4 -4
  51. package/dist/{index-4dhv7mqz.js → index-qjwpqvnf.js} +48 -1
  52. package/dist/{index-xccywqdj.js → index-rvf1726x.js} +3 -3
  53. package/dist/{index-1pf5qrx4.js → index-vyfrgwhk.js} +3 -3
  54. package/dist/{index-s8ks5nz4.js → index-watde7a1.js} +2 -2
  55. package/dist/{v2/server-fzgyvsb1.js → index-y14pawe1.js} +3 -0
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +61 -52
  58. package/dist/{message-index-bounded-6fr624zf.js → message-index-bounded-r1qys471.js} +4 -4
  59. package/dist/migration-worker.js +3 -3
  60. package/dist/plugin/messages-transform.d.ts +3 -4
  61. package/dist/plugin/messages-transform.d.ts.map +1 -1
  62. package/dist/plugin/refusal-notice.d.ts +3 -0
  63. package/dist/plugin/refusal-notice.d.ts.map +1 -0
  64. package/dist/{project-embedding-registry-q80scexh.js → project-embedding-registry-8t0gwf59.js} +3 -3
  65. package/dist/raw-ordinal-warmup-worker.js +4 -4
  66. package/dist/{read-session-chunk-6wedfths.js → read-session-chunk-xv9f0wgb.js} +3 -3
  67. package/dist/{recomp-orchestrator-7ecg8ryx.js → recomp-orchestrator-2ztmtxt2.js} +18 -18
  68. package/dist/{render-yqp7q79f.js → render-d6q6h9hy.js} +10 -10
  69. package/dist/{rpc-notifications-t9q0ynq7.js → rpc-notifications-ta2zsxpq.js} +1 -1
  70. package/dist/{search-archive-r4h96j2z.js → search-archive-g96jn6p0.js} +5 -5
  71. package/dist/{search-bw22d7zc.js → search-d5aajhs3.js} +14 -14
  72. package/dist/{send-session-notification-7x518gew.js → send-session-notification-gzxz88vq.js} +1 -1
  73. package/dist/shared/assistant-message-extractor.d.ts +2 -0
  74. package/dist/shared/assistant-message-extractor.d.ts.map +1 -1
  75. package/dist/shared/prompt-async-transport.d.ts.map +1 -1
  76. package/dist/shared/rpc-notifications.d.ts +1 -1
  77. package/dist/shared/rpc-notifications.d.ts.map +1 -1
  78. package/dist/{storage-memory-e6a7mb0k.js → storage-memory-hhrvfw0x.js} +2 -2
  79. package/dist/{storage-tags-y2mrb8e6.js → storage-tags-f1ftvjpw.js} +2 -2
  80. package/dist/{transform-postprocess-phase-t99yj9vt.js → transform-postprocess-phase-b2yjw8by.js} +19 -19
  81. package/dist/v2/auto-search-worker.js +13 -7
  82. package/dist/v2/chunk-embedding-write-worker.js +4 -4
  83. package/dist/v2/{compartment-chunk-embedding-x6qw6mjk.js → compartment-chunk-embedding-knt2468v.js} +3 -1
  84. package/dist/v2/{context-k8sx1nyy.js → context-s86114yy.js} +219 -62
  85. package/dist/v2/{embedding-backfill-k8kqnwfq.js → embedding-backfill-tazkbpyg.js} +4 -4
  86. package/dist/v2/{embedding-cache-mgyr73ef.js → embedding-cache-zn4r1c31.js} +5 -1
  87. package/dist/v2/fold/native-replay.d.ts +3 -1
  88. package/dist/v2/fold/native-replay.d.ts.map +1 -1
  89. package/dist/v2/hidden-child-record.d.ts +1 -0
  90. package/dist/v2/hidden-child-record.d.ts.map +1 -1
  91. package/dist/v2/hidden-completion.d.ts.map +1 -1
  92. package/dist/v2/hooks/context.d.ts.map +1 -1
  93. package/dist/v2/{message-index-bounded-jqy7283g.js → message-index-bounded-b07r9cjv.js} +4 -4
  94. package/dist/v2/migration-worker.js +3 -3
  95. package/dist/v2/{project-embedding-registry-2jp1antr.js → project-embedding-registry-ah3gsg48.js} +3 -3
  96. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  97. package/dist/v2/{read-session-chunk-n3nhfvd7.js → read-session-chunk-38wdy8nd.js} +3 -3
  98. package/dist/v2/{recomp-orchestrator-ssde9ft1.js → recomp-orchestrator-kc62xgb9.js} +17 -17
  99. package/dist/v2/{render-fezgh7pa.js → render-j05per51.js} +10 -10
  100. package/dist/v2/{rpc-notifications-t9q0ynq7.js → rpc-notifications-ta2zsxpq.js} +1 -1
  101. package/dist/v2/{search-archive-zz1kza50.js → search-archive-b4ptw02k.js} +5 -5
  102. package/dist/v2/{search-m251amra.js → search-kg31ad2s.js} +13 -13
  103. package/dist/v2/{send-session-notification-p52rhjzy.js → send-session-notification-zazaxxpf.js} +1 -1
  104. package/dist/v2/{server-ps6rz88g.js → server-2p0qayr1.js} +1 -1
  105. package/dist/v2/{server-fsw8kbng.js → server-2r9btf0g.js} +46 -17
  106. package/dist/v2/{server-wdq85mxj.js → server-6250cxzs.js} +14 -8
  107. package/dist/v2/{server-brgandk4.js → server-6vnbz81n.js} +2 -2
  108. package/dist/v2/{server-jjvbk92s.js → server-9emdjcb5.js} +1 -1
  109. package/dist/v2/{server-ap81bk3c.js → server-9n2qgk29.js} +1 -1
  110. package/dist/v2/{server-mbkwcwgw.js → server-axdmkvd5.js} +2 -2
  111. package/dist/v2/{server-2k8tkbhz.js → server-c7awk5s2.js} +10 -4
  112. package/dist/v2/{server-4wwwm2ya.js → server-ct0gs8fc.js} +4 -4
  113. package/dist/v2/{server-97w51d8n.js → server-ff5wcfy4.js} +3 -3
  114. package/dist/v2/{server-ssg29wjg.js → server-gqrw0br5.js} +20 -13
  115. package/dist/v2/{server-y31y6gws.js → server-gwhj0362.js} +3 -3
  116. package/dist/v2/{server-w7mpvkpj.js → server-pbp58w5x.js} +1 -1
  117. package/dist/v2/{server-s15knz0w.js → server-pmws7we9.js} +1 -1
  118. package/dist/v2/{server-4dhv7mqz.js → server-qjwpqvnf.js} +48 -1
  119. package/dist/v2/{server-a2f1bhyj.js → server-stjy5dxv.js} +9 -2
  120. package/dist/v2/{server-hn8b7sfe.js → server-xn7zqs4j.js} +2 -2
  121. package/dist/{index-fzgyvsb1.js → v2/server-y14pawe1.js} +3 -0
  122. package/dist/v2/{server-8pdfmc27.js → server-y17r5ryz.js} +4 -4
  123. package/dist/v2/{server-n5zr7190.js → server-yh2z4gg2.js} +3 -3
  124. package/dist/v2/{server-sxfbjdye.js → server-yx0nyj1q.js} +2 -2
  125. package/dist/v2/server.js +3 -3
  126. package/dist/v2/{storage-memory-e6a7mb0k.js → storage-memory-hhrvfw0x.js} +2 -2
  127. package/dist/v2/{storage-tags-xq81zgt2.js → storage-tags-pmw33chf.js} +2 -2
  128. package/dist/v2/{v2-archive-reader-e2w39c3p.js → v2-archive-reader-2ayz16s4.js} +1 -1
  129. package/dist/v2/{wrapup-orchestrator-eg5b1p89.js → wrapup-orchestrator-e20sjbdz.js} +17 -17
  130. package/dist/{v2-archive-reader-8dsngf2j.js → v2-archive-reader-x39mzvwn.js} +1 -1
  131. package/dist/{wrapup-orchestrator-nmk6yf7f.js → wrapup-orchestrator-h3s905vs.js} +19 -19
  132. package/package.json +1 -1
  133. package/src/shared/assistant-message-extractor.test.ts +22 -0
  134. package/src/shared/assistant-message-extractor.ts +13 -0
  135. package/src/shared/model-suggestion-retry.test.ts +43 -12
  136. package/src/shared/prompt-async-transport.test.ts +275 -8
  137. package/src/shared/prompt-async-transport.ts +41 -2
  138. package/src/shared/reusable-worker.fixture.ts +15 -3
  139. package/src/shared/reusable-worker.test.ts +20 -10
  140. package/src/shared/rpc-notifications.ts +4 -1
  141. package/src/shared/sqlite-foreground-wait.test.ts +2 -2
  142. package/src/shared/startup-maintenance-policy.test.ts +4 -2
@@ -1,5 +1,8 @@
1
- import { describe, expect, mock, test } from "bun:test";
2
- import { refuseBudgetedToolCall } from "../features/magic-context/dreamer/token-budget";
1
+ import { afterEach, beforeEach, describe, expect, jest, mock, test } from "bun:test";
2
+ import {
3
+ createDreamTokenBudget,
4
+ refuseBudgetedToolCall,
5
+ } from "../features/magic-context/dreamer/token-budget";
3
6
  import { createDroppedInputToolExecuteBeforeHook } from "../hooks/magic-context/dropped-input-guard";
4
7
  import { promptSyncWithValidatedOutputRetry } from "./model-suggestion-retry";
5
8
  import {
@@ -609,6 +612,234 @@ describe("dreamer budget on an async child", () => {
609
612
  });
610
613
  });
611
614
 
615
+ describe("tool refusals at finalize submission", () => {
616
+ const toolPart = (callID: string, status = "running", interrupted = false) => ({
617
+ type: "tool",
618
+ callID,
619
+ state: {
620
+ status,
621
+ ...(interrupted
622
+ ? { error: "Tool execution aborted", metadata: { interrupted: true } }
623
+ : {}),
624
+ },
625
+ });
626
+ const interruptedPart = (id: string) => toolPart(id, "error", true);
627
+
628
+ interface RefusalScript {
629
+ beforeAbort?: ReturnType<typeof toolPart>[];
630
+ afterAbort?: ReturnType<typeof toolPart>[] | null;
631
+ duringAbort?: string[];
632
+ afterSubmission?: (string | undefined)[];
633
+ counts: number[];
634
+ answer?: boolean;
635
+ }
636
+
637
+ async function runScript(script: RefusalScript) {
638
+ const before = createDroppedInputToolExecuteBeforeHook();
639
+ const budget = createDreamTokenBudget(100);
640
+ const counts: number[] = [];
641
+ const answer = { type: "text", text: "<mappings/>" };
642
+ const replies = (parts: ReturnType<typeof toolPart>[]) => [
643
+ {
644
+ info: {
645
+ id: "meter",
646
+ role: "assistant",
647
+ tokens: { input: 81 },
648
+ finish: "tool-calls",
649
+ },
650
+ },
651
+ { info: { id: "pending", role: "assistant" }, parts },
652
+ ];
653
+ let submissions = 0;
654
+ let latest: unknown;
655
+ const refuse = async (id: string | undefined) => {
656
+ let reason: unknown;
657
+ try {
658
+ await before({ tool: "read", sessionID: "ses-child", callID: id }, { args: {} });
659
+ } catch (error) {
660
+ reason = error;
661
+ }
662
+ counts.push(budget.snapshot().refusedCalls);
663
+ expect(reason).toBeInstanceOf(Error);
664
+ expect((reason as Error).message).toContain("Out of token budget");
665
+ };
666
+ const abort = mock(async () => {
667
+ if (submissions === 1) {
668
+ for (const id of script.duringAbort ?? []) await refuse(id);
669
+ }
670
+ });
671
+ const client = {
672
+ session: {
673
+ promptAsync: async () => {
674
+ submissions++;
675
+ if (submissions === 1) {
676
+ await before(
677
+ { tool: "read", sessionID: "ses-child", callID: "a" },
678
+ { args: {} },
679
+ );
680
+ expect(refuseBudgetedToolCall("ses-child")).toBeNull();
681
+ }
682
+ if (submissions === 2) {
683
+ await before(
684
+ { tool: "read", sessionID: "other-child", callID: "a" },
685
+ { args: {} },
686
+ );
687
+ for (const id of script.afterSubmission ?? []) await refuse(id);
688
+ if (script.answer) {
689
+ latest = {
690
+ info: {
691
+ id: "final",
692
+ role: "assistant",
693
+ finish: "stop",
694
+ time: { completed: 1 },
695
+ },
696
+ parts: [answer],
697
+ };
698
+ }
699
+ }
700
+ return { data: undefined };
701
+ },
702
+ abort,
703
+ status: async () => ({
704
+ data:
705
+ submissions === 1 && abort.mock.calls.length === 0
706
+ ? { "ses-child": { type: "busy" } }
707
+ : {},
708
+ }),
709
+ messages: async () => {
710
+ if (!submissions) return { data: [] };
711
+ if (abort.mock.calls.length === 0)
712
+ return { data: replies(script.beforeAbort ?? []) };
713
+ if (submissions === 1 && script.afterAbort === null)
714
+ return { error: "unavailable" };
715
+ const rows: unknown[] = replies(script.afterAbort ?? script.beforeAbort ?? []);
716
+ if (submissions === 2) rows.push({ info: { id: "finalize", role: "user" } });
717
+ if (latest) rows.push(latest);
718
+ return { data: rows };
719
+ },
720
+ },
721
+ } as never;
722
+ const result = await promptAsyncAndWaitForIdle(client, request(), {
723
+ pollIntervalMs: 1,
724
+ startGraceMs: 30,
725
+ budgetGuard: budget,
726
+ }).catch((error: unknown) => error);
727
+ expect(counts).toEqual(script.counts);
728
+ expect(submissions).toBe(2);
729
+ if (script.answer) {
730
+ expect(result).toBeUndefined();
731
+ expect(latest).toMatchObject({ parts: [answer] });
732
+ expect(abort).toHaveBeenCalledTimes(1);
733
+ } else {
734
+ expect(result).toBeInstanceOf(Error);
735
+ expect((result as Error).message).toContain("token_budget");
736
+ expect(abort).toHaveBeenCalledTimes(2);
737
+ }
738
+ expect(refuseBudgetedToolCall("ses-child")).toBeNull();
739
+ }
740
+
741
+ test("keeps the answer after two old calls are refused before submission", () =>
742
+ runScript({ duringAbort: ["a", "b"], counts: [0, 0], answer: true }));
743
+
744
+ test("keeps the answer when two cancelled tools reach the guard after submission", () =>
745
+ runScript({
746
+ beforeAbort: [toolPart("a")],
747
+ afterAbort: [interruptedPart("a"), interruptedPart("b")],
748
+ afterSubmission: ["b", "a"],
749
+ counts: [0, 0],
750
+ answer: true,
751
+ }));
752
+
753
+ test("spares a call that is still running in the cancellation snapshot", () =>
754
+ runScript({
755
+ afterAbort: [toolPart("a", "running")],
756
+ afterSubmission: ["a"],
757
+ counts: [0],
758
+ answer: true,
759
+ }));
760
+
761
+ test("counts a call whose part closed with an ordinary tool error", () =>
762
+ runScript({
763
+ afterAbort: [{ ...toolPart("a"), state: { status: "error", error: "File not found" } }],
764
+ afterSubmission: ["a", "b"],
765
+ counts: [1, 2],
766
+ }));
767
+
768
+ test("spares an early refusal but counts a reuse and a second new call", () =>
769
+ runScript({
770
+ beforeAbort: [toolPart("a")],
771
+ duringAbort: ["a"],
772
+ afterSubmission: ["a", "b"],
773
+ counts: [0, 1, 2],
774
+ }));
775
+
776
+ test("stops on exactly two new calls issued after submission", () =>
777
+ runScript({ afterSubmission: ["a", "b"], counts: [1, 2] }));
778
+
779
+ test("spares each in-flight id only once when ids are reused after submission", () =>
780
+ runScript({
781
+ afterAbort: [interruptedPart("a"), toolPart("b", "pending")],
782
+ afterSubmission: ["a", "b", "a", "b"],
783
+ counts: [0, 0, 1, 2],
784
+ }));
785
+
786
+ test("counts both refusals when the cancellation snapshot is unreadable", () =>
787
+ runScript({
788
+ beforeAbort: [toolPart("a"), toolPart("b")],
789
+ afterAbort: null,
790
+ afterSubmission: ["a", "b"],
791
+ counts: [1, 2],
792
+ }));
793
+
794
+ test("releases the guard without submitting finalize when the cancellation read throws", async () => {
795
+ const readError = new Error("socket hang up");
796
+ const meter = { info: { id: "meter", role: "assistant", tokens: { input: 81 } } };
797
+ const cancelled = {
798
+ info: {
799
+ id: "cancelled",
800
+ role: "assistant",
801
+ finish: "tool-calls",
802
+ time: { completed: 1 },
803
+ },
804
+ parts: [toolPart("a", "completed")],
805
+ };
806
+ const promptAsync = mock(async () => ({ data: undefined }));
807
+ const abort = mock(async () => ({ data: true }));
808
+ const messages = mock(async () => {
809
+ if (!promptAsync.mock.calls.length) return { data: [] };
810
+ if (!abort.mock.calls.length) return { data: [meter] };
811
+ if (promptAsync.mock.calls.length === 1) throw readError;
812
+ // A settled tool reply missing from the poll that triggered cancellation
813
+ // must not be mistaken for the finalize response.
814
+ return { data: [meter, cancelled] };
815
+ });
816
+ const client = {
817
+ session: { promptAsync, abort, messages, status: async () => ({ data: {} }) },
818
+ } as never;
819
+ const run = promptAsyncAndWaitForIdle(client, request(), {
820
+ pollIntervalMs: 1,
821
+ tokenBudget: 100,
822
+ });
823
+ await expect(run).rejects.toBe(readError);
824
+ expect(promptAsync).toHaveBeenCalledTimes(1);
825
+ expect(abort).toHaveBeenCalledTimes(1);
826
+ expect(refuseBudgetedToolCall("ses-child")).toBeNull();
827
+ });
828
+
829
+ test("counts missing ids and ids of completed tools after submission", () =>
830
+ runScript({
831
+ beforeAbort: [toolPart("a"), toolPart("b")],
832
+ afterAbort: [toolPart("a", "completed"), toolPart("b", "running")],
833
+ afterSubmission: ["a", undefined],
834
+ counts: [1, 2],
835
+ }));
836
+
837
+ test("does not carry an unspent exemption into a fresh run on the same child", async () => {
838
+ await runScript({ afterAbort: [interruptedPart("a")], counts: [], answer: true });
839
+ await runScript({ afterSubmission: ["a", "b"], counts: [1, 2] });
840
+ });
841
+ });
842
+
612
843
  describe("prompt_async transport under the retry chain", () => {
613
844
  test("our slice stays the only timer and aborts the busy child when it expires", async () => {
614
845
  const host = asyncHost({ plan: ["busy"] });
@@ -683,6 +914,18 @@ test("session errors belonging to another child do not fail the run", async () =
683
914
  });
684
915
 
685
916
  describe("prompt_async transport and the first-output deadline", () => {
917
+ beforeEach(() => {
918
+ jest.useFakeTimers({ doNotFake: ["setImmediate"] });
919
+ jest.setSystemTime(new Date("2026-08-11T12:00:00Z"));
920
+ });
921
+ afterEach(() => jest.useRealTimers());
922
+
923
+ async function poll(ms: number) {
924
+ jest.advanceTimersByTime(ms);
925
+ // Drain the host replies and let the waiter arm its next poll.
926
+ await new Promise<void>((resolve) => setImmediate(resolve));
927
+ }
928
+
686
929
  /**
687
930
  * A child session where each model answers its own way. "dead" leaves the
688
931
  * empty assistant row the host writes before the provider responds and stays
@@ -784,19 +1027,38 @@ describe("prompt_async transport and the first-output deadline", () => {
784
1027
  const host = modelHost({ "opencode/free-model": "dead" });
785
1028
  const startedAt = Date.now();
786
1029
 
787
- const run = await runChain(host, 5_000, 60);
1030
+ const pending = runChain(host, 5_000, 60);
1031
+ await new Promise<void>((resolve) => setImmediate(resolve));
1032
+ await poll(59);
1033
+ expect(host.sent).toEqual(["opencode/free-model"]);
1034
+ expect(host.abort).not.toHaveBeenCalled();
1035
+ await poll(1);
1036
+ expect(host.sent).toEqual(["opencode/free-model", "anthropic/claude-sonnet-5-5"]);
1037
+ await poll(5);
1038
+ const run = await pending;
788
1039
 
789
1040
  expect(run.attempt.label).toBe("anthropic/claude-sonnet-5-5");
790
- expect(host.sent).toEqual(["opencode/free-model", "anthropic/claude-sonnet-5-5"]);
791
1041
  // The dead model's run is stopped on the host before the fallback is sent.
792
1042
  expect(host.abort).toHaveBeenCalledWith({ path: { id: "ses-child" } });
793
- expect(Date.now() - startedAt).toBeLessThan(2_000);
1043
+ expect(Date.now() - startedAt).toBe(65);
794
1044
  });
795
1045
 
796
1046
  test("a model that streamed part of an answer keeps its timeout and does not fall back", async () => {
797
1047
  const host = modelHost({ "opencode/free-model": "partial" });
798
1048
 
799
- await expect(runChain(host, 200, 40)).rejects.toThrow("prompt timed out after 200ms");
1049
+ let outcome: unknown;
1050
+ const pending = runChain(host, 200, 40).then(
1051
+ (result) => (outcome = result),
1052
+ (error: unknown) => (outcome = error),
1053
+ );
1054
+ await new Promise<void>((resolve) => setImmediate(resolve));
1055
+ await poll(5); // Let the first poll see the streamed answer before advancing to the cut.
1056
+ await poll(194);
1057
+ expect(host.abort).not.toHaveBeenCalled();
1058
+ await poll(1);
1059
+ expect(outcome).toBeInstanceOf(Error);
1060
+ expect((outcome as Error).message).toBe("prompt timed out after 200ms");
1061
+ await pending;
800
1062
  expect(host.sent).toEqual(["opencode/free-model"]);
801
1063
  });
802
1064
 
@@ -804,12 +1066,17 @@ describe("prompt_async transport and the first-output deadline", () => {
804
1066
  test(`a recorded provider ${failure} stops the host retry loop and immediately tries the fallback`, async () => {
805
1067
  const host = modelHost({ "opencode/free-model": failure });
806
1068
  const startedAt = Date.now();
807
- const result = await runChain(host, 5_000, 5_000);
1069
+ const pending = runChain(host, 5_000, 5_000);
1070
+ await new Promise<void>((resolve) => setImmediate(resolve));
1071
+ await poll(5);
1072
+ expect(host.sent).toEqual(["opencode/free-model", "anthropic/claude-sonnet-5-5"]);
1073
+ await poll(5);
1074
+ const result = await pending;
808
1075
  expect(result.attempt.label).toBe("anthropic/claude-sonnet-5-5");
809
1076
  expect(host.sent).toEqual(["opencode/free-model", "anthropic/claude-sonnet-5-5"]);
810
1077
  expect(host.abort).toHaveBeenCalledTimes(1);
811
1078
  expect(host.abort).toHaveBeenCalledWith({ path: { id: "ses-child" } });
812
- expect(Date.now() - startedAt).toBeLessThan(2_000);
1079
+ expect(Date.now() - startedAt).toBe(10);
813
1080
  });
814
1081
  }
815
1082
  });
@@ -200,6 +200,38 @@ function messageId(message: unknown): string | null {
200
200
  return typeof id === "string" ? id : null;
201
201
  }
202
202
 
203
+ function inFlightAtAbort(messages: unknown[], initialBaseline: Set<string>): Set<string> {
204
+ // OpenCode finishes a reply's tool batch before starting the next reply.
205
+ // Cleanup can mark the cancelled reply's outstanding parts as errors even
206
+ // though their callbacks may still reach the hook. Exempt each of those
207
+ // call IDs once at most: even with reused IDs, the stop takes no more than
208
+ // this many post-submission refusals plus the two counted refusals.
209
+ const reply = messages
210
+ .slice()
211
+ .reverse()
212
+ .find((message) => {
213
+ const id = messageId(message);
214
+ return id !== null && !initialBaseline.has(id) && infoOf(message).role === "assistant";
215
+ });
216
+ const parts = (reply as { parts?: unknown } | undefined)?.parts;
217
+ const ids = new Set<string>();
218
+ if (Array.isArray(parts)) {
219
+ for (const part of parts) {
220
+ if (part?.type !== "tool" || typeof part.callID !== "string") continue;
221
+ const state = part.state;
222
+ if (
223
+ state?.status === "pending" ||
224
+ state?.status === "running" ||
225
+ (state?.status === "error" &&
226
+ state.error === "Tool execution aborted" &&
227
+ state.metadata?.interrupted === true)
228
+ )
229
+ ids.add(part.callID);
230
+ }
231
+ }
232
+ return ids;
233
+ }
234
+
203
235
  function recordedAssistantError(message: unknown): unknown {
204
236
  const info = infoOf(message);
205
237
  if (info.error != null) return info.error;
@@ -520,7 +552,7 @@ export async function promptAsyncAndWaitForIdle(
520
552
  budget.snapshot(),
521
553
  );
522
554
  budgetAbortedSessions.add(sessionId);
523
- registerBudgetFinalizeChild(sessionId, budget);
555
+ const countRefusals = registerBudgetFinalizeChild(sessionId, budget);
524
556
  if (!session.abort)
525
557
  throw new DreamTokenBudgetExceeded(sessionId, budget.snapshot().spent);
526
558
  await session.abort({ path: { id: sessionId } });
@@ -535,12 +567,19 @@ export async function promptAsyncAndWaitForIdle(
535
567
  if ((await readStatus(session, sessionId, dir, signal)) !== "idle") {
536
568
  throw new DreamTokenBudgetExceeded(sessionId, budget.snapshot().spent);
537
569
  }
570
+ const cancelled = await readMessages(session, sessionId, dir, signal);
538
571
  // An aborted assistant is not the answer to the new user turn.
539
572
  completionBaseline = new Set(
540
- (await readMessages(session, sessionId, dir, signal))
573
+ (cancelled.length ? cancelled : messages)
541
574
  .map(messageId)
542
575
  .filter((value): value is string => value !== null),
543
576
  );
577
+ const exemptCallIds = inFlightAtAbort(cancelled, initialBaseline);
578
+ countRefusals(exemptCallIds);
579
+ sessionLog(sessionId, "dreamer token budget: counting tool refusals", {
580
+ snapshot: cancelled.length ? "read" : "unreadable",
581
+ exemptCallIds: [...exemptCallIds],
582
+ });
544
583
  const finalizeResponse = await session.promptAsync?.({
545
584
  ...request,
546
585
  body: {
@@ -1,16 +1,23 @@
1
1
  import { parentPort, threadId } from "node:worker_threads";
2
2
  import { serveWorkerJobs } from "./reusable-worker-entry";
3
3
 
4
+ let replyToReleasedJob: (() => void) | undefined;
5
+
4
6
  serveWorkerJobs<{
5
7
  crash?: boolean;
6
8
  hang?: boolean;
9
+ acknowledgeHang?: boolean;
7
10
  late?: boolean;
11
+ deliverLate?: boolean;
8
12
  exitCode?: boolean;
9
13
  value?: string;
10
14
  shared?: SharedArrayBuffer;
11
15
  }>(async (input, port) => {
12
16
  if (input.crash) throw new Error("injected worker crash");
13
- if (input.hang) return await new Promise<void>(() => {});
17
+ if (input.hang) {
18
+ if (input.acknowledgeHang) port.postMessage({ threadId, hanging: true });
19
+ return await new Promise<void>(() => {});
20
+ }
14
21
  if (input.exitCode) process.exitCode = 1;
15
22
  if (input.shared) {
16
23
  const state = new Int32Array(input.shared);
@@ -25,11 +32,16 @@ serveWorkerJobs<{
25
32
  return;
26
33
  }
27
34
  if (input.late)
28
- setTimeout(() => {
35
+ replyToReleasedJob = () => {
29
36
  port.postMessage({ value: "stale" });
30
37
  // Bypass the job port to verify the owner ignores a mismatched job id.
31
38
  parentPort?.postMessage({ jobId: -1, value: { value: "stale" } });
32
- }, 20);
39
+ };
40
+ if (input.deliverLate) {
41
+ if (!replyToReleasedJob) throw new Error("fixture did not reuse the prior thread");
42
+ replyToReleasedJob();
43
+ replyToReleasedJob = undefined;
44
+ }
33
45
  port.postMessage({ threadId, value: input.value });
34
46
  port.close();
35
47
  });
@@ -1,4 +1,4 @@
1
- import { describe, expect, test } from "bun:test";
1
+ import { afterEach, describe, expect, jest, test } from "bun:test";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { once } from "node:events";
4
4
  import { readFileSync, writeFileSync } from "node:fs";
@@ -22,6 +22,8 @@ async function result(worker: Worker) {
22
22
  }
23
23
 
24
24
  describe("reusable job workers", () => {
25
+ afterEach(() => jest.useRealTimers());
26
+
25
27
  test("reuses a thread but gives each job fresh input and port state", async () => {
26
28
  const path = `reuse-${++key}`;
27
29
  const first = await result(start(path, { value: "first" }));
@@ -45,20 +47,27 @@ describe("reusable job workers", () => {
45
47
  test("terminates a hung job and replaces its thread", async () => {
46
48
  const path = `hang-${++key}`;
47
49
  const first = await result(start(path));
48
- const hung = start(path, { hang: true });
49
- // Allow dispatch, then terminate the worker to exercise the hard-stop behavior.
50
- await new Promise((resolve) => setTimeout(resolve, 25));
51
- await hung.terminate();
50
+ const hung = start(path, { hang: true, acknowledgeHang: true });
51
+ try {
52
+ const [reply] = await once(hung, "message");
53
+ expect(reply).toEqual({ threadId: first.threadId, hanging: true });
54
+ } finally {
55
+ await hung.terminate();
56
+ }
52
57
  const next = await result(start(path));
53
58
  expect(next.threadId).not.toBe(first.threadId);
54
59
  });
55
60
 
56
61
  test("shuts the thread down after its idle lifetime", async () => {
62
+ jest.useFakeTimers({ doNotFake: ["setImmediate"] });
57
63
  const path = `idle-${++key}`;
58
64
  const first = await result(start(path, {}, 20));
59
- await new Promise((resolve) => setTimeout(resolve, 80));
65
+ jest.advanceTimersByTime(19);
66
+ expect((await result(start(path, {}, 20))).threadId).toBe(first.threadId);
67
+ jest.advanceTimersByTime(20);
60
68
  const next = await result(start(path, {}, 20));
61
69
  expect(next.threadId).not.toBe(first.threadId);
70
+ jest.advanceTimersByTime(20);
62
71
  });
63
72
 
64
73
  test("rejects late replies from a released job", async () => {
@@ -67,13 +76,14 @@ describe("reusable job workers", () => {
67
76
  const oldReplies: unknown[] = [];
68
77
  prior.on("message", (reply) => oldReplies.push(reply));
69
78
  const first = await result(prior);
70
- const next = start(path, { hang: true });
79
+ const next = start(path, { deliverLate: true, value: "next" });
71
80
  const replies: unknown[] = [];
72
81
  next.on("message", (reply) => replies.push(reply));
73
- await new Promise((resolve) => setTimeout(resolve, 60));
82
+ // The fixture sends both stale packets before acknowledging the next job.
83
+ const nextReply = await result(next);
84
+ expect(nextReply).toEqual({ threadId: first.threadId, value: "next" });
74
85
  expect(oldReplies).toHaveLength(1);
75
- expect(replies).toEqual([]);
76
- await next.terminate();
86
+ expect(replies).toEqual([nextReply]);
77
87
  expect(first.threadId).toBeGreaterThan(0);
78
88
  });
79
89
 
@@ -63,16 +63,19 @@ export function pushLiveNotification(
63
63
  type: string,
64
64
  payload: Record<string, unknown>,
65
65
  sessionId: string,
66
- ): void {
66
+ ): boolean {
67
67
  const notification: RpcNotification = { id: nextNotificationId++, type, payload, sessionId };
68
+ let delivered = false;
68
69
  for (const sink of sinks) {
69
70
  if (sink.sessionId !== sessionId) continue;
70
71
  try {
71
72
  sink.send(notification);
73
+ delivered = true;
72
74
  } catch {
73
75
  // A socket that closed during the send has no live terminal to notify.
74
76
  }
75
77
  }
78
+ return delivered;
76
79
  }
77
80
 
78
81
  /** Push a notification to the TUI. Fans out to any live WS sink immediately and
@@ -57,7 +57,7 @@ for (const holdMs of [1000, 2500]) {
57
57
  const diagnostics: string[] = [];
58
58
  registerSqliteDiagnosticSink((line) => diagnostics.push(line));
59
59
  const handler = createMessagesTransformHandler({
60
- onStorageBusyRefusal: async (id) => {
60
+ onRefusal: async (id) => {
61
61
  expect(id).toBe(sessionId);
62
62
  refusals++;
63
63
  },
@@ -128,7 +128,7 @@ for (const holdMs of [1000, 2500]) {
128
128
  ],
129
129
  };
130
130
  const handler = createMessagesTransformHandler({
131
- onStorageBusyRefusal: async () => {
131
+ onRefusal: async () => {
132
132
  refusals++;
133
133
  },
134
134
  magicContext: {
@@ -44,7 +44,8 @@ test.each([
44
44
  );
45
45
  const statements = source.statements.map((statement) => statement.getText(source));
46
46
  // Inspect statements, not comments: a commented-out policy must fail this guard.
47
- expect(statements[0]).toBe(
47
+ expect(statements[0]).toBe("delete process.env.OPENCODE_DB;");
48
+ expect(statements[1]).toBe(
48
49
  'await import(new URL("../test-preload.ts", import.meta.url).href);',
49
50
  );
50
51
  expect(statements.at(-1)).toBe("__setScheduleStartupMaintenanceOnOpenForTests(false);");
@@ -52,7 +53,7 @@ test.each([
52
53
  packageName === "plugin"
53
54
  ? "./features/magic-context/storage-db"
54
55
  : "@magic-context/core/features/magic-context/storage-db";
55
- expect(statements[1]).toMatch(
56
+ expect(statements[2]).toMatch(
56
57
  new RegExp(
57
58
  `const \\{ __setScheduleStartupMaintenanceOnOpenForTests \\} = await import\\(\\s*"${storageModule}"\\s*\\);`,
58
59
  ),
@@ -63,6 +64,7 @@ test("CLI uses the unit policy while end-to-end tests retain the shared isolatio
63
64
  expect(preloads("cli")).toEqual(["../plugin/src/test-preload.ts"]);
64
65
  expect(preloads("e2e-tests")).toEqual(["../plugin/test-preload.ts"]);
65
66
  const isolation = readFileSync(join(root, "packages/plugin/test-preload.ts"), "utf8");
67
+ expect(isolation).not.toContain("delete process.env.OPENCODE_DB");
66
68
  expect(isolation).not.toContain("__setScheduleStartupMaintenanceOnOpenForTests");
67
69
  expect(isolation).not.toContain("src/test-preload");
68
70
  });