@cortexkit/opencode-magic-context 0.49.49 → 0.49.51

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 (138) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/config/project-security.d.ts.map +1 -1
  4. package/dist/config/schema/magic-context.d.ts +10 -0
  5. package/dist/config/schema/magic-context.d.ts.map +1 -1
  6. package/dist/{context-bwf57gnh.js → context-r77d4fdy.js} +37 -23
  7. package/dist/{embedding-backfill-d9x9q2e2.js → embedding-backfill-3wdjzrvs.js} +4 -4
  8. package/dist/embedding-worker.js +2 -2
  9. package/dist/features/magic-context/dreamer/provider-output-failure.d.ts +5 -7
  10. package/dist/features/magic-context/dreamer/provider-output-failure.d.ts.map +1 -1
  11. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  12. package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
  13. package/dist/features/magic-context/memory/embedding-identity.d.ts.map +1 -1
  14. package/dist/features/magic-context/memory/embedding-openai.d.ts +4 -0
  15. package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
  16. package/dist/features/magic-context/memory/embedding-probe.d.ts +10 -0
  17. package/dist/features/magic-context/memory/embedding-probe.d.ts.map +1 -1
  18. package/dist/features/magic-context/memory/embedding.d.ts.map +1 -1
  19. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  20. package/dist/features/magic-context/search-rerank.d.ts +2 -2
  21. package/dist/features/magic-context/search-rerank.d.ts.map +1 -1
  22. package/dist/features/magic-context/storage-db.d.ts +14 -0
  23. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  24. package/dist/features/magic-context/transform-decision-log.d.ts +2 -0
  25. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  27. package/dist/{index-qb75tv9j.js → index-07rp6xcn.js} +1 -1
  28. package/dist/{index-5bksfv58.js → index-30sf7e5k.js} +27 -9
  29. package/dist/{index-7n2n3v92.js → index-5dptmnvd.js} +2 -2
  30. package/dist/{index-arxg51bj.js → index-8d7gkgjs.js} +4 -3
  31. package/dist/{index-wdmfnmv1.js → index-97bjd14c.js} +4 -4
  32. package/dist/{index-0mdh2cke.js → index-bamnjp2t.js} +20 -4
  33. package/dist/{index-5850zme4.js → index-ct3ettqt.js} +3 -3
  34. package/dist/{index-3n9ee4jh.js → index-cwj6qhmf.js} +1 -1
  35. package/dist/{index-j7verehm.js → index-gv7dwx5b.js} +36 -27
  36. package/dist/{index-va9x7y48.js → index-h8g08nxs.js} +135 -81
  37. package/dist/{index-jedbxq6n.js → index-hkveze74.js} +1 -1
  38. package/dist/{index-4dpvnp8k.js → index-jjy5a5w0.js} +3 -0
  39. package/dist/{index-h3p558ec.js → index-mjh63zvw.js} +1 -1
  40. package/dist/{index-vyv4tame.js → index-n0twfvah.js} +53 -2
  41. package/dist/{index-tj5gz396.js → index-rbs27k1d.js} +4 -2
  42. package/dist/{index-cs7pmwt6.js → index-s131svmx.js} +1 -1
  43. package/dist/{index-vbmh68fb.js → index-v4a1pnny.js} +4 -4
  44. package/dist/{index-k47v0tmk.js → index-wr2t8zb0.js} +8 -8
  45. package/dist/{index-agfh931z.js → index-z4832qfe.js} +4 -2
  46. package/dist/index.js +22 -22
  47. package/dist/{message-index-bounded-2shxmht9.js → message-index-bounded-k0ebpy3y.js} +3 -3
  48. package/dist/migration-worker.js +1 -1
  49. package/dist/plugin/embedding-bootstrap-helpers.d.ts.map +1 -1
  50. package/dist/plugin/embedding-routing.d.ts.map +1 -1
  51. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  52. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  53. package/dist/{project-embedding-registry-nzgkq61z.js → project-embedding-registry-5dwh5zfn.js} +3 -3
  54. package/dist/raw-ordinal-warmup-worker.js +3 -3
  55. package/dist/{read-session-chunk-c15y8yg6.js → read-session-chunk-6712p893.js} +2 -2
  56. package/dist/{recomp-orchestrator-gfxqqpph.js → recomp-orchestrator-8ebydg5j.js} +11 -11
  57. package/dist/{render-5tx8r0me.js → render-dtc4qkq4.js} +6 -6
  58. package/dist/{search-k2n5bvsk.js → search-75bj2430.js} +9 -9
  59. package/dist/{search-archive-6tgh88xp.js → search-archive-f6hjbnsa.js} +4 -4
  60. package/dist/shared/hidden-model-cooldown.d.ts +23 -0
  61. package/dist/shared/hidden-model-cooldown.d.ts.map +1 -0
  62. package/dist/shared/model-suggestion-retry.d.ts +0 -2
  63. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  64. package/dist/shared/provider-response-completion.d.ts +10 -0
  65. package/dist/shared/provider-response-completion.d.ts.map +1 -1
  66. package/dist/shared/rpc-types.d.ts +1 -0
  67. package/dist/shared/rpc-types.d.ts.map +1 -1
  68. package/dist/shared/status-summary.d.ts +1 -0
  69. package/dist/shared/status-summary.d.ts.map +1 -1
  70. package/dist/shared/status-view-check.d.ts.map +1 -1
  71. package/dist/shared/status-view.d.ts +1 -0
  72. package/dist/shared/status-view.d.ts.map +1 -1
  73. package/dist/shared/test-db.d.ts +13 -0
  74. package/dist/shared/test-db.d.ts.map +1 -0
  75. package/dist/test-preload.d.ts +2 -0
  76. package/dist/test-preload.d.ts.map +1 -0
  77. package/dist/{transform-postprocess-phase-36dw4kxb.js → transform-postprocess-phase-1bg25094.js} +12 -12
  78. package/dist/v2/auto-search-worker.js +3 -3
  79. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  80. package/dist/v2/{context-td3jyze3.js → context-cpbhpxks.js} +47 -30
  81. package/dist/v2/{embedding-backfill-5dqdm3ff.js → embedding-backfill-x1zpc04f.js} +4 -4
  82. package/dist/v2/embedding-worker.js +2 -2
  83. package/dist/v2/hidden-completion.d.ts.map +1 -1
  84. package/dist/v2/hooks/context.d.ts.map +1 -1
  85. package/dist/v2/hooks/usage-persist.d.ts +1 -1
  86. package/dist/v2/hooks/usage-persist.d.ts.map +1 -1
  87. package/dist/v2/hooks/usage-reading.d.ts +3 -0
  88. package/dist/v2/hooks/usage-reading.d.ts.map +1 -1
  89. package/dist/v2/{message-index-bounded-j1jskn8a.js → message-index-bounded-a36rw93p.js} +3 -3
  90. package/dist/v2/migration-worker.js +1 -1
  91. package/dist/v2/{project-embedding-registry-swm4mw1t.js → project-embedding-registry-v2fxrs8b.js} +3 -3
  92. package/dist/v2/raw-ordinal-warmup-worker.js +3 -3
  93. package/dist/v2/{read-session-chunk-carzw3m8.js → read-session-chunk-hzhxvhyv.js} +2 -2
  94. package/dist/v2/{recomp-orchestrator-e7vrs932.js → recomp-orchestrator-yzr49pd0.js} +11 -11
  95. package/dist/v2/{render-e9mh9y1d.js → render-rhaevxv1.js} +6 -6
  96. package/dist/v2/{search-sr23g316.js → search-3yrdpr38.js} +8 -8
  97. package/dist/v2/{search-archive-j3kb9ggd.js → search-archive-9924fyk8.js} +4 -4
  98. package/dist/v2/{server-z7n3n1ra.js → server-016a1whm.js} +134 -81
  99. package/dist/v2/{server-4y2pcckw.js → server-0k586y7d.js} +3 -3
  100. package/dist/v2/{server-p9s40wfa.js → server-0ms13pc8.js} +3 -0
  101. package/dist/v2/{server-c5kq8d5n.js → server-16kfxcxj.js} +1 -1
  102. package/dist/v2/{server-2qxt6qv0.js → server-3bfc26r7.js} +1 -1
  103. package/dist/v2/{server-fw49gc57.js → server-4h4acntc.js} +20 -4
  104. package/dist/v2/{server-yxe0gh3v.js → server-88yvx6r9.js} +53 -2
  105. package/dist/v2/{server-1ppcpsdw.js → server-brsx45r6.js} +4 -2
  106. package/dist/v2/{server-e20kfytm.js → server-eznem83k.js} +26 -8
  107. package/dist/v2/{server-y7q8cds3.js → server-jxrqsn84.js} +1 -1
  108. package/dist/v2/{server-t5cgb15n.js → server-q93jdtz8.js} +2 -2
  109. package/dist/v2/{server-ttrrh27h.js → server-sb55ddgn.js} +3 -2
  110. package/dist/v2/{server-e14c3hd6.js → server-scp3y4dh.js} +4 -2
  111. package/dist/v2/{server-0qxb8r8q.js → server-sgn61hht.js} +1 -1
  112. package/dist/v2/{server-r7y35vm9.js → server-vjadwb3j.js} +4 -3
  113. package/dist/v2/server.js +4 -4
  114. package/dist/v2/{v2-archive-reader-jnzjavzr.js → v2-archive-reader-5ggewg8q.js} +1 -1
  115. package/dist/v2/{wrapup-orchestrator-jw4nre49.js → wrapup-orchestrator-36c5wyvq.js} +11 -11
  116. package/dist/{v2-archive-reader-b76tfeje.js → v2-archive-reader-gx5ke1d7.js} +1 -1
  117. package/dist/{wrapup-orchestrator-fhfazjkq.js → wrapup-orchestrator-ya31knav.js} +12 -12
  118. package/package.json +1 -1
  119. package/src/config/index.test.ts +20 -0
  120. package/src/config/project-security.test.ts +5 -1
  121. package/src/config/project-security.ts +4 -0
  122. package/src/config/schema/magic-context.test.ts +43 -0
  123. package/src/config/schema/magic-context.ts +19 -0
  124. package/src/shared/hidden-model-cooldown.test.ts +117 -0
  125. package/src/shared/hidden-model-cooldown.ts +123 -0
  126. package/src/shared/model-suggestion-retry.test.ts +53 -76
  127. package/src/shared/model-suggestion-retry.ts +38 -53
  128. package/src/shared/provider-response-completion.test.ts +49 -0
  129. package/src/shared/provider-response-completion.ts +64 -0
  130. package/src/shared/rpc-types.ts +1 -0
  131. package/src/shared/startup-maintenance-policy.test.ts +115 -0
  132. package/src/shared/status-detail-text.test.ts +7 -0
  133. package/src/shared/status-summary.ts +3 -0
  134. package/src/shared/status-view-check.ts +1 -0
  135. package/src/shared/status-view.test.ts +15 -0
  136. package/src/shared/status-view.ts +11 -1
  137. package/src/shared/test-db.test.ts +84 -0
  138. package/src/shared/test-db.ts +36 -0
@@ -704,6 +704,26 @@ describe("loadPluginConfig — secret redaction", () => {
704
704
  expect(result.embedding.model).toBe("repo-model");
705
705
  expect(result.configWarnings?.join("\n")).toContain("embedding.endpoint/provider");
706
706
  });
707
+
708
+ it("ignores a project embedding.dimensions override while the user width still applies", () => {
709
+ const userConfig = JSON.stringify({
710
+ embedding: {
711
+ provider: "openai-compatible",
712
+ endpoint: "https://trusted.example/v1",
713
+ model: "qwen/qwen3-embedding-8b",
714
+ dimensions: 768,
715
+ },
716
+ });
717
+ const projectConfig = JSON.stringify({ embedding: { dimensions: 4096 } });
718
+
719
+ const result = loadWithUserAndProjectConfig(userConfig, projectConfig);
720
+
721
+ expect(result.embedding.provider).toBe("openai-compatible");
722
+ if (result.embedding.provider === "openai-compatible") {
723
+ expect(result.embedding.dimensions).toBe(768);
724
+ }
725
+ expect(result.configWarnings?.join("\n")).toContain("dimensions");
726
+ });
707
727
  });
708
728
 
709
729
  describe("loadPluginConfig — experimental graduation migration", () => {
@@ -173,6 +173,7 @@ describe("stripUnsafeProjectConfigFields", () => {
173
173
  query_input_type: "query",
174
174
  query_instruction: "repo-controlled instruction",
175
175
  document_prefix: "repo-controlled document prefix",
176
+ dimensions: 1,
176
177
  },
177
178
  };
178
179
 
@@ -185,9 +186,12 @@ describe("stripUnsafeProjectConfigFields", () => {
185
186
  expect(embedding.query_input_type).toBe("query");
186
187
  expect(embedding.query_instruction).toBeUndefined();
187
188
  expect(embedding.document_prefix).toBeUndefined();
189
+ expect(embedding.dimensions).toBeUndefined();
188
190
  expect(
189
191
  warnings.some((w) =>
190
- w.includes("embedding.endpoint/provider/query_instruction/document_prefix"),
192
+ w.includes(
193
+ "embedding.endpoint/provider/query_instruction/document_prefix/dimensions",
194
+ ),
191
195
  ),
192
196
  ).toBe(true);
193
197
  });
@@ -64,6 +64,10 @@ const EMBEDDING_USER_ONLY_FIELDS = [
64
64
  "fallback_provider",
65
65
  "query_instruction",
66
66
  "document_prefix",
67
+ // Per-request output width. A repository choosing it changes the stored-vector
68
+ // identity (one re-embed of the project's history) and, if the pinned endpoint
69
+ // ignores or rejects that width, breaks embedding and semantic search outright.
70
+ "dimensions",
67
71
  ] as const;
68
72
  const PERCENTAGE_THRESHOLD_REASON =
69
73
  "security: a repository may only raise compaction thresholds above the user's effective value; it cannot force earlier historian work or cloned-repo cost escalation.";
@@ -770,6 +770,49 @@ describe("MagicContextConfigSchema", () => {
770
770
  ).toMatchObject({ query_instruction: false });
771
771
  });
772
772
 
773
+ it("preserves embedding.dimensions through the schema transform", () => {
774
+ const parsed = MagicContextConfigSchema.parse({
775
+ embedding: {
776
+ provider: "openai-compatible",
777
+ endpoint: "http://localhost:1234/v1",
778
+ model: "qwen/qwen3-embedding-8b",
779
+ dimensions: 768,
780
+ },
781
+ }).embedding;
782
+
783
+ expect(parsed).toMatchObject({ dimensions: 768 });
784
+ // The transform rebuilds the object field by field; a field it forgets
785
+ // is silently dropped and the wire request loses the parameter.
786
+ expect("dimensions" in parsed).toBe(true);
787
+ });
788
+
789
+ it("omits embedding.dimensions from the resolved config when unset", () => {
790
+ const parsed = MagicContextConfigSchema.parse({
791
+ embedding: {
792
+ provider: "openai-compatible",
793
+ endpoint: "http://localhost:1234/v1",
794
+ model: "text-embedding-3-small",
795
+ },
796
+ }).embedding;
797
+
798
+ expect("dimensions" in parsed).toBe(false);
799
+ });
800
+
801
+ it("rejects a non-positive or non-integer embedding.dimensions", () => {
802
+ for (const dimensions of [0, -768, 1.5]) {
803
+ expect(
804
+ MagicContextConfigSchema.safeParse({
805
+ embedding: {
806
+ provider: "openai-compatible",
807
+ endpoint: "http://localhost:1234/v1",
808
+ model: "text-embedding-3-small",
809
+ dimensions,
810
+ },
811
+ }).success,
812
+ ).toBe(false);
813
+ }
814
+ });
815
+
773
816
  it("defaults local embedding runtime to auto and accepts explicit overrides", () => {
774
817
  expect(
775
818
  MagicContextConfigSchema.parse({ embedding: { provider: "local" } }).embedding,
@@ -795,6 +795,15 @@ const BaseEmbeddingConfigSchema = z
795
795
  .describe(
796
796
  "Optional truncate mode sent in the embedding request body (e.g. NVIDIA NIM accepts 'NONE' | 'START' | 'END'). Omitted from the request when unset.",
797
797
  ),
798
+ dimensions: z
799
+ .number()
800
+ .int()
801
+ .min(1)
802
+ .max(8192)
803
+ .optional()
804
+ .describe(
805
+ "Optional output width for Matryoshka embedding models (e.g. Qwen3-Embedding-8B accepts 768 | 1024 | 2048 | 4096; OpenAI text-embedding-3-* accept smaller widths than native). Sent as the OpenAI-compatible `dimensions` request field. Omitted from the request when unset, so the endpoint default applies. Changing it changes the produced vectors and folds into the embedding model identity, so switching widths re-embeds rather than mixing vector spaces. Not supported for the local provider, and ignored from project config like the other embedding fields (a repository cannot choose how private text is embedded).",
806
+ ),
798
807
  max_input_tokens: z
799
808
  .number()
800
809
  .int()
@@ -864,6 +873,12 @@ export const EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data)
864
873
  ...(model ? { model } : {}),
865
874
  ...(endpoint ? { endpoint } : {}),
866
875
  ...(apiKey ? { api_key: apiKey } : {}),
876
+ // dimensions is carried on the synapse block ONLY so it survives to
877
+ // the openai-compatible fallback lane (fallbackConfig rebuilds that
878
+ // provider from this object). Synapse's own lane ignores it — its
879
+ // width is pinned from the first embed response, and a static width
880
+ // here would fight that.
881
+ ...(data.dimensions ? { dimensions: data.dimensions } : {}),
867
882
  ...(inputType ? { input_type: inputType } : {}),
868
883
  ...(queryInputType ? { query_input_type: queryInputType } : {}),
869
884
  ...(data.query_instruction !== undefined
@@ -902,6 +917,10 @@ export const EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data)
902
917
  provider: "openai-compatible" as const,
903
918
  model: data.model?.trim() ?? "",
904
919
  endpoint: data.endpoint?.trim() ?? "",
920
+ // dimensions is spread CONDITIONALLY (mirrors truncate/local_dtype):
921
+ // omitting it when unset keeps the identity byte-identical for every
922
+ // existing config, so adding this field forces no global re-embed.
923
+ ...(data.dimensions ? { dimensions: data.dimensions } : {}),
905
924
  ...(apiKey ? { api_key: apiKey } : {}),
906
925
  ...(inputType ? { input_type: inputType } : {}),
907
926
  ...(queryInputType ? { query_input_type: queryInputType } : {}),
@@ -0,0 +1,117 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { HiddenModelCooldowns } from "./hidden-model-cooldown";
3
+
4
+ const epoch = Date.parse("2026-10-08T00:00:00Z");
5
+ const refusal = (seconds: string, statusCode = 412) => ({
6
+ name: "APIError",
7
+ data: { statusCode, responseHeaders: { "retry-after": seconds }, isRetryable: false },
8
+ });
9
+
10
+ describe("hidden model quota cooldown", () => {
11
+ test("structured quota refusal skips across runs, expires, and is removed", () => {
12
+ let now = epoch;
13
+ const table = new HiddenModelCooldowns(() => now);
14
+ const messages: string[] = [];
15
+ table.record("google/primary", refusal("190000"));
16
+ expect(
17
+ table.startIndex(["google/primary", "other/fallback"], (line) => messages.push(line)),
18
+ ).toBe(1);
19
+ expect(messages).toEqual([
20
+ "skipping google/primary until 2026-10-10T04:46:40.000Z: provider said to retry later",
21
+ ]);
22
+ now += 190_000_000;
23
+ expect(table.startIndex(["google/primary", "other/fallback"], () => {})).toBe(0);
24
+ expect(table.live()).toEqual([]);
25
+ });
26
+
27
+ test("success clears a model and providers have independent keys", () => {
28
+ const table = new HiddenModelCooldowns(() => epoch);
29
+ table.record("one/model", refusal("120"));
30
+ table.record("two/model", refusal("180"));
31
+ table.succeeded("one/model");
32
+ expect(table.live().map((entry) => entry.model)).toEqual(["two/model"]);
33
+ expect(table.startIndex(["one/model", "two/model"], () => {})).toBe(0);
34
+ });
35
+
36
+ test("all unavailable models still try the soonest, preserving subsequent fallback order", () => {
37
+ const table = new HiddenModelCooldowns(() => epoch);
38
+ for (const [model, delay] of [
39
+ ["p/first", "300"],
40
+ ["p/second", "120"],
41
+ ["p/third", "200"],
42
+ ])
43
+ table.record(model, refusal(delay));
44
+ expect(table.startIndex(["p/first", "p/second", "p/third"], () => {})).toBe(1);
45
+ expect(table.startIndex(["p/first"], () => {})).toBe(0);
46
+ });
47
+
48
+ test("clamps long windows to seven days and leaves ordinary retries at sixty seconds alone", () => {
49
+ const table = new HiddenModelCooldowns(() => epoch);
50
+ table.record("p/long", refusal("99999999"));
51
+ table.record("p/short", refusal("60"));
52
+ table.record("p/above-floor", refusal("61"));
53
+ expect(table.live()).toEqual([
54
+ {
55
+ model: "p/long",
56
+ until: epoch + 604_800_000,
57
+ reason: "provider said to retry later",
58
+ },
59
+ {
60
+ model: "p/above-floor",
61
+ until: epoch + 61_000,
62
+ reason: "provider said to retry later",
63
+ },
64
+ ]);
65
+ });
66
+
67
+ test("accepts HTTP dates and OpenCode 2.2 millisecond delays with not-now statuses", () => {
68
+ const table = new HiddenModelCooldowns(() => epoch);
69
+ table.record("p/date", refusal("Thu, 08 Oct 2026 00:02:00 GMT", 429));
70
+ table.record("p/oc2", {
71
+ type: "provider.overloaded",
72
+ status: 503,
73
+ retryAfterMs: 190_000_000,
74
+ });
75
+ table.record("p/sdk", {
76
+ statusCode: 412,
77
+ data: { error: "quota" },
78
+ responseHeaders: { "Retry-After": "120" },
79
+ });
80
+ table.record("p/rfc850", refusal("Thursday, 08-Oct-26 00:02:00 GMT"));
81
+ table.record("p/asctime", refusal("Thu Oct 8 00:02:00 2026"));
82
+ expect(table.live().map((entry) => entry.until)).toEqual([
83
+ epoch + 120_000,
84
+ epoch + 190_000_000,
85
+ epoch + 120_000,
86
+ epoch + 120_000,
87
+ epoch + 120_000,
88
+ ]);
89
+ });
90
+
91
+ test("ignores missing, invalid, nonfinite, past and prose reset times and unrelated failures", () => {
92
+ const table = new HiddenModelCooldowns(() => epoch);
93
+ const failures: unknown[] = [
94
+ { data: { statusCode: 412, message: "Quota resets in 52h 38m" } },
95
+ { type: "provider.rate-limit", status: 429, message: "Quota exhausted" },
96
+ new Error("timeout"),
97
+ refusal("190000", 500),
98
+ refusal("190000", 401),
99
+ refusal("190000", 404),
100
+ ...[
101
+ "0",
102
+ "-1",
103
+ "1.5",
104
+ "NaN",
105
+ "Infinity",
106
+ "1e10",
107
+ "52h 38m",
108
+ "120 seconds",
109
+ "Wed, 07 Oct 2026 00:00:00 GMT",
110
+ ].map((delay) => refusal(delay)),
111
+ { status: 429, retryAfterMs: Number.POSITIVE_INFINITY },
112
+ { status: 429, retryAfterMs: Number.NaN },
113
+ ];
114
+ for (const error of failures) table.record("p/model", error);
115
+ expect(table.live()).toEqual([]);
116
+ });
117
+ });
@@ -0,0 +1,123 @@
1
+ import type { ModelInput } from "./model-resolution";
2
+ import { isRecord } from "./record-type-guard";
3
+ import { toModelEntry } from "./resolve-fallbacks";
4
+
5
+ const MAX_SKIP_MS = 7 * 24 * 60 * 60 * 1_000;
6
+ const MIN_SKIP_MS = 60_000;
7
+ // Quota (412), rate limit (429) and overload (503) all arrive as "not before this time",
8
+ // so the wording names what the provider said, not why.
9
+ const RETRY_LATER_REASON = "provider said to retry later";
10
+
11
+ export interface HiddenModelCooldown {
12
+ model: string;
13
+ until: number;
14
+ reason: string;
15
+ }
16
+
17
+ /** Process-local provider evidence, shared by hidden agents but never by user requests. */
18
+ export class HiddenModelCooldowns {
19
+ private readonly entries = new Map<string, HiddenModelCooldown>();
20
+
21
+ constructor(private readonly now: () => number = () => Date.now()) {}
22
+
23
+ record(model: string | undefined, error: unknown): void {
24
+ if (!model?.includes("/")) return;
25
+ const now = this.now();
26
+ const delay = retryDelay(error, now);
27
+ if (delay === undefined || !Number.isFinite(delay) || delay <= MIN_SKIP_MS) return;
28
+ this.entries.set(model, {
29
+ model,
30
+ until: now + Math.min(delay, MAX_SKIP_MS),
31
+ reason: RETRY_LATER_REASON,
32
+ });
33
+ }
34
+
35
+ succeeded(model: string | undefined): void {
36
+ if (model) this.entries.delete(model);
37
+ }
38
+
39
+ live(): HiddenModelCooldown[] {
40
+ const now = this.now();
41
+ for (const [model, entry] of this.entries) {
42
+ if (entry.until <= now) this.entries.delete(model);
43
+ }
44
+ return [...this.entries.values()];
45
+ }
46
+
47
+ startIndex(models: readonly string[], log: (message: string) => void): number {
48
+ const live = new Map(this.live().map((entry) => [entry.model, entry]));
49
+ let start = models.findIndex((model) => !live.has(model));
50
+ // Even a fully exhausted chain must try a model, rather than suppress work.
51
+ if (start < 0) {
52
+ start = 0;
53
+ for (let i = 1; i < models.length; i++) {
54
+ if (
55
+ (live.get(models[i])?.until ?? Infinity) <
56
+ (live.get(models[start])?.until ?? Infinity)
57
+ )
58
+ start = i;
59
+ }
60
+ }
61
+ const logged = new Set<string>();
62
+ for (const model of models.slice(0, start)) {
63
+ const entry = live.get(model);
64
+ if (entry && !logged.has(model)) {
65
+ log(
66
+ `skipping ${model} until ${new Date(entry.until).toISOString()}: provider said to retry later`,
67
+ );
68
+ logged.add(model);
69
+ }
70
+ }
71
+ return start;
72
+ }
73
+ }
74
+
75
+ function retryDelay(error: unknown, now: number, depth = 0): number | undefined {
76
+ if (!isRecord(error) || depth > 4) return undefined;
77
+ const data =
78
+ typeof error.statusCode === "number" || typeof error.status === "number"
79
+ ? error
80
+ : isRecord(error.data)
81
+ ? error.data
82
+ : error;
83
+ const status = data.statusCode ?? data.status;
84
+ if (status === 412 || status === 429 || status === 503) {
85
+ // OpenCode 2.2 exposes milliseconds; OpenCode 1 retains the HTTP headers.
86
+ if (typeof data.retryAfterMs === "number") return data.retryAfterMs;
87
+ const headers = data.responseHeaders;
88
+ if (isRecord(headers)) {
89
+ const value = Object.entries(headers).find(
90
+ ([name]) => name.toLowerCase() === "retry-after",
91
+ )?.[1];
92
+ if (typeof value === "string") {
93
+ const text = value.trim();
94
+ if (/^\d+$/.test(text)) return Number(text) * 1_000;
95
+ // Require an HTTP-date shape: Date.parse also accepts bare numbers and prose.
96
+ if (
97
+ /^(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT|(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), \d{2}-[A-Z][a-z]{2}-\d{2} \d{2}:\d{2}:\d{2} GMT|(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) [A-Z][a-z]{2} [ \d]\d \d{2}:\d{2}:\d{2} \d{4})$/.test(
98
+ text,
99
+ )
100
+ )
101
+ return Date.parse(text) - now;
102
+ }
103
+ }
104
+ }
105
+ return retryDelay(error.hostError ?? error.cause, now, depth + 1);
106
+ }
107
+
108
+ export const hiddenModelCooldowns = new HiddenModelCooldowns();
109
+
110
+ /** Change only the starting point; failures still continue down the configured suffix. */
111
+ export function selectHiddenModelStart(
112
+ primary: ModelInput | undefined,
113
+ fallbacks: readonly ModelInput[] = [],
114
+ note: (message: string) => void,
115
+ ): { primary: ModelInput | undefined; fallbacks: readonly ModelInput[] } {
116
+ if (!primary) return { primary, fallbacks };
117
+ const chain = [primary, ...fallbacks];
118
+ const start = hiddenModelCooldowns.startIndex(
119
+ chain.map((entry) => toModelEntry(entry)?.model ?? ""),
120
+ note,
121
+ );
122
+ return { primary: chain[start], fallbacks: chain.slice(start + 1) };
123
+ }
@@ -1,8 +1,7 @@
1
1
  import { describe, expect, mock, spyOn, test } from "bun:test";
2
- import { withDreamerModelCooldown } from "../features/magic-context/dreamer/provider-output-failure";
3
2
  import { recordedGeminiQuotaMessages } from "../features/magic-context/dreamer/provider-output-failure.test-support";
4
-
5
3
  import { HiddenAgentStepLimit } from "../v2/hooks/hidden-child";
4
+ import { hiddenModelCooldowns } from "./hidden-model-cooldown";
6
5
  import {
7
6
  getPromptFailureDetail,
8
7
  noteModelActivityMonitored,
@@ -422,104 +421,82 @@ describe("promptSyncWithModelSuggestionRetry", () => {
422
421
  });
423
422
  });
424
423
 
425
- describe("run-scoped primary quota cooldown", () => {
426
- test("preserves fallback order, retries the primary after reset, and forgets it in a new run", async () => {
424
+ describe("process-wide hidden model quota cooldown", () => {
425
+ test("structured refusal makes later runs start on the fallback, then expires", async () => {
427
426
  let now = 1791425104275;
428
427
  const clock = spyOn(Date, "now").mockImplementation(() => now);
429
428
  const models: string[] = [];
430
- const primary = { providerID: "google", modelID: "antigravity-gemini-3.8-flash" };
431
- let latestModel = "";
432
- let primaryCalls = 0;
429
+ const primary = { providerID: "quota-test", modelID: "primary" };
433
430
  const client = createClient(
434
431
  mock(async (args: PromptCall) => {
435
- latestModel = `${args.body.model?.providerID}/${args.body.model?.modelID}`;
436
- models.push(latestModel);
437
- if (latestModel.startsWith("google/")) primaryCalls++;
438
- if (latestModel === "deepseek/first") throw new Error("fallback unavailable");
432
+ const model = `${args.body.model?.providerID}/${args.body.model?.modelID}`;
433
+ models.push(model);
434
+ if (model === "quota-test/primary" && models.length === 1)
435
+ throw Object.assign(new Error("provider quota exhausted"), {
436
+ statusCode: 412,
437
+ responseHeaders: { "retry-after": "190000" },
438
+ });
439
+ if (model === "quota-test/first") throw new Error("fallback unavailable");
439
440
  return {};
440
441
  }),
441
442
  );
442
443
  const run = () =>
443
444
  promptSyncWithValidatedOutputRetry(client, createArgs(primary), {
444
- fallbackModels: ["deepseek/first", "deepseek/second"],
445
- fetchOutput: async () =>
446
- latestModel.startsWith("google/") && primaryCalls <= 2
447
- ? recordedGeminiQuotaMessages()
448
- : [
449
- {
450
- info: { role: "assistant" },
451
- parts: [{ type: "text", text: "valid" }],
452
- },
453
- ],
454
- validateOutput: () => "valid",
445
+ fallbackModels: ["quota-test/first", "quota-test/second"],
446
+ fetchOutput: async () => "valid",
447
+ validateOutput: (output) => output,
455
448
  });
456
449
  try {
457
- await withDreamerModelCooldown(async () => {
458
- await run();
459
- await run();
460
- });
461
- await withDreamerModelCooldown(async () => {
462
- await run();
463
- await run();
464
- now += 5_700_000;
465
- await run();
466
- });
450
+ await run();
451
+ await run();
452
+ now += 190_000_000;
453
+ await run();
467
454
  expect(models).toEqual([
468
- "google/antigravity-gemini-3.8-flash",
469
- "deepseek/first",
470
- "deepseek/second",
471
- "deepseek/first",
472
- "deepseek/second",
473
- "google/antigravity-gemini-3.8-flash",
474
- "deepseek/first",
475
- "deepseek/second",
476
- "deepseek/first",
477
- "deepseek/second",
478
- "google/antigravity-gemini-3.8-flash",
455
+ "quota-test/primary",
456
+ "quota-test/first",
457
+ "quota-test/second",
458
+ "quota-test/first",
459
+ "quota-test/second",
460
+ "quota-test/primary",
479
461
  ]);
480
462
  } finally {
463
+ hiddenModelCooldowns.succeeded("quota-test/primary");
481
464
  clock.mockRestore();
482
465
  }
483
466
  });
484
467
 
485
- test("records primary quota exhaustion alongside a failing fallback, not a manifest error", async () => {
486
- let model = "";
468
+ test("a prose quota notice still falls back but never creates a cooldown", async () => {
469
+ const models: string[] = [];
470
+ let latest = "";
487
471
  const client = createClient(
488
472
  mock(async (args: PromptCall) => {
489
- model = args.body.model?.providerID ?? "";
490
- if (model === "deepseek") throw new Error("SessionExecutionFence.Lost");
473
+ latest = `${args.body.model?.providerID}/${args.body.model?.modelID}`;
474
+ models.push(latest);
491
475
  return {};
492
476
  }),
493
477
  );
494
- let caught: unknown;
495
- await withDreamerModelCooldown(async () => {
496
- try {
497
- await promptSyncWithValidatedOutputRetry(
498
- client,
499
- createArgs({ providerID: "google", modelID: "antigravity-gemini-3.8-flash" }),
500
- {
501
- fallbackModels: ["deepseek/deepseek-flash"],
502
- fetchOutput: async () => recordedGeminiQuotaMessages(),
503
- validateOutput: () => {
504
- throw new Error("verify manifest missing complete root element");
505
- },
506
- },
507
- );
508
- } catch (error) {
509
- caught = error;
510
- }
511
- });
512
- expect(String(caught)).toContain("primary quota exhausted until");
513
- expect(String(caught)).toContain("SessionExecutionFence.Lost");
514
- expect(String(caught)).not.toContain("manifest missing");
515
- expect(getPromptFailureDetail(caught)).toMatchObject({
516
- failureClass: "provider_error",
517
- modelAttempted: "deepseek/deepseek-flash",
518
- modelsTried: ["google/antigravity-gemini-3.8-flash", "deepseek/deepseek-flash"],
519
- });
520
- expect(getPromptFailureDetail(caught)?.providerError).toContain(
521
- "primary quota exhausted until",
522
- );
478
+ const run = () =>
479
+ promptSyncWithValidatedOutputRetry(
480
+ client,
481
+ createArgs({ providerID: "quota-prose", modelID: "primary" }),
482
+ {
483
+ fallbackModels: ["quota-prose/fallback"],
484
+ fetchOutput: async () =>
485
+ latest.endsWith("/primary") ? recordedGeminiQuotaMessages() : [],
486
+ validateOutput: () => "valid",
487
+ },
488
+ );
489
+ await run();
490
+ await run();
491
+ expect(models).toEqual([
492
+ "quota-prose/primary",
493
+ "quota-prose/fallback",
494
+ "quota-prose/primary",
495
+ "quota-prose/fallback",
496
+ ]);
497
+ expect(
498
+ hiddenModelCooldowns.live().some((entry) => entry.model === "quota-prose/primary"),
499
+ ).toBe(false);
523
500
  });
524
501
  });
525
502