@reddb-io/red-skills 2.56.7 → 2.56.9
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/code-nav.bundle.min.mjs +1 -1
- package/dist/dev.bundle.min.mjs +443 -432
- package/dist/memory.bundle.min.mjs +671 -660
- package/dist/rsp.bundle.min.mjs +104 -93
- package/package.json +1 -1
package/dist/rsp.bundle.min.mjs
CHANGED
|
@@ -1,61 +1,72 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
expected at: ${
|
|
3
|
+
var su=Object.defineProperty;var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var N=(e,t)=>{for(var n in t)su(e,n,{get:t[n],enumerable:!0})};async function oi(e,t){return iu?cu(e,t):ou?lu(e,t):au(e,t)}async function au(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 cu(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:uu(n.stdout),kill(){n.kill()},wait(){return n.exited}}}async function*uu(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 lu(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:du(r.stdout),kill(){try{r.kill("SIGTERM")}catch{}},async wait(){return(await r.status).code??0}}}async function*du(e){let t=e.getReader();try{for(;;){let{value:n,done:r}=await t.read();if(r)return;yield n}}finally{t.releaseLock()}}var iu,ou,ai=R(()=>{iu=typeof globalThis.Bun<"u"&&typeof globalThis.Bun.spawn=="function",ou=typeof globalThis.Deno<"u"&&typeof globalThis.Deno.Command=="function"});import{existsSync as fu}from"node:fs";import{join as mu}from"node:path";function ci(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=mu(n,"bin",t);if(fu(i))return i;throw new Error(`reddb: binary "${t}" not found.
|
|
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
|
|
7
|
+
or check the postinstall log for a download error.`)}var ui=R(()=>{});import{fileURLToPath as pu}from"node:url";import{dirname as gu,resolve as hu,join as Yh}from"node:path";function bu(){return typeof process<"u"&&process.platform==="win32"?"red.exe":"red"}function li(){let e=process.env?.REDDB_BINARY_PATH;return typeof e=="string"&&e!==""&&!process.env?.REDDB_BIN?e:ci({name:bu(),packageRoot:wu,envVar:"REDDB_BIN"})}var yu,wu,di=R(()=>{ui();yu=gu(pu(import.meta.url)),wu=hu(yu,"..")});var _u,Ru,b,on,be=R(()=>{_u=new TextEncoder,Ru=new TextDecoder("utf-8"),b=class extends Error{constructor(t,n,r){super(n),this.name="RedDBError",this.code=t,this.data=r??null}},on=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 b("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(_u.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(Ru.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 b(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 b("CLIENT_CLOSED",t);for(let{reject:r}of this.pending.values())r(n);this.pending.clear()}}});function cr(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:/"?Su(e):Eu(e)}function Su(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 b("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=ku(s),a=n.port?Number(n.port):ar(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 Eu(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 b("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):ar(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 b("UNPARSEABLE_URI",`failed to parse '${e}': ${n.message}`)}return{kind:t.protocol==="https:"?"https":"http",host:t.hostname,port:t.port?Number(t.port):ar(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 b("UNSUPPORTED_SCHEME",`unsupported URI: '${e}'. Use 'red://...' or one of memory://, file://, grpc://, http(s)://`)}function ku(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 b("UNSUPPORTED_PROTO",`unknown proto='${e}'. Supported: red | reds | grpc | grpcs | http | https | pg`)}}function ar(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 ur=R(()=>{be()});function Tu(e){if(typeof e=="string"){let t=new TextEncoder().encode(e);return fi(t)}if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return fi(e);throw new TypeError("cache value must be a string, Uint8Array, or Buffer")}function fi(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 vu(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 xu,Rt,lr=R(()=>{be();xu=new Set(["embedded"]),Rt=class{constructor(t,n){this._client=t,this._transport=n??null}_guard(t){if(this._transport&&xu.has(this._transport))throw new b("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:vu(r.value)}async put(t,n,r,s={}){this._guard("put");let i=Tu(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 dr(e,t){return`${fr(e)}.${Pu(t)}`}function fr(e){let t=String(e),n=t.match(/[^A-Za-z0-9_]/);if(n)throw new b("INVALID_KV_KEY",`invalid KV key "${t}": character "${n[0]}" is not supported`);return t}function Pu(e){let t=String(e);return/^[A-Za-z0-9_]+$/.test(t)?t:`'${t.replace(/'/g,"''")}'`}function Ou(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 mi(e){return`'${String(e).replace(/'/g,"''")}'`}var et,mr=R(()=>{be();et=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(mi).join(", ")}]`:"",o=r.expireMs!=null?` EXPIRE ${Number(r.expireMs)} ms`:"";return this.client.call("query",{sql:`KV PUT ${dr(s,t)} = ${Ou(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 ${dr(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 ${dr(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 b("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 ${fr(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(mi).join(", ")}] FROM ${fr(r)}`});return s.affected??s.affected_rows??s.rows?.[0]?.invalidated??0}async*watch(t,n={}){if(!this.client.baseUrl)throw new b("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 b("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 Wu(e,t,n){let{waitMs:r,group:i=null,count:s=null}=n??{};if(!Number.isInteger(r)||r<0)throw new b("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let o=de(e),a=de(t),c=i!=null?` GROUP ${de(i)}`:"",u=s!=null?Er(s):"";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 b("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function Er(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new b("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function Ku(e){if(!Number.isInteger(e))throw new b("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function zu(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new b("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${Ku(e.priority)}`),e.key!=null&&(t+=` KEY ${kr(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${kr(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function Yu(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?kr(e):JSON.stringify(e)}function kr(e){return`'${String(e).replace(/'/g,"''")}'`}function Sr(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var vt,xr=E(()=>{Se();vt=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 i=zu(r);return this.client.call("query",{sql:`QUEUE PUSH ${de(t)} ${Yu(n)}${i}`})}async pop(t,n){let r=await this.client.call("query",{sql:`QUEUE POP ${de(t)}${Er(n)}`});return Sr(r)}async peek(t,n){let r=await this.client.call("query",{sql:`QUEUE PEEK ${de(t)}${Er(n)}`});return Sr(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 i=Wu(t,n,r),s=await this.client.call("query",{sql:i});return Sr(s)}}});function bs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new b("INVALID_ARGUMENT",`${t} must be an object`)}function Qu(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new b("INVALID_ARGUMENT","limit must be a positive integer");return e}function ln(e){return String(e).split(".").map(_s).join(".")}function _s(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new b("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function Xu(e){return Rs(JSON.stringify(e))}function Zu(e){return JSON.stringify(e)}function el(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?Xu(e):Rs(e)}function Rs(e){return`'${String(e).replace(/'/g,"''")}'`}var Ot,Tr=E(()=>{Se();Ot=class{constructor(t){this.db=t}async insert(t,n){bs(n,"documents.insert document"),await this.ensureCollection(t);let r=await this.db.query(`INSERT INTO ${ln(t)} DOCUMENT VALUES (${Zu(n)}) RETURNING *`),i=r.rows?.[0];if(!i||i.rid==null)throw new b("INVALID_RESPONSE","documents.insert expected one returned item with rid");return{affected:r.affected??1,rid:i.rid,item:i}}async get(t,n){let r=await this.db.get(t,n);if(!r.entity)throw new b("NOT_FOUND",`document ${String(n)} was not found`);return r.entity}async list(t,n={}){let r=Qu(n.limit),i=n.orderBy??n.order_by??"rid ASC",s=n.filter?` WHERE ${String(n.filter)}`:"";return{items:(await this.db.query(`SELECT * FROM ${ln(t)}${s} ORDER BY ${i} LIMIT ${r}`)).rows??[]}}async patch(t,n,r){bs(r,"documents.patch patch");let i=Object.entries(r);if(i.length===0)throw new b("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of i)if(c.includes("/"))throw new b("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let s=i.map(([c,u])=>`${_s(c)} = ${el(u)}`).join(", "),a=(await this.db.query(`UPDATE ${ln(t)} SET ${s} WHERE rid = $1 RETURNING *`,n)).rows?.[0];if(!a)throw new b("NOT_FOUND",`document ${String(n)} was not found`);return a}async delete(t,n){let i=(await this.db.delete(t,n)).affected??0;return{affected:i,deleted:i>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 tl(e,t){if(t.secretRef){let{collection:n,key:r}=t.secretRef;return`SECRET_REF(vault, ${Ee(n)}.${Ee(r)})`}return rl(e)}function nl(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 rl(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Ss(e)}function Ss(e){return`'${String(e).replace(/'/g,"''")}'`}var Pt,vr=E(()=>{Pt=class{constructor(t,n="red.config"){this.client=t,this.collection=n}put(t,n,r={}){nl(r,"config");let i=r.collection??this.collection,s=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(Ss).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${Ee(i)} ${Ee(t)} = ${tl(n,r)}${s}`})}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 il(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 it(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 sl(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):Es(e)}function Es(e){return`'${String(e).replace(/'/g,"''")}'`}var Dt,Or=E(()=>{Dt=class{constructor(t,n="red.vault"){this.client=t,this.collection=n}put(t,n,r={}){il(r,"vault");let i=r.collection??this.collection,s=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(Es).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${it(i)}.${it(t)} = ${sl(n)}${s}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${it(r)}.${it(t)}`})}unseal(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${it(r)}.${it(t)}`})}}});async function xs(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(ol)}async function Ts(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${cl(t)}`)).rows??[]).some(r=>r.name===String(t))}function ol(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function ks(e){return String(e).split(".").map(al).join(".")}function al(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new b("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function cl(e){return`'${String(e).replace(/'/g,"''")}'`}var It,Pr=E(()=>{Se();It=class e{constructor(t,n,r=null,i=[],s=[]){this.db=t,this.collection=n,this.columns=r,this.whereClauses=i,this.params=s}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 b("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(ks).join(", "),n=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(o=>`(${o})`).join(" AND ")}`:"",r=`SELECT ${t} FROM ${ks(this.collection)}${n}`,s=(this.params.length>0?await this.db.query(r,this.params):await this.db.query(r)).rows??[];return this.columns==null?s:s.map(o=>{let a={};for(let c of this.columns)a[c]=o[c];return a})}}});async function mn(e,t={}){let n=yr(e);if(wl(n),n.kind==="embedded"){let r=hl(n,t.auth);if(r.token||r.username)throw new b("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let i=yl(n),s=t.binary??gs(),o=await ds(s,i),a=new un(o);return await a.call("version",{}),new Ir(a,{transport:"embedded"})}}function Os(e){return dl(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:ml(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&gl(e)?{$uuid:e}:e}function dl(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new b("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 b("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new b("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function fl(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(Os):e.map(Os)}function ml(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 pl(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 gl(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 pl(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,i]of Object.entries(e))n[r]=dn(i);return n}return e}function yl(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function hl(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 wl(e){if(e.kind!=="embedded")throw new b("EMBEDDED_ONLY",ul)}function $r(){return new b(vs,`${vs}: nested transactions are not supported on one connection`)}function Ds(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function bl(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new b("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${Ps} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function _l(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new b("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${Ps} 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 b("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}var ul,ll,Ps,vs,fn,Dr,Ir,Ar=E(()=>{fs();ys();Se();hr();wr();Rr();xr();Tr();vr();Or();Pr();wr();Rr();xr();Tr();vr();Or();Pr();hr();ul="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",ll="1.0",Ps="1.0.9",vs="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 $r()}},Dr=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw $r();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 b("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 b("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 b("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){Ds(n,r)}throw n}}},Ir=class{constructor(t,n={}){this.client=t,this.transport=n.transport??null,this.helperSpecVersion=ll,this.cache=new Tt(t,this.transport),this.queue=new vt(t),this.queues=this.queue,this.documents=new Ot(this);let r=new rt(t);this.kv=Object.assign((i="kv_default")=>new rt(t,i),{put:r.put.bind(r),invalidateTags:r.invalidateTags.bind(r),watch:r.watch.bind(r),watchPrefix:r.watchPrefix.bind(r)}),this.config=(i="red.config")=>new Pt(t,i),this.vault=(i="red.vault")=>new Dt(t,i),this.inTransaction=!1}query(t,...n){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new b("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let r=fl(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 bl(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 _l(r,n.length)}tx(){return new Dr(this)}async transaction(t){if(this.inTransaction)throw $r();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(i){Ds(r,i)}throw r}finally{this.inTransaction=!1}}exists(t){return Ts(this,t)}list(){return xs(this)}from(t){return new It(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 Cs(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001F]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function Ls(e){let t="",n=0;for(;n<e.length;){if(e[n]==="\\"){if(n+1>=e.length)throw new SyntaxError("Invalid escape sequence: backslash at end of string");let r=e[n+1];if(r==="n"){t+=`
|
|
12
|
-
`,n+=2;continue}if(r==="t"){t+=" ",n+=2;continue}if(r==="r"){t+="\r",n+=2;continue}if(r==="\\"){t+="\\",n+=2;continue}if(r==='"'){t+='"',n+=2;continue}if(r==="u"){if(n+6>e.length)throw new SyntaxError(`Invalid escape sequence: truncated \\u escape at "${e.slice(n,n+6)}"`);let i=e.slice(n+2,n+6);if(!/^[0-9a-f]{4}$/i.test(i))throw new SyntaxError(`Invalid escape sequence: \\u must be followed by 4 hex digits, got "${i}"`);let s=Number.parseInt(i,16);if(s>=55296&&s<=57343)throw new SyntaxError(`Invalid escape sequence: \\u${i} is a lone surrogate; supplementary code points MUST appear as literal UTF-8`);t+=String.fromCodePoint(s),n+=6;continue}throw new SyntaxError(`Invalid escape sequence: \\${r}`)}t+=e[n],n++}return t}function bn(e,t){let n=t+1;for(;n<e.length;){if(e[n]==="\\"&&n+1<e.length){n+=2;continue}if(e[n]==='"')return n;n++}return-1}function Cr(e,t,n=0){let r=!1,i=n;for(;i<e.length;){if(e[i]==="\\"&&i+1<e.length&&r){i+=2;continue}if(e[i]==='"'){r=!r,i++;continue}if(e[i]===t&&!r)return i;i++}return-1}function J(e,t){try{return t()}catch(n){throw n instanceof H?n:n instanceof Error?new H(n.message,{line:e.lineNumber,source:e.raw,cause:n}):n}}function Ms(e){return e==="true"||e==="false"||e==="null"}function El(e){if(!e||!Sl.test(e))return!1;let t=Number(e);return!Number.isNaN(t)&&Number.isFinite(t)}function yn(e,t,n=!1){let r=e.trimStart(),i=-1;if(r.startsWith('"')){let p=bn(r,0);if(p===-1||!r.slice(p+1).startsWith("["))return;let k=e.length-r.length+p+1;i=e.indexOf("[",k)}else i=e.indexOf("[");if(i===-1)return;let s=e.indexOf("]",i);if(s===-1)return;let o=s+1,a=o,c=e.indexOf("{",s);if(c!==-1&&c<e.indexOf(":",s)){let p=e.slice(s+1,c);if(p!==""){if(n){let R=p.trim();throw new SyntaxError(R===""?"Unexpected whitespace between bracket and fields segment":`Unexpected content "${R}" between bracket and fields segment`)}return}let k=e.indexOf("}",c);k!==-1&&(a=k+1)}if(o=e.indexOf(":",Math.max(s,a)),o===-1)return;let u=Math.max(s+1,a),l=e.slice(u,o);if(l!==""){if(n){let p=l.trim();throw new SyntaxError(p===""?"Unexpected whitespace between bracket segment and colon":`Unexpected content "${p}" between bracket segment and colon`)}return}let d;if(i>0){let p=e.slice(0,i).trim();d=p.startsWith('"')?Nr(p):p}let f=e.slice(o+1).trim(),w=e.slice(i+1,s),y;try{y=xl(w,t)}catch(p){if(n)throw p;return}let{length:m,delimiter:g}=y,S;if(c!==-1&&c<o){let p=e.indexOf("}",c);if(p!==-1&&p<o){let k=e.slice(c+1,p),R=vl(k,g);if(R!==void 0){if(n)throw new SyntaxError(`Header delimiter mismatch: bracket declares "${Is(g)}" but fields segment contains unquoted "${Is(R)}"`);return}S=Lr(k,g).map(T=>Nr(T.trim()))}}return{header:{key:d,length:m,delimiter:g,fields:S},inlineValues:f||void 0}}function xl(e,t){let n=e,r=t;if(n.endsWith(" ")?(r=gn.tab,n=n.slice(0,-1)):n.endsWith("|")&&(r=gn.pipe,n=n.slice(0,-1)),!kl.test(n))throw new SyntaxError(`Invalid array length: "${e}" (expected non-negative integer with no leading zeros)`);return{length:Number.parseInt(n,10),delimiter:r}}function vl(e,t){for(let n of Tl)if(n!==t&&Cr(e,n)!==-1)return n}function Is(e){return e===" "?"\\t":e}function Lr(e,t){let n=[],r="",i=!1,s=0;for(;s<e.length;){let o=e[s];if(o==="\\"&&s+1<e.length&&i){r+=o+e[s+1],s+=2;continue}if(o==='"'){i=!i,r+=o,s++;continue}if(o===t&&!i){n.push(r.trim()),r="",s++;continue}r+=o,s++}return(r||n.length>0)&&n.push(r.trim()),n}function js(e){return e.map(t=>_n(t))}function _n(e){let t=e.trim();if(!t)return"";if(t.startsWith('"'))return Nr(t);if(Ms(t)){if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null}if(El(t)){let n=Number.parseFloat(t);return Object.is(n,-0)?0:n}return t}function Nr(e){let t=e.trim();if(t.startsWith('"')){let n=bn(t,0);if(n===-1)throw new SyntaxError("Unterminated string: missing closing quote");if(n!==t.length-1)throw new SyntaxError("Unexpected characters after closing quote");return Ls(t.slice(1,n))}return t}function Ol(e,t){let n=t;for(;n<e.length&&e[n]!==":";)n++;if(n>=e.length||e[n]!==":")throw new SyntaxError("Missing colon after key");let r=e.slice(t,n).trim();return n++,{key:r,end:n}}function Pl(e,t){let n=bn(e,t);if(n===-1)throw new SyntaxError("Unterminated quoted key");let r=Ls(e.slice(t+1,n)),i=n+1;if(i>=e.length||e[i]!==":")throw new SyntaxError("Missing colon after key");return i++,{key:r,end:i}}function Dl(e,t){let n=e[t]==='"';return{...n?Pl(e,t):Ol(e,t),isQuoted:n}}function Us(e){return e.trim().startsWith("[")&&Cr(e,":")!==-1}function Il(e){return Cr(e,":")!==-1}function $l(){return{lineNumber:0,blankLines:[]}}function Al(e,t,n,r){t.lineNumber++;let i=t.lineNumber,s=0;for(;s<e.length&&e[s]===" ";)s++;let o=e.slice(s);if(!o.trim()){let c=$s(s,n);t.blankLines.push({lineNumber:i,indent:s,depth:c});return}let a=$s(s,n);if(r){let c=0;for(;c<e.length&&(e[c]===" "||e[c]===" ");)c++;if(e.slice(0,c).includes(" "))throw new H("Tabs are not allowed in indentation in strict mode",{line:i,source:e});if(s>0&&s%n!==0)throw new H(`Indentation must be exact multiple of ${n}, but found ${s} spaces`,{line:i,source:e})}return{raw:e,indent:s,content:o,depth:a,lineNumber:i}}function*Nl(e,t,n,r){for(let i of e){let s=Al(i,r,t,n);s!==void 0&&(yield s)}}function $s(e,t){return Math.floor(e/t)}function $t(e,t,n,r,i){if(r.strict&&e!==t)throw new H(`Expected ${t} ${n}, but got ${e}`,{line:i.lineNumber,source:i.raw})}function Bl(e,t,n){if(e?.depth===t&&e.content.startsWith("- "))throw new H(`Expected ${n} list array items, but found more`,{line:e.lineNumber,source:e.raw})}function Cl(e,t,n){if(e?.depth===t&&!e.content.startsWith("- ")&&Ll(e.content,n.delimiter))throw new H(`Expected ${n.length} tabular rows, but found more`,{line:e.lineNumber,source:e.raw})}function Fs(e,t,n,r,i){if(!r)return;let s=n.find(o=>o.lineNumber>e&&o.lineNumber<t);if(s)throw new H(`Blank lines inside ${i} are not allowed in strict mode`,{line:s.lineNumber})}function Ll(e,t){let n=e.indexOf(":"),r=e.indexOf(t);return n===-1||r!==-1&&r<n}function*jl(e,t){if(t?.expandPaths!==void 0)throw new Error("expandPaths is not supported in streaming decode");let n={indent:t?.indent??2,strict:t?.strict??!0},r=$l(),i=new Ml(Nl(e,n.indent,n.strict,r),r),s=i.peekSync();if(!s){yield{type:"startObject"},yield{type:"endObject"};return}if(s.content.trim()==="[]"){i.advanceSync(),yield{type:"startArray",length:0},yield{type:"endArray"};return}if(Us(s.content)){let a=J(s,()=>yn(s.content,te,n.strict));if(a){i.advanceSync(),yield*hn(a.header,a.inlineValues,i,0,n,s);return}}if(i.advanceSync(),i.atEndSync()&&!Ns(s)){yield{type:"primitive",value:J(s,()=>_n(s.content.trim()))};return}if(!Ns(s)&&i.peekSync()?.depth===0)throw new H("Top-level document must start with a key-value or array-header line",{line:s.lineNumber,source:s.raw});let o=n.strict?new Set:void 0;for(yield{type:"startObject"},yield*st(s,i,0,n,o);!i.atEndSync();){let a=i.peekSync();if(!a||a.depth!==0)break;i.advanceSync(),yield*st(a,i,0,n,o)}yield{type:"endObject"}}function As(e,t,n){if(n){if(n.has(e))throw new H(`Duplicate sibling key "${e}"`,{line:t.lineNumber,source:t.raw});n.add(e)}}function*st(e,t,n,r,i){let s=e.content,o=J(e,()=>yn(s,te,r.strict));if(o&&o.header.key!==void 0){As(o.header.key,e,i),yield{type:"key",key:o.header.key},yield*hn(o.header,o.inlineValues,t,n,r,e);return}let{key:a,isQuoted:c}=J(e,()=>Dl(s,0)),u=s.indexOf(":",a.length),l=u>=0?s.slice(u+1).trim():"";if(As(a,e,i),yield c?{type:"key",key:a,wasQuoted:!0}:{type:"key",key:a},!l){let d=t.peekSync();if(d&&d.depth>n){yield{type:"startObject"},yield*Ul(t,n+1,r),yield{type:"endObject"};return}yield{type:"startObject"},yield{type:"endObject"};return}if(l==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}yield{type:"primitive",value:J(e,()=>_n(l))}}function*Ul(e,t,n){let r,i=n.strict?new Set:void 0;for(;!e.atEndSync();){let s=e.peekSync();if(!s||s.depth<t)break;if(r===void 0&&s.depth>=t&&(r=s.depth),s.depth===r)e.advanceSync(),yield*st(s,e,r,n,i);else break}}function*hn(e,t,n,r,i,s){if(yield{type:"startArray",length:e.length},t){yield*Fl(e,t,i,s),yield{type:"endArray"};return}if(e.fields&&e.fields.length>0){yield*Gl(e,n,r,i,s),yield{type:"endArray"};return}yield*ql(e,n,r,i,s),yield{type:"endArray"}}function*Fl(e,t,n,r){if(!t.trim()){$t(0,e.length,"inline array items",n,r);return}let i=J(r,()=>Lr(t,e.delimiter)),s=J(r,()=>js(i));$t(s.length,e.length,"inline array items",n,r);for(let o of s)yield{type:"primitive",value:o}}function*Gl(e,t,n,r,i){let s=n+1,o=0,a,c,u=i;for(;!t.atEndSync()&&o<e.length;){let l=t.peekSync();if(!l||l.depth<s)break;if(l.depth===s){a===void 0&&(a=l.lineNumber),c=l.lineNumber,u=l,t.advanceSync();let d=J(l,()=>Lr(l.content,e.delimiter));$t(d.length,e.fields.length,"tabular row values",r,l);let f=J(l,()=>js(d));yield*Hl(e.fields,f),o++}else break}$t(o,e.length,"tabular rows",r,u),r.strict&&a!==void 0&&c!==void 0&&Fs(a,c,t.getBlankLines(),r.strict,"tabular array"),r.strict&&Cl(t.peekSync(),s,e)}function*ql(e,t,n,r,i){let s=n+1,o=0,a,c,u=i;for(;!t.atEndSync()&&o<e.length;){let l=t.peekSync();if(!l||l.depth<s)break;let d=l.content.startsWith("- ")||l.content==="-";if(l.depth===s&&d){a===void 0&&(a=l.lineNumber),c=l.lineNumber,u=l,yield*Jl(t,s,r);let f=t.current();f&&(c=f.lineNumber,u=f),o++}else break}$t(o,e.length,"list array items",r,u),r.strict&&a!==void 0&&c!==void 0&&Fs(a,c,t.getBlankLines(),r.strict,"list array"),r.strict&&Bl(t.peekSync(),s,e.length)}function*Jl(e,t,n){let r=e.nextSync();if(!r)throw new ReferenceError("Expected list item");let i;if(r.content==="-"){yield{type:"startObject"},yield{type:"endObject"};return}else if(r.content.startsWith("- "))i=r.content.slice(2);else throw new H('Expected list item to start with "- "',{line:r.lineNumber,source:r.raw});if(!i.trim()){yield{type:"startObject"},yield{type:"endObject"};return}if(i.trim()==="[]"){yield{type:"startArray",length:0},yield{type:"endArray"};return}let s={...r,content:i};if(Us(i)){let a=J(s,()=>yn(i,te,n.strict));if(a){yield*hn(a.header,a.inlineValues,e,t,n,s);return}}let o=J(s,()=>yn(i,te,n.strict));if(o&&o.header.key!==void 0&&o.header.fields!==void 0){let a=o.header,c=n.strict?new Set([a.key]):void 0;yield{type:"startObject"},yield{type:"key",key:a.key},yield*hn(a,o.inlineValues,e,t+1,n,s);let u=t+1;for(;!e.atEndSync();){let l=e.peekSync();if(!l||l.depth<u)break;if(l.depth===u&&!l.content.startsWith("- "))e.advanceSync(),yield*st(l,e,u,n,c);else break}yield{type:"endObject"};return}if(Il(i)){let a=n.strict?new Set:void 0;yield{type:"startObject"},yield*st(s,e,t+1,n,a);let c=t+1;for(;!e.atEndSync();){let u=e.peekSync();if(!u||u.depth<c)break;if(u.depth===c&&!u.content.startsWith("- "))e.advanceSync(),yield*st(u,e,c,n,a);else break}yield{type:"endObject"};return}yield{type:"primitive",value:J(s,()=>_n(i))}}function Ns(e){let t=e.content;if(t.startsWith('"')){let n=bn(t,0);return n===-1?!1:t.slice(n+1).includes(":")}else return t.includes(":")}function*Hl(e,t){yield{type:"startObject"};for(let n=0;n<e.length;n++)yield{type:"key",key:e[n]},yield{type:"primitive",value:t[n]};yield{type:"endObject"}}function fe(e){if(e===null)return null;if(typeof e=="object"&&e!==null&&"toJSON"in e&&typeof e.toJSON=="function"){let t=e.toJSON();if(t!==e)return fe(t)}if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e=="bigint")return e>=Number.MIN_SAFE_INTEGER&&e<=Number.MAX_SAFE_INTEGER?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(fe);if(e instanceof Set)return Array.from(e).map(fe);if(e instanceof Map)return Object.fromEntries(Array.from(e,([t,n])=>[String(t),fe(n)]));if(Vl(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(t[n]=fe(e[n]));return t}return null}function je(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function ke(e){return Array.isArray(e)}function B(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function At(e){return Object.keys(e).length===0}function Vl(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Nt(e){return e.length===0||e.every(t=>je(t))}function Wl(e){return e.length===0||e.every(t=>ke(t))}function Gs(e){return e.length===0||e.every(t=>B(t))}function Yl(e){return/^[A-Z_][\w.]*$/i.test(e)}function qs(e){return/^[A-Z_]\w*$/i.test(e)}function Ql(e,t=te){return!(!e||e!==e.trim()||Ms(e)||Xl(e)||e.includes(":")||e.includes('"')||e.includes("\\")||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith("-"))}function Xl(e){return Kl.test(e)||zl.test(e)}function pn(e,t){if(Array.isArray(e))return e.map(n=>pn(n,t));if(B(e)){let n={},r=e[Js];for(let[i,s]of Object.entries(e)){let o=r?.has(i);if(i.includes(".")&&!o){let c=i.split(".");if(c.every(u=>qs(u))){Zl(n,c,pn(s,t),t);continue}}let a=pn(s,t);if(i in n){let c=n[i];if(jr(c,a))Mr(c,a,t);else{if(t)throw new TypeError(`Path expansion conflict at key "${i}": cannot merge ${typeof c} with ${typeof a}`);n[i]=a}}else n[i]=a}return n}return e}function Zl(e,t,n,r){let i=e;for(let a=0;a<t.length-1;a++){let c=t[a],u=i[c];if(u===void 0){let l={};i[c]=l,i=l}else if(B(u))i=u;else{if(r)throw new TypeError(`Path expansion conflict at segment "${c}": expected object but found ${typeof u}`);let l={};i[c]=l,i=l}}let s=t[t.length-1],o=i[s];if(o===void 0)i[s]=n;else if(jr(o,n))Mr(o,n,r);else{if(r)throw new TypeError(`Path expansion conflict at key "${s}": cannot merge ${typeof o} with ${typeof n}`);i[s]=n}}function Mr(e,t,n){for(let[r,i]of Object.entries(t)){let s=e[r];if(s===void 0)e[r]=i;else if(jr(s,i))Mr(s,i,n);else{if(n)throw new TypeError(`Path expansion conflict at key "${r}": cannot merge ${typeof s} with ${typeof i}`);e[r]=i}}}function jr(e,t){return B(e)&&B(t)}function ed(e){let t={stack:[],root:void 0};for(let n of e)td(t,n);return nd(t)}function td(e,t){let{stack:n}=e;switch(t.type){case"startObject":{let r={},i=new Set;if(n.length===0)n.push({type:"object",obj:r,quotedKeys:i});else{let s=n[n.length-1];if(s.type==="object"){if(s.currentKey===void 0)throw new Error("Object startObject event without preceding key");s.obj[s.currentKey]=r,s.currentKey=void 0}else s.type==="array"&&s.arr.push(r);n.push({type:"object",obj:r,quotedKeys:i})}break}case"endObject":{if(n.length===0)throw new Error("Unexpected endObject event");let r=n.pop();if(r.type!=="object")throw new Error("Mismatched endObject event");r.quotedKeys.size>0&&Object.defineProperty(r.obj,Js,{value:r.quotedKeys,enumerable:!1,writable:!1,configurable:!1}),n.length===0&&(e.root=r.obj);break}case"startArray":{let r=[];if(n.length===0)n.push({type:"array",arr:r});else{let i=n[n.length-1];if(i.type==="object"){if(i.currentKey===void 0)throw new Error("Array startArray event without preceding key");i.obj[i.currentKey]=r,i.currentKey=void 0}else i.type==="array"&&i.arr.push(r);n.push({type:"array",arr:r})}break}case"endArray":{if(n.length===0)throw new Error("Unexpected endArray event");let r=n.pop();if(r.type!=="array")throw new Error("Mismatched endArray event");n.length===0&&(e.root=r.arr);break}case"key":{if(n.length===0)throw new Error("Key event outside of object context");let r=n[n.length-1];if(r.type!=="object")throw new Error("Key event in non-object context");r.currentKey=t.key,t.wasQuoted&&r.quotedKeys.add(t.key);break}case"primitive":if(n.length===0)e.root=t.value;else{let r=n[n.length-1];if(r.type==="object"){if(r.currentKey===void 0)throw new Error("Primitive event without preceding key in object");r.obj[r.currentKey]=t.value,r.currentKey=void 0}else r.type==="array"&&r.arr.push(t.value)}break}}function nd(e){if(e.stack.length!==0)throw new Error("Incomplete event stream: stack not empty at end");if(e.root===void 0)throw new Error("No root value built from events");return e.root}function rd(e,t,n,r,i,s,o){if(r.keyFolding!=="safe"||!B(t))return;let{segments:a,tail:c,leafValue:u}=id(e,t,o??r.flattenDepth);if(a.length<2||!a.every(f=>qs(f)))return;let l=sd(a),d=s?`${s}.${l}`:l;if(!n.includes(l)&&!(i&&i.has(d)))return{foldedKey:l,remainder:c,leafValue:u,segmentCount:a.length}}function id(e,t,n){let r=[e],i=t;for(;r.length<n&&B(i);){let s=Object.keys(i);if(s.length!==1)break;let o=s[0],a=i[o];r.push(o),i=a}return!B(i)||At(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function sd(e){return e.join(".")}function at(e,t){return e===null?Rl:typeof e=="boolean"||typeof e=="number"?String(e):od(e,t)}function od(e,t=te){return Ql(e,t)?e:`"${Cs(e)}"`}function ct(e){return Yl(e)?e:`"${Cs(e)}"`}function Hs(e,t=te){return e.map(n=>at(n,t)).join(t)}function Ue(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??",",s="";if(n!=null&&(s+=ct(n)),s+=`[${e}${i!==te?i:""}]`,r){let o=r.map(a=>ct(a));s+=`{${o.join(i)}}`}return s+=":",s}function*ad(e,t,n){if(je(e)){let r=at(e,t.delimiter);r!==""&&(yield r);return}ke(e)?yield*Br(void 0,e,n,t):B(e)&&(yield*ot(e,n,t))}function*ot(e,t,n,r,i,s){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(c=>c.includes("."))));let a=s??n.flattenDepth;for(let[c,u]of Object.entries(e))yield*cd(c,u,t,n,o,r,i,a)}function*cd(e,t,n,r,i,s,o,a){let c=o?`${o}.${e}`:e,u=a??r.flattenDepth;if(r.keyFolding==="safe"&&i){let d=rd(e,t,i,r,s,o,u);if(d){let{foldedKey:f,remainder:w,leafValue:y,segmentCount:m}=d,g=ct(f);if(w===void 0){if(je(y)){yield U(n,`${g}: ${at(y,r.delimiter)}`,r.indent);return}else if(ke(y)){yield*Br(f,y,n,r);return}else if(B(y)&&At(y)){yield U(n,`${g}:`,r.indent);return}}if(B(w)){yield U(n,`${g}:`,r.indent);let S=u-m,p=o?`${o}.${f}`:f;yield*ot(w,n+1,r,s,p,S);return}}}let l=ct(e);je(t)?yield U(n,`${l}: ${at(t,r.delimiter)}`,r.indent):ke(t)?yield*Br(e,t,n,r):B(t)&&(yield U(n,`${l}:`,r.indent),At(t)||(yield*ot(t,n+1,r,s,c,u)))}function*Br(e,t,n,r){if(t.length===0){yield U(n,e!=null?`${ct(e)}: []`:"[]",r.indent);return}if(Nt(t)){yield U(n,Rn(t,r.delimiter,e),r.indent);return}if(Wl(t)&&t.every(i=>Nt(i))){yield*ud(e,t,n,r);return}if(Gs(t)){let i=Vs(t);i?yield*ld(e,t,i,n,r):yield*Bs(e,t,n,r);return}yield*Bs(e,t,n,r)}function*ud(e,t,n,r){yield U(n,Ue(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let i of t)if(Nt(i)){let s=Rn(i,r.delimiter);yield ee(n+1,s,r.indent)}}function Rn(e,t,n){let r=Ue(e.length,{key:n,delimiter:t}),i=Hs(e,t);return e.length===0?r:`${r} ${i}`}function*ld(e,t,n,r,i){yield U(r,Ue(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Ws(t,n,r+1,i)}function Vs(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&dd(e,n))return n}function dd(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let r of t)if(!(r in n)||!je(n[r]))return!1}return!0}function*Ws(e,t,n,r){for(let i of e)yield U(n,Hs(t.map(s=>i[s]),r.delimiter),r.indent)}function*Bs(e,t,n,r){yield U(n,Ue(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let i of t)yield*Ur(i,n+1,r)}function*fd(e,t,n){if(At(e)){yield U(t,"-",n.indent);return}let r=Object.entries(e),[i,s]=r[0],o=r.slice(1);if(ke(s)&&Gs(s)){let c=Vs(s);if(c){yield ee(t,Ue(s.length,{key:i,fields:c,delimiter:n.delimiter}),n.indent),yield*Ws(s,c,t+2,n),o.length>0&&(yield*ot(Object.fromEntries(o),t+1,n));return}}let a=ct(i);if(je(s))yield ee(t,`${a}: ${at(s,n.delimiter)}`,n.indent);else if(ke(s))if(s.length===0)yield ee(t,`${a}: []`,n.indent);else if(Nt(s))yield ee(t,`${a}${Rn(s,n.delimiter)}`,n.indent);else{yield ee(t,`${a}${Ue(s.length,{delimiter:n.delimiter})}`,n.indent);for(let c of s)yield*Ur(c,t+2,n)}else B(s)&&(yield ee(t,`${a}:`,n.indent),At(s)||(yield*ot(s,t+2,n)));o.length>0&&(yield*ot(Object.fromEntries(o),t+1,n))}function*Ur(e,t,n){if(je(e))yield ee(t,at(e,n.delimiter),n.indent);else if(ke(e))if(Nt(e))yield ee(t,Rn(e,n.delimiter),n.indent);else{yield ee(t,Ue(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Ur(r,t+1,n)}else B(e)&&(yield*fd(e,t,n))}function U(e,t,n){return" ".repeat(n*e)+t}function ee(e,t,n){return U(e,"- "+t,n)}function md(e,t){let n=t("",e,[]);return n===void 0?wn(e,t,[]):wn(fe(n),t,[])}function wn(e,t,n){return B(e)?pd(e,t,n):ke(e)?gd(e,t,n):e}function pd(e,t,n){let r={};for(let[i,s]of Object.entries(e)){let o=[...n,i],a=t(i,s,o);a!==void 0&&(r[i]=wn(fe(a),t,o))}return r}function gd(e,t,n){let r=[];for(let i=0;i<e.length;i++){let s=e[i],o=[...n,i],a=t(String(i),s,o);if(a===void 0)continue;let c=fe(a);r.push(wn(c,t,o))}return r}function O(e,t){return Array.from(Ks(e,t)).join(`
|
|
13
|
-
|
|
14
|
-
`),t)}function
|
|
15
|
-
`)
|
|
16
|
-
`)}
|
|
17
|
-
`)
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
`)}function jd(e,t){let n=Buffer.byteLength(e,"utf8");return n<=t?e:Buffer.from(e,"utf8").subarray(n-t).toString("utf8").replace(/^\uFFFD+/,"")}async function ro(e,t){try{let n=await Lt(e.registryPath);if(!n||n.socket_path!==e.socketPath||n.store_uri!==t.storeUri)return;if(!dt(n.pid)){await ne(e.registryPath,{force:!0});return}if(await Fe(n.socket_path,100))return;if(wo(t.clientVersion,n.resident_version)&&(await Ud(n.pid,1500),!dt(n.pid))){await ne(e.registryPath,{force:!0});return}await yo(n.pid),await ne(e.registryPath,{force:!0})}catch{}}function dt(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function yo(e){if(!dt(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!dt(e))return;await new Promise(n=>setTimeout(n,50))}try{process.kill(e,"SIGKILL")}catch{}}async function Ud(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!dt(e))return;await new Promise(r=>setTimeout(r,50))}}async function Fd(e){if(!e.startsWith("file://"))return!1;try{return await Dd(uo(e)),!1}catch(t){return t.code==="ENOENT"}}function ho(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?kn(process.argv[1]):uo(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function Gd(e){let t=Td("sha256").update(e).digest("hex").slice(0,20),n=process.env.XDG_RUNTIME_DIR;if(n){let i=V(n,"red-skills",t);if(V(i,"rsp.sock").length<Ad)return i}let r=typeof process.getuid=="function"?process.getuid():"nouid";return V($d(),`red-skills-${r}`,t)}function qd(e){let t=kn(e);for(let n=0;n<32;n++){try{let i=Kr(V(t,".git"));if(i!=null)return Jd(t,i)??t;if(Kr(V(t,".git","HEAD"))!=null||Kr(V(t,".red","config.yaml"))!=null)return t}catch{}let r=Te(t);if(r===t)return null;t=r}return null}function Jd(e,t){let n=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!n)return null;let r=kn(e,n[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(r)?Te(Te(Te(r))):null}function Kr(e){try{return vd(e,"utf8")}catch{return null}}async function io(e,t){let n=await fo(e).catch(()=>null);return n?wo(t.clientVersion,n.version)?(await Hd(e,t.clientVersion),await zd(e),!1):!0:!1}async function Hd(e,t){try{await lt({socketPath:e,timeoutMs:200},{id:oo(),op:"handover",clientVersion:t})}catch{}}function wo(e,t){return!e||!t?!1:Vd(e,t)>0}function Vd(e,t){let n=so(e),r=so(t);return!n||!r?0:n.major-r.major||n.minor-r.minor||n.patch-r.patch}function so(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 bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wd(e){return typeof e=="string"&&e.length>0?e:void 0}function Kd(e){return bo(e)&&e.version===lo&&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 zd(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await Fe(e,50))return;await new Promise(n=>setTimeout(n,50))}}var Ad,lo,Nd,Md,Pn=E(()=>{Hr();Ad=108,lo=1,Nd=5e3;Md=8*1024});var xo={};$(xo,{DEFAULT_RSP_BYTE_BUDGET:()=>he,DEFAULT_RSP_EPHEMERAL_TTL_HOURS:()=>ye,DEFAULT_RSP_HEAVY_GIT_BYTE_THRESHOLD:()=>pe,DEFAULT_RSP_IDLE_MS:()=>An,DEFAULT_RSP_STORE_PATH:()=>Dn,DEFAULT_RSP_TELEMETRY_BYTE_BUDGET:()=>$n,DEFAULT_RSP_TELEMETRY_DRAIN_INTERVAL_MS:()=>So,DEFAULT_RSP_TELEMETRY_DRAIN_TIMEOUT_MS:()=>Eo,DEFAULT_RSP_TELEMETRY_TTL_DAYS:()=>In,DEFAULT_RSP_TTL_DAYS:()=>ge,MIN_RSP_IDLE_MS:()=>ko,resolveRspConfig:()=>we});import{readFileSync as Yd}from"node:fs";import{join as _o,resolve as Ro}from"node:path";function we(e,t,n){let r=eo(Ro(e),_o(".red","config.yaml")),i=r?Yd(r,"utf8"):"",s=Sn(i,"rsp.enabled")==="true",o=Sn(i,"rsp.proxy.enabled")==="true",a=me(re(i,"rsp.ttlDays"),ge),c=me(Mt(t.RSP_EPHEMERAL_TTL_HOURS)??re(i,"rsp.ephemeralTtlHours"),ye),u=me(re(i,"rsp.byteBudget"),he),l=me(re(i,"rsp.telemetryTtlDays"),In),d=me(re(i,"rsp.telemetryByteBudget")??re(i,"rsp.byteBudget"),$n),f=me(Mt(t.RSP_TELEMETRY_DRAIN_INTERVAL_MS)??re(i,"rsp.telemetryDrainIntervalMs"),So),w=me(Mt(t.RSP_TELEMETRY_DRAIN_TIMEOUT_MS)??re(i,"rsp.telemetryDrainTimeoutMs"),Eo),y=Qd(Mt(t.RSP_IDLE_MS)??re(i,"rsp.idleMs"),An,ko),m=me(Mt(t.RSP_HEAVY_GIT_BYTE_THRESHOLD)??re(i,"rsp.heavyGitByteThreshold"),pe),g=ve(e).rootDir,S=n??t.RSP_STORE_URI??`file://${_o(Ro(g),Dn)}`;return{enabled:s,proxyEnabled:o,storeUri:S,ttlDays:a,ephemeralTtlHours:c,byteBudget:u,telemetryTtlDays:l,telemetryByteBudget:d,telemetryDrainIntervalMs:f,telemetryDrainTimeoutMs:w,idleMs:y,heavyGitByteThreshold:m}}function re(e,t){let n=Sn(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 Qd(e,t,n){let r=me(e,t);return Math.max(r,n)}function Mt(e){if(e==null||e.trim()==="")return;let t=Number(e);return Number.isFinite(t)?t:void 0}var pe,Dn,ge,ye,he,In,$n,So,Eo,An,ko,ie=E(()=>{"use strict";to();Pn();pe=8*1024,Dn=".red/tmp/red-skills.rdb",ge=7,ye=6,he=64*1024*1024,In=90,$n=4*1024*1024,So=3e4,Eo=2e3,An=5*6e4,ko=5e3});var To=E(()=>{"use strict";Hr()});var Ut={};$(Ut,{ResidentRspElisionStore:()=>jt,ensureResidentServer:()=>xn,kickResidentServer:()=>Tn,pingResident:()=>Fe,readResidentRegistry:()=>Lt,removeResidentRegistry:()=>On,residentRegistryStatus:()=>Ct,resolveResidentPaths:()=>ve,sweepResidentRegistry:()=>po,warmResidentServer:()=>mo,writeResidentRegistry:()=>vn});import{randomUUID as Xd}from"node:crypto";function vo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var jt,Ge=E(()=>{"use strict";To();Pn();jt=class{constructor(t,n,r={}){this.paths=t;this.config=n;this.opts=r}metrics;lastResponseMetrics(){return this.metrics}async mint(t,n){let i=(await this.request({op:"mint",original:Buffer.from(t).toString("base64"),meta:n})).handle;if(!i?.startsWith("el:"))throw new Error("resident rsp returned invalid handle");return i}async get(t){let n=await this.request({op:"get",handle:t});return n?vo(n)&&n.status==="expired"?n:!vo(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 xn(this.paths,this.config);let n=await lt(this.paths,{...t,id:Xd()});if(!n.ok)throw new Error(n.error);return this.metrics={storeOpenCount:n.storeOpenCount,storeElapsedMs:n.storeElapsedMs},n.value}}});var Ht={};$(Ht,{DEFAULT_RSP_BYTE_BUDGET:()=>he,DEFAULT_RSP_EPHEMERAL_TTL_HOURS:()=>ye,DEFAULT_RSP_TTL_DAYS:()=>ge,RSP_ELISION_COLLECTION:()=>F,RspElisionStore:()=>qt,ensureReddbBinaryFromWarmCache:()=>Uo,storageClassForCommand:()=>Je});import{createHash as Ln}from"node:crypto";import{spawnSync as Gt}from"node:child_process";import{existsSync as Zd}from"node:fs";import{mkdir as ef,readFile as ti,readdir as Co,rename as tf,writeFile as nf}from"node:fs/promises";import{homedir as rf}from"node:os";import{basename as ni,dirname as Lo,join as mt}from"node:path";import{fileURLToPath as sf}from"node:url";import{gunzipSync as of,gzipSync as af}from"node:zlib";function Oo(e,t){return`el:${Ln("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 qe(e){return`expired:${e.slice(3)}`}function zr(){return"index:v1"}function cf(e){return`blob:${e}`}function Je(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":Mn(t)?"re-executable":"ephemeral"}return"ephemeral"}function Ft(e){return jn(e.storage_class)?e.storage_class:Je(e.command)}function uf(e){return jn(e.storage_class)?e.storage_class:Je(e.command)}function Po(e){let t=pf(),n={derivable:new Set,"re-executable":new Set,ephemeral:new Set};for(let r of e){let i=uf(r);if(t[i].records+=1,t[i].raw_bytes+=r.raw_bytes??r.bytes,r.blob_key){if(n[i].has(r.blob_key))continue;n[i].add(r.blob_key)}t[i].bytes+=r.bytes}return t}function Do(e,t,n,r){let i=t==="ephemeral"?r*60*60*1e3:n*24*60*60*1e3;return new Date(e.getTime()+i).toISOString()}function ft(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 Io(e,t){let n=process.cwd(),r=Gt("git",["rev-parse","--is-inside-work-tree"],{cwd:n,encoding:"utf8"});if(r.status!==0||r.stdout.trim()!=="true")return null;let i=Gt("git",["hash-object","-w","--stdin"],{cwd:n,input:e,encoding:"buffer"});if(i.status!==0)return null;let s=i.stdout.toString("utf8").trim();return/^[0-9a-f]{40,64}$/.test(s)?{kind:"git-blob",command:t,cwd:n,object_ids:[s],working_tree_fingerprint:lf(n),original_bytes:e.length}:null}function lf(e){let t=Yr(e,["rev-parse","HEAD"])||"unborn",n=Yr(e,["write-tree"])||"no-index",r=Yr(e,["status","--porcelain=v1","-z"])||"";return Ln("sha256").update(t).update("\0").update(n).update("\0").update(r).digest("hex")}function Yr(e,t){let n=Gt("git",t,{cwd:e,encoding:"utf8"});return n.status===0?n.stdout.trim():null}function $o(e,t){let n=t.trim().split(/\s+/).filter(Boolean);if(!Mn(n))return null;let r=Mo(process.cwd(),n,e.length);return!r||gt(r)!==gt(e)?null:{kind:"command",command:t,cwd:process.cwd(),argv:n,original_bytes:e.length,content_hash:gt(e)}}function Mn(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 gt(e){return Ln("sha256").update("rsp-reexecutable-content-v1\0").update(e).digest("hex")}function Ao(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 Qr(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 No(e,t,n){let r=af(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 df(e){try{let t=of(Buffer.from(e.bytes,"base64"));return t.length===e.original_bytes?t:null}catch{return null}}function ff(e){let t=e.object_ids[0];if(!t)return null;let n=Gt("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 mf(e){if(!Mn(e.argv))return null;let t=Mo(e.cwd,e.argv,e.original_bytes);return t?gt(t)===e.content_hash?t:Buffer.concat([Buffer.from(`reconstructed after state moved - current snapshot follows
|
|
21
|
-
|
|
22
|
-
`,"utf8"),await tf(n,e)}function Bo(){return{version:1,records:{},blobs:{},tombstones:{},index:{version:1,records:[]}}}function vf(e){return W(e)&&e.version===1&&W(e.records)&&Object.values(e.records).every(pt)&&(e.blobs===void 0||W(e.blobs)&&Object.values(e.blobs).every(ei))&&W(e.tombstones)&&Object.values(e.tombstones).every(Cn)&&Zr(e.index)}function Of(e){if(!e.startsWith("file://"))throw new Error("rsp elision store requires a file:// URI");return sf(e)}var F,qt,He=E(()=>{"use strict";Ar();ie();F="rsp_elisions_v1",qt=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=Of(t.uri),r=await kf(n),i=new e(r,{uri:t.uri,ttlDays:Xr(t.ttlDays,ge),ephemeralTtlHours:Xr(t.ephemeralTtlHours,ye),byteBudget:Xr(t.byteBudget,he),now:t.now??(()=>new Date)});return jo(r)?(await Uo(),i.db=await mn(`file://${r}`),await i.ensureRedDbCollections(),await i.ensureRedDbStore()):i.document=await Ef(i.path),i}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),i=this.opts.now(),s=i.toISOString(),o=Oo(r,n),a=be(o),c=Je(n.command),u=c==="derivable"?Io(r,n.command):null,l=c==="re-executable"?$o(r,n.command):null,d=c==="derivable"&&!u||c==="re-executable"&&!l?"ephemeral":c,f=Do(i,d,this.opts.ttlDays,this.opts.ephemeralTtlHours),w=gt(r),y=d==="ephemeral"?No(r,w,s):null,m=Ao(r,u,l,y);y&&!this.document.blobs[y.key]&&(this.document.blobs[y.key]=y,this.dirty=!0);let g={collection:F,handle:o,original_bytes:r.length,stored_bytes:m,command:n.command,created_at:s,expires_at:f,loss:n.loss,storage_class:d,content_hash:w,...u?{derivation_recipe:u}:l?{reexecution_recipe:l}:{blob_key:y?.key}};return delete this.document.tombstones[qe(o)],this.document.records[a]=g,this.upsertIndex({handle:o,key:a,bytes:m,raw_bytes:r.length,command:n.command,created_at:s,expires_at:f,storage_class:d,blob_key:y?.key}),this.prune(),await this.flush(),o}async get(t){if(this.db)return await this.getRedDb(t);if(!Jt(t))return null;let n=this.tombstone(t);if(n)return n;let r=this.document.records[be(t)];if(!pt(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let s={status:"expired",expired_at:r.expires_at,command:r.command};return this.expireEntry({handle:r.handle,key:be(r.handle),bytes:Qr(r),raw_bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at,storage_class:Ft(r),blob_key:r.blob_key},r.expires_at),await this.flush(),s}let i=await this.readOriginal(r);return!i&&(r.derivation_recipe||r.reexecution_recipe)?{status:"expired",expired_at:r.expires_at,command:r.command}:i?{collection:F,handle:r.handle,original:i,command:r.command,created_at:r.created_at,loss:r.loss,storage_class:Ft(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:ft(n),oldest:n.reduce((r,i)=>r==null||i.created_at<r?i.created_at:r,null),budget:this.opts.byteBudget,storage_classes:Po(n)}}readIndex(){return this.document.index}writeIndex(t){this.document.index=t}upsertIndex(t){let r=this.readIndex().records.filter(i=>i.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(),i=[];for(let o of r.records)Date.parse(o.expires_at)<=t?this.expireEntry(o,o.expires_at):i.push(o);let s=ft(i);for(i.sort((o,a)=>o.created_at.localeCompare(a.created_at));s>this.opts.byteBudget&&i.length>0;){let o=i.shift();this.expireEntry(o,n),s=ft(i)}i.length<r.records.length&&this.writeIndex({version:1,records:i}),this.deleteUnreferencedLocalBlobs(i)}expireEntry(t,n){delete this.document.records[t.key],this.document.tombstones[qe(t.handle)]={status:"expired",expired_at:n,command:t.command},this.dirty=!0}tombstone(t){let n=this.document.tombstones[qe(t)];return Cn(n)?n:null}async readOriginal(t){if(t.original)return Buffer.from(t.original,"base64");if(t.derivation_recipe)return ff(t.derivation_recipe);if(t.reexecution_recipe)return mf(t.reexecution_recipe);if(t.blob_key){let n=this.db?await this.kvGet(t.blob_key):this.document.blobs[t.blob_key];return ei(n)?df(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 Fo(this.path,this.document),this.dirty=!1)}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(r=>r.name===F);if(!t){await this.db.query(`CREATE KV IF NOT EXISTS ${F}`);return}if(t.model==="kv")return;if(t.model!=="table")throw new Error(`cannot self-heal elision collection ${F}: unsupported model ${t.model}`);let n=await this.readLegacyElisionTableRows();await this.db.query(`DROP TABLE ${F}`),await this.db.query(`CREATE KV IF NOT EXISTS ${F}`);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 ${F}`),n=[];for(let r of t.rows){let i=hf(r);i&&n.push(i)}return n}async ensureMigratedRedDbIndex(t){if(t.some(i=>i.key===zr()&&Zr(Bn(i.value))))return;let r=t.map(i=>{let s=Bn(i.value);return pt(s)?{handle:s.handle,key:be(s.handle),bytes:Qr(s),raw_bytes:s.original_bytes,command:s.command,created_at:s.created_at,expires_at:s.expires_at,storage_class:Ft(s),blob_key:s.blob_key}:null}).filter(i=>i!=null);await this.writeRedDbIndex({version:1,records:r})}async mintRedDb(t,n){let r=Buffer.from(t),i=this.opts.now(),s=i.toISOString(),o=Oo(r,n),a=be(o),c=Je(n.command),u=c==="derivable"?Io(r,n.command):null,l=c==="re-executable"?$o(r,n.command):null,d=c==="derivable"&&!u||c==="re-executable"&&!l?"ephemeral":c,f=Do(i,d,this.opts.ttlDays,this.opts.ephemeralTtlHours),w=gt(r),y=d==="ephemeral"?No(r,w,s):null,m=Ao(r,u,l,y);y&&!ei(await this.kvGet(y.key))&&await this.kv().put(y.key,y);let g={collection:F,handle:o,original_bytes:r.length,stored_bytes:m,command:n.command,created_at:s,expires_at:f,loss:n.loss,storage_class:d,content_hash:w,...u?{derivation_recipe:u}:l?{reexecution_recipe:l}:{blob_key:y?.key}};await this.kv().delete(qe(o)),await this.kv().put(a,g);let p=(await this.readRedDbIndex()).records.filter(k=>k.handle!==o);return p.push({handle:o,key:a,bytes:m,raw_bytes:r.length,command:n.command,created_at:s,expires_at:f,storage_class:d,blob_key:y?.key}),await this.pruneRedDb({version:1,records:p},!0),await this.assertRedDbMintPersisted(o,m),o}async getRedDb(t){if(!Jt(t))return null;let n=await this.kvGet(qe(t));if(Cn(n))return n;let r=await this.kvGet(be(t));if(!pt(r))return null;if(Date.parse(r.expires_at)<=this.opts.now().getTime()){let s={status:"expired",expired_at:r.expires_at,command:r.command};return await this.expireRedDbEntry({handle:r.handle,key:be(r.handle),bytes:Qr(r),raw_bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at,storage_class:Ft(r),blob_key:r.blob_key},r.expires_at),s}let i=await this.readOriginal(r);return!i&&(r.derivation_recipe||r.reexecution_recipe)?{status:"expired",expired_at:r.expires_at,command:r.command}:i?{collection:F,handle:r.handle,original:i,command:r.command,created_at:r.created_at,loss:r.loss,storage_class:Ft(r)}:null}async statsRedDb(){let t=await this.pruneRedDb(await this.readRedDbIndex());return{records:t.records.length,bytes:ft(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:Po(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=gf(n);return await this.memoryRecallRedDb(r.query,r.limit)}if(t==="ingest"){let r=yf(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 wf(t.cwd,t.maxFiles??200,t.ignore??[]),r=0;for(let i of n){let o=(await ti(i,"utf8").catch(()=>"")).trim();if(!o)continue;let a=ni(i),c=Ln("sha256").update("resident-memory-v1\0").update(i).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:i,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:[i],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"),i=t.toLowerCase().split(/\s+/).filter(Boolean),s=r.rows.map(o=>bf(o,i)).filter(o=>o!=null).sort((o,a)=>a.score-o.score).slice(0,Math.max(1,Math.min(100,n)));return{hits:s,context_md:s.map(o=>`- memory_nodes:${o.rid} ${o.label}: ${o.excerpt}`).join(`
|
|
23
|
-
`)
|
|
24
|
-
|
|
11
|
+
`).find(d=>d.startsWith("data: "));l&&(yield JSON.parse(l.slice(6)))}}watchPrefix(t,n={}){return this.watch(`${t}.*`,n)}}});function Du(e,t,n){let{waitMs:r,group:s=null,count:i=null}=n??{};if(!Number.isInteger(r)||r<0)throw new b("INVALID_QUEUE_WAIT","queue readWait requires an explicit non-negative integer waitMs (no infinite wait)");let o=ue(e),a=ue(t),c=s!=null?` GROUP ${ue(s)}`:"",u=i!=null?gr(i):"";return`QUEUE READ ${o}${c} CONSUMER ${a}${u} WAIT ${r}ms`}function ue(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new b("INVALID_QUEUE_NAME",`invalid queue name "${t}": expected an SQL identifier`);return t}function gr(e){if(e==null)return"";if(!Number.isInteger(e)||e<0)throw new b("INVALID_QUEUE_COUNT","queue count must be a non-negative integer");return` COUNT ${e}`}function Iu(e){if(!Number.isInteger(e))throw new b("INVALID_QUEUE_PRIORITY","queue priority must be an integer");return String(e)}function $u(e){if(e.key!=null&&(e.delay!=null||e.at!=null))throw new b("INVALID_ARGUMENT","QUEUE PUSH KEY cannot be combined with DELAY / AVAILABLE AT");let t="";return e.priority!=null&&(t+=` PRIORITY ${Iu(e.priority)}`),e.key!=null&&(t+=` KEY ${hr(e.key)}`),e.dedup!=null&&(t+=` DEDUP ${hr(e.dedup)}`),e.delay!=null&&(t+=` DELAY ${e.delay}`),e.at!=null&&(t+=` AVAILABLE AT ${e.at}`),t}function Nu(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":typeof e=="string"?hr(e):JSON.stringify(e)}function hr(e){return`'${String(e).replace(/'/g,"''")}'`}function pr(e){return Array.isArray(e?.rows)?e.rows.map(t=>t.payload):[]}var St,yr=R(()=>{be();St=class{constructor(t){this.client=t}create(t){return this.client.call("query",{sql:`CREATE QUEUE IF NOT EXISTS ${ue(t)}`})}push(t,n,r={}){let s=$u(r);return this.client.call("query",{sql:`QUEUE PUSH ${ue(t)} ${Nu(n)}${s}`})}async pop(t,n){let r=await this.client.call("query",{sql:`QUEUE POP ${ue(t)}${gr(n)}`});return pr(r)}async peek(t,n){let r=await this.client.call("query",{sql:`QUEUE PEEK ${ue(t)}${gr(n)}`});return pr(r)}async len(t){let n=await this.client.call("query",{sql:`QUEUE LEN ${ue(t)}`});return Number(n?.rows?.[0]?.len??0)}purge(t){return this.client.call("query",{sql:`QUEUE PURGE ${ue(t)}`})}async readWait(t,n,r={}){let s=Du(t,n,r),i=await this.client.call("query",{sql:s});return pr(i)}}});function pi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new b("INVALID_ARGUMENT",`${t} must be an object`)}function Bu(e){if(e==null)return 100;if(!Number.isInteger(e)||e<=0)throw new b("INVALID_ARGUMENT","limit must be a positive integer");return e}function an(e){return String(e).split(".").map(gi).join(".")}function gi(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new b("INVALID_ARGUMENT",`invalid SQL identifier "${t}"`);return t}function Cu(e){return hi(JSON.stringify(e))}function Au(e){return JSON.stringify(e)}function Lu(e){return e==null?"NULL":typeof e=="number"||typeof e=="boolean"?String(e):typeof e=="object"?Cu(e):hi(e)}function hi(e){return`'${String(e).replace(/'/g,"''")}'`}var Et,wr=R(()=>{be();Et=class{constructor(t){this.db=t}async insert(t,n){pi(n,"documents.insert document"),await this.ensureCollection(t);let r=await this.db.query(`INSERT INTO ${an(t)} DOCUMENT VALUES (${Au(n)}) RETURNING *`),s=r.rows?.[0];if(!s||s.rid==null)throw new b("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 b("NOT_FOUND",`document ${String(n)} was not found`);return r.entity}async list(t,n={}){let r=Bu(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 ${an(t)}${i} ORDER BY ${s} LIMIT ${r}`)).rows??[]}}async patch(t,n,r){pi(r,"documents.patch patch");let s=Object.entries(r);if(s.length===0)throw new b("INVALID_ARGUMENT","documents.patch patch must be a non-empty object");for(let[c]of s)if(c.includes("/"))throw new b("INVALID_ARGUMENT","documents.patch currently accepts top-level document fields");let i=s.map(([c,u])=>`${gi(c)} = ${Lu(u)}`).join(", "),a=(await this.db.query(`UPDATE ${an(t)} SET ${i} WHERE rid = $1 RETURNING *`,n)).rows?.[0];if(!a)throw new b("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 ${an(t)}`)}catch(n){if(!String(n?.message??"").includes("already exists"))throw n}}}});function Mu(e,t){if(t.secretRef){let{collection:n,key:r}=t.secretRef;return`SECRET_REF(vault, ${_e(n)}.${_e(r)})`}return Uu(e)}function ju(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 _e(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 Uu(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):yi(e)}function yi(e){return`'${String(e).replace(/'/g,"''")}'`}var kt,br=R(()=>{kt=class{constructor(t,n="red.config"){this.client=t,this.collection=n}put(t,n,r={}){ju(r,"config");let s=r.collection??this.collection,i=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(yi).join(", ")}]`:"";return this.client.call("query",{sql:`PUT CONFIG ${_e(s)} ${_e(t)} = ${Mu(n,r)}${i}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`GET CONFIG ${_e(r)} ${_e(t)}`})}resolve(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`RESOLVE CONFIG ${_e(r)} ${_e(t)}`})}}});function Fu(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 tt(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 Gu(e){return typeof e=="number"||typeof e=="boolean"?String(e):e==null?"NULL":Array.isArray(e)||typeof e=="object"?JSON.stringify(e):wi(e)}function wi(e){return`'${String(e).replace(/'/g,"''")}'`}var xt,_r=R(()=>{xt=class{constructor(t,n="red.vault"){this.client=t,this.collection=n}put(t,n,r={}){Fu(r,"vault");let s=r.collection??this.collection,i=Array.isArray(r.tags)&&r.tags.length>0?` TAGS [${r.tags.map(wi).join(", ")}]`:"";return this.client.call("query",{sql:`VAULT PUT ${tt(s)}.${tt(t)} = ${Gu(n)}${i}`})}get(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`VAULT GET ${tt(r)}.${tt(t)}`})}unseal(t,n={}){let r=n.collection??this.collection;return this.client.call("query",{sql:`UNSEAL VAULT ${tt(r)}.${tt(t)}`})}}});async function _i(e){return((await e.query("SHOW COLLECTIONS")).rows??[]).map(qu)}async function Ri(e,t){return((await e.query(`SHOW COLLECTIONS WHERE name = ${Hu(t)}`)).rows??[]).some(r=>r.name===String(t))}function qu(e){return{...e,name:String(e.name),model:String(e.model),capabilities:Array.isArray(e.capabilities)?e.capabilities:[]}}function bi(e){return String(e).split(".").map(Ju).join(".")}function Ju(e){let t=String(e);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw new b("INVALID_IDENTIFIER",`invalid SQL identifier "${t}"`);return t}function Hu(e){return`'${String(e).replace(/'/g,"''")}'`}var Tt,Rr=R(()=>{be();Tt=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 b("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(bi).join(", "),n=this.whereClauses.length>0?` WHERE ${this.whereClauses.map(o=>`(${o})`).join(" AND ")}`:"",r=`SELECT ${t} FROM ${bi(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 ln(e,t={}){let n=cr(e);if(tl(n),n.kind==="embedded"){let r=el(n,t.auth);if(r.token||r.username)throw new b("AUTH_NOT_APPLICABLE","auth is only meaningful for remote connections; embedded modes inherit caller privileges.");let s=Zu(n),i=t.binary??li(),o=await oi(i,s),a=new on(o);return await a.call("version",{}),new Er(a,{transport:"embedded"})}}function Ei(e){return Ku(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:Yu(e)}:typeof e=="number"&&!Number.isFinite(e)?Number.isNaN(e)?{$float:"NaN"}:{$float:e>0?"Infinity":"-Infinity"}:typeof e=="string"&&Xu(e)?{$uuid:e}:e}function Ku(e){if(e!=null&&!(typeof e=="boolean"||typeof e=="number"||typeof e=="string")){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new b("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 b("UNSUPPORTED_PARAM","array query parameters must contain only numbers")}if(!(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype))throw new b("UNSUPPORTED_PARAM",`cannot encode query parameter of type ${typeof e}`)}}}function zu(e){return e.length===0?null:e.length===1&&Array.isArray(e[0])?e[0].map(Ei):e.map(Ei)}function Yu(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 Qu(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 Xu(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}function cn(e){if(Array.isArray(e))return e.map(cn);if(e&&typeof e=="object"){if(Object.keys(e).length===1){if(typeof e.$bytes=="string")return Qu(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]=cn(s);return n}return e}function Zu(e){return e.path?["rpc","--stdio","--path",e.path]:["rpc","--stdio"]}function el(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 tl(e){if(e.kind!=="embedded")throw new b("EMBEDDED_ONLY",Wu)}function kr(){return new b(Si,`${Si}: nested transactions are not supported on one connection`)}function xi(e,t){if(e&&typeof e=="object")try{e.rollbackError=t}catch{}}function nl(e,t){if(!e||typeof e!="object"||e.rid==null&&e.id==null)throw new b("ENGINE_TOO_OLD",`${t}() requires RedDB engine >= ${ki} with insert id support`);return e.rid==null&&(e.rid=e.id),e.id==null&&(e.id=e.rid),e}function rl(e,t){if(!e||typeof e!="object"||!Array.isArray(e.rids)&&!Array.isArray(e.ids))throw new b("ENGINE_TOO_OLD",`bulkInsert() requires RedDB engine >= ${ki} 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 b("INVALID_RESPONSE",`bulkInsert() expected ${t} rids, got ${e.rids.length}`);return e}var Wu,Vu,ki,Si,un,Sr,Er,xr=R(()=>{ai();di();be();ur();lr();mr();yr();wr();br();_r();Rr();lr();mr();yr();wr();br();_r();Rr();ur();Wu="remote URIs are not supported in @reddb-io/sdk; install @reddb-io/client for grpc/http/red transports",Vu="1.0",ki="1.0.9",Si="NESTED_TX_NOT_SUPPORTED";un=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 kr()}},Sr=class{constructor(t){this.db=t,this.active=!1}async begin(){if(this.db.inTransaction)throw kr();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 b("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 b("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 b("INVALID_ARGUMENT","nested tx.run() is not supported; issue savepoints via tx.query() instead");await this.begin();try{let n=await t(new un(this.db));return await this.commit(),n}catch(n){if(this.active)try{await this.rollback()}catch(r){xi(n,r)}throw n}}},Er=class{constructor(t,n={}){this.client=t,this.transport=n.transport??null,this.helperSpecVersion=Vu,this.cache=new Rt(t,this.transport),this.queue=new St(t),this.queues=this.queue,this.documents=new Et(this);let r=new et(t);this.kv=Object.assign((s="kv_default")=>new et(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 kt(t,s),this.vault=(s="red.vault")=>new xt(t,s),this.inTransaction=!1}query(t,...n){if(typeof t!="string"||t.trim().length===0)return Promise.reject(new b("INVALID_ARGUMENT","query() requires a non-empty SQL string"));let r=zu(n);return r==null?this.client.call("query",{sql:t}).then(cn):this.client.call("query",{sql:t,params:r}).then(cn)}execute(t,...n){return this.query(t,...n)}async insert(t,n){let r=await this.client.call("insert",{collection:t,payload:n});return nl(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 rl(r,n.length)}tx(){return new Sr(this)}async transaction(t){if(this.inTransaction)throw kr();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 un(this));return await this.query("COMMIT"),r}catch(r){if(n)try{await this.query("ROLLBACK")}catch(s){xi(r,s)}throw r}finally{this.inTransaction=!1}}exists(t){return Ri(this,t)}list(){return _i(this)}from(t){return new Tt(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 S(e,t){return new dn(e,t)}var dn,vt=R(()=>{dn=class extends Error{constructor(t,n){super(t===0?n:`line ${t}: ${n}`),this.name="ToonError",this.line=t,this.reason=n}}});function Tr(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 X(e){return S(e,"invalid quoted string")}function Ce(e,t){if(e==="")return"";if(e.startsWith('"'))return Ti(e,t);if(e.includes('"'))throw X(t);return e==="true"?!0:e==="false"?!1:e==="null"?null:sl(e)?Number(e):e}function Pt(e,t){let n=e.trim();if(n.startsWith('"'))return[Ti(n,t),!0];if(n.includes('"')||/\s/.test(n))throw S(t,"expected non-empty field name");return[n,!1]}function Ti(e,t){if(e[0]!=='"')throw X(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 X(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 X(t);let a=Number.parseInt(o,16);if(a>=55296&&a<=57343)throw X(t);n+=String.fromCharCode(a),r+=4;break}default:throw X(t)}continue}if(s<" "&&s!==" ")throw X(t);n+=s}throw X(t)}function Ot(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 X(n);return r.push(e.slice(s).trim()),r}function z(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 X(n);return-1}function sl(e){return/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function il(e){return/^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(e)}function ol(e){if(Object.is(e,-0))return"0";if(!Number.isFinite(e))throw S(0,"number is not representable in TOON");return String(e)}function fn(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"}function Ae(e,t){if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return ol(e);if(typeof e=="string")return cl(e,t);throw S(0,"not a primitive")}function al(e){return/^[A-Za-z_][A-Za-z0-9_.]*$/.test(e)}function Le(e){return al(e)?e:vi(e)}function cl(e,t){return ul(e,t)?vi(e):e}function ul(e,t){return e===""||e.trim()!==e||e==="true"||e==="false"||e==="null"||il(e)||/[:"\\[\]{}]/.test(e)||/[\u0000-\u001f]/.test(e)||e.includes(t)||e.startsWith("-")}function vi(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 nt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}var Z,vr=R(()=>{vt();Z=","});function ll(e={}){return{indent:Math.max(1,e.indent??$r),strict:e.strict??!0,expandPaths:e.expandPaths==="safe"||e.expandPaths===!0}}function dl(e,t){let n=[],r=!1;return Tr(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 S(o,"invalid indentation");if(t.strict&&a%t.indent!==0)throw S(o,"invalid indentation");n.push({number:o,depth:Math.floor(a/t.indent),content:s.slice(a),blankBefore:r}),r=!1}),n}function Dt(e,t){let n=ll(t),r=dl(e,n),s=r[0];if(s===void 0)return{};if(s.depth!==0)throw S(s.number,"invalid indentation");let i=r.length===1;if(i&&s.content.trim()==="[]")return[];if(s.content.startsWith("[")){let u;try{u=Cr(s.content,z(s.content,":",s.number))}catch(l){if(n.strict)throw Di(l,s.number);u=void 0}if(u!==void 0)return ml(u,r,n)}if(i&&z(s.content,":",s.number)===-1)return Ce(s.content.trim(),s.number);let o={index:0},a=Nr(r,o,0,n),c=r[o.index];if(c!==void 0)throw S(c.number,"expected end of document");return a}function Nr(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 S(i.number,"invalid indentation");let{key:o,quoted:a,value:c}=fl(e,t,n,r);yl(s,o,a,c,r,i.number)}return s}function fl(e,t,n,r){let s=e[t.index],i=s.content,o=z(i,":",s.number);if(o===-1)throw S(s.number,"expected `key: value`");let a=i.slice(0,o),c=i.slice(o+1);if(z(a,"[",s.number)!==-1){let f;try{f=Cr(a,o)}catch(g){if(r.strict)throw Di(g,s.number);t.index+=1;let m=Pi(e,t,n,c,s.number,r);return{key:a.trim(),quoted:!1,value:m}}if(f.key===""&&!f.keyQuoted)throw S(s.number,"expected non-empty field name");let y=Br(f,c,e,t,n,r);return{key:f.key,quoted:f.keyQuoted,value:y}}let[u,l]=Pt(a,s.number);if(u===""&&!l)throw S(s.number,"expected non-empty field name");t.index+=1;let d=Pi(e,t,n,c,s.number,r);return{key:u,quoted:l,value:d}}function Pi(e,t,n,r,s,i){let o=r.trim();if(o==="[]")return[];if(o!=="")return Ce(o,s);let a=e[t.index];return a!==void 0&&a.depth>n?Nr(e,t,n+1,i):{}}function ml(e,t,n){let r=t[0],s=z(r.content,":",r.number);if(s===-1)throw S(r.number,"expected `key: value`");let i=r.content.slice(s+1),o={index:0},a=Br(e,i,t,o,0,n),c=t[o.index];if(c!==void 0)throw S(c.number,"expected end of document");return a}function Br(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 S(o,"expected tabular rows");return pl(e,e.fields,n,r,s+1,i)}if(a!==""){let c=Ot(a,e.delimiter,o).map(u=>Ce(u,o));if(c.length!==e.len)throw S(o,"array length mismatch");return c}return gl(e,n,r,s+1,i)}function pl(e,t,n,r,s,i){let o=[];for(;o.length<e.len;){let c=n[r.index];if(c===void 0)throw Or(n,r.index);if(c.depth<s)break;if(c.depth>s)throw S(c.number,"invalid indentation");if(c.blankBefore&&i.strict)throw S(c.number,"blank line inside array");if(!Oi(c.content,e.delimiter,c.number))break;let u=Ot(c.content,e.delimiter,c.number);if(u.length!==t.length)throw S(c.number,"array row length mismatch");let l={};t.forEach((d,f)=>{nt(l,d,Ce(u[f],c.number))}),o.push(l),r.index+=1}if(o.length!==e.len)throw Or(n,r.index);let a=n[r.index];if(a!==void 0&&a.depth>=s&&Oi(a.content,e.delimiter,a.number))throw S(a.number,"array length mismatch");return o}function Oi(e,t,n){let r=z(e,":",n);if(r===-1)return!0;let s=z(e,t,n);return s===-1?!1:s<r}function gl(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 Or(t,n.index);if(a.depth>r)throw S(a.number,"invalid indentation");if(a.blankBefore&&s.strict)throw S(a.number,"blank line inside array");i.push(hl(t,n,r,s))}let o=t[n.index];if(o!==void 0&&o.depth>=r)throw S(o.number,"array length mismatch");return i}function hl(e,t,n,r){let s=e[t.index];if(!s.content.startsWith("-"))throw S(s.number,"expected array item");let i=s.content.slice(1).replace(/^\s+/,"");if(i==="")return t.index+=1,{};if(i.startsWith("[")){let o=z(i,":",s.number),a;try{a=Cr(i,o)}catch{a=void 0}if(a!==void 0){let c=i.slice(o+1);return Br(a,c,e,t,n,r)}}if(z(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 Nr(o,{index:0},n+1,r)}return t.index+=1,Ce(i,s.number)}function Or(e,t){let n=e[t]??e[e.length-1];return S(n===void 0?1:n.number,"array length mismatch")}function Cr(e,t){if(t===-1)throw S(0,"array header missing colon");let n=e.slice(0,t),r=z(n,"[",0);if(r===-1)throw S(0,"invalid array header");let s,i;try{[s,i]=Pt(n.slice(0,r),0)}catch{throw S(0,"invalid array header")}let o=n.slice(r+1),a=o.indexOf("]");if(a===-1)throw S(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 S(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 S(0,"invalid array header")}let f=o.slice(a+1),y;if(f==="")y=void 0;else if(f.startsWith("{")&&f.endsWith("}")&&f.length>=2){let g;try{g=Ot(f.slice(1,-1),d,0),y=g.map(m=>Pt(m,0)[0])}catch{throw S(0,"invalid array header")}}else throw S(0,"invalid array header");return{key:s,keyQuoted:i,len:l,delimiter:d,fields:y}}function Di(e,t){return S(t,e.reason??String(e.message))}function yl(e,t,n,r,s,i){if(s.expandPaths&&!n&&t.includes(".")){let o=t.split(".");if(o.every(wl)){Dr(e,o,r,s,i);return}}Dr(e,[t],r,s,i)}function Dr(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(s,"duplicate key");nt(e,i,n);return}if(o&&!rt(e[i])){if(r.strict)throw S(s,"path expansion conflict");nt(e,i,{})}else o||nt(e,i,{});Dr(e[i],t.slice(1),n,r,s)}function wl(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)}function rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function v(e){let t=[];return Array.isArray(e)?Ar(t,void 0,e,0,!1):rt(e)?Ii(t,e,0):t.push(Ae(e,Z)),t.join("")}function mn(e,t){e.push(" ".repeat(t*$r))}function Ii(e,t,n){for(let[r,s]of Object.entries(t))mn(e,n),Ir(e,r,s,n)}function Ir(e,t,n,r){if(Array.isArray(n)){Ar(e,t,n,r,!1);return}if(rt(n)){e.push(Le(t),`:
|
|
15
|
+
`),Ii(e,n,r+1);return}e.push(Le(t),": ",Ae(n,Z),`
|
|
16
|
+
`)}function Ar(e,t,n,r,s){if(n.length===0){t!==void 0?e.push(Le(t),`: []
|
|
17
|
+
`):s?e.push(`[0]:
|
|
18
|
+
`):e.push(`[]
|
|
19
|
+
`);return}if(n.every(fn)){Pr(e,t,n.length,void 0),e.push(" "),e.push(n.map(o=>Ae(o,Z)).join(Z)),e.push(`
|
|
20
|
+
`);return}let i=s?void 0:_l(n);if(i!==void 0){Pr(e,t,n.length,i),e.push(`
|
|
21
|
+
`);for(let o of n)mn(e,r+1),e.push(i.map(a=>Ae(o[a],Z)).join(Z)),e.push(`
|
|
22
|
+
`);return}Pr(e,t,n.length,void 0),e.push(`
|
|
23
|
+
`);for(let o of n)mn(e,r+1),bl(e,o,r+1)}function bl(e,t,n){if(Array.isArray(t)){e.push("- "),Ar(e,void 0,t,n,!0);return}if(rt(t)){let r=Object.entries(t);if(r.length===0){e.push(`-
|
|
24
|
+
`);return}e.push("- "),Ir(e,r[0][0],r[0][1],n+1);for(let[s,i]of r.slice(1))mn(e,n+1),Ir(e,s,i,n+1);return}e.push("- ",Ae(t,Z),`
|
|
25
|
+
`)}function Pr(e,t,n,r){t!==void 0&&e.push(Le(t)),e.push("[",String(n),"]"),r!==void 0&&e.push("{",r.map(Le).join(Z),"}"),e.push(":")}function _l(e){let t=e[0];if(!rt(t))return;let n=Object.keys(t);if(n.length!==0){for(let r of e){if(!rt(r))return;let s=Object.keys(r);if(s.length!==n.length||s.some(i=>!fn(r[i]))||n.some(i=>!Object.prototype.hasOwnProperty.call(r,i)))return}return n}}var $r,It=R(()=>{vt();vr();$r=2});var $i=R(()=>{It()});var Ni=R(()=>{vt();It();vr()});var Re=R(()=>{vt();It();It();$i();Ni()});function Mr(e,t,n=Ci){let r=Math.max(0,Math.floor(e)),s=n in Ai?n:Ci,i=Ai[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:Lr(r,i),dollars_saved_low_usd:o==null?null:Lr(o,i),dollars_saved_high_usd:a==null?null:Lr(a,i),pricing_model_family:s,pricing_input_usd_per_million_tokens:i,pricing_note:Sl}}function Lr(e,t){return El(Math.max(0,e)/1e6*t)}function $t(e){return`$${e.toFixed(6)}`}function El(e){return Math.round(e*1e6)/1e6}var Ci,Ai,Sl,jr=R(()=>{"use strict";Ci="gpt-5",Ai={"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},Sl="estimate derived from byte-based token estimate when token counts are estimated"});import{existsSync as kl,readFileSync as Sw}from"node:fs";import{dirname as xl,join as Tl}from"node:path";function Li(e,t){let n=e;for(let r=0;r<16;r++){let s=Tl(n,t);if(kl(s))return s;let i=xl(n);if(i===n)break;n=i}return null}function vl(e){let t=e.indexOf(" #");return(t>=0?e.slice(0,t):e).trim()}function pn(e,t){let n=[];for(let r of e.split(`
|
|
26
|
+
`)){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 vl(u)}}var Mi=R(()=>{});import{createConnection as Pl}from"node:net";async function it(e,t){let n=e.timeoutMs??1e3;return await new Promise((r,s)=>{let i=Pl(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)}
|
|
27
|
+
`)}),i.on("data",l=>{a+=l.toString("utf8");let d=a.indexOf(`
|
|
28
|
+
`);if(d<0)return;let f=a.slice(0,d);u(()=>{try{r(JSON.parse(f))}catch(y){s(y)}}),i.end()}),i.on("error",l=>u(()=>s(l))),i.on("close",()=>{o||u(()=>s(new Error("resident rsp server closed without response")))})})}var Ur=R(()=>{});import{createHash as Ol,randomUUID as qi}from"node:crypto";import{spawn as Ji}from"node:child_process";import{constants as Fr}from"node:fs";import{readFileSync as Dl}from"node:fs";import{mkdir as gn,open as Il,readFile as Hi,rename as $l,rm as ee,stat as Nl,writeFile as Bl}from"node:fs/promises";import{tmpdir as Cl}from"node:os";import{dirname as Se,join as q,resolve as hn}from"node:path";import{fileURLToPath as Wi}from"node:url";function Ee(e){let t=Wl(e)??hn(e),n=Hl(t);return{rootDir:t,socketPath:q(n,"rsp.sock"),pidPath:q(n,"rsp.pid"),lockPath:q(n,"rsp.lock"),wakeLockPath:q(t,".red","tmp","rsp.wake.lock"),summaryPath:q(t,".red","tmp","rsp-status-summary.json"),registryPath:q(t,".red","tmp","rsp-resident.pid.json")}}async function yn(e,t){if(await gn(Se(e.socketPath),{recursive:!0,mode:448}),await Fi(e.socketPath,t))return;await Ui(e,t);let n=await Qi(e.lockPath);if(n)try{if(await Fi(e.socketPath,t))return;await Ui(e,t),await jl(e.socketPath);let r=Ul(e,t);await ji(e.socketPath,r);return}finally{await n.close(),await ee(e.lockPath,{force:!0})}await ji(e.socketPath)}async function Me(e,t=200){try{return await Ki(e,t)!=null}catch{return!1}}async function Ki(e,t=200){let n=await it({socketPath:e,timeoutMs:t},{id:qi(),op:"ping"});return n.ok?to(n.value)?{version:Yl(n.value.version)}:{}:null}async function wn(e,t){if(await gn(Se(e.socketPath),{recursive:!0,mode:448}),await Me(e.socketPath,50))return!1;let n=await Qi(e.wakeLockPath);if(!n)return!1;await n.close();let[r,s]=Zi(t);return Ji(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 zi(e,t){try{await yn(e,t)}finally{await ee(e.wakeLockPath,{force:!0})}}async function Bt(e){try{let t=JSON.parse(await Hi(e,"utf8"));return Ql(t)?t:null}catch{return null}}async function bn(e,t){let n={version:Vi,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 gn(Se(e),{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;await Bl(r,`${JSON.stringify(n)}
|
|
29
|
+
`,{encoding:"utf8",mode:384}),await $l(r,e)}async function _n(e,t=process.pid){try{let n=await Bt(e);if(n&&n.pid!==t)return;await ee(e,{force:!0})}catch{}}async function Nt(e){let t=await Bt(e.registryPath);if(!t)try{return await Hi(e.registryPath,"utf8"),{registry_path:e.registryPath,state:"invalid"}}catch{return{registry_path:e.registryPath,state:"missing"}}if(!ot(t.pid))return{registry_path:e.registryPath,state:"registered-dead",entry:t};let n=await Me(t.socket_path,100);return n&&await Jl(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 Yi(e){let t=await Nt(e);return t.state==="registered-dead"||t.state==="invalid"?(await ee(e.registryPath,{force:!0}),await Nt(e)):(t.state==="registered-alive-socket-dead"||t.state==="registered-alive-store-missing")&&t.entry?(await Xi(t.entry.pid),await ee(e.registryPath,{force:!0}),await ee(t.entry.socket_path,{force:!0}),await Nt(e)):t}async function ji(e,t){let n=Date.now()+Ml(),r;for(;Date.now()<n;){if(await Me(e))return;if(t){let s=t.spawnError();if(s)throw new Error(Gr("resident rsp server spawn failed",t,s));if(t.child.exitCode!=null||t.child.signalCode!=null)throw new Error(Gr("resident rsp server exited before ready",t))}await new Promise(s=>setTimeout(s,50))}throw r instanceof Error?r:new Error(t?Gr("resident rsp server did not start",t):"resident rsp server did not start")}function Ml(){let e=Number(process.env.RSP_RESIDENT_READY_TIMEOUT_MS??"");return Number.isFinite(e)&&e>0?e:Ll}async function jl(e){await ee(e,{force:!0})}async function Qi(e){await gn(Se(e),{recursive:!0,mode:448});try{return await Il(e,Fr.O_CREAT|Fr.O_EXCL|Fr.O_RDWR)}catch(t){if(t.code!=="EEXIST")throw t;return null}}function Ul(e,t){let[n,r]=Zi(t),s=process.env.RSP_DEBUG==="1",i,o="",a=Ji(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=Gl(`${o}${c}`,Fl)})),a.unref(),{child:a,stderrTail:()=>o,spawnError:()=>i}}function Gr(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:
|
|
30
|
+
${s}`),r.join(`
|
|
31
|
+
`)}function Gl(e,t){let n=Buffer.byteLength(e,"utf8");return n<=t?e:Buffer.from(e,"utf8").subarray(n-t).toString("utf8").replace(/^\uFFFD+/,"")}async function Ui(e,t){try{let n=await Bt(e.registryPath);if(!n||n.socket_path!==e.socketPath||n.store_uri!==t.storeUri)return;if(!ot(n.pid)){await ee(e.registryPath,{force:!0});return}if(await Me(n.socket_path,100))return;if(eo(t.clientVersion,n.resident_version)&&(await ql(n.pid,1500),!ot(n.pid))){await ee(e.registryPath,{force:!0});return}await Xi(n.pid),await ee(e.registryPath,{force:!0})}catch{}}function ot(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}async function Xi(e){if(!ot(e))return;try{process.kill(e,"SIGTERM")}catch{return}let t=Date.now()+1e3;for(;Date.now()<t;){if(!ot(e))return;await new Promise(n=>setTimeout(n,50))}try{process.kill(e,"SIGKILL")}catch{}}async function ql(e,t){let n=Date.now()+t;for(;Date.now()<n;){if(!ot(e))return;await new Promise(r=>setTimeout(r,50))}}async function Jl(e){if(!e.startsWith("file://"))return!1;try{return await Nl(Wi(e)),!1}catch(t){return t.code==="ENOENT"}}function Zi(e){if(e.serverCommand)return[e.serverCommand,e.serverArgs??[]];let t=process.argv[1]?hn(process.argv[1]):Wi(import.meta.url);return[process.execPath,[...process.execArgv,t]]}function Hl(e){let t=Ol("sha256").update(e).digest("hex").slice(0,20),n=process.env.XDG_RUNTIME_DIR;if(n){let s=q(n,"red-skills",t);if(q(s,"rsp.sock").length<Al)return s}let r=typeof process.getuid=="function"?process.getuid():"nouid";return q(Cl(),`red-skills-${r}`,t)}function Wl(e){let t=hn(e);for(let n=0;n<32;n++){try{let s=qr(q(t,".git"));if(s!=null)return Vl(t,s)??t;if(qr(q(t,".git","HEAD"))!=null||qr(q(t,".red","config.yaml"))!=null)return t}catch{}let r=Se(t);if(r===t)return null;t=r}return null}function Vl(e,t){let n=/^gitdir:\s*(.+?)\s*$/m.exec(t);if(!n)return null;let r=hn(e,n[1]);return/[/\\]worktrees[/\\][^/\\]+$/.test(r)?Se(Se(Se(r))):null}function qr(e){try{return Dl(e,"utf8")}catch{return null}}async function Fi(e,t){let n=await Ki(e).catch(()=>null);return n?eo(t.clientVersion,n.version)?(await Kl(e,t.clientVersion),await Xl(e),!1):!0:!1}async function Kl(e,t){try{await it({socketPath:e,timeoutMs:200},{id:qi(),op:"handover",clientVersion:t})}catch{}}function eo(e,t){return!e||!t?!1:zl(e,t)>0}function zl(e,t){let n=Gi(e),r=Gi(t);return!n||!r?0:n.major-r.major||n.minor-r.minor||n.patch-r.patch}function Gi(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 to(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yl(e){return typeof e=="string"&&e.length>0?e:void 0}function Ql(e){return to(e)&&e.version===Vi&&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 Xl(e){let t=Date.now()+1e3;for(;Date.now()<t;){if(!await Me(e,50))return;await new Promise(n=>setTimeout(n,50))}}var Al,Vi,Ll,Fl,Rn=R(()=>{Ur();Al=108,Vi=1,Ll=5e3;Fl=8*1024});var ao={};N(ao,{DEFAULT_RSP_BYTE_BUDGET:()=>pe,DEFAULT_RSP_EPHEMERAL_TTL_HOURS:()=>me,DEFAULT_RSP_HEAVY_GIT_BYTE_THRESHOLD:()=>de,DEFAULT_RSP_IDLE_MS:()=>xn,DEFAULT_RSP_STORE_PATH:()=>Sn,DEFAULT_RSP_TELEMETRY_BYTE_BUDGET:()=>kn,DEFAULT_RSP_TELEMETRY_DRAIN_INTERVAL_MS:()=>so,DEFAULT_RSP_TELEMETRY_DRAIN_TIMEOUT_MS:()=>io,DEFAULT_RSP_TELEMETRY_TTL_DAYS:()=>En,DEFAULT_RSP_TTL_DAYS:()=>fe,MIN_RSP_IDLE_MS:()=>oo,resolveRspConfig:()=>ge});import{readFileSync as Zl}from"node:fs";import{join as no,resolve as ro}from"node:path";function ge(e,t,n){let r=Li(ro(e),no(".red","config.yaml")),s=r?Zl(r,"utf8"):"",i=pn(s,"rsp.enabled")==="true",o=pn(s,"rsp.proxy.enabled")==="true",a=le(te(s,"rsp.ttlDays"),fe),c=le(Ct(t.RSP_EPHEMERAL_TTL_HOURS)??te(s,"rsp.ephemeralTtlHours"),me),u=le(te(s,"rsp.byteBudget"),pe),l=le(te(s,"rsp.telemetryTtlDays"),En),d=le(te(s,"rsp.telemetryByteBudget")??te(s,"rsp.byteBudget"),kn),f=le(Ct(t.RSP_TELEMETRY_DRAIN_INTERVAL_MS)??te(s,"rsp.telemetryDrainIntervalMs"),so),y=le(Ct(t.RSP_TELEMETRY_DRAIN_TIMEOUT_MS)??te(s,"rsp.telemetryDrainTimeoutMs"),io),g=ed(Ct(t.RSP_IDLE_MS)??te(s,"rsp.idleMs"),xn,oo),m=le(Ct(t.RSP_HEAVY_GIT_BYTE_THRESHOLD)??te(s,"rsp.heavyGitByteThreshold"),de),p=Ee(e).rootDir,k=n??t.RSP_STORE_URI??`file://${no(ro(p),Sn)}`;return{enabled:i,proxyEnabled:o,storeUri:k,ttlDays:a,ephemeralTtlHours:c,byteBudget:u,telemetryTtlDays:l,telemetryByteBudget:d,telemetryDrainIntervalMs:f,telemetryDrainTimeoutMs:y,idleMs:g,heavyGitByteThreshold:m}}function te(e,t){let n=pn(e,t);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function le(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function ed(e,t,n){let r=le(e,t);return Math.max(r,n)}function Ct(e){if(e==null||e.trim()==="")return;let t=Number(e);return Number.isFinite(t)?t:void 0}var de,Sn,fe,me,pe,En,kn,so,io,xn,oo,ne=R(()=>{"use strict";Mi();Rn();de=8*1024,Sn=".red/tmp/red-skills.rdb",fe=7,me=6,pe=64*1024*1024,En=90,kn=4*1024*1024,so=3e4,io=2e3,xn=5*6e4,oo=5e3});var co=R(()=>{"use strict";Ur()});var Lt={};N(Lt,{ResidentRspElisionStore:()=>At,ensureResidentServer:()=>yn,kickResidentServer:()=>wn,pingResident:()=>Me,readResidentRegistry:()=>Bt,removeResidentRegistry:()=>_n,residentRegistryStatus:()=>Nt,resolveResidentPaths:()=>Ee,sweepResidentRegistry:()=>Yi,warmResidentServer:()=>zi,writeResidentRegistry:()=>bn});import{randomUUID as td}from"node:crypto";function uo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var At,je=R(()=>{"use strict";co();Rn();At=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?uo(n)&&n.status==="expired"?n:!uo(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 yn(this.paths,this.config);let n=await it(this.paths,{...t,id:td()});if(!n.ok)throw new Error(n.error);return this.metrics={storeOpenCount:n.storeOpenCount,storeElapsedMs:n.storeElapsedMs},n.value}}});var Gt={};N(Gt,{DEFAULT_RSP_BYTE_BUDGET:()=>pe,DEFAULT_RSP_EPHEMERAL_TTL_HOURS:()=>me,DEFAULT_RSP_TTL_DAYS:()=>fe,RSP_ELISION_COLLECTION:()=>U,RspElisionStore:()=>Ut,ensureReddbBinaryFromWarmCache:()=>Eo,storageClassForCommand:()=>Fe});import{createHash as On}from"node:crypto";import{spawnSync as jt}from"node:child_process";import{existsSync as nd}from"node:fs";import{mkdir as rd,readFile as Yr,readdir as bo,rename as sd,writeFile as id}from"node:fs/promises";import{homedir as od}from"node:os";import{basename as Qr,dirname as _o,join as ct}from"node:path";import{fileURLToPath as ad}from"node:url";import{gunzipSync as cd,gzipSync as ud}from"node:zlib";function lo(e,t){return`el:${On("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 he(e){return`record:${e.slice(3)}`}function Ue(e){return`expired:${e.slice(3)}`}function Jr(){return"index:v1"}function ld(e){return`blob:${e}`}function Fe(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":Dn(t)?"re-executable":"ephemeral"}return"ephemeral"}function Mt(e){return In(e.storage_class)?e.storage_class:Fe(e.command)}function dd(e){return In(e.storage_class)?e.storage_class:Fe(e.command)}function fo(e){let t=hd(),n={derivable:new Set,"re-executable":new Set,ephemeral:new Set};for(let r of e){let s=dd(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 mo(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 at(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 po(e,t){let n=process.cwd(),r=jt("git",["rev-parse","--is-inside-work-tree"],{cwd:n,encoding:"utf8"});if(r.status!==0||r.stdout.trim()!=="true")return null;let s=jt("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:fd(n),original_bytes:e.length}:null}function fd(e){let t=Hr(e,["rev-parse","HEAD"])||"unborn",n=Hr(e,["write-tree"])||"no-index",r=Hr(e,["status","--porcelain=v1","-z"])||"";return On("sha256").update(t).update("\0").update(n).update("\0").update(r).digest("hex")}function Hr(e,t){let n=jt("git",t,{cwd:e,encoding:"utf8"});return n.status===0?n.stdout.trim():null}function go(e,t){let n=t.trim().split(/\s+/).filter(Boolean);if(!Dn(n))return null;let r=Ro(process.cwd(),n,e.length);return!r||lt(r)!==lt(e)?null:{kind:"command",command:t,cwd:process.cwd(),argv:n,original_bytes:e.length,content_hash:lt(e)}}function Dn(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 lt(e){return On("sha256").update("rsp-reexecutable-content-v1\0").update(e).digest("hex")}function ho(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 Wr(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 yo(e,t,n){let r=ud(e);return{key:ld(t),content_hash:t,encoding:"gzip+base64",bytes:r.toString("base64"),original_bytes:e.length,stored_bytes:r.length,created_at:n}}function md(e){try{let t=cd(Buffer.from(e.bytes,"base64"));return t.length===e.original_bytes?t:null}catch{return null}}function pd(e){let t=e.object_ids[0];if(!t)return null;let n=jt("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 gd(e){if(!Dn(e.argv))return null;let t=Ro(e.cwd,e.argv,e.original_bytes);return t?lt(t)===e.content_hash?t:Buffer.concat([Buffer.from(`reconstructed after state moved - current snapshot follows
|
|
32
|
+
`,"utf8"),t]):null}function Ro(e,t,n){let r=t[0];if(!r)return null;let s=jt(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 hd(){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 Ft(e){return/^el:[a-f0-9]{12}$/.test(e)}function Tn(e){return/^blob:[a-f0-9]{64}$/.test(e)}function yd(e){if(!dt(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:dt(e.scope)?e.scope:void 0,ranking:dt(e.ranking)?e.ranking:void 0}}}function wd(e){if(!dt(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 dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bd(e){return dt(e)?typeof e.key=="string"&&e.key.trim()!==""?{key:e.key,value:vn(e.value)}:typeof e.record_key=="string"&&e.record_key.trim()!==""?{key:e.record_key,value:vn(e.value)}:ut(e)?{key:he(e.handle),value:e}:Pn(e)&&typeof e.handle=="string"&&Ft(e.handle)?{key:Ue(e.handle),value:e}:null:null}function vn(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}async function _d(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 bo(o,{withFileTypes:!0}).catch(()=>[]);for(let c of a){if(r.length>=t)return;if(s.has(c.name))continue;let u=ct(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 Rd(e,t){let n=Number(e.red_entity_id??e.rid);if(!Number.isFinite(n))return null;let r=e.properties??e.PROPERTIES,s=dt(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 Vr(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function ut(e){if(!J(e))return!1;let t=typeof e.original=="string"&&e.original_encoding==="base64",n=Ed(e.derivation_recipe),r=kd(e.reexecution_recipe),s=e.blob_key,i=typeof s=="string"&&Tn(s);return e.collection===U&&typeof e.handle=="string"&&Ft(e.handle)&&(t||n||r||i)&&typeof e.original_bytes=="number"&&(e.content_hash===void 0||Xr(e.content_hash))&&(e.stored_bytes===void 0||typeof e.stored_bytes=="number")&&(s===void 0||typeof s=="string"&&Tn(s))&&typeof e.command=="string"&&typeof e.created_at=="string"&&typeof e.expires_at=="string"&&Sd(e.loss)&&(e.storage_class===void 0||In(e.storage_class))}function Kr(e){return!J(e)||e.version!==1||!Array.isArray(e.records)?!1:e.records.every(t=>{if(!J(t))return!1;let n=t.blob_key;return typeof t.handle=="string"&&Ft(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||In(t.storage_class))&&(n===void 0||typeof n=="string"&&Tn(n))})}function zr(e){return J(e)&&typeof e.key=="string"&&Tn(e.key)&&Xr(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 Pn(e){return J(e)&&e.status==="expired"&&typeof e.expired_at=="string"&&typeof e.command=="string"}function Sd(e){return J(e)&&typeof e.level=="string"&&typeof e.bytes_elided=="number"}function In(e){return e==="derivable"||e==="re-executable"||e==="ephemeral"}function Ed(e){return J(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 kd(e){return J(e)&&e.kind==="command"&&typeof e.command=="string"&&typeof e.cwd=="string"&&Array.isArray(e.argv)&&e.argv.every(t=>typeof t=="string")&&Dn(e.argv)&&typeof e.original_bytes=="number"&&Xr(e.content_hash)}function Xr(e){return typeof e=="string"&&/^[0-9a-f]{64}$/.test(e)}function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}async function xd(e){try{let t=await Yr(e,"utf8");if(t.trim()==="")return wo();let n=JSON.parse(t);if(Od(n))return{...n,blobs:n.blobs??{}}}catch(t){if(t.code==="ENOENT"){let n=wo();return await ko(e,n),n}throw t}throw new Error("rsp elision store is unreadable")}async function Td(e){try{let t=await Yr(e);return So(e)?e:vd(t)?Pd(e):e}catch(t){if(t.code==="ENOENT")return e;throw t}}function vd(e){return e.subarray(0,8).toString("ascii")==="RDBSBLK1"}function Pd(e){return Qr(e)==="red.rdb"?ct(_o(e),"tmp","rsp-elisions.json"):`${e}.json`}function So(e){return Qr(e)==="red-skills.rdb"}async function Eo(){if(process.env.REDDB_BIN)return;let e=process.env.RED_SKILLS_CACHE_DIR??(process.env.XDG_CACHE_HOME?ct(process.env.XDG_CACHE_HOME,"red-skills","bundles"):ct(od(),".cache","red-skills","bundles")),t=ct(e,"reddb"),n;try{n=await bo(t)}catch{return}n.sort().reverse();for(let r of n){let s=ct(t,r,process.platform==="win32"?"red.exe":"red");if(nd(s)){process.env.REDDB_BIN=s;return}}}async function ko(e,t){await rd(_o(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await id(n,`${JSON.stringify(t)}
|
|
33
|
+
`,"utf8"),await sd(n,e)}function wo(){return{version:1,records:{},blobs:{},tombstones:{},index:{version:1,records:[]}}}function Od(e){return J(e)&&e.version===1&&J(e.records)&&Object.values(e.records).every(ut)&&(e.blobs===void 0||J(e.blobs)&&Object.values(e.blobs).every(zr))&&J(e.tombstones)&&Object.values(e.tombstones).every(Pn)&&Kr(e.index)}function Dd(e){if(!e.startsWith("file://"))throw new Error("rsp elision store requires a file:// URI");return ad(e)}var U,Ut,Ge=R(()=>{"use strict";xr();ne();U="rsp_elisions_v1",Ut=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=Dd(t.uri),r=await Td(n),s=new e(r,{uri:t.uri,ttlDays:Vr(t.ttlDays,fe),ephemeralTtlHours:Vr(t.ephemeralTtlHours,me),byteBudget:Vr(t.byteBudget,pe),now:t.now??(()=>new Date)});return So(r)?(await Eo(),s.db=await ln(`file://${r}`),await s.ensureRedDbCollections(),await s.ensureRedDbStore()):s.document=await xd(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=lo(r,n),a=he(o),c=Fe(n.command),u=c==="derivable"?po(r,n.command):null,l=c==="re-executable"?go(r,n.command):null,d=c==="derivable"&&!u||c==="re-executable"&&!l?"ephemeral":c,f=mo(s,d,this.opts.ttlDays,this.opts.ephemeralTtlHours),y=lt(r),g=d==="ephemeral"?yo(r,y,i):null,m=ho(r,u,l,g);g&&!this.document.blobs[g.key]&&(this.document.blobs[g.key]=g,this.dirty=!0);let p={collection:U,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[Ue(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(!Ft(t))return null;let n=this.tombstone(t);if(n)return n;let r=this.document.records[he(t)];if(!ut(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:he(r.handle),bytes:Wr(r),raw_bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at,storage_class:Mt(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:U,handle:r.handle,original:s,command:r.command,created_at:r.created_at,loss:r.loss,storage_class:Mt(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:at(n),oldest:n.reduce((r,s)=>r==null||s.created_at<r?s.created_at:r,null),budget:this.opts.byteBudget,storage_classes:fo(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=at(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=at(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[Ue(t.handle)]={status:"expired",expired_at:n,command:t.command},this.dirty=!0}tombstone(t){let n=this.document.tombstones[Ue(t)];return Pn(n)?n:null}async readOriginal(t){if(t.original)return Buffer.from(t.original,"base64");if(t.derivation_recipe)return pd(t.derivation_recipe);if(t.reexecution_recipe)return gd(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)?md(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 ko(this.path,this.document),this.dirty=!1)}kv(){if(!this.db)throw new Error("rsp RedDB store is not open");return this.db.kv(U)}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===U);if(!t){await this.db.query(`CREATE KV IF NOT EXISTS ${U}`);return}if(t.model==="kv")return;if(t.model!=="table")throw new Error(`cannot self-heal elision collection ${U}: unsupported model ${t.model}`);let n=await this.readLegacyElisionTableRows();await this.db.query(`DROP TABLE ${U}`),await this.db.query(`CREATE KV IF NOT EXISTS ${U}`);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 ${U}`),n=[];for(let r of t.rows){let s=bd(r);s&&n.push(s)}return n}async ensureMigratedRedDbIndex(t){if(t.some(s=>s.key===Jr()&&Kr(vn(s.value))))return;let r=t.map(s=>{let i=vn(s.value);return ut(i)?{handle:i.handle,key:he(i.handle),bytes:Wr(i),raw_bytes:i.original_bytes,command:i.command,created_at:i.created_at,expires_at:i.expires_at,storage_class:Mt(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=lo(r,n),a=he(o),c=Fe(n.command),u=c==="derivable"?po(r,n.command):null,l=c==="re-executable"?go(r,n.command):null,d=c==="derivable"&&!u||c==="re-executable"&&!l?"ephemeral":c,f=mo(s,d,this.opts.ttlDays,this.opts.ephemeralTtlHours),y=lt(r),g=d==="ephemeral"?yo(r,y,i):null,m=ho(r,u,l,g);g&&!zr(await this.kvGet(g.key))&&await this.kv().put(g.key,g);let p={collection:U,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(Ue(o)),await this.kv().put(a,p);let w=(await this.readRedDbIndex()).records.filter(T=>T.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(!Ft(t))return null;let n=await this.kvGet(Ue(t));if(Pn(n))return n;let r=await this.kvGet(he(t));if(!ut(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:he(r.handle),bytes:Wr(r),raw_bytes:r.original_bytes,command:r.command,created_at:r.created_at,expires_at:r.expires_at,storage_class:Mt(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:U,handle:r.handle,original:s,command:r.command,created_at:r.created_at,loss:r.loss,storage_class:Mt(r)}:null}async statsRedDb(){let t=await this.pruneRedDb(await this.readRedDbIndex());return{records:t.records.length,bytes:at(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:fo(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=yd(n);return await this.memoryRecallRedDb(r.query,r.limit)}if(t==="ingest"){let r=wd(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 _d(t.cwd,t.maxFiles??200,t.ignore??[]),r=0;for(let s of n){let o=(await Yr(s,"utf8").catch(()=>"")).trim();if(!o)continue;let a=Qr(s),c=On("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=>Rd(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(`
|
|
34
|
+
`),diagnostics:{vector:{status:"unavailable",candidates:0,contributed:0,reason:"resident-basic-recall"}}}}async readRedDbIndex(){let t=await this.kvGet(Jr());return Kr(t)?t:{version:1,records:[]}}async writeRedDbIndex(t){await this.kv().put(Jr(),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=at(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=at(i)}let a={version:1,records:i};return(n||i.length<t.records.length)&&await this.writeRedDbIndex(a),await this.deleteUnreferencedRedDbBlobs(i),a}async expireRedDbEntry(t,n){await this.kv().delete(t.key),await this.kv().put(Ue(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(he(t));if(!ut(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 Wt={};N(Wt,{RSP_ACCOUNTING_EVENTS_COLLECTION:()=>H,RSP_DECISIONS_COLLECTION:()=>W,RSP_TELEMETRY_DEGRADATIONS_COLLECTION:()=>xe,RSP_TELEMETRY_INDEX_COLLECTION:()=>Ht,RSP_TELEMETRY_INVOCATIONS_COLLECTION:()=>re,RSP_TELEMETRY_SPOOL:()=>$o,appendTelemetryEvent:()=>Je,drainTelemetrySpool:()=>ts,parseTelemetryEvent:()=>ns,readAccountingLaneStats:()=>rs,readTelemetryGainsReport:()=>ss,readTelemetryStats:()=>Cn,takeTelemetrySpool:()=>jd,telemetrySpoolPath:()=>Bn});import{appendFileSync as Id,mkdirSync as $d,readFileSync as Nd}from"node:fs";import{mkdir as Oo,readdir as Bd,readFile as Cd,rename as Do,rm as Io,writeFile as Zr}from"node:fs/promises";import{basename as Ad,dirname as Nn,join as es}from"node:path";function Bn(e){return es(e,$o)}async function Je(e,t){try{let n=Bn(e);$d(Nn(n),{recursive:!0}),Id(n,`${JSON.stringify(Md(t))}
|
|
35
|
+
`,{encoding:"utf8",mode:384})}catch{}}function Md(e){return xo(xo(e,"raw_text","raw_bytes"),"emitted_text","emitted_bytes")}function xo(e,t,n){let r=e[t];if(typeof r!="string")return e;let s=Buffer.byteLength(r,"utf8");if(s<=Ld)return e;let i={...e};return delete i[t],ye(i[n])===0&&(i[n]=s),i.estimated=!0,i}async function jd(e){let t=Bn(e),n=`${t}.${process.pid}.${Date.now()}.drain`;try{await Oo(Nn(t),{recursive:!0}),await Do(t,n)}catch(r){return r.code==="ENOENT"?[]:[]}try{return await Zr(t,"",{flag:"wx"}).catch(()=>{}),(await No(n)).split(/\r?\n/).filter(s=>s.trim()!=="")}finally{await Io(n,{force:!0})}}async function ts(e,t){let n=Bn(e);await Oo(Nn(n),{recursive:!0}).catch(()=>{});for(let s of await Ud(n))await To(n,s,t);let r=`${n}.${process.pid}.${Date.now()}.drain`;try{await Do(n,r)}catch{return}await Zr(n,"",{flag:"wx"}).catch(()=>{}),await To(n,r,t)}async function Ud(e){let t=Nn(e),n=`${Ad(e)}.`;return(await Bd(t).catch(()=>[])).filter(s=>s.startsWith(n)&&s.endsWith(".drain")).filter(s=>{let i=Number(s.slice(n.length).split(".")[0]);return!(Number.isInteger(i)&&i!==process.pid&&Fd(i))}).sort().map(s=>es(t,s))}function Fd(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function To(e,t,n){let r=[];try{let i=(await No(t)).split(/\r?\n/).filter(o=>o.trim()!=="");for(let o of i){try{if(await n(o))continue}catch{}r.push(o)}}finally{if(r.length>0){let s=Gd(e);await Zr(e,`${r.join(`
|
|
25
36
|
`)}
|
|
26
|
-
${i}`,"utf8")}await Ko(t,{force:!0})}}function Uf(e){try{return If(e,"utf8")}catch{return""}}async function Yo(e){let t="";for(let n=0;n<5;n++){let r=await Af(e,"utf8").catch(()=>"");if(r===t)return r;t=r,await new Promise(i=>setTimeout(i,2))}return t}function ai(e){try{let t=JSON.parse(e);return!Xo(t)||t.collection!==K&&t.collection!==z&&t.collection!==se&&t.collection!==Pe?null:t}catch{return null}}async function qn(e,t,n=new Date){let r=Number.isFinite(t)&&t>0?t:30,i=n.getTime()-r*24*60*60*1e3,s=await Qo(e,i),o=(await Vt(e,z)).filter(_=>wt(_)>=i),a=s.filter(_=>D(_.event_type)!=="show"&&D(_.degradation_reason)===""),c=s.filter(_=>D(_.event_type)==="show"),u=s.filter(_=>D(_.degradation_reason)!==""),l=0,d=0,f=0,w=0,y=!1,m=new Map,g=new Map,S=[],p=0,k=0,R=0;for(let _ of a){_.elided===!0&&l++;let P=_e(_.raw_bytes),h=_e(_.emitted_bytes),x=Math.max(0,P-h),Ze=Un(_,"raw"),et=Un(_,"emitted"),Q=Math.max(0,Ze.tokens-et.tokens);y||=(_.estimated===!0||Ze.estimated||et.estimated)&&Q>0,d+=P,f+=h,w+=Q;let q=Ve(_).slice(0,10);q&&m.set(q,(m.get(q)??0)+Q);let Me=D(_.command)||"unknown",Re=g.get(Me)??{command:Me,invocations:0,bytes_saved:0,tokens_saved:0};Re.invocations++,Re.bytes_saved+=x,Re.tokens_saved+=Q,g.set(Me,Re);let tt=Wt(_.wrapper_ms);tt!=null&&S.push(tt),p+=_e(_.store_open_count);let nt=Wt(_.store_elapsed_ms);nt!=null&&(k+=nt,R++)}let T=new Map,A=null;for(let _ of u){let P=D(_.degradation_reason)||D(_.reason)||"unknown";T.set(P,(T.get(P)??0)+1);let h=Ve(_);(!A||h>A.timestamp)&&(A={timestamp:h,reason:P,command:D(_.command)||"unknown"})}let j=a.length+u.length,Y=c.filter(_=>_.hit===!0).length,I=qr(w,y),an=Ff(o);return{window_days:r,empty:s.length===0,savings:{invocations:a.length,elided:l,raw_bytes:d,emitted_bytes:f,bytes_saved:Math.max(0,d-f),tokens_saved:w,tokens_saved_estimated:I.tokens_saved_estimated,token_estimate_range_pct:I.token_estimate_range_pct,tokens_saved_low:I.tokens_saved_low,tokens_saved_high:I.tokens_saved_high,dollars_saved_estimate_usd:I.dollars_saved_estimate_usd,dollars_saved_low_usd:I.dollars_saved_low_usd,dollars_saved_high_usd:I.dollars_saved_high_usd,pricing_model_family:I.pricing_model_family,pricing_input_usd_per_million_tokens:I.pricing_input_usd_per_million_tokens,pricing_note:I.pricing_note,daily_tokens_saved:[...m.entries()].sort(([_],[P])=>_.localeCompare(P)).map(([_,P])=>({date:_,tokens_saved:P})),top_commands:[...g.values()].sort((_,P)=>P.bytes_saved-_.bytes_saved||P.tokens_saved-_.tokens_saved||_.command.localeCompare(P.command))},health:{degradations:u.length,degradation_rate:j===0?0:u.length/j,show_total:c.length,show_hits:Y,show_misses:Math.max(0,c.length-Y),show_hit_rate:c.length===0?0:Oe(Y/c.length),by_reason:[...T.entries()].sort((_,P)=>P[1]-_[1]||_[0].localeCompare(P[0])).map(([_,P])=>({reason:_,count:P})),most_recent:A},latency:{wrapper_ms_p50:ht(S,.5),wrapper_ms_p95:ht(S,.95),store_open_count_sum:p,store_elapsed_ms_sum:Oe(k),store_elapsed_ms_avg:R===0?null:Oe(k/R)},decisions:an}}function Ff(e){let t=0,n=0,r=0,i=new Map;for(let s of e){let o=D(s.decision);if(o==="contributed"?t++:o==="failed-open"?r++:n++,o!=="contributed"){let a=D(s.reason)||"unknown";i.set(a,(i.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:[...i.entries()].sort((s,o)=>o[1]-s[1]||s[0].localeCompare(o[0])).map(([s,o])=>({reason:s,count:o}))}}async function ci(e,t,n=new Date){let i=(await Vt(e,K)).filter(s=>wt(s)<=n.getTime()||Ve(s)==="");return{records:i.length,bytes:i.reduce((s,o)=>s+Buffer.byteLength(JSON.stringify(o),"utf8"),0),oldest:i.reduce((s,o)=>{let a=Ve(o);return a&&(s==null||a<s)?a:s},null),budget:t,storage_classes:Gf(i)}}async function ui(e,t,n=new Date){let r=Number.isFinite(t)&&t>0?t:28,i=n.toISOString(),s=new Date(n.getTime()-r*24*60*60*1e3).toISOString(),o=Date.parse(s),a=await Qo(e,o),c=a.filter(h=>D(h.event_type)!=="show"&&D(h.degradation_reason)===""),u=a.filter(h=>D(h.degradation_reason)!==""),l=[...c,...u].map(wt).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)/Qf()))),w=[],y=new Map,m=new Map,g=new Map,S=new Map,p=new Map,k=new Map,R=0,T=!1,A=0,j=null,Y=0,I=0;for(let h of c){let x=Ve(h),Ze=x.slice(0,10),et=x.slice(0,16),Q=Ho(D(h.command)),q=Math.max(0,Un(h,"raw").tokens-Un(h,"emitted").tokens);R+=q,T||=h.estimated===!0&&q>0;let Me=Math.max(0,_e(h.raw_bytes)-_e(h.emitted_bytes)),Re=Wt(h.wrapper_ms);if(Re!=null){w.push(Re);let ls=y.get(Q)??[];ls.push(Re),y.set(Q,ls)}Ze&&m.set(Ze,(m.get(Ze)??0)+1),et&&g.set(et,(g.get(et)??0)+1);let tt=Vf(x);tt&&S.set(tt,(S.get(tt)??0)+1);let nt=zf(x);nt&&p.set(nt,(p.get(nt)??0)+q);let cn=k.get(Q)??{command_family:Q,invocations:0,tokens_saved:0,bytes_saved:0};cn.invocations++,cn.tokens_saved+=q,cn.bytes_saved+=Me,k.set(Q,cn),h.elided===!0&&A++,(h.store_open_count!=null||h.store_elapsed_ms!=null)&&(Y++,_e(h.store_open_count)>0&&I++),q>0&&(!j||q>j.tokens_saved||q===j.tokens_saved&&Me>j.bytes_saved)&&(j={timestamp:x,command_family:Q,tokens_saved:q,bytes_saved:Me})}let an=u.map(h=>({timestamp:Ve(h),command_family:Ho(D(h.command)),reason:D(h.degradation_reason)||D(h.reason)||"unknown"})).sort((h,x)=>h.timestamp.localeCompare(x.timestamp)),_=new Map;for(let h of an)_.set(h.reason,(_.get(h.reason)??0)+1);let P=[...g.entries()].sort((h,x)=>x[1]-h[1]||h[0].localeCompare(x[0]))[0];return{schema_version:"red.rsp.gains.v1",window:{requested_days:r,data_days:f,since:s,until:i,label:`window: ${r}d, data: ${f}d`,empty:c.length===0&&u.length===0,invocations:c.length,degradations:u.length},latency:{global:Jo(w),by_command_family:[...y.entries()].sort((h,x)=>x[1].length-h[1].length||h[0].localeCompare(x[0])).map(([h,x])=>({command_family:h,count:x.length,...Jo(x)}))},throughput:{requests_per_day:[...m.entries()].sort(([h],[x])=>h.localeCompare(x)).map(([h,x])=>({date:h,requests:x})),active_minute_avg:g.size===0?null:Oe([...g.values()].reduce((h,x)=>h+x,0)/g.size),peak_minute:P?{minute:P[0],requests:P[1]}:null,hour_weekday_heatmap:Wf(S)},savings:{tokens:qr(R,T),weekly_tokens_saved:Yf(p),elision_rate:c.length===0?0:Oe(A/c.length),top_commands_by_tokens_saved:[...k.values()].sort((h,x)=>x.tokens_saved-h.tokens_saved||x.bytes_saved-h.bytes_saved||h.command_family.localeCompare(x.command_family)).slice(0,10),top_commands_by_invocation_count:[...k.values()].sort((h,x)=>x.invocations-h.invocations||x.tokens_saved-h.tokens_saved||h.command_family.localeCompare(x.command_family)).slice(0,10),single_biggest_elision:j},health:{degradation_timeline:an,degradations_by_reason:[..._.entries()].sort((h,x)=>x[1]-h[1]||h[0].localeCompare(x[0])).map(([h,x])=>({reason:h,count:x})),cold_boots:Y===0?null:I,warm_hits:Y===0?null:Math.max(0,Y-I)}}}async function Qo(e,t){let n=(await Vt(e,K)).filter(s=>wt(s)>=t);if(n.length>0)return n;let r=(await Vt(e,se)).filter(s=>wt(s)>=t).map(s=>({...s,event_type:"invocation"})),i=(await Vt(e,Pe)).filter(s=>wt(s)>=t).map(s=>({...s,event_type:"invocation",degradation_reason:D(s.reason)||"unknown"}));return[...r,...i]}function Un(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 Gf(e){let t=Jf();for(let n of e){if(D(n.event_type)==="show"||D(n.degradation_reason)!==""||n.elided!==!0)continue;let r=qf(n.storage_class)??Je(D(n.command));t[r].records+=1;let i=_e(n.raw_bytes);t[r].bytes+=i,t[r].raw_bytes+=i}return t}function qf(e){return e==="derivable"||e==="re-executable"||e==="ephemeral"?e:null}function Jf(){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 Vt(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=>Hf(r.value)).filter(r=>Xo(r))}function Hf(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function wt(e){let t=Date.parse(Ve(e));return Number.isFinite(t)?t:0}function Ve(e){return D(e.created_at)||D(e.ts)||""}function D(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 ht(e,t){if(e.length===0)return null;let n=[...e].sort((i,s)=>i-s),r=Math.min(n.length-1,Math.max(0,Math.ceil(n.length*t)-1));return Oe(n[r])}function Jo(e){return{wrapper_ms_p50:ht(e,.5),wrapper_ms_p90:ht(e,.9),wrapper_ms_p95:ht(e,.95),wrapper_ms_p99:ht(e,.99)}}function Oe(e){return Math.round(e*100)/100}function Ho(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 Vf(e){let t=new Date(e);return Number.isFinite(t.getTime())?`${Kf(t.getUTCDay())}:${t.getUTCHours()}`:null}function Wf(e){let t=[];for(let n of["sun","mon","tue","wed","thu","fri","sat"])for(let r=0;r<24;r++){let i=e.get(`${n}:${r}`)??0;i>0&&t.push({weekday:n,hour:r,requests:i})}return t}function Kf(e){return["sun","mon","tue","wed","thu","fri","sat"][e]??"unknown"}function zf(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 Yf(e){let t=null;return[...e.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>{let i=t==null||t===0?null:Oe((r-t)/t*100);return t=r,{week_start:n,tokens_saved:r,wow_delta_pct:i}})}function Qf(){return 24*60*60*1e3}function Xo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zo,K,z,se,Pe,Kt,Bf,De=E(()=>{"use strict";He();Jr();zo=si(".red","tmp","rsp-telemetry.spool.jsonl"),K="rsp_accounting_events_v1",z="rsp_decisions_v1",se="rsp_telemetry_invocations_v1",Pe="rsp_telemetry_degradations_v1",Kt="rsp_telemetry_index_v1",Bf=64*1024});var pi={};$(pi,{RSP_WRAPPER_CAPABILITIES:()=>Xt,formatCodexHookDecision:()=>ra,formatHookDecision:()=>na,hookDecisionFromClaudePreExecJson:()=>nm,hookDecisionFromCodexPreExecJson:()=>rm,rewriteCommand:()=>ea,rewriteTableFromCapabilities:()=>Zo,runClaudePreExecHook:()=>im,runCodexPreExecHook:()=>sm});import{readFileSync as Wn}from"node:fs";import{existsSync as Xf}from"node:fs";import{fileURLToPath as Zf}from"node:url";function Zo(e){let t=new Map;for(let n of e)t.set(Em(n.command),["rsp",...n.wrapper]);return t}function ea(e){let t=pm(e);if(t)return t;let n=fm(e);if(!n)return Hn(e);let r=n.tokens.map(c=>c.text);if(r.length>0&&pa(r[0]))return Hn(e);let i=tm(n);if(i)return i;if(n.tokens.some(c=>c.quoted))return Hn(e);let s=[...Xt].sort((c,u)=>u.command.length-c.command.length).find(c=>mm(r,c.command));if(!s)return Hn(e);let o=["rsp",...s.wrapper,...r.slice(s.command.length)],a=ua(n.redirectSuffix);return{kind:"rewrite",command:[...o.map(Qt),...a].join(" "),capabilityId:s.id}}function tm(e){let t=e.tokens.map(i=>i.text),n=t[0],r=ua(e.redirectSuffix);return n==="cat"&&t.length===2&&Jn(t[1])?{kind:"rewrite",command:["rsp","cat",Qt(t[1]),...r].join(" "),capabilityId:"cat:file"}:(n==="head"||n==="tail")&&t.length===2&&Jn(t[1])?{kind:"rewrite",command:["rsp","cat",`--${n}`,"10",Qt(t[1]),...r].join(" "),capabilityId:`cat:${n}`}:(n==="head"||n==="tail")&&t.length===4&&t[1]==="-n"&&/^[1-9][0-9]*$/.test(t[2])&&Jn(t[3])?{kind:"rewrite",command:["rsp","cat",`--${n}`,t[2],Qt(t[3]),...r].join(" "),capabilityId:`cat:${n}`}:(n==="head"||n==="tail")&&t.length===3&&/^-[1-9][0-9]*$/.test(t[1])&&Jn(t[2])?{kind:"rewrite",command:["rsp","cat",`--${n}`,t[1].slice(1),Qt(t[2]),...r].join(" "),capabilityId:`cat:${n}`}:null}function Jn(e){return!!e&&!e.startsWith("-")}async function nm(e,t){return await ta(e,t)}async function rm(e,t){return await ta(e,t)}async function ta(e,t){return(await di(e,t,"pre-exec")).decision}async function di(e,t,n){let r=ga(e);if(!r.ok){let f={kind:"passthrough",reason:r.reason};return{decision:f,telemetryRoot:t.cwd,event:Yt({hook:n,command:"",decision:f,reason:r.reason})}}let i=r.payload,s=X(i,["cwd"])||X(i,["tool_input","cwd"])||t.cwd;if(!await(t.isEnabled??om)(s)){let f={kind:"passthrough",reason:"disabled"};return{decision:f,telemetryRoot:s,event:Yt({hook:n,command:li(i),decision:f,reason:"disabled"})}}let a=li(i);if(!a){let f={kind:"passthrough",reason:"missing-command"};return{decision:f,telemetryRoot:s,event:Yt({hook:n,command:a,decision:f,reason:"missing-command"})}}let c=process.hrtime.bigint(),l=we(s,process.env).proxyEnabled?ym(a):(t.rewrite??ea)(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:s,event:Yt({hook:n,command:a,decision:f,reason:f.reason??"unsupported-command",decisionMs:d})}}return await cm(s,t.wakeResident??am),{decision:l,telemetryRoot:s,event:Yt({hook:n,command:a,decision:l,reason:l.capabilityId==="proxy:universal"?"universal-proxy":"matched-capability",decisionMs:d})}}function na(e){return e.kind==="rewrite"?ia(e.command):{stdout:"",status:0}}function ra(e){return e.kind==="rewrite"?ia(e.command):{stdout:"",status:0}}function ia(e){return{stdout:`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:{command:e}}})}
|
|
27
|
-
`,status:0}}async function
|
|
37
|
+
${s}`,"utf8")}await Io(t,{force:!0})}}function Gd(e){try{return Nd(e,"utf8")}catch{return""}}async function No(e){let t="";for(let n=0;n<5;n++){let r=await Cd(e,"utf8").catch(()=>"");if(r===t)return r;t=r,await new Promise(s=>setTimeout(s,2))}return t}function ns(e){try{let t=JSON.parse(e);return!Co(t)||t.collection!==H&&t.collection!==W&&t.collection!==re&&t.collection!==xe?null:t}catch{return null}}async function Cn(e,t,n=new Date){let r=Number.isFinite(t)&&t>0?t:30,s=n.getTime()-r*24*60*60*1e3,i=await Bo(e,s),o=(await qt(e,W)).filter(_=>mt(_)>=s),a=i.filter(_=>I(_.event_type)!=="show"&&I(_.degradation_reason)===""),c=i.filter(_=>I(_.event_type)==="show"),u=i.filter(_=>I(_.degradation_reason)!==""),l=0,d=0,f=0,y=0,g=!1,m=new Map,p=new Map,k=[],w=0,T=0,x=0;for(let _ of a){_.elided===!0&&l++;let D=ye(_.raw_bytes),h=ye(_.emitted_bytes),E=Math.max(0,D-h),Ye=$n(_,"raw"),Qe=$n(_,"emitted"),K=Math.max(0,Ye.tokens-Qe.tokens);g||=(_.estimated===!0||Ye.estimated||Qe.estimated)&&K>0,d+=D,f+=h,y+=K;let G=qe(_).slice(0,10);G&&m.set(G,(m.get(G)??0)+K);let Be=I(_.command)||"unknown",we=p.get(Be)??{command:Be,invocations:0,bytes_saved:0,tokens_saved:0};we.invocations++,we.bytes_saved+=E,we.tokens_saved+=K,p.set(Be,we);let Xe=Jt(_.wrapper_ms);Xe!=null&&k.push(Xe),w+=ye(_.store_open_count);let Ze=Jt(_.store_elapsed_ms);Ze!=null&&(T+=Ze,x++)}let P=new Map,B=null;for(let _ of u){let D=I(_.degradation_reason)||I(_.reason)||"unknown";P.set(D,(P.get(D)??0)+1);let h=qe(_);(!B||h>B.timestamp)&&(B={timestamp:h,reason:D,command:I(_.command)||"unknown"})}let j=a.length+u.length,V=c.filter(_=>_.hit===!0).length,$=Mr(y,g),rn=qd(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(([_],[D])=>_.localeCompare(D)).map(([_,D])=>({date:_,tokens_saved:D})),top_commands:[...p.values()].sort((_,D)=>D.bytes_saved-_.bytes_saved||D.tokens_saved-_.tokens_saved||_.command.localeCompare(D.command))},health:{degradations:u.length,degradation_rate:j===0?0:u.length/j,show_total:c.length,show_hits:V,show_misses:Math.max(0,c.length-V),show_hit_rate:c.length===0?0:ke(V/c.length),by_reason:[...P.entries()].sort((_,D)=>D[1]-_[1]||_[0].localeCompare(D[0])).map(([_,D])=>({reason:_,count:D})),most_recent:B},latency:{wrapper_ms_p50:ft(k,.5),wrapper_ms_p95:ft(k,.95),store_open_count_sum:w,store_elapsed_ms_sum:ke(T),store_elapsed_ms_avg:x===0?null:ke(T/x)},decisions:rn}}function qd(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:ke(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 rs(e,t,n=new Date){let s=(await qt(e,H)).filter(i=>mt(i)<=n.getTime()||qe(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=qe(o);return a&&(i==null||a<i)?a:i},null),budget:t,storage_classes:Jd(s)}}async function ss(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 Bo(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(mt).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)/Zd()))),y=[],g=new Map,m=new Map,p=new Map,k=new Map,w=new Map,T=new Map,x=0,P=!1,B=0,j=null,V=0,$=0;for(let h of c){let E=qe(h),Ye=E.slice(0,10),Qe=E.slice(0,16),K=Po(I(h.command)),G=Math.max(0,$n(h,"raw").tokens-$n(h,"emitted").tokens);x+=G,P||=h.estimated===!0&&G>0;let Be=Math.max(0,ye(h.raw_bytes)-ye(h.emitted_bytes)),we=Jt(h.wrapper_ms);if(we!=null){y.push(we);let ii=g.get(K)??[];ii.push(we),g.set(K,ii)}Ye&&m.set(Ye,(m.get(Ye)??0)+1),Qe&&p.set(Qe,(p.get(Qe)??0)+1);let Xe=Kd(E);Xe&&k.set(Xe,(k.get(Xe)??0)+1);let Ze=Qd(E);Ze&&w.set(Ze,(w.get(Ze)??0)+G);let sn=T.get(K)??{command_family:K,invocations:0,tokens_saved:0,bytes_saved:0};sn.invocations++,sn.tokens_saved+=G,sn.bytes_saved+=Be,T.set(K,sn),h.elided===!0&&B++,(h.store_open_count!=null||h.store_elapsed_ms!=null)&&(V++,ye(h.store_open_count)>0&&$++),G>0&&(!j||G>j.tokens_saved||G===j.tokens_saved&&Be>j.bytes_saved)&&(j={timestamp:E,command_family:K,tokens_saved:G,bytes_saved:Be})}let rn=u.map(h=>({timestamp:qe(h),command_family:Po(I(h.command)),reason:I(h.degradation_reason)||I(h.reason)||"unknown"})).sort((h,E)=>h.timestamp.localeCompare(E.timestamp)),_=new Map;for(let h of rn)_.set(h.reason,(_.get(h.reason)??0)+1);let D=[...p.entries()].sort((h,E)=>E[1]-h[1]||h[0].localeCompare(E[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:vo(y),by_command_family:[...g.entries()].sort((h,E)=>E[1].length-h[1].length||h[0].localeCompare(E[0])).map(([h,E])=>({command_family:h,count:E.length,...vo(E)}))},throughput:{requests_per_day:[...m.entries()].sort(([h],[E])=>h.localeCompare(E)).map(([h,E])=>({date:h,requests:E})),active_minute_avg:p.size===0?null:ke([...p.values()].reduce((h,E)=>h+E,0)/p.size),peak_minute:D?{minute:D[0],requests:D[1]}:null,hour_weekday_heatmap:zd(k)},savings:{tokens:Mr(x,P),weekly_tokens_saved:Xd(w),elision_rate:c.length===0?0:ke(B/c.length),top_commands_by_tokens_saved:[...T.values()].sort((h,E)=>E.tokens_saved-h.tokens_saved||E.bytes_saved-h.bytes_saved||h.command_family.localeCompare(E.command_family)).slice(0,10),top_commands_by_invocation_count:[...T.values()].sort((h,E)=>E.invocations-h.invocations||E.tokens_saved-h.tokens_saved||h.command_family.localeCompare(E.command_family)).slice(0,10),single_biggest_elision:j},health:{degradation_timeline:rn,degradations_by_reason:[..._.entries()].sort((h,E)=>E[1]-h[1]||h[0].localeCompare(E[0])).map(([h,E])=>({reason:h,count:E})),cold_boots:V===0?null:$,warm_hits:V===0?null:Math.max(0,V-$)}}}async function Bo(e,t){let n=(await qt(e,H)).filter(i=>mt(i)>=t);if(n.length>0)return n;let r=(await qt(e,re)).filter(i=>mt(i)>=t).map(i=>({...i,event_type:"invocation"})),s=(await qt(e,xe)).filter(i=>mt(i)>=t).map(i=>({...i,event_type:"invocation",degradation_reason:I(i.reason)||"unknown"}));return[...r,...s]}function $n(e,t){let n=Jt(e[t==="raw"?"tokens_raw":"tokens_emitted"]);if(n!=null)return{tokens:n,estimated:!1};let r=ye(e[t==="raw"?"raw_bytes":"emitted_bytes"]);return{tokens:Math.ceil(r/4),estimated:r>0}}function Jd(e){let t=Wd();for(let n of e){if(I(n.event_type)==="show"||I(n.degradation_reason)!==""||n.elided!==!0)continue;let r=Hd(n.storage_class)??Fe(I(n.command));t[r].records+=1;let s=ye(n.raw_bytes);t[r].bytes+=s,t[r].raw_bytes+=s}return t}function Hd(e){return e==="derivable"||e==="re-executable"||e==="ephemeral"?e:null}function Wd(){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 qt(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=>Vd(r.value)).filter(r=>Co(r))}function Vd(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function mt(e){let t=Date.parse(qe(e));return Number.isFinite(t)?t:0}function qe(e){return I(e.created_at)||I(e.ts)||""}function I(e){return typeof e=="string"?e:""}function ye(e){return Jt(e)??0}function Jt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function ft(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 ke(n[r])}function vo(e){return{wrapper_ms_p50:ft(e,.5),wrapper_ms_p90:ft(e,.9),wrapper_ms_p95:ft(e,.95),wrapper_ms_p99:ft(e,.99)}}function ke(e){return Math.round(e*100)/100}function Po(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 Kd(e){let t=new Date(e);return Number.isFinite(t.getTime())?`${Yd(t.getUTCDay())}:${t.getUTCHours()}`:null}function zd(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 Yd(e){return["sun","mon","tue","wed","thu","fri","sat"][e]??"unknown"}function Qd(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 Xd(e){let t=null;return[...e.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>{let s=t==null||t===0?null:ke((r-t)/t*100);return t=r,{week_start:n,tokens_saved:r,wow_delta_pct:s}})}function Zd(){return 24*60*60*1e3}function Co(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var $o,H,W,re,xe,Ht,Ld,Te=R(()=>{"use strict";Ge();jr();$o=es(".red","tmp","rsp-telemetry.spool.jsonl"),H="rsp_accounting_events_v1",W="rsp_decisions_v1",re="rsp_telemetry_invocations_v1",xe="rsp_telemetry_degradations_v1",Ht="rsp_telemetry_index_v1",Ld=64*1024});var us={};N(us,{RSP_WRAPPER_CAPABILITIES:()=>zt,formatCodexHookDecision:()=>Uo,formatHookDecision:()=>jo,hookDecisionFromClaudePreExecJson:()=>sf,hookDecisionFromCodexPreExecJson:()=>of,rewriteCommand:()=>Lo,rewriteTableFromCapabilities:()=>Ao,runClaudePreExecHook:()=>af,runCodexPreExecHook:()=>cf});import{readFileSync as jn}from"node:fs";import{existsSync as ef}from"node:fs";import{fileURLToPath as tf}from"node:url";function Ao(e){let t=new Map;for(let n of e)t.set(Tf(n.command),["rsp",...n.wrapper]);return t}function Lo(e){let t=yf(e);if(t)return t;let n=gf(e);if(!n)return Ln(e);let r=n.tokens.map(c=>c.text);if(r.length>0&&Qo(r[0]))return Ln(e);let s=rf(n);if(s)return s;if(n.tokens.some(c=>c.quoted))return Ln(e);let i=[...zt].sort((c,u)=>u.command.length-c.command.length).find(c=>hf(r,c.command));if(!i)return Ln(e);let o=["rsp",...i.wrapper,...r.slice(i.command.length)],a=Wo(n.redirectSuffix);return{kind:"rewrite",command:[...o.map(Kt),...a].join(" "),capabilityId:i.id}}function rf(e){let t=e.tokens.map(s=>s.text),n=t[0],r=Wo(e.redirectSuffix);return n==="cat"&&t.length===2&&An(t[1])?{kind:"rewrite",command:["rsp","cat",Kt(t[1]),...r].join(" "),capabilityId:"cat:file"}:(n==="head"||n==="tail")&&t.length===2&&An(t[1])?{kind:"rewrite",command:["rsp","cat",`--${n}`,"10",Kt(t[1]),...r].join(" "),capabilityId:`cat:${n}`}:(n==="head"||n==="tail")&&t.length===4&&t[1]==="-n"&&/^[1-9][0-9]*$/.test(t[2])&&An(t[3])?{kind:"rewrite",command:["rsp","cat",`--${n}`,t[2],Kt(t[3]),...r].join(" "),capabilityId:`cat:${n}`}:(n==="head"||n==="tail")&&t.length===3&&/^-[1-9][0-9]*$/.test(t[1])&&An(t[2])?{kind:"rewrite",command:["rsp","cat",`--${n}`,t[1].slice(1),Kt(t[2]),...r].join(" "),capabilityId:`cat:${n}`}:null}function An(e){return!!e&&!e.startsWith("-")}async function sf(e,t){return await Mo(e,t)}async function of(e,t){return await Mo(e,t)}async function Mo(e,t){return(await os(e,t,"pre-exec")).decision}async function os(e,t,n){let r=Xo(e);if(!r.ok){let f={kind:"passthrough",reason:r.reason};return{decision:f,telemetryRoot:t.cwd,event:Vt({hook:n,command:"",decision:f,reason:r.reason})}}let s=r.payload,i=Y(s,["cwd"])||Y(s,["tool_input","cwd"])||t.cwd;if(!await(t.isEnabled??uf)(i)){let f={kind:"passthrough",reason:"disabled"};return{decision:f,telemetryRoot:i,event:Vt({hook:n,command:is(s),decision:f,reason:"disabled"})}}let a=is(s);if(!a){let f={kind:"passthrough",reason:"missing-command"};return{decision:f,telemetryRoot:i,event:Vt({hook:n,command:a,decision:f,reason:"missing-command"})}}let c=process.hrtime.bigint(),l=ge(i,process.env).proxyEnabled?bf(a):(t.rewrite??Lo)(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:Vt({hook:n,command:a,decision:f,reason:f.reason??"unsupported-command",decisionMs:d})}}return await df(i,t.wakeResident??lf),{decision:l,telemetryRoot:i,event:Vt({hook:n,command:a,decision:l,reason:l.capabilityId==="proxy:universal"?"universal-proxy":"matched-capability",decisionMs:d})}}function jo(e){return e.kind==="rewrite"?Fo(e.command):{stdout:"",status:0}}function Uo(e){return e.kind==="rewrite"?Fo(e.command):{stdout:"",status:0}}function Fo(e){return{stdout:`${JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",updatedInput:{command:e}}})}
|
|
38
|
+
`,status:0}}async function af(e){let t="";try{t=e?jn(e,"utf8"):jn(0,"utf8");let n=await os(t,{cwd:process.cwd()},"claude-pre-exec");Un(n.telemetryRoot,n.event);let r=n.decision;qo("claude-pre-exec",r);let s=jo(r);return s.stdout&&process.stdout.write(s.stdout),s.status}catch(n){return Un(process.cwd(),Go("claude-pre-exec",t,n)),Jo("claude-pre-exec",n),0}}async function cf(e){let t="";try{t=e?jn(e,"utf8"):jn(0,"utf8");let n=await os(t,{cwd:process.cwd()},"codex-pre-exec");Un(n.telemetryRoot,n.event);let r=n.decision;qo("codex-pre-exec",r);let s=Uo(r);return s.stdout&&process.stdout.write(s.stdout),s.status}catch(n){return Un(process.cwd(),Go("codex-pre-exec",t,n)),Jo("codex-pre-exec",n),0}}function Un(e,t){Je(e,t).catch(()=>{})}function Vt(e){let t=e.command.trim(),n=e.decision.kind==="rewrite"?e.decision.capabilityId:void 0;return{collection:W,event_type:"decision",ts:new Date().toISOString(),hook:e.hook,command:t||"unknown",command_family:Yo(t),decision:n?"contributed":"passed",reason:e.reason,capability_id:n,decision_ms:e.decisionMs}}function Go(e,t,n){let r=Xo(t),s=r.ok?is(r.payload):"";return{collection:W,event_type:"decision",ts:new Date().toISOString(),hook:e,command:s||"unknown",command_family:Yo(s),decision:"failed-open",reason:"hook-exception",error:as(n)}}function uf(e){return ge(e,process.env).enabled}async function lf(e){let t=ge(e,process.env);if(!t.enabled||!pf(t))return;let n=Ee(e);await wn(n,mf(t))}async function df(e,t){try{await Promise.resolve(t(e))}catch(n){ff(n)}}function qo(e,t){if(process.env.RSP_DEBUG==="1"){if(t.kind==="rewrite"){process.stderr.write(`rsp hook ${e}: rewrite ${t.capabilityId}
|
|
28
39
|
`);return}process.stderr.write(`rsp hook ${e}: passthrough ${t.reason??"unsupported-command"}
|
|
29
|
-
`)}}function
|
|
30
|
-
`)}function
|
|
31
|
-
`)}function
|
|
32
|
-
`),detected:!0,lossy:!0,totalItems:
|
|
40
|
+
`)}}function Jo(e,t){process.env.RSP_DEBUG==="1"&&process.stderr.write(`rsp hook ${e}: exception ${as(t)}
|
|
41
|
+
`)}function ff(e){process.env.RSP_DEBUG==="1"&&process.stderr.write(`rsp hook pre-exec: resident-wake-failed ${as(e)}
|
|
42
|
+
`)}function as(e){return e instanceof Error?e.name||"Error":typeof e}function mf(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 pf(e){if(!e.storeUri.startsWith("file://"))return!0;try{return ef(tf(e.storeUri))}catch{return!1}}function is(e){return Y(e,["tool_input","command"])||Y(e,["tool_input","cmd"])||Y(e,["tool_input","args","command"])||Y(e,["input","command"])||Y(e,["input","cmd"])||Y(e,["arguments","command"])||Y(e,["arguments","cmd"])||Y(e,["command"])||Y(e,["cmd"])}function gf(e){let t=e.trim();if(!t||/[\n\r|;()$`]/.test(t))return null;let n=Ho(t);if(n.length===0||n[0]?.quoted||n.some(i=>/[()$`]/.test(i.text))||n.some(i=>i.text.includes("=")&&Qo(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 Ho(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 hf(e,t){return e.length<t.length?!1:t.every((n,r)=>e[r]===n)}function yf(e){let t=Ho(e.trim()).map(n=>n.text);return Mn(t)?{kind:"passthrough",reason:nf}:null}function Mn(e){return e[0]==="gh"&&e.some(wf)}function wf(e){return e==="--json"||e==="--jq"||e.startsWith("--json=")||e.startsWith("--jq=")}function Wo(e){return e.map(t=>t.text)}function Kt(e){return/[^\w@%+=:,./-]/.test(e)?cs(e):e}function bf(e){let t=_f(e);return t?{kind:"passthrough",reason:t}:{kind:"rewrite",command:`rsp proxy -- ${cs(e.trim())}`,capabilityId:"proxy:universal"}}function _f(e){let t=e.trim();if(!t)return"missing-command";if(Ko(t))return"background";if(/\b(?:RSP_NO_PROXY|RED_SKILLS_RSP_NO_PROXY)=1\b/.test(t))return"opt-out";let n=Gn(Fn(t)[0]??"")[0];if(n==="rsp")return"opt-out";if(n&&Vo.has(n))return"interactive"}function Ln(e){let t=e.trim();return Rf(t)?{kind:"rewrite",command:`rsp exec -- ${cs(t)}`,capabilityId:"exec:compound"}:{kind:"passthrough"}}function Rf(e){return!(!e||!Sf(e)||!Ef(e)||Ko(e)||/<<-?/.test(e)||/\$\(|`/.test(e)||/[<>]/.test(e)||kf(e,"rsp")||zo(e,Vo)||xf(e))}function Sf(e){return/&&|[;|]/.test(e)}function Ko(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 Ef(e){return Fn(e).some(t=>{let n=Gn(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 zo(e,t){return Fn(e).some(n=>{let r=Gn(n)[0];return r?t.has(r):!1})}function kf(e,t){return zo(e,new Set([t]))}function xf(e){return Fn(e).some(t=>{let n=Gn(t);return n[0]==="grep"&&n.includes("-q")})}function Fn(e){return e.split(/&&|[;|]/).map(t=>t.trim()).filter(Boolean)}function Gn(e){return e.split(/[ \t]+/).filter(Boolean).map(t=>t.replace(/^env$/,""))}function cs(e){return`'${e.replace(/'/g,"'\\''")}'`}function Yo(e){let t=e.trim().split(/\s+/).filter(Boolean);return t.length===0?"unknown":t[0]==="git"&&t[1]?`git ${t[1]}`:Mn(t)&&t[1]&&t[2]?`gh ${t[1]} ${t[2]} json-jq`:Mn(t)&&t[1]?`gh ${t[1]} json-jq`:Mn(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 Qo(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}function Tf(e){return e.join("\0")}function Xo(e){try{let t=JSON.parse(e);return Zo(t)?{ok:!0,payload:t}:{ok:!1,reason:"payload-not-object"}}catch{return{ok:!1,reason:"payload-parse-error"}}}function Y(e,t){let n=e;for(let r of t){if(!Zo(n))return"";n=n[r]}return typeof n=="string"?n:""}function Zo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zt,mb,nf,Vo,qn=R(()=>{"use strict";ne();je();Te();zt=[{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"]}],mb=Ao(zt),nf="lossless-gh-json-jq";Vo=new Set(["bash","fish","htop","less","more","nano","node","python","python3","ssh","top","vi","vim","zsh"])});var ds={};N(ds,{NORMALIZATION_ALLOWLIST:()=>ca,NORMALIZE_ANSI:()=>na,NORMALIZE_BLANK_LINES:()=>ia,NORMALIZE_CR_PROGRESS:()=>ra,NORMALIZE_JSON_TOON:()=>aa,NORMALIZE_TRAILING_WHITESPACE:()=>sa,formatCodexNormalizeDecision:()=>ma,formatNormalizeDecision:()=>fa,hookDecisionFromClaudePostExecJson:()=>ua,hookDecisionFromCodexPostExecJson:()=>la,normalizeOutput:()=>pt,renderGenericJsonLane:()=>Yt,runClaudePostExecHook:()=>Of,runCodexPostExecHook:()=>Df,transcodeJsonToToon:()=>oa});import{readFileSync as Jn}from"node:fs";function oa(e,t){let n=t?.encode??v,r=t?.decode??Dt,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 ls(i,a)?o.trimEnd():e}async function Yt(e,t={}){let n=Bf(e);if(!n)return{output:e,detected:!1,lossy:!1};let r=n.value;if(!Array.isArray(r))return{output:v(r).trimEnd(),detected:!0,lossy:!1};let s=r.length,i=ta(t.minTokens,vf),o=ta(t.maxItems,Pf);if(!(s>o&&jf(e)>=i))return{output:v(r).trimEnd(),detected:!0,lossy:!1,totalItems:s,keptItems:s};let c=Cf(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"}`,y=v(u).trimEnd();return{output:[l,f,y].filter(Boolean).join(`
|
|
43
|
+
`),detected:!0,lossy:!0,totalItems:s,keptItems:c.length,handle:d}}function pt(e){let t=e;for(let n of ca)t=n.apply(t);return t}async function ua(e,t){return await da(e,t)}async function la(e,t){return await da(e,t)}async function da(e,t){let n=Nf(e),r=Uf(n,["cwd"])||t.cwd;if(!await(t.isEnabled??$f)(r))return{kind:"passthrough",reason:"disabled"};let i=Ff(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??pt)(o);return c===o?{kind:"passthrough",reason:"no-change"}:{kind:"normalized",output:c}}function fa(e){return e.kind==="normalized"?{stdout:JSON.stringify({tool_response:{output:e.output}}),status:0}:{stdout:"",status:0}}function ma(e){return{stdout:"",status:0}}async function Of(e){let t=e?Jn(e,"utf8"):Jn(0,"utf8"),n=await ua(t,{cwd:process.cwd()}),r=fa(n);return r.stdout&&process.stdout.write(r.stdout),r.status}async function Df(e){let t=e?Jn(e,"utf8"):Jn(0,"utf8"),n=await la(t,{cwd:process.cwd()}),r=ma(n);return r.stdout&&process.stdout.write(r.stdout),r.status}function If(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&&ea(e.charCodeAt(n));)n++;n<e.length&&n++;continue}n+=s>=32?2:1;continue}if(r===155){for(n++;n<e.length&&ea(e.charCodeAt(n));)n++;n<e.length&&n++;continue}t+=e[n++]}return t}function ea(e){return e>=32&&e<=63}function $f(e){return ge(e,process.env).enabled}function Nf(e){try{let t=JSON.parse(e);return ve(t)?t:{}}catch{return{}}}function Bf(e){let t=e.trim();if(!t)return null;try{let r=JSON.parse(t);return ve(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 Cf(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++)Af(e[i])&&n.add(i);for(let i of Lf(e))n.add(i);for(let i of Mf(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 Af(e){if(!ve(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 Lf(e){let t=new Map;e.forEach((r,s)=>{if(ve(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 Mf(e){let t=new Set;for(let n=1;n<e.length;n++){let r=e[n-1],s=e[n];if(!(!ve(r)||!ve(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 jf(e){return Math.ceil(e.length/4)}function ta(e,t){return e==null?t:Number.isFinite(e)&&e>0?Math.floor(e):t}function Uf(e,t){let n=e;for(let r of t){if(!ve(n))return"";n=n[r]}return typeof n=="string"?n:""}function Ff(e,t){let n=e[t];return ve(n)?n:null}function ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ls(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)=>ls(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)&&ls(n[o],r[o]))}var na,ra,sa,ia,aa,vf,Pf,ca,Qt=R(()=>{"use strict";Re();ne();na={id:"ansi",apply:If},ra={id:"cr-progress",apply:e=>e.split(`
|
|
33
44
|
`).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(`
|
|
34
|
-
`)},
|
|
45
|
+
`)},sa={id:"trailing-whitespace",apply:e=>e.split(`
|
|
35
46
|
`).map(t=>t.replace(/[ \t]+$/,"")).join(`
|
|
36
|
-
`)},
|
|
47
|
+
`)},ia={id:"blank-lines",apply:e=>e.replace(/\n{3,}/g,`
|
|
37
48
|
|
|
38
|
-
`)};
|
|
39
|
-
`),
|
|
49
|
+
`)};aa={id:"json-to-toon",apply:e=>oa(e)},vf=200,Pf=15;ca=[na,ra,sa,ia,aa]});var Ra={};N(Ra,{REPO_STORE_PATH:()=>fs,mergeRspBlock:()=>wa,provisionRspRepoStore:()=>zf});import{constants as Gf}from"node:fs";import{access as qf,copyFile as Jf,mkdir as pa,readFile as Hf,writeFile as ga}from"node:fs/promises";import{dirname as Wf,join as Hn,resolve as Vf}from"node:path";async function zf(e,t={}){let n=Vf(e),r=Hn(n,".red"),s=Hn(r,"config.yaml"),i=Hn(n,fs);await pa(r,{recursive:!0}),await pa(Wf(i),{recursive:!0});let o="";try{o=await Hf(s,"utf8")}catch(f){if(f.code!=="ENOENT")throw f}let a=wa(o,{enabled:!0,ttlDays:t.ttlDays??fe,ephemeralTtlHours:t.ephemeralTtlHours??me,byteBudget:t.byteBudget??pe,heavyGitByteThreshold:t.heavyGitByteThreshold??de}),c=a!==o;c&&await ga(s,a,"utf8");let u=!await ya(i),l=!1;if(u){let f=Hn(n,Kf);if(await ya(f))await Jf(f,i),l=!0;else{let{RspElisionStore:y}=await Promise.resolve().then(()=>(Ge(),Gt)),g=process.env.REDDB_BIN;try{await(await y.open({uri:`file://${i}`,ttlDays:t.ttlDays??fe,ephemeralTtlHours:t.ephemeralTtlHours??me,byteBudget:t.byteBudget??pe,allowResidentOpen:!0})).close()}finally{g===void 0?delete process.env.REDDB_BIN:process.env.REDDB_BIN=g}}}let d=Yf(a,fs);return d!==a&&await ga(s,d,"utf8"),{configPath:s,storePath:i,configChanged:c||d!==a,storeCreated:u,memoryStoreMigrated:l}}function wa(e,t){let n=["rsp:",` enabled: ${t.enabled?"true":"false"}`,` ttlDays: ${Wn(t.ttlDays,fe)}`,` ephemeralTtlHours: ${Wn(t.ephemeralTtlHours,me)}`,` byteBudget: ${Wn(t.byteBudget,pe)}`,` heavyGitByteThreshold: ${Wn(t.heavyGitByteThreshold,de)}`],r=e===""?[]:e.replace(/\n+$/,"").split(`
|
|
50
|
+
`),s=ba(r,"rsp");if(s===-1){let a=[...r];return a.length>0&&a[a.length-1].trim()!==""&&a.push(""),a.push(...n),`${a.join(`
|
|
40
51
|
`)}
|
|
41
|
-
`}let
|
|
52
|
+
`}let i=ms(r,s,0);return`${[...r.slice(0,s),...n,...r.slice(i)].join(`
|
|
42
53
|
`)}
|
|
43
|
-
`}function
|
|
44
|
-
`),r=
|
|
54
|
+
`}function ba(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(gs(r)&&ps(r)===0&&_a(r)===t)return n}return-1}function ms(e,t,n){let r=e.length;for(let s=t+1;s<e.length;s++)if(gs(e[s])&&ps(e[s])<=n){r=s;break}for(;r-1>t&&e[r-1].trim()==="";)r--;return r}function ps(e){return(e.match(/^ */)?.[0]??"").length}function gs(e){let t=e.trim();return t!==""&&!t.startsWith("#")}function _a(e){return e.replace(/^ */,"").replace(/:.*$/,"").trim()}function Wn(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Yf(e,t){let n=e===""?[]:e.replace(/\n+$/,"").split(`
|
|
55
|
+
`),r=ba(n,"plugins");if(r===-1)return e;let s=ms(n,r,0),i=ha(n,"memory",r+1,s,2);if(i===-1)return e;let o=ms(n,i,2),a=[...n],c=ha(a,"storePath",i+1,o,4);return c!==-1?a[c]=` storePath: ${t}`:a.splice(o,0,` storePath: ${t}`),`${a.join(`
|
|
45
56
|
`)}
|
|
46
|
-
`}function
|
|
57
|
+
`}function ha(e,t,n,r,s){for(let i=n;i<r;i++){let o=e[i];if(gs(o)&&ps(o)===s&&_a(o)===t)return i}return-1}async function ya(e){try{return await qf(e,Gf.F_OK),!0}catch{return!1}}var fs,Kf,Sa=R(()=>{"use strict";ne();fs=Sn,Kf=".red/memory/graph.rdb"});var Pa={};N(Pa,{runRspMcpServer:()=>Xf});import{createInterface as Qf}from"node:readline";async function Xf(){let e=ge(process.cwd(),process.env),t=Qf({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 Zf(r,e);Ta({jsonrpc:"2.0",id:r.id??null,result:s})}catch(s){Ta({jsonrpc:"2.0",id:typeof va(n)?.id>"u"?null:va(n)?.id,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}})}}}async function Zf(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:xa(t)}]};if(!t.enabled)return{content:[{type:"text",text:xa(t)}],isError:!0};let r=im(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 em(n.arguments,r)}]}}return{}}async function em(e,t){let n=tm(e?.payload),r=nm(e?.level),s=await Yt(n,{level:r,command:"rsp mcp compress",store:t});if(s.detected)return Ea(s.output);let i=pt(n);if(r==="brief"&&Buffer.byteLength(i)<=2*1024)return Ea(i);let o=Buffer.from(n),a=await t.mint(o,{command:"rsp mcp compress",loss:{level:r,bytes_elided:o.length}});return rm(i,o.length,a,r)}function tm(e){return typeof e=="string"?e:e==null?"":JSON.stringify(e)}function nm(e){return e==="terse"?"terse":"brief"}function rm(e,t,n,r){let s=r==="terse"?1024:2048,i=Buffer.from(e),o=Math.max(1,Math.floor(s/2)),a=ka(i.subarray(0,o)),c=ka(i.subarray(Math.max(0,i.length-o))),u=["payload summary",`bytes: ${t}`,`lines: ${sm(i)}`,"head:",a];return c&&c!==a&&u.push("tail:",c),u.push(`\u2026 elided payload (+${t}) \u2014 rsp show ${n}`),`${u.join(`
|
|
47
58
|
`)}
|
|
48
|
-
`}function
|
|
59
|
+
`}function Ea(e){return e.endsWith(`
|
|
49
60
|
`)?e:`${e}
|
|
50
|
-
`}function
|
|
51
|
-
`)}function
|
|
52
|
-
`),0;if(!
|
|
53
|
-
`),await
|
|
54
|
-
`)}function
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function rr(e,t){if(t.length===0)return[];if(t.some(s=>s.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(s=>s.command.slice(1)).filter(s=>s.length===1).map(s=>s[0]).filter(ir),r=t.map(s=>s.command.slice(1)).filter(s=>s.length>1&&s.every(ir)),i=[`${e}() {`," if ! command -v rsp >/dev/null 2>&1; then",` command ${e} "$@"`," return"," fi",' case "$1" in'];if(n.length>0){let s=n.map(o=>ec(o)).join("|");i.push(` ${s}) command rsp ${e} "$@" ;;`)}for(let[s,o]of Ip(r)){let a=o.map(c=>c.map((u,l)=>`[ "$${l+2}" = '${Ap(u)}' ]`).join(" && ")).join(" || ");i.push(` ${ec(s)}) if ${a}; then command rsp ${e} "$@"; else command ${e} "$@"; fi ;;`)}return i.push(` *) command ${e} "$@" ;;`," esac","}"),i}function Ip(e){let t=new Map;for(let[n,...r]of e){if(!n)continue;let i=t.get(n)??[];i.push(r),t.set(n,i)}return t}function $p(e){let t=new Map;for(let n of e){let r=n.command[0];if(!r||!ir(r))continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function ir(e){return!!(e&&/^[A-Za-z0-9_./:-]+$/.test(e))}function ec(e){return e.replace(/[\\|)&;]/g,"\\$&")}function Ap(e){return e.replace(/'/g,"'\\''")}function Np(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}var nc=E(()=>{"use strict";Qn()});function Oi(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"&&Bp(t.chosenOption)&&Cp(t.outcome)&&Lp(t.cost)}function Bp(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function Cp(e){return e==="success"||e==="failure"||e==="escalated"}function Lp(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 rc=E(()=>{});import{createHash as Mp}from"node:crypto";function gc(e,t){return new Di(e,t)}function ic(e){let t=Number(e.red_entity_id??e.rid),n=Ii(e.properties??e.PROPERTIES),r=yc(String(e.node_type??e.NODE_TYPE??n.kind??"note"));if(!Number.isFinite(t))return null;let i=String(n.id??e.label??e.LABEL??t),s=String(n.title??e.label??e.LABEL??i),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??i),kind:r,properties:{...n,id:i,title:s,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 sc(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),i=hc(String(e.label??e.LABEL??"related_to"));return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)?null:{rid:t,kind:i,from_rid:n,to_rid:r,weight:Number(e.weight??1),properties:Ii(e.properties??e.PROPERTIES)}}function Fp(e){let t=Number(e.red_entity_id??e.rid),n=Ii(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Oi(n)?null:{rid:t,event:n}}function Ii(e){return e==null?{}:typeof e=="string"?JSON.parse(e):sr(e)?e:{}}function yc(e){let t=e==="contact"?"person":e;if(jp.has(t))return t;throw new Error(`invalid Brain artifact kind: ${e}`)}function hc(e){if(Up.has(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function Gp(e){return e==="hour"||e==="week"||e==="month"?e:"day"}function oc(e){if(typeof e=="number")return e;let t=String(e??"");return/^\d+$/.test(t)?Number(t):t}function ze(e){return sr(e)?e:{}}function ac(e,t){return ze(e)[t]}function cc(e,t){let n=e[t];if(typeof n!="string")throw new Error(`brain ${t} must be a string`);return n}function uc(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function lc(e){let t=ze(e);return{excludeRids:Array.isArray(t.excludeRids)?t.excludeRids.map(Number).filter(Number.isFinite):void 0}}function L(e){return typeof e=="string"&&e.length>0?e:void 0}function sr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pi(e){return e!=null}function qp(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function Jp(e){return Mp("sha256").update(JSON.stringify(e)).digest("hex")}function Hp(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"artifact"}function dc(e){return`artifact-hash:${e}`}function fc(e,t,n){return`connection:${e}:${t}:${n}`}function mc(){return"model-tier-bandit:v1"}function Vp(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function pc(e,t){let n=0,r=e.indexOf(t);for(;r>=0;)n++,r=e.indexOf(t,r+t.length);return n}function wc(e,t){let n=e.properties.title.toLowerCase(),r=e.properties.content.toLowerCase(),i=e.properties.tags.map(o=>o.toLowerCase()),s=e.kind.toLowerCase();return{lexical:t.reduce((o,a)=>o+pc(n,a)*3+pc(r,a),0),tags:t.reduce((o,a)=>o+i.reduce((c,u)=>c+(u===a?4:u.includes(a)||a.includes(u)?2:0),0),0),kind:t.reduce((o,a)=>o+(s===a?3:s.includes(a)||a.includes(s)?1:0),0)}}function Wp(e,t,n,r){let i=0;for(let s of n){let o=s.from_rid===e.rid?s.to_rid:s.to_rid===e.rid?s.from_rid:null;if(o==null)continue;let a=r.get(o);if(!a)continue;let c=bc({...wc(a,t),connections:0,vector:0}).total;c>0&&(i+=Math.min(c,12)*.35)}return Ke(i)}function bc(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 Kp(e,t){if(e.length<=220)return e;let n=e.toLowerCase(),r=t.map(s=>n.indexOf(s)).filter(s=>s>=0).sort((s,o)=>s-o)[0]??0,i=Math.max(0,r-80);return`${i>0?"...":""}${e.slice(i,i+220)}${i+220<e.length?"...":""}`}function zp(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((i,s)=>({ref:`B${s+1}`,rid:i.artifact.rid,id:i.artifact.properties.id,title:i.artifact.properties.title,kind:i.artifact.kind,score:i.score,score_breakdown:i.score_breakdown,excerpt:i.excerpt})),confidence:n,missing_evidence:r}}function Yp(e){let t={};for(let n of e)t[n]=(t[n]??0)+1;return t}var oe,jp,Up,Di,_c=E(()=>{"use strict";rc();oe={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"},jp=new Set(["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"]),Up=new Set(["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"]),Di=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(ac(n,"ridOrId"));if(t==="listArtifacts")return await this.listArtifacts();if(t==="search"){let r=ze(n);return await this.search(cc(r,"query"),uc(r,"limit")??10,lc(r.options))}if(t==="think"){let r=ze(n);return await this.think(cc(r,"query"),uc(r,"limit")??8,lc(r.options))}if(t==="link")return await this.link(ze(n));if(t==="backlinks")return await this.backlinks(ac(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:Yp(t.map(r=>r.kind))}}async capture(t){let n=L(t.title)||"Untitled artifact",r=L(t.content);if(!r)throw new Error("brain capture requires content");let i=yc(L(t.kind)||"note"),s=qp(Array.isArray(t.tags)?t.tags.map(String):[]),o=Date.now(),a=Jp([i,n,r,s,L(t.sourcePath),L(t.sourceSession)]),c=await this.kv().get(dc(a));if(c!=null){let y=await this.getArtifact(Number(c));if(y)return y}let u=`${Hp(n)}-${a.slice(0,8)}`,l={id:u,title:n,content:r,tags:s,source_agent:L(t.sourceAgent),source_runner:L(t.sourceRunner),source_session:L(t.sourceSession),source_path:L(t.sourcePath),created_at:o,updated_at:o,hash:a,metadata:sr(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,i,a,l)).rows[0];if(!f)throw new Error("INSERT artifact returned no row");let w=ic(f);if(!w)throw new Error("INSERT artifact returned invalid row");return await this.kv().put(dc(a),w.rid),await this.materializeTagConnections(w),w}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(ic).filter(Pi)}async search(t,n,r={}){let i=Vp(t),s=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=>!s.has(u.rid)).map(u=>{let l=wc(u,i),d=bc({...l,connections:Wp(u,i,a,c),vector:0});return{artifact:u,score:d.total,score_breakdown:d,excerpt:Kp(u.properties.content,i)}}).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 i=(await this.search(t,Math.max(n*2,n+5),r)).slice(0,n);return zp(t,i)}async link(t){let n=await this.getArtifact(oc(t.from)),r=await this.getArtifact(oc(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 i=hc(L(t.kind)||"related_to"),s=await this.findConnection(n.rid,r.rid,i);if(s!=null){let l=(await this.listConnections()).find(d=>d.rid===s);if(l)return l}let o={reason:L(t.reason),confidence:L(t.confidence)||"explicit",created_at:Date.now(),metadata:sr(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 *`,i,n.rid,r.rid,1,o)).rows[0];if(!c)throw new Error("INSERT connection returned no row");let u=sc(c);if(!u)throw new Error("INSERT connection returned invalid row");return await this.kv().put(fc(n.rid,r.rid,i),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(sc).filter(Pi)}async eventKpis(t){let n=(await this.listArtifacts()).filter(s=>s.kind==="event"),r=Gp(L(t.interval)||"day"),i=L(t.timeField)==="ingested"?"ingested":"event";return{kind:"event",interval:r,timeField:i,range:{from:null,to:null},total:n.length,series:[{group:null,total:n.length,buckets:[]}]}}async appendOutcomeEvent(t){if(!Oi(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(Fp).filter(Pi).sort((n,r)=>n.rid-r.rid).map(({event:n})=>n)}async loadModelTierBanditDocument(){let t=await this.kv().get(mc());return typeof t=="string"?JSON.parse(t):t}async saveModelTierBanditDocument(t){return await this.kv().put(mc(),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 i=await this.kv().get(fc(t,n,r));return i!=null?Number(i):null}kv(){return this.db.kv(oe.kv)}}});var Ac={};$(Ac,{runResidentServer:()=>ig});import{randomUUID as Rt}from"node:crypto";import{execFileSync as Qp,spawn as Xp}from"node:child_process";import{existsSync as Zp}from"node:fs";import{mkdir as vc,rename as eg,rm as Rc,writeFile as Oc}from"node:fs/promises";import{createServer as tg}from"node:net";import{dirname as Bi,join as rn}from"node:path";import{fileURLToPath as ng,pathToFileURL as rg}from"node:url";async function ig(e){await vc(Bi(e.socketPath),{recursive:!0});let t=hg();yg();let n=e.telemetryDrainTimeoutMs??Pc,r={kind:"opening",startedAt:process.hrtime.bigint()},i,s=!1,o=e.idleMs??An,a,c,u=!1,l=new Set,d=e.telemetryDrainIntervalMs??3e4,f=tg(R=>{l.add(R),R.once("close",()=>l.delete(R)),y(),kg(R,async T=>{y();let A=await xg(r,T,e.storeUri,e.residentVersion??"0.0.0-dev"),j={id:T.id,ok:!0,value:A,storeOpenCount:r.kind==="ready"?r.storeOpenCount:void 0,storeElapsedMs:r.kind==="ready"?r.storeElapsedMs:void 0};$c(R,j),T.op==="handover"&&setImmediate(()=>w())})});function w(){s=!0,u=!0,c=gg(c),f.close();for(let R of l)R.destroy()}function y(){r.kind!=="opening"&&(a&&clearTimeout(a),a=setTimeout(()=>{w()},o),a.unref())}let g=["SIGINT","SIGTERM"].map(R=>{let T=()=>{or(),f.close();for(let A of l)A.destroy();setTimeout(()=>process.exit(0),1e3)};return process.once(R,T),{signal:R,handler:T}});await new Promise((R,T)=>{f.once("error",T),f.listen(e.socketPath,()=>{f.off("error",T),R()})}),(async()=>{let R=process.hrtime.bigint();process.env.RSP_TEST_HANG_RESIDENT_STORE_OPEN==="1"&&await new Promise(()=>{});let T=Number(process.env.RSP_TEST_DELAY_RESIDENT_STORE_OPEN_MS??"0");Number.isFinite(T)&&T>0&&await new Promise(I=>setTimeout(I,T));let A=await qt.open({uri:e.storeUri,ttlDays:e.ttlDays,ephemeralTtlHours:e.ephemeralTtlHours,byteBudget:e.byteBudget,allowResidentOpen:!0}),j=Number(process.hrtime.bigint()-R)/1e6,Y=new Ni(A,{rootDir:e.rootDir??process.cwd(),ttlDays:e.telemetryTtlDays??In,byteBudget:e.telemetryByteBudget??e.byteBudget??$n});if(s){await A.close();return}if(await $i(Y,n),s){await A.close();return}r={kind:"ready",store:A,telemetry:Y,storeOpenCount:1,storeElapsedMs:j},i=setInterval(()=>{let I=r.kind==="ready"?r:void 0;I&&$i(I.telemetry,n)},d),i.unref(),y()})().catch(R=>{r={kind:"failed",error:R instanceof Error?R:new Error(String(R))},y()}),e.pidPath&&await Oc(e.pidPath,`${process.pid}
|
|
57
|
-
`,{encoding:"utf8",mode:384});let
|
|
58
|
-
`)}}async function
|
|
61
|
+
`}function ka(e){return e.toString("utf8").replace(/�$/g,"")}function sm(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 im(e){return new At(Ee(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 xa(e){return e.enabled?"rsp is enabled in this directory":"rsp is not enabled in this directory; run /red-setup"}function Ta(e){process.stdout.write(`${JSON.stringify(e)}
|
|
62
|
+
`)}function va(e){try{return JSON.parse(e)}catch{return null}}var Oa=R(()=>{"use strict";ne();Qt();je()});var Ca={};N(Ca,{renderWaitHelp:()=>bs,runWait:()=>dm});import{spawn as Rs}from"node:child_process";import{existsSync as ws}from"node:fs";import{mkdir as om,readdir as am,readFile as cm,rm as $a,writeFile as Na}from"node:fs/promises";import{join as Zt,resolve as hs}from"node:path";import{randomUUID as um}from"node:crypto";async function dm(e,t=process.cwd()){let n=mm(e);if(n.kind==="help"||e.includes("--help")||e.includes("-h"))return process.stdout.write(bs()),0;if(n.kind==="ls")return process.stdout.write(`${v({waits:await _m(t)})}
|
|
63
|
+
`),0;if(!fm(n.kind))return process.stdout.write(bs()),2;let r=n.kind,s={id:um(),target:km(n),reason:n.options.reason,pid:process.pid,started_at:new Date().toISOString(),poll_tier:lm[n.kind],status:"running"},i=Zt(await _s(t),`${s.id}.json`),o={status:"indeterminate",exitCode:2,summary:"wait did not start"};try{return await om(await _s(t),{recursive:!0}),await Na(i,JSON.stringify(s,null,2),"utf8"),o=await pm({...n,kind:r},t,i,s),process.stdout.write(`${v(Em(r,s,o))}
|
|
64
|
+
`),await Sm(n.options),o.exitCode}finally{await $a(i,{force:!0})}}function fm(e){return e==="cmd"||e==="pr"||e==="run"||e==="release"}function bs(){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(`
|
|
65
|
+
`)}function mm(e){let t=e[1],n={timeoutMs:Da.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=Da[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=Tm(e[++o]??""):a==="--reason"?n.reason=e[++o]??"":a==="--signal-pid"?n.signalPid=Number(e[++o]):a==="--signal"?n.signal=vm(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 pm(e,t,n,r){switch(e.kind){case"cmd":return await gm(e.commandLine??"",e.options.timeoutMs,t,n,r);case"pr":return await ys(()=>hm(e.target??"",t),e.options.timeoutMs,15e3,n,r);case"run":return await ys(()=>ym(e,t),e.options.timeoutMs,15e3,n,r);case"release":return await ys(()=>bm(e.tagGlob,new Date(r.started_at),t),e.options.timeoutMs,6e4,n,r)}}async function gm(e,t,n,r,s){return e.trim()?await new Promise(i=>{let o=!1,a=l=>{o||(o=!0,i(l))},c=Rs(e,{cwd:n,shell:!0,stdio:"ignore",detached:!1}),u=setTimeout(()=>{c.kill("SIGTERM"),Xt(r,s,"timeout"),a({status:"timeout",exitCode:2,summary:`command timed out after ${Ba(t)}`})},t);c.once("error",l=>{clearTimeout(u),Xt(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;Xt(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 ys(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 Xt(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 Dm(Math.min(c,Math.max(0,i-Date.now())))}return await Xt(r,s,"timeout"),{status:"timeout",exitCode:2,summary:`timed out after ${Ba(t)}`}}async function hm(e,t){if(!/^[1-9][0-9]*$/.test(e))return{status:"indeterminate",exitCode:2,summary:"missing PR number"};let n=await Vn(["pr","view",e,"--json","number,state,mergeable,statusCheckRollup,url"],t);if(n.status!==0)return{status:"indeterminate",exitCode:2,summary:n.stderr||"gh pr view failed"};let r=Ss(n.stdout),s=Array.isArray(r.statusCheckRollup)?r.statusCheckRollup:[],i=s.map(xm),o=i.filter(c=>c==="failure").length,a=i.filter(c=>c==="pending").length;return String(r.state)!=="OPEN"?gt("failure",`PR #${e} is ${String(r.state).toLowerCase()}`,{mergeable:String(r.mergeable??"")}):o>0?gt("failure",`PR #${e} has failing checks`,{failing:o,pending:a,mergeable:String(r.mergeable??"")}):a>0?{status:"running",exitCode:2,summary:`PR #${e} has ${a} pending checks`}:gt("success",`PR #${e} checks passed`,{checks:s.length,mergeable:String(r.mergeable??"")})}async function ym(e,t){let n=e.target??(e.latest&&e.branch?await wm(e.branch,t):"");if(!n)return{status:"indeterminate",exitCode:2,summary:"missing run id"};let r=await Vn(["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=Ss(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"?gt("success",`run ${n} succeeded`,Ia(s)):gt("failure",`run ${n} concluded ${o||"unknown"}`,Ia(s))}async function wm(e,t){let n=await Vn(["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 Kn(s)&&s.databaseId!=null?String(s.databaseId):""}async function bm(e,t,n){let r=await Vn(["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(Kn):[]).find(a=>{let c=String(a.tagName??""),u=new Date(String(a.publishedAt??""));return a.isDraft!==!0&&(!e||Pm(e,c))&&u>=t});return o?gt("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 Vn(e,t){return await new Promise(n=>{let r=Rs("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 _m(e){let t=await _s(e);if(!ws(t))return[];let n=await am(t).catch(()=>[]),r=[];for(let s of n.filter(i=>i.endsWith(".json"))){let i=Zt(t,s),o=Ss(await cm(i,"utf8").catch(()=>"{}")),a=typeof o.pid=="number"?o.pid:0;if(!a||!Om(a)){await $a(i,{force:!0});continue}r.push(o)}return r}async function _s(e){return Zt(await Rm(e),".red","tmp","waits")}async function Rm(e){let t=hs(e);for(;;){if(ws(Zt(t,".red"))||ws(Zt(t,".git")))return t;let n=hs(t,"..");if(n===t)return hs(e);t=n}}async function Xt(e,t,n){await Na(e,JSON.stringify({...t,status:n},null,2),"utf8").catch(()=>{})}async function Sm(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=Rs(e.notifyCmd,{shell:!0,stdio:"ignore",detached:!0});n.once("error",()=>t()),n.once("close",()=>t())})}function Em(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 gt(e,t,n){return{status:e,exitCode:e==="success"?0:1,summary:t,details:n}}function km(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 xm(e){let t=Kn(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 Ia(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 Ss(e){let t=JSON.parse(e);if(!Kn(t))throw new Error("expected JSON object");return t}function Kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tm(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 vm(e){return e.startsWith("SIG")?e:`SIG${e}`}function Ba(e){return e%36e5===0?`${e/36e5}h`:e%6e4===0?`${e/6e4}m`:e%1e3===0?`${e/1e3}s`:`${e}ms`}function Pm(e,t){let n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`).test(t)}function Om(e){try{return process.kill(e,0),!0}catch{return!1}}async function Dm(e){await new Promise(t=>setTimeout(t,e))}var Da,lm,Aa=R(()=>{"use strict";Re();Da={cmd:30*6e4,pr:60*6e4,run:60*6e4,release:2*60*6e4},lm={cmd:"local-cmd:2-5s",pr:"github-pr:15-20s-backoff-jitter",run:"github-run:15-20s-backoff-jitter",release:"release:60s"}});var Ma={};N(Ma,{renderShellInit:()=>Im});function Im(e,t=zt){if(e==="fish")return $m(t);if(e==="bash"||e==="zsh")return Nm(e,t);throw new Error(`unsupported shell: ${e}`)}function $m(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(Yn))].map(n=>` abbr --add --position command -- ${n} '${Lm(`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(`
|
|
66
|
+
`)}function Nm(e,t){let n=Cm(t);return[`# rsp shell-init ${e}`,`# Opt-in only: source this output from ${e} startup files; remove that line to restore raw commands.`,...zn("git",n.get("git")??[]),...zn("gh",n.get("gh")??[]),...zn("vitest",n.get("vitest")??[]),...zn("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(`
|
|
67
|
+
`)}function zn(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(Yn),r=t.map(i=>i.command.slice(1)).filter(i=>i.length>1&&i.every(Yn)),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=>La(o)).join("|");s.push(` ${i}) command rsp ${e} "$@" ;;`)}for(let[i,o]of Bm(r)){let a=o.map(c=>c.map((u,l)=>`[ "$${l+2}" = '${Am(u)}' ]`).join(" && ")).join(" || ");s.push(` ${La(i)}) if ${a}; then command rsp ${e} "$@"; else command ${e} "$@"; fi ;;`)}return s.push(` *) command ${e} "$@" ;;`," esac","}"),s}function Bm(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 Cm(e){let t=new Map;for(let n of e){let r=n.command[0];if(!r||!Yn(r))continue;let s=t.get(r)??[];s.push(n),t.set(r,s)}return t}function Yn(e){return!!(e&&/^[A-Za-z0-9_./:-]+$/.test(e))}function La(e){return e.replace(/[\\|)&;]/g,"\\$&")}function Am(e){return e.replace(/'/g,"'\\''")}function Lm(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}var ja=R(()=>{"use strict";qn()});function Es(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"&&Mm(t.chosenOption)&&jm(t.outcome)&&Um(t.cost)}function Mm(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&t.kind.length>0}function jm(e){return e==="success"||e==="failure"||e==="escalated"}function Um(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 Ua=R(()=>{});import{createHash as Fm}from"node:crypto";function Xa(e,t){return new xs(e,t)}function Fa(e){let t=Number(e.red_entity_id??e.rid),n=Ts(e.properties??e.PROPERTIES),r=Za(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 Ga(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=ec(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:Ts(e.properties??e.PROPERTIES)}}function Jm(e){let t=Number(e.red_entity_id??e.rid),n=Ts(e.properties??e.PROPERTIES);return!Number.isFinite(t)||!Es(n)?null:{rid:t,event:n}}function Ts(e){return e==null?{}:typeof e=="string"?JSON.parse(e):Qn(e)?e:{}}function Za(e){let t=e==="contact"?"person":e;if(Gm.has(t))return t;throw new Error(`invalid Brain artifact kind: ${e}`)}function ec(e){if(qm.has(e))return e;throw new Error(`invalid Brain connection kind: ${e}`)}function Hm(e){return e==="hour"||e==="week"||e==="month"?e:"day"}function qa(e){if(typeof e=="number")return e;let t=String(e??"");return/^\d+$/.test(t)?Number(t):t}function We(e){return Qn(e)?e:{}}function Ja(e,t){return We(e)[t]}function Ha(e,t){let n=e[t];if(typeof n!="string")throw new Error(`brain ${t} must be a string`);return n}function Wa(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Va(e){let t=We(e);return{excludeRids:Array.isArray(t.excludeRids)?t.excludeRids.map(Number).filter(Number.isFinite):void 0}}function L(e){return typeof e=="string"&&e.length>0?e:void 0}function Qn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ks(e){return e!=null}function Wm(e){return Array.from(new Set(e.map(t=>t.trim()).filter(Boolean))).sort()}function Vm(e){return Fm("sha256").update(JSON.stringify(e)).digest("hex")}function Km(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"artifact"}function Ka(e){return`artifact-hash:${e}`}function za(e,t,n){return`connection:${e}:${t}:${n}`}function Ya(){return"model-tier-bandit:v1"}function zm(e){return e.toLowerCase().split(/[^a-z0-9_]+/).map(t=>t.trim()).filter(t=>t.length>1)}function Qa(e,t){let n=0,r=e.indexOf(t);for(;r>=0;)n++,r=e.indexOf(t,r+t.length);return n}function tc(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+Qa(n,a)*3+Qa(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 Ym(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=nc({...tc(a,t),connections:0,vector:0}).total;c>0&&(s+=Math.min(c,12)*.35)}return He(s)}function nc(e){return{...e,lexical:He(e.lexical),tags:He(e.tags),kind:He(e.kind),connections:He(e.connections),vector:He(e.vector),total:He(e.lexical+e.tags+e.kind+e.connections+e.vector)}}function He(e){return Math.round(e*1e3)/1e3}function Qm(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 Xm(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 Zm(e){let t={};for(let n of e)t[n]=(t[n]??0)+1;return t}var se,Gm,qm,xs,rc=R(()=>{"use strict";Ua();se={artifacts:"brain_artifacts",connections:"brain_connections",outcomeEvents:"brain_outcome_events",kv:"brain_kv"},Gm=new Set(["pillar","decision","concept","question","playbook","task","event","pattern","hypothesis","fact","source","bookmark","note","reference","custom","project","idea","meeting","claim","organization","person"]),qm=new Set(["supports","contradicts","depends_on","derived_from","related_to","part_of","preceded_by","followed_by","authored","tagged"]),xs=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(We(n));if(t==="getArtifact")return await this.getArtifact(Ja(n,"ridOrId"));if(t==="listArtifacts")return await this.listArtifacts();if(t==="search"){let r=We(n);return await this.search(Ha(r,"query"),Wa(r,"limit")??10,Va(r.options))}if(t==="think"){let r=We(n);return await this.think(Ha(r,"query"),Wa(r,"limit")??8,Va(r.options))}if(t==="link")return await this.link(We(n));if(t==="backlinks")return await this.backlinks(Ja(n,"target"));if(t==="listConnections")return await this.listConnections();if(t==="eventKpis")return await this.eventKpis(We(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 ${se.artifacts}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${se.connections}`),await this.db.execute(`CREATE GRAPH IF NOT EXISTS ${se.outcomeEvents}`)}async status(){let t=await this.listArtifacts(),n=await this.listConnections();return{uri:this.uri,artifacts:t.length,connections:n.length,kinds:Zm(t.map(r=>r.kind))}}async capture(t){let n=L(t.title)||"Untitled artifact",r=L(t.content);if(!r)throw new Error("brain capture requires content");let s=Za(L(t.kind)||"note"),i=Wm(Array.isArray(t.tags)?t.tags.map(String):[]),o=Date.now(),a=Vm([s,n,r,i,L(t.sourcePath),L(t.sourceSession)]),c=await this.kv().get(Ka(a));if(c!=null){let g=await this.getArtifact(Number(c));if(g)return g}let u=`${Km(n)}-${a.slice(0,8)}`,l={id:u,title:n,content:r,tags:i,source_agent:L(t.sourceAgent),source_runner:L(t.sourceRunner),source_session:L(t.sourceSession),source_path:L(t.sourcePath),created_at:o,updated_at:o,hash:a,metadata:Qn(t.metadata)?t.metadata:void 0},f=(await this.db.query(`INSERT INTO ${se.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=Fa(f);if(!y)throw new Error("INSERT artifact returned invalid row");return await this.kv().put(Ka(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 ${se.artifacts}`)).rows.map(Fa).filter(ks)}async search(t,n,r={}){let s=zm(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=tc(u,s),d=nc({...l,connections:Ym(u,s,a,c),vector:0});return{artifact:u,score:d.total,score_breakdown:d,excerpt:Qm(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 Xm(t,s)}async link(t){let n=await this.getArtifact(qa(t.from)),r=await this.getArtifact(qa(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=ec(L(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:L(t.reason),confidence:L(t.confidence)||"explicit",created_at:Date.now(),metadata:Qn(t.metadata)?t.metadata:void 0},c=(await this.db.query(`INSERT INTO ${se.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=Ga(c);if(!u)throw new Error("INSERT connection returned invalid row");return await this.kv().put(za(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 ${se.connections}`)).rows.map(Ga).filter(ks)}async eventKpis(t){let n=(await this.listArtifacts()).filter(i=>i.kind==="event"),r=Hm(L(t.interval)||"day"),s=L(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(!Es(t))throw new Error("invalid Brain outcome event");if(!(await this.db.query(`INSERT INTO ${se.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 ${se.outcomeEvents}`)).rows.map(Jm).filter(ks).sort((n,r)=>n.rid-r.rid).map(({event:n})=>n)}async loadModelTierBanditDocument(){let t=await this.kv().get(Ya());return typeof t=="string"?JSON.parse(t):t}async saveModelTierBanditDocument(t){return await this.kv().put(Ya(),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(za(t,n,r));return s!=null?Number(s):null}kv(){return this.db.kv(se.kv)}}});var hc={};N(hc,{runResidentServer:()=>ap});import{randomUUID as ht}from"node:crypto";import{execFileSync as ep,spawn as tp}from"node:child_process";import{existsSync as np}from"node:fs";import{mkdir as lc,rename as rp,rm as sc,writeFile as dc}from"node:fs/promises";import{createServer as sp}from"node:net";import{dirname as Ds,join as en}from"node:path";import{fileURLToPath as ip,pathToFileURL as op}from"node:url";async function ap(e){await lc(Ds(e.socketPath),{recursive:!0});let t=_p();bp();let n=e.telemetryDrainTimeoutMs??fc,r={kind:"opening",startedAt:process.hrtime.bigint()},s,i=!1,o=e.idleMs??xn,a,c,u=!1,l=new Set,d=e.telemetryDrainIntervalMs??3e4,f=sp(x=>{l.add(x),x.once("close",()=>l.delete(x)),g(),vp(x,async P=>{g();let B=await Pp(r,P,e.storeUri,e.residentVersion??"0.0.0-dev"),j={id:P.id,ok:!0,value:B,storeOpenCount:r.kind==="ready"?r.storeOpenCount:void 0,storeElapsedMs:r.kind==="ready"?r.storeElapsedMs:void 0};gc(x,j),P.op==="handover"&&setImmediate(()=>y())})});function y(){i=!0,u=!0,c=wp(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 P=()=>{Xn(),f.close();for(let B of l)B.destroy();setTimeout(()=>process.exit(0),1e3)};return process.once(x,P),{signal:x,handler:P}});await new Promise((x,P)=>{f.once("error",P),f.listen(e.socketPath,()=>{f.off("error",P),x()})}),(async()=>{let x=process.hrtime.bigint();process.env.RSP_TEST_HANG_RESIDENT_STORE_OPEN==="1"&&await new Promise(()=>{});let P=Number(process.env.RSP_TEST_DELAY_RESIDENT_STORE_OPEN_MS??"0");Number.isFinite(P)&&P>0&&await new Promise($=>setTimeout($,P));let B=await Ut.open({uri:e.storeUri,ttlDays:e.ttlDays,ephemeralTtlHours:e.ephemeralTtlHours,byteBudget:e.byteBudget,allowResidentOpen:!0}),j=Number(process.hrtime.bigint()-x)/1e6,V=new Os(B,{rootDir:e.rootDir??process.cwd(),ttlDays:e.telemetryTtlDays??En,byteBudget:e.telemetryByteBudget??e.byteBudget??kn});if(i){await B.close();return}if(await vs(V,n),i){await B.close();return}r={kind:"ready",store:B,telemetry:V,storeOpenCount:1,storeElapsedMs:j},s=setInterval(()=>{let $=r.kind==="ready"?r:void 0;$&&vs($.telemetry,n)},d),s.unref(),g()})().catch(x=>{r={kind:"failed",error:x instanceof Error?x:new Error(String(x))},g()}),e.pidPath&&await dc(e.pidPath,`${process.pid}
|
|
68
|
+
`,{encoding:"utf8",mode:384});let k=e.residentVersion??"0.0.0-dev",w=e.registryPath??en(e.rootDir??process.cwd(),".red","tmp","rsp-resident.pid.json");try{await bn(w,{socket_path:e.socketPath,store_uri:e.storeUri,resident_version:k})}catch{}await new Promise(x=>f.once("close",x)),a&&clearTimeout(a),s&&clearInterval(s),await sc(e.socketPath,{force:!0});let T=r;T.kind==="ready"&&(await vs(T.telemetry,n,u),await T.store.close()),c&&clearTimeout(c);for(let{signal:x,handler:P}of p)process.off(x,P);t?.kill("SIGTERM"),Xn(),e.pidPath&&await sc(e.pidPath,{force:!0}),await _n(w)}async function mp(e,t,n=new Date){let r=await Cn(e,1,n),s=n.toISOString().slice(0,10),i=r.savings.daily_tokens_saved.find(u=>u.date===s)?.tokens_saved??0,o=r.savings.tokens_saved>0?i/r.savings.tokens_saved*r.savings.dollars_saved_estimate_usd:0,a=en(t,dp),c=`${a}.${process.pid}.${Date.now()}.tmp`;await lc(Ds(a),{recursive:!0}),await dc(c,JSON.stringify({version:1,tokens_saved_today:i,dollars_saved_today_usd:Math.round(o*1e6)/1e6,show_total_today:r.health.show_total,show_hit_rate:r.health.show_total>0?r.health.show_hit_rate:void 0,decisions:r.decisions.seen>0?{seen:r.decisions.seen,contributed:r.decisions.contributed}:void 0,updated_at:n.toISOString()}),{encoding:"utf8",mode:384}),await rp(c,a)}async function vs(e,t=fc,n=!1){try{n&&process.env.RSP_TEST_HANG_TELEMETRY_DRAIN==="1"&&await new Promise(()=>{}),await pc(e.drainAndSweep(),t,"telemetry drain timed out")}catch(r){process.stderr.write(`rsp resident: telemetry drain failed: ${r instanceof Error?r.message:String(r)}
|
|
69
|
+
`)}}async function pp(e){let t=[];for(let n of fp){let r=await gp(e,n);r.ok||(r.previousModel&&(r.previousModel!=="collection"&&await hp(e,n,r.previousModel),t.push({collection:n,previousModel:r.previousModel})),await e.query(`CREATE KV IF NOT EXISTS ${mc(n)}`))}return t}async function gp(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 hp(e,t,n){let r=yp(n);if(!r)throw new Error(`cannot self-heal telemetry collection ${t}: unsupported model ${n}`);await e.query(`DROP ${r} ${mc(t)}`)}function yp(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 mc(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`invalid telemetry collection name: ${e}`);return e}function wp(e){return e&&clearTimeout(e),setTimeout(()=>{Xn(),process.exit(0)},lp)}function bp(){ic||(ic=!0,process.on("exit",()=>Xn()))}function _p(){if(process.platform==="win32")return;let t=tp(process.execPath,["-e",`
|
|
59
70
|
const { execFileSync } = require("node:child_process");
|
|
60
71
|
const parentPid = Number(process.argv[1]);
|
|
61
72
|
const known = new Set();
|
|
@@ -96,64 +107,64 @@ const timer = setInterval(() => {
|
|
|
96
107
|
clearInterval(timer);
|
|
97
108
|
process.exit(0);
|
|
98
109
|
}, 500);
|
|
99
|
-
`,String(process.pid)],{detached:!0,stdio:"ignore"});return t.unref(),t}function
|
|
100
|
-
`);if(
|
|
101
|
-
`)}catch{}}async function
|
|
102
|
-
`),n(127)}),t.on("close",(r,
|
|
103
|
-
`).filter(
|
|
110
|
+
`,String(process.pid)],{detached:!0,stdio:"ignore"});return t.unref(),t}function Xn(){for(let e of Rp())try{process.kill(e,"SIGTERM")}catch{}}function Rp(){if(process.platform==="win32")return[];let e="";try{e=ep("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 Sp(e){if(e.collection!==re)return e;let t=await oc(e.raw_text,cc(e.raw_bytes)),n=await oc(e.emitted_text,cc(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 oc(e,t){if(typeof e=="string"){let n=Buffer.byteLength(e,"utf8");if(n<=cp)try{return await pc((async()=>({tokens:(await Ep())("cl100k_base").encode(e).length,estimated:!1}))(),up,"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 Ep(){return ac??=import(op(kp()).href).then(e=>{let t=e.getEncoding;if(!t)throw new Error("js-tiktoken getEncoding export not found");return t}),await ac}function kp(){let e=Ds(ip(import.meta.url)),n=[en(e,"..","node_modules","js-tiktoken","dist","index.js"),en(e,"..","apps","rsp","node_modules","js-tiktoken","dist","index.js")].find(r=>np(r));if(!n)throw new Error("js-tiktoken dependency not found");return n}function cc(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function M(e){return typeof e=="string"&&e.trim()!==""?e:void 0}function Ps(e){return e.trim().split(/\s+/).filter(Boolean)[0]??"unknown"}async function pc(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 xp(e){try{return JSON.parse(e)}catch{return e}}function Tp(e){return uc(e)&&e.version===1&&Array.isArray(e.records)&&e.records.every(t=>uc(t)&&(t.collection===H||t.collection===W||t.collection===re||t.collection===xe)&&typeof t.key=="string"&&typeof t.created_at=="string"&&typeof t.expires_at=="string"&&typeof t.bytes=="number")}function uc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vp(e,t){let n="";e.setEncoding("utf8"),e.on("error",()=>{}),e.on("data",r=>{n+=r;let s=n.indexOf(`
|
|
111
|
+
`);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??ht(),ok:!1,error:a instanceof Error?a.message:String(a)};gc(e,u)}finally{e.end()}})()})}function gc(e,t){if(!(e.destroyed||!e.writable))try{e.write(`${JSON.stringify(t)}
|
|
112
|
+
`)}catch{}}async function Pp(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 rs(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 Cn(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 ss(i,t.sinceDays)}if(t.op==="mint")return{handle:await s.mint(Buffer.from(t.original,"base64"),t.meta)};if(t.op==="get")return Dp(await s.get(t.handle));if(t.op==="memory")return await s.memory(t.action,t.payload);if(t.op==="brain")return await Op(s,n,t.action,t.payload);throw new Error(`unsupported resident op: ${t.op??"unknown"}`)}async function Op(e,t,n,r){let s=e.redDb();if(!s)throw new Error("resident brain operations require the shared RedDB store");return await Xa(s,t).request(n,r)}function Dp(e){return e?"status"in e?e:{...e,original:e.original.toString("base64"),original_encoding:"base64"}:null}var cp,up,fc,lp,dp,fp,Os,ic,ac,yc=R(()=>{"use strict";Rn();Ge();rc();Te();ne();cp=256*1024,up=500,fc=2e3,lp=Math.max(1,Number(process.env.RSP_TEST_IDLE_SHUTDOWN_WATCHDOG_MS??"10000")),dp=en(".red","tmp","rsp-status-summary.json"),fp=[H,W,re,xe,Ht],Os=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 pp(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 ts(this.opts.rootDir,async a=>{let c=ns(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:M(c.command)||"unknown",source_id:M(c.id),source_collection:M(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 mp(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:ht(),a={...await Sp(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===H?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===H||n.accounting_recorded===!0?null:n.collection===re?await this.writeEvent(t,{collection:H,id:`mirror:${M(n.id)||ht()}`,created_at:M(n.created_at)||M(n.ts)||new Date().toISOString(),event_type:"invocation",command:M(n.command)||"unknown",command_class:Ps(M(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===xe?await this.writeEvent(t,{collection:H,id:`mirror:${M(n.id)||ht()}`,created_at:M(n.created_at)||M(n.ts)||new Date().toISOString(),event_type:"invocation",command:M(n.command)||"unknown",command_class:Ps(M(n.command)||"unknown"),loss:"lossless",raw_bytes:0,emitted_bytes:0,degradation_reason:M(n.reason)||"unknown"}):null}async writeDrainDegradation(t,n){let r=await this.writeEvent(t,{collection:xe,id:ht(),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:H,id:`mirror:${ht()}`,created_at:r.created_at,event_type:"invocation",command:n.command,command_class:Ps(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(Ht).get("index:v1"),r=typeof n=="string"?xp(n):n;return Tp(r)?r:{version:1,records:[]}}async writeIndex(t,n){await t.kv(Ht).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})}};ic=!1});var Ns={};N(Ns,{parseProxyCommandLine:()=>Rc,rewriteProxyCommandLine:()=>_c,runProxy:()=>$p});import{spawn as Ip}from"node:child_process";async function $p(e,t){let n="",r="",s=[],i=process.hrtime.bigint();try{if(n=Rc(e),process.env.RSP_PROXY_FAIL_INTERNAL==="1")throw new Error("forced proxy failure");let c=_c(n,t.level??"lossless");r=c.commandLine,s=c.matches}catch(c){if(n)return await Np(t.telemetryRoot,n,c),await wc(n);throw c}for(let c of s)await Bp(t.telemetryRoot,c);let o=await wc(r||n),a=Number(process.hrtime.bigint()-i)/1e6;return await Je(t.telemetryRoot,{collection:re,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 _c(e,t="lossless"){let n=Up(e),r=[];return{commandLine:n.map((i,o)=>{if(i.kind==="operator"||jp(n,o)==="|")return i.text;let a=Cp(i.text,t);return a?(r.push(a.match),a.text):i.text}).join(""),matches:r}}function Rc(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 Np(e,t,n){await Je(e,{collection:W,event_type:"decision",ts:new Date().toISOString(),hook:"proxy",command:t,command_family:$s(t),decision:"failed-open",reason:"proxy-internal-error",error:n instanceof Error?n.name:typeof n})}async function Bp(e,t){await Je(e,{collection:W,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 wc(e){let t=Ip(e,{shell:!0,stdio:"inherit"});return await new Promise(n=>{t.on("error",r=>{process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
113
|
+
`),n(127)}),t.on("close",(r,s)=>{if(s){process.kill(process.pid,s),n(128);return}n(r??0)})})}function Cp(e,t){let n=e.match(/^\s*/)?.[0]??"",r=e.match(/\s*$/)?.[0]??"",s=e.trim();if(!s)return null;let i=Gp(s);if(!i)return null;let o=Mp(i);if(o>=i.length)return null;let a=i.slice(o),c=a.map(y=>y.value);if(Zn(c))return{text:e,match:{command:a.map(y=>y.raw).join(" "),commandFamily:$s(c.join(" ")),decision:"passed",reason:"lossless-gh-json-jq"}};let u=Ap(a);if(!u)return null;let l=i.slice(0,o).map(y=>y.raw),d=t==="lossless"?[]:[`--${t}`],f=[...l,"rsp",...d,...u.wrapperWords].join(" ");return{text:`${n}${f}${r}`,match:{command:a.map(y=>y.raw).join(" "),commandFamily:$s(c.join(" ")),decision:"contributed",reason:"proxy-segment",capabilityId:u.capabilityId}}}function Ap(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}:Lp(t,n)}function Lp(e,t){return e[0]==="cat"&&e.length===2&&Is(e[1])?{capabilityId:"cat:file",wrapperWords:["cat",t[1]]}:(e[0]==="head"||e[0]==="tail")&&e.length===2&&Is(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])&&Is(e[3])?{capabilityId:`cat:${e[0]}`,wrapperWords:["cat",`--${e[0]}`,e[2],t[3]]}:null}function Is(e){return!!e&&!e.startsWith("-")}function Mp(e){let t=0;for(;t<e.length&&bc(e[t].value);)t+=1;if(e[t]?.value!=="env")return t;for(t+=1;t<e.length&&bc(e[t].value);)t+=1;return t}function jp(e,t){for(let n=t+1;n<e.length;n+=1)if(e[n].kind==="operator")return e[n].text}function Up(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=Fp(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 Fp(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 Gp(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 $s(e){let t=e.trim().split(/\s+/).filter(Boolean);return t.length===0?"unknown":t[0]==="git"&&t[1]?`git ${t[1]}`:Zn(t)&&t[1]&&t[2]?`gh ${t[1]} ${t[2]} json-jq`:Zn(t)&&t[1]?`gh ${t[1]} json-jq`:Zn(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 Zn(e){return e[0]==="gh"&&e.some(qp)}function qp(e){return e==="--json"||e==="--jq"||e.startsWith("--json=")||e.startsWith("--jq=")}function bc(e){return/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e)}var Bs=R(()=>{"use strict";Te()});function Pe(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 Sc(e,t){if(!t)return!0;let n=Cs(e).toLowerCase();return t.toLowerCase().split(/\s+/).filter(Boolean).every(r=>n.includes(r))}function A(e,t){return t?e.filter(n=>Sc(n,t)):[...e]}function yt(e,t){if(!t)return e;let r=e.split(`
|
|
114
|
+
`).filter(s=>s&&Sc(s,t));return r.length>0?`${r.join(`
|
|
104
115
|
`)}
|
|
105
|
-
`:""}function
|
|
106
|
-
`)return{stdout:Buffer.from(
|
|
107
|
-
`;return{stdout:Buffer.from(`${
|
|
108
|
-
${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
|
|
109
|
-
`;let
|
|
110
|
-
`)[0]??"",r=/^\[([^ ]+) ([0-9a-f]+)\] (.+)$/.exec(n),
|
|
111
|
-
`).filter(Boolean),r=n.find(c=>c.startsWith("To "))?.slice(3)??"",
|
|
112
|
-
`),
|
|
113
|
-
`).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??""}}),
|
|
114
|
-
`)){let
|
|
115
|
-
`).length:0,files:
|
|
116
|
-
`;return{stdout:Buffer.from(`${
|
|
117
|
-
${
|
|
116
|
+
`:""}function Oe(e,t){let n=t.filter(Boolean);return n.length===0?e:{...e,help:n}}function Cs(e){return Array.isArray(e)?e.map(Cs).join(" "):typeof e=="object"&&e!==null?Object.values(e).map(Cs).join(" "):String(e??"")}var er=R(()=>{"use strict"});var As={};N(As,{DEFAULT_RSP_HEAVY_GIT_BYTE_THRESHOLD:()=>de,GIT_LOG_MACHINE_FIELDS:()=>Ec,recoveryInstruction:()=>Q,renderGitContract:()=>kc,runGitWrapper:()=>Hp});import{spawn as Jp}from"node:child_process";async function Hp(e,t){let n=xc(e),r=Tc(n.argv),s=await zp(r,n.argv.slice(1));return kc(e,s,t)}async function kc(e,t,n){let r=xc(e);if((t.status??0)!==0||t.signal)return{stdout:Buffer.from(yt(t.stdout,r.query)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let s=Tc(r.argv),i=Yp(s,r.argv,t.stdout,r.query);if(i===`git empty
|
|
117
|
+
`)return{stdout:Buffer.from(i),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let o=v(i);if(Wp(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=ag(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 ${Q(u)}
|
|
118
|
+
`;return{stdout:Buffer.from(`${v(a.payload)}
|
|
119
|
+
${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 Q(e){return e.startsWith("el:")?`rsp show ${e}`:e}function xc(e){let t=Pe(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 Wp(e,t,n,r){if(r.level==="terse")return!1;if(n||r.level==="full"||!Vp(e)||r.level!=="lossless")return!0;let s=og(r.heavyGitByteThreshold,de);return Buffer.byteLength(t)<=s}function Vp(e){return e==="diff"||e==="log"||e==="blame"||e==="show"}function Tc(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 Kp(e,t){let n=t.slice(1);switch(e){case"status":return["status","--porcelain=v2","-z","-b",...n];case"log":return["log",`--format=%x1e${Ec.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 zp(e,t){let n=Jp("git",Kp(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 Yp(e,t,n,r){switch(e){case"status":return Qp(t,n,r);case"log":return Xp(t,n,r);case"diff":return Zp(t,n,r);case"commit":return De(eg(t,n),r,["rsp git status --query <path-or-state>"]);case"push":return De(tg(t,n),r,["rsp gh pr list --query <branch>"]);case"blame":return ng(t,n,r);case"branch":return rg(t,n,r);case"show":return sg(t,n,r)}}function Qp(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:ig(u)})}if(s.length===0)return`git empty
|
|
120
|
+
`;let i=A(s,n),o=vc(i,"state");return De({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 Xp(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=A(r,n);return De({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 Zp(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=A(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 De({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 eg(e,t){let n=t.split(`
|
|
121
|
+
`)[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 tg(e,t){let n=t.split(`
|
|
122
|
+
`).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,y]=(l??"").split(":");return{flag:u??"",from:f??"",to:y??"",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 ng(e,t,n){let r=t.split(`
|
|
123
|
+
`),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=A(s,n),a=vc(o,"author");return De({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 rg(e,t,n){let r=t.split(`
|
|
124
|
+
`).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=A(r,n),i=s.find(o=>o.current)?.name??"";return De({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 sg(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(""),y=[];for(let w of o.split(`
|
|
125
|
+
`)){let T=/^\s*(.+?)\s+\|\s+(\d+)\s+([+\-]+|Bin.*)$/.exec(w);if(!T)continue;let x=T[3]??"";y.push({path:(T[1]??"").trim(),changed:Number(T[2]??0),added:[...x].filter(P=>P==="+").length,deleted:[...x].filter(P=>P==="-").length,binary:x.startsWith("Bin")})}let g=A(y,n),m=0,p=0,k=0;for(let w of g)m+=typeof w.changed=="number"?w.changed:0,p+=typeof w.added=="number"?w.added:0,k+=typeof w.deleted=="number"?w.deleted:0;return De({command:e.join(" "),commit:a??"",short:c??"",author:u??"",date:l??"",subject:d??"",body_lines:f.trim()?f.trim().split(`
|
|
126
|
+
`).length:0,files:g,summary:`${n?`${g.length}/${y.length}`:g.length} files, ${m} changed, +${p} -${k}`},n,["rsp git blame --query <author-or-path>","rsp git diff --query <path>"])}function De(e,t,n){return t?Oe(e,n):e}function ig(e){return e.includes("A")?"added":e.includes("D")?"deleted":e.includes("R")?"renamed":e.includes("M")?"modified":"changed"}function vc(e,t){let n={};for(let r of e){let s=String(r[t]??"");n[s]=(n[s]??0)+1}return n}function og(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function ag(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 Ec,Ve=R(()=>{"use strict";Re();ne();er();ne();Ec=["%h","%an","%as","%s"]});var Us={};N(Us,{renderGhContract:()=>Dc,runGhWrapper:()=>dg});import{spawn as Oc}from"node:child_process";async function dg(e,t){let n=Ic(e),r=await mg(n);return Dc(e,r,t)}async function Dc(e,t,n){let r=Pe(e);if((t.status??0)!==0||t.signal)return{stdout:Buffer.from(yt(t.stdout,r.query)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal};let s=Ic(e),i=tr(t.stdout),o=gg(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=Sg(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=v(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=Eg(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 y=`\u2026 elided ${l.rowsElided} rows (+${d}) \u2014 ${Q(f)}
|
|
127
|
+
`;return{stdout:Buffer.from(`${v(l.payload)}
|
|
128
|
+
${y}`),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 Ic(e){let t=Pe(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 fg(e){if(e.action==="combined")throw new Error("combined gh command uses multiple machine calls");let t=`${e.kind}:${e.action}`,n=e.wide?ug[t]:cg[t];return[e.kind,e.action,...e.passthrough,"--json",n.join(",")]}async function mg(e){if(e.action==="combined")return await pg(e);let t=Oc("gh",fg(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 pg(e){let t=e.target??"",n=["number","title","state","body","author","labels","url","baseRefName","headRefName"],r=["comments"],[s,i,o]=await Promise.all([Ls(["pr","view",t,"--json",n.join(",")]),Ls(["pr","checks",t,"--json","name,state,bucket,conclusion,link,startedAt,completedAt,workflow"]),Ls(["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:tr(s.stdout),checks:tr(i.stdout),comments:tr(o.stdout)}),stderr:[s.stderr,i.stderr,o.stderr].filter(Boolean).join(""),status:0,signal:null}}async function Ls(e){let t=Oc("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 gg(e,t,n){if(e.action==="list"&&Array.isArray(n)&&n.length===0)return bg(e.kind);let r={command:t.join(" ")};switch(`${e.kind}:${e.action}`){case"pr:list":{let s=bt(n).map(o=>$c(o,e.wide)),i=A(s,e.query);return wt({...r,prs:i,summary:`${Ms(i.length,s.length,e.query)} ${Pc(i,"open")} PRs`},e,["rsp gh pr <number>","rsp gh pr list --query <title-or-label>"])}case"pr:view":return wt({...r,pr:Nc(ie(n),e),summary:`PR #${Ke(ie(n),"number")}`},e,["rsp gh pr <number>","rsp gh pr view <number> --full"]);case"pr:combined":return hg(e,t,ie(n));case"issue:list":{let s=bt(n).map(o=>Bc(o,e.wide)),i=A(s,e.query);return wt({...r,issues:i,summary:`${Ms(i.length,s.length,e.query)} ${Pc(i,"open")} issues`},e,["rsp gh issue view <number>","rsp gh issue list --query <label-or-title>"])}case"issue:view":return wt({...r,issue:_g(ie(n),e),summary:`issue #${Ke(ie(n),"number")}`},e,["rsp gh issue view <number> --full"]);case"run:list":{let s=bt(n).map(o=>Cc(o,e.wide)),i=A(s,e.query);return wt({...r,runs:i,summary:`${Ms(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 wt({...r,run:Rg(ie(n),e),summary:`run ${Ke(ie(n),"databaseId")}`},e,["rsp gh run view <id> --full"])}throw new Error(`unsupported gh command: ${e.kind} ${e.action}`)}function hg(e,t,n){let r=Nc(ie(n.view),{...e,action:"view",wide:!0}),s=A(bt(n.checks).map(yg),e.query),i=ie(n.comments).comments,o=A(bt(i).map(wg).slice(-3),e.query);return Oe({command:t.join(" "),pr:r,checks:s,comments:o,summary:`PR #${Ke(ie(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 yg(e){return{name:O(e,"name"),state:tn(e),bucket:O(e,"bucket"),conclusion:O(e,"conclusion"),workflow:O(e,"workflow"),link:O(e,"link")}}function wg(e){return{author:Mc(e.author),body:nr(e,"body",js,!1),created:O(e,"createdAt")}}function bg(e){return e==="pr"?`0 open PRs \u2014 try: rsp gh issue list
|
|
118
129
|
`:e==="issue"?`0 open issues \u2014 try: rsp gh issue list --state all
|
|
119
130
|
`:`0 runs \u2014 try: rsp gh run list --limit 20
|
|
120
|
-
`}function
|
|
121
|
-
${
|
|
131
|
+
`}function $c(e,t){let n={number:Ke(e,"number"),title:O(e,"title"),state:tn(e),draft:!!e.isDraft};return t&&Object.assign(n,Ac(e)),n}function Nc(e,t){let n=$c(e,t.wide);return n.body=nr(e,"body",js,t.full),t.wide&&(n.base=O(e,"baseRefName"),n.head=O(e,"headRefName")),n}function Bc(e,t){let n={number:Ke(e,"number"),title:O(e,"title"),state:tn(e),labels:Lc(e.labels)};return t&&Object.assign(n,Ac(e)),n}function _g(e,t){let n=Bc(e,t.wide);return n.body=nr(e,"body",js,t.full),n}function Cc(e,t){let n={id:Ke(e,"databaseId"),name:O(e,"name"),status:tn(e),conclusion:O(e,"conclusion")};return t&&(n.event=O(e,"event"),n.branch=O(e,"headBranch"),n.workflow=O(e,"workflowName"),n.created=O(e,"createdAt")),n}function Rg(e,t){let n=Cc(e,t.wide),r=bt(e.jobs).map(s=>({name:O(s,"name"),status:tn(s),conclusion:O(s,"conclusion"),log:nr(s,"log",lg,t.full)}));return n.jobs=r,n}function nr(e,t,n,r){let s=O(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 Sg(e){let t=[e];for(;t.length>0;){let n=t.pop();if(Array.isArray(n))t.push(...n);else if(_t(n)){if(_t(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 Eg(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 Pc(e,t){return e.every(n=>n.state===t)?t:"returned"}function Ms(e,t,n){return n?`${e}/${t}`:String(e)}function wt(e,t,n){return t.query?Oe(e,n):e}function tn(e){return(O(e,"state")||O(e,"status")).toLowerCase()}function Ac(e){return{author:Mc(e.author),labels:Lc(e.labels),url:O(e,"url"),updated:O(e,"updatedAt")}}function Lc(e){return Array.isArray(e)?e.map(t=>_t(t)?O(t,"name"):String(t)).filter(Boolean):[]}function Mc(e){return _t(e)?O(e,"login"):""}function tr(e){return e.trim()?JSON.parse(e):null}function bt(e){return Array.isArray(e)?e.filter(_t):[]}function ie(e){return _t(e)?e:{}}function O(e,t){let n=e[t];return typeof n=="string"?n:""}function Ke(e,t){let n=e[t];return typeof n=="number"?n:0}function _t(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var cg,ug,js,lg,Fs=R(()=>{"use strict";Re();Ve();er();cg={"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"]},ug={"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"]},js=160,lg=160});var qs={};N(qs,{renderTestContract:()=>jc,runTestWrapper:()=>Pg});import{spawn as kg}from"node:child_process";async function Pg(e,t){let n=Pe(e),r=await Ng(n.argv);return await jc(e,r,t)}async function jc(e,t,n){let r=Pe(e),i=Uc(r.argv)==="vitest"?Bg(t.stdout):Cg(t.stdout),o=t.status;if(!i||(o??0)!==0&&i.failed===0)return{stdout:Buffer.from(yt(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 ${Mg(i.durationSeconds)}`,c=A(i.failures,r.query);if(n.level==="terse")return await Og(r.argv,t,{...i,failures:c},o,a,n,r.query);let u=[],l,d=0;for(let g of c){let m=await Ag(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 y=r.query?Oe(f,["rsp show <handle>","rsp vitest --query <suite-or-test>"]):f;return{stdout:Buffer.from(v(y)),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:y,mintedHandle:l,bytesElided:d>0?d:void 0,rowsElided:u.length>0?Math.max(0,i.total-u.length):void 0}}async function Og(e,t,n,r,s,i,o){let a=Dg(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?Oe(c,["rsp show <handle>","rsp vitest --query <suite-or-test>"]):c,l=v(u),d=Math.max(0,n.failures.length-a.length),f=a.some((T,x)=>T.excerpt!==n.failures[x].excerpt);if(d===0&&!f)return{stdout:Buffer.from(l),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:u};let y={exit_code:r,summary:s};n.failures.length>0&&(y.failures=n.failures.map(T=>({suite:T.suite,name:T.name,excerpt:T.excerpt})));let g=v(y),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 w=`\u2026 elided ${d>0?`${d} failures`:"full detail"} (+${m}) \u2014 ${Q(p)}`;return{stdout:Buffer.from(`${l}
|
|
132
|
+
${w}`),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,payload:u,mintedHandle:p,bytesElided:m,rowsElided:d,rawOutput:Buffer.from(g)}}function Dg(e){let t=[],n=Tg;for(let r of e.slice(0,vg)){let s=Ig(r.excerpt,Math.min(xg,n));n=Math.max(0,n-Buffer.byteLength(s)),t.push({suite:r.suite,name:r.name,excerpt:s})}return t}function Ig(e,t){if(t<=0)return"";let n=e.split(`
|
|
122
133
|
`),r=n.length<=2?e:`${n[0]}
|
|
123
134
|
\u2026
|
|
124
|
-
${n[n.length-1]}`,
|
|
125
|
-
`).filter(Boolean).map(c=>
|
|
126
|
-
`)}),
|
|
127
|
-
\u2026 elided ${o} bytes (+${r.length}) \u2014 ${
|
|
128
|
-
`):""}function
|
|
129
|
-
`;if(!o&&Buffer.byteLength(c)<=
|
|
130
|
-
`;return{stdout:Buffer.from(`${c}${l}`),stderr:Buffer.alloc(0),status:0,signal:null,payload:a,mintedHandle:u,bytesElided:n.length,rawOutput:n}}function
|
|
131
|
-
`),r=n.at(-1)==="",
|
|
135
|
+
${n[n.length-1]}`,s=Buffer.from(r);return s.length<=t?r:s.subarray(0,t).toString("utf8").replace(/�$/,"")}function Uc(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 $g(e){if(Uc(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 Ng(e){let t=$g(e),n=kg(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 Bg(e){let t=Fc(e);if(!Ie(t))return null;let n=Array.isArray(t.testResults)?t.testResults:[],r=[],s=$e(t.numTotalTests),i=$e(t.numFailedTests),o=jg($e(t.startTime),$e(t.endTime));for(let a of n){if(!Ie(a))continue;let c=oe(a.name)||oe(a.file)||"",u=Array.isArray(a.assertionResults)?a.assertionResults:[];for(let l of u)Ie(l)&&l.status==="failed"&&r.push({suite:c,name:oe(l.fullName)||oe(l.title)||oe(l.name),excerpt:Lg(l.failureMessages)||oe(l.failureMessage)})}return s||=n.reduce((a,c)=>!Ie(c)||!Array.isArray(c.assertionResults)?a:a+c.assertionResults.length,0),i||=r.length,o||=n.reduce((a,c)=>Ie(c)?a+$e(c.perfStats&&Ie(c.perfStats)?c.perfStats.runtime:c.duration)/1e3:a,0),{failed:i,total:s,suites:n.length||1,durationSeconds:o,failures:r}}function Cg(e){let t=e.split(`
|
|
136
|
+
`).filter(Boolean).map(c=>Fc(c)).filter(Ie);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+=$e(c.test_count)),(c.event==="failed"||c.event==="ok")&&(s+=$e(c.failed),o+=$e(c.exec_time));continue}if(c.type==="test"&&c.event==="failed"){n.push({suite:oe(c.name).split("::").slice(0,-1).join("::"),name:oe(c.name),excerpt:oe(c.stdout)});continue}if(c.reason==="compiler-message"&&Ie(c.message)){let u=oe(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(`
|
|
137
|
+
`)}),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 Ag(e,t,n){let r=Buffer.from(e);if(r.length<=Gs)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,Gs).toString("utf8").replace(/\uFFFD$/,""),o=r.length-Buffer.byteLength(i);return{text:`${i}
|
|
138
|
+
\u2026 elided ${o} bytes (+${r.length}) \u2014 ${Q(s)}`,handle:s,bytesElided:r.length}}function Fc(e){try{return JSON.parse(e)}catch{return null}}function Lg(e){return Array.isArray(e)?e.map(t=>String(t)).filter(Boolean).join(`
|
|
139
|
+
`):""}function Mg(e){return`${Number(e.toFixed(1))}s`}function jg(e,t){return e>0&&t>e?(t-e)/1e3:0}function $e(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function oe(e){return typeof e=="string"?e:""}function Ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Gs,xg,Tg,vg,Js=R(()=>{"use strict";Re();Ve();er();Gs=320,xg=160,Tg=Gs,vg=3});var Vs={};N(Vs,{parseCatCommand:()=>Ws,renderCatContract:()=>Vg,runCatWrapper:()=>Wg});import{isUtf8 as Ug}from"node:buffer";import{readFile as Fg}from"node:fs/promises";import{extname as Gg}from"node:path";async function Wg(e,t){let n=Ws(e),r=await Fg(n.file);return Vc(r)?{stdout:r,stderr:Buffer.alloc(0),status:0,signal:null,rawOutput:r}:await Wc(e,n,r,t)}async function Vg(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=Ws(e),s=Buffer.from(t.stdout,"utf8");return Vc(s)?{stdout:s,stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal,rawOutput:s}:{...await Wc(e,r,s,n),stderr:Buffer.from(t.stderr),status:t.status,signal:t.signal}}function Ws(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=Hc(t[++o],Hs);continue}if(a.startsWith("--head=")||a.startsWith("--tail=")){let[c,u]=a.split("=",2);n=c.slice(2),r=Hc(u,Hs);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 Wc(e,t,n,r){let s=n.toString("utf8"),i=Yg(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>Jc(r.heavyByteThreshold,Gc)||i.truncated;if(!qc(t.file)&&!o)return{stdout:Buffer.from(i.text),stderr:Buffer.alloc(0),status:0,signal:null,rawOutput:n};let a=qc(t.file)?Kg(e,t.file,n,s,r.level,i):zg(e,t.file,n,s,i),c=`${v(a)}
|
|
140
|
+
`;if(!o&&Buffer.byteLength(c)<=Jc(r.heavyByteThreshold,Gc))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 ${Q(u)}
|
|
141
|
+
`;return{stdout:Buffer.from(`${c}${l}`),stderr:Buffer.alloc(0),status:0,signal:null,payload:a,mintedHandle:u,bytesElided:n.length,rawOutput:n}}function Kg(e,t,n,r,s,i){let o=rr(r),a=s==="terse"?Jg:qg,c=rr(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:Qg(o),content:{head:u,tail:l,truncated:i.truncated||u.length+l.length<o.length}}}function zg(e,t,n,r,s){return{command:e.join(" "),file:t,kind:"text",bytes:n.length,lines:rr(r).length,content:rr(s.text),truncated:s.truncated}}function Yg(e,t){if(t.mode==="full")return{text:e,truncated:!1};let n=e.split(`
|
|
142
|
+
`),r=n.at(-1)==="",s=r?n.slice(0,-1):n,i=t.limit??Hs,o=t.mode==="head"?s.slice(0,i):s.slice(Math.max(0,s.length-i));return{text:`${o.join(`
|
|
132
143
|
`)}${r&&o.length>0?`
|
|
133
|
-
`:""}`,truncated:o.length<
|
|
134
|
-
`);return t.at(-1)===""?t.slice(0,-1):t}function
|
|
144
|
+
`:""}`,truncated:o.length<s.length}}function Qg(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&&!Xg(a[1])&&t.push({kind:"method",name:a[1],line:n+1,signature:s})}return t}function rr(e){let t=e.split(`
|
|
145
|
+
`);return t.at(-1)===""?t.slice(0,-1):t}function Vc(e){return e.includes(0)||!Ug(e)}function qc(e){return Hg.has(Gg(e).toLowerCase())}function Xg(e){return["for","if","switch","while"].includes(e)}function Jc(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}function Hc(e,t){let n=Number(e);return Number.isInteger(n)&&n>0?n:t}var Gc,Hs,qg,Jg,Hg,Ks=R(()=>{"use strict";Re();Ve();Gc=8*1024,Hs=10,qg=8,Jg=2,Hg=new Set([".c",".cc",".cpp",".cs",".go",".java",".js",".jsx",".mjs",".py",".rs",".ts",".tsx"])});var sr={};N(sr,{parseExecCommandLine:()=>Yc,renderExecContract:()=>zc,runExecWrapper:()=>sh});import{isUtf8 as Zg}from"node:buffer";import{spawn as eh}from"node:child_process";async function sh(e,t){let n=Yc(e),r=await ih(n);return await zc(n,r,t)}async function zc(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=oh(r);if(i.kind==="text"){let d=await Yt(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=uh(n.heavyByteThreshold,th);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(ah(o,r.length,l,n.level)),stderr:s,status:t.status,signal:t.signal,mintedHandle:l,bytesElided:c,rawOutput:r}}function Yc(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 ih(e){let t=eh(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 oh(e){return Zg(e)?{kind:"text",text:pt(e.toString("utf8"))}:{kind:"bytes"}}function ah(e,t,n,r){let i=Math.max(1,Math.floor((r==="terse"?rh:nh)/2)),o=Kc(e.subarray(0,i)),a=Kc(e.subarray(Math.max(0,e.length-i))),c=ch(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 ${Q(n)}`),`${u.join(`
|
|
135
146
|
`)}
|
|
136
|
-
`}function
|
|
137
|
-
`),2;let{renderShellInit:
|
|
138
|
-
`),0);if(n.command==="git"&&
|
|
139
|
-
`),0)}if(n.command==="warm-resident"){let m=o(process.cwd()),
|
|
140
|
-
`),0}if(!n.storeUri&&
|
|
141
|
-
`),1);let l=(m=!0)=>Promise.resolve(new a(u,{storeUri:
|
|
142
|
-
`),1;let
|
|
143
|
-
`;return process.stdout.write(
|
|
144
|
-
`;return process.stdout.write(
|
|
145
|
-
`),2}catch(m){if(
|
|
147
|
+
`}function Kc(e){return e.toString("utf8").replace(/�$/g,"")}function ch(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 uh(e,t){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:t}var th,nh,rh,ir=R(()=>{"use strict";Ve();Qt();th=8*1024,nh=2*1024,rh=1024});xr();Re();import{spawn as lh}from"node:child_process";import{createHash as dh}from"node:crypto";import{appendFileSync as Qc,existsSync as nn,mkdirSync as fh,readFileSync as mh,readdirSync as ph,statSync as gh}from"node:fs";import{tmpdir as hh}from"node:os";import{dirname as eu,join as ce}from"node:path";import{fileURLToPath as tu}from"node:url";function Bi(e){let t={app:e,version:Rl(st("__RED_BUILD_VERSION__",()=>"2.56.9")??"0.0.0-dev"),gitSha:st("__RED_BUILD_GIT_SHA__",()=>"81574b2ba4a9c4d2797824aa8a04950111c59a9d")??"unknown",buildTime:st("__RED_BUILD_TIME__",()=>"2026-07-14T23:32:03-03:00")??"unknown",bundleAsset:st("__RED_BUNDLE_ASSET__",()=>"rsp.bundle.min.mjs")??"unknown"},n=st("__REDDB_SDK_VERSION__",()=>"1.23.1"),r=st("__REDDB_BINARY_TAG__",()=>"v1.23.1");return n&&(t.reddbSdkVersion=n),r&&(t.reddbBinaryTag=r),t}function Rl(e){return e.startsWith("v")?e.slice(1):e}function st(e,t){try{let n=t();return typeof n=="string"&&n.length>0?n:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}jr();async function yh(e=process.argv.slice(2)){let t=Bi("rsp"),n=$h(e);if(n.command==="hook"&&n.positional[1]==="claude-pre-exec"){let{runClaudePreExecHook:m}=await Promise.resolve().then(()=>(qn(),us));return await m()}if(n.command==="hook"&&n.positional[1]==="codex-pre-exec"){let{runCodexPreExecHook:m}=await Promise.resolve().then(()=>(qn(),us));return await m()}if(n.command==="hook"&&n.positional[1]==="claude-post-exec"){let{runClaudePostExecHook:m}=await Promise.resolve().then(()=>(Qt(),ds));return await m()}if(n.command==="hook"&&n.positional[1]==="codex-post-exec"){let{runCodexPostExecHook:m}=await Promise.resolve().then(()=>(Qt(),ds));return await m()}if(n.command==="setup"){let{provisionRspRepoStore:m}=await Promise.resolve().then(()=>(Sa(),Ra)),p=await m(process.cwd());return process.stdout.write(Gh(p)),0}if(n.command==="mcp"){let{runRspMcpServer:m}=await Promise.resolve().then(()=>(Oa(),Pa));return await m(),0}if(n.command==="wait"){let{runWait:m}=await Promise.resolve().then(()=>(Aa(),Ca));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
|
|
148
|
+
`),2;let{renderShellInit:p}=await Promise.resolve().then(()=>(ja(),Ma));return process.stdout.write(p(m)),0}let{resolveRspConfig:r}=await Promise.resolve().then(()=>(ne(),ao)),s=r(process.cwd(),process.env,n.storeUri),i=Dh(n.command);if(!s.enabled)return i?await Oh(n.positional):(process.stdout.write(`${ni()}
|
|
149
|
+
`),0);if(n.command==="git"&&Xs(n.positional)){let m=process.hrtime.bigint();return await F(n,await Zs(),m,void 0,await wh(process.cwd()))}let{resolveResidentPaths:o,ResidentRspElisionStore:a,ensureResidentServer:c}=await Promise.resolve().then(()=>(je(),Lt));if(n.command==="server"){let{runResidentServer:m}=await Promise.resolve().then(()=>(yc(),hc)),p=o(process.cwd()),k=ae(n.positional,"--socket")??p.socketPath,w=r(process.cwd(),process.env,n.storeUri??ae(n.positional,"--store-uri"));return w.enabled?(await m({socketPath:k,pidPath:ae(n.positional,"--pid-file")??o(process.cwd()).pidPath,rootDir:p.rootDir,storeUri:w.storeUri,ttlDays:C(n.positional,"--ttl-days")??w.ttlDays,ephemeralTtlHours:C(n.positional,"--ephemeral-ttl-hours")??w.ephemeralTtlHours,byteBudget:C(n.positional,"--byte-budget")??w.byteBudget,telemetryTtlDays:C(n.positional,"--telemetry-ttl-days")??w.telemetryTtlDays,telemetryByteBudget:C(n.positional,"--telemetry-byte-budget")??w.telemetryByteBudget,telemetryDrainIntervalMs:C(n.positional,"--telemetry-drain-interval-ms")??w.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:C(n.positional,"--telemetry-drain-timeout-ms")??w.telemetryDrainTimeoutMs,idleMs:C(n.positional,"--idle-ms")??w.idleMs,residentVersion:ae(n.positional,"--resident-version")??t.version,registryPath:ae(n.positional,"--registry")??p.registryPath}),0):(process.stdout.write(`${ni()}
|
|
150
|
+
`),0)}if(n.command==="warm-resident"){let m=o(process.cwd()),p=ae(n.positional,"--socket")??m.socketPath,k=ae(n.positional,"--wake-lock")??m.wakeLockPath,w=r(process.cwd(),process.env,n.storeUri??ae(n.positional,"--store-uri"));if(!w.enabled)return 0;let{warmResidentServer:T}=await Promise.resolve().then(()=>(je(),Lt));return await T({...m,socketPath:p,wakeLockPath:k},{storeUri:w.storeUri,ttlDays:C(n.positional,"--ttl-days")??w.ttlDays,ephemeralTtlHours:C(n.positional,"--ephemeral-ttl-hours")??w.ephemeralTtlHours,byteBudget:C(n.positional,"--byte-budget")??w.byteBudget,telemetryTtlDays:C(n.positional,"--telemetry-ttl-days")??w.telemetryTtlDays,telemetryByteBudget:C(n.positional,"--telemetry-byte-budget")??w.telemetryByteBudget,telemetryDrainIntervalMs:C(n.positional,"--telemetry-drain-interval-ms")??w.telemetryDrainIntervalMs,telemetryDrainTimeoutMs:C(n.positional,"--telemetry-drain-timeout-ms")??w.telemetryDrainTimeoutMs,idleMs:C(n.positional,"--idle-ms")??w.idleMs,clientVersion:t.version}),0}let u=o(process.cwd());if(n.command==="proxy"){let{runProxy:m}=await Promise.resolve().then(()=>(Bs(),Ns));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(()=>(je(),Lt)),k=n.command==="sweep"?await p(u):await m(u);return process.stdout.write(`${v(k)}
|
|
151
|
+
`),0}if(!n.storeUri&&s.storeUri.startsWith("file://")&&!nn(tu(s.storeUri)))return i?await Rh(n,s,u.rootDir):(process.stdout.write(`error: rsp repo store is not provisioned - run /red-setup
|
|
152
|
+
`),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(()=>(Ge(),Gt));return await m.open({uri:s.storeUri,ttlDays:s.ttlDays,ephemeralTtlHours:s.ephemeralTtlHours,byteBudget:s.byteBudget})},y=()=>s.storeUri.endsWith("/red-skills.rdb")?l():f(),g;try{if(!n.command||n.command==="stats"){let{stats:m,telemetry:p}=await Sh(s,Xc(n.positional,30));return process.stdout.write(Bh(m,p,Nh(n.positional))),0}if(n.command==="gains"){let m=await y();if(g=()=>m.close(),!_h(m))return process.stdout.write(`error: rsp gains requires the shared RedDB store
|
|
153
|
+
`),1;let p=await m.telemetryGains(Xc(n.positional,28));return process.stdout.write(Ch(p)),0}if(n.command==="git"){if(Ne(d()),Xs(n.positional)){let T=process.hrtime.bigint();return await F(n,await Zs(),T,void 0,u.rootDir)}let{runGitWrapper:m}=await Promise.resolve().then(()=>(Ve(),As)),p=new ze(()=>l(!1));g=()=>p.close();let k=process.hrtime.bigint(),w=await m(n.positional,{level:n.level,store:p,heavyGitByteThreshold:s.heavyGitByteThreshold});return await F(n,w,k,p,u.rootDir)}if(n.command==="gh"){Ne(d());let{runGhWrapper:m}=await Promise.resolve().then(()=>(Fs(),Us)),p=new ze(()=>l(!1));g=()=>p.close();let k=process.hrtime.bigint(),w=await m(n.positional,{level:n.level,store:p});return await F(n,w,k,p,u.rootDir)}if(n.command==="vitest"||n.command==="cargo"){Ne(d());let{runTestWrapper:m}=await Promise.resolve().then(()=>(Js(),qs)),p=new ze(()=>l(!1));g=()=>p.close();let k=process.hrtime.bigint(),w=await m(n.positional,{level:n.level,store:p});return await F(n,w,k,p,u.rootDir)}if(n.command==="cat"){Ne(d());let{runCatWrapper:m}=await Promise.resolve().then(()=>(Ks(),Vs)),p=new ze(()=>l(!1));g=()=>p.close();let k=process.hrtime.bigint(),w=await m(n.positional,{level:n.level,store:p,heavyByteThreshold:s.heavyGitByteThreshold});return await F(n,w,k,p,u.rootDir)}if(n.command==="exec"){Ne(d());let{runExecWrapper:m}=await Promise.resolve().then(()=>(ir(),sr)),p=new ze(()=>l(!1));g=()=>p.close();let k=process.hrtime.bigint(),w=await m(n.positional,{level:n.level,store:p,heavyByteThreshold:s.heavyGitByteThreshold});return await F(n,w,k,p,u.rootDir)}if(n.command==="show"&&n.handle){let m=await y();g=()=>m.close();let p=await m.get(n.handle);if(p&&"original"in p&&p.original)return process.stdout.write(p.original),await zs(u.rootDir,n.handle,!0,p.original.length),0;if(p?.status==="expired"){let w=`expired ${p.expired_at} \u2014 re-run: ${p.command}
|
|
154
|
+
`;return process.stdout.write(w),await zs(u.rootDir,n.handle,!1,Buffer.byteLength(w,"utf8")),1}let k=`expired unknown \u2014 re-run: ${n.handle}
|
|
155
|
+
`;return process.stdout.write(k),await zs(u.rootDir,n.handle,!1,Buffer.byteLength(k,"utf8")),1}return process.stdout.write(`error: usage rsp show el:<id>
|
|
156
|
+
`),2}catch(m){if(i)return await ti("wrapper failed",n.positional,m,u.rootDir);throw m}finally{await g?.()}}function ae(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:void 0}function C(e,t){let n=ae(e,t);if(n==null)return;let r=Number(n);return Number.isFinite(r)&&r>0?r:void 0}function Xs(e){return e.length===2&&e[0]==="git"&&e[1]==="status"}async function Zs(){if(bh(process.cwd()))return{stdout:Buffer.from(`git empty
|
|
146
157
|
`),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
|
|
147
158
|
`),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
|
|
148
|
-
`):n.stdout;return{stdout:r,stderr:n.stderr,status:0,signal:n.signal,rawOutput:r}}async function
|
|
159
|
+
`):n.stdout;return{stdout:r,stderr:n.stderr,status:0,signal:n.signal,rawOutput:r}}async function wh(e){try{let{resolveResidentPaths:t}=await Promise.resolve().then(()=>(je(),Lt));return t(e).rootDir}catch{return e}}function bh(e){try{return!nn(`${e}/.git`)||nn(`${e}/.git/index`)?!1:ph(e).every(t=>t===".git")}catch{return!1}}function _h(e){return typeof e=="object"&&e!==null&&"telemetryGains"in e&&typeof e.telemetryGains=="function"}var ze=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}},ei=class{async mint(t,n){return`recovery unavailable (cold store) \u2014 re-run: ${n.command}`}lastResponseMetrics(){}async close(){}};async function Rh(e,t,n,r){if(process.env.RSP_DEBUG==="1")throw r instanceof Error?r:new Error("cold store");let s=new ei,i=process.hrtime.bigint();try{if(e.command==="git"){if(Xs(e.positional))return await F(e,await Zs(),i,s,n,t);let{runGitWrapper:o}=await Promise.resolve().then(()=>(Ve(),As)),a=await o(e.positional,{level:e.level,store:s,heavyGitByteThreshold:t.heavyGitByteThreshold});return await F(e,a,i,s,n,t)}if(e.command==="gh"){let{runGhWrapper:o}=await Promise.resolve().then(()=>(Fs(),Us)),a=await o(e.positional,{level:e.level,store:s});return await F(e,a,i,s,n,t)}if(e.command==="vitest"||e.command==="cargo"){let{runTestWrapper:o}=await Promise.resolve().then(()=>(Js(),qs)),a=await o(e.positional,{level:e.level,store:s});return await F(e,a,i,s,n,t)}if(e.command==="cat"){let{runCatWrapper:o}=await Promise.resolve().then(()=>(Ks(),Vs)),a=await o(e.positional,{level:e.level,store:s,heavyByteThreshold:t.heavyGitByteThreshold});return await F(e,a,i,s,n,t)}if(e.command==="exec"){let{runExecWrapper:o}=await Promise.resolve().then(()=>(ir(),sr)),a=await o(e.positional,{level:e.level,store:s,heavyByteThreshold:t.heavyGitByteThreshold});return await F(e,a,i,s)}}catch(o){return await ti("wrapper failed",e.positional,o,n)}finally{await s.close()}return await ti("wrapper failed",e.positional,r,n)}async function Sh(e,t){let n={stats:Fh(e.telemetryByteBudget),telemetry:si(t)};if(!e.storeUri.startsWith("file://"))return n;let r=tu(e.storeUri);if(!nn(r))return n;if(!r.endsWith("red-skills.rdb")){let{RspElisionStore:c}=await Promise.resolve().then(()=>(Ge(),Gt)),u=await c.open({uri:e.storeUri,ttlDays:e.ttlDays,ephemeralTtlHours:e.ephemeralTtlHours,byteBudget:e.byteBudget});try{return{stats:await u.stats(),telemetry:si(t)}}finally{await u.close()}}let{ensureReddbBinaryFromWarmCache:s}=await Promise.resolve().then(()=>(Ge(),Gt));await s();let{readAccountingLaneStats:i,readTelemetryStats:o}=await Promise.resolve().then(()=>(Te(),Wt)),a=await ln(e.storeUri);try{return{stats:await i(a,e.telemetryByteBudget),telemetry:await o(a,t)}}finally{await a.close()}}async function F(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?(Ne(vh(s,e,t,o,r.lastResponseMetrics())),i&&Eh(s,i)):Ph(s,e,t,o),t.signal?(process.kill(process.pid,t.signal),128):t.status??0}function Eh(e,t){try{let n=ce(e,".red","tmp","rsp-telemetry.spool.jsonl"),r=gh(n),s=t.telemetryDrainIntervalMs*2;if(r.size<t.telemetryByteBudget&&!Th(n,Date.now()-s))return;let i=kh(e),o=xh(i),a=ce(o,"rsp.sock"),c=ce(o,"rsp.pid"),u=ce(i,".red","tmp","rsp-resident.pid.json"),l=ce(i,".red","tmp","rsp.wake.lock");lh(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 kh(e){let t=e;for(;;){if(nn(ce(t,".git")))return t;let n=eu(t);if(n===t)return e;t=n}}function xh(e){let t=dh("sha256").update(e).digest("hex").slice(0,20),n=process.env.XDG_RUNTIME_DIR;if(n){let s=ce(n,"red-skills",t);if(ce(s,"rsp.sock").length<108)return s}let r=typeof process.getuid=="function"?process.getuid():"nouid";return ce(hh(),`red-skills-${r}`,t)}function Th(e,t){try{let n=mh(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 vh(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(),Wt));await a(e,{collection:c,event_type:"invocation",ts:new Date().toISOString(),command:or(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:or(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 Ph(e,t,n,r){try{let s=Buffer.concat([n.stdout,n.stderr]),i=Buffer.concat([n.rawOutput??n.stdout,n.stderr]),o=ce(e,".red","tmp","rsp-telemetry.spool.jsonl"),a=JSON.stringify({collection:"rsp_accounting_events_v1",event_type:"invocation",ts:new Date().toISOString(),command:or(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}),c=JSON.stringify({collection:"rsp_telemetry_invocations_v1",ts:new Date().toISOString(),command:or(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}),u=`${a}
|
|
149
160
|
${c}
|
|
150
|
-
`;try{
|
|
151
|
-
`);let
|
|
152
|
-
`),await
|
|
153
|
-
`),
|
|
154
|
-
`),2}let{spawn:n}=await import("node:child_process"),r=n(t,{shell:!0,stdio:"inherit"});return await new Promise(
|
|
155
|
-
`),
|
|
156
|
-
`)}function
|
|
157
|
-
`}function Ah(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
|
|
158
|
-
`)}import.meta.url===`file://${process.argv[1]}`&&
|
|
159
|
-
`),process.exit(1)});export{
|
|
161
|
+
`;try{Qc(o,u,{encoding:"utf8",mode:384})}catch(l){if(l.code!=="ENOENT")return;fh(eu(o),{recursive:!0}),Qc(o,u,{encoding:"utf8",mode:384})}}catch{}}async function ti(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
|
|
162
|
+
`);let s=await nu(t);if(r){let{appendTelemetryEvent:i,RSP_ACCOUNTING_EVENTS_COLLECTION:o,RSP_TELEMETRY_DEGRADATIONS_COLLECTION:a}=await Promise.resolve().then(()=>(Te(),Wt));Ne(i(r,{collection:o,event_type:"invocation",ts:new Date().toISOString(),command:ri(t),command_class:t[0]??"unknown",loss:"lossless",raw_bytes:0,emitted_bytes:0,degradation_reason:e})),Ne(i(r,{collection:a,ts:new Date().toISOString(),command:ri(t),reason:e,accounting_recorded:!0}))}return s}function Ne(e){e.catch(()=>{})}async function zs(e,t,n,r){let{appendTelemetryEvent:s,RSP_ACCOUNTING_EVENTS_COLLECTION:i}=await Promise.resolve().then(()=>(Te(),Wt));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 Oh(e){return process.env.RSP_DEBUG==="1"&&process.stderr.write(`rsp: ${ni()}, passing through
|
|
163
|
+
`),await nu(e)}function ni(){return"rsp is not enabled in this directory; run /red-setup"}function Dh(e){return e==="git"||e==="gh"||e==="vitest"||e==="cargo"||e==="cat"||e==="exec"||e==="proxy"}async function nu(e){if(e[0]==="exec"||e[0]==="proxy")return await Ih(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)}
|
|
164
|
+
`),s(127)}),r.on("close",(i,o)=>{if(o){process.kill(process.pid,o),s(128);return}s(i??0)})})}async function Ih(e){let t;try{if(e[0]==="proxy"){let{parseProxyCommandLine:s}=await Promise.resolve().then(()=>(Bs(),Ns));t=s(e)}else{let{parseExecCommandLine:s}=await Promise.resolve().then(()=>(ir(),sr));t=s(e)}}catch(s){return process.stderr.write(`${s instanceof Error?s.message:String(s)}
|
|
165
|
+
`),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)}
|
|
166
|
+
`),s(127)}),r.on("close",(i,o)=>{if(o){process.kill(process.pid,o),s(128);return}s(i??0)})})}function or(e){return ri(e.positional)}function ri(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 $h(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 Xc(e,t){let n=ae(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 Nh(e){return e.includes("--full")}function Bh(e,t=si(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??ru();return[`records: ${e.records}`,`bytes: ${e.bytes}`,`oldest: ${e.oldest??"none"}`,`budget: ${e.budget}`,"storage_classes:",...Uh(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: ${Ah(t.savings)}`,` dollars_saved_estimate_usd: ${Lh(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:",...Mh(s),...!n&&t.savings.daily_tokens_saved.length>s.length?[` elided_days: ${t.savings.daily_tokens_saved.length-s.length}`," hint: --full"]:[]," top_commands:",...jh(r),"health:",` degradations: ${t.health.degradations}`,` degradation_rate: ${Qs(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: ${Qs(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:",...Zc(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: ${Qs(t.decisions.contribution_rate)}`," top_pass_reasons:",...Zc(t.decisions.top_pass_reasons.slice(0,n?10:3)),"latency:",` wrapper_ms_p50: ${Ys(t.latency.wrapper_ms_p50)}`,` wrapper_ms_p95: ${Ys(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: ${Ys(t.latency.store_elapsed_ms_avg)}`,""].join(`
|
|
167
|
+
`)}function Ch(e){return`${v(e)}
|
|
168
|
+
`}function Ah(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 Lh(e){return e.dollars_saved_low_usd==null||e.dollars_saved_high_usd==null?$t(e.dollars_saved_estimate_usd):`${$t(e.dollars_saved_low_usd)}-${$t(e.dollars_saved_high_usd)} (estimate_midpoint: ${$t(e.dollars_saved_estimate_usd)})`}function Mh(e){return e.length===0?[" empty: true"]:e.map(t=>` ${t.date}: ${t.tokens_saved}`)}function jh(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 Zc(e){return e.length===0?[" empty: true"]:e.map(t=>` ${t.reason}: ${t.count}`)}function Uh(e){return["derivable","re-executable","ephemeral"].map(t=>` ${t}: records: ${e[t].records} bytes: ${e[t].bytes} raw_bytes: ${e[t].raw_bytes}`)}function Ys(e){return e==null?"none":String(e)}function Qs(e){return e.toFixed(4).replace(/0+$/,"").replace(/\.$/,".0")}function si(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 Fh(e){return{records:0,bytes:0,oldest:null,budget:e,storage_classes:ru()}}function ru(){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 Gh(e){return[`config: ${e.configChanged?"updated":"unchanged"}`,`store: ${e.storeCreated?"created":"existing"}`,""].join(`
|
|
169
|
+
`)}import.meta.url===`file://${process.argv[1]}`&&yh().then(e=>process.exit(e),e=>{process.stdout.write(`error: ${e instanceof Error?e.message:String(e)}
|
|
170
|
+
`),process.exit(1)});export{yh as main,Gh as renderSetupResult,Bh as renderStats};
|