@howaboua/opencode-chat 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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +116 -0
  3. package/dist/config.d.ts +13 -0
  4. package/dist/config.d.ts.map +1 -0
  5. package/dist/config.js +65 -0
  6. package/dist/index.d.ts +8 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +44 -0
  9. package/dist/script/download-model.d.ts +2 -0
  10. package/dist/script/download-model.d.ts.map +1 -0
  11. package/dist/script/download-model.js +39 -0
  12. package/dist/script/semantic-index.d.ts +2 -0
  13. package/dist/script/semantic-index.d.ts.map +1 -0
  14. package/dist/script/semantic-index.js +63 -0
  15. package/dist/semantic/chunker.d.ts +8 -0
  16. package/dist/semantic/chunker.d.ts.map +1 -0
  17. package/dist/semantic/chunker.js +163 -0
  18. package/dist/semantic/embedder.d.ts +12 -0
  19. package/dist/semantic/embedder.d.ts.map +1 -0
  20. package/dist/semantic/embedder.js +54 -0
  21. package/dist/semantic/index.d.ts +41 -0
  22. package/dist/semantic/index.d.ts.map +1 -0
  23. package/dist/semantic/index.js +178 -0
  24. package/dist/system.d.ts +5 -0
  25. package/dist/system.d.ts.map +1 -0
  26. package/dist/system.js +93 -0
  27. package/dist/tools/bash.d.ts +22 -0
  28. package/dist/tools/bash.d.ts.map +1 -0
  29. package/dist/tools/bash.js +59 -0
  30. package/dist/tools/batch.d.ts +25 -0
  31. package/dist/tools/batch.d.ts.map +1 -0
  32. package/dist/tools/batch.js +49 -0
  33. package/dist/tools/edit.d.ts +25 -0
  34. package/dist/tools/edit.d.ts.map +1 -0
  35. package/dist/tools/edit.js +44 -0
  36. package/dist/tools/glob.d.ts +19 -0
  37. package/dist/tools/glob.d.ts.map +1 -0
  38. package/dist/tools/glob.js +54 -0
  39. package/dist/tools/grep.d.ts +22 -0
  40. package/dist/tools/grep.d.ts.map +1 -0
  41. package/dist/tools/grep.js +92 -0
  42. package/dist/tools/index.d.ts +12 -0
  43. package/dist/tools/index.d.ts.map +1 -0
  44. package/dist/tools/index.js +51 -0
  45. package/dist/tools/patch.d.ts +16 -0
  46. package/dist/tools/patch.d.ts.map +1 -0
  47. package/dist/tools/patch.js +87 -0
  48. package/dist/tools/read.d.ts +22 -0
  49. package/dist/tools/read.d.ts.map +1 -0
  50. package/dist/tools/read.js +70 -0
  51. package/dist/tools/remember.d.ts +16 -0
  52. package/dist/tools/remember.d.ts.map +1 -0
  53. package/dist/tools/remember.js +58 -0
  54. package/dist/tools/semantic-search.d.ts +19 -0
  55. package/dist/tools/semantic-search.d.ts.map +1 -0
  56. package/dist/tools/semantic-search.js +54 -0
  57. package/dist/tools/skill.d.ts +17 -0
  58. package/dist/tools/skill.d.ts.map +1 -0
  59. package/dist/tools/skill.js +106 -0
  60. package/dist/tools/todo.d.ts +62 -0
  61. package/dist/tools/todo.d.ts.map +1 -0
  62. package/dist/tools/todo.js +62 -0
  63. package/dist/tools/write.d.ts +19 -0
  64. package/dist/tools/write.d.ts.map +1 -0
  65. package/dist/tools/write.js +37 -0
  66. package/dist/util/constants.d.ts +16 -0
  67. package/dist/util/constants.d.ts.map +1 -0
  68. package/dist/util/constants.js +39 -0
  69. package/dist/util/patch.d.ts +32 -0
  70. package/dist/util/patch.d.ts.map +1 -0
  71. package/dist/util/patch.js +240 -0
  72. package/dist/util/paths.d.ts +6 -0
  73. package/dist/util/paths.d.ts.map +1 -0
  74. package/dist/util/paths.js +76 -0
  75. package/dist/util/text.d.ts +4 -0
  76. package/dist/util/text.d.ts.map +1 -0
  77. package/dist/util/text.js +37 -0
  78. package/dist/util/todo.d.ts +5 -0
  79. package/dist/util/todo.d.ts.map +1 -0
  80. package/dist/util/todo.js +48 -0
  81. package/dist/util/types.d.ts +22 -0
  82. package/dist/util/types.d.ts.map +1 -0
  83. package/dist/util/types.js +1 -0
  84. package/package.json +53 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Igor Wiedler
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 ADDED
@@ -0,0 +1,116 @@
1
+ # OpenCode Chatifier
2
+
3
+ A conversational coding assistant plugin for OpenCode with semantic code search.
4
+
5
+ ## What It Does
6
+
7
+ **Chatifier** transforms OpenCode into a more conversational experience with two specialized agents and local semantic search.
8
+
9
+ ![opencode-chat](https://github.com/user-attachments/assets/d489422c-a5a6-4003-b955-adf9b17260c2)
10
+
11
+ ### Chat Agents
12
+
13
+ | Agent | Purpose |
14
+ | ------------- | ---------------------------------------------------- |
15
+ | **Just Chat** | Quick questions, web research, remembering context |
16
+ | **Tool Chat** | Full coding toolkit with semantic search and editing |
17
+
18
+ ### Features
19
+
20
+ - **Semantic Search** - Ask "where is auth handled?" and find code by meaning, not keywords
21
+ - **Memory** - Tell it to remember preferences and they persist across sessions
22
+ - **Task Tracking** - Built-in todo list for multi-step work
23
+ - **Skills** - Load project-specific guidance from `.opencode/skill/`
24
+ - **Streamlined Prompts** - Concise, direct responses without filler
25
+
26
+ ## Installation
27
+
28
+ Add to your `opencode.json`:
29
+
30
+ ```json
31
+ {
32
+ "plugin": ["@howaboua/opencode-chat"]
33
+ }
34
+ ```
35
+
36
+ OpenCode automatically installs the plugin on next launch.
37
+
38
+ ### Pin a version (optional)
39
+
40
+ ```json
41
+ {
42
+ "plugin": ["@howaboua/opencode-chat@0.1.0"]
43
+ }
44
+ ```
45
+
46
+ ## Setup
47
+
48
+ ### New or Small Projects
49
+
50
+ For new projects or directories with fewer than 100 files, just launch OpenCode. The plugin automatically:
51
+
52
+ 1. Downloads the embedding model (~90MB, cached in `.opencode/chat/models/`)
53
+ 2. Indexes your codebase for semantic search
54
+
55
+ ### Existing Large Projects (IMPORTANT)
56
+
57
+ **For directories with 100+ files (Obsidian vaults, large codebases, etc.), you MUST run setup manually before launching OpenCode.** Otherwise, the plugin will skip indexing to avoid blocking startup.
58
+
59
+ ```bash
60
+ cd your-project
61
+
62
+ # Download the embedding model first
63
+ npx opencode-chat-download-model
64
+
65
+ # Index your files (may take several minutes for large directories)
66
+ npx opencode-chat-semantic-index --mode full
67
+ ```
68
+
69
+ After this one-time setup, OpenCode will launch normally and only re-index changed files.
70
+
71
+ ## Usage
72
+
73
+ ### Switch Agents
74
+
75
+ Use the agent selector in OpenCode to switch between:
76
+
77
+ - **Just Chat** - Conversational, minimal tools, web access
78
+ - **Tool Chat** - Full toolkit including semantic search
79
+
80
+ ### Semantic Search
81
+
82
+ Ask natural language questions:
83
+
84
+ - "Where is the database connection configured?"
85
+ - "Find error handling for API requests"
86
+ - "Show me the authentication flow"
87
+
88
+ The assistant searches by meaning using local embeddings - no API calls, fully private.
89
+
90
+ ### Memory
91
+
92
+ Tell the assistant to remember things:
93
+
94
+ - "Remember that I prefer TypeScript over JavaScript"
95
+ - "Remember this project uses React 19"
96
+
97
+ Memories persist in `AGENTS.md` and apply to future sessions.
98
+
99
+ ### Task Tracking
100
+
101
+ For multi-step tasks, the assistant creates and tracks a todo list automatically. The list persists in `todo.md` and is removed when all tasks complete.
102
+
103
+ ## Requirements
104
+
105
+ - [OpenCode](https://opencode.ai) v1.0.201+
106
+ - [Bun](https://bun.sh) runtime (for semantic indexing)
107
+
108
+ ## How It Works
109
+
110
+ - **Embeddings**: Uses [fastembed](https://github.com/Anush008/fastembed-js) with the AllMiniLML6V2 model
111
+ - **Storage**: SQLite database in `.opencode/chat/semantic.sqlite`
112
+ - **Indexing**: Incremental - only re-indexes changed files
113
+
114
+ ## License
115
+
116
+ MIT
@@ -0,0 +1,13 @@
1
+ type AgentConfig = {
2
+ tools?: Record<string, boolean>;
3
+ prompt?: string;
4
+ [key: string]: unknown;
5
+ };
6
+ type ConfigWithTools = {
7
+ tools?: Record<string, boolean>;
8
+ agent?: Record<string, AgentConfig>;
9
+ default_agent?: string;
10
+ };
11
+ export declare function configureChatAgents(config: ConfigWithTools, toolIds: string[]): void;
12
+ export {};
13
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../config.ts"],"names":[],"mappings":"AAUA,KAAK,WAAW,GAAG;IAAE,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAA;AAC/F,KAAK,eAAe,GAAG;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IACnC,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB,CAAA;AAgCD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,QA+B7E"}
package/dist/config.js ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Configuration helpers for the chatifier plugin.
3
+ * Disables chat_* tools globally via config.tools, then enables them for chatified agents.
4
+ *
5
+ * Agents:
6
+ * - Just Chat: Minimal tools for conversation and web research
7
+ * - Tool Chat: Full toolkit for files, code, and web
8
+ */
9
+ import { CHATIFIER_PROMPT } from "./system";
10
+ const NATIVE_TOOLS = [
11
+ "bash",
12
+ "read",
13
+ "write",
14
+ "edit",
15
+ "glob",
16
+ "grep",
17
+ "webfetch",
18
+ "websearch",
19
+ "codesearch",
20
+ "task",
21
+ "todowrite",
22
+ "todoread",
23
+ "patch",
24
+ "multiedit",
25
+ "lsp",
26
+ "lsp_hover",
27
+ "lsp_diagnostics",
28
+ "batch",
29
+ "skill",
30
+ ];
31
+ // Tools for Just Chat: web research and conversation
32
+ // Uses native tools directly (no chat_* wrappers needed)
33
+ const JUST_CHAT_NATIVE = ["webfetch", "websearch"];
34
+ const JUST_CHAT_TOOLS = ["chat_remember", "chat_todowrite", "chat_todoread"];
35
+ // Native tools to enable for Tool Chat (in addition to chat_* tools)
36
+ const TOOL_CHAT_NATIVE = ["websearch", "webfetch"];
37
+ export function configureChatAgents(config, toolIds) {
38
+ // Disable chat_* tools globally - this affects all built-in agents
39
+ config.tools = config.tools ?? {};
40
+ for (const id of toolIds) {
41
+ config.tools[id] = false;
42
+ }
43
+ config.agent = config.agent ?? {};
44
+ // Just Chat: minimal tools for conversation and web research
45
+ config.agent["Just Chat"] = {
46
+ description: "Conversational agent with web access",
47
+ mode: "primary",
48
+ prompt: CHATIFIER_PROMPT,
49
+ tools: {
50
+ ...Object.fromEntries(NATIVE_TOOLS.map((id) => [id, false])),
51
+ ...Object.fromEntries(JUST_CHAT_NATIVE.map((id) => [id, true])),
52
+ ...Object.fromEntries(JUST_CHAT_TOOLS.map((id) => [id, true])),
53
+ },
54
+ };
55
+ // Tool Chat: full toolkit for files, code, and web
56
+ config.agent["Tool Chat"] = {
57
+ description: "Full toolkit agent for files and code",
58
+ prompt: CHATIFIER_PROMPT,
59
+ tools: {
60
+ ...Object.fromEntries(NATIVE_TOOLS.map((id) => [id, false])),
61
+ ...Object.fromEntries(TOOL_CHAT_NATIVE.map((id) => [id, true])),
62
+ ...Object.fromEntries(toolIds.map((id) => [id, true])),
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Chatifier plugin entrypoint.
3
+ * Wires chat_* tools, config mutations, and system prompt updates.
4
+ * Keeps orchestration minimal and delegates logic to modules.
5
+ */
6
+ import type { Plugin } from "@opencode-ai/plugin";
7
+ export declare const ChatifierPlugin: Plugin;
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAQjD,eAAO,MAAM,eAAe,EAAE,MAyC7B,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,44 @@
1
+ import path from "path";
2
+ import { TODO_FILENAME } from "./util/constants";
3
+ import { configureChatAgents } from "./config";
4
+ import { replaceSystemPrompt } from "./system";
5
+ import { createChatTools } from "./tools";
6
+ import { ensureSemanticIndex, ensureModel } from "./semantic";
7
+ export const ChatifierPlugin = async ({ directory, worktree }) => {
8
+ const todoPath = path.join(worktree, TODO_FILENAME);
9
+ await ensureModel(worktree);
10
+ const result = await ensureSemanticIndex(worktree, {
11
+ mode: "changed",
12
+ maxTargets: 100,
13
+ onProgress: (progress) => {
14
+ if (progress.total === 0)
15
+ return;
16
+ const percent = Math.floor((progress.processed / progress.total) * 100);
17
+ const filled = Math.round((percent / 100) * 20);
18
+ const bar = "=".repeat(filled) + "-".repeat(20 - filled);
19
+ const current = progress.currentPath ? `\n ${progress.currentPath}` : "";
20
+ console.log(`[semantic] [${bar}] ${percent}% ${progress.processed}/${progress.total} files, chunks: ${progress.chunks}${current}`);
21
+ },
22
+ });
23
+ if (result.skippedReason) {
24
+ console.log(`\n[semantic] ⚠️ indexing skipped: ${result.skippedReason} (${result.total} files)`);
25
+ console.log(`[semantic] Run \`bun run semantic-index\` to index all files.\n`);
26
+ await Bun.sleep(10000);
27
+ }
28
+ else if (result.indexed > 0) {
29
+ console.log(`[semantic] indexed ${result.indexed} files (${result.chunks} chunks)`);
30
+ }
31
+ else if (result.total === 0 && result.skipped > 0) {
32
+ console.log(`[semantic] index up to date (${result.skipped} files unchanged)`);
33
+ }
34
+ const chatTools = createChatTools(directory, worktree, todoPath);
35
+ return {
36
+ config: async (config) => {
37
+ configureChatAgents(config, chatTools.toolIds);
38
+ },
39
+ "experimental.chat.system.transform": async (_input, output) => {
40
+ replaceSystemPrompt(output.system);
41
+ },
42
+ tool: chatTools.tools,
43
+ };
44
+ };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=download-model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"download-model.d.ts","sourceRoot":"","sources":["../../script/download-model.ts"],"names":[],"mappings":""}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Download embedding model for semantic search.
3
+ * Usage: bun script/download-model.ts
4
+ * Automatically finds repo root by walking up to .opencode/
5
+ */
6
+ import * as path from "path";
7
+ import * as fs from "fs/promises";
8
+ import { EmbeddingModel, ExecutionProvider, FlagEmbedding } from "fastembed";
9
+ const MODEL_DIRNAME = "models";
10
+ async function findRepoRoot(start) {
11
+ let dir = start;
12
+ while (dir !== "/") {
13
+ const opencodePath = path.join(dir, ".opencode");
14
+ const exists = await fs
15
+ .stat(opencodePath)
16
+ .then((s) => s.isDirectory())
17
+ .catch(() => false);
18
+ if (exists)
19
+ return dir;
20
+ dir = path.dirname(dir);
21
+ }
22
+ return start;
23
+ }
24
+ async function main() {
25
+ const worktree = await findRepoRoot(path.resolve(process.cwd()));
26
+ const cacheDir = path.join(worktree, ".opencode", "chat", MODEL_DIRNAME);
27
+ console.log(`[model] worktree: ${worktree}`);
28
+ console.log(`[model] cache dir: ${cacheDir}`);
29
+ console.log(`[model] downloading AllMiniLML6V2...`);
30
+ await fs.mkdir(cacheDir, { recursive: true });
31
+ await FlagEmbedding.init({
32
+ model: EmbeddingModel.AllMiniLML6V2,
33
+ executionProviders: [ExecutionProvider.CPU],
34
+ cacheDir,
35
+ showDownloadProgress: true,
36
+ });
37
+ console.log(`[model] download complete!`);
38
+ }
39
+ await main();
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=semantic-index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semantic-index.d.ts","sourceRoot":"","sources":["../../script/semantic-index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Manual semantic indexer.
3
+ * Usage: bun script/semantic-index.ts --mode changed|full
4
+ * Automatically finds repo root by walking up to .opencode/
5
+ */
6
+ import * as path from "path";
7
+ import * as fs from "fs/promises";
8
+ import { ensureSemanticIndex } from "../semantic";
9
+ async function findRepoRoot(start) {
10
+ let dir = start;
11
+ while (dir !== "/") {
12
+ const opencodePath = path.join(dir, ".opencode");
13
+ const exists = await fs
14
+ .stat(opencodePath)
15
+ .then((s) => s.isDirectory())
16
+ .catch(() => false);
17
+ if (exists)
18
+ return dir;
19
+ dir = path.dirname(dir);
20
+ }
21
+ return start;
22
+ }
23
+ function parseMode(argv) {
24
+ const idx = argv.indexOf("--mode");
25
+ if (idx === -1)
26
+ return "changed";
27
+ const value = argv[idx + 1];
28
+ if (value === "full")
29
+ return "full";
30
+ return "changed";
31
+ }
32
+ function formatProgress(progress) {
33
+ if (progress.total === 0)
34
+ return "[semantic] no files to index";
35
+ const percent = Math.floor((progress.processed / progress.total) * 100);
36
+ const width = 24;
37
+ const filled = Math.round((percent / 100) * width);
38
+ const bar = "=".repeat(filled) + "-".repeat(width - filled);
39
+ const current = progress.currentPath ? `\n ${progress.currentPath}` : "";
40
+ return `[semantic] [${bar}] ${percent}% ${progress.processed}/${progress.total} files, chunks: ${progress.chunks}${current}`;
41
+ }
42
+ async function main() {
43
+ const mode = parseMode(process.argv);
44
+ const worktree = await findRepoRoot(path.resolve(process.cwd()));
45
+ console.log(`[semantic] worktree: ${worktree}`);
46
+ let lastShown = "";
47
+ const result = await ensureSemanticIndex(worktree, {
48
+ mode,
49
+ onProgress: (progress) => {
50
+ const line = formatProgress(progress);
51
+ if (line === lastShown)
52
+ return;
53
+ lastShown = line;
54
+ console.log(line);
55
+ },
56
+ });
57
+ console.log("Semantic index complete.");
58
+ console.log(`mode: ${result.mode}`);
59
+ console.log(`files indexed: ${result.indexed}`);
60
+ console.log(`files skipped: ${result.skipped}`);
61
+ console.log(`chunks: ${result.chunks}`);
62
+ }
63
+ await main();
@@ -0,0 +1,8 @@
1
+ export type Chunk = {
2
+ path: string;
3
+ startLine: number;
4
+ endLine: number;
5
+ content: string;
6
+ };
7
+ export declare function chunkFile(filePath: string, text: string): Chunk[];
8
+ //# sourceMappingURL=chunker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chunker.d.ts","sourceRoot":"","sources":["../../semantic/chunker.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,KAAK,GAAG;IAClB,IAAI,EAAE,MAAM,CAAA;IACZ,SAAS,EAAE,MAAM,CAAA;IACjB,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE,MAAM,CAAA;CAChB,CAAA;AA+KD,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,KAAK,EAAE,CAIjE"}
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Text chunking strategies for semantic indexing.
3
+ * Splits files into embeddable chunks respecting content boundaries.
4
+ */
5
+ import * as path from "path";
6
+ const MAX_CHUNK_CHARS = 6000;
7
+ function linesToText(lines) {
8
+ return lines.join("\n");
9
+ }
10
+ function splitByParagraphs(lines, startLine, maxChars) {
11
+ const paragraphs = [];
12
+ let current = [];
13
+ let currentStart = startLine;
14
+ for (let i = 0; i < lines.length; i++) {
15
+ const line = lines[i];
16
+ if (current.length === 0)
17
+ currentStart = startLine + i;
18
+ current.push(line);
19
+ if (line.trim() === "") {
20
+ paragraphs.push({ start: currentStart, end: startLine + i, lines: current });
21
+ current = [];
22
+ }
23
+ }
24
+ if (current.length > 0) {
25
+ paragraphs.push({ start: currentStart, end: startLine + lines.length - 1, lines: current });
26
+ }
27
+ const chunks = [];
28
+ let acc = [];
29
+ let accStart = startLine;
30
+ let accLen = 0;
31
+ for (const para of paragraphs) {
32
+ const text = linesToText(para.lines);
33
+ const nextLen = accLen + text.length;
34
+ if (accLen > 0 && nextLen > maxChars) {
35
+ chunks.push({ start: accStart, end: accStart + acc.length - 1, lines: acc });
36
+ acc = [];
37
+ accLen = 0;
38
+ }
39
+ if (text.length > maxChars) {
40
+ if (acc.length > 0) {
41
+ chunks.push({ start: accStart, end: accStart + acc.length - 1, lines: acc });
42
+ acc = [];
43
+ accLen = 0;
44
+ }
45
+ let slice = [];
46
+ let sliceStart = para.start;
47
+ let sliceLen = 0;
48
+ for (let i = 0; i < para.lines.length; i++) {
49
+ const line = para.lines[i];
50
+ const lineLen = line.length + 1;
51
+ if (sliceLen > 0 && sliceLen + lineLen > maxChars) {
52
+ chunks.push({ start: sliceStart, end: sliceStart + slice.length - 1, lines: slice });
53
+ slice = [];
54
+ sliceLen = 0;
55
+ sliceStart = para.start + i;
56
+ }
57
+ slice.push(line);
58
+ sliceLen += lineLen;
59
+ }
60
+ if (slice.length > 0) {
61
+ chunks.push({ start: sliceStart, end: sliceStart + slice.length - 1, lines: slice });
62
+ }
63
+ continue;
64
+ }
65
+ if (acc.length === 0)
66
+ accStart = para.start;
67
+ acc.push(...para.lines);
68
+ accLen += text.length;
69
+ }
70
+ if (acc.length > 0) {
71
+ chunks.push({ start: accStart, end: accStart + acc.length - 1, lines: acc });
72
+ }
73
+ return chunks;
74
+ }
75
+ function chunkMarkdown(filePath, text) {
76
+ const lines = text.split("\n");
77
+ const chunks = [];
78
+ let index = 0;
79
+ if (lines[0] === "---") {
80
+ let end = -1;
81
+ for (let i = 1; i < lines.length; i++) {
82
+ if (lines[i] === "---") {
83
+ end = i;
84
+ break;
85
+ }
86
+ }
87
+ if (end > 0) {
88
+ chunks.push({ path: filePath, startLine: 1, endLine: end + 1, content: linesToText(lines.slice(0, end + 1)) });
89
+ index = end + 1;
90
+ }
91
+ }
92
+ let sectionStart = index;
93
+ let sectionLines = [];
94
+ const flushSection = (startLine, linesToFlush) => {
95
+ if (linesToFlush.length === 0)
96
+ return;
97
+ const textContent = linesToText(linesToFlush);
98
+ if (textContent.length <= MAX_CHUNK_CHARS) {
99
+ chunks.push({
100
+ path: filePath,
101
+ startLine: startLine + 1,
102
+ endLine: startLine + linesToFlush.length,
103
+ content: textContent,
104
+ });
105
+ return;
106
+ }
107
+ for (const chunk of splitByParagraphs(linesToFlush, startLine + 1, MAX_CHUNK_CHARS)) {
108
+ chunks.push({ path: filePath, startLine: chunk.start, endLine: chunk.end, content: linesToText(chunk.lines) });
109
+ }
110
+ };
111
+ for (let i = index; i < lines.length; i++) {
112
+ const line = lines[i];
113
+ if (line.startsWith("#")) {
114
+ flushSection(sectionStart, sectionLines);
115
+ sectionStart = i;
116
+ sectionLines = [line];
117
+ continue;
118
+ }
119
+ sectionLines.push(line);
120
+ }
121
+ flushSection(sectionStart, sectionLines);
122
+ return chunks;
123
+ }
124
+ function chunkText(filePath, text) {
125
+ const lines = text.split("\n");
126
+ const chunks = [];
127
+ let current = [];
128
+ let currentStart = 1;
129
+ let currentLen = 0;
130
+ for (let i = 0; i < lines.length; i++) {
131
+ const line = lines[i];
132
+ const nextLen = currentLen + line.length + 1;
133
+ if (currentLen > 0 && nextLen > MAX_CHUNK_CHARS) {
134
+ chunks.push({
135
+ path: filePath,
136
+ startLine: currentStart,
137
+ endLine: currentStart + current.length - 1,
138
+ content: linesToText(current),
139
+ });
140
+ current = [];
141
+ currentLen = 0;
142
+ }
143
+ if (current.length === 0)
144
+ currentStart = i + 1;
145
+ current.push(line);
146
+ currentLen += line.length + 1;
147
+ }
148
+ if (current.length > 0) {
149
+ chunks.push({
150
+ path: filePath,
151
+ startLine: currentStart,
152
+ endLine: currentStart + current.length - 1,
153
+ content: linesToText(current),
154
+ });
155
+ }
156
+ return chunks;
157
+ }
158
+ export function chunkFile(filePath, text) {
159
+ const ext = path.extname(filePath).toLowerCase();
160
+ if (ext === ".md" || ext === ".mdx")
161
+ return chunkMarkdown(filePath, text);
162
+ return chunkText(filePath, text);
163
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Embedding model management and vector operations.
3
+ * Handles model initialization and similarity scoring.
4
+ */
5
+ import { FlagEmbedding } from "fastembed";
6
+ export declare function getEmbedder(cacheDir: string): Promise<FlagEmbedding>;
7
+ export declare function ensureModel(worktree: string): Promise<void>;
8
+ export declare function encodeEmbedding(vec: number[]): Buffer<ArrayBuffer>;
9
+ export declare function decodeEmbedding(blob: Uint8Array): Float32Array<ArrayBufferLike>;
10
+ export declare function cosineSimilarity(a: Float32Array, b: Float32Array): number;
11
+ export declare function getModelDir(dbDir: string): string;
12
+ //# sourceMappingURL=embedder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedder.d.ts","sourceRoot":"","sources":["../../semantic/embedder.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAqC,aAAa,EAAE,MAAM,WAAW,CAAA;AAO5E,wBAAsB,WAAW,CAAC,QAAQ,EAAE,MAAM,0BASjD;AAED,wBAAsB,WAAW,CAAC,QAAQ,EAAE,MAAM,iBAUjD;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,uBAE5C;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,UAAU,iCAE/C;AAED,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,UAWhE;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,UAExC"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Embedding model management and vector operations.
3
+ * Handles model initialization and similarity scoring.
4
+ */
5
+ import { EmbeddingModel, ExecutionProvider, FlagEmbedding } from "fastembed";
6
+ import * as path from "path";
7
+ import * as fs from "fs/promises";
8
+ const MODEL_DIRNAME = "models";
9
+ let embedder = null;
10
+ export async function getEmbedder(cacheDir) {
11
+ if (embedder)
12
+ return embedder;
13
+ embedder = await FlagEmbedding.init({
14
+ model: EmbeddingModel.AllMiniLML6V2,
15
+ executionProviders: [ExecutionProvider.CPU],
16
+ cacheDir,
17
+ showDownloadProgress: true,
18
+ });
19
+ return embedder;
20
+ }
21
+ export async function ensureModel(worktree) {
22
+ const cacheDir = path.join(worktree, ".opencode", "chat", MODEL_DIRNAME);
23
+ const modelPath = path.join(cacheDir, "fast-all-MiniLM-L6-v2", "model.onnx");
24
+ const exists = await fs
25
+ .stat(modelPath)
26
+ .then(() => true)
27
+ .catch(() => false);
28
+ if (exists)
29
+ return;
30
+ await fs.mkdir(cacheDir, { recursive: true });
31
+ await getEmbedder(cacheDir);
32
+ }
33
+ export function encodeEmbedding(vec) {
34
+ return Buffer.from(new Float32Array(vec).buffer);
35
+ }
36
+ export function decodeEmbedding(blob) {
37
+ return new Float32Array(blob.buffer, blob.byteOffset, blob.byteLength / 4);
38
+ }
39
+ export function cosineSimilarity(a, b) {
40
+ let dot = 0;
41
+ let normA = 0;
42
+ let normB = 0;
43
+ for (let i = 0; i < a.length; i++) {
44
+ dot += a[i] * b[i];
45
+ normA += a[i] * a[i];
46
+ normB += b[i] * b[i];
47
+ }
48
+ if (normA === 0 || normB === 0)
49
+ return 0;
50
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
51
+ }
52
+ export function getModelDir(dbDir) {
53
+ return path.join(dbDir, MODEL_DIRNAME);
54
+ }