@chatpanel/gateway 0.19.2 → 0.23.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/src/service.js CHANGED
@@ -1,28 +1,33 @@
1
- import u from"node:os";import o from"node:path";import{mkdirSync as f,writeFileSync as $,rmSync as g,existsSync as l}from"node:fs";import{spawnSync as A,spawn as b}from"node:child_process";const p="net.chatpanel.gateway",L="ChatPanel Privacy Gateway";function P(){const e=process.execPath,t=o.basename(e).toLowerCase();return(t.startsWith("node")||t.startsWith("bun"))&&process.argv[1]?{program:e,args:[o.resolve(process.argv[1])]}:{program:e,args:[]}}function C(){const e=o.join(u.homedir(),".chatpanel");return f(e,{recursive:!0}),{out:o.join(e,"gateway.log"),err:o.join(e,"gateway.err.log")}}function n(e,t,s={}){return A(e,t,{encoding:"utf8",...s})}const h=()=>o.join(u.homedir(),"Library","LaunchAgents",`${p}.plist`);function I(){const{program:e,args:t}=P(),{out:s,err:a}=C(),r=[e,...t].map(v=>` <string>${v}</string>`).join(`
2
- `),c=`<?xml version="1.0" encoding="UTF-8"?>
1
+ import u from"node:os";import o from"node:path";import{mkdirSync as f,writeFileSync as b,rmSync as g,existsSync as l}from"node:fs";import{spawnSync as C,spawn as x}from"node:child_process";const d="net.chatpanel.gateway",I="ChatPanel Privacy Gateway";function P(){const e=process.execPath,t=o.basename(e).toLowerCase();return(t.startsWith("node")||t.startsWith("bun"))&&process.argv[1]?{program:e,args:[o.resolve(process.argv[1])]}:{program:e,args:[]}}function N(){const e=o.join(u.homedir(),".chatpanel");return f(e,{recursive:!0}),{out:o.join(e,"gateway.log"),err:o.join(e,"gateway.err.log")}}function s(e,t,n={}){return C(e,t,{encoding:"utf8",...n})}const m=()=>o.join(u.homedir(),"Library","LaunchAgents",`${d}.plist`),_={MallocLargeCache:"0"};function R({program:e,args:t,out:n,err:c,env:r=_,label:a=d}={}){const i=p=>String(p).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),v=[e,...t].map(p=>` <string>${i(p)}</string>`).join(`
2
+ `),$=Object.entries(r).map(([p,L])=>` <key>${i(p)}</key><string>${i(L)}</string>`).join(`
3
+ `);return`<?xml version="1.0" encoding="UTF-8"?>
3
4
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
4
5
  <plist version="1.0">
5
6
  <dict>
6
- <key>Label</key><string>${p}</string>
7
+ <key>Label</key><string>${a}</string>
7
8
  <key>ProgramArguments</key>
8
9
  <array>
9
- ${r}
10
+ ${v}
10
11
  </array>
12
+ <key>EnvironmentVariables</key>
13
+ <dict>
14
+ ${$}
15
+ </dict>
11
16
  <key>RunAtLoad</key><true/>
12
17
  <key>KeepAlive</key><true/>
13
- <key>StandardOutPath</key><string>${s}</string>
14
- <key>StandardErrorPath</key><string>${a}</string>
18
+ <key>StandardOutPath</key><string>${i(n)}</string>
19
+ <key>StandardErrorPath</key><string>${i(c)}</string>
15
20
  </dict>
16
21
  </plist>
17
- `,i=h();f(o.dirname(i),{recursive:!0}),$(i,c),n("launchctl",["unload",i]);const d=n("launchctl",["load","-w",i]);if(d.status!==0)throw new Error((d.stderr||"").trim()||"launchctl load failed")}function N(){const e=h();n("launchctl",["unload","-w",e]),l(e)&&g(e)}function _(){return(n("launchctl",["list"]).stdout||"").includes(p)}const m="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",x="ChatPanelGateway",S=()=>o.join(u.homedir(),".chatpanel","gateway-launch.vbs");function k(){const e=`Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'chatpanel-gateway' -and $_.ProcessId -ne ${process.pid} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;n("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{timeout:15e3}),n("taskkill",["/IM","chatpanel-gateway.exe","/F"])}function Y(){if(process.platform==="win32")return k();process.platform==="darwin"?n("launchctl",["bootout",`gui/${process.getuid?.()??""}/${p}`]):n("systemctl",["--user","stop","chatpanel-gateway.service"]),n("pkill",["-f","chatpanel-gateway"])}function D(){const{program:e,args:t}=P(),s=[e,...t].map(c=>`""${c}""`).join(" "),a=S();f(o.dirname(a),{recursive:!0}),$(a,`CreateObject("WScript.Shell").Run "${s}", 0, False\r
18
- `);const r=n("reg",["add",m,"/v",x,"/t","REG_SZ","/d",`wscript.exe "${a}"`,"/f"]);if(r.status!==0)throw new Error((r.stderr||"").trim()||"reg add failed");k(),n("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),n("wscript.exe",[a])}function R(){n("reg",["delete",m,"/v",x,"/f"]),k()}function W(){return n("reg",["query",m,"/v",x]).status===0}const w=()=>o.join(u.homedir(),".config","systemd","user","chatpanel-gateway.service");function U(){const{program:e,args:t}=P(),s=[e,...t].map(i=>/\s/.test(i)?`"${i}"`:i).join(" "),a=`[Unit]
19
- Description=${L}
22
+ `}function D(){const{program:e,args:t}=P(),{out:n,err:c}=N(),r=R({program:e,args:t,out:n,err:c}),a=m();f(o.dirname(a),{recursive:!0}),b(a,r),s("launchctl",["unload",a]);const i=s("launchctl",["load","-w",a]);if(i.status!==0)throw new Error((i.stderr||"").trim()||"launchctl load failed")}function W(){const e=m();s("launchctl",["unload","-w",e]),l(e)&&g(e)}function U(){return(s("launchctl",["list"]).stdout||"").includes(d)}const h="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",S="ChatPanelGateway",k=()=>o.join(u.homedir(),".chatpanel","gateway-launch.vbs");function j(){const e=`Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -match 'chatpanel-gateway' -and $_.ProcessId -ne ${process.pid} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;s("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{timeout:15e3}),s("taskkill",["/IM","chatpanel-gateway.exe","/F"])}function z(){if(process.platform==="win32")return j();process.platform==="darwin"?s("launchctl",["bootout",`gui/${process.getuid?.()??""}/${d}`]):s("systemctl",["--user","stop","chatpanel-gateway.service"]),s("pkill",["-f","chatpanel-gateway"])}function O(){const{program:e,args:t}=P(),n=[e,...t].map(a=>`""${a}""`).join(" "),c=k();f(o.dirname(c),{recursive:!0}),b(c,`CreateObject("WScript.Shell").Run "${n}", 0, False\r
23
+ `);const r=s("reg",["add",h,"/v",S,"/t","REG_SZ","/d",`wscript.exe "${c}"`,"/f"]);if(r.status!==0)throw new Error((r.stderr||"").trim()||"reg add failed");j(),s("powershell.exe",["-NoProfile","-NonInteractive","-Command","Start-Sleep -Milliseconds 800"]),s("wscript.exe",[c])}function T(){s("reg",["delete",h,"/v",S,"/f"]),j()}function B(){return s("reg",["query",h,"/v",S]).status===0}const y=()=>o.join(u.homedir(),".config","systemd","user","chatpanel-gateway.service");function F(){const{program:e,args:t}=P(),n=[e,...t].map(i=>/\s/.test(i)?`"${i}"`:i).join(" "),c=`[Unit]
24
+ Description=${I}
20
25
  After=network.target
21
26
 
22
27
  [Service]
23
- ExecStart=${s}
28
+ ExecStart=${n}
24
29
  Restart=on-failure
25
30
 
26
31
  [Install]
27
32
  WantedBy=default.target
28
- `,r=w();f(o.dirname(r),{recursive:!0}),$(r,a),n("systemctl",["--user","daemon-reload"]);const c=n("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(c.status!==0)throw new Error((c.stderr||"").trim()||"systemctl enable failed")}function O(){n("systemctl",["--user","disable","--now","chatpanel-gateway"]);const e=w();l(e)&&g(e)}function B(){return(n("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function F({home:e=u.homedir(),platform:t=process.platform,env:s=process.env}={}){return t==="win32"?[o.join(s.LOCALAPPDATA||o.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[o.join(e,".local","bin","chatpanel-bridge")]}const E="net.chatpanel.bridge",j="ChatPanelBridge";function T({platform:e=process.platform,runImpl:t=n,paths:s=F(),home:a=u.homedir()}={}){if(e==="win32"){t("reg",["delete",m,"/v",j,"/f"]),t("schtasks",["/End","/TN",j]),t("schtasks",["/Delete","/TN",j,"/F"]);for(const r of s){const c=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",c],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${E}`]);const r=o.join(a,"Library","LaunchAgents",`${E}.plist`);l(r)&&g(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=o.join(a,".config","systemd","user","chatpanel-bridge.service");l(r)&&g(r,{force:!0})}for(const r of s)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function y(e,t,s){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return s();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function H({winInstall:e=""}={}){try{if(process.platform==="darwin")return l(h())?(b("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${p}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux")return l(w())?(b("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="win32"){const t=S();if(!l(t))return!1;const s=o.dirname(process.execPath),a=`timeout /t 3 >nul & ${e?`${e} & `:""}wscript.exe "${t}" & del /q "${o.join(s,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},c=Object.keys(r).find(i=>i.toLowerCase()==="path")||"Path";return r[c]=[s,...(r[c]||"").split(";").filter(Boolean)].filter((i,d,v)=>v.indexOf(i)===d).join(";"),b("cmd",["/c",a],{detached:!0,stdio:"ignore",windowsHide:!0,env:r}).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function V(){try{return y(()=>l(h()),()=>l(S()),()=>l(w()))}catch{return!1}}function Z(){return T(),y(I,D,U)}function z(){return y(N,R,O)}function J(){return y(_,W,B)}export{Z as installService,P as resolveLaunch,H as restartService,T as retireStandaloneBridge,V as serviceRegistered,J as serviceStatus,F as standaloneCandidates,Y as stopService,z as uninstallService};
33
+ `,r=y();f(o.dirname(r),{recursive:!0}),b(r,c),s("systemctl",["--user","daemon-reload"]);const a=s("systemctl",["--user","enable","--now","chatpanel-gateway"]);if(a.status!==0)throw new Error((a.stderr||"").trim()||"systemctl enable failed")}function G(){s("systemctl",["--user","disable","--now","chatpanel-gateway"]);const e=y();l(e)&&g(e)}function M(){return(s("systemctl",["--user","is-enabled","chatpanel-gateway"]).stdout||"").trim()==="enabled"}function K({home:e=u.homedir(),platform:t=process.platform,env:n=process.env}={}){return t==="win32"?[o.join(n.LOCALAPPDATA||o.join(e,"AppData","Local"),"ChatPanel","chatpanel-bridge.exe")]:[o.join(e,".local","bin","chatpanel-bridge")]}const A="net.chatpanel.bridge",E="ChatPanelBridge";function V({platform:e=process.platform,runImpl:t=s,paths:n=K(),home:c=u.homedir()}={}){if(e==="win32"){t("reg",["delete",h,"/v",E,"/f"]),t("schtasks",["/End","/TN",E]),t("schtasks",["/Delete","/TN",E,"/F"]);for(const r of n){const a=`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${r.replace(/'/g,"''")}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;t("powershell.exe",["-NoProfile","-NonInteractive","-Command",a],{timeout:15e3})}return}if(e==="darwin"){t("launchctl",["bootout",`gui/${process.getuid?.()??""}/${A}`]);const r=o.join(c,"Library","LaunchAgents",`${A}.plist`);l(r)&&g(r,{force:!0})}else{t("systemctl",["--user","disable","--now","chatpanel-bridge.service"]);const r=o.join(c,".config","systemd","user","chatpanel-bridge.service");l(r)&&g(r,{force:!0})}for(const r of n)t("pkill",["-f",`^${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(\\s|$)`])}function w(e,t,n){if(process.platform==="darwin")return e();if(process.platform==="win32")return t();if(process.platform==="linux")return n();throw new Error(`Auto-start isn't supported on ${process.platform} yet — run the gateway directly.`)}function J({winInstall:e=""}={}){try{if(process.platform==="darwin")return l(m())?(x("launchctl",["kickstart","-k",`gui/${process.getuid?.()??0}/${d}`],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="linux")return l(y())?(x("systemctl",["--user","restart","chatpanel-gateway"],{detached:!0,stdio:"ignore"}).unref(),!0):!1;if(process.platform==="win32"){const t=k();if(!l(t))return!1;const n=o.dirname(process.execPath),c=`timeout /t 3 >nul & ${e?`${e} & `:""}wscript.exe "${t}" & del /q "${o.join(n,"chatpanel-gateway.old-*.exe")}" >nul 2>&1`,r={...process.env},a=Object.keys(r).find(i=>i.toLowerCase()==="path")||"Path";return r[a]=[n,...(r[a]||"").split(";").filter(Boolean)].filter((i,v,$)=>$.indexOf(i)===v).join(";"),x("cmd",["/c",c],{detached:!0,stdio:"ignore",windowsHide:!0,env:r}).unref(),setTimeout(()=>process.exit(0),300),!0}}catch{}return!1}function Q(){try{return w(()=>l(m()),()=>l(k()),()=>l(y()))}catch{return!1}}function X(){return V(),w(D,O,F)}function ee(){return w(W,T,G)}function te(){return w(U,B,M)}export{_ as DARWIN_LAUNCH_ENV,X as installService,R as macPlistText,P as resolveLaunch,J as restartService,V as retireStandaloneBridge,Q as serviceRegistered,te as serviceStatus,K as standaloneCandidates,z as stopService,ee as uninstallService};
@@ -0,0 +1 @@
1
+ function c(n,{exit:t=e=>process.exit(e),graceMs:s=2e3}={}){let e=!1;const o=()=>{e||(e=!0,t(0))};n.close(o),n.closeIdleConnections?.(),setTimeout(()=>{n.closeAllConnections?.(),o()},s).unref()}export{c as closeAndExit};
@@ -0,0 +1,19 @@
1
+ const a="web_search",u='You can call web_search to look up current information from the web — prices, news, recent events, documentation, or anything time-sensitive or that may have changed since your training. Call it whenever the user asks about such things instead of guessing or saying you are unsure. Cite results inline as markdown links — e.g. ([1](https://…)) — never HTML, <sup>, or bare numbers, and finish with a "Sources" list of the links you used.',c=Object.freeze({name:a,annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},description:"Search the web and return ranked result snippets with their source URLs. Use this for current events, live prices/quotes, news, product/library docs, or any fact you are unsure about or that may have changed since training — prefer it over guessing.",parameters:{type:"object",properties:{query:{type:"string",description:"The search query — a few keywords work best."}},required:["query"],additionalProperties:!1}});function l(e){if(!e?.results?.length){const t=(e?.engines||[]).join(", ");return`No web results for "${e?.query||""}"`+(t?` (searched: ${t}).`:".")+" This may mean the engine blocked the request rather than that nothing exists — do NOT conclude the information is unavailable. Try a shorter, more general query (drop dates and qualifiers), and tell the user they can enable another search engine in ChatPanel settings if it keeps failing."}const r=Array.isArray(e.engines)?e.engines:[],o=e.results.map(t=>`[${t.rank}] [${t.title}](${t.url})`).join(`
2
+ `),s=e.results[0].url,n=`Web search results for "${e.query}" (engines: ${r.join(", ")}).
3
+
4
+ Citation rules: when a claim draws on a result below, cite it inline as a markdown link to that result's URL — e.g. ([1](${s})). Cite multiple sources as separate links: ([1](url)) ([3](url)). Do NOT output HTML, <sup>, or bare bracket numbers like [1] — every citation must be a clickable markdown link. Finish with a "Sources" section that repeats, as markdown links, each source you cited.
5
+
6
+ Sources:
7
+ ${o}`,i=e.results.map(t=>`### [${t.rank}] ${t.title}
8
+ <${t.url}>
9
+
10
+ ${t.text}`).join(`
11
+
12
+ ---
13
+
14
+ `);return`${n}
15
+
16
+ ---
17
+ Result details:
18
+
19
+ ${i}`}function h({search:e}={}){if(typeof e!="function")throw new Error("webSearchToolProvider: search required");return{specs:[c],system:u,async execute(r,o){if(r!==a)return JSON.stringify({error:`Unknown tool: ${r}`});const s=String(o?.query||"").trim();if(!s)return"No query provided to web_search.";try{const n=await e(s),i=(n?.engines||[]).join(", ");return{text:l(n),note:i?`ChatPanel · ${i}`:"ChatPanel"}}catch(n){return`web_search failed: ${n?.message||n}`}}}}export{c as WEB_SEARCH_SPEC,a as WEB_SEARCH_TOOL_NAME,u as WEB_SEARCH_TOOL_SYSTEM,l as searchResultsToText,h as webSearchToolProvider};