@asterxsk/kiln 0.1.0 → 0.3.0

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 (491) hide show
  1. package/README.md +155 -170
  2. package/agent/AGENTS.md +67 -67
  3. package/agent/README.md +5 -5
  4. package/agent/extensions/ask-user/index.ts +418 -418
  5. package/agent/extensions/ask-user/install.ps1 +4 -0
  6. package/agent/extensions/ask-user/install.sh +3 -0
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/install.ps1 +4 -0
  14. package/agent/extensions/background-terminals/install.sh +3 -0
  15. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  16. package/agent/extensions/background-terminals/output.test.ts +109 -109
  17. package/agent/extensions/background-terminals/package-lock.json +769 -769
  18. package/agent/extensions/background-terminals/package.json +17 -17
  19. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  20. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  21. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  22. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  23. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  24. package/agent/extensions/background-terminals/src/output.ts +84 -84
  25. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  26. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  27. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  28. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  29. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  30. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  31. package/agent/extensions/destructive/install.ps1 +4 -0
  32. package/agent/extensions/destructive/install.sh +3 -0
  33. package/agent/extensions/file-search/index.spec.ts +443 -443
  34. package/agent/extensions/file-search/index.ts +459 -459
  35. package/agent/extensions/file-search/install.ps1 +4 -0
  36. package/agent/extensions/file-search/install.sh +3 -0
  37. package/agent/extensions/file-search/package-lock.json +2253 -2253
  38. package/agent/extensions/file-search/package.json +23 -23
  39. package/agent/extensions/file-search/src/args.ts +122 -122
  40. package/agent/extensions/file-search/src/binaries.ts +422 -422
  41. package/agent/extensions/file-search/src/output.ts +126 -126
  42. package/agent/extensions/file-search/src/process.ts +146 -146
  43. package/agent/extensions/file-search/src/prompt.ts +52 -52
  44. package/agent/extensions/file-search/tsconfig.json +7 -7
  45. package/agent/extensions/goal/install.ps1 +4 -0
  46. package/agent/extensions/goal/install.sh +3 -0
  47. package/agent/extensions/herdr-agent-state.ts +257 -0
  48. package/agent/extensions/kiln-update/README.md +25 -0
  49. package/agent/extensions/kiln-update/index.ts +99 -0
  50. package/agent/extensions/kiln-update/install.ps1 +27 -0
  51. package/agent/extensions/kiln-update/install.sh +24 -0
  52. package/agent/extensions/modelconf/PLAN.md +915 -915
  53. package/agent/extensions/modelconf/index.ts +296 -296
  54. package/agent/extensions/modelconf/install.ps1 +4 -0
  55. package/agent/extensions/modelconf/install.sh +3 -0
  56. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  57. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  58. package/agent/extensions/pi-web-access/LICENSE +21 -21
  59. package/agent/extensions/pi-web-access/README.md +470 -470
  60. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  61. package/agent/extensions/pi-web-access/activity.ts +101 -101
  62. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  63. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  64. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  65. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  66. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  67. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  68. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  69. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  70. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  71. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  72. package/agent/extensions/pi-web-access/exa.ts +526 -526
  73. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  74. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  75. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  76. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  77. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  78. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  79. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  80. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  81. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  82. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  83. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  84. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  85. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  86. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  87. package/agent/extensions/pi-web-access/package.json +64 -64
  88. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  89. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  90. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  91. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  92. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  93. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  94. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  95. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  96. package/agent/extensions/pi-web-access/storage.ts +521 -521
  97. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  98. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  99. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  100. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  101. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  102. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  103. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  104. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  105. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  106. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  107. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  108. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  109. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  110. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  111. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  112. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  113. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  114. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  115. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  116. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  117. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  118. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  119. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  120. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  121. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  122. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  123. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  124. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  125. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  126. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  127. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  128. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  129. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  130. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  131. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  132. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  133. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  134. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  135. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  136. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  137. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  138. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  139. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  140. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  141. package/agent/extensions/pi-web-access/utils.ts +451 -451
  142. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  143. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  144. package/agent/extensions/shared/activity-status.ts +31 -31
  145. package/agent/extensions/shared/child-session.test.ts +270 -270
  146. package/agent/extensions/shared/child-session.ts +148 -148
  147. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  148. package/agent/extensions/shared/context-utilization.ts +47 -47
  149. package/agent/extensions/shared/dashboard-state.ts +99 -99
  150. package/agent/extensions/shared/install.ps1 +4 -0
  151. package/agent/extensions/shared/install.sh +3 -0
  152. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  153. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  154. package/agent/extensions/skillsconf/install.ps1 +4 -0
  155. package/agent/extensions/skillsconf/install.sh +3 -0
  156. package/agent/extensions/statusline/index.ts +282 -0
  157. package/agent/extensions/statusline/install.ps1 +27 -0
  158. package/agent/extensions/statusline/install.sh +24 -0
  159. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  160. package/agent/extensions/subagents/claude.test.ts +119 -119
  161. package/agent/extensions/subagents/codex.test.ts +102 -102
  162. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  163. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  164. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  165. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  166. package/agent/extensions/subagents/index.ts +779 -779
  167. package/agent/extensions/subagents/install.ps1 +4 -0
  168. package/agent/extensions/subagents/install.sh +3 -0
  169. package/agent/extensions/subagents/manager.test.ts +276 -276
  170. package/agent/extensions/subagents/package-lock.json +2244 -2244
  171. package/agent/extensions/subagents/package.json +19 -19
  172. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  173. package/agent/extensions/subagents/src/backend.ts +73 -73
  174. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  175. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  176. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  177. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  178. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  179. package/agent/extensions/subagents/src/domain.ts +253 -253
  180. package/agent/extensions/subagents/src/format.ts +74 -74
  181. package/agent/extensions/subagents/src/manager.ts +736 -736
  182. package/agent/extensions/subagents/src/prompt.ts +92 -92
  183. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  184. package/agent/extensions/subagents/src/runtime.ts +53 -53
  185. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  186. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  187. package/agent/extensions/subagents/takeover.test.ts +29 -29
  188. package/agent/extensions/subagents/tsconfig.json +7 -7
  189. package/agent/extensions/taste/install.ps1 +4 -0
  190. package/agent/extensions/taste/install.sh +3 -0
  191. package/agent/extensions/todo/AGENTS.md +38 -38
  192. package/agent/extensions/todo/LICENSE +21 -21
  193. package/agent/extensions/todo/config.ts +55 -55
  194. package/agent/extensions/todo/index.ts +151 -151
  195. package/agent/extensions/todo/install.ps1 +4 -0
  196. package/agent/extensions/todo/install.sh +3 -0
  197. package/agent/extensions/todo/locales/de.json +17 -17
  198. package/agent/extensions/todo/locales/en.json +15 -15
  199. package/agent/extensions/todo/locales/es.json +17 -17
  200. package/agent/extensions/todo/locales/fr.json +17 -17
  201. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  202. package/agent/extensions/todo/locales/pt.json +17 -17
  203. package/agent/extensions/todo/locales/ru.json +17 -17
  204. package/agent/extensions/todo/locales/uk.json +17 -17
  205. package/agent/extensions/todo/locales/zh.json +17 -17
  206. package/agent/extensions/todo/package-lock.json +3358 -3358
  207. package/agent/extensions/todo/package.json +67 -67
  208. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  209. package/agent/extensions/todo/state/invariants.ts +20 -20
  210. package/agent/extensions/todo/state/replay.ts +38 -38
  211. package/agent/extensions/todo/state/selectors.ts +107 -107
  212. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  213. package/agent/extensions/todo/state/state.ts +18 -18
  214. package/agent/extensions/todo/state/store.ts +82 -82
  215. package/agent/extensions/todo/state/task-graph.ts +57 -57
  216. package/agent/extensions/todo/todo-overlay.ts +200 -200
  217. package/agent/extensions/todo/todo.ts +155 -155
  218. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  219. package/agent/extensions/todo/tool/types.ts +206 -206
  220. package/agent/extensions/todo/view/format.ts +177 -177
  221. package/agent/extensions/trim-context/install.ps1 +4 -0
  222. package/agent/extensions/trim-context/install.sh +3 -0
  223. package/agent/keybindings.json +7 -7
  224. package/agent/version.txt +1 -0
  225. package/agent.bak.20260905-190020/AGENTS.md +67 -0
  226. package/agent.bak.20260905-190020/README.md +5 -0
  227. package/agent.bak.20260905-190020/extensions/ask-user/index.ts +418 -0
  228. package/agent.bak.20260905-190020/extensions/ask-user/package-lock.json +769 -0
  229. package/agent.bak.20260905-190020/extensions/ask-user/package.json +19 -0
  230. package/agent.bak.20260905-190020/extensions/ask-user/prompt.ts +45 -0
  231. package/agent.bak.20260905-190020/extensions/ask-user/tsconfig.json +7 -0
  232. package/agent.bak.20260905-190020/extensions/background-terminals/docs/implementation-guide.md +942 -0
  233. package/agent.bak.20260905-190020/extensions/background-terminals/index.ts +629 -0
  234. package/agent.bak.20260905-190020/extensions/background-terminals/install.ps1 +23 -0
  235. package/agent.bak.20260905-190020/extensions/background-terminals/install.sh +21 -0
  236. package/agent.bak.20260905-190020/extensions/background-terminals/package-lock.json +769 -0
  237. package/agent.bak.20260905-190020/extensions/background-terminals/package.json +17 -0
  238. package/agent.bak.20260905-190020/extensions/background-terminals/src/domain.ts +87 -0
  239. package/agent.bak.20260905-190020/extensions/background-terminals/src/manager.ts +907 -0
  240. package/agent.bak.20260905-190020/extensions/background-terminals/src/output.ts +84 -0
  241. package/agent.bak.20260905-190020/extensions/background-terminals/src/prompt.ts +142 -0
  242. package/agent.bak.20260905-190020/extensions/background-terminals/src/result-delivery.ts +27 -0
  243. package/agent.bak.20260905-190020/extensions/background-terminals/src/runtime.ts +36 -0
  244. package/agent.bak.20260905-190020/extensions/background-terminals/src/ui/output-view.ts +79 -0
  245. package/agent.bak.20260905-190020/extensions/background-terminals/src/ui/ps.ts +621 -0
  246. package/agent.bak.20260905-190020/extensions/background-terminals/src/widget-order.ts +121 -0
  247. package/agent.bak.20260905-190020/extensions/background-terminals/test/manager.test.ts +735 -0
  248. package/agent.bak.20260905-190020/extensions/background-terminals/test/output.test.ts +109 -0
  249. package/agent.bak.20260905-190020/extensions/background-terminals/test/prompt.test.ts +125 -0
  250. package/agent.bak.20260905-190020/extensions/background-terminals/test/ps.test.ts +82 -0
  251. package/agent.bak.20260905-190020/extensions/background-terminals/test/result-delivery.test.ts +44 -0
  252. package/agent.bak.20260905-190020/extensions/background-terminals/tsconfig.json +7 -0
  253. package/agent.bak.20260905-190020/extensions/destructive/README.md +34 -0
  254. package/agent.bak.20260905-190020/extensions/destructive/index.ts +124 -0
  255. package/agent.bak.20260905-190020/extensions/destructive/install.ps1 +23 -0
  256. package/agent.bak.20260905-190020/extensions/destructive/install.sh +21 -0
  257. package/agent.bak.20260905-190020/extensions/file-search/index.ts +459 -0
  258. package/agent.bak.20260905-190020/extensions/file-search/install.ps1 +23 -0
  259. package/agent.bak.20260905-190020/extensions/file-search/install.sh +21 -0
  260. package/agent.bak.20260905-190020/extensions/file-search/package-lock.json +2253 -0
  261. package/agent.bak.20260905-190020/extensions/file-search/package.json +23 -0
  262. package/agent.bak.20260905-190020/extensions/file-search/src/args.ts +122 -0
  263. package/agent.bak.20260905-190020/extensions/file-search/src/binaries.ts +422 -0
  264. package/agent.bak.20260905-190020/extensions/file-search/src/output.ts +126 -0
  265. package/agent.bak.20260905-190020/extensions/file-search/src/process.ts +146 -0
  266. package/agent.bak.20260905-190020/extensions/file-search/src/prompt.ts +52 -0
  267. package/agent.bak.20260905-190020/extensions/file-search/test/index.spec.ts +443 -0
  268. package/agent.bak.20260905-190020/extensions/file-search/tsconfig.json +7 -0
  269. package/agent.bak.20260905-190020/extensions/goal/README.md +50 -0
  270. package/agent.bak.20260905-190020/extensions/goal/index.ts +155 -0
  271. package/agent.bak.20260905-190020/extensions/goal/install.ps1 +23 -0
  272. package/agent.bak.20260905-190020/extensions/goal/install.sh +21 -0
  273. package/agent.bak.20260905-190020/extensions/kiln-update/README.md +25 -0
  274. package/agent.bak.20260905-190020/extensions/kiln-update/index.ts +99 -0
  275. package/agent.bak.20260905-190020/extensions/kiln-update/install.ps1 +23 -0
  276. package/agent.bak.20260905-190020/extensions/kiln-update/install.sh +21 -0
  277. package/agent.bak.20260905-190020/extensions/modelconf/PLAN.md +915 -0
  278. package/agent.bak.20260905-190020/extensions/modelconf/README.md +66 -0
  279. package/agent.bak.20260905-190020/extensions/modelconf/index.ts +296 -0
  280. package/agent.bak.20260905-190020/extensions/modelconf/install.ps1 +23 -0
  281. package/agent.bak.20260905-190020/extensions/modelconf/install.sh +21 -0
  282. package/agent.bak.20260905-190020/extensions/modelconf/package-lock.json +1809 -0
  283. package/agent.bak.20260905-190020/extensions/modelconf/package.json +13 -0
  284. package/agent.bak.20260905-190020/extensions/modelconf/src/fuzzy.ts +26 -0
  285. package/agent.bak.20260905-190020/extensions/modelconf/src/glob.ts +13 -0
  286. package/agent.bak.20260905-190020/extensions/modelconf/src/persistence.test.ts +46 -0
  287. package/agent.bak.20260905-190020/extensions/modelconf/src/persistence.ts +164 -0
  288. package/agent.bak.20260905-190020/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -0
  289. package/agent.bak.20260905-190020/extensions/modelconf/src/ui/ModelConfView.ts +1101 -0
  290. package/agent.bak.20260905-190020/extensions/modelconf/tsconfig.json +15 -0
  291. package/agent.bak.20260905-190020/extensions/pi-web-access/CHANGELOG.md +690 -0
  292. package/agent.bak.20260905-190020/extensions/pi-web-access/LICENSE +21 -0
  293. package/agent.bak.20260905-190020/extensions/pi-web-access/README.md +470 -0
  294. package/agent.bak.20260905-190020/extensions/pi-web-access/SECURITY.md +5 -0
  295. package/agent.bak.20260905-190020/extensions/pi-web-access/activity.ts +101 -0
  296. package/agent.bak.20260905-190020/extensions/pi-web-access/auth-fetch.ts +148 -0
  297. package/agent.bak.20260905-190020/extensions/pi-web-access/banner.png +0 -0
  298. package/agent.bak.20260905-190020/extensions/pi-web-access/brightdata-unlocker.ts +272 -0
  299. package/agent.bak.20260905-190020/extensions/pi-web-access/chrome-cookies.ts +669 -0
  300. package/agent.bak.20260905-190020/extensions/pi-web-access/content-find.ts +139 -0
  301. package/agent.bak.20260905-190020/extensions/pi-web-access/credential-source.ts +191 -0
  302. package/agent.bak.20260905-190020/extensions/pi-web-access/data-uri-sanitize.ts +406 -0
  303. package/agent.bak.20260905-190020/extensions/pi-web-access/datalab-pdf-extract.ts +568 -0
  304. package/agent.bak.20260905-190020/extensions/pi-web-access/declared-web-links.ts +173 -0
  305. package/agent.bak.20260905-190020/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -0
  306. package/agent.bak.20260905-190020/extensions/pi-web-access/evidence/contract-probe.mjs +140 -0
  307. package/agent.bak.20260905-190020/extensions/pi-web-access/exa.ts +526 -0
  308. package/agent.bak.20260905-190020/extensions/pi-web-access/extract.ts +1196 -0
  309. package/agent.bak.20260905-190020/extensions/pi-web-access/feature-config.ts +29 -0
  310. package/agent.bak.20260905-190020/extensions/pi-web-access/fetch-params.ts +111 -0
  311. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-adc.ts +298 -0
  312. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-api.ts +353 -0
  313. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-pdf-extract.ts +108 -0
  314. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-search.ts +21 -0
  315. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-url-context.ts +128 -0
  316. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-web-config.ts +101 -0
  317. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-web.ts +487 -0
  318. package/agent.bak.20260905-190020/extensions/pi-web-access/github-api.ts +197 -0
  319. package/agent.bak.20260905-190020/extensions/pi-web-access/github-extract.ts +746 -0
  320. package/agent.bak.20260905-190020/extensions/pi-web-access/github-issue-pr.ts +700 -0
  321. package/agent.bak.20260905-190020/extensions/pi-web-access/index.ts +1737 -0
  322. package/agent.bak.20260905-190020/extensions/pi-web-access/package-lock.json +5808 -0
  323. package/agent.bak.20260905-190020/extensions/pi-web-access/package.json +64 -0
  324. package/agent.bak.20260905-190020/extensions/pi-web-access/page-query.ts +96 -0
  325. package/agent.bak.20260905-190020/extensions/pi-web-access/pdf-extract.ts +409 -0
  326. package/agent.bak.20260905-190020/extensions/pi-web-access/pi-web-fetch-demo.mp4 +0 -0
  327. package/agent.bak.20260905-190020/extensions/pi-web-access/promise-try.d.ts +7 -0
  328. package/agent.bak.20260905-190020/extensions/pi-web-access/query-rewrite.ts +51 -0
  329. package/agent.bak.20260905-190020/extensions/pi-web-access/render-search-error.ts +170 -0
  330. package/agent.bak.20260905-190020/extensions/pi-web-access/rsc-extract.ts +338 -0
  331. package/agent.bak.20260905-190020/extensions/pi-web-access/search-types.ts +20 -0
  332. package/agent.bak.20260905-190020/extensions/pi-web-access/source-check.ts +282 -0
  333. package/agent.bak.20260905-190020/extensions/pi-web-access/ssrf-protection.ts +526 -0
  334. package/agent.bak.20260905-190020/extensions/pi-web-access/storage.ts +521 -0
  335. package/agent.bak.20260905-190020/extensions/pi-web-access/summary-model-scope.ts +125 -0
  336. package/agent.bak.20260905-190020/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -0
  337. package/agent.bak.20260905-190020/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -0
  338. package/agent.bak.20260905-190020/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -0
  339. package/agent.bak.20260905-190020/extensions/pi-web-access/test/config-path.test.mjs +283 -0
  340. package/agent.bak.20260905-190020/extensions/pi-web-access/test/content-find.test.mjs +25 -0
  341. package/agent.bak.20260905-190020/extensions/pi-web-access/test/credential-source.test.mjs +118 -0
  342. package/agent.bak.20260905-190020/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -0
  343. package/agent.bak.20260905-190020/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -0
  344. package/agent.bak.20260905-190020/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -0
  345. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -0
  346. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -0
  347. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -0
  348. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -0
  349. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -0
  350. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-params.test.mjs +86 -0
  351. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -0
  352. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -0
  353. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -0
  354. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -0
  355. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -0
  356. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -0
  357. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -0
  358. package/agent.bak.20260905-190020/extensions/pi-web-access/test/get-search-content.test.mjs +223 -0
  359. package/agent.bak.20260905-190020/extensions/pi-web-access/test/github-extract.test.mjs +378 -0
  360. package/agent.bak.20260905-190020/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -0
  361. package/agent.bak.20260905-190020/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -0
  362. package/agent.bak.20260905-190020/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -0
  363. package/agent.bak.20260905-190020/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -0
  364. package/agent.bak.20260905-190020/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -0
  365. package/agent.bak.20260905-190020/extensions/pi-web-access/test/page-query.test.mjs +51 -0
  366. package/agent.bak.20260905-190020/extensions/pi-web-access/test/pdf-config.test.mjs +140 -0
  367. package/agent.bak.20260905-190020/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -0
  368. package/agent.bak.20260905-190020/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -0
  369. package/agent.bak.20260905-190020/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -0
  370. package/agent.bak.20260905-190020/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -0
  371. package/agent.bak.20260905-190020/extensions/pi-web-access/test/search-error-render.test.mjs +152 -0
  372. package/agent.bak.20260905-190020/extensions/pi-web-access/test/search-providers.test.mjs +274 -0
  373. package/agent.bak.20260905-190020/extensions/pi-web-access/test/source-check.test.mjs +179 -0
  374. package/agent.bak.20260905-190020/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -0
  375. package/agent.bak.20260905-190020/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -0
  376. package/agent.bak.20260905-190020/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -0
  377. package/agent.bak.20260905-190020/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -0
  378. package/agent.bak.20260905-190020/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -0
  379. package/agent.bak.20260905-190020/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -0
  380. package/agent.bak.20260905-190020/extensions/pi-web-access/tsconfig.json +11 -0
  381. package/agent.bak.20260905-190020/extensions/pi-web-access/utils.ts +451 -0
  382. package/agent.bak.20260905-190020/extensions/pi-web-access/video-extract.ts +392 -0
  383. package/agent.bak.20260905-190020/extensions/pi-web-access/youtube-extract.ts +328 -0
  384. package/agent.bak.20260905-190020/extensions/shared/activity-status.ts +31 -0
  385. package/agent.bak.20260905-190020/extensions/shared/child-session.ts +148 -0
  386. package/agent.bak.20260905-190020/extensions/shared/context-utilization.ts +47 -0
  387. package/agent.bak.20260905-190020/extensions/shared/dashboard-state.ts +99 -0
  388. package/agent.bak.20260905-190020/extensions/shared/install.ps1 +23 -0
  389. package/agent.bak.20260905-190020/extensions/shared/install.sh +21 -0
  390. package/agent.bak.20260905-190020/extensions/shared/test/child-session.test.ts +270 -0
  391. package/agent.bak.20260905-190020/extensions/shared/test/context-utilization.test.ts +48 -0
  392. package/agent.bak.20260905-190020/extensions/shared/test/tool-call-timeout.test.ts +117 -0
  393. package/agent.bak.20260905-190020/extensions/shared/test/widget-order.test.ts +167 -0
  394. package/agent.bak.20260905-190020/extensions/shared/tool-call-timeout.ts +104 -0
  395. package/agent.bak.20260905-190020/extensions/skillsconf/README.md +74 -0
  396. package/agent.bak.20260905-190020/extensions/skillsconf/index.ts +92 -0
  397. package/agent.bak.20260905-190020/extensions/skillsconf/install.ps1 +23 -0
  398. package/agent.bak.20260905-190020/extensions/skillsconf/install.sh +21 -0
  399. package/agent.bak.20260905-190020/extensions/skillsconf/package-lock.json +1809 -0
  400. package/agent.bak.20260905-190020/extensions/skillsconf/package.json +18 -0
  401. package/agent.bak.20260905-190020/extensions/skillsconf/src/delete-skill.test.ts +64 -0
  402. package/agent.bak.20260905-190020/extensions/skillsconf/src/delete-skill.ts +45 -0
  403. package/agent.bak.20260905-190020/extensions/skillsconf/src/filter.test.ts +80 -0
  404. package/agent.bak.20260905-190020/extensions/skillsconf/src/filter.ts +74 -0
  405. package/agent.bak.20260905-190020/extensions/skillsconf/src/fuzzy.ts +26 -0
  406. package/agent.bak.20260905-190020/extensions/skillsconf/src/persistence.test.ts +72 -0
  407. package/agent.bak.20260905-190020/extensions/skillsconf/src/persistence.ts +169 -0
  408. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -0
  409. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/SkillConfView.ts +758 -0
  410. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/text-input.ts +91 -0
  411. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/tui-helpers.ts +144 -0
  412. package/agent.bak.20260905-190020/extensions/skillsconf/tsconfig.json +15 -0
  413. package/agent.bak.20260905-190020/extensions/statusline/install.ps1 +23 -0
  414. package/agent.bak.20260905-190020/extensions/statusline/install.sh +21 -0
  415. package/agent.bak.20260905-190020/extensions/subagents/docs/design-plan.md +568 -0
  416. package/agent.bak.20260905-190020/extensions/subagents/docs/effect-v4-extension-guide.md +354 -0
  417. package/agent.bak.20260905-190020/extensions/subagents/docs/effect-v4-notes.md +571 -0
  418. package/agent.bak.20260905-190020/extensions/subagents/index.ts +826 -0
  419. package/agent.bak.20260905-190020/extensions/subagents/install.ps1 +23 -0
  420. package/agent.bak.20260905-190020/extensions/subagents/install.sh +21 -0
  421. package/agent.bak.20260905-190020/extensions/subagents/package-lock.json +2244 -0
  422. package/agent.bak.20260905-190020/extensions/subagents/package.json +19 -0
  423. package/agent.bak.20260905-190020/extensions/subagents/src/backend.ts +73 -0
  424. package/agent.bak.20260905-190020/extensions/subagents/src/backends/claude.ts +701 -0
  425. package/agent.bak.20260905-190020/extensions/subagents/src/backends/codex.ts +1060 -0
  426. package/agent.bak.20260905-190020/extensions/subagents/src/backends/pi.ts +575 -0
  427. package/agent.bak.20260905-190020/extensions/subagents/src/backends/stub.ts +300 -0
  428. package/agent.bak.20260905-190020/extensions/subagents/src/by-the-way.ts +21 -0
  429. package/agent.bak.20260905-190020/extensions/subagents/src/domain.ts +253 -0
  430. package/agent.bak.20260905-190020/extensions/subagents/src/format.ts +74 -0
  431. package/agent.bak.20260905-190020/extensions/subagents/src/manager.ts +736 -0
  432. package/agent.bak.20260905-190020/extensions/subagents/src/prompt.ts +92 -0
  433. package/agent.bak.20260905-190020/extensions/subagents/src/result-delivery.ts +20 -0
  434. package/agent.bak.20260905-190020/extensions/subagents/src/runtime.ts +53 -0
  435. package/agent.bak.20260905-190020/extensions/subagents/src/ui/takeover.ts +583 -0
  436. package/agent.bak.20260905-190020/extensions/subagents/src/ui/transcript.ts +201 -0
  437. package/agent.bak.20260905-190020/extensions/subagents/src/widget-order.ts +121 -0
  438. package/agent.bak.20260905-190020/extensions/subagents/test/by-the-way.test.ts +29 -0
  439. package/agent.bak.20260905-190020/extensions/subagents/test/claude.test.ts +119 -0
  440. package/agent.bak.20260905-190020/extensions/subagents/test/codex.test.ts +102 -0
  441. package/agent.bak.20260905-190020/extensions/subagents/test/context-usage.test.ts +107 -0
  442. package/agent.bak.20260905-190020/extensions/subagents/test/manager.test.ts +276 -0
  443. package/agent.bak.20260905-190020/extensions/subagents/test/result-delivery.test.ts +27 -0
  444. package/agent.bak.20260905-190020/extensions/subagents/test/takeover.test.ts +29 -0
  445. package/agent.bak.20260905-190020/extensions/subagents/tsconfig.json +7 -0
  446. package/agent.bak.20260905-190020/extensions/taste/index.ts +443 -0
  447. package/agent.bak.20260905-190020/extensions/taste/install.ps1 +23 -0
  448. package/agent.bak.20260905-190020/extensions/taste/install.sh +21 -0
  449. package/agent.bak.20260905-190020/extensions/todo/AGENTS.md +38 -0
  450. package/agent.bak.20260905-190020/extensions/todo/LICENSE +21 -0
  451. package/agent.bak.20260905-190020/extensions/todo/config.ts +55 -0
  452. package/agent.bak.20260905-190020/extensions/todo/index.ts +151 -0
  453. package/agent.bak.20260905-190020/extensions/todo/install.ps1 +23 -0
  454. package/agent.bak.20260905-190020/extensions/todo/install.sh +21 -0
  455. package/agent.bak.20260905-190020/extensions/todo/locales/de.json +17 -0
  456. package/agent.bak.20260905-190020/extensions/todo/locales/en.json +15 -0
  457. package/agent.bak.20260905-190020/extensions/todo/locales/es.json +17 -0
  458. package/agent.bak.20260905-190020/extensions/todo/locales/fr.json +17 -0
  459. package/agent.bak.20260905-190020/extensions/todo/locales/pt-BR.json +17 -0
  460. package/agent.bak.20260905-190020/extensions/todo/locales/pt.json +17 -0
  461. package/agent.bak.20260905-190020/extensions/todo/locales/ru.json +17 -0
  462. package/agent.bak.20260905-190020/extensions/todo/locales/uk.json +17 -0
  463. package/agent.bak.20260905-190020/extensions/todo/locales/zh.json +17 -0
  464. package/agent.bak.20260905-190020/extensions/todo/package-lock.json +3358 -0
  465. package/agent.bak.20260905-190020/extensions/todo/package.json +67 -0
  466. package/agent.bak.20260905-190020/extensions/todo/state/i18n-bridge.ts +64 -0
  467. package/agent.bak.20260905-190020/extensions/todo/state/invariants.ts +20 -0
  468. package/agent.bak.20260905-190020/extensions/todo/state/replay.ts +38 -0
  469. package/agent.bak.20260905-190020/extensions/todo/state/selectors.ts +107 -0
  470. package/agent.bak.20260905-190020/extensions/todo/state/state-reducer.ts +326 -0
  471. package/agent.bak.20260905-190020/extensions/todo/state/state.ts +18 -0
  472. package/agent.bak.20260905-190020/extensions/todo/state/store.ts +82 -0
  473. package/agent.bak.20260905-190020/extensions/todo/state/task-graph.ts +57 -0
  474. package/agent.bak.20260905-190020/extensions/todo/todo-overlay.ts +204 -0
  475. package/agent.bak.20260905-190020/extensions/todo/todo.ts +155 -0
  476. package/agent.bak.20260905-190020/extensions/todo/tool/response-envelope.ts +109 -0
  477. package/agent.bak.20260905-190020/extensions/todo/tool/types.ts +206 -0
  478. package/agent.bak.20260905-190020/extensions/todo/view/format.ts +177 -0
  479. package/agent.bak.20260905-190020/extensions/todo/widget-order.ts +121 -0
  480. package/agent.bak.20260905-190020/extensions/trim-context/README.md +54 -0
  481. package/agent.bak.20260905-190020/extensions/trim-context/index.ts +487 -0
  482. package/agent.bak.20260905-190020/extensions/trim-context/install.ps1 +23 -0
  483. package/agent.bak.20260905-190020/extensions/trim-context/install.sh +21 -0
  484. package/agent.bak.20260905-190020/keybindings.json +7 -0
  485. package/bin/kiln.js +588 -358
  486. package/package.json +27 -21
  487. package/agent/install.ps1 +0 -527
  488. package/agent/install.sh +0 -511
  489. /package/{agent/extensions/status line → agent.bak.20260905-190020/extensions/ask-user}/install.ps1 +0 -0
  490. /package/{agent/extensions/status line → agent.bak.20260905-190020/extensions/ask-user}/install.sh +0 -0
  491. /package/{agent/extensions/status line → agent.bak.20260905-190020/extensions/statusline}/index.ts +0 -0
@@ -1,746 +1,746 @@
1
- import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, unlinkSync } from "node:fs";
2
- import { execFile, spawn, type ChildProcess } from "node:child_process";
3
- import { createHash } from "node:crypto";
4
- import { basename, dirname, extname, join, resolve as resolvePath, sep as pathSep } from "node:path";
5
- import { activityMonitor } from "./activity.ts";
6
- import type { ExtractedContent } from "./extract.ts";
7
- import { checkGhAvailable, checkRepoSize, fetchViaApi, showGhHint } from "./github-api.ts";
8
- import { getWebSearchConfigPath } from "./utils.ts";
9
-
10
- const CONFIG_PATH = getWebSearchConfigPath();
11
-
12
- const BINARY_EXTENSIONS = new Set([
13
- ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".svg", ".tiff", ".tif",
14
- ".mp3", ".mp4", ".avi", ".mov", ".mkv", ".flv", ".wmv", ".wav", ".ogg", ".webm", ".flac", ".aac",
15
- ".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar", ".zst",
16
- ".exe", ".dll", ".so", ".dylib", ".bin", ".o", ".a", ".lib",
17
- ".woff", ".woff2", ".ttf", ".otf", ".eot",
18
- ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
19
- ".sqlite", ".db", ".sqlite3",
20
- ".pyc", ".pyo", ".class", ".jar", ".war",
21
- ".iso", ".img", ".dmg",
22
- ]);
23
-
24
- const NOISE_DIRS = new Set([
25
- "node_modules", "vendor", ".next", "dist", "build", "__pycache__",
26
- ".venv", "venv", ".tox", ".mypy_cache", ".pytest_cache",
27
- "target", ".gradle", ".idea", ".vscode",
28
- ]);
29
-
30
- const MAX_INLINE_FILE_CHARS = 100_000;
31
- const MAX_TREE_ENTRIES = 200;
32
-
33
- export interface GitHubUrlInfo {
34
- owner: string;
35
- repo: string;
36
- ref?: string;
37
- refIsFullSha: boolean;
38
- path?: string;
39
- type: "root" | "blob" | "tree";
40
- }
41
-
42
- interface CachedClone {
43
- destination: CloneDestination;
44
- clonePromise: Promise<string | null>;
45
- }
46
-
47
- interface CloneDestination {
48
- rootPath: string;
49
- localPath: string;
50
- }
51
-
52
- interface GitHubCloneConfig {
53
- enabled: boolean;
54
- maxRepoSizeMB: number;
55
- cloneTimeoutSeconds: number;
56
- clonePath: string;
57
- }
58
-
59
- const cloneCache = new Map<string, CachedClone>();
60
-
61
- let cachedConfig: GitHubCloneConfig | null = null;
62
-
63
- function normalizeEnabled(value: unknown, fallback: boolean): boolean {
64
- return typeof value === "boolean" ? value : fallback;
65
- }
66
-
67
- function normalizePositiveNumber(value: unknown, fallback: number): number {
68
- if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
69
- return value > 0 ? value : fallback;
70
- }
71
-
72
- function expandPath(value: string): string {
73
- let expanded = value;
74
- // Expand ~ at the start of the path
75
- if (expanded.startsWith("~/") || expanded === "~") {
76
- expanded = expanded.replace(/^~/, process.env.HOME || process.env.USERPROFILE || "");
77
- }
78
- // Expand environment variables like $HOME, $USER, etc.
79
- expanded = expanded.replace(/\$([A-Z_][A-Z0-9_]*)/gi, (match, varName) => {
80
- return process.env[varName] ?? match;
81
- });
82
- return expanded;
83
- }
84
-
85
- function normalizeClonePath(value: unknown, fallback: string): string {
86
- if (typeof value !== "string") return fallback;
87
- const normalized = value.trim();
88
- if (normalized.length === 0) return fallback;
89
- return expandPath(normalized);
90
- }
91
-
92
- function loadGitHubConfig(): GitHubCloneConfig {
93
- if (cachedConfig) return cachedConfig;
94
-
95
- const defaults: GitHubCloneConfig = {
96
- enabled: true,
97
- maxRepoSizeMB: 350,
98
- cloneTimeoutSeconds: 30,
99
- clonePath: "/tmp/pi-github-repos",
100
- };
101
-
102
- if (!existsSync(CONFIG_PATH)) {
103
- cachedConfig = defaults;
104
- return cachedConfig;
105
- }
106
-
107
- const rawText = readFileSync(CONFIG_PATH, "utf-8");
108
- let raw: { githubClone?: { enabled?: unknown; maxRepoSizeMB?: unknown; cloneTimeoutSeconds?: unknown; clonePath?: unknown } };
109
- try {
110
- raw = JSON.parse(rawText) as { githubClone?: { enabled?: unknown; maxRepoSizeMB?: unknown; cloneTimeoutSeconds?: unknown; clonePath?: unknown } };
111
- } catch (err) {
112
- const message = err instanceof Error ? err.message : String(err);
113
- throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
114
- }
115
-
116
- const gc = raw.githubClone ?? {};
117
- cachedConfig = {
118
- enabled: normalizeEnabled(gc.enabled, defaults.enabled),
119
- maxRepoSizeMB: normalizePositiveNumber(gc.maxRepoSizeMB, defaults.maxRepoSizeMB),
120
- cloneTimeoutSeconds: normalizePositiveNumber(gc.cloneTimeoutSeconds, defaults.cloneTimeoutSeconds),
121
- clonePath: normalizeClonePath(gc.clonePath, defaults.clonePath),
122
- };
123
- return cachedConfig;
124
- }
125
-
126
- const NON_CODE_SEGMENTS = new Set([
127
- "issues", "pull", "pulls", "discussions", "releases", "wiki",
128
- "actions", "settings", "security", "projects", "graphs",
129
- "compare", "commits", "tags", "branches", "stargazers",
130
- "watchers", "network", "forks", "milestone", "labels",
131
- "packages", "codespaces", "contribute", "community",
132
- "sponsors", "invitations", "notifications", "insights",
133
- ]);
134
-
135
- export function parseGitHubUrl(url: string): GitHubUrlInfo | null {
136
- let parsed: URL;
137
- try {
138
- parsed = new URL(url);
139
- } catch {
140
- return null;
141
- }
142
-
143
- const host = parsed.hostname.toLowerCase();
144
- if (host !== "github.com" && host !== "www.github.com") return null;
145
-
146
- const segments: string[] = [];
147
- for (const segment of parsed.pathname.split("/").filter(Boolean)) {
148
- try {
149
- segments.push(decodeURIComponent(segment));
150
- } catch {
151
- return null;
152
- }
153
- }
154
- if (segments.length < 2) return null;
155
-
156
- const owner = segments[0];
157
- const repo = segments[1].replace(/\.git$/, "");
158
- if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(owner)) return null;
159
- if (owner.includes("--")) return null;
160
- if (!/^[A-Za-z0-9._-]{1,100}$/.test(repo) || repo === "." || repo === "..") return null;
161
-
162
- if (NON_CODE_SEGMENTS.has(segments[2]?.toLowerCase())) return null;
163
-
164
- if (segments.length === 2) {
165
- return { owner, repo, refIsFullSha: false, type: "root" };
166
- }
167
-
168
- const action = segments[2];
169
- if (action !== "blob" && action !== "tree") return null;
170
- if (segments.length < 4) return null;
171
-
172
- const ref = segments[3];
173
- if (ref.length === 0 || ref.length > 1024 || /[\0-\x1f\x7f]/.test(ref)) return null;
174
- const refIsFullSha = /^[0-9a-f]{40}$/.test(ref);
175
- const pathParts = segments.slice(4);
176
- const path = pathParts.length > 0 ? pathParts.join("/") : "";
177
-
178
- return {
179
- owner,
180
- repo,
181
- ref,
182
- refIsFullSha,
183
- path,
184
- type: action as "blob" | "tree",
185
- };
186
- }
187
-
188
- function cacheKey(owner: string, repo: string, ref?: string): string {
189
- return ref ? `${owner}/${repo}@${ref}` : `${owner}/${repo}`;
190
- }
191
-
192
- function cloneDestination(config: GitHubCloneConfig, owner: string, repo: string, ref?: string): CloneDestination | null {
193
- try {
194
- mkdirSync(resolvePath(config.clonePath), { recursive: true });
195
- const rootPath = realpathSync(resolvePath(config.clonePath));
196
- const digest = createHash("sha256").update(JSON.stringify([owner, repo, ref ?? null])).digest("hex");
197
- const localPath = resolvePath(rootPath, digest);
198
- if (dirname(localPath) !== rootPath) return null;
199
- return { rootPath, localPath };
200
- } catch {
201
- return null;
202
- }
203
- }
204
-
205
- function removeCloneDestination(destination: CloneDestination): boolean {
206
- const rootPath = resolvePath(destination.rootPath);
207
- const localPath = resolvePath(destination.localPath);
208
- if (dirname(localPath) !== rootPath || !/^[0-9a-f]{64}$/.test(basename(localPath))) return false;
209
- try {
210
- const entry = lstatSync(localPath);
211
- if (entry.isSymbolicLink()) unlinkSync(localPath);
212
- else rmSync(localPath, { recursive: true, force: true });
213
- return true;
214
- } catch (err) {
215
- if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") return true;
216
- return false;
217
- }
218
- }
219
-
220
- const PROCESS_KILL_GRACE_MS = 3000;
221
-
222
- function terminateProcessTree(child: ChildProcess): void {
223
- const pid = child.pid;
224
- if (!pid) return;
225
-
226
- if (process.platform === "win32") {
227
- const killer = execFile(
228
- "taskkill",
229
- ["/pid", String(pid), "/T", "/F"],
230
- { windowsHide: true },
231
- (err) => {
232
- if (err) child.kill();
233
- },
234
- );
235
- killer.unref();
236
- return;
237
- }
238
-
239
- try {
240
- // Clone commands run in their own process group so git/gh helpers cannot
241
- // survive a timeout or cancellation and keep reading from the host TTY.
242
- process.kill(-pid, "SIGTERM");
243
- } catch {
244
- child.kill();
245
- }
246
-
247
- // A credential helper may handle or ignore SIGTERM. Escalate against the
248
- // entire process group so neither git nor any descendant can block forever.
249
- const forceKill = setTimeout(() => {
250
- try {
251
- process.kill(-pid, "SIGKILL");
252
- } catch {
253
- child.kill("SIGKILL");
254
- }
255
- }, PROCESS_KILL_GRACE_MS);
256
- forceKill.unref();
257
- }
258
-
259
- function execClone(args: string[], destination: CloneDestination, timeoutMs: number, signal?: AbortSignal): Promise<string | null> {
260
- return new Promise((resolve) => {
261
- const { localPath } = destination;
262
- let settled = false;
263
- let timeout: ReturnType<typeof setTimeout> | undefined;
264
- let onAbort: (() => void) | undefined;
265
-
266
- const finish = (success: boolean) => {
267
- if (settled) return;
268
- settled = true;
269
- if (timeout) clearTimeout(timeout);
270
- if (signal && onAbort) signal.removeEventListener("abort", onAbort);
271
-
272
- if (!success) {
273
- removeCloneDestination(destination);
274
- resolve(null);
275
- return;
276
- }
277
- resolve(localPath);
278
- };
279
-
280
- const child = spawn(args[0], args.slice(1), {
281
- detached: process.platform !== "win32",
282
- env: {
283
- ...process.env,
284
- GIT_TERMINAL_PROMPT: "0",
285
- GCM_INTERACTIVE: "Never",
286
- GH_PROMPT_DISABLED: "1",
287
- },
288
- stdio: "ignore",
289
- windowsHide: true,
290
- });
291
-
292
- child.once("error", () => finish(false));
293
- child.once("close", (code) => finish(code === 0));
294
-
295
- timeout = setTimeout(() => terminateProcessTree(child), timeoutMs);
296
- timeout.unref();
297
-
298
- if (signal) {
299
- onAbort = () => {
300
- if (timeout) clearTimeout(timeout);
301
- terminateProcessTree(child);
302
- };
303
- if (signal.aborted) onAbort();
304
- else signal.addEventListener("abort", onAbort, { once: true });
305
- }
306
- });
307
- }
308
-
309
- async function cloneRepo(
310
- owner: string,
311
- repo: string,
312
- ref: string | undefined,
313
- config: GitHubCloneConfig,
314
- destination: CloneDestination,
315
- signal?: AbortSignal,
316
- ): Promise<string | null> {
317
- const { localPath } = destination;
318
- if (!removeCloneDestination(destination)) return null;
319
-
320
- const timeoutMs = config.cloneTimeoutSeconds * 1000;
321
- const hasGh = await checkGhAvailable();
322
-
323
- if (hasGh) {
324
- const args = ["gh", "repo", "clone", `${owner}/${repo}`, localPath, "--", "--depth", "1", "--single-branch"];
325
- if (ref) args.push("--branch", ref);
326
- return execClone(args, destination, timeoutMs, signal);
327
- }
328
-
329
- showGhHint();
330
-
331
- const gitUrl = `https://github.com/${owner}/${repo}.git`;
332
- const args = ["git", "clone", "--depth", "1", "--single-branch"];
333
- if (ref) args.push("--branch", ref);
334
- args.push(gitUrl, localPath);
335
- return execClone(args, destination, timeoutMs, signal);
336
- }
337
-
338
- function isBinaryFile(filePath: string): boolean {
339
- const ext = extname(filePath).toLowerCase();
340
- if (BINARY_EXTENSIONS.has(ext)) return true;
341
-
342
- let fd: number;
343
- try {
344
- fd = openSync(filePath, "r");
345
- } catch {
346
- return false;
347
- }
348
- try {
349
- const buf = Buffer.alloc(512);
350
- const bytesRead = readSync(fd, buf, 0, 512, 0);
351
- for (let i = 0; i < bytesRead; i++) {
352
- if (buf[i] === 0) return true;
353
- }
354
- } catch {
355
- return false;
356
- } finally {
357
- closeSync(fd);
358
- }
359
-
360
- return false;
361
- }
362
-
363
- function formatFileSize(bytes: number): string {
364
- if (bytes < 1024) return `${bytes} B`;
365
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
366
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
367
- }
368
-
369
- function resolveWithinRepo(rootPath: string, relativePath: string): string | null {
370
- const normalizedRoot = resolvePath(rootPath);
371
- const candidate = resolvePath(normalizedRoot, relativePath);
372
- if (candidate !== normalizedRoot) {
373
- const rootPrefix = normalizedRoot.endsWith(pathSep) ? normalizedRoot : normalizedRoot + pathSep;
374
- if (!candidate.startsWith(rootPrefix)) return null;
375
- }
376
-
377
- if (!existsSync(candidate)) return candidate;
378
-
379
- try {
380
- const realRoot = realpathSync(normalizedRoot);
381
- const realCandidate = realpathSync(candidate);
382
- if (realCandidate === realRoot) return candidate;
383
- const realRootPrefix = realRoot.endsWith(pathSep) ? realRoot : realRoot + pathSep;
384
- return realCandidate.startsWith(realRootPrefix) ? candidate : null;
385
- } catch {
386
- return null;
387
- }
388
- }
389
-
390
- function readTextFile(path: string): string | null {
391
- try {
392
- return readFileSync(path, "utf-8");
393
- } catch {
394
- return null;
395
- }
396
- }
397
-
398
- function buildTree(rootPath: string): string {
399
- const entries: string[] = [];
400
-
401
- function walk(dir: string, relPath: string): void {
402
- if (entries.length >= MAX_TREE_ENTRIES) return;
403
-
404
- let items: string[];
405
- try {
406
- items = readdirSync(dir).sort();
407
- } catch {
408
- return;
409
- }
410
-
411
- for (const item of items) {
412
- if (entries.length >= MAX_TREE_ENTRIES) return;
413
- if (item === ".git") continue;
414
-
415
- const rel = relPath ? `${relPath}/${item}` : item;
416
- const safePath = resolveWithinRepo(rootPath, rel);
417
- if (!safePath) {
418
- entries.push(`${rel} [outside repo skipped]`);
419
- continue;
420
- }
421
-
422
- let stat;
423
- try {
424
- stat = statSync(safePath);
425
- } catch {
426
- continue;
427
- }
428
-
429
- if (stat.isDirectory()) {
430
- if (NOISE_DIRS.has(item)) {
431
- entries.push(`${rel}/ [skipped]`);
432
- continue;
433
- }
434
- entries.push(`${rel}/`);
435
- walk(safePath, rel);
436
- } else {
437
- entries.push(rel);
438
- }
439
- }
440
- }
441
-
442
- walk(rootPath, "");
443
-
444
- if (entries.length >= MAX_TREE_ENTRIES) {
445
- entries.push(`... (truncated at ${MAX_TREE_ENTRIES} entries)`);
446
- }
447
-
448
- return entries.join("\n");
449
- }
450
-
451
- function buildDirListing(rootPath: string, subPath: string): string {
452
- const targetPath = resolveWithinRepo(rootPath, subPath);
453
- if (!targetPath) return "(path escapes repository root)";
454
- const lines: string[] = [];
455
-
456
- let items: string[];
457
- try {
458
- items = readdirSync(targetPath).sort();
459
- } catch {
460
- return "(directory not readable)";
461
- }
462
-
463
- for (const item of items) {
464
- if (item === ".git") continue;
465
- const rel = subPath ? `${subPath}/${item}` : item;
466
- const safePath = resolveWithinRepo(rootPath, rel);
467
- if (!safePath) {
468
- lines.push(` ${item} (outside repo)`);
469
- continue;
470
- }
471
- try {
472
- const stat = statSync(safePath);
473
- if (stat.isDirectory()) {
474
- lines.push(` ${item}/`);
475
- } else {
476
- lines.push(` ${item} (${formatFileSize(stat.size)})`);
477
- }
478
- } catch {
479
- lines.push(` ${item} (unreadable)`);
480
- }
481
- }
482
-
483
- return lines.join("\n");
484
- }
485
-
486
- function readReadme(localPath: string): string | null {
487
- const candidates = ["README.md", "readme.md", "README", "README.txt", "README.rst"];
488
- for (const name of candidates) {
489
- const readmePath = join(localPath, name);
490
- if (existsSync(readmePath)) {
491
- try {
492
- const content = readFileSync(readmePath, "utf-8");
493
- return content.length > 8192 ? content.slice(0, 8192) + "\n\n[README truncated at 8K chars]" : content;
494
- } catch {
495
- continue;
496
- }
497
- }
498
- }
499
- return null;
500
- }
501
-
502
- function generateContent(localPath: string, info: GitHubUrlInfo): string {
503
- const lines: string[] = [];
504
- lines.push(`Repository cloned to: ${localPath}`);
505
- lines.push("");
506
-
507
- if (info.type === "root") {
508
- lines.push("## Structure");
509
- lines.push(buildTree(localPath));
510
- lines.push("");
511
-
512
- const readme = readReadme(localPath);
513
- if (readme) {
514
- lines.push("## README.md");
515
- lines.push(readme);
516
- lines.push("");
517
- }
518
-
519
- lines.push("Use `read` and `bash` tools at the path above to explore further.");
520
- return lines.join("\n");
521
- }
522
-
523
- if (info.type === "tree") {
524
- const dirPath = info.path || "";
525
- const fullDirPath = resolveWithinRepo(localPath, dirPath);
526
-
527
- if (!fullDirPath || !existsSync(fullDirPath)) {
528
- lines.push(`Path \`${dirPath}\` not found in clone. Showing repository root instead.`);
529
- lines.push("");
530
- lines.push("## Structure");
531
- lines.push(buildTree(localPath));
532
- } else {
533
- lines.push(`## ${dirPath || "/"}`);
534
- lines.push(buildDirListing(localPath, dirPath));
535
- }
536
-
537
- lines.push("");
538
- lines.push("Use `read` and `bash` tools at the path above to explore further.");
539
- return lines.join("\n");
540
- }
541
-
542
- if (info.type === "blob") {
543
- const filePath = info.path || "";
544
- const fullFilePath = resolveWithinRepo(localPath, filePath);
545
-
546
- if (!fullFilePath || !existsSync(fullFilePath)) {
547
- lines.push(`Path \`${filePath}\` not found in clone. Showing repository root instead.`);
548
- lines.push("");
549
- lines.push("## Structure");
550
- lines.push(buildTree(localPath));
551
- lines.push("");
552
- lines.push("Use `read` and `bash` tools at the path above to explore further.");
553
- return lines.join("\n");
554
- }
555
-
556
- let stat: ReturnType<typeof statSync>;
557
- try {
558
- stat = statSync(fullFilePath);
559
- } catch (err) {
560
- const message = err instanceof Error ? err.message : String(err);
561
- lines.push(`Could not inspect \`${filePath}\`: ${message}`);
562
- lines.push("");
563
- lines.push("Use `read` and `bash` tools at the path above to explore further.");
564
- return lines.join("\n");
565
- }
566
-
567
- if (stat.isDirectory()) {
568
- lines.push(`## ${filePath || "/"}`);
569
- lines.push(buildDirListing(localPath, filePath));
570
- lines.push("");
571
- lines.push("Use `read` and `bash` tools at the path above to explore further.");
572
- return lines.join("\n");
573
- }
574
-
575
- if (isBinaryFile(fullFilePath)) {
576
- const ext = extname(filePath).replace(".", "");
577
- lines.push(`## ${filePath}`);
578
- lines.push(`Binary file (${ext}, ${formatFileSize(stat.size)}). Use \`read\` or \`bash\` tools at the path above to inspect.`);
579
- return lines.join("\n");
580
- }
581
-
582
- const content = readTextFile(fullFilePath);
583
- if (content === null) {
584
- lines.push(`Could not read \`${filePath}\` as UTF-8 text.`);
585
- lines.push("");
586
- lines.push("Use `read` and `bash` tools at the path above to explore further.");
587
- return lines.join("\n");
588
- }
589
- lines.push(`## ${filePath}`);
590
-
591
- if (content.length > MAX_INLINE_FILE_CHARS) {
592
- lines.push(content.slice(0, MAX_INLINE_FILE_CHARS));
593
- lines.push("");
594
- lines.push(`[File truncated at 100K chars. Full file: ${fullFilePath}]`);
595
- } else {
596
- lines.push(content);
597
- }
598
-
599
- lines.push("");
600
- lines.push("Use `read` and `bash` tools at the path above to explore further.");
601
- return lines.join("\n");
602
- }
603
-
604
- return lines.join("\n");
605
- }
606
-
607
- async function awaitCachedClone(
608
- cached: CachedClone,
609
- url: string,
610
- owner: string,
611
- repo: string,
612
- info: GitHubUrlInfo,
613
- signal?: AbortSignal,
614
- ): Promise<ExtractedContent | null> {
615
- if (signal?.aborted) return null;
616
- const result = await cached.clonePromise;
617
- if (signal?.aborted) return null;
618
- if (result) {
619
- const content = generateContent(result, info);
620
- const title = info.path ? `${owner}/${repo} - ${info.path}` : `${owner}/${repo}`;
621
- return { url, title, content, error: null };
622
- }
623
- return fetchViaApi(url, owner, repo, info);
624
- }
625
-
626
- export async function extractGitHub(
627
- url: string,
628
- signal?: AbortSignal,
629
- forceClone?: boolean,
630
- ): Promise<ExtractedContent | null> {
631
- const info = parseGitHubUrl(url);
632
- if (!info) return null;
633
-
634
- if (signal?.aborted) return null;
635
-
636
- const config = loadGitHubConfig();
637
- if (!config.enabled) return null;
638
-
639
- const { owner, repo } = info;
640
- const key = cacheKey(owner, repo, info.ref);
641
-
642
- const cached = cloneCache.get(key);
643
- if (cached) return awaitCachedClone(cached, url, owner, repo, info, signal);
644
-
645
- if (info.refIsFullSha) {
646
- if (signal?.aborted) return null;
647
- const sizeNote = `Note: Commit SHA URLs use the GitHub API instead of cloning.`;
648
- return fetchViaApi(url, owner, repo, info, sizeNote);
649
- }
650
-
651
- const activityId = activityMonitor.logStart({ type: "fetch", url: `github.com/${owner}/${repo}` });
652
-
653
- if (!forceClone) {
654
- const sizeKB = await checkRepoSize(owner, repo);
655
- if (signal?.aborted) {
656
- activityMonitor.logComplete(activityId, 0);
657
- return null;
658
- }
659
- if (sizeKB !== null) {
660
- const sizeMB = sizeKB / 1024;
661
- if (sizeMB > config.maxRepoSizeMB) {
662
- if (signal?.aborted) {
663
- activityMonitor.logComplete(activityId, 0);
664
- return null;
665
- }
666
- const sizeNote =
667
- `Note: Repository is ${Math.round(sizeMB)}MB (threshold: ${config.maxRepoSizeMB}MB). ` +
668
- `Showing API-fetched content instead of full clone. Ask the user if they'd like to clone the full repo -- ` +
669
- `if yes, call fetch_content again with the same URL and add forceClone: true to the params.`;
670
- const apiView = await fetchViaApi(url, owner, repo, info, sizeNote);
671
- if (apiView) {
672
- activityMonitor.logComplete(activityId, 200);
673
- return apiView;
674
- }
675
- activityMonitor.logError(activityId, "api fallback unavailable for oversized repository");
676
- return null;
677
- }
678
- }
679
- }
680
-
681
- if (signal?.aborted) {
682
- activityMonitor.logComplete(activityId, 0);
683
- return null;
684
- }
685
-
686
- // Re-check: another concurrent caller may have started a clone while we awaited the size check
687
- const cachedAfterSizeCheck = cloneCache.get(key);
688
- if (cachedAfterSizeCheck) {
689
- const cachedResult = await awaitCachedClone(cachedAfterSizeCheck, url, owner, repo, info, signal);
690
- if (signal?.aborted) {
691
- activityMonitor.logComplete(activityId, 0);
692
- } else if (cachedResult) {
693
- activityMonitor.logComplete(activityId, 200);
694
- } else {
695
- activityMonitor.logError(activityId, "clone failed");
696
- }
697
- return cachedResult;
698
- }
699
-
700
- const destination = cloneDestination(config, owner, repo, info.ref);
701
- if (!destination) {
702
- const apiFallback = await fetchViaApi(url, owner, repo, info);
703
- if (apiFallback) activityMonitor.logComplete(activityId, 200);
704
- else activityMonitor.logError(activityId, "invalid clone destination");
705
- return apiFallback;
706
- }
707
- const clonePromise = cloneRepo(owner, repo, info.ref, config, destination, signal);
708
- cloneCache.set(key, { destination, clonePromise });
709
-
710
- const result = await clonePromise;
711
- if (signal?.aborted) {
712
- if (!result) cloneCache.delete(key);
713
- activityMonitor.logComplete(activityId, 0);
714
- return null;
715
- }
716
-
717
- if (!result) {
718
- cloneCache.delete(key);
719
- if (signal?.aborted) {
720
- activityMonitor.logComplete(activityId, 0);
721
- return null;
722
- }
723
-
724
- const apiFallback = await fetchViaApi(url, owner, repo, info);
725
- if (apiFallback) {
726
- activityMonitor.logComplete(activityId, 200);
727
- return apiFallback;
728
- }
729
-
730
- activityMonitor.logError(activityId, "clone and API fallback failed");
731
- return null;
732
- }
733
-
734
- activityMonitor.logComplete(activityId, 200);
735
- const content = generateContent(result, info);
736
- const title = info.path ? `${owner}/${repo} - ${info.path}` : `${owner}/${repo}`;
737
- return { url, title, content, error: null };
738
- }
739
-
740
- export function clearCloneCache(): void {
741
- for (const entry of cloneCache.values()) {
742
- removeCloneDestination(entry.destination);
743
- }
744
- cloneCache.clear();
745
- cachedConfig = null;
746
- }
1
+ import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, unlinkSync } from "node:fs";
2
+ import { execFile, spawn, type ChildProcess } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { basename, dirname, extname, join, resolve as resolvePath, sep as pathSep } from "node:path";
5
+ import { activityMonitor } from "./activity.ts";
6
+ import type { ExtractedContent } from "./extract.ts";
7
+ import { checkGhAvailable, checkRepoSize, fetchViaApi, showGhHint } from "./github-api.ts";
8
+ import { getWebSearchConfigPath } from "./utils.ts";
9
+
10
+ const CONFIG_PATH = getWebSearchConfigPath();
11
+
12
+ const BINARY_EXTENSIONS = new Set([
13
+ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".svg", ".tiff", ".tif",
14
+ ".mp3", ".mp4", ".avi", ".mov", ".mkv", ".flv", ".wmv", ".wav", ".ogg", ".webm", ".flac", ".aac",
15
+ ".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar", ".zst",
16
+ ".exe", ".dll", ".so", ".dylib", ".bin", ".o", ".a", ".lib",
17
+ ".woff", ".woff2", ".ttf", ".otf", ".eot",
18
+ ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
19
+ ".sqlite", ".db", ".sqlite3",
20
+ ".pyc", ".pyo", ".class", ".jar", ".war",
21
+ ".iso", ".img", ".dmg",
22
+ ]);
23
+
24
+ const NOISE_DIRS = new Set([
25
+ "node_modules", "vendor", ".next", "dist", "build", "__pycache__",
26
+ ".venv", "venv", ".tox", ".mypy_cache", ".pytest_cache",
27
+ "target", ".gradle", ".idea", ".vscode",
28
+ ]);
29
+
30
+ const MAX_INLINE_FILE_CHARS = 100_000;
31
+ const MAX_TREE_ENTRIES = 200;
32
+
33
+ export interface GitHubUrlInfo {
34
+ owner: string;
35
+ repo: string;
36
+ ref?: string;
37
+ refIsFullSha: boolean;
38
+ path?: string;
39
+ type: "root" | "blob" | "tree";
40
+ }
41
+
42
+ interface CachedClone {
43
+ destination: CloneDestination;
44
+ clonePromise: Promise<string | null>;
45
+ }
46
+
47
+ interface CloneDestination {
48
+ rootPath: string;
49
+ localPath: string;
50
+ }
51
+
52
+ interface GitHubCloneConfig {
53
+ enabled: boolean;
54
+ maxRepoSizeMB: number;
55
+ cloneTimeoutSeconds: number;
56
+ clonePath: string;
57
+ }
58
+
59
+ const cloneCache = new Map<string, CachedClone>();
60
+
61
+ let cachedConfig: GitHubCloneConfig | null = null;
62
+
63
+ function normalizeEnabled(value: unknown, fallback: boolean): boolean {
64
+ return typeof value === "boolean" ? value : fallback;
65
+ }
66
+
67
+ function normalizePositiveNumber(value: unknown, fallback: number): number {
68
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
69
+ return value > 0 ? value : fallback;
70
+ }
71
+
72
+ function expandPath(value: string): string {
73
+ let expanded = value;
74
+ // Expand ~ at the start of the path
75
+ if (expanded.startsWith("~/") || expanded === "~") {
76
+ expanded = expanded.replace(/^~/, process.env.HOME || process.env.USERPROFILE || "");
77
+ }
78
+ // Expand environment variables like $HOME, $USER, etc.
79
+ expanded = expanded.replace(/\$([A-Z_][A-Z0-9_]*)/gi, (match, varName) => {
80
+ return process.env[varName] ?? match;
81
+ });
82
+ return expanded;
83
+ }
84
+
85
+ function normalizeClonePath(value: unknown, fallback: string): string {
86
+ if (typeof value !== "string") return fallback;
87
+ const normalized = value.trim();
88
+ if (normalized.length === 0) return fallback;
89
+ return expandPath(normalized);
90
+ }
91
+
92
+ function loadGitHubConfig(): GitHubCloneConfig {
93
+ if (cachedConfig) return cachedConfig;
94
+
95
+ const defaults: GitHubCloneConfig = {
96
+ enabled: true,
97
+ maxRepoSizeMB: 350,
98
+ cloneTimeoutSeconds: 30,
99
+ clonePath: "/tmp/pi-github-repos",
100
+ };
101
+
102
+ if (!existsSync(CONFIG_PATH)) {
103
+ cachedConfig = defaults;
104
+ return cachedConfig;
105
+ }
106
+
107
+ const rawText = readFileSync(CONFIG_PATH, "utf-8");
108
+ let raw: { githubClone?: { enabled?: unknown; maxRepoSizeMB?: unknown; cloneTimeoutSeconds?: unknown; clonePath?: unknown } };
109
+ try {
110
+ raw = JSON.parse(rawText) as { githubClone?: { enabled?: unknown; maxRepoSizeMB?: unknown; cloneTimeoutSeconds?: unknown; clonePath?: unknown } };
111
+ } catch (err) {
112
+ const message = err instanceof Error ? err.message : String(err);
113
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
114
+ }
115
+
116
+ const gc = raw.githubClone ?? {};
117
+ cachedConfig = {
118
+ enabled: normalizeEnabled(gc.enabled, defaults.enabled),
119
+ maxRepoSizeMB: normalizePositiveNumber(gc.maxRepoSizeMB, defaults.maxRepoSizeMB),
120
+ cloneTimeoutSeconds: normalizePositiveNumber(gc.cloneTimeoutSeconds, defaults.cloneTimeoutSeconds),
121
+ clonePath: normalizeClonePath(gc.clonePath, defaults.clonePath),
122
+ };
123
+ return cachedConfig;
124
+ }
125
+
126
+ const NON_CODE_SEGMENTS = new Set([
127
+ "issues", "pull", "pulls", "discussions", "releases", "wiki",
128
+ "actions", "settings", "security", "projects", "graphs",
129
+ "compare", "commits", "tags", "branches", "stargazers",
130
+ "watchers", "network", "forks", "milestone", "labels",
131
+ "packages", "codespaces", "contribute", "community",
132
+ "sponsors", "invitations", "notifications", "insights",
133
+ ]);
134
+
135
+ export function parseGitHubUrl(url: string): GitHubUrlInfo | null {
136
+ let parsed: URL;
137
+ try {
138
+ parsed = new URL(url);
139
+ } catch {
140
+ return null;
141
+ }
142
+
143
+ const host = parsed.hostname.toLowerCase();
144
+ if (host !== "github.com" && host !== "www.github.com") return null;
145
+
146
+ const segments: string[] = [];
147
+ for (const segment of parsed.pathname.split("/").filter(Boolean)) {
148
+ try {
149
+ segments.push(decodeURIComponent(segment));
150
+ } catch {
151
+ return null;
152
+ }
153
+ }
154
+ if (segments.length < 2) return null;
155
+
156
+ const owner = segments[0];
157
+ const repo = segments[1].replace(/\.git$/, "");
158
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(owner)) return null;
159
+ if (owner.includes("--")) return null;
160
+ if (!/^[A-Za-z0-9._-]{1,100}$/.test(repo) || repo === "." || repo === "..") return null;
161
+
162
+ if (NON_CODE_SEGMENTS.has(segments[2]?.toLowerCase())) return null;
163
+
164
+ if (segments.length === 2) {
165
+ return { owner, repo, refIsFullSha: false, type: "root" };
166
+ }
167
+
168
+ const action = segments[2];
169
+ if (action !== "blob" && action !== "tree") return null;
170
+ if (segments.length < 4) return null;
171
+
172
+ const ref = segments[3];
173
+ if (ref.length === 0 || ref.length > 1024 || /[\0-\x1f\x7f]/.test(ref)) return null;
174
+ const refIsFullSha = /^[0-9a-f]{40}$/.test(ref);
175
+ const pathParts = segments.slice(4);
176
+ const path = pathParts.length > 0 ? pathParts.join("/") : "";
177
+
178
+ return {
179
+ owner,
180
+ repo,
181
+ ref,
182
+ refIsFullSha,
183
+ path,
184
+ type: action as "blob" | "tree",
185
+ };
186
+ }
187
+
188
+ function cacheKey(owner: string, repo: string, ref?: string): string {
189
+ return ref ? `${owner}/${repo}@${ref}` : `${owner}/${repo}`;
190
+ }
191
+
192
+ function cloneDestination(config: GitHubCloneConfig, owner: string, repo: string, ref?: string): CloneDestination | null {
193
+ try {
194
+ mkdirSync(resolvePath(config.clonePath), { recursive: true });
195
+ const rootPath = realpathSync(resolvePath(config.clonePath));
196
+ const digest = createHash("sha256").update(JSON.stringify([owner, repo, ref ?? null])).digest("hex");
197
+ const localPath = resolvePath(rootPath, digest);
198
+ if (dirname(localPath) !== rootPath) return null;
199
+ return { rootPath, localPath };
200
+ } catch {
201
+ return null;
202
+ }
203
+ }
204
+
205
+ function removeCloneDestination(destination: CloneDestination): boolean {
206
+ const rootPath = resolvePath(destination.rootPath);
207
+ const localPath = resolvePath(destination.localPath);
208
+ if (dirname(localPath) !== rootPath || !/^[0-9a-f]{64}$/.test(basename(localPath))) return false;
209
+ try {
210
+ const entry = lstatSync(localPath);
211
+ if (entry.isSymbolicLink()) unlinkSync(localPath);
212
+ else rmSync(localPath, { recursive: true, force: true });
213
+ return true;
214
+ } catch (err) {
215
+ if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") return true;
216
+ return false;
217
+ }
218
+ }
219
+
220
+ const PROCESS_KILL_GRACE_MS = 3000;
221
+
222
+ function terminateProcessTree(child: ChildProcess): void {
223
+ const pid = child.pid;
224
+ if (!pid) return;
225
+
226
+ if (process.platform === "win32") {
227
+ const killer = execFile(
228
+ "taskkill",
229
+ ["/pid", String(pid), "/T", "/F"],
230
+ { windowsHide: true },
231
+ (err) => {
232
+ if (err) child.kill();
233
+ },
234
+ );
235
+ killer.unref();
236
+ return;
237
+ }
238
+
239
+ try {
240
+ // Clone commands run in their own process group so git/gh helpers cannot
241
+ // survive a timeout or cancellation and keep reading from the host TTY.
242
+ process.kill(-pid, "SIGTERM");
243
+ } catch {
244
+ child.kill();
245
+ }
246
+
247
+ // A credential helper may handle or ignore SIGTERM. Escalate against the
248
+ // entire process group so neither git nor any descendant can block forever.
249
+ const forceKill = setTimeout(() => {
250
+ try {
251
+ process.kill(-pid, "SIGKILL");
252
+ } catch {
253
+ child.kill("SIGKILL");
254
+ }
255
+ }, PROCESS_KILL_GRACE_MS);
256
+ forceKill.unref();
257
+ }
258
+
259
+ function execClone(args: string[], destination: CloneDestination, timeoutMs: number, signal?: AbortSignal): Promise<string | null> {
260
+ return new Promise((resolve) => {
261
+ const { localPath } = destination;
262
+ let settled = false;
263
+ let timeout: ReturnType<typeof setTimeout> | undefined;
264
+ let onAbort: (() => void) | undefined;
265
+
266
+ const finish = (success: boolean) => {
267
+ if (settled) return;
268
+ settled = true;
269
+ if (timeout) clearTimeout(timeout);
270
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
271
+
272
+ if (!success) {
273
+ removeCloneDestination(destination);
274
+ resolve(null);
275
+ return;
276
+ }
277
+ resolve(localPath);
278
+ };
279
+
280
+ const child = spawn(args[0], args.slice(1), {
281
+ detached: process.platform !== "win32",
282
+ env: {
283
+ ...process.env,
284
+ GIT_TERMINAL_PROMPT: "0",
285
+ GCM_INTERACTIVE: "Never",
286
+ GH_PROMPT_DISABLED: "1",
287
+ },
288
+ stdio: "ignore",
289
+ windowsHide: true,
290
+ });
291
+
292
+ child.once("error", () => finish(false));
293
+ child.once("close", (code) => finish(code === 0));
294
+
295
+ timeout = setTimeout(() => terminateProcessTree(child), timeoutMs);
296
+ timeout.unref();
297
+
298
+ if (signal) {
299
+ onAbort = () => {
300
+ if (timeout) clearTimeout(timeout);
301
+ terminateProcessTree(child);
302
+ };
303
+ if (signal.aborted) onAbort();
304
+ else signal.addEventListener("abort", onAbort, { once: true });
305
+ }
306
+ });
307
+ }
308
+
309
+ async function cloneRepo(
310
+ owner: string,
311
+ repo: string,
312
+ ref: string | undefined,
313
+ config: GitHubCloneConfig,
314
+ destination: CloneDestination,
315
+ signal?: AbortSignal,
316
+ ): Promise<string | null> {
317
+ const { localPath } = destination;
318
+ if (!removeCloneDestination(destination)) return null;
319
+
320
+ const timeoutMs = config.cloneTimeoutSeconds * 1000;
321
+ const hasGh = await checkGhAvailable();
322
+
323
+ if (hasGh) {
324
+ const args = ["gh", "repo", "clone", `${owner}/${repo}`, localPath, "--", "--depth", "1", "--single-branch"];
325
+ if (ref) args.push("--branch", ref);
326
+ return execClone(args, destination, timeoutMs, signal);
327
+ }
328
+
329
+ showGhHint();
330
+
331
+ const gitUrl = `https://github.com/${owner}/${repo}.git`;
332
+ const args = ["git", "clone", "--depth", "1", "--single-branch"];
333
+ if (ref) args.push("--branch", ref);
334
+ args.push(gitUrl, localPath);
335
+ return execClone(args, destination, timeoutMs, signal);
336
+ }
337
+
338
+ function isBinaryFile(filePath: string): boolean {
339
+ const ext = extname(filePath).toLowerCase();
340
+ if (BINARY_EXTENSIONS.has(ext)) return true;
341
+
342
+ let fd: number;
343
+ try {
344
+ fd = openSync(filePath, "r");
345
+ } catch {
346
+ return false;
347
+ }
348
+ try {
349
+ const buf = Buffer.alloc(512);
350
+ const bytesRead = readSync(fd, buf, 0, 512, 0);
351
+ for (let i = 0; i < bytesRead; i++) {
352
+ if (buf[i] === 0) return true;
353
+ }
354
+ } catch {
355
+ return false;
356
+ } finally {
357
+ closeSync(fd);
358
+ }
359
+
360
+ return false;
361
+ }
362
+
363
+ function formatFileSize(bytes: number): string {
364
+ if (bytes < 1024) return `${bytes} B`;
365
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
366
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
367
+ }
368
+
369
+ function resolveWithinRepo(rootPath: string, relativePath: string): string | null {
370
+ const normalizedRoot = resolvePath(rootPath);
371
+ const candidate = resolvePath(normalizedRoot, relativePath);
372
+ if (candidate !== normalizedRoot) {
373
+ const rootPrefix = normalizedRoot.endsWith(pathSep) ? normalizedRoot : normalizedRoot + pathSep;
374
+ if (!candidate.startsWith(rootPrefix)) return null;
375
+ }
376
+
377
+ if (!existsSync(candidate)) return candidate;
378
+
379
+ try {
380
+ const realRoot = realpathSync(normalizedRoot);
381
+ const realCandidate = realpathSync(candidate);
382
+ if (realCandidate === realRoot) return candidate;
383
+ const realRootPrefix = realRoot.endsWith(pathSep) ? realRoot : realRoot + pathSep;
384
+ return realCandidate.startsWith(realRootPrefix) ? candidate : null;
385
+ } catch {
386
+ return null;
387
+ }
388
+ }
389
+
390
+ function readTextFile(path: string): string | null {
391
+ try {
392
+ return readFileSync(path, "utf-8");
393
+ } catch {
394
+ return null;
395
+ }
396
+ }
397
+
398
+ function buildTree(rootPath: string): string {
399
+ const entries: string[] = [];
400
+
401
+ function walk(dir: string, relPath: string): void {
402
+ if (entries.length >= MAX_TREE_ENTRIES) return;
403
+
404
+ let items: string[];
405
+ try {
406
+ items = readdirSync(dir).sort();
407
+ } catch {
408
+ return;
409
+ }
410
+
411
+ for (const item of items) {
412
+ if (entries.length >= MAX_TREE_ENTRIES) return;
413
+ if (item === ".git") continue;
414
+
415
+ const rel = relPath ? `${relPath}/${item}` : item;
416
+ const safePath = resolveWithinRepo(rootPath, rel);
417
+ if (!safePath) {
418
+ entries.push(`${rel} [outside repo skipped]`);
419
+ continue;
420
+ }
421
+
422
+ let stat;
423
+ try {
424
+ stat = statSync(safePath);
425
+ } catch {
426
+ continue;
427
+ }
428
+
429
+ if (stat.isDirectory()) {
430
+ if (NOISE_DIRS.has(item)) {
431
+ entries.push(`${rel}/ [skipped]`);
432
+ continue;
433
+ }
434
+ entries.push(`${rel}/`);
435
+ walk(safePath, rel);
436
+ } else {
437
+ entries.push(rel);
438
+ }
439
+ }
440
+ }
441
+
442
+ walk(rootPath, "");
443
+
444
+ if (entries.length >= MAX_TREE_ENTRIES) {
445
+ entries.push(`... (truncated at ${MAX_TREE_ENTRIES} entries)`);
446
+ }
447
+
448
+ return entries.join("\n");
449
+ }
450
+
451
+ function buildDirListing(rootPath: string, subPath: string): string {
452
+ const targetPath = resolveWithinRepo(rootPath, subPath);
453
+ if (!targetPath) return "(path escapes repository root)";
454
+ const lines: string[] = [];
455
+
456
+ let items: string[];
457
+ try {
458
+ items = readdirSync(targetPath).sort();
459
+ } catch {
460
+ return "(directory not readable)";
461
+ }
462
+
463
+ for (const item of items) {
464
+ if (item === ".git") continue;
465
+ const rel = subPath ? `${subPath}/${item}` : item;
466
+ const safePath = resolveWithinRepo(rootPath, rel);
467
+ if (!safePath) {
468
+ lines.push(` ${item} (outside repo)`);
469
+ continue;
470
+ }
471
+ try {
472
+ const stat = statSync(safePath);
473
+ if (stat.isDirectory()) {
474
+ lines.push(` ${item}/`);
475
+ } else {
476
+ lines.push(` ${item} (${formatFileSize(stat.size)})`);
477
+ }
478
+ } catch {
479
+ lines.push(` ${item} (unreadable)`);
480
+ }
481
+ }
482
+
483
+ return lines.join("\n");
484
+ }
485
+
486
+ function readReadme(localPath: string): string | null {
487
+ const candidates = ["README.md", "readme.md", "README", "README.txt", "README.rst"];
488
+ for (const name of candidates) {
489
+ const readmePath = join(localPath, name);
490
+ if (existsSync(readmePath)) {
491
+ try {
492
+ const content = readFileSync(readmePath, "utf-8");
493
+ return content.length > 8192 ? content.slice(0, 8192) + "\n\n[README truncated at 8K chars]" : content;
494
+ } catch {
495
+ continue;
496
+ }
497
+ }
498
+ }
499
+ return null;
500
+ }
501
+
502
+ function generateContent(localPath: string, info: GitHubUrlInfo): string {
503
+ const lines: string[] = [];
504
+ lines.push(`Repository cloned to: ${localPath}`);
505
+ lines.push("");
506
+
507
+ if (info.type === "root") {
508
+ lines.push("## Structure");
509
+ lines.push(buildTree(localPath));
510
+ lines.push("");
511
+
512
+ const readme = readReadme(localPath);
513
+ if (readme) {
514
+ lines.push("## README.md");
515
+ lines.push(readme);
516
+ lines.push("");
517
+ }
518
+
519
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
520
+ return lines.join("\n");
521
+ }
522
+
523
+ if (info.type === "tree") {
524
+ const dirPath = info.path || "";
525
+ const fullDirPath = resolveWithinRepo(localPath, dirPath);
526
+
527
+ if (!fullDirPath || !existsSync(fullDirPath)) {
528
+ lines.push(`Path \`${dirPath}\` not found in clone. Showing repository root instead.`);
529
+ lines.push("");
530
+ lines.push("## Structure");
531
+ lines.push(buildTree(localPath));
532
+ } else {
533
+ lines.push(`## ${dirPath || "/"}`);
534
+ lines.push(buildDirListing(localPath, dirPath));
535
+ }
536
+
537
+ lines.push("");
538
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
539
+ return lines.join("\n");
540
+ }
541
+
542
+ if (info.type === "blob") {
543
+ const filePath = info.path || "";
544
+ const fullFilePath = resolveWithinRepo(localPath, filePath);
545
+
546
+ if (!fullFilePath || !existsSync(fullFilePath)) {
547
+ lines.push(`Path \`${filePath}\` not found in clone. Showing repository root instead.`);
548
+ lines.push("");
549
+ lines.push("## Structure");
550
+ lines.push(buildTree(localPath));
551
+ lines.push("");
552
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
553
+ return lines.join("\n");
554
+ }
555
+
556
+ let stat: ReturnType<typeof statSync>;
557
+ try {
558
+ stat = statSync(fullFilePath);
559
+ } catch (err) {
560
+ const message = err instanceof Error ? err.message : String(err);
561
+ lines.push(`Could not inspect \`${filePath}\`: ${message}`);
562
+ lines.push("");
563
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
564
+ return lines.join("\n");
565
+ }
566
+
567
+ if (stat.isDirectory()) {
568
+ lines.push(`## ${filePath || "/"}`);
569
+ lines.push(buildDirListing(localPath, filePath));
570
+ lines.push("");
571
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
572
+ return lines.join("\n");
573
+ }
574
+
575
+ if (isBinaryFile(fullFilePath)) {
576
+ const ext = extname(filePath).replace(".", "");
577
+ lines.push(`## ${filePath}`);
578
+ lines.push(`Binary file (${ext}, ${formatFileSize(stat.size)}). Use \`read\` or \`bash\` tools at the path above to inspect.`);
579
+ return lines.join("\n");
580
+ }
581
+
582
+ const content = readTextFile(fullFilePath);
583
+ if (content === null) {
584
+ lines.push(`Could not read \`${filePath}\` as UTF-8 text.`);
585
+ lines.push("");
586
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
587
+ return lines.join("\n");
588
+ }
589
+ lines.push(`## ${filePath}`);
590
+
591
+ if (content.length > MAX_INLINE_FILE_CHARS) {
592
+ lines.push(content.slice(0, MAX_INLINE_FILE_CHARS));
593
+ lines.push("");
594
+ lines.push(`[File truncated at 100K chars. Full file: ${fullFilePath}]`);
595
+ } else {
596
+ lines.push(content);
597
+ }
598
+
599
+ lines.push("");
600
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
601
+ return lines.join("\n");
602
+ }
603
+
604
+ return lines.join("\n");
605
+ }
606
+
607
+ async function awaitCachedClone(
608
+ cached: CachedClone,
609
+ url: string,
610
+ owner: string,
611
+ repo: string,
612
+ info: GitHubUrlInfo,
613
+ signal?: AbortSignal,
614
+ ): Promise<ExtractedContent | null> {
615
+ if (signal?.aborted) return null;
616
+ const result = await cached.clonePromise;
617
+ if (signal?.aborted) return null;
618
+ if (result) {
619
+ const content = generateContent(result, info);
620
+ const title = info.path ? `${owner}/${repo} - ${info.path}` : `${owner}/${repo}`;
621
+ return { url, title, content, error: null };
622
+ }
623
+ return fetchViaApi(url, owner, repo, info);
624
+ }
625
+
626
+ export async function extractGitHub(
627
+ url: string,
628
+ signal?: AbortSignal,
629
+ forceClone?: boolean,
630
+ ): Promise<ExtractedContent | null> {
631
+ const info = parseGitHubUrl(url);
632
+ if (!info) return null;
633
+
634
+ if (signal?.aborted) return null;
635
+
636
+ const config = loadGitHubConfig();
637
+ if (!config.enabled) return null;
638
+
639
+ const { owner, repo } = info;
640
+ const key = cacheKey(owner, repo, info.ref);
641
+
642
+ const cached = cloneCache.get(key);
643
+ if (cached) return awaitCachedClone(cached, url, owner, repo, info, signal);
644
+
645
+ if (info.refIsFullSha) {
646
+ if (signal?.aborted) return null;
647
+ const sizeNote = `Note: Commit SHA URLs use the GitHub API instead of cloning.`;
648
+ return fetchViaApi(url, owner, repo, info, sizeNote);
649
+ }
650
+
651
+ const activityId = activityMonitor.logStart({ type: "fetch", url: `github.com/${owner}/${repo}` });
652
+
653
+ if (!forceClone) {
654
+ const sizeKB = await checkRepoSize(owner, repo);
655
+ if (signal?.aborted) {
656
+ activityMonitor.logComplete(activityId, 0);
657
+ return null;
658
+ }
659
+ if (sizeKB !== null) {
660
+ const sizeMB = sizeKB / 1024;
661
+ if (sizeMB > config.maxRepoSizeMB) {
662
+ if (signal?.aborted) {
663
+ activityMonitor.logComplete(activityId, 0);
664
+ return null;
665
+ }
666
+ const sizeNote =
667
+ `Note: Repository is ${Math.round(sizeMB)}MB (threshold: ${config.maxRepoSizeMB}MB). ` +
668
+ `Showing API-fetched content instead of full clone. Ask the user if they'd like to clone the full repo -- ` +
669
+ `if yes, call fetch_content again with the same URL and add forceClone: true to the params.`;
670
+ const apiView = await fetchViaApi(url, owner, repo, info, sizeNote);
671
+ if (apiView) {
672
+ activityMonitor.logComplete(activityId, 200);
673
+ return apiView;
674
+ }
675
+ activityMonitor.logError(activityId, "api fallback unavailable for oversized repository");
676
+ return null;
677
+ }
678
+ }
679
+ }
680
+
681
+ if (signal?.aborted) {
682
+ activityMonitor.logComplete(activityId, 0);
683
+ return null;
684
+ }
685
+
686
+ // Re-check: another concurrent caller may have started a clone while we awaited the size check
687
+ const cachedAfterSizeCheck = cloneCache.get(key);
688
+ if (cachedAfterSizeCheck) {
689
+ const cachedResult = await awaitCachedClone(cachedAfterSizeCheck, url, owner, repo, info, signal);
690
+ if (signal?.aborted) {
691
+ activityMonitor.logComplete(activityId, 0);
692
+ } else if (cachedResult) {
693
+ activityMonitor.logComplete(activityId, 200);
694
+ } else {
695
+ activityMonitor.logError(activityId, "clone failed");
696
+ }
697
+ return cachedResult;
698
+ }
699
+
700
+ const destination = cloneDestination(config, owner, repo, info.ref);
701
+ if (!destination) {
702
+ const apiFallback = await fetchViaApi(url, owner, repo, info);
703
+ if (apiFallback) activityMonitor.logComplete(activityId, 200);
704
+ else activityMonitor.logError(activityId, "invalid clone destination");
705
+ return apiFallback;
706
+ }
707
+ const clonePromise = cloneRepo(owner, repo, info.ref, config, destination, signal);
708
+ cloneCache.set(key, { destination, clonePromise });
709
+
710
+ const result = await clonePromise;
711
+ if (signal?.aborted) {
712
+ if (!result) cloneCache.delete(key);
713
+ activityMonitor.logComplete(activityId, 0);
714
+ return null;
715
+ }
716
+
717
+ if (!result) {
718
+ cloneCache.delete(key);
719
+ if (signal?.aborted) {
720
+ activityMonitor.logComplete(activityId, 0);
721
+ return null;
722
+ }
723
+
724
+ const apiFallback = await fetchViaApi(url, owner, repo, info);
725
+ if (apiFallback) {
726
+ activityMonitor.logComplete(activityId, 200);
727
+ return apiFallback;
728
+ }
729
+
730
+ activityMonitor.logError(activityId, "clone and API fallback failed");
731
+ return null;
732
+ }
733
+
734
+ activityMonitor.logComplete(activityId, 200);
735
+ const content = generateContent(result, info);
736
+ const title = info.path ? `${owner}/${repo} - ${info.path}` : `${owner}/${repo}`;
737
+ return { url, title, content, error: null };
738
+ }
739
+
740
+ export function clearCloneCache(): void {
741
+ for (const entry of cloneCache.values()) {
742
+ removeCloneDestination(entry.destination);
743
+ }
744
+ cloneCache.clear();
745
+ cachedConfig = null;
746
+ }