pi-knowledge 0.15.0 → 0.16.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/CHANGELOG.md +29 -0
- package/README.md +61 -23
- package/dist/index.d.ts +10 -4
- package/dist/index.js +145 -166
- package/dist/src/coverage-snapshot.d.ts +23 -0
- package/dist/src/coverage-snapshot.js +53 -0
- package/dist/src/daemon/client.d.ts +60 -0
- package/dist/src/daemon/client.js +360 -0
- package/dist/src/daemon/main.d.ts +2 -0
- package/dist/src/daemon/main.js +109 -0
- package/dist/src/daemon/protocol.d.ts +71 -0
- package/dist/src/daemon/protocol.js +170 -0
- package/dist/src/daemon/runtime.d.ts +26 -0
- package/dist/src/daemon/runtime.js +192 -0
- package/dist/src/daemon/server.d.ts +46 -0
- package/dist/src/daemon/server.js +500 -0
- package/dist/src/daemon/service.d.ts +49 -0
- package/dist/src/daemon/service.js +527 -0
- package/dist/src/diagnostics/health.d.ts +6 -0
- package/dist/src/diagnostics/health.js +135 -2
- package/dist/src/engine.d.ts +13 -8
- package/dist/src/engine.js +569 -100
- package/dist/src/filesystem-access.d.ts +9 -0
- package/dist/src/filesystem-access.js +100 -0
- package/dist/src/indexer/chunker.d.ts +12 -0
- package/dist/src/indexer/chunker.js +307 -9
- package/dist/src/mcp/http.d.ts +47 -0
- package/dist/src/mcp/http.js +564 -0
- package/dist/src/mcp/main.d.ts +2 -0
- package/dist/src/mcp/main.js +97 -0
- package/dist/src/mcp/protocol.d.ts +81 -0
- package/dist/src/mcp/protocol.js +444 -0
- package/dist/src/mcp/server.d.ts +42 -0
- package/dist/src/mcp/server.js +378 -0
- package/dist/src/model-worker-client.js +9 -0
- package/dist/src/model-worker-contract.d.ts +3 -0
- package/dist/src/model-worker-contract.js +8 -0
- package/dist/src/model-worker.js +76 -4
- package/dist/src/network/safe-fetch.d.ts +7 -0
- package/dist/src/network/safe-fetch.js +199 -0
- package/dist/src/node-runtime.d.ts +3 -0
- package/dist/src/node-runtime.js +78 -0
- package/dist/src/profiles.d.ts +15 -0
- package/dist/src/profiles.js +160 -0
- package/dist/src/runtime-config.js +5 -6
- package/dist/src/secure-files.d.ts +17 -0
- package/dist/src/secure-files.js +183 -0
- package/dist/src/status.js +12 -7
- package/dist/src/storage/sqlite.d.ts +4 -1
- package/dist/src/storage/sqlite.js +46 -3
- package/dist/src/type-guards.d.ts +1 -0
- package/dist/src/type-guards.js +3 -0
- package/dist/src/watcher/file-watcher.d.ts +3 -1
- package/dist/src/watcher/file-watcher.js +166 -32
- package/dist/src/windows-security.d.ts +4 -0
- package/dist/src/windows-security.js +67 -0
- package/docs/configuration.md +40 -9
- package/docs/daemon-profiles.md +302 -0
- package/docs/mcp-clients.md +266 -0
- package/docs/offline-mode.md +6 -6
- package/package.json +28 -2
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { lookup } from "node:dns/promises";
|
|
2
|
+
import { request as httpRequest } from "node:http";
|
|
3
|
+
import { request as httpsRequest } from "node:https";
|
|
4
|
+
import { isIP } from "node:net";
|
|
5
|
+
const DEFAULT_MAX_BYTES = 16 * 1024 * 1024;
|
|
6
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
7
|
+
const DEFAULT_MAX_REDIRECTS = 5;
|
|
8
|
+
function isPublicIpv4(address) {
|
|
9
|
+
const octets = address.split(".").map(Number);
|
|
10
|
+
if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
const [first = 0, second = 0, third = 0] = octets;
|
|
14
|
+
if (first === 0 || first === 10 || first === 127 || first >= 224)
|
|
15
|
+
return false;
|
|
16
|
+
if (first === 100 && second >= 64 && second <= 127)
|
|
17
|
+
return false;
|
|
18
|
+
if (first === 169 && second === 254)
|
|
19
|
+
return false;
|
|
20
|
+
if (first === 172 && second >= 16 && second <= 31)
|
|
21
|
+
return false;
|
|
22
|
+
if (first === 192 && (second === 0 || second === 168))
|
|
23
|
+
return false;
|
|
24
|
+
if (first === 198 && (second === 18 || second === 19 || (second === 51 && third === 100)))
|
|
25
|
+
return false;
|
|
26
|
+
if (first === 203 && second === 0 && third === 113)
|
|
27
|
+
return false;
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
function isPublicIpv6(address) {
|
|
31
|
+
const normalized = address.toLowerCase().split("%")[0] ?? "";
|
|
32
|
+
if (!normalized || normalized === "::" || normalized === "::1")
|
|
33
|
+
return false;
|
|
34
|
+
if (normalized.startsWith("::ffff:"))
|
|
35
|
+
return isPublicIpv4(normalized.slice("::ffff:".length));
|
|
36
|
+
const first = Number.parseInt(normalized.split(":")[0] ?? "", 16);
|
|
37
|
+
if (!Number.isInteger(first) || first < 0x2000 || first > 0x3fff)
|
|
38
|
+
return false;
|
|
39
|
+
if (normalized.startsWith("2001:0:") ||
|
|
40
|
+
normalized.startsWith("2001:2:") ||
|
|
41
|
+
normalized.startsWith("2001:10:") ||
|
|
42
|
+
normalized.startsWith("2001:db8:") ||
|
|
43
|
+
normalized.startsWith("2002:")) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
function assertPublicAddress(address) {
|
|
49
|
+
const family = isIP(address);
|
|
50
|
+
const allowed = family === 4 ? isPublicIpv4(address) : family === 6 ? isPublicIpv6(address) : false;
|
|
51
|
+
if (!allowed)
|
|
52
|
+
throw new Error(`URL host resolved to a non-public address: ${address}`);
|
|
53
|
+
}
|
|
54
|
+
function remainingTime(deadline) {
|
|
55
|
+
const remaining = deadline - Date.now();
|
|
56
|
+
if (remaining <= 0)
|
|
57
|
+
throw new Error("URL fetch timed out");
|
|
58
|
+
return remaining;
|
|
59
|
+
}
|
|
60
|
+
function withDeadline(operation, deadline, signal) {
|
|
61
|
+
if (signal?.aborted)
|
|
62
|
+
return Promise.reject(new Error("Cancelled"));
|
|
63
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
64
|
+
let settled = false;
|
|
65
|
+
const finish = (error, value) => {
|
|
66
|
+
if (settled)
|
|
67
|
+
return;
|
|
68
|
+
settled = true;
|
|
69
|
+
clearTimeout(timeout);
|
|
70
|
+
signal?.removeEventListener("abort", abort);
|
|
71
|
+
if (error)
|
|
72
|
+
reject(error);
|
|
73
|
+
else
|
|
74
|
+
resolve(value);
|
|
75
|
+
};
|
|
76
|
+
const abort = () => finish(new Error("Cancelled"));
|
|
77
|
+
const timeout = setTimeout(() => finish(new Error("URL fetch timed out")), remainingTime(deadline));
|
|
78
|
+
timeout.unref();
|
|
79
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
80
|
+
void operation.then((value) => finish(undefined, value), (error) => finish(error instanceof Error ? error : new Error(String(error))));
|
|
81
|
+
return promise;
|
|
82
|
+
}
|
|
83
|
+
async function resolvePublicAddress(hostname, deadline, signal) {
|
|
84
|
+
if (isIP(hostname)) {
|
|
85
|
+
assertPublicAddress(hostname);
|
|
86
|
+
return { address: hostname, family: isIP(hostname) };
|
|
87
|
+
}
|
|
88
|
+
const addresses = await withDeadline(lookup(hostname, { all: true, verbatim: true }), deadline, signal);
|
|
89
|
+
if (addresses.length === 0)
|
|
90
|
+
throw new Error(`URL host did not resolve: ${hostname}`);
|
|
91
|
+
for (const candidate of addresses)
|
|
92
|
+
assertPublicAddress(candidate.address);
|
|
93
|
+
const selected = addresses[0];
|
|
94
|
+
if (!selected || (selected.family !== 4 && selected.family !== 6)) {
|
|
95
|
+
throw new Error(`URL host did not resolve to IPv4 or IPv6: ${hostname}`);
|
|
96
|
+
}
|
|
97
|
+
return { address: selected.address, family: selected.family };
|
|
98
|
+
}
|
|
99
|
+
async function requestText(url, signal, maxBytes, deadline) {
|
|
100
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
101
|
+
throw new Error(`Unsupported URL protocol: ${url.protocol}`);
|
|
102
|
+
}
|
|
103
|
+
if (url.username || url.password)
|
|
104
|
+
throw new Error("URL credentials are not allowed");
|
|
105
|
+
if (signal?.aborted)
|
|
106
|
+
throw new Error("Cancelled");
|
|
107
|
+
const hostname = url.hostname.replace(/^\[|\]$/g, "");
|
|
108
|
+
const target = await resolvePublicAddress(hostname, deadline, signal);
|
|
109
|
+
if (signal?.aborted)
|
|
110
|
+
throw new Error("Cancelled");
|
|
111
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
112
|
+
let request;
|
|
113
|
+
let settled = false;
|
|
114
|
+
const finish = (error, result) => {
|
|
115
|
+
if (settled)
|
|
116
|
+
return;
|
|
117
|
+
settled = true;
|
|
118
|
+
clearTimeout(timeout);
|
|
119
|
+
signal?.removeEventListener("abort", abort);
|
|
120
|
+
if (error)
|
|
121
|
+
reject(error);
|
|
122
|
+
else
|
|
123
|
+
resolve(result);
|
|
124
|
+
};
|
|
125
|
+
const abort = () => {
|
|
126
|
+
request.destroy();
|
|
127
|
+
finish(new Error("Cancelled"));
|
|
128
|
+
};
|
|
129
|
+
const timeout = setTimeout(() => {
|
|
130
|
+
request.destroy();
|
|
131
|
+
finish(new Error("URL fetch timed out"));
|
|
132
|
+
}, remainingTime(deadline));
|
|
133
|
+
timeout.unref();
|
|
134
|
+
const transport = url.protocol === "https:" ? httpsRequest : httpRequest;
|
|
135
|
+
request = transport({
|
|
136
|
+
protocol: url.protocol,
|
|
137
|
+
hostname: target.address,
|
|
138
|
+
family: target.family,
|
|
139
|
+
port: url.port || undefined,
|
|
140
|
+
path: `${url.pathname}${url.search}`,
|
|
141
|
+
method: "GET",
|
|
142
|
+
headers: { Accept: "text/html, text/plain;q=0.9", Host: url.host },
|
|
143
|
+
servername: url.protocol === "https:" ? hostname : undefined,
|
|
144
|
+
}, (response) => {
|
|
145
|
+
response.once("error", (error) => finish(error));
|
|
146
|
+
const statusCode = response.statusCode ?? 0;
|
|
147
|
+
const location = response.headers.location;
|
|
148
|
+
if (statusCode >= 300 && statusCode < 400 && location) {
|
|
149
|
+
response.destroy();
|
|
150
|
+
finish(undefined, { location, body: "", bytes: 0 });
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (statusCode < 200 || statusCode >= 300) {
|
|
154
|
+
response.destroy();
|
|
155
|
+
finish(new Error(`Fetch failed: ${statusCode}`));
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const declaredLength = Number(response.headers["content-length"]);
|
|
159
|
+
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
|
|
160
|
+
response.destroy();
|
|
161
|
+
finish(new Error(`URL response exceeds ${maxBytes} bytes`));
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const chunks = [];
|
|
165
|
+
let bytes = 0;
|
|
166
|
+
response.on("data", (chunk) => {
|
|
167
|
+
bytes += chunk.length;
|
|
168
|
+
if (bytes > maxBytes) {
|
|
169
|
+
response.destroy();
|
|
170
|
+
finish(new Error(`URL response exceeds ${maxBytes} bytes`));
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
chunks.push(chunk);
|
|
174
|
+
});
|
|
175
|
+
response.once("end", () => finish(undefined, { body: Buffer.concat(chunks, bytes).toString("utf8"), bytes }));
|
|
176
|
+
});
|
|
177
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
178
|
+
request.once("error", (error) => finish(error));
|
|
179
|
+
request.end();
|
|
180
|
+
return promise;
|
|
181
|
+
}
|
|
182
|
+
export async function fetchPublicText(source, signal, options = {}) {
|
|
183
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
184
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
185
|
+
const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
|
|
186
|
+
const deadline = Date.now() + timeoutMs;
|
|
187
|
+
let remainingBytes = maxBytes;
|
|
188
|
+
let current = new URL(source);
|
|
189
|
+
for (let redirects = 0; redirects <= maxRedirects; redirects++) {
|
|
190
|
+
const response = await requestText(current, signal, remainingBytes, deadline);
|
|
191
|
+
remainingBytes -= response.bytes;
|
|
192
|
+
if (!response.location)
|
|
193
|
+
return response.body;
|
|
194
|
+
if (redirects === maxRedirects)
|
|
195
|
+
throw new Error(`URL exceeded ${maxRedirects} redirects`);
|
|
196
|
+
current = new URL(response.location, current);
|
|
197
|
+
}
|
|
198
|
+
throw new Error("URL redirect handling failed");
|
|
199
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { lstatSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, isAbsolute, parse } from "node:path";
|
|
4
|
+
import { readRuntimeConfig, writeRuntimeConfig } from "./runtime-config.js";
|
|
5
|
+
import { assertWindowsExecutableTrusted } from "./windows-security.js";
|
|
6
|
+
const MIN_NODE_MAJOR = 22;
|
|
7
|
+
function parseNodeMajor(version) {
|
|
8
|
+
const match = /^v?(?<major>\d+)\./.exec(version.trim());
|
|
9
|
+
if (!match?.groups?.major)
|
|
10
|
+
return undefined;
|
|
11
|
+
const major = Number(match.groups.major);
|
|
12
|
+
return Number.isInteger(major) ? major : undefined;
|
|
13
|
+
}
|
|
14
|
+
function assertTrustedExecutable(path) {
|
|
15
|
+
if (!isAbsolute(path))
|
|
16
|
+
throw new Error(`Daemon Node executable must be an absolute path: ${path}`);
|
|
17
|
+
const directInfo = lstatSync(path);
|
|
18
|
+
if (!directInfo.isFile() && !directInfo.isSymbolicLink()) {
|
|
19
|
+
throw new Error(`Daemon Node executable is not a file: ${path}`);
|
|
20
|
+
}
|
|
21
|
+
const canonical = realpathSync.native(path);
|
|
22
|
+
const info = statSync(canonical);
|
|
23
|
+
if (!info.isFile())
|
|
24
|
+
throw new Error(`Daemon Node executable is not a regular file: ${canonical}`);
|
|
25
|
+
if (process.platform === "win32") {
|
|
26
|
+
assertWindowsExecutableTrusted(canonical);
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
if (typeof process.getuid === "function" && info.uid !== process.getuid() && info.uid !== 0) {
|
|
30
|
+
throw new Error(`Daemon Node executable is not owned by the current user or root: ${canonical}`);
|
|
31
|
+
}
|
|
32
|
+
if ((info.mode & 0o022) !== 0) {
|
|
33
|
+
throw new Error(`Daemon Node executable must not be group/world writable: ${canonical}`);
|
|
34
|
+
}
|
|
35
|
+
const root = parse(canonical).root;
|
|
36
|
+
let parent = dirname(canonical);
|
|
37
|
+
while (parent !== root) {
|
|
38
|
+
const parentInfo = lstatSync(parent);
|
|
39
|
+
if (!parentInfo.isDirectory())
|
|
40
|
+
throw new Error(`Daemon Node parent is not a directory: ${parent}`);
|
|
41
|
+
if (typeof process.getuid === "function" && parentInfo.uid !== process.getuid() && parentInfo.uid !== 0) {
|
|
42
|
+
throw new Error(`Daemon Node parent is not owned by the current user or root: ${parent}`);
|
|
43
|
+
}
|
|
44
|
+
if ((parentInfo.mode & 0o022) !== 0) {
|
|
45
|
+
throw new Error(`Daemon Node parent must not be group/world writable: ${parent}`);
|
|
46
|
+
}
|
|
47
|
+
parent = dirname(parent);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const version = execFileSync(canonical, ["--version"], {
|
|
51
|
+
encoding: "utf8",
|
|
52
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
53
|
+
timeout: 5_000,
|
|
54
|
+
windowsHide: true,
|
|
55
|
+
}).trim();
|
|
56
|
+
const major = parseNodeMajor(version);
|
|
57
|
+
if (major === undefined || major < MIN_NODE_MAJOR) {
|
|
58
|
+
throw new Error(`Node ${MIN_NODE_MAJOR}+ is required for the profile daemon; ${canonical} reported ${version}`);
|
|
59
|
+
}
|
|
60
|
+
return canonical;
|
|
61
|
+
}
|
|
62
|
+
export function resolveDaemonNodePath(profile) {
|
|
63
|
+
const executableName = basename(process.execPath).toLowerCase();
|
|
64
|
+
if (executableName === "node" || executableName === "node.exe") {
|
|
65
|
+
const major = parseNodeMajor(process.version);
|
|
66
|
+
if (major !== undefined && major >= MIN_NODE_MAJOR)
|
|
67
|
+
return assertTrustedExecutable(process.execPath);
|
|
68
|
+
}
|
|
69
|
+
const persisted = readRuntimeConfig(profile.storageDir).node_path?.trim();
|
|
70
|
+
if (persisted)
|
|
71
|
+
return assertTrustedExecutable(persisted);
|
|
72
|
+
throw new Error(`No trusted Node ${MIN_NODE_MAJOR}+ runtime is configured for knowledge profile "${profile.name}". Call knowledge_configure with an explicit absolute node_path before starting the daemon.`);
|
|
73
|
+
}
|
|
74
|
+
export function configureDaemonNodePath(profile, nodePath) {
|
|
75
|
+
const configured = assertTrustedExecutable(nodePath.trim());
|
|
76
|
+
writeRuntimeConfig({ node_path: configured }, profile.storageDir);
|
|
77
|
+
return configured;
|
|
78
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface KnowledgeProfile {
|
|
2
|
+
name: string;
|
|
3
|
+
id: string;
|
|
4
|
+
storageDir: string;
|
|
5
|
+
runtimeDir: string;
|
|
6
|
+
profileRoot: string;
|
|
7
|
+
registryPath: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ResolveProfileOptions {
|
|
10
|
+
env?: NodeJS.ProcessEnv;
|
|
11
|
+
homeDir?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function selectedProfileName(env?: NodeJS.ProcessEnv): string;
|
|
14
|
+
export declare function resolveKnowledgeProfile(name?: string, options?: ResolveProfileOptions): KnowledgeProfile;
|
|
15
|
+
export declare function profileHasDatabase(profile: KnowledgeProfile): boolean;
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, lstatSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { ensureOwnerOnlyDirectory, ensurePrivateDirectory, readPrivateJson, writeJsonExclusive, } from "./secure-files.js";
|
|
6
|
+
const PROFILE_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
|
|
7
|
+
const WINDOWS_RESERVED_NAMES = {
|
|
8
|
+
con: true,
|
|
9
|
+
prn: true,
|
|
10
|
+
aux: true,
|
|
11
|
+
nul: true,
|
|
12
|
+
com1: true,
|
|
13
|
+
com2: true,
|
|
14
|
+
com3: true,
|
|
15
|
+
com4: true,
|
|
16
|
+
com5: true,
|
|
17
|
+
com6: true,
|
|
18
|
+
com7: true,
|
|
19
|
+
com8: true,
|
|
20
|
+
com9: true,
|
|
21
|
+
lpt1: true,
|
|
22
|
+
lpt2: true,
|
|
23
|
+
lpt3: true,
|
|
24
|
+
lpt4: true,
|
|
25
|
+
lpt5: true,
|
|
26
|
+
lpt6: true,
|
|
27
|
+
lpt7: true,
|
|
28
|
+
lpt8: true,
|
|
29
|
+
lpt9: true,
|
|
30
|
+
};
|
|
31
|
+
function profileHome(homeDir) {
|
|
32
|
+
return join(homeDir, ".pi-knowledge");
|
|
33
|
+
}
|
|
34
|
+
function profileRoot(env, homeDir) {
|
|
35
|
+
const configured = env.PI_KNOWLEDGE_PROFILE_ROOT?.trim();
|
|
36
|
+
return configured ? resolve(configured) : join(profileHome(homeDir), "profiles");
|
|
37
|
+
}
|
|
38
|
+
function registryPath(homeDir) {
|
|
39
|
+
return join(profileHome(homeDir), "profiles.json");
|
|
40
|
+
}
|
|
41
|
+
function assertProfileName(name) {
|
|
42
|
+
if (!PROFILE_NAME_PATTERN.test(name) || name !== name.toLowerCase() || name.endsWith(".") || name.endsWith(" ")) {
|
|
43
|
+
throw new Error(`Invalid knowledge profile name "${name}". Use 1-63 lowercase ASCII letters, digits, underscores, or hyphens.`);
|
|
44
|
+
}
|
|
45
|
+
const base = name.split(".")[0];
|
|
46
|
+
if (base && WINDOWS_RESERVED_NAMES[base]) {
|
|
47
|
+
throw new Error(`Invalid knowledge profile name "${name}": reserved device name`);
|
|
48
|
+
}
|
|
49
|
+
return name;
|
|
50
|
+
}
|
|
51
|
+
function isWithin(child, parent) {
|
|
52
|
+
const rel = relative(parent, child);
|
|
53
|
+
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
54
|
+
}
|
|
55
|
+
function assertNoCaseFoldCollision(root, canonicalName) {
|
|
56
|
+
const collision = readdirSync(root, { withFileTypes: true }).find((entry) => entry.name !== canonicalName && entry.name.toLowerCase() === canonicalName);
|
|
57
|
+
if (collision) {
|
|
58
|
+
throw new Error(`Knowledge profile "${canonicalName}" conflicts with existing case-variant entry "${collision.name}"`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function readRegistry(path) {
|
|
62
|
+
if (!existsSync(path))
|
|
63
|
+
return undefined;
|
|
64
|
+
const parsed = readPrivateJson(path, "knowledge profile registry");
|
|
65
|
+
if (typeof parsed !== "object" ||
|
|
66
|
+
parsed === null ||
|
|
67
|
+
!("schema_version" in parsed) ||
|
|
68
|
+
parsed.schema_version !== 1 ||
|
|
69
|
+
!("default_storage" in parsed) ||
|
|
70
|
+
typeof parsed.default_storage !== "string" ||
|
|
71
|
+
!isAbsolute(parsed.default_storage)) {
|
|
72
|
+
throw new Error(`Invalid knowledge profile registry: ${path}`);
|
|
73
|
+
}
|
|
74
|
+
return parsed;
|
|
75
|
+
}
|
|
76
|
+
function existingDatabaseCandidates(env, homeDir) {
|
|
77
|
+
const candidates = [];
|
|
78
|
+
const configuredAgentDir = env.PI_CODING_AGENT_DIR?.trim() || env.OMP_CODING_AGENT_DIR?.trim();
|
|
79
|
+
if (configuredAgentDir)
|
|
80
|
+
candidates.push(join(dirname(resolve(configuredAgentDir)), "knowledge"));
|
|
81
|
+
candidates.push(join(homeDir, ".pi", "knowledge"), join(homeDir, ".omp", "knowledge"));
|
|
82
|
+
const canonical = new Map();
|
|
83
|
+
for (const candidate of candidates) {
|
|
84
|
+
if (!existsSync(join(candidate, "knowledge.db")))
|
|
85
|
+
continue;
|
|
86
|
+
const resolved = realpathSync.native(candidate);
|
|
87
|
+
canonical.set(process.platform === "win32" ? resolved.toLowerCase() : resolved, resolved);
|
|
88
|
+
}
|
|
89
|
+
return [...canonical.values()];
|
|
90
|
+
}
|
|
91
|
+
function resolveDefaultStorage(env, homeDir, root, registry) {
|
|
92
|
+
const explicit = env.PI_KNOWLEDGE_DIR?.trim() || env.OMP_KNOWLEDGE_DIR?.trim();
|
|
93
|
+
if (explicit)
|
|
94
|
+
return ensureOwnerOnlyDirectory(resolve(explicit));
|
|
95
|
+
const persisted = readRegistry(registry);
|
|
96
|
+
if (persisted)
|
|
97
|
+
return ensureOwnerOnlyDirectory(persisted.default_storage);
|
|
98
|
+
const legacy = existingDatabaseCandidates(env, homeDir);
|
|
99
|
+
if (legacy.length > 1) {
|
|
100
|
+
throw new Error(`Multiple legacy knowledge databases were found (${legacy.join(", ")}). Set PI_KNOWLEDGE_DIR to choose the default profile storage explicitly.`);
|
|
101
|
+
}
|
|
102
|
+
if (legacy.length === 0)
|
|
103
|
+
assertNoCaseFoldCollision(root, "default");
|
|
104
|
+
const selected = legacy[0] ?? join(root, "default");
|
|
105
|
+
const canonical = ensureOwnerOnlyDirectory(selected);
|
|
106
|
+
const claimed = writeJsonExclusive(registry, {
|
|
107
|
+
schema_version: 1,
|
|
108
|
+
default_storage: canonical,
|
|
109
|
+
});
|
|
110
|
+
if (claimed)
|
|
111
|
+
return canonical;
|
|
112
|
+
const winner = readRegistry(registry);
|
|
113
|
+
if (!winner)
|
|
114
|
+
throw new Error(`Knowledge profile registry claim disappeared: ${registry}`);
|
|
115
|
+
return ensureOwnerOnlyDirectory(winner.default_storage);
|
|
116
|
+
}
|
|
117
|
+
export function selectedProfileName(env = process.env) {
|
|
118
|
+
return assertProfileName(env.PI_KNOWLEDGE_PROFILE?.trim() || "default");
|
|
119
|
+
}
|
|
120
|
+
export function resolveKnowledgeProfile(name = selectedProfileName(), options = {}) {
|
|
121
|
+
const env = options.env ?? process.env;
|
|
122
|
+
const homeDir = options.homeDir ?? homedir();
|
|
123
|
+
const canonicalName = assertProfileName(name);
|
|
124
|
+
const defaultRoot = ensurePrivateDirectory(join(profileHome(homeDir), "profiles"));
|
|
125
|
+
const root = canonicalName === "default" ? defaultRoot : ensurePrivateDirectory(profileRoot(env, homeDir));
|
|
126
|
+
const registry = registryPath(homeDir);
|
|
127
|
+
let storageDir;
|
|
128
|
+
if (canonicalName === "default") {
|
|
129
|
+
storageDir = resolveDefaultStorage(env, homeDir, root, registry);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
if (env.PI_KNOWLEDGE_DIR?.trim() || env.OMP_KNOWLEDGE_DIR?.trim()) {
|
|
133
|
+
throw new Error("PI_KNOWLEDGE_DIR/OMP_KNOWLEDGE_DIR can only override the default knowledge profile");
|
|
134
|
+
}
|
|
135
|
+
assertNoCaseFoldCollision(root, canonicalName);
|
|
136
|
+
const candidate = join(root, canonicalName);
|
|
137
|
+
if (existsSync(candidate) && lstatSync(candidate).isSymbolicLink()) {
|
|
138
|
+
throw new Error(`Named knowledge profile cannot be a symbolic link: ${candidate}`);
|
|
139
|
+
}
|
|
140
|
+
storageDir = ensureOwnerOnlyDirectory(candidate);
|
|
141
|
+
if (basename(storageDir) !== canonicalName) {
|
|
142
|
+
throw new Error(`Named knowledge profile does not round-trip to its canonical name: ${canonicalName}`);
|
|
143
|
+
}
|
|
144
|
+
if (!isWithin(storageDir, root)) {
|
|
145
|
+
throw new Error(`Named knowledge profile escapes the configured profile root: ${canonicalName}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const id = createHash("sha256").update(storageDir).digest("hex").slice(0, 24);
|
|
149
|
+
return {
|
|
150
|
+
name: canonicalName,
|
|
151
|
+
id,
|
|
152
|
+
storageDir,
|
|
153
|
+
runtimeDir: join(storageDir, ".runtime"),
|
|
154
|
+
profileRoot: root,
|
|
155
|
+
registryPath: registry,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
export function profileHasDatabase(profile) {
|
|
159
|
+
return (existsSync(join(profile.storageDir, "knowledge.db")) && statSync(join(profile.storageDir, "knowledge.db")).isFile());
|
|
160
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { existsSync
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { hardenPrivateFile, readPrivateJson, writeJsonAtomic } from "./secure-files.js";
|
|
3
4
|
import { getDefaultKnowledgeDir } from "./storage/sqlite.js";
|
|
4
5
|
const CONFIG_FILE = "config.json";
|
|
5
6
|
function runtimeConfigPath(knowledgeDir = getDefaultKnowledgeDir()) {
|
|
@@ -16,7 +17,8 @@ export function readRuntimeConfig(knowledgeDir = getDefaultKnowledgeDir()) {
|
|
|
16
17
|
const configPath = runtimeConfigPath(knowledgeDir);
|
|
17
18
|
if (!existsSync(configPath))
|
|
18
19
|
return {};
|
|
19
|
-
|
|
20
|
+
hardenPrivateFile(configPath, "pi-knowledge runtime config");
|
|
21
|
+
const parsed = readPrivateJson(configPath, "pi-knowledge runtime config");
|
|
20
22
|
if (!isRuntimeConfig(parsed))
|
|
21
23
|
throw new Error(`Invalid pi-knowledge runtime config: ${configPath}`);
|
|
22
24
|
return parsed;
|
|
@@ -25,12 +27,9 @@ export function getConfiguredNodePath() {
|
|
|
25
27
|
return readRuntimeConfig().node_path?.trim() || undefined;
|
|
26
28
|
}
|
|
27
29
|
export function writeRuntimeConfig(update, knowledgeDir = getDefaultKnowledgeDir()) {
|
|
28
|
-
mkdirSync(knowledgeDir, { recursive: true });
|
|
29
30
|
const existing = readRuntimeConfig(knowledgeDir);
|
|
30
31
|
const next = { ...existing, ...update, updated_at: Date.now() };
|
|
31
32
|
const configPath = runtimeConfigPath(knowledgeDir);
|
|
32
|
-
|
|
33
|
-
writeFileSync(tempPath, `${JSON.stringify(next, null, 2)}\n`);
|
|
34
|
-
renameSync(tempPath, configPath);
|
|
33
|
+
writeJsonAtomic(configPath, next);
|
|
35
34
|
return next;
|
|
36
35
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare function assertOwnedDirectory(path: string): void;
|
|
2
|
+
export declare function ensurePrivateDirectory(path: string): string;
|
|
3
|
+
export declare function ensureOwnerOnlyDirectory(path: string): string;
|
|
4
|
+
export declare function fsyncDirectory(path: string): void;
|
|
5
|
+
export interface SafeNewFile {
|
|
6
|
+
outputPath: string;
|
|
7
|
+
parentPath: string;
|
|
8
|
+
parentDevice: number;
|
|
9
|
+
parentInode: number;
|
|
10
|
+
tempPath: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function prepareSafeNewFile(path: string): SafeNewFile;
|
|
13
|
+
export declare function publishNewFile(tempPath: string, target: SafeNewFile): void;
|
|
14
|
+
export declare function hardenPrivateFile(path: string, label: string): void;
|
|
15
|
+
export declare function readPrivateJson(path: string, label: string): unknown;
|
|
16
|
+
export declare function writeJsonAtomic(path: string, value: unknown): void;
|
|
17
|
+
export declare function writeJsonExclusive(path: string, value: unknown): boolean;
|