@chatpanel/gateway 0.154.4 → 0.155.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/kb.js +3 -3
- package/src/mcp.js +4 -1
- package/src/stt-engine.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.155.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.52.0",
|
|
27
|
-
"@chatpanel/events": "^0.
|
|
27
|
+
"@chatpanel/events": "^0.507.2",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/kb.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFileSync as oe,statSync as
|
|
2
|
-
`).find(
|
|
3
|
-
`));if(k&&x){const c=e.docs.find(a=>a.textHash===x&&a.id!==r);if(c)return{duplicateOf:c}}const T=o.path&&s.links?.length?Tt(o.path,s.links,{root:f||Ie(o.path)}):[],t=ie(e,{id:r,title:i||s.title||W(d),pages:s.pages,source:{kind:o.kind||"bytes",name:d,...o},hash:s.hash||"",type:s.type,reach:u,now:v,links:T,textHash:x,markdownHeadings:!!s.markdown});return{id:t.doc.id,title:t.doc.title,pages:t.doc.pages,chunks:t.doc.chunks,replaced:t.replaced,...s.scanned?{scanned:!0}:{}}}function _e(e,n){const d=Z(e).toLowerCase();return!Se.has(d)&&!Mt.has(d)?!1:n?.length?n.some(l=>{const i=String(l).toLowerCase().replace(/^\*/,"");return d===(i.startsWith(".")?i:`.${i}`)||e.toLowerCase().endsWith(i)}):!0}function fe(e,{recursive:n=!0,include:d=null}={}){const l=At(e,{home:H,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const i=me(Fe(e.replace(/^~(?=$|\/)/,H))),o=[],u=[];let r=0;const f=(x,T)=>{if(o.length>=U.files)return u.push({path:T,why:`stopped at ${U.files} files`}),!1;if(ve(x))return u.push({path:T,why:"withheld (a credential store)"}),!0;let t;try{t=ae(x)}catch{return!0}const c=Z(x).toLowerCase(),a=Se.has(c)||Lt.has(c)?le:U.textBytes;return t.size>a?(u.push({path:T,why:`too large (${Math.round(t.size/1048576)} MB)`}),!0):r+t.size>U.bytes?(u.push({path:T,why:"stopped: the folder is past the size limit"}),!1):(r+=t.size,o.push({full:x,rel:T,size:t.size,mtime:Math.floor(t.mtimeMs)}),!0)};if(!ae(i).isDirectory())return f(i,W(i)),{root:i,files:o,skipped:u,single:!0};const s=(x,T,t)=>{if(t>U.depth)return!0;let c=[];try{c=Be(x,{withFileTypes:!0}).sort((a,h)=>a.name.localeCompare(h.name))}catch{return!0}for(const a of c){const h=a.name;if(h.startsWith(".")&&a.isDirectory())continue;const w=De(x,h),p=T?`${T}/${h}`:h;if(a.isDirectory()){if(Et.has(h)||!n)continue;try{if(!me(w).startsWith(i)){u.push({path:p,why:"links outside the folder"});continue}}catch{continue}if(!s(w,p,t+1))return!1;continue}if(!(!a.isFile()&&!a.isSymbolicLink())){if(ve(w)){u.push({path:p,why:"withheld (a credential store)"});continue}if(_e(h,d)&&!f(w,p))return!1}}return!0};return s(i,"",0),{root:i,files:o,skipped:u}}async function Ee(e,{path:n,recursive:d=!0,include:l=null,title:i=""}){const{files:o,skipped:u,single:r}=fe(n,{recursive:d,include:l}),f=[];for(const k of o)try{const s=await V(e,oe(k.full),{name:W(k.full),title:f.length===0&&(r||!k.rel.includes("/"))?i:"",source:{kind:"file",path:k.full},reach:"internal"});f.push({...s,path:k.rel})}catch(s){u.push({path:k.rel,why:s.message})}return{added:f,skipped:u}}async function Pe(e,{path:n,include:d=null,rebuild:l=!1},{progress:i=null}={}){const{root:o,files:u,skipped:r}=fe(n,{recursive:!0,include:d}),f=vt(e,o,{include:d});if(l){for(const p of Object.values(f.files))p?.id&&q(e,p.id,{now:v});f.files={}}const k=new Set(u.map(p=>p.full));for(const[p,O]of Object.entries(f.files))O?.dupOf&&!k.has(O.dupOf)&&delete f.files[p];const s=yt({known:St(f),listing:u.map(p=>({path:p.full,size:p.size,mtime:p.mtime}))});i&&(i.total=s.add.length+s.change.length,i.done=0);const x=new Map(u.map(p=>[p.full,p])),T=[];for(const p of s.remove){q(e,p,{now:v});for(const[O,E]of Object.entries(f.files))E.id===p&&(delete f.files[O],T.push(O.startsWith(`${o}/`)?O.slice(o.length+1):O))}const t=[],c=[],a=[],h=p=>String(p||"").startsWith(`${o}/`)?p.slice(o.length+1):p,w=async(p,O)=>{if(i?.cancel)return;await new Promise(_=>setImmediate(_));const E=x.get(p),j=wt(p);try{const _=await V(e,oe(p),{name:W(p),source:{kind:"file",path:p},reach:"internal",id:j,root:o,dedupe:!0});_.duplicateOf?(e.docs.some(R=>R.id===j)&&q(e,j,{now:v}),f.files[p]={id:j,size:E.size,mtime:E.mtime,dupOf:_.duplicateOf.source?.path||_.duplicateOf.id},a.push({path:E.rel,of:h(_.duplicateOf.source?.path||_.duplicateOf.title)})):(f.files[p]={id:j,size:E.size,mtime:E.mtime},O.push({..._,path:E.rel}))}catch(_){r.push({path:E.rel,why:_.message})}i&&(i.done+=1)};for(const p of s.add)await w(p,t);for(const p of s.change)await w(p.path,c);return f.syncedAt=v(),f.lastSync={at:f.syncedAt,added:t.length,changed:c.length,removed:T.length,same:s.same,duplicates:a.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:a.slice(0,20)},{root:o,added:t,changed:c,removed:T,same:s.same,duplicates:a,skipped:r}}async function Ae(e,{url:n,title:d=""}){if(!G)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await G().read({url:n,format:"markdown"});if(l.status!==200)throw Object.assign(new Error(l.body?.error?.message||`read failed (${l.status})`),{code:"read_failed"});const i=String(l.body.markdown||l.body.text||"");if(!i.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const o=te(i).map((r,f)=>({page:f+1,text:r})),u=ie(e,{title:d||l.body.title||n,pages:o,source:{kind:"url",url:l.body.url||n,name:l.body.title||""},type:"html",reach:"web",now:v});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function je(e,n,{admin:d=!1}={}){const l=v();let i=[],o=[];if(n.kind==="bytes"){const r=Buffer.from(n.data,"base64");if(!r.length)return g(400,"invalid_request","kb: data decoded to nothing");if(r.length>le)return g(413,"too_large",`kb: ${r.length} bytes is over the ${le}-byte limit`);try{i.push(await V(e,r,{name:n.name,hint:n.type||"",title:n.title,reach:n.reach}))}catch(f){return Y(f)}}else if(n.kind==="path"){if(!d)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:i,skipped:o}=await Ee(e,n))}catch(r){return Y(r)}}else if(n.kind==="url")try{i.push(await Ae(e,n))}catch(r){return Y(r)}else if(n.kind==="text"){const r=te(n.text).map((k,s)=>({page:s+1,text:k})),f=ie(e,{title:n.title||n.name,pages:r,source:{kind:"text",name:n.name},type:"text",reach:n.reach,now:v});i.push({id:f.doc.id,title:f.doc.title,pages:f.doc.pages,chunks:f.doc.chunks,replaced:f.replaced})}const u=i.length?await I(e):0;return y.save(e),S({added:i,skipped:o,embedded:u,kb:P(e,d),ms:v()-l})}function Y(e){const n=e?.code||"";return n==="refused"?g(403,"refused",`kb: ${e.message}`):n==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):n==="too_large"?g(413,"too_large",`kb: ${e.message}`):n==="read_failed"||n==="empty"?g(502,"read_failed",`kb: ${e.message}`):n==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const Ke=e=>e.vectors?.model&&e.vectors.model!==N()?null:ne("query"),re=(e,n)=>Ue(e,n.query,{limit:n.limit,hops:n.hops,docs:n.docs||null,queries:n.queries||[],...n.filters?{filters:n.filters}:{},embed:Ke(e),rerank:n.rerank===!1?null:Te,now:v}),Le=(e,n)=>e.docs.find(d=>d.id===n)?.title||n,pe=(e,n)=>{const d=ce(e,n);if(!d)return null;const l=d.kind==="note"?"Note":Le(e,d.doc);return{...d,title:l,cite:d.kind==="note"?`[note ${d.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${d.page}]`}};function Me(e,n){ee(e);const d=n.node.replace(/^chunk:/,""),l=(/#\d+$/.test(d)&&ce(e,d)?{id:`chunk:${d}`,kind:"chunk",label:d}:null)||ke(e.graph,n.node);if(!l)return S({node:null,neighbours:[],message:`no node named "${n.node}"`});const i=r=>{const f=e.graph.nodes.find(k=>k.id===r);return{id:r,label:f?.label||r.replace(/^chunk:/,"passage "),kind:f?.kind||"chunk"}},o=Qe(e,l.id,{limit:Math.min(8,n.limit||6),...n.query?{query:n.query}:{}}),u={node:{id:l.id,kind:l.kind,label:l.label},neighbours:qe(e.graph,l.id,{hops:n.hops,kinds:n.kinds||null,limit:n.limit}),passages:o.passages,next:o.next};if(n.to){const r=ke(e.graph,n.to);u.to=n.to,u.path=r?(et(e.graph,l.id,r.id)||[]).map(i):null,r&&!u.path.length&&(u.path=null)}return S(u)}async function Ge(e,n,{admin:d=!1}={}){if(n.model&&!d)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=n.model&&typeof F=="function"?F(n.model):null,i=P(e,d),o=await Ze(n.question,{search:async(u,r)=>{const f=await re(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||n.docs||null});return f&&Array.isArray(f.results)?{...f,results:f.results.map(k=>({...k,kb:e.id}))}:f},outline:async u=>u?ye(e.chunks,{doc:u}):e.outline,read:async u=>{const r=pe(e,u);return r&&{...r,kb:e.id}},complete:l,kbName:e.name,docs:i.documents,previous:n.previous||null,answer:n.answer||"",ask:n.ask!==!1,now:v});return S({attachment:o.attachment,read:o.read,hits:o.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:o.queries,verdict:o.verdict,rounds:o.rounds,ask:o.ask,how:o.how,frame:{whole:o.frame.whole,docs:o.frame.docs},ms:o.ms})}const L=new Map;function he(e,n){const d=P(e,n),l=e.chunks.length?e.chunks.filter(o=>o.form||o.label).length/e.chunks.length:1,i=n?(e.sources||[]).map(o=>({kind:o.kind,syncedAt:o.syncedAt||0,...o.lastSync?{lastSync:{at:o.lastSync.at,added:o.lastSync.added,changed:o.lastSync.changed,removed:o.lastSync.removed,skipped:o.lastSync.skipped}}:{}})):(e.sources||[]).map(o=>({kind:o.kind,syncedAt:o.syncedAt||0}));return mt({...d,coverage:d.chunks?Math.round(d.vectors/d.chunks*100):0,placed:l,sources:i,...L.has(e.id)?{syncing:(({done:o,total:u})=>({done:o,total:u}))(L.get(e.id).progress)}:{}},{outline:e.outline,team:C(e.id),now:v()})}async function ze({method:e="GET",pathname:n="",query:d=new URLSearchParams,body:l=null,admin:i=!1,agent:o="",local:u=!0}={}){const r=nt(n);if(!r)return g(404,"not_found",`no route ${n}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(ht.includes(r.sub)&&!u)return g(501,"local_only",`kb: ${r.sub} acts on the computer this gateway runs on, and is not available on a remote gateway`);const f={admin:i,agent:String(o||d.get("agent")||"").trim().toLowerCase()},k=t=>{try{return{value:t()}}catch(c){return{res:g(400,"invalid_request",c.message)}}};if(!r.id){if(e==="GET"&&d.get("view")==="card"){const t=[];for(const{manifest:a}of y.list()){if(!de({access:a.access},f))continue;const h=y.load(a.id);h&&t.push(he(h,i))}const c=i&&typeof m=="function"?await m({admin:i}).catch(a=>[{gateway:"remote",error:a.message}]):[];return S({cards:t,...c.length?{remote:c}:{}})}if(e==="GET")return S({kbs:y.list().filter(({manifest:t})=>de({access:t.access},f)).map(({manifest:t})=>({id:t.id,name:t.name,docs:(t.docs||[]).length,updatedAt:t.updatedAt,vectors:t.vectors?.count||0,model:t.vectors?.model||"",access:t.access||{agents:"all"}}))});if(e==="POST"){const t=k(()=>st(l||{}));if(t.res)return t.res;const c=t.value;if(c.id&&y.load(c.id))return S({kb:P(y.load(c.id),i),existed:!0});const a=be({id:c.id,name:c.name,embed:c.embed,now:v});return y.save(a),{status:201,body:{kb:P(a,i)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!i)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(C(r.id))return J(r.id);const t=k(()=>ut(l||{}));if(t.res)return t.res;const c=t.value,a=L.get(r.id);if(a)return{status:202,body:{running:!0,progress:{...a.progress},kb:a.base?P(a.base,i):null}};let h=y.load(r.id);const w=!h;h||(h=be({id:r.id,name:c.name||W(String(c.path).replace(/[\\/]+$/,""))||r.id,now:v}),y.save(h));const p=v(),O={done:0,total:0},E=(async()=>{const b=await Pe(h,c,{progress:O});if(O.cancel)return{cancelled:!0};const M=b.added.length+b.changed.length+b.removed.length,B=b.added.length||b.changed.length?await I(h):0;return(M||w)&&y.save(h),{folder:b.root,added:b.added,changed:b.changed,removed:b.removed,same:b.same,duplicates:b.duplicates,skipped:b.skipped,embedded:B,made:w,kb:P(h,i),ms:v()-p}})();L.set(r.id,{progress:O,base:h}),E.catch(b=>z(`[kb] ${r.id}: sync failed — ${b?.message||b}`)).finally(()=>L.delete(r.id));const j=c.waitMs??5e3;if(j===0)return{status:202,body:{running:!0,progress:{...O},made:w,kb:P(h,i)}};let _=null;const R=new Promise(b=>{_=setTimeout(()=>b(null),j)});let Q;try{Q=await Promise.race([E,R])}catch(b){return clearTimeout(_),Y(b)}return clearTimeout(_),Q?S(Q):{status:202,body:{running:!0,progress:{...O},made:w,kb:P(h,i)}}}const s=y.load(r.id);if(!s)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const x=C(s.id)?.role==="replica",T=!!C(s.id);if(!de(s,f))return g(404,"not_found",`kb: no knowledge base ${r.id} for ${f.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){L.has(s.id)||ue(s);const t=P(s,i),c=i?(s.sources||[]).map(a=>({kind:a.kind,path:a.path,files:Object.keys(a.files||{}).length,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:a.lastSync}:{}})):void 0;return S({kb:{...t,coverage:t.chunks?Math.round(t.vectors/t.chunks*100):0,bytes:y.sizeOf(s.id),dir:i?y.dirOf(s.id):void 0,...c?.length?{sources:c}:{},...L.has(s.id)?{syncing:(({done:a,total:h})=>({done:a,total:h}))(L.get(s.id).progress)}:{}}})}if(e==="DELETE"){if(!i)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const t=L.get(s.id);return t&&(t.progress.cancel=!0),y.remove(s.id),S({ok:!0,...t?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(T&&(e==="POST"||e==="DELETE"))return J(s.id);if(e==="POST"&&!r.rest){const t=k(()=>rt(l||{}));return t.res?t.res:je(s,t.value,{admin:i})}if(e==="DELETE"&&r.rest)return i?q(s,r.rest,{now:v})?(y.save(s),S({ok:!0,kb:P(s,i)})):g(404,"not_found",`kb: no document ${r.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const t=Number(d.get("page"))||1,c=Ye(s,r.rest,t);return c?S(c):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return S({documents:P(s,i).documents});break}case"passages":{if(e==="GET"&&r.rest){const t=pe(s,r.rest);return t?S(t):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){ee(s);const t=d.get("doc");return S({outline:t?ye(s.chunks,{doc:t}):s.outline})}break}case"search":{if(e==="POST"){const t=k(()=>ot(l||{}));if(t.res)return t.res;const c=v(),a=await re(s,t.value);return ue(s),S({...a,ms:v()-c})}break}case"research":{if(e==="POST"){const t=k(()=>at(l||{}));return t.res?t.res:Ge(s,t.value,{admin:i})}break}case"graph":{if(e==="GET")return S(Gt(s,{limit:pt(d.get("limit"))}));if(e==="POST"){const t=k(()=>it(l||{}));return t.res?t.res:Me(s,t.value)}break}case"report":{if(e==="GET")return ee(s),{status:200,text:tt(s),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return S({notes:s.notes});if(x&&e==="POST")return J(s.id);if(e==="POST"&&!r.rest){const t=k(()=>ct(l||{}));if(t.res)return t.res;const c=t.value,a=c.status==="accepted"&&i?"accepted":"proposed",h=Re(s,{text:c.text,cites:c.cites||[],by:c.by||(i?"user":"agent"),status:a,now:v});return await I(s),y.save(s),{status:201,body:{note:h}}}if(e==="POST"&&r.rest){if(!i)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const t=k(()=>dt(l||{}));if(t.res)return t.res;const c=t.value,a=We(s,r.rest,c.status,{now:v});return a?(y.save(s),S({note:a,removed:c.status==="removed"})):g(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return S({access:s.access});if(x&&e==="POST")return J(s.id);if(e==="POST"){if(!i)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const t=k(()=>lt(l||{}));if(t.res)return t.res;const c=Je(s,t.value,{now:v});return y.save(s),S({access:c})}break}case"pages":{if(e!=="GET")break;const t=d.get("doc")||s.docs[0]?.id,c=s.docs.find(a=>a.id===t);return c?S(bt(s.chunks,c)):g(404,"not_found",`kb: no document ${t||""}`)}case"view":{if(e!=="GET")break;const t=d.get("original");if(t){const b=s.docs.find(Ce=>Ce.id===t),M=b?.source?.kind==="file"?String(b.source.path||""):"",B=$e[Z(M).toLowerCase()];if(!M||!B)return g(404,"not_found","kb: no original on this machine for that document");let ge;try{ge=oe(M)}catch{return g(404,"not_found","kb: the original is no longer where it was read")}return{status:200,text:ge,contentType:B,headers:{"content-security-policy":"sandbox","x-content-type-options":"nosniff"}}}const c=d.get("passage")||"",a=c&&ce(s,c);if(!a)return g(404,"not_found",`kb: no passage ${c.slice(0,80)}`);const h=s.docs.find(b=>b.id===a.doc)||{id:a.doc,title:a.doc},w=a.page||1,p=s.chunks.filter(b=>b.doc===a.doc&&(b.page||1)<=w&&(b.pageEnd||b.page||1)>=w),O=b=>{const M=s.chunks.find(B=>B.doc===a.doc&&(B.page||1)===b);return M?`?passage=${encodeURIComponent(M.id)}`:""},E=h.source?.kind==="file"?String(h.source.path||""):"",j=Z(E).toLowerCase(),_=String(a.text||"").replace(/\s+/g," ").trim().split(" ").slice(0,6).join(" "),R=h.source?.kind==="url"&&/^https?:\/\//.test(h.source.url||"")?`${h.source.url}#:~:text=${encodeURIComponent(_)}`:$e[j]?`?original=${encodeURIComponent(h.id)}${j===".pdf"?`#page=${w}`:""}`:"";return{status:200,text:kt({base:s.name||s.id,doc:{title:h.title,pages:h.pages,original:R},page:w,label:a.label||"",passages:p.map(b=>({id:b.id,text:b.text,section:b.section?String(b.section).split(" › ").slice(-2).join(" › "):""})),cited:a.id,prev:w>1?O(w-1):"",next:O(w+1)}),contentType:"text/html; charset=utf-8",headers:{"content-security-policy":"default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:","x-content-type-options":"nosniff","referrer-policy":"no-referrer"}}}case"reveal":{if(e!=="POST")break;if(!i)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(xe())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(C(s.id))return g(409,"not_on_disk","kb: a team base lives in its bucket — there is no file on this computer to show");if(typeof X!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const t=k(()=>ft(l||{}));if(t.res)return t.res;const c=t.value;let a="",h="file";if(c.doc){const w=s.docs.find(p=>p.id===c.doc);if(!w)return g(404,"not_found",`kb: no document ${c.doc}`);a=w.source?.path||"",a||(a=y.dirOf(s.id),h="index")}else if(c.source!=null){const w=(s.sources||[])[c.source];if(!w?.path)return g(404,"not_found",`kb: no kept folder ${c.source}`);a=w.path,h="folder"}else{const w=(s.sources||[]).find(p=>p.path);a=w?.path||y.dirOf(s.id),h=w?"folder":"index"}try{ae(a)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await X(a,{folder:h!=="file"})}catch(w){return g(502,"reveal_failed",`kb: the file manager did not open — ${w.message}`)}return S({ok:!0,revealed:h})}case"embed":{if(e==="POST"){const t=N(),c=$&&t?$.health("embed",t):{state:"off"},a=await I(s);return a&&y.save(s),S({embedded:a,vectors:s.vectors.by.size,model:s.vectors.model||t,dims:s.vectors.dims,state:c.state,...c.progress?{progress:c.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${n} is not a route`)}function J(e){return g(409,"read_only",`kb: ${e} is a team base kept in its bucket — add or remove documents in the bucket (POST /v1/context/providers/{id}/upload); the builder publishes the next index`)}return{handle:ze,store:y,embedModel:N,cardOf:he,addBytes:(e,n,d)=>V(e,n,d),embedAll:e=>I(e),searchBase:(e,n)=>re(e,n)}}export{U as KB_WALK_LIMITS,qt as createKbService,P as kbStatusFor,Gt as wholeGraph};
|
|
1
|
+
import{readFileSync as oe,statSync as ie,readdirSync as Ce,realpathSync as me}from"node:fs";import{join as De,basename as U,extname as Z,resolve as Fe,dirname as Ne}from"node:path";import Re from"node:os";import{createKb as be,addDocument as ae,removeDocument as q,addNote as We,setNoteStatus as Ue,searchKb as He,embedMissing as Xe,kbNeedsVectors as Ve,kbStatus as Ye,readPage as Je,chunkById as ce,refreshKb as ee,setKbAccess as Qe,kbMayUse as de,graphWalk as Ze}from"@chatpanel/events/kb-index.js";import{kbResearch as qe}from"@chatpanel/events/kb-research.js";import{neighbours as et,pathBetween as tt,resolveNode as ke,graphReport as nt}from"@chatpanel/events/kb-graph.js";import{outlineOf as ye}from"@chatpanel/events/kb-chunk.js";import{validateKbInstructions as st,setKbInstructions as rt,normalizeKbInstructions as we,kbInstructionsBlock as ot}from"@chatpanel/events/kb-instructions.js";import{routeKb as it,validateKbCreate as at,validateKbAdd as ct,validateKbSearch as dt,validateKbResearch as lt,validateKbGraph as ut,validateKbNote as ft,validateKbNoteStatus as pt,validateKbAccess as ht,validateKbSync as gt,validateKbReveal as mt,kbGraphLimit as bt,KB_LOCAL_ACTIONS as kt}from"@chatpanel/events/kb-capability.js";import{communities as yt,topEntities as ve}from"@chatpanel/events/kb-graph.js";import{kbCard as wt,pageStrip as vt}from"@chatpanel/events/kb-view.js";import{passagePageHtml as St}from"@chatpanel/events/kb-cite.js";import{planFolderSync as $t,folderDocId as xt,folderSource as Tt,knownFiles as Ot}from"@chatpanel/events/kb-folder-sync.js";import{htmlForIndex as _t,markdownLinks as Et,resolveLinks as Pt,visibleTextHash as At,decodeText as jt}from"@chatpanel/events/kb-html.js";import{secretReason as Se,SKIP_DIR_NAMES as Kt,sniffType as It,checkAttachablePath as Lt}from"@chatpanel/events/attached-paths.js";import{paginateText as te,MAX_DOCUMENT_BYTES as le}from"./extract-capability.js";import{defaultEmbeddedModel as Mt}from"./embedded-models.js";import{primaryProvider as Gt}from"./capability-config.js";function P(y,A){const x=Ye(y);return A?x:{...x,documents:x.documents.map(K=>{const{path:C,...M}=K.source||{};return{...K,source:M}})}}const H=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),$e=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),zt=new Set([".html",".htm",".xhtml"]),Bt=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),g=(y,A,x,K={})=>({status:y,body:{error:{type:A,message:x},...K}}),S=y=>({status:200,body:y});function Ct(y,{limit:A=60}={}){ee(y);const x=y.graph||{nodes:[],edges:[]},K=new Set(ve(x,{limit:A}).map(m=>m.id)),C=new Map(ve(x,{limit:A}).map(m=>[m.id,m.weight])),M=x.nodes.filter(m=>m.kind==="entity"?K.has(m.id)||m.type==="person"||m.type==="role":m.kind!=="chunk").slice(0,A*6),D=new Set(M.map(m=>m.id)),G=x.edges.filter(m=>D.has(m.from)&&D.has(m.to)),v=m=>m.kind==="holds"||m.kind==="member"||m.kind==="has",X=[...G.filter(v),...G.filter(m=>!v(m))].slice(0,A*20),z=yt(x).map(m=>({...m,members:m.members.filter(V=>D.has(V))})).filter(m=>m.members.length>=2).slice(0,24);return{nodes:M.map(m=>({id:m.id,kind:m.kind,label:m.label,count:m.count,...m.type?{type:m.type}:{},...m.doc?{doc:m.doc}:{},...C.has(m.id)?{weight:C.get(m.id)}:{}})),edges:X,communities:z,total:{nodes:x.nodes.length,edges:x.edges.length}}}const xe=Object.freeze({".pdf":"application/pdf",".txt":"text/plain; charset=utf-8",".md":"text/plain; charset=utf-8",".csv":"text/plain; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg"});function rn({store:y,extract:A=null,embedded:x=null,cfg:K={},rerank:C=null,read:M=null,completer:D=null,log:G=()=>{},now:v=()=>Date.now(),home:X=Re.homedir(),team:z=()=>null,remoteCards:m=null,reveal:V=null,confined:Te=()=>!1}={}){const N=()=>{const e=Gt(K.capabilities?.embed,"embed",{destinations:K.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||Mt("embed")||""},ne=(e="passage")=>{const s=N();if(!x||!s)return null;const d=x.health("embed",s);return d.state!=="ready"&&d.state!=="loading"&&!d.installed?(x.embed(s,["warm"],{kind:e}).catch(()=>{}),null):async l=>(await x.embed(s,l,{kind:e})).vectors},Oe=typeof C=="function"?C:null,se=new Set;function ue(e){!e||se.has(e.id)||e.embed==="off"||!ne("passage")||Ve(e)&&(se.add(e.id),F(e).then(s=>{s&&(y.save(e),G(`[kb] ${e.id}: ${s} passages given vectors (catch-up)`))}).catch(()=>{}).finally(()=>se.delete(e.id)))}async function F(e,{late:s=()=>!1}={}){const d=ne("passage");if(!d)return 0;try{return await Xe(e,d,{model:N(),late:s})}catch(l){return G(`[kb] ${e.id}: embedding failed — ${l.message}`),0}}async function _e(e,s,d=""){const l=It(e,s);if(l.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(l.text){const r=jt(e);if(/\.x?html?$/i.test(s)||/html/i.test(l.label||"")){const n=_t(r);return{type:"html",pages:te(n.markdown).map(($,T)=>({page:T+1,text:$})),title:n.title,links:n.links,markdown:!0}}const f=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(r.split(`
|
|
2
|
+
`).find(n=>n.trim())||""),k=/\.(md|markdown)$/i.test(s);return{type:l.label||"text",pages:te(r).map((n,$)=>({page:$+1,text:n})),title:f?f[1].trim():"",links:k?Et(r):[],markdown:k}}if(l.group!=="document")throw Object.assign(new Error(`${l.label||"binary"} is not a document`),{code:"unsupported"});if(!A)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const o=A(),i=await o.open(e,{name:s,hint:d}),u=[];for(let r=1;r<=i.pages;r+=1){let f="";try{f=String((await o.page(i.hash,r)).text||"")}catch(k){G(`[kb] ${s} p.${r}: ${k.message}`)}u.push({page:r,text:f,...i.labels?.[r-1]?{label:i.labels[r-1]}:{}})}return{type:i.type,pages:u,title:i.title||"",hash:i.hash,scanned:!!i.scanned,markdown:!!i.markdown,labels:i.labels||[]}}async function Y(e,s,{name:d,hint:l="",title:o="",source:i={},reach:u="",id:r="",root:f="",dedupe:k=!1}){const n=await _e(s,d,l),$=At(n.pages.map(c=>c.text).join(`
|
|
3
|
+
`));if(k&&$){const c=e.docs.find(a=>a.textHash===$&&a.id!==r);if(c)return{duplicateOf:c}}const T=i.path&&n.links?.length?Pt(i.path,n.links,{root:f||Ne(i.path)}):[],t=ae(e,{id:r,title:o||n.title||U(d),pages:n.pages,source:{kind:i.kind||"bytes",name:d,...i},hash:n.hash||"",type:n.type,reach:u,now:v,links:T,textHash:$,markdownHeadings:!!n.markdown});return{id:t.doc.id,title:t.doc.title,pages:t.doc.pages,chunks:t.doc.chunks,replaced:t.replaced,...n.scanned?{scanned:!0}:{}}}function Ee(e,s){const d=Z(e).toLowerCase();return!$e.has(d)&&!Bt.has(d)?!1:s?.length?s.some(l=>{const o=String(l).toLowerCase().replace(/^\*/,"");return d===(o.startsWith(".")?o:`.${o}`)||e.toLowerCase().endsWith(o)}):!0}function fe(e,{recursive:s=!0,include:d=null}={}){const l=Lt(e,{home:X,cwd:process.cwd()});if(!l.ok)throw Object.assign(new Error(l.reason||"that path cannot be attached"),{code:"refused"});const o=me(Fe(e.replace(/^~(?=$|\/)/,X))),i=[],u=[];let r=0;const f=($,T)=>{if(i.length>=H.files)return u.push({path:T,why:`stopped at ${H.files} files`}),!1;if(Se($))return u.push({path:T,why:"withheld (a credential store)"}),!0;let t;try{t=ie($)}catch{return!0}const c=Z($).toLowerCase(),a=$e.has(c)||zt.has(c)?le:H.textBytes;return t.size>a?(u.push({path:T,why:`too large (${Math.round(t.size/1048576)} MB)`}),!0):r+t.size>H.bytes?(u.push({path:T,why:"stopped: the folder is past the size limit"}),!1):(r+=t.size,i.push({full:$,rel:T,size:t.size,mtime:Math.floor(t.mtimeMs)}),!0)};if(!ie(o).isDirectory())return f(o,U(o)),{root:o,files:i,skipped:u,single:!0};const n=($,T,t)=>{if(t>H.depth)return!0;let c=[];try{c=Ce($,{withFileTypes:!0}).sort((a,p)=>a.name.localeCompare(p.name))}catch{return!0}for(const a of c){const p=a.name;if(p.startsWith(".")&&a.isDirectory())continue;const w=De($,p),h=T?`${T}/${p}`:p;if(a.isDirectory()){if(Kt.has(p)||!s)continue;try{if(!me(w).startsWith(o)){u.push({path:h,why:"links outside the folder"});continue}}catch{continue}if(!n(w,h,t+1))return!1;continue}if(!(!a.isFile()&&!a.isSymbolicLink())){if(Se(w)){u.push({path:h,why:"withheld (a credential store)"});continue}if(Ee(p,d)&&!f(w,h))return!1}}return!0};return n(o,"",0),{root:o,files:i,skipped:u}}async function Pe(e,{path:s,recursive:d=!0,include:l=null,title:o=""}){const{files:i,skipped:u,single:r}=fe(s,{recursive:d,include:l}),f=[];for(const k of i)try{const n=await Y(e,oe(k.full),{name:U(k.full),title:f.length===0&&(r||!k.rel.includes("/"))?o:"",source:{kind:"file",path:k.full},reach:"internal"});f.push({...n,path:k.rel})}catch(n){u.push({path:k.rel,why:n.message})}return{added:f,skipped:u}}async function Ae(e,{path:s,include:d=null,rebuild:l=!1},{progress:o=null}={}){const{root:i,files:u,skipped:r}=fe(s,{recursive:!0,include:d}),f=Tt(e,i,{include:d});if(l){for(const h of Object.values(f.files))h?.id&&q(e,h.id,{now:v});f.files={}}const k=new Set(u.map(h=>h.full));for(const[h,O]of Object.entries(f.files))O?.dupOf&&!k.has(O.dupOf)&&delete f.files[h];const n=$t({known:Ot(f),listing:u.map(h=>({path:h.full,size:h.size,mtime:h.mtime}))});o&&(o.total=n.add.length+n.change.length,o.done=0);const $=new Map(u.map(h=>[h.full,h])),T=[];for(const h of n.remove){q(e,h,{now:v});for(const[O,E]of Object.entries(f.files))E.id===h&&(delete f.files[O],T.push(O.startsWith(`${i}/`)?O.slice(i.length+1):O))}const t=[],c=[],a=[],p=h=>String(h||"").startsWith(`${i}/`)?h.slice(i.length+1):h,w=async(h,O)=>{if(o?.cancel)return;await new Promise(_=>setImmediate(_));const E=$.get(h),j=xt(h);try{const _=await Y(e,oe(h),{name:U(h),source:{kind:"file",path:h},reach:"internal",id:j,root:i,dedupe:!0});_.duplicateOf?(e.docs.some(W=>W.id===j)&&q(e,j,{now:v}),f.files[h]={id:j,size:E.size,mtime:E.mtime,dupOf:_.duplicateOf.source?.path||_.duplicateOf.id},a.push({path:E.rel,of:p(_.duplicateOf.source?.path||_.duplicateOf.title)})):(f.files[h]={id:j,size:E.size,mtime:E.mtime},O.push({..._,path:E.rel}))}catch(_){r.push({path:E.rel,why:_.message})}o&&(o.done+=1)};for(const h of n.add)await w(h,t);for(const h of n.change)await w(h.path,c);return f.syncedAt=v(),f.lastSync={at:f.syncedAt,added:t.length,changed:c.length,removed:T.length,same:n.same,duplicates:a.length,skipped:r.length,skippedSample:r.slice(0,20),duplicateSample:a.slice(0,20)},{root:i,added:t,changed:c,removed:T,same:n.same,duplicates:a,skipped:r}}async function je(e,{url:s,title:d=""}){if(!M)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const l=await M().read({url:s,format:"markdown"});if(l.status!==200)throw Object.assign(new Error(l.body?.error?.message||`read failed (${l.status})`),{code:"read_failed"});const o=String(l.body.markdown||l.body.text||"");if(!o.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const i=te(o).map((r,f)=>({page:f+1,text:r})),u=ae(e,{title:d||l.body.title||s,pages:i,source:{kind:"url",url:l.body.url||s,name:l.body.title||""},type:"html",reach:"web",now:v});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced}}async function Ke(e,s,{admin:d=!1}={}){const l=v();let o=[],i=[];if(s.kind==="bytes"){const r=Buffer.from(s.data,"base64");if(!r.length)return g(400,"invalid_request","kb: data decoded to nothing");if(r.length>le)return g(413,"too_large",`kb: ${r.length} bytes is over the ${le}-byte limit`);try{o.push(await Y(e,r,{name:s.name,hint:s.type||"",title:s.title,reach:s.reach}))}catch(f){return J(f)}}else if(s.kind==="path"){if(!d)return g(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:o,skipped:i}=await Pe(e,s))}catch(r){return J(r)}}else if(s.kind==="url")try{o.push(await je(e,s))}catch(r){return J(r)}else if(s.kind==="text"){const r=te(s.text).map((k,n)=>({page:n+1,text:k})),f=ae(e,{title:s.title||s.name,pages:r,source:{kind:"text",name:s.name},type:"text",reach:s.reach,now:v});o.push({id:f.doc.id,title:f.doc.title,pages:f.doc.pages,chunks:f.doc.chunks,replaced:f.replaced})}const u=o.length?await F(e):0;return y.save(e),S({added:o,skipped:i,embedded:u,kb:P(e,d),ms:v()-l})}function J(e){const s=e?.code||"";return s==="refused"?g(403,"refused",`kb: ${e.message}`):s==="unsupported"?g(415,"unsupported",`kb: ${e.message}`):s==="too_large"?g(413,"too_large",`kb: ${e.message}`):s==="read_failed"||s==="empty"?g(502,"read_failed",`kb: ${e.message}`):s==="timeout"?g(504,"extract_timeout","kb: the document took too long to parse"):g(500,"kb_error",`kb: ${e?.message||e}`)}const Ie=e=>e.vectors?.model&&e.vectors.model!==N()?null:ne("query"),re=(e,s)=>He(e,s.query,{limit:s.limit,hops:s.hops,docs:s.docs||null,queries:s.queries||[],...s.filters?{filters:s.filters}:{},embed:Ie(e),rerank:s.rerank===!1?null:Oe,now:v}),Le=(e,s)=>e.docs.find(d=>d.id===s)?.title||s,pe=(e,s)=>{const d=ce(e,s);if(!d)return null;const l=d.kind==="note"?"Note":Le(e,d.doc);return{...d,title:l,cite:d.kind==="note"?`[note ${d.id.slice(5)}]`:`[${l.replace(/[[\]]/g,"")} p.${d.page}]`}};function Me(e,s){ee(e);const d=s.node.replace(/^chunk:/,""),l=(/#\d+$/.test(d)&&ce(e,d)?{id:`chunk:${d}`,kind:"chunk",label:d}:null)||ke(e.graph,s.node);if(!l)return S({node:null,neighbours:[],message:`no node named "${s.node}"`});const o=r=>{const f=e.graph.nodes.find(k=>k.id===r);return{id:r,label:f?.label||r.replace(/^chunk:/,"passage "),kind:f?.kind||"chunk"}},i=Ze(e,l.id,{limit:Math.min(8,s.limit||6),...s.query?{query:s.query}:{}}),u={node:{id:l.id,kind:l.kind,label:l.label},neighbours:et(e.graph,l.id,{hops:s.hops,kinds:s.kinds||null,limit:s.limit}),passages:i.passages,next:i.next};if(s.to){const r=ke(e.graph,s.to);u.to=s.to,u.path=r?(tt(e.graph,l.id,r.id)||[]).map(o):null,r&&!u.path.length&&(u.path=null)}return S(u)}async function Ge(e,s,{admin:d=!1}={}){if(s.model&&!d)return g(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const l=s.model&&typeof D=="function"?D(s.model):null,o=P(e,d),i=await qe(s.question,{search:async(u,r)=>{const f=await re(e,{query:u,limit:r.limit||10,hops:r.hops??1,docs:r.docs||s.docs||null});return f&&Array.isArray(f.results)?{...f,results:f.results.map(k=>({...k,kb:e.id}))}:f},outline:async u=>u?ye(e.chunks,{doc:u}):e.outline,read:async u=>{const r=pe(e,u);return r&&{...r,kb:e.id}},complete:l,kbName:e.name,docs:o.documents,previous:s.previous||null,answer:s.answer||"",ask:s.ask!==!1,now:v,instructions:ot([{name:e.name,instructions:e.instructions}])});return S({attachment:i.attachment,read:i.read,hits:i.hits.map(u=>({id:u.id,doc:u.doc,title:u.title,page:u.page,section:u.section,cite:u.cite,lanes:u.lanes,via:u.via})),queries:i.queries,verdict:i.verdict,rounds:i.rounds,ask:i.ask,how:i.how,frame:{whole:i.frame.whole,docs:i.frame.docs},ms:i.ms})}const I=new Map;function he(e,s){const d=P(e,s),l=e.chunks.length?e.chunks.filter(i=>i.form||i.label).length/e.chunks.length:1,o=s?(e.sources||[]).map(i=>({kind:i.kind,syncedAt:i.syncedAt||0,...i.lastSync?{lastSync:{at:i.lastSync.at,added:i.lastSync.added,changed:i.lastSync.changed,removed:i.lastSync.removed,skipped:i.lastSync.skipped}}:{}})):(e.sources||[]).map(i=>({kind:i.kind,syncedAt:i.syncedAt||0}));return wt({...d,coverage:d.chunks?Math.round(d.vectors/d.chunks*100):0,placed:l,sources:o,...I.has(e.id)?{syncing:(({done:i,total:u})=>({done:i,total:u}))(I.get(e.id).progress)}:{}},{outline:e.outline,team:z(e.id),now:v()})}async function ze({method:e="GET",pathname:s="",query:d=new URLSearchParams,body:l=null,admin:o=!1,agent:i="",local:u=!0}={}){const r=it(s);if(!r)return g(404,"not_found",`no route ${s}`);if(r.bad)return g(400,"invalid_request",`kb: "${r.bad}" is not a valid id or route`);if(kt.includes(r.sub)&&!u)return g(501,"local_only",`kb: ${r.sub} acts on the computer this gateway runs on, and is not available on a remote gateway`);const f={admin:o,agent:String(i||d.get("agent")||"").trim().toLowerCase()},k=t=>{try{return{value:t()}}catch(c){return{res:g(400,"invalid_request",c.message)}}};if(!r.id){if(e==="GET"&&d.get("view")==="card"){const t=[];for(const{manifest:a}of y.list()){if(!de({access:a.access},f))continue;const p=y.load(a.id);p&&t.push(he(p,o))}const c=o&&typeof m=="function"?await m({admin:o}).catch(a=>[{gateway:"remote",error:a.message}]):[];return S({cards:t,...c.length?{remote:c}:{}})}if(e==="GET")return S({kbs:y.list().filter(({manifest:t})=>de({access:t.access},f)).map(({manifest:t})=>({id:t.id,name:t.name,docs:(t.docs||[]).length,updatedAt:t.updatedAt,vectors:t.vectors?.count||0,model:t.vectors?.model||"",access:t.access||{agents:"all"}}))});if(e==="POST"){const t=k(()=>at(l||{}));if(t.res)return t.res;const c=t.value;if(c.id&&y.load(c.id))return S({kb:P(y.load(c.id),o),existed:!0});const a=be({id:c.id,name:c.name,embed:c.embed,now:v});return y.save(a),{status:201,body:{kb:P(a,o)}}}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}if(r.sub==="sync"){if(e!=="POST")return g(405,"method_not_allowed","kb: sync is POST");if(!o)return g(403,"forbidden","kb: keeping a folder needs the gateway token or the extension origin — a path is a read on this machine");if(z(r.id))return R(r.id);const t=k(()=>gt(l||{}));if(t.res)return t.res;const c=t.value,a=I.get(r.id);if(a)return{status:202,body:{running:!0,progress:{...a.progress},kb:a.base?P(a.base,o):null}};let p=y.load(r.id);const w=!p;p||(p=be({id:r.id,name:c.name||U(String(c.path).replace(/[\\/]+$/,""))||r.id,now:v}),y.save(p));const h=v(),O={done:0,total:0},E=(async()=>{const b=await Ae(p,c,{progress:O});if(O.cancel)return{cancelled:!0};const L=b.added.length+b.changed.length+b.removed.length,B=b.added.length||b.changed.length?await F(p):0;return(L||w)&&y.save(p),{folder:b.root,added:b.added,changed:b.changed,removed:b.removed,same:b.same,duplicates:b.duplicates,skipped:b.skipped,embedded:B,made:w,kb:P(p,o),ms:v()-h}})();I.set(r.id,{progress:O,base:p}),E.catch(b=>G(`[kb] ${r.id}: sync failed — ${b?.message||b}`)).finally(()=>I.delete(r.id));const j=c.waitMs??5e3;if(j===0)return{status:202,body:{running:!0,progress:{...O},made:w,kb:P(p,o)}};let _=null;const W=new Promise(b=>{_=setTimeout(()=>b(null),j)});let Q;try{Q=await Promise.race([E,W])}catch(b){return clearTimeout(_),J(b)}return clearTimeout(_),Q?S(Q):{status:202,body:{running:!0,progress:{...O},made:w,kb:P(p,o)}}}const n=y.load(r.id);if(!n)return g(404,"not_found",`kb: no knowledge base ${r.id} — POST /v1/kb to create one`);const $=z(n.id)?.role==="replica",T=!!z(n.id);if(!de(n,f))return g(404,"not_found",`kb: no knowledge base ${r.id} for ${f.agent||"this caller"} — the owner can grant it (POST /v1/kb/${r.id}/access)`);if(!r.sub){if(e==="GET"){I.has(n.id)||ue(n);const t=P(n,o),c=o?(n.sources||[]).map(a=>({kind:a.kind,path:a.path,files:Object.keys(a.files||{}).length,syncedAt:a.syncedAt||0,...a.lastSync?{lastSync:a.lastSync}:{}})):void 0;return S({kb:{...t,canInstruct:o&&!$,coverage:t.chunks?Math.round(t.vectors/t.chunks*100):0,bytes:y.sizeOf(n.id),dir:o?y.dirOf(n.id):void 0,...c?.length?{sources:c}:{},...I.has(n.id)?{syncing:(({done:a,total:p})=>({done:a,total:p}))(I.get(n.id).progress)}:{}}})}if(e==="DELETE"){if(!o)return g(403,"forbidden","kb: deleting needs the gateway token or the extension origin");const t=I.get(n.id);return t&&(t.progress.cancel=!0),y.remove(n.id),S({ok:!0,...t?{stoppedSync:!0}:{}})}return g(405,"method_not_allowed",`kb: ${e} is not allowed here`)}switch(r.sub){case"documents":{if(T&&(e==="POST"||e==="DELETE"))return R(n.id);if(e==="POST"&&!r.rest){const t=k(()=>ct(l||{}));return t.res?t.res:Ke(n,t.value,{admin:o})}if(e==="DELETE"&&r.rest)return o?q(n,r.rest,{now:v})?(y.save(n),S({ok:!0,kb:P(n,o)})):g(404,"not_found",`kb: no document ${r.rest}`):g(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&r.rest){const t=Number(d.get("page"))||1,c=Je(n,r.rest,t);return c?S(c):g(404,"not_found",`kb: no document ${r.rest}`)}if(e==="GET")return S({documents:P(n,o).documents});break}case"passages":{if(e==="GET"&&r.rest){const t=pe(n,r.rest);return t?S(t):g(404,"not_found",`kb: no passage ${r.rest}`)}break}case"outline":{if(e==="GET"){ee(n);const t=d.get("doc");return S({outline:t?ye(n.chunks,{doc:t}):n.outline})}break}case"search":{if(e==="POST"){const t=k(()=>dt(l||{}));if(t.res)return t.res;const c=v(),a=await re(n,t.value);ue(n);const p=we(n.instructions);return S({...a,...p?.text?{instructions:p}:{},ms:v()-c})}break}case"research":{if(e==="POST"){const t=k(()=>lt(l||{}));return t.res?t.res:Ge(n,t.value,{admin:o})}break}case"graph":{if(e==="GET")return S(Ct(n,{limit:bt(d.get("limit"))}));if(e==="POST"){const t=k(()=>ut(l||{}));return t.res?t.res:Me(n,t.value)}break}case"report":{if(e==="GET")return ee(n),{status:200,text:nt(n),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return S({notes:n.notes});if($&&e==="POST")return R(n.id);if(e==="POST"&&!r.rest){const t=k(()=>ft(l||{}));if(t.res)return t.res;const c=t.value,a=c.status==="accepted"&&o?"accepted":"proposed",p=We(n,{text:c.text,cites:c.cites||[],by:c.by||(o?"user":"agent"),status:a,now:v});return await F(n),y.save(n),{status:201,body:{note:p}}}if(e==="POST"&&r.rest){if(!o)return g(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const t=k(()=>pt(l||{}));if(t.res)return t.res;const c=t.value,a=Ue(n,r.rest,c.status,{now:v});return a?(y.save(n),S({note:a,removed:c.status==="removed"})):g(404,"not_found",`kb: no note ${r.rest}`)}break}case"access":{if(e==="GET")return S({access:n.access});if($&&e==="POST")return R(n.id);if(e==="POST"){if(!o)return g(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const t=k(()=>ht(l||{}));if(t.res)return t.res;const c=Qe(n,t.value,{now:v});return y.save(n),S({access:c})}break}case"instructions":{if(e==="GET")return S({instructions:we(n.instructions),canInstruct:o&&!$});if(e==="POST"){if($)return R(n.id);if(!o)return g(403,"forbidden","kb: setting a base's instructions needs the gateway token or the extension origin");const t=k(()=>st(l||{}));if(t.res)return t.res;const c=rt(n,t.value,{now:v});return y.save(n),S({instructions:c})}break}case"pages":{if(e!=="GET")break;const t=d.get("doc")||n.docs[0]?.id,c=n.docs.find(a=>a.id===t);return c?S(vt(n.chunks,c)):g(404,"not_found",`kb: no document ${t||""}`)}case"view":{if(e!=="GET")break;const t=d.get("original");if(t){const b=n.docs.find(Be=>Be.id===t),L=b?.source?.kind==="file"?String(b.source.path||""):"",B=xe[Z(L).toLowerCase()];if(!L||!B)return g(404,"not_found","kb: no original on this machine for that document");let ge;try{ge=oe(L)}catch{return g(404,"not_found","kb: the original is no longer where it was read")}return{status:200,text:ge,contentType:B,headers:{"content-security-policy":"sandbox","x-content-type-options":"nosniff"}}}const c=d.get("passage")||"",a=c&&ce(n,c);if(!a)return g(404,"not_found",`kb: no passage ${c.slice(0,80)}`);const p=n.docs.find(b=>b.id===a.doc)||{id:a.doc,title:a.doc},w=a.page||1,h=n.chunks.filter(b=>b.doc===a.doc&&(b.page||1)<=w&&(b.pageEnd||b.page||1)>=w),O=b=>{const L=n.chunks.find(B=>B.doc===a.doc&&(B.page||1)===b);return L?`?passage=${encodeURIComponent(L.id)}`:""},E=p.source?.kind==="file"?String(p.source.path||""):"",j=Z(E).toLowerCase(),_=String(a.text||"").replace(/\s+/g," ").trim().split(" ").slice(0,6).join(" "),W=p.source?.kind==="url"&&/^https?:\/\//.test(p.source.url||"")?`${p.source.url}#:~:text=${encodeURIComponent(_)}`:xe[j]?`?original=${encodeURIComponent(p.id)}${j===".pdf"?`#page=${w}`:""}`:"";return{status:200,text:St({base:n.name||n.id,doc:{title:p.title,pages:p.pages,original:W},page:w,label:a.label||"",passages:h.map(b=>({id:b.id,text:b.text,section:b.section?String(b.section).split(" › ").slice(-2).join(" › "):""})),cited:a.id,prev:w>1?O(w-1):"",next:O(w+1)}),contentType:"text/html; charset=utf-8",headers:{"content-security-policy":"default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:","x-content-type-options":"nosniff","referrer-policy":"no-referrer"}}}case"reveal":{if(e!=="POST")break;if(!o)return g(403,"forbidden","kb: showing a file needs the gateway token or the extension origin");if(Te())return g(403,"confined","kb: this gateway runs confined (--confined) and does not open windows on this computer");if(z(n.id))return g(409,"not_on_disk","kb: a team base lives in its bucket — there is no file on this computer to show");if(typeof V!="function")return g(501,"unavailable","kb: this gateway cannot open a file manager here");const t=k(()=>mt(l||{}));if(t.res)return t.res;const c=t.value;let a="",p="file";if(c.doc){const w=n.docs.find(h=>h.id===c.doc);if(!w)return g(404,"not_found",`kb: no document ${c.doc}`);a=w.source?.path||"",a||(a=y.dirOf(n.id),p="index")}else if(c.source!=null){const w=(n.sources||[])[c.source];if(!w?.path)return g(404,"not_found",`kb: no kept folder ${c.source}`);a=w.path,p="folder"}else{const w=(n.sources||[]).find(h=>h.path);a=w?.path||y.dirOf(n.id),p=w?"folder":"index"}try{ie(a)}catch{return g(410,"gone","kb: not found on disk — refresh the base")}try{await V(a,{folder:p!=="file"})}catch(w){return g(502,"reveal_failed",`kb: the file manager did not open — ${w.message}`)}return S({ok:!0,revealed:p})}case"embed":{if(e==="POST"){const t=N(),c=x&&t?x.health("embed",t):{state:"off"},a=await F(n);return a&&y.save(n),S({embedded:a,vectors:n.vectors.by.size,model:n.vectors.model||t,dims:n.vectors.dims,state:c.state,...c.progress?{progress:c.progress}:{}})}break}default:break}return g(405,"method_not_allowed",`kb: ${e} ${s} is not a route`)}function R(e){return g(409,"read_only",`kb: ${e} is a team base kept in its bucket — add or remove documents in the bucket (POST /v1/context/providers/{id}/upload); the builder publishes the next index`)}return{handle:ze,store:y,embedModel:N,cardOf:he,addBytes:(e,s,d)=>Y(e,s,d),embedAll:e=>F(e),searchBase:(e,s)=>re(e,s)}}export{H as KB_WALK_LIMITS,rn as createKbService,P as kbStatusFor,Ct as wholeGraph};
|
package/src/mcp.js
CHANGED
|
@@ -35,7 +35,10 @@ Then retry. History tools work without the bridge. [${r.message}]`}const t=o.ski
|
|
|
35
35
|
`)+`
|
|
36
36
|
|
|
37
37
|
Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(n==="open_skill"){let o;try{o=await $(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(t){return`Could not open "${e.name}": ${t.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return o.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(n==="read_skill_file"){const o=encodeURIComponent(String(e.name||"").trim()),t=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let r;try{r=await $(`/skills/${o}/file/${t}`)}catch(a){return`Could not read ${e.path}: ${a.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return r.text||"(empty)"}if(n.startsWith("kb_"))return re(n,e);if(n==="search_context")return oe(e);throw new Error(`unknown tool: ${n}`)}async function re(n,e={}){const s=String(e.kb||"").trim(),i=s?`/v1/kb/${encodeURIComponent(s)}`:"",c={"x-chatpanel-agent":String(m||"unknown").toLowerCase()},o=(t,r)=>d(t,{method:"POST",headers:{"content-type":"application/json",...c},body:JSON.stringify(r)});if(n==="kb_list"){const r=(await d("/v1/kb",{headers:c})).kbs||[];return r.length?[`${r.length} knowledge base${r.length===1?"":"s"}:`,...r.map(a=>`- ${a.id}: ${a.name} — ${a.docs} document${a.docs===1?"":"s"}${a.vectors?`, ${a.vectors} vectors`:""}`),"","kb_report <id> for the map, kb_search <id> for a question."].join(`
|
|
38
|
-
`):"No knowledge bases on this machine yet. The user builds one in ChatPanel (attach a folder or a document) or with `chatpanel kb build <path>`."}if(!s)return"Which knowledge base? kb_list gives the ids.";if(n==="kb_search"){const t=await o(`${i}/search`,{query:String(e.query||""),limit:Math.max(1,Math.min(30,Number(e.limit)||8)),...e.doc?{docs:[String(e.doc)]}:{},...Array.isArray(e.queries)?{queries:e.queries.map(String)}:{}});return
|
|
38
|
+
`):"No knowledge bases on this machine yet. The user builds one in ChatPanel (attach a folder or a document) or with `chatpanel kb build <path>`."}if(!s)return"Which knowledge base? kb_list gives the ids.";if(n==="kb_search"){const t=await o(`${i}/search`,{query:String(e.query||""),limit:Math.max(1,Math.min(30,Number(e.limit)||8)),...e.doc?{docs:[String(e.doc)]}:{},...Array.isArray(e.queries)?{queries:e.queries.map(String)}:{}});return`${t.instructions?.text?`Instructions from the administrator of this base — follow them when answering from it:
|
|
39
|
+
${t.instructions.text}
|
|
40
|
+
|
|
41
|
+
`:""}${M(t)}`}if(n==="kb_read"){if(e.id)try{const t=await d(`${i}/passages/${encodeURIComponent(String(e.id))}`,{headers:c});return`${t.cite||t.id}${t.section?` §${t.section}`:""}
|
|
39
42
|
${t.text}`}catch(t){return`No passage ${e.id}: ${t.message}. Search first; passage ids look like "d3f2a1b4c5d6#12".`}if(e.doc)try{const t=await d(`${i}/documents/${encodeURIComponent(String(e.doc))}?page=${Number(e.page)||1}`,{headers:c});return`${t.title} — page ${t.page} of ${t.pages}${t.page<t.pages?` (next: ${t.page+1})`:" (last page)"}
|
|
40
43
|
${t.text||"(no text on this page — an image or a scan)"}`}catch(t){return`No document ${e.doc}: ${t.message}. kb_status lists the ids.`}return"kb_read needs a passage id, or a document id with a page."}if(n==="kb_outline"){const[t,r]=await Promise.all([d(`${i}/outline${e.doc?`?doc=${encodeURIComponent(String(e.doc))}`:""}`,{headers:c}),d(i,{headers:c})]);return U(t.outline||[],r.kb)}if(n==="kb_graph")return D(await o(`${i}/graph`,{node:String(e.node||""),hops:Math.max(1,Math.min(3,Number(e.hops)||1)),...e.to?{to:String(e.to)}:{},...typeof e.query=="string"&&e.query.trim()?{query:e.query}:{}}));if(n==="kb_status")return H((await d(i,{headers:c})).kb);if(n==="kb_report"){const t=await fetch(`${f()}${i}/report`,{headers:c});if(!t.ok)throw new Error(`the gateway returned HTTP ${t.status} for the report`);return t.text()}if(n==="kb_note"){const r=(await o(`${i}/notes`,{text:String(e.text||""),cites:Array.isArray(e.cites)?e.cites.map(String):[]})).note||{};return`Noted (${r.status||"proposed"} — the user can accept it in ChatPanel): ${r.text}${r.cites?.length?` — cites ${r.cites.join(", ")}`:""}`}throw new Error(`unknown tool: ${n}`)}async function oe(n={}){const e={"x-chatpanel-agent":String(m||"unknown").toLowerCase()},s={...Array.isArray(n.pages)&&n.pages.length?{pages:n.pages.slice(0,2).map(Number)}:{},...n.section?{section:String(n.section)}:{},...n.form?{form:String(n.form)}:{}},i=await d("/v1/context",{method:"POST",headers:{"content-type":"application/json",...e},body:JSON.stringify({query:String(n.query||""),sources:Array.isArray(n.sources)&&n.sources.length?n.sources.map(String):["kb:*"],...Object.keys(s).length?{filters:s}:{},max_tokens:Math.max(200,Math.min(2e4,Number(n.max_tokens)||4e3))})}),c=Object.entries(i.providers||{}).filter(([,o])=>o.error).map(([o,t])=>`${o}: ${t.error}`);return[B(i),...c.length?["",`Not searched — ${c.join("; ")}`]:[]].join(`
|
|
41
44
|
`)}async function ie(n){const{id:e,method:s,params:i}=n||{},c=t=>({jsonrpc:"2.0",id:e,result:t}),o=(t,r)=>({jsonrpc:"2.0",id:e,error:{code:t,message:r}});try{switch(s){case"initialize":{m=i?.clientInfo?.name||m;const t=await X(),r=T(S()).some(a=>a.name==="delegate_task")?`
|
package/src/stt-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as ot}from"node:path";import{deflateSync as rt}from"node:zlib";import Oe from"node:os";import{existsSync as at,readdirSync as lt}from"node:fs";import{randomUUID as st}from"node:crypto";import{ensureLib as Re,modelRoot as Ce}from"./ner-engine.js";import{runtimeDtype as ue,runtimeName as Fe,DTYPE_SUFFIX as it}from"./model-runtime.js";import{verifyModelWeights as ct}from"./model-integrity.js";import{DEFAULT_STT_MODEL as $e,isEnglishOnly as me,sttModelDtype as _e,isKnownSttModel as ut,sttModelEngine as j}from"./stt-models.js";import*as X from"./parakeet-engine.js";import*as we from"./coreml-stt-engine.js";import*as le from"./indic-engine.js";import*as U from"./diarize-engine.js";import*as B from"./segment-engine.js";import{turnsFromSpans as He,mainLocal as Ue,timeByLocal as ft,audioOfLocal as dt}from"@chatpanel/events/speaker-turns.js";import{regroupSpeakers as gt,regroupThreshold as pt}from"@chatpanel/events/speaker-recluster.js";import{diarizeApproxMB as ht}from"./diarize-models.js";import*as se from"./translate-engine.js";import*as ne from"./indictrans-engine.js";import{rawOrtAvailable as mt}from"./ort.js";import*as z from"./vad-engine.js";import*as oe from"./echo-pair.js";import*as ye from"./aec-engine.js";import{pickSegmentLanguage as _t,detectTextLanguage as wt,needsTranslation as yt,localTranslatable as Mt,normalizeLanguages as Et,normalizeLanguage as St,decodeLanguages as Tt,lineLanguage as Lt,autoCandidates as At,AUTO_LEARN_CONFIDENCE as xt,AUTO_LEARN_SECONDS as kt,ANY_LANGUAGE_CONFIDENCE as bt,AUTO_LANGUAGES as vt}from"@chatpanel/events/speech-language.js";import*as Dt from"@chatpanel/events/speech-language.js";import{makeWarmTimer as Me}from"./warm-timer.js";const h=16e3,ze=h,Ge=3*h,Nt=2,Pt=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function Ot(e,t){if(t>Nt*h)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?Pt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const Rt=12,Ee=3;function Ct(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<Ee)return{text:String(e||"").trim(),removed:0,total:t.length};const n=a=>a.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let a=0;a<t.length;){let i=0,c=0;for(let s=1;s<=Rt&&a+s*Ee<=t.length;s++){let l=1;for(;a+(l+1)*s<=t.length&&t.slice(a+l*s,a+(l+1)*s).every((f,d)=>n(f)===n(t[a+d]));)l++;l>=Ee&&(l-1)*s>i&&(i=(l-1)*s,c=s)}i?(o.push(...t.slice(a,a+c)),r+=i,a+=c+i):(o.push(t[a]),a++)}return{text:o.join(" "),removed:r,total:t.length}}const Ft=.6,Ke=2.4;function je(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/rt(t).length}function $t(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function Ht({cores:e=Oe.availableParallelism?.()??Oe.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function ie(e){return{intraOpNumThreads:Ht(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Ut=.12,Be=.8,zt=.15,Gt=.5,Kt=1.2,Ie=(e,t)=>e>=Gt||e>=zt&&!(t<Kt),jt=.999,Bt=2.5;function Se(e={},t=1/0){return Ie(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}const It=.9,Wt=.5;function Xt(e={},t=1/0,n=null){const o=Se(e,t);if(!o||o==="en")return o;const r=e[o]??0;return r>=It?(n?.add(o),o):r>=Wt&&n?.has(o)?o:"en"}function Vt(e,t=[]){const n=[];return e.forEach((o,r)=>{const a=t[r]??o.lang,i=n[n.length-1];i&&i.lang===a?i.to=o.to:n.push({from:o.from,to:o.to,lang:a})}),n}function Yt(e,{base:t=null,rate:n=h}={}){const o=e||[],r=s=>{const[l,f]=Object.entries(s.scores||{}).sort((d,x)=>x[1]-d[1])[0]||[];return l&&l!=="en"&&f>=jt?l:null},a=new Array(o.length).fill(null);for(let s=0;s<o.length;){const l=r(o[s]);let f=s+1;if(l)for(;f<o.length&&r(o[f])===l;)f++;if(l&&(o[f-1].to-o[s].from)/n>=Bt)for(let d=s;d<f;d++)a[d]=l;s=f}const i=[];let c=t;return o.forEach((s,l)=>{a[l]?c=a[l]:c!=="en"&&Ie(s.scores?.en??0,(s.to-s.from)/n)&&(c="en");const f=i[i.length-1];f&&f.lang===c?f.to=s.to:i.push({from:s.from,to:s.to,lang:c})}),i}async function qt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:a,SPELLED_SHAPE_MIN:i}=Dt;if(typeof o!="function")return e;const c=[];let s=!1;for(const l of e){const f=o(l.text);if(!l.lang||l.lang==="en"||f.english<a&&!r(l.text)){c.push(l);continue}const d=f.words>=i&&f.shaped===f.words,x=[];for(let u=0;u+1<t.length;u++)t[u]>=l.from&&t[u+1]<=l.to&&x.push([t[u],t[u+1]]);if(x.length<2||d){const u=r(l.text)?await n(l.from,l.to,"en"):"";u?(c.push({...l,text:u,lang:"en"}),s=!0):c.push(l);continue}const T=[];for(const[u,p]of x){const N=await n(u,p,l.lang),k=o(N),re=k.words>0&&k.words-k.shaped<=(k.english>=1&&k.words>=3?1:0);T.push({from:u,to:p,text:N,near:re,lang:r(N)?"en":l.lang})}for(let u=!0;u;)u=!1,T.forEach((p,N)=>{p.lang!=="en"&&p.near&&(T[N-1]?.lang==="en"||T[N+1]?.lang==="en")&&(p.lang="en",u=!0)});if(!T.some(u=>u.lang==="en")){c.push(l);continue}const E=[];for(const u of T){const p=E[E.length-1];p&&p.lang===u.lang?(p.to=u.to,p.n++):E.push({from:u.from,to:u.to,lang:u.lang,n:1,text:u.text})}for(const u of E){const p=u.n===1&&u.lang===l.lang?u.text:await n(u.from,u.to,u.lang);p&&c.push({from:u.from,to:u.to,lang:u.lang,text:p})}s=!0}return s?c.reduce((l,f)=>{const d=l[l.length-1];return d&&d.lang===f.lang&&d.to===f.from?l[l.length-1]={...d,to:f.to,text:`${d.text} ${f.text}`}:l.push(f),l},[]):e}function Qt(e,t,{frame:n=Math.round(.03*h),minPause:o=Ut*h,minPiece:r=Be*h}={}){const a=[];let i=0,c=-1;for(let s=0;s+n<=e;s+=n){const l=t(s,s+n)===!1;if(l&&c<0&&(c=s),(!l||s+2*n>e)&&c>=0){const f=l?s+n:s,d=Math.round((c+f)/2);f-c>=o&&d-i>=r&&e-d>=r&&(a.push(d),i=d),c=-1}}return a}const Jt=.12;function Zt(e,t=Math.round(.03*h)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=ee(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Jt)}let w="off",A=null,m=null,D=null,Q=null,L=null,V=null,R=null;function en(e=A||$e,t=_e(e)||ue()){if(j(e)==="parakeet-tdt")return X.parakeetOnDisk(e,X.parakeetDtype(t));if(j(e)==="coreml-tdt")return we.coremlOnDisk(e);if(j(e)==="indic-canary")return le.indicOnDisk();const n=ot(Ce(),...e.split("/"),"onnx");if(!at(n))return!1;const o=it[t]??"";try{const r=lt(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(a=>a===`decoder_model_merged${o}.onnx`||a===`decoder_model${o}.onnx`)}catch{return!1}}function Bn(){return w}function fe(){return w==="ready"&&!!m}function In(){return L}function Wn(){return{configured:w!=="off",ok:fe(),state:w,model:A,dtype:V,runtime:Fe(),error:D,warmMs:R?.warmMs??null,vad:z.state()}}function Xn(){return!!R?.pending()}function ce(){return G.size>0||w==="loading"||w==="downloading"}async function Te({log:e=()=>{}}={}){if(ce())return!1;R?.disarm();const t=m;if(m=null,Q=null,V=null,L=null,D=null,w="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((R?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function We(e){return e.then(t=>(t&&!ce()&&R?.arm(),t))}async function Xe(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(j(e)==="parakeet-tdt")return tn(e,{log:t,allowDownload:n,dtype:o});if(j(e)==="coreml-tdt")return on(e,{log:t,allowDownload:n});if(j(e)==="indic-canary")return rn(e,{log:t,allowDownload:n,licenseAccepted:r});const a=m,i=A;let c;try{c=await Re()}catch(T){return w="error",D=`engine load failed: ${T.message}`,t(`[stt] transformers.js not available (${T.message}) — dictation falls back to the browser engine`),!1}const l=(o&&o!=="auto"?o:null)||_e(e)||ue(),f=en(e,l);if(c.env.allowRemoteModels=f?!1:!!n,!f&&!n)return w="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,x=!ut(e);if(!f&&x)try{c.env.remoteHost="https://huggingface.co/"}catch{}w=f?"loading":"downloading",f||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${x?", from Hugging Face":""})…`));try{const T=u=>{if(!u)return;const p=typeof u.progress=="number"?Math.round(u.progress):L?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?L={model:e,file:u.file||L?.file||null,pct:p}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let E;try{E=await c.pipeline("automatic-speech-recognition",e,{dtype:l,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:ie()}})}catch(u){if(f||x||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,E=await c.pipeline("automatic-speech-recognition",e,{dtype:l,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:ie()}})}if(!f)try{ct(e,{modelsDir:Ce(),log:t})}catch(u){try{await E.dispose?.()}catch{}throw u}if(m=E,A=e,w="ready",D=null,L=null,V=l,a&&a!==E)try{await a.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${l} (in-process, offline) — local dictation active`),!0}catch(T){return D=T.message,L=null,a?(m=a,A=i,w="ready"):w="error",t(`[stt] model load failed (${T.message})${a?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function tn(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=m,a=A,i=X.parakeetDtype(o&&o!=="auto"?o:nn()),c=X.parakeetOnDisk(e,i);if(!c&&!n)return w="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;w=c?"loading":"downloading",c||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const s=await X.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:ie(),onProgress:f=>{L={model:e,file:f.file||null,pct:typeof f.pct=="number"?f.pct:L?.pct??0}}}),l=async f=>({text:await s.transcribe(f)});if(l.__transducer=!0,l.dispose=()=>s.dispose(),m=l,A=e,w="ready",D=null,L=null,V=i,r&&r!==l)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(s){return D=s.message,L=null,r?(m=r,A=a,w="ready"):w="error",t(`[stt] model load failed (${s.message})${r?" — keeping previous model":""}`),!1}}function nn(){return X.PARAKEET_DEFAULT_DTYPE}const Ve="fp16";async function on(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=m,r=A,a=we.coremlOnDisk(e);if(!a&&!n)return w="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;w=a?"loading":"downloading",a||(L={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const c=await we.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:s=>{L={model:e,file:s.file||null,pct:typeof s.pct=="number"?s.pct:L?.pct??0}},onExit:s=>{m===i&&(m=null,Q=null,w="error",D=s,R?.disarm(),t(`[stt] ${s} — reloads on the next dictation`))}});if(i=async s=>({text:await c.transcribe(s)}),i.__transducer=!0,i.dispose=()=>c.dispose(),m=i,A=e,w="ready",D=null,L=null,V=Ve,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${c.version}, windows ${c.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return D=i.message,L=null,o?(m=o,A=r,w="ready"):w="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function rn(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=m,a=A,i=le.indicOnDisk();if(!i&&!n)return w="error",D="model not on disk and downloads disabled",!1;w=i?"loading":"downloading",i||(L={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{i||await le.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:l=>{L={model:e,file:l.file,pct:l.pct}}});const c=await le.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:ie(),log:t}),s=async(l,f={})=>c.transcribe(l,f);if(s.identify=(l,f)=>c.identify(l,f),s.__transducer=!0,s.__indic=!0,s.dispose=()=>c.dispose(),m=s,A=e,w="ready",D=null,L=null,V="int8",r&&r!==s)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${le.INDIC_LICENSE.attribution}`),!0}catch(c){return D=c.message,L=null,r?(m=r,A=a,w="ready"):w="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const an=30;function Ye({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=an||e==="download"?{allowDownload:!0}:null}function Le(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Ye({mode:e,onDisk:U.modelOnDisk(),ready:U.isReady(),approxMB:ht(U.activeModel())});if(r&&U.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Ae)return;const a=Ye({mode:e,onDisk:B.modelOnDisk(),ready:B.isReady(),approxMB:B.SEGMENT_MODEL_APPROX_MB});a&&B.init({allowDownload:a.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Ae=!1,xe=null;function ke(e={},{log:t=()=>{}}={}){e.vad!==!1&&(xe={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(z.state()==="off"||z.state()==="error")&&z.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function Vn(e={}){if(Q&&w!=="error")return Q;const t=typeof e.onLog=="function"?e.onLog:()=>{};return A=e.model||$e,Ae=e.segment===!1,w="loading",R=Me({warmMs:e.warmMs,busy:ce,log:t,unload:()=>Te({log:t})}),Q=We(Xe(A,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Le(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),ke(e,{log:t})),n)),Q}async function Yn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Ae=t.segment===!1);const o=j(e)==="parakeet-tdt"?X.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:X.PARAKEET_DEFAULT_DTYPE):j(e)==="coreml-tdt"?Ve:j(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:_e(e)||ue();if(e===A&&fe()&&V===o)return Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;R??=Me({warmMs:t.warmMs,busy:ce,log:n,unload:()=>Te({log:n})});const r=await We(Xe(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),ke(t,{log:n})),r}const ln=8,sn=12e4,cn=6e4,un=1200,de=12,fn=3,dn=1,gn=.8,pn=.5,hn=60,be=700,ve=.008,mn=.002,_n=4;function wn(e){return e>0?Math.min(ve,Math.max(mn,e*_n)):ve}function yn(e){const t=Math.round(.1*h),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=ee(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const qe=30,Mn=15e3,G=new Map,J=new Map;let Z=Promise.resolve();function qn(){return G.size}const En=300,Sn=3e3;function Tn(e){const t=Number(e);return Number.isFinite(t)?Math.min(Sn,Math.max(En,Math.round(t))):be}function Qn({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:a=!1,diarize:i=!1,vectors:c=!1,speakerLabel:s=null,endSilenceMs:l=be,interims:f=!0,remote:d=null,poll:x=!1,format:T="f32"}={}){if(G.size>=ln){const N=new Error("too many concurrent dictation sessions");throw N.code="too_many_sessions",N}const E=Array.isArray(t)?Et(t):null,u=typeof e=="string"&&e?e.slice(0,12):null,p={id:st(),format:T==="pcm16"?"pcm16":"f32",endSilenceMs:Tn(l),lang:E?E.length===1?E[0]:E.length?null:u:u,langs:E,lastLang:null,lastDecoded:null,learned:new Set,translateTo:St(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?oe.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!a,diarize:!!i,speakerLabel:typeof s=="string"&&s?s.slice(0,40):null,diarizer:i?new U.Diarizer:null,prints:i?[]:null,shown:new Map,regroupedAt:0,vectors:!!i&&c===!0,remote:d||null,interims:f!==!1&&!d,chunks:[],samples:0,listeners:new Set,poll:x?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return G.set(p.id,p),R?.disarm(),p.diarizer&&(U.retain(),B.retain()),p.translateTo&&(se.retain(),ne.retain()),p.echo&&ye.retain(),z.retain(),xe&&(z.state()==="off"||z.state()==="error")&&ke(xe),Qe(p),{id:p.id}}function ge(e){return G.get(String(e||""))||null}function Jn(e,t){const n=ge(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function I(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function Zn(e){const t=String(e||""),n=G.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=J.get(t);return o?(clearTimeout(o.timer),J.delete(t),o.session.poll.splice(0)):null}function eo(e){return J.get(String(e||""))?.session||null}function Qe(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>bn(e.id).catch(()=>{}),cn),e.idleTimer.unref?.()}function to(e,t){const n=ge(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(Qe(n),n.echo?.role==="mic"){oe.pushMic(n.echo,t),Je(n);return}n.echo?.role==="reference"&&oe.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,Je(n)}}function no(e){const t=ge(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),Z=Z.then(()=>De(t).catch(()=>{})),Z)}function oo(e,t="f32"){if(t==="pcm16"){const r=new Float32Array(Math.floor(e.length/2));for(let a=0;a<r.length;a++)r[a]=e.readInt16LE(a*2)/32768;return r}const n=e.length-e.length%4,o=new Float32Array(n/4);for(let r=0;r<o.length;r++)o[r]=e.readFloatLE(r*4);return o}function Je(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+un-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,Z=Z.then(()=>De(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function pe(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(Ze(e).subarray(t)),e.chunks=r,e.samples=r.reduce((a,i)=>a+i.length,0),e.lastInterim=""}function Ze(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function Ln(e,t,n){const o=h/100,r=Math.max(0,e.length-t),a=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(a<=i)return 0;const c=new Float32Array(a);for(let d=0;d<a;d++){let x=0;const T=r+d*o;for(let E=0;E<o;E++)x+=e[T+E]*e[T+E];c[d]=x/o}let s=-1,l=1/0,f=0;for(let d=0;d<i;d++)f+=c[d];for(let d=0;d+i<=a;d++)d>0&&(f+=c[d+i-1]-c[d-1]),f<l&&(l=f,s=d);return s<0?0:r+Math.round((s+i/2)*o)}function ee(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let a=t;a<n;a++)o+=e[a]*e[a];return Math.sqrt(o/r)}function An(e,t=ve){const n=Math.round(.02*h);let o=0,r=e.length;for(let a=0;a+n<=e.length;a+=n)if(ee(e,a,a+n)>=t){o=a;break}for(let a=e.length-n;a>=0;a-=n)if(ee(e,a,a+n)>=t){r=a+n;break}return r>o?e.subarray(o,r):e}async function et(e){try{const t=await Re(),n=m?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>h*8?e.subarray(0,h*8):e,r=await m.processor(o),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await m.model({...r,decoder_input_ids:a}),c={};for(const[s,l]of Object.entries(n.lang_to_id))c[s.slice(2,-2)]=Number(i.logits.data[l]);return c}catch{return null}}async function xn(e){const t=await et(e);if(!t)return null;let n=null,o=-1/0;for(const[r,a]of Object.entries(t))a>o&&(o=a,n=r);return n}async function De(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await oe.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!fe()||!e.samples)return;e.lastDecodeAt=Date.now();let n=Ze(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),a=Math.round((e.endSilenceMs||be)/1e3*h),i=yn(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const c=wn(e.noiseFloor);let s=null,l=null;z.isReady()&&(e.vad||=z.createStream(),await e.vad.advance(n,r)&&(s=e.vad.speechIn(r,r+n.length,z.ONSET),n.length>a&&(l=e.vad.speechIn(r+n.length-a,r+n.length,z.OFFSET))));const f=n.length>a&&(l!==null?!l:ee(n,n.length-a)<c);if(s===!1||s===null&&ee(n)<c){n.length>h*5&&(e.chunks=[n.subarray(n.length-h)],e.samples=h);return}let d=!1,x=null;if(e.diarizer&&!e.speakerLabel&&!t&&B.isReady()&&n.length>=fn*h){const g=await kn(n);g&&(x=n.subarray(g),n=n.subarray(0,g),d=!0)}if(!e.interims&&!t&&!f&&!d&&n.length<de*h)return;if(!d&&!t&&!f&&o>=de*h&&o<qe*h){const g=Ln(n,3*h,Math.round(.2*h));g>0&&g<n.length&&(x=n.subarray(g),n=n.subarray(0,g))}const T=!e.remote&&!me(A)&&!m?.__transducer;if(T&&!e.langs&&!e.lang&&!e.langTried&&n.length>=h){e.langTried=!0;const g=await xn(n);g&&(e.lang=g,I(e,{type:"language",lang:g}))}const E=t||f||d||o>=de*h;let u=e.lang;if(T&&e.langs&&!e.lang){const g=e.langs.length>0,C=g?Tt(e.langs):At([...e.learned]);if(C.length===1)u=C[0];else if(u=C.includes(e.lastDecoded)?e.lastDecoded:null,(E||!u)&&n.length>=h/2){const F=await et(n);if(F){const S=_t({scores:F,allowed:C,seconds:n.length/h,last:e.lastDecoded});u=!g&&!S.inherited&&S.confidence<bt?e.lastDecoded||"en":S.lang,!g&&E&&!S.inherited&&S.confidence>=xt&&n.length>=kt*h&&e.learned.add(S.lang)}}E&&u&&(e.lastDecoded=u)}let p="",N=null,k=null,re=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});p=g.text,re=g.lang||null}else{const g=m.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:Se}:e.lang?{lang:e.lang}:{langs:[...vt],last:e.lastLang,choose:(_,y)=>Xt(_,y,e.learned)}:me(A)?{}:{language:u||void 0,task:"transcribe"},C=m.__indic&&m.identify&&E&&g.langs&&n.length>=2*Be*h?Qt(n.length,(_=>(y,b)=>ee(n,y,b)>=_)(Zt(n))):[],F=[0,...C,n.length];let S=null;const Y=g.choose||Se;if(C.length){const _=await m.identify(n,{langs:g.langs}),y=[];for(let b=0;b+1<F.length;b++){const O=await m.identify(n.subarray(F[b],F[b+1]),{langs:g.langs});y.push({from:F[b],to:F[b+1],scores:O?.scores||{}})}if(S=Yt(y,{base:_?.scores?Y(_.scores,n.length/h):null}),S.length>1){const b=[];for(let O=0;O<S.length;O++){const $=S[O],M=$.lang&&$.lang!=="en"&&(S[O-1]?.lang==="en"||S[O+1]?.lang==="en");b.push(M?Y((await m.identify(n.subarray($.from,$.to),{langs:g.langs}))?.scores||{},($.to-$.from)/h):$.lang)}S=Vt(S,b)}S.length<2&&(S=null)}if(S){k=[];for(const _ of S){const y=await m(n.subarray(_.from,_.to),_.lang?{lang:_.lang}:{...g}),b=String(y?.text||"").trim(),O=y?.lang||_.lang||null;b&&k.push({text:b,lang:O,from:_.from,to:_.to}),O&&(g.last=O)}}else{const _=await m(n,g);p=String(_?.text||"").trim(),m.__indic&&(N=_?.lang||null),m.__indic&&p&&(k=[{text:p,lang:N,from:0,to:n.length}])}if(k&&E&&g.langs&&(k=await qt(k,F,async(_,y,b)=>String((await m(n.subarray(_,y),{lang:b}))?.text||"").trim())),k){p=k.map(y=>y.text).join(" ");const _=new Map;for(const y of k)y.lang&&_.set(y.lang,(_.get(y.lang)||0)+(y.to-y.from));N=[..._].sort((y,b)=>b[1]-y[1])[0]?.[0]||null,(k.length<2||_.size<2)&&(k=null)}}}catch(g){I(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),E&&pe(e,o,x);return}if(!p){E&&pe(e,o,x);return}{const g=Ct(p);if(g.removed&&g.removed/g.total>=Ft&&g.total>=12?p="":p=g.text,p&&je(p)>Ke){const C=$t(p);p=C.replace(/[\s\p{P}]/gu,"").length<12||je(C)>Ke?"":C}if(!p){E&&pe(e,o,x);return}}const nt=o>=de*h,Ne=o>=qe*h;if(t||f||d||nt||Ne){const g=t?"flush":f?"silence":d?"speaker":Ne?"overflow":"length",C=g==="flush"||g==="silence"||g==="speaker";pe(e,o,x);const F=An(n,c);if(Ot(p,F?F.length:0)||e.echo?.role==="mic"&&ye.mostlyEcho(oe.verdict(e.echo,r,r+n.length)))return;let S=null,Y=null,_=null;if(e.diarizer)try{const M=e.speakerLabel?null:await B.spans(n),v=M?He(M):[];if(v.length){const H=new Map,K=new Map;for(const{local:P}of ft(v)){const W=dt(n,v,P),te=W.length?await U.embed(W):null;te&&K.set(P,{vec:te,samples:W.length});const q=W.length<ze,ae=W.length<Ge;H.set(P,e.diarizer.assign(te,{pinnedLabel:null,weak:q,thin:ae}))}const he=Math.round(r/h*1e3);Y=v.map(P=>({startMs:he+Math.round(P.start*1e3),durationMs:Math.round((P.end-P.start)*1e3),speaker:H.get(P.local)})).filter(P=>P.speaker),S=H.get(Ue(v))||null,S&&(_=K.get(Ue(v))||null)}}catch{}if(e.diarizer&&!S)try{const M=F,v=M?await U.embed(M):null,H=!!M&&M.length<ze,K=!!M&&M.length<Ge;v&&(_={vec:v,samples:M.length}),S=e.diarizer.assign(v,{pinnedLabel:e.speakerLabel,weak:H,thin:K})}catch{}let y=null;(e.langs||e.translateTo)&&(N?y=N:re?y=re:me(A)&&!e.remote?y="en":T?y=Lt(p,u||e.lang)||null:y=e.lang||wt(p,{allowed:e.langs||[],last:e.lastLang}).lang,y&&y!==e.lastLang&&(e.lastLang=y,I(e,{type:"language",lang:y})));const b=e.vectors&&_?{vec:U.plainVector(_.vec),seconds:Math.round(_.samples/h*100)/100,speakerModel:U.activeModel()}:null,O=Math.round(r/h*1e3),$=k&&(e.langs||e.translateTo)?k.map((M,v)=>({text:M.text,lang:M.lang,startMs:O+Math.round(M.from/h*1e3),durationMs:Math.round((M.to-M.from)/h*1e3),last:v===k.length-1})):[{text:p,lang:y,startMs:O,durationMs:Math.round(n.length/h*1e3),last:!0}];for(const M of $){$.length>1&&M.lang&&M.lang!==e.lastLang&&(e.lastLang=M.lang,I(e,{type:"language",lang:M.lang}));const{text:v,lang:H,startMs:K}=M,he=(v.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(v.match(new RegExp("\\p{L}","gu"))||[]).length),P=ne.indictransLanguage(H)&&he<.5&&ne.state()!=="error"&&mt(),W=!!e.translateTo&&yt(H,e.translateTo)&&(P||Mt(v,H)&&se.state()!=="error"),te=$.length>1&&Y?Y.filter(q=>q.startMs<K+M.durationMs&&q.startMs+q.durationMs>K):Y;if(I(e,{type:"final",text:v,reason:g,endOfTurn:M.last?C:!1,durationMs:M.durationMs,startMs:K,...H?{lang:H}:{},...W?{translating:!0}:{},...S?{speaker:S}:{},...te?.length?{turns:te}:{},...b||{}}),W){const q=e.translateTo,ae=P?ne:se;ae.state()==="off"&&ae.init({...e.translateLoad,...P?{sessionOptions:ie()}:{}}),e.translations=e.translations.then(async()=>{await ae.ready();const Pe=P?await ne.translate(v,H):await se.translate(v);I(e,{type:"translation",startMs:K,lang:H,to:q,text:Pe||null,...Pe?{}:{failed:!0}})}).catch(()=>{})}}if(e.prints&&!e.speakerLabel&&_&&S?.label){e.prints.push({starts:$.map(M=>M.startMs),vec:Array.from(_.vec),seconds:_.samples/h,label:S.label});for(const M of $)e.shown.set(M.startMs,S.label);(e.pushed||0)-e.regroupedAt>=hn*h&&tt(e)}}else p!==e.lastInterim&&(e.lastInterim=p,I(e,{type:"interim",text:p}))}async function kn(e){try{const t=await B.spans(e),n=t?He(t):[];if(n.length<2)return 0;const o=n[0].local;for(const r of n){if(r.local===o||r.start<dn||r.end-r.start<gn||n.some(i=>i.local===o&&i.end>r.start+pn))continue;const a=Math.round(Math.max(0,r.start-.05)*h);return a>h&&a<e.length-h/2?a:0}}catch{}return 0}function tt(e){if(!e.prints?.length)return;e.regroupedAt=e.pushed||0;const t=gt(e.prints.map((o,r)=>({key:r,vec:o.vec,seconds:o.seconds,label:o.label})),{threshold:pt(U.activeModel())}),n=[];e.prints.forEach((o,r)=>{const a=t.get(r);if(a)for(const i of o.starts)e.shown.get(i)!==a&&(e.shown.set(i,a),n.push({startMs:i,speaker:{label:a}}))}),n.length&&I(e,{type:"speakers",changes:n})}async function bn(e){const t=ge(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(Z=Z.then(()=>De(t,{flush:!0}).catch(()=>{}))),tt(t),await Promise.race([t.translations,new Promise(n=>setTimeout(n,Mn).unref?.())])}finally{if(I(t,{type:"end"}),t.listeners.clear(),G.delete(t.id),t.poll){const n=setTimeout(()=>J.delete(t.id),sn);n.unref?.(),J.set(t.id,{session:t,timer:n})}t.diarizer&&(U.release(),B.release()),t.translateTo&&(se.release(),ne.release()),t.echo&&ye.release(),z.release(),oe.leave(t.echo),G.size===0&&fe()&&R?.arm()}return!0}function ro(){for(const e of G.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);G.clear();for(const e of J.values())clearTimeout(e.timer);J.clear(),R?.disarm(),R=null,w="off",A=null,m=null,D=null,Q=null,L=null}function ao(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){m=e,A=t,w=e?"ready":"off",V=o,n!==null&&(R=Me({warmMs:n,busy:ce,unload:()=>Te()}),e&&R.arm())}export{an as AUTO_FETCH_MAX_MB,Ke as COMPRESSION_LIMIT,jt as FROM_ENGLISH,Bt as FROM_ENGLISH_RUN_S,Wt as LEAVE_KNOWN,It as LEAVE_SURE,Ft as LOOP_DROP,Jt as PAUSE_SHARE,Be as PIECE_MIN_S,Ut as PIECE_PAUSE_S,h as SAMPLE_RATE,Gt as SURE_ENGLISH,Ge as THIN_SPEAKER_SAMPLES,zt as TO_ENGLISH,Kt as WEAK_ENGLISH_MIN_S,ze as WEAK_SPEAKER_SAMPLES,ro as _reset,ao as _setPipeForTest,Xt as anyLanguageSegment,Tn as clampEndSilence,Ct as collapseLoops,$t as collapseRuns,je as compressionRatio,Qn as createSession,no as decodeNow,Zn as drainEvents,bn as endSession,eo as endedSession,ge as getSession,Wn as health,Vn as init,fe as isReady,Yt as languageGroups,Ot as looksHallucinated,en as modelOnDisk,yn as noiseFloorOf,Qt as pauseCuts,Zt as pauseLevel,In as progress,to as pushAudio,Ln as quietestCut,Vt as relabelGroups,qt as respellEnglish,ue as runtimeDtype,Fe as runtimeName,Se as segmentLanguage,qn as sessionCount,Yn as setModel,wn as silenceGate,Ye as speakerPlan,Bn as state,ie as sttSessionOptions,Ht as sttThreads,Jn as subscribe,oo as toFloat32,Te as unload,Xn as warmPending};
|
|
1
|
+
import{join as at}from"node:path";import{deflateSync as lt}from"node:zlib";import Oe from"node:os";import{existsSync as st,readdirSync as it}from"node:fs";import{randomUUID as ct}from"node:crypto";import{ensureLib as Re,modelRoot as Ce}from"./ner-engine.js";import{runtimeDtype as fe,runtimeName as Fe,DTYPE_SUFFIX as ut}from"./model-runtime.js";import{verifyModelWeights as ft}from"./model-integrity.js";import{DEFAULT_STT_MODEL as $e,isEnglishOnly as _e,sttModelDtype as we,isKnownSttModel as dt,sttModelEngine as j}from"./stt-models.js";import*as V from"./parakeet-engine.js";import*as ye from"./coreml-stt-engine.js";import*as le from"./indic-engine.js";import*as z from"./diarize-engine.js";import*as B from"./segment-engine.js";import{turnsFromSpans as He,mainLocal as Ue,timeByLocal as gt,audioOfLocal as pt}from"@chatpanel/events/speaker-turns.js";import{regroupSpeakers as ht,regroupThreshold as mt}from"@chatpanel/events/speaker-recluster.js";import{diarizeApproxMB as _t}from"./diarize-models.js";import*as se from"./translate-engine.js";import*as oe from"./indictrans-engine.js";import{rawOrtAvailable as wt}from"./ort.js";import*as U from"./vad-engine.js";import*as re from"./echo-pair.js";import*as Me from"./aec-engine.js";import{pickSegmentLanguage as yt,detectTextLanguage as Mt,needsTranslation as Et,localTranslatable as St,normalizeLanguages as Tt,normalizeLanguage as Lt,decodeLanguages as At,lineLanguage as xt,autoCandidates as kt,AUTO_LEARN_CONFIDENCE as bt,AUTO_LEARN_SECONDS as vt,ANY_LANGUAGE_CONFIDENCE as Dt,AUTO_LANGUAGES as Nt}from"@chatpanel/events/speech-language.js";import*as Pt from"@chatpanel/events/speech-language.js";import{makeWarmTimer as Ee}from"./warm-timer.js";const p=16e3,ze=p,Ge=3*p,Ot=2,Rt=new Set(["thank you","thanks","thank you for watching","thanks for watching","you","uh","um","hmm","hm","mm","amen","bye","okay","ok","yeah","oh","the","that","so","and","i","a","me","we","yes","no","thank you very much","subtitles by the amara.org community","you you"]);function Ct(e,t){if(t>Ot*p)return!1;const n=String(e||"").toLowerCase().replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return n?Rt.has(n)||/^(you ?){2,}$/.test(n)||/^(thank you\.? ?){2,}$/.test(n):!0}const Ft=12,Se=3;function $t(e){const t=String(e||"").split(/\s+/).filter(Boolean);if(t.length<Se)return{text:String(e||"").trim(),removed:0,total:t.length};const n=a=>a.toLowerCase().replace(/[^\p{L}\p{N}']/gu,""),o=[];let r=0;for(let a=0;a<t.length;){let i=0,c=0;for(let l=1;l<=Ft&&a+l*Se<=t.length;l++){let s=1;for(;a+(s+1)*l<=t.length&&t.slice(a+s*l,a+(s+1)*l).every((f,d)=>n(f)===n(t[a+d]));)s++;s>=Se&&(s-1)*l>i&&(i=(s-1)*l,c=l)}i?(o.push(...t.slice(a,a+c)),r+=i,a+=c+i):(o.push(t[a]),a++)}return{text:o.join(" "),removed:r,total:t.length}}const Ht=.6,Ie=2.4;function Ke(e){const t=Buffer.from(String(e||""),"utf8");return t.length<40?1:t.length/lt(t).length}function Ut(e){return String(e||"").replace(/([^\d\s]{1,8}?)\1{4,}/gu,"$1")}function zt({cores:e=Oe.availableParallelism?.()??Oe.cpus().length,env:t=process.env}={}){const n=Number(t.CHATPANEL_STT_THREADS);return Number.isFinite(n)&&n>0?Math.floor(n):Math.max(1,Math.min(4,Math.floor(e/2)))}function ie(e){return{intraOpNumThreads:zt(e),interOpNumThreads:1,extra:{session:{intra_op:{allow_spinning:"0"}}}}}const Gt=.12,je=.8,It=.15,Kt=.5,jt=1.2,Be=(e,t)=>e>=Kt||e>=It&&!(t<jt),Bt=.999,Wt=2.5;function We(e={},t=1/0){return Be(e.en??0,t)?"en":Object.entries(e).sort((n,o)=>o[1]-n[1])[0]?.[0]||null}const Xt=.9,Vt=.5;function Xe(e={},t=1/0,n=null){const o=We(e,t);if(!o||o==="en")return o;const r=e[o]??0;return r>=Xt?(n?.add(o),o):r>=Vt&&n?.has(o)?o:"en"}function Yt(e,t=[]){const n=[];return e.forEach((o,r)=>{const a=t[r]??o.lang,i=n[n.length-1];i&&i.lang===a?i.to=o.to:n.push({from:o.from,to:o.to,lang:a})}),n}function qt(e,{base:t=null,rate:n=p}={}){const o=e||[],r=l=>{const[s,f]=Object.entries(l.scores||{}).sort((d,k)=>k[1]-d[1])[0]||[];return s&&s!=="en"&&f>=Bt?s:null},a=new Array(o.length).fill(null);for(let l=0;l<o.length;){const s=r(o[l]);let f=l+1;if(s)for(;f<o.length&&r(o[f])===s;)f++;if(s&&(o[f-1].to-o[l].from)/n>=Wt)for(let d=l;d<f;d++)a[d]=s;l=f}const i=[];let c=t;return o.forEach((l,s)=>{a[s]?c=a[s]:c!=="en"&&Be(l.scores?.en??0,(l.to-l.from)/n)&&(c="en");const f=i[i.length-1];f&&f.lang===c?f.to=l.to:i.push({from:l.from,to:l.to,lang:c})}),i}async function Qt(e,t,n){const{spelledEnglish:o,isSpelledEnglish:r,SPELLED_ENGLISH_MIN:a,SPELLED_SHAPE_MIN:i}=Pt;if(typeof o!="function")return e;const c=[];let l=!1;for(const s of e){const f=o(s.text);if(!s.lang||s.lang==="en"||f.english<a&&!r(s.text)){c.push(s);continue}const d=f.words>=i&&f.shaped===f.words,k=[];for(let u=0;u+1<t.length;u++)t[u]>=s.from&&t[u+1]<=s.to&&k.push([t[u],t[u+1]]);if(k.length<2||d){const u=r(s.text)?await n(s.from,s.to,"en"):"";u?(c.push({...s,text:u,lang:"en"}),l=!0):c.push(s);continue}const T=[];for(const[u,w]of k){const M=await n(u,w,s.lang),G=o(M),N=G.words>0&&G.words-G.shaped<=(G.english>=1&&G.words>=3?1:0);T.push({from:u,to:w,text:M,near:N,lang:r(M)?"en":s.lang})}for(let u=!0;u;)u=!1,T.forEach((w,M)=>{w.lang!=="en"&&w.near&&(T[M-1]?.lang==="en"||T[M+1]?.lang==="en")&&(w.lang="en",u=!0)});if(!T.some(u=>u.lang==="en")){c.push(s);continue}const L=[];for(const u of T){const w=L[L.length-1];w&&w.lang===u.lang?(w.to=u.to,w.n++):L.push({from:u.from,to:u.to,lang:u.lang,n:1,text:u.text})}for(const u of L){const w=u.n===1&&u.lang===s.lang?u.text:await n(u.from,u.to,u.lang);w&&c.push({from:u.from,to:u.to,lang:u.lang,text:w})}l=!0}return l?c.reduce((s,f)=>{const d=s[s.length-1];return d&&d.lang===f.lang&&d.to===f.from?s[s.length-1]={...d,to:f.to,text:`${d.text} ${f.text}`}:s.push(f),s},[]):e}function Jt(e,t,{frame:n=Math.round(.03*p),minPause:o=Gt*p,minPiece:r=je*p}={}){const a=[];let i=0,c=-1;for(let l=0;l+n<=e;l+=n){const s=t(l,l+n)===!1;if(s&&c<0&&(c=l),(!s||l+2*n>e)&&c>=0){const f=s?l+n:l,d=Math.round((c+f)/2);f-c>=o&&d-i>=r&&e-d>=r&&(a.push(d),i=d),c=-1}}return a}const Zt=.12;function en(e,t=Math.round(.03*p)){const n=Math.floor(e.length/t);if(n<3)return 0;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=te(e,r*t,(r+1)*t);return o.sort(),Math.max(1e-4,o[Math.floor(n*.9)]*Zt)}let y="off",x=null,_=null,D=null,J=null,A=null,Y=null,R=null;function tn(e=x||$e,t=we(e)||fe()){if(j(e)==="parakeet-tdt")return V.parakeetOnDisk(e,V.parakeetDtype(t));if(j(e)==="coreml-tdt")return ye.coremlOnDisk(e);if(j(e)==="indic-canary")return le.indicOnDisk();const n=at(Ce(),...e.split("/"),"onnx");if(!st(n))return!1;const o=ut[t]??"";try{const r=it(n);return r.includes(`encoder_model${o}.onnx`)&&r.some(a=>a===`decoder_model_merged${o}.onnx`||a===`decoder_model${o}.onnx`)}catch{return!1}}function Wn(){return y}function de(){return y==="ready"&&!!_}function Xn(){return A}function Vn(){return{configured:y!=="off",ok:de(),state:y,model:x,dtype:Y,runtime:Fe(),error:D,warmMs:R?.warmMs??null,vad:U.state()}}function Yn(){return!!R?.pending()}function ce(){return I.size>0||y==="loading"||y==="downloading"}async function Te({log:e=()=>{}}={}){if(ce())return!1;R?.disarm();const t=_;if(_=null,J=null,Y=null,A=null,D=null,y="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((R?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function Ve(e){return e.then(t=>(t&&!ce()&&R?.arm(),t))}async function Ye(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null,licenseAccepted:r=null}={}){if(j(e)==="parakeet-tdt")return nn(e,{log:t,allowDownload:n,dtype:o});if(j(e)==="coreml-tdt")return rn(e,{log:t,allowDownload:n});if(j(e)==="indic-canary")return an(e,{log:t,allowDownload:n,licenseAccepted:r});const a=_,i=x;let c;try{c=await Re()}catch(T){return y="error",D=`engine load failed: ${T.message}`,t(`[stt] transformers.js not available (${T.message}) — dictation falls back to the browser engine`),!1}const s=(o&&o!=="auto"?o:null)||we(e)||fe(),f=tn(e,s);if(c.env.allowRemoteModels=f?!1:!!n,!f&&!n)return y="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const d=c.env.remoteHost,k=!dt(e);if(!f&&k)try{c.env.remoteHost="https://huggingface.co/"}catch{}y=f?"loading":"downloading",f||(A={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${k?", from Hugging Face":""})…`));try{const T=u=>{if(!u)return;const w=typeof u.progress=="number"?Math.round(u.progress):A?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?A={model:e,file:u.file||A?.file||null,pct:w}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let L;try{L=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:ie()}})}catch(u){if(f||k||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),c.env.remoteHost="https://huggingface.co/",c.env.allowRemoteModels=!0,L=await c.pipeline("automatic-speech-recognition",e,{dtype:s,progress_callback:T,...globalThis.__CHATPANEL_WASM_PATHS__?{}:{session_options:ie()}})}if(!f)try{ft(e,{modelsDir:Ce(),log:t})}catch(u){try{await L.dispose?.()}catch{}throw u}if(_=L,x=e,y="ready",D=null,A=null,Y=s,a&&a!==L)try{await a.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (in-process, offline) — local dictation active`),!0}catch(T){return D=T.message,A=null,a?(_=a,x=i,y="ready"):y="error",t(`[stt] model load failed (${T.message})${a?" — keeping previous model":""}`),!1}finally{try{c.env.remoteHost=d}catch{}}}async function nn(e,{log:t=()=>{},allowDownload:n=!0,dtype:o=null}={}){const r=_,a=x,i=V.parakeetDtype(o&&o!=="auto"?o:on()),c=V.parakeetOnDisk(e,i);if(!c&&!n)return y="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;y=c?"loading":"downloading",c||(A={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const l=await V.loadRecognizer({modelId:e,dtype:i,allowDownload:n,log:t,sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:ie(),onProgress:f=>{A={model:e,file:f.file||null,pct:typeof f.pct=="number"?f.pct:A?.pct??0}}}),s=async f=>({text:await l.transcribe(f)});if(s.__transducer=!0,s.dispose=()=>l.dispose(),_=s,x=e,y="ready",D=null,A=null,Y=i,r&&r!==s)try{await r.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(l){return D=l.message,A=null,r?(_=r,x=a,y="ready"):y="error",t(`[stt] model load failed (${l.message})${r?" — keeping previous model":""}`),!1}}function on(){return V.PARAKEET_DEFAULT_DTYPE}const qe="fp16";async function rn(e,{log:t=()=>{},allowDownload:n=!0}={}){const o=_,r=x,a=ye.coremlOnDisk(e);if(!a&&!n)return y="error",D="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;y=a?"loading":"downloading",a||(A={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{let i=null;const c=await ye.loadRecognizer({modelId:e,allowDownload:n,log:t,onProgress:l=>{A={model:e,file:l.file||null,pct:typeof l.pct=="number"?l.pct:A?.pct??0}},onExit:l=>{_===i&&(_=null,J=null,y="error",D=l,R?.disarm(),t(`[stt] ${l} — reloads on the next dictation`))}});if(i=async l=>({text:await c.transcribe(l)}),i.__transducer=!0,i.dispose=()=>c.dispose(),_=i,x=e,y="ready",D=null,A=null,Y=qe,o&&o!==i)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} (Core ML on the Neural Engine, helper ${c.version}, windows ${c.windows.join("/")} s, offline) — local dictation active`),!0}catch(i){return D=i.message,A=null,o?(_=o,x=r,y="ready"):y="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}async function an(e,{log:t=()=>{},allowDownload:n=!0,licenseAccepted:o=null}={}){const r=_,a=x,i=le.indicOnDisk();if(!i&&!n)return y="error",D="model not on disk and downloads disabled",!1;y=i?"loading":"downloading",i||(A={model:e,file:null,pct:0},t(`[stt] downloading ${e} (one-time, ~1.5 GB, from Hugging Face)…`));try{i||await le.ensureIndicFiles({licenseAccepted:o,log:t,onProgress:s=>{A={model:e,file:s.file,pct:s.pct}}});const c=await le.loadRecognizer({sessionOptions:globalThis.__CHATPANEL_WASM_PATHS__?null:ie(),log:t}),l=async(s,f={})=>c.transcribe(s,f);if(l.identify=(s,f)=>c.identify(s,f),l.__transducer=!0,l.__indic=!0,l.dispose=()=>c.dispose(),_=l,x=e,y="ready",D=null,A=null,Y="int8",r&&r!==l)try{await r.dispose?.()}catch{}return t(`[stt] ready — ${e} (Indic-Transcribe, int8, in-process, offline) — ${le.INDIC_LICENSE.attribution}`),!0}catch(c){return D=c.message,A=null,r?(_=r,x=a,y="ready"):y="error",t(`[stt] model load failed (${c.message})${r?" — keeping previous model":""}`),!1}}const ln=30;function Qe({mode:e="ondisk",onDisk:t=!1,ready:n=!1,approxMB:o=null}={}){return n||e==="off"?null:t?{allowDownload:!1}:typeof o=="number"&&o<=ln||e==="download"?{allowDownload:!0}:null}function Le(e,{log:t=()=>{},warmMs:n,allowDownload:o=!0}={}){const r=Qe({mode:e,onDisk:z.modelOnDisk(),ready:z.isReady(),approxMB:_t(z.activeModel())});if(r&&z.init({allowDownload:r.allowDownload&&o!==!1,warmMs:n,onLog:t}),e==="off"||Ae)return;const a=Qe({mode:e,onDisk:B.modelOnDisk(),ready:B.isReady(),approxMB:B.SEGMENT_MODEL_APPROX_MB});a&&B.init({allowDownload:a.allowDownload&&o!==!1,warmMs:n,onLog:t})}let Ae=!1,xe=null;function ke(e={},{log:t=()=>{}}={}){e.vad!==!1&&(xe={vad:e.vad,allowDownload:e.allowDownload,warmMs:e.warmMs},(U.state()==="off"||U.state()==="error")&&U.init({allowDownload:e.allowDownload!==!1,warmMs:e.warmMs,onLog:t}))}function qn(e={}){if(J&&y!=="error")return J;const t=typeof e.onLog=="function"?e.onLog:()=>{};return x=e.model||$e,Ae=e.segment===!1,y="loading",R=Ee({warmMs:e.warmMs,busy:ce,log:t,unload:()=>Te({log:t})}),J=Ve(Ye(x,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype,licenseAccepted:e.licenseAccepted||null})).then(n=>(n&&(Le(e.speaker,{log:t,warmMs:e.warmMs,allowDownload:e.allowDownload!==!1}),ke(e,{log:t})),n)),J}async function Qn(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;t.segment!==void 0&&(Ae=t.segment===!1);const o=j(e)==="parakeet-tdt"?V.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:V.PARAKEET_DEFAULT_DTYPE):j(e)==="coreml-tdt"?qe:j(e)==="indic-canary"?"int8":t.dtype&&t.dtype!=="auto"?t.dtype:we(e)||fe();if(e===x&&de()&&Y===o)return Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),!0;R??=Ee({warmMs:t.warmMs,busy:ce,log:n,unload:()=>Te({log:n})});const r=await Ve(Ye(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype,licenseAccepted:t.licenseAccepted||null}));return r&&(Le(t.speaker,{log:n,warmMs:t.warmMs,allowDownload:t.allowDownload!==!1}),ke(t,{log:n})),r}const sn=8,cn=12e4,un=6e4,fn=1200,ue=12,dn=3,gn=1,pn=.8,hn=.5,mn=60,be=700,_n=.3,ve=.008,wn=.002,yn=4;function Mn(e){return e>0?Math.min(ve,Math.max(wn,e*yn)):ve}function En(e){const t=Math.round(.1*p),n=Math.floor(e.length/t);if(n<5)return null;const o=new Float32Array(n);for(let r=0;r<n;r++)o[r]=te(e,r*t,(r+1)*t);return o.sort(),o[Math.floor(n*.1)]}const Je=30,Sn=15e3,I=new Map,Z=new Map;let ee=Promise.resolve();function Jn(){return I.size}const Tn=300,Ln=3e3;function An(e){const t=Number(e);return Number.isFinite(t)?Math.min(Ln,Math.max(Tn,Math.round(t))):be}function Zn({lang:e,langs:t=null,translateTo:n=null,translateLoad:o=null,echo:r=null,redact:a=!1,diarize:i=!1,vectors:c=!1,speakerLabel:l=null,endSilenceMs:s=be,interims:f=!0,remote:d=null,poll:k=!1,format:T="f32"}={}){if(I.size>=sn){const M=new Error("too many concurrent dictation sessions");throw M.code="too_many_sessions",M}const L=Array.isArray(t)?Tt(t):null,u=typeof e=="string"&&e?e.slice(0,12):null,w={id:ct(),format:T==="pcm16"?"pcm16":"f32",endSilenceMs:An(s),lang:L?L.length===1?L[0]:L.length?null:u:u,langs:L,lastLang:null,lastDecoded:null,learned:new Set,translateTo:Lt(n)||null,translateLoad:o||{},translations:Promise.resolve(),echo:r&&typeof r=="object"?re.join(r.group,r.role):null,langTried:!1,pushed:0,noiseFloor:null,redact:!!a,diarize:!!i,speakerLabel:typeof l=="string"&&l?l.slice(0,40):null,diarizer:i?new z.Diarizer:null,prints:i?[]:null,shown:new Map,regroupedAt:0,vectors:!!i&&c===!0,remote:d||null,interims:f!==!1&&!d,chunks:[],samples:0,listeners:new Set,poll:k?[]:null,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return I.set(w.id,w),R?.disarm(),w.diarizer&&(z.retain(),B.retain()),w.translateTo&&(se.retain(),oe.retain()),w.echo&&Me.retain(),U.retain(),xe&&(U.state()==="off"||U.state()==="error")&&ke(xe),Ze(w),{id:w.id}}function ge(e){return I.get(String(e||""))||null}function eo(e,t){const n=ge(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function W(e,t){e.poll&&e.poll.push(t);for(const n of e.listeners)try{n(t)}catch{}}function to(e){const t=String(e||""),n=I.get(t);if(n)return n.poll?n.poll.splice(0):null;const o=Z.get(t);return o?(clearTimeout(o.timer),Z.delete(t),o.session.poll.splice(0)):null}function no(e){return Z.get(String(e||""))?.session||null}function Ze(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>Dn(e.id).catch(()=>{}),un),e.idleTimer.unref?.()}function oo(e,t){const n=ge(e);if(!n||n.closed){const o=new Error("no such session");throw o.code="no_session",o}if(!(!(t instanceof Float32Array)||!t.length)){if(Ze(n),n.echo?.role==="mic"){re.pushMic(n.echo,t),et(n);return}n.echo?.role==="reference"&&re.pushReference(n.echo,t),n.chunks.push(t),n.samples+=t.length,n.pushed+=t.length,et(n)}}function ro(e){const t=ge(e);return!t||t.closed?Promise.resolve():(t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null),ee=ee.then(()=>De(t).catch(()=>{})),ee)}function ao(e,t="f32"){if(t==="pcm16"){const r=new Float32Array(Math.floor(e.length/2));for(let a=0;a<r.length;a++)r[a]=e.readInt16LE(a*2)/32768;return r}const n=e.length-e.length%4,o=new Float32Array(n/4);for(let r=0;r<o.length;r++)o[r]=e.readFloatLE(r*4);return o}function et(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+fn-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,ee=ee.then(()=>De(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function pe(e,t,n){const o=e.samples-t,r=[];n&&r.push(n),o>0&&r.push(tt(e).subarray(t)),e.chunks=r,e.samples=r.reduce((a,i)=>a+i.length,0),e.lastInterim=""}function tt(e){const t=new Float32Array(e.samples);let n=0;for(const o of e.chunks)t.set(o,n),n+=o.length;return t}function xn(e,t,n){const o=p/100,r=Math.max(0,e.length-t),a=Math.floor((e.length-r)/o),i=Math.max(1,Math.round(n/o));if(a<=i)return 0;const c=new Float32Array(a);for(let d=0;d<a;d++){let k=0;const T=r+d*o;for(let L=0;L<o;L++)k+=e[T+L]*e[T+L];c[d]=k/o}let l=-1,s=1/0,f=0;for(let d=0;d<i;d++)f+=c[d];for(let d=0;d+i<=a;d++)d>0&&(f+=c[d+i-1]-c[d-1]),f<s&&(s=f,l=d);return l<0?0:r+Math.round((l+i/2)*o)}function te(e,t=0,n=e.length){let o=0;const r=Math.max(1,n-t);for(let a=t;a<n;a++)o+=e[a]*e[a];return Math.sqrt(o/r)}function kn(e,t=ve){const n=Math.round(.02*p);let o=0,r=e.length;for(let a=0;a+n<=e.length;a+=n)if(te(e,a,a+n)>=t){o=a;break}for(let a=e.length-n;a>=0;a-=n)if(te(e,a,a+n)>=t){r=a+n;break}return r>o?e.subarray(o,r):e}async function nt(e){try{const t=await Re(),n=_?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const o=e.length>p*8?e.subarray(0,p*8):e,r=await _.processor(o),a=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),i=await _.model({...r,decoder_input_ids:a}),c={};for(const[l,s]of Object.entries(n.lang_to_id))c[l.slice(2,-2)]=Number(i.logits.data[s]);return c}catch{return null}}async function bn(e){const t=await nt(e);if(!t)return null;let n=null,o=-1/0;for(const[r,a]of Object.entries(t))a>o&&(o=a,n=r);return n}async function De(e,{flush:t=!1}={}){if(e.closed&&!t)return;if(e.echo?.role==="mic"){const g=await re.drain(e.echo,{force:t});g.length&&(e.chunks.push(g),e.samples+=g.length,e.pushed+=g.length)}if(!e.remote&&!de()||!e.samples)return;e.lastDecodeAt=Date.now();let n=tt(e);const o=n.length,r=Math.max(0,(e.pushed||0)-e.samples),a=Math.round((e.endSilenceMs||be)/1e3*p),i=En(n);i!==null&&(e.noiseFloor==null||i<e.noiseFloor)&&(e.noiseFloor=i);const c=Mn(e.noiseFloor);let l=null,s=null,f=!1;U.isReady()&&(e.vad||=U.createStream(),await e.vad.advance(n,r)&&(l=e.vad.speechIn(r,r+n.length,U.ONSET),f=l===!0&&e.vad.voicedIn(r,r+n.length,U.OFFSET)<_n,n.length>a&&(s=e.vad.speechIn(r+n.length-a,r+n.length,U.OFFSET))));const d=n.length>a&&(s!==null?!s:te(n,n.length-a)<c);if(l===!1||l===null&&te(n)<c){n.length>p*5&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}if(f){!t&&n.length>ue*p&&(e.chunks=[n.subarray(n.length-p)],e.samples=p);return}let k=!1,T=null;if(e.diarizer&&!e.speakerLabel&&!t&&B.isReady()&&n.length>=dn*p){const g=await vn(n);g&&(T=n.subarray(g),n=n.subarray(0,g),k=!0)}if(!e.interims&&!t&&!d&&!k&&n.length<ue*p)return;if(!k&&!t&&!d&&o>=ue*p&&o<Je*p){const g=xn(n,3*p,Math.round(.2*p));g>0&&g<n.length&&(T=n.subarray(g),n=n.subarray(0,g))}const L=!e.remote&&!_e(x)&&!_?.__transducer;if(L&&!e.langs&&!e.lang&&!e.langTried&&n.length>=p){e.langTried=!0;const g=await bn(n);g&&(e.lang=g,W(e,{type:"language",lang:g}))}const u=t||d||k||o>=ue*p;let w=e.lang;if(L&&e.langs&&!e.lang){const g=e.langs.length>0,C=g?At(e.langs):kt([...e.learned]);if(C.length===1)w=C[0];else if(w=C.includes(e.lastDecoded)?e.lastDecoded:null,(u||!w)&&n.length>=p/2){const F=await nt(n);if(F){const S=yt({scores:F,allowed:C,seconds:n.length/p,last:e.lastDecoded});w=!g&&!S.inherited&&S.confidence<Dt?e.lastDecoded||"en":S.lang,!g&&u&&!S.inherited&&S.confidence>=bt&&n.length>=vt*p&&e.learned.add(S.lang)}}u&&w&&(e.lastDecoded=w)}let M="",G=null,N=null,he=null;try{if(e.remote){const g=await e.remote.transcribe(n,{lang:e.lang,langs:e.langs});M=g.text,he=g.lang||null}else{const g=_.__indic?e.langs?.length?{langs:[...new Set([...e.langs,"en"])],last:e.lastLang,choose:(h,m)=>Xe(h,m,e.learned)}:e.lang?{lang:e.lang}:{langs:[...Nt],last:e.lastLang,choose:(h,m)=>Xe(h,m,e.learned)}:_e(x)?{}:{language:w||void 0,task:"transcribe"},C=_.__indic&&_.identify&&u&&g.langs&&n.length>=2*je*p?Jt(n.length,(h=>(m,b)=>te(n,m,b)>=h)(en(n))):[],F=[0,...C,n.length];let S=null;const q=g.choose||We;if(C.length){const h=await _.identify(n,{langs:g.langs}),m=[];for(let b=0;b+1<F.length;b++){const O=await _.identify(n.subarray(F[b],F[b+1]),{langs:g.langs});m.push({from:F[b],to:F[b+1],scores:O?.scores||{}})}if(S=qt(m,{base:h?.scores?q(h.scores,n.length/p):null}),S.length>1){const b=[];for(let O=0;O<S.length;O++){const $=S[O],E=$.lang&&$.lang!=="en"&&(S[O-1]?.lang==="en"||S[O+1]?.lang==="en");b.push(E?q((await _.identify(n.subarray($.from,$.to),{langs:g.langs}))?.scores||{},($.to-$.from)/p):$.lang)}S=Yt(S,b)}S.length<2&&(S=null)}if(S){N=[];for(const h of S){const m=await _(n.subarray(h.from,h.to),h.lang?{lang:h.lang}:{...g}),b=String(m?.text||"").trim(),O=m?.lang||h.lang||null;b&&N.push({text:b,lang:O,from:h.from,to:h.to}),O&&(g.last=O)}}else{const h=await _(n,g);M=String(h?.text||"").trim(),_.__indic&&(G=h?.lang||null),_.__indic&&M&&(N=[{text:M,lang:G,from:0,to:n.length}])}if(N&&u&&g.langs&&(N=await Qt(N,F,async(h,m,b)=>String((await _(n.subarray(h,m),{lang:b}))?.text||"").trim())),N){M=N.map(m=>m.text).join(" ");const h=new Map;for(const m of N)m.lang&&h.set(m.lang,(h.get(m.lang)||0)+(m.to-m.from));G=[...h].sort((m,b)=>b[1]-m[1])[0]?.[0]||null,(N.length<2||h.size<2)&&(N=null)}}}catch(g){W(e,{type:"error",code:"decode_failed",message:g.message,fatal:!1}),u&&pe(e,o,T);return}if(!M){u&&pe(e,o,T);return}{const g=$t(M);if(g.removed&&g.removed/g.total>=Ht&&g.total>=12?M="":M=g.text,M&&Ke(M)>Ie){const C=Ut(M);M=C.replace(/[\s\p{P}]/gu,"").length<12||Ke(C)>Ie?"":C}if(!M){u&&pe(e,o,T);return}}const rt=o>=ue*p,Ne=o>=Je*p;if(t||d||k||rt||Ne){const g=t?"flush":d?"silence":k?"speaker":Ne?"overflow":"length",C=g==="flush"||g==="silence"||g==="speaker";pe(e,o,T);const F=kn(n,c);if(Ct(M,F?F.length:0)||e.echo?.role==="mic"&&Me.mostlyEcho(re.verdict(e.echo,r,r+n.length)))return;let S=null,q=null,h=null;if(e.diarizer)try{const E=e.speakerLabel?null:await B.spans(n),v=E?He(E):[];if(v.length){const H=new Map,K=new Map;for(const{local:P}of gt(v)){const X=pt(n,v,P),ne=X.length?await z.embed(X):null;ne&&K.set(P,{vec:ne,samples:X.length});const Q=X.length<ze,ae=X.length<Ge;H.set(P,e.diarizer.assign(ne,{pinnedLabel:null,weak:Q,thin:ae}))}const me=Math.round(r/p*1e3);q=v.map(P=>({startMs:me+Math.round(P.start*1e3),durationMs:Math.round((P.end-P.start)*1e3),speaker:H.get(P.local)})).filter(P=>P.speaker),S=H.get(Ue(v))||null,S&&(h=K.get(Ue(v))||null)}}catch{}if(e.diarizer&&!S)try{const E=F,v=E?await z.embed(E):null,H=!!E&&E.length<ze,K=!!E&&E.length<Ge;v&&(h={vec:v,samples:E.length}),S=e.diarizer.assign(v,{pinnedLabel:e.speakerLabel,weak:H,thin:K})}catch{}let m=null;(e.langs||e.translateTo)&&(G?m=G:he?m=he:_e(x)&&!e.remote?m="en":L?m=xt(M,w||e.lang)||null:m=e.lang||Mt(M,{allowed:e.langs||[],last:e.lastLang}).lang,m&&m!==e.lastLang&&(e.lastLang=m,W(e,{type:"language",lang:m})));const b=e.vectors&&h?{vec:z.plainVector(h.vec),seconds:Math.round(h.samples/p*100)/100,speakerModel:z.activeModel()}:null,O=Math.round(r/p*1e3),$=N&&(e.langs||e.translateTo)?N.map((E,v)=>({text:E.text,lang:E.lang,startMs:O+Math.round(E.from/p*1e3),durationMs:Math.round((E.to-E.from)/p*1e3),last:v===N.length-1})):[{text:M,lang:m,startMs:O,durationMs:Math.round(n.length/p*1e3),last:!0}];for(const E of $){$.length>1&&E.lang&&E.lang!==e.lastLang&&(e.lastLang=E.lang,W(e,{type:"language",lang:E.lang}));const{text:v,lang:H,startMs:K}=E,me=(v.match(new RegExp("\\p{Script=Latin}","gu"))||[]).length/Math.max(1,(v.match(new RegExp("\\p{L}","gu"))||[]).length),P=oe.indictransLanguage(H)&&me<.5&&oe.state()!=="error"&&wt(),X=!!e.translateTo&&Et(H,e.translateTo)&&(P||St(v,H)&&se.state()!=="error"),ne=$.length>1&&q?q.filter(Q=>Q.startMs<K+E.durationMs&&Q.startMs+Q.durationMs>K):q;if(W(e,{type:"final",text:v,reason:g,endOfTurn:E.last?C:!1,durationMs:E.durationMs,startMs:K,...H?{lang:H}:{},...X?{translating:!0}:{},...S?{speaker:S}:{},...ne?.length?{turns:ne}:{},...b||{}}),X){const Q=e.translateTo,ae=P?oe:se;ae.state()==="off"&&ae.init({...e.translateLoad,...P?{sessionOptions:ie()}:{}}),e.translations=e.translations.then(async()=>{await ae.ready();const Pe=P?await oe.translate(v,H):await se.translate(v);W(e,{type:"translation",startMs:K,lang:H,to:Q,text:Pe||null,...Pe?{}:{failed:!0}})}).catch(()=>{})}}if(e.prints&&!e.speakerLabel&&h&&S?.label){e.prints.push({starts:$.map(E=>E.startMs),vec:Array.from(h.vec),seconds:h.samples/p,label:S.label});for(const E of $)e.shown.set(E.startMs,S.label);(e.pushed||0)-e.regroupedAt>=mn*p&&ot(e)}}else M!==e.lastInterim&&(e.lastInterim=M,W(e,{type:"interim",text:M}))}async function vn(e){try{const t=await B.spans(e),n=t?He(t):[];if(n.length<2)return 0;const o=n[0].local;for(const r of n){if(r.local===o||r.start<gn||r.end-r.start<pn||n.some(i=>i.local===o&&i.end>r.start+hn))continue;const a=Math.round(Math.max(0,r.start-.05)*p);return a>p&&a<e.length-p/2?a:0}}catch{}return 0}function ot(e){if(!e.prints?.length)return;e.regroupedAt=e.pushed||0;const t=ht(e.prints.map((o,r)=>({key:r,vec:o.vec,seconds:o.seconds,label:o.label})),{threshold:mt(z.activeModel())}),n=[];e.prints.forEach((o,r)=>{const a=t.get(r);if(a)for(const i of o.starts)e.shown.get(i)!==a&&(e.shown.set(i,a),n.push({startMs:i,speaker:{label:a}}))}),n.length&&W(e,{type:"speakers",changes:n})}async function Dn(e){const t=ge(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(ee=ee.then(()=>De(t,{flush:!0}).catch(()=>{}))),ot(t),await Promise.race([t.translations,new Promise(n=>setTimeout(n,Sn).unref?.())])}finally{if(W(t,{type:"end"}),t.listeners.clear(),I.delete(t.id),t.poll){const n=setTimeout(()=>Z.delete(t.id),cn);n.unref?.(),Z.set(t.id,{session:t,timer:n})}t.diarizer&&(z.release(),B.release()),t.translateTo&&(se.release(),oe.release()),t.echo&&Me.release(),U.release(),re.leave(t.echo),I.size===0&&de()&&R?.arm()}return!0}function lo(){for(const e of I.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);I.clear();for(const e of Z.values())clearTimeout(e.timer);Z.clear(),R?.disarm(),R=null,y="off",x=null,_=null,D=null,J=null,A=null}function so(e,t="test/fake",{warmMs:n=null,dtype:o=null}={}){_=e,x=t,y=e?"ready":"off",Y=o,n!==null&&(R=Ee({warmMs:n,busy:ce,unload:()=>Te()}),e&&R.arm())}export{ln as AUTO_FETCH_MAX_MB,Ie as COMPRESSION_LIMIT,Bt as FROM_ENGLISH,Wt as FROM_ENGLISH_RUN_S,Vt as LEAVE_KNOWN,Xt as LEAVE_SURE,Ht as LOOP_DROP,_n as MIN_VOICED_S,Zt as PAUSE_SHARE,je as PIECE_MIN_S,Gt as PIECE_PAUSE_S,p as SAMPLE_RATE,Kt as SURE_ENGLISH,Ge as THIN_SPEAKER_SAMPLES,It as TO_ENGLISH,jt as WEAK_ENGLISH_MIN_S,ze as WEAK_SPEAKER_SAMPLES,lo as _reset,so as _setPipeForTest,Xe as anyLanguageSegment,An as clampEndSilence,$t as collapseLoops,Ut as collapseRuns,Ke as compressionRatio,Zn as createSession,ro as decodeNow,to as drainEvents,Dn as endSession,no as endedSession,ge as getSession,Vn as health,qn as init,de as isReady,qt as languageGroups,Ct as looksHallucinated,tn as modelOnDisk,En as noiseFloorOf,Jt as pauseCuts,en as pauseLevel,Xn as progress,oo as pushAudio,xn as quietestCut,Yt as relabelGroups,Qt as respellEnglish,fe as runtimeDtype,Fe as runtimeName,We as segmentLanguage,Jn as sessionCount,Qn as setModel,Mn as silenceGate,Qe as speakerPlan,Wn as state,ie as sttSessionOptions,zt as sttThreads,eo as subscribe,ao as toFloat32,Te as unload,Yn as warmPending};
|
package/src/vad-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{verifyFresh as
|
|
1
|
+
import{verifyFresh as O}from"./model-integrity.js";import{existsSync as F}from"node:fs";import{join as S}from"node:path";import{ensureLib as R,modelRoot as T,withModelSource as V}from"./ner-engine.js";import{makeWarmTimer as I}from"./warm-timer.js";import{engineLoadOptions as N}from"./ort.js";const h="onnx-community/silero-vad",J=2.2,L=16e3,s=512,b=.5,Q=.35,P=.05,B=40,G=62;let o="off",c=null,M=null,m=null,g=null,w=null,p=null,x=0,y=0,_=null;function Y(){return o}function A(){return o==="ready"&&(!!c||!!_)}function Z(){return w}function ee(){return{configured:o!=="off",ok:A(),state:o,model:h,error:m,warmMs:p?.warmMs??null}}function v(){return y>0||x>0||o==="loading"||o==="downloading"}function te(){x++,p?.disarm()}function ne(){x=Math.max(0,x-1),x===0&&y===0&&A()&&p?.arm()}function W(){return F(S(T(),...h.split("/"),"onnx","model.onnx"))}async function j({log:e=()=>{}}={}){if(v())return!1;p?.disarm();const n=c;if(c=null,g=null,w=null,m=null,o="off",n){try{await n.dispose?.()}catch{}e("[vad] idle — model unloaded")}return!0}async function X({log:e=()=>{},allowDownload:n=!0}={}){try{M=await R()}catch(r){return o="error",m=r.message,!1}const t=W();if(!t&&!n)return o="error",m="model not on disk and downloads disabled",!1;o=t?"loading":"downloading",t||(w={model:h,file:null,pct:0},e(`[vad] downloading ${h} (one-time, ~2 MB)…`));try{return c=await V({host:t?null:"https://huggingface.co/",allowRemote:!t},r=>r.AutoModel.from_pretrained(h,{config:{model_type:"custom"},dtype:"fp32",...N({threads:1})})),await O(!t,h,{modelsDir:T(),log:e,dispose:async()=>{await c?.dispose?.(),c=null}}),o="ready",m=null,w=null,e("[vad] ready — Silero VAD on levelled audio decides what is speech (the energy gate is the fallback)"),!0}catch(r){return m=r.message,w=null,o="error",e(`[vad] load failed (${r.message}) — the energy gate decides, as before`),!1}}function oe(e={}){if(g&&o!=="error")return g;o="loading";const n=typeof e.onLog=="function"?e.onLog:()=>{};return p=I({warmMs:e.warmMs,busy:v,log:n,unload:()=>j({log:n})}),g=X({log:n,allowDownload:e.allowDownload!==!1}).then(t=>(t&&!v()&&p?.arm(),t)),g}function $(e){if(!e.length)return 1;const n=[...e].sort((r,E)=>r-E),t=n[Math.floor(n.length*.9)]||0;return t>0?Math.min(B,Math.max(1,P/t)):1}function re(){let e=null,n=0;const t=new Map,r=[],E=Math.ceil(90*L/s);async function k(l){let u=0;for(let i=0;i<l.length;i++)u+=l[i]*l[i];r.push(Math.sqrt(u/l.length)),r.length>G&&r.shift();const d=$(r),a=d===1?l:l.map(i=>i*d);if(_)return _(a);e||=new M.Tensor("float32",new Float32Array(256),[2,1,128]);const f=await c({input:new M.Tensor("float32",a,[1,s]),sr:new M.Tensor("int64",[BigInt(L)],[]),state:e});return e=f.stateN,Number(f.output.data[0])}return{async advance(l,u){if(!A())return!1;const d=u+l.length;n<u&&(n=Math.ceil(u/s)*s),y++;try{for(;n+s<=d;n+=s){const a=n-u;t.set(n/s,await k(l.slice(a,a+s)))}}catch{return!1}finally{y--}for(const a of t.keys()){if(t.size<=E)break;t.delete(a)}return!0},speechIn(l,u,d=b){let a=!1;for(let f=Math.floor(l/s);f*s<u;f++){const i=t.get(f);if(i!==void 0&&(a=!0,i>=d))return!0}return a?!1:null},voicedIn(l,u,d=b){let a=!1,f=0;for(let i=Math.floor(l/s);i*s<u;i++){const D=t.get(i);D!==void 0&&(a=!0,D>=d&&f++)}return a?f*s/L:null},_probs:t}}function le(){p?.disarm(),p=null,x=0,y=0,o="off",c=null,_=null,m=null,g=null,w=null}function ae(e){_=e||null,o=e?"ready":"off"}export{h as DEFAULT_VAD_MODEL,s as FRAME,B as LEVEL_MAX_GAIN,P as LEVEL_TARGET,G as LEVEL_WINDOW,Q as OFFSET,b as ONSET,L as SAMPLE_RATE,J as VAD_MODEL_APPROX_MB,le as _reset,ae as _setForTest,re as createStream,ee as health,oe as init,A as isReady,$ as levelGain,W as modelOnDisk,Z as progress,ne as release,te as retain,Y as state,j as unload};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.155.0";export{o as VERSION};
|