@asterxsk/kiln 0.4.0 → 0.4.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 (259) hide show
  1. package/README.md +155 -155
  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 +27 -27
  6. package/agent/extensions/ask-user/install.sh +24 -24
  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 +27 -27
  14. package/agent/extensions/background-terminals/install.sh +24 -24
  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/README.md +31 -31
  32. package/agent/extensions/destructive/index.ts +88 -88
  33. package/agent/extensions/destructive/install.ps1 +27 -27
  34. package/agent/extensions/destructive/install.sh +24 -24
  35. package/agent/extensions/file-search/index.spec.ts +443 -443
  36. package/agent/extensions/file-search/index.ts +459 -459
  37. package/agent/extensions/file-search/install.ps1 +27 -27
  38. package/agent/extensions/file-search/install.sh +24 -24
  39. package/agent/extensions/file-search/package-lock.json +2253 -2253
  40. package/agent/extensions/file-search/package.json +23 -23
  41. package/agent/extensions/file-search/src/args.ts +122 -122
  42. package/agent/extensions/file-search/src/binaries.ts +422 -422
  43. package/agent/extensions/file-search/src/output.ts +126 -126
  44. package/agent/extensions/file-search/src/process.ts +146 -146
  45. package/agent/extensions/file-search/src/prompt.ts +52 -52
  46. package/agent/extensions/file-search/tsconfig.json +7 -7
  47. package/agent/extensions/goal/README.md +50 -50
  48. package/agent/extensions/goal/index.ts +155 -155
  49. package/agent/extensions/goal/install.ps1 +27 -27
  50. package/agent/extensions/goal/install.sh +24 -24
  51. package/agent/extensions/kiln-update/README.md +38 -25
  52. package/agent/extensions/kiln-update/index.ts +177 -99
  53. package/agent/extensions/modelconf/PLAN.md +915 -915
  54. package/agent/extensions/modelconf/README.md +66 -66
  55. package/agent/extensions/modelconf/index.ts +296 -296
  56. package/agent/extensions/modelconf/install.ps1 +27 -27
  57. package/agent/extensions/modelconf/install.sh +24 -24
  58. package/agent/extensions/modelconf/package-lock.json +1809 -1809
  59. package/agent/extensions/modelconf/package.json +13 -13
  60. package/agent/extensions/modelconf/src/fuzzy.ts +26 -26
  61. package/agent/extensions/modelconf/src/glob.ts +13 -13
  62. package/agent/extensions/modelconf/src/persistence.test.ts +46 -46
  63. package/agent/extensions/modelconf/src/persistence.ts +164 -164
  64. package/agent/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -75
  65. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  66. package/agent/extensions/modelconf/tsconfig.json +15 -15
  67. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  68. package/agent/extensions/pi-web-access/LICENSE +21 -21
  69. package/agent/extensions/pi-web-access/README.md +470 -470
  70. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  71. package/agent/extensions/pi-web-access/activity.ts +101 -101
  72. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  73. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  74. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  75. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  76. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  77. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  78. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  79. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  80. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  81. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  82. package/agent/extensions/pi-web-access/exa.ts +526 -526
  83. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  84. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  85. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  86. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  87. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  88. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  89. package/agent/extensions/pi-web-access/gemini-search.ts +21 -21
  90. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  91. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  92. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  93. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  94. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  95. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  96. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  97. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  98. package/agent/extensions/pi-web-access/package.json +64 -64
  99. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  100. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  101. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  102. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  103. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  104. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  105. package/agent/extensions/pi-web-access/search-types.ts +20 -20
  106. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  107. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  108. package/agent/extensions/pi-web-access/storage.ts +521 -521
  109. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  110. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  111. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  112. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  113. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  114. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  115. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  116. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  117. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  118. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  119. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  120. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  121. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  122. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  123. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  124. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  125. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  126. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  127. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  128. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  129. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  130. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  131. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  132. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  133. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  134. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  135. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  136. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  137. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  138. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  139. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  140. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  141. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  142. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  143. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  144. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  145. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  146. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  147. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  148. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  149. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  150. package/agent/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -106
  151. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  152. package/agent/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -66
  153. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  154. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  155. package/agent/extensions/pi-web-access/utils.ts +451 -451
  156. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  157. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  158. package/agent/extensions/shared/activity-status.ts +31 -31
  159. package/agent/extensions/shared/child-session.test.ts +270 -270
  160. package/agent/extensions/shared/child-session.ts +148 -148
  161. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  162. package/agent/extensions/shared/context-utilization.ts +47 -47
  163. package/agent/extensions/shared/dashboard-state.ts +99 -99
  164. package/agent/extensions/shared/install.ps1 +27 -27
  165. package/agent/extensions/shared/install.sh +24 -24
  166. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  167. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  168. package/agent/extensions/skillsconf/README.md +74 -74
  169. package/agent/extensions/skillsconf/index.ts +92 -92
  170. package/agent/extensions/skillsconf/install.ps1 +27 -27
  171. package/agent/extensions/skillsconf/install.sh +24 -24
  172. package/agent/extensions/skillsconf/package-lock.json +1809 -1809
  173. package/agent/extensions/skillsconf/package.json +18 -18
  174. package/agent/extensions/skillsconf/src/delete-skill.test.ts +64 -64
  175. package/agent/extensions/skillsconf/src/delete-skill.ts +45 -45
  176. package/agent/extensions/skillsconf/src/filter.test.ts +80 -80
  177. package/agent/extensions/skillsconf/src/filter.ts +74 -74
  178. package/agent/extensions/skillsconf/src/fuzzy.ts +26 -26
  179. package/agent/extensions/skillsconf/src/persistence.test.ts +72 -72
  180. package/agent/extensions/skillsconf/src/persistence.ts +169 -169
  181. package/agent/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -337
  182. package/agent/extensions/skillsconf/src/ui/SkillConfView.ts +758 -758
  183. package/agent/extensions/skillsconf/src/ui/text-input.ts +91 -91
  184. package/agent/extensions/skillsconf/src/ui/tui-helpers.ts +144 -144
  185. package/agent/extensions/skillsconf/tsconfig.json +15 -15
  186. package/agent/extensions/statusline/index.ts +273 -282
  187. package/agent/extensions/statusline/install.ps1 +27 -27
  188. package/agent/extensions/statusline/install.sh +24 -24
  189. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  190. package/agent/extensions/subagents/claude.test.ts +119 -119
  191. package/agent/extensions/subagents/codex.test.ts +102 -102
  192. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  193. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  194. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  195. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  196. package/agent/extensions/subagents/index.ts +779 -779
  197. package/agent/extensions/subagents/install.ps1 +27 -27
  198. package/agent/extensions/subagents/install.sh +24 -24
  199. package/agent/extensions/subagents/manager.test.ts +276 -276
  200. package/agent/extensions/subagents/package-lock.json +2244 -2244
  201. package/agent/extensions/subagents/package.json +19 -19
  202. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  203. package/agent/extensions/subagents/src/backend.ts +73 -73
  204. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  205. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  206. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  207. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  208. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  209. package/agent/extensions/subagents/src/domain.ts +253 -253
  210. package/agent/extensions/subagents/src/format.ts +74 -74
  211. package/agent/extensions/subagents/src/manager.ts +736 -736
  212. package/agent/extensions/subagents/src/prompt.ts +92 -92
  213. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  214. package/agent/extensions/subagents/src/runtime.ts +53 -53
  215. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  216. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  217. package/agent/extensions/subagents/takeover.test.ts +29 -29
  218. package/agent/extensions/subagents/tsconfig.json +7 -7
  219. package/agent/extensions/todo/AGENTS.md +38 -38
  220. package/agent/extensions/todo/LICENSE +21 -21
  221. package/agent/extensions/todo/config.ts +55 -55
  222. package/agent/extensions/todo/index.ts +151 -151
  223. package/agent/extensions/todo/install.ps1 +27 -27
  224. package/agent/extensions/todo/install.sh +24 -24
  225. package/agent/extensions/todo/locales/de.json +17 -17
  226. package/agent/extensions/todo/locales/en.json +15 -15
  227. package/agent/extensions/todo/locales/es.json +17 -17
  228. package/agent/extensions/todo/locales/fr.json +17 -17
  229. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  230. package/agent/extensions/todo/locales/pt.json +17 -17
  231. package/agent/extensions/todo/locales/ru.json +17 -17
  232. package/agent/extensions/todo/locales/uk.json +17 -17
  233. package/agent/extensions/todo/locales/zh.json +17 -17
  234. package/agent/extensions/todo/package-lock.json +3358 -3358
  235. package/agent/extensions/todo/package.json +67 -67
  236. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  237. package/agent/extensions/todo/state/invariants.ts +20 -20
  238. package/agent/extensions/todo/state/replay.ts +38 -38
  239. package/agent/extensions/todo/state/selectors.ts +107 -107
  240. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  241. package/agent/extensions/todo/state/state.ts +18 -18
  242. package/agent/extensions/todo/state/store.ts +82 -82
  243. package/agent/extensions/todo/state/task-graph.ts +57 -57
  244. package/agent/extensions/todo/todo-overlay.ts +200 -200
  245. package/agent/extensions/todo/todo.ts +155 -155
  246. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  247. package/agent/extensions/todo/tool/types.ts +206 -206
  248. package/agent/extensions/todo/view/format.ts +177 -177
  249. package/agent/extensions/trim-context/README.md +54 -54
  250. package/agent/extensions/trim-context/index.ts +487 -487
  251. package/agent/extensions/trim-context/install.ps1 +27 -27
  252. package/agent/extensions/trim-context/install.sh +24 -24
  253. package/agent/keybindings.json +7 -7
  254. package/agent/version.txt +1 -1
  255. package/bin/kiln.js +20 -13
  256. package/package.json +1 -1
  257. package/agent/extensions/taste/index.ts +0 -443
  258. package/agent/extensions/taste/install.ps1 +0 -27
  259. package/agent/extensions/taste/install.sh +0 -24
@@ -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
+ }