@chatpanel/gateway 0.117.0 → 0.119.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/package.json +2 -2
- package/src/apple-notes.js +1 -0
- package/src/diarize-engine.js +1 -1
- package/src/indic-engine.js +1 -1
- package/src/link-host.js +1 -1
- package/src/lossless-store.js +4 -4
- package/src/model-hashes.json +105 -1
- package/src/model-integrity.js +1 -1
- package/src/model-sources.js +1 -1
- package/src/parakeet-engine.js +2 -2
- package/src/segment-engine.js +1 -1
- package/src/server.js +26 -26
- package/src/stt-engine.js +1 -1
- package/src/stt-models.js +1 -1
- package/src/translate-engine.js +1 -1
- package/src/tts-engine.js +1 -1
- package/src/tts-models.js +1 -1
- package/src/vad-engine.js +1 -1
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.119.0",
|
|
4
4
|
"description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
26
26
|
"@chatpanel/bridge": "^0.47.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.392.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.0",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{execFile as _}from"node:child_process";let l=null;async function d(){return l||=import("@chatpanel/events/apple-notes-source.js").catch(()=>null),l}const g=512,w=Object.freeze({list:18e4,body:6e4}),h=64*1024*1024,i=(n,e,o="invalid_request")=>({status:n,body:{error:{message:e,type:o}}});function m({execFileImpl:n=_}={}){return async(e,o=[])=>{const s=(await d())?.APPLE_NOTES_SCRIPTS?.[e];if(!s)throw Object.assign(new Error(`no script named ${e}`),{stderr:""});return S(n,e,s,o)}}function S(n,e,o,s){return new Promise((p,u)=>{n("/usr/bin/osascript",["-l","JavaScript","-e",o,...s],{timeout:w[e]||6e4,maxBuffer:h,encoding:"utf8",windowsHide:!0},(r,c,a)=>{r?u(Object.assign(new Error(String(a||r.message||r)),{stderr:String(a||""),timedOut:!!r.killed})):p(String(c||""))})})}async function E(n,{platform:e=process.platform,run:o=m()}={}){const s=await d();if(!s)return i(501,"This gateway needs @chatpanel/events 0.391 or later to read Apple Notes — update the gateway.","unsupported");const{APPLE_NOTES_OPS:p,appleScriptError:u}=s,r=n?.op;if(typeof r!="string"||!p.includes(r))return i(400,`apple-notes: op must be one of ${p.join(", ")}`);const c=[];if(r==="body"){const t=n?.id;if(typeof t!="string"||!t||t.length>g||/[\u0000-\u001f\u007f]/.test(t))return i(400,"apple-notes: body needs the note id");c.push(t)}if(e!=="darwin")return i(501,"Apple Notes can only be read on a Mac — this gateway runs elsewhere.","unsupported");let a;try{a=await o(r,c)}catch(t){const f=t?.timedOut?"Notes took too long to answer.":u(t?.stderr||t?.message);return i(502,f,"apple_notes_error")}try{const t=JSON.parse(String(a).trim());if(!t||typeof t!="object")throw new Error("not an object");return{status:200,body:t}}catch{return i(502,"Notes answered with something that is not a list of notes.","apple_notes_error")}}export{h as APPLE_NOTES_MAX_OUTPUT,w as APPLE_NOTES_TIMEOUT_MS,g as MAX_NOTE_ID,d as appleNotesScripts,E as handleAppleNotes,m as osascriptRunner};
|
package/src/diarize-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ensureLib as
|
|
1
|
+
import{verifyFresh as O}from"./model-integrity.js";import{ensureLib as P,modelRoot as S,withModelSource as q}from"./ner-engine.js";import{join as I}from"node:path";import{existsSync as C,readdirSync as H}from"node:fs";import{makeWarmTimer as M}from"./warm-timer.js";import{createSpeakerClusterer as N}from"@chatpanel/events/speaker-cluster.js";import{DEFAULT_DIARIZE_MODEL as b,diarizeThreshold as W,isKnownDiarizeModel as Z}from"./diarize-models.js";const Y=b;let l="off",c=b,d=null,g=null,p=null,u=null,f=null,i=null,w=0,_=0;function ee(){return c}function A(){return W(c)}function z(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function te(){return l}function D(){return l==="ready"&&!!d&&!!g}function re(){return f}function ne(){return{configured:l!=="off",ok:D(),state:l,model:c,loaded:!!d,threshold:A(),error:p,warmMs:i?.warmMs??null}}function oe(){return!!i?.pending()}function le(){w++,i?.disarm()}function ie(){w=Math.max(0,w-1),w===0&&_===0&&D()&&i?.arm()}function h(){return w>0||_>0||l==="loading"||l==="downloading"}async function y({log:e=()=>{}}={}){if(h())return!1;i?.disarm();const t=d;if(d=null,g=null,u=null,f=null,p=null,l="off",t){try{await t.dispose?.()}catch{}e("[diarize] idle — speaker model unloaded (reloads on the next diarizing session)")}return!0}function j(e=c,t=z()){const n=I(S(),...e.split("/"),"onnx");if(!C(n))return!1;const r=t==="fp32"?"":t==="q8"?"_quantized":`_${t}`;try{return H(n).some(a=>a===`model${r}.onnx`)}catch{return!1}}async function T({log:e=()=>{},allowDownload:t=!0}={}){let n;try{n=await P()}catch(o){return l="error",p=o.message,e(`[diarize] engine unavailable (${o.message})`),!1}const r=c,a=j(r);if(!a&&!t)return l="error",p="model not on disk and downloads disabled",!1;l=a?"loading":"downloading",a||(f={model:r,file:null,pct:0},e(`[diarize] downloading ${r} (one-time)…`));try{const{AutoModel:o,AutoProcessor:s}=n,k=m=>{if(!m)return;const R=typeof m.progress=="number"?Math.round(m.progress):f?.pct??0;(m.status==="progress"||m.status==="download"||m.status==="initiate")&&(f={model:r,file:m.file||f?.file||null,pct:R})},{processor:L,model:$}=await q({host:a?null:"https://huggingface.co/",allowRemote:!a},async()=>({processor:await s.from_pretrained(r,{progress_callback:k}),model:await o.from_pretrained(r,{dtype:z(),progress_callback:k})}));return await O(!a,r,{modelsDir:S(),log:e,dispose:()=>$.dispose?.()}),g=L,d=$,l="ready",p=null,f=null,e(`[diarize] ready — ${r} @ ${z()} (speakers split at cosine ${A()})`),!0}catch(o){return p=o.message,f=null,l="error",e(`[diarize] load failed (${o.message}) — diarization off`),!1}}function ae(e={}){if(u&&l!=="error")return u;l="loading";const t=typeof e.onLog=="function"?e.onLog:()=>{};return i=M({warmMs:e.warmMs,busy:h,log:t,unload:()=>y({log:t})}),u=F(T({log:t,allowDownload:e.allowDownload!==!1})),u}function F(e){return e.then(t=>(t&&!h()&&i?.arm(),t))}async function se(e,{log:t=()=>{}}={}){return Z(e)?e===c?!0:h()?!1:(await y({log:()=>{}}),c=e,t(`[diarize] speaker model set to ${e} (loads on the next diarizing session)`),!0):!1}function ue({onLog:e}={}){return u=null,l="loading",i??=M({warmMs:void 0,busy:h,log:e||(()=>{}),unload:()=>y({log:e||(()=>{})})}),u=F(T({log:e,allowDownload:!0})),u}const E=16e3;function x(e){let t=0;for(const r of e)t+=r*r;t=Math.sqrt(t)||1;const n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]/t;return n}async function v(e){try{const t=await g(e),n=await d(t),r=n.embeddings??n.logits??n.last_hidden_state;return r?.data?Float32Array.from(r.data):null}catch{return null}}async function fe(e){if(!D()||!(e instanceof Float32Array)||!e.length)return null;_++;try{return await J(e)}finally{_--,h()||i?.arm()}}async function J(e){const t=2*E,n=Math.round(1.3*E);if(e.length<=Math.round(t*1.4)){const o=await v(e);return o?x(o):null}const r=[];for(let o=0;o+t<=e.length;o+=n){const s=await v(e.subarray(o,o+t));s&&r.push(x(s))}if(!r.length){const o=await v(e);return o?x(o):null}const a=new Float32Array(r[0].length);for(const o of r)for(let s=0;s<a.length;s++)a[s]+=o[s];return x(a)}function ce(){i?.disarm(),i=null,w=0,_=0,l="off",c=b,d=null,g=null,p=null,u=null,f=null}function de(e,t,{warmMs:n=null}={}){d=e,g=t,l=e?"ready":"off",n!==null&&(i=M({warmMs:n,busy:h,unload:()=>y()}),e&&i.arm())}class me{constructor({threshold:t=A(),maxSpeakers:n=12}={}){this.threshold=t,this.maxSpeakers=n,this._voices=N({threshold:t,maxSpeakers:n})}assign(t,n){return this._voices.assign(t,n)}get centroids(){return this._voices.toJSON().centroids}}export{Y as DIARIZE_MODEL,me as Diarizer,ce as _reset,de as _setForTest,ee as activeModel,A as activeThreshold,ue as download,fe as embed,ne as health,ae as init,D as isReady,j as modelOnDisk,re as progress,ie as release,le as retain,se as setModel,te as state,y as unload,oe as warmPending};
|
package/src/indic-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{modelFetch as Q}from"./model-sources.js";import{existsSync as
|
|
1
|
+
import{modelFetch as Q}from"./model-sources.js";import{existsSync as z,readFileSync as Z,mkdirSync as V,createWriteStream as ee,createReadStream as te,renameSync as ne,rmSync as U}from"node:fs";import{createHash as re}from"node:crypto";import{join as A}from"node:path";import{modelRoot as oe}from"./ner-engine.js";import{getOrt as ce,ortProviders as ae,rawOrtAvailable as se}from"./ort.js";import{fft as ie}from"./aec-engine.js";import{INDIC_LICENSE as M,licenseAcceptance as fe}from"./stt-models.js";const $e="bodhan-ai/indic-transcribe-core",de=fe(M);function $(){return A(oe(),"bodhan-ai","indic-transcribe-core-int8")}const le="https://huggingface.co/ChatPanel/indic-transcribe-core-int8/resolve/main",D=Object.freeze({"encoder.onnx":"fa49d702bf83d52327105736ded11aea2e6afcfcb1667182e6db36e5cc27f097","encoder.onnx.data":"66c3442b950a3ff5e18fc33db1d15069b7888235776bdc86824d6f99d728f9a5","cross_kv.onnx":"0aed59ffef5e77e2b957d42f742ea2645fed3ac49954b6a91dc8e629d7196c26","cross_kv.onnx.data":"022d88763437e56ac1156b3953c68a01c205b52627094a086d243b822f6e810b","decoder.onnx":"f858a610f1d3498a993d5eb0424ef888d96edc853be3b7aa32846b237d2c4a97","decoder.onnx.data":"c557a469b426ad424b0ed04c7422df44fc12131df2ae300b3f4bc92bdf50d05b","mel_fb_128x257.f32":"586bbdf62da6485f02faecb278f781277fab9537558a57d611bf2fc35e12452b","window_400.f32":"cb9f40f78ef078b89ba969960015aa5e5a833e0c549e9dcdb532d9defbb418d2","vocab.json":"894a3b8761a73dec92577e7ef1664d1357fdee6008a598add2c9006423d3c79d","LICENSE.md":"b39f2a9cb2d5ace3a03f4425cbc6db38ebd9a53ab7a7648d67dc1e0998ad75c2"});function q(){return Object.keys(D).every(a=>z(A($(),a)))}const G=a=>new Promise((o,s)=>{const i=re("sha256");te(a).on("data",b=>i.update(b)).on("error",s).on("end",()=>o(i.digest("hex")))});async function De({licenseAccepted:a=null,onProgress:o=()=>{},log:s=()=>{},fetchImpl:i=Q()}={}){if(q())return $();if(a!==de){const x=new Error(`Indic-Transcribe is downloaded only after its licence (${M.name}) is accepted`);throw x.code="license_required",x}const b=$();V(b,{recursive:!0});const d=Object.keys(D);for(const[x,u]of d.entries()){const y=A(b,u);if(z(y))continue;const g=await i(`${le}/${u}`);if(!g.ok||!g.body)throw new Error(`${u}: HTTP ${g.status}`);const f=Number(g.headers.get("content-length"))||0,v=`${y}.part`;if(await new Promise((w,r)=>{const h=ee(v),n=g.body.getReader();let e=0;const c=()=>n.read().then(({done:t,value:p})=>{if(t){h.end(w);return}e+=p.length,f&&o({file:u,pct:Math.round((x+e/f)/d.length*100)}),h.write(Buffer.from(p)),c()},r);h.on("error",r),c()}),await G(v)!==D[u])throw U(v,{force:!0}),new Error(`${u} does not match its pinned hash — not used`);ne(v,y),s(`[indic] fetched ${u}`)}return b}const P=16e3,C=512,W=160,J=400,L=128,T=C/2+1,be=.97,pe=2**-24,me=1e-5,we=24,he=8,ue=128,K=new Set,X=3;function ge(a,{fb:o,window:s}){const i=a.length,b=new Float32Array(i);b[0]=a[0]||0;for(let r=1;r<i;r++)b[r]=a[r]-be*a[r-1];const d=Math.floor(i/W)+1,x=C/2,u=r=>(r<0&&(r=-r),r>=i&&(r=2*(i-1)-r),b[Math.max(0,Math.min(i-1,r))]),y=(C-J)/2,g=new Float64Array(C),f=new Float64Array(C),v=new Float64Array(T),w=new Float32Array(L*d);for(let r=0;r<d;r++){const h=r*W-x;for(let n=0;n<C;n++){const e=n>=y&&n<y+J?s[n-y]:0;g[n]=e?u(h+n)*e:0,f[n]=0}ie(g,f);for(let n=0;n<T;n++)v[n]=g[n]*g[n]+f[n]*f[n];for(let n=0;n<L;n++){let e=0;const c=n*T;for(let t=0;t<T;t++)e+=o[c+t]*v[t];w[n*d+r]=Math.log(e+pe)}}for(let r=0;r<L;r++){const h=r*d;let n=0;for(let t=0;t<d;t++)n+=w[h+t];n/=d;let e=0;for(let t=0;t<d;t++)e+=(w[h+t]-n)**2;const c=Math.sqrt(e/Math.max(1,d-1))+me;for(let t=0;t<d;t++)w[h+t]=(w[h+t]-n)/c}return{data:w,frames:d}}function _e(a){return String(a||"").replace(/\b[A-Z][A-Z']*(?:[\s,.!?;:-]+[A-Z][A-Z']*){2,}\b/g,o=>o.toLowerCase().replace(/\bi\b/g,"I").replace(/\bi'(m|ll|ve|d)\b/g,(i,b)=>`I'${b}`).replace(/(^|[.!?]\s+)([a-z])/g,(i,b,d)=>b+d.toUpperCase())).replace(/(^|[.!?]\s+)([a-z])/,(o,s,i)=>/[A-Z]{3}/.test(a)?s+i.toUpperCase():o)}const ye=/\b(do|does|did|is|are|was|were|ca|could|would|should|wo|have|has|had|ai|must|need)n t\b/gi,Ie=[[ye,(a,o)=>`${o}n't`],[/\b(can) t\b/gi,(a,o)=>`${o}'t`],[/\b(it|that|what|there|here|let|he|she|who|where|how|everyone|nobody) s\b/gi,(a,o)=>`${o}'s`],[/\b(I) (m)\b/g,()=>"I'm"],[/\b(I|you|we|they) (ll|ve|d)\b/gi,(a,o,s)=>`${o}'${s}`],[/\b(you|we|they) re\b/gi,(a,o)=>`${o}'re`]];function xe(a){let o=String(a||"");for(const[s,i]of Ie)o=o.replace(s,i);return o}function ve(a,o){return a.map(s=>o[s]??"").join("").replace(/▁/g," ").trim()}async function Le({sessionOptions:a=null,log:o=()=>{}}={}){if(!se())throw new Error("Indic-Transcribe needs the npm gateway (the standalone binary cannot run it)");if(!q())throw new Error("Indic-Transcribe is not downloaded");const s=$();for(const[e,c]of Object.entries(D))if(!K.has(e)){if(await G(A(s,e))!==c)throw U(A(s,e),{force:!0}),new Error(`${e} changed on disk — removed`);K.add(e)}const i=await ce(),b={executionProviders:ae(),graphOptimizationLevel:"all",logSeverityLevel:3,...a||{}},[d,x,u]=await Promise.all(["encoder","cross_kv","decoder"].map(e=>i.InferenceSession.create(A(s,`${e}.onnx`),b))),y=e=>{const c=Z(A(s,e));return new Float32Array(c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength))},g={fb:y("mel_fb_128x257.f32"),window:y("window_400.f32")},f=JSON.parse(Z(A(s,"vocab.json"),"utf8")),v=new Set(f.eos),w=i.Tensor;o("[indic] ready — Indic-Transcribe-core (int8, in-process, offline)");async function r(e,c,t){const p=await u.run({ids:new w("int64",BigInt64Array.from([BigInt(c)]),[1,1]),pos:new w("int64",BigInt64Array.from([BigInt(t)]),[1]),self_k:e.k,self_v:e.v,cross_k:e.ck,cross_v:e.cv});return e.k=p.new_self_k,e.v=p.new_self_v,p.logits.data}async function h(e){const{data:c,frames:t}=ge(e,g),p=(await d.run({features:new w("float32",c,[1,L,t])})).states,S=await x.run({states:p}),E=new w("float32",new Float32Array(0),[we,1,he,0,ue]),l={k:E,v:E,ck:S.cross_k,cv:S.cross_v},_=f.prompt_te.slice();let F=null;for(let I=0;I<X;I++)F=await r(l,_[I],I);return{st:l,prompt:_,logits:F}}function n(e,c){const t=(c&&c.length?c:Object.keys(f.lang_ids)).filter(l=>f.lang_ids[l]!=null);let p=-1/0;for(const l of t)p=Math.max(p,e[f.lang_ids[l]]);let S=0;const E={};for(const l of t)E[l]=Math.exp(e[f.lang_ids[l]]-p),S+=E[l];return t.map(l=>[l,E[l]/S]).sort((l,_)=>_[1]-l[1])}return{vocab:f,async identify(e,{langs:c=[]}={}){if(!(e instanceof Float32Array)||e.length<P/4)return{lang:null,confidence:0,scores:{}};const t=n((await h(e)).logits,c);return t.length?{lang:t[0][0],confidence:t[0][1],scores:Object.fromEntries(t)}:{lang:null,confidence:0,scores:{}}},async transcribe(e,{lang:c=null,langs:t=[],last:p=null,maxNew:S=256,choose:E=null}={}){if(!(e instanceof Float32Array)||e.length<P/4)return{text:"",lang:c,confidence:0};const{st:l,prompt:_,logits:F}=await h(e);let I=null,O=c,R=1;if(!O){const m=n(F,t),k=Object.fromEntries(m);O=(E&&m.length?E(k,e.length/P):null)||m[0]?.[0]||p||"en",R=k[O]??0}const Y=f.lang_ids[O]??f.lang_ids.en;_[3]=_[4]=Y;for(let m=X;m<_.length;m++)I=await r(l,_[m],m);const j=[];for(let m=_.length;m<_.length+S;m++){let k=0,H=-1/0;for(let N=0;N<I.length;N++)I[N]>H&&(H=I[N],k=N);if(v.has(k))break;j.push(k),I=await r(l,k,m)}const B=_e(ve(j.filter(m=>!f.timestamp_ids.includes(m)),f.pieces));return{text:O==="en"?xe(B):B,lang:O,confidence:R}},async dispose(){for(const e of[d,x,u])try{await e.release?.()}catch{}}}}export{D as INDIC_FILES,M as INDIC_LICENSE,de as INDIC_LICENSE_ACCEPTANCE,$e as INDIC_MODEL_ID,le as INDIC_SOURCE,P as SAMPLE_RATE,ve as decodeIds,De as ensureIndicFiles,$ as indicDir,q as indicOnDisk,Le as loadRecognizer,ge as melFeatures,xe as restoreApostrophes,_e as restoreCase};
|
package/src/link-host.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as Oe,writeFileSync as Re,renameSync as Ue,mkdirSync as ee,chmodSync as Ce}from"node:fs";import{dirname as J,join as ue,resolve as de,sep as Ie}from"node:path";import te from"node:os";import{createLinkEndpoint as De}from"@chatpanel/events/link-connect.js";import{noiseCrypto as Fe}from"@chatpanel/events/link-noise.js";import{pairingUri as fe,pairingCode as Me,admissionToken as G,admissionVerifier as F,toB64url as O,fromB64url as ne,coalesceChunks as je}from"@chatpanel/events/link-protocol.js";import{linkPaths as me,linkRoute as z,checkLinkRoute as Be,DEFAULT_LINK_RELAY as Ve,LINK_ROUTES as he,LINK_TUNNEL_ROOM_PATH as He,tunnelSetup as Je}from"@chatpanel/events/link-routes.js";import{linkDeviceKind as M,partnerMay as Ge,partnerHeaders as ze,withoutLinkMarks as We,linkMarkHeaders as Ye,checkPartnerName as Qe,checkPartnerScopes as Ze,describePartnerAccess as Xe,checkPartnerFolder as qe,partnerFolderSlug as et}from"@chatpanel/events/link-scopes.js";import{timingSafeEqual as tt}from"node:crypto";import{acceptWebSocket as nt,refuseUpgrade as oe}from"./ws-accept.js";import{qrSvg as ot}from"@chatpanel/events/qr.js";import{verifyEntitlement as rt,licenseFromPayload as at,can as st,FEATURE_TIER as ye}from"@chatpanel/events/entitlement.js";const bt="https://link.chatpanel.net",W=10*6e4,it=3e4,re=[1e3,2e3,5e3,1e4,3e4,6e4],lt=30,Y="chatpanel-link.v1",ct=/(^|\n): ?ping\n\n/g,pt=4,ut=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/,/^\/v1\/link\/routes$/,/^\/v1\/agent-sessions(?:\/read|\/adopt|\/catchup)?$/],dt=c=>ut.some(i=>i.test(String(c||""))),ge="x-chatpanel-entitlement",we="x-chatpanel-install",ke=(c,i)=>{for(const[g,k]of Object.entries(c||{}))if(g.toLowerCase()===i)return String(k||"");return""};async function Se(c,{now:i=Date.now()}={}){if(!ye.link||ye.link==="free")return!1;const g=ke(c,ge),k=ke(c,we);if(!g||!k)return!1;const N=await rt(g,k,{now:i});return!!N&&st(at(N,{at:i}),"link",0,i)}const ft=!1;async function mt(c,i,{now:g=Date.now(),phoneCheck:k=Se,ownerIsPro:N=async()=>!1}={}){return M(c)==="partner"?ft?!!await N():!0:k(i?.headers||{},{now:g})}const L=c=>Object.assign(new Error(c),{code:"bad_partner"}),R=c=>{try{return new URL(c).host}catch{return""}};function Lt(c=ae()){return ve(c).rooms.filter(i=>M(i)==="partner"&&i.phoneKey).map(i=>({id:i.room,kind:"partner",name:i.name,partner:{name:i.partner?.name||i.name},scopes:i.scopes||[],route:i.route||null,host:R(i.relay||i.gw||""),pairedAt:i.pairedAt||null,lastSeen:i.lastSeen||null,...(i.scopes||[]).includes("agents")?{folder:Q(i,c)}:{}}))}function Q(c,i=ae()){return c?.folder||ue(J(i),"partners",et(c?.partner?.name||c?.name))}const ht=(c,i)=>{const g=de(c),k=de(i);return g===k||g.startsWith(`${k}${Ie}`)};function ae(){return ue(te.homedir(),".chatpanel","link.json")}function ve(c){try{const i=JSON.parse(Oe(c,"utf8"));return{v:1,key:i.key||null,rooms:Array.isArray(i.rooms)?i.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function Ee(c,i){ee(J(c),{recursive:!0});const g=`${c}.tmp`;Re(g,JSON.stringify(i,null,2),{mode:384});try{Ce(g,384)}catch{}Ue(g,c)}function Nt({settings:c={},relay:i=null,port:g=4320,name:k=te.hostname(),dispatch:N,path:T=ae(),fetch:$e=globalThis.fetch,WebSocket:Te=globalThis.WebSocket,now:w=()=>Date.now(),random:j=v=>globalThis.crypto.getRandomValues(new Uint8Array(v)),crypto:Z=Fe(),log:U=v=>{},mayLink:Pe=Se,ownerIsPro:Ae=async()=>!1,home:_e=te.homedir(),confined:be=process.env.CHATPANEL_CONFINED==="1"}={}){const v=i?new URL(i).origin:null;if(v&&!/^https:/.test(v)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(v))throw new Error("link: the relay must be https");const se=t=>{const e=me(t);return v&&e.relay?{...e,relay:v}:e};let l=se(c);l.problem&&U(`link: ${l.problem} — using ChatPanel Link`);let u=ve(T);const Le=v||me({relayUrl:c?.relayUrl}).relay;for(const t of u.rooms)t.relay===void 0&&(t.relay=Le);const S=new Map,P=new Map;let _=null;async function K(){return _||(u.key?_=await Z.keyPairFromPrivate(ne(u.key)):(_=await Z.generateKeyPair(),u.key=O(_.raw),Ee(T,u)),_)}const A=t=>u.rooms.find(e=>e.room===t)||null,B=()=>Ee(T,u),C=t=>M(t)==="partner"?!!t.relay:!!t.relay&&t.relay===l.relay,$=t=>M(t)==="partner",V=async(t,e,n,o,r)=>{try{return await $e(`${r}/v1/room/${t}`,{method:e,headers:{authorization:`Bearer ${n}`,...o?{"content-type":"application/json"}:{}},body:o?JSON.stringify(o):void 0})}catch(s){const a=s?.cause?.code||"",d=a==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":a?`${a}`:s?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(r).host}: ${d}`)}};async function Ne(t,e,n){t.lastSeen=w();const o=$(t);if(o?!Ge(t.scopes,e):!dt(e.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?`link: partner "${t.name}" may not call ${e.method} ${e.path.split("?")[0]} — its scopes are ${(t.scopes||[]).join(", ")||"none"}`:"link: a paired phone may not call this",type:"forbidden",...o?{code:"link_scope"}:{}}})),n.end();if(!await mt(t,e,{now:w(),phoneCheck:Pe,ownerIsPro:Ae}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?"ChatPanel Link partner devices need ChatPanel Pro on this computer":"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();if(e.path==="/v1/link/routes")return await n.head(200,{"content-type":"application/json"}),await n.write(JSON.stringify({route:l.route,relay:C(t)?t.relay:null,gw:l.tunnel})),n.end();let r={};if(o)r=ze(e.headers);else for(const[m,y]of Object.entries(e.headers||{}))m.toLowerCase()!==ge&&m.toLowerCase()!==we&&(r[m]=y);r={...We(r),...Ye(t)};const s=e.method==="GET"?void 0:await e.body.bytes(),a=await N({method:e.method,path:e.path,headers:r,body:s,device:t.room}),d={};a.headers?.forEach?.((m,y)=>{d[y]=m});let f=!1;try{await n.head(a.status,d)}catch{f=!0}if(a.body){const m=/event-stream/.test(String(a.headers?.get?.("content-type")||""));for await(const y of je(Ke(a.body,m))){if(n.cancelled)break;if(!f)try{await n.write(y)}catch{f=!0}}}if(!f)return n.end()}async function*Ke(t,e){for await(const n of t){let o=n instanceof Uint8Array?n:new TextEncoder().encode(String(n));if(e){const r=new TextDecoder().decode(o);if(r.includes(": ping")){const s=r.replace(ct,"$1");if(!s)continue;o=new TextEncoder().encode(s)}}yield o}}function ie(t,e,n,o,r){return De({side:"laptop",keyPair:e,crypto:Z,psk:t.phoneKey?null:ne(n.psk),peerKey:t.phoneKey?ne(t.phoneKey):null,sendBytes:r,onRequest:(s,a)=>Ne(t,s,a),onSession:(s,a)=>{o.online=!0,o.attempts=0,t.lastSeen=w(),a.paired&&(t.phoneKey=O(a.peerKey),$(t)||(t.name=a.name||t.name||"Phone"),t.pairedAt=w(),t.pending=null,U(`link: paired ${t.name}`)),B()},onEnd:()=>{o.online=!1}})}async function I(t){if(!C(t))return;const e=S.get(t.room)||{attempts:0,stopped:!1,online:!1};if(S.set(t.room,e),e.stopped)return;const n=await K(),o=t.pending&&t.pending.expiresAt>w()?t.pending:null;if(!t.phoneKey&&!o){D(t.room,"the pairing code expired");return}const r=`${t.relay.replace(/^http/,"ws")}/v1/room/${t.room}`;let s;try{s=new Te(r,[Y,t.token])}catch(a){le(t,a?.message);return}s.binaryType="arraybuffer",e.ws=s,e.endpoint=ie(t,n,o,e,a=>{try{s.send(a)}catch{}}),s.onopen=()=>{if(e.stopped||S.get(t.room)!==e){try{s.close(1e3,"stopped")}catch{}return}clearInterval(e.keepalive),e.keepalive=setInterval(()=>{try{s.send("ping")}catch{}},it),e.keepalive.unref?.()},s.onmessage=a=>typeof a.data=="string"?e.endpoint.onText(a.data):e.endpoint.onBinary(new Uint8Array(a.data)),s.onclose=a=>{if(clearInterval(e.keepalive),e.online=!1,e.endpoint?.close("socket closed"),!e.stopped){if(a?.code===4003||a?.code===4004){q(t.room,"the relay removed the room");return}le(t,a?.code===4001?"replaced":a?.code===4008?"over the relay's budget":`closed ${a?.code||""}`,a?.code===4001?5:a?.code===4008?pt:null)}},s.onerror=()=>{}}function le(t,e,n=null){const o=S.get(t.room);if(!o||o.stopped)return;const r=n??Math.min(o.attempts,re.length-1);o.attempts++,clearTimeout(o.timer),o.timer=setTimeout(()=>I(t),re[r]),o.timer.unref?.(),U(`link: ${e}; again in ${re[r]/1e3}s`)}function X(t){const e=S.get(t);if(e){e.stopped=!0,clearTimeout(e.timer),clearInterval(e.keepalive),e.endpoint?.close("stopped");try{e.ws?.close(1e3,"stopped")}catch{}S.delete(t)}}function H(t,e=1e3,n="stopped"){const o=P.get(t);if(o?.ws){o.endpoint?.close(n);try{o.ws.close(e,n)}catch{}o.ws=null,o.endpoint=null,o.online=!1}}function D(t,e){const n=A(t);n&&!n.phoneKey&&n.relay&&V(t,"DELETE",n.token,null,n.relay).catch(()=>{}),q(t,e)}function q(t,e){X(t),H(t,4004,"room removed"),P.delete(t),u.rooms=u.rooms.filter(n=>n.room!==t),B(),U(`link: ${e}`)}function xe({route:t=null,relay:e=""}={}){const n=t||(e?"relay":l.route);if(!z(n))throw L(`unknown route "${n}" — one of ${he.map(r=>r.id).join(", ")}`);if(z(n).kind==="tunnel"){if(l.route!==n||!l.tunnel)throw L(`this gateway's ${z(n).label} door is not open — set it as the route first (chatpanel-gateway link route ${n} --gw <https address>), then pair`);return{route:n,relay:null,gw:l.tunnel,host:R(l.tunnel)}}if(n==="relay"){const r=e||(l.route==="relay"?l.relay:"");if(!r)throw L('the relay route needs the relay’s https address (--relay <url>), or "Your own relay" set as the route');let s;try{s=Be({id:"relay",url:r})}catch(a){throw L(a.message)}return{route:s.id,relay:s.url,gw:null,host:R(s.url)}}const o=v||Ve;return{route:"link",relay:o,gw:null,host:R(o)}}function ce({partner:t,scopes:e,route:n=null,relay:o="",folder:r=""}={}){const s=Qe(t),a=Ze(e),d=xe({route:n,relay:o});let f="";if(a.includes("agents")){try{f=String(r||"").trim()?qe(r,{name:s,home:_e}):Q({partner:{name:s}},T)}catch(m){throw L(m.message)}if(be&&!ht(f,J(T)))throw L(`this gateway runs confined and writes only ${J(T)} — leave the folder empty (the default is inside it), or run the gateway unconfined to use ${f}`)}return{via:d,folder:f,preview:Xe({partner:s,scopes:a,route:d.route,host:d.host,folder:f})}}return{previewPartner(t={}){return ce(t).preview},deviceNameOf(t){const e=A(t);return e?.phoneKey?String(e.name||""):""},partnerFolderOf(t){const e=A(t);if(!e||!$(e)||!e.phoneKey||!(e.scopes||[]).includes("agents"))return null;const n=Q(e,T);try{ee(n,{recursive:!0,mode:448})}catch{return null}return n},async pairPartner(t={}){const{via:e,preview:n,folder:o}=ce(t);if(o)try{ee(o,{recursive:!0,mode:448})}catch(h){throw L(`could not create ${o}: ${h.message}`)}const r=await K(),s=j(16),a=j(32),d=O(s),f=await G(a,s,"laptop"),m=await F(await G(a,s,"phone"));if(e.relay){const h=await V(d,"PUT",f,{laptop:await F(f),phone:m},e.relay);if(h.status!==200&&h.status!==201)throw new Error(`link: the relay refused the room (${h.status})`)}for(const h of u.rooms.filter(b=>!b.phoneKey&&$(b)))D(h.room,"a new partner code replaced this one");const y=w()+W,p={room:d,token:f,relay:e.relay,phoneVerifier:m,phoneKey:null,name:n.partner,pairedAt:null,lastSeen:null,pending:{psk:O(a),expiresAt:y},kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,...o?{folder:o}:{}};u.rooms.push(p),B();const x=Me({uri:fe({relay:e.relay,gw:e.gw,room:s,key:r.publicKey,secret:a,name:""}),expiresAt:y,route:e.route});return I(p),setTimeout(()=>{const h=A(d);h&&!h.phoneKey&&D(d,"the partner code expired")},W+1e3).unref?.(),U(`link: partner code issued for ${n.partner} (${n.scopes.join(", ")}; route ${e.route} via ${e.host})`),{code:x,expiresAt:y,room:d,kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,host:e.host,...o?{folder:o}:{},preview:n}},async pair({name:t=k}={}){const e=await K(),n=j(16),o=j(32),r=O(n),s=await G(o,n,"laptop"),a=await G(o,n,"phone"),d=await F(a);if(l.relay){const p=await V(r,"PUT",s,{laptop:await F(s),phone:d},l.relay);if(p.status!==200&&p.status!==201)throw new Error(`link: the relay refused the room (${p.status})`)}for(const p of u.rooms.filter(x=>!x.phoneKey&&!$(x)))D(p.room,"a new pairing code replaced this one");const f=w()+W,m={room:r,token:s,relay:l.relay,phoneVerifier:d,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:O(o),expiresAt:f}};u.rooms.push(m),B();const y=fe({relay:l.relay,gw:l.tunnel,room:n,key:e.publicKey,secret:o,name:String(t||"").slice(0,60)});return I(m),setTimeout(()=>{const p=A(r);p&&!p.phoneKey&&D(r,"the pairing code expired")},W+1e3).unref?.(),{uri:y,svg:ot(y,{ecc:"M"}),expiresAt:f,room:r}},status(){const t=e=>!!S.get(e.room)?.online||!!P.get(e.room)?.online;return{route:l.route,relay:l.relay,tunnel:l.tunnel,...l.problem?{problem:l.problem}:{},routes:he,setup:Je(l.route,{port:g,url:l.tunnel||""}),devices:u.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,kind:M(e),name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:t(e),...$(e)?{partner:{name:e.partner?.name||e.name},scopes:e.scopes||[],route:e.route||null,host:R(e.relay||"")||R(e.route===l.route&&l.tunnel||""),...(e.scopes||[]).includes("agents")?{folder:Q(e,T)}:{},...e.route&&z(e.route)?.kind==="tunnel"&&e.route!==l.route?{routeClosed:!0}:{}}:{},via:P.get(e.room)?.online?"tunnel":S.get(e.room)?.online?"relay":null,...e.relay&&!C(e)?{staleRelay:e.relay}:{},...!$(e)&&l.tunnel&&!e.phoneVerifier?{tunnelNeedsRelink:!0}:{}})),pairing:u.rooms.filter(e=>!e.phoneKey&&!$(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:t(e)}))[0]||null,partnerPairing:u.rooms.filter(e=>!e.phoneKey&&$(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,partner:{name:e.name},scopes:e.scopes||[],route:e.route||null}))[0]||null}},async applySettings(t={}){l=se(t);for(const e of[...S.keys()]){const n=A(e);(!n||!C(n))&&X(e)}if(!l.tunnel)for(const e of[...P.keys()])H(e,1001,"the tunnel was switched off");u.rooms.length&&await K();for(const e of u.rooms)C(e)&&!S.has(e.room)&&I(e);return this.status()},async acceptTunnel(t,e,n){const o=decodeURIComponent(String(t.url||"").split("?")[0].slice(He.length));if(!l.tunnel)return oe(e,404,"not found");const r=A(o),s=String(t.headers["sec-websocket-protocol"]||"").split(",").map(E=>E.trim()).filter(Boolean),d=/^Bearer ([A-Za-z0-9_-]+)$/.exec(String(t.headers.authorization||""))?.[1]||(s.length===2&&s.includes(Y)?s.find(E=>E!==Y):null),f=r&&!r.phoneKey&&r.pending?.expiresAt>w()?r.pending:null,m=d?Buffer.from(await F(d)):null,y=r?.phoneVerifier?Buffer.from(r.phoneVerifier):null;if(!r||!r.phoneKey&&!f||!m||!y||m.length!==y.length||!tt(m,y))return oe(e,403,"not admitted");const p=P.get(o)||{connects:[]};if(P.set(o,p),p.connects=p.connects.filter(E=>w()-E<6e4),p.connects.length>=lt)return oe(e,429,"too many connects");p.connects.push(w());const x=await K(),h=nt(t,e,n,{protocol:Y});if(!h)return;H(o,4001,"replaced"),p.ws=h,p.online=!1;const b=ie(r,x,f,p,E=>{try{h.send(E)}catch{}});p.endpoint=b,h.onmessage=E=>{typeof E.data!="string"&&b.onBinary(new Uint8Array(E.data))},h.onclose=()=>{b.close("socket closed"),p.ws===h&&(p.ws=null,p.endpoint=null,p.online=!1)};const pe=JSON.stringify({t:"peer",up:!0});b.onText(pe),h.send(pe)},async remove(t){const e=A(t);if(!e)return!1;if(e.relay)try{await V(t,"DELETE",e.token,null,e.relay)}catch{}return q(t,"removed"),!0},async start(){if(u.rooms.length){await K();for(const t of u.rooms)I(t)}},stop(){for(const t of[...S.keys()])X(t);for(const t of[...P.keys()])H(t,1001,"going away")},get publicKey(){return _?.publicKey||null}}}export{ut as COMPANION_PATHS,bt as DEFAULT_RELAY,ge as ENTITLEMENT_HEADER,we as INSTALL_HEADER,W as PAIRING_TTL_MS,ft as PARTNER_DEVICES_REQUIRE_PRO,dt as companionMay,Nt as createLinkHost,ae as defaultLinkPath,mt as deviceMayLink,Lt as partnerDevicesOnDisk,Q as partnerFolderFor,Se as phoneMayLink};
|
|
1
|
+
import{readFileSync as Oe,writeFileSync as Re,renameSync as Ue,mkdirSync as ee,chmodSync as Ce}from"node:fs";import{dirname as J,join as ue,resolve as de,sep as Ie}from"node:path";import te from"node:os";import{createLinkEndpoint as De}from"@chatpanel/events/link-connect.js";import{noiseCrypto as Fe}from"@chatpanel/events/link-noise.js";import{pairingUri as fe,pairingCode as Me,admissionToken as G,admissionVerifier as F,toB64url as O,fromB64url as ne,coalesceChunks as je}from"@chatpanel/events/link-protocol.js";import{linkPaths as me,linkRoute as z,checkLinkRoute as Be,DEFAULT_LINK_RELAY as Ve,LINK_ROUTES as he,LINK_TUNNEL_ROOM_PATH as He,tunnelSetup as Je}from"@chatpanel/events/link-routes.js";import{linkDeviceKind as M,partnerMay as Ge,partnerHeaders as ze,withoutLinkMarks as We,linkMarkHeaders as Ye,checkPartnerName as Qe,checkPartnerScopes as Ze,describePartnerAccess as Xe,checkPartnerFolder as qe,partnerFolderSlug as et}from"@chatpanel/events/link-scopes.js";import{timingSafeEqual as tt}from"node:crypto";import{acceptWebSocket as nt,refuseUpgrade as oe}from"./ws-accept.js";import{qrSvg as ot}from"@chatpanel/events/qr.js";import{verifyEntitlement as rt,licenseFromPayload as at,can as st,FEATURE_TIER as ye}from"@chatpanel/events/entitlement.js";const bt="https://link.chatpanel.net",W=10*6e4,it=3e4,re=[1e3,2e3,5e3,1e4,3e4,6e4],lt=30,Y="chatpanel-link.v1",ct=/(^|\n): ?ping\n\n/g,pt=4,ut=[/^\/v1\/models(?:\/|$|\?)/,/^\/v1\/chat\/completions$/,/^\/v1\/messages$/,/^\/v1\/audio\/(?:transcriptions|speech)$/,/^\/v1\/history\/(?:search|smart-search|get|list|related|status)(?:$|\?)/,/^\/v1\/history\/(?:records|stream)(?:$|\?)/,/^\/v1\/memory\/(?:recall|list|remember)(?:$|\?)/,/^\/v1\/(?:research|search|read|rerank|decide|capabilities|fusions)(?:$|\?)/,/^\/v1\/status$/,/^\/v1\/stt\/sessions(?:\/[0-9a-f-]{36}(?:\/audio)?)?$/,/^\/v1\/link\/routes$/,/^\/v1\/agent-sessions(?:\/read|\/adopt|\/catchup)?$/],dt=c=>ut.some(i=>i.test(String(c||""))),ge="x-chatpanel-entitlement",we="x-chatpanel-install",ke=(c,i)=>{for(const[g,k]of Object.entries(c||{}))if(g.toLowerCase()===i)return String(k||"");return""};async function ve(c,{now:i=Date.now()}={}){if(!ye.link||ye.link==="free")return!1;const g=ke(c,ge),k=ke(c,we);if(!g||!k)return!1;const N=await rt(g,k,{now:i});return!!N&&st(at(N,{at:i}),"link",0,i)}const ft=!1;async function mt(c,i,{now:g=Date.now(),phoneCheck:k=ve,ownerIsPro:N=async()=>!1}={}){return M(c)==="partner"?ft?!!await N():!0:k(i?.headers||{},{now:g})}const L=c=>Object.assign(new Error(c),{code:"bad_partner"}),R=c=>{try{return new URL(c).host}catch{return""}};function Lt(c=ae()){return Se(c).rooms.filter(i=>M(i)==="partner"&&i.phoneKey).map(i=>({id:i.room,kind:"partner",name:i.name,partner:{name:i.partner?.name||i.name},scopes:i.scopes||[],route:i.route||null,host:R(i.relay||i.gw||""),pairedAt:i.pairedAt||null,lastSeen:i.lastSeen||null,...(i.scopes||[]).includes("agents")?{folder:Q(i,c)}:{}}))}function Q(c,i=ae()){return c?.folder||ue(J(i),"partners",et(c?.partner?.name||c?.name))}const ht=(c,i)=>{const g=de(c),k=de(i);return g===k||g.startsWith(`${k}${Ie}`)};function ae(){return ue(te.homedir(),".chatpanel","link.json")}function Se(c){try{const i=JSON.parse(Oe(c,"utf8"));return{v:1,key:i.key||null,rooms:Array.isArray(i.rooms)?i.rooms:[]}}catch{return{v:1,key:null,rooms:[]}}}function Ee(c,i){ee(J(c),{recursive:!0});const g=`${c}.tmp`;Re(g,JSON.stringify(i,null,2),{mode:384});try{Ce(g,384)}catch{}Ue(g,c)}function Nt({settings:c={},relay:i=null,port:g=4320,name:k=te.hostname(),dispatch:N,path:T=ae(),fetch:$e=globalThis.fetch,WebSocket:Te=globalThis.WebSocket,now:w=()=>Date.now(),random:j=S=>globalThis.crypto.getRandomValues(new Uint8Array(S)),crypto:Z=Fe(),log:U=S=>{},mayLink:Pe=ve,ownerIsPro:Ae=async()=>!1,home:_e=te.homedir(),confined:be=process.env.CHATPANEL_CONFINED==="1"}={}){const S=i?new URL(i).origin:null;if(S&&!/^https:/.test(S)&&!/^http:\/\/127\.0\.0\.1(?::\d+)?$/.test(S))throw new Error("link: the relay must be https");const se=t=>{const e=me(t);return S&&e.relay?{...e,relay:S}:e};let l=se(c);l.problem&&U(`link: ${l.problem} — using ChatPanel Link`);let u=Se(T);const Le=S||me({relayUrl:c?.relayUrl}).relay;for(const t of u.rooms)t.relay===void 0&&(t.relay=Le);const v=new Map,P=new Map;let _=null;async function K(){return _||(u.key?_=await Z.keyPairFromPrivate(ne(u.key)):(_=await Z.generateKeyPair(),u.key=O(_.raw),Ee(T,u)),_)}const A=t=>u.rooms.find(e=>e.room===t)||null,B=()=>Ee(T,u),C=t=>M(t)==="partner"?!!t.relay:!!t.relay&&t.relay===l.relay,$=t=>M(t)==="partner",V=async(t,e,n,o,r)=>{try{return await $e(`${r}/v1/room/${t}`,{method:e,headers:{authorization:`Bearer ${n}`,...o?{"content-type":"application/json"}:{}},body:o?JSON.stringify(o):void 0})}catch(s){const a=s?.cause?.code||"",d=a==="ENOTFOUND"?"this computer cannot look up its name (a VPN or DNS that does not know it yet)":a?`${a}`:s?.message||"no answer";throw new Error(`cannot reach the Link relay at ${new URL(r).host}: ${d}`)}};async function Ne(t,e,n){t.lastSeen=w();const o=$(t);if(o?!Ge(t.scopes,e):!dt(e.path))return await n.head(403,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?`link: partner "${t.name}" may not call ${e.method} ${e.path.split("?")[0]} — its scopes are ${(t.scopes||[]).join(", ")||"none"}`:"link: a paired phone may not call this",type:"forbidden",...o?{code:"link_scope"}:{}}})),n.end();if(!await mt(t,e,{now:w(),phoneCheck:Pe,ownerIsPro:Ae}))return await n.head(402,{"content-type":"application/json"}),await n.write(JSON.stringify({error:{message:o?"ChatPanel Link partner devices need ChatPanel Pro on this computer":"ChatPanel Link needs Pro on this phone — upgrade on the phone, or restore its Pro under Settings › Plan",type:"pro_required"}})),n.end();if(e.path==="/v1/link/routes")return await n.head(200,{"content-type":"application/json"}),await n.write(JSON.stringify({route:l.route,relay:C(t)?t.relay:null,gw:l.tunnel})),n.end();let r={};if(o)r=ze(e.headers);else for(const[m,y]of Object.entries(e.headers||{}))m.toLowerCase()!==ge&&m.toLowerCase()!==we&&(r[m]=y);r={...We(r),...Ye(t)};const s=e.method==="GET"?void 0:await e.body.bytes(),a=await N({method:e.method,path:e.path,headers:r,body:s,device:t.room}),d={};a.headers?.forEach?.((m,y)=>{d[y]=m});let f=!1;try{await n.head(a.status,d)}catch{f=!0}if(a.body){const m=/event-stream/.test(String(a.headers?.get?.("content-type")||""));for await(const y of je(Ke(a.body,m))){if(n.cancelled)break;if(!f)try{await n.write(y)}catch{f=!0}}}if(!f)return n.end()}async function*Ke(t,e){for await(const n of t){let o=n instanceof Uint8Array?n:new TextEncoder().encode(String(n));if(e){const r=new TextDecoder().decode(o);if(r.includes(": ping")){const s=r.replace(ct,"$1");if(!s)continue;o=new TextEncoder().encode(s)}}yield o}}function ie(t,e,n,o,r){return De({side:"laptop",keyPair:e,crypto:Z,psk:t.phoneKey?null:ne(n.psk),peerKey:t.phoneKey?ne(t.phoneKey):null,sendBytes:r,onRequest:(s,a)=>Ne(t,s,a),onSession:(s,a)=>{o.online=!0,o.attempts=0,t.lastSeen=w(),a.paired&&(t.phoneKey=O(a.peerKey),$(t)||(t.name=a.name||t.name||"Phone"),t.pairedAt=w(),t.pending=null,U(`link: paired ${t.name}`)),B()},onEnd:()=>{o.online=!1}})}async function I(t){if(!C(t))return;const e=v.get(t.room)||{attempts:0,stopped:!1,online:!1};if(v.set(t.room,e),e.stopped)return;const n=await K(),o=t.pending&&t.pending.expiresAt>w()?t.pending:null;if(!t.phoneKey&&!o){D(t.room,"the pairing code expired");return}const r=`${t.relay.replace(/^http/,"ws")}/v1/room/${t.room}`;let s;try{s=new Te(r,[Y,t.token])}catch(a){le(t,a?.message);return}s.binaryType="arraybuffer",e.ws=s,e.endpoint=ie(t,n,o,e,a=>{try{s.send(a)}catch{}}),s.onopen=()=>{if(e.stopped||v.get(t.room)!==e){try{s.close(1e3,"stopped")}catch{}return}clearInterval(e.keepalive),e.keepalive=setInterval(()=>{try{s.send("ping")}catch{}},it),e.keepalive.unref?.()},s.onmessage=a=>typeof a.data=="string"?e.endpoint.onText(a.data):e.endpoint.onBinary(new Uint8Array(a.data)),s.onclose=a=>{if(clearInterval(e.keepalive),e.online=!1,e.endpoint?.close("socket closed"),!e.stopped){if(a?.code===4003||a?.code===4004){q(t.room,"the relay removed the room");return}le(t,a?.code===4001?"replaced":a?.code===4008?"over the relay's budget":`closed ${a?.code||""}`,a?.code===4001?5:a?.code===4008?pt:null)}},s.onerror=()=>{}}function le(t,e,n=null){const o=v.get(t.room);if(!o||o.stopped)return;const r=n??Math.min(o.attempts,re.length-1);o.attempts++,clearTimeout(o.timer),o.timer=setTimeout(()=>I(t),re[r]),o.timer.unref?.(),U(`link: ${e}; again in ${re[r]/1e3}s`)}function X(t){const e=v.get(t);if(e){e.stopped=!0,clearTimeout(e.timer),clearInterval(e.keepalive),e.endpoint?.close("stopped");try{e.ws?.close(1e3,"stopped")}catch{}v.delete(t)}}function H(t,e=1e3,n="stopped"){const o=P.get(t);if(o?.ws){o.endpoint?.close(n);try{o.ws.close(e,n)}catch{}o.ws=null,o.endpoint=null,o.online=!1}}function D(t,e){const n=A(t);n&&!n.phoneKey&&n.relay&&V(t,"DELETE",n.token,null,n.relay).catch(()=>{}),q(t,e)}function q(t,e){X(t),H(t,4004,"room removed"),P.delete(t),u.rooms=u.rooms.filter(n=>n.room!==t),B(),U(`link: ${e}`)}function xe({route:t=null,relay:e=""}={}){const n=t||(e?"relay":l.route);if(!z(n))throw L(`unknown route "${n}" — one of ${he.map(r=>r.id).join(", ")}`);if(z(n).kind==="tunnel"){if(l.route!==n||!l.tunnel)throw L(`this gateway's ${z(n).label} door is not open — set it as the route first (chatpanel-gateway link route ${n} --gw <https address>), then pair`);return{route:n,relay:null,gw:l.tunnel,host:R(l.tunnel)}}if(n==="relay"){const r=e||(l.route==="relay"?l.relay:"");if(!r)throw L('the relay route needs the relay’s https address (--relay <url>), or "Your own relay" set as the route');let s;try{s=Be({id:"relay",url:r})}catch(a){throw L(a.message)}return{route:s.id,relay:s.url,gw:null,host:R(s.url)}}const o=S||Ve;return{route:"link",relay:o,gw:null,host:R(o)}}function ce({partner:t,scopes:e,route:n=null,relay:o="",folder:r=""}={}){const s=Qe(t),a=Ze(e),d=xe({route:n,relay:o});let f="";if(a.includes("agents")){try{f=String(r||"").trim()?qe(r,{name:s,home:_e}):Q({partner:{name:s}},T)}catch(m){throw L(m.message)}if(be&&!ht(f,J(T)))throw L(`this gateway runs confined and writes only ${J(T)} — leave the folder empty (the default is inside it), or run the gateway unconfined to use ${f}`)}return{via:d,folder:f,preview:Xe({partner:s,scopes:a,route:d.route,host:d.host,folder:f})}}return{previewPartner(t={}){return ce(t).preview},deviceNameOf(t){const e=A(t);return e?.phoneKey?String(e.name||""):""},partnerFolderOf(t){const e=A(t);if(!e||!$(e)||!e.phoneKey||!(e.scopes||[]).includes("agents"))return null;const n=Q(e,T);try{ee(n,{recursive:!0,mode:448})}catch{return null}return n},async pairPartner(t={}){const{via:e,preview:n,folder:o}=ce(t);if(o)try{ee(o,{recursive:!0,mode:448})}catch(h){throw L(`could not create ${o}: ${h.message}`)}const r=await K(),s=j(16),a=j(32),d=O(s),f=await G(a,s,"laptop"),m=await F(await G(a,s,"phone"));if(e.relay){const h=await V(d,"PUT",f,{laptop:await F(f),phone:m},e.relay);if(h.status!==200&&h.status!==201)throw new Error(`link: the relay refused the room (${h.status})`)}for(const h of u.rooms.filter(b=>!b.phoneKey&&$(b)))D(h.room,"a new partner code replaced this one");const y=w()+W,p={room:d,token:f,relay:e.relay,phoneVerifier:m,phoneKey:null,name:n.partner,pairedAt:null,lastSeen:null,pending:{psk:O(a),expiresAt:y},kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,...o?{folder:o}:{}};u.rooms.push(p),B();const x=Me({uri:fe({relay:e.relay,gw:e.gw,room:s,key:r.publicKey,secret:a,name:""}),expiresAt:y,route:e.route});return I(p),setTimeout(()=>{const h=A(d);h&&!h.phoneKey&&D(d,"the partner code expired")},W+1e3).unref?.(),U(`link: partner code issued for ${n.partner} (${n.scopes.join(", ")}; route ${e.route} via ${e.host})`),{code:x,expiresAt:y,room:d,kind:"partner",partner:{name:n.partner},scopes:n.scopes,route:e.route,host:e.host,...o?{folder:o}:{},preview:n}},async pair({name:t=k}={}){const e=await K(),n=j(16),o=j(32),r=O(n),s=await G(o,n,"laptop"),a=await G(o,n,"phone"),d=await F(a);if(l.relay){const p=await V(r,"PUT",s,{laptop:await F(s),phone:d},l.relay);if(p.status!==200&&p.status!==201)throw new Error(`link: the relay refused the room (${p.status})`)}for(const p of u.rooms.filter(x=>!x.phoneKey&&!$(x)))D(p.room,"a new pairing code replaced this one");const f=w()+W,m={room:r,token:s,relay:l.relay,phoneVerifier:d,phoneKey:null,name:"",pairedAt:null,lastSeen:null,pending:{psk:O(o),expiresAt:f}};u.rooms.push(m),B();const y=fe({relay:l.relay,gw:l.tunnel,room:n,key:e.publicKey,secret:o,name:String(t||"").slice(0,60)});return I(m),setTimeout(()=>{const p=A(r);p&&!p.phoneKey&&D(r,"the pairing code expired")},W+1e3).unref?.(),{uri:y,svg:ot(y,{ecc:"M"}),expiresAt:f,room:r}},status(){const t=e=>!!v.get(e.room)?.online||!!P.get(e.room)?.online;return{route:l.route,relay:l.relay,tunnel:l.tunnel,...l.problem?{problem:l.problem}:{},routes:he,setup:Je(l.route,{port:g,url:l.tunnel||""}),devices:u.rooms.filter(e=>e.phoneKey).map(e=>({id:e.room,kind:M(e),name:e.name||"Phone",pairedAt:e.pairedAt,lastSeen:e.lastSeen,online:t(e),...$(e)?{partner:{name:e.partner?.name||e.name},scopes:e.scopes||[],route:e.route||null,host:R(e.relay||"")||R(e.route===l.route&&l.tunnel||""),...(e.scopes||[]).includes("agents")?{folder:Q(e,T)}:{},...e.route&&z(e.route)?.kind==="tunnel"&&e.route!==l.route?{routeClosed:!0}:{}}:{},via:P.get(e.room)?.online?"tunnel":v.get(e.room)?.online?"relay":null,...e.relay&&!C(e)?{staleRelay:e.relay}:{},...!$(e)&&l.tunnel&&!e.phoneVerifier?{tunnelNeedsRelink:!0}:{}})),pairing:u.rooms.filter(e=>!e.phoneKey&&!$(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,connected:t(e)}))[0]||null,partnerPairing:u.rooms.filter(e=>!e.phoneKey&&$(e)&&e.pending?.expiresAt>w()).map(e=>({id:e.room,expiresAt:e.pending.expiresAt,partner:{name:e.name},scopes:e.scopes||[],route:e.route||null}))[0]||null}},async applySettings(t={}){l=se(t);for(const e of[...v.keys()]){const n=A(e);(!n||!C(n))&&X(e)}if(!l.tunnel)for(const e of[...P.keys()])H(e,1001,"the tunnel was switched off");u.rooms.length&&await K();for(const e of u.rooms)C(e)&&!v.has(e.room)&&I(e);return this.status()},async acceptTunnel(t,e,n){const o=decodeURIComponent(String(t.url||"").split("?")[0].slice(He.length));if(!l.tunnel)return oe(e,404,"not found");const r=A(o),s=String(t.headers["sec-websocket-protocol"]||"").split(",").map(E=>E.trim()).filter(Boolean),d=/^Bearer ([A-Za-z0-9_-]+)$/.exec(String(t.headers.authorization||""))?.[1]||(s.length===2&&s.includes(Y)?s.find(E=>E!==Y):null),f=r&&!r.phoneKey&&r.pending?.expiresAt>w()?r.pending:null,m=d?Buffer.from(await F(d)):null,y=r?.phoneVerifier?Buffer.from(r.phoneVerifier):null;if(!r||!r.phoneKey&&!f||!m||!y||m.length!==y.length||!tt(m,y))return oe(e,403,"not admitted");const p=P.get(o)||{connects:[]};if(P.set(o,p),p.connects=p.connects.filter(E=>w()-E<6e4),p.connects.length>=lt)return oe(e,429,"too many connects");p.connects.push(w());const x=await K(),h=nt(t,e,n,{protocol:Y});if(!h)return;H(o,4001,"replaced"),p.ws=h,p.online=!1;const b=ie(r,x,f,p,E=>{try{h.send(E)}catch{}});p.endpoint=b,h.onmessage=E=>{typeof E.data!="string"&&b.onBinary(new Uint8Array(E.data))},h.onclose=()=>{b.close("socket closed"),p.ws===h&&(p.ws=null,p.endpoint=null,p.online=!1)};const pe=JSON.stringify({t:"peer",up:!0});b.onText(pe),h.send(pe)},async remove(t){const e=A(t);if(!e)return!1;if(e.relay)try{await V(t,"DELETE",e.token,null,e.relay)}catch{}return q(t,"removed"),!0},async start(){if(u.rooms.length){await K();for(const t of u.rooms)I(t)}},stop(){for(const t of[...v.keys()])X(t);for(const t of[...P.keys()])H(t,1001,"going away")},get publicKey(){return _?.publicKey||null}}}export{ut as COMPANION_PATHS,bt as DEFAULT_RELAY,ge as ENTITLEMENT_HEADER,we as INSTALL_HEADER,W as PAIRING_TTL_MS,ft as PARTNER_DEVICES_REQUIRE_PRO,dt as companionMay,Nt as createLinkHost,ae as defaultLinkPath,mt as deviceMayLink,Lt as partnerDevicesOnDisk,Q as partnerFolderFor,ve as phoneMayLink};
|
package/src/lossless-store.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{mergeNoteRecords as S}from"@chatpanel/events/note-merge.js";const d
|
|
1
|
+
import{mergeNoteRecords as S}from"@chatpanel/events/note-merge.js";const s=d=>Number.isFinite(Number(d))?Number(d):0,y=20,_=new Set(["rev","host","at","baseRev"]);function R(d){return Array.isArray(d)?`[${d.map(R).join(",")}]`:d&&typeof d=="object"?`{${Object.keys(d).filter(t=>!_.has(t)&&!(t==="deletedAt"&&!d[t])).sort().map(t=>`${JSON.stringify(t)}:${R(d[t])}`).join(",")}}`:JSON.stringify(d??null)}const v=(d,t)=>R(d)===R(t),g=d=>Math.max(s(d?.updatedAt),s(d?.deletedAt));class M{constructor(t){this.db=t}init(){this.db.exec(`CREATE TABLE IF NOT EXISTS library(
|
|
2
2
|
id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
|
|
3
3
|
updated_at INTEGER NOT NULL DEFAULT 0, deleted_at INTEGER NOT NULL DEFAULT 0,
|
|
4
4
|
host TEXT NOT NULL DEFAULT '', seq INTEGER NOT NULL DEFAULT 0, at INTEGER NOT NULL DEFAULT 0,
|
|
5
5
|
record TEXT, sealed TEXT, bytes INTEGER NOT NULL DEFAULT 0,
|
|
6
6
|
stamp INTEGER NOT NULL DEFAULT 0
|
|
7
|
-
)`),this.db.exec("CREATE INDEX IF NOT EXISTS library_since ON library(stamp, id)");try{this.db.exec("ALTER TABLE library ADD COLUMN rev INTEGER NOT NULL DEFAULT 0")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS library_rev ON library(rev)"),this.db.exec("CREATE TABLE IF NOT EXISTS note_versions(id TEXT NOT NULL, rev INTEGER NOT NULL, host TEXT NOT NULL DEFAULT '', record TEXT NOT NULL, PRIMARY KEY(id, rev))"),this._rev=this.db.get("SELECT MAX(rev) m FROM library")?.m||0;const t=this.db.all("SELECT id FROM library WHERE rev = 0 ORDER BY stamp ASC, id ASC");if(t.length){this.db.exec("BEGIN");try{for(const i of t)this.db.run("UPDATE library SET rev = ? WHERE id = ?",[++this._rev,i.id]);this.db.exec("COMMIT")}catch(i){throw this.db.exec("ROLLBACK"),i}}return this}get rev(){return this._rev||0}get size(){return this.db.get("SELECT COUNT(*) c FROM library WHERE deleted_at = 0")?.c||0}get newest(){return this.db.get("SELECT MAX(stamp) m FROM library")?.m||0}stamp(t){const i=this.db.get("SELECT id, updated_at, deleted_at, at, rev FROM library WHERE id = ?",[t]);return i?{id:i.id,updatedAt:i.updated_at,deletedAt:i.deleted_at,at:i.at,rev:i.rev}:null}_wins(t,i,c,a){const e=this.stamp(t);if(!e)return!0;const r=Math.max(
|
|
8
|
-
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?)`,[t.id,E,String(t.title||""),e,r,String(i||""),
|
|
9
|
-
VALUES(?, ?, '', ?, 0, ?, ?, ?, NULL, ?, ?, ?, ?)`,[e.id,e.id.split(":")[0],r,String(e.host||""),
|
|
7
|
+
)`),this.db.exec("CREATE INDEX IF NOT EXISTS library_since ON library(stamp, id)");try{this.db.exec("ALTER TABLE library ADD COLUMN rev INTEGER NOT NULL DEFAULT 0")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS library_rev ON library(rev)"),this.db.exec("CREATE TABLE IF NOT EXISTS note_versions(id TEXT NOT NULL, rev INTEGER NOT NULL, host TEXT NOT NULL DEFAULT '', record TEXT NOT NULL, PRIMARY KEY(id, rev))"),this._rev=this.db.get("SELECT MAX(rev) m FROM library")?.m||0;const t=this.db.all("SELECT id FROM library WHERE rev = 0 ORDER BY stamp ASC, id ASC");if(t.length){this.db.exec("BEGIN");try{for(const i of t)this.db.run("UPDATE library SET rev = ? WHERE id = ?",[++this._rev,i.id]);this.db.exec("COMMIT")}catch(i){throw this.db.exec("ROLLBACK"),i}}return this}get rev(){return this._rev||0}get size(){return this.db.get("SELECT COUNT(*) c FROM library WHERE deleted_at = 0")?.c||0}get newest(){return this.db.get("SELECT MAX(stamp) m FROM library")?.m||0}stamp(t){const i=this.db.get("SELECT id, updated_at, deleted_at, at, rev FROM library WHERE id = ?",[t]);return i?{id:i.id,updatedAt:i.updated_at,deletedAt:i.deleted_at,at:i.at,rev:i.rev}:null}_wins(t,i,c,a){const e=this.stamp(t);if(!e)return!0;const r=Math.max(s(i),s(c)),n=Math.max(s(e.updatedAt),s(e.deletedAt));return r!==n?r>n:s(a)>s(e.at)}upsert(t,i={}){return this.write(t,i).written}write(t,{host:i="",seq:c=0,at:a=Date.now(),merge:e=!1}={}){const r=[],n={},l=[],E=[];this.db.exec("BEGIN");try{for(const h of t||[]){if(!h||typeof h.id!="string"||!h.id.includes(":"))continue;const{baseRev:T,...o}=h;let p=s(o.updatedAt),u=s(o.deletedAt);if(!p&&!u)continue;if(T!=null){const A=this.stamp(o.id);if(s(A?.rev)!==s(T)){const L=e&&!u?this._mergeNote(o,s(T),a):null;if(!L){l.push(this.get(o.id));continue}const O=this._put(L,{host:i,seq:c,at:a});r.push(o.id),n[o.id]=O,E.push({...L,rev:O});continue}const N=A?Math.max(s(A.updatedAt),s(A.deletedAt))+1:0;u&&u<N?u=N:!u&&p<N&&(p=N),o.updatedAt=p,u&&(o.deletedAt=u)}else{if(!this._wins(o.id,p,u,a))continue;const A=this.stamp(o.id);if(A&&Math.max(s(A.updatedAt),s(A.deletedAt))===Math.max(p,u)&&v(this.get(o.id),o))continue}const b=this._put(o,{host:i,seq:c,at:a});r.push(o.id),n[o.id]=b}this.db.exec("COMMIT")}catch(h){throw this.db.exec("ROLLBACK"),this._rev=this.db.get("SELECT MAX(rev) m FROM library")?.m||0,h}return{written:r,revs:n,conflicts:l.filter(Boolean),merged:E}}_put(t,{host:i="",seq:c=0,at:a=0}={}){const e=s(t.updatedAt),r=s(t.deletedAt),n=r?null:JSON.stringify(t),l=++this._rev,E=t.kind||t.id.split(":")[0];return this.db.run(`INSERT OR REPLACE INTO library(id, kind, title, updated_at, deleted_at, host, seq, at, record, sealed, bytes, stamp, rev)
|
|
8
|
+
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?)`,[t.id,E,String(t.title||""),e,r,String(i||""),s(c),s(a),n,n?n.length:0,Math.max(e,r),l]),E==="note"&&n&&(this.db.run("INSERT OR REPLACE INTO note_versions(id, rev, host, record) VALUES(?, ?, ?, ?)",[t.id,l,String(i||""),n]),this.db.run("DELETE FROM note_versions WHERE id = ? AND rev NOT IN (SELECT rev FROM note_versions WHERE id = ? ORDER BY rev DESC LIMIT ?)",[t.id,t.id,y])),l}noteVersions(t){return this.db.all("SELECT rev, host, record FROM note_versions WHERE id = ? ORDER BY rev DESC",[t]).map(i=>{try{return{rev:i.rev,host:i.host,record:JSON.parse(i.record)}}catch{return null}}).filter(Boolean)}_mergeNote(t,i,c){const a=this.get(t.id);if(!a||a.deletedAt||(a.kind||t.id.split(":")[0])!=="note")return null;const e=this.db.get("SELECT record FROM note_versions WHERE id = ? AND rev = ?",[t.id,i]);let r=null;try{r=e?JSON.parse(e.record):null}catch{r=null}if(!r)return null;const{host:n,at:l,rev:E,...h}=a,{record:T}=S({base:{title:r.title??"",tags:r.tags??[],markdown:r.body?.markdown??"",folder:r.body?.folder??null},ours:t,theirs:h,now:Math.max(s(c),s(a.updatedAt),s(t.updatedAt))+1});return T}async upsertEntries(t,{open:i=async()=>null}={}){const c=[];let a=0;for(const e of t||[]){if(!e||typeof e.id!="string"||!e.stamp)continue;const r=s(e.stamp.updatedAt),n=s(e.stamp.deletedAt);if(!r&&!n||!this._wins(e.id,r,n,e.at))continue;if(n){this.upsert([{id:e.id,kind:e.id.split(":")[0],updatedAt:r,deletedAt:n}],{host:e.host,seq:e.seq,at:e.at}),c.push(e.id);continue}let l=null;try{l=await i(e)}catch{l=null}if(l&&typeof l=="object")this.upsert([{...l,id:e.id,updatedAt:s(l.updatedAt)||r,deletedAt:0}],{host:e.host,seq:e.seq,at:e.at});else{const E=JSON.stringify(e.blob||null);this.db.run(`INSERT OR REPLACE INTO library(id, kind, title, updated_at, deleted_at, host, seq, at, record, sealed, bytes, stamp, rev)
|
|
9
|
+
VALUES(?, ?, '', ?, 0, ?, ?, ?, NULL, ?, ?, ?, ?)`,[e.id,e.id.split(":")[0],r,String(e.host||""),s(e.seq),s(e.at),E,E.length,r,++this._rev]),a+=1}c.push(e.id)}return{written:c,sealed:a}}get(t){return f(this.db.get("SELECT * FROM library WHERE id = ?",[t]))}since({since:t=0,cursor:i="",limit:c=200,kind:a=null,bytes:e=0,afterRev:r=null}={}){const n=Math.min(1e3,Math.max(1,s(c)||200));if(r!=null&&r!=="")return this._sinceRev(s(r),n,a,s(e));let l=s(t),E="";if(i){const N=String(i).indexOf(":");N>0&&(l=s(i.slice(0,N)),E=i.slice(N+1))}const h=[i?"(stamp > ? OR (stamp = ? AND id > ?))":"stamp > ?"],T=i?[l,l,E]:[l];a&&(h.push("kind = ?"),T.push(String(a)));const o=this.db.all(`SELECT * FROM library WHERE ${h.join(" AND ")} ORDER BY stamp ASC, id ASC LIMIT ?`,[...T,n+1]);let p=o.length>n,u=p?o.slice(0,n):o;const b=s(e);if(b>0){let N=0;const L=u.findIndex((O,m)=>(N+=s(O.bytes),m>0&&N>b));L>0&&(u=u.slice(0,L),p=!0)}const A=u.at(-1);return{records:u.map(f),next:p&&A?`${A.stamp}:${A.id}`:null}}_sinceRev(t,i,c,a){const e=["rev > ?"],r=[t];c&&(e.push("kind = ?"),r.push(String(c)));const n=this.db.all(`SELECT * FROM library WHERE ${e.join(" AND ")} ORDER BY rev ASC LIMIT ?`,[...r,i+1]);let l=n.length>i,E=l?n.slice(0,i):n;if(a>0){let h=0;const T=E.findIndex((o,p)=>(h+=s(o.bytes),p>0&&h>a));T>0&&(E=E.slice(0,T),l=!0)}return{records:E.map(f),next:l&&E.length?String(E.at(-1).rev):null,rev:this.rev}}stamps(){return this.db.all("SELECT id, updated_at, deleted_at FROM library").map(t=>({id:t.id,updatedAt:t.updated_at,deletedAt:t.deleted_at}))}clear(){const t=this.db.get("SELECT COUNT(*) c FROM library")?.c||0;return this.db.exec("DELETE FROM library"),t}}function f(d){if(!d)return null;const t=s(d.rev);if(d.deleted_at)return{id:d.id,kind:d.kind,updatedAt:d.updated_at,deletedAt:d.deleted_at,host:d.host,at:d.at,rev:t};if(d.record)try{return{...JSON.parse(d.record),host:d.host,at:d.at,rev:t}}catch{}let i=null;try{i=d.sealed?JSON.parse(d.sealed):null}catch{i=null}return{id:d.id,kind:d.kind,updatedAt:d.updated_at,deletedAt:0,sealed:i,host:d.host,at:d.at,rev:t}}export{M as LosslessStore,y as NOTE_VERSIONS_KEPT,v as sameContent};
|
package/src/model-hashes.json
CHANGED
|
@@ -1,3 +1,107 @@
|
|
|
1
1
|
{
|
|
2
|
-
"_README": "SHA-256
|
|
2
|
+
"_README": "SHA-256 of the curated models' weight files, keyed by model id then by path relative to the model's cache dir (~/.chatpanel/models/<org>/<name>/). GENERATED by tools/model-copies/to-module.mjs from the copies in huggingface.co/ChatPanel (copy_models.py hashed each file it downloaded from the pinned upstream commit) — do NOT hand-edit. model-integrity.js checks a freshly downloaded model against these and refuses a mismatch; a model or file not listed is warn-and-allow.",
|
|
3
|
+
"ChatPanel/indic-transcribe-core-int8": {
|
|
4
|
+
"cross_kv.onnx": "0aed59ffef5e77e2b957d42f742ea2645fed3ac49954b6a91dc8e629d7196c26",
|
|
5
|
+
"cross_kv.onnx.data": "022d88763437e56ac1156b3953c68a01c205b52627094a086d243b822f6e810b",
|
|
6
|
+
"decoder.onnx": "f858a610f1d3498a993d5eb0424ef888d96edc853be3b7aa32846b237d2c4a97",
|
|
7
|
+
"decoder.onnx.data": "c557a469b426ad424b0ed04c7422df44fc12131df2ae300b3f4bc92bdf50d05b",
|
|
8
|
+
"encoder.onnx": "fa49d702bf83d52327105736ded11aea2e6afcfcb1667182e6db36e5cc27f097",
|
|
9
|
+
"encoder.onnx.data": "66c3442b950a3ff5e18fc33db1d15069b7888235776bdc86824d6f99d728f9a5"
|
|
10
|
+
},
|
|
11
|
+
"ChatPanel/indictrans2-indic-en-int8": {
|
|
12
|
+
"cross_kv.onnx": "eb10975a209e5cb0abb01e0e272e236ae2455973e7702e82c0f9aa7193ee9db8",
|
|
13
|
+
"cross_kv.onnx.data": "dc560bf3c174c203df69d3d2bc323ba16e0d1901bfc49db853406f6fa5b8c918",
|
|
14
|
+
"decoder.onnx": "b848027adbd61f3d06dc3019d96f509ef19608d701cb32874b004ad7055927bd",
|
|
15
|
+
"decoder.onnx.data": "f64be74f42e7d2bc642881430df7d9fe28d9f7b3ccec46ad36e9d1a791a6747c",
|
|
16
|
+
"encoder.onnx": "b08c9150c013ebdc39fc91eb374e4b5acbbea609b7b86065d917be237fab7259",
|
|
17
|
+
"encoder.onnx.data": "523545913dfd3a76e8ca58d0b7d4fd74353a571e6e2525cf10d73006ed02b526"
|
|
18
|
+
},
|
|
19
|
+
"MoritzLaurer/ModernBERT-base-zeroshot-v2.0": {
|
|
20
|
+
"onnx/model_quantized.onnx": "d49899e1fa3b04701a3e38b8040119d5b089ca9c0774736a23d1f5c9d9e6571f"
|
|
21
|
+
},
|
|
22
|
+
"Xenova/all-MiniLM-L6-v2": {
|
|
23
|
+
"onnx/model_quantized.onnx": "afdb6f1a0e45b715d0bb9b11772f032c399babd23bfc31fed1c170afc848bdb1"
|
|
24
|
+
},
|
|
25
|
+
"Xenova/bert-base-NER": {
|
|
26
|
+
"onnx/model_quantized.onnx": "caaee70a5518ec7f9e46e5308fcc9263a8c227703a9ce46cf61c69a552349648"
|
|
27
|
+
},
|
|
28
|
+
"Xenova/bert-base-multilingual-cased-ner-hrl": {
|
|
29
|
+
"onnx/model_quantized.onnx": "5b65139844be260b624a2a13782b01d122e613d64ce16ed0ba4d82e0b816f1a9"
|
|
30
|
+
},
|
|
31
|
+
"Xenova/bge-reranker-base": {
|
|
32
|
+
"onnx/model_quantized.onnx": "dd98f3e67837d23210a6b7550c08cced4f61845b940ac45be3565840a10f3244"
|
|
33
|
+
},
|
|
34
|
+
"Xenova/distilbert-base-multilingual-cased-ner-hrl": {
|
|
35
|
+
"onnx/model_quantized.onnx": "24a0b98f4dd4cd92842f5a541272f86f760225a64a29928eddef14bdb2edb986"
|
|
36
|
+
},
|
|
37
|
+
"Xenova/ms-marco-TinyBERT-L-2-v2": {
|
|
38
|
+
"onnx/model_quantized.onnx": "026c2ec3257cd351696e45bbd6040bb83cf818ba89059b4344bd6350138b62ce"
|
|
39
|
+
},
|
|
40
|
+
"Xenova/multilingual-e5-small": {
|
|
41
|
+
"onnx/model_quantized.onnx": "f80102d3f2a1229f387d3c81909990d8945513e347b0eab049f7de3c6f98c193"
|
|
42
|
+
},
|
|
43
|
+
"Xenova/opus-mt-mul-en": {
|
|
44
|
+
"onnx/decoder_model_merged_quantized.onnx": "6add167a0cd3f78aa298b8f927d2e8645e33cb17df11e92967f0c5b5703c8c4d",
|
|
45
|
+
"onnx/encoder_model_quantized.onnx": "5ce609a524375dbdd9c66b62b82b41abc667799022667ce424f20c245bd56925"
|
|
46
|
+
},
|
|
47
|
+
"Xenova/speecht5_hifigan": {
|
|
48
|
+
"onnx/model_quantized.onnx": "d092ea63bbc7839f7317657b5f531ebb68377ee05ec866ec096dba25911f9feb"
|
|
49
|
+
},
|
|
50
|
+
"Xenova/speecht5_tts": {
|
|
51
|
+
"onnx/decoder_model_merged_quantized.onnx": "6afe602f82ecdb34a2db003f45ccc1419c77aaf0032c263b4f6a0f8bf5835798",
|
|
52
|
+
"onnx/decoder_postnet_and_vocoder_quantized.onnx": "d092ea63bbc7839f7317657b5f531ebb68377ee05ec866ec096dba25911f9feb",
|
|
53
|
+
"onnx/encoder_model_quantized.onnx": "407375255d220d8ddf81e9a06d4100f80f870f8446e77d4f20951d2a4c08a156"
|
|
54
|
+
},
|
|
55
|
+
"fastrepl/dtln-aec-128": {
|
|
56
|
+
"model_128_1.onnx": "a060e46a6bebed03d6360262d814851dc6c2806cec7c1b6a388e617cae7c082c",
|
|
57
|
+
"model_128_2.onnx": "6b6e312f701a3fad2aac2981ca1ed978d25dffa0bc8da9f33235a2e91f56705a"
|
|
58
|
+
},
|
|
59
|
+
"istupakov/parakeet-tdt-0.6b-v3-onnx": {
|
|
60
|
+
"decoder_joint-model.int8.onnx": "eea7483ee3d1a30375daedc8ed83e3960c91b098812127a0d99d1c8977667a70",
|
|
61
|
+
"encoder-model.int8.onnx": "6139d2fa7e1b086097b277c7149725edbab89cc7c7ae64b23c741be4055aff09",
|
|
62
|
+
"nemo128.onnx": "a9fde1486ebfcc08f328d75ad4610c67835fea58c73ba57e3209a6f6cf019e9f"
|
|
63
|
+
},
|
|
64
|
+
"jinaai/jina-reranker-v1-tiny-en": {
|
|
65
|
+
"onnx/model_quantized.onnx": "5fa8508528828b4ad9bc97c97b6e020984e3b745fbcb53f0a907e68704f8a18a"
|
|
66
|
+
},
|
|
67
|
+
"onnx-community/Kokoro-82M-v1.0-ONNX": {
|
|
68
|
+
"onnx/model.onnx": "8fbea51ea711f2af382e88c833d9e288c6dc82ce5e98421ea61c058ce21a34cb",
|
|
69
|
+
"onnx/model_quantized.onnx": "fbae9257e1e05ffc727e951ef9b9c98418e6d79f1c9b6b13bd59f5c9028a1478"
|
|
70
|
+
},
|
|
71
|
+
"onnx-community/Kokoro-82M-v1.1-zh-ONNX": {
|
|
72
|
+
"onnx/model.onnx": "94b973941b1852754f979be5d5e20be666d5c81d9bb886b88ae1dc85c9b895ca",
|
|
73
|
+
"onnx/model_quantized.onnx": "a39469be791eeaa3089c1ed5e58b8731d1f2462ea0e7dae2bc44388e58f973d8"
|
|
74
|
+
},
|
|
75
|
+
"onnx-community/multilang-pii-ner-ONNX": {
|
|
76
|
+
"onnx/model_quantized.onnx": "1d02f3829ad90d95dea5e64d35f5528f96d7b223c1e056a96075c6229a484356"
|
|
77
|
+
},
|
|
78
|
+
"onnx-community/pyannote-segmentation-3.0": {
|
|
79
|
+
"onnx/model_quantized.onnx": "93a3eb106923c9b76a7d8af07ac337dd24c2d0dcd20f1b6c55f21133e944d658"
|
|
80
|
+
},
|
|
81
|
+
"onnx-community/silero-vad": {
|
|
82
|
+
"onnx/model.onnx": "a4a068cd6cf1ea8355b84327595838ca748ec29a25bc91fc82e6c299ccdc5808"
|
|
83
|
+
},
|
|
84
|
+
"onnx-community/wespeaker-voxceleb-resnet34-LM": {
|
|
85
|
+
"onnx/model_quantized.onnx": "f73f647730ae440ae411c2241290f42ff5b2106dd3176c897fe6fbb1950d5393"
|
|
86
|
+
},
|
|
87
|
+
"onnx-community/whisper-base": {
|
|
88
|
+
"onnx/decoder_model_merged_quantized.onnx": "fa3ef9902734ce5ae6f9ef2bdb2ba9a6c4b5785b09f4f420ce036573dc9d090b",
|
|
89
|
+
"onnx/encoder_model_quantized.onnx": "5862993336bf33acd23736071aae2b32261d3b1b2f37780194460d4ef974dd46"
|
|
90
|
+
},
|
|
91
|
+
"onnx-community/whisper-large-v3-turbo": {
|
|
92
|
+
"onnx/decoder_model_merged_quantized.onnx": "61481bd3be3a445d5a4b9070e8f8b2c6cc4fbbbbdc9f0e7ed048a132b8b84e0d",
|
|
93
|
+
"onnx/encoder_model_quantized.onnx": "d2f853dc3254fdc0079f55dd4433ea716ac98ec5574d3b475f288f2a77cebba9"
|
|
94
|
+
},
|
|
95
|
+
"onnx-community/whisper-small": {
|
|
96
|
+
"onnx/decoder_model_merged_quantized.onnx": "ec07c3cbb64172c39791e26ee870a65ac22b458c36722bfe2776b3dbf741e0c9",
|
|
97
|
+
"onnx/encoder_model_quantized.onnx": "a43a83f3c5361cd591cfa7c36f14b43cf7cb22f47a415cc14a8d557be800fa92"
|
|
98
|
+
},
|
|
99
|
+
"onnx-community/whisper-tiny.en": {
|
|
100
|
+
"onnx/decoder_model_merged_quantized.onnx": "c0592d0749413c960569e1c7fb806b060d5d18f3ebad4a95cbf9a77dc6e9be52",
|
|
101
|
+
"onnx/encoder_model_quantized.onnx": "e93ec822f16a8fd264e7de972ad17d615ea7334b75a52d54c50c2e18dd503a25"
|
|
102
|
+
},
|
|
103
|
+
"openai/privacy-filter": {
|
|
104
|
+
"onnx/model_quantized.onnx": "a325fb5341567a73c94e91ec5e49060d38d9b16111f518ad34773039a0c9c098",
|
|
105
|
+
"onnx/model_quantized.onnx_data": "50f4c8c7f3c27fbc1fe16d4f74f6f7c3b74ba8f18a262e8b6911854c64c33a6d"
|
|
106
|
+
}
|
|
3
107
|
}
|
package/src/model-integrity.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as
|
|
1
|
+
import{createHash as y}from"node:crypto";import{readFileSync as u,existsSync as m,rmSync as g}from"node:fs";import{join as d}from"node:path";import{fileURLToPath as $}from"node:url";const f=$(new URL("./model-hashes.json",import.meta.url));let h=null;function k(e=f){if(h&&e===f)return h;let r={};try{const i=JSON.parse(u(e,"utf8"));for(const[n,t]of Object.entries(i))!n.startsWith("_")&&t&&typeof t=="object"&&(r[n]=t)}catch{r={}}return e===f&&(h=r),r}function w(e){return y("sha256").update(u(e)).digest("hex")}function x(e,{modelsDir:r,log:i=()=>{},manifest:n=k()}={}){const t=n[e];if(!t||Object.keys(t).length===0)return i(`[integrity] no recorded hashes for ${e} — skipping verification (run tools/gen-model-hashes.mjs on a trusted host to enable)`),{verified:!1,reason:"unlisted",checked:0};const s=d(r,...e.split("/"));let o=0;for(const[c,l]of Object.entries(t)){const a=d(s,...c.split("/"));if(!m(a)){i(`[integrity] ${e}: listed file ${c} not on disk — skipping`);continue}const p=w(a);if(p!==l){try{g(a)}catch{}throw new Error(`[integrity] ${e}/${c} SHA-256 mismatch (expected ${l.slice(0,12)}…, got ${p.slice(0,12)}…) — deleted the file and refusing to load a tampered model`)}o++}return o&&i(`[integrity] ${e}: ${o} weight file(s) verified ✓`),{verified:o>0,reason:o?"ok":"no-files-present",checked:o}}async function F(e,r,{modelsDir:i,log:n=()=>{},dispose:t=null}={}){if(!e)return null;try{return x(r,{modelsDir:i,log:n})}catch(s){try{await t?.()}catch{}throw s}}export{k as loadHashManifest,w as sha256File,F as verifyFresh,x as verifyModelWeights};
|
package/src/model-sources.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MODEL_COPIES as
|
|
1
|
+
import{MODEL_COPIES as p}from"./model-copies.js";const h="https://huggingface.co/",m="https://dl.chatpanel.net/models/",y=/^https:\/\/(?:huggingface\.co|dl\.chatpanel\.net\/models)\/([^/]+\/[^/]+)\/resolve\/([^/]+)\/(.+)$/;function $(e){const n=y.exec(String(e||"").split("?")[0]);if(!n)return null;let t;try{t=decodeURIComponent(n[3])}catch{return null}return{id:n[1],rev:n[2],file:t}}const d=e=>e.split("/").map(encodeURIComponent).join("/");function R(e,{copies:n=p}={}){const t=$(e);if(!t)return[String(e)];const s=[],r=n[t.id],c=r&&(!r.files||r.files[t.file]);c&&s.push(`${h}${r.repo}/resolve/${r.revision}/${d(t.file)}`);const i=c&&t.rev==="main"&&r.upstreamRevision?r.upstreamRevision:t.rev;return s.push(`${h}${t.id}/resolve/${i}/${d(t.file)}`),s.push(`${m}${t.id}/resolve/${i}/${d(t.file)}`),[...new Set(s)]}function E(e=globalThis.fetch,{copies:n=p}={}){return async function(s,r){const c=typeof s=="string"?s:s?.url??String(s),i=R(c,{copies:n});if(i.length===1)return e(i[0],r);const g=$(c),v=i.find(l=>l.startsWith(`${h}${g.id}/`))||i[i.length-2],S=l=>l.status>=500||l.status===429;let u=null,a=null;for(const l of i){const f=l===v,x=l.startsWith(m);try{const o=await e(l,r);if(o.ok||o.status===304||f&&!S(o))return o;if((f||!u&&!x)&&(u=o,a=null),o!==u)try{await o.body?.cancel?.()}catch{}}catch(o){(f||!u&&!a)&&(a=o)}}if(u)return u;throw a||new Error(`model file unavailable: ${c}`)}}function M(e,{copies:n=p}={}){return n[e]||null}export{h as HF_HOST,m as MIRROR_HOST,M as modelCopy,E as modelFetch,$ as parseModelUrl,R as sourceUrls};
|
package/src/parakeet-engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{modelFetch as
|
|
2
|
-
`)){if(!
|
|
1
|
+
import{verifyFresh as et}from"./model-integrity.js";import{modelFetch as nt}from"./model-sources.js";import{join as i}from"node:path";import{existsSync as D,mkdirSync as ot,readFileSync as rt,createWriteStream as st,renameSync as at,statSync as C}from"node:fs";import{Readable as ct}from"node:stream";import{modelRoot as Y}from"./ner-engine.js";import{getOrt as it,ortProviders as ft}from"./ort.js";const lt=new Set(["nemo-conformer-tdt","nemo-conformer-rnnt","parakeet_tdt","parakeet-tdt","parakeet_rnnt"]);function St(t){return lt.has(String(t||"").trim())}const $="int8";function V(t){return t==="fp32"?"fp32":$}function W(t){const e=V(t)==="fp32"?"":".int8",n=["config.json","vocab.txt","nemo128.onnx",`encoder-model${e}.onnx`,`decoder_joint-model${e}.onnx`];return e||n.push("encoder-model.onnx.data"),n}function E(t){return i(Y(),...String(t).split("/"))}function ut(t,e=$){const n=E(t);if(!D(n))return!1;try{return W(e).every(r=>{const o=i(n,r);return D(o)&&C(o).size>0})}catch{return!1}}async function dt(t,e,n,{onProgress:r,log:o}={}){const a=`https://huggingface.co/${t}/resolve/main/${encodeURIComponent(e).replace(/%2F/g,"/")}`,s=await nt()(a,{redirect:"follow"});if(!s.ok||!s.body)throw new Error(`fetch ${e} → HTTP ${s.status}`);const f=Number(s.headers.get("content-length"))||0,l=i(n,`${e}.part`),u=st(l);let h=0,p=-1;const m=ct.fromWeb(s.body);m.on("data",g=>{if(h+=g.length,f){const c=Math.round(h/f*100);c!==p&&(p=c,r?.({file:e,pct:c}))}}),await new Promise((g,c)=>{m.pipe(u),u.on("finish",g),u.on("error",c),m.on("error",c)}),at(l,i(n,e)),o?.(`[parakeet] fetched ${e}`)}async function pt(t,e,{onProgress:n,log:r}={}){const o=E(t);ot(o,{recursive:!0});let a=!1;for(const s of W(e)){const f=i(o,s);D(f)&&C(f).size>0||(r?.(`[parakeet] downloading ${s}…`),await dt(t,s,o,{onProgress:n,log:r}),a=!0)}return await et(a,t,{modelsDir:Y(),log:r||(()=>{})}),o}function mt(t){const e=[];let n=-1;for(const r of rt(i(t,"vocab.txt"),"utf8").split(`
|
|
2
|
+
`)){if(!r)continue;const o=r.lastIndexOf(" ");if(o<0)continue;const a=parseInt(r.slice(o+1),10),s=r.slice(0,o);Number.isFinite(a)&&(e[a]=s.replace(/▁/g," "),s==="<blk>"&&(n=a))}return n<0&&(n=e.length-1),{vocab:e,blank:n}}function H(t,e,n){let r=e,o=t[e];for(let a=e+1;a<n;a++)t[a]>o&&(o=t[a],r=a);return r}const gt=5,K=10;async function vt({modelId:t,dtype:e=$,allowDownload:n=!0,onProgress:r,log:o=()=>{},sessionOptions:a=null}){const s=V(e),f=ut(t,s);if(!f&&!n)throw new Error("model not on disk and downloads disabled");const l=f?E(t):await pt(t,s,{onProgress:r,log:o}),u=await it(),h=s==="fp32"?"":".int8",p={executionProviders:ft(),graphOptimizationLevel:"all",logSeverityLevel:3,...a||{}},[m,g,c]=await Promise.all([u.InferenceSession.create(i(l,"nemo128.onnx"),p),u.InferenceSession.create(i(l,`encoder-model${h}.onnx`),p),u.InferenceSession.create(i(l,`decoder_joint-model${h}.onnx`),p)]),{vocab:X,blank:_}=mt(l),x=_+1,d=u.Tensor;async function q(w){if(!(w instanceof Float32Array)||w.length<400)return"";const P=w.length,I=await m.run({waveforms:new d("float32",w,[1,P]),waveforms_lens:new d("int64",BigInt64Array.from([BigInt(P)]),[1])}),O=await g.run({audio_signal:I.features,length:I.features_lens}),R=O.outputs,[,A,J]=R.dims,L=Number(O.encoded_lengths.data[0]),Q=R.data;let M=new Float32Array(2*640),N=new Float32Array(2*640);const y=[],z=new Float32Array(A);let b=0,k=0;const Z=L*(K+1)+8;for(let S=0;b<L&&S<Z;S++){for(let v=0;v<A;v++)z[v]=Q[v*J+b];const tt=y.length?y[y.length-1]:_,F=await c.run({encoder_outputs:new d("float32",z,[1,A,1]),targets:new d("int32",Int32Array.from([tt]),[1,1]),target_length:new d("int32",Int32Array.from([1]),[1]),input_states_1:new d("float32",M,[2,1,640]),input_states_2:new d("float32",N,[2,1,640])}),U=F.outputs.data,T=H(U,0,x),j=H(U,x,x+gt)-x;T!==_&&(M=F.output_states_1.data,N=F.output_states_2.data,y.push(T),k++),j>0?(b+=j,k=0):(T===_||k>=K)&&(b+=1,k=0)}let B="";for(const S of y)B+=X[S]??"";return B.replace(/^\s+/,"").replace(/\s+/g," ").trimEnd()}function G(){for(const w of[m,g,c])try{w.release?.()}catch{}}return{transcribe:q,dispose:G,dtype:s,dir:l}}export{$ as PARAKEET_DEFAULT_DTYPE,St as isTransducerModelType,vt as loadRecognizer,E as parakeetDir,V as parakeetDtype,ut as parakeetOnDisk};
|
package/src/segment-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{verifyFresh as $}from"./model-integrity.js";import{existsSync as S,readdirSync as T}from"node:fs";import{join as P}from"node:path";import{ensureLib as R,modelRoot as A,withModelSource as v}from"./ner-engine.js";import{runtimeDtype as h}from"./model-runtime.js";import{makeWarmTimer as b}from"./warm-timer.js";const k="onnx-community/pyannote-segmentation-3.0",U=6,F=16e3;let n="off",g=k,f=null,c=null,s=null,m=null,a=null,o=null,_=0,p=0,w=null;function W(){return g}function X(){return n}function x(){return n==="ready"&&!!f&&!!c}function H(){return a}function J(){return{configured:n!=="off",ok:x(),state:n,model:g,loaded:!!f,error:s,warmMs:o?.warmMs??null}}function y(){return _>0||p>0||n==="loading"||n==="downloading"}function K(){p++,o?.disarm()}function Q(){p=Math.max(0,p-1),p===0&&_===0&&x()&&o?.arm()}async function E({log:e=()=>{}}={}){if(y())return!1;o?.disarm();const r=f;if(f=null,c=null,w=null,m=null,a=null,s=null,n="off",r){try{await r.dispose?.()}catch{}e("[segment] idle — model unloaded (reloads on the next diarizing session)")}return!0}function O(e=g,r=h()){const l=P(A(),...e.split("/"),"onnx");if(!S(l))return!1;const t=r==="fp32"?"":r==="q8"?"_quantized":`_${r}`;try{return T(l).some(i=>i===`model${t}.onnx`)}catch{return!1}}async function z({log:e=()=>{},allowDownload:r=!0}={}){let l;try{l=await R()}catch(u){return n="error",s=u.message,e(`[segment] engine unavailable (${u.message})`),!1}if(!l.AutoModelForAudioFrameClassification)return n="error",s="this transformers.js has no audio frame classification",e(`[segment] ${s}`),!1;const t=g,i=O(t);if(!i&&!r)return n="error",s="model not on disk and downloads disabled",!1;n=i?"loading":"downloading",i||(a={model:t,file:null,pct:0},e(`[segment] downloading ${t} (one-time)…`));try{const u=d=>{if(!d)return;const L=typeof d.progress=="number"?Math.round(d.progress):a?.pct??0;(d.status==="progress"||d.status==="download"||d.status==="initiate")&&(a={model:t,file:d.file||a?.file||null,pct:L})},{processor:D,model:M}=await v({host:i?null:"https://huggingface.co/",allowRemote:!i},async()=>({processor:await l.AutoProcessor.from_pretrained(t,{progress_callback:u}),model:await l.AutoModelForAudioFrameClassification.from_pretrained(t,{dtype:h(),progress_callback:u})}));return await $(!i,t,{modelsDir:A(),log:e,dispose:()=>M.dispose?.()}),c=D,f=M,n="ready",s=null,a=null,e(`[segment] ready — ${t} @ ${h()} (speaker turns inside a segment)`),!0}catch(u){return s=u.message,a=null,n="error",e(`[segment] load failed (${u.message}) — one speaker per segment, as before`),!1}}function j(e){return e.then(r=>(r&&!y()&&o?.arm(),r))}function V(e={}){if(m&&n!=="error")return m;n="loading";const r=typeof e.onLog=="function"?e.onLog:()=>{};return o=b({warmMs:e.warmMs,busy:y,log:r,unload:()=>E({log:r})}),m=j(z({log:r,allowDownload:e.allowDownload!==!1})),m}async function Y(e){if(!x()||!(e instanceof Float32Array)||e.length<F/2)return null;_++;try{if(w)return await w(e);const r=await c(e),{logits:l}=await f(r),t=c.post_process_speaker_diarization(l,e.length);return Array.isArray(t?.[0])?t[0]:null}catch{return null}finally{_--,y()||o?.arm()}}function Z(){o?.disarm(),o=null,p=0,_=0,n="off",g=k,f=null,c=null,s=null,m=null,a=null}function ee(e,{warmMs:r=null}={}){w=e||null,f=e?{dispose:async()=>{}}:null,c=e?{}:null,n=e?"ready":"off",r!==null&&(o=b({warmMs:r,busy:y,unload:()=>E()}),e&&o.arm())}export{k as DEFAULT_SEGMENT_MODEL,F as SAMPLE_RATE,U as SEGMENT_MODEL_APPROX_MB,Z as _reset,ee as _setForTest,W as activeModel,J as health,V as init,x as isReady,O as modelOnDisk,H as progress,Q as release,K as retain,Y as spans,X as state,E as unload};
|