@reddb-io/red-skills 2.60.2 → 2.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.bundle.min.mjs +46 -46
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +583 -529
- package/dist/memory.bundle.min.mjs +562 -562
- package/dist/rsp.bundle.min.mjs +109 -104
- package/package.json +1 -1
package/dist/rsp.bundle.min.mjs
CHANGED
|
@@ -1,76 +1,83 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
3
|
+
var ol=Object.defineProperty;var S=(e,t)=>()=>(e&&(t=e(e=0)),t);var B=(e,t)=>{for(var n in t)ol(e,n,{get:t[n],enumerable:!0})};async function $i(e,t){return al?ll(e,t):cl?fl(e,t):ul(e,t)}async function ul(e,t){let{spawn:n}=await import("node:child_process"),r=n(e,t,{stdio:["pipe","pipe","inherit"]});return{runtime:"node",stdin:{write(s){return new Promise((i,o)=>{r.stdin.write(s,a=>a?o(a):i())})},end(){r.stdin.end()}},stdout:r.stdout,kill(){r.kill("SIGTERM")},wait(){return new Promise(s=>{r.on("exit",i=>s(i??0))})}}}function ll(e,t){let n=globalThis.Bun.spawn({cmd:[e,...t],stdin:"pipe",stdout:"pipe",stderr:"inherit"}),r=n.stdin.getWriter?n.stdin.getWriter():null;return{runtime:"bun",stdin:{async write(s){r?await r.write(s):(n.stdin.write(s),await n.stdin.flush())},end(){r?r.close():n.stdin.end()}},stdout:dl(n.stdout),kill(){n.kill()},wait(){return n.exited}}}async function*dl(e){let t=e.getReader();try{for(;;){let{value:n,done:r}=await t.read();if(r)return;yield n}}finally{t.releaseLock()}}async function fl(e,t){let r=new globalThis.Deno.Command(e,{args:t,stdin:"piped",stdout:"piped",stderr:"inherit"}).spawn(),s=r.stdin.getWriter();return{runtime:"deno",stdin:{async write(i){await s.write(i)},end(){try{s.close()}catch{}}},stdout:ml(r.stdout),kill(){try{r.kill("SIGTERM")}catch{}},async wait(){return(await r.status).code??0}}}async function*ml(e){let t=e.getReader();try{for(;;){let{value:n,done:r}=await t.read();if(r)return;yield n}}finally{t.releaseLock()}}var al,cl,Ci=S(()=>{al=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",cl=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function"});import{existsSync as pl}from"node:fs";import{join as gl}from"node:path";function Ni(e){if(!e||typeof e!="object")throw new TypeError("resolveBin: options object required");let{name:t,packageRoot:n,envVar:r}=e;if(typeof t!="string"||t==="")throw new TypeError("resolveBin: `name` must be a non-empty string");if(typeof n!="string"||n==="")throw new TypeError("resolveBin: `packageRoot` must be a non-empty string");if(typeof r!="string"||r==="")throw new TypeError("resolveBin: `envVar` must be a non-empty string");let s=process.env?.[r];if(typeof s=="string"&&s!=="")return s;let i=gl(n,"bin",t);if(pl(i))return i;throw new Error(`reddb: binary "${t}" not found.
|
|
4
4
|
expected at: ${i}
|
|
5
5
|
override: set ${r}=/path/to/${t}
|
|
6
6
|
fix: re-run \`pnpm install\` (the postinstall script downloads it),
|
|
7
|
-
or check the postinstall log for a download error.`)}var
|
|
8
|
-
`)).catch(a=>{this.pending.delete(r),o(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let n of this.child.stdout){let r=new Uint8Array(t.length+n.length);r.set(t,0),r.set(n,t.length),t=r;let s=0;for(let i=0;i<t.length;i++)if(t[i]===10){let o=t.subarray(s,i);this.#n(
|
|
7
|
+
or check the postinstall log for a download error.`)}var Ai=S(()=>{});import{fileURLToPath as hl}from"node:url";import{dirname as yl,resolve as wl,join as vw}from"node:path";function Rl(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function Bi(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:Ni({name:Rl(),packageRoot:_l,envVar:"REDDB_BIN"})}var bl,_l,Li=S(()=>{Ai();bl=yl(hl(import.meta.url)),_l=wl(bl,"..")});var Sl,kl,R,kn,Pe=S(()=>{Sl=new TextEncoder,kl=new TextDecoder("utf-8"),R=class extends Error{constructor(t,n,r){super(n),this.name="RedDBError",this.code=t,this.data=r??null}},kn=class{constructor(t){this.child=t,this.nextId=1,this.pending=new Map,this.closed=!1,this.closeReason=null,this.readerPromise=this.#t()}call(t,n={}){if(this.closed)return Promise.reject(new R("CLIENT_CLOSED",`client is closed: ${this.closeReason??"unknown"}`));let r=this.nextId++,s=JSON.stringify({jsonrpc:"2.0",id:r,method:t,params:n});return new Promise((i,o)=>{this.pending.set(r,{resolve:i,reject:o}),this.child.stdin.write(Sl.encode(s+`
|
|
8
|
+
`)).catch(a=>{this.pending.delete(r),o(a)})})}async close(){if(!this.closed){try{await this.call("close",{})}catch{}this.#e("close requested");try{this.child.stdin.end()}catch{}await this.child.wait()}}async#t(){let t=new Uint8Array(0);try{for await(let n of this.child.stdout){let r=new Uint8Array(t.length+n.length);r.set(t,0),r.set(n,t.length),t=r;let s=0;for(let i=0;i<t.length;i++)if(t[i]===10){let o=t.subarray(s,i);this.#n(kl.decode(o)),s=i+1}s>0&&(t=t.subarray(s))}}catch(n){this.#e(`stdout reader error: ${n.message}`);return}this.#e("server stdout closed")}#n(t){if(!t.trim())return;let n;try{n=JSON.parse(t)}catch(i){this.#e(`malformed server response: ${i.message}`);return}let r=n.id;if(r==null)return;let s=this.pending.get(r);s&&(this.pending.delete(r),n.error?s.reject(new R(n.error.code??"UNKNOWN",n.error.message??"unknown error",n.error.data)):s.resolve(n.result))}#e(t){if(this.closed)return;this.closed=!0,this.closeReason=t;let n=new R("CLIENT_CLOSED",t);for(let{reject:r}of this.pending.values())r(n);this.pending.clear()}}});function Pr(e){if(typeof e!="string"||e.length===0)throw new TypeError("connect() requires a URI string (e.g. 'red://localhost:5050' or 'red:///data.rdb')");return e.startsWith("red://")||e==="red:"||e==="red:/"?El(e):xl(e)}function El(e){let t=e;e==="red:"||e==="red:/"||e==="red://"?t="red://embedded.local":e.startsWith("red:///")?t=`red://embedded.local${e.slice(6)}`:(e==="red://memory"||e==="red://memory/"||e==="red://:memory"||e==="red://:memory:")&&(t="red://embedded.local");let n;try{n=new URL(t)}catch(l){throw new R("UNPARSEABLE_URI",`failed to parse '${e}': ${l.message}`)}let r=n.searchParams,s=(r.get("proto")||"").toLowerCase(),i=n.pathname&&n.pathname!=="/"?n.pathname:"";if(n.hostname==="embedded.local")return i?{kind:"embedded",path:i,params:r,originalUri:e}:{kind:"embedded",params:r,originalUri:e};let o=Tl(s),a=n.port?Number(n.port):vr(o),c=n.username?decodeURIComponent(n.username):void 0,u=n.password?decodeURIComponent(n.password):void 0;return{kind:o,host:n.hostname,port:a,path:i||void 0,username:c,password:u,token:r.get("token")??void 0,apiKey:r.get("apiKey")??r.get("api_key")??void 0,loginUrl:r.get("loginUrl")??r.get("login_url")??void 0,params:r,originalUri:e}}function xl(e){if(e==="memory://"||e==="memory:")return{kind:"embedded",originalUri:e};if(e.startsWith("file://")){let t=e.slice(7);if(!t)throw new TypeError(`invalid file:// URI: missing path in '${e}'`);return{kind:"embedded",path:t,originalUri:e}}if(e.startsWith("grpc://")||e.startsWith("grpcs://")||e.startsWith("reds://")){let t=e.split("://",1)[0],n;try{n=new URL("https://"+e.slice(`${t}://`.length))}catch(i){throw new R("UNPARSEABLE_URI",`failed to parse '${e}': ${i.message}`)}if(!n.hostname)throw new TypeError(`invalid ${t}:// URI: missing host in '${e}'`);let r=t==="reds"?"reds":t==="grpcs"?"grpcs":"grpc",s=n.searchParams;return{kind:r,host:n.hostname,port:n.port?Number(n.port):vr(r),username:n.username?decodeURIComponent(n.username):void 0,password:n.password?decodeURIComponent(n.password):void 0,token:s.get("token")??void 0,apiKey:s.get("apiKey")??s.get("api_key")??void 0,loginUrl:s.get("loginUrl")??s.get("login_url")??void 0,params:s,originalUri:e}}if(e.startsWith("http://")||e.startsWith("https://")){let t;try{t=new URL(e)}catch(n){throw new R("UNPARSEABLE_URI",`failed to parse '${e}': ${n.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):vr(t.protocol==="https:"?"https":"http"),path:t.pathname!=="/"?t.pathname:void 0,username:t.username?decodeURIComponent(t.username):void 0,password:t.password?decodeURIComponent(t.password):void 0,token:t.searchParams.get("token")??void 0,apiKey:t.searchParams.get("apiKey")??void 0,params:t.searchParams,originalUri:e}}throw new R("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function Tl(e){switch(e){case"":case"red":return"red";case"reds":return"reds";case"grpc":return"grpc";case"grpcs":return"grpcs";case"http":return"http";case"https":return"https";case"pg":case"postgres":case"postgresql":return"pg";default:throw new R("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function vr(e){switch(e){case"http":return 5e3;case"https":return 55555;case"red":case"reds":case"redwire":return 5050;case"grpc":return 55055;case"grpcs":return 55555;case"pg":case"postgres":case"postgresql":return 5432;default:return}}var Or=S(()=>{Pe()});function Pl(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return Mi(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return Mi(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function Mi(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function Ol(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}var vl,$t,Dr=S(()=>{Pe();vl=new Set(["embedded"]),$t=class{constructor(t,n){this._client=t,this._transport=n??null}_guard(t){if(this._transport&&vl.has(this._transport))throw new R("UNSUPPORTED_TRANSPORT",`cache.${t} is not available on '${this._transport}' transport; use @reddb-io/client for remote cache endpoints.`)}async get(t,n){this._guard("get");let r=await this._client.call("cache.get",{namespace:t,key:n});return r==null||r.value==null?null:Ol(r.value)}async put(t,n,r,s={}){this._guard("put");let i=Pl(r);await this._client.call("cache.put",{namespace:t,key:n,value:i,...s})}async exists(t,n){return this._guard("exists"),(await this._client.call("cache.exists",{namespace:t,key:n}))?.status??"maybe"}async invalidate(t,n){this._guard("invalidate"),await this._client.call("cache.invalidate",{namespace:t,key:n})}async invalidatePrefix(t,n){return this._guard("invalidatePrefix"),(await this._client.call("cache.invalidate_prefix",{namespace:t,prefix:n}))?.removed??0}async invalidateTags(t,n){return this._guard("invalidateTags"),(await this._client.call("cache.invalidate_tags",{namespace:t,tags:n}))?.removed??0}async flushNamespace(t){this._guard("flushNamespace"),await this._client.call("cache.flush_namespace",{namespace:t})}}});function Ir(e,t){return`${$r(e)}.${Dl(t)}`}function $r(e){let t=String(e),n=t.match(/[^A-Za-z0-9_]/);if(n)throw new R("INVALID_KV_KEY",`invalid KV key "${t}": character "${n[0]}" is not supported`);return t}function Dl(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function Il(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="object"?`'${JSON.stringify(e).replace(/'/g,"''")}'`:`'${String(e).replace(/'/g,"''")}'`}function ji(e){return`'${String(e).replace(/'/g,"''")}'`}var ut,Cr=S(()=>{Pe();ut=class{constructor(t,n="kv_default"){this.client=t,this.collection=n}put(t,n,r={}){let s=r.collection??this.collection,i=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(ji).join(", ")}]`:"",o=r.expireMs!=null?` EXPIRE ${Number(r.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${Ir(s,t)} = ${Il(n)}${o}${i}`})}set(t,n,r={}){return this.put(t,n,r)}async get(t,n={}){let r=n.collection??this.collection;return(await this.client.call("query",{sql:`KV GET ${Ir(r,t)}`}))?.rows?.[0]?.value??null}async getMany(t,n={}){let r=[];for(let s of t)r.push(await this.get(s,n));return r}async exists(t,n={}){return{exists:await this.get(t,n)!==null}}async delete(t,n={}){let r=n.collection??this.collection,s=await this.client.call("query",{sql:`KV DELETE ${Ir(r,t)}`}),i=s.affected??s.affected_rows??0;return{affected:i,deleted:i>0}}async list(t={}){let n=t.collection??this.collection,r=t.limit==null?100:Number(t.limit);if(!Number.isInteger(r)||r<=0)throw new R("INVALID_ARGUMENT","kv.list limit must be a positive integer");let s=t.prefix==null?"":String(t.prefix),o=(await this.client.call("query",{sql:`SELECT key, value FROM ${$r(n)} ORDER BY key ASC LIMIT ${r}`})).rows??[];return{items:s.length>0?o.filter(c=>String(c.key).startsWith(s)):o}}async invalidateTags(t,n={}){let r=n.collection??this.collection,s=await this.client.call("query",{sql:`INVALIDATE TAGS [${t.map(ji).join(", ")}] FROM ${$r(r)}`});return s.affected??s.affected_rows??s.rows?.[0]?.invalidated??0}async*watch(t,n={}){if(!this.client.baseUrl)throw new R("UNSUPPORTED_TRANSPORT","kv.watch requires the HTTP transport");let r=n.collection??this.collection,s=new URLSearchParams;n.sinceLsn!=null&&s.set("since_lsn",String(n.sinceLsn)),n.limit!=null&&s.set("limit",String(n.limit));let i=s.toString()?`?${s}`:"",o=`${this.client.baseUrl}/collections/${encodeURIComponent(r)}/kv/${encodeURIComponent(String(t))}/watch${i}`,a=await fetch(o,this.client.attachAuth({method:"GET"}));if(!a.ok)throw new R("HTTP_ERROR",`kv.watch failed with HTTP ${a.status}`);let c=await a.text();for(let u of c.split(`
|
|
9
9
|
|
|
10
10
|
`)){let l=u.split(`
|
|
11
|
-
`).find(d=>d.startsWith("data: "));l&&(yield JSON.parse(l.slice(6)))}}watchPrefix(t,n={}){return this.watch(`${t}.*`,n)}}});function Uu(e,t,n){let{waitMs:r,group:s=null,count:i=null}=n??{};if(!Number.isInteger(r)||r<0)throw new _("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let o=de(e),a=de(t),c=s!=null?` GROUP ${de(s)}`:"",u=i!=null?hr(i):"";return`QUEUE READ ${o}${c} CONSUMER ${a}${u} WAIT ${r}ms`}function de(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new _("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function hr(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new _("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function Fu(e){if(!Number.isInteger(e))throw new _("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function Gu(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new _("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${Fu(e.priority)}`),e.key!=null&&(t+=` KEY ${yr(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${yr(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function qu(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?yr(e):JSON.stringify(e)}function yr(e){return`'${String(e).replace(/'/g,"''")}'`}function gr(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Et,wr=S(()=>{Se();Et=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${de(t)}`})}push(t,n,r={}){let s=Gu(r);return this.client.call("query",{sql:`QUEUE PUSH ${de(t)} ${qu(n)}${s}`})}async pop(t,n){let r=await this.client.call("query",{sql:`QUEUE POP ${de(t)}${hr(n)}`});return gr(r)}async peek(t,n){let r=await this.client.call("query",{sql:`QUEUE PEEK ${de(t)}${hr(n)}`});return gr(r)}async len(t){let n=await this.client.call("query",{sql:`QUEUE LEN ${de(t)}`});return Number(n?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${de(t)}`})}async readWait(t,n,r={}){let s=Uu(t,n,r),i=await this.client.call("query",{sql:s});return gr(i)}}});function wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new _("INVALID_ARGUMENT",`${t} must be an object`)}function Ju(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new _("INVALID_ARGUMENT","limit must be a positive integer");return e}function ln(e){return String(e).split(".").map(bi).join(".")}function bi(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new _("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function Hu(e){return _i(JSON.stringify(e))}function Wu(e){return JSON.stringify(e)}function Vu(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?Hu(e):_i(e)}function _i(e){return`'${String(e).replace(/'/g,"''")}'`}var kt,br=S(()=>{Se();kt=class{constructor(t){this.db=t}async insert(t,n){wi(n,"documents.insert document"),await this.ensureCollection(t);let r=await this.db.query(`INSERT INTO ${ln(t)} DOCUMENT VALUES (${Wu(n)}) RETURNING *`),s=r.rows?.[0];if(!s||s.rid==null)throw new _("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:r.affected??1,rid:s.rid,item:s}}async get(t,n){let r=await this.db.get(t,n);if(!r.entity)throw new _("NOT_FOUND",`document ${String(n)} was not found`);return r.entity}async list(t,n={}){let r=Ju(n.limit),s=n.orderBy??n.order_by??"rid ASC",i=n.filter?` WHERE ${String(n.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${ln(t)}${i} ORDER BY ${s} LIMIT ${r}`)).rows??[]}}async patch(t,n,r){wi(r,"documents.patch patch");let s=Object.entries(r);if(s.length===0)throw new _("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of s)if(c.includes("/"))throw new _("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let i=s.map(([c,u])=>`${bi(c)} = ${Vu(u)}`).join(", "),a=(await this.db.query(`UPDATE ${ln(t)} SET ${i} WHERE rid = $1 RETURNING *`,n)).rows?.[0];if(!a)throw new _("NOT_FOUND",`document ${String(n)} was not found`);return a}async delete(t,n){let s=(await this.db.delete(t,n)).affected??0;return{affected:s,deleted:s>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${ln(t)}`)}catch(n){if(!String(n?.message??"").includes("already exists"))throw n}}}});function Ku(e,t){if(t.secretRef){let{collection:n,key:r}=t.secretRef;return`SECRET_REF(vault, ${Ee(n)}.${Ee(r)})`}return Yu(e)}function zu(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function Ee(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function Yu(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Ri(e)}function Ri(e){return`'${String(e).replace(/'/g,"''")}'`}var xt,_r=S(()=>{xt=class{constructor(t,n="red.config"){this.client=t,this.collection=n}put(t,n,r={}){zu(r,"config");let s=r.collection??this.collection,i=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(Ri).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${Ee(s)} ${Ee(t)} = ${Ku(n,r)}${i}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${Ee(r)} ${Ee(t)}`})}resolve(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${Ee(r)} ${Ee(t)}`})}}});function Qu(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function st(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function Xu(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Si(e)}function Si(e){return`'${String(e).replace(/'/g,"''")}'`}var Tt,Rr=S(()=>{Tt=class{constructor(t,n="red.vault"){this.client=t,this.collection=n}put(t,n,r={}){Qu(r,"vault");let s=r.collection??this.collection,i=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(Si).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${st(s)}.${st(t)} = ${Xu(n)}${i}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${st(r)}.${st(t)}`})}unseal(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${st(r)}.${st(t)}`})}}});async function ki(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(Zu)}async function xi(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${tl(t)}`)).rows??[]).some(r=>r.name===String(t))}function Zu(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function Ei(e){return String(e).split(".").map(el).join(".")}function el(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new _("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function tl(e){return`'${String(e).replace(/'/g,"''")}'`}var vt,Sr=S(()=>{Se();vt=class e{constructor(t,n,r=null,s=[],i=[]){this.db=t,this.collection=n,this.columns=r,this.whereClauses=s,this.params=i}select(...t){let n=t.length===1&&Array.isArray(t[0])?t[0]:t,r=n.length===1&&n[0]==="*"?null:n;return new e(this.db,this.collection,r!=null&&r.length>0?r:null,this.whereClauses,this.params)}where(t,...n){if(typeof t!="string"||t.trim().length===0)throw new _("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let r=n.length===1&&Array.isArray(n[0])?n[0]:n;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...r])}async run(){let t=this.columns==null?"*":this.columns.map(Ei).join(", "),n=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(o=>`(${o})`).join(" AND ")}`:"",r=`SELECT ${t} FROM ${Ei(this.collection)}${n}`,i=(this.params.length>0?await this.db.query(r,this.params):await this.db.query(r)).rows??[];return this.columns==null?i:i.map(o=>{let a={};for(let c of this.columns)a[c]=o[c];return a})}}});async function mn(e,t={}){let n=ur(e);if(dl(n),n.kind==="embedded"){let r=ll(n,t.auth);if(r.token||r.username)throw new _("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let s=ul(n),i=t.binary??pi(),o=await li(i,s),a=new un(o);return await a.call("version",{}),new kr(a,{transport:"embedded"})}}function vi(e){return sl(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:ol(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&cl(e)?{$uuid:e}:e}function sl(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new _("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new _("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new _("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function il(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(vi):e.map(vi)}function ol(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function al(e){if(typeof Buffer<"u"){let r=Buffer.from(e,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function cl(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function dn(e){if(Array.isArray(e))return e.map(dn);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return al(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let r=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(r/1000000n))}}let n={};for(let[r,s]of Object.entries(e))n[r]=dn(s);return n}return e}function ul(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function ll(e,t){let n={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return n;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");n.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");n.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");n.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");n.password=t.password}return t.loginUrl!=null&&(n.loginUrl=t.loginUrl),n}function dl(e){if(e.kind!=="embedded")throw new _("EMBEDDED_ONLY",nl)}function xr(){return new _(Ti,`${Ti}: nested transactions are not supported on one connection`)}function Pi(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function fl(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new _("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${Oi} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function ml(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new _("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${Oi} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new _("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}var nl,rl,Oi,Ti,fn,Er,kr,Tr=S(()=>{di();gi();Se();lr();dr();pr();wr();br();_r();Rr();Sr();dr();pr();wr();br();_r();Rr();Sr();lr();nl="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",rl="1.0",Oi="1.0.9",Ti="NESTED_TX_NOT_SUPPORTED";fn=class{constructor(t){this.db=t}query(t,...n){return this.db.query(t,...n)}execute(t,...n){return this.db.execute(t,...n)}insert(t,n){return this.db.insert(t,n)}bulkInsert(t,n){return this.db.bulkInsert(t,n)}async transaction(){throw xr()}},Er=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw xr();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new _("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new _("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new _("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let n=await t(new fn(this.db));return await this.commit(),n}catch(n){if(this.active)try{await this.rollback()}catch(r){Pi(n,r)}throw n}}},kr=class{constructor(t,n={}){this.client=t,this.transport=n.transport??null,this.helperSpecVersion=rl,this.cache=new St(t,this.transport),this.queue=new Et(t),this.queues=this.queue,this.documents=new kt(this);let r=new rt(t);this.kv=Object.assign((s="kv_default")=>new rt(t,s),{put:r.put.bind(r),invalidateTags:r.invalidateTags.bind(r),watch:r.watch.bind(r),watchPrefix:r.watchPrefix.bind(r)}),this.config=(s="red.config")=>new xt(t,s),this.vault=(s="red.vault")=>new Tt(t,s),this.inTransaction=!1}query(t,...n){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new _("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let r=il(n);return r==null?this.client.call("query",{sql:t}).then(dn):this.client.call("query",{sql:t,params:r}).then(dn)}execute(t,...n){return this.query(t,...n)}async insert(t,n){let r=await this.client.call("insert",{collection:t,payload:n});return fl(r,"insert")}async bulkInsert(t,n){if(Array.isArray(n)&&n.length===0)return{affected:0,rids:[],ids:[]};let r=await this.client.call("bulk_insert",{collection:t,payloads:n});return ml(r,n.length)}tx(){return new Er(this)}async transaction(t){if(this.inTransaction)throw xr();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let n=!1;try{await this.query("BEGIN"),n=!0;let r=await t(new fn(this));return await this.query("COMMIT"),r}catch(r){if(n)try{await this.query("ROLLBACK")}catch(s){Pi(r,s)}throw r}finally{this.inTransaction=!1}}exists(t){return xi(this,t)}list(){return ki(this)}from(t){return new vt(this,t)}get(t,n){return this.client.call("get",{collection:t,id:String(n)})}delete(t,n){return this.client.call("delete",{collection:t,id:String(n)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,n){return this.client.call("auth.login",{username:t,password:n})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,n){return this.client.call("auth.change_password",{current_password:t,new_password:n})}createApiKey({username:t,role:n}={}){return this.client.call("auth.create_api_key",{username:t,role:n})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}}});function b(e,t){return new pn(e,t)}var pn,Ot=S(()=>{pn=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonError",this.line=t,this.reason=n}}});function vr(e){let t=e.split(`
|
|
12
|
-
`);return t.length>0&&t[t.length-1]===""&&t.pop(),t.map(n=>n.endsWith("\r")?n.slice(0,-1):n)}function
|
|
13
|
-
`;break;case"r":n+="\r";break;case"t":n+=" ";break;case"u":{let o=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(o))throw
|
|
14
|
-
`:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;default:n<" "?t+=`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`:t+=n}return`${t}"`}function
|
|
15
|
-
`);for(let[o,a]of Object.entries(n))
|
|
16
|
-
`);return}e.push(
|
|
17
|
-
`),
|
|
18
|
-
`)}function
|
|
11
|
+
`).find(d=>d.startsWith("data: "));l&&(yield JSON.parse(l.slice(6)))}}watchPrefix(t,n={}){return this.watch(`${t}.*`,n)}}});function $l(e,t,n){let{waitMs:r,group:s=null,count:i=null}=n??{};if(!Number.isInteger(r)||r<0)throw new R("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let o=ge(e),a=ge(t),c=s!=null?` GROUP ${ge(s)}`:"",u=i!=null?Ar(i):"";return`QUEUE READ ${o}${c} CONSUMER ${a}${u} WAIT ${r}ms`}function ge(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new R("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function Ar(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new R("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function Cl(e){if(!Number.isInteger(e))throw new R("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function Nl(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new R("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${Cl(e.priority)}`),e.key!=null&&(t+=` KEY ${Br(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${Br(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function Al(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?Br(e):JSON.stringify(e)}function Br(e){return`'${String(e).replace(/'/g,"''")}'`}function Nr(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var Ct,Lr=S(()=>{Pe();Ct=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${ge(t)}`})}push(t,n,r={}){let s=Nl(r);return this.client.call("query",{sql:`QUEUE PUSH ${ge(t)} ${Al(n)}${s}`})}async pop(t,n){let r=await this.client.call("query",{sql:`QUEUE POP ${ge(t)}${Ar(n)}`});return Nr(r)}async peek(t,n){let r=await this.client.call("query",{sql:`QUEUE PEEK ${ge(t)}${Ar(n)}`});return Nr(r)}async len(t){let n=await this.client.call("query",{sql:`QUEUE LEN ${ge(t)}`});return Number(n?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${ge(t)}`})}async readWait(t,n,r={}){let s=$l(t,n,r),i=await this.client.call("query",{sql:s});return Nr(i)}}});function Ui(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new R("INVALID_ARGUMENT",`${t} must be an object`)}function Bl(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new R("INVALID_ARGUMENT","limit must be a positive integer");return e}function En(e){return String(e).split(".").map(Fi).join(".")}function Fi(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new R("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function Ll(e){return Gi(JSON.stringify(e))}function Ml(e){return JSON.stringify(e)}function jl(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?Ll(e):Gi(e)}function Gi(e){return`'${String(e).replace(/'/g,"''")}'`}var Nt,Mr=S(()=>{Pe();Nt=class{constructor(t){this.db=t}async insert(t,n){Ui(n,"documents.insert document"),await this.ensureCollection(t);let r=await this.db.query(`INSERT INTO ${En(t)} DOCUMENT VALUES (${Ml(n)}) RETURNING *`),s=r.rows?.[0];if(!s||s.rid==null)throw new R("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:r.affected??1,rid:s.rid,item:s}}async get(t,n){let r=await this.db.get(t,n);if(!r.entity)throw new R("NOT_FOUND",`document ${String(n)} was not found`);return r.entity}async list(t,n={}){let r=Bl(n.limit),s=n.orderBy??n.order_by??"rid ASC",i=n.filter?` WHERE ${String(n.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${En(t)}${i} ORDER BY ${s} LIMIT ${r}`)).rows??[]}}async patch(t,n,r){Ui(r,"documents.patch patch");let s=Object.entries(r);if(s.length===0)throw new R("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of s)if(c.includes("/"))throw new R("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let i=s.map(([c,u])=>`${Fi(c)} = ${jl(u)}`).join(", "),a=(await this.db.query(`UPDATE ${En(t)} SET ${i} WHERE rid = $1 RETURNING *`,n)).rows?.[0];if(!a)throw new R("NOT_FOUND",`document ${String(n)} was not found`);return a}async delete(t,n){let s=(await this.db.delete(t,n)).affected??0;return{affected:s,deleted:s>0}}async ensureCollection(t){try{await this.db.query(`CREATE DOCUMENT ${En(t)}`)}catch(n){if(!String(n?.message??"").includes("already exists"))throw n}}}});function Ul(e,t){if(t.secretRef){let{collection:n,key:r}=t.secretRef;return`SECRET_REF(vault, ${Oe(n)}.${Oe(r)})`}return Gl(e)}function Fl(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function Oe(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function Gl(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):qi(e)}function qi(e){return`'${String(e).replace(/'/g,"''")}'`}var At,jr=S(()=>{At=class{constructor(t,n="red.config"){this.client=t,this.collection=n}put(t,n,r={}){Fl(r,"config");let s=r.collection??this.collection,i=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(qi).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${Oe(s)} ${Oe(t)} = ${Ul(n,r)}${i}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${Oe(r)} ${Oe(t)}`})}resolve(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${Oe(r)} ${Oe(t)}`})}}});function ql(e,t){for(let n of["ttl","ttlMs","ttl_ms","expireMs","expire_ms","expiresAt"])if(e[n]!=null)throw new TypeError(`${t} does not support TTL or expiration options`)}function lt(e){let t=String(e);if(!/^[A-Za-z0-9_.]+$/.test(t))throw new TypeError("keyed collection and key names must use letters, numbers, underscores, or dots");return t}function Jl(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Ji(e)}function Ji(e){return`'${String(e).replace(/'/g,"''")}'`}var Bt,Ur=S(()=>{Bt=class{constructor(t,n="red.vault"){this.client=t,this.collection=n}put(t,n,r={}){ql(r,"vault");let s=r.collection??this.collection,i=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(Ji).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${lt(s)}.${lt(t)} = ${Jl(n)}${i}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${lt(r)}.${lt(t)}`})}unseal(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${lt(r)}.${lt(t)}`})}}});async function Wi(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(Hl)}async function Vi(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${Vl(t)}`)).rows??[]).some(r=>r.name===String(t))}function Hl(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function Hi(e){return String(e).split(".").map(Wl).join(".")}function Wl(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new R("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function Vl(e){return`'${String(e).replace(/'/g,"''")}'`}var Lt,Fr=S(()=>{Pe();Lt=class e{constructor(t,n,r=null,s=[],i=[]){this.db=t,this.collection=n,this.columns=r,this.whereClauses=s,this.params=i}select(...t){let n=t.length===1&&Array.isArray(t[0])?t[0]:t,r=n.length===1&&n[0]==="*"?null:n;return new e(this.db,this.collection,r!=null&&r.length>0?r:null,this.whereClauses,this.params)}where(t,...n){if(typeof t!="string"||t.trim().length===0)throw new R("INVALID_QUERY_BUILDER","where() requires a non-empty SQL condition");let r=n.length===1&&Array.isArray(n[0])?n[0]:n;return new e(this.db,this.collection,this.columns,[...this.whereClauses,t.trim()],[...this.params,...r])}async run(){let t=this.columns==null?"*":this.columns.map(Hi).join(", "),n=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(o=>`(${o})`).join(" AND ")}`:"",r=`SELECT ${t} FROM ${Hi(this.collection)}${n}`,i=(this.params.length>0?await this.db.query(r,this.params):await this.db.query(r)).rows??[];return this.columns==null?i:i.map(o=>{let a={};for(let c of this.columns)a[c]=o[c];return a})}}});async function dt(e,t={}){let n=Pr(e);if(rd(n),n.kind==="embedded"){let r=nd(n,t.auth);if(r.token||r.username)throw new R("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let s=td(n),i=t.binary??Bi(),o=await $i(i,s),a=new kn(o);return await a.call("version",{}),new qr(a,{transport:"embedded"})}}function zi(e){return Yl(e),e instanceof Float32Array||e instanceof Float64Array?Array.from(e):e instanceof Date?{$ts:String(BigInt(e.getTime())*1000000n)}:e instanceof Uint8Array||typeof Buffer<"u"&&e instanceof Buffer?{$bytes:Xl(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&ed(e)?{$uuid:e}:e}function Yl(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new R("UNSUPPORTED_PARAM","cannot encode invalid Date query parameter");return}if(!(e instanceof Uint8Array||e instanceof Float32Array||e instanceof Float64Array||typeof Buffer<"u"&&e instanceof Buffer)){if(Array.isArray(e)){if(e.every(t=>typeof t=="number"))return;throw new R("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new R("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function Ql(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(zi):e.map(zi)}function Xl(e){let t=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof Buffer<"u")return Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64");let n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function Zl(e){if(typeof Buffer<"u"){let r=Buffer.from(e,"base64");return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function ed(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function xn(e){if(Array.isArray(e))return e.map(xn);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return Zl(e.$bytes);if(typeof e.$uuid=="string")return e.$uuid;if(typeof e.$float=="string"){if(e.$float==="NaN")return Number.NaN;if(e.$float==="Infinity"||e.$float==="+Infinity")return 1/0;if(e.$float==="-Infinity")return-1/0}if(typeof e.$ts=="string"||typeof e.$ts=="number"){let r=typeof e.$ts=="string"?BigInt(e.$ts):BigInt(Math.trunc(e.$ts));return new Date(Number(r/1000000n))}}let n={};for(let[r,s]of Object.entries(e))n[r]=xn(s);return n}return e}function td(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function nd(e,t){let n={token:e.token??e.apiKey??null,username:e.username??null,password:e.password??null,loginUrl:e.loginUrl??null};if(t==null)return n;if(typeof t!="object")throw new TypeError("options.auth must be an object");if(t.token!=null){if(typeof t.token!="string"||t.token.length===0)throw new TypeError("options.auth.token must be a non-empty string");n.token=t.token}if(t.apiKey!=null){if(typeof t.apiKey!="string"||t.apiKey.length===0)throw new TypeError("options.auth.apiKey must be a non-empty string");n.token=t.apiKey}if(t.username!=null){if(typeof t.username!="string"||t.username.length===0)throw new TypeError("options.auth.username must be a non-empty string");n.username=t.username}if(t.password!=null){if(typeof t.password!="string"||t.password.length===0)throw new TypeError("options.auth.password must be a non-empty string");n.password=t.password}return t.loginUrl!=null&&(n.loginUrl=t.loginUrl),n}function rd(e){if(e.kind!=="embedded")throw new R("EMBEDDED_ONLY",Kl)}function Jr(){return new R(Ki,`${Ki}: nested transactions are not supported on one connection`)}function Qi(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function sd(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new R("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${Yi} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function id(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new R("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${Yi} with bulk insert id support`);if(Array.isArray(e.rids)||(e.rids=e.ids),Array.isArray(e.ids)||(e.ids=e.rids),e.rids.length!==t)throw new R("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}var Kl,zl,Yi,Ki,Tn,Gr,qr,Hr=S(()=>{Ci();Li();Pe();Or();Dr();Cr();Lr();Mr();jr();Ur();Fr();Dr();Cr();Lr();Mr();jr();Ur();Fr();Or();Kl="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",zl="1.0",Yi="1.0.9",Ki="NESTED_TX_NOT_SUPPORTED";Tn=class{constructor(t){this.db=t}query(t,...n){return this.db.query(t,...n)}execute(t,...n){return this.db.execute(t,...n)}insert(t,n){return this.db.insert(t,n)}bulkInsert(t,n){return this.db.bulkInsert(t,n)}async transaction(){throw Jr()}},Gr=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw Jr();this.db.inTransaction=!0,this.active=!0;try{return await this.db.query("BEGIN")}catch(t){throw this.db.inTransaction=!1,this.active=!1,t}}async commit(){if(!this.active)throw new R("INVALID_ARGUMENT","tx.commit() called without an open transaction");try{return await this.db.query("COMMIT")}finally{this.active=!1,this.db.inTransaction=!1}}async rollback(){if(!this.active)throw new R("INVALID_ARGUMENT","tx.rollback() called without an open transaction");try{return await this.db.query("ROLLBACK")}finally{this.active=!1,this.db.inTransaction=!1}}async run(t){if(typeof t!="function")throw new TypeError("tx.run(callback) requires a function");if(this.db.inTransaction)throw new R("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let n=await t(new Tn(this.db));return await this.commit(),n}catch(n){if(this.active)try{await this.rollback()}catch(r){Qi(n,r)}throw n}}},qr=class{constructor(t,n={}){this.client=t,this.transport=n.transport??null,this.helperSpecVersion=zl,this.cache=new $t(t,this.transport),this.queue=new Ct(t),this.queues=this.queue,this.documents=new Nt(this);let r=new ut(t);this.kv=Object.assign((s="kv_default")=>new ut(t,s),{put:r.put.bind(r),invalidateTags:r.invalidateTags.bind(r),watch:r.watch.bind(r),watchPrefix:r.watchPrefix.bind(r)}),this.config=(s="red.config")=>new At(t,s),this.vault=(s="red.vault")=>new Bt(t,s),this.inTransaction=!1}query(t,...n){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new R("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let r=Ql(n);return r==null?this.client.call("query",{sql:t}).then(xn):this.client.call("query",{sql:t,params:r}).then(xn)}execute(t,...n){return this.query(t,...n)}async insert(t,n){let r=await this.client.call("insert",{collection:t,payload:n});return sd(r,"insert")}async bulkInsert(t,n){if(Array.isArray(n)&&n.length===0)return{affected:0,rids:[],ids:[]};let r=await this.client.call("bulk_insert",{collection:t,payloads:n});return id(r,n.length)}tx(){return new Gr(this)}async transaction(t){if(this.inTransaction)throw Jr();if(typeof t!="function")throw new TypeError("transaction(callback) requires a function");this.inTransaction=!0;let n=!1;try{await this.query("BEGIN"),n=!0;let r=await t(new Tn(this));return await this.query("COMMIT"),r}catch(r){if(n)try{await this.query("ROLLBACK")}catch(s){Qi(r,s)}throw r}finally{this.inTransaction=!1}}exists(t){return Vi(this,t)}list(){return Wi(this)}from(t){return new Lt(this,t)}get(t,n){return this.client.call("get",{collection:t,id:String(n)})}delete(t,n){return this.client.call("delete",{collection:t,id:String(n)})}health(){return this.client.call("health",{})}version(){return this.client.call("version",{})}login(t,n){return this.client.call("auth.login",{username:t,password:n})}whoami(){return this.client.call("auth.whoami",{})}changePassword(t,n){return this.client.call("auth.change_password",{current_password:t,new_password:n})}createApiKey({username:t,role:n}={}){return this.client.call("auth.create_api_key",{username:t,role:n})}revokeApiKey(t){return this.client.call("auth.revoke_api_key",{key:t})}close(){return this.client.close()}}});import{isAbsolute as mb,join as ft,resolve as pb}from"node:path";function ad(e){if(!e)throw new Error("root is required");return e.replace(/\/$/,"")}function Xi(e){return ft(ad(e),od)}function Zi(e){return ft(Xi(e),"state")}function cd(e){return ft(Xi(e),"tmp")}function W(e){return ft(Zi(e),"rsp")}function ud(e){return ft(Zi(e),"red-skills.rdb")}function ld(e){return ft(cd(e),"red-skills.rdb")}function no(e,t){let n=ud(e);if(t(n))return n;let r=ld(e);return t(r)?r:n}var od,eo,to,De=S(()=>{od=".red";eo=".red/state/red-skills.rdb";to=".red/tmp/red-skills.rdb"});function _(e,t){return new Mt(e,t)}function P(e,t){return new Je(e,t)}function mt(e){return e instanceof Je?e:e instanceof Mt?new Je(e.line,e.reason):new Je(0,String(e&&e.message?e.message:e))}var Mt,Je,jt=S(()=>{Mt=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonError",this.line=t,this.reason=n}},Je=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonlError",this.line=t,this.reason=n}}});function vn(e){let t=e.split(`
|
|
12
|
+
`);return t.length>0&&t[t.length-1]===""&&t.pop(),t.map(n=>n.endsWith("\r")?n.slice(0,-1):n)}function ne(e){return _(e,"invalid quoted string")}function re(e,t){if(e==="")return"";if(e.startsWith('"'))return ro(e,t);if(e.includes('"'))throw ne(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:dd(e)?Number(e):e}function he(e,t){let n=e.trim();if(n.startsWith('"'))return[ro(n,t),!0];if(n.includes('"')||/\s/.test(n))throw _(t,"expected non-empty field name");return[n,!1]}function ro(e,t){if(e[0]!=='"')throw ne(t);let n="",r=1;for(;r<e.length;){let s=e[r];if(r+=1,s==='"'){if(e.slice(r).trim()==="")return n;throw ne(t)}if(s==="\\"){let i=e[r];switch(r+=1,i){case'"':n+='"';break;case"\\":n+="\\";break;case"n":n+=`
|
|
13
|
+
`;break;case"r":n+="\r";break;case"t":n+=" ";break;case"u":{let o=e.slice(r,r+4);if(!/^[0-9a-fA-F]{4}$/.test(o))throw ne(t);let a=Number.parseInt(o,16);if(a>=55296&&a<=57343)throw ne(t);n+=String.fromCharCode(a),r+=4;break}default:throw ne(t)}continue}if(s<" "&&s!==" ")throw ne(t);n+=s}throw ne(t)}function He(e,t,n){if(e==="")return[];let r=[],s=0,i=!1,o=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){o=!1;continue}c==="\\"&&i?o=!0:c==='"'?i=!i:c===t&&!i&&(r.push(e.slice(s,a).trim()),s=a+1)}if(i||o)throw ne(n);return r.push(e.slice(s).trim()),r}function U(e,t,n){let r=!1,s=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(s){s=!1;continue}if(o==="\\"&&r)s=!0;else if(o==='"')r=!r;else if(o===t&&!r)return i}if(r||s)throw ne(n);return-1}function dd(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function fd(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function md(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw _(0,"number is not representable in TOON");return String(e)}function Ut(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function se(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return md(e);if(typeof e=="string")return gd(e,t);throw _(0,"not a primitive")}function pd(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function Z(e){return pd(e)?e:so(e)}function gd(e,t){return hd(e,t)?so(e):e}function hd(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||fd(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}function so(e){let t='"';for(let n of e)switch(n){case'"':t+='\\"';break;case"\\":t+="\\\\";break;case`
|
|
14
|
+
`:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;default:n<" "?t+=`\\u${n.charCodeAt(0).toString(16).padStart(4,"0")}`:t+=n}return`${t}"`}function pt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}var I,Wr=S(()=>{jt();I=","});function yd(e={}){return{indent:Math.max(1,e.indent??Zr),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function wd(e,t){let n=[],r=!1;return vn(e).forEach((s,i)=>{let o=i+1;if(s.trim()===""){r=!0;return}let a=s.length-s.replace(/^ +/,"").length;if(s[a]===" ")throw _(o,"invalid indentation");if(t.strict&&a%t.indent!==0)throw _(o,"invalid indentation");n.push({number:o,depth:Math.floor(a/t.indent),content:s.slice(a),blankBefore:r}),r=!1}),n}function ie(e,t){let n=yd(t),r=wd(e,n),s=r[0];if(s===void 0)return{};if(s.depth!==0)throw _(s.number,"invalid indentation");let i=r.length===1;if(i&&s.content.trim()==="[]")return[];if(s.content.startsWith("[")){let u;try{u=ns(s.content,U(s.content,":",s.number))}catch(l){if(n.strict)throw Qr(l,s.number);u=void 0}if(u!==void 0)return Rd(u,r,n)}if(i&&U(s.content,":",s.number)===-1)return re(s.content.trim(),s.number);let o={index:0},a=es(r,o,0,n),c=r[o.index];if(c!==void 0)throw _(c.number,"expected end of document");return a}function es(e,t,n,r){let s={};for(;t.index<e.length;){let i=e[t.index];if(i.depth<n)break;if(i.depth>n)throw _(i.number,"invalid indentation");let{key:o,quoted:a,value:c}=bd(e,t,n,r);ao(s,o,a,c,r,i.number)}return s}function bd(e,t,n,r){let s=e[t.index],i=s.content,o=U(i,":",s.number);if(o===-1)throw _(s.number,"expected `key: value`");let a=i.slice(0,o),c=i.slice(o+1),u=U(a,"[",s.number),l=U(a,"{",s.number);if(l!==-1&&(u===-1||l<u)){let g;try{g=xd(a)}catch(p){if(r.strict)throw Qr(p,s.number);t.index+=1;let w=Vr(e,t,n,c,s.number,r);return{key:a.trim(),quoted:!1,value:w}}if(c.trim()!=="")throw _(s.number,"expected keyed map rows");let m=_d(g,e,t,n+1,r);return{key:g.key,quoted:g.keyQuoted,value:m}}if(u!==-1){let g;try{g=ns(a,o)}catch(p){if(r.strict)throw Qr(p,s.number);t.index+=1;let w=Vr(e,t,n,c,s.number,r);return{key:a.trim(),quoted:!1,value:w}}if(g.key===""&&!g.keyQuoted)throw _(s.number,"expected non-empty field name");let m=ts(g,c,e,t,n,r);return{key:g.key,quoted:g.keyQuoted,value:m}}let[d,f]=he(a,s.number);if(d===""&&!f)throw _(s.number,"expected non-empty field name");t.index+=1;let h=Vr(e,t,n,c,s.number,r);return{key:d,quoted:f,value:h}}function Vr(e,t,n,r,s,i){let o=r.trim();if(o==="[]")return[];if(o!=="")return re(o,s);let a=e[t.index];return a!==void 0&&a.depth>n?es(e,t,n+1,i):{}}function _d(e,t,n,r,s){let i={};for(n.index+=1;n.index<t.length;){let o=t[n.index];if(o.depth<r)break;if(o.depth>r)throw _(o.number,"invalid indentation");if(o.blankBefore&&s.strict)throw _(o.number,"blank line inside keyed map");let a=U(o.content,":",o.number);if(a===-1)throw _(o.number,"expected `key: value`");let[c,u]=he(o.content.slice(0,a),o.number);if(c===""&&!u)throw _(o.number,"expected non-empty field name");let l=He(o.content.slice(a+1).trim(),e.delimiter,o.number);if(l.length!==e.fields.length)throw _(o.number,"keyed map row length mismatch");let d={};e.fields.forEach((f,h)=>{Ft(d,f,re(l[h],o.number),s,o.number)}),ao(i,c,u,d,s,o.number),n.index+=1}return i}function Rd(e,t,n){let r=t[0],s=U(r.content,":",r.number);if(s===-1)throw _(r.number,"expected `key: value`");let i=r.content.slice(s+1),o={index:0},a=ts(e,i,t,o,0,n),c=t[o.index];if(c!==void 0)throw _(c.number,"expected end of document");return a}function ts(e,t,n,r,s,i){let o=n[r.index].number,a=t.trim();if(r.index+=1,e.fields!==void 0){if(a!=="")throw _(o,"expected tabular rows");return Sd(e,e.fields,n,r,s+1,i)}if(a!==""){let c=He(a,e.delimiter,o).map(u=>re(u,o));if(c.length!==e.len)throw _(o,"array length mismatch");return c}return kd(e,n,r,s+1,i)}function Sd(e,t,n,r,s,i){let o=[];for(;o.length<e.len;){let c=n[r.index];if(c===void 0)throw zr(n,r.index);if(c.depth<s)break;if(c.depth>s)throw _(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw _(c.number,"blank line inside array");if(!io(c.content,e.delimiter,c.number))break;let u=He(c.content,e.delimiter,c.number);if(u.length!==t.length)throw _(c.number,"array row length mismatch");let l={};t.forEach((d,f)=>{Ft(l,d,re(u[f],c.number),i,c.number)}),o.push(l),r.index+=1}if(o.length!==e.len)throw zr(n,r.index);let a=n[r.index];if(a!==void 0&&a.depth>=s&&io(a.content,e.delimiter,a.number))throw _(a.number,"array length mismatch");return o}function io(e,t,n){let r=U(e,":",n);if(r===-1)return!0;let s=U(e,t,n);return s===-1?!1:s<r}function kd(e,t,n,r,s){let i=[];for(;i.length<e.len;){let a=t[n.index];if(a===void 0||a.depth<r)throw zr(t,n.index);if(a.depth>r)throw _(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw _(a.number,"blank line inside array");i.push(Ed(t,n,r,s))}let o=t[n.index];if(o!==void 0&&o.depth>=r)throw _(o.number,"array length mismatch");return i}function Ed(e,t,n,r){let s=e[t.index];if(!s.content.startsWith("-"))throw _(s.number,"expected array item");let i=s.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let o=U(i,":",s.number),a;try{a=ns(i,o)}catch{a=void 0}if(a!==void 0){let c=i.slice(o+1);return ts(a,c,e,t,n,r)}}if(U(i,":",s.number)!==-1){let o=[{number:s.number,depth:n+1,content:i,blankBefore:!1}];for(t.index+=1;t.index<e.length;){let a=e[t.index];if(a.depth<=n)break;o.push(a),t.index+=1}return es(o,{index:0},n+1,r)}return t.index+=1,re(i,s.number)}function zr(e,t){let n=e[t]??e[e.length-1];return _(n===void 0?1:n.number,"array length mismatch")}function ns(e,t){if(t===-1)throw _(0,"array header missing colon");let n=e.slice(0,t),r=U(n,"[",0);if(r===-1)throw _(0,"invalid array header");let s,i;try{[s,i]=he(n.slice(0,r),0)}catch{throw _(0,"invalid array header")}let o=n.slice(r+1),a=o.indexOf("]");if(a===-1)throw _(0,"invalid array header");let c=o.slice(0,a),u=/^[0-9]*/.exec(c)[0];if(u===""||u.length>1&&u.startsWith("0"))throw _(0,"invalid array header");let l=Number.parseInt(u,10),d;switch(c.slice(u.length)){case"":d=",";break;case" ":d=" ";break;case"|":d="|";break;default:throw _(0,"invalid array header")}let f=o.slice(a+1),h;if(f==="")h=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2)try{h=oo(f.slice(1,-1),d)}catch(g){throw _(0,g.reason==="duplicate key"?"duplicate key":"invalid array header")}else throw _(0,"invalid array header");return{key:s,keyQuoted:i,len:l,delimiter:d,fields:h}}function xd(e){let t=U(e,"{",0);if(t===-1||!e.endsWith("}"))throw _(0,"invalid keyed map header");let n,r;try{[n,r]=he(e.slice(0,t),0)}catch{throw _(0,"invalid keyed map header")}if(n===""&&!r)throw _(0,"expected non-empty field name");let s;try{s=oo(e.slice(t+1,-1),I)}catch(i){throw _(0,i.reason==="duplicate key"?"duplicate key":"invalid keyed map header")}return{key:n,keyQuoted:r,delimiter:I,fields:s}}function oo(e,t){let n=[],r=0;function s(a,c){let u=0;for(;r<e.length&&!(c&&e[r]==="}");){if(e[r]===t||e[r]==="}")throw _(0,"invalid array header");let l=r;for(;r<e.length;){let f=e[r];if(f==='"'){i();continue}if(f===t||f==="{"||f==="}")break;r+=1}let[d]=he(e.slice(l,r),0);if(d==="")throw _(0,"invalid array header");if(u+=1,e[r]==="{"){r+=1;let f=n.length;if(s([...a,d],!0),e[r]!=="}"||n.length===f)throw _(0,"invalid array header");r+=1}else n.push([...a,d]);if(e[r]===t){if(r+=1,r>=e.length||e[r]==="}")throw _(0,"invalid array header");continue}if(c?e[r]==="}":r===e.length)break;throw _(0,"invalid array header")}if(u===0)throw _(0,"invalid array header")}function i(){for(r+=1;r<e.length;){let a=e[r];if(r+=1,a==="\\")r+=1;else if(a==='"')return}}if(s([],!1),r!==e.length)throw _(0,"invalid array header");let o=new Set;for(let a=0;a<n.length;a+=1)for(let c=a+1;c<n.length;c+=1)if(Td(n[a],n[c])||Yr(n[a],n[c])||Yr(n[c],n[a]))throw _(0,"duplicate key");for(let a of n){let c=a.join("\0");if(o.has(c))throw _(0,"duplicate key");o.add(c)}return n}function Td(e,t){return e.length===t.length&&Yr(e,t)}function Yr(e,t){return t.every((n,r)=>e[r]===n)}function Qr(e,t){return _(t,e.reason??String(e.message))}function ao(e,t,n,r,s,i){if(s.expandPaths&&!n&&t.includes(".")){let o=t.split(".");if(o.every(vd)){Ft(e,o,r,s,i);return}}Ft(e,[t],r,s,i)}function Ft(e,t,n,r,s){let i=t[0],o=Object.prototype.hasOwnProperty.call(e,i);if(t.length===1){if(o&&r.strict)throw _(s,"duplicate key");pt(e,i,n);return}if(o&&!gt(e[i])){if(r.strict)throw _(s,"path expansion conflict");pt(e,i,{})}else o||pt(e,i,{});Ft(e[i],t.slice(1),n,r,s)}function vd(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function O(e,t={}){let n={nestedTabularHeaders:t.nestedTabularHeaders===!0,keyedMapCollapse:t.keyedMapCollapse===!0},r=[];return Array.isArray(e)?rs(r,void 0,e,0,!1,n):gt(e)?co(r,e,0,n):r.push(se(e,I)),r.join("")}function Gt(e,t){e.push(" ".repeat(t*Zr))}function co(e,t,n,r){for(let[s,i]of Object.entries(t))Gt(e,n),Xr(e,s,i,n,r)}function Xr(e,t,n,r,s){if(Array.isArray(n)){rs(e,t,n,r,!1,s);return}if(gt(n)){let i=s.keyedMapCollapse?Od(n,s):void 0;if(i!==void 0){e.push(Z(t),"{",i.fields.map(ss).join(I),`}:
|
|
15
|
+
`);for(let[o,a]of Object.entries(n))Gt(e,r+1),e.push(Z(o),": ",i.paths.map(c=>se(mo(a,c),I)).join(I),`
|
|
16
|
+
`);return}e.push(Z(t),`:
|
|
17
|
+
`),co(e,n,r+1,s);return}e.push(Z(t),": ",se(n,I),`
|
|
18
|
+
`)}function rs(e,t,n,r,s,i){if(n.length===0){t!==void 0?e.push(Z(t),`: []
|
|
19
19
|
`):s?e.push(`[0]:
|
|
20
20
|
`):e.push(`[]
|
|
21
|
-
`);return}if(n.every(
|
|
22
|
-
`);return}let o=s?void 0:
|
|
23
|
-
`);for(let a of n)
|
|
24
|
-
`);return}
|
|
25
|
-
`);for(let a of n)
|
|
26
|
-
`);return}e.push("- "),
|
|
27
|
-
`)}function
|
|
28
|
-
`
|
|
21
|
+
`);return}if(n.every(Ut)){Kr(e,t,n.length,void 0),e.push(" "),e.push(n.map(a=>se(a,I)).join(I)),e.push(`
|
|
22
|
+
`);return}let o=s?void 0:uo(n,i);if(o!==void 0){Kr(e,t,n.length,o.fields),e.push(`
|
|
23
|
+
`);for(let a of n)Gt(e,r+1),e.push(o.paths.map(c=>se(mo(a,c),I)).join(I)),e.push(`
|
|
24
|
+
`);return}Kr(e,t,n.length,void 0),e.push(`
|
|
25
|
+
`);for(let a of n)Gt(e,r+1),Pd(e,a,r+1,i)}function Pd(e,t,n,r){if(Array.isArray(t)){e.push("- "),rs(e,void 0,t,n,!0,r);return}if(gt(t)){let s=Object.entries(t);if(s.length===0){e.push(`-
|
|
26
|
+
`);return}e.push("- "),Xr(e,s[0][0],s[0][1],n+1,r);for(let[i,o]of s.slice(1))Gt(e,n+1),Xr(e,i,o,n+1,r);return}e.push("- ",se(t,I),`
|
|
27
|
+
`)}function Kr(e,t,n,r){t!==void 0&&e.push(Z(t)),e.push("[",String(n),"]"),r!==void 0&&e.push("{",r.map(ss).join(I),"}"),e.push(":")}function uo(e,t){let n=lo(e.map(r=>({value:r})),t);return n===void 0?void 0:{fields:n,paths:fo(n)}}function Od(e,t){let n=Object.values(e);if(!(n.length<2))return uo(n,t)}function lo(e,t){let n=e[0]?.value;if(!gt(n))return;let r=Object.keys(n).map(s=>({key:s}));if(r.length!==0){for(let{value:s}of e)if(!gt(s)||Object.keys(s).length!==r.length||r.some(o=>!Object.prototype.hasOwnProperty.call(s,o.key)))return;for(let s of r){let i=e.map(({value:a})=>({value:a[s.key]}));if(i.every(({value:a})=>Ut(a)))continue;if(!t.nestedTabularHeaders)return;let o=lo(i,t);if(o===void 0)return;s.children=o}return r}}function fo(e,t=[]){return e.flatMap(n=>{let r=[...t,n.key];return n.children===void 0?[r]:fo(n.children,r)})}function mo(e,t){let n=e;for(let r of t)n=n[r];return n}function ss(e){return e.children===void 0?Z(e.key):`${Z(e.key)}{${e.children.map(ss).join(I)}}`}var Zr,qt=S(()=>{jt();Wr();Zr=2});var po=S(()=>{qt()});function Id(e,t){if(!(e.startsWith("[=")&&e.endsWith("]")))return null;let n=e.slice(2,-1);if(!/^[0-9]+$/.test(n))throw P(t,"invalid trailer count");return Number.parseInt(n,10)}function xo(e,t){if(!Eo.test(e))throw P(t,"invalid tag")}function $d(e,t){let n=e.indexOf(":");if(n<=0)return null;let r=e.slice(0,n);if(!Eo.test(r)){if(/^[A-Za-z0-9_-]/.test(r)&&/^[^,[\]|{}:\t ]+$/.test(r))throw P(t,"invalid tag");return null}return{tag:r,cellsText:e.slice(n+1)}}function Cd(e,t){if(!e.startsWith("["))return null;let n=e.slice(1),r=n.indexOf("]");if(r===-1)throw P(t,"invalid header");let s=n.slice(0,r),i=s.startsWith("~"),o=i?s.slice(1):s;if(!i&&o.startsWith("="))return null;if(!So.includes(o)&&o!=="")throw P(t,"invalid header delimiter");let a=o===""?I:o,c=n.slice(r+1),u=null;if(!i&&c.startsWith("<")){let f=c.indexOf(">");if(f===-1)throw P(t,"invalid tag");if(u=c.slice(1,f),xo(u,t),o!=="")throw P(t,"invalid header delimiter");c=c.slice(f+1)}if(!c.startsWith("{")||!c.endsWith("}:"))throw P(t,"invalid header");let l=c.slice(1,-2),d;try{d=He(l,a,t).map(f=>he(f,t)[0])}catch(f){throw mt(f)}if(d.length===0||d.some(f=>f===""))throw P(t,"invalid header fields");return{delimiter:a,fields:d,fieldText:l,continuation:i,tag:u}}function Nd(e,t,n){if(e===null||e.delimiter===void 0)throw P(n,"continuation header before header");if(e.delimiter!==t.delimiter||e.fieldText!==t.fieldText)throw P(n,"continuation header mismatch")}function go(e,t,n,r){let s;try{s=He(e,t,r)}catch(i){throw mt(i)}if(s.length!==n)throw P(r,"row arity mismatch");for(let i of s)try{re(i,r)}catch(o){throw mt(o)}return s}function Ad(e,t,n){let r={};return e.forEach((s,i)=>{try{pt(r,s,re(t[i],n))}catch(o){throw mt(o)}}),r}function Bd(e,t,n){if(e.startsWith("- "))throw P(t,"reserved line prefix");let r=Id(e,t);if(r!==null){if(n===null||n.delimiter===void 0)throw P(t,"trailer without header");if(n.rowCount!==r)throw P(t,"trailer count mismatch");return{kind:"trailer"}}let s=Cd(e,t);if(s!==null)return s.continuation?(Nd(n,s,t),{kind:"continuation"}):s.tag!==null?{kind:"tag-header",header:s}:{kind:"header",header:s};let i=$d(e,t);if(i!==null){let o=n?.taggedLanes?.get(i.tag);if(o===void 0)throw P(t,"unknown tag");return{kind:"tagged-row",tag:i.tag,cells:go(i.cellsText,o.delimiter,o.fields.length,t)}}if(n===null||n.delimiter===void 0)throw P(t,"row before header");return{kind:"row",cells:go(e,n.delimiter,n.fields.length,t)}}function Ld(e,t={}){let n=[],r=new Map,s=[],i=[],o=null,a=!1,c=!1;function u(h,g){let m=i.at(-1);if(m!==void 0&&m.lane===h.lane&&m.delimiter===h.delimiter&&m.fieldText===h.fieldText){m.rows.push(g);return}i.push({lane:h.lane,delimiter:h.delimiter,fields:h.fields,fieldText:h.fieldText,rows:[g]})}function l(){o!==null&&s.push({delimiter:o.delimiter,fields:o.fields,fieldText:o.fieldText,lane:o.lane,rows:o.rows})}function d(h,g,m){let p=r.get(h);if(p===void 0){if(r.size>=ko)throw P(m,"too many tagged lanes");p={segments:[],current:null},r.set(h,p),n.push(h)}else p.current!==null&&p.segments.push(p.current);p.current={lane:h,delimiter:g.delimiter,fields:g.fields,fieldText:g.fieldText,rows:[]},p.delimiter=g.delimiter,p.fields=g.fields,p.fieldText=g.fieldText}if(vn(e).forEach((h,g)=>{let m=g+1;if(h==="")return;let p=o===null?{taggedLanes:r}:{delimiter:o.delimiter,fields:o.fields,fieldText:o.fieldText,rowCount:o.rows.length,taggedLanes:r},w=Bd(h,m,p);if(w.kind==="trailer"){l(),o=null;return}if(w.kind!=="continuation"){if(w.kind==="tag-header"){c=!0,d(w.header.tag,w.header,m);return}if(w.kind==="header"){l(),a||(n.push(null),a=!0),o={lane:null,delimiter:w.header.delimiter,fields:w.header.fields,fieldText:w.header.fieldText,rows:[]};return}if(w.kind==="tagged-row"){c=!0;let y=r.get(w.tag).current;y.rows.push(w.cells),u(y,w.cells);return}if(o===null)throw P(m,"row before header");o.rows.push(w.cells),u(o,w.cells)}}),!c)return l(),t.preserveInterleaving===!0,s;let f=[];l();for(let h of n){if(h===null){f.push(...s);continue}let g=r.get(h);f.push(...g.segments),g.current!==null&&f.push(g.current)}return t.preserveInterleaving===!0?i:f}function Pn(e){return Ld(e).flatMap(t=>t.rows.map(n=>Ad(t.fields,n,0)))}function Md(e){if(!So.includes(e))throw P(0,"invalid header delimiter")}function ho(e,t,n=!1){return`[${`${n?"~":""}${e===I?"":e}`}]{${t}}:
|
|
28
|
+
`}function yo(e,t){return`[]<${e}>{${t}}:
|
|
29
|
+
`}function is(e,t){return t.map(Z).join(e)}function jd(e){if(!Array.isArray(e)||e.length===0)throw P(0,"TOONL header requires fields");return e.map(t=>{let n;try{[n]=he(String(t),0)}catch(r){throw mt(r)}if(n==="")throw P(0,"TOONL header requires fields");return n})}function wo(e,t){return e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r])}function bo(e){if(e!==void 0&&(!Number.isInteger(e)||e<=0))throw P(0,"TOONL continuation cadence must be positive")}function Ud(e,t,n){return e.continuationEveryRows!==void 0&&t>=e.continuationEveryRows||e.continuationEveryBytes!==void 0&&n>=e.continuationEveryBytes}function _o(e){if(e===null||typeof e!="object"||Array.isArray(e))throw P(0,"TOONL output requires object rows");let t=Object.keys(e);if(t.length===0)throw P(0,"TOONL output requires object rows");if(t.some(n=>!Ut(e[n])))throw P(0,"TOONL rows must be flat objects");return t}function Fd(e){return JSON.stringify([...e].sort())}function Ro(e,t){let n=Fd(e),r=t.get(n);return r!==void 0?r:(t.set(n,e),e)}function On({delimiter:e=I,trailer:t=!0,continuationEveryRows:n,continuationEveryBytes:r}={}){Md(e),bo(n),bo(r);let s=null,i="",o=new Map,a=0,c=0,u=0,l=new Map,d=!1,f={continuationEveryRows:n,continuationEveryBytes:r},h=()=>s===null||!t?"":`[=${a}]
|
|
30
|
+
`,g=()=>Ud(f,c,u)?(c=0,u=0,ho(e,i,!0)):"",m=p=>{xo(p,0);let w=l.get(p);if(w===void 0){if(l.size>=ko)throw P(0,"too many tagged lanes");w={fields:null,fieldsByShape:new Map},l.set(p,w)}return w};return{push(p){if(d)throw P(0,"TOONL encoder is closed");let w=Ro(_o(p),o),y="";(s===null||s.length!==w.length||s.some((v,N)=>v!==w[N]))&&(y+=h(),s=w,i=is(e,s),a=0,c=0,u=0,y+=ho(e,i));let x=s.map(v=>se(p[v],e));y+=g();let E=`${x.join(e)}
|
|
31
|
+
`;return y+=E,a+=1,c+=1,u+=E.length,y},declareLane(p,w){if(d)throw P(0,"TOONL encoder is closed");let y=jd(w),x=is(I,y),E=m(p);return wo(E.fields,y)?"":(E.fields=y,yo(p,x))},pushTagged(p,w){if(d)throw P(0,"TOONL encoder is closed");let y=m(p),x=Ro(_o(w),y.fieldsByShape),E=is(I,x),v=x.map(M=>se(w[M],I)),N="";return wo(y.fields,x)||(y.fields=x,N+=yo(p,E)),`${N}${p}:${v.join(I)}
|
|
32
|
+
`},end(){return d?"":(d=!0,h())}}}var So,ko,Eo,vb,Pb,To=S(()=>{jt();qt();Wr();So=[I,"|"," "],ko=8,Eo=/^[A-Za-z0-9_-]+$/,vb=new TextEncoder,Pb=new TextDecoder});var oe=S(()=>{jt();qt();qt();po();To()});function ye(e){return O(e,{keyedMapCollapse:!0})}var Gd,qd,t_,Dn=S(()=>{oe();De();Gd=[{id:"memory.config",plugin:"memory",legacyPath:".red/memory/config.json",toonPath:".red/memory/config.toon",kind:"toon"}],qd=[{id:"dev.afk-history",plugin:"dev",legacyPath:".red/state/afk-history.jsonl",toonPath:".red/state/afk-history.toonl",kind:"toonl"},{id:"dev.agent-log",plugin:"dev",legacyPath:".red/tmp/agent.log.jsonl",toonPath:".red/tmp/agent.log.toonl",kind:"toonl"},{id:"dev.supervisor-firehose",plugin:"dev",legacyPath:".red/tmp/afk-supervisor.log.jsonl",toonPath:".red/tmp/afk-supervisor.log.jsonl",kind:"toonl",migration:"sniff-read"},{id:"dev.code-understanding-bench-runs",plugin:"dev",legacyPath:".red/tmp/bench/code-understanding/runs.jsonl",toonPath:".red/tmp/bench/code-understanding/runs.toonl",kind:"toonl"},{id:"dev.attempt-state",plugin:"dev",legacyPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.json",toonPath:".red/tmp/{workers,go-workers,scout-workers}/*/*/afk.state.json",kind:"toon"},{id:"dev.statusline-count-cache",plugin:"dev",legacyPath:".red/tmp/statusline-cache.json",toonPath:".red/tmp/statusline-cache.json",kind:"toon"},{id:"dev.statusline-repo-cache",plugin:"dev",legacyPath:".red/tmp/statusline-repo-cache.json",toonPath:".red/tmp/statusline-repo-cache.json",kind:"toon"},{id:"dev.rsp-resident-registry",plugin:"dev",legacyPath:".red/state/rsp/rsp-resident.pid.json",toonPath:".red/state/rsp/rsp-resident.pid.json",kind:"toon"},{id:"dev.rsp-status-summary",plugin:"dev",legacyPath:".red/state/rsp/rsp-status-summary.json",toonPath:".red/state/rsp/rsp-status-summary.json",kind:"toon"},{id:"dev.rsp-wait-registry",plugin:"dev",legacyPath:".red/tmp/waits/*.json",toonPath:".red/tmp/waits/*.json",kind:"toon"}],t_=[...Gd,...qd]});function as(e,t,n=Po){let r=Math.max(0,Math.floor(e)),s=n in Oo?n:Po,i=Oo[s],o=t?Math.floor(r*(1-.25)):null,a=t?Math.ceil(r*(1+.25)):null;return{tokens_saved:r,tokens_saved_estimated:t,token_estimate_range_pct:t?.25:null,tokens_saved_low:o,tokens_saved_high:a,dollars_saved_estimate_usd:os(r,i),dollars_saved_low_usd:o==null?null:os(o,i),dollars_saved_high_usd:a==null?null:os(a,i),pricing_model_family:s,pricing_input_usd_per_million_tokens:i,pricing_note:Hd}}function os(e,t){return Wd(Math.max(0,e)/1e6*t)}function Jt(e){return`$${e.toFixed(6)}`}function Wd(e){return Math.round(e*1e6)/1e6}var Po,Oo,Hd,cs=S(()=>{"use strict";Po="gpt-5",Oo={"gpt-5":1.25,"gpt-5-mini":.25,"gpt-5-nano":.05,"gpt-4.1":2,"gpt-4.1-mini":.4,"gpt-4o":2.5,"gpt-4o-mini":.15},Hd="estimate derived from byte-based token estimate when token counts are estimated"});import{existsSync as Vd,readFileSync as o_}from"node:fs";import{dirname as Kd,join as zd}from"node:path";function Do(e,t){let n=e;for(let r=0;r<16;r++){let s=zd(n,t);if(Vd(s))return s;let i=Kd(n);if(i===n)break;n=i}return null}function Yd(e){let t=e.indexOf(" #");return(t>=0?e.slice(0,t):e).trim()}function In(e,t){let n=[];for(let r of e.split(`
|
|
33
|
+
`)){let s=r.replace(/\r$/,""),i=s.trim();if(!i||i.startsWith("#"))continue;let o=s.indexOf(":");if(o<0)continue;let a=s.length-s.trimStart().length,c=s.slice(0,o).trim();if(!c)continue;let u=s.slice(o+1).trim();for(;n.length&&n[n.length-1].indent>=a;)n.pop();if(n.push({indent:a,key:c}),u&&n.map(d=>d.key).join(".")===t)return Yd(u)}}var Io=S(()=>{});import{createConnection as Qd}from"node:net";async function yt(e,t){let n=e.timeoutMs??1e3;return await new Promise((r,s)=>{let i=Qd(e.socketPath),o=!1,a="",c=setTimeout(()=>{u(()=>s(new Error("resident rsp server timed out"))),i.destroy()},n);function u(l){o||(o=!0,clearTimeout(c),l())}i.on("connect",()=>{i.write(`${JSON.stringify(t)}
|
|
29
34
|
`)}),i.on("data",l=>{a+=l.toString("utf8");let d=a.indexOf(`
|
|
30
|
-
`);if(d<0)return;let f=a.slice(0,d);u(()=>{try{r(JSON.parse(f))}catch(
|
|
31
|
-
`,{encoding:"utf8",mode:384}),await
|
|
35
|
+
`);if(d<0)return;let f=a.slice(0,d);u(()=>{try{r(JSON.parse(f))}catch(h){s(h)}}),i.end()}),i.on("error",l=>u(()=>s(l))),i.on("close",()=>{o||u(()=>s(new Error("resident rsp server closed without response")))})})}var us=S(()=>{});import{createHash as Xd,randomUUID as Bo}from"node:crypto";import{spawn as Lo}from"node:child_process";import{constants as ls}from"node:fs";import{readFileSync as Zd}from"node:fs";import{mkdir as $n,open as ef,readFile as Mo,rename as tf,rm as ae,stat as nf,writeFile as rf}from"node:fs/promises";import{tmpdir as sf}from"node:os";import{dirname as Ie,join as V,resolve as Cn}from"node:path";import{fileURLToPath as jo}from"node:url";function $e(e){let t=yf(e)??Cn(e),n=hf(t),r=W(t);return{rootDir:t,socketPath:V(n,"rsp.sock"),pidPath:V(n,"rsp.pid"),lockPath:V(n,"rsp.lock"),wakeLockPath:V(t,".red","tmp","rsp.wake.lock"),summaryPath:V(r,"rsp-status-summary.json"),registryPath:V(r,"rsp-resident.pid.json")}}async function Nn(e,t){if(await $n(Ie(e.socketPath),{recursive:!0,mode:448}),await No(e.socketPath,t))return;await Co(e,t);let n=await Jo(e.lockPath);if(n)try{if(await No(e.socketPath,t))return;await Co(e,t),await uf(e.socketPath);let r=lf(e,t);await $o(e.socketPath,r);return}finally{await n.close(),await ae(e.lockPath,{force:!0})}await $o(e.socketPath)}async function We(e,t=200){try{return await Fo(e,t)!=null}catch{return!1}}async function Fo(e,t=200){let n=await yt({socketPath:e,timeoutMs:t},{id:Bo(),op:"ping"});return n.ok?Ko(n.value)?{version:Rf(n.value.version)}:{}:null}async function An(e,t){if(await $n(Ie(e.socketPath),{recursive:!0,mode:448}),await We(e.socketPath,50))return!1;let n=await Jo(e.wakeLockPath);if(!n)return!1;await n.close();let[r,s]=Wo(t);return Lo(r,[...s,"warm-resident","--socket",e.socketPath,"--pid-file",e.pidPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--ephemeral-ttl-hours",String(t.ephemeralTtlHours??6),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--idle-ms",String(t.idleMs??3e5),"--resident-version",t.clientVersion??"0.0.0-dev","--registry",e.registryPath,"--wake-lock",e.wakeLockPath],{cwd:e.rootDir,detached:!0,stdio:"ignore",env:{...process.env,RSP_RESIDENT_WARMER:"1"}}).unref(),!0}async function Go(e,t){try{await Nn(e,t)}finally{await ae(e.wakeLockPath,{force:!0})}}async function Wt(e){try{let t=mf(await Mo(e,"utf8"));return Sf(t)?t:null}catch{return null}}async function Bn(e,t){let n={version:Uo,pid:t.pid??process.pid,socket_path:t.socket_path,store_uri:t.store_uri,resident_version:t.resident_version,started_at:t.started_at??new Date().toISOString()};await $n(Ie(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await rf(r,`${O(n)}
|
|
36
|
+
`,{encoding:"utf8",mode:384}),await tf(r,e)}async function Ln(e,t=process.pid){try{let n=await Wt(e);if(n&&n.pid!==t)return;await ae(e,{force:!0})}catch{}}async function Ht(e){let t=await Wt(e.registryPath);if(!t)try{return await Mo(e.registryPath,"utf8"),{registry_path:e.registryPath,state:"invalid"}}catch{return{registry_path:e.registryPath,state:"missing"}}if(!wt(t.pid))return{registry_path:e.registryPath,state:"registered-dead",entry:t};let n=await We(t.socket_path,100);return n&&await gf(t.store_uri)?{registry_path:e.registryPath,state:"registered-alive-store-missing",entry:t}:{registry_path:e.registryPath,state:n?"registered-alive-socket-healthy":"registered-alive-socket-dead",entry:t}}async function qo(e){let t=await Ht(e);return t.state==="registered-dead"||t.state==="invalid"?(await ae(e.registryPath,{force:!0}),await Ht(e)):(t.state==="registered-alive-socket-dead"||t.state==="registered-alive-store-missing")&&t.entry?(await Ho(t.entry.pid),await ae(e.registryPath,{force:!0}),await ae(t.entry.socket_path,{force:!0}),await Ht(e)):t}async function $o(e,t){let n=Date.now()+cf(),r;for(;Date.now()<n;){if(await We(e))return;if(t){let s=t.spawnError();if(s)throw new Error(ds("resident rsp server spawn failed",t,s));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(ds("resident rsp server exited before ready",t))}await new Promise(s=>setTimeout(s,50))}throw r instanceof Error?r:new Error(t?ds("resident rsp server did not start",t):"resident rsp server did not start")}function cf(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:af}async function uf(e){await ae(e,{force:!0})}async function Jo(e){await $n(Ie(e),{recursive:!0,mode:448});try{return await ef(e,ls.O_CREAT|ls.O_EXCL|ls.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function lf(e,t){let[n,r]=Wo(t),s=process.env.RSP_DEBUG==="1",i,o="",a=Lo(n,[...r,"server","--socket",e.socketPath,"--pid-file",e.pidPath,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--ephemeral-ttl-hours",String(t.ephemeralTtlHours??6),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays??90),"--telemetry-byte-budget",String(t.telemetryByteBudget??t.byteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs??3e4),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs??2e3),"--idle-ms",String(t.idleMs??3e5),"--resident-version",t.clientVersion??"0.0.0-dev","--registry",e.registryPath],{cwd:e.rootDir,detached:!0,stdio:s?["ignore","ignore","pipe"]:"ignore",env:{...process.env,RSP_RESIDENT_SERVER:"1"}});return a.on("error",c=>{i=c}),s&&(a.stderr?.setEncoding("utf8"),a.stderr?.on("data",c=>{o=ff(`${o}${c}`,df)})),a.unref(),{child:a,stderrTail:()=>o,spawnError:()=>i}}function ds(e,t,n){let r=[e];n&&r.push(`error: ${n.message}`),t.child.exitCode!=null&&r.push(`exit code: ${t.child.exitCode}`),t.child.signalCode!=null&&r.push(`signal: ${t.child.signalCode}`);let s=t.stderrTail().trimEnd();return s&&r.push(`stderr tail:
|
|
32
37
|
${s}`),r.join(`
|
|
33
|
-
`)}function td(e,t){let n=Buffer.byteLength(e,"utf8");return n<=t?e:Buffer.from(e,"utf8").subarray(n-t).toString("utf8").replace(/^\uFFFD+/,"")}function nd(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return fe(t)}}async function Ki(e,t){try{let n=await At(e.registryPath);if(!n||n.socket_path!==e.socketPath||n.store_uri!==t.storeUri)return;if(!ct(n.pid)){await ne(e.registryPath,{force:!0});return}if(await Ue(n.socket_path,100))return;if(co(t.clientVersion,n.resident_version)&&(await rd(n.pid,1500),!ct(n.pid))){await ne(e.registryPath,{force:!0});return}await oo(n.pid),await ne(e.registryPath,{force:!0})}catch{}}function ct(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function oo(e){if(!ct(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!ct(e))return;await new Promise(n=>setTimeout(n,50))}try{process.kill(e,"SIGKILL")}catch{}}async function rd(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!ct(e))return;await new Promise(r=>setTimeout(r,50))}}async function sd(e){if(!e.startsWith("file://"))return!1;try{return await Wl(eo(e)),!1}catch(t){return t.code==="ENOENT"}}function ao(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?wn(process.argv[1]):eo(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function id(e){let t=Gl("sha256").update(e).digest("hex").slice(0,20),n=process.env.XDG_RUNTIME_DIR;if(n){let s=H(n,"red-skills",t);if(H(s,"rsp.sock").length<zl)return s}let r=typeof process.getuid=="function"?process.getuid():"nouid";return H(Kl(),`red-skills-${r}`,t)}function od(e){let t=wn(e);for(let n=0;n<32;n++){try{let s=Vr(H(t,".git"));if(s!=null)return ad(t,s)??t;if(Vr(H(t,".git","HEAD"))!=null||Vr(H(t,".red","config.yaml"))!=null)return t}catch{}let r=Te(t);if(r===t)return null;t=r}return null}function ad(e,t){let n=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!n)return null;let r=wn(e,n[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(r)?Te(Te(Te(r))):null}function Vr(e){try{return ql(e,"utf8")}catch{return null}}async function zi(e,t){let n=await no(e).catch(()=>null);return n?co(t.clientVersion,n.version)?(await cd(e,t.clientVersion),await fd(e),!1):!0:!1}async function cd(e,t){try{await at({socketPath:e,timeoutMs:200},{id:Qi(),op:"handover",clientVersion:t})}catch{}}function co(e,t){return!e||!t?!1:ud(e,t)>0}function ud(e,t){let n=Yi(e),r=Yi(t);return!n||!r?0:n.major-r.major||n.minor-r.minor||n.patch-r.patch}function Yi(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function uo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ld(e){return typeof e=="string"&&e.length>0?e:void 0}function dd(e){return uo(e)&&e.version===to&&Number.isInteger(e.pid)&&typeof e.socket_path=="string"&&typeof e.store_uri=="string"&&typeof e.resident_version=="string"&&typeof e.started_at=="string"}async function fd(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await Ue(e,50))return;await new Promise(n=>setTimeout(n,50))}}var zl,to,Yl,ed,En=S(()=>{te();Jr();zl=108,to=1,Yl=5e3;ed=8*1024});var ho={};C(ho,{DEFAULT_RSP_BYTE_BUDGET:()=>ye,DEFAULT_RSP_EPHEMERAL_TTL_HOURS:()=>he,DEFAULT_RSP_HEAVY_GIT_BYTE_THRESHOLD:()=>pe,DEFAULT_RSP_IDLE_MS:()=>vn,DEFAULT_RSP_STORE_PATH:()=>kn,DEFAULT_RSP_TELEMETRY_BYTE_BUDGET:()=>Tn,DEFAULT_RSP_TELEMETRY_DRAIN_INTERVAL_MS:()=>mo,DEFAULT_RSP_TELEMETRY_DRAIN_TIMEOUT_MS:()=>po,DEFAULT_RSP_TELEMETRY_TTL_DAYS:()=>xn,DEFAULT_RSP_TTL_DAYS:()=>ge,MIN_RSP_IDLE_MS:()=>go,resolveRspConfig:()=>we});import{readFileSync as md}from"node:fs";import{join as lo,resolve as fo}from"node:path";function we(e,t,n){let r=Hi(fo(e),lo(".red","config.yaml")),s=r?md(r,"utf8"):"",i=hn(s,"rsp.enabled")==="true",o=hn(s,"rsp.proxy.enabled")==="true",a=me(re(s,"rsp.ttlDays"),ge),c=me(Lt(t.RSP_EPHEMERAL_TTL_HOURS)??re(s,"rsp.ephemeralTtlHours"),he),u=me(re(s,"rsp.byteBudget"),ye),l=me(re(s,"rsp.telemetryTtlDays"),xn),d=me(re(s,"rsp.telemetryByteBudget")??re(s,"rsp.byteBudget"),Tn),f=me(Lt(t.RSP_TELEMETRY_DRAIN_INTERVAL_MS)??re(s,"rsp.telemetryDrainIntervalMs"),mo),y=me(Lt(t.RSP_TELEMETRY_DRAIN_TIMEOUT_MS)??re(s,"rsp.telemetryDrainTimeoutMs"),po),g=pd(Lt(t.RSP_IDLE_MS)??re(s,"rsp.idleMs"),vn,go),m=me(Lt(t.RSP_HEAVY_GIT_BYTE_THRESHOLD)??re(s,"rsp.heavyGitByteThreshold"),pe),p=ve(e).rootDir,E=n??t.RSP_STORE_URI??`file://${lo(fo(p),kn)}`;return{enabled:i,proxyEnabled:o,storeUri:E,ttlDays:a,ephemeralTtlHours:c,byteBudget:u,telemetryTtlDays:l,telemetryByteBudget:d,telemetryDrainIntervalMs:f,telemetryDrainTimeoutMs:y,idleMs:g,heavyGitByteThreshold:m}}function re(e,t){let n=hn(e,t);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function me(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function pd(e,t,n){let r=me(e,t);return Math.max(r,n)}function Lt(e){if(e==null||e.trim()==="")return;let t=Number(e);return Number.isFinite(t)?t:void 0}var pe,kn,ge,he,ye,xn,Tn,mo,po,vn,go,se=S(()=>{"use strict";Wi();En();pe=8*1024,kn=".red/tmp/red-skills.rdb",ge=7,he=6,ye=64*1024*1024,xn=90,Tn=4*1024*1024,mo=3e4,po=2e3,vn=5*6e4,go=5e3});var yo=S(()=>{"use strict";Jr()});var jt={};C(jt,{ResidentRspElisionStore:()=>Mt,ensureResidentServer:()=>bn,kickResidentServer:()=>_n,pingResident:()=>Ue,readResidentRegistry:()=>At,removeResidentRegistry:()=>Sn,residentRegistryStatus:()=>Bt,resolveResidentPaths:()=>ve,sweepResidentRegistry:()=>so,warmResidentServer:()=>ro,writeResidentRegistry:()=>Rn});import{randomUUID as gd}from"node:crypto";function wo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Mt,Fe=S(()=>{"use strict";yo();En();Mt=class{constructor(t,n,r={}){this.paths=t;this.config=n;this.opts=r}metrics;lastResponseMetrics(){return this.metrics}async mint(t,n){let s=(await this.request({op:"mint",original:Buffer.from(t).toString("base64"),meta:n})).handle;if(!s?.startsWith("el:"))throw new Error("resident rsp returned invalid handle");return s}async get(t){let n=await this.request({op:"get",handle:t});return n?wo(n)&&n.status==="expired"?n:!wo(n)||typeof n.original!="string"?null:{...n,original:Buffer.from(n.original,"base64")}:null}async stats(){return await this.request({op:"stats"})}async accountingStats(t){return await this.request({op:"accounting-stats",byteBudget:t})}async telemetryStats(t){return await this.request({op:"telemetry-stats",sinceDays:t})}async telemetryGains(t){return await this.request({op:"telemetry-gains",sinceDays:t})}async memory(t,n){return await this.request({op:"memory",action:t,payload:n})}async close(){}async request(t){this.opts.ensureResident!==!1&&await bn(this.paths,this.config);let n=await at(this.paths,{...t,id:gd()});if(!n.ok)throw new Error(n.error);return this.metrics={storeOpenCount:n.storeOpenCount,storeElapsedMs:n.storeElapsedMs},n.value}}});var Jt={};C(Jt,{DEFAULT_RSP_BYTE_BUDGET:()=>ye,DEFAULT_RSP_EPHEMERAL_TTL_HOURS:()=>he,DEFAULT_RSP_TTL_DAYS:()=>ge,RSP_ELISION_COLLECTION:()=>G,RspElisionStore:()=>Gt,ensureReddbBinaryFromWarmCache:()=>Io,storageClassForCommand:()=>qe});import{createHash as In}from"node:crypto";import{spawnSync as Ft}from"node:child_process";import{existsSync as hd}from"node:fs";import{mkdir as yd,readFile as es,readdir as vo,rename as wd,writeFile as bd}from"node:fs/promises";import{homedir as _d}from"node:os";import{basename as ts,dirname as Oo,join as lt}from"node:path";import{fileURLToPath as Rd}from"node:url";import{gunzipSync as Sd,gzipSync as Ed}from"node:zlib";function bo(e,t){return`el:${In("sha256").update("rsp-elision-v1\0").update(e).update("\0").update(JSON.stringify({command:t.command,loss:t.loss})).digest("hex").slice(0,12)}`}function be(e){return`record:${e.slice(3)}`}function Ge(e){return`expired:${e.slice(3)}`}function Kr(){return"index:v1"}function kd(e){return`blob:${e}`}function qe(e){let t=e.trim().split(/\s+/).filter(Boolean),n=t[0]??"";if(n==="cat")return"derivable";if(n==="git"){let r=t[1]??"";return r==="log"||r==="diff"||r==="blame"||r==="show"?"derivable":$n(t)?"re-executable":"ephemeral"}return"ephemeral"}function Ut(e){return Cn(e.storage_class)?e.storage_class:qe(e.command)}function xd(e){return Cn(e.storage_class)?e.storage_class:qe(e.command)}function _o(e){let t=Dd(),n={derivable:new Set,"re-executable":new Set,ephemeral:new Set};for(let r of e){let s=xd(r);if(t[s].records+=1,t[s].raw_bytes+=r.raw_bytes??r.bytes,r.blob_key){if(n[s].has(r.blob_key))continue;n[s].add(r.blob_key)}t[s].bytes+=r.bytes}return t}function Ro(e,t,n,r){let s=t==="ephemeral"?r*60*60*1e3:n*24*60*60*1e3;return new Date(e.getTime()+s).toISOString()}function ut(e){let t=0,n=new Set;for(let r of e){if(r.blob_key){if(n.has(r.blob_key))continue;n.add(r.blob_key)}t+=r.bytes}return t}function So(e,t){let n=process.cwd(),r=Ft("git",["rev-parse","--is-inside-work-tree"],{cwd:n,encoding:"utf8"});if(r.status!==0||r.stdout.trim()!=="true")return null;let s=Ft("git",["hash-object","-w","--stdin"],{cwd:n,input:e,encoding:"buffer"});if(s.status!==0)return null;let i=s.stdout.toString("utf8").trim();return/^[0-9a-f]{40,64}$/.test(i)?{kind:"git-blob",command:t,cwd:n,object_ids:[i],working_tree_fingerprint:Td(n),original_bytes:e.length}:null}function Td(e){let t=zr(e,["rev-parse","HEAD"])||"unborn",n=zr(e,["write-tree"])||"no-index",r=zr(e,["status","--porcelain=v1","-z"])||"";return In("sha256").update(t).update("\0").update(n).update("\0").update(r).digest("hex")}function zr(e,t){let n=Ft("git",t,{cwd:e,encoding:"utf8"});return n.status===0?n.stdout.trim():null}function Eo(e,t){let n=t.trim().split(/\s+/).filter(Boolean);if(!$n(n))return null;let r=Po(process.cwd(),n,e.length);return!r||ft(r)!==ft(e)?null:{kind:"command",command:t,cwd:process.cwd(),argv:n,original_bytes:e.length,content_hash:ft(e)}}function $n(e){return e[0]==="git"?e[1]==="status"?!0:e[1]!=="branch"?!1:e.length===2||e.slice(2).every(t=>/^-[avvr]+$/.test(t)):!1}function ft(e){return In("sha256").update("rsp-reexecutable-content-v1\0").update(e).digest("hex")}function ko(e,t,n,r){return t?Buffer.byteLength(JSON.stringify(t),"utf8"):n?Buffer.byteLength(JSON.stringify(n),"utf8"):r?r.stored_bytes:e.length}function Yr(e){return typeof e.stored_bytes=="number"?e.stored_bytes:e.derivation_recipe?Buffer.byteLength(JSON.stringify(e.derivation_recipe),"utf8"):e.reexecution_recipe?Buffer.byteLength(JSON.stringify(e.reexecution_recipe),"utf8"):e.blob_key?typeof e.stored_bytes=="number"?e.stored_bytes:0:e.original_bytes}function xo(e,t,n){let r=Ed(e);return{key:kd(t),content_hash:t,encoding:"gzip+base64",bytes:r.toString("base64"),original_bytes:e.length,stored_bytes:r.length,created_at:n}}function vd(e){try{let t=Sd(Buffer.from(e.bytes,"base64"));return t.length===e.original_bytes?t:null}catch{return null}}function Od(e){let t=e.object_ids[0];if(!t)return null;let n=Ft("git",["cat-file","-p",t],{cwd:e.cwd,encoding:"buffer",maxBuffer:Math.max(e.original_bytes+1024,1024*1024)});return n.status!==0||n.stdout.length!==e.original_bytes?null:n.stdout}function Pd(e){if(!$n(e.argv))return null;let t=Po(e.cwd,e.argv,e.original_bytes);return t?ft(t)===e.content_hash?t:Buffer.concat([Buffer.from(`reconstructed after state moved - current snapshot follows
|
|
34
|
-
`,"utf8"),t]):null}function
|
|
35
|
-
`,"utf8"),await wd(n,e)}function To(){return{version:1,records:{},blobs:{},tombstones:{},index:{version:1,records:[]}}}function qd(e){return W(e)&&e.version===1&&W(e.records)&&Object.values(e.records).every(dt)&&(e.blobs===void 0||W(e.blobs)&&Object.values(e.blobs).every(Zr))&&W(e.tombstones)&&Object.values(e.tombstones).every(Dn)&&Xr(e.index)}function Jd(e){if(!e.startsWith("file://"))throw new Error("rsp elision store requires a file:// URI");return Rd(e)}var G,Gt,Je=S(()=>{"use strict";Tr();se();G="rsp_elisions_v1",Gt=class e{constructor(t,n){this.opts=n;this.path=t}document;db;path;dirty=!1;static async open(t){if(process.env.RSP_FAIL_IF_STORE_OPEN==="1"&&!t.allowResidentOpen)throw new Error("RSP_FAIL_IF_STORE_OPEN blocked store open");let n=Jd(t.uri),r=await Ud(n),s=new e(r,{uri:t.uri,ttlDays:Qr(t.ttlDays,ge),ephemeralTtlHours:Qr(t.ephemeralTtlHours,he),byteBudget:Qr(t.byteBudget,ye),now:t.now??(()=>new Date)});return Do(r)?(await Io(),s.db=await mn(`file://${r}`),await s.ensureRedDbCollections(),await s.ensureRedDbStore()):s.document=await jd(s.path),s}async close(){await this.db?.close()}redDb(){return this.db}async mint(t,n){if(this.db)return await this.mintRedDb(t,n);let r=Buffer.from(t),s=this.opts.now(),i=s.toISOString(),o=bo(r,n),a=be(o),c=qe(n.command),u=c==="derivable"?So(r,n.command):null,l=c==="re-executable"?Eo(r,n.command):null,d=c==="derivable"&&!u||c==="re-executable"&&!l?"ephemeral":c,f=Ro(s,d,this.opts.ttlDays,this.opts.ephemeralTtlHours),y=ft(r),g=d==="ephemeral"?xo(r,y,i):null,m=ko(r,u,l,g);g&&!this.document.blobs[g.key]&&(this.document.blobs[g.key]=g,this.dirty=!0);let p={collection:G,handle:o,original_bytes:r.length,stored_bytes:m,command:n.command,created_at:i,expires_at:f,loss:n.loss,storage_class:d,content_hash:y,...u?{derivation_recipe:u}:l?{reexecution_recipe:l}:{blob_key:g?.key}};return delete this.document.tombstones[Ge(o)],this.document.records[a]=p,this.upsertIndex({handle:o,key:a,bytes:m,raw_bytes:r.length,command:n.command,created_at:i,expires_at:f,storage_class:d,blob_key:g?.key}),this.prune(),await this.flush(),o}async get(t){if(this.db)return await this.getRedDb(t);if(!qt(t))return null;let n=this.tombstone(t);if(n)return n;let r=this.document.records[be(t)];if(!dt(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let i={status:"expired",expired_at:r.expires_at,command:r.command};return this.expireEntry({handle:r.handle,key:be(r.handle),bytes:Yr(r),raw_bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at,storage_class:Ut(r),blob_key:r.blob_key},r.expires_at),await this.flush(),i}let s=await this.readOriginal(r);return!s&&(r.derivation_recipe||r.reexecution_recipe)?{status:"expired",expired_at:r.expires_at,command:r.command}:s?{collection:G,handle:r.handle,original:s,command:r.command,created_at:r.created_at,loss:r.loss,storage_class:Ut(r)}:null}async stats(){if(this.db)return await this.statsRedDb();this.prune(),await this.flush();let n=this.readIndex().records;return{records:n.length,bytes:ut(n),oldest:n.reduce((r,s)=>r==null||s.created_at<r?s.created_at:r,null),budget:this.opts.byteBudget,storage_classes:_o(n)}}readIndex(){return this.document.index}writeIndex(t){this.document.index=t}upsertIndex(t){let r=this.readIndex().records.filter(s=>s.handle!==t.handle);r.push(t),this.writeIndex({version:1,records:r}),this.dirty=!0}prune(){let t=this.opts.now().getTime(),n=new Date(t).toISOString(),r=this.readIndex(),s=[];for(let o of r.records)Date.parse(o.expires_at)<=t?this.expireEntry(o,o.expires_at):s.push(o);let i=ut(s);for(s.sort((o,a)=>o.created_at.localeCompare(a.created_at));i>this.opts.byteBudget&&s.length>0;){let o=s.shift();this.expireEntry(o,n),i=ut(s)}s.length<r.records.length&&this.writeIndex({version:1,records:s}),this.deleteUnreferencedLocalBlobs(s)}expireEntry(t,n){delete this.document.records[t.key],this.document.tombstones[Ge(t.handle)]={status:"expired",expired_at:n,command:t.command},this.dirty=!0}tombstone(t){let n=this.document.tombstones[Ge(t)];return Dn(n)?n:null}async readOriginal(t){if(t.original)return Buffer.from(t.original,"base64");if(t.derivation_recipe)return Od(t.derivation_recipe);if(t.reexecution_recipe)return Pd(t.reexecution_recipe);if(t.blob_key){let n=this.db?await this.kvGet(t.blob_key):this.document.blobs[t.blob_key];return Zr(n)?vd(n):null}return null}deleteUnreferencedLocalBlobs(t){let n=new Set(t.map(r=>r.blob_key).filter(r=>typeof r=="string"));for(let r of Object.keys(this.document.blobs))n.has(r)||(delete this.document.blobs[r],this.dirty=!0)}async flush(){this.dirty&&(await $o(this.path,this.document),this.dirty=!1)}kv(){if(!this.db)throw new Error("rsp RedDB store is not open");return this.db.kv(G)}async kvGet(t){let n=await this.kv().get(t);if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}async ensureRedDbStore(){let t=await this.readRedDbIndex();await this.writeRedDbIndex(t)}async ensureRedDbCollections(){if(!this.db)throw new Error("rsp RedDB store is not open");let t=(await this.db.list()).find(r=>r.name===G);if(!t){await this.db.query(`CREATE KV IF NOT EXISTS ${G}`);return}if(t.model==="kv")return;if(t.model!=="table")throw new Error(`cannot self-heal elision collection ${G}: unsupported model ${t.model}`);let n=await this.readLegacyElisionTableRows();await this.db.query(`DROP TABLE ${G}`),await this.db.query(`CREATE KV IF NOT EXISTS ${G}`);for(let r of n)await this.kv().put(r.key,r.value);await this.ensureMigratedRedDbIndex(n)}async readLegacyElisionTableRows(){if(!this.db)throw new Error("rsp RedDB store is not open");let t=await this.db.query(`SELECT * FROM ${G}`),n=[];for(let r of t.rows){let s=Cd(r);s&&n.push(s)}return n}async ensureMigratedRedDbIndex(t){if(t.some(s=>s.key===Kr()&&Xr(Pn(s.value))))return;let r=t.map(s=>{let i=Pn(s.value);return dt(i)?{handle:i.handle,key:be(i.handle),bytes:Yr(i),raw_bytes:i.original_bytes,command:i.command,created_at:i.created_at,expires_at:i.expires_at,storage_class:Ut(i),blob_key:i.blob_key}:null}).filter(s=>s!=null);await this.writeRedDbIndex({version:1,records:r})}async mintRedDb(t,n){let r=Buffer.from(t),s=this.opts.now(),i=s.toISOString(),o=bo(r,n),a=be(o),c=qe(n.command),u=c==="derivable"?So(r,n.command):null,l=c==="re-executable"?Eo(r,n.command):null,d=c==="derivable"&&!u||c==="re-executable"&&!l?"ephemeral":c,f=Ro(s,d,this.opts.ttlDays,this.opts.ephemeralTtlHours),y=ft(r),g=d==="ephemeral"?xo(r,y,i):null,m=ko(r,u,l,g);g&&!Zr(await this.kvGet(g.key))&&await this.kv().put(g.key,g);let p={collection:G,handle:o,original_bytes:r.length,stored_bytes:m,command:n.command,created_at:i,expires_at:f,loss:n.loss,storage_class:d,content_hash:y,...u?{derivation_recipe:u}:l?{reexecution_recipe:l}:{blob_key:g?.key}};await this.kv().delete(Ge(o)),await this.kv().put(a,p);let w=(await this.readRedDbIndex()).records.filter(v=>v.handle!==o);return w.push({handle:o,key:a,bytes:m,raw_bytes:r.length,command:n.command,created_at:i,expires_at:f,storage_class:d,blob_key:g?.key}),await this.pruneRedDb({version:1,records:w},!0),await this.assertRedDbMintPersisted(o,m),o}async getRedDb(t){if(!qt(t))return null;let n=await this.kvGet(Ge(t));if(Dn(n))return n;let r=await this.kvGet(be(t));if(!dt(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let i={status:"expired",expired_at:r.expires_at,command:r.command};return await this.expireRedDbEntry({handle:r.handle,key:be(r.handle),bytes:Yr(r),raw_bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at,storage_class:Ut(r),blob_key:r.blob_key},r.expires_at),i}let s=await this.readOriginal(r);return!s&&(r.derivation_recipe||r.reexecution_recipe)?{status:"expired",expired_at:r.expires_at,command:r.command}:s?{collection:G,handle:r.handle,original:s,command:r.command,created_at:r.created_at,loss:r.loss,storage_class:Ut(r)}:null}async statsRedDb(){let t=await this.pruneRedDb(await this.readRedDbIndex());return{records:t.records.length,bytes:ut(t.records),oldest:t.records.reduce((n,r)=>n==null||r.created_at<n?r.created_at:n,null),budget:this.opts.byteBudget,storage_classes:_o(t.records)}}async memory(t,n){if(!this.db)throw new Error("resident memory operations require the shared RedDB store");if(await this.ensureMemoryGraphStore(),t==="recall"){let r=Id(n);return await this.memoryRecallRedDb(r.query,r.limit)}if(t==="ingest"){let r=$d(n);return await this.memoryIngestRedDb(r)}throw new Error(`unsupported memory action: ${t}`)}async ensureMemoryGraphStore(){if(!this.db)throw new Error("rsp RedDB store is not open");await this.db.execute("CREATE GRAPH IF NOT EXISTS memory_nodes"),await this.db.execute("CREATE GRAPH IF NOT EXISTS memory_edges")}async memoryIngestRedDb(t){if(!this.db)throw new Error("rsp RedDB store is not open");let n=await Nd(t.cwd,t.maxFiles??200,t.ignore??[]),r=0;for(let s of n){let o=(await es(s,"utf8").catch(()=>"")).trim();if(!o)continue;let a=ts(s),c=In("sha256").update("resident-memory-v1\0").update(s).update("\0").update(o).digest("hex");if(await this.db.kv("memory_kv").get(`resident-node-hash:${c}`)!=null)continue;let u=Date.now(),l={title:a,content:o,source:s,confidence:"EXTRACTED",hash:c,project:"default",scope:"project",importance:1,tier:"durable",provenance_tier:"oracle",created_at:u,updated_at:u,accessed_at:u,access_count:0,provenance:{source_kind:"system",writer:"rsp-resident",confidence:"EXTRACTED",evidence:[s],created_at:u,updated_at:u}},d=await this.db.query("INSERT INTO memory_nodes NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *",a,"concept",c,l),f=Number(d.rows[0]?.red_entity_id??d.rows[0]?.rid);Number.isFinite(f)&&await this.db.kv("memory_kv").put(`resident-node-hash:${c}`,f),r+=1}return{files:n.length,nodes:r,edges:0,docs:n.length,added:r,updated:0,skipped:n.length-r,stale:0,semantic:{enabled:!1,nodes:0,edges:0,token_cost:{input:0,output:0}},durationMs:0}}async memoryRecallRedDb(t,n){if(!this.db)throw new Error("rsp RedDB store is not open");let r=await this.db.query("SELECT * FROM memory_nodes"),s=t.toLowerCase().split(/\s+/).filter(Boolean),i=r.rows.map(o=>Bd(o,s)).filter(o=>o!=null).sort((o,a)=>a.score-o.score).slice(0,Math.max(1,Math.min(100,n)));return{hits:i,context_md:i.map(o=>`- memory_nodes:${o.rid} ${o.label}: ${o.excerpt}`).join(`
|
|
36
|
-
|
|
37
|
-
`,{encoding:"utf8",mode:384})}catch{}}function
|
|
38
|
-
|
|
39
|
-
${s}`,"utf8")}await jo(t,{force:!0})}}function nf(e){try{return Vd(e,"utf8")}catch{return""}}async function Fo(e){let t="";for(let n=0;n<5;n++){let r=await zd(e,"utf8").catch(()=>"");if(r===t)return r;t=r,await new Promise(s=>setTimeout(s,2))}return t}function os(e){try{let t=JSON.parse(e);return!qo(t)||t.collection!==V&&t.collection!==K&&t.collection!==ie&&t.collection!==Pe?null:t}catch{return null}}async function Ln(e,t,n=new Date){let r=Number.isFinite(t)&&t>0?t:30,s=n.getTime()-r*24*60*60*1e3,i=await Go(e,s),o=(await Ht(e,K)).filter(R=>gt(R)>=s),a=i.filter(R=>I(R.event_type)!=="show"&&I(R.degradation_reason)===""),c=i.filter(R=>I(R.event_type)==="show"),u=i.filter(R=>I(R.degradation_reason)!==""),l=0,d=0,f=0,y=0,g=!1,m=new Map,p=new Map,E=[],w=0,v=0,x=0;for(let R of a){R.elided===!0&&l++;let D=_e(R.raw_bytes),h=_e(R.emitted_bytes),k=Math.max(0,D-h),Ze=Nn(R,"raw"),et=Nn(R,"emitted"),Y=Math.max(0,Ze.tokens-et.tokens);g||=(R.estimated===!0||Ze.estimated||et.estimated)&&Y>0,d+=D,f+=h,y+=Y;let J=He(R).slice(0,10);J&&m.set(J,(m.get(J)??0)+Y);let Me=I(R.command)||"unknown",Re=p.get(Me)??{command:Me,invocations:0,bytes_saved:0,tokens_saved:0};Re.invocations++,Re.bytes_saved+=k,Re.tokens_saved+=Y,p.set(Me,Re);let tt=Wt(R.wrapper_ms);tt!=null&&E.push(tt),w+=_e(R.store_open_count);let nt=Wt(R.store_elapsed_ms);nt!=null&&(v+=nt,x++)}let O=new Map,N=null;for(let R of u){let D=I(R.degradation_reason)||I(R.reason)||"unknown";O.set(D,(O.get(D)??0)+1);let h=He(R);(!N||h>N.timestamp)&&(N={timestamp:h,reason:D,command:I(R.command)||"unknown"})}let F=a.length+u.length,z=c.filter(R=>R.hit===!0).length,$=Gr(y,g),an=rf(o);return{window_days:r,empty:i.length===0,savings:{invocations:a.length,elided:l,raw_bytes:d,emitted_bytes:f,bytes_saved:Math.max(0,d-f),tokens_saved:y,tokens_saved_estimated:$.tokens_saved_estimated,token_estimate_range_pct:$.token_estimate_range_pct,tokens_saved_low:$.tokens_saved_low,tokens_saved_high:$.tokens_saved_high,dollars_saved_estimate_usd:$.dollars_saved_estimate_usd,dollars_saved_low_usd:$.dollars_saved_low_usd,dollars_saved_high_usd:$.dollars_saved_high_usd,pricing_model_family:$.pricing_model_family,pricing_input_usd_per_million_tokens:$.pricing_input_usd_per_million_tokens,pricing_note:$.pricing_note,daily_tokens_saved:[...m.entries()].sort(([R],[D])=>R.localeCompare(D)).map(([R,D])=>({date:R,tokens_saved:D})),top_commands:[...p.values()].sort((R,D)=>D.bytes_saved-R.bytes_saved||D.tokens_saved-R.tokens_saved||R.command.localeCompare(D.command))},health:{degradations:u.length,degradation_rate:F===0?0:u.length/F,show_total:c.length,show_hits:z,show_misses:Math.max(0,c.length-z),show_hit_rate:c.length===0?0:Oe(z/c.length),by_reason:[...O.entries()].sort((R,D)=>D[1]-R[1]||R[0].localeCompare(D[0])).map(([R,D])=>({reason:R,count:D})),most_recent:N},latency:{wrapper_ms_p50:pt(E,.5),wrapper_ms_p95:pt(E,.95),store_open_count_sum:w,store_elapsed_ms_sum:Oe(v),store_elapsed_ms_avg:x===0?null:Oe(v/x)},decisions:an}}function rf(e){let t=0,n=0,r=0,s=new Map;for(let i of e){let o=I(i.decision);if(o==="contributed"?t++:o==="failed-open"?r++:n++,o!=="contributed"){let a=I(i.reason)||"unknown";s.set(a,(s.get(a)??0)+1)}}return{seen:e.length,contributed:t,passed:n,failed_open:r,contribution_rate:e.length===0?0:Oe(t/e.length),top_pass_reasons:[...s.entries()].sort((i,o)=>o[1]-i[1]||i[0].localeCompare(o[0])).map(([i,o])=>({reason:i,count:o}))}}async function as(e,t,n=new Date){let s=(await Ht(e,V)).filter(i=>gt(i)<=n.getTime()||He(i)==="");return{records:s.length,bytes:s.reduce((i,o)=>i+Buffer.byteLength(JSON.stringify(o),"utf8"),0),oldest:s.reduce((i,o)=>{let a=He(o);return a&&(i==null||a<i)?a:i},null),budget:t,storage_classes:sf(s)}}async function cs(e,t,n=new Date){let r=Number.isFinite(t)&&t>0?t:28,s=n.toISOString(),i=new Date(n.getTime()-r*24*60*60*1e3).toISOString(),o=Date.parse(i),a=await Go(e,o),c=a.filter(h=>I(h.event_type)!=="show"&&I(h.degradation_reason)===""),u=a.filter(h=>I(h.degradation_reason)!==""),l=[...c,...u].map(gt).filter(h=>Number.isFinite(h)&&h>0),d=l.length===0?null:Math.min(...l),f=d==null?0:Math.max(1,Math.min(r,Math.ceil((n.getTime()-d)/pf()))),y=[],g=new Map,m=new Map,p=new Map,E=new Map,w=new Map,v=new Map,x=0,O=!1,N=0,F=null,z=0,$=0;for(let h of c){let k=He(h),Ze=k.slice(0,10),et=k.slice(0,16),Y=Ao(I(h.command)),J=Math.max(0,Nn(h,"raw").tokens-Nn(h,"emitted").tokens);x+=J,O||=h.estimated===!0&&J>0;let Me=Math.max(0,_e(h.raw_bytes)-_e(h.emitted_bytes)),Re=Wt(h.wrapper_ms);if(Re!=null){y.push(Re);let ui=g.get(Y)??[];ui.push(Re),g.set(Y,ui)}Ze&&m.set(Ze,(m.get(Ze)??0)+1),et&&p.set(et,(p.get(et)??0)+1);let tt=uf(k);tt&&E.set(tt,(E.get(tt)??0)+1);let nt=ff(k);nt&&w.set(nt,(w.get(nt)??0)+J);let cn=v.get(Y)??{command_family:Y,invocations:0,tokens_saved:0,bytes_saved:0};cn.invocations++,cn.tokens_saved+=J,cn.bytes_saved+=Me,v.set(Y,cn),h.elided===!0&&N++,(h.store_open_count!=null||h.store_elapsed_ms!=null)&&(z++,_e(h.store_open_count)>0&&$++),J>0&&(!F||J>F.tokens_saved||J===F.tokens_saved&&Me>F.bytes_saved)&&(F={timestamp:k,command_family:Y,tokens_saved:J,bytes_saved:Me})}let an=u.map(h=>({timestamp:He(h),command_family:Ao(I(h.command)),reason:I(h.degradation_reason)||I(h.reason)||"unknown"})).sort((h,k)=>h.timestamp.localeCompare(k.timestamp)),R=new Map;for(let h of an)R.set(h.reason,(R.get(h.reason)??0)+1);let D=[...p.entries()].sort((h,k)=>k[1]-h[1]||h[0].localeCompare(k[0]))[0];return{schema_version:"red.rsp.gains.v1",window:{requested_days:r,data_days:f,since:i,until:s,label:`window: ${r}d, data: ${f}d`,empty:c.length===0&&u.length===0,invocations:c.length,degradations:u.length},latency:{global:Bo(y),by_command_family:[...g.entries()].sort((h,k)=>k[1].length-h[1].length||h[0].localeCompare(k[0])).map(([h,k])=>({command_family:h,count:k.length,...Bo(k)}))},throughput:{requests_per_day:[...m.entries()].sort(([h],[k])=>h.localeCompare(k)).map(([h,k])=>({date:h,requests:k})),active_minute_avg:p.size===0?null:Oe([...p.values()].reduce((h,k)=>h+k,0)/p.size),peak_minute:D?{minute:D[0],requests:D[1]}:null,hour_weekday_heatmap:lf(E)},savings:{tokens:Gr(x,O),weekly_tokens_saved:mf(w),elision_rate:c.length===0?0:Oe(N/c.length),top_commands_by_tokens_saved:[...v.values()].sort((h,k)=>k.tokens_saved-h.tokens_saved||k.bytes_saved-h.bytes_saved||h.command_family.localeCompare(k.command_family)).slice(0,10),top_commands_by_invocation_count:[...v.values()].sort((h,k)=>k.invocations-h.invocations||k.tokens_saved-h.tokens_saved||h.command_family.localeCompare(k.command_family)).slice(0,10),single_biggest_elision:F},health:{degradation_timeline:an,degradations_by_reason:[...R.entries()].sort((h,k)=>k[1]-h[1]||h[0].localeCompare(k[0])).map(([h,k])=>({reason:h,count:k})),cold_boots:z===0?null:$,warm_hits:z===0?null:Math.max(0,z-$)}}}async function Go(e,t){let n=(await Ht(e,V)).filter(i=>gt(i)>=t);if(n.length>0)return n;let r=(await Ht(e,ie)).filter(i=>gt(i)>=t).map(i=>({...i,event_type:"invocation"})),s=(await Ht(e,Pe)).filter(i=>gt(i)>=t).map(i=>({...i,event_type:"invocation",degradation_reason:I(i.reason)||"unknown"}));return[...r,...s]}function Nn(e,t){let n=Wt(e[t==="raw"?"tokens_raw":"tokens_emitted"]);if(n!=null)return{tokens:n,estimated:!1};let r=_e(e[t==="raw"?"raw_bytes":"emitted_bytes"]);return{tokens:Math.ceil(r/4),estimated:r>0}}function sf(e){let t=af();for(let n of e){if(I(n.event_type)==="show"||I(n.degradation_reason)!==""||n.elided!==!0)continue;let r=of(n.storage_class)??qe(I(n.command));t[r].records+=1;let s=_e(n.raw_bytes);t[r].bytes+=s,t[r].raw_bytes+=s}return t}function of(e){return e==="derivable"||e==="re-executable"||e==="ephemeral"?e:null}function af(){return{derivable:{records:0,bytes:0,raw_bytes:0},"re-executable":{records:0,bytes:0,raw_bytes:0},ephemeral:{records:0,bytes:0,raw_bytes:0}}}async function Ht(e,t){return(await e.kv(t).list({limit:1e4}).catch(r=>{if(r instanceof Error&&/\bnot found\b/i.test(r.message))return{items:[]};throw r})).items.map(r=>cf(r.value)).filter(r=>qo(r))}function cf(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function gt(e){let t=Date.parse(He(e));return Number.isFinite(t)?t:0}function He(e){return I(e.created_at)||I(e.ts)||""}function I(e){return typeof e=="string"?e:""}function _e(e){return Wt(e)??0}function Wt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function pt(e,t){if(e.length===0)return null;let n=[...e].sort((s,i)=>s-i),r=Math.min(n.length-1,Math.max(0,Math.ceil(n.length*t)-1));return Oe(n[r])}function Bo(e){return{wrapper_ms_p50:pt(e,.5),wrapper_ms_p90:pt(e,.9),wrapper_ms_p95:pt(e,.95),wrapper_ms_p99:pt(e,.99)}}function Oe(e){return Math.round(e*100)/100}function Ao(e){let t=e.trim().split(/\s+/).filter(Boolean);return t.length===0?"unknown":t[0]==="git"&&t[1]?`git ${t[1]}`:t[0]==="gh"&&t[1]&&t[2]?`gh ${t[1]} ${t[2]}`:t[0]==="gh"&&t[1]?`gh ${t[1]}`:t[0]==="cargo"&&t[1]?`cargo ${t[1]}`:t[0]==="vitest"?"vitest":t[0]}function uf(e){let t=new Date(e);return Number.isFinite(t.getTime())?`${df(t.getUTCDay())}:${t.getUTCHours()}`:null}function lf(e){let t=[];for(let n of["sun","mon","tue","wed","thu","fri","sat"])for(let r=0;r<24;r++){let s=e.get(`${n}:${r}`)??0;s>0&&t.push({weekday:n,hour:r,requests:s})}return t}function df(e){return["sun","mon","tue","wed","thu","fri","sat"][e]??"unknown"}function ff(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return null;let n=t.getUTCDay(),r=n===0?-6:1-n;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()+r)).toISOString().slice(0,10)}function mf(e){let t=null;return[...e.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>{let s=t==null||t===0?null:Oe((r-t)/t*100);return t=r,{week_start:n,tokens_saved:r,wow_delta_pct:s}})}function pf(){return 24*60*60*1e3}function qo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Uo,V,K,ie,Pe,Vt,Qd,De=S(()=>{"use strict";Je();qr();Uo=ss(".red","tmp","rsp-telemetry.spool.jsonl"),V="rsp_accounting_events_v1",K="rsp_decisions_v1",ie="rsp_telemetry_invocations_v1",Pe="rsp_telemetry_degradations_v1",Vt="rsp_telemetry_index_v1",Qd=64*1024});var ms={};C(ms,{RSP_WRAPPER_CAPABILITIES:()=>Qt,formatCodexHookDecision:()=>Ko,formatHookDecision:()=>Vo,hookDecisionFromClaudePreExecJson:()=>bf,hookDecisionFromCodexPreExecJson:()=>_f,rewriteCommand:()=>Ho,rewriteTableFromCapabilities:()=>Jo,runClaudePreExecHook:()=>Rf,runCodexPreExecHook:()=>Sf});import{readFileSync as Fn}from"node:fs";import{existsSync as gf}from"node:fs";import{fileURLToPath as hf}from"node:url";function Jo(e){let t=new Map;for(let n of e)t.set(Uf(n.command),["rsp",...n.wrapper]);return t}function Ho(e){let t=If(e);if(t)return t;let n=Pf(e);if(!n)return jn(e);let r=n.tokens.map(c=>c.text);if(r.length>0&&ia(r[0]))return jn(e);let s=wf(n);if(s)return s;if(n.tokens.some(c=>c.quoted))return jn(e);let i=[...Qt].sort((c,u)=>u.command.length-c.command.length).find(c=>Df(r,c.command));if(!i)return jn(e);let o=["rsp",...i.wrapper,...r.slice(i.command.length)],a=ea(n.redirectSuffix);return{kind:"rewrite",command:[...o.map(Yt),...a].join(" "),capabilityId:i.id}}function wf(e){let t=e.tokens.map(s=>s.text),n=t[0],r=ea(e.redirectSuffix);return n==="cat"&&t.length===2&&Mn(t[1])?{kind:"rewrite",command:["rsp","cat",Yt(t[1]),...r].join(" "),capabilityId:"cat:file"}:(n==="head"||n==="tail")&&t.length===2&&Mn(t[1])?{kind:"rewrite",command:["rsp","cat",`--${n}`,"10",Yt(t[1]),...r].join(" "),capabilityId:`cat:${n}`}:(n==="head"||n==="tail")&&t.length===4&&t[1]==="-n"&&/^[1-9][0-9]*$/.test(t[2])&&Mn(t[3])?{kind:"rewrite",command:["rsp","cat",`--${n}`,t[2],Yt(t[3]),...r].join(" "),capabilityId:`cat:${n}`}:(n==="head"||n==="tail")&&t.length===3&&/^-[1-9][0-9]*$/.test(t[1])&&Mn(t[2])?{kind:"rewrite",command:["rsp","cat",`--${n}`,t[1].slice(1),Yt(t[2]),...r].join(" "),capabilityId:`cat:${n}`}:null}function Mn(e){return!!e&&!e.startsWith("-")}async function bf(e,t){return await Wo(e,t)}async function _f(e,t){return await Wo(e,t)}async function Wo(e,t){return(await ls(e,t,"pre-exec")).decision}async function ls(e,t,n){let r=oa(e);if(!r.ok){let f={kind:"passthrough",reason:r.reason};return{decision:f,telemetryRoot:t.cwd,event:zt({hook:n,command:"",decision:f,reason:r.reason})}}let s=r.payload,i=Q(s,["cwd"])||Q(s,["tool_input","cwd"])||t.cwd;if(!await(t.isEnabled??Ef)(i)){let f={kind:"passthrough",reason:"disabled"};return{decision:f,telemetryRoot:i,event:zt({hook:n,command:us(s),decision:f,reason:"disabled"})}}let a=us(s);if(!a){let f={kind:"passthrough",reason:"missing-command"};return{decision:f,telemetryRoot:i,event:zt({hook:n,command:a,decision:f,reason:"missing-command"})}}let c=process.hrtime.bigint(),l=we(i,process.env).proxyEnabled?Cf(a):(t.rewrite??Ho)(a),d=Number(process.hrtime.bigint()-c)/1e6;if(l.kind!=="rewrite"){let f=l.reason?l:{...l,reason:"unsupported-command"};return{decision:f,telemetryRoot:i,event:zt({hook:n,command:a,decision:f,reason:f.reason??"unsupported-command",decisionMs:d})}}return await xf(i,t.wakeResident??kf),{decision:l,telemetryRoot:i,event:zt({hook:n,command:a,decision:l,reason:l.capabilityId==="proxy:universal"?"universal-proxy":"matched-capability",decisionMs:d})}}function Vo(e){return e.kind==="rewrite"?zo(e.command):{stdout:"",status:0}}function Ko(e){return e.kind==="rewrite"?zo(e.command):{stdout:"",status:0}}function zo(e){return{stdout:`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:{command:e}}})}
|
|
40
|
-
|
|
38
|
+
`)}function ff(e,t){let n=Buffer.byteLength(e,"utf8");return n<=t?e:Buffer.from(e,"utf8").subarray(n-t).toString("utf8").replace(/^\uFFFD+/,"")}function mf(e){let t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch{return ie(t)}}async function Co(e,t){try{let n=await Wt(e.registryPath);if(!n||n.socket_path!==e.socketPath||n.store_uri!==t.storeUri)return;if(!wt(n.pid)){await ae(e.registryPath,{force:!0});return}if(await We(n.socket_path,100))return;if(Vo(t.clientVersion,n.resident_version)&&(await pf(n.pid,1500),!wt(n.pid))){await ae(e.registryPath,{force:!0});return}await Ho(n.pid),await ae(e.registryPath,{force:!0})}catch{}}function wt(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function Ho(e){if(!wt(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!wt(e))return;await new Promise(n=>setTimeout(n,50))}try{process.kill(e,"SIGKILL")}catch{}}async function pf(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!wt(e))return;await new Promise(r=>setTimeout(r,50))}}async function gf(e){if(!e.startsWith("file://"))return!1;try{return await nf(jo(e)),!1}catch(t){return t.code==="ENOENT"}}function Wo(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?Cn(process.argv[1]):jo(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function hf(e){let t=Xd("sha256").update(e).digest("hex").slice(0,20),n=process.env.XDG_RUNTIME_DIR;if(n){let s=V(n,"red-skills",t);if(V(s,"rsp.sock").length<of)return s}let r=typeof process.getuid=="function"?process.getuid():"nouid";return V(sf(),`red-skills-${r}`,t)}function yf(e){let t=Cn(e);for(let n=0;n<32;n++){try{let s=fs(V(t,".git"));if(s!=null)return wf(t,s)??t;if(fs(V(t,".git","HEAD"))!=null||fs(V(t,".red","config.yaml"))!=null)return t}catch{}let r=Ie(t);if(r===t)return null;t=r}return null}function wf(e,t){let n=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!n)return null;let r=Cn(e,n[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(r)?Ie(Ie(Ie(r))):null}function fs(e){try{return Zd(e,"utf8")}catch{return null}}async function No(e,t){let n=await Fo(e).catch(()=>null);return n?Vo(t.clientVersion,n.version)?(await bf(e,t.clientVersion),await kf(e),!1):!0:!1}async function bf(e,t){try{await yt({socketPath:e,timeoutMs:200},{id:Bo(),op:"handover",clientVersion:t})}catch{}}function Vo(e,t){return!e||!t?!1:_f(e,t)>0}function _f(e,t){let n=Ao(e),r=Ao(t);return!n||!r?0:n.major-r.major||n.minor-r.minor||n.patch-r.patch}function Ao(e){let t=/^(\d+)\.(\d+)\.(\d+)/.exec(String(e).trim());return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])}:null}function Ko(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rf(e){return typeof e=="string"&&e.length>0?e:void 0}function Sf(e){return Ko(e)&&e.version===Uo&&Number.isInteger(e.pid)&&typeof e.socket_path=="string"&&typeof e.store_uri=="string"&&typeof e.resident_version=="string"&&typeof e.started_at=="string"}async function kf(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await We(e,50))return;await new Promise(n=>setTimeout(n,50))}}var of,Uo,af,df,Mn=S(()=>{oe();De();us();of=108,Uo=1,af=5e3;df=8*1024});var Zo={};B(Zo,{DEFAULT_RSP_BYTE_BUDGET:()=>Se,DEFAULT_RSP_EPHEMERAL_TTL_HOURS:()=>Re,DEFAULT_RSP_HEAVY_GIT_BYTE_THRESHOLD:()=>be,DEFAULT_RSP_IDLE_MS:()=>Fn,DEFAULT_RSP_STORE_PATH:()=>ms,DEFAULT_RSP_TELEMETRY_BYTE_BUDGET:()=>Un,DEFAULT_RSP_TELEMETRY_DRAIN_INTERVAL_MS:()=>Yo,DEFAULT_RSP_TELEMETRY_DRAIN_TIMEOUT_MS:()=>Qo,DEFAULT_RSP_TELEMETRY_TTL_DAYS:()=>jn,DEFAULT_RSP_TTL_DAYS:()=>_e,MIN_RSP_IDLE_MS:()=>Xo,resolveRspConfig:()=>ke});import{existsSync as Ef,readFileSync as xf}from"node:fs";import{join as Tf,resolve as zo}from"node:path";function ke(e,t,n){let r=Do(zo(e),Tf(".red","config.yaml")),s=r?xf(r,"utf8"):"",i=In(s,"rsp.enabled")==="true",o=In(s,"rsp.proxy.enabled")==="true",a=we(ce(s,"rsp.ttlDays"),_e),c=we(Vt(t.RSP_EPHEMERAL_TTL_HOURS)??ce(s,"rsp.ephemeralTtlHours"),Re),u=we(ce(s,"rsp.byteBudget"),Se),l=we(ce(s,"rsp.telemetryTtlDays"),jn),d=we(ce(s,"rsp.telemetryByteBudget")??ce(s,"rsp.byteBudget"),Un),f=we(Vt(t.RSP_TELEMETRY_DRAIN_INTERVAL_MS)??ce(s,"rsp.telemetryDrainIntervalMs"),Yo),h=we(Vt(t.RSP_TELEMETRY_DRAIN_TIMEOUT_MS)??ce(s,"rsp.telemetryDrainTimeoutMs"),Qo),g=vf(Vt(t.RSP_IDLE_MS)??ce(s,"rsp.idleMs"),Fn,Xo),m=we(Vt(t.RSP_HEAVY_GIT_BYTE_THRESHOLD)??ce(s,"rsp.heavyGitByteThreshold"),be),p=$e(e).rootDir,w=n??t.RSP_STORE_URI??`file://${no(zo(p),Ef)}`;return{enabled:i,proxyEnabled:o,storeUri:w,ttlDays:a,ephemeralTtlHours:c,byteBudget:u,telemetryTtlDays:l,telemetryByteBudget:d,telemetryDrainIntervalMs:f,telemetryDrainTimeoutMs:h,idleMs:g,heavyGitByteThreshold:m}}function ce(e,t){let n=In(e,t);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function we(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function vf(e,t,n){let r=we(e,t);return Math.max(r,n)}function Vt(e){if(e==null||e.trim()==="")return;let t=Number(e);return Number.isFinite(t)?t:void 0}var be,ms,_e,Re,Se,jn,Un,Yo,Qo,Fn,Xo,ue=S(()=>{"use strict";Io();De();Mn();be=8*1024,ms=eo,_e=7,Re=6,Se=64*1024*1024,jn=90,Un=4*1024*1024,Yo=3e4,Qo=2e3,Fn=5*6e4,Xo=5e3});var en={};B(en,{DEFAULT_RSP_BYTE_BUDGET:()=>Se,DEFAULT_RSP_EPHEMERAL_TTL_HOURS:()=>Re,DEFAULT_RSP_TTL_DAYS:()=>_e,RSP_ELISION_COLLECTION:()=>F,RspElisionStore:()=>Zt,ensureReddbBinaryFromWarmCache:()=>ga,storageClassForCommand:()=>Ke});import{createHash as Kn}from"node:crypto";import{spawnSync as Xt}from"node:child_process";import{existsSync as ws}from"node:fs";import{mkdir as ca,readFile as ua,readdir as la,rename as Jn,rm as Kt,stat as ps,writeFile as Pf}from"node:fs/promises";import{homedir as Of}from"node:os";import{basename as da,dirname as fa,join as zt}from"node:path";import{fileURLToPath as Df}from"node:url";import{gunzipSync as If,gzipSync as $f}from"node:zlib";function ea(e,t){return`el:${Kn("sha256").update("rsp-elision-v1\0").update(e).update("\0").update(JSON.stringify({command:t.command,loss:t.loss})).digest("hex").slice(0,12)}`}function Ve(e){return`record:${e.slice(3)}`}function bt(e){return`expired:${e.slice(3)}`}function gs(){return"index:v1"}function Cf(e){return`blob:${e}`}function Nf(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`invalid RedDB identifier: ${e}`);return e}function Ke(e){let t=e.trim().split(/\s+/).filter(Boolean),n=t[0]??"";if(n==="cat")return"derivable";if(n==="git"){let r=t[1]??"";return r==="log"||r==="diff"||r==="blame"||r==="show"?"derivable":zn(t)?"re-executable":"ephemeral"}return"ephemeral"}function Gn(e){return Yn(e.storage_class)?e.storage_class:Ke(e.command)}function Af(e){return Yn(e.storage_class)?e.storage_class:Ke(e.command)}function ta(e){let t=Uf(),n={derivable:new Set,"re-executable":new Set,ephemeral:new Set};for(let r of e){let s=Af(r);if(t[s].records+=1,t[s].raw_bytes+=r.raw_bytes??r.bytes,r.blob_key){if(n[s].has(r.blob_key))continue;n[s].add(r.blob_key)}t[s].bytes+=r.bytes}return t}function na(e,t,n,r){let s=t==="ephemeral"?r*60*60*1e3:n*24*60*60*1e3;return new Date(e.getTime()+s).toISOString()}function _t(e){let t=0,n=new Set;for(let r of e){if(r.blob_key){if(n.has(r.blob_key))continue;n.add(r.blob_key)}t+=r.bytes}return t}function ra(e,t){let n=process.cwd(),r=Xt("git",["rev-parse","--is-inside-work-tree"],{cwd:n,encoding:"utf8"});if(r.status!==0||r.stdout.trim()!=="true")return null;let s=Xt("git",["hash-object","-w","--stdin"],{cwd:n,input:e,encoding:"buffer"});if(s.status!==0)return null;let i=s.stdout.toString("utf8").trim();return/^[0-9a-f]{40,64}$/.test(i)?{kind:"git-blob",command:t,cwd:n,object_ids:[i],working_tree_fingerprint:Bf(n),original_bytes:e.length}:null}function Bf(e){let t=hs(e,["rev-parse","HEAD"])||"unborn",n=hs(e,["write-tree"])||"no-index",r=hs(e,["status","--porcelain=v1","-z"])||"";return Kn("sha256").update(t).update("\0").update(n).update("\0").update(r).digest("hex")}function hs(e,t){let n=Xt("git",t,{cwd:e,encoding:"utf8"});return n.status===0?n.stdout.trim():null}function sa(e,t){let n=t.trim().split(/\s+/).filter(Boolean);if(!zn(n))return null;let r=ma(process.cwd(),n,e.length);return!r||Rt(r)!==Rt(e)?null:{kind:"command",command:t,cwd:process.cwd(),argv:n,original_bytes:e.length,content_hash:Rt(e)}}function zn(e){return e[0]==="git"?e[1]==="status"?!0:e[1]!=="branch"?!1:e.length===2||e.slice(2).every(t=>/^-[avvr]+$/.test(t)):!1}function Rt(e){return Kn("sha256").update("rsp-reexecutable-content-v1\0").update(e).digest("hex")}function ia(e,t,n,r){return t?Buffer.byteLength(JSON.stringify(t),"utf8"):n?Buffer.byteLength(JSON.stringify(n),"utf8"):r?r.stored_bytes:e.length}function oa(e){return typeof e.stored_bytes=="number"?e.stored_bytes:e.derivation_recipe?Buffer.byteLength(JSON.stringify(e.derivation_recipe),"utf8"):e.reexecution_recipe?Buffer.byteLength(JSON.stringify(e.reexecution_recipe),"utf8"):e.blob_key?typeof e.stored_bytes=="number"?e.stored_bytes:0:e.original_bytes}function aa(e,t,n){let r=$f(e);return{key:Cf(t),content_hash:t,encoding:"gzip+base64",bytes:r.toString("base64"),original_bytes:e.length,stored_bytes:r.length,created_at:n}}function Lf(e){try{let t=If(Buffer.from(e.bytes,"base64"));return t.length===e.original_bytes?t:null}catch{return null}}function Mf(e){let t=e.object_ids[0];if(!t)return null;let n=Xt("git",["cat-file","-p",t],{cwd:e.cwd,encoding:"buffer",maxBuffer:Math.max(e.original_bytes+1024,1024*1024)});return n.status!==0||n.stdout.length!==e.original_bytes?null:n.stdout}function jf(e){if(!zn(e.argv))return null;let t=ma(e.cwd,e.argv,e.original_bytes);return t?Rt(t)===e.content_hash?t:Buffer.concat([Buffer.from(`reconstructed after state moved - current snapshot follows
|
|
39
|
+
`,"utf8"),t]):null}function ma(e,t,n){let r=t[0];if(!r)return null;let s=Xt(r,t.slice(1),{cwd:e,encoding:"buffer",maxBuffer:Math.max(n+1024,1024*1024)});return s.status!==0||s.signal?null:s.stdout}function Uf(){return{derivable:{records:0,bytes:0,raw_bytes:0},"re-executable":{records:0,bytes:0,raw_bytes:0},ephemeral:{records:0,bytes:0,raw_bytes:0}}}function Wn(e){return/^el:[a-f0-9]{12}$/.test(e)}function Vn(e){return/^blob:[a-f0-9]{64}$/.test(e)}function Ff(e){if(!Yt(e))throw new Error("memory recall payload must be an object");let t=e.query;if(typeof t!="string"||t.trim()==="")throw new Error("memory recall query is required");let n=typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:10;return{query:t,limit:n,options:{includeSuperseded:e.includeSuperseded===!0,scope:Yt(e.scope)?e.scope:void 0,ranking:Yt(e.ranking)?e.ranking:void 0}}}function Gf(e){if(!Yt(e))throw new Error("memory ingest payload must be an object");let t=e.cwd;if(typeof t!="string"||t.trim()==="")throw new Error("memory ingest cwd is required");let n=typeof e.maxFiles=="number"&&Number.isFinite(e.maxFiles)?e.maxFiles:void 0,r=Array.isArray(e.ignore)?e.ignore.filter(s=>typeof s=="string"):void 0;return{cwd:t,maxFiles:n,ignore:r}}function Yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function qf(e,t,n){let r=[],s=new Set([".git","node_modules",".red",...n]);async function i(o){if(r.length>=t)return;let a=await la(o,{withFileTypes:!0}).catch(()=>[]);for(let c of a){if(r.length>=t)return;if(s.has(c.name))continue;let u=zt(o,c.name);c.isDirectory()?await i(u):c.isFile()&&/\.(md|mdx|txt|ts|tsx|js|jsx|json|yaml|yml|toml|rs|go|py|sql)$/i.test(c.name)&&r.push(u)}}return await i(e),r}function Jf(e,t){let n=Number(e.red_entity_id??e.rid);if(!Number.isFinite(n))return null;let r=e.properties??e.PROPERTIES,s=Yt(r)?r:{},i=String(e.label??e.LABEL??s.title??`memory-${n}`),o=String(e.node_type??e.NODE_TYPE??"concept"),a=String(s.content??s.summary??s.title??i),c=`${i} ${a}`.toLowerCase(),u=t.filter(l=>c.includes(l));return u.length===0&&t.length>0?null:{id:String(n),rid:n,label:i,node_type:o,score:u.length||1,excerpt:a.slice(0,500)}}function ys(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Hn(e){if(!K(e))return!1;let t=typeof e.original=="string"&&e.original_encoding==="base64",n=Wf(e.derivation_recipe),r=Vf(e.reexecution_recipe),s=e.blob_key,i=typeof s=="string"&&Vn(s);return e.collection===F&&typeof e.handle=="string"&&Wn(e.handle)&&(t||n||r||i)&&typeof e.original_bytes=="number"&&(e.content_hash===void 0||Rs(e.content_hash))&&(e.stored_bytes===void 0||typeof e.stored_bytes=="number")&&(s===void 0||typeof s=="string"&&Vn(s))&&typeof e.command=="string"&&typeof e.created_at=="string"&&typeof e.expires_at=="string"&&Hf(e.loss)&&(e.storage_class===void 0||Yn(e.storage_class))}function pa(e){return!K(e)||e.version!==1||!Array.isArray(e.records)?!1:e.records.every(t=>{if(!K(t))return!1;let n=t.blob_key;return typeof t.handle=="string"&&Wn(t.handle)&&typeof t.key=="string"&&typeof t.bytes=="number"&&(t.raw_bytes===void 0||typeof t.raw_bytes=="number")&&typeof t.command=="string"&&typeof t.created_at=="string"&&typeof t.expires_at=="string"&&(t.storage_class===void 0||Yn(t.storage_class))&&(n===void 0||typeof n=="string"&&Vn(n))})}function bs(e){return K(e)&&typeof e.key=="string"&&Vn(e.key)&&Rs(e.content_hash)&&e.encoding==="gzip+base64"&&typeof e.bytes=="string"&&typeof e.original_bytes=="number"&&typeof e.stored_bytes=="number"&&typeof e.created_at=="string"}function _s(e){return K(e)&&e.status==="expired"&&typeof e.expired_at=="string"&&typeof e.command=="string"}function Hf(e){return K(e)&&typeof e.level=="string"&&typeof e.bytes_elided=="number"}function Yn(e){return e==="derivable"||e==="re-executable"||e==="ephemeral"}function Wf(e){return K(e)&&e.kind==="git-blob"&&typeof e.command=="string"&&typeof e.cwd=="string"&&Array.isArray(e.object_ids)&&e.object_ids.every(t=>typeof t=="string"&&/^[0-9a-f]{40,64}$/.test(t))&&typeof e.working_tree_fingerprint=="string"&&typeof e.original_bytes=="number"}function Vf(e){return K(e)&&e.kind==="command"&&typeof e.command=="string"&&typeof e.cwd=="string"&&Array.isArray(e.argv)&&e.argv.every(t=>typeof t=="string")&&zn(e.argv)&&typeof e.original_bytes=="number"&&Rs(e.content_hash)}function Rs(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function Kf(e){try{let n=await ua(e,"utf8");if(n.trim()==="")return qn();let r=JSON.parse(n);if(Qf(r))return{...r,blobs:r.blobs??{}}}catch(n){if(n.code==="ENOENT"){let s=qn();return await Qt(e,s),s}let r=qn();return await Qt(e,r),r}let t=qn();return await Qt(e,t),t}async function zf(e){try{return e}catch(t){if(t.code==="ENOENT")return e;throw t}}function Yf(e){return da(e)==="red-skills.rdb"}async function ga(){if(process.env.REDDB_BIN)return;let e=process.env.RED_SKILLS_CACHE_DIR??(process.env.XDG_CACHE_HOME?zt(process.env.XDG_CACHE_HOME,"red-skills","bundles"):zt(Of(),".cache","red-skills","bundles")),t=zt(e,"reddb"),n;try{n=await la(t)}catch{return}n.sort().reverse();for(let r of n){let s=zt(t,r,process.platform==="win32"?"red.exe":"red");if(ws(s)){process.env.REDDB_BIN=s;return}}}async function Qt(e,t){await ca(fa(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await Pf(n,`${JSON.stringify(t)}
|
|
40
|
+
`,"utf8"),await Jn(n,e)}function qn(){return{version:1,records:{},blobs:{},tombstones:{},index:{version:1,records:[]}}}function Qf(e){return K(e)&&e.version===1&&K(e.records)&&Object.values(e.records).every(Hn)&&(e.blobs===void 0||K(e.blobs)&&Object.values(e.blobs).every(bs))&&K(e.tombstones)&&Object.values(e.tombstones).every(_s)&&pa(e.index)}function Xf(e){if(!e.startsWith("file://"))throw new Error("rsp elision store requires a file:// URI");return Df(e)}var F,Zt,ze=S(()=>{"use strict";Hr();ue();F="rsp_elisions_v1",Zt=class e{constructor(t,n){this.opts=n;this.path=t}document;db;path;dirty=!1;static async open(t){if(process.env.RSP_FAIL_IF_STORE_OPEN==="1"&&!t.allowResidentOpen)throw new Error("RSP_FAIL_IF_STORE_OPEN blocked store open");let n=Xf(t.uri),r=await zf(n),s=new e(r,{uri:t.uri,ttlDays:ys(t.ttlDays,_e),ephemeralTtlHours:ys(t.ephemeralTtlHours,Re),byteBudget:ys(t.byteBudget,Se),now:t.now??(()=>new Date)});return Yf(r)?(await ga(),await ca(fa(r),{recursive:!0}),s.db=await dt(`file://${r}`),await s.ensureRedDbCollections(),await s.ensureRedDbStore()):s.document=await Kf(s.path),s}async close(){await this.db?.close()}redDb(){return this.db}async mint(t,n){if(this.db)return await this.mintRedDb(t,n);let r=Buffer.from(t),s=this.opts.now(),i=s.toISOString(),o=ea(r,n),a=Ve(o),c=Ke(n.command),u=c==="derivable"?ra(r,n.command):null,l=c==="re-executable"?sa(r,n.command):null,d=c==="derivable"&&!u||c==="re-executable"&&!l?"ephemeral":c,f=na(s,d,this.opts.ttlDays,this.opts.ephemeralTtlHours),h=Rt(r),g=d==="ephemeral"?aa(r,h,i):null,m=ia(r,u,l,g);g&&!this.document.blobs[g.key]&&(this.document.blobs[g.key]=g,this.dirty=!0);let p={collection:F,handle:o,original_bytes:r.length,stored_bytes:m,command:n.command,created_at:i,expires_at:f,loss:n.loss,storage_class:d,content_hash:h,...u?{derivation_recipe:u}:l?{reexecution_recipe:l}:{blob_key:g?.key}};return delete this.document.tombstones[bt(o)],this.document.records[a]=p,this.upsertIndex({handle:o,key:a,bytes:m,raw_bytes:r.length,command:n.command,created_at:i,expires_at:f,storage_class:d,blob_key:g?.key}),this.prune(),await this.flush(),o}async get(t){if(this.db)return await this.getRedDb(t);if(!Wn(t))return null;let n=this.tombstone(t);if(n)return n;let r=this.document.records[Ve(t)];if(!Hn(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let i={status:"expired",expired_at:r.expires_at,command:r.command};return this.expireEntry({handle:r.handle,key:Ve(r.handle),bytes:oa(r),raw_bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at,storage_class:Gn(r),blob_key:r.blob_key},r.expires_at),await this.flush(),i}let s=await this.readOriginal(r);return!s&&(r.derivation_recipe||r.reexecution_recipe)?{status:"expired",expired_at:r.expires_at,command:r.command}:s?{collection:F,handle:r.handle,original:s,command:r.command,created_at:r.created_at,loss:r.loss,storage_class:Gn(r)}:null}async stats(){if(this.db)return await this.statsRedDb();this.prune(),await this.flush();let n=this.readIndex().records;return{records:n.length,bytes:_t(n),oldest:n.reduce((r,s)=>r==null||s.created_at<r?s.created_at:r,null),budget:this.opts.byteBudget,storage_classes:ta(n)}}readIndex(){return this.document.index}writeIndex(t){this.document.index=t}upsertIndex(t){let r=this.readIndex().records.filter(s=>s.handle!==t.handle);r.push(t),this.writeIndex({version:1,records:r}),this.dirty=!0}prune(){let t=this.opts.now().getTime(),n=new Date(t).toISOString(),r=this.readIndex(),s=[];for(let o of r.records)Date.parse(o.expires_at)<=t?this.expireEntry(o,o.expires_at):s.push(o);let i=_t(s);for(s.sort((o,a)=>o.created_at.localeCompare(a.created_at));i>this.opts.byteBudget&&s.length>0;){let o=s.shift();this.expireEntry(o,n),i=_t(s)}s.length<r.records.length&&this.writeIndex({version:1,records:s}),this.deleteUnreferencedLocalBlobs(s)}expireEntry(t,n){delete this.document.records[t.key],this.document.tombstones[bt(t.handle)]={status:"expired",expired_at:n,command:t.command},this.dirty=!0}tombstone(t){let n=this.document.tombstones[bt(t)];return _s(n)?n:null}async readOriginal(t){if(t.original)return Buffer.from(t.original,"base64");if(t.derivation_recipe)return Mf(t.derivation_recipe);if(t.reexecution_recipe)return jf(t.reexecution_recipe);if(t.blob_key){let n=this.db?await this.kvGet(t.blob_key):this.document.blobs[t.blob_key];return bs(n)?Lf(n):null}return null}deleteUnreferencedLocalBlobs(t){let n=new Set(t.map(r=>r.blob_key).filter(r=>typeof r=="string"));for(let r of Object.keys(this.document.blobs))n.has(r)||(delete this.document.blobs[r],this.dirty=!0)}async flush(){this.dirty&&(await Qt(this.path,this.document),this.dirty=!1),await this.rotateLocalGenerationIfOversized()}async rotateLocalGenerationIfOversized(){let t=await ps(this.path).then(a=>a.size,()=>0);if(t<=this.opts.byteBudget)return;let n=this.readIndex().records,r=new Set(n.map(a=>a.key)),s=new Set(n.map(a=>a.blob_key).filter(a=>typeof a=="string")),i={version:1,records:Object.fromEntries(Object.entries(this.document.records).filter(([a])=>r.has(a))),blobs:Object.fromEntries(Object.entries(this.document.blobs).filter(([a])=>s.has(a))),tombstones:{},index:{version:1,records:n}},o=Buffer.byteLength(`${JSON.stringify(i)}
|
|
41
|
+
`,"utf8");o>this.opts.byteBudget||o>=t||(this.document=i,await Qt(this.path,this.document))}kv(){if(!this.db)throw new Error("rsp RedDB store is not open");return this.db.kv(F)}async kvGet(t){let n=await this.kv().get(t);if(typeof n!="string")return n;try{return JSON.parse(n)}catch{return n}}async ensureRedDbStore(){let t=await this.readRedDbIndex();await this.writeRedDbIndex(t)}async ensureRedDbCollections(){if(!this.db)throw new Error("rsp RedDB store is not open");let t=(await this.db.list()).find(n=>n.name===F);if(!t){await this.db.query(`CREATE KV IF NOT EXISTS ${F}`);return}if(t.model!=="kv"){if(t.model!=="table")throw new Error(`cannot self-heal elision collection ${F}: unsupported model ${t.model}`);await this.db.query(`DROP TABLE ${F}`),await this.db.query(`CREATE KV IF NOT EXISTS ${F}`)}}async mintRedDb(t,n){let r=Buffer.from(t),s=this.opts.now(),i=s.toISOString(),o=ea(r,n),a=Ve(o),c=Ke(n.command),u=c==="derivable"?ra(r,n.command):null,l=c==="re-executable"?sa(r,n.command):null,d=c==="derivable"&&!u||c==="re-executable"&&!l?"ephemeral":c,f=na(s,d,this.opts.ttlDays,this.opts.ephemeralTtlHours),h=Rt(r),g=d==="ephemeral"?aa(r,h,i):null,m=ia(r,u,l,g);g&&!bs(await this.kvGet(g.key))&&await this.kv().put(g.key,g);let p={collection:F,handle:o,original_bytes:r.length,stored_bytes:m,command:n.command,created_at:i,expires_at:f,loss:n.loss,storage_class:d,content_hash:h,...u?{derivation_recipe:u}:l?{reexecution_recipe:l}:{blob_key:g?.key}};await this.kv().delete(bt(o)),await this.kv().put(a,p);let y=(await this.readRedDbIndex()).records.filter(x=>x.handle!==o);return y.push({handle:o,key:a,bytes:m,raw_bytes:r.length,command:n.command,created_at:i,expires_at:f,storage_class:d,blob_key:g?.key}),await this.pruneRedDb({version:1,records:y},!0),await this.assertRedDbMintPersisted(o,m),o}async getRedDb(t){if(!Wn(t))return null;let n=await this.kvGet(bt(t));if(_s(n))return n;let r=await this.kvGet(Ve(t));if(!Hn(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let i={status:"expired",expired_at:r.expires_at,command:r.command};return await this.expireRedDbEntry({handle:r.handle,key:Ve(r.handle),bytes:oa(r),raw_bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at,storage_class:Gn(r),blob_key:r.blob_key},r.expires_at),i}let s=await this.readOriginal(r);return!s&&(r.derivation_recipe||r.reexecution_recipe)?{status:"expired",expired_at:r.expires_at,command:r.command}:s?{collection:F,handle:r.handle,original:s,command:r.command,created_at:r.created_at,loss:r.loss,storage_class:Gn(r)}:null}async statsRedDb(){let t=await this.pruneRedDb(await this.readRedDbIndex());return{records:t.records.length,bytes:_t(t.records),oldest:t.records.reduce((n,r)=>n==null||r.created_at<n?r.created_at:n,null),budget:this.opts.byteBudget,storage_classes:ta(t.records)}}async memory(t,n){if(!this.db)throw new Error("resident memory operations require the shared RedDB store");if(await this.ensureMemoryGraphStore(),t==="recall"){let r=Ff(n);return await this.memoryRecallRedDb(r.query,r.limit)}if(t==="ingest"){let r=Gf(n);return await this.memoryIngestRedDb(r)}throw new Error(`unsupported memory action: ${t}`)}async ensureMemoryGraphStore(){if(!this.db)throw new Error("rsp RedDB store is not open");await this.db.execute("CREATE GRAPH IF NOT EXISTS memory_nodes"),await this.db.execute("CREATE GRAPH IF NOT EXISTS memory_edges")}async memoryIngestRedDb(t){if(!this.db)throw new Error("rsp RedDB store is not open");let n=await qf(t.cwd,t.maxFiles??200,t.ignore??[]),r=0;for(let s of n){let o=(await ua(s,"utf8").catch(()=>"")).trim();if(!o)continue;let a=da(s),c=Kn("sha256").update("resident-memory-v1\0").update(s).update("\0").update(o).digest("hex");if(await this.db.kv("memory_kv").get(`resident-node-hash:${c}`)!=null)continue;let u=Date.now(),l={title:a,content:o,source:s,confidence:"EXTRACTED",hash:c,project:"default",scope:"project",importance:1,tier:"durable",provenance_tier:"oracle",created_at:u,updated_at:u,accessed_at:u,access_count:0,provenance:{source_kind:"system",writer:"rsp-resident",confidence:"EXTRACTED",evidence:[s],created_at:u,updated_at:u}},d=await this.db.query("INSERT INTO memory_nodes NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *",a,"concept",c,l),f=Number(d.rows[0]?.red_entity_id??d.rows[0]?.rid);Number.isFinite(f)&&await this.db.kv("memory_kv").put(`resident-node-hash:${c}`,f),r+=1}return{files:n.length,nodes:r,edges:0,docs:n.length,added:r,updated:0,skipped:n.length-r,stale:0,semantic:{enabled:!1,nodes:0,edges:0,token_cost:{input:0,output:0}},durationMs:0}}async memoryRecallRedDb(t,n){if(!this.db)throw new Error("rsp RedDB store is not open");let r=await this.db.query("SELECT * FROM memory_nodes"),s=t.toLowerCase().split(/\s+/).filter(Boolean),i=r.rows.map(o=>Jf(o,s)).filter(o=>o!=null).sort((o,a)=>a.score-o.score).slice(0,Math.max(1,Math.min(100,n)));return{hits:i,context_md:i.map(o=>`- memory_nodes:${o.rid} ${o.label}: ${o.excerpt}`).join(`
|
|
42
|
+
`),diagnostics:{vector:{status:"unavailable",candidates:0,contributed:0,reason:"resident-basic-recall"}}}}async readRedDbIndex(){let t=await this.kvGet(gs());return pa(t)?t:{version:1,records:[]}}async writeRedDbIndex(t){await this.kv().put(gs(),t)}async pruneRedDb(t,n=!1){let r=this.opts.now().getTime(),s=new Date(r).toISOString(),i=[];for(let c of t.records)Date.parse(c.expires_at)<=r?await this.expireRedDbEntry(c,c.expires_at):i.push(c);let o=_t(i);for(i.sort((c,u)=>c.created_at.localeCompare(u.created_at));o>this.opts.byteBudget&&i.length>0;){let c=i.shift();await this.expireRedDbEntry(c,s),o=_t(i)}let a={version:1,records:i};return(n||i.length<t.records.length)&&await this.writeRedDbIndex(a),await this.deleteUnreferencedRedDbBlobs(i),await this.rotateRedDbGenerationIfOversized(a),a}async rotateRedDbGenerationIfOversized(t){if(!this.db)throw new Error("rsp RedDB store is not open");let n=await ps(this.path).then(u=>u.size,()=>0);if(n<=this.opts.byteBudget)return;let r=await this.snapshotRedDbKvCollections(t);if(!r)return;let s=`${process.pid}.${Date.now()}`,i=`${this.path}.${s}.compact`,o=`${this.path}.${s}.old`;await Kt(i,{force:!0}),await Kt(o,{force:!0});let a=await dt(`file://${i}`);try{for(let u of r){await a.query(`CREATE KV IF NOT EXISTS ${Nf(u.name)}`);let l=a.kv(u.name);for(let d of u.items)await l.put(d.key,d.value)}}finally{await a.close()}let c=await ps(i).then(u=>u.size,()=>0);if(c===0||c>this.opts.byteBudget||c>=n){await Kt(i,{force:!0});return}await this.db.close(),this.db=void 0;try{await Jn(this.path,o),await Jn(i,this.path),await Kt(o,{force:!0})}catch(u){throw!ws(this.path)&&ws(o)&&await Jn(o,this.path),await Kt(i,{force:!0}),u}finally{this.db=await dt(`file://${this.path}`)}}async snapshotRedDbKvCollections(t){if(!this.db)throw new Error("rsp RedDB store is not open");let n=await this.db.list();if(n.some(i=>i.model!=="kv"))return null;let r=[],s=!1;for(let i of n){let o=String(i.name??"").trim();if(o===F){r.push(await this.snapshotRedDbElisions(t)),s=!0;continue}let a=await this.db.kv(o).list({limit:1e4});if(a.items.length>=1e4)return null;r.push({name:o,items:a.items})}return s||r.push(await this.snapshotRedDbElisions(t)),r}async snapshotRedDbElisions(t){let n=[{key:gs(),value:t}],r=new Set;for(let s of t.records)r.add(s.key),s.blob_key&&r.add(s.blob_key);for(let s of r){let i=await this.kvGet(s);i!=null&&n.push({key:s,value:i})}return{name:F,items:n}}async expireRedDbEntry(t,n){await this.kv().delete(t.key),await this.kv().put(bt(t.handle),{status:"expired",expired_at:n,command:t.command})}async deleteUnreferencedRedDbBlobs(t){let n=new Set(t.map(s=>s.blob_key).filter(s=>typeof s=="string")),r=await this.kv().list({limit:1e4}).catch(()=>({items:[]}));for(let s of r.items)s.key.startsWith("blob:")&&!n.has(s.key)&&await this.kv().delete(s.key)}async assertRedDbMintPersisted(t,n){let r=await this.kvGet(Ve(t));if(!Hn(r))throw new Error(`rsp resident failed to persist elision record ${t}`);let i=(await this.readRedDbIndex()).records.find(o=>o.handle===t);if(!i||i.bytes!==n)throw new Error(`rsp resident failed to persist elision index ${t}`)}}});var an={};B(an,{RSP_ACCOUNTING_EVENTS_COLLECTION:()=>z,RSP_DECISIONS_COLLECTION:()=>Y,RSP_TELEMETRY_DEGRADATIONS_COLLECTION:()=>Ne,RSP_TELEMETRY_INDEX_COLLECTION:()=>sn,RSP_TELEMETRY_INVOCATIONS_COLLECTION:()=>le,RSP_TELEMETRY_LEGACY_SPOOL_FILE:()=>Pa,RSP_TELEMETRY_SPOOL_CORRECTIONS_FILE:()=>Oa,RSP_TELEMETRY_SPOOL_FILE:()=>va,appendTelemetryEvent:()=>Qe,appendTelemetryEventSync:()=>on,drainTelemetrySpool:()=>vs,parseTelemetryEvent:()=>xt,readAccountingLaneStats:()=>Ps,readTelemetryGainsReport:()=>Os,readTelemetryStats:()=>tr,takeTelemetrySpool:()=>im,telemetryLegacySpoolPath:()=>er,telemetrySpoolCorrectionsPath:()=>Ts,telemetrySpoolPath:()=>xe});import{randomUUID as ks,createHash as Zf}from"node:crypto";import{appendFileSync as Sa,existsSync as em,mkdirSync as ka}from"node:fs";import{mkdir as Ea,readdir as tm,readFile as xa,rename as nm,rm as Ta,writeFile as Es}from"node:fs/promises";import{basename as Ss,dirname as rn,join as Et,resolve as ha}from"node:path";function Zn(e){if(!e)return null;let t=ha(e);for(;;){if(em(Et(t,".red")))return t;let n=ha(Et(t,".."));if(n===t)break;t=n}return null}function xe(e){return Et(W(e),va)}function er(e){return Et(W(e),Pa)}function Ts(e){return Et(W(e),Oa)}async function Qe(e,t){on(e,t)}function on(e,t){try{let n=Zn(e);if(!n)return;let r=xe(n);ka(rn(r),{recursive:!0}),Sa(r,cm({spool_id:ks(),event:sm(t)}),{encoding:"utf8",mode:384})}catch{}}function sm(e){return ya(ya(e,"raw_text","raw_bytes"),"emitted_text","emitted_bytes")}function ya(e,t,n){let r=e[t];if(typeof r!="string")return e;let s=Buffer.byteLength(r,"utf8");if(s<=rm)return e;let i={...e};return delete i[t],Ee(i[n])===0&&(i[n]=s),i.estimated=!0,i}async function im(e){let t=Zn(e);if(!t)return[];let n=xe(t);await Ea(rn(n),{recursive:!0}).catch(()=>{});let r=await $a(t),s=[...await Ca(t),...await lm(r)];return await Promise.all(r.map(i=>Ta(i,{force:!0}))),s.map(i=>JSON.stringify(i.event))}async function vs(e,t){let n=Zn(e);if(!n)return;let r=xe(n);await Ea(rn(r),{recursive:!0}).catch(()=>{}),await um(n);for(let s of await om(n))await wa(n,s,t);for(let s of await Ca(n))await Da(n,s,t,!0);for(let s of await $a(n))await wa(n,s,t)}async function om(e){let t=[xe(e),er(e)],n=rn(t[0]);return(await tm(n).catch(()=>[])).filter(s=>t.some(i=>s.startsWith(`${Ss(i)}.`)&&s.endsWith(".drain"))).filter(s=>{let i=t.find(c=>s.startsWith(`${Ss(c)}.`));if(!i)return!1;let o=`${Ss(i)}.`,a=Number(s.slice(o.length).split(".")[0]);return!(Number.isInteger(a)&&a!==process.pid&&am(a))}).sort().map(s=>Et(n,s))}function am(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function wa(e,t,n){try{let r=await Ia(t);for(let s of Na(r))await Da(e,s,n,!1)}finally{await Ta(t,{force:!0})}}async function Da(e,t,n,r){let s=t.event?JSON.stringify(t.event):t.raw_line??"";try{if(await n(s)){r&&ba(e,{correction_id:ks(),target_spool_id:t.spool_id,action:"resolved",created_at:new Date().toISOString()});return}}catch{}ba(e,{correction_id:ks(),target_spool_id:t.spool_id,action:"retry",created_at:new Date().toISOString(),event_json:t.event?JSON.stringify(t.event):void 0})}async function Ia(e){let t="";for(let n=0;n<5;n++){let r=await xa(e,"utf8").catch(()=>"");if(r===t)return r;t=r,await new Promise(s=>setTimeout(s,2))}return t}function xt(e){try{let t=JSON.parse(e);return!nr(t)||t.collection!==z&&t.collection!==Y&&t.collection!==le&&t.collection!==Ne?null:t}catch{return null}}function cm(e){return On().push(mm(e))}function ba(e,t){try{let n=Zn(e);if(!n)return;let r=Ts(n);ka(rn(r),{recursive:!0});let s=On();Sa(r,s.push({correction_id:t.correction_id,target_spool_id:t.target_spool_id,action:t.action,created_at:t.created_at,event_json:t.event_json??null}),{encoding:"utf8",mode:384})}catch{}}async function $a(e){let t=[xe(e),er(e)],n=[];for(let r of t){let s=`${r}.${process.pid}.${Date.now()}.drain`;try{await nm(r,s),await Es(r,"",{flag:"wx"}).catch(()=>{}),n.push(s)}catch(i){if(i.code!=="ENOENT")continue}}return n}async function um(e){await Promise.all([Es(xe(e),"",{flag:"a"}),Es(er(e),"",{flag:"a"})]).catch(()=>{})}async function lm(e){let t=[];for(let n of e)t.push(...Na(await Ia(n)));return t}async function Ca(e){let t=await xa(Ts(e),"utf8").catch(()=>""),n=new Map;for(let r of dm(t))n.set(r.target_spool_id,r);return[...n.values()].filter(r=>r.action==="retry"&&r.event_json).map(r=>({spool_id:r.target_spool_id,event:xt(r.event_json)??void 0})).filter(r=>r.event!==void 0)}function Na(e){let t=[],n="";for(let r of e.split(/\r?\n/)){let s=r.trim();if(s){try{let i=JSON.parse(s);if(nr(i)){let o=xt(JSON.stringify(i));t.push(o?{spool_id:Qn(JSON.stringify(i)),event:o}:{spool_id:Qn(s),raw_line:s})}continue}catch{}if(/^\[(?:\d*)\]\{[^}]+\}:$/.test(s)){n=s;continue}if(!n){t.push({spool_id:Qn(s),raw_line:s});continue}try{for(let i of Pn(`${n}
|
|
43
|
+
${s}
|
|
44
|
+
`))xs(i)&&pm(i)&&t.push({spool_id:i.spool_id,event:Aa(i)})}catch{s.startsWith("{")&&t.push({spool_id:Qn(s),raw_line:s})}}}return t}function dm(e){return fm(e).map(gm).filter(t=>t!==null)}function fm(e){let t=[],n="";for(let r of e.split(/\r?\n/)){let s=r.trim();if(s)try{let i=JSON.parse(s);xs(i)&&t.push(i)}catch{if(/^\[(?:\d*)\]\{[^}]+\}:$/.test(s)){n=s;continue}if(!n)continue;try{for(let i of Pn(`${n}
|
|
45
|
+
${s}
|
|
46
|
+
`))xs(i)&&t.push(i)}catch{}}}return t}function Qn(e){return`legacy:${Zf("sha256").update(e).digest("hex").slice(0,24)}`}function mm(e){let t={spool_id:e.spool_id};for(let[n,r]of Object.entries(e.event??{}))n!=="spool_id"&&(typeof r=="string"||typeof r=="number"||typeof r=="boolean"||r===null?t[n]=r:r!==void 0&&(t[n]=JSON.stringify(r)));return t}function Aa(e){let{spool_id:t,...n}=e;return xt(JSON.stringify(n))}function pm(e){return typeof e.spool_id=="string"&&Aa(e)!==null}function gm(e){return typeof e.correction_id=="string"&&typeof e.target_spool_id=="string"&&(e.action==="retry"||e.action==="resolved")&&typeof e.created_at=="string"&&(e.event_json===null||typeof e.event_json=="string")?{correction_id:e.correction_id,target_spool_id:e.target_spool_id,action:e.action,created_at:e.created_at,event_json:e.event_json??void 0}:null}function xs(e){return nr(e)?Object.values(e).every(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null):!1}async function tr(e,t,n=new Date){let r=Number.isFinite(t)&&t>0?t:30,s=n.getTime()-r*24*60*60*1e3,i=await Ba(e,s),o=(await tn(e,Y)).filter(k=>kt(k)>=s),a=i.filter(k=>C(k.event_type)!=="show"&&C(k.degradation_reason)===""),c=i.filter(k=>C(k.event_type)==="show"),u=i.filter(k=>C(k.degradation_reason)!==""),l=0,d=0,f=0,h=0,g=!1,m=new Map,p=new Map,w=[],y=0,x=0,E=0;for(let k of a){k.elided===!0&&l++;let $=Ee(k.raw_bytes),b=Ee(k.emitted_bytes),T=Math.max(0,$-b),it=Xn(k,"raw"),ot=Xn(k,"emitted"),X=Math.max(0,it.tokens-ot.tokens);g||=(k.estimated===!0||it.estimated||ot.estimated)&&X>0,d+=$,f+=b,h+=X;let H=Ye(k).slice(0,10);H&&m.set(H,(m.get(H)??0)+X);let qe=C(k.command)||"unknown",ve=p.get(qe)??{command:qe,invocations:0,bytes_saved:0,tokens_saved:0};ve.invocations++,ve.bytes_saved+=T,ve.tokens_saved+=X,p.set(qe,ve);let at=nn(k.wrapper_ms);at!=null&&w.push(at),y+=Ee(k.store_open_count);let ct=nn(k.store_elapsed_ms);ct!=null&&(x+=ct,E++)}let v=new Map,N=null;for(let k of u){let $=C(k.degradation_reason)||C(k.reason)||"unknown";v.set($,(v.get($)??0)+1);let b=Ye(k);(!N||b>N.timestamp)&&(N={timestamp:b,reason:$,command:C(k.command)||"unknown"})}let M=a.length+u.length,Q=c.filter(k=>k.hit===!0).length,A=as(h,g),Rn=hm(o);return{window_days:r,empty:i.length===0,savings:{invocations:a.length,elided:l,raw_bytes:d,emitted_bytes:f,bytes_saved:Math.max(0,d-f),tokens_saved:h,tokens_saved_estimated:A.tokens_saved_estimated,token_estimate_range_pct:A.token_estimate_range_pct,tokens_saved_low:A.tokens_saved_low,tokens_saved_high:A.tokens_saved_high,dollars_saved_estimate_usd:A.dollars_saved_estimate_usd,dollars_saved_low_usd:A.dollars_saved_low_usd,dollars_saved_high_usd:A.dollars_saved_high_usd,pricing_model_family:A.pricing_model_family,pricing_input_usd_per_million_tokens:A.pricing_input_usd_per_million_tokens,pricing_note:A.pricing_note,daily_tokens_saved:[...m.entries()].sort(([k],[$])=>k.localeCompare($)).map(([k,$])=>({date:k,tokens_saved:$})),top_commands:[...p.values()].sort((k,$)=>$.bytes_saved-k.bytes_saved||$.tokens_saved-k.tokens_saved||k.command.localeCompare($.command))},health:{degradations:u.length,degradation_rate:M===0?0:u.length/M,show_total:c.length,show_hits:Q,show_misses:Math.max(0,c.length-Q),show_hit_rate:c.length===0?0:Ce(Q/c.length),by_reason:[...v.entries()].sort((k,$)=>$[1]-k[1]||k[0].localeCompare($[0])).map(([k,$])=>({reason:k,count:$})),most_recent:N},latency:{wrapper_ms_p50:St(w,.5),wrapper_ms_p95:St(w,.95),store_open_count_sum:y,store_elapsed_ms_sum:Ce(x),store_elapsed_ms_avg:E===0?null:Ce(x/E)},decisions:Rn}}function hm(e){let t=0,n=0,r=0,s=new Map;for(let i of e){let o=C(i.decision);if(o==="contributed"?t++:o==="failed-open"?r++:n++,o!=="contributed"){let a=C(i.reason)||"unknown";s.set(a,(s.get(a)??0)+1)}}return{seen:e.length,contributed:t,passed:n,failed_open:r,contribution_rate:e.length===0?0:Ce(t/e.length),top_pass_reasons:[...s.entries()].sort((i,o)=>o[1]-i[1]||i[0].localeCompare(o[0])).map(([i,o])=>({reason:i,count:o}))}}async function Ps(e,t,n=new Date){let s=(await tn(e,z)).filter(i=>kt(i)<=n.getTime()||Ye(i)==="");return{records:s.length,bytes:s.reduce((i,o)=>i+Buffer.byteLength(JSON.stringify(o),"utf8"),0),oldest:s.reduce((i,o)=>{let a=Ye(o);return a&&(i==null||a<i)?a:i},null),budget:t,storage_classes:ym(s)}}async function Os(e,t,n=new Date){let r=Number.isFinite(t)&&t>0?t:28,s=n.toISOString(),i=new Date(n.getTime()-r*24*60*60*1e3).toISOString(),o=Date.parse(i),a=await Ba(e,o),c=a.filter(b=>C(b.event_type)!=="show"&&C(b.degradation_reason)===""),u=a.filter(b=>C(b.degradation_reason)!==""),l=[...c,...u].map(kt).filter(b=>Number.isFinite(b)&&b>0),d=l.length===0?null:Math.min(...l),f=d==null?0:Math.max(1,Math.min(r,Math.ceil((n.getTime()-d)/Tm()))),h=[],g=new Map,m=new Map,p=new Map,w=new Map,y=new Map,x=new Map,E=0,v=!1,N=0,M=null,Q=0,A=0;for(let b of c){let T=Ye(b),it=T.slice(0,10),ot=T.slice(0,16),X=Ra(C(b.command)),H=Math.max(0,Xn(b,"raw").tokens-Xn(b,"emitted").tokens);E+=H,v||=b.estimated===!0&&H>0;let qe=Math.max(0,Ee(b.raw_bytes)-Ee(b.emitted_bytes)),ve=nn(b.wrapper_ms);if(ve!=null){h.push(ve);let Ii=g.get(X)??[];Ii.push(ve),g.set(X,Ii)}it&&m.set(it,(m.get(it)??0)+1),ot&&p.set(ot,(p.get(ot)??0)+1);let at=Rm(T);at&&w.set(at,(w.get(at)??0)+1);let ct=Em(T);ct&&y.set(ct,(y.get(ct)??0)+H);let Sn=x.get(X)??{command_family:X,invocations:0,tokens_saved:0,bytes_saved:0};Sn.invocations++,Sn.tokens_saved+=H,Sn.bytes_saved+=qe,x.set(X,Sn),b.elided===!0&&N++,(b.store_open_count!=null||b.store_elapsed_ms!=null)&&(Q++,Ee(b.store_open_count)>0&&A++),H>0&&(!M||H>M.tokens_saved||H===M.tokens_saved&&qe>M.bytes_saved)&&(M={timestamp:T,command_family:X,tokens_saved:H,bytes_saved:qe})}let Rn=u.map(b=>({timestamp:Ye(b),command_family:Ra(C(b.command)),reason:C(b.degradation_reason)||C(b.reason)||"unknown"})).sort((b,T)=>b.timestamp.localeCompare(T.timestamp)),k=new Map;for(let b of Rn)k.set(b.reason,(k.get(b.reason)??0)+1);let $=[...p.entries()].sort((b,T)=>T[1]-b[1]||b[0].localeCompare(T[0]))[0];return{schema_version:"red.rsp.gains.v1",window:{requested_days:r,data_days:f,since:i,until:s,label:`window: ${r}d, data: ${f}d`,empty:c.length===0&&u.length===0,invocations:c.length,degradations:u.length},latency:{global:_a(h),by_command_family:[...g.entries()].sort((b,T)=>T[1].length-b[1].length||b[0].localeCompare(T[0])).map(([b,T])=>({command_family:b,count:T.length,..._a(T)}))},throughput:{requests_per_day:[...m.entries()].sort(([b],[T])=>b.localeCompare(T)).map(([b,T])=>({date:b,requests:T})),active_minute_avg:p.size===0?null:Ce([...p.values()].reduce((b,T)=>b+T,0)/p.size),peak_minute:$?{minute:$[0],requests:$[1]}:null,hour_weekday_heatmap:Sm(w)},savings:{tokens:as(E,v),weekly_tokens_saved:xm(y),elision_rate:c.length===0?0:Ce(N/c.length),top_commands_by_tokens_saved:[...x.values()].sort((b,T)=>T.tokens_saved-b.tokens_saved||T.bytes_saved-b.bytes_saved||b.command_family.localeCompare(T.command_family)).slice(0,10),top_commands_by_invocation_count:[...x.values()].sort((b,T)=>T.invocations-b.invocations||T.tokens_saved-b.tokens_saved||b.command_family.localeCompare(T.command_family)).slice(0,10),single_biggest_elision:M},health:{degradation_timeline:Rn,degradations_by_reason:[...k.entries()].sort((b,T)=>T[1]-b[1]||b[0].localeCompare(T[0])).map(([b,T])=>({reason:b,count:T})),cold_boots:Q===0?null:A,warm_hits:Q===0?null:Math.max(0,Q-A)}}}async function Ba(e,t){let n=(await tn(e,z)).filter(i=>kt(i)>=t);if(n.length>0)return n;let r=(await tn(e,le)).filter(i=>kt(i)>=t).map(i=>({...i,event_type:"invocation"})),s=(await tn(e,Ne)).filter(i=>kt(i)>=t).map(i=>({...i,event_type:"invocation",degradation_reason:C(i.reason)||"unknown"}));return[...r,...s]}function Xn(e,t){let n=nn(e[t==="raw"?"tokens_raw":"tokens_emitted"]);if(n!=null)return{tokens:n,estimated:!1};let r=Ee(e[t==="raw"?"raw_bytes":"emitted_bytes"]);return{tokens:Math.ceil(r/4),estimated:r>0}}function ym(e){let t=bm();for(let n of e){if(C(n.event_type)==="show"||C(n.degradation_reason)!==""||n.elided!==!0)continue;let r=wm(n.storage_class)??Ke(C(n.command));t[r].records+=1;let s=Ee(n.raw_bytes);t[r].bytes+=s,t[r].raw_bytes+=s}return t}function wm(e){return e==="derivable"||e==="re-executable"||e==="ephemeral"?e:null}function bm(){return{derivable:{records:0,bytes:0,raw_bytes:0},"re-executable":{records:0,bytes:0,raw_bytes:0},ephemeral:{records:0,bytes:0,raw_bytes:0}}}async function tn(e,t){return(await e.kv(t).list({limit:1e4}).catch(r=>{if(r instanceof Error&&/\bnot found\b/i.test(r.message))return{items:[]};throw r})).items.map(r=>_m(r.value)).filter(r=>nr(r))}function _m(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function kt(e){let t=Date.parse(Ye(e));return Number.isFinite(t)?t:0}function Ye(e){return C(e.created_at)||C(e.ts)||""}function C(e){return typeof e=="string"?e:""}function Ee(e){return nn(e)??0}function nn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function St(e,t){if(e.length===0)return null;let n=[...e].sort((s,i)=>s-i),r=Math.min(n.length-1,Math.max(0,Math.ceil(n.length*t)-1));return Ce(n[r])}function _a(e){return{wrapper_ms_p50:St(e,.5),wrapper_ms_p90:St(e,.9),wrapper_ms_p95:St(e,.95),wrapper_ms_p99:St(e,.99)}}function Ce(e){return Math.round(e*100)/100}function Ra(e){let t=e.trim().split(/\s+/).filter(Boolean);return t.length===0?"unknown":t[0]==="git"&&t[1]?`git ${t[1]}`:t[0]==="gh"&&t[1]&&t[2]?`gh ${t[1]} ${t[2]}`:t[0]==="gh"&&t[1]?`gh ${t[1]}`:t[0]==="cargo"&&t[1]?`cargo ${t[1]}`:t[0]==="vitest"?"vitest":t[0]}function Rm(e){let t=new Date(e);return Number.isFinite(t.getTime())?`${km(t.getUTCDay())}:${t.getUTCHours()}`:null}function Sm(e){let t=[];for(let n of["sun","mon","tue","wed","thu","fri","sat"])for(let r=0;r<24;r++){let s=e.get(`${n}:${r}`)??0;s>0&&t.push({weekday:n,hour:r,requests:s})}return t}function km(e){return["sun","mon","tue","wed","thu","fri","sat"][e]??"unknown"}function Em(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return null;let n=t.getUTCDay(),r=n===0?-6:1-n;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()+r)).toISOString().slice(0,10)}function xm(e){let t=null;return[...e.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>{let s=t==null||t===0?null:Ce((r-t)/t*100);return t=r,{week_start:n,tokens_saved:r,wow_delta_pct:s}})}function Tm(){return 24*60*60*1e3}function nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var va,Pa,Oa,z,Y,le,Ne,sn,rm,Te=S(()=>{"use strict";De();oe();ze();cs();va="rsp-telemetry.spool.toonl",Pa="rsp-telemetry.spool.jsonl",Oa="rsp-telemetry.spool.corrections.toonl",z="rsp_accounting_events_v1",Y="rsp_decisions_v1",le="rsp_telemetry_invocations_v1",Ne="rsp_telemetry_degradations_v1",sn="rsp_telemetry_index_v1",rm=64*1024});var La=S(()=>{"use strict";us()});var un={};B(un,{ResidentRspElisionStore:()=>cn,ensureResidentServer:()=>Nn,kickResidentServer:()=>An,pingResident:()=>We,readResidentRegistry:()=>Wt,removeResidentRegistry:()=>Ln,residentRegistryStatus:()=>Ht,resolveResidentPaths:()=>$e,sweepResidentRegistry:()=>qo,warmResidentServer:()=>Go,writeResidentRegistry:()=>Bn});import{randomUUID as vm}from"node:crypto";function Ma(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var cn,Xe=S(()=>{"use strict";La();Mn();cn=class{constructor(t,n,r={}){this.paths=t;this.config=n;this.opts=r}metrics;lastResponseMetrics(){return this.metrics}async mint(t,n){let s=(await this.request({op:"mint",original:Buffer.from(t).toString("base64"),meta:n})).handle;if(!s?.startsWith("el:"))throw new Error("resident rsp returned invalid handle");return s}async get(t){let n=await this.request({op:"get",handle:t});return n?Ma(n)&&n.status==="expired"?n:!Ma(n)||typeof n.original!="string"?null:{...n,original:Buffer.from(n.original,"base64")}:null}async stats(){return await this.request({op:"stats"})}async accountingStats(t){return await this.request({op:"accounting-stats",byteBudget:t})}async telemetryStats(t){return await this.request({op:"telemetry-stats",sinceDays:t})}async telemetryGains(t){return await this.request({op:"telemetry-gains",sinceDays:t})}async memory(t,n){return await this.request({op:"memory",action:t,payload:n})}async close(){}async request(t){this.opts.ensureResident!==!1&&await Nn(this.paths,this.config);let n=await yt(this.paths,{...t,id:vm()});if(!n.ok)throw new Error(n.error);return this.metrics={storeOpenCount:n.storeOpenCount,storeElapsedMs:n.storeElapsedMs},n.value}}});var Ns={};B(Ns,{RSP_WRAPPER_CAPABILITIES:()=>fn,formatCodexHookDecision:()=>qa,formatHookDecision:()=>Ga,hookDecisionFromClaudePreExecJson:()=>$m,hookDecisionFromCodexPreExecJson:()=>Cm,rewriteCommand:()=>Ua,rewriteTableFromCapabilities:()=>ja,runClaudePreExecHook:()=>Nm,runCodexPreExecHook:()=>Am});import{readFileSync as or}from"node:fs";import{existsSync as Pm}from"node:fs";import{fileURLToPath as Om}from"node:url";function ja(e){let t=new Map;for(let n of e)t.set(Zm(n.command),["rsp",...n.wrapper]);return t}function Ua(e){let t=Jm(e);if(t)return t;let n=Gm(e);if(!n)return sr(e);let r=n.tokens.map(c=>c.text);if(r.length>0&&ec(r[0]))return sr(e);let s=Im(n);if(s)return s;if(n.tokens.some(c=>c.quoted))return sr(e);let i=[...fn].sort((c,u)=>u.command.length-c.command.length).find(c=>qm(r,c.command));if(!i)return sr(e);let o=["rsp",...i.wrapper,...r.slice(i.command.length)],a=za(n.redirectSuffix);return{kind:"rewrite",command:[...o.map(dn),...a].join(" "),capabilityId:i.id}}function Im(e){let t=e.tokens.map(s=>s.text),n=t[0],r=za(e.redirectSuffix);return n==="cat"&&t.length===2&&rr(t[1])?{kind:"rewrite",command:["rsp","cat",dn(t[1]),...r].join(" "),capabilityId:"cat:file"}:(n==="head"||n==="tail")&&t.length===2&&rr(t[1])?{kind:"rewrite",command:["rsp","cat",`--${n}`,"10",dn(t[1]),...r].join(" "),capabilityId:`cat:${n}`}:(n==="head"||n==="tail")&&t.length===4&&t[1]==="-n"&&/^[1-9][0-9]*$/.test(t[2])&&rr(t[3])?{kind:"rewrite",command:["rsp","cat",`--${n}`,t[2],dn(t[3]),...r].join(" "),capabilityId:`cat:${n}`}:(n==="head"||n==="tail")&&t.length===3&&/^-[1-9][0-9]*$/.test(t[1])&&rr(t[2])?{kind:"rewrite",command:["rsp","cat",`--${n}`,t[1].slice(1),dn(t[2]),...r].join(" "),capabilityId:`cat:${n}`}:null}function rr(e){return!!e&&!e.startsWith("-")}async function $m(e,t){return await Fa(e,t)}async function Cm(e,t){return await Fa(e,t)}async function Fa(e,t){return(await Is(e,t,"pre-exec")).decision}async function Is(e,t,n){let r=tc(e);if(!r.ok){let f={kind:"passthrough",reason:r.reason};return{decision:f,telemetryRoot:t.cwd,event:ln({hook:n,command:"",decision:f,reason:r.reason})}}let s=r.payload,i=ee(s,["cwd"])||ee(s,["tool_input","cwd"])||t.cwd;if(!await(t.isEnabled??Bm)(i)){let f={kind:"passthrough",reason:"disabled"};return{decision:f,telemetryRoot:i,event:ln({hook:n,command:Ds(s),decision:f,reason:"disabled"})}}let a=Ds(s);if(!a){let f={kind:"passthrough",reason:"missing-command"};return{decision:f,telemetryRoot:i,event:ln({hook:n,command:a,decision:f,reason:"missing-command"})}}let c=process.hrtime.bigint(),l=ke(i,process.env).proxyEnabled?Wm(a):(t.rewrite??Ua)(a),d=Number(process.hrtime.bigint()-c)/1e6;if(l.kind!=="rewrite"){let f=l.reason?l:{...l,reason:"unsupported-command"};return{decision:f,telemetryRoot:i,event:ln({hook:n,command:a,decision:f,reason:f.reason??"unsupported-command",decisionMs:d})}}return await Mm(i,t.wakeResident??Lm),{decision:l,telemetryRoot:i,event:ln({hook:n,command:a,decision:l,reason:l.capabilityId==="proxy:universal"?"universal-proxy":"matched-capability",decisionMs:d})}}function Ga(e){return e.kind==="rewrite"?Ja(e.command):{stdout:"",status:0}}function qa(e){return e.kind==="rewrite"?Ja(e.command):{stdout:"",status:0}}function Ja(e){return{stdout:`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:{command:e}}})}
|
|
47
|
+
`,status:0}}async function Nm(e){let t="";try{t=e?or(e,"utf8"):or(0,"utf8");let n=await Is(t,{cwd:process.cwd()},"claude-pre-exec");ar(n.telemetryRoot,n.event);let r=n.decision;Wa("claude-pre-exec",r);let s=Ga(r);return s.stdout&&process.stdout.write(s.stdout),s.status}catch(n){return ar(process.cwd(),Ha("claude-pre-exec",t,n)),Va("claude-pre-exec",n),0}}async function Am(e){let t="";try{t=e?or(e,"utf8"):or(0,"utf8");let n=await Is(t,{cwd:process.cwd()},"codex-pre-exec");ar(n.telemetryRoot,n.event);let r=n.decision;Wa("codex-pre-exec",r);let s=qa(r);return s.stdout&&process.stdout.write(s.stdout),s.status}catch(n){return ar(process.cwd(),Ha("codex-pre-exec",t,n)),Va("codex-pre-exec",n),0}}function ar(e,t){Qe(e,t).catch(()=>{})}function ln(e){let t=e.command.trim(),n=e.decision.kind==="rewrite"?e.decision.capabilityId:void 0;return{collection:Y,event_type:"decision",ts:new Date().toISOString(),hook:e.hook,command:t||"unknown",command_family:Za(t),decision:n?"contributed":"passed",reason:e.reason,capability_id:n,decision_ms:e.decisionMs}}function Ha(e,t,n){let r=tc(t),s=r.ok?Ds(r.payload):"";return{collection:Y,event_type:"decision",ts:new Date().toISOString(),hook:e,command:s||"unknown",command_family:Za(s),decision:"failed-open",reason:"hook-exception",error:$s(n)}}function Bm(e){return ke(e,process.env).enabled}async function Lm(e){let t=ke(e,process.env);if(!t.enabled||!Fm(t))return;let n=$e(e);await An(n,Um(t))}async function Mm(e,t){try{await Promise.resolve(t(e))}catch(n){jm(n)}}function Wa(e,t){if(process.env.RSP_DEBUG==="1"){if(t.kind==="rewrite"){process.stderr.write(`rsp hook ${e}: rewrite ${t.capabilityId}
|
|
41
48
|
`);return}process.stderr.write(`rsp hook ${e}: passthrough ${t.reason??"unsupported-command"}
|
|
42
|
-
`)}}function
|
|
43
|
-
`)}function
|
|
44
|
-
`)}function
|
|
45
|
-
`),detected:!0,lossy:!0,totalItems:s,keptItems:c.length,handle:d}}function
|
|
49
|
+
`)}}function Va(e,t){process.env.RSP_DEBUG==="1"&&process.stderr.write(`rsp hook ${e}: exception ${$s(t)}
|
|
50
|
+
`)}function jm(e){process.env.RSP_DEBUG==="1"&&process.stderr.write(`rsp hook pre-exec: resident-wake-failed ${$s(e)}
|
|
51
|
+
`)}function $s(e){return e instanceof Error?e.name||"Error":typeof e}function Um(e){return{storeUri:e.storeUri,ttlDays:e.ttlDays,ephemeralTtlHours:e.ephemeralTtlHours,byteBudget:e.byteBudget,telemetryTtlDays:e.telemetryTtlDays,telemetryByteBudget:e.telemetryByteBudget,telemetryDrainIntervalMs:e.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:e.telemetryDrainTimeoutMs,idleMs:e.idleMs}}function Fm(e){if(!e.storeUri.startsWith("file://"))return!0;try{return Pm(Om(e.storeUri))}catch{return!1}}function Ds(e){return ee(e,["tool_input","command"])||ee(e,["tool_input","cmd"])||ee(e,["tool_input","args","command"])||ee(e,["input","command"])||ee(e,["input","cmd"])||ee(e,["arguments","command"])||ee(e,["arguments","cmd"])||ee(e,["command"])||ee(e,["cmd"])}function Gm(e){let t=e.trim();if(!t||/[\n\r|;()$`]/.test(t))return null;let n=Ka(t);if(n.length===0||n[0]?.quoted||n.some(i=>/[()$`]/.test(i.text))||n.some(i=>i.text.includes("=")&&ec(i.text)))return null;let r=[],s=[];for(let i of n){if(i.text.includes(">")||i.text.includes("<")){if(i.quoted||i.text!=="2>/dev/null"&&i.text!=="2>&1")return null;s.push(i);continue}r.push(i)}return r.length===0?null:{tokens:r,redirectSuffix:s}}function Ka(e){let t=[],n="",r=!1,s=null,i=()=>{!n&&!r||(t.push({text:n,quoted:r}),n="",r=!1)};for(let o=0;o<e.length;o+=1){let a=e[o];if(s){if(a===s){s=null;continue}if(s==='"'&&a==="\\"&&o+1<e.length){o+=1,n+=e[o];continue}n+=a;continue}if(a==="'"||a==='"'){s=a,r=!0;continue}if(a==="\\"&&o+1<e.length){o+=1,n+=e[o];continue}if(/[ \t]/.test(a)){i();continue}n+=a}return s?[]:(i(),t)}function qm(e,t){return e.length<t.length?!1:t.every((n,r)=>e[r]===n)}function Jm(e){let t=Ka(e.trim()).map(n=>n.text);return ir(t)?{kind:"passthrough",reason:Dm}:null}function ir(e){return e[0]==="gh"&&e.some(Hm)}function Hm(e){return e==="--json"||e==="--jq"||e.startsWith("--json=")||e.startsWith("--jq=")}function za(e){return e.map(t=>t.text)}function dn(e){return/[^\w@%+=:,./-]/.test(e)?Cs(e):e}function Wm(e){let t=Vm(e);return t?{kind:"passthrough",reason:t}:{kind:"rewrite",command:`rsp proxy -- ${Cs(e.trim())}`,capabilityId:"proxy:universal"}}function Vm(e){let t=e.trim();if(!t)return"missing-command";if(Qa(t))return"background";if(/\b(?:RSP_NO_PROXY|RED_SKILLS_RSP_NO_PROXY)=1\b/.test(t))return"opt-out";let n=ur(cr(t)[0]??"")[0];if(n==="rsp")return"opt-out";if(n&&Ya.has(n))return"interactive"}function sr(e){let t=e.trim();return Km(t)?{kind:"rewrite",command:`rsp exec -- ${Cs(t)}`,capabilityId:"exec:compound"}:{kind:"passthrough"}}function Km(e){return!(!e||!zm(e)||!Ym(e)||Qa(e)||/<<-?/.test(e)||/\$\(|`/.test(e)||/[<>]/.test(e)||Qm(e,"rsp")||Xa(e,Ya)||Xm(e))}function zm(e){return/&&|[;|]/.test(e)}function Qa(e){for(let t=0;t<e.length;t+=1)if(e[t]==="&"&&!(e[t-1]==="&"||e[t+1]==="&")&&!(e[t-1]===">"||e[t+1]===">"))return!0;return!1}function Ym(e){return cr(e).some(t=>{let n=ur(t);return n.length===0?!1:n[0]==="git"?["log","diff","show","blame"].includes(n[1]??""):n[0]==="gh"?n.some((r,s)=>s>0&&(r==="list"||r==="view")):n[0]==="vitest"?!0:n[0]==="cargo"&&n[1]==="test"})}function Xa(e,t){return cr(e).some(n=>{let r=ur(n)[0];return r?t.has(r):!1})}function Qm(e,t){return Xa(e,new Set([t]))}function Xm(e){return cr(e).some(t=>{let n=ur(t);return n[0]==="grep"&&n.includes("-q")})}function cr(e){return e.split(/&&|[;|]/).map(t=>t.trim()).filter(Boolean)}function ur(e){return e.split(/[ \t]+/).filter(Boolean).map(t=>t.replace(/^env$/,""))}function Cs(e){return`'${e.replace(/'/g,"'\\''")}'`}function Za(e){let t=e.trim().split(/\s+/).filter(Boolean);return t.length===0?"unknown":t[0]==="git"&&t[1]?`git ${t[1]}`:ir(t)&&t[1]&&t[2]?`gh ${t[1]} ${t[2]} json-jq`:ir(t)&&t[1]?`gh ${t[1]} json-jq`:ir(t)?"gh json-jq":t[0]==="gh"&&t[1]&&t[2]?`gh ${t[1]} ${t[2]}`:t[0]==="gh"&&t[1]?`gh ${t[1]}`:t[0]==="cargo"&&t[1]?`cargo ${t[1]}`:t[0]==="vitest"?"vitest":t[0]}function ec(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}function Zm(e){return e.join("\0")}function tc(e){try{let t=JSON.parse(e);return nc(t)?{ok:!0,payload:t}:{ok:!1,reason:"payload-not-object"}}catch{return{ok:!1,reason:"payload-parse-error"}}}function ee(e,t){let n=e;for(let r of t){if(!nc(n))return"";n=n[r]}return typeof n=="string"?n:""}function nc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var fn,rR,Dm,Ya,lr=S(()=>{"use strict";ue();Xe();Te();fn=[{id:"git:status",command:["git","status"],wrapper:["git","status"]},{id:"git:log",command:["git","log"],wrapper:["git","log"]},{id:"git:diff",command:["git","diff"],wrapper:["git","diff"]},{id:"git:commit",command:["git","commit"],wrapper:["git","commit"]},{id:"git:push",command:["git","push"],wrapper:["git","push"]},{id:"git:blame",command:["git","blame"],wrapper:["git","blame"]},{id:"git:branch:av",command:["git","branch","-av"],wrapper:["git","branch","-av"]},{id:"git:show",command:["git","show"],wrapper:["git","show"]},{id:"gh:pr:list",command:["gh","pr","list"],wrapper:["gh","pr","list"]},{id:"gh:pr:view",command:["gh","pr","view"],wrapper:["gh","pr","view"]},{id:"gh:issue:list",command:["gh","issue","list"],wrapper:["gh","issue","list"]},{id:"gh:issue:view",command:["gh","issue","view"],wrapper:["gh","issue","view"]},{id:"gh:run:list",command:["gh","run","list"],wrapper:["gh","run","list"]},{id:"gh:run:view",command:["gh","run","view"],wrapper:["gh","run","view"]},{id:"vitest",command:["vitest"],wrapper:["vitest"]},{id:"vitest:run",command:["vitest","run"],wrapper:["vitest","run"]},{id:"cargo:test",command:["cargo","test"],wrapper:["cargo","test"]}],rR=ja(fn),Dm="lossless-gh-json-jq";Ya=new Set(["bash","fish","htop","less","more","nano","node","python","python3","ssh","top","vi","vim","zsh"])});var Bs={};B(Bs,{NORMALIZATION_ALLOWLIST:()=>dc,NORMALIZE_ANSI:()=>ic,NORMALIZE_BLANK_LINES:()=>cc,NORMALIZE_CR_PROGRESS:()=>oc,NORMALIZE_JSON_TOON:()=>lc,NORMALIZE_TRAILING_WHITESPACE:()=>ac,formatCodexNormalizeDecision:()=>hc,formatNormalizeDecision:()=>gc,hookDecisionFromClaudePostExecJson:()=>fc,hookDecisionFromCodexPostExecJson:()=>mc,normalizeOutput:()=>Tt,renderGenericJsonLane:()=>mn,runClaudePostExecHook:()=>np,runCodexPostExecHook:()=>rp,transcodeJsonToToon:()=>uc});import{readFileSync as dr}from"node:fs";function uc(e,t){let n=t?.encode??O,r=t?.decode??ie,s=e.trimEnd();if(!s)return e;let i;try{i=JSON.parse(s)}catch{return e}let o;try{o=n(i)}catch{return e}let a;try{a=r(o)}catch{return e}return As(i,a)?o.trimEnd():e}async function mn(e,t={}){let n=ap(e);if(!n)return{output:e,detected:!1,lossy:!1};let r=n.value;if(!Array.isArray(r))return{output:O(r).trimEnd(),detected:!0,lossy:!1};let s=r.length,i=sc(t.minTokens,ep),o=sc(t.maxItems,tp);if(!(s>o&&fp(e)>=i))return{output:O(r).trimEnd(),detected:!0,lossy:!1,totalItems:s,keptItems:s};let c=cp(r,o),u={items:c},l=`items: ${c.length} of ${s} kept`,d;t.level&&t.level!=="lossless"&&(d=await t.store?.mint(Buffer.from(e),{command:t.command??"rsp json",loss:{level:t.level,bytes_elided:Buffer.byteLength(e)}}));let f=d?`original: rsp show ${d}`:`original: unavailable - re-run: ${t.command??"command"}`,h=O(u).trimEnd();return{output:[l,f,h].filter(Boolean).join(`
|
|
52
|
+
`),detected:!0,lossy:!0,totalItems:s,keptItems:c.length,handle:d}}function Tt(e){let t=e;for(let n of dc)t=n.apply(t);return t}async function fc(e,t){return await pc(e,t)}async function mc(e,t){return await pc(e,t)}async function pc(e,t){let n=op(e),r=mp(n,["cwd"])||t.cwd;if(!await(t.isEnabled??ip)(r))return{kind:"passthrough",reason:"disabled"};let i=pp(n,"tool_response");if(!i)return{kind:"passthrough",reason:"missing-output"};if(typeof i.output!="string")return{kind:"passthrough",reason:"missing-output"};let o=i.output,c=(t.normalize??Tt)(o);return c===o?{kind:"passthrough",reason:"no-change"}:{kind:"normalized",output:c}}function gc(e){return e.kind==="normalized"?{stdout:JSON.stringify({tool_response:{output:e.output}}),status:0}:{stdout:"",status:0}}function hc(e){return{stdout:"",status:0}}async function np(e){let t=e?dr(e,"utf8"):dr(0,"utf8"),n=await fc(t,{cwd:process.cwd()}),r=gc(n);return r.stdout&&process.stdout.write(r.stdout),r.status}async function rp(e){let t=e?dr(e,"utf8"):dr(0,"utf8"),n=await mc(t,{cwd:process.cwd()}),r=hc(n);return r.stdout&&process.stdout.write(r.stdout),r.status}function sp(e){let t="",n=0;for(;n<e.length;){let r=e.charCodeAt(n);if(r===27){let s=e.charCodeAt(n+1);if(s===93){for(n+=2;n<e.length;){let i=e.charCodeAt(n);if(i===7){n++;break}if(i===27&&e.charCodeAt(n+1)===92){n+=2;break}n++}continue}if(s===91){for(n+=2;n<e.length&&rc(e.charCodeAt(n));)n++;n<e.length&&n++;continue}n+=s>=32?2:1;continue}if(r===155){for(n++;n<e.length&&rc(e.charCodeAt(n));)n++;n<e.length&&n++;continue}t+=e[n++]}return t}function rc(e){return e>=32&&e<=63}function ip(e){return ke(e,process.env).enabled}function op(e){try{let t=JSON.parse(e);return Ae(t)?t:{}}catch{return{}}}function ap(e){let t=e.trim();if(!t)return null;try{let r=JSON.parse(t);return Ae(r)||Array.isArray(r)?{value:r}:null}catch{}let n=[];for(let r of e.split(/\r?\n/))if(r.trim())try{n.push(JSON.parse(r))}catch{return null}return n.length>0?{value:n}:null}function cp(e,t){if(e.length<=t)return[...e];let n=new Set,r=Math.max(1,Math.floor(t*.2));for(let i=0;i<r;i++)n.add(i),n.add(e.length-1-i);for(let i=0;i<e.length;i++)up(e[i])&&n.add(i);for(let i of lp(e))n.add(i);for(let i of dp(e))n.add(i);let s=Math.max(1,Math.floor(e.length/Math.max(1,t-n.size)));for(let i=0;n.size<t&&i<s;i++)for(let o=i;n.size<t&&o<e.length;o+=s)n.add(o);return[...n].sort((i,o)=>i-o).slice(0,t).map(i=>e[i])}function up(e){if(!Ae(e))return!1;let t=e.level;if(typeof t=="string"&&t.toLowerCase()==="error"||Object.prototype.hasOwnProperty.call(e,"error")&&e.error)return!0;let n=e.status;return typeof n=="number"&&n>=400}function lp(e){let t=new Map;e.forEach((r,s)=>{if(Ae(r))for(let[i,o]of Object.entries(r)){if(typeof o!="number"||!Number.isFinite(o))continue;let a=t.get(i)??[];a.push({index:s,value:o}),t.set(i,a)}});let n=new Set;for(let r of t.values()){if(r.length<3)continue;let s=r.reduce((a,c)=>a+c.value,0)/r.length,i=r.reduce((a,c)=>a+Math.pow(c.value-s,2),0)/r.length,o=Math.sqrt(i);if(o!==0)for(let a of r)Math.abs(a.value-s)>o*2&&n.add(a.index)}return[...n]}function dp(e){let t=new Set;for(let n=1;n<e.length;n++){let r=e[n-1],s=e[n];if(!(!Ae(r)||!Ae(s)))for(let[i,o]of Object.entries(s)){if(typeof o!="number"||!Number.isFinite(o))continue;let a=r[i];typeof a!="number"||!Number.isFinite(a)||(a===0?Math.abs(o)>10:Math.abs((o-a)/a)>=2)&&t.add(n)}}return[...t]}function fp(e){return Math.ceil(e.length/4)}function sc(e,t){return e==null?t:Number.isFinite(e)&&e>0?Math.floor(e):t}function mp(e,t){let n=e;for(let r of t){if(!Ae(n))return"";n=n[r]}return typeof n=="string"?n:""}function pp(e,t){let n=e[t];return Ae(n)?n:null}function Ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function As(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!=typeof t||typeof e!="object"||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)){let o=t;return e.length!==o.length?!1:e.every((a,c)=>As(a,o[c]))}let n=e,r=t,s=Object.keys(n),i=Object.keys(r);return s.length!==i.length?!1:s.every(o=>Object.prototype.hasOwnProperty.call(r,o)&&As(n[o],r[o]))}var ic,oc,ac,cc,lc,ep,tp,dc,pn=S(()=>{"use strict";oe();ue();ic={id:"ansi",apply:sp},oc={id:"cr-progress",apply:e=>e.split(`
|
|
46
53
|
`).map(t=>{let n=t.endsWith("\r")?t.slice(0,-1):t,r=n.lastIndexOf("\r");return r>=0?n.slice(r+1):n}).join(`
|
|
47
|
-
`)},
|
|
54
|
+
`)},ac={id:"trailing-whitespace",apply:e=>e.split(`
|
|
48
55
|
`).map(t=>t.replace(/[ \t]+$/,"")).join(`
|
|
49
|
-
`)},
|
|
56
|
+
`)},cc={id:"blank-lines",apply:e=>e.replace(/\n{3,}/g,`
|
|
50
57
|
|
|
51
|
-
`)};
|
|
52
|
-
`),s=
|
|
58
|
+
`)};lc={id:"json-to-toon",apply:e=>uc(e)},ep=200,tp=15;dc=[ic,oc,ac,cc,lc]});var kc={};B(kc,{REPO_STORE_PATH:()=>Ms,mergeRspBlock:()=>_c,provisionRspRepoStore:()=>Ep});import{constants as gp}from"node:fs";import{access as hp,copyFile as yp,mkdir as yc,readFile as wp,rename as bp,writeFile as wc}from"node:fs/promises";import{dirname as _p,join as gn,resolve as Rp}from"node:path";async function Ep(e,t={}){let n=Rp(e),r=gn(n,".red"),s=gn(r,"config.yaml"),i=gn(n,Ms);await yc(r,{recursive:!0}),await yc(_p(i),{recursive:!0});let o="";try{o=await wp(s,"utf8")}catch(h){if(h.code!=="ENOENT")throw h}let a=_c(o,{enabled:!0,ttlDays:t.ttlDays??_e,ephemeralTtlHours:t.ephemeralTtlHours??Re,byteBudget:t.byteBudget??Se,heavyGitByteThreshold:t.heavyGitByteThreshold??be}),c=a!==o;c&&await wc(s,a,"utf8");let u=!await Ls(i),l=!1,d=!1;if(u){let h=gn(n,Sp),g=gn(n,kp);if(await Ls(h))await bp(h,i),d=!0;else if(await Ls(g))await yp(g,i),l=!0;else{let{RspElisionStore:m}=await Promise.resolve().then(()=>(ze(),en)),p=process.env.REDDB_BIN;try{await(await m.open({uri:`file://${i}`,ttlDays:t.ttlDays??_e,ephemeralTtlHours:t.ephemeralTtlHours??Re,byteBudget:t.byteBudget??Se,allowResidentOpen:!0})).close()}finally{p===void 0?delete process.env.REDDB_BIN:process.env.REDDB_BIN=p}}}let f=xp(a,Ms);return f!==a&&await wc(s,f,"utf8"),{configPath:s,storePath:i,configChanged:c||f!==a,storeCreated:u,memoryStoreMigrated:l,legacyStoreMigrated:d}}function _c(e,t){let n=["rsp:",` enabled: ${t.enabled?"true":"false"}`,` ttlDays: ${fr(t.ttlDays,_e)}`,` ephemeralTtlHours: ${fr(t.ephemeralTtlHours,Re)}`,` byteBudget: ${fr(t.byteBudget,Se)}`,` heavyGitByteThreshold: ${fr(t.heavyGitByteThreshold,be)}`],r=e===""?[]:e.replace(/\n+$/,"").split(`
|
|
59
|
+
`),s=Rc(r,"rsp");if(s===-1){let a=[...r];return a.length>0&&a[a.length-1].trim()!==""&&a.push(""),a.push(...n),`${a.join(`
|
|
53
60
|
`)}
|
|
54
|
-
`}let i=
|
|
61
|
+
`}let i=js(r,s,0);return`${[...r.slice(0,s),...n,...r.slice(i)].join(`
|
|
55
62
|
`)}
|
|
56
|
-
`}function
|
|
57
|
-
`),r=
|
|
63
|
+
`}function Rc(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(Fs(r)&&Us(r)===0&&Sc(r)===t)return n}return-1}function js(e,t,n){let r=e.length;for(let s=t+1;s<e.length;s++)if(Fs(e[s])&&Us(e[s])<=n){r=s;break}for(;r-1>t&&e[r-1].trim()==="";)r--;return r}function Us(e){return(e.match(/^ */)?.[0]??"").length}function Fs(e){let t=e.trim();return t!==""&&!t.startsWith("#")}function Sc(e){return e.replace(/^ */,"").replace(/:.*$/,"").trim()}function fr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function xp(e,t){let n=e===""?[]:e.replace(/\n+$/,"").split(`
|
|
64
|
+
`),r=Rc(n,"plugins");if(r===-1)return e;let s=js(n,r,0),i=bc(n,"memory",r+1,s,2);if(i===-1)return e;let o=js(n,i,2),a=[...n],c=bc(a,"storePath",i+1,o,4);return c!==-1?a[c]=` storePath: ${t}`:a.splice(o,0,` storePath: ${t}`),`${a.join(`
|
|
58
65
|
`)}
|
|
59
|
-
`}function
|
|
66
|
+
`}function bc(e,t,n,r,s){for(let i=n;i<r;i++){let o=e[i];if(Fs(o)&&Us(o)===s&&Sc(o)===t)return i}return-1}async function Ls(e){try{return await hp(e,gp.F_OK),!0}catch{return!1}}var Ms,Sp,kp,Ec=S(()=>{"use strict";De();ue();Ms=ms,Sp=to,kp=".red/memory/graph.rdb"});var Dc={};B(Dc,{runRspMcpServer:()=>vp});import{createInterface as Tp}from"node:readline";async function vp(){let e=ke(process.cwd(),process.env),t=Tp({input:process.stdin,crlfDelay:1/0});for await(let n of t){if(!n.trim())continue;let r;try{r=JSON.parse(n);let s=await Pp(r,e);Pc({jsonrpc:"2.0",id:r.id??null,result:s})}catch(s){Pc({jsonrpc:"2.0",id:typeof Oc(n)?.id>"u"?null:Oc(n)?.id,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}})}}}async function Pp(e,t){if(e.method==="initialize")return{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"rsp",version:"0.1.0"}};if(e.method==="tools/list")return t.enabled?{tools:[{name:"rsp_status",description:"Explain whether rsp is enabled in this directory.",inputSchema:{type:"object",properties:{}}},{name:"rsp_stats",description:"Read resident rsp accounting stats.",inputSchema:{type:"object",properties:{}}},{name:"rsp_show",description:"Read an rsp elision handle through the resident server.",inputSchema:{type:"object",properties:{handle:{type:"string"}},required:["handle"]}},{name:"rsp_compress",description:"Compress arbitrary text or JSON through rsp normalization, JSON selection, TOON rendering, and reversible elision.",inputSchema:{type:"object",properties:{payload:{description:"Text, JSON value, or JSON-serializable payload to compress."},level:{type:"string",enum:["brief","terse"],description:"Compression level. Defaults to brief."}},required:["payload"]}}]}:{tools:[{name:"rsp_status",description:"Explain whether rsp is enabled in this directory.",inputSchema:{type:"object",properties:{}}}]};if(e.method==="tools/call"){let n=e.params;if(n?.name==="rsp_status")return{content:[{type:"text",text:vc(t)}]};if(!t.enabled)return{content:[{type:"text",text:vc(t)}],isError:!0};let r=Np(t);if(n?.name==="rsp_stats")return{content:[{type:"text",text:JSON.stringify(await r.accountingStats(t.telemetryByteBudget))}]};if(n?.name==="rsp_show"){let s=String(n.arguments?.handle??""),i=await r.get(s);return i?"status"in i?{content:[{type:"text",text:JSON.stringify(i)}],isError:!0}:{content:[{type:"text",text:i.original.toString("utf8")}]}:{content:[{type:"text",text:"not found"}],isError:!0}}if(n?.name==="rsp_compress")return{content:[{type:"text",text:await Op(n.arguments,r)}]}}return{}}async function Op(e,t){let n=Dp(e?.payload),r=Ip(e?.level),s=await mn(n,{level:r,command:"rsp mcp compress",store:t});if(s.detected)return xc(s.output);let i=Tt(n);if(r==="brief"&&Buffer.byteLength(i)<=2*1024)return xc(i);let o=Buffer.from(n),a=await t.mint(o,{command:"rsp mcp compress",loss:{level:r,bytes_elided:o.length}});return $p(i,o.length,a,r)}function Dp(e){return typeof e=="string"?e:e==null?"":JSON.stringify(e)}function Ip(e){return e==="terse"?"terse":"brief"}function $p(e,t,n,r){let s=r==="terse"?1024:2048,i=Buffer.from(e),o=Math.max(1,Math.floor(s/2)),a=Tc(i.subarray(0,o)),c=Tc(i.subarray(Math.max(0,i.length-o))),u=["payload summary",`bytes: ${t}`,`lines: ${Cp(i)}`,"head:",a];return c&&c!==a&&u.push("tail:",c),u.push(`\u2026 elided payload (+${t}) \u2014 rsp show ${n}`),`${u.join(`
|
|
60
67
|
`)}
|
|
61
|
-
`}function
|
|
68
|
+
`}function xc(e){return e.endsWith(`
|
|
62
69
|
`)?e:`${e}
|
|
63
|
-
`}function
|
|
64
|
-
`)}function
|
|
65
|
-
`),0;if(!
|
|
66
|
-
`),await
|
|
67
|
-
`)}function
|
|
68
|
-
`,"utf8")}async function
|
|
69
|
-
`)}function
|
|
70
|
-
`)}function Yn(e,t){if(t.length===0)return[];if(t.some(i=>i.command.length===1))return[`${e}() {`," if command -v rsp >/dev/null 2>&1; then",` command rsp ${e} "$@"`," return"," fi",` command ${e} "$@"`,"}"];let n=t.map(i=>i.command.slice(1)).filter(i=>i.length===1).map(i=>i[0]).filter(Qn),r=t.map(i=>i.command.slice(1)).filter(i=>i.length>1&&i.every(Qn)),s=[`${e}() {`," if ! command -v rsp >/dev/null 2>&1; then",` command ${e} "$@"`," return"," fi",' case "$1" in'];if(n.length>0){let i=n.map(o=>Va(o)).join("|");s.push(` ${i}) command rsp ${e} "$@" ;;`)}for(let[i,o]of Ym(r)){let a=o.map(c=>c.map((u,l)=>`[ "$${l+2}" = '${Xm(u)}' ]`).join(" && ")).join(" || ");s.push(` ${Va(i)}) if ${a}; then command rsp ${e} "$@"; else command ${e} "$@"; fi ;;`)}return s.push(` *) command ${e} "$@" ;;`," esac","}"),s}function Ym(e){let t=new Map;for(let[n,...r]of e){if(!n)continue;let s=t.get(n)??[];s.push(r),t.set(n,s)}return t}function Qm(e){let t=new Map;for(let n of e){let r=n.command[0];if(!r||!Qn(r))continue;let s=t.get(r)??[];s.push(n),t.set(r,s)}return t}function Qn(e){return!!(e&&/^[A-Za-z0-9_./:-]+$/.test(e))}function Va(e){return e.replace(/[\\|)&;]/g,"\\$&")}function Xm(e){return e.replace(/'/g,"'\\''")}function Zm(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}var za=S(()=>{"use strict";Hn()});function vs(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.id=="string"&&t.id.length>0&&typeof t.emitter=="string"&&t.emitter.length>0&&typeof t.occurredAt=="string"&&typeof t.taskClass=="string"&&ep(t.chosenOption)&&tp(t.outcome)&&np(t.cost)}function ep(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function tp(e){return e==="success"||e==="failure"||e==="escalated"}function np(e){if(typeof e!="object"||e===null)return!1;let t=e.signal;return t==="none"||t==="low"||t==="medium"||t==="high"||t==="unknown"}var Ya=S(()=>{});import{createHash as rp}from"node:crypto";function cc(e,t){return new Ps(e,t)}function Qa(e){let t=Number(e.red_entity_id??e.rid),n=Ds(e.properties??e.PROPERTIES),r=uc(String(e.node_type??e.NODE_TYPE??n.kind??"note"));if(!Number.isFinite(t))return null;let s=String(n.id??e.label??e.LABEL??t),i=String(n.title??e.label??e.LABEL??s),o=String(n.content??""),a=Array.isArray(n.tags)?n.tags.map(String):[],c=Date.now();return{rid:t,label:String(e.label??e.LABEL??s),kind:r,properties:{...n,id:s,title:i,content:o,tags:a,created_at:Number(n.created_at??c),updated_at:Number(n.updated_at??n.created_at??c),hash:String(n.hash??"")}}}function Xa(e){let t=Number(e.red_entity_id??e.rid),n=Number(e.from??e.FROM??e.from_rid??e.source),r=Number(e.to??e.TO??e.to_rid??e.target),s=lc(String(e.label??e.LABEL??"related_to"));return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)?null:{rid:t,kind:s,from_rid:n,to_rid:r,weight:Number(e.weight??1),properties:Ds(e.properties??e.PROPERTIES)}}function op(e){let t=Number(e.red_entity_id??e.rid),n=Ds(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!vs(n)?null:{rid:t,event:n}}function Ds(e){return e==null?{}:typeof e=="string"?JSON.parse(e):Xn(e)?e:{}}function uc(e){let t=e==="contact"?"person":e;if(sp.has(t))return t;throw new Error(`invalid Brain artifact kind: ${e}`)}function lc(e){if(ip.has(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function ap(e){return e==="hour"||e==="week"||e==="month"?e:"day"}function Za(e){if(typeof e=="number")return e;let t=String(e??"");return/^\d+$/.test(t)?Number(t):t}function ze(e){return Xn(e)?e:{}}function ec(e,t){return ze(e)[t]}function tc(e,t){let n=e[t];if(typeof n!="string")throw new Error(`brain ${t} must be a string`);return n}function nc(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function rc(e){let t=ze(e);return{excludeRids:Array.isArray(t.excludeRids)?t.excludeRids.map(Number).filter(Number.isFinite):void 0}}function j(e){return typeof e=="string"&&e.length>0?e:void 0}function Xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Os(e){return e!=null}function cp(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function up(e){return rp("sha256").update(JSON.stringify(e)).digest("hex")}function lp(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"artifact"}function sc(e){return`artifact-hash:${e}`}function ic(e,t,n){return`connection:${e}:${t}:${n}`}function oc(){return"model-tier-bandit:v1"}function dp(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function ac(e,t){let n=0,r=e.indexOf(t);for(;r>=0;)n++,r=e.indexOf(t,r+t.length);return n}function dc(e,t){let n=e.properties.title.toLowerCase(),r=e.properties.content.toLowerCase(),s=e.properties.tags.map(o=>o.toLowerCase()),i=e.kind.toLowerCase();return{lexical:t.reduce((o,a)=>o+ac(n,a)*3+ac(r,a),0),tags:t.reduce((o,a)=>o+s.reduce((c,u)=>c+(u===a?4:u.includes(a)||a.includes(u)?2:0),0),0),kind:t.reduce((o,a)=>o+(i===a?3:i.includes(a)||a.includes(i)?1:0),0)}}function fp(e,t,n,r){let s=0;for(let i of n){let o=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(o==null)continue;let a=r.get(o);if(!a)continue;let c=fc({...dc(a,t),connections:0,vector:0}).total;c>0&&(s+=Math.min(c,12)*.35)}return Ke(s)}function fc(e){return{...e,lexical:Ke(e.lexical),tags:Ke(e.tags),kind:Ke(e.kind),connections:Ke(e.connections),vector:Ke(e.vector),total:Ke(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function Ke(e){return Math.round(e*1e3)/1e3}function mp(e,t){if(e.length<=220)return e;let n=e.toLowerCase(),r=t.map(i=>n.indexOf(i)).filter(i=>i>=0).sort((i,o)=>i-o)[0]??0,s=Math.max(0,r-80);return`${s>0?"...":""}${e.slice(s,s+220)}${s+220<e.length?"...":""}`}function pp(e,t){let n=t.length===0?"none":t[0].score>=5?"high":t[0].score>=3?"medium":"low",r=t.length===0?[`No Brain artifacts matched "${e}".`]:[];return{answer:t.length===0?`Brain has no cited evidence for "${e}".`:`Brain found ${t.length} cited artifact${t.length===1?"":"s"} for "${e}".`,hits:t,citations:t.map((s,i)=>({ref:`B${i+1}`,rid:s.artifact.rid,id:s.artifact.properties.id,title:s.artifact.properties.title,kind:s.artifact.kind,score:s.score,score_breakdown:s.score_breakdown,excerpt:s.excerpt})),confidence:n,missing_evidence:r}}function gp(e){let t={};for(let n of e)t[n]=(t[n]??0)+1;return t}var oe,sp,ip,Ps,mc=S(()=>{"use strict";Ya();oe={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"},sp=new Set(["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"]),ip=new Set(["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"]),Ps=class{constructor(t,n){this.db=t;this.uri=n}async request(t,n){if(await this.bootstrap(),t==="status")return await this.status();if(t==="capture")return await this.capture(ze(n));if(t==="getArtifact")return await this.getArtifact(ec(n,"ridOrId"));if(t==="listArtifacts")return await this.listArtifacts();if(t==="search"){let r=ze(n);return await this.search(tc(r,"query"),nc(r,"limit")??10,rc(r.options))}if(t==="think"){let r=ze(n);return await this.think(tc(r,"query"),nc(r,"limit")??8,rc(r.options))}if(t==="link")return await this.link(ze(n));if(t==="backlinks")return await this.backlinks(ec(n,"target"));if(t==="listConnections")return await this.listConnections();if(t==="eventKpis")return await this.eventKpis(ze(n));if(t==="appendOutcomeEvent")return await this.appendOutcomeEvent(n);if(t==="replayOutcomeEvents")return await this.replayOutcomeEvents();if(t==="loadModelTierBanditDocument")return await this.loadModelTierBanditDocument();if(t==="saveModelTierBanditDocument")return await this.saveModelTierBanditDocument(n);if(t==="refreshModelTierBanditDocument")return await this.refreshModelTierBanditDocument();throw new Error(`unsupported resident brain action: ${t}`)}async bootstrap(){await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${oe.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${oe.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${oe.outcomeEvents}`)}async status(){let t=await this.listArtifacts(),n=await this.listConnections();return{uri:this.uri,artifacts:t.length,connections:n.length,kinds:gp(t.map(r=>r.kind))}}async capture(t){let n=j(t.title)||"Untitled artifact",r=j(t.content);if(!r)throw new Error("brain capture requires content");let s=uc(j(t.kind)||"note"),i=cp(Array.isArray(t.tags)?t.tags.map(String):[]),o=Date.now(),a=up([s,n,r,i,j(t.sourcePath),j(t.sourceSession)]),c=await this.kv().get(sc(a));if(c!=null){let g=await this.getArtifact(Number(c));if(g)return g}let u=`${lp(n)}-${a.slice(0,8)}`,l={id:u,title:n,content:r,tags:i,source_agent:j(t.sourceAgent),source_runner:j(t.sourceRunner),source_session:j(t.sourceSession),source_path:j(t.sourcePath),created_at:o,updated_at:o,hash:a,metadata:Xn(t.metadata)?t.metadata:void 0},f=(await this.db.query(`INSERT INTO ${oe.artifacts} NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *`,u,s,a,l)).rows[0];if(!f)throw new Error("INSERT artifact returned no row");let y=Qa(f);if(!y)throw new Error("INSERT artifact returned invalid row");return await this.kv().put(sc(a),y.rid),await this.materializeTagConnections(y),y}async getArtifact(t){let n=await this.listArtifacts();return typeof t=="number"?n.find(r=>r.rid===t)??null:n.find(r=>r.properties.id===t||r.label===t)??null}async listArtifacts(){return(await this.db.query(`SELECT * FROM ${oe.artifacts}`)).rows.map(Qa).filter(Os)}async search(t,n,r={}){let s=dp(t),i=new Set(r.excludeRids??[]),o=await this.listArtifacts(),a=await this.listConnections(),c=new Map(o.map(u=>[u.rid,u]));return o.filter(u=>!i.has(u.rid)).map(u=>{let l=dc(u,s),d=fc({...l,connections:fp(u,s,a,c),vector:0});return{artifact:u,score:d.total,score_breakdown:d,excerpt:mp(u.properties.content,s)}}).filter(u=>u.score>0).sort((u,l)=>l.score-u.score||l.artifact.properties.updated_at-u.artifact.properties.updated_at).slice(0,Math.max(1,Math.min(100,n)))}async think(t,n,r={}){let s=(await this.search(t,Math.max(n*2,n+5),r)).slice(0,n);return pp(t,s)}async link(t){let n=await this.getArtifact(Za(t.from)),r=await this.getArtifact(Za(t.to));if(!n)throw new Error(`Brain artifact not found: ${String(t.from)}`);if(!r)throw new Error(`Brain artifact not found: ${String(t.to)}`);let s=lc(j(t.kind)||"related_to"),i=await this.findConnection(n.rid,r.rid,s);if(i!=null){let l=(await this.listConnections()).find(d=>d.rid===i);if(l)return l}let o={reason:j(t.reason),confidence:j(t.confidence)||"explicit",created_at:Date.now(),metadata:Xn(t.metadata)?t.metadata:void 0},c=(await this.db.query(`INSERT INTO ${oe.connections} EDGE (label, from, to, weight, properties) VALUES ($1, $2, $3, $4, $5) RETURNING *`,s,n.rid,r.rid,1,o)).rows[0];if(!c)throw new Error("INSERT connection returned no row");let u=Xa(c);if(!u)throw new Error("INSERT connection returned invalid row");return await this.kv().put(ic(n.rid,r.rid,s),u.rid),u}async backlinks(t){let n=await this.getArtifact(t);if(!n)throw new Error(`Brain artifact not found: ${t}`);return(await this.listConnections()).filter(r=>r.to_rid===n.rid)}async listConnections(){return(await this.db.query(`SELECT * FROM ${oe.connections}`)).rows.map(Xa).filter(Os)}async eventKpis(t){let n=(await this.listArtifacts()).filter(i=>i.kind==="event"),r=ap(j(t.interval)||"day"),s=j(t.timeField)==="ingested"?"ingested":"event";return{kind:"event",interval:r,timeField:s,range:{from:null,to:null},total:n.length,series:[{group:null,total:n.length,buckets:[]}]}}async appendOutcomeEvent(t){if(!vs(t))throw new Error("invalid Brain outcome event");if(!(await this.db.query(`INSERT INTO ${oe.outcomeEvents} NODE (label, node_type, properties) VALUES ($1, $2, $3) RETURNING *`,t.id,`outcome_event.v${t.schemaVersion}`,t)).rows[0])throw new Error("INSERT outcome event returned no row");return t}async replayOutcomeEvents(){return(await this.db.query(`SELECT * FROM ${oe.outcomeEvents}`)).rows.map(op).filter(Os).sort((n,r)=>n.rid-r.rid).map(({event:n})=>n)}async loadModelTierBanditDocument(){let t=await this.kv().get(oc());return typeof t=="string"?JSON.parse(t):t}async saveModelTierBanditDocument(t){return await this.kv().put(oc(),JSON.stringify(t)),t}async refreshModelTierBanditDocument(){let t=await this.loadModelTierBanditDocument();if(t!=null)return t;let n={schema_version:"brain.model-tier-bandit.v1",updated_at:new Date().toISOString(),arms:{}};return await this.saveModelTierBanditDocument(n),n}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let n of t.properties.tags){let r=await this.capture({title:n,content:`Tag: ${n}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:r.rid,kind:"tagged",confidence:"derived"})}}async findConnection(t,n,r){let s=await this.kv().get(ic(t,n,r));return s!=null?Number(s):null}kv(){return this.db.kv(oe.kv)}}});var Tc={};C(Tc,{runResidentServer:()=>Ep});import{randomUUID as yt}from"node:crypto";import{execFileSync as hp,spawn as yp}from"node:child_process";import{existsSync as wp}from"node:fs";import{mkdir as _c,rename as bp,rm as pc,writeFile as Rc}from"node:fs/promises";import{createServer as _p}from"node:net";import{dirname as Ns,join as rn}from"node:path";import{fileURLToPath as Rp,pathToFileURL as Sp}from"node:url";async function Ep(e){await _c(Ns(e.socketPath),{recursive:!0});let t=Ap();Bp();let n=e.telemetryDrainTimeoutMs??Sc,r={kind:"opening",startedAt:process.hrtime.bigint()},s,i=!1,o=e.idleMs??vn,a,c,u=!1,l=new Set,d=e.telemetryDrainIntervalMs??3e4,f=_p(x=>{l.add(x),x.once("close",()=>l.delete(x)),g(),qp(x,async O=>{g();let N=await Jp(r,O,e.storeUri,e.residentVersion??"0.0.0-dev"),F={id:O.id,ok:!0,value:N,storeOpenCount:r.kind==="ready"?r.storeOpenCount:void 0,storeElapsedMs:r.kind==="ready"?r.storeElapsedMs:void 0};xc(x,F),O.op==="handover"&&setImmediate(()=>y())})});function y(){i=!0,u=!0,c=Np(c),f.close();for(let x of l)x.destroy()}function g(){r.kind!=="opening"&&(a&&clearTimeout(a),a=setTimeout(()=>{y()},o),a.unref())}let p=["SIGINT","SIGTERM"].map(x=>{let O=()=>{Zn(),f.close();for(let N of l)N.destroy();setTimeout(()=>process.exit(0),1e3)};return process.once(x,O),{signal:x,handler:O}});await new Promise((x,O)=>{f.once("error",O),f.listen(e.socketPath,()=>{f.off("error",O),x()})}),(async()=>{let x=process.hrtime.bigint();process.env.RSP_TEST_HANG_RESIDENT_STORE_OPEN==="1"&&await new Promise(()=>{});let O=Number(process.env.RSP_TEST_DELAY_RESIDENT_STORE_OPEN_MS??"0");Number.isFinite(O)&&O>0&&await new Promise($=>setTimeout($,O));let N=await Gt.open({uri:e.storeUri,ttlDays:e.ttlDays,ephemeralTtlHours:e.ephemeralTtlHours,byteBudget:e.byteBudget,allowResidentOpen:!0}),F=Number(process.hrtime.bigint()-x)/1e6,z=new Cs(N,{rootDir:e.rootDir??process.cwd(),ttlDays:e.telemetryTtlDays??xn,byteBudget:e.telemetryByteBudget??e.byteBudget??Tn});if(i){await N.close();return}if(await Is(z,n),i){await N.close();return}r={kind:"ready",store:N,telemetry:z,storeOpenCount:1,storeElapsedMs:F},s=setInterval(()=>{let $=r.kind==="ready"?r:void 0;$&&Is($.telemetry,n)},d),s.unref(),g()})().catch(x=>{r={kind:"failed",error:x instanceof Error?x:new Error(String(x))},g()}),e.pidPath&&await Rc(e.pidPath,`${process.pid}
|
|
71
|
-
`,{encoding:"utf8",mode:384});let
|
|
72
|
-
`,{encoding:"utf8",mode:384}),await
|
|
73
|
-
`)}}async function
|
|
70
|
+
`}function Tc(e){return e.toString("utf8").replace(/�$/g,"")}function Cp(e){if(e.length===0)return 0;let t=0;for(let n of e)n===10&&t++;return e[e.length-1]===10?t:t+1}function Np(e){return new cn($e(process.cwd()),{storeUri:e.storeUri,ttlDays:e.ttlDays,ephemeralTtlHours:e.ephemeralTtlHours,byteBudget:e.byteBudget,telemetryTtlDays:e.telemetryTtlDays,telemetryByteBudget:e.telemetryByteBudget,telemetryDrainIntervalMs:e.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:e.telemetryDrainTimeoutMs,idleMs:e.idleMs})}function vc(e){return e.enabled?"rsp is enabled in this directory":"rsp is not enabled in this directory; run /red-setup"}function Pc(e){process.stdout.write(`${JSON.stringify(e)}
|
|
71
|
+
`)}function Oc(e){try{return JSON.parse(e)}catch{return null}}var Ic=S(()=>{"use strict";ue();pn();Xe()});var jc={};B(jc,{renderWaitHelp:()=>Hs,runWait:()=>Fp});import{spawn as Vs}from"node:child_process";import{existsSync as Js}from"node:fs";import{mkdir as Ap,readdir as Bp,readFile as Lp,rm as Ac,writeFile as Mp}from"node:fs/promises";import{join as yn,resolve as Gs}from"node:path";import{randomUUID as jp}from"node:crypto";async function Fp(e,t=process.cwd()){let n=qp(e);if(n.kind==="help"||e.includes("--help")||e.includes("-h"))return process.stdout.write(Hs()),0;if(n.kind==="ls")return process.stdout.write(`${ye({waits:await Qp(t)})}
|
|
72
|
+
`),0;if(!Gp(n.kind))return process.stdout.write(Hs()),2;let r=n.kind,s={id:jp(),target:tg(n),reason:n.options.reason,pid:process.pid,started_at:new Date().toISOString(),poll_tier:Up[n.kind],status:"running"},i=yn(await Ws(t),`${s.id}.json`),o={status:"indeterminate",exitCode:2,summary:"wait did not start"};try{return await Ap(await Ws(t),{recursive:!0}),await Bc(i,s),o=await Jp({...n,kind:r},t,i,s),process.stdout.write(`${ye(eg(r,s,o))}
|
|
73
|
+
`),await Zp(n.options),o.exitCode}finally{await Ac(i,{force:!0})}}function Gp(e){return e==="cmd"||e==="pr"||e==="run"||e==="release"}function Hs(){return["usage: rsp wait <subcommand> [options]","","Subcommands:"," rsp wait pr <number> [--timeout 45m] [--reason <text>]"," rsp wait run <id|--branch <branch> --latest> [--timeout 45m]"," rsp wait release [--tag <glob>] [--timeout 2h]",' rsp wait cmd -- "<command line>" [--timeout 30m]'," rsp wait ls","","Examples:",' rsp wait pr 123 --reason "before merge"'," rsp wait run --branch feature/wait --latest",' rsp wait release --tag "v2.*"',' rsp wait cmd -- "pnpm -C apps/rsp build"'," rsp wait ls","","Doctrine: never hand-write sleep polling loops; run rsp wait in a background shell - process exit IS the signal.","Exit codes: 0 = success verdict, 1 = failure verdict, 2 = timeout/indeterminate.",'Completion hooks: --signal-pid <pid> [--signal USR1] and --notify-cmd "<cmd>" run after a verdict.',""].join(`
|
|
74
|
+
`)}function qp(e){let t=e[1],n={timeoutMs:$c.cmd,reason:"",signal:"SIGUSR1"},r={kind:t,options:n};if(!t||t==="--help"||t==="-h")return{...r,kind:"help"};if(t==="ls")return r;if(t!=="cmd"&&t!=="pr"&&t!=="run"&&t!=="release")return{...r,kind:void 0};n.timeoutMs=$c[t];let s=e.indexOf("--"),i=s>=0?s:e.length;for(let o=2;o<i;o++){let a=e[o];a==="--timeout"?n.timeoutMs=Lc(e[++o]??""):a==="--reason"?n.reason=e[++o]??"":a==="--signal-pid"?n.signalPid=Number(e[++o]):a==="--signal"?n.signal=sg(e[++o]??""):a==="--notify-cmd"?n.notifyCmd=e[++o]??"":t==="run"&&a==="--branch"?r.branch=e[++o]??"":t==="run"&&a==="--latest"?r.latest=!0:t==="release"&&a==="--tag"?r.tagGlob=e[++o]??"":!a.startsWith("--")&&!r.target&&(r.target=a)}return t==="cmd"&&(r.commandLine=s>=0?e.slice(s+1).join(" "):""),r}async function Jp(e,t,n,r){switch(e.kind){case"cmd":return await Hp(e.commandLine??"",e.options.timeoutMs,t,n,r);case"pr":return await qs(Wp(e.target??"",t,{emptyChecksGraceMs:Nc("RSP_WAIT_PR_EMPTY_CHECKS_GRACE_MS",3e4)}),e.options.timeoutMs,Nc("RSP_WAIT_PR_POLL_MS",15e3),n,r);case"run":return await qs(()=>Kp(e,t),e.options.timeoutMs,15e3,n,r);case"release":return await qs(()=>Yp(e.tagGlob,new Date(r.started_at),t),e.options.timeoutMs,6e4,n,r)}}async function Hp(e,t,n,r,s){return e.trim()?await new Promise(i=>{let o=!1,a=l=>{o||(o=!0,i(l))},c=Vs(e,{cwd:n,shell:!0,stdio:"ignore",detached:!1}),u=setTimeout(()=>{c.kill("SIGTERM"),hn(r,s,"timeout"),a({status:"timeout",exitCode:2,summary:`command timed out after ${Mc(t)}`})},t);c.once("error",l=>{clearTimeout(u),hn(r,s,"failure"),a({status:"failure",exitCode:1,summary:l.message})}),c.once("close",(l,d)=>{if(clearTimeout(u),o)return;let f=l===0;hn(r,s,f?"success":"failure"),a({status:f?"success":"failure",exitCode:f?0:1,summary:f?"command exited successfully":`command exited with ${d??l??"unknown"}`,details:{status:l??null,signal:d??null}})})}):{status:"indeterminate",exitCode:2,summary:"missing command line"}}async function qs(e,t,n,r,s){let i=Date.now()+t,o=0;for(;Date.now()<i;){let a=await e();if(a.status!=="running"&&a.status!=="indeterminate")return await hn(r,s,a.status),a;let c=Math.min(n*4,Math.round(n*Math.pow(1.25,o++)))+Math.floor(Math.random()*1e3);await ag(Math.min(c,Math.max(0,i-Date.now())))}return await hn(r,s,"timeout"),{status:"timeout",exitCode:2,summary:`timed out after ${Mc(t)}`}}function Wp(e,t,n){let r=Date.now();return()=>Vp(e,t,n,r)}async function Vp(e,t,n,r){if(!/^[1-9][0-9]*$/.test(e))return{status:"indeterminate",exitCode:2,summary:"missing PR number"};let s=await mr(["pr","view",e,"--json","number,state,mergeable,statusCheckRollup,url"],t);if(s.status!==0)return{status:"indeterminate",exitCode:2,summary:s.stderr||"gh pr view failed"};let i=Ks(s.stdout),o=Array.isArray(i.statusCheckRollup)?i.statusCheckRollup:[],a=String(i.mergeable??""),c=o.map(ng),u=c.filter(d=>d==="failure").length,l=c.filter(d=>d==="pending").length;if(String(i.state)!=="OPEN")return Ze("failure",`PR #${e} is ${String(i.state).toLowerCase()}`,{mergeable:a});if(u>0)return Ze("failure",`PR #${e} has failing checks`,{failing:u,pending:l,mergeable:a});if(l>0)return{status:"running",exitCode:2,summary:`PR #${e} has ${l} pending checks`};if(o.length===0){let d=Date.now()-r;return a==="UNKNOWN"||d<n.emptyChecksGraceMs?{status:"running",exitCode:2,summary:`PR #${e} has no registered checks yet`,details:{checks:0,mergeable:a,empty_checks_elapsed_ms:d}}:Ze("success",`PR #${e} has no checks configured`,{checks:0,mergeable:a})}return a==="UNKNOWN"?{status:"running",exitCode:2,summary:`PR #${e} mergeability is still unknown`,details:{checks:o.length,mergeable:a}}:Ze("success",`PR #${e} checks passed`,{checks:o.length,mergeable:a})}async function Kp(e,t){let n=e.target??(e.latest&&e.branch?await zp(e.branch,t):"");if(!n)return{status:"indeterminate",exitCode:2,summary:"missing run id"};let r=await mr(["run","view",n,"--json","databaseId,status,conclusion,workflowName,headBranch,url"],t);if(r.status!==0)return{status:"indeterminate",exitCode:2,summary:r.stderr||"gh run view failed"};let s=Ks(r.stdout),i=String(s.status??"").toLowerCase(),o=String(s.conclusion??"").toLowerCase();return i!=="completed"?{status:"running",exitCode:2,summary:`run ${n} is ${i||"pending"}`}:o==="success"?Ze("success",`run ${n} succeeded`,Cc(s)):Ze("failure",`run ${n} concluded ${o||"unknown"}`,Cc(s))}async function zp(e,t){let n=await mr(["run","list","--branch",e,"--limit","1","--json","databaseId"],t);if(n.status!==0)return"";let r=JSON.parse(n.stdout),s=Array.isArray(r)?r[0]:void 0;return wn(s)&&s.databaseId!=null?String(s.databaseId):""}async function Yp(e,t,n){let r=await mr(["release","list","--limit","20","--json","tagName,publishedAt,isDraft"],n);if(r.status!==0)return{status:"indeterminate",exitCode:2,summary:r.stderr||"gh release list failed"};let s=JSON.parse(r.stdout),o=(Array.isArray(s)?s.filter(wn):[]).find(a=>{let c=String(a.tagName??""),u=new Date(String(a.publishedAt??""));return a.isDraft!==!0&&(!e||ig(e,c))&&u>=t});return o?Ze("success",`release ${String(o.tagName)} published`,{tag:String(o.tagName),published_at:String(o.publishedAt??"")}):{status:"running",exitCode:2,summary:"no matching release is published yet"}}async function mr(e,t){return await new Promise(n=>{let r=Vs("gh",e,{cwd:t,stdio:["ignore","pipe","pipe"]}),s=[],i=[];r.stdout.on("data",o=>s.push(Buffer.from(o))),r.stderr.on("data",o=>i.push(Buffer.from(o))),r.once("error",o=>n({status:1,stdout:"",stderr:o.message})),r.once("close",o=>{n({status:o??1,stdout:Buffer.concat(s).toString("utf8"),stderr:Buffer.concat(i).toString("utf8").trim()})})})}async function Qp(e){let t=await Ws(e);if(!Js(t))return[];let n=await Bp(t).catch(()=>[]),r=[];for(let s of n.filter(i=>i.endsWith(".json")||i.endsWith(".toon"))){let i=yn(t,s),o=rg(await Lp(i,"utf8").catch(()=>"{}")),a=typeof o.pid=="number"?o.pid:0;if(!a||!og(a)){await Ac(i,{force:!0});continue}r.push(o)}return r}async function Ws(e){return yn(await Xp(e),".red","tmp","waits")}async function Xp(e){let t=Gs(e);for(;;){if(Js(yn(t,".red"))||Js(yn(t,".git")))return t;let n=Gs(t,"..");if(n===t)return Gs(e);t=n}}async function hn(e,t,n){await Bc(e,{...t,status:n}).catch(()=>{})}async function Bc(e,t){await Mp(e,`${ye(t)}
|
|
75
|
+
`,"utf8")}async function Zp(e){if(e.signalPid&&Number.isInteger(e.signalPid)&&e.signalPid>0)try{process.kill(e.signalPid,e.signal)}catch{}e.notifyCmd?.trim()&&await new Promise(t=>{let n=Vs(e.notifyCmd,{shell:!0,stdio:"ignore",detached:!0});n.once("error",()=>t()),n.once("close",()=>t())})}function eg(e,t,n){return{wait:{id:t.id,target:t.target,kind:e,status:n.status,reason:t.reason,started_at:t.started_at,completed_at:new Date().toISOString(),poll_tier:t.poll_tier},verdict:{exit_code:n.exitCode,summary:n.summary,...n.details?{details:n.details}:{}}}}function Ze(e,t,n){return{status:e,exitCode:e==="success"?0:1,summary:t,details:n}}function tg(e){return e.kind==="cmd"?`cmd:${e.commandLine??""}`:e.kind==="run"&&e.branch&&e.latest?`run:${e.branch}:latest`:e.kind==="release"?`release:${e.tagGlob??"*"}`:`${e.kind}:${e.target??""}`}function ng(e){let t=wn(e)?e:{},n=String(t.conclusion??t.state??t.status??"").toLowerCase();return["success","successful","passed","completed","neutral","skipped"].includes(n)?"success":["failure","failed","error","timed_out","cancelled","action_required"].includes(n)?"failure":"pending"}function Cc(e){return{database_id:typeof e.databaseId=="number"?e.databaseId:String(e.databaseId??""),conclusion:String(e.conclusion??""),workflow:String(e.workflowName??""),branch:String(e.headBranch??""),url:String(e.url??"")}}function Ks(e){let t=JSON.parse(e);if(!wn(t))throw new Error("expected JSON object");return t}function rg(e){let t=e.trim();if(!t)return{};try{return Ks(t)}catch{let n=ie(t);if(!wn(n))throw new Error("expected structured object");return n}}function wn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lc(e){let t=/^([1-9][0-9]*)(ms|s|m|h)?$/.exec(e);if(!t)throw new Error(`invalid timeout: ${e}`);let n=Number(t[1]),r=t[2]??"ms";return r==="ms"?n:r==="s"?n*1e3:r==="m"?n*6e4:n*60*6e4}function Nc(e,t){let n=process.env[e];if(!n)return t;try{return Lc(n)}catch{return t}}function sg(e){return e.startsWith("SIG")?e:`SIG${e}`}function Mc(e){return e%36e5===0?`${e/36e5}h`:e%6e4===0?`${e/6e4}m`:e%1e3===0?`${e/1e3}s`:`${e}ms`}function ig(e,t){let n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function og(e){try{return process.kill(e,0),!0}catch{return!1}}async function ag(e){await new Promise(t=>setTimeout(t,e))}var $c,Up,Uc=S(()=>{"use strict";oe();Dn();$c={cmd:30*6e4,pr:60*6e4,run:60*6e4,release:2*60*6e4},Up={cmd:"local-cmd:2-5s",pr:"github-pr:15-20s-backoff-jitter",run:"github-run:15-20s-backoff-jitter",release:"release:60s"}});var Gc={};B(Gc,{renderShellInit:()=>cg});function cg(e,t=fn){if(e==="fish")return ug(t);if(e==="bash"||e==="zsh")return lg(e,t);throw new Error(`unsupported shell: ${e}`)}function ug(e){return["# rsp shell-init fish","# Opt-in only: source this output from config.fish; remove that line to restore raw commands.","if type -q rsp",...[...new Set(e.map(n=>n.command[0]).filter(gr))].map(n=>` abbr --add --position command -- ${n} '${pg(`rsp ${n}`)}'`)," function rspx --description 'Run a shell pipeline through rsp exec'"," rsp exec -- $argv"," end","else"," # rsp is not on PATH; rsp abbreviations and rspx were not installed.","end",""].join(`
|
|
76
|
+
`)}function lg(e,t){let n=fg(t);return[`# rsp shell-init ${e}`,`# Opt-in only: source this output from ${e} startup files; remove that line to restore raw commands.`,...pr("git",n.get("git")??[]),...pr("gh",n.get("gh")??[]),...pr("vitest",n.get("vitest")??[]),...pr("cargo",n.get("cargo")??[]),"rspx() {"," if command -v rsp >/dev/null 2>&1; then",' command rsp exec -- "$@"'," return"," fi"," printf '%s\\n' 'rspx requires rsp with exec support on PATH' >&2"," return 127","}",""].join(`
|
|
77
|
+
`)}function pr(e,t){if(t.length===0)return[];if(t.some(i=>i.command.length===1))return[`${e}() {`," if command -v rsp >/dev/null 2>&1; then",` command rsp ${e} "$@"`," return"," fi",` command ${e} "$@"`,"}"];let n=t.map(i=>i.command.slice(1)).filter(i=>i.length===1).map(i=>i[0]).filter(gr),r=t.map(i=>i.command.slice(1)).filter(i=>i.length>1&&i.every(gr)),s=[`${e}() {`," if ! command -v rsp >/dev/null 2>&1; then",` command ${e} "$@"`," return"," fi",' case "$1" in'];if(n.length>0){let i=n.map(o=>Fc(o)).join("|");s.push(` ${i}) command rsp ${e} "$@" ;;`)}for(let[i,o]of dg(r)){let a=o.map(c=>c.map((u,l)=>`[ "$${l+2}" = '${mg(u)}' ]`).join(" && ")).join(" || ");s.push(` ${Fc(i)}) if ${a}; then command rsp ${e} "$@"; else command ${e} "$@"; fi ;;`)}return s.push(` *) command ${e} "$@" ;;`," esac","}"),s}function dg(e){let t=new Map;for(let[n,...r]of e){if(!n)continue;let s=t.get(n)??[];s.push(r),t.set(n,s)}return t}function fg(e){let t=new Map;for(let n of e){let r=n.command[0];if(!r||!gr(r))continue;let s=t.get(r)??[];s.push(n),t.set(r,s)}return t}function gr(e){return!!(e&&/^[A-Za-z0-9_./:-]+$/.test(e))}function Fc(e){return e.replace(/[\\|)&;]/g,"\\$&")}function mg(e){return e.replace(/'/g,"'\\''")}function pg(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}var qc=S(()=>{"use strict";lr()});function zs(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.schemaVersion===1&&typeof t.id=="string"&&t.id.length>0&&typeof t.emitter=="string"&&t.emitter.length>0&&typeof t.occurredAt=="string"&&typeof t.taskClass=="string"&&gg(t.chosenOption)&&hg(t.outcome)&&yg(t.cost)}function gg(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function hg(e){return e==="success"||e==="failure"||e==="escalated"}function yg(e){if(typeof e!="object"||e===null)return!1;let t=e.signal;return t==="none"||t==="low"||t==="medium"||t==="high"||t==="unknown"}var Jc=S(()=>{});import{createHash as wg}from"node:crypto";function nu(e,t){return new Qs(e,t)}function Hc(e){let t=Number(e.red_entity_id??e.rid),n=Xs(e.properties??e.PROPERTIES),r=ru(String(e.node_type??e.NODE_TYPE??n.kind??"note"));if(!Number.isFinite(t))return null;let s=String(n.id??e.label??e.LABEL??t),i=String(n.title??e.label??e.LABEL??s),o=String(n.content??""),a=Array.isArray(n.tags)?n.tags.map(String):[],c=Date.now();return{rid:t,label:String(e.label??e.LABEL??s),kind:r,properties:{...n,id:s,title:i,content:o,tags:a,created_at:Number(n.created_at??c),updated_at:Number(n.updated_at??n.created_at??c),hash:String(n.hash??"")}}}function Wc(e){let t=Number(e.red_entity_id??e.rid),n=Number(e.from??e.FROM??e.from_rid??e.source),r=Number(e.to??e.TO??e.to_rid??e.target),s=su(String(e.label??e.LABEL??"related_to"));return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)?null:{rid:t,kind:s,from_rid:n,to_rid:r,weight:Number(e.weight??1),properties:Xs(e.properties??e.PROPERTIES)}}function Rg(e){let t=Number(e.red_entity_id??e.rid),n=Xs(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!zs(n)?null:{rid:t,event:n}}function Xs(e){return e==null?{}:typeof e=="string"?JSON.parse(e):hr(e)?e:{}}function ru(e){let t=e==="contact"?"person":e;if(bg.has(t))return t;throw new Error(`invalid Brain artifact kind: ${e}`)}function su(e){if(_g.has(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function Sg(e){return e==="hour"||e==="week"||e==="month"?e:"day"}function Vc(e){if(typeof e=="number")return e;let t=String(e??"");return/^\d+$/.test(t)?Number(t):t}function tt(e){return hr(e)?e:{}}function Kc(e,t){return tt(e)[t]}function zc(e,t){let n=e[t];if(typeof n!="string")throw new Error(`brain ${t} must be a string`);return n}function Yc(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Qc(e){let t=tt(e);return{excludeRids:Array.isArray(t.excludeRids)?t.excludeRids.map(Number).filter(Number.isFinite):void 0}}function G(e){return typeof e=="string"&&e.length>0?e:void 0}function hr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ys(e){return e!=null}function kg(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function Eg(e){return wg("sha256").update(JSON.stringify(e)).digest("hex")}function xg(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"artifact"}function Xc(e){return`artifact-hash:${e}`}function Zc(e,t,n){return`connection:${e}:${t}:${n}`}function eu(){return"model-tier-bandit:v1"}function Tg(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function tu(e,t){let n=0,r=e.indexOf(t);for(;r>=0;)n++,r=e.indexOf(t,r+t.length);return n}function iu(e,t){let n=e.properties.title.toLowerCase(),r=e.properties.content.toLowerCase(),s=e.properties.tags.map(o=>o.toLowerCase()),i=e.kind.toLowerCase();return{lexical:t.reduce((o,a)=>o+tu(n,a)*3+tu(r,a),0),tags:t.reduce((o,a)=>o+s.reduce((c,u)=>c+(u===a?4:u.includes(a)||a.includes(u)?2:0),0),0),kind:t.reduce((o,a)=>o+(i===a?3:i.includes(a)||a.includes(i)?1:0),0)}}function vg(e,t,n,r){let s=0;for(let i of n){let o=i.from_rid===e.rid?i.to_rid:i.to_rid===e.rid?i.from_rid:null;if(o==null)continue;let a=r.get(o);if(!a)continue;let c=ou({...iu(a,t),connections:0,vector:0}).total;c>0&&(s+=Math.min(c,12)*.35)}return et(s)}function ou(e){return{...e,lexical:et(e.lexical),tags:et(e.tags),kind:et(e.kind),connections:et(e.connections),vector:et(e.vector),total:et(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function et(e){return Math.round(e*1e3)/1e3}function Pg(e,t){if(e.length<=220)return e;let n=e.toLowerCase(),r=t.map(i=>n.indexOf(i)).filter(i=>i>=0).sort((i,o)=>i-o)[0]??0,s=Math.max(0,r-80);return`${s>0?"...":""}${e.slice(s,s+220)}${s+220<e.length?"...":""}`}function Og(e,t){let n=t.length===0?"none":t[0].score>=5?"high":t[0].score>=3?"medium":"low",r=t.length===0?[`No Brain artifacts matched "${e}".`]:[];return{answer:t.length===0?`Brain has no cited evidence for "${e}".`:`Brain found ${t.length} cited artifact${t.length===1?"":"s"} for "${e}".`,hits:t,citations:t.map((s,i)=>({ref:`B${i+1}`,rid:s.artifact.rid,id:s.artifact.properties.id,title:s.artifact.properties.title,kind:s.artifact.kind,score:s.score,score_breakdown:s.score_breakdown,excerpt:s.excerpt})),confidence:n,missing_evidence:r}}function Dg(e){let t={};for(let n of e)t[n]=(t[n]??0)+1;return t}var de,bg,_g,Qs,au=S(()=>{"use strict";Jc();de={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"},bg=new Set(["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"]),_g=new Set(["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"]),Qs=class{constructor(t,n){this.db=t;this.uri=n}async request(t,n){if(await this.bootstrap(),t==="status")return await this.status();if(t==="capture")return await this.capture(tt(n));if(t==="getArtifact")return await this.getArtifact(Kc(n,"ridOrId"));if(t==="listArtifacts")return await this.listArtifacts();if(t==="search"){let r=tt(n);return await this.search(zc(r,"query"),Yc(r,"limit")??10,Qc(r.options))}if(t==="think"){let r=tt(n);return await this.think(zc(r,"query"),Yc(r,"limit")??8,Qc(r.options))}if(t==="link")return await this.link(tt(n));if(t==="backlinks")return await this.backlinks(Kc(n,"target"));if(t==="listConnections")return await this.listConnections();if(t==="eventKpis")return await this.eventKpis(tt(n));if(t==="appendOutcomeEvent")return await this.appendOutcomeEvent(n);if(t==="replayOutcomeEvents")return await this.replayOutcomeEvents();if(t==="loadModelTierBanditDocument")return await this.loadModelTierBanditDocument();if(t==="saveModelTierBanditDocument")return await this.saveModelTierBanditDocument(n);if(t==="refreshModelTierBanditDocument")return await this.refreshModelTierBanditDocument();throw new Error(`unsupported resident brain action: ${t}`)}async bootstrap(){await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${de.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${de.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${de.outcomeEvents}`)}async status(){let t=await this.listArtifacts(),n=await this.listConnections();return{uri:this.uri,artifacts:t.length,connections:n.length,kinds:Dg(t.map(r=>r.kind))}}async capture(t){let n=G(t.title)||"Untitled artifact",r=G(t.content);if(!r)throw new Error("brain capture requires content");let s=ru(G(t.kind)||"note"),i=kg(Array.isArray(t.tags)?t.tags.map(String):[]),o=Date.now(),a=Eg([s,n,r,i,G(t.sourcePath),G(t.sourceSession)]),c=await this.kv().get(Xc(a));if(c!=null){let g=await this.getArtifact(Number(c));if(g)return g}let u=`${xg(n)}-${a.slice(0,8)}`,l={id:u,title:n,content:r,tags:i,source_agent:G(t.sourceAgent),source_runner:G(t.sourceRunner),source_session:G(t.sourceSession),source_path:G(t.sourcePath),created_at:o,updated_at:o,hash:a,metadata:hr(t.metadata)?t.metadata:void 0},f=(await this.db.query(`INSERT INTO ${de.artifacts} NODE (label, node_type, hash, properties) VALUES ($1, $2, $3, $4) RETURNING *`,u,s,a,l)).rows[0];if(!f)throw new Error("INSERT artifact returned no row");let h=Hc(f);if(!h)throw new Error("INSERT artifact returned invalid row");return await this.kv().put(Xc(a),h.rid),await this.materializeTagConnections(h),h}async getArtifact(t){let n=await this.listArtifacts();return typeof t=="number"?n.find(r=>r.rid===t)??null:n.find(r=>r.properties.id===t||r.label===t)??null}async listArtifacts(){return(await this.db.query(`SELECT * FROM ${de.artifacts}`)).rows.map(Hc).filter(Ys)}async search(t,n,r={}){let s=Tg(t),i=new Set(r.excludeRids??[]),o=await this.listArtifacts(),a=await this.listConnections(),c=new Map(o.map(u=>[u.rid,u]));return o.filter(u=>!i.has(u.rid)).map(u=>{let l=iu(u,s),d=ou({...l,connections:vg(u,s,a,c),vector:0});return{artifact:u,score:d.total,score_breakdown:d,excerpt:Pg(u.properties.content,s)}}).filter(u=>u.score>0).sort((u,l)=>l.score-u.score||l.artifact.properties.updated_at-u.artifact.properties.updated_at).slice(0,Math.max(1,Math.min(100,n)))}async think(t,n,r={}){let s=(await this.search(t,Math.max(n*2,n+5),r)).slice(0,n);return Og(t,s)}async link(t){let n=await this.getArtifact(Vc(t.from)),r=await this.getArtifact(Vc(t.to));if(!n)throw new Error(`Brain artifact not found: ${String(t.from)}`);if(!r)throw new Error(`Brain artifact not found: ${String(t.to)}`);let s=su(G(t.kind)||"related_to"),i=await this.findConnection(n.rid,r.rid,s);if(i!=null){let l=(await this.listConnections()).find(d=>d.rid===i);if(l)return l}let o={reason:G(t.reason),confidence:G(t.confidence)||"explicit",created_at:Date.now(),metadata:hr(t.metadata)?t.metadata:void 0},c=(await this.db.query(`INSERT INTO ${de.connections} EDGE (label, from, to, weight, properties) VALUES ($1, $2, $3, $4, $5) RETURNING *`,s,n.rid,r.rid,1,o)).rows[0];if(!c)throw new Error("INSERT connection returned no row");let u=Wc(c);if(!u)throw new Error("INSERT connection returned invalid row");return await this.kv().put(Zc(n.rid,r.rid,s),u.rid),u}async backlinks(t){let n=await this.getArtifact(t);if(!n)throw new Error(`Brain artifact not found: ${t}`);return(await this.listConnections()).filter(r=>r.to_rid===n.rid)}async listConnections(){return(await this.db.query(`SELECT * FROM ${de.connections}`)).rows.map(Wc).filter(Ys)}async eventKpis(t){let n=(await this.listArtifacts()).filter(i=>i.kind==="event"),r=Sg(G(t.interval)||"day"),s=G(t.timeField)==="ingested"?"ingested":"event";return{kind:"event",interval:r,timeField:s,range:{from:null,to:null},total:n.length,series:[{group:null,total:n.length,buckets:[]}]}}async appendOutcomeEvent(t){if(!zs(t))throw new Error("invalid Brain outcome event");if(!(await this.db.query(`INSERT INTO ${de.outcomeEvents} NODE (label, node_type, properties) VALUES ($1, $2, $3) RETURNING *`,t.id,`outcome_event.v${t.schemaVersion}`,t)).rows[0])throw new Error("INSERT outcome event returned no row");return t}async replayOutcomeEvents(){return(await this.db.query(`SELECT * FROM ${de.outcomeEvents}`)).rows.map(Rg).filter(Ys).sort((n,r)=>n.rid-r.rid).map(({event:n})=>n)}async loadModelTierBanditDocument(){let t=await this.kv().get(eu());return typeof t=="string"?JSON.parse(t):t}async saveModelTierBanditDocument(t){return await this.kv().put(eu(),JSON.stringify(t)),t}async refreshModelTierBanditDocument(){let t=await this.loadModelTierBanditDocument();if(t!=null)return t;let n={schema_version:"brain.model-tier-bandit.v1",updated_at:new Date().toISOString(),arms:{}};return await this.saveModelTierBanditDocument(n),n}async materializeTagConnections(t){if(t.properties.metadata?.derived_kind!=="tag")for(let n of t.properties.tags){let r=await this.capture({title:n,content:`Tag: ${n}`,kind:"custom",tags:["tag"],metadata:{derived:!0,derived_kind:"tag"}});await this.link({from:t.rid,to:r.rid,kind:"tagged",confidence:"derived"})}}async findConnection(t,n,r){let s=await this.kv().get(Zc(t,n,r));return s!=null?Number(s):null}kv(){return this.db.kv(de.kv)}}});var _u={};B(_u,{runResidentServer:()=>Mg});import{randomUUID as vt}from"node:crypto";import{execFileSync as Ig,spawn as $g}from"node:child_process";import{existsSync as Cg}from"node:fs";import{mkdir as pu,rename as Ng,rm as cu,writeFile as gu}from"node:fs/promises";import{createServer as Ag}from"node:net";import{dirname as ni,join as yr}from"node:path";import{fileURLToPath as Bg,pathToFileURL as Lg}from"node:url";async function Mg(e){await pu(ni(e.socketPath),{recursive:!0});let t=Qg();Yg();let n=e.telemetryDrainTimeoutMs??hu,r={kind:"opening",startedAt:process.hrtime.bigint()},s,i=!1,o=e.idleMs??Fn,a,c,u=!1,l=new Set,d=e.telemetryDrainIntervalMs??3e4,f=Ag(E=>{l.add(E),E.once("close",()=>l.delete(E)),g(),sh(E,async v=>{g();let N=await ih(r,v,e.storeUri,e.residentVersion??"0.0.0-dev"),M={id:v.id,ok:!0,value:N,storeOpenCount:r.kind==="ready"?r.storeOpenCount:void 0,storeElapsedMs:r.kind==="ready"?r.storeElapsedMs:void 0};bu(E,M),v.op==="handover"&&setImmediate(()=>h())})});function h(){i=!0,u=!0,c=zg(c),f.close();for(let E of l)E.destroy()}function g(){r.kind!=="opening"&&(a&&clearTimeout(a),a=setTimeout(()=>{h()},o),a.unref())}let p=["SIGINT","SIGTERM"].map(E=>{let v=()=>{wr(),f.close();for(let N of l)N.destroy();setTimeout(()=>process.exit(0),1e3)};return process.once(E,v),{signal:E,handler:v}});await new Promise((E,v)=>{f.once("error",v),f.listen(e.socketPath,()=>{f.off("error",v),E()})}),(async()=>{let E=process.hrtime.bigint();process.env.RSP_TEST_HANG_RESIDENT_STORE_OPEN==="1"&&await new Promise(()=>{});let v=Number(process.env.RSP_TEST_DELAY_RESIDENT_STORE_OPEN_MS??"0");Number.isFinite(v)&&v>0&&await new Promise(A=>setTimeout(A,v));let N=await Zt.open({uri:e.storeUri,ttlDays:e.ttlDays,ephemeralTtlHours:e.ephemeralTtlHours,byteBudget:e.byteBudget,allowResidentOpen:!0}),M=Number(process.hrtime.bigint()-E)/1e6,Q=new ti(N,{rootDir:e.rootDir??process.cwd(),ttlDays:e.telemetryTtlDays??jn,byteBudget:e.telemetryByteBudget??e.byteBudget??Un});if(i){await N.close();return}if(await Zs(Q,n),i){await N.close();return}r={kind:"ready",store:N,telemetry:Q,storeOpenCount:1,storeElapsedMs:M},s=setInterval(()=>{let A=r.kind==="ready"?r:void 0;A&&Zs(A.telemetry,n)},d),s.unref(),g()})().catch(E=>{r={kind:"failed",error:E instanceof Error?E:new Error(String(E))},g()}),e.pidPath&&await gu(e.pidPath,`${process.pid}
|
|
78
|
+
`,{encoding:"utf8",mode:384});let w=e.residentVersion??"0.0.0-dev",y=e.registryPath??yr(W(e.rootDir??process.cwd()),"rsp-resident.pid.json");try{await Bn(y,{socket_path:e.socketPath,store_uri:e.storeUri,resident_version:w})}catch{}await new Promise(E=>f.once("close",E)),a&&clearTimeout(a),s&&clearInterval(s),await cu(e.socketPath,{force:!0});let x=r;x.kind==="ready"&&(await Zs(x.telemetry,n,u),await x.store.close()),c&&clearTimeout(c);for(let{signal:E,handler:v}of p)process.off(E,v);t?.kill("SIGTERM"),wr(),e.pidPath&&await cu(e.pidPath,{force:!0}),await Ln(y)}async function Jg(e,t,n=new Date){let r=await tr(e,1,n),s=n.toISOString().slice(0,10),i=r.savings.daily_tokens_saved.find(l=>l.date===s)?.tokens_saved??0,o=r.savings.tokens_saved>0?i/r.savings.tokens_saved*r.savings.dollars_saved_estimate_usd:0,a=yr(W(t),Gg),c=`${a}.${process.pid}.${Date.now()}.tmp`,u={version:1,tokens_saved_today:i,dollars_saved_today_usd:Math.round(o*1e6)/1e6,show_total_today:r.health.show_total,updated_at:n.toISOString()};r.health.show_total>0&&(u.show_hit_rate=r.health.show_hit_rate),r.decisions.seen>0&&(u.decisions={seen:r.decisions.seen,contributed:r.decisions.contributed}),await pu(ni(a),{recursive:!0}),await gu(c,`${ye(u)}
|
|
79
|
+
`,{encoding:"utf8",mode:384}),await Ng(c,a)}async function Zs(e,t=hu,n=!1){try{n&&process.env.RSP_TEST_HANG_TELEMETRY_DRAIN==="1"&&await new Promise(()=>{}),await wu(e.drainAndSweep(),t,"telemetry drain timed out")}catch(r){process.stderr.write(`rsp resident: telemetry drain failed: ${r instanceof Error?r.message:String(r)}
|
|
80
|
+
`)}}async function Hg(e){let t=[];for(let n of qg){let r=await Wg(e,n);r.ok||(r.previousModel&&(r.previousModel!=="collection"&&await Vg(e,n,r.previousModel),t.push({collection:n,previousModel:r.previousModel})),await e.query(`CREATE KV IF NOT EXISTS ${yu(n)}`))}return t}async function Wg(e,t){try{return await e.kv(t).get("__rsp_telemetry_model_probe__"),{ok:!0}}catch(n){let r=n instanceof Error?n.message:String(n);if(/\bnot found\b/i.test(r))return{ok:!1,previousModel:null};let s=r.match(/model mismatch: expected kv, got ([A-Za-z_][A-Za-z0-9_]*)/i);if(s?.[1])return{ok:!1,previousModel:s[1].toLowerCase()};if(/does not allow 'kv' operations/i.test(r))return{ok:!1,previousModel:"collection"};let i=(await e.list()).find(o=>o.name===t);if(i&&i.model!=="kv")return{ok:!1,previousModel:i.model};throw n}}async function Vg(e,t,n){let r=Kg(n);if(!r)throw new Error(`cannot self-heal telemetry collection ${t}: unsupported model ${n}`);await e.query(`DROP ${r} ${yu(t)}`)}function Kg(e){let t=e.toLowerCase();return t==="table"?"TABLE":t==="kv"?"KV":t==="graph"?"GRAPH":t==="queue"?"QUEUE":t==="document"||t==="documents"?"DOCUMENT":null}function yu(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`invalid telemetry collection name: ${e}`);return e}function zg(e){return e&&clearTimeout(e),setTimeout(()=>{wr(),process.exit(0)},Fg)}function Yg(){uu||(uu=!0,process.on("exit",()=>wr()))}function Qg(){if(process.platform==="win32")return;let t=$g(process.execPath,["-e",`
|
|
74
81
|
const { execFileSync } = require("node:child_process");
|
|
75
82
|
const parentPid = Number(process.argv[1]);
|
|
76
83
|
const known = new Set();
|
|
@@ -111,64 +118,62 @@ const timer = setInterval(() => {
|
|
|
111
118
|
clearInterval(timer);
|
|
112
119
|
process.exit(0);
|
|
113
120
|
}, 500);
|
|
114
|
-
`,String(process.pid)],{detached:!0,stdio:"ignore"});return t.unref(),t}function
|
|
115
|
-
`);if(s<0)return;let i=n.slice(0,s);e.pause(),(async()=>{let o;try{o=JSON.parse(i),await t(o)}catch(a){let u={id:o?.id??
|
|
116
|
-
`)}catch{}}async function
|
|
117
|
-
`),n(127)}),t.on("close",(r,s)=>{if(s){process.kill(process.pid,s),n(128);return}n(r??0)})})}function
|
|
118
|
-
`).filter(s=>s
|
|
121
|
+
`,String(process.pid)],{detached:!0,stdio:"ignore"});return t.unref(),t}function wr(){for(let e of Xg())try{process.kill(e,"SIGTERM")}catch{}}function Xg(){if(process.platform==="win32")return[];let e="";try{e=Ig("ps",["-eo","pid=,ppid=,args="],{encoding:"utf8"})}catch{return[]}let t=[];for(let n of e.split(/\n/)){let r=/^\s*(\d+)\s+(\d+)\s+([\s\S]*)$/.exec(n);if(!r)continue;let s=Number(r[1]),i=Number(r[2]),o=r[3]??"";i===process.pid&&/(^|\s)\S*red(?:\.exe)?\s+rpc\s+--stdio(\s|$)/.test(o)&&t.push(s)}return t}async function Zg(e){if(e.collection!==le)return e;let t=await lu(e.raw_text,fu(e.raw_bytes)),n=await lu(e.emitted_text,fu(e.emitted_bytes)),{raw_text:r,emitted_text:s,...i}=e;return{...i,tokens_raw:t.tokens,tokens_emitted:n.tokens,estimated:t.estimated||n.estimated}}async function lu(e,t){if(typeof e=="string"){let n=Buffer.byteLength(e,"utf8");if(n<=jg)try{return await wu((async()=>({tokens:(await eh())("cl100k_base").encode(e).length,estimated:!1}))(),Ug,"telemetry tokenization timed out")}catch{return{tokens:Math.ceil(n/4),estimated:!0}}return{tokens:Math.ceil(n/4),estimated:!0}}return t!=null?{tokens:Math.ceil(t/4),estimated:!0}:{tokens:0,estimated:!1}}async function eh(){return du??=import(Lg(th()).href).then(e=>{let t=e.getEncoding;if(!t)throw new Error("js-tiktoken getEncoding export not found");return t}),await du}function th(){let e=ni(Bg(import.meta.url)),n=[yr(e,"..","node_modules","js-tiktoken","dist","index.js"),yr(e,"..","apps","rsp","node_modules","js-tiktoken","dist","index.js")].find(r=>Cg(r));if(!n)throw new Error("js-tiktoken dependency not found");return n}function fu(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function q(e){return typeof e=="string"&&e.trim()!==""?e:void 0}function ei(e){return e.trim().split(/\s+/).filter(Boolean)[0]??"unknown"}async function wu(e,t,n){let r;try{return await Promise.race([e,new Promise((s,i)=>{r=setTimeout(()=>i(new Error(n)),t),r.unref()})])}finally{r&&clearTimeout(r)}}function nh(e){try{return JSON.parse(e)}catch{return e}}function rh(e){return mu(e)&&e.version===1&&Array.isArray(e.records)&&e.records.every(t=>mu(t)&&(t.collection===z||t.collection===Y||t.collection===le||t.collection===Ne)&&typeof t.key=="string"&&typeof t.created_at=="string"&&typeof t.expires_at=="string"&&typeof t.bytes=="number")}function mu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sh(e,t){let n="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",r=>{n+=r;let s=n.indexOf(`
|
|
122
|
+
`);if(s<0)return;let i=n.slice(0,s);e.pause(),(async()=>{let o;try{o=JSON.parse(i),await t(o)}catch(a){let u={id:o?.id??vt(),ok:!1,error:a instanceof Error?a.message:String(a)};bu(e,u)}finally{e.end()}})()})}function bu(e,t){if(!(e.destroyed||!e.writable))try{e.write(`${JSON.stringify(t)}
|
|
123
|
+
`)}catch{}}async function ih(e,t,n,r){if(t.op==="handover")return{handover:!0,version:r,clientVersion:t.clientVersion};if(e.kind==="opening")throw new Error("rsp resident store is not ready");if(e.kind==="failed")throw new Error(`rsp resident store failed to open: ${e.error.message}`);let s=e.store;if(t.op==="ping")return{pong:!0,version:r};if(t.op==="stats")return await s.stats();if(t.op==="accounting-stats"){let i=s.redDb();if(!i)throw new Error("rsp accounting stats require the shared RedDB store");return await Ps(i,t.byteBudget)}if(t.op==="telemetry-stats"){let i=s.redDb();if(!i)throw new Error("rsp telemetry stats require the shared RedDB store");return await tr(i,t.sinceDays)}if(t.op==="telemetry-gains"){let i=s.redDb();if(!i)throw new Error("rsp telemetry gains require the shared RedDB store");return await Os(i,t.sinceDays)}if(t.op==="mint")return{handle:await s.mint(Buffer.from(t.original,"base64"),t.meta)};if(t.op==="get")return ah(await s.get(t.handle));if(t.op==="memory")return await s.memory(t.action,t.payload);if(t.op==="brain")return await oh(s,n,t.action,t.payload);throw new Error(`unsupported resident op: ${t.op??"unknown"}`)}async function oh(e,t,n,r){let s=e.redDb();if(!s)throw new Error("resident brain operations require the shared RedDB store");return await nu(s,t).request(n,r)}function ah(e){return e?"status"in e?e:{...e,original:e.original.toString("base64"),original_encoding:"base64"}:null}var jg,Ug,hu,Fg,Gg,qg,ti,uu,du,Ru=S(()=>{"use strict";De();Mn();Dn();ze();au();Te();ue();jg=256*1024,Ug=500,hu=2e3,Fg=Math.max(1,Number(process.env.RSP_TEST_IDLE_SHUTDOWN_WATCHDOG_MS??"10000")),Gg="rsp-status-summary.json",qg=[z,Y,le,Ne,sn],ti=class{constructor(t,n){this.store=t;this.opts=n;this.pendingHeals=[...n.bootHeals??[]]}running;pending=!1;pendingHeals;async drainAndSweep(){if(this.running){this.pending=!0,await this.running;return}this.running=(async()=>{do this.pending=!1,await this.drainAndSweepOnce();while(this.pending)})().finally(()=>{this.running=void 0}),await this.running}async drainAndSweepOnce(){let t=this.store.redDb();if(!t)return;let n=await Hg(t);n.unshift(...this.pendingHeals),this.pendingHeals=[];let r=await this.readIndex(t),s=r.records.length,i=[...r.records];for(let a of n)i.push(await this.writeDrainDegradation(t,{reason:"telemetry collection model mismatch",command:"rsp resident telemetry drain",source_collection:a.collection,error:`expected kv, got ${a.previousModel}`,bytes:0}));await vs(this.opts.rootDir,async a=>{let c=xt(a);if(!c){let u=await this.writeDrainDegradation(t,{reason:"telemetry parse failed",command:"unknown",bytes:Buffer.byteLength(a,"utf8")});return i.push(u),!0}try{let u=await this.writeEvent(t,c);i.push(u);let l=await this.writeAccountingMirror(t,c);return l&&i.push(l),!0}catch(u){let l=await this.writeDrainDegradation(t,{reason:"telemetry event dropped",command:q(c.command)||"unknown",source_id:q(c.id),source_collection:q(c.collection),error:u instanceof Error?u.message:String(u),bytes:Buffer.byteLength(a,"utf8")});return i.push(l),!0}});let o=i.length>s;await this.prune(t,{version:1,records:i},o),await Jg(t,this.opts.rootDir)}async writeEvent(t,n){let r=new Date,s=typeof n.created_at=="string"?n.created_at:r.toISOString(),i=new Date(Date.parse(s)+this.opts.ttlDays*24*60*60*1e3).toISOString(),o=typeof n.id=="string"&&n.id.trim()!==""?n.id:vt(),a={...await Zg(n),id:o,created_at:s,expires_at:i};return await t.kv(n.collection).put(o,a),{collection:n.collection,key:o,created_at:s,expires_at:i,bytes:n.collection===z?0:typeof n.bytes=="number"&&Number.isFinite(n.bytes)?Math.max(0,n.bytes):Buffer.byteLength(JSON.stringify(a),"utf8")}}async writeAccountingMirror(t,n){return n.collection===z||n.accounting_recorded===!0?null:n.collection===le?await this.writeEvent(t,{collection:z,id:`mirror:${q(n.id)||vt()}`,created_at:q(n.created_at)||q(n.ts)||new Date().toISOString(),event_type:"invocation",command:q(n.command)||"unknown",command_class:ei(q(n.command)||"unknown"),wrapper:n.wrapper,loss:n.loss,elided:n.elided,raw_bytes:n.raw_bytes,emitted_bytes:n.emitted_bytes,tokens_raw:n.tokens_raw,tokens_emitted:n.tokens_emitted,estimated:n.estimated,wrapper_ms:n.wrapper_ms,store_open_count:n.store_open_count,store_elapsed_ms:n.store_elapsed_ms}):n.collection===Ne?await this.writeEvent(t,{collection:z,id:`mirror:${q(n.id)||vt()}`,created_at:q(n.created_at)||q(n.ts)||new Date().toISOString(),event_type:"invocation",command:q(n.command)||"unknown",command_class:ei(q(n.command)||"unknown"),loss:"lossless",raw_bytes:0,emitted_bytes:0,degradation_reason:q(n.reason)||"unknown"}):null}async writeDrainDegradation(t,n){let r=await this.writeEvent(t,{collection:Ne,id:vt(),created_at:new Date().toISOString(),reason:n.reason,command:n.command,bytes:n.bytes,source_id:n.source_id,source_collection:n.source_collection,error:n.error});return await this.writeEvent(t,{collection:z,id:`mirror:${vt()}`,created_at:r.created_at,event_type:"invocation",command:n.command,command_class:ei(n.command),loss:"lossless",raw_bytes:0,emitted_bytes:0,degradation_reason:n.reason,source_id:n.source_id,source_collection:n.source_collection,error:n.error}),r}async readIndex(t){let n=await t.kv(sn).get("index:v1"),r=typeof n=="string"?nh(n):n;return rh(r)?r:{version:1,records:[]}}async writeIndex(t,n){await t.kv(sn).put("index:v1",n)}async prune(t,n,r=!1){let s=Date.now(),i=[];for(let a of n.records)Date.parse(a.expires_at)<=s?await t.kv(a.collection).delete(a.key):i.push(a);let o=i.reduce((a,c)=>a+c.bytes,0);for(i.sort((a,c)=>a.created_at.localeCompare(c.created_at));o>this.opts.byteBudget&&i.length>0;){let a=i.shift();o-=a.bytes,await t.kv(a.collection).delete(a.key)}(r||i.length<n.records.length)&&await this.writeIndex(t,{version:1,records:i})}};uu=!1});var ii={};B(ii,{parseProxyCommandLine:()=>xu,rewriteProxyCommandLine:()=>Eu,runProxy:()=>uh});import{spawn as ch}from"node:child_process";async function uh(e,t){let n="",r="",s=[],i=process.hrtime.bigint();try{if(n=xu(e),process.env.RSP_PROXY_FAIL_INTERNAL==="1")throw new Error("forced proxy failure");let c=Eu(n,t.level??"lossless");r=c.commandLine,s=c.matches}catch(c){if(n)return await lh(t.telemetryRoot,n,c),await Su(n);throw c}for(let c of s)await dh(t.telemetryRoot,c);let o=await Su(r||n),a=Number(process.hrtime.bigint()-i)/1e6;return await Qe(t.telemetryRoot,{collection:le,ts:new Date().toISOString(),command:n,wrapper:"proxy",loss:"lossless",elided:!1,raw_bytes:0,emitted_bytes:0,wrapper_ms:a,accounting_recorded:!1}),o}function Eu(e,t="lossless"){let n=yh(e),r=[];return{commandLine:n.map((i,o)=>{if(i.kind==="operator"||hh(n,o)==="|")return i.text;let a=fh(i.text,t);return a?(r.push(a.match),a.text):i.text}).join(""),matches:r}}function xu(e){if(e[0]!=="proxy")throw new Error("expected rsp proxy -- <command line>");let t=e.indexOf("--"),n=t>=0?e.slice(t+1):e.slice(1),r=n.length===1?n[0]:n.join(" ");if(!r.trim())throw new Error("usage: rsp proxy -- <command line>");return r}async function lh(e,t,n){await Qe(e,{collection:Y,event_type:"decision",ts:new Date().toISOString(),hook:"proxy",command:t,command_family:si(t),decision:"failed-open",reason:"proxy-internal-error",error:n instanceof Error?n.name:typeof n})}async function dh(e,t){await Qe(e,{collection:Y,event_type:"decision",ts:new Date().toISOString(),hook:"proxy",command:t.command,command_family:t.commandFamily,decision:t.decision,reason:t.reason,capability_id:t.capabilityId})}async function Su(e){let t=ch(e,{shell:!0,stdio:"inherit"});return await new Promise(n=>{t.on("error",r=>{process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
124
|
+
`),n(127)}),t.on("close",(r,s)=>{if(s){process.kill(process.pid,s),n(128);return}n(r??0)})})}function fh(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"",s=e.trim();if(!s)return null;let i=bh(s);if(!i)return null;let o=gh(i);if(o>=i.length)return null;let a=i.slice(o),c=a.map(h=>h.value);if(br(c))return{text:e,match:{command:a.map(h=>h.raw).join(" "),commandFamily:si(c.join(" ")),decision:"passed",reason:"lossless-gh-json-jq"}};let u=mh(a);if(!u)return null;let l=i.slice(0,o).map(h=>h.raw),d=t==="lossless"?[]:[`--${t}`],f=[...l,"rsp",...d,...u.wrapperWords].join(" ");return{text:`${n}${f}${r}`,match:{command:a.map(h=>h.raw).join(" "),commandFamily:si(c.join(" ")),decision:"contributed",reason:"proxy-segment",capabilityId:u.capabilityId}}}function mh(e){let t=e.map(r=>r.value),n=e.map(r=>r.raw);return t[0]==="git"&&["status","log","diff","show","blame"].includes(t[1]??"")?{capabilityId:`git:${t[1]}`,wrapperWords:n}:t[0]==="gh"&&["pr","issue","run"].includes(t[1]??"")&&["list","view"].includes(t[2]??"")?{capabilityId:`gh:${t[1]}:${t[2]}`,wrapperWords:n}:t[0]==="vitest"?{capabilityId:t[1]==="run"?"vitest:run":"vitest",wrapperWords:n}:t[0]==="cargo"&&t[1]==="test"?{capabilityId:"cargo:test",wrapperWords:n}:ph(t,n)}function ph(e,t){return e[0]==="cat"&&e.length===2&&ri(e[1])?{capabilityId:"cat:file",wrapperWords:["cat",t[1]]}:(e[0]==="head"||e[0]==="tail")&&e.length===2&&ri(e[1])?{capabilityId:`cat:${e[0]}`,wrapperWords:["cat",`--${e[0]}`,"10",t[1]]}:(e[0]==="head"||e[0]==="tail")&&e.length===4&&e[1]==="-n"&&/^[1-9][0-9]*$/.test(e[2])&&ri(e[3])?{capabilityId:`cat:${e[0]}`,wrapperWords:["cat",`--${e[0]}`,e[2],t[3]]}:null}function ri(e){return!!e&&!e.startsWith("-")}function gh(e){let t=0;for(;t<e.length&&ku(e[t].value);)t+=1;if(e[t]?.value!=="env")return t;for(t+=1;t<e.length&&ku(e[t].value);)t+=1;return t}function hh(e,t){for(let n=t+1;n<e.length;n+=1)if(e[n].kind==="operator")return e[n].text}function yh(e){let t=[],n=0,r,s=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(r){o===r&&(r=void 0);continue}if(o==="'"||o==='"'){r=o;continue}let a=wh(e,i);a&&(i>n&&t.push({kind:"segment",text:e.slice(n,i)}),t.push({kind:"operator",text:a}),i+=a.length-1,n=i+1)}return n<e.length&&t.push({kind:"segment",text:e.slice(n)}),t}function wh(e,t){let n=e.slice(t,t+2);if(n==="&&"||n==="||")return n;let r=e[t];return r===";"||r==="|"?r:void 0}function bh(e){let t=[],n="",r="",s,i=!1,o=!1,a=()=>{o&&(t.push({raw:n,value:r}),n="",r="",o=!1)};for(let c=0;c<e.length;c+=1){let u=e[c];if(i){n+=u,r+=u,i=!1,o=!0;continue}if(u==="\\"){n+=u,i=!0,o=!0;continue}if(s){n+=u,u===s?s=void 0:r+=u,o=!0;continue}if(u==="'"||u==='"'){n+=u,s=u,o=!0;continue}if(/[ \t]/.test(u)){a();continue}if(/[()<>`]/.test(u))return null;n+=u,r+=u,o=!0}return s||i?null:(a(),t)}function si(e){let t=e.trim().split(/\s+/).filter(Boolean);return t.length===0?"unknown":t[0]==="git"&&t[1]?`git ${t[1]}`:br(t)&&t[1]&&t[2]?`gh ${t[1]} ${t[2]} json-jq`:br(t)&&t[1]?`gh ${t[1]} json-jq`:br(t)?"gh json-jq":t[0]==="gh"&&t[1]&&t[2]?`gh ${t[1]} ${t[2]}`:t[0]==="gh"&&t[1]?`gh ${t[1]}`:t[0]==="cargo"&&t[1]?`cargo ${t[1]}`:t[0]==="vitest"?"vitest":t[0]}function br(e){return e[0]==="gh"&&e.some(_h)}function _h(e){return e==="--json"||e==="--jq"||e.startsWith("--json=")||e.startsWith("--jq=")}function ku(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}var oi=S(()=>{"use strict";Te()});function Be(e){let t=[],n;for(let r=0;r<e.length;r++){let s=e[r];if(s==="--query"){n=e[++r];continue}if(s.startsWith("--query=")){n=s.slice(8);continue}t.push(s)}return{argv:t,query:n?.trim()||void 0}}function Tu(e,t){if(!t)return!0;let n=ai(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(r=>n.includes(r))}function j(e,t){return t?e.filter(n=>Tu(n,t)):[...e]}function Pt(e,t){if(!t)return e;let r=e.split(`
|
|
125
|
+
`).filter(s=>s&&Tu(s,t));return r.length>0?`${r.join(`
|
|
119
126
|
`)}
|
|
120
|
-
`:""}function
|
|
121
|
-
`)return{stdout:Buffer.from(i),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let o=
|
|
122
|
-
`;return{stdout:Buffer.from(`${
|
|
123
|
-
${l}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:a.payload,mintedHandle:u,bytesElided:c,rowsElided:a.rowsElided,rawOutput:Buffer.from(o)}}function
|
|
124
|
-
`;let i=
|
|
125
|
-
`)[0]??"",r=/^\[([^ ]+) ([0-9a-f]+)\] (.+)$/.exec(n),s=/(\d+) files? changed/.exec(t),i=/(\d+) insertions?\(\+\)/.exec(t),o=/(\d+) deletions?\(-\)/.exec(t),a=r?.[1]??"",c=r?.[2]??"",u=Number(s?.[1]??0),l=Number(i?.[1]??0),d=Number(o?.[1]??0);return{command:e.join(" "),branch:a,commit:c,subject:r?.[3]??"",files_changed:u,insertions:l,deletions:d,summary:`commit ${c} on ${a}: ${u} files, +${l} -${d}`}}function
|
|
126
|
-
`).filter(Boolean),r=n.find(c=>c.startsWith("To "))?.slice(3)??"",s=n.filter(c=>c.includes(" ")).map(c=>{let[u,l,d=""]=c.split(" "),[f,
|
|
127
|
-
`),s=[],i=null;for(let c of r){let u=/^([0-9a-f]{8,40}) \d+ (\d+)(?: \d+)?$/.exec(c);if(u){i={commit:u[1]??"",finalLine:Number(u[2]??0),author:"",path:""};continue}if(!i)continue;if(c.startsWith("author ")){i.author=c.slice(7);continue}if(c.startsWith("filename ")){i.path=c.slice(9);continue}if(!c.startsWith(" "))continue;let l=s.at(-1),d=i.commit.slice(0,12);l&&l.commit===d&&l.author===i.author&&l.path===i.path&&l.line_end+1===i.finalLine?l.line_end=i.finalLine:s.push({line_start:i.finalLine,line_end:i.finalLine,author:i.author,commit:d,path:i.path}),i=null}let o=
|
|
128
|
-
`).filter(Boolean).map(o=>{let[a,c,u,l,d,f]=o.split("\0");return{current:a==="*",name:c??"",commit:u??"",upstream:l||null,worktree:d||null,subject:f??""}}),s=
|
|
129
|
-
`)){let
|
|
130
|
-
`).length:0,files:g,summary:`${n?`${g.length}/${
|
|
131
|
-
`;return{stdout:Buffer.from(`${
|
|
132
|
-
${
|
|
127
|
+
`:""}function Le(e,t){let n=t.filter(Boolean);return n.length===0?e:{...e,help:n}}function ai(e){return Array.isArray(e)?e.map(ai).join(" "):typeof e=="object"&&e!==null?Object.values(e).map(ai).join(" "):String(e??"")}var _r=S(()=>{"use strict"});var ci={};B(ci,{DEFAULT_RSP_HEAVY_GIT_BYTE_THRESHOLD:()=>be,GIT_LOG_MACHINE_FIELDS:()=>vu,recoveryInstruction:()=>te,renderGitContract:()=>Pu,runGitWrapper:()=>Sh});import{spawn as Rh}from"node:child_process";async function Sh(e,t){let n=Ou(e),r=Du(n.argv),s=await Th(r,n.argv.slice(1));return Pu(e,s,t)}async function Pu(e,t,n){let r=Ou(e);if((t.status??0)!==0||t.signal)return{stdout:Buffer.from(Pt(t.stdout,r.query)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let s=Du(r.argv),i=vh(s,r.argv,t.stdout,r.query);if(i===`git empty
|
|
128
|
+
`)return{stdout:Buffer.from(i),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let o=O(i);if(kh(s,o,r.full,n))return{stdout:Buffer.from(o),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:i};let a=Mh(i);if(!a)return{stdout:Buffer.from(o),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:i};let c=Buffer.byteLength(o),u=await n.store?.mint(Buffer.from(o),{command:e.join(" "),loss:{level:"terse",bytes_elided:c}});if(!u)throw new Error("terse git output requires an elision store");let l=`\u2026 elided ${a.rowsElided} rows (+${c}) \u2014 ${te(u)}
|
|
129
|
+
`;return{stdout:Buffer.from(`${O(a.payload)}
|
|
130
|
+
${l}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:a.payload,mintedHandle:u,bytesElided:c,rowsElided:a.rowsElided,rawOutput:Buffer.from(o)}}function te(e){return e.startsWith("el:")?`rsp show ${e}`:e}function Ou(e){let t=Be(e),n=[],r=!1;for(let s of t.argv){if(s==="--full"){r=!0;continue}n.push(s)}return{argv:n,query:t.query,full:r}}function kh(e,t,n,r){if(r.level==="terse")return!1;if(n||r.level==="full"||!Eh(e)||r.level!=="lossless")return!0;let s=Lh(r.heavyGitByteThreshold,be);return Buffer.byteLength(t)<=s}function Eh(e){return e==="diff"||e==="log"||e==="blame"||e==="show"}function Du(e){if(e[0]!=="git")throw new Error("expected rsp git <subcommand>");let t=e[1];if(t==="status"||t==="log"||t==="diff"||t==="commit"||t==="push"||t==="blame"||t==="branch"||t==="show")return t;throw new Error(`unsupported git subcommand: ${t??""}`)}function xh(e,t){let n=t.slice(1);switch(e){case"status":return["status","--porcelain=v2","-z","-b",...n];case"log":return["log",`--format=%x1e${vu.join("%x1f")}`,"-z",...n];case"diff":return["diff","--numstat","-z",...n];case"commit":return["commit",...n];case"push":return["push","--porcelain",...n];case"blame":return["blame","--line-porcelain",...n];case"branch":return["branch","--format=%(HEAD)%00%(refname:short)%00%(objectname:short)%00%(upstream:short)%00%(worktreepath)%00%(contents:subject)",...n];case"show":return["show","--format=%x1e%H%x1f%h%x1f%an%x1f%aI%x1f%s%x1f%b%x1e","--stat",...n]}}async function Th(e,t){let n=Rh("git",xh(e,t),{stdio:["ignore","pipe","pipe"]}),r=[],s=[];return n.stdout.on("data",i=>r.push(i)),n.stderr.on("data",i=>s.push(i)),await new Promise((i,o)=>{n.on("error",o),n.on("close",(a,c)=>{i({stdout:Buffer.concat(r).toString("utf8"),stderr:Buffer.concat(s).toString("utf8"),status:a,signal:c})})})}function vh(e,t,n,r){switch(e){case"status":return Ph(t,n,r);case"log":return Oh(t,n,r);case"diff":return Dh(t,n,r);case"commit":return Me(Ih(t,n),r,["rsp git status --query <path-or-state>"]);case"push":return Me($h(t,n),r,["rsp gh pr list --query <branch>"]);case"blame":return Ch(t,n,r);case"branch":return Nh(t,n,r);case"show":return Ah(t,n,r)}}function Ph(e,t,n){let r="",s=[];for(let a of t.split("\0")){if(!a)continue;if(a.startsWith("# branch.head ")){r=a.slice(14);continue}if(!a.startsWith("1 "))continue;let c=a.split(" "),u=c[1]??"..",l=c.slice(8).join(" ");s.push({path:l,index:u[0]??".",worktree:u[1]??".",state:Bh(u)})}if(s.length===0)return`git empty
|
|
131
|
+
`;let i=j(s,n),o=Iu(i,"state");return Me({command:e.join(" "),branch:r,rows:i,summary:`${n?`${i.length}/${s.length}`:i.length} changes: ${o.added??0} added, ${o.modified??0} modified, ${o.deleted??0} deleted`},n,["rsp git diff --query <path>","rsp git log --query <subject>"])}function Oh(e,t,n){let r=t.split("\0").filter(Boolean).map(i=>{let o=i.replace(/^\x1e/,"").split("");return{short:o[0]??"",author:o[1]??"",date:o[2]??"",subject:o[3]??""}}),s=j(r,n);return Me({command:e.join(" "),commits:s,summary:`${n?`${s.length}/${r.length}`:s.length} commits`},n,["rsp git diff --query <path>","rsp gh pr list --query <branch>"])}function Dh(e,t,n){let s=t.split("\0").filter(Boolean).map(a=>{let[c,u,l]=a.split(" ");return{path:l??"",added:c==="-"?null:Number(c??0),deleted:u==="-"?null:Number(u??0)}}),i=j(s,n),o=i.reduce((a,c)=>(a.added+=typeof c.added=="number"?c.added:0,a.deleted+=typeof c.deleted=="number"?c.deleted:0,a),{added:0,deleted:0});return Me({command:e.join(" "),files:i,summary:`${n?`${i.length}/${s.length}`:i.length} files, +${o.added} -${o.deleted}`},n,["rsp git status --query <path>","rsp git log --query <subject>"])}function Ih(e,t){let n=t.split(`
|
|
132
|
+
`)[0]??"",r=/^\[([^ ]+) ([0-9a-f]+)\] (.+)$/.exec(n),s=/(\d+) files? changed/.exec(t),i=/(\d+) insertions?\(\+\)/.exec(t),o=/(\d+) deletions?\(-\)/.exec(t),a=r?.[1]??"",c=r?.[2]??"",u=Number(s?.[1]??0),l=Number(i?.[1]??0),d=Number(o?.[1]??0);return{command:e.join(" "),branch:a,commit:c,subject:r?.[3]??"",files_changed:u,insertions:l,deletions:d,summary:`commit ${c} on ${a}: ${u} files, +${l} -${d}`}}function $h(e,t){let n=t.split(`
|
|
133
|
+
`).filter(Boolean),r=n.find(c=>c.startsWith("To "))?.slice(3)??"",s=n.filter(c=>c.includes(" ")).map(c=>{let[u,l,d=""]=c.split(" "),[f,h]=(l??"").split(":");return{flag:u??"",from:f??"",to:h??"",summary:d}}),i=s.find(c=>c.flag!=="=")??s[0],o=i?.to.startsWith("refs/heads/")?i.to.slice(11):i?.to??"",a=i?.summary.includes("..")?1:0;return{command:e.join(" "),remote:r,refs:s,summary:`pushed ${o} -> ${r} +${a} commits`}}function Ch(e,t,n){let r=t.split(`
|
|
134
|
+
`),s=[],i=null;for(let c of r){let u=/^([0-9a-f]{8,40}) \d+ (\d+)(?: \d+)?$/.exec(c);if(u){i={commit:u[1]??"",finalLine:Number(u[2]??0),author:"",path:""};continue}if(!i)continue;if(c.startsWith("author ")){i.author=c.slice(7);continue}if(c.startsWith("filename ")){i.path=c.slice(9);continue}if(!c.startsWith(" "))continue;let l=s.at(-1),d=i.commit.slice(0,12);l&&l.commit===d&&l.author===i.author&&l.path===i.path&&l.line_end+1===i.finalLine?l.line_end=i.finalLine:s.push({line_start:i.finalLine,line_end:i.finalLine,author:i.author,commit:d,path:i.path}),i=null}let o=j(s,n),a=Iu(o,"author");return Me({command:e.join(" "),ranges:o,authors:a,summary:`${n?`${o.length}/${s.length}`:o.length} ranges, ${Object.keys(a).length} authors`},n,["rsp git show --query <commit>","rsp git log --query <author>"])}function Nh(e,t,n){let r=t.split(`
|
|
135
|
+
`).filter(Boolean).map(o=>{let[a,c,u,l,d,f]=o.split("\0");return{current:a==="*",name:c??"",commit:u??"",upstream:l||null,worktree:d||null,subject:f??""}}),s=j(r,n),i=s.find(o=>o.current)?.name??"";return Me({command:e.join(" "),branches:s,summary:`${n?`${s.length}/${r.length}`:s.length} branches${i?`, current ${i}`:""}`},n,["rsp git log --query <branch>","rsp gh pr list --query <branch>"])}function Ah(e,t,n){let r=t.indexOf(""),s=r>=0?t.indexOf("",r+1):-1,i=r>=0&&s>=0?t.slice(r+1,s):"",o=s>=0?t.slice(s+1):t,[a,c,u,l,d,f=""]=i.split(""),h=[];for(let y of o.split(`
|
|
136
|
+
`)){let x=/^\s*(.+?)\s+\|\s+(\d+)\s+([+\-]+|Bin.*)$/.exec(y);if(!x)continue;let E=x[3]??"";h.push({path:(x[1]??"").trim(),changed:Number(x[2]??0),added:[...E].filter(v=>v==="+").length,deleted:[...E].filter(v=>v==="-").length,binary:E.startsWith("Bin")})}let g=j(h,n),m=0,p=0,w=0;for(let y of g)m+=typeof y.changed=="number"?y.changed:0,p+=typeof y.added=="number"?y.added:0,w+=typeof y.deleted=="number"?y.deleted:0;return Me({command:e.join(" "),commit:a??"",short:c??"",author:u??"",date:l??"",subject:d??"",body_lines:f.trim()?f.trim().split(`
|
|
137
|
+
`).length:0,files:g,summary:`${n?`${g.length}/${h.length}`:g.length} files, ${m} changed, +${p} -${w}`},n,["rsp git blame --query <author-or-path>","rsp git diff --query <path>"])}function Me(e,t,n){return t?Le(e,n):e}function Bh(e){return e.includes("A")?"added":e.includes("D")?"deleted":e.includes("R")?"renamed":e.includes("M")?"modified":"changed"}function Iu(e,t){let n={};for(let r of e){let s=String(r[t]??"");n[s]=(n[s]??0)+1}return n}function Lh(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Mh(e){for(let t of["rows","commits","files","refs","ranges","branches"]){let n=e[t];if(Array.isArray(n)&&n.length>1)return{payload:{...e,[t]:n.slice(0,1)},rowsElided:n.length-1}}return null}var vu,nt=S(()=>{"use strict";oe();ue();_r();ue();vu=["%h","%an","%as","%s"]});var fi={};B(fi,{renderGhContract:()=>Nu,runGhWrapper:()=>Gh});import{spawn as Cu}from"node:child_process";async function Gh(e,t){let n=Au(e),r=await Jh(n);return Nu(e,r,t)}async function Nu(e,t,n){let r=Be(e);if((t.status??0)!==0||t.signal)return{stdout:Buffer.from(Pt(t.stdout,r.query)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let s=Au(e),i=Rr(t.stdout),o=Wh(s,e,i);if(typeof o=="string")return{stdout:Buffer.from(o),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let a=Zh(o);if(a){if(!n.store)throw new Error("truncated gh output requires an elision store");let g=await n.store.mint(Buffer.from(a.original),{command:e.join(" "),loss:{level:s.full?"brief":n.level,bytes_elided:a.bytes}});a.target.truncated.handle=g}let c=a?.target.truncated.handle||void 0,u=O(o);if(n.level!=="terse")return{stdout:Buffer.from(u),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:o,mintedHandle:c,bytesElided:a?.bytes};let l=ey(o);if(!l)return{stdout:Buffer.from(u),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:o,mintedHandle:c,bytesElided:a?.bytes};let d=Buffer.byteLength(u),f=await n.store?.mint(Buffer.from(u),{command:e.join(" "),loss:{level:"terse",bytes_elided:d}});if(!f)throw new Error("terse gh output requires an elision store");let h=`\u2026 elided ${l.rowsElided} rows (+${d}) \u2014 ${te(f)}
|
|
138
|
+
`;return{stdout:Buffer.from(`${O(l.payload)}
|
|
139
|
+
${h}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:l.payload,mintedHandle:f,bytesElided:d,rowsElided:l.rowsElided,rawOutput:Buffer.from(u)}}function Au(e){let t=Be(e);if(t.argv[0]!=="gh")throw new Error("expected rsp gh <surface> <subcommand>");let n=t.argv[1],r=t.argv[2];if(!(n==="pr"||n==="issue"||n==="run"))throw new Error(`unsupported gh surface: ${n??""}`);let s=n==="pr"&&r&&r!=="list"&&r!=="view";if(!(r==="list"||r==="view"||s))throw new Error(`unsupported gh subcommand: ${r??""}`);let i=[],o=!1,a=!1;for(let u of t.argv.slice(3))u==="--full"?o=!0:u==="--wide"?a=!0:i.push(u);return{kind:n,action:s?"combined":r==="list"?"list":"view",target:s?r:void 0,full:o,wide:a,passthrough:i,query:t.query}}function qh(e){if(e.action==="combined")throw new Error("combined gh command uses multiple machine calls");let t=`${e.kind}:${e.action}`,n=e.wide?Uh[t]:jh[t];return[e.kind,e.action,...e.passthrough,"--json",n.join(",")]}async function Jh(e){if(e.action==="combined")return await Hh(e);let t=Cu("gh",qh(e),{stdio:["ignore","pipe","pipe"]}),n=[],r=[];return t.stdout.on("data",s=>n.push(s)),t.stderr.on("data",s=>r.push(s)),await new Promise((s,i)=>{t.on("error",i),t.on("close",(o,a)=>{s({stdout:Buffer.concat(n).toString("utf8"),stderr:Buffer.concat(r).toString("utf8"),status:o,signal:a})})})}async function Hh(e){let t=e.target??"",n=["number","title","state","body","author","labels","url","baseRefName","headRefName"],r=["comments"],[s,i,o]=await Promise.all([ui(["pr","view",t,"--json",n.join(",")]),ui(["pr","checks",t,"--json","name,state,bucket,conclusion,link,startedAt,completedAt,workflow"]),ui(["pr","view",t,"--comments","--json",r.join(",")])]),a=[s,i,o].find(c=>(c.status??0)!==0||c.signal);return a||{stdout:JSON.stringify({view:Rr(s.stdout),checks:Rr(i.stdout),comments:Rr(o.stdout)}),stderr:[s.stderr,i.stderr,o.stderr].filter(Boolean).join(""),status:0,signal:null}}async function ui(e){let t=Cu("gh",e,{stdio:["ignore","pipe","pipe"]}),n=[],r=[];return t.stdout.on("data",s=>n.push(s)),t.stderr.on("data",s=>r.push(s)),await new Promise((s,i)=>{t.on("error",i),t.on("close",(o,a)=>{s({stdout:Buffer.concat(n).toString("utf8"),stderr:Buffer.concat(r).toString("utf8"),status:o,signal:a})})})}function Wh(e,t,n){if(e.action==="list"&&Array.isArray(n)&&n.length===0)return Yh(e.kind);let r={command:t.join(" ")};switch(`${e.kind}:${e.action}`){case"pr:list":{let s=Dt(n).map(o=>Bu(o,e.wide)),i=j(s,e.query);return Ot({...r,prs:i,summary:`${li(i.length,s.length,e.query)} ${$u(i,"open")} PRs`},e,["rsp gh pr <number>","rsp gh pr list --query <title-or-label>"])}case"pr:view":return Ot({...r,pr:Lu(fe(n),e),summary:`PR #${rt(fe(n),"number")}`},e,["rsp gh pr <number>","rsp gh pr view <number> --full"]);case"pr:combined":return Vh(e,t,fe(n));case"issue:list":{let s=Dt(n).map(o=>Mu(o,e.wide)),i=j(s,e.query);return Ot({...r,issues:i,summary:`${li(i.length,s.length,e.query)} ${$u(i,"open")} issues`},e,["rsp gh issue view <number>","rsp gh issue list --query <label-or-title>"])}case"issue:view":return Ot({...r,issue:Qh(fe(n),e),summary:`issue #${rt(fe(n),"number")}`},e,["rsp gh issue view <number> --full"]);case"run:list":{let s=Dt(n).map(o=>ju(o,e.wide)),i=j(s,e.query);return Ot({...r,runs:i,summary:`${li(i.length,s.length,e.query)} runs`},e,["rsp gh run view <id>","rsp gh run list --query <workflow-or-status>"])}case"run:view":return Ot({...r,run:Xh(fe(n),e),summary:`run ${rt(fe(n),"databaseId")}`},e,["rsp gh run view <id> --full"])}throw new Error(`unsupported gh command: ${e.kind} ${e.action}`)}function Vh(e,t,n){let r=Lu(fe(n.view),{...e,action:"view",wide:!0}),s=j(Dt(n.checks).map(Kh),e.query),i=fe(n.comments).comments,o=j(Dt(i).map(zh).slice(-3),e.query);return Le({command:t.join(" "),pr:r,checks:s,comments:o,summary:`PR #${rt(fe(n.view),"number")}: ${s.length} checks, ${o.length} comments`},["rsp gh pr view <number> --full","rsp gh pr <number> --query <check-or-comment>","rsp gh run view <id>"])}function Kh(e){return{name:D(e,"name"),state:bn(e),bucket:D(e,"bucket"),conclusion:D(e,"conclusion"),workflow:D(e,"workflow"),link:D(e,"link")}}function zh(e){return{author:Gu(e.author),body:Sr(e,"body",di,!1),created:D(e,"createdAt")}}function Yh(e){return e==="pr"?`0 open PRs \u2014 try: rsp gh issue list
|
|
133
140
|
`:e==="issue"?`0 open issues \u2014 try: rsp gh issue list --state all
|
|
134
141
|
`:`0 runs \u2014 try: rsp gh run list --limit 20
|
|
135
|
-
`}function
|
|
136
|
-
${
|
|
142
|
+
`}function Bu(e,t){let n={number:rt(e,"number"),title:D(e,"title"),state:bn(e),draft:!!e.isDraft};return t&&Object.assign(n,Uu(e)),n}function Lu(e,t){let n=Bu(e,t.wide);return n.body=Sr(e,"body",di,t.full),t.wide&&(n.base=D(e,"baseRefName"),n.head=D(e,"headRefName")),n}function Mu(e,t){let n={number:rt(e,"number"),title:D(e,"title"),state:bn(e),labels:Fu(e.labels)};return t&&Object.assign(n,Uu(e)),n}function Qh(e,t){let n=Mu(e,t.wide);return n.body=Sr(e,"body",di,t.full),n}function ju(e,t){let n={id:rt(e,"databaseId"),name:D(e,"name"),status:bn(e),conclusion:D(e,"conclusion")};return t&&(n.event=D(e,"event"),n.branch=D(e,"headBranch"),n.workflow=D(e,"workflowName"),n.created=D(e,"createdAt")),n}function Xh(e,t){let n=ju(e,t.wide),r=Dt(e.jobs).map(s=>({name:D(s,"name"),status:bn(s),conclusion:D(s,"conclusion"),log:Sr(s,"log",Fh,t.full)}));return n.jobs=r,n}function Sr(e,t,n,r){let s=D(e,t);if(r||Buffer.byteLength(s)<=n)return s;let i=s.slice(0,n),o={preview:i,truncated:{bytes:Buffer.byteLength(s),shown_bytes:Buffer.byteLength(i),hint:"--full",handle:""}};return Object.defineProperty(o,"__rsp_original",{value:s,enumerable:!1}),o}function Zh(e){let t=[e];for(;t.length>0;){let n=t.pop();if(Array.isArray(n))t.push(...n);else if(It(n)){if(It(n.truncated)&&n.truncated.handle===""&&typeof n.preview=="string"){let r=typeof n.__rsp_original=="string"?n.__rsp_original:n.preview;return{target:n,original:r,bytes:Number(n.truncated.bytes??0)}}t.push(...Object.values(n))}}return null}function ey(e){for(let t of["prs","issues","runs","jobs"]){let n=e[t];if(Array.isArray(n)&&n.length>1)return{payload:{...e,[t]:n.slice(0,1)},rowsElided:n.length-1}}return null}function $u(e,t){return e.every(n=>n.state===t)?t:"returned"}function li(e,t,n){return n?`${e}/${t}`:String(e)}function Ot(e,t,n){return t.query?Le(e,n):e}function bn(e){return(D(e,"state")||D(e,"status")).toLowerCase()}function Uu(e){return{author:Gu(e.author),labels:Fu(e.labels),url:D(e,"url"),updated:D(e,"updatedAt")}}function Fu(e){return Array.isArray(e)?e.map(t=>It(t)?D(t,"name"):String(t)).filter(Boolean):[]}function Gu(e){return It(e)?D(e,"login"):""}function Rr(e){return e.trim()?JSON.parse(e):null}function Dt(e){return Array.isArray(e)?e.filter(It):[]}function fe(e){return It(e)?e:{}}function D(e,t){let n=e[t];return typeof n=="string"?n:""}function rt(e,t){let n=e[t];return typeof n=="number"?n:0}function It(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var jh,Uh,di,Fh,mi=S(()=>{"use strict";oe();nt();_r();jh={"pr:list":["number","title","state","isDraft"],"pr:view":["number","title","state","body"],"issue:list":["number","title","state","labels"],"issue:view":["number","title","state","body"],"run:list":["databaseId","name","status","conclusion"],"run:view":["databaseId","name","status","conclusion","jobs"]},Uh={"pr:list":["number","title","state","isDraft","author","labels","url","updatedAt"],"pr:view":["number","title","state","body","author","labels","url","baseRefName","headRefName"],"issue:list":["number","title","state","labels","author","url","updatedAt"],"issue:view":["number","title","state","body","author","labels","url","updatedAt"],"run:list":["databaseId","name","status","conclusion","event","headBranch","workflowName","createdAt"],"run:view":["databaseId","name","status","conclusion","event","headBranch","workflowName","createdAt","jobs","url"]},di=160,Fh=160});var gi={};B(gi,{renderTestContract:()=>qu,runTestWrapper:()=>iy});import{spawn as ty}from"node:child_process";async function iy(e,t){let n=Be(e),r=await ly(n.argv);return await qu(e,r,t)}async function qu(e,t,n){let r=Be(e),i=Ju(r.argv)==="vitest"?dy(t.stdout):fy(t.stdout),o=t.status;if(!i||(o??0)!==0&&i.failed===0)return{stdout:Buffer.from(Pt(t.stdout,r.query)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let a=`${i.failed}/${i.total} failed \xB7 ${i.suites} suites \xB7 ${gy(i.durationSeconds)}`,c=j(i.failures,r.query);if(n.level==="terse")return await oy(r.argv,t,{...i,failures:c},o,a,n,r.query);let u=[],l,d=0;for(let g of c){let m=await my(g.excerpt,r.argv.join(" "),n.store);u.push({suite:g.suite,name:g.name,excerpt:m.text}),l??=m.handle,d+=m.bytesElided}let f={exit_code:o,summary:r.query?`${a} \xB7 ${c.length}/${i.failures.length} failures matched`:a};u.length>0&&(f.failures=u);let h=r.query?Le(f,["rsp show <handle>","rsp vitest --query <suite-or-test>"]):f;return{stdout:Buffer.from(O(h)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:h,mintedHandle:l,bytesElided:d>0?d:void 0,rowsElided:u.length>0?Math.max(0,i.total-u.length):void 0}}async function oy(e,t,n,r,s,i,o){let a=ay(n.failures),c={exit_code:r,summary:o?`${s} \xB7 ${n.failures.length} failures matched`:s};a.length>0&&(c.failures=a);let u=o?Le(c,["rsp show <handle>","rsp vitest --query <suite-or-test>"]):c,l=O(u),d=Math.max(0,n.failures.length-a.length),f=a.some((x,E)=>x.excerpt!==n.failures[E].excerpt);if(d===0&&!f)return{stdout:Buffer.from(l),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:u};let h={exit_code:r,summary:s};n.failures.length>0&&(h.failures=n.failures.map(x=>({suite:x.suite,name:x.name,excerpt:x.excerpt})));let g=O(h),m=Buffer.byteLength(g),p=await i.store?.mint(Buffer.from(g),{command:e.join(" "),loss:{level:"terse",bytes_elided:m}});if(!p)throw new Error("terse test output requires an elision store");let y=`\u2026 elided ${d>0?`${d} failures`:"full detail"} (+${m}) \u2014 ${te(p)}`;return{stdout:Buffer.from(`${l}
|
|
143
|
+
${y}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:u,mintedHandle:p,bytesElided:m,rowsElided:d,rawOutput:Buffer.from(g)}}function ay(e){let t=[],n=ry;for(let r of e.slice(0,sy)){let s=cy(r.excerpt,Math.min(ny,n));n=Math.max(0,n-Buffer.byteLength(s)),t.push({suite:r.suite,name:r.name,excerpt:s})}return t}function cy(e,t){if(t<=0)return"";let n=e.split(`
|
|
137
144
|
`),r=n.length<=2?e:`${n[0]}
|
|
138
145
|
\u2026
|
|
139
|
-
${n[n.length-1]}`,s=Buffer.from(r);return s.length<=t?r:s.subarray(0,t).toString("utf8").replace(/�$/,"")}function
|
|
140
|
-
`).filter(Boolean).map(c=>
|
|
141
|
-
`)}),i||=1,r||=1,s||=1),s||=n.length,i||=1,r||=Math.max(s,n.length),{failed:s,total:r,suites:i,durationSeconds:o,failures:n}}async function
|
|
142
|
-
\u2026 elided ${o} bytes (+${r.length}) \u2014 ${
|
|
143
|
-
`):""}function
|
|
144
|
-
`;if(!o&&Buffer.byteLength(c)<=
|
|
145
|
-
`;return{stdout:Buffer.from(`${c}${l}`),stderr:Buffer.alloc(0),status:0,signal:null,payload:a,mintedHandle:u,bytesElided:n.length,rawOutput:n}}function
|
|
146
|
-
`),r=n.at(-1)==="",s=r?n.slice(0,-1):n,i=t.limit??
|
|
146
|
+
${n[n.length-1]}`,s=Buffer.from(r);return s.length<=t?r:s.subarray(0,t).toString("utf8").replace(/�$/,"")}function Ju(e){if(e[0]==="vitest")return"vitest";if(e[0]==="cargo"&&e[1]==="test")return"cargo";throw new Error(`unsupported test command: ${e.join(" ")}`)}function uy(e){if(Ju(e)==="vitest"){let s=e.slice(1);return{executable:"vitest",args:s.some(o=>o==="--reporter=json"||o==="--reporter"||o.startsWith("--reporter="))?s:["run","--reporter=json",...s]}}let n=e.slice(1);return{executable:"cargo",args:n.some(s=>s==="--message-format=json"||s.startsWith("--message-format="))?n:["test","--message-format=json",...n.slice(1)]}}async function ly(e){let t=uy(e),n=ty(t.executable,t.args,{stdio:["ignore","pipe","pipe"]}),r=[],s=[];return n.stdout.on("data",i=>r.push(i)),n.stderr.on("data",i=>s.push(i)),await new Promise((i,o)=>{n.on("error",o),n.on("close",(a,c)=>{i({stdout:Buffer.concat(r).toString("utf8"),stderr:Buffer.concat(s).toString("utf8"),status:a,signal:c})})})}function dy(e){let t=Hu(e);if(!je(t))return null;let n=Array.isArray(t.testResults)?t.testResults:[],r=[],s=Ue(t.numTotalTests),i=Ue(t.numFailedTests),o=hy(Ue(t.startTime),Ue(t.endTime));for(let a of n){if(!je(a))continue;let c=me(a.name)||me(a.file)||"",u=Array.isArray(a.assertionResults)?a.assertionResults:[];for(let l of u)je(l)&&l.status==="failed"&&r.push({suite:c,name:me(l.fullName)||me(l.title)||me(l.name),excerpt:py(l.failureMessages)||me(l.failureMessage)})}return s||=n.reduce((a,c)=>!je(c)||!Array.isArray(c.assertionResults)?a:a+c.assertionResults.length,0),i||=r.length,o||=n.reduce((a,c)=>je(c)?a+Ue(c.perfStats&&je(c.perfStats)?c.perfStats.runtime:c.duration)/1e3:a,0),{failed:i,total:s,suites:n.length||1,durationSeconds:o,failures:r}}function fy(e){let t=e.split(`
|
|
147
|
+
`).filter(Boolean).map(c=>Hu(c)).filter(je);if(t.length===0)return null;let n=[],r=0,s=0,i=0,o=0,a=[];for(let c of t){if(c.type==="suite"){c.event==="started"&&(i+=1,r+=Ue(c.test_count)),(c.event==="failed"||c.event==="ok")&&(s+=Ue(c.failed),o+=Ue(c.exec_time));continue}if(c.type==="test"&&c.event==="failed"){n.push({suite:me(c.name).split("::").slice(0,-1).join("::"),name:me(c.name),excerpt:me(c.stdout)});continue}if(c.reason==="compiler-message"&&je(c.message)){let u=me(c.message.rendered);u&&a.push(u)}}return n.length===0&&a.length>0&&(n.push({suite:"cargo check",name:"compile-error",excerpt:a.join(`
|
|
148
|
+
`)}),i||=1,r||=1,s||=1),s||=n.length,i||=1,r||=Math.max(s,n.length),{failed:s,total:r,suites:i,durationSeconds:o,failures:n}}async function my(e,t,n){let r=Buffer.from(e);if(r.length<=pi)return{text:e,bytesElided:0};if(!n)throw new Error("over-limit test failure excerpt requires an elision store");let s=await n.mint(r,{command:t,loss:{level:"brief",bytes_elided:r.length}}),i=r.subarray(0,pi).toString("utf8").replace(/\uFFFD$/,""),o=r.length-Buffer.byteLength(i);return{text:`${i}
|
|
149
|
+
\u2026 elided ${o} bytes (+${r.length}) \u2014 ${te(s)}`,handle:s,bytesElided:r.length}}function Hu(e){try{return JSON.parse(e)}catch{return null}}function py(e){return Array.isArray(e)?e.map(t=>String(t)).filter(Boolean).join(`
|
|
150
|
+
`):""}function gy(e){return`${Number(e.toFixed(1))}s`}function hy(e,t){return e>0&&t>e?(t-e)/1e3:0}function Ue(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function me(e){return typeof e=="string"?e:""}function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var pi,ny,ry,sy,hi=S(()=>{"use strict";oe();nt();_r();pi=320,ny=160,ry=pi,sy=3});var bi={};B(bi,{parseCatCommand:()=>wi,renderCatContract:()=>Ey,runCatWrapper:()=>ky});import{isUtf8 as yy}from"node:buffer";import{readFile as wy}from"node:fs/promises";import{extname as by}from"node:path";async function ky(e,t){let n=wi(e),r=await wy(n.file);return Qu(r)?{stdout:r,stderr:Buffer.alloc(0),status:0,signal:null,rawOutput:r}:await Yu(e,n,r,t)}async function Ey(e,t,n){if((t.status??0)!==0||t.signal)return{stdout:Buffer.from(t.stdout),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let r=wi(e),s=Buffer.from(t.stdout,"utf8");return Qu(s)?{stdout:s,stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,rawOutput:s}:{...await Yu(e,r,s,n),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal}}function wi(e){if(e[0]!=="cat")throw new Error("expected rsp cat <file>");let t=e.slice(1),n="full",r,s=!1,i=[];for(let o=0;o<t.length;o++){let a=t[o];if(a==="--full"){s=!0;continue}if(a==="--head"||a==="--tail"){n=a.slice(2),r=zu(t[++o],yi);continue}if(a.startsWith("--head=")||a.startsWith("--tail=")){let[c,u]=a.split("=",2);n=c.slice(2),r=zu(u,yi);continue}i.push(a)}if(i.length!==1)throw new Error("usage: rsp cat [--full] [--head N|--tail N] <file>");return{file:i[0],mode:n,...r?{limit:r}:{},...s?{inlineFull:s}:{}}}async function Yu(e,t,n,r){let s=n.toString("utf8"),i=vy(s,t);if(t.inlineFull)return{stdout:Buffer.from(i.text),stderr:Buffer.alloc(0),status:0,signal:null,rawOutput:n};let o=r.level!=="lossless"||n.length>Ku(r.heavyByteThreshold,Wu)||i.truncated;if(!Vu(t.file)&&!o)return{stdout:Buffer.from(i.text),stderr:Buffer.alloc(0),status:0,signal:null,rawOutput:n};let a=Vu(t.file)?xy(e,t.file,n,s,r.level,i):Ty(e,t.file,n,s,i),c=`${O(a)}
|
|
151
|
+
`;if(!o&&Buffer.byteLength(c)<=Ku(r.heavyByteThreshold,Wu))return{stdout:Buffer.from(c),stderr:Buffer.alloc(0),status:0,signal:null,payload:a,rawOutput:n};let u=await r.store?.mint(n,{command:e.join(" "),loss:{level:r.level==="lossless"?"terse":r.level,bytes_elided:n.length}});if(!u)throw new Error("rsp cat elision requires an elision store");let l=`\u2026 elided file bytes (+${n.length}) \u2014 ${te(u)}
|
|
152
|
+
`;return{stdout:Buffer.from(`${c}${l}`),stderr:Buffer.alloc(0),status:0,signal:null,payload:a,mintedHandle:u,bytesElided:n.length,rawOutput:n}}function xy(e,t,n,r,s,i){let o=kr(r),a=s==="terse"?Ry:_y,c=kr(i.text),u=c.slice(0,a),l=c.slice(Math.max(u.length,c.length-a));return{command:e.join(" "),file:t,kind:"code",outline_source:"regex",bytes:n.length,lines:o.length,symbols:Py(o),content:{head:u,tail:l,truncated:i.truncated||u.length+l.length<o.length}}}function Ty(e,t,n,r,s){return{command:e.join(" "),file:t,kind:"text",bytes:n.length,lines:kr(r).length,content:kr(s.text),truncated:s.truncated}}function vy(e,t){if(t.mode==="full")return{text:e,truncated:!1};let n=e.split(`
|
|
153
|
+
`),r=n.at(-1)==="",s=r?n.slice(0,-1):n,i=t.limit??yi,o=t.mode==="head"?s.slice(0,i):s.slice(Math.max(0,s.length-i));return{text:`${o.join(`
|
|
147
154
|
`)}${r&&o.length>0?`
|
|
148
|
-
`:""}`,truncated:o.length<s.length}}function
|
|
149
|
-
`);return t.at(-1)===""?t.slice(0,-1):t}function
|
|
155
|
+
`:""}`,truncated:o.length<s.length}}function Py(e){let t=[];for(let n=0;n<e.length;n++){let s=e[n].trim(),i=/^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(class|interface|type)\s+([A-Za-z_$][\w$]*)/.exec(s);if(i){t.push({kind:i[1],name:i[2],line:n+1,signature:s});continue}let o=/^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::[^{]+)?/.exec(s);if(o){t.push({kind:"function",name:o[1],line:n+1,signature:s});continue}let a=/^(?:public\s+|private\s+|protected\s+|static\s+|async\s+)*([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::[^{]+)?\s*\{/.exec(s);a&&!Oy(a[1])&&t.push({kind:"method",name:a[1],line:n+1,signature:s})}return t}function kr(e){let t=e.split(`
|
|
156
|
+
`);return t.at(-1)===""?t.slice(0,-1):t}function Qu(e){return e.includes(0)||!yy(e)}function Vu(e){return Sy.has(by(e).toLowerCase())}function Oy(e){return["for","if","switch","while"].includes(e)}function Ku(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function zu(e,t){let n=Number(e);return Number.isInteger(n)&&n>0?n:t}var Wu,yi,_y,Ry,Sy,_i=S(()=>{"use strict";oe();nt();Wu=8*1024,yi=10,_y=8,Ry=2,Sy=new Set([".c",".cc",".cpp",".cs",".go",".java",".js",".jsx",".mjs",".py",".rs",".ts",".tsx"])});var Er={};B(Er,{parseExecCommandLine:()=>el,renderExecContract:()=>Zu,runExecWrapper:()=>Ay});import{isUtf8 as Dy}from"node:buffer";import{spawn as Iy}from"node:child_process";async function Ay(e,t){let n=el(e),r=await By(n);return await Zu(n,r,t)}async function Zu(e,t,n){let r=Buffer.from(t.stdout,"binary"),s=Buffer.from(t.stderr,"binary");if(r.length===0)return{stdout:r,stderr:s,status:t.status,signal:t.signal,rawOutput:r};let i=Ly(r);if(i.kind==="text"){let d=await mn(i.text,{level:n.level,command:e,store:n.store?{mint:async(...f)=>await n.store.mint(...f)}:void 0});if(d.detected)return{stdout:Buffer.from(d.output),stderr:s,status:t.status,signal:t.signal,mintedHandle:d.handle,bytesElided:d.lossy?r.length:void 0,rawOutput:r}}let o=i.kind==="text"?Buffer.from(i.text):r,a=Uy(n.heavyByteThreshold,$y);if(o.length<=a&&n.level!=="terse")return{stdout:o,stderr:s,status:t.status,signal:t.signal,rawOutput:r};let c=r.length,u=n.level==="lossless"?"terse":n.level,l=await n.store?.mint(r,{command:e,loss:{level:u,bytes_elided:c}});if(!l)throw new Error("rsp exec output elision requires an elision store");return{stdout:Buffer.from(My(o,r.length,l,n.level)),stderr:s,status:t.status,signal:t.signal,mintedHandle:l,bytesElided:c,rawOutput:r}}function el(e){if(e[0]!=="exec")throw new Error("expected rsp exec -- <command line>");let t=e.indexOf("--"),n=t>=0?e.slice(t+1):e.slice(1),r=n.length===1?n[0]:n.join(" ");if(!r.trim())throw new Error("usage: rsp exec -- <command line>");return r}async function By(e){let t=Iy(e,{shell:!0,stdio:["inherit","pipe","pipe"]}),n=[],r=[];return t.stdout.on("data",s=>n.push(s)),t.stderr.on("data",s=>r.push(s)),await new Promise((s,i)=>{t.on("error",i),t.on("close",(o,a)=>{s({stdout:Buffer.concat(n).toString("binary"),stderr:Buffer.concat(r).toString("binary"),status:o,signal:a})})})}function Ly(e){return Dy(e)?{kind:"text",text:Tt(e.toString("utf8"))}:{kind:"bytes"}}function My(e,t,n,r){let i=Math.max(1,Math.floor((r==="terse"?Ny:Cy)/2)),o=Xu(e.subarray(0,i)),a=Xu(e.subarray(Math.max(0,e.length-i))),c=jy(e),u=["stdout summary",`bytes: ${t}`,`lines: ${c}`,"head:",o];return a&&a!==o&&u.push("tail:",a),u.push(`\u2026 elided stdout (+${t}) \u2014 ${te(n)}`),`${u.join(`
|
|
150
157
|
`)}
|
|
151
|
-
`}function
|
|
152
|
-
`),2;let{renderShellInit:p}=await Promise.resolve().then(()=>(
|
|
153
|
-
`),0);if(n.command==="git"&&
|
|
154
|
-
`),0)}if(n.command==="warm-resident"){let m=o(process.cwd()),p=
|
|
155
|
-
`),0}if(!n.storeUri&&s.storeUri.startsWith("file://")&&!
|
|
156
|
-
`),1);let l=(m=!0)=>Promise.resolve(new a(u,{storeUri:s.storeUri,ttlDays:s.ttlDays,ephemeralTtlHours:s.ephemeralTtlHours,byteBudget:s.byteBudget,telemetryTtlDays:s.telemetryTtlDays,telemetryByteBudget:s.telemetryByteBudget,telemetryDrainIntervalMs:s.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:s.telemetryDrainTimeoutMs,idleMs:s.idleMs,clientVersion:t.version},{ensureResident:m})),d=()=>c(u,{storeUri:s.storeUri,ttlDays:s.ttlDays,ephemeralTtlHours:s.ephemeralTtlHours,byteBudget:s.byteBudget,telemetryTtlDays:s.telemetryTtlDays,telemetryByteBudget:s.telemetryByteBudget,telemetryDrainIntervalMs:s.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:s.telemetryDrainTimeoutMs,idleMs:s.idleMs,clientVersion:t.version}),f=async()=>{let{RspElisionStore:m}=await Promise.resolve().then(()=>(
|
|
157
|
-
`),1;let p=await m.telemetryGains(
|
|
158
|
-
`;return process.stdout.write(
|
|
159
|
-
`;return process.stdout.write(
|
|
160
|
-
`),2}catch(m){if(i)return await
|
|
158
|
+
`}function Xu(e){return e.toString("utf8").replace(/�$/g,"")}function jy(e){if(e.length===0)return 0;let t=0;for(let n of e)n===10&&t++;return e[e.length-1]===10?t:t+1}function Uy(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}var $y,Cy,Ny,xr=S(()=>{"use strict";nt();pn();$y=8*1024,Cy=2*1024,Ny=1024});Hr();De();Dn();import{spawn as Fy}from"node:child_process";import{createHash as Gy}from"node:crypto";import{existsSync as _n,readFileSync as qy,readdirSync as Jy,statSync as Hy}from"node:fs";import{tmpdir as Wy}from"node:os";import{dirname as Vy,join as Ge}from"node:path";import{fileURLToPath as rl}from"node:url";function vo(e){let t={app:e,version:Jd(ht("__RED_BUILD_VERSION__",()=>"2.61.0")??"0.0.0-dev"),gitSha:ht("__RED_BUILD_GIT_SHA__",()=>"50ee4834c0036f4d9900052791935e2f8216091b")??"unknown",buildTime:ht("__RED_BUILD_TIME__",()=>"2026-07-17T06:26:58.038Z")??"unknown",bundleAsset:ht("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},n=ht("__REDDB_SDK_VERSION__",()=>"1.23.1"),r=ht("__REDDB_BINARY_TAG__",()=>"v1.23.1");return n&&(t.reddbSdkVersion=n),r&&(t.reddbBinaryTag=r),t}function Jd(e){return e.startsWith("v")?e.slice(1):e}function ht(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}cs();Te();async function Ky(e=process.argv.slice(2)){let t=vo("rsp"),n=uw(e);if(n.command==="hook"&&n.positional[1]==="claude-pre-exec"){let{runClaudePreExecHook:m}=await Promise.resolve().then(()=>(lr(),Ns));return await m()}if(n.command==="hook"&&n.positional[1]==="codex-pre-exec"){let{runCodexPreExecHook:m}=await Promise.resolve().then(()=>(lr(),Ns));return await m()}if(n.command==="hook"&&n.positional[1]==="claude-post-exec"){let{runClaudePostExecHook:m}=await Promise.resolve().then(()=>(pn(),Bs));return await m()}if(n.command==="hook"&&n.positional[1]==="codex-post-exec"){let{runCodexPostExecHook:m}=await Promise.resolve().then(()=>(pn(),Bs));return await m()}if(n.command==="setup"){let{provisionRspRepoStore:m}=await Promise.resolve().then(()=>(Ec(),kc)),p=await m(process.cwd());return process.stdout.write(bw(p)),0}if(n.command==="mcp"){let{runRspMcpServer:m}=await Promise.resolve().then(()=>(Ic(),Dc));return await m(),0}if(n.command==="wait"){let{runWait:m}=await Promise.resolve().then(()=>(Uc(),jc));return await m(n.positional)}if(n.command==="shell-init"){let m=n.positional[1];if(m!=="fish"&&m!=="bash"&&m!=="zsh")return process.stdout.write(`error: usage rsp shell-init fish|bash|zsh
|
|
159
|
+
`),2;let{renderShellInit:p}=await Promise.resolve().then(()=>(qc(),Gc));return process.stdout.write(p(m)),0}let{resolveRspConfig:r}=await Promise.resolve().then(()=>(ue(),Zo)),s=r(process.cwd(),process.env,n.storeUri),i=aw(n.command);if(!s.enabled)return i?await ow(n.positional):(process.stdout.write(`${Pi()}
|
|
160
|
+
`),0);if(n.command==="git"&&Ei(n.positional)){let m=process.hrtime.bigint();return await J(n,await xi(),m,void 0,await zy(process.cwd()))}let{resolveResidentPaths:o,ResidentRspElisionStore:a,ensureResidentServer:c}=await Promise.resolve().then(()=>(Xe(),un));if(n.command==="server"){let{runResidentServer:m}=await Promise.resolve().then(()=>(Ru(),_u)),p=o(process.cwd()),w=pe(n.positional,"--socket")??p.socketPath,y=r(process.cwd(),process.env,n.storeUri??pe(n.positional,"--store-uri"));return y.enabled?(await m({socketPath:w,pidPath:pe(n.positional,"--pid-file")??o(process.cwd()).pidPath,rootDir:p.rootDir,storeUri:y.storeUri,ttlDays:L(n.positional,"--ttl-days")??y.ttlDays,ephemeralTtlHours:L(n.positional,"--ephemeral-ttl-hours")??y.ephemeralTtlHours,byteBudget:L(n.positional,"--byte-budget")??y.byteBudget,telemetryTtlDays:L(n.positional,"--telemetry-ttl-days")??y.telemetryTtlDays,telemetryByteBudget:L(n.positional,"--telemetry-byte-budget")??y.telemetryByteBudget,telemetryDrainIntervalMs:L(n.positional,"--telemetry-drain-interval-ms")??y.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:L(n.positional,"--telemetry-drain-timeout-ms")??y.telemetryDrainTimeoutMs,idleMs:L(n.positional,"--idle-ms")??y.idleMs,residentVersion:pe(n.positional,"--resident-version")??t.version,registryPath:pe(n.positional,"--registry")??p.registryPath}),0):(process.stdout.write(`${Pi()}
|
|
161
|
+
`),0)}if(n.command==="warm-resident"){let m=o(process.cwd()),p=pe(n.positional,"--socket")??m.socketPath,w=pe(n.positional,"--wake-lock")??m.wakeLockPath,y=r(process.cwd(),process.env,n.storeUri??pe(n.positional,"--store-uri"));if(!y.enabled)return 0;let{warmResidentServer:x}=await Promise.resolve().then(()=>(Xe(),un));return await x({...m,socketPath:p,wakeLockPath:w},{storeUri:y.storeUri,ttlDays:L(n.positional,"--ttl-days")??y.ttlDays,ephemeralTtlHours:L(n.positional,"--ephemeral-ttl-hours")??y.ephemeralTtlHours,byteBudget:L(n.positional,"--byte-budget")??y.byteBudget,telemetryTtlDays:L(n.positional,"--telemetry-ttl-days")??y.telemetryTtlDays,telemetryByteBudget:L(n.positional,"--telemetry-byte-budget")??y.telemetryByteBudget,telemetryDrainIntervalMs:L(n.positional,"--telemetry-drain-interval-ms")??y.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:L(n.positional,"--telemetry-drain-timeout-ms")??y.telemetryDrainTimeoutMs,idleMs:L(n.positional,"--idle-ms")??y.idleMs,clientVersion:t.version}),0}let u=o(process.cwd());if(n.command==="proxy"){let{runProxy:m}=await Promise.resolve().then(()=>(oi(),ii));return await m(n.positional,{telemetryRoot:u.rootDir,level:n.level})}if(n.command==="status"||n.command==="sweep"){let{residentRegistryStatus:m,sweepResidentRegistry:p}=await Promise.resolve().then(()=>(Xe(),un)),w=n.command==="sweep"?await p(u):await m(u);return process.stdout.write(`${ye(w)}
|
|
162
|
+
`),0}if(!n.storeUri&&s.storeUri.startsWith("file://")&&!_n(rl(s.storeUri)))return i?await Xy(n,s,u.rootDir):(process.stdout.write(`error: rsp repo store is not provisioned - run /red-setup
|
|
163
|
+
`),1);let l=(m=!0)=>Promise.resolve(new a(u,{storeUri:s.storeUri,ttlDays:s.ttlDays,ephemeralTtlHours:s.ephemeralTtlHours,byteBudget:s.byteBudget,telemetryTtlDays:s.telemetryTtlDays,telemetryByteBudget:s.telemetryByteBudget,telemetryDrainIntervalMs:s.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:s.telemetryDrainTimeoutMs,idleMs:s.idleMs,clientVersion:t.version},{ensureResident:m})),d=()=>c(u,{storeUri:s.storeUri,ttlDays:s.ttlDays,ephemeralTtlHours:s.ephemeralTtlHours,byteBudget:s.byteBudget,telemetryTtlDays:s.telemetryTtlDays,telemetryByteBudget:s.telemetryByteBudget,telemetryDrainIntervalMs:s.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:s.telemetryDrainTimeoutMs,idleMs:s.idleMs,clientVersion:t.version}),f=async()=>{let{RspElisionStore:m}=await Promise.resolve().then(()=>(ze(),en));return await m.open({uri:s.storeUri,ttlDays:s.ttlDays,ephemeralTtlHours:s.ephemeralTtlHours,byteBudget:s.byteBudget})},h=()=>s.storeUri.endsWith("/red-skills.rdb")?l():f(),g;try{if(!n.command||n.command==="stats"){let{stats:m,telemetry:p}=await Zy(s,tl(n.positional,30));return process.stdout.write(dw(m,p,lw(n.positional))),0}if(n.command==="gains"){let m=await h();if(g=()=>m.close(),!Qy(m))return process.stdout.write(`error: rsp gains requires the shared RedDB store
|
|
164
|
+
`),1;let p=await m.telemetryGains(tl(n.positional,28));return process.stdout.write(fw(p)),0}if(n.command==="git"){if(Fe(d()),Ei(n.positional)){let x=process.hrtime.bigint();return await J(n,await xi(),x,void 0,u.rootDir)}let{runGitWrapper:m}=await Promise.resolve().then(()=>(nt(),ci)),p=new st(()=>l(!1));g=()=>p.close();let w=process.hrtime.bigint(),y=await m(n.positional,{level:n.level,store:p,heavyGitByteThreshold:s.heavyGitByteThreshold});return await J(n,y,w,p,u.rootDir)}if(n.command==="gh"){Fe(d());let{runGhWrapper:m}=await Promise.resolve().then(()=>(mi(),fi)),p=new st(()=>l(!1));g=()=>p.close();let w=process.hrtime.bigint(),y=await m(n.positional,{level:n.level,store:p});return await J(n,y,w,p,u.rootDir)}if(n.command==="vitest"||n.command==="cargo"){Fe(d());let{runTestWrapper:m}=await Promise.resolve().then(()=>(hi(),gi)),p=new st(()=>l(!1));g=()=>p.close();let w=process.hrtime.bigint(),y=await m(n.positional,{level:n.level,store:p});return await J(n,y,w,p,u.rootDir)}if(n.command==="cat"){Fe(d());let{runCatWrapper:m}=await Promise.resolve().then(()=>(_i(),bi)),p=new st(()=>l(!1));g=()=>p.close();let w=process.hrtime.bigint(),y=await m(n.positional,{level:n.level,store:p,heavyByteThreshold:s.heavyGitByteThreshold});return await J(n,y,w,p,u.rootDir)}if(n.command==="exec"){Fe(d());let{runExecWrapper:m}=await Promise.resolve().then(()=>(xr(),Er)),p=new st(()=>l(!1));g=()=>p.close();let w=process.hrtime.bigint(),y=await m(n.positional,{level:n.level,store:p,heavyByteThreshold:s.heavyGitByteThreshold});return await J(n,y,w,p,u.rootDir)}if(n.command==="show"&&n.handle){let m=await h();g=()=>m.close();let p=await m.get(n.handle);if(p&&"original"in p&&p.original)return process.stdout.write(p.original),await Ri(u.rootDir,n.handle,!0,p.original.length),0;if(p?.status==="expired"){let y=`expired ${p.expired_at} \u2014 re-run: ${p.command}
|
|
165
|
+
`;return process.stdout.write(y),await Ri(u.rootDir,n.handle,!1,Buffer.byteLength(y,"utf8")),1}let w=`expired unknown \u2014 re-run: ${n.handle}
|
|
166
|
+
`;return process.stdout.write(w),await Ri(u.rootDir,n.handle,!1,Buffer.byteLength(w,"utf8")),1}return process.stdout.write(`error: usage rsp show el:<id>
|
|
167
|
+
`),2}catch(m){if(i)return await vi("wrapper failed",n.positional,m,u.rootDir);throw m}finally{await g?.()}}function pe(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:void 0}function L(e,t){let n=pe(e,t);if(n==null)return;let r=Number(n);return Number.isFinite(r)&&r>0?r:void 0}function Ei(e){return e.length===2&&e[0]==="git"&&e[1]==="status"}async function xi(){if(Yy(process.cwd()))return{stdout:Buffer.from(`git empty
|
|
161
168
|
`),stderr:Buffer.alloc(0),status:0,signal:null};let{spawnSync:e}=await import("node:child_process");if(e("git",["diff-index","--quiet","HEAD","--"],{stdio:"ignore"}).status===0)return{stdout:Buffer.from(`git empty
|
|
162
169
|
`),stderr:Buffer.alloc(0),status:0,signal:null};let n=e("git",["status","--porcelain=v1"],{encoding:"buffer"});if((n.status??0)!==0)return{stdout:n.stdout,stderr:n.stderr,status:n.status??1,signal:n.signal};let r=n.stdout.length===0?Buffer.from(`git empty
|
|
163
|
-
`):n.stdout;return{stdout:r,stderr:n.stderr,status:0,signal:n.signal,rawOutput:r}}async function
|
|
164
|
-
${
|
|
165
|
-
|
|
166
|
-
`)
|
|
167
|
-
`),await fu(e)}function oi(){return"rsp is not enabled in this directory; run /red-setup"}function Wh(e){return e==="git"||e==="gh"||e==="vitest"||e==="cargo"||e==="cat"||e==="exec"||e==="proxy"}async function fu(e){if(e[0]==="exec"||e[0]==="proxy")return await Vh(e);let t=e[0];if(!t)return 2;let{spawn:n}=await import("node:child_process"),r=n(t,e.slice(1),{stdio:"inherit"});return await new Promise(s=>{r.on("error",i=>{process.stderr.write(`${i instanceof Error?i.message:String(i)}
|
|
168
|
-
`),s(127)}),r.on("close",(i,o)=>{if(o){process.kill(process.pid,o),s(128);return}s(i??0)})})}async function Vh(e){let t;try{if(e[0]==="proxy"){let{parseProxyCommandLine:s}=await Promise.resolve().then(()=>(Ms(),Ls));t=s(e)}else{let{parseExecCommandLine:s}=await Promise.resolve().then(()=>(or(),ir));t=s(e)}}catch(s){return process.stderr.write(`${s instanceof Error?s.message:String(s)}
|
|
170
|
+
`):n.stdout;return{stdout:r,stderr:n.stderr,status:0,signal:n.signal,rawOutput:r}}async function zy(e){try{let{resolveResidentPaths:t}=await Promise.resolve().then(()=>(Xe(),un));return t(e).rootDir}catch{return e}}function Yy(e){try{return!_n(`${e}/.git`)||_n(`${e}/.git/index`)?!1:Jy(e).every(t=>t===".git")}catch{return!1}}function Qy(e){return typeof e=="object"&&e!==null&&"telemetryGains"in e&&typeof e.telemetryGains=="function"}var st=class{constructor(t){this.openStore=t}store;metrics;async mint(...t){try{let n=await this.open(),r=await n.mint(...t);return this.metrics=n.lastResponseMetrics?.(),r}catch{return`recovery unavailable (resident cold) \u2014 re-run: ${t[1].command}`}}async close(){if(!this.store)return;let t;try{t=await this.store}catch{return}await t.close()}open(){return this.store??=this.openStore(),this.store}lastResponseMetrics(){return this.metrics}},Ti=class{async mint(t,n){return`recovery unavailable (cold store) \u2014 re-run: ${n.command}`}lastResponseMetrics(){}async close(){}};async function Xy(e,t,n,r){if(process.env.RSP_DEBUG==="1")throw r instanceof Error?r:new Error("cold store");let s=new Ti,i=process.hrtime.bigint();try{if(e.command==="git"){if(Ei(e.positional))return await J(e,await xi(),i,s,n,t);let{runGitWrapper:o}=await Promise.resolve().then(()=>(nt(),ci)),a=await o(e.positional,{level:e.level,store:s,heavyGitByteThreshold:t.heavyGitByteThreshold});return await J(e,a,i,s,n,t)}if(e.command==="gh"){let{runGhWrapper:o}=await Promise.resolve().then(()=>(mi(),fi)),a=await o(e.positional,{level:e.level,store:s});return await J(e,a,i,s,n,t)}if(e.command==="vitest"||e.command==="cargo"){let{runTestWrapper:o}=await Promise.resolve().then(()=>(hi(),gi)),a=await o(e.positional,{level:e.level,store:s});return await J(e,a,i,s,n,t)}if(e.command==="cat"){let{runCatWrapper:o}=await Promise.resolve().then(()=>(_i(),bi)),a=await o(e.positional,{level:e.level,store:s,heavyByteThreshold:t.heavyGitByteThreshold});return await J(e,a,i,s,n,t)}if(e.command==="exec"){let{runExecWrapper:o}=await Promise.resolve().then(()=>(xr(),Er)),a=await o(e.positional,{level:e.level,store:s,heavyByteThreshold:t.heavyGitByteThreshold});return await J(e,a,i,s)}}catch(o){return await vi("wrapper failed",e.positional,o,n)}finally{await s.close()}return await vi("wrapper failed",e.positional,r,n)}async function Zy(e,t){let n={stats:ww(e.telemetryByteBudget),telemetry:Di(t)};if(!e.storeUri.startsWith("file://"))return n;let r=rl(e.storeUri);if(!_n(r))return n;if(!r.endsWith("red-skills.rdb")){let{RspElisionStore:c}=await Promise.resolve().then(()=>(ze(),en)),u=await c.open({uri:e.storeUri,ttlDays:e.ttlDays,ephemeralTtlHours:e.ephemeralTtlHours,byteBudget:e.byteBudget});try{return{stats:await u.stats(),telemetry:Di(t)}}finally{await u.close()}}let{ensureReddbBinaryFromWarmCache:s}=await Promise.resolve().then(()=>(ze(),en));await s();let{readAccountingLaneStats:i,readTelemetryStats:o}=await Promise.resolve().then(()=>(Te(),an)),a=await dt(e.storeUri);try{return{stats:await i(a,e.telemetryByteBudget),telemetry:await o(a,t)}}finally{await a.close()}}async function J(e,t,n,r,s=process.cwd(),i){process.stdout.write(t.stdout),process.stderr.write(t.stderr);let o=Number(process.hrtime.bigint()-n)/1e6;return r?(Fe(sw(s,e,t,o,r.lastResponseMetrics())),i&&ew(s,i)):iw(s,e,t,o),t.signal?(process.kill(process.pid,t.signal),128):t.status??0}function ew(e,t){try{let n=xe(e),r=Hy(n),s=t.telemetryDrainIntervalMs*2;if(r.size<t.telemetryByteBudget&&!rw(n,Date.now()-s))return;let i=tw(e),o=nw(i),a=Ge(o,"rsp.sock"),c=Ge(o,"rsp.pid"),u=Ge(W(i),"rsp-resident.pid.json"),l=Ge(i,".red","tmp","rsp.wake.lock");Fy(process.execPath,[...process.execArgv,process.argv[1]??"","warm-resident","--socket",a,"--pid-file",c,"--store-uri",t.storeUri,"--ttl-days",String(t.ttlDays),"--ephemeral-ttl-hours",String(t.ephemeralTtlHours),"--byte-budget",String(t.byteBudget),"--telemetry-ttl-days",String(t.telemetryTtlDays),"--telemetry-byte-budget",String(t.telemetryByteBudget),"--telemetry-drain-interval-ms",String(t.telemetryDrainIntervalMs),"--telemetry-drain-timeout-ms",String(t.telemetryDrainTimeoutMs),"--idle-ms",String(t.idleMs),"--registry",u,"--wake-lock",l],{cwd:i,detached:!0,stdio:"ignore",env:{...process.env,RSP_RESIDENT_WARMER:"1"}}).unref()}catch{}}function tw(e){let t=e;for(;;){if(_n(Ge(t,".git")))return t;let n=Vy(t);if(n===t)return e;t=n}}function nw(e){let t=Gy("sha256").update(e).digest("hex").slice(0,20),n=process.env.XDG_RUNTIME_DIR;if(n){let s=Ge(n,"red-skills",t);if(Ge(s,"rsp.sock").length<108)return s}let r=typeof process.getuid=="function"?process.getuid():"nouid";return Ge(Wy(),`red-skills-${r}`,t)}function rw(e,t){try{let n=qy(e,"utf8");for(let r of n.split(/\r?\n/))if(r.trim())try{let s=JSON.parse(r),i=typeof s.created_at=="string"?s.created_at:s.ts;if(typeof i=="string"){let o=Date.parse(i);if(Number.isFinite(o)&&o<=t)return!0}}catch{}}catch{}return!1}async function sw(e,t,n,r,s){let i=Buffer.concat([n.stdout,n.stderr]),o=Buffer.concat([n.rawOutput??n.stdout,n.stderr]),{appendTelemetryEvent:a,RSP_ACCOUNTING_EVENTS_COLLECTION:c,RSP_TELEMETRY_INVOCATIONS_COLLECTION:u}=await Promise.resolve().then(()=>(Te(),an));await a(e,{collection:c,event_type:"invocation",ts:new Date().toISOString(),command:Tr(t),command_class:t.command??"unknown",wrapper:t.command,loss:t.level,elided:!!(n.mintedHandle||n.bytesElided),raw_bytes:o.length,emitted_bytes:i.length,wrapper_ms:r,store_open_count:s?.storeOpenCount,store_elapsed_ms:s?.storeElapsedMs}),await a(e,{collection:u,ts:new Date().toISOString(),command:Tr(t),wrapper:t.command,loss:t.level,elided:!!(n.mintedHandle||n.bytesElided),raw_bytes:o.length,emitted_bytes:i.length,raw_text:o.toString("utf8"),emitted_text:i.toString("utf8"),wrapper_ms:r,store_open_count:s?.storeOpenCount,store_elapsed_ms:s?.storeElapsedMs,accounting_recorded:!0})}function iw(e,t,n,r){try{let s=Buffer.concat([n.stdout,n.stderr]),i=Buffer.concat([n.rawOutput??n.stdout,n.stderr]);on(e,{collection:"rsp_accounting_events_v1",event_type:"invocation",ts:new Date().toISOString(),command:Tr(t),command_class:t.command??"unknown",wrapper:t.command,loss:t.level,elided:!!(n.mintedHandle||n.bytesElided),raw_bytes:i.length,emitted_bytes:s.length,wrapper_ms:r}),on(e,{collection:"rsp_telemetry_invocations_v1",ts:new Date().toISOString(),command:Tr(t),wrapper:t.command,loss:t.level,elided:!!(n.mintedHandle||n.bytesElided),raw_bytes:i.length,emitted_bytes:s.length,wrapper_ms:r,accounting_recorded:!0})}catch{}}async function vi(e,t,n,r){if(process.env.RSP_DEBUG==="1")throw n instanceof Error?n:new Error(e);process.stderr.write(`rsp: ${e}, passing through
|
|
171
|
+
`);let s=await sl(t);if(r){let{appendTelemetryEvent:i,RSP_ACCOUNTING_EVENTS_COLLECTION:o,RSP_TELEMETRY_DEGRADATIONS_COLLECTION:a}=await Promise.resolve().then(()=>(Te(),an));Fe(i(r,{collection:o,event_type:"invocation",ts:new Date().toISOString(),command:Oi(t),command_class:t[0]??"unknown",loss:"lossless",raw_bytes:0,emitted_bytes:0,degradation_reason:e})),Fe(i(r,{collection:a,ts:new Date().toISOString(),command:Oi(t),reason:e,accounting_recorded:!0}))}return s}function Fe(e){e.catch(()=>{})}async function Ri(e,t,n,r){let{appendTelemetryEvent:s,RSP_ACCOUNTING_EVENTS_COLLECTION:i}=await Promise.resolve().then(()=>(Te(),an));await s(e,{collection:i,event_type:"show",ts:new Date().toISOString(),command:"rsp show",command_class:"show",handle:t,hit:n,loss:"lossless",raw_bytes:n?r:0,emitted_bytes:r})}async function ow(e){return process.env.RSP_DEBUG==="1"&&process.stderr.write(`rsp: ${Pi()}, passing through
|
|
172
|
+
`),await sl(e)}function Pi(){return"rsp is not enabled in this directory; run /red-setup"}function aw(e){return e==="git"||e==="gh"||e==="vitest"||e==="cargo"||e==="cat"||e==="exec"||e==="proxy"}async function sl(e){if(e[0]==="exec"||e[0]==="proxy")return await cw(e);let t=e[0];if(!t)return 2;let{spawn:n}=await import("node:child_process"),r=n(t,e.slice(1),{stdio:"inherit"});return await new Promise(s=>{r.on("error",i=>{process.stderr.write(`${i instanceof Error?i.message:String(i)}
|
|
173
|
+
`),s(127)}),r.on("close",(i,o)=>{if(o){process.kill(process.pid,o),s(128);return}s(i??0)})})}async function cw(e){let t;try{if(e[0]==="proxy"){let{parseProxyCommandLine:s}=await Promise.resolve().then(()=>(oi(),ii));t=s(e)}else{let{parseExecCommandLine:s}=await Promise.resolve().then(()=>(xr(),Er));t=s(e)}}catch(s){return process.stderr.write(`${s instanceof Error?s.message:String(s)}
|
|
169
174
|
`),2}let{spawn:n}=await import("node:child_process"),r=n(t,{shell:!0,stdio:"inherit"});return await new Promise(s=>{r.on("error",i=>{process.stderr.write(`${i instanceof Error?i.message:String(i)}
|
|
170
|
-
`),s(127)}),r.on("close",(i,o)=>{if(o){process.kill(process.pid,o),s(128);return}s(i??0)})})}function
|
|
171
|
-
`)}function
|
|
172
|
-
`}function
|
|
173
|
-
`)}import.meta.url===`file://${process.argv[1]}`&&
|
|
174
|
-
`),process.exit(1)});export{
|
|
175
|
+
`),s(127)}),r.on("close",(i,o)=>{if(o){process.kill(process.pid,o),s(128);return}s(i??0)})})}function Tr(e){return Oi(e.positional)}function Oi(e){if(e[0]!=="exec")return e.join(" ");try{let t=e.indexOf("--"),n=t>=0?e.slice(t+1):e.slice(1);return n.length===1?n[0]:n.join(" ")}catch{return e.join(" ")}}function uw(e){let t={level:"lossless",positional:[]},n=[];for(let r=0;r<e.length;r++){let s=e[r];s==="--store-uri"?t.storeUri=e[++r]:s==="--brief"?t.level="brief":s==="--terse"?t.level="terse":s==="--query"?t.query=e[++r]:s.startsWith("--query=")?t.query=s.slice(8):n.push(s)}return t.query&&n[0]!=="show"&&!n.some(r=>r==="--query"||r.startsWith("--query="))&&n.push("--query",t.query),t.command=n[0],t.handle=n[1],t.positional=n,t}function tl(e,t){let n=pe(e,"--since")??e.find(i=>i.startsWith("--since="))?.slice(8);if(!n)return t;let r=/^(\d+)(d)?$/.exec(n);if(!r)return t;let s=Number(r[1]);return Number.isFinite(s)&&s>0?s:t}function lw(e){return e.includes("--full")}function dw(e,t=Di(30),n=!1){let r=t.savings.top_commands.slice(0,n?10:3),s=n?t.savings.daily_tokens_saved:t.savings.daily_tokens_saved.slice(-7),i=e.storage_classes??il();return[`records: ${e.records}`,`bytes: ${e.bytes}`,`oldest: ${e.oldest??"none"}`,`budget: ${e.budget}`,"storage_classes:",...yw(i),"savings:",` window_days: ${t.window_days}`,` empty: ${t.empty}`,` invocations: ${t.savings.invocations}`,` elided: ${t.savings.elided}`,` raw_bytes: ${t.savings.raw_bytes}`,` emitted_bytes: ${t.savings.emitted_bytes}`,` bytes_saved: ${t.savings.bytes_saved}`,` tokens_saved: ${mw(t.savings)}`,` dollars_saved_estimate_usd: ${pw(t.savings)}`,` pricing_model_family: ${t.savings.pricing_model_family}`,` pricing_input_usd_per_million_tokens: ${t.savings.pricing_input_usd_per_million_tokens}`,` pricing_note: ${t.savings.pricing_note}`," daily_tokens_saved:",...gw(s),...!n&&t.savings.daily_tokens_saved.length>s.length?[` elided_days: ${t.savings.daily_tokens_saved.length-s.length}`," hint: --full"]:[]," top_commands:",...hw(r),"health:",` degradations: ${t.health.degradations}`,` degradation_rate: ${ki(t.health.degradation_rate)}`,` show_total: ${t.health.show_total}`,` show_hits: ${t.health.show_hits}`,` show_misses: ${t.health.show_misses}`,` show_hit_rate: ${ki(t.health.show_hit_rate)}`,` most_recent_degradation_at: ${t.health.most_recent?.timestamp??"none"}`,` most_recent_degradation_reason: ${t.health.most_recent?.reason??"none"}`," degradations_by_reason:",...nl(t.health.by_reason),"decisions:",` seen: ${t.decisions.seen}`,` contributed: ${t.decisions.contributed}`,` passed: ${t.decisions.passed}`,` failed_open: ${t.decisions.failed_open}`,` contribution_rate: ${ki(t.decisions.contribution_rate)}`," top_pass_reasons:",...nl(t.decisions.top_pass_reasons.slice(0,n?10:3)),"latency:",` wrapper_ms_p50: ${Si(t.latency.wrapper_ms_p50)}`,` wrapper_ms_p95: ${Si(t.latency.wrapper_ms_p95)}`,` store_open_count_sum: ${t.latency.store_open_count_sum}`,` store_elapsed_ms_sum: ${t.latency.store_elapsed_ms_sum}`,` store_elapsed_ms_avg: ${Si(t.latency.store_elapsed_ms_avg)}`,""].join(`
|
|
176
|
+
`)}function fw(e){return`${ye(e)}
|
|
177
|
+
`}function mw(e){return e.tokens_saved_estimated?`${e.tokens_saved_low}-${e.tokens_saved_high} (estimate_midpoint: ${e.tokens_saved}, range_pct: ${e.token_estimate_range_pct})`:String(e.tokens_saved)}function pw(e){return e.dollars_saved_low_usd==null||e.dollars_saved_high_usd==null?Jt(e.dollars_saved_estimate_usd):`${Jt(e.dollars_saved_low_usd)}-${Jt(e.dollars_saved_high_usd)} (estimate_midpoint: ${Jt(e.dollars_saved_estimate_usd)})`}function gw(e){return e.length===0?[" empty: true"]:e.map(t=>` ${t.date}: ${t.tokens_saved}`)}function hw(e){return e.length===0?[" empty: true"]:e.map(t=>` - command: ${t.command} invocations: ${t.invocations} bytes_saved: ${t.bytes_saved} tokens_saved: ${t.tokens_saved}`)}function nl(e){return e.length===0?[" empty: true"]:e.map(t=>` ${t.reason}: ${t.count}`)}function yw(e){return["derivable","re-executable","ephemeral"].map(t=>` ${t}: records: ${e[t].records} bytes: ${e[t].bytes} raw_bytes: ${e[t].raw_bytes}`)}function Si(e){return e==null?"none":String(e)}function ki(e){return e.toFixed(4).replace(/0+$/,"").replace(/\.$/,".0")}function Di(e){return{window_days:e,empty:!0,savings:{invocations:0,elided:0,raw_bytes:0,emitted_bytes:0,bytes_saved:0,tokens_saved:0,tokens_saved_estimated:!1,token_estimate_range_pct:null,tokens_saved_low:null,tokens_saved_high:null,dollars_saved_estimate_usd:0,dollars_saved_low_usd:null,dollars_saved_high_usd:null,pricing_model_family:"gpt-5",pricing_input_usd_per_million_tokens:1.25,pricing_note:"estimate derived from byte-based token estimate when token counts are estimated",daily_tokens_saved:[],top_commands:[]},health:{degradations:0,degradation_rate:0,show_total:0,show_hits:0,show_misses:0,show_hit_rate:0,by_reason:[],most_recent:null},latency:{wrapper_ms_p50:null,wrapper_ms_p95:null,store_open_count_sum:0,store_elapsed_ms_sum:0,store_elapsed_ms_avg:null},decisions:{seen:0,contributed:0,passed:0,failed_open:0,contribution_rate:0,top_pass_reasons:[]}}}function ww(e){return{records:0,bytes:0,oldest:null,budget:e,storage_classes:il()}}function il(){return{derivable:{records:0,bytes:0,raw_bytes:0},"re-executable":{records:0,bytes:0,raw_bytes:0},ephemeral:{records:0,bytes:0,raw_bytes:0}}}function bw(e){let t=e.legacyStoreMigrated?"migrated":e.storeCreated?"created":"existing";return[`config: ${e.configChanged?"updated":"unchanged"}`,`store: ${t}`,""].join(`
|
|
178
|
+
`)}import.meta.url===`file://${process.argv[1]}`&&Ky().then(e=>process.exit(e),e=>{process.stdout.write(`error: ${e instanceof Error?e.message:String(e)}
|
|
179
|
+
`),process.exit(1)});export{Ky as main,bw as renderSetupResult,dw as renderStats};
|