@cortexkit/opencode-magic-context 0.49.49 → 0.49.50

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 (136) 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-4js5qnnm.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/storage-db.d.ts +14 -0
  21. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  22. package/dist/features/magic-context/transform-decision-log.d.ts +2 -0
  23. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
  25. package/dist/{index-qb75tv9j.js → index-07rp6xcn.js} +1 -1
  26. package/dist/{index-7n2n3v92.js → index-5dptmnvd.js} +2 -2
  27. package/dist/{index-j7verehm.js → index-5g6npyw5.js} +36 -27
  28. package/dist/{index-5bksfv58.js → index-5t1mr0bt.js} +5 -5
  29. package/dist/{index-arxg51bj.js → index-8d7gkgjs.js} +4 -3
  30. package/dist/{index-wdmfnmv1.js → index-97bjd14c.js} +4 -4
  31. package/dist/{index-0mdh2cke.js → index-bamnjp2t.js} +20 -4
  32. package/dist/{index-5850zme4.js → index-ct3ettqt.js} +3 -3
  33. package/dist/{index-3n9ee4jh.js → index-cwj6qhmf.js} +1 -1
  34. package/dist/{index-va9x7y48.js → index-h8g08nxs.js} +135 -81
  35. package/dist/{index-jedbxq6n.js → index-hkveze74.js} +1 -1
  36. package/dist/{index-4dpvnp8k.js → index-jjy5a5w0.js} +3 -0
  37. package/dist/{index-h3p558ec.js → index-mjh63zvw.js} +1 -1
  38. package/dist/{index-vyv4tame.js → index-n0twfvah.js} +53 -2
  39. package/dist/{index-tj5gz396.js → index-rbs27k1d.js} +4 -2
  40. package/dist/{index-cs7pmwt6.js → index-s131svmx.js} +1 -1
  41. package/dist/{index-vbmh68fb.js → index-v4a1pnny.js} +4 -4
  42. package/dist/{index-k47v0tmk.js → index-wr2t8zb0.js} +8 -8
  43. package/dist/{index-agfh931z.js → index-z4832qfe.js} +4 -2
  44. package/dist/index.js +22 -22
  45. package/dist/{message-index-bounded-2shxmht9.js → message-index-bounded-k0ebpy3y.js} +3 -3
  46. package/dist/migration-worker.js +1 -1
  47. package/dist/plugin/embedding-bootstrap-helpers.d.ts.map +1 -1
  48. package/dist/plugin/embedding-routing.d.ts.map +1 -1
  49. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  50. package/dist/plugin/rpc-handlers.d.ts.map +1 -1
  51. package/dist/{project-embedding-registry-nzgkq61z.js → project-embedding-registry-5dwh5zfn.js} +3 -3
  52. package/dist/raw-ordinal-warmup-worker.js +3 -3
  53. package/dist/{read-session-chunk-c15y8yg6.js → read-session-chunk-6712p893.js} +2 -2
  54. package/dist/{recomp-orchestrator-gfxqqpph.js → recomp-orchestrator-8ebydg5j.js} +11 -11
  55. package/dist/{render-5tx8r0me.js → render-dtc4qkq4.js} +6 -6
  56. package/dist/{search-archive-6tgh88xp.js → search-archive-f6hjbnsa.js} +4 -4
  57. package/dist/{search-k2n5bvsk.js → search-edv0gy1d.js} +9 -9
  58. package/dist/shared/hidden-model-cooldown.d.ts +23 -0
  59. package/dist/shared/hidden-model-cooldown.d.ts.map +1 -0
  60. package/dist/shared/model-suggestion-retry.d.ts +0 -2
  61. package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
  62. package/dist/shared/provider-response-completion.d.ts +10 -0
  63. package/dist/shared/provider-response-completion.d.ts.map +1 -1
  64. package/dist/shared/rpc-types.d.ts +1 -0
  65. package/dist/shared/rpc-types.d.ts.map +1 -1
  66. package/dist/shared/status-summary.d.ts +1 -0
  67. package/dist/shared/status-summary.d.ts.map +1 -1
  68. package/dist/shared/status-view-check.d.ts.map +1 -1
  69. package/dist/shared/status-view.d.ts +1 -0
  70. package/dist/shared/status-view.d.ts.map +1 -1
  71. package/dist/shared/test-db.d.ts +13 -0
  72. package/dist/shared/test-db.d.ts.map +1 -0
  73. package/dist/test-preload.d.ts +2 -0
  74. package/dist/test-preload.d.ts.map +1 -0
  75. package/dist/{transform-postprocess-phase-36dw4kxb.js → transform-postprocess-phase-1bg25094.js} +12 -12
  76. package/dist/v2/auto-search-worker.js +3 -3
  77. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  78. package/dist/v2/{context-td3jyze3.js → context-qkr7z6d0.js} +47 -30
  79. package/dist/v2/{embedding-backfill-5dqdm3ff.js → embedding-backfill-x1zpc04f.js} +4 -4
  80. package/dist/v2/embedding-worker.js +2 -2
  81. package/dist/v2/hidden-completion.d.ts.map +1 -1
  82. package/dist/v2/hooks/context.d.ts.map +1 -1
  83. package/dist/v2/hooks/usage-persist.d.ts +1 -1
  84. package/dist/v2/hooks/usage-persist.d.ts.map +1 -1
  85. package/dist/v2/hooks/usage-reading.d.ts +3 -0
  86. package/dist/v2/hooks/usage-reading.d.ts.map +1 -1
  87. package/dist/v2/{message-index-bounded-j1jskn8a.js → message-index-bounded-a36rw93p.js} +3 -3
  88. package/dist/v2/migration-worker.js +1 -1
  89. package/dist/v2/{project-embedding-registry-swm4mw1t.js → project-embedding-registry-v2fxrs8b.js} +3 -3
  90. package/dist/v2/raw-ordinal-warmup-worker.js +3 -3
  91. package/dist/v2/{read-session-chunk-carzw3m8.js → read-session-chunk-hzhxvhyv.js} +2 -2
  92. package/dist/v2/{recomp-orchestrator-e7vrs932.js → recomp-orchestrator-yzr49pd0.js} +11 -11
  93. package/dist/v2/{render-e9mh9y1d.js → render-rhaevxv1.js} +6 -6
  94. package/dist/v2/{search-archive-j3kb9ggd.js → search-archive-9924fyk8.js} +4 -4
  95. package/dist/v2/{search-sr23g316.js → search-ggvexvv7.js} +8 -8
  96. package/dist/v2/{server-z7n3n1ra.js → server-016a1whm.js} +134 -81
  97. package/dist/v2/{server-4y2pcckw.js → server-0k586y7d.js} +3 -3
  98. package/dist/v2/{server-p9s40wfa.js → server-0ms13pc8.js} +3 -0
  99. package/dist/v2/{server-c5kq8d5n.js → server-16kfxcxj.js} +1 -1
  100. package/dist/v2/{server-2qxt6qv0.js → server-3bfc26r7.js} +1 -1
  101. package/dist/v2/{server-e20kfytm.js → server-3qf9n5ck.js} +4 -4
  102. package/dist/v2/{server-fw49gc57.js → server-4h4acntc.js} +20 -4
  103. package/dist/v2/{server-yxe0gh3v.js → server-88yvx6r9.js} +53 -2
  104. package/dist/v2/{server-1ppcpsdw.js → server-brsx45r6.js} +4 -2
  105. package/dist/v2/{server-y7q8cds3.js → server-jxrqsn84.js} +1 -1
  106. package/dist/v2/{server-t5cgb15n.js → server-q93jdtz8.js} +2 -2
  107. package/dist/v2/{server-ttrrh27h.js → server-sb55ddgn.js} +3 -2
  108. package/dist/v2/{server-e14c3hd6.js → server-scp3y4dh.js} +4 -2
  109. package/dist/v2/{server-0qxb8r8q.js → server-sgn61hht.js} +1 -1
  110. package/dist/v2/{server-r7y35vm9.js → server-vjadwb3j.js} +4 -3
  111. package/dist/v2/server.js +4 -4
  112. package/dist/v2/{v2-archive-reader-jnzjavzr.js → v2-archive-reader-5ggewg8q.js} +1 -1
  113. package/dist/v2/{wrapup-orchestrator-jw4nre49.js → wrapup-orchestrator-36c5wyvq.js} +11 -11
  114. package/dist/{v2-archive-reader-b76tfeje.js → v2-archive-reader-gx5ke1d7.js} +1 -1
  115. package/dist/{wrapup-orchestrator-fhfazjkq.js → wrapup-orchestrator-ya31knav.js} +12 -12
  116. package/package.json +1 -1
  117. package/src/config/index.test.ts +20 -0
  118. package/src/config/project-security.test.ts +5 -1
  119. package/src/config/project-security.ts +4 -0
  120. package/src/config/schema/magic-context.test.ts +43 -0
  121. package/src/config/schema/magic-context.ts +19 -0
  122. package/src/shared/hidden-model-cooldown.test.ts +117 -0
  123. package/src/shared/hidden-model-cooldown.ts +123 -0
  124. package/src/shared/model-suggestion-retry.test.ts +53 -76
  125. package/src/shared/model-suggestion-retry.ts +38 -53
  126. package/src/shared/provider-response-completion.test.ts +49 -0
  127. package/src/shared/provider-response-completion.ts +64 -0
  128. package/src/shared/rpc-types.ts +1 -0
  129. package/src/shared/startup-maintenance-policy.test.ts +115 -0
  130. package/src/shared/status-detail-text.test.ts +7 -0
  131. package/src/shared/status-summary.ts +3 -0
  132. package/src/shared/status-view-check.ts +1 -0
  133. package/src/shared/status-view.test.ts +15 -0
  134. package/src/shared/status-view.ts +11 -1
  135. package/src/shared/test-db.test.ts +84 -0
  136. package/src/shared/test-db.ts +36 -0
@@ -1,9 +1,7 @@
1
1
  import type { createOpencodeClient } from "@opencode-ai/sdk";
2
2
  import {
3
- DreamerProviderOutputFailureError,
4
- primaryQuotaFailure,
3
+ isAccountPoolQuotaNotice,
5
4
  providerOutputFailureFromInvalidManifest,
6
- rememberPrimaryQuota,
7
5
  } from "../features/magic-context/dreamer/provider-output-failure";
8
6
  import { DreamTokenBudgetExceeded } from "../features/magic-context/dreamer/token-budget";
9
7
  import { detectOverflow } from "../features/magic-context/overflow-detection";
@@ -15,10 +13,11 @@ import {
15
13
  extractLatestAssistantFailure,
16
14
  extractLatestAssistantText,
17
15
  } from "./assistant-message-extractor";
16
+ import { hiddenModelCooldowns, selectHiddenModelStart } from "./hidden-model-cooldown";
18
17
  import { log } from "./logger";
19
18
  import type { ModelInput } from "./model-resolution";
20
19
  import { sanitizeDiagnosticText } from "./redaction";
21
- import { parseProviderModel, toModelEntry } from "./resolve-fallbacks";
20
+ import { modelBodyField, parseProviderModel, toModelEntry } from "./resolve-fallbacks";
22
21
 
23
22
  type Client = ReturnType<typeof createOpencodeClient> | undefined;
24
23
 
@@ -67,8 +66,6 @@ export interface PromptAttemptInfo {
67
66
  totalAttempts: number;
68
67
  /** Explicit model override for this attempt, when one was supplied. */
69
68
  model?: { providerID: string; modelID: string };
70
- /** A run-local quota deadline prevented dispatch; not an actual model call. */
71
- skipped?: boolean;
72
69
  }
73
70
 
74
71
  export interface PromptRetryOptions {
@@ -553,25 +550,14 @@ function throwWithPromptFailure(
553
550
  legacyError instanceof Error ? legacyError : new Error(extractMessage(legacyError));
554
551
  const last = failedAttempts.at(-1);
555
552
  const failureClass = last?.failureClass ?? "unknown";
556
- const quota = failedAttempts.find(
557
- (failure) =>
558
- failure.error instanceof DreamerProviderOutputFailureError &&
559
- failure.error.quotaResetAt !== undefined,
560
- )?.error as DreamerProviderOutputFailureError | undefined;
561
- if (quota && error !== quota && !error.message.includes(quota.message))
562
- error.message = `${quota.message}; ${error.message}`;
563
553
  const providerError =
564
- failureClass === "provider_error" || quota
565
- ? sanitizeDiagnosticText(
566
- `${quota ? `${quota.message}; ` : ""}${shortErr(last?.error ?? legacyError)}`,
567
- ).slice(0, 500)
554
+ failureClass === "provider_error"
555
+ ? sanitizeDiagnosticText(shortErr(last?.error ?? legacyError)).slice(0, 500)
568
556
  : null;
569
557
  promptFailureDetails.set(error, {
570
558
  failureClass,
571
559
  modelAttempted: last?.attempt.label ?? null,
572
- modelsTried: failedAttempts
573
- .filter((failure) => !failure.attempt.skipped)
574
- .map((failure) => failure.attempt.label),
560
+ modelsTried: failedAttempts.map((failure) => failure.attempt.label),
575
561
  providerError,
576
562
  timeoutMs: failureClass === "provider_timeout" ? timeoutMs : null,
577
563
  childSessionId: transport ? (transport.childSessionId ?? null) : args.path.id || null,
@@ -618,6 +604,8 @@ async function attemptOnce(
618
604
  } catch (error) {
619
605
  // Non-retryable failures and callers with model suggestions disabled
620
606
  // must surface the original error without accepting a provider suggestion.
607
+ if (!signal?.aborted && !isPromptTimeoutError(error))
608
+ hiddenModelCooldowns.record(label, error);
621
609
  if (isNonRetryable(error, signal) || !allowModelSuggestions) throw error;
622
610
 
623
611
  const suggestion = parseModelSuggestion(error);
@@ -686,6 +674,24 @@ function createChainClock(options: PromptRetryOptions, timeoutMs: number) {
686
674
  };
687
675
  }
688
676
 
677
+ function cooldownStart<T extends PromptRetryOptions>(
678
+ args: PromptArgs,
679
+ options: T,
680
+ ): { args: PromptArgs; options: T } {
681
+ const model = args.body.model;
682
+ if (!model) return { args, options };
683
+ const selected = selectHiddenModelStart(
684
+ { model: `${model.providerID}/${model.modelID}`, qualifier: args.body.variant },
685
+ options.fallbackModels,
686
+ log,
687
+ );
688
+ const { variant: _variant, ...body } = args.body;
689
+ return {
690
+ args: copyPromptArgs(args, { ...body, ...modelBodyField(selected.primary) }),
691
+ options: { ...options, fallbackModels: selected.fallbacks },
692
+ };
693
+ }
694
+
689
695
  /**
690
696
  * Run an OpenCode subagent prompt with model fallback support.
691
697
  *
@@ -705,6 +711,7 @@ export async function promptSyncWithModelSuggestionRetry(
705
711
  args: PromptArgs,
706
712
  options: PromptRetryOptions = {},
707
713
  ): Promise<void> {
714
+ ({ args, options } = cooldownStart(args, options));
708
715
  const timeoutMs = options.timeoutMs ?? 300_000;
709
716
  const callContext = options.callContext ?? "subagent";
710
717
  const fallbacks = options.fallbackModels ?? [];
@@ -848,6 +855,8 @@ async function attemptAndValidate<TOutput, TValidated>(
848
855
  try {
849
856
  output = await raceWithSignal(options.fetchOutput(args, attempt), options.signal);
850
857
  } catch (error) {
858
+ if (!signal?.aborted && !isPromptTimeoutError(error))
859
+ hiddenModelCooldowns.record(attempt.label, error);
851
860
  throw {
852
861
  error,
853
862
  failureClass: classifyPromptFailure(error, "output", signal),
@@ -856,7 +865,7 @@ async function attemptAndValidate<TOutput, TValidated>(
856
865
  }
857
866
 
858
867
  try {
859
- // Only the structured account-pool notice bypasses caller validation.
868
+ // Only the exact account-pool notice bypasses caller validation.
860
869
  // The near-zero-token heuristic remains owned by manifest callers.
861
870
  const messages = Array.isArray(output)
862
871
  ? output
@@ -864,7 +873,7 @@ async function attemptAndValidate<TOutput, TValidated>(
864
873
  const text = extractLatestAssistantText(messages);
865
874
  if (text) {
866
875
  const failure = providerOutputFailureFromInvalidManifest(messages, text);
867
- if (failure?.quotaResetAt !== undefined) throw failure;
876
+ if (failure && isAccountPoolQuotaNotice(text)) throw failure;
868
877
  }
869
878
  if (!extractLatestAssistantText(output)) {
870
879
  const assistantFailure = extractLatestAssistantFailure(output);
@@ -875,10 +884,13 @@ async function attemptAndValidate<TOutput, TValidated>(
875
884
  Object.assign(error, {
876
885
  name: "DreamerProviderOutputFailureError",
877
886
  transient: true,
887
+ hostError: assistantFailure.error,
878
888
  });
889
+ hiddenModelCooldowns.record(attempt.label, assistantFailure.error);
879
890
  throw error;
880
891
  }
881
892
  }
893
+ hiddenModelCooldowns.succeeded(attempt.label);
882
894
  const validated = await options.validateOutput(output, attempt);
883
895
  return { output, validated, attempt };
884
896
  } catch (error) {
@@ -903,6 +915,7 @@ export async function promptSyncWithValidatedOutputRetry<TOutput, TValidated = T
903
915
  args: PromptArgs,
904
916
  options: ValidatedPromptRetryOptions<TOutput, TValidated>,
905
917
  ): Promise<ValidatedPromptRetryResult<TOutput, TValidated>> {
918
+ ({ args, options } = cooldownStart(args, options));
906
919
  const timeoutMs = options.timeoutMs ?? 300_000;
907
920
  const callContext = options.callContext ?? "subagent";
908
921
  const fallbacks = options.fallbackModels ?? [];
@@ -920,24 +933,10 @@ export async function promptSyncWithValidatedOutputRetry<TOutput, TValidated = T
920
933
  const failedAttempts: FailedAttempt[] = [];
921
934
  let firstError: unknown = null;
922
935
  let lastError: unknown = null;
923
- const cooledPrimary = primaryQuotaFailure(explicitPrimaryLabel);
924
936
  const clock = createChainClock(options, timeoutMs);
925
937
 
926
938
  const primaryStartedAt = Date.now();
927
939
  try {
928
- if (cooledPrimary)
929
- throw {
930
- error: cooledPrimary,
931
- failureClass: "provider_error",
932
- attempt: {
933
- label: explicitPrimaryLabel,
934
- attemptIndex: 0,
935
- isFallback: false,
936
- totalAttempts,
937
- model: baseBody.model,
938
- skipped: true,
939
- },
940
- } satisfies FailedAttempt;
941
940
  const budget = clock.budget(0);
942
941
  return await attemptAndValidate(
943
942
  client,
@@ -961,19 +960,6 @@ export async function promptSyncWithValidatedOutputRetry<TOutput, TValidated = T
961
960
  clock.settle(failure.error, primaryStartedAt);
962
961
  firstError = failure.error;
963
962
  lastError = failure.error;
964
- if (
965
- failure.error instanceof DreamerProviderOutputFailureError &&
966
- failure.error.quotaResetAt !== undefined
967
- )
968
- failure.error.message = failure.error.message.replace(
969
- /^provider quota exhausted/,
970
- "primary quota exhausted",
971
- );
972
- const quota = !cooledPrimary && rememberPrimaryQuota(explicitPrimaryLabel, failure.error);
973
- if (quota)
974
- log(
975
- `[${callContext}] ${quota.message}; skipping ${explicitPrimaryLabel} for this run until reset`,
976
- );
977
963
  if (isNonRetryable(failure.error, options.signal)) {
978
964
  throwWithPromptFailure(
979
965
  failure.error,
@@ -994,10 +980,9 @@ export async function promptSyncWithValidatedOutputRetry<TOutput, TValidated = T
994
980
  );
995
981
  }
996
982
 
997
- if (!cooledPrimary && !quota)
998
- log(
999
- `[${callContext}] primary (${explicitPrimaryLabel}) failed validation/prompt: ${shortErr(failure.error)}; ${fallbacks.length} fallback(s) configured, subject to remaining budget`,
1000
- );
983
+ log(
984
+ `[${callContext}] primary (${explicitPrimaryLabel}) failed validation/prompt: ${shortErr(failure.error)}; ${fallbacks.length} fallback(s) configured, subject to remaining budget`,
985
+ );
1001
986
  }
1002
987
 
1003
988
  for (let i = 0; i < fallbacks.length; i += 1) {
@@ -0,0 +1,49 @@
1
+ import { expect, test } from "bun:test";
2
+ import * as completion from "./provider-response-completion";
3
+
4
+ for (const location of ["native", "state"]) {
5
+ test(`detects usage and boundary markers in ${location}.signature`, () => {
6
+ for (const [signature, expected] of [
7
+ [
8
+ 'cortexkit-server-fallback-usage-v1:{"iterations":[{"type":"fallback_message","input_tokens":1}]}',
9
+ { kind: "usage", inputTokens: 1 },
10
+ ],
11
+ [
12
+ "cortexkit-server-fallback-v1:primary|fallback",
13
+ { kind: "boundary", invalidUsage: false },
14
+ ],
15
+ ] as const) {
16
+ const content = [{ type: "reasoning", [location]: { signature } }];
17
+ expect(completion.hasServerFallbackUsage(content)).toBe(true);
18
+ expect(completion.readServerFallbackUsage(content)).toEqual(expected);
19
+ }
20
+ });
21
+ }
22
+
23
+ test("detects server-fallback usage only in the marked reasoning part", () => {
24
+ const content = [
25
+ { type: "reasoning", text: "thinking", native: { signature: "real-signature" } },
26
+ {
27
+ type: "reasoning",
28
+ text: " ",
29
+ native: {
30
+ signature: "cortexkit-server-fallback-v1:claude-opus-5-5|claude-opus-4-8",
31
+ },
32
+ },
33
+ { type: "text", text: "answer" },
34
+ { type: "tool", name: "read" },
35
+ ];
36
+ expect(completion.hasServerFallbackUsage(content)).toBe(true);
37
+ expect(completion.hasServerFallbackUsage([content[0], content[2]])).toBe(false);
38
+ for (const invalid of [
39
+ undefined,
40
+ null,
41
+ {},
42
+ [null, {}, { type: "reasoning", native: { signature: 3 } }],
43
+ [{ type: "text", native: content[1]!.native }],
44
+ [{ type: "reasoning", native: { signature: "cortexkit-server-fallback-v10:models" } }],
45
+ [{ type: "reasoning", native: { signature: "other-cortexkit-server-fallback-v1:models" } }],
46
+ ]) {
47
+ expect(completion.hasServerFallbackUsage(invalid)).toBe(false);
48
+ }
49
+ });
@@ -1,3 +1,67 @@
1
+ import { isRecord } from "./record-type-guard";
2
+
3
+ const SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX = "cortexkit-server-fallback-usage-v1:";
4
+ const SERVER_FALLBACK_SIGNATURE_PREFIX = "cortexkit-server-fallback-v1:";
5
+
6
+ export function hasServerFallbackUsage(content: unknown): boolean {
7
+ return readServerFallbackUsage(content) !== undefined;
8
+ }
9
+
10
+ type ServerFallbackUsage =
11
+ | { kind: "usage"; inputTokens: number }
12
+ | { kind: "boundary"; invalidUsage: boolean };
13
+
14
+ function parseServerFallbackInputTokens(json: string): number | undefined {
15
+ try {
16
+ const payload: unknown = JSON.parse(json);
17
+ if (!isRecord(payload) || !Array.isArray(payload.iterations)) return undefined;
18
+ let last: unknown;
19
+ for (const entry of payload.iterations) {
20
+ if (isRecord(entry) && entry.type === "fallback_message") last = entry;
21
+ }
22
+ if (!isRecord(last)) return undefined;
23
+ const counts = [
24
+ last.input_tokens,
25
+ last.cache_read_input_tokens ?? 0,
26
+ last.cache_creation_input_tokens ?? 0,
27
+ ];
28
+ if (
29
+ !counts.every(
30
+ (count) => typeof count === "number" && Number.isFinite(count) && count >= 0,
31
+ )
32
+ )
33
+ return undefined;
34
+ const inputTokens = counts.reduce<number>((sum, count) => sum + Number(count), 0);
35
+ return Number.isFinite(inputTokens) ? inputTokens : undefined;
36
+ } catch {
37
+ // Invalid usage must not replace the previous pressure measurement.
38
+ return undefined;
39
+ }
40
+ }
41
+
42
+ export function readServerFallbackUsage(content: unknown): ServerFallbackUsage | undefined {
43
+ if (!Array.isArray(content)) return undefined;
44
+ let boundary = false;
45
+ let invalidUsage = false;
46
+ for (const part of content) {
47
+ if (!isRecord(part) || part.type !== "reasoning") continue;
48
+ for (const location of [part.native, part.state]) {
49
+ if (!isRecord(location) || typeof location.signature !== "string") continue;
50
+ const signature = location.signature;
51
+ if (signature.startsWith(SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX)) {
52
+ const inputTokens = parseServerFallbackInputTokens(
53
+ signature.slice(SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX.length),
54
+ );
55
+ if (inputTokens !== undefined) return { kind: "usage", inputTokens };
56
+ invalidUsage = true;
57
+ } else if (signature.startsWith(SERVER_FALLBACK_SIGNATURE_PREFIX)) {
58
+ boundary = true;
59
+ }
60
+ }
61
+ }
62
+ return boundary || invalidUsage ? { kind: "boundary", invalidUsage } : undefined;
63
+ }
64
+
1
65
  /** Failure markers take precedence over a completion timestamp or token usage. */
2
66
  export function providerResponseFailed(input: { finish?: unknown; error?: unknown }): boolean {
3
67
  if (input.error !== undefined && input.error !== null && input.error !== "") return true;
@@ -149,6 +149,7 @@ export interface SidebarSnapshot {
149
149
  /** Dreamer tasks whose last scheduled run failed. Empty when all of them are
150
150
  * healthy; absent on a database with no scheduler table yet. */
151
151
  dreamerFailures?: DreamTaskFailureState[];
152
+ hiddenModelSkips?: string[];
152
153
  dreamerSkipped?: string[];
153
154
  recompProgress?: {
154
155
  /** "recomp" → "Recomp" labels; "upgrade" → "Upgrade" labels. */
@@ -0,0 +1,115 @@
1
+ import { afterEach, expect, spyOn, test } from "bun:test";
2
+ import { readFileSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import ts from "typescript";
5
+ import * as messageTime from "../features/magic-context/message-time-backfill";
6
+ import {
7
+ __getDatabaseStartupStateForTests,
8
+ __setScheduleStartupMaintenanceOnOpenForTests,
9
+ __waitForDatabaseStartupForTests,
10
+ closeDatabase,
11
+ getPersistedSchemaVersion,
12
+ LATEST_SUPPORTED_VERSION,
13
+ openDatabase,
14
+ openDatabaseAsync,
15
+ } from "../features/magic-context/storage-db";
16
+ import * as warmup from "../hooks/magic-context/raw-ordinal-warmup";
17
+ import { createTestTempDir } from "./test-temp-dir";
18
+
19
+ const root = resolve(import.meta.dir, "../../../..");
20
+ const originalDataHome = process.env.XDG_DATA_HOME;
21
+
22
+ afterEach(async () => {
23
+ await closeDatabase();
24
+ if (originalDataHome === undefined) delete process.env.XDG_DATA_HOME;
25
+ else process.env.XDG_DATA_HOME = originalDataHome;
26
+ });
27
+
28
+ function preloads(packageName: string): string[] {
29
+ return Bun.TOML.parse(readFileSync(join(root, "packages", packageName, "bunfig.toml"), "utf8"))
30
+ .test.preload as string[];
31
+ }
32
+
33
+ test.each([
34
+ "plugin",
35
+ "pi-plugin",
36
+ ])("%s unit preload preserves isolation and disables startup maintenance", (packageName) => {
37
+ expect(preloads(packageName)).toEqual(["./src/test-preload.ts"]);
38
+ const path = join(root, "packages", packageName, "src/test-preload.ts");
39
+ const source = ts.createSourceFile(
40
+ path,
41
+ readFileSync(path, "utf8"),
42
+ ts.ScriptTarget.Latest,
43
+ true,
44
+ );
45
+ const statements = source.statements.map((statement) => statement.getText(source));
46
+ // Inspect statements, not comments: a commented-out policy must fail this guard.
47
+ expect(statements[0]).toBe(
48
+ 'await import(new URL("../test-preload.ts", import.meta.url).href);',
49
+ );
50
+ expect(statements.at(-1)).toBe("__setScheduleStartupMaintenanceOnOpenForTests(false);");
51
+ const storageModule =
52
+ packageName === "plugin"
53
+ ? "./features/magic-context/storage-db"
54
+ : "@magic-context/core/features/magic-context/storage-db";
55
+ expect(statements[1]).toMatch(
56
+ new RegExp(
57
+ `const \\{ __setScheduleStartupMaintenanceOnOpenForTests \\} = await import\\(\\s*"${storageModule}"\\s*\\);`,
58
+ ),
59
+ );
60
+ });
61
+
62
+ test("CLI uses the unit policy while end-to-end tests retain the shared isolation-only preload", () => {
63
+ expect(preloads("cli")).toEqual(["../plugin/src/test-preload.ts"]);
64
+ expect(preloads("e2e-tests")).toEqual(["../plugin/test-preload.ts"]);
65
+ const isolation = readFileSync(join(root, "packages/plugin/test-preload.ts"), "utf8");
66
+ expect(isolation).not.toContain("__setScheduleStartupMaintenanceOnOpenForTests");
67
+ expect(isolation).not.toContain("src/test-preload");
68
+ });
69
+
70
+ test.each([
71
+ "sync",
72
+ "async",
73
+ ] as const)("default unit %s open schedules no startup job, but an opted-in open does", async (mode) => {
74
+ process.env.XDG_DATA_HOME = createTestTempDir("mc-startup-policy-").dir;
75
+ const worker = spyOn(warmup, "runSessionWarmupWorker").mockResolvedValue({
76
+ ftsRowidBackfill: true,
77
+ });
78
+ const time = spyOn(messageTime, "startMessageTimeBackfill").mockResolvedValue();
79
+ const open = () => (mode === "sync" ? openDatabase() : openDatabaseAsync());
80
+ try {
81
+ const db = (await open())!;
82
+ expect(db).not.toBeNull();
83
+ expect(getPersistedSchemaVersion(db)).toBe(LATEST_SUPPORTED_VERSION);
84
+ expect(__getDatabaseStartupStateForTests(db)).toEqual({
85
+ timerScheduled: false,
86
+ running: null,
87
+ });
88
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
89
+ expect(worker).not.toHaveBeenCalled();
90
+ expect(time).not.toHaveBeenCalled();
91
+ await closeDatabase();
92
+
93
+ const previous = __setScheduleStartupMaintenanceOnOpenForTests(true);
94
+ try {
95
+ const optedIn = (await open())!;
96
+ expect(__getDatabaseStartupStateForTests(optedIn)).toEqual({
97
+ timerScheduled: true,
98
+ running: null,
99
+ });
100
+ await __waitForDatabaseStartupForTests(optedIn);
101
+ expect(__getDatabaseStartupStateForTests(optedIn)).toEqual({
102
+ timerScheduled: false,
103
+ running: expect.any(Promise),
104
+ });
105
+ expect(worker).toHaveBeenCalledTimes(1);
106
+ expect(time).toHaveBeenCalledTimes(1);
107
+ } finally {
108
+ __setScheduleStartupMaintenanceOnOpenForTests(previous);
109
+ }
110
+ } finally {
111
+ await closeDatabase();
112
+ worker.mockRestore();
113
+ time.mockRestore();
114
+ }
115
+ });
@@ -165,6 +165,13 @@ describe("status detail text", () => {
165
165
  expect(summary).not.toContain("manifest missing");
166
166
  });
167
167
 
168
+ test("shows live hidden-model quota skips in chat-only status", () => {
169
+ const value = "google/primary until 2026-10-10T04:46:40.000Z: provider said to retry later";
170
+ expect(
171
+ formatStatusDetailMarkdown({ ...STATUS_FIXTURE, hiddenModelSkips: [value] }),
172
+ ).toContain(value);
173
+ });
174
+
168
175
  test("keeps internal vocabulary and identifiers out of the summary", () => {
169
176
  const summary = formatStatusDetailMarkdown({
170
177
  ...STATUS_FIXTURE,
@@ -39,6 +39,7 @@ export interface UserStatusSummary {
39
39
  hiddenVariantWarnings?: string[];
40
40
  dreamerSkipped?: readonly string[];
41
41
  dreamerQuotas?: readonly string[];
42
+ hiddenModelSkips?: readonly string[];
42
43
  }
43
44
 
44
45
  /**
@@ -131,6 +132,7 @@ export function statusSummaryFromDetail(detail: StatusDetail): UserStatusSummary
131
132
  warnings: statusWarningsFromDetail(detail),
132
133
  hiddenVariantWarnings: detail.hiddenVariantWarnings ?? [],
133
134
  dreamerSkipped: detail.dreamerSkipped,
135
+ hiddenModelSkips: detail.hiddenModelSkips,
134
136
  dreamerQuotas: [
135
137
  ...new Set(
136
138
  (detail.dreamerFailures ?? []).flatMap((failure) => {
@@ -232,6 +234,7 @@ export function renderUserStatusSummary(
232
234
  }
233
235
  for (const skipped of summary.dreamerSkipped ?? []) values.push(["Dreamer skipped", skipped]);
234
236
  for (const quota of summary.dreamerQuotas ?? []) values.push(["Dreamer quota", quota]);
237
+ for (const quota of summary.hiddenModelSkips ?? []) values.push(["Hidden model quota", quota]);
235
238
  if (summary.historianRefusal) {
236
239
  values.push([
237
240
  "Historian refusal",
@@ -312,6 +312,7 @@ export function checkStatusViewSource(candidate: unknown):
312
312
  lastDreamerRunAt: optional.read("lastDreamerRunAt", isNullableNumber),
313
313
  dreamerUnsupportedTasks: optional.readArray("dreamerUnsupportedTasks", isString),
314
314
  dreamerSkipped: optional.readArray("dreamerSkipped", isString),
315
+ hiddenModelSkips: optional.readArray("hiddenModelSkips", isString),
315
316
  dreamerFailures: optional.readArray(
316
317
  "dreamerFailures",
317
318
  (value): value is { task: string; error: string } =>
@@ -403,6 +403,21 @@ describe("status view model", () => {
403
403
  * (issue 496).
404
404
  */
405
405
  describe("blocked background maintenance", () => {
406
+ test("shows live hidden-model quota skips beside background failures", () => {
407
+ const value =
408
+ "google/primary until 2026-10-10T04:46:40.000Z: provider said to retry later";
409
+ for (const compactionEnabled of [true, false]) {
410
+ const rows = view({
411
+ hiddenModelSkips: [value],
412
+ compactionEnabled,
413
+ }).sections.flatMap((section) => section.rows);
414
+ expect(rows.find((row) => row.label === "Hidden model quota")).toMatchObject({
415
+ value,
416
+ tone: "warning",
417
+ });
418
+ }
419
+ });
420
+
406
421
  test("shows a scheduled task's primary quota deadline in the status dialog", () => {
407
422
  const error =
408
423
  "primary quota exhausted until 2026-10-08T03:40:04.275Z; account=private@example.com";
@@ -159,6 +159,7 @@ export interface StatusViewSource {
159
159
  */
160
160
  readonly dreamerTickFailure?: DreamerTickFailure | null;
161
161
  readonly dreamerFailures?: readonly { task: string; error: string }[];
162
+ readonly hiddenModelSkips?: readonly string[];
162
163
  readonly memoryCount: number;
163
164
  readonly sessionNoteCount?: number;
164
165
  readonly readySmartNoteCount?: number;
@@ -529,7 +530,7 @@ function dreamerUnsupportedRows(source: StatusViewSource): StatusRow[] {
529
530
 
530
531
  /** One row naming the stage that stopped the last maintenance pass, if one did. */
531
532
  function dreamerTickFailureRows(source: StatusViewSource, now: number): StatusRow[] {
532
- const quotas = [
533
+ const quotas: StatusRow[] = [
533
534
  ...new Set(
534
535
  (source.dreamerFailures ?? []).flatMap((failure) => {
535
536
  const quota = primaryQuotaDiagnostic(failure.error);
@@ -537,6 +538,15 @@ function dreamerTickFailureRows(source: StatusViewSource, now: number): StatusRo
537
538
  }),
538
539
  ),
539
540
  ].map((value): StatusRow => ({ label: "Dreamer quota", value, tone: "warning" }));
541
+ quotas.push(
542
+ ...(source.hiddenModelSkips ?? []).map(
543
+ (value): StatusRow => ({
544
+ label: "Hidden model quota",
545
+ value,
546
+ tone: "warning",
547
+ }),
548
+ ),
549
+ );
540
550
  const failure = source.dreamerTickFailure;
541
551
  if (!failure) return quotas;
542
552
  return [
@@ -0,0 +1,84 @@
1
+ import { afterEach, expect, spyOn, test } from "bun:test";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import * as messageTime from "../features/magic-context/message-time-backfill";
5
+ import {
6
+ __getDatabaseStartupStateForTests,
7
+ closeDatabase,
8
+ getDatabasePath,
9
+ openDatabase,
10
+ } from "../features/magic-context/storage-db";
11
+ import * as warmup from "../hooks/magic-context/raw-ordinal-warmup";
12
+ import { setHarness } from "./harness";
13
+ import { openTestDatabase, openTestDb } from "./test-db";
14
+ import { createTestTempDirFromPath } from "./test-temp-dir";
15
+
16
+ const originalHome = process.env.XDG_DATA_HOME;
17
+ afterEach(async () => {
18
+ await closeDatabase();
19
+ if (originalHome === undefined) delete process.env.XDG_DATA_HOME;
20
+ else process.env.XDG_DATA_HOME = originalHome;
21
+ setHarness("opencode");
22
+ });
23
+
24
+ test("transform fixture opener opts into and joins both startup writers before returning the serving handle", async () => {
25
+ process.env.XDG_DATA_HOME = createTestTempDirFromPath(join(tmpdir(), "mc-startup-barrier-"));
26
+ setHarness("opencode");
27
+ const ftsStarted = Promise.withResolvers<void>();
28
+ const releaseFts = Promise.withResolvers<void>();
29
+ const timeStarted = Promise.withResolvers<void>();
30
+ const releaseTime = Promise.withResolvers<void>();
31
+ let blocker: ReturnType<typeof openTestDb> | undefined;
32
+ const fts = spyOn(warmup, "runSessionWarmupWorker").mockImplementation(async (input) => {
33
+ if (!input.ftsRowidBackfill) throw new Error("Unexpected startup job");
34
+ blocker = openTestDb(input.path);
35
+ blocker.exec("BEGIN IMMEDIATE");
36
+ ftsStarted.resolve();
37
+ await releaseFts.promise;
38
+ blocker.exec("ROLLBACK");
39
+ blocker.close();
40
+ blocker = undefined;
41
+ return { ftsRowidBackfill: true };
42
+ });
43
+ const time = spyOn(messageTime, "startMessageTimeBackfill").mockImplementation(async () => {
44
+ timeStarted.resolve();
45
+ await releaseTime.promise;
46
+ });
47
+ let returned = false;
48
+ const opening = openTestDatabase().then((db) => {
49
+ returned = true;
50
+ return db;
51
+ });
52
+ try {
53
+ await ftsStarted.promise;
54
+ expect(returned).toBe(false);
55
+ const dbPath = blocker!.prepare("PRAGMA database_list").all() as Array<{ file: string }>;
56
+ const serving = openTestDb(dbPath[0]!.file);
57
+ try {
58
+ serving.exec("PRAGMA busy_timeout=0");
59
+ expect(() => serving.exec("BEGIN IMMEDIATE")).toThrow("database is locked");
60
+ } finally {
61
+ serving.close();
62
+ }
63
+ releaseFts.resolve();
64
+ await timeStarted.promise;
65
+ expect(returned).toBe(false);
66
+ releaseTime.resolve();
67
+ const db = await opening;
68
+ expect(__getDatabaseStartupStateForTests(db).running).toBeInstanceOf(Promise);
69
+ expect(getDatabasePath(db)).toBe(dbPath[0]!.file);
70
+ db.exec("BEGIN IMMEDIATE; ROLLBACK");
71
+ await closeDatabase();
72
+ const next = openDatabase()!;
73
+ expect(__getDatabaseStartupStateForTests(next)).toEqual({
74
+ timerScheduled: false,
75
+ running: null,
76
+ });
77
+ } finally {
78
+ releaseFts.resolve();
79
+ releaseTime.resolve();
80
+ await opening;
81
+ fts.mockRestore();
82
+ time.mockRestore();
83
+ }
84
+ });
@@ -0,0 +1,36 @@
1
+ import {
2
+ __setScheduleStartupMaintenanceOnOpenForTests,
3
+ __waitForDatabaseStartupForTests,
4
+ openDatabase,
5
+ } from "../features/magic-context/storage-db";
6
+ import { Database } from "./sqlite";
7
+
8
+ /** A raw fixture connection, without changing the caller's SQLite lock policy. */
9
+ export function openTestDb(
10
+ path: string,
11
+ options?: ConstructorParameters<typeof Database>[1],
12
+ ): Database {
13
+ return new Database(path, options);
14
+ }
15
+
16
+ /**
17
+ * Real transform fixtures need an idle serving database. Startup backfills open
18
+ * separate connections to the same SQLite file. Their write locks can make a
19
+ * healthy pass replay the previous saved request instead of running the work
20
+ * the test is asserting. This helper opts into real startup even when the unit
21
+ * preload disables it, then joins the writers before returning.
22
+ */
23
+ export async function openTestDatabase(
24
+ ...args: Parameters<typeof openDatabase>
25
+ ): Promise<Database> {
26
+ const previous = __setScheduleStartupMaintenanceOnOpenForTests(true);
27
+ let db: Database | null;
28
+ try {
29
+ db = openDatabase(...args);
30
+ } finally {
31
+ __setScheduleStartupMaintenanceOnOpenForTests(previous);
32
+ }
33
+ if (!db) throw new Error("Test database unavailable");
34
+ await __waitForDatabaseStartupForTests(db);
35
+ return db;
36
+ }