@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.
- package/ASTACK.md +23 -0
- package/CHANGELOG.md +1289 -0
- package/LICENSE +21 -0
- package/README.md +1215 -2
- package/SECURITY.md +5 -0
- package/abortable.ts +17 -0
- package/activity.ts +101 -0
- package/anysearch.ts +188 -0
- package/auth-fetch.ts +152 -0
- package/baizhi.ts +124 -0
- package/banner.png +0 -0
- package/bocha.ts +203 -0
- package/brave-rate-limit.ts +176 -0
- package/brave.ts +247 -0
- package/brightdata-unlocker.ts +272 -0
- package/ceramic.ts +220 -0
- package/chrome-cookies.ts +752 -0
- package/cloudflare-search.ts +237 -0
- package/content-find.ts +255 -0
- package/crawl4ai.ts +196 -0
- package/credential-source.ts +242 -0
- package/curator-page.ts +3607 -0
- package/curator-run.ts +45 -0
- package/curator-server.ts +761 -0
- package/custom-search.ts +226 -0
- package/data-uri-sanitize.ts +406 -0
- package/datalab-pdf-extract.ts +568 -0
- package/declared-web-links.ts +173 -0
- package/deepseek.ts +377 -0
- package/degoog.ts +323 -0
- package/dist/index.js +28286 -0
- package/dist/mcp-cli.js +29186 -0
- package/dist/pi-mcp.js +20855 -0
- package/dist/types/abortable.d.ts +2 -0
- package/dist/types/activity.d.ts +33 -0
- package/dist/types/anysearch.d.ts +7 -0
- package/dist/types/auth-fetch.d.ts +14 -0
- package/dist/types/baizhi.d.ts +3 -0
- package/dist/types/bocha.d.ts +3 -0
- package/dist/types/brave-rate-limit.d.ts +35 -0
- package/dist/types/brave.d.ts +3 -0
- package/dist/types/brightdata-unlocker.d.ts +11 -0
- package/dist/types/ceramic.d.ts +3 -0
- package/dist/types/chrome-cookies.d.ts +44 -0
- package/dist/types/cloudflare-search.d.ts +4 -0
- package/dist/types/content-find.d.ts +10 -0
- package/dist/types/crawl4ai.d.ts +8 -0
- package/dist/types/credential-source.d.ts +29 -0
- package/dist/types/curator-page.d.ts +5 -0
- package/dist/types/curator-run.d.ts +10 -0
- package/dist/types/curator-server.d.ts +72 -0
- package/dist/types/custom-search.d.ts +22 -0
- package/dist/types/data-uri-sanitize.d.ts +20 -0
- package/dist/types/datalab-pdf-extract.d.ts +59 -0
- package/dist/types/declared-web-links.d.ts +7 -0
- package/dist/types/deepseek.d.ts +13 -0
- package/dist/types/degoog.d.ts +3 -0
- package/dist/types/domain-filter-normalization.d.ts +9 -0
- package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
- package/dist/types/duckduckgo.d.ts +6 -0
- package/dist/types/endpoint-pdf-extract.d.ts +22 -0
- package/dist/types/exa.d.ts +17 -0
- package/dist/types/extract.d.ts +70 -0
- package/dist/types/feature-config.d.ts +2 -0
- package/dist/types/fetch-params.d.ts +39 -0
- package/dist/types/field-extract.d.ts +37 -0
- package/dist/types/firecrawl.d.ts +18 -0
- package/dist/types/gemini-adc.d.ts +9 -0
- package/dist/types/gemini-api.d.ts +37 -0
- package/dist/types/gemini-pdf-extract.d.ts +8 -0
- package/dist/types/gemini-search.d.ts +76 -0
- package/dist/types/gemini-url-context.d.ts +3 -0
- package/dist/types/gemini-web-config.d.ts +25 -0
- package/dist/types/gemini-web.d.ts +31 -0
- package/dist/types/github-api.d.ts +6 -0
- package/dist/types/github-extract.d.ts +19 -0
- package/dist/types/github-issue-pr.d.ts +28 -0
- package/dist/types/index.d.ts +53 -0
- package/dist/types/jina-search.d.ts +7 -0
- package/dist/types/kagi.d.ts +14 -0
- package/dist/types/keenable.d.ts +3 -0
- package/dist/types/kimi-search.d.ts +4 -0
- package/dist/types/linkup.d.ts +5 -0
- package/dist/types/mcp-cli.d.ts +2 -0
- package/dist/types/mcp-server.d.ts +10 -0
- package/dist/types/mcp-tool-definitions.d.ts +16 -0
- package/dist/types/mistral-search.d.ts +3 -0
- package/dist/types/ninerouter.d.ts +3 -0
- package/dist/types/offtopic-judge.d.ts +26 -0
- package/dist/types/ollama.d.ts +14 -0
- package/dist/types/openai-search.d.ts +23 -0
- package/dist/types/page-query.d.ts +22 -0
- package/dist/types/parallel-mcp.d.ts +10 -0
- package/dist/types/parallel.d.ts +13 -0
- package/dist/types/pdf-extract.d.ts +44 -0
- package/dist/types/perplexity.d.ts +26 -0
- package/dist/types/pi-mcp.d.ts +56 -0
- package/dist/types/pi-session-results.d.ts +8 -0
- package/dist/types/querit.d.ts +9 -0
- package/dist/types/query-rewrite.d.ts +2 -0
- package/dist/types/render-search-error.d.ts +56 -0
- package/dist/types/retrieval-only.d.ts +78 -0
- package/dist/types/rsc-extract.d.ts +11 -0
- package/dist/types/search-answer-formatting.d.ts +7 -0
- package/dist/types/search-result-count-normalization.d.ts +1 -0
- package/dist/types/searchinfinity.d.ts +7 -0
- package/dist/types/searxng.d.ts +3 -0
- package/dist/types/source-check.d.ts +102 -0
- package/dist/types/ssrf-protection.d.ts +66 -0
- package/dist/types/storage.d.ts +69 -0
- package/dist/types/summary-model-scope.d.ts +33 -0
- package/dist/types/summary-review.d.ts +30 -0
- package/dist/types/tabstack.d.ts +5 -0
- package/dist/types/tavily.d.ts +7 -0
- package/dist/types/tinyfish.d.ts +10 -0
- package/dist/types/tool-activation.d.ts +7 -0
- package/dist/types/tool-arguments.d.ts +1 -0
- package/dist/types/upgrade-notice.d.ts +6 -0
- package/dist/types/utils.d.ts +55 -0
- package/dist/types/valyu.d.ts +5 -0
- package/dist/types/video-extract.d.ts +15 -0
- package/dist/types/web-tool-contract.d.ts +98 -0
- package/dist/types/web-tool-core.d.ts +227 -0
- package/dist/types/xai-search.d.ts +12 -0
- package/dist/types/you.d.ts +3 -0
- package/dist/types/youtube-extract.d.ts +29 -0
- package/dist/types/zai.d.ts +3 -0
- package/docs/pi-mcp.md +41 -0
- package/domain-filter-normalization.ts +44 -0
- package/duckduckgo-rate-limit.ts +205 -0
- package/duckduckgo.ts +123 -0
- package/endpoint-pdf-extract.ts +225 -0
- package/exa.ts +620 -0
- package/extract.ts +1721 -0
- package/feature-config.ts +29 -0
- package/fetch-params.ts +147 -0
- package/field-extract.ts +347 -0
- package/firecrawl.ts +476 -0
- package/gemini-adc.ts +345 -0
- package/gemini-api.ts +368 -0
- package/gemini-pdf-extract.ts +108 -0
- package/gemini-search.ts +1162 -0
- package/gemini-url-context.ts +128 -0
- package/gemini-web-config.ts +131 -0
- package/gemini-web.ts +527 -0
- package/github-api.ts +197 -0
- package/github-extract.ts +1064 -0
- package/github-issue-pr.ts +717 -0
- package/index.ts +2819 -0
- package/jina-search.ts +275 -0
- package/kagi.ts +257 -0
- package/keenable.ts +222 -0
- package/kimi-search.ts +209 -0
- package/linkup.ts +170 -0
- package/mcp-cli.ts +40 -0
- package/mcp-server.ts +84 -0
- package/mcp-tool-definitions.ts +143 -0
- package/mistral-search.ts +268 -0
- package/ninerouter.ts +92 -0
- package/offtopic-judge.ts +72 -0
- package/ollama.ts +237 -0
- package/openai-search.ts +855 -0
- package/package.json +108 -4
- package/page-query.ts +185 -0
- package/parallel-mcp.ts +255 -0
- package/parallel.ts +373 -0
- package/pdf-extract.ts +447 -0
- package/perplexity.ts +245 -0
- package/pi-mcp.ts +139 -0
- package/pi-session-results.ts +40 -0
- package/pi-web-fetch-demo.mp4 +0 -0
- package/promise-try.d.ts +7 -0
- package/querit.ts +394 -0
- package/query-rewrite.ts +84 -0
- package/render-search-error.ts +170 -0
- package/retrieval-only.ts +102 -0
- package/rsc-extract.ts +338 -0
- package/search-answer-formatting.ts +11 -0
- package/search-result-count-normalization.ts +4 -0
- package/searchinfinity.ts +246 -0
- package/searxng.ts +236 -0
- package/source-check.ts +269 -0
- package/ssrf-protection.ts +602 -0
- package/storage.ts +547 -0
- package/summary-model-scope.ts +72 -0
- package/summary-review.ts +476 -0
- package/tabstack.ts +289 -0
- package/tavily.ts +257 -0
- package/tinyfish.ts +373 -0
- package/tool-activation.ts +169 -0
- package/tool-arguments.ts +23 -0
- package/upgrade-notice.ts +47 -0
- package/utils.ts +693 -0
- package/valyu.ts +177 -0
- package/video-extract.ts +398 -0
- package/web-tool-contract.ts +93 -0
- package/web-tool-core.ts +1810 -0
- package/xai-search.ts +443 -0
- package/you.ts +165 -0
- package/youtube-extract.ts +336 -0
- package/zai.ts +161 -0
package/storage.ts
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, type Stats, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import type { ExtractedContent } from "./extract.ts";
|
|
6
|
+
import type { SearchResult } from "./perplexity.ts";
|
|
7
|
+
import { getWebSearchConfigDir } from "./utils.ts";
|
|
8
|
+
|
|
9
|
+
const CACHE_TTL_MS = 60 * 60 * 1000;
|
|
10
|
+
const FETCH_CACHE_DIR = "web-search-cache";
|
|
11
|
+
const FETCH_CACHE_VERSION = 1;
|
|
12
|
+
const CACHE_KEY_PATTERN = /^[A-Za-z0-9_-]+\.json$/;
|
|
13
|
+
const CACHE_TMP_PATTERN = /^[A-Za-z0-9_-]+\.json\.\d+\.\d+(?:\.[a-f0-9]{32})?\.tmp$/;
|
|
14
|
+
const CACHE_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
15
|
+
const MAX_METADATA_TEXT = 8192;
|
|
16
|
+
const DEFAULT_CACHE_LIMITS = { maxEntries: 128, maxBytes: 128 * 1024 * 1024 };
|
|
17
|
+
const O_DIRECTORY = process.platform === "win32" ? 0 : (constants.O_DIRECTORY ?? 0);
|
|
18
|
+
const O_NOFOLLOW = process.platform === "win32" ? 0 : (constants.O_NOFOLLOW ?? 0);
|
|
19
|
+
|
|
20
|
+
interface FetchCacheLimits {
|
|
21
|
+
maxEntries: number;
|
|
22
|
+
maxBytes: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface CacheFile {
|
|
26
|
+
name: string;
|
|
27
|
+
size: number;
|
|
28
|
+
mtimeMs: number;
|
|
29
|
+
dev: number;
|
|
30
|
+
ino: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface QueryResultData {
|
|
34
|
+
query: string;
|
|
35
|
+
answer: string;
|
|
36
|
+
results: SearchResult[];
|
|
37
|
+
error: string | null;
|
|
38
|
+
provider?: string;
|
|
39
|
+
providers?: string[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface FetchCacheRef {
|
|
43
|
+
version: typeof FETCH_CACHE_VERSION;
|
|
44
|
+
key: string;
|
|
45
|
+
storedAt: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface StoredFetchUrlMetadata {
|
|
49
|
+
url: string;
|
|
50
|
+
title: string;
|
|
51
|
+
error: string | null;
|
|
52
|
+
contentLength: number;
|
|
53
|
+
mimeType?: string;
|
|
54
|
+
status?: number;
|
|
55
|
+
duration?: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface StoredSearchData {
|
|
59
|
+
id: string;
|
|
60
|
+
type: "search" | "fetch" | "research";
|
|
61
|
+
timestamp: number;
|
|
62
|
+
queries?: QueryResultData[];
|
|
63
|
+
urls?: ExtractedContent[];
|
|
64
|
+
artifact?: unknown;
|
|
65
|
+
fetchCache?: FetchCacheRef;
|
|
66
|
+
urlMetadata?: StoredFetchUrlMetadata[];
|
|
67
|
+
fetchCacheError?: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const storedResults = new Map<string, StoredSearchData>();
|
|
71
|
+
/** How many live sessions hold each result. Sessions forked from one history hold the same ids. */
|
|
72
|
+
const resultHolders = new Map<string, number>();
|
|
73
|
+
|
|
74
|
+
export function generateId(): string {
|
|
75
|
+
return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function getFetchCacheDir(): string {
|
|
79
|
+
// Always append our own folder: pruning deletes stale *.json files, so the override must
|
|
80
|
+
// never point pruning at a directory that holds user files.
|
|
81
|
+
return join(process.env.PI_WEB_ACCESS_CACHE_ROOT || getWebSearchConfigDir(), FETCH_CACHE_DIR);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function fetchCachePath(key: string): string | null {
|
|
85
|
+
if (!CACHE_KEY_PATTERN.test(key)) return null;
|
|
86
|
+
return join(getFetchCacheDir(), key);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function cacheKeyForId(id: string): string {
|
|
90
|
+
if (!CACHE_ID_PATTERN.test(id)) {
|
|
91
|
+
throw new Error(`Invalid fetched content cache id: ${id}`);
|
|
92
|
+
}
|
|
93
|
+
return `${id}.json`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function truncateMetadataText(value: string | undefined): string {
|
|
97
|
+
if (!value) return "";
|
|
98
|
+
return value.length > MAX_METADATA_TEXT ? `${value.slice(0, MAX_METADATA_TEXT)}...` : value;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function metadataForUrls(urls: ExtractedContent[]): StoredFetchUrlMetadata[] {
|
|
102
|
+
return urls.map((url) => ({
|
|
103
|
+
url: truncateMetadataText(url.url),
|
|
104
|
+
title: truncateMetadataText(url.title),
|
|
105
|
+
error: url.error ? truncateMetadataText(url.error) : null,
|
|
106
|
+
contentLength: url.content.length,
|
|
107
|
+
...(url.mimeType ? { mimeType: truncateMetadataText(url.mimeType) } : {}),
|
|
108
|
+
...(typeof url.status === "number" ? { status: url.status } : {}),
|
|
109
|
+
...(typeof url.duration === "number" ? { duration: url.duration } : {}),
|
|
110
|
+
}));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isFetchCacheRef(value: unknown): value is FetchCacheRef {
|
|
114
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
115
|
+
const ref = value as Record<string, unknown>;
|
|
116
|
+
return ref.version === FETCH_CACHE_VERSION &&
|
|
117
|
+
typeof ref.key === "string" && CACHE_KEY_PATTERN.test(ref.key) &&
|
|
118
|
+
typeof ref.storedAt === "number" && Number.isFinite(ref.storedAt);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function isStoredFetchUrlMetadata(value: unknown): value is StoredFetchUrlMetadata {
|
|
122
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
123
|
+
const meta = value as Record<string, unknown>;
|
|
124
|
+
return typeof meta.url === "string" &&
|
|
125
|
+
typeof meta.title === "string" &&
|
|
126
|
+
(meta.error === null || typeof meta.error === "string") &&
|
|
127
|
+
typeof meta.contentLength === "number" && Number.isFinite(meta.contentLength) && meta.contentLength >= 0 &&
|
|
128
|
+
(meta.mimeType === undefined || typeof meta.mimeType === "string") &&
|
|
129
|
+
(meta.status === undefined || typeof meta.status === "number") &&
|
|
130
|
+
(meta.duration === undefined || typeof meta.duration === "number");
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function isInlineFetchedUrl(value: unknown): value is ExtractedContent {
|
|
134
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
135
|
+
const url = value as Record<string, unknown>;
|
|
136
|
+
return typeof url.url === "string" &&
|
|
137
|
+
typeof url.title === "string" &&
|
|
138
|
+
typeof url.content === "string" &&
|
|
139
|
+
(url.error === null || typeof url.error === "string");
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function isInlineFetchData(data: StoredSearchData): data is StoredSearchData & { urls: ExtractedContent[] } {
|
|
143
|
+
return data.type === "fetch" && Array.isArray(data.urls) && data.urls.every(isInlineFetchedUrl);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function cacheLimits(limits?: Partial<FetchCacheLimits>): FetchCacheLimits {
|
|
147
|
+
const resolved = {
|
|
148
|
+
maxEntries: limits?.maxEntries ?? DEFAULT_CACHE_LIMITS.maxEntries,
|
|
149
|
+
maxBytes: limits?.maxBytes ?? DEFAULT_CACHE_LIMITS.maxBytes,
|
|
150
|
+
};
|
|
151
|
+
if (!Number.isFinite(resolved.maxEntries) || !Number.isInteger(resolved.maxEntries) || resolved.maxEntries <= 0 ||
|
|
152
|
+
!Number.isFinite(resolved.maxBytes) || !Number.isInteger(resolved.maxBytes) || resolved.maxBytes <= 0) {
|
|
153
|
+
throw new Error("Fetched content cache limits must be finite positive integers");
|
|
154
|
+
}
|
|
155
|
+
return resolved;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function enforceMode(fd: number, mode: number): void {
|
|
159
|
+
try {
|
|
160
|
+
fchmodSync(fd, mode);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
if (process.platform !== "win32") throw err;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function safeFetchCacheDir(create: true): string;
|
|
167
|
+
function safeFetchCacheDir(create: false): string | null;
|
|
168
|
+
function safeFetchCacheDir(create: boolean): string | null {
|
|
169
|
+
const dir = getFetchCacheDir();
|
|
170
|
+
if (create) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
171
|
+
let before: Stats;
|
|
172
|
+
try {
|
|
173
|
+
before = lstatSync(dir);
|
|
174
|
+
} catch (err) {
|
|
175
|
+
if (!create && (err as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
176
|
+
throw err;
|
|
177
|
+
}
|
|
178
|
+
if (before.isSymbolicLink() || !before.isDirectory()) {
|
|
179
|
+
throw new Error("Fetched content cache path is not a safe directory");
|
|
180
|
+
}
|
|
181
|
+
if (process.platform !== "win32") {
|
|
182
|
+
const fd = openSync(dir, constants.O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
|
|
183
|
+
try {
|
|
184
|
+
const opened = fstatSync(fd);
|
|
185
|
+
if (!opened.isDirectory() || opened.dev !== before.dev || opened.ino !== before.ino) {
|
|
186
|
+
throw new Error("Fetched content cache directory changed while opening");
|
|
187
|
+
}
|
|
188
|
+
enforceMode(fd, 0o700);
|
|
189
|
+
} finally {
|
|
190
|
+
closeSync(fd);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const after = lstatSync(dir);
|
|
194
|
+
if (after.isSymbolicLink() || !after.isDirectory() || after.dev !== before.dev || after.ino !== before.ino) {
|
|
195
|
+
throw new Error("Fetched content cache directory changed while securing it");
|
|
196
|
+
}
|
|
197
|
+
return dir;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function openRegularFile(path: string): { fd: number; info: Stats } {
|
|
201
|
+
const before = lstatSync(path);
|
|
202
|
+
if (before.isSymbolicLink() || !before.isFile()) throw new Error("Fetched content cache entry is not a regular file");
|
|
203
|
+
const fd = openSync(path, constants.O_RDONLY | O_NOFOLLOW);
|
|
204
|
+
try {
|
|
205
|
+
const info = fstatSync(fd);
|
|
206
|
+
if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino) {
|
|
207
|
+
throw new Error("Fetched content cache entry changed while opening");
|
|
208
|
+
}
|
|
209
|
+
return { fd, info };
|
|
210
|
+
} catch (err) {
|
|
211
|
+
closeSync(fd);
|
|
212
|
+
throw err;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// True once the entry is gone; false when the directory or entry changed underneath us or could not be removed.
|
|
217
|
+
function unlinkCacheFile(dir: string, file: CacheFile): boolean {
|
|
218
|
+
try {
|
|
219
|
+
const root = lstatSync(dir);
|
|
220
|
+
if (root.isSymbolicLink() || !root.isDirectory()) return false;
|
|
221
|
+
} catch {
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
const path = join(dir, file.name);
|
|
226
|
+
const current = lstatSync(path);
|
|
227
|
+
if (current.isSymbolicLink() || !current.isFile() || current.dev !== file.dev || current.ino !== file.ino) return false;
|
|
228
|
+
unlinkSync(path);
|
|
229
|
+
return true;
|
|
230
|
+
} catch (err) {
|
|
231
|
+
return (err as NodeJS.ErrnoException).code === "ENOENT";
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function pruneFetchCache(now: number, limits: FetchCacheLimits, preferredKey?: string, reservation?: { key: string; bytes: number }): boolean {
|
|
236
|
+
let dir: string | null;
|
|
237
|
+
try {
|
|
238
|
+
dir = safeFetchCacheDir(false);
|
|
239
|
+
} catch {
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
if (!dir) return true;
|
|
243
|
+
|
|
244
|
+
let entries: string[];
|
|
245
|
+
try {
|
|
246
|
+
entries = readdirSync(dir);
|
|
247
|
+
} catch {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const files: CacheFile[] = [];
|
|
252
|
+
for (const entry of entries) {
|
|
253
|
+
if (!CACHE_KEY_PATTERN.test(entry) && !CACHE_TMP_PATTERN.test(entry)) continue;
|
|
254
|
+
let info: Stats;
|
|
255
|
+
try {
|
|
256
|
+
const opened = openRegularFile(join(dir, entry));
|
|
257
|
+
info = opened.info;
|
|
258
|
+
try {
|
|
259
|
+
enforceMode(opened.fd, 0o600);
|
|
260
|
+
} finally {
|
|
261
|
+
closeSync(opened.fd);
|
|
262
|
+
}
|
|
263
|
+
} catch {
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
const file = { name: entry, size: info.size, mtimeMs: info.mtimeMs, dev: info.dev, ino: info.ino };
|
|
267
|
+
if (now - file.mtimeMs >= CACHE_TTL_MS) {
|
|
268
|
+
if (!unlinkCacheFile(dir, file)) return false;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
if (CACHE_KEY_PATTERN.test(entry)) files.push(file);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
files.sort((a, b) => a.mtimeMs - b.mtimeMs || a.name.localeCompare(b.name));
|
|
275
|
+
const projectedUsage = () => {
|
|
276
|
+
const replaced = reservation ? files.find((file) => file.name === reservation.key) : undefined;
|
|
277
|
+
return {
|
|
278
|
+
entries: files.length + (reservation && !replaced ? 1 : 0),
|
|
279
|
+
bytes: files.reduce((total, file) => total + file.size, 0) + (reservation ? reservation.bytes - (replaced?.size ?? 0) : 0),
|
|
280
|
+
};
|
|
281
|
+
};
|
|
282
|
+
const attempted = new Set<string>();
|
|
283
|
+
let usage = projectedUsage();
|
|
284
|
+
while (usage.entries > limits.maxEntries || usage.bytes > limits.maxBytes) {
|
|
285
|
+
const index = files.findIndex((file) => file.name !== preferredKey && !attempted.has(file.name));
|
|
286
|
+
if (index < 0) break;
|
|
287
|
+
const file = files[index];
|
|
288
|
+
attempted.add(file.name);
|
|
289
|
+
if (unlinkCacheFile(dir, file)) files.splice(index, 1);
|
|
290
|
+
usage = projectedUsage();
|
|
291
|
+
}
|
|
292
|
+
return usage.entries <= limits.maxEntries && usage.bytes <= limits.maxBytes;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function writeFetchCache(data: StoredSearchData & { urls: ExtractedContent[] }): FetchCacheRef {
|
|
296
|
+
const limits = DEFAULT_CACHE_LIMITS;
|
|
297
|
+
const serialized = JSON.stringify(data);
|
|
298
|
+
const size = Buffer.byteLength(serialized);
|
|
299
|
+
if (size > limits.maxBytes) throw new Error(`Fetched content cache entry exceeds ${limits.maxBytes} bytes`);
|
|
300
|
+
|
|
301
|
+
const dir = safeFetchCacheDir(true);
|
|
302
|
+
const key = cacheKeyForId(data.id);
|
|
303
|
+
if (!pruneFetchCache(Date.now(), limits, key, { key, bytes: size })) {
|
|
304
|
+
throw new Error("Fetched content cache could not reserve space for a new entry");
|
|
305
|
+
}
|
|
306
|
+
const finalPath = join(dir, key);
|
|
307
|
+
const tmpName = `${key}.${process.pid}.${Date.now()}.${randomBytes(16).toString("hex")}.tmp`;
|
|
308
|
+
const tmpPath = join(dir, tmpName);
|
|
309
|
+
let fd: number | null = null;
|
|
310
|
+
let tmpFile: CacheFile | null = null;
|
|
311
|
+
let renamed = false;
|
|
312
|
+
try {
|
|
313
|
+
fd = openSync(tmpPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | O_NOFOLLOW, 0o600);
|
|
314
|
+
const tmpInfo = fstatSync(fd);
|
|
315
|
+
tmpFile = { name: tmpName, size: tmpInfo.size, mtimeMs: tmpInfo.mtimeMs, dev: tmpInfo.dev, ino: tmpInfo.ino };
|
|
316
|
+
enforceMode(fd, 0o600);
|
|
317
|
+
writeFileSync(fd, serialized, "utf8");
|
|
318
|
+
fsyncSync(fd);
|
|
319
|
+
closeSync(fd);
|
|
320
|
+
fd = null;
|
|
321
|
+
safeFetchCacheDir(false);
|
|
322
|
+
renameSync(tmpPath, finalPath);
|
|
323
|
+
renamed = true;
|
|
324
|
+
const written = lstatSync(finalPath);
|
|
325
|
+
if (!written.isFile() || written.dev !== tmpFile.dev || written.ino !== tmpFile.ino) {
|
|
326
|
+
throw new Error("Fetched content cache entry changed after writing");
|
|
327
|
+
}
|
|
328
|
+
if (!pruneFetchCache(Date.now(), limits, key)) {
|
|
329
|
+
throw new Error("Fetched content cache could not meet its limits after writing");
|
|
330
|
+
}
|
|
331
|
+
} catch (err) {
|
|
332
|
+
if (fd !== null) try { closeSync(fd); } catch {}
|
|
333
|
+
if (tmpFile) unlinkCacheFile(dir, { ...tmpFile, name: renamed ? key : tmpName });
|
|
334
|
+
throw err;
|
|
335
|
+
}
|
|
336
|
+
return { version: FETCH_CACHE_VERSION, key, storedAt: Date.now() };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function createFetchSessionData(data: StoredSearchData & { urls: ExtractedContent[] }, ref: FetchCacheRef | null, cacheError?: string): StoredSearchData {
|
|
340
|
+
return {
|
|
341
|
+
id: data.id,
|
|
342
|
+
type: "fetch",
|
|
343
|
+
timestamp: data.timestamp,
|
|
344
|
+
urlMetadata: metadataForUrls(data.urls),
|
|
345
|
+
...(ref ? { fetchCache: ref } : {}),
|
|
346
|
+
...(cacheError ? { fetchCacheError: truncateMetadataText(cacheError) } : {}),
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function fetchUrlMetadata(data: StoredSearchData): StoredFetchUrlMetadata[] {
|
|
351
|
+
if (data.urlMetadata) return data.urlMetadata;
|
|
352
|
+
return isInlineFetchData(data) ? metadataForUrls(data.urls) : [];
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function unavailableFetchData(data: StoredSearchData, reason: string): StoredSearchData {
|
|
356
|
+
return {
|
|
357
|
+
...data,
|
|
358
|
+
urls: fetchUrlMetadata(data).map((meta) => ({
|
|
359
|
+
url: meta.url,
|
|
360
|
+
title: meta.title,
|
|
361
|
+
content: "",
|
|
362
|
+
error: reason,
|
|
363
|
+
...(meta.mimeType ? { mimeType: meta.mimeType } : {}),
|
|
364
|
+
...(typeof meta.status === "number" ? { status: meta.status } : {}),
|
|
365
|
+
...(typeof meta.duration === "number" ? { duration: meta.duration } : {}),
|
|
366
|
+
})),
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function readCachedFetchData(data: StoredSearchData): StoredSearchData {
|
|
371
|
+
if (data.type !== "fetch") return data;
|
|
372
|
+
if (Date.now() - data.timestamp >= CACHE_TTL_MS) {
|
|
373
|
+
return unavailableFetchData(data, "Cached fetched content is missing or expired");
|
|
374
|
+
}
|
|
375
|
+
if (isInlineFetchData(data)) return data;
|
|
376
|
+
if (!data.fetchCache) {
|
|
377
|
+
return unavailableFetchData(data, data.fetchCacheError ?? "Cached fetched content is unavailable");
|
|
378
|
+
}
|
|
379
|
+
const path = fetchCachePath(data.fetchCache.key);
|
|
380
|
+
if (!path) return unavailableFetchData(data, "Cached fetched content is missing or expired");
|
|
381
|
+
let fd: number | null = null;
|
|
382
|
+
try {
|
|
383
|
+
if (!safeFetchCacheDir(false)) return unavailableFetchData(data, "Cached fetched content is missing or expired");
|
|
384
|
+
const opened = openRegularFile(path);
|
|
385
|
+
fd = opened.fd;
|
|
386
|
+
enforceMode(fd, 0o600);
|
|
387
|
+
const parsed: unknown = JSON.parse(readFileSync(fd, "utf8"));
|
|
388
|
+
if (!isValidStoredData(parsed) || parsed.type !== "fetch" || parsed.id !== data.id || !isInlineFetchData(parsed)) {
|
|
389
|
+
return unavailableFetchData(data, "Cached fetched content is invalid");
|
|
390
|
+
}
|
|
391
|
+
return { ...parsed, fetchCache: data.fetchCache, urlMetadata: data.urlMetadata };
|
|
392
|
+
} catch (err) {
|
|
393
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
394
|
+
return unavailableFetchData(data, "Cached fetched content is missing or expired");
|
|
395
|
+
}
|
|
396
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
397
|
+
return unavailableFetchData(data, `Cached fetched content could not be read: ${message}`);
|
|
398
|
+
} finally {
|
|
399
|
+
if (fd !== null) try { closeSync(fd); } catch {}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function pruneExpiredFetchedResults(now: number): void {
|
|
404
|
+
for (const [id, data] of storedResults) {
|
|
405
|
+
if (data.type === "fetch" && now - data.timestamp >= CACHE_TTL_MS) {
|
|
406
|
+
storedResults.set(id, unavailableFetchData(data, "Cached fetched content is missing or expired"));
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export function pruneExpiredFetchCache(now = Date.now(), requestedLimits?: Partial<FetchCacheLimits>): void {
|
|
412
|
+
const limits = cacheLimits(requestedLimits);
|
|
413
|
+
pruneExpiredFetchedResults(now);
|
|
414
|
+
try { pruneFetchCache(now, limits); } catch {}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export function storeResult(id: string, data: StoredSearchData): void {
|
|
418
|
+
storedResults.set(id, data);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
export function storeFetchedContentResult(id: string, data: StoredSearchData & { type: "fetch"; urls: ExtractedContent[] }): StoredSearchData {
|
|
422
|
+
pruneExpiredFetchedResults(Date.now());
|
|
423
|
+
let ref: FetchCacheRef | null = null;
|
|
424
|
+
let cacheError: string | undefined;
|
|
425
|
+
try {
|
|
426
|
+
ref = writeFetchCache(data);
|
|
427
|
+
} catch (err) {
|
|
428
|
+
cacheError = `Failed to write fetched content cache: ${err instanceof Error ? err.message : String(err)}`;
|
|
429
|
+
}
|
|
430
|
+
const sessionData = createFetchSessionData(data, ref, cacheError);
|
|
431
|
+
// Content written to the disk cache is read back from there, so memory stays within the cache's limits.
|
|
432
|
+
// Only a failed write keeps it in memory, where it has nowhere else to live.
|
|
433
|
+
storedResults.set(id, ref ? sessionData : { ...data, fetchCacheError: cacheError });
|
|
434
|
+
return sessionData;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export function getResult(id: string): StoredSearchData | null {
|
|
438
|
+
const data = storedResults.get(id);
|
|
439
|
+
if (!data) return null;
|
|
440
|
+
const loaded = readCachedFetchData(data);
|
|
441
|
+
// Content read from the disk cache is not kept, so a file the cache evicted reads as missing.
|
|
442
|
+
if (loaded !== data && !data.fetchCache) storedResults.set(id, loaded);
|
|
443
|
+
return loaded;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
export function getAllResults(): StoredSearchData[] {
|
|
447
|
+
return Array.from(storedResults.values());
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export function deleteResult(id: string): boolean {
|
|
451
|
+
const data = storedResults.get(id);
|
|
452
|
+
if (data?.fetchCache) {
|
|
453
|
+
try {
|
|
454
|
+
const dir = safeFetchCacheDir(false);
|
|
455
|
+
const path = fetchCachePath(data.fetchCache.key);
|
|
456
|
+
if (dir && path) {
|
|
457
|
+
const info = lstatSync(path);
|
|
458
|
+
if (!info.isSymbolicLink() && info.isFile()) {
|
|
459
|
+
unlinkCacheFile(dir, { name: data.fetchCache.key, size: info.size, mtimeMs: info.mtimeMs, dev: info.dev, ino: info.ino });
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
} catch {}
|
|
463
|
+
}
|
|
464
|
+
resultHolders.delete(id);
|
|
465
|
+
return storedResults.delete(id);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
export function clearResults(): void {
|
|
469
|
+
storedResults.clear();
|
|
470
|
+
resultHolders.clear();
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Record that one more live session holds each of these results. */
|
|
474
|
+
export function holdResults(ids: Iterable<string>): void {
|
|
475
|
+
for (const id of ids) resultHolders.set(id, (resultHolders.get(id) ?? 0) + 1);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** Release one session's hold on each result, and drop a result from memory once no live
|
|
479
|
+
* session holds it. Unlike deleteResult, the fetch cache files stay: the session journal
|
|
480
|
+
* still references them, and a later restore reads them back. */
|
|
481
|
+
export function releaseResults(ids: Iterable<string>): void {
|
|
482
|
+
for (const id of ids) {
|
|
483
|
+
const holders = (resultHolders.get(id) ?? 0) - 1;
|
|
484
|
+
if (holders > 0) {
|
|
485
|
+
resultHolders.set(id, holders);
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
resultHolders.delete(id);
|
|
489
|
+
storedResults.delete(id);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** Delete a result for one session that holds it. Other live sessions holding the same
|
|
494
|
+
* result keep it and its fetch cache file; the last holder deletes both. */
|
|
495
|
+
export function deleteHeldResult(id: string): void {
|
|
496
|
+
if ((resultHolders.get(id) ?? 0) > 1) releaseResults([id]);
|
|
497
|
+
else deleteResult(id);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function isValidStoredData(data: unknown): data is StoredSearchData {
|
|
501
|
+
if (!data || typeof data !== "object") return false;
|
|
502
|
+
const d = data as Record<string, unknown>;
|
|
503
|
+
if (typeof d.id !== "string" || !d.id) return false;
|
|
504
|
+
if (d.type !== "search" && d.type !== "fetch" && d.type !== "research") return false;
|
|
505
|
+
if (typeof d.timestamp !== "number") return false;
|
|
506
|
+
if (d.type === "search" && !Array.isArray(d.queries)) return false;
|
|
507
|
+
if (d.type === "fetch") {
|
|
508
|
+
if (Array.isArray(d.urls)) return d.urls.every(isInlineFetchedUrl);
|
|
509
|
+
if (!Array.isArray(d.urlMetadata) || !d.urlMetadata.every(isStoredFetchUrlMetadata)) return false;
|
|
510
|
+
return d.fetchCache === undefined ? d.fetchCacheError === undefined || typeof d.fetchCacheError === "string" : isFetchCacheRef(d.fetchCache);
|
|
511
|
+
}
|
|
512
|
+
if (d.type === "research" && (!d.artifact || typeof d.artifact !== "object")) return false;
|
|
513
|
+
return true;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
export function restoreFromSession(ctx: ExtensionContext): void {
|
|
517
|
+
storedResults.clear();
|
|
518
|
+
loadSessionResults(ctx);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Add one session's stored results to memory, leaving other sessions' results in place,
|
|
522
|
+
* and return the results it loaded. A host that runs several sessions at once (one extension
|
|
523
|
+
* instance per session) restores each with this, holds their ids with holdResults, and
|
|
524
|
+
* releases them with releaseResults. */
|
|
525
|
+
export function loadSessionResults(ctx: ExtensionContext): StoredSearchData[] {
|
|
526
|
+
const now = Date.now();
|
|
527
|
+
pruneExpiredFetchCache(now);
|
|
528
|
+
|
|
529
|
+
const loaded: StoredSearchData[] = [];
|
|
530
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
531
|
+
if (entry.type === "custom" && entry.customType === "web-search-results") {
|
|
532
|
+
const data = entry.data;
|
|
533
|
+
if (isValidStoredData(data) && now - data.timestamp < CACHE_TTL_MS) {
|
|
534
|
+
// Another live session may hold this result with its fetched content in memory after a
|
|
535
|
+
// failed cache write; the journal copy holds only metadata.
|
|
536
|
+
const live = storedResults.get(data.id);
|
|
537
|
+
if (live) {
|
|
538
|
+
loaded.push(live);
|
|
539
|
+
continue;
|
|
540
|
+
}
|
|
541
|
+
storedResults.set(data.id, data);
|
|
542
|
+
loaded.push(data);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
return loaded;
|
|
547
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
2
|
+
|
|
3
|
+
export type SummaryThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
4
|
+
|
|
5
|
+
export interface ModelLike {
|
|
6
|
+
provider: string;
|
|
7
|
+
id: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface ModelRegistryLike<T extends ModelLike = ModelLike> {
|
|
11
|
+
find(provider: string, id: string): T | undefined;
|
|
12
|
+
getAvailable(): readonly T[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Resolve a model through its native provider or a provider that routes that model ID.
|
|
17
|
+
*
|
|
18
|
+
* The direct registry fallback preserves explicit/native model resolution when a
|
|
19
|
+
* provider's availability snapshot does not include the configured model. Callers
|
|
20
|
+
* continue to apply their existing enabled-model and authentication checks.
|
|
21
|
+
*/
|
|
22
|
+
export function findModelWithProviderRouting<T extends ModelLike>(
|
|
23
|
+
registry: ModelRegistryLike<T>,
|
|
24
|
+
provider: string,
|
|
25
|
+
id: string,
|
|
26
|
+
): T | undefined {
|
|
27
|
+
const available = registry.getAvailable();
|
|
28
|
+
const direct = available.find(model => model.provider === provider && model.id === id);
|
|
29
|
+
if (direct) return direct;
|
|
30
|
+
|
|
31
|
+
const routedId = `${provider}/${id}`;
|
|
32
|
+
// If multiple routers expose the same model ID, Pi's available-model ordering
|
|
33
|
+
// determines which route is selected. An explicit provider/model selector can
|
|
34
|
+
// select a specific route when that distinction matters.
|
|
35
|
+
const routed = available.find(model => model.id === routedId);
|
|
36
|
+
return routed ?? registry.find(provider, id);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Pi resolves `--models` and `enabledModels` against the available catalogue and exposes the
|
|
41
|
+
* result as `ctx.scopedModels`; an empty scope means every available model is allowed.
|
|
42
|
+
*/
|
|
43
|
+
export function isModelInScope(model: ModelLike, scopedModels: ReadonlyArray<{ model: ModelLike }>): boolean {
|
|
44
|
+
return scopedModels.length === 0 || scopedModels.some(scoped => scoped.model.provider === model.provider && scoped.model.id === model.id);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function splitThinkingSuffix(value: string): { value: string; thinkingLevel?: SummaryThinkingLevel } {
|
|
48
|
+
const index = value.lastIndexOf(":");
|
|
49
|
+
if (index < 0) return { value };
|
|
50
|
+
const suffix = value.slice(index + 1);
|
|
51
|
+
return THINKING_LEVELS.has(suffix)
|
|
52
|
+
? { value: value.slice(0, index), thinkingLevel: suffix as SummaryThinkingLevel }
|
|
53
|
+
: { value };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Parse `current[:level]` or `provider/model-id[:level]`; `current` names the active Pi session model and
|
|
58
|
+
* resolves to undefined when there is none. Throws for any other value.
|
|
59
|
+
*/
|
|
60
|
+
export function resolveHelperModelSelector(
|
|
61
|
+
value: string,
|
|
62
|
+
label: string,
|
|
63
|
+
currentModel?: ModelLike,
|
|
64
|
+
): { provider: string; id: string; thinkingLevel?: SummaryThinkingLevel } | undefined {
|
|
65
|
+
const { value: selector, thinkingLevel } = splitThinkingSuffix(value.trim());
|
|
66
|
+
if (selector === "current") return currentModel ? { provider: currentModel.provider, id: currentModel.id, thinkingLevel } : undefined;
|
|
67
|
+
const slashIndex = selector.indexOf("/");
|
|
68
|
+
if (slashIndex <= 0 || slashIndex >= selector.length - 1) {
|
|
69
|
+
throw new Error(`Invalid ${label}: ${value}. Use provider/model-id or current.`);
|
|
70
|
+
}
|
|
71
|
+
return { provider: selector.slice(0, slashIndex), id: selector.slice(slashIndex + 1), thinkingLevel };
|
|
72
|
+
}
|