@abhishek944/pi-web-access 0.0.0-stage → 0.1.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 (201) hide show
  1. package/ASTACK.md +23 -0
  2. package/CHANGELOG.md +1289 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1215 -2
  5. package/SECURITY.md +5 -0
  6. package/abortable.ts +17 -0
  7. package/activity.ts +101 -0
  8. package/anysearch.ts +188 -0
  9. package/auth-fetch.ts +152 -0
  10. package/baizhi.ts +124 -0
  11. package/banner.png +0 -0
  12. package/bocha.ts +203 -0
  13. package/brave-rate-limit.ts +176 -0
  14. package/brave.ts +247 -0
  15. package/brightdata-unlocker.ts +272 -0
  16. package/ceramic.ts +220 -0
  17. package/chrome-cookies.ts +752 -0
  18. package/cloudflare-search.ts +237 -0
  19. package/content-find.ts +255 -0
  20. package/crawl4ai.ts +196 -0
  21. package/credential-source.ts +242 -0
  22. package/curator-page.ts +3607 -0
  23. package/curator-run.ts +45 -0
  24. package/curator-server.ts +761 -0
  25. package/custom-search.ts +226 -0
  26. package/data-uri-sanitize.ts +406 -0
  27. package/datalab-pdf-extract.ts +568 -0
  28. package/declared-web-links.ts +173 -0
  29. package/deepseek.ts +377 -0
  30. package/degoog.ts +323 -0
  31. package/dist/index.js +28286 -0
  32. package/dist/mcp-cli.js +29186 -0
  33. package/dist/pi-mcp.js +20855 -0
  34. package/dist/types/abortable.d.ts +2 -0
  35. package/dist/types/activity.d.ts +33 -0
  36. package/dist/types/anysearch.d.ts +7 -0
  37. package/dist/types/auth-fetch.d.ts +14 -0
  38. package/dist/types/baizhi.d.ts +3 -0
  39. package/dist/types/bocha.d.ts +3 -0
  40. package/dist/types/brave-rate-limit.d.ts +35 -0
  41. package/dist/types/brave.d.ts +3 -0
  42. package/dist/types/brightdata-unlocker.d.ts +11 -0
  43. package/dist/types/ceramic.d.ts +3 -0
  44. package/dist/types/chrome-cookies.d.ts +44 -0
  45. package/dist/types/cloudflare-search.d.ts +4 -0
  46. package/dist/types/content-find.d.ts +10 -0
  47. package/dist/types/crawl4ai.d.ts +8 -0
  48. package/dist/types/credential-source.d.ts +29 -0
  49. package/dist/types/curator-page.d.ts +5 -0
  50. package/dist/types/curator-run.d.ts +10 -0
  51. package/dist/types/curator-server.d.ts +72 -0
  52. package/dist/types/custom-search.d.ts +22 -0
  53. package/dist/types/data-uri-sanitize.d.ts +20 -0
  54. package/dist/types/datalab-pdf-extract.d.ts +59 -0
  55. package/dist/types/declared-web-links.d.ts +7 -0
  56. package/dist/types/deepseek.d.ts +13 -0
  57. package/dist/types/degoog.d.ts +3 -0
  58. package/dist/types/domain-filter-normalization.d.ts +9 -0
  59. package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
  60. package/dist/types/duckduckgo.d.ts +6 -0
  61. package/dist/types/endpoint-pdf-extract.d.ts +22 -0
  62. package/dist/types/exa.d.ts +17 -0
  63. package/dist/types/extract.d.ts +70 -0
  64. package/dist/types/feature-config.d.ts +2 -0
  65. package/dist/types/fetch-params.d.ts +39 -0
  66. package/dist/types/field-extract.d.ts +37 -0
  67. package/dist/types/firecrawl.d.ts +18 -0
  68. package/dist/types/gemini-adc.d.ts +9 -0
  69. package/dist/types/gemini-api.d.ts +37 -0
  70. package/dist/types/gemini-pdf-extract.d.ts +8 -0
  71. package/dist/types/gemini-search.d.ts +76 -0
  72. package/dist/types/gemini-url-context.d.ts +3 -0
  73. package/dist/types/gemini-web-config.d.ts +25 -0
  74. package/dist/types/gemini-web.d.ts +31 -0
  75. package/dist/types/github-api.d.ts +6 -0
  76. package/dist/types/github-extract.d.ts +19 -0
  77. package/dist/types/github-issue-pr.d.ts +28 -0
  78. package/dist/types/index.d.ts +53 -0
  79. package/dist/types/jina-search.d.ts +7 -0
  80. package/dist/types/kagi.d.ts +14 -0
  81. package/dist/types/keenable.d.ts +3 -0
  82. package/dist/types/kimi-search.d.ts +4 -0
  83. package/dist/types/linkup.d.ts +5 -0
  84. package/dist/types/mcp-cli.d.ts +2 -0
  85. package/dist/types/mcp-server.d.ts +10 -0
  86. package/dist/types/mcp-tool-definitions.d.ts +16 -0
  87. package/dist/types/mistral-search.d.ts +3 -0
  88. package/dist/types/ninerouter.d.ts +3 -0
  89. package/dist/types/offtopic-judge.d.ts +26 -0
  90. package/dist/types/ollama.d.ts +14 -0
  91. package/dist/types/openai-search.d.ts +23 -0
  92. package/dist/types/page-query.d.ts +22 -0
  93. package/dist/types/parallel-mcp.d.ts +10 -0
  94. package/dist/types/parallel.d.ts +13 -0
  95. package/dist/types/pdf-extract.d.ts +44 -0
  96. package/dist/types/perplexity.d.ts +26 -0
  97. package/dist/types/pi-mcp.d.ts +56 -0
  98. package/dist/types/pi-session-results.d.ts +8 -0
  99. package/dist/types/querit.d.ts +9 -0
  100. package/dist/types/query-rewrite.d.ts +2 -0
  101. package/dist/types/render-search-error.d.ts +56 -0
  102. package/dist/types/retrieval-only.d.ts +78 -0
  103. package/dist/types/rsc-extract.d.ts +11 -0
  104. package/dist/types/search-answer-formatting.d.ts +7 -0
  105. package/dist/types/search-result-count-normalization.d.ts +1 -0
  106. package/dist/types/searchinfinity.d.ts +7 -0
  107. package/dist/types/searxng.d.ts +3 -0
  108. package/dist/types/source-check.d.ts +102 -0
  109. package/dist/types/ssrf-protection.d.ts +66 -0
  110. package/dist/types/storage.d.ts +69 -0
  111. package/dist/types/summary-model-scope.d.ts +33 -0
  112. package/dist/types/summary-review.d.ts +30 -0
  113. package/dist/types/tabstack.d.ts +5 -0
  114. package/dist/types/tavily.d.ts +7 -0
  115. package/dist/types/tinyfish.d.ts +10 -0
  116. package/dist/types/tool-activation.d.ts +7 -0
  117. package/dist/types/tool-arguments.d.ts +1 -0
  118. package/dist/types/upgrade-notice.d.ts +6 -0
  119. package/dist/types/utils.d.ts +55 -0
  120. package/dist/types/valyu.d.ts +5 -0
  121. package/dist/types/video-extract.d.ts +15 -0
  122. package/dist/types/web-tool-contract.d.ts +98 -0
  123. package/dist/types/web-tool-core.d.ts +227 -0
  124. package/dist/types/xai-search.d.ts +12 -0
  125. package/dist/types/you.d.ts +3 -0
  126. package/dist/types/youtube-extract.d.ts +29 -0
  127. package/dist/types/zai.d.ts +3 -0
  128. package/docs/pi-mcp.md +41 -0
  129. package/domain-filter-normalization.ts +44 -0
  130. package/duckduckgo-rate-limit.ts +205 -0
  131. package/duckduckgo.ts +123 -0
  132. package/endpoint-pdf-extract.ts +225 -0
  133. package/exa.ts +620 -0
  134. package/extract.ts +1721 -0
  135. package/feature-config.ts +29 -0
  136. package/fetch-params.ts +147 -0
  137. package/field-extract.ts +347 -0
  138. package/firecrawl.ts +476 -0
  139. package/gemini-adc.ts +345 -0
  140. package/gemini-api.ts +368 -0
  141. package/gemini-pdf-extract.ts +108 -0
  142. package/gemini-search.ts +1162 -0
  143. package/gemini-url-context.ts +128 -0
  144. package/gemini-web-config.ts +131 -0
  145. package/gemini-web.ts +527 -0
  146. package/github-api.ts +197 -0
  147. package/github-extract.ts +1064 -0
  148. package/github-issue-pr.ts +717 -0
  149. package/index.ts +2819 -0
  150. package/jina-search.ts +275 -0
  151. package/kagi.ts +257 -0
  152. package/keenable.ts +222 -0
  153. package/kimi-search.ts +209 -0
  154. package/linkup.ts +170 -0
  155. package/mcp-cli.ts +40 -0
  156. package/mcp-server.ts +84 -0
  157. package/mcp-tool-definitions.ts +143 -0
  158. package/mistral-search.ts +268 -0
  159. package/ninerouter.ts +92 -0
  160. package/offtopic-judge.ts +72 -0
  161. package/ollama.ts +237 -0
  162. package/openai-search.ts +855 -0
  163. package/package.json +108 -4
  164. package/page-query.ts +185 -0
  165. package/parallel-mcp.ts +255 -0
  166. package/parallel.ts +373 -0
  167. package/pdf-extract.ts +447 -0
  168. package/perplexity.ts +245 -0
  169. package/pi-mcp.ts +139 -0
  170. package/pi-session-results.ts +40 -0
  171. package/pi-web-fetch-demo.mp4 +0 -0
  172. package/promise-try.d.ts +7 -0
  173. package/querit.ts +394 -0
  174. package/query-rewrite.ts +84 -0
  175. package/render-search-error.ts +170 -0
  176. package/retrieval-only.ts +102 -0
  177. package/rsc-extract.ts +338 -0
  178. package/search-answer-formatting.ts +11 -0
  179. package/search-result-count-normalization.ts +4 -0
  180. package/searchinfinity.ts +246 -0
  181. package/searxng.ts +236 -0
  182. package/source-check.ts +269 -0
  183. package/ssrf-protection.ts +602 -0
  184. package/storage.ts +547 -0
  185. package/summary-model-scope.ts +72 -0
  186. package/summary-review.ts +476 -0
  187. package/tabstack.ts +289 -0
  188. package/tavily.ts +257 -0
  189. package/tinyfish.ts +373 -0
  190. package/tool-activation.ts +169 -0
  191. package/tool-arguments.ts +23 -0
  192. package/upgrade-notice.ts +47 -0
  193. package/utils.ts +693 -0
  194. package/valyu.ts +177 -0
  195. package/video-extract.ts +398 -0
  196. package/web-tool-contract.ts +93 -0
  197. package/web-tool-core.ts +1810 -0
  198. package/xai-search.ts +443 -0
  199. package/you.ts +165 -0
  200. package/youtube-extract.ts +336 -0
  201. package/zai.ts +161 -0
@@ -0,0 +1,1064 @@
1
+ import { chmodSync, closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { lstat as lstatAsync, open as openAsync, opendir as opendirAsync, readFile as readFileAsync, realpath as realpathAsync, rm as rmAsync, type FileHandle } from "node:fs/promises";
3
+ import { execFile, spawn, type ChildProcess } from "node:child_process";
4
+ import { createHash } from "node:crypto";
5
+ import { basename, dirname, extname, join, resolve as resolvePath, sep as pathSep } from "node:path";
6
+ import { tmpdir } from "node:os";
7
+ import { activityMonitor } from "./activity.ts";
8
+ import type { ExtractedContent } from "./extract.ts";
9
+ import { checkGhAvailable, checkRepoSize, fetchViaApi, showGhHint } from "./github-api.ts";
10
+ import { getWebSearchConfigPath } from "./utils.ts";
11
+
12
+ const CONFIG_PATH = getWebSearchConfigPath();
13
+
14
+ const BINARY_EXTENSIONS = new Set([
15
+ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".svg", ".tiff", ".tif",
16
+ ".mp3", ".mp4", ".avi", ".mov", ".mkv", ".flv", ".wmv", ".wav", ".ogg", ".webm", ".flac", ".aac",
17
+ ".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar", ".zst",
18
+ ".exe", ".dll", ".so", ".dylib", ".bin", ".o", ".a", ".lib",
19
+ ".woff", ".woff2", ".ttf", ".otf", ".eot",
20
+ ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
21
+ ".sqlite", ".db", ".sqlite3",
22
+ ".pyc", ".pyo", ".class", ".jar", ".war",
23
+ ".iso", ".img", ".dmg",
24
+ ]);
25
+
26
+ const NOISE_DIRS = new Set([
27
+ "node_modules", "vendor", ".next", "dist", "build", "__pycache__",
28
+ ".venv", "venv", ".tox", ".mypy_cache", ".pytest_cache",
29
+ "target", ".gradle", ".idea", ".vscode",
30
+ ]);
31
+
32
+ const MAX_INLINE_FILE_CHARS = 100_000;
33
+ const MAX_TREE_ENTRIES = 200;
34
+ const CLONE_RUNTIME_OWNER_FILENAME = ".owner.json";
35
+ const CLONE_RUNTIME_OWNER_VERSION = 1;
36
+ const MAX_CLONE_RUNTIME_OWNER_BYTES = 1024;
37
+
38
+ export interface GitHubUrlInfo {
39
+ owner: string;
40
+ repo: string;
41
+ ref?: string;
42
+ refIsFullSha: boolean;
43
+ path?: string;
44
+ type: "root" | "blob" | "tree";
45
+ }
46
+
47
+ interface CachedClone {
48
+ destination: CloneDestination;
49
+ clonePromise: Promise<string | null>;
50
+ /** When a fetch last returned this clone's path. */
51
+ lastUsedAt: number;
52
+ settled: boolean;
53
+ }
54
+
55
+ interface CloneDestination {
56
+ rootPath: string;
57
+ localPath: string;
58
+ }
59
+
60
+ interface CloneRuntimeOwner {
61
+ version: 1;
62
+ pid: number;
63
+ platform: string;
64
+ bootId?: string;
65
+ startTime?: string;
66
+ }
67
+
68
+ interface GitHubCloneConfig {
69
+ enabled: boolean;
70
+ maxRepoSizeMB: number;
71
+ cloneTimeoutSeconds: number;
72
+ clonePath: string;
73
+ }
74
+
75
+ const cloneCache = new Map<string, CachedClone>();
76
+ const startedCloneRuntimeCleanups = new Set<string>();
77
+
78
+ let cachedConfig: GitHubCloneConfig | null = null;
79
+ let cloneRuntime: { parentPath: string; rootPath: string } | null = null;
80
+
81
+ function normalizeEnabled(value: unknown, fallback: boolean): boolean {
82
+ return typeof value === "boolean" ? value : fallback;
83
+ }
84
+
85
+ function normalizePositiveNumber(value: unknown, fallback: number): number {
86
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
87
+ return value > 0 ? value : fallback;
88
+ }
89
+
90
+ function expandPath(value: string): string {
91
+ let expanded = value;
92
+ // Expand ~ at the start of the path
93
+ if (expanded.startsWith("~/") || expanded === "~") {
94
+ expanded = expanded.replace(/^~/, process.env.HOME || process.env.USERPROFILE || "");
95
+ }
96
+ // Expand environment variables like $HOME, $USER, etc.
97
+ expanded = expanded.replace(/\$([A-Z_][A-Z0-9_]*)/gi, (match, varName) => {
98
+ return process.env[varName] ?? match;
99
+ });
100
+ return expanded;
101
+ }
102
+
103
+ function normalizeClonePath(value: unknown, fallback: string): string {
104
+ if (typeof value !== "string") return fallback;
105
+ const normalized = value.trim();
106
+ if (normalized.length === 0) return fallback;
107
+ return expandPath(normalized);
108
+ }
109
+
110
+ function loadGitHubConfig(): GitHubCloneConfig {
111
+ if (cachedConfig) return cachedConfig;
112
+
113
+ const defaults: GitHubCloneConfig = {
114
+ enabled: true,
115
+ maxRepoSizeMB: 350,
116
+ cloneTimeoutSeconds: 30,
117
+ clonePath: join(tmpdir(), "pi-github-repos"),
118
+ };
119
+
120
+ if (!existsSync(CONFIG_PATH)) {
121
+ cachedConfig = defaults;
122
+ return cachedConfig;
123
+ }
124
+
125
+ const rawText = readFileSync(CONFIG_PATH, "utf-8");
126
+ let raw: { githubClone?: { enabled?: unknown; maxRepoSizeMB?: unknown; cloneTimeoutSeconds?: unknown; clonePath?: unknown } };
127
+ try {
128
+ raw = JSON.parse(rawText) as { githubClone?: { enabled?: unknown; maxRepoSizeMB?: unknown; cloneTimeoutSeconds?: unknown; clonePath?: unknown } };
129
+ } catch (err) {
130
+ const message = err instanceof Error ? err.message : String(err);
131
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
132
+ }
133
+
134
+ const gc = raw.githubClone ?? {};
135
+ cachedConfig = {
136
+ enabled: normalizeEnabled(gc.enabled, defaults.enabled),
137
+ maxRepoSizeMB: normalizePositiveNumber(gc.maxRepoSizeMB, defaults.maxRepoSizeMB),
138
+ cloneTimeoutSeconds: normalizePositiveNumber(gc.cloneTimeoutSeconds, defaults.cloneTimeoutSeconds),
139
+ clonePath: normalizeClonePath(gc.clonePath, defaults.clonePath),
140
+ };
141
+ return cachedConfig;
142
+ }
143
+
144
+ const NON_CODE_SEGMENTS = new Set([
145
+ "issues", "pull", "pulls", "discussions", "releases", "wiki",
146
+ "actions", "settings", "security", "projects", "graphs",
147
+ "compare", "commits", "tags", "branches", "stargazers",
148
+ "watchers", "network", "forks", "milestone", "labels",
149
+ "packages", "codespaces", "contribute", "community",
150
+ "sponsors", "invitations", "notifications", "insights",
151
+ ]);
152
+
153
+ export function parseGitHubUrl(url: string): GitHubUrlInfo | null {
154
+ let parsed: URL;
155
+ try {
156
+ parsed = new URL(url);
157
+ } catch {
158
+ return null;
159
+ }
160
+
161
+ const host = parsed.hostname.toLowerCase();
162
+ if (host !== "github.com" && host !== "www.github.com") return null;
163
+
164
+ const segments: string[] = [];
165
+ for (const segment of parsed.pathname.split("/").filter(Boolean)) {
166
+ try {
167
+ segments.push(decodeURIComponent(segment));
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+ if (segments.length < 2) return null;
173
+
174
+ const owner = segments[0];
175
+ const repo = segments[1].replace(/\.git$/, "");
176
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(owner)) return null;
177
+ if (owner.includes("--")) return null;
178
+ if (!/^[A-Za-z0-9._-]{1,100}$/.test(repo) || repo === "." || repo === "..") return null;
179
+
180
+ if (NON_CODE_SEGMENTS.has(segments[2]?.toLowerCase())) return null;
181
+
182
+ if (segments.length === 2) {
183
+ return { owner, repo, refIsFullSha: false, type: "root" };
184
+ }
185
+
186
+ const action = segments[2];
187
+ if (action !== "blob" && action !== "tree") return null;
188
+ if (segments.length < 4) return null;
189
+
190
+ const ref = segments[3];
191
+ if (ref.length === 0 || ref.length > 1024 || /[\0-\x1f\x7f]/.test(ref)) return null;
192
+ const refIsFullSha = /^[0-9a-f]{40}$/.test(ref);
193
+ const pathParts = segments.slice(4);
194
+ const path = pathParts.length > 0 ? pathParts.join("/") : "";
195
+
196
+ return {
197
+ owner,
198
+ repo,
199
+ ref,
200
+ refIsFullSha,
201
+ path,
202
+ type: action as "blob" | "tree",
203
+ };
204
+ }
205
+
206
+ function cacheKey(owner: string, repo: string, ref?: string): string {
207
+ return ref ? `${owner}/${repo}@${ref}` : `${owner}/${repo}`;
208
+ }
209
+
210
+ function readLinuxBootId(): string | null {
211
+ try {
212
+ const bootId = readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim();
213
+ return bootId.length > 0 ? bootId : null;
214
+ } catch {
215
+ return null;
216
+ }
217
+ }
218
+
219
+ async function readLinuxBootIdAsync(): Promise<string | null> {
220
+ try {
221
+ const bootId = (await readFileAsync("/proc/sys/kernel/random/boot_id", "utf-8")).trim();
222
+ return bootId.length > 0 ? bootId : null;
223
+ } catch {
224
+ return null;
225
+ }
226
+ }
227
+
228
+ interface LinuxProcessInfo {
229
+ state: string;
230
+ startTime: string | null;
231
+ dead: boolean;
232
+ }
233
+
234
+ function parseLinuxProcessInfo(stat: string): LinuxProcessInfo | null {
235
+ const closingParen = stat.lastIndexOf(") ");
236
+ if (closingParen < 0) return null;
237
+ const fields = stat.slice(closingParen + 2).trim().split(/\s+/);
238
+ const state = fields[0];
239
+ const startTime = fields[19];
240
+ if (!state || !startTime || !/^\d+$/.test(startTime)) return null;
241
+ return { state, startTime, dead: false };
242
+ }
243
+
244
+ function readLinuxProcessInfo(pid: number): LinuxProcessInfo | null {
245
+ try {
246
+ return parseLinuxProcessInfo(readFileSync(`/proc/${pid}/stat`, "utf-8"));
247
+ } catch (err) {
248
+ if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") {
249
+ return { state: "", startTime: null, dead: true };
250
+ }
251
+ return null;
252
+ }
253
+ }
254
+
255
+ async function readLinuxProcessInfoAsync(pid: number): Promise<LinuxProcessInfo | null> {
256
+ try {
257
+ return parseLinuxProcessInfo(await readFileAsync(`/proc/${pid}/stat`, "utf-8"));
258
+ } catch (err) {
259
+ if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") {
260
+ return { state: "", startTime: null, dead: true };
261
+ }
262
+ return null;
263
+ }
264
+ }
265
+
266
+ function currentCloneRuntimeOwner(): CloneRuntimeOwner {
267
+ const owner: CloneRuntimeOwner = {
268
+ version: CLONE_RUNTIME_OWNER_VERSION,
269
+ pid: process.pid,
270
+ platform: process.platform,
271
+ };
272
+
273
+ if (process.platform === "linux") {
274
+ const bootId = readLinuxBootId();
275
+ const processInfo = readLinuxProcessInfo(process.pid);
276
+ if (bootId && processInfo?.startTime) {
277
+ owner.bootId = bootId;
278
+ owner.startTime = processInfo.startTime;
279
+ }
280
+ }
281
+
282
+ return owner;
283
+ }
284
+
285
+ function writeCloneRuntimeOwner(runtimePath: string): void {
286
+ const ownerPath = join(runtimePath, CLONE_RUNTIME_OWNER_FILENAME);
287
+ writeFileSync(ownerPath, JSON.stringify(currentCloneRuntimeOwner()), {
288
+ encoding: "utf-8",
289
+ flag: "wx",
290
+ mode: 0o600,
291
+ });
292
+ }
293
+
294
+ function parseCloneRuntimeOwner(text: string): CloneRuntimeOwner | null {
295
+ let parsed: unknown;
296
+ try {
297
+ parsed = JSON.parse(text);
298
+ } catch {
299
+ return null;
300
+ }
301
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
302
+
303
+ const record = parsed as Record<string, unknown>;
304
+ if (
305
+ record.version !== CLONE_RUNTIME_OWNER_VERSION ||
306
+ typeof record.pid !== "number" ||
307
+ !Number.isSafeInteger(record.pid) ||
308
+ record.pid <= 0 ||
309
+ typeof record.platform !== "string" ||
310
+ record.platform.length === 0 ||
311
+ record.platform.length > 32
312
+ ) {
313
+ return null;
314
+ }
315
+
316
+ const owner: CloneRuntimeOwner = {
317
+ version: CLONE_RUNTIME_OWNER_VERSION,
318
+ pid: record.pid,
319
+ platform: record.platform,
320
+ };
321
+ if (record.bootId !== undefined) {
322
+ if (typeof record.bootId !== "string" || record.bootId.length === 0 || record.bootId.length > 256) return null;
323
+ owner.bootId = record.bootId;
324
+ }
325
+ if (record.startTime !== undefined) {
326
+ if (typeof record.startTime !== "string" || !/^\d+$/.test(record.startTime)) return null;
327
+ owner.startTime = record.startTime;
328
+ }
329
+ return owner;
330
+ }
331
+
332
+ async function readCloneRuntimeOwner(runtimePath: string): Promise<CloneRuntimeOwner | null> {
333
+ const ownerPath = join(runtimePath, CLONE_RUNTIME_OWNER_FILENAME);
334
+ let file: FileHandle | undefined;
335
+ try {
336
+ const entry = await lstatAsync(ownerPath);
337
+ if (!entry.isFile() || entry.size > MAX_CLONE_RUNTIME_OWNER_BYTES) return null;
338
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
339
+ file = await openAsync(ownerPath, fsConstants.O_RDONLY | noFollow);
340
+ const opened = await file.stat();
341
+ if (!opened.isFile() || opened.size > MAX_CLONE_RUNTIME_OWNER_BYTES) return null;
342
+ return parseCloneRuntimeOwner(await file.readFile("utf-8"));
343
+ } catch {
344
+ return null;
345
+ } finally {
346
+ if (file !== undefined) {
347
+ try {
348
+ await file.close();
349
+ } catch {
350
+ // The handle may already have been closed externally.
351
+ }
352
+ }
353
+ }
354
+ }
355
+
356
+ function processNonexistenceProven(pid: number): boolean {
357
+ try {
358
+ process.kill(pid, 0);
359
+ return false;
360
+ } catch (err) {
361
+ return Boolean(err && typeof err === "object" && "code" in err && err.code === "ESRCH");
362
+ }
363
+ }
364
+
365
+ async function cloneRuntimeOwnerIsDead(owner: CloneRuntimeOwner, bootId: string | null): Promise<boolean> {
366
+ if (owner.platform !== process.platform) return false;
367
+
368
+ if (process.platform !== "linux") {
369
+ return processNonexistenceProven(owner.pid);
370
+ }
371
+
372
+ // Linux PID values can be reused. Require both boot ID and proc start time
373
+ // before treating a runtime as owned, and preserve it when either check is
374
+ // unavailable.
375
+ if (!owner.bootId || !owner.startTime || !bootId) return false;
376
+ const processInfo = await readLinuxProcessInfoAsync(owner.pid);
377
+ if (!processInfo) return false;
378
+ if (processInfo.dead || processInfo.state === "Z" || processInfo.state === "X") return true;
379
+ return processInfo.startTime !== owner.startTime || bootId !== owner.bootId;
380
+ }
381
+
382
+ async function removeCloneRuntimeAsync(parentPath: string, runtimePath: string): Promise<void> {
383
+ const normalizedParentPath = resolvePath(parentPath);
384
+ const normalizedRuntimePath = resolvePath(runtimePath);
385
+ if (dirname(normalizedRuntimePath) !== normalizedParentPath || !basename(normalizedRuntimePath).startsWith("runtime-")) return;
386
+
387
+ try {
388
+ const realRuntimePath = await realpathAsync(normalizedRuntimePath);
389
+ if (dirname(realRuntimePath) !== normalizedParentPath || basename(realRuntimePath) !== basename(normalizedRuntimePath)) return;
390
+ const entry = await lstatAsync(normalizedRuntimePath);
391
+ if (entry.isSymbolicLink() || !entry.isDirectory()) return;
392
+ await rmAsync(normalizedRuntimePath, { recursive: true, force: true });
393
+ } catch {
394
+ // The runtime directory may already have been removed externally.
395
+ }
396
+ }
397
+
398
+ async function sweepStaleCloneRuntimes(parentPath: string): Promise<void> {
399
+ const normalizedParentPath = resolvePath(parentPath);
400
+ const bootId = process.platform === "linux" ? await readLinuxBootIdAsync() : null;
401
+ try {
402
+ const directory = await opendirAsync(normalizedParentPath);
403
+ for await (const entry of directory) {
404
+ if (!entry.name.startsWith("runtime-")) continue;
405
+ try {
406
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
407
+ const runtimePath = resolvePath(normalizedParentPath, entry.name);
408
+ if (dirname(runtimePath) !== normalizedParentPath) continue;
409
+ const runtimeEntry = await lstatAsync(runtimePath);
410
+ if (!runtimeEntry.isDirectory() || runtimeEntry.isSymbolicLink()) continue;
411
+ const realRuntimePath = await realpathAsync(runtimePath);
412
+ if (dirname(realRuntimePath) !== normalizedParentPath || basename(realRuntimePath) !== basename(runtimePath)) continue;
413
+ const owner = await readCloneRuntimeOwner(runtimePath);
414
+ if (!owner || !(await cloneRuntimeOwnerIsDead(owner, bootId))) continue;
415
+ await removeCloneRuntimeAsync(normalizedParentPath, runtimePath);
416
+ } catch {
417
+ // A changing or unreadable runtime must not stop the rest of the sweep.
418
+ }
419
+ }
420
+ } catch {
421
+ // Cleanup is opportunistic. A changing or unreadable cache must not stop
422
+ // GitHub extraction from falling back to the API.
423
+ }
424
+ }
425
+
426
+ function startStaleCloneRuntimeCleanup(parentPath: string): void {
427
+ const normalizedParentPath = resolvePath(parentPath);
428
+ if (startedCloneRuntimeCleanups.has(normalizedParentPath)) return;
429
+ startedCloneRuntimeCleanups.add(normalizedParentPath);
430
+ // Keep runtime creation synchronous and let the complete sweep run in the background.
431
+ void sweepStaleCloneRuntimes(normalizedParentPath).catch(() => {
432
+ // Cleanup is best effort and must never affect extraction.
433
+ });
434
+ }
435
+
436
+ function removeCloneRuntime(parentPath: string, runtimePath: string): void {
437
+ const normalizedParentPath = resolvePath(parentPath);
438
+ const normalizedRuntimePath = resolvePath(runtimePath);
439
+ if (dirname(normalizedRuntimePath) !== normalizedParentPath || !basename(normalizedRuntimePath).startsWith("runtime-")) return;
440
+
441
+ try {
442
+ const entry = lstatSync(normalizedRuntimePath);
443
+ if (entry.isSymbolicLink()) unlinkSync(normalizedRuntimePath);
444
+ else rmSync(normalizedRuntimePath, { recursive: true, force: true });
445
+ } catch {
446
+ // The runtime directory may already have been removed externally.
447
+ }
448
+ }
449
+
450
+ function getCloneRuntimeRoot(config: GitHubCloneConfig): string | null {
451
+ if (cloneRuntime) return cloneRuntime.rootPath;
452
+
453
+ let parentPath: string | null = null;
454
+ let runtimePath: string | null = null;
455
+ try {
456
+ const configuredPath = resolvePath(config.clonePath);
457
+ mkdirSync(configuredPath, { recursive: true });
458
+ parentPath = realpathSync(configuredPath);
459
+ startStaleCloneRuntimeCleanup(parentPath);
460
+ runtimePath = mkdtempSync(join(parentPath, "runtime-"));
461
+ chmodSync(runtimePath, 0o700);
462
+ const rootPath = realpathSync(runtimePath);
463
+ if (dirname(rootPath) !== parentPath) {
464
+ removeCloneRuntime(parentPath, runtimePath);
465
+ return null;
466
+ }
467
+ writeCloneRuntimeOwner(rootPath);
468
+ cloneRuntime = { parentPath, rootPath };
469
+ return rootPath;
470
+ } catch {
471
+ if (parentPath && runtimePath) removeCloneRuntime(parentPath, runtimePath);
472
+ return null;
473
+ }
474
+ }
475
+
476
+ function cloneDestination(config: GitHubCloneConfig, owner: string, repo: string, ref?: string): CloneDestination | null {
477
+ try {
478
+ const rootPath = getCloneRuntimeRoot(config);
479
+ if (!rootPath) return null;
480
+ const digest = createHash("sha256").update(JSON.stringify([owner, repo, ref ?? null])).digest("hex");
481
+ const localPath = resolvePath(rootPath, digest);
482
+ if (dirname(localPath) !== rootPath) return null;
483
+ return { rootPath, localPath };
484
+ } catch {
485
+ return null;
486
+ }
487
+ }
488
+
489
+ function removeCloneDestination(destination: CloneDestination): boolean {
490
+ const rootPath = resolvePath(destination.rootPath);
491
+ const localPath = resolvePath(destination.localPath);
492
+ if (dirname(localPath) !== rootPath || !/^[0-9a-f]{64}$/.test(basename(localPath))) return false;
493
+ try {
494
+ const entry = lstatSync(localPath);
495
+ if (entry.isSymbolicLink()) unlinkSync(localPath);
496
+ else rmSync(localPath, { recursive: true, force: true });
497
+ return true;
498
+ } catch (err) {
499
+ if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") return true;
500
+ return false;
501
+ }
502
+ }
503
+
504
+ const PROCESS_KILL_GRACE_MS = 3000;
505
+
506
+ function terminateProcessTree(child: ChildProcess): void {
507
+ const pid = child.pid;
508
+ if (!pid) return;
509
+
510
+ if (process.platform === "win32") {
511
+ const killer = execFile(
512
+ "taskkill",
513
+ ["/pid", String(pid), "/T", "/F"],
514
+ { windowsHide: true },
515
+ (err) => {
516
+ if (err) child.kill();
517
+ },
518
+ );
519
+ killer.unref();
520
+ return;
521
+ }
522
+
523
+ try {
524
+ // Clone commands run in their own process group so git/gh helpers cannot
525
+ // survive a timeout or cancellation and keep reading from the host TTY.
526
+ process.kill(-pid, "SIGTERM");
527
+ } catch {
528
+ child.kill();
529
+ }
530
+
531
+ // A credential helper may handle or ignore SIGTERM. Escalate against the
532
+ // entire process group so neither git nor any descendant can block forever.
533
+ const forceKill = setTimeout(() => {
534
+ try {
535
+ process.kill(-pid, "SIGKILL");
536
+ } catch {
537
+ child.kill("SIGKILL");
538
+ }
539
+ }, PROCESS_KILL_GRACE_MS);
540
+ forceKill.unref();
541
+ }
542
+
543
+ function execClone(args: string[], destination: CloneDestination, timeoutMs: number, signal?: AbortSignal): Promise<string | null> {
544
+ return new Promise((resolve) => {
545
+ const { localPath } = destination;
546
+ let settled = false;
547
+ let timeout: ReturnType<typeof setTimeout> | undefined;
548
+ let onAbort: (() => void) | undefined;
549
+
550
+ const finish = (success: boolean) => {
551
+ if (settled) return;
552
+ settled = true;
553
+ if (timeout) clearTimeout(timeout);
554
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
555
+
556
+ if (!success) {
557
+ removeCloneDestination(destination);
558
+ resolve(null);
559
+ return;
560
+ }
561
+ resolve(localPath);
562
+ };
563
+
564
+ const child = spawn(args[0], args.slice(1), {
565
+ detached: process.platform !== "win32",
566
+ env: {
567
+ ...process.env,
568
+ GIT_TERMINAL_PROMPT: "0",
569
+ GCM_INTERACTIVE: "Never",
570
+ GH_PROMPT_DISABLED: "1",
571
+ },
572
+ stdio: "ignore",
573
+ windowsHide: true,
574
+ });
575
+
576
+ child.once("error", () => finish(false));
577
+ child.once("close", (code) => finish(code === 0));
578
+
579
+ timeout = setTimeout(() => terminateProcessTree(child), timeoutMs);
580
+ timeout.unref();
581
+
582
+ if (signal) {
583
+ onAbort = () => {
584
+ if (timeout) clearTimeout(timeout);
585
+ terminateProcessTree(child);
586
+ };
587
+ if (signal.aborted) onAbort();
588
+ else signal.addEventListener("abort", onAbort, { once: true });
589
+ }
590
+ });
591
+ }
592
+
593
+ async function cloneRepo(
594
+ owner: string,
595
+ repo: string,
596
+ ref: string | undefined,
597
+ config: GitHubCloneConfig,
598
+ destination: CloneDestination,
599
+ signal?: AbortSignal,
600
+ ): Promise<string | null> {
601
+ const { localPath } = destination;
602
+ if (!removeCloneDestination(destination)) return null;
603
+
604
+ const timeoutMs = config.cloneTimeoutSeconds * 1000;
605
+ const hasGh = await checkGhAvailable();
606
+
607
+ if (hasGh) {
608
+ const args = ["gh", "repo", "clone", `${owner}/${repo}`, localPath, "--", "--depth", "1", "--single-branch"];
609
+ if (ref) args.push("--branch", ref);
610
+ return execClone(args, destination, timeoutMs, signal);
611
+ }
612
+
613
+ showGhHint();
614
+
615
+ const gitUrl = `https://github.com/${owner}/${repo}.git`;
616
+ const args = ["git", "clone", "--depth", "1", "--single-branch"];
617
+ if (ref) args.push("--branch", ref);
618
+ args.push(gitUrl, localPath);
619
+ return execClone(args, destination, timeoutMs, signal);
620
+ }
621
+
622
+ function isBinaryFile(filePath: string): boolean {
623
+ const ext = extname(filePath).toLowerCase();
624
+ if (BINARY_EXTENSIONS.has(ext)) return true;
625
+
626
+ let fd: number;
627
+ try {
628
+ fd = openSync(filePath, "r");
629
+ } catch {
630
+ return false;
631
+ }
632
+ try {
633
+ const buf = Buffer.alloc(512);
634
+ const bytesRead = readSync(fd, buf, 0, 512, 0);
635
+ for (let i = 0; i < bytesRead; i++) {
636
+ if (buf[i] === 0) return true;
637
+ }
638
+ } catch {
639
+ return false;
640
+ } finally {
641
+ closeSync(fd);
642
+ }
643
+
644
+ return false;
645
+ }
646
+
647
+ function formatFileSize(bytes: number): string {
648
+ if (bytes < 1024) return `${bytes} B`;
649
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
650
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
651
+ }
652
+
653
+ function resolveWithinRepo(rootPath: string, relativePath: string): string | null {
654
+ const normalizedRoot = resolvePath(rootPath);
655
+ const candidate = resolvePath(normalizedRoot, relativePath);
656
+ if (candidate !== normalizedRoot) {
657
+ const rootPrefix = normalizedRoot.endsWith(pathSep) ? normalizedRoot : normalizedRoot + pathSep;
658
+ if (!candidate.startsWith(rootPrefix)) return null;
659
+ }
660
+
661
+ if (!existsSync(candidate)) return candidate;
662
+
663
+ try {
664
+ const realRoot = realpathSync(normalizedRoot);
665
+ const realCandidate = realpathSync(candidate);
666
+ if (realCandidate === realRoot) return candidate;
667
+ const realRootPrefix = realRoot.endsWith(pathSep) ? realRoot : realRoot + pathSep;
668
+ return realCandidate.startsWith(realRootPrefix) ? candidate : null;
669
+ } catch {
670
+ return null;
671
+ }
672
+ }
673
+
674
+ function readTextFile(path: string): string | null {
675
+ try {
676
+ return readFileSync(path, "utf-8");
677
+ } catch {
678
+ return null;
679
+ }
680
+ }
681
+
682
+ function buildTree(rootPath: string): string {
683
+ const entries: string[] = [];
684
+
685
+ function walk(dir: string, relPath: string): void {
686
+ if (entries.length >= MAX_TREE_ENTRIES) return;
687
+
688
+ let items: string[];
689
+ try {
690
+ items = readdirSync(dir).sort();
691
+ } catch {
692
+ return;
693
+ }
694
+
695
+ for (const item of items) {
696
+ if (entries.length >= MAX_TREE_ENTRIES) return;
697
+ if (item === ".git") continue;
698
+
699
+ const rel = relPath ? `${relPath}/${item}` : item;
700
+ const safePath = resolveWithinRepo(rootPath, rel);
701
+ if (!safePath) {
702
+ entries.push(`${rel} [outside repo skipped]`);
703
+ continue;
704
+ }
705
+
706
+ let stat;
707
+ try {
708
+ stat = statSync(safePath);
709
+ } catch {
710
+ continue;
711
+ }
712
+
713
+ if (stat.isDirectory()) {
714
+ if (NOISE_DIRS.has(item)) {
715
+ entries.push(`${rel}/ [skipped]`);
716
+ continue;
717
+ }
718
+ entries.push(`${rel}/`);
719
+ walk(safePath, rel);
720
+ } else {
721
+ entries.push(rel);
722
+ }
723
+ }
724
+ }
725
+
726
+ walk(rootPath, "");
727
+
728
+ if (entries.length >= MAX_TREE_ENTRIES) {
729
+ entries.push(`... (truncated at ${MAX_TREE_ENTRIES} entries)`);
730
+ }
731
+
732
+ return entries.join("\n");
733
+ }
734
+
735
+ function buildDirListing(rootPath: string, subPath: string): string {
736
+ const targetPath = resolveWithinRepo(rootPath, subPath);
737
+ if (!targetPath) return "(path escapes repository root)";
738
+ const lines: string[] = [];
739
+
740
+ let items: string[];
741
+ try {
742
+ items = readdirSync(targetPath).sort();
743
+ } catch {
744
+ return "(directory not readable)";
745
+ }
746
+
747
+ for (const item of items) {
748
+ if (item === ".git") continue;
749
+ const rel = subPath ? `${subPath}/${item}` : item;
750
+ const safePath = resolveWithinRepo(rootPath, rel);
751
+ if (!safePath) {
752
+ lines.push(` ${item} (outside repo)`);
753
+ continue;
754
+ }
755
+ try {
756
+ const stat = statSync(safePath);
757
+ if (stat.isDirectory()) {
758
+ lines.push(` ${item}/`);
759
+ } else {
760
+ lines.push(` ${item} (${formatFileSize(stat.size)})`);
761
+ }
762
+ } catch {
763
+ lines.push(` ${item} (unreadable)`);
764
+ }
765
+ }
766
+
767
+ return lines.join("\n");
768
+ }
769
+
770
+ function readReadme(localPath: string): string | null {
771
+ const candidates = ["README.md", "readme.md", "README", "README.txt", "README.rst"];
772
+ for (const name of candidates) {
773
+ const readmePath = join(localPath, name);
774
+ if (existsSync(readmePath)) {
775
+ try {
776
+ const content = readFileSync(readmePath, "utf-8");
777
+ return content.length > MAX_INLINE_FILE_CHARS ? `${content.slice(0, MAX_INLINE_FILE_CHARS)}\n\n[README truncated at 100K chars. Full file: ${readmePath}]` : content;
778
+ } catch {
779
+ continue;
780
+ }
781
+ }
782
+ }
783
+ return null;
784
+ }
785
+
786
+ function generateContent(localPath: string, info: GitHubUrlInfo): string {
787
+ const lines: string[] = [];
788
+ lines.push(`Repository cloned to: ${localPath}`);
789
+ lines.push("");
790
+
791
+ if (info.type === "root") {
792
+ lines.push("## Structure");
793
+ lines.push(buildTree(localPath));
794
+ lines.push("");
795
+
796
+ const readme = readReadme(localPath);
797
+ if (readme) {
798
+ lines.push("## README.md");
799
+ lines.push(readme);
800
+ lines.push("");
801
+ }
802
+
803
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
804
+ return lines.join("\n");
805
+ }
806
+
807
+ if (info.type === "tree") {
808
+ const dirPath = info.path || "";
809
+ const fullDirPath = resolveWithinRepo(localPath, dirPath);
810
+
811
+ if (!fullDirPath || !existsSync(fullDirPath)) {
812
+ lines.push(`Path \`${dirPath}\` not found in clone. Showing repository root instead.`);
813
+ lines.push("");
814
+ lines.push("## Structure");
815
+ lines.push(buildTree(localPath));
816
+ } else {
817
+ lines.push(`## ${dirPath || "/"}`);
818
+ lines.push(buildDirListing(localPath, dirPath));
819
+ }
820
+
821
+ lines.push("");
822
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
823
+ return lines.join("\n");
824
+ }
825
+
826
+ if (info.type === "blob") {
827
+ const filePath = info.path || "";
828
+ const fullFilePath = resolveWithinRepo(localPath, filePath);
829
+
830
+ if (!fullFilePath || !existsSync(fullFilePath)) {
831
+ lines.push(`Path \`${filePath}\` not found in clone. Showing repository root instead.`);
832
+ lines.push("");
833
+ lines.push("## Structure");
834
+ lines.push(buildTree(localPath));
835
+ lines.push("");
836
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
837
+ return lines.join("\n");
838
+ }
839
+
840
+ let stat: ReturnType<typeof statSync>;
841
+ try {
842
+ stat = statSync(fullFilePath);
843
+ } catch (err) {
844
+ const message = err instanceof Error ? err.message : String(err);
845
+ lines.push(`Could not inspect \`${filePath}\`: ${message}`);
846
+ lines.push("");
847
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
848
+ return lines.join("\n");
849
+ }
850
+
851
+ if (stat.isDirectory()) {
852
+ lines.push(`## ${filePath || "/"}`);
853
+ lines.push(buildDirListing(localPath, filePath));
854
+ lines.push("");
855
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
856
+ return lines.join("\n");
857
+ }
858
+
859
+ if (isBinaryFile(fullFilePath)) {
860
+ const ext = extname(filePath).replace(".", "");
861
+ lines.push(`## ${filePath}`);
862
+ lines.push(`Binary file (${ext}, ${formatFileSize(stat.size)}). Use \`read\` or \`bash\` tools at the path above to inspect.`);
863
+ return lines.join("\n");
864
+ }
865
+
866
+ const content = readTextFile(fullFilePath);
867
+ if (content === null) {
868
+ lines.push(`Could not read \`${filePath}\` as UTF-8 text.`);
869
+ lines.push("");
870
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
871
+ return lines.join("\n");
872
+ }
873
+ lines.push(`## ${filePath}`);
874
+
875
+ if (content.length > MAX_INLINE_FILE_CHARS) {
876
+ lines.push(content.slice(0, MAX_INLINE_FILE_CHARS));
877
+ lines.push("");
878
+ lines.push(`[File truncated at 100K chars. Full file: ${fullFilePath}]`);
879
+ } else {
880
+ lines.push(content);
881
+ }
882
+
883
+ lines.push("");
884
+ lines.push("Use `read` and `bash` tools at the path above to explore further.");
885
+ return lines.join("\n");
886
+ }
887
+
888
+ return lines.join("\n");
889
+ }
890
+
891
+ async function awaitCachedClone(
892
+ cached: CachedClone,
893
+ url: string,
894
+ owner: string,
895
+ repo: string,
896
+ info: GitHubUrlInfo,
897
+ signal?: AbortSignal,
898
+ ): Promise<ExtractedContent | null> {
899
+ if (signal?.aborted) return null;
900
+ const result = await cached.clonePromise;
901
+ if (signal?.aborted) return null;
902
+ if (result) {
903
+ const content = generateContent(result, info);
904
+ const title = info.path ? `${owner}/${repo} - ${info.path}` : `${owner}/${repo}`;
905
+ return { url, title, content, error: null };
906
+ }
907
+ return fetchViaApi(url, owner, repo, info);
908
+ }
909
+
910
+ export async function extractGitHub(
911
+ url: string,
912
+ signal?: AbortSignal,
913
+ forceClone?: boolean,
914
+ ): Promise<ExtractedContent | null> {
915
+ const info = parseGitHubUrl(url);
916
+ if (!info) return null;
917
+
918
+ if (signal?.aborted) return null;
919
+
920
+ const config = loadGitHubConfig();
921
+ if (!config.enabled) return null;
922
+
923
+ const { owner, repo } = info;
924
+ const key = cacheKey(owner, repo, info.ref);
925
+
926
+ const cached = cloneCache.get(key);
927
+ if (cached) {
928
+ cached.lastUsedAt = Date.now();
929
+ return awaitCachedClone(cached, url, owner, repo, info, signal);
930
+ }
931
+
932
+ if (info.refIsFullSha) {
933
+ if (signal?.aborted) return null;
934
+ const sizeNote = `Note: Commit SHA URLs use the GitHub API instead of cloning.`;
935
+ return fetchViaApi(url, owner, repo, info, sizeNote);
936
+ }
937
+
938
+ const activityId = activityMonitor.logStart({ type: "fetch", url: `github.com/${owner}/${repo}` });
939
+
940
+ if (!forceClone) {
941
+ const sizeKB = await checkRepoSize(owner, repo);
942
+ if (signal?.aborted) {
943
+ activityMonitor.logComplete(activityId, 0);
944
+ return null;
945
+ }
946
+ if (sizeKB !== null) {
947
+ const sizeMB = sizeKB / 1024;
948
+ if (sizeMB > config.maxRepoSizeMB) {
949
+ if (signal?.aborted) {
950
+ activityMonitor.logComplete(activityId, 0);
951
+ return null;
952
+ }
953
+ const sizeNote =
954
+ `Note: Repository is ${Math.round(sizeMB)}MB (threshold: ${config.maxRepoSizeMB}MB). ` +
955
+ `Showing API-fetched content instead of full clone. Ask the user if they'd like to clone the full repo -- ` +
956
+ `if yes, call fetch_content again with the same URL and add forceClone: true to the params.`;
957
+ const apiView = await fetchViaApi(url, owner, repo, info, sizeNote);
958
+ if (apiView) {
959
+ activityMonitor.logComplete(activityId, 200);
960
+ return apiView;
961
+ }
962
+ activityMonitor.logError(activityId, "api fallback unavailable for oversized repository");
963
+ return null;
964
+ }
965
+ }
966
+ }
967
+
968
+ if (signal?.aborted) {
969
+ activityMonitor.logComplete(activityId, 0);
970
+ return null;
971
+ }
972
+
973
+ // Re-check: another concurrent caller may have started a clone while we awaited the size check
974
+ const cachedAfterSizeCheck = cloneCache.get(key);
975
+ if (cachedAfterSizeCheck) {
976
+ cachedAfterSizeCheck.lastUsedAt = Date.now();
977
+ const cachedResult = await awaitCachedClone(cachedAfterSizeCheck, url, owner, repo, info, signal);
978
+ if (signal?.aborted) {
979
+ activityMonitor.logComplete(activityId, 0);
980
+ } else if (cachedResult) {
981
+ activityMonitor.logComplete(activityId, 200);
982
+ } else {
983
+ activityMonitor.logError(activityId, "clone failed");
984
+ }
985
+ return cachedResult;
986
+ }
987
+
988
+ const destination = cloneDestination(config, owner, repo, info.ref);
989
+ if (!destination) {
990
+ const apiFallback = await fetchViaApi(url, owner, repo, info);
991
+ if (apiFallback) activityMonitor.logComplete(activityId, 200);
992
+ else activityMonitor.logError(activityId, "invalid clone destination");
993
+ return apiFallback;
994
+ }
995
+ const clonePromise = cloneRepo(owner, repo, info.ref, config, destination, signal);
996
+ const entry: CachedClone = { destination, clonePromise, lastUsedAt: Date.now(), settled: false };
997
+ cloneCache.set(key, entry);
998
+ void clonePromise.finally(() => { entry.settled = true; });
999
+
1000
+ const result = await clonePromise;
1001
+ if (signal?.aborted) {
1002
+ if (!result) cloneCache.delete(key);
1003
+ activityMonitor.logComplete(activityId, 0);
1004
+ return null;
1005
+ }
1006
+
1007
+ if (!result) {
1008
+ cloneCache.delete(key);
1009
+ if (signal?.aborted) {
1010
+ activityMonitor.logComplete(activityId, 0);
1011
+ return null;
1012
+ }
1013
+
1014
+ const apiFallback = await fetchViaApi(url, owner, repo, info);
1015
+ if (apiFallback) {
1016
+ activityMonitor.logComplete(activityId, 200);
1017
+ return apiFallback;
1018
+ }
1019
+
1020
+ activityMonitor.logError(activityId, "clone and API fallback failed");
1021
+ return null;
1022
+ }
1023
+
1024
+ activityMonitor.logComplete(activityId, 200);
1025
+ const content = generateContent(result, info);
1026
+ const title = info.path ? `${owner}/${repo} - ${info.path}` : `${owner}/${repo}`;
1027
+ return { url, title, content, error: null };
1028
+ }
1029
+
1030
+ /** Mark the clones these URLs name as used now. A session that restores results from history
1031
+ * (its own, or one it was forked from) holds their clone paths without fetching them again. */
1032
+ export function touchClones(urls: Iterable<string>): void {
1033
+ const now = Date.now();
1034
+ for (const url of urls) {
1035
+ const info = parseGitHubUrl(url);
1036
+ if (!info) continue;
1037
+ const entry = cloneCache.get(cacheKey(info.owner, info.repo, info.ref));
1038
+ if (entry) entry.lastUsedAt = now;
1039
+ }
1040
+ }
1041
+
1042
+ /** Remove finished clones no fetch has returned since `time`. A host that runs several
1043
+ * sessions at once passes when its oldest live session started: no live session can have
1044
+ * been given those paths, so they are reclaimed while sessions keep overlapping. */
1045
+ export function releaseClonesUnusedSince(time: number): void {
1046
+ for (const [key, entry] of cloneCache) {
1047
+ if (!entry.settled || entry.lastUsedAt >= time) continue;
1048
+ removeCloneDestination(entry.destination);
1049
+ cloneCache.delete(key);
1050
+ }
1051
+ }
1052
+
1053
+ export function clearCloneCache(): void {
1054
+ for (const entry of cloneCache.values()) {
1055
+ removeCloneDestination(entry.destination);
1056
+ }
1057
+ cloneCache.clear();
1058
+
1059
+ if (cloneRuntime) {
1060
+ removeCloneRuntime(cloneRuntime.parentPath, cloneRuntime.rootPath);
1061
+ }
1062
+ cloneRuntime = null;
1063
+ cachedConfig = null;
1064
+ }