@nandoblanco/opencode-local-search 0.0.0-stage → 1.0.1

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 Fernando Blanco
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,244 @@
1
- # Temporary Holding Version
1
+ # opencode-local-search
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
+ **Local-first, zero-token interactive session search plugin for OpenCode**: indexes your local SQLite session history automatically, previews matching messages, tools, and files as you type, and jumps straight to the exact matched message in any conversation.
4
+
5
+ ![opencode-local-search TUI preview](./assets/screenshot.png)
6
+
7
+ ## Background
8
+
9
+ This project started as a small local CLI script wired to a custom `/search` command. It queried OpenCode's SQLite database and printed matching session IDs into the chat, which worked as a quick prototype but had two limitations in daily use:
10
+
11
+ 1. **Every search ran through an LLM turn**: Because custom markdown commands send their output to the model, searching past sessions took several seconds and used prompt and completion tokens just to look up an old conversation.
12
+ 2. **Results were static text**: Getting a list of session IDs in the chat still meant copying an ID or opening `/sessions` to actually switch to the session.
13
+
14
+ `opencode-local-search` makes session search a native part of the terminal interface:
15
+
16
+ 1. **Zero-token local SQLite indexing**: Queries OpenCode's local SQLite database directly inside the TUI using the runtime's built-in driver (`bun:sqlite` or `node:sqlite`) without making an LLM request.
17
+ 2. **Live split-pane preview**: Filter across your past work on every keystroke on the left while inspecting highlighted message snippets, tools used, and files touched on the right.
18
+ 3. **Jump to the exact message**: Pressing `Enter` opens the selected session and scrolls the transcript straight to the message that matched instead of the bottom of the conversation.
19
+
20
+ ## Features
21
+
22
+ | Feature | Details |
23
+ | :--- | :--- |
24
+ | Local-first, zero-token execution | Queries your local OpenCode SQLite database directly inside the TUI with zero LLM token usage, zero server tools, and zero cloud dependencies |
25
+ | Zero external npm dependencies | Uses the SQLite driver built into OpenCode's runtime (`bun:sqlite` or `node:sqlite`) and a built-in bounded Levenshtein matcher, requiring no native C++ addons |
26
+ | Dual-schema support (OpenCode V2 + V1) | Automatically detects and indexes both the OpenCode V2 schema (`session_v2` and `session_message`) and the V1 schema (`session`, `message`, and `part`) |
27
+ | Interactive `/search` TUI modal | Wide (`80%` default, configurable via `dialogWidth`) split-pane popup with colored filter pills (`^p` scope, `^g` role, `^t` date, `^r` mode, `^l` refresh), live session list on the left, and highlighted message/tool/file snippet cards on the right |
28
+ | Session-level multi-term AND ranking | Searching `auth cookie` finds sessions where both terms appear anywhere across the session title, user prompts, assistant replies, tool calls, or file paths, ranking single-message co-occurrences higher |
29
+ | Typo-tolerant fuzzy & regex search | Supports `"exact phrase"`, `/regex/i` (`re:`), explicit `~fuzzy` terms, and automatic bounded Levenshtein fallback when a multi-word query has a typo |
30
+ | Auto-scroll to matched message | Pressing `Enter` (or clicking any snippet card in the preview pane) opens the session and automatically scrolls the transcript to the exact matched message |
31
+
32
+ ## Installation
33
+
34
+ ### Option 1: One-Command Install (Recommended)
35
+
36
+ ```sh
37
+ npx @nandoblanco/opencode-local-search install
38
+ # or directly from GitHub:
39
+ npx github:nandoblanco/opencode-local-search install
40
+ ```
41
+
42
+ Or install with OpenCode's native plugin CLI:
43
+
44
+ ```sh
45
+ opencode plugin add @nandoblanco/opencode-local-search
46
+ # or directly from GitHub:
47
+ opencode plugin add github:nandoblanco/opencode-local-search
48
+ ```
49
+
50
+ ### Option 2: Manual Configuration
51
+
52
+ Add `@nandoblanco/opencode-local-search` to `~/.config/opencode/cli.json` (or `$XDG_CONFIG_HOME/opencode/cli.json`):
53
+
54
+ ```json
55
+ {
56
+ "plugins": [
57
+ [
58
+ "@nandoblanco/opencode-local-search",
59
+ {
60
+ "dialogWidth": "80%"
61
+ }
62
+ ]
63
+ ]
64
+ }
65
+ ```
66
+
67
+ ### From a Local Directory
68
+
69
+ Clone or copy this folder and reference it in `~/.config/opencode/cli.json` (no `npm install` or build step required):
70
+
71
+ ```json
72
+ {
73
+ "plugins": ["file:///path/to/opencode-local-search"]
74
+ }
75
+ ```
76
+
77
+ ## Usage
78
+
79
+ ### Zero-Token TUI Commands
80
+
81
+ 1. **Interactive `/search` popup**: Run `/search` to open the popup, or `/search <query>` (for example `/search playwright` or `/search file:tui.ts`) to open with your search pre-filled.
82
+ 2. **Command palette**: Press `Ctrl+P` and select `Search session history...`.
83
+ 3. **Custom keybind**: Bind `session.history.search` in `~/.config/opencode/cli.json`:
84
+
85
+ ```json
86
+ {
87
+ "keybinds": {
88
+ "session.history.search": "ctrl+f"
89
+ }
90
+ }
91
+ ```
92
+
93
+ ## TUI Query Syntax (`/search`)
94
+
95
+ Type filters inline in the search bar or toggle them with keyboard shortcuts and clickable filter pills.
96
+
97
+ | Syntax | Description | Example |
98
+ | :--- | :--- | :--- |
99
+ | `term1 term2` | Session-level AND across title, messages, tools, and files (single-message hits rank higher) | `auth cookie` |
100
+ | `"exact phrase"` | Exact substring phrase match | `"session_message"` |
101
+ | `~term` | Typo-tolerant fuzzy match (bounded Levenshtein distance) | `~playwrigth` |
102
+ | `/pattern/i` or `re:pattern` | Regular expression match | `/error\s+\d+/i` |
103
+ | `role:user` / `role:assistant` / `role:shell` | Filter by message author (`from:user`, `from:ai` also work) | `role:user backup` |
104
+ | `scope:project` / `scope:all` | Filter to current workspace directory or all workspaces | `scope:project` |
105
+ | `date:today` / `date:yesterday` / `date:7d` / `date:30d` | Relative date filter | `date:7d migration` |
106
+ | `date:YYYY-MM` or `date:YYYY-MM-DD..YYYY-MM-DD` | Month or date range filter | `date:2026-10` |
107
+ | `file:<path>` | Filter sessions that read or modified a matching file path | `file:tui.ts` |
108
+ | `tool:<name>` | Filter sessions that invoked a matching tool | `tool:edit` |
109
+ | `in:title` / `in:message` / `in:tool` / `in:file` | Restrict search to a specific entry type | `in:title plugin` |
110
+
111
+ ## Keyboard Shortcuts (`/search`)
112
+
113
+ | Key | Action |
114
+ | :--- | :--- |
115
+ | `Enter` | Open the selected session and auto-scroll to the active matched snippet |
116
+ | `Up` / `Down` or `Ctrl+N` / `Ctrl+K` | Move selection up or down (or cycle matching snippets when the Preview pane is focused; `j`/`k` also work in List and Preview panes) |
117
+ | `PageUp` / `PageDown` or `Ctrl+U` / `Ctrl+D` | Jump 6 sessions up/down (or scroll the Preview pane by 8 lines when focused) |
118
+ | `Tab` / `Shift+Tab` | Switch focus between Search Input, Session List, and Preview Pane (`/` returns to Search Input) |
119
+ | `Ctrl+P` | Toggle project scope pill (`scope:all` <-> `scope:project`) |
120
+ | `Ctrl+G` | Cycle role filter pill (`all` -> `user` -> `assistant` -> `shell`) |
121
+ | `Ctrl+T` | Cycle date filter pill (`all` -> `today` -> `yesterday` -> `7d` -> `30d`) |
122
+ | `Ctrl+R` | Cycle search mode pill (`smart` -> `fuzzy` -> `regex`) |
123
+ | `Ctrl+L` | Force refresh the SQLite session index |
124
+ | `Esc` | Close popup |
125
+
126
+ ## How It Works (Architecture & Internals)
127
+
128
+ ### 1. Zero-Dependency Native SQLite Driver (`openReadOnlyDb` & `resolveDbPath`)
129
+
130
+ `opencode-local-search` has zero runtime npm dependencies and requires no compiled C++ addons. When the popup opens, `openReadOnlyDb()` detects the active JavaScript runtime (`Bun` vs. Node.js) and dynamically imports the built-in SQLite driver (`bun:sqlite` or `node:sqlite`) in read-only mode.
131
+
132
+ `resolveDbPath()` locates the OpenCode database in this order:
133
+
134
+ 1. Explicit `customPath` argument (used by tests or custom callers)
135
+ 2. `OPENCODE_DB_PATH` environment variable
136
+ 3. `$XDG_DATA_HOME/opencode/opencode.db`
137
+ 4. `~/.local/share/opencode/opencode.db` (macOS, Linux, Windows)
138
+ 5. `%LOCALAPPDATA%/opencode/opencode.db` (Windows fallback)
139
+
140
+ Once loaded, `loadSessionIndex()` caches the parsed `SessionIndex` in memory for 6 seconds (`INDEX_TTL_MS = 6000`) so typing in the search bar filters in sub-millisecond time without re-querying SQLite on every keystroke (`Ctrl+L` forces an immediate re-index).
141
+
142
+ ### 2. Dual-Schema Indexing (OpenCode V2 + V1 Fallback)
143
+
144
+ At index time, `loadSessionIndex()` inspects `sqlite_master` to support both OpenCode database generations automatically:
145
+
146
+ - **OpenCode V2 (`session_v2` + `session_message`)**:
147
+ - Inspects `PRAGMA table_info(session_v2)` to resolve workspace directory columns (`directory` or `COALESCE(workspace_directory, root_directory, '')`) and exclude archived sessions (`WHERE time_archived IS NULL`).
148
+ - Loads the 800 most recently updated sessions and uses a window function (`ROW_NUMBER() OVER (PARTITION BY m.session_id ORDER BY m.time_created DESC)`) to pull up to the latest 250 messages per session (`LIMIT 30000`, with a plain `ORDER BY` fallback if window functions are unavailable).
149
+ - **OpenCode V1 Fallback (`session` + `message` + `part`)**:
150
+ - Automatically falls back to joining `part` and `message` (`json_extract(m.data, '$.role')`) if `session_v2` is not present.
151
+ - **Structured entry extraction**:
152
+ - The indexer splits each message JSON payload into three `SearchEntry` kinds:
153
+ - `message`: User prompt text and assistant reply text parts
154
+ - `tool`: Tool invocations (`[toolName] key: value · ...` via `stringifyToolInput()`) and shell commands plus terminal output (`$ command\noutput`)
155
+ - `filepath`: Attached user files, patch file lists, and file paths extracted from tool arguments (`path`, `filePath`, `file`, `file_path`, `targetFile`, `workdir`, `directory`, `files` via `extractFilePathsFromInput()`)
156
+
157
+ ### 3. Query Parser & Session-Level AND Ranking (`parseSearchQuery` & `searchSessionIndex`)
158
+
159
+ `parseSearchQuery()` tokenizes raw input with `/(\/[^/]+\/[gimsuy]*|[a-zA-Z]+:"[^"]+"|"[^"]+"|\S+)/g`, separating inline filter tokens (`role:`, `scope:`, `date:`, `file:`, `tool:`, `in:`, `re:`, `~fuzzy`) from search terms and quoted phrases.
160
+
161
+ When filtering sessions, `searchSessionIndex()` enforces **session-level multi-term AND matching**: every required term in `terms` and `fuzzyTerms` must appear somewhere in the session, even if one term is in the session title, another is in a user prompt, and a third is in an edited file path. `searchSessionIndex()` scores matching sessions with fixed weights:
162
+
163
+ | Signal | Score Contribution | Notes |
164
+ | :--- | :--- | :--- |
165
+ | Title regex match | `+120` | When searching in `regex` mode (`/pattern/i` or `re:`) |
166
+ | Title exact substring match | `+90` | Per query term matched in `session.title` |
167
+ | Title fuzzy match | `+65 - (distance * 10)` | Explicit `~term` (`+55 - distance * 10` in `fuzzy` mode) |
168
+ | Entry exact match | `+35 * entryMatchedTerms` | Per message, tool call, or file path entry (`+50` / `+35` in `regex` mode) |
169
+ | Entry fuzzy match | `+20 * entryMatchedTerms` | When matched via bounded Levenshtein distance |
170
+ | Single-message co-occurrence bonus | `+45` | Added when a single message contains **all** query terms |
171
+ | Active `file:` / `tool:` target bonus | `+25` | Added when an entry directly matches the active `file:` or `tool:` filter |
172
+ | Recency boost | `max(0, 15 - recencyDays * 0.4)` | Breaks ties in favor of recently updated sessions |
173
+
174
+ ### 4. Zero-Dependency Typo Tolerance (`editDistanceBounded` & `findFuzzyWordMatch`)
175
+
176
+ `src/search.ts` implements a bounded Levenshtein dynamic programming matcher (`editDistanceBounded(a, b, maxDist)`) for typo tolerance:
177
+
178
+ - Uses two rolling row arrays (`prev` and `curr`) and aborts immediately if length difference exceeds `maxDist` or if the minimum value in the current DP row exceeds `maxDist`.
179
+ - Allows edit distance `<= 1` for short words (3 to 5 characters) and `<= 2` for longer words (6+ characters), pre-filtering candidate tokens by a shared 2-character prefix or length within `maxDist`.
180
+ - **Automatic Smart Fallback**: In default `smart` mode, if a multi-word query fails the strict session-level AND check because one word has a typo (for example, `playwrigth`), `searchSessionIndex()` automatically retries the missing term through `findFuzzyWordMatch()` (`+30` title / `+22` entry) and tags the resulting snippet as `[FUZZY]`.
181
+
182
+ ### 5. Auto-Scroll to the Exact Matched Message (`scrollToMatchedMessage`)
183
+
184
+ When you press `Enter` on a session (or click a specific snippet card in the right preview pane), the plugin navigates to that session (`context.ui.router.navigate({ type: "session", sessionID })`) and runs `scrollToMatchedMessage()` to scroll the transcript to the matched message:
185
+
186
+ 1. **Message store sync**: Triggers `context.data.session.message.sync(sessionId)` and polls the live `@opentui` render tree every 60ms (up to 25 attempts) while the session view mounts.
187
+ 2. **Viewport discovery**: Traverses `context.renderer.root` to find the largest visible `ScrollBoxRenderable` representing the conversation transcript.
188
+ 3. **Three-tier node resolution**:
189
+ - **Tier 1 (Exact ID)**: Matches a render node whose `id` equals or contains the target `messageId`.
190
+ - **Tier 2 (Tiered text needles + chronological ratio)**: Walks `scrollBox.content` and compares `extractRenderableText(node)` against progressively broader normalized snippet needles. If multiple nodes match the same text, it computes the message's chronological index ratio (`msgIdx / (liveMessages.length - 1)`) and picks the candidate whose vertical position (`relY`) is closest to `ratio`.
191
+ - **Tier 3 (Collapsed tool fallback)**: If the match was inside a collapsed tool call output, falls back after 6 attempts to scrolling to `topChildren[Math.round(ratio * (topChildren.length - 1))]`.
192
+ 4. **Viewport positioning & scroll lock**: Scrolls the matched node to 22% from the top of the viewport (`scrollBox.scrollBy({ x: 0, y: dy })`), sets `scrollBox._hasManualScroll = true` so OpenCode's auto-scroll-to-bottom does not snap back, and re-applies the offset after 120ms to settle layout reflows.
193
+
194
+ ### 6. Interactive OpenTUI `/search` Modal Architecture (`src/tui.ts`)
195
+
196
+ 1. **Wide modal layout (`applyDialogWidth` & `dialog.set`)**:
197
+ - Calls `context.ui.dialog.show(...)` followed by `context.ui.dialog.set({ size: "xlarge", centered: true })` so the dialog opens wide without being reset to default width.
198
+ - Inside `onMount` and `ref`, `applyDialogWidth()` walks upward from `rootRef` to the outer `absolute`-positioned dialog container and sets `width: "80%"` (or your configured `dialogWidth`), `maxWidth: "80%"`, and `minWidth: 72`.
199
+ 2. **Interactive filter pills & inline badge sync**:
200
+ - Renders clickable `Pill` components beneath the search input for `scope:<all|project>` (`^p`), `role:<role>` (`^g`), `date:<range>` (`^t`), and `mode:<mode>` (`^r`), plus live indicator badges when `file:<path>`, `tool:<name>`, or regex syntax errors are active in the query string.
201
+ 3. **Split-pane session list & selectable snippet cards**:
202
+ - Splits the main body into a 44%-width left session list (session title, match kind badge, relative age, and 1-line snippet preview) and a 56%-width right preview pane (session metadata header, files touched chips, and individual matched snippet cards).
203
+ - Focusing the right preview pane (`Tab`) lets you cycle through individual snippet cards inside the selected session with `Up`/`Down` and press `Enter` (or click a card directly) to jump straight to that specific message.
204
+
205
+ ### 7. Agent Tools Registered by the Server Plugin
206
+
207
+ `src/server.ts` is intentionally a no-op entrypoint that registers **zero LLM agent tools**. All session indexing, filtering, and navigation happen strictly inside the TUI (`src/tui.ts`), adding **0 schema tokens** to your model context.
208
+
209
+ ### 8. Token Usage Breakdown
210
+
211
+ Every operation in `opencode-local-search` uses zero LLM tokens:
212
+
213
+ | Operation | Token Cost | Why |
214
+ | :--- | :--- | :--- |
215
+ | Opening `/search` & indexing SQLite (`loadSessionIndex`) | **0 tokens** | Queries `~/.local/share/opencode/opencode.db` directly in read-only mode via `bun:sqlite` or `node:sqlite` |
216
+ | Live filtering, fuzzy matching & snippet preview | **0 tokens** | Runs synchronously in memory (`searchSessionIndex`) inside the TUI process on every keystroke |
217
+ | Jumping to a matched session & message (`Enter`) | **0 tokens** | Navigates via `context.ui.router.navigate()` and scrolls the local `@opentui` transcript tree directly |
218
+ | Server plugin entrypoint (`src/server.ts`) | **0 schema tokens** | Registers no LLM tools or system prompts |
219
+
220
+ ## Configuration Options
221
+
222
+ Options can be passed in `~/.config/opencode/cli.json` (or `opencode.jsonc`) or via environment variables:
223
+
224
+ ```json
225
+ {
226
+ "plugins": [
227
+ [
228
+ "@nandoblanco/opencode-local-search",
229
+ {
230
+ "dialogWidth": "80%"
231
+ }
232
+ ]
233
+ ]
234
+ }
235
+ ```
236
+
237
+ | Option | Env Variable | Default | Description |
238
+ | :--- | :--- | :--- | :--- |
239
+ | `dialogWidth` | `OPENCODE_SESSION_SEARCH_DIALOG_WIDTH` | `"80%"` | Width of the centered `/search` TUI modal (`"80%"` or column count like `120`; also respects `OPENCODE_DIALOG_WIDTH`) |
240
+ | *(db path)* | `OPENCODE_DB_PATH` | `~/.local/share/opencode/opencode.db` | Override path to the OpenCode SQLite database |
241
+
242
+ ## License
243
+
244
+ MIT
Binary file
package/cli.js ADDED
@@ -0,0 +1,269 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import os from "node:os";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const cliName = "open" + "code";
10
+
11
+ export function resolveConfigDir(explicitDir) {
12
+ if (explicitDir) {
13
+ if (explicitDir === "~") return os.homedir();
14
+ if (explicitDir.startsWith("~/") || explicitDir.startsWith("~\\")) {
15
+ return path.join(os.homedir(), explicitDir.slice(2));
16
+ }
17
+ return path.resolve(explicitDir);
18
+ }
19
+ if (process.env.OPENCODE_CONFIG_DIR) return path.resolve(process.env.OPENCODE_CONFIG_DIR);
20
+ if (process.env.XDG_CONFIG_HOME) return path.join(process.env.XDG_CONFIG_HOME, cliName);
21
+ return path.join(os.homedir(), ".config", cliName);
22
+ }
23
+
24
+ function findPluginsArraySpan(raw) {
25
+ const pluginsMatch = /"plugins"\s*:\s*\[/.exec(raw);
26
+ if (!pluginsMatch) return null;
27
+ const openBracketIdx = pluginsMatch.index + pluginsMatch[0].length - 1;
28
+ let depth = 0;
29
+ let inString = false;
30
+ let escape = false;
31
+ let inLineComment = false;
32
+ let inBlockComment = false;
33
+
34
+ for (let i = openBracketIdx; i < raw.length; i++) {
35
+ const ch = raw[i];
36
+ const next = raw[i + 1];
37
+
38
+ if (inLineComment) {
39
+ if (ch === "\n") inLineComment = false;
40
+ continue;
41
+ }
42
+ if (inBlockComment) {
43
+ if (ch === "*" && next === "/") {
44
+ inBlockComment = false;
45
+ i++;
46
+ }
47
+ continue;
48
+ }
49
+ if (escape) {
50
+ escape = false;
51
+ continue;
52
+ }
53
+ if (inString) {
54
+ if (ch === "\\") escape = true;
55
+ else if (ch === '"') inString = false;
56
+ continue;
57
+ }
58
+ if (ch === "/" && next === "/") {
59
+ inLineComment = true;
60
+ i++;
61
+ continue;
62
+ }
63
+ if (ch === "/" && next === "*") {
64
+ inBlockComment = true;
65
+ i++;
66
+ continue;
67
+ }
68
+ if (ch === '"') {
69
+ inString = true;
70
+ continue;
71
+ }
72
+ if (ch === "[") depth++;
73
+ else if (ch === "]") {
74
+ depth--;
75
+ if (depth === 0) {
76
+ return { openBracketIdx, closeBracketIdx: i };
77
+ }
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+
83
+ function findLastCodeCharIndex(str) {
84
+ let inString = false;
85
+ let escape = false;
86
+ let inLineComment = false;
87
+ let inBlockComment = false;
88
+ let lastCodeIdx = -1;
89
+
90
+ for (let i = 0; i < str.length; i++) {
91
+ const ch = str[i];
92
+ const next = str[i + 1];
93
+
94
+ if (inLineComment) {
95
+ if (ch === "\n") inLineComment = false;
96
+ continue;
97
+ }
98
+ if (inBlockComment) {
99
+ if (ch === "*" && next === "/") {
100
+ inBlockComment = false;
101
+ i++;
102
+ }
103
+ continue;
104
+ }
105
+ if (escape) {
106
+ escape = false;
107
+ lastCodeIdx = i;
108
+ continue;
109
+ }
110
+ if (inString) {
111
+ if (ch === "\\") escape = true;
112
+ else if (ch === '"') inString = false;
113
+ lastCodeIdx = i;
114
+ continue;
115
+ }
116
+ if (ch === "/" && next === "/") {
117
+ inLineComment = true;
118
+ i++;
119
+ continue;
120
+ }
121
+ if (ch === "/" && next === "*") {
122
+ inBlockComment = true;
123
+ i++;
124
+ continue;
125
+ }
126
+ if (ch === '"') {
127
+ inString = true;
128
+ lastCodeIdx = i;
129
+ continue;
130
+ }
131
+ if (!/\s/.test(ch)) {
132
+ lastCodeIdx = i;
133
+ }
134
+ }
135
+ return lastCodeIdx;
136
+ }
137
+
138
+ function addPluginToJsoncFile(filePath, defaultSchema, pluginEntryStr, matchSubstr) {
139
+ if (!fs.existsSync(filePath)) {
140
+ const initial =
141
+ "{\n" +
142
+ ' "$schema": "' +
143
+ defaultSchema +
144
+ '",\n' +
145
+ ' "plugins": [\n' +
146
+ " " +
147
+ pluginEntryStr +
148
+ "\n" +
149
+ " ]\n" +
150
+ "}\n";
151
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
152
+ fs.writeFileSync(filePath, initial, "utf8");
153
+ return "created";
154
+ }
155
+
156
+ const raw = fs.readFileSync(filePath, "utf8");
157
+ if (raw.includes(matchSubstr)) {
158
+ return "already-present";
159
+ }
160
+
161
+ const span = findPluginsArraySpan(raw);
162
+ if (span) {
163
+ const { openBracketIdx, closeBracketIdx } = span;
164
+ const insideRaw = raw.slice(openBracketIdx + 1, closeBracketIdx);
165
+ const lastCodeIdx = findLastCodeCharIndex(insideRaw);
166
+ if (lastCodeIdx === -1) {
167
+ const updated =
168
+ raw.slice(0, openBracketIdx + 1) +
169
+ "\n " +
170
+ pluginEntryStr +
171
+ "\n " +
172
+ raw.slice(closeBracketIdx);
173
+ fs.writeFileSync(filePath, updated, "utf8");
174
+ return "updated";
175
+ }
176
+ const lastChar = insideRaw[lastCodeIdx];
177
+ const withComma =
178
+ lastChar === ","
179
+ ? insideRaw.replace(/\s+$/, "")
180
+ : insideRaw.slice(0, lastCodeIdx + 1) + "," + insideRaw.slice(lastCodeIdx + 1).replace(/\s+$/, "");
181
+ const updated =
182
+ raw.slice(0, openBracketIdx + 1) +
183
+ withComma +
184
+ "\n " +
185
+ pluginEntryStr +
186
+ "\n " +
187
+ raw.slice(closeBracketIdx);
188
+ fs.writeFileSync(filePath, updated, "utf8");
189
+ return "updated";
190
+ }
191
+
192
+ const lastBraceIdx = raw.lastIndexOf("}");
193
+ if (lastBraceIdx !== -1) {
194
+ const beforeRaw = raw.slice(0, lastBraceIdx);
195
+ const lastCodeIdx = findLastCodeCharIndex(beforeRaw);
196
+ const lastChar = lastCodeIdx !== -1 ? beforeRaw[lastCodeIdx] : "{";
197
+ const needsComma = lastChar !== "{" && lastChar !== ",";
198
+ const withComma = needsComma
199
+ ? beforeRaw.slice(0, lastCodeIdx + 1) + "," + beforeRaw.slice(lastCodeIdx + 1).replace(/\s+$/, "")
200
+ : beforeRaw.replace(/\s+$/, "");
201
+ const updated =
202
+ withComma +
203
+ '\n "plugins": [\n ' +
204
+ pluginEntryStr +
205
+ "\n ]\n}\n";
206
+ fs.writeFileSync(filePath, updated, "utf8");
207
+ return "updated";
208
+ }
209
+
210
+ return "skipped";
211
+ }
212
+
213
+ export async function installPlugin(options) {
214
+ const opts = options || {};
215
+ const configDir = resolveConfigDir(opts.configDir);
216
+ fs.mkdirSync(configDir, { recursive: true });
217
+
218
+ const pkgName = "@nandoblanco/opencode-local-search";
219
+ const matchKey = "opencode-local-search";
220
+ const entryStr = opts.dialogWidth
221
+ ? '["' + pkgName + '", { "dialogWidth": "' + String(opts.dialogWidth) + '" }]'
222
+ : '"' + pkgName + '"';
223
+
224
+ const cliConfigFile = path.join(configDir, "cli.json");
225
+ const cliStatus = addPluginToJsoncFile(
226
+ cliConfigFile,
227
+ "https://" + cliName + ".ai/v2/cli.json",
228
+ entryStr,
229
+ matchKey
230
+ );
231
+
232
+ return {
233
+ configDir,
234
+ cliConfigFile,
235
+ cliStatus,
236
+ };
237
+ }
238
+
239
+ const isDirectRun =
240
+ process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
241
+ if (isDirectRun) {
242
+ const cmd = process.argv[2] || "install";
243
+ if (cmd === "install" || cmd === "init" || cmd === "setup") {
244
+ const args = process.argv.slice(3);
245
+ let configDir;
246
+ let dialogWidth;
247
+ for (let i = 0; i < args.length; i++) {
248
+ if ((args[i] === "--dir" || args[i] === "-d") && args[i + 1]) {
249
+ configDir = args[i + 1];
250
+ i++;
251
+ } else if ((args[i] === "--width" || args[i] === "--dialog-width") && args[i + 1]) {
252
+ dialogWidth = args[i + 1];
253
+ i++;
254
+ }
255
+ }
256
+ installPlugin({ configDir, dialogWidth })
257
+ .then((res) => {
258
+ console.log("opencode-local-search installed:");
259
+ console.log(" TUI config: " + res.cliConfigFile + " (" + res.cliStatus + ")");
260
+ })
261
+ .catch((err) => {
262
+ console.error("Install failed:", err);
263
+ process.exit(1);
264
+ });
265
+ } else {
266
+ console.log("Usage:");
267
+ console.log(" npx @nandoblanco/opencode-local-search install [--dir <config-dir>] [--width 80%]");
268
+ }
269
+ }
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@nandoblanco/opencode-local-search",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "Local-first, zero-token interactive TUI popup plugin to search past OpenCode sessions with multi-term AND, regex, fuzzy matching, and inline filters (role, date, file, tool, project scope).",
8
+ "type": "module",
9
+ "main": "./src/index.ts",
10
+ "exports": {
11
+ ".": "./src/index.ts",
12
+ "./server": "./src/server.ts",
13
+ "./tui": "./src/tui.ts"
14
+ },
15
+ "bin": {
16
+ "opencode-local-search": "cli.js"
17
+ },
18
+ "files": [
19
+ "cli.js",
20
+ "src/*.ts",
21
+ "assets/screenshot.png",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "scripts": {
26
+ "test": "node --no-warnings --experimental-strip-types --test test/search.test.ts"
27
+ },
28
+ "sideEffects": false,
29
+ "engines": {
30
+ "node": ">=22.5.0"
31
+ },
32
+ "keywords": [
33
+ "opencode",
34
+ "opencode-plugin",
35
+ "local-first",
36
+ "zero-token",
37
+ "session-search",
38
+ "history-search",
39
+ "tui",
40
+ "sqlite",
41
+ "fuzzy-search"
42
+ ],
43
+ "peerDependencies": {
44
+ "@opencode-ai/plugin": ">=2.0.0",
45
+ "@opentui/core": "*",
46
+ "@opentui/solid": "*",
47
+ "solid-js": "*"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "@opencode-ai/plugin": {
51
+ "optional": true
52
+ },
53
+ "@opentui/core": {
54
+ "optional": true
55
+ },
56
+ "@opentui/solid": {
57
+ "optional": true
58
+ },
59
+ "solid-js": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "author": "nandoblanco",
64
+ "license": "MIT",
65
+ "repository": {
66
+ "type": "git",
67
+ "url": "git+https://github.com/nandoblanco/opencode-local-search.git"
68
+ }
69
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+
3
+ import server from "./server.ts";
4
+
5
+ export { server };
6
+ export * from "./search.ts";
7
+ export default server;