@ours.network/mcp 0.12.0-nightly.13 → 0.12.0-nightly.14
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/cli.js
CHANGED
|
@@ -46,12 +46,12 @@ ${z}`,d++;break;case"id":u=z.includes("\0")?void 0:z;break;case"retry":/^\d+$/.t
|
|
|
46
46
|
`,{mode:384});try{Ie.chmodSync(t,384)}catch{}return t}var zs=".ours-identity";function Ps(e){if(!e.name.trim())throw new Error("identity name must not be empty");let t={identity:e.name.trim()};return e.force&&(t.force=!0),t.expose_local=e.exposeLocal??!0,t.local_auto_accept=e.localAutoAccept??!0,t}function fu(e){let t=Ss(e);return GS(t)===zs?t:lu(t,zs)}function Ig(e,t,r=!1){let n=Ps(t),o=fu(e);if(!r&&Ie.existsSync(o))throw new Error(`${o} already exists \u2014 pass overwrite to replace it`);return Ie.mkdirSync(du(o),{recursive:!0}),Ie.writeFileSync(o,JSON.stringify(n,null,2)+`
|
|
47
47
|
`),o}import Cg from"node:process";var Ts=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
48
48
|
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),tk(r)}clear(){this._buffer=void 0}};function tk(e){return br.parse(JSON.parse(e))}function Og(e){return JSON.stringify(e)+`
|
|
49
|
-
`}var Rs=class{constructor(t=Cg.stdin,r=Cg.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Ts,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 t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}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(t){return new Promise(r=>{let n=Og(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function Ag(e){let{selfVersion:t,daemonVersion:r}=e;return!r||r===t?null:`ours: version mismatch \u2014 this plugin/connector is v${t}, the running daemon is v${r}. Everything still works; for the best experience run matching versions. The daemon is a shared singleton and is never restarted automatically, so when no other session is mid-task run \`ours-mcp stop\` (the next session starts the daemon at the new version) \u2014 or update the lagging side to match. No action is required; this is advisory.`}import{mkdirSync as rk,writeFileSync as nk,readFileSync as ok,readdirSync as sk,statSync as Ng,unlinkSync as ik,chmodSync as jg}from"node:fs";import{join as Es}from"node:path";import{homedir as ak}from"node:os";var ck="0.12.0-nightly.
|
|
49
|
+
`}var Rs=class{constructor(t=Cg.stdin,r=Cg.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Ts,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 t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}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(t){return new Promise(r=>{let n=Og(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};function Ag(e){let{selfVersion:t,daemonVersion:r}=e;return!r||r===t?null:`ours: version mismatch \u2014 this plugin/connector is v${t}, the running daemon is v${r}. Everything still works; for the best experience run matching versions. The daemon is a shared singleton and is never restarted automatically, so when no other session is mid-task run \`ours-mcp stop\` (the next session starts the daemon at the new version) \u2014 or update the lagging side to match. No action is required; this is advisory.`}import{mkdirSync as rk,writeFileSync as nk,readFileSync as ok,readdirSync as sk,statSync as Ng,unlinkSync as ik,chmodSync as jg}from"node:fs";import{join as Es}from"node:path";import{homedir as ak}from"node:os";var ck="0.12.0-nightly.14",uk=new Set(["choose_identity","create_identity","create_root_identity"]),Zg=e=>new Promise(t=>setTimeout(t,e)),lk=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,dk=e=>e&&typeof e=="object"&&!("method"in e)&&e.id!==void 0&&e.id!==null,Mg=e=>{let t=e.result;return!!e.error||!!(t&&t.isError)},Dg=Number(process.env.OURS_RESTORE_TTL_MS)>0?Number(process.env.OURS_RESTORE_TTL_MS):7*24*60*60*1e3,qg=["1","true","yes","on"].includes((process.env.OURS_NO_AUTORESTORE??"").trim().toLowerCase());async function Lg(e){let t=new URL(e.url),r=(...I)=>process.stderr.write(`[ours-proxy] ${I.join(" ")}
|
|
50
50
|
`),n=I=>Number.isInteger(I)&&I>1,o=Number(process.env.OURS_CLIENT_PID),s=n(o)?o:n(process.ppid)?process.ppid:process.pid,i=(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||`client:${s}`,a=null,c=null,u,l=null,d=new Map,m=null,f=qg?null:(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||null,h=e.stateDir??process.env.OURS_STATE_DIR??Es(ak(),".ours"),g=Es(h,"session-restore"),v=f&&/^[A-Za-z0-9._-]{1,200}$/.test(f)?f:null,w=v?Es(g,`${v}.json`):null,x=!1,$=null;function T(I){if(w)try{rk(g,{recursive:!0,mode:448}),nk(w,JSON.stringify({claudeSessionId:f,identity:I,boundAt:new Date().toISOString()}),{mode:384}),jg(g,448),jg(w,384)}catch(F){r("restore persist failed (non-fatal):",String(F))}}function y(){if(!w)return null;try{if(Date.now()-Ng(w).mtimeMs>Dg)return null;let I=JSON.parse(ok(w,"utf8"));return(typeof I.identity=="string"?I.identity.trim():"")||null}catch{return null}}function z(){try{let I=Date.now();for(let F of sk(g)){if(!F.endsWith(".json"))continue;let G=Es(g,F);try{I-Ng(G).mtimeMs>Dg&&(ik(G),r("session-restore: pruned expired record",F))}catch{}}}catch{}}let R=null,Y=!1,ee=!1,ge=!1,st=[],lr="__ours_proxy_init__",xt=0,Ae=new Set,dr=new Set,Zt=new Rs;Zt.onmessage=I=>{let F=[],G=!1;for(let Ge of Ug(I)){let _e=Ge;if(_e.method==="notifications/initialized"&&(G=!0),lk(_e)){if(_e.method==="initialize"&&(a=_e,c)){r("absorbed re-initialize locally \u2014 upstream session kept stable"),Zt.send({jsonrpc:"2.0",id:_e.id,result:c}).catch(we=>r("local initialize reply failed:",String(we)));continue}if(_e.method==="tools/call"){let we=_e.params;we&&uk.has(we.name??"")&&typeof we.arguments?.name=="string"&&d.set(_e.id,we.arguments.name)}}F.push(_e)}if(F.length){let Ge=Array.isArray(I)?F:F[0];bu(Ge)}G&&t_()},Zt.onclose=()=>void js(0),Zt.onerror=I=>r("downstream error:",String(I));function t_(){if(x||!l)return;x=!0;let I=`__ours_proxy_restore_${++xt}__`;Ae.add(I),$=I,r("session-restore: self-recovering bound identity",`"${l}"`),bu({jsonrpc:"2.0",id:I,method:"tools/call",params:{name:"choose_identity",arguments:{name:l}}})}function bu(I){if(Y&&R){let F=R;R.send(I).catch(G=>{r("upstream send failed:",String(G)),st.push(I),xu(F,"send failed")})}else st.push(I)}function xu(I,F){if(ee||ge||R!==null&&I!==R)return;r(`upstream dropped (${F}) \u2014 reconnecting`),Y=!1;let G=R;R=null;try{G?.close?.()}catch{}n_()}function r_(I){I.onmessage=F=>{let G=[];for(let Ge of Ug(F)){let _e=Ge;if(dk(_e)){let we=_e.id,Zs=_e.result?.protocolVersion;if(Zs&&(dr.has(we)||zu(we))){u=Zs;try{R?.setProtocolVersion?.(Zs)}catch{}if(c==null&&zu(we)&&!Ae.has(we)){let pt=_e.result??null;pt&&m&&(pt.instructions=`${pt.instructions?pt.instructions+`
|
|
51
51
|
|
|
52
52
|
`:""}${m}`),c=pt}dr.delete(we)}if(Ae.has(we)){Ae.delete(we),we===$&&($=null,Mg(_e)&&(l=null,r("session-restore: re-bind refused (identity live elsewhere) \u2014 staying unbound")));continue}if(d.has(we)){let pt=d.get(we);d.delete(we),Mg(_e)||(l=pt,r("bound identity tracked:",pt),T(pt))}}G.push(_e)}if(G.length){let Ge=Array.isArray(F)?G:G[0];Zt.send(Ge).catch(_e=>r("downstream send failed:",String(_e)))}},I.onerror=F=>r("upstream error:",String(F)),I.onclose=()=>xu(I,"closed")}let zu=I=>a!=null&&a.id===I;async function Su(){e.ensureDaemon&&await e.ensureDaemon().catch(F=>r("ensureDaemon:",String(F)));let I=new Fr(t,{requestInit:{headers:{"x-ours-lease-token":i,"x-ours-client-pid":String(s),...e.apiToken?{"x-ours-api-token":e.apiToken}:{}}}});if(r_(I),await I.start(),u)try{I.setProtocolVersion?.(u)}catch{}R=I}async function ku(I,F){F&&I.id!==void 0&&Ae.add(I.id),await R.send(I)}async function n_(){if(ge||ee)return;ge=!0;let I=500;for(;;){if(ee){ge=!1;return}try{if(await Su(),a){let G=`${lr}${xt}`;dr.add(G),await ku({...a,id:G},!0),await R.send({jsonrpc:"2.0",method:"notifications/initialized"})}if(l){let G=`__ours_proxy_rebind_${++xt}__`;await ku({jsonrpc:"2.0",id:G,method:"tools/call",params:{name:"choose_identity",arguments:{name:l}}},!0)}Y=!0;let F=st.splice(0);for(let G of F)await R.send(G).catch(Ge=>r("flush failed:",String(Ge)));r("upstream reconnected",l?`(re-bound "${l}")`:""),ge=!1;return}catch(F){r("reconnect attempt failed:",String(F)),await Zg(I),I=Math.min(Math.floor(I*1.5),1e4)}}}async function js(I){if(!ee){ee=!0;try{await R?.close()}catch{}try{await Zt.close()}catch{}process.exit(I)}}process.on("SIGINT",()=>void js(0)),process.on("SIGTERM",()=>void js(0));async function o_(){let I=new URL(t.href);I.pathname="/state-dir";let F;try{F=await(await fetch(I,{signal:AbortSignal.timeout(3e3)})).json()}catch(G){r("compat handshake: could not read daemon /state-dir, proceeding:",String(G));return}m=Ag({selfVersion:ck,daemonVersion:typeof F?.version=="string"?F.version:null}),m&&r(m)}if((async()=>{e.ensureDaemon&&await e.ensureDaemon().catch(G=>r("ensureDaemon:",String(G))),await o_();let I=500;for(;;)try{await Su();break}catch(G){r("initial upstream connect failed, retrying:",String(G)),await Zg(I),I=Math.min(Math.floor(I*1.5),1e4)}Y=!0;let F=st.splice(0);for(let G of F)await R.send(G).catch(Ge=>r("flush failed:",String(Ge)));r(`upstream ready \u2014 stdio \u21C4 ${t.href}`)})(),f){z();let I=y();I&&(l=I,r("session-restore: found prior binding for this session \u2014 will self-recover",`"${I}"`))}else qg&&r("session-restore: disabled via OURS_NO_AUTORESTORE \u2014 pure in-memory binding");await Zt.start(),r("proxy started (stdio transport up)")}function Ug(e){return Array.isArray(e)?e:[e]}if(!process.env.XDG_RUNTIME_DIR&&typeof process.getuid=="function"){let e=`/run/user/${process.getuid()}`;U.existsSync(e)&&(process.env.XDG_RUNTIME_DIR=e)}var Kr=pu(),qe=Kr.stateDir,ne=Kr.port,yu=Rg(Kr,{generate:!1})?.token??null,As=()=>yu?{"x-ours-api-token":yu}:{},Br=Kr.brokerUrl,cr=bt(qe,"daemon.pid"),ir=bt(qe,"daemon.log"),Jr=fk(import.meta.url),b=(...e)=>process.stdout.write(`${e.join(" ")}
|
|
53
53
|
`),W=(...e)=>process.stderr.write(`${e.join(" ")}
|
|
54
|
-
`),ar="0.12.0-nightly.
|
|
54
|
+
`),ar="0.12.0-nightly.14";async function vu(){for(let e of["/version","/state-dir"])try{let t=new AbortController,r=setTimeout(()=>t.abort(),1500),n=await fetch(`http://127.0.0.1:${ne}${e}`,{signal:t.signal});if(clearTimeout(r),n.ok){let o=await n.json();if(o&&typeof o.version=="string")return o}}catch{}return null}function Fg(e){if(b(` cli: v${ar}`),e?.version){let t=e.version!==ar;b(` daemon: v${e.version}${e.compat?` (compat ${e.compat})`:""}`+(t?` \u26A0 differs from CLI \u2014 \`ours-mcp restart\` to load v${ar}`:""))}else b(" daemon: version unknown (running build predates /version \u2014 restart to update)")}var Ns=e=>new Promise(t=>setTimeout(t,e));function hk(){try{let e=parseInt(U.readFileSync(cr,"utf8").trim(),10);return Number.isFinite(e)?e:null}catch{return null}}function wu(e){try{return process.kill(e,0),!0}catch{return!1}}function io(){let e=hk();if(e&&wu(e))return e;if(e)try{U.rmSync(cr,{force:!0})}catch{}return null}function ur(e,t=1e3){return new Promise(r=>{let n=pk({host:"127.0.0.1",port:e}),o=s=>{n.destroy(),r(s)};n.setTimeout(t),n.once("connect",()=>o(!0)),n.once("timeout",()=>o(!1)),n.once("error",()=>o(!1))})}async function Wg(e,t=3e4){let r=Date.now()+t;for(;Date.now()<r;){if(await ur(e))return!0;await Ns(400)}return!1}async function Vg(){let e=io();if(e){b(`ours-mcp is already running (pid ${e}, port ${ne}).`);return}U.mkdirSync(qe,{recursive:!0});let t=U.openSync(ir,"a"),r=Bg(process.execPath,[Jr,"serve"],{detached:!0,stdio:["ignore",t,t],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(ne),OURS_BROKER_URL:Br,OURS_STATE_DIR:qe}});r.unref(),r.pid||(W("failed to spawn the daemon."),process.exit(1)),U.writeFileSync(cr,String(r.pid)),b(`starting ours-mcp (pid ${r.pid})\u2026`),await Wg(ne)?(b(`ours-mcp is up on http://localhost:${ne}/mcp`),b(` broker: ${Br}`),b(` state: ${qe}`),b(` logs: ${ir}`)):(W(`daemon started (pid ${r.pid}) but port ${ne} did not open within 30s \u2014 check ${ir}.`),process.exit(1))}async function gk(){if(!await ur(ne)){if(!io()){U.mkdirSync(qe,{recursive:!0});let e=U.openSync(ir,"a"),t=Bg(process.execPath,[Jr,"serve"],{detached:!0,stdio:["ignore",e,e],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(ne),OURS_BROKER_URL:Br,OURS_STATE_DIR:qe}});if(t.unref(),t.pid)try{U.writeFileSync(cr,String(t.pid))}catch{}}await Wg(ne)}}async function Os(){let e=io();if(!e){b("ours-mcp is not running.");return}b(`stopping ours-mcp (pid ${e})\u2026`);try{process.kill(e,"SIGTERM")}catch(t){W(`failed to signal pid ${e}: ${String(t)}`)}for(let t=0;t<25&&wu(e);t++)await Ns(200);if(wu(e)){W(`pid ${e} did not exit; sending SIGKILL.`);try{process.kill(e,"SIGKILL")}catch{}}try{U.rmSync(cr,{force:!0})}catch{}b("stopped.")}async function _k(){let e=io();if(!e){if(await ur(ne)){let n=await vu();b("ours-mcp: running (no pidfile \u2014 likely a stale process or external launcher)"),b(` url: http://localhost:${ne}/mcp (reachable)`),Fg(n);return}b("ours-mcp: stopped"),b(` cli: v${ar}`),process.exitCode=1;return}let t=await ur(ne),r=t?await vu():null;b("ours-mcp: running"),b(` pid: ${e}`),b(` url: http://localhost:${ne}/mcp ${t?"(reachable)":"(port not answering!)"}`),b(` broker: ${Br}`),b(` state: ${qe}`),b(` logs: ${ir}`),Fg(r)}async function yk(){if(b(`ours-mcp v${ar}`),await ur(ne)){let e=await vu();e?.version?b(`running daemon: v${e.version}`+(e.version!==ar?" (differs \u2014 restart to update)":"")):b("running daemon: version unknown (predates /version)")}else b("daemon: not running")}async function vk(){let e=pu(),t=ks();b(`ours-mcp setup \u2014 ${t}`),b("Enter a value, or press Enter to keep the current [bracketed] one."),b("");let r=Is({input:process.stdin,output:process.stdout}),n;try{let u=async(T,y)=>{let z=(await r.question(` ${T} [${y}]: `)).trim();return z===""?y:z},l=await u("broker URL",e.brokerUrl),d=await u("HTTP port",String(e.port)),m=await u("state dir",e.stateDir),f=await u("GC interval (ms)",String(e.gcIntervalMs)),h=await u("proxy auto-starts daemon (true/false)",String(e.autoStart)),g=await u("HTTP visibility (owner=same-user only / shared=cross-user w/ token / open=all local users)",e.apiVisibility),v=parseInt(d,10);(!Number.isFinite(v)||v<=0)&&(W(`invalid port: ${d}`),process.exit(1));let w=parseInt(f,10);(!Number.isFinite(w)||w<=0)&&(W(`invalid GC interval: ${f}`),process.exit(1));let x=h.toLowerCase()==="true"||h==="1",$=g.trim().toLowerCase();oo.includes($)||(W(`invalid visibility: ${g} (expected one of ${oo.join(", ")})`),process.exit(1)),n={brokerUrl:l,port:v,stateDir:Gg(m),gcIntervalMs:w,autoStart:x,apiVisibility:$,...e.apiToken?{apiToken:e.apiToken}:{}}}finally{r.close()}Eg(n),b(""),b(`wrote ${t} (mode 0600):`),b(JSON.stringify(n,null,2));let o=["OURS_BROKER_URL","OURS_PORT","OURS_STATE_DIR","OURS_GC_INTERVAL_MS","OURS_AUTOSTART","OURS_API_VISIBILITY","OURS_API_TOKEN"].filter(u=>process.env[u]!==void 0);o.length&&(b(""),b(`note: these env vars are set and OVERRIDE the file at runtime: ${o.join(", ")}`));let s=io();if(!s)return;let i=Is({input:process.stdin,output:process.stdout}),a=!1;try{let u=(await i.question(`
|
|
55
55
|
daemon is running (pid ${s}); restart now to apply? [y/N]: `)).trim().toLowerCase();a=u==="y"||u==="yes"}finally{i.close()}if(!a){b("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await Os();let c=Cs(process.execPath,[Jr,"start"],{stdio:"inherit"});c.status!==0&&process.exit(c.status??1)}function hu(e,t,r){return e.includes(r)?{value:!1,set:!0}:e.includes(t)?{value:!0,set:!0}:{value:void 0,set:!1}}function gu(e,t){let r=e.indexOf(t);return r>=0&&r+1<e.length?e[r+1]:void 0}async function wk(e){let t=gu(e,"--name"),r=hu(e,"--force-bind","--no-force-bind"),n=hu(e,"--local-book","--no-local-book"),o=hu(e,"--auto-accept-local","--no-auto-accept-local"),s=e.includes("--overwrite"),i=e.includes("--print"),a=gu(e,"--path")??gu(e,"--dir")??process.cwd(),c=t!==void 0||r.set||n.set||o.set||i,u;if(c?((!t||!t.trim())&&(W("define-local-identity-file: --name is required in non-interactive mode."),process.exit(1)),u={name:t.trim(),force:r.value??!1,exposeLocal:n.value??!0,localAutoAccept:o.value??!0}):u=await $k(),i){b(JSON.stringify(Ps(u),null,2));return}let l=fu(a);if(!s&&U.existsSync(l)){c&&(W(`define-local-identity-file: ${l} already exists \u2014 pass --overwrite to replace it.`),process.exit(1));let m=Is({input:process.stdin,output:process.stdout}),f=!1;try{let h=(await m.question(`
|
|
56
56
|
${l} already exists \u2014 overwrite? [y/N]: `)).trim().toLowerCase();f=h==="y"||h==="yes"}finally{m.close()}if(!f){b("aborted \u2014 nothing written.");return}}let d=Ig(a,u,!0);b(""),b(`wrote ${d}:`),b(JSON.stringify(Ps(u),null,2))}async function $k(){b("ours-mcp define-local-identity-file \u2014 interactive"),b(`Answer the prompts; the result is written to ${bt(process.cwd(),zs)}.`),b("");let e=Is({input:process.stdin,output:process.stdout});try{let t=async(i,a)=>{let c=a?"Y/n":"y/N",u=(await e.question(` ${i} [${c}]: `)).trim().toLowerCase();return u===""?a:u==="y"||u==="yes"},r="";for(;!r;)r=(await e.question(" Identity name: ")).trim(),r||b(" (name is required)");let n=await t("Force-bind (pin pre-authorizes evicting another session)?",!1),o=await t("Add to the host-local contact book?",!0),s=await t("Auto-accept local invites/introductions?",!0);return{name:r,force:n,exposeLocal:o,localAutoAccept:s}}finally{e.close()}}async function bk(e){let t=(e[0]??"").trim();(!t||t.startsWith("--"))&&(W('usage: ours-mcp create-root "<your name>"'),process.exit(1)),await ur(ne)||(W(`create-root: the daemon is not running on port ${ne} \u2014 start it with \`ours-mcp start\`.`),process.exit(1));let r=new Fr(new URL(`http://127.0.0.1:${ne}/mcp`),{requestInit:{headers:As()}}),n=new $s({name:"ours-mcp-cli",version:ar});try{await n.connect(r);let o=await n.callTool({name:"create_root_identity",arguments:{name:t,skip_if_root_exists:!0}}),s=(Array.isArray(o.content)?o.content:[]).map(i=>typeof i.text=="string"?i.text:"").join(" ").split(/\n\nAsk the user\b/)[0].replace(/^create_root_identity failed: /,"").trim();if(o.isError){if(/a root identity already exists/i.test(s)){b(`create-root: ${s.split("\u2014")[0].trim()} \u2014 nothing to do.`);return}W(`create-root failed: ${s}`),process.exit(1)}b(s)}finally{try{await r.terminateSession()}catch{}try{await n.close()}catch{}}}function Yg(e,t){t.event==="message_received"?b(`[${e}] new message from ${t.from??"?"}`+(t.msg_id!==void 0?` (#${t.msg_id})`:"")+(t.date?` (${t.date})`:"")):t.event==="file_received"?b(`[${e}] new file ${t.filename??"?"} from ${t.from??"?"}`+(t.bytes!==void 0?` (${t.bytes} B)`:"")+(t.file_id!==void 0?` (#${t.file_id})`:"")+(t.date?` (${t.date})`:"")):t.event==="local_contact_request"?b(`[${e}] pending local introduction from ${t.from??"?"} \u2014 respond_to_introduction to approve/reject`):t.event==="pending_message"&&b(`[${e}] ${t.from??"?"} queued a message awaiting introduction approval (${t.queued??"?"} queued)`)}function jt(e){W(`ours-mcp watch: ${e}`),process.exit(1)}async function xk(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch(`http://127.0.0.1:${ne}/state-dir`,{signal:e.signal});if(clearTimeout(t),r.ok){let n=await r.json();return typeof n.stateDir=="string"&&n.stateDir?Gg(n.stateDir):qe}}catch{}return null}var zk=e=>`http://127.0.0.1:${ne}/identities/${encodeURIComponent(e)}/notifications`;async function Hg(e){let t=async o=>{let s=new AbortController,i=setTimeout(()=>s.abort(),35e3),a;try{a=await fetch(`${zk(e)}?since=${o}`,{headers:As(),signal:s.signal})}finally{clearTimeout(i)}if(a.status===401&&jt(`daemon rejected the API token (401) for identity "${e}". Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode).`),!a.ok)throw new Error(`daemon returned HTTP ${a.status}`);return await a.json()},r=(await t("tip")).cursor??0,n=0;for(;;)try{let o=await t(String(r));if(n=0,Array.isArray(o.events))for(let s of o.events)Yg(e,s);typeof o.cursor=="number"&&(r=o.cursor)}catch(o){n=Math.min(n+1e3,5e3),W(`ours-mcp watch: notifications stream for "${e}" hiccupped (${String(o?.message??o)}), retrying\u2026`),await Ns(n)}}async function Sk(e){if(e){await Hg(e);return}let t=new Set;for(;;){try{let r=await fetch(`http://127.0.0.1:${ne}/identities`,{headers:As()});if(r.status===401&&jt("daemon rejected the API token (401). Set OURS_API_TOKEN or run watch as the daemon owner."),r.ok){let n=await r.json();for(let o of n.identities??[]){let s=typeof o?.name=="string"?o.name:void 0;s&&!t.has(s)&&(t.add(s),Hg(s))}}}catch{}await Ns(3e3)}}var _u=e=>{let t=e?.code;return t==="EACCES"||t==="EPERM"};function kk(e,t){try{U.readdirSync(e)}catch(i){jt(`cannot watch \u2014 the daemon API is unreachable AND ${e} is not readable (${i?.code??i}). On a multi-user host, run watch as the daemon owner, or enable the daemon API (start the daemon) so watch can stream over HTTP.`)}if(t)try{U.readdirSync(bt(e,t))}catch(i){jt(`cannot watch identity "${t}" \u2014 ${bt(e,t)} is not readable (${i?.code??i}). Is the daemon running and the name correct?`)}let r=new Map,n=i=>{let a;try{a=U.readdirSync(e,{withFileTypes:!0}).filter(c=>c.isDirectory()).map(c=>c.name)}catch(c){_u(c)&&jt(`lost read access to ${e} (${c.code}) \u2014 cannot watch.`);return}for(let c of a){if(t&&c!==t)continue;let u=bt(e,c,"notifications.log"),l;try{l=U.statSync(u).size}catch(f){_u(f)&&jt(`cannot read ${u} (${f.code}) \u2014 cannot watch identity "${c}".`);continue}let d=r.get(u);if(d===void 0&&(d=i?l:0,r.set(u,d),i))continue;if(l<=d){l<d&&r.set(u,l);continue}let m;try{let f=U.openSync(u,"r"),h=Buffer.alloc(l-d);U.readSync(f,h,0,h.length,d),U.closeSync(f),m=h.toString("utf8")}catch(f){_u(f)&&jt(`cannot read ${u} (${f.code}) \u2014 cannot watch identity "${c}".`);continue}r.set(u,l);for(let f of m.split(`
|
|
57
57
|
`))if(f.trim())try{Yg(c,JSON.parse(f))}catch{}}};W(`ours-mcp watch: daemon API unreachable \u2014 falling back to file poll of ${e} (Ctrl-C to stop)`),n(!0);let o=setInterval(()=>n(!1),1e3),s=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}async function Pk(){try{let e=await fetch(`http://127.0.0.1:${ne}/identities`,{headers:As()});return e.status===401&&jt("daemon rejected the API token (401). Set OURS_API_TOKEN to the daemon's token (shared mode) or run watch as the daemon owner (owner mode)."),e.status===404?"file":e.ok?"api":"file"}catch{return"file"}}async function Tk(e){let t=()=>process.exit(0);if(process.on("SIGINT",t),process.on("SIGTERM",t),await xk()!==null&&await Pk()==="api"){W(`ours-mcp watch: streaming ${e?`identity "${e}"`:"all identities"} from the daemon API on port ${ne} (Ctrl-C to stop)`),await Sk(e);return}kk(qe,e)}var so="ours.service",Qg="solutions.adaptframework.ours";function Xg(){return bt(Jg(),".config","systemd","user",so)}function e_(){return bt(Jg(),"Library","LaunchAgents",`${Qg}.plist`)}function Hr(e,t){return Cs(e,t,{stdio:"inherit"}).status===0}function Rk(){let e=Xg();U.mkdirSync($u(e),{recursive:!0});let t=`[Unit]
|
package/dist/index.js
CHANGED
|
@@ -53,7 +53,7 @@ data:
|
|
|
53
53
|
|
|
54
54
|
`,e.enqueue(r.encode(s)),!0}catch(s){return this.onerror?.(s),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!o||!o.includes("application/json"))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},i;if(r?.parsedBody!==void 0)i=r.parsedBody;else try{i=await e.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let a;try{Array.isArray(i)?a=i.map(v=>ho.parse(v)):a=[ho.parse(i)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let c=a.some(yo);if(c){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let v=this.validateSession(e);if(v)return v;let y=this.validateProtocolVersion(e);if(y)return y}if(!a.some(rr)){for(let v of a)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),d=a.find(v=>yo(v)),p=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??Om;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(l)}});for(let y of a)rr(y)&&this._requestToStreamMapping.set(y.id,l);for(let y of a)this.onmessage?.(y,{authInfo:r?.authInfo,requestInfo:s})});let f=new TextEncoder,m,h=new ReadableStream({start:v=>{m=v},cancel:()=>{this._streamMapping.delete(l)}}),g={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(g["mcp-session-id"]=this.sessionId);for(let v of a)rr(v)&&(this._streamMapping.set(l,{controller:m,encoder:f,cleanup:()=>{this._streamMapping.delete(l);try{m.close()}catch{}}}),this._requestToStreamMapping.set(v.id,l));await this.writePrimingEvent(m,f,l,p);for(let v of a){let y,$;rr(v)&&this._eventStore&&p>="2025-11-25"&&(y=()=>{this.closeSSEStream(v.id)},$=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:y,closeStandaloneSSEStream:$})}return new Response(h,{status:200,headers:g})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let r=this.validateSession(e);if(r)return r;let n=this.validateProtocolVersion(e);return n||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=e.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let r=e.headers.get("mcp-protocol-version");if(r!==null&&!yn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${yn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${yn.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let r=this._requestToStreamMapping.get(e);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,r){let n=r?.relatedRequestId;if((Lt(e)||_n(e))&&(n=e.id),n===void 0){if(Lt(e)||_n(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let s=this._streamMapping.get(o);if(!this._enableJsonResponse&&s?.controller&&s?.encoder){let i;this._eventStore&&(i=await this._eventStore.storeEvent(o,e)),this.writeSSEEvent(s.controller,s.encoder,e,i)}if(Lt(e)||_n(e)){this._requestResponseMap.set(n,e);let i=Array.from(this._requestToStreamMapping.entries()).filter(([c,u])=>u===o).map(([c])=>c);if(i.every(c=>this._requestResponseMap.has(c))){if(!s)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&s.resolveJson){let c={"Content-Type":"application/json"};this.sessionId!==void 0&&(c["mcp-session-id"]=this.sessionId);let u=i.map(l=>this._requestResponseMap.get(l));u.length===1?s.resolveJson(new Response(JSON.stringify(u[0]),{status:200,headers:c})):s.resolveJson(new Response(JSON.stringify(u),{status:200,headers:c}))}else s.cleanup();for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c)}}}};var sa=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new oa(e),this._requestListener=np(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,r){return this._webStandardTransport.send(e,r)}async handleRequest(e,r,n){let o=e.auth;await np(async i=>this._webStandardTransport.handleRequest(i,{authInfo:o,parsedBody:n}),{overrideGlobalObjects:!1})(e,r)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};import{resolve as RI,join as Re,dirname as TI,isAbsolute as EI,basename as II}from"node:path";import{fileURLToPath as PI}from"node:url";import{randomBytes as fv,randomInt as mv,randomUUID as OI,timingSafeEqual as NI}from"node:crypto";import{createServer as AI}from"node:http";import{brotliCompressSync as CI,brotliDecompressSync as jI}from"node:zlib";import*as T from"node:fs";import{readFile as ZI,mkdir as MI,writeFile as qI}from"node:fs/promises";import{adapt_wrapper as DI}from"@adapt-toolkit/sdk/executables";import{PacketWrapperConfigurator as VI}from"@adapt-toolkit/sdk/wrappers";import{object_to_adapt_value as hv}from"@adapt-toolkit/sdk/wrapper";import{AdaptObjectLifetime as kp}from"@adapt-toolkit/sdk/common";import*as st from"node:fs";import{randomBytes as pI}from"node:crypto";import{homedir as U_}from"node:os";import{resolve as ia,join as op,dirname as F_,basename as fI}from"node:path";var B_=["owner","shared","open"],Bn={brokerUrl:"wss://broker1.ours.network",port:3050,stateDir:ia(U_(),".ours"),gcIntervalMs:36e5,autoStart:!1,apiVisibility:"owner"};function mI(){return process.env.OURS_CONFIG??op(U_(),".ours","config.json")}function hI(){let t;try{t=st.readFileSync(mI(),"utf8")}catch{return{}}let e;try{e=JSON.parse(t)}catch{return{}}let r={};return typeof e.brokerUrl=="string"&&(r.brokerUrl=e.brokerUrl),typeof e.port=="number"&&Number.isFinite(e.port)&&(r.port=e.port),typeof e.stateDir=="string"&&(r.stateDir=ia(e.stateDir)),typeof e.gcIntervalMs=="number"&&Number.isFinite(e.gcIntervalMs)&&(r.gcIntervalMs=e.gcIntervalMs),typeof e.autoStart=="boolean"&&(r.autoStart=e.autoStart),typeof e.apiVisibility=="string"&&B_.includes(e.apiVisibility)&&(r.apiVisibility=e.apiVisibility),typeof e.apiToken=="string"&&e.apiToken.trim()&&(r.apiToken=e.apiToken.trim()),r}function gI(){let t=process.env.OURS_API_VISIBILITY?.trim().toLowerCase();return t&&B_.includes(t)?t:void 0}function yI(t){let e=process.env[t];if(e!==void 0)return e==="1"||e.toLowerCase()==="true"}function V_(t){let e=process.env[t];if(e===void 0)return;let r=parseInt(e,10);return Number.isNaN(r)?void 0:r}function H_(){let t=hI();return{brokerUrl:process.env.OURS_BROKER_URL??t.brokerUrl??Bn.brokerUrl,port:V_("OURS_PORT")??t.port??Bn.port,stateDir:ia(process.env.OURS_STATE_DIR??t.stateDir??Bn.stateDir),gcIntervalMs:V_("OURS_GC_INTERVAL_MS")??t.gcIntervalMs??Bn.gcIntervalMs,autoStart:yI("OURS_AUTOSTART")??t.autoStart??Bn.autoStart,apiVisibility:gI()??t.apiVisibility??Bn.apiVisibility,apiToken:process.env.OURS_API_TOKEN?.trim()||t.apiToken}}var _I="daemon-token";function sp(t){return op(t.stateDir,_I)}function G_(t){let e=process.env.OURS_API_TOKEN?.trim();return e||t.apiToken?.trim()||void 0}function J_(t,e={}){let r=process.env.OURS_API_TOKEN?.trim();if(r)return{token:r,source:"env"};let n=t.apiToken?.trim();if(n)return{token:n,source:"config"};let o=sp(t);try{let i=st.readFileSync(o,"utf8").trim();if(i)return{token:i,source:"file"}}catch{}if(!e.generate)return null;let s=pI(32).toString("hex");try{st.mkdirSync(F_(o),{recursive:!0}),st.writeFileSync(o,s+`
|
|
55
55
|
`,{mode:384}),st.chmodSync(o,384)}catch{}return{token:s,source:"generated"}}var L_=".ours-identity";function ip(t){if(!t.name.trim())throw new Error("identity name must not be empty");let e={identity:t.name.trim()};return t.force&&(e.force=!0),e.expose_local=t.exposeLocal??!0,e.local_auto_accept=t.localAutoAccept??!0,e}function vI(t){let e=ia(t);return fI(e)===L_?e:op(e,L_)}function K_(t,e,r=!1){let n=ip(e),o=vI(t);if(!r&&st.existsSync(o))throw new Error(`${o} already exists \u2014 pass overwrite to replace it`);return st.mkdirSync(F_(o),{recursive:!0}),st.writeFileSync(o,JSON.stringify(n,null,2)+`
|
|
56
|
-
`),o}import{basename as bI,extname as wI}from"node:path";var $I={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".html":"text/html",".xml":"application/xml",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime"};function W_(t){return $I[wI(t).toLowerCase()]??"application/octet-stream"}function Y_(t){let e=bI(t).replace(/[^A-Za-z0-9._-]/g,"_");return e.length?e.slice(0,200):"file"}var xI=new Set(["e2e_app_recv","migration_deferred_flush"]);function X_(t){let e=new Set;for(let r of t){if(!r||typeof r!="object")continue;let n=r.event;if(typeof n!="string"||!xI.has(n))continue;let o=r.wire_id;typeof o=="string"&&o.length>0&&e.add(o)}return e}function kI(t,e){return t&&e.has(t)?"e2e":"legacy"}function SI(t,e){let r=kI(t.wire_id,e);return{msg_id:t.msg_id,wire_id:t.wire_id,from:{id:t.sender_id,name:t.sender_name},encryption:r,transport:r==="e2e"?"double_ratchet":"legacy_box",text:t.text,date:t.date,status:t.status,reply_to:t.reply_to}}function Q_(t,e){let r=t.map(n=>SI(n,e));return{count:r.length,messages:r}}function zI(t){let{selfVersion:e,daemonVersion:r}=t;return!r||r===e?null:`ours: version mismatch \u2014 this plugin/connector is v${e}, the running daemon is v${r}. Everything still works; for the best experience run matching versions. The daemon is a shared singleton and is never restarted automatically, so when no other session is mid-task run \`ours-mcp stop\` (the next session starts the daemon at the new version) \u2014 or update the lagging side to match. No action is required; this is advisory.`}var ss="0.12.0-nightly.
|
|
56
|
+
`),o}import{basename as bI,extname as wI}from"node:path";var $I={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".bmp":"image/bmp",".ico":"image/x-icon",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".json":"application/json",".csv":"text/csv",".html":"text/html",".xml":"application/xml",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime"};function W_(t){return $I[wI(t).toLowerCase()]??"application/octet-stream"}function Y_(t){let e=bI(t).replace(/[^A-Za-z0-9._-]/g,"_");return e.length?e.slice(0,200):"file"}var xI=new Set(["e2e_app_recv","migration_deferred_flush"]);function X_(t){let e=new Set;for(let r of t){if(!r||typeof r!="object")continue;let n=r.event;if(typeof n!="string"||!xI.has(n))continue;let o=r.wire_id;typeof o=="string"&&o.length>0&&e.add(o)}return e}function kI(t,e){return t&&e.has(t)?"e2e":"legacy"}function SI(t,e){let r=kI(t.wire_id,e);return{msg_id:t.msg_id,wire_id:t.wire_id,from:{id:t.sender_id,name:t.sender_name},encryption:r,transport:r==="e2e"?"double_ratchet":"legacy_box",text:t.text,date:t.date,status:t.status,reply_to:t.reply_to}}function Q_(t,e){let r=t.map(n=>SI(n,e));return{count:r.length,messages:r}}function zI(t){let{selfVersion:e,daemonVersion:r}=t;return!r||r===e?null:`ours: version mismatch \u2014 this plugin/connector is v${e}, the running daemon is v${r}. Everything still works; for the best experience run matching versions. The daemon is a shared singleton and is never restarted automatically, so when no other session is mid-task run \`ours-mcp stop\` (the next session starts the daemon at the new version) \u2014 or update the lagging side to match. No action is required; this is advisory.`}var ss="0.12.0-nightly.14",fr=H_(),je=fr.stateDir,da=fr.brokerUrl,LI=process.env.OURS_TRANSPORT??"http",ap=fr.port,tv=fr.gcIntervalMs,pp=fr.apiVisibility,w=(...t)=>process.stderr.write(`ours: ${t.join(" ")}
|
|
57
57
|
`);function UI(){if(pp==="open")return null;if(pp==="shared"){let t=G_(fr);if(!t)throw new Error(`apiVisibility=shared requires an operator-supplied token so it can be distributed to cross-user agents \u2014 set OURS_API_TOKEN or "apiToken" in config (${sp(fr)} is not used for shared mode). Use apiVisibility=owner for a same-user-only auto-token, or =open to disable auth.`);return t}return J_(fr,{generate:!0}).token}var rv=UI();function FI(t){let e=t.headers["x-ours-api-token"];if(typeof e=="string"&&e)return e;let r=t.headers.authorization;if(typeof r=="string"){let n=/^Bearer\s+(.+)$/i.exec(r.trim());if(n)return n[1]}}function BI(t){if(rv===null)return!0;let e=FI(t);if(!e)return!1;let r=Buffer.from(e),n=Buffer.from(rv);return r.length===n.length&&NI(r,n)}function aa(t,e){return BI(t)?!0:(e.writeHead(401,{"Content-Type":"application/json"}),e.end(JSON.stringify({error:"unauthorized"})),!1)}var HI=/^[A-Za-z0-9 _.@-]{1,64}$/,pa="contact-book";function fa(t){return HI.test(t)?t==="."||t===".."||t.includes("/")||t.includes("\\")?"invalid name":t===pa?`"${pa}" is reserved for the local contact book`:t==="root.json"||t==="bindings.json"?`"${t}" is reserved for daemon bookkeeping`:null:"name must be 1-64 chars of letters, digits, space, _ . @ or -"}function GI(){let t=TI(PI(import.meta.url)),e=process.env.OURS_UNIT_DIR,r=process.env.OURS_ADVERTISE_MIGRATE==="0",n=s=>r?[`${s}-nocap`]:[s],o=e?n(RI(e)):[Re(t,"mufl_code"),Re(t,"..","mufl_code")].flatMap(n);for(let s of o){if(!T.existsSync(s))continue;let i=T.readdirSync(s).find(a=>a.endsWith(".muflo"));if(i){let a=i.slice(0,-6),c=new Uint8Array(T.readFileSync(Re(s,i)));return{dir:s,hash:a,contents:c}}}throw new Error(`no compiled .muflo packet found (looked in: ${o.join(", ")})`+(r?' \u2014 OURS_ADVERTISE_MIGRATE=0 requires a "<dir>-nocap" packet variant (compiled with $advertise = [core.e2e] only); build it or unset the env.':""))}var is,Qr,L=new Map,_t=null,fp=null,Ee=new Map,ha=new Set,it=new Map;function mp(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function gv(t){for(let e of Ee.values())if(e.token===t)return e}var nv=()=>Re(je,"bindings.json");function ls(){try{T.mkdirSync(je,{recursive:!0});let t=`${nv()}.tmp`;T.writeFileSync(t,JSON.stringify({pid:process.pid,bound:[...Ee.keys()],holders:[...Ee.values()].map(e=>({identity:e.identity,pid:e.pid}))})),T.renameSync(t,nv())}catch(t){w("failed to persist bindings snapshot:",String(t))}}var yv=t=>Re(je,t),ds=t=>Re(t,"identity.key"),en=t=>Re(t,"state_data.bin"),Sp=t=>Re(t,"notifications.log"),hp=t=>Re(t,"unread.json"),JI=t=>Re(t.dir,"files");function KI(){for(let t of zp()){let e=Re(je,t);try{T.chmodSync(e,448)}catch(r){w(`[${t}] chmod 0700 failed:`,String(r))}for(let r of[en(e),ds(e)])if(T.existsSync(r))try{T.chmodSync(r,384)}catch(n){w(`[${t}] chmod 0600 ${r} failed:`,String(n))}}}function zp(){return T.existsSync(je)?T.readdirSync(je,{withFileTypes:!0}).filter(t=>t.isDirectory()&&T.existsSync(ds(Re(je,t.name)))).map(t=>t.name):[]}var cs=()=>Re(je,pa),ov=()=>Re(cs(),"registrar.key"),gp=()=>Re(cs(),"book.json");function ga(){try{let t=JSON.parse(T.readFileSync(gp(),"utf8"));return t&&typeof t.entries=="object"?t.entries:{}}catch{return{}}}function _v(t){T.mkdirSync(cs(),{recursive:!0});let e=`${gp()}.tmp`;T.writeFileSync(e,JSON.stringify({v:1,entries:t},null,2),{mode:384}),T.renameSync(e,gp())}function Jn(t){return He(e=>Buffer.from(ke(t,"::actor::export_address_document",e).GetBinary()))}function vv(t){return He(e=>Buffer.from(ke(t,"::actor::export_signing_secret",e).Serialize()).toString("hex"))}async function bv(t){if(!_t)throw new Error("registrar is not available");let e=Jn(t),r=await B(async o=>{let s=await Z(_t,"::actor::sign_book_entry",{name:t.name,ad:_t.pw.packet.NewBinaryFromBuffer(e).Attach(o)},o);return Buffer.from(s.Reduce("sig").GetBinary()).toString("base64url")}),n=ga();n[t.name]={v:1,name:t.name,container_id:t.cid,address_document:e.toString("base64url"),published_at:new Date().toISOString(),registrar_sig:r},_v(n),w(`[${t.name}] published to the local contact book`)}function wv(t){let e=ga();t in e&&(delete e[t],_v(e),w(`[${t}] removed from the local contact book`))}async function $v(t){if(!fp)throw new Error("registrar is not available");await B(async e=>{await Z(t,"::actor::pin_registrar",{registrar_ad:t.pw.packet.NewBinaryFromBuffer(fp).Attach(e)},e)})}var ma=()=>Re(je,"root.json"),ie=null;function WI(){try{let t=JSON.parse(T.readFileSync(ma(),"utf8"));return typeof t.name=="string"?t.name:null}catch{return null}}function YI(t){T.mkdirSync(je,{recursive:!0});let e=`${ma()}.tmp`;T.writeFileSync(e,JSON.stringify({v:1,name:t})),T.renameSync(e,ma())}function xv(){T.rmSync(ma(),{force:!0})}function yt(t){return He(e=>{let r=ke(t,"::actor::describe_identity",e);return{bio:r.Reduce("bio").Visualize(),persona:r.Reduce("persona").Visualize(),hasCert:r.Reduce("has_cert").GetBoolean(),roleId:r.Reduce("role_id").Visualize(),rootCid:r.Reduce("root_cid").Visualize(),rootName:r.Reduce("root_name").Visualize(),monitoringEnabled:r.Reduce("monitoring_enabled").GetBoolean()}})}async function Hn(t,e){await B(async r=>{let n=Jn(e),o=await Z(t,"::actor::sign_delegation",{role_ad:t.pw.packet.NewBinaryFromBuffer(n).Attach(r),role_id:e.name},r),s=Buffer.from(o.Reduce("cert").GetBinary()),i=await Z(t,"::actor::export_root_profile",{},r),a=Buffer.from(i.Reduce("profile").GetBinary()),c=Jn(t),u=Buffer.from((await Z(e,"::actor::export_v1_address_document",{},r)).Reduce("ad").GetBinary()),l=await Z(t,"::actor::sign_delegation",{role_ad:t.pw.packet.NewBinaryFromBuffer(u).Attach(r),role_id:e.name},r),d=Buffer.from(l.Reduce("cert").GetBinary());await Z(e,"::actor::set_delegation",{cert:e.pw.packet.NewBinaryFromBuffer(s).Attach(r),root_ad:e.pw.packet.NewBinaryFromBuffer(c).Attach(r),root_profile:e.pw.packet.NewBinaryFromBuffer(a).Attach(r),cert_v1:e.pw.packet.NewBinaryFromBuffer(d).Attach(r)},r)}),w(`[${e.name}] delegated as a role under root "${t.name}"`)}async function sv(t){ie=t.name,YI(t.name);let e=[],r=[];for(let n of L.values())if(n.name!==t.name)try{await Hn(t,n),e.push(n.name)}catch(o){w(`failed to adopt "${n.name}" as a role under new root "${t.name}":`,String(o)),r.push(n.name)}return w(`[${t.name}] established as the host root${e.length?` (adopted ${e.length} role(s))`:""}`),{adopted:e,failed:r}}function XI(t,e){if(!ie||!L.has(ie))return null;let r=L.get(e)??[...L.values()].find(o=>o.cid===e);if(!r||r.name===t.name)return null;let n=o=>o.name===ie||yt(o).roleId!=="";return n(t)&&n(r)?r:null}async function QI(t,e,r){let n=Jn(e);return await B(async o=>{await Z(t,"::actor::connect_sibling",{name:e.name,target_ad:t.pw.packet.NewBinaryFromBuffer(n).Attach(o),text:r},o)}),`"${e.name}" was not a contact yet \u2014 connected as an intra-root sibling (delegation-cert auto-accept) and delivered the message.`}async function eP(t,e,r){if(!_t)throw new Error(`"${e}" is not a contact, and the local contact book is unavailable.`);let n=ga(),o=n[e]??Object.values(n).find(c=>c.container_id===e);if(!o)throw new Error(`"${e}" is not a contact and has no local contact-book entry. Use generate_invite/add_contact for remote peers, or list_local_contact_book to see local ones.`);if(o.container_id===t.cid)throw new Error("that contact-book entry is this identity itself.");let s=Buffer.from(o.address_document,"base64url"),i=Buffer.from(o.registrar_sig,"base64url"),a=Jn(t);return await B(async c=>{let u=await Z(_t,"::actor::mint_introduction",{joiner_ad:_t.pw.packet.NewBinaryFromBuffer(a).Attach(c),target_ad:_t.pw.packet.NewBinaryFromBuffer(s).Attach(c)},c),l=Buffer.from(u.Reduce("intro").GetBinary());await Z(t,"::actor::connect_local",{name:o.name,target_ad:t.pw.packet.NewBinaryFromBuffer(s).Attach(c),intro:t.pw.packet.NewBinaryFromBuffer(l).Attach(c),entry_sig:t.pw.packet.NewBinaryFromBuffer(i).Attach(c),text:r},c)}),`"${o.name}" was not a contact yet \u2014 connected via the local contact book and sent the message with the introduction. If "${o.name}" requires approval for local introductions, delivery completes once they approve.`}function ps(t){return He(e=>{let r=ke(t,"::a2a_messaging::get_monitoring_status",e),n=ke(t,"::actor::get_monitoring_status",e);return{enabled:r.Reduce("monitored").GetBoolean(),proxyCid:r.Reduce("proxy_cid").Visualize(),proxyPending:r.Reduce("proxy_pending").GetBoolean(),copiesQueued:parseInt(n.Reduce("copies_queued").Visualize(),10)||0,controlQueued:parseInt(n.Reduce("control_queued").Visualize(),10)||0}})}async function as(t,e,r){await B(async n=>{await Z(t,"::a2a_control::send_control",{contact:e,payload:JSON.stringify(r)},n)})}function kv(t){try{return He(e=>{let r=ke(t,"::a2a_capabilities::get_manifest",e).Reduce("capabilities");return r.IsNil()?[]:[...r.GetKeys()].map(n=>typeof n=="string"?n:n.Visualize())})}catch{return[]}}function tP(t){let e="",r="",n="",o="",s=[];try{He(i=>{let a=ke(t,"::a2a_capabilities::get_manifest",i),c=l=>{let d=a.Reduce(l);return d.IsNil()?"":d.Visualize()};e=c("app_id"),r=c("name"),n=c("description"),o=c("version");let u=a.Reduce("capabilities");u.IsNil()||(s=[...u.GetKeys()].map(l=>typeof l=="string"?l:l.Visualize()))})}catch{}return{app_id:e,name:r,description:n,version:o,capabilities:s,monitoring_status:ps(t).proxyCid?"bound":"unbound"}}function rP(t){let e=[];for(let r of L.values()){if(r.name===t.name)continue;let n=yt(r);n.rootCid===t.cid&&e.push({name:r.name,cid:r.cid,role_id:n.roleId,bio:n.bio,monitoring:n.monitoringEnabled,capabilities:kv(r)})}return e}function Sv(t){try{Qr.remove_packet(t.cid)}catch(e){w(`remove_packet(${t.cid}) failed:`,String(e))}L.delete(t.name);try{wv(t.name)}catch(e){w(`failed to unpublish "${t.name}" from the contact book:`,String(e))}Ee.has(t.name)&&(Ee.delete(t.name),ls()),t.name===ie&&(ie=null,xv());try{T.rmSync(t.dir,{recursive:!0,force:!0}),mr.delete(t.name)}catch(e){return`deleting ${t.dir} failed: ${String(e)}`}return null}var Rp=!0,zv=Rp?2:1,nP=6e5,yp=new Map,_p=(t,e)=>`${t}:${e}`;function Rv(t,e,r){e&&yp.set(_p(t,e),{response:r,at:Date.now()})}function oP(t,e){if(!e)return;let r=yp.get(_p(t,e));if(r){if(Date.now()-r.at>nP){yp.delete(_p(t,e));return}return r.response}}async function sP(t,e,r){let n=us(r);if(!n||typeof n!="object")return;let o=n,s=o.result;if(s&&typeof s=="object"&&s.pending===!0)return;let i=String(o.req_id??"");i&&(await as(t,e,o),Rv(e,i,o))}async function iP(t,e,r,n,o,s){let i;try{let d=JSON.parse(o);if(!d||typeof d!="object")throw new Error("not an object");i=d}catch{w(`[${t.name}] dropping unparseable control payload from ${n}`);return}if(i.v===1){i.t==="get_manifest"?await as(t,r,{v:1,t:"res",id:i.id??null,ok:!0,manifest:{...tP(t),protocol_version:zv}}):await as(t,r,{v:1,t:"res",id:i.id??null,error:{code:"protocol_upgraded",message:"This host now speaks the ours control-envelope protocol (v2). Refresh / cache-bust the control plane."}});return}let a=String(i.req_id??""),c=oP(r,a);if(c){await as(t,r,c);return}let u=i.args&&typeof i.args=="object"?i.args:{},l={cap:String(i.cap??""),verb:String(i.verb??""),args:u,req_id:a};await B(async d=>{let p;try{p=await Z(t,"::actor::process_control_envelope",{sender_id:e,sender_name:n,envelope:l,date:s},d)}catch(f){w(`[${t.name}] dispatch of "${l.cap}.${l.verb}" from ${n} failed:`,String(f));return}if(await sP(t,r,p),l.cap==="core.monitoring"&&l.verb==="bind")try{let f=us(p);f&&(f.ok===!0||f.$ok===!0)&&pP(t,r)}catch{}})}async function aP(t){for(;;)if(await B(async r=>{let o=(await Z(t,"::actor::get_control_requests",{},r)).Reduce("requests"),s=o.GetKeys();if(s.length===0)return!0;for(let i=0;i<s.length;i++){let a=o.Reduce(i),c=a.Reduce("sender_cid");await iP(t,c,c.Visualize(),a.Reduce("sender_name").Visualize(),a.Reduce("payload").Visualize(),a.Reduce("date"))}return!1}))return}function cP(){return String(mv(0,1e6)).padStart(6,"0")}var tn=new Map;function ya(t){return[...L.values()].find(e=>e.cid===t)}async function fs(t,e){let r=e.Reduce("target").Visualize(),n=us(e.Reduce("response"));if(!n||typeof n!="object")return;await as(t,r,n);let o=String(n.req_id??"");o&&Rv(r,o,n)}async function uP(t,e,r,n){try{if(L.has(e)){w(`[${t.name}] host_provision_child("${e}") rejected: name exists (settles via sweep timeout)`);return}let o=await xp(e);await B(async s=>{r&&await Z(o,"::a2a_messaging::set_my_bio",{bio:r},s),await Hn(t,o);let i=yt(o).roleId,a=ke(o,"::actor::export_address_document_native",s),c=await Z(t,"::a2a_cluster::register_provisioned_child",{pending_handle:n,role_id:i,child_ad:a},s);await fs(t,c)})}catch(o){w(`[${t.name}] host_provision_child("${e}") failed (settles via sweep timeout):`,String(o))}}async function lP(t,e,r){try{let n=ya(e.Visualize());if(n){let o=Sv(n);o&&w(`[${t.name}] host_destroy_child teardown warning:`,o)}tn.delete(e.Visualize()),await B(async o=>{let s=await Z(t,"::a2a_cluster::confirm_child_destroyed",{pending_handle:r,cid:e},o);await fs(t,s)})}catch(n){w(`[${t.name}] host_destroy_child failed (settles via sweep timeout):`,String(n))}}async function dP(t,e,r){try{let n=ya(e.Visualize());if(!n){w(`[${t.name}] host_mint_child_invite: unknown child ${e.Visualize()} (settles via sweep timeout)`);return}await B(async o=>{let s=await Z(n,"::a2a_messaging::generate_invite",{},o),i=t.pw.packet.NewBinaryFromBuffer(Buffer.from(s.Reduce("invite").GetBinary())).Attach(o),a=await Z(t,"::a2a_cluster::register_child_invite",{pending_handle:r,invite:i},o);await fs(t,a)})}catch(n){w(`[${t.name}] host_mint_child_invite failed (settles via sweep timeout):`,String(n))}}async function vp(t,e,r,n){await B(async o=>{if(e){n&&await Z(t,"::a2a_messaging::host_register_monitoring_cp",{cp_ad:n},o);let s=cP();await Z(t,"::a2a_messaging::set_proxy_pending",{code:s,proxy:r},o),await Z(t,"::a2a_messaging::verify_proxy_code",{code:s,sender:r},o),tn.set(t.cid,r??"")}else await Z(t,"::a2a_messaging::host_clear_child_monitoring",{},o),tn.delete(t.cid)})}async function iv(t,e,r,n,o,s){try{let i=ya(e.Visualize());if(!i){w(`[${t.name}] host_set_child_monitoring: unknown child ${e.Visualize()} (settles via sweep timeout)`);return}r?await vp(i,!0,o?.Visualize(),s):await vp(i,!1),await B(async a=>{let c=await Z(t,"::a2a_cluster::confirm_child_monitoring",{pending_handle:n,cid:e,enabled:r},a);await fs(t,c)})}catch(i){w(`[${t.name}] host_set_child_monitoring failed (settles via sweep timeout):`,String(i))}}async function pP(t,e){for(let[r,n]of[...tn.entries()]){if(n===e)continue;let o=ya(r);if(!o){tn.delete(r);continue}await vp(o,!1).catch(s=>w(`[${t.name}] CP-rebind clear of child ${r} failed:`,String(s)))}}function fP(t,e){let r=[];for(let n of L.values()){if(n.name===t.name)continue;let o=yt(n);if(o.rootCid!==t.cid)continue;let s=ke(n,"::actor::export_address_document_native",e);r.push({cid:s.Reduce("identity").Reduce("container_id"),role_id:o.roleId,name:n.name,bio:o.bio,persona:o.persona,caps:kv(n),child_ad:s})}return r}var cp=new Set;async function Tv(t){if(!cp.has(t.name)){cp.add(t.name);try{await B(async e=>{await Z(t,"::a2a_cluster::reconcile",{pending_handle:"",children:fP(t,e)},e);let n=(await Z(t,"::a2a_cluster::sweep_and_settle",{},e)).Reduce("settled"),o=n.GetKeys();for(let s=0;s<o.length;s++)await fs(t,n.Reduce(s))})}catch(e){w(`[${t.name}] cluster sweep failed:`,String(e))}finally{cp.delete(t.name)}}}var mP=6e4;function hP(){setInterval(()=>{if(Rp)for(let t of L.values())yt(t).roleId===""&&Tv(t)},mP).unref()}function gP(){for(let t of L.values())if(yt(t).roleId!=="")try{let e=ps(t).proxyCid;e&&tn.set(t.cid,e)}catch(e){tn.set(t.cid,""),w(`[${t.name}] monitoredChildren rebuild read failed (added clear-on-repoint):`,String(e))}}var up=new Set;async function Tp(t){if(!up.has(t.name)){up.add(t.name);try{await aP(t)}catch(e){w(`[${t.name}] control dispatch failed:`,String(e))}finally{up.delete(t.name)}if(L.has(t.name)&&ps(t).controlQueued>0)return Tp(t)}}async function yP(){T.mkdirSync(cs(),{recursive:!0});let t;try{t=T.readFileSync(ov(),"utf8").trim()}catch{}let e=fv(24).toString("hex");_t=await Ip(pa,e,cs(),!1,t),t||T.writeFileSync(ov(),vv(_t),{mode:384}),fp=Jn(_t),w(`contact-book registrar ready (${_t.cid})`)}function _P(t){try{return T.existsSync(en(t))&&T.statSync(en(t)).size>0}catch{return!1}}function bp(t){let e=He(s=>Buffer.from(ke(t,"::actor::export_state",s).Serialize()));T.mkdirSync(t.dir,{recursive:!0,mode:448});let r=en(t.dir),n=`${r}.tmp`,o;try{o=T.openSync(n,"w",384),T.fchmodSync(o,384),T.writeFileSync(o,e),T.fsyncSync(o),T.closeSync(o),o=void 0,T.renameSync(n,r),T.chmodSync(r,384);try{T.chmodSync(ds(t.dir),384)}catch{}let s=T.openSync(t.dir,"r");try{T.fsyncSync(s)}finally{T.closeSync(s)}}catch(s){if(o!==void 0)try{T.closeSync(o)}catch{}try{T.rmSync(n,{force:!0})}catch{}throw s}}function Ep(t){try{bp(t),t.persistFailed&&(t.persistFailed=!1,w(`[${t.name}] persist recovered \u2014 quarantine lifted`),me(t,{event:"persist_recovered"}))}catch(e){t.persistFailed=!0,w(`[${t.name}] PERSIST FAILED \u2014 identity quarantined (fail-closed), outbound of this txn withheld:`,String(e));try{me(t,{event:"persist_failed",error:String(e).slice(0,300)})}catch{}throw process.nextTick(()=>tt(t.name,`[${t.name}] PERSIST FAILED \u2014 messaging quarantined until the state file is writable again`)),e}}function vP(t){let e=[],r=t.Reduce("degraded");if(r.IsNil())return e;for(let n=0;;n++){let o=r.Reduce(n);if(o.IsNil())break;e.push({cid:o.Reduce("container_id").Visualize(),name:o.Reduce("name").Visualize(),attempts:Number(o.Reduce("attempts").Visualize()),queued:Number(o.Reduce("queued").Visualize())})}return e}function bP(t){let e=[],r=t.Reduce("queues");if(r.IsNil())return e;for(let n=0;;n++){let o=r.Reduce(n);if(o.IsNil())break;e.push({cid:o.Reduce("container_id").Visualize(),queued:Number(o.Reduce("queued").Visualize()),degraded:o.Reduce("degraded").GetBoolean()})}return e}async function Ev(t,e){try{let r=await B(async n=>{let o=await Z(t,"::a2a_messaging::flush_deferred",{contact:e},n);return Number(o.Reduce("flushed").Visualize())});r>0&&w(`[${t.name}] flushed ${r} deferred message(s) to ${e.slice(0,12)}\u2026`)}catch(r){w(`[${t.name}] deferred flush to ${e.slice(0,12)}\u2026 failed:`,String(r))}}async function Iv(t){try{let e=await B(async n=>{let o=await Z(t,"::a2a_messaging::restore_degraded_contacts",{},n);return Number(o.Reduce("requested").Visualize())});e>0&&w(`[${t.name}] contact restore requested for ${e} degraded contact(s)`);let r=He(n=>bP(ke(t,"::a2a_messaging::list_deferred_queues",n)));for(let n of r)n.degraded||await Ev(t,n.cid)}catch(e){w(`[${t.name}] contact-restore sweep failed:`,String(e))}}async function wp(t){try{let e=await B(async r=>{let n=await Z(t,"::a2a_messaging::readvertise_on_upgrade",{},r);return Number(n.Reduce("readvertised").Visualize())});e>0&&w(`[${t.name}] re-advertised v2 AD to ${e} pre-existing legacy contact(s) (migration bootstrap)`)}catch(e){w(`[${t.name}] readvertise-on-upgrade sweep failed:`,String(e))}}async function $p(t){try{let e=await B(async r=>{let n=await Z(t,"::a2a_messaging::readvertise_e2e_recovery",{},r);return Number(n.Reduce("readvertised").Visualize())});e>0&&w(`[${t.name}] re-advertised fresh AD to ${e} e2e contact(s) (session recovery)`)}catch(e){w(`[${t.name}] e2e recovery re-advertise failed:`,String(e))}try{await B(async e=>{await Z(t,"::a2a_messaging::sweep_e2e_migrations",{},e)})}catch(e){w(`[${t.name}] e2e migration sweep failed:`,String(e))}try{let e=await B(async r=>{let n=await Z(t,"::a2a_messaging::redrive_unacked_sweep",{},r),o=s=>n.Reduce(s).IsNil()?0:Number(n.Reduce(s).Visualize());return{redriven:o("redriven_contacts"),purged:o("purged_contacts"),deferred:o("deferred_contacts")}});(e.redriven>0||e.purged>0||e.deferred>0)&&w(`[${t.name}] unacked sweep: redriven=${e.redriven} ttl_purged=${e.purged} deferred=${e.deferred} contact(s)`)}catch(e){w(`[${t.name}] unacked redrive sweep failed:`,String(e))}}var ua=new Map;function wP(t){let e=ua.get(t);if(!(!e||e.size===0))for(let r of[...e])try{r()}catch{}}function $P(t,e){return new Promise(r=>{let n=ua.get(t);n||(n=new Set,ua.set(t,n));let o=!1,s=()=>{o||(o=!0,n.delete(i),n.size===0&&ua.delete(t),clearTimeout(a),r())},i=s,a=setTimeout(s,e);n.add(i)})}function me(t,e){try{T.mkdirSync(t.dir,{recursive:!0,mode:448}),T.appendFileSync(Sp(t.dir),JSON.stringify(e)+`
|
|
58
58
|
`)}catch(r){w(`[${t.name}] failed to append notifications.log:`,String(r))}wP(t.name)}function xP(t){let e=Sp(t.dir),r="";try{r=T.readFileSync(e,"utf8")}catch{return new Set}let n=[];for(let o of r.split(`
|
|
59
59
|
`))if(o.trim())try{n.push(JSON.parse(o))}catch{}return X_(n)}function os(t,e){let r=t.Reduce(e);return r.IsNil()?"":Buffer.from(r.GetBinary()).toString("hex")}var kP=Number(process.env.OURS_NOTIFY_LONGPOLL_MS)>0?Number(process.env.OURS_NOTIFY_LONGPOLL_MS):25e3,SP=250;function lp(t){try{return T.statSync(t).size}catch{return 0}}function zP(t,e,r){if(r<=e)return{events:[],cursor:e};let n=Buffer.alloc(r-e),o=0;try{let c=T.openSync(t,"r");try{o=T.readSync(c,n,0,n.length,e)}finally{T.closeSync(c)}}catch{return{events:[],cursor:e}}let s=n.subarray(0,o),i=s.lastIndexOf(10);if(i===-1)return{events:[],cursor:e};let a=[];for(let c of s.subarray(0,i+1).toString("utf8").split(`
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ours.network/mcp",
|
|
3
|
-
"version": "0.12.0-nightly.
|
|
3
|
+
"version": "0.12.0-nightly.14",
|
|
4
4
|
"description": "MCP server daemon for ours — one native ADAPT wrapper hosting N self-sovereign identities, exposing secure agent-to-agent messaging tools over HTTP (Streamable HTTP). Run `ours-mcp start`.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "FSL-1.1-Apache-2.0",
|
|
@@ -48,11 +48,11 @@
|
|
|
48
48
|
"serve": "node dist/cli.js serve",
|
|
49
49
|
"prepublishOnly": "node build.mjs",
|
|
50
50
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
51
|
-
"test": "node test/loopback-bind.test.mjs && node test/lease-binding.test.mjs && node test/session-restore.test.mjs && node test/daemon-restart-resume.test.mjs && node test/version-advisory.test.mjs && node test/files-helpers.test.mjs && node test/inbox-encryption.test.mjs && node test/validate-name.test.mjs && node test/port-visibility.test.mjs && node test/notify-http-api.test.mjs && node test/unread-http-api.test.mjs && node test/create-root-cli.test.mjs && node test/session-reaper.test.mjs && node test/mig1867-verify.test.mjs && node test/single-root-policy.test.mjs"
|
|
51
|
+
"test": "node test/loopback-bind.test.mjs && node test/lease-binding.test.mjs && node test/session-restore.test.mjs && node test/daemon-restart-resume.test.mjs && node test/version-advisory.test.mjs && node test/files-helpers.test.mjs && node test/inbox-encryption.test.mjs && node test/validate-name.test.mjs && node test/port-visibility.test.mjs && node test/notify-http-api.test.mjs && node test/unread-http-api.test.mjs && node test/create-root-cli.test.mjs && node test/session-reaper.test.mjs && node test/mig1867-verify.test.mjs && node test/single-root-policy.test.mjs && node test/pre137-blob-import-regression.test.mjs"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@adapt-toolkit/sdk": "
|
|
55
|
-
"@adapt-toolkit/sdk-native": "0.10.
|
|
54
|
+
"@adapt-toolkit/sdk": "0.10.12",
|
|
55
|
+
"@adapt-toolkit/sdk-native": "0.10.12"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@modelcontextprotocol/sdk": "^1.0.4",
|