@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chiyu Hao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ > This is a chalice package, check out github.com/leolastforce/Chalice
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > This is a fork of Chiyu Hao/pi-code-index, see the original. This was forked for the chalice ecosystem to have control over source, version, etc..
4
+
5
+ # Semantic file indexing
6
+
7
+ ## What does semantic file indexing refer to in Chalice?
8
+ Semantic indexing helps the agent find code by describing what it does, in scenarios where the agent might not know the exact filename or identifier. For example, the agent might search "the code that retries failed embedding requests" instead of guessing the function name.
9
+
10
+ It's an alternative option to the ordinary search tools, it's tool call is semantic_code_search.
11
+
12
+ ## How the index is built
13
+ When indexing is turned on, Chalice finds eligible projects files (see ## Which files are ignored for details), divides their content into "chunks", and sends each "chunk" to your configured embedding provider.
14
+
15
+ When the search happens, Chalice embeds that query with same provider and looks for chunks with similar vectors. The file path, line range, and short code snippet is then returned as the result from the tool.
16
+
17
+ > Supported providers for semantic file as of right now (feel free to request more in a github issue!):
18
+ - Voyage AI (Reccomended, considered to have the greatest indexing models overall.)
19
+ - Openrouter (Generally perfectly fine and easy to set up)
20
+ - Local OpenAI-compatible embeddings (See ## OpenAI-compatible embeddings provider information subcategory)
21
+
22
+ ## Which files are indexed and how to explicitly ignore files?
23
+ Each file that is included in the list below will not be indexed:
24
+
25
+ - Git's ignore rules when the project is a Git repo
26
+ - Entries in ```.indexignore```
27
+ - Entries in ```.contextignore```
28
+ - Configured excluded directories, such as ```node_modules``` and ```dist```
29
+
30
+ Additionally, it is checked if a file is binary, oversized (768 KiB+), and files matching known secret filename or content patterns for privacy. Change this with /index config.
31
+
32
+ ## How does index updating work?
33
+ Alright so, you've indexed your project, and now you've added new changes, now what?
34
+
35
+ When indexing is enabled, a file watcher will update the index as files change. Small changes can be embedded automatically, but if many changes arrive together (common), the automatic embedding pauses and you will be notified to run /index update.
36
+
37
+ ## Tags
38
+ Tags let you filter semantic search results by project area without rebuilding the index.
39
+
40
+ ```.index_tag``` files let you label directories so that you can filter search results. The tags are manually inputed and inherited from parent directories. Okay an example: a test tag in ```test/.index_tag``` applies to files under ```tests/```
41
+
42
+ Use ```exclude_tags``` to in turn remove tagged areas while still leaving untagged files eligible, use ```include_tags``` to restrict results to files with at least one listed tag.
43
+
44
+ Tag changes take effect at the tool call time so you do not need to reindex. Run /index tags to see tags.
45
+ ## Costs and provider
46
+ You will get an estimated token cost with the configured provider so you don't get caught offguard, for most repos, expect this to be dirt cheap, typically landing between 0.01 to 0.05$. If the provider remote's pricing is unknown, you'll just get an estimate in tokens instead.
47
+
48
+ The first time you enable indexing with a remote provider, Chalice will ask you to confirm that the code chunks can be sent to that provider, and local embeddings do not require an API key or send requests to a remote provider, so you will not be prompted. This is just a light privacy check <3
49
+
50
+ ## OpenAI-compatible embeddings provider information
51
+ I wanted to clarify on how the OpenAI-compatible provider worked as an option since it doesn't work out of the box.
52
+ The local option connects to an embedding server running on your machine. It uses an OpenAI-compatible embeddings API, so the server needs to accept `POST /v1/embeddings` requests and return embedding vectors in the OpenAI response format. So, Chalice uses the server, and doesn't download or do anything from you.
53
+
54
+ The default endpoint is `http://127.0.0.1:11434/v1/embeddings` with the model `nomic-embed-text`, which works with a compatible local setup such as Ollama. Make sure the server is running and the model is available before indexing. You can change the endpoint and model in `/index config`.
55
+
56
+ The local provider needs no API key and makes embedding requests to the configured local endpoint instead of a remote provider. The index and vectors are stored locally too. The separate `custom` provider can also connect to an OpenAI-compatible endpoint; configure its base URL, model, and API key environment variable in `/index config`.
57
+
58
+ ## Other
59
+ - The semantic index is stored in ~/.pi/agent/code-index/indexes/<project-hash>/ by default
package/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from "./src/index.ts";
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
- "name": "@leolastforce/chalice-code-index",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@leolastforce/chalice-code-index",
3
+ "version": "0.1.0",
4
+ "description": "[ORIGINAL EXTENSION: Chiyu Hao/pi-code-index] Chalice module for semantic index",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "chalice",
9
+ "pi-package"
10
+ ],
11
+ "dependencies": {
12
+ "@lancedb/lancedb": "0.30.0",
13
+ "chokidar": "5.0.0",
14
+ "fast-glob": "3.3.3",
15
+ "ignore": "7.0.8",
16
+ "web-tree-sitter": "0.20.8",
17
+ "tree-sitter-wasms": "0.1.13",
18
+ "@leolastforce/chalice-shared": "0.1.0"
19
+ },
20
+ "pi": {
21
+ "extensions": [
22
+ "./index.ts"
23
+ ]
24
+ },
25
+ "files": [
26
+ "index.ts",
27
+ "src",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "peerDependencies": {
32
+ "@earendil-works/pi-coding-agent": "*",
33
+ "typebox": "*"
34
+ },
35
+ "peerDependenciesMeta": {
36
+ "@earendil-works/pi-coding-agent": {
37
+ "optional": true
38
+ },
39
+ "typebox": {
40
+ "optional": true
41
+ }
42
+ },
43
+ "engines": {
44
+ "node": ">=22.19.0"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ }
49
+ }
@@ -0,0 +1,305 @@
1
+ import Parser from "web-tree-sitter";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import type { CodeChunk, ResolvedConfig, SourceFile } from "./types.ts";
6
+
7
+ // This extension is vendored under Chalice rather than installed as its own package. Resolve the
8
+ // grammar assets through Node's module resolver so they work from both the source tree and a
9
+ // packaged installation, regardless of the extension's location.
10
+ const wasmDir = join(dirname(createRequire(import.meta.url).resolve("tree-sitter-wasms/package.json")), "out");
11
+
12
+ let parserReady: Promise<void> | undefined;
13
+ const languages = new Map<string, any>();
14
+
15
+ const GRAMMAR_BY_LANGUAGE: Record<string, string> = {
16
+ typescript: "tree-sitter-typescript.wasm",
17
+ tsx: "tree-sitter-tsx.wasm",
18
+ javascript: "tree-sitter-javascript.wasm",
19
+ jsx: "tree-sitter-javascript.wasm",
20
+ python: "tree-sitter-python.wasm",
21
+ rust: "tree-sitter-rust.wasm",
22
+ go: "tree-sitter-go.wasm",
23
+ java: "tree-sitter-java.wasm",
24
+ };
25
+
26
+ // Leaf declarations become a chunk on their own; we prune (do not descend) once matched so
27
+ // nested members are never double-covered by an enclosing node.
28
+ const LEAF_NODE_TYPES = new Set([
29
+ "function_declaration",
30
+ "function_definition",
31
+ "method_definition",
32
+ "method_declaration",
33
+ "function_item",
34
+ "lexical_declaration",
35
+ "variable_declaration",
36
+ ]);
37
+
38
+ // Containers are descended into so their members chunk at method granularity; an empty container
39
+ // (e.g. an interface or a struct with no methods) is emitted whole as a fallback.
40
+ const CONTAINER_NODE_TYPES = new Set([
41
+ "class_declaration",
42
+ "class_definition",
43
+ "impl_item",
44
+ "trait_item",
45
+ "interface_declaration",
46
+ "struct_item",
47
+ "enum_item",
48
+ ]);
49
+
50
+ function sha(text: string): string {
51
+ return createHash("sha256").update(text).digest("hex");
52
+ }
53
+
54
+ function sliceLines(lines: string[], startLine: number, endLine: number): string {
55
+ return lines.slice(startLine - 1, endLine).join("\n");
56
+ }
57
+
58
+ // Keep requests below common embedding-provider limits. Code can tokenize much more densely than
59
+ // prose, so this conservative character cap prevents an individual chunk from exceeding an 8K-token
60
+ // provider limit (including the metadata prefix). Oversized lines are split as well.
61
+ const MAX_EMBEDDED_CONTENT_CHARS = 6000;
62
+
63
+ function makeSafeChunks(source: SourceFile, projectRoot: string, startLine: number, endLine: number, content: string, symbol: string | undefined, prefixContext?: string): CodeChunk[] {
64
+ const limit = Math.max(1000, MAX_EMBEDDED_CONTENT_CHARS - (prefixContext?.length ?? 0));
65
+ if (content.length <= limit) return [makeChunk(source, projectRoot, startLine, endLine, content, symbol, prefixContext)];
66
+
67
+ const chunks: CodeChunk[] = [];
68
+ let offset = 0;
69
+ let chunkStartLine = startLine;
70
+ while (offset < content.length) {
71
+ let end = Math.min(content.length, offset + limit);
72
+ if (end < content.length) {
73
+ const newline = content.lastIndexOf("\n", end);
74
+ if (newline > offset) end = newline;
75
+ }
76
+ const piece = content.slice(offset, end);
77
+ if (piece.trim()) {
78
+ const linesInPiece = piece.match(/\n/g)?.length ?? 0;
79
+ const chunkEndLine = Math.min(endLine, chunkStartLine + linesInPiece);
80
+ chunks.push(makeChunk(source, projectRoot, chunkStartLine, chunkEndLine, piece, symbol, prefixContext));
81
+ chunkStartLine = chunkEndLine + (end < content.length && content[end] === "\n" ? 1 : 0);
82
+ }
83
+ offset = end < content.length && content[end] === "\n" ? end + 1 : end;
84
+ }
85
+ return chunks;
86
+ }
87
+ function makeChunk(source: SourceFile, projectRoot: string, startLine: number, endLine: number, content: string, symbol: string | undefined, prefixContext?: string): CodeChunk {
88
+ // embeddedText omits line numbers so the contentHash is stable under line drift, letting the
89
+ // incremental indexer reuse an unchanged chunk's existing vector instead of re-embedding it.
90
+ // prefixContext (an optional overlap tail of the preceding chunk) is folded into the EMBEDDED text
91
+ // for cross-boundary recall but is NOT stored as content, so the agent-facing snippet and line
92
+ // range stay exact. It does enter contentHash, so overlap reduces incremental-reuse hit rate.
93
+ const embedBody = prefixContext ? `${prefixContext}\n${content}` : content;
94
+ const embeddedText = `File: ${source.path}\nLanguage: ${source.language}\n${symbol ? `Symbol: ${symbol}\n` : ""}Code:\n${embedBody}`;
95
+ const contentHash = sha(embeddedText);
96
+ const id = sha(`${projectRoot}:${source.path}:${startLine}:${contentHash}`).slice(0, 32);
97
+ return {
98
+ id,
99
+ projectRoot,
100
+ path: source.path,
101
+ language: source.language,
102
+ symbol,
103
+ startLine,
104
+ endLine,
105
+ content,
106
+ embeddedText,
107
+ contentHash,
108
+ fileHash: source.fileHash,
109
+ mtimeMs: source.mtimeMs,
110
+ size: source.size,
111
+ };
112
+ }
113
+
114
+ function windowRange(source: SourceFile, projectRoot: string, config: ResolvedConfig, fromLine: number, toLine: number, lines: string[], symbol: string | undefined): CodeChunk[] {
115
+ const chunks: CodeChunk[] = [];
116
+ const size = Math.max(1, config.chunkLines);
117
+ const overlap = Math.max(0, Math.min(config.chunkOverlap, size - 1));
118
+ let start = fromLine;
119
+ while (start <= toLine) {
120
+ const end = Math.min(toLine, start + size - 1);
121
+ const content = sliceLines(lines, start, end);
122
+ if (content.trim()) chunks.push(...makeSafeChunks(source, projectRoot, start, end, content, symbol));
123
+ if (end === toLine) break;
124
+ start = end - overlap + 1;
125
+ }
126
+ return chunks;
127
+ }
128
+
129
+ async function ensureParserReady(): Promise<void> {
130
+ if (!parserReady) parserReady = Parser.init();
131
+ await parserReady;
132
+ }
133
+
134
+ async function loadLanguage(language: string): Promise<any | undefined> {
135
+ const grammar = GRAMMAR_BY_LANGUAGE[language];
136
+ if (!grammar) return undefined;
137
+ if (languages.has(language)) return languages.get(language);
138
+ await ensureParserReady();
139
+ try {
140
+ const lang = await Parser.Language.load(join(wasmDir, grammar));
141
+ languages.set(language, lang);
142
+ return lang;
143
+ } catch {
144
+ return undefined;
145
+ }
146
+ }
147
+
148
+ function getNodeName(node: any): string | undefined {
149
+ try {
150
+ const named = node.childForFieldName?.("name");
151
+ if (named?.text) return named.text;
152
+ } catch {}
153
+ for (const child of node.namedChildren ?? []) {
154
+ if (child.type === "identifier" || child.type === "property_identifier" || child.type === "type_identifier") return child.text;
155
+ }
156
+ return undefined;
157
+ }
158
+
159
+ function nearestClassName(node: any): string | undefined {
160
+ let cur = node.parent;
161
+ while (cur) {
162
+ if (cur.type === "class_declaration" || cur.type === "class_definition") return getNodeName(cur);
163
+ cur = cur.parent;
164
+ }
165
+ return undefined;
166
+ }
167
+
168
+ function symbolFor(node: any): string | undefined {
169
+ const name = getNodeName(node);
170
+ if (!name) return undefined;
171
+ const cls = nearestClassName(node);
172
+ if (cls && !["class_declaration", "class_definition"].includes(node.type)) return `${cls} > ${name}`;
173
+ return name;
174
+ }
175
+
176
+ // Single top-down pass: emit leaf declarations (pruning their subtree) and descend into containers
177
+ // so members chunk individually. No node is collected twice, so chunks never overlap.
178
+ function collectChunkNodes(root: any): any[] {
179
+ const out: any[] = [];
180
+ function visit(node: any): boolean {
181
+ if (LEAF_NODE_TYPES.has(node.type)) {
182
+ out.push(node);
183
+ return true;
184
+ }
185
+ if (CONTAINER_NODE_TYPES.has(node.type)) {
186
+ let covered = false;
187
+ for (const child of node.namedChildren ?? []) covered = visit(child) || covered;
188
+ if (!covered) out.push(node);
189
+ return true;
190
+ }
191
+ let covered = false;
192
+ for (const child of node.namedChildren ?? []) covered = visit(child) || covered;
193
+ return covered;
194
+ }
195
+ visit(root);
196
+ return out
197
+ .filter((n) => n.endPosition.row > n.startPosition.row || String(n.text ?? "").length > 80)
198
+ .sort((a, b) => a.startIndex - b.startIndex);
199
+ }
200
+
201
+ // Cover the lines that no AST chunk claimed (imports, top-level statements, code between members)
202
+ // with line-window chunks so they are still searchable.
203
+ function gapChunks(source: SourceFile, projectRoot: string, config: ResolvedConfig, lines: string[], covered: Set<number>): CodeChunk[] {
204
+ const chunks: CodeChunk[] = [];
205
+ const pushGap = (from: number, to: number): void => {
206
+ const seg = sliceLines(lines, from, to);
207
+ if (seg.trim() && /[A-Za-z0-9_]/.test(seg)) chunks.push(...windowRange(source, projectRoot, config, from, to, lines, undefined));
208
+ };
209
+ let start = -1;
210
+ for (let ln = 1; ln <= lines.length; ln++) {
211
+ const isCovered = covered.has(ln);
212
+ if (!isCovered && start === -1) start = ln;
213
+ if (isCovered && start !== -1) {
214
+ pushGap(start, ln - 1);
215
+ start = -1;
216
+ }
217
+ }
218
+ if (start !== -1) pushGap(start, lines.length);
219
+ return chunks;
220
+ }
221
+
222
+ // Sub-split a large AST node along its body's STATEMENT boundaries (not raw line windows), so each
223
+ // sub-chunk is a coherent slice with focused semantics instead of one diluted whole-function vector.
224
+ // The first sub-chunk keeps the signature line(s); all sub-chunks carry the parent symbol.
225
+ function subSplitNode(node: any, source: SourceFile, projectRoot: string, config: ResolvedConfig, lines: string[], symbol: string | undefined): CodeChunk[] {
226
+ const nodeStart = node.startPosition.row + 1;
227
+ const nodeEnd = node.endPosition.row + 1;
228
+ const body = node.childForFieldName?.("body") ?? node;
229
+ const stmts = (body.namedChildren ?? []).filter((c: any) => c.endPosition.row > c.startPosition.row || String(c.text ?? "").length > 40);
230
+ if (stmts.length <= 1) return windowRange(source, projectRoot, config, nodeStart, nodeEnd, lines, symbol);
231
+ const chunks: CodeChunk[] = [];
232
+ let groupStart = nodeStart; // first sub-chunk includes the signature line(s)
233
+ let curEnd = nodeStart - 1;
234
+ let groupChars = 0;
235
+ const flush = (nextStart: number): void => {
236
+ const content = sliceLines(lines, groupStart, curEnd);
237
+ if (content.trim()) chunks.push(...makeSafeChunks(source, projectRoot, groupStart, curEnd, content, symbol));
238
+ groupStart = nextStart;
239
+ groupChars = 0;
240
+ };
241
+ for (const st of stmts) {
242
+ const stChars = String(st.text ?? "").length;
243
+ if (groupChars > 0 && groupChars + stChars > config.maxChunkChars) flush(st.startPosition.row + 1);
244
+ curEnd = st.endPosition.row + 1;
245
+ groupChars += stChars;
246
+ }
247
+ const tail = sliceLines(lines, groupStart, curEnd);
248
+ if (tail.trim()) chunks.push(...makeSafeChunks(source, projectRoot, groupStart, curEnd, tail, symbol));
249
+ return chunks.length ? chunks : windowRange(source, projectRoot, config, nodeStart, nodeEnd, lines, symbol);
250
+ }
251
+
252
+ // Fold a tail slice of each chunk's predecessor into its embedded text (claude-context's addOverlap
253
+ // idea) to give the embedding cross-boundary context. Unlike claude-context we keep the returned
254
+ // content + line range exact — the overlap rides only in embeddedText. Overlap never crosses files
255
+ // (chunks are per-file here). Off (chunkOverlapChars=0) by default; flip it and reindex to A/B test.
256
+ function applyOverlap(chunks: CodeChunk[], source: SourceFile, projectRoot: string, config: ResolvedConfig): CodeChunk[] {
257
+ const n = Math.max(0, config.chunkOverlapChars ?? 0);
258
+ if (n <= 0 || chunks.length <= 1) return chunks;
259
+ const out: CodeChunk[] = [chunks[0]];
260
+ for (let i = 1; i < chunks.length; i++) {
261
+ const prevTail = chunks[i - 1].content.slice(-n).trim();
262
+ const cur = chunks[i];
263
+ if (prevTail) out.push(...makeSafeChunks(source, projectRoot, cur.startLine, cur.endLine, cur.content, cur.symbol, prevTail));
264
+ }
265
+ return out;
266
+ }
267
+
268
+ export async function chunkSourceFile(source: SourceFile, projectRoot: string, config: ResolvedConfig): Promise<CodeChunk[]> {
269
+ const lines = source.content.split(/\r?\n/);
270
+ const lang = await loadLanguage(source.language);
271
+ if (!lang) return windowRange(source, projectRoot, config, 1, lines.length, lines, undefined);
272
+ try {
273
+ const parser = new Parser();
274
+ parser.setLanguage(lang);
275
+ const tree = parser.parse(source.content);
276
+ const nodes = collectChunkNodes(tree.rootNode);
277
+ if (nodes.length === 0) return windowRange(source, projectRoot, config, 1, lines.length, lines, undefined);
278
+ const chunks: CodeChunk[] = [];
279
+ const covered = new Set<number>();
280
+ for (const node of nodes) {
281
+ const startLine = node.startPosition.row + 1;
282
+ const endLine = node.endPosition.row + 1;
283
+ for (let ln = startLine; ln <= endLine; ln++) covered.add(ln);
284
+ const content = sliceLines(lines, startLine, endLine);
285
+ if (!content.trim()) continue;
286
+ const symbol = symbolFor(node);
287
+ if (content.length > config.maxChunkChars) chunks.push(...subSplitNode(node, source, projectRoot, config, lines, symbol));
288
+ else chunks.push(...makeSafeChunks(source, projectRoot, startLine, endLine, content, symbol));
289
+ }
290
+ chunks.push(...gapChunks(source, projectRoot, config, lines, covered));
291
+ if (chunks.length === 0) return windowRange(source, projectRoot, config, 1, lines.length, lines, undefined);
292
+ return applyOverlap(chunks.sort((a, b) => a.startLine - b.startLine), source, projectRoot, config);
293
+ } catch {
294
+ return windowRange(source, projectRoot, config, 1, lines.length, lines, undefined);
295
+ }
296
+ }
297
+
298
+ export function estimateTokens(text: string): number {
299
+ return Math.ceil(text.length / 4);
300
+ }
301
+
302
+ export async function estimateChunksForFile(source: SourceFile, projectRoot: string, config: ResolvedConfig): Promise<{ chunks: CodeChunk[]; tokens: number }> {
303
+ const chunks = await chunkSourceFile(source, projectRoot, config);
304
+ return { chunks, tokens: chunks.reduce((sum, c) => sum + estimateTokens(c.embeddedText), 0) };
305
+ }