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