@ours.network/mcp 0.9.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -46,16 +46,14 @@ ${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 JS(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),ek(r)}clear(){this._buffer=void 0}};function ek(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 tk,writeFileSync as rk,readFileSync as nk,readdirSync as ok,statSync as Ng,unlinkSync as sk,chmodSync as jg}from"node:fs";import{join as Es}from"node:path";import{homedir as ik}from"node:os";var ak="0.9.1",ck=new Set(["choose_identity","create_identity","create_root_identity"]),Zg=e=>new Promise(t=>setTimeout(t,e)),uk=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,lk=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(" ")}
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 tk,writeFileSync as rk,readFileSync as nk,readdirSync as ok,statSync as Ng,unlinkSync as sk,chmodSync as jg}from"node:fs";import{join as Es}from"node:path";import{homedir as ik}from"node:os";var ak="0.10.1",ck=new Set(["choose_identity","create_identity","create_root_identity"]),Zg=e=>new Promise(t=>setTimeout(t,e)),uk=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,lk=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(ik(),".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{tk(g,{recursive:!0,mode:448}),rk(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(nk(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 ok(g)){if(!F.endsWith(".json"))continue;let G=Es(g,F);try{I-Ng(G).mtimeMs>Dg&&(sk(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),uk(_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&&ck.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(lk(_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:ak,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=pk(import.meta.url),b=(...e)=>process.stdout.write(`${e.join(" ")}
53
53
  `),W=(...e)=>process.stderr.write(`${e.join(" ")}
54
- `),ar="0.9.1";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 mk(){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=mk();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=dk({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 hk(){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 gk(){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 _k(){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 yk(){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(`
54
+ `),ar="0.10.1";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 mk(){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=mk();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=dk({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 hk(){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 gk(){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 _k(){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 yk(){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 vk(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 wk(),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
- ${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 wk(){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 $k(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}}),s=(Array.isArray(o.content)?o.content:[]).map(i=>typeof i.text=="string"?i.text:"").join(" ").split(`
57
-
58
- Ask the user:`)[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==="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)`):b(`[${e}] new message from ${t.from??"?"}`+(t.msg_id!==void 0?` (#${t.msg_id})`:"")+(t.date?` (${t.date})`:""))}function jt(e){W(`ours-mcp watch: ${e}`),process.exit(1)}async function bk(){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 xk=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(`${xk(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 zk(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 Sk(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(`
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 wk(){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 $k(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}}),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==="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)`):b(`[${e}] new message from ${t.from??"?"}`+(t.msg_id!==void 0?` (#${t.msg_id})`:"")+(t.date?` (${t.date})`:""))}function jt(e){W(`ours-mcp watch: ${e}`),process.exit(1)}async function bk(){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 xk=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(`${xk(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 zk(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 Sk(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(`
59
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 kk(){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 Pk(e){let t=()=>process.exit(0);if(process.on("SIGINT",t),process.on("SIGTERM",t),await bk()!==null&&await kk()==="api"){W(`ours-mcp watch: streaming ${e?`identity "${e}"`:"all identities"} from the daemon API on port ${ne} (Ctrl-C to stop)`),await zk(e);return}Sk(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 Tk(){let e=Xg();U.mkdirSync($u(e),{recursive:!0});let t=`[Unit]
60
58
  Description=ours MCP daemon (secure agent-to-agent messaging over ADAPT)
61
59
  After=network-online.target