@cortexkit/opencode-magic-context 0.49.83 → 0.49.85

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 (137) hide show
  1. package/dist/{announcement-p41dde4h.js → announcement-fnyxaahs.js} +3 -1
  2. package/dist/auto-search-worker.js +3 -3
  3. package/dist/chunk-embedding-write-worker.js +5 -4
  4. package/dist/{context-xmyke353.js → context-bjfwzbts.js} +314 -107
  5. package/dist/{derive-budgets-2z6xxm7e.js → derive-budgets-90869322.js} +3 -1
  6. package/dist/{embedding-backfill-k994xdas.js → embedding-backfill-v6sw58m8.js} +7 -5
  7. package/dist/embedding-worker.js +15 -27
  8. package/dist/features/magic-context/memory/embedding-worker-boundary.test-support.d.ts +24 -0
  9. package/dist/features/magic-context/memory/embedding-worker-boundary.test-support.d.ts.map +1 -0
  10. package/dist/features/magic-context/memory/embedding-worker-client.d.ts +35 -1
  11. package/dist/features/magic-context/memory/embedding-worker-client.d.ts.map +1 -1
  12. package/dist/features/magic-context/memory/embedding-worker-loop.d.ts +57 -0
  13. package/dist/features/magic-context/memory/embedding-worker-loop.d.ts.map +1 -0
  14. package/dist/features/magic-context/mural/render-trigger.d.ts +3 -3
  15. package/dist/features/magic-context/mural/render-trigger.d.ts.map +1 -1
  16. package/dist/features/magic-context/project-embedding-registry.d.ts +6 -1
  17. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  18. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  19. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  20. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
  21. package/dist/{index-zzvd4a9z.js → index-05bm2ndp.js} +1 -1
  22. package/dist/{index-93rezfvc.js → index-08jfpny9.js} +37 -6
  23. package/dist/{index-dg5jvh9r.js → index-0rge5rkh.js} +8 -8
  24. package/dist/{index-2xhzmwf6.js → index-1pf5qrx4.js} +5 -5
  25. package/dist/{index-e21n48yd.js → index-1y4y98r1.js} +23 -0
  26. package/dist/{index-98qy103c.js → index-2kf73btc.js} +1 -1
  27. package/dist/{index-vpw46557.js → index-3dtzyred.js} +1 -1
  28. package/dist/{index-bd34njzg.js → index-4ntnt8ee.js} +1 -1
  29. package/dist/{index-w2wpx7t5.js → index-4w5rx7de.js} +1 -1
  30. package/dist/{index-twmeey4h.js → index-70cv85b0.js} +2 -2
  31. package/dist/{index-rnyaa7cj.js → index-798s7c8s.js} +2 -2
  32. package/dist/{index-2q0t43fy.js → index-7j2zv9nm.js} +1 -1
  33. package/dist/{index-fpqdbb67.js → index-7svecf3m.js} +3 -3
  34. package/dist/{index-eptthgkw.js → index-9fsxmjs6.js} +5 -5
  35. package/dist/{v2/server-fvnzcnww.js → index-c5tmzym6.js} +192 -11
  36. package/dist/{index-w8dcjt7f.js → index-k0tb2z28.js} +1 -1
  37. package/dist/{index-zb4h9nrk.js → index-k50xhjw1.js} +202 -14
  38. package/dist/{index-hz1xdb15.js → index-kqnef2tg.js} +4 -4
  39. package/dist/{index-2ygw6q5s.js → index-nny4gm06.js} +2 -2
  40. package/dist/{index-fgy6hnr3.js → index-pw279hmt.js} +2 -2
  41. package/dist/{index-eyk7msgw.js → index-qvn3q9f1.js} +41 -41
  42. package/dist/{index-shpyv8gq.js → index-s8ks5nz4.js} +16 -9
  43. package/dist/{index-wxxcfpxh.js → index-sbr58jaf.js} +8 -8
  44. package/dist/{index-b2787fk6.js → index-tzbcb8yt.js} +36 -20
  45. package/dist/{index-x8qgqnym.js → index-w6v4dw5f.js} +25 -25
  46. package/dist/{index-zvane1rq.js → index-xccywqdj.js} +16 -16
  47. package/dist/{index-y208s7zx.js → index-xrnhxkz7.js} +6 -1
  48. package/dist/{index-tky3j43e.js → index-zmqx48vt.js} +58 -14
  49. package/dist/index.js +37 -37
  50. package/dist/{message-index-bounded-cfkeyf72.js → message-index-bounded-6fr624zf.js} +3 -3
  51. package/dist/migration-worker.js +4 -3
  52. package/dist/{project-embedding-registry-y3z36mjy.js → project-embedding-registry-q80scexh.js} +6 -4
  53. package/dist/raw-ordinal-warmup-worker.js +4 -4
  54. package/dist/{read-session-chunk-s3qac56g.js → read-session-chunk-6wedfths.js} +2 -2
  55. package/dist/{recomp-orchestrator-fjdp3t1d.js → recomp-orchestrator-xzs0a455.js} +19 -18
  56. package/dist/{render-c9fjwrad.js → render-yqp7q79f.js} +12 -11
  57. package/dist/{search-archive-s2jas2jb.js → search-archive-r4h96j2z.js} +4 -4
  58. package/dist/{search-1jejx5cx.js → search-ztgy3ya6.js} +15 -13
  59. package/dist/shared/models-dev-cache.d.ts +6 -1
  60. package/dist/shared/models-dev-cache.d.ts.map +1 -1
  61. package/dist/shared/storage-file-mutex.d.ts.map +1 -1
  62. package/dist/shared/storage-permissions.d.ts +5 -3
  63. package/dist/shared/storage-permissions.d.ts.map +1 -1
  64. package/dist/shared/test-git-env.d.ts +3 -0
  65. package/dist/shared/test-git-env.d.ts.map +1 -0
  66. package/dist/{storage-tags-6e83pvff.js → storage-tags-y2mrb8e6.js} +1 -1
  67. package/dist/{store-ggrq9e14.js → store-n4yz3n66.js} +2 -2
  68. package/dist/{store-reader-tr64nxyy.js → store-reader-nf8z86n9.js} +1 -1
  69. package/dist/{transform-postprocess-phase-p2egg02g.js → transform-postprocess-phase-39a5hm2a.js} +20 -19
  70. package/dist/v2/auto-search-worker.js +3 -3
  71. package/dist/v2/chunk-embedding-write-worker.js +6 -5
  72. package/dist/v2/{context-zn18k0yk.js → context-k2rrqzf4.js} +446 -248
  73. package/dist/v2/{derive-budgets-2eam671q.js → derive-budgets-ecjy1aqh.js} +4 -2
  74. package/dist/v2/{embedding-backfill-hjvjxp7d.js → embedding-backfill-k8kqnwfq.js} +7 -5
  75. package/dist/v2/embedding-worker.js +15 -27
  76. package/dist/v2/fold/restore.d.ts.map +1 -1
  77. package/dist/v2/hooks/context.d.ts.map +1 -1
  78. package/dist/v2/hooks/revert-message-state.d.ts +12 -0
  79. package/dist/v2/hooks/revert-message-state.d.ts.map +1 -0
  80. package/dist/v2/hooks/storage-notice.d.ts +12 -6
  81. package/dist/v2/hooks/storage-notice.d.ts.map +1 -1
  82. package/dist/v2/{message-index-bounded-0xy4dn04.js → message-index-bounded-jqy7283g.js} +4 -4
  83. package/dist/v2/migration-worker.js +5 -4
  84. package/dist/v2/{project-embedding-registry-mzsvyads.js → project-embedding-registry-2jp1antr.js} +6 -4
  85. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  86. package/dist/v2/{read-session-chunk-6mt2t6dy.js → read-session-chunk-n3nhfvd7.js} +3 -3
  87. package/dist/v2/{recomp-orchestrator-jn39mxh0.js → recomp-orchestrator-jnbxbsc8.js} +21 -20
  88. package/dist/v2/{render-q2aj9bgy.js → render-fezgh7pa.js} +13 -12
  89. package/dist/v2/{search-archive-fj59gjv1.js → search-archive-zz1kza50.js} +5 -5
  90. package/dist/v2/{search-9xn6ds9x.js → search-h5w7510x.js} +15 -13
  91. package/dist/v2/{server-2gcfmd47.js → server-2k8tkbhz.js} +2 -2
  92. package/dist/v2/{server-4z964n1c.js → server-3p6b0qya.js} +1 -1
  93. package/dist/v2/{server-c8mqs0v5.js → server-4wwwm2ya.js} +32 -32
  94. package/dist/v2/{server-1cn3kryt.js → server-97w51d8n.js} +5 -5
  95. package/dist/v2/{server-gx1s06dx.js → server-98hsp35q.js} +2 -2
  96. package/dist/v2/{server-xepx8t43.js → server-a2f1bhyj.js} +1 -1
  97. package/dist/v2/{server-r00xyx66.js → server-ap81bk3c.js} +28 -28
  98. package/dist/v2/{server-d706s5xn.js → server-b93f0bqh.js} +205 -17
  99. package/dist/v2/{server-2w1rdttn.js → server-brgandk4.js} +2 -2
  100. package/dist/v2/{server-rp52f40v.js → server-cwtehwbb.js} +1 -1
  101. package/dist/v2/{server-bj779zmp.js → server-e2k9mt86.js} +1 -1
  102. package/dist/v2/{server-68q80y27.js → server-hn8b7sfe.js} +16 -9
  103. package/dist/v2/{server-pejjj0nv.js → server-mbkwcwgw.js} +1 -1
  104. package/dist/v2/{server-g1a0nhtk.js → server-n5zr7190.js} +18 -18
  105. package/dist/v2/{server-2ktxmtbd.js → server-ps6rz88g.js} +2 -2
  106. package/dist/v2/{server-5yfq912a.js → server-qyazxy92.js} +23 -0
  107. package/dist/{index-fvnzcnww.js → v2/server-r2es6zt7.js} +192 -11
  108. package/dist/v2/{server-bt546axy.js → server-rz4snd3x.js} +3 -3
  109. package/dist/v2/{server-xdh4r20h.js → server-s15knz0w.js} +642 -627
  110. package/dist/v2/{server-vt6nj2hn.js → server-s76ty4ws.js} +41 -25
  111. package/dist/v2/{server-0dmzr7f9.js → server-sxfbjdye.js} +2 -2
  112. package/dist/v2/{server-569he5mh.js → server-w7mpvkpj.js} +1 -1
  113. package/dist/v2/{server-53n8hv5q.js → server-x77hd658.js} +8 -8
  114. package/dist/v2/{server-nqdzv8b7.js → server-xa8fefhw.js} +58 -14
  115. package/dist/v2/{server-1efjj215.js → server-ytqps2xa.js} +37 -6
  116. package/dist/v2/server.js +6 -4
  117. package/dist/v2/{storage-tags-z8j8wq34.js → storage-tags-xq81zgt2.js} +2 -2
  118. package/dist/v2/{store-reader-83tka051.js → store-reader-2vhx33n6.js} +1 -1
  119. package/dist/v2/store-reader.d.ts +11 -0
  120. package/dist/v2/store-reader.d.ts.map +1 -1
  121. package/dist/v2/{store-qdgzd38f.js → store-y56y034s.js} +2 -2
  122. package/dist/v2/{v2-archive-reader-9z8z97db.js → v2-archive-reader-e2w39c3p.js} +1 -1
  123. package/dist/v2/{wrapup-orchestrator-vd5zfp3v.js → wrapup-orchestrator-mmje3etf.js} +20 -19
  124. package/dist/{v2-archive-reader-r0xpxsb1.js → v2-archive-reader-8dsngf2j.js} +1 -1
  125. package/dist/{wrapup-orchestrator-k29zqfp9.js → wrapup-orchestrator-sm6pwf3p.js} +20 -19
  126. package/package.json +1 -1
  127. package/src/shared/models-dev-cache.ts +90 -21
  128. package/src/shared/reusable-worker.test.ts +31 -29
  129. package/src/shared/sqlite.test.ts +19 -6
  130. package/src/shared/storage-file-mutex-review.test.ts +125 -2
  131. package/src/shared/storage-file-mutex.ts +17 -8
  132. package/src/shared/storage-permissions-creators.test.ts +194 -0
  133. package/src/shared/storage-permissions-startup.test.ts +476 -0
  134. package/src/shared/storage-permissions.ts +227 -12
  135. package/src/shared/test-db.test.ts +5 -3
  136. package/src/shared/test-git-env.test.ts +38 -0
  137. package/src/shared/test-git-env.ts +10 -0
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./server-1cn3kryt.js";
4
+ } from "./server-97w51d8n.js";
5
5
  import"./server-v0p37hm2.js";
6
6
  import"./server-gzy5w8ya.js";
7
7
  import"./server-1d042x6w.js";
@@ -12,7 +12,7 @@ import {
12
12
  getCompartments,
13
13
  getLastCompartmentEndMessage,
14
14
  requestPendingMaterialization
15
- } from "./server-c8mqs0v5.js";
15
+ } from "./server-4wwwm2ya.js";
16
16
  import"./server-2amn2s73.js";
17
17
  import"./server-y8xjr8rx.js";
18
18
  import"./server-x6fn9x8q.js";
@@ -25,7 +25,7 @@ import"./server-1d042x6w.js";
25
25
  import"./server-6ash6z8z.js";
26
26
  import"./server-ds8vpfkr.js";
27
27
  import"./server-8pdfmc27.js";
28
- import"./server-r00xyx66.js";
28
+ import"./server-ap81bk3c.js";
29
29
  import {
30
30
  getWrapupInProgressState,
31
31
  acquireWrapupInProgress,
@@ -33,23 +33,24 @@ import {
33
33
  releaseWrapupInProgress,
34
34
  getHistorianFailureState,
35
35
  clearEmergencyRecovery
36
- } from "./server-xdh4r20h.js";
37
- import"./server-xepx8t43.js";
38
- import"./server-g1a0nhtk.js";
36
+ } from "./server-s15knz0w.js";
37
+ import"./server-a2f1bhyj.js";
38
+ import"./server-n5zr7190.js";
39
39
  import"./server-1zx87sdm.js";
40
40
  import"./server-rz6g5xne.js";
41
41
  import"./server-2ra6pwf3.js";
42
42
  import"./server-3ap5dmhc.js";
43
43
  import {
44
44
  prepareRawSessionOrdinals2
45
- } from "./server-2gcfmd47.js";
45
+ } from "./server-2k8tkbhz.js";
46
46
  import"./server-fr0wbhdn.js";
47
- import"./server-2ktxmtbd.js";
48
- import"./server-bt546axy.js";
49
- import"./server-5yfq912a.js";
47
+ import"./server-ps6rz88g.js";
48
+ import"./server-r2es6zt7.js";
49
+ import"./server-rz4snd3x.js";
50
+ import"./server-qyazxy92.js";
50
51
  import"./server-fb3zxn06.js";
51
52
  import"./server-39bcszk4.js";
52
- import"./server-569he5mh.js";
53
+ import"./server-w7mpvkpj.js";
53
54
  import {
54
55
  pushNotification2
55
56
  } from "./server-fzgyvsb1.js";
@@ -64,18 +65,18 @@ import {
64
65
  registerActiveCompartmentRun,
65
66
  setRecompStarting2,
66
67
  setRecompTerminal2
67
- } from "./server-vt6nj2hn.js";
68
+ } from "./server-s76ty4ws.js";
68
69
  import"./server-qt1qqasc.js";
69
- import"./server-68q80y27.js";
70
- import"./server-4z964n1c.js";
70
+ import"./server-hn8b7sfe.js";
71
+ import"./server-3p6b0qya.js";
71
72
  import"./server-4dhv7mqz.js";
72
- import"./server-d706s5xn.js";
73
- import"./server-gx1s06dx.js";
74
- import"./server-pejjj0nv.js";
73
+ import"./server-b93f0bqh.js";
74
+ import"./server-98hsp35q.js";
75
+ import"./server-mbkwcwgw.js";
75
76
  import"./server-jjvbk92s.js";
76
- import"./server-bj779zmp.js";
77
- import"./server-nqdzv8b7.js";
78
- import"./server-rp52f40v.js";
77
+ import"./server-e2k9mt86.js";
78
+ import"./server-xa8fefhw.js";
79
+ import"./server-cwtehwbb.js";
79
80
  import"./server-npdey91q.js";
80
81
  import {
81
82
  sendStatusNotification2
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./index-2xhzmwf6.js";
4
+ } from "./index-1pf5qrx4.js";
5
5
  import"./index-v0p37hm2.js";
6
6
  import"./index-gzy5w8ya.js";
7
7
  import"./index-1d042x6w.js";
@@ -1,48 +1,49 @@
1
1
  import {
2
2
  runManagedWrapup2
3
- } from "./index-eptthgkw.js";
4
- import"./index-hz1xdb15.js";
5
- import"./index-b2787fk6.js";
3
+ } from "./index-9fsxmjs6.js";
4
+ import"./index-kqnef2tg.js";
5
+ import"./index-tzbcb8yt.js";
6
6
  import"./index-832w615x.js";
7
7
  import"./index-sd3egckz.js";
8
- import"./index-fgy6hnr3.js";
9
- import"./index-w8dcjt7f.js";
8
+ import"./index-pw279hmt.js";
9
+ import"./index-k0tb2z28.js";
10
10
  import"./index-jjvbk92s.js";
11
- import"./index-shpyv8gq.js";
11
+ import"./index-s8ks5nz4.js";
12
12
  import"./index-4dhv7mqz.js";
13
- import"./index-x8qgqnym.js";
14
- import"./index-bd34njzg.js";
15
- import"./index-zzvd4a9z.js";
13
+ import"./index-w6v4dw5f.js";
14
+ import"./index-4ntnt8ee.js";
15
+ import"./index-05bm2ndp.js";
16
16
  import"./index-2amn2s73.js";
17
- import"./index-e21n48yd.js";
18
- import"./index-tky3j43e.js";
17
+ import"./index-1y4y98r1.js";
18
+ import"./index-zmqx48vt.js";
19
19
  import"./index-g6hfh4h4.js";
20
20
  import"./index-qt1qqasc.js";
21
- import"./index-2q0t43fy.js";
22
- import"./index-y208s7zx.js";
21
+ import"./index-7j2zv9nm.js";
22
+ import"./index-xrnhxkz7.js";
23
23
  import"./index-1zx87sdm.js";
24
24
  import"./index-x40zr813.js";
25
25
  import"./index-fzgyvsb1.js";
26
26
  import"./index-e6ncz7a6.js";
27
- import"./index-zb4h9nrk.js";
27
+ import"./index-k50xhjw1.js";
28
28
  import"./index-6nqz8hsz.js";
29
- import"./index-vpw46557.js";
29
+ import"./index-3dtzyred.js";
30
30
  import"./index-snbpdpa3.js";
31
31
  import"./index-pxnzyvjc.js";
32
- import"./index-zvane1rq.js";
32
+ import"./index-xccywqdj.js";
33
33
  import"./index-fb3zxn06.js";
34
- import"./index-w2wpx7t5.js";
34
+ import"./index-4w5rx7de.js";
35
35
  import"./index-fr0wbhdn.js";
36
- import"./index-fpqdbb67.js";
36
+ import"./index-7svecf3m.js";
37
37
  import"./index-s32f8y67.js";
38
38
  import"./index-wh9fxds5.js";
39
- import"./index-gqf8r04r.js";
40
39
  import"./index-jrj95cce.js";
41
40
  import"./index-q7q6qp1f.js";
42
41
  import"./index-96ztjvkn.js";
43
42
  import"./index-v0p37hm2.js";
44
43
  import"./index-58e3y90n.js";
45
44
  import"./index-m0pwswv9.js";
45
+ import"./index-c5tmzym6.js";
46
+ import"./index-gqf8r04r.js";
46
47
  import"./index-5vsk2cpp.js";
47
48
  import"./index-gzy5w8ya.js";
48
49
  import"./index-ywrz4wy2.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-magic-context",
3
- "version": "0.49.83",
3
+ "version": "0.49.85",
4
4
  "type": "module",
5
5
  "description": "OpenCode plugin for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",
@@ -300,6 +300,7 @@ function setCachedModelMetadata(
300
300
  attachment?: unknown;
301
301
  }
302
302
  | undefined,
303
+ allowPartial: boolean,
303
304
  ): void {
304
305
  const contextLimit = model?.limit?.context;
305
306
  const inputLimit = model?.limit?.input;
@@ -313,18 +314,21 @@ function setCachedModelMetadata(
313
314
  // Validate the raw provider metadata before reservation. A legitimate 20K
314
315
  // context may resolve below MIN_SANE_LIMIT after carving output, but it must
315
316
  // still remain cached; the 50%/1024 usable floor protects the result.
316
- if (rawLimit === undefined) return;
317
+ if (rawLimit === undefined && !allowPartial) return;
317
318
 
318
319
  const values = [model?.capabilities, model?.modalities, model?.input, model?.attachment];
319
- const vision = values.some(
320
- (value) =>
321
- JSON.stringify(value ?? "")
322
- .toLowerCase()
323
- .includes("image") ||
324
- JSON.stringify(value ?? "")
325
- .toLowerCase()
326
- .includes("vision"),
327
- );
320
+ const capabilityInput =
321
+ getHarness() === "opencode2"
322
+ ? (model?.capabilities as { input?: unknown } | undefined)?.input
323
+ : undefined;
324
+ const vision = Array.isArray(capabilityInput)
325
+ ? capabilityInput.includes("image")
326
+ : allowPartial && values.every((value) => value == null)
327
+ ? undefined
328
+ : values.some((value) => {
329
+ const capabilities = JSON.stringify(value ?? "").toLowerCase();
330
+ return capabilities.includes("image") || capabilities.includes("vision");
331
+ });
328
332
  const value: CachedModelMetadata = {
329
333
  // Keep a sane raw fallback for old persisted-cache readers. Runtime
330
334
  // resolution below uses context/input/output so user overrides stay live.
@@ -347,6 +351,50 @@ function setCachedModelMetadata(
347
351
  }
348
352
  }
349
353
 
354
+ function mergeUsageModelMetadata(
355
+ updates: Map<string, CachedModelMetadata>,
356
+ draftOnlyModelKey?: string,
357
+ ): void {
358
+ loadPersistedApiCacheOnce();
359
+ const merged = new Map(apiCache);
360
+ const refreshed = new Set<string>();
361
+ for (const [key, incoming] of updates) {
362
+ const previous = merged.get(key);
363
+ const draftOnly = key === draftOnlyModelKey;
364
+ // A listed row normally replaces all its limits. If neither context nor
365
+ // input passes the sanity check, keep the old entry. Losing it would
366
+ // expose the generic 200K default instead of the last sane window.
367
+ if (!draftOnly && incoming.limit === undefined) continue;
368
+ const contextLimit =
369
+ incoming.contextLimit ?? (draftOnly ? previous?.contextLimit : undefined);
370
+ const inputLimit = incoming.inputLimit ?? (draftOnly ? previous?.inputLimit : undefined);
371
+ const limit = contextLimit ?? inputLimit ?? (draftOnly ? previous?.limit : undefined);
372
+ if (limit === undefined) continue;
373
+ merged.set(key, {
374
+ limit,
375
+ contextLimit,
376
+ inputLimit,
377
+ outputLimit: incoming.outputLimit ?? (draftOnly ? previous?.outputLimit : undefined),
378
+ vision: incoming.vision ?? previous?.vision,
379
+ });
380
+ if (incoming.limit !== undefined) refreshed.add(key);
381
+ }
382
+ clearRefreshedV2DraftModelLimits(refreshed, merged);
383
+ apiCache = merged;
384
+ }
385
+
386
+ function clearRefreshedV2DraftModelLimits(
387
+ refreshed: ReadonlySet<string>,
388
+ merged: ReadonlyMap<string, CachedModelMetadata>,
389
+ ): void {
390
+ for (const key of v2DraftModelLimits.keys()) {
391
+ const tag = key.lastIndexOf(":");
392
+ const usesRefreshedBase =
393
+ !merged.has(key) && tag > key.indexOf("/") + 1 && refreshed.has(key.slice(0, tag));
394
+ if (refreshed.has(key) || usesRefreshedBase) v2DraftModelLimits.delete(key);
395
+ }
396
+ }
397
+
350
398
  /**
351
399
  * Asynchronously refresh the API-layer cache from OpenCode's SDK.
352
400
  *
@@ -361,16 +409,28 @@ function setCachedModelMetadata(
361
409
  * a few times so the cache warms instead of leaving the session on the 128k
362
410
  * default until the next restart. A successful load (any providers) stops early.
363
411
  *
364
- * Safe to call concurrently; only overwrites the cache on success.
412
+ * A full catalog replaces the previous snapshot. When OpenCode 2 reads the
413
+ * list while recording usage, merge mode keeps unlisted models and replaces
414
+ * the limits for listed models. Only a row synthesized from the request
415
+ * because its model was not listed retains omitted limits field by field.
365
416
  */
366
417
  export async function refreshModelLimitsFromApi(
367
418
  client: OpencodeClientLike,
368
- options?: { retries?: number; retryDelayMs?: number },
419
+ options?: {
420
+ retries?: number;
421
+ retryDelayMs?: number;
422
+ mode?: "merge" | "replace";
423
+ draftOnlyModelKey?: string;
424
+ },
369
425
  ): Promise<void> {
370
426
  const attempts = Math.max(1, (options?.retries ?? 0) + 1);
371
427
  const delayMs = options?.retryDelayMs ?? 1000;
372
428
  for (let attempt = 1; attempt <= attempts; attempt++) {
373
- const ok = await refreshModelLimitsOnce(client);
429
+ const ok = await refreshModelLimitsOnce(
430
+ client,
431
+ options?.mode === "merge",
432
+ options?.draftOnlyModelKey,
433
+ );
374
434
  if (ok) return;
375
435
  if (attempt < attempts) {
376
436
  await new Promise((resolve) => setTimeout(resolve, delayMs));
@@ -413,8 +473,12 @@ export function resetAuthRewarmLatchForTest(): void {
413
473
  authRewarmDone = false;
414
474
  }
415
475
 
416
- /** Single SDK fetch + cache rebuild. Returns true when providers were loaded. */
417
- async function refreshModelLimitsOnce(client: OpencodeClientLike): Promise<boolean> {
476
+ /** Single SDK fetch + cache update. Returns true when providers were loaded. */
477
+ async function refreshModelLimitsOnce(
478
+ client: OpencodeClientLike,
479
+ merge = false,
480
+ draftOnlyModelKey?: string,
481
+ ): Promise<boolean> {
418
482
  try {
419
483
  const result = await client.config.providers();
420
484
  const data = (result as { data?: { providers?: Array<unknown> } }).data;
@@ -441,27 +505,32 @@ async function refreshModelLimitsOnce(client: OpencodeClientLike): Promise<boole
441
505
  };
442
506
  if (!p?.id || !p.models || typeof p.models !== "object") continue;
443
507
  for (const [modelId, model] of Object.entries(p.models)) {
444
- setCachedModelMetadata(map, `${p.id}/${modelId}`, model);
508
+ setCachedModelMetadata(map, `${p.id}/${modelId}`, model, merge);
445
509
  }
446
510
  }
447
511
 
448
512
  const previousSize = apiCache?.size ?? null;
449
- apiCache = map;
450
- v2DraftModelLimits.clear();
513
+ if (merge) {
514
+ mergeUsageModelMetadata(map, draftOnlyModelKey);
515
+ } else {
516
+ apiCache = map;
517
+ v2DraftModelLimits.clear();
518
+ }
451
519
  apiLoadedAt = Date.now();
452
520
  // Persist the freshly-resolved (sane-filtered) limits so the next process
453
521
  // cold-starts with the real values instead of the 128k default.
454
522
  persistApiCache();
455
523
 
524
+ const size = apiCache?.size ?? 0;
456
525
  if (previousSize === null) {
457
526
  sessionLog(
458
527
  "global",
459
- `models-dev-cache: API layer loaded ${map.size} model metadata entries`,
528
+ `models-dev-cache: API layer loaded ${size} model metadata entries`,
460
529
  );
461
- } else if (previousSize !== map.size) {
530
+ } else if (previousSize !== size) {
462
531
  sessionLog(
463
532
  "global",
464
- `models-dev-cache: API layer loaded ${map.size} model metadata entries (was ${previousSize})`,
533
+ `models-dev-cache: API layer loaded ${size} model metadata entries (was ${previousSize})`,
465
534
  );
466
535
  }
467
536
  return true;
@@ -156,35 +156,33 @@ describe("reusable job workers", () => {
156
156
  test("a file ending with queued jobs cannot interrupt the next parallel file", () => {
157
157
  withTestTempDir("reusable-worker-files-", (dir) => {
158
158
  const outcomes = join(dir, "outcomes.jsonl");
159
+ const owner = join(dir, "owner-started");
159
160
  writeFileSync(outcomes, "");
160
- writeFileSync(
161
- join(dir, "01-owner.test.ts"),
162
- `import { test } from "bun:test";
163
- import { appendFileSync } from "node:fs";
161
+ // The single Bun worker visits both files, but it need not visit them
162
+ // in filename order. The first file to run takes the owner role.
163
+ const fixture = `import { expect, test } from "bun:test";
164
+ import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
164
165
  import { reuseWorker } from ${JSON.stringify(new URL("./reusable-worker.ts", import.meta.url).href)};
165
- test("owner finishes with queued work", async () => {
166
- const entry = new URL(${JSON.stringify(entry.href)});
167
- const active = reuseWorker(entry, { workerData: { path: "file-exit", hang: true } });
168
- active.on("error", () => {});
169
- for (let id = 0; id < 3; id++) {
170
- const queued = reuseWorker(entry, { workerData: { path: "file-exit", value: "queued" } });
171
- let replied = false;
172
- let failed = false;
173
- queued.on("message", () => { replied = true; });
174
- queued.on("error", () => { failed = true; });
175
- queued.on("exit", code => appendFileSync(${JSON.stringify(outcomes)}, JSON.stringify({
176
- id, outcome: code === 0 && replied && !failed ? "completed" : "failed",
177
- }) + "\\n"));
178
- }
179
- await Promise.resolve();
180
- });`,
181
- );
182
- writeFileSync(
183
- join(dir, "02-next.test.ts"),
184
- `import { describe, expect, test } from "bun:test";
185
- import { readFileSync } from "node:fs";
186
- await new Promise(resolve => setTimeout(resolve, 50));
187
- describe("next file", () => {
166
+ const owner = ${JSON.stringify(owner)};
167
+ if (!existsSync(owner)) {
168
+ test("owner finishes with queued work", async () => {
169
+ writeFileSync(owner, "");
170
+ const entry = new URL(${JSON.stringify(entry.href)});
171
+ const active = reuseWorker(entry, { workerData: { path: "file-exit", hang: true } });
172
+ active.on("error", () => {});
173
+ for (let id = 0; id < 3; id++) {
174
+ const queued = reuseWorker(entry, { workerData: { path: "file-exit", value: "queued" } });
175
+ let replied = false;
176
+ let failed = false;
177
+ queued.on("message", () => { replied = true; });
178
+ queued.on("error", () => { failed = true; });
179
+ queued.on("exit", code => appendFileSync(${JSON.stringify(outcomes)}, JSON.stringify({
180
+ id, outcome: code === 0 && replied && !failed ? "completed" : "failed",
181
+ }) + "\\n"));
182
+ }
183
+ await Promise.resolve();
184
+ });
185
+ } else {
188
186
  test("still registers after every queued client settles once", () => {
189
187
  const outcomes = readFileSync(${JSON.stringify(outcomes)}, "utf8").trim().split("\\n").filter(Boolean).map(line => JSON.parse(line));
190
188
  expect(outcomes).toHaveLength(3);
@@ -194,8 +192,8 @@ describe("next file", () => {
194
192
  expect(["completed", "failed"]).toContain(client[0].outcome);
195
193
  }
196
194
  });
197
- });`,
198
- );
195
+ }`;
196
+ for (const name of ["a.test.ts", "b.test.ts"]) writeFileSync(join(dir, name), fixture);
199
197
  // The real preload owns file teardown. Bun may discard a bare file's
200
198
  // callbacks without notifying its workers' clients during VM teardown.
201
199
  const child = spawnSync(
@@ -212,6 +210,10 @@ describe("next file", () => {
212
210
  const output = child.stdout + child.stderr;
213
211
  expect(output).toContain("2 pass");
214
212
  expect(output).toContain("0 fail");
213
+ expect(output).toContain("(pass) owner finishes with queued work");
214
+ expect(output).toContain(
215
+ "(pass) still registers after every queued client settles once",
216
+ );
215
217
  expect(output).not.toContain("Unhandled error");
216
218
  expect(child.status).toBe(0);
217
219
  const settled = readFileSync(outcomes, "utf8").trim().split("\n").filter(Boolean);
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from "bun:test";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
- import { existsSync, readFileSync } from "node:fs";
4
+ import { copyFileSync, existsSync, readFileSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import {
7
7
  Database,
@@ -113,11 +113,24 @@ describe("SQLite runtime selector", () => {
113
113
  );
114
114
  const path = join(directory, "context.db");
115
115
  try {
116
- const writer = new Database(path);
117
- writer.exec(
118
- "PRAGMA journal_mode=WAL; CREATE TABLE sample (value INTEGER); INSERT INTO sample VALUES (42); PRAGMA wal_checkpoint(TRUNCATE)",
119
- );
120
- writer.close();
116
+ const source = join(directory, "writer.db");
117
+ const writer = new Database(source);
118
+ try {
119
+ expect(writer.prepare("PRAGMA journal_mode=WAL").get()).toEqual({
120
+ journal_mode: "wal",
121
+ });
122
+ writer.exec("CREATE TABLE sample (value INTEGER); INSERT INTO sample VALUES (42)");
123
+ expect(writer.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()).toEqual({
124
+ busy: 0,
125
+ log: 0,
126
+ checkpointed: 0,
127
+ });
128
+ } finally {
129
+ writer.close();
130
+ }
131
+ // Apple's SQLite may keep the sidecars after close. Copy only the
132
+ // fully checkpointed main file, which is still in WAL mode.
133
+ copyFileSync(source, path);
121
134
  expect(existsSync(`${path}-wal`)).toBe(false);
122
135
  expect(existsSync(`${path}-shm`)).toBe(false);
123
136
 
@@ -1,5 +1,6 @@
1
1
  import { expect, spyOn, test } from "bun:test";
2
- import { readdirSync, readFileSync, rmdirSync, writeFileSync } from "node:fs";
2
+ import * as fs from "node:fs";
3
+ import { existsSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { __resetRpcIdentityTestHooks, __setRpcIdentityTestHooks } from "./rpc-utils";
5
6
  import { withStorageFileMutex } from "./storage-file-mutex";
@@ -9,6 +10,46 @@ import { createTestTempDir } from "./test-temp-dir";
9
10
 
10
11
  const mutex = join(import.meta.dir, "storage-file-mutex.ts");
11
12
 
13
+ test("mutex removes its empty directory after sequential operations and thrown work", () => {
14
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-sequence-");
15
+ const directory = join(root, "locks");
16
+ try {
17
+ for (let i = 0; i < 2; i++) {
18
+ expect(withStorageFileMutex(directory, () => i)).toBe(i);
19
+ expect(existsSync(directory)).toBe(false);
20
+ }
21
+ expect(() =>
22
+ withStorageFileMutex(directory, () => {
23
+ throw new Error("work failed");
24
+ }),
25
+ ).toThrow("work failed");
26
+ expect(existsSync(directory)).toBe(false);
27
+ } finally {
28
+ cleanup();
29
+ }
30
+ });
31
+
32
+ test("mutex directory cleanup preserves a ticket published during locked work", () => {
33
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-ticket-");
34
+ const directory = join(root, "locks");
35
+ const contender = join(directory, `${process.pid}-00000000-0000-0000-0000-000000000000.lock`);
36
+ try {
37
+ expect(
38
+ withStorageFileMutex(directory, () => {
39
+ writeFileSync(contender, "choosing", { mode: 0o600 });
40
+ return "done";
41
+ }),
42
+ ).toBe("done");
43
+ expect(readFileSync(contender, "utf8")).toBe("choosing");
44
+ expect(readdirSync(directory)).toHaveLength(1);
45
+ rmSync(contender);
46
+ withStorageFileMutex(directory, () => undefined);
47
+ expect(existsSync(directory)).toBe(false);
48
+ } finally {
49
+ cleanup();
50
+ }
51
+ });
52
+
12
53
  test("mutex retries ticket creation when empty-directory cleanup wins the mkdir race", () => {
13
54
  const { dir: root, cleanup } = createTestTempDir("mc-mutex-rmdir-");
14
55
  const directory = join(root, "locks");
@@ -28,6 +69,88 @@ test("mutex retries ticket creation when empty-directory cleanup wins the mkdir
28
69
  }
29
70
  });
30
71
 
72
+ test("mutex retries mkdir after EEXIST during lock directory cleanup", () => {
73
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-mkdir-race-");
74
+ const directory = join(root, "locks");
75
+ const mkdir = fs.mkdirSync;
76
+ let attempts = 0;
77
+ const mkdirSpy = spyOn(fs, "mkdirSync").mockImplementation((...args) => {
78
+ if (args[0] === directory && attempts++ === 0) {
79
+ throw Object.assign(new Error("lock mkdir raced with cleanup"), { code: "EEXIST" });
80
+ }
81
+ return mkdir(...args);
82
+ });
83
+ try {
84
+ expect(withStorageFileMutex(directory, () => "acquired")).toBe("acquired");
85
+ expect(attempts).toBeGreaterThan(1);
86
+ } finally {
87
+ mkdirSpy.mockRestore();
88
+ cleanup();
89
+ }
90
+ });
91
+
92
+ test("mutex retries ticket creation after EINVAL during lock directory cleanup", () => {
93
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-open-race-");
94
+ const directory = join(root, "locks");
95
+ const write = permissions.writeStorageFileSync;
96
+ let attempts = 0;
97
+ const writer = spyOn(permissions, "writeStorageFileSync").mockImplementation((...args) => {
98
+ if (attempts++ === 0) {
99
+ rmdirSync(directory);
100
+ throw Object.assign(new Error("ticket open raced with cleanup"), { code: "EINVAL" });
101
+ }
102
+ return write(...args);
103
+ });
104
+ try {
105
+ expect(withStorageFileMutex(directory, () => "acquired")).toBe("acquired");
106
+ expect(attempts).toBe(3);
107
+ } finally {
108
+ writer.mockRestore();
109
+ cleanup();
110
+ }
111
+ });
112
+
113
+ test("mutex keeps retrying ticket creation while cleanups remove the directory", () => {
114
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-rmdir-repeat-");
115
+ const directory = join(root, "locks");
116
+ const write = permissions.writeStorageFileSync;
117
+ let attempts = 0;
118
+ const writer = spyOn(permissions, "writeStorageFileSync").mockImplementation((...args) => {
119
+ // Three releases in sequence each remove the empty directory.
120
+ if (attempts++ < 3) rmdirSync(directory);
121
+ return write(...args);
122
+ });
123
+ try {
124
+ expect(withStorageFileMutex(directory, () => "acquired")).toBe("acquired");
125
+ expect(attempts).toBe(5);
126
+ } finally {
127
+ writer.mockRestore();
128
+ cleanup();
129
+ }
130
+ });
131
+
132
+ test("mutex retries when retirement removes the lock directory before validation", () => {
133
+ const { dir: root, cleanup } = createTestTempDir("mc-mutex-validate-race-");
134
+ const directory = join(root, "locks");
135
+ const lstatSync = fs.lstatSync;
136
+ let removals = 0;
137
+ const lstat = spyOn(fs, "lstatSync").mockImplementation((...args) => {
138
+ if (args[0] === directory && removals < 2) {
139
+ rmdirSync(directory);
140
+ removals++;
141
+ }
142
+ return lstatSync(...args);
143
+ });
144
+ try {
145
+ expect(withStorageFileMutex(directory, () => "acquired")).toBe("acquired");
146
+ expect(removals).toBe(2);
147
+ expect(existsSync(directory)).toBe(false);
148
+ } finally {
149
+ lstat.mockRestore();
150
+ cleanup();
151
+ }
152
+ });
153
+
31
154
  async function holder(root: string) {
32
155
  const script = `
33
156
  import { existsSync } from 'node:fs';
@@ -99,7 +222,7 @@ test.skipIf(process.platform === "win32")(
99
222
  200,
100
223
  );
101
224
  expect(reached).toBe(true);
102
- expect(readdirSync(join(root, "locks"))).toEqual([]);
225
+ expect(existsSync(join(root, "locks"))).toBe(false);
103
226
  } finally {
104
227
  if (child.exitCode === null) {
105
228
  child.kill("SIGKILL");