pi-knowledge 0.5.4 → 0.5.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.5] - 2026-07-23
4
+
5
+ ### Added
6
+ - Added `knowledge_configure` so agents can validate and persist a Node 22+ executable for the isolated local model worker without relying on environment variables injected after OMP startup.
7
+
8
+ ### Fixed
9
+ - Auto-discovers Codex bundled Windows Node runtimes under `%LOCALAPPDATA%\OpenAI\Codex\runtimes\cua_node\*\bin\node.exe` for OMP sessions without global `node` on `PATH`.
10
+ - Reuses persisted runtime config before falling back to process or PATH discovery, so one successful configuration survives future OMP sessions.
11
+
3
12
  ## [0.5.4] - 2026-07-23
4
13
 
5
14
  ### Fixed
package/README.md CHANGED
@@ -110,6 +110,7 @@ omp install ./pi-knowledge
110
110
  | `knowledge_show` | List all knowledge bases with stats |
111
111
  | `knowledge_status` | Show engine status with health diagnostics (stale, orphans, coverage) |
112
112
  | `knowledge_doctor` | Diagnose health score, skipped files, stuck jobs, stale data, and recommended fixes |
113
+ | `knowledge_configure` | Persist runtime prerequisites such as a Windows `node.exe` path for the isolated local model worker |
113
114
  | `knowledge_clear` | Remove all knowledge bases after `confirm: true` |
114
115
  | `knowledge_export` | Export a KB to shareable JSONL file |
115
116
  | `knowledge_import` | Import a KB from JSONL (re-embeds content) |
package/dist/index.js CHANGED
@@ -248,6 +248,41 @@ export default function (pi) {
248
248
  };
249
249
  },
250
250
  });
251
+ pi.registerTool({
252
+ name: "knowledge_configure",
253
+ label: "Knowledge Configure",
254
+ description: "Configure pi-knowledge runtime settings such as the local model worker Node executable",
255
+ promptSnippet: "Configure local pi-knowledge runtime prerequisites before indexing",
256
+ promptGuidelines: [
257
+ "Use knowledge_configure when knowledge_doctor or knowledge_add reports that local embeddings cannot find a usable Node executable",
258
+ "On Windows, pass the full node.exe path when the user provides one; paths with spaces are accepted",
259
+ "If node_path is omitted, the tool auto-discovers a usable Node 22+ executable and persists it for future sessions",
260
+ "Do not switch users to API embeddings unless they explicitly choose a network embedding provider",
261
+ ],
262
+ parameters: Type.Object({
263
+ node_path: Type.Optional(Type.String({
264
+ description: "Optional full path to a Node 22+ executable for the isolated local embedding model worker, such as C:\\Program Files\\nodejs\\node.exe",
265
+ })),
266
+ }),
267
+ async execute(_id, params, _signal) {
268
+ if (_signal?.aborted)
269
+ throw new Error("Cancelled");
270
+ const { configureModelWorkerNodePath } = await import(__rewriteRelativeImportExtension(runtimeModule("./src/model-worker-client")));
271
+ if (_signal?.aborted)
272
+ throw new Error("Cancelled");
273
+ const nodePath = typeof params.node_path === "string" && params.node_path.trim() ? params.node_path : undefined;
274
+ const configuredPath = configureModelWorkerNodePath(nodePath);
275
+ return {
276
+ content: [
277
+ {
278
+ type: "text",
279
+ text: `Configured local model worker Node executable: ${configuredPath}`,
280
+ },
281
+ ],
282
+ details: { node_path: configuredPath },
283
+ };
284
+ },
285
+ });
251
286
  pi.registerTool({
252
287
  name: "knowledge_add",
253
288
  label: "Knowledge Add",
@@ -1,3 +1,6 @@
1
+ export declare function validateModelWorkerNodePath(nodePath: string): string;
2
+ export declare function resolveModelWorkerNodePath(): string;
3
+ export declare function configureModelWorkerNodePath(nodePath?: string): string;
1
4
  export declare function embedInModelWorker(texts: string[], prefix: "query" | "passage", signal?: AbortSignal): Promise<Float32Array[]>;
2
5
  export interface RerankWorkerCandidate {
3
6
  chunkId: string;
@@ -1,8 +1,9 @@
1
1
  import { execFileSync, fork, spawn } from "node:child_process";
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, readdirSync, statSync } from "node:fs";
3
3
  import { basename, delimiter, join } from "node:path";
4
4
  import { StringDecoder } from "node:string_decoder";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { getConfiguredNodePath, writeRuntimeConfig } from "./runtime-config.js";
6
7
  let worker = null;
7
8
  let nextRequestId = 1;
8
9
  let resolvedNodeExecPath = null;
@@ -59,6 +60,25 @@ function appendIfPresent(candidates, value, suffix) {
59
60
  return;
60
61
  candidates.push(suffix ? join(normalized, suffix) : normalized);
61
62
  }
63
+ function appendCodexNodeCandidates(candidates) {
64
+ const localAppData = process.env.LOCALAPPDATA ? normalizeExecutableCandidate(process.env.LOCALAPPDATA) : "";
65
+ if (!localAppData)
66
+ return;
67
+ const runtimeRoot = join(localAppData, "OpenAI", "Codex", "runtimes", "cua_node");
68
+ if (!existsSync(runtimeRoot))
69
+ return;
70
+ const discovered = readdirSync(runtimeRoot, { withFileTypes: true })
71
+ .filter((entry) => entry.isDirectory())
72
+ .map((entry) => {
73
+ const nodePath = join(runtimeRoot, entry.name, "bin", "node.exe");
74
+ const mtimeMs = existsSync(nodePath) ? statSync(nodePath).mtimeMs : 0;
75
+ return { nodePath, mtimeMs };
76
+ })
77
+ .filter((candidate) => candidate.mtimeMs > 0)
78
+ .sort((a, b) => b.mtimeMs - a.mtimeMs);
79
+ for (const candidate of discovered)
80
+ candidates.push(candidate.nodePath);
81
+ }
62
82
  function getWindowsNodeCandidates() {
63
83
  const candidates = [];
64
84
  appendIfPresent(candidates, process.env.NVM_SYMLINK, "node.exe");
@@ -66,6 +86,7 @@ function getWindowsNodeCandidates() {
66
86
  appendIfPresent(candidates, process.env.ProgramFiles, join("nodejs", "node.exe"));
67
87
  appendIfPresent(candidates, process.env["ProgramFiles(x86)"], join("nodejs", "node.exe"));
68
88
  appendIfPresent(candidates, process.env.LOCALAPPDATA, join("Programs", "nodejs", "node.exe"));
89
+ appendCodexNodeCandidates(candidates);
69
90
  for (const directory of pathEnvValue().split(delimiter)) {
70
91
  appendIfPresent(candidates, directory, "node.exe");
71
92
  }
@@ -100,6 +121,16 @@ function getNodeExecPath() {
100
121
  throw new Error(`PI_KNOWLEDGE_NODE_PATH does not point to a usable Node ${MIN_NODE_MAJOR}+ executable: ${toError(error).message}`);
101
122
  }
102
123
  }
124
+ const persisted = getConfiguredNodePath();
125
+ if (persisted) {
126
+ try {
127
+ resolvedNodeExecPath = validateNodeExecPath(normalizeExecutableCandidate(persisted));
128
+ return resolvedNodeExecPath;
129
+ }
130
+ catch {
131
+ // Persisted paths can point at removable Codex runtimes; continue with auto-discovery.
132
+ }
133
+ }
103
134
  const execName = basename(process.execPath).toLowerCase();
104
135
  const currentProcessLooksLikeNode = execName === "node" || execName === "node.exe";
105
136
  if (currentProcessLooksLikeNode) {
@@ -120,6 +151,18 @@ function getNodeExecPath() {
120
151
  }
121
152
  throw new Error(`Node ${MIN_NODE_MAJOR}+ is required for local pi-knowledge embeddings, but no usable node executable was found. Install Node ${MIN_NODE_MAJOR}+ or set PI_KNOWLEDGE_NODE_PATH to the full node.exe path.`);
122
153
  }
154
+ export function validateModelWorkerNodePath(nodePath) {
155
+ return validateNodeExecPath(normalizeExecutableCandidate(nodePath));
156
+ }
157
+ export function resolveModelWorkerNodePath() {
158
+ return getNodeExecPath();
159
+ }
160
+ export function configureModelWorkerNodePath(nodePath) {
161
+ const resolved = nodePath ? validateModelWorkerNodePath(nodePath) : getNodeExecPath();
162
+ writeRuntimeConfig({ node_path: resolved });
163
+ resolvedNodeExecPath = resolved;
164
+ return resolved;
165
+ }
123
166
  function appendWorkerStderr(current, chunk) {
124
167
  const next = `${current}${chunk.toString("utf-8")}`;
125
168
  return next.length > WORKER_STDERR_TAIL_CHARS ? next.slice(-WORKER_STDERR_TAIL_CHARS) : next;
@@ -0,0 +1,7 @@
1
+ export type RuntimeConfig = {
2
+ node_path?: string;
3
+ updated_at?: number;
4
+ };
5
+ export declare function readRuntimeConfig(knowledgeDir?: string): RuntimeConfig;
6
+ export declare function getConfiguredNodePath(): string | undefined;
7
+ export declare function writeRuntimeConfig(update: RuntimeConfig, knowledgeDir?: string): RuntimeConfig;
@@ -0,0 +1,36 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { getDefaultKnowledgeDir } from "./storage/sqlite.js";
4
+ const CONFIG_FILE = "config.json";
5
+ function runtimeConfigPath(knowledgeDir = getDefaultKnowledgeDir()) {
6
+ return join(knowledgeDir, CONFIG_FILE);
7
+ }
8
+ function isRuntimeConfig(value) {
9
+ if (typeof value !== "object" || value === null)
10
+ return false;
11
+ if ("node_path" in value && value.node_path !== undefined && typeof value.node_path !== "string")
12
+ return false;
13
+ return !("updated_at" in value) || value.updated_at === undefined || typeof value.updated_at === "number";
14
+ }
15
+ export function readRuntimeConfig(knowledgeDir = getDefaultKnowledgeDir()) {
16
+ const configPath = runtimeConfigPath(knowledgeDir);
17
+ if (!existsSync(configPath))
18
+ return {};
19
+ const parsed = JSON.parse(readFileSync(configPath, "utf8"));
20
+ if (!isRuntimeConfig(parsed))
21
+ throw new Error(`Invalid pi-knowledge runtime config: ${configPath}`);
22
+ return parsed;
23
+ }
24
+ export function getConfiguredNodePath() {
25
+ return readRuntimeConfig().node_path?.trim() || undefined;
26
+ }
27
+ export function writeRuntimeConfig(update, knowledgeDir = getDefaultKnowledgeDir()) {
28
+ mkdirSync(knowledgeDir, { recursive: true });
29
+ const existing = readRuntimeConfig(knowledgeDir);
30
+ const next = { ...existing, ...update, updated_at: Date.now() };
31
+ const configPath = runtimeConfigPath(knowledgeDir);
32
+ const tempPath = `${configPath}.${process.pid}.tmp`;
33
+ writeFileSync(tempPath, `${JSON.stringify(next, null, 2)}\n`);
34
+ renameSync(tempPath, configPath);
35
+ return next;
36
+ }
@@ -30,7 +30,7 @@ Default data storage is `~/.pi/knowledge` under Pi and `~/.omp/knowledge` under
30
30
  | `PI_KNOWLEDGE_EMBEDDING_IDLE_MS` | `30000` | Idle timer used only when native idle disposal coordination is enabled. Mainly for lifecycle stress tests. |
31
31
  | `PI_KNOWLEDGE_OFFLINE` | unset | Use with a pre-populated model cache for offline local model operation. See `docs/offline-mode.md`. |
32
32
 
33
- Local embeddings require a real Node 22+ executable for the isolated model worker. `pi-knowledge` first tries Node IPC and automatically falls back to a stdin/stdout JSONL worker transport when the host runtime does not expose `child_process.fork().send()`, which can happen in Windows OMP compatibility layers. On Windows it searches common Node, Volta, NVM, and `PATH` locations before failing. If worker startup still fails, set `PI_KNOWLEDGE_NODE_PATH` to the full `node.exe` path such as `C:\Program Files\nodejs\node.exe`; accidental surrounding quotes are ignored. OpenAI-compatible embeddings avoid the local worker entirely.
33
+ Local embeddings require a real Node 22+ executable for the isolated model worker. `pi-knowledge` first tries Node IPC and automatically falls back to a stdin/stdout JSONL worker transport when the host runtime does not expose `child_process.fork().send()`, which can happen in Windows OMP compatibility layers. On Windows it searches `PI_KNOWLEDGE_NODE_PATH`, persisted `knowledge_configure` settings, common Node, Volta, NVM, Codex `cua_node`, and `PATH` locations before failing. If worker startup still fails, call `knowledge_configure` with the full `node.exe` path such as `C:\Program Files\nodejs\node.exe`; accidental surrounding quotes are ignored. OpenAI-compatible embeddings avoid the local worker entirely.
34
34
 
35
35
  API embedding failures intentionally surface by default. Silent fallback can hide bad API keys, wrong base URLs, unsupported model names, or context-window errors and can produce a KB with a different embedding model than intended.
36
36
 
@@ -48,6 +48,8 @@ Search diagnostics include result provenance in both text output and structured
48
48
 
49
49
  `knowledge_doctor` emits both human-readable issues and machine-readable actions in structured `details`. Action codes include `run_update`, `rebuild_kb`, `wait_for_indexing`, `review_skipped_scope`, `rebuild_vectors`, `check_source`, and `none`. Agents should prefer these action codes over parsing the English action text.
50
50
 
51
+ `knowledge_configure` writes runtime configuration to the knowledge directory's `config.json`. It validates Node 22+ before persisting `node_path`, so agents can configure a Codex- or user-installed `node.exe` once without relying on environment variables being injected into an already-running OMP process.
52
+
51
53
  `knowledge_symbol_search` uses a lightweight declaration-pattern index stored in `knowledge.db`. It is rebuilt during `knowledge_add`, `knowledge_update`, and `knowledge_import`, and can find common code symbols, route-like handlers, Markdown headings, config keys, and environment variables. It is not a full LSP or code graph; for methods, uncommon syntax, or empty important lookups, use `knowledge_search` mode `fast`/`adaptive` and check `knowledge_doctor` for stale or missing symbol metadata. Older file/directory/URL KBs without symbol metadata should be updated before relying on symbol lookup. Imported portable KBs and inline text KBs do not retain an active source path; rebuild their symbols by re-importing or re-adding the content.
52
54
 
53
55
  ## Test and Release Fixtures
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-knowledge",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "description": "Local-first RAG knowledge base for Pi and OMP coding agents with hybrid code/doc search, reranking, diagnostics, and large-project indexing",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",