@chatpanel/gateway 0.154.5 → 0.157.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/contexts-api.js +1 -1
- package/src/gateway-events.js +1 -0
- package/src/kb.js +3 -3
- package/src/link-activity.js +2 -2
- package/src/mcp.js +4 -1
- package/src/server.js +20 -20
- 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.157.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.509.0",
|
|
28
28
|
"@chatpanel/pii": "^0.15.6",
|
|
29
29
|
"@huggingface/transformers": "^4.2.0",
|
|
30
30
|
"defuddle": "^0.19.4",
|
package/src/contexts-api.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{makeContext as
|
|
1
|
+
import{makeContext as F,editContext as P,addToContext as W,removeFromContext as Z,contextIndex as D,contextMembers as _,suggestContexts as H,contextScope as K,addRefs as Q,removeRefs as V,setPeople as Y,parseRef as X,CONTEXT_COLORS as p,CONTEXT_NO_ACCESS as U,CONTEXT_ROLES as z,MAX_CONTEXT_INSTRUCTIONS as G}from"@chatpanel/events/contexts.js";import{contextAllows as J,contextFor as q}from"@chatpanel/events/context-access.js";import{toSearchRecord as tt}from"@chatpanel/events/library.js";import{randomUUID as et}from"node:crypto";const nt=/^context:[A-Za-z0-9_-]{1,80}$/,L=/^(chat|note|meeting|brief):[^\s]{1,200}$/,x=Object.freeze({kind:"owner"});class N extends Error{constructor(c,h){super(h),this.status=c}}function it({store:s,notify:c=()=>{},host:h="gateway",now:i=()=>Date.now(),newId:E=()=>et().replace(/-/g,"").slice(0,20),upstreamOk:k=()=>!1,audit:l=()=>{}}={}){const y=()=>s.ofKind("context").filter(t=>!t.deletedAt),S=t=>s.heads(t),u=(t,e=null,n=x)=>{const o=q(n,t,{upstreamOk:r=>k(r,n)});return o?{id:t.id,title:t.title,color:t.body?.color||p[0],about:t.body?.about||"",keywords:t.body?.keywords||[],...e?{counts:e.counts,last:e.last}:{},updatedAt:t.updatedAt,instructions:o.instructions,refs:o.refs,mcp_servers:o.mcp_servers,skills:o.skills,...o.access?{access:o.access}:{}}:null},d=(t,e,n)=>J(t,e,n),f=t=>{const e=s.write([t],{host:h,at:i()});return e.written.length&&c({ids:e.written}),s.get(t.id)||t},m=t=>{if(!nt.test(String(t||"")))return null;const e=s.get(t);return e&&!e.deletedAt?e:null},$=t=>t?.kind==="agent"?{kind:"agent",id:String(t.name||"unknown")}:{kind:"user",id:t?.kind==="person"?String(t.id):t?.kind==="owner"?"owner":"unknown"},C=(t,e,n,o,r)=>(l("access.denied",{resource:String(e||"context:?").slice(0,120),action:n,actor:$(t)}),new N(o,r)),j=(t,e,n)=>l("access.changed",{resource:e.id,actor:$(t),fields:n}),O=(t,e,n)=>{const o=m(e);if(!o)throw new N(404,"no such context");if(!d(t,o,"list"))throw C(t,e,n,404,"no such context");if(!d(t,o,n))throw C(t,e,n,403,`contexts: ${n} needs a role this caller does not have`);return o},R=t=>L.test(t),M=t=>(Array.isArray(t)?t:[]).slice(0,500);return{list(t=x){const e=y().filter(o=>d(t,o,"list")),n=[...new Set(e.flatMap(o=>_(o)))];return D(e,S(n)).map(o=>u(o.context,o,t)).filter(Boolean)},create(t={},e=x){if(e?.kind!=="owner")throw C(e,"context:new","create",403,"contexts: only the owner makes one here");B(t);const n=P(F({name:t.name,color:t.color,about:t.about,keywords:t.keywords,newId:E,now:i()}),ot(t),{now:i()});return u(f(n),null,e)},get(t,e=x){const n=O(e,t,"list");if(!d(e,n,"read"))return{context:u(n,null,e),items:[]};const[o]=D([n],S(_(n)));return{context:u(n,o,e),items:(o?.items||[]).map(r=>({id:r.id,kind:r.kind,title:r.title,updatedAt:r.updatedAt}))}},edit(t,e={},n=x){B(e);const o=e.agents!==void 0||e.noAccess!==void 0,r=O(n,t,o?"manage":"edit"),a=u(f(P(r,e,{now:i()})),null,n);return o&&j(n,r,["agents","noAccess"].filter(A=>e[A]!==void 0)),a},remove(t,e=x){const n=O(e,t,"manage"),o=i();return f({id:n.id,kind:"context",title:n.title,updatedAt:Math.max(o,Number(n.updatedAt)||0),deletedAt:Math.max(o,(Number(n.updatedAt)||0)+1)}),!0},items(t,{add:e=[],remove:n=[]}={},o=x){return this.resources(t,{add:M(e).map(String).filter(R),remove:M(n).map(String).filter(R)},o)},resources(t,{add:e=[],remove:n=[]}={},o=x){let r=O(o,t,"edit");const a=i(),A=w=>{const T=[],I=[];for(const b of M(w))typeof b=="string"&&R(b)?T.push(b):(typeof b=="string"?X(b):b&&X(`${b.type}:${b.id}`))&&I.push(b);return{members:T,refs:I}},g=A(e),v=A(n);return g.members.length&&(r=W(r,g.members,{now:a})),v.members.length&&(r=Z(r,v.members,{now:a})),g.refs.length&&(r=Q(r,g.refs,{now:a})),v.refs.length&&(r=V(r,v.refs,{now:a})),u(f(r),null,o)},people(t,e={},n=x){const o=O(n,t,"manage"),r={};for(const[A,g]of Object.entries(e&&typeof e=="object"?e:{})){if(g!==null&&!z.includes(g))throw new Error(`a role is ${z.join(", ")} or null`);r[A]=g}const a=u(f(Y(o,r,{now:i()})),null,n);return Object.keys(r).length&&j(n,o,["people"]),a},suggest({id:t="",title:e="",text:n="",limit:o=3}={},r=x){let a=String(e||""),A=String(n||"");if(t&&L.test(String(t))){const w=s.get(t),T=w?tt(w):null;a=a||w?.title||"",A=A||T?.text||""}const g=y().filter(w=>d(r,w,"edit")),v=S([...new Set(g.flatMap(w=>_(w)))]);return H({title:a,text:A,contexts:g,records:v,limit:Math.min(8,Math.max(1,Number(o)||3))}).filter(w=>!(t&&g.find(T=>T.id===w.id)?.body?.members?.[t]?.on))},scope(t,e=x){const n=O(e,t,"use");return K(n,S(_(n)))}}}function B(s={}){if(s.instructions!==void 0&&(typeof s.instructions!="string"||s.instructions.length>G))throw new Error(`instructions are a string of at most ${G} characters`);for(const c of["mcp_servers","skills","agents"])if(s[c]!==void 0&&s[c]!==null&&!(Array.isArray(s[c])&&s[c].every(h=>typeof h=="string")))throw new Error(`${c} is a list of names, or null for every one`);if(s.noAccess!==void 0&&!U.includes(s.noAccess))throw new Error(`noAccess is ${U.join(" or ")}`)}const ot=s=>Object.fromEntries(["instructions","mcp_servers","skills","noAccess","agents"].filter(c=>s[c]!==void 0).map(c=>[c,s[c]]));async function dt(s,c,{pathname:h,api:i,readJson:E,sendJson:k,principal:l=x}){if(!h.startsWith("/v1/contexts"))return!1;const y=(u,d,f="invalid_request_error")=>k(c,u,{error:{message:d,type:f}}),S=u=>{const d=u();return d?k(c,200,{ok:!0,context:d}):y(404,"no such context","not_found")};try{if(h==="/v1/contexts"&&s.method==="GET")return k(c,200,{ok:!0,contexts:i.list(l)}),!0;if(h==="/v1/contexts"&&s.method==="POST"){const m=await E(s);return String(m?.name||"").trim()?(k(c,200,{ok:!0,context:i.create(m,l)}),!0):(y(400,"a context needs a name"),!0)}if(h==="/v1/contexts/suggest"&&s.method==="POST")return k(c,200,{ok:!0,suggestions:i.suggest(await E(s),l)}),!0;const u=/^\/v1\/contexts\/(context:[A-Za-z0-9_-]{1,80})(\/items|\/scope|\/resources|\/people)?$/.exec(decodeURIComponent(h));if(!u)return y(404,"no such contexts route","not_found"),!0;const[,d,f]=u;if(!f&&s.method==="GET")return k(c,200,{ok:!0,...i.get(d,l)}),!0;if(!f&&s.method==="PATCH"){const m=await E(s);return S(()=>i.edit(d,m,l)),!0}if(!f&&s.method==="DELETE")return i.remove(d,l),k(c,200,{ok:!0}),!0;if(f==="/items"&&s.method==="POST"){const m=await E(s);return S(()=>i.items(d,m,l)),!0}if(f==="/resources"&&s.method==="POST"){const m=await E(s);return S(()=>i.resources(d,m,l)),!0}if(f==="/people"&&s.method==="POST"){const m=await E(s);return S(()=>i.people(d,m,l)),!0}return f==="/scope"&&s.method==="GET"?(k(c,200,{ok:!0,...i.scope(d,l)}),!0):(y(405,"method not allowed","method_not_allowed"),!0)}catch(u){return u instanceof N?(y(u.status,u.message,u.status===404?"not_found":"forbidden"),!0):(y(400,`contexts: ${u.message}`),!0)}}export{N as ContextDenied,it as createContextsApi,dt as handleContexts};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID as l}from"node:crypto";import{createAppender as s}from"./event.js";const o="gateway";function w({store:r=null,now:p=()=>Date.now(),newId:u=()=>l(),log:c=t=>{}}={}){let t=null;return function(n,f){if(!r)return!1;for(let a=0;a<2;a++)try{if(!t){const e=r.cursor()[o];t=s({host:o,seq:Number.isInteger(e)?e+1:0,now:p,newId:u})}return r.append(t.append(n,f)),!0}catch(e){if(t=null,e?.code!=="SEQ")return c(`[gateway-events] ${n} not recorded: ${e?.code||e?.message||e}`),!1}return!1}}export{o as GATEWAY_HOST,w as createGatewayEvents};
|
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/link-activity.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{randomUUID as
|
|
2
|
-
`))!==-1;)
|
|
1
|
+
import{randomUUID as v}from"node:crypto";import{createGatewayEvents as N,GATEWAY_HOST as R}from"./gateway-events.js";const d=e=>Math.max(0,Number(e)||0),i=(e,t)=>String(e??"").replace(/[\r\n\t]+/g," ").trim().slice(0,t);function D(e,t=""){if(!e)return null;if(e.kind==="partner")return`partner:${i(e.partner,40)||"partner"}`;const n=i(t,40);return n?`phone:${n}`:"phone"}function b(e){if(!e||typeof e!="object")return null;const t=d(e.prompt_tokens_details?.cached_tokens??e.input_tokens_details?.cached_tokens??e.cache_read_input_tokens),n=e.prompt_tokens!=null||e.input_tokens_details!=null,s=d(e.prompt_tokens??e.input_tokens),o={inputTokens:n?Math.max(0,s-t):s,outputTokens:d(e.completion_tokens??e.output_tokens),cacheReadTokens:t,cacheWriteTokens:d(e.cache_creation_input_tokens)};return o.inputTokens||o.outputTokens||o.cacheReadTokens||o.cacheWriteTokens?o:null}const S=e=>[e?.usage,e?.message?.usage,e?.response?.usage].filter(t=>t&&typeof t=="object");function U(e){try{const t=S(JSON.parse(String(e)))[0];return t?b(t):null}catch{return null}}function E(){const e=new TextDecoder;let t="",n=null;const s=c=>{const u=c.trim();if(!u.startsWith("data:"))return;const r=u.slice(5).trim();if(!r||r==="[DONE]"||!r.includes("usage"))return;let f;try{f=JSON.parse(r)}catch{return}for(const h of S(f)){n={...n||{}};for(const[T,l]of Object.entries(h))l!=null&&(n[T]=l)}};return{stream:new TransformStream({transform(c,u){t+=e.decode(c,{stream:!0});let r;for(;(r=t.indexOf(`
|
|
2
|
+
`))!==-1;)s(t.slice(0,r)),t=t.slice(r+1);u.enqueue(c)},flush(){t+=e.decode(),t&&s(t),t=""}}),usage:()=>b(n)}}function I({store:e=null,now:t=()=>Date.now(),newId:n=()=>v(),log:s=c=>{},events:o=null}={}){const c=o||N({store:e,now:t,newId:n,log:s}),u=r=>c("turn.ended",r);return{begin({caller:r,surface:f,agentId:h=null,model:T=null,dest:l=null,threadId:g=null,startedAt:y}={}){if(!e||!r||!f)return null;const W=Number.isFinite(y)?y:t(),x=`link-${n()}`,p={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};let O=!1,_=!1;return{turnId:x,get ended(){return _},add(a){if(!a)return;const m=Object.keys(p);if(m.some(k=>d(a[k]))){O=!0;for(const k of m)p[k]+=d(a[k])}},end(a="ok",{code:m=""}={}){if(_)return!1;_=!0;const k={turnId:x,reason:a,stepped:a==="ok",ms:Math.max(0,t()-W),kind:"chat",relayed:!0,surface:f,...h?{agentId:i(h,120)}:{},...T?{model:i(T,200)}:{},...l?.type?{dest:{type:l.type,id:i(l.id,120)}}:{},...g?{threadId:i(g,160)}:{},...O?{tokensIn:p.inputTokens,tokensOut:p.outputTokens,cacheReadTokens:p.cacheReadTokens,cacheWriteTokens:p.cacheWriteTokens}:{},...a==="error"&&m?{error:{code:i(m,60)}}:{}};return u(k)}}}}}export{R as GATEWAY_HOST,I as createLinkActivity,D as linkSurface,b as providerUsage,E as sseUsageTap,U as usageOfBody};
|
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/server.js
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
import{createServer as
|
|
1
|
+
import{createServer as mr}from"node:http";import{loadConfig as to}from"./config.js";import{startEntitlementRefresh as pr,maybeRevalidate as hr}from"./entitlement-refresh.js";import{redactSegments as We,segment as at,rememberAnswer as oo}from"./redact.js";import{pipeRestoredStream as yr,pipeRestoredOpenAIStream as fr,makeTokenRestorer as ro,restoreDeep as gr}from"./stream.js";import{restoreText as wr,gatedDictionary as br,narrowSpecs as vr,makeToolHarness as kr,placeholderToolNote as Sr,placeholderNote as Tr,assertEndpointUrl as xr,capRunOptions as _r,isPaired as no}from"@chatpanel/pii";import{ensureGatewayToken as Pe,currentGatewayToken as Je,isAdminAuthorized as R,callerTrustOf as Ke,setPinnedExtensionIds as Or,issuePairingCode as Er,claimPairingCode as Pr}from"./gateway-token.js";import{createPairAsk as $r,nativeConfirm as Ar}from"./pair-prompt.js";import{createEngineProbe as Nr}from"./local-engine-probe.js";import{randomUUID as Br}from"node:crypto";import{installEgressLedger as Mr,egressAudit as Dr}from"./egress.js";import{trustSystemCertificates as Cr,systemCaWanted as ao,systemCaState as Ir}from"./system-ca.js";import{initPolicy as Rr,activePolicy as st,applyPolicyToConfig as so,managedSummary as Qe,PolicyLoadError as Jr}from"./policy.js";import{routeAllowed as io,agentAllowed as Lr,egressAllowed as jr}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as Ye}from"./bridge.js";import{secureFetch as Le}from"./secure-fetch.js";import{fetchCard as it,forgetCard as zr,sendMessage as Gr,streamMessage as Hr,getTask as Ur,cancelTask as Vr,knownAgents as Fr,A2AError as lo}from"./a2a.js";import{streamBridgeChat as co,readBridgeToken as Xe,openBridgeChat as Wr,acceptedBridgeToken as uo}from"./bridge.js";import{createRelaySession as Kr,getRelaySession as mo,endRelaySession as Ze,pumpBridgeStream as Qr,deliverToolResult as po,toolsToSpecs as Yr,wantsApprovals as Xr,parseToolCallId as ho,touchRelaySession as lt}from"./toolrelay.js";import{shaperFor as kt}from"./shape.js";import{startNer as Zr,ensureNer as dt,unionForThisMachine as qr,skippedCompanions as en}from"./ner.js";import{recommendDetector as yo}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as tn}from"./log.js";import{saveBackupSecret as on,clearBackupSecret as rn,loadBackupSecret as St,hasBackupSecret as fo}from"./history-store.js";import{createContextsApi as nn,handleContexts as an}from"./contexts-api.js";let go=null;import{createMemoryStore as sn}from"./memory-store.js";import{createPrefsStore as ln}from"./prefs-store.js";import{agentCardFor as wo,runHintFor as bo}from"@chatpanel/events/agent-run-hint.js";import{normalizeThread as dn}from"@chatpanel/events/agent-thread.js";import{portClashPlan as cn,serviceManagerOf as un,STANDBY_POLL_MS as mn}from"@chatpanel/events/service-standby.js";import{threadTarget as pn,frameQuestion as hn,wireMessages as yn,appendExchange as fn,MAX_MESSAGE as vo}from"@chatpanel/events/thread-send.js";import{researchStore as gn,researchResponse as wn}from"./research.js";import{createTeamStore as bn,loadOrCreateKey as Tt}from"./team-store.js";import{createScorecardStore as vn}from"./scorecard-store.js";import{createEngineLedgerStore as kn}from"./engine-ledger-store.js";import{createProjectStore as Sn}from"./project-store.js";import{applicationsFor as Tn,recruitPass as xn}from"./recruiting.js";import{ensureBridge as _n,holderOf as On}from"./bridge-supervisor.js";import{checkForUpdate as En,updateStatus as Pn,startUpdate as $n,updateJob as An,installKind as Nn}from"./update.js";import{confinedStatus as ct,confinedLine as Bn}from"./confine.js";import{appleHelperWanted as Mn,findAppleHelper as xt}from"./apple-helper-fetch.js";import{createHistoryStore as Dn}from"./sqlite-store.js";import{createEventStore as Cn}from"./event-store.js";import{createGatewayEvents as In}from"./gateway-events.js";import{createLinkActivity as Rn,linkSurface as Jn,sseUsageTap as Ln,usageOfBody as jn,GATEWAY_HOST as ko}from"./link-activity.js";import{ingestCloudEvents as zn,cursorOf as So}from"./event-sync.js";import{eventStats as Gn,projectYear as Hn}from"./event-stats.js";import{toCloudEvent as _t,ceHostOf as Un}from"./cloudevents.js";import{fusionsDocument as Vn,resolveFusionModel as Fn}from"./fusions.js";import{ingestBackups as Ot}from"./backup-ingest.js";import{toSearchRecord as To}from"@chatpanel/events/library.js";import{deriveBackupKey as Wn,openRecord as Kn,keyCache as Qn,nodeCodec as Yn}from"@chatpanel/events/backup-envelope.js";import Xn from"node:zlib";import*as j from"./ner-engine.js";import Et from"node:os";import{capabilitiesDocument as Zn,handleDetect as qn}from"./capabilities.js";import{createExtractService as ea}from"./extract/service.js";import{workerSandbox as ta,disposeWorkerSandbox as oa}from"./worker-sandbox.js";import{createRuntime as ra,SERVICES as na}from"./runtime.js";import{createCapabilityProxy as aa}from"./capability-proxy.js";import{createEmbeddedCapabilities as sa}from"./capability-embedded.js";import{EMBEDDED_MODELS as ia,EMBEDDED_IDS as la}from"./embedded-models.js";import{handleExtract as da,handleExtractContext as ca}from"./extract/handler.js";import{createKbStore as ua}from"./kb-store.js";import{createKbService as ma}from"./kb.js";import{MAX_DOCUMENT_BYTES as ut}from"./extract-capability.js";import{createReader as pa}from"./retrieval/read.js";import{createBrowserRelayHost as ha}from"./browser-relay.js";import{createLinkHost as ya}from"./link-host.js";import{checkLinkRoute as fa,tunnelHeader as ga,LINK_TUNNEL_ROOM_PATH as wa}from"@chatpanel/events/link-routes.js";import{linkCallerOf as Be,linkDestinationAllowed as ba,linkVia as va,partnerRunHint as ka,PARTNER_APPROVAL_DECISIONS as xo,partnerFilePath as Sa}from"@chatpanel/events/link-scopes.js";import{listPartnerFiles as Ta,readPartnerFile as xa,writePartnerFile as _a,removePartnerFile as Oa}from"./link-files.js";import{handleFileWrite as Ea}from"./file-write.js";import{handleFileRead as Pa}from"./file-read.js";import{handleAppleNotes as $a}from"./apple-notes.js";import{handlePickFolder as Aa}from"./folder-picker.js";import{createContextService as Na}from"./context.js";import{createBucketSync as Ba}from"./kb-bucket-sync.js";import{createCloudProfiles as Ma}from"./cloud-profiles.js";import{revealPath as Da}from"./reveal.js";import{apiEnginesFrom as Ca}from"@chatpanel/events/search-api.js";import{CONTEXT_FEDERATED_HEADER as Ia}from"@chatpanel/events/context-api.js";import{WRITE_MAX_BYTES as Ra}from"@chatpanel/events/file-write.js";import{isPermissionTool as _o}from"@chatpanel/events/agent-permission.js";import{createApprovalInbox as Ja}from"./link-approvals.js";import{createSearcher as La,toJinaSearch as ja,SEARCH_DEFAULTS as za}from"./retrieval/search.js";import{createSearxng as Ga}from"./retrieval/search-searxng.js";import{searchEngines as Ha}from"./retrieval/search-apis.js";import{toJinaText as Ua}from"./read-document.js";import*as N from"./stt-engine.js";import*as $ from"./diarize-engine.js";import*as Me from"./translate-engine.js";import*as Va from"./indictrans-engine.js";import*as Pt from"./aec-engine.js";import{speechCoverage as Fa}from"@chatpanel/events/speech-language.js";import*as Wa from"./segment-engine.js";import{DIARIZE_MODEL_CATALOG as Ka,DEFAULT_DIARIZE_MODEL as Qa,isKnownDiarizeModel as Oo,diarizeModelEntry as Ya}from"./diarize-models.js";import{providerOf as $t}from"./providers.js";import{createRemoteTranscriber as Eo}from"./stt-remote.js";import{parseMultipart as Xa,decodeAudioFile as Za}from"./audio-file.js";import{MODEL_CATALOG as Po,isKnownModel as $o,isValidCustomModelId as Ao,recommendFor as qa}from"./models.js";import{STT_MODEL_CATALOG as es,isKnownSttModel as ts,isValidCustomSttId as os,DEFAULT_STT_MODEL as je,STT_DTYPES as rs,isValidDtype as ns,sttModel as mt,sttModelUnavailable as No,licenseAcceptance as Bo}from"./stt-models.js";import*as C from"./tts-engine.js";import{TTS_MODEL_CATALOG as Mo,TTS_VOICES as as,isKnownTtsModel as ss,isValidCustomTtsId as is,isKnownVoice as Do,isValidVoiceId as Co,DEFAULT_TTS_MODEL as Io,DEFAULT_TTS_VOICE as $e,TTS_DTYPES as ls,isValidTtsDtype as ds,MAX_TTS_CHARS as Ro,ttsModelHasCustomVoices as cs,resolveDefaultModel as Jo,POCKET_VOICES as us,DEFAULT_POCKET_VOICE as pt,isPocketVoice as ht,ttsModelEngine as yt}from"./tts-models.js";import{ttsDestination as ms,synthesizeRemote as ps,isValidRemoteVoice as hs}from"./tts-remote.js";import{rawOrtAvailable as At}from"./ort.js";import*as le from"./tts-voices.js";import{resolveTtsVoice as ys}from"./tts-voice-resolve.js";import{resolvePro as ke,checkQuota as fs,consume as gs,usage as ws}from"./freegate.js";import{publicConfig as Lo,applyConfigPatch as Nt,isSelfDestination as bs,registryChildEnv as vs,applyNerModelSelection as jo,persistConfig as he,configPath as te,bridgeAgentOptions as zo,PERMISSION_MODES as ks,sandboxEnvFor as Ss,sandboxProblems as Ts}from"./configstore.js";import{createDestinationsService as xs}from"./destinations-service.js";import{freeLimitProblem as _s}from"./capability-config.js";import ze from"node:path";import{resolveDestination as ft,aggregateModelsAsync as Os,listDestinations as Es,ensureModelCatalog as Ps,agentOwnsModel as $s}from"./router.js";import{makeAccessEvent as Go}from"./observability.js";import{createPersistentAccessLog as As}from"./access-log-store.js";import{planQueries as Ns,multiSearch as Bs}from"./rrf.js";import*as Bt from"./openai.js";import*as Ho from"./responses.js";import*as Mt from"./anthropic.js";import{closeAndExit as Ms}from"./shutdown.js";import{VERSION as se}from"./version.js";import{VERSION as dd}from"./version.js";const J=await Dn(),_e=new Set;function Ge({ids:t=[]}={}){const c=J.lossless;if(!c||!_e.size)return;const u=JSON.stringify({newest:c.newest,rev:c.rev,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const p of _e)try{p.write(`event: records
|
|
2
2
|
data: ${u}
|
|
3
3
|
|
|
4
4
|
`)}catch{_e.delete(p)}}setInterval(()=>{for(const t of _e)try{t.write(`: ping
|
|
5
5
|
|
|
6
|
-
`)}catch{_e.delete(t)}},25e3).unref?.();const
|
|
6
|
+
`)}catch{_e.delete(t)}},25e3).unref?.();const W=await Cn(),Uo=In({store:W,log:t=>console.log(t)}),Dt=Rn({store:W,events:Uo,log:t=>console.log(t)}),Ae=new Set;W?.watch(t=>{if(!Ae.size)return;const c=`event: cloudevent
|
|
7
7
|
data: ${JSON.stringify(_t(t))}
|
|
8
8
|
|
|
9
9
|
`;for(const u of Ae)try{u.write(c)}catch{Ae.delete(u)}}),setInterval(()=>{for(const t of Ae)try{t.write(`: ping
|
|
10
10
|
|
|
11
|
-
`)}catch{Ae.delete(t)}},25e3).unref?.();const ye=await
|
|
11
|
+
`)}catch{Ae.delete(t)}},25e3).unref?.();const ye=await sn(),de=ln(),He=vn({key:Tt()}),Ue=kn({key:Tt()}),ce=Sn({key:Tt()}),oe=bn({scorecards:He,engines:Ue}),Ct=new Set,Vo=(t,c)=>{for(const p of Ct)try{p({applied:t,by:c,revision:de.revision})}catch{}const u=JSON.stringify({revision:de.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const p of _e)try{p.write(`event: prefs
|
|
12
12
|
data: ${u}
|
|
13
13
|
|
|
14
|
-
`)}catch{_e.delete(p)}},It=
|
|
14
|
+
`)}catch{_e.delete(p)}},It=As(),Fo=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Ds=16,Cs=/^mcp[_-]/i,Wo=t=>t&&t.function&&t.function.name||t&&t.name||"",Is=t=>t&&t.function&&t.function.description||t&&t.description||"";function Ko(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function Rs(t,c){if(!t)return"";if(c==="responses"){const p=t.input;return typeof p=="string"?p:Array.isArray(p)?p.map(b=>Ko(b&&(b.content??b))).join(" "):""}const u=Array.isArray(t.messages)?t.messages:[];for(let p=u.length-1;p>=0;p--)if(u[p]&&u[p].role==="user")return Ko(u[p].content);return""}const Qo=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function gt(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function Js(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function Ls(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const Yo=Date.now();function js(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(u=>`${c[u]||u} ${t[u]}ms`).join(" · ")}function zs(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function Gs(t){const c=performance.now(),u={};let p=!1;const b=(g,A)=>{u[g]=Math.round(A*10)/10};return{meta:{},timings:u,mark:b,lap(g,A){b(g,performance.now()-A)},clock(){return performance.now()},commit(){if(p)return;p=!0,b("total",performance.now()-c);const g={...this.meta,timings:u};setImmediate(()=>{t(g),console.log(`[gateway] model=${g.model||"-"} → ${g.dest?`${g.dest}(${g.type})`:"none"} · ${g.redaction==="off"?"redaction OFF (client request)":`redacted ${g.redacted||0}`}${g.sanitized?` · scrubbed ${g.sanitized} hidden`:""}${g.narrowed?` · narrowed -${g.narrowed}`:""} · ${js(u)}`)})}}}function Xo(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const u=[];for(const[p,b]of t.byToken){const g=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(p),A=g?g[1]:"PII",M=p.replace(/^\[\[|\]\]$/g,"");u.push(c==="values"?{token:M,type:A,value:b}:{token:M,type:A})}return u}function Hs(t,c,u){return Mt.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:Mt,redactable:Mt.matches(t),base:u.upstreams?.anthropic?.baseUrl}:Ho.matches(t)?{kind:"responses",adapter:Ho,redactable:!0,base:u.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Bt,redactable:Bt.matches(t),base:u.upstreams?.openai?.baseUrl}}function Rt(t,c){const u=String(t||"");if(Fo.has(u))return{agent:u,agentModel:""};const p=u.indexOf("/");if(p>0){const b=u.slice(0,p);if(Fo.has(b))return{agent:b,agentModel:u.slice(p+1)}}return{agent:c.bridge.agent,agentModel:""}}function Zo(t,c){return Rt(t,c).agent}function Us(t,c){if(c!=="openai"||!t)return!1;const u=Bt.extractLatestToolResult(t);if(!u)return!1;const p=ho(u.tool_call_id);return!!(p&&mo(p.gwId))}function Vs(t,c){try{const u=new URL(t),p=u.hostname.replace(/^\[|\]$/g,""),b=p==="127.0.0.1"||p==="localhost"||p==="::1",g=u.port||(u.protocol==="https:"?"443":"80");return b&&String(g)===String(c.port)}catch{return!1}}const Fs=25*1024*1024;async function k(t,c){const u=[];let p=0;for await(const b of t){if(p+=b.length,c&&p>c){const g=new Error("payload too large");throw g.code=413,g}u.push(b)}return Buffer.concat(u)}function a(t,c,u){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(u))}function qo(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Jt(t){const c=t?.redaction?.detection,u=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:u,coverage:u==="full"?"names":"patterns"};const p=j.health(),b=p.ok&&u==="full";return{source:"bundled",state:p.state,model:p.model||t?.ner?.model||null,installed:j.modelOnDisk(t?.ner?.model||void 0),error:p.error||null,ready:b,tier:u,coverage:b?"names":"patterns"}}async function er(t){if(j.state()!=="off"){const u=j.health();return{configured:u.configured,ok:u.ok,state:u.state,model:u.model,error:u.error||null,url:u.configured?`http://${t.host}:${t.port}/ner`:null,stats:u.stats,companions:u.companions}}const c=qo(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const u=await Le(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!u.ok)return{configured:!0,ok:!1,url:c,model:null};const p=await u.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:p.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function Ws(t,c){const u={};for(const[p,b]of Object.entries(t)){const g=p.toLowerCase();g.startsWith("x-chatpanel-")||Qo.has(g)||(u[p]=b)}u["accept-encoding"]="identity";try{u.host=new URL(c).host}catch{}return u}async function tr(t,c,u,p){const b=ro(c.vault),g=jt();t.on("close",()=>{t.writableFinished||Ze(c.id)});const A=c.linkTurn||null,M=p?p.clock():0;let E=M,S=!0;const x=()=>{p&&S&&(p.lap("upstream",M),E=p.clock(),S=!1)};let L="";const z=()=>{c.redaction&&L&&oo(L,c.redaction),L=""};let F=null;const P={onText:V=>{x(),lt(c.id);const G=b.push(V);G&&(L+=G,t.write(u.sseDelta(G)))},onToolRequest:({name:V,restoredArgs:G,toolId:Y})=>{if(x(),lt(c.id),c.ownerApprovals&&_o(V)){F=G;return}const ee=b.flush();ee&&(L+=ee,t.write(u.sseDelta(ee))),t.write(u.sseToolCalls([{id:Y,name:V,arguments:JSON.stringify(G)}])),t.write(u.sseToolFinish(g.value)),p&&p.lap("stream",E),t.end(),p?.commit(),z()},onDone:()=>{const V=b.flush();V&&(L+=V,t.write(u.sseDelta(V))),t.write(u.sseTail(g.value)),p&&p.lap("stream",E),t.end(),A?.end("ok"),Ze(c.id),p?.commit(),z(),Lt(c)},onError:V=>{t.write(`data: ${JSON.stringify({error:{message:V.message,type:"bridge_error"}})}
|
|
15
15
|
|
|
16
|
-
`),t.end(),A?.end("error",{code:"bridge_error"}),Ze(c.id),p?.commit(),Lt(c)},onUsage:V=>{g.add(V),A?.add(V)}};for(;;){if(F=null,await
|
|
16
|
+
`),t.end(),A?.end("error",{code:"bridge_error"}),Ze(c.id),p?.commit(),Lt(c)},onUsage:V=>{g.add(V),A?.add(V)}};for(;;){if(F=null,await Qr(c,P)!=="parked"||!F)return;const G=c.ownerApprovals,Y=new AbortController,ee=()=>Y.abort();t.once("close",ee);const X=setInterval(()=>{lt(c.id),t.writableEnded||t.write(`: waiting for the owner’s approval
|
|
17
17
|
|
|
18
|
-
`)},15e3);X.unref?.();let me;try{me=await G.inbox.ask(F,{partner:G.partner,device:G.device,conversation:G.conversation,signal:Y.signal})}finally{clearInterval(X),t.off("close",ee)}if(Y.signal.aborted||t.writableEnded){Lt(c);return}try{await po(c,JSON.stringify(me))}catch(q){P.onError(q);return}}}function Lt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function
|
|
18
|
+
`)},15e3);X.unref?.();let me;try{me=await G.inbox.ask(F,{partner:G.partner,device:G.device,conversation:G.conversation,signal:Y.signal})}finally{clearInterval(X),t.off("close",ee)}if(Y.signal.aborted||t.writableEnded){Lt(c);return}try{await po(c,JSON.stringify(me))}catch(q){P.onError(q);return}}}function Lt(t){t.ownerApprovals?.turnScoped&&t.ownerApprovals.inbox.forget(t.ownerApprovals.conversation)}async function Ks(t,c,{kind:u,adapter:p,agent:b,run:g=null,owner:A=null,linkTurn:M=null},E,S,x,L,z,F=null,P=null){const{messages:V,system:G}=p.toTurn(E),{agentModel:Y}=Rt(E?.model,x),ee=zo(x,{...Y?{model:Y}:{},...g||{}}),X=Xe(x.bridge.token),me=kt(u,E?.model||b),q={tier:x.redaction.tier==="full"?"full":"basic",dictionary:br(x.redaction,L),entities:[]},pe=await Ye(x),I=Kr({vault:S,redactOpts:q,bridgeUrl:pe,token:X,harness:F});A&&(I.ownerApprovals={...A,conversation:A.conversation||`partner.${A.device}.turn-${I.id}`,turnScoped:!A.conversation}),M&&(I.linkTurn=M,I.onEnd=()=>M.end("aborted")),S&&(I.redaction=x.redaction);let Z;try{Z=await Wr({bridgeUrl:pe,agent:b,token:X,messages:V,system:G,specs:Yr(z),options:ee,signal:void 0,approvals:!!A||Xr(z)})}catch(be){return M?.end("error",{code:"bridge_error"}),Ze(I.id),P?.commit(),a(c,502,{error:{message:`bridge: ${be.message}`,type:"bridge_error"}})}return I.reader=Z.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(me.sseHead()),tr(c,I,me,P)}async function Qs(t,c,u,p,b=null){lt(c.id),c.rounds=(c.rounds||0)+1;try{const A=b?b.clock():0;await po(c,u),b&&b.lap("redact",A)}catch(A){return c.linkTurn?.end("error",{code:"tool_result"}),Ze(c.id),b?.commit(),a(t,502,{error:{message:`tool-result: ${A.message}`,type:"bridge_error"}})}const g=kt("openai",p||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(g.sseHead()),tr(t,c,g,b)}function jt(){let t=!1;const c={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0};return{add(u){t=!0;for(const p of Object.keys(c))c[p]+=Math.max(0,Number(u?.[p])||0)},get value(){return t?c:null}}}async function Ys(t,c,{kind:u,adapter:p,redactable:b,pathname:g,agentOverride:A,harness:M,trace:E,run:S=null,owner:x=null,link:L=null},z,F,P,V){if(!b)return E?.commit(),a(c,404,{error:`endpoint ${g} not supported by the bridge backend`});if(u==="openai"){const r=p.extractLatestToolResult(z);if(r){const y=ho(r.tool_call_id),i=y&&mo(y.gwId);if(i)return Qs(c,i,r.content,z?.model,E)}const o=p.extractTools(z);if((o.length||x)&&z?.stream===!0){const y=A||Zo(z?.model,P),i=L?Dt.begin({...L,agentId:y}):null;return Ks(t,c,{kind:u,adapter:p,agent:y,run:S,owner:x,linkTurn:i},z,F,P,V,o,M,E)}}const{messages:G,system:Y}=p.toTurn(z),ee=A||Zo(z?.model,P),X=L?Dt.begin({...L,agentId:ee}):null,me=z?.stream===!0,q=kt(u,z?.model||ee),pe=Xe(P.bridge.token),I=new AbortController;c.on("close",()=>{c.writableFinished||I.abort()});const{agentModel:Z}=Rt(z?.model,P),be={bridgeUrl:await Ye(P),agent:ee,token:pe,messages:G,system:Y,signal:I.signal,options:zo(P,{...Z?{model:Z}:{},...S||{}})};if(!me)try{let r="";const o=jt(),y=E?E.clock():0;await co(be,H=>{r+=H},null,H=>o.add(H)),E&&E.lap("upstream",y);const i=E?E.clock():0,K=q.full(wr(r,F),o.value);return E&&E.lap("restore",i),c.writeHead(200,{"content-type":q.contentType}),c.end(K),X?.add(o.value),X?.end("ok"),E?.commit()}catch(r){return X?.end(I.signal.aborted?"aborted":"error",{code:"bridge_error"}),E?.commit(),a(c,502,{error:{message:`bridge backend failed: ${r.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(q.sseHead());const Oe=ro(F),Se=E?E.clock():0;let De=Se;const Ee=jt();let Ce="",ge=!1;try{let r=!0;await co(be,y=>{E&&r&&(E.lap("upstream",Se),De=E.clock(),r=!1);const i=Oe.push(y);i&&(Ce+=i,c.write(q.sseDelta(i)))},q.sseActivity?y=>{try{c.write(q.sseActivity(gr(y,F)))}catch{}}:null,y=>Ee.add(y));const o=Oe.flush();o&&(Ce+=o,c.write(q.sseDelta(o))),c.write(q.sseTail(Ee.value))}catch(r){ge=!0,c.write(`data: ${JSON.stringify({error:{message:r.message,type:"bridge_error"}})}
|
|
19
19
|
|
|
20
|
-
`)}E&&E.lap("stream",De),c.end(),X&&(X.add(Ee.value),X.end(I.signal.aborted?"aborted":ge?"error":"ok",{code:"bridge_error"})),E?.commit(),F&&Ce&&oo(Ce,P.redaction)}function Qs(t,c,u=""){const p=String(t||"").replace(/\/+$/,""),b=String(c||"").split("/")[1];return b&&p.endsWith(`/${b}`)?p.slice(0,-(b.length+1))+c+u:p+c+u}const tr=9e4,zt=60,or=zt*16e3*4,Ys=4e3;function Xs(t,c,u){if(c===u)return t;const p=c/u,b=new Float32Array(Math.floor(t.length/p));for(let g=0;g<b.length;g++){const A=g*p,M=Math.floor(A),E=Math.min(t.length-1,M+1),S=A-M;b[g]=t[M]*(1-S)+t[E]*S}return b}const rr=new WeakMap,Zs=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function nr(t,c){const u=mt(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Bo(u):null}function Gt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function we(t,c,u,p,{method:b="GET",timeoutMs:g=8e3,pick:A=M=>M}={}){const M=await Ye(u);if(!M)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const E=Xe(u.bridge?.token),S=b!=="GET"&&b!=="DELETE";try{const x=S?(await k(t,u.maxBodyBytes)).toString("utf8"):"",J=await fetch(`${M}${p}`,{method:b,headers:{Accept:"application/json",...S?{"content-type":"application/json"}:{},...E?{Authorization:`Bearer ${E}`}:{}},...S?{body:x||"{}"}:{},signal:AbortSignal.timeout(g)}),z=await J.json().catch(()=>({}));return J.ok?a(c,200,A(z)):a(c,J.status,{error:{message:z?.error||`bridge ${J.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Ht(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ve(t,c){const u=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&u.append("dir",g);const p=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();p&&u.set("workdir",p);const b=u.toString();return b?`?${b}`:""}async function qs(t,c,{adapter:u,kind:p,pathname:b,search:g,base:A,destKey:M,destProtocol:E,harness:S,trace:x,link:J=null},z,F){let P;const V=x?x.clock():0,G=J?Dt.begin(J):null;let Y=!1;const ee=new AbortController;c.on("close",()=>{c.writableFinished||(Y=!0,ee.abort())});const X=(I,Z)=>{G&&(G.add(Z),G.end(Y?"aborted":I>=400?"error":"ok",{code:`http_${I}`}))};try{const I=Vs(t.headers,A);M&&(E==="anthropic"?(I["x-api-key"]=M,delete I.authorization):I.authorization=`Bearer ${M}`);const Z=Tr(Qs(A,b,g)).toString();P=await fetch(Z,{method:t.method,headers:I,body:["GET","HEAD"].includes(t.method)?void 0:z,signal:ee.signal})}catch(I){return Y?(X(499),x?.commit()):(G?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${I.message}`}))}const me=P.headers.get("content-type")||"",q={};if(P.headers.forEach((I,Z)=>{Ko.has(Z.toLowerCase())||(q[Z]=I)}),me.includes("text/event-stream")&&P.body){x&&x.lap("upstream",V);const I=x?x.clock():0;c.writeHead(P.status,q);const Z=G?Rn():null,be=Z?P.body.pipeThrough(Z.stream):P.body,Oe=p==="openai"?yr(be,c,F,S):hr(be,c,F);return Promise.resolve(Oe).catch(Se=>{if(!Y)throw Se}).finally(()=>{x&&x.lap("stream",I),X(P.status,Z?.usage()),x?.commit()})}let pe;try{pe=Buffer.from(await P.arrayBuffer())}catch(I){if(Y)return X(499),x?.commit();throw I}if(x&&x.lap("upstream",V),G&&X(P.status,me.includes("json")?Jn(pe.toString("utf8")):null),F&&me.includes("application/json"))try{const I=x?x.clock():0,Z=u.restoreResponse(JSON.parse(pe.toString("utf8")),F,S);return x&&x.lap("restore",I),c.writeHead(P.status,{...q,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(Z),"utf8")),x?.commit()}catch{}c.writeHead(P.status,q),c.end(pe),x?.commit()}function ei(t=to()){const c=Ar({first:async r=>{const o=Number(new URL(r).port),y=oa.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await z())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),u=Pr({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):$r(r),newId:()=>Nr()}),p=ma({version:se}),b=Ia({log:r=>console.log(` ${r}`)}),g=t.link?.enabled===!1?null:pa({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:W,signal:H})=>fetch(`http://127.0.0.1:${ge.address()?.port||t.port}${o}`,{method:r,body:i,...H?{signal:H}:{},headers:{...y,"x-chatpanel-token":Je()||Pe(),"x-chatpanel-link-device":String(W||"")}}),ownerIsPro:()=>ke(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==$.activeModel()&&(Oo(t.stt.diarizeModel)?$.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Wa}`));let A=null;const M=()=>{if(!A){const r=t.read||{};A=ua({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return A};let E=null;const S=()=>(E||(E=Zn({wrap:(r,o,y,i)=>qn().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),E);let x={at:0,fn:()=>"unknown"},J=null;async function z(){if(Date.now()-x.at<1e4)return x.fn;let r=new Map;try{const i=await P().health();for(const[W,H]of Object.entries(i)){const ve=(t.destinations||[]).filter(ue=>ue?.service===W).flatMap(ue=>[ue.id,...ue.models||[]]);for(const ue of[W,...ve])r.set(ue,H)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return P().contextWindow(y.get(i)||i)}catch{return null}},o.card=i=>{try{return P().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),x={at:Date.now(),fn:o},x.fn}let F=null;const P=()=>(F||(F=ta({cfg:t,bridgeHealth:async()=>{const r=await Ye(t);if(!r)return null;const o=Xe(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{he(t,te())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:ze.join(ze.dirname(te()),"runtime"),workers:()=>{const r=E?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),F),V=Number(t.runtime?.idleMinutes),G=na({warmMs:(Number.isFinite(V)&&V>=0?V:10)*6e4,log:r=>console.log(r)}),Y=ra({cfg:t,wake:(r,o)=>P().wake(r,o),embedded:G,asleep:r=>P().isAsleep(r)});let ee=null;const X=()=>(ee||(ee=ca({store:da({log:r=>console.warn(`[kb] ${r}`)}),extract:S,embedded:G,cfg:t,rerank:async(r,o)=>{const y=await Y.call("rerank",{query:r,documents:o.map(W=>String(W).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const W of y.body.results||[])i[W.index]=W.relevance_score;return i},read:()=>M(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,W=setTimeout(()=>i.abort(),3e4);try{const H=Je()||Pe(),ve=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...H?{Authorization:`Bearer ${H}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),ue=await ve.json().catch(()=>({}));return ve.ok?String(ue?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(W)}},log:r=>console.warn(r),team:r=>I().teamOf(r),remoteCards:()=>be().remoteCards(),reveal:(r,o)=>Ba(r,o),confined:()=>!!ct({stateDir:ze.dirname(te())}).on})),ee);let me=null;const q=()=>me||=Na();let pe=null;const I=()=>(pe||(pe=Aa({store:X().store,kb:()=>X(),profiles:q(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>Le(r,{...o,maxRedirects:0}),version:se,log:r=>console.log(r)})),pe);let Z=null;const be=()=>(Z||(Z=$a({cfg:t,kb:()=>X(),buckets:I(),profiles:q(),search:async(r,{limit:o=8}={})=>{Oe();const y=await De().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:Ma(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await We([at(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await Y.call("rerank",{query:r,documents:o.map(W=>String(W).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const W of y.body.results||[])i[W.index]=W.relevance_score;return i},fetchFn:(r,o)=>Le(r,o),persist:()=>he(t,te()),log:r=>console.log(r)})),Z),Oe=()=>{t.search?.searxng?.url&&P().wake("searxng").catch(()=>{})};let Se=null;const De=()=>{if(!Se){const r=t.search||{},o=r.searxng?.url?ja({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;Se=Ra({reader:M(),searxng:o,engines:()=>za(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await We([at(()=>i,W=>{i=W})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return Se};_r(t.allowedExtensionIds||[]);const Ee=[],Ce=r=>{Ee.push(r),Ee.length>50&&Ee.shift()},ge=ur(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!gt(r.headers.host))return a(o,403,{error:"loopback only"});if(!Is(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(gt(t.host)&&ya(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&Rs(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&r.method==="POST")return L(r)?a(o,200,{token:Pe()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!L(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Or();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Er(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${Ke(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${Ke(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await uo(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Je()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=Ke(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(no(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=u.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=u.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await uo(t);return a(o,200,{ok:!0,status:n,token:Je()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=Ke(r);return a(o,200,{ok:!0,trust:e,paired:no(e),version:se})}if(i==="/audit"&&r.method==="GET")return L(r)?a(o,200,Mr(t,{version:se,startedAt:Qo,managed:Qe(),certificates:{...Cr(),wanted:ao(t)},linkPartners:g?g.status().devices.filter(e=>e.kind==="partner"):[],confined:ct({stateDir:ze.dirname(te())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!L(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await On(se,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:se,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:$n()})}if(i==="/update"&&r.method==="POST"){const e=Pn(se);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!L(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!L(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&r.method==="POST"&&!L(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&r.method!=="GET"&&i!=="/v1/contexts/suggest"&&!L(r))return a(o,403,{error:{message:"contexts write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!L(r))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!L(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!L(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!L(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!L(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!L(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${se} is running.
|
|
20
|
+
`)}E&&E.lap("stream",De),c.end(),X&&(X.add(Ee.value),X.end(I.signal.aborted?"aborted":ge?"error":"ok",{code:"bridge_error"})),E?.commit(),F&&Ce&&oo(Ce,P.redaction)}function Xs(t,c,u=""){const p=String(t||"").replace(/\/+$/,""),b=String(c||"").split("/")[1];return b&&p.endsWith(`/${b}`)?p.slice(0,-(b.length+1))+c+u:p+c+u}const or=9e4,zt=60,rr=zt*16e3*4,Zs=4e3;function qs(t,c,u){if(c===u)return t;const p=c/u,b=new Float32Array(Math.floor(t.length/p));for(let g=0;g<b.length;g++){const A=g*p,M=Math.floor(A),E=Math.min(t.length-1,M+1),S=A-M;b[g]=t[M]*(1-S)+t[E]*S}return b}const nr=new WeakMap,ei=["/tts","/stt","/ner","/diarize","/skills","/agent-defs","/agent-sessions","/a2a","/redact","/config","/logs","/status","/admin","/v1/browser","/v1/link","/v1/voice"];function ar(t,c){const u=mt(c)?.license;return u&&t.stt?.licenses?.[u.id]?.version===u.version?Bo(u):null}function Gt(t,{installing:c=!1}={}){return t.stt?.diarize===!1?"off":c&&t.stt?.allowDownload!==!1?"download":"ondisk"}async function we(t,c,u,p,{method:b="GET",timeoutMs:g=8e3,pick:A=M=>M}={}){const M=await Ye(u);if(!M)return a(c,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const E=Xe(u.bridge?.token),S=b!=="GET"&&b!=="DELETE";try{const x=S?(await k(t,u.maxBodyBytes)).toString("utf8"):"",L=await fetch(`${M}${p}`,{method:b,headers:{Accept:"application/json",...S?{"content-type":"application/json"}:{},...E?{Authorization:`Bearer ${E}`}:{}},...S?{body:x||"{}"}:{},signal:AbortSignal.timeout(g)}),z=await L.json().catch(()=>({}));return L.ok?a(c,200,A(z)):a(c,L.status,{error:{message:z?.error||`bridge ${L.status}`,type:"bridge_error"}})}catch(x){return a(c,502,{error:{message:`bridge unreachable: ${x.message}`,type:"bridge_unreachable"}})}}function Ht(t){return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")}function Ve(t,c){const u=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&u.append("dir",g);const p=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();p&&u.set("workdir",p);const b=u.toString();return b?`?${b}`:""}async function ti(t,c,{adapter:u,kind:p,pathname:b,search:g,base:A,destKey:M,destProtocol:E,harness:S,trace:x,link:L=null},z,F){let P;const V=x?x.clock():0,G=L?Dt.begin(L):null;let Y=!1;const ee=new AbortController;c.on("close",()=>{c.writableFinished||(Y=!0,ee.abort())});const X=(I,Z)=>{G&&(G.add(Z),G.end(Y?"aborted":I>=400?"error":"ok",{code:`http_${I}`}))};try{const I=Ws(t.headers,A);M&&(E==="anthropic"?(I["x-api-key"]=M,delete I.authorization):I.authorization=`Bearer ${M}`);const Z=xr(Xs(A,b,g)).toString();P=await fetch(Z,{method:t.method,headers:I,body:["GET","HEAD"].includes(t.method)?void 0:z,signal:ee.signal})}catch(I){return Y?(X(499),x?.commit()):(G?.end("error",{code:"upstream_unreachable"}),x?.commit(),a(c,502,{error:`upstream fetch failed: ${I.message}`}))}const me=P.headers.get("content-type")||"",q={};if(P.headers.forEach((I,Z)=>{Qo.has(Z.toLowerCase())||(q[Z]=I)}),me.includes("text/event-stream")&&P.body){x&&x.lap("upstream",V);const I=x?x.clock():0;c.writeHead(P.status,q);const Z=G?Ln():null,be=Z?P.body.pipeThrough(Z.stream):P.body,Oe=p==="openai"?fr(be,c,F,S):yr(be,c,F);return Promise.resolve(Oe).catch(Se=>{if(!Y)throw Se}).finally(()=>{x&&x.lap("stream",I),X(P.status,Z?.usage()),x?.commit()})}let pe;try{pe=Buffer.from(await P.arrayBuffer())}catch(I){if(Y)return X(499),x?.commit();throw I}if(x&&x.lap("upstream",V),G&&X(P.status,me.includes("json")?jn(pe.toString("utf8")):null),F&&me.includes("application/json"))try{const I=x?x.clock():0,Z=u.restoreResponse(JSON.parse(pe.toString("utf8")),F,S);return x&&x.lap("restore",I),c.writeHead(P.status,{...q,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(Z),"utf8")),x?.commit()}catch{}c.writeHead(P.status,q),c.end(pe),x?.commit()}function oi(t=to()){const c=Nr({first:async r=>{const o=Number(new URL(r).port),y=na.find(i=>i.port===o&&(i.provides||[]).includes("chat"));return y&&(await z())(y.id)==="up"?{engine:y.id,label:y.label,models:null}:null}}),u=$r({confirm:r=>typeof t.pairing?.confirm=="function"?t.pairing.confirm(r):Ar(r),newId:()=>Br()}),p=ha({version:se}),b=Ja({log:r=>console.log(` ${r}`)}),g=t.link?.enabled===!1?null:ya({settings:t.link||{},port:t.port,...t.link?.path?{path:t.link.path}:{},dispatch:({method:r,path:o,headers:y,body:i,device:K,signal:H})=>fetch(`http://127.0.0.1:${ge.address()?.port||t.port}${o}`,{method:r,body:i,...H?{signal:H}:{},headers:{...y,"x-chatpanel-token":Je()||Pe(),"x-chatpanel-link-device":String(K||"")}}),ownerIsPro:()=>ke(t.pro?.entitlementToken),log:r=>console.log(` ${r}`)});t.stt?.diarizeModel&&t.stt.diarizeModel!==$.activeModel()&&(Oo(t.stt.diarizeModel)?$.setModel(t.stt.diarizeModel,{log:r=>console.log(r)}):console.warn(`[diarize] config names an unknown speaker model (${t.stt.diarizeModel}) — using ${Qa}`));let A=null;const M=()=>{if(!A){const r=t.read||{};A=pa({remote:r.remote?.url?{url:r.remote.url,key:r.remote.key||""}:null,defaultProvider:r.provider||"defuddle"})}return A};let E=null;const S=()=>(E||(E=ea({wrap:(r,o,y,i)=>ta().wrap(r,o,y,i),onLog:r=>console.warn(`[extract worker] ${r}`)})),E);let x={at:0,fn:()=>"unknown"},L=null;async function z(){if(Date.now()-x.at<1e4)return x.fn;let r=new Map;try{const i=await P().health();for(const[K,H]of Object.entries(i)){const ve=(t.destinations||[]).filter(ue=>ue?.service===K).flatMap(ue=>[ue.id,...ue.models||[]]);for(const ue of[K,...ve])r.set(ue,H)}}catch{r=new Map}const o=i=>r.get(i)||"unknown",y=new Map((t.destinations||[]).filter(i=>i?.service).map(i=>[i.id,i.service]));return o.window=i=>{try{return P().contextWindow(y.get(i)||i)}catch{return null}},o.card=i=>{try{return P().modelCard(y.get(i)||i)}catch{return null}},o.sig=JSON.stringify([...r.entries()].sort()),x={at:Date.now(),fn:o},x.fn}let F=null;const P=()=>(F||(F=ra({cfg:t,bridgeHealth:async()=>{const r=await Ye(t);if(!r)return null;const o=Xe(t.bridge?.token),y=await fetch(`${r}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return y.ok?y.json():null},persist:()=>{try{he(t,te())}catch(r){console.warn(`[runtime] could not persist config: ${r.message}`)}},stateDir:ze.join(ze.dirname(te()),"runtime"),workers:()=>{const r=E?.status();return r?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:r.pid,sandbox:r.sandbox,refused:[]}]:[]},log:r=>console.log(r)})),F),V=Number(t.runtime?.idleMinutes),G=sa({warmMs:(Number.isFinite(V)&&V>=0?V:10)*6e4,log:r=>console.log(r)}),Y=aa({cfg:t,wake:(r,o)=>P().wake(r,o),embedded:G,asleep:r=>P().isAsleep(r)});let ee=null;const X=()=>(ee||(ee=ma({store:ua({log:r=>console.warn(`[kb] ${r}`)}),extract:S,embedded:G,cfg:t,rerank:async(r,o)=>{const y=await Y.call("rerank",{query:r,documents:o.map(K=>String(K).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const K of y.body.results||[])i[K.index]=K.relevance_score;return i},read:()=>M(),completer:r=>async(o,{maxTokens:y=160}={})=>{const i=new AbortController,K=setTimeout(()=>i.abort(),3e4);try{const H=Je()||Pe(),ve=await fetch(`http://127.0.0.1:${t.port}/v1/chat/completions`,{method:"POST",signal:i.signal,headers:{"content-type":"application/json",...H?{Authorization:`Bearer ${H}`}:{},"X-ChatPanel-Client":"kb"},body:JSON.stringify({model:r,messages:[{role:"user",content:o}],stream:!1,max_tokens:y,temperature:0})}),ue=await ve.json().catch(()=>({}));return ve.ok?String(ue?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(K)}},log:r=>console.warn(r),team:r=>I().teamOf(r),remoteCards:()=>be().remoteCards(),reveal:(r,o)=>Da(r,o),confined:()=>!!ct({stateDir:ze.dirname(te())}).on})),ee);let me=null;const q=()=>me||=Ma();let pe=null;const I=()=>(pe||(pe=Ba({store:X().store,kb:()=>X(),profiles:q(),entries:()=>Array.isArray(t.context?.providers)?t.context.providers:[],fetchFn:(r,o)=>Le(r,{...o,maxRedirects:0}),version:se,log:r=>console.log(r)})),pe);let Z=null;const be=()=>(Z||(Z=Na({cfg:t,kb:()=>X(),buckets:I(),profiles:q(),search:async(r,{limit:o=8}={})=>{Oe();const y=await De().search({q:r,limit:o,read:0});if(y.status!==200)throw new Error(y.body?.error?.message||`search ${y.status}`);return y.body},apiEngines:()=>t.search?.provider==="searxng"?[]:Ca(t.search?.apis).filter(r=>r.enabled!==!1),redact:async r=>{let o=r;return await We([at(()=>o,y=>{o=y})],{...t.redaction,tier:"basic"},{isPro:!0}),o.replace(/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g," ").replace(/\s+/g," ").trim()},rerank:async(r,o)=>{const y=await Y.call("rerank",{query:r,documents:o.map(K=>String(K).slice(0,2e3))});if(y.status!==200)return null;const i=new Array(o.length).fill(0);for(const K of y.body.results||[])i[K.index]=K.relevance_score;return i},fetchFn:(r,o)=>Le(r,o),persist:()=>he(t,te()),log:r=>console.log(r)})),Z),Oe=()=>{t.search?.searxng?.url&&P().wake("searxng").catch(()=>{})};let Se=null;const De=()=>{if(!Se){const r=t.search||{},o=r.searxng?.url?Ga({url:r.searxng.url,token:r.searxng.token||"",engines:r.searxng.engines||"",safesearch:r.searxng.safesearch??null}):null;Se=La({reader:M(),searxng:o,engines:()=>Ha(t),wakeSearxng:()=>P().wake("searxng"),defaultProvider:r.provider||"auto",redact:async y=>{let i=y;return await We([at(()=>i,K=>{i=K})],{...t.redaction,tier:"basic"},{isPro:!0}),i}})}return Se};Or(t.allowedExtensionIds||[]);const Ee=[],Ce=r=>{Ee.push(r),Ee.length>50&&Ee.shift()},ge=mr(async(r,o)=>{const y=new URL(r.url,"http://127.0.0.1");let i=y.pathname;if(!gt(r.headers.host))return a(o,403,{error:"loopback only"});if(!Js(r.headers.origin,t))return a(o,403,{error:"origin not allowed"});if(gt(t.host)&&ga(r.headers))return a(o,403,{error:{message:"this gateway answers a tunnel only on its Link path (/v1/link)",type:"forbidden"}});if(r.headers.origin&&Ls(o,r.headers.origin),r.method==="OPTIONS")return o.writeHead(204),o.end();if(i==="/admin/token"&&r.method==="POST")return R(r)?a(o,200,{token:Pe()}):a(o,403,{error:"admin: extension origin or gateway token required"});if(i==="/pair/code"&&r.method==="POST"){if(!R(r))return a(o,403,{error:"pair/code: extension origin or gateway token required"});const e=Er();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),a(o,200,{ok:!0,...e})}if(i==="/pair"&&r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=Pr(e?.code);if(!n.ok)return console.log(`[gateway] pairing refused (${n.reason}) from ${Ke(r)} caller`),a(o,403,{error:n.reason});console.log(`[gateway] paired a ${Ke(r)} client${r.headers.origin?` (${r.headers.origin})`:""}`);const{token:s,refused:l}=await uo(t);return l&&console.log(`[gateway] pairing: the bridge at ${l.url}${l.version?` (v${l.version})`:""} accepts none of the tokens this gateway holds — not handing one over`),a(o,200,{ok:!0,token:Je()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/pair/ask"&&r.method==="POST"){const e=Ke(r);if(t.pairing?.prompt===!1)return a(o,403,{error:"pairing by confirmation is switched off on this gateway — use a pairing code",type:"disabled"});if(no(e))return a(o,409,{error:"this client is already trusted by the gateway",type:"already"});if(e!=="unpaired")return a(o,403,{error:"pair/ask: only a browser extension may ask to be paired",type:"forbidden"});let n=null;try{n=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n=null}const s=u.ask({browser:n?.browser,who:r.headers.origin||""});if(!s.ok){const l=s.reason==="busy"?"a pairing question is already on screen — answer it, or wait a minute":"too many pairing questions — wait a few minutes, or use a pairing code";return a(o,429,{error:l,type:s.reason})}return console.log(`[gateway] pairing: an unrecognised extension (${r.headers.origin}) asked — the question is on screen`),a(o,202,{ok:!0,id:s.id,number:s.number,expiresAt:s.expiresAt})}if(i==="/pair/ask/result"&&r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const{status:n}=u.result(e?.id,{who:r.headers.origin||""});if(n!=="allowed")return a(o,200,{ok:!0,status:n});console.log(`[gateway] paired ${r.headers.origin} — allowed in the dialog on this computer`);const{token:s,refused:l}=await uo(t);return a(o,200,{ok:!0,status:n,token:Je()||Pe(),...s?{bridgeToken:s}:{},...l?{bridgeRefused:l}:{}})}if(i==="/whoami"&&r.method==="POST"){const e=Ke(r);return a(o,200,{ok:!0,trust:e,paired:no(e),version:se})}if(i==="/audit"&&r.method==="GET")return R(r)?a(o,200,Dr(t,{version:se,startedAt:Yo,managed:Qe(),certificates:{...Ir(),wanted:ao(t)},linkPartners:g?g.status().devices.filter(e=>e.kind==="partner"):[],confined:ct({stateDir:ze.dirname(te())})})):a(o,403,{error:"audit: extension origin or gateway token required"});if((i==="/config"||i==="/logs"||i==="/update"&&r.method!=="GET")&&!R(r))return a(o,403,{error:"admin route: extension origin or gateway token required"});if(i==="/update"&&r.method==="GET"){const e=await En(se,{force:y.searchParams.get("force")==="1"}).catch(n=>({current:se,updateAvailable:!1,error:String(n?.message||n)}));return a(o,200,{ok:!0,update:e,job:An()})}if(i==="/update"&&r.method==="POST"){const e=$n(se);return a(o,e.already?409:202,{ok:!0,job:e})}if((i==="/v1/history/key"||i==="/v1/history/ingest-backup")&&r.method==="POST"&&!R(r))return a(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(i==="/v1/history/records"&&r.method==="PUT"&&!R(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/history/ingest"||i==="/v1/history/clear")&&r.method==="POST"&&!R(r))return a(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/contexts")&&!R(r))return a(o,403,{error:{message:"contexts — the gateway token or the ChatPanel extension is required",type:"forbidden"}});if((i==="/v1/memory/remember"||i==="/v1/memory/forget"||i==="/v1/memory/sync"||i==="/v1/memory/clear")&&r.method==="POST"&&!R(r))return a(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/prefs"||i.startsWith("/v1/prefs/")||i.startsWith("/v1/teams")||i.startsWith("/v1/agents")||i.startsWith("/v1/projects"))&&!R(r))return a(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/browser"||i.startsWith("/v1/browser/"))&&!R(r))return a(o,403,{error:{message:"browser: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/link"||i.startsWith("/v1/link/"))&&!R(r))return a(o,403,{error:{message:"link: extension origin or gateway token required",type:"forbidden"}});if((i==="/v1/events"||i.startsWith("/v1/events/"))&&!R(r))return a(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(i.startsWith("/v1/observability")&&!R(r))return a(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/")return o.writeHead(200,{"content-type":"text/plain; charset=utf-8","cache-control":"no-store"}),o.end(`ChatPanel Privacy Gateway v${se} is running.
|
|
21
21
|
|
|
22
22
|
This address is for ChatPanel's apps, not a web page — there is nothing to open here.
|
|
23
23
|
Use ChatPanel itself (the browser extension's Settings, or the desktop app).
|
|
24
24
|
In a terminal, \`chatpanel-gateway --status\` shows what is running.
|
|
25
|
-
`);if(r.method==="GET"&&i==="/health"){const e=N.health(),n=C.health();return a(o,200,{ok:!0,version:se,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Qe()?{managed:Qe()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:
|
|
25
|
+
`);if(r.method==="GET"&&i==="/health"){const e=N.health(),n=C.health();return a(o,200,{ok:!0,version:se,backend:t.backend,tier:t.redaction.tier,pairing:!0,pairPrompt:t.pairing?.prompt!==!1,...Qe()?{managed:Qe()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},install:Nn(),confined:ct({stateDir:ze.dirname(te())}),...Mn({release:Et.release()})?{appleHelper:!!xt()}:{},...qe?{bridge:qe.status()}:wt?{bridge:wt}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||je,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:n.state,ready:n.ok,model:n.model||t.tts?.model||Io,voice:t.tts?.voice||$e,runtime:n.runtime,dtype:n.dtype},events:W?{count:W.count(),hosts:W.hosts().length}:null,browser:p.health()})}if(i==="/status"&&r.method==="GET"){hr(t);const e=await ke(t.pro?.entitlementToken),n=await er(t);return a(o,200,{ok:!0,version:se,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...Qe()?{managed:Qe()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:n.configured,ready:n.ok,model:n.model,url:n.url},detector:Jt(t),pro:{unlocked:e},usage:ws(t),uptimeSeconds:Math.floor((Date.now()-Yo)/1e3),update:Pn(se)})}if(i==="/v1/history/ingest"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=J.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,size:n})}catch(e){return a(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/v1/prefs"&&r.method==="GET"){const e=String(y.searchParams.get("section")||"");return y.searchParams.get("stamps")?a(o,200,{ok:!0,revision:de.revision,stamps:de.stamps()}):a(o,200,{ok:!0,revision:de.revision,sections:de.get(e)})}if(i==="/v1/prefs"&&(r.method==="POST"||r.method==="PUT"))try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=de.put(e.sections||{},{by:e.by||""});return n.applied.length&&Vo(n.applied,e.by||""),a(o,200,{ok:!0,...n})}catch(e){return a(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(i==="/v1/prefs"&&r.method==="DELETE"){const e=String(y.searchParams.get("section")||""),n=e?de.remove(e):!1;return n&&Vo([e],""),a(o,200,{ok:!0,removed:n})}if(i==="/v1/prefs/events"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>o.write(`data: ${JSON.stringify(l)}
|
|
26
26
|
|
|
27
27
|
`);e({type:"hello",revision:de.revision,stamps:de.stamps()});const n=l=>e({type:"changed",...l});Ct.add(n);const s=setInterval(()=>{try{o.write(`: keep-alive
|
|
28
28
|
|
|
29
|
-
`)}catch{}},25e3);o.on("close",()=>{Ct.delete(n),clearInterval(s)});return}if(i==="/v1/projects"&&r.method==="GET")return a(o,200,{ok:!0,projects:ce.list({limit:y.searchParams.get("limit")||50,status:y.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&r.method==="GET")return a(o,200,{ok:!0,jobs:ce.openJobs()});if(i==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:ce.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(i);if(e){const n=e[1],s=e[2]||"",l=e[3]||"",d=e[4]||"",m=()=>a(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(d){const h=ce.get(n);if(!h)return m();const f=h.jobs.find(v=>v.id===l);if(!f)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const w={cfg:t,prefsStore:de,scorecards:He,engines:Ue,engineAt:c.engineAt};if(d==="/applications"&&r.method==="GET"){const v=await
|
|
29
|
+
`)}catch{}},25e3);o.on("close",()=>{Ct.delete(n),clearInterval(s)});return}if(i==="/v1/projects"&&r.method==="GET")return a(o,200,{ok:!0,projects:ce.list({limit:y.searchParams.get("limit")||50,status:y.searchParams.get("status")||""})});if(i==="/v1/projects/jobs"&&r.method==="GET")return a(o,200,{ok:!0,jobs:ce.openJobs()});if(i==="/v1/projects"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{};return a(o,200,{ok:!0,project:ce.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return a(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(i);if(e){const n=e[1],s=e[2]||"",l=e[3]||"",d=e[4]||"",m=()=>a(o,404,{error:{message:`no project ${n}`,type:"not_found"}});if(d){const h=ce.get(n);if(!h)return m();const f=h.jobs.find(v=>v.id===l);if(!f)return a(o,404,{error:{message:`no job ${l}`,type:"not_found"}});const w={cfg:t,prefsStore:de,scorecards:He,engines:Ue,engineAt:c.engineAt};if(d==="/applications"&&r.method==="GET"){const v=await Tn(f,{...w,reach:y.searchParams.get("reach")||"any",chatModel:y.searchParams.get("chatModel")||null});return a(o,200,{ok:!0,job:f,...v})}if(d==="/recruit"&&r.method==="POST"){if(!["open","evaluating"].includes(f.status))return a(o,400,{error:{message:`job ${l} is ${f.status}; only an open job is recruited`,type:"project_error"}});try{const v=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},_=String(v.by||"evaluator").slice(0,80),T=await xn(f,{...w,record:h,reach:v.reach||"any",chatModel:v.chatModel||null,evaluation:v.evaluation||null,text:v.text??null,by:_});let D=null;for(const Q of T.events)Q.type==="job.updated"?D=ce.updateJob(n,l,Q.job,{by:Q.by||_}):D=ce.append(n,[Q]);return a(o,200,{ok:!0,project:D,decision:T.decision,applications:T.applications,evaluation:T.evaluation})}catch(v){return a(o,400,{error:{message:`recruit: ${v.message}`,type:"project_error"}})}}return a(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!s&&r.method==="GET"){const h=ce.get(n,{events:y.searchParams.get("events")==="1"});return h?a(o,200,{ok:!0,project:h}):m()}if(!s&&r.method==="DELETE")return a(o,200,{ok:!0,removed:ce.remove(n)});if(r.method==="POST"&&(s==="/events"||s.startsWith("/jobs")))try{const h=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},f=String(h.by||"person").slice(0,80),w=s==="/events"?ce.append(n,h.events||[]):l?ce.updateJob(n,l,h.patch||h,{by:f}):ce.postJob(n,h.job||h,{by:f});return a(o,200,{ok:!0,project:w})}catch(h){return a(o,h.message.startsWith("no ")?404:400,{error:{message:`project: ${h.message}`,type:"project_error"}})}if(s==="/events"&&r.method==="GET"){if(!ce.get(n))return m();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const h=_=>o.write(`data: ${JSON.stringify(_)}
|
|
30
30
|
|
|
31
31
|
`);let f=y.searchParams.has("after")?Number(y.searchParams.get("after")):-1;h({seq:-1,type:"hello",at:Date.now(),payload:{project:ce.get(n),after:f}});const w=ce.watch(n,_=>{_.seq>f&&(f=_.seq,h(_))});for(const _ of ce.eventsSince(n,f))f=_.seq,h(_);const v=setInterval(()=>{try{o.write(`: keep
|
|
32
32
|
|
|
33
|
-
`)}catch{}},25e3);r.on("close",()=>{clearInterval(v),w()});return}}}if(i==="/v1/agents/scorecards"&&r.method==="GET")return a(o,200,{ok:!0,agents:He.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return a(o,200,{ok:!0,...await He.get(n)});if(r.method==="POST")try{const s=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},l=await He.append({agentId:n,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Ue.fromRating(He.chains.get(n)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&r.method==="GET")return a(o,200,
|
|
33
|
+
`)}catch{}},25e3);r.on("close",()=>{clearInterval(v),w()});return}}}if(i==="/v1/agents/scorecards"&&r.method==="GET")return a(o,200,{ok:!0,agents:He.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(i);if(e){const n=decodeURIComponent(e[1]);if(r.method==="GET")return a(o,200,{ok:!0,...await He.get(n)});if(r.method==="POST")try{const s=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},l=await He.append({agentId:n,kind:"rating",runId:s.runId,taskId:s.taskId,jobId:s.jobId,rating:{by:String(s.by||"person").slice(0,40),score:s.score,note:s.note,about:s.about},refs:s.refs});return Ue.fromRating(He.chains.get(n)||[],{...l,jobKind:s.jobKind?String(s.jobKind).slice(0,60):void 0}),a(o,200,{ok:!0,entry:l})}catch(s){return a(o,400,{error:{message:`scorecard: ${s.message}`,type:"scorecard_error"}})}}}if(i==="/v1/capabilities"&&r.method==="GET")return a(o,200,Zn(t,{version:se,reader:A,searcher:Se,extract:S(),proxy:Y}));if(i==="/v1/fusions"&&r.method==="GET"){const e={active:j.health().model||t.ner?.model||null,companions:j.companions()};let n=null;try{n=await P().status()}catch{n=null}return a(o,200,Vn({cfg:t,ner:e,runtimeDoc:n}))}if(i==="/v1/runtime"&&r.method==="GET"){const e=Object.fromEntries(la.map(n=>{const s=$t(t,n);return[n,{provider:s.kind,model:s.kind==="embedded"?s.model:null,models:ia[n],threads:G.threads,...s.kind==="embedded"?G.health(n,s.model):{}}]}));return a(o,200,{...await P().status(),inProcess:e})}if(i==="/v1/runtime/recipe"&&r.method==="GET"){if(!R(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});const e=new URL(r.url,"http://x").searchParams,n=await P().recipe(String(e.get("service")||"llama"),e.get("model"));return a(o,n.ok?200:400,n)}if(i==="/v1/runtime/plan"&&r.method==="GET"){const e=new URL(r.url,"http://x").searchParams,n=await P().plan(String(e.get("service")||"mlx"),{model:e.get("model")||void 0,ctx:e.get("ctx"),needMB:e.get("need_mb")});return a(o,n.ok?200:400,n)}{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(i);if(e&&r.method==="POST"){if(!R(r))return a(o,403,{error:"runtime: extension origin or gateway token required"});let n={};try{n=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{n={}}const s=String(n.action||"start"),l=P(),d=e[1]==="engines"?s==="start"?await l.startEngine(e[2]):{ok:!1,error:`unknown action ${s}`}:s==="start"?await l.startService(e[2],{force:n.force===!0}):s==="stop"?await l.stopService(e[2]):s==="model"?await l.setModel(e[2],n.model,{tunings:n.tunings||null}):s==="tune"?await l.setTunings(e[2],n.tunings):s==="profile"?await l.setProfile(e[2],n.profile):s==="pull"?await l.pullModel(e[2]):s==="install"?await l.installRunner(e[2]):s==="update"?await l.updateRunner(e[2]):s==="build"?await l.setBuild(e[2],String(n.build||"")):s==="cancel"?l.cancelJob(e[2]):s==="remove"?await l.removeService(e[2]):{ok:!1,error:`unknown action ${s}`};return a(o,d.ok?200:400,d)}}if(i==="/v1/embeddings"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"embed: body must be JSON",type:"invalid_request"}})}const n=await Y.call("embed",e);return a(o,n.status,n.body)}if((i==="/v1/rerank"||i==="/v1/decide")&&r.method==="POST"){const e=i.slice(4);let n;try{n=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const s=await Y.call(e,n);return a(o,s.status,s.body)}if(i==="/v1/detect"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const n=await qn(e,{ensure:()=>dt(t),model:j.health().model});return a(o,n.status,n.body)}catch(n){return a(o,500,{error:{message:`detect: ${n.message}`,type:"detector_error"}})}}if(i==="/v1/extract/context"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,Math.max(t.maxBodyBytes,Math.ceil(ut*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract/context: body must be JSON",type:"invalid_request"}})}const n=await ca(e,{service:S()});return a(o,n.status,n.body)}if((i==="/v1/files/write"||i==="/v1/files/exists")&&r.method==="POST"){if(!R(r)||Be(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(r,Math.max(t.maxBodyBytes,Ra*6+4096))).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Ea(i.slice(10),e);return a(o,n.status,n.body)}if(i==="/v1/files/fs"&&r.method==="POST"){if(!R(r)||Be(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(r,64*1024)).toString("utf8"))}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Pa(e);return a(o,n.status,n.body)}if(i==="/v1/files/pick-folder"&&r.method==="POST"){if(!R(r)||Be(r.headers))return a(o,403,{error:{message:"files: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e={};try{e=JSON.parse((await k(r,4*1024)).toString("utf8")||"{}")}catch{return a(o,400,{error:{message:"files: body must be JSON",type:"invalid_request"}})}const n=await Aa(e);return a(o,n.status,n.body)}if(i==="/v1/import/apple-notes"&&r.method==="POST"){if(!R(r)||Be(r.headers))return a(o,403,{error:{message:"apple-notes: a client on this computer with the gateway token or the pinned extension only",type:"forbidden"}});let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"apple-notes: body must be JSON",type:"invalid_request"}})}const n=await $a(e);return a(o,n.status,n.body)}if(i==="/v1/extract"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,Math.max(t.maxBodyBytes,Math.ceil(ut*4/3)+1024))).toString("utf8"))}catch{return a(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const n=await da(e,{service:S()});return a(o,n.status,n.body)}if(i==="/v1/read"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const n=await M().read(e);return a(o,n.status,n.body)}if(i==="/v1/search"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}Oe();const n=await De().search(e);return a(o,n.status,n.body)}if(/^\/v1\/search\/./.test(i)&&r.method==="GET"){let e;try{e=decodeURIComponent(i.slice(11))}catch{e=i.slice(11)}const n=y.searchParams.has("read")?Math.max(0,Math.min(10,Number(y.searchParams.get("read"))||0)):za.aliasRead;Oe();const s=await De().search({q:e,read:n,limit:Math.max(n,5)});return a(o,s.status,s.status===200?ja(s.body):s.body)}if(/^\/v1\/read\/./.test(i)&&r.method==="GET"){const e=String(r.url||"").slice(9),n=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),s=/application\/json/i.test(r.headers.accept||""),l=/^text$/i.test(r.headers["x-return-format"]||"")?"text":"markdown",d=await M().read({url:n,format:l});return d.status!==200||s?a(o,d.status,d.status===200?{code:200,status:2e4,data:d.body}:d.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":d.body.provider}),o.end(Ua(d.body)))}if(i==="/v1/engines"&&r.method==="GET"){const e=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,engines:Ue.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(i);if(e){const n=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&r.method==="GET"){const s=Number(y.searchParams.get("minCalls"))||void 0;return a(o,200,{ok:!0,...await Ue.get(n,{entries:y.searchParams.get("entries")==="1",minCalls:s})})}if(e[2]==="entries"&&r.method==="POST")try{const s=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},l=s.engine||zs(n);if(!l)return a(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const d=await Ue.append({...s,engine:l,kind:s.kind||"call"});return d.key!==n?a(o,400,{error:{message:`model-ledger: entry is for ${d.key}, not ${n}`,type:"model_ledger_error"}}):a(o,200,{ok:!0,entry:d})}catch(s){return a(o,400,{error:{message:`model-ledger: ${s.message}`,type:"model_ledger_error"}})}}}if(i==="/v1/teams/stream"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=l=>{try{o.write(`data: ${JSON.stringify(l)}
|
|
34
34
|
|
|
35
35
|
`)}catch{}};e({type:"hello",at:Date.now()});const n=oe.watchAll(l=>e({type:"run",id:l.id,removed:!!l.removed})),s=setInterval(()=>{try{o.write(`: keep-alive
|
|
36
36
|
|
|
@@ -38,30 +38,30 @@ In a terminal, \`chatpanel-gateway --status\` shows what is running.
|
|
|
38
38
|
|
|
39
39
|
`),d=y.searchParams.has("after")?Number(y.searchParams.get("after")):NaN;let m=Number.isFinite(d)?d:-1;l({seq:-1,type:"hello",at:Date.now(),payload:{run:oe.get(n),after:m}});const h=oe.watch(n,w=>{w.seq==null?l(w):w.seq>m&&(m=w.seq,l(w))});for(const w of oe.eventsSince(n,m))m=w.seq,l(w);const f=setInterval(()=>{try{o.write(`: keep-alive
|
|
40
40
|
|
|
41
|
-
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=R.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});if(go||=rn({store:e,notify:Ge}),await nn(r,o,{pathname:i,api:go,readJson:async s=>{const l=(await k(s,262144)).toString("utf8");return l?JSON.parse(l):{}},sendJson:a}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:ye.size,memories:ye.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:ye.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=ye.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:ye.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:ye.clear(),size:ye.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=R.clear();return a(o,200,{ok:!0,dropped:e,size:R.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=R.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:R.size,newest:R.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=$s(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await As(s,f=>R.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:R.size,newest:R.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!L(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(w,{maxTokens:v=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const D=Je()||Pe(),K=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...D?{Authorization:`Bearer ${D}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:v,temperature:.2})}),fe=await K.json().catch(()=>({}));return K.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=de.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await fn(n,{store:R,memories:ye.list(),complete:d,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,gn(n,f,{size:R.size,newest:R.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(ut*4/3)+1024:t.maxBodyBytes;try{const l=(await k(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await be().handle({method:r.method,pathname:i,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Da]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await k(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=Ss({cfg:t,apply:Nt,persist:()=>he(t,te()),isSelf:l=>gs(l,t)}).handle({method:r.method,pathname:i,body:e,admin:L(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await k(r,Math.max(t.maxBodyBytes,Math.ceil(ut*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await X().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:L(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Be(r.headers)});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:R.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:R.size,newest:R.newest,bytes:R.bytes,lossless:R.lossless?{records:R.lossless.size,newest:R.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:R.size,bytes:R.bytes,newest:R.newest}},access:It.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=It.push(Go({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await k(r,Math.max(t.maxBodyBytes||0,Us))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,h={},f=[],w=[];const v={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&v.removes.push(T.id);return}try{const D=To(T);D&&v.upserts.push(D)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),h=T.revs,f=T.conflicts,w=T.merged;for(const D of T.written)_(e.get(D))}if(Array.isArray(n.entries)){const T=St(),D=T?Wn((re,xe)=>Vn(T,{salt:re,iterations:xe})):null,K=async re=>{if(!D||!re.blob)return null;const xe=await D(re.blob),U=re.blob.compression&&re.blob.compression!=="none"?Kn(Qn,re.blob.compression):null;return Fn(re.blob,xe,{codec:U})},fe=await e.upsertEntries(n.entries,{open:K});d.push(...fe.written),m+=fe.sealed;for(const re of fe.written)_(e.get(re))}return(v.upserts.length||v.removes.length)&&R.bulk(v),d.length&&Ge({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:f,merged:w,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!Q)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=Q.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=Q.deleteOf(l);for(const m of Ae)try{m.write(`event: deleted
|
|
41
|
+
`)}catch{}},25e3);o.on("close",()=>{h(),clearInterval(f)});return}}}if(i.startsWith("/v1/contexts")){const e=J.lossless;if(!e)return a(o,501,{error:{message:"contexts need the SQLite warm store",type:"unavailable"}});go||=nn({store:e,notify:Ge,audit:Uo});const n=async l=>{const d=(await k(l,262144)).toString("utf8");return d?JSON.parse(d):{}},s=R(r)?{kind:"owner"}:null;if(await an(r,o,{pathname:i,api:go,readJson:n,sendJson:a,principal:s}))return}if(i==="/v1/memory/list"&&r.method==="GET")return a(o,200,{ok:!0,size:ye.size,memories:ye.list()});if(i==="/v1/memory/recall"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return a(o,200,{ok:!0,size:ye.size,...n})}catch(e){return a(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/remember"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return a(o,200,{ok:!0,action:n.action,record:n.record,replaced:n.replaces||null,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/forget"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},{removed:n}=ye.forget(String(e.query||""));return a(o,200,{ok:!0,removed:n,size:ye.size})}catch(e){return a(o,400,{error:{message:e.message,type:"memory_error"}})}if(i==="/v1/memory/sync"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=ye.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return a(o,200,{ok:!0,...n,memories:ye.list()})}catch(e){return a(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(i==="/v1/memory/clear"&&r.method==="POST")return a(o,200,{ok:!0,dropped:ye.clear(),size:ye.size});if(i==="/v1/history/clear"&&r.method==="POST"){const e=J.clear();return a(o,200,{ok:!0,dropped:e,size:J.size})}if(i==="/v1/history/search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=J.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return a(o,200,{ok:!0,size:J.size,newest:J.newest,results:n})}catch(e){return a(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/history/smart-search"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=String(e.question||e.query||""),s=Ns(n,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),l={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},d=Math.min(30,Math.max(5,Number(e.limit)||10)*2),m=await Bs(s,f=>J.search(f,{limit:d,...l}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),h=l.type?m:[...m.filter(f=>f.type==="brief"),...m.filter(f=>f.type!=="brief")];return a(o,200,{ok:!0,size:J.size,newest:J.newest,queries:s,results:h})}catch(e){return a(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(i==="/v1/research"&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"research: the body must be JSON",type:"invalid_request_error"}})}const n=String(e.question||"").trim();if(!n)return a(o,400,{error:{message:"research: `question` is required",type:"invalid_request_error"}});const s=typeof e.model=="string"?e.model.trim():"";if(s&&!R(r))return a(o,403,{error:{message:"research with a model: extension origin or gateway token required",type:"forbidden"}});const l=`http://127.0.0.1:${r.socket.localPort}`,d=s?async(w,{maxTokens:v=220}={})=>{const _=new AbortController,T=setTimeout(()=>_.abort(),3e4);try{const D=Je()||Pe(),Q=await fetch(`${l}/v1/chat/completions`,{method:"POST",signal:_.signal,headers:{"content-type":"application/json",...D?{Authorization:`Bearer ${D}`}:{},"X-ChatPanel-Client":"research"},body:JSON.stringify({model:s,messages:[{role:"user",content:w}],stream:!1,max_tokens:v,temperature:.2})}),fe=await Q.json().catch(()=>({}));return Q.ok?String(fe?.choices?.[0]?.message?.content||""):""}finally{clearTimeout(T)}}:null,m=de.get("identity")?.identity?.value||{},h=e.previous&&typeof e.previous=="object"&&e.previous.plan&&typeof e.previous.plan=="object"?{plan:e.previous.plan,top:typeof e.previous.top=="string"?e.previous.top:null,answer:String(e.previous.answer||"").slice(0,4e3)}:null,f=await gn(n,{store:J,memories:ye.list(),complete:d,previous:h,self:String(m.selfName||"").trim(),excludeId:typeof e.excludeId=="string"?e.excludeId:null,parallel:3});return a(o,200,wn(n,f,{size:J.size,newest:J.newest}))}if(i==="/v1/context"||i.startsWith("/v1/context/")){let e=null;if(r.method==="POST"){const s=/\/upload$/.test(i)?Math.ceil(ut*4/3)+1024:t.maxBodyBytes;try{const l=(await k(r,Math.max(t.maxBodyBytes,s))).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"context: body must be JSON",type:"invalid_request"}})}}const n=await be().handle({method:r.method,pathname:i,body:e,admin:R(r),agent:String(r.headers["x-chatpanel-agent"]||""),federated:!!r.headers[Ia]});return a(o,n.status,n.body)}if(i==="/v1/destinations"||i.startsWith("/v1/destinations/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const l=(await k(r,t.maxBodyBytes)).toString("utf8");e=l?JSON.parse(l):{}}catch{return a(o,400,{error:{message:"destinations: body must be JSON",type:"invalid_request"}})}const s=xs({cfg:t,apply:Nt,persist:()=>he(t,te()),isSelf:l=>bs(l,t)}).handle({method:r.method,pathname:i,body:e,admin:R(r)});return a(o,s.status,s.body)}if(i==="/v1/kb"||i.startsWith("/v1/kb/")){let e=null;if(r.method==="POST"||r.method==="PUT")try{const s=(await k(r,Math.max(t.maxBodyBytes,Math.ceil(ut*4/3)+1024))).toString("utf8");e=s?JSON.parse(s):{}}catch{return a(o,400,{error:{message:"kb: body must be JSON",type:"invalid_request"}})}const n=await X().handle({method:r.method,pathname:i,query:y.searchParams,body:e,admin:R(r),agent:String(r.headers["x-chatpanel-agent"]||""),local:!Be(r.headers)});return n.text!=null?(o.writeHead(n.status,{"content-type":n.contentType||"text/plain; charset=utf-8",...n.headers||{}}),o.end(n.text)):a(o,n.status,n.body)}if(i==="/v1/history/related"&&r.method==="GET"){const e=String(y.searchParams.get("id")||""),n=Math.min(30,Math.max(1,Number(y.searchParams.get("limit"))||5));return a(o,200,{ok:!0,results:J.related(e,{limit:n})})}if(i==="/v1/history/status"&&r.method==="GET")return a(o,200,{ok:!0,size:J.size,newest:J.newest,bytes:J.bytes,lossless:J.lossless?{records:J.lossless.size,newest:J.lossless.newest}:null});if(i==="/v1/observability"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||200));return a(o,200,{ok:!0,storage:{warm:{records:J.size,bytes:J.bytes,newest:J.newest}},access:It.snapshot(e)})}if(i==="/v1/observability/access"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=It.push(Go({ts:Date.now(),...e}));return a(o,200,{ok:!0,event:n})}catch(e){return a(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(i==="/v1/history/records"&&r.method==="PUT"){const e=J.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const n=JSON.parse((await k(r,Math.max(t.maxBodyBytes||0,Fs))).toString("utf8"))||{},s=String(n.host||"").slice(0,80),l=Number(n.at)||Date.now(),d=[];let m=0,h={},f=[],w=[];const v={upserts:[],removes:[]},_=T=>{if(!T||T.deletedAt){T?.id&&v.removes.push(T.id);return}try{const D=To(T);D&&v.upserts.push(D)}catch{}};if(Array.isArray(n.records)){const T=e.write(n.records,{host:s,at:l,merge:n.merge===!0});d.push(...T.written),h=T.revs,f=T.conflicts,w=T.merged;for(const D of T.written)_(e.get(D))}if(Array.isArray(n.entries)){const T=St(),D=T?Qn((re,xe)=>Wn(T,{salt:re,iterations:xe})):null,Q=async re=>{if(!D||!re.blob)return null;const xe=await D(re.blob),U=re.blob.compression&&re.blob.compression!=="none"?Yn(Xn,re.blob.compression):null;return Kn(re.blob,xe,{codec:U})},fe=await e.upsertEntries(n.entries,{open:Q});d.push(...fe.written),m+=fe.sealed;for(const re of fe.written)_(e.get(re))}return(v.upserts.length||v.removes.length)&&J.bulk(v),d.length&&Ge({ids:d}),a(o,200,{ok:!0,written:d.length,ids:d,revs:h,conflicts:f,merged:w,sealed:m,size:e.size,rev:e.rev})}catch(n){return a(o,400,{error:{message:`records failed: ${n.message}`,type:"ingest_error"}})}}if(i==="/v1/events"&&r.method==="DELETE"){if(!W)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=m=>/^(1|true|yes)$/i.test(y.searchParams.get(m)||""),n=y.searchParams.get("host"),s=e("all");if((n===null||n==="")==!s)return a(o,400,{error:{message:"events: name one host (?host=<id>) or the whole log (?all=1) — exactly one",type:"invalid_request_error"}});if(n!==null&&n.length>200)return a(o,400,{error:{message:"events: host is at most 200 characters",type:"invalid_request_error"}});const l=s?null:n;if(!e("force")){const m=W.countOf(l);return a(o,409,{ok:!1,wouldDelete:m,...s?{all:!0}:{host:n},error:{message:`events: add force=1 to delete ${m} event(s) ${s?"in the whole log":`for host "${n}"`} — nothing was deleted`,type:"confirm_required",code:"confirm_required"}})}const d=W.deleteOf(l);for(const m of Ae)try{m.write(`event: deleted
|
|
42
42
|
data: ${JSON.stringify({...s?{all:!0}:{host:n},deleted:d})}
|
|
43
43
|
|
|
44
|
-
`)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:n},cursor:
|
|
45
|
-
data: ${JSON.stringify({cursor:
|
|
44
|
+
`)}catch{}return a(o,200,{ok:!0,deleted:d,...s?{all:!0}:{host:n},cursor:W.cursor()})}if(i==="/v1/events"&&r.method==="POST"){if(!W)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{},n=Array.isArray(e)?e:e.events;if(!Array.isArray(n))return a(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(n.length>2e3)return a(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const s=m=>(typeof m?.host=="string"&&m.host?m.host:Un(m?.source))===ko,l=n.filter(s).map(m=>({id:m?.id??null,code:"RESERVED_HOST",message:`host "${ko}" is this gateway's own log`})),d=zn(W,l.length?n.filter(m=>!s(m)):n);return a(o,200,{ok:!0,appended:d.appended,duplicates:d.duplicates,rejected:[...l,...d.rejected],cursor:W.cursor()})}catch(e){return a(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(i==="/v1/events/cursor"&&r.method==="GET")return W?a(o,200,{ok:!0,cursor:W.cursor(),count:W.count()}):a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(i==="/v1/events/stats"&&r.method==="GET"){if(!W)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Gn(W.all());return a(o,200,{ok:!0,stats:e,year:Hn(e)})}if(i==="/v1/events"&&r.method==="GET"){if(!W)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=So(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{return a(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const n=W.since(e,{limit:Number(y.searchParams.get("limit"))||void 0,host:y.searchParams.get("host")||null});return a(o,200,{ok:!0,events:n.events.map(s=>_t(s)),cursor:n.cursor,more:n.more})}if(i==="/v1/events/stream"&&r.method==="GET"){if(!W)return a(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(y.searchParams.has("cursor"))try{e=So(JSON.parse(y.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
45
|
+
data: ${JSON.stringify({cursor:W.cursor(),count:W.count(),version:se})}
|
|
46
46
|
|
|
47
|
-
`),Ae.add(o),r.on("close",()=>Ae.delete(o)),e){let n={cursor:e,more:!0};for(;n.more;){n=
|
|
47
|
+
`),Ae.add(o),r.on("close",()=>Ae.delete(o)),e){let n={cursor:e,more:!0};for(;n.more;){n=W.since(n.cursor);for(const s of n.events)o.write(`event: cloudevent
|
|
48
48
|
data: ${JSON.stringify(_t(s))}
|
|
49
49
|
|
|
50
|
-
`)}}return}if(i==="/v1/link"&&r.method==="GET")return a(o,200,{...g?{enabled:!0,...g.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&r.method==="POST"){if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{he(t,te())}catch(n){console.warn(`[link] could not persist the settings: ${n.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&r.method==="POST"){if(!g)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const n={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=g.previewPartner(n)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await g.pairPartner(n)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await g.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(n){return a(o,502,{error:{message:n?.message||String(n),type:"relay"}})}}if(i==="/v1/link/route"&&r.method==="POST"){if(!g)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let n;try{n=
|
|
50
|
+
`)}}return}if(i==="/v1/link"&&r.method==="GET")return a(o,200,{...g?{enabled:!0,...g.status()}:{enabled:!1,devices:[],pairing:null},agentSessions:t.link?.agentSessions!==!1});if(i==="/v1/link/settings"&&r.method==="POST"){if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change what it may reach",type:"forbidden"}});let e={};try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(typeof e.agentSessions!="boolean")return a(o,400,{error:{message:"link settings: { agentSessions: true|false }",type:"invalid_request"}});t.link={...t.link||{},agentSessions:e.agentSessions};try{he(t,te())}catch(n){console.warn(`[link] could not persist the settings: ${n.message}`)}return a(o,200,{ok:!0,agentSessions:t.link.agentSessions})}if(i==="/v1/link/pair"&&r.method==="POST"){if(!g)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot pair another",type:"forbidden"}});let e={};try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}if(e?.kind==="partner"){const n={partner:e.partner?.name,scopes:e.scopes,route:e.route||null,relay:String(e.relay||""),folder:typeof e.folder=="string"?e.folder:""};let s;try{s=g.previewPartner(n)}catch(l){return a(o,400,{error:{message:l?.message||String(l),type:"invalid_request",code:l?.code||"bad_partner"}})}if(e.confirm!==!0)return a(o,200,{confirmed:!1,preview:s});try{return a(o,200,{confirmed:!0,...await g.pairPartner(n)})}catch(l){return a(o,l?.code==="bad_partner"?400:502,{error:{message:l?.message||String(l),type:l?.code==="bad_partner"?"invalid_request":"relay"}})}}if(e?.kind&&e.kind!=="phone")return a(o,400,{error:{message:"link pair: kind is phone or partner",type:"invalid_request"}});try{return a(o,200,await g.pair({name:String(e?.name||"").slice(0,60)||void 0}))}catch(n){return a(o,502,{error:{message:n?.message||String(n),type:"relay"}})}}if(i==="/v1/link/route"&&r.method==="POST"){if(!g)return a(o,409,{error:{message:"link is off (link.enabled: false)",type:"disabled"}});if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"a paired phone cannot change the route",type:"forbidden"}});let e={};try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{e={}}let n;try{n=fa({id:String(e.route||"link"),url:String(e.url||"")})}catch(l){return a(o,400,{error:{message:l.message,type:"bad_route"}})}const s={...t.link||{},route:n.id,fallback:e.fallback!==!1};n.id==="relay"?s.relayUrl=n.url:n.id==="link"&&delete s.relayUrl,(n.id==="tailscale"||n.id==="cloudflare")&&(s.tunnelUrl=n.url),t.link=s;try{he(t,te())}catch(l){console.warn(`[link] could not persist the route: ${l.message}`)}return a(o,200,{enabled:!0,...await g.applySettings(s)})}if(i.startsWith("/v1/link/devices/")&&r.method==="DELETE"){if(!g)return a(o,404,{error:{message:"link is off",type:"disabled"}});const e=decodeURIComponent(i.slice(17));return await g.remove(e)?(b.cancelDevice(e),a(o,200,{ok:!0})):a(o,404,{error:{message:"no such device",type:"not_found"}})}if(i==="/v1/link/files"||i.startsWith("/v1/link/files/")){const e=Be(r.headers);if(e?.kind!=="partner"||!e.scopes.includes("files"))return a(o,403,{error:{message:"link files: a partner’s own folder, for a partner granted files",type:"forbidden",code:"link_scope"}});const n=g?.partnerFolderOf(e.device);if(!n)return a(o,403,{error:{message:"link files: this partner has no folder on this computer — pair it again with agents and files",type:"forbidden",code:"link_scope"}});const s=i.slice(14).replace(/^\//,"");let l=s;try{l=decodeURIComponent(s)}catch{}const d=r.method==="GET"&&(!s||/^(data|\.claude\/skills|\.claude\/agents|\.agents\/skills)\/?$/.test(l));let m;try{m=Sa(s,{listing:d})}catch(h){return a(o,400,{error:{message:h.message,type:"invalid_request",code:"bad_path"}})}try{if(r.method==="GET"&&d)return a(o,200,{folder:"its own",files:Ta(n,m.replace(/\/$/,""))});if(r.method==="GET"){const h=xa(n,m);o.writeHead(200,{"content-type":"application/octet-stream","content-length":String(h.size)}),h.stream.pipe(o);return}return r.method==="PUT"?a(o,200,_a(n,m,await k(r,t.maxBodyBytes))):r.method==="DELETE"?Oa(n,m)?a(o,200,{ok:!0}):a(o,404,{error:{message:`${m}: no such file`,type:"not_found"}}):a(o,405,{error:{message:"link files: GET, PUT or DELETE",type:"invalid_request"}})}catch(h){const f=h?.status||(h?.code===413?413:h?.code==="bad_partner"?400:500);return a(o,f,{error:{message:h?.message||String(h),type:f===404?"not_found":f===413?"too_large":"invalid_request"}})}}if(i==="/v1/link/approvals"||i.startsWith("/v1/link/approvals/")){if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"an agent’s approval is the owner’s to give, on this computer",type:"forbidden"}});if(i==="/v1/link/approvals"&&r.method==="GET")return a(o,200,{pending:b.list()});if(i==="/v1/link/approvals/stream"&&r.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const n=d=>o.write(`event: approvals
|
|
51
51
|
data: ${JSON.stringify({pending:d})}
|
|
52
52
|
|
|
53
53
|
`);n(b.list());const s=b.subscribe(n),l=setInterval(()=>o.write(`:
|
|
54
54
|
|
|
55
|
-
`),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&r.method==="POST"){let n={};try{n=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{n={}}return xo.some(s=>s.id===n.decision)?b.answer(e[1],n.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${xo.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&r.method==="GET")return a(o,200,p.status());if(i==="/v1/browser/stream"&&r.method==="GET"){p.stream(r,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const n=i==="/v1/browser/call"?await p.call(e,r):i==="/v1/browser/announce"?p.announce(e):p.result(e);return a(o,n.status,n.body)}if(i==="/v1/history/stream"&&r.method==="GET"){const e=
|
|
55
|
+
`),25e3);l.unref?.(),o.on("close",()=>{s(),clearInterval(l)});return}const e=/^\/v1\/link\/approvals\/([A-Za-z0-9_-]{1,40})$/.exec(i);if(e&&r.method==="POST"){let n={};try{n=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{n={}}return xo.some(s=>s.id===n.decision)?b.answer(e[1],n.decision)?a(o,200,{ok:!0}):a(o,404,{error:{message:"nothing is waiting under that id — answered, withdrawn or expired",type:"not_found"}}):a(o,400,{error:{message:`link approvals: { decision: ${xo.map(s=>s.id).join(" | ")} }`,type:"invalid_request"}})}}if(i==="/v1/browser"&&r.method==="GET")return a(o,200,p.status());if(i==="/v1/browser/stream"&&r.method==="GET"){p.stream(r,o);return}if((i==="/v1/browser/call"||i==="/v1/browser/announce"||i==="/v1/browser/result")&&r.method==="POST"){let e;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{return a(o,400,{error:{message:"browser: body must be JSON",type:"invalid_request"}})}const n=i==="/v1/browser/call"?await p.call(e,r):i==="/v1/browser/announce"?p.announce(e):p.result(e);return a(o,n.status,n.body)}if(i==="/v1/history/stream"&&r.method==="GET"){const e=J.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
56
56
|
data: ${JSON.stringify({newest:e.newest,rev:e.rev,size:e.size,version:se,prefsRevision:de.revision})}
|
|
57
57
|
|
|
58
|
-
`),_e.add(o),r.on("close",()=>_e.delete(o));return}if(i==="/v1/history/records"&&r.method==="GET"){const e=R.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(y.searchParams.get("since"))||0,cursor:y.searchParams.get("cursor")||"",limit:Number(y.searchParams.get("limit"))||200,kind:y.searchParams.get("kind")||null,bytes:Number(y.searchParams.get("bytes"))||0,afterRev:y.searchParams.has("after_rev")?Number(y.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||50)),n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=y.searchParams.get("type")||null;return a(o,200,{ok:!0,...R.list({limit:e,offset:n,type:s})})}if(i==="/v1/history/get"&&r.method==="GET"){const e=y.searchParams.get("maxChars")!=null?Math.max(1,Number(y.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=R.get(String(y.searchParams.get("id")||""),{maxChars:e,offset:n});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&r.method==="GET")return a(o,200,{ok:!0,hasKey:fo()});if(i==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?tn(String(e.passphrase)):on();const n=e.passphrase?await Ot(R,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&Ge(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Ot(R,St());return e.ok&&e.whole&&Ge(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(r.method==="GET"){const e=await qo(t);return a(o,e.ok?200:503,e)}if(r.method==="POST"){if(await dt(t),j.state()!=="off"){if(!j.isReady()){const n=j.health();return a(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await k(r,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(n.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await j.detect(s,{strict:l});return a(o,200,{entities:d})}catch(n){return a(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=Zo(t);if(!e){const n=j.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:j.state(),model:t.ner?.model||null})}try{const n=await k(r,t.maxBodyBytes),s=await Le(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(n){return a(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Jt(t)});try{let n=e;const s=await ke(t.pro?.entitlementToken);await dt(t);const l=await We([at(()=>n,d=>{n=d})],t.redaction,{isPro:s});return a(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Yo(l.vault,"types")||[],detector:Jt(t)})}catch(n){return a(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(r.method==="GET"){const e=j.health().model||t.ner?.model||null,n=Math.round(Et.totalmem()/1048576),s=Xa(Po,{totalRamMB:n}).map(l=>({...l,installed:j.modelOnDisk(l.id)}));for(const l of[e,...j.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:j.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:j.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:n},skipped:qr(),recommendation:yo(s,{totalRamMB:n},[]),state:j.state(),progress:j.progress(),available:s})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Et.totalmem()/1048576),l=yo(Po.map(d=>({...d,installed:j.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const n=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!($o(d)||Ao(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=n||t.ner?.model||j.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),n&&jo(t,n);try{he(t,te())}catch{}return(async()=>{n&&await j.setModel(n,{onLog:m=>console.log(m)});const d=Zr(t.ner,{log:m=>console.log(m)});for(const m of j.companions())d.includes(m.model)||await j.removeCompanion(m.model);for(const m of d)await j.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});j.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:j.companions(),state:j.state()})}if(!n||!($o(n)||Ao(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});jo(t,n);try{he(t,te())}catch{}return j.setModel(n,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:n,state:j.state(),progress:j.progress()})}}if(i==="/stt/models"){if(r.method==="GET"){const e=N.health().model||t.stt?.model||je,n={platform:process.platform,arch:process.arch,helper:!!xt()},s=Za.map(l=>{const d=No(l,n);return{...l,installed:N.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:N.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:N.state(),progress:N.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:N.health().dtype,runtime:N.health().runtime,dtypes:ts,licenses:t.stt?.licenses||{}})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(qa(n)||es(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=No(mt(n),{platform:process.platform,arch:process.arch,helper:!!xt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=mt(n)?.license||null;if(l){const m=Bo(l),h=t.stt?.licenses?.[l.id]?.version===l.version;if(!h&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});h||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&os(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{he(t,te())}catch{}return N.setModel(n,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Gt(t,{installing:!0}),licenseAccepted:nr(t,n)}),a(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:N.state(),progress:N.progress(),speaker:{id:$.activeModel(),state:$.state(),installed:$.modelOnDisk()}})}}if(i==="/diarize/model"){if(r.method==="GET"){const e=$.activeModel(),n=Fa.map(s=>({...s,installed:$.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:$.state(),threshold:$.activeThreshold(),segment:Va.health(),translate:Me.health(),indictrans:Ha.health(),aec:Pt.health(),progress:$.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n){if(!Oo(n))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await $.setModel(n,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=n:t.stt={enabled:!0,diarize:!0,diarizeModel:n};try{he(t,te())}catch{}return $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}return $.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}}if(i==="/tts/models"){if(r.method==="GET"){const e=C.health().model||t.tts?.model||Jo(At()),n=At(),s=Mo.find(d=>d.id===e)||null,l=Mo.map(d=>({...d,installed:C.modelOnDisk(d.id),unavailable:d.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:C.state(),progress:C.progress(),available:l,voice:t.tts?.voice||(yt(e)==="pocket-tts"?pt:$e),arch:C.arch(),supportsVoices:C.arch()?C.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:C.arch()?C.supportsCustomVoices():!!s?.customVoices,sampleRate:C.sampleRate(),voices:C.isPocket()||!C.arch()&&yt(e)==="pocket-tts"?(C.builtinVoices().length?C.builtinVoices():ds).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:C.builtinVoices().includes(d)})):C.arch()&&C.arch()!=="style-tts2"?[]:rs.map(d=>({...d,installed:C.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:ss})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(ns(n)||as(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=le.parseCustomVoice(s);if(!(d?!!le.getVoice(d):ht(s)||Do(s)&&Co(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&is(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Io,voice:$e,allowDownload:!0}),n&&(t.tts.model=n),s&&(t.tts.voice=s),n&&!s){const d=ls(n),m=le.parseCustomVoice(t.tts.voice||""),h=!!(m&&le.getVoice(m));if(d&&!h)if(yt(n)==="pocket-tts")t.tts.voice=pt;else{const w=le.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!d&&h&&(t.tts.voice=$e);const f=yt(n)==="pocket-tts";f&&!le.parseCustomVoice(t.tts.voice||"")&&!ht(t.tts.voice)&&(t.tts.voice=pt),!f&&ht(t.tts.voice)&&(t.tts.voice=$e)}l&&(t.tts.dtype=l==="auto"?null:l);try{he(t,te())}catch{}return n&&C.setModel(n,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:C.state(),progress:C.progress()})}}if(i==="/tts/voices"){if(r.method==="GET")return a(o,200,{voices:le.listVoices(),usable:C.supportsCustomVoices(),embedder:$.activeModel(),embedderReady:$.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!le.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...le.renameVoice(l,n),usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{const d=Ka($.activeModel())?.dim===le.EMBED_DIM;if(d&&!$.isReady()){const _=$.download({onLog:K=>console.log(K)}),T=Symbol("timeout"),D=await Promise.race([_.then(()=>null).catch(K=>K),new Promise(K=>setTimeout(()=>K(T),tr))]);if(D===T||!$.isReady())return a(o,503,{error:{message:D===T?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${$.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:$.progress()})}const m=Float32Array.from(s),h=d?await $.embed(m):null;let f=null;try{const _=await C.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:T=>console.log(T)});_&&(f=await _.encodeVoice(Xs(m,16e3,24e3)))}catch(_){console.log(`[tts] pocket conditioning unavailable for this voice (${_.message})`)}const w=l?le.replaceVoice(l,{vec:h,pocket:f}):le.saveVoice({name:n,vec:h,pocket:f}),v=l&&n&&n!==w.name?le.renameVoice(l,n):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${v.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...v,usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=y.searchParams.get("id")||"",n=le.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const s=le.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:$e;try{he(t,te())}catch{}}return a(o,200,{deleted:n,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Ro)return a(o,413,{error:{message:`text too long (max ${Ro} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=cs(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||$e);if(l&&!ms(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:re,contentType:xe,redacted:U}=await us({dest:l,text:n,voice:m,speed:s,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken),format:h});return o.writeHead(200,{"Content-Type":xe,"Content-Length":String(re.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(U)}),o.end(re)}if(!await C.ready({onLog:re=>console.log(re),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Jo(At()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:C.health().error||"tts model not ready",type:"tts_unavailable"}});const w=ps({requested:d,configured:m,engine:C,voices:le,isPocketVoice:ht,isKnownVoice:Do,isValidVoiceId:Co,defaultVoice:$e,defaultPocketVoice:pt});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:v,customId:_,speakerEmbedding:T}=w,D=await C.synth(n,{voice:v,speed:s,speakerEmbedding:T}),K=C.sampleRate(),fe=h==="pcm"?Buffer.from(new Float32Array(D).buffer):C.toWav(D,K);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(fe.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(K),..._||C.isPocket()||C.supportsVoices()?{"X-Tts-Voice":v}:{}}),o.end(fe)}catch(f){return a(o,500,{error:{message:f.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=Qa(await k(r,Math.max(t.maxBodyBytes||0,64*1024*1024)),r.headers["content-type"])}catch(v){return a(o,v.code===413?413:415,{error:{message:v.message,type:"bad_request"}})}const n=v=>e.find(_=>_.name===v&&!_.filename)?.data.toString("utf8").trim()||"",s=e.find(v=>v.name==="file"&&v.filename)||e.find(v=>v.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await Ya(s.data)}catch(v){return a(o,v.code===415?415:500,{error:{message:v.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(n("response_format"))?n("response_format"):"json",m=$t(t,"stt");let h=null;if(m.kind==="remote"||m.kind==="container")try{h=Eo(m,{fetchImpl:Le})}catch(v){return a(o,500,{error:{message:`stt provider: ${v.message}`,type:"bad_provider"}})}if(!h&&!N.isReady()&&await N.init({model:t.stt?.model||je,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Gt(t),onLog:v=>console.log(v)}),!h&&!N.isReady())return a(o,503,{error:{message:`speech model not ready: ${N.health().error||N.state()}`,type:"stt_not_ready"}});const f=n("diarize")==="true"&&t.stt?.diarize!==!1;f&&!$.isReady()&&await $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:v=>console.log(v)});const w=Date.now();try{const{id:v}=N.createSession({lang:n("language")||void 0,diarize:f,interims:!1,remote:h}),_=[],T=[];let D=null;N.subscribe(v,U=>{U.type==="final"&&U.text?_.push(U):U.type==="language"?D=U.lang:U.type==="error"&&T.push(U.message||U.code)});const K=16e3*5;for(let U=0;U<l.pcm.length;U+=K)N.pushAudio(v,l.pcm.subarray(U,Math.min(l.pcm.length,U+K))),await N.decodeNow(v);if(await N.endSession(v),!_.length&&T.length)return a(o,500,{error:{message:T[0],type:"decode_failed"}});let fe=0;const re=_.map((U,dr)=>{const eo=typeof U.startMs=="number"?U.startMs/1e3:fe,cr=(U.durationMs||0)/1e3;return fe=eo+cr,{id:dr,start:Math.round(eo*100)/100,end:Math.round(fe*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(nt=>({start:Math.round(nt.startMs/10)/100,end:Math.round((nt.startMs+nt.durationMs)/10)/100,speaker:nt.speaker}))}:{}}}),xe=re.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(xe)):d==="verbose_json"?a(o,200,{task:"transcribe",language:D||n("language")||null,duration:Math.round(l.seconds*100)/100,text:xe,segments:re,provider:m.kind,took_ms:Date.now()-w}):a(o,200,{text:xe})}catch(v){return a(o,v.code==="too_many_sessions"?429:500,{error:{message:v.message,type:v.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(r.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(r.headers["content-length"])>or)return a(o,413,{error:{message:`at most ${zt} s of audio`,type:"too_large"}});let n;try{n=await k(r,or)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${zt} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=N.toFloat32(n);if(s.length<Ys)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!$.isReady()){const d=$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:f=>console.log(f)}),m=Symbol("timeout"),h=await Promise.race([d.then(()=>null,()=>null),new Promise(f=>{setTimeout(()=>f(m),tr).unref?.()})]);if(!$.isReady())return a(o,503,{error:{message:h===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${$.health().error||$.state()}`,type:"speaker_not_ready"},...$.progress()?{progress:$.progress()}:{}})}const l=await $.embed(s);return l?a(o,200,{vec:$.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:$.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=$t(t,"stt");let s=null;if(n.kind==="remote"||n.kind==="container")try{s=Eo(n,{fetchImpl:Le})}catch(_){return a(o,500,{error:{message:`stt provider: ${_.message}`,type:"bad_provider"}})}!s&&!N.isReady()&&N.init({model:t.stt?.model||je,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Gt(t),licenseAccepted:nr(t,t.stt?.model||je),onLog:_=>console.log(_)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!$.isReady()&&$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)}:null,h=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;h&&Pt.state()==="off"&&Pt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const f=Array.isArray(e?.langs)?e.langs.slice(0,12):null,w=t.stt?.model||je,v=f&&!s?Ua(f,{engine:mt(w)?.engine||"",englishOnly:/\.en$/.test(w)}).missing:[];try{const _=e?.poll===!0,T=e?.format==="pcm16"?"pcm16":"f32",D=l&&e?.vectors===!0,{id:K}=N.createSession({lang:e?.lang,langs:f,translateTo:d,translateLoad:m,echo:h,redact:e?.redact===!0,diarize:l,vectors:D,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:_,format:T});return a(o,201,{id:K,state:N.state(),format:T,..._?{poll:!0}:{},...D?{vectors:!0}:{},...v.length?{languagesMissing:v}:{},...d?{translate:Me.state()}:{}})}catch(_){return a(o,_.code==="too_many_sessions"?429:500,{error:{message:_.message,type:_.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1],s=async(d,m,h)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let f=m.text;return await We([at(()=>f,w=>{f=w})],t.redaction,{isPro:h}),{...m,text:f}}catch{return m}},l=async d=>{const m=N.drainEvents(n);if(!m)return null;const h=[];if(d&&!d.closed){const w=d.remote?"ready":N.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...N.progress()||{}}):w==="error"?h.push({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes($.state())?h.push({type:"diarize-progress",state:$.state(),...$.progress()||{}}):d.translateTo&&["downloading","loading"].includes(Me.state())?h.push({type:"translate-progress",state:Me.state(),...Me.progress()||{}}):rr.get(d)!==w&&(rr.set(d,w),h.push({type:"state",state:w}))}const f=d?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of m)d?h.push(await s(d,w,f)):w.type!=="final"&&w.type!=="interim"&&w.type!=="translation"&&h.push(w);return h};if(e[2]==="/audio"&&r.method==="POST"){const d=N.getSession(n)||N.endedSession(n);try{const m=await k(r,t.maxBodyBytes);N.pushAudio(n,N.toFloat32(m,d?.format));const h=await l(d);return a(o,200,{ok:!0,state:N.state(),...h?{events:h}:{}})}catch(m){const h=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...h?{events:h}:{}})}}if(e[2]==="/events"&&r.method==="GET"){const d=N.getSession(n);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=T=>o.write(`data: ${JSON.stringify(T)}
|
|
58
|
+
`),_e.add(o),r.on("close",()=>_e.delete(o));return}if(i==="/v1/history/records"&&r.method==="GET"){const e=J.lossless;if(!e)return a(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const n=e.since({since:Number(y.searchParams.get("since"))||0,cursor:y.searchParams.get("cursor")||"",limit:Number(y.searchParams.get("limit"))||200,kind:y.searchParams.get("kind")||null,bytes:Number(y.searchParams.get("bytes"))||0,afterRev:y.searchParams.has("after_rev")?Number(y.searchParams.get("after_rev"))||0:null});return a(o,200,{ok:!0,...n,size:e.size,newest:e.newest})}if(i==="/v1/history/list"&&r.method==="GET"){const e=Math.min(500,Math.max(1,Number(y.searchParams.get("limit"))||50)),n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=y.searchParams.get("type")||null;return a(o,200,{ok:!0,...J.list({limit:e,offset:n,type:s})})}if(i==="/v1/history/get"&&r.method==="GET"){const e=y.searchParams.get("maxChars")!=null?Math.max(1,Number(y.searchParams.get("maxChars"))||0):null,n=Math.max(0,Number(y.searchParams.get("offset"))||0),s=J.get(String(y.searchParams.get("id")||""),{maxChars:e,offset:n});return s?a(o,200,{ok:!0,record:s}):a(o,404,{error:{message:"no such record",type:"not_found"}})}if(i==="/v1/history/key"&&r.method==="GET")return a(o,200,{ok:!0,hasKey:fo()});if(i==="/v1/history/key"&&r.method==="POST")try{const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?on(String(e.passphrase)):rn();const n=e.passphrase?await Ot(J,String(e.passphrase)):{ok:!0,ingested:0};return n.ok&&n.whole&&Ge(),a(o,200,{ok:!0,hasKey:!!e.passphrase,...n})}catch(e){return a(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(i==="/v1/history/ingest-backup"&&r.method==="POST")try{const e=await Ot(J,St());return e.ok&&e.whole&&Ge(),a(o,e.ok?200:409,e)}catch(e){return a(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(i==="/ner"){if(r.method==="GET"){const e=await er(t);return a(o,e.ok?200:503,e)}if(r.method==="POST"){if(await dt(t),j.state()!=="off"){if(!j.isReady()){const n=j.health();return a(o,503,{error:{message:n.state==="error"?`NER model failed to load: ${n.error||"unknown error"}`:`NER model is ${n.state} — not ready yet`,type:n.state==="error"?"ner_error":"ner_loading"},state:n.state,model:n.model})}try{const n=await k(r,t.maxBodyBytes);let s="",l=!1;try{const m=JSON.parse(n.toString("utf8"));s=m?.text||"",l=m?.strict===!0}catch{}const d=await j.detect(s,{strict:l});return a(o,200,{entities:d})}catch(n){return a(o,500,{error:{message:`NER error: ${n.message}`,type:"ner_error"}})}}const e=qo(t);if(!e){const n=j.modelOnDisk(t.ner?.model||void 0);return a(o,503,{error:{message:n?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:n?"ner_error":"ner_not_installed"},state:j.state(),model:t.ner?.model||null})}try{const n=await k(r,t.maxBodyBytes),s=await Le(e,{method:"POST",headers:{"content-type":"application/json"},body:n,signal:AbortSignal.timeout(8e3)}),l=await s.text();return o.writeHead(s.status,{"content-type":"application/json"}),o.end(l)}catch(n){return a(o,502,{error:{message:`NER unreachable: ${n.message}`,type:"ner_unreachable"}})}}}if(i==="/redact"&&r.method==="POST"){let e="";try{e=String(JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return a(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Jt(t)});try{let n=e;const s=await ke(t.pro?.entitlementToken);await dt(t);const l=await We([at(()=>n,d=>{n=d})],t.redaction,{isPro:s});return a(o,200,{text:n,count:l.count||0,sanitized:l.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Xo(l.vault,"types")||[],detector:Jt(t)})}catch(n){return a(o,500,{error:{message:`redaction preview failed: ${n.message}`,type:"redact_error"}})}}if(i==="/ner/models"){if(r.method==="GET"){const e=j.health().model||t.ner?.model||null,n=Math.round(Et.totalmem()/1048576),s=qa(Po,{totalRamMB:n}).map(l=>({...l,installed:j.modelOnDisk(l.id)}));for(const l of[e,...j.modelsOnDisk()])!l||s.some(d=>d.id===l)||s.push({id:l,label:l,lang:"—",custom:!0,installed:j.modelOnDisk(l),note:"Custom model (from Hugging Face)."});return a(o,200,{active:e,companions:j.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:n},skipped:en(),recommendation:yo(s,{totalRamMB:n},[]),state:j.state(),progress:j.progress(),available:s})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const s=Math.round(Et.totalmem()/1048576),l=yo(Po.map(d=>({...d,installed:j.modelOnDisk(d.id)})),{totalRamMB:s},[]);e={id:l.primary,union:l.union}}const n=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const s=[...new Set(e.union.map(d=>String(d||"").trim()).filter(Boolean))];for(const d of s)if(!($o(d)||Ao(d)))return a(o,400,{error:{message:`unknown or invalid model id in union: ${d}`,type:"bad_model"}});const l=n||t.ner?.model||j.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=s.filter(d=>d!==l),n&&jo(t,n);try{he(t,te())}catch{}return(async()=>{n&&await j.setModel(n,{onLog:m=>console.log(m)});const d=qr(t.ner,{log:m=>console.log(m)});for(const m of j.companions())d.includes(m.model)||await j.removeCompanion(m.model);for(const m of d)await j.addCompanion(m,{onLog:h=>console.log(h),allowDownload:t.ner.allowDownload!==!1});j.setUnionOrder(d)})().catch(d=>console.log(`[ner] union update failed: ${d.message}`)),a(o,202,{accepted:!0,active:l,union:t.ner.union,companions:j.companions(),state:j.state()})}if(!n||!($o(n)||Ao(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});jo(t,n);try{he(t,te())}catch{}return j.setModel(n,{onLog:s=>console.log(s)}).then(s=>{s&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),a(o,202,{accepted:!0,active:n,state:j.state(),progress:j.progress()})}}if(i==="/stt/models"){if(r.method==="GET"){const e=N.health().model||t.stt?.model||je,n={platform:process.platform,arch:process.arch,helper:!!xt()},s=es.map(l=>{const d=No(l,n);return{...l,installed:N.modelOnDisk(l.id),...d?{unavailable:d}:{}}});return e&&!s.some(l=>l.id===e)&&s.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:N.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:N.state(),progress:N.progress(),available:s,dtype:t.stt?.dtype||"auto",loadedDtype:N.health().dtype,runtime:N.health().runtime,dtypes:rs,licenses:t.stt?.licenses||{}})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(!n||!(ts(n)||os(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=No(mt(n),{platform:process.platform,arch:process.arch,helper:!!xt()});if(s)return a(o,400,{error:{message:s,type:"bad_model"}});const l=mt(n)?.license||null;if(l){const m=Bo(l),h=t.stt?.licenses?.[l.id]?.version===l.version;if(!h&&e.acceptLicense!==m)return a(o,409,{error:{message:`Accept the ${l.name} to use this model`,type:"license_required"},license:{...l,accept:m}});h||(t.stt||={enabled:!0,allowDownload:!0},t.stt.licenses={...t.stt.licenses||{},[l.id]:{version:l.version,acceptedAt:new Date().toISOString()}})}const d=typeof e.dtype=="string"&&ns(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=n:t.stt={enabled:!0,model:n,allowDownload:!0},d&&(t.stt.dtype=d==="auto"?null:d);try{he(t,te())}catch{}return N.setModel(n,{onLog:m=>console.log(m),dtype:d||t.stt.dtype||"auto",warmMs:t.stt.warmMs,allowDownload:t.stt?.allowDownload!==!1,segment:t.stt?.segment,speaker:Gt(t,{installing:!0}),licenseAccepted:ar(t,n)}),a(o,202,{accepted:!0,active:n,dtype:t.stt.dtype||"auto",state:N.state(),progress:N.progress(),speaker:{id:$.activeModel(),state:$.state(),installed:$.modelOnDisk()}})}}if(i==="/diarize/model"){if(r.method==="GET"){const e=$.activeModel(),n=Ka.map(s=>({...s,installed:$.modelOnDisk(s.id)})).sort((s,l)=>(l.id===e?1:0)-(s.id===e?1:0));return a(o,200,{active:e,state:$.state(),threshold:$.activeThreshold(),segment:Wa.health(),translate:Me.health(),indictrans:Va.health(),aec:Pt.health(),progress:$.progress(),available:n})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n){if(!Oo(n))return a(o,400,{error:{message:"unknown speaker model id",type:"bad_model"}});if(!await $.setModel(n,{log:s=>console.log(s)}))return a(o,409,{error:{message:"a diarizing session is using the current speaker model — try again when it ends",type:"model_busy"}});t.stt?t.stt.diarizeModel=n:t.stt={enabled:!0,diarize:!0,diarizeModel:n};try{he(t,te())}catch{}return $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}return $.download({onLog:s=>console.log(s)}),a(o,202,{accepted:!0,active:$.activeModel(),state:$.state(),threshold:$.activeThreshold(),progress:$.progress()})}}if(i==="/tts/models"){if(r.method==="GET"){const e=C.health().model||t.tts?.model||Jo(At()),n=At(),s=Mo.find(d=>d.id===e)||null,l=Mo.map(d=>({...d,installed:C.modelOnDisk(d.id),unavailable:d.requiresNative&&!n?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!l.some(d=>d.id===e)&&l.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:C.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),a(o,200,{active:e,state:C.state(),progress:C.progress(),available:l,voice:t.tts?.voice||(yt(e)==="pocket-tts"?pt:$e),arch:C.arch(),supportsVoices:C.arch()?C.supportsVoices():s?s.arch==="style-tts2"&&!!s.voices:!0,supportsCustomVoices:C.arch()?C.supportsCustomVoices():!!s?.customVoices,sampleRate:C.sampleRate(),voices:C.isPocket()||!C.arch()&&yt(e)==="pocket-tts"?(C.builtinVoices().length?C.builtinVoices():us).map(d=>({id:d,label:d[0].toUpperCase()+d.slice(1),lang:"en",installed:C.builtinVoices().includes(d)})):C.arch()&&C.arch()!=="style-tts2"?[]:as.map(d=>({...d,installed:C.voiceOnDisk(d.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:C.health().dtype,runtime:C.health().runtime,dtypes:ls})}if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.id=="string"?e.id.trim():null;if(n&&!(ss(n)||is(n)))return a(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const s=e&&typeof e.voice=="string"?e.voice.trim():null;if(s){const d=le.parseCustomVoice(s);if(!(d?!!le.getVoice(d):ht(s)||Do(s)&&Co(s)))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const l=e&&typeof e.dtype=="string"&&ds(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Io,voice:$e,allowDownload:!0}),n&&(t.tts.model=n),s&&(t.tts.voice=s),n&&!s){const d=cs(n),m=le.parseCustomVoice(t.tts.voice||""),h=!!(m&&le.getVoice(m));if(d&&!h)if(yt(n)==="pocket-tts")t.tts.voice=pt;else{const w=le.listVoices();t.tts.voice=w.length?`custom:${w[0].id}`:""}else!d&&h&&(t.tts.voice=$e);const f=yt(n)==="pocket-tts";f&&!le.parseCustomVoice(t.tts.voice||"")&&!ht(t.tts.voice)&&(t.tts.voice=pt),!f&&ht(t.tts.voice)&&(t.tts.voice=$e)}l&&(t.tts.dtype=l==="auto"?null:l);try{he(t,te())}catch{}return n&&C.setModel(n,{onLog:d=>console.log(d),dtype:l||t.tts.dtype||"auto"}),a(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:C.state(),progress:C.progress()})}}if(i==="/tts/voices"){if(r.method==="GET")return a(o,200,{voices:le.listVoices(),usable:C.supportsCustomVoices(),embedder:$.activeModel(),embedderReady:$.isReady()});if(r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof e.name=="string"?e.name.trim():"",s=e&&Array.isArray(e.pcm)?e.pcm:null,l=e&&typeof e.id=="string"?e.id.trim():"";if(l){if(!le.getVoice(l))return a(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!s){if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return a(o,200,{...le.renameVoice(l,n),usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"rename_failed"}})}}if(s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!n)return a(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!s||s.length<16e3)return a(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{const d=Ya($.activeModel())?.dim===le.EMBED_DIM;if(d&&!$.isReady()){const _=$.download({onLog:Q=>console.log(Q)}),T=Symbol("timeout"),D=await Promise.race([_.then(()=>null).catch(Q=>Q),new Promise(Q=>setTimeout(()=>Q(T),or))]);if(D===T||!$.isReady())return a(o,503,{error:{message:D===T?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${$.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:$.progress()})}const m=Float32Array.from(s),h=d?await $.embed(m):null;let f=null;try{const _=await C.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:T=>console.log(T)});_&&(f=await _.encodeVoice(qs(m,16e3,24e3)))}catch(_){console.log(`[tts] pocket conditioning unavailable for this voice (${_.message})`)}const w=l?le.replaceVoice(l,{vec:h,pocket:f}):le.saveVoice({name:n,vec:h,pocket:f}),v=l&&n&&n!==w.name?le.renameVoice(l,n):w;return console.log(`[tts] ${l?"re-recorded":"saved"} custom voice "${v.name}" (${(w.kinds||[]).join(" + ")}, sample discarded)`),a(o,l?200:201,{...w,...v,usable:C.supportsCustomVoices()})}catch(d){return a(o,400,{error:{message:d.message,type:"save_failed"}})}}if(r.method==="DELETE"){const e=y.searchParams.get("id")||"",n=le.deleteVoice(e);if(n&&t.tts?.voice===`custom:${e}`){const s=le.listVoices();t.tts.voice=s.length?`custom:${s[0].id}`:$e;try{he(t,te())}catch{}}return a(o,200,{deleted:n,voice:t.tts?.voice})}}if((i==="/tts"||i==="/v1/audio/speech")&&r.method==="POST"){if(t.tts?.enabled===!1)return a(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const n=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!n)return a(o,400,{error:{message:"text is required",type:"bad_request"}});if(n.length>Ro)return a(o,413,{error:{message:`text too long (max ${Ro} chars)`,type:"too_long"}});const s=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,l=ms(t),d=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,m=d||(l?l.voice:t.tts?.voice||$e);if(l&&!hs(m))return a(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const h=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(h!=="wav"&&h!=="pcm")return a(o,400,{error:{message:`unsupported response_format "${h}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(l){const{audio:re,contentType:xe,redacted:U}=await ps({dest:l,text:n,voice:m,speed:s,auth:r.headers.authorization||r.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await ke(t.pro?.entitlementToken),format:h});return o.writeHead(200,{"Content-Type":xe,"Content-Length":String(re.length),"Cache-Control":"no-store","X-Tts-Provider":l.kind,"X-Tts-Redacted":String(U)}),o.end(re)}if(!await C.ready({onLog:re=>console.log(re),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||Jo(At()),dtype:t.tts?.dtype||"auto"}))return a(o,503,{error:{message:C.health().error||"tts model not ready",type:"tts_unavailable"}});const w=ys({requested:d,configured:m,engine:C,voices:le,isPocketVoice:ht,isKnownVoice:Do,isValidVoiceId:Co,defaultVoice:$e,defaultPocketVoice:pt});if(!w.ok)return a(o,w.status,{error:{message:w.message,type:w.type}});const{voice:v,customId:_,speakerEmbedding:T}=w,D=await C.synth(n,{voice:v,speed:s,speakerEmbedding:T}),Q=C.sampleRate(),fe=h==="pcm"?Buffer.from(new Float32Array(D).buffer):C.toWav(D,Q);return o.writeHead(200,{"Content-Type":h==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(fe.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(Q),..._||C.isPocket()||C.supportsVoices()?{"X-Tts-Voice":v}:{}}),o.end(fe)}catch(f){return a(o,500,{error:{message:f.message,type:"tts_failed"}})}}if(i==="/v1/audio/transcriptions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=Xa(await k(r,Math.max(t.maxBodyBytes||0,64*1024*1024)),r.headers["content-type"])}catch(v){return a(o,v.code===413?413:415,{error:{message:v.message,type:"bad_request"}})}const n=v=>e.find(_=>_.name===v&&!_.filename)?.data.toString("utf8").trim()||"",s=e.find(v=>v.name==="file"&&v.filename)||e.find(v=>v.filename);if(!s?.data?.length)return a(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let l;try{l=await Za(s.data)}catch(v){return a(o,v.code===415?415:500,{error:{message:v.message,type:"unsupported_media"}})}const d=["json","text","verbose_json"].includes(n("response_format"))?n("response_format"):"json",m=$t(t,"stt");let h=null;if(m.kind==="remote"||m.kind==="container")try{h=Eo(m,{fetchImpl:Le})}catch(v){return a(o,500,{error:{message:`stt provider: ${v.message}`,type:"bad_provider"}})}if(!h&&!N.isReady()&&await N.init({model:t.stt?.model||je,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Gt(t),onLog:v=>console.log(v)}),!h&&!N.isReady())return a(o,503,{error:{message:`speech model not ready: ${N.health().error||N.state()}`,type:"stt_not_ready"}});const f=n("diarize")==="true"&&t.stt?.diarize!==!1;f&&!$.isReady()&&await $.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:v=>console.log(v)});const w=Date.now();try{const{id:v}=N.createSession({lang:n("language")||void 0,diarize:f,interims:!1,remote:h}),_=[],T=[];let D=null;N.subscribe(v,U=>{U.type==="final"&&U.text?_.push(U):U.type==="language"?D=U.lang:U.type==="error"&&T.push(U.message||U.code)});const Q=16e3*5;for(let U=0;U<l.pcm.length;U+=Q)N.pushAudio(v,l.pcm.subarray(U,Math.min(l.pcm.length,U+Q))),await N.decodeNow(v);if(await N.endSession(v),!_.length&&T.length)return a(o,500,{error:{message:T[0],type:"decode_failed"}});let fe=0;const re=_.map((U,cr)=>{const eo=typeof U.startMs=="number"?U.startMs/1e3:fe,ur=(U.durationMs||0)/1e3;return fe=eo+ur,{id:cr,start:Math.round(eo*100)/100,end:Math.round(fe*100)/100,text:U.text,...U.speaker?{speaker:U.speaker}:{},...U.turns?{turns:U.turns.map(nt=>({start:Math.round(nt.startMs/10)/100,end:Math.round((nt.startMs+nt.durationMs)/10)/100,speaker:nt.speaker}))}:{}}}),xe=re.map(U=>U.text).join(" ").replace(/\s+/g," ").trim();return d==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(xe)):d==="verbose_json"?a(o,200,{task:"transcribe",language:D||n("language")||null,duration:Math.round(l.seconds*100)/100,text:xe,segments:re,provider:m.kind,took_ms:Date.now()-w}):a(o,200,{text:xe})}catch(v){return a(o,v.code==="too_many_sessions"?429:500,{error:{message:v.message,type:v.code||"stt_error"}})}}if(i==="/v1/voice/embed"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});if(t.stt?.diarize===!1)return a(o,403,{error:{message:"the speaker model is switched off in the gateway config (stt.diarize)",type:"speaker_disabled"}});const e=String(r.headers["content-type"]||"").split(";")[0].trim().toLowerCase();if(e&&e!=="audio/pcm"&&e!=="application/octet-stream")return a(o,415,{error:{message:"send raw 16 kHz mono Float32 little-endian samples as audio/pcm or application/octet-stream",type:"unsupported_media"}});if(Number(r.headers["content-length"])>rr)return a(o,413,{error:{message:`at most ${zt} s of audio`,type:"too_large"}});let n;try{n=await k(r,rr)}catch(d){return a(o,d.code===413?413:400,{error:{message:d.code===413?`at most ${zt} s of audio`:d.message,type:d.code===413?"too_large":"bad_request"}})}const s=N.toFloat32(n);if(s.length<Zs)return a(o,400,{error:{message:"too little audio to fingerprint (at least a quarter of a second)",type:"sample_too_short"}});if(!$.isReady()){const d=$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:f=>console.log(f)}),m=Symbol("timeout"),h=await Promise.race([d.then(()=>null,()=>null),new Promise(f=>{setTimeout(()=>f(m),or).unref?.()})]);if(!$.isReady())return a(o,503,{error:{message:h===m?"the speaker model is still downloading — try again shortly":`the speaker model is not available: ${$.health().error||$.state()}`,type:"speaker_not_ready"},...$.progress()?{progress:$.progress()}:{}})}const l=await $.embed(s);return l?a(o,200,{vec:$.plainVector(l),seconds:Math.round(s.length/16e3*100)/100,model:$.activeModel()}):a(o,500,{error:{message:"the speaker model gave no fingerprint for this audio",type:"embed_failed"}})}if(i.startsWith("/v1/stt/sessions")&&(i=i.slice(3)),i==="/stt/sessions"&&r.method==="POST"){if(t.stt?.enabled===!1)return a(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const n=$t(t,"stt");let s=null;if(n.kind==="remote"||n.kind==="container")try{s=Eo(n,{fetchImpl:Le})}catch(_){return a(o,500,{error:{message:`stt provider: ${_.message}`,type:"bad_provider"}})}!s&&!N.isReady()&&N.init({model:t.stt?.model||je,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,segment:t.stt?.segment,speaker:Gt(t),licenseAccepted:ar(t,t.stt?.model||je),onLog:_=>console.log(_)});const l=e?.diarize===!0&&t.stt?.diarize!==!1;l&&!$.isReady()&&$.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const d=typeof e?.translateTo=="string"&&t.stt?.translate!==!1?e.translateTo:null,m=d?{allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)}:null,h=e?.echo&&typeof e.echo=="object"&&typeof e.echo.group=="string"&&["mic","reference"].includes(e.echo.role)&&t.stt?.aec!==!1&&!s?{group:e.echo.group,role:e.echo.role}:null;h&&Pt.state()==="off"&&Pt.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:_=>console.log(_)});const f=Array.isArray(e?.langs)?e.langs.slice(0,12):null,w=t.stt?.model||je,v=f&&!s?Fa(f,{engine:mt(w)?.engine||"",englishOnly:/\.en$/.test(w)}).missing:[];try{const _=e?.poll===!0,T=e?.format==="pcm16"?"pcm16":"f32",D=l&&e?.vectors===!0,{id:Q}=N.createSession({lang:e?.lang,langs:f,translateTo:d,translateLoad:m,echo:h,redact:e?.redact===!0,diarize:l,vectors:D,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:s,poll:_,format:T});return a(o,201,{id:Q,state:N.state(),format:T,..._?{poll:!0}:{},...D?{vectors:!0}:{},...v.length?{languagesMissing:v}:{},...d?{translate:Me.state()}:{}})}catch(_){return a(o,_.code==="too_many_sessions"?429:500,{error:{message:_.message,type:_.code||"stt_error"}})}}{const e=i.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const n=e[1],s=async(d,m,h)=>{if(m.type!=="final"&&m.type!=="translation"||!d.redact||!m.text)return m;try{let f=m.text;return await We([at(()=>f,w=>{f=w})],t.redaction,{isPro:h}),{...m,text:f}}catch{return m}},l=async d=>{const m=N.drainEvents(n);if(!m)return null;const h=[];if(d&&!d.closed){const w=d.remote?"ready":N.state();w==="downloading"||w==="loading"?h.push({type:"progress",state:w,...N.progress()||{}}):w==="error"?h.push({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}):d.diarize&&["downloading","loading"].includes($.state())?h.push({type:"diarize-progress",state:$.state(),...$.progress()||{}}):d.translateTo&&["downloading","loading"].includes(Me.state())?h.push({type:"translate-progress",state:Me.state(),...Me.progress()||{}}):nr.get(d)!==w&&(nr.set(d,w),h.push({type:"state",state:w}))}const f=d?.redact?await ke(t.pro?.entitlementToken):!0;for(const w of m)d?h.push(await s(d,w,f)):w.type!=="final"&&w.type!=="interim"&&w.type!=="translation"&&h.push(w);return h};if(e[2]==="/audio"&&r.method==="POST"){const d=N.getSession(n)||N.endedSession(n);try{const m=await k(r,t.maxBodyBytes);N.pushAudio(n,N.toFloat32(m,d?.format));const h=await l(d);return a(o,200,{ok:!0,state:N.state(),...h?{events:h}:{}})}catch(m){const h=m.code==="no_session"?await l(d).catch(()=>null):null;return a(o,m.code==="no_session"?404:400,{error:{message:m.message,type:m.code||"stt_error"},...h?{events:h}:{}})}}if(e[2]==="/events"&&r.method==="GET"){const d=N.getSession(n);if(!d)return a(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const m=T=>o.write(`data: ${JSON.stringify(T)}
|
|
59
59
|
|
|
60
|
-
`),h=d.redact?await ke(t.pro?.entitlementToken):!0,f=T=>s(d,T,h);m({type:"state",state:d.remote?"ready":N.state()});const w=setInterval(()=>{const T=d.remote?"ready":N.state();if(T==="downloading"||T==="loading"){m({type:"progress",state:T,...N.progress()||{}});return}if(T==="error"){m({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(d.diarize){const D=$.state();if(D==="downloading"||D==="loading"){m({type:"diarize-progress",state:D,...$.progress()||{}});return}}if(d.translateTo){const D=Me.state();if(D==="downloading"||D==="loading"){m({type:"translate-progress",state:D,...Me.progress()||{}});return}}m({type:"state",state:T}),clearInterval(w)},500);w.unref?.();let v=Promise.resolve();const _=N.subscribe(n,T=>{v=v.then(async()=>{m(await f(T)),T.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(w),_?.()});return}if(!e[2]&&r.method==="DELETE"){const d=N.getSession(n);await N.endSession(n);const m=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&r.method==="GET")return a(o,200,{entries:[...Ee].reverse()});if(i==="/config"&&r.method==="GET"){const e=await ke(t.pro?.entitlementToken);return a(o,200,Lo(t,{proUnlocked:e,policy:st()}))}if(i==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const n=JSON.stringify(t.sandbox||null);if(e.capabilities&&typeof e.capabilities=="object"){const h=JSON.parse(JSON.stringify({capabilities:t.capabilities||{},redaction:t.redaction||{}}));try{Nt(h,{capabilities:e.capabilities})}catch(w){if(w?.code==="SHAPE")return a(o,400,{error:w.message});throw w}const f=Object.keys(e.capabilities).map(w=>
|
|
60
|
+
`),h=d.redact?await ke(t.pro?.entitlementToken):!0,f=T=>s(d,T,h);m({type:"state",state:d.remote?"ready":N.state()});const w=setInterval(()=>{const T=d.remote?"ready":N.state();if(T==="downloading"||T==="loading"){m({type:"progress",state:T,...N.progress()||{}});return}if(T==="error"){m({type:"error",code:"model_failed",message:N.health().error||"model failed to load",fatal:!0}),clearInterval(w);return}if(d.diarize){const D=$.state();if(D==="downloading"||D==="loading"){m({type:"diarize-progress",state:D,...$.progress()||{}});return}}if(d.translateTo){const D=Me.state();if(D==="downloading"||D==="loading"){m({type:"translate-progress",state:D,...Me.progress()||{}});return}}m({type:"state",state:T}),clearInterval(w)},500);w.unref?.();let v=Promise.resolve();const _=N.subscribe(n,T=>{v=v.then(async()=>{m(await f(T)),T.type==="end"&&(clearInterval(w),o.end())}).catch(()=>{})});r.on("close",()=>{clearInterval(w),_?.()});return}if(!e[2]&&r.method==="DELETE"){const d=N.getSession(n);await N.endSession(n);const m=d?.poll?await l(d).catch(()=>null):null;return a(o,200,{ok:!0,...m?{events:m}:{}})}}}if(i==="/logs"&&r.method==="GET")return a(o,200,{entries:[...Ee].reverse()});if(i==="/config"&&r.method==="GET"){const e=await ke(t.pro?.entitlementToken);return a(o,200,Lo(t,{proUnlocked:e,policy:st()}))}if(i==="/config"&&r.method==="POST"){let e=null;try{e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return a(o,400,{error:"invalid config patch"});const n=JSON.stringify(t.sandbox||null);if(e.capabilities&&typeof e.capabilities=="object"){const h=JSON.parse(JSON.stringify({capabilities:t.capabilities||{},redaction:t.redaction||{}}));try{Nt(h,{capabilities:e.capabilities})}catch(w){if(w?.code==="SHAPE")return a(o,400,{error:w.message});throw w}const f=Object.keys(e.capabilities).map(w=>_s(w,t.capabilities?.[w],h.capabilities?.[w])).find(Boolean);if(f&&!await ke(t.pro?.entitlementToken))return a(o,403,{error:f,needs:"pro"})}try{Nt(t,e)}catch(h){if(h?.code==="SHAPE")return a(o,400,{error:h.message});throw h}so(t),JSON.stringify(t.sandbox||null)!==n&&qe?.restart("sandbox settings changed");try{he(t,te())}catch(h){return a(o,500,{error:`could not persist config: ${h.message}`})}const s=t.redaction?.detection,l=!s||!s.backend||s.backend==="off",d=j.state();t.ner?.autostart&&l&&d!=="ready"&&d!=="loading"&&d!=="downloading"&&j.setModel(t.ner.model,{onLog:h=>console.log(h)}).then(h=>{h&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const m=await ke(t.pro?.entitlementToken);return a(o,200,Lo(t,{proUnlocked:m,policy:st()}))}if(r.method==="GET"&&i==="/skills")return we(r,o,t,`/skills${Ve(y,t)}`,{pick:e=>({skills:Array.isArray(e?.skills)?e.skills:[]})});if(r.method==="POST"&&i==="/v1/threads/send"){if(!R(r))return a(o,403,{error:{message:"asking another chat: extension origin or gateway token required",type:"forbidden"}});if(r.headers["x-chatpanel-link-device"])return a(o,403,{error:{message:"asking another chat is not available from a linked phone yet",type:"forbidden"}});const e=J.lossless;if(!e)return a(o,501,{error:{message:"asking another chat needs the SQLite warm store",type:"unavailable"}});let n={};try{n=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}")||{}}catch{return a(o,400,{error:{message:"threads/send: body must be JSON",type:"invalid_request"}})}const s=String(n.to||""),l=String(n.message||"").trim();if(!l||l.length>vo)return a(o,400,{error:{message:`threads/send: a message of 1–${vo} characters`,type:"invalid_request"}});const d=n.from&&typeof n.from=="object"?{id:String(n.from.id||"").slice(0,200),title:String(n.from.title||"").slice(0,200)}:null,m=e.get(s);if(!m||m.deletedAt)return a(o,404,{error:{message:"no such chat on this computer — it may not have synced here yet",type:"not_found"}});const h=pn(m,{cards:de.get("agentTools").agentTools?.value?.agents||[]});if(h.error)return a(o,409,{error:{message:h.error,type:"no_model"}});if(n.dryRun===!0)return a(o,200,{ok:!0,title:m.title,model:h.model});const f=hn({fromTitle:d?.title,message:l}),w={thread:{id:h.thread,...m.title?{title:m.title}:{}},...h.workingDir?{workingDir:h.workingDir}:{}};let v="";try{const T=await fetch(`http://127.0.0.1:${r.socket.localPort}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json","x-chatpanel-token":Je()||Pe(),"x-chatpanel-run":encodeURIComponent(JSON.stringify(w))},body:JSON.stringify({model:h.model,messages:[...yn(m),{role:"user",content:f}],stream:!1}),signal:AbortSignal.timeout(6e5)}),D=await T.json().catch(()=>null);if(!T.ok)return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${D?.error?.message||`HTTP ${T.status}`}`,type:"upstream"}});v=String(D?.choices?.[0]?.message?.content||"")}catch(T){return a(o,502,{error:{message:`that chat's ${h.model} did not answer: ${T?.message||T}`,type:"upstream"}})}const _=fn(e.get(s)||m,{question:f,reply:v,model:h.model,from:d});e.write([_],{host:"gateway",at:Date.now()});try{const T=To(e.get(s));T&&J.bulk({upserts:[T],removes:[]})}catch{}return Ge({ids:[s]}),a(o,200,{ok:!0,title:m.title,model:h.model,reply:v})}const K=/^(?:\/v1)?(\/agent-sessions(?:\/read|\/adopt|\/catchup)?)$/.exec(i)?.[1];if(r.method==="POST"&&K)return R(r)?r.headers["x-chatpanel-link-device"]&&t.link?.agentSessions===!1?a(o,403,{error:{message:"this computer does not share its coding agents' sessions with a linked phone — Settings › Link › Phones",type:"forbidden"}}):we(r,o,t,K,{method:"POST",timeoutMs:3e4}):a(o,403,{error:{message:"the agents' own sessions: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&i==="/skills-quarantined")return we(r,o,t,`/skills-quarantined${Ve(y,t)}`,{pick:e=>({quarantined:Array.isArray(e?.quarantined)?e.quarantined:[]})});if(i==="/skills"&&r.method==="POST")return R(r)?we(r,o,t,"/skills",{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill: extension origin or gateway token required",type:"forbidden"}});if(/^\/skills\/[^/]+$/.test(i)&&r.method==="DELETE"){const e=decodeURIComponent(i.slice(8));return Ht(e)?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):R(r)?we(r,o,t,`/skills/${encodeURIComponent(e)}`,{method:"DELETE"}):a(o,403,{error:{message:"deleting a skill: extension origin or gateway token required",type:"forbidden"}})}if(/^\/skills\/[^/]+\/file\/.+/.test(i)&&r.method==="PUT"){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]);return Ht(n)||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(e[2]))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):R(r)?we(r,o,t,`/skills/${encodeURIComponent(n)}/file/${e[2]}`,{method:"PUT",timeoutMs:15e3}):a(o,403,{error:{message:"writing a skill file: extension origin or gateway token required",type:"forbidden"}})}if(r.method==="GET"&&i==="/agent-defs")return we(r,o,t,`/agent-defs${Ve(y,t)}`,{pick:e=>({agents:Array.isArray(e?.agents)?e.agents:[],...e?.quarantined?{quarantined:e.quarantined}:{},...e?.problems?{problems:e.problems}:{}})});if(r.method==="GET"&&/^\/agent-defs\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(12));return Ht(e)?a(o,400,{error:{message:"not an agent id",type:"invalid_request"}}):we(r,o,t,`/agent-defs/${encodeURIComponent(e)}${Ve(y,t)}`)}if(i.startsWith("/a2a/")){if(!R(r))return a(o,403,{error:{message:"a2a: extension origin or gateway token required",type:"forbidden"}});try{if(r.method==="GET"&&i==="/a2a/agents")return a(o,200,{agents:Fr()});if(r.method==="POST"&&i==="/a2a/card"){const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}");e.forget&&zr(e.url||"");const n=await it(e.url,{force:!!e.force,auth:String(e.auth||"")});return a(o,200,{ok:!0,card:n.card,fingerprint:n.fingerprint,fresh:n.fresh,changed:!!n.changed,url:n.url})}if(r.method==="POST"&&i==="/a2a/message"){const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await it(e.url,{auth:String(e.auth||"")})).card,s=await Gr({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),returnImmediately:!!e.returnImmediately,contextId:String(e.contextId||""),taskId:String(e.taskId||"")});return a(o,200,{ok:!0,...s})}if(r.method==="POST"&&i==="/a2a/message/stream"){const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await it(e.url,{auth:String(e.auth||"")})).card;o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const s=(l,d)=>o.write(`event: ${l}
|
|
61
61
|
data: ${JSON.stringify(d)}
|
|
62
62
|
|
|
63
|
-
`);try{const l=await Gr({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(r.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await it(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Ur({card:n,id:String(e.id||""),auth:String(e.auth||"")}):await Hr({card:n,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const n=e instanceof lo||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof lo&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:n}})}}if(r.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return L(r)?we(r,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):we(r,o,t,`/skills/${encodeURIComponent(e)}${Ve(y,t)}`,{pick:n=>({skill:n?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!L(r))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&r.method==="GET"||i!=="/channels"&&r.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Ye(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=Xe(t.bridge?.token);try{const s=r.method==="POST"?(await k(r,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]),s=e[2];return!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):we(r,o,t,`/skills/${encodeURIComponent(n)}/file/${s}${Ve(y,t)}`)}if(r.method==="GET"&&/\/models$/.test(i)){const e=await z(),n=e.sig!==void 0&&e.sig!==J;return J=e.sig,a(o,200,await xs(t,{serviceHealth:async()=>e,fresh:n,engineAt:c.engineAt}))}if(Zs.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${se}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const H=zs(i,r.headers,t);let ve;try{ve=await k(r,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let ue=null,O=null,Fe=ve,Vt=0,Ft=0,Wt=0,Te=!1,Ne=!1,Kt="",Ie=!0;const ne=t.logRequests&&H.redactable&&r.method==="POST"?js(Ce):null,ar=Date.now();if(H.redactable&&r.method==="POST"&&ve.length){try{O=JSON.parse(ve.toString("utf8"))}catch{O=null}if(O&&Gs(O,H.kind))Fe=ve;else if(O){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(O.tools)&&O.tools.length){const f=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Bs,w=e.narrowAll?null:_=>!Ms.test(Fo(_)),v=O.tools.length;O.tools=br(O.tools,Cs(O,H.kind),{cap:f,keep:w,name:Fo,description:Ds}),Wt=v-O.tools.length}if(Ie=await ke(t.pro?.entitlementToken),Te=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&L(r),!Te){const f=ft(O?.model,t,H.kind,{destination:String(r.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:()=>!1}),w=f?.type==="api"?await c.decide(f,O?.model).catch(()=>null):null;Ne=w?.redact===!1,Kt=Ne?w.engine||"declared":""}if(!Te&&!Ne){const f=hs(t,Ie);if(!f.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${f.cap} redactions). If you have ChatPanel Pro, open Chap (the browser extension or the desktop app) and it hands this gateway its plan — or paste an entitlement token in Settings › Gateway › Pro.`,type:"free_limit_reached"}})}!Te&&!Ne&&await dt(t);const n=Te?[]:H.adapter.collectSegments(O,t.redaction,{skipPublic:L(r)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ne?ne.clock():0,{vault:d,count:m,sanitized:h}=Te?{vault:null,count:0,sanitized:0}:await We(n,t.redaction,{signal:s.signal,isPro:Ie,sanitizeOnly:Ne,onEgress:f=>It.push(Go({ts:Date.now(),client:"redaction",tool:`detect:${f.backend}@${f.host||"local"}`,ok:f.ok,ms:f.ms,error:f.error}))});if(ne&&ne.lap("redact",l),H.adapter.joinTextParts?.(O),ue=d,Vt=m,Ft=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ie&&m>0){ys(t,Ie);try{he(t,te())}catch{}}if(!Te&&!Ne&&Array.isArray(O.tools)&&O.tools.length&&typeof H.adapter.injectSystemNote=="function"){const f=ft(O?.model,t,H.kind,{destination:String(r.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:v=>!!v.service&&x.fn(v.id)==="down"}),w=!(f&&f.type==="api");H.adapter.injectSystemNote(O,kr({toolData:t.tools?.toolData,ownTools:w}))}else!Te&&m>0&&typeof H.adapter.injectSystemNote=="function"&&H.adapter.injectSystemNote(O,Sr());Fe=Buffer.from(JSON.stringify(O),"utf8")}}const Qt=vr({vault:ue,toolData:t.tools?.toolData}),et=O&&typeof O.chatpanel=="object"&&O.chatpanel||null;if(et&&(delete O.chatpanel,Fe=Buffer.from(JSON.stringify(O),"utf8")),typeof O?.model=="string"&&O.model.startsWith("fusion:")){const e=Un(O.model,t,await z());if(e?.error)return ne?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(O.model=e.model,Fe=Buffer.from(JSON.stringify(O),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ae={destination:String(r.headers["x-chatpanel-destination"]||et?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||et?.reach||"").trim(),run:Ut(r.headers["x-chatpanel-run"],et?.run)},tt=await z(),Yt=e=>!!e.service&&tt(e.id)==="down";let B=ft(O?.model,t,H.kind,{destination:ae.destination,down:Yt});B?.type==="agent"&&O?.model&&!ae.destination&&!Es(B,O.model)&&(await Os(t,{serviceHealth:async()=>tt,engineAt:c.engineAt}),B=ft(O?.model,t,H.kind,{destination:ae.destination,down:Yt}));const Xt=B?.service&&tt(B.id)==="down"?await P().revive(B.service).catch(()=>null):null;if(Xt?.ok&&(x.at=0),B?.service&&tt(B.id)==="down"&&!Xt?.ok)return ne?.commit(),a(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(O?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(ae.destination&&(!B||B.id!==ae.destination))return ne?.commit(),a(o,404,{error:{message:`no destination "${ae.destination}" is configured on this gateway`,type:"unknown_destination",known:_s(t).map(e=>e.id)}});const ie=Be(r.headers);if(ie&&!ga(ie,B?.type==="api"?"api":"agent"))return ne?.commit(),a(o,403,{error:{message:`link: partner "${ie.partner}" may not use ${B?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ie.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const ot=ie&&H.redactable&&r.method==="POST"&&O?{caller:ie,surface:In(ie,ie.kind==="partner"?"":g?.deviceNameOf(ie.device)),model:O.model||null,startedAt:ar}:null;ne&&(ne.meta={t:Date.now(),model:O?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:Vt,sanitized:Ft,narrowed:Wt,detail:Yo(ue,t.logDetail),redaction:Te?"off":Ne?`on-device (${Kt})`:t.redaction.tier||"basic",...ie?.kind==="partner"?{via:wa(ie)}:{}});const rt=st();if(rt&&B){const e=B.type==="api"?io(rt,{model:O?.model||"",endpoint:B.baseUrl||""}):Jr(rt,B.agent||B.id)?io(rt,{model:O?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ne?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?Hs(B.baseUrl,t)?(ne?.commit(),a(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):qs(r,o,{...H,pathname:i,search:y.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:Qt,trace:ne,link:ot&&{...ot,agentId:B.id,dest:{type:"api",id:B.id}}},Fe,ue):(ne?.commit(),a(o,502,{error:`destination "${B.id}" has no baseUrl`}));const bt=Ke(r),Zt=bt==="local"&&t.bridge?.openAgentLane?"token":bt;if(Zt==="local")return ne?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const qt=Math.max(0,Math.min(8,Number(r.headers["x-chatpanel-ask-depth"])||0)),sr=new Set(["thread","ephemeral","workingDir","worker"]),vt=ie?.kind==="partner";if(bt==="token"&&r.headers["x-chatpanel-link-device"]&&!vt&&!(ae.run&&Object.keys(ae.run).some(e=>!sr.has(e)))){const e=Ut(null,bo(wo(de.get("agentTools").agentTools?.value,B?.agent||O?.model)));e&&(ae.run={...e,...ae.run||{}})}if(vt){const e=Ut(null,bo(wo(de.get("agentTools").agentTools?.value,B?.agent||O?.model)));ae.run={...e||{},...ba(ae.run,ie.device)};const n=g?.partnerFolderOf(ie.device);if(!n)return ne?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ae.run.workingDir=n,ae.reach="",Array.isArray(O?.tools)&&(O.tools=O.tools.filter(s=>!_o(s?.function?.name??s?.name)))}const Re=xr({...ae.run||{},...ae.reach?{reach:ae.reach}:{},...qt?{askDepth:qt}:{}},Zt);Re.reach&&o.setHeader("x-chatpanel-reach-used",Re.reach);const ir=vt?{inbox:b,partner:ie.partner,device:ie.device,conversation:Re.thread?.id||null}:null,lr=ot&&{...ot,dest:{type:"agent",id:B?.id||"bridge"},threadId:Re.thread?.id||null};return Ks(r,o,{...H,pathname:i,agentOverride:B?.agent,harness:Qt,trace:ne,run:Object.keys(Re).length?Re:null,owner:ir,link:lr},O,ue,t,Ie)});return ge.on("close",()=>{E?.stop("closed"),ea(),p.close(),g?.stop(),b.stop()}),ge.on("upgrade",(r,o,y)=>{o.on("error",()=>{});const i=String(r.url||"").split("?")[0];if(g&&i.startsWith(fa)){g.acceptTunnel(r,o,y).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
|
|
63
|
+
`);try{const l=await Hr({card:n,message:e.message||{messageId:`cp_${Date.now().toString(36)}`,role:"ROLE_USER",parts:[{text:String(e.text||"")}]},auth:String(e.auth||""),contextId:String(e.contextId||""),taskId:String(e.taskId||""),onEvent:d=>s(d.kind,{kind:d.kind,task:d.task,message:d.message})});s("done",l)}catch(l){s("error",{code:l.code||"ERROR",message:l.message})}return o.end()}if(r.method==="POST"&&i==="/a2a/task"){const e=JSON.parse((await k(r,t.maxBodyBytes)).toString("utf8")||"{}"),n=e.card||(await it(e.url,{auth:String(e.auth||"")})).card,s=e.cancel?await Vr({card:n,id:String(e.id||""),auth:String(e.auth||"")}):await Ur({card:n,id:String(e.id||""),auth:String(e.auth||"")});return a(o,200,{ok:!0,...s})}return a(o,404,{error:{message:`no such a2a route: ${i}`,type:"invalid_request"}})}catch(e){const n=e instanceof lo||e?.name==="A2AClientError"?e.code:"ERROR";return a(o,e instanceof lo&&e.code==="UNREACHABLE"?502:400,{error:{message:e.message,type:"a2a_error",code:n}})}}if(r.method==="POST"&&(i==="/agent-defs/export"||i==="/agent-defs/export-plan"))return R(r)?we(r,o,t,i,{method:"POST",timeoutMs:15e3}):a(o,403,{error:{message:"exporting an agent: extension origin or gateway token required",type:"forbidden"}});if(r.method==="GET"&&/^\/skills\/[^/]+$/.test(i)){const e=decodeURIComponent(i.slice(8));return!e||e==="."||e===".."||e.includes("/")||e.includes("\\")?a(o,400,{error:{message:"not a skill id",type:"invalid_request"}}):we(r,o,t,`/skills/${encodeURIComponent(e)}${Ve(y,t)}`,{pick:n=>({skill:n?.skill||null})})}if(i==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(i)){if(!R(r))return a(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(i==="/channels"&&r.method==="GET"||i!=="/channels"&&r.method==="POST"))return a(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await Ye(t);if(!e)return a(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const n=Xe(t.bridge?.token);try{const s=r.method==="POST"?(await k(r,t.maxBodyBytes)).toString("utf8"):"",l=await fetch(`${e}${i}`,{method:r.method,headers:{Accept:"application/json",...r.method==="POST"?{"content-type":"application/json"}:{},...n?{Authorization:`Bearer ${n}`}:{}},...r.method==="POST"?{body:s||"{}"}:{},signal:AbortSignal.timeout(15e3)}),d=await l.json().catch(()=>({}));return a(o,l.status,d)}catch(s){return a(o,502,{error:{message:`bridge unreachable: ${s.message}`,type:"bridge_unreachable"}})}}if(r.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(i)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(i),n=decodeURIComponent(e[1]),s=e[2];return!n||n==="."||n===".."||n.includes("/")||n.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(s))?a(o,400,{error:{message:"not a skill file",type:"invalid_request"}}):we(r,o,t,`/skills/${encodeURIComponent(n)}/file/${s}${Ve(y,t)}`)}if(r.method==="GET"&&/\/models$/.test(i)){const e=await z(),n=e.sig!==void 0&&e.sig!==L;return L=e.sig,a(o,200,await Os(t,{serviceHealth:async()=>e,fresh:n,engineAt:c.engineAt}))}if(ei.some(e=>i===e||i.startsWith(`${e}/`)))return a(o,404,{error:{message:`this gateway (${se}) has no ${i} — update it to use this feature`,type:"unknown_endpoint"}});const H=Hs(i,r.headers,t);let ve;try{ve=await k(r,t.maxBodyBytes)}catch(e){a(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),r.destroy();return}let ue=null,O=null,Fe=ve,Vt=0,Ft=0,Wt=0,Te=!1,Ne=!1,Kt="",Ie=!0;const ne=t.logRequests&&H.redactable&&r.method==="POST"?Gs(Ce):null,sr=Date.now();if(H.redactable&&r.method==="POST"&&ve.length){try{O=JSON.parse(ve.toString("utf8"))}catch{O=null}if(O&&Us(O,H.kind))Fe=ve;else if(O){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(O.tools)&&O.tools.length){const f=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Ds,w=e.narrowAll?null:_=>!Cs.test(Wo(_)),v=O.tools.length;O.tools=vr(O.tools,Rs(O,H.kind),{cap:f,keep:w,name:Wo,description:Is}),Wt=v-O.tools.length}if(Ie=await ke(t.pro?.entitlementToken),Te=String(r.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&R(r),!Te){const f=ft(O?.model,t,H.kind,{destination:String(r.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:()=>!1}),w=f?.type==="api"?await c.decide(f,O?.model).catch(()=>null):null;Ne=w?.redact===!1,Kt=Ne?w.engine||"declared":""}if(!Te&&!Ne){const f=fs(t,Ie);if(!f.allowed)return a(o,402,{error:{message:`ChatPanel Gateway free trial used up (${f.cap} redactions). If you have ChatPanel Pro, open Chap (the browser extension or the desktop app) and it hands this gateway its plan — or paste an entitlement token in Settings › Gateway › Pro.`,type:"free_limit_reached"}})}!Te&&!Ne&&await dt(t);const n=Te?[]:H.adapter.collectSegments(O,t.redaction,{skipPublic:R(r)}),s=new AbortController;o.on("close",()=>{o.writableFinished||s.abort()});const l=ne?ne.clock():0,{vault:d,count:m,sanitized:h}=Te?{vault:null,count:0,sanitized:0}:await We(n,t.redaction,{signal:s.signal,isPro:Ie,sanitizeOnly:Ne,onEgress:f=>It.push(Go({ts:Date.now(),client:"redaction",tool:`detect:${f.backend}@${f.host||"local"}`,ok:f.ok,ms:f.ms,error:f.error}))});if(ne&&ne.lap("redact",l),H.adapter.joinTextParts?.(O),ue=d,Vt=m,Ft=h||0,m>0&&o.setHeader("x-chatpanel-redacted",String(m)),!Ie&&m>0){gs(t,Ie);try{he(t,te())}catch{}}if(!Te&&!Ne&&Array.isArray(O.tools)&&O.tools.length&&typeof H.adapter.injectSystemNote=="function"){const f=ft(O?.model,t,H.kind,{destination:String(r.headers["x-chatpanel-destination"]||O?.chatpanel?.destination||"").trim(),down:v=>!!v.service&&x.fn(v.id)==="down"}),w=!(f&&f.type==="api");H.adapter.injectSystemNote(O,Sr({toolData:t.tools?.toolData,ownTools:w}))}else!Te&&m>0&&typeof H.adapter.injectSystemNote=="function"&&H.adapter.injectSystemNote(O,Tr());Fe=Buffer.from(JSON.stringify(O),"utf8")}}const Qt=kr({vault:ue,toolData:t.tools?.toolData}),et=O&&typeof O.chatpanel=="object"&&O.chatpanel||null;if(et&&(delete O.chatpanel,Fe=Buffer.from(JSON.stringify(O),"utf8")),typeof O?.model=="string"&&O.model.startsWith("fusion:")){const e=Fn(O.model,t,await z());if(e?.error)return ne?.commit(),a(o,400,{error:{message:e.error,type:"fusion"}});e&&(O.model=e.model,Fe=Buffer.from(JSON.stringify(O),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const ae={destination:String(r.headers["x-chatpanel-destination"]||et?.destination||"").trim(),reach:String(r.headers["x-chatpanel-reach"]||et?.reach||"").trim(),run:Ut(r.headers["x-chatpanel-run"],et?.run)},tt=await z(),Yt=e=>!!e.service&&tt(e.id)==="down";let B=ft(O?.model,t,H.kind,{destination:ae.destination,down:Yt});B?.type==="agent"&&O?.model&&!ae.destination&&!$s(B,O.model)&&(await Ps(t,{serviceHealth:async()=>tt,engineAt:c.engineAt}),B=ft(O?.model,t,H.kind,{destination:ae.destination,down:Yt}));const Xt=B?.service&&tt(B.id)==="down"?await P().revive(B.service).catch(()=>null):null;if(Xt?.ok&&(x.at=0),B?.service&&tt(B.id)==="down"&&!Xt?.ok)return ne?.commit(),a(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(O?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(ae.destination&&(!B||B.id!==ae.destination))return ne?.commit(),a(o,404,{error:{message:`no destination "${ae.destination}" is configured on this gateway`,type:"unknown_destination",known:Es(t).map(e=>e.id)}});const ie=Be(r.headers);if(ie&&!ba(ie,B?.type==="api"?"api":"agent"))return ne?.commit(),a(o,403,{error:{message:`link: partner "${ie.partner}" may not use ${B?.type==="api"?"this model":"this computer’s coding agents"} — its scopes are ${ie.scopes.join(", ")||"none"}; the owner grants agents at pairing`,type:"forbidden",code:"link_scope"}});const ot=ie&&H.redactable&&r.method==="POST"&&O?{caller:ie,surface:Jn(ie,ie.kind==="partner"?"":g?.deviceNameOf(ie.device)),model:O.model||null,startedAt:sr}:null;ne&&(ne.meta={t:Date.now(),model:O?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:Vt,sanitized:Ft,narrowed:Wt,detail:Xo(ue,t.logDetail),redaction:Te?"off":Ne?`on-device (${Kt})`:t.redaction.tier||"basic",...ie?.kind==="partner"?{via:va(ie)}:{}});const rt=st();if(rt&&B){const e=B.type==="api"?io(rt,{model:O?.model||"",endpoint:B.baseUrl||""}):Lr(rt,B.agent||B.id)?io(rt,{model:O?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return ne?.commit(),a(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?Vs(B.baseUrl,t)?(ne?.commit(),a(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):ti(r,o,{...H,pathname:i,search:y.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:Qt,trace:ne,link:ot&&{...ot,agentId:B.id,dest:{type:"api",id:B.id}}},Fe,ue):(ne?.commit(),a(o,502,{error:`destination "${B.id}" has no baseUrl`}));const bt=Ke(r),Zt=bt==="local"&&t.bridge?.openAgentLane?"token":bt;if(Zt==="local")return ne?.commit(),a(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const qt=Math.max(0,Math.min(8,Number(r.headers["x-chatpanel-ask-depth"])||0)),ir=new Set(["thread","ephemeral","workingDir","worker"]),vt=ie?.kind==="partner";if(bt==="token"&&r.headers["x-chatpanel-link-device"]&&!vt&&!(ae.run&&Object.keys(ae.run).some(e=>!ir.has(e)))){const e=Ut(null,bo(wo(de.get("agentTools").agentTools?.value,B?.agent||O?.model)));e&&(ae.run={...e,...ae.run||{}})}if(vt){const e=Ut(null,bo(wo(de.get("agentTools").agentTools?.value,B?.agent||O?.model)));ae.run={...e||{},...ka(ae.run,ie.device)};const n=g?.partnerFolderOf(ie.device);if(!n)return ne?.commit(),a(o,403,{error:{message:"link: this partner has no folder on this computer — pair it again with agents",type:"forbidden",code:"link_scope"}});ae.run.workingDir=n,ae.reach="",Array.isArray(O?.tools)&&(O.tools=O.tools.filter(s=>!_o(s?.function?.name??s?.name)))}const Re=_r({...ae.run||{},...ae.reach?{reach:ae.reach}:{},...qt?{askDepth:qt}:{}},Zt);Re.reach&&o.setHeader("x-chatpanel-reach-used",Re.reach);const lr=vt?{inbox:b,partner:ie.partner,device:ie.device,conversation:Re.thread?.id||null}:null,dr=ot&&{...ot,dest:{type:"agent",id:B?.id||"bridge"},threadId:Re.thread?.id||null};return Ys(r,o,{...H,pathname:i,agentOverride:B?.agent,harness:Qt,trace:ne,run:Object.keys(Re).length?Re:null,owner:lr,link:dr},O,ue,t,Ie)});return ge.on("close",()=>{E?.stop("closed"),oa(),p.close(),g?.stop(),b.stop()}),ge.on("upgrade",(r,o,y)=>{o.on("error",()=>{});const i=String(r.url||"").split("?")[0];if(g&&i.startsWith(wa)){g.acceptTunnel(r,o,y).catch(()=>{try{o.destroy()}catch{}});return}try{o.end(`HTTP/1.1 404 Not Found\r
|
|
64
64
|
connection: close\r
|
|
65
65
|
content-length: 0\r
|
|
66
66
|
\r
|
|
67
|
-
`)}catch{}}),ge.once("listening",()=>{P()}),ge.linkHost=g,ge.teamBuckets=I,ge.runtimeDefaults=()=>P().ensureDefaults(),ge}function Ut(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(g=>String(g).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const g=u.workspace;p.workspace={repo:String(g.repo).slice(0,400),projectId:String(g.projectId||"").slice(0,120),jobId:String(g.jobId||"").slice(0,120),...g.base?{base:String(g.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),
|
|
67
|
+
`)}catch{}}),ge.once("listening",()=>{P()}),ge.linkHost=g,ge.teamBuckets=I,ge.runtimeDefaults=()=>P().ensureDefaults(),ge}function Ut(t,c){let u=c&&typeof c=="object"?c:null;if(!u&&t)try{u=JSON.parse(decodeURIComponent(String(t)))}catch{u=null}if(!u||typeof u!="object")return null;const p={};if(Array.isArray(u.grants)&&(p.grants=u.grants.map(g=>String(g).slice(0,80)).slice(0,32)),u.workspace&&typeof u.workspace=="object"&&u.workspace.repo){const g=u.workspace;p.workspace={repo:String(g.repo).slice(0,400),projectId:String(g.projectId||"").slice(0,120),jobId:String(g.jobId||"").slice(0,120),...g.base?{base:String(g.base).slice(0,120)}:{}}}if(u.connectionId&&(p.connectionId=String(u.connectionId).slice(0,64)),typeof u.workingDir=="string"&&u.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(u.workingDir.trim())&&(p.workingDir=u.workingDir.trim().slice(0,1024)),ks.includes(u.permissionMode)&&u.permissionMode!=="default"&&(p.permissionMode=u.permissionMode),u.sandbox&&typeof u.sandbox=="object"){const g=(Array.isArray(u.sandbox.hosts)?u.sandbox.hosts:String(u.sandbox.hosts||"").split(/[\s,;]+/)).map(S=>String(S).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),A=(Array.isArray(u.sandbox.write)?u.sandbox.write:[]).map(S=>String(S).slice(0,1024)).filter(Boolean).slice(0,32),M=u.sandbox.outside===!0,E=(Array.isArray(u.sandbox.signIn)?u.sandbox.signIn:[]).map(S=>String(S).trim().toLowerCase().slice(0,32)).filter(Boolean).slice(0,8);(g.length||A.length||M||E.length)&&(p.sandbox={...g.length?{hosts:g}:{},...A.length?{write:A}:{},...M?{outside:!0}:{},...E.length?{signIn:E}:{}})}const b=dn(u.thread);return b&&(p.thread=b),u.ephemeral===!0&&(p.ephemeral=!0),u.worker===!0&&(p.worker=!0,p.ephemeral=!0),u.lean===!0&&(p.lean=!0,p.ephemeral=!0),Object.keys(p).length?p:null}let qe=null,wt=null;async function sd(t=to()){tn();let c=null;try{c=await Rr()}catch(S){throw S instanceof Jr&&(console.error(`[chatpanel-gateway] org policy: ${S.message}`),process.exit(78)),S}const u=c?.policy||null;u&&(so(t,u),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`));const p=Cr({enabled:ao(t)});console.log(`[chatpanel-gateway] certificates: ${p.on?`this computer's list is trusted too (${p.added} added to the runtime's own)`:`the runtime's own list only — ${p.why}`}`),Mr(globalThis,{allow:u?.egress?(S,{local:x})=>jr(u,S,{local:x}):null}),Pe();const b=oi(t),g=Zr(t),A=pr(t);let M=!1;b.on("error",S=>{if(S&&S.code==="EADDRINUSE"){const x=gt(t.host)?"127.0.0.1":t.host;fetch(`http://${x}:${t.port}/health`,{signal:AbortSignal.timeout(1500)}).then(L=>L.ok?L.json():null).catch(()=>null).then(L=>{const z=!!(L?.version&&typeof L.tier=="string"),F=cn({name:"gateway",self:se,holder:z?{ours:z,version:L.version}:null,managedBy:un(process.env),port:t.port});if(F.action==="standby"||M&&!L){if(!M)for(const P of F.lines)console.error(P);M=!0,setTimeout(()=>b.listen(t.port,t.host),mn);return}if(z){const P=L.managedBy?` (run by ${L.managedBy})`:"";for(const[V,G]of F.lines.entries())console.error(V===0?G.replace(` on ${t.port}`,` at http://${x}:${t.port}${P}`):G)}else{const P=On(t.port);console.error(`Port ${t.port} is held by ${P||"another program"}, which is not a ChatPanel gateway.`),console.error(`Fix: stop that program, or set a different port — edit "port" in ${te()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`)}process.exit(1)});return}console.error(`Gateway server error: ${S?.message||S}`),process.exit(1)}),b.listen(t.port,t.host,()=>{if(M&&console.log(" standby : the other gateway is gone — this copy has the port now"),M=!1,console.log(`ChatPanel Privacy Gateway v${se} on http://${t.host}:${t.port}`),b.linkHost?.start().catch(S=>console.log(` link : not started (${S?.message||S})`)),(t.context?.providers||[]).some(S=>S?.kind==="bucket"&&S.enabled!==!1))try{b.teamBuckets?.().start()}catch(S){console.log(` team : not started (${S?.message||S})`)}b.runtimeDefaults?.().then(S=>{for(const x of S||[])console.log(` ${x.label.toLowerCase().padEnd(9).slice(0,9)}: ${x.ok?x.already?"running":x.adopted?"already running — adopted":"started":`not started (${x.skipped})`}`)}).catch(S=>console.log(` runtime : defaults not started (${S?.message||S})`)),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token");for(const S of Ts(t))console.log(` ⚠ sandbox : ${S}`);console.log(` confined : ${Bn(ct({stateDir:ze.dirname(te())}))}`),wt={mode:"starting",version:null,pid:null,restarts:0,why:"deciding: adopt the bridge that answers, or start ours"},_n(t,{childEnv:()=>({...Ss(t,process.env,st()),...vs(t)})}).then(S=>{qe=S}).catch(S=>{wt={mode:"off",version:null,pid:null,restarts:0,why:`not supervised (${S?.message||S})`},console.log(` bridge : not supervised (${S?.message||S})`)}),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),gt(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),fo()&&Ot(J,St()).then(S=>{S?.ok&&(console.log(` warm : seeded ${S.ingested} records from ${S.file}`),S.whole&&Ge())}).catch(()=>{});const E=()=>{g?.stop(),A.stop(),qe?.stop(),Ms(b)};return process.on("SIGINT",E),process.on("SIGTERM",E),b}export{Fs as RECORDS_MAX_BYTES,dd as VERSION,oi as createGateway,Xs as joinUpstream,Rt as parseAgentModel,sd as start};
|
package/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const o="0.
|
|
1
|
+
const o="0.157.0";export{o as VERSION};
|