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