@chatpanel/gateway 0.136.2 → 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 +2 -2
- package/src/configstore.js +1 -1
- package/src/providers.js +1 -1
- package/src/tts-remote.js +1 -1
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.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.
|
|
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",
|
package/src/configstore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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 K,EMBEDDED_IDS as v,isEmbeddedModel as W}from"./embedded-models.js";import{capabilityList as g,isProviderList as O,listProblems as Y,primaryProvider as z,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,n]of Object.entries(e))if(n!=null)try{if(!L.test(i))throw m(`not an agent id: ${JSON.stringify(i)}`);const t=x(n);ee(t)||(o[i]=t)}catch(t){if(r)throw m(`sandbox.agents.${i}: ${t.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 n=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 t=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:n,required:t,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),D=(...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 n=w(r),t=f(i).mode;n.unknown&&o.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&&o.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(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:n}=k(i,o);Array.isArray(n.command)&&(n.command=JSON.stringify(n.command));const t=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,...n.agents||{}};return{CHATPANEL_SANDBOX:o?.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:o?.sandbox?.reads||c(r)||n.reads,CHATPANEL_SANDBOX_REQUIRED:n.required==="policy"?"policy":String(r.CHATPANEL_SANDBOX_REQUIRED||"")||(n.required?"on":""),CHATPANEL_SANDBOX_ALLOW_HOSTS:D(n.hosts,S(r.CHATPANEL_SANDBOX_ALLOW_HOSTS)).join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:D(n.write,S(r.CHATPANEL_SANDBOX_ALLOW_WRITE)).join(","),CHATPANEL_SANDBOX_DENY_READ:D(n.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,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[n]=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}:{}};if(o.provider==="embedded")return v.includes(e)&&o.model!=null?(W(e,o.model)||i(`capabilities.${e}.model must be one of ${K[e].map(t=>t.id).join(", ")}`),{provider:"embedded",model:o.model}):{provider:"embedded"};if(o.provider==="none"&&v.includes(e))return{provider:"none"};const n={...r};if("url"in o){const t=String(o.url||"").trim();t&&E(t);const s=d=>{try{return new URL(d).origin}catch{return d}};r.url&&t&&s(r.url)!==s(t)&&typeof o.token!="string"&&delete n.token,n.url=t}return typeof o.adapter=="string"&&/^[a-z-]+$/.test(o.adapter)&&(n.adapter=o.adapter),typeof o.model=="string"&&(n.model=o.model.trim()),typeof o.token=="string"&&(n.token=o.token),typeof o.calibrated=="boolean"&&(n.calibrated=o.calibrated),typeof o.redact=="boolean"&&(n.redact=o.redact),n.url?(n.provider="remote",delete n.service,delete n.hasToken,n):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: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(f(e.sandbox),o);return Array.isArray(i.command)&&(i.command=JSON.stringify(i.command)),{...i,...w().mode?{envMode:w().mode}:{},...c()?{envReads:c()}:{},...n.length?{locked:n,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,n])=>[i,O(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: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),n=Number(o.port)||(o.protocol==="https:"?443:80);return i&&n===(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 De(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 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(d=>typeof d=="string"&&d):[]};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 d=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;d&&(n.apiKey=d)}const t=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;t&&(n.service=t),(i.fromEndpoint===!0||i.fromEndpoint===void 0&&o.get(i.id)?.fromEndpoint===!0)&&(n.fromEndpoint=!0);const s=typeof i.endpointId=="string"&&/^[\w.:-]{1,80}$/.test(i.endpointId)?i.endpointId:o.get(i.id)?.endpointId;return s&&(n.endpointId=s),n}).filter((i,n,t)=>!i.endpointId||t.findIndex(s=>s.endpointId===i.endpointId)===n)}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 n of Q)n in r.registries&&(o[n]?i[n]=o[n]:delete i[n]);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 n=new Error(i);throw n.code="SHAPE",n};for(const i of["rerank","decide","stt","tts","detect","embed"]){if(!(i in r.capabilities))continue;const n=r.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(O(n)){const t=Y(i,n);t.length&&o(t[0]);const s=g(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(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:n.mode??g(e.capabilities[i],i).mode,providers:d},i))}else{const t=g(e.capabilities[i],i),s=R(i,t.providers[0]||{},n,o);P(e,i,_({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 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,De 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};
|
|
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/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 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}:{},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};
|
|
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/tts-remote.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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: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),
|
|
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.
|
|
1
|
+
const o="0.137.1";export{o as VERSION};
|