@cortexkit/opencode-magic-context 0.49.84 → 0.49.86

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 (107) 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-3sajdysh.js → context-xesm7rj3.js} +27 -26
  5. package/dist/{derive-budgets-0kcek5ex.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/memory/verification-paths.d.ts.map +1 -1
  15. package/dist/features/magic-context/project-embedding-registry.d.ts +6 -1
  16. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  17. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  18. package/dist/hooks/magic-context/lkg-recovery-fence.d.ts.map +1 -1
  19. package/dist/{index-xjfan0za.js → index-022w6314.js} +37 -37
  20. package/dist/{index-tvbkemec.js → index-08jfpny9.js} +1 -1
  21. package/dist/{index-fgy6hnr3.js → index-1bqkqde0.js} +5 -4
  22. package/dist/{index-0wehkw71.js → index-1pf5qrx4.js} +4 -4
  23. package/dist/{index-tqnvn9pa.js → index-25nktq8n.js} +3 -3
  24. package/dist/{index-98qy103c.js → index-2kf73btc.js} +1 -1
  25. package/dist/{index-vpw46557.js → index-3dtzyred.js} +1 -1
  26. package/dist/{index-bd34njzg.js → index-4ntnt8ee.js} +1 -1
  27. package/dist/{index-w2wpx7t5.js → index-4w5rx7de.js} +1 -1
  28. package/dist/{index-xd0ww0ns.js → index-798s7c8s.js} +1 -1
  29. package/dist/{index-fpqdbb67.js → index-7svecf3m.js} +3 -3
  30. package/dist/{v2/server-fvnzcnww.js → index-c5tmzym6.js} +192 -11
  31. package/dist/{index-k0jnsjcp.js → index-d0rtbv0f.js} +6 -6
  32. package/dist/{index-qybp04ff.js → index-e32b3x4n.js} +3 -3
  33. package/dist/{index-cfy5k1pa.js → index-gxdc95cp.js} +5 -5
  34. package/dist/{index-w8dcjt7f.js → index-k0tb2z28.js} +1 -1
  35. package/dist/{index-zb4h9nrk.js → index-k50xhjw1.js} +202 -14
  36. package/dist/{index-szwrpyac.js → index-nny4gm06.js} +1 -1
  37. package/dist/{index-shpyv8gq.js → index-s8ks5nz4.js} +16 -9
  38. package/dist/{index-d028gmgp.js → index-ttk3trse.js} +14 -14
  39. package/dist/{index-skwwbcnv.js → index-w6v4dw5f.js} +24 -24
  40. package/dist/{index-5wjv4c41.js → index-xccywqdj.js} +15 -15
  41. package/dist/{index-kthfyf45.js → index-zmqx48vt.js} +3 -3
  42. package/dist/index.js +33 -33
  43. package/dist/migration-worker.js +4 -3
  44. package/dist/{project-embedding-registry-y3z36mjy.js → project-embedding-registry-q80scexh.js} +6 -4
  45. package/dist/raw-ordinal-warmup-worker.js +2 -2
  46. package/dist/{recomp-orchestrator-m2s3jpvj.js → recomp-orchestrator-7ecg8ryx.js} +16 -15
  47. package/dist/{render-p2j7rn9a.js → render-yqp7q79f.js} +8 -7
  48. package/dist/{search-archive-hz9xh7nh.js → search-archive-r4h96j2z.js} +2 -2
  49. package/dist/{search-ksx0f1qd.js → search-bw22d7zc.js} +12 -10
  50. package/dist/shared/storage-file-mutex.d.ts.map +1 -1
  51. package/dist/shared/storage-permissions.d.ts +5 -3
  52. package/dist/shared/storage-permissions.d.ts.map +1 -1
  53. package/dist/{store-x0swqb5c.js → store-n4yz3n66.js} +2 -2
  54. package/dist/{store-reader-tsv1w4vt.js → store-reader-nf8z86n9.js} +1 -1
  55. package/dist/{transform-postprocess-phase-1wb2rrr1.js → transform-postprocess-phase-t99yj9vt.js} +17 -16
  56. package/dist/v2/auto-search-worker.js +3 -3
  57. package/dist/v2/chunk-embedding-write-worker.js +5 -4
  58. package/dist/v2/{context-at9nje0j.js → context-k8sx1nyy.js} +39 -39
  59. package/dist/v2/{derive-budgets-xbwcap8k.js → derive-budgets-ecjy1aqh.js} +4 -2
  60. package/dist/v2/{embedding-backfill-hjvjxp7d.js → embedding-backfill-k8kqnwfq.js} +7 -5
  61. package/dist/v2/embedding-worker.js +15 -27
  62. package/dist/v2/migration-worker.js +4 -3
  63. package/dist/v2/{project-embedding-registry-mzsvyads.js → project-embedding-registry-2jp1antr.js} +6 -4
  64. package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
  65. package/dist/v2/{recomp-orchestrator-nhef90gc.js → recomp-orchestrator-ssde9ft1.js} +17 -16
  66. package/dist/v2/{render-c9r2g2jv.js → render-fezgh7pa.js} +8 -7
  67. package/dist/v2/{search-archive-80ckv9kq.js → search-archive-zz1kza50.js} +2 -2
  68. package/dist/v2/{search-t06js5dc.js → search-m251amra.js} +11 -9
  69. package/dist/v2/{server-4z964n1c.js → server-3p6b0qya.js} +1 -1
  70. package/dist/v2/{server-3cndh146.js → server-4wwwm2ya.js} +24 -24
  71. package/dist/v2/{server-mr9rqn0y.js → server-97w51d8n.js} +4 -4
  72. package/dist/v2/{server-d706s5xn.js → server-b93f0bqh.js} +205 -17
  73. package/dist/v2/{server-dfesqfv1.js → server-brgandk4.js} +1 -1
  74. package/dist/v2/{server-w1jfaxas.js → server-cwtehwbb.js} +1 -1
  75. package/dist/v2/{server-y4favn4d.js → server-e2k9mt86.js} +1 -1
  76. package/dist/v2/{server-3hhakg5a.js → server-fsw8kbng.js} +13 -13
  77. package/dist/v2/{server-68q80y27.js → server-hn8b7sfe.js} +16 -9
  78. package/dist/v2/{server-pejjj0nv.js → server-mbkwcwgw.js} +1 -1
  79. package/dist/v2/{server-ry6rpspz.js → server-n5zr7190.js} +15 -15
  80. package/dist/v2/{server-210rc0z9.js → server-ps6rz88g.js} +1 -1
  81. package/dist/{index-fvnzcnww.js → v2/server-r2es6zt7.js} +192 -11
  82. package/dist/v2/{server-bt546axy.js → server-rz4snd3x.js} +3 -3
  83. package/dist/v2/{server-863bwkga.js → server-ssg29wjg.js} +6 -6
  84. package/dist/v2/{server-hhw6rzsn.js → server-w7mpvkpj.js} +1 -1
  85. package/dist/v2/{server-sy98vksf.js → server-xa8fefhw.js} +3 -3
  86. package/dist/v2/{server-gx1s06dx.js → server-y31y6gws.js} +5 -4
  87. package/dist/v2/{server-cce6m31c.js → server-ytqps2xa.js} +1 -1
  88. package/dist/v2/server.js +6 -4
  89. package/dist/v2/{store-reader-paamf0ac.js → store-reader-2vhx33n6.js} +1 -1
  90. package/dist/v2/{store-h3s95ywe.js → store-y56y034s.js} +2 -2
  91. package/dist/v2/{v2-archive-reader-1zzteaa5.js → v2-archive-reader-e2w39c3p.js} +1 -1
  92. package/dist/v2/{wrapup-orchestrator-9y98qcqz.js → wrapup-orchestrator-eg5b1p89.js} +16 -15
  93. package/dist/{v2-archive-reader-3yjxaj5z.js → v2-archive-reader-8dsngf2j.js} +1 -1
  94. package/dist/{wrapup-orchestrator-sa3a075a.js → wrapup-orchestrator-nmk6yf7f.js} +17 -16
  95. package/package.json +1 -1
  96. package/src/shared/storage-file-mutex-review.test.ts +125 -2
  97. package/src/shared/storage-file-mutex.ts +17 -8
  98. package/src/shared/storage-permissions-creators.test.ts +194 -0
  99. package/src/shared/storage-permissions-startup.test.ts +476 -0
  100. package/src/shared/storage-permissions.ts +227 -12
  101. package/src/tui/compaction-off.ts +2 -2
  102. package/src/tui/slots/sidebar-content-render.test.ts +309 -0
  103. package/src/tui/slots/sidebar-content.tsx +134 -99
  104. package/src/tui-compiled/compaction-off.ts +2 -2
  105. package/src/tui-compiled/slots/sidebar-content.tsx +321 -247
  106. /package/dist/{index-rdh63md0.js → index-1y4y98r1.js} +0 -0
  107. /package/dist/v2/{server-9nk5h6w6.js → server-qyazxy92.js} +0 -0
@@ -3,11 +3,11 @@ import {
3
3
  renderVerboseRangeForTool2,
4
4
  renderItemByTag2
5
5
  } from "./server-sxfbjdye.js";
6
- import"./server-3cndh146.js";
7
- import"./server-hhw6rzsn.js";
6
+ import"./server-4wwwm2ya.js";
7
+ import"./server-w7mpvkpj.js";
8
8
  import"./server-ap81bk3c.js";
9
9
  import"./server-2amn2s73.js";
10
- import"./server-9nk5h6w6.js";
10
+ import"./server-qyazxy92.js";
11
11
  import"./server-2k8tkbhz.js";
12
12
  import"./server-s15knz0w.js";
13
13
  import"./server-1zx87sdm.js";
@@ -15,14 +15,13 @@ import"./server-3ap5dmhc.js";
15
15
  import"./server-rz6g5xne.js";
16
16
  import"./server-8pdfmc27.js";
17
17
  import"./server-x6fn9x8q.js";
18
- import"./server-ry6rpspz.js";
18
+ import"./server-n5zr7190.js";
19
19
  import"./server-fb3zxn06.js";
20
- import"./server-210rc0z9.js";
20
+ import"./server-ps6rz88g.js";
21
21
  import"./server-fr0wbhdn.js";
22
- import"./server-bt546axy.js";
22
+ import"./server-rz4snd3x.js";
23
23
  import"./server-ds8vpfkr.js";
24
24
  import"./server-39bcszk4.js";
25
- import"./server-jdfe07mp.js";
26
25
  import"./server-a2f1bhyj.js";
27
26
  import"./server-6ash6z8z.js";
28
27
  import"./server-96ztjvkn.js";
@@ -30,6 +29,8 @@ import"./server-v0p37hm2.js";
30
29
  import"./server-2ra6pwf3.js";
31
30
  import"./server-5sbsnpkn.js";
32
31
  import"./server-y8xjr8rx.js";
32
+ import"./server-r2es6zt7.js";
33
+ import"./server-jdfe07mp.js";
33
34
  import"./server-gzy5w8ya.js";
34
35
  import"./server-j8376q08.js";
35
36
  import"./server-pavzsdc6.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  renderSearchArchive2,
3
3
  renderSearchArchiveOffThread2
4
- } from "./server-dfesqfv1.js";
5
- import"./server-mr9rqn0y.js";
4
+ } from "./server-brgandk4.js";
5
+ import"./server-97w51d8n.js";
6
6
  import"./server-52x68mj4.js";
7
7
  import"./server-2k8tkbhz.js";
8
8
  import"./server-s15knz0w.js";
@@ -5,14 +5,14 @@ import {
5
5
  resolveMemoriesByIdsForSearch2,
6
6
  unifiedSearch2,
7
7
  formatSearchResults2
8
- } from "./server-863bwkga.js";
8
+ } from "./server-ssg29wjg.js";
9
9
  import"./server-52x68mj4.js";
10
- import"./server-gx1s06dx.js";
11
- import"./server-pejjj0nv.js";
10
+ import"./server-y31y6gws.js";
11
+ import"./server-mbkwcwgw.js";
12
12
  import"./server-jjvbk92s.js";
13
- import"./server-68q80y27.js";
13
+ import"./server-hn8b7sfe.js";
14
14
  import"./server-4dhv7mqz.js";
15
- import"./server-hhw6rzsn.js";
15
+ import"./server-w7mpvkpj.js";
16
16
  import"./server-ap81bk3c.js";
17
17
  import"./server-2amn2s73.js";
18
18
  import"./server-qt1qqasc.js";
@@ -20,14 +20,14 @@ import"./server-2k8tkbhz.js";
20
20
  import"./server-s15knz0w.js";
21
21
  import"./server-1zx87sdm.js";
22
22
  import"./server-3ap5dmhc.js";
23
- import"./server-d706s5xn.js";
23
+ import"./server-b93f0bqh.js";
24
24
  import"./server-rz6g5xne.js";
25
- import"./server-4z964n1c.js";
25
+ import"./server-3p6b0qya.js";
26
26
  import"./server-8pdfmc27.js";
27
27
  import"./server-x6fn9x8q.js";
28
- import"./server-210rc0z9.js";
28
+ import"./server-ps6rz88g.js";
29
29
  import"./server-fr0wbhdn.js";
30
- import"./server-bt546axy.js";
30
+ import"./server-rz4snd3x.js";
31
31
  import"./server-ds8vpfkr.js";
32
32
  import"./server-a2f1bhyj.js";
33
33
  import"./server-6ash6z8z.js";
@@ -36,6 +36,8 @@ import"./server-v0p37hm2.js";
36
36
  import"./server-2ra6pwf3.js";
37
37
  import"./server-5sbsnpkn.js";
38
38
  import"./server-y8xjr8rx.js";
39
+ import"./server-r2es6zt7.js";
40
+ import"./server-jdfe07mp.js";
39
41
  import"./server-gzy5w8ya.js";
40
42
  import"./server-j8376q08.js";
41
43
  import"./server-pavzsdc6.js";
@@ -3,7 +3,7 @@ import {
3
3
  } from "./server-pavzsdc6.js";
4
4
  import {
5
5
  isUserHomeDirectory
6
- } from "./server-bt546axy.js";
6
+ } from "./server-rz4snd3x.js";
7
7
  import {
8
8
  logSlowWriteTransaction
9
9
  } from "./server-5sbsnpkn.js";
@@ -75,11 +75,18 @@ import {
75
75
  import {
76
76
  layoutLkgPrefix,
77
77
  assembleLkgPrefix
78
- } from "./server-210rc0z9.js";
78
+ } from "./server-ps6rz88g.js";
79
+ import {
80
+ ensurePrivateStorageDirectorySync,
81
+ writeStorageFileSync,
82
+ writeStorageFileAtomicSync,
83
+ syncStorageDirectorySync,
84
+ writeStorageFileDurableAtomicSync
85
+ } from "./server-r2es6zt7.js";
79
86
  import {
80
87
  gaDatabasePath2,
81
88
  V2StoreReader2
82
- } from "./server-9nk5h6w6.js";
89
+ } from "./server-qyazxy92.js";
83
90
  import {
84
91
  markHostInstructionRow,
85
92
  hostInstructionRowID,
@@ -93,13 +100,6 @@ import {
93
100
  import {
94
101
  logSlowWriteTransaction
95
102
  } from "./server-5sbsnpkn.js";
96
- import {
97
- ensurePrivateStorageDirectorySync,
98
- writeStorageFileSync,
99
- writeStorageFileAtomicSync,
100
- syncStorageDirectorySync,
101
- writeStorageFileDurableAtomicSync
102
- } from "./server-fvnzcnww.js";
103
103
 
104
104
  // src/features/magic-context/compartment-lease.ts
105
105
  var COMPARTMENT_LEASE_TTL_MS = 5 * 60 * 1000;
@@ -664,13 +664,13 @@ import { Buffer as Buffer2 } from "node:buffer";
664
664
 
665
665
  // src/hooks/magic-context/lkg-recovery-fence.ts
666
666
  import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
667
- import { lstatSync as lstatSync2, readdirSync as readdirSync2, readFileSync as readFileSync3, rmdirSync, rmSync as rmSync2 } from "node:fs";
668
- import { basename, dirname, join as join2 } from "node:path";
667
+ import { lstatSync as lstatSync2, readFileSync as readFileSync3, rmdirSync as rmdirSync2, rmSync as rmSync2 } from "node:fs";
668
+ import { dirname, join as join2 } from "node:path";
669
669
 
670
670
  // src/shared/storage-file-mutex.ts
671
671
  import { execFileSync } from "node:child_process";
672
672
  import { createHash as createHash2, randomUUID } from "node:crypto";
673
- import { readdirSync, readFileSync as readFileSync2, rmSync } from "node:fs";
673
+ import { readdirSync, readFileSync as readFileSync2, rmdirSync, rmSync } from "node:fs";
674
674
  import { join } from "node:path";
675
675
  var ticketChecksum = (name, ticket) => createHash2("sha256").update(JSON.stringify([name, ticket.choosing, ticket.number, ticket.birth])).digest("hex");
676
676
  function processBirth(pid) {
@@ -703,23 +703,23 @@ function processBirth(pid) {
703
703
  }
704
704
  var pause = new Int32Array(new SharedArrayBuffer(4));
705
705
  function withStorageFileMutex(directory, work, timeoutMs = 1000) {
706
- ensurePrivateStorageDirectorySync(directory);
706
+ const deadline = performance.now() + timeoutMs;
707
707
  const name = `${process.pid}-${randomUUID()}.lock`;
708
708
  const ownPath = join(directory, name);
709
709
  const birth = processBirth(process.pid);
710
710
  const ticket = { choosing: true, number: 0, birth, checksum: "" };
711
711
  const encodedTicket = () => JSON.stringify({ ...ticket, checksum: ticketChecksum(name, ticket) });
712
- for (let attempt = 0;; attempt++) {
712
+ for (;; ) {
713
713
  try {
714
+ ensurePrivateStorageDirectorySync(directory);
714
715
  writeStorageFileSync(ownPath, encodedTicket(), { flag: "wx", forcePrivate: true });
715
716
  break;
716
717
  } catch (error) {
717
- if (error.code !== "ENOENT" || attempt >= 2)
718
+ const code = error.code;
719
+ if (code !== "ENOENT" && code !== "EEXIST" && code !== "EINVAL" || performance.now() >= deadline)
718
720
  throw error;
719
- ensurePrivateStorageDirectorySync(directory);
720
721
  }
721
722
  }
722
- const deadline = performance.now() + timeoutMs;
723
723
  const peers = () => {
724
724
  const found = [];
725
725
  for (const other of readdirSync(directory)) {
@@ -761,6 +761,9 @@ function withStorageFileMutex(directory, work, timeoutMs = 1000) {
761
761
  return result;
762
762
  } finally {
763
763
  rmSync(ownPath, { force: true });
764
+ try {
765
+ rmdirSync(directory);
766
+ } catch {}
764
767
  }
765
768
  }
766
769
 
@@ -847,7 +850,7 @@ function publishRecord(record) {
847
850
  try {
848
851
  if (record.state === "clean")
849
852
  observer?.("clean");
850
- writeStorageFileDurableAtomicSync(lkgRecoveryFencePath(record.sessionId), JSON.stringify({ ...record, checksum: hash(JSON.stringify(payload(record))) }), () => observer?.("temp-synced"));
853
+ writeStorageFileDurableAtomicSync(lkgRecoveryFencePath(record.sessionId), JSON.stringify({ ...record, checksum: hash(JSON.stringify(payload(record))) }), () => observer?.("temp-synced"), `${lkgRecoveryFencePath(record.sessionId)}.tmp`);
851
854
  if (record.state === "dirty")
852
855
  observer?.("dirty");
853
856
  remember(record.sessionId, {
@@ -858,7 +861,7 @@ function publishRecord(record) {
858
861
  const visible = read(record.sessionId);
859
862
  if (record.state === "clean" && visible?.state === "clean" && visible.revision === record.revision && visible.slotKey === record.slotKey) {
860
863
  const dirty = { ...record, state: "dirty" };
861
- writeStorageFileDurableAtomicSync(lkgRecoveryFencePath(record.sessionId), JSON.stringify({ ...dirty, checksum: hash(JSON.stringify(payload(dirty))) }));
864
+ writeStorageFileDurableAtomicSync(lkgRecoveryFencePath(record.sessionId), JSON.stringify({ ...dirty, checksum: hash(JSON.stringify(payload(dirty))) }), undefined, `${lkgRecoveryFencePath(record.sessionId)}.tmp`);
862
865
  }
863
866
  remember(record.sessionId, { state: "invalid", record: null });
864
867
  throw error;
@@ -898,10 +901,7 @@ function locked(sessionId, work) {
898
901
  ioObserver?.("mutex");
899
902
  return withStorageFileMutex(`${lkgRecoveryFencePath(sessionId)}.locks`, () => {
900
903
  const path = lkgRecoveryFencePath(sessionId);
901
- for (const name of readdirSync2(dirname(path))) {
902
- if (name.startsWith(`${basename(path)}.`) && name.endsWith(".tmp"))
903
- rmSync2(join2(dirname(path), name), { force: true });
904
- }
904
+ rmSync2(`${path}.tmp`, { force: true });
905
905
  return work();
906
906
  });
907
907
  }
@@ -1081,7 +1081,7 @@ function clearLkgRecoveryFence(sessionId, remove, shouldClear) {
1081
1081
  });
1082
1082
  } finally {
1083
1083
  try {
1084
- rmdirSync(`${path}.locks`);
1084
+ rmdirSync2(`${path}.locks`);
1085
1085
  } catch {}
1086
1086
  }
1087
1087
  }
@@ -137,11 +137,11 @@ async function serveV2ArchiveReads2(port, openConnections) {
137
137
  { createV2RecoveryAttachments }
138
138
  ] = await Promise.all([
139
139
  import("./sqlite-zdgm52sv.js"),
140
- import("./store-reader-paamf0ac.js"),
141
- import("./store-h3s95ywe.js"),
140
+ import("./store-reader-2vhx33n6.js"),
141
+ import("./store-y56y034s.js"),
142
142
  import("./read-session-chunk-n3nhfvd7.js"),
143
- import("./render-c9r2g2jv.js"),
144
- import("./search-archive-80ckv9kq.js"),
143
+ import("./render-fezgh7pa.js"),
144
+ import("./search-archive-zz1kza50.js"),
145
145
  import("./expand-attachments-h33jbgyz.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -7,8 +7,16 @@ import {
7
7
  import {
8
8
  getMagicContextStorageDir,
9
9
  importPluginModule,
10
- log2
10
+ log2,
11
+ flushLogger2
11
12
  } from "./server-j8376q08.js";
13
+ import {
14
+ shouldEnforcePrivateStoragePermissions,
15
+ ensureStorageDirectorySync,
16
+ writeStorageFileAsync,
17
+ writeStorageFileHandleAsync,
18
+ createStorageFileHandleAsync
19
+ } from "./server-r2es6zt7.js";
12
20
  import {
13
21
  getSynapseLaneIdentity
14
22
  } from "./server-x6fn9x8q.js";
@@ -18,13 +26,6 @@ import {
18
26
  import {
19
27
  computeNormalizedHash
20
28
  } from "./server-2bvekkfy.js";
21
- import {
22
- shouldEnforcePrivateStoragePermissions,
23
- ensureStorageDirectorySync,
24
- writeStorageFileAsync,
25
- writeStorageFileHandleAsync,
26
- createStorageFileHandleAsync
27
- } from "./server-fvnzcnww.js";
28
29
 
29
30
  // src/features/magic-context/memory/embedding-local.ts
30
31
  import { readdirSync, statSync as statSync2 } from "node:fs";
@@ -675,6 +676,80 @@ function getEmbeddingProviderIdentity(config) {
675
676
  import { fork } from "node:child_process";
676
677
  import { Worker } from "node:worker_threads";
677
678
 
679
+ // src/features/magic-context/memory/embedding-worker-loop.ts
680
+ var EMBEDDING_WORKER_STOPPING_ERROR = "embedding worker stopping";
681
+ function isEmbeddingWorkerStopNotice(message) {
682
+ return typeof message === "object" && message !== null && "control" in message && (message.control === "stopping" || message.control === "stopped");
683
+ }
684
+ function serveEmbeddingWorker(port, model, options) {
685
+ const now = options.now ?? (() => performance.now());
686
+ let queue = Promise.resolve();
687
+ let stopping = false;
688
+ let busySince = null;
689
+ const refuse = (id) => port.postMessage({ id, loaded: false, error: EMBEDDING_WORKER_STOPPING_ERROR });
690
+ const handle = async (request) => {
691
+ if (stopping)
692
+ return refuse(request.id);
693
+ busySince = now();
694
+ try {
695
+ const loaded = await model.initialize();
696
+ let vectors;
697
+ if (loaded && request.texts) {
698
+ vectors = [];
699
+ for (let offset = 0;offset < request.texts.length; offset += options.batchSize) {
700
+ if (offset > 0)
701
+ await new Promise((resolve) => setImmediate(resolve));
702
+ if (stopping)
703
+ throw new Error(EMBEDDING_WORKER_STOPPING_ERROR);
704
+ vectors.push(...await model.embedBatch(request.texts.slice(offset, offset + options.batchSize)));
705
+ }
706
+ }
707
+ port.postMessage({
708
+ id: request.id,
709
+ loaded,
710
+ vectors,
711
+ failure: model.getLastFailureReason(),
712
+ stats: options.stats?.()
713
+ }, vectors?.flatMap((vector) => vector ? [vector.buffer] : []) ?? []);
714
+ } catch (error) {
715
+ port.postMessage({ id: request.id, loaded: false, error: String(error) });
716
+ } finally {
717
+ busySince = null;
718
+ }
719
+ };
720
+ const stop = async () => {
721
+ stopping = true;
722
+ const requestedAt = now();
723
+ const busy = busySince !== null;
724
+ port.postMessage({
725
+ control: "stopping",
726
+ busy,
727
+ busyMs: busySince === null ? 0 : requestedAt - busySince
728
+ });
729
+ await queue;
730
+ try {
731
+ await model.dispose();
732
+ } catch {}
733
+ port.postMessage({
734
+ control: "stopped",
735
+ busy,
736
+ waitedMs: now() - requestedAt
737
+ });
738
+ options.exit();
739
+ };
740
+ port.on("message", (message) => {
741
+ if (message?.stop === true) {
742
+ if (!stopping)
743
+ stop();
744
+ return;
745
+ }
746
+ const request = message;
747
+ if (stopping)
748
+ return refuse(request.id);
749
+ queue = queue.then(() => handle(request));
750
+ });
751
+ }
752
+
678
753
  // src/features/magic-context/memory/onnx-telemetry.ts
679
754
  import { isMainThread } from "node:worker_threads";
680
755
  var FFI_SPECIFIER = "bun:ffi";
@@ -721,6 +796,41 @@ async function prepareNativeOnnxTelemetry() {
721
796
 
722
797
  // src/features/magic-context/memory/embedding-worker-client.ts
723
798
  var warnedWindowsTelemetry = false;
799
+ var EMBEDDING_WORKER_STOP_GRACE_MS = 5000;
800
+ var EMBEDDING_WORKER_FORCED_EXIT_WAIT_MS = 2000;
801
+ var EMBEDDING_WORKER_SIGKILL_WAIT_MS = 200;
802
+ var EMBEDDING_WORKER_STOP_MAX_MS = EMBEDDING_WORKER_STOP_GRACE_MS + EMBEDDING_WORKER_FORCED_EXIT_WAIT_MS + EMBEDDING_WORKER_SIGKILL_WAIT_MS;
803
+ function busySince(state) {
804
+ let oldest = null;
805
+ for (const sentAt of state.dispatched.values()) {
806
+ if (oldest === null || sentAt < oldest)
807
+ oldest = sentAt;
808
+ }
809
+ return oldest;
810
+ }
811
+ async function exitsWithin(exit, ms) {
812
+ let timer;
813
+ try {
814
+ return await Promise.race([
815
+ exit.then(() => true),
816
+ new Promise((resolve) => {
817
+ timer = setTimeout(() => resolve(false), ms);
818
+ })
819
+ ]);
820
+ } finally {
821
+ clearTimeout(timer);
822
+ }
823
+ }
824
+ function describeRunning(since, at) {
825
+ return since === null ? "no" : `yes (for ${Math.max(0, Math.round(at - since))}ms)`;
826
+ }
827
+ function describeStuckWorker(state, stopSince) {
828
+ const notice = state.stopNotice;
829
+ const at = performance.now();
830
+ if (notice)
831
+ return describeRunning(notice.busy ? notice.receivedAt - notice.busyMs : null, at);
832
+ return `${describeRunning(stopSince, at)}, no answer to the stop request`;
833
+ }
724
834
 
725
835
  class EmbeddingWorkerClient {
726
836
  data;
@@ -728,19 +838,23 @@ class EmbeddingWorkerClient {
728
838
  timeoutMs;
729
839
  prepareTelemetry;
730
840
  idleMs;
841
+ options;
731
842
  worker = null;
732
843
  startPromise = null;
844
+ states = new WeakMap;
845
+ stopping = new Set;
733
846
  nextId = 1;
734
847
  pending = new Map;
735
848
  disposed = false;
736
849
  activeRequests = 0;
737
850
  idleTimer = null;
738
- constructor(data, entry = new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./embedding-worker.ts" : "./embedding-worker.js", import.meta.url), timeoutMs = 5 * 60000, prepareTelemetry = prepareNativeOnnxTelemetry, idleMs = 10 * 60000) {
851
+ constructor(data, entry = new URL(new URL(import.meta.url).pathname.endsWith(".ts") ? "./embedding-worker.ts" : "./embedding-worker.js", import.meta.url), timeoutMs = 5 * 60000, prepareTelemetry = prepareNativeOnnxTelemetry, idleMs = 10 * 60000, options = {}) {
739
852
  this.data = data;
740
853
  this.entry = entry;
741
854
  this.timeoutMs = timeoutMs;
742
855
  this.prepareTelemetry = prepareTelemetry;
743
856
  this.idleMs = idleMs;
857
+ this.options = options;
744
858
  }
745
859
  start() {
746
860
  if (this.startPromise)
@@ -778,14 +892,38 @@ class EmbeddingWorkerClient {
778
892
  }
779
893
  }
780
894
  this.worker = worker;
895
+ let markExited;
896
+ const state = {
897
+ dispatched: new Map,
898
+ stopNotice: null,
899
+ exited: false,
900
+ exit: new Promise((resolve) => {
901
+ markExited = resolve;
902
+ })
903
+ };
904
+ this.states.set(worker, state);
905
+ worker.once("exit", () => {
906
+ state.exited = true;
907
+ markExited();
908
+ });
781
909
  worker.unref();
782
910
  if (!(worker instanceof Worker))
783
911
  worker.channel?.unref?.();
784
912
  worker.on("message", (wire) => {
913
+ if (isEmbeddingWorkerStopNotice(wire)) {
914
+ if (wire.control === "stopping")
915
+ state.stopNotice = {
916
+ busy: wire.busy,
917
+ busyMs: wire.busyMs,
918
+ receivedAt: performance.now()
919
+ };
920
+ return;
921
+ }
785
922
  const reply = worker instanceof Worker ? wire : {
786
923
  ...wire,
787
924
  vectors: wire.vectors?.map((vector) => vector === null ? null : new Float32Array(Uint8Array.from(Buffer.from(vector, "base64")).buffer))
788
925
  };
926
+ state.dispatched.delete(reply.id);
789
927
  if (this.worker !== worker)
790
928
  return;
791
929
  const request = this.pending.get(reply.id);
@@ -893,6 +1031,7 @@ class EmbeddingWorkerClient {
893
1031
  worker.ref();
894
1032
  if (!(worker instanceof Worker))
895
1033
  worker.channel?.ref?.();
1034
+ this.states.get(worker)?.dispatched.set(id, performance.now());
896
1035
  try {
897
1036
  if (worker instanceof Worker)
898
1037
  worker.postMessage({ id, texts });
@@ -915,21 +1054,70 @@ class EmbeddingWorkerClient {
915
1054
  request.reject(error);
916
1055
  }
917
1056
  this.pending.clear();
918
- if (worker instanceof Worker) {
919
- await worker.terminate();
920
- } else if (worker && worker.exitCode === null && worker.signalCode === null) {
921
- worker.ref();
1057
+ if (!worker)
1058
+ return;
1059
+ const stopped = this.stopWorker(worker, error.message);
1060
+ this.stopping.add(stopped);
1061
+ try {
1062
+ await stopped;
1063
+ } finally {
1064
+ this.stopping.delete(stopped);
1065
+ }
1066
+ }
1067
+ async stopWorker(worker, reason) {
1068
+ const state = this.states.get(worker);
1069
+ if (!state || state.exited)
1070
+ return;
1071
+ const writeLog = this.options.log ?? log2;
1072
+ const graceMs = this.options.stopGraceMs ?? EMBEDDING_WORKER_STOP_GRACE_MS;
1073
+ const forcedExitWaitMs = this.options.forcedExitWaitMs ?? EMBEDDING_WORKER_FORCED_EXIT_WAIT_MS;
1074
+ const owner = worker instanceof Worker ? `pid ${process.pid}` : `pid ${process.pid}, worker pid ${worker.pid ?? "unknown"}`;
1075
+ const startedAt = performance.now();
1076
+ const stopSince = busySince(state);
1077
+ worker.ref();
1078
+ if (!(worker instanceof Worker))
922
1079
  worker.channel?.ref?.();
923
- await new Promise((resolve) => {
924
- worker.once("exit", () => resolve());
1080
+ const request = { stop: true };
1081
+ try {
1082
+ if (worker instanceof Worker)
1083
+ worker.postMessage(request);
1084
+ else if (worker.connected)
1085
+ worker.send(request, () => {});
1086
+ } catch {}
1087
+ if (await exitsWithin(state.exit, graceMs)) {
1088
+ writeLog(`[magic-context] embedding worker stopped (${reason}; ${owner}; inference running: ${describeRunning(stopSince, startedAt)}; stop took ${Math.round(performance.now() - startedAt)}ms)`);
1089
+ flushLogger2();
1090
+ return;
1091
+ }
1092
+ writeLog(`[magic-context] embedding worker did not stop within ${graceMs}ms; terminating it (${reason}; ${owner}; inference running: ${describeStuckWorker(state, stopSince)})`);
1093
+ flushLogger2();
1094
+ try {
1095
+ if (worker instanceof Worker)
1096
+ worker.terminate().catch(() => {});
1097
+ else
925
1098
  worker.kill();
926
- });
1099
+ } catch {}
1100
+ if (await exitsWithin(state.exit, forcedExitWaitMs))
1101
+ return;
1102
+ let killed = false;
1103
+ if (!(worker instanceof Worker) && process.platform !== "win32") {
1104
+ try {
1105
+ killed = worker.kill("SIGKILL");
1106
+ } catch {}
1107
+ if (await exitsWithin(state.exit, EMBEDDING_WORKER_SIGKILL_WAIT_MS))
1108
+ return;
927
1109
  }
1110
+ writeLog(`[magic-context] embedding worker has not exited ${forcedExitWaitMs}ms after it was terminated${killed ? " and sent SIGKILL" : ""}; no longer waiting for it (${reason}; ${owner})`);
1111
+ flushLogger2();
1112
+ worker.unref();
1113
+ if (!(worker instanceof Worker))
1114
+ worker.channel?.unref?.();
928
1115
  }
929
1116
  async dispose() {
930
1117
  this.disposed = true;
931
1118
  await this.startPromise?.catch(() => {});
932
1119
  await this.stop(new Error("embedding worker disposed"));
1120
+ await Promise.all([...this.stopping]);
933
1121
  }
934
1122
  }
935
1123
 
@@ -1651,4 +1839,4 @@ class LocalEmbeddingProvider {
1651
1839
  }
1652
1840
  }
1653
1841
 
1654
- export { dominantEmbeddingFailure, embeddingModelsMatch, resolveEmbeddingTextPrefixes, getCachedLocalEmbeddingPooling, logLocalEmbeddingPoolingDecisionOnce, preflightLocalEmbeddingPooling, logLocalEmbeddingPoolingUnavailableOnce, getEmbeddingProviderIdentity, resolveLocalEmbeddingWorkerRuntime, getLocalEmbeddingNativeMemoryStats, LocalEmbeddingProvider };
1842
+ export { dominantEmbeddingFailure, embeddingModelsMatch, resolveEmbeddingTextPrefixes, getCachedLocalEmbeddingPooling, logLocalEmbeddingPoolingDecisionOnce, preflightLocalEmbeddingPooling, logLocalEmbeddingPoolingUnavailableOnce, getEmbeddingProviderIdentity, serveEmbeddingWorker, resolveLocalEmbeddingWorkerRuntime, getLocalEmbeddingNativeMemoryStats, LocalEmbeddingProvider };
@@ -22,7 +22,7 @@ import {
22
22
  } from "./server-2k8tkbhz.js";
23
23
  import {
24
24
  readV2ArchiveOffThread2
25
- } from "./server-mr9rqn0y.js";
25
+ } from "./server-97w51d8n.js";
26
26
 
27
27
  // src/tools/ctx-expand/search-archive.ts
28
28
  var archiveReadsOnThisThread = 0;
@@ -5,7 +5,7 @@ import {
5
5
  getSdkWindowGeometry,
6
6
  getSdkContextLimit,
7
7
  getSdkInputLimit
8
- } from "./server-sy98vksf.js";
8
+ } from "./server-xa8fefhw.js";
9
9
  import {
10
10
  localBudget,
11
11
  calibrationForModelKey
@@ -3,7 +3,7 @@ import {
3
3
  } from "./server-j8376q08.js";
4
4
  import {
5
5
  setOutputReserveConfig
6
- } from "./server-sy98vksf.js";
6
+ } from "./server-xa8fefhw.js";
7
7
  import {
8
8
  DEFAULT_EXECUTE_THRESHOLD_PERCENTAGE,
9
9
  PROTECTED_TOKENS_MIN,