@chatpanel/gateway 0.133.3 → 0.137.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.133.3",
3
+ "version": "0.137.1",
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.49.0",
27
- "@chatpanel/events": "^0.425.2",
27
+ "@chatpanel/events": "^0.430.1",
28
28
  "@chatpanel/pii": "^0.15.6",
29
29
  "@huggingface/transformers": "^4.2.0",
30
30
  "defuddle": "^0.19.4",
@@ -1 +1 @@
1
- import{secureFetch as N}from"./secure-fetch.js";import{primaryProvider as z,capabilityList as J}from"./capability-config.js";import{createReadStats as G}from"./retrieval/read.js";import{CAPABILITY_ROUTES as j,overBudget as D,validateRerankRequest as H,validateRerankResponse as U,validateDecideRequest as V,validateDecideResponse as W,validateEmbedRequest as X,validateEmbedResponse as Y}from"./capability-endpoints.js";import{adaptRequest as K,adaptResponse as Q}from"./capability-adapters.js";import{defaultEmbeddedModel as S}from"./embedded-models.js";const M=Object.freeze(["rerank","decide","embed"]),x={rerank:{request:H,response:U,chars:m=>m.query.length+m.documents.reduce((h,c)=>h+c.length,0)},decide:{request:V,response:W,chars:m=>m.state.length},embed:{request:X,response:Y,chars:m=>m.input.reduce((h,c)=>h+c.length,0)}},Z=18e4,ee=6e4,i=(m,h,c,y={})=>({status:m,body:{error:{type:h,message:c,...y}}});function le({cfg:m,fetchImpl:h=N,now:c=()=>Date.now(),wake:y=null,embedded:g=null,asleep:A=null}={}){const q=Object.fromEntries(M.map(e=>[e,{stats:G(),last:null,error:null}])),R=e=>z(m.capabilities?.[e],e),w=e=>{const t=R(e);return t&&t.provider!=="embedded"&&t.provider!=="none"&&typeof t.url=="string"&&/^https?:\/\//.test(t.url)&&typeof t.adapter=="string"?t:null},E=e=>{if(!g||w(e))return null;const t=R(e);if(t?.provider==="none")return null;const n=t?.provider==="embedded"&&typeof t.model=="string"&&t.model?t.model:S(e);return n?{model:n}:null},L=e=>{if(!g||R(e)?.provider==="none")return null;const t=S(e);return t?{model:t}:null};async function $(e,t,n){const d=x[e];let s;try{s=d.request(n)}catch(u){return i(400,"invalid_request",u.message)}if(s.model&&s.model!==t.model)return i(404,"model_not_found",`${e}: model ${s.model} is not served here (${t.model} is)`);const a=q[e],v=d.chars(s),r=D(a.stats.stats(),v,s.budgetMs);if(r)return{status:503,body:r};const o=c();let f;try{f={...await g.call(e,s,t.model),model:t.model}}catch(u){return u.code==="WARMING"?i(503,"provider_warming",u.message,u.progress?{progress:u.progress}:{}):i(503,"provider_unavailable",`${e}: the in-process model ${t.model} could not answer — ${u.message}`)}const _=c()-o;f={...f,ms:_,...e==="decide"?{calibrated:!1}:{}};try{d.response(f,s)}catch(u){return i(502,"bad_shape",`${e}: the in-process answer did not fit the contract — ${u.message}`)}return a.stats.record(_,v),a.error=null,a.last=c(),{status:200,body:f}}async function B(e,t){if(!M.includes(e))return i(404,"unknown_capability",`no such capability ${e}`);let n=J(m.capabilities?.[e],e).providers;if(!n.length||n[0]?.provider==="none"||!w(e)&&n[0]?.provider!=="embedded"){const r=w(e);if(r)return T(e,r,t);const o=E(e);return o?$(e,o,t):i(404,"no_provider",`no ${e} provider — it is turned off (capabilities.${e}.provider = none): turn it on under Settings › Runtime, or point capabilities.${e}.url at a server that provides it`)}let d;try{d=x[e].request(t)}catch(r){return i(400,"invalid_request",r.message)}const s=r=>r.provider==="embedded"?typeof r.model=="string"&&r.model?r.model:S(e):r.model||null;if(d.model){const r=n.filter(o=>!s(o)||s(o)===d.model);r.length?n=r:n=n.slice(0,1)}if(e==="embed"){const r=s(n[0]);n=n.filter(o=>s(o)===r)}if(d.wake===!1){const r=g?n.find(f=>f.provider==="embedded"):null;if(r)return $(e,{model:s(r)},t);const o=L(e);if(o)return $(e,o,t)}const a=[];let v=null;for(const r of n){if(r.provider==="none")break;let o;if(r.provider==="embedded"){if(!g)continue;o=await $(e,{model:s(r)},t)}else{if(!(typeof r.url=="string"&&/^https?:\/\//.test(r.url)&&typeof r.adapter=="string"))continue;o=await T(e,r,t)}if(o.status===200)return a.length?{status:200,body:{...o.body,fellBackFrom:a}}:o;if(o.status===400||o.status===404)return o;a.push(r.service||r.id||(r.provider==="embedded"?"in-process":r.url)),v=o}return v||i(404,"no_provider",`no ${e} provider answers here`)}async function T(e,t,n){const d=x[e];let s;try{s=d.request(n)}catch(l){return i(400,"invalid_request",l.message)}if(s.model&&t.model&&s.model!==t.model)return i(404,"model_not_found",`${e}: model ${s.model} is not served here (${t.model} is)`);const a=q[e],v=d.chars(s),r=D(a.stats.stats(),v,s.budgetMs);if(r)return{status:503,body:r};let o;try{o=K(t.adapter,{...s,model:s.model||t.model||void 0})}catch(l){return i(500,"bad_adapter",l.message)}const f=`${t.url.replace(/\/+$/,"")}${o.route}`,_=()=>h(f,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...t.token?{authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify(o.body),signal:AbortSignal.timeout(s.budgetMs?Math.max(s.budgetMs*2,5e3):a.stats.stats().calls?ee:Z)});if(s.wake===!1){const l=L(e);if(l)return $(e,l,n);if(t.service&&typeof A=="function"&&A(t.service))return i(503,"provider_asleep",`${e}: the ${t.service} container is asleep and this call does not wake it — carry on without it`)}const u=!!(t.service&&typeof y=="function");if(u){const l=await y(t.service).catch(O=>({ok:!1,error:O.message}));if(!l?.ok)return a.error=l?.error||"could not start",a.last=c(),i(503,"provider_unavailable",`${e}: the ${t.service} container could not be started — ${a.error}`)}const F=c();let b;try{b=await _()}catch(l){const O=u?await y(t.service,{force:!0}).catch(()=>null):null;try{if(!O?.ok)throw l;b=await _()}catch(P){return a.error=P.message,a.last=c(),i(503,"provider_unavailable",`${e}: ${t.service?`the ${t.service} container`:t.url} did not answer — ${P.message}`)}}let p;try{p=await b.json()}catch{p=null}if(!b.ok)return a.error=`HTTP ${b.status}`,a.last=c(),i(502,"provider_error",`${e}: the provider answered ${b.status}${p?.detail?` — ${typeof p.detail=="string"?p.detail:JSON.stringify(p.detail)}`:p?.error?` — ${typeof p.error=="string"?p.error:p.error.message||""}`:""}`);const I=c()-F;let k;try{const l=Q(t.adapter,p,s);k={...l,model:t.model||l.model||t.adapter,...l.model&&t.model&&l.model!==t.model?{providerModel:l.model}:{},ms:I,...e==="decide"?{calibrated:t.calibrated===!0}:{}},d.response(k,s)}catch(l){return a.error=l.message,a.last=c(),i(502,"bad_shape",`${e}: the provider's answer did not fit the contract — ${l.message}`)}return a.stats.record(I,v),a.error=null,a.last=c(),{status:200,body:k}}function C(e){const t=w(e),n=q[e],d=n.stats.stats();if(!t){const s=E(e);if(!s)return null;const a=g.health(e,s.model);return{id:e,route:j[e],models:[s.model],default:s.model,requirements:{egress:"none"},...e==="decide"?{calibrated:!1}:{},stats:d,runtime:{...a,name:"embedded",model:s.model,threads:g.threads}}}return{id:e,route:j[e],models:t.model?[t.model]:[],...t.model?{default:t.model}:{},requirements:{egress:/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(t.url)?"none":"trusted"},...e==="decide"?{calibrated:t.calibrated===!0}:{},stats:d,runtime:{state:n.error?"down":d.calls?"ready":"idle",name:t.service?"container":"external",adapter:t.adapter,...t.service?{service:t.service}:{},url:t.url,...n.error?{error:n.error}:{}}}}return{call:B,entry:C,stats:e=>q[e]?.stats.stats()||{calls:0},capabilities:M}}export{le as createCapabilityProxy};
1
+ import{secureFetch as N}from"./secure-fetch.js";import{primaryProvider as z,capabilityList as J}from"./capability-config.js";import{createReadStats as G}from"./retrieval/read.js";import{CAPABILITY_ROUTES as j,overBudget as D,validateRerankRequest as H,validateRerankResponse as U,validateDecideRequest as V,validateDecideResponse as W,validateEmbedRequest as X,validateEmbedResponse as Y}from"./capability-endpoints.js";import{adaptRequest as K,adaptResponse as Q}from"./capability-adapters.js";import{defaultEmbeddedModel as S}from"./embedded-models.js";const M=Object.freeze(["rerank","decide","embed"]),x={rerank:{request:H,response:U,chars:u=>u.query.length+u.documents.reduce((h,d)=>h+d.length,0)},decide:{request:V,response:W,chars:u=>u.state.length},embed:{request:X,response:Y,chars:u=>u.input.reduce((h,d)=>h+d.length,0)}},Z=18e4,ee=6e4,i=(u,h,d,y={})=>({status:u,body:{error:{type:h,message:d,...y}}});function le({cfg:u,fetchImpl:h=N,now:d=()=>Date.now(),wake:y=null,embedded:g=null,asleep:A=null}={}){const q=Object.fromEntries(M.map(e=>[e,{stats:G(),last:null,error:null}])),R=e=>z(u.capabilities?.[e],e,{destinations:u.destinations||[]}),w=e=>{const t=R(e);return t&&t.provider!=="embedded"&&t.provider!=="none"&&typeof t.url=="string"&&/^https?:\/\//.test(t.url)&&typeof t.adapter=="string"?t:null},E=e=>{if(!g||w(e))return null;const t=R(e);if(t?.provider==="none")return null;const n=t?.provider==="embedded"&&typeof t.model=="string"&&t.model?t.model:S(e);return n?{model:n}:null},L=e=>{if(!g||R(e)?.provider==="none")return null;const t=S(e);return t?{model:t}:null};async function $(e,t,n){const c=x[e];let s;try{s=c.request(n)}catch(m){return i(400,"invalid_request",m.message)}if(s.model&&s.model!==t.model)return i(404,"model_not_found",`${e}: model ${s.model} is not served here (${t.model} is)`);const a=q[e],v=c.chars(s),r=D(a.stats.stats(),v,s.budgetMs);if(r)return{status:503,body:r};const o=d();let f;try{f={...await g.call(e,s,t.model),model:t.model}}catch(m){return m.code==="WARMING"?i(503,"provider_warming",m.message,m.progress?{progress:m.progress}:{}):i(503,"provider_unavailable",`${e}: the in-process model ${t.model} could not answer — ${m.message}`)}const _=d()-o;f={...f,ms:_,...e==="decide"?{calibrated:!1}:{}};try{c.response(f,s)}catch(m){return i(502,"bad_shape",`${e}: the in-process answer did not fit the contract — ${m.message}`)}return a.stats.record(_,v),a.error=null,a.last=d(),{status:200,body:f}}async function B(e,t){if(!M.includes(e))return i(404,"unknown_capability",`no such capability ${e}`);let n=J(u.capabilities?.[e],e,{destinations:u.destinations||[]}).providers;if(!n.length||n[0]?.provider==="none"||!w(e)&&n[0]?.provider!=="embedded"){const r=w(e);if(r)return T(e,r,t);const o=E(e);return o?$(e,o,t):i(404,"no_provider",`no ${e} provider — it is turned off (capabilities.${e}.provider = none): turn it on under Settings › Runtime, or point capabilities.${e}.url at a server that provides it`)}let c;try{c=x[e].request(t)}catch(r){return i(400,"invalid_request",r.message)}const s=r=>r.provider==="embedded"?typeof r.model=="string"&&r.model?r.model:S(e):r.model||null;if(c.model){const r=n.filter(o=>!s(o)||s(o)===c.model);r.length?n=r:n=n.slice(0,1)}if(e==="embed"){const r=s(n[0]);n=n.filter(o=>s(o)===r)}if(c.wake===!1){const r=g?n.find(f=>f.provider==="embedded"):null;if(r)return $(e,{model:s(r)},t);const o=L(e);if(o)return $(e,o,t)}const a=[];let v=null;for(const r of n){if(r.provider==="none")break;let o;if(r.provider==="embedded"){if(!g)continue;o=await $(e,{model:s(r)},t)}else{if(!(typeof r.url=="string"&&/^https?:\/\//.test(r.url)&&typeof r.adapter=="string"))continue;o=await T(e,r,t)}if(o.status===200)return a.length?{status:200,body:{...o.body,fellBackFrom:a}}:o;if(o.status===400||o.status===404)return o;a.push(r.service||r.id||(r.provider==="embedded"?"in-process":r.url)),v=o}return v||i(404,"no_provider",`no ${e} provider answers here`)}async function T(e,t,n){const c=x[e];let s;try{s=c.request(n)}catch(l){return i(400,"invalid_request",l.message)}if(s.model&&t.model&&s.model!==t.model)return i(404,"model_not_found",`${e}: model ${s.model} is not served here (${t.model} is)`);const a=q[e],v=c.chars(s),r=D(a.stats.stats(),v,s.budgetMs);if(r)return{status:503,body:r};let o;try{o=K(t.adapter,{...s,model:s.model||t.model||void 0})}catch(l){return i(500,"bad_adapter",l.message)}const f=`${t.url.replace(/\/+$/,"")}${o.route}`,_=()=>h(f,{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...t.token?{authorization:`Bearer ${t.token}`}:{}},body:JSON.stringify(o.body),signal:AbortSignal.timeout(s.budgetMs?Math.max(s.budgetMs*2,5e3):a.stats.stats().calls?ee:Z)});if(s.wake===!1){const l=L(e);if(l)return $(e,l,n);if(t.service&&typeof A=="function"&&A(t.service))return i(503,"provider_asleep",`${e}: the ${t.service} container is asleep and this call does not wake it — carry on without it`)}const m=!!(t.service&&typeof y=="function");if(m){const l=await y(t.service).catch(O=>({ok:!1,error:O.message}));if(!l?.ok)return a.error=l?.error||"could not start",a.last=d(),i(503,"provider_unavailable",`${e}: the ${t.service} container could not be started — ${a.error}`)}const F=d();let b;try{b=await _()}catch(l){const O=m?await y(t.service,{force:!0}).catch(()=>null):null;try{if(!O?.ok)throw l;b=await _()}catch(P){return a.error=P.message,a.last=d(),i(503,"provider_unavailable",`${e}: ${t.service?`the ${t.service} container`:t.url} did not answer — ${P.message}`)}}let p;try{p=await b.json()}catch{p=null}if(!b.ok)return a.error=`HTTP ${b.status}`,a.last=d(),i(502,"provider_error",`${e}: the provider answered ${b.status}${p?.detail?` — ${typeof p.detail=="string"?p.detail:JSON.stringify(p.detail)}`:p?.error?` — ${typeof p.error=="string"?p.error:p.error.message||""}`:""}`);const I=d()-F;let k;try{const l=Q(t.adapter,p,s);k={...l,model:t.model||l.model||t.adapter,...l.model&&t.model&&l.model!==t.model?{providerModel:l.model}:{},ms:I,...e==="decide"?{calibrated:t.calibrated===!0}:{}},c.response(k,s)}catch(l){return a.error=l.message,a.last=d(),i(502,"bad_shape",`${e}: the provider's answer did not fit the contract — ${l.message}`)}return a.stats.record(I,v),a.error=null,a.last=d(),{status:200,body:k}}function C(e){const t=w(e),n=q[e],c=n.stats.stats();if(!t){const s=E(e);if(!s)return null;const a=g.health(e,s.model);return{id:e,route:j[e],models:[s.model],default:s.model,requirements:{egress:"none"},...e==="decide"?{calibrated:!1}:{},stats:c,runtime:{...a,name:"embedded",model:s.model,threads:g.threads}}}return{id:e,route:j[e],models:t.model?[t.model]:[],...t.model?{default:t.model}:{},requirements:{egress:/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(t.url)?"none":"trusted"},...e==="decide"?{calibrated:t.calibrated===!0}:{},stats:c,runtime:{state:n.error?"down":c.calls?"ready":"idle",name:t.service?"container":"external",adapter:t.adapter,...t.service?{service:t.service}:{},url:t.url,...n.error?{error:n.error}:{}}}}return{call:B,entry:C,stats:e=>q[e]?.stats.stats()||{calls:0},capabilities:M}}export{le as createCapabilityProxy};
@@ -1 +1 @@
1
- import{patchApis as B,viewApis as I}from"./retrieval/search-apis.js";import{writeFileSync as $,mkdirSync as M,chmodSync as X}from"node:fs";import{join as G,dirname as U}from"node:path";import q from"node:os";import{usage as F}from"./freegate.js";import{applyFusionsPatch as J}from"./fusions.js";import{EMBEDDED_MODELS as K,EMBEDDED_IDS as O,isEmbeddedModel as W}from"./embedded-models.js";import{capabilityList as w,isProviderList as _,listProblems as Y,primaryProvider as z,storedShape as v}from"./capability-config.js";import{normalizeRegistries as Z,REGISTRY_KINDS as Q}from"@chatpanel/events/registries.js";import{assertEndpointUrl as x}from"@chatpanel/pii";import{normalizeGrant as N}from"@chatpanel/bridge/src/events/sandbox-policy.js";import{SANDBOX_READ_MODES as A,SANDBOX_RUNTIMES as S,parseWrapperTemplate as V}from"@chatpanel/events/sandbox-choice.js";import{sandboxUnderPolicy as k}from"@chatpanel/events/policy.js";const p=["open","allowlist","off"],T=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(o=>String(o).trim()).filter(o=>o&&o.length<1024&&!o.includes("\0")),m=e=>Object.assign(new Error(e),{code:"SHAPE"}),h=/^[A-Za-z0-9][\w.-]{0,63}$/,ee=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function re(e,{strict:o=!1}={}){const r={};if(!e||typeof e!="object"||Array.isArray(e))return r;for(const[i,n]of Object.entries(e))if(n!=null)try{if(!h.test(i))throw m(`not an agent id: ${JSON.stringify(i)}`);const t=N(n);ee(t)||(r[i]=t)}catch(t){if(o)throw m(`sandbox.agents.${i}: ${t.message}`)}return r}function y(e={},{strict:o=!1}={}){const r=e&&typeof e=="object"?e:{};if(o&&r.mode!==void 0&&!p.includes(r.mode))throw m(`sandbox.mode must be one of ${p.join(", ")} — got ${JSON.stringify(r.mode)}`);const i=p.includes(r.mode)?r.mode:"open";if(o&&r.reads!==void 0&&!A.includes(r.reads))throw m(`sandbox.reads must be one of ${A.join(", ")} — got ${JSON.stringify(r.reads)}`);const n=A.includes(r.reads)?r.reads:A[0];if(o&&r.required!==void 0&&typeof r.required!="boolean")throw m(`sandbox.required must be true or false — got ${JSON.stringify(r.required)}`);if(o&&r.required===!0&&r.mode==="off")throw m("the sandbox cannot be required while it is off — choose open or allowlist first");const t=r.required===!0&&i!=="off";if(o&&r.runtime!==void 0&&!S.includes(r.runtime))throw m(`sandbox.runtime must be one of ${S.join(", ")} — got ${JSON.stringify(r.runtime)}`);const s=S.includes(r.runtime)?r.runtime:"srt";let d="";if(r.command!==void 0&&String(Array.isArray(r.command)?r.command.join(""):r.command).trim())try{V(r.command),d=Array.isArray(r.command)?JSON.stringify(r.command):String(r.command).trim()}catch(l){if(o)throw m(`sandbox.command: ${l.message.replace(/^sandbox command: /,"")}`);d=""}const a=typeof r.image=="string"&&/^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,254}$/.test(r.image.trim())?r.image.trim():"";if(o&&r.image!==void 0&&String(r.image).trim()&&!a)throw m("sandbox.image must be an image reference (registry/name:tag)");const u=["podman","docker"].includes(r.engine)?r.engine:"";if(o&&s==="command"&&!d)throw m("the sandbox command is empty — name your sandbox tool, with {cmd} where the command goes");if(o&&s==="container"&&!a)throw m("a container needs an image — name the image the agents run in");const{hosts:f}=N({hosts:r.hosts??[]}),b=re(r.agents,{strict:o});return{mode:i,reads:n,required:t,runtime:s,command:d,image:a,engine:u,hosts:f,write:T(r.write),denyRead:T(r.denyRead),...Object.keys(b).length?{agents:b}:{}}}const oe=["off","0","false"],g=e=>String(e||"").split(",").map(o=>o.trim()).filter(Boolean),D=(...e)=>[...new Set(e.flat())];function c(e=process.env){const o=String(e.CHATPANEL_SANDBOX_READS??"").trim().toLowerCase();return A.includes(o)?o:""}function E(e=process.env){const o=String(e.CHATPANEL_SANDBOX??"").trim().toLowerCase();return o?oe.includes(o)?{mode:"off"}:p.includes(o)?{mode:o}:{unknown:o}:{}}function ce(e,o=process.env){const r=[],i=e?.sandbox&&typeof e.sandbox=="object"?e.sandbox:{};i.mode!==void 0&&!p.includes(i.mode)&&r.push(`sandbox.mode ${JSON.stringify(i.mode)} in the config is not one of ${p.join(", ")} — the sandbox stays ON, in "open" mode`);for(const[a,u]of Object.entries(i.agents&&typeof i.agents=="object"?i.agents:{}))try{if(!h.test(a))throw new Error("not an agent id");N(u)}catch(f){r.push(`sandbox.agents.${a} in the config is not valid and is ignored — ${f.message}`)}const n=E(o),t=y(i).mode;n.unknown&&r.push(`CHATPANEL_SANDBOX="${n.unknown}" in this process's environment is not one of ${p.join(", ")} — ignored; the config's "${t}" applies`),n.mode&&n.mode!==t&&r.push(`the sandbox mode is "${n.mode}" — from CHATPANEL_SANDBOX in this process's environment, which wins over the config's "${t}"; Settings › Runtime cannot change it while that variable is set`);const s=c(o),d=y(i).reads;return s&&s!==d&&r.push(`what agents may read is "${s}" — from CHATPANEL_SANDBOX_READS in this process's environment, which wins over the config's "${d}"; Settings › Runtime cannot change it while that variable is set`),r}function Ee(e,o=process.env,r=null){const i=y(e?.sandbox),{sandbox:n}=k(i,r);Array.isArray(n.command)&&(n.command=JSON.stringify(n.command));const t=E(o);let s={};try{const a=JSON.parse(o.CHATPANEL_SANDBOX_AGENTS||"{}");a&&typeof a=="object"&&!Array.isArray(a)&&(s=a)}catch{}const d={...s,...n.agents||{}};return{CHATPANEL_SANDBOX:r?.sandbox?.mode||t.mode||n.mode,CHATPANEL_SANDBOX_RUNTIME:n.runtime,CHATPANEL_SANDBOX_COMMAND:n.command||"",CHATPANEL_SANDBOX_IMAGE:n.image||"",CHATPANEL_SANDBOX_ENGINE:n.engine||"",CHATPANEL_SANDBOX_READS:r?.sandbox?.reads||c(o)||n.reads,CHATPANEL_SANDBOX_REQUIRED:n.required==="policy"?"policy":String(o.CHATPANEL_SANDBOX_REQUIRED||"")||(n.required?"on":""),CHATPANEL_SANDBOX_ALLOW_HOSTS:D(n.hosts,g(o.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:D(n.write,g(o.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:D(n.denyRead,g(o.CHATPANEL_SANDBOX_DENY_READ)).join(","),...Object.keys(d).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(d)}:{}}}function L(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||G(q.homedir(),".chatpanel","gateway.config.json")}function we(e){const o=e?.registries||{},r={};for(const[i,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])o[i]&&(r[n]=o[i]);return r}function P(e,o,r){r?e.capabilities[o]=r:delete e.capabilities[o]}function R(e,o,r,i){if(r.provider==="embedded")return O.includes(e)&&r.model!=null?(W(e,r.model)||i(`capabilities.${e}.model must be one of ${K[e].map(t=>t.id).join(", ")}`),{provider:"embedded",model:r.model}):{provider:"embedded"};if(r.provider==="none"&&O.includes(e))return{provider:"none"};const n={...o};if("url"in r){const t=String(r.url||"").trim();t&&x(t);const s=d=>{try{return new URL(d).origin}catch{return d}};o.url&&t&&s(o.url)!==s(t)&&typeof r.token!="string"&&delete n.token,n.url=t}return typeof r.adapter=="string"&&/^[a-z-]+$/.test(r.adapter)&&(n.adapter=r.adapter),typeof r.model=="string"&&(n.model=r.model.trim()),typeof r.token=="string"&&(n.token=r.token),typeof r.calibrated=="boolean"&&(n.calibrated=r.calibrated),typeof r.redact=="boolean"&&(n.redact=r.redact),n.url?(n.provider="remote",delete n.service,delete n.hasToken,n):null}const j=e=>{const{token:o,...r}=e||{};return{...r,hasToken:!!o}};function xe(e,o=L()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&o===L({}))throw new Error(`refusing to persist the real gateway config (${o}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);M(U(o),{recursive:!0,mode:448});const r={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link,tls:e.tls};$(o,JSON.stringify(r,null,2),{mode:384});try{X(o,384)}catch{}}function Ne(e,{proUnlocked:o=!1,policy:r=null}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:n,...t}=i;return{...t,hasKey:!!n}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:i,...n}=e.redaction?.detection||{backend:"off"};return n})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:(()=>{const{sandbox:i,locked:n}=k(y(e.sandbox),r);return Array.isArray(i.command)&&(i.command=JSON.stringify(i.command)),{...i,...E().mode?{envMode:E().mode}:{},...c()?{envReads:c()}:{},...n.length?{locked:n,lockedBy:r?.org?.name||"your organisation"}:{}}})(),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0},apis:I(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,n])=>[i,_(n)?{...n,providers:n.providers.map(j)}:j(n)])),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:o,hasToken:!!e.pro?.entitlementToken,free:F(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function Se(e,o){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=o,e.ner.autostart=!0,e.ner}function ie(e,o={}){if(!e||e.type!=="api")return!1;let r;try{r=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(r.hostname),n=Number(r.port)||(r.protocol==="https:"?443:80);return i&&n===(Number(o.port)||4320)}const C=["default","acceptEdits","bypassPermissions"];function ge(e,o={}){const r=e?.bridge||{};return{...C.includes(r.permissionMode)&&r.permissionMode!=="default"?{permissionMode:r.permissionMode}:{},...typeof r.workingDir=="string"&&r.workingDir.trim()?{workingDir:r.workingDir.trim()}:{},...o}}function De(e,o={}){if((o.backend==="bridge"||o.backend==="api")&&(e.backend=o.backend),Array.isArray(o.destinations)){const r=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=o.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const n=ie(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:r.get(i.id)?.apiKey;s&&(n.apiKey=s)}const t=typeof i.service=="string"&&i.service?i.service:r.get(i.id)?.service;return t&&(n.service=t),(i.fromEndpoint===!0||i.fromEndpoint===void 0&&r.get(i.id)?.fromEndpoint===!0)&&(n.fromEndpoint=!0),n})}if(o.bridge&&typeof o.bridge=="object"&&(typeof o.bridge.url=="string"&&(e.bridge.url=o.bridge.url),typeof o.bridge.agent=="string"&&(e.bridge.agent=o.bridge.agent),C.includes(o.bridge.permissionMode)&&(e.bridge.permissionMode=o.bridge.permissionMode),typeof o.bridge.workingDir=="string"&&(e.bridge.workingDir=o.bridge.workingDir.trim().slice(0,1024)),typeof o.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=o.bridge.openAgentLane)),Array.isArray(o.allowedExtensionIds)&&(e.allowedExtensionIds=o.allowedExtensionIds.map(r=>String(r).trim()).filter(r=>/^[a-p]{32}$/.test(r))),o.upstreams&&typeof o.upstreams=="object")for(const r of["openai","anthropic"]){const i=o.upstreams[r];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[r]={...e.upstreams[r],baseUrl:i.baseUrl.trim()})}if(o.redaction&&typeof o.redaction=="object"){const r=o.redaction;(r.tier==="basic"||r.tier==="full")&&(e.redaction.tier=r.tier),"redactSystem"in r&&(e.redaction.redactSystem=!!r.redactSystem),Array.isArray(r.dictionary)&&(e.redaction.dictionary=r.dictionary),r.detection&&typeof r.detection=="object"&&(e.redaction.detection=r.detection)}if(Array.isArray(o.allowedOrigins)&&(e.allowedOrigins=o.allowedOrigins),o.sandbox&&typeof o.sandbox=="object"){const r=y(e.sandbox),i={...r,...o.sandbox};o.sandbox.agents&&typeof o.sandbox.agents=="object"&&!Array.isArray(o.sandbox.agents)&&(i.agents={...r.agents||{},...o.sandbox.agents}),e.sandbox=y(i,{strict:!0})}if(o.pro&&typeof o.pro=="object"&&typeof o.pro.entitlementToken=="string"&&(e.pro.entitlementToken=o.pro.entitlementToken),o.stt&&typeof o.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in o.stt&&(e.stt.enabled=!!o.stt.enabled),"allowDownload"in o.stt&&(e.stt.allowDownload=!!o.stt.allowDownload)),o.read&&typeof o.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},o.read.remote&&typeof o.read.remote=="object"){if("url"in o.read.remote){const r=String(o.read.remote.url||"").trim();r&&x(r),e.read.remote.url=r}typeof o.read.remote.key=="string"&&(e.read.remote.key=o.read.remote.key)}["defuddle","text","remote"].includes(o.read.provider)&&(e.read.provider=o.read.provider==="remote"&&!e.read.remote.url?e.read.provider:o.read.provider)}if(o.registries&&typeof o.registries=="object"){const r=Z(o.registries),i={...e.registries||{}};for(const n of Q)n in o.registries&&(r[n]?i[n]=r[n]:delete i[n]);e.registries=i}if(o.search&&typeof o.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const r=o.search.searxng;if(r&&typeof r=="object"){if("url"in r){const i=String(r.url||"").trim();i&&x(i),e.search.searxng.url=i}typeof r.token=="string"&&(e.search.searxng.token=r.token),typeof r.engines=="string"&&(e.search.searxng.engines=r.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(r.safesearch)&&(e.search.searxng.safesearch=r.safesearch)}"apis"in o.search&&(e.search.apis=B(e.search.apis,o.search.apis)),["auto","serp","searxng"].includes(o.search.provider)&&(e.search.provider=o.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:o.search.provider)}if("fusions"in o){const r=J(e,o.fusions);if(r){const i=new Error(r);throw i.code="SHAPE",i}}if(o.capabilities&&typeof o.capabilities=="object"){e.capabilities=e.capabilities||{};const r=i=>{const n=new Error(i);throw n.code="SHAPE",n};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in o.capabilities))continue;const n=o.capabilities[i];if(n===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!(!n||typeof n!="object")){if(_(n)){const t=Y(i,n);t.length&&r(t[0]);const s=w(e.capabilities[i],i).providers,d=[];for(const a of n.providers){if(!a||typeof a!="object")continue;if(typeof a.service=="string"&&a.service){const l=s.find(H=>H.service===a.service);l&&d.push(l);continue}const u=l=>{try{return new URL(l).origin}catch{return null}},f=(typeof a.id=="string"?s.find(l=>l.id===a.id):null)||(typeof a.url=="string"&&u(a.url)?s.find(l=>!l.id&&!l.service&&u(l.url)===u(a.url)):null)||{},b=R(i,f,a,r);b&&d.push(typeof a.id=="string"?{...b,id:a.id}:b)}P(e,i,v({mode:n.mode??w(e.capabilities[i],i).mode,providers:d},i))}else{const t=w(e.capabilities[i],i),s=R(i,t.providers[0]||{},n,r);P(e,i,v({mode:t.mode,providers:s?[s,...t.providers.slice(1)]:t.providers.slice(1)},i))}if(i==="detect"){const t=z(e.capabilities[i],i);t?.url&&t.provider==="remote"?(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:t.url,...t.token?{apiKey:t.token}:{}}):e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"})}}}}if(typeof o.logRequests=="boolean"&&(e.logRequests=o.logRequests),["off","types","values"].includes(o.logDetail)&&(e.logDetail=o.logDetail),o.tools&&typeof o.tools=="object"){e.tools=e.tools||{},"autoNarrow"in o.tools&&(e.tools.autoNarrow=!!o.tools.autoNarrow),"narrowAll"in o.tools&&(e.tools.narrowAll=!!o.tools.narrowAll),(o.tools.toolData==="real"||o.tools.toolData==="redactRemote")&&(e.tools.toolData=o.tools.toolData);const r=Number(o.tools.maxPerTurn);Number.isFinite(r)&&r>=1&&(e.tools.maxPerTurn=Math.floor(r))}return e}export{C as PERMISSION_MODES,p as SANDBOX_MODES,De as applyConfigPatch,Se as applyNerModelSelection,ge as bridgeAgentOptions,L as configPath,ie as isSelfDestination,y as normalizeSandboxConfig,xe as persistConfig,Ne as publicConfig,we as registryChildEnv,Ee as sandboxEnvFor,E as sandboxModeFromEnv,ce as sandboxProblems,c as sandboxReadsFromEnv};
1
+ import{patchApis as $,viewApis as H}from"./retrieval/search-apis.js";import{writeFileSync as B,mkdirSync as M,chmodSync as X}from"node:fs";import{join as G,dirname as U}from"node:path";import q from"node:os";import{usage as F}from"./freegate.js";import{applyFusionsPatch as J}from"./fusions.js";import{EMBEDDED_MODELS as z,EMBEDDED_IDS as D,isEmbeddedModel as K}from"./embedded-models.js";import{capabilityList as g,isProviderList as O,listProblems as W,primaryProvider as Y,storedShape as _}from"./capability-config.js";import{normalizeRegistries as Z,REGISTRY_KINDS as Q}from"@chatpanel/events/registries.js";import{assertEndpointUrl as E}from"@chatpanel/pii";import{normalizeGrant as x}from"@chatpanel/bridge/src/events/sandbox-policy.js";import{SANDBOX_READ_MODES as A,SANDBOX_RUNTIMES as N,parseWrapperTemplate as V}from"@chatpanel/events/sandbox-choice.js";import{sandboxUnderPolicy as k}from"@chatpanel/events/policy.js";const p=["open","allowlist","off"],T=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0")),m=e=>Object.assign(new Error(e),{code:"SHAPE"}),L=/^[A-Za-z0-9][\w.-]{0,63}$/,ee=e=>!e.hosts.length&&!e.write.length&&!e.outside&&!e.signIn;function oe(e,{strict:r=!1}={}){const o={};if(!e||typeof e!="object"||Array.isArray(e))return o;for(const[i,t]of Object.entries(e))if(t!=null)try{if(!L.test(i))throw m(`not an agent id: ${JSON.stringify(i)}`);const n=x(t);ee(n)||(o[i]=n)}catch(n){if(r)throw m(`sandbox.agents.${i}: ${n.message}`)}return o}function f(e={},{strict:r=!1}={}){const o=e&&typeof e=="object"?e:{};if(r&&o.mode!==void 0&&!p.includes(o.mode))throw m(`sandbox.mode must be one of ${p.join(", ")} — got ${JSON.stringify(o.mode)}`);const i=p.includes(o.mode)?o.mode:"open";if(r&&o.reads!==void 0&&!A.includes(o.reads))throw m(`sandbox.reads must be one of ${A.join(", ")} — got ${JSON.stringify(o.reads)}`);const t=A.includes(o.reads)?o.reads:A[0];if(r&&o.required!==void 0&&typeof o.required!="boolean")throw m(`sandbox.required must be true or false — got ${JSON.stringify(o.required)}`);if(r&&o.required===!0&&o.mode==="off")throw m("the sandbox cannot be required while it is off — choose open or allowlist first");const n=o.required===!0&&i!=="off";if(r&&o.runtime!==void 0&&!N.includes(o.runtime))throw m(`sandbox.runtime must be one of ${N.join(", ")} — got ${JSON.stringify(o.runtime)}`);const s=N.includes(o.runtime)?o.runtime:"srt";let d="";if(o.command!==void 0&&String(Array.isArray(o.command)?o.command.join(""):o.command).trim())try{V(o.command),d=Array.isArray(o.command)?JSON.stringify(o.command):String(o.command).trim()}catch(l){if(r)throw m(`sandbox.command: ${l.message.replace(/^sandbox command: /,"")}`);d=""}const a=typeof o.image=="string"&&/^[A-Za-z0-9][A-Za-z0-9._/:@-]{0,254}$/.test(o.image.trim())?o.image.trim():"";if(r&&o.image!==void 0&&String(o.image).trim()&&!a)throw m("sandbox.image must be an image reference (registry/name:tag)");const u=["podman","docker"].includes(o.engine)?o.engine:"";if(r&&s==="command"&&!d)throw m("the sandbox command is empty — name your sandbox tool, with {cmd} where the command goes");if(r&&s==="container"&&!a)throw m("a container needs an image — name the image the agents run in");const{hosts:y}=x({hosts:o.hosts??[]}),b=oe(o.agents,{strict:r});return{mode:i,reads:t,required:n,runtime:s,command:d,image:a,engine:u,hosts:y,write:T(o.write),denyRead:T(o.denyRead),...Object.keys(b).length?{agents:b}:{}}}const re=["off","0","false"],S=e=>String(e||"").split(",").map(r=>r.trim()).filter(Boolean),v=(...e)=>[...new Set(e.flat())];function c(e=process.env){const r=String(e.CHATPANEL_SANDBOX_READS??"").trim().toLowerCase();return A.includes(r)?r:""}function w(e=process.env){const r=String(e.CHATPANEL_SANDBOX??"").trim().toLowerCase();return r?re.includes(r)?{mode:"off"}:p.includes(r)?{mode:r}:{unknown:r}:{}}function ce(e,r=process.env){const o=[],i=e?.sandbox&&typeof e.sandbox=="object"?e.sandbox:{};i.mode!==void 0&&!p.includes(i.mode)&&o.push(`sandbox.mode ${JSON.stringify(i.mode)} in the config is not one of ${p.join(", ")} — the sandbox stays ON, in "open" mode`);for(const[a,u]of Object.entries(i.agents&&typeof i.agents=="object"?i.agents:{}))try{if(!L.test(a))throw new Error("not an agent id");x(u)}catch(y){o.push(`sandbox.agents.${a} in the config is not valid and is ignored — ${y.message}`)}const t=w(r),n=f(i).mode;t.unknown&&o.push(`CHATPANEL_SANDBOX="${t.unknown}" in this process's environment is not one of ${p.join(", ")} — ignored; the config's "${n}" applies`),t.mode&&t.mode!==n&&o.push(`the sandbox mode is "${t.mode}" — from CHATPANEL_SANDBOX in this process's environment, which wins over the config's "${n}"; Settings › Runtime cannot change it while that variable is set`);const s=c(r),d=f(i).reads;return s&&s!==d&&o.push(`what agents may read is "${s}" — from CHATPANEL_SANDBOX_READS in this process's environment, which wins over the config's "${d}"; Settings › Runtime cannot change it while that variable is set`),o}function we(e,r=process.env,o=null){const i=f(e?.sandbox),{sandbox:t}=k(i,o);Array.isArray(t.command)&&(t.command=JSON.stringify(t.command));const n=w(r);let s={};try{const a=JSON.parse(r.CHATPANEL_SANDBOX_AGENTS||"{}");a&&typeof a=="object"&&!Array.isArray(a)&&(s=a)}catch{}const d={...s,...t.agents||{}};return{CHATPANEL_SANDBOX:o?.sandbox?.mode||n.mode||t.mode,CHATPANEL_SANDBOX_RUNTIME:t.runtime,CHATPANEL_SANDBOX_COMMAND:t.command||"",CHATPANEL_SANDBOX_IMAGE:t.image||"",CHATPANEL_SANDBOX_ENGINE:t.engine||"",CHATPANEL_SANDBOX_READS:o?.sandbox?.reads||c(r)||t.reads,CHATPANEL_SANDBOX_REQUIRED:t.required==="policy"?"policy":String(r.CHATPANEL_SANDBOX_REQUIRED||"")||(t.required?"on":""),CHATPANEL_SANDBOX_ALLOW_HOSTS:v(t.hosts,S(r.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:v(t.write,S(r.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:v(t.denyRead,S(r.CHATPANEL_SANDBOX_DENY_READ)).join(","),...Object.keys(d).length?{CHATPANEL_SANDBOX_AGENTS:JSON.stringify(d)}:{}}}function h(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||G(q.homedir(),".chatpanel","gateway.config.json")}function ge(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function P(e,r,o){o?e.capabilities[r]=o:delete e.capabilities[r]}function R(e,r,o,i){if(o.provider==="endpoint")return(typeof o.endpoint!="string"||!/^[\w.:-]{1,80}$/.test(o.endpoint))&&i(`capabilities.${e}: an endpoint provider names its endpoint`),(typeof o.model!="string"||!o.model.trim()||o.model.length>200)&&i(`capabilities.${e}: an endpoint provider names its model`),(typeof o.adapter!="string"||!/^[a-z-]{2,40}$/.test(o.adapter))&&i(`capabilities.${e}: an endpoint provider names its adapter`),{provider:"endpoint",endpoint:o.endpoint,model:o.model.trim(),adapter:o.adapter,...typeof o.id=="string"&&o.id?{id:o.id}:{},...typeof o.label=="string"&&o.label.length<=160?{label:o.label}:{},...typeof o.redact=="boolean"?{redact:o.redact}:{},...typeof o.voice=="string"&&/^[A-Za-z0-9_-]{1,64}$/.test(o.voice)?{voice:o.voice}:{}};if(o.provider==="embedded")return D.includes(e)&&o.model!=null?(K(e,o.model)||i(`capabilities.${e}.model must be one of ${z[e].map(n=>n.id).join(", ")}`),{provider:"embedded",model:o.model}):{provider:"embedded"};if(o.provider==="none"&&D.includes(e))return{provider:"none"};const t={...r};if("url"in o){const n=String(o.url||"").trim();n&&E(n);const s=d=>{try{return new URL(d).origin}catch{return d}};r.url&&n&&s(r.url)!==s(n)&&typeof o.token!="string"&&delete t.token,t.url=n}return typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(t.adapter=o.adapter),typeof o.model=="string"&&(t.model=o.model.trim()),typeof o.token=="string"&&(t.token=o.token),typeof o.calibrated=="boolean"&&(t.calibrated=o.calibrated),typeof o.redact=="boolean"&&(t.redact=o.redact),t.url?(t.provider="remote",delete t.service,delete t.hasToken,t):null}const j=e=>{const{token:r,...o}=e||{};return{...o,hasToken:!!r}};function Ee(e,r=h()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===h({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);M(U(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp,link:e.link,tls:e.tls};B(r,JSON.stringify(o,null,2),{mode:384});try{X(r,384)}catch{}}function xe(e,{proUnlocked:r=!1,policy:o=null}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(i=>{const{apiKey:t,...n}=i;return{...n,hasKey:!!t}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:i,...t}=e.redaction?.detection||{backend:"off"};return t})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:(()=>{const{sandbox:i,locked:t}=k(f(e.sandbox),o);return Array.isArray(i.command)&&(i.command=JSON.stringify(i.command)),{...i,...w().mode?{envMode:w().mode}:{},...c()?{envReads:c()}:{},...t.length?{locked:t,lockedBy:o?.org?.name||"your organisation"}:{}}})(),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0},apis:H(e)},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([i,t])=>[i,O(t)?{...t,providers:t.providers.map(j)}:j(t)])),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:F(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function Ne(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function ie(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const I=["default","acceptEdits","bypassPermissions"];function Se(e,r={}){const o=e?.bridge||{};return{...I.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function ve(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=ie(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(d=>typeof d=="string"&&d):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const d=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;d&&(t.apiKey=d)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;n&&(t.service=n),(i.fromEndpoint===!0||i.fromEndpoint===void 0&&o.get(i.id)?.fromEndpoint===!0)&&(t.fromEndpoint=!0);const s=typeof i.endpointId=="string"&&/^[\w.:-]{1,80}$/.test(i.endpointId)?i.endpointId:o.get(i.id)?.endpointId;return s&&(t.endpointId=s),t}).filter((i,t,n)=>!i.endpointId||n.findIndex(s=>s.endpointId===i.endpointId)===t)}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),I.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"){const o=f(e.sandbox),i={...o,...r.sandbox};r.sandbox.agents&&typeof r.sandbox.agents=="object"&&!Array.isArray(r.sandbox.agents)&&(i.agents={...o.agents||{},...r.sandbox.agents}),e.sandbox=f(i,{strict:!0})}if(r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&E(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=Z(r.registries),i={...e.registries||{}};for(const t of Q)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&E(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}"apis"in r.search&&(e.search.apis=$(e.search.apis,r.search.apis)),["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=J(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};const o=i=>{const t=new Error(i);throw t.code="SHAPE",t};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const t=r.capabilities[i];if(t===null){delete e.capabilities[i],i==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!(!t||typeof t!="object")){if(O(t)){const n=W(i,t);n.length&&o(n[0]);const s=g(e.capabilities[i],i).providers,d=[];for(const a of t.providers){if(!a||typeof a!="object")continue;if(typeof a.service=="string"&&a.service){const l=s.find(C=>C.service===a.service);l&&d.push(l);continue}const u=l=>{try{return new URL(l).origin}catch{return null}},y=(typeof a.id=="string"?s.find(l=>l.id===a.id):null)||(typeof a.url=="string"&&u(a.url)?s.find(l=>!l.id&&!l.service&&u(l.url)===u(a.url)):null)||{},b=R(i,y,a,o);b&&d.push(typeof a.id=="string"?{...b,id:a.id}:b)}P(e,i,_({mode:t.mode??g(e.capabilities[i],i).mode,providers:d},i))}else{const n=g(e.capabilities[i],i),s=R(i,n.providers[0]||{},t,o);P(e,i,_({mode:n.mode,providers:s?[s,...n.providers.slice(1)]:n.providers.slice(1)},i))}if(i==="detect"){const n=Y(e.capabilities[i],i);n?.url&&n.provider==="remote"?(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}}):e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"})}}}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{I as PERMISSION_MODES,p as SANDBOX_MODES,ve as applyConfigPatch,Ne as applyNerModelSelection,Se as bridgeAgentOptions,h as configPath,ie as isSelfDestination,f as normalizeSandboxConfig,Ee as persistConfig,xe as publicConfig,ge as registryChildEnv,we as sandboxEnvFor,w as sandboxModeFromEnv,ce as sandboxProblems,c as sandboxReadsFromEnv};
package/src/egress.js CHANGED
@@ -1,2 +1,2 @@
1
- import{confinedLine as $}from"./confine.js";import{capabilityList as S}from"./capability-config.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as L}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const P=()=>new Date().toISOString();function y(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:g(t,{allowLoopback:!1,allowPrivate:!1})&&!g(t,{allowLoopback:!0,allowPrivate:!0})};function A({clock:e=P}={}){const t=new Map;return{record(a){const r=y(a);if(!r||!r.host)return;const u=`${r.scheme}://${r.host}:${r.port}`,s=e(),c=t.get(u);if(c){c.count+=1,c.lastAt=s;return}t.set(u,{host:r.host,port:r.port,scheme:r.scheme,local:w(r.host),count:1,firstAt:s,lastAt:s})},snapshot(){return[...t.values()].sort((a,r)=>a.local===r.local?r.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let b=null;function O(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=A();let r=t;a.setGate=l=>{r=l},a.blocked=[];const u=l=>{let i=null;try{i=y(l),a.record(l)}catch{}if(!r||!i?.host)return null;let h=!0;try{h=r(`${i.scheme}://${i.host}:${i.port}`,{local:w(i.host)})}catch{h=!0}if(h)return null;const o=`${i.host}:${i.port}`;a.blocked.includes(o)||a.blocked.push(o);const n=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return n.code="EGRESS_POLICY",n},s=e.fetch;typeof s=="function"&&(e.fetch=function(i,h){const o=u(i);return o?Promise.reject(o):s.call(this,i,h)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(l,i,h){const o=u(i[0]);if(o)throw o;return Reflect.construct(l,i,h)}})),e.__chatpanelEgress=a,e===globalThis&&(b=a),a}function x(){return b||(globalThis.__chatpanelEgress??null)}function f(e){try{return new URL(e).host}catch{return String(e||"")}}function T(e={},t=process.env,a=process.platform,r=process.arch){const u=[],s=(n,p,{when:d="always",off:m=null,local:v=!1,data:k=""}={})=>{n&&u.push({host:n,purpose:p,when:d,off:m,local:v,data:k})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),s("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),e.runtime?.services?.llama?.build!=="system"&&(s("api.github.com","llama.cpp for the Runtime: which files Unsloth’s release has, and their SHA-256",{when:"Start, Install or Update of llama.cpp when its build is not here yet",off:'runtime.services.llama.build = "system" — the llama-server on PATH (Homebrew’s, or your own)',data:"nothing — a read of the release (github.com/unslothai/llama.cpp)"}),s("github.com","llama.cpp for the Runtime: Unsloth’s prebuilt llama-server for this machine (~13 MB on a Mac)",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"}),s("release-assets.githubusercontent.com","where github.com redirects that download — GitHub’s own file host",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"})),s("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),t.CHATPANEL_ORT_DIR||s("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),a==="darwin"&&r==="arm64"&&s("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const c=e.link?.enabled===!1?null:L(e.link||{}).relay;if(c){const n=new URL(c).host;s(n,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const l=e.search?.searxng?.url||"";if(l){let n=l;try{n=new URL(l).host}catch{}s(n,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(n)})}if(e.search?.provider!=="searxng"){s("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),s("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),s("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const n of E(e).filter(p=>p.kind==="api"&&p.enabled!==!1))s(n.api.host,`web search: ${n.api.name} (search API${n.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${n.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let n=e.read.remote.url;try{n=new URL(e.read.remote.url).host}catch{}s(n,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(n)})}const i={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions (ElevenLabs: /speech-to-text)",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[n,p]of Object.entries(i))for(const d of S(e.capabilities?.[n],n).providers){if(!d?.url||d.provider==="embedded")continue;let m=d.url;try{m=new URL(d.url).host}catch{}s(m,`${p.what}${d.service?` (the ${d.service} container, started under Settings › Runtime)`:` (${d.adapter} at the address you configured)`}`,{when:`a client calls /v1/${n}`,off:d.service?`stop the ${d.service} service under Settings › Runtime`:`capabilities.${n} = null`,data:`${p.data}${d.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(m)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[n,p]of Object.entries(e.upstreams||{}))p?.baseUrl&&s(f(p.baseUrl),`model upstream "${n}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n}`,off:`upstreams.${n}.baseUrl`,local:w(f(p.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const n of e.destinations||[])n?.baseUrl&&s(f(n.baseUrl),`destination "${n.id||n.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n.id||"it"}`,off:"destinations[]",local:w(f(n.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(f(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(f(e.ner.url).split(":")[0]),data:"the text being redacted"});const h=e.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const n=h.remote?.baseUrl?f(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(n,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}a==="darwin"&&e.runtime?.heatwatch!==!1&&s("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const o=e.bridge?.url||"http://127.0.0.1:4319";return s(f(o),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),u}function _(e,{ledger:t=x(),version:a="",startedAt:r=null,env:u=process.env,managed:s=null,certificates:c=null,linkPartners:l=null,confined:i=null}={}){const h=T(e,u);for(const o of l||[])!o.host||o.route!=="link"&&o.route!=="relay"||h.some(n=>n.host===o.host)||h.push({host:o.host,purpose:`ChatPanel Link: the relay partner "${o.partner?.name||o.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${o.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:a,since:r?new Date(r).toISOString():null,...c?{certificates:c}:{},...i?{confined:i}:{},...s?{managed:s,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:h,...l?{link:{partners:l.map(o=>({id:o.id,partner:o.partner?.name||o.name,scopes:o.scopes||[],route:o.route||null,host:o.host||null,...o.folder?{folder:o.folder}:{},pairedAt:o.pairedAt||null,lastSeen:o.lastSeen||null,online:!!o.online}))}}:{}}}function q(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const a of e.observed||[])t.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const a of e.declared||[])t.push(` ${a.local?"[local] ":""}${a.host}`),t.push(` ${a.purpose}`),t.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&t.push(` sends: ${a.data}`);if(e.certificates){const a=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(a.on?` the runtime's own list, and this computer's (${a.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${a.why?` — ${a.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(e.confined&&(t.push(""),t.push("CONFINEMENT — what this process itself can reach on this computer"),t.push(` ${$(e.confined)}`),e.confined.on&&t.push(" checked at start: home folder listed "+(e.confined.homeListed?"YES":"no")+" · home folder written "+(e.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(e.confined.fenceWritten?"YES":"no")+" · own folder written "+(e.confined.stateWritten?"yes":"NO"))),e.link){t.push(""),t.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),e.link.partners?.length||t.push(" (none — no partner can reach this gateway until you pair one)");for(const a of e.link.partners||[]){const r=a.lastSeen?new Date(a.lastSeen).toISOString():"never";t.push(` partner:${a.partner} scopes: ${a.scopes.join(", ")||"none"} agents: ${a.scopes.includes("agents")?"yes":"no"}`),t.push(` route: ${a.route||"?"}${a.host?` via ${a.host}`:""} · last seen ${r}${a.online?" (online)":""}`),a.scopes.includes("agents")&&t.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${a.folder||"its folder"}; it never answers their approval prompts`),t.push(` revoke: chatpanel-gateway link revoke ${a.id}`)}}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,a])=>a).map(([a,r])=>r===!0?a:`${a}=${r}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
1
+ import{confinedLine as $}from"./confine.js";import{capabilityList as S}from"./capability-config.js";import{searchEngines as E}from"./retrieval/search-apis.js";import{linkPaths as L}from"@chatpanel/events/link-routes.js";import{isBlockedHost as g}from"@chatpanel/pii";const P=()=>new Date().toISOString();function y(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url),a=t.protocol.replace(":","");return{host:t.hostname,port:t.port||{https:"443",wss:"443",http:"80",ws:"80"}[a]||"",scheme:a}}catch{return null}}const w=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:g(t,{allowLoopback:!1,allowPrivate:!1})&&!g(t,{allowLoopback:!0,allowPrivate:!0})};function A({clock:e=P}={}){const t=new Map;return{record(a){const r=y(a);if(!r||!r.host)return;const u=`${r.scheme}://${r.host}:${r.port}`,s=e(),c=t.get(u);if(c){c.count+=1,c.lastAt=s;return}t.set(u,{host:r.host,port:r.port,scheme:r.scheme,local:w(r.host),count:1,firstAt:s,lastAt:s})},snapshot(){return[...t.values()].sort((a,r)=>a.local===r.local?r.count-a.count:a.local?1:-1)},reset(){t.clear()}}}let b=null;function O(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const a=A();let r=t;a.setGate=l=>{r=l},a.blocked=[];const u=l=>{let i=null;try{i=y(l),a.record(l)}catch{}if(!r||!i?.host)return null;let h=!0;try{h=r(`${i.scheme}://${i.host}:${i.port}`,{local:w(i.host)})}catch{h=!0}if(h)return null;const o=`${i.host}:${i.port}`;a.blocked.includes(o)||a.blocked.push(o);const n=new Error(`egress to ${i.host} is blocked by your organisation’s policy`);return n.code="EGRESS_POLICY",n},s=e.fetch;typeof s=="function"&&(e.fetch=function(i,h){const o=u(i);return o?Promise.reject(o):s.call(this,i,h)});const c=e.WebSocket;return typeof c=="function"&&(e.WebSocket=new Proxy(c,{construct(l,i,h){const o=u(i[0]);if(o)throw o;return Reflect.construct(l,i,h)}})),e.__chatpanelEgress=a,e===globalThis&&(b=a),a}function x(){return b||(globalThis.__chatpanelEgress??null)}function f(e){try{return new URL(e).host}catch{return String(e||"")}}function T(e={},t=process.env,a=process.platform,r=process.arch){const u=[],s=(n,p,{when:d="always",off:m=null,local:v=!1,data:k=""}={})=>{n&&u.push({host:n,purpose:p,when:d,off:m,local:v,data:k})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("huggingface.co","model weights (NER, dictation, read-aloud, translation, meetings) — ChatPanel’s pinned copies in huggingface.co/ChatPanel, or the upstream repo",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id and file being downloaded"}),s("dl.chatpanel.net","model weights only when Hugging Face is failing (an outage or a network that blocks it), and the installer",{when:"a model download Hugging Face could not serve",off:"the same switches as huggingface.co",data:"the model id being downloaded"}),e.runtime?.services?.llama?.build!=="system"&&(s("api.github.com","llama.cpp for the Runtime: which files Unsloth’s release has, and their SHA-256",{when:"Start, Install or Update of llama.cpp when its build is not here yet",off:'runtime.services.llama.build = "system" — the llama-server on PATH (Homebrew’s, or your own)',data:"nothing — a read of the release (github.com/unslothai/llama.cpp)"}),s("github.com","llama.cpp for the Runtime: Unsloth’s prebuilt llama-server for this machine (~13 MB on a Mac)",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"}),s("release-assets.githubusercontent.com","where github.com redirects that download — GitHub’s own file host",{when:"the same — once per release",off:'runtime.services.llama.build = "system"',data:"nothing — the release file being downloaded"})),s("raw.githubusercontent.com","the meeting echo canceller's weights (DTLN-aec, ~7 MB, pinned commit and hashes) — only when ChatPanel’s copy on Hugging Face cannot be reached",{when:"the first meeting captured with both the microphone and what is playing",off:"stt.aec = false, or the same switches as dl.chatpanel.net",data:"the file path being downloaded"}),t.CHATPANEL_ORT_DIR||s("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),a==="darwin"&&r==="arm64"&&s("registry.npmjs.org","the Apple on-device helper, for an install that came without it (the standalone binary)",{when:"Install on the Apple on-device row, `--install` or `--fetch-apple-helper` — never when the helper is already here",off:"do not run them; the npm package and the desktop app carry the helper and never fetch it",data:"nothing — this gateway version's package and its checksum"});const c=e.link?.enabled===!1?null:L(e.link||{}).relay;if(c){const n=new URL(c).host;s(n,"ChatPanel Link: the relay a paired phone reaches this gateway through",{when:"only after a phone or a partner server is paired (Settings › Link your phone, `chatpanel-gateway link pair`), and while pairing",off:"link.enabled = false, or remove every paired device",data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"})}s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const l=e.search?.searxng?.url||"";if(l){let n=l;try{n=new URL(l).host}catch{}s(n,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(n)})}if(e.search?.provider!=="searxng"){s("www.startpage.com","web search: the built-in results-page search, one of three engines",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),s("html.duckduckgo.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"}),s("www.bing.com","web search: the built-in results-page search, one of three engines",{when:"the same as www.startpage.com",off:"the same switch as www.startpage.com",data:"the same query"});for(const n of E(e).filter(p=>p.kind==="api"&&p.enabled!==!1))s(n.api.host,`web search: ${n.api.name} (search API${n.api.needsKey?", with the key you gave it":", no key"})`,{when:"the same as www.startpage.com — one engine per search, a keyed API asked first",off:`search.apis: [{ id: "${n.api.id}", enabled: false }]`,data:"the same query"})}if(e.read?.remote?.url){let n=e.read.remote.url;try{n=new URL(e.read.remote.url).host}catch{}s(n,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(n)})}const i={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions (ElevenLabs: /speech-to-text)",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[n,p]of Object.entries(i))for(const d of S(e.capabilities?.[n],n,{destinations:e.destinations||[]}).providers){if(!d?.url||d.provider==="embedded")continue;let m=d.url;try{m=new URL(d.url).host}catch{}s(m,`${p.what}${d.service?` (the ${d.service} container, started under Settings › Runtime)`:` (${d.adapter} at the address you configured)`}`,{when:`a client calls /v1/${n}`,off:d.service?`stop the ${d.service} service under Settings › Runtime`:`capabilities.${n} = null`,data:`${p.data}${d.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(m)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[n,p]of Object.entries(e.upstreams||{}))p?.baseUrl&&s(f(p.baseUrl),`model upstream "${n}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n}`,off:`upstreams.${n}.baseUrl`,local:w(f(p.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const n of e.destinations||[])n?.baseUrl&&s(f(n.baseUrl),`destination "${n.id||n.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${n.id||"it"}`,off:"destinations[]",local:w(f(n.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(f(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:w(f(e.ner.url).split(":")[0]),data:"the text being redacted"});const h=e.tts||{};if(h.provider==="openai"||h.provider==="elevenlabs"){const n=h.remote?.baseUrl?f(h.remote.baseUrl):h.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(n,`remote read-aloud voice (${h.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:h.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}a==="darwin"&&e.runtime?.heatwatch!==!1&&s("127.0.0.1:7878","live memory: will this local model fit in what is free now? (Heatwatch, when installed)",{when:"before the Runtime starts a local model, and GET /v1/runtime/plan",off:"runtime.heatwatch = false",local:!0,data:"a number — the memory the model needs; never chat content"});const o=e.bridge?.url||"http://127.0.0.1:4319";return s(f(o),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),u}function _(e,{ledger:t=x(),version:a="",startedAt:r=null,env:u=process.env,managed:s=null,certificates:c=null,linkPartners:l=null,confined:i=null}={}){const h=T(e,u);for(const o of l||[])!o.host||o.route!=="link"&&o.route!=="relay"||h.some(n=>n.host===o.host)||h.push({host:o.host,purpose:`ChatPanel Link: the relay partner "${o.partner?.name||o.name}" reaches this gateway through`,when:"while that partner device is paired",off:`remove it: chatpanel-gateway link revoke ${o.id}`,data:"a room id, an admission token, and end-to-end encrypted frames the relay cannot read"});return{ok:!0,version:a,since:r?new Date(r).toISOString():null,...c?{certificates:c}:{},...i?{confined:i}:{},...s?{managed:s,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests and sockets. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:h,...l?{link:{partners:l.map(o=>({id:o.id,partner:o.partner?.name||o.name,scopes:o.scopes||[],route:o.route||null,host:o.host||null,...o.folder?{folder:o.folder}:{},pairedAt:o.pairedAt||null,lastSeen:o.lastSeen||null,online:!!o.online}))}}:{}}}function q(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const a of e.observed||[])t.push(` ${a.local?"[local] ":""}${a.scheme}://${a.host}:${a.port} ×${a.count} last ${a.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const a of e.declared||[])t.push(` ${a.local?"[local] ":""}${a.host}`),t.push(` ${a.purpose}`),t.push(` when: ${a.when}${a.off?` · off: ${a.off}`:""}`),a.data&&t.push(` sends: ${a.data}`);if(e.certificates){const a=e.certificates;t.push(""),t.push("CERTIFICATES — whose word is taken that a server is who it says"),t.push(a.on?` the runtime's own list, and this computer's (${a.added} added) — what a company proxy that re-signs HTTPS needs; checks stay on`:` the runtime's own list only${a.why?` — ${a.why}`:""}`),t.push(" off: tls.systemCa: false in the config, or CHATPANEL_SYSTEM_CA=off, then restart")}if(e.confined&&(t.push(""),t.push("CONFINEMENT — what this process itself can reach on this computer"),t.push(` ${$(e.confined)}`),e.confined.on&&t.push(" checked at start: home folder listed "+(e.confined.homeListed?"YES":"no")+" · home folder written "+(e.confined.homeWritten?"YES":"no")+" · sandbox runtime written "+(e.confined.fenceWritten?"YES":"no")+" · own folder written "+(e.confined.stateWritten?"yes":"NO"))),e.link){t.push(""),t.push("LINK PARTNERS — servers the owner paired to reach this gateway over ChatPanel Link"),e.link.partners?.length||t.push(" (none — no partner can reach this gateway until you pair one)");for(const a of e.link.partners||[]){const r=a.lastSeen?new Date(a.lastSeen).toISOString():"never";t.push(` partner:${a.partner} scopes: ${a.scopes.join(", ")||"none"} agents: ${a.scopes.includes("agents")?"yes":"no"}`),t.push(` route: ${a.route||"?"}${a.host?` via ${a.host}`:""} · last seen ${r}${a.online?" (online)":""}`),a.scopes.includes("agents")&&t.push(` agents run as yours do (your Coding Agents settings and sandbox), in ${a.folder||"its folder"}; it never answers their approval prompts`),t.push(` revoke: chatpanel-gateway link revoke ${a.id}`)}}return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,a])=>a).map(([a,r])=>r===!0?a:`${a}=${r}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
2
  `)}export{A as createEgressLedger,T as declaredEgress,_ as egressAudit,x as egressLedger,q as formatAudit,O as installEgressLedger};
package/src/kb.js CHANGED
@@ -1,2 +1,2 @@
1
- import{readFileSync as pe,statSync as H,readdirSync as fe,realpathSync as J}from"node:fs";import{join as he,basename as L,extname as Q,resolve as ge}from"node:path";import me from"node:os";import{createKb as be,addDocument as j,removeDocument as ke,addNote as ye,setNoteStatus as we,searchKb as ve,embedMissing as xe,kbStatus as S,readPage as $e,chunkById as Se,refreshKb as A,setKbAccess as Te,kbMayUse as V}from"@chatpanel/events/kb-index.js";import{kbResearch as _e}from"@chatpanel/events/kb-research.js";import{neighbours as Ee,pathBetween as Oe,resolveNode as Z,graphReport as Ke}from"@chatpanel/events/kb-graph.js";import{outlineOf as q}from"@chatpanel/events/kb-chunk.js";import{routeKb as Pe,validateKbCreate as De,validateKbAdd as Be,validateKbSearch as Ge,validateKbResearch as Le,validateKbGraph as je,validateKbNote as Ae,validateKbNoteStatus as Me,validateKbAccess as Ne}from"@chatpanel/events/kb-capability.js";import{secretReason as ee,SKIP_DIR_NAMES as Ce,sniffType as ze,checkAttachablePath as Fe}from"@chatpanel/events/attached-paths.js";import{paginateText as M,MAX_DOCUMENT_BYTES as N}from"./extract-capability.js";import{defaultEmbeddedModel as Re}from"./embedded-models.js";import{primaryProvider as We}from"./capability-config.js";const T=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),te=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),Ie=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),p=(f,_,v,P={})=>({status:f,body:{error:{type:_,message:v},...P}}),h=f=>({status:200,body:f});function st({store:f,extract:_=null,embedded:v=null,cfg:P={},rerank:C=null,read:z=null,completer:F=null,log:R=()=>{},now:g=()=>Date.now(),home:W=me.homedir()}={}){const E=()=>{const e=We(P.capabilities?.embed,"embed");return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||Re("embed")||""},I=(e="passage")=>{const t=E();if(!v||!t)return null;const a=v.health("embed",t);return a.state!=="ready"&&!a.installed?(v.embed(t,["warm"],{kind:e}).catch(()=>{}),null):async o=>(await v.embed(t,o,{kind:e})).vectors},ne=typeof C=="function"?C:null;async function D(e,{late:t=()=>!1}={}){const a=I("passage");if(!a)return 0;try{return await xe(e,a,{model:E(),late:t})}catch(o){return R(`[kb] ${e.id}: embedding failed — ${o.message}`),0}}async function se(e,t,a=""){const o=ze(e,t);if(o.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(o.text){const i=Buffer.from(e).toString("utf8"),u=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(i.split(`
2
- `).find(r=>r.trim())||"");return{type:o.label||"text",pages:M(i).map((r,n)=>({page:n+1,text:r})),title:u?u[1].trim():""}}if(o.group!=="document")throw Object.assign(new Error(`${o.label||"binary"} is not a document`),{code:"unsupported"});if(!_)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const c=_(),d=await c.open(e,{name:t,hint:a}),s=[];for(let i=1;i<=d.pages;i+=1){let u="";try{u=String((await c.page(d.hash,i)).text||"")}catch(r){R(`[kb] ${t} p.${i}: ${r.message}`)}s.push({page:i,text:u})}return{type:d.type,pages:s,title:d.title||"",hash:d.hash,scanned:!!d.scanned}}async function U(e,t,{name:a,hint:o="",title:c="",source:d={},reach:s=""}){const i=await se(t,a,o),u=j(e,{title:c||i.title||L(a),pages:i.pages,source:{kind:d.kind||"bytes",name:a,...d},hash:i.hash||"",type:i.type,reach:s,now:g});return{id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced,...i.scanned?{scanned:!0}:{}}}function re(e,t){const a=Q(e).toLowerCase();return!te.has(a)&&!Ie.has(a)?!1:t?.length?t.some(o=>{const c=String(o).toLowerCase().replace(/^\*/,"");return a===(c.startsWith(".")?c:`.${c}`)||e.toLowerCase().endsWith(c)}):!0}async function ae(e,{path:t,recursive:a=!0,include:o=null,title:c=""}){const d=Fe(t,{home:W,cwd:process.cwd()});if(!d.ok)throw Object.assign(new Error(d.reason||"that path cannot be attached"),{code:"refused"});const s=J(ge(t.replace(/^~(?=$|\/)/,W))),i=[],u=[];let r=0,n=0;const l=async(y,b)=>{if(r>=T.files)return u.push({path:b,why:`stopped at ${T.files} files`}),!1;if(ee(y))return u.push({path:b,why:"withheld (a credential store)"}),!0;let x;try{x=H(y)}catch{return!0}const w=Q(y).toLowerCase(),k=te.has(w)?N:T.textBytes;if(x.size>k)return u.push({path:b,why:`too large (${Math.round(x.size/1048576)} MB)`}),!0;if(n+x.size>T.bytes)return u.push({path:b,why:"stopped: the folder is past the size limit"}),!1;r+=1,n+=x.size;try{const $=await U(e,pe(y),{name:L(y),title:i.length===0&&!b.includes("/")?c:"",source:{kind:"file",path:y},reach:"internal"});i.push({...$,path:b})}catch($){u.push({path:b,why:$.message})}return!0};if(!H(s).isDirectory())return await l(s,L(s)),{added:i,skipped:u};const O=async(y,b,G)=>{if(G>T.depth)return!0;let x=[];try{x=fe(y,{withFileTypes:!0}).sort((w,k)=>w.name.localeCompare(k.name))}catch{return!0}for(const w of x){const k=w.name;if(k.startsWith(".")&&w.isDirectory())continue;const $=he(y,k),K=b?`${b}/${k}`:k;if(w.isDirectory()){if(Ce.has(k)||!a)continue;try{if(!J($).startsWith(s)){u.push({path:K,why:"links outside the folder"});continue}}catch{continue}if(!await O($,K,G+1))return!1;continue}if(!(!w.isFile()&&!w.isSymbolicLink())){if(ee($)){u.push({path:K,why:"withheld (a credential store)"});continue}if(re(k,o)&&!await l($,K))return!1}}return!0};return await O(s,"",0),{added:i,skipped:u}}async function oe(e,{url:t,title:a=""}){if(!z)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const o=await z().read({url:t,format:"markdown"});if(o.status!==200)throw Object.assign(new Error(o.body?.error?.message||`read failed (${o.status})`),{code:"read_failed"});const c=String(o.body.markdown||o.body.text||"");if(!c.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const d=M(c).map((i,u)=>({page:u+1,text:i})),s=j(e,{title:a||o.body.title||t,pages:d,source:{kind:"url",url:o.body.url||t,name:o.body.title||""},type:"html",reach:"web",now:g});return{id:s.doc.id,title:s.doc.title,pages:s.doc.pages,chunks:s.doc.chunks,replaced:s.replaced}}async function ie(e,t,{admin:a=!1}={}){const o=g();let c=[],d=[];if(t.kind==="bytes"){const i=Buffer.from(t.data,"base64");if(!i.length)return p(400,"invalid_request","kb: data decoded to nothing");if(i.length>N)return p(413,"too_large",`kb: ${i.length} bytes is over the ${N}-byte limit`);try{c.push(await U(e,i,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(u){return B(u)}}else if(t.kind==="path"){if(!a)return p(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:c,skipped:d}=await ae(e,t))}catch(i){return B(i)}}else if(t.kind==="url")try{c.push(await oe(e,t))}catch(i){return B(i)}else if(t.kind==="text"){const i=M(t.text).map((r,n)=>({page:n+1,text:r})),u=j(e,{title:t.title||t.name,pages:i,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:g});c.push({id:u.doc.id,title:u.doc.title,pages:u.doc.pages,chunks:u.doc.chunks,replaced:u.replaced})}const s=c.length?await D(e):0;return f.save(e),h({added:c,skipped:d,embedded:s,kb:S(e),ms:g()-o})}function B(e){const t=e?.code||"";return t==="refused"?p(403,"refused",`kb: ${e.message}`):t==="unsupported"?p(415,"unsupported",`kb: ${e.message}`):t==="too_large"?p(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?p(502,"read_failed",`kb: ${e.message}`):t==="timeout"?p(504,"extract_timeout","kb: the document took too long to parse"):p(500,"kb_error",`kb: ${e?.message||e}`)}const X=(e,t)=>ve(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],embed:I("query"),rerank:t.rerank===!1?null:ne,now:g}),ce=(e,t)=>e.docs.find(a=>a.id===t)?.title||t,Y=(e,t)=>{const a=Se(e,t);if(!a)return null;const o=a.kind==="note"?"Note":ce(e,a.doc);return{...a,title:o,cite:a.kind==="note"?`[note ${a.id.slice(5)}]`:`[${o.replace(/[[\]]/g,"")} p.${a.page}]`}};function ue(e,t){A(e);const a=Z(e.graph,t.node);if(!a)return h({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=d=>{const s=e.graph.nodes.find(i=>i.id===d);return{id:d,label:s?.label||d.replace(/^chunk:/,"passage "),kind:s?.kind||"chunk"}},c={node:{id:a.id,kind:a.kind,label:a.label},neighbours:Ee(e.graph,a.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit})};if(t.to){const d=Z(e.graph,t.to);c.to=t.to,c.path=d?(Oe(e.graph,a.id,d.id)||[]).map(o):null,d&&!c.path.length&&(c.path=null)}return h(c)}async function de(e,t,{admin:a=!1}={}){if(t.model&&!a)return p(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const o=t.model&&typeof F=="function"?F(t.model):null,c=S(e),d=await _e(t.question,{search:(s,i)=>X(e,{query:s,limit:i.limit||10,hops:i.hops??1,docs:i.docs||t.docs||null}),outline:async s=>s?q(e.chunks,{doc:s}):e.outline,read:async s=>Y(e,s),complete:o,kbName:e.name,docs:c.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:g});return h({attachment:d.attachment,read:d.read,hits:d.hits.map(s=>({id:s.id,doc:s.doc,title:s.title,page:s.page,section:s.section,cite:s.cite,lanes:s.lanes,via:s.via})),queries:d.queries,verdict:d.verdict,rounds:d.rounds,ask:d.ask,how:d.how,frame:{whole:d.frame.whole,docs:d.frame.docs},ms:d.ms})}async function le({method:e="GET",pathname:t="",query:a=new URLSearchParams,body:o=null,admin:c=!1,agent:d=""}={}){const s=Pe(t);if(!s)return p(404,"not_found",`no route ${t}`);if(s.bad)return p(400,"invalid_request",`kb: "${s.bad}" is not a valid id or route`);const i={admin:c,agent:String(d||a.get("agent")||"").trim().toLowerCase()},u=n=>{try{return{value:n()}}catch(l){return{res:p(400,"invalid_request",l.message)}}};if(!s.id){if(e==="GET")return h({kbs:f.list().filter(({manifest:n})=>V({access:n.access},i)).map(({manifest:n})=>({id:n.id,name:n.name,docs:(n.docs||[]).length,updatedAt:n.updatedAt,vectors:n.vectors?.count||0,model:n.vectors?.model||"",access:n.access||{agents:"all"}}))});if(e==="POST"){const n=u(()=>De(o||{}));if(n.res)return n.res;const l=n.value;if(l.id&&f.load(l.id))return h({kb:S(f.load(l.id)),existed:!0});const m=be({id:l.id,name:l.name,embed:l.embed,now:g});return f.save(m),{status:201,body:{kb:S(m)}}}return p(405,"method_not_allowed",`kb: ${e} is not allowed here`)}const r=f.load(s.id);if(!r)return p(404,"not_found",`kb: no knowledge base ${s.id} — POST /v1/kb to create one`);if(!V(r,i))return p(404,"not_found",`kb: no knowledge base ${s.id} for ${i.agent||"this caller"} — the owner can grant it (POST /v1/kb/${s.id}/access)`);if(!s.sub)return e==="GET"?h({kb:{...S(r),bytes:f.sizeOf(r.id),dir:c?f.dirOf(r.id):void 0}}):e==="DELETE"?c?(f.remove(r.id),h({ok:!0})):p(403,"forbidden","kb: deleting needs the gateway token or the extension origin"):p(405,"method_not_allowed",`kb: ${e} is not allowed here`);switch(s.sub){case"documents":{if(e==="POST"&&!s.rest){const n=u(()=>Be(o||{}));return n.res?n.res:ie(r,n.value,{admin:c})}if(e==="DELETE"&&s.rest)return c?ke(r,s.rest,{now:g})?(f.save(r),h({ok:!0,kb:S(r)})):p(404,"not_found",`kb: no document ${s.rest}`):p(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&s.rest){const n=Number(a.get("page"))||1,l=$e(r,s.rest,n);return l?h(l):p(404,"not_found",`kb: no document ${s.rest}`)}if(e==="GET")return h({documents:S(r).documents});break}case"passages":{if(e==="GET"&&s.rest){const n=Y(r,s.rest);return n?h(n):p(404,"not_found",`kb: no passage ${s.rest}`)}break}case"outline":{if(e==="GET"){A(r);const n=a.get("doc");return h({outline:n?q(r.chunks,{doc:n}):r.outline})}break}case"search":{if(e==="POST"){const n=u(()=>Ge(o||{}));return n.res?n.res:h(await X(r,n.value))}break}case"research":{if(e==="POST"){const n=u(()=>Le(o||{}));return n.res?n.res:de(r,n.value,{admin:c})}break}case"graph":{if(e==="POST"){const n=u(()=>je(o||{}));return n.res?n.res:ue(r,n.value)}break}case"report":{if(e==="GET")return A(r),{status:200,text:Ke(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return h({notes:r.notes});if(e==="POST"&&!s.rest){const n=u(()=>Ae(o||{}));if(n.res)return n.res;const l=n.value,m=l.status==="accepted"&&c?"accepted":"proposed",O=ye(r,{text:l.text,cites:l.cites||[],by:l.by||(c?"user":"agent"),status:m,now:g});return await D(r),f.save(r),{status:201,body:{note:O}}}if(e==="POST"&&s.rest){if(!c)return p(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=u(()=>Me(o||{}));if(n.res)return n.res;const l=n.value,m=we(r,s.rest,l.status,{now:g});return m?(f.save(r),h({note:m,removed:l.status==="removed"})):p(404,"not_found",`kb: no note ${s.rest}`)}break}case"access":{if(e==="GET")return h({access:r.access});if(e==="POST"){if(!c)return p(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=u(()=>Ne(o||{}));if(n.res)return n.res;const l=Te(r,n.value,{now:g});return f.save(r),h({access:l})}break}case"embed":{if(e==="POST"){const n=E(),l=v&&n?v.health("embed",n):{state:"off"},m=await D(r);return m&&f.save(r),h({embedded:m,vectors:r.vectors.by.size,model:r.vectors.model||n,dims:r.vectors.dims,state:l.state,...l.progress?{progress:l.progress}:{}})}break}default:break}return p(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}return{handle:le,store:f,embedModel:E}}export{T as KB_WALK_LIMITS,st as createKbService};
1
+ import{readFileSync as pe,statSync as H,readdirSync as fe,realpathSync as J}from"node:fs";import{join as he,basename as L,extname as Q,resolve as ge}from"node:path";import me from"node:os";import{createKb as be,addDocument as j,removeDocument as ke,addNote as ye,setNoteStatus as we,searchKb as ve,embedMissing as xe,kbStatus as S,readPage as $e,chunkById as Se,refreshKb as A,setKbAccess as Te,kbMayUse as V}from"@chatpanel/events/kb-index.js";import{kbResearch as _e}from"@chatpanel/events/kb-research.js";import{neighbours as Ee,pathBetween as Oe,resolveNode as Z,graphReport as Ke}from"@chatpanel/events/kb-graph.js";import{outlineOf as q}from"@chatpanel/events/kb-chunk.js";import{routeKb as Pe,validateKbCreate as De,validateKbAdd as Be,validateKbSearch as Ge,validateKbResearch as Le,validateKbGraph as je,validateKbNote as Ae,validateKbNoteStatus as Me,validateKbAccess as Ne}from"@chatpanel/events/kb-capability.js";import{secretReason as ee,SKIP_DIR_NAMES as Ce,sniffType as ze,checkAttachablePath as Fe}from"@chatpanel/events/attached-paths.js";import{paginateText as M,MAX_DOCUMENT_BYTES as N}from"./extract-capability.js";import{defaultEmbeddedModel as Re}from"./embedded-models.js";import{primaryProvider as We}from"./capability-config.js";const T=Object.freeze({files:2e3,bytes:512*1024*1024,depth:8,textBytes:8*1024*1024}),te=new Set([".pdf",".docx",".xlsx",".pptx",".odt",".ods",".odp",".epub"]),Ie=new Set([".md",".markdown",".txt",".text",".csv",".json",".html",".htm",".xml",".rst",".adoc",".log",".yaml",".yml",".toml"]),p=(f,_,v,E={})=>({status:f,body:{error:{type:_,message:v},...E}}),h=f=>({status:200,body:f});function st({store:f,extract:_=null,embedded:v=null,cfg:E={},rerank:C=null,read:z=null,completer:F=null,log:R=()=>{},now:g=()=>Date.now(),home:W=me.homedir()}={}){const O=()=>{const e=We(E.capabilities?.embed,"embed",{destinations:E.destinations||[]});return e?.provider==="none"?"":e?.provider==="embedded"&&typeof e.model=="string"&&e.model||Re("embed")||""},I=(e="passage")=>{const t=O();if(!v||!t)return null;const a=v.health("embed",t);return a.state!=="ready"&&!a.installed?(v.embed(t,["warm"],{kind:e}).catch(()=>{}),null):async o=>(await v.embed(t,o,{kind:e})).vectors},ne=typeof C=="function"?C:null;async function D(e,{late:t=()=>!1}={}){const a=I("passage");if(!a)return 0;try{return await xe(e,a,{model:O(),late:t})}catch(o){return R(`[kb] ${e.id}: embedding failed — ${o.message}`),0}}async function se(e,t,a=""){const o=ze(e,t);if(o.group==="key")throw Object.assign(new Error("its contents look like a credential — withheld"),{code:"refused"});if(o.text){const i=Buffer.from(e).toString("utf8"),d=/^\s*#\s+(.+?)\s*#*\s*$/m.exec(i.split(`
2
+ `).find(r=>r.trim())||"");return{type:o.label||"text",pages:M(i).map((r,n)=>({page:n+1,text:r})),title:d?d[1].trim():""}}if(o.group!=="document")throw Object.assign(new Error(`${o.label||"binary"} is not a document`),{code:"unsupported"});if(!_)throw Object.assign(new Error("no document extractor on this gateway"),{code:"unsupported"});const c=_(),u=await c.open(e,{name:t,hint:a}),s=[];for(let i=1;i<=u.pages;i+=1){let d="";try{d=String((await c.page(u.hash,i)).text||"")}catch(r){R(`[kb] ${t} p.${i}: ${r.message}`)}s.push({page:i,text:d})}return{type:u.type,pages:s,title:u.title||"",hash:u.hash,scanned:!!u.scanned}}async function U(e,t,{name:a,hint:o="",title:c="",source:u={},reach:s=""}){const i=await se(t,a,o),d=j(e,{title:c||i.title||L(a),pages:i.pages,source:{kind:u.kind||"bytes",name:a,...u},hash:i.hash||"",type:i.type,reach:s,now:g});return{id:d.doc.id,title:d.doc.title,pages:d.doc.pages,chunks:d.doc.chunks,replaced:d.replaced,...i.scanned?{scanned:!0}:{}}}function re(e,t){const a=Q(e).toLowerCase();return!te.has(a)&&!Ie.has(a)?!1:t?.length?t.some(o=>{const c=String(o).toLowerCase().replace(/^\*/,"");return a===(c.startsWith(".")?c:`.${c}`)||e.toLowerCase().endsWith(c)}):!0}async function ae(e,{path:t,recursive:a=!0,include:o=null,title:c=""}){const u=Fe(t,{home:W,cwd:process.cwd()});if(!u.ok)throw Object.assign(new Error(u.reason||"that path cannot be attached"),{code:"refused"});const s=J(ge(t.replace(/^~(?=$|\/)/,W))),i=[],d=[];let r=0,n=0;const l=async(y,b)=>{if(r>=T.files)return d.push({path:b,why:`stopped at ${T.files} files`}),!1;if(ee(y))return d.push({path:b,why:"withheld (a credential store)"}),!0;let x;try{x=H(y)}catch{return!0}const w=Q(y).toLowerCase(),k=te.has(w)?N:T.textBytes;if(x.size>k)return d.push({path:b,why:`too large (${Math.round(x.size/1048576)} MB)`}),!0;if(n+x.size>T.bytes)return d.push({path:b,why:"stopped: the folder is past the size limit"}),!1;r+=1,n+=x.size;try{const $=await U(e,pe(y),{name:L(y),title:i.length===0&&!b.includes("/")?c:"",source:{kind:"file",path:y},reach:"internal"});i.push({...$,path:b})}catch($){d.push({path:b,why:$.message})}return!0};if(!H(s).isDirectory())return await l(s,L(s)),{added:i,skipped:d};const K=async(y,b,G)=>{if(G>T.depth)return!0;let x=[];try{x=fe(y,{withFileTypes:!0}).sort((w,k)=>w.name.localeCompare(k.name))}catch{return!0}for(const w of x){const k=w.name;if(k.startsWith(".")&&w.isDirectory())continue;const $=he(y,k),P=b?`${b}/${k}`:k;if(w.isDirectory()){if(Ce.has(k)||!a)continue;try{if(!J($).startsWith(s)){d.push({path:P,why:"links outside the folder"});continue}}catch{continue}if(!await K($,P,G+1))return!1;continue}if(!(!w.isFile()&&!w.isSymbolicLink())){if(ee($)){d.push({path:P,why:"withheld (a credential store)"});continue}if(re(k,o)&&!await l($,P))return!1}}return!0};return await K(s,"",0),{added:i,skipped:d}}async function oe(e,{url:t,title:a=""}){if(!z)throw Object.assign(new Error("no reader on this gateway"),{code:"unsupported"});const o=await z().read({url:t,format:"markdown"});if(o.status!==200)throw Object.assign(new Error(o.body?.error?.message||`read failed (${o.status})`),{code:"read_failed"});const c=String(o.body.markdown||o.body.text||"");if(!c.trim())throw Object.assign(new Error("the page had no readable text"),{code:"empty"});const u=M(c).map((i,d)=>({page:d+1,text:i})),s=j(e,{title:a||o.body.title||t,pages:u,source:{kind:"url",url:o.body.url||t,name:o.body.title||""},type:"html",reach:"web",now:g});return{id:s.doc.id,title:s.doc.title,pages:s.doc.pages,chunks:s.doc.chunks,replaced:s.replaced}}async function ie(e,t,{admin:a=!1}={}){const o=g();let c=[],u=[];if(t.kind==="bytes"){const i=Buffer.from(t.data,"base64");if(!i.length)return p(400,"invalid_request","kb: data decoded to nothing");if(i.length>N)return p(413,"too_large",`kb: ${i.length} bytes is over the ${N}-byte limit`);try{c.push(await U(e,i,{name:t.name,hint:t.type||"",title:t.title,reach:t.reach}))}catch(d){return B(d)}}else if(t.kind==="path"){if(!a)return p(403,"forbidden","kb: adding a path needs the gateway token or the extension origin — a path is a read on this machine");try{({added:c,skipped:u}=await ae(e,t))}catch(i){return B(i)}}else if(t.kind==="url")try{c.push(await oe(e,t))}catch(i){return B(i)}else if(t.kind==="text"){const i=M(t.text).map((r,n)=>({page:n+1,text:r})),d=j(e,{title:t.title||t.name,pages:i,source:{kind:"text",name:t.name},type:"text",reach:t.reach,now:g});c.push({id:d.doc.id,title:d.doc.title,pages:d.doc.pages,chunks:d.doc.chunks,replaced:d.replaced})}const s=c.length?await D(e):0;return f.save(e),h({added:c,skipped:u,embedded:s,kb:S(e),ms:g()-o})}function B(e){const t=e?.code||"";return t==="refused"?p(403,"refused",`kb: ${e.message}`):t==="unsupported"?p(415,"unsupported",`kb: ${e.message}`):t==="too_large"?p(413,"too_large",`kb: ${e.message}`):t==="read_failed"||t==="empty"?p(502,"read_failed",`kb: ${e.message}`):t==="timeout"?p(504,"extract_timeout","kb: the document took too long to parse"):p(500,"kb_error",`kb: ${e?.message||e}`)}const X=(e,t)=>ve(e,t.query,{limit:t.limit,hops:t.hops,docs:t.docs||null,queries:t.queries||[],embed:I("query"),rerank:t.rerank===!1?null:ne,now:g}),ce=(e,t)=>e.docs.find(a=>a.id===t)?.title||t,Y=(e,t)=>{const a=Se(e,t);if(!a)return null;const o=a.kind==="note"?"Note":ce(e,a.doc);return{...a,title:o,cite:a.kind==="note"?`[note ${a.id.slice(5)}]`:`[${o.replace(/[[\]]/g,"")} p.${a.page}]`}};function de(e,t){A(e);const a=Z(e.graph,t.node);if(!a)return h({node:null,neighbours:[],message:`no node named "${t.node}"`});const o=u=>{const s=e.graph.nodes.find(i=>i.id===u);return{id:u,label:s?.label||u.replace(/^chunk:/,"passage "),kind:s?.kind||"chunk"}},c={node:{id:a.id,kind:a.kind,label:a.label},neighbours:Ee(e.graph,a.id,{hops:t.hops,kinds:t.kinds||null,limit:t.limit})};if(t.to){const u=Z(e.graph,t.to);c.to=t.to,c.path=u?(Oe(e.graph,a.id,u.id)||[]).map(o):null,u&&!c.path.length&&(c.path=null)}return h(c)}async function ue(e,t,{admin:a=!1}={}){if(t.model&&!a)return p(403,"forbidden","kb: research with a model needs the gateway token or the extension origin");const o=t.model&&typeof F=="function"?F(t.model):null,c=S(e),u=await _e(t.question,{search:(s,i)=>X(e,{query:s,limit:i.limit||10,hops:i.hops??1,docs:i.docs||t.docs||null}),outline:async s=>s?q(e.chunks,{doc:s}):e.outline,read:async s=>Y(e,s),complete:o,kbName:e.name,docs:c.documents,previous:t.previous||null,answer:t.answer||"",ask:t.ask!==!1,now:g});return h({attachment:u.attachment,read:u.read,hits:u.hits.map(s=>({id:s.id,doc:s.doc,title:s.title,page:s.page,section:s.section,cite:s.cite,lanes:s.lanes,via:s.via})),queries:u.queries,verdict:u.verdict,rounds:u.rounds,ask:u.ask,how:u.how,frame:{whole:u.frame.whole,docs:u.frame.docs},ms:u.ms})}async function le({method:e="GET",pathname:t="",query:a=new URLSearchParams,body:o=null,admin:c=!1,agent:u=""}={}){const s=Pe(t);if(!s)return p(404,"not_found",`no route ${t}`);if(s.bad)return p(400,"invalid_request",`kb: "${s.bad}" is not a valid id or route`);const i={admin:c,agent:String(u||a.get("agent")||"").trim().toLowerCase()},d=n=>{try{return{value:n()}}catch(l){return{res:p(400,"invalid_request",l.message)}}};if(!s.id){if(e==="GET")return h({kbs:f.list().filter(({manifest:n})=>V({access:n.access},i)).map(({manifest:n})=>({id:n.id,name:n.name,docs:(n.docs||[]).length,updatedAt:n.updatedAt,vectors:n.vectors?.count||0,model:n.vectors?.model||"",access:n.access||{agents:"all"}}))});if(e==="POST"){const n=d(()=>De(o||{}));if(n.res)return n.res;const l=n.value;if(l.id&&f.load(l.id))return h({kb:S(f.load(l.id)),existed:!0});const m=be({id:l.id,name:l.name,embed:l.embed,now:g});return f.save(m),{status:201,body:{kb:S(m)}}}return p(405,"method_not_allowed",`kb: ${e} is not allowed here`)}const r=f.load(s.id);if(!r)return p(404,"not_found",`kb: no knowledge base ${s.id} — POST /v1/kb to create one`);if(!V(r,i))return p(404,"not_found",`kb: no knowledge base ${s.id} for ${i.agent||"this caller"} — the owner can grant it (POST /v1/kb/${s.id}/access)`);if(!s.sub)return e==="GET"?h({kb:{...S(r),bytes:f.sizeOf(r.id),dir:c?f.dirOf(r.id):void 0}}):e==="DELETE"?c?(f.remove(r.id),h({ok:!0})):p(403,"forbidden","kb: deleting needs the gateway token or the extension origin"):p(405,"method_not_allowed",`kb: ${e} is not allowed here`);switch(s.sub){case"documents":{if(e==="POST"&&!s.rest){const n=d(()=>Be(o||{}));return n.res?n.res:ie(r,n.value,{admin:c})}if(e==="DELETE"&&s.rest)return c?ke(r,s.rest,{now:g})?(f.save(r),h({ok:!0,kb:S(r)})):p(404,"not_found",`kb: no document ${s.rest}`):p(403,"forbidden","kb: removing a document needs the gateway token or the extension origin");if(e==="GET"&&s.rest){const n=Number(a.get("page"))||1,l=$e(r,s.rest,n);return l?h(l):p(404,"not_found",`kb: no document ${s.rest}`)}if(e==="GET")return h({documents:S(r).documents});break}case"passages":{if(e==="GET"&&s.rest){const n=Y(r,s.rest);return n?h(n):p(404,"not_found",`kb: no passage ${s.rest}`)}break}case"outline":{if(e==="GET"){A(r);const n=a.get("doc");return h({outline:n?q(r.chunks,{doc:n}):r.outline})}break}case"search":{if(e==="POST"){const n=d(()=>Ge(o||{}));return n.res?n.res:h(await X(r,n.value))}break}case"research":{if(e==="POST"){const n=d(()=>Le(o||{}));return n.res?n.res:ue(r,n.value,{admin:c})}break}case"graph":{if(e==="POST"){const n=d(()=>je(o||{}));return n.res?n.res:de(r,n.value)}break}case"report":{if(e==="GET")return A(r),{status:200,text:Ke(r),contentType:"text/markdown; charset=utf-8"};break}case"notes":{if(e==="GET")return h({notes:r.notes});if(e==="POST"&&!s.rest){const n=d(()=>Ae(o||{}));if(n.res)return n.res;const l=n.value,m=l.status==="accepted"&&c?"accepted":"proposed",K=ye(r,{text:l.text,cites:l.cites||[],by:l.by||(c?"user":"agent"),status:m,now:g});return await D(r),f.save(r),{status:201,body:{note:K}}}if(e==="POST"&&s.rest){if(!c)return p(403,"forbidden","kb: accepting or removing a note needs the gateway token or the extension origin");const n=d(()=>Me(o||{}));if(n.res)return n.res;const l=n.value,m=we(r,s.rest,l.status,{now:g});return m?(f.save(r),h({note:m,removed:l.status==="removed"})):p(404,"not_found",`kb: no note ${s.rest}`)}break}case"access":{if(e==="GET")return h({access:r.access});if(e==="POST"){if(!c)return p(403,"forbidden","kb: granting a base needs the gateway token or the extension origin");const n=d(()=>Ne(o||{}));if(n.res)return n.res;const l=Te(r,n.value,{now:g});return f.save(r),h({access:l})}break}case"embed":{if(e==="POST"){const n=O(),l=v&&n?v.health("embed",n):{state:"off"},m=await D(r);return m&&f.save(r),h({embedded:m,vectors:r.vectors.by.size,model:r.vectors.model||n,dims:r.vectors.dims,state:l.state,...l.progress?{progress:l.progress}:{}})}break}default:break}return p(405,"method_not_allowed",`kb: ${e} ${t} is not a route`)}return{handle:le,store:f,embedModel:O}}export{T as KB_WALK_LIMITS,st as createKbService};
package/src/providers.js CHANGED
@@ -1 +1 @@
1
- import{CAPABILITIES as m,CAPABILITY_ROUTES as v,PROVIDER_KINDS as g}from"./capability-endpoints.js";import{listDestinations as f}from"./router.js";import{defaultEmbeddedModel as p}from"./embedded-models.js";import{capabilityList as c}from"./capability-config.js";const y=/^(localhost|127\.|\[::1\]|0\.0\.0\.0)/,w=/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?fe80:|.*\.local$)/i;function l(n){if(!n)return"none";let e="";try{e=new URL(n).hostname}catch{return"internet"}return y.test(e)?"loopback":w.test(e)?"lan":"internet"}const i=n=>typeof n=="string"&&n.trim()?n.trim():null;function x(n,e){if(!e||typeof e!="object")return null;const r=i(e.url);let d=g.includes(e.provider)?e.provider:null;return d||(d=e.service?"container":r?"remote":"embedded"),d==="remote"&&!/^https?:\/\//.test(r||"")?null:{kind:d,...r?{url:r}:{},...i(e.adapter)?{adapter:i(e.adapter)}:{},...i(e.model)?{model:i(e.model)}:d==="embedded"&&p(n)?{model:p(n)}:{},...i(e.service)?{service:i(e.service)}:{},...i(e.token)?{token:i(e.token)}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},...typeof e.id=="string"&&e.id?{id:e.id}:{},egress:d==="embedded"?"none":d==="container"?"loopback":l(r)}}const b=(n,e)=>c(n?.capabilities?.[e],e).providers.map(r=>x(e,r)).filter(Boolean),O=(n,e)=>b(n,e)[0]||null;function k(n,e,r={}){if(!m.includes(e))throw new Error(`providerOf: unknown capability ${e}`);const d=O(n,e);if(d)return o(e,d,r);switch(e){case"chat":{const t=f(n),s=t.filter(u=>u.type==="agent").length,a=t.filter(u=>u.type!=="agent");if(!t.length)return o(e,{kind:"none",egress:"none"},r);if(!a.length)return o(e,{kind:"harness",egress:"internet",destinations:t.length,harnesses:s},r);const h=a.some(u=>l(u.baseUrl)==="internet")?"internet":a.some(u=>l(u.baseUrl)==="lan")?"lan":"loopback";return o(e,{kind:"router",egress:h,destinations:t.length,harnesses:s,apis:a.length},r)}case"detect":{const t=n?.redaction?.detection;return t?.backend==="endpoint"&&i(t.url)?o(e,{kind:"remote",url:t.url,adapter:"detect",egress:l(t.url)},r):t?.backend&&t.backend!=="off"&&t.backend!=="endpoint"?o(e,{kind:"embedded",egress:"none",model:r.nerModel||n?.ner?.model},r):o(e,{kind:"embedded",egress:"none",model:r.nerModel||n?.ner?.model},r)}case"stt":return n?.stt?.enabled===!1?o(e,{kind:"none",egress:"none"},r):o(e,{kind:"embedded",egress:"none",model:r.sttModel||n?.stt?.model},r);case"tts":{const t=n?.tts?.provider;if(n?.tts?.enabled===!1)return o(e,{kind:"none",egress:"none"},r);if(t&&t!=="local"){const s=n?.tts?.remote||{},a=i(s.baseUrl)||(t==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1");return o(e,{kind:"remote",url:a,adapter:t,model:i(s.model)||void 0,egress:l(a),redact:s.redact!==!1},r)}return o(e,{kind:"embedded",egress:"none",model:r.ttsModel||n?.tts?.model},r)}case"search":{const t=n?.search?.provider||"auto",s=i(n?.search?.searxng?.url);return t==="searxng"||t==="auto"&&s?o(e,{kind:l(s)==="loopback"?"container":"remote",url:s,adapter:"searxng",egress:l(s)},r):o(e,{kind:"embedded",adapter:"serp",egress:"internet"},r)}case"read":{const t=n?.read?.provider||"defuddle",s=i(n?.read?.remote?.url);return t==="remote"&&s?o(e,{kind:"remote",url:s,adapter:"remote",egress:l(s)},r):o(e,{kind:"embedded",adapter:t,egress:"internet"},r)}case"extract":return o(e,{kind:"embedded",egress:"none"},r);case"rerank":case"decide":return o(e,{kind:"embedded",model:p(e),egress:"none"},r);case"embed":return o(e,{kind:"embedded",model:p(e),egress:"none"},r);default:return o(e,{kind:"none",egress:"none"},r)}}const L={embedded:"this device",container:"a container on this device",remote:"a server",harness:"coding agents, each at its own vendor",router:"the model router",none:"nobody yet"};function o(n,e,r){const d=e.kind==="remote"?(()=>{try{return new URL(e.url).host}catch{return e.url}})():L[e.kind],t=e.model||e.adapter||e.service||"";return{...e,label:t?`${t} — ${d}`:d,route:v[n]}}function E(n,e,r={}){if(!m.includes(e))throw new Error(`providersOf: unknown capability ${e}`);const{mode:d}=c(n?.capabilities?.[e],e),t=b(n,e);return{mode:d,providers:t.length?t.map(s=>o(e,s,r)):[k(n,e,r)]}}function R(n,e={}){return Object.fromEntries(m.map(r=>[r,k(n,r,e)]))}function S(n,e={}){const r=[];for(const d of m)for(const t of E(n,d,e).providers){if(t.kind!=="remote"||!t.url)continue;let s=t.url;try{s=new URL(t.url).host}catch{}r.push({id:d,host:s,adapter:t.adapter||"",token:!!t.token,egress:t.egress,route:t.route})}return r}export{S as declaredProviderHosts,l as egressOf,k as providerOf,R as providerTable,E as providersOf};
1
+ import{CAPABILITIES as m,CAPABILITY_ROUTES as v,PROVIDER_KINDS as g}from"./capability-endpoints.js";import{listDestinations as f}from"./router.js";import{defaultEmbeddedModel as p}from"./embedded-models.js";import{capabilityList as c}from"./capability-config.js";const y=/^(localhost|127\.|\[::1\]|0\.0\.0\.0)/,w=/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?fe80:|.*\.local$)/i;function a(n){if(!n)return"none";let e="";try{e=new URL(n).hostname}catch{return"internet"}return y.test(e)?"loopback":w.test(e)?"lan":"internet"}const i=n=>typeof n=="string"&&n.trim()?n.trim():null;function x(n,e){if(!e||typeof e!="object")return null;const r=i(e.url);let d=g.includes(e.provider)?e.provider:null;return d||(d=e.service?"container":r?"remote":"embedded"),d==="remote"&&!/^https?:\/\//.test(r||"")?null:{kind:d,...r?{url:r}:{},...i(e.adapter)?{adapter:i(e.adapter)}:{},...i(e.model)?{model:i(e.model)}:d==="embedded"&&p(n)?{model:p(n)}:{},...i(e.service)?{service:i(e.service)}:{},...i(e.token)?{token:i(e.token)}:{},...typeof e.calibrated=="boolean"?{calibrated:e.calibrated}:{},...typeof e.redact=="boolean"?{redact:e.redact}:{},...typeof e.id=="string"&&e.id?{id:e.id}:{},...typeof e.voice=="string"&&e.voice?{voice:e.voice}:{},egress:d==="embedded"?"none":d==="container"?"loopback":a(r)}}const b=(n,e)=>c(n?.capabilities?.[e],e,{destinations:n?.destinations||[]}).providers.map(r=>x(e,r)).filter(Boolean),O=(n,e)=>b(n,e)[0]||null;function k(n,e,r={}){if(!m.includes(e))throw new Error(`providerOf: unknown capability ${e}`);const d=O(n,e);if(d)return o(e,d,r);switch(e){case"chat":{const t=f(n),s=t.filter(u=>u.type==="agent").length,l=t.filter(u=>u.type!=="agent");if(!t.length)return o(e,{kind:"none",egress:"none"},r);if(!l.length)return o(e,{kind:"harness",egress:"internet",destinations:t.length,harnesses:s},r);const h=l.some(u=>a(u.baseUrl)==="internet")?"internet":l.some(u=>a(u.baseUrl)==="lan")?"lan":"loopback";return o(e,{kind:"router",egress:h,destinations:t.length,harnesses:s,apis:l.length},r)}case"detect":{const t=n?.redaction?.detection;return t?.backend==="endpoint"&&i(t.url)?o(e,{kind:"remote",url:t.url,adapter:"detect",egress:a(t.url)},r):t?.backend&&t.backend!=="off"&&t.backend!=="endpoint"?o(e,{kind:"embedded",egress:"none",model:r.nerModel||n?.ner?.model},r):o(e,{kind:"embedded",egress:"none",model:r.nerModel||n?.ner?.model},r)}case"stt":return n?.stt?.enabled===!1?o(e,{kind:"none",egress:"none"},r):o(e,{kind:"embedded",egress:"none",model:r.sttModel||n?.stt?.model},r);case"tts":{const t=n?.tts?.provider;if(n?.tts?.enabled===!1)return o(e,{kind:"none",egress:"none"},r);if(t&&t!=="local"){const s=n?.tts?.remote||{},l=i(s.baseUrl)||(t==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1");return o(e,{kind:"remote",url:l,adapter:t,model:i(s.model)||void 0,egress:a(l),redact:s.redact!==!1},r)}return o(e,{kind:"embedded",egress:"none",model:r.ttsModel||n?.tts?.model},r)}case"search":{const t=n?.search?.provider||"auto",s=i(n?.search?.searxng?.url);return t==="searxng"||t==="auto"&&s?o(e,{kind:a(s)==="loopback"?"container":"remote",url:s,adapter:"searxng",egress:a(s)},r):o(e,{kind:"embedded",adapter:"serp",egress:"internet"},r)}case"read":{const t=n?.read?.provider||"defuddle",s=i(n?.read?.remote?.url);return t==="remote"&&s?o(e,{kind:"remote",url:s,adapter:"remote",egress:a(s)},r):o(e,{kind:"embedded",adapter:t,egress:"internet"},r)}case"extract":return o(e,{kind:"embedded",egress:"none"},r);case"rerank":case"decide":return o(e,{kind:"embedded",model:p(e),egress:"none"},r);case"embed":return o(e,{kind:"embedded",model:p(e),egress:"none"},r);default:return o(e,{kind:"none",egress:"none"},r)}}const L={embedded:"this device",container:"a container on this device",remote:"a server",harness:"coding agents, each at its own vendor",router:"the model router",none:"nobody yet"};function o(n,e,r){const d=e.kind==="remote"?(()=>{try{return new URL(e.url).host}catch{return e.url}})():L[e.kind],t=e.model||e.adapter||e.service||"";return{...e,label:t?`${t} — ${d}`:d,route:v[n]}}function E(n,e,r={}){if(!m.includes(e))throw new Error(`providersOf: unknown capability ${e}`);const{mode:d}=c(n?.capabilities?.[e],e),t=b(n,e);return{mode:d,providers:t.length?t.map(s=>o(e,s,r)):[k(n,e,r)]}}function R(n,e={}){return Object.fromEntries(m.map(r=>[r,k(n,r,e)]))}function S(n,e={}){const r=[];for(const d of m)for(const t of E(n,d,e).providers){if(t.kind!=="remote"||!t.url)continue;let s=t.url;try{s=new URL(t.url).host}catch{}r.push({id:d,host:s,adapter:t.adapter||"",token:!!t.token,egress:t.egress,route:t.route})}return r}export{S as declaredProviderHosts,a as egressOf,k as providerOf,R as providerTable,E as providersOf};
package/src/stt-remote.js CHANGED
@@ -1 +1 @@
1
- const L=16e3;function b(t,a=16e3){const o=t.length,e=Buffer.alloc(44+o*2);e.write("RIFF",0),e.writeUInt32LE(36+o*2,4),e.write("WAVE",8),e.write("fmt ",12),e.writeUInt32LE(16,16),e.writeUInt16LE(1,20),e.writeUInt16LE(1,22),e.writeUInt32LE(a,24),e.writeUInt32LE(a*2,28),e.writeUInt16LE(2,32),e.writeUInt16LE(16,34),e.write("data",36),e.writeUInt32LE(o*2,40);for(let r=0;r<o;r++){const i=Math.max(-1,Math.min(1,t[r]));e.writeInt16LE(i<0?i*32768:i*32767,44+r*2)}return e}const _=Object.freeze(["openai","elevenlabs"]),E=Object.freeze({openai:"/audio/transcriptions",elevenlabs:"/speech-to-text"});function x(t){const a=String(t||"").trim();if(!a)return null;try{return new Intl.Locale(a).language.toLowerCase()||null}catch{return null}}function S(t,{fetchImpl:a,now:o=()=>performance.now()}={}){if(!t||!["remote","container"].includes(t.kind)||!/^https?:\/\//.test(t.url||""))throw new Error("stt-remote: a remote provider needs a url");const e=t.adapter||"openai";if(!_.includes(e))throw new Error(`stt-remote: unknown adapter ${e}`);const r=t.url.replace(/\/+$/,"");return{provider:{kind:t.kind,url:t.url,adapter:e,model:t.model||(e==="elevenlabs"?"scribe_v1":"whisper-1")},async transcribe(i,{lang:c=null,langs:h=null,timeoutMs:p=3e4}={}){const d=o();if(e==="elevenlabs"){const n=new FormData;n.append("file",new Blob([b(i)],{type:"audio/wav"}),"segment.wav"),n.append("model_id",t.model||"scribe_v1"),c&&!h?.length&&n.append("language_code",c),n.append("tag_audio_events","false"),n.append("diarize","false");const u=await a(`${r}${E.elevenlabs}`,{method:"POST",headers:{accept:"application/json",...t.token?{"xi-api-key":t.token}:{}},body:n,signal:AbortSignal.timeout(p)});if(!u.ok){const f=await u.text().catch(()=>"");throw new Error(`elevenlabs transcription ${u.status}${f?`: ${f.slice(0,200)}`:""}`)}const w=await u.json().catch(()=>({})),m=x(w?.language_code);return{text:String(w?.text||"").trim(),ms:Math.round(o()-d),...m?{lang:m,confidence:Number(w?.language_probability)||null}:{}}}const s=new FormData;s.append("file",new Blob([b(i)],{type:"audio/wav"}),"segment.wav"),s.append("model",t.model||"whisper-1"),s.append("response_format","json"),c&&s.append("language",c);const l=await a(`${r}${E.openai}`,{method:"POST",headers:{accept:"application/json",...t.token?{authorization:`Bearer ${t.token}`}:{}},body:s,signal:AbortSignal.timeout(p)});if(!l.ok){const n=await l.text().catch(()=>"");throw new Error(`${e} transcription ${l.status}${n?`: ${n.slice(0,200)}`:""}`)}const g=await l.json().catch(()=>({}));return{text:String(g?.text||"").trim(),ms:Math.round(o()-d)}}}}export{_ as STT_REMOTE_ADAPTERS,E as STT_REMOTE_PATHS,S as createRemoteTranscriber,x as languageFromService,b as wavFromFloat32};
1
+ const _=16e3;function h(e,a=16e3){const o=e.length,t=Buffer.alloc(44+o*2);t.write("RIFF",0),t.writeUInt32LE(36+o*2,4),t.write("WAVE",8),t.write("fmt ",12),t.writeUInt32LE(16,16),t.writeUInt16LE(1,20),t.writeUInt16LE(1,22),t.writeUInt32LE(a,24),t.writeUInt32LE(a*2,28),t.writeUInt16LE(2,32),t.writeUInt16LE(16,34),t.write("data",36),t.writeUInt32LE(o*2,40);for(let r=0;r<o;r++){const i=Math.max(-1,Math.min(1,e[r]));t.writeInt16LE(i<0?i*32768:i*32767,44+r*2)}return t}const x=Object.freeze(["openai","elevenlabs","cloudflare"]),g=Object.freeze({openai:"/audio/transcriptions",elevenlabs:"/speech-to-text",cloudflare:"/run/<model>"});function S(e){const a=String(e||"").trim();if(!a)return null;try{return new Intl.Locale(a).language.toLowerCase()||null}catch{return null}}function k(e,{fetchImpl:a,now:o=()=>performance.now()}={}){if(!e||!["remote","container"].includes(e.kind)||!/^https?:\/\//.test(e.url||""))throw new Error("stt-remote: a remote provider needs a url");const t=e.adapter||"openai";if(!x.includes(t))throw new Error(`stt-remote: unknown adapter ${t}`);const r=e.url.replace(/\/+$/,"");return{provider:{kind:e.kind,url:e.url,adapter:t,model:e.model||(t==="elevenlabs"?"scribe_v1":t==="cloudflare"?"@cf/openai/whisper":"whisper-1")},async transcribe(i,{lang:l=null,langs:E=null,timeoutMs:f=3e4}={}){const m=o();if(t==="elevenlabs"){const n=new FormData;n.append("file",new Blob([h(i)],{type:"audio/wav"}),"segment.wav"),n.append("model_id",e.model||"scribe_v1"),l&&!E?.length&&n.append("language_code",l),n.append("tag_audio_events","false"),n.append("diarize","false");const s=await a(`${r}${g.elevenlabs}`,{method:"POST",headers:{accept:"application/json",...e.token?{"xi-api-key":e.token}:{}},body:n,signal:AbortSignal.timeout(f)});if(!s.ok){const p=await s.text().catch(()=>"");throw new Error(`elevenlabs transcription ${s.status}${p?`: ${p.slice(0,200)}`:""}`)}const u=await s.json().catch(()=>({})),c=S(u?.language_code);return{text:String(u?.text||"").trim(),ms:Math.round(o()-m),...c?{lang:c,confidence:Number(u?.language_probability)||null}:{}}}if(t==="cloudflare"){const n=e.model||"@cf/openai/whisper",s=h(i),u=/large-v3-turbo/.test(n),c=await a(`${r}/run/${n}`,{method:"POST",headers:{accept:"application/json","content-type":u?"application/json":"application/octet-stream",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:u?JSON.stringify({audio:Buffer.from(s).toString("base64"),...l?{language:l}:{}}):s,signal:AbortSignal.timeout(f)});if(!c.ok){const b=await c.text().catch(()=>"");throw new Error(`cloudflare transcription ${c.status}${b?`: ${b.slice(0,200)}`:""}`)}const p=await c.json().catch(()=>({}));return{text:String(p?.result?.text||"").trim(),ms:Math.round(o()-m)}}const w=new FormData;w.append("file",new Blob([h(i)],{type:"audio/wav"}),"segment.wav"),w.append("model",e.model||"whisper-1"),w.append("response_format","json"),l&&w.append("language",l);const d=await a(`${r}${g.openai}`,{method:"POST",headers:{accept:"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},body:w,signal:AbortSignal.timeout(f)});if(!d.ok){const n=await d.text().catch(()=>"");throw new Error(`${t} transcription ${d.status}${n?`: ${n.slice(0,200)}`:""}`)}const $=await d.json().catch(()=>({}));return{text:String($?.text||"").trim(),ms:Math.round(o()-m)}}}}export{x as STT_REMOTE_ADAPTERS,g as STT_REMOTE_PATHS,k as createRemoteTranscriber,S as languageFromService,h as wavFromFloat32};
package/src/tts-remote.js CHANGED
@@ -1 +1 @@
1
- import{secureFetch as k}from"./secure-fetch.js";import{redactSegments as w,segment as S}from"./redact.js";import{primaryProvider as $}from"./capability-config.js";const _=["local","openai","elevenlabs"];function b(e){return _.includes(String(e||""))}function E(e={}){const r=e.tts||{},t=$(e.capabilities?.tts,"tts");if(t&&typeof t=="object"){if(t.provider==="embedded")return null;const n=t.adapter||"openai";if(t.url&&b(n)){const c=r.remote||{};return{kind:n,baseUrl:String(t.url).replace(/\/+$/,""),model:t.model||c.model||(n==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:c.voice||(n==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:t.redact!==!1,token:t.token||""}}}const i=r.provider||"local";if(i==="local"||!b(i))return null;const a=r.remote||{};return{kind:i,baseUrl:String(a.baseUrl||(i==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1")).replace(/\/+$/,""),model:a.model||(i==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:a.voice||(i==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:a.redact!==!1}}function U(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}async function V({dest:e,text:r,voice:t,speed:i=1,auth:a,redaction:n,isPro:c=!0,onEgress:h=null,fetchImpl:y=null}={}){const l=a||e?.token||"";if(!e)throw new Error("no remote TTS destination configured");const u=t||e.voice;if(!U(u))throw new Error(`invalid remote voice id: ${u}`);let m=String(r),v=0;if(e.redact&&n){const o={text:m},T=await w([S(()=>o.text,g=>{o.text=g})],n,{isPro:c,onEgress:h});m=o.text,v=T?.count||0}const x=y||k,d={"Content-Type":"application/json"};let p,f;if(e.kind==="elevenlabs"){p=`${e.baseUrl}/text-to-speech/${encodeURIComponent(u)}`,f={text:m,model_id:e.model};const o=B(l);o&&(d["xi-api-key"]=o)}else p=`${e.baseUrl}/audio/speech`,f={model:e.model,input:m,voice:u,response_format:"wav",speed:i},l&&(d.Authorization=l.startsWith("Bearer ")?l:`Bearer ${l}`);const s=await x(p,{method:"POST",headers:d,body:JSON.stringify(f)});if(!s.ok){let o=`HTTP ${s.status}`;try{o=(await s.text()).slice(0,300)||o}catch{}throw new Error(`remote tts failed: ${o}`)}return{audio:Buffer.from(await s.arrayBuffer()),contentType:s.headers.get("content-type")||"audio/mpeg",redacted:v}}function B(e){const r=String(e||"").trim();return r.toLowerCase().startsWith("bearer ")?r.slice(7).trim():r}export{_ as TTS_PROVIDERS,U as isValidRemoteVoice,b as isValidTtsProvider,V as synthesizeRemote,E as ttsDestination};
1
+ import{secureFetch as g}from"./secure-fetch.js";import{redactSegments as T,segment as w}from"./redact.js";import{primaryProvider as $}from"./capability-config.js";const _=["local","openai","elevenlabs"];function b(e){return _.includes(String(e||""))}function z(e={}){const o=e.tts||{},t=$(e.capabilities?.tts,"tts",{destinations:e.destinations||[]});if(t&&typeof t=="object"){if(t.provider==="embedded")return null;const i=t.adapter||"openai";if(t.url&&b(i)){const c=o.remote||{};return{kind:i,baseUrl:String(t.url).replace(/\/+$/,""),model:t.model||c.model||(i==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:t.voice||c.voice||(i==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:t.redact!==!1,token:t.token||"",...t.endpoint?{endpoint:t.endpoint}:{}}}}const r=o.provider||"local";if(r==="local"||!b(r))return null;const a=o.remote||{};return{kind:r,baseUrl:String(a.baseUrl||(r==="elevenlabs"?"https://api.elevenlabs.io/v1":"https://api.openai.com/v1")).replace(/\/+$/,""),model:a.model||(r==="elevenlabs"?"eleven_multilingual_v2":"tts-1"),voice:a.voice||(r==="elevenlabs"?"21m00Tcm4TlvDq8ikWAM":"alloy"),redact:a.redact!==!1}}function A(e){return/^[A-Za-z0-9_-]{1,64}$/.test(String(e||""))}const E=new Set(["alloy","ash","ballad","coral","echo","fable","nova","onyx","sage","shimmer","verse"]);function P(e,o){const t=String(o||"");return t?e.endpoint?e.kind==="elevenlabs"?/^[A-Za-z0-9]{20}$/.test(t)?t:e.voice:E.has(t)?t:e.voice:t:e.voice}async function C({dest:e,text:o,voice:t,speed:r=1,auth:a,redaction:i,isPro:c=!0,onEgress:h=null,fetchImpl:y=null}={}){if(!e)throw new Error("no remote TTS destination configured");const l=e.endpoint&&e.token?e.token:a||e.token||"",u=P(e,t);if(!A(u))throw new Error(`invalid remote voice id: ${u}`);let m=String(o),f=0;if(e.redact&&i){const n={text:m},k=await T([w(()=>n.text,S=>{n.text=S})],i,{isPro:c,onEgress:h});m=n.text,f=k?.count||0}const x=y||g,p={"Content-Type":"application/json"};let d,v;if(e.kind==="elevenlabs"){d=`${e.baseUrl}/text-to-speech/${encodeURIComponent(u)}`,v={text:m,model_id:e.model};const n=U(l);n&&(p["xi-api-key"]=n)}else d=`${e.baseUrl}/audio/speech`,v={model:e.model,input:m,voice:u,response_format:"wav",speed:r},l&&(p.Authorization=l.startsWith("Bearer ")?l:`Bearer ${l}`);const s=await x(d,{method:"POST",headers:p,body:JSON.stringify(v)});if(!s.ok){let n=`HTTP ${s.status}`;try{n=(await s.text()).slice(0,300)||n}catch{}throw new Error(`remote tts failed: ${n}`)}return{audio:Buffer.from(await s.arrayBuffer()),contentType:s.headers.get("content-type")||"audio/mpeg",redacted:f}}function U(e){const o=String(e||"").trim();return o.toLowerCase().startsWith("bearer ")?o.slice(7).trim():o}export{_ as TTS_PROVIDERS,A as isValidRemoteVoice,b as isValidTtsProvider,P as remoteVoiceFor,C as synthesizeRemote,z as ttsDestination};
package/src/version.js CHANGED
@@ -1 +1 @@
1
- const o="0.133.3";export{o as VERSION};
1
+ const o="0.137.1";export{o as VERSION};