@chatpanel/gateway 0.6.110 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -4
- package/bin/chatpanel-gateway-bin.mjs +1 -24
- package/bin/chatpanel-gateway.js +3 -97
- package/package.json +1 -7
- package/src/access-log-store.js +1 -45
- package/src/agent.js +2 -256
- package/src/anthropic.js +3 -83
- package/src/backup-decrypt.js +1 -45
- package/src/backup-ingest.js +6 -120
- package/src/bridge-supervisor.js +3 -212
- package/src/bridge.js +4 -252
- package/src/budget.js +1 -117
- package/src/config.js +1 -209
- package/src/configstore.js +1 -181
- package/src/connect-agents.js +22 -179
- package/src/diarize-engine.js +1 -188
- package/src/egress.js +2 -0
- package/src/engine-ledger-store.js +1 -150
- package/src/engine.js +1 -132
- package/src/entitlement-refresh.js +1 -84
- package/src/entitlement.js +1 -76
- package/src/extraction.js +4 -294
- package/src/freegate.js +1 -47
- package/src/gate.js +1 -75
- package/src/gateway-token.js +1 -60
- package/src/history-store.js +1 -251
- package/src/job.js +3 -148
- package/src/knowledge.js +3 -215
- package/src/local-status.js +6 -102
- package/src/log.js +1 -21
- package/src/mcp-cli.js +19 -113
- package/src/mcp.js +34 -546
- package/src/memory-store.js +1 -176
- package/src/memory.js +2 -642
- package/src/model-integrity.js +1 -82
- package/src/model-ledger.js +1 -229
- package/src/model-runtime.js +1 -37
- package/src/models.js +1 -92
- package/src/ner-engine.js +1 -318
- package/src/ner.js +1 -113
- package/src/observability.js +1 -123
- package/src/openai.js +2 -84
- package/src/ort.js +1 -52
- package/src/parakeet-engine.js +2 -228
- package/src/pocket-tts-engine.js +1 -520
- package/src/prefs-store.js +1 -149
- package/src/project-store.js +1 -139
- package/src/project.js +1 -171
- package/src/recruit.js +3 -424
- package/src/recruiting.js +1 -93
- package/src/redact.js +2 -123
- package/src/responses.js +2 -80
- package/src/router.js +1 -292
- package/src/rrf.js +1 -93
- package/src/scorecard-store.js +1 -92
- package/src/scorecard.js +1 -336
- package/src/search-index.js +2 -134
- package/src/secure-fetch.js +1 -58
- package/src/sentencepiece.js +1 -184
- package/src/server.js +10 -2296
- package/src/service.js +11 -189
- package/src/shape.js +5 -121
- package/src/sqlite-store.js +3 -212
- package/src/stream.js +5 -182
- package/src/structured.js +4 -902
- package/src/stt-engine.js +1 -486
- package/src/stt-models.js +1 -144
- package/src/subject-kinds.js +1 -6
- package/src/subject-name.js +1 -97
- package/src/team-board.js +6 -338
- package/src/team-record.js +1 -226
- package/src/team-store.js +1 -261
- package/src/team.js +1 -303
- package/src/toolrelay.js +3 -122
- package/src/tts-engine.js +1 -453
- package/src/tts-models.js +1 -254
- package/src/tts-remote.js +1 -109
- package/src/tts-voice-resolve.js +1 -78
- package/src/tts-voices.js +1 -192
- package/src/update.js +1 -305
package/src/service.js
CHANGED
|
@@ -1,206 +1,28 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
//
|
|
4
|
-
// chatpanel-gateway --install register login auto-start + start now
|
|
5
|
-
// chatpanel-gateway --uninstall remove it
|
|
6
|
-
// chatpanel-gateway --status is it registered?
|
|
7
|
-
//
|
|
8
|
-
// macOS → LaunchAgent · Windows → HKCU Run (hidden VBS) · Linux → systemd user.
|
|
9
|
-
|
|
10
|
-
import os from 'node:os';
|
|
11
|
-
import path from 'node:path';
|
|
12
|
-
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
|
|
13
|
-
import { spawnSync, spawn } from 'node:child_process';
|
|
14
|
-
|
|
15
|
-
const LABEL = 'net.chatpanel.gateway';
|
|
16
|
-
const DISPLAY = 'ChatPanel Privacy Gateway';
|
|
17
|
-
|
|
18
|
-
// The command that launches THIS gateway. A compiled single-file binary launches
|
|
19
|
-
// itself; running under node launches the interpreter + the bin entry.
|
|
20
|
-
export function resolveLaunch() {
|
|
21
|
-
const exe = process.execPath;
|
|
22
|
-
const base = path.basename(exe).toLowerCase();
|
|
23
|
-
const underInterpreter = base.startsWith('node') || base.startsWith('bun');
|
|
24
|
-
if (underInterpreter && process.argv[1]) {
|
|
25
|
-
return { program: exe, args: [path.resolve(process.argv[1])] };
|
|
26
|
-
}
|
|
27
|
-
return { program: exe, args: [] };
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function logPaths() {
|
|
31
|
-
const dir = path.join(os.homedir(), '.chatpanel');
|
|
32
|
-
mkdirSync(dir, { recursive: true });
|
|
33
|
-
return { out: path.join(dir, 'gateway.log'), err: path.join(dir, 'gateway.err.log') };
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function run(cmd, args, opts = {}) {
|
|
37
|
-
return spawnSync(cmd, args, { encoding: 'utf8', ...opts });
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// ---------------------------------------------------------------- macOS
|
|
41
|
-
const macPlist = () => path.join(os.homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
|
|
42
|
-
|
|
43
|
-
function macInstall() {
|
|
44
|
-
const { program, args } = resolveLaunch();
|
|
45
|
-
const { out, err } = logPaths();
|
|
46
|
-
const progArgs = [program, ...args].map((a) => ` <string>${a}</string>`).join('\n');
|
|
47
|
-
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
|
1
|
+
import p from"node:os";import n from"node:path";import{mkdirSync as d,writeFileSync as w,rmSync as k,existsSync as i}from"node:fs";import{spawnSync as I,spawn as y}from"node:child_process";const u="net.chatpanel.gateway",E="ChatPanel Privacy Gateway";function h(){const t=process.execPath,r=n.basename(t).toLowerCase();return(r.startsWith("node")||r.startsWith("bun"))&&process.argv[1]?{program:t,args:[n.resolve(process.argv[1])]}:{program:t,args:[]}}function j(){const t=n.join(p.homedir(),".chatpanel");return d(t,{recursive:!0}),{out:n.join(t,"gateway.log"),err:n.join(t,"gateway.err.log")}}function e(t,r,s={}){return I(t,r,{encoding:"utf8",...s})}const f=()=>n.join(p.homedir(),"Library","LaunchAgents",`${u}.plist`);function L(){const{program:t,args:r}=h(),{out:s,err:a}=j(),c=[t,...r].map(b=>` <string>${b}</string>`).join(`
|
|
2
|
+
`),l=`<?xml version="1.0" encoding="UTF-8"?>
|
|
48
3
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
49
4
|
<plist version="1.0">
|
|
50
5
|
<dict>
|
|
51
|
-
<key>Label</key><string>${
|
|
6
|
+
<key>Label</key><string>${u}</string>
|
|
52
7
|
<key>ProgramArguments</key>
|
|
53
8
|
<array>
|
|
54
|
-
${
|
|
9
|
+
${c}
|
|
55
10
|
</array>
|
|
56
11
|
<key>RunAtLoad</key><true/>
|
|
57
12
|
<key>KeepAlive</key><true/>
|
|
58
|
-
<key>StandardOutPath</key><string>${
|
|
59
|
-
<key>StandardErrorPath</key><string>${
|
|
13
|
+
<key>StandardOutPath</key><string>${s}</string>
|
|
14
|
+
<key>StandardErrorPath</key><string>${a}</string>
|
|
60
15
|
</dict>
|
|
61
16
|
</plist>
|
|
62
|
-
`;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
writeFileSync(p, plist);
|
|
66
|
-
run('launchctl', ['unload', p]);
|
|
67
|
-
const r = run('launchctl', ['load', '-w', p]);
|
|
68
|
-
if (r.status !== 0) throw new Error((r.stderr || '').trim() || 'launchctl load failed');
|
|
69
|
-
}
|
|
70
|
-
function macUninstall() {
|
|
71
|
-
const p = macPlist();
|
|
72
|
-
run('launchctl', ['unload', '-w', p]);
|
|
73
|
-
if (existsSync(p)) rmSync(p);
|
|
74
|
-
}
|
|
75
|
-
function macStatus() {
|
|
76
|
-
return (run('launchctl', ['list']).stdout || '').includes(LABEL);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// ---------------------------------------------------------------- Windows
|
|
80
|
-
const WIN_RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
|
|
81
|
-
const WIN_RUN_NAME = 'ChatPanelGateway';
|
|
82
|
-
const winVbs = () => path.join(os.homedir(), '.chatpanel', 'gateway-launch.vbs');
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Stop every running gateway process — the exe, the npm build under node, and the embedded
|
|
86
|
-
* bridge child (`--bridge`) — except this one. Matched on the command line, because on the
|
|
87
|
-
* npm path the process is `node.exe` and `taskkill /IM chatpanel-gateway.exe` never saw it.
|
|
88
|
-
* launchd restarts the macOS service for us; Windows has no supervisor, so `--install` after an
|
|
89
|
-
* update used to launch a second instance that died on the busy port while the OLD build kept
|
|
90
|
-
* answering /health with its old version.
|
|
91
|
-
*/
|
|
92
|
-
function winStopRunning() {
|
|
93
|
-
const ps = `Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'chatpanel-gateway' -and $_.ProcessId -ne ${process.pid} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;
|
|
94
|
-
run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', ps], { timeout: 15000 });
|
|
95
|
-
run('taskkill', ['/IM', 'chatpanel-gateway.exe', '/F']); // belt and braces for the exe
|
|
96
|
-
}
|
|
97
|
-
/** Stop the running gateway (and its bridge child) on any platform — what an update needs first. */
|
|
98
|
-
export function stopService() {
|
|
99
|
-
if (process.platform === 'win32') return winStopRunning();
|
|
100
|
-
if (process.platform === 'darwin') { run('launchctl', ['bootout', `gui/${process.getuid?.() ?? ''}/${LABEL}`]); }
|
|
101
|
-
else run('systemctl', ['--user', 'stop', 'chatpanel-gateway.service']);
|
|
102
|
-
run('pkill', ['-f', 'chatpanel-gateway']);
|
|
103
|
-
return undefined;
|
|
104
|
-
}
|
|
105
|
-
function winInstall() {
|
|
106
|
-
const { program, args } = resolveLaunch();
|
|
107
|
-
const parts = [program, ...args].map((p) => `""${p}""`).join(' ');
|
|
108
|
-
const vbs = winVbs();
|
|
109
|
-
mkdirSync(path.dirname(vbs), { recursive: true });
|
|
110
|
-
writeFileSync(vbs, `CreateObject("WScript.Shell").Run "${parts}", 0, False\r\n`);
|
|
111
|
-
const r = run('reg', ['add', WIN_RUN_KEY, '/v', WIN_RUN_NAME, '/t', 'REG_SZ', '/d', `wscript.exe "${vbs}"`, '/f']);
|
|
112
|
-
if (r.status !== 0) throw new Error((r.stderr || '').trim() || 'reg add failed');
|
|
113
|
-
winStopRunning();
|
|
114
|
-
// Give the port a moment to be released before the new instance binds it.
|
|
115
|
-
run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', 'Start-Sleep -Milliseconds 800']);
|
|
116
|
-
run('wscript.exe', [vbs]);
|
|
117
|
-
}
|
|
118
|
-
function winUninstall() {
|
|
119
|
-
run('reg', ['delete', WIN_RUN_KEY, '/v', WIN_RUN_NAME, '/f']);
|
|
120
|
-
winStopRunning();
|
|
121
|
-
}
|
|
122
|
-
function winStatus() {
|
|
123
|
-
return run('reg', ['query', WIN_RUN_KEY, '/v', WIN_RUN_NAME]).status === 0;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// ---------------------------------------------------------------- Linux (systemd user)
|
|
127
|
-
const linUnit = () => path.join(os.homedir(), '.config', 'systemd', 'user', 'chatpanel-gateway.service');
|
|
128
|
-
|
|
129
|
-
function linInstall() {
|
|
130
|
-
const { program, args } = resolveLaunch();
|
|
131
|
-
const exec = [program, ...args].map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(' ');
|
|
132
|
-
const unit = `[Unit]
|
|
133
|
-
Description=${DISPLAY}
|
|
17
|
+
`,o=f();d(n.dirname(o),{recursive:!0}),w(o,l),e("launchctl",["unload",o]);const P=e("launchctl",["load","-w",o]);if(P.status!==0)throw new Error((P.stderr||"").trim()||"launchctl load failed")}function A(){const t=f();e("launchctl",["unload","-w",t]),i(t)&&k(t)}function C(){return(e("launchctl",["list"]).stdout||"").includes(u)}const v="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",S="ChatPanelGateway",$=()=>n.join(p.homedir(),".chatpanel","gateway-launch.vbs");function x(){const t=`Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'chatpanel-gateway' -and $_.ProcessId -ne ${process.pid} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;e("powershell.exe",["-NoProfile","-NonInteractive","-Command",t],{timeout:15e3}),e("taskkill",["/IM","chatpanel-gateway.exe","/F"])}function M(){if(process.platform==="win32")return x();process.platform==="darwin"?e("launchctl",["bootout",`gui/${process.getuid?.()??""}/${u}`]):e("systemctl",["--user","stop","chatpanel-gateway.service"]),e("pkill",["-f","chatpanel-gateway"])}function N(){const{program:t,args:r}=h(),s=[t,...r].map(l=>`""${l}""`).join(" "),a=$();d(n.dirname(a),{recursive:!0}),w(a,`CreateObject("WScript.Shell").Run "${s}", 0, False\r
|
|
18
|
+
`);const c=e("reg",["add",v,"/v",S,"/t","REG_SZ","/d",`wscript.exe "${a}"`,"/f"]);if(c.status!==0)throw new Error((c.stderr||"").trim()||"reg add failed");x(),e("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),e("wscript.exe",[a])}function U(){e("reg",["delete",v,"/v",S,"/f"]),x()}function R(){return e("reg",["query",v,"/v",S]).status===0}const m=()=>n.join(p.homedir(),".config","systemd","user","chatpanel-gateway.service");function W(){const{program:t,args:r}=h(),s=[t,...r].map(o=>/\s/.test(o)?`"${o}"`:o).join(" "),a=`[Unit]
|
|
19
|
+
Description=${E}
|
|
134
20
|
After=network.target
|
|
135
21
|
|
|
136
22
|
[Service]
|
|
137
|
-
ExecStart=${
|
|
23
|
+
ExecStart=${s}
|
|
138
24
|
Restart=on-failure
|
|
139
25
|
|
|
140
26
|
[Install]
|
|
141
27
|
WantedBy=default.target
|
|
142
|
-
`;
|
|
143
|
-
const p = linUnit();
|
|
144
|
-
mkdirSync(path.dirname(p), { recursive: true });
|
|
145
|
-
writeFileSync(p, unit);
|
|
146
|
-
run('systemctl', ['--user', 'daemon-reload']);
|
|
147
|
-
const r = run('systemctl', ['--user', 'enable', '--now', 'chatpanel-gateway']);
|
|
148
|
-
if (r.status !== 0) throw new Error((r.stderr || '').trim() || 'systemctl enable failed');
|
|
149
|
-
}
|
|
150
|
-
function linUninstall() {
|
|
151
|
-
run('systemctl', ['--user', 'disable', '--now', 'chatpanel-gateway']);
|
|
152
|
-
const p = linUnit();
|
|
153
|
-
if (existsSync(p)) rmSync(p);
|
|
154
|
-
}
|
|
155
|
-
function linStatus() {
|
|
156
|
-
return (run('systemctl', ['--user', 'is-enabled', 'chatpanel-gateway']).stdout || '').trim() === 'enabled';
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// ---------------------------------------------------------------- dispatch
|
|
160
|
-
function byPlatform(mac, win, lin) {
|
|
161
|
-
if (process.platform === 'darwin') return mac();
|
|
162
|
-
if (process.platform === 'win32') return win();
|
|
163
|
-
if (process.platform === 'linux') return lin();
|
|
164
|
-
throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`);
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
/**
|
|
168
|
-
* Relaunch the registered service into whatever is now installed (src/update.js). Returns
|
|
169
|
-
* `false` when this gateway is not run by a service it can restart — the caller then says
|
|
170
|
-
* "installed; start it again yourself" rather than exiting into nothing.
|
|
171
|
-
*
|
|
172
|
-
* macOS / Linux: the service manager stops this process and starts the new one. Windows has
|
|
173
|
-
* no supervisor: a detached helper waits for THIS process to exit (freeing the port and the
|
|
174
|
-
* onnxruntime DLL npm cannot overwrite while it is loaded), optionally runs the npm install
|
|
175
|
-
* that had to wait for that, relaunches through the registered VBS, and cleans up a renamed
|
|
176
|
-
* .exe. The caller exits after spawning it.
|
|
177
|
-
*/
|
|
178
|
-
export function restartService({ winInstall: winInstallCmd = '' } = {}) {
|
|
179
|
-
try {
|
|
180
|
-
if (process.platform === 'darwin') {
|
|
181
|
-
if (!existsSync(macPlist())) return false;
|
|
182
|
-
spawn('launchctl', ['kickstart', '-k', `gui/${process.getuid?.() ?? 0}/${LABEL}`], { detached: true, stdio: 'ignore' }).unref();
|
|
183
|
-
return true;
|
|
184
|
-
}
|
|
185
|
-
if (process.platform === 'linux') {
|
|
186
|
-
if (!existsSync(linUnit())) return false;
|
|
187
|
-
spawn('systemctl', ['--user', 'restart', 'chatpanel-gateway'], { detached: true, stdio: 'ignore' }).unref();
|
|
188
|
-
return true;
|
|
189
|
-
}
|
|
190
|
-
if (process.platform === 'win32') {
|
|
191
|
-
const vbs = winVbs();
|
|
192
|
-
if (!existsSync(vbs)) return false;
|
|
193
|
-
const dir = path.dirname(process.execPath);
|
|
194
|
-
const cmd = `timeout /t 3 >nul & ${winInstallCmd ? `${winInstallCmd} & ` : ''}wscript.exe "${vbs}" & del /q "${path.join(dir, 'chatpanel-gateway.old-*.exe')}" >nul 2>&1`;
|
|
195
|
-
spawn('cmd', ['/c', cmd], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
|
|
196
|
-
setTimeout(() => process.exit(0), 300);
|
|
197
|
-
return true;
|
|
198
|
-
}
|
|
199
|
-
} catch { /* fall through */ }
|
|
200
|
-
return false;
|
|
201
|
-
}
|
|
202
|
-
export function serviceRegistered() { try { return byPlatform(() => existsSync(macPlist()), () => existsSync(winVbs()), () => existsSync(linUnit())); } catch { return false; } }
|
|
203
|
-
|
|
204
|
-
export function installService() { return byPlatform(macInstall, winInstall, linInstall); }
|
|
205
|
-
export function uninstallService() { return byPlatform(macUninstall, winUninstall, linUninstall); }
|
|
206
|
-
export function serviceStatus() { return byPlatform(macStatus, winStatus, linStatus); }
|
|
28
|
+
`,c=m();d(n.dirname(c),{recursive:!0}),w(c,a),e("systemctl",["--user","daemon-reload"]);const l=e("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(l.status!==0)throw new Error((l.stderr||"").trim()||"systemctl enable failed")}function _(){e("systemctl",["--user","disable","--now","chatpanel-gateway"]);const t=m();i(t)&&k(t)}function D(){return(e("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function g(t,r,s){if(process.platform==="darwin")return t();if(process.platform==="win32")return r();if(process.platform==="linux")return s();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function B({winInstall:t=""}={}){try{if(process.platform==="darwin")return i(f())?(y("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${u}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux")return i(m())?(y("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="win32"){const r=$();if(!i(r))return!1;const s=n.dirname(process.execPath),a=`timeout /t 3 >nul & ${t?`${t} & `:""}wscript.exe "${r}" & del /q "${n.join(s,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`;return y("cmd",["/c",a],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function K(){try{return g(()=>i(f()),()=>i($()),()=>i(m()))}catch{return!1}}function Y(){return g(L,N,W)}function q(){return g(A,U,_)}function H(){return g(C,R,D)}export{Y as installService,h as resolveLaunch,B as restartService,K as serviceRegistered,H as serviceStatus,M as stopService,q as uninstallService};
|
package/src/shape.js
CHANGED
|
@@ -1,124 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
// non-streaming body and an SSE event sequence. Used only by the bridge backend,
|
|
3
|
-
// where the gateway synthesizes the provider response itself.
|
|
4
|
-
//
|
|
5
|
-
// Each shaper exposes:
|
|
6
|
-
// contentType 'application/json' | 'text/event-stream'
|
|
7
|
-
// full(text) -> string non-streaming JSON body
|
|
8
|
-
// sseHead() -> string opening SSE events (may be '')
|
|
9
|
-
// sseDelta(text) -> string one chunk of text
|
|
10
|
-
// sseTail() -> string closing SSE events
|
|
1
|
+
function r(e){return`${e}_${Date.now().toString(36)}${Math.random().toString(36).slice(2,10)}`}const c=()=>Math.floor(Date.now()/1e3),a=e=>`data: ${JSON.stringify(e)}
|
|
11
2
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
return `${prefix}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
|
|
15
|
-
}
|
|
16
|
-
const now = () => Math.floor(Date.now() / 1000);
|
|
17
|
-
const sse = (obj) => `data: ${JSON.stringify(obj)}\n\n`;
|
|
18
|
-
const event = (name, obj) => `event: ${name}\n` + sse(obj);
|
|
3
|
+
`,s=(e,t)=>`event: ${e}
|
|
4
|
+
`+a(t);function l(e){const t=r("chatcmpl"),n={id:t,object:"chat.completion.chunk",created:c(),model:e};return{contentType:"application/json",full(o){return JSON.stringify({id:t,object:"chat.completion",created:c(),model:e,choices:[{index:0,message:{role:"assistant",content:o},finish_reason:"stop"}],usage:{}})},sseHead(){return a({...n,choices:[{index:0,delta:{role:"assistant"},finish_reason:null}]})},sseDelta(o){return a({...n,choices:[{index:0,delta:{content:o},finish_reason:null}]})},sseTail(){return a({...n,choices:[{index:0,delta:{},finish_reason:"stop"}]})+`data: [DONE]
|
|
19
5
|
|
|
20
|
-
|
|
21
|
-
const rid = id('chatcmpl');
|
|
22
|
-
const base = { id: rid, object: 'chat.completion.chunk', created: now(), model };
|
|
23
|
-
return {
|
|
24
|
-
contentType: 'application/json',
|
|
25
|
-
full(text) {
|
|
26
|
-
return JSON.stringify({
|
|
27
|
-
id: rid, object: 'chat.completion', created: now(), model,
|
|
28
|
-
choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }],
|
|
29
|
-
usage: {},
|
|
30
|
-
});
|
|
31
|
-
},
|
|
32
|
-
sseHead() {
|
|
33
|
-
return sse({ ...base, choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] });
|
|
34
|
-
},
|
|
35
|
-
sseDelta(text) {
|
|
36
|
-
return sse({ ...base, choices: [{ index: 0, delta: { content: text }, finish_reason: null }] });
|
|
37
|
-
},
|
|
38
|
-
sseTail() {
|
|
39
|
-
return sse({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }) + 'data: [DONE]\n\n';
|
|
40
|
-
},
|
|
41
|
-
/**
|
|
42
|
-
* What the agent is DOING, on a chunk an OpenAI client ignores.
|
|
43
|
-
*
|
|
44
|
-
* The chunk is well-formed and carries an empty delta, so a strict client sees a frame
|
|
45
|
-
* with nothing in it and moves on — which is what makes this additive rather than a
|
|
46
|
-
* change to the wire contract. A ChatPanel client reads the extra `chatpanel` key.
|
|
47
|
-
*
|
|
48
|
-
* This exists because an agent spends its first ten seconds reading files, and a client
|
|
49
|
-
* routed through the gateway had no way to know that while one talking to the bridge
|
|
50
|
-
* directly did. A protocol gap that rewards going around the redacting proxy is a
|
|
51
|
-
* security problem wearing a UI problem's clothes.
|
|
52
|
-
*/
|
|
53
|
-
sseActivity(evt) {
|
|
54
|
-
return sse({
|
|
55
|
-
...base,
|
|
56
|
-
choices: [{ index: 0, delta: {}, finish_reason: null }],
|
|
57
|
-
chatpanel: { kind: 'activity', event: evt },
|
|
58
|
-
});
|
|
59
|
-
},
|
|
60
|
-
// Tool-relay (agent destinations): emit the agent's tool call as an OpenAI
|
|
61
|
-
// tool_calls delta, then end the turn with finish_reason:tool_calls.
|
|
62
|
-
sseToolCalls(calls) {
|
|
63
|
-
return sse({ ...base, choices: [{ index: 0, delta: { tool_calls: calls.map((c, i) => ({ index: i, id: c.id, type: 'function', function: { name: c.name, arguments: c.arguments } })) }, finish_reason: null }] });
|
|
64
|
-
},
|
|
65
|
-
sseToolFinish() {
|
|
66
|
-
return sse({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] }) + 'data: [DONE]\n\n';
|
|
67
|
-
},
|
|
68
|
-
};
|
|
69
|
-
}
|
|
6
|
+
`},sseActivity(o){return a({...n,choices:[{index:0,delta:{},finish_reason:null}],chatpanel:{kind:"activity",event:o}})},sseToolCalls(o){return a({...n,choices:[{index:0,delta:{tool_calls:o.map((i,p)=>({index:p,id:i.id,type:"function",function:{name:i.name,arguments:i.arguments}}))},finish_reason:null}]})},sseToolFinish(){return a({...n,choices:[{index:0,delta:{},finish_reason:"tool_calls"}]})+`data: [DONE]
|
|
70
7
|
|
|
71
|
-
|
|
72
|
-
const rid = id('resp');
|
|
73
|
-
return {
|
|
74
|
-
contentType: 'application/json',
|
|
75
|
-
full(text) {
|
|
76
|
-
return JSON.stringify({
|
|
77
|
-
id: rid, object: 'response', created_at: now(), model, status: 'completed',
|
|
78
|
-
output: [{ id: id('msg'), type: 'message', role: 'assistant', content: [{ type: 'output_text', text }] }],
|
|
79
|
-
output_text: text,
|
|
80
|
-
});
|
|
81
|
-
},
|
|
82
|
-
sseHead() {
|
|
83
|
-
return event('response.created', { type: 'response.created', response: { id: rid, status: 'in_progress', model } });
|
|
84
|
-
},
|
|
85
|
-
sseDelta(text) {
|
|
86
|
-
return event('response.output_text.delta', { type: 'response.output_text.delta', delta: text });
|
|
87
|
-
},
|
|
88
|
-
sseTail() {
|
|
89
|
-
return event('response.completed', { type: 'response.completed', response: { id: rid, status: 'completed', model } });
|
|
90
|
-
},
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
export function anthropicMessages(model) {
|
|
95
|
-
const rid = id('msg');
|
|
96
|
-
return {
|
|
97
|
-
contentType: 'application/json',
|
|
98
|
-
full(text) {
|
|
99
|
-
return JSON.stringify({
|
|
100
|
-
id: rid, type: 'message', role: 'assistant', model,
|
|
101
|
-
content: [{ type: 'text', text }], stop_reason: 'end_turn', stop_sequence: null, usage: {},
|
|
102
|
-
});
|
|
103
|
-
},
|
|
104
|
-
sseHead() {
|
|
105
|
-
return event('message_start', { type: 'message_start', message: { id: rid, type: 'message', role: 'assistant', model, content: [], stop_reason: null, usage: {} } })
|
|
106
|
-
+ event('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } });
|
|
107
|
-
},
|
|
108
|
-
sseDelta(text) {
|
|
109
|
-
return event('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } });
|
|
110
|
-
},
|
|
111
|
-
sseTail() {
|
|
112
|
-
return event('content_block_stop', { type: 'content_block_stop', index: 0 })
|
|
113
|
-
+ event('message_delta', { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: {} })
|
|
114
|
-
+ event('message_stop', { type: 'message_stop' });
|
|
115
|
-
},
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// Pick a shaper for a parsed request + its adapter name.
|
|
120
|
-
export function shaperFor(kind, model) {
|
|
121
|
-
if (kind === 'anthropic') return anthropicMessages(model);
|
|
122
|
-
if (kind === 'responses') return openaiResponses(model);
|
|
123
|
-
return openaiChat(model);
|
|
124
|
-
}
|
|
8
|
+
`}}}function u(e){const t=r("resp");return{contentType:"application/json",full(n){return JSON.stringify({id:t,object:"response",created_at:c(),model:e,status:"completed",output:[{id:r("msg"),type:"message",role:"assistant",content:[{type:"output_text",text:n}]}],output_text:n})},sseHead(){return s("response.created",{type:"response.created",response:{id:t,status:"in_progress",model:e}})},sseDelta(n){return s("response.output_text.delta",{type:"response.output_text.delta",delta:n})},sseTail(){return s("response.completed",{type:"response.completed",response:{id:t,status:"completed",model:e}})}}}function d(e){const t=r("msg");return{contentType:"application/json",full(n){return JSON.stringify({id:t,type:"message",role:"assistant",model:e,content:[{type:"text",text:n}],stop_reason:"end_turn",stop_sequence:null,usage:{}})},sseHead(){return s("message_start",{type:"message_start",message:{id:t,type:"message",role:"assistant",model:e,content:[],stop_reason:null,usage:{}}})+s("content_block_start",{type:"content_block_start",index:0,content_block:{type:"text",text:""}})},sseDelta(n){return s("content_block_delta",{type:"content_block_delta",index:0,delta:{type:"text_delta",text:n}})},sseTail(){return s("content_block_stop",{type:"content_block_stop",index:0})+s("message_delta",{type:"message_delta",delta:{stop_reason:"end_turn"},usage:{}})+s("message_stop",{type:"message_stop"})}}}function _(e,t){return e==="anthropic"?d(t):e==="responses"?u(t):l(t)}export{d as anthropicMessages,l as openaiChat,u as openaiResponses,_ as shaperFor};
|
package/src/sqlite-store.js
CHANGED
|
@@ -1,215 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
// as history-store.js's HistoryStore). SQLite is memory-mapped, so a year of
|
|
3
|
-
// chats/meetings is searchable without loading the whole corpus into RAM, with
|
|
4
|
-
// battle-tested BM25 full-text search and O(1) record lookups.
|
|
5
|
-
//
|
|
6
|
-
// Dual runtime: the npm gateway runs on Node (node:sqlite, built in since 22); the
|
|
7
|
-
// standalone binary is compiled with Bun (bun:sqlite). Both ship FTS5. The
|
|
8
|
-
// specifier is computed so neither bundler tries to resolve the other runtime's
|
|
9
|
-
// module. createHistoryStore() falls back to the encrypted-JSON HistoryStore if
|
|
10
|
-
// SQLite can't load at all, so this can never break a gateway.
|
|
11
|
-
//
|
|
12
|
-
// AT REST: a local .db file (0600) under ~/.chatpanel, protected by OS disk
|
|
13
|
-
// encryption — the on-device warm tier. Zero-knowledge encryption is the COLD/cloud
|
|
14
|
-
// tier's job, not this one. The backup passphrase (a credential) stays encrypted
|
|
15
|
-
// via history-store.js's saveBackupSecret.
|
|
16
|
-
|
|
17
|
-
import { join } from 'node:path';
|
|
18
|
-
import { mkdirSync, chmodSync, existsSync, statSync } from 'node:fs';
|
|
19
|
-
import os from 'node:os';
|
|
20
|
-
import { HistoryStore } from './history-store.js';
|
|
21
|
-
|
|
22
|
-
const DIR = join(os.homedir(), '.chatpanel');
|
|
23
|
-
const DB_PATH = process.env.CHATPANEL_HISTORY_DB || join(DIR, 'history.db');
|
|
24
|
-
|
|
25
|
-
// Silence node:sqlite's one-time "experimental" warning for a clean CLI; pass
|
|
26
|
-
// every other warning through untouched.
|
|
27
|
-
if (typeof Bun === 'undefined') {
|
|
28
|
-
const emit = process.emitWarning.bind(process);
|
|
29
|
-
process.emitWarning = (w, ...a) => (typeof w === 'string' && w.includes('SQLite is an experimental') ? undefined : emit(w, ...a));
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// Normalize node:sqlite (DatabaseSync) and bun:sqlite (Database) to one tiny API.
|
|
33
|
-
async function openDb(path) {
|
|
34
|
-
if (typeof Bun !== 'undefined') {
|
|
35
|
-
const { Database } = await import('bun:sqlite');
|
|
36
|
-
const db = new Database(path, { create: true });
|
|
37
|
-
return {
|
|
38
|
-
exec: (sql) => db.run(sql),
|
|
39
|
-
run: (sql, p = []) => db.prepare(sql).run(...p),
|
|
40
|
-
all: (sql, p = []) => db.query(sql).all(...p),
|
|
41
|
-
get: (sql, p = []) => db.query(sql).get(...p),
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
const spec = 'node' + ':sqlite'; // computed so the Bun bundler won't touch it
|
|
45
|
-
const { DatabaseSync } = await import(spec);
|
|
46
|
-
const db = new DatabaseSync(path);
|
|
47
|
-
return {
|
|
48
|
-
exec: (sql) => db.exec(sql),
|
|
49
|
-
run: (sql, p = []) => db.prepare(sql).run(...p),
|
|
50
|
-
all: (sql, p = []) => db.prepare(sql).all(...p),
|
|
51
|
-
get: (sql, p = []) => db.prepare(sql).get(...p),
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// query text → a safe FTS5 MATCH string. Each term is quoted (so FTS5 operators in
|
|
56
|
-
// user text can't inject), joined with OR for recall — bm25 handles the ranking.
|
|
57
|
-
function ftsMatch(query) {
|
|
58
|
-
const terms = String(query || '').toLowerCase().match(/[a-z0-9][a-z0-9'_+-]*/g);
|
|
59
|
-
if (!terms || !terms.length) return null;
|
|
60
|
-
return terms.map((t) => `"${t.replace(/"/g, '""')}"`).join(' OR ');
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export class SqliteHistoryStore {
|
|
64
|
-
constructor({ path = DB_PATH } = {}) {
|
|
65
|
-
this.path = path;
|
|
66
|
-
this.db = null;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
async init() {
|
|
70
|
-
if (this.path !== ':memory:') {
|
|
71
|
-
mkdirSync(DIR, { recursive: true, mode: 0o700 });
|
|
72
|
-
try { chmodSync(DIR, 0o700); } catch { /* non-POSIX */ }
|
|
73
|
-
}
|
|
74
|
-
this.db = await openDb(this.path);
|
|
75
|
-
this.db.exec('PRAGMA journal_mode=WAL');
|
|
76
|
-
this.db.exec('CREATE TABLE IF NOT EXISTS records(id TEXT PRIMARY KEY, title TEXT, type TEXT, date INTEGER, chars INTEGER)');
|
|
77
|
-
this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(id UNINDEXED, title, text, tokenize='unicode61')");
|
|
78
|
-
if (this.path !== ':memory:') {
|
|
79
|
-
for (const path of [this.path, this.path + '-wal', this.path + '-shm']) {
|
|
80
|
-
try { if (existsSync(path)) chmodSync(path, 0o600); } catch { /* best effort */ }
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
return this;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Kept for interface-compatibility with HistoryStore (SQLite is already loaded).
|
|
87
|
-
load() {
|
|
88
|
-
return this;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
get size() {
|
|
92
|
-
return this.db.get('SELECT COUNT(*) c FROM records')?.c || 0;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// Freshness horizon — the newest record's timestamp. The MCP tools surface this so
|
|
96
|
-
// an agent knows how current the warm copy is (and stops denying un-synced items).
|
|
97
|
-
get newest() {
|
|
98
|
-
return this.db.get('SELECT MAX(date) m FROM records')?.m || 0;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// On-disk footprint for the storage dashboard: the .db plus its WAL/shm sidecars.
|
|
102
|
-
get bytes() {
|
|
103
|
-
if (this.path === ':memory:') return 0;
|
|
104
|
-
let total = 0;
|
|
105
|
-
for (const p of [this.path, `${this.path}-wal`, `${this.path}-shm`]) {
|
|
106
|
-
try { if (existsSync(p)) total += statSync(p).size; } catch { /* ignore */ }
|
|
107
|
-
}
|
|
108
|
-
return total;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
bulk({ upserts = [], removes = [] } = {}) {
|
|
112
|
-
this.db.exec('BEGIN');
|
|
113
|
-
try {
|
|
114
|
-
for (const id of removes) {
|
|
115
|
-
this.db.run('DELETE FROM records WHERE id = ?', [id]);
|
|
116
|
-
this.db.run('DELETE FROM fts WHERE id = ?', [id]);
|
|
117
|
-
}
|
|
118
|
-
for (const d of upserts) {
|
|
119
|
-
if (!d || !d.id) continue;
|
|
120
|
-
const text = String(d.text || '');
|
|
121
|
-
this.db.run('DELETE FROM fts WHERE id = ?', [d.id]); // FTS5 has no UPSERT on UNINDEXED id
|
|
122
|
-
this.db.run('INSERT INTO fts(id, title, text) VALUES(?, ?, ?)', [d.id, d.title || '', text]);
|
|
123
|
-
this.db.run('INSERT OR REPLACE INTO records(id, title, type, date, chars) VALUES(?, ?, ?, ?, ?)', [d.id, d.title || '', d.type || '', d.date || 0, text.length]);
|
|
124
|
-
}
|
|
125
|
-
this.db.exec('COMMIT');
|
|
126
|
-
} catch (e) {
|
|
127
|
-
this.db.exec('ROLLBACK');
|
|
128
|
-
throw e;
|
|
129
|
-
}
|
|
130
|
-
return this.size;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// [{ id, score, title, type, date, snippet }] — score higher = better (bm25 is negated).
|
|
134
|
-
// Filters: type (chat|meeting|note), since/before (epoch ms bounds), offset (paging).
|
|
135
|
-
// `snippet` returns the matching excerpt from the transcript/body so a caller can rank and
|
|
136
|
-
// decide what to fetch WITHOUT pulling full bodies — the token-management path.
|
|
137
|
-
search(query, { limit = 10, offset = 0, type = null, since = null, before = null } = {}) {
|
|
138
|
-
const match = ftsMatch(query);
|
|
139
|
-
if (!match) return [];
|
|
140
|
-
const where = ['fts MATCH ?'];
|
|
141
|
-
const params = [match];
|
|
142
|
-
if (type) { where.push('r.type = ?'); params.push(String(type)); }
|
|
143
|
-
if (since != null) { where.push('r.date >= ?'); params.push(Number(since)); }
|
|
144
|
-
if (before != null) { where.push('r.date <= ?'); params.push(Number(before)); }
|
|
145
|
-
params.push(limit, offset);
|
|
146
|
-
const rows = this.db.all(
|
|
147
|
-
`SELECT r.id id, r.title title, r.type type, r.date date, bm25(fts) b,
|
|
1
|
+
import{join as E}from"node:path";import{mkdirSync as T,chmodSync as u,existsSync as p,statSync as b}from"node:fs";import m from"node:os";import{HistoryStore as R}from"./history-store.js";const h=E(m.homedir(),".chatpanel"),y=process.env.CHATPANEL_HISTORY_DB||E(h,"history.db");if(typeof Bun>"u"){const c=process.emitWarning.bind(process);process.emitWarning=(e,...s)=>typeof e=="string"&&e.includes("SQLite is an experimental")?void 0:c(e,...s)}async function S(c){if(typeof Bun<"u"){const{Database:r}=await import("bun:sqlite"),n=new r(c,{create:!0});return{exec:o=>n.run(o),run:(o,i=[])=>n.prepare(o).run(...i),all:(o,i=[])=>n.query(o).all(...i),get:(o,i=[])=>n.query(o).get(...i)}}const e="node:sqlite",{DatabaseSync:s}=await import(e),t=new s(c);return{exec:r=>t.exec(r),run:(r,n=[])=>t.prepare(r).run(...n),all:(r,n=[])=>t.prepare(r).all(...n),get:(r,n=[])=>t.prepare(r).get(...n)}}function f(c){const e=String(c||"").toLowerCase().match(/[a-z0-9][a-z0-9'_+-]*/g);return!e||!e.length?null:e.map(s=>`"${s.replace(/"/g,'""')}"`).join(" OR ")}class O{constructor({path:e=y}={}){this.path=e,this.db=null}async init(){if(this.path!==":memory:"){T(h,{recursive:!0,mode:448});try{u(h,448)}catch{}}if(this.db=await S(this.path),this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("CREATE TABLE IF NOT EXISTS records(id TEXT PRIMARY KEY, title TEXT, type TEXT, date INTEGER, chars INTEGER)"),this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(id UNINDEXED, title, text, tokenize='unicode61')"),this.path!==":memory:")for(const e of[this.path,this.path+"-wal",this.path+"-shm"])try{p(e)&&u(e,384)}catch{}return this}load(){return this}get size(){return this.db.get("SELECT COUNT(*) c FROM records")?.c||0}get newest(){return this.db.get("SELECT MAX(date) m FROM records")?.m||0}get bytes(){if(this.path===":memory:")return 0;let e=0;for(const s of[this.path,`${this.path}-wal`,`${this.path}-shm`])try{p(s)&&(e+=b(s).size)}catch{}return e}bulk({upserts:e=[],removes:s=[]}={}){this.db.exec("BEGIN");try{for(const t of s)this.db.run("DELETE FROM records WHERE id = ?",[t]),this.db.run("DELETE FROM fts WHERE id = ?",[t]);for(const t of e){if(!t||!t.id)continue;const r=String(t.text||"");this.db.run("DELETE FROM fts WHERE id = ?",[t.id]),this.db.run("INSERT INTO fts(id, title, text) VALUES(?, ?, ?)",[t.id,t.title||"",r]),this.db.run("INSERT OR REPLACE INTO records(id, title, type, date, chars) VALUES(?, ?, ?, ?, ?)",[t.id,t.title||"",t.type||"",t.date||0,r.length])}this.db.exec("COMMIT")}catch(t){throw this.db.exec("ROLLBACK"),t}return this.size}search(e,{limit:s=10,offset:t=0,type:r=null,since:n=null,before:o=null}={}){const i=f(e);if(!i)return[];const a=["fts MATCH ?"],l=[i];return r&&(a.push("r.type = ?"),l.push(String(r))),n!=null&&(a.push("r.date >= ?"),l.push(Number(n))),o!=null&&(a.push("r.date <= ?"),l.push(Number(o))),l.push(s,t),this.db.all(`SELECT r.id id, r.title title, r.type type, r.date date, bm25(fts) b,
|
|
148
2
|
snippet(fts, 2, '«', '»', ' … ', 12) snip
|
|
149
3
|
FROM fts JOIN records r ON r.id = fts.id
|
|
150
|
-
WHERE ${
|
|
151
|
-
params,
|
|
152
|
-
);
|
|
153
|
-
return rows.map((r) => ({ id: r.id, score: -r.b, title: r.title, type: r.type, date: r.date, snippet: r.snip || '' }));
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// Graph navigation — records most connected to a given one, by shared content. "More like
|
|
157
|
-
// this": build a MATCH from the record's title + a sample of its body, rank by bm25, drop
|
|
158
|
-
// self. Cheap and index-only; no embeddings needed for a first-class "related" primitive.
|
|
159
|
-
related(id, { limit = 5 } = {}) {
|
|
160
|
-
const rec = this.get(id);
|
|
161
|
-
if (!rec) return [];
|
|
162
|
-
const terms = ftsMatch(`${rec.title || ''} ${String(rec.text || '').slice(0, 2000)}`);
|
|
163
|
-
if (!terms) return [];
|
|
164
|
-
// Cap the OR-set so a long transcript doesn't build a giant MATCH.
|
|
165
|
-
const capped = terms.split(' OR ').slice(0, 40).join(' OR ');
|
|
166
|
-
const rows = this.db.all(
|
|
167
|
-
`SELECT r.id id, r.title title, r.type type, r.date date, bm25(fts) b
|
|
4
|
+
WHERE ${a.join(" AND ")} ORDER BY b LIMIT ? OFFSET ?`,l).map(d=>({id:d.id,score:-d.b,title:d.title,type:d.type,date:d.date,snippet:d.snip||""}))}related(e,{limit:s=5}={}){const t=this.get(e);if(!t)return[];const r=f(`${t.title||""} ${String(t.text||"").slice(0,2e3)}`);if(!r)return[];const n=r.split(" OR ").slice(0,40).join(" OR ");return this.db.all(`SELECT r.id id, r.title title, r.type type, r.date date, bm25(fts) b
|
|
168
5
|
FROM fts JOIN records r ON r.id = fts.id
|
|
169
|
-
WHERE fts MATCH ? AND r.id != ? ORDER BY b LIMIT ?`,
|
|
170
|
-
[capped, id, limit],
|
|
171
|
-
);
|
|
172
|
-
return rows.map((r) => ({ id: r.id, score: -r.b, title: r.title, type: r.type, date: r.date }));
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
// `type` is additive: list_briefs is "list, of type brief", not a second index.
|
|
176
|
-
list({ limit = 50, offset = 0, type = null } = {}) {
|
|
177
|
-
const where = type ? ' WHERE type = ?' : '';
|
|
178
|
-
const params = type ? [String(type)] : [];
|
|
179
|
-
const total = this.db.get(`SELECT COUNT(*) c FROM records${where}`, params)?.c || 0;
|
|
180
|
-
const items = this.db.all(`SELECT id, title, type, date, chars FROM records${where} ORDER BY date DESC LIMIT ? OFFSET ?`, [...params, limit, offset]);
|
|
181
|
-
return { total, items };
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// Paged fetch for token management: maxChars caps the returned slice, offset pages a long
|
|
185
|
-
// transcript. Reports totalChars + truncated so a caller knows there is more to fetch.
|
|
186
|
-
get(id, { maxChars = null, offset = 0 } = {}) {
|
|
187
|
-
const meta = this.db.get('SELECT id, title, type, date FROM records WHERE id = ?', [id]);
|
|
188
|
-
if (!meta) return null;
|
|
189
|
-
const body = this.db.get('SELECT text FROM fts WHERE id = ?', [id]);
|
|
190
|
-
const full = body?.text || '';
|
|
191
|
-
let text = offset ? full.slice(offset) : full;
|
|
192
|
-
let truncated = false;
|
|
193
|
-
if (maxChars && text.length > maxChars) { text = text.slice(0, maxChars); truncated = true; }
|
|
194
|
-
return { ...meta, text, totalChars: full.length, offset: Number(offset) || 0, truncated };
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
// Wipe every record — the user purging the on-disk warm copy. Returns how many were dropped.
|
|
198
|
-
clear() {
|
|
199
|
-
const n = this.size;
|
|
200
|
-
this.db.exec('DELETE FROM records');
|
|
201
|
-
this.db.exec('DELETE FROM fts');
|
|
202
|
-
return n;
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// Pick the best available warm engine. SQLite when it loads; otherwise the
|
|
207
|
-
// encrypted-JSON HistoryStore — so a gateway is never left without a warm store.
|
|
208
|
-
export async function createHistoryStore(opts = {}) {
|
|
209
|
-
try {
|
|
210
|
-
return await new SqliteHistoryStore(opts).init();
|
|
211
|
-
} catch (e) {
|
|
212
|
-
console.log(`[warm] SQLite unavailable (${e.message}); using the encrypted file store`);
|
|
213
|
-
return new HistoryStore(opts).load();
|
|
214
|
-
}
|
|
215
|
-
}
|
|
6
|
+
WHERE fts MATCH ? AND r.id != ? ORDER BY b LIMIT ?`,[n,e,s]).map(i=>({id:i.id,score:-i.b,title:i.title,type:i.type,date:i.date}))}list({limit:e=50,offset:s=0,type:t=null}={}){const r=t?" WHERE type = ?":"",n=t?[String(t)]:[],o=this.db.get(`SELECT COUNT(*) c FROM records${r}`,n)?.c||0,i=this.db.all(`SELECT id, title, type, date, chars FROM records${r} ORDER BY date DESC LIMIT ? OFFSET ?`,[...n,e,s]);return{total:o,items:i}}get(e,{maxChars:s=null,offset:t=0}={}){const r=this.db.get("SELECT id, title, type, date FROM records WHERE id = ?",[e]);if(!r)return null;const o=this.db.get("SELECT text FROM fts WHERE id = ?",[e])?.text||"";let i=t?o.slice(t):o,a=!1;return s&&i.length>s&&(i=i.slice(0,s),a=!0),{...r,text:i,totalChars:o.length,offset:Number(t)||0,truncated:a}}clear(){const e=this.size;return this.db.exec("DELETE FROM records"),this.db.exec("DELETE FROM fts"),e}}async function x(c={}){try{return await new O(c).init()}catch(e){return console.log(`[warm] SQLite unavailable (${e.message}); using the encrypted file store`),new R(c).load()}}export{O as SqliteHistoryStore,x as createHistoryStore};
|