@leolastforce/chalice-code-index 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/LICENSE +21 -0
- package/README.md +58 -2
- package/index.ts +1 -0
- package/package.json +48 -5
- package/src/chunking.ts +305 -0
- package/src/config.ts +245 -0
- package/src/embeddings.ts +130 -0
- package/src/filtering.ts +221 -0
- package/src/index.ts +480 -0
- package/src/indexer.ts +153 -0
- package/src/project.ts +76 -0
- package/src/section.ts +159 -0
- package/src/store.ts +208 -0
- package/src/tagging.ts +247 -0
- package/src/tool.ts +146 -0
- package/src/types.ts +146 -0
- package/src/ui.ts +45 -0
- package/src/watcher.ts +168 -0
package/src/config.ts
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import type { ApiKeySource, GlobalConfig, ProjectInfo, ProjectState, ProviderId, ProviderPreset, ResolvedConfig } from "./types.ts";
|
|
7
|
+
|
|
8
|
+
export const AGENT_DIR = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
9
|
+
export const DATA_DIR = join(AGENT_DIR, "code-index");
|
|
10
|
+
export const GLOBAL_CONFIG_PATH = join(DATA_DIR, "config.json");
|
|
11
|
+
export const AUTH_FILE_PATH = join(AGENT_DIR, "auth.json");
|
|
12
|
+
|
|
13
|
+
export const PROVIDER_PRESETS: Record<ProviderId, ProviderPreset> = {
|
|
14
|
+
voyage: {
|
|
15
|
+
id: "voyage",
|
|
16
|
+
label: "Voyage AI (code, default)",
|
|
17
|
+
baseUrl: "https://api.voyageai.com/v1/embeddings",
|
|
18
|
+
model: "voyage-code-3",
|
|
19
|
+
apiKeyEnv: "VOYAGE_API_KEY",
|
|
20
|
+
embeddingDim: 1024,
|
|
21
|
+
pricePerMillionTokens: 0.12,
|
|
22
|
+
},
|
|
23
|
+
openrouter: {
|
|
24
|
+
id: "openrouter",
|
|
25
|
+
label: "OpenRouter (general fallback)",
|
|
26
|
+
baseUrl: "https://openrouter.ai/api/v1/embeddings",
|
|
27
|
+
model: "openai/text-embedding-3-large",
|
|
28
|
+
apiKeyEnv: "OPENROUTER_API_KEY",
|
|
29
|
+
embeddingDim: 3072,
|
|
30
|
+
pricePerMillionTokens: 0.13,
|
|
31
|
+
},
|
|
32
|
+
local: {
|
|
33
|
+
id: "local",
|
|
34
|
+
label: "Local OpenAI-compatible embeddings",
|
|
35
|
+
baseUrl: "http://127.0.0.1:11434/v1/embeddings",
|
|
36
|
+
model: "nomic-embed-text",
|
|
37
|
+
embeddingDim: undefined,
|
|
38
|
+
pricePerMillionTokens: 0,
|
|
39
|
+
},
|
|
40
|
+
custom: {
|
|
41
|
+
id: "custom",
|
|
42
|
+
label: "Custom OpenAI-compatible embeddings",
|
|
43
|
+
baseUrl: "https://api.voyageai.com/v1/embeddings",
|
|
44
|
+
model: "voyage-code-3",
|
|
45
|
+
apiKeyEnv: "VOYAGE_API_KEY",
|
|
46
|
+
embeddingDim: 1024,
|
|
47
|
+
pricePerMillionTokens: 0.12,
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export const DEFAULT_EXCLUDE_DIRS = [
|
|
52
|
+
".git",
|
|
53
|
+
CONFIG_DIR_NAME,
|
|
54
|
+
"node_modules",
|
|
55
|
+
"dist",
|
|
56
|
+
"build",
|
|
57
|
+
"target",
|
|
58
|
+
".venv",
|
|
59
|
+
"venv",
|
|
60
|
+
"vendor",
|
|
61
|
+
".next",
|
|
62
|
+
".cache",
|
|
63
|
+
"coverage",
|
|
64
|
+
".turbo",
|
|
65
|
+
".pnpm-store",
|
|
66
|
+
"__pycache__",
|
|
67
|
+
".pytest_cache",
|
|
68
|
+
".ruff_cache",
|
|
69
|
+
".mypy_cache",
|
|
70
|
+
".omc",
|
|
71
|
+
".omo",
|
|
72
|
+
".omx",
|
|
73
|
+
".kilo",
|
|
74
|
+
".codegraph",
|
|
75
|
+
".playwright-mcp",
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
export const DEFAULT_CONFIG: GlobalConfig = {
|
|
79
|
+
provider: "voyage",
|
|
80
|
+
batchSize: 32,
|
|
81
|
+
requestConcurrency: 2,
|
|
82
|
+
timeoutMs: 45_000,
|
|
83
|
+
chunkLines: 80,
|
|
84
|
+
chunkOverlap: 20,
|
|
85
|
+
maxFileBytes: 768 * 1024,
|
|
86
|
+
maxChunkChars: 12_000,
|
|
87
|
+
watcherDebounceMs: 1000,
|
|
88
|
+
watcherBulkThreshold: 50,
|
|
89
|
+
largeRepoConfirmChunks: 5000,
|
|
90
|
+
annIndexThreshold: 50_000,
|
|
91
|
+
maxTopK: 50,
|
|
92
|
+
// Minimum similarity (score = 1/(1+distance), range (0,1]) for a result to be returned; 0 = off.
|
|
93
|
+
// Borrowed from claude-context's 0.5 cutoff — trims low-relevance noise, does NOT raise recall.
|
|
94
|
+
scoreThreshold: 0,
|
|
95
|
+
// Chars of the preceding chunk folded into each chunk's EMBEDDED text for cross-boundary context
|
|
96
|
+
// (agent-facing content + line range stay exact); 0 = off. A/B test via eval before enabling.
|
|
97
|
+
chunkOverlapChars: 0,
|
|
98
|
+
excludeDirs: DEFAULT_EXCLUDE_DIRS,
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// Single source of truth for the scalar fields that change the STORED vectors. Both the settings UI
|
|
102
|
+
// (which prompts "reindex") and manifestCompatible (which enforces staleness) derive from this list,
|
|
103
|
+
// so the "asks you to reindex" set and the "detects stale" set can never drift apart.
|
|
104
|
+
export const INDEX_AFFECTING_KEYS = ["maxChunkChars", "chunkOverlapChars", "chunkLines", "chunkOverlap", "maxFileBytes"] as const;
|
|
105
|
+
|
|
106
|
+
async function readJson<T>(path: string): Promise<T | undefined> {
|
|
107
|
+
try {
|
|
108
|
+
return JSON.parse(await readFile(path, "utf8")) as T;
|
|
109
|
+
} catch {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function writeJson(path: string, data: unknown): Promise<void> {
|
|
115
|
+
await mkdir(join(path, ".."), { recursive: true });
|
|
116
|
+
await writeFile(path, `${JSON.stringify(data, null, "\t")}\n`, "utf8");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function loadGlobalConfig(): Promise<GlobalConfig> {
|
|
120
|
+
await mkdir(DATA_DIR, { recursive: true });
|
|
121
|
+
const existing = await readJson<Partial<GlobalConfig>>(GLOBAL_CONFIG_PATH);
|
|
122
|
+
if (!existing) {
|
|
123
|
+
await writeJson(GLOBAL_CONFIG_PATH, DEFAULT_CONFIG);
|
|
124
|
+
return { ...DEFAULT_CONFIG };
|
|
125
|
+
}
|
|
126
|
+
const merged = { ...DEFAULT_CONFIG, ...existing };
|
|
127
|
+
return merged;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Synchronous read for single-frame UI such as the `/chalicesettings` list, which cannot await.
|
|
132
|
+
* Always merges over the defaults so a partial config file still resolves.
|
|
133
|
+
*/
|
|
134
|
+
export function readGlobalConfigSync(): GlobalConfig {
|
|
135
|
+
try {
|
|
136
|
+
const parsed: unknown = JSON.parse(readFileSync(GLOBAL_CONFIG_PATH, "utf8"));
|
|
137
|
+
return isRecord(parsed) ? { ...DEFAULT_CONFIG, ...(parsed as Partial<GlobalConfig>) } : { ...DEFAULT_CONFIG };
|
|
138
|
+
} catch {
|
|
139
|
+
return { ...DEFAULT_CONFIG };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function saveGlobalConfig(config: GlobalConfig): Promise<void> {
|
|
144
|
+
const sanitized = { ...config } as Record<string, unknown>;
|
|
145
|
+
delete sanitized.apiKey;
|
|
146
|
+
await writeJson(GLOBAL_CONFIG_PATH, sanitized);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
150
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function readPiAuthData(): Promise<Record<string, unknown>> {
|
|
154
|
+
try {
|
|
155
|
+
const parsed: unknown = JSON.parse(await readFile(AUTH_FILE_PATH, "utf8"));
|
|
156
|
+
if (!isRecord(parsed)) throw new Error("pi auth.json must contain an object");
|
|
157
|
+
return parsed;
|
|
158
|
+
} catch (error) {
|
|
159
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
|
|
160
|
+
throw error;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function loadStoredApiKey(provider: ProviderId): Promise<string | undefined> {
|
|
165
|
+
const authData = await readPiAuthData();
|
|
166
|
+
const entry = authData[`code-index-${provider}`];
|
|
167
|
+
if (!isRecord(entry) || typeof entry.key !== "string") return undefined;
|
|
168
|
+
return entry.key.trim() || undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export async function saveStoredApiKey(provider: ProviderId, key: string | undefined): Promise<void> {
|
|
172
|
+
const authData = await readPiAuthData();
|
|
173
|
+
const id = `code-index-${provider}`;
|
|
174
|
+
if (key?.trim()) {
|
|
175
|
+
authData[id] = { type: "api_key", key: key.trim() };
|
|
176
|
+
} else {
|
|
177
|
+
delete authData[id];
|
|
178
|
+
}
|
|
179
|
+
await mkdir(dirname(AUTH_FILE_PATH), { recursive: true, mode: 0o700 });
|
|
180
|
+
await writeFile(AUTH_FILE_PATH, `${JSON.stringify(authData, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
181
|
+
await chmod(AUTH_FILE_PATH, 0o600);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export async function loadProjectState(project: ProjectInfo): Promise<ProjectState> {
|
|
185
|
+
return (await readJson<ProjectState>(project.statePath)) ?? { enabled: false };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function saveProjectState(project: ProjectInfo, state: ProjectState): Promise<void> {
|
|
189
|
+
await mkdir(join(project.statePath, ".."), { recursive: true });
|
|
190
|
+
const sanitized = { ...state } as Record<string, unknown>;
|
|
191
|
+
delete sanitized.apiKey;
|
|
192
|
+
await writeFile(project.statePath, `${JSON.stringify(sanitized, null, "\t")}\n`, "utf8");
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export async function resolveConfig(project: ProjectInfo): Promise<{ global: GlobalConfig; project: ProjectState; resolved: ResolvedConfig }> {
|
|
196
|
+
const global = await loadGlobalConfig();
|
|
197
|
+
const projectState = await loadProjectState(project);
|
|
198
|
+
const provider = (global.provider ?? "voyage") as ProviderId;
|
|
199
|
+
const preset = PROVIDER_PRESETS[provider] ?? PROVIDER_PRESETS.voyage;
|
|
200
|
+
const baseUrl = projectState.baseUrl ?? global.baseUrl ?? preset.baseUrl;
|
|
201
|
+
const model = projectState.model ?? global.model ?? preset.model;
|
|
202
|
+
const apiKeyEnv = projectState.apiKeyEnv ?? global.apiKeyEnv ?? preset.apiKeyEnv;
|
|
203
|
+
// Track where the credential came from so a 401 can name its source instead of guessing.
|
|
204
|
+
let apiKey: string | undefined;
|
|
205
|
+
let apiKeySource: ApiKeySource = "none";
|
|
206
|
+
if (provider !== "local") {
|
|
207
|
+
const envKey = apiKeyEnv ? process.env[apiKeyEnv]?.trim() : undefined;
|
|
208
|
+
const storedKey = envKey ? undefined : await loadStoredApiKey(provider);
|
|
209
|
+
apiKey = envKey || storedKey;
|
|
210
|
+
apiKeySource = apiKey ? (envKey ? "env" : "stored") : "none";
|
|
211
|
+
}
|
|
212
|
+
const pricePerMillionTokens = global.pricePerMillionTokens ?? preset.pricePerMillionTokens;
|
|
213
|
+
return {
|
|
214
|
+
global,
|
|
215
|
+
project: projectState,
|
|
216
|
+
resolved: {
|
|
217
|
+
...global,
|
|
218
|
+
excludeDirs: projectState.excludeDirs ?? global.excludeDirs,
|
|
219
|
+
chunkLines: projectState.chunkLines ?? global.chunkLines,
|
|
220
|
+
chunkOverlap: projectState.chunkOverlap ?? global.chunkOverlap,
|
|
221
|
+
maxFileBytes: projectState.maxFileBytes ?? global.maxFileBytes,
|
|
222
|
+
providerPreset: preset,
|
|
223
|
+
baseUrl,
|
|
224
|
+
model,
|
|
225
|
+
apiKeyEnv,
|
|
226
|
+
apiKeyPresent: Boolean(apiKey) || provider === "local",
|
|
227
|
+
apiKey,
|
|
228
|
+
apiKeySource,
|
|
229
|
+
embeddingDim: global.embeddingDim ?? preset.embeddingDim,
|
|
230
|
+
pricePerMillionTokens,
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// One-line description of which credential is in play, for error messages. Never prints the whole key:
|
|
236
|
+
// last 4 chars only, and it says whether the value came from the environment or the stored auth entry.
|
|
237
|
+
export function describeCredentials(config: Pick<ResolvedConfig, "provider" | "apiKeyEnv" | "apiKeySource" | "apiKey">): string {
|
|
238
|
+
if (config.provider === "local") return "no credential needed (local endpoint)";
|
|
239
|
+
const envName = config.apiKeyEnv ?? "(no apiKeyEnv configured)";
|
|
240
|
+
const storedId = `code-index-${config.provider}`;
|
|
241
|
+
const suffix = config.apiKey ? `…${config.apiKey.slice(-4)}` : "none";
|
|
242
|
+
if (config.apiKeySource === "env") return `${envName} from environment (key ${suffix})`;
|
|
243
|
+
if (config.apiKeySource === "stored") return `${storedId} entry in ${AUTH_FILE_PATH} (key ${suffix})`;
|
|
244
|
+
return `no credential: ${envName} is unset and ${AUTH_FILE_PATH} has no ${storedId} entry`;
|
|
245
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { ResolvedConfig } from "./types.ts";
|
|
2
|
+
import { describeCredentials } from "./config.ts";
|
|
3
|
+
|
|
4
|
+
export class EmbeddingError extends Error {
|
|
5
|
+
// Deterministic failures (401, 400, dimension mismatch) can never succeed on retry; only transient
|
|
6
|
+
// ones (429, 5xx, network) are worth another attempt.
|
|
7
|
+
readonly retryable: boolean;
|
|
8
|
+
|
|
9
|
+
constructor(message: string, options?: { retryable?: boolean; cause?: unknown }) {
|
|
10
|
+
super(message, options?.cause === undefined ? undefined : { cause: options.cause });
|
|
11
|
+
this.retryable = options?.retryable ?? false;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Voyage supports asymmetric encoding: index chunks as "document", encode searches as "query".
|
|
16
|
+
// Other OpenAI-compatible providers reject the field, so it is only sent for the voyage provider.
|
|
17
|
+
export type InputType = "document" | "query";
|
|
18
|
+
|
|
19
|
+
export interface EmbeddingResult {
|
|
20
|
+
vectors: number[][];
|
|
21
|
+
dimension: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const t = setTimeout(resolve, ms);
|
|
27
|
+
if (signal) {
|
|
28
|
+
signal.addEventListener(
|
|
29
|
+
"abort",
|
|
30
|
+
() => {
|
|
31
|
+
clearTimeout(t);
|
|
32
|
+
reject(new Error("aborted"));
|
|
33
|
+
},
|
|
34
|
+
{ once: true },
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function mapWithConcurrency<T, R>(items: T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> {
|
|
41
|
+
const results = new Array<R>(items.length);
|
|
42
|
+
let next = 0;
|
|
43
|
+
const workerCount = Math.max(1, Math.min(limit, items.length));
|
|
44
|
+
const workers = Array.from({ length: workerCount }, async () => {
|
|
45
|
+
while (true) {
|
|
46
|
+
const index = next++;
|
|
47
|
+
if (index >= items.length) break;
|
|
48
|
+
results[index] = await fn(items[index], index);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
await Promise.all(workers);
|
|
52
|
+
return results;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function postEmbeddings(config: ResolvedConfig, input: string[], signal: AbortSignal | undefined, inputType: InputType | undefined): Promise<EmbeddingResult> {
|
|
56
|
+
if (!config.apiKeyPresent && config.provider !== "local") {
|
|
57
|
+
throw new EmbeddingError(`Missing API key for ${config.provider}: ${describeCredentials(config)}. Run /index config to store one, or export the variable.`);
|
|
58
|
+
}
|
|
59
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
60
|
+
if (config.apiKey) headers.Authorization = `Bearer ${config.apiKey}`;
|
|
61
|
+
const body: Record<string, unknown> = { model: config.model, input };
|
|
62
|
+
if (inputType && config.provider === "voyage") body.input_type = inputType;
|
|
63
|
+
const controller = new AbortController();
|
|
64
|
+
const timeout = setTimeout(() => controller.abort(), config.timeoutMs);
|
|
65
|
+
if (signal) signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
66
|
+
try {
|
|
67
|
+
const res = await fetch(config.baseUrl, {
|
|
68
|
+
method: "POST",
|
|
69
|
+
headers,
|
|
70
|
+
body: JSON.stringify(body),
|
|
71
|
+
signal: controller.signal,
|
|
72
|
+
});
|
|
73
|
+
const text = await res.text();
|
|
74
|
+
if (!res.ok) {
|
|
75
|
+
const retryable = res.status === 429 || res.status >= 500;
|
|
76
|
+
throw new EmbeddingError(
|
|
77
|
+
`Embedding request failed (${res.status}) for ${config.model} at ${config.baseUrl} using ${describeCredentials(config)}: ${text.slice(0, 500)}`,
|
|
78
|
+
{ retryable },
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
const json = JSON.parse(text) as { data?: Array<{ embedding?: number[] }> };
|
|
82
|
+
const vectors = json.data?.map((d) => d.embedding).filter((v): v is number[] => Array.isArray(v)) ?? [];
|
|
83
|
+
if (vectors.length !== input.length) throw new EmbeddingError(`Embedding response count mismatch: got ${vectors.length}, expected ${input.length}`);
|
|
84
|
+
const dimension = vectors[0]?.length ?? 0;
|
|
85
|
+
if (!dimension) throw new EmbeddingError("Embedding response contained empty vectors");
|
|
86
|
+
if (!vectors.every((v) => v.length === dimension)) throw new EmbeddingError("Embedding response contained mixed dimensions");
|
|
87
|
+
if (config.embeddingDim && dimension !== config.embeddingDim) {
|
|
88
|
+
throw new EmbeddingError(`Embedding dimension mismatch for ${config.model}: got ${dimension}, expected ${config.embeddingDim}`);
|
|
89
|
+
}
|
|
90
|
+
return { vectors, dimension };
|
|
91
|
+
} finally {
|
|
92
|
+
clearTimeout(timeout);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function embedBatch(config: ResolvedConfig, input: string[], signal: AbortSignal | undefined, inputType: InputType | undefined): Promise<EmbeddingResult> {
|
|
97
|
+
let last: unknown;
|
|
98
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
99
|
+
try {
|
|
100
|
+
return await postEmbeddings(config, input, signal, inputType);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
last = error;
|
|
103
|
+
if (signal?.aborted) throw error;
|
|
104
|
+
if (error instanceof EmbeddingError && !error.retryable) throw error;
|
|
105
|
+
if (attempt < 2) await sleep(750 * 2 ** attempt, signal);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
throw last instanceof Error ? last : new EmbeddingError(String(last));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function embedTexts(config: ResolvedConfig, texts: string[], signal?: AbortSignal, inputType?: InputType, onProgress?: (done: number, total: number) => void): Promise<EmbeddingResult> {
|
|
112
|
+
if (texts.length === 0) return { vectors: [], dimension: config.embeddingDim ?? 0 };
|
|
113
|
+
const batches: string[][] = [];
|
|
114
|
+
for (let i = 0; i < texts.length; i += config.batchSize) batches.push(texts.slice(i, i + config.batchSize));
|
|
115
|
+
let done = 0;
|
|
116
|
+
const batchResults = await mapWithConcurrency(batches, config.requestConcurrency, async (batch) => {
|
|
117
|
+
const result = await embedBatch(config, batch, signal, inputType);
|
|
118
|
+
done += batch.length;
|
|
119
|
+
onProgress?.(done, texts.length);
|
|
120
|
+
return result;
|
|
121
|
+
});
|
|
122
|
+
const vectors: number[][] = [];
|
|
123
|
+
let dimension = config.embeddingDim ?? 0;
|
|
124
|
+
for (const result of batchResults) {
|
|
125
|
+
if (dimension && result.dimension !== dimension) throw new EmbeddingError(`Embedding dimension changed: got ${result.dimension}, expected ${dimension}`);
|
|
126
|
+
dimension = result.dimension;
|
|
127
|
+
vectors.push(...result.vectors);
|
|
128
|
+
}
|
|
129
|
+
return { vectors, dimension };
|
|
130
|
+
}
|
package/src/filtering.ts
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import fg from "fast-glob";
|
|
2
|
+
import ignore from "ignore";
|
|
3
|
+
import { readFile, stat } from "node:fs/promises";
|
|
4
|
+
import { basename, extname, join } from "node:path";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { execFile } from "node:child_process";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
import type { ProjectInfo, ResolvedConfig, SourceFile } from "./types.ts";
|
|
9
|
+
|
|
10
|
+
const execFileAsync = promisify(execFile);
|
|
11
|
+
|
|
12
|
+
const SPECIAL_FILENAMES = new Map([
|
|
13
|
+
["Dockerfile", "dockerfile"],
|
|
14
|
+
["Containerfile", "dockerfile"],
|
|
15
|
+
["Makefile", "makefile"],
|
|
16
|
+
["CMakeLists.txt", "cmake"],
|
|
17
|
+
["BUILD", "bazel"],
|
|
18
|
+
["BUILD.bazel", "bazel"],
|
|
19
|
+
["MODULE.bazel", "bazel"],
|
|
20
|
+
["WORKSPACE", "bazel"],
|
|
21
|
+
["WORKSPACE.bazel", "bazel"],
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
const SECRET_BASENAME_PATTERNS = [/^\.env(?:\..*)?$/i, /^id_rsa$/i, /^id_dsa$/i, /^id_ecdsa$/i, /^id_ed25519$/i, /\.pem$/i, /\.key$/i, /\.p12$/i, /\.pfx$/i];
|
|
25
|
+
const SECRET_CONTENT_PATTERNS = [/-----BEGIN [A-Z ]*PRIVATE KEY-----/, /AWS_SECRET_ACCESS_KEY\s*=/, /OPENAI_API_KEY\s*=/, /ANTHROPIC_API_KEY\s*=/, /VOYAGE_API_KEY\s*=/, /OPENROUTER_API_KEY\s*=/];
|
|
26
|
+
|
|
27
|
+
function normalizePattern(pattern: string): string {
|
|
28
|
+
return pattern.replaceAll("\\", "/");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function loadIgnoreFile(path: string): Promise<string[]> {
|
|
32
|
+
try {
|
|
33
|
+
const text = await readFile(path, "utf8");
|
|
34
|
+
return text.split(/\r?\n/).filter((line) => line.trim() && !line.trim().startsWith("#"));
|
|
35
|
+
} catch {
|
|
36
|
+
return [];
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Call git to list all tracked + untracked-but-not-ignored files in the repo.
|
|
41
|
+
// Returns relative posix paths, or undefined if root is not a git repo or git fails/times out.
|
|
42
|
+
async function gitListFiles(root: string): Promise<string[] | undefined> {
|
|
43
|
+
try {
|
|
44
|
+
const { stdout } = await execFileAsync(
|
|
45
|
+
"git",
|
|
46
|
+
["-C", root, "ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
|
47
|
+
{ timeout: 15_000, maxBuffer: 64 * 1024 * 1024 },
|
|
48
|
+
);
|
|
49
|
+
return stdout.split("\0").filter((p) => p.length > 0).map((p) => p.replaceAll("\\", "/"));
|
|
50
|
+
} catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function buildIgnoreMatcher(project: ProjectInfo, config: ResolvedConfig, isGitRepo: boolean) {
|
|
56
|
+
const ig = ignore();
|
|
57
|
+
ig.add(config.excludeDirs.flatMap((dir) => [`${dir}/`, `**/${dir}/`]));
|
|
58
|
+
// When git is acting as the file-list oracle it already handles all four ignore layers
|
|
59
|
+
// (.gitignore, nested .gitignore, core.excludesFile, .git/info/exclude). Reading .gitignore
|
|
60
|
+
// again here would cause double-application and could trip up the `ignore` library.
|
|
61
|
+
if (!isGitRepo) ig.add(await loadIgnoreFile(join(project.root, ".gitignore")));
|
|
62
|
+
ig.add(await loadIgnoreFile(join(project.root, ".indexignore")));
|
|
63
|
+
ig.add(await loadIgnoreFile(join(project.root, ".contextignore")));
|
|
64
|
+
return ig;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function languageForPath(path: string): string | undefined {
|
|
68
|
+
const base = basename(path);
|
|
69
|
+
if (SPECIAL_FILENAMES.has(base)) return SPECIAL_FILENAMES.get(base);
|
|
70
|
+
const ext = extname(path).toLowerCase();
|
|
71
|
+
const map: Record<string, string> = {
|
|
72
|
+
".ts": "typescript",
|
|
73
|
+
".tsx": "tsx",
|
|
74
|
+
".js": "javascript",
|
|
75
|
+
".jsx": "jsx",
|
|
76
|
+
".mjs": "javascript",
|
|
77
|
+
".cjs": "javascript",
|
|
78
|
+
".py": "python",
|
|
79
|
+
".rs": "rust",
|
|
80
|
+
".go": "go",
|
|
81
|
+
".java": "java",
|
|
82
|
+
".kt": "kotlin",
|
|
83
|
+
".kts": "kotlin",
|
|
84
|
+
".scala": "scala",
|
|
85
|
+
".sc": "scala",
|
|
86
|
+
".swift": "swift",
|
|
87
|
+
".c": "c",
|
|
88
|
+
".cpp": "cpp",
|
|
89
|
+
".cc": "cpp",
|
|
90
|
+
".cxx": "cpp",
|
|
91
|
+
".h": "c",
|
|
92
|
+
".hpp": "cpp",
|
|
93
|
+
".m": "objective-c",
|
|
94
|
+
".mm": "objective-cpp",
|
|
95
|
+
".cu": "cuda",
|
|
96
|
+
".cuh": "cuda",
|
|
97
|
+
".cs": "csharp",
|
|
98
|
+
".fs": "fsharp",
|
|
99
|
+
".fsx": "fsharp",
|
|
100
|
+
".rb": "ruby",
|
|
101
|
+
".php": "php",
|
|
102
|
+
".lua": "lua",
|
|
103
|
+
".r": "r",
|
|
104
|
+
".jl": "julia",
|
|
105
|
+
".dart": "dart",
|
|
106
|
+
".ex": "elixir",
|
|
107
|
+
".exs": "elixir",
|
|
108
|
+
".erl": "erlang",
|
|
109
|
+
".hrl": "erlang",
|
|
110
|
+
".hs": "haskell",
|
|
111
|
+
".lhs": "haskell",
|
|
112
|
+
".clj": "clojure",
|
|
113
|
+
".cljs": "clojure",
|
|
114
|
+
".edn": "edn",
|
|
115
|
+
".nim": "nim",
|
|
116
|
+
".zig": "zig",
|
|
117
|
+
".v": "verilog",
|
|
118
|
+
".sv": "systemverilog",
|
|
119
|
+
".svh": "systemverilog",
|
|
120
|
+
".sol": "solidity",
|
|
121
|
+
".sql": "sql",
|
|
122
|
+
".proto": "protobuf",
|
|
123
|
+
".graphql": "graphql",
|
|
124
|
+
".gql": "graphql",
|
|
125
|
+
".prisma": "prisma",
|
|
126
|
+
".tf": "terraform",
|
|
127
|
+
".tfvars": "terraform",
|
|
128
|
+
".hcl": "hcl",
|
|
129
|
+
".nix": "nix",
|
|
130
|
+
".vue": "vue",
|
|
131
|
+
".svelte": "svelte",
|
|
132
|
+
".html": "html",
|
|
133
|
+
".css": "css",
|
|
134
|
+
".scss": "scss",
|
|
135
|
+
".xml": "xml",
|
|
136
|
+
".md": "markdown",
|
|
137
|
+
".mdx": "markdown",
|
|
138
|
+
".adoc": "asciidoc",
|
|
139
|
+
".txt": "text",
|
|
140
|
+
".rst": "rst",
|
|
141
|
+
".tex": "latex",
|
|
142
|
+
".bib": "bibtex",
|
|
143
|
+
".yaml": "yaml",
|
|
144
|
+
".yml": "yaml",
|
|
145
|
+
".toml": "toml",
|
|
146
|
+
".json": "json",
|
|
147
|
+
".ini": "ini",
|
|
148
|
+
".cfg": "config",
|
|
149
|
+
".conf": "config",
|
|
150
|
+
".properties": "properties",
|
|
151
|
+
".sh": "shell",
|
|
152
|
+
".bash": "shell",
|
|
153
|
+
".zsh": "shell",
|
|
154
|
+
".ps1": "powershell",
|
|
155
|
+
".cmake": "cmake",
|
|
156
|
+
".gradle": "gradle",
|
|
157
|
+
".bazel": "bazel",
|
|
158
|
+
".bzl": "bazel",
|
|
159
|
+
".dockerfile": "dockerfile",
|
|
160
|
+
".containerfile": "dockerfile",
|
|
161
|
+
};
|
|
162
|
+
return map[ext];
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function isSecretPath(path: string): boolean {
|
|
166
|
+
const base = basename(path);
|
|
167
|
+
return SECRET_BASENAME_PATTERNS.some((r) => r.test(base));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function looksBinary(buf: Buffer): boolean {
|
|
171
|
+
const n = Math.min(buf.length, 4096);
|
|
172
|
+
for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function hasSecretContent(text: string): boolean {
|
|
177
|
+
return SECRET_CONTENT_PATTERNS.some((r) => r.test(text));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function listIndexableFiles(project: ProjectInfo, config: ResolvedConfig): Promise<string[]> {
|
|
181
|
+
const gitFiles = await gitListFiles(project.root);
|
|
182
|
+
const isGitRepo = gitFiles !== undefined;
|
|
183
|
+
const ig = await buildIgnoreMatcher(project, config, isGitRepo);
|
|
184
|
+
let entries: string[];
|
|
185
|
+
if (isGitRepo) {
|
|
186
|
+
entries = gitFiles;
|
|
187
|
+
} else {
|
|
188
|
+
const raw = await fg("**/*", {
|
|
189
|
+
cwd: project.root,
|
|
190
|
+
dot: true,
|
|
191
|
+
onlyFiles: true,
|
|
192
|
+
followSymbolicLinks: false,
|
|
193
|
+
ignore: config.excludeDirs.flatMap((dir) => [`**/${dir}/**`, `${dir}/**`]),
|
|
194
|
+
});
|
|
195
|
+
entries = raw.map(normalizePattern);
|
|
196
|
+
}
|
|
197
|
+
// Git visibility and content checks determine eligibility. Extension mappings are used only for
|
|
198
|
+
// syntax-aware chunking; unknown readable files are indexed as plain text.
|
|
199
|
+
return entries.filter((p) => !ig.ignores(p)).filter((p) => !isSecretPath(p));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export async function readSourceFile(project: ProjectInfo, relPath: string, config: ResolvedConfig): Promise<SourceFile | undefined> {
|
|
203
|
+
const absPath = join(project.root, relPath);
|
|
204
|
+
const st = await stat(absPath).catch(() => undefined);
|
|
205
|
+
if (!st || !st.isFile()) return undefined;
|
|
206
|
+
if (st.size > config.maxFileBytes) return undefined;
|
|
207
|
+
if (isSecretPath(relPath)) return undefined;
|
|
208
|
+
const buf = await readFile(absPath);
|
|
209
|
+
if (looksBinary(buf)) return undefined;
|
|
210
|
+
const content = buf.toString("utf8");
|
|
211
|
+
if (content.includes("�")) return undefined;
|
|
212
|
+
if (hasSecretContent(content)) return undefined;
|
|
213
|
+
const language = languageForPath(relPath) ?? "text";
|
|
214
|
+
const fileHash = createHash("sha256").update(buf).digest("hex");
|
|
215
|
+
return { path: relPath, absPath, language, content, size: st.size, mtimeMs: st.mtimeMs, fileHash };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export async function isPathIndexable(project: ProjectInfo, config: ResolvedConfig, relPath: string): Promise<boolean> {
|
|
219
|
+
const files = await listIndexableFiles(project, config);
|
|
220
|
+
return files.includes(normalizePattern(relPath));
|
|
221
|
+
}
|