@angri450/zvec-grep 0.2.2

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 (418) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +319 -0
  3. package/README_CN.md +297 -0
  4. package/dist/authorization/index.d.ts +7 -0
  5. package/dist/authorization/index.js +7 -0
  6. package/dist/authorization/index.js.map +1 -0
  7. package/dist/authorization/manager.d.ts +8 -0
  8. package/dist/authorization/manager.js +19 -0
  9. package/dist/authorization/manager.js.map +1 -0
  10. package/dist/authorization/operation.d.ts +7 -0
  11. package/dist/authorization/operation.js +50 -0
  12. package/dist/authorization/operation.js.map +1 -0
  13. package/dist/authorization/planner.d.ts +21 -0
  14. package/dist/authorization/planner.js +97 -0
  15. package/dist/authorization/planner.js.map +1 -0
  16. package/dist/authorization/prompt.d.ts +12 -0
  17. package/dist/authorization/prompt.js +63 -0
  18. package/dist/authorization/prompt.js.map +1 -0
  19. package/dist/authorization/store.d.ts +20 -0
  20. package/dist/authorization/store.js +251 -0
  21. package/dist/authorization/store.js.map +1 -0
  22. package/dist/authorization/target.d.ts +15 -0
  23. package/dist/authorization/target.js +49 -0
  24. package/dist/authorization/target.js.map +1 -0
  25. package/dist/authorization/types.d.ts +61 -0
  26. package/dist/authorization/types.js +2 -0
  27. package/dist/authorization/types.js.map +1 -0
  28. package/dist/cli/args.d.ts +6 -0
  29. package/dist/cli/args.js +1255 -0
  30. package/dist/cli/args.js.map +1 -0
  31. package/dist/cli/auth.d.ts +21 -0
  32. package/dist/cli/auth.js +209 -0
  33. package/dist/cli/auth.js.map +1 -0
  34. package/dist/cli/commands.d.ts +4 -0
  35. package/dist/cli/commands.js +801 -0
  36. package/dist/cli/commands.js.map +1 -0
  37. package/dist/cli/errors.d.ts +9 -0
  38. package/dist/cli/errors.js +131 -0
  39. package/dist/cli/errors.js.map +1 -0
  40. package/dist/cli/format/context.d.ts +9 -0
  41. package/dist/cli/format/context.js +786 -0
  42. package/dist/cli/format/context.js.map +1 -0
  43. package/dist/cli/format/debug.d.ts +4 -0
  44. package/dist/cli/format/debug.js +60 -0
  45. package/dist/cli/format/debug.js.map +1 -0
  46. package/dist/cli/format/highlight.d.ts +3 -0
  47. package/dist/cli/format/highlight.js +106 -0
  48. package/dist/cli/format/highlight.js.map +1 -0
  49. package/dist/cli/format/progress.d.ts +13 -0
  50. package/dist/cli/format/progress.js +290 -0
  51. package/dist/cli/format/progress.js.map +1 -0
  52. package/dist/cli/format/range.d.ts +3 -0
  53. package/dist/cli/format/range.js +24 -0
  54. package/dist/cli/format/range.js.map +1 -0
  55. package/dist/cli/format/status.d.ts +83 -0
  56. package/dist/cli/format/status.js +530 -0
  57. package/dist/cli/format/status.js.map +1 -0
  58. package/dist/cli/help.d.ts +1 -0
  59. package/dist/cli/help.js +546 -0
  60. package/dist/cli/help.js.map +1 -0
  61. package/dist/cli/index.d.ts +2 -0
  62. package/dist/cli/index.js +40 -0
  63. package/dist/cli/index.js.map +1 -0
  64. package/dist/cli/install.d.ts +4 -0
  65. package/dist/cli/install.js +1735 -0
  66. package/dist/cli/install.js.map +1 -0
  67. package/dist/cli/managed-rg.d.ts +10 -0
  68. package/dist/cli/managed-rg.js +337 -0
  69. package/dist/cli/managed-rg.js.map +1 -0
  70. package/dist/cli/server-search.d.ts +3 -0
  71. package/dist/cli/server-search.js +12 -0
  72. package/dist/cli/server-search.js.map +1 -0
  73. package/dist/cli/types.d.ts +87 -0
  74. package/dist/cli/types.js +10 -0
  75. package/dist/cli/types.js.map +1 -0
  76. package/dist/cli/version.d.ts +1 -0
  77. package/dist/cli/version.js +13 -0
  78. package/dist/cli/version.js.map +1 -0
  79. package/dist/client/daemon-client.d.ts +31 -0
  80. package/dist/client/daemon-client.js +203 -0
  81. package/dist/client/daemon-client.js.map +1 -0
  82. package/dist/client/mode-router.d.ts +9 -0
  83. package/dist/client/mode-router.js +28 -0
  84. package/dist/client/mode-router.js.map +1 -0
  85. package/dist/client/search-policy.d.ts +11 -0
  86. package/dist/client/search-policy.js +15 -0
  87. package/dist/client/search-policy.js.map +1 -0
  88. package/dist/daemon/backend.d.ts +78 -0
  89. package/dist/daemon/backend.js +1118 -0
  90. package/dist/daemon/backend.js.map +1 -0
  91. package/dist/daemon/change-set.d.ts +30 -0
  92. package/dist/daemon/change-set.js +163 -0
  93. package/dist/daemon/change-set.js.map +1 -0
  94. package/dist/daemon/config.d.ts +27 -0
  95. package/dist/daemon/config.js +107 -0
  96. package/dist/daemon/config.js.map +1 -0
  97. package/dist/daemon/errors.d.ts +5 -0
  98. package/dist/daemon/errors.js +11 -0
  99. package/dist/daemon/errors.js.map +1 -0
  100. package/dist/daemon/http-server.d.ts +30 -0
  101. package/dist/daemon/http-server.js +307 -0
  102. package/dist/daemon/http-server.js.map +1 -0
  103. package/dist/daemon/index-coordinator.d.ts +22 -0
  104. package/dist/daemon/index-coordinator.js +55 -0
  105. package/dist/daemon/index-coordinator.js.map +1 -0
  106. package/dist/daemon/job-scheduler.d.ts +85 -0
  107. package/dist/daemon/job-scheduler.js +492 -0
  108. package/dist/daemon/job-scheduler.js.map +1 -0
  109. package/dist/daemon/logger.d.ts +10 -0
  110. package/dist/daemon/logger.js +101 -0
  111. package/dist/daemon/logger.js.map +1 -0
  112. package/dist/daemon/model-pool.d.ts +48 -0
  113. package/dist/daemon/model-pool.js +190 -0
  114. package/dist/daemon/model-pool.js.map +1 -0
  115. package/dist/daemon/root-lease.d.ts +14 -0
  116. package/dist/daemon/root-lease.js +197 -0
  117. package/dist/daemon/root-lease.js.map +1 -0
  118. package/dist/daemon/root-runtime.d.ts +80 -0
  119. package/dist/daemon/root-runtime.js +340 -0
  120. package/dist/daemon/root-runtime.js.map +1 -0
  121. package/dist/daemon/runtime-manager.d.ts +47 -0
  122. package/dist/daemon/runtime-manager.js +252 -0
  123. package/dist/daemon/runtime-manager.js.map +1 -0
  124. package/dist/daemon/runtime.d.ts +12 -0
  125. package/dist/daemon/runtime.js +105 -0
  126. package/dist/daemon/runtime.js.map +1 -0
  127. package/dist/daemon/server-controller.d.ts +38 -0
  128. package/dist/daemon/server-controller.js +327 -0
  129. package/dist/daemon/server-controller.js.map +1 -0
  130. package/dist/daemon/watch-manager.d.ts +62 -0
  131. package/dist/daemon/watch-manager.js +415 -0
  132. package/dist/daemon/watch-manager.js.map +1 -0
  133. package/dist/daemon/workspace-read-session-cache.d.ts +31 -0
  134. package/dist/daemon/workspace-read-session-cache.js +115 -0
  135. package/dist/daemon/workspace-read-session-cache.js.map +1 -0
  136. package/dist/engine/code-formats.d.ts +3 -0
  137. package/dist/engine/code-formats.js +14 -0
  138. package/dist/engine/code-formats.js.map +1 -0
  139. package/dist/engine/config.d.ts +57 -0
  140. package/dist/engine/config.js +351 -0
  141. package/dist/engine/config.js.map +1 -0
  142. package/dist/engine/errors.d.ts +20 -0
  143. package/dist/engine/errors.js +51 -0
  144. package/dist/engine/errors.js.map +1 -0
  145. package/dist/engine/extraction/code/adapter.d.ts +19 -0
  146. package/dist/engine/extraction/code/adapter.js +24 -0
  147. package/dist/engine/extraction/code/adapter.js.map +1 -0
  148. package/dist/engine/extraction/code/extractor.d.ts +13 -0
  149. package/dist/engine/extraction/code/extractor.js +696 -0
  150. package/dist/engine/extraction/code/extractor.js.map +1 -0
  151. package/dist/engine/extraction/code/families/c-family.d.ts +2 -0
  152. package/dist/engine/extraction/code/families/c-family.js +122 -0
  153. package/dist/engine/extraction/code/families/c-family.js.map +1 -0
  154. package/dist/engine/extraction/code/families/js-ts.d.ts +12 -0
  155. package/dist/engine/extraction/code/families/js-ts.js +118 -0
  156. package/dist/engine/extraction/code/families/js-ts.js.map +1 -0
  157. package/dist/engine/extraction/code/families/metadata.d.ts +8 -0
  158. package/dist/engine/extraction/code/families/metadata.js +86 -0
  159. package/dist/engine/extraction/code/families/metadata.js.map +1 -0
  160. package/dist/engine/extraction/code/families/name-field.d.ts +3 -0
  161. package/dist/engine/extraction/code/families/name-field.js +22 -0
  162. package/dist/engine/extraction/code/families/name-field.js.map +1 -0
  163. package/dist/engine/extraction/code/languages/c.d.ts +1 -0
  164. package/dist/engine/extraction/code/languages/c.js +12 -0
  165. package/dist/engine/extraction/code/languages/c.js.map +1 -0
  166. package/dist/engine/extraction/code/languages/cpp.d.ts +1 -0
  167. package/dist/engine/extraction/code/languages/cpp.js +18 -0
  168. package/dist/engine/extraction/code/languages/cpp.js.map +1 -0
  169. package/dist/engine/extraction/code/languages/go.d.ts +2 -0
  170. package/dist/engine/extraction/code/languages/go.js +70 -0
  171. package/dist/engine/extraction/code/languages/go.js.map +1 -0
  172. package/dist/engine/extraction/code/languages/java.d.ts +1 -0
  173. package/dist/engine/extraction/code/languages/java.js +17 -0
  174. package/dist/engine/extraction/code/languages/java.js.map +1 -0
  175. package/dist/engine/extraction/code/languages/javascript.d.ts +2 -0
  176. package/dist/engine/extraction/code/languages/javascript.js +23 -0
  177. package/dist/engine/extraction/code/languages/javascript.js.map +1 -0
  178. package/dist/engine/extraction/code/languages/python.d.ts +2 -0
  179. package/dist/engine/extraction/code/languages/python.js +52 -0
  180. package/dist/engine/extraction/code/languages/python.js.map +1 -0
  181. package/dist/engine/extraction/code/languages/rust.d.ts +2 -0
  182. package/dist/engine/extraction/code/languages/rust.js +25 -0
  183. package/dist/engine/extraction/code/languages/rust.js.map +1 -0
  184. package/dist/engine/extraction/code/languages/typescript.d.ts +2 -0
  185. package/dist/engine/extraction/code/languages/typescript.js +37 -0
  186. package/dist/engine/extraction/code/languages/typescript.js.map +1 -0
  187. package/dist/engine/extraction/code/tree-sitter/grammar.d.ts +4 -0
  188. package/dist/engine/extraction/code/tree-sitter/grammar.js +49 -0
  189. package/dist/engine/extraction/code/tree-sitter/grammar.js.map +1 -0
  190. package/dist/engine/extraction/code/tree-sitter/nodes.d.ts +3 -0
  191. package/dist/engine/extraction/code/tree-sitter/nodes.js +27 -0
  192. package/dist/engine/extraction/code/tree-sitter/nodes.js.map +1 -0
  193. package/dist/engine/extraction/code/tree-sitter/parser.d.ts +2 -0
  194. package/dist/engine/extraction/code/tree-sitter/parser.js +31 -0
  195. package/dist/engine/extraction/code/tree-sitter/parser.js.map +1 -0
  196. package/dist/engine/extraction/ids.d.ts +1 -0
  197. package/dist/engine/extraction/ids.js +5 -0
  198. package/dist/engine/extraction/ids.js.map +1 -0
  199. package/dist/engine/extraction/image/extractor.d.ts +5 -0
  200. package/dist/engine/extraction/image/extractor.js +35 -0
  201. package/dist/engine/extraction/image/extractor.js.map +1 -0
  202. package/dist/engine/extraction/index.d.ts +4 -0
  203. package/dist/engine/extraction/index.js +3 -0
  204. package/dist/engine/extraction/index.js.map +1 -0
  205. package/dist/engine/extraction/markdown/extractor.d.ts +7 -0
  206. package/dist/engine/extraction/markdown/extractor.js +362 -0
  207. package/dist/engine/extraction/markdown/extractor.js.map +1 -0
  208. package/dist/engine/extraction/runtime.d.ts +9 -0
  209. package/dist/engine/extraction/runtime.js +37 -0
  210. package/dist/engine/extraction/runtime.js.map +1 -0
  211. package/dist/engine/extraction/source.d.ts +18 -0
  212. package/dist/engine/extraction/source.js +22 -0
  213. package/dist/engine/extraction/source.js.map +1 -0
  214. package/dist/engine/extraction/text/extractor.d.ts +7 -0
  215. package/dist/engine/extraction/text/extractor.js +168 -0
  216. package/dist/engine/extraction/text/extractor.js.map +1 -0
  217. package/dist/engine/extraction/types.d.ts +4 -0
  218. package/dist/engine/extraction/types.js +2 -0
  219. package/dist/engine/extraction/types.js.map +1 -0
  220. package/dist/engine/extraction/vector-content.d.ts +5 -0
  221. package/dist/engine/extraction/vector-content.js +83 -0
  222. package/dist/engine/extraction/vector-content.js.map +1 -0
  223. package/dist/engine/file-size-policy.d.ts +6 -0
  224. package/dist/engine/file-size-policy.js +20 -0
  225. package/dist/engine/file-size-policy.js.map +1 -0
  226. package/dist/engine/file-type.d.ts +15 -0
  227. package/dist/engine/file-type.js +152 -0
  228. package/dist/engine/file-type.js.map +1 -0
  229. package/dist/engine/index-status.d.ts +9 -0
  230. package/dist/engine/index-status.js +38 -0
  231. package/dist/engine/index-status.js.map +1 -0
  232. package/dist/engine/manifest.d.ts +13 -0
  233. package/dist/engine/manifest.js +124 -0
  234. package/dist/engine/manifest.js.map +1 -0
  235. package/dist/engine/models/artifact-cache-lock.d.ts +16 -0
  236. package/dist/engine/models/artifact-cache-lock.js +228 -0
  237. package/dist/engine/models/artifact-cache-lock.js.map +1 -0
  238. package/dist/engine/models/artifact-downloader.d.ts +77 -0
  239. package/dist/engine/models/artifact-downloader.js +766 -0
  240. package/dist/engine/models/artifact-downloader.js.map +1 -0
  241. package/dist/engine/models/backends/llama-cpp.d.ts +100 -0
  242. package/dist/engine/models/backends/llama-cpp.js +567 -0
  243. package/dist/engine/models/backends/llama-cpp.js.map +1 -0
  244. package/dist/engine/models/backends/model2vec-runtime.d.ts +63 -0
  245. package/dist/engine/models/backends/model2vec-runtime.js +112 -0
  246. package/dist/engine/models/backends/model2vec-runtime.js.map +1 -0
  247. package/dist/engine/models/backends/model2vec-tokenizer.d.ts +2 -0
  248. package/dist/engine/models/backends/model2vec-tokenizer.js +42 -0
  249. package/dist/engine/models/backends/model2vec-tokenizer.js.map +1 -0
  250. package/dist/engine/models/backends/model2vec-worker-pool.d.ts +25 -0
  251. package/dist/engine/models/backends/model2vec-worker-pool.js +264 -0
  252. package/dist/engine/models/backends/model2vec-worker-pool.js.map +1 -0
  253. package/dist/engine/models/backends/model2vec-worker.d.ts +1 -0
  254. package/dist/engine/models/backends/model2vec-worker.js +41 -0
  255. package/dist/engine/models/backends/model2vec-worker.js.map +1 -0
  256. package/dist/engine/models/backends/model2vec.d.ts +38 -0
  257. package/dist/engine/models/backends/model2vec.js +344 -0
  258. package/dist/engine/models/backends/model2vec.js.map +1 -0
  259. package/dist/engine/models/backends/qwen.d.ts +44 -0
  260. package/dist/engine/models/backends/qwen.js +411 -0
  261. package/dist/engine/models/backends/qwen.js.map +1 -0
  262. package/dist/engine/models/backends/transformers-js.d.ts +90 -0
  263. package/dist/engine/models/backends/transformers-js.js +411 -0
  264. package/dist/engine/models/backends/transformers-js.js.map +1 -0
  265. package/dist/engine/models/catalog.d.ts +490 -0
  266. package/dist/engine/models/catalog.js +522 -0
  267. package/dist/engine/models/catalog.js.map +1 -0
  268. package/dist/engine/models/download-progress.d.ts +16 -0
  269. package/dist/engine/models/download-progress.js +47 -0
  270. package/dist/engine/models/download-progress.js.map +1 -0
  271. package/dist/engine/models/embeddings.d.ts +73 -0
  272. package/dist/engine/models/embeddings.js +125 -0
  273. package/dist/engine/models/embeddings.js.map +1 -0
  274. package/dist/engine/models/factory.d.ts +2 -0
  275. package/dist/engine/models/factory.js +51 -0
  276. package/dist/engine/models/factory.js.map +1 -0
  277. package/dist/engine/models/index.d.ts +5 -0
  278. package/dist/engine/models/index.js +6 -0
  279. package/dist/engine/models/index.js.map +1 -0
  280. package/dist/engine/models/local-embedding-parallelism.d.ts +15 -0
  281. package/dist/engine/models/local-embedding-parallelism.js +63 -0
  282. package/dist/engine/models/local-embedding-parallelism.js.map +1 -0
  283. package/dist/engine/models/local-embedding-queue.d.ts +12 -0
  284. package/dist/engine/models/local-embedding-queue.js +65 -0
  285. package/dist/engine/models/local-embedding-queue.js.map +1 -0
  286. package/dist/engine/models/ranking.d.ts +19 -0
  287. package/dist/engine/models/ranking.js +2 -0
  288. package/dist/engine/models/ranking.js.map +1 -0
  289. package/dist/engine/models/resolution.d.ts +8 -0
  290. package/dist/engine/models/resolution.js +22 -0
  291. package/dist/engine/models/resolution.js.map +1 -0
  292. package/dist/engine/pipeline/indexing/index.d.ts +14 -0
  293. package/dist/engine/pipeline/indexing/index.js +1219 -0
  294. package/dist/engine/pipeline/indexing/index.js.map +1 -0
  295. package/dist/engine/pipeline/indexing/input-budget.d.ts +2 -0
  296. package/dist/engine/pipeline/indexing/input-budget.js +51 -0
  297. package/dist/engine/pipeline/indexing/input-budget.js.map +1 -0
  298. package/dist/engine/pipeline/indexing/root-paths.d.ts +7 -0
  299. package/dist/engine/pipeline/indexing/root-paths.js +148 -0
  300. package/dist/engine/pipeline/indexing/root-paths.js.map +1 -0
  301. package/dist/engine/pipeline/indexing/scanner/index.d.ts +14 -0
  302. package/dist/engine/pipeline/indexing/scanner/index.js +776 -0
  303. package/dist/engine/pipeline/indexing/scanner/index.js.map +1 -0
  304. package/dist/engine/pipeline/search/index.d.ts +12 -0
  305. package/dist/engine/pipeline/search/index.js +811 -0
  306. package/dist/engine/pipeline/search/index.js.map +1 -0
  307. package/dist/engine/service/index.d.ts +3 -0
  308. package/dist/engine/service/index.js +2 -0
  309. package/dist/engine/service/index.js.map +1 -0
  310. package/dist/engine/service/lexical.d.ts +28 -0
  311. package/dist/engine/service/lexical.js +446 -0
  312. package/dist/engine/service/lexical.js.map +1 -0
  313. package/dist/engine/service/root.d.ts +15 -0
  314. package/dist/engine/service/root.js +57 -0
  315. package/dist/engine/service/root.js.map +1 -0
  316. package/dist/engine/service/structure-enrichment.d.ts +8 -0
  317. package/dist/engine/service/structure-enrichment.js +178 -0
  318. package/dist/engine/service/structure-enrichment.js.map +1 -0
  319. package/dist/engine/service/types.d.ts +212 -0
  320. package/dist/engine/service/types.js +2 -0
  321. package/dist/engine/service/types.js.map +1 -0
  322. package/dist/engine/service/workspace-index.d.ts +26 -0
  323. package/dist/engine/service/workspace-index.js +157 -0
  324. package/dist/engine/service/workspace-index.js.map +1 -0
  325. package/dist/engine/service/zvec-grep.d.ts +15 -0
  326. package/dist/engine/service/zvec-grep.js +1520 -0
  327. package/dist/engine/service/zvec-grep.js.map +1 -0
  328. package/dist/engine/storage/index.d.ts +53 -0
  329. package/dist/engine/storage/index.js +3 -0
  330. package/dist/engine/storage/index.js.map +1 -0
  331. package/dist/engine/storage/layout.d.ts +10 -0
  332. package/dist/engine/storage/layout.js +29 -0
  333. package/dist/engine/storage/layout.js.map +1 -0
  334. package/dist/engine/storage/zvec.d.ts +4 -0
  335. package/dist/engine/storage/zvec.js +976 -0
  336. package/dist/engine/storage/zvec.js.map +1 -0
  337. package/dist/engine/types.d.ts +303 -0
  338. package/dist/engine/types.js +14 -0
  339. package/dist/engine/types.js.map +1 -0
  340. package/dist/engine/utils/atomic-file.d.ts +3 -0
  341. package/dist/engine/utils/atomic-file.js +39 -0
  342. package/dist/engine/utils/atomic-file.js.map +1 -0
  343. package/dist/engine/utils/daemon-lease.d.ts +17 -0
  344. package/dist/engine/utils/daemon-lease.js +175 -0
  345. package/dist/engine/utils/daemon-lease.js.map +1 -0
  346. package/dist/engine/utils/file-selection.d.ts +10 -0
  347. package/dist/engine/utils/file-selection.js +157 -0
  348. package/dist/engine/utils/file-selection.js.map +1 -0
  349. package/dist/engine/utils/glob.d.ts +9 -0
  350. package/dist/engine/utils/glob.js +208 -0
  351. package/dist/engine/utils/glob.js.map +1 -0
  352. package/dist/engine/utils/hash.d.ts +2 -0
  353. package/dist/engine/utils/hash.js +8 -0
  354. package/dist/engine/utils/hash.js.map +1 -0
  355. package/dist/engine/utils/json.d.ts +8 -0
  356. package/dist/engine/utils/json.js +83 -0
  357. package/dist/engine/utils/json.js.map +1 -0
  358. package/dist/engine/utils/lock.d.ts +19 -0
  359. package/dist/engine/utils/lock.js +254 -0
  360. package/dist/engine/utils/lock.js.map +1 -0
  361. package/dist/engine/utils/path.d.ts +4 -0
  362. package/dist/engine/utils/path.js +18 -0
  363. package/dist/engine/utils/path.js.map +1 -0
  364. package/dist/engine/utils/timing.d.ts +19 -0
  365. package/dist/engine/utils/timing.js +87 -0
  366. package/dist/engine/utils/timing.js.map +1 -0
  367. package/dist/index-progress.d.ts +10 -0
  368. package/dist/index-progress.js +159 -0
  369. package/dist/index-progress.js.map +1 -0
  370. package/dist/index.d.ts +6 -0
  371. package/dist/index.js +4 -0
  372. package/dist/index.js.map +1 -0
  373. package/dist/mcp/http-transport.d.ts +27 -0
  374. package/dist/mcp/http-transport.js +182 -0
  375. package/dist/mcp/http-transport.js.map +1 -0
  376. package/dist/mcp/input-normalization.d.ts +38 -0
  377. package/dist/mcp/input-normalization.js +104 -0
  378. package/dist/mcp/input-normalization.js.map +1 -0
  379. package/dist/mcp/progress-heartbeat.d.ts +17 -0
  380. package/dist/mcp/progress-heartbeat.js +46 -0
  381. package/dist/mcp/progress-heartbeat.js.map +1 -0
  382. package/dist/mcp/request-metadata.d.ts +2 -0
  383. package/dist/mcp/request-metadata.js +11 -0
  384. package/dist/mcp/request-metadata.js.map +1 -0
  385. package/dist/mcp/request-state.d.ts +40 -0
  386. package/dist/mcp/request-state.js +210 -0
  387. package/dist/mcp/request-state.js.map +1 -0
  388. package/dist/mcp/result-format.d.ts +13 -0
  389. package/dist/mcp/result-format.js +75 -0
  390. package/dist/mcp/result-format.js.map +1 -0
  391. package/dist/mcp/schemas.d.ts +668 -0
  392. package/dist/mcp/schemas.js +512 -0
  393. package/dist/mcp/schemas.js.map +1 -0
  394. package/dist/mcp/stdio-bridge.d.ts +15 -0
  395. package/dist/mcp/stdio-bridge.js +190 -0
  396. package/dist/mcp/stdio-bridge.js.map +1 -0
  397. package/dist/mcp/tools.d.ts +153 -0
  398. package/dist/mcp/tools.js +488 -0
  399. package/dist/mcp/tools.js.map +1 -0
  400. package/dist/mcp/toolset.d.ts +5 -0
  401. package/dist/mcp/toolset.js +12 -0
  402. package/dist/mcp/toolset.js.map +1 -0
  403. package/dist/observability/trace-context.d.ts +11 -0
  404. package/dist/observability/trace-context.js +138 -0
  405. package/dist/observability/trace-context.js.map +1 -0
  406. package/dist/prompts/zvec-grep-guidance.d.ts +2 -0
  407. package/dist/prompts/zvec-grep-guidance.js +9 -0
  408. package/dist/prompts/zvec-grep-guidance.js.map +1 -0
  409. package/docs/01-agents.md +217 -0
  410. package/docs/02-cli.md +259 -0
  411. package/docs/03-mcp.md +185 -0
  412. package/docs/04-pipeline.md +234 -0
  413. package/docs/05-architecture.md +86 -0
  414. package/docs/06-server.md +279 -0
  415. package/docs/07-embedding.md +227 -0
  416. package/docs/08-roadmap.md +85 -0
  417. package/docs/README.md +53 -0
  418. package/package.json +87 -0
@@ -0,0 +1,766 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import { mkdir, lstat, open, readFile, rename, rm, stat, } from "node:fs/promises";
4
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
5
+ import { writeJsonFile } from "../utils/json.js";
6
+ import { acquireModelArtifactCacheLock, } from "./artifact-cache-lock.js";
7
+ export class ArtifactDownloadError extends Error {
8
+ kind;
9
+ source;
10
+ artifact;
11
+ status;
12
+ fallbackAllowed;
13
+ constructor(message, kind, source, artifact, status, options) {
14
+ super(message, options);
15
+ this.kind = kind;
16
+ this.source = source;
17
+ this.artifact = artifact;
18
+ this.status = status;
19
+ this.name = "ArtifactDownloadError";
20
+ this.fallbackAllowed =
21
+ kind === "network" ||
22
+ kind === "timeout" ||
23
+ kind === "integrity" ||
24
+ (kind === "http" &&
25
+ status !== undefined &&
26
+ (status === 403 ||
27
+ status === 404 ||
28
+ status === 408 ||
29
+ status === 429 ||
30
+ (status >= 500 && status <= 599)));
31
+ }
32
+ }
33
+ export class ModelArtifactResolutionError extends AggregateError {
34
+ model;
35
+ primaryError;
36
+ fallbackError;
37
+ constructor(model, primaryError, fallbackError) {
38
+ super([primaryError, fallbackError], `Unable to download artifacts for ${model} from Hugging Face or ModelScope: ${primaryError instanceof Error ? primaryError.message : String(primaryError)}; ${fallbackError instanceof Error ? fallbackError.message : String(fallbackError)}`, { cause: fallbackError });
39
+ this.model = model;
40
+ this.primaryError = primaryError;
41
+ this.fallbackError = fallbackError;
42
+ this.name = "ModelArtifactResolutionError";
43
+ }
44
+ }
45
+ export function isFallbackEligibleArtifactError(error) {
46
+ return error instanceof ArtifactDownloadError && error.fallbackAllowed;
47
+ }
48
+ const DEFAULT_RESPONSE_HEADER_TIMEOUT_MS = 10_000;
49
+ const DEFAULT_READ_IDLE_TIMEOUT_MS = 30_000;
50
+ const DEFAULT_LOCK_POLL_MS = 250;
51
+ const DEFAULT_LOCK_STALE_MS = 10 * 60_000;
52
+ const DEFAULT_LOCK_HEARTBEAT_MS = 30_000;
53
+ const MANIFEST_VERSION = 1;
54
+ const defaultDependencies = {
55
+ fetch: (...arguments_) => globalThis.fetch(...arguments_),
56
+ setTimeout: (callback, milliseconds) => globalThis.setTimeout(callback, milliseconds),
57
+ clearTimeout: (handle) => globalThis.clearTimeout(handle),
58
+ now: () => Date.now(),
59
+ };
60
+ class DeadlineError extends Error {
61
+ phase;
62
+ constructor(phase) {
63
+ super(`Timed out waiting for ${phase}`);
64
+ this.phase = phase;
65
+ this.name = "DeadlineError";
66
+ }
67
+ }
68
+ /**
69
+ * Resolves a complete, integrity-checked local artifact snapshot.
70
+ *
71
+ * Cache lookup is performed for every source before any network request. Source
72
+ * order is always Hugging Face followed by ModelScope, independent of the input
73
+ * array order.
74
+ */
75
+ export async function resolveModelArtifacts(options) {
76
+ const normalized = normalizeOptions(options);
77
+ const manifests = new Map(normalized.sources.map((source) => [
78
+ source.kind,
79
+ createSourceManifest(normalized.model, source, normalized.artifacts),
80
+ ]));
81
+ // Check all caches first. In particular, a complete ModelScope snapshot must
82
+ // avoid a doomed Hugging Face network attempt.
83
+ for (const source of normalized.sources) {
84
+ const manifest = manifests.get(source.kind);
85
+ if (await validateSnapshot(normalized.model, source, normalized.artifacts, manifest)) {
86
+ await writeCompleteMarkerBestEffort(source, normalized.artifacts, manifest);
87
+ return resolvedResult(source, manifest);
88
+ }
89
+ }
90
+ let primaryError;
91
+ let hasPrimaryError = false;
92
+ let warned = false;
93
+ for (const [sourceIndex, source] of normalized.sources.entries()) {
94
+ const manifest = manifests.get(source.kind);
95
+ try {
96
+ await downloadSourceSnapshot(normalized, source, manifest);
97
+ return resolvedResult(source, manifest);
98
+ }
99
+ catch (error) {
100
+ if (sourceIndex === 0) {
101
+ primaryError = error;
102
+ hasPrimaryError = true;
103
+ }
104
+ const fallback = normalized.sources[sourceIndex + 1];
105
+ if (!fallback || !isFallbackEligibleArtifactError(error)) {
106
+ if (hasPrimaryError && sourceIndex > 0) {
107
+ throw new ModelArtifactResolutionError(normalized.model, primaryError, error);
108
+ }
109
+ throw error;
110
+ }
111
+ if (!warned) {
112
+ warned = true;
113
+ invokeFallbackCallback(normalized.onFallback, `Hugging Face download failed for ${normalized.model}; falling back to ModelScope.`, source, error);
114
+ }
115
+ }
116
+ }
117
+ // normalizeOptions guarantees at least one source, so this is unreachable.
118
+ throw new ArtifactDownloadError(`No artifact source is available for ${normalized.model}`, "invalid-input");
119
+ }
120
+ export function modelArtifactUrl(source, artifactPath) {
121
+ const base = source.kind === "huggingface"
122
+ ? "https://huggingface.co"
123
+ : "https://modelscope.cn/models";
124
+ return `${base}/${encodePath(source.repo)}/resolve/${encodeURIComponent(source.revision)}/${encodePath(artifactPath)}`;
125
+ }
126
+ function normalizeOptions(options) {
127
+ if (options.model.trim().length === 0) {
128
+ throw invalidInput("Model reference must not be empty");
129
+ }
130
+ if (options.artifacts.length === 0) {
131
+ throw invalidInput(`At least one artifact is required for ${options.model}`);
132
+ }
133
+ const sourceKinds = new Set();
134
+ for (const source of options.sources) {
135
+ if (sourceKinds.has(source.kind)) {
136
+ throw invalidInput(`Duplicate artifact source '${source.kind}'`);
137
+ }
138
+ sourceKinds.add(source.kind);
139
+ validateSource(source);
140
+ }
141
+ if (sourceKinds.size === 0) {
142
+ throw invalidInput(`At least one artifact source is required for ${options.model}`);
143
+ }
144
+ const artifactPaths = new Set();
145
+ for (const artifact of options.artifacts) {
146
+ validateRelativePath(artifact.path, "artifact path");
147
+ if (artifactPaths.has(artifact.path)) {
148
+ throw invalidInput(`Duplicate artifact path '${artifact.path}'`);
149
+ }
150
+ artifactPaths.add(artifact.path);
151
+ if (!Number.isSafeInteger(artifact.size) || artifact.size < 0) {
152
+ throw invalidInput(`Invalid size for artifact '${artifact.path}'`);
153
+ }
154
+ if (!/^[a-f\d]{64}$/iu.test(artifact.sha256)) {
155
+ throw invalidInput(`Invalid SHA-256 for artifact '${artifact.path}'`);
156
+ }
157
+ }
158
+ for (const source of options.sources) {
159
+ for (const artifactPath of Object.keys(source.localPaths ?? {})) {
160
+ if (!artifactPaths.has(artifactPath)) {
161
+ throw invalidInput(`${source.kind} local path mapping references unknown artifact '${artifactPath}'`);
162
+ }
163
+ }
164
+ }
165
+ const dependencies = { ...defaultDependencies, ...options.dependencies };
166
+ const responseHeaderMs = options.timeouts?.responseHeaderMs ?? DEFAULT_RESPONSE_HEADER_TIMEOUT_MS;
167
+ const readIdleMs = options.timeouts?.readIdleMs ?? DEFAULT_READ_IDLE_TIMEOUT_MS;
168
+ const lockPollMs = options.lock?.pollMs ?? DEFAULT_LOCK_POLL_MS;
169
+ const lockStaleMs = options.lock?.staleMs ?? DEFAULT_LOCK_STALE_MS;
170
+ const lockHeartbeatMs = options.lock?.heartbeatMs ?? DEFAULT_LOCK_HEARTBEAT_MS;
171
+ for (const [name, value] of [
172
+ ["responseHeaderMs", responseHeaderMs],
173
+ ["readIdleMs", readIdleMs],
174
+ ["lockPollMs", lockPollMs],
175
+ ["lockStaleMs", lockStaleMs],
176
+ ["lockHeartbeatMs", lockHeartbeatMs],
177
+ ]) {
178
+ if (!Number.isFinite(value) || value <= 0) {
179
+ throw invalidInput(`${name} must be a positive number`);
180
+ }
181
+ }
182
+ if (lockHeartbeatMs >= lockStaleMs) {
183
+ throw invalidInput("lock heartbeat must be shorter than its stale timeout");
184
+ }
185
+ const orderedSources = [...options.sources].sort((left, right) => sourceOrder(left.kind) - sourceOrder(right.kind));
186
+ return {
187
+ model: options.model,
188
+ sources: orderedSources,
189
+ artifacts: options.artifacts.map((artifact) => ({
190
+ ...artifact,
191
+ sha256: artifact.sha256.toLowerCase(),
192
+ })),
193
+ onProgress: options.onProgress,
194
+ onDownloadPlan: options.onDownloadPlan,
195
+ onFallback: options.onFallback,
196
+ dependencies,
197
+ responseHeaderMs,
198
+ readIdleMs,
199
+ lockPollMs,
200
+ lockStaleMs,
201
+ lockHeartbeatMs,
202
+ };
203
+ }
204
+ function validateSource(source) {
205
+ if (source.kind !== "huggingface" && source.kind !== "modelscope") {
206
+ throw invalidInput(`Unknown artifact source '${String(source.kind)}'`);
207
+ }
208
+ if (source.repo.trim().length === 0 || source.revision.trim().length === 0) {
209
+ throw invalidInput(`${source.kind} repo and revision must not be empty`);
210
+ }
211
+ validateRelativePath(source.repo, "repository");
212
+ if (source.revision.includes("\0") ||
213
+ source.revision === "." ||
214
+ source.revision === "..") {
215
+ throw invalidInput(`Invalid ${source.kind} revision`);
216
+ }
217
+ if (source.cacheDirectory.trim().length === 0 ||
218
+ source.cacheDirectory.includes("\0")) {
219
+ throw invalidInput(`${source.kind} cache directory must not be empty`);
220
+ }
221
+ const localPaths = new Set();
222
+ for (const [artifact, localPath] of Object.entries(source.localPaths ?? {})) {
223
+ validateRelativePath(artifact, "artifact mapping key");
224
+ validateRelativePath(localPath, "local artifact path");
225
+ if (localPaths.has(localPath)) {
226
+ throw invalidInput(`Multiple ${source.kind} artifacts map to '${localPath}'`);
227
+ }
228
+ localPaths.add(localPath);
229
+ }
230
+ }
231
+ function validateRelativePath(path, label) {
232
+ const normalized = path.replaceAll("\\", "/");
233
+ if (normalized.length === 0 ||
234
+ normalized.includes("\0") ||
235
+ isAbsolute(path) ||
236
+ normalized.startsWith("/") ||
237
+ normalized
238
+ .split("/")
239
+ .some((segment) => segment === "" || segment === "." || segment === "..")) {
240
+ throw invalidInput(`Invalid ${label} '${path}'`);
241
+ }
242
+ }
243
+ function invalidInput(message) {
244
+ return new ArtifactDownloadError(message, "invalid-input");
245
+ }
246
+ function sourceOrder(kind) {
247
+ return kind === "huggingface" ? 0 : 1;
248
+ }
249
+ function createSourceManifest(model, source, artifacts) {
250
+ const localPaths = {};
251
+ const seenPaths = new Set();
252
+ for (const artifact of artifacts) {
253
+ const localPath = source.localPaths?.[artifact.path] ?? artifact.path;
254
+ validateRelativePath(localPath, "local artifact path");
255
+ if (seenPaths.has(localPath)) {
256
+ throw invalidInput(`Multiple ${source.kind} artifacts map to '${localPath}'`);
257
+ }
258
+ seenPaths.add(localPath);
259
+ localPaths[artifact.path] = localPath;
260
+ }
261
+ const serialized = JSON.stringify({
262
+ version: MANIFEST_VERSION,
263
+ model,
264
+ source: {
265
+ kind: source.kind,
266
+ repo: source.repo,
267
+ revision: source.revision,
268
+ },
269
+ artifacts: artifacts.map((artifact) => ({
270
+ path: artifact.path,
271
+ localPath: localPaths[artifact.path],
272
+ size: artifact.size,
273
+ sha256: artifact.sha256.toLowerCase(),
274
+ })),
275
+ });
276
+ const fingerprint = createHash("sha256")
277
+ .update(serialized)
278
+ .digest("hex")
279
+ .slice(0, 24);
280
+ return {
281
+ fingerprint,
282
+ markerPath: join(source.cacheDirectory, `.zvec-grep-artifacts-${fingerprint}.complete`),
283
+ lockPath: join(source.cacheDirectory, `.zvec-grep-artifacts-${fingerprint}.lock`),
284
+ localPaths,
285
+ };
286
+ }
287
+ function resolvedResult(source, manifest) {
288
+ return {
289
+ source,
290
+ directory: resolve(source.cacheDirectory),
291
+ paths: Object.fromEntries(Object.entries(manifest.localPaths).map(([artifact, localPath]) => [
292
+ artifact,
293
+ safeLocalPath(source.cacheDirectory, localPath),
294
+ ])),
295
+ };
296
+ }
297
+ async function validateSnapshot(model, source, artifacts, manifest) {
298
+ if (await hasValidCompleteMarker(source, artifacts, manifest)) {
299
+ return true;
300
+ }
301
+ for (const artifact of artifacts) {
302
+ if (!(await validateArtifact(model, source, artifact, manifest))) {
303
+ return false;
304
+ }
305
+ }
306
+ return true;
307
+ }
308
+ async function hasValidCompleteMarker(source, artifacts, manifest) {
309
+ try {
310
+ let marker;
311
+ try {
312
+ marker = JSON.parse(await readFile(manifest.markerPath, "utf8"));
313
+ }
314
+ catch (error) {
315
+ if (isMissingFileError(error)) {
316
+ return false;
317
+ }
318
+ if (error instanceof SyntaxError) {
319
+ return false;
320
+ }
321
+ throw error;
322
+ }
323
+ if (!isRecord(marker) ||
324
+ marker.version !== MANIFEST_VERSION ||
325
+ marker.fingerprint !== manifest.fingerprint ||
326
+ !isRecord(marker.files)) {
327
+ return false;
328
+ }
329
+ for (const artifact of artifacts) {
330
+ const recorded = marker.files[artifact.path];
331
+ if (!isRecord(recorded)) {
332
+ return false;
333
+ }
334
+ const stats = await stat(safeLocalPath(source.cacheDirectory, manifest.localPaths[artifact.path]));
335
+ if (!stats.isFile() ||
336
+ stats.size !== artifact.size ||
337
+ stats.size !== recorded.size ||
338
+ stats.mtimeMs !== recorded.mtimeMs ||
339
+ stats.ctimeMs !== recorded.ctimeMs) {
340
+ return false;
341
+ }
342
+ }
343
+ return true;
344
+ }
345
+ catch (error) {
346
+ if (isMissingFileError(error)) {
347
+ return false;
348
+ }
349
+ throw filesystemError(`Unable to inspect ${source.kind} artifact completion marker`, source, undefined, error);
350
+ }
351
+ }
352
+ async function validateArtifact(model, source, artifact, manifest) {
353
+ const localPath = safeLocalPath(source.cacheDirectory, manifest.localPaths[artifact.path]);
354
+ try {
355
+ const stats = await stat(localPath);
356
+ if (!stats.isFile() || stats.size !== artifact.size) {
357
+ return false;
358
+ }
359
+ const hash = createHash("sha256");
360
+ for await (const chunk of createReadStream(localPath)) {
361
+ hash.update(chunk);
362
+ }
363
+ return hash.digest("hex") === artifact.sha256.toLowerCase();
364
+ }
365
+ catch (error) {
366
+ if (isMissingFileError(error)) {
367
+ return false;
368
+ }
369
+ throw filesystemError(`Unable to validate cached artifact '${artifact.path}' for ${model}`, source, artifact.path, error);
370
+ }
371
+ }
372
+ async function downloadSourceSnapshot(options, source, manifest) {
373
+ try {
374
+ await mkdir(source.cacheDirectory, { recursive: true });
375
+ const lock = await acquireModelArtifactCacheLock(manifest.lockPath, {
376
+ pollMs: options.lockPollMs,
377
+ staleMs: options.lockStaleMs,
378
+ heartbeatMs: options.lockHeartbeatMs,
379
+ dependencies: options.dependencies,
380
+ });
381
+ try {
382
+ // Another process may have completed the snapshot while we waited.
383
+ if (await hasValidCompleteMarker(source, options.artifacts, manifest)) {
384
+ return;
385
+ }
386
+ const missingArtifacts = [];
387
+ for (const artifact of options.artifacts) {
388
+ if (!(await validateArtifact(options.model, source, artifact, manifest))) {
389
+ missingArtifacts.push(artifact);
390
+ }
391
+ }
392
+ invokeDownloadPlanCallback(options, source, missingArtifacts);
393
+ for (const artifact of missingArtifacts) {
394
+ await downloadArtifact(options, source, artifact, manifest, lock);
395
+ }
396
+ await lock.assertOwned();
397
+ await writeCompleteMarker(source, manifest);
398
+ }
399
+ finally {
400
+ await lock.release();
401
+ }
402
+ }
403
+ catch (error) {
404
+ if (error instanceof ArtifactDownloadError) {
405
+ throw error;
406
+ }
407
+ throw filesystemError(`Unable to prepare ${source.kind} model cache`, source, undefined, error);
408
+ }
409
+ }
410
+ async function downloadArtifact(options, source, artifact, manifest, lock) {
411
+ const destination = safeLocalPath(source.cacheDirectory, manifest.localPaths[artifact.path]);
412
+ const partialPath = `${destination}.part-${process.pid}-${randomUUID()}`;
413
+ const url = modelArtifactUrl(source, artifact.path);
414
+ let originalDestination;
415
+ let file;
416
+ let reader;
417
+ const controller = new AbortController();
418
+ try {
419
+ try {
420
+ await mkdir(dirname(destination), { recursive: true });
421
+ originalDestination = await inspectFileIdentity(destination);
422
+ file = await open(partialPath, "wx");
423
+ }
424
+ catch (error) {
425
+ throw filesystemError(`Unable to prepare local artifact '${artifact.path}'`, source, artifact.path, error);
426
+ }
427
+ invokeProgressCallback(options, source, artifact, 0);
428
+ let response;
429
+ try {
430
+ response = await withDeadline(Promise.resolve(options.dependencies.fetch(url, {
431
+ redirect: "follow",
432
+ signal: controller.signal,
433
+ })), options.responseHeaderMs, "response headers", controller, options.dependencies);
434
+ }
435
+ catch (error) {
436
+ throw requestError(`Unable to request model artifact from ${source.kind}`, source, artifact.path, error, controller.signal);
437
+ }
438
+ if (!response.ok) {
439
+ await response.body?.cancel().catch(() => undefined);
440
+ throw new ArtifactDownloadError(`HTTP ${response.status} ${response.statusText} while downloading model from ${source.kind}`, "http", source.kind, artifact.path, response.status);
441
+ }
442
+ if (!response.body) {
443
+ throw new ArtifactDownloadError(`Response body is missing for '${artifact.path}' from ${source.kind}`, "network", source.kind, artifact.path);
444
+ }
445
+ reader = response.body.getReader();
446
+ const hash = createHash("sha256");
447
+ let downloadedBytes = 0;
448
+ while (true) {
449
+ let result;
450
+ try {
451
+ result = await withDeadline(readUntilData(reader), options.readIdleMs, "network read", controller, options.dependencies);
452
+ }
453
+ catch (error) {
454
+ throw requestError(`Model download stream failed from ${source.kind}`, source, artifact.path, error, controller.signal);
455
+ }
456
+ if (result.done) {
457
+ break;
458
+ }
459
+ try {
460
+ await writeAll(file, result.value);
461
+ }
462
+ catch (error) {
463
+ throw filesystemError(`Unable to write local artifact '${artifact.path}'`, source, artifact.path, error);
464
+ }
465
+ hash.update(result.value);
466
+ downloadedBytes += result.value.byteLength;
467
+ if (downloadedBytes > artifact.size) {
468
+ throw new ArtifactDownloadError(`Integrity check failed for '${artifact.path}' from ${source.kind}: response exceeded the expected ${artifact.size} bytes`, "integrity", source.kind, artifact.path);
469
+ }
470
+ await lock.touch();
471
+ invokeProgressCallback(options, source, artifact, downloadedBytes);
472
+ }
473
+ try {
474
+ await file.sync();
475
+ await file.close();
476
+ file = undefined;
477
+ }
478
+ catch (error) {
479
+ throw filesystemError(`Unable to finish local artifact '${artifact.path}'`, source, artifact.path, error);
480
+ }
481
+ const actualSha256 = hash.digest("hex");
482
+ if (downloadedBytes !== artifact.size ||
483
+ actualSha256 !== artifact.sha256.toLowerCase()) {
484
+ throw new ArtifactDownloadError(`Integrity check failed for '${artifact.path}' from ${source.kind}: expected ${artifact.size} bytes/${artifact.sha256.toLowerCase()}, received ${downloadedBytes} bytes/${actualSha256}`, "integrity", source.kind, artifact.path);
485
+ }
486
+ await installDownloadedArtifact(partialPath, destination, originalDestination, options.model, source, artifact, manifest, lock);
487
+ }
488
+ finally {
489
+ controller.abort();
490
+ await reader?.cancel().catch(() => undefined);
491
+ await file?.close().catch(() => undefined);
492
+ await rm(partialPath, { force: true }).catch(() => undefined);
493
+ }
494
+ }
495
+ async function writeAll(file, bytes) {
496
+ let offset = 0;
497
+ while (offset < bytes.byteLength) {
498
+ const { bytesWritten } = await file.write(bytes, offset, bytes.byteLength - offset, null);
499
+ if (bytesWritten === 0) {
500
+ throw new Error("File write made no progress");
501
+ }
502
+ offset += bytesWritten;
503
+ }
504
+ }
505
+ async function readUntilData(reader) {
506
+ while (true) {
507
+ const result = await reader.read();
508
+ if (result.done || result.value.byteLength > 0) {
509
+ return result;
510
+ }
511
+ }
512
+ }
513
+ async function installDownloadedArtifact(partialPath, destination, originalDestination, model, source, artifact, manifest, lock) {
514
+ try {
515
+ await lock.assertOwned();
516
+ const currentDestination = await inspectFileIdentity(destination);
517
+ if (!sameFileIdentity(originalDestination, currentDestination)) {
518
+ if (await validateArtifact(model, source, artifact, manifest)) {
519
+ return;
520
+ }
521
+ throw new Error("Artifact destination changed concurrently while downloading");
522
+ }
523
+ if (currentDestination && !currentDestination.replaceable) {
524
+ throw new Error(`Refusing to replace non-file destination '${destination}'`);
525
+ }
526
+ // All downloader writers use the snapshot lock. POSIX rename replaces the
527
+ // destination atomically. Windows rejects that operation when the existing
528
+ // file is open, so preserve the old entry under a unique name while the
529
+ // verified replacement is installed.
530
+ try {
531
+ await rename(partialPath, destination);
532
+ }
533
+ catch (error) {
534
+ if (process.platform !== "win32" ||
535
+ !currentDestination ||
536
+ !isWindowsRenameReplacementError(error)) {
537
+ throw error;
538
+ }
539
+ await replaceDownloadedArtifactOnWindows(partialPath, destination, currentDestination, lock);
540
+ }
541
+ }
542
+ catch (error) {
543
+ if (error instanceof ArtifactDownloadError) {
544
+ throw error;
545
+ }
546
+ throw filesystemError(`Unable to install local artifact '${artifact.path}'`, source, artifact.path, error);
547
+ }
548
+ }
549
+ async function replaceDownloadedArtifactOnWindows(partialPath, destination, expectedDestination, lock) {
550
+ await lock.assertOwned();
551
+ const currentDestination = await inspectFileIdentity(destination);
552
+ if (!sameFileIdentity(expectedDestination, currentDestination)) {
553
+ throw new Error("Artifact destination changed concurrently while replacing");
554
+ }
555
+ const displacedPath = `${destination}.replaced-${process.pid}-${randomUUID()}`;
556
+ await rename(destination, displacedPath);
557
+ let replacementInstalled = false;
558
+ try {
559
+ await lock.assertOwned();
560
+ if ((await inspectFileIdentity(destination)) !== undefined) {
561
+ throw new Error("Artifact destination was recreated concurrently while replacing");
562
+ }
563
+ await rename(partialPath, destination);
564
+ replacementInstalled = true;
565
+ }
566
+ catch (error) {
567
+ if ((await inspectFileIdentity(destination)) === undefined) {
568
+ try {
569
+ await rename(displacedPath, destination);
570
+ }
571
+ catch (restoreError) {
572
+ throw new AggregateError([error, restoreError], "Unable to install or restore the local artifact", { cause: restoreError });
573
+ }
574
+ }
575
+ throw error;
576
+ }
577
+ finally {
578
+ if (replacementInstalled) {
579
+ await rm(displacedPath, { force: true });
580
+ }
581
+ }
582
+ }
583
+ function isWindowsRenameReplacementError(error) {
584
+ const code = error?.code;
585
+ return code === "EACCES" || code === "EEXIST" || code === "EPERM";
586
+ }
587
+ async function writeCompleteMarker(source, manifest) {
588
+ try {
589
+ const files = Object.fromEntries(await Promise.all(Object.entries(manifest.localPaths).map(async ([artifactPath, localPath]) => {
590
+ const stats = await stat(safeLocalPath(source.cacheDirectory, localPath));
591
+ if (!stats.isFile()) {
592
+ throw new Error(`Artifact '${artifactPath}' is not a file`);
593
+ }
594
+ return [
595
+ artifactPath,
596
+ {
597
+ size: stats.size,
598
+ mtimeMs: stats.mtimeMs,
599
+ ctimeMs: stats.ctimeMs,
600
+ },
601
+ ];
602
+ })));
603
+ const marker = {
604
+ version: MANIFEST_VERSION,
605
+ fingerprint: manifest.fingerprint,
606
+ files,
607
+ };
608
+ await writeJsonFile(manifest.markerPath, marker);
609
+ }
610
+ catch (error) {
611
+ throw filesystemError(`Unable to record completed ${source.kind} model snapshot`, source, undefined, error);
612
+ }
613
+ }
614
+ async function writeCompleteMarkerBestEffort(source, artifacts, manifest) {
615
+ try {
616
+ if (await hasValidCompleteMarker(source, artifacts, manifest)) {
617
+ return;
618
+ }
619
+ await writeCompleteMarker(source, manifest);
620
+ }
621
+ catch {
622
+ // A complete marker is only a hashing optimization. A valid read-only cache
623
+ // remains usable even when metadata cannot be written beside it.
624
+ }
625
+ }
626
+ async function inspectFileIdentity(path) {
627
+ try {
628
+ return fileIdentity(await lstat(path));
629
+ }
630
+ catch (error) {
631
+ if (isMissingFileError(error)) {
632
+ return undefined;
633
+ }
634
+ throw error;
635
+ }
636
+ }
637
+ function fileIdentity(stats) {
638
+ return {
639
+ device: stats.dev,
640
+ inode: stats.ino,
641
+ mode: stats.mode,
642
+ size: stats.size,
643
+ mtimeMs: stats.mtimeMs,
644
+ ctimeMs: stats.ctimeMs,
645
+ replaceable: stats.isFile() || stats.isSymbolicLink(),
646
+ };
647
+ }
648
+ function sameFileIdentity(left, right) {
649
+ return (left === right ||
650
+ (left !== undefined &&
651
+ right !== undefined &&
652
+ left.device === right.device &&
653
+ left.inode === right.inode &&
654
+ left.mode === right.mode &&
655
+ left.size === right.size &&
656
+ left.mtimeMs === right.mtimeMs &&
657
+ left.ctimeMs === right.ctimeMs &&
658
+ left.replaceable === right.replaceable));
659
+ }
660
+ function invokeDownloadPlanCallback(options, source, artifacts) {
661
+ try {
662
+ options.onDownloadPlan?.(artifacts);
663
+ }
664
+ catch (error) {
665
+ throw new ArtifactDownloadError(`Model download plan callback failed for ${options.model}`, "callback", source.kind, undefined, undefined, { cause: error });
666
+ }
667
+ }
668
+ function invokeProgressCallback(options, source, artifact, downloadedBytes) {
669
+ try {
670
+ options.onProgress?.({
671
+ model: options.model,
672
+ source: source.kind,
673
+ artifact: artifact.path,
674
+ downloadedBytes,
675
+ totalBytes: artifact.size,
676
+ });
677
+ }
678
+ catch (error) {
679
+ throw new ArtifactDownloadError(`Artifact progress callback failed for ${options.model}`, "callback", source.kind, artifact.path, undefined, { cause: error });
680
+ }
681
+ }
682
+ function invokeFallbackCallback(callback, message, source, cause) {
683
+ try {
684
+ callback?.(message);
685
+ }
686
+ catch (error) {
687
+ throw new ArtifactDownloadError("Artifact fallback warning callback failed", "callback", source.kind, undefined, undefined, { cause: new AggregateError([cause, error]) });
688
+ }
689
+ }
690
+ async function withDeadline(promise, timeoutMs, phase, controller, dependencies) {
691
+ let timer;
692
+ const timeout = new Promise((_resolve, reject) => {
693
+ timer = dependencies.setTimeout(() => {
694
+ const error = new DeadlineError(phase);
695
+ reject(error);
696
+ controller.abort(error);
697
+ }, timeoutMs);
698
+ });
699
+ try {
700
+ return await Promise.race([promise, timeout]);
701
+ }
702
+ finally {
703
+ if (timer !== undefined) {
704
+ dependencies.clearTimeout(timer);
705
+ }
706
+ }
707
+ }
708
+ function requestError(message, source, artifact, error, signal) {
709
+ if (error instanceof ArtifactDownloadError) {
710
+ return error;
711
+ }
712
+ const deadlineError = error instanceof DeadlineError
713
+ ? error
714
+ : signal?.reason instanceof DeadlineError
715
+ ? signal.reason
716
+ : undefined;
717
+ if (deadlineError) {
718
+ return new ArtifactDownloadError(`${message}: ${deadlineError.message}`, "timeout", source.kind, artifact, undefined, { cause: deadlineError });
719
+ }
720
+ if (isAbortError(error)) {
721
+ return new ArtifactDownloadError(`${message}: request was aborted`, "aborted", source.kind, artifact, undefined, { cause: error });
722
+ }
723
+ return new ArtifactDownloadError(`${message}: ${error instanceof Error ? error.message : String(error)}`, "network", source.kind, artifact, undefined, { cause: error });
724
+ }
725
+ function filesystemError(message, source, artifact, cause) {
726
+ if (cause instanceof ArtifactDownloadError) {
727
+ return cause;
728
+ }
729
+ return new ArtifactDownloadError(message, "filesystem", source.kind, artifact, undefined, { cause });
730
+ }
731
+ function isAbortError(error) {
732
+ return error instanceof DOMException
733
+ ? error.name === "AbortError"
734
+ : error instanceof Error && error.name === "AbortError";
735
+ }
736
+ function isRecord(value) {
737
+ return typeof value === "object" && value !== null && !Array.isArray(value);
738
+ }
739
+ function isMissingFileError(error) {
740
+ return isErrorCode(error, "ENOENT");
741
+ }
742
+ function isErrorCode(error, code) {
743
+ return (typeof error === "object" &&
744
+ error !== null &&
745
+ "code" in error &&
746
+ error.code === code);
747
+ }
748
+ function safeLocalPath(cacheDirectory, localPath) {
749
+ const root = resolve(cacheDirectory);
750
+ const candidate = resolve(root, localPath);
751
+ const relativePath = relative(root, candidate);
752
+ if (relativePath === ".." ||
753
+ relativePath.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ||
754
+ isAbsolute(relativePath)) {
755
+ throw invalidInput(`Local artifact path escapes cache: '${localPath}'`);
756
+ }
757
+ return candidate;
758
+ }
759
+ function encodePath(path) {
760
+ return path
761
+ .replaceAll("\\", "/")
762
+ .split("/")
763
+ .map((segment) => encodeURIComponent(segment))
764
+ .join("/");
765
+ }
766
+ //# sourceMappingURL=artifact-downloader.js.map