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