@ours.network/mcp 0.1.1 → 0.1.3
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/README.md +1 -1
- package/dist/cli.js +3 -3
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ exposes the messaging tools — each a thin wrapper over one MUFL user transacti
|
|
|
22
22
|
| Env var | Default | Meaning |
|
|
23
23
|
|---------|---------|---------|
|
|
24
24
|
| `OURS_STATE_DIR` | `~/.ours` | Node identity + serialized state. Distinct per node. |
|
|
25
|
-
| `OURS_BROKER_URL` | `
|
|
25
|
+
| `OURS_BROKER_URL` | `wss://ours.network/broker_new` | The ADAPT broker to connect through. Set to `ws://localhost:9000` for a local broker. |
|
|
26
26
|
|
|
27
27
|
## Daemon lifecycle
|
|
28
28
|
|
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
3
|
-
var Ac=Object.defineProperty;var gr=(e,t)=>{for(var r in t)Ac(e,r,{get:t[r],enumerable:!0})};import{spawn as bc,spawnSync as dr}from"node:child_process";import{connect as Ld}from"node:net";import{homedir as Sc,userInfo as xc}from"node:os";import{resolve as $c,join as je,dirname as Uo}from"node:path";import{fileURLToPath as Dd,pathToFileURL as Md}from"node:url";import{createInterface as lr}from"node:readline/promises";import*as Z from"node:fs";import*as de from"node:fs";import{homedir as qo}from"node:os";import{resolve as Ut,join as Bo,dirname as Vo,basename as Uc}from"node:path";var ot={brokerUrl:"wss://ours.network/
|
|
3
|
+
var Ac=Object.defineProperty;var gr=(e,t)=>{for(var r in t)Ac(e,r,{get:t[r],enumerable:!0})};import{spawn as bc,spawnSync as dr}from"node:child_process";import{connect as Ld}from"node:net";import{homedir as Sc,userInfo as xc}from"node:os";import{resolve as $c,join as je,dirname as Uo}from"node:path";import{fileURLToPath as Dd,pathToFileURL as Md}from"node:url";import{createInterface as lr}from"node:readline/promises";import*as Z from"node:fs";import*as de from"node:fs";import{homedir as qo}from"node:os";import{resolve as Ut,join as Bo,dirname as Vo,basename as Uc}from"node:path";var ot={brokerUrl:"wss://ours.network/broker_new",port:3050,stateDir:Ut(qo(),".ours"),gcIntervalMs:36e5,autoStart:!1};function Nt(){return process.env.OURS_CONFIG??Bo(qo(),".ours","config.json")}function Nc(){let e;try{e=de.readFileSync(Nt(),"utf8")}catch{return{}}let t;try{t=JSON.parse(e)}catch{return{}}let r={};return typeof t.brokerUrl=="string"&&(r.brokerUrl=t.brokerUrl),typeof t.port=="number"&&Number.isFinite(t.port)&&(r.port=t.port),typeof t.stateDir=="string"&&(r.stateDir=Ut(t.stateDir)),typeof t.gcIntervalMs=="number"&&Number.isFinite(t.gcIntervalMs)&&(r.gcIntervalMs=t.gcIntervalMs),typeof t.autoStart=="boolean"&&(r.autoStart=t.autoStart),r}function jc(e){let t=process.env[e];if(t!==void 0)return t==="1"||t.toLowerCase()==="true"}function Fo(e){let t=process.env[e];if(t===void 0)return;let r=parseInt(t,10);return Number.isNaN(r)?void 0:r}function _r(){let e=Nc();return{brokerUrl:process.env.OURS_BROKER_URL??e.brokerUrl??ot.brokerUrl,port:Fo("OURS_PORT")??e.port??ot.port,stateDir:Ut(process.env.OURS_STATE_DIR??e.stateDir??ot.stateDir),gcIntervalMs:Fo("OURS_GC_INTERVAL_MS")??e.gcIntervalMs??ot.gcIntervalMs,autoStart:jc("OURS_AUTOSTART")??e.autoStart??ot.autoStart}}function Wo(e){let t=Nt();de.mkdirSync(Vo(t),{recursive:!0}),de.writeFileSync(t,JSON.stringify(e,null,2)+`
|
|
4
4
|
`,{mode:384});try{de.chmodSync(t,384)}catch{}return t}var At=".ours-identity";function jt(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 zr(e){let t=Ut(e);return Uc(t)===At?t:Bo(t,At)}function Jo(e,t,r=!1){let o=jt(t),n=zr(e);if(!r&&de.existsSync(n))throw new Error(`${n} already exists \u2014 pass overwrite to replace it`);return de.mkdirSync(Vo(n),{recursive:!0}),de.writeFileSync(n,JSON.stringify(o,null,2)+`
|
|
5
5
|
`),n}import Ba from"node:process";var xr=Object.freeze({status:"aborted"});function u(e,t,r){function o(c,l){var p;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(p=c._zod).traits??(p.traits=new Set),c._zod.traits.add(e),t(c,l);for(let f in s.prototype)f in c||Object.defineProperty(c,f,{value:s.prototype[f].bind(c)});c._zod.constr=s,c._zod.def=l}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function s(c){var l;let p=r?.Parent?new i:this;o(p,c),(l=p._zod).deferred??(l.deferred=[]);for(let f of p._zod.deferred)f();return p}return Object.defineProperty(s,"init",{value:o}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var Lc=Symbol("zod_brand"),ye=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Lt={};function ce(e){return e&&Object.assign(Lt,e),Lt}var O={};gr(O,{BIGINT_FORMAT_RANGES:()=>Ho,Class:()=>yr,NUMBER_FORMAT_RANGES:()=>Zr,aborted:()=>Ze,allowsEval:()=>kr,assert:()=>Bc,assertEqual:()=>Dc,assertIs:()=>Fc,assertNever:()=>qc,assertNotEqual:()=>Mc,assignProp:()=>$r,cached:()=>it,captureStackTrace:()=>Mt,cleanEnum:()=>ou,cleanRegex:()=>at,clone:()=>ge,createTransparentProxy:()=>Kc,defineLazy:()=>N,esc:()=>Pe,escapeRegex:()=>$e,extend:()=>Qc,finalizeIssue:()=>_e,floatSafeRemainder:()=>Sr,getElementAtPath:()=>Vc,getEnumValues:()=>wr,getLengthableOrigin:()=>ct,getParsedType:()=>Hc,getSizableOrigin:()=>Ko,isObject:()=>Me,isPlainObject:()=>Fe,issue:()=>Ir,joinValues:()=>Dt,jsonStringifyReplacer:()=>br,merge:()=>eu,normalizeParams:()=>b,nullish:()=>st,numKeys:()=>Gc,omit:()=>Xc,optionalKeys:()=>Pr,partial:()=>tu,pick:()=>Yc,prefixIssues:()=>xe,primitiveTypes:()=>Go,promiseAllObject:()=>Wc,propertyKeyTypes:()=>Rr,randomString:()=>Jc,required:()=>ru,stringifyPrimitive:()=>Ft,unwrapMessage:()=>nt});function Dc(e){return e}function Mc(e){return e}function Fc(e){}function qc(e){throw new Error}function Bc(e){}function wr(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function Dt(e,t="|"){return e.map(r=>Ft(r)).join(t)}function br(e,t){return typeof t=="bigint"?t.toString():t}function it(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function st(e){return e==null}function at(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Sr(e,t){let r=(e.toString().split(".")[1]||"").length,o=(t.toString().split(".")[1]||"").length,n=r>o?r:o,i=Number.parseInt(e.toFixed(n).replace(".","")),s=Number.parseInt(t.toFixed(n).replace(".",""));return i%s/10**n}function N(e,t,r){Object.defineProperty(e,t,{get(){{let n=r();return e[t]=n,n}throw new Error("cached value already set")},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function $r(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Vc(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function Wc(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function Jc(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function Pe(e){return JSON.stringify(e)}var Mt=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var kr=it(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Fe(e){if(Me(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(Me(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Gc(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var Hc=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Rr=new Set(["string","number","symbol"]),Go=new Set(["string","number","bigint","boolean","symbol","undefined"]);function $e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ge(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function b(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Kc(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function Ft(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Pr(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Zr={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ho={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Yc(e,t){let r={},o=e._zod.def;for(let n in t){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(r[n]=o.shape[n])}return ge(e,{...e._zod.def,shape:r,checks:[]})}function Xc(e,t){let r={...e._zod.def.shape},o=e._zod.def;for(let n in t){if(!(n in o.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&delete r[n]}return ge(e,{...e._zod.def,shape:r,checks:[]})}function Qc(e,t){if(!Fe(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let o={...e._zod.def.shape,...t};return $r(this,"shape",o),o},checks:[]};return ge(e,r)}function eu(e,t){return ge(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return $r(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function tu(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=e?new e({type:"optional",innerType:o[i]}):o[i])}else for(let i in o)n[i]=e?new e({type:"optional",innerType:o[i]}):o[i];return ge(t,{...t._zod.def,shape:n,checks:[]})}function ru(e,t,r){let o=t._zod.def.shape,n={...o};if(r)for(let i in r){if(!(i in n))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(n[i]=new e({type:"nonoptional",innerType:o[i]}))}else for(let i in o)n[i]=new e({type:"nonoptional",innerType:o[i]});return ge(t,{...t._zod.def,shape:n,checks:[]})}function Ze(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function xe(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function nt(e){return typeof e=="string"?e:e?.message}function _e(e,t,r){let o={...e,path:e.path??[]};if(!e.message){let n=nt(e.inst?._zod.def?.error?.(e))??nt(t?.error?.(e))??nt(r.customError?.(e))??nt(r.localeError?.(e))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,t?.reportInput||delete o.input,o}function Ko(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ct(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ir(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function ou(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var yr=class{constructor(...t){}};var Yo=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,br,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},qt=u("$ZodError",Yo),Tr=u("$ZodError",Yo,{Parent:Error});function Or(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function Cr(e,t){let r=t||function(i){return i.message},o={_errors:[]},n=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(c=>n({issues:c}));else if(s.code==="invalid_key")n({issues:s.issues});else if(s.code==="invalid_element")n({issues:s.issues});else if(s.path.length===0)o._errors.push(r(s));else{let c=o,l=0;for(;l<s.path.length;){let p=s.path[l];l===s.path.length-1?(c[p]=c[p]||{_errors:[]},c[p]._errors.push(r(s))):c[p]=c[p]||{_errors:[]},c=c[p],l++}}};return n(e),o}var Xo=e=>(t,r,o,n)=>{let i=o?Object.assign(o,{async:!1}):{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new ye;if(s.issues.length){let c=new(n?.Err??e)(s.issues.map(l=>_e(l,i,ce())));throw Mt(c,n?.callee),c}return s.value};var Qo=e=>async(t,r,o,n)=>{let i=o?Object.assign(o,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let c=new(n?.Err??e)(s.issues.map(l=>_e(l,i,ce())));throw Mt(c,n?.callee),c}return s.value};var Er=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new ye;return i.issues.length?{success:!1,error:new(e??qt)(i.issues.map(s=>_e(s,n,ce())))}:{success:!0,data:i.value}},en=Er(Tr),Ar=e=>async(t,r,o)=>{let n=o?Object.assign(o,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>_e(s,n,ce())))}:{success:!0,data:i.value}},tn=Ar(Tr);var rn=/^[cC][^\s-]{8,}$/,on=/^[0-9a-z]+$/,nn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,sn=/^[0-9a-vA-V]{20}$/,an=/^[A-Za-z0-9]{27}$/,cn=/^[a-zA-Z0-9_-]{21}$/,un=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ln=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ur=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var pn=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var iu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function dn(){return new RegExp(iu,"u")}var mn=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,fn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,hn=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,gn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_n=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Nr=/^[A-Za-z0-9_-]*$/,zn=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var xn=/^\+(?:[0-9]){6,14}[0-9]$/,vn="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",yn=new RegExp(`^${vn}$`);function wn(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function bn(e){return new RegExp(`^${wn(e)}$`)}function Sn(e){let t=wn({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${vn}T(?:${o})$`)}var $n=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},kn=/^\d+n?$/,Rn=/^\d+$/,Pn=/^-?\d+(?:\.\d+)?/i,Zn=/true|false/i,In=/null/i;var Tn=/^[^A-Z]*$/,On=/^[^a-z]*$/;var ie=u("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Cn={number:"number",bigint:"bigint",object:"date"},jr=u("$ZodCheckLessThan",(e,t)=>{ie.init(e,t);let r=Cn[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Lr=u("$ZodCheckGreaterThan",(e,t)=>{ie.init(e,t);let r=Cn[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),En=u("$ZodCheckMultipleOf",(e,t)=>{ie.init(e,t),e._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Sr(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),An=u("$ZodCheckNumberFormat",(e,t)=>{ie.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=Zr[t.format];e._zod.onattach.push(s=>{let c=s._zod.bag;c.format=t.format,c.minimum=n,c.maximum=i,r&&(c.pattern=Rn)}),e._zod.check=s=>{let c=s.value;if(r){if(!Number.isInteger(c)){s.issues.push({expected:o,format:t.format,code:"invalid_type",input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort}):s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,continue:!t.abort});return}}c<n&&s.issues.push({origin:"number",input:c,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),c>i&&s.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:e})}});var Un=u("$ZodCheckMaxLength",(e,t)=>{var r;ie.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!st(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let s=ct(n);o.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),Nn=u("$ZodCheckMinLength",(e,t)=>{var r;ie.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!st(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let s=ct(n);o.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),jn=u("$ZodCheckLengthEquals",(e,t)=>{var r;ie.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!st(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=o=>{let n=o.value,i=n.length;if(i===t.length)return;let s=ct(n),c=i>t.length;o.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),ut=u("$ZodCheckStringFormat",(e,t)=>{var r,o;ie.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),Ln=u("$ZodCheckRegex",(e,t)=>{ut.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Dn=u("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Tn),ut.init(e,t)}),Mn=u("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=On),ut.init(e,t)}),Fn=u("$ZodCheckIncludes",(e,t)=>{ie.init(e,t);let r=$e(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),qn=u("$ZodCheckStartsWith",(e,t)=>{ie.init(e,t);let r=new RegExp(`^${$e(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),Bn=u("$ZodCheckEndsWith",(e,t)=>{ie.init(e,t);let r=new RegExp(`.*${$e(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});var Vn=u("$ZodCheckOverwrite",(e,t)=>{ie.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var Vt=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
|
|
6
6
|
`).filter(s=>s),n=Math.min(...o.map(s=>s.length-s.trimStart().length)),i=o.map(s=>s.slice(n)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,n=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,n.join(`
|
|
@@ -38,12 +38,12 @@ ${se}`,g++}else cc(v,z,D)?x=v.slice(v.charCodeAt(z+6)===Ae?z+7:z+6,$)||void 0:H(
|
|
|
38
38
|
`,z)}return v.slice(z)}for(;z<v.length;){let $=v.indexOf("\r",z),D=v.indexOf(`
|
|
39
39
|
`,z),W=-1;if($!==-1&&D!==-1?W=$<D?$:D:$!==-1?$===v.length-1?W=-1:W=$:D!==-1&&(W=D),W===-1)break;H(v,z,W),z=W+1,v.charCodeAt(z-1)===Rd&&v.charCodeAt(z)===sc&&z++}return v.slice(z)}function H(v,z,$){if(z===$){k();return}let D=v.charCodeAt(z);if(ac(v,z,D)){let pe=v.charCodeAt(z+5)===Ae?z+6:z+5,De=v.slice(pe,$);f=g===0?De:`${f}
|
|
40
40
|
${De}`,g++;return}if(cc(v,z,D)){x=v.slice(v.charCodeAt(z+6)===Ae?z+7:z+6,$)||void 0;return}if(D===105&&v.charCodeAt(z+1)===100&&v.charCodeAt(z+2)===58){let pe=v.slice(v.charCodeAt(z+3)===Ae?z+4:z+3,$);p=pe.includes("\0")?void 0:pe;return}if(D===58){if(n){let pe=v.slice(z,$);n(pe.slice(v.charCodeAt(z+1)===Ae?2:1))}return}let W=v.slice(z,$),se=W.indexOf(":");if(se===-1){A(W,"",W);return}let Le=W.slice(0,se),mr=W.charCodeAt(se+1)===Ae?2:1,rt=W.slice(se+mr);A(Le,rt,W)}function A(v,z,$){switch(v){case"event":x=z||void 0;break;case"data":f=g===0?z:`${f}
|
|
41
|
-
${z}`,g++;break;case"id":p=z.includes("\0")?void 0:z;break;case"retry":/^\d+$/.test(z)?o(parseInt(z,10)):r(new Tt(`Invalid \`retry\` value: "${z}"`,{type:"invalid-retry",value:z,line:$}));break;default:r(new Tt(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:z,line:$}));break}}function k(){g>0&&t({id:p,event:x,data:f}),p=void 0,f="",g=0,x=void 0}function T(v={}){if(v.consume&&s.length>0){let z=s.join("");H(z,0,z.length)}l=!0,p=void 0,f="",g=0,x=void 0,s.length=0,c=0,_=!1}return{feed:S,reset:T}}function ac(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function cc(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var ar=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:o,maxBufferSize:n}={}){let i;super({start(s){i=uc({onEvent:c=>{s.enqueue(c)},onError(c){typeof t=="function"&&t(c),(t==="terminate"||c.type==="max-buffer-size-exceeded")&&s.error(c)},onRetry:r,onComment:o,maxBufferSize:n})},transform(s){i.feed(s)}})}};var Pd={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},ke=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},cr=class{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Va(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Pd}async _authThenStart(){if(!this._authProvider)throw new Se("No auth provider");let t;try{t=await It(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Se;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(t.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=sr(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){let{resumptionToken:r}=t;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),r&&o.set("last-event-id",r);let n=await(this._fetch??fetch)(this._url,{method:"GET",headers:o,signal:this._abortController?.signal});if(!n.ok){if(await n.body?.cancel(),n.status===401&&this._authProvider)return await this._authThenStart();if(n.status===405)return;throw new ke(n.status,`Failed to open SSE stream: ${n.statusText}`)}this._handleSseStream(n.body,t,!0)}catch(o){throw this.onerror?.(o),o}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(o,t),n)}_scheduleReconnection(t,r=0){let o=this._reconnectionOptions.maxRetries;if(r>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let n=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,r+1)})},n)}_handleSseStream(t,r,o){if(!t)return;let{onresumptiontoken:n,replayMessageId:i}=r,s,c=!1,l=!1;(async()=>{try{let f=t.pipeThrough(new TextDecoderStream).pipeThrough(new ar({onRetry:_=>{this._serverRetryMs=_}})).getReader();for(;;){let{value:_,done:S}=await f.read();if(S)break;if(_.id&&(s=_.id,c=!0,n?.(_.id)),!!_.data&&(!_.event||_.event==="message"))try{let R=He.parse(JSON.parse(_.data));xa(R)&&(l=!0,i!==void 0&&(R.id=i)),this.onmessage?.(R)}catch(R){this.onerror?.(R)}}(o||c)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:i},0)}catch(f){if(this.onerror?.(new Error(`SSE stream disconnected: ${f}`)),(o||c)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:i},0)}catch(_){this.onerror?.(new Error(`Failed to reconnect: ${_ instanceof Error?_.message:String(_)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new Se("No auth provider");if(await It(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Se("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:o,onresumptiontoken:n}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:za(t)?t.id:void 0}).catch(x=>this.onerror?.(x));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,s),l=c.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!c.ok){let x=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ke(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:_,scope:S}=Zo(c);if(this._resourceMetadataUrl=_,this._scope=S,await It(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Se;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:_,scope:S,error:R}=Zo(c);if(R==="insufficient_scope"){let ee=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===ee)throw new ke(403,"Server returned 403 after trying upscoping");if(S&&(this._scope=S),_&&(this._resourceMetadataUrl=_),this._lastUpscopingHeader=ee??void 0,await It(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Se;return this.send(t)}}throw new ke(c.status,`Error POSTing to endpoint: ${x}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),$a(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(x=>this.onerror?.(x));return}let f=(Array.isArray(t)?t:[t]).filter(x=>"method"in x&&"id"in x&&x.id!==void 0).length>0,g=c.headers.get("content-type");if(f)if(g?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:n},!1);else if(g?.includes("application/json")){let x=await c.json(),_=Array.isArray(x)?x.map(S=>He.parse(S)):[He.parse(x)];for(let S of _)this.onmessage?.(S)}else throw await c.body?.cancel(),new ke(-1,`Unexpected content type: ${g}`);else await c.body?.cancel()}catch(o){throw this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,r);if(await o.body?.cancel(),!o.ok&&o.status!==405)throw new ke(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};function lc(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 Zd,writeFileSync as Id,readFileSync as Td,readdirSync as Od,statSync as pc,unlinkSync as Cd,chmodSync as dc}from"node:fs";import{join as ur}from"node:path";import{homedir as Ed}from"node:os";var Ad="0.1.
|
|
41
|
+
${z}`,g++;break;case"id":p=z.includes("\0")?void 0:z;break;case"retry":/^\d+$/.test(z)?o(parseInt(z,10)):r(new Tt(`Invalid \`retry\` value: "${z}"`,{type:"invalid-retry",value:z,line:$}));break;default:r(new Tt(`Unknown field "${v.length>20?`${v.slice(0,20)}\u2026`:v}"`,{type:"unknown-field",field:v,value:z,line:$}));break}}function k(){g>0&&t({id:p,event:x,data:f}),p=void 0,f="",g=0,x=void 0}function T(v={}){if(v.consume&&s.length>0){let z=s.join("");H(z,0,z.length)}l=!0,p=void 0,f="",g=0,x=void 0,s.length=0,c=0,_=!1}return{feed:S,reset:T}}function ac(e,t,r){return r===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function cc(e,t,r){return r===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var ar=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:o,maxBufferSize:n}={}){let i;super({start(s){i=uc({onEvent:c=>{s.enqueue(c)},onError(c){typeof t=="function"&&t(c),(t==="terminate"||c.type==="max-buffer-size-exceeded")&&s.error(c)},onRetry:r,onComment:o,maxBufferSize:n})},transform(s){i.feed(s)}})}};var Pd={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},ke=class extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},cr=class{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Va(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Pd}async _authThenStart(){if(!this._authProvider)throw new Se("No auth provider");let t;try{t=await It(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Se;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(t.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=sr(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){let{resumptionToken:r}=t;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),r&&o.set("last-event-id",r);let n=await(this._fetch??fetch)(this._url,{method:"GET",headers:o,signal:this._abortController?.signal});if(!n.ok){if(await n.body?.cancel(),n.status===401&&this._authProvider)return await this._authThenStart();if(n.status===405)return;throw new ke(n.status,`Failed to open SSE stream: ${n.statusText}`)}this._handleSseStream(n.body,t,!0)}catch(o){throw this.onerror?.(o),o}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(o,t),n)}_scheduleReconnection(t,r=0){let o=this._reconnectionOptions.maxRetries;if(r>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let n=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,r+1)})},n)}_handleSseStream(t,r,o){if(!t)return;let{onresumptiontoken:n,replayMessageId:i}=r,s,c=!1,l=!1;(async()=>{try{let f=t.pipeThrough(new TextDecoderStream).pipeThrough(new ar({onRetry:_=>{this._serverRetryMs=_}})).getReader();for(;;){let{value:_,done:S}=await f.read();if(S)break;if(_.id&&(s=_.id,c=!0,n?.(_.id)),!!_.data&&(!_.event||_.event==="message"))try{let R=He.parse(JSON.parse(_.data));xa(R)&&(l=!0,i!==void 0&&(R.id=i)),this.onmessage?.(R)}catch(R){this.onerror?.(R)}}(o||c)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:i},0)}catch(f){if(this.onerror?.(new Error(`SSE stream disconnected: ${f}`)),(o||c)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:i},0)}catch(_){this.onerror?.(new Error(`Failed to reconnect: ${_ instanceof Error?_.message:String(_)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new Se("No auth provider");if(await It(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Se("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:o,onresumptiontoken:n}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:za(t)?t.id:void 0}).catch(x=>this.onerror?.(x));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,s),l=c.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!c.ok){let x=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ke(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:_,scope:S}=Zo(c);if(this._resourceMetadataUrl=_,this._scope=S,await It(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Se;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:_,scope:S,error:R}=Zo(c);if(R==="insufficient_scope"){let ee=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===ee)throw new ke(403,"Server returned 403 after trying upscoping");if(S&&(this._scope=S),_&&(this._resourceMetadataUrl=_),this._lastUpscopingHeader=ee??void 0,await It(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Se;return this.send(t)}}throw new ke(c.status,`Error POSTing to endpoint: ${x}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),$a(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(x=>this.onerror?.(x));return}let f=(Array.isArray(t)?t:[t]).filter(x=>"method"in x&&"id"in x&&x.id!==void 0).length>0,g=c.headers.get("content-type");if(f)if(g?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:n},!1);else if(g?.includes("application/json")){let x=await c.json(),_=Array.isArray(x)?x.map(S=>He.parse(S)):[He.parse(x)];for(let S of _)this.onmessage?.(S)}else throw await c.body?.cancel(),new ke(-1,`Unexpected content type: ${g}`);else await c.body?.cancel()}catch(o){throw this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,r);if(await o.body?.cancel(),!o.ok&&o.status!==405)throw new ke(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};function lc(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 Zd,writeFileSync as Id,readFileSync as Td,readdirSync as Od,statSync as pc,unlinkSync as Cd,chmodSync as dc}from"node:fs";import{join as ur}from"node:path";import{homedir as Ed}from"node:os";var Ad="0.1.3",Ud=new Set(["choose_identity","create_identity","create_root_identity"]),mc=e=>new Promise(t=>setTimeout(t,e)),Nd=e=>typeof e?.method=="string"&&e.id!==void 0&&e.id!==null,jd=e=>e&&typeof e=="object"&&!("method"in e)&&e.id!==void 0&&e.id!==null,fc=e=>{let t=e.result;return!!e.error||!!(t&&t.isError)},hc=Number(process.env.OURS_RESTORE_TTL_MS)>0?Number(process.env.OURS_RESTORE_TTL_MS):7*24*60*60*1e3,gc=["1","true","yes","on"].includes((process.env.OURS_NO_AUTORESTORE??"").trim().toLowerCase());async function zc(e){let t=new URL(e.url),r=(...w)=>process.stderr.write(`[ours-proxy] ${w.join(" ")}
|
|
42
42
|
`),o=w=>Number.isInteger(w)&&w>1,n=Number(process.env.OURS_CLIENT_PID),i=o(n)?n:o(process.ppid)?process.ppid:process.pid,s=(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||`client:${i}`,c=null,l=null,p,f=null,g=new Map,x=null,_=gc?null:(process.env.CLAUDE_CODE_SESSION_ID??"").trim()||null,S=e.stateDir??process.env.OURS_STATE_DIR??ur(Ed(),".ours"),R=ur(S,"session-restore"),ee=_&&/^[A-Za-z0-9._-]{1,200}$/.test(_)?_:null,H=ee?ur(R,`${ee}.json`):null,A=!1,k=null;function T(w){if(H)try{Zd(R,{recursive:!0,mode:448}),Id(H,JSON.stringify({claudeSessionId:_,identity:w,boundAt:new Date().toISOString()}),{mode:384}),dc(R,448),dc(H,384)}catch(P){r("restore persist failed (non-fatal):",String(P))}}function v(){if(!H)return null;try{if(Date.now()-pc(H).mtimeMs>hc)return null;let w=JSON.parse(Td(H,"utf8"));return(typeof w.identity=="string"?w.identity.trim():"")||null}catch{return null}}function z(){try{let w=Date.now();for(let P of Od(R)){if(!P.endsWith(".json"))continue;let C=ur(R,P);try{w-pc(C).mtimeMs>hc&&(Cd(C),r("session-restore: pruned expired record",P))}catch{}}}catch{}}let $=null,D=!1,W=!1,se=!1,Le=[],mr="__ours_proxy_init__",rt=0,pe=new Set,De=new Set,Re=new ir;Re.onmessage=w=>{let P=[],C=!1;for(let he of _c(w)){let Y=he;if(Y.method==="notifications/initialized"&&(C=!0),Nd(Y)){if(Y.method==="initialize"&&(c=Y,l)){r("absorbed re-initialize locally \u2014 upstream session kept stable"),Re.send({jsonrpc:"2.0",id:Y.id,result:l}).catch(te=>r("local initialize reply failed:",String(te)));continue}if(Y.method==="tools/call"){let te=Y.params;te&&Ud.has(te.name??"")&&typeof te.arguments?.name=="string"&&g.set(Y.id,te.arguments.name)}}P.push(Y)}if(P.length){let he=Array.isArray(w)?P:P[0];No(he)}C&&Tc()},Re.onclose=()=>void fr(0),Re.onerror=w=>r("downstream error:",String(w));function Tc(){if(A||!f)return;A=!0;let w=`__ours_proxy_restore_${++rt}__`;pe.add(w),k=w,r("session-restore: self-recovering bound identity",`"${f}"`),No({jsonrpc:"2.0",id:w,method:"tools/call",params:{name:"choose_identity",arguments:{name:f}}})}function No(w){if(D&&$){let P=$;$.send(w).catch(C=>{r("upstream send failed:",String(C)),Le.push(w),jo(P,"send failed")})}else Le.push(w)}function jo(w,P){if(W||se||$!==null&&w!==$)return;r(`upstream dropped (${P}) \u2014 reconnecting`),D=!1;let C=$;$=null;try{C?.close?.()}catch{}Cc()}function Oc(w){w.onmessage=P=>{let C=[];for(let he of _c(P)){let Y=he;if(jd(Y)){let te=Y.id,hr=Y.result?.protocolVersion;if(hr&&(De.has(te)||Lo(te))){p=hr;try{$?.setProtocolVersion?.(hr)}catch{}if(l==null&&Lo(te)&&!pe.has(te)){let ve=Y.result??null;ve&&x&&(ve.instructions=`${ve.instructions?ve.instructions+`
|
|
43
43
|
|
|
44
44
|
`:""}${x}`),l=ve}De.delete(te)}if(pe.has(te)){pe.delete(te),te===k&&(k=null,fc(Y)&&(f=null,r("session-restore: re-bind refused (identity live elsewhere) \u2014 staying unbound")));continue}if(g.has(te)){let ve=g.get(te);g.delete(te),fc(Y)||(f=ve,r("bound identity tracked:",ve),T(ve))}}C.push(Y)}if(C.length){let he=Array.isArray(P)?C:C[0];Re.send(he).catch(Y=>r("downstream send failed:",String(Y)))}},w.onerror=P=>r("upstream error:",String(P)),w.onclose=()=>jo(w,"closed")}let Lo=w=>c!=null&&c.id===w;async function Do(){e.ensureDaemon&&await e.ensureDaemon().catch(P=>r("ensureDaemon:",String(P)));let w=new cr(t,{requestInit:{headers:{"x-ours-lease-token":s,"x-ours-client-pid":String(i)}}});if(Oc(w),await w.start(),p)try{w.setProtocolVersion?.(p)}catch{}$=w}async function Mo(w,P){P&&w.id!==void 0&&pe.add(w.id),await $.send(w)}async function Cc(){if(se||W)return;se=!0;let w=500;for(;;){if(W){se=!1;return}try{if(await Do(),c){let C=`${mr}${rt}`;De.add(C),await Mo({...c,id:C},!0),await $.send({jsonrpc:"2.0",method:"notifications/initialized"})}if(f){let C=`__ours_proxy_rebind_${++rt}__`;await Mo({jsonrpc:"2.0",id:C,method:"tools/call",params:{name:"choose_identity",arguments:{name:f}}},!0)}D=!0;let P=Le.splice(0);for(let C of P)await $.send(C).catch(he=>r("flush failed:",String(he)));r("upstream reconnected",f?`(re-bound "${f}")`:""),se=!1;return}catch(P){r("reconnect attempt failed:",String(P)),await mc(w),w=Math.min(Math.floor(w*1.5),1e4)}}}async function fr(w){if(!W){W=!0;try{await $?.close()}catch{}try{await Re.close()}catch{}process.exit(w)}}process.on("SIGINT",()=>void fr(0)),process.on("SIGTERM",()=>void fr(0));async function Ec(){let w=new URL(t.href);w.pathname="/state-dir";let P;try{P=await(await fetch(w,{signal:AbortSignal.timeout(3e3)})).json()}catch(C){r("compat handshake: could not read daemon /state-dir, proceeding:",String(C));return}x=lc({selfVersion:Ad,daemonVersion:typeof P?.version=="string"?P.version:null}),x&&r(x)}if((async()=>{e.ensureDaemon&&await e.ensureDaemon().catch(C=>r("ensureDaemon:",String(C))),await Ec();let w=500;for(;;)try{await Do();break}catch(C){r("initial upstream connect failed, retrying:",String(C)),await mc(w),w=Math.min(Math.floor(w*1.5),1e4)}D=!0;let P=Le.splice(0);for(let C of P)await $.send(C).catch(he=>r("flush failed:",String(he)));r(`upstream ready \u2014 stdio \u21C4 ${t.href}`)})(),_){z();let w=v();w&&(f=w,r("session-restore: found prior binding for this session \u2014 will self-recover",`"${w}"`))}else gc&&r("session-restore: disabled via OURS_NO_AUTORESTORE \u2014 pure in-memory binding");await Re.start(),r("proxy started (stdio transport up)")}function _c(e){return Array.isArray(e)?e:[e]}var Ct=_r(),le=Ct.stateDir,K=Ct.port,Qe=Ct.brokerUrl,Ne=je(le,"daemon.pid"),Ue=je(le,"daemon.log"),tt=Dd(import.meta.url),d=(...e)=>process.stdout.write(`${e.join(" ")}
|
|
45
45
|
`),G=(...e)=>process.stderr.write(`${e.join(" ")}
|
|
46
|
-
`),Ye="0.1.
|
|
46
|
+
`),Ye="0.1.3";async function Eo(){for(let e of["/version","/state-dir"])try{let t=new AbortController,r=setTimeout(()=>t.abort(),1500),o=await fetch(`http://127.0.0.1:${K}${e}`,{signal:t.signal});if(clearTimeout(r),o.ok){let n=await o.json();if(n&&typeof n.version=="string")return n}}catch{}return null}function vc(e){if(d(` cli: v${Ye}`),e?.version){let t=e.version!==Ye;d(` daemon: v${e.version}${e.compat?` (compat ${e.compat})`:""}`+(t?` \u26A0 differs from CLI \u2014 \`ours-mcp restart\` to load v${Ye}`:""))}else d(" daemon: version unknown (running build predates /version \u2014 restart to update)")}var kc=e=>new Promise(t=>setTimeout(t,e));function Fd(){try{let e=parseInt(Z.readFileSync(Ne,"utf8").trim(),10);return Number.isFinite(e)?e:null}catch{return null}}function Ao(e){try{return process.kill(e,0),!0}catch{return!1}}function Et(){let e=Fd();if(e&&Ao(e))return e;if(e)try{Z.rmSync(Ne,{force:!0})}catch{}return null}function et(e,t=1e3){return new Promise(r=>{let o=Ld({host:"127.0.0.1",port:e}),n=i=>{o.destroy(),r(i)};o.setTimeout(t),o.once("connect",()=>n(!0)),o.once("timeout",()=>n(!1)),o.once("error",()=>n(!1))})}async function Rc(e,t=3e4){let r=Date.now()+t;for(;Date.now()<r;){if(await et(e))return!0;await kc(400)}return!1}async function yc(){let e=Et();if(e){d(`ours-mcp is already running (pid ${e}, port ${K}).`);return}Z.mkdirSync(le,{recursive:!0});let t=Z.openSync(Ue,"a"),r=bc(process.execPath,[tt,"serve"],{detached:!0,stdio:["ignore",t,t],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(K),OURS_BROKER_URL:Qe,OURS_STATE_DIR:le}});r.unref(),r.pid||(G("failed to spawn the daemon."),process.exit(1)),Z.writeFileSync(Ne,String(r.pid)),d(`starting ours-mcp (pid ${r.pid})\u2026`),await Rc(K)?(d(`ours-mcp is up on http://localhost:${K}/mcp`),d(` broker: ${Qe}`),d(` state: ${le}`),d(` logs: ${Ue}`)):(G(`daemon started (pid ${r.pid}) but port ${K} did not open within 30s \u2014 check ${Ue}.`),process.exit(1))}async function qd(){if(!await et(K)){if(!Et()){Z.mkdirSync(le,{recursive:!0});let e=Z.openSync(Ue,"a"),t=bc(process.execPath,[tt,"serve"],{detached:!0,stdio:["ignore",e,e],env:{...process.env,OURS_TRANSPORT:"http",OURS_PORT:String(K),OURS_BROKER_URL:Qe,OURS_STATE_DIR:le}});if(t.unref(),t.pid)try{Z.writeFileSync(Ne,String(t.pid))}catch{}}await Rc(K)}}async function pr(){let e=Et();if(!e){d("ours-mcp is not running.");return}d(`stopping ours-mcp (pid ${e})\u2026`);try{process.kill(e,"SIGTERM")}catch(t){G(`failed to signal pid ${e}: ${String(t)}`)}for(let t=0;t<25&&Ao(e);t++)await kc(200);if(Ao(e)){G(`pid ${e} did not exit; sending SIGKILL.`);try{process.kill(e,"SIGKILL")}catch{}}try{Z.rmSync(Ne,{force:!0})}catch{}d("stopped.")}async function Bd(){let e=Et();if(!e){if(await et(K)){let o=await Eo();d("ours-mcp: running (no pidfile \u2014 likely a stale process or external launcher)"),d(` url: http://localhost:${K}/mcp (reachable)`),vc(o);return}d("ours-mcp: stopped"),d(` cli: v${Ye}`),process.exitCode=1;return}let t=await et(K),r=t?await Eo():null;d("ours-mcp: running"),d(` pid: ${e}`),d(` url: http://localhost:${K}/mcp ${t?"(reachable)":"(port not answering!)"}`),d(` broker: ${Qe}`),d(` state: ${le}`),d(` logs: ${Ue}`),vc(r)}async function Vd(){if(d(`ours-mcp v${Ye}`),await et(K)){let e=await Eo();e?.version?d(`running daemon: v${e.version}`+(e.version!==Ye?" (differs \u2014 restart to update)":"")):d("running daemon: version unknown (predates /version)")}else d("daemon: not running")}async function Wd(){let e=_r(),t=Nt();d(`ours-mcp setup \u2014 ${t}`),d("Enter a value, or press Enter to keep the current [bracketed] one."),d("");let r=lr({input:process.stdin,output:process.stdout}),o;try{let p=async(A,k)=>{let T=(await r.question(` ${A} [${k}]: `)).trim();return T===""?k:T},f=await p("broker URL",e.brokerUrl),g=await p("HTTP port",String(e.port)),x=await p("state dir",e.stateDir),_=await p("GC interval (ms)",String(e.gcIntervalMs)),S=await p("proxy auto-starts daemon (true/false)",String(e.autoStart)),R=parseInt(g,10);(!Number.isFinite(R)||R<=0)&&(G(`invalid port: ${g}`),process.exit(1));let ee=parseInt(_,10);(!Number.isFinite(ee)||ee<=0)&&(G(`invalid GC interval: ${_}`),process.exit(1));let H=S.toLowerCase()==="true"||S==="1";o={brokerUrl:f,port:R,stateDir:$c(x),gcIntervalMs:ee,autoStart:H}}finally{r.close()}Wo(o),d(""),d(`wrote ${t} (mode 0600):`),d(JSON.stringify(o,null,2));let n=["OURS_BROKER_URL","OURS_PORT","OURS_STATE_DIR","OURS_GC_INTERVAL_MS","OURS_AUTOSTART"].filter(p=>process.env[p]!==void 0);n.length&&(d(""),d(`note: these env vars are set and OVERRIDE the file at runtime: ${n.join(", ")}`));let i=Et();if(!i)return;let s=lr({input:process.stdin,output:process.stdout}),c=!1;try{let p=(await s.question(`
|
|
47
47
|
daemon is running (pid ${i}); restart now to apply? [y/N]: `)).trim().toLowerCase();c=p==="y"||p==="yes"}finally{s.close()}if(!c){d("not restarting \u2014 changes apply on the next `ours-mcp restart`.");return}await pr();let l=dr(process.execPath,[tt,"start"],{stdio:"inherit"});l.status!==0&&process.exit(l.status??1)}function Oo(e,t,r){return e.includes(r)?{value:!1,set:!0}:e.includes(t)?{value:!0,set:!0}:{value:void 0,set:!1}}function Co(e,t){let r=e.indexOf(t);return r>=0&&r+1<e.length?e[r+1]:void 0}async function Jd(e){let t=Co(e,"--name"),r=Oo(e,"--force-bind","--no-force-bind"),o=Oo(e,"--local-book","--no-local-book"),n=Oo(e,"--auto-accept-local","--no-auto-accept-local"),i=e.includes("--overwrite"),s=e.includes("--print"),c=Co(e,"--path")??Co(e,"--dir")??process.cwd(),l=t!==void 0||r.set||o.set||n.set||s,p;if(l?((!t||!t.trim())&&(G("define-local-identity-file: --name is required in non-interactive mode."),process.exit(1)),p={name:t.trim(),force:r.value??!1,exposeLocal:o.value??!0,localAutoAccept:n.value??!0}):p=await Gd(),s){d(JSON.stringify(jt(p),null,2));return}let f=zr(c);if(!i&&Z.existsSync(f)){l&&(G(`define-local-identity-file: ${f} already exists \u2014 pass --overwrite to replace it.`),process.exit(1));let x=lr({input:process.stdin,output:process.stdout}),_=!1;try{let S=(await x.question(`
|
|
48
48
|
${f} already exists \u2014 overwrite? [y/N]: `)).trim().toLowerCase();_=S==="y"||S==="yes"}finally{x.close()}if(!_){d("aborted \u2014 nothing written.");return}}let g=Jo(c,p,!0);d(""),d(`wrote ${g}:`),d(JSON.stringify(jt(p),null,2))}async function Gd(){d("ours-mcp define-local-identity-file \u2014 interactive"),d(`Answer the prompts; the result is written to ${je(process.cwd(),At)}.`),d("");let e=lr({input:process.stdin,output:process.stdout});try{let t=async(s,c)=>{let l=c?"Y/n":"y/N",p=(await e.question(` ${s} [${l}]: `)).trim().toLowerCase();return p===""?c:p==="y"||p==="yes"},r="";for(;!r;)r=(await e.question(" Identity name: ")).trim(),r||d(" (name is required)");let o=await t("Force-bind (pin pre-authorizes evicting another session)?",!1),n=await t("Add to the host-local contact book?",!0),i=await t("Auto-accept local invites/introductions?",!0);return{name:r,force:o,exposeLocal:n,localAutoAccept:i}}finally{e.close()}}async function Hd(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),1500),r=await fetch(`http://127.0.0.1:${K}/state-dir`,{signal:e.signal});if(clearTimeout(t),r.ok){let o=await r.json();if(typeof o.stateDir=="string"&&o.stateDir)return $c(o.stateDir)}}catch{}return le}async function Kd(e){let t=await Hd(),r=new Map,o=s=>{let c;try{c=Z.readdirSync(t,{withFileTypes:!0}).filter(l=>l.isDirectory()).map(l=>l.name)}catch{return}for(let l of c){if(e&&l!==e)continue;let p=je(t,l,"notifications.log"),f;try{f=Z.statSync(p).size}catch{continue}let g=r.get(p);if(g===void 0&&(g=s?f:0,r.set(p,g),s))continue;if(f<=g){f<g&&r.set(p,f);continue}let x;try{let _=Z.openSync(p,"r"),S=Buffer.alloc(f-g);Z.readSync(_,S,0,S.length,g),Z.closeSync(_),x=S.toString("utf8")}catch{continue}r.set(p,f);for(let _ of x.split(`
|
|
49
49
|
`)){if(!_.trim())continue;let S;try{S=JSON.parse(_)}catch{continue}S.event==="local_contact_request"?d(`[${l}] pending local introduction from ${S.from??"?"} \u2014 respond_to_introduction to approve/reject`):S.event==="pending_message"?d(`[${l}] ${S.from??"?"} queued a message awaiting introduction approval (${S.queued??"?"} queued)`):d(`[${l}] new message from ${S.from??"?"}`+(S.msg_id!==void 0?` (#${S.msg_id})`:"")+(S.date?` (${S.date})`:""))}}};G(`ours-mcp watch: watching ${e?`identity "${e}"`:"all identities"} under ${t} (Ctrl-C to stop)`),o(!0);let n=setInterval(()=>o(!1),1e3),i=()=>{clearInterval(n),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}var Ot="ours.service",Pc="solutions.adaptframework.ours";function Zc(){return je(Sc(),".config","systemd","user",Ot)}function Ic(){return je(Sc(),"Library","LaunchAgents",`${Pc}.plist`)}function Xe(e,t){return dr(e,t,{stdio:"inherit"}).status===0}function Yd(){let e=Zc();Z.mkdirSync(Uo(e),{recursive:!0});let t=`[Unit]
|
package/dist/index.js
CHANGED
|
@@ -51,8 +51,8 @@ data:
|
|
|
51
51
|
`;return o&&(s+=`id: ${o}
|
|
52
52
|
`),s+=`data: ${JSON.stringify(n)}
|
|
53
53
|
|
|
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(_=>co.parse(_)):a=[co.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(lo);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 _=this.validateSession(e);if(_)return _;let b=this.validateProtocolVersion(e);if(b)return b}if(!a.some(er)){for(let _ of a)this.onmessage?.(_,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),d=a.find(_=>lo(_)),f=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??ym;if(this._enableJsonResponse)return new Promise(_=>{this._streamMapping.set(l,{resolveJson:_,cleanup:()=>{this._streamMapping.delete(l)}});for(let b of a)er(b)&&this._requestToStreamMapping.set(b.id,l);for(let b of a)this.onmessage?.(b,{authInfo:r?.authInfo,requestInfo:s})});let m=new TextEncoder,p,h=new ReadableStream({start:_=>{p=_},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 _ of a)er(_)&&(this._streamMapping.set(l,{controller:p,encoder:m,cleanup:()=>{this._streamMapping.delete(l);try{p.close()}catch{}}}),this._requestToStreamMapping.set(_.id,l));await this.writePrimingEvent(p,m,l,f);for(let _ of a){let b,w;er(_)&&this._eventStore&&f>="2025-11-25"&&(b=()=>{this.closeSSEStream(_.id)},w=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(_,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:b,closeStandaloneSSEStream:w})}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&&!fn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${fn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${fn.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((qt(e)||mn(e))&&(n=e.id),n===void 0){if(qt(e)||mn(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(qt(e)||mn(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 Xi=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Qi(e),this._requestListener=Yd(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 Yd(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 tE,join as Me,dirname as rE,isAbsolute as nE,basename as oE}from"node:path";import{fileURLToPath as sE}from"node:url";import{randomBytes as J_,randomInt as G_,randomUUID as iE}from"node:crypto";import{createServer as aE}from"node:http";import{brotliCompressSync as cE,brotliDecompressSync as uE}from"node:zlib";import*as L from"node:fs";import{readFile as lE,mkdir as dE,writeFile as pE}from"node:fs/promises";import{adapt_wrapper as fE}from"@adapt-toolkit/sdk/executables";import{PacketWrapperConfigurator as mE}from"@adapt-toolkit/sdk/wrappers";import{object_to_adapt_value as K_}from"@adapt-toolkit/sdk/wrapper";import{AdaptObjectLifetime as dp}from"@adapt-toolkit/sdk/common";import*as Ft from"node:fs";import{homedir as T_}from"node:os";import{resolve as ea,join as P_,dirname as BP,basename as HP}from"node:path";var Qo={brokerUrl:"wss://ours.network/broker",port:3050,stateDir:ea(T_(),".ours"),gcIntervalMs:36e5,autoStart:!1};function JP(){return process.env.OURS_CONFIG??P_(T_(),".ours","config.json")}function GP(){let t;try{t=Ft.readFileSync(JP(),"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=ea(e.stateDir)),typeof e.gcIntervalMs=="number"&&Number.isFinite(e.gcIntervalMs)&&(r.gcIntervalMs=e.gcIntervalMs),typeof e.autoStart=="boolean"&&(r.autoStart=e.autoStart),r}function KP(t){let e=process.env[t];if(e!==void 0)return e==="1"||e.toLowerCase()==="true"}function z_(t){let e=process.env[t];if(e===void 0)return;let r=parseInt(e,10);return Number.isNaN(r)?void 0:r}function E_(){let t=GP();return{brokerUrl:process.env.OURS_BROKER_URL??t.brokerUrl??Qo.brokerUrl,port:z_("OURS_PORT")??t.port??Qo.port,stateDir:ea(process.env.OURS_STATE_DIR??t.stateDir??Qo.stateDir),gcIntervalMs:z_("OURS_GC_INTERVAL_MS")??t.gcIntervalMs??Qo.gcIntervalMs,autoStart:KP("OURS_AUTOSTART")??t.autoStart??Qo.autoStart}}var R_=".ours-identity";function Qd(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 WP(t){let e=ea(t);return HP(e)===R_?e:P_(e,R_)}function I_(t,e,r=!1){let n=Qd(e),o=WP(t);if(!r&&Ft.existsSync(o))throw new Error(`${o} already exists \u2014 pass overwrite to replace it`);return Ft.mkdirSync(BP(o),{recursive:!0}),Ft.writeFileSync(o,JSON.stringify(n,null,2)+`
|
|
55
|
-
`),o}import{basename as YP,extname as QP}from"node:path";var XP={".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 O_(t){return XP[QP(t).toLowerCase()]??"application/octet-stream"}function N_(t){let e=YP(t).replace(/[^A-Za-z0-9._-]/g,"_");return e.length?e.slice(0,200):"file"}function eE(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 Xo="0.1.
|
|
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(_=>co.parse(_)):a=[co.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(lo);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 _=this.validateSession(e);if(_)return _;let b=this.validateProtocolVersion(e);if(b)return b}if(!a.some(er)){for(let _ of a)this.onmessage?.(_,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),d=a.find(_=>lo(_)),f=d?d.params.protocolVersion:e.headers.get("mcp-protocol-version")??ym;if(this._enableJsonResponse)return new Promise(_=>{this._streamMapping.set(l,{resolveJson:_,cleanup:()=>{this._streamMapping.delete(l)}});for(let b of a)er(b)&&this._requestToStreamMapping.set(b.id,l);for(let b of a)this.onmessage?.(b,{authInfo:r?.authInfo,requestInfo:s})});let m=new TextEncoder,p,h=new ReadableStream({start:_=>{p=_},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 _ of a)er(_)&&(this._streamMapping.set(l,{controller:p,encoder:m,cleanup:()=>{this._streamMapping.delete(l);try{p.close()}catch{}}}),this._requestToStreamMapping.set(_.id,l));await this.writePrimingEvent(p,m,l,f);for(let _ of a){let b,w;er(_)&&this._eventStore&&f>="2025-11-25"&&(b=()=>{this.closeSSEStream(_.id)},w=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(_,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:b,closeStandaloneSSEStream:w})}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&&!fn.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${fn.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${fn.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((qt(e)||mn(e))&&(n=e.id),n===void 0){if(qt(e)||mn(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(qt(e)||mn(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 Xi=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Qi(e),this._requestListener=Yd(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 Yd(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 tE,join as Me,dirname as rE,isAbsolute as nE,basename as oE}from"node:path";import{fileURLToPath as sE}from"node:url";import{randomBytes as J_,randomInt as G_,randomUUID as iE}from"node:crypto";import{createServer as aE}from"node:http";import{brotliCompressSync as cE,brotliDecompressSync as uE}from"node:zlib";import*as L from"node:fs";import{readFile as lE,mkdir as dE,writeFile as pE}from"node:fs/promises";import{adapt_wrapper as fE}from"@adapt-toolkit/sdk/executables";import{PacketWrapperConfigurator as mE}from"@adapt-toolkit/sdk/wrappers";import{object_to_adapt_value as K_}from"@adapt-toolkit/sdk/wrapper";import{AdaptObjectLifetime as dp}from"@adapt-toolkit/sdk/common";import*as Ft from"node:fs";import{homedir as T_}from"node:os";import{resolve as ea,join as P_,dirname as BP,basename as HP}from"node:path";var Qo={brokerUrl:"wss://ours.network/broker_new",port:3050,stateDir:ea(T_(),".ours"),gcIntervalMs:36e5,autoStart:!1};function JP(){return process.env.OURS_CONFIG??P_(T_(),".ours","config.json")}function GP(){let t;try{t=Ft.readFileSync(JP(),"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=ea(e.stateDir)),typeof e.gcIntervalMs=="number"&&Number.isFinite(e.gcIntervalMs)&&(r.gcIntervalMs=e.gcIntervalMs),typeof e.autoStart=="boolean"&&(r.autoStart=e.autoStart),r}function KP(t){let e=process.env[t];if(e!==void 0)return e==="1"||e.toLowerCase()==="true"}function z_(t){let e=process.env[t];if(e===void 0)return;let r=parseInt(e,10);return Number.isNaN(r)?void 0:r}function E_(){let t=GP();return{brokerUrl:process.env.OURS_BROKER_URL??t.brokerUrl??Qo.brokerUrl,port:z_("OURS_PORT")??t.port??Qo.port,stateDir:ea(process.env.OURS_STATE_DIR??t.stateDir??Qo.stateDir),gcIntervalMs:z_("OURS_GC_INTERVAL_MS")??t.gcIntervalMs??Qo.gcIntervalMs,autoStart:KP("OURS_AUTOSTART")??t.autoStart??Qo.autoStart}}var R_=".ours-identity";function Qd(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 WP(t){let e=ea(t);return HP(e)===R_?e:P_(e,R_)}function I_(t,e,r=!1){let n=Qd(e),o=WP(t);if(!r&&Ft.existsSync(o))throw new Error(`${o} already exists \u2014 pass overwrite to replace it`);return Ft.mkdirSync(BP(o),{recursive:!0}),Ft.writeFileSync(o,JSON.stringify(n,null,2)+`
|
|
55
|
+
`),o}import{basename as YP,extname as QP}from"node:path";var XP={".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 O_(t){return XP[QP(t).toLowerCase()]??"application/octet-stream"}function N_(t){let e=YP(t).replace(/[^A-Za-z0-9._-]/g,"_");return e.length?e.slice(0,200):"file"}function eE(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 Xo="0.1.3",ca=E_(),rt=ca.stateDir,oa=ca.brokerUrl,hE=process.env.OURS_TRANSPORT??"http",Xd=ca.port,A_=ca.gcIntervalMs,I=(...t)=>process.stderr.write(`ours: ${t.join(" ")}
|
|
56
56
|
`),gE=/^[A-Za-z0-9 _.@-]{1,64}$/,sa="contact-book";function j_(t){return gE.test(t)?t==="."||t===".."||t.includes("/")||t.includes("\\")?"invalid name":t===sa?`"${sa}" 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 yE(){let t=rE(sE(import.meta.url)),e=process.env.OURS_UNIT_DIR,r=e?[tE(e)]:[Me(t,"mufl_code"),Me(t,"..","mufl_code")];for(let n of r){if(!L.existsSync(n))continue;let o=L.readdirSync(n).find(s=>s.endsWith(".muflo"));if(o){let s=o.slice(0,-6),i=new Uint8Array(L.readFileSync(Me(n,o)));return{dir:n,hash:s,contents:i}}}throw new Error(`no compiled .muflo packet found (looked in: ${r.join(", ")})`)}var es,ts,K=new Map,ft=null,sp=null,Re=new Map,ua=new Set,xt=new Map;function Z_(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function W_(t){for(let e of Re.values())if(e.token===t)return e}var M_=()=>Me(rt,"bindings.json");function ss(){try{L.mkdirSync(rt,{recursive:!0});let t=`${M_()}.tmp`;L.writeFileSync(t,JSON.stringify({pid:process.pid,bound:[...Re.keys()],holders:[...Re.values()].map(e=>({identity:e.identity,pid:e.pid}))})),L.renameSync(t,M_())}catch(t){I("failed to persist bindings snapshot:",String(t))}}var Y_=t=>Me(rt,t),pp=t=>Me(t,"identity.key"),Wr=t=>Me(t,"state_data.bin"),_E=t=>Me(t,"notifications.log"),q_=t=>Me(t,"unread.json"),vE=t=>Me(t.dir,"files");function bE(){return L.existsSync(rt)?L.readdirSync(rt,{withFileTypes:!0}).filter(t=>t.isDirectory()&&L.existsSync(pp(Me(rt,t.name)))).map(t=>t.name):[]}var ns=()=>Me(rt,sa),D_=()=>Me(ns(),"registrar.key"),ip=()=>Me(ns(),"book.json");function la(){try{let t=JSON.parse(L.readFileSync(ip(),"utf8"));return t&&typeof t.entries=="object"?t.entries:{}}catch{return{}}}function Q_(t){L.mkdirSync(ns(),{recursive:!0});let e=`${ip()}.tmp`;L.writeFileSync(e,JSON.stringify({v:1,entries:t},null,2),{mode:384}),L.renameSync(e,ip())}function Vn(t){return Qe(e=>Buffer.from(xe(t,"::actor::export_address_document",e).GetBinary()))}function X_(t){return Qe(e=>Buffer.from(xe(t,"::actor::export_signing_secret",e).Serialize()).toString("hex"))}async function ev(t){if(!ft)throw new Error("registrar is not available");let e=Vn(t),r=await X(async o=>{let s=await U(ft,"::actor::sign_book_entry",{name:t.name,ad:ft.pw.packet.NewBinaryFromBuffer(e).Attach(o)},o);return Buffer.from(s.Reduce("sig").GetBinary()).toString("base64url")}),n=la();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},Q_(n),I(`[${t.name}] published to the local contact book`)}function tv(t){let e=la();t in e&&(delete e[t],Q_(e),I(`[${t}] removed from the local contact book`))}async function rv(t){if(!sp)throw new Error("registrar is not available");await X(async e=>{await U(t,"::actor::pin_registrar",{registrar_ad:t.pw.packet.NewBinaryFromBuffer(sp).Attach(e)},e)})}var ia=()=>Me(rt,"root.json"),le=null;function wE(){try{let t=JSON.parse(L.readFileSync(ia(),"utf8"));return typeof t.name=="string"?t.name:null}catch{return null}}function $E(t){L.mkdirSync(rt,{recursive:!0});let e=`${ia()}.tmp`;L.writeFileSync(e,JSON.stringify({v:1,name:t})),L.renameSync(e,ia())}function nv(){L.rmSync(ia(),{force:!0})}function kt(t){return Qe(e=>{let r=xe(t,"::actor::describe_identity",e);return{bio:r.Reduce("bio").Visualize(),persona:r.Reduce("persona").Visualize(),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 ta(t,e){await X(async r=>{let n=Vn(e),o=await U(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 U(t,"::actor::export_root_profile",{},r),a=Buffer.from(i.Reduce("profile").GetBinary()),c=Vn(t);await U(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)},r)}),I(`[${e.name}] delegated as a role under root "${t.name}"`)}function xE(t,e){if(!le||!K.has(le))return null;let r=K.get(e)??[...K.values()].find(o=>o.cid===e);if(!r||r.name===t.name)return null;let n=o=>o.name===le||kt(o).roleId!=="";return n(t)&&n(r)?r:null}async function kE(t,e,r){let n=Vn(e);return await X(async o=>{await U(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 SE(t,e,r){if(!ft)throw new Error(`"${e}" is not a contact, and the local contact book is unavailable.`);let n=la(),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=Vn(t);return await X(async c=>{let u=await U(ft,"::actor::mint_introduction",{joiner_ad:ft.pw.packet.NewBinaryFromBuffer(a).Attach(c),target_ad:ft.pw.packet.NewBinaryFromBuffer(s).Attach(c)},c),l=Buffer.from(u.Reduce("intro").GetBinary());await U(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 is(t){return Qe(e=>{let r=xe(t,"::a2a_messaging::get_monitoring_status",e),n=xe(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 rs(t,e,r){await X(async n=>{await U(t,"::a2a_control::send_control",{contact:e,payload:JSON.stringify(r)},n)})}function ov(t){try{return Qe(e=>{let r=xe(t,"::a2a_capabilities::get_manifest",e).Reduce("capabilities");return r.IsNil()?[]:[...r.GetKeys()].map(n=>typeof n=="string"?n:n.Visualize())})}catch{return[]}}function zE(t){let e="",r="",n="",o="",s=[];try{Qe(i=>{let a=xe(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:is(t).proxyCid?"bound":"unbound"}}function RE(t){let e=[];for(let r of K.values()){if(r.name===t.name)continue;let n=kt(r);n.rootCid===t.cid&&e.push({name:r.name,cid:r.cid,role_id:n.roleId,bio:n.bio,monitoring:n.monitoringEnabled,capabilities:ov(r)})}return e}function sv(t){try{ts.remove_packet(t.cid)}catch(e){I(`remove_packet(${t.cid}) failed:`,String(e))}K.delete(t.name);try{tv(t.name)}catch(e){I(`failed to unpublish "${t.name}" from the contact book:`,String(e))}Re.has(t.name)&&(Re.delete(t.name),ss()),t.name===le&&(le=null,nv());try{L.rmSync(t.dir,{recursive:!0,force:!0})}catch(e){return`deleting ${t.dir} failed: ${String(e)}`}return null}var fp=!0,iv=fp?2:1,TE=6e5,ap=new Map,cp=(t,e)=>`${t}:${e}`;function av(t,e,r){e&&ap.set(cp(t,e),{response:r,at:Date.now()})}function PE(t,e){if(!e)return;let r=ap.get(cp(t,e));if(r){if(Date.now()-r.at>TE){ap.delete(cp(t,e));return}return r.response}}async function EE(t,e,r){let n=os(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 rs(t,e,o),av(e,i,o))}async function IE(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{I(`[${t.name}] dropping unparseable control payload from ${n}`);return}if(i.v===1){i.t==="get_manifest"?await rs(t,r,{v:1,t:"res",id:i.id??null,ok:!0,manifest:{...zE(t),protocol_version:iv}}):await rs(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=PE(r,a);if(c){await rs(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 X(async d=>{let f;try{f=await U(t,"::actor::process_control_envelope",{sender_id:e,sender_name:n,envelope:l,date:s},d)}catch(m){I(`[${t.name}] dispatch of "${l.cap}.${l.verb}" from ${n} failed:`,String(m));return}if(await EE(t,r,f),l.cap==="core.monitoring"&&l.verb==="bind")try{let m=os(f);m&&(m.ok===!0||m.$ok===!0)&&ZE(t,r)}catch{}})}async function OE(t){for(;;)if(await X(async r=>{let o=(await U(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 IE(t,c,c.Visualize(),a.Reduce("sender_name").Visualize(),a.Reduce("payload").Visualize(),a.Reduce("date"))}return!1}))return}function NE(){return String(G_(0,1e6)).padStart(6,"0")}var Yr=new Map;function da(t){return[...K.values()].find(e=>e.cid===t)}async function as(t,e){let r=e.Reduce("target").Visualize(),n=os(e.Reduce("response"));if(!n||typeof n!="object")return;await rs(t,r,n);let o=String(n.req_id??"");o&&av(r,o,n)}async function CE(t,e,r,n){try{if(K.has(e)){I(`[${t.name}] host_provision_child("${e}") rejected: name exists (settles via sweep timeout)`);return}let o=await lp(e);await X(async s=>{r&&await U(o,"::a2a_messaging::set_my_bio",{bio:r},s),await ta(t,o);let i=kt(o).roleId,a=xe(o,"::actor::export_address_document_native",s),c=await U(t,"::a2a_cluster::register_provisioned_child",{pending_handle:n,role_id:i,child_ad:a},s);await as(t,c)})}catch(o){I(`[${t.name}] host_provision_child("${e}") failed (settles via sweep timeout):`,String(o))}}async function AE(t,e,r){try{let n=da(e.Visualize());if(n){let o=sv(n);o&&I(`[${t.name}] host_destroy_child teardown warning:`,o)}Yr.delete(e.Visualize()),await X(async o=>{let s=await U(t,"::a2a_cluster::confirm_child_destroyed",{pending_handle:r,cid:e},o);await as(t,s)})}catch(n){I(`[${t.name}] host_destroy_child failed (settles via sweep timeout):`,String(n))}}async function jE(t,e,r){try{let n=da(e.Visualize());if(!n){I(`[${t.name}] host_mint_child_invite: unknown child ${e.Visualize()} (settles via sweep timeout)`);return}await X(async o=>{let s=await U(n,"::a2a_messaging::generate_invite",{},o),i=t.pw.packet.NewBinaryFromBuffer(Buffer.from(s.Reduce("invite").GetBinary())).Attach(o),a=await U(t,"::a2a_cluster::register_child_invite",{pending_handle:r,invite:i},o);await as(t,a)})}catch(n){I(`[${t.name}] host_mint_child_invite failed (settles via sweep timeout):`,String(n))}}async function up(t,e,r,n){await X(async o=>{if(e){n&&await U(t,"::a2a_messaging::host_register_monitoring_cp",{cp_ad:n},o);let s=NE();await U(t,"::a2a_messaging::set_proxy_pending",{code:s,proxy:r},o),await U(t,"::a2a_messaging::verify_proxy_code",{code:s,sender:r},o),Yr.set(t.cid,r??"")}else await U(t,"::a2a_messaging::host_clear_child_monitoring",{},o),Yr.delete(t.cid)})}async function L_(t,e,r,n,o,s){try{let i=da(e.Visualize());if(!i){I(`[${t.name}] host_set_child_monitoring: unknown child ${e.Visualize()} (settles via sweep timeout)`);return}r?await up(i,!0,o?.Visualize(),s):await up(i,!1),await X(async a=>{let c=await U(t,"::a2a_cluster::confirm_child_monitoring",{pending_handle:n,cid:e,enabled:r},a);await as(t,c)})}catch(i){I(`[${t.name}] host_set_child_monitoring failed (settles via sweep timeout):`,String(i))}}async function ZE(t,e){for(let[r,n]of[...Yr.entries()]){if(n===e)continue;let o=da(r);if(!o){Yr.delete(r);continue}await up(o,!1).catch(s=>I(`[${t.name}] CP-rebind clear of child ${r} failed:`,String(s)))}}function ME(t,e){let r=[];for(let n of K.values()){if(n.name===t.name)continue;let o=kt(n);if(o.rootCid!==t.cid)continue;let s=xe(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:ov(n),child_ad:s})}return r}var ep=new Set;async function cv(t){if(!ep.has(t.name)){ep.add(t.name);try{await X(async e=>{await U(t,"::a2a_cluster::reconcile",{pending_handle:"",children:ME(t,e)},e);let n=(await U(t,"::a2a_cluster::sweep_and_settle",{},e)).Reduce("settled"),o=n.GetKeys();for(let s=0;s<o.length;s++)await as(t,n.Reduce(s))})}catch(e){I(`[${t.name}] cluster sweep failed:`,String(e))}finally{ep.delete(t.name)}}}var qE=6e4;function DE(){setInterval(()=>{if(fp)for(let t of K.values())kt(t).roleId===""&&cv(t)},qE).unref()}function LE(){for(let t of K.values())if(kt(t).roleId!=="")try{let e=is(t).proxyCid;e&&Yr.set(t.cid,e)}catch(e){Yr.set(t.cid,""),I(`[${t.name}] monitoredChildren rebuild read failed (added clear-on-repoint):`,String(e))}}var tp=new Set;async function mp(t){if(!tp.has(t.name)){tp.add(t.name);try{await OE(t)}catch(e){I(`[${t.name}] control dispatch failed:`,String(e))}finally{tp.delete(t.name)}if(K.has(t.name)&&is(t).controlQueued>0)return mp(t)}}async function VE(){L.mkdirSync(ns(),{recursive:!0});let t;try{t=L.readFileSync(D_(),"utf8").trim()}catch{}let e=J_(24).toString("hex");ft=await hp(sa,e,ns(),!1,t),t||L.writeFileSync(D_(),X_(ft),{mode:384}),sp=Vn(ft),I(`contact-book registrar ready (${ft.cid})`)}function UE(t){try{return L.existsSync(Wr(t))&&L.statSync(Wr(t)).size>0}catch{return!1}}function aa(t){try{let e=Qe(n=>Buffer.from(xe(t,"::actor::export_state",n).Serialize()));L.mkdirSync(t.dir,{recursive:!0});let r=`${Wr(t.dir)}.tmp`;L.writeFileSync(r,e),L.renameSync(r,Wr(t.dir))}catch(e){I(`[${t.name}] failed to save state:`,String(e))}}function FE(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 BE(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 uv(t,e){try{let r=await X(async n=>{let o=await U(t,"::a2a_messaging::flush_deferred",{contact:e},n);return Number(o.Reduce("flushed").Visualize())});r>0&&I(`[${t.name}] flushed ${r} deferred message(s) to ${e.slice(0,12)}\u2026`)}catch(r){I(`[${t.name}] deferred flush to ${e.slice(0,12)}\u2026 failed:`,String(r))}}async function lv(t){try{let e=await X(async n=>{let o=await U(t,"::a2a_messaging::restore_degraded_contacts",{},n);return Number(o.Reduce("requested").Visualize())});e>0&&I(`[${t.name}] contact restore requested for ${e} degraded contact(s)`);let r=Qe(n=>BE(xe(t,"::a2a_messaging::list_deferred_queues",n)));for(let n of r)n.degraded||await uv(t,n.cid)}catch(e){I(`[${t.name}] contact-restore sweep failed:`,String(e))}}function pr(t,e){try{L.mkdirSync(t.dir,{recursive:!0}),L.appendFileSync(_E(t.dir),JSON.stringify(e)+`
|
|
57
57
|
`)}catch(r){I(`[${t.name}] failed to append notifications.log:`,String(r))}}function Kr(t){try{let{unread:e,unreadFiles:r}=Qe(s=>{let a=na(xe(t,"::actor::list_incoming_messages",s)).filter(l=>l.status==="unread"),c=xe(t,"::actor::list_incoming_files",s),u=[];if(!c.IsNil())for(let l=0;;l++){let d=c.Reduce(l);if(d.IsNil())break;d.Reduce("status").Visualize()==="unread"&&u.push({file_id:d.Reduce("file_id").Visualize(),from:d.Reduce("sender_name").Visualize(),filename:d.Reduce("filename").Visualize(),mime:d.Reduce("mime").Visualize(),wire_id:d.Reduce("wire_id").Visualize()})}return{unread:a,unreadFiles:u}}),n={count:e.length,recent:e.slice(-10).map(s=>({from:s.sender_name,msg_id:s.msg_id,date:s.date})),files:r.length,unread_files:r.slice(-10)};L.mkdirSync(t.dir,{recursive:!0});let o=`${q_(t.dir)}.tmp`;L.writeFileSync(o,JSON.stringify(n)),L.renameSync(o,q_(t.dir))}catch(e){I(`[${t.name}] failed to refresh unread snapshot:`,String(e))}}var ra=new Map,dv=t=>`ours://inbox/${encodeURIComponent(t)}`;function dr(t,e){I(`[${t}] notify:`,e);let r=Re.get(t)?.sid;if(!r)return;let n=ra.get(r);if(n){try{n.sendLoggingMessage({level:"info",logger:"ours",data:e})}catch(o){I("sendLoggingMessage failed:",String(o))}try{n.server.sendResourceUpdated({uri:dv(t)})}catch{}}}function Qe(t){let e=new dp;try{return t(e)}finally{e.Finalize()}}async function X(t){let e=new dp;try{return await t(e)}finally{e.Finalize()}}function xe(t,e,r){let n=K_({name:e,targ:void 0}),o=t.pw.packet.ExecuteTransaction(n);return n.Destroy(),r?o.Attach(r):o}async function HE(t,e){let r=t.lock,n;t.lock=new Promise(o=>n=o),await r;try{return await e()}finally{n()}}function JE(t,e,r=25e3){return new Promise((n,o)=>{let s=setTimeout(()=>{let i=t.pending.findIndex(a=>a.timer===s);i>=0&&t.pending.splice(i,1),o(new Error("timed out waiting for the transaction result"))},r);t.pending.push({resolve:n,reject:o,timer:s}),t.pw.add_client_message(e)})}function U(t,e,r,n,o){let s=K_({name:e,targ:r});return HE(t,()=>JE(t,s,o)).then(i=>(s.Destroy(),n?i.Attach(n):i),i=>{try{s.Destroy()}catch{}throw i})}function GE(t){t.pw.on_return_data=e=>{let r=new dp;e.Attach(r);try{let n=e.Reduce("kind").Visualize();if(n==="save_state"){aa(t);return}if(n==="notify_agent"){let s=e.Reduce("payload"),i=s.Reduce("event").Visualize();if(i==="message_received"){let a=s.Reduce("sender_name").Visualize(),c=s.Reduce("msg_id").Visualize(),u=s.Reduce("date").Visualize();pr(t,{event:"message_received",from:a,msg_id:c,date:u}),Kr(t),process.nextTick(()=>dr(t.name,`[${t.name}] new message from ${a} (#${c})`))}else if(i==="file_received"){let a=s.Reduce("sender_name").Visualize(),c=s.Reduce("file_id").Visualize(),u=s.Reduce("filename").Visualize(),l=s.Reduce("mime").Visualize(),d=s.Reduce("bytes").Visualize(),f=s.Reduce("date").Visualize();pr(t,{event:"file_received",from:a,file_id:c,filename:u,mime:l,bytes:d,date:f}),Kr(t),process.nextTick(()=>dr(t.name,`[${t.name}] new file ${u} (${d} B) from ${a} (#${c})`))}else if(i==="contact_accepted"){let a=s.Reduce("name").Visualize(),c=s.Reduce("container_id").Visualize();process.nextTick(()=>dr(t.name,`[${t.name}] contact "${a}" (${c}) accepted your invite.`))}else if(i==="local_contact_added"){let a=s.Reduce("name").Visualize(),c=s.Reduce("container_id").Visualize();process.nextTick(()=>dr(t.name,`[${t.name}] local contact "${a}" (${c}) connected via the contact book.`))}else if(i==="sibling_contact_added"){let a=s.Reduce("name").Visualize(),c=s.Reduce("container_id").Visualize();pr(t,{event:"sibling_contact_added",from:a}),process.nextTick(()=>dr(t.name,`[${t.name}] sibling "${a}" (${c}) connected (intra-root auto-accept).`))}else if(i==="local_contact_request"){let a=s.Reduce("name").Visualize(),c=s.Reduce("container_id").Visualize();pr(t,{event:"local_contact_request",from:a}),process.nextTick(()=>dr(t.name,`[${t.name}] pending local introduction from "${a}" (${c}) \u2014 approve or reject with respond_to_introduction.`))}else if(i==="pending_message"){let a=s.Reduce("sender_name").Visualize(),c=s.Reduce("queued").Visualize();pr(t,{event:"pending_message",from:a,queued:c}),process.nextTick(()=>dr(t.name,`[${t.name}] "${a}" queued a message awaiting introduction approval (${c} queued).`))}else if(i==="contact_restored"){let a=s.Reduce("name").Visualize(),c=s.Reduce("container_id").Visualize();pr(t,{event:"contact_restored",from:a}),I(`[${t.name}] contact "${a}" restored (re-keyed)`),process.nextTick(()=>void uv(t,String(c)))}else if(i==="control_request"){let a=s.Reduce("sender_name").Visualize();I(`[${t.name}] control request queued by ${a}`),process.nextTick(()=>void mp(t))}else if(i==="host_provision_child"){let a=s.Reduce("name").Visualize(),c=s.Reduce("bio").Visualize(),u=s.Reduce("pending_handle").Visualize();process.nextTick(()=>void CE(t,a,c,u))}else if(i==="host_destroy_child"){let a=s.Reduce("cid").Detach(),c=s.Reduce("pending_handle").Visualize();process.nextTick(()=>void AE(t,a,c).finally(()=>a.Destroy()))}else if(i==="host_mint_child_invite"){let a=s.Reduce("cid").Detach(),c=s.Reduce("pending_handle").Visualize();process.nextTick(()=>void jE(t,a,c).finally(()=>a.Destroy()))}else if(i==="host_set_child_monitoring"){let a=s.Reduce("cid").Detach(),c=s.Reduce("enabled").GetBoolean(),u=s.Reduce("pending_handle").Visualize();if(c){let l=s.Reduce("cp_cid").Detach(),d=s.Reduce("cp_ad").Detach();process.nextTick(()=>void L_(t,a,!0,u,l,d).finally(()=>{a.Destroy(),l.Destroy(),d.Destroy()}))}else process.nextTick(()=>void L_(t,a,!1,u).finally(()=>a.Destroy()))}return}let o=t.pending.shift();if(!o)return;clearTimeout(o.timer),o.resolve(e.Reduce("payload").Detach())}finally{r.Finalize()}},t.pw.on_transaction_failure=e=>{let r=t.pending.shift();r?(clearTimeout(r.timer),r.reject(new Error(e))):(I(`[${t.name}] inbound transaction rejected:`,e),pr(t,{event:"inbound_error",message:e}),process.nextTick(()=>dr(t.name,`[${t.name}] inbound transaction rejected: ${e}`)))}}function hp(t,e,r,n=!0,o){let s=new mE,i=["--unit_hash",es.hash,"--seed_phrase",e,"--unit_dir_path",es.dir];return o&&i.push("--init_trn_argument",JSON.stringify(o)),s.process_arguments(i),new Promise((a,c)=>{let u=setTimeout(()=>c(new Error(`packet creation for "${t}" timed out`)),3e4);ts.packet_manager.create_packet(s,l=>{clearTimeout(u);let d={name:t,cid:Qe(f=>l.packet.GetContainerID().Attach(f).Visualize()),pw:l,dir:r,pending:[],lock:Promise.resolve()};GE(d),n&&K.set(t,d),I(`[${t}] packet created \u2014 container id ${d.cid}`),a(d)},es.contents)})}async function lp(t,e={exposeLocal:!0,localAutoAccept:!0}){let r=Y_(t);L.mkdirSync(r,{recursive:!0});let n=J_(24).toString("hex"),o=await hp(t,n,r);return L.writeFileSync(pp(r),X_(o),{mode:384}),await X(async s=>{await U(o,"::a2a_messaging::set_my_name",{name:t},s)}),await rv(o),e.localAutoAccept||await X(async s=>{await U(o,"::actor::set_local_policy",{auto_accept:!1},s)}),e.exposeLocal&&await ev(o),aa(o),o}async function KE(t){let e=Y_(t),r=L.readFileSync(pp(e),"utf8").trim(),n=await hp(t,"",e,!0,r);if(UE(e))try{let o=L.readFileSync(Wr(e));await X(async s=>{let i=n.pw.packet.ParseValue(new Uint8Array(o)).Attach(s);await U(n,"::actor::import_state",i,s)})}catch(o){I(`[${t}] FAILED TO IMPORT SAVED STATE \u2014 continuing with the reseeded identity; surviving contacts (if the blob was partially migrated) self-heal via contact restore:`,String(o)),pr(n,{event:"state_import_failed",error:String(o).slice(0,300)});try{L.renameSync(Wr(e),`${Wr(e)}.failed-${Date.now()}`),I(`[${t}] unreadable state blob preserved as state_data.bin.failed-*`)}catch{}}return await lv(n),Kr(n),n}async function V_(){es=yE();let t=["--broker_address",oa,"--test_mode","--logger_config","--level","INFO","--stdout","stderr","--logger_config_end"];I(`booting wrapper (unit ${es.hash.slice(0,12)}\u2026, broker ${oa})`),ts=await fE.start(t),ts.on_packet_created_cb=n=>I(`wrapper: packet ready ${n.slice(0,12)}\u2026`),ts.start();try{await VE()}catch(n){I("failed to start the contact-book registrar (local contact book disabled):",String(n))}let e=bE();if(e.length===0)I("no persisted identities \u2014 start with create_identity");else{I(`restoring ${e.length} identit${e.length===1?"y":"ies"}: ${e.join(", ")}`);for(let n of e)try{let o=await KE(n);ft&&await rv(o)}catch(o){I(`failed to restore "${n}":`,String(o))}}LE(),DE(),le=wE(),le&&!K.has(le)&&(I(`root marker names a missing identity "${le}" \u2014 clearing it`),le=null,nv()),le&&I(`root identity: ${le}`);let r=le?K.get(le):void 0;if(r)try{is(r).controlQueued>0&&mp(r)}catch(n){I("boot-time monitoring/control drain failed:",String(n))}ss()}function U_(t){let e=xt.get(t)?.token;if(!e)return{error:"No identity bound to this session. Call choose_identity (or create_identity) first."};if(ua.has(e))return{error:"Your identity binding was reassigned to another session. Call choose_identity again to continue."};let r=W_(e);if(!r)return{error:"No identity bound to this session. Call choose_identity (or create_identity) first."};let n=K.get(r.identity);if(!n)return Re.delete(r.identity),ss(),{error:`The bound identity "${r.identity}" no longer exists. Choose another with choose_identity.`};r.sid=t;let o=xt.get(t)?.pid;return o&&(r.pid=o),{id:n}}function rp(t,e){let r=xt.get(t),n=r?.token;if(!n)return;for(let[s,i]of[...Re])i.token===n&&s!==e&&Re.delete(s);let o=Re.get(e)?.epoch??0;Re.set(e,{identity:e,token:n,pid:r?.pid??0,sid:t,epoch:o+1,boundAt:Date.now()}),ua.delete(n),ss()}function WE(t){let e=[];if(t.IsNil())return e;for(let r of t.GetKeys()){let n=t.Reduce(r);n.IsNil()||e.push({name:n.Reduce("name").Visualize(),container_id:n.Reduce("container_id").Visualize()})}return e}function na(t){let e=[];if(t.IsNil())return e;for(let r=0;;r++){let n=t.Reduce(r);if(n.IsNil())break;let o=n.Reduce("reply_to"),s=null;if(!o.IsNil()){s={wire_id:o.Reduce("wire_id").Visualize()};let i=o.Reduce("sentence");i.IsNil()||(s.sentence=parseInt(i.Visualize(),10))}e.push({msg_id:parseInt(n.Reduce("msg_id").Visualize(),10),sender_id:n.Reduce("sender_id").Visualize(),sender_name:n.Reduce("sender_name").Visualize(),text:n.Reduce("text").Visualize(),date:n.Reduce("date").Visualize(),status:n.Reduce("status").Visualize(),wire_id:n.Reduce("wire_id").Visualize(),reply_to:s})}return e}function YE(t){if(t.IsNil())return"No files received.";let e=[];for(let r=0;;r++){let n=t.Reduce(r);if(n.IsNil())break;let o=n.Reduce("filename").Visualize(),s=n.Reduce("mime").Visualize(),i=n.Reduce("sender_name").Visualize(),a=n.Reduce("status").Visualize(),c=n.Reduce("wire_id").Visualize();e.push(` \u2022 ${o} (${s||"application/octet-stream"}) from ${i} [${a}] {${c}}`)}return e.length===0?"No files received.":`${e.length} file(s):
|
|
58
58
|
${e.join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ours.network/mcp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
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",
|