@reddb-io/red-skills 2.43.0 → 2.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.bundle.min.mjs +1 -1
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +298 -298
- package/dist/memory.bundle.min.mjs +2 -2
- package/dist/rsp.bundle.min.mjs +60 -59
- package/package.json +1 -1
|
@@ -37,7 +37,7 @@ var Dy=Object.create;var mi=Object.defineProperty;var jy=Object.getOwnPropertyDe
|
|
|
37
37
|
`}var bE=Dc.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function $E(){let e={};for(let t of bE){let r=Dc.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}var Vo=class{constructor(t){this._readBuffer=new Fo,this._stderrStream=null,this._serverParams=t,(t.stderr==="pipe"||t.stderr==="overlapped")&&(this._stderrStream=new wE)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._process=(0,$g.default)(this._serverParams.command,this._serverParams.args??[],{env:{...$E(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Dc.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{t()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{this._readBuffer.append(n),this.processReadBuffer()}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){if(this._process){let t=this._process;this._process=void 0;let r=new Promise(n=>{t.once("close",()=>{n()})});try{t.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),t.exitCode===null){try{t.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(t.exitCode===null)try{t.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(t){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=bg(t);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var xE=["conversations_list","conversation_get","messages_read","attachments_fetch","events_poll","events_wait","messages_send","channels_list","permissions_list_open","permissions_respond"];var qt=class e{client;transport;constructor(t,r){this.client=t,this.transport=r}static async connect(t={}){let r=new Vo({command:t.command??"hermes",args:t.args??["mcp","serve"],cwd:t.cwd,env:t.env??kE(),stderr:t.stderr??"pipe"}),n=new Zo({name:"brain-channel-bridge",version:"0.0.0"},{capabilities:{}});try{await n.connect(r);let o=new e(n,r);return await o.assertHermesContract(),o}catch(o){throw await n.close().catch(()=>{}),await r.close().catch(()=>{}),o}}async poll(t={}){let r=await this.callJson("events_poll",{after_cursor:t.afterCursor,session_key:t.sessionKey,limit:t.limit});return{events:EE(r).map(zE),nextCursor:xg(r,["next_cursor","nextCursor","cursor"]),raw:r}}async send(t,r){let n=await this.callJson("messages_send",{target:t,message:r});return{ok:!Ko(n,["error"])&&RE(n,["ok","success"],!0),target:t,messageId:Fe(n,["message_id","messageId","id"]),raw:n}}async channels(t={}){let r=await this.callJson("channels_list",{platform:t.platform});return{channels:TE(r).map(PE).filter(n=>n!=null),raw:r}}async close(){await this.client.close(),await this.transport.close().catch(()=>{})}async assertHermesContract(){let{tools:t}=await this.client.listTools(),r=new Set(t.map(o=>o.name)),n=xE.filter(o=>!r.has(o));if(n.length>0)throw new Error(`Hermes channel bridge is missing tool(s): ${n.join(", ")}`)}async callJson(t,r){let n=await this.client.callTool({name:t,arguments:SE(r)},dt);if(n.structuredContent&&Object.keys(n.structuredContent).length>0)return n.structuredContent;let i=(Array.isArray(n.content)?n.content:[]).filter(s=>s.type==="text").map(s=>s.text??"").join(`
|
|
38
38
|
`).trim();if(!i)return{};try{return JSON.parse(i)}catch{return{text:i}}}};function kE(){let e={};for(let[t,r]of Object.entries(process.env))typeof r=="string"&&(e[t]=r);return e}function SE(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function EE(e){if(Array.isArray(e))return e;if(!hr(e))return[];let t=e.events;if(Array.isArray(t))return t;let r=e.event;return r&&hr(r)?[r]:[]}function zE(e){return hr(e)?{id:Fe(e,["id","message_id","messageId"]),cursor:xg(e,["cursor"]),type:Fe(e,["type","event_type","eventType"]),platform:Fe(e,["platform"]),target:Fe(e,["target"]),sessionKey:Fe(e,["session_key","sessionKey"]),timestamp:Fe(e,["timestamp","created_at","createdAt"]),message:Fe(e,["message","text","content"]),raw:e}:{raw:e}}function TE(e){if(Array.isArray(e))return e;if(!hr(e))return[];for(let t of["channels","targets","conversations"]){let r=e[t];if(Array.isArray(r))return r}return[]}function PE(e){if(!hr(e))return null;let t=Fe(e,["target","id","session_key","sessionKey"]);return t?{target:t,platform:Fe(e,["platform"]),name:Fe(e,["name","display_name","displayName","chat_name","chatName"]),raw:e}:null}function Fe(e,t){let r=Ko(e,t);return typeof r=="string"?r:void 0}function RE(e,t,r){let n=Ko(e,t);return typeof n=="boolean"?n:r}function xg(e,t){let r=Ko(e,t);return typeof r=="string"||typeof r=="number"?r:void 0}function Ko(e,t){if(hr(e))for(let r of t){let n=e[r];if(n!=null)return n}}function hr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{mkdir as fP,writeFile as mP}from"node:fs/promises";import{join as by}from"node:path";import{basename as wy}from"node:path";import{createHash as AE,randomUUID as Mc}from"node:crypto";import{spawn as CE}from"node:child_process";import{constants as jc}from"node:fs";import{readFileSync as NE}from"node:fs";import{mkdir as Tg,open as OE,rm as Pg}from"node:fs/promises";import{tmpdir as DE}from"node:os";import{dirname as qc,join as st,resolve as Bc}from"node:path";import{fileURLToPath as jE}from"node:url";import{createConnection as IE}from"node:net";async function Ho(e,t){let r=e.timeoutMs??1e3;return await new Promise((n,o)=>{let i=IE(e.socketPath),s=!1,a="",c=setTimeout(()=>{l(()=>o(new Error("resident rsp server timed out"))),i.destroy()},r);function l(u){s||(s=!0,clearTimeout(c),u())}i.on("connect",()=>{i.write(`${JSON.stringify(t)}
|
|
39
39
|
`)}),i.on("data",u=>{a+=u.toString("utf8");let d=a.indexOf(`
|
|
40
|
-
`);if(d<0)return;let p=a.slice(0,d);l(()=>{try{n(JSON.parse(p))}catch(f){o(f)}}),i.end()}),i.on("error",u=>l(()=>o(u))),i.on("close",()=>{s||l(()=>o(new Error("resident rsp server closed without response")))})})}var ME=108;function Wo(e){let t=VE(e)??Bc(e),r=FE(t);return{rootDir:t,socketPath:st(r,"rsp.sock"),lockPath:st(r,"rsp.lock"),wakeLockPath:st(t,".red","tmp","rsp.wake.lock"),summaryPath:st(t,".red","tmp","rsp-status-summary.json")}}var Go=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await qE(this.paths,this.config);let r=await Ho(this.paths,{...t,id:Mc()});if(!r.ok)throw new Error(r.error);return r.value}};async function qE(e,t){if(await Tg(qc(e.socketPath),{recursive:!0,mode:448}),await Eg(e.socketPath,t))return;let r=await LE(e.lockPath);if(r)try{if(await Eg(e.socketPath,t))return;await BE(e.socketPath);let n=ZE(e,t);await kg(e.socketPath,n);return}finally{await r.close(),await Pg(e.lockPath,{force:!0})}await kg(e.socketPath)}async function Jo(e,t=200){try{return await Rg(e,t)!=null}catch{return!1}}async function Rg(e,t=200){let r=await Ho({socketPath:e,timeoutMs:t},{id:Mc(),op:"ping"});return r.ok?WE(r.value)?{version:JE(r.value.version)}:{}:null}async function kg(e,t){let r=Date.now()+5e3,n;for(;Date.now()<r;){if(await Jo(e))return;if(t&&t.exitCode!=null)throw new Error(`resident rsp server exited before ready (${t.exitCode})`);await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error("resident rsp server did not start")}async function BE(e){await Pg(e,{force:!0})}async function LE(e){await Tg(qc(e),{recursive:!0,mode:448});try{return await OE(e,jc.O_CREAT|jc.O_EXCL|jc.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function ZE(e,t){let[r,n]=UE(t),o=CE(r,[...n,"server","--socket",e.socketPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--resident-version",t.clientVersion??"0.0.0-dev"],{cwd:e.rootDir,detached:!0,stdio:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return o.unref(),o}function UE(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?Bc(process.argv[1]):jE(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function FE(e){let t=AE("sha256").update(e).digest("hex").slice(0,20),r=process.env.XDG_RUNTIME_DIR;if(r){let o=st(r,"red-skills",t);if(st(o,"rsp.sock").length<ME)return o}let n=typeof process.getuid=="function"?process.getuid():"nouid";return st(DE(),`red-skills-${n}`,t)}function VE(e){let t=Bc(e);for(let r=0;r<32;r++){try{if(Sg(st(t,".red","config.yaml"))!=null||Sg(st(t,".git","HEAD"))!=null)return t}catch{}let n=qc(t);if(n===t)return null;t=n}return null}function Sg(e){try{return NE(e,"utf8")}catch{return null}}async function Eg(e,t){let r=await Rg(e).catch(()=>null);return r?HE(t.clientVersion,r.version)?(await KE(e,t.clientVersion),await QE(e),!1):!0:!1}async function KE(e,t){try{await Ho({socketPath:e,timeoutMs:200},{id:Mc(),op:"handover",clientVersion:t})}catch{}}function HE(e,t){return!e||!t?!1:GE(e,t)>0}function GE(e,t){let r=zg(e),n=zg(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function zg(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function WE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function JE(e){return typeof e=="string"&&e.length>0?e:void 0}async function QE(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await Jo(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as YE}from"node:child_process";var Zc=["supports","contradicts","related_to"];function Uc(e){return{rid:e.rid,id:e.properties.id,title:e.properties.title,kind:e.kind,content:e.properties.content,tags:e.properties.tags}}function Fc(e){return typeof e=="string"&&Zc.includes(e)}function gr(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function Ig(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
|
|
40
|
+
`);if(d<0)return;let p=a.slice(0,d);l(()=>{try{n(JSON.parse(p))}catch(f){o(f)}}),i.end()}),i.on("error",u=>l(()=>o(u))),i.on("close",()=>{s||l(()=>o(new Error("resident rsp server closed without response")))})})}var ME=108;function Wo(e){let t=VE(e)??Bc(e),r=FE(t);return{rootDir:t,socketPath:st(r,"rsp.sock"),lockPath:st(r,"rsp.lock"),wakeLockPath:st(t,".red","tmp","rsp.wake.lock"),summaryPath:st(t,".red","tmp","rsp-status-summary.json")}}var Go=class{constructor(t,r){this.paths=t;this.config=r}async request(t){await qE(this.paths,this.config);let r=await Ho(this.paths,{...t,id:Mc()});if(!r.ok)throw new Error(r.error);return r.value}};async function qE(e,t){if(await Tg(qc(e.socketPath),{recursive:!0,mode:448}),await Eg(e.socketPath,t))return;let r=await LE(e.lockPath);if(r)try{if(await Eg(e.socketPath,t))return;await BE(e.socketPath);let n=ZE(e,t);await kg(e.socketPath,n);return}finally{await r.close(),await Pg(e.lockPath,{force:!0})}await kg(e.socketPath)}async function Jo(e,t=200){try{return await Rg(e,t)!=null}catch{return!1}}async function Rg(e,t=200){let r=await Ho({socketPath:e,timeoutMs:t},{id:Mc(),op:"ping"});return r.ok?WE(r.value)?{version:JE(r.value.version)}:{}:null}async function kg(e,t){let r=Date.now()+5e3,n;for(;Date.now()<r;){if(await Jo(e))return;if(t&&t.exitCode!=null)throw new Error(`resident rsp server exited before ready (${t.exitCode})`);await new Promise(o=>setTimeout(o,50))}throw n instanceof Error?n:new Error("resident rsp server did not start")}async function BE(e){await Pg(e,{force:!0})}async function LE(e){await Tg(qc(e),{recursive:!0,mode:448});try{return await OE(e,jc.O_CREAT|jc.O_EXCL|jc.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function ZE(e,t){let[r,n]=UE(t),o=CE(r,[...n,"server","--socket",e.socketPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--idle-ms",String(t.idleMs??3e5),"--resident-version",t.clientVersion??"0.0.0-dev"],{cwd:e.rootDir,detached:!0,stdio:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return o.unref(),o}function UE(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?Bc(process.argv[1]):jE(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function FE(e){let t=AE("sha256").update(e).digest("hex").slice(0,20),r=process.env.XDG_RUNTIME_DIR;if(r){let o=st(r,"red-skills",t);if(st(o,"rsp.sock").length<ME)return o}let n=typeof process.getuid=="function"?process.getuid():"nouid";return st(DE(),`red-skills-${n}`,t)}function VE(e){let t=Bc(e);for(let r=0;r<32;r++){try{if(Sg(st(t,".red","config.yaml"))!=null||Sg(st(t,".git","HEAD"))!=null)return t}catch{}let n=qc(t);if(n===t)return null;t=n}return null}function Sg(e){try{return NE(e,"utf8")}catch{return null}}async function Eg(e,t){let r=await Rg(e).catch(()=>null);return r?HE(t.clientVersion,r.version)?(await KE(e,t.clientVersion),await QE(e),!1):!0:!1}async function KE(e,t){try{await Ho({socketPath:e,timeoutMs:200},{id:Mc(),op:"handover",clientVersion:t})}catch{}}function HE(e,t){return!e||!t?!1:GE(e,t)>0}function GE(e,t){let r=zg(e),n=zg(t);return!r||!n?0:r.major-n.major||r.minor-n.minor||r.patch-n.patch}function zg(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function WE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function JE(e){return typeof e=="string"&&e.length>0?e:void 0}async function QE(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await Jo(e,50))return;await new Promise(r=>setTimeout(r,50))}}import{spawn as YE}from"node:child_process";var Zc=["supports","contradicts","related_to"];function Uc(e){return{rid:e.rid,id:e.properties.id,title:e.properties.title,kind:e.kind,content:e.properties.content,tags:e.properties.tags}}function Fc(e){return typeof e=="string"&&Zc.includes(e)}function gr(e){return e.properties.metadata?.derived===!0||typeof e.properties.metadata?.derived_kind=="string"}function Ig(e){return[e.properties.title,e.kind,...e.properties.tags,e.properties.content].join(`
|
|
41
41
|
`)}function XE(e){return{deriveConnections(t){return tz(e,t)}}}function Ag(e=process.env){let t=e.RED_BRAIN_AUTOLINK_AFK_COMMAND??e.RED_BRAIN_AUTOLINK_HEADLESS_COMMAND;if(t)return XE({command:t,args:rz(e.RED_BRAIN_AUTOLINK_AFK_ARGS??e.RED_BRAIN_AUTOLINK_HEADLESS_ARGS),cwd:e.RED_BRAIN_AUTOLINK_AFK_CWD??e.RED_BRAIN_AUTOLINK_HEADLESS_CWD,env:e,timeoutMs:nz(e.RED_BRAIN_AUTOLINK_AFK_TIMEOUT_MS)??6e4})}function ez(e){let t=JSON.parse(oz(e));return(Array.isArray(t)?t:Lc(t)&&Array.isArray(t.connections)?t.connections:[]).filter(iz).map(n=>({from:n.from,to:n.to,kind:n.kind,reason:typeof n.reason=="string"?n.reason:void 0,metadata:Lc(n.metadata)?n.metadata:void 0}))}async function tz(e,t){let r=YE(e.command,e.args??[],{cwd:e.cwd,env:e.env,stdio:["pipe","pipe","pipe"]}),n=[],o=[],i,s=new Promise((a,c)=>{r.once("error",c),r.stdout.on("data",l=>n.push(l)),r.stderr.on("data",l=>o.push(l)),r.once("close",l=>a(l??0)),e.timeoutMs&&e.timeoutMs>0&&(i=setTimeout(()=>{r.kill("SIGTERM"),c(new Error(`Brain autolink AFK headless provider timed out after ${e.timeoutMs}ms`))},e.timeoutMs))});r.stdin.end(JSON.stringify(t));try{let a=await s;if(a!==0){let c=Buffer.concat(o).toString("utf8").trim();throw new Error(`Brain autolink AFK headless provider exited ${a}${c?`: ${c}`:""}`)}return ez(Buffer.concat(n).toString("utf8"))}finally{i&&clearTimeout(i)}}function rz(e){if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error("RED_BRAIN_AUTOLINK_AFK_ARGS must be a JSON array of strings");return t}function nz(e){if(e==null||e==="")return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function oz(e){let t=e.trim();return(t.match(/```(?:json)?\s*([\s\S]*?)\s*```/i)?.[1]??t).trim()}function iz(e){return Lc(e)&&(typeof e.from=="number"||typeof e.from=="string")&&(typeof e.to=="number"||typeof e.to=="string")&&Fc(e.kind)}function Lc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{existsSync as Qo}from"node:fs";import{mkdir as sz,readFile as Vc,writeFile as az}from"node:fs/promises";import{dirname as Kc,isAbsolute as cz,join as yr,resolve as bt}from"node:path";var Yo="file://./.red/brain/brain.rdb",uz="RED_BRAIN_ROOT",lz="brain.root";async function dz(e=process.cwd(),t={}){let n=(t.env??process.env)[uz];if(n)return bt(e,n);let o=await pz(e);if(o)return o;let i=bt(e),s=null;for(;;){let a=yr(i,".red");if(Qo(a)&&(s??=i,Qo(yr(a,"brain"))||Qo(yr(a,lz))))return i;let c=Kc(i);if(c===i)return s??bt(e);i=c}}async function pz(e){let t=bt(e);for(;;){let r=yr(t,".red","config.yaml");try{let o=await Vc(r,"utf8"),i=fz(o);if(i)return bt(t,i)}catch(o){if(o.code!=="ENOENT")throw o}let n=Kc(t);if(n===t)return null;t=n}}function fz(e){let t=mz(e);return t["plugins.brain.rootDir"]??t["plugins.brain.root"]??t["plugins.brain.root_dir"]??t["brain.rootDir"]??t["brain.root"]??t["brain.root_dir"]??null}function mz(e){let t={},r=[],n=[];for(let o of e.split(`
|
|
42
42
|
`)){let i=o.replace(/\r$/,"");if(!/".*"/.test(i)&&!/'.*'/.test(i)){let p=i.indexOf("#");p>=0&&(i=i.slice(0,p))}if(i.replace(/\s/g,"")==="")continue;let s=i.match(/^ */)?.[0].length??0;if(s%2!==0)continue;let a=i.slice(s).replace(/\s+$/,""),c=a.indexOf(":");if(c<0||!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(a.slice(0,c)))continue;let l=a.slice(0,c),u=a.slice(c+1).replace(/^\s+/,"");for((u.startsWith('"')&&u.endsWith('"')&&u.length>=2||u.startsWith("'")&&u.endsWith("'")&&u.length>=2)&&(u=u.slice(1,-1));n.length>0&&n[n.length-1]>=s;)r.pop(),n.pop();let d=r.length>0?`${r.join(".")}.${l}`:l;u===""?(r.push(l),n.push(s)):t[d]=u}return t}function Cg(e){return yr(bt(e),".red","brain","config.yaml")}function hz(e){return yr(bt(e),".env")}async function gz(e){let t=Cg(e);return Qo(t)||(await sz(Kc(t),{recursive:!0}),await az(t,`connection_string: ${Yo}
|
|
43
43
|
`,"utf8")),t}async function yz(e){let t=Cg(e);try{let r=await Vc(t,"utf8");return _z(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}function _z(e){let t=e.split(/\r?\n/).map(n=>n.trim()).find(n=>n.startsWith("connection_string:"));if(!t)return{connection_string:Yo};let r=t.slice(18).trim();return{connection_string:Ng(r)||Yo}}function Ng(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}async function Og(e=process.cwd()){let t=await dz(e),r=await gz(t),n=await yz(t)??{connection_string:Yo},o=await vz(t),i=n.connection_string,s=wz(i,o);return{rootDir:t,configPath:r,rawConnectionString:i,connectionString:bz(t,s)}}async function vz(e){let t={...process.env};try{let r=await Vc(hz(e),"utf8");for(let n of r.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let s=o.slice(0,i).trim(),a=Ng(o.slice(i+1).trim());t[s]==null&&(t[s]=a)}}catch(r){if(r.code!=="ENOENT")throw r}return t}function wz(e,t){return e.replace(/\$(\w+)|\$\{([^}]+)\}/g,(r,n,o)=>{let i=String(n??o),s=t[i];if(s==null||s==="")throw new Error(`Brain connection_string references missing environment variable ${i}`);return s})}function bz(e,t){if(!t.startsWith("file://"))return t;let r=t.slice(7);return cz(r)?t:`file://${bt(e,r)}`}import{resolve as $z}from"node:path";var xz=".red/tmp/red-skills.rdb",kz=7,Sz=64*1024*1024;function jg(e){return e.connectionString.startsWith("file://")?e.connectionString.slice(7)===qg(e.rootDir):!1}async function Mg(e){let t=Wo(e.rootDir),r=new Go(t,zz(e.rootDir));return await r.request({op:"ping"}),new Hc(r)}function Ez(e){return`file://${qg(e)}`}function qg(e){return $z(e,xz)}function zz(e){return{storeUri:Ez(e),ttlDays:kz,byteBudget:Sz,serverCommand:process.env.RSP_BIN??"rsp"}}var Hc=class{constructor(t){this.client=t}async close(){}async status(){let t=await this.request("status");return Tz(t)?t:{}}async capture(t){return await this.request("capture",t)}async getArtifact(t){return await this.request("getArtifact",{ridOrId:t})}async listArtifacts(){return await this.request("listArtifacts")}async search(t,r=10,n={}){return await this.request("search",{query:t,limit:r,options:Dg(n)})}async think(t,r=8,n={}){return await this.request("think",{query:t,limit:r,options:Dg(n)})}async link(t){return await this.request("link",t)}async backlinks(t){return await this.request("backlinks",{target:t})}async listConnections(){return await this.request("listConnections")}async eventKpis(t={}){return await this.request("eventKpis",t)}async appendOutcomeEvent(t){return await this.request("appendOutcomeEvent",t)}async replayOutcomeEvents(){return await this.request("replayOutcomeEvents")}async loadModelTierBanditDocument(){return await this.request("loadModelTierBanditDocument")}async saveModelTierBanditDocument(t){return await this.request("saveModelTierBanditDocument",t)}async refreshModelTierBanditDocument(){return await this.request("refreshModelTierBanditDocument")}async request(t,r){return await this.client.request({op:"brain",action:t,payload:r})}};function Dg(e){return{...e,excludeRids:e.excludeRids?[...e.excludeRids]:void 0}}function Tz(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Pz=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",Rz=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function";async function Bg(e,t){return Pz?Az(e,t):Rz?Nz(e,t):Iz(e,t)}async function Iz(e,t){let{spawn:r}=await import("node:child_process"),n=r(e,t,{stdio:["pipe","pipe","inherit"]});return{runtime:"node",stdin:{write(o){return new Promise((i,s)=>{n.stdin.write(o,a=>a?s(a):i())})},end(){n.stdin.end()}},stdout:n.stdout,kill(){n.kill("SIGTERM")},wait(){return new Promise(o=>{n.on("exit",i=>o(i??0))})}}}function Az(e,t){let r=globalThis.Bun.spawn({cmd:[e,...t],stdin:"pipe",stdout:"pipe",stderr:"inherit"}),n=r.stdin.getWriter?r.stdin.getWriter():null;return{runtime:"bun",stdin:{async write(o){n?await n.write(o):(r.stdin.write(o),await r.stdin.flush())},end(){n?n.close():r.stdin.end()}},stdout:Cz(r.stdout),kill(){r.kill()},wait(){return r.exited}}}async function*Cz(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}async function Nz(e,t){let n=new globalThis.Deno.Command(e,{args:t,stdin:"piped",stdout:"piped",stderr:"inherit"}).spawn(),o=n.stdin.getWriter();return{runtime:"deno",stdin:{async write(i){await o.write(i)},end(){try{o.close()}catch{}}},stdout:Oz(n.stdout),kill(){try{n.kill("SIGTERM")}catch{}},async wait(){return(await n.status).code??0}}}async function*Oz(e){let t=e.getReader();try{for(;;){let{value:r,done:n}=await t.read();if(n)return;yield r}}finally{t.releaseLock()}}import{fileURLToPath as Mz}from"node:url";import{dirname as qz,resolve as Bz,join as ej}from"node:path";import{existsSync as Dz}from"node:fs";import{join as jz}from"node:path";function Lg(e){if(!e||typeof e!="object")throw new TypeError("resolveBin: options object required");let{name:t,packageRoot:r,envVar:n}=e;if(typeof t!="string"||t==="")throw new TypeError("resolveBin: `name` must be a non-empty string");if(typeof r!="string"||r==="")throw new TypeError("resolveBin: `packageRoot` must be a non-empty string");if(typeof n!="string"||n==="")throw new TypeError("resolveBin: `envVar` must be a non-empty string");let o=process.env?.[n];if(typeof o=="string"&&o!=="")return o;let i=jz(r,"bin",t);if(Dz(i))return i;throw new Error(`reddb: binary "${t}" not found.
|
|
@@ -74,7 +74,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
74
74
|
`:`[${n[c]}\r
|
|
75
75
|
]`;continue}o+=n[c],n[c]==="\\"?i=!0:s&&n[c]==="]"?s=!1:!s&&n[c]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function uc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Be(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=cc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=ac(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function C_(t,e){if(e.mapStrategy==="record")return uc(t,e);let r=Q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Be(e),n=Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Be(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function O_(t){let e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(n.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function N_(t){return t.target==="openAi"?void 0:{not:Be({...t,currentPath:[...t.currentPath,"not"]})}}function j_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var is={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function M_(t,e){if(e.target==="openApi3")return D_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in is&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,i)=>{let s=is[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:r.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(i=>!n.includes(i))],[])};return D_(t,e)}var D_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Q(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function A_(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:is[t.innerType._def.typeName],nullable:!0}:{type:[is[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function q_(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",gf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?he(r,"minimum",n.value,n.message,e):he(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),he(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?he(r,"maximum",n.value,n.message,e):he(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),he(r,"maximum",n.value,n.message,e));break;case"multipleOf":he(r,"multipleOf",n.value,n.message,e);break}return r}function Z_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],i=t.shape();for(let a in i){let c=i[a];if(c===void 0||c._def===void 0)continue;let l=Mz(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let f=Q(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});f!==void 0&&(n.properties[a]=f,l||o.push(a))}o.length&&(n.required=o);let s=Dz(t,e);return s!==void 0&&(n.additionalProperties=s),n}function Dz(t,e){if(t.catchall._def.typeName!=="ZodNever")return Q(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Mz(t){try{return t.isOptional()}catch{return!0}}var L_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Q(t.innerType._def,e);let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Be(e)},r]}:Be(e)};var F_=(t,e)=>{if(e.pipeStrategy==="input")return Q(t.in._def,e);if(e.pipeStrategy==="output")return Q(t.out._def,e);let r=Q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function U_(t,e){return Q(t.type._def,e)}function V_(t,e){let n={type:"array",uniqueItems:!0,items:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&he(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&he(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function H_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function B_(t){return{not:Be(t)}}function W_(t){return Be(t)}var J_=(t,e)=>Q(t.innerType._def,e);var K_=(t,e,r)=>{switch(e){case D.ZodString:return cc(t,r);case D.ZodNumber:return q_(t,r);case D.ZodObject:return Z_(t,r);case D.ZodBigInt:return $_(t,r);case D.ZodBoolean:return k_();case D.ZodDate:return yf(t,r);case D.ZodUndefined:return B_(r);case D.ZodNull:return j_(r);case D.ZodArray:return x_(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return M_(t,r);case D.ZodIntersection:return z_(t,r);case D.ZodTuple:return H_(t,r);case D.ZodRecord:return uc(t,r);case D.ZodLiteral:return E_(t,r);case D.ZodEnum:return R_(t);case D.ZodNativeEnum:return O_(t);case D.ZodNullable:return A_(t,r);case D.ZodOptional:return L_(t,r);case D.ZodMap:return C_(t,r);case D.ZodSet:return V_(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return U_(t,r);case D.ZodNaN:case D.ZodNever:return N_(r);case D.ZodEffects:return P_(t,r);case D.ZodAny:return Be(r);case D.ZodUnknown:return W_(r);case D.ZodDefault:return T_(t,r);case D.ZodBranded:return ac(t,r);case D.ZodReadonly:return J_(t,r);case D.ZodCatch:return S_(t,r);case D.ZodPipeline:return F_(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}};function Q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==v_)return a}if(n&&!r){let a=Az(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=K_(t,t.typeName,e),s=typeof i=="function"?Q(i(),e):i;if(s&&qz(t,e,s),e.postProcess){let a=e.postProcess(s,t,e);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var Az=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:sc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Be(e)):e.$refStrategy==="seen"?Be(e):void 0}},qz=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var bf=(t,e)=>{let r=w_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,f])=>({...c,[l]:Q(f._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Be(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=Q(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Be(r),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...i,[r.definitionPath]:n}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:i}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function Zz(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function wf(t,e){return Kt(t)?Fd(t,{target:Zz(e?.target),io:e?.pipeStrategy??"input"}):bf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function xf(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Da(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function $f(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var Lz=6e4,lc=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ua,r=>{this._oncancel(r)}),this.setNotificationHandler(Ha,r=>{this._onprogress(r)}),this.setRequestHandler(Va,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ba,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ja,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,f=this._requestResolvers.get(l);if(f)if(this._requestResolvers.delete(l),a.type==="response")f(c);else{let p=c,w=new B(p.error.code,p.error.message,p.error.data);f(w)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new B(G.InvalidParams,`Task not found: ${i}`);if(!cn(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(cn(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[an]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Ka,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new B(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Xa,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(cn(o.status))throw new B(G.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new B(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof B?o:new B(G.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),B.fromError(G.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Gi(i)||a_(i)?this._onresponse(i):tf(i)?this._onrequest(i,s):s_(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=B.fromError(G.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[an]?.taskId;if(n===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:f,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(f).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=n_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async f=>{if(s.signal.aborted)return;let p={relatedRequestId:e.id};i&&(p.relatedTask={taskId:i}),await this.notification(f,p)},sendRequest:async(f,p,w)=>{if(s.signal.aborted)throw new B(G.ConnectionClosed,"Request was cancelled");let b={...w,relatedRequestId:e.id};i&&!b.relatedTask&&(b.relatedTask={taskId:i});let g=b.relatedTask?.taskId??i;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(f,p,b)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async f=>{if(s.signal.aborted)return;let p={result:f,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async f=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:G.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(f=>this._onerror(new Error(`Failed to send response: ${f}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Gi(e))n(e);else{let s=new B(e.error.code,e.error.message,e.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Gi(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Gi(e))o(e);else{let s=B.fromError(e.error.code,e.error.message,e.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(s){yield{type:"error",error:s instanceof B?s:new B(G.InternalError,String(s))}}return}let i;try{let s=await this.request(e,jo,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new B(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},cn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new B(G.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(G.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof B?s:new B(G.InternalError,String(s))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((l,f)=>{let p=O=>{f(O)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(O){p(O);return}n?.signal?.throwIfAborted();let w=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:w};n?.onprogress&&(this._progressHandlers.set(w,n.onprogress),b.params={...e.params,_meta:{...e.params?._meta||{},progressToken:w}}),a&&(b.params={...b.params,task:a}),c&&(b.params={...b.params,_meta:{...b.params?._meta||{},[an]:c}});let g=O=>{this._responseHandlers.delete(w),this._progressHandlers.delete(w),this._cleanupTimeout(w),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:w,reason:String(O)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(Z=>this._onerror(new Error(`Failed to send cancellation: ${Z}`)));let z=O instanceof B?O:new B(G.RequestTimeout,String(O));f(z)};this._responseHandlers.set(w,O=>{if(!n?.signal?.aborted){if(O instanceof Error)return f(O);try{let z=on(r,O.result);z.success?l(z.data):f(z.error)}catch(z){f(z)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let x=n?.timeout??Lz,S=()=>g(B.fromError(G.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout(w,x,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let N=c?.taskId;if(N){let O=z=>{let Z=this._responseHandlers.get(w);Z?Z(z):this._onerror(new Error(`Response handler missing for side-channeled request ${w}`))};this._requestResolvers.set(w,O),this._enqueueTaskMessage(N,{type:"request",message:b,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(w),f(z)})}else this._transport.send(b,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(O=>{this._cleanupTimeout(w),f(O)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Wa,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ga,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},l_,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[an]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[an]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[an]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let n=xf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=$f(e,o);return Promise.resolve(r(s,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=xf(e);this._notificationHandlers.set(n,o=>{let i=$f(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&tf(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new B(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new B(G.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new B(G.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=ts.parse({method:"notifications/tasks/status",params:a});await this.notification(c),cn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new B(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(cn(a.status))throw new B(G.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let l=ts.parse({method:"notifications/tasks/status",params:c});await this.notification(l),cn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function G_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function X_(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let s=r[o];G_(s)&&G_(i)?r[o]={...s,...i}:r[o]=i}return r}var Fw=la(um(),1),Uw=la(Lw(),1);function Vj(){let t=new Fw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Uw.default)(t),t}var Hc=class{constructor(e){this._ajv=e??Vj()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Bc=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(f=>f.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(f=>f.type==="tool_use");if(s){if(i.some(f=>f.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let f=new Set(c.filter(w=>w.type==="tool_use").map(w=>w.id)),p=new Set(i.filter(w=>w.type==="tool_result").map(w=>w.toolUseId));if(f.size!==p.size||![...f].every(w=>p.has(w)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},os,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:i},Ao,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Vw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Hw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Wc=class extends lc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ns.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Hc,this.setRequestHandler(of,n=>this._oninitialize(n)),this.setNotificationHandler(sf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(pf,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=ns.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Bc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=X_(this._capabilities,e)}setRequestHandler(e,r){let o=sn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Kt(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,l)=>{let f=on(Mo,c);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new B(G.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:p}=f.data,w=await Promise.resolve(r(c,l));if(p.task){let g=on(jo,w);if(!g.success){let x=g.error instanceof Error?g.error.message:String(g.error);throw new B(G.InvalidParams,`Invalid task creation result: ${x}`)}return g.data}let b=on(oc,w);if(!b.success){let g=b.error instanceof Error?b.error.message:String(b.error);throw new B(G.InvalidParams,`Invalid tools/call result: ${g}`)}return b.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Hw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Vw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:e_.includes(r)?r:Qd,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Fa)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(l=>l.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(l=>l.type==="tool_use");if(i){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),f=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==f.size||![...l].every(p=>f.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},mf,r):this.request({method:"sampling/createMessage",params:e},os,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Ao,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Ao,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new B(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof B?s:new B(G.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},hf,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Ww=Symbol.for("mcp.completable");function ym(t){return!!t&&typeof t=="object"&&Ww in t}function Jw(t){return t[Ww]?.complete}var Bw;(function(t){t.Completable="McpCompletable"})(Bw||(Bw={}));var Hj=/^[A-Za-z0-9._-]{1,128}$/;function Bj(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!Hj.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Wj(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function _m(t){let e=Bj(t);return Wj(t,e.warnings),e.isValid}var Jc=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var Kc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Wc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Jc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(nc)),this.server.assertCanSetRequestHandler(yn(Mo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(nc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Oo(r.inputSchema);return o?wf(o,{strictUnions:!0,pipeStrategy:"input"}):Jj})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Oo(r.outputSchema);o&&(n.outputSchema=wf(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Mo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new B(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new B(G.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new B(G.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof B&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let i=Oo(e.inputSchema)??e.inputSchema,s=await Na(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=ja(a);throw new B(G.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new B(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Oo(e.outputSchema),i=await Na(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=ja(s);throw new B(G.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(e.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),i=e.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,l=a.task,f=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(w=>setTimeout(w,f));let p=await n.taskStore.getTask(c);if(!p)throw new B(G.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(yn(ic)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ic,async e=>{switch(e.params.ref.type){case"ref/prompt":return g_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return y_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new B(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return js;let i=sn(n.argsSchema)?.[e.params.argument.name];if(!ym(i))return js;let s=Jw(i);if(!s)return js;let a=await s(e.params.argument.value,e.params.context);return Gw(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return js;throw new B(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return js;let i=await o(e.params.argument.value,e.params.context);return Gw(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(Ya)),this.server.assertCanSetRequestHandler(yn(Qa)),this.server.assertCanSetRequestHandler(yn(ec)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ya,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Qa,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ec,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new B(G.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new B(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(tc)),this.server.assertCanSetRequestHandler(yn(rc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(tc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Kj(r.argsSchema):void 0}))})),this.server.setRequestHandler(rc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new B(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Oo(n.argsSchema),i=await Na(o,e.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",l=ja(c);throw new B(G.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,r,n,o,i){let s={name:e,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(e,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=s)),typeof l.title<"u"&&(s.title=l.title),typeof l.template<"u"&&(s.resourceTemplate=l.template),typeof l.metadata<"u"&&(s.metadata=l.metadata),typeof l.callback<"u"&&(s.readCallback=l.callback),typeof l.enabled<"u"&&(s.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Qn(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Qn(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,o&&Object.values(o).some(c=>{let l=c instanceof zt?c._def?.innerType:c;return ym(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,r,n,o,i,s,a,c,l){_m(e);let f={title:r,description:n,inputSchema:Kw(o),outputSchema:Kw(i),annotations:s,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>f.update({enabled:!1}),enable:()=>f.update({enabled:!0}),remove:()=>f.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&_m(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=f)),typeof p.title<"u"&&(f.title=p.title),typeof p.description<"u"&&(f.description=p.description),typeof p.paramsSchema<"u"&&(f.inputSchema=Qn(p.paramsSchema)),typeof p.outputSchema<"u"&&(f.outputSchema=Qn(p.outputSchema)),typeof p.callback<"u"&&(f.handler=p.callback),typeof p.annotations<"u"&&(f.annotations=p.annotations),typeof p._meta<"u"&&(f._meta=p._meta),typeof p.enabled<"u"&&(f.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=f,this.setToolRequestHandlers(),this.sendToolListChanged(),f}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(vm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!vm(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,i,s,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(e,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(e,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var Jj={type:"object",properties:{}};function Xw(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Yw(t){return"_def"in t||"_zod"in t||Xw(t)}function vm(t){return typeof t!="object"||t===null||Yw(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Xw)}function Kw(t){if(t){if(vm(t))return Qn(t);if(!Yw(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Kj(t){let e=sn(t);return e?Object.entries(e).map(([r,n])=>{let o=Ey(n),i=Iy(n);return{name:r,description:o,required:!i}}):[]}function yn(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Da(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Gw(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var js={completion:{values:[],hasMore:!1}};import ex from"node:process";var Gc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
76
76
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Gj(r)}clear(){this._buffer=void 0}};function Gj(t){return c_.parse(JSON.parse(t))}function Qw(t){return JSON.stringify(t)+`
|
|
77
|
-
`}var Xc=class{constructor(e=ex.stdin,r=ex.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Qw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function tx(t){let e={app:t,version:Xj(ni("__RED_BUILD_VERSION__",()=>"2.
|
|
77
|
+
`}var Xc=class{constructor(e=ex.stdin,r=ex.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Qw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function tx(t){let e={app:t,version:Xj(ni("__RED_BUILD_VERSION__",()=>"2.44.0")??"0.0.0-dev"),gitSha:ni("__RED_BUILD_GIT_SHA__",()=>"525a5c20b8019baf3432c78899c6d8d5cd266889")??"unknown",buildTime:ni("__RED_BUILD_TIME__",()=>"2026-07-13T03:44:30-03:00")??"unknown",bundleAsset:ni("__RED_BUNDLE_ASSET__",()=>"code-nav.bundle.min.mjs")??"unknown"},r=ni("__REDDB_SDK_VERSION__",()=>""),n=ni("__REDDB_BINARY_TAG__",()=>"");return r&&(e.reddbSdkVersion=r),n&&(e.reddbBinaryTag=n),e}function Xj(t){return t.startsWith("v")?t.slice(1):t}function rx(t){return`${t.app} ${t.version} ${t.gitSha}`}function ni(t,e){try{let r=e();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[t.replace(/^__|__$/g,"")]}}var bm={typescript:{command:"typescript-language-server",args:["--stdio"],extensions:[".ts",".tsx",".js",".jsx",".mts",".cts",".mjs",".cjs"],languageId:"typescript"},go:{command:"gopls",args:[],extensions:[".go"],languageId:"go"},rust:{command:"rust-analyzer",args:[],extensions:[".rs"],languageId:"rust"},python:{command:"pyright-langserver",args:["--stdio"],extensions:[".py",".pyi"],languageId:"python"}};function nx(){let t=process.env.CODE_NAV_SERVERS;if(!t)return bm;try{let e=JSON.parse(t),r={...bm};for(let[n,o]of Object.entries(e))r[n]={...r[n]??{},...o};return r}catch(e){return process.stderr.write(`code-nav: failed to parse CODE_NAV_SERVERS, using defaults: ${String(e)}
|
|
78
78
|
`),bm}}function ox(t){let e=new Map;for(let[r,n]of Object.entries(t))for(let o of n.extensions)e.set(o,r);return e}var $i=la(jk(),1),xt=la(Jh(),1);import{spawn as t1}from"node:child_process";import{readFile as r1}from"node:fs/promises";import{pathToFileURL as Dk,fileURLToPath as n1}from"node:url";import{resolve as o1}from"node:path";var Hs=class{constructor(e,r){this.spec=e;this.rootPath=r}spec;rootPath;proc;conn;ready;openDocs=new Set;async ensureStarted(){return this.ready?this.ready:(this.ready=this.start(),this.ready)}async start(){let e=t1(this.spec.command,this.spec.args,{cwd:this.rootPath,stdio:["pipe","pipe","pipe"]});this.proc=e,await new Promise((i,s)=>{e.once("spawn",()=>i()),e.once("error",a=>s(new Error(`failed to spawn '${this.spec.command}': ${a.message}`)))}),e.stderr.on("data",i=>{process.stderr.write(`[${this.spec.command}] ${i.toString()}`)}),e.once("exit",()=>{try{this.conn?.dispose()}catch{}});let r=(0,$i.createProtocolConnection)(new $i.StreamMessageReader(e.stdout),new $i.StreamMessageWriter(e.stdin));this.conn=r,r.listen();let n=Dk(this.rootPath).toString(),o={processId:process.pid,rootUri:n,workspaceFolders:[{uri:n,name:"workspace"}],capabilities:{textDocument:{definition:{linkSupport:!0},references:{},documentSymbol:{hierarchicalDocumentSymbolSupport:!0},hover:{contentFormat:["markdown","plaintext"]}},workspace:{symbol:{}}}};await r.sendRequest(xt.InitializeRequest.type,o),await r.sendNotification(xt.InitializedNotification.type,{})}async ensureOpen(e){let r=o1(this.rootPath,e),n=Dk(r).toString();if(this.openDocs.has(n))return n;let o=await r1(r,"utf8");return await this.conn.sendNotification(xt.DidOpenTextDocumentNotification.type,{textDocument:{uri:n,languageId:this.spec.languageId,version:1,text:o}}),this.openDocs.add(n),n}async definition(e,r,n){await this.ensureStarted();let o=await this.ensureOpen(e),i=await this.conn.sendRequest(xt.DefinitionRequest.type,{textDocument:{uri:o},position:{line:r,character:n}});return i1(i)}async references(e,r,n,o){await this.ensureStarted();let i=await this.ensureOpen(e);return await this.conn.sendRequest(xt.ReferencesRequest.type,{textDocument:{uri:i},position:{line:r,character:n},context:{includeDeclaration:o}})??[]}async documentSymbols(e){await this.ensureStarted();let r=await this.ensureOpen(e);return await this.conn.sendRequest(xt.DocumentSymbolRequest.type,{textDocument:{uri:r}})??[]}async hover(e,r,n){await this.ensureStarted();let o=await this.ensureOpen(e);return this.conn.sendRequest(xt.HoverRequest.type,{textDocument:{uri:o},position:{line:r,character:n}})}async workspaceSymbols(e){return await this.ensureStarted(),await this.conn.sendRequest(xt.WorkspaceSymbolRequest.type,{query:e})??[]}dispose(){try{this.conn?.dispose()}catch{}this.proc?.kill()}};function i1(t){return t?(Array.isArray(t)?t:[t]).map(r=>"targetUri"in r?{uri:r.targetUri,range:r.targetSelectionRange}:r):[]}function Kh(t,e){try{let r=n1(t);return(r.startsWith(e)?r.slice(e.length).replace(/^[/\\]/,""):r)||r}catch{return t}}var Ws=process.env.CODE_NAV_ROOT??process.cwd(),Bs=nx(),Mk=ox(Bs),ki=new Map;function Au(t){let e=s1(t),r=Mk.get(e);if(!r)throw new Error(`no language server configured for '${e}'. Configured extensions: ${[...Mk.keys()].join(", ")||"(none)"}.`);let n=ki.get(r);return n||(n=new Hs(Bs[r],Ws),ki.set(r,n)),n}function a1(){for(let t of Object.keys(Bs))ki.has(t)||ki.set(t,new Hs(Bs[t],Ws));return[...ki.values()]}function Xh(t,e){return`${Kh(t,Ws)}:${e.start.line+1}:${e.start.character+1}`}var Gh=tx("code-nav"),Si=new Kc({name:"code-nav",version:Gh.version}),qu={file:tn.string().describe("Workspace-relative path to the source file."),line:tn.number().int().describe("Zero-based line number."),character:tn.number().int().describe("Zero-based character offset on the line.")};Si.registerTool("goto_definition",{title:"Go to definition",description:"Resolve the symbol at a file position to its definition(s). Returns file:line:column locations. Use this instead of grepping for a name.",inputSchema:qu},async({file:t,line:e,character:r})=>{let n=await Au(t).definition(t,e,r);return n.length===0?Cr("No definition found."):Cr(n.map(o=>Xh(o.uri,o.range)).join(`
|
|
79
79
|
`))});Si.registerTool("find_references",{title:"Find references",description:"Find every reference to the symbol at a file position across the workspace. Semantic \u2014 matches the actual symbol, not text.",inputSchema:{...qu,includeDeclaration:tn.boolean().optional().describe("Include the declaration itself (default true).")}},async({file:t,line:e,character:r,includeDeclaration:n})=>{let o=await Au(t).references(t,e,r,n??!0);return o.length===0?Cr("No references found."):Cr(`${o.length} reference(s):
|
|
80
80
|
`+o.map(i=>Xh(i.uri,i.range)).join(`
|