@probnaya/057-cli 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
- import{existsSync as ge,createReadStream as jm,statSync as fa,mkdirSync as eu,chmodSync as pa,writeFileSync as Wl,renameSync as Kl,rmSync as Dm,readFileSync as Gl}from"node:fs";import{createInterface as Ib}from"node:readline";import{createServer as Lm}from"node:http";import{join as ue,isAbsolute as tu,relative as Sc,sep as ru,dirname as vi,resolve as $s,normalize as Ob,extname as Cb}from"node:path";import{fileURLToPath as Nb}from"node:url";import{stat as sn,readdir as Ze,readFile as _r}from"node:fs/promises";import{hostname as Tb,homedir as xn}from"node:os";import $b from"node:zlib";import{createHash as fo,webcrypto as Bb,randomBytes as Yn,X509Certificate as Jo,timingSafeEqual as Rb,verify as Mb,createPublicKey as _b}from"node:crypto";import{execFileSync as jb,execFile as Db}from"node:child_process";import{DatabaseSync as Bs}from"node:sqlite";import{isMainThread as Pm,workerData as bi,parentPort as Fn,Worker as Um}from"node:worker_threads";import{promisify as Lb}from"node:util";import{createServer as Pb}from"node:https";function Ub(t){const e=new AbortController,r={controller:e,consumers:0,settled:!1,promise:t(e.signal)};return r.promise.then(()=>{r.settled=!0},()=>{r.settled=!0}),r}function yf(t,e){return t.consumers++,new Promise((r,n)=>{let o=!1;const s=a=>{o||(o=!0,e?.removeEventListener("abort",i),t.consumers--,!t.settled&&t.consumers===0&&t.controller.abort(),a())},i=()=>s(()=>n(new Error("analytical read cancelled")));e?.addEventListener("abort",i,{once:!0}),t.promise.then(a=>s(()=>r(a)),a=>s(()=>n(a))),e?.aborted&&i()})}const gf=["machine","session","execution","process","artifact"];function Vb(t){return`${t.ns}|${t.parts.join("|")}`}const Z={interactions:"interactions",steps:"steps",errors:"errors",retries:"retries",cpuMs:"cpu.ms",tokensInput:"tokens.input",tokensOutput:"tokens.output",tokensCacheRead:"tokens.cacheRead",tokensReasoning:"tokens.reasoning"},Hb=[{a:"execution",b:"process",kind:"ran-as"},{a:"session",b:"process",kind:"ran-as"},{a:"execution",b:"session",kind:"ran-as"},{a:"session",b:"session",kind:"same-as"},{a:"execution",b:"execution",kind:"same-as"},{a:"machine",b:"machine",kind:"same-as"},{a:"process",b:"process",kind:"same-as"}];function vf(t,e){for(const r of Hb){if(t.subjectType===r.a&&e.subjectType===r.b)return{kind:r.kind,from:t,to:e};if(e.subjectType===r.a&&t.subjectType===r.b)return{kind:r.kind,from:e,to:t}}return null}const Fb=(t,e)=>t.validFrom<=e.validTo&&e.validFrom<=t.validTo;function Wb(t,e){const r=Math.max(t.validFrom,e.validFrom),n=Math.min(t.validTo,e.validTo);if(n<r)return 0;const o=Math.max(t.validTo,e.validTo)-Math.min(t.validFrom,e.validFrom);return o<=0?1:(n-r)/o}const Kb=.5;function Gb(t,e){return Fb(t,e)?Wb(t,e)>=Kb?2:1:0}const Bt=t=>`${t.subjectType}:${t.subjectId}`,qb="inferred",zb="Two observers asserted the same identity claim over overlapping validity windows, and each was the other's only candidate at the strongest available evidence tier (two lifetimes that substantially coincide beat a bare overlap). The claims themselves are measured; the identification is inferred.";function Yb(t){const e=new Map;for(const s of t){const i=e.get(s.key);i?i.push(s):e.set(s.key,[s])}const r=[],n=[];let o=0;for(const[s,i]of[...e.entries()].sort(([a],[c])=>a<c?-1:1)){const a=new Map;for(const p of i){const h=Bt(p),v=a.get(h);if(!v){a.set(h,{...p});continue}v.validFrom=Math.min(v.validFrom,p.validFrom),v.validTo=Math.max(v.validTo,p.validTo)}const c=[...a.values()].sort((p,h)=>Bt(p)<Bt(h)?-1:1);if(c.length<2){o++;continue}const u=[];let d=!1;for(let p=0;p<c.length;p++)for(let h=p+1;h<c.length;h++){const v=c[p],g=c[h];if(v.sourceId===g.sourceId)continue;const I=Gb(v,g);if(I!==0){if(!vf(v,g)){d=!0;continue}u.push({x:v,y:g,tier:I})}}const l=new Map;for(const p of u)for(const h of[p.x,p.y]){const v=Bt(h);l.set(v,Math.max(l.get(v)??0,p.tier))}const m=new Map;for(const p of u)for(const h of[p.x,p.y]){const v=Bt(h);l.get(v)===p.tier&&m.set(v,(m.get(v)??0)+1)}if(u.length===0){n.push({key:s,reason:d?"no-pairing-defined":"no-window-overlap",subjects:[...a.keys()].sort()});continue}for(const{x:p,y:h,tier:v}of u){if(l.get(Bt(p))!==v||l.get(Bt(h))!==v)continue;if(m.get(Bt(p))!==1||m.get(Bt(h))!==1){n.push({key:s,reason:"multiple-candidates",subjects:[Bt(p),Bt(h)].sort()});continue}const g=vf(p,h);r.push({from:{type:g.from.subjectType,id:g.from.subjectId},to:{type:g.to.subjectType,id:g.to.subjectId},kind:g.kind,basis:qb,assumption:zb,via:s})}}return{relationships:r,ambiguous:n,unmatched:o,considered:e.size}}async function Xb(t,e,r,n,o){const s=[];let i=0,a=0;for(const c of e){const u=Date.now();try{const d=await c.collect(r,n),l=t.append(d);i+=l.inserted,a+=l.duplicate,s.push({id:c.id,ok:!0,collected:d.length,inserted:l.inserted,duplicate:l.duplicate,ms:Date.now()-u})}catch(d){s.push({id:c.id,ok:!1,collected:0,inserted:0,duplicate:0,error:d instanceof Error?d.message:String(d),ms:Date.now()-u})}o?.(s[s.length-1])}return{sources:s,inserted:i,duplicate:a}}const Vm=1e3,bf=60*Vm;function fe(t){if(!Number.isFinite(t)||t<=0)return"0m";if(t<bf)return`${Math.max(1,Math.round(t/Vm))}s`;const e=Math.round(t/bf),r=Math.floor(e/60),n=e%60;return r===0?`${n}m`:n===0?`${r}h`:`${r}h ${n}m`}function ze(t){if(!Number.isFinite(t))return"—";const e=Math.abs(t);return e>=1e9?`${(t/1e9).toFixed(e>=1e10?0:2)}B`:e>=1e6?`${(t/1e6).toFixed(e>=1e7?0:2)}M`:e>=1e3?`${(t/1e3).toFixed(e>=1e4?0:1)}k`:String(Math.round(t))}function Jb(t,e="NOT OBSERVED"){return t===void 0?e:ze(t)}function wi(t,e){if(e<=0)return"—";const r=t/e*100;return r>0&&r<1?"<1%":`${Math.round(r)}%`}function Zb(t){return t===void 0||!Number.isFinite(t)?"—":t>=1e9?`${(t/1e9).toFixed(1)} GB`:t>=1e6?`${(t/1e6).toFixed(0)} MB`:t>=1e3?`${(t/1e3).toFixed(0)} KB`:`${t} B`}function wf(t){const e=new Date(t);return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}function Ne(t){const e=t.split("/").filter(Boolean);return e[e.length-1]??t}const ql="deepseek-harness",Qb={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"supported",waits:"supported",model:"supported",context:"supported",outcome:"supported"},Me=t=>typeof t=="number"&&Number.isFinite(t)?t:0,dt=t=>typeof t=="string"?t:void 0;function ew(t){const e=t.split("/").filter(Boolean);return(e[e.length-1]??t).toUpperCase()}function tw(t,e){const r=[],n=t[0];if(!n||n.type!=="session"||!n.id)return r;const o=n.id,s=n.cwd??"",i=Me(n.createdAt),a=Me(n.delegationDepth),c=ew(s);let u="deepseek",d,l;for(const x of t)if(x.type==="request/context"&&x.data?(u=dt(x.data.provider)??u,d=dt(x.data.model)??d):x.type==="session/title"&&x.data&&(l=dt(x.data.title)??l),d&&l)break;const p={source:{id:ql,instance:e.instance},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let h=i;for(const x of t){const D=Me(x.time);D>h&&(h=D)}const v={ns:"fs.cwd",parts:[e.host,s],validFrom:i,validTo:Math.max(i,h)};r.push({...p,occurredAt:i,seq:"session",kind:"began",subject:{type:"session",id:o},claims:s?[v]:void 0,core:{machineId:e.machine.id,label:l,projectLabel:s?Ne(s):void 0,taskLabel:l,executor:u,model:d,depth:a},attrs:{context:s,"dsh.delegationDepth":a}});const g=x=>`${o}:turn:${x}`;let I=null;const N=new Map,S=new Map;let T=i;for(const x of t){const D=Me(x.time)||T;if(D<i)continue;T=D;const w=x.data??{},$=x.seq??`t${D}`,E=B=>({type:"execution",id:g(B)});switch(x.type){case"turn/start":{const B=Me(w.turn);I=B,r.push({...p,occurredAt:D,seq:$,kind:"began",subject:E(B),core:{machineId:e.machine.id,sessionId:o,label:l?`${c} · ${l}`:c,executor:u,model:d,depth:a},attrs:{"dsh.turn":B}});break}case"turn/end":{const B=Me(w.turn),C=w.reason,P=C?.kind;if(P==="error"){const L=C?.error??{};r.push({...p,occurredAt:D,seq:$,kind:"ended",subject:E(B),core:{outcome:"error",failureCode:dt(L.code)??"ERROR",failureMessage:dt(L.message)??"Run failed"},attrs:{"dsh.endReason":P}})}else r.push({...p,occurredAt:D,seq:$,kind:"ended",subject:E(B),core:{outcome:P==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":P??"completed"}});I===B&&(I=null);break}case"assistant/message":{const B=Me(w.turn),C=w.usage;if(!C)break;const P={[Z.tokensInput]:Me(C.inputTokens),[Z.tokensOutput]:Me(C.outputTokens),[Z.tokensCacheRead]:Me(C.cacheReadTokens),[Z.tokensReasoning]:Me(C.reasoningTokens),[Z.steps]:1};r.push({...p,occurredAt:D,seq:$,kind:"progressed",subject:E(B),core:{measures:P},attrs:{"dsh.inputTokens":Me(C.inputTokens),"dsh.outputTokens":Me(C.outputTokens),"dsh.cacheReadTokens":Me(C.cacheReadTokens),"dsh.reasoningTokens":Me(C.reasoningTokens)}});break}case"tool/call":{r.push({...p,occurredAt:D,seq:$,kind:"progressed",subject:E(Me(w.turn)),core:{measures:{[Z.interactions]:1}},attrs:{"dsh.tool":dt(w.name)}});break}case"tool/result":{const B=w.message;let C=!1;for(const P of B?.content??[])P.isError===!0&&(C=!0);C&&r.push({...p,occurredAt:D,seq:$,kind:"progressed",subject:E(Me(w.turn)),core:{measures:{[Z.errors]:1}}});break}case"llm/retry":{r.push({...p,occurredAt:D,seq:$,kind:"progressed",subject:E(Me(w.turn)),core:{measures:{[Z.retries]:1}}});break}case"approval/asked":{const B=dt(w.id);if(I===null)break;B&&N.set(B,I),r.push({...p,occurredAt:D,seq:$,kind:"blocked",subject:E(I),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":B}});break}case"approval/decided":{const B=dt(w.id),C=B?N.get(B):I;if(C==null)break;N.delete(B??""),r.push({...p,occurredAt:D,seq:$,kind:"resumed",subject:E(C),attrs:{"dsh.approvalId":B}});break}case"tool-workflow/agent-start":{if(I===null)break;const B=dt(w.childId);if(!B)break;const C=`${o}:agent:${B}`;S.set(`${dt(w.runId)}:${Me(w.seq)}`,C),r.push({...p,occurredAt:D,seq:$,kind:"began",subject:{type:"execution",id:C},core:{machineId:e.machine.id,sessionId:o,label:dt(w.label)??`${c} · SUB`,executor:u,model:d,parentId:g(I),depth:a+1},attrs:{"dsh.childId":B}});break}case"tool-workflow/agent-end":{const B=`${dt(w.runId)}:${Me(w.seq)}`,C=S.get(B);if(!C)break;S.delete(B);const P=dt(w.outcome);r.push({...p,occurredAt:D,seq:$,kind:"ended",subject:{type:"execution",id:C},core:P==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:P??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":P}});break}}}if(e.closeOpenTurns){const x="The session log has not been written to for longer than the live window, so the process that owned it is gone and any turn left open was cut off rather than still running.";I!==null&&r.push({...p,occurredAt:T,seq:"close:turn",kind:"ended",subject:{type:"execution",id:g(I)},core:{outcome:"interrupted"},basis:"inferred",assumption:x});for(const D of S.values())r.push({...p,occurredAt:T,seq:`close:${D}`,kind:"ended",subject:{type:"execution",id:D},core:{outcome:"interrupted"},basis:"inferred",assumption:x});r.push({...p,occurredAt:T,seq:"close:session",kind:"ended",subject:{type:"session",id:o},basis:"inferred",assumption:x})}return e.since!==void 0?r.filter(x=>x.occurredAt>=e.since):r}function rw(t){const e=[];let r=0;for(;r<t.length;){let n=t.indexOf(`
2
- `,r);n===-1&&(n=t.length);const o=t.slice(r,n);if(r=n+1,o.length!==0&&!(o.startsWith('{"type":"reasoning-chunks"')||o.startsWith('{"type":"text-chunks"')||o.startsWith('{"type":"tool-call-chunks"')||o.startsWith('{"type":"assistant/chunk"')))try{e.push(JSON.parse(o))}catch{}}return e}function nw(t){const e=JSON.stringify([t.source.id,t.source.instance,t.occurredAt,t.clock,t.kind,t.subject.type,t.subject.id,t.basis,t.seq??null,Ai(t.core),Ai(t.attrs)]);return fo("sha256").update(e).digest("hex").slice(0,32)}function Ai(t){if(t==null)return null;if(Array.isArray(t))return t.map(Ai);if(typeof t!="object")return t;const e={};for(const r of Object.keys(t).sort())e[r]=Ai(t[r]);return e}function Zt(t){const{seq:e,...r}=t;return{id:nw(t),...r}}let Af;function ow(){try{const t=jb("/usr/sbin/scutil",["--get","LocalHostName"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();return/^[A-Za-z0-9-]{1,63}$/.test(t)?t:void 0}catch{return}}function Hm(){return Af??=ow()??Tb().replace(/\.local$/i,""),Af}const Si="host:";function sw(t){return`${Si}${t}`}function iw(t){return t.startsWith(Si)?t.slice(Si.length):void 0}function Sf(t){return t.startsWith(Si)}const aw=4247762216,cw=407710288,uw=407710303;function lw(t){const e=[];for(let o=0;o+4<=t.length;o++){const s=t.readUInt32LE(o);(s===aw||s>=cw&&s<=uw)&&e.push(o)}if(e.length===0)return Buffer.alloc(0);const r=[];let n=0;for(;n<e.length;){let o=n+1,s=null;for(;;){const i=o<e.length?e[o]:t.length;try{s=$b.zstdDecompressSync(t.subarray(e[n],i));break}catch{if(o>=e.length)break;o++}}s?(r.push(s),n=o):n++}return Buffer.concat(r)}function zl(){return process.env.DSH_HOME||ue(xn(),".dsh")}function Ur(){return Hm()}function Vr(){const t=Ur();return{id:sw(t),name:t.toUpperCase(),kind:"laptop",firstSeenAt:0}}const kf=new Map;async function Fm(){const t=ue(zl(),"sessions");if(!ge(t))return[];const e=[];for(const r of await Ze(t)){const n=ue(t,r);let o;try{o=await Ze(n)}catch{continue}for(const s of o){const i=ue(n,s,"session.jsonl.zstd");ge(i)&&e.push({path:i,workspace:r,sessionId:s})}}return e}const Yl=10*6e4;async function dw(t,e){const r=await sn(t.path),n=kf.get(t.path);if(n&&n.mtimeMs===r.mtimeMs&&n.size===r.size)return n.envelopes;const o=await _r(t.path),s=lw(o).toString("utf8"),i=rw(s),a=Date.now()-r.mtimeMs>Yl,u=tw(i,{machine:e,host:Ur(),instance:zl(),observedAt:Date.now(),closeOpenTurns:a}).map(Zt);return kf.set(t.path,{mtimeMs:r.mtimeMs,size:r.size,envelopes:u}),u}async function fw(t,e){const r=Vr(),n=await Fm(),o=[];for(const s of n){let i;try{i=await sn(s.path)}catch{continue}if(!(i.mtimeMs<t))for(const a of await dw(s,r))a.occurredAt>=t&&a.occurredAt<=e&&o.push(a)}return o}async function Ef(){const t=await Fm(),e=zl();return{available:t.length>0,present:ge(e),home:e,sessions:t.length}}const ki="0x2f",pw={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"supported",model:"partial",context:"supported",outcome:"supported"},ar=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0},Wm=(t,e)=>`2f:${t}#${e}`,hw=(t,e,r)=>`${Wm(t,e)}:run:${r}`;function xf(t){return t?.type==="permission"?"approval":"input"}function mw(t){const e=new Map;for(const r of t){const n=typeof r.run=="number"?r.run:1,o=e.get(n);o?o.push(r):e.set(n,[r])}return e}function yw(t,e){const r=e.find(s=>s.type==="run.started");let n;for(let s=e.length-1;s>=0;s--){const i=e[s];if(i.type==="run.completed"||i.type==="run.failed"||i.type==="needs_user"&&i.blockedOn){n=i;break}}let o;return n?.type==="run.completed"?o="ready":n?.type==="run.failed"?o="failed":n?o="needs_you":t.status==="needs_you"||t.status==="ready"||t.status==="failed"?o=t.status:t.status==="working"?o="working":o=t.error?"failed":"ready",{run:1,provider:t.execution?.provider??null,node:t.execution?.node??null,model:t.execution?.model,externalSessionId:t.execution?.externalSessionId,attempts:t.execution?.attempts??1,startedAt:r?.at,completedAt:n?.at,outcome:o,error:t.error??(n?.type==="run.failed"?n.error:void 0),blockedOn:n?.type==="needs_user"?n.blockedOn:void 0,failure:t.failure}}function gw(t,e){return Array.isArray(t.runs)&&t.runs.length?t.runs:[yw(t,e)]}function vw(t,e,r){if(typeof t.id!="number")return[];const n=Wm(r.base,t.id),o=gw(t,e),s=Ne(r.base).toUpperCase(),i=t.title,a=t.execution?.provider??o.at(-1)?.provider??ki,c=ar(t.createdAt)??o.map(g=>ar(g.startedAt)).find(g=>g!==void 0);if(c===void 0)return[];const d={source:{id:ki,instance:r.base},observedAt:r.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},l=[{...d,occurredAt:c,kind:"began",subject:{type:"session",id:n},core:{machineId:r.machine.id,label:i,projectLabel:Ne(r.base),taskLabel:i,executor:a,model:t.execution?.model},attrs:{context:r.base,"0x2f.taskId":t.id,"0x2f.status":t.status}}],m=mw(e),p=e.filter(g=>g.type==="task.answered"),h=e.find(g=>g.type==="task.closed"),v=o.at(-1);for(let g=0;g<o.length;g++){const I=o[g],N=ar(I.startedAt);if(N===void 0)continue;const S=hw(r.base,t.id,I.run),T=I.provider??a,x=ar(I.completedAt),D=x??r.now,w=[{ns:"fs.cwd",parts:[r.host,r.base],validFrom:N,validTo:D}];typeof I.externalSessionId=="string"&&I.externalSessionId&&w.push({ns:"agent.session",parts:[T,I.externalSessionId],validFrom:N,validTo:D}),I===v&&typeof t.pid=="number"&&w.push({ns:"os.process",parts:[r.host,t.pid],validFrom:N,validTo:D}),l.push({...d,occurredAt:N,seq:`run:${I.run}`,kind:"began",subject:{type:"execution",id:S},claims:w,core:{machineId:r.machine.id,sessionId:n,label:i?`${s} · ${i} · RUN ${I.run}`:`${s} · RUN ${I.run}`,executor:T,model:I.model??t.execution?.model,depth:0},attrs:{"0x2f.run":I.run,"0x2f.provider":T,"0x2f.workspace":r.base,...I.requestedProvider?{"0x2f.requestedProvider":I.requestedProvider}:{},...t.pid!==void 0&&I===v?{"0x2f.workerPid":t.pid}:{}}});let $=!1,E=0;for(const C of m.get(I.run)??[]){E++;const P=ar(C.at);if(P===void 0||P<N)continue;const L=`run:${I.run}:${E}`;if(C.type==="tool.started")l.push({...d,occurredAt:P,seq:L,kind:"progressed",subject:{type:"execution",id:S},core:{measures:{[Z.interactions]:1}},attrs:{"0x2f.tool":C.name}});else if(C.type==="progress")l.push({...d,occurredAt:P,seq:L,kind:"progressed",subject:{type:"execution",id:S}});else if(C.type==="needs_user"&&C.blockedOn){if($)continue;$=!0,l.push({...d,occurredAt:P,seq:L,kind:"blocked",subject:{type:"execution",id:S},core:{blockedOn:xf(C.blockedOn)},attrs:{"0x2f.blockedOn":C.blockedOn.type}})}else if(C.type==="permission.resolved"||C.type==="task.updated"&&typeof C.grant=="string"){if(!$)continue;$=!1,l.push({...d,occurredAt:P,seq:L,kind:"resumed",subject:{type:"execution",id:S},attrs:{"0x2f.grant":C.grant}})}}const B=(C,P,L)=>l.push({...d,occurredAt:C,seq:L,kind:"ended",subject:{type:"execution",id:S},core:P});if(I.outcome==="ready"&&x!==void 0)B(x,{outcome:"completed"},`run:${I.run}:end`);else if(I.outcome==="failed"&&x!==void 0)B(x,{outcome:"error",failureCode:(I.failure?.kind??t.failure?.kind??"unclassified").toUpperCase(),failureMessage:I.error??t.error??"Run failed"},`run:${I.run}:end`);else if(I.outcome==="needs_you"&&x!==void 0){$||($=!0,l.push({...d,occurredAt:x,seq:`run:${I.run}:block`,kind:"blocked",subject:{type:"execution",id:S},core:{blockedOn:xf(I.blockedOn)}}));const C=bw(x,p,o[g+1],h);C!==void 0&&B(C,{outcome:"interrupted"},`run:${I.run}:end`)}}if(h){const g=ar(h.at);g!==void 0&&l.push({...d,occurredAt:g,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return l}function bw(t,e,r,n){const o=[...e.map(i=>ar(i.at)),ar(r?.startedAt),ar(n?.at)];let s;for(const i of o)i===void 0||i<t||(s===void 0||i<s)&&(s=i);return s}function ww(t){const e=[];for(const r of t.split(`
3
- `))if(r.trim())try{const n=JSON.parse(r);n&&typeof n.type=="string"&&e.push(n)}catch{}return e}const Km=".work";function Gm(){const t=process.env.WORK_ROOTS;return t?t.split(/[:,]/).map(e=>e.trim()).filter(Boolean):[xn()]}const If=t=>ge(ue(t,Km,"tasks")),Aw=new Set(["Desktop","Documents","Downloads"]);async function qm(){const t=new Set,e=!process.env.WORK_ROOTS;for(const r of Gm()){if(If(r)){t.add(r);continue}let n;try{n=await Ze(r,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory()||o.name.startsWith(".")||e&&Aw.has(o.name))continue;const s=ue(r,o.name);If(s)&&t.add(s)}}return[...t].sort()}async function Sw(){const t=[];for(const e of await qm()){const r=ue(e,Km,"tasks");let n;try{n=await Ze(r,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory())continue;const s=ue(r,o.name,"task.json");ge(s)&&t.push({base:e,slug:o.name,taskPath:s,eventsPath:ue(r,o.name,"events.jsonl")})}}return t}const Of=new Map;async function kw(t,e,r){let n;try{n=await sn(t.taskPath)}catch{return null}const o=await sn(t.eventsPath).catch(()=>null),s=Math.max(n.mtimeMs,o?.mtimeMs??0),i=`${n.mtimeMs}:${n.size}:${o?.mtimeMs??0}:${o?.size??0}`,a=Of.get(t.taskPath);if(a&&a.stamp===i)return{envelopes:a.envelopes,touchedAt:s};let c;try{c=JSON.parse(await _r(t.taskPath,"utf8"))}catch{return null}let u=[];try{u=ww(await _r(t.eventsPath,"utf8"))}catch{}const d=vw(c,u,{machine:e,base:t.base,host:Ur(),observedAt:Date.now(),now:r}).map(Zt);return Of.set(t.taskPath,{stamp:i,envelopes:d}),{envelopes:d,touchedAt:s}}async function Ew(t,e){const r=Vr(),n=await Sw(),o=[];for(const s of n){const i=await kw(s,r,e);if(i&&!(i.touchedAt<t))for(const a of i.envelopes)a.occurredAt>=t&&a.occurredAt<=e&&o.push(a)}return o}async function Cf(){const t=Gm(),e=await qm();return{available:e.length>0,present:t.some(r=>ge(r)),roots:t,workspaces:e}}const en="claude-code",xw={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"partial"},zm="claude-code";class lr extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const Ym=t=>`claude:${t}`;function Iw(t,e){const r=t,n=typeof r?.version=="string"?r.version:void 0;if(!r||typeof r!="object")throw new lr("registry entry is not an object",e,n);if(typeof r.sessionId!="string"||!r.sessionId)throw new lr("registry entry has no sessionId",e,n);if(typeof r.pid!="number"||!Number.isFinite(r.pid))throw new lr("registry entry has no numeric pid",e,n);if(typeof r.startedAt!="number"||!Number.isFinite(r.startedAt))throw new lr("registry entry has no numeric startedAt",e,n);return r}function Ow(t,e,r){const n=[{ns:"agent.session",parts:[zm,t.sessionId],validFrom:t.startedAt,validTo:r.now},{ns:"os.process",parts:[r.host,t.pid],validFrom:t.startedAt,validTo:r.now}];return{source:{id:en,instance:r.host},occurredAt:t.startedAt,observedAt:r.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:Ym(t.sessionId)},claims:n,basis:"measured",core:{machineId:r.machine.id,label:t.name??Ne(t.cwd??"").toUpperCase(),projectLabel:t.cwd?Ne(t.cwd):void 0,taskLabel:t.name,executor:en},attrs:{context:t.cwd,"claude.sessionId":t.sessionId,"claude.pid":t.pid,"claude.procStart":t.procStart,"claude.version":t.version,"claude.kind":t.kind,"claude.entrypoint":t.entrypoint,"claude.status":t.status,"claude.waitingFor":t.waitingFor},provenance:{path:e,recordId:t.sessionId,sourceVersion:t.version},seq:"registry"}}const Cw=new Set(["stop_hook_summary","turn_duration"]),Nw="The transcript has not been written to for longer than the live window, so the process that owned it is gone and the turn ended at its last record.",cr=t=>typeof t=="number"&&Number.isFinite(t)?t:0,Bn=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function Tw(t){const e=[];for(const r of t.split(`
4
- `))if(r.trim())try{const n=JSON.parse(r);n&&typeof n=="object"&&e.push(n)}catch{}return e}function $w(t){if(!t)return{};const e=t.output_tokens_details;return{[Z.tokensInput]:cr(t.input_tokens)+cr(t.cache_creation_input_tokens),[Z.tokensOutput]:cr(t.output_tokens),[Z.tokensCacheRead]:cr(t.cache_read_input_tokens),[Z.tokensReasoning]:cr(e?.thinking_tokens),[Z.steps]:1}}function Bw(t,e){const r=t.filter(N=>Bn(N.timestamp)!==void 0);if(r.length===0)throw new lr("transcript has no timestamped records",e.path);const n=t.find(N=>typeof N.sessionId=="string")?.sessionId;if(n&&n!==e.sessionId)throw new lr(`transcript names session ${n} but is filed under ${e.sessionId}`,e.path);const o=t.find(N=>typeof N.version=="string")?.version,s=t.find(N=>typeof N.cwd=="string")?.cwd??"",i=t.find(N=>typeof N.gitBranch=="string")?.gitBranch,a=t.find(N=>typeof N.entrypoint=="string")?.entrypoint,c=Ne(s).toUpperCase(),u=e.sessionId,d=Ym(u),l=Bn(r[0].timestamp),m=Bn(r[r.length-1].timestamp),h={source:{id:en,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},v=(N,S)=>({path:e.path,...N?{recordId:N}:{},...S!==void 0?{index:S}:{},...o?{sourceVersion:o}:{}}),g=[{...h,occurredAt:l,kind:"began",subject:{type:"session",id:d},claims:[{ns:"agent.session",parts:[zm,u],validFrom:l,validTo:m}],core:{machineId:e.machine.id,label:c,projectLabel:s?Ne(s):void 0,executor:en},attrs:{context:s,"claude.sessionId":u,"claude.gitBranch":i,"claude.entrypoint":a,"claude.version":o},provenance:v(u),seq:"session"}],I=[];for(let N=0;N<t.length;N++){const S=t[N];S.type==="user"&&typeof S.promptSource=="string"&&Bn(S.timestamp)!==void 0&&I.push(N)}if(I.length===0)throw new lr(`transcript has ${t.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,e.path,o);for(let N=0;N<I.length;N++){const S=I[N],T=N+1<I.length?I[N+1]:t.length,x=N+1,D=`${d}:turn:${x}`,w=Bn(t[S].timestamp),$=t.slice(S,T).some(U=>U.isSidechain===!0);let E,B=w,C,P=!1;const L=[];for(let U=S;U<T;U++){const V=t[U],z=Bn(V.timestamp);if(z===void 0)continue;const se=V.type==="assistant"||V.type==="user"&&Array.isArray(V.message?.content);if(se&&z>B&&(B=z),se?(C=V,P=!1):V.type==="system"&&Cw.has(V.subtype??"")&&(P=!0),V.type==="assistant"&&V.message){E??=V.message.model;const Ae=(Array.isArray(V.message.content)?V.message.content:[]).filter(Ie=>!!Ie&&typeof Ie=="object"&&Ie.type==="tool_use"),_e={...$w(V.message.usage)};Ae.length&&(_e[Z.interactions]=Ae.length),L.push({...h,occurredAt:z,kind:"progressed",subject:{type:"execution",id:D},core:{measures:_e},attrs:{...Ae.length?{"claude.tools":Ae.map(Ie=>Ie.name??"unknown")}:{},...V.message.model?{"claude.model":V.message.model}:{},...V.requestId?{"claude.requestId":V.requestId}:{},...V.message.stop_reason?{"claude.stopReason":V.message.stop_reason}:{},...V.message.usage?{"claude.usage.inputTokens":cr(V.message.usage.input_tokens),"claude.usage.outputTokens":cr(V.message.usage.output_tokens),"claude.usage.cacheReadTokens":cr(V.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":cr(V.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":V.message.usage.service_tier}:{}},provenance:v(V.uuid,U),seq:V.uuid??`a${U}`})}else if(V.type==="user"&&V.message&&Array.isArray(V.message.content)){const ve=V.message.content.filter(Ae=>!!Ae&&typeof Ae=="object"&&Ae.is_error===!0).length;ve&&L.push({...h,occurredAt:z,kind:"progressed",subject:{type:"execution",id:D},core:{measures:{[Z.errors]:ve}},provenance:v(V.uuid,U),seq:V.uuid??`e${U}`})}}if(g.push({...h,occurredAt:w,kind:"began",subject:{type:"execution",id:D},core:{machineId:e.machine.id,sessionId:d,label:`${c} · TURN ${x}`,executor:en,model:E,depth:$?1:0},attrs:{"claude.turn":x,"claude.promptSource":t[S].promptSource,"claude.promptId":t[S].promptId,...$?{"claude.isSidechain":!0}:{}},provenance:v(t[S].uuid,S),seq:`turn:${x}`}),g.push(...L),N+1<I.length||P)g.push({...h,occurredAt:B,kind:"ended",subject:{type:"execution",id:D},core:{outcome:"completed"},provenance:v(t[S].uuid,S),seq:`turn:${x}:end`});else if(e.closeOpenTurns){const U=C?.type==="assistant"&&(C.message?.stop_reason==="end_turn"||C.message?.stop_reason==="stop_sequence");g.push({...h,occurredAt:B,kind:"ended",subject:{type:"execution",id:D},core:{outcome:U?"completed":"interrupted"},basis:"inferred",assumption:Nw,provenance:v(t[S].uuid,S),seq:`turn:${x}:end`})}}return g}function Xl(){return process.env.CLAUDE_HOME||ue(xn(),".claude")}const nu=()=>ue(Xl(),"sessions"),Rw=()=>ue(Xl(),"projects"),Nf=new Map;async function Mw(t,e,r){const n=nu();if(!ge(n))return;r.identityAvailable=!0;let o;try{o=await Ze(n)}catch(s){r.problems.push({path:n,message:String(s)});return}for(const s of o){if(!s.endsWith(".json"))continue;const i=ue(n,s);try{const a=Iw(JSON.parse(await _r(i,"utf8")),i);r.envelopes.push(Zt(Ow(a,i,{machine:t,host:Ur(),observedAt:e,now:e}))),r.registryEntries++}catch(a){r.problems.push({path:i,message:a instanceof Error?a.message:String(a),sourceVersion:a instanceof lr?a.sourceVersion:void 0})}}}async function Xm(){const t=Rw();if(!ge(t))return[];const e=[];let r;try{r=await Ze(t)}catch{return e}for(const n of r){let o;try{o=await Ze(ue(t,n))}catch{continue}for(const s of o)s.endsWith(".jsonl")&&e.push({path:ue(t,n,s),sessionId:s.slice(0,-6),project:n})}return e}async function _w(t,e,r,n){const o=await Xm();if(o.length!==0){n.storedAvailable=!0;for(const s of o){let i;try{i=await sn(s.path)}catch{continue}if(i.mtimeMs<e)continue;const a=Date.now()-i.mtimeMs>Yl,c=`${i.mtimeMs}:${i.size}:${a}`,u=Nf.get(s.path);let d;if(u&&u.stamp===c)d=u.envelopes;else try{const l=Tw(await _r(s.path,"utf8"));d=Bw(l,{machine:t,host:Ur(),observedAt:Date.now(),path:s.path,sessionId:s.sessionId,closeOpenTurns:a}).map(Zt),Nf.set(s.path,{stamp:c,envelopes:d})}catch(l){n.transcriptsFailed++,n.problems.push({path:s.path,message:l instanceof Error?l.message:String(l),sourceVersion:l instanceof lr?l.sourceVersion:void 0});continue}n.transcriptsRead++;for(const l of d)l.occurredAt>=e&&l.occurredAt<=r&&n.envelopes.push(l)}}}async function Jm(t,e){const r=Vr(),n=Date.now(),o={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await Mw(r,n,o),await _w(r,t,e,o),o}async function jw(t,e){return(await Jm(t,e)).envelopes}async function Tf(){const t=Xl(),e=ge(nu())?(await Ze(nu()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,r=(await Xm()).length;return{available:e>0||r>0,present:ge(t),home:t,registry:e,transcripts:r}}const Zo="codex",Dw={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"supported"},Lw="codex",Pw=10*6e4;class Yr extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const Uw=t=>`codex:${t}`,Yt=t=>typeof t=="number"&&Number.isFinite(t)?t:0,Se=t=>typeof t=="string"&&t?t:void 0,kc=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function Vw(t){const e=Yt(t.input_tokens),r=Yt(t.cached_input_tokens);return{[Z.tokensInput]:Math.max(0,e-r),[Z.tokensOutput]:Yt(t.output_tokens),[Z.tokensCacheRead]:r,[Z.tokensReasoning]:Yt(t.reasoning_output_tokens),[Z.steps]:1}}function Hw(t,e){const r=t.find(N=>N.type==="session_meta");if(!r||!r.payload)throw new Yr("rollout has no session_meta record",e.path);const n=r.payload,o=Se(n.cli_version),s=Se(n.session_id)??Se(n.id);if(s&&s!==e.sessionId)throw new Yr(`rollout names session ${s} but is filed under ${e.sessionId}`,e.path,o);const i=Se(n.cwd)??"",a=kc(n.timestamp)??kc(r.timestamp);if(a===void 0)throw new Yr("session_meta has no parseable timestamp",e.path,o);const c=Ne(i).toUpperCase(),u=Uw(e.sessionId),l={source:{id:Zo,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},m=(N,S)=>({path:e.path,...N?{recordId:N}:{},...S!==void 0?{index:S}:{},...o?{sourceVersion:o}:{}}),p=[];let h=null,v=a,g=0;for(let N=0;N<t.length;N++){const S=t[N],T=kc(S.timestamp);T!==void 0&&T>v&&(v=T);const x=S.payload;if(!x)continue;if(S.type==="turn_context"){h&&Se(x.turn_id)===h.turnId&&(h.model??=Se(x.model),h.effort??=Se(x.effort));continue}if(S.type!=="event_msg")continue;const D=Se(x.type);if(D==="task_started"){const $=Se(x.turn_id);if(!$||T===void 0)throw new Yr(`task_started at ordinal ${S.ordinal} is missing turn_id or timestamp`,e.path,o);h={turnId:$,startedAt:T,interior:[],lastAt:T},p.push(h);continue}if(D==="task_complete"){const $=Se(x.turn_id),E=p.find(B=>B.turnId===$)??h;if(E&&T!==void 0){E.completedAt=T;const B=x.error;E.outcome=B?"error":"completed",E.failureMessage=B?Se(B.message):void 0,E.lastAt=Math.max(E.lastAt,T)}E===h&&(h=null);continue}if(D==="turn_aborted"){const $=Se(x.turn_id);if(!$||T===void 0)throw new Yr(`turn_aborted at ordinal ${S.ordinal} is missing turn_id or timestamp`,e.path,o);const E=p.find(B=>B.turnId===$);E&&E.completedAt===void 0&&(E.completedAt=T,E.outcome="interrupted",E.lastAt=Math.max(E.lastAt,T)),E===h&&(h=null);continue}if(D==="token_count"||D==="item_completed"){if(!h){g++;continue}if(T===void 0)continue}else continue;const w=`${u}:turn:${h.turnId}`;if(D==="token_count"){const E=x.info?.last_token_usage;if(!E)continue;h.lastAt=Math.max(h.lastAt,T),h.interior.push({...l,occurredAt:T,kind:"progressed",subject:{type:"execution",id:w},core:{measures:Vw(E)},attrs:{"codex.usage.inputTokens":Yt(E.input_tokens),"codex.usage.cachedInputTokens":Yt(E.cached_input_tokens),"codex.usage.cacheWriteInputTokens":Yt(E.cache_write_input_tokens),"codex.usage.outputTokens":Yt(E.output_tokens),"codex.usage.reasoningOutputTokens":Yt(E.reasoning_output_tokens)},provenance:m(void 0,S.ordinal),seq:`o${S.ordinal??N}`});continue}if(D==="item_completed"){const $=x.item,E=Se($?.type);if(!$||!E)continue;h.lastAt=Math.max(h.lastAt,T);let B,C;if(E==="CommandExecution"){const P=Yt($.exit_code);B={[Z.interactions]:1,...P!==0?{[Z.errors]:1}:{}},C={"codex.itemType":E,"codex.exitCode":P,...$.process_id!==void 0?{"codex.processId":$.process_id}:{},...Se($.status)?{"codex.status":$.status}:{}}}else if(E==="McpToolCall"){const P=Se($.status)==="failed"||Se($.status)==="error";B={[Z.interactions]:1,...P?{[Z.errors]:1}:{}},C={"codex.itemType":E,"codex.tool":[Se($.server),Se($.tool)].filter(Boolean).join("."),...Se($.status)?{"codex.status":$.status}:{}}}else if(E==="WebSearch")B={[Z.interactions]:1},C={"codex.itemType":E};else if(E==="FileChange"){const P=$.changes;B={[Z.interactions]:1},C={"codex.itemType":E,...P&&typeof P=="object"?{"codex.fileChanges":Object.entries(P).map(([L,te])=>({path:L,kind:Se(te?.type)}))}:{}}}else continue;h.interior.push({...l,occurredAt:T,kind:"progressed",subject:{type:"execution",id:w},core:{measures:B},attrs:C,provenance:m(Se($.id),S.ordinal),seq:`o${S.ordinal??N}`})}}if(p.length===0&&g>0)throw new Yr(`rollout has ${g} work records but no task_started marker`,e.path,o);const I=[{...l,occurredAt:a,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[Lw,e.sessionId],validFrom:a,validTo:v}],core:{machineId:e.machine.id,label:c,projectLabel:e.projectLabel??(i?Ne(i):void 0),taskLabel:e.taskLabel,executor:Zo},attrs:{context:i,"codex.sessionId":e.sessionId,"codex.cliVersion":o,"codex.originator":Se(n.originator),"codex.source":Se(n.source),"codex.modelProvider":Se(n.model_provider),...Fw(n.git)},provenance:m(e.sessionId,r.ordinal),seq:"session"}];for(let N=0;N<p.length;N++){const S=p[N],T=`${u}:turn:${S.turnId}`;I.push({...l,occurredAt:S.startedAt,kind:"began",subject:{type:"execution",id:T},core:{machineId:e.machine.id,sessionId:u,label:`${c} · TURN ${N+1}`,executor:Zo,model:S.model,depth:0},attrs:{"codex.turnId":S.turnId,...S.effort?{"codex.effort":S.effort}:{}},provenance:m(S.turnId),seq:`turn:${S.turnId}`}),I.push(...S.interior),S.completedAt!==void 0?I.push({...l,occurredAt:S.completedAt,kind:"ended",subject:{type:"execution",id:T},core:{outcome:S.outcome??"completed",...S.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:S.failureMessage??"turn failed"}:{}},provenance:m(S.turnId),seq:`turn:${S.turnId}:end`}):e.now-v>Pw&&I.push({...l,basis:"inferred",assumption:"A rollout untouched for 10 minutes belongs to a dead process, so a turn left open in it was interrupted, not still running. Its end is the last instant the rollout moved.",occurredAt:S.lastAt,kind:"ended",subject:{type:"execution",id:T},core:{outcome:"interrupted"},provenance:m(S.turnId),seq:`turn:${S.turnId}:end`})}return I}function Fw(t){if(!t||typeof t!="object")return{};const e=t;return{...Se(e.branch)?{"codex.gitBranch":e.branch}:{},...Se(e.commit_hash)?{"codex.gitCommit":e.commit_hash}:{},...Se(e.repository_url)?{"codex.gitOriginUrl":e.repository_url}:{}}}function Jl(){return process.env.CODEX_HOME||ue(xn(),".codex")}const Zm=()=>ue(Jl(),"sessions"),Ww=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,Ec=new Map,Kw=new Set(["CommandExecution","McpToolCall","WebSearch","FileChange"]);function Gw(t){const e={timestamp:t.timestamp,ordinal:t.ordinal,type:t.type},r=t.payload;if(!r)return t.type==="session_meta"?{...e}:void 0;if(t.type==="session_meta"){const a=r.git;return{...e,payload:{session_id:r.session_id,id:r.id,timestamp:r.timestamp,cwd:r.cwd,originator:r.originator,cli_version:r.cli_version,source:r.source,model_provider:r.model_provider,git:a?{branch:a.branch,commit_hash:a.commit_hash,repository_url:a.repository_url}:void 0}}}if(t.type==="turn_context")return{...e,payload:{turn_id:r.turn_id,model:r.model,effort:r.effort}};if(t.type!=="event_msg")return;const n=r.type;if(n==="task_started"||n==="turn_aborted")return{...e,payload:{type:n,turn_id:r.turn_id}};if(n==="task_complete"){const a=r.error;return{...e,payload:{type:n,turn_id:r.turn_id,...a?{error:{message:a.message}}:{}}}}if(n==="token_count"){const c=r.info?.last_token_usage;return c?{...e,payload:{type:n,info:{last_token_usage:{input_tokens:c.input_tokens,cached_input_tokens:c.cached_input_tokens,cache_write_input_tokens:c.cache_write_input_tokens,output_tokens:c.output_tokens,reasoning_output_tokens:c.reasoning_output_tokens}}}}:{...e,payload:{type:n}}}if(n!=="item_completed")return;const o=r.item,s=typeof o?.type=="string"?o.type:void 0;if(!o||!s||!Kw.has(s))return{...e,payload:{type:n,item:s?{type:s}:void 0}};const i={type:s,id:o.id};if(s==="CommandExecution")i.process_id=o.process_id,i.exit_code=o.exit_code,i.status=o.status;else if(s==="McpToolCall")i.server=o.server,i.tool=o.tool,i.status=o.status;else if(s==="FileChange"){const a=o.changes;i.changes=a?Object.fromEntries(Object.entries(a).map(([c,u])=>[c,{type:u?.type}])):void 0}return{...e,payload:{type:n,item:i}}}async function qw(t,e=0){const r=[];let n=[],o=0,s=0,i=e;const a=(c,u)=>{if(u===0)return;const d=Buffer.concat(c,Math.min(u,1024)).subarray(0,1024).toString("utf8"),l=/^\s*\{\s*"timestamp"\s*:\s*"(?:\\.|[^"])*"\s*,\s*"type"\s*:\s*"([^"]+)"/.exec(d)?.[1];if(l&&l!=="session_meta"&&l!=="turn_context"&&l!=="event_msg")return;const m=Buffer.concat(c,u).toString("utf8");if(m.trim())try{const p=JSON.parse(m);if(!p||typeof p!="object")return;const h=Gw(p);h&&r.push(h)}catch{}};for await(const c of jm(t,{start:e})){const u=Buffer.isBuffer(c)?c:Buffer.from(c),d=s;s+=u.length;let l=0;for(;;){const m=u.indexOf(10,l);if(m<0)break;const p=u.subarray(l,m);a([...n,p],o+p.length),n=[],o=0,l=m+1,i=e+d+l}if(l<u.length){const m=u.subarray(l);n.push(m),o+=m.length}}return{records:r,offset:i,bytesRead:s}}function zw(t,e,r){return t.occurredAt>=e&&t.occurredAt<=r||t.subject.type==="session"&&t.kind==="began"&&(typeof t.core?.projectLabel=="string"||typeof t.core?.taskLabel=="string")}function Yw(t,e=Jl()){const r=ue(e,"state_5.sqlite");if(!ge(r))return new Map;let n;try{n=new Bs(r,{readOnly:!0}),n.exec("PRAGMA query_only = ON");const o=n.prepare("SELECT name FROM threads WHERE id = ? LIMIT 1");let s;try{s=n.prepare(`SELECT projects.name AS projectName
1
+ import{existsSync as ve,createReadStream as Qm,statSync as ka,mkdirSync as pu,chmodSync as Ea,writeFileSync as od,renameSync as id,rmSync as ey,readFileSync as ad}from"node:fs";import{createInterface as Fb}from"node:readline";import{createServer as ty}from"node:http";import{join as ue,isAbsolute as hu,relative as Mc,sep as mu,dirname as Oi,resolve as Lo,normalize as Wb,extname as Kb}from"node:path";import{fileURLToPath as Gb}from"node:url";import{stat as fn,readdir as Qe,readFile as Ur}from"node:fs/promises";import{hostname as qb,homedir as Bn}from"node:os";import zb from"node:zlib";import{createHash as vs,randomBytes as pn,webcrypto as Yb,X509Certificate as so,timingSafeEqual as Xb,verify as Jb,createPublicKey as Zb}from"node:crypto";import{execFileSync as Qb,execFile as ew,spawn as tw}from"node:child_process";import{DatabaseSync as Uo}from"node:sqlite";import{isMainThread as ry,workerData as Ni,parentPort as Jn,Worker as ny}from"node:worker_threads";import{promisify as rw}from"node:util";import{createServer as nw}from"node:https";function sw(t){const e=new AbortController,r={controller:e,consumers:0,settled:!1,promise:t(e.signal)};return r.promise.then(()=>{r.settled=!0},()=>{r.settled=!0}),r}function $f(t,e){return t.consumers++,new Promise((r,n)=>{let s=!1;const o=a=>{s||(s=!0,e?.removeEventListener("abort",i),t.consumers--,!t.settled&&t.consumers===0&&t.controller.abort(),a())},i=()=>o(()=>n(new Error("analytical read cancelled")));e?.addEventListener("abort",i,{once:!0}),t.promise.then(a=>o(()=>r(a)),a=>o(()=>n(a))),e?.aborted&&i()})}const Bf=["machine","session","execution","process","artifact"];function ow(t){return`${t.ns}|${t.parts.join("|")}`}const z={interactions:"interactions",steps:"steps",errors:"errors",retries:"retries",cpuMs:"cpu.ms",cpuUtilization:"cpu.utilization",tokensInput:"tokens.input",tokensOutput:"tokens.output",tokensCacheRead:"tokens.cacheRead",tokensReasoning:"tokens.reasoning"},iw=[{a:"execution",b:"process",kind:"ran-as"},{a:"session",b:"process",kind:"ran-as"},{a:"execution",b:"session",kind:"ran-as"},{a:"session",b:"session",kind:"same-as"},{a:"execution",b:"execution",kind:"same-as"},{a:"machine",b:"machine",kind:"same-as"},{a:"process",b:"process",kind:"same-as"}];function _f(t,e){for(const r of iw){if(t.subjectType===r.a&&e.subjectType===r.b)return{kind:r.kind,from:t,to:e};if(e.subjectType===r.a&&t.subjectType===r.b)return{kind:r.kind,from:e,to:t}}return null}const aw=(t,e)=>t.validFrom<=e.validTo&&e.validFrom<=t.validTo;function cw(t,e){const r=Math.max(t.validFrom,e.validFrom),n=Math.min(t.validTo,e.validTo);if(n<r)return 0;const s=Math.max(t.validTo,e.validTo)-Math.min(t.validFrom,e.validFrom);return s<=0?1:(n-r)/s}const uw=.5;function lw(t,e){return aw(t,e)?cw(t,e)>=uw?2:1:0}const Rt=t=>`${t.subjectType}:${t.subjectId}`,dw="inferred",fw="Two observers asserted the same identity claim over overlapping validity windows, and each was the other's only candidate at the strongest available evidence tier (two lifetimes that substantially coincide beat a bare overlap). The claims themselves are measured; the identification is inferred.";function pw(t){const e=new Map;for(const o of t){const i=e.get(o.key);i?i.push(o):e.set(o.key,[o])}const r=[],n=[];let s=0;for(const[o,i]of[...e.entries()].sort(([a],[c])=>a<c?-1:1)){const a=new Map;for(const p of i){const h=Rt(p),g=a.get(h);if(!g){a.set(h,{...p});continue}g.validFrom=Math.min(g.validFrom,p.validFrom),g.validTo=Math.max(g.validTo,p.validTo)}const c=[...a.values()].sort((p,h)=>Rt(p)<Rt(h)?-1:1);if(c.length<2){s++;continue}const u=[];let l=!1;for(let p=0;p<c.length;p++)for(let h=p+1;h<c.length;h++){const g=c[p],v=c[h];if(g.sourceId===v.sourceId)continue;const b=lw(g,v);if(b!==0){if(!_f(g,v)){l=!0;continue}u.push({x:g,y:v,tier:b})}}const d=new Map;for(const p of u)for(const h of[p.x,p.y]){const g=Rt(h);d.set(g,Math.max(d.get(g)??0,p.tier))}const m=new Map;for(const p of u)for(const h of[p.x,p.y]){const g=Rt(h);d.get(g)===p.tier&&m.set(g,(m.get(g)??0)+1)}if(u.length===0){n.push({key:o,reason:l?"no-pairing-defined":"no-window-overlap",subjects:[...a.keys()].sort()});continue}for(const{x:p,y:h,tier:g}of u){if(d.get(Rt(p))!==g||d.get(Rt(h))!==g)continue;if(m.get(Rt(p))!==1||m.get(Rt(h))!==1){n.push({key:o,reason:"multiple-candidates",subjects:[Rt(p),Rt(h)].sort()});continue}const v=_f(p,h);r.push({from:{type:v.from.subjectType,id:v.from.subjectId},to:{type:v.to.subjectType,id:v.to.subjectId},kind:v.kind,basis:dw,assumption:fw,via:o})}}return{relationships:r,ambiguous:n,unmatched:s,considered:e.size}}async function hw(t,e,r,n,s){const o=[];let i=0,a=0;for(const c of e){const u=Date.now();try{const l=await c.collect(r,n),d=t.append(l);i+=d.inserted,a+=d.duplicate,o.push({id:c.id,ok:!0,collected:l.length,inserted:d.inserted,duplicate:d.duplicate,ms:Date.now()-u})}catch(l){o.push({id:c.id,ok:!1,collected:0,inserted:0,duplicate:0,error:l instanceof Error?l.message:String(l),ms:Date.now()-u})}s?.(o[o.length-1])}return{sources:o,inserted:i,duplicate:a}}const sy=1e3,Mf=60*sy;function fe(t){if(!Number.isFinite(t)||t<=0)return"0m";if(t<Mf)return`${Math.max(1,Math.round(t/sy))}s`;const e=Math.round(t/Mf),r=Math.floor(e/60),n=e%60;return r===0?`${n}m`:n===0?`${r}h`:`${r}h ${n}m`}function Ye(t){if(!Number.isFinite(t))return"—";const e=Math.abs(t);return e>=1e9?`${(t/1e9).toFixed(e>=1e10?0:2)}B`:e>=1e6?`${(t/1e6).toFixed(e>=1e7?0:2)}M`:e>=1e3?`${(t/1e3).toFixed(e>=1e4?0:1)}k`:String(Math.round(t))}function mw(t,e="NOT OBSERVED"){return t===void 0?e:Ye(t)}function Ti(t,e){if(e<=0)return"—";const r=t/e*100;return r>0&&r<1?"<1%":`${Math.round(r)}%`}function yw(t){return t===void 0||!Number.isFinite(t)?"—":t>=1e9?`${(t/1e9).toFixed(1)} GB`:t>=1e6?`${(t/1e6).toFixed(0)} MB`:t>=1e3?`${(t/1e3).toFixed(0)} KB`:`${t} B`}function Rf(t){const e=new Date(t);return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}function Be(t){const e=t.split("/").filter(Boolean);return e[e.length-1]??t}const cd="deepseek-harness",gw={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"supported",waits:"supported",model:"supported",context:"supported",outcome:"supported"},De=t=>typeof t=="number"&&Number.isFinite(t)?t:0,ft=t=>typeof t=="string"?t:void 0;function vw(t){const e=t.split("/").filter(Boolean);return(e[e.length-1]??t).toUpperCase()}function bw(t,e){const r=[],n=t[0];if(!n||n.type!=="session"||!n.id)return r;const s=n.id,o=n.cwd??"",i=De(n.createdAt),a=De(n.delegationDepth),c=vw(o);let u="deepseek",l,d;for(const k of t)if(k.type==="request/context"&&k.data?(u=ft(k.data.provider)??u,l=ft(k.data.model)??l):k.type==="session/title"&&k.data&&(d=ft(k.data.title)??d),l&&d)break;const p={source:{id:cd,instance:e.instance},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let h=i;for(const k of t){const w=De(k.time);w>h&&(h=w)}const g={ns:"fs.cwd",parts:[e.host,o],validFrom:i,validTo:Math.max(i,h)};r.push({...p,occurredAt:i,seq:"session",kind:"began",subject:{type:"session",id:s},claims:o?[g]:void 0,core:{machineId:e.machine.id,label:d,projectLabel:o?Be(o):void 0,taskLabel:d,executor:u,model:l,depth:a},attrs:{context:o,"dsh.delegationDepth":a}});const v=k=>`${s}:turn:${k}`;let b=null;const _=new Map,E=new Map;let I=i;for(const k of t){const w=De(k.time)||I;if(w<i)continue;I=w;const N=k.data??{},$=k.seq??`t${w}`,P=C=>({type:"execution",id:v(C)});switch(k.type){case"turn/start":{const C=De(N.turn);b=C,r.push({...p,occurredAt:w,seq:$,kind:"began",subject:P(C),core:{machineId:e.machine.id,sessionId:s,label:d?`${c} · ${d}`:c,executor:u,model:l,depth:a},attrs:{"dsh.turn":C}});break}case"turn/end":{const C=De(N.turn),T=N.reason,R=T?.kind;if(R==="error"){const H=T?.error??{};r.push({...p,occurredAt:w,seq:$,kind:"ended",subject:P(C),core:{outcome:"error",failureCode:ft(H.code)??"ERROR",failureMessage:ft(H.message)??"Run failed"},attrs:{"dsh.endReason":R}})}else r.push({...p,occurredAt:w,seq:$,kind:"ended",subject:P(C),core:{outcome:R==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":R??"completed"}});b===C&&(b=null);break}case"assistant/message":{const C=De(N.turn),T=N.usage;if(!T)break;const R={[z.tokensInput]:De(T.inputTokens),[z.tokensOutput]:De(T.outputTokens),[z.tokensCacheRead]:De(T.cacheReadTokens),[z.tokensReasoning]:De(T.reasoningTokens),[z.steps]:1};r.push({...p,occurredAt:w,seq:$,kind:"progressed",subject:P(C),core:{measures:R},attrs:{"dsh.inputTokens":De(T.inputTokens),"dsh.outputTokens":De(T.outputTokens),"dsh.cacheReadTokens":De(T.cacheReadTokens),"dsh.reasoningTokens":De(T.reasoningTokens)}});break}case"tool/call":{r.push({...p,occurredAt:w,seq:$,kind:"progressed",subject:P(De(N.turn)),core:{measures:{[z.interactions]:1}},attrs:{"dsh.tool":ft(N.name)}});break}case"tool/result":{const C=N.message;let T=!1;for(const R of C?.content??[])R.isError===!0&&(T=!0);T&&r.push({...p,occurredAt:w,seq:$,kind:"progressed",subject:P(De(N.turn)),core:{measures:{[z.errors]:1}}});break}case"llm/retry":{r.push({...p,occurredAt:w,seq:$,kind:"progressed",subject:P(De(N.turn)),core:{measures:{[z.retries]:1}}});break}case"approval/asked":{const C=ft(N.id);if(b===null)break;C&&_.set(C,b),r.push({...p,occurredAt:w,seq:$,kind:"blocked",subject:P(b),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":C}});break}case"approval/decided":{const C=ft(N.id),T=C?_.get(C):b;if(T==null)break;_.delete(C??""),r.push({...p,occurredAt:w,seq:$,kind:"resumed",subject:P(T),attrs:{"dsh.approvalId":C}});break}case"tool-workflow/agent-start":{if(b===null)break;const C=ft(N.childId);if(!C)break;const T=`${s}:agent:${C}`;E.set(`${ft(N.runId)}:${De(N.seq)}`,T),r.push({...p,occurredAt:w,seq:$,kind:"began",subject:{type:"execution",id:T},core:{machineId:e.machine.id,sessionId:s,label:ft(N.label)??`${c} · SUB`,executor:u,model:l,parentId:v(b),depth:a+1},attrs:{"dsh.childId":C}});break}case"tool-workflow/agent-end":{const C=`${ft(N.runId)}:${De(N.seq)}`,T=E.get(C);if(!T)break;E.delete(C);const R=ft(N.outcome);r.push({...p,occurredAt:w,seq:$,kind:"ended",subject:{type:"execution",id:T},core:R==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:R??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":R}});break}}}if(e.closeOpenTurns){const k="The session log has not been written to for longer than the live window, so the process that owned it is gone and any turn left open was cut off rather than still running.";b!==null&&r.push({...p,occurredAt:I,seq:"close:turn",kind:"ended",subject:{type:"execution",id:v(b)},core:{outcome:"interrupted"},basis:"inferred",assumption:k});for(const w of E.values())r.push({...p,occurredAt:I,seq:`close:${w}`,kind:"ended",subject:{type:"execution",id:w},core:{outcome:"interrupted"},basis:"inferred",assumption:k});r.push({...p,occurredAt:I,seq:"close:session",kind:"ended",subject:{type:"session",id:s},basis:"inferred",assumption:k})}return e.since!==void 0?r.filter(k=>k.occurredAt>=e.since):r}function ww(t){const e=[];let r=0;for(;r<t.length;){let n=t.indexOf(`
2
+ `,r);n===-1&&(n=t.length);const s=t.slice(r,n);if(r=n+1,s.length!==0&&!(s.startsWith('{"type":"reasoning-chunks"')||s.startsWith('{"type":"text-chunks"')||s.startsWith('{"type":"tool-call-chunks"')||s.startsWith('{"type":"assistant/chunk"')))try{e.push(JSON.parse(s))}catch{}}return e}function Sw(t){const e=JSON.stringify([t.source.id,t.source.instance,t.occurredAt,t.clock,t.kind,t.subject.type,t.subject.id,t.basis,t.seq??null,$i(t.core),$i(t.attrs)]);return vs("sha256").update(e).digest("hex").slice(0,32)}function $i(t){if(t==null)return null;if(Array.isArray(t))return t.map($i);if(typeof t!="object")return t;const e={};for(const r of Object.keys(t).sort())e[r]=$i(t[r]);return e}function Wt(t){const{seq:e,...r}=t;return{id:Sw(t),...r}}let jf;function Aw(){try{const t=Qb("/usr/sbin/scutil",["--get","LocalHostName"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();return/^[A-Za-z0-9-]{1,63}$/.test(t)?t:void 0}catch{return}}function oy(){return jf??=Aw()??qb().replace(/\.local$/i,""),jf}const Bi="host:";function kw(t){return`${Bi}${t}`}function Ew(t){return t.startsWith(Bi)?t.slice(Bi.length):void 0}function yu(t){return t.startsWith(Bi)}const xw=4247762216,Iw=407710288,Cw=407710303;function Ow(t){const e=[];for(let s=0;s+4<=t.length;s++){const o=t.readUInt32LE(s);(o===xw||o>=Iw&&o<=Cw)&&e.push(s)}if(e.length===0)return Buffer.alloc(0);const r=[];let n=0;for(;n<e.length;){let s=n+1,o=null;for(;;){const i=s<e.length?e[s]:t.length;try{o=zb.zstdDecompressSync(t.subarray(e[n],i));break}catch{if(s>=e.length)break;s++}}o?(r.push(o),n=s):n++}return Buffer.concat(r)}function ud(){return process.env.DSH_HOME||ue(Bn(),".dsh")}function Kr(){return oy()}function Gr(){const t=Kr();return{id:kw(t),name:t.toUpperCase(),kind:"laptop",firstSeenAt:0}}const Df=new Map;async function iy(){const t=ue(ud(),"sessions");if(!ve(t))return[];const e=[];for(const r of await Qe(t)){const n=ue(t,r);let s;try{s=await Qe(n)}catch{continue}for(const o of s){const i=ue(n,o,"session.jsonl.zstd");ve(i)&&e.push({path:i,workspace:r,sessionId:o})}}return e}const ld=10*6e4;async function Nw(t,e){const r=await fn(t.path),n=Df.get(t.path);if(n&&n.mtimeMs===r.mtimeMs&&n.size===r.size)return n.envelopes;const s=await Ur(t.path),o=Ow(s).toString("utf8"),i=ww(o),a=Date.now()-r.mtimeMs>ld,u=bw(i,{machine:e,host:Kr(),instance:ud(),observedAt:Date.now(),closeOpenTurns:a}).map(Wt);return Df.set(t.path,{mtimeMs:r.mtimeMs,size:r.size,envelopes:u}),u}async function Tw(t,e){const r=Gr(),n=await iy(),s=[];for(const o of n){let i;try{i=await fn(o.path)}catch{continue}if(!(i.mtimeMs<t))for(const a of await Nw(o,r))a.occurredAt>=t&&a.occurredAt<=e&&s.push(a)}return s}async function Pf(){const t=await iy(),e=ud();return{available:t.length>0,present:ve(e),home:e,sessions:t.length}}const _i="0x2f",$w={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"supported",model:"partial",context:"supported",outcome:"supported"},fr=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0},ay=(t,e)=>`2f:${t}#${e}`,Bw=(t,e,r)=>`${ay(t,e)}:run:${r}`;function Lf(t){return t?.type==="permission"?"approval":"input"}function _w(t){const e=new Map;for(const r of t){const n=typeof r.run=="number"?r.run:1,s=e.get(n);s?s.push(r):e.set(n,[r])}return e}function Mw(t,e){const r=e.find(o=>o.type==="run.started");let n;for(let o=e.length-1;o>=0;o--){const i=e[o];if(i.type==="run.completed"||i.type==="run.failed"||i.type==="needs_user"&&i.blockedOn){n=i;break}}let s;return n?.type==="run.completed"?s="ready":n?.type==="run.failed"?s="failed":n?s="needs_you":t.status==="needs_you"||t.status==="ready"||t.status==="failed"?s=t.status:t.status==="working"?s="working":s=t.error?"failed":"ready",{run:1,provider:t.execution?.provider??null,node:t.execution?.node??null,model:t.execution?.model,externalSessionId:t.execution?.externalSessionId,attempts:t.execution?.attempts??1,startedAt:r?.at,completedAt:n?.at,outcome:s,error:t.error??(n?.type==="run.failed"?n.error:void 0),blockedOn:n?.type==="needs_user"?n.blockedOn:void 0,failure:t.failure}}function Rw(t,e){return Array.isArray(t.runs)&&t.runs.length?t.runs:[Mw(t,e)]}function jw(t,e,r){if(typeof t.id!="number")return[];const n=ay(r.base,t.id),s=Rw(t,e),o=Be(r.base).toUpperCase(),i=t.title,a=t.execution?.provider??s.at(-1)?.provider??_i,c=fr(t.createdAt)??s.map(v=>fr(v.startedAt)).find(v=>v!==void 0);if(c===void 0)return[];const l={source:{id:_i,instance:r.base},observedAt:r.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},d=[{...l,occurredAt:c,kind:"began",subject:{type:"session",id:n},core:{machineId:r.machine.id,label:i,projectLabel:Be(r.base),taskLabel:i,executor:a,model:t.execution?.model},attrs:{context:r.base,"0x2f.taskId":t.id,"0x2f.status":t.status}}],m=_w(e),p=e.filter(v=>v.type==="task.answered"),h=e.find(v=>v.type==="task.closed"),g=s.at(-1);for(let v=0;v<s.length;v++){const b=s[v],_=fr(b.startedAt);if(_===void 0)continue;const E=Bw(r.base,t.id,b.run),I=b.provider??a,k=fr(b.completedAt),w=k??r.now,N=[{ns:"fs.cwd",parts:[r.host,r.base],validFrom:_,validTo:w}];typeof b.externalSessionId=="string"&&b.externalSessionId&&N.push({ns:"agent.session",parts:[I,b.externalSessionId],validFrom:_,validTo:w}),b===g&&typeof t.pid=="number"&&N.push({ns:"os.process",parts:[r.host,t.pid],validFrom:_,validTo:w}),d.push({...l,occurredAt:_,seq:`run:${b.run}`,kind:"began",subject:{type:"execution",id:E},claims:N,core:{machineId:r.machine.id,sessionId:n,label:i?`${o} · ${i} · RUN ${b.run}`:`${o} · RUN ${b.run}`,executor:I,model:b.model??t.execution?.model,depth:0},attrs:{"0x2f.run":b.run,"0x2f.provider":I,"0x2f.workspace":r.base,...b.requestedProvider?{"0x2f.requestedProvider":b.requestedProvider}:{},...t.pid!==void 0&&b===g?{"0x2f.workerPid":t.pid}:{}}});let $=!1,P=0;for(const T of m.get(b.run)??[]){P++;const R=fr(T.at);if(R===void 0||R<_)continue;const H=`run:${b.run}:${P}`;if(T.type==="tool.started")d.push({...l,occurredAt:R,seq:H,kind:"progressed",subject:{type:"execution",id:E},core:{measures:{[z.interactions]:1}},attrs:{"0x2f.tool":T.name}});else if(T.type==="progress")d.push({...l,occurredAt:R,seq:H,kind:"progressed",subject:{type:"execution",id:E}});else if(T.type==="needs_user"&&T.blockedOn){if($)continue;$=!0,d.push({...l,occurredAt:R,seq:H,kind:"blocked",subject:{type:"execution",id:E},core:{blockedOn:Lf(T.blockedOn)},attrs:{"0x2f.blockedOn":T.blockedOn.type}})}else if(T.type==="permission.resolved"||T.type==="task.updated"&&typeof T.grant=="string"){if(!$)continue;$=!1,d.push({...l,occurredAt:R,seq:H,kind:"resumed",subject:{type:"execution",id:E},attrs:{"0x2f.grant":T.grant}})}}const C=(T,R,H)=>d.push({...l,occurredAt:T,seq:H,kind:"ended",subject:{type:"execution",id:E},core:R});if(b.outcome==="ready"&&k!==void 0)C(k,{outcome:"completed"},`run:${b.run}:end`);else if(b.outcome==="failed"&&k!==void 0)C(k,{outcome:"error",failureCode:(b.failure?.kind??t.failure?.kind??"unclassified").toUpperCase(),failureMessage:b.error??t.error??"Run failed"},`run:${b.run}:end`);else if(b.outcome==="needs_you"&&k!==void 0){$||($=!0,d.push({...l,occurredAt:k,seq:`run:${b.run}:block`,kind:"blocked",subject:{type:"execution",id:E},core:{blockedOn:Lf(b.blockedOn)}}));const T=Dw(k,p,s[v+1],h);T!==void 0&&C(T,{outcome:"interrupted"},`run:${b.run}:end`)}}if(h){const v=fr(h.at);v!==void 0&&d.push({...l,occurredAt:v,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return d}function Dw(t,e,r,n){const s=[...e.map(i=>fr(i.at)),fr(r?.startedAt),fr(n?.at)];let o;for(const i of s)i===void 0||i<t||(o===void 0||i<o)&&(o=i);return o}function Pw(t){const e=[];for(const r of t.split(`
3
+ `))if(r.trim())try{const n=JSON.parse(r);n&&typeof n.type=="string"&&e.push(n)}catch{}return e}const cy=".work";function uy(){const t=process.env.WORK_ROOTS;return t?t.split(/[:,]/).map(e=>e.trim()).filter(Boolean):[Bn()]}const Uf=t=>ve(ue(t,cy,"tasks")),Lw=new Set(["Desktop","Documents","Downloads"]);async function ly(){const t=new Set,e=!process.env.WORK_ROOTS;for(const r of uy()){if(Uf(r)){t.add(r);continue}let n;try{n=await Qe(r,{withFileTypes:!0})}catch{continue}for(const s of n){if(!s.isDirectory()||s.name.startsWith(".")||e&&Lw.has(s.name))continue;const o=ue(r,s.name);Uf(o)&&t.add(o)}}return[...t].sort()}async function Uw(){const t=[];for(const e of await ly()){const r=ue(e,cy,"tasks");let n;try{n=await Qe(r,{withFileTypes:!0})}catch{continue}for(const s of n){if(!s.isDirectory())continue;const o=ue(r,s.name,"task.json");ve(o)&&t.push({base:e,slug:s.name,taskPath:o,eventsPath:ue(r,s.name,"events.jsonl")})}}return t}const Hf=new Map;async function Hw(t,e,r){let n;try{n=await fn(t.taskPath)}catch{return null}const s=await fn(t.eventsPath).catch(()=>null),o=Math.max(n.mtimeMs,s?.mtimeMs??0),i=`${n.mtimeMs}:${n.size}:${s?.mtimeMs??0}:${s?.size??0}`,a=Hf.get(t.taskPath);if(a&&a.stamp===i)return{envelopes:a.envelopes,touchedAt:o};let c;try{c=JSON.parse(await Ur(t.taskPath,"utf8"))}catch{return null}let u=[];try{u=Pw(await Ur(t.eventsPath,"utf8"))}catch{}const l=jw(c,u,{machine:e,base:t.base,host:Kr(),observedAt:Date.now(),now:r}).map(Wt);return Hf.set(t.taskPath,{stamp:i,envelopes:l}),{envelopes:l,touchedAt:o}}async function Vw(t,e){const r=Gr(),n=await Uw(),s=[];for(const o of n){const i=await Hw(o,r,e);if(i&&!(i.touchedAt<t))for(const a of i.envelopes)a.occurredAt>=t&&a.occurredAt<=e&&s.push(a)}return s}async function Vf(){const t=uy(),e=await ly();return{available:e.length>0,present:t.some(r=>ve(r)),roots:t,workspaces:e}}const an="claude-code",Fw={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"partial"},dy="claude-code";class mr extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const fy=t=>`claude:${t}`;function Ww(t,e){const r=t,n=typeof r?.version=="string"?r.version:void 0;if(!r||typeof r!="object")throw new mr("registry entry is not an object",e,n);if(typeof r.sessionId!="string"||!r.sessionId)throw new mr("registry entry has no sessionId",e,n);if(typeof r.pid!="number"||!Number.isFinite(r.pid))throw new mr("registry entry has no numeric pid",e,n);if(typeof r.startedAt!="number"||!Number.isFinite(r.startedAt))throw new mr("registry entry has no numeric startedAt",e,n);return r}function Kw(t,e,r){const n=[{ns:"agent.session",parts:[dy,t.sessionId],validFrom:t.startedAt,validTo:r.now},{ns:"os.process",parts:[r.host,t.pid],validFrom:t.startedAt,validTo:r.now}];return{source:{id:an,instance:r.host},occurredAt:t.startedAt,observedAt:r.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:fy(t.sessionId)},claims:n,basis:"measured",core:{machineId:r.machine.id,label:t.name??Be(t.cwd??"").toUpperCase(),projectLabel:t.cwd?Be(t.cwd):void 0,taskLabel:t.name,executor:an},attrs:{context:t.cwd,"claude.sessionId":t.sessionId,"claude.pid":t.pid,"claude.procStart":t.procStart,"claude.version":t.version,"claude.kind":t.kind,"claude.entrypoint":t.entrypoint,"claude.status":t.status,"claude.waitingFor":t.waitingFor},provenance:{path:e,recordId:t.sessionId,sourceVersion:t.version},seq:"registry"}}const Gw=new Set(["stop_hook_summary","turn_duration"]),qw="The transcript has not been written to for longer than the live window, so the process that owned it is gone and the turn ended at its last record.",pr=t=>typeof t=="number"&&Number.isFinite(t)?t:0,Pn=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function zw(t){const e=[];for(const r of t.split(`
4
+ `))if(r.trim())try{const n=JSON.parse(r);n&&typeof n=="object"&&e.push(n)}catch{}return e}function Yw(t){if(!t)return{};const e=t.output_tokens_details;return{[z.tokensInput]:pr(t.input_tokens)+pr(t.cache_creation_input_tokens),[z.tokensOutput]:pr(t.output_tokens),[z.tokensCacheRead]:pr(t.cache_read_input_tokens),[z.tokensReasoning]:pr(e?.thinking_tokens),[z.steps]:1}}function Xw(t,e){const r=t.filter(_=>Pn(_.timestamp)!==void 0);if(r.length===0)throw new mr("transcript has no timestamped records",e.path);const n=t.find(_=>typeof _.sessionId=="string")?.sessionId;if(n&&n!==e.sessionId)throw new mr(`transcript names session ${n} but is filed under ${e.sessionId}`,e.path);const s=t.find(_=>typeof _.version=="string")?.version,o=t.find(_=>typeof _.cwd=="string")?.cwd??"",i=t.find(_=>typeof _.gitBranch=="string")?.gitBranch,a=t.find(_=>typeof _.entrypoint=="string")?.entrypoint,c=Be(o).toUpperCase(),u=e.sessionId,l=fy(u),d=Pn(r[0].timestamp),m=Pn(r[r.length-1].timestamp),h={source:{id:an,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},g=(_,E)=>({path:e.path,..._?{recordId:_}:{},...E!==void 0?{index:E}:{},...s?{sourceVersion:s}:{}}),v=[{...h,occurredAt:d,kind:"began",subject:{type:"session",id:l},claims:[{ns:"agent.session",parts:[dy,u],validFrom:d,validTo:m}],core:{machineId:e.machine.id,label:c,projectLabel:o?Be(o):void 0,executor:an},attrs:{context:o,"claude.sessionId":u,"claude.gitBranch":i,"claude.entrypoint":a,"claude.version":s},provenance:g(u),seq:"session"}],b=[];for(let _=0;_<t.length;_++){const E=t[_];E.type==="user"&&typeof E.promptSource=="string"&&Pn(E.timestamp)!==void 0&&b.push(_)}if(b.length===0)throw new mr(`transcript has ${t.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,e.path,s);for(let _=0;_<b.length;_++){const E=b[_],I=_+1<b.length?b[_+1]:t.length,k=_+1,w=`${l}:turn:${k}`,N=Pn(t[E].timestamp),$=t.slice(E,I).some(L=>L.isSidechain===!0);let P,C=N,T,R=!1;const H=[];for(let L=E;L<I;L++){const G=t[L],te=Pn(G.timestamp);if(te===void 0)continue;const ne=G.type==="assistant"||G.type==="user"&&Array.isArray(G.message?.content);if(ne&&te>C&&(C=te),ne?(T=G,R=!1):G.type==="system"&&Gw.has(G.subtype??"")&&(R=!0),G.type==="assistant"&&G.message){P??=G.message.model;const we=(Array.isArray(G.message.content)?G.message.content:[]).filter(Oe=>!!Oe&&typeof Oe=="object"&&Oe.type==="tool_use"),Pe={...Yw(G.message.usage)};we.length&&(Pe[z.interactions]=we.length),H.push({...h,occurredAt:te,kind:"progressed",subject:{type:"execution",id:w},core:{measures:Pe},attrs:{...we.length?{"claude.tools":we.map(Oe=>Oe.name??"unknown")}:{},...G.message.model?{"claude.model":G.message.model}:{},...G.requestId?{"claude.requestId":G.requestId}:{},...G.message.stop_reason?{"claude.stopReason":G.message.stop_reason}:{},...G.message.usage?{"claude.usage.inputTokens":pr(G.message.usage.input_tokens),"claude.usage.outputTokens":pr(G.message.usage.output_tokens),"claude.usage.cacheReadTokens":pr(G.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":pr(G.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":G.message.usage.service_tier}:{}},provenance:g(G.uuid,L),seq:G.uuid??`a${L}`})}else if(G.type==="user"&&G.message&&Array.isArray(G.message.content)){const ge=G.message.content.filter(we=>!!we&&typeof we=="object"&&we.is_error===!0).length;ge&&H.push({...h,occurredAt:te,kind:"progressed",subject:{type:"execution",id:w},core:{measures:{[z.errors]:ge}},provenance:g(G.uuid,L),seq:G.uuid??`e${L}`})}}if(v.push({...h,occurredAt:N,kind:"began",subject:{type:"execution",id:w},core:{machineId:e.machine.id,sessionId:l,label:`${c} · TURN ${k}`,executor:an,model:P,depth:$?1:0},attrs:{"claude.turn":k,"claude.promptSource":t[E].promptSource,"claude.promptId":t[E].promptId,...$?{"claude.isSidechain":!0}:{}},provenance:g(t[E].uuid,E),seq:`turn:${k}`}),v.push(...H),_+1<b.length||R)v.push({...h,occurredAt:C,kind:"ended",subject:{type:"execution",id:w},core:{outcome:"completed"},provenance:g(t[E].uuid,E),seq:`turn:${k}:end`});else if(e.closeOpenTurns){const L=T?.type==="assistant"&&(T.message?.stop_reason==="end_turn"||T.message?.stop_reason==="stop_sequence");v.push({...h,occurredAt:C,kind:"ended",subject:{type:"execution",id:w},core:{outcome:L?"completed":"interrupted"},basis:"inferred",assumption:qw,provenance:g(t[E].uuid,E),seq:`turn:${k}:end`})}}return v}function dd(){return process.env.CLAUDE_HOME||ue(Bn(),".claude")}const gu=()=>ue(dd(),"sessions"),Jw=()=>ue(dd(),"projects"),Ff=new Map;async function Zw(t,e,r){const n=gu();if(!ve(n))return;r.identityAvailable=!0;let s;try{s=await Qe(n)}catch(o){r.problems.push({path:n,message:String(o)});return}for(const o of s){if(!o.endsWith(".json"))continue;const i=ue(n,o);try{const a=Ww(JSON.parse(await Ur(i,"utf8")),i);r.envelopes.push(Wt(Kw(a,i,{machine:t,host:Kr(),observedAt:e,now:e}))),r.registryEntries++}catch(a){r.problems.push({path:i,message:a instanceof Error?a.message:String(a),sourceVersion:a instanceof mr?a.sourceVersion:void 0})}}}async function py(){const t=Jw();if(!ve(t))return[];const e=[];let r;try{r=await Qe(t)}catch{return e}for(const n of r){let s;try{s=await Qe(ue(t,n))}catch{continue}for(const o of s)o.endsWith(".jsonl")&&e.push({path:ue(t,n,o),sessionId:o.slice(0,-6),project:n})}return e}async function Qw(t,e,r,n){const s=await py();if(s.length!==0){n.storedAvailable=!0;for(const o of s){let i;try{i=await fn(o.path)}catch{continue}if(i.mtimeMs<e)continue;const a=Date.now()-i.mtimeMs>ld,c=`${i.mtimeMs}:${i.size}:${a}`,u=Ff.get(o.path);let l;if(u&&u.stamp===c)l=u.envelopes;else try{const d=zw(await Ur(o.path,"utf8"));l=Xw(d,{machine:t,host:Kr(),observedAt:Date.now(),path:o.path,sessionId:o.sessionId,closeOpenTurns:a}).map(Wt),Ff.set(o.path,{stamp:c,envelopes:l})}catch(d){n.transcriptsFailed++,n.problems.push({path:o.path,message:d instanceof Error?d.message:String(d),sourceVersion:d instanceof mr?d.sourceVersion:void 0});continue}n.transcriptsRead++;for(const d of l)d.occurredAt>=e&&d.occurredAt<=r&&n.envelopes.push(d)}}}async function hy(t,e){const r=Gr(),n=Date.now(),s={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await Zw(r,n,s),await Qw(r,t,e,s),s}async function e0(t,e){return(await hy(t,e)).envelopes}async function Wf(){const t=dd(),e=ve(gu())?(await Qe(gu()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,r=(await py()).length;return{available:e>0||r>0,present:ve(t),home:t,registry:e,transcripts:r}}const oo="codex",t0={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"supported"},r0="codex",n0=10*6e4;class en extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const s0=t=>`codex:${t}`,Qt=t=>typeof t=="number"&&Number.isFinite(t)?t:0,ke=t=>typeof t=="string"&&t?t:void 0,Rc=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function o0(t){const e=Qt(t.input_tokens),r=Qt(t.cached_input_tokens);return{[z.tokensInput]:Math.max(0,e-r),[z.tokensOutput]:Qt(t.output_tokens),[z.tokensCacheRead]:r,[z.tokensReasoning]:Qt(t.reasoning_output_tokens),[z.steps]:1}}function i0(t,e){const r=t.find(_=>_.type==="session_meta");if(!r||!r.payload)throw new en("rollout has no session_meta record",e.path);const n=r.payload,s=ke(n.cli_version),o=ke(n.session_id)??ke(n.id);if(o&&o!==e.sessionId)throw new en(`rollout names session ${o} but is filed under ${e.sessionId}`,e.path,s);const i=ke(n.cwd)??"",a=Rc(n.timestamp)??Rc(r.timestamp);if(a===void 0)throw new en("session_meta has no parseable timestamp",e.path,s);const c=Be(i).toUpperCase(),u=s0(e.sessionId),d={source:{id:oo,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},m=(_,E)=>({path:e.path,..._?{recordId:_}:{},...E!==void 0?{index:E}:{},...s?{sourceVersion:s}:{}}),p=[];let h=null,g=a,v=0;for(let _=0;_<t.length;_++){const E=t[_],I=Rc(E.timestamp);I!==void 0&&I>g&&(g=I);const k=E.payload;if(!k)continue;if(E.type==="turn_context"){h&&ke(k.turn_id)===h.turnId&&(h.model??=ke(k.model),h.effort??=ke(k.effort));continue}if(E.type!=="event_msg")continue;const w=ke(k.type);if(w==="task_started"){const $=ke(k.turn_id);if(!$||I===void 0)throw new en(`task_started at ordinal ${E.ordinal} is missing turn_id or timestamp`,e.path,s);h={turnId:$,startedAt:I,interior:[],lastAt:I},p.push(h);continue}if(w==="task_complete"){const $=ke(k.turn_id),P=p.find(C=>C.turnId===$)??h;if(P&&I!==void 0){P.completedAt=I;const C=k.error;P.outcome=C?"error":"completed",P.failureMessage=C?ke(C.message):void 0,P.lastAt=Math.max(P.lastAt,I)}P===h&&(h=null);continue}if(w==="turn_aborted"){const $=ke(k.turn_id);if(!$||I===void 0)throw new en(`turn_aborted at ordinal ${E.ordinal} is missing turn_id or timestamp`,e.path,s);const P=p.find(C=>C.turnId===$);P&&P.completedAt===void 0&&(P.completedAt=I,P.outcome="interrupted",P.lastAt=Math.max(P.lastAt,I)),P===h&&(h=null);continue}if(w==="token_count"||w==="item_completed"){if(!h){v++;continue}if(I===void 0)continue}else continue;const N=`${u}:turn:${h.turnId}`;if(w==="token_count"){const P=k.info?.last_token_usage;if(!P)continue;h.lastAt=Math.max(h.lastAt,I),h.interior.push({...d,occurredAt:I,kind:"progressed",subject:{type:"execution",id:N},core:{measures:o0(P)},attrs:{"codex.usage.inputTokens":Qt(P.input_tokens),"codex.usage.cachedInputTokens":Qt(P.cached_input_tokens),"codex.usage.cacheWriteInputTokens":Qt(P.cache_write_input_tokens),"codex.usage.outputTokens":Qt(P.output_tokens),"codex.usage.reasoningOutputTokens":Qt(P.reasoning_output_tokens)},provenance:m(void 0,E.ordinal),seq:`o${E.ordinal??_}`});continue}if(w==="item_completed"){const $=k.item,P=ke($?.type);if(!$||!P)continue;h.lastAt=Math.max(h.lastAt,I);let C,T;if(P==="CommandExecution"){const R=Qt($.exit_code);C={[z.interactions]:1,...R!==0?{[z.errors]:1}:{}},T={"codex.itemType":P,"codex.exitCode":R,...$.process_id!==void 0?{"codex.processId":$.process_id}:{},...ke($.status)?{"codex.status":$.status}:{}}}else if(P==="McpToolCall"){const R=ke($.status)==="failed"||ke($.status)==="error";C={[z.interactions]:1,...R?{[z.errors]:1}:{}},T={"codex.itemType":P,"codex.tool":[ke($.server),ke($.tool)].filter(Boolean).join("."),...ke($.status)?{"codex.status":$.status}:{}}}else if(P==="WebSearch")C={[z.interactions]:1},T={"codex.itemType":P};else if(P==="FileChange"){const R=$.changes;C={[z.interactions]:1},T={"codex.itemType":P,...R&&typeof R=="object"?{"codex.fileChanges":Object.entries(R).map(([H,U])=>({path:H,kind:ke(U?.type)}))}:{}}}else continue;h.interior.push({...d,occurredAt:I,kind:"progressed",subject:{type:"execution",id:N},core:{measures:C},attrs:T,provenance:m(ke($.id),E.ordinal),seq:`o${E.ordinal??_}`})}}if(p.length===0&&v>0)throw new en(`rollout has ${v} work records but no task_started marker`,e.path,s);const b=[{...d,occurredAt:a,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[r0,e.sessionId],validFrom:a,validTo:g}],core:{machineId:e.machine.id,label:c,projectLabel:e.projectLabel??(i?Be(i):void 0),taskLabel:e.taskLabel,executor:oo},attrs:{context:i,"codex.sessionId":e.sessionId,"codex.cliVersion":s,"codex.originator":ke(n.originator),"codex.source":ke(n.source),"codex.modelProvider":ke(n.model_provider),...a0(n.git)},provenance:m(e.sessionId,r.ordinal),seq:"session"}];for(let _=0;_<p.length;_++){const E=p[_],I=`${u}:turn:${E.turnId}`;b.push({...d,occurredAt:E.startedAt,kind:"began",subject:{type:"execution",id:I},core:{machineId:e.machine.id,sessionId:u,label:`${c} · TURN ${_+1}`,executor:oo,model:E.model,depth:0},attrs:{"codex.turnId":E.turnId,...E.effort?{"codex.effort":E.effort}:{}},provenance:m(E.turnId),seq:`turn:${E.turnId}`}),b.push(...E.interior),E.completedAt!==void 0?b.push({...d,occurredAt:E.completedAt,kind:"ended",subject:{type:"execution",id:I},core:{outcome:E.outcome??"completed",...E.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:E.failureMessage??"turn failed"}:{}},provenance:m(E.turnId),seq:`turn:${E.turnId}:end`}):e.now-g>n0&&b.push({...d,basis:"inferred",assumption:"A rollout untouched for 10 minutes belongs to a dead process, so a turn left open in it was interrupted, not still running. Its end is the last instant the rollout moved.",occurredAt:E.lastAt,kind:"ended",subject:{type:"execution",id:I},core:{outcome:"interrupted"},provenance:m(E.turnId),seq:`turn:${E.turnId}:end`})}return b}function a0(t){if(!t||typeof t!="object")return{};const e=t;return{...ke(e.branch)?{"codex.gitBranch":e.branch}:{},...ke(e.commit_hash)?{"codex.gitCommit":e.commit_hash}:{},...ke(e.repository_url)?{"codex.gitOriginUrl":e.repository_url}:{}}}function fd(){return process.env.CODEX_HOME||ue(Bn(),".codex")}const my=()=>ue(fd(),"sessions"),c0=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,jc=new Map,u0=new Set(["CommandExecution","McpToolCall","WebSearch","FileChange"]);function l0(t){const e={timestamp:t.timestamp,ordinal:t.ordinal,type:t.type},r=t.payload;if(!r)return t.type==="session_meta"?{...e}:void 0;if(t.type==="session_meta"){const a=r.git;return{...e,payload:{session_id:r.session_id,id:r.id,timestamp:r.timestamp,cwd:r.cwd,originator:r.originator,cli_version:r.cli_version,source:r.source,model_provider:r.model_provider,git:a?{branch:a.branch,commit_hash:a.commit_hash,repository_url:a.repository_url}:void 0}}}if(t.type==="turn_context")return{...e,payload:{turn_id:r.turn_id,model:r.model,effort:r.effort}};if(t.type!=="event_msg")return;const n=r.type;if(n==="task_started"||n==="turn_aborted")return{...e,payload:{type:n,turn_id:r.turn_id}};if(n==="task_complete"){const a=r.error;return{...e,payload:{type:n,turn_id:r.turn_id,...a?{error:{message:a.message}}:{}}}}if(n==="token_count"){const c=r.info?.last_token_usage;return c?{...e,payload:{type:n,info:{last_token_usage:{input_tokens:c.input_tokens,cached_input_tokens:c.cached_input_tokens,cache_write_input_tokens:c.cache_write_input_tokens,output_tokens:c.output_tokens,reasoning_output_tokens:c.reasoning_output_tokens}}}}:{...e,payload:{type:n}}}if(n!=="item_completed")return;const s=r.item,o=typeof s?.type=="string"?s.type:void 0;if(!s||!o||!u0.has(o))return{...e,payload:{type:n,item:o?{type:o}:void 0}};const i={type:o,id:s.id};if(o==="CommandExecution")i.process_id=s.process_id,i.exit_code=s.exit_code,i.status=s.status;else if(o==="McpToolCall")i.server=s.server,i.tool=s.tool,i.status=s.status;else if(o==="FileChange"){const a=s.changes;i.changes=a?Object.fromEntries(Object.entries(a).map(([c,u])=>[c,{type:u?.type}])):void 0}return{...e,payload:{type:n,item:i}}}async function d0(t,e=0){const r=[];let n=[],s=0,o=0,i=e;const a=(c,u)=>{if(u===0)return;const l=Buffer.concat(c,Math.min(u,1024)).subarray(0,1024).toString("utf8"),d=/^\s*\{\s*"timestamp"\s*:\s*"(?:\\.|[^"])*"\s*,\s*"type"\s*:\s*"([^"]+)"/.exec(l)?.[1];if(d&&d!=="session_meta"&&d!=="turn_context"&&d!=="event_msg")return;const m=Buffer.concat(c,u).toString("utf8");if(m.trim())try{const p=JSON.parse(m);if(!p||typeof p!="object")return;const h=l0(p);h&&r.push(h)}catch{}};for await(const c of Qm(t,{start:e})){const u=Buffer.isBuffer(c)?c:Buffer.from(c),l=o;o+=u.length;let d=0;for(;;){const m=u.indexOf(10,d);if(m<0)break;const p=u.subarray(d,m);a([...n,p],s+p.length),n=[],s=0,d=m+1,i=e+l+d}if(d<u.length){const m=u.subarray(d);n.push(m),s+=m.length}}return{records:r,offset:i,bytesRead:o}}function f0(t,e,r){return t.occurredAt>=e&&t.occurredAt<=r||t.subject.type==="session"&&t.kind==="began"&&(typeof t.core?.projectLabel=="string"||typeof t.core?.taskLabel=="string")}function p0(t,e=fd()){const r=ue(e,"state_5.sqlite");if(!ve(r))return new Map;let n;try{n=new Uo(r,{readOnly:!0}),n.exec("PRAGMA query_only = ON");const s=n.prepare("SELECT name FROM threads WHERE id = ? LIMIT 1");let o;try{o=n.prepare(`SELECT projects.name AS projectName
5
5
  FROM threads JOIN projects ON projects.id = threads.project_id
6
- WHERE threads.id = ? LIMIT 1`)}catch{}const i=new Map;for(const a of t){const c=o.get(a.sessionId),u=s?.get(a.sessionId),d=typeof c?.name=="string"?c.name.trim():"",l=typeof u?.projectName=="string"?u.projectName.trim():"";(d||l)&&i.set(a.sessionId,{...d?{taskLabel:d}:{},...l?{projectLabel:l}:{}})}return i}catch{return new Map}finally{n?.close()}}function Xw(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function Jw(t,e){if(e?.trim())return e.trim();const r=t.find(s=>s.type==="session_meta"),n=Xw(r?.payload?.cwd);if(!n)return;if(ge(ue(n,".git")))return Ne(n);const o=new Map;for(const s of t){if(s.type!=="event_msg"||s.payload?.type!=="item_completed")continue;const i=s.payload.item;if(i?.type!=="FileChange")continue;const a=i.changes;for(const c of Object.keys(a??{})){if(!tu(c))continue;const u=Sc(n,c);if(!u||u===".."||u.startsWith(`..${ru}`)||tu(u))continue;const d=u.split(ru).filter(Boolean)[0];if(!d||d.startsWith("."))continue;const l=ue(n,d);let m;if(ge(ue(l,".git")))m=l;else{let h=vi(c);for(;h!==n&&Sc(n,h)&&!Sc(n,h).startsWith("..");){ge(ue(h,".git"))&&(m=h);const v=vi(h);if(v===h)break;h=v}}const p=m?Ne(m):d;o.set(p,(o.get(p)??0)+1)}}return[...o.entries()].sort(([s,i],[a,c])=>c-i||s.localeCompare(a))[0]?.[0]??Ne(n)}async function Qm(){const t=Zm();if(!ge(t))return[];const e=[];let r;try{r=await Ze(t)}catch{return e}for(const n of r){let o;try{o=await Ze(ue(t,n))}catch{continue}for(const s of o){let i;try{i=await Ze(ue(t,n,s))}catch{continue}for(const a of i){let c;try{c=await Ze(ue(t,n,s,a))}catch{continue}for(const u of c){const d=Ww.exec(u);d&&e.push({path:ue(t,n,s,a,u),sessionId:d[1]})}}}}return e}async function ey(t,e){const r=Vr(),n=Date.now(),o={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},s=await Qm();if(s.length===0)return o.storedAvailable=ge(Zm()),o;o.storedAvailable=!0;const i=Yw(s);for(const a of s){let c;try{c=await sn(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=i.get(a.sessionId),d=`${u?.projectLabel??""}:${u?.taskLabel??""}`;let l=Ec.get(a.path);l&&c.size<l.offset&&(Ec.delete(a.path),l=void 0);let m;const p=await qw(a.path,l?.offset??0),h=l?p.records.length>0?[...l.records,...p.records]:l.records:p.records,v=!l||p.offset!==l.offset;if(l&&!v&&l.annotationStamp===d)m=l.envelopes;else try{const g=Jw(h,u?.projectLabel);m=Hw(h,{machine:r,host:Ur(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n,projectLabel:g,taskLabel:u?.taskLabel}).map(Zt),Ec.set(a.path,{offset:p.offset,records:h,annotationStamp:d,envelopes:m})}catch(g){o.rolloutsFailed++,o.problems.push({path:a.path,message:g instanceof Error?g.message:String(g),sourceVersion:g instanceof Yr?g.sourceVersion:void 0});continue}o.rolloutsRead++;for(const g of m)zw(g,t,e)&&o.envelopes.push(g)}return o}async function Zw(t,e){return(await ey(t,e)).envelopes}async function $f(){const t=Jl(),e=(await Qm()).length;return{available:e>0,present:ge(t),home:t,rollouts:e}}const Xn="cursor",Qw={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"unsupported",context:"partial",outcome:"partial"},e0="cursor";class ui extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const ou=t=>`cursor:${t}`,Xr=t=>typeof t=="string"&&t?t:void 0,Js=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Bf=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function ty(t,e){if(typeof t.composerId!="string"||!t.composerId)throw new ui("composer header has no composerId",e);if(typeof t.createdAt!="number"||!Number.isFinite(t.createdAt))throw new ui("composer header has no numeric createdAt",e);if(typeof t.lastUpdatedAt!="number"||!Number.isFinite(t.lastUpdatedAt))throw new ui("composer header has no numeric lastUpdatedAt",e)}function t0(t,e){ty(t,e.path);const r=t.value??{},n=r.subagentInfo,o=n?Xr(n.parentComposerId):void 0,s=e.workspacePath??"",i=Xr(r.name)?.toUpperCase()??(s?Ne(s).toUpperCase():"CURSOR");return{source:{id:Xn,instance:e.host},occurredAt:t.createdAt,observedAt:e.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:ou(t.composerId)},claims:[{ns:"agent.session",parts:[e0,t.composerId],validFrom:t.createdAt,validTo:t.lastUpdatedAt}],basis:"measured",core:{machineId:e.machine.id,label:i,projectLabel:s?Ne(s):void 0,taskLabel:Xr(r.name),executor:Xn,...o?{parentId:ou(o)}:{}},attrs:{context:s,"cursor.composerId":t.composerId,"cursor.workspaceId":t.workspaceId,"cursor.isSubagent":t.isSubagent,...n?{"cursor.parentComposerId":Xr(n.parentComposerId),"cursor.subagentType":Xr(n.subagentTypeName)}:{},...Js(r.totalLinesAdded)!==void 0?{"cursor.linesAdded":r.totalLinesAdded}:{},...Js(r.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":r.totalLinesRemoved}:{},...Js(r.filesChangedCount)!==void 0?{"cursor.filesChanged":r.filesChangedCount}:{},...Xr(r.unifiedMode)?{"cursor.mode":r.unifiedMode}:{},...Js(r._v)!==void 0?{"cursor.schemaVersion":r._v}:{}},provenance:{path:e.path,recordId:t.composerId},seq:"composer"}}const Rf="Cursor persists no turn timing: the bounds are the first and last timestamped records inside the turn, untimestamped activity may extend beyond them, and the turn is taken as completed because Cursor records no turn outcome.";function r0(t,e,r){ty(t,r.path);const n=ou(t.composerId),s={source:{id:Xn,instance:r.host},observedAt:r.observedAt,clock:"wall",stratum:"stored-semantics"},i=d=>({path:r.path,...d?{recordId:d}:{}}),a=[];for(let d=0;d<e.length;d++)e[d].type===1&&a.push(d);const c=[];let u=0;for(let d=0;d<a.length;d++){const l=a[d],m=d+1<a.length?a[d+1]:e.length,p=d+1,h=e.slice(l,m),v=h.map(x=>({bubble:x,at:Bf(x.createdAt)})).filter(x=>x.at!==void 0);if(v.length<2){u++;continue}const g=Math.min(...v.map(x=>x.at)),I=Math.max(...v.map(x=>x.at)),N=`${n}:turn:${p}`,S=h.filter(x=>x.toolName&&Bf(x.createdAt)===void 0),T=S.filter(x=>x.toolStatus==="error").length;c.push({...s,occurredAt:g,kind:"began",subject:{type:"execution",id:N},basis:"inferred",assumption:Rf,core:{machineId:r.machine.id,sessionId:n,label:`${Xr(t.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${p}`,executor:Xn,depth:t.isSubagent?1:0,...S.length?{measures:{[Z.interactions]:S.length,...T?{[Z.errors]:T}:{}}}:{}},attrs:{"cursor.turn":p},provenance:i(e[l].bubbleId),seq:`turn:${p}`});for(const{bubble:x,at:D}of v){if(!x.toolName)continue;const w=x.toolStatus==="error",$={[Z.interactions]:1,...w?{[Z.errors]:1}:{}};c.push({...s,occurredAt:D,kind:"progressed",subject:{type:"execution",id:N},basis:"measured",core:{measures:$},attrs:{"cursor.tool":x.toolName,...x.toolStatus?{"cursor.toolStatus":x.toolStatus}:{}},provenance:i(x.bubbleId),seq:x.bubbleId})}c.push({...s,occurredAt:I,kind:"ended",subject:{type:"execution",id:N},basis:"inferred",assumption:Rf,core:{outcome:"completed"},provenance:i(e[l].bubbleId),seq:`turn:${p}:end`})}return{drafts:c,turns:a.length,untimedTurns:u}}function Qo(){return process.env.CURSOR_GLOBAL_STORAGE||ue(xn(),"Library","Application Support","Cursor","User","globalStorage")}function n0(){return process.env.CURSOR_WORKSPACE_STORAGE||ue(Qo(),"..","workspaceStorage")}const ry=()=>ue(Qo(),"state.vscdb"),Mf=new Map;async function o0(){const t=new Map,e=n0();if(!ge(e))return t;let r;try{r=await Ze(e)}catch{return t}for(const n of r)try{const o=JSON.parse(await _r(ue(e,n,"workspace.json"),"utf8"));typeof o.folder=="string"&&o.folder.startsWith("file://")&&t.set(n,decodeURIComponent(o.folder.slice(7)))}catch{continue}return t}function s0(t,e){let r;if(t.value)try{r=JSON.parse(t.value)}catch{r=void 0}const n=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0,o=t.lastUpdatedAt??n(r?.lastUpdatedAt)??n(r?.conversationCheckpointLastUpdatedAt)??t.createdAt??NaN,s={composerId:t.composerId,workspaceId:t.workspaceId??void 0,createdAt:t.createdAt??NaN,lastUpdatedAt:o,isSubagent:t.isSubagent===1,value:r};if(!Number.isFinite(s.createdAt)||!Number.isFinite(s.lastUpdatedAt))throw new ui(`composer ${t.composerId} has no numeric createdAt/lastUpdatedAt`,e);return s}function i0(t,e){const r=t.prepare("SELECT value FROM cursorDiskKV WHERE key = ?").get(`composerData:${e}`);if(!r?.value)return[];const n=typeof r.value=="string"?r.value:Buffer.from(r.value).toString("utf8"),s=JSON.parse(n).fullConversationHeadersOnly??[],i=t.prepare("SELECT key, value FROM cursorDiskKV WHERE key >= ? AND key < ?").all(`bubbleId:${e}:`,`bubbleId:${e};`),a=new Map;for(const c of i){const u=c.key.slice(`bubbleId:${e}:`.length);try{const d=typeof c.value=="string"?c.value:Buffer.from(c.value).toString("utf8"),l=JSON.parse(d);a.set(u,{bubbleId:u,type:l.type,createdAt:typeof l.createdAt=="string"&&l.createdAt?l.createdAt:void 0,toolName:l.toolFormerData?.name,toolStatus:l.toolFormerData?.status})}catch{continue}}return s.filter(c=>typeof c.bubbleId=="string").map(c=>a.get(c.bubbleId)??{bubbleId:c.bubbleId,type:c.type})}async function ny(t,e){const r=Vr(),n=Date.now(),o=ry(),s={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!ge(o))return s;s.storedAvailable=!0;const i=await o0();let a;try{a=new Bs(o,{readOnly:!0})}catch(c){return s.problems.push({path:o,message:`cannot open read-only: ${String(c)}`}),s}try{let c;try{c=a.prepare("SELECT composerId, workspaceId, createdAt, lastUpdatedAt, isSubagent, value FROM composerHeaders WHERE (lastUpdatedAt >= ? OR lastUpdatedAt IS NULL) AND createdAt <= ?").all(t,e)}catch(u){return s.problems.push({path:o,message:`composerHeaders unreadable: ${String(u)}`}),s}for(const u of c)try{const d=s0(u,o);if(d.lastUpdatedAt<t)continue;const l={machine:r,host:Ur(),observedAt:n,path:o,workspacePath:d.workspaceId?i.get(d.workspaceId):void 0};s.envelopes.push(Zt(t0(d,l)));const m=`${d.lastUpdatedAt}`,p=Mf.get(d.composerId);let h;if(p&&p.stamp===m)h=p.envelopes;else{const v=i0(a,d.composerId),{drafts:g}=r0(d,v,l);h=g.map(Zt),Mf.set(d.composerId,{stamp:m,envelopes:h})}for(const v of h)v.occurredAt>=t&&v.occurredAt<=e&&s.envelopes.push(v);s.composersRead++}catch(d){s.composersFailed++,s.problems.push({path:o,message:`${u.composerId}: ${d instanceof Error?d.message:String(d)}`})}}finally{a.close()}return s}async function a0(t,e){return(await ny(t,e)).envelopes}async function _f(){const t=ry();if(!ge(t))return{available:!1,present:!1,globalStorage:Qo()};try{const e=new Bs(t,{readOnly:!0});try{const r=e.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:r.n>0,present:!0,globalStorage:Qo(),composers:r.n}}finally{e.close()}}catch{return{available:!1,present:!0,globalStorage:Qo()}}}const es="gemini",c0={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"unsupported",model:"supported",context:"partial",outcome:"partial"},u0="gemini";class Ei extends Error{constructor(e,r){super(e),this.path=r,this.name="GeminiFormatError"}path}const l0="The session file has not been written to for longer than the live window, so the runtime that owned it is gone and the turn ended at its last message.";function d0(t){return(typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(r=>r?.text).filter(r=>typeof r=="string").join(`
6
+ WHERE threads.id = ? LIMIT 1`)}catch{}const i=new Map;for(const a of t){const c=s.get(a.sessionId),u=o?.get(a.sessionId),l=typeof c?.name=="string"?c.name.trim():"",d=typeof u?.projectName=="string"?u.projectName.trim():"";(l||d)&&i.set(a.sessionId,{...l?{taskLabel:l}:{},...d?{projectLabel:d}:{}})}return i}catch{return new Map}finally{n?.close()}}function h0(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function m0(t,e){if(e?.trim())return e.trim();const r=t.find(o=>o.type==="session_meta"),n=h0(r?.payload?.cwd);if(!n)return;if(ve(ue(n,".git")))return Be(n);const s=new Map;for(const o of t){if(o.type!=="event_msg"||o.payload?.type!=="item_completed")continue;const i=o.payload.item;if(i?.type!=="FileChange")continue;const a=i.changes;for(const c of Object.keys(a??{})){if(!hu(c))continue;const u=Mc(n,c);if(!u||u===".."||u.startsWith(`..${mu}`)||hu(u))continue;const l=u.split(mu).filter(Boolean)[0];if(!l||l.startsWith("."))continue;const d=ue(n,l);let m;if(ve(ue(d,".git")))m=d;else{let h=Oi(c);for(;h!==n&&Mc(n,h)&&!Mc(n,h).startsWith("..");){ve(ue(h,".git"))&&(m=h);const g=Oi(h);if(g===h)break;h=g}}const p=m?Be(m):l;s.set(p,(s.get(p)??0)+1)}}return[...s.entries()].sort(([o,i],[a,c])=>c-i||o.localeCompare(a))[0]?.[0]??Be(n)}async function yy(){const t=my();if(!ve(t))return[];const e=[];let r;try{r=await Qe(t)}catch{return e}for(const n of r){let s;try{s=await Qe(ue(t,n))}catch{continue}for(const o of s){let i;try{i=await Qe(ue(t,n,o))}catch{continue}for(const a of i){let c;try{c=await Qe(ue(t,n,o,a))}catch{continue}for(const u of c){const l=c0.exec(u);l&&e.push({path:ue(t,n,o,a,u),sessionId:l[1]})}}}}return e}async function gy(t,e){const r=Gr(),n=Date.now(),s={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},o=await yy();if(o.length===0)return s.storedAvailable=ve(my()),s;s.storedAvailable=!0;const i=p0(o);for(const a of o){let c;try{c=await fn(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=i.get(a.sessionId),l=`${u?.projectLabel??""}:${u?.taskLabel??""}`;let d=jc.get(a.path);d&&c.size<d.offset&&(jc.delete(a.path),d=void 0);let m;const p=await d0(a.path,d?.offset??0),h=d?p.records.length>0?[...d.records,...p.records]:d.records:p.records,g=!d||p.offset!==d.offset;if(d&&!g&&d.annotationStamp===l)m=d.envelopes;else try{const v=m0(h,u?.projectLabel);m=i0(h,{machine:r,host:Kr(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n,projectLabel:v,taskLabel:u?.taskLabel}).map(Wt),jc.set(a.path,{offset:p.offset,records:h,annotationStamp:l,envelopes:m})}catch(v){s.rolloutsFailed++,s.problems.push({path:a.path,message:v instanceof Error?v.message:String(v),sourceVersion:v instanceof en?v.sourceVersion:void 0});continue}s.rolloutsRead++;for(const v of m)f0(v,t,e)&&s.envelopes.push(v)}return s}async function y0(t,e){return(await gy(t,e)).envelopes}async function Kf(){const t=fd(),e=(await yy()).length;return{available:e>0,present:ve(t),home:t,rollouts:e}}const ns="cursor",g0={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"unsupported",context:"partial",outcome:"partial"},v0="cursor";class bi extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const vu=t=>`cursor:${t}`,tn=t=>typeof t=="string"&&t?t:void 0,oi=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Gf=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function vy(t,e){if(typeof t.composerId!="string"||!t.composerId)throw new bi("composer header has no composerId",e);if(typeof t.createdAt!="number"||!Number.isFinite(t.createdAt))throw new bi("composer header has no numeric createdAt",e);if(typeof t.lastUpdatedAt!="number"||!Number.isFinite(t.lastUpdatedAt))throw new bi("composer header has no numeric lastUpdatedAt",e)}function b0(t,e){vy(t,e.path);const r=t.value??{},n=r.subagentInfo,s=n?tn(n.parentComposerId):void 0,o=e.workspacePath??"",i=tn(r.name)?.toUpperCase()??(o?Be(o).toUpperCase():"CURSOR");return{source:{id:ns,instance:e.host},occurredAt:t.createdAt,observedAt:e.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:vu(t.composerId)},claims:[{ns:"agent.session",parts:[v0,t.composerId],validFrom:t.createdAt,validTo:t.lastUpdatedAt}],basis:"measured",core:{machineId:e.machine.id,label:i,projectLabel:o?Be(o):void 0,taskLabel:tn(r.name),executor:ns,...s?{parentId:vu(s)}:{}},attrs:{context:o,"cursor.composerId":t.composerId,"cursor.workspaceId":t.workspaceId,"cursor.isSubagent":t.isSubagent,...n?{"cursor.parentComposerId":tn(n.parentComposerId),"cursor.subagentType":tn(n.subagentTypeName)}:{},...oi(r.totalLinesAdded)!==void 0?{"cursor.linesAdded":r.totalLinesAdded}:{},...oi(r.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":r.totalLinesRemoved}:{},...oi(r.filesChangedCount)!==void 0?{"cursor.filesChanged":r.filesChangedCount}:{},...tn(r.unifiedMode)?{"cursor.mode":r.unifiedMode}:{},...oi(r._v)!==void 0?{"cursor.schemaVersion":r._v}:{}},provenance:{path:e.path,recordId:t.composerId},seq:"composer"}}const qf="Cursor persists no turn timing: the bounds are the first and last timestamped records inside the turn, untimestamped activity may extend beyond them, and the turn is taken as completed because Cursor records no turn outcome.";function w0(t,e,r){vy(t,r.path);const n=vu(t.composerId),o={source:{id:ns,instance:r.host},observedAt:r.observedAt,clock:"wall",stratum:"stored-semantics"},i=l=>({path:r.path,...l?{recordId:l}:{}}),a=[];for(let l=0;l<e.length;l++)e[l].type===1&&a.push(l);const c=[];let u=0;for(let l=0;l<a.length;l++){const d=a[l],m=l+1<a.length?a[l+1]:e.length,p=l+1,h=e.slice(d,m),g=h.map(k=>({bubble:k,at:Gf(k.createdAt)})).filter(k=>k.at!==void 0);if(g.length<2){u++;continue}const v=Math.min(...g.map(k=>k.at)),b=Math.max(...g.map(k=>k.at)),_=`${n}:turn:${p}`,E=h.filter(k=>k.toolName&&Gf(k.createdAt)===void 0),I=E.filter(k=>k.toolStatus==="error").length;c.push({...o,occurredAt:v,kind:"began",subject:{type:"execution",id:_},basis:"inferred",assumption:qf,core:{machineId:r.machine.id,sessionId:n,label:`${tn(t.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${p}`,executor:ns,depth:t.isSubagent?1:0,...E.length?{measures:{[z.interactions]:E.length,...I?{[z.errors]:I}:{}}}:{}},attrs:{"cursor.turn":p},provenance:i(e[d].bubbleId),seq:`turn:${p}`});for(const{bubble:k,at:w}of g){if(!k.toolName)continue;const N=k.toolStatus==="error",$={[z.interactions]:1,...N?{[z.errors]:1}:{}};c.push({...o,occurredAt:w,kind:"progressed",subject:{type:"execution",id:_},basis:"measured",core:{measures:$},attrs:{"cursor.tool":k.toolName,...k.toolStatus?{"cursor.toolStatus":k.toolStatus}:{}},provenance:i(k.bubbleId),seq:k.bubbleId})}c.push({...o,occurredAt:b,kind:"ended",subject:{type:"execution",id:_},basis:"inferred",assumption:qf,core:{outcome:"completed"},provenance:i(e[d].bubbleId),seq:`turn:${p}:end`})}return{drafts:c,turns:a.length,untimedTurns:u}}function io(){return process.env.CURSOR_GLOBAL_STORAGE||ue(Bn(),"Library","Application Support","Cursor","User","globalStorage")}function S0(){return process.env.CURSOR_WORKSPACE_STORAGE||ue(io(),"..","workspaceStorage")}const by=()=>ue(io(),"state.vscdb"),zf=new Map;async function A0(){const t=new Map,e=S0();if(!ve(e))return t;let r;try{r=await Qe(e)}catch{return t}for(const n of r)try{const s=JSON.parse(await Ur(ue(e,n,"workspace.json"),"utf8"));typeof s.folder=="string"&&s.folder.startsWith("file://")&&t.set(n,decodeURIComponent(s.folder.slice(7)))}catch{continue}return t}function k0(t,e){let r;if(t.value)try{r=JSON.parse(t.value)}catch{r=void 0}const n=i=>typeof i=="number"&&Number.isFinite(i)?i:void 0,s=t.lastUpdatedAt??n(r?.lastUpdatedAt)??n(r?.conversationCheckpointLastUpdatedAt)??t.createdAt??NaN,o={composerId:t.composerId,workspaceId:t.workspaceId??void 0,createdAt:t.createdAt??NaN,lastUpdatedAt:s,isSubagent:t.isSubagent===1,value:r};if(!Number.isFinite(o.createdAt)||!Number.isFinite(o.lastUpdatedAt))throw new bi(`composer ${t.composerId} has no numeric createdAt/lastUpdatedAt`,e);return o}function E0(t,e){const r=t.prepare("SELECT value FROM cursorDiskKV WHERE key = ?").get(`composerData:${e}`);if(!r?.value)return[];const n=typeof r.value=="string"?r.value:Buffer.from(r.value).toString("utf8"),o=JSON.parse(n).fullConversationHeadersOnly??[],i=t.prepare("SELECT key, value FROM cursorDiskKV WHERE key >= ? AND key < ?").all(`bubbleId:${e}:`,`bubbleId:${e};`),a=new Map;for(const c of i){const u=c.key.slice(`bubbleId:${e}:`.length);try{const l=typeof c.value=="string"?c.value:Buffer.from(c.value).toString("utf8"),d=JSON.parse(l);a.set(u,{bubbleId:u,type:d.type,createdAt:typeof d.createdAt=="string"&&d.createdAt?d.createdAt:void 0,toolName:d.toolFormerData?.name,toolStatus:d.toolFormerData?.status})}catch{continue}}return o.filter(c=>typeof c.bubbleId=="string").map(c=>a.get(c.bubbleId)??{bubbleId:c.bubbleId,type:c.type})}async function wy(t,e){const r=Gr(),n=Date.now(),s=by(),o={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!ve(s))return o;o.storedAvailable=!0;const i=await A0();let a;try{a=new Uo(s,{readOnly:!0})}catch(c){return o.problems.push({path:s,message:`cannot open read-only: ${String(c)}`}),o}try{let c;try{c=a.prepare("SELECT composerId, workspaceId, createdAt, lastUpdatedAt, isSubagent, value FROM composerHeaders WHERE (lastUpdatedAt >= ? OR lastUpdatedAt IS NULL) AND createdAt <= ?").all(t,e)}catch(u){return o.problems.push({path:s,message:`composerHeaders unreadable: ${String(u)}`}),o}for(const u of c)try{const l=k0(u,s);if(l.lastUpdatedAt<t)continue;const d={machine:r,host:Kr(),observedAt:n,path:s,workspacePath:l.workspaceId?i.get(l.workspaceId):void 0};o.envelopes.push(Wt(b0(l,d)));const m=`${l.lastUpdatedAt}`,p=zf.get(l.composerId);let h;if(p&&p.stamp===m)h=p.envelopes;else{const g=E0(a,l.composerId),{drafts:v}=w0(l,g,d);h=v.map(Wt),zf.set(l.composerId,{stamp:m,envelopes:h})}for(const g of h)g.occurredAt>=t&&g.occurredAt<=e&&o.envelopes.push(g);o.composersRead++}catch(l){o.composersFailed++,o.problems.push({path:s,message:`${u.composerId}: ${l instanceof Error?l.message:String(l)}`})}}finally{a.close()}return o}async function x0(t,e){return(await wy(t,e)).envelopes}async function Yf(){const t=by();if(!ve(t))return{available:!1,present:!1,globalStorage:io()};try{const e=new Uo(t,{readOnly:!0});try{const r=e.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:r.n>0,present:!0,globalStorage:io(),composers:r.n}}finally{e.close()}}catch{return{available:!1,present:!0,globalStorage:io()}}}const ao="gemini",I0={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"unsupported",model:"supported",context:"partial",outcome:"partial"},C0="gemini";class Mi extends Error{constructor(e,r){super(e),this.path=r,this.name="GeminiFormatError"}path}const O0="The session file has not been written to for longer than the live window, so the runtime that owned it is gone and the turn ended at its last message.";function N0(t){return(typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(r=>r?.text).filter(r=>typeof r=="string").join(`
7
7
  `):"").split(`
8
- `)[0].trim().slice(0,200)||"Gemini reported an error"}const f0=t=>`gemini:${t}`,Xt=t=>typeof t=="number"&&Number.isFinite(t)?t:0,Zs=t=>typeof t=="string"&&t?t:void 0,Rn=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function p0(t,e){const r=t.split(`
9
- `).filter(a=>a.trim());if(r.length===0)throw new Ei("session file is empty",e);let n=null;const o=[],s=new Map,i=a=>{const c=a;!c||typeof c!="object"||typeof c.id!="string"||(s.has(c.id)||o.push(c.id),s.set(c.id,c))};for(const a of r){let c;try{c=JSON.parse(a)}catch{continue}if(!c||typeof c!="object")continue;const u=c;if(!n&&typeof u.sessionId=="string"){n=u;continue}const d=u.$set;if(d){const l=d.messages;if(Array.isArray(l))for(const m of l)i(m);continue}typeof u.id=="string"&&i(u)}if(!n||!n.sessionId)throw new Ei("session file has no header with a sessionId",e);return{header:n,messages:o.map(a=>s.get(a))}}const oy=t=>Array.isArray(t.content)&&t.content.some(e=>!!e&&typeof e=="object"&&"functionResponse"in e);function h0(t){if(t.type!=="user"||oy(t))return!1;const e=Array.isArray(t.content)?t.content.map(n=>n?.text).filter(n=>typeof n=="string"):[];if(e.length===0)return!1;const r=e[0];return!r.startsWith("<session_context>")&&!r.startsWith("[System:")}function m0(t){const e=Xt(t.input),r=Xt(t.cached);return{[Z.tokensInput]:Math.max(0,e-r),[Z.tokensOutput]:Xt(t.output)+Xt(t.thoughts),[Z.tokensCacheRead]:r,[Z.tokensReasoning]:Xt(t.thoughts),[Z.steps]:1}}function y0(t,e){const{header:r,messages:n}=t,o=r.sessionId,s=Rn(r.startTime);if(s===void 0)throw new Ei("session header has no parseable startTime",e.path);const i=n.filter(g=>Rn(g.timestamp)!==void 0),a=i.length?Math.max(...i.map(g=>Rn(g.timestamp))):s,c=e.workspacePath??"",u=c?Ne(c).toUpperCase():"GEMINI",d=f0(o),m={source:{id:es,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},p=g=>({path:e.path,...g?{recordId:g}:{}}),h=[{...m,occurredAt:s,kind:"began",subject:{type:"session",id:d},claims:[{ns:"agent.session",parts:[u0,o],validFrom:s,validTo:a}],core:{machineId:e.machine.id,label:u,projectLabel:c?Ne(c):void 0,executor:es},attrs:{context:c,"gemini.sessionId":o,"gemini.projectHash":r.projectHash,...Zs(r.kind)?{"gemini.kind":r.kind}:{}},provenance:p(o),seq:"session"}],v=[];for(let g=0;g<n.length;g++)h0(n[g])&&Rn(n[g].timestamp)!==void 0&&v.push(g);if(v.length===0){if(n.some(g=>g.type==="gemini"))throw new Ei(`session has ${n.length} messages including model output but no recognisable user prompt`,e.path);return h}for(let g=0;g<v.length;g++){const I=v[g],N=g+1<v.length?v[g+1]:n.length,S=g+1,T=`${d}:turn:${S}`,x=Rn(n[I].timestamp);let D=x,w,$;const E=[];for(let te=I;te<N;te++){const U=n[te],V=Rn(U.timestamp);if(V===void 0||U.type!=="gemini"&&U.type!=="error"&&!(U.type==="user"&&oy(U))||(V>D&&(D=V),$=U,U.type!=="gemini"))continue;w??=Zs(U.model);const z=Array.isArray(U.toolCalls)?U.toolCalls:[],se=U.tokens?m0(U.tokens):{};z.length&&(se[Z.interactions]=z.length),Object.keys(se).length!==0&&E.push({...m,occurredAt:V,kind:"progressed",subject:{type:"execution",id:T},core:{measures:se},attrs:{...z.length?{"gemini.tools":z.map(ve=>Zs(ve.name)??"unknown")}:{},...Zs(U.model)?{"gemini.model":U.model}:{},...U.tokens?{"gemini.usage.input":Xt(U.tokens.input),"gemini.usage.output":Xt(U.tokens.output),"gemini.usage.cached":Xt(U.tokens.cached),"gemini.usage.thoughts":Xt(U.tokens.thoughts),"gemini.usage.tool":Xt(U.tokens.tool)}:{}},provenance:p(U.id),seq:U.id})}h.push({...m,occurredAt:x,kind:"began",subject:{type:"execution",id:T},core:{machineId:e.machine.id,sessionId:d,label:`${u} · TURN ${S}`,executor:es,model:w,depth:0},attrs:{"gemini.turn":S},provenance:p(n[I].id),seq:`turn:${S}`}),h.push(...E);const B=$?.type==="error",C=$?.type==="gemini"&&!(Array.isArray($.toolCalls)&&$.toolCalls.length),P=g+1<v.length,L=(te,U)=>({...m,occurredAt:D,kind:"ended",subject:{type:"execution",id:T},core:te,...U?{basis:"inferred",assumption:l0}:{},provenance:p(n[I].id),seq:`turn:${S}:end`});B?h.push(L({outcome:"error",failureMessage:d0($)},!1)):P||C&&e.settled?h.push(L({outcome:"completed"},!1)):e.closeOpenTurns&&h.push(L({outcome:C?"completed":"interrupted"},!0))}return h}const g0=3e3;function Zl(){return process.env.GEMINI_HOME||ue(xn(),".gemini")}const sy=()=>ue(Zl(),"tmp"),jf=new Map;async function v0(){const t=new Map;try{const e=JSON.parse(await _r(ue(Zl(),"projects.json"),"utf8"));for(const[r,n]of Object.entries(e.projects??{}))typeof n=="string"&&t.set(n,r)}catch{}return t}async function iy(){const t=sy();if(!ge(t))return[];const e=[];let r;try{r=await Ze(t)}catch{return e}for(const n of r){let o;try{o=await Ze(ue(t,n,"chats"))}catch{continue}for(const s of o)s.startsWith("session-")&&s.endsWith(".jsonl")&&e.push({path:ue(t,n,"chats",s),slug:n})}return e}async function ay(t,e){const r=Vr(),n=Date.now(),o={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},s=await iy();if(s.length===0)return o.storedAvailable=ge(sy()),o;o.storedAvailable=!0;const i=await v0();for(const a of s){let c;try{c=await sn(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=Date.now()-c.mtimeMs,d=u>g0,l=u>Yl,m=`${c.mtimeMs}:${c.size}:${d}:${l}`,p=jf.get(a.path);let h;if(p&&p.stamp===m)h=p.envelopes;else try{const v=p0(await _r(a.path,"utf8"),a.path);h=y0(v,{machine:r,host:Ur(),observedAt:n,path:a.path,workspacePath:i.get(a.slug),settled:d,closeOpenTurns:l}).map(Zt),jf.set(a.path,{stamp:m,envelopes:h})}catch(v){o.sessionsFailed++,o.problems.push({path:a.path,message:v instanceof Error?v.message:String(v)});continue}o.sessionsRead++;for(const v of h)v.occurredAt>=t&&v.occurredAt<=e&&o.envelopes.push(v)}return o}async function b0(t,e){return(await ay(t,e)).envelopes}async function Df(){const t=Zl(),e=(await iy()).length;return{available:e>0,present:ge(t),home:t,sessions:e}}const w0=new Set(["running","waiting"]);function cy(t){return w0.has(t)}function Ql(t,e){return{now:t,dayStart:t,dayEnd:e,machines:new Map,sources:new Map,sessions:new Map,executions:new Map,processes:new Map,artifacts:new Map,transfers:new Map,relationships:[],active:new Set,seen:new Set}}const A0=5*6e4;function S0(t){const e=[];for(const r of t)r.parentId&&e.push({from:{type:"session",id:r.parentId},to:{type:"session",id:r.id},kind:"spawned",basis:"measured",via:"recorded by the child session's own runtime"});return e}function k0(t,e){const r=t.now-A0,n=new Set;for(const a of e)a.from.type==="process"&&n.add(a.from.id),a.to.type==="process"&&n.add(a.to.id);const o=[];let s=0,i=0;for(const a of t.processes.values())a.lastSeenAt>=r&&s++,a.endInferred&&i++,n.has(a.id)&&o.push(a);return{now:t.now,dayStart:t.dayStart,dayEnd:t.dayEnd,machines:[...t.machines.values()],sources:[...t.sources.values()],sessions:[...t.sessions.values()],executions:[...t.executions.values()],processes:o,processTotals:{observed:t.processes.size,recentlySeen:s,exitsInferred:i},relationships:[...e,...S0(t.sessions.values())]}}function xc(t){const e=Ql(t.dayStart,t.dayEnd);e.now=t.now;for(const r of t.machines)e.machines.set(r.id,r);for(const r of t.sources)e.sources.set(`${r.id}:${r.instance}`,r);for(const r of t.sessions)e.sessions.set(r.id,r);for(const r of t.executions)e.executions.set(r.id,r),cy(r.status)&&e.active.add(r.id);for(const r of t.processes)e.processes.set(r.id,r);return e.processTotals=t.processTotals,e.relationships=t.relationships,e}function vt(t,e){const r=t[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function cs(t,e){for(const[r,n]of Object.entries(e)){if(typeof n!="number"||!Number.isFinite(n))continue;const o=r;t[o]=(t[o]??0)+n}}const E0=[Z.tokensInput,Z.tokensOutput,Z.tokensCacheRead];function jr(t){let e=0,r=!1;for(const n of E0){const o=vt(t,n);o!==void 0&&(r=!0,e+=o)}return r?e:void 0}function uy(t){return{input:vt(t,Z.tokensInput)??0,output:vt(t,Z.tokensOutput)??0,cacheRead:vt(t,Z.tokensCacheRead)??0,reasoning:vt(t,Z.tokensReasoning)??0}}function ly(t){const e=jr(t.measures);if(e!==void 0)return Lf(e/1e3,200);const r=vt(t.measures,Z.cpuMs);if(r!==void 0)return Lf(r/1e3,200)}function po(t){return vt(t.measures,Z.interactions)}function dy(t){return vt(t.measures,Z.steps)??0}function xi(t){return vt(t.measures,Z.errors)??0}function su(t){return vt(t.measures,Z.retries)??0}function Lf(t,e){return Math.min(1,Math.log1p(Math.max(0,t))/Math.log1p(e))}function x0(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function Ii(t,e=0){return x0(t+"#"+e)%1e5/1e5}const Ic=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function I0(t){if(t<Ic.length)return Ic[t];const r=-.9+(t-Ic.length)*1.15;return{x:620+Math.cos(r)*520,y:300+Math.sin(r)*250,extentX:150,extentY:94}}function O0(t){const e=r=>r==="laptop"?0:r==="desktop"?1:2;return[...t].sort((r,n)=>e(r.kind)-e(n.kind)||r.firstSeenAt-n.firstSeenAt||(r.id<n.id?-1:r.id>n.id?1:0))}function Pf(t,e){const r=Ii(e,1),n=Ii(e,2),o=r*Math.PI*2+n*2.399963,s=.34+.46*Math.sqrt(n);return{x:t.x+Math.cos(o)*t.extentX*s,y:t.y+Math.sin(o)*t.extentY*s}}const Uf=30,C0=74;function N0(t){return Uf+t*(C0-Uf)}const Vf=64,T0=8,$0=8,Hf=16,Ff=.45;function B0(t,e){switch(t.status){case"running":{const r=e-t.lastActivityAt;return .55+.45*Math.exp(-r/45e3)}case"waiting":return .08;case"failed":return .9;case"completed":return 0;case"idle":return .03}}const Wf=.32;function R0(t){const e=ly(t),r=t.depth>0?.62:1;return e===void 0?Wf*r:Math.min(1,(Wf+.68*e)*r)}function M0(t,e){const r=Math.max(1,(t.endedAt??e)-t.startedAt),n=(po(t)??0)/(r/6e4);return Math.min(1,.25+n/24)}function Kf(t){return(t.status==="failed"?3:t.status==="waiting"?2:t.status==="running"?1:0)*1e15+t.lastActivityAt}function _0(t){const e=new Set,r=new Set,n=new Map,o=new Map,s=(i,a,c)=>{const u=i.get(a);u?u.push(c):i.set(a,[c])};for(const i of t.relationships){const{from:a,to:c,kind:u}=i;u==="ran-as"?(a.type==="execution"&&e.add(a.id),c.type==="execution"&&e.add(c.id),a.type==="session"&&c.type==="process"&&r.add(a.id),c.type==="session"&&a.type==="process"&&r.add(c.id),a.type==="execution"&&c.type==="session"?n.set(a.id,c.id):a.type==="session"&&c.type==="execution"&&n.set(c.id,a.id)):u==="same-as"&&a.type==="execution"&&c.type==="execution"&&(e.add(a.id),e.add(c.id),s(o,a.id,c.id),s(o,c.id,a.id))}return{resolvedExecutions:e,sessionsWithProcess:r,runObservesSession:n,sameExecution:o}}function j0(t,e){const n=t.startBasis===void 0?.5:t.startBasis==="measured"?1:0,o=t.endBasis===void 0?.5:t.endBasis==="measured"?1:0,s=t.endedAt===void 0?n:(n+o)/2,i=ly(t)===void 0?0:1,a=e.resolvedExecutions.has(t.id)||e.sessionsWithProcess.has(t.sessionId)?1:0;return(1+s+i+a)/4}function Gf(t){let e=1;for(const r of t)e*=1-Math.min(1,Math.max(0,r));return 1-e}function qf(t,e,r,n){const o=Math.max(t,r),s=Math.min(e,n);if(s<o)return 0;const i=Math.max(e,n)-Math.min(t,r);return i<=0?1:(s-o)/i}function Oc(t){const e=t.now,r=O0(t.machines.values()).slice(0,T0),n=new Map,o=[];let s=1;const i=new Map;for(const w of t.executions.values()){const $=(i.get(w.machineId)??0)+1;i.set(w.machineId,$),$>s&&(s=$)}r.forEach((w,$)=>{const E=I0($);n.set(w.id,E),o.push({id:w.id,name:w.name,kind:w.kind,x:E.x,y:E.y,extentX:E.extentX,extentY:E.extentY,prominence:(i.get(w.id)??0)/s,seed:Ii(w.id,7)})});const a=45e3,c=[];for(const w of t.executions.values())(w.status==="completed"||w.status==="failed")&&e-(w.endedAt??e)>a||w.status==="idle"&&e-w.lastActivityAt>a*4||n.has(w.machineId)&&c.push(w);c.length>Vf&&(c.sort((w,$)=>Kf($)-Kf(w)),c.length=Vf);const u=_0(t),d=w=>{const $=n.get(w.machineId),{x:E,y:B}=Pf($,w.id),C=t.sessions.get(w.sessionId);return{id:w.id,massId:w.machineId,sessionId:w.sessionId,x:E,y:B,extent:R0(w),energy:B0(w,e),rate:M0(w,e),phase:Ii(w.id,3)*Math.PI*2,status:w.status,label:w.label,projectLabel:C?.projectLabel,taskLabel:C?.taskLabel,statusSince:w.waitingSince??w.endedAt??w.startedAt,articulation:j0(w,u),shoulder:0,observers:1}},l=new Set(c.map(w=>w.id)),m=new Set,p=[],h=w=>[w.startedAt,w.endedAt??e];for(const w of[...c].sort(($,E)=>$.id<E.id?-1:1)){if(m.has(w.id))continue;const $=[w];m.add(w.id);for(let te=0;te<$.length;te++)for(const U of u.sameExecution.get($[te].id)??[])!l.has(U)||m.has(U)||(m.add(U),$.push(t.executions.get(U)));if($.length===1){p.push(d(w));continue}const E=$.map(d),B=E.reduce((te,U)=>U.articulation>te.articulation||U.articulation===te.articulation&&U.id<te.id?U:te);let C=1;const[P,L]=h(t.executions.get(B.id));for(const te of $){const[U,V]=h(te);C=Math.min(C,qf(P,L,U,V))}p.push({...B,extent:Math.max(...E.map(te=>te.extent)),energy:Math.max(...E.map(te=>te.energy)),articulation:Gf(E.map(te=>te.articulation)),shoulder:Math.min(Ff,1-C),observers:$.length})}const v=new Map;for(const w of p){if(u.runObservesSession.has(w.id))continue;const $=v.get(w.sessionId);$?$.push(w):v.set(w.sessionId,[w])}const g=new Map,I=[];for(const w of p){const $=u.runObservesSession.get(w.id),E=$?v.get($):void 0;if(!$||!E||E.length===0){if(I.push(w),$){const V=v.get(w.sessionId);V?V.push(w):v.set(w.sessionId,[w])}continue}const B=t.executions.get(w.id);let C=1/0,P=-1/0;for(const V of E){const[z,se]=h(t.executions.get(V.id));C=Math.min(C,z),P=Math.max(P,se)}const[L,te]=h(B),U=g.get($)??{articulations:[],coincidence:1};U.articulations.push(w.articulation),U.coincidence=Math.min(U.coincidence,qf(L,te,C,P)),g.set($,U)}const N=[];for(const w of[...v.keys()].sort()){const $=v.get(w),E=t.sessions.get(w);if(!E||$.length===0)continue;let B=0,C=0;for(const V of $)B+=V.x,C+=V.y;B/=$.length,C/=$.length;let P=0,L=0;for(const V of $){const z=N0(V.extent);P=Math.max(P,Math.abs(V.x-B)+z*1.5),L=Math.max(L,Math.abs(V.y-C)+z)}const te=g.get(w),U=Math.max(...$.map(V=>V.articulation));N.push({id:w,massId:$[0].massId,x:B,y:C,extentX:Math.max(P,52),extentY:Math.max(L,36),presence:1,articulation:te?Gf([U,...te.articulations]):U,parentId:E.parentId,empty:!1,shoulder:te?Math.min(Ff,1-te.coincidence):0,observers:1+(te?.articulations.length??0),label:E.label??E.executor??w,projectLabel:E.projectLabel,taskLabel:E.taskLabel})}for(const w of[...t.sessions.values()].sort(($,E)=>$.id<E.id?-1:1)){if(w.executionIds.length>0||w.endedAt!==void 0&&e-w.endedAt>a)continue;const $=n.get(w.machineId);if(!$)continue;const{x:E,y:B}=Pf($,`session-presence:${w.id}`);N.push({id:w.id,massId:w.machineId,x:E,y:B,extentX:64,extentY:42,presence:1,articulation:u.sessionsWithProcess.has(w.id)?.5:.25,parentId:w.parentId,empty:!0,shoulder:0,observers:1,label:w.label??w.executor??w.id,projectLabel:w.projectLabel,taskLabel:w.taskLabel})}if(N.length>Hf){const w=$=>$.empty?0:v.get($.id)?.length??0;N.sort(($,E)=>w(E)-w($)||($.id<E.id?-1:1)),N.length=Hf}const S=[];for(const w of t.transfers.values())if(w.endedAt===void 0&&!(!n.has(w.fromMachineId)||!n.has(w.toMachineId))){if(S.length>=$0)break;S.push({id:w.id,fromMassId:w.fromMachineId,toMassId:w.toMachineId,energy:1,label:w.label})}const T=new Map;r.forEach((w,$)=>T.set(w.id,$));const x=Math.max(1,t.dayEnd-t.dayStart),D=[];for(const w of t.executions.values()){const $=T.get(w.machineId);if($===void 0)continue;const E=(w.startedAt-t.dayStart)/x,B=((w.endedAt??e)-t.dayStart)/x;D.push({id:w.id,massId:w.machineId,lane:$,startFraction:Math.max(0,Math.min(1,E)),endFraction:Math.max(0,Math.min(1,B)),status:w.status,label:w.label})}return{time:e,masses:o,disturbances:I,plinths:N,couplings:S,strata:D}}const Oi="057.landscape",us=1;function D0(t){return{contract:Oi,version:us,landscape:t}}const fy=9e4;function zf(t,e){if(t.waitingSince===void 0)return;const r=t.waitingSince,n=Math.max(r,e);t.waitingMs+=n-r,t.waits.push({start:r,end:n})}function L0(t,e){const r=`${e.source.id}:${e.source.instance}`;let n=t.sources.get(r);n||(n={id:e.source.id,instance:e.source.instance,origin:e.source.instance,firstSeenAt:e.occurredAt,lastSeenAt:e.occurredAt,events:0,strata:{}},t.sources.set(r,n)),n.events++,e.occurredAt<n.firstSeenAt&&(n.firstSeenAt=e.occurredAt),e.occurredAt>n.lastSeenAt&&(n.lastSeenAt=e.occurredAt),e.stratum&&(n.strata[e.stratum]=(n.strata[e.stratum]??0)+1);const o=e.provenance?.sourceVersion;o&&(n.sourceVersions?n.sourceVersions.includes(o)||n.sourceVersions.push(o):n.sourceVersions=[o])}function P0(t,e){if(t.seen.has(e.id))return;t.seen.add(e.id),e.occurredAt>t.now&&(t.now=e.occurredAt),L0(t,e);const r=e.core??{},n=e.occurredAt;switch(e.subject.type){case"machine":{if(t.machines.has(e.subject.id))break;const o={id:e.subject.id,name:r.machineName??e.subject.id,kind:r.machineKind??"laptop",parentId:r.parentId,firstSeenAt:n};t.machines.set(o.id,o);break}case"session":{if(e.kind==="began"){const o=t.sessions.get(e.subject.id);if(o){o.parentId===void 0&&r.parentId&&(o.parentId=r.parentId),o.projectLabel===void 0&&r.projectLabel&&(o.projectLabel=r.projectLabel),o.taskLabel===void 0&&r.taskLabel&&(o.taskLabel=r.taskLabel);break}const s={id:e.subject.id,machineId:r.machineId??"",label:r.label,projectLabel:r.projectLabel,taskLabel:r.taskLabel,context:e.attrs?.context??r.label??"",executor:r.executor,model:r.model,startedAt:n,executionIds:[],parentId:r.parentId};t.sessions.set(s.id,s)}else if(e.kind==="ended"){const o=t.sessions.get(e.subject.id);o&&(o.endedAt=n)}break}case"execution":U0(t,e,n);break;case"process":V0(t,e,n);break;case"artifact":{if(t.artifacts.has(e.subject.id))break;t.artifacts.set(e.subject.id,{id:e.subject.id,kind:"file",path:r.label??e.subject.id,firstSeenAt:n});break}}}function U0(t,e,r){const n=e.core??{},o=e.subject.id;if(e.kind==="began"){if(t.executions.has(o))return;const i={id:o,sessionId:n.sessionId??n.parentId??"",machineId:n.machineId??"",label:n.label??o,executor:n.executor??"unknown",model:n.model,status:"running",startedAt:r,lastActivityAt:r,measures:{},waitingMs:0,waits:[],parentId:n.parentId,depth:n.depth??0,startBasis:e.basis,boundsAssumption:e.assumption};n.measures&&cs(i.measures,n.measures),t.executions.set(o,i),t.active.add(o),t.sessions.get(i.sessionId)?.executionIds.push(o);return}const s=t.executions.get(o);if(s)switch(s.endBasis==="inferred"&&s.endedAt!==void 0&&r>s.endedAt&&(e.kind==="progressed"||e.kind==="blocked"||e.kind==="resumed")&&(delete s.endedAt,delete s.endBasis,delete s.outcome,delete s.failure,s.startBasis!=="inferred"&&delete s.boundsAssumption,s.status="running",t.active.add(o)),e.kind){case"progressed":{n.measures&&cs(s.measures,n.measures),s.lastActivityAt=r,s.status==="idle"&&(s.status="running",t.active.add(o));break}case"blocked":{if(!cy(s.status))break;s.status="waiting",s.waitingSince=r,s.waitReason=n.blockedOn??"input",s.lastActivityAt=r;break}case"resumed":{zf(s,r),s.status="running",s.waitingSince=void 0,s.waitReason=void 0,s.lastActivityAt=r,t.active.add(o);break}case"ended":{const i=n.outcome==="error";s.status=i?"failed":"completed",s.endedAt=r,s.endBasis=e.basis,e.assumption&&!s.boundsAssumption&&(s.boundsAssumption=e.assumption),s.lastActivityAt=r,s.outcome=n.outcome??"completed",i&&(s.failure={code:n.failureCode??"ERROR",message:n.failureMessage??"Execution failed"}),zf(s,r),s.waitingSince=void 0,s.waitReason=void 0,t.active.delete(o);break}case"observed":s.lastActivityAt=Math.max(s.lastActivityAt,r);break}}function V0(t,e,r){const n=e.core??{},o=e.subject.id,s=Number(e.attrs?.["os.pid"]??0);if(e.kind==="began"){if(t.processes.has(o))return;const a={id:o,machineId:n.machineId??"",pid:s,ppid:typeof e.attrs?.["os.ppid"]=="number"?e.attrs["os.ppid"]:void 0,command:n.label??n.executor??String(s),startedAt:r,lastSeenAt:r,status:"running",measures:{}};n.measures&&cs(a.measures,n.measures),t.processes.set(o,a);return}const i=t.processes.get(o);if(i)if(e.kind==="observed"||e.kind==="progressed"){if(i.lastSeenAt=Math.max(i.lastSeenAt,r),n.measures){const a=n.measures[Z.cpuMs];typeof a=="number"&&(i.measures[Z.cpuMs]=a);const{[Z.cpuMs]:c,...u}=n.measures;cs(i.measures,u)}}else e.kind==="ended"&&(i.endedAt=r,i.lastSeenAt=Math.max(i.lastSeenAt,r),i.status="exited",i.endInferred=e.basis==="inferred")}function py(t,e){for(let r=0;r<e.length;r++)P0(t,e[r])}function hy(t,e){e>t.now&&(t.now=e),e=t.now;for(const r of t.active){const n=t.executions.get(r);if(!n){t.active.delete(r);continue}n.status==="running"&&e-n.lastActivityAt>fy&&(n.status="idle")}}const my=`Wall-clock time covered by recorded run intervals, with parallel intervals counted once and waiting included. An open running record becomes idle after ${fy/1e3} seconds without an event; its interval then stops at its last event instead of the period end. Explicit waits still count to the period end. A later event or ending includes the intervening silence again. The estimate can decrease or be revised. In flight is not computing time or human attention.`,ft=t=>({value:t,basis:"measured"}),Oo=(t,e)=>({value:t,basis:"inferred",assumption:e});function ed(t){if(t.length===0)return[];t.sort((r,n)=>r.start-n.start);const e=[{start:t[0].start,end:t[0].end}];for(let r=1;r<t.length;r++){const n=t[r],o=e[e.length-1];n.start<=o.end?n.end>o.end&&(o.end=n.end):e.push({start:n.start,end:n.end})}return e}function yy(t){let e=0;for(const r of t)e+=r.end-r.start;return e}function H0(t){const e=t.filter(s=>s.end>s.start).flatMap(s=>[{at:s.start,delta:1},{at:s.end,delta:-1}]).sort((s,i)=>s.at-i.at||s.delta-i.delta);let r=0,n=e[0]?.at??0,o=0;for(const s of e)r>=2&&(o+=s.at-n),r+=s.delta,n=s.at;return o}function gy(t){if(t.length===0)return{peak:0,at:0};const e=[];for(const s of t)e.push({t:s.start,d:1}),e.push({t:s.end,d:-1});e.sort((s,i)=>s.t-i.t||s.d-i.d);let r=0,n=0,o=e[0].t;for(const s of e)r+=s.d,r>n&&(n=r,o=s.t);return{peak:n,at:o}}function F0(t){if(t.length===0)return;const e=[...t].sort((n,o)=>n-o),r=e.length>>1;return e.length%2?e[r]:(e[r-1]+e[r])/2}function ho(t,e,r=t.startedAt){const n=Math.max(r,t.startedAt),o=Math.min(e,t.endedAt??(t.status==="idle"?t.lastActivityAt:e));return{start:n,end:Math.max(n,o)}}function td(t,e){return t.waitingMs+(t.waitingSince===void 0?0:Math.max(0,e-t.waitingSince))}function rd(t){const e=t.now,r=[...t.executions.values()];let n=0,o=0,s=0;const i={tokens:0,tools:0,requests:0};let a=0,c=0,u=0,d=0,l=0;const m=[],p=new Map;for(const x of r){n+=dy(x),vt(x.measures,Z.steps)!==void 0&&i.requests++;const D=jr(x.measures),w=po(x);D!==void 0&&(o+=D,i.tokens++),w!==void 0&&(s+=w,i.tools++),x.status==="completed"&&x.outcome!=="interrupted"?a++:x.status==="failed"?c++:x.status==="waiting"?u++:x.status==="idle"&&d++;const $=ho(x,e,t.dayStart);m.push($),l+=x.waitingMs,x.waitingSince!==void 0&&(l+=Math.max(0,e-x.waitingSince));let E=p.get(x.machineId);E||(E={machineId:x.machineId,executions:0,tokens:0,computeTime:0},p.set(x.machineId,E)),E.executions++,E.tokens+=jr(x.measures)??0,E.computeTime+=$.end-$.start}const h=ed(m.map(x=>({...x}))),{peak:v,at:g}=gy(m),I=W0(t),N=G0(I);let S=null;for(const x of I)(!S||x.end-x.start>S.end-S.start)&&(S=x);let T=0;for(const x of t.sessions.values())x.executionIds.some(D=>t.executions.has(D))&&T++;return{requests:ft(n),sessions:ft(T),executions:ft(r.length),tokens:ft(o),toolCalls:ft(s),accounting:i,timeInFlight:Oo(yy(h),my),parallelTime:Oo(H0(m),"Wall-clock time in this period with at least two runs in flight. Parallel intervals count once; waiting is included and trailing idle silence is excluded."),peakConcurrency:r.some(x=>x.startBasis==="inferred"||x.endBasis==="inferred"||x.status==="idle")?Oo(v,"Peak overlap of the recorded run intervals in this period. Some bounds are inferred, or an idle interval ends at its last observed output."):ft(v),peakConcurrencyAt:ft(g),contextSwitches:Oo(N,"Changes between successive non-overlapping groups of runs, each confined to one known working directory. Groups containing concurrent work in different directories are excluded. This does not measure human attention."),longestContextSpan:Oo(S,"Longest span of consecutive runs in one working directory, including gaps of up to 15 minutes. Other contexts may run concurrently. This does not measure human focus."),waitingOnYou:ft(l),completed:ft(a),failed:ft(c),waiting:ft(u),idle:ft(d),byMachine:p,contextSpans:I,transfers:ft(t.transfers.size)}}function W0(t){const e=[];for(const n of t.executions.values()){const o=t.sessions.get(n.sessionId);if(!o?.context)continue;const s=ho(n,t.now,t.dayStart);s.end>s.start&&e.push({context:o.context,...s})}e.sort((n,o)=>n.start-o.start);const r=[];for(const n of e){const o=r[r.length-1];o&&o.context===n.context&&n.start<=o.end?n.end>o.end&&(o.end=n.end):o&&o.context===n.context?n.start-o.end<=K0?o.end=Math.max(o.end,n.end):r.push({context:n.context,start:n.start,end:n.end}):r.push({context:n.context,start:n.start,end:n.end})}return r}const K0=15*6e4;function G0(t){let e=-1/0,r=new Set,n,o=0;const s=()=>{const i=r.size===1?[...r][0]:void 0;n!==void 0&&i!==void 0&&n!==i&&o++,n=i};for(const i of t)i.end<=i.start||(i.start>=e&&(r.size>0&&s(),r=new Set),r.add(i.context),e=Math.max(e,i.end));return r.size>0&&s(),o}function q0(t){return{key:t,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function Qs(t,e){const r=new Map,n=new Map;for(const o of t.executions.values()){const s=e(o,t.sessions.get(o.sessionId));if(s===void 0)continue;let i=r.get(s);i||(i=q0(s),r.set(s,i)),i.runs++;const a=jr(o.measures);if(a!==void 0&&(i.tokens+=a,i.tokenRuns++,o.endedAt!==void 0&&o.startedAt>=t.dayStart&&o.endedAt<=t.now&&o.endedAt<t.dayEnd)){let u=n.get(s);u||(u=[],n.set(s,u)),u.push(a)}const c=ho(o,t.now,t.dayStart);i.computeMs+=c.end-c.start,i.waitingMs+=td(o,t.now),i.toolCalls+=po(o)??0,o.status==="failed"&&i.failed++}for(const[o,s]of n){const i=r.get(o);i&&(i.medianTokens=F0(s),i.medianRuns=s.length)}return[...r.values()].sort((o,s)=>s.computeMs-o.computeMs)}function z0(t){const e={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const r of t.executions.values()){const n=uy(r.measures);e.input+=n.input,e.output+=n.output,e.cacheRead+=n.cacheRead,e.reasoning+=n.reasoning}return e.total=e.input+e.output+e.cacheRead,e}function Y0(t){const e={count:0,totalMs:0,longestMs:0,openNow:0};for(const r of t.executions.values()){for(const n of r.waits){e.count++;const o=n.end-n.start;e.totalMs+=o,o>e.longestMs&&(e.longestMs=o)}if(r.waitingSince!==void 0){e.count++,e.openNow++;const n=t.now-r.waitingSince;e.totalMs+=n,n>e.longestMs&&(e.longestMs=n)}}return e}function vy(t){const e={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const r of t.executions.values())e.toolCalls+=po(r)??0,e.toolErrors+=xi(r),e.retries+=su(r),r.status==="failed"?e.failed++:r.outcome==="interrupted"?e.interrupted++:r.outcome==="completed"&&e.completed++;return e}function Yf(t,e){const r=[...t.executions.values()].map(i=>{const a=ho(i,t.now);return{start:Math.max(t.dayStart,a.start),end:Math.min(t.now,a.end)}}).filter(i=>i.end>i.start);if(r.length===0)return[];const n=ed(r.map(i=>({...i}))),o=new Date(t.dayStart);e==="day"?o.setHours(0,0,0,0):o.setMinutes(0,0,0);const s=[];for(let i=o.getTime();i<t.now;){const a=new Date(i);e==="day"?a.setDate(a.getDate()+1):a.setTime(i+36e5);const c=a.getTime(),u=n.reduce((l,m)=>l+Math.max(0,Math.min(m.end,c)-Math.max(m.start,i)),0),d=r.filter(l=>l.start<c&&l.end>i).map(l=>({start:Math.max(l.start,i),end:Math.min(l.end,c)}));s.push({from:i,to:c,computeMs:u,runs:d.length,peak:gy(d).peak}),i=c}return s}const nd="SHAPES FIELD",od="METADATA — DOES NOT SHAPE FIELD";function sd(t){const e=new Date(t),r=n=>String(n).padStart(2,"0");return`${r(e.getHours())}:${r(e.getMinutes())}:${r(e.getSeconds())}`}function Xf(t){const e=new Date(t),r=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())} ${sd(t).slice(0,5)}`}function X0(t){return fe(t).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function Jf(t,e,r,n,o=()=>{},s){if(r==="mass")return Q0(t,e,n);if(r==="coupling")return eA(t,n);const i=t.executions.get(n);if(!i)return null;const a=s?.[n],c=a?{...i,startedAt:a.at,startBasis:a.basis,boundsAssumption:a.assumption??i.boundsAssumption}:i;return J0(t,e,c,r,o("execution",n))}function J0(t,e,r,n,o){const s=t.sessions.get(r.sessionId),i=t.machines.get(r.machineId),c=e.disturbances.find(I=>I.id===r.id)?.statusSince??r.endedAt??r.startedAt,u=r.startBasis==="inferred"||r.endBasis==="inferred",d=jr(r.measures),l=r.outcome==="interrupted",m=[{key:"MACHINE",value:(i?.name??r.machineId).toUpperCase()},{key:"STATE",value:l?"STOPPED":r.status.toUpperCase(),tone:l?void 0:r.status},{key:"SINCE",value:sd(c)},d===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:ze(d)}];if(s){const I=s.executionIds.indexOf(r.id),N=e.plinths.some(T=>T.id===s.id),S=I>=0?`${I+1} OF ${s.executionIds.length}`:`OF ${s.executionIds.length}`;m.push({key:"SESSION",value:N?`${S} · PLINTH`:S})}const p=Z0(t,r.id),h=[r.model??s?.model?{key:"MODEL",value:r.model??s?.model}:{key:"MODEL",value:"not observed",tone:"absent",note:"This source does not record the model."}];s?.projectLabel&&h.push({key:"PROJECT",value:s.projectLabel}),s?.context&&h.push({key:"FOLDER",value:Ne(s.context),note:s.context}),h.push({key:"SOURCE",value:[r.executor,p===void 0?void 0:`pid ${p}`].filter(Boolean).join(" · "),note:o}),h.push({key:"REQUESTS",value:String(dy(r))}),h.push({key:"STARTED",value:`${r.startBasis==="inferred"?"~":""}${Xf(r.startedAt)}`,note:r.startBasis==="inferred"?r.boundsAssumption??"The start bound was inferred by the source.":void 0}),r.endedAt!==void 0&&h.push({key:"ENDED",value:`${r.endBasis==="inferred"?"~":""}${Xf(r.endedAt)}`,note:r.endBasis==="inferred"?r.boundsAssumption??"The end bound was inferred by the source.":void 0});const v=po(r);if(h.push(v===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:Jb(v)}),h.push({key:"ELAPSED",value:`${fe((r.endedAt??t.now)-r.startedAt)}${u?" · inferred":""}`,note:[u?r.boundsAssumption:void 0,r.startedAt<t.dayStart?"Full elapsed interval includes time before the selected window.":void 0].filter(Boolean).join(" · ")||void 0}),d!==void 0){const I=uy(r.measures);h.push({key:"INPUT",value:ze(I.input)},{key:"OUTPUT",value:ze(I.output)}),h.push({key:"CACHE READ",value:ze(I.cacheRead)},{key:"REASONING",value:ze(I.reasoning)})}xi(r)>0&&h.push({key:"TOOL ERRORS",value:String(xi(r)),tone:"failed"}),su(r)>0&&h.push({key:"RETRIES",value:String(su(r)),tone:"waiting",note:"Provider retries."}),(r.waits.length>0||r.waitingMs>0||r.waitingSince!==void 0)&&h.push({key:"BLOCKED",value:`${fe(td(r,t.now))} on you · ${r.waits.length+(r.waitingSince===void 0?0:1)}×${r.waitingSince===void 0?"":" · still waiting"}`,tone:"waiting"}),r.depth>0&&h.push({key:"SUB-AGENT",value:`depth ${r.depth}`});const g=!l&&(r.status==="running"||r.status==="waiting");return{id:r.id,eyebrow:n==="stratum"||!g?"SELECTED · RUN":"SELECTED · PROCESS",title:r.label.toUpperCase(),state:{text:l?"STOPPED":g?`${r.status.toUpperCase()} · ${X0(t.now-c)}`:r.status.toUpperCase(),status:l?void 0:r.status},groups:[{title:nd,metadata:!1,rows:m},{title:od,metadata:!0,rows:h}],failure:r.failure?`${r.failure.code}: ${r.failure.message}`:void 0,reveal:o}}function Z0(t,e){for(const r of t.relationships){if(r.kind!=="ran-as")continue;const n=r.from.type==="execution"&&r.from.id===e&&r.to.type==="process"?r.to.id:r.to.type==="execution"&&r.to.id===e&&r.from.type==="process"?r.from.id:void 0;if(n)return t.processes.get(n)?.pid}}function Q0(t,e,r){const n=t.machines.get(r);if(!n)return null;let o=0,s=0,i=0,a;for(const p of t.executions.values()){if(p.machineId!==n.id)continue;const h=jr(p.measures);h!==void 0&&(a=(a??0)+h),p.status==="running"?o++:p.status==="waiting"?s++:i++}const u=[{key:"KIND",value:(e.masses.find(p=>p.id===r)?.kind??n.kind).toUpperCase()},{key:"RUNNING",value:String(o),tone:o>0?"running":void 0}];s>0&&u.push({key:"WAITING",value:String(s),tone:"waiting"}),u.push({key:"RAN TODAY",value:String(i)});const d=[a===void 0?{key:"TOKENS",value:"not observed",tone:"absent",note:"No execution in this window reported token accounting."}:{key:"TOKENS",value:ze(a)}],l=t.processTotals;if(l){const p=new Set;for(const h of t.relationships)h.kind==="ran-as"&&(h.from.type==="process"&&p.add(h.from.id),h.to.type==="process"&&p.add(h.to.id));d.push({key:"PROCESSES",value:`${l.observed} observed`}),d.push({key:"LAST 5 MIN",value:`${l.recentlySeen} seen`,note:"Processes with a liveness observation in the last five minutes. The sampler never witnesses an exit, so recency is the honest liveness signal."}),d.push({key:"ATTRIBUTED",value:`${p.size} of ${l.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const m=o+s;return{id:r,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:m>0?{text:`${m} ACTIVE`,status:o>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:nd,metadata:!1,rows:u},{title:od,metadata:!0,rows:d}]}}function eA(t,e){const r=t.transfers.get(e);if(!r)return null;const n=t.machines.get(r.fromMachineId)?.name??r.fromMachineId,o=t.machines.get(r.toMachineId)?.name??r.toMachineId;return{id:e,eyebrow:"SELECTED · TRANSFER",title:`${n} → ${o}`.toUpperCase(),state:{text:"TRANSFERRING",status:"running"},groups:[{title:nd,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:o.toUpperCase()},{key:"SINCE",value:sd(r.startedAt)}]},{title:od,metadata:!0,rows:[{key:"WHAT",value:r.label},{key:"SIZE",value:Zb(r.bytes)}]}]}}const tA=6e4;function rA(t,e){const r=[],n=e.contextSpans,o=e.longestContextSpan.value;if(e.executions.value===0)return{headline:"NO RUN RECORDS",clauses:["No runs observed in this window. This does not establish inactivity."]};const s=e.peakConcurrency.value>1?`UP TO ${e.peakConcurrency.value} RUNS AT ONCE`:"ONE RUN AT A TIME";if(e.peakConcurrency.value>=2?(r.push(`Up to ${e.peakConcurrency.value} runs in flight at once; ${fe(e.timeInFlight.value)} of wall-clock time had a run in flight.`),r.push(`Parallel runs overlapped for ${fe(e.parallelTime.value)} within this period; each instant counts once.`)):r.push(`Runs happened one at a time, across ${fe(e.timeInFlight.value)} of wall-clock time.`),o&&r.push(`The longest context span covered ${fe(o.end-o.start)} in ${Ne(o.context)}; gaps of up to 15 minutes are included.`),e.contextSwitches.value>0){const i=new Set(n.map(a=>a.context)).size;r.push(`${e.contextSwitches.value} sequential ${e.contextSwitches.value===1?"change":"changes"} between working directories, across ${i} contexts; concurrent contexts are excluded.`)}if(e.waitingOnYou.value>tA&&r.push(`${fe(e.waitingOnYou.value)} was spent with a run waiting on your answer.`),e.failed.value>0&&r.push(`${e.failed.value} of ${e.executions.value} runs ended in failure; ${e.completed.value} completed.`),e.byMachine.size>1){const i=[...e.byMachine.values()].sort((a,c)=>c.computeTime-a.computeTime).map(a=>`${t.machines.get(a.machineId)?.name??a.machineId} ${fe(a.computeTime)}`);r.push(`Summed run intervals by machine: ${i.join(", ")}.`)}return{headline:s,clauses:r}}const Zf="(no model)";function nA(t){if(t.medianTokens===void 0)return t.tokenRuns>0?{text:"no complete runs in this window for a median",title:"Token accounting is present. The median requires ended runs with both bounds inside this window; open and boundary-crossing runs are excluded.",absent:!0}:{text:"no token accounting",title:"No run in this group reports token accounting, so there is no figure — not a figure of zero.",absent:!0};if(t.medianRuns===1)return{text:`single run ${ze(t.medianTokens)}`,title:"One ended run fully inside this window reports accounting, so this is its figure, not a median. Open and boundary-crossing runs are excluded.",absent:!1};const e=t.medianRuns===t.runs?`${t.runs}`:`${t.medianRuns} of ${t.runs}`;return{text:`median ${ze(t.medianTokens)} over ${e} runs`,title:`Median billed tokens per complete run, over the runs in this group fully inside this window that have ended and whose source reports token accounting — ${t.medianRuns} of ${t.runs} here. Runs still in flight are excluded: their totals are partial. Boundary-crossing runs are excluded. Runs whose source persists no accounting are excluded: absence is not zero. Same window as the rest of TODAY.`,absent:!1}}function oA(t,e,r){if(r&&r.reported===0)return jt("WAITING ON YOU","—",void 0,{note:"not reported by sources in this window"});const n=e.count>0?`${e.count} ${e.count===1?"block":"blocks"} · longest ${fe(e.longestMs)}`:void 0,o=r&&r.reported<r.runs?`from the ${r.reported} of ${r.runs} runs whose sources report waits`:void 0;return jt("WAITING ON YOU",fe(t.value),t,{tone:t.value>0?"waiting":void 0,note:[n,o].filter(Boolean).join(" · ")||void 0})}function jt(t,e,r,n={}){const o=r?.basis==="inferred";return{key:t,value:e,inferred:o,assumption:o?r?.assumption:void 0,...n}}function Cc(t,e,r,n,o){return jt(t,r>0?ze(e.value):"—",e,{note:r===0?"not reported in this window":[o,r<n?`reported for ${r} of ${n} runs`:void 0].filter(Boolean).join(" · ")||void 0})}function sA(t){const e=[["CACHE READS",t.cacheRead],["INPUT",t.input],["OUTPUT",t.output]].map(([r,n])=>({key:r,value:ze(n),fraction:n/Math.max(1,t.total),percent:Math.round(n/Math.max(1,t.total)*100),percentLabel:wi(n,t.total)}));return t.reasoning>0&&e.push({key:"REASONING · OF OUTPUT",value:ze(t.reasoning),subset:!0,fraction:t.reasoning/Math.max(1,t.output),percent:Math.round(t.reasoning/Math.max(1,t.output)*100),percentLabel:wi(t.reasoning,t.output)}),e}function Nc(t,e,r){const n=t[0]?.computeMs??0;return t.map(o=>({key:o.key,label:e(o.key),detail:`${o.runs} ${o.runs===1?"run":"runs"}${o.tokenRuns>0?` · ${ze(o.tokens)} tok${o.tokenRuns<o.runs?` (${o.tokenRuns}/${o.runs} reported)`:""}`:" · tokens not reported"} · ${fe(o.computeMs)}`,failed:o.failed,fraction:n>0?o.computeMs/n:0,median:r?nA(o):void 0}))}function Qf(t,e,r="today"){const n=rd(t),o=rA(t,n),s=z0(t),i=Y0(t),a=vy(t),c=r==="today"?Yf(t,"hour"):[],u=r==="last-7d"?Yf(t,"day"):[],d=Qs(t,(A,ae)=>ae?.context),l=Qs(t,A=>A.model??Zf),m=Qs(t,A=>A.machineId),p=[...t.executions.values()],h=p.filter(A=>A.endedAt===void 0),v=p.length-h.length,g=p.filter(A=>A.endBasis==="inferred").length,I=p.filter(A=>(A.measures.errors??0)>0),N=[[I.filter(A=>A.outcome==="completed").length,"completed"],[I.filter(A=>A.status==="failed").length,"failed"],[I.filter(A=>A.outcome==="interrupted").length,"stopped"],[I.filter(A=>A.endedAt===void 0).length,"still open"]],S=Qs(t,A=>A.sessionId).filter(A=>A.tokenRuns>0).sort((A,ae)=>ae.tokens-A.tokens).slice(0,3).map(A=>({sessionId:A.key,label:t.sessions.get(A.key)?.taskLabel??t.sessions.get(A.key)?.label??"Session",detail:`${ze(A.tokens)} tok · ${wi(A.tokens,n.tokens.value)} of reported volume · ${A.runs} runs${A.tokenRuns<A.runs?` · ${A.tokenRuns}/${A.runs} reported`:""}`,fraction:A.tokens/Math.max(1,n.tokens.value)})),T=p.filter(A=>A.depth>0).length,x=n.longestContextSpan.value,D=A=>r==="today"?wf(A):`${new Date(A).toLocaleDateString("en-GB",{day:"2-digit",month:"short"})} ${wf(A)}`,w=(A,ae)=>`${A} ${ae}${A===1?"":"s"}`,$=A=>[[A.filter(ye=>ye.outcome==="completed").length,"completed","completed","completed"],[A.filter(ye=>ye.status==="failed"&&ye.outcome!=="interrupted").length,"failed","failed","failed"],[A.filter(ye=>ye.outcome==="interrupted").length,"stopped","stopped","stopped"],[A.filter(ye=>ye.endedAt===void 0&&ye.status==="waiting").length,"waiting","waiting for your response","need response"],[A.filter(ye=>ye.endedAt===void 0&&ye.status==="running").length,"running","with recent events","with recent events"],[A.filter(ye=>ye.endedAt===void 0&&ye.status==="idle").length,"idle","without a recorded ending","no ending"]].filter(([ye])=>ye>0).map(([ye,we,Wt,He])=>({filter:we,label:`${ye} ${we==="waiting"&&ye===1?"needs response":He}`,text:`${ye} ${Wt}`})),E=A=>$(A).map(ae=>ae.text).join(" · "),B=new Map;for(const A of p){const ae=B.get(A.sessionId)??[];ae.push(A),B.set(A.sessionId,ae)}const C=[...B].map(([A,ae])=>{const ye=t.sessions.get(A),we=ae.map(Kt=>ho(Kt,t.now,t.dayStart)),Wt=yy(ed(we)),He=Math.min(t.now,ae.reduce((Kt,Ir)=>Math.max(Kt,Ir.endedAt??Ir.lastActivityAt),t.dayStart)),$n=ae.reduce((Kt,Ir)=>Math.min(Kt,Math.max(t.dayStart,Ir.startedAt)),t.now),Gr=we.reduce((Kt,Ir)=>Math.max(Kt,Ir.end),$n);return{sessionId:A,label:ye?.taskLabel??ye?.label??"Untitled session",taskLabel:ye?.taskLabel??null,project:ye?.projectLabel??null,context:ye?.context?Ne(ye.context):null,detail:`${w(ae.length,"run")} · ${fe(Wt)} recorded run time · ${D($n)}–${D(Gr)}`,outcomes:E(ae),states:$(ae),time:fe(Wt),span:`${D($n)}–${D(Gr)}`,runCount:ae.length,timeMs:Wt,lastAt:He}}).sort((A,ae)=>ae.timeMs-A.timeMs||ae.lastAt-A.lastAt||A.sessionId.localeCompare(ae.sessionId)),P=[],L=h.filter(A=>A.status==="waiting"),te=h.filter(A=>A.status==="running"),U=h.filter(A=>A.status==="idle");L.length&&P.push({filter:"waiting",title:`${w(L.length,"run")} waiting for your response`,detail:"The source explicitly recorded a request for input or approval."}),te.length&&P.push({filter:"running",title:`${w(te.length,"run")} with recent events`,detail:"An ending has not been recorded. Open the runs to inspect their latest events."}),a.failed&&P.push({filter:"failed",title:`${w(a.failed,"run")} ended with a failure`,detail:"Open the records to inspect the reported failure. A later retry may be a separate run."}),a.interrupted&&P.push({filter:"stopped",title:`${w(a.interrupted,"run")} stopped before completion`,detail:"The source recorded an interruption; it does not say whether stopping was intentional."}),I.length&&P.push({filter:"toolErrors",title:`${w(I.length,"run")} reported tool errors`,detail:N.filter(([A])=>A>0).map(([A,ae])=>`${A} ${ae}`).join(" · ")+". Error resolution is not recorded."}),U.length&&P.push({filter:"idle",title:`${w(U.length,"run")} without a recorded ending`,detail:(U.length===1?`Last event ${D(U[0].lastActivityAt)}. `:"No recent events. ")+"Activity beyond those events is unknown."});const V=["waiting","failed","running","idle","stopped"].map(A=>P.find(ae=>ae.filter===A)).find(A=>A!==void 0)??null,z=V?p.filter(A=>V.filter==="stopped"?A.outcome==="interrupted":V.filter==="failed"?A.status==="failed"&&A.outcome!=="interrupted":A.endedAt===void 0&&A.status===V.filter):[],se=[...new Set(z.map(A=>A.sessionId))],ve=se.length===1?t.sessions.get(se[0]):void 0,Ae=[ve?.projectLabel,ve?.taskLabel].filter(Boolean).join(" · "),_e=V?{...V,detail:(Ae?Ae+". ":"")+V.detail}:null,Ie=[Cc("REQUESTS",n.requests,n.accounting.requests,p.length),jt("RUNS",String(n.executions.value),n.executions,{note:T>0?`${T} of them sub-agents`:void 0}),jt("SESSIONS",String(n.sessions.value),n.sessions),Cc("TOKENS",n.tokens,n.accounting.tokens,p.length,`${wi(s.cacheRead,s.total)} cache reads${h.some(A=>Object.keys(A.measures).some(ae=>ae.startsWith("tokens.")))?" · includes accumulating open runs":""}`),Cc("TOOL CALLS",n.toolCalls,n.accounting.tools,p.length,a.toolErrors>0?`${a.toolErrors} tool ${a.toolErrors===1?"error":"errors"}`:void 0),jt("TIME IN FLIGHT",fe(n.timeInFlight.value),n.timeInFlight,{note:`${h.length>0?"provisional open intervals · ":""}within period · includes waiting · parallel intervals count once`}),jt("TIME WITH PARALLEL RUNS",fe(n.parallelTime.value),n.parallelTime),jt("PEAK CONCURRENCY",n.peakConcurrency.value>0?`${n.peakConcurrency.value} · ${D(n.peakConcurrencyAt.value)}`:"0",n.peakConcurrency),jt("CONTEXT CHANGES",String(n.contextSwitches.value),n.contextSwitches,{note:`sequential only · known contexts: ${d.filter(A=>A.key.length>0).length}`}),jt("LONGEST CONTEXT SPAN",x?fe(x.end-x.start):"—",n.longestContextSpan,{note:x?`${Ne(x.context)} · ${D(x.start)}–${D(x.end)}`:void 0}),oA(n.waitingOnYou,i,e),jt("FAILED",v>0?String(a.failed):"—",void 0,{tone:a.failed>0?"failed":void 0,note:v>0?`${v} terminal records${g?` · ${g} endings inferred`:""}${h.length?` · ${h.length} runs still open`:""}${a.interrupted?` · ${a.interrupted} stopped`:""}`:"no terminal outcomes recorded yet"})],q=c.length>0?c.reduce((A,ae)=>ae.computeMs>A.computeMs?ae:A,c[0]):void 0,qe=A=>`${String(A).padStart(2,"0")}:00`,rt=[{title:"WHERE THE TIME WENT",rows:Nc(d,Ne,!1)}];return m.length>0&&rt.push({title:"BY MACHINE",rows:Nc(m,A=>t.machines.get(A)?.name??A,!1)}),l.length>0&&rt.push({title:"BY MODEL",rows:Nc(l,A=>A===Zf?"model not observed":A,!0)}),{activity:{summary:`${w(p.length,"run")} recorded in ${w(B.size,"session")}.`,leadSessionId:C[0]?.timeMs>0?C[0].sessionId:null,focus:_e,outcomes:E(p),states:$(p),timing:`Recorded run intervals cover ${fe(n.timeInFlight.value)}. `+(n.parallelTime.value>0?`For ${fe(n.parallelTime.value)}, two or more runs overlapped.`:"No overlapping run intervals were recorded."),timingSummary:`${fe(n.timeInFlight.value)} in recorded runs · waiting included · overlaps counted once${h.length?" · open runs estimated":""}`,timingNote:"Waiting is included; overlapping intervals count once. "+(h.length?"Open intervals are provisional: silence can shorten the estimate and later events can revise it. ":"")+"This measures recorded intervals, not CPU time or your time at work.",checks:P,sessions:C},observation:"Only events 057 could read are included. Gaps may mean missing data; they do not establish inactivity.",overview:`${p.length} runs observed · ${a.completed} completed · ${a.failed} failed · ${a.interrupted} stopped · ${h.length} still open${g?` · ${g} endings inferred`:""}`,errorOutcomes:I.length?`${I.length} runs reported tool errors: ${N.filter(([A])=>A>0).map(([A,ae])=>`${A} ${ae}`).join(", ")}. Completion does not establish that every error was resolved.`:void 0,contributors:S,headline:o.headline,empty:p.length===0?"No runs observed in this window. This does not establish that no work happened.":void 0,clauses:[...o.clauses],measures:Ie.map(A=>({...A,...iA[A.key]})),hours:c.map(A=>({hour:new Date(A.from).getHours(),from:Math.max(t.dayStart,A.from),to:Math.min(t.now,A.to),partial:A.from<t.dayStart||A.to>t.now,computeMs:A.computeMs,runs:A.runs,peak:A.peak})),busiest:q?`most time in flight ${qe(new Date(q.from).getHours())} · ${fe(q.computeMs)}`:void 0,timeline:r==="last-7d"?{title:"DAY BY DAY",legend:"Time in flight within the selected window · first and last days may be partial · brighter columns contain parallel runs",buckets:u.map(A=>({label:new Date(A.from).toLocaleDateString("en-GB",{day:"2-digit",month:"short"}).toUpperCase(),from:Math.max(t.dayStart,A.from),to:Math.min(t.now,A.to),partial:A.from<t.dayStart||A.to>t.now,computeMs:A.computeMs,fraction:A.computeMs/(A.to-A.from),runs:A.runs,peak:A.peak}))}:void 0,groups:rt,tokens:n.accounting.tokens===0?[]:sA(s),tokensNote:n.accounting.tokens===0?"Token accounting is not reported in this window.":"Input, output and cache reads form the total. Reasoning is part of output and is never added again. Cache reads count replayed context, not newly generated output.",failures:p.filter(A=>A.status==="failed").sort((A,ae)=>ae.startedAt-A.startedAt).slice(0,12).map(A=>({id:A.id,at:D(A.startedAt),label:A.label,reason:A.failure?`${A.failure.code}: ${A.failure.message}`:"failed"})),notAvailable:[{key:"COST",text:"Every source here reports tokens or CPU time; none reports money. Converting one to the other needs a price table 057 does not have, so no cost figure is shown anywhere."},{key:"TOKENS, FROM SOME SOURCES",text:"Cursor persists no usage and 0x2F records none; their runs read NOT OBSERVED rather than 0, and the token totals sum only the runs that report."},{key:"CLAUDE IN A BROWSER",text:"Claude on claude.ai — chat, Claude Design, cloud Claude Code sessions — runs on Anthropic's servers and writes nothing to this Mac. Only Claude Code sessions that run here (a terminal, an editor, the desktop app's Code tab) leave the files 057 reads; the browser is seen as a process, never as work."},{key:"MACHINE-TO-MACHINE TRANSFER",text:"Every observed source is single-host. Transfers are modelled and the field renders them, but no real adapter emits one; only the synthetic source does."},{key:"PROCESS EXITS",text:"The OS collector samples; an exit is inferred from disappearance between samples, never witnessed."},{key:"OUTCOME QUALITY",text:"The log records that a run completed, not whether the work was any good."}]}}const iA={REQUESTS:{title:"REPORTED REQUESTS",meaning:"Model requests counted by sources that report them. One run can make several requests."},RUNS:{title:"RECORDED RUNS",meaning:"Recorded attempts or turns inside AI-tool sessions. This is not a count of solved tasks."},SESSIONS:{title:"SESSIONS WITH RUNS",meaning:"Conversations or task containers with at least one run in this period."},TOKENS:{title:"REPORTED TOKENS",meaning:"Input + output + cache reads. Repeated context can dominate this total; it is not generated output alone."},"TOOL CALLS":{title:"REPORTED TOOL CALLS",meaning:"Operations such as commands or tool requests. Errors can occur in a run that later completes."},"TIME IN FLIGHT":{title:"RECORDED RUN TIME",meaning:"Time covered by at least one recorded run, including waiting. Overlapping runs count once."},"TIME WITH PARALLEL RUNS":{title:"TIME WITH OVERLAPPING RUNS",meaning:"Time covered by two or more recorded run intervals. This does not measure CPU load."},"PEAK CONCURRENCY":{title:"MOST RUNS AT ONCE",meaning:"Largest number of overlapping run intervals, followed by the local time it was first reached."},"CONTEXT CHANGES":{title:"WORKING FOLDER CHANGES",meaning:"Sequential changes between observed working folders. Parallel folders have no definite order."},"LONGEST CONTEXT SPAN":{title:"LONGEST WORKING FOLDER SPAN",meaning:"Recorded run continuity in one folder, joining gaps up to 15 minutes. This does not measure human focus."},"WAITING ON YOU":{title:"WAITING FOR YOUR RESPONSE",meaning:"Recorded requests for your input or approval. Summed across runs; simultaneous waits add together."},FAILED:{title:"RUNS ENDED WITH FAILURE",meaning:"Runs with a recorded failure outcome. Later retries and the quality of the task result are separate."}};function ep(t,e=!1){const{period:r,asOf:n,project:o,today:s,comparison:i}=t,a=u=>new Date(u).toISOString(),c=["057 · ACTIVITY SUMMARY",`Period: ${r.label}`,`From (inclusive, UTC): ${a(r.from)}`,`To (exclusive, UTC): ${a(r.to)}`,`Snapshot (UTC): ${a(n)}`,`Working context: ${o?e?o.privateLabel:o.label:"ALL WORKING CONTEXTS"}`];o&&!e&&c.push(`Working context: ${o.detail}`),e&&c.push("Privacy Mode: identifying labels and free-text details omitted."),c.push("","OBSERVATION",s.empty??"Records are present. Historical observation continuity is unknown; absence of records does not establish inactivity.","","MEASURES");for(const u of s.measures)c.push(`${u.key}: ${u.value}${u.inferred?" [inferred]":""}`),u.note&&(!e||u.key!=="LONGEST CONTEXT SPAN")&&c.push(` ${u.note}`),u.assumption&&c.push(` Basis: ${u.assumption}`);if(c.push("","TIME DEFINITIONS","Time in flight is the union of run intervals within this window. Parallel intervals count once.","Group run time adds run intervals within the window. Parallel intervals add together.","LOG run intervals are clipped to this window and exclude trailing idle silence; parallel runs add together.","Tokens and tool counts include only accounting events in the selected half-open window. Open runs are accumulating.","The inspector separates these period contributions from the full retained run record as of the window end.","Completion records an outcome, not the quality of the work."),!e){c.push("","READING THE PERIOD",s.headline,...s.clauses);for(const u of s.groups){c.push("",u.title);for(const d of u.rows)c.push(`${d.label}: ${d.detail}${d.failed?` · ${d.failed} failed`:""}${d.median?` · ${d.median.text}`:""}`,...d.median?[` ${d.median.title}`]:[])}if(s.failures.length){c.push("","FAILURE RECORDS");for(const u of s.failures)c.push(`${u.at} · ${u.label}: ${u.reason}`)}}c.push("","TOKEN COMPOSITION",s.tokensNote);for(const u of s.tokens)c.push(`${u.key}: ${u.value} · ${u.percentLabel}${u.subset?" (subset of output)":""}`);if(i){c.push("","PERIOD COMPARISON",t.comparisonLabel?`B: ${t.comparisonLabel}. Exact bounds and qualifications follow.`:"B immediately precedes A and has the same duration.",i.verdict??"");for(const u of i.periods??[])c.push(`${u.k}: ${u.w} · ${u.s}`);for(const u of i.evidence){const d=u.comparison;d&&c.push(`${u.k}: A ${d.a} [${d.aEvidence}] · B ${d.b} [${d.bEvidence}] · ${d.eligibility}`,...d.reasons.map(l=>` ${l}`))}for(const u of i.reasons)c.push(`${u.k}: ${u.v}`)}c.push("","SOURCE LIMITS");for(const u of s.notAvailable)c.push(`${u.key}: ${u.text}`);return c.join(`
8
+ `)[0].trim().slice(0,200)||"Gemini reported an error"}const T0=t=>`gemini:${t}`,er=t=>typeof t=="number"&&Number.isFinite(t)?t:0,ii=t=>typeof t=="string"&&t?t:void 0,Ln=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function $0(t,e){const r=t.split(`
9
+ `).filter(a=>a.trim());if(r.length===0)throw new Mi("session file is empty",e);let n=null;const s=[],o=new Map,i=a=>{const c=a;!c||typeof c!="object"||typeof c.id!="string"||(o.has(c.id)||s.push(c.id),o.set(c.id,c))};for(const a of r){let c;try{c=JSON.parse(a)}catch{continue}if(!c||typeof c!="object")continue;const u=c;if(!n&&typeof u.sessionId=="string"){n=u;continue}const l=u.$set;if(l){const d=l.messages;if(Array.isArray(d))for(const m of d)i(m);continue}typeof u.id=="string"&&i(u)}if(!n||!n.sessionId)throw new Mi("session file has no header with a sessionId",e);return{header:n,messages:s.map(a=>o.get(a))}}const Sy=t=>Array.isArray(t.content)&&t.content.some(e=>!!e&&typeof e=="object"&&"functionResponse"in e);function B0(t){if(t.type!=="user"||Sy(t))return!1;const e=Array.isArray(t.content)?t.content.map(n=>n?.text).filter(n=>typeof n=="string"):[];if(e.length===0)return!1;const r=e[0];return!r.startsWith("<session_context>")&&!r.startsWith("[System:")}function _0(t){const e=er(t.input),r=er(t.cached);return{[z.tokensInput]:Math.max(0,e-r),[z.tokensOutput]:er(t.output)+er(t.thoughts),[z.tokensCacheRead]:r,[z.tokensReasoning]:er(t.thoughts),[z.steps]:1}}function M0(t,e){const{header:r,messages:n}=t,s=r.sessionId,o=Ln(r.startTime);if(o===void 0)throw new Mi("session header has no parseable startTime",e.path);const i=n.filter(v=>Ln(v.timestamp)!==void 0),a=i.length?Math.max(...i.map(v=>Ln(v.timestamp))):o,c=e.workspacePath??"",u=c?Be(c).toUpperCase():"GEMINI",l=T0(s),m={source:{id:ao,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},p=v=>({path:e.path,...v?{recordId:v}:{}}),h=[{...m,occurredAt:o,kind:"began",subject:{type:"session",id:l},claims:[{ns:"agent.session",parts:[C0,s],validFrom:o,validTo:a}],core:{machineId:e.machine.id,label:u,projectLabel:c?Be(c):void 0,executor:ao},attrs:{context:c,"gemini.sessionId":s,"gemini.projectHash":r.projectHash,...ii(r.kind)?{"gemini.kind":r.kind}:{}},provenance:p(s),seq:"session"}],g=[];for(let v=0;v<n.length;v++)B0(n[v])&&Ln(n[v].timestamp)!==void 0&&g.push(v);if(g.length===0){if(n.some(v=>v.type==="gemini"))throw new Mi(`session has ${n.length} messages including model output but no recognisable user prompt`,e.path);return h}for(let v=0;v<g.length;v++){const b=g[v],_=v+1<g.length?g[v+1]:n.length,E=v+1,I=`${l}:turn:${E}`,k=Ln(n[b].timestamp);let w=k,N,$;const P=[];for(let U=b;U<_;U++){const L=n[U],G=Ln(L.timestamp);if(G===void 0||L.type!=="gemini"&&L.type!=="error"&&!(L.type==="user"&&Sy(L))||(G>w&&(w=G),$=L,L.type!=="gemini"))continue;N??=ii(L.model);const te=Array.isArray(L.toolCalls)?L.toolCalls:[],ne=L.tokens?_0(L.tokens):{};te.length&&(ne[z.interactions]=te.length),Object.keys(ne).length!==0&&P.push({...m,occurredAt:G,kind:"progressed",subject:{type:"execution",id:I},core:{measures:ne},attrs:{...te.length?{"gemini.tools":te.map(ge=>ii(ge.name)??"unknown")}:{},...ii(L.model)?{"gemini.model":L.model}:{},...L.tokens?{"gemini.usage.input":er(L.tokens.input),"gemini.usage.output":er(L.tokens.output),"gemini.usage.cached":er(L.tokens.cached),"gemini.usage.thoughts":er(L.tokens.thoughts),"gemini.usage.tool":er(L.tokens.tool)}:{}},provenance:p(L.id),seq:L.id})}h.push({...m,occurredAt:k,kind:"began",subject:{type:"execution",id:I},core:{machineId:e.machine.id,sessionId:l,label:`${u} · TURN ${E}`,executor:ao,model:N,depth:0},attrs:{"gemini.turn":E},provenance:p(n[b].id),seq:`turn:${E}`}),h.push(...P);const C=$?.type==="error",T=$?.type==="gemini"&&!(Array.isArray($.toolCalls)&&$.toolCalls.length),R=v+1<g.length,H=(U,L)=>({...m,occurredAt:w,kind:"ended",subject:{type:"execution",id:I},core:U,...L?{basis:"inferred",assumption:O0}:{},provenance:p(n[b].id),seq:`turn:${E}:end`});C?h.push(H({outcome:"error",failureMessage:N0($)},!1)):R||T&&e.settled?h.push(H({outcome:"completed"},!1)):e.closeOpenTurns&&h.push(H({outcome:T?"completed":"interrupted"},!0))}return h}const R0=3e3;function pd(){return process.env.GEMINI_HOME||ue(Bn(),".gemini")}const Ay=()=>ue(pd(),"tmp"),Xf=new Map;async function j0(){const t=new Map;try{const e=JSON.parse(await Ur(ue(pd(),"projects.json"),"utf8"));for(const[r,n]of Object.entries(e.projects??{}))typeof n=="string"&&t.set(n,r)}catch{}return t}async function ky(){const t=Ay();if(!ve(t))return[];const e=[];let r;try{r=await Qe(t)}catch{return e}for(const n of r){let s;try{s=await Qe(ue(t,n,"chats"))}catch{continue}for(const o of s)o.startsWith("session-")&&o.endsWith(".jsonl")&&e.push({path:ue(t,n,"chats",o),slug:n})}return e}async function Ey(t,e){const r=Gr(),n=Date.now(),s={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},o=await ky();if(o.length===0)return s.storedAvailable=ve(Ay()),s;s.storedAvailable=!0;const i=await j0();for(const a of o){let c;try{c=await fn(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=Date.now()-c.mtimeMs,l=u>R0,d=u>ld,m=`${c.mtimeMs}:${c.size}:${l}:${d}`,p=Xf.get(a.path);let h;if(p&&p.stamp===m)h=p.envelopes;else try{const g=$0(await Ur(a.path,"utf8"),a.path);h=M0(g,{machine:r,host:Kr(),observedAt:n,path:a.path,workspacePath:i.get(a.slug),settled:l,closeOpenTurns:d}).map(Wt),Xf.set(a.path,{stamp:m,envelopes:h})}catch(g){s.sessionsFailed++,s.problems.push({path:a.path,message:g instanceof Error?g.message:String(g)});continue}s.sessionsRead++;for(const g of h)g.occurredAt>=t&&g.occurredAt<=e&&s.envelopes.push(g)}return s}async function D0(t,e){return(await Ey(t,e)).envelopes}async function Jf(){const t=pd(),e=(await ky()).length;return{available:e>0,present:ve(t),home:t,sessions:e}}const P0=new Set(["running","waiting"]);function xy(t){return P0.has(t)}function xa(t,e){return{now:t,dayStart:t,dayEnd:e,machines:new Map,sources:new Map,sessions:new Map,executions:new Map,processes:new Map,artifacts:new Map,transfers:new Map,relationships:[],active:new Set,seen:new Set}}const L0=5*6e4;function U0(t){const e=[];for(const r of t)r.parentId&&e.push({from:{type:"session",id:r.parentId},to:{type:"session",id:r.id},kind:"spawned",basis:"measured",via:"recorded by the child session's own runtime"});return e}function H0(t,e){const r=t.now-L0,n=new Set;for(const a of e)a.from.type==="process"&&n.add(a.from.id),a.to.type==="process"&&n.add(a.to.id);const s=[];let o=0,i=0;for(const a of t.processes.values())a.lastSeenAt>=r&&o++,a.endInferred&&i++,n.has(a.id)&&s.push(a);return{now:t.now,dayStart:t.dayStart,dayEnd:t.dayEnd,machines:[...t.machines.values()],sources:[...t.sources.values()],sessions:[...t.sessions.values()],executions:[...t.executions.values()],processes:s,processTotals:{observed:t.processes.size,recentlySeen:o,exitsInferred:i},relationships:[...e,...U0(t.sessions.values())]}}function Dc(t){const e=xa(t.dayStart,t.dayEnd);e.now=t.now;for(const r of t.machines)e.machines.set(r.id,r);for(const r of t.sources)e.sources.set(`${r.id}:${r.instance}`,r);for(const r of t.sessions)e.sessions.set(r.id,r);for(const r of t.executions)e.executions.set(r.id,r),xy(r.status)&&e.active.add(r.id);for(const r of t.processes)e.processes.set(r.id,r);return e.processTotals=t.processTotals,e.relationships=t.relationships,e}function et(t,e){const r=t[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function yo(t,e){for(const[r,n]of Object.entries(e)){if(typeof n!="number"||!Number.isFinite(n))continue;const s=r;t[s]=(t[s]??0)+n}}const V0=[z.tokensInput,z.tokensOutput,z.tokensCacheRead];function Hr(t){let e=0,r=!1;for(const n of V0){const s=et(t,n);s!==void 0&&(r=!0,e+=s)}return r?e:void 0}function Iy(t){return{input:et(t,z.tokensInput)??0,output:et(t,z.tokensOutput)??0,cacheRead:et(t,z.tokensCacheRead)??0,reasoning:et(t,z.tokensReasoning)??0}}function Cy(t){const e=Hr(t.measures);if(e!==void 0)return Zf(e/1e3,200);const r=et(t.measures,z.cpuMs);if(r!==void 0)return Zf(r/1e3,200)}function bs(t){return et(t.measures,z.interactions)}function Oy(t){return et(t.measures,z.steps)??0}function Ri(t){return et(t.measures,z.errors)??0}function bu(t){return et(t.measures,z.retries)??0}function Zf(t,e){return Math.min(1,Math.log1p(Math.max(0,t))/Math.log1p(e))}const Qf=30,Ny=74;function F0(t){return Qf+t*(Ny-Qf)}function W0(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function ji(t,e=0){return W0(t+"#"+e)%1e5/1e5}const Pc=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function K0(t){if(t<Pc.length)return Pc[t];const r=-.9+(t-Pc.length)*1.15;return{x:620+Math.cos(r)*520,y:300+Math.sin(r)*250,extentX:150,extentY:94}}function G0(t){const e=r=>r==="laptop"?0:r==="desktop"?1:2;return[...t].sort((r,n)=>e(r.kind)-e(n.kind)||r.firstSeenAt-n.firstSeenAt||(r.id<n.id?-1:r.id>n.id?1:0))}function wu(t,e){const r=ji(e,1),n=ji(e,2),s=r*Math.PI*2+n*2.399963,o=.34+.46*Math.sqrt(n);return{x:t.x+Math.cos(s)*t.extentX*o,y:t.y+Math.sin(s)*t.extentY*o}}function q0(t,e,r=new Map){const n=new Map,s=new Map,o=new Map,i=(c,u)=>Math.hypot(c.x-u.x,(c.y-u.y)*1.5),a=(c,u)=>{const l=new Set;for(let d=c;d&&!l.has(d);d=r.get(d)?.parentId){if(d===u)return!0;l.add(d)}return!1};for(const c of[...e].sort((u,l)=>u.startedAt-l.startedAt||(u.id<l.id?-1:u.id>l.id?1:0))){const u=t.get(c.machineId);if(!u)continue;const l=(s.get(c.machineId)??[]).filter(h=>h.until>=c.startedAt),d=l.filter(h=>!a(h.session,c.sessionId)&&!a(c.sessionId,h.session));let m=wu(u,c.id);const p=h=>Math.min(...d.map(g=>i(h,g)));if(p(m)<Ny*2.05){let h=o.get(c.machineId);if(!h){h=[];for(let v=-7;v<=7;v++)for(let b=-9;b<=9;b++)v*v+b*b>81||h.push({x:u.x+v*u.extentX/10,y:u.y+b*u.extentY/10});o.set(c.machineId,h)}let g=p(m);for(const v of h){const b=p(v);b>g&&(m=v,g=b)}}n.set(c.id,m),l.push({...m,until:c.endedAt===void 0?1/0:c.endedAt+45e3,session:c.sessionId}),s.set(c.machineId,l)}return n}const ep=64,z0=8,Y0=8,tp=16,rp=.45;function X0(t,e){switch(t.status){case"running":{const r=e-t.lastActivityAt;return .55+.45*Math.exp(-r/45e3)}case"waiting":return .08;case"failed":return .9;case"completed":return 0;case"idle":return .03}}const np=.32;function J0(t){const e=Cy(t),r=t.depth>0?.62:1;return e===void 0?np*r:Math.min(1,(np+.68*e)*r)}function Z0(t,e){const r=Math.max(1,(t.endedAt??e)-t.startedAt),n=(bs(t)??0)/(r/6e4);return Math.min(1,.25+n/24)}function sp(t){return(t.status==="failed"?3:t.status==="waiting"?2:t.status==="running"?1:0)*1e15+t.lastActivityAt}function Q0(t){const e=new Set,r=new Set,n=new Map,s=new Map,o=(i,a,c)=>{const u=i.get(a);u?u.push(c):i.set(a,[c])};for(const i of t.relationships){const{from:a,to:c,kind:u}=i;u==="ran-as"?(a.type==="execution"&&e.add(a.id),c.type==="execution"&&e.add(c.id),a.type==="session"&&c.type==="process"&&r.add(a.id),c.type==="session"&&a.type==="process"&&r.add(c.id),a.type==="execution"&&c.type==="session"?n.set(a.id,c.id):a.type==="session"&&c.type==="execution"&&n.set(c.id,a.id)):u==="same-as"&&a.type==="execution"&&c.type==="execution"&&(e.add(a.id),e.add(c.id),o(s,a.id,c.id),o(s,c.id,a.id))}return{resolvedExecutions:e,sessionsWithProcess:r,runObservesSession:n,sameExecution:s}}function eS(t,e){const n=t.startBasis===void 0?.5:t.startBasis==="measured"?1:0,s=t.endBasis===void 0?.5:t.endBasis==="measured"?1:0,o=t.endedAt===void 0?n:(n+s)/2,i=Cy(t)===void 0?0:1,a=e.resolvedExecutions.has(t.id)||e.sessionsWithProcess.has(t.sessionId)?1:0;return(1+o+i+a)/4}function op(t){let e=1;for(const r of t)e*=1-Math.min(1,Math.max(0,r));return 1-e}function ip(t,e,r,n){const s=Math.max(t,r),o=Math.min(e,n);if(o<s)return 0;const i=Math.max(e,n)-Math.min(t,r);return i<=0?1:(o-s)/i}function Lc(t){const e=t.now,r=G0(t.machines.values()).slice(0,z0),n=new Map,s=[];r.forEach((w,N)=>{const $=K0(N);n.set(w.id,$),s.push({id:w.id,name:w.name,kind:w.kind,x:$.x,y:$.y,extentX:$.extentX,extentY:$.extentY,prominence:tS(w,e),...w.activity?.validForMs===void 0?{}:{activityValidUntil:w.activity.observedAt+w.activity.validForMs},seed:ji(w.id,7)})});const o=45e3,i=[];for(const w of t.executions.values())(w.status==="completed"||w.status==="failed")&&e-(w.endedAt??e)>o||w.status==="idle"&&e-w.lastActivityAt>o*4||n.has(w.machineId)&&i.push(w);i.length>ep&&(i.sort((w,N)=>sp(N)-sp(w)),i.length=ep);const a=Q0(t),c=q0(n,t.executions.values(),t.sessions),u=w=>{const N=n.get(w.machineId),{x:$,y:P}=c.get(w.id)??wu(N,w.id),C=t.sessions.get(w.sessionId);return{id:w.id,massId:w.machineId,sessionId:w.sessionId,x:$,y:P,extent:J0(w),energy:X0(w,e),rate:Z0(w,e),phase:ji(w.id,3)*Math.PI*2,status:w.status,label:w.label,projectLabel:C?.projectLabel,taskLabel:C?.taskLabel,statusSince:w.waitingSince??w.endedAt??w.startedAt,articulation:eS(w,a),shoulder:0,observers:1}},l=new Set(i.map(w=>w.id)),d=new Set,m=[],p=w=>[w.startedAt,w.endedAt??e];for(const w of[...i].sort((N,$)=>N.id<$.id?-1:1)){if(d.has(w.id))continue;const N=[w];d.add(w.id);for(let H=0;H<N.length;H++)for(const U of a.sameExecution.get(N[H].id)??[])!l.has(U)||d.has(U)||(d.add(U),N.push(t.executions.get(U)));if(N.length===1){m.push(u(w));continue}const $=N.map(u),P=$.reduce((H,U)=>U.articulation>H.articulation||U.articulation===H.articulation&&U.id<H.id?U:H);let C=1;const[T,R]=p(t.executions.get(P.id));for(const H of N){const[U,L]=p(H);C=Math.min(C,ip(T,R,U,L))}m.push({...P,extent:Math.max(...$.map(H=>H.extent)),energy:Math.max(...$.map(H=>H.energy)),articulation:op($.map(H=>H.articulation)),shoulder:Math.min(rp,1-C),observers:N.length})}const h=new Map;for(const w of m){if(a.runObservesSession.has(w.id))continue;const N=h.get(w.sessionId);N?N.push(w):h.set(w.sessionId,[w])}const g=new Map,v=[];for(const w of m){const N=a.runObservesSession.get(w.id),$=N?h.get(N):void 0;if(!N||!$||$.length===0){if(v.push(w),N){const L=h.get(w.sessionId);L?L.push(w):h.set(w.sessionId,[w])}continue}const P=t.executions.get(w.id);let C=1/0,T=-1/0;for(const L of $){const[G,te]=p(t.executions.get(L.id));C=Math.min(C,G),T=Math.max(T,te)}const[R,H]=p(P),U=g.get(N)??{articulations:[],coincidence:1};U.articulations.push(w.articulation),U.coincidence=Math.min(U.coincidence,ip(R,H,C,T)),g.set(N,U)}const b=[];for(const w of[...h.keys()].sort()){const N=h.get(w),$=t.sessions.get(w);if(!$||N.length===0)continue;let P=0,C=0;for(const L of N)P+=L.x,C+=L.y;P/=N.length,C/=N.length;let T=0,R=0;for(const L of N){const G=F0(L.extent);T=Math.max(T,Math.abs(L.x-P)+G*1.5),R=Math.max(R,Math.abs(L.y-C)+G)}const H=g.get(w),U=Math.max(...N.map(L=>L.articulation));b.push({id:w,massId:N[0].massId,x:P,y:C,extentX:Math.max(T,52),extentY:Math.max(R,36),presence:1,articulation:H?op([U,...H.articulations]):U,parentId:$.parentId,empty:!1,shoulder:H?Math.min(rp,1-H.coincidence):0,observers:1+(H?.articulations.length??0),label:$.label??$.executor??w,projectLabel:$.projectLabel,taskLabel:$.taskLabel})}for(const w of[...t.sessions.values()].sort((N,$)=>N.id<$.id?-1:1)){if(w.executionIds.length>0||w.endedAt!==void 0&&e-w.endedAt>o)continue;const N=n.get(w.machineId);if(!N)continue;const{x:$,y:P}=wu(N,`session-presence:${w.id}`);b.push({id:w.id,massId:w.machineId,x:$,y:P,extentX:64,extentY:42,presence:1,articulation:a.sessionsWithProcess.has(w.id)?.5:.25,parentId:w.parentId,empty:!0,shoulder:0,observers:1,label:w.label??w.executor??w.id,projectLabel:w.projectLabel,taskLabel:w.taskLabel})}if(b.length>tp){const w=N=>N.empty?0:h.get(N.id)?.length??0;b.sort((N,$)=>w($)-w(N)||(N.id<$.id?-1:1)),b.length=tp}const _=[];for(const w of t.transfers.values())if(w.endedAt===void 0&&!(!n.has(w.fromMachineId)||!n.has(w.toMachineId))){if(_.length>=Y0)break;_.push({id:w.id,fromMassId:w.fromMachineId,toMassId:w.toMachineId,energy:1,label:w.label})}const E=new Map;r.forEach((w,N)=>E.set(w.id,N));const I=Math.max(1,t.dayEnd-t.dayStart),k=[];for(const w of t.executions.values()){const N=E.get(w.machineId);if(N===void 0)continue;const $=(w.startedAt-t.dayStart)/I,P=((w.endedAt??e)-t.dayStart)/I;k.push({id:w.id,massId:w.machineId,lane:N,startFraction:Math.max(0,Math.min(1,$)),endFraction:Math.max(0,Math.min(1,P)),status:w.status,label:w.label})}return{time:e,masses:s,disturbances:v,plinths:b,couplings:_,strata:k}}function tS(t,e){const r=t.activity;if(!r||r.validForMs===void 0||e<r.observedAt||e-r.observedAt>=r.validForMs)return 0;const n=et(r.measures,z.cpuUtilization);return n===void 0||!Number.isFinite(n)?0:Math.min(1,Math.max(0,n))}const Di="057.landscape",go=1;function rS(t){return{contract:Di,version:go,landscape:t}}const Ty=9e4;function ap(t,e){if(t.waitingSince===void 0)return;const r=t.waitingSince,n=Math.max(r,e);t.waitingMs+=n-r,t.waits.push({start:r,end:n})}function nS(t,e){const r=`${e.source.id}:${e.source.instance}`;let n=t.sources.get(r);n||(n={id:e.source.id,instance:e.source.instance,origin:e.source.instance,firstSeenAt:e.occurredAt,lastSeenAt:e.occurredAt,events:0,strata:{}},t.sources.set(r,n)),n.events++,e.occurredAt<n.firstSeenAt&&(n.firstSeenAt=e.occurredAt),e.occurredAt>n.lastSeenAt&&(n.lastSeenAt=e.occurredAt),e.stratum&&(n.strata[e.stratum]=(n.strata[e.stratum]??0)+1);const s=e.provenance?.sourceVersion;s&&(n.sourceVersions?n.sourceVersions.includes(s)||n.sourceVersions.push(s):n.sourceVersions=[s])}function sS(t,e){if(t.seen.has(e.id))return;t.seen.add(e.id),e.occurredAt>t.now&&(t.now=e.occurredAt),nS(t,e);const r=e.core??{},n=e.occurredAt;switch(e.subject.type){case"machine":{const s=t.machines.get(e.subject.id);if(s)r.measures&&(s.activity={observedAt:n,measures:{...r.measures},validForMs:r.measureValidityMs,basis:e.basis,assumption:e.assumption});else{const o={id:e.subject.id,name:r.machineName??e.subject.id,kind:r.machineKind??"laptop",parentId:r.parentId,firstSeenAt:n};r.measures&&(o.activity={observedAt:n,measures:{...r.measures},validForMs:r.measureValidityMs,basis:e.basis,assumption:e.assumption}),t.machines.set(o.id,o)}break}case"session":{if(e.kind==="began"){const s=t.sessions.get(e.subject.id);if(s){s.parentId===void 0&&r.parentId&&(s.parentId=r.parentId),s.projectLabel===void 0&&r.projectLabel&&(s.projectLabel=r.projectLabel),s.taskLabel===void 0&&r.taskLabel&&(s.taskLabel=r.taskLabel);break}const o={id:e.subject.id,machineId:r.machineId??"",label:r.label,projectLabel:r.projectLabel,taskLabel:r.taskLabel,context:e.attrs?.context??r.label??"",executor:r.executor,model:r.model,startedAt:n,executionIds:[],parentId:r.parentId};t.sessions.set(o.id,o)}else if(e.kind==="ended"){const s=t.sessions.get(e.subject.id);s&&(s.endedAt=n)}break}case"execution":oS(t,e,n);break;case"process":iS(t,e,n);break;case"artifact":{if(t.artifacts.has(e.subject.id))break;t.artifacts.set(e.subject.id,{id:e.subject.id,kind:"file",path:r.label??e.subject.id,firstSeenAt:n});break}}}function oS(t,e,r){const n=e.core??{},s=e.subject.id;if(e.kind==="began"){if(t.executions.has(s))return;const i={id:s,sessionId:n.sessionId??n.parentId??"",machineId:n.machineId??"",label:n.label??s,executor:n.executor??"unknown",model:n.model,status:"running",startedAt:r,lastActivityAt:r,measures:{},waitingMs:0,waits:[],parentId:n.parentId,depth:n.depth??0,startBasis:e.basis,boundsAssumption:e.assumption};n.measures&&yo(i.measures,n.measures),t.executions.set(s,i),t.active.add(s),t.sessions.get(i.sessionId)?.executionIds.push(s);return}const o=t.executions.get(s);if(o)switch(o.endBasis==="inferred"&&o.endedAt!==void 0&&r>o.endedAt&&(e.kind==="progressed"||e.kind==="blocked"||e.kind==="resumed")&&(delete o.endedAt,delete o.endBasis,delete o.outcome,delete o.failure,o.startBasis!=="inferred"&&delete o.boundsAssumption,o.status="running",t.active.add(s)),e.kind){case"progressed":{n.measures&&yo(o.measures,n.measures),o.lastActivityAt=r,o.status==="idle"&&(o.status="running",t.active.add(s));break}case"blocked":{if(!xy(o.status))break;o.status="waiting",o.waitingSince=r,o.waitReason=n.blockedOn??"input",o.lastActivityAt=r;break}case"resumed":{ap(o,r),o.status="running",o.waitingSince=void 0,o.waitReason=void 0,o.lastActivityAt=r,t.active.add(s);break}case"ended":{const i=n.outcome==="error";o.status=i?"failed":"completed",o.endedAt=r,o.endBasis=e.basis,e.assumption&&!o.boundsAssumption&&(o.boundsAssumption=e.assumption),o.lastActivityAt=r,o.outcome=n.outcome??"completed",i&&(o.failure={code:n.failureCode??"ERROR",message:n.failureMessage??"Execution failed"}),ap(o,r),o.waitingSince=void 0,o.waitReason=void 0,t.active.delete(s);break}case"observed":o.lastActivityAt=Math.max(o.lastActivityAt,r);break}}function iS(t,e,r){const n=e.core??{},s=e.subject.id,o=n.pid??Number(e.attrs?.["os.pid"]??0);if(e.kind==="began"){if(t.processes.has(s))return;const a={id:s,machineId:n.machineId??"",pid:o,ppid:n.ppid??(typeof e.attrs?.["os.ppid"]=="number"?e.attrs["os.ppid"]:void 0),command:n.label??n.executor??String(o),startedAt:r,lastSeenAt:r,status:"running",measures:{}};n.measures&&yo(a.measures,n.measures),t.processes.set(s,a);return}const i=t.processes.get(s);if(i)if(e.kind==="observed"||e.kind==="progressed"){if(i.lastSeenAt=Math.max(i.lastSeenAt,r),n.measures){const a=n.measures[z.cpuMs];typeof a=="number"&&(i.measures[z.cpuMs]=a);const{[z.cpuMs]:c,...u}=n.measures;yo(i.measures,u)}}else e.kind==="ended"&&(i.endedAt=r,i.lastSeenAt=Math.max(i.lastSeenAt,r),i.status="exited",i.endInferred=e.basis==="inferred")}function hd(t,e){for(let r=0;r<e.length;r++)sS(t,e[r])}function $y(t,e){e>t.now&&(t.now=e),e=t.now;for(const r of t.active){const n=t.executions.get(r);if(!n){t.active.delete(r);continue}n.status==="running"&&e-n.lastActivityAt>Ty&&(n.status="idle")}}const By=`Wall-clock time covered by recorded run intervals, with parallel intervals counted once and waiting included. An open running record becomes idle after ${Ty/1e3} seconds without an event; its interval then stops at its last event instead of the period end. Explicit waits still count to the period end. A later event or ending includes the intervening silence again. The estimate can decrease or be revised. In flight is not computing time or human attention.`,pt=t=>({value:t,basis:"measured"}),_s=(t,e)=>({value:t,basis:"inferred",assumption:e});function md(t){if(t.length===0)return[];t.sort((r,n)=>r.start-n.start);const e=[{start:t[0].start,end:t[0].end}];for(let r=1;r<t.length;r++){const n=t[r],s=e[e.length-1];n.start<=s.end?n.end>s.end&&(s.end=n.end):e.push({start:n.start,end:n.end})}return e}function _y(t){let e=0;for(const r of t)e+=r.end-r.start;return e}function aS(t){const e=t.filter(o=>o.end>o.start).flatMap(o=>[{at:o.start,delta:1},{at:o.end,delta:-1}]).sort((o,i)=>o.at-i.at||o.delta-i.delta);let r=0,n=e[0]?.at??0,s=0;for(const o of e)r>=2&&(s+=o.at-n),r+=o.delta,n=o.at;return s}function My(t){if(t.length===0)return{peak:0,at:0};const e=[];for(const o of t)e.push({t:o.start,d:1}),e.push({t:o.end,d:-1});e.sort((o,i)=>o.t-i.t||o.d-i.d);let r=0,n=0,s=e[0].t;for(const o of e)r+=o.d,r>n&&(n=r,s=o.t);return{peak:n,at:s}}function cS(t){if(t.length===0)return;const e=[...t].sort((n,s)=>n-s),r=e.length>>1;return e.length%2?e[r]:(e[r-1]+e[r])/2}function ws(t,e,r=t.startedAt){const n=Math.max(r,t.startedAt),s=Math.min(e,t.endedAt??(t.status==="idle"?t.lastActivityAt:e));return{start:n,end:Math.max(n,s)}}function yd(t,e){return t.waitingMs+(t.waitingSince===void 0?0:Math.max(0,e-t.waitingSince))}function gd(t){const e=t.now,r=[...t.executions.values()];let n=0,s=0,o=0;const i={tokens:0,tools:0,requests:0};let a=0,c=0,u=0,l=0,d=0;const m=[],p=new Map;for(const k of r){n+=Oy(k),et(k.measures,z.steps)!==void 0&&i.requests++;const w=Hr(k.measures),N=bs(k);w!==void 0&&(s+=w,i.tokens++),N!==void 0&&(o+=N,i.tools++),k.status==="completed"&&k.outcome!=="interrupted"?a++:k.status==="failed"?c++:k.status==="waiting"?u++:k.status==="idle"&&l++;const $=ws(k,e,t.dayStart);m.push($),d+=k.waitingMs,k.waitingSince!==void 0&&(d+=Math.max(0,e-k.waitingSince));let P=p.get(k.machineId);P||(P={machineId:k.machineId,executions:0,tokens:0,computeTime:0},p.set(k.machineId,P)),P.executions++,P.tokens+=Hr(k.measures)??0,P.computeTime+=$.end-$.start}const h=md(m.map(k=>({...k}))),{peak:g,at:v}=My(m),b=uS(t),_=dS(b);let E=null;for(const k of b)(!E||k.end-k.start>E.end-E.start)&&(E=k);let I=0;for(const k of t.sessions.values())k.executionIds.some(w=>t.executions.has(w))&&I++;return{requests:pt(n),sessions:pt(I),executions:pt(r.length),tokens:pt(s),toolCalls:pt(o),accounting:i,timeInFlight:_s(_y(h),By),parallelTime:_s(aS(m),"Wall-clock time in this period with at least two runs in flight. Parallel intervals count once; waiting is included and trailing idle silence is excluded."),peakConcurrency:r.some(k=>k.startBasis==="inferred"||k.endBasis==="inferred"||k.status==="idle")?_s(g,"Peak overlap of the recorded run intervals in this period. Some bounds are inferred, or an idle interval ends at its last observed output."):pt(g),peakConcurrencyAt:pt(v),contextSwitches:_s(_,"Changes between successive non-overlapping groups of runs, each confined to one known working directory. Groups containing concurrent work in different directories are excluded. This does not measure human attention."),longestContextSpan:_s(E,"Longest span of consecutive runs in one working directory, including gaps of up to 15 minutes. Other contexts may run concurrently. This does not measure human focus."),waitingOnYou:pt(d),completed:pt(a),failed:pt(c),waiting:pt(u),idle:pt(l),byMachine:p,contextSpans:b,transfers:pt(t.transfers.size)}}function uS(t){const e=[];for(const n of t.executions.values()){const s=t.sessions.get(n.sessionId);if(!s?.context)continue;const o=ws(n,t.now,t.dayStart);o.end>o.start&&e.push({context:s.context,...o})}e.sort((n,s)=>n.start-s.start);const r=[];for(const n of e){const s=r[r.length-1];s&&s.context===n.context&&n.start<=s.end?n.end>s.end&&(s.end=n.end):s&&s.context===n.context?n.start-s.end<=lS?s.end=Math.max(s.end,n.end):r.push({context:n.context,start:n.start,end:n.end}):r.push({context:n.context,start:n.start,end:n.end})}return r}const lS=15*6e4;function dS(t){let e=-1/0,r=new Set,n,s=0;const o=()=>{const i=r.size===1?[...r][0]:void 0;n!==void 0&&i!==void 0&&n!==i&&s++,n=i};for(const i of t)i.end<=i.start||(i.start>=e&&(r.size>0&&o(),r=new Set),r.add(i.context),e=Math.max(e,i.end));return r.size>0&&o(),s}function fS(t){return{key:t,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function ai(t,e){const r=new Map,n=new Map;for(const s of t.executions.values()){const o=e(s,t.sessions.get(s.sessionId));if(o===void 0)continue;let i=r.get(o);i||(i=fS(o),r.set(o,i)),i.runs++;const a=Hr(s.measures);if(a!==void 0&&(i.tokens+=a,i.tokenRuns++,s.endedAt!==void 0&&s.startedAt>=t.dayStart&&s.endedAt<=t.now&&s.endedAt<t.dayEnd)){let u=n.get(o);u||(u=[],n.set(o,u)),u.push(a)}const c=ws(s,t.now,t.dayStart);i.computeMs+=c.end-c.start,i.waitingMs+=yd(s,t.now),i.toolCalls+=bs(s)??0,s.status==="failed"&&i.failed++}for(const[s,o]of n){const i=r.get(s);i&&(i.medianTokens=cS(o),i.medianRuns=o.length)}return[...r.values()].sort((s,o)=>o.computeMs-s.computeMs)}function pS(t){const e={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const r of t.executions.values()){const n=Iy(r.measures);e.input+=n.input,e.output+=n.output,e.cacheRead+=n.cacheRead,e.reasoning+=n.reasoning}return e.total=e.input+e.output+e.cacheRead,e}function hS(t){const e={count:0,totalMs:0,longestMs:0,openNow:0};for(const r of t.executions.values()){for(const n of r.waits){e.count++;const s=n.end-n.start;e.totalMs+=s,s>e.longestMs&&(e.longestMs=s)}if(r.waitingSince!==void 0){e.count++,e.openNow++;const n=t.now-r.waitingSince;e.totalMs+=n,n>e.longestMs&&(e.longestMs=n)}}return e}function Ry(t){const e={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const r of t.executions.values())e.toolCalls+=bs(r)??0,e.toolErrors+=Ri(r),e.retries+=bu(r),r.status==="failed"?e.failed++:r.outcome==="interrupted"?e.interrupted++:r.outcome==="completed"&&e.completed++;return e}function cp(t,e){const r=[...t.executions.values()].map(i=>{const a=ws(i,t.now);return{start:Math.max(t.dayStart,a.start),end:Math.min(t.now,a.end)}}).filter(i=>i.end>i.start);if(r.length===0)return[];const n=md(r.map(i=>({...i}))),s=new Date(t.dayStart);e==="day"?s.setHours(0,0,0,0):s.setMinutes(0,0,0);const o=[];for(let i=s.getTime();i<t.now;){const a=new Date(i);e==="day"?a.setDate(a.getDate()+1):a.setTime(i+36e5);const c=a.getTime(),u=n.reduce((d,m)=>d+Math.max(0,Math.min(m.end,c)-Math.max(m.start,i)),0),l=r.filter(d=>d.start<c&&d.end>i).map(d=>({start:Math.max(d.start,i),end:Math.min(d.end,c)}));o.push({from:i,to:c,computeMs:u,runs:l.length,peak:My(l).peak}),i=c}return o}const vd="SHAPES FIELD",bd="METADATA — DOES NOT SHAPE FIELD";function wd(t){const e=new Date(t),r=n=>String(n).padStart(2,"0");return`${r(e.getHours())}:${r(e.getMinutes())}:${r(e.getSeconds())}`}function up(t){const e=new Date(t),r=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())} ${wd(t).slice(0,5)}`}function mS(t){return fe(t).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function lp(t,e,r,n,s=()=>{},o){if(r==="mass")return vS(t,e,n);if(r==="coupling")return bS(t,n);const i=t.executions.get(n);if(!i)return null;const a=o?.[n],c=a?{...i,startedAt:a.at,startBasis:a.basis,boundsAssumption:a.assumption??i.boundsAssumption}:i;return yS(t,e,c,r,s("execution",n))}function yS(t,e,r,n,s){const o=t.sessions.get(r.sessionId),i=t.machines.get(r.machineId),c=e.disturbances.find(b=>b.id===r.id)?.statusSince??r.endedAt??r.startedAt,u=r.startBasis==="inferred"||r.endBasis==="inferred",l=Hr(r.measures),d=r.outcome==="interrupted",m=[{key:"MACHINE",value:(i?.name??r.machineId).toUpperCase()},{key:"STATE",value:d?"STOPPED":r.status.toUpperCase(),tone:d?void 0:r.status},{key:"SINCE",value:wd(c)},l===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:Ye(l)}];if(o){const b=o.executionIds.indexOf(r.id),_=e.plinths.some(I=>I.id===o.id),E=b>=0?`${b+1} OF ${o.executionIds.length}`:`OF ${o.executionIds.length}`;m.push({key:"SESSION",value:_?`${E} · PLINTH`:E})}const p=gS(t,r.id),h=[r.model??o?.model?{key:"MODEL",value:r.model??o?.model}:{key:"MODEL",value:"not observed",tone:"absent",note:"This source does not record the model."}];o?.projectLabel&&h.push({key:"PROJECT",value:o.projectLabel}),o?.context&&h.push({key:"FOLDER",value:Be(o.context),note:o.context}),h.push({key:"SOURCE",value:[r.executor,p===void 0?void 0:`pid ${p}`].filter(Boolean).join(" · "),note:s}),h.push({key:"REQUESTS",value:String(Oy(r))}),h.push({key:"STARTED",value:`${r.startBasis==="inferred"?"~":""}${up(r.startedAt)}`,note:r.startBasis==="inferred"?r.boundsAssumption??"The start bound was inferred by the source.":void 0}),r.endedAt!==void 0&&h.push({key:"ENDED",value:`${r.endBasis==="inferred"?"~":""}${up(r.endedAt)}`,note:r.endBasis==="inferred"?r.boundsAssumption??"The end bound was inferred by the source.":void 0});const g=bs(r);if(h.push(g===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:mw(g)}),h.push({key:"ELAPSED",value:`${fe((r.endedAt??t.now)-r.startedAt)}${u?" · inferred":""}`,note:[u?r.boundsAssumption:void 0,r.startedAt<t.dayStart?"Full elapsed interval includes time before the selected window.":void 0].filter(Boolean).join(" · ")||void 0}),l!==void 0){const b=Iy(r.measures);h.push({key:"INPUT",value:Ye(b.input)},{key:"OUTPUT",value:Ye(b.output)}),h.push({key:"CACHE READ",value:Ye(b.cacheRead)},{key:"REASONING",value:Ye(b.reasoning)})}Ri(r)>0&&h.push({key:"TOOL ERRORS",value:String(Ri(r)),tone:"failed"}),bu(r)>0&&h.push({key:"RETRIES",value:String(bu(r)),tone:"waiting",note:"Provider retries."}),(r.waits.length>0||r.waitingMs>0||r.waitingSince!==void 0)&&h.push({key:"BLOCKED",value:`${fe(yd(r,t.now))} on you · ${r.waits.length+(r.waitingSince===void 0?0:1)}×${r.waitingSince===void 0?"":" · still waiting"}`,tone:"waiting"}),r.depth>0&&h.push({key:"SUB-AGENT",value:`depth ${r.depth}`});const v=!d&&(r.status==="running"||r.status==="waiting");return{id:r.id,eyebrow:n==="stratum"||!v?"SELECTED · RUN":"SELECTED · PROCESS",title:r.label.toUpperCase(),state:{text:d?"STOPPED":v?`${r.status.toUpperCase()} · ${mS(t.now-c)}`:r.status.toUpperCase(),status:d?void 0:r.status},groups:[{title:vd,metadata:!1,rows:m},{title:bd,metadata:!0,rows:h}],failure:r.failure?`${r.failure.code}: ${r.failure.message}`:void 0,reveal:s}}function gS(t,e){for(const r of t.relationships){if(r.kind!=="ran-as")continue;const n=r.from.type==="execution"&&r.from.id===e&&r.to.type==="process"?r.to.id:r.to.type==="execution"&&r.to.id===e&&r.from.type==="process"?r.from.id:void 0;if(n)return t.processes.get(n)?.pid}}function vS(t,e,r){const n=t.machines.get(r);if(!n)return null;let s=0,o=0,i=0,a;for(const g of t.executions.values()){if(g.machineId!==n.id)continue;const v=Hr(g.measures);v!==void 0&&(a=(a??0)+v),g.status==="running"?s++:g.status==="waiting"?o++:i++}const u=[{key:"KIND",value:(e.masses.find(g=>g.id===r)?.kind??n.kind).toUpperCase()},{key:"RUNNING",value:String(s),tone:s>0?"running":void 0}],l=n.activity&&n.activity.validForMs!==void 0&&t.now-n.activity.observedAt<=n.activity.validForMs?n.activity:void 0,d=l?et(l.measures,z.cpuUtilization):void 0;d!==void 0&&l&&u.push({key:`CPU ACTIVITY · ${l.basis.toUpperCase()}`,value:`${Math.round(d*100)}%`,note:l.assumption}),o>0&&u.push({key:"WAITING",value:String(o),tone:"waiting"}),u.push({key:"RAN TODAY",value:String(i)});const m=[a===void 0?{key:"TOKENS",value:"not observed",tone:"absent",note:"No execution in this window reported token accounting."}:{key:"TOKENS",value:Ye(a)}],p=t.processTotals;if(p){const g=new Set;for(const v of t.relationships)v.kind==="ran-as"&&(v.from.type==="process"&&g.add(v.from.id),v.to.type==="process"&&g.add(v.to.id));m.push({key:"PROCESSES",value:`${p.observed} observed`}),m.push({key:"LAST 5 MIN",value:`${p.recentlySeen} seen`,note:"Processes with a liveness observation in the last five minutes. The sampler never witnesses an exit, so recency is the honest liveness signal."}),m.push({key:"ATTRIBUTED",value:`${g.size} of ${p.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const h=s+o;return{id:r,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:h>0?{text:`${h} ACTIVE`,status:s>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:vd,metadata:!1,rows:u},{title:bd,metadata:!0,rows:m}]}}function bS(t,e){const r=t.transfers.get(e);if(!r)return null;const n=t.machines.get(r.fromMachineId)?.name??r.fromMachineId,s=t.machines.get(r.toMachineId)?.name??r.toMachineId;return{id:e,eyebrow:"SELECTED · TRANSFER",title:`${n} → ${s}`.toUpperCase(),state:{text:"TRANSFERRING",status:"running"},groups:[{title:vd,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:s.toUpperCase()},{key:"SINCE",value:wd(r.startedAt)}]},{title:bd,metadata:!0,rows:[{key:"WHAT",value:r.label},{key:"SIZE",value:yw(r.bytes)}]}]}}const wS=6e4;function SS(t,e){const r=[],n=e.contextSpans,s=e.longestContextSpan.value;if(e.executions.value===0)return{headline:"NO RUN RECORDS",clauses:["No runs observed in this window. This does not establish inactivity."]};const o=e.peakConcurrency.value>1?`UP TO ${e.peakConcurrency.value} RUNS AT ONCE`:"ONE RUN AT A TIME";if(e.peakConcurrency.value>=2?(r.push(`Up to ${e.peakConcurrency.value} runs in flight at once; ${fe(e.timeInFlight.value)} of wall-clock time had a run in flight.`),r.push(`Parallel runs overlapped for ${fe(e.parallelTime.value)} within this period; each instant counts once.`)):r.push(`Runs happened one at a time, across ${fe(e.timeInFlight.value)} of wall-clock time.`),s&&r.push(`The longest context span covered ${fe(s.end-s.start)} in ${Be(s.context)}; gaps of up to 15 minutes are included.`),e.contextSwitches.value>0){const i=new Set(n.map(a=>a.context)).size;r.push(`${e.contextSwitches.value} sequential ${e.contextSwitches.value===1?"change":"changes"} between working directories, across ${i} contexts; concurrent contexts are excluded.`)}if(e.waitingOnYou.value>wS&&r.push(`${fe(e.waitingOnYou.value)} was spent with a run waiting on your answer.`),e.failed.value>0&&r.push(`${e.failed.value} of ${e.executions.value} runs ended in failure; ${e.completed.value} completed.`),e.byMachine.size>1){const i=[...e.byMachine.values()].sort((a,c)=>c.computeTime-a.computeTime).map(a=>`${t.machines.get(a.machineId)?.name??a.machineId} ${fe(a.computeTime)}`);r.push(`Summed run intervals by machine: ${i.join(", ")}.`)}return{headline:o,clauses:r}}const dp="(no model)";function AS(t){if(t.medianTokens===void 0)return t.tokenRuns>0?{text:"no complete runs in this window for a median",title:"Token accounting is present. The median requires ended runs with both bounds inside this window; open and boundary-crossing runs are excluded.",absent:!0}:{text:"no token accounting",title:"No run in this group reports token accounting, so there is no figure — not a figure of zero.",absent:!0};if(t.medianRuns===1)return{text:`single run ${Ye(t.medianTokens)}`,title:"One ended run fully inside this window reports accounting, so this is its figure, not a median. Open and boundary-crossing runs are excluded.",absent:!1};const e=t.medianRuns===t.runs?`${t.runs}`:`${t.medianRuns} of ${t.runs}`;return{text:`median ${Ye(t.medianTokens)} over ${e} runs`,title:`Median billed tokens per complete run, over the runs in this group fully inside this window that have ended and whose source reports token accounting — ${t.medianRuns} of ${t.runs} here. Runs still in flight are excluded: their totals are partial. Boundary-crossing runs are excluded. Runs whose source persists no accounting are excluded: absence is not zero. Same window as the rest of TODAY.`,absent:!1}}function kS(t,e,r){if(r&&r.reported===0)return Lt("WAITING ON YOU","—",void 0,{note:"not reported by sources in this window"});const n=e.count>0?`${e.count} ${e.count===1?"block":"blocks"} · longest ${fe(e.longestMs)}`:void 0,s=r&&r.reported<r.runs?`from the ${r.reported} of ${r.runs} runs whose sources report waits`:void 0;return Lt("WAITING ON YOU",fe(t.value),t,{tone:t.value>0?"waiting":void 0,note:[n,s].filter(Boolean).join(" · ")||void 0})}function Lt(t,e,r,n={}){const s=r?.basis==="inferred";return{key:t,value:e,inferred:s,assumption:s?r?.assumption:void 0,...n}}function Uc(t,e,r,n,s){return Lt(t,r>0?Ye(e.value):"—",e,{note:r===0?"not reported in this window":[s,r<n?`reported for ${r} of ${n} runs`:void 0].filter(Boolean).join(" · ")||void 0})}function ES(t){const e=[["CACHE READS",t.cacheRead],["INPUT",t.input],["OUTPUT",t.output]].map(([r,n])=>({key:r,value:Ye(n),fraction:n/Math.max(1,t.total),percent:Math.round(n/Math.max(1,t.total)*100),percentLabel:Ti(n,t.total)}));return t.reasoning>0&&e.push({key:"REASONING · OF OUTPUT",value:Ye(t.reasoning),subset:!0,fraction:t.reasoning/Math.max(1,t.output),percent:Math.round(t.reasoning/Math.max(1,t.output)*100),percentLabel:Ti(t.reasoning,t.output)}),e}function Hc(t,e,r){const n=t[0]?.computeMs??0;return t.map(s=>({key:s.key,label:e(s.key),detail:`${s.runs} ${s.runs===1?"run":"runs"}${s.tokenRuns>0?` · ${Ye(s.tokens)} tok${s.tokenRuns<s.runs?` (${s.tokenRuns}/${s.runs} reported)`:""}`:" · tokens not reported"} · ${fe(s.computeMs)}`,failed:s.failed,fraction:n>0?s.computeMs/n:0,median:r?AS(s):void 0}))}function fp(t,e,r="today"){const n=gd(t),s=SS(t,n),o=pS(t),i=hS(t),a=Ry(t),c=r==="today"?cp(t,"hour"):[],u=r==="last-7d"?cp(t,"day"):[],l=ai(t,(A,ae)=>ae?.context),d=ai(t,A=>A.model??dp),m=ai(t,A=>A.machineId),p=[...t.executions.values()],h=p.filter(A=>A.endedAt===void 0),g=p.length-h.length,v=p.filter(A=>A.endBasis==="inferred").length,b=p.filter(A=>(A.measures.errors??0)>0),_=[[b.filter(A=>A.outcome==="completed").length,"completed"],[b.filter(A=>A.status==="failed").length,"failed"],[b.filter(A=>A.outcome==="interrupted").length,"stopped"],[b.filter(A=>A.endedAt===void 0).length,"still open"]],E=ai(t,A=>A.sessionId).filter(A=>A.tokenRuns>0).sort((A,ae)=>ae.tokens-A.tokens).slice(0,3).map(A=>({sessionId:A.key,label:t.sessions.get(A.key)?.taskLabel??t.sessions.get(A.key)?.label??"Session",detail:`${Ye(A.tokens)} tok · ${Ti(A.tokens,n.tokens.value)} of reported volume · ${A.runs} runs${A.tokenRuns<A.runs?` · ${A.tokenRuns}/${A.runs} reported`:""}`,fraction:A.tokens/Math.max(1,n.tokens.value)})),I=p.filter(A=>A.depth>0).length,k=n.longestContextSpan.value,w=A=>r==="today"?Rf(A):`${new Date(A).toLocaleDateString("en-GB",{day:"2-digit",month:"short"})} ${Rf(A)}`,N=(A,ae)=>`${A} ${ae}${A===1?"":"s"}`,$=A=>[[A.filter(me=>me.outcome==="completed").length,"completed","completed","completed"],[A.filter(me=>me.status==="failed"&&me.outcome!=="interrupted").length,"failed","failed","failed"],[A.filter(me=>me.outcome==="interrupted").length,"stopped","stopped","stopped"],[A.filter(me=>me.endedAt===void 0&&me.status==="waiting").length,"waiting","waiting for your response","need response"],[A.filter(me=>me.endedAt===void 0&&me.status==="running").length,"running","with recent events","with recent events"],[A.filter(me=>me.endedAt===void 0&&me.status==="idle").length,"idle","without a recorded ending","no ending"]].filter(([me])=>me>0).map(([me,_t,lr,Se])=>({filter:_t,label:`${me} ${_t==="waiting"&&me===1?"needs response":Se}`,text:`${me} ${lr}`})),P=A=>$(A).map(ae=>ae.text).join(" · "),C=new Map;for(const A of p){const ae=C.get(A.sessionId)??[];ae.push(A),C.set(A.sessionId,ae)}const T=[...C].map(([A,ae])=>{const me=t.sessions.get(A),_t=ae.map(Yt=>ws(Yt,t.now,t.dayStart)),lr=_y(md(_t)),Se=Math.min(t.now,ae.reduce((Yt,$r)=>Math.max(Yt,$r.endedAt??$r.lastActivityAt),t.dayStart)),dr=ae.reduce((Yt,$r)=>Math.min(Yt,Math.max(t.dayStart,$r.startedAt)),t.now),zt=_t.reduce((Yt,$r)=>Math.max(Yt,$r.end),dr);return{sessionId:A,label:me?.taskLabel??me?.label??"Untitled session",taskLabel:me?.taskLabel??null,project:me?.projectLabel??null,context:me?.context?Be(me.context):null,detail:`${N(ae.length,"run")} · ${fe(lr)} recorded run time · ${w(dr)}–${w(zt)}`,outcomes:P(ae),states:$(ae),time:fe(lr),span:`${w(dr)}–${w(zt)}`,runCount:ae.length,timeMs:lr,lastAt:Se}}).sort((A,ae)=>ae.timeMs-A.timeMs||ae.lastAt-A.lastAt||A.sessionId.localeCompare(ae.sessionId)),R=[],H=h.filter(A=>A.status==="waiting"),U=h.filter(A=>A.status==="running"),L=h.filter(A=>A.status==="idle");H.length&&R.push({filter:"waiting",title:`${N(H.length,"run")} waiting for your response`,detail:"The source explicitly recorded a request for input or approval."}),U.length&&R.push({filter:"running",title:`${N(U.length,"run")} with recent events`,detail:"An ending has not been recorded. Open the runs to inspect their latest events."}),a.failed&&R.push({filter:"failed",title:`${N(a.failed,"run")} ended with a failure`,detail:"Open the records to inspect the reported failure. A later retry may be a separate run."}),a.interrupted&&R.push({filter:"stopped",title:`${N(a.interrupted,"run")} stopped before completion`,detail:"The source recorded an interruption; it does not say whether stopping was intentional."}),b.length&&R.push({filter:"toolErrors",title:`${N(b.length,"run")} reported tool errors`,detail:_.filter(([A])=>A>0).map(([A,ae])=>`${A} ${ae}`).join(" · ")+". Error resolution is not recorded."}),L.length&&R.push({filter:"idle",title:`${N(L.length,"run")} without a recorded ending`,detail:(L.length===1?`Last event ${w(L[0].lastActivityAt)}. `:"No recent events. ")+"Activity beyond those events is unknown."});const G=["waiting","failed","running","idle","stopped"].map(A=>R.find(ae=>ae.filter===A)).find(A=>A!==void 0)??null,te=G?p.filter(A=>G.filter==="stopped"?A.outcome==="interrupted":G.filter==="failed"?A.status==="failed"&&A.outcome!=="interrupted":A.endedAt===void 0&&A.status===G.filter):[],ne=[...new Set(te.map(A=>A.sessionId))],ge=ne.length===1?t.sessions.get(ne[0]):void 0,we=[ge?.projectLabel,ge?.taskLabel].filter(Boolean).join(" · "),Pe=G?{...G,detail:(we?we+". ":"")+G.detail}:null,Oe=[Uc("REQUESTS",n.requests,n.accounting.requests,p.length),Lt("RUNS",String(n.executions.value),n.executions,{note:I>0?`${I} of them sub-agents`:void 0}),Lt("SESSIONS",String(n.sessions.value),n.sessions),Uc("TOKENS",n.tokens,n.accounting.tokens,p.length,`${Ti(o.cacheRead,o.total)} cache reads${h.some(A=>Object.keys(A.measures).some(ae=>ae.startsWith("tokens.")))?" · includes accumulating open runs":""}`),Uc("TOOL CALLS",n.toolCalls,n.accounting.tools,p.length,a.toolErrors>0?`${a.toolErrors} tool ${a.toolErrors===1?"error":"errors"}`:void 0),Lt("TIME IN FLIGHT",fe(n.timeInFlight.value),n.timeInFlight,{note:`${h.length>0?"provisional open intervals · ":""}within period · includes waiting · parallel intervals count once`}),Lt("TIME WITH PARALLEL RUNS",fe(n.parallelTime.value),n.parallelTime),Lt("PEAK CONCURRENCY",n.peakConcurrency.value>0?`${n.peakConcurrency.value} · ${w(n.peakConcurrencyAt.value)}`:"0",n.peakConcurrency),Lt("CONTEXT CHANGES",String(n.contextSwitches.value),n.contextSwitches,{note:`sequential only · known contexts: ${l.filter(A=>A.key.length>0).length}`}),Lt("LONGEST CONTEXT SPAN",k?fe(k.end-k.start):"—",n.longestContextSpan,{note:k?`${Be(k.context)} · ${w(k.start)}–${w(k.end)}`:void 0}),kS(n.waitingOnYou,i,e),Lt("FAILED",g>0?String(a.failed):"—",void 0,{tone:a.failed>0?"failed":void 0,note:g>0?`${g} terminal records${v?` · ${v} endings inferred`:""}${h.length?` · ${h.length} runs still open`:""}${a.interrupted?` · ${a.interrupted} stopped`:""}`:"no terminal outcomes recorded yet"})],Q=c.length>0?c.reduce((A,ae)=>ae.computeMs>A.computeMs?ae:A,c[0]):void 0,Ae=A=>`${String(A).padStart(2,"0")}:00`,Ne=[{title:"WHERE THE TIME WENT",rows:Hc(l,Be,!1)}];return m.length>0&&Ne.push({title:"BY MACHINE",rows:Hc(m,A=>t.machines.get(A)?.name??A,!1)}),d.length>0&&Ne.push({title:"BY MODEL",rows:Hc(d,A=>A===dp?"model not observed":A,!0)}),{activity:{summary:`${N(p.length,"run")} recorded in ${N(C.size,"session")}.`,leadSessionId:T[0]?.timeMs>0?T[0].sessionId:null,focus:Pe,outcomes:P(p),states:$(p),timing:`Recorded run intervals cover ${fe(n.timeInFlight.value)}. `+(n.parallelTime.value>0?`For ${fe(n.parallelTime.value)}, two or more runs overlapped.`:"No overlapping run intervals were recorded."),timingSummary:`${fe(n.timeInFlight.value)} in recorded runs · waiting included · overlaps counted once${h.length?" · open runs estimated":""}`,timingNote:"Waiting is included; overlapping intervals count once. "+(h.length?"Open intervals are provisional: silence can shorten the estimate and later events can revise it. ":"")+"This measures recorded intervals, not CPU time or your time at work.",checks:R,sessions:T},observation:"Only events 057 could read are included. Gaps may mean missing data; they do not establish inactivity.",overview:`${p.length} runs observed · ${a.completed} completed · ${a.failed} failed · ${a.interrupted} stopped · ${h.length} still open${v?` · ${v} endings inferred`:""}`,errorOutcomes:b.length?`${b.length} runs reported tool errors: ${_.filter(([A])=>A>0).map(([A,ae])=>`${A} ${ae}`).join(", ")}. Completion does not establish that every error was resolved.`:void 0,contributors:E,headline:s.headline,empty:p.length===0?"No runs observed in this window. This does not establish that no work happened.":void 0,clauses:[...s.clauses],measures:Oe.map(A=>({...A,...xS[A.key]})),hours:c.map(A=>({hour:new Date(A.from).getHours(),from:Math.max(t.dayStart,A.from),to:Math.min(t.now,A.to),partial:A.from<t.dayStart||A.to>t.now,computeMs:A.computeMs,runs:A.runs,peak:A.peak})),busiest:Q?`most time in flight ${Ae(new Date(Q.from).getHours())} · ${fe(Q.computeMs)}`:void 0,timeline:r==="last-7d"?{title:"DAY BY DAY",legend:"Time in flight within the selected window · first and last days may be partial · brighter columns contain parallel runs",buckets:u.map(A=>({label:new Date(A.from).toLocaleDateString("en-GB",{day:"2-digit",month:"short"}).toUpperCase(),from:Math.max(t.dayStart,A.from),to:Math.min(t.now,A.to),partial:A.from<t.dayStart||A.to>t.now,computeMs:A.computeMs,fraction:A.computeMs/(A.to-A.from),runs:A.runs,peak:A.peak}))}:void 0,groups:Ne,tokens:n.accounting.tokens===0?[]:ES(o),tokensNote:n.accounting.tokens===0?"Token accounting is not reported in this window.":"Input, output and cache reads form the total. Reasoning is part of output and is never added again. Cache reads count replayed context, not newly generated output.",failures:p.filter(A=>A.status==="failed").sort((A,ae)=>ae.startedAt-A.startedAt).slice(0,12).map(A=>({id:A.id,at:w(A.startedAt),label:A.label,reason:A.failure?`${A.failure.code}: ${A.failure.message}`:"failed"})),notAvailable:[{key:"COST",text:"Every source here reports tokens or CPU time; none reports money. Converting one to the other needs a price table 057 does not have, so no cost figure is shown anywhere."},{key:"TOKENS, FROM SOME SOURCES",text:"Cursor persists no usage and 0x2F records none; their runs read NOT OBSERVED rather than 0, and the token totals sum only the runs that report."},{key:"CLAUDE IN A BROWSER",text:"Claude on claude.ai — chat, Claude Design, cloud Claude Code sessions — runs on Anthropic's servers and writes nothing to this Mac. Only Claude Code sessions that run here (a terminal, an editor, the desktop app's Code tab) leave the files 057 reads; the browser is seen as a process, never as work."},{key:"MACHINE-TO-MACHINE TRANSFER",text:"Every observed source is single-host. Transfers are modelled and the field renders them, but no real adapter emits one; only the synthetic source does."},{key:"PROCESS EXITS",text:"The OS collector samples; an exit is inferred from disappearance between samples, never witnessed."},{key:"OUTCOME QUALITY",text:"The log records that a run completed, not whether the work was any good."}]}}const xS={REQUESTS:{title:"REPORTED REQUESTS",meaning:"Model requests counted by sources that report them. One run can make several requests."},RUNS:{title:"RECORDED RUNS",meaning:"Recorded attempts or turns inside AI-tool sessions. This is not a count of solved tasks."},SESSIONS:{title:"SESSIONS WITH RUNS",meaning:"Conversations or task containers with at least one run in this period."},TOKENS:{title:"REPORTED TOKENS",meaning:"Input + output + cache reads. Repeated context can dominate this total; it is not generated output alone."},"TOOL CALLS":{title:"REPORTED TOOL CALLS",meaning:"Operations such as commands or tool requests. Errors can occur in a run that later completes."},"TIME IN FLIGHT":{title:"RECORDED RUN TIME",meaning:"Time covered by at least one recorded run, including waiting. Overlapping runs count once."},"TIME WITH PARALLEL RUNS":{title:"TIME WITH OVERLAPPING RUNS",meaning:"Time covered by two or more recorded run intervals. This does not measure CPU load."},"PEAK CONCURRENCY":{title:"MOST RUNS AT ONCE",meaning:"Largest number of overlapping run intervals, followed by the local time it was first reached."},"CONTEXT CHANGES":{title:"WORKING FOLDER CHANGES",meaning:"Sequential changes between observed working folders. Parallel folders have no definite order."},"LONGEST CONTEXT SPAN":{title:"LONGEST WORKING FOLDER SPAN",meaning:"Recorded run continuity in one folder, joining gaps up to 15 minutes. This does not measure human focus."},"WAITING ON YOU":{title:"WAITING FOR YOUR RESPONSE",meaning:"Recorded requests for your input or approval. Summed across runs; simultaneous waits add together."},FAILED:{title:"RUNS ENDED WITH FAILURE",meaning:"Runs with a recorded failure outcome. Later retries and the quality of the task result are separate."}};function pp(t,e=!1){const{period:r,asOf:n,project:s,today:o,comparison:i}=t,a=u=>new Date(u).toISOString(),c=["057 · ACTIVITY SUMMARY",`Period: ${r.label}`,`From (inclusive, UTC): ${a(r.from)}`,`To (exclusive, UTC): ${a(r.to)}`,`Snapshot (UTC): ${a(n)}`,`Working context: ${s?e?s.privateLabel:s.label:"ALL WORKING CONTEXTS"}`];s&&!e&&c.push(`Working context: ${s.detail}`),e&&c.push("Privacy Mode: identifying labels and free-text details omitted."),c.push("","OBSERVATION",o.empty??"Records are present. Historical observation continuity is unknown; absence of records does not establish inactivity.","","MEASURES");for(const u of o.measures)c.push(`${u.key}: ${u.value}${u.inferred?" [inferred]":""}`),u.note&&(!e||u.key!=="LONGEST CONTEXT SPAN")&&c.push(` ${u.note}`),u.assumption&&c.push(` Basis: ${u.assumption}`);if(c.push("","TIME DEFINITIONS","Time in flight is the union of run intervals within this window. Parallel intervals count once.","Group run time adds run intervals within the window. Parallel intervals add together.","LOG run intervals are clipped to this window and exclude trailing idle silence; parallel runs add together.","Tokens and tool counts include only accounting events in the selected half-open window. Open runs are accumulating.","The inspector separates these period contributions from the full retained run record as of the window end.","Completion records an outcome, not the quality of the work."),!e){c.push("","READING THE PERIOD",o.headline,...o.clauses);for(const u of o.groups){c.push("",u.title);for(const l of u.rows)c.push(`${l.label}: ${l.detail}${l.failed?` · ${l.failed} failed`:""}${l.median?` · ${l.median.text}`:""}`,...l.median?[` ${l.median.title}`]:[])}if(o.failures.length){c.push("","FAILURE RECORDS");for(const u of o.failures)c.push(`${u.at} · ${u.label}: ${u.reason}`)}}c.push("","TOKEN COMPOSITION",o.tokensNote);for(const u of o.tokens)c.push(`${u.key}: ${u.value} · ${u.percentLabel}${u.subset?" (subset of output)":""}`);if(i){c.push("","PERIOD COMPARISON",t.comparisonLabel?`B: ${t.comparisonLabel}. Exact bounds and qualifications follow.`:"B immediately precedes A and has the same duration.",i.verdict??"");for(const u of i.periods??[])c.push(`${u.k}: ${u.w} · ${u.s}`);for(const u of i.evidence){const l=u.comparison;l&&c.push(`${u.k}: A ${l.a} [${l.aEvidence}] · B ${l.b} [${l.bEvidence}] · ${l.eligibility}`,...l.reasons.map(d=>` ${d}`))}for(const u of i.reasons)c.push(`${u.k}: ${u.v}`)}c.push("","SOURCE LIMITS");for(const u of o.notAvailable)c.push(`${u.key}: ${u.text}`);return c.join(`
10
10
  `)+`
11
- `}function id(t){const e=t?.context.trim()||t?.projectLabel?.trim();if(!e)return{key:'["unassigned"]',kind:"unassigned"};const r=t?.context.trim()?"context":"label",n=t?.machineId??"";return{key:JSON.stringify([r,n,e]),kind:r,machine:n,value:e}}function li(t){if(t.length>4096)return null;try{const e=JSON.parse(t);if(!Array.isArray(e))return null;if(t==='["unassigned"]'&&e.length===1&&e[0]==="unassigned")return{key:t,kind:"unassigned"};const[r,n,o]=e;return e.length!==3||r!=="context"&&r!=="label"||typeof n!="string"||typeof o!="string"||!o.trim()?null:JSON.stringify([r,n,o])===t?{key:t,kind:r,machine:n,value:o}:null}catch{return null}}function ls(t,e){if(e===void 0)return t;const r=new Map([...t.executions].filter(([,o])=>id(t.sessions.get(o.sessionId)).key===e)),n=new Set([...r.values()].map(o=>o.sessionId));return{...t,executions:r,sessions:new Map([...t.sessions].filter(([o])=>n.has(o)).map(([o,s])=>[o,{...s,executionIds:s.executionIds.filter(i=>r.has(i))}])),active:new Set([...t.active].filter(o=>r.has(o)))}}function Tc(t,e,r={}){const n=new Set(e.disturbances.map(i=>i.id)),o=new Set(e.strata.map(i=>i.id)),s=[...t.executions.values()].sort((i,a)=>a.startedAt-i.startedAt).map(i=>{const a=t.sessions.get(i.sessionId),c=r.starts?.[i.id],u=c?.at??i.startedAt,d=ho(i,t.now,t.dayStart);return{id:i.id,startedAt:u,endedAt:i.endedAt??null,windowClipped:u<t.dayStart,boundsAssumption:c?.assumption??i.boundsAssumption??null,label:i.label,sessionId:i.sessionId,projectKey:id(a).key,sessionLabel:a?.taskLabel??a?.label??null,taskLabel:a?.taskLabel??null,project:a?.projectLabel??null,toolErrors:xi(i),toolErrorsReported:vt(i.measures,Z.errors)!==void 0,waitsReported:r.waitReportedIds?r.waitReportedIds.includes(i.id):null,depth:i.depth,context:a?.context?Ne(a.context):null,model:i.model??null,status:i.status,stopped:i.outcome==="interrupted",durationMs:d.end-d.start,intervalFrom:d.start,intervalTo:d.end,durationBasis:"window-in-flight",inferred:(c?.basis??i.startBasis)==="inferred"||i.endBasis==="inferred",tokens:jr(i.measures)??null,tools:po(i)??null,waitedMs:td(i,t.now),inField:n.has(i.id)?"disturbance":o.has(i.id)?"stratum":null}});return s.sort((i,a)=>a.startedAt-i.startedAt),{now:t.now,rows:s}}function by(t,e){const r=ls(t,e.key),n=rd(r),o=vy(r).toolErrors,s=e.kind==="unassigned"?"CONTEXT NOT REPORTED":e.kind==="context"?Ne(e.value??""):e.value??"",i=e.machine?t.machines.get(e.machine)?.name??e.machine:void 0,a=e.kind==="unassigned"?"No working context or project label reported":[e.value,i,e.kind==="label"?"grouped by reported label; no working context":void 0].filter(Boolean).join(" · "),c=n.accounting.tokens,u=r.executions.size;let d=2166136261;for(const l of e.key)d=Math.imul(d^l.charCodeAt(0),16777619);return{key:e.key,label:s,detail:a,runs:u,context:e.value,machine:i,privateLabel:e.kind==="unassigned"?"CONTEXT NOT REPORTED":`PROJECT ${(d>>>0).toString(16).padStart(8,"0").toUpperCase()}`,summary:`${u} ${u===1?"run":"runs"} · ${fe(n.timeInFlight.value)} in flight`+(c>0?` · ${ze(n.tokens.value)} tok${c<u?` (${c}/${u} reported)`:""}`:" · tokens not reported")+(o>0?` · ${o} tool ${o===1?"error":"errors"}`:"")}}function aA(t){const e=new Map;for(const r of t.executions.values()){const n=id(t.sessions.get(r.sessionId));e.set(n.key,n)}return[...e.values()].map(r=>by(t,r)).sort((r,n)=>n.runs-r.runs||r.detail.localeCompare(n.detail))}function cA(t,e){const r=e===void 0?null:li(e);return r?by(t,r):null}const ad={width:80,color:!1,ascii:!1},uA={dim:"2",bold:"1",yellow:"33","bold-yellow":"1;33"};class lA{segments=[];length=0;text(e,r){return e.length>0&&(this.segments.push({text:e,role:r}),this.length+=$e(e)),this}at(e,r,n){return this.padTo(e),this.text(r,n)}right(e,r,n){return this.at(e-$e(r)+1,r,n)}append(e){for(const r of e.segments)this.text(r.text,r.role);return this}padTo(e){const r=e-this.length;return r>0?this.text(" ".repeat(r)):this.length>0&&!this.endsWithSpace()&&this.text(" "),this}endsWithSpace(){const e=this.segments[this.segments.length-1];return e!==void 0&&e.text.endsWith(" ")}}function _(){return new lA}function ha(t,e){return`${t.map(r=>dA(r,e.color)).join(`
11
+ `}function Sd(t){const e=t?.context.trim()||t?.projectLabel?.trim();if(!e)return{key:'["unassigned"]',kind:"unassigned"};const r=t?.context.trim()?"context":"label",n=t?.machineId??"";return{key:JSON.stringify([r,n,e]),kind:r,machine:n,value:e}}function wi(t){if(t.length>4096)return null;try{const e=JSON.parse(t);if(!Array.isArray(e))return null;if(t==='["unassigned"]'&&e.length===1&&e[0]==="unassigned")return{key:t,kind:"unassigned"};const[r,n,s]=e;return e.length!==3||r!=="context"&&r!=="label"||typeof n!="string"||typeof s!="string"||!s.trim()?null:JSON.stringify([r,n,s])===t?{key:t,kind:r,machine:n,value:s}:null}catch{return null}}function vo(t,e){if(e===void 0)return t;const r=new Map([...t.executions].filter(([,s])=>Sd(t.sessions.get(s.sessionId)).key===e)),n=new Set([...r.values()].map(s=>s.sessionId));return{...t,executions:r,sessions:new Map([...t.sessions].filter(([s])=>n.has(s)).map(([s,o])=>[s,{...o,executionIds:o.executionIds.filter(i=>r.has(i))}])),active:new Set([...t.active].filter(s=>r.has(s)))}}function Vc(t,e,r={}){const n=new Set(e.disturbances.map(i=>i.id)),s=new Set(e.strata.map(i=>i.id)),o=[...t.executions.values()].sort((i,a)=>a.startedAt-i.startedAt).map(i=>{const a=t.sessions.get(i.sessionId),c=r.starts?.[i.id],u=c?.at??i.startedAt,l=ws(i,t.now,t.dayStart);return{id:i.id,startedAt:u,endedAt:i.endedAt??null,windowClipped:u<t.dayStart,boundsAssumption:c?.assumption??i.boundsAssumption??null,label:i.label,sessionId:i.sessionId,projectKey:Sd(a).key,sessionLabel:a?.taskLabel??a?.label??null,taskLabel:a?.taskLabel??null,project:a?.projectLabel??null,toolErrors:Ri(i),toolErrorsReported:et(i.measures,z.errors)!==void 0,waitsReported:r.waitReportedIds?r.waitReportedIds.includes(i.id):null,depth:i.depth,context:a?.context?Be(a.context):null,model:i.model??null,status:i.status,stopped:i.outcome==="interrupted",durationMs:l.end-l.start,intervalFrom:l.start,intervalTo:l.end,durationBasis:"window-in-flight",inferred:(c?.basis??i.startBasis)==="inferred"||i.endBasis==="inferred",tokens:Hr(i.measures)??null,tools:bs(i)??null,waitedMs:yd(i,t.now),inField:n.has(i.id)?"disturbance":s.has(i.id)?"stratum":null}});return o.sort((i,a)=>a.startedAt-i.startedAt),{now:t.now,rows:o}}function jy(t,e){const r=vo(t,e.key),n=gd(r),s=Ry(r).toolErrors,o=e.kind==="unassigned"?"CONTEXT NOT REPORTED":e.kind==="context"?Be(e.value??""):e.value??"",i=e.machine?t.machines.get(e.machine)?.name??e.machine:void 0,a=e.kind==="unassigned"?"No working context or project label reported":[e.value,i,e.kind==="label"?"grouped by reported label; no working context":void 0].filter(Boolean).join(" · "),c=n.accounting.tokens,u=r.executions.size;let l=2166136261;for(const d of e.key)l=Math.imul(l^d.charCodeAt(0),16777619);return{key:e.key,label:o,detail:a,runs:u,context:e.value,machine:i,privateLabel:e.kind==="unassigned"?"CONTEXT NOT REPORTED":`PROJECT ${(l>>>0).toString(16).padStart(8,"0").toUpperCase()}`,summary:`${u} ${u===1?"run":"runs"} · ${fe(n.timeInFlight.value)} in flight`+(c>0?` · ${Ye(n.tokens.value)} tok${c<u?` (${c}/${u} reported)`:""}`:" · tokens not reported")+(s>0?` · ${s} tool ${s===1?"error":"errors"}`:"")}}function IS(t){const e=new Map;for(const r of t.executions.values()){const n=Sd(t.sessions.get(r.sessionId));e.set(n.key,n)}return[...e.values()].map(r=>jy(t,r)).sort((r,n)=>n.runs-r.runs||r.detail.localeCompare(n.detail))}function CS(t,e){const r=e===void 0?null:wi(e);return r?jy(t,r):null}const Ad={width:80,color:!1,ascii:!1},OS={dim:"2",bold:"1",yellow:"33","bold-yellow":"1;33"};class NS{segments=[];length=0;text(e,r){return e.length>0&&(this.segments.push({text:e,role:r}),this.length+=Me(e)),this}at(e,r,n){return this.padTo(e),this.text(r,n)}right(e,r,n){return this.at(e-Me(r)+1,r,n)}append(e){for(const r of e.segments)this.text(r.text,r.role);return this}padTo(e){const r=e-this.length;return r>0?this.text(" ".repeat(r)):this.length>0&&!this.endsWithSpace()&&this.text(" "),this}endsWithSpace(){const e=this.segments[this.segments.length-1];return e!==void 0&&e.text.endsWith(" ")}}function j(){return new NS}function Ia(t,e){return`${t.map(r=>TS(r,e.color)).join(`
12
12
  `)}
13
- `}function dA(t,e){const r=t.segments.map(n=>({...n}));for(;r.length>0&&r[r.length-1].text.trim()==="";)r.pop();if(r.length>0){const n=r[r.length-1];n.text=n.text.trimEnd()}return r.map(n=>{if(!e||!n.role||n.text.trim()==="")return n.text;const o=n.text.length-n.text.trimStart().length,s=n.text.trim(),i=n.text.length-o-s.length;return`${" ".repeat(o)}\x1B[${uA[n.role]}m${s}\x1B[0m${" ".repeat(i)}`}).join("")}function $e(t){return[...t].length}function fA(t,e){const r=t.split(/\s+/).filter(s=>s.length>0),n=[];let o="";for(const s of r)o.length===0?o=s:$e(o)+1+$e(s)<=e?o+=` ${s}`:(n.push(o),o=s);return(o.length>0||n.length===0)&&n.push(o),n}function tn(t,e,r,n,o,s){const i=Math.max(12,o-Math.max(e,r)),a=fA(n,i),c=[t.at(e,a[0],s)];for(const u of a.slice(1))c.push(_().at(r,u,s));return c}function an(t){return t.ascii?{sep:", ",dash:"--",arrow:"->",range:"-"}:{sep:" · ",dash:"—",arrow:"→",range:"–"}}function Lt(t,e){const r=an(e).sep,n=r.trim(),o=r.slice(0,r.indexOf(n));return t.text(o).text(n,"dim").text(r.slice(o.length+n.length))}function J(t){return t.replace(/-/g," ")}function Je(t){return t==="observed"?"dim":void 0}function ce(t){return"value"in t?t.value:void 0}function Ke(t,e){return t===1?e:`${e}s`}function Te(t){return Number.isInteger(t)?t.toLocaleString("en-US"):t.toLocaleString("en-US",{minimumFractionDigits:1,maximumFractionDigits:1})}function Et(t){if(t<1e3)return String(Math.round(t));if(t<1e6)return`${(t/1e3).toFixed(t<1e4?1:0)}K`;if(t<1e9)return`${(t/1e6).toFixed(t<1e7?1:0)}M`;const e=t/1e9;return`${e.toFixed(e<10?3:e<100?2:1)}B`}function mt(t){const e=Math.round(t/6e4);return e<1?`${Math.round(t/1e3)}s`:e<60?`${e}m`:`${Math.floor(e/60)}h ${e%60}m`}function wy(t){if(t<6e4)return`${Math.round(t/1e3)}s`;if(t<36e5)return`${Math.round(t/6e4)}m`;const e=Math.round(t/6e4);return`${Math.floor(e/60)}h ${e%60}m`}function iu(t){const e=Math.round(t/1e3);if(e<60)return`${e}s`;if(e<3600){const n=e%60;return n===0?`${Math.floor(e/60)}m`:`${Math.floor(e/60)}m ${n}s`}const r=Math.round(t/6e4);return`${Math.floor(r/60)}h ${r%60}m`}function Wn(t,e){const r=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(t)),n=o=>r.find(s=>s.type===o)?.value??"";return{day:`${n("year")}-${n("month")}-${n("day")}`,time:`${n("hour")}:${n("minute")}`,zone:pA(t,e)}}function pA(t,e){const r=s=>new Intl.DateTimeFormat(s,{timeZone:e,timeZoneName:"short"}).formatToParts(new Date(t)).find(i=>i.type==="timeZoneName")?.value??"",n=r("en-US");if(!n.startsWith("GMT"))return n;const o=r("en-GB");return o.length>0?o:n}function ds(t,e){const r=an(e),n=Wn(t.from,e.timeZone),o=Wn(t.to,e.timeZone);if(n.day===o.day&&n.zone===o.zone)return`${n.day}${r.sep}${n.time}${r.range}${o.time} ${o.zone}`;const s=n.zone===o.zone?"":` ${n.zone}`;return`${n.day} ${n.time}${s} ${r.arrow} ${o.day} ${o.time} ${o.zone}`}function au(t,e,r){const n=Wn(t,r.timeZone);return Wn(e.from,r.timeZone).day===Wn(e.to,r.timeZone).day?n.time:`${n.day} ${n.time}`}function cd(t,e){const r=Wn(t,e.timeZone);return`${r.day} ${r.time} ${r.zone}`}function ma(t,e){const r=_().text("057","dim").text(" ").text("COMPUTATIONAL ACTIVITY","bold");return r.length+2+$e(t)<=e?[r.right(e-1,t,"dim")]:[r,_().right(e-1,t,"dim")]}function ud(t,e,r,n){const o=ds(t,n),s=_();return e.forEach((i,a)=>{a>0&&Lt(s,n),s.text(i.text,i.role)}),e.length===0?[_().text(o)]:$e(o)+2+s.length<=r?[_().text(o).padTo(r-s.length).append(s)]:[_().text(o),s]}function fs(t){return t==="observed"?void 0:"yellow"}function Ay(t){return t==="within-retention"||t==="retained-indefinitely"?void 0:"yellow"}function bt(t,e){const r=t.match(/^\[(.+)\]$/);if(!r)return{text:t,pseudo:!1};const n=J(r[1]);return{text:e==="model"||e==="executor"?`${e} ${n}`:n,pseudo:!0}}function hA(t,e=ad){const r=mA(e.width),{summary:n,availability:o}=t,s=[...ma("SUMMARY",r.measure),...ud(t.period,[{text:J(o.observation),role:fs(o.observation)},{text:J(o.retention.state),role:Ay(o.retention.state)}],r.measure,e),Lt(_().text(String(n.executions),"bold").text(` ${Ke(n.executions,"execution")}`),e).text(String(n.sessions),"bold").text(` ${Ke(n.sessions,"session")}`)];for(const i of yA(t,e)){s.push(_(),_().text(i.head,"dim"));const a=Math.max(4,...i.rows.map(c=>c.kind==="model"?(c.tokens??"").length:0));for(const c of i.rows)s.push(...gA(c,r,a,e))}return ha(s,e)}function mA(t){if(t>=80)return{measure:79,labelMax:22,figureEnd:33,compositeCol:24,tailCol:35,evidenceCol:67,split:!1,stacked:!1};const e=Math.max(1,t-1);if(t>=56)return{measure:e,labelMax:20,figureEnd:29,compositeCol:4,tailCol:31,evidenceCol:43,split:!0,stacked:!1};const r=Math.min(43,Math.max(24,e-12));return{measure:e,labelMax:20,figureEnd:29,compositeCol:4,tailCol:31,evidenceCol:r,split:!0,stacked:!0}}function yA(t,e){const{summary:r,availability:n}=t,o=an(e).dash,s=(v,g,I,N)=>{const S=ce(g);return S===void 0?{kind:"figure",label:v,figure:o,dash:!0,evidence:g.state}:{kind:"figure",label:v,figure:I(S),dash:!1,tail:N?.(S),evidence:g.state}},i=(v,g)=>({kind:"figure",label:v,figure:String(g),dash:!1}),a=r.executions===0&&n.observation!=="observed"?{head:"RECORDED LIFECYCLE",rows:[{kind:"prose",text:"no execution records; zero work is not established"}]}:{head:n.observation==="observed"?"NOW":"RECORDED LIFECYCLE",rows:[i("running",r.runningNow),s("waiting",r.waitingNow,String),i("idle",r.idleNow)]},c=r.terminalExecutionDuration,u=ce(c),d=u===void 0?{kind:"figure",label:"terminal execution",figure:o,dash:!0,evidence:c.state}:{kind:"composite",label:"terminal execution",evidence:c.state,value:Lt(Lt(_().text("median ").text(mt(u.median),"bold"),e).text("p90 ").text(mt(u.p90),"bold"),e).text("max ").text(mt(u.maximum),"bold")},l=r.usageByModel.map(v=>{const g=ce(v.tokens);return{kind:"model",label:v.model,pseudo:!1,executions:v.executions,tokens:g===void 0?o:Et(g),dash:g===void 0,evidence:v.tokens.state}}),m=r.modelMix.filter(v=>bt(v.key,"model").pseudo);if(m.reduce((v,g)=>v+g.executions,0)===r.executionsWithoutModel)for(const v of m)l.push({kind:"model",label:bt(v.key,"model").text,pseudo:!0,executions:v.executions});else r.executionsWithoutModel>0&&l.push({kind:"model",label:"model not observed",pseudo:!0,executions:r.executionsWithoutModel});const h=[a,{head:"OUTCOMES",rows:[s("completed",r.completed,String),s("failed",r.failed,String),s("interrupted",r.interrupted,String)]},{head:"DURATION",rows:[s("time in flight",r.inFlight.totalMs,fe),s("added by open records",r.inFlight.openContributionMs,fe),s("parallel in flight",r.inFlight.parallelMs,fe),s("in-flight peak",r.inFlight.peak,v=>String(v.peak),v=>v.at===null?_():_().text(`at ${au(v.at,t.period,e)}`)),d,s("terminal interval",r.terminalExecutionIntervalMs,mt),s("terminal overlap",r.overlappingTerminalIntervalMs,mt),s("terminal peak",r.peakTerminalConcurrency,v=>String(v.peak),v=>v.at===null?_():_().text(`at ${au(v.at,t.period,e)}`))]},{head:"USAGE",rows:[s("tokens",r.tokens,Et),s("tool interactions",r.toolInteractions,Et),s("tool errors",r.toolErrors,Et),s("explicit waits",r.waits,v=>String(v.count),v=>{const g=_().text("for ").text(mt(v.durationMs),"bold");return v.openNow>0?Lt(g,e).text(String(v.openNow),"bold").text(" open"):g})]}];return h.push({head:"INTERVAL POLICY",rows:[{kind:"prose",text:r.inFlight.assumption}]}),l.length>0&&h.push({head:"BY MODEL",rows:l}),h}function gA(t,e,r,n){const o=(s,i)=>i===void 0?s:s.at(e.evidenceCol,J(i),Je(i));switch(t.kind){case"prose":return tn(_(),2,2,t.text,e.measure);case"figure":{const s=t.dash?void 0:"bold";if(e.stacked){const c=_().at(4,t.figure,s);return t.tail&&t.tail.length>0&&c.text(" ").append(t.tail),[o(_().at(2,t.label),t.evidence),c]}const i=[];let a=_();return t.label.length>e.labelMax?i.push(_().at(2,t.label)):a.at(2,t.label),a.right(e.figureEnd,t.figure,s),t.tail&&t.tail.length>0&&a.at(e.tailCol,"").append(t.tail),i.push(o(a,t.evidence)),i}case"composite":{if(e.split)return[o(_().at(2,t.label),t.evidence),_().at(4,"").append(t.value)];const s=[],i=_();return t.label.length>e.labelMax?s.push(_().at(2,t.label)):i.at(2,t.label),s.push(o(i.at(e.compositeCol,"").append(t.value),t.evidence)),s}case"model":{const s=t.pseudo?"dim":void 0,i=t.tokens===void 0?` ${Ke(t.executions,"execution")}`:` ${Ke(t.executions,"execution").padEnd(10)}`,a=d=>(d.text(String(t.executions),"bold").text(i),t.tokens===void 0?d:Lt(d,n).text(t.tokens.padStart(r),t.dash?void 0:"bold").text(" tokens"));if(e.split){const d=_().padTo(7-String(t.executions).length);return[o(_().at(2,t.label,s),t.evidence),a(d)]}const c=[],u=_();return t.label.length>e.labelMax?c.push(_().at(2,t.label,s)):u.at(2,t.label,s),u.padTo(e.figureEnd-String(t.executions).length+1),c.push(o(a(u),t.evidence)),c}}}const Kn={"median terminal execution duration":{label:"median terminal duration",duration:!0},"terminal execution interval union":{label:"terminal interval union",duration:!0},"overlapping terminal interval":{label:"overlapping interval",duration:!0},"explicit wait count":{label:"explicit waits"}};function vA(t,e){const r=an(e).dash,n=[],o=[];for(const u of t.dimensions)if(bA(u)){const d=u.dimension.replace(/ mix$/,"");o.push({head:u.dimension.toUpperCase(),subject:d,a:tp(u.periodA,d),b:tp(u.periodB,d),result:J(u.eligibility)})}else{const d=Kn[u.dimension],l=m=>{const p=ce(m);return typeof p!="number"?{value:r,dash:!0,evidence:m.state}:{value:d?.duration?iu(p):Te(p),dash:!1,evidence:m.state}};n.push({label:d?.label??u.dimension,a:l(u.periodA),b:l(u.periodB),result:J(u.eligibility)})}const s=AA(n,o),i=s.measure<=e.width-1?"wide":e.width>=80?"paired":"stacked",a=i==="wide"?s.measure:i==="paired"?79:Math.max(1,e.width-1),c=[...ma("COMPARISON",a)];return c.push(...rp("A",t.periodA,t.availabilityA.observation,a,e)),c.push(...rp("B",t.periodB,t.availabilityB.observation,a,e)),c.push(_(),...wA(t,a)),c.push(_()),i==="wide"?c.push(...SA(n,o,s,r)):i==="paired"?c.push(...kA(n,o)):c.push(...EA(n,o)),ha(c,e)}function bA(t){const e=ce(t.periodA)??ce(t.periodB);return t.dimension.endsWith(" mix")||e!==void 0&&typeof e=="object"}function tp(t,e){const r=ce(t);return r===void 0||typeof r=="number"?{evidence:t.state}:{evidence:t.state,items:Object.entries(r).map(([n,o])=>{const s=bt(n,e);return{key:s.text,pseudo:s.pseudo,count:o}})}}function rp(t,e,r,n,o){const s=ds(e,o),i=J(r),a=Math.max(46,3+$e(s)+3),c=_().text(t,"bold").at(3,s);return a+$e(i)<=n?[c.at(a,i,fs(r))]:[c,_().at(3,i,fs(r))]}function wA(t,e){const r=[_().text(J(t.eligibility).toUpperCase(),t.eligibility==="comparable"?"bold":"bold-yellow")];for(const o of t.reasons){const s=o.match(/^period ([AB]): (.*)$/);s?r.push(...tn(_().at(2,s[1],"dim"),5,5,s[2],e)):r.push(...tn(_(),2,2,o,e))}const n=new Map;for(const o of t.dimensions)for(const s of o.reasons){const i=n.get(s)??[];i.push(Kn[o.dimension]?.label??o.dimension),n.set(s,i)}for(const[o,s]of n){const i=s.length===t.dimensions.length?"All dimensions":s.join(", ");r.push(...tn(_(),2,2,`${i}: ${o}.`,e))}return r}function AA(t,e){const r=p=>e.flatMap(h=>h[p].items?.map(v=>Te(v.count))??[]),n=(p,h)=>Math.max(h,...p.map($e)),o=n([...t.map(p=>p.a.value),...r("a")],13),s=n([...t.map(p=>p.b.value),...r("b")],13),i=n([...t.flatMap(p=>[J(p.a.evidence),J(p.b.evidence)]),...e.flatMap(p=>[J(p.a.evidence),J(p.b.evidence)])],12),a=29+o-1,c=a+3,u=c+i+2+s,d=u+3,l=d+i+3,m=n([...t.map(p=>p.result),...e.map(p=>p.result)],0);return{measure:l+m,aEnd:a,aEvidence:c,bEnd:u,bEvidence:d,result:l}}function Ci(t){return t.dash?void 0:"bold"}function cu(t,e,r,n){return $e(t)>e?{lead:[_().at(r,t,n)],row:_()}:{lead:[],row:_().at(r,t,n)}}function SA(t,e,r,n){const o=[_().text("MEASURE","dim").right(r.aEnd,"A","dim").right(r.bEnd,"B","dim").at(r.result,"COMPARISON","dim")];for(const s of t){const{lead:i,row:a}=cu(s.label,25,2);o.push(...i,a.right(r.aEnd,s.a.value,Ci(s.a)).at(r.aEvidence,J(s.a.evidence),Je(s.a.evidence)).right(r.bEnd,s.b.value,Ci(s.b)).at(r.bEvidence,J(s.b.evidence),Je(s.b.evidence)).at(r.result,s.result))}for(const s of e){o.push(_(),_().text(s.head,"dim").at(r.aEvidence,J(s.a.evidence),Je(s.a.evidence)).at(r.bEvidence,J(s.b.evidence),Je(s.b.evidence)).at(r.result,s.result));const i=new Map;for(const a of s.a.items??[])i.set(a.key,{pseudo:a.pseudo,a:a.count});for(const a of s.b.items??[])i.set(a.key,{...i.get(a.key),pseudo:a.pseudo,b:a.count});for(const[a,c]of i){const{lead:u,row:d}=cu(a,25,2,c.pseudo?"dim":void 0);s.a.items&&d.right(r.aEnd,c.a===void 0?n:Te(c.a),c.a===void 0?void 0:"bold"),s.b.items&&d.right(r.bEnd,c.b===void 0?n:Te(c.b),c.b===void 0?void 0:"bold"),o.push(...u,d)}}return o}function kA(t,e){const r=[_().text("MEASURES","dim").right(78,"COMPARISON","dim")],n=(o,s,i,a)=>o.at(i,s,"dim").right(i+15,a.value,Ci(a)).at(i+18,J(a.evidence),Je(a.evidence));for(const o of t)r.push(_().at(2,o.label).right(78,o.result)),r.push(n(n(_(),"A",4,o.a),"B",40,o.b));for(const o of e)r.push(_(),_().text(o.head,"dim").right(78,o.result)),r.push(...Sy(o,29));return r}function EA(t,e){const r=[_().text("MEASURES","dim")],n=(o,s)=>_().at(4,o,"dim").right(28,s.value,Ci(s)).at(31,J(s.evidence),Je(s.evidence));t.forEach((o,s)=>{s>0&&r.push(_()),r.push(_().at(2,o.label),n("A",o.a),n("B",o.b),_().at(4,"comparison","dim").at(16,o.result))});for(const o of e)r.push(_(),_().text(o.head,"dim"),...Sy(o,28)),r.push(_().at(2,"comparison","dim").at(16,o.result));return r}function Sy(t,e){const r=[];for(const[n,o]of[["A",t.a],["B",t.b]]){r.push(_().at(2,n,"dim").at(5,J(o.evidence),Je(o.evidence)));for(const s of o.items??[]){const{lead:i,row:a}=cu(s.key,e-5-1-$e(Te(s.count)),5,s.pseudo?"dim":void 0);r.push(...i,a.right(e,Te(s.count),"bold"))}}return r}const xA=["summary","availability","compare","breakdown"];function tr(t,e,r=ad){switch(t.operation){case"summary":return hA(t.result,r);case"availability":return IA(t.result,r);case"compare":return vA(t.result,r);case"breakdown":return OA(t.result,e,r)}}const ky={"tool-interactions":"tool interactions","tool-errors":"tool errors"};function IA(t,e){const r=e.width>=80,n=e.width<56,o=r?79:Math.max(1,e.width-1),s=25,i=[...ma("AVAILABILITY",o),...ud(t.period,[],o,e)],a=(m,p)=>n?[_().at(2,m),_().padTo(4).append(p)]:[_().at(2,m).padTo(s).append(p)],c=(m,p)=>_().text(m,p),u=m=>i.push(_(),_().text(m,"dim"));u("OBSERVATION"),i.push(...a("state",c(J(t.observation),fs(t.observation))),...a("records",Lt(_().text(String(t.executionRecords),"bold").text(` ${Ke(t.executionRecords,"execution")}`),e).text(String(t.sessionRecords),"bold").text(` ${Ke(t.sessionRecords,"session")}`)),...a("continuity",c(J(t.continuity.state),Je(t.continuity.state))),...a("observation gaps",c(J(t.observationGaps.state),Je(t.observationGaps.state))),...a("unprojected work",c(J(t.unprojectedSourceWork.state),Je(t.unprojectedSourceWork.state)))),u("RETENTION"),i.push(...a("state",c(J(t.retention.state),Ay(t.retention.state)))),t.retention.semanticFrom!==null&&i.push(...a("semantic history from",c(cd(t.retention.semanticFrom,e),"bold")));const d=t.bounds;if(o>=51)i.push(_(),_().text("BOUNDS","dim").right(32,"observed","dim").right(42,"inferred","dim").right(50,"open","dim"),_().at(2,"starts").right(32,String(d.observedStarts),"bold").right(42,String(d.inferredStarts),"bold"),_().at(2,"ends").right(32,String(d.observedEnds),"bold").right(42,String(d.inferredEnds),"bold").right(50,String(d.openEnds),"bold"));else{const m=p=>{const h=_().padTo(4);return p.forEach(([v,g],I)=>{I>0&&Lt(h,e),h.text(String(v),"bold").text(` ${g}`)}),h};u("BOUNDS"),i.push(_().at(2,"starts"),m([[d.observedStarts,"observed"],[d.inferredStarts,"inferred"]]),_().at(2,"ends"),m([[d.observedEnds,"observed"],[d.inferredEnds,"inferred"],[d.openEnds,"open"]]))}u("COMPARISON");const l=t.comparisonReadiness==="comparable"?void 0:"yellow";i.push(...a("readiness",c(J(t.comparisonReadiness),l))),t.reasons.forEach((m,p)=>{const h=p===0?"because":"";n?(h&&i.push(_().at(2,h)),i.push(...tn(_(),4,4,m,o))):i.push(...tn(_().at(2,h),s,s,m,o))}),i.push(_()),r?i.push(_().text("MEASURES","dim").at(21,"state","dim").at(35,"coverage","dim").right(78,"records","dim")):i.push(_().text("MEASURES","dim").at(s,"state","dim").right(o-1,"records","dim"));for(const m of t.measures){const p=ky[m.dimension]??J(m.dimension),h=J(m.state),v=_().text("/","dim").text(" ").text(String(m.coverage.records),"bold");if(r){const g=_().at(2,p).at(21,h,Je(m.state));i.push(...np(g,35,78,m.coverage,v,e))}else i.push(_().at(2,p).at(s,h,Je(m.state))),i.push(...np(_(),4,o-1,m.coverage,v,e))}u("SOURCES"),t.sources.length===0&&i.push(_().at(2,"none observed"));for(const m of t.sources){const p=String(m.executionRecords),h=`execution ${Ke(m.executionRecords,"record")}`;if(29+$e(h)>o){i.push(_().at(2,m.source),_().at(4,p,"bold").text(` ${h}`));continue}const v=g=>g.right(27,p,"bold").at(29,h);$e(m.source)>22?i.push(_().at(2,m.source),v(_())):i.push(v(_().at(2,m.source)))}return ha(i,e)}function np(t,e,r,n,o,s){const a=[[n.observed,"observed"],[n.inferred,"inferred"],[n.partial,"partial"],[n.notObserved,"not-observed"],[n.unsupported,"unsupported"],[n.unknown,"unknown"]].filter(([m])=>m>0).map(([m,p])=>_().text(String(m),"bold").text(" ").text(J(p),Je(p))),c=an(s).sep,u=r-o.length,d=[[]];let l=e;for(const m of a){const p=d[d.length-1],h=l+(p.length>0?c.length:0)+m.length;p.length>0&&h>u?(d.push([m]),l=e+m.length):(p.push(m),l=h)}return d.map((m,p)=>{const h=p===0?t.padTo(e):_().padTo(e);if(m.forEach((v,g)=>{g>0&&Lt(h,s),h.append(v)}),p<d.length-1){const v=c.trim();return h.text(c.slice(0,c.indexOf(v))).text(v,"dim"),h}return h.padTo(r-o.length+1).append(o)})}function OA(t,e,r){const n=an(r).dash,o=d=>{const l=ce(d);return l===void 0?{value:n,dash:!0,evidence:d.state}:{value:Te(l),dash:!1,evidence:d.state}},s=t.items.filter(d=>e===void 0||d.key===e).map(d=>{const l=bt(d.key,t.dimension),m=ce(d.terminalDuration);return{key:l.text,pseudo:l.pseudo,executions:Te(d.executions),singular:d.executions===1,terminal:Te(d.terminalExecutions),median:m===void 0?n:wy(m.median),medianDash:m===void 0,tokens:o(d.tokens),tools:o(d.toolInteractions),errors:o(d.toolErrors),failed:o(d.failed)}}),i=CA(s,t.dimension),a=s.length>0&&i.measure<=r.width-1?"table":r.width>=80?"records":"narrow",c=a==="table"?i.measure:a==="records"?79:Math.max(1,r.width-1),u=[...ma(`BREAKDOWN${an(r).sep}${J(t.dimension).toUpperCase()}`,c),...ud(t.period,[{text:J(t.availability.observation),role:fs(t.availability.observation)}],c,r),_()];if(s.length===0)u.push(_().text("none observed"));else if(a==="table")u.push(...i.lines);else{const d=a==="records"?NA(s):null;s.forEach((l,m)=>{m>0&&u.push(_()),u.push(...d?TA(l,d,r):$A(l,s,r))})}return u.push(_(),...tn(_(),0,0,t.qualification,c,"dim")),ha(u,r)}function Ni(t){return t.pseudo?"dim":"bold"}function Ti(t,e,r){return r.evidence===void 0?t:t.at(e,J(r.evidence),Je(r.evidence))}function CA(t,e){const r=J(e).toUpperCase(),n=[{caption:"EXECUTIONS",value:m=>m.executions},{caption:"TERMINAL",value:m=>m.terminal},{caption:"MEDIAN",value:m=>m.median}],o=[{caption:"TOKENS",value:m=>m.tokens},{caption:"TOOLS",value:m=>m.tools},{caption:"ERRORS",value:m=>m.errors},{caption:"FAILED",value:m=>m.failed}],s=m=>Math.max(0,...m.map($e));let i=Math.max($e(r),s(t.map(m=>m.key))),a=$e(r)-1;const c=n.map(m=>{const p=i+2+Math.max($e(m.caption),s(t.map(m.value)))-1;return i=p+1,a=p,p}),u=o.map(m=>{const p=t.map(m.value);let h=i+2+s(p.map(v=>v.value))-1;return h=Math.max(h,a+2+$e(m.caption)),i=h+3+s(p.map(v=>J(v.evidence??""))),a=h,h}),d=_().text(r,"dim");n.forEach((m,p)=>d.right(c[p],m.caption,"dim")),o.forEach((m,p)=>d.right(u[p],m.caption,"dim"));const l=[d];for(const m of t){const p=_().text(m.key,Ni(m));n.forEach((h,v)=>p.right(c[v],h.value(m),"bold")),o.forEach((h,v)=>{const g=h.value(m);Ti(p.right(u[v],g.value,g.dash?void 0:"bold"),u[v]+3,g)}),l.push(p)}return{measure:i,lines:l}}function Ey(t){const e=r=>Math.max(3,...t.map(n=>$e(r(n))));return{countWidth:e(r=>r.executions),terminalWidth:e(r=>r.terminal),medianWidth:e(r=>r.median)}}function NA(t){const e=o=>Math.max(1,...t.flatMap(s=>o(s).map(i=>$e(i.value)))),r=Math.max(24,10+e(o=>[o.tokens,o.errors])-1),n=Math.max(44,r+3+12+2);return{...Ey(t),countEnd:34,leftEnd:r,rightLabel:n,rightEnd:Math.max(61,n+6+2+e(o=>[o.tools,o.failed])-1)}}function xy(t,e,r,n){return t.text(e.executions.padStart(r.countWidth),"bold").text(` ${(e.singular?"execution":"executions").padEnd(10)}`),Lt(t,n).text(e.terminal.padStart(r.terminalWidth),"bold").text(" terminal"),Lt(t,n).text("median "),t.text(e.median.padStart(r.medianWidth),e.medianDash?void 0:"bold")}function TA(t,e,r){const n=[],o=e.countEnd-e.countWidth+1,s=_();$e(t.key)>=o?n.push(_().text(t.key,Ni(t))):s.text(t.key,Ni(t)),n.push(xy(s.padTo(o),t,e,r));const i=(a,c,u,d)=>{const l=_().at(2,a);return Ti(l.right(e.leftEnd,c.value,c.dash?void 0:"bold"),e.leftEnd+3,c),l.at(e.rightLabel,u),Ti(l.right(e.rightEnd,d.value,d.dash?void 0:"bold"),e.rightEnd+3,d)};return n.push(i("tokens",t.tokens,"tools",t.tools),i("errors",t.errors,"failed",t.failed)),n}function $A(t,e,r){const n=Math.max(1,...e.flatMap(i=>[i.tokens,i.tools,i.errors,i.failed].map(a=>$e(a.value)))),o=Math.max(24,10+n-1),s=(i,a)=>Ti(_().at(2,i).right(o,a.value,a.dash?void 0:"bold"),o+3,a);return[_().text(t.key,Ni(t)),xy(_().padTo(2),t,Ey(e),r),s("tokens",t.tokens),s("tools",t.tools),s("errors",t.errors),s("failed",t.failed)]}const op=["summary","availability","compare","breakdown"],sp=["lifecycle","duration","tokens","waits","errors"],ip=["model","executor"],ap=["today","last-7d"];function BA(t){const e=op.find(a=>a===t.query),r=ap.find(a=>a===(t.scope??"today"));if(!e)return{error:`query must be one of ${op.join(", ")}`};if(!r)return{error:`scope must be one of ${ap.join(", ")}`};const n=t.focus?sp.find(a=>a===t.focus):void 0,o=t.by?ip.find(a=>a===t.by):void 0;if(t.focus&&!n)return{error:`focus must be one of ${sp.join(", ")}`};if(t.by&&!o)return{error:`by must be one of ${ip.join(", ")}`};if(!{summary:[void 0,"lifecycle","duration"],availability:[void 0,"tokens","waits"],breakdown:[void 0,"errors"],compare:[void 0]}[e].includes(n))return{error:`${e} has no ${n} reading`};if(e==="breakdown"&&!o)return{error:"breakdown needs by=model|executor"};if(e!=="breakdown"&&o)return{error:`${e} takes no dimension`};if(n==="errors"&&o!=="model")return{error:"errors are read by model"};const i={query:e,scope:r};return n&&(i.focus=n),o&&(i.by=o),i}function uu(t,e){if(t==="last-7d")return{from:e-7*864e5,to:e};const r=new Date(e);return r.setHours(0,0,0,0),{from:r.getTime(),to:e}}function ld(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function Iy(t,e){const r=n=>{const o=new Date(n);return o.setDate(o.getDate()-e),o.getTime()};return{from:r(t.from),to:r(t.to)}}function RA(t,e,r,n={}){const o=n.period??uu(e.scope,r),s={};switch(e.query){case"summary":s.summary=t.summary(o);break;case"availability":e.focus&&(s.summary=t.summary(o)),s.availability=s.summary?.availability??t.availability(o);break;case"breakdown":s.breakdown=t.breakdown(o,e.by??"model"),e.focus==="errors"&&(s.summary=t.summary(o));break;case"compare":s.comparison=t.compare(o,ld(o));break}return Oy(e,s,n)}function Oy(t,e,r={}){const n=MA(t,e,r);return r.projectKey!==void 0&&(n.observation.unshift({k:"WORKING CONTEXT",v:"Selected working context only; the same filter applies to every period."}),n.command="No equivalent CLI command for this working-context selection.",n.text=`SELECTED WORKING CONTEXT ONLY — filtered before aggregation.
13
+ `}function TS(t,e){const r=t.segments.map(n=>({...n}));for(;r.length>0&&r[r.length-1].text.trim()==="";)r.pop();if(r.length>0){const n=r[r.length-1];n.text=n.text.trimEnd()}return r.map(n=>{if(!e||!n.role||n.text.trim()==="")return n.text;const s=n.text.length-n.text.trimStart().length,o=n.text.trim(),i=n.text.length-s-o.length;return`${" ".repeat(s)}\x1B[${OS[n.role]}m${o}\x1B[0m${" ".repeat(i)}`}).join("")}function Me(t){return[...t].length}function $S(t,e){const r=t.split(/\s+/).filter(o=>o.length>0),n=[];let s="";for(const o of r)s.length===0?s=o:Me(s)+1+Me(o)<=e?s+=` ${o}`:(n.push(s),s=o);return(s.length>0||n.length===0)&&n.push(s),n}function cn(t,e,r,n,s,o){const i=Math.max(12,s-Math.max(e,r)),a=$S(n,i),c=[t.at(e,a[0],o)];for(const u of a.slice(1))c.push(j().at(r,u,o));return c}function hn(t){return t.ascii?{sep:", ",dash:"--",arrow:"->",range:"-"}:{sep:" · ",dash:"—",arrow:"→",range:"–"}}function Ht(t,e){const r=hn(e).sep,n=r.trim(),s=r.slice(0,r.indexOf(n));return t.text(s).text(n,"dim").text(r.slice(s.length+n.length))}function J(t){return t.replace(/-/g," ")}function Ze(t){return t==="observed"?"dim":void 0}function ce(t){return"value"in t?t.value:void 0}function qe(t,e){return t===1?e:`${e}s`}function _e(t){return Number.isInteger(t)?t.toLocaleString("en-US"):t.toLocaleString("en-US",{minimumFractionDigits:1,maximumFractionDigits:1})}function It(t){if(t<1e3)return String(Math.round(t));if(t<1e6)return`${(t/1e3).toFixed(t<1e4?1:0)}K`;if(t<1e9)return`${(t/1e6).toFixed(t<1e7?1:0)}M`;const e=t/1e9;return`${e.toFixed(e<10?3:e<100?2:1)}B`}function yt(t){const e=Math.round(t/6e4);return e<1?`${Math.round(t/1e3)}s`:e<60?`${e}m`:`${Math.floor(e/60)}h ${e%60}m`}function Dy(t){if(t<6e4)return`${Math.round(t/1e3)}s`;if(t<36e5)return`${Math.round(t/6e4)}m`;const e=Math.round(t/6e4);return`${Math.floor(e/60)}h ${e%60}m`}function Su(t){const e=Math.round(t/1e3);if(e<60)return`${e}s`;if(e<3600){const n=e%60;return n===0?`${Math.floor(e/60)}m`:`${Math.floor(e/60)}m ${n}s`}const r=Math.round(t/6e4);return`${Math.floor(r/60)}h ${r%60}m`}function Zn(t,e){const r=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(t)),n=s=>r.find(o=>o.type===s)?.value??"";return{day:`${n("year")}-${n("month")}-${n("day")}`,time:`${n("hour")}:${n("minute")}`,zone:BS(t,e)}}function BS(t,e){const r=o=>new Intl.DateTimeFormat(o,{timeZone:e,timeZoneName:"short"}).formatToParts(new Date(t)).find(i=>i.type==="timeZoneName")?.value??"",n=r("en-US");if(!n.startsWith("GMT"))return n;const s=r("en-GB");return s.length>0?s:n}function bo(t,e){const r=hn(e),n=Zn(t.from,e.timeZone),s=Zn(t.to,e.timeZone);if(n.day===s.day&&n.zone===s.zone)return`${n.day}${r.sep}${n.time}${r.range}${s.time} ${s.zone}`;const o=n.zone===s.zone?"":` ${n.zone}`;return`${n.day} ${n.time}${o} ${r.arrow} ${s.day} ${s.time} ${s.zone}`}function Au(t,e,r){const n=Zn(t,r.timeZone);return Zn(e.from,r.timeZone).day===Zn(e.to,r.timeZone).day?n.time:`${n.day} ${n.time}`}function kd(t,e){const r=Zn(t,e.timeZone);return`${r.day} ${r.time} ${r.zone}`}function Ca(t,e){const r=j().text("057","dim").text(" ").text("COMPUTATIONAL ACTIVITY","bold");return r.length+2+Me(t)<=e?[r.right(e-1,t,"dim")]:[r,j().right(e-1,t,"dim")]}function Ed(t,e,r,n){const s=bo(t,n),o=j();return e.forEach((i,a)=>{a>0&&Ht(o,n),o.text(i.text,i.role)}),e.length===0?[j().text(s)]:Me(s)+2+o.length<=r?[j().text(s).padTo(r-o.length).append(o)]:[j().text(s),o]}function wo(t){return t==="observed"?void 0:"yellow"}function Py(t){return t==="within-retention"||t==="retained-indefinitely"?void 0:"yellow"}function bt(t,e){const r=t.match(/^\[(.+)\]$/);if(!r)return{text:t,pseudo:!1};const n=J(r[1]);return{text:e==="model"||e==="executor"?`${e} ${n}`:n,pseudo:!0}}function _S(t,e=Ad){const r=MS(e.width),{summary:n,availability:s}=t,o=[...Ca("SUMMARY",r.measure),...Ed(t.period,[{text:J(s.observation),role:wo(s.observation)},{text:J(s.retention.state),role:Py(s.retention.state)}],r.measure,e),Ht(j().text(String(n.executions),"bold").text(` ${qe(n.executions,"execution")}`),e).text(String(n.sessions),"bold").text(` ${qe(n.sessions,"session")}`)];for(const i of RS(t,e)){o.push(j(),j().text(i.head,"dim"));const a=Math.max(4,...i.rows.map(c=>c.kind==="model"?(c.tokens??"").length:0));for(const c of i.rows)o.push(...jS(c,r,a,e))}return Ia(o,e)}function MS(t){if(t>=80)return{measure:79,labelMax:22,figureEnd:33,compositeCol:24,tailCol:35,evidenceCol:67,split:!1,stacked:!1};const e=Math.max(1,t-1);if(t>=56)return{measure:e,labelMax:20,figureEnd:29,compositeCol:4,tailCol:31,evidenceCol:43,split:!0,stacked:!1};const r=Math.min(43,Math.max(24,e-12));return{measure:e,labelMax:20,figureEnd:29,compositeCol:4,tailCol:31,evidenceCol:r,split:!0,stacked:!0}}function RS(t,e){const{summary:r,availability:n}=t,s=hn(e).dash,o=(g,v,b,_)=>{const E=ce(v);return E===void 0?{kind:"figure",label:g,figure:s,dash:!0,evidence:v.state}:{kind:"figure",label:g,figure:b(E),dash:!1,tail:_?.(E),evidence:v.state}},i=(g,v)=>({kind:"figure",label:g,figure:String(v),dash:!1}),a=r.executions===0&&n.observation!=="observed"?{head:"RECORDED LIFECYCLE",rows:[{kind:"prose",text:"no execution records; zero work is not established"}]}:{head:n.observation==="observed"?"NOW":"RECORDED LIFECYCLE",rows:[i("running",r.runningNow),o("waiting",r.waitingNow,String),i("idle",r.idleNow)]},c=r.terminalExecutionDuration,u=ce(c),l=u===void 0?{kind:"figure",label:"terminal execution",figure:s,dash:!0,evidence:c.state}:{kind:"composite",label:"terminal execution",evidence:c.state,value:Ht(Ht(j().text("median ").text(yt(u.median),"bold"),e).text("p90 ").text(yt(u.p90),"bold"),e).text("max ").text(yt(u.maximum),"bold")},d=r.usageByModel.map(g=>{const v=ce(g.tokens);return{kind:"model",label:g.model,pseudo:!1,executions:g.executions,tokens:v===void 0?s:It(v),dash:v===void 0,evidence:g.tokens.state}}),m=r.modelMix.filter(g=>bt(g.key,"model").pseudo);if(m.reduce((g,v)=>g+v.executions,0)===r.executionsWithoutModel)for(const g of m)d.push({kind:"model",label:bt(g.key,"model").text,pseudo:!0,executions:g.executions});else r.executionsWithoutModel>0&&d.push({kind:"model",label:"model not observed",pseudo:!0,executions:r.executionsWithoutModel});const h=[a,{head:"OUTCOMES",rows:[o("completed",r.completed,String),o("failed",r.failed,String),o("interrupted",r.interrupted,String)]},{head:"DURATION",rows:[o("time in flight",r.inFlight.totalMs,fe),o("added by open records",r.inFlight.openContributionMs,fe),o("parallel in flight",r.inFlight.parallelMs,fe),o("in-flight peak",r.inFlight.peak,g=>String(g.peak),g=>g.at===null?j():j().text(`at ${Au(g.at,t.period,e)}`)),l,o("terminal interval",r.terminalExecutionIntervalMs,yt),o("terminal overlap",r.overlappingTerminalIntervalMs,yt),o("terminal peak",r.peakTerminalConcurrency,g=>String(g.peak),g=>g.at===null?j():j().text(`at ${Au(g.at,t.period,e)}`))]},{head:"USAGE",rows:[o("tokens",r.tokens,It),o("tool interactions",r.toolInteractions,It),o("tool errors",r.toolErrors,It),o("explicit waits",r.waits,g=>String(g.count),g=>{const v=j().text("for ").text(yt(g.durationMs),"bold");return g.openNow>0?Ht(v,e).text(String(g.openNow),"bold").text(" open"):v})]}];return h.push({head:"INTERVAL POLICY",rows:[{kind:"prose",text:r.inFlight.assumption}]}),d.length>0&&h.push({head:"BY MODEL",rows:d}),h}function jS(t,e,r,n){const s=(o,i)=>i===void 0?o:o.at(e.evidenceCol,J(i),Ze(i));switch(t.kind){case"prose":return cn(j(),2,2,t.text,e.measure);case"figure":{const o=t.dash?void 0:"bold";if(e.stacked){const c=j().at(4,t.figure,o);return t.tail&&t.tail.length>0&&c.text(" ").append(t.tail),[s(j().at(2,t.label),t.evidence),c]}const i=[];let a=j();return t.label.length>e.labelMax?i.push(j().at(2,t.label)):a.at(2,t.label),a.right(e.figureEnd,t.figure,o),t.tail&&t.tail.length>0&&a.at(e.tailCol,"").append(t.tail),i.push(s(a,t.evidence)),i}case"composite":{if(e.split)return[s(j().at(2,t.label),t.evidence),j().at(4,"").append(t.value)];const o=[],i=j();return t.label.length>e.labelMax?o.push(j().at(2,t.label)):i.at(2,t.label),o.push(s(i.at(e.compositeCol,"").append(t.value),t.evidence)),o}case"model":{const o=t.pseudo?"dim":void 0,i=t.tokens===void 0?` ${qe(t.executions,"execution")}`:` ${qe(t.executions,"execution").padEnd(10)}`,a=l=>(l.text(String(t.executions),"bold").text(i),t.tokens===void 0?l:Ht(l,n).text(t.tokens.padStart(r),t.dash?void 0:"bold").text(" tokens"));if(e.split){const l=j().padTo(7-String(t.executions).length);return[s(j().at(2,t.label,o),t.evidence),a(l)]}const c=[],u=j();return t.label.length>e.labelMax?c.push(j().at(2,t.label,o)):u.at(2,t.label,o),u.padTo(e.figureEnd-String(t.executions).length+1),c.push(s(a(u),t.evidence)),c}}}const Qn={"median terminal execution duration":{label:"median terminal duration",duration:!0},"terminal execution interval union":{label:"terminal interval union",duration:!0},"overlapping terminal interval":{label:"overlapping interval",duration:!0},"explicit wait count":{label:"explicit waits"}};function DS(t,e){const r=hn(e).dash,n=[],s=[];for(const u of t.dimensions)if(PS(u)){const l=u.dimension.replace(/ mix$/,"");s.push({head:u.dimension.toUpperCase(),subject:l,a:hp(u.periodA,l),b:hp(u.periodB,l),result:J(u.eligibility)})}else{const l=Qn[u.dimension],d=m=>{const p=ce(m);return typeof p!="number"?{value:r,dash:!0,evidence:m.state}:{value:l?.duration?Su(p):_e(p),dash:!1,evidence:m.state}};n.push({label:l?.label??u.dimension,a:d(u.periodA),b:d(u.periodB),result:J(u.eligibility)})}const o=US(n,s),i=o.measure<=e.width-1?"wide":e.width>=80?"paired":"stacked",a=i==="wide"?o.measure:i==="paired"?79:Math.max(1,e.width-1),c=[...Ca("COMPARISON",a)];return c.push(...mp("A",t.periodA,t.availabilityA.observation,a,e)),c.push(...mp("B",t.periodB,t.availabilityB.observation,a,e)),c.push(j(),...LS(t,a)),c.push(j()),i==="wide"?c.push(...HS(n,s,o,r)):i==="paired"?c.push(...VS(n,s)):c.push(...FS(n,s)),Ia(c,e)}function PS(t){const e=ce(t.periodA)??ce(t.periodB);return t.dimension.endsWith(" mix")||e!==void 0&&typeof e=="object"}function hp(t,e){const r=ce(t);return r===void 0||typeof r=="number"?{evidence:t.state}:{evidence:t.state,items:Object.entries(r).map(([n,s])=>{const o=bt(n,e);return{key:o.text,pseudo:o.pseudo,count:s}})}}function mp(t,e,r,n,s){const o=bo(e,s),i=J(r),a=Math.max(46,3+Me(o)+3),c=j().text(t,"bold").at(3,o);return a+Me(i)<=n?[c.at(a,i,wo(r))]:[c,j().at(3,i,wo(r))]}function LS(t,e){const r=[j().text(J(t.eligibility).toUpperCase(),t.eligibility==="comparable"?"bold":"bold-yellow")];for(const s of t.reasons){const o=s.match(/^period ([AB]): (.*)$/);o?r.push(...cn(j().at(2,o[1],"dim"),5,5,o[2],e)):r.push(...cn(j(),2,2,s,e))}const n=new Map;for(const s of t.dimensions)for(const o of s.reasons){const i=n.get(o)??[];i.push(Qn[s.dimension]?.label??s.dimension),n.set(o,i)}for(const[s,o]of n){const i=o.length===t.dimensions.length?"All dimensions":o.join(", ");r.push(...cn(j(),2,2,`${i}: ${s}.`,e))}return r}function US(t,e){const r=p=>e.flatMap(h=>h[p].items?.map(g=>_e(g.count))??[]),n=(p,h)=>Math.max(h,...p.map(Me)),s=n([...t.map(p=>p.a.value),...r("a")],13),o=n([...t.map(p=>p.b.value),...r("b")],13),i=n([...t.flatMap(p=>[J(p.a.evidence),J(p.b.evidence)]),...e.flatMap(p=>[J(p.a.evidence),J(p.b.evidence)])],12),a=29+s-1,c=a+3,u=c+i+2+o,l=u+3,d=l+i+3,m=n([...t.map(p=>p.result),...e.map(p=>p.result)],0);return{measure:d+m,aEnd:a,aEvidence:c,bEnd:u,bEvidence:l,result:d}}function Pi(t){return t.dash?void 0:"bold"}function ku(t,e,r,n){return Me(t)>e?{lead:[j().at(r,t,n)],row:j()}:{lead:[],row:j().at(r,t,n)}}function HS(t,e,r,n){const s=[j().text("MEASURE","dim").right(r.aEnd,"A","dim").right(r.bEnd,"B","dim").at(r.result,"COMPARISON","dim")];for(const o of t){const{lead:i,row:a}=ku(o.label,25,2);s.push(...i,a.right(r.aEnd,o.a.value,Pi(o.a)).at(r.aEvidence,J(o.a.evidence),Ze(o.a.evidence)).right(r.bEnd,o.b.value,Pi(o.b)).at(r.bEvidence,J(o.b.evidence),Ze(o.b.evidence)).at(r.result,o.result))}for(const o of e){s.push(j(),j().text(o.head,"dim").at(r.aEvidence,J(o.a.evidence),Ze(o.a.evidence)).at(r.bEvidence,J(o.b.evidence),Ze(o.b.evidence)).at(r.result,o.result));const i=new Map;for(const a of o.a.items??[])i.set(a.key,{pseudo:a.pseudo,a:a.count});for(const a of o.b.items??[])i.set(a.key,{...i.get(a.key),pseudo:a.pseudo,b:a.count});for(const[a,c]of i){const{lead:u,row:l}=ku(a,25,2,c.pseudo?"dim":void 0);o.a.items&&l.right(r.aEnd,c.a===void 0?n:_e(c.a),c.a===void 0?void 0:"bold"),o.b.items&&l.right(r.bEnd,c.b===void 0?n:_e(c.b),c.b===void 0?void 0:"bold"),s.push(...u,l)}}return s}function VS(t,e){const r=[j().text("MEASURES","dim").right(78,"COMPARISON","dim")],n=(s,o,i,a)=>s.at(i,o,"dim").right(i+15,a.value,Pi(a)).at(i+18,J(a.evidence),Ze(a.evidence));for(const s of t)r.push(j().at(2,s.label).right(78,s.result)),r.push(n(n(j(),"A",4,s.a),"B",40,s.b));for(const s of e)r.push(j(),j().text(s.head,"dim").right(78,s.result)),r.push(...Ly(s,29));return r}function FS(t,e){const r=[j().text("MEASURES","dim")],n=(s,o)=>j().at(4,s,"dim").right(28,o.value,Pi(o)).at(31,J(o.evidence),Ze(o.evidence));t.forEach((s,o)=>{o>0&&r.push(j()),r.push(j().at(2,s.label),n("A",s.a),n("B",s.b),j().at(4,"comparison","dim").at(16,s.result))});for(const s of e)r.push(j(),j().text(s.head,"dim"),...Ly(s,28)),r.push(j().at(2,"comparison","dim").at(16,s.result));return r}function Ly(t,e){const r=[];for(const[n,s]of[["A",t.a],["B",t.b]]){r.push(j().at(2,n,"dim").at(5,J(s.evidence),Ze(s.evidence)));for(const o of s.items??[]){const{lead:i,row:a}=ku(o.key,e-5-1-Me(_e(o.count)),5,o.pseudo?"dim":void 0);r.push(...i,a.right(e,_e(o.count),"bold"))}}return r}const WS=["summary","availability","compare","breakdown"];function sr(t,e,r=Ad){switch(t.operation){case"summary":return _S(t.result,r);case"availability":return KS(t.result,r);case"compare":return DS(t.result,r);case"breakdown":return GS(t.result,e,r)}}const Uy={"tool-interactions":"tool interactions","tool-errors":"tool errors"};function KS(t,e){const r=e.width>=80,n=e.width<56,s=r?79:Math.max(1,e.width-1),o=25,i=[...Ca("AVAILABILITY",s),...Ed(t.period,[],s,e)],a=(m,p)=>n?[j().at(2,m),j().padTo(4).append(p)]:[j().at(2,m).padTo(o).append(p)],c=(m,p)=>j().text(m,p),u=m=>i.push(j(),j().text(m,"dim"));u("OBSERVATION"),i.push(...a("state",c(J(t.observation),wo(t.observation))),...a("records",Ht(j().text(String(t.executionRecords),"bold").text(` ${qe(t.executionRecords,"execution")}`),e).text(String(t.sessionRecords),"bold").text(` ${qe(t.sessionRecords,"session")}`)),...a("continuity",c(J(t.continuity.state),Ze(t.continuity.state))),...a("observation gaps",c(J(t.observationGaps.state),Ze(t.observationGaps.state))),...a("unprojected work",c(J(t.unprojectedSourceWork.state),Ze(t.unprojectedSourceWork.state)))),u("RETENTION"),i.push(...a("state",c(J(t.retention.state),Py(t.retention.state)))),t.retention.semanticFrom!==null&&i.push(...a("semantic history from",c(kd(t.retention.semanticFrom,e),"bold")));const l=t.bounds;if(s>=51)i.push(j(),j().text("BOUNDS","dim").right(32,"observed","dim").right(42,"inferred","dim").right(50,"open","dim"),j().at(2,"starts").right(32,String(l.observedStarts),"bold").right(42,String(l.inferredStarts),"bold"),j().at(2,"ends").right(32,String(l.observedEnds),"bold").right(42,String(l.inferredEnds),"bold").right(50,String(l.openEnds),"bold"));else{const m=p=>{const h=j().padTo(4);return p.forEach(([g,v],b)=>{b>0&&Ht(h,e),h.text(String(g),"bold").text(` ${v}`)}),h};u("BOUNDS"),i.push(j().at(2,"starts"),m([[l.observedStarts,"observed"],[l.inferredStarts,"inferred"]]),j().at(2,"ends"),m([[l.observedEnds,"observed"],[l.inferredEnds,"inferred"],[l.openEnds,"open"]]))}u("COMPARISON");const d=t.comparisonReadiness==="comparable"?void 0:"yellow";i.push(...a("readiness",c(J(t.comparisonReadiness),d))),t.reasons.forEach((m,p)=>{const h=p===0?"because":"";n?(h&&i.push(j().at(2,h)),i.push(...cn(j(),4,4,m,s))):i.push(...cn(j().at(2,h),o,o,m,s))}),i.push(j()),r?i.push(j().text("MEASURES","dim").at(21,"state","dim").at(35,"coverage","dim").right(78,"records","dim")):i.push(j().text("MEASURES","dim").at(o,"state","dim").right(s-1,"records","dim"));for(const m of t.measures){const p=Uy[m.dimension]??J(m.dimension),h=J(m.state),g=j().text("/","dim").text(" ").text(String(m.coverage.records),"bold");if(r){const v=j().at(2,p).at(21,h,Ze(m.state));i.push(...yp(v,35,78,m.coverage,g,e))}else i.push(j().at(2,p).at(o,h,Ze(m.state))),i.push(...yp(j(),4,s-1,m.coverage,g,e))}u("SOURCES"),t.sources.length===0&&i.push(j().at(2,"none observed"));for(const m of t.sources){const p=String(m.executionRecords),h=`execution ${qe(m.executionRecords,"record")}`;if(29+Me(h)>s){i.push(j().at(2,m.source),j().at(4,p,"bold").text(` ${h}`));continue}const g=v=>v.right(27,p,"bold").at(29,h);Me(m.source)>22?i.push(j().at(2,m.source),g(j())):i.push(g(j().at(2,m.source)))}return Ia(i,e)}function yp(t,e,r,n,s,o){const a=[[n.observed,"observed"],[n.inferred,"inferred"],[n.partial,"partial"],[n.notObserved,"not-observed"],[n.unsupported,"unsupported"],[n.unknown,"unknown"]].filter(([m])=>m>0).map(([m,p])=>j().text(String(m),"bold").text(" ").text(J(p),Ze(p))),c=hn(o).sep,u=r-s.length,l=[[]];let d=e;for(const m of a){const p=l[l.length-1],h=d+(p.length>0?c.length:0)+m.length;p.length>0&&h>u?(l.push([m]),d=e+m.length):(p.push(m),d=h)}return l.map((m,p)=>{const h=p===0?t.padTo(e):j().padTo(e);if(m.forEach((g,v)=>{v>0&&Ht(h,o),h.append(g)}),p<l.length-1){const g=c.trim();return h.text(c.slice(0,c.indexOf(g))).text(g,"dim"),h}return h.padTo(r-s.length+1).append(s)})}function GS(t,e,r){const n=hn(r).dash,s=l=>{const d=ce(l);return d===void 0?{value:n,dash:!0,evidence:l.state}:{value:_e(d),dash:!1,evidence:l.state}},o=t.items.filter(l=>e===void 0||l.key===e).map(l=>{const d=bt(l.key,t.dimension),m=ce(l.terminalDuration);return{key:d.text,pseudo:d.pseudo,executions:_e(l.executions),singular:l.executions===1,terminal:_e(l.terminalExecutions),median:m===void 0?n:Dy(m.median),medianDash:m===void 0,tokens:s(l.tokens),tools:s(l.toolInteractions),errors:s(l.toolErrors),failed:s(l.failed)}}),i=qS(o,t.dimension),a=o.length>0&&i.measure<=r.width-1?"table":r.width>=80?"records":"narrow",c=a==="table"?i.measure:a==="records"?79:Math.max(1,r.width-1),u=[...Ca(`BREAKDOWN${hn(r).sep}${J(t.dimension).toUpperCase()}`,c),...Ed(t.period,[{text:J(t.availability.observation),role:wo(t.availability.observation)}],c,r),j()];if(o.length===0)u.push(j().text("none observed"));else if(a==="table")u.push(...i.lines);else{const l=a==="records"?zS(o):null;o.forEach((d,m)=>{m>0&&u.push(j()),u.push(...l?YS(d,l,r):XS(d,o,r))})}return u.push(j(),...cn(j(),0,0,t.qualification,c,"dim")),Ia(u,r)}function Li(t){return t.pseudo?"dim":"bold"}function Ui(t,e,r){return r.evidence===void 0?t:t.at(e,J(r.evidence),Ze(r.evidence))}function qS(t,e){const r=J(e).toUpperCase(),n=[{caption:"EXECUTIONS",value:m=>m.executions},{caption:"TERMINAL",value:m=>m.terminal},{caption:"MEDIAN",value:m=>m.median}],s=[{caption:"TOKENS",value:m=>m.tokens},{caption:"TOOLS",value:m=>m.tools},{caption:"ERRORS",value:m=>m.errors},{caption:"FAILED",value:m=>m.failed}],o=m=>Math.max(0,...m.map(Me));let i=Math.max(Me(r),o(t.map(m=>m.key))),a=Me(r)-1;const c=n.map(m=>{const p=i+2+Math.max(Me(m.caption),o(t.map(m.value)))-1;return i=p+1,a=p,p}),u=s.map(m=>{const p=t.map(m.value);let h=i+2+o(p.map(g=>g.value))-1;return h=Math.max(h,a+2+Me(m.caption)),i=h+3+o(p.map(g=>J(g.evidence??""))),a=h,h}),l=j().text(r,"dim");n.forEach((m,p)=>l.right(c[p],m.caption,"dim")),s.forEach((m,p)=>l.right(u[p],m.caption,"dim"));const d=[l];for(const m of t){const p=j().text(m.key,Li(m));n.forEach((h,g)=>p.right(c[g],h.value(m),"bold")),s.forEach((h,g)=>{const v=h.value(m);Ui(p.right(u[g],v.value,v.dash?void 0:"bold"),u[g]+3,v)}),d.push(p)}return{measure:i,lines:d}}function Hy(t){const e=r=>Math.max(3,...t.map(n=>Me(r(n))));return{countWidth:e(r=>r.executions),terminalWidth:e(r=>r.terminal),medianWidth:e(r=>r.median)}}function zS(t){const e=s=>Math.max(1,...t.flatMap(o=>s(o).map(i=>Me(i.value)))),r=Math.max(24,10+e(s=>[s.tokens,s.errors])-1),n=Math.max(44,r+3+12+2);return{...Hy(t),countEnd:34,leftEnd:r,rightLabel:n,rightEnd:Math.max(61,n+6+2+e(s=>[s.tools,s.failed])-1)}}function Vy(t,e,r,n){return t.text(e.executions.padStart(r.countWidth),"bold").text(` ${(e.singular?"execution":"executions").padEnd(10)}`),Ht(t,n).text(e.terminal.padStart(r.terminalWidth),"bold").text(" terminal"),Ht(t,n).text("median "),t.text(e.median.padStart(r.medianWidth),e.medianDash?void 0:"bold")}function YS(t,e,r){const n=[],s=e.countEnd-e.countWidth+1,o=j();Me(t.key)>=s?n.push(j().text(t.key,Li(t))):o.text(t.key,Li(t)),n.push(Vy(o.padTo(s),t,e,r));const i=(a,c,u,l)=>{const d=j().at(2,a);return Ui(d.right(e.leftEnd,c.value,c.dash?void 0:"bold"),e.leftEnd+3,c),d.at(e.rightLabel,u),Ui(d.right(e.rightEnd,l.value,l.dash?void 0:"bold"),e.rightEnd+3,l)};return n.push(i("tokens",t.tokens,"tools",t.tools),i("errors",t.errors,"failed",t.failed)),n}function XS(t,e,r){const n=Math.max(1,...e.flatMap(i=>[i.tokens,i.tools,i.errors,i.failed].map(a=>Me(a.value)))),s=Math.max(24,10+n-1),o=(i,a)=>Ui(j().at(2,i).right(s,a.value,a.dash?void 0:"bold"),s+3,a);return[j().text(t.key,Li(t)),Vy(j().padTo(2),t,Hy(e),r),o("tokens",t.tokens),o("tools",t.tools),o("errors",t.errors),o("failed",t.failed)]}const gp=["summary","availability","compare","breakdown"],vp=["lifecycle","duration","tokens","waits","errors"],bp=["model","executor"],wp=["today","last-7d"];function JS(t){const e=gp.find(a=>a===t.query),r=wp.find(a=>a===(t.scope??"today"));if(!e)return{error:`query must be one of ${gp.join(", ")}`};if(!r)return{error:`scope must be one of ${wp.join(", ")}`};const n=t.focus?vp.find(a=>a===t.focus):void 0,s=t.by?bp.find(a=>a===t.by):void 0;if(t.focus&&!n)return{error:`focus must be one of ${vp.join(", ")}`};if(t.by&&!s)return{error:`by must be one of ${bp.join(", ")}`};if(!{summary:[void 0,"lifecycle","duration"],availability:[void 0,"tokens","waits"],breakdown:[void 0,"errors"],compare:[void 0]}[e].includes(n))return{error:`${e} has no ${n} reading`};if(e==="breakdown"&&!s)return{error:"breakdown needs by=model|executor"};if(e!=="breakdown"&&s)return{error:`${e} takes no dimension`};if(n==="errors"&&s!=="model")return{error:"errors are read by model"};const i={query:e,scope:r};return n&&(i.focus=n),s&&(i.by=s),i}function Eu(t,e){if(t==="last-7d")return{from:e-7*864e5,to:e};const r=new Date(e);return r.setHours(0,0,0,0),{from:r.getTime(),to:e}}function xd(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function Fy(t,e){const r=n=>{const s=new Date(n);return s.setDate(s.getDate()-e),s.getTime()};return{from:r(t.from),to:r(t.to)}}function ZS(t,e,r,n={}){const s=n.period??Eu(e.scope,r),o={};switch(e.query){case"summary":o.summary=t.summary(s);break;case"availability":e.focus&&(o.summary=t.summary(s)),o.availability=o.summary?.availability??t.availability(s);break;case"breakdown":o.breakdown=t.breakdown(s,e.by??"model"),e.focus==="errors"&&(o.summary=t.summary(s));break;case"compare":o.comparison=t.compare(s,xd(s));break}return Wy(e,o,n)}function Wy(t,e,r={}){const n=QS(t,e,r);return r.projectKey!==void 0&&(n.observation.unshift({k:"WORKING CONTEXT",v:"Selected working context only; the same filter applies to every period."}),n.command="No equivalent CLI command for this working-context selection.",n.text=`SELECTED WORKING CONTEXT ONLY — filtered before aggregation.
14
14
 
15
- `+n.text),r.period&&(n.title="SELECTED PERIOD",n.command="Selected historical bounds; use the period controls to reproduce this reading."),n}function MA(t,e,r){const n={...ad,timeZone:r.timeZone};switch(t.query){case"summary":{const o=qr(e.summary,"summary");return t.focus==="duration"?DA(t,o,r,n):t.focus==="lifecycle"?jA(t,o,r,n):_A(t,o,r,n)}case"availability":{const o=qr(e.availability,"availability");return t.focus==="tokens"?PA(t,qr(e.summary,"summary"),r,n):t.focus==="waits"?UA(t,qr(e.summary,"summary"),r,n):LA(t,o,r,n)}case"breakdown":{const o=qr(e.breakdown,"breakdown");return t.focus==="errors"?HA(t,o,qr(e.summary,"summary"),r,n):VA(t,o,r,n)}case"compare":return FA(t,qr(e.comparison,"comparison"),n)}}function _A(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"SUMMARY",s,!0,r,n),a=tr({operation:"summary",result:e},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=[Cy(e)],u=ce(o.completed),d=ce(o.failed);u!==void 0&&d!==void 0&&c.push(`${u} completed and ${d} failed${jy([o.completed,o.failed])}.`);const l=cn(s,"waits");l&&Jn(l.coverage,"unsupported")&&c.push(`Waits are unsupported for all ${o.executions}.`);const m=[...i.observation,ya(s)],p=zA(s);return p&&m.push(p),m.push({k:"ENDS",v:Ry(s)}),{...i,finding:c.join(" "),observation:m,evidence:[...Ny(e,"lifecycle",t),De("completed",o.completed,String,Ce(t,"summary","lifecycle")),De("failed",o.failed,String,Ce(t,"summary","lifecycle")),De("interrupted",o.interrupted,String,Ce(t,"summary","lifecycle")),De("terminal interval",o.terminalExecutionIntervalMs,mt,Ce(t,"summary","duration")),De("overlapping interval",o.overlappingTerminalIntervalMs,mt,Ce(t,"summary","duration")),De("tokens",o.tokens,Et,Ce(t,"availability","tokens")),De("tool interactions",o.toolInteractions,Et,Ce(t,"breakdown","errors")),De("tool errors",o.toolErrors,Et,Ce(t,"breakdown","errors")),Ty(e,Ce(t,"availability","waits"))],command:rr("summary",t.scope),text:a}}function jA(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"SUMMARY · LIFECYCLE",s,!0,r,n),a=tr({operation:"summary",result:e},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=[Cy(e)],u=[o.completed,o.failed,o.interrupted],[d,l,m]=u.map(I=>ce(I));d!==void 0&&l!==void 0&&m!==void 0&&c.push(`${d} completed, ${l} failed and ${m} interrupted${jy(u)}.`),Jn(o.waitingNow.coverage,"unsupported")&&c.push(`Waiting is unsupported for all ${o.executions}.`);const p=cn(s,"outcomes"),h=[...i.observation];p&&h.push({k:"OUTCOMES",v:ps(p.state,p.coverage)}),h.push({k:"ENDS",v:Ry(s)});const v=o.terminalExecutionDuration,g=ce(v);return{...i,finding:c.join(" "),observation:h,evidence:[...Ny(e,void 0,t),De("completed",o.completed,String),De("failed",o.failed,String),De("interrupted",o.interrupted,String),{k:"terminal execution",...g?{t:_y(g)}:{},v:g?"":"—",e:J(v.state),focus:Ce(t,"summary","duration")}],command:rr("summary",t.scope),text:a}}function DA(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"SUMMARY · DURATION",s,!0,r,n),a=tr({operation:"summary",result:e},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=ce(o.inFlight.totalMs),u=ce(o.terminalExecutionIntervalMs),d=ce(o.inFlight.openContributionMs),l=ce(o.inFlight.parallelMs),m=ce(o.inFlight.peak),p=[];c!==void 0&&u!==void 0&&d!==void 0&&l!==void 0&&(p.push(`Recorded intervals cover ${fe(c)} — the TIME IN FLIGHT estimate.`),p.push(`Ended runs cover ${fe(u)}; open records add ${fe(d)} after overlaps are removed.`),p.push(`Parallel intervals overlap for ${fe(l)}.`));const h=[...i.observation];s.bounds.openEnds>0&&h.push({k:"OPEN ENDS",v:`${s.bounds.openEnds} of ${o.executions} executions ${s.bounds.openEnds===1?"has":"have"} no observed end`}),s.continuity.state!=="observed"&&h.push(ya(s)),h.push({k:"INTERVAL POLICY",v:o.inFlight.assumption}),h.push({k:"ROUNDING",v:"Durations are rounded independently; displayed parts may differ from their total by a minute."});const v=o.terminalExecutionDuration,g=ce(v);return{...i,finding:p.join(" "),observation:h,evidence:[De("time in flight",o.inFlight.totalMs,fe),De("ended interval union",o.terminalExecutionIntervalMs,fe),De("added by open records",o.inFlight.openContributionMs,fe),De("overlapping interval",o.inFlight.parallelMs,fe),{...De("peak concurrency",o.inFlight.peak,I=>String(I.peak)),...m&&m.at!==null?{t:`at ${au(m.at,e.period,n)}`}:{}},{k:"terminal execution",...g?{t:_y(g)}:{},v:g?"":"—",e:J(v.state)},{k:"executions",v:String(o.executions),e:"",focus:Ce(t,"summary","lifecycle")},{k:"sessions",v:String(o.sessions),e:"",focus:Ce(t,"summary","lifecycle")}],command:rr("summary",t.scope),text:a}}function Cy(t){const{summary:e}=t,r=ce(e.waitingNow),n=[e.runningNow>0?`${e.runningNow} running`:void 0,r!==void 0&&r>0?`${r} waiting`:void 0,e.idleNow>0?`${e.idleNow} idle`:void 0].filter(s=>s!==void 0),o=`${e.executions} ${Ke(e.executions,"execution")} across ${e.sessions} ${Ke(e.sessions,"session")}`;return n.length>0?`${o}; ${Zn(n)}.`:`${o}.`}function Ny(t,e,r){const{summary:n}=t,o=e?Ce(r,"summary",e):void 0,s=(i,a)=>({k:i,v:String(a),e:"",...o?{focus:o}:{}});return[s("executions",n.executions),s("sessions",n.sessions),s("running",n.runningNow),De("waiting",n.waitingNow,String,o),s("idle",n.idleNow)]}function Ty(t,e){const r=t.summary.waits,n=ce(r);return{k:"explicit waits",...n?{t:`for ${mt(n.durationMs)}${n.openNow>0?` · ${n.openNow} open`:""}`}:{},v:n?String(n.count):"—",e:J(r.state),...e?{focus:e}:{}}}function LA(t,e,r,n){const o=Hr(t,"AVAILABILITY",e,!1,r,n),s=tr({operation:"availability",result:e},void 0,n),i=e.executionRecords;if(Ar(e))return Fr(o,e,s,n);const a=[],c=[e.continuity.state==="unknown"?"Continuity":void 0,e.observationGaps.state==="unknown"?"gaps":void 0,e.unprojectedSourceWork.state==="unknown"?"unprojected work":void 0].filter(l=>l!==void 0);if(c.length>0){const l=Zn(c);a.push(`${l[0].toUpperCase()}${l.slice(1)} ${c.length===1?"is":"are"} unknown.`)}if(i===0)a.push("No execution records, so no measure has coverage to report.");else{const l=e.measures.filter(p=>Jn(p.coverage,"unsupported"));if(l.length>0){const p=Zn(l.map(h=>$c(h.dimension)));a.push(`${p[0].toUpperCase()}${p.slice(1)} ${l.length===1?"is":"are"} unsupported for all ${i}.`)}const m=[...e.measures].filter(p=>!Jn(p.coverage,"unsupported")&&p.coverage.notObserved>0).sort((p,h)=>h.coverage.notObserved-p.coverage.notObserved)[0];m&&a.push(`The ${$c(m.dimension)} is not observed for ${m.coverage.notObserved} of ${i}.`)}const u=[...o.observation,{k:"RETENTION",v:My(e,n)},{k:"COMPARISON",v:J(e.comparisonReadiness)}],d=[{k:"continuity",v:J(e.continuity.state),e:""},{k:"observation gaps",v:J(e.observationGaps.state),e:""},{k:"unprojected work",v:J(e.unprojectedSourceWork.state),e:""},{k:"execution records",v:String(i),e:""},...e.measures.map(l=>{const m=KA(t,l.dimension);return{k:$c(l.dimension),...l.coverage.records>0?{t:By(l.coverage)}:{},v:"",e:J(l.state),...m?{focus:m}:{}}})];return{...o,finding:a.join(" ")||void 0,observation:u,evidenceCaption:"COVERAGE",evidence:d,command:rr("availability",t.scope),text:s}}function PA(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"AVAILABILITY · TOKENS",s,!1,r,n),a=tr({operation:"availability",result:s},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=cn(s,"tokens"),u=cn(s,"model"),d=ce(o.tokens),l=[];if(d!==void 0&&c){const p=c.coverage,h=[p.inferred>0?`${p.inferred} ${p.inferred===1?"is":"are"} inferred`:void 0,p.partial>0?`${p.partial} ${p.partial===1?"is":"are"} partial`:void 0,p.notObserved>0?`${p.notObserved} ${p.notObserved===1?"was":"were"} not observed`:void 0,p.unsupported>0?`${p.unsupported} ${p.unsupported===1?"is":"are"} unsupported`:void 0,p.unknown>0?`${p.unknown} ${p.unknown===1?"is":"are"} unknown`:void 0].filter(v=>v!==void 0);l.push(h.length===0?`${Et(d)} is fully observed for all ${p.records} executions.`:`${Et(d)} is fully observed for ${p.observed} of ${p.records} executions; ${Zn(h)}.`)}else l.push(`Tokens are ${J(o.tokens.state)} for this period.`);o.executionsWithoutModel>0&&l.push(`${o.executionsWithoutModel} ${Ke(o.executionsWithoutModel,"execution")} carry no observed model, so it cannot be divided completely by model.`);const m=[...i.observation];return c&&m.push({k:"TOKENS",v:ps(c.state,c.coverage)}),u&&m.push({k:"MODEL",v:ps(u.state,u.coverage)}),m.push(ya(s)),{...i,finding:l.join(" "),observation:m,evidence:[De("tokens",o.tokens,Et),...WA(e)],command:rr("availability",t.scope),text:a}}function UA(t,e,r,n){const{summary:o,availability:s}=e,i=Hr(t,"AVAILABILITY · WAITS",s,!1,r,n),a=tr({operation:"availability",result:s},void 0,n);if(o.executions===0||Ar(s))return Fr(i,s,a,n);const c=cn(s,"waits"),u=o.executions,d=ce(o.waits);let l,m;const p=c&&(Jn(c.coverage,"unsupported")||Jn(c.coverage,"notObserved"));!d||p?(l="NOT OBSERVED",m=`Wait behaviour is ${J(o.waits.state)} for all ${u} executions in this period, so time blocked on a person cannot be read from it.`):(m=`${d.count} explicit ${Ke(d.count,"wait")} for ${mt(d.durationMs)}${d.openNow>0?`, ${d.openNow} open now`:""}.`,c&&c.coverage.unsupported>0&&(m+=` Waits are unsupported for ${c.coverage.unsupported} of ${u} executions.`));const h=[...i.observation];return c&&h.push({k:"WAITS",v:ps(c.state,c.coverage)}),h.push({k:"SOURCES",v:s.sources.map(v=>`${v.source} ${v.executionRecords}`).join(" · ")}),{...i,...l?{verdict:l}:{},finding:m,observation:h,evidence:[Ty(e),{...De("waiting",o.waitingNow,String),t:"recorded lifecycle"},{k:"executions",v:String(u),e:""}],command:rr("availability",t.scope),text:a}}function VA(t,e,r,n){const o=t.by??"model",s=Hr(t,`BREAKDOWN · ${o.toUpperCase()}`,e.availability,!1,r,n),i=tr({operation:"breakdown",result:e},void 0,n),a=e.availability.executionRecords;if(a===0||Ar(e.availability))return Fr(s,e.availability,i,n);const c=e.items.filter(p=>!bt(p.key,o).pseudo),u=e.items.filter(p=>bt(p.key,o).pseudo),d=[];if(o==="executor")d.push(`${Zn(c.map(p=>`${p.key} ${p.executions}`))} execution ${Ke(c.reduce((p,h)=>p+h.executions,0),"record")}.`);else if(c[0]){const p=c[0],h=ce(p.tokens);d.push(`${p.key} accounts for ${p.executions} of ${a} executions${h!==void 0?` and ${Te(h)} tokens`:""}.`)}for(const p of u)d.push(`${p.executions} ${Ke(p.executions,"execution")} ${p.executions===1?"carries":"carry"} ${YA(p.key,o)}.`);const l=cn(e.availability,o),m=[...s.observation];return l&&m.push({k:o.toUpperCase(),v:ps(l.state,l.coverage)}),m.push({k:"CAUSALITY",v:"grouped records; not a causal performance difference"}),{...s,finding:d.join(" "),observation:m,evidenceCaption:"TOKENS",evidence:e.items.map(p=>{const h=ce(p.terminalDuration),v=ce(p.tokens);return{k:bt(p.key,o).text,t:`${Te(p.executions)} ${Ke(p.executions,"execution")}${h?` · median ${wy(h.median)}`:""}`,v:v===void 0?"—":Te(v),e:J(p.tokens.state)}}),command:rr("breakdown",t.scope,o),text:i}}function HA(t,e,r,n,o){const s=Hr(t,"BREAKDOWN · MODEL · ERRORS",e.availability,!1,n,o),i=tr({operation:"breakdown",result:e},void 0,o);if(e.availability.executionRecords===0||Ar(e.availability))return Fr(s,e.availability,i,o);const a=[...e.items].sort((v,g)=>(ce(g.toolErrors)??-1)-(ce(v.toolErrors)??-1)||g.executions-v.executions),c=ce(r.summary.toolErrors),u=a.filter(v=>!bt(v.key,"model").pseudo&&ce(v.toolErrors)!==void 0),d=[],l=v=>{const g=ce(v.toolInteractions);return g===void 0?"":`, across ${Te(g)} tool interactions`};if(c===void 0)d.push(`Tool errors are ${J(r.summary.toolErrors.state)} for this period.`);else if(c===0)d.push("No tool errors were recorded.");else if(u[0]){const[v,g]=u,I=ce(v.toolErrors)??0;if(d.push(I*2>c?`Tool errors are concentrated in ${v.key}: ${Te(I)} of ${Te(c)} recorded errors${l(v)}.`:`Tool errors are spread across models: ${v.key} recorded ${Te(I)} of ${Te(c)}${l(v)}.`),g){const N=ce(g.toolInteractions);d.push(`${g.key} recorded ${Te(ce(g.toolErrors)??0)}${N===void 0?"":` across ${Te(N)}`}.`)}}const m=[...s.observation],p=e.items.filter(v=>v.toolErrors.state==="unsupported").map(v=>bt(v.key,"model").text);p.length>0&&m.push({k:"ERRORS",v:`unsupported for ${Zn(p)}`}),m.push({k:"CAUSALITY",v:"grouped records; not a causal performance difference"});const h=(v,g)=>{const I=ce(v),N=ce(g);return`${I===void 0?"—":Te(I)} / ${N===void 0?"—":Te(N)}`};return{...s,finding:d.join(" "),observation:m,evidenceCaption:"ERRORS / TOOLS",evidence:[{k:"all executions",v:h(r.summary.toolErrors,r.summary.toolInteractions),e:J(r.summary.toolErrors.state)},...a.map(v=>({k:bt(v.key,"model").text,v:h(v.toolErrors,v.toolInteractions),e:J(v.toolErrors.state)}))],command:rr("breakdown",t.scope,"model"),text:i}}function FA(t,e,r){const n=[{k:"A",w:ds(e.periodA,r),s:J(e.availabilityA.observation)},{k:"B",w:ds(e.periodB,r),s:J(e.availabilityB.observation)}],o=[...e.availabilityA.reasons.map(l=>({k:"A",v:l})),...e.availabilityB.reasons.map(l=>({k:"B",v:l})),...e.reasons.filter(l=>!l.startsWith("period A: ")&&!l.startsWith("period B: ")).map(l=>({k:"",v:l}))],s=e.dimensions.filter(l=>!l.dimension.endsWith(" mix")),i=new Set(e.dimensions.flatMap(l=>l.reasons)),c=[{k:"DIMENSIONS",v:e.dimensions.every(l=>l.eligibility===e.eligibility)&&i.size===1?`all — ${[...i][0]}`:["comparable","partially-comparable","not-comparable"].map(l=>[e.dimensions.filter(m=>m.eligibility===l).length,J(l)]).filter(([l])=>l>0).map(([l,m])=>`${l} ${m}`).join(" · ")}],u=(l,m)=>{const p=ce(m);return typeof p!="number"?"—":Kn[l]?.duration?iu(p):Te(p)},d=(l,m)=>{const p=ce(m);return typeof p!="number"?"—":Kn[l]?.duration?iu(p):Et(p)};return{request:t,title:$y(t.scope),resolution:`COMPARISON · AGAINST PREVIOUS${t.scope==="last-7d"?" 7D":""}`,periods:n,partial:e.availabilityA.observation!=="observed"||e.availabilityB.observation!=="observed",verdict:J(e.eligibility).toUpperCase(),reasons:o,observation:c,evidenceCaption:"A · B",evidence:s.map(l=>{const m=GA(t,l.dimension);return{k:Kn[l.dimension]?.label??l.dimension,t:`B ${u(l.dimension,l.periodB)} ${J(l.periodB.state)}`,v:u(l.dimension,l.periodA),e:J(l.periodA.state),comparison:{a:u(l.dimension,l.periodA),b:u(l.dimension,l.periodB),aCompact:d(l.dimension,l.periodA),bCompact:d(l.dimension,l.periodB),aEvidence:J(l.periodA.state),bEvidence:J(l.periodB.state),eligibility:J(l.eligibility),reasons:l.reasons},...m?{focus:m}:{}}}),command:rr("compare",t.scope),text:tr({operation:"compare",result:e},void 0,r)}}function Hr(t,e,r,n,o,s){const i=[J(r.observation),...n?[J(r.retention.state)]:[]].join(" · "),a=[],c=$y(t.scope);return o.view&&o.view!==c&&a.push({k:"PERIOD",v:`${c.toLowerCase()}, as asked · the view is showing ${o.view.toLowerCase()}`}),{request:t,title:c,resolution:e,window:ds(r.period,s),qualification:i,partial:r.observation!=="observed",reasons:[],observation:a}}function Fr(t,e,r,n){const o=t.request,s=rr(o.query,o.scope,o.by);if(Ar(e)){const i=e.retention.semanticFrom;return{...t,verdict:"OUTSIDE RETENTION",finding:i===null?"This period precedes semantic history.":`Semantic history starts at ${cd(i,n)}; this period precedes it.`,observation:[...t.observation,{k:"RETENTION",v:My(e,n)}],evidence:[],command:s,text:r}}return{...t,finding:"No execution records. A quiet period cannot be told from an unobserved one, so zero work is not established.",observation:[...t.observation,ya(e)],evidence:[{k:"execution records",v:"0",e:""}],command:s,text:r}}function WA(t){const{summary:e}=t,r=e.usageByModel.map(o=>{const s=ce(o.tokens);return{k:o.model,t:`${o.executions} ${Ke(o.executions,"execution")}`,v:s===void 0?"—":Et(s),e:J(o.tokens.state)}}),n=e.modelMix.filter(o=>bt(o.key,"model").pseudo);if(n.reduce((o,s)=>o+s.executions,0)===e.executionsWithoutModel)for(const o of n)r.push({k:bt(o.key,"model").text,t:`${o.executions} ${Ke(o.executions,"execution")}`,v:"",e:""});else e.executionsWithoutModel>0&&r.push({k:"model not observed",t:`${e.executionsWithoutModel} ${Ke(e.executionsWithoutModel,"execution")}`,v:"",e:""});return r}function De(t,e,r,n){const o=ce(e);return{k:t,v:o===void 0?"—":r(o),e:J(e.state),...n?{focus:n}:{}}}function Ce(t,e,r){const n=e==="breakdown"?{query:e,scope:t.scope,focus:r,by:"model"}:{query:e,scope:t.scope,focus:r};return qA(n,t)?void 0:n}function KA(t,e){switch(e){case"tokens":return Ce(t,"availability","tokens");case"waits":return Ce(t,"availability","waits");case"tool-errors":case"tool-interactions":return Ce(t,"breakdown","errors");case"outcomes":return Ce(t,"summary","lifecycle");case"bounds":return Ce(t,"summary","duration");case"model":return{query:"breakdown",scope:t.scope,by:"model"};case"executor":return{query:"breakdown",scope:t.scope,by:"executor"}}}function GA(t,e){return e==="tokens"?Ce(t,"availability","tokens"):e==="explicit wait count"?Ce(t,"availability","waits"):e==="tool interactions"||e==="tool errors"?Ce(t,"breakdown","errors"):Kn[e]?.duration||e==="peak terminal concurrency"?Ce(t,"summary","duration"):Ce(t,"summary","lifecycle")}function qA(t,e){return t.query===e.query&&t.scope===e.scope&&t.focus===e.focus&&t.by===e.by}function rr(t,e,r){const n=e==="last-7d"?" --last 7d":"";switch(t){case"summary":return`057 activity summary${n}`;case"availability":return`057 activity availability${n}`;case"breakdown":return`057 activity breakdown${n} --by ${r??"model"}`;case"compare":return`057 activity compare${n} --previous`}}function $y(t){return t==="last-7d"?"LAST 7D":"TODAY"}function cn(t,e){return t.measures.find(r=>r.dimension===e)}function $c(t){return ky[t]??t}function Ar(t){return t.retention.state==="outside-retention"}function Jn(t,e){return t.records>0&&t[e]===t.records}function By(t){return[[t.observed,"observed"],[t.inferred,"inferred"],[t.partial,"partial"],[t.notObserved,"not observed"],[t.unsupported,"unsupported"],[t.unknown,"unknown"]].filter(([e])=>e>0).map(([e,r])=>`${e} ${r}`).join(" · ")}function ps(t,e){return e.records===0?J(t):`${J(t)} · ${By(e)} / ${e.records}`}function ya(t){return{k:"CONTINUITY",v:J(t.continuity.state)}}function zA(t){const e=cn(t,"model");if(!e||e.coverage.records===0)return;const r=e.coverage,n=[r.notObserved>0?`${r.notObserved} of ${r.records} not observed`:void 0,r.unsupported>0?`${r.unsupported} of ${r.records} unsupported`:void 0,r.unknown>0?`${r.unknown} of ${r.records} unknown`:void 0].filter(o=>o!==void 0);return n.length>0?{k:"MODEL",v:n.join(" · ")}:void 0}function Ry(t){const e=t.bounds;return[e.observedEnds>0?`${e.observedEnds} observed`:void 0,e.inferredEnds>0?`${e.inferredEnds} inferred`:void 0,e.openEnds>0?`${e.openEnds} open`:void 0].filter(n=>n!==void 0).join(" · ")||"none"}function My(t,e){const r=t.retention.semanticFrom;return`${J(t.retention.state)}${r===null?"":` · from ${cd(r,e)}`}`}function _y(t){return`median ${mt(t.median)} · p90 ${mt(t.p90)} · max ${mt(t.maximum)}`}function jy(t){const e=new Set(t.map(n=>n.state));if(e.size!==1)return` (${t.map(n=>J(n.state)).join(", ")})`;const[r]=[...e];return r==="observed"?"":`, ${t.length===2?"both":"all"} ${J(r)}`}function YA(t,e){const r=bt(t,e).text.replace(`${e} `,"");return r==="not observed"?`no observed ${e}`:`a ${e} that is ${r}`}function Zn(t){return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function qr(t,e){if(t===void 0)throw new Error(`the ${e} result is missing`);return t}const cp=448,XA=384;function JA(){return ue(xn(),".057")}function ga(){const t=process.env.O57_STORE;return t&&t.length>0?t===":memory:"||tu(t)?t:$s(process.cwd(),t):ue(JA(),"events.db")}function Dy(){const t=process.env.O57_STORE;return typeof t=="string"&&t.length>0}function va(t){return[t,`${t}-wal`,`${t}-shm`]}function ZA(t){return t===":memory:"?[]:[...va(t),`${t}.display`]}function QA(t){if(t===":memory:")return;const e=vi(t);eu(e,{recursive:!0,mode:cp}),Ly(e,cp)}function lu(t){if(t===":memory:")return[];const e=[];for(const r of va(t))if(ge(r)&&!Ly(r,XA)){const n=dd(r);n!==null&&(n&63)!==0&&e.push({path:r,mode:n})}return e}function dd(t){try{return fa(t).mode&511}catch{return null}}function Ly(t,e){if(process.platform==="win32")return!1;const r=dd(t);if(r===null)return!1;if((r&~e)===0)return!0;try{return pa(t,e),!0}catch{return!1}}function Py(){if(Dy())return null;const t=$s(process.cwd(),".057","events.db");return ge(t)&&t!==ga()?t:null}const du={processDays:7,eventDays:90},eS=["machine"],up=["process"],Bc={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},tS=["execution","session","artifact"];function Uy(t=process.env){return{processDays:lp(t.O57_RETAIN_PROCESS_DAYS,du.processDays),eventDays:lp(t.O57_RETAIN_DAYS,du.eventDays)}}function lp(t,e){if(t===void 0||t.trim()==="")return e;const r=Number(t);return Number.isFinite(r)&&r>=0?r:e}function ba(t){const e=(r,n)=>r===0?`${n} kept indefinitely`:`${n} ${r}d`;return`${e(t.processDays,"processes")}, ${e(t.eventDays,"sessions/executions")}, machines never expire`}const rS=`-- 057 local store.
15
+ `+n.text),r.period&&(n.title="SELECTED PERIOD",n.command="Selected historical bounds; use the period controls to reproduce this reading."),n}function QS(t,e,r){const n={...Ad,timeZone:r.timeZone};switch(t.query){case"summary":{const s=Jr(e.summary,"summary");return t.focus==="duration"?rA(t,s,r,n):t.focus==="lifecycle"?tA(t,s,r,n):eA(t,s,r,n)}case"availability":{const s=Jr(e.availability,"availability");return t.focus==="tokens"?sA(t,Jr(e.summary,"summary"),r,n):t.focus==="waits"?oA(t,Jr(e.summary,"summary"),r,n):nA(t,s,r,n)}case"breakdown":{const s=Jr(e.breakdown,"breakdown");return t.focus==="errors"?aA(t,s,Jr(e.summary,"summary"),r,n):iA(t,s,r,n)}case"compare":return cA(t,Jr(e.comparison,"comparison"),n)}}function eA(t,e,r,n){const{summary:s,availability:o}=e,i=qr(t,"SUMMARY",o,!0,r,n),a=sr({operation:"summary",result:e},void 0,n);if(s.executions===0||Ir(o))return zr(i,o,a,n);const c=[Ky(e)],u=ce(s.completed),l=ce(s.failed);u!==void 0&&l!==void 0&&c.push(`${u} completed and ${l} failed${Qy([s.completed,s.failed])}.`);const d=mn(o,"waits");d&&ss(d.coverage,"unsupported")&&c.push(`Waits are unsupported for all ${s.executions}.`);const m=[...i.observation,Oa(o)],p=pA(o);return p&&m.push(p),m.push({k:"ENDS",v:Xy(o)}),{...i,finding:c.join(" "),observation:m,evidence:[...Gy(e,"lifecycle",t),Ue("completed",s.completed,String,$e(t,"summary","lifecycle")),Ue("failed",s.failed,String,$e(t,"summary","lifecycle")),Ue("interrupted",s.interrupted,String,$e(t,"summary","lifecycle")),Ue("terminal interval",s.terminalExecutionIntervalMs,yt,$e(t,"summary","duration")),Ue("overlapping interval",s.overlappingTerminalIntervalMs,yt,$e(t,"summary","duration")),Ue("tokens",s.tokens,It,$e(t,"availability","tokens")),Ue("tool interactions",s.toolInteractions,It,$e(t,"breakdown","errors")),Ue("tool errors",s.toolErrors,It,$e(t,"breakdown","errors")),qy(e,$e(t,"availability","waits"))],command:or("summary",t.scope),text:a}}function tA(t,e,r,n){const{summary:s,availability:o}=e,i=qr(t,"SUMMARY · LIFECYCLE",o,!0,r,n),a=sr({operation:"summary",result:e},void 0,n);if(s.executions===0||Ir(o))return zr(i,o,a,n);const c=[Ky(e)],u=[s.completed,s.failed,s.interrupted],[l,d,m]=u.map(b=>ce(b));l!==void 0&&d!==void 0&&m!==void 0&&c.push(`${l} completed, ${d} failed and ${m} interrupted${Qy(u)}.`),ss(s.waitingNow.coverage,"unsupported")&&c.push(`Waiting is unsupported for all ${s.executions}.`);const p=mn(o,"outcomes"),h=[...i.observation];p&&h.push({k:"OUTCOMES",v:So(p.state,p.coverage)}),h.push({k:"ENDS",v:Xy(o)});const g=s.terminalExecutionDuration,v=ce(g);return{...i,finding:c.join(" "),observation:h,evidence:[...Gy(e,void 0,t),Ue("completed",s.completed,String),Ue("failed",s.failed,String),Ue("interrupted",s.interrupted,String),{k:"terminal execution",...v?{t:Zy(v)}:{},v:v?"":"—",e:J(g.state),focus:$e(t,"summary","duration")}],command:or("summary",t.scope),text:a}}function rA(t,e,r,n){const{summary:s,availability:o}=e,i=qr(t,"SUMMARY · DURATION",o,!0,r,n),a=sr({operation:"summary",result:e},void 0,n);if(s.executions===0||Ir(o))return zr(i,o,a,n);const c=ce(s.inFlight.totalMs),u=ce(s.terminalExecutionIntervalMs),l=ce(s.inFlight.openContributionMs),d=ce(s.inFlight.parallelMs),m=ce(s.inFlight.peak),p=[];c!==void 0&&u!==void 0&&l!==void 0&&d!==void 0&&(p.push(`Recorded intervals cover ${fe(c)} — the TIME IN FLIGHT estimate.`),p.push(`Ended runs cover ${fe(u)}; open records add ${fe(l)} after overlaps are removed.`),p.push(`Parallel intervals overlap for ${fe(d)}.`));const h=[...i.observation];o.bounds.openEnds>0&&h.push({k:"OPEN ENDS",v:`${o.bounds.openEnds} of ${s.executions} executions ${o.bounds.openEnds===1?"has":"have"} no observed end`}),o.continuity.state!=="observed"&&h.push(Oa(o)),h.push({k:"INTERVAL POLICY",v:s.inFlight.assumption}),h.push({k:"ROUNDING",v:"Durations are rounded independently; displayed parts may differ from their total by a minute."});const g=s.terminalExecutionDuration,v=ce(g);return{...i,finding:p.join(" "),observation:h,evidence:[Ue("time in flight",s.inFlight.totalMs,fe),Ue("ended interval union",s.terminalExecutionIntervalMs,fe),Ue("added by open records",s.inFlight.openContributionMs,fe),Ue("overlapping interval",s.inFlight.parallelMs,fe),{...Ue("peak concurrency",s.inFlight.peak,b=>String(b.peak)),...m&&m.at!==null?{t:`at ${Au(m.at,e.period,n)}`}:{}},{k:"terminal execution",...v?{t:Zy(v)}:{},v:v?"":"—",e:J(g.state)},{k:"executions",v:String(s.executions),e:"",focus:$e(t,"summary","lifecycle")},{k:"sessions",v:String(s.sessions),e:"",focus:$e(t,"summary","lifecycle")}],command:or("summary",t.scope),text:a}}function Ky(t){const{summary:e}=t,r=ce(e.waitingNow),n=[e.runningNow>0?`${e.runningNow} running`:void 0,r!==void 0&&r>0?`${r} waiting`:void 0,e.idleNow>0?`${e.idleNow} idle`:void 0].filter(o=>o!==void 0),s=`${e.executions} ${qe(e.executions,"execution")} across ${e.sessions} ${qe(e.sessions,"session")}`;return n.length>0?`${s}; ${os(n)}.`:`${s}.`}function Gy(t,e,r){const{summary:n}=t,s=e?$e(r,"summary",e):void 0,o=(i,a)=>({k:i,v:String(a),e:"",...s?{focus:s}:{}});return[o("executions",n.executions),o("sessions",n.sessions),o("running",n.runningNow),Ue("waiting",n.waitingNow,String,s),o("idle",n.idleNow)]}function qy(t,e){const r=t.summary.waits,n=ce(r);return{k:"explicit waits",...n?{t:`for ${yt(n.durationMs)}${n.openNow>0?` · ${n.openNow} open`:""}`}:{},v:n?String(n.count):"—",e:J(r.state),...e?{focus:e}:{}}}function nA(t,e,r,n){const s=qr(t,"AVAILABILITY",e,!1,r,n),o=sr({operation:"availability",result:e},void 0,n),i=e.executionRecords;if(Ir(e))return zr(s,e,o,n);const a=[],c=[e.continuity.state==="unknown"?"Continuity":void 0,e.observationGaps.state==="unknown"?"gaps":void 0,e.unprojectedSourceWork.state==="unknown"?"unprojected work":void 0].filter(d=>d!==void 0);if(c.length>0){const d=os(c);a.push(`${d[0].toUpperCase()}${d.slice(1)} ${c.length===1?"is":"are"} unknown.`)}if(i===0)a.push("No execution records, so no measure has coverage to report.");else{const d=e.measures.filter(p=>ss(p.coverage,"unsupported"));if(d.length>0){const p=os(d.map(h=>Fc(h.dimension)));a.push(`${p[0].toUpperCase()}${p.slice(1)} ${d.length===1?"is":"are"} unsupported for all ${i}.`)}const m=[...e.measures].filter(p=>!ss(p.coverage,"unsupported")&&p.coverage.notObserved>0).sort((p,h)=>h.coverage.notObserved-p.coverage.notObserved)[0];m&&a.push(`The ${Fc(m.dimension)} is not observed for ${m.coverage.notObserved} of ${i}.`)}const u=[...s.observation,{k:"RETENTION",v:Jy(e,n)},{k:"COMPARISON",v:J(e.comparisonReadiness)}],l=[{k:"continuity",v:J(e.continuity.state),e:""},{k:"observation gaps",v:J(e.observationGaps.state),e:""},{k:"unprojected work",v:J(e.unprojectedSourceWork.state),e:""},{k:"execution records",v:String(i),e:""},...e.measures.map(d=>{const m=lA(t,d.dimension);return{k:Fc(d.dimension),...d.coverage.records>0?{t:Yy(d.coverage)}:{},v:"",e:J(d.state),...m?{focus:m}:{}}})];return{...s,finding:a.join(" ")||void 0,observation:u,evidenceCaption:"COVERAGE",evidence:l,command:or("availability",t.scope),text:o}}function sA(t,e,r,n){const{summary:s,availability:o}=e,i=qr(t,"AVAILABILITY · TOKENS",o,!1,r,n),a=sr({operation:"availability",result:o},void 0,n);if(s.executions===0||Ir(o))return zr(i,o,a,n);const c=mn(o,"tokens"),u=mn(o,"model"),l=ce(s.tokens),d=[];if(l!==void 0&&c){const p=c.coverage,h=[p.inferred>0?`${p.inferred} ${p.inferred===1?"is":"are"} inferred`:void 0,p.partial>0?`${p.partial} ${p.partial===1?"is":"are"} partial`:void 0,p.notObserved>0?`${p.notObserved} ${p.notObserved===1?"was":"were"} not observed`:void 0,p.unsupported>0?`${p.unsupported} ${p.unsupported===1?"is":"are"} unsupported`:void 0,p.unknown>0?`${p.unknown} ${p.unknown===1?"is":"are"} unknown`:void 0].filter(g=>g!==void 0);d.push(h.length===0?`${It(l)} is fully observed for all ${p.records} executions.`:`${It(l)} is fully observed for ${p.observed} of ${p.records} executions; ${os(h)}.`)}else d.push(`Tokens are ${J(s.tokens.state)} for this period.`);s.executionsWithoutModel>0&&d.push(`${s.executionsWithoutModel} ${qe(s.executionsWithoutModel,"execution")} carry no observed model, so it cannot be divided completely by model.`);const m=[...i.observation];return c&&m.push({k:"TOKENS",v:So(c.state,c.coverage)}),u&&m.push({k:"MODEL",v:So(u.state,u.coverage)}),m.push(Oa(o)),{...i,finding:d.join(" "),observation:m,evidence:[Ue("tokens",s.tokens,It),...uA(e)],command:or("availability",t.scope),text:a}}function oA(t,e,r,n){const{summary:s,availability:o}=e,i=qr(t,"AVAILABILITY · WAITS",o,!1,r,n),a=sr({operation:"availability",result:o},void 0,n);if(s.executions===0||Ir(o))return zr(i,o,a,n);const c=mn(o,"waits"),u=s.executions,l=ce(s.waits);let d,m;const p=c&&(ss(c.coverage,"unsupported")||ss(c.coverage,"notObserved"));!l||p?(d="NOT OBSERVED",m=`Wait behaviour is ${J(s.waits.state)} for all ${u} executions in this period, so time blocked on a person cannot be read from it.`):(m=`${l.count} explicit ${qe(l.count,"wait")} for ${yt(l.durationMs)}${l.openNow>0?`, ${l.openNow} open now`:""}.`,c&&c.coverage.unsupported>0&&(m+=` Waits are unsupported for ${c.coverage.unsupported} of ${u} executions.`));const h=[...i.observation];return c&&h.push({k:"WAITS",v:So(c.state,c.coverage)}),h.push({k:"SOURCES",v:o.sources.map(g=>`${g.source} ${g.executionRecords}`).join(" · ")}),{...i,...d?{verdict:d}:{},finding:m,observation:h,evidence:[qy(e),{...Ue("waiting",s.waitingNow,String),t:"recorded lifecycle"},{k:"executions",v:String(u),e:""}],command:or("availability",t.scope),text:a}}function iA(t,e,r,n){const s=t.by??"model",o=qr(t,`BREAKDOWN · ${s.toUpperCase()}`,e.availability,!1,r,n),i=sr({operation:"breakdown",result:e},void 0,n),a=e.availability.executionRecords;if(a===0||Ir(e.availability))return zr(o,e.availability,i,n);const c=e.items.filter(p=>!bt(p.key,s).pseudo),u=e.items.filter(p=>bt(p.key,s).pseudo),l=[];if(s==="executor")l.push(`${os(c.map(p=>`${p.key} ${p.executions}`))} execution ${qe(c.reduce((p,h)=>p+h.executions,0),"record")}.`);else if(c[0]){const p=c[0],h=ce(p.tokens);l.push(`${p.key} accounts for ${p.executions} of ${a} executions${h!==void 0?` and ${_e(h)} tokens`:""}.`)}for(const p of u)l.push(`${p.executions} ${qe(p.executions,"execution")} ${p.executions===1?"carries":"carry"} ${hA(p.key,s)}.`);const d=mn(e.availability,s),m=[...o.observation];return d&&m.push({k:s.toUpperCase(),v:So(d.state,d.coverage)}),m.push({k:"CAUSALITY",v:"grouped records; not a causal performance difference"}),{...o,finding:l.join(" "),observation:m,evidenceCaption:"TOKENS",evidence:e.items.map(p=>{const h=ce(p.terminalDuration),g=ce(p.tokens);return{k:bt(p.key,s).text,t:`${_e(p.executions)} ${qe(p.executions,"execution")}${h?` · median ${Dy(h.median)}`:""}`,v:g===void 0?"—":_e(g),e:J(p.tokens.state)}}),command:or("breakdown",t.scope,s),text:i}}function aA(t,e,r,n,s){const o=qr(t,"BREAKDOWN · MODEL · ERRORS",e.availability,!1,n,s),i=sr({operation:"breakdown",result:e},void 0,s);if(e.availability.executionRecords===0||Ir(e.availability))return zr(o,e.availability,i,s);const a=[...e.items].sort((g,v)=>(ce(v.toolErrors)??-1)-(ce(g.toolErrors)??-1)||v.executions-g.executions),c=ce(r.summary.toolErrors),u=a.filter(g=>!bt(g.key,"model").pseudo&&ce(g.toolErrors)!==void 0),l=[],d=g=>{const v=ce(g.toolInteractions);return v===void 0?"":`, across ${_e(v)} tool interactions`};if(c===void 0)l.push(`Tool errors are ${J(r.summary.toolErrors.state)} for this period.`);else if(c===0)l.push("No tool errors were recorded.");else if(u[0]){const[g,v]=u,b=ce(g.toolErrors)??0;if(l.push(b*2>c?`Tool errors are concentrated in ${g.key}: ${_e(b)} of ${_e(c)} recorded errors${d(g)}.`:`Tool errors are spread across models: ${g.key} recorded ${_e(b)} of ${_e(c)}${d(g)}.`),v){const _=ce(v.toolInteractions);l.push(`${v.key} recorded ${_e(ce(v.toolErrors)??0)}${_===void 0?"":` across ${_e(_)}`}.`)}}const m=[...o.observation],p=e.items.filter(g=>g.toolErrors.state==="unsupported").map(g=>bt(g.key,"model").text);p.length>0&&m.push({k:"ERRORS",v:`unsupported for ${os(p)}`}),m.push({k:"CAUSALITY",v:"grouped records; not a causal performance difference"});const h=(g,v)=>{const b=ce(g),_=ce(v);return`${b===void 0?"—":_e(b)} / ${_===void 0?"—":_e(_)}`};return{...o,finding:l.join(" "),observation:m,evidenceCaption:"ERRORS / TOOLS",evidence:[{k:"all executions",v:h(r.summary.toolErrors,r.summary.toolInteractions),e:J(r.summary.toolErrors.state)},...a.map(g=>({k:bt(g.key,"model").text,v:h(g.toolErrors,g.toolInteractions),e:J(g.toolErrors.state)}))],command:or("breakdown",t.scope,"model"),text:i}}function cA(t,e,r){const n=[{k:"A",w:bo(e.periodA,r),s:J(e.availabilityA.observation)},{k:"B",w:bo(e.periodB,r),s:J(e.availabilityB.observation)}],s=[...e.availabilityA.reasons.map(d=>({k:"A",v:d})),...e.availabilityB.reasons.map(d=>({k:"B",v:d})),...e.reasons.filter(d=>!d.startsWith("period A: ")&&!d.startsWith("period B: ")).map(d=>({k:"",v:d}))],o=e.dimensions.filter(d=>!d.dimension.endsWith(" mix")),i=new Set(e.dimensions.flatMap(d=>d.reasons)),c=[{k:"DIMENSIONS",v:e.dimensions.every(d=>d.eligibility===e.eligibility)&&i.size===1?`all — ${[...i][0]}`:["comparable","partially-comparable","not-comparable"].map(d=>[e.dimensions.filter(m=>m.eligibility===d).length,J(d)]).filter(([d])=>d>0).map(([d,m])=>`${d} ${m}`).join(" · ")}],u=(d,m)=>{const p=ce(m);return typeof p!="number"?"—":Qn[d]?.duration?Su(p):_e(p)},l=(d,m)=>{const p=ce(m);return typeof p!="number"?"—":Qn[d]?.duration?Su(p):It(p)};return{request:t,title:zy(t.scope),resolution:`COMPARISON · AGAINST PREVIOUS${t.scope==="last-7d"?" 7D":""}`,periods:n,partial:e.availabilityA.observation!=="observed"||e.availabilityB.observation!=="observed",verdict:J(e.eligibility).toUpperCase(),reasons:s,observation:c,evidenceCaption:"A · B",evidence:o.map(d=>{const m=dA(t,d.dimension);return{k:Qn[d.dimension]?.label??d.dimension,t:`B ${u(d.dimension,d.periodB)} ${J(d.periodB.state)}`,v:u(d.dimension,d.periodA),e:J(d.periodA.state),comparison:{a:u(d.dimension,d.periodA),b:u(d.dimension,d.periodB),aCompact:l(d.dimension,d.periodA),bCompact:l(d.dimension,d.periodB),aEvidence:J(d.periodA.state),bEvidence:J(d.periodB.state),eligibility:J(d.eligibility),reasons:d.reasons},...m?{focus:m}:{}}}),command:or("compare",t.scope),text:sr({operation:"compare",result:e},void 0,r)}}function qr(t,e,r,n,s,o){const i=[J(r.observation),...n?[J(r.retention.state)]:[]].join(" · "),a=[],c=zy(t.scope);return s.view&&s.view!==c&&a.push({k:"PERIOD",v:`${c.toLowerCase()}, as asked · the view is showing ${s.view.toLowerCase()}`}),{request:t,title:c,resolution:e,window:bo(r.period,o),qualification:i,partial:r.observation!=="observed",reasons:[],observation:a}}function zr(t,e,r,n){const s=t.request,o=or(s.query,s.scope,s.by);if(Ir(e)){const i=e.retention.semanticFrom;return{...t,verdict:"OUTSIDE RETENTION",finding:i===null?"This period precedes semantic history.":`Semantic history starts at ${kd(i,n)}; this period precedes it.`,observation:[...t.observation,{k:"RETENTION",v:Jy(e,n)}],evidence:[],command:o,text:r}}return{...t,finding:"No execution records. A quiet period cannot be told from an unobserved one, so zero work is not established.",observation:[...t.observation,Oa(e)],evidence:[{k:"execution records",v:"0",e:""}],command:o,text:r}}function uA(t){const{summary:e}=t,r=e.usageByModel.map(s=>{const o=ce(s.tokens);return{k:s.model,t:`${s.executions} ${qe(s.executions,"execution")}`,v:o===void 0?"—":It(o),e:J(s.tokens.state)}}),n=e.modelMix.filter(s=>bt(s.key,"model").pseudo);if(n.reduce((s,o)=>s+o.executions,0)===e.executionsWithoutModel)for(const s of n)r.push({k:bt(s.key,"model").text,t:`${s.executions} ${qe(s.executions,"execution")}`,v:"",e:""});else e.executionsWithoutModel>0&&r.push({k:"model not observed",t:`${e.executionsWithoutModel} ${qe(e.executionsWithoutModel,"execution")}`,v:"",e:""});return r}function Ue(t,e,r,n){const s=ce(e);return{k:t,v:s===void 0?"—":r(s),e:J(e.state),...n?{focus:n}:{}}}function $e(t,e,r){const n=e==="breakdown"?{query:e,scope:t.scope,focus:r,by:"model"}:{query:e,scope:t.scope,focus:r};return fA(n,t)?void 0:n}function lA(t,e){switch(e){case"tokens":return $e(t,"availability","tokens");case"waits":return $e(t,"availability","waits");case"tool-errors":case"tool-interactions":return $e(t,"breakdown","errors");case"outcomes":return $e(t,"summary","lifecycle");case"bounds":return $e(t,"summary","duration");case"model":return{query:"breakdown",scope:t.scope,by:"model"};case"executor":return{query:"breakdown",scope:t.scope,by:"executor"}}}function dA(t,e){return e==="tokens"?$e(t,"availability","tokens"):e==="explicit wait count"?$e(t,"availability","waits"):e==="tool interactions"||e==="tool errors"?$e(t,"breakdown","errors"):Qn[e]?.duration||e==="peak terminal concurrency"?$e(t,"summary","duration"):$e(t,"summary","lifecycle")}function fA(t,e){return t.query===e.query&&t.scope===e.scope&&t.focus===e.focus&&t.by===e.by}function or(t,e,r){const n=e==="last-7d"?" --last 7d":"";switch(t){case"summary":return`057 activity summary${n}`;case"availability":return`057 activity availability${n}`;case"breakdown":return`057 activity breakdown${n} --by ${r??"model"}`;case"compare":return`057 activity compare${n} --previous`}}function zy(t){return t==="last-7d"?"LAST 7D":"TODAY"}function mn(t,e){return t.measures.find(r=>r.dimension===e)}function Fc(t){return Uy[t]??t}function Ir(t){return t.retention.state==="outside-retention"}function ss(t,e){return t.records>0&&t[e]===t.records}function Yy(t){return[[t.observed,"observed"],[t.inferred,"inferred"],[t.partial,"partial"],[t.notObserved,"not observed"],[t.unsupported,"unsupported"],[t.unknown,"unknown"]].filter(([e])=>e>0).map(([e,r])=>`${e} ${r}`).join(" · ")}function So(t,e){return e.records===0?J(t):`${J(t)} · ${Yy(e)} / ${e.records}`}function Oa(t){return{k:"CONTINUITY",v:J(t.continuity.state)}}function pA(t){const e=mn(t,"model");if(!e||e.coverage.records===0)return;const r=e.coverage,n=[r.notObserved>0?`${r.notObserved} of ${r.records} not observed`:void 0,r.unsupported>0?`${r.unsupported} of ${r.records} unsupported`:void 0,r.unknown>0?`${r.unknown} of ${r.records} unknown`:void 0].filter(s=>s!==void 0);return n.length>0?{k:"MODEL",v:n.join(" · ")}:void 0}function Xy(t){const e=t.bounds;return[e.observedEnds>0?`${e.observedEnds} observed`:void 0,e.inferredEnds>0?`${e.inferredEnds} inferred`:void 0,e.openEnds>0?`${e.openEnds} open`:void 0].filter(n=>n!==void 0).join(" · ")||"none"}function Jy(t,e){const r=t.retention.semanticFrom;return`${J(t.retention.state)}${r===null?"":` · from ${kd(r,e)}`}`}function Zy(t){return`median ${yt(t.median)} · p90 ${yt(t.p90)} · max ${yt(t.maximum)}`}function Qy(t){const e=new Set(t.map(n=>n.state));if(e.size!==1)return` (${t.map(n=>J(n.state)).join(", ")})`;const[r]=[...e];return r==="observed"?"":`, ${t.length===2?"both":"all"} ${J(r)}`}function hA(t,e){const r=bt(t,e).text.replace(`${e} `,"");return r==="not observed"?`no observed ${e}`:`a ${e} that is ${r}`}function os(t){return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function Jr(t,e){if(t===void 0)throw new Error(`the ${e} result is missing`);return t}const Sp=448,mA=384;function yA(){return ue(Bn(),".057")}function Na(){const t=process.env.O57_STORE;return t&&t.length>0?t===":memory:"||hu(t)?t:Lo(process.cwd(),t):ue(yA(),"events.db")}function eg(){const t=process.env.O57_STORE;return typeof t=="string"&&t.length>0}function Ta(t){return[t,`${t}-wal`,`${t}-shm`]}function gA(t){return t===":memory:"?[]:[...Ta(t),`${t}.display`]}function vA(t){if(t===":memory:")return;const e=Oi(t);pu(e,{recursive:!0,mode:Sp}),tg(e,Sp)}function xu(t){if(t===":memory:")return[];const e=[];for(const r of Ta(t))if(ve(r)&&!tg(r,mA)){const n=Id(r);n!==null&&(n&63)!==0&&e.push({path:r,mode:n})}return e}function Id(t){try{return ka(t).mode&511}catch{return null}}function tg(t,e){if(process.platform==="win32")return!1;const r=Id(t);if(r===null)return!1;if((r&~e)===0)return!0;try{return Ea(t,e),!0}catch{return!1}}function rg(){if(eg())return null;const t=Lo(process.cwd(),".057","events.db");return ve(t)&&t!==Na()?t:null}const Iu={processDays:7,eventDays:90},bA=["machine"],Ap=["process"],Wc={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},wA=["execution","session","artifact"];function ng(t=process.env){return{processDays:kp(t.O57_RETAIN_PROCESS_DAYS,Iu.processDays),eventDays:kp(t.O57_RETAIN_DAYS,Iu.eventDays)}}function kp(t,e){if(t===void 0||t.trim()==="")return e;const r=Number(t);return Number.isFinite(r)&&r>=0?r:e}function $a(t){const e=(r,n)=>r===0?`${n} kept indefinitely`:`${n} ${r}d`;return`${e(t.processDays,"processes")}, ${e(t.eventDays,"sessions/executions")}, machines never expire`}const SA=`-- 057 local store.
16
16
  --
17
17
  -- \`events\` is the only durable truth. \`claims\` is denormalized out of events so identity
18
18
  -- resolution is one indexed read rather than a scan; it is rebuildable from events at any time.
@@ -48,6 +48,8 @@ CREATE INDEX IF NOT EXISTS events_source ON events(source_id, occurred_at);
48
48
  -- 057 took to start listening. With it, 0.13 s. An index, not a schema change: older builds open a
49
49
  -- store that has it, so user_version stays where it is.
50
50
  CREATE INDEX IF NOT EXISTS events_subject_time ON events(subject_type, subject_id, occurred_at);
51
+ -- Live observations are read by type and time, without visiting a subject's entire history.
52
+ CREATE INDEX IF NOT EXISTS events_type_time ON events(subject_type, occurred_at, id);
51
53
  -- Window hydration needs every declaration, including later annotations, but no observations.
52
54
  -- The general subject index visits a subject's entire history just to reject non-began rows;
53
55
  -- on a long-lived session this delayed the first Display frame by more than 20 seconds.
@@ -70,15 +72,15 @@ CREATE INDEX IF NOT EXISTS claims_window ON claims(valid_to, valid_from);
70
72
  CREATE INDEX IF NOT EXISTS claims_event ON claims(event_id);
71
73
  -- Semantic readings need claims sharing their subjects' keys, not every unrelated OS sample.
72
74
  CREATE INDEX IF NOT EXISTS claims_subject_window ON claims(subject_type, valid_to, valid_from, key);
73
- `,ur=1;class xt extends Error{constructor(e,r,n){super(e),this.kind=r,this.remedy=n,this.name="StoreError"}kind;remedy}function di(t){const e=t?.code;if(e==="EACCES"||e==="EPERM"||e==="EROFS")return!0;const r=t instanceof Error?t.message:String(t);return/readonly|read-only|attempt to write a readonly database|unable to open database file|permission denied|SQLITE_(READONLY|PERM|CANTOPEN)/i.test(r)}function Rc(t,e){const r=e instanceof Error?e.message:String(e);return new xt(`store ${t} cannot be written: ${r}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory and that both are writable (057 needs 0600 on the store and 0700 on its directory), or point O57_STORE at a writable path.")}function nS(t){QA(t);let e;try{e=new Bs(t)}catch(p){throw di(p)?Rc(t,p):new xt(`cannot open the store at ${t}: ${p instanceof Error?p.message:String(p)}`,"unreadable","Check that the path exists and names a file 057 can open, or point O57_STORE elsewhere.")}let r;try{r=Number(e.prepare("PRAGMA user_version").get().user_version)}catch(p){throw e.close(),di(p)?Rc(t,p):new xt(`store ${t} is not a readable database: ${p instanceof Error?p.message:String(p)}`,"unreadable","The file exists but is not a 057 store. Move it aside and 057 will start a new one; `057 reset` does that for you. Back it up first if it might be data you want.")}if(r>ur)throw e.close(),new xt(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${ur})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{e.exec(rS);const p=new Set(e.prepare("PRAGMA table_info(events)").all().map(h=>String(h.name)));p.has("stratum")||e.exec("ALTER TABLE events ADD COLUMN stratum TEXT"),p.has("provenance")||e.exec("ALTER TABLE events ADD COLUMN provenance TEXT"),r!==ur&&e.exec(`PRAGMA user_version = ${ur}`)}catch(p){e.close();const h=p instanceof Error?p.message:String(p);throw di(p)?Rc(t,p):new xt(`store ${t} could not be prepared: ${h}`,"unreadable","The file may be corrupt. Back it up, then move it aside and 057 will start a new store; `057 reset` does that for you.")}lu(t);const n=1e3,o=new Set,s=new Set;let i=null;const a=(p,h)=>{s.add(p),i??=Date.now(),o.size<n&&o.add(h)},c=p=>Fy(p,a),u=e.prepare(`INSERT OR IGNORE INTO events
75
+ `,hr=1;class Ct extends Error{constructor(e,r,n){super(e),this.kind=r,this.remedy=n,this.name="StoreError"}kind;remedy}function Si(t){const e=t?.code;if(e==="EACCES"||e==="EPERM"||e==="EROFS")return!0;const r=t instanceof Error?t.message:String(t);return/readonly|read-only|attempt to write a readonly database|unable to open database file|permission denied|SQLITE_(READONLY|PERM|CANTOPEN)/i.test(r)}function Kc(t,e){const r=e instanceof Error?e.message:String(e);return new Ct(`store ${t} cannot be written: ${r}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory and that both are writable (057 needs 0600 on the store and 0700 on its directory), or point O57_STORE at a writable path.")}function AA(t){vA(t);let e;try{e=new Uo(t)}catch(p){throw Si(p)?Kc(t,p):new Ct(`cannot open the store at ${t}: ${p instanceof Error?p.message:String(p)}`,"unreadable","Check that the path exists and names a file 057 can open, or point O57_STORE elsewhere.")}let r;try{r=Number(e.prepare("PRAGMA user_version").get().user_version)}catch(p){throw e.close(),Si(p)?Kc(t,p):new Ct(`store ${t} is not a readable database: ${p instanceof Error?p.message:String(p)}`,"unreadable","The file exists but is not a 057 store. Move it aside and 057 will start a new one; `057 reset` does that for you. Back it up first if it might be data you want.")}if(r>hr)throw e.close(),new Ct(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${hr})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{e.exec(SA);const p=new Set(e.prepare("PRAGMA table_info(events)").all().map(h=>String(h.name)));p.has("stratum")||e.exec("ALTER TABLE events ADD COLUMN stratum TEXT"),p.has("provenance")||e.exec("ALTER TABLE events ADD COLUMN provenance TEXT"),r!==hr&&e.exec(`PRAGMA user_version = ${hr}`)}catch(p){e.close();const h=p instanceof Error?p.message:String(p);throw Si(p)?Kc(t,p):new Ct(`store ${t} could not be prepared: ${h}`,"unreadable","The file may be corrupt. Back it up, then move it aside and 057 will start a new store; `057 reset` does that for you.")}xu(t);const n=1e3,s=new Set,o=new Set;let i=null;const a=(p,h)=>{o.add(p),i??=Date.now(),s.size<n&&s.add(h)},c=p=>ig(p,a),u=e.prepare(`INSERT OR IGNORE INTO events
74
76
  (id, source_id, source_instance, occurred_at, observed_at, clock, kind,
75
77
  subject_type, subject_id, core, attrs, basis, assumption, stratum, provenance)
76
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),d=e.prepare(`INSERT INTO claims
78
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),l=e.prepare(`INSERT INTO claims
77
79
  (event_id, key, ns, subject_type, subject_id, source_id, valid_from, valid_to)
78
- VALUES (?,?,?,?,?,?,?,?)`),l=Vy(e,c),m={path:t,schemaVersion:ur,append(p){let h=0,v=0;e.exec("BEGIN");try{for(const g of p){if(u.run(g.id,g.source.id,g.source.instance,g.occurredAt,g.observedAt,g.clock,g.kind,g.subject.type,g.subject.id,g.core?JSON.stringify(g.core):null,g.attrs?JSON.stringify(g.attrs):null,g.basis,g.assumption??null,g.stratum??null,g.provenance?JSON.stringify(g.provenance):null).changes===0){v++;continue}h++;for(const N of g.claims??[])d.run(g.id,Vb(N),N.ns,g.subject.type,g.subject.id,g.source.id,N.validFrom,N.validTo)}e.exec("COMMIT")}catch(g){throw e.exec("ROLLBACK"),g}return{inserted:h,duplicate:v}},query:l.query,claims:l.claims,stats:l.stats,begansFor:l.begansFor,executionCarry:l.executionCarry,subjectEvents(p,h){return e.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(p,h).map(c)},latestFor(p){return e.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(p)?.hi??null},sweep(p=du,h=Date.now()){const v=p.processDays>0?h-p.processDays*864e5:null,g=p.eventDays>0?h-p.eventDays*864e5:null;if(v===null&&g===null)return{...Bc};const I=z=>eS.includes(z)?null:up.includes(z)?v:g,N=e.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
79
- FROM events GROUP BY subject_type, subject_id`).all().map(z=>{const se=z;return{type:String(se.t),id:String(se.i),last:Number(se.last)}}),S=(z,se)=>`${z}:${se}`,T=new Set,x=new Map;for(const z of N){const se=I(z.type);se===null||z.last>=se?T.add(S(z.type,z.id)):x.set(S(z.type,z.id),{type:z.type,id:z.id})}if(x.size===0)return{...Bc,processBefore:v,otherBefore:g};const D=[...tS],w=e.prepare(`SELECT DISTINCT core FROM events
80
- WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),$=new Set(D);let E=[...T].filter(z=>$.has(z.slice(0,z.indexOf(":"))));const B=new Set(E);let C=0;for(let z=0;z<4&&E.length>0;z++){const se=[];for(const ve of E){const Ae=ve.indexOf(":");for(const _e of w.all(ve.slice(0,Ae),ve.slice(Ae+1))){const Ie=fi(_e.core);if(Ie)for(const[q,qe]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const rt=Ie[q];if(typeof rt!="string")continue;const A=S(qe,rt);x.has(A)&&(x.delete(A),T.add(A),C++,!B.has(A)&&$.has(qe)&&(B.add(A),se.push(A)))}}}E=se}if(x.size===0)return{...Bc,retainedByDependents:C,processBefore:v,otherBefore:g};const P=e.prepare(`DELETE FROM claims WHERE event_id IN
81
- (SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),L=e.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let te=0,U=0,V=0;e.exec("BEGIN");try{for(const{type:z,id:se}of x.values()){V+=Number(P.run(z,se).changes);const ve=Number(L.run(z,se).changes);up.includes(z)?te+=ve:U+=ve}e.exec("COMMIT")}catch(z){throw e.exec("ROLLBACK"),z}return te+U>0&&m.checkpoint(),{processEvents:te,otherEvents:U,claims:V,subjects:x.size,retainedByDependents:C,processBefore:v,otherBefore:g}},checkpoint(){try{e.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes:()=>Hy(t),health(){const p=o.size;return p===0?{ok:!0,malformedRows:0,columns:[],since:null}:{ok:!1,malformedRows:p,columns:[...s].sort(),since:i,remedy:`${p} stored row(s) could not be read as JSON and lost their ${[...s].sort().join("/")} channel. Everything else is being used normally and nothing has been deleted. Run \`057 compact\` to rewrite the store; if the count keeps growing, back the store up and run \`057 reset\` to start a new one.`}},compact(){e.exec("VACUUM"),m.checkpoint(),lu(t)},close(){m.checkpoint(),e.close()}};return m}function wa(t){if(t===":memory:"||!ge(t))throw new xt(`no 057 store exists at ${t}`,"unreadable","Nothing has been observed there yet. Run 057, or open 057.app, to start observing; reading never creates a store.");let e,r;try{e=new Bs(t,{readOnly:!0})}catch(o){throw dp(t,o)}try{e.exec("PRAGMA query_only = ON"),r=Number(e.prepare("PRAGMA user_version").get().user_version)}catch(o){throw e.close(),dp(t,o)}if(r!==ur)throw e.close(),r>ur?new xt(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${ur})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified."):new xt(`store ${t} has not been prepared by this 057 yet (schema ${r})`,"unreadable","Start 057 or 057.app once so it can prepare the store, then query again. The store was not modified.");const n=Vy(e,o=>Fy(o));return{path:t,schemaVersion:ur,...n,sizeBytes:()=>Hy(t),close(){e.close()}}}function dp(t,e){const r=e instanceof Error?e.message:String(e);return di(e)?new xt(`store ${t} cannot be read: ${r}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory."):new xt(`store ${t} is not a readable database: ${r}`,"unreadable","The store was not modified. Check that O57_STORE names a 057 store.")}function Vy(t,e){const r=t.prepare("SELECT * FROM events WHERE occurred_at >= ? AND occurred_at <= ? ORDER BY occurred_at, id"),n=new Map,o=t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'events_subject_time'").get()?"INDEXED BY events_subject_time":"",s=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
80
+ VALUES (?,?,?,?,?,?,?,?)`),d=sg(e,c),m={path:t,schemaVersion:hr,append(p){let h=0,g=0;e.exec("BEGIN");try{for(const v of p){if(u.run(v.id,v.source.id,v.source.instance,v.occurredAt,v.observedAt,v.clock,v.kind,v.subject.type,v.subject.id,v.core?JSON.stringify(v.core):null,v.attrs?JSON.stringify(v.attrs):null,v.basis,v.assumption??null,v.stratum??null,v.provenance?JSON.stringify(v.provenance):null).changes===0){g++;continue}h++;for(const _ of v.claims??[])l.run(v.id,ow(_),_.ns,v.subject.type,v.subject.id,v.source.id,_.validFrom,_.validTo)}e.exec("COMMIT")}catch(v){throw e.exec("ROLLBACK"),v}return{inserted:h,duplicate:g}},query:d.query,claims:d.claims,stats:d.stats,begansFor:d.begansFor,executionCarry:d.executionCarry,subjectEvents(p,h){return e.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(p,h).map(c)},latestFor(p){return e.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(p)?.hi??null},sweep(p=Iu,h=Date.now()){const g=p.processDays>0?h-p.processDays*864e5:null,v=p.eventDays>0?h-p.eventDays*864e5:null;if(g===null&&v===null)return{...Wc};const b=te=>bA.includes(te)?null:Ap.includes(te)?g:v,_=e.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
81
+ FROM events GROUP BY subject_type, subject_id`).all().map(te=>{const ne=te;return{type:String(ne.t),id:String(ne.i),last:Number(ne.last)}}),E=(te,ne)=>`${te}:${ne}`,I=new Set,k=new Map;for(const te of _){const ne=b(te.type);ne===null||te.last>=ne?I.add(E(te.type,te.id)):k.set(E(te.type,te.id),{type:te.type,id:te.id})}if(k.size===0)return{...Wc,processBefore:g,otherBefore:v};const w=[...wA],N=e.prepare(`SELECT DISTINCT core FROM events
82
+ WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),$=new Set(w);let P=[...I].filter(te=>$.has(te.slice(0,te.indexOf(":"))));const C=new Set(P);let T=0;for(let te=0;te<4&&P.length>0;te++){const ne=[];for(const ge of P){const we=ge.indexOf(":");for(const Pe of N.all(ge.slice(0,we),ge.slice(we+1))){const Oe=Ai(Pe.core);if(Oe)for(const[Q,Ae]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const Ne=Oe[Q];if(typeof Ne!="string")continue;const A=E(Ae,Ne);k.has(A)&&(k.delete(A),I.add(A),T++,!C.has(A)&&$.has(Ae)&&(C.add(A),ne.push(A)))}}}P=ne}if(k.size===0)return{...Wc,retainedByDependents:T,processBefore:g,otherBefore:v};const R=e.prepare(`DELETE FROM claims WHERE event_id IN
83
+ (SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),H=e.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let U=0,L=0,G=0;e.exec("BEGIN");try{for(const{type:te,id:ne}of k.values()){G+=Number(R.run(te,ne).changes);const ge=Number(H.run(te,ne).changes);Ap.includes(te)?U+=ge:L+=ge}e.exec("COMMIT")}catch(te){throw e.exec("ROLLBACK"),te}return U+L>0&&m.checkpoint(),{processEvents:U,otherEvents:L,claims:G,subjects:k.size,retainedByDependents:T,processBefore:g,otherBefore:v}},checkpoint(){try{e.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes:()=>og(t),health(){const p=s.size;return p===0?{ok:!0,malformedRows:0,columns:[],since:null}:{ok:!1,malformedRows:p,columns:[...o].sort(),since:i,remedy:`${p} stored row(s) could not be read as JSON and lost their ${[...o].sort().join("/")} channel. Everything else is being used normally and nothing has been deleted. Run \`057 compact\` to rewrite the store; if the count keeps growing, back the store up and run \`057 reset\` to start a new one.`}},compact(){e.exec("VACUUM"),m.checkpoint(),xu(t)},close(){m.checkpoint(),e.close()}};return m}function Ba(t){if(t===":memory:"||!ve(t))throw new Ct(`no 057 store exists at ${t}`,"unreadable","Nothing has been observed there yet. Run 057, or open 057.app, to start observing; reading never creates a store.");let e,r;try{e=new Uo(t,{readOnly:!0})}catch(s){throw Ep(t,s)}try{e.exec("PRAGMA query_only = ON"),r=Number(e.prepare("PRAGMA user_version").get().user_version)}catch(s){throw e.close(),Ep(t,s)}if(r!==hr)throw e.close(),r>hr?new Ct(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${hr})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified."):new Ct(`store ${t} has not been prepared by this 057 yet (schema ${r})`,"unreadable","Start 057 or 057.app once so it can prepare the store, then query again. The store was not modified.");const n=sg(e,s=>ig(s));return{path:t,schemaVersion:hr,...n,sizeBytes:()=>og(t),close(){e.close()}}}function Ep(t,e){const r=e instanceof Error?e.message:String(e);return Si(e)?new Ct(`store ${t} cannot be read: ${r}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory."):new Ct(`store ${t} is not a readable database: ${r}`,"unreadable","The store was not modified. Check that O57_STORE names a 057 store.")}function ci(t,...e){return typeof t.iterate=="function"?t.iterate(...e):t.all(...e)}function sg(t,e){const r=t.prepare("SELECT * FROM events WHERE occurred_at >= ? AND occurred_at <= ? ORDER BY occurred_at, id"),n=new Map,s=t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'events_type_time'").get()?"INDEXED BY events_type_time":t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'events_subject_time'").get()?"INDEXED BY events_subject_time":"",o=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
82
84
  FROM claims WHERE valid_from <= ? AND valid_to >= ?`),i=new Map,a=t.prepare(`
83
85
  SELECT subject_id FROM events WHERE subject_type = 'execution' AND occurred_at >= ? AND occurred_at < ?
84
86
  UNION
@@ -88,53 +90,307 @@ CREATE INDEX IF NOT EXISTS claims_subject_window ON claims(subject_type, valid_t
88
90
  SELECT 1 FROM events n WHERE n.subject_type = 'execution' AND n.subject_id = z.subject_id
89
91
  AND n.occurred_at > z.occurred_at AND n.occurred_at < ? AND n.kind IN ('progressed','blocked','resumed')))
90
92
  ORDER BY z.occurred_at DESC LIMIT 1) IS NULL`),c=t.prepare(`SELECT * FROM events
91
- WHERE subject_type = 'execution' AND subject_id = ? AND occurred_at < ? ORDER BY occurred_at, id`);return{executionCarry(u,d){const l=[];for(const m of a.all(u,d,u,u,u)){const p=String(m.subject_id);l.push(...c.all(p,u).map(e))}return l.sort((m,p)=>m.occurredAt-p.occurredAt||m.id.localeCompare(p.id))},subjectEvents(u,d){return t.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(u,d).map(e)},query(u,d,l){if(!l||l.length===0)return r.all(u,d).map(e);const m=[...l].sort().join(",");let p=n.get(m);if(!p){const h=l.map(()=>"?").join(",");p=t.prepare(`SELECT * FROM events ${o}
93
+ WHERE subject_type = 'execution' AND subject_id = ? AND occurred_at < ? ORDER BY occurred_at, id`);return{executionCarry(u,l){const d=[];for(const m of a.all(u,l,u,u,u)){const p=String(m.subject_id);d.push(...c.all(p,u).map(e))}return d.sort((m,p)=>m.occurredAt-p.occurredAt||m.id.localeCompare(p.id))},subjectEvents(u,l){return t.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(u,l).map(e)},query(u,l,d){if(!d||d.length===0)return Array.from(ci(r,u,l),e);const m=[...d].sort().join(",");let p=n.get(m);if(!p){const h=d.map(()=>"?").join(",");p=t.prepare(`SELECT * FROM events ${s}
92
94
  WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${h})
93
- ORDER BY occurred_at, id`),n.set(m,p)}return p.all(u,d,...l).map(e)},claims(u,d,l){let m;if(l?.length){const p=[...l].sort().join(",");let h=i.get(p);if(!h){const v=l.map(()=>"?").join(",");h=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
95
+ ORDER BY occurred_at, id`),n.set(m,p)}return Array.from(ci(p,u,l,...d),e)},claims(u,l,d){let m;if(d?.length){const p=[...d].sort().join(",");let h=i.get(p);if(!h){const g=d.map(()=>"?").join(",");h=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
94
96
  FROM claims INDEXED BY claims_key WHERE key IN (
95
- SELECT key FROM claims WHERE subject_type IN (${v}) AND valid_from <= ? AND valid_to >= ?
96
- ) AND valid_from <= ? AND valid_to >= ?`),i.set(p,h)}m=h.all(...l,d,u,d,u)}else m=s.all(d,u);return m.map(p=>{const h=p;return{key:String(h.key),subjectType:h.subject_type,subjectId:String(h.subject_id),sourceId:String(h.source_id),validFrom:Number(h.valid_from),validTo:Number(h.valid_to)}})},stats(){const u=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),d=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),l=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),m=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
97
- FROM events GROUP BY source_id ORDER BY s`).all().map(p=>{const h=p;return{source:String(h.s),events:Number(h.c),first:Number(h.lo),last:Number(h.hi)}});return{events:u,claims:d,bySource:m,earliest:l.lo,latest:l.hi}},begansFor(u){const d=[],l=t.prepare(`SELECT * FROM events
97
+ SELECT key FROM claims WHERE subject_type IN (${g}) AND valid_from <= ? AND valid_to >= ?
98
+ ) AND valid_from <= ? AND valid_to >= ?`),i.set(p,h)}m=ci(h,...d,l,u,l,u)}else m=ci(o,l,u);return Array.from(m,p=>{const h=p;return{key:String(h.key),subjectType:h.subject_type,subjectId:String(h.subject_id),sourceId:String(h.source_id),validFrom:Number(h.valid_from),validTo:Number(h.valid_to)}})},stats(){const u=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),l=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),d=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),m=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
99
+ FROM events GROUP BY source_id ORDER BY s`).all().map(p=>{const h=p;return{source:String(h.s),events:Number(h.c),first:Number(h.lo),last:Number(h.hi)}});return{events:u,claims:l,bySource:m,earliest:d.lo,latest:d.hi}},begansFor(u){const l=[],d=t.prepare(`SELECT * FROM events
98
100
  WHERE kind = 'began' AND subject_type = ? AND subject_id = ?
99
- ORDER BY occurred_at, id`);for(const m of u){const p=m.indexOf(":");if(p<0)continue;const h=l.all(m.slice(0,p),m.slice(p+1));for(const v of h)d.push(e(v))}return d}}}function Hy(t){const[e,r,n]=va(t).map(oS);return{db:e,wal:r,shm:n,total:e+r+n}}function oS(t){try{return fa(t).size}catch{return 0}}function fi(t,e,r){if(t!=null)try{const n=JSON.parse(String(t));if(n&&typeof n=="object")return n;e&&r?.(e);return}catch{e&&r?.(e);return}}function Fy(t,e){const r=t,n=e?o=>e(o,String(r.id)):void 0;return{id:String(r.id),source:{id:String(r.source_id),instance:String(r.source_instance)},occurredAt:Number(r.occurred_at),observedAt:Number(r.observed_at),clock:r.clock,kind:r.kind,subject:{type:r.subject_type,id:String(r.subject_id)},core:fi(r.core,"core",n),attrs:fi(r.attrs,"attrs",n),basis:r.basis,assumption:r.assumption?String(r.assumption):void 0,stratum:r.stratum?r.stratum:void 0,provenance:fi(r.provenance,"provenance",n)}}const fp={tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"};function Wy(t){const e=new Map;for(const s of t.declarations)s.kind==="began"&&e.set(`${s.subject.type}:${s.subject.id}`,s);const r=[...t.state.executions.values()].map(s=>sS(s,t,e)).sort((s,i)=>s.start.at-i.start.at||s.ref.localeCompare(i.ref)),n=new Set(r.map(s=>s.ref)),o=[...t.state.sessions.values()].map(s=>({ref:Cr("session",s.id),executionRefs:s.executionIds.map(i=>Cr("execution",i)).filter(i=>n.has(i)).sort(),spawnedBy:s.parentId?it({ref:Cr("session",s.parentId)}):un("no parent session was reported")})).filter(s=>s.executionRefs.length>0).sort((s,i)=>s.ref.localeCompare(i.ref));return{experimental:!0,window:{from:t.from,to:t.to},executions:r,sessions:o,summary:dS(r,o,t.from,t.to,rd(t.state))}}function sS(t,e,r){const n=r.get(`execution:${t.id}`),o=n?.source.id,s=o?e.capabilities.get(o)??fp:fp,i=e.state.sessions.get(t.sessionId),a=e.state.machines.get(t.machineId),c=t.status==="completed"||t.status==="failed",u=aS(n?.occurredAt??t.startedAt,n?.basis??t.startBasis),d=e.relationships.filter(h=>h.kind==="ran-as"&&(h.from.type==="execution"&&h.from.id===t.id&&h.to.type==="process"||h.to.type==="execution"&&h.to.id===t.id&&h.from.type==="process")).map(h=>{const v=h.from.type==="process"?h.from:h.to;return{kind:"ran-as",target:{type:"process",ref:Cr("process",v.id)},evidence:iS(h.basis),...h.basis==="inferred"?{qualification:"resolved from overlapping identity claims"}:{}}}).sort((h,v)=>h.target.ref.localeCompare(v.target.ref)),l=i?.context,m=t.model??i?.model,p={current:t.status==="waiting",...t.waitReason?{reason:t.waitReason}:{},count:t.waits.length+(t.waitingSince===void 0?0:1),durationMs:t.waitingMs+(t.waitingSince===void 0?0:Math.max(0,e.to-t.waitingSince))};return{ref:Cr("execution",t.id),observer:o??"unknown-observer",sessionRef:Cr("session",t.sessionId),machine:t.machineId?it({ref:Cr("machine",t.machineId),...a?{kind:a.kind}:{}}):un("no machine was reported"),context:l?fu(s.context,{ref:Cr("context",l)},"context"):pi(s.context,"context"),executor:t.executor&&t.executor!=="unknown"?it(t.executor):un("no executor was reported"),model:m?fu(s.model,m,"model"):pi(s.model,"model"),start:u,end:t.endedAt===void 0?mr(e.to,"the execution is open; query time is an elapsed wall bound, not a terminal end"):t.endBasis==="inferred"?hs(t.endedAt,"the terminal bound was inferred by its observer"):it(t.endedAt),lifecycle:cS(t),outcome:uS(t,s.outcome),measures:{tokens:{input:Or(t,Z.tokensInput,s.tokens,c,!1,"token input"),output:Or(t,Z.tokensOutput,s.tokens,c,!1,"token output"),cacheRead:Or(t,Z.tokensCacheRead,s.tokens,c,!1,"cache-read tokens"),reasoning:Or(t,Z.tokensReasoning,s.tokens,c,!1,"reasoning tokens"),total:Ky(jr(t.measures),s.tokens,c,!1,"token total")},requests:Or(t,Z.steps,s.requests,c,!0,"requests"),toolInteractions:Or(t,Z.interactions,s.toolInteractions,c,!0,"tool interactions"),toolErrors:Or(t,Z.errors,s.toolErrors,c,!0,"tool errors"),retries:Or(t,Z.retries,s.retries,c,!0,"retries")},wait:lS(p,s.waits,c),failure:t.status==="failed"?it("execution-failed"):c?s.outcome==="supported"?it("none"):pi(s.outcome,"failure state"):Ht("the execution is not terminal"),depth:t.depth,relationships:d}}function Cr(t,e){const r=fo("sha256").update(`057-activity\0${t}\0${e}`).digest("hex").slice(0,16);return`${t}_${r}`}function iS(t){return t==="inferred"?"inferred":"observed"}function aS(t,e){return e==="inferred"?{at:t,evidence:"inferred",qualification:"the observer inferred this temporal bound"}:e===void 0?{at:t,evidence:"inferred",qualification:"a legacy record did not declare its timing basis"}:{at:t,evidence:"observed"}}function cS(t){return t.status==="waiting"?{state:"waiting",evidence:"observed"}:t.status==="running"?{state:"running",evidence:"observed"}:t.status==="idle"?{state:"idle",evidence:"inferred",qualification:"no activity was observed for the idle threshold"}:{state:"terminal",evidence:t.endBasis==="inferred"?"inferred":"observed",...t.endBasis==="inferred"?{qualification:"the observer inferred the terminal bound"}:{}}}function uS(t,e){if(t.status!=="completed"&&t.status!=="failed")return Ht("the execution is not terminal");const r=t.outcome==="error"?"failed":t.outcome==="interrupted"?"interrupted":t.outcome==="completed"?"completed":void 0;return r?t.endBasis==="inferred"?hs(r,"the terminal outcome follows an inferred terminal bound"):fu(e,r,"outcome"):pi(e,"outcome")}function Or(t,e,r,n,o,s){return Ky(vt(t.measures,e),r,n,o,s)}function Ky(t,e,r,n,o){return e==="unsupported"?In(`this observer does not report ${o}`):e==="unknown"?Ht(`coverage for ${o} is not declared`):e==="partial"?mr(t,`this observer reports ${o} only partially`):r?t!==void 0?it(t):n?it(0):un(`${o} was not present in this execution`):mr(t,`${o} may still increase while the execution is active`)}function lS(t,e,r){return e==="unsupported"?In("this observer does not report explicit waits"):e==="unknown"?Ht("wait coverage is not declared"):e==="partial"?mr(t,"this observer reports explicit waits only partially"):!r||t.current?mr(t,"an explicit wait may still be open"):it(t)}function fu(t,e,r){return t==="supported"?it(e):t==="partial"?mr(e,`this observer reports ${r} only partially`):t==="unsupported"?In(`this observer does not report ${r}`):Ht(`coverage for ${r} is not declared`)}function pi(t,e){return t==="supported"?un(`${e} was not present in this execution`):t==="partial"?mr(void 0,`this observer reports ${e} only partially`):t==="unsupported"?In(`this observer does not report ${e}`):Ht(`coverage for ${e} is not declared`)}function it(t){return{state:"observed",value:t}}function hs(t,e){return{state:"inferred",value:t,qualification:e}}function mr(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function In(t){return{state:"unsupported",qualification:t}}function un(t){return{state:"not-observed",qualification:t}}function Ht(t){return{state:"unknown",qualification:t}}function dS(t,e,r,n,o){const s=t.map(h=>({start:Math.max(r,h.start.at),end:Math.min(n,yt(h.end)??n),inferred:h.start.evidence==="inferred"||h.end.state==="inferred",partial:h.end.state!=="observed"&&h.end.state!=="inferred"})),i=rn(s.map(h=>h.partial?"partial":h.inferred?"inferred":"observed")),a=mp(s),c=yp(s),u=t.filter(h=>h.lifecycle.state==="terminal"),d=u.flatMap(h=>{const v=yt(h.end);return v===void 0?[]:[{start:Math.max(r,h.start.at),end:Math.min(n,v),inferred:h.start.evidence==="inferred"||h.end.state==="inferred"}]}),l=rn(u.map(h=>yt(h.end)===void 0?"unknown":h.start.evidence==="inferred"||h.end.state==="inferred"?"inferred":"observed")),m=mp(d),p=rn(t.map(h=>h.lifecycle.state==="terminal"?"inferred":"partial"));return{executions:t.length,sessions:e.length,openExecutions:t.length-u.length,terminalExecutions:u.length,runningNow:t.filter(h=>h.lifecycle.state==="running").length,waitingNow:Pn(t.map(fS)),idleNow:t.filter(h=>h.lifecycle.state==="idle").length,completed:jc(u,"completed"),failed:jc(u,"failed"),interrupted:jc(u,"interrupted"),inFlight:{totalMs:pt(o.timeInFlight.value,p),openContributionMs:pt(Math.max(0,o.timeInFlight.value-m),p),parallelMs:pt(o.parallelTime.value,p),peak:pt({peak:o.peakConcurrency.value,at:o.peakConcurrency.value>0?o.peakConcurrencyAt.value:null},p),assumption:my},executionWallIntervalMs:pt(a,i),peakExecutionConcurrency:pt(c,i),executionDuration:Mc(t.map(h=>{const v=yt(h.end)??n,g=Math.max(0,v-h.start.at);return h.end.state!=="observed"&&h.end.state!=="inferred"?mr(g,"elapsed wall duration for an open execution"):h.start.evidence==="inferred"||h.end.state==="inferred"?hs(g,"one or more execution bounds were inferred"):it(g)})),terminalExecutionDuration:Mc(u.map(h=>{const v=yt(h.end);if(v===void 0)return Ht("the terminal execution has no usable end bound");const g=Math.max(0,v-h.start.at);return h.start.evidence==="inferred"||h.end.state==="inferred"?hs(g,"one or more execution bounds were inferred"):it(g)})),terminalExecutionIntervalMs:pt(m,l),overlappingTerminalIntervalMs:pt(mS(d),l),peakTerminalConcurrency:pt(yp(d),l),sessionExecutionCount:Mc(e.map(h=>it(h.executionRefs.length))),tokens:Pn(t.map(h=>h.measures.tokens.total)),toolInteractions:Pn(t.map(h=>h.measures.toolInteractions)),toolErrors:Pn(t.map(h=>h.measures.toolErrors)),waits:pS(t.map(h=>h.wait)),usageByModel:hS(t),executionsWithoutModel:t.filter(h=>yt(h.model)===void 0).length,modelMix:hp(t,h=>pp(h.model)),executorMix:hp(t,h=>pp(h.executor))}}function yt(t){return"value"in t?t.value:void 0}function pp(t){return yt(t)??`[${t.state}]`}function rn(t){const e={records:t.length,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0};for(const r of t)r==="not-observed"?e.notObserved++:e[r]++;return e}function pt(t,e){return e.partial+e.unsupported+e.notObserved+e.unknown>0?{state:"partial",value:t,qualification:"coverage is incomplete",coverage:e}:e.inferred>0?{state:"inferred",value:t,qualification:"one or more bounds were inferred",coverage:e}:{state:"observed",value:t,coverage:e}}function Pn(t){const e=rn(t.map(o=>o.state));let r=0,n=0;for(const o of t){const s=yt(o);s!==void 0&&(r+=s,n++)}return n>0?pt(r,e):e.records>0&&e.unsupported===e.records?{...In("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...un("no value was observed"),coverage:e}:{...Ht("no usable value was observed"),coverage:e}}function Mc(t){const e=rn(t.map(n=>n.state)),r=t.map(yt).filter(n=>n!==void 0).sort((n,o)=>n-o);return r.length===0?{...Ht("no usable duration samples were observed"),coverage:e}:pt({samples:r.length,minimum:r[0],median:_c(r,.5),p75:_c(r,.75),p90:_c(r,.9),maximum:r[r.length-1]},e)}function _c(t,e){const r=(t.length-1)*e,n=Math.floor(r),o=Math.ceil(r);return n===o?t[n]:t[n]+(t[o]-t[n])*(r-n)}function fS(t){const e=yt(t.wait);return Gy(t.wait,e?.current?1:0)}function jc(t,e){return t.length===0?pt(0,rn([])):Pn(t.map(r=>{const n=yt(r.outcome);return Gy(r.outcome,n===e?1:0)}))}function Gy(t,e){switch(t.state){case"observed":return it(e);case"inferred":return hs(e,t.qualification);case"partial":return mr("value"in t?e:void 0,t.qualification);case"unsupported":return In(t.qualification);case"not-observed":return un(t.qualification);case"unknown":return Ht(t.qualification)}}function pS(t){const e=rn(t.map(o=>o.state));let r=0;const n={count:0,durationMs:0,openNow:0};for(const o of t){const s=yt(o);s&&(r++,n.count+=s.count,n.durationMs+=s.durationMs,s.current&&n.openNow++)}return r>0?pt(n,e):e.unsupported===e.records?{...In("no observer reports explicit waits"),coverage:e}:{...Ht("no usable wait value was observed"),coverage:e}}function hS(t){const e=new Map;for(const r of t){const n=yt(r.model);if(!n)continue;const o=e.get(n)??[];o.push(r.measures.tokens.total),e.set(n,o)}return[...e.entries()].map(([r,n])=>({model:r,executions:n.length,tokens:Pn(n)})).sort((r,n)=>n.executions-r.executions||r.model.localeCompare(n.model))}function hp(t,e){const r=new Map;for(const n of t){const o=e(n);r.set(o,(r.get(o)??0)+1)}return[...r.entries()].map(([n,o])=>({key:n,executions:o})).sort((n,o)=>o.executions-n.executions||n.key.localeCompare(o.key))}function mp(t){const e=t.filter(s=>s.end>s.start).map(s=>({start:s.start,end:s.end})).sort((s,i)=>s.start-i.start||s.end-i.end);let r=0,n,o=0;for(const s of e)n===void 0?(n=s.start,o=s.end):s.start<=o?o=Math.max(o,s.end):(r+=o-n,n=s.start,o=s.end);return r+(n===void 0?0:o-n)}function yp(t){const e=[];for(const s of t)s.end<=s.start||e.push({at:s.start,delta:1},{at:s.end,delta:-1});e.sort((s,i)=>s.at-i.at||s.delta-i.delta);let r=0,n=0,o=null;for(const s of e)r+=s.delta,r>n&&(n=r,o=s.at);return{peak:n,at:o}}function mS(t){const e=[];for(const s of t)s.end<=s.start||e.push({at:s.start,delta:1},{at:s.end,delta:-1});e.sort((s,i)=>s.at-i.at||s.delta-i.delta);let r=0,n,o=0;for(const s of e)n!==void 0&&r>=2&&(o+=s.at-n),r+=s.delta,n=s.at;return o}function ms(t,e){const r=t.window,n=It(e.continuity),o=e.continuity.state==="observed"&&n!==void 0&&n.from<=r.from&&n.to>=r.to,s=e.retention.state==="within-retention"||e.retention.state==="retained-indefinitely",i=t.executions.length,a=[];let c,u;s?o?(c="observed",u="comparable"):i>0?(c="partially-observed",u="partially-comparable",a.push("execution records are present, but historical observation continuity is unknown")):(c="unknown",u="not-comparable",a.push("zero execution records cannot distinguish a quiet period from an unobserved period")):(c="not-sufficiently-observed",u="not-comparable",a.push("the requested period is not wholly inside semantic retention"));const d=t.executions.map(g=>g.start.at),l=t.executions.map(g=>It(g.end)??g.start.at),m=i>0?dr({from:Math.min(...d),to:Math.max(...l)}):hr("no execution records establish an observed span"),p=new Map;for(const g of t.executions){const I=p.get(g.observer)??[];I.push(g),p.set(g.observer,I)}const h=[...p.entries()].map(([g,I])=>({source:g,executionRecords:I.length,firstExecutionAt:Math.min(...I.map(N=>N.start.at)),lastExecutionAt:Math.max(...I.map(N=>N.start.at)),capabilities:e.capabilities.get(g)??kS()})).sort((g,I)=>I.executionRecords-g.executionRecords||g.source.localeCompare(I.source)),v=[Co("tokens",t.summary.tokens),Co("tool-interactions",t.summary.toolInteractions),Co("tool-errors",t.summary.toolErrors),Co("waits",t.summary.waits),Dc("outcomes",t.executions.map(g=>g.outcome)),Co("bounds",SS(t.executions)),Dc("model",t.executions.map(g=>g.model)),Dc("executor",t.executions.map(g=>g.executor))];return{experimental:!0,period:r,observation:c,recordPresence:i>0?"present":"none",executionRecords:i,sessionRecords:t.sessions.length,continuity:e.continuity,observationGaps:o?dr([]):hr("historical observation gaps are not retained"),unprojectedSourceWork:hr("observers do not currently retain counts for source work omitted before a timed execution could be projected"),retention:e.retention,observedSpan:m,sources:h,measures:v,bounds:{observedStarts:t.executions.filter(g=>g.start.evidence==="observed").length,inferredStarts:t.executions.filter(g=>g.start.evidence==="inferred").length,observedEnds:t.executions.filter(g=>g.end.state==="observed").length,inferredEnds:t.executions.filter(g=>g.end.state==="inferred").length,openEnds:t.executions.filter(g=>g.end.state!=="observed"&&g.end.state!=="inferred").length},comparisonReadiness:u,reasons:a}}function yS(t,e){const r=ms(t,e),n=r.comparisonReadiness==="not-comparable"?gS(t.summary):t.summary;return{experimental:!0,period:t.window,availability:r,summary:n}}function gS(t){const e=r=>({state:"unknown",qualification:"the period was not sufficiently observed",coverage:r.coverage});return{...t,waitingNow:e(t.waitingNow),completed:e(t.completed),failed:e(t.failed),interrupted:e(t.interrupted),inFlight:{...t.inFlight,totalMs:e(t.inFlight.totalMs),openContributionMs:e(t.inFlight.openContributionMs),parallelMs:e(t.inFlight.parallelMs),peak:e(t.inFlight.peak)},executionWallIntervalMs:e(t.executionWallIntervalMs),peakExecutionConcurrency:e(t.peakExecutionConcurrency),executionDuration:e(t.executionDuration),terminalExecutionDuration:e(t.terminalExecutionDuration),terminalExecutionIntervalMs:e(t.terminalExecutionIntervalMs),overlappingTerminalIntervalMs:e(t.overlappingTerminalIntervalMs),peakTerminalConcurrency:e(t.peakTerminalConcurrency),sessionExecutionCount:e(t.sessionExecutionCount),tokens:e(t.tokens),toolInteractions:e(t.toolInteractions),toolErrors:e(t.toolErrors),waits:e(t.waits),usageByModel:t.usageByModel.map(r=>({...r,tokens:e(r.tokens)}))}}function vS(t,e,r){const n=new Map;for(const s of t.executions){const i=bS(s,r),a=n.get(i)??[];a.push(s),n.set(i,a)}const o=[...n.entries()].map(([s,i])=>wS(s,i)).sort((s,i)=>i.executions-s.executions||s.key.localeCompare(i.key));return{experimental:!0,period:t.window,dimension:r,availability:ms(t,e),items:o,qualification:r==="model"||r==="executor"?"Observed differences describe grouped records; they do not establish causal performance differences.":"Breakdown counts only privacy-reduced execution records present in this period."}}function qy(t,e,r,n){const o=ms(t,e),s=ms(r,n),i=AS(o.comparisonReadiness,s.comparisonReadiness),a=t.window.to-t.window.from===r.window.to-r.window.from,c=a?i:"not-comparable",u=[...o.reasons.map(l=>`period A: ${l}`),...s.reasons.map(l=>`period B: ${l}`),...a?[]:["the requested periods do not have equal duration"]],d=[$o("execution records",ei(t.executions.length,o),ei(r.executions.length,s),c),$o("session records",ei(t.sessions.length,o),ei(r.sessions.length,s),c),Rt("median terminal execution duration",vp(t.summary.terminalExecutionDuration),vp(r.summary.terminalExecutionDuration),c,o,s),Rt("terminal execution interval union",t.summary.terminalExecutionIntervalMs,r.summary.terminalExecutionIntervalMs,c,o,s),Rt("overlapping terminal interval",t.summary.overlappingTerminalIntervalMs,r.summary.overlappingTerminalIntervalMs,c,o,s),Rt("peak terminal concurrency",Bo(t.summary.peakTerminalConcurrency,l=>l.peak),Bo(r.summary.peakTerminalConcurrency,l=>l.peak),c,o,s),$o("model mix",Un(dr(ti(t.summary.modelMix)),o),Un(dr(ti(r.summary.modelMix)),s),c),$o("executor mix",Un(dr(ti(t.summary.executorMix)),o),Un(dr(ti(r.summary.executorMix)),s),c),Rt("completed executions",t.summary.completed,r.summary.completed,c,o,s),Rt("failed executions",t.summary.failed,r.summary.failed,c,o,s),Rt("interrupted executions",t.summary.interrupted,r.summary.interrupted,c,o,s),Rt("tokens",t.summary.tokens,r.summary.tokens,c,o,s),Rt("tool interactions",t.summary.toolInteractions,r.summary.toolInteractions,c,o,s),Rt("tool errors",t.summary.toolErrors,r.summary.toolErrors,c,o,s),Rt("explicit wait count",Bo(t.summary.waits,l=>l.count),Bo(r.summary.waits,l=>l.count),c,o,s)];return{experimental:!0,eligibility:c,periodA:t.window,periodB:r.window,availabilityA:o,availabilityB:s,dimensions:d,reasons:u}}function bS(t,e){switch(e){case"model":return It(t.model)??`[${t.model.state}]`;case"executor":return It(t.executor)??`[${t.executor.state}]`;case"lifecycle":return t.lifecycle.state;case"outcome":return t.lifecycle.state==="terminal"?It(t.outcome)??"unknown":"open";case"session":return t.sessionRef;case"duration-band":{if(t.lifecycle.state!=="terminal")return"open";const r=It(t.end);if(r===void 0)return"[unknown-duration]";const n=Math.max(0,r-t.start.at);return n<6e4?"under-1m":n<3e5?"1m-to-5m":n<18e5?"5m-to-30m":"30m-or-more"}}}function wS(t,e){const r=e.filter(n=>n.lifecycle.state==="terminal");return{key:t,executions:e.length,terminalExecutions:r.length,terminalDuration:xS(r.map(n=>{const o=It(n.end);if(o===void 0)return hr("the terminal execution has no usable end bound");const s=Math.max(0,o-n.start.at);return n.start.evidence==="inferred"||n.end.state==="inferred"?Yy(s,"one or more execution bounds were inferred"):dr(s)})),tokens:ri(e.map(n=>n.measures.tokens.total)),toolInteractions:ri(e.map(n=>n.measures.toolInteractions)),toolErrors:ri(e.map(n=>n.measures.toolErrors)),failed:ri(r.map(n=>ES(n.outcome,"failed")))}}function ei(t,e){return e.observation==="observed"?dr(t):e.executionRecords>0?Xy(t,"record count is known, but observation continuity is not"):hr("the period was not sufficiently observed to interpret zero records as zero work")}function Rt(t,e,r,n,o,s){return $o(t,Un(e,o),Un(r,s),n)}function Un(t,e){return e.comparisonReadiness==="not-comparable"?hr("the period was not sufficiently observed"):t}function $o(t,e,r,n){const o=It(e)!==void 0&&It(r)!==void 0;let s;const i=[];return n==="not-comparable"?(s="not-comparable",i.push("one or both periods are not sufficiently observed")):!o||gp(e.state)||gp(r.state)?(s="not-comparable",i.push(`measure states are ${e.state} and ${r.state}`)):n==="partially-comparable"||e.state==="partial"||r.state==="partial"||e.state==="inferred"||r.state==="inferred"?(s="partially-comparable",i.push("the values are present, but period or measure coverage is qualified")):s="comparable",{dimension:t,eligibility:s,periodA:e,periodB:r,reasons:i}}function gp(t){return t==="unsupported"||t==="not-observed"||t==="unknown"}function AS(t,e){return t==="not-comparable"||e==="not-comparable"?"not-comparable":t==="partially-comparable"||e==="partially-comparable"?"partially-comparable":"comparable"}function vp(t){return Bo(t,e=>e.median)}function Bo(t,e){switch(t.state){case"observed":return{state:"observed",value:e(t.value),coverage:t.coverage};case"inferred":return{state:"inferred",value:e(t.value),qualification:t.qualification,coverage:t.coverage};case"partial":return"value"in t&&t.value!==void 0?{state:"partial",value:e(t.value),qualification:t.qualification,coverage:t.coverage}:{state:"partial",qualification:t.qualification,coverage:t.coverage};case"unsupported":return{...t};case"not-observed":return{...t};case"unknown":return{...t}}}function ti(t){return Object.fromEntries(t.map(e=>[e.key,e.executions]))}function Co(t,e){return{dimension:t,state:e.state,coverage:e.coverage,qualification:zy(e.state)}}function Dc(t,e){const r=Aa(e.map(o=>o.state)),n=IS(r);return{dimension:t,state:n,coverage:r,qualification:zy(n)}}function SS(t){const e=t.map(r=>r.end.state!=="observed"&&r.end.state!=="inferred"?"partial":r.start.evidence==="inferred"||r.end.state==="inferred"?"inferred":"observed");return fd(e.length,Aa(e))}function zy(t){switch(t){case"observed":return"all contributing records are observed for this dimension";case"inferred":return"one or more contributing values were inferred";case"partial":return"a subtotal is available, but one or more records are incomplete";case"unsupported":return"the contributing observers do not support this dimension";case"not-observed":return"the dimension is supported but no value was recorded";case"unknown":return"coverage cannot be established"}}function kS(){return{tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"}}function ES(t,e){const r=It(t);return CS(t,r===e?1:0)}function ri(t){const e=Aa(t.map(n=>n.state)),r=t.map(It).filter(n=>n!==void 0);return r.length>0?fd(r.reduce((n,o)=>n+o,0),e):e.records>0&&e.unsupported===e.records?{...Jy("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...Zy("no value was observed"),coverage:e}:{...hr("no usable value was observed"),coverage:e}}function xS(t){const e=Aa(t.map(n=>n.state)),r=t.map(It).filter(n=>n!==void 0).sort((n,o)=>n-o);return r.length===0?{...hr("no terminal duration samples were observed"),coverage:e}:fd({samples:r.length,minimum:r[0],median:Lc(r,.5),p75:Lc(r,.75),p90:Lc(r,.9),maximum:r[r.length-1]},e)}function Lc(t,e){const r=(t.length-1)*e,n=Math.floor(r),o=Math.ceil(r);return n===o?t[n]:t[n]+(t[o]-t[n])*(r-n)}function fd(t,e){return e.partial+e.unsupported+e.notObserved+e.unknown>0?{state:"partial",value:t,qualification:"coverage is incomplete",coverage:e}:e.inferred>0?{state:"inferred",value:t,qualification:"one or more values were inferred",coverage:e}:{state:"observed",value:t,coverage:e}}function IS(t){return t.records===0?"unknown":t.unsupported===t.records?"unsupported":t.notObserved===t.records?"not-observed":t.unknown===t.records?"unknown":t.partial+t.unsupported+t.notObserved+t.unknown>0?"partial":t.inferred>0?"inferred":"observed"}function Aa(t){const e=OS();e.records=t.length;for(const r of t)r==="not-observed"?e.notObserved++:e[r]++;return e}function OS(){return{records:0,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0}}function It(t){return"value"in t?t.value:void 0}function CS(t,e){switch(t.state){case"observed":return dr(e);case"inferred":return Yy(e,t.qualification);case"partial":return Xy("value"in t?e:void 0,t.qualification);case"unsupported":return Jy(t.qualification);case"not-observed":return Zy(t.qualification);case"unknown":return hr(t.qualification)}}function dr(t){return{state:"observed",value:t}}function Yy(t,e){return{state:"inferred",value:t,qualification:e}}function Xy(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function Jy(t){return{state:"unsupported",qualification:t}}function Zy(t){return{state:"not-observed",qualification:t}}function hr(t){return{state:"unknown",qualification:t}}const Jr="os",NS=(t,e)=>`os:${t}:${e.pid}:${e.startedAt}`;function TS(t,e){const r=/^os:[^:]+:(\d+):(\d+)$/.exec(t);return r?`os:${e}:${r[1]}:${r[2]}`:void 0}const $S=t=>`The process was present in one ${Math.round(t/1e3)}s snapshot and absent from the next, so it exited somewhere in that window. The recorded instant is the last moment it was observed alive — a lower bound on the true exit. A process that started and exited entirely within one interval is never observed at all.`,BS=250,RS=8*1024*1024;function MS(t,e,r){const n={source:{id:Jr,instance:r.host},observedAt:r.observedAt,clock:"wall",stratum:"machine"},o=[],s=new Map;for(const i of e){const a=NS(r.host,i);s.set(a,i);const c={ns:"os.process",parts:[r.host,i.pid],validFrom:i.startedAt,validTo:r.observedAt};if(!t.has(a)){o.push({...n,occurredAt:i.startedAt,kind:"began",subject:{type:"process",id:a},claims:[c],basis:"measured",core:{machineId:r.machineId,label:_S(i.command),executor:i.command,measures:{[Z.cpuMs]:i.cpuMs}},attrs:{"os.pid":i.pid,"os.ppid":i.ppid,"os.command":i.command,"os.rssBytes":i.rssBytes}});continue}const u=t.get(a),d=i.cpuMs-u.cpuMs>=BS,l=Math.abs(i.rssBytes-u.rssBytes)>=RS;(d||l)&&o.push({...n,occurredAt:r.observedAt,seq:`obs:${r.observedAt}`,kind:"observed",subject:{type:"process",id:a},claims:[c],basis:"measured",core:{measures:{[Z.cpuMs]:i.cpuMs}},attrs:{"os.rssBytes":i.rssBytes}})}for(const[i,a]of t)s.has(i)||o.push({...n,occurredAt:r.observedAt-r.intervalMs,kind:"ended",subject:{type:"process",id:i},basis:"inferred",assumption:$S(r.intervalMs),core:{outcome:"completed",measures:{[Z.cpuMs]:a.cpuMs}},attrs:{"os.pid":a.pid}});return{envelopes:o,next:s}}function _S(t){return(t.split("/").pop()??t).toUpperCase()}function Qy(t,e,r,n,o){const s=o?tg(o):void 0,i=t.query(e,r,n),a=i.filter(S=>S.occurredAt<r),c=i.filter(S=>S.occurredAt===r&&S.subject.type==="execution"&&S.kind==="ended"),u=s?Vn(a,s):a,d=!n||n.includes("execution")?t.executionCarry(e,r):[],l=s?Vn(d,s):d,m=new Set,p=new Set,h=new Map,v=S=>{const T=`${S.subject.type}:${S.subject.id}`;S.kind==="began"?(m.add(T),h.set(T,S)):p.add(T),S.core?.sessionId&&p.add(`session:${S.core.sessionId}`),S.core?.machineId&&p.add(`machine:${S.core.machineId}`)};for(const S of[...l,...u,...c])v(S);const g=[];for(let S=0;S<4;S++){const T=[...p].filter(w=>!m.has(w));if(T.length===0)break;const x=t.begansFor(T).filter(w=>w.occurredAt<=r),D=s?Vn(x,s):x;if(D.length===0)break;for(const w of D)h.set(`${w.subject.type}:${w.subject.id}`,w),g.push(w),v(w),m.add(`${w.subject.type}:${w.subject.id}`)}const I=S=>S.occurredAt<e?{...S,occurredAt:e}:S;return{events:[...g.map(I),...l.filter(S=>S.kind==="began").map(I),...u].sort((S,T)=>S.occurredAt-T.occurredAt||Qn(S)-Qn(T)),inWindow:u,history:[...g.filter(S=>S.occurredAt<e),...l],rightBounds:s?Vn(c,s):c,declarations:[...h.values()],relationships:Yb(t.claims(e,r,n)).relationships}}function eg(t,e,r,n,o){const s=performance.now(),{events:i,inWindow:a,history:c,rightBounds:u,declarations:d,relationships:l}=Qy(t,e,r,o,n),m=performance.now()-s,p=performance.now(),h=Ql(e,r);py(h,[...c,...i,...u].sort((T,x)=>T.occurredAt-x.occurredAt||Qn(T)-Qn(x))),hy(h,r);const v=new Set(a.filter(T=>T.subject.type==="execution").map(T=>T.subject.id)),g=new Map;for(const T of a){if(T.subject.type!=="execution"||!T.core?.measures)continue;const x=g.get(T.subject.id)??{};cs(x,T.core.measures),g.set(T.subject.id,x)}const I=new Map;for(const T of h.executions.values()){if(!v.has(T.id)&&T.status!=="waiting"&&T.status!=="running"&&T.endedAt!==r||T.startedAt>=r)continue;const x=T.waits.map(D=>({start:Math.max(e,D.start),end:Math.min(r,D.end)})).filter(D=>D.end>D.start);I.set(T.id,{...T,measures:g.get(T.id)??{},waits:x,waitingMs:x.reduce((D,w)=>D+w.end-w.start,0),waitingSince:T.waitingSince===void 0?void 0:Math.max(e,T.waitingSince)})}h.executions=I,h.active=new Set([...h.active].filter(T=>I.has(T)));const N=new Set(a.flatMap(T=>T.subject.type==="session"?[T.subject.id]:T.core?.sessionId?[T.core.sessionId]:[]));for(const T of h.sessions.values())T.executionIds=T.executionIds.filter(x=>I.has(x)),T.executionIds.length===0&&!N.has(T.id)&&h.sessions.delete(T.id);const S=performance.now()-p;return{state:h,events:i,declarations:d,relationships:l,meta:{events:i.length,readMs:Math.round(m*10)/10,deriveMs:Math.round(S*10)/10}}}function jS(t,e,r,n){const o=n?tg(n):void 0,s=t.subjectEvents("execution",e).filter(d=>d.occurredAt<=r),i=o?Vn(s,o):s,a=new Set;for(const d of i)d.core?.sessionId&&a.add(`session:${d.core.sessionId}`),d.core?.machineId&&a.add(`machine:${d.core.machineId}`);let c=t.begansFor([...a]).filter(d=>d.occurredAt<=r);o&&(c=Vn(c,o));const u=Ql(i[0]?.occurredAt??r,r);return py(u,[...c,...i].sort((d,l)=>d.occurredAt-l.occurredAt||Qn(d)-Qn(l))),hy(u,r),u}function bp(t,e,r,n,o){const s=eg(t,e,r,n,o),i=performance.now();return{world:k0(s.state,s.relationships),state:s.state,declarations:s.declarations,relationships:s.relationships,meta:{...s.meta,serializeMs:Math.round((performance.now()-i)*10)/10}}}function tg(t){const e=iw(t);return r=>{if(r.subject.type==="machine")return r.subject.id!==t&&Sf(r.subject.id)?null:r;const n=r.core?.machineId;if(!n||n===t||!Sf(n))return r;const o=r.subject.type==="process"&&e?TS(r.subject.id,e):void 0;return{...r,...o?{subject:{...r.subject,id:o}}:{},core:{...r.core,machineId:t}}}}function Vn(t,e){const r=[];for(const n of t){const o=e(n);o&&r.push(o)}return r}function Qn(t){if(t.kind==="ended")return 5;switch(t.subject.type){case"machine":return 0;case"session":return 1;case"execution":case"process":return t.kind==="began"?2:3;default:return 4}}const DS=[[ql,Qb],[ki,pw],[en,xw],[Zo,Dw],[Xn,Qw],[es,c0]],Sa=new Map(DS);function rg(t,e,r,n,o){const s=eg(t,e,r,n,["machine","session","execution"]);return Wy({state:ls(s.state,o),declarations:s.declarations,relationships:s.relationships,capabilities:Sa,from:e,to:r})}function ng(t,e,r,n=Date.now(),o){const s=new Map,i=c=>{const u=`${c.from}:${c.to}`,d=s.get(u);if(d)return d;const l=rg(t,c.from,c.to,r,o);return s.set(u,l),l},a=c=>pu(c,e,n);return{summary(c){return yS(i(c),a(c))},availability(c){return ms(i(c),a(c))},compare(c,u){return qy(i(c),a(c),i(u),a(u))},breakdown(c,u){return vS(i(c),a(c),u)}}}function pu(t,e,r){const n=e.eventDays===0?null:r-e.eventDays*864e5,o=n===null?"retained-indefinitely":t.to<n?"outside-retention":t.from<n?"partially-within-retention":"within-retention";return{capabilities:Sa,continuity:{state:"unknown",qualification:"057 does not retain historical source-health continuity for this period"},retention:{state:o,semanticFrom:n,qualification:n===null?"semantic history is configured to be retained indefinitely":o==="within-retention"?"the requested period is inside the configured semantic retention window":o==="partially-within-retention"?"the requested period crosses the configured semantic retention boundary":"the requested period precedes the configured semantic retention window"}}}const LS=3e4;function PS(t,e,r){const n=wa(t.path);try{const o=r.at??t.now?.()??Date.now(),s=ng(n,t.retention,t.machineId,o,r.projectKey);return RA(s,e,o,r)}finally{n.close()}}function US(t,e){return JSON.stringify([t.query,t.scope,t.focus,t.by,e.view,e.timeZone,e.projectKey,e.at,e.period])}function og(t){const e=new Map;return{async read(r,n){const o=t.now?.()??Date.now(),s=US(r,n),i=e.get(s);if(i&&o-i.at<LS)return i.reading;const a=PS(t,r,n);if(e.set(s,{at:o,reading:a}),e.size>32){const c=e.keys().next().value;c!==void 0&&e.delete(c)}return a},close(){e.clear()}}}function VS(t,e){let r=null,n=1;const o=new Map,s=a=>{for(const c of o.values())c.reject(a);o.clear()},i=()=>{const a={o57:"activity-reader",path:e.path,retention:e.retention,machineId:e.machineId},c=new Um(new URL(t),{workerData:a,execArgv:["--disable-warning=ExperimentalWarning"]});return c.unref(),c.on("message",u=>{const d=o.get(u.id);d&&(o.delete(u.id),u.reading?d.resolve(u.reading):d.reject(new Error(u.error??"the reading failed")))}),c.on("error",u=>{r=null,s(u instanceof Error?u:new Error(String(u)))}),c.on("exit",u=>{r===c&&(r=null),o.size>0&&s(new Error(`the reading worker stopped (${u})`))}),c};return{read(a,c){r??=i();const u=n++,d={id:u,request:a,context:c};return new Promise((l,m)=>{o.set(u,{resolve:l,reject:m}),r?.postMessage(d)})},close(){s(new Error("the Core is stopping")),r?.terminate(),r=null}}}function HS(t){const e=og(t);Fn?.on("message",r=>{e.read(r.request,r.context).then(n=>Fn?.postMessage({id:r.id,reading:n}),n=>Fn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)}))})}!Pm&&bi?.o57==="activity-reader"&&HS(bi);const pd={[Oi]:us};function hd(t){return`${t}.core.json`}function sg(t){const e=hd(t);if(!ge(e))return null;try{const r=JSON.parse(Gl(e,"utf8"));return typeof r.pid!="number"||typeof r.url!="string"?null:r}catch{return null}}function FS(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function WS(t,e=1500){const r=sg(t);if(!r||r.pid===process.pid||!FS(r.pid))return null;try{const n=await fetch(`${r.url}/api/health`,{signal:AbortSignal.timeout(e)});return n.ok&&(await n.json()).pid===r.pid?r:null}catch{return null}}function KS(t,e){if(t===":memory:")return;const r=hd(t),n=`${r}.${process.pid}.tmp`;Wl(n,`${JSON.stringify(e,null,1)}
100
- `,{mode:384}),Kl(n,r)}function GS(t,e=process.pid){if(t===":memory:")return;const r=sg(t);r&&r.pid===e&&Dm(hd(t),{force:!0})}class md extends Error{constructor(e){super(`057 is already observing ${e.store} at ${e.url} (pid ${e.pid})`),this.record=e}record}const qS=Lb(Db);function zS(){return Hm()}function YS(t){const e=[];for(const r of t.split(`
101
- `)){const n=r.trim();if(!n)continue;const o=n.match(/^(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+([\d:.]+)\s+(\d+)\s+(.*)$/);if(!o)continue;const[,s,i,a,c,u,d]=o,l=Date.parse(a);Number.isFinite(l)&&e.push({pid:Number(s),ppid:Number(i),startedAt:l,cpuMs:XS(c),rssBytes:Number(u)*1024,command:d.trim()})}return e}function XS(t){const[e,r]=t.includes("-")?t.split("-"):["0",t],n=r.split(":").map(Number);let o=0;for(const s of n)o=o*60+(Number.isFinite(s)?s:0);return Math.round((o+Number(e)*86400)*1e3)}async function JS(){const{stdout:t}=await qS("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return YS(t)}const wp=5e3;function ZS(t,e){const r=zS();let n=new Map,o=null,s=0,i=null,a,c=!1;async function u(){if(c)return[];c=!0;try{const d=await JS(),l=Date.now(),{envelopes:m,next:p}=MS(n,d,{machineId:e,host:r,observedAt:l,intervalMs:wp}),h=m.map(Zt);return t.append(h),n=p,s++,i=l,a=void 0,h}catch(d){return a=d instanceof Error?d.message:String(d),[]}finally{c=!1}}return{sample:u,start(){o||(u(),o=setInterval(()=>{u()},wp),o.unref?.())},stop(){o&&clearInterval(o),o=null},get running(){return o!==null},stats(){return{samples:s,tracked:n.size,lastSampleAt:i,lastError:a}}}}const ig={info:t=>console.log(t),warn:t=>console.warn(t),error:t=>console.error(t)},QS=36e5,ek=15e3,tk=3;function ag(t={}){const e=t.log??ig,r=t.path??ga(),n=t.retention??Uy(),o=nS(r),s=o.stats();e.info(s.events>0?`[057] store ${r}: opened with ${s.events} events`:`[057] store ${r}: NEW EMPTY STORE — if history existed before, it was lost, not carried`);const i=Py();i&&e.warn(`[057] a store from a previous layout exists at ${i} and is NOT in use. Run 057 with O57_STORE=${i} to keep using it, or move it to ${r}.`);const a=Vr();o.append([Zt({source:{id:"host",instance:a.id},occurredAt:0,observedAt:Date.now(),clock:"wall",kind:"began",stratum:"machine",subject:{type:"machine",id:a.id},basis:"measured",core:{machineName:a.name,machineKind:a.kind},seq:"host"})]);const c=ZS(o,a.id),u=new Map;function d(N){for(const S of N){const T=u.get(S.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};S.ok?(T.consecutiveFailures=0,T.failing=!1,T.failingSince=void 0,T.lastSuccessAt=Date.now()):(T.consecutiveFailures===0&&(T.failingSince=Date.now()),T.consecutiveFailures++,T.totalFailures++,T.lastFailureAt=Date.now(),T.lastError=S.error,T.consecutiveFailures>=tk&&!T.failing&&(T.failing=!0,e.warn(`[057] source ${S.id} has failed ${T.consecutiveFailures} collection rounds in a row: ${S.error??"unknown error"}`))),u.set(S.id,T)}}const l=Ap(r);let m=null;function p(N){return m||(m=N,e.error(`[057] ${N.message} — ${N.remedy}`),c.stop()),m}function h(){if(m)return m;if(r===":memory:")return null;if(!ge(r))return p({kind:"unlinked",message:`the store at ${r} no longer exists on disk; captured events are going to an orphaned file and will be lost`,remedy:"Stop 057 and start it again. It will open a new store at the same path.",since:Date.now()});const N=Ap(r);return l!==null&&N!==null&&N!==l?p({kind:"replaced",message:`the store at ${r} was replaced by a different file while 057 was running; captured events are going to the old one`,remedy:"Stop 057 and start it again so it opens the file that is actually there.",since:Date.now()}):null}t.observe!==!1&&c.start();const v=o.sweep(n);v.processEvents+v.otherEvents>0&&e.info(`[057] retention: removed ${v.processEvents} process and ${v.otherEvents} semantic events (${ba(n)})`);const g=setInterval(()=>{if(!m)try{o.sweep(n),lu(r)}catch(N){e.warn(`[057] retention sweep failed: ${String(N)}`)}},QS);g.unref?.();const I=setInterval(()=>{h()},ek);return I.unref?.(),{store:o,machine:a,os:c,path:r,retention:n,fault:()=>m,sweep:N=>o.sweep(n,N),checkStore:h,recordCollection:d,collectionHealth:()=>Object.fromEntries(u),stop(){clearInterval(g),clearInterval(I),c.stop(),o.close()}}}function Ap(t){try{return fa(t).ino}catch{return null}}function cg(t,e){const r=new Map;for(const o of e)o.kind==="began"&&o.subject.type==="execution"&&r.set(o.subject.id,o.source.id);const n=[];for(const o of t.executions.keys()){const s=r.get(o),i=s?Sa.get(s)?.waits:void 0;(i==="supported"||i==="partial")&&n.push(o)}return n}function rk(t,e){return{reported:cg(t,e).length,runs:t.executions.size}}function ug(t,e,r){let n={from:r.from,to:r.to},o=r.label,s=bp(t,n.from,n.to,e,r.subjectTypes);if(r.widenFrom!==void 0&&s.world.executions.length===0&&s.world.sessions.length===0){const a=bp(t,r.widenFrom,r.to,e,r.subjectTypes);(a.world.executions.length>0||a.world.sessions.length>0)&&(n={from:r.widenFrom,to:r.to},o=r.widenedLabel??o,s=a)}let i;if(r.comparison){const{projectKey:a,scope:c,retention:u,evaluatedAt:d}=r.comparison,l=ls(s.state,a),m=Wy({state:l,declarations:s.declarations,relationships:s.relationships,capabilities:Sa,...n}),p=r.comparison.basis==="calendar"?Iy(n,c==="today"?1:7):ld(n),h=rg(t,p.from,p.to,e,a),v=qy(m,pu(n,u,d),h,pu(p,u,d));i=Oy({query:"compare",scope:c},{comparison:v},{projectKey:a,period:n})}return{...n,label:o,comparison:i,world:s.world,meta:s.meta,waits:rk(s.state,s.declarations),executionStarts:Object.fromEntries(s.declarations.filter(a=>a.subject.type==="execution"&&a.kind==="began").map(a=>[a.subject.id,{at:a.occurredAt,basis:a.basis,assumption:a.assumption}])),waitReportedIds:cg(s.state,s.declarations)}}function Sp(t,e){return{async read(r,n){if(n?.aborted)throw new Error("analytical read cancelled");return ug(t,e,r)},close(){}}}function kp(t,e){let r=null,n=1,o=null,s=null;const i=new Map,a=d=>{for(const l of i.values())l.detach(),l.reject(d);i.clear(),s=null},c=()=>{const d={o57:"landscape-reader",...e},l=new Um(new URL(t),{workerData:d,execArgv:["--disable-warning=ExperimentalWarning"]});return l.unref(),l.on("message",m=>{if(r!==l)return;const p=i.get(m.id);i.delete(m.id),s===m.id&&(s=null),p&&(p.detach(),m.snapshot?p.resolve(m.snapshot):p.reject(new Error(m.error??"the landscape read failed"))),u()}),l.on("error",m=>{r===l&&(r=null,a(m instanceof Error?m:new Error(String(m))))}),l.on("exit",m=>{r===l&&(r=null,a(new Error(`the landscape worker stopped (${m})`)))}),l},u=()=>{if(s!==null)return;const d=i.entries().next().value;if(!d)return;const[l,m]=d;r??=c(),s=l,r.postMessage({id:l,request:m.request})};return{read(d,l){if(d.label==="TODAY"&&o)return o;if(l?.aborted)return Promise.reject(new Error("analytical read cancelled"));if(i.size>=32)return Promise.reject(new Error("Too many analytical reads; retry the selected window."));const m=n++,p=new Promise((h,v)=>{const g=()=>{i.delete(m),l?.removeEventListener("abort",g),v(new Error("analytical read cancelled"))};i.set(m,{request:d,resolve:h,reject:v,detach:()=>l?.removeEventListener("abort",g)}),l?.addEventListener("abort",g,{once:!0}),u()});return d.label!=="TODAY"?p:(o=p.finally(()=>{o=null}),o)},close(){a(new Error("the Core is stopping")),r?.terminate(),r=null,o=null}}}function nk(t){const e=wa(t.path);Fn?.on("message",r=>{try{Fn?.postMessage({id:r.id,snapshot:ug(e,t.machineId,r.request)})}catch(n){Fn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)})}})}!Pm&&bi?.o57==="landscape-reader"&&nk(bi);const hu=[{id:ql,collect:(t,e)=>fw(t,e)},{id:ki,collect:(t,e)=>Ew(t,e)},{id:en,collect:(t,e)=>jw(t,e)},{id:Zo,collect:(t,e)=>Zw(t,e)},{id:Xn,collect:(t,e)=>a0(t,e)},{id:es,collect:(t,e)=>b0(t,e)}],Ep=[...hu.map(t=>t.id),Jr],xp=10*365*24*36e5,ni=2e5,ok=24*36e5;function Ip(t){const e=new AbortController;return t.once("close",()=>{t.writableEnded||e.abort()}),e.signal}const Op=72*36e5;function Cp(t){const e=new Date(t);return e.setHours(0,0,0,0),{from:e.getTime(),to:t}}function Np(t){const e=t.collectionHealth(),r=Object.entries(e).filter(([,a])=>a.failing).map(([a])=>a),n=t.store.health(),o=t.os.stats(),s=t.fault();let i=null;for(const a of Object.values(e))a.lastSuccessAt&&(i===null||a.lastSuccessAt>i)&&(i=a.lastSuccessAt);return{ok:r.length===0&&n.ok&&!s&&!o.lastError,fault:s??void 0,failingSources:r,errors:Object.fromEntries(Object.entries(e).filter(([,a])=>a.failing).map(([a,c])=>[a,c.lastError??"failing"])),failing:Object.fromEntries(Object.entries(e).filter(([,a])=>a.failing).map(([a,c])=>[a,{since:c.failingSince??null,rounds:c.consecutiveFailures}])),store:{ok:n.ok,remedy:n.remedy},os:{running:t.os.running,lastSampleAt:o.lastSampleAt,lastError:o.lastError},lastCollectionAt:i,sources:{total:Ep.length,reported:Ep.filter(a=>e[a]!==void 0).length}}}function sk(t,e,r){const n=e.startsWith("/api/");if(r){const a=(t.headers.host??"").toLowerCase(),c=a.startsWith("[")?a.slice(0,a.indexOf("]")+1):a.split(":")[0];if(!r.includes(c))return`refusing a request for host "${a}"; 057 answers only on ${r.join(", ")}`}const o=t.headers.origin;if(typeof o=="string"&&o!=="null"){const a=(t.headers.host??"").toLowerCase();let c="";try{c=new URL(o).host.toLowerCase()}catch{return"refusing a request with an unparseable Origin"}if(c!==a)return`refusing a cross-origin request from ${o}`}const s=t.headers["sec-fetch-site"],i=String(t.headers["sec-fetch-dest"]??"");if(ak.has(i))return`refusing to be embedded as ${i}`;if(typeof s=="string"&&s!==""){if(s!=="same-origin"&&s!=="none")return`refusing a ${s} request`;if(s==="none"&&n)return"refusing a directly-navigated API request"}else if(n&&e==="/api/collect"&&!t.headers[ik])return"refusing a state-changing request that carries no fetch metadata";return null}const ik="x-057-client",ak=new Set(["iframe","frame","embed","object","fencedframe"]);function yd(t){t.setHeader("x-frame-options","DENY"),t.setHeader("content-security-policy","frame-ancestors 'none'")}function ck(t,e){const r=(s,i)=>{const a=t.get(s);if(a===null||a==="")return i;const c=Number(a);return Number.isSafeInteger(c)?c:null},n=r("from",e-864e5),o=r("to",e);return n===null||o===null?{error:"from and to must be integer epoch millis"}:o<n?{error:"to must not precede from"}:o>e+ok?{error:"to is too far in the future"}:o-n>xp?{error:`window must not exceed ${xp} ms`}:{from:n,to:o}}function be(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),yd(t),t.end(JSON.stringify(r))}function uk(t){const e=t.problems.filter(r=>r.path.includes("/sessions/")).length;return{identity:t.identityAvailable?e===0?"available":t.registryEntries>0?"partial":"failed":"unavailable","stored-semantics":t.storedAvailable?t.transcriptsFailed===0?"available":t.transcriptsRead>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function Pc(t){return{"stored-semantics":t.storedAvailable?t.failed===0?"available":t.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function lk(t){return t.error?"failed":t.available?"observing":t.present?"installed-no-data":"not-installed"}function dk(t){const e=t.home??t.globalStorage;if(typeof e=="string")return e;const r=t.roots;return Array.isArray(r)?r.join(", "):void 0}function zr(t){return{available:t.available,present:t.present??!1,presence:lk(t),origin:dk(t),error:t.error}}function fk(t){const{runtime:e,log:r}=t,n=t.activity??og({path:e.path,retention:e.retention,machineId:e.machine.id}),o=t.landscape??Sp(e.store,e.machine.id),s=t.analytics??Sp(e.store,e.machine.id);let i=null;const a=new Map,c=new Map,u=new Map;async function d(m,p,h,v,g,I="previous"){const N=g??uu(m,p),S=JSON.stringify([m,g??(m==="today"?N.from:null),h??null,h!==void 0,I]),T=a.get(S);if(T&&p>=T.asOf&&p-T.asOf<(m==="today"?5e3:6e4)&&(m!=="today"||T.period.from===N.from))return T;const x=u.get(S);if(x&&!x.controller.signal.aborted)return yf(x,v);const D=Ub(async $=>{const E=g?"SELECTED PERIOD":m==="today"?"TODAY":"LAST 7 DAYS",B=await s.read({...N,label:`ANALYTICS · ${E}`,subjectTypes:["machine","session","execution"],comparison:h===void 0?void 0:{scope:m,projectKey:h??void 0,retention:e.retention,evaluatedAt:p,basis:I}},$);if($.aborted)throw new Error("analytical read cancelled");const C=xc(B.world),P={period:{scope:m,label:E,...N,fixed:g!==void 0},asOf:p,world:C,landscape:Oc(C),waits:B.waits,waitReportedIds:B.waitReportedIds,executionStarts:B.executionStarts,comparison:B.comparison};if(a.set(S,P),c.set(JSON.stringify([m,N.from,N.to,p]),P),c.size>16){const L=c.keys().next().value;L!==void 0&&c.delete(L)}if(a.size>16){const L=a.keys().next().value;L!==void 0&&a.delete(L)}return P});u.set(S,D);const w=()=>{u.get(S)===D&&u.delete(S)};return D.promise.then(w,w),yf(D,v)}async function l(m){if(!i||m-i.at>6e4){const p=Cp(m),h=await o.read({...p,label:"TODAY",widenFrom:m-Op,widenedLabel:"LAST 72H"}),v=xc(h.world);i={at:m,label:h.label,world:v,landscape:Oc(v),waits:h.waits}}return i}return async function(p,h){const v=p.url??"";if(!v.startsWith("/api/"))return!1;const g=new URL(v,"http://localhost"),I=sk(p,g.pathname,t.allowedHosts);if(I)return r.warn(`[057] ${I}`),be(h,403,{error:I}),!0;const N=e.store,S=Date.now(),T=ck(g.searchParams,S);if("error"in T)return be(h,400,{error:T.error}),!0;const{from:x,to:D}=T,w=g.searchParams.has("from")||g.searchParams.has("to"),$=w?{from:x,to:D}:void 0;if(["/api/analytics","/api/activity","/api/inspect"].includes(g.pathname)&&w&&(!/^\d+$/.test(g.searchParams.get("from")??"")||!/^\d+$/.test(g.searchParams.get("to")??"")||D<=x||D>S||D-x>31*864e5))return be(h,400,{error:"analytical bounds need from < to, no future end, and at most 31 days"}),!0;try{if(g.pathname==="/api/state"){const[E,B,C,P,L,te]=await Promise.all([Ef().catch(we=>({available:!1,error:String(we)})),Cf().catch(we=>({available:!1,error:String(we)})),Tf().catch(we=>({available:!1,error:String(we)})),$f().catch(we=>({available:!1,error:String(we)})),_f().catch(we=>({available:!1,error:String(we)})),Df().catch(we=>({available:!1,error:String(we)}))]),[U,V,z,se]=await Promise.all([Jm(x,D).catch(()=>null),ey(x,D).catch(()=>null),ny(x,D).catch(()=>null),ay(x,D).catch(()=>null)]),ve={strata:{"stored-semantics":"failed"}},Ae={"claude-code":U?{strata:uk(U),registryEntries:U.registryEntries,transcriptsRead:U.transcriptsRead,transcriptsFailed:U.transcriptsFailed,problems:U.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:V?{strata:Pc({storedAvailable:V.storedAvailable,read:V.rolloutsRead,failed:V.rolloutsFailed}),rolloutsRead:V.rolloutsRead,rolloutsFailed:V.rolloutsFailed,problems:V.problems.slice(0,20)}:ve,cursor:z?{strata:Pc({storedAvailable:z.storedAvailable,read:z.composersRead,failed:z.composersFailed}),composersRead:z.composersRead,composersFailed:z.composersFailed,problems:z.problems.slice(0,20)}:ve,gemini:se?{strata:Pc({storedAvailable:se.storedAvailable,read:se.sessionsRead,failed:se.sessionsFailed}),sessionsRead:se.sessionsRead,sessionsFailed:se.sessionsFailed,problems:se.problems.slice(0,20)}:ve},_e={deepseek:zr(E),"0x2f":zr(B),"claude-code":zr(C),codex:zr(P),cursor:zr(L),gemini:zr(te)},Ie=e.collectionHealth();for(const[we,Wt]of Object.entries(_e)){const He=Ie[we];He?.failing&&(Wt.presence="failed",Wt.error??=He.lastError)}const q=e.os.stats(),rt=Object.values(_e).filter(we=>we.available).length>0?"observing":q.samples>0?"os-only":"empty",A=Object.entries(Ie).filter(([,we])=>we.failing).map(([we])=>we),ae=N.health(),ye={ok:A.length===0&&ae.ok&&!e.fault()&&!q.lastError,failingSources:A,collection:Ie,store:ae,os:q.lastError?{failing:!0,lastError:q.lastError}:{failing:!1}};return be(h,200,{machine:e.machine,mode:rt,fault:e.fault()??void 0,health:ye,store:{...N.stats(),path:N.path,schemaVersion:N.schemaVersion,bytes:N.sizeBytes(),retention:{...e.retention,description:ba(e.retention)}},os:{...q,running:e.os.running,source:Jr},sources:_e,observation:Ae}),!0}if(g.pathname==="/api/collect"){const E=e.checkStore();if(E)return be(h,503,{error:E.message,fault:E}),!0;const B=await Xb(N,hu,x,D,P=>e.recordCollection([P])),C=await e.os.sample();return e.recordCollection([{id:Jr,ok:!e.os.stats().lastError,error:e.os.stats().lastError}]),be(h,200,{...B,sources:[...B.sources,{id:Jr,ok:!e.os.stats().lastError,collected:C.length,inserted:C.length,duplicate:0,error:e.os.stats().lastError,ms:0}]}),!0}if(g.pathname==="/api/world"){const E=await o.read({from:x,to:D,label:"WINDOW"});return be(h,200,{from:x,to:D,now:S,world:E.world,meta:E.meta,waits:E.waits}),!0}if(g.pathname==="/api/health")return be(h,200,{pid:process.pid,version:t.version??"dev",contract:pd,store:e.path,health:Np(e)}),!0;if(g.pathname==="/api/landscape"){const E=g.searchParams.get("window")==="live",B=E?Cp(S):{from:x,to:D},C=await o.read({...B,label:E?"TODAY":"WINDOW",...E?{widenFrom:S-Op,widenedLabel:"LAST 72H"}:{}}),P=xc(C.world),L=Oc(P);return E&&(i={at:S,label:C.label,world:P,landscape:L,waits:C.waits}),be(h,200,{from:C.from,to:C.to,now:S,window:C.label,meta:C.meta,health:Np(e),...D0(L)}),!0}if(g.pathname==="/api/analytics"){const E=g.searchParams.get("scope")??"today";if(E!=="today"&&E!=="last-7d")return be(h,400,{error:"analytics needs scope=today|last-7d"}),!0;const B=g.searchParams.get("project")??void 0;if(B!==void 0&&!li(B))return be(h,400,{error:"invalid project key"}),!0;const C=g.searchParams.get("comparison");if(C!==null&&C!=="previous"&&C!=="calendar")return be(h,400,{error:"comparison must be previous|calendar"}),!0;const P=C==="calendar"?"calendar":"previous",L=await d(E,S,C?B??null:void 0,Ip(h),$,P),te=ls(L.world,B),U={runs:te.executions.size,reported:L.waitReportedIds.filter(_e=>te.executions.has(_e)).length},V=i?.landscape??{disturbances:[],strata:[]},z=Qf(te,U,$?D-x<=25*36e5?"today":"last-7d":E),se=cA(L.world,B),ve=P==="calendar"?E==="today"?"same local hours one day earlier":"same local bounds one week earlier":`previous ${fe(L.period.to-L.period.from)}`,Ae={period:L.period,asOf:L.asOf,project:se,today:z,comparison:L.comparison,comparisonLabel:ve};return be(h,200,{summaryText:ep(Ae),privateSummaryText:ep(Ae,!0),period:L.period,asOf:L.asOf,comparisonPeriod:C?P==="calendar"?Iy(L.period,E==="today"?1:7):ld(L.period):void 0,comparisonLabel:ve,comparisonBasis:P,projects:aA(L.world),project:se,projectKey:B??null,comparison:L.comparison,today:{window:L.period.label,...z},log:{window:L.period.label,...Tc(te,V,{starts:L.executionStarts,waitReportedIds:L.waitReportedIds})}}),!0}if(g.pathname==="/api/today"||g.pathname==="/api/log"){const E=await l(S);return be(h,200,g.pathname==="/api/today"?{window:E.label,...Qf(E.world,E.waits)}:{window:E.label,...Tc(E.world,E.landscape)}),!0}if(g.pathname==="/api/inspect"){const E=g.searchParams.get("kind")??"",B=g.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(E)||!B||B.length>512)return be(h,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;const C=g.searchParams.get("scope");if(C!==null&&C!=="today"&&C!=="last-7d")return be(h,400,{error:"inspect needs scope=today|last-7d"}),!0;const P=g.searchParams.get("project")??void 0;if(P!==void 0&&(!C||!li(P)))return be(h,400,{error:"project inspection needs a scope and a valid project key"}),!0;const L=g.searchParams.get("at"),te=L===null?S:Number(L);if(!Number.isSafeInteger(te)||te>S||te<S-6e5)return be(h,400,{error:"refresh the analytical snapshot before inspecting it"}),!0;const U=C?$??uu(C,te):void 0,z=(C&&L!==null&&U?c.get(JSON.stringify([C,U.from,U.to,te])):void 0)??(C?await d(C,te,void 0,Ip(h),$):await l(S)),se=(_e,Ie)=>{for(const q of N.subjectEvents(_e,Ie))if(q.provenance?.path)return q.provenance.path},ve=ls(z.world,P);let Ae=Jf(ve,z.landscape,E,B,se,C&&"executionStarts"in z?z.executionStarts:void 0);if(C&&Ae&&ve.executions.has(B)){const _e=jS(N,B,ve.now,e.machine.id),Ie=Jf(_e,z.landscape,E,B,se),q=Tc(ve,z.landscape).rows.find(qe=>qe.id===B);if(Ie&&q){for(const qe of Ie.groups)for(const rt of qe.rows)rt.key==="ELAPSED"&&(rt.note=[rt.note,`Full retained record as of ${new Date(ve.now).toISOString()}; may include time outside the selected period.`].filter(Boolean).join(" "));Ae={...Ie,groups:[{title:"IN SELECTED PERIOD",metadata:!0,rows:[{key:"RUN TIME",value:fe(q.durationMs),note:"Clipped to the selected period; trailing idle silence excluded. Parallel runs add together."},{key:"TOKENS",value:q.tokens===null?"not reported":ze(q.tokens),note:"Only accounting events recorded in the selected period."},{key:"TOOL CALLS",value:q.tools===null?"not reported":String(q.tools)},{key:"WAITING",value:"waitReportedIds"in z&&z.waitReportedIds.includes(B)?fe(q.waitedMs):"not reported",note:"Includes an explicit wait still open at the snapshot."}]},...Ie.groups]}}}return Ae?(be(h,200,Ae),!0):(be(h,404,{error:"not in the current world"}),!0)}if(g.pathname==="/api/activity"){const E=g.searchParams,B=BA({query:E.get("query"),scope:E.get("scope"),focus:E.get("focus"),by:E.get("by")});if("error"in B)return be(h,400,B),!0;const C=E.get("project")??void 0,P=E.get("at"),L=P===null?void 0:Number(P);if(C!==void 0&&!li(C))return be(h,400,{error:"invalid project key"}),!0;if(L!==void 0&&(!P?.match(/^\d+$/)||!Number.isSafeInteger(L)||L>S||L<S-6e5))return be(h,400,{error:"reading snapshot must be within the last ten minutes; refresh the analytical view"}),!0;const te=E.get("view")==="live"?i?.label??(await l(S)).label:void 0;return be(h,200,await n.read(B,{...te?{view:te}:{},projectKey:C,at:L,period:$})),!0}if(g.pathname==="/api/sources"){const E=await Promise.all([Ef().catch(L=>({available:!1,error:String(L)})),Cf().catch(L=>({available:!1,error:String(L)})),Tf().catch(L=>({available:!1,error:String(L)})),$f().catch(L=>({available:!1,error:String(L)})),_f().catch(L=>({available:!1,error:String(L)})),Df().catch(L=>({available:!1,error:String(L)}))]),B=e.collectionHealth(),C=e.os.stats(),P=hu.map((L,te)=>{const U=zr(E[te]),V=B[L.id];return{id:L.id,presence:V?.failing?"failed":U.presence,origin:U.origin,error:V?.failing?V.lastError??U.error:U.error,consecutiveFailures:V?.consecutiveFailures??0,lastSuccessAt:V?.lastSuccessAt}});return P.push({id:Jr,presence:C.lastError?"failed":C.samples>0?"observing":"installed-no-data",origin:void 0,error:C.lastError,consecutiveFailures:B[Jr]?.consecutiveFailures??0,lastSuccessAt:C.lastSampleAt??void 0}),be(h,200,{sources:P}),!0}if(g.pathname==="/api/detail"){const E=g.searchParams.get("type")??"",B=g.searchParams.get("id")??"";if(!gf.includes(E)||!B)return be(h,400,{error:"detail needs type=<entity type> and id"}),!0;if(B.length>512)return be(h,400,{error:"id is too long"}),!0;const C=N.subjectEvents(E,B);return be(h,200,{type:E,id:B,events:C.slice(0,ni),truncated:C.length>ni}),!0}if(g.pathname==="/api/events"){const E=g.searchParams.get("subject"),B=E?E.split(",").filter(P=>gf.includes(P)):void 0,C=Qy(N,x,D,B,e.machine.id);return be(h,200,{from:x,to:D,now:S,events:C.events.slice(0,ni),truncated:C.events.length>ni,relationships:C.relationships}),!0}return be(h,404,{error:"unknown endpoint"}),!0}catch(E){return h.destroyed||(r.error(`[057] ${String(E)}`),be(h,500,{error:String(E)})),!0}}}var Tp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$p={};var Bp;function pk(){if(Bp)return $p;Bp=1;var t;return(function(e){(function(r){var n=typeof globalThis=="object"?globalThis:typeof Tp=="object"?Tp:typeof self=="object"?self:typeof this=="object"?this:c(),o=s(e);typeof n.Reflect<"u"&&(o=s(n.Reflect,o)),r(o,n),typeof n.Reflect>"u"&&(n.Reflect=e);function s(u,d){return function(l,m){Object.defineProperty(u,l,{configurable:!0,writable:!0,value:m}),d&&d(l,m)}}function i(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function c(){return i()||a()}})(function(r,n){var o=Object.prototype.hasOwnProperty,s=typeof Symbol=="function",i=s&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",a=s&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",c=typeof Object.create=="function",u={__proto__:[]}instanceof Array,d=!c&&!u,l={create:c?function(){return Ac(Object.create(null))}:u?function(){return Ac({__proto__:null})}:function(){return Ac({})},has:d?function(k,O){return o.call(k,O)}:function(k,O){return O in k},get:d?function(k,O){return o.call(k,O)?k[O]:void 0}:function(k,O){return k[O]}},m=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Ab(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Sb(),v=typeof WeakMap=="function"?WeakMap:kb(),g=s?Symbol.for("@reflect-metadata:registry"):void 0,I=vb(),N=bb(I);function S(k,O,M,F){if(q(M)){if(!$n(k))throw new TypeError;if(!Kt(O))throw new TypeError;return L(k,O)}else{if(!$n(k))throw new TypeError;if(!A(O))throw new TypeError;if(!A(F)&&!q(F)&&!qe(F))throw new TypeError;return qe(F)&&(F=void 0),M=He(M),te(k,O,M,F)}}r("decorate",S);function T(k,O){function M(F,ne){if(!A(F))throw new TypeError;if(!q(ne)&&!Ir(ne))throw new TypeError;ve(k,O,F,ne)}return M}r("metadata",T);function x(k,O,M,F){if(!A(M))throw new TypeError;return q(F)||(F=He(F)),ve(k,O,M,F)}r("defineMetadata",x);function D(k,O,M){if(!A(O))throw new TypeError;return q(M)||(M=He(M)),U(k,O,M)}r("hasMetadata",D);function w(k,O,M){if(!A(O))throw new TypeError;return q(M)||(M=He(M)),V(k,O,M)}r("hasOwnMetadata",w);function $(k,O,M){if(!A(O))throw new TypeError;return q(M)||(M=He(M)),z(k,O,M)}r("getMetadata",$);function E(k,O,M){if(!A(O))throw new TypeError;return q(M)||(M=He(M)),se(k,O,M)}r("getOwnMetadata",E);function B(k,O){if(!A(k))throw new TypeError;return q(O)||(O=He(O)),Ae(k,O)}r("getMetadataKeys",B);function C(k,O){if(!A(k))throw new TypeError;return q(O)||(O=He(O)),_e(k,O)}r("getOwnMetadataKeys",C);function P(k,O,M){if(!A(O))throw new TypeError;if(q(M)||(M=He(M)),!A(O))throw new TypeError;q(M)||(M=He(M));var F=Io(O,M,!1);return q(F)?!1:F.OrdinaryDeleteMetadata(k,O,M)}r("deleteMetadata",P);function L(k,O){for(var M=k.length-1;M>=0;--M){var F=k[M],ne=F(O);if(!q(ne)&&!qe(ne)){if(!Kt(ne))throw new TypeError;O=ne}}return O}function te(k,O,M,F){for(var ne=k.length-1;ne>=0;--ne){var Ue=k[ne],je=Ue(O,M,F);if(!q(je)&&!qe(je)){if(!A(je))throw new TypeError;F=je}}return F}function U(k,O,M){var F=V(k,O,M);if(F)return!0;var ne=wc(O);return qe(ne)?!1:U(k,ne,M)}function V(k,O,M){var F=Io(O,M,!1);return q(F)?!1:we(F.OrdinaryHasOwnMetadata(k,O,M))}function z(k,O,M){var F=V(k,O,M);if(F)return se(k,O,M);var ne=wc(O);if(!qe(ne))return z(k,ne,M)}function se(k,O,M){var F=Io(O,M,!1);if(!q(F))return F.OrdinaryGetOwnMetadata(k,O,M)}function ve(k,O,M,F){var ne=Io(M,F,!0);ne.OrdinaryDefineOwnMetadata(k,O,M,F)}function Ae(k,O){var M=_e(k,O),F=wc(k);if(F===null)return M;var ne=Ae(F,O);if(ne.length<=0)return M;if(M.length<=0)return ne;for(var Ue=new h,je=[],le=0,G=M;le<G.length;le++){var X=G[le],Q=Ue.has(X);Q||(Ue.add(X),je.push(X))}for(var re=0,de=ne;re<de.length;re++){var X=de[re],Q=Ue.has(X);Q||(Ue.add(X),je.push(X))}return je}function _e(k,O){var M=Io(k,O,!1);return M?M.OrdinaryOwnMetadataKeys(k,O):[]}function Ie(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function q(k){return k===void 0}function qe(k){return k===null}function rt(k){return typeof k=="symbol"}function A(k){return typeof k=="object"?k!==null:typeof k=="function"}function ae(k,O){switch(Ie(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var M="string",F=lf(k,i);if(F!==void 0){var ne=F.call(k,M);if(A(ne))throw new TypeError;return ne}return ye(k)}function ye(k,O){var M,F;{var ne=k.toString;if(Gr(ne)){var F=ne.call(k);if(!A(F))return F}var M=k.valueOf;if(Gr(M)){var F=M.call(k);if(!A(F))return F}}throw new TypeError}function we(k){return!!k}function Wt(k){return""+k}function He(k){var O=ae(k);return rt(O)?O:Wt(O)}function $n(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function Gr(k){return typeof k=="function"}function Kt(k){return typeof k=="function"}function Ir(k){switch(Ie(k)){case 3:return!0;case 4:return!0;default:return!1}}function bc(k,O){return k===O||k!==k&&O!==O}function lf(k,O){var M=k[O];if(M!=null){if(!Gr(M))throw new TypeError;return M}}function df(k){var O=lf(k,a);if(!Gr(O))throw new TypeError;var M=O.call(k);if(!A(M))throw new TypeError;return M}function ff(k){return k.value}function pf(k){var O=k.next();return O.done?!1:O}function hf(k){var O=k.return;O&&O.call(k)}function wc(k){var O=Object.getPrototypeOf(k);if(typeof k!="function"||k===m||O!==m)return O;var M=k.prototype,F=M&&Object.getPrototypeOf(M);if(F==null||F===Object.prototype)return O;var ne=F.constructor;return typeof ne!="function"||ne===k?O:ne}function gb(){var k;!q(g)&&typeof n.Reflect<"u"&&!(g in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(k=wb(n.Reflect));var O,M,F,ne=new v,Ue={registerProvider:je,getProvider:G,setProvider:Q};return Ue;function je(re){if(!Object.isExtensible(Ue))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===re:break;case q(O):O=re;break;case O===re:break;case q(M):M=re;break;case M===re:break;default:F===void 0&&(F=new h),F.add(re);break}}function le(re,de){if(!q(O)){if(O.isProviderFor(re,de))return O;if(!q(M)){if(M.isProviderFor(re,de))return O;if(!q(F))for(var Ee=df(F);;){var Be=pf(Ee);if(!Be)return;var $t=ff(Be);if($t.isProviderFor(re,de))return hf(Ee),$t}}}if(!q(k)&&k.isProviderFor(re,de))return k}function G(re,de){var Ee=ne.get(re),Be;return q(Ee)||(Be=Ee.get(de)),q(Be)&&(Be=le(re,de),q(Be)||(q(Ee)&&(Ee=new p,ne.set(re,Ee)),Ee.set(de,Be))),Be}function X(re){if(q(re))throw new TypeError;return O===re||M===re||!q(F)&&F.has(re)}function Q(re,de,Ee){if(!X(Ee))throw new Error("Metadata provider not registered.");var Be=G(re,de);if(Be!==Ee){if(!q(Be))return!1;var $t=ne.get(re);q($t)&&($t=new p,ne.set(re,$t)),$t.set(de,Ee)}return!0}}function vb(){var k;return!q(g)&&A(n.Reflect)&&Object.isExtensible(n.Reflect)&&(k=n.Reflect[g]),q(k)&&(k=gb()),!q(g)&&A(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,g,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function bb(k){var O=new v,M={isProviderFor:function(X,Q){var re=O.get(X);return q(re)?!1:re.has(Q)},OrdinaryDefineOwnMetadata:je,OrdinaryHasOwnMetadata:ne,OrdinaryGetOwnMetadata:Ue,OrdinaryOwnMetadataKeys:le,OrdinaryDeleteMetadata:G};return I.registerProvider(M),M;function F(X,Q,re){var de=O.get(X),Ee=!1;if(q(de)){if(!re)return;de=new p,O.set(X,de),Ee=!0}var Be=de.get(Q);if(q(Be)){if(!re)return;if(Be=new p,de.set(Q,Be),!k.setProvider(X,Q,M))throw de.delete(Q),Ee&&O.delete(X),new Error("Wrong provider for target.")}return Be}function ne(X,Q,re){var de=F(Q,re,!1);return q(de)?!1:we(de.has(X))}function Ue(X,Q,re){var de=F(Q,re,!1);if(!q(de))return de.get(X)}function je(X,Q,re,de){var Ee=F(re,de,!0);Ee.set(X,Q)}function le(X,Q){var re=[],de=F(X,Q,!1);if(q(de))return re;for(var Ee=de.keys(),Be=df(Ee),$t=0;;){var mf=pf(Be);if(!mf)return re.length=$t,re;var Eb=ff(mf);try{re[$t]=Eb}catch(xb){try{hf(Be)}finally{throw xb}}$t++}}function G(X,Q,re){var de=F(Q,re,!1);if(q(de)||!de.delete(X))return!1;if(de.size===0){var Ee=O.get(Q);q(Ee)||(Ee.delete(re),Ee.size===0&&O.delete(Ee))}return!0}}function wb(k){var O=k.defineMetadata,M=k.hasOwnMetadata,F=k.getOwnMetadata,ne=k.getOwnMetadataKeys,Ue=k.deleteMetadata,je=new v,le={isProviderFor:function(G,X){var Q=je.get(G);return!q(Q)&&Q.has(X)?!0:ne(G,X).length?(q(Q)&&(Q=new h,je.set(G,Q)),Q.add(X),!0):!1},OrdinaryDefineOwnMetadata:O,OrdinaryHasOwnMetadata:M,OrdinaryGetOwnMetadata:F,OrdinaryOwnMetadataKeys:ne,OrdinaryDeleteMetadata:Ue};return le}function Io(k,O,M){var F=I.getProvider(k,O);if(!q(F))return F;if(M){if(I.setProvider(k,O,N))return N;throw new Error("Illegal state.")}}function Ab(){var k={},O=[],M=(function(){function le(G,X,Q){this._index=0,this._keys=G,this._values=X,this._selector=Q}return le.prototype["@@iterator"]=function(){return this},le.prototype[a]=function(){return this},le.prototype.next=function(){var G=this._index;if(G>=0&&G<this._keys.length){var X=this._selector(this._keys[G],this._values[G]);return G+1>=this._keys.length?(this._index=-1,this._keys=O,this._values=O):this._index++,{value:X,done:!1}}return{value:void 0,done:!0}},le.prototype.throw=function(G){throw this._index>=0&&(this._index=-1,this._keys=O,this._values=O),G},le.prototype.return=function(G){return this._index>=0&&(this._index=-1,this._keys=O,this._values=O),{value:G,done:!0}},le})(),F=(function(){function le(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(le.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),le.prototype.has=function(G){return this._find(G,!1)>=0},le.prototype.get=function(G){var X=this._find(G,!1);return X>=0?this._values[X]:void 0},le.prototype.set=function(G,X){var Q=this._find(G,!0);return this._values[Q]=X,this},le.prototype.delete=function(G){var X=this._find(G,!1);if(X>=0){for(var Q=this._keys.length,re=X+1;re<Q;re++)this._keys[re-1]=this._keys[re],this._values[re-1]=this._values[re];return this._keys.length--,this._values.length--,bc(G,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},le.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},le.prototype.keys=function(){return new M(this._keys,this._values,ne)},le.prototype.values=function(){return new M(this._keys,this._values,Ue)},le.prototype.entries=function(){return new M(this._keys,this._values,je)},le.prototype["@@iterator"]=function(){return this.entries()},le.prototype[a]=function(){return this.entries()},le.prototype._find=function(G,X){if(!bc(this._cacheKey,G)){this._cacheIndex=-1;for(var Q=0;Q<this._keys.length;Q++)if(bc(this._keys[Q],G)){this._cacheIndex=Q;break}}return this._cacheIndex<0&&X&&(this._cacheIndex=this._keys.length,this._keys.push(G),this._values.push(void 0)),this._cacheIndex},le})();return F;function ne(le,G){return le}function Ue(le,G){return G}function je(le,G){return[le,G]}}function Sb(){var k=(function(){function O(){this._map=new p}return Object.defineProperty(O.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),O.prototype.has=function(M){return this._map.has(M)},O.prototype.add=function(M){return this._map.set(M,M),this},O.prototype.delete=function(M){return this._map.delete(M)},O.prototype.clear=function(){this._map.clear()},O.prototype.keys=function(){return this._map.keys()},O.prototype.values=function(){return this._map.keys()},O.prototype.entries=function(){return this._map.entries()},O.prototype["@@iterator"]=function(){return this.keys()},O.prototype[a]=function(){return this.keys()},O})();return k}function kb(){var k=16,O=l.create(),M=F();return(function(){function G(){this._key=F()}return G.prototype.has=function(X){var Q=ne(X,!1);return Q!==void 0?l.has(Q,this._key):!1},G.prototype.get=function(X){var Q=ne(X,!1);return Q!==void 0?l.get(Q,this._key):void 0},G.prototype.set=function(X,Q){var re=ne(X,!0);return re[this._key]=Q,this},G.prototype.delete=function(X){var Q=ne(X,!1);return Q!==void 0?delete Q[this._key]:!1},G.prototype.clear=function(){this._key=F()},G})();function F(){var G;do G="@@WeakMap@@"+le();while(l.has(O,G));return O[G]=!0,G}function ne(G,X){if(!o.call(G,M)){if(!X)return;Object.defineProperty(G,M,{value:l.create()})}return G[M]}function Ue(G,X){for(var Q=0;Q<X;++Q)G[Q]=Math.random()*255|0;return G}function je(G){if(typeof Uint8Array=="function"){var X=new Uint8Array(G);return typeof crypto<"u"?crypto.getRandomValues(X):typeof msCrypto<"u"?msCrypto.getRandomValues(X):Ue(X,G),X}return Ue(new Array(G),G)}function le(){var G=je(k);G[6]=G[6]&79|64,G[8]=G[8]&191|128;for(var X="",Q=0;Q<k;++Q){var re=G[Q];(Q===4||Q===6||Q===8)&&(X+="-"),re<16&&(X+="0"),X+=re.toString(16).toLowerCase()}return X}}function Ac(k){return k.__=void 0,delete k.__,k}})})(t||(t={})),$p}pk();const hk="[object ArrayBuffer]";class K{static isArrayBuffer(e){return Object.prototype.toString.call(e)===hk}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,r){if(e.constructor===r)return e;if(this.isArrayBuffer(e))return new r(e);if(this.isArrayBufferView(e))return new r(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,r){const n=K.toUint8Array(e),o=K.toUint8Array(r);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...e){let r;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?r=e[0]:e[e.length-1]instanceof Function?r=e.slice(0,e.length-1):r=e;let n=0;for(const i of r)n+=i.byteLength;const o=new Uint8Array(n);let s=0;for(const i of r){const a=this.toUint8Array(i);o.set(a,s),s+=a.length}return e[e.length-1]instanceof Function?this.toView(o,e[e.length-1]):o.buffer}}const Uc="string",mk=/^[0-9a-f\s]+$/i,yk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,gk=/^[a-zA-Z0-9-_]+$/;class Rp{static fromString(e){const r=unescape(encodeURIComponent(e)),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return n.buffer}static toString(e){const r=K.toUint8Array(e);let n="";for(let s=0;s<r.length;s++)n+=String.fromCharCode(r[s]);return decodeURIComponent(escape(n))}}class Gt{static toString(e,r=!1){const n=K.toArrayBuffer(e),o=new DataView(n);let s="";for(let i=0;i<n.byteLength;i+=2){const a=o.getUint16(i,r);s+=String.fromCharCode(a)}return s}static fromString(e,r=!1){const n=new ArrayBuffer(e.length*2),o=new DataView(n);for(let s=0;s<e.length;s++)o.setUint16(s*2,e.charCodeAt(s),r);return n}}class ee{static isHex(e){return typeof e===Uc&&mk.test(e)}static isBase64(e){return typeof e===Uc&&yk.test(e)}static isBase64Url(e){return typeof e===Uc&&gk.test(e)}static ToString(e,r="utf8"){const n=K.toUint8Array(e);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Gt.toString(n,!0);case"utf16":case"utf16be":return Gt.toString(n);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromString(e,r="utf8"){if(!e)return new ArrayBuffer(0);switch(r.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Gt.fromString(e,!0);case"utf16":case"utf16be":return Gt.fromString(e);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToBase64(e){const r=K.toUint8Array(e);if(typeof btoa<"u"){const n=this.ToString(r,"binary");return btoa(n)}else return Buffer.from(r).toString("base64")}static FromBase64(e){const r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!ee.isBase64(r))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(r)):new Uint8Array(Buffer.from(r,"base64")).buffer}static FromBase64Url(e){const r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!ee.isBase64Url(r))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(r.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,r=ee.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.FromBinary(e);case"utf8":return Rp.fromString(e);case"utf16":case"utf16be":return Gt.fromString(e);case"utf16le":case"usc2":return Gt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToUtf8String(e,r=ee.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.ToBinary(e);case"utf8":return Rp.toString(e);case"utf16":case"utf16be":return Gt.toString(e);case"utf16le":case"usc2":return Gt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromBinary(e){const r=e.length,n=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);return n.buffer}static ToBinary(e){const r=K.toUint8Array(e);let n="";for(let o=0;o<r.length;o++)n+=String.fromCharCode(r[o]);return n}static ToHex(e){const r=K.toUint8Array(e);let n="";const o=r.length;for(let s=0;s<o;s++){const i=r[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!ee.isHex(r))throw new TypeError("Argument 'hexString' is not HEX encoded");r.length%2&&(r=`0${r}`);const n=new Uint8Array(r.length/2);for(let o=0;o<r.length;o=o+2){const s=r.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(e,r=!1){return Gt.toString(e,r)}static FromUtf16String(e,r=!1){return Gt.fromString(e,r)}static Base64Padding(e){const r=4-e.length%4;if(r<4)for(let n=0;n<r;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}}ee.DEFAULT_UTF8_ENCODING="utf8";function vk(...t){const e=t.map(o=>o.byteLength).reduce((o,s)=>o+s),r=new Uint8Array(e);let n=0;return t.map(o=>new Uint8Array(o)).forEach(o=>{for(const s of o)r[n++]=s}),r.buffer}function bk(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let o=0;o<t.byteLength;o++)if(r[o]!==n[o])return!1;return!0}function eo(t,e){let r=0;if(t.length===1)return t[0];for(let n=t.length-1;n>=0;n--)r+=t[t.length-1-n]*Math.pow(2,e*n);return r}function ln(t,e,r=-1){const n=r;let o=t,s=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(t<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}const u=new Uint8Array(c);for(let d=a-1;d>=0;d--){const l=Math.pow(2,d*e);u[s-d-1]=Math.floor(o/l),o-=u[s-d-1]*l}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function mu(...t){let e=0,r=0;for(const s of t)e+=s.length;const n=new ArrayBuffer(e),o=new Uint8Array(n);for(const s of t)o.set(s,r),r+=s.length;return o}function lg(){const t=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const a=t[0]===255&&t[1]&128,c=t[0]===0&&(t[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}const e=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)r[a]=0;r[0]=t[0]&128;const n=eo(r,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=t[a];return s[0]&=127,eo(s,8)-n}function wk(t){const e=t<0?t*-1:t;let r=128;for(let n=1;n<8;n++){if(e<=r){if(t<0){const i=r-e,a=ln(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=ln(e,8,n),s=new Uint8Array(o);if(s[0]&128){const i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}r*=Math.pow(2,8)}return new ArrayBuffer(0)}function Ak(t,e){if(t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let o=0;o<r.length;o++)if(r[o]!==n[o])return!1;return!0}function ht(t,e){const r=t.toString(10);if(e<r.length)return"";const n=e-r.length,o=Array.from({length:n});for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(r)}function $i(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function gd(t){let e=0,r=0;for(let o=0;o<t.length;o++){const s=t[o];e+=s.byteLength}const n=new Uint8Array(e);for(let o=0;o<t.length;o++){const s=t[o];n.set(new Uint8Array(s),r),r+=s.byteLength}return n.buffer}function Sr(t,e,r,n){return e instanceof Uint8Array?e.byteLength?r<0?(t.error="Wrong parameter: inputOffset less than zero",!1):n<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-r-n<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class ka{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return gd(this.items)}}const No=[new Uint8Array([1])],Mp="0123456789",Vc="name",_p="valueHexView",Sk="isHexOnly",kk="idBlock",Ek="tagClass",xk="tagNumber",Ik="isConstructed",Ok="fromBER",Ck="toBER",Nk="local",ot="",nr=new ArrayBuffer(0),Ea=new Uint8Array(0),ys="EndOfContent",dg="OCTET STRING",fg="BIT STRING";function or(t){var e;return e=class extends t{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var o;super(...n);const s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?K.toUint8Array(s.valueHex):Ea}fromBER(n,o,s,i){const a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Sr(this,a,o,s))return-1;const c=o+s;return this.valueHexView=a.subarray(o,c),this.valueHexView.length?(this.blockLength=s,c):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",nr)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ee.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}class On{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:r=ot,warnings:n=[],valueBeforeDecode:o=Ea}={}){this.blockLength=e,this.error=r,this.warnings=n,this.valueBeforeDecodeView=K.toUint8Array(o)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ee.ToHex(this.valueBeforeDecodeView)}}}On.NAME="baseBlock";class Xe extends On{fromBER(e,r,n,o){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Xe.NAME="valueBlock";class pg extends or(On){constructor({idBlock:e={}}={}){var r,n,o,s;super(),e?(this.isHexOnly=(r=e.isHexOnly)!==null&&r!==void 0?r:!1,this.valueHexView=e.valueHex?K.toUint8Array(e.valueHex):Ea,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=e.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=e.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let r=0;switch(this.tagClass){case 1:r|=0;break;case 2:r|=64;break;case 3:r|=128;break;case 4:r|=192;break;default:return this.error="Unknown tag class",nr}if(this.isConstructed&&(r|=32),this.tagNumber<31&&!this.isHexOnly){const o=new Uint8Array(1);if(!e){let s=this.tagNumber;s&=31,r|=s,o[0]=r}return o.buffer}if(!this.isHexOnly){const o=ln(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=r|31,!e){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}const n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=r|31,!e){const o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(e,r,n){const o=K.toUint8Array(e);if(!Sr(this,o,r,n))return-1;const s=o.subarray(r,r+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;const a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){const d=c+1;if(d>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(s[d]&128)===0)break}this.blockLength=c+1;const u=this.valueHexView=new Uint8Array(c);for(let d=0;d<c;d++)u[d]=s[d+1]&127;this.blockLength<=9?this.tagNumber=eo(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return r+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}pg.NAME="identificationBlock";class hg extends On{constructor({lenBlock:e={}}={}){var r,n,o;super(),this.isIndefiniteForm=(r=e.isIndefiniteForm)!==null&&r!==void 0?r:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=e.length)!==null&&o!==void 0?o:0}fromBER(e,r,n){const o=K.toUint8Array(e);if(!Sr(this,o,r,n))return-1;const s=o.subarray(r,r+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,r+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,r+this.blockLength;const i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const a=r+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=eo(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,r+this.blockLength}toBER(e=!1){let r,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=128),r;if(this.longFormUsed){const o=ln(this.length,8);if(o.byteLength>127)return this.error="Too big length",nr;if(r=new ArrayBuffer(o.byteLength+1),e)return r;const s=new Uint8Array(o);n=new Uint8Array(r),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return r}return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=this.length),r}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}hg.NAME="lengthBlock";const Y={};class Ve extends On{constructor({name:e=ot,optional:r=!1,primitiveSchema:n,...o}={},s){super(o),this.name=e,this.optional=r,n&&(this.primitiveSchema=n),this.idBlock=new pg(o),this.lenBlock=new hg(o),this.valueBlock=s?new s(o):new Xe(o)}fromBER(e,r,n,o){const s=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}toBER(e,r){const n=r||new ka;r||mg(this);const o=this.idBlock.toBER(e);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{const s=this.valueBlock.toBER(e);this.lenBlock.length=s.byteLength;const i=this.lenBlock.toBER(e);n.write(i),n.write(s)}return r?nr:n.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():ee.ToHex(this.toBER())}onAsciiEncoding(){const e=this.constructor.NAME,r=ee.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${r}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;const r=this.toBER(),n=e.toBER();return Ak(r,n)}}Ve.NAME="BaseBlock";function mg(t){var e;if(t instanceof Y.Constructed)for(const r of t.valueBlock.value)mg(r)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}class vd extends Ve{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=ot,...r}={},n){super(r,n),e&&this.fromString(e)}fromBER(e,r,n){const o=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}vd.NAME="BaseStringBlock";class yg extends or(Xe){constructor({isHexOnly:e=!0,...r}={}){super(r),this.isHexOnly=e}}yg.NAME="PrimitiveValueBlock";var gg;class Rs extends Ve{constructor(e={}){super(e,yg),this.idBlock.isConstructed=!1}}gg=Rs;Y.Primitive=gg;Rs.NAME="PRIMITIVE";const vg=100,bg=1e4,wg=16*1024*1024,Tk="Maximum ASN.1 nesting depth exceeded",$k="Maximum ASN.1 node count exceeded",Bk="Maximum ASN.1 content length exceeded";function Ms(t={}){var e,r,n;return{depth:0,maxDepth:(e=t.maxDepth)!==null&&e!==void 0?e:vg,nodesCount:0,maxNodes:(r=t.maxNodes)!==null&&r!==void 0?r:bg,maxContentLength:(n=t.maxContentLength)!==null&&n!==void 0?n:wg}}function Rk(t){const e=new Ve({},Xe);return e.error=t,{offset:-1,result:e}}function Mk(t){if(t.nodesCount+=1,t.nodesCount>t.maxNodes)return $k}function _k(t,e){if(t>e.maxContentLength)return Bk}function bd(t,e,r,n){const o=n.depth+1;if(o>n.maxDepth)return Rk(Tk);n.depth=o;try{return xa(t,e,r,n)}finally{n.depth-=1}}function jk(t,e){if(t instanceof e)return t;const r=new e;return r.idBlock=t.idBlock,r.lenBlock=t.lenBlock,r.warnings=t.warnings,r.valueBeforeDecodeView=t.valueBeforeDecodeView,r}function xa(t,e=0,r=t.length,n=Ms()){const o=e;let s=new Ve({},Xe);const i=new On;if(!Sr(i,t,e,r))return s.error=i.error,{offset:-1,result:s};if(!t.subarray(e,e+r).length)return s.error="Zero buffer length",{offset:-1,result:s};const c=Mk(n);if(c)return s.error=c,{offset:-1,result:s};let u=s.idBlock.fromBER(t,e,r);if(s.idBlock.warnings.length&&s.warnings.concat(s.idBlock.warnings),u===-1)return s.error=s.idBlock.error,{offset:-1,result:s};if(e=u,r-=s.idBlock.blockLength,u=s.lenBlock.fromBER(t,e,r),s.lenBlock.warnings.length&&s.warnings.concat(s.lenBlock.warnings),u===-1)return s.error=s.lenBlock.error,{offset:-1,result:s};e=u,r-=s.lenBlock.blockLength;const d=s.lenBlock.isIndefiniteForm?r:s.lenBlock.length,l=_k(d,n);if(l)return s.error=l,{offset:-1,result:s};if(!s.idBlock.isConstructed&&s.lenBlock.isIndefiniteForm)return s.error="Indefinite length form used for primitive encoding form",{offset:-1,result:s};let m=Ve;switch(s.idBlock.tagClass){case 1:if(s.idBlock.tagNumber>=37&&s.idBlock.isHexOnly===!1)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};m=Y.EndOfContent;break;case 1:m=Y.Boolean;break;case 2:m=Y.Integer;break;case 3:m=Y.BitString;break;case 4:m=Y.OctetString;break;case 5:m=Y.Null;break;case 6:m=Y.ObjectIdentifier;break;case 10:m=Y.Enumerated;break;case 12:m=Y.Utf8String;break;case 13:m=Y.RelativeObjectIdentifier;break;case 14:m=Y.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:m=Y.Sequence;break;case 17:m=Y.Set;break;case 18:m=Y.NumericString;break;case 19:m=Y.PrintableString;break;case 20:m=Y.TeletexString;break;case 21:m=Y.VideotexString;break;case 22:m=Y.IA5String;break;case 23:m=Y.UTCTime;break;case 24:m=Y.GeneralizedTime;break;case 25:m=Y.GraphicString;break;case 26:m=Y.VisibleString;break;case 27:m=Y.GeneralString;break;case 28:m=Y.UniversalString;break;case 29:m=Y.CharacterString;break;case 30:m=Y.BmpString;break;case 31:m=Y.DATE;break;case 32:m=Y.TimeOfDay;break;case 33:m=Y.DateTime;break;case 34:m=Y.Duration;break;default:{const p=s.idBlock.isConstructed?new Y.Constructed:new Y.Primitive;p.idBlock=s.idBlock,p.lenBlock=s.lenBlock,p.warnings=s.warnings,s=p}}break;default:m=s.idBlock.isConstructed?Y.Constructed:Y.Primitive}return s=jk(s,m),u=s.fromBER(t,e,d,n),s.valueBeforeDecodeView=t.subarray(o,o+s.blockLength),{offset:u,result:s}}function Gn(t,e={}){if(!t.byteLength){const r=new Ve({},Xe);return r.error="Input buffer has zero length",{offset:-1,result:r}}return xa(K.toUint8Array(t).slice(),0,t.byteLength,Ms(e))}function Dk(t,e){return t?1:e}class Rr extends Xe{constructor({value:e=[],isIndefiniteForm:r=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=r}fromBER(e,r,n,o){const s=K.toUint8Array(e),i=o??Ms();if(!Sr(this,s,r,n))return-1;if(this.valueBeforeDecodeView=s.subarray(r,r+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),r;let a=r;for(;Dk(this.isIndefiniteForm,n)>0;){const c=bd(s,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===ys)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===ys?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,r){const n=r||new ka;for(let o=0;o<this.value.length;o++)this.value[o].toBER(e,n);return r?nr:n.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const r of this.value)e.value.push(r.toJSON());return e}}Rr.NAME="ConstructedValueBlock";var Ag;class et extends Ve{constructor(e={}){super(e,Rr),this.idBlock.isConstructed=!0}fromBER(e,r,n,o){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const s=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,o);return s===-1?(this.error=this.valueBlock.error,s):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){const e=[];for(const n of this.valueBlock.value)e.push(n.toString("ascii").split(`
102
- `).map(o=>` ${o}`).join(`
101
+ ORDER BY occurred_at, id`);for(const m of u){const p=m.indexOf(":");if(p<0)continue;const h=d.all(m.slice(0,p),m.slice(p+1));for(const g of h)l.push(e(g))}return l}}}function og(t){const[e,r,n]=Ta(t).map(kA);return{db:e,wal:r,shm:n,total:e+r+n}}function kA(t){try{return ka(t).size}catch{return 0}}function Ai(t,e,r){if(t!=null)try{const n=JSON.parse(String(t));if(n&&typeof n=="object")return n;e&&r?.(e);return}catch{e&&r?.(e);return}}function ig(t,e){const r=t,n=e?s=>e(s,String(r.id)):void 0;return{id:String(r.id),source:{id:String(r.source_id),instance:String(r.source_instance)},occurredAt:Number(r.occurred_at),observedAt:Number(r.observed_at),clock:r.clock,kind:r.kind,subject:{type:r.subject_type,id:String(r.subject_id)},core:Ai(r.core,"core",n),attrs:Ai(r.attrs,"attrs",n),basis:r.basis,assumption:r.assumption?String(r.assumption):void 0,stratum:r.stratum?r.stratum:void 0,provenance:Ai(r.provenance,"provenance",n)}}const xp={tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"};function ag(t){const e=new Map;for(const o of t.declarations)o.kind==="began"&&e.set(`${o.subject.type}:${o.subject.id}`,o);const r=[...t.state.executions.values()].map(o=>EA(o,t,e)).sort((o,i)=>o.start.at-i.start.at||o.ref.localeCompare(i.ref)),n=new Set(r.map(o=>o.ref)),s=[...t.state.sessions.values()].map(o=>({ref:_r("session",o.id),executionRefs:o.executionIds.map(i=>_r("execution",i)).filter(i=>n.has(i)).sort(),spawnedBy:o.parentId?at({ref:_r("session",o.parentId)}):yn("no parent session was reported")})).filter(o=>o.executionRefs.length>0).sort((o,i)=>o.ref.localeCompare(i.ref));return{experimental:!0,window:{from:t.from,to:t.to},executions:r,sessions:s,summary:TA(r,s,t.from,t.to,gd(t.state))}}function EA(t,e,r){const n=r.get(`execution:${t.id}`),s=n?.source.id,o=s?e.capabilities.get(s)??xp:xp,i=e.state.sessions.get(t.sessionId),a=e.state.machines.get(t.machineId),c=t.status==="completed"||t.status==="failed",u=IA(n?.occurredAt??t.startedAt,n?.basis??t.startBasis),l=e.relationships.filter(h=>h.kind==="ran-as"&&(h.from.type==="execution"&&h.from.id===t.id&&h.to.type==="process"||h.to.type==="execution"&&h.to.id===t.id&&h.from.type==="process")).map(h=>{const g=h.from.type==="process"?h.from:h.to;return{kind:"ran-as",target:{type:"process",ref:_r("process",g.id)},evidence:xA(h.basis),...h.basis==="inferred"?{qualification:"resolved from overlapping identity claims"}:{}}}).sort((h,g)=>h.target.ref.localeCompare(g.target.ref)),d=i?.context,m=t.model??i?.model,p={current:t.status==="waiting",...t.waitReason?{reason:t.waitReason}:{},count:t.waits.length+(t.waitingSince===void 0?0:1),durationMs:t.waitingMs+(t.waitingSince===void 0?0:Math.max(0,e.to-t.waitingSince))};return{ref:_r("execution",t.id),observer:s??"unknown-observer",sessionRef:_r("session",t.sessionId),machine:t.machineId?at({ref:_r("machine",t.machineId),...a?{kind:a.kind}:{}}):yn("no machine was reported"),context:d?Cu(o.context,{ref:_r("context",d)},"context"):ki(o.context,"context"),executor:t.executor&&t.executor!=="unknown"?at(t.executor):yn("no executor was reported"),model:m?Cu(o.model,m,"model"):ki(o.model,"model"),start:u,end:t.endedAt===void 0?wr(e.to,"the execution is open; query time is an elapsed wall bound, not a terminal end"):t.endBasis==="inferred"?Ao(t.endedAt,"the terminal bound was inferred by its observer"):at(t.endedAt),lifecycle:CA(t),outcome:OA(t,o.outcome),measures:{tokens:{input:Br(t,z.tokensInput,o.tokens,c,!1,"token input"),output:Br(t,z.tokensOutput,o.tokens,c,!1,"token output"),cacheRead:Br(t,z.tokensCacheRead,o.tokens,c,!1,"cache-read tokens"),reasoning:Br(t,z.tokensReasoning,o.tokens,c,!1,"reasoning tokens"),total:cg(Hr(t.measures),o.tokens,c,!1,"token total")},requests:Br(t,z.steps,o.requests,c,!0,"requests"),toolInteractions:Br(t,z.interactions,o.toolInteractions,c,!0,"tool interactions"),toolErrors:Br(t,z.errors,o.toolErrors,c,!0,"tool errors"),retries:Br(t,z.retries,o.retries,c,!0,"retries")},wait:NA(p,o.waits,c),failure:t.status==="failed"?at("execution-failed"):c?o.outcome==="supported"?at("none"):ki(o.outcome,"failure state"):Gt("the execution is not terminal"),depth:t.depth,relationships:l}}function _r(t,e){const r=vs("sha256").update(`057-activity\0${t}\0${e}`).digest("hex").slice(0,16);return`${t}_${r}`}function xA(t){return t==="inferred"?"inferred":"observed"}function IA(t,e){return e==="inferred"?{at:t,evidence:"inferred",qualification:"the observer inferred this temporal bound"}:e===void 0?{at:t,evidence:"inferred",qualification:"a legacy record did not declare its timing basis"}:{at:t,evidence:"observed"}}function CA(t){return t.status==="waiting"?{state:"waiting",evidence:"observed"}:t.status==="running"?{state:"running",evidence:"observed"}:t.status==="idle"?{state:"idle",evidence:"inferred",qualification:"no activity was observed for the idle threshold"}:{state:"terminal",evidence:t.endBasis==="inferred"?"inferred":"observed",...t.endBasis==="inferred"?{qualification:"the observer inferred the terminal bound"}:{}}}function OA(t,e){if(t.status!=="completed"&&t.status!=="failed")return Gt("the execution is not terminal");const r=t.outcome==="error"?"failed":t.outcome==="interrupted"?"interrupted":t.outcome==="completed"?"completed":void 0;return r?t.endBasis==="inferred"?Ao(r,"the terminal outcome follows an inferred terminal bound"):Cu(e,r,"outcome"):ki(e,"outcome")}function Br(t,e,r,n,s,o){return cg(et(t.measures,e),r,n,s,o)}function cg(t,e,r,n,s){return e==="unsupported"?_n(`this observer does not report ${s}`):e==="unknown"?Gt(`coverage for ${s} is not declared`):e==="partial"?wr(t,`this observer reports ${s} only partially`):r?t!==void 0?at(t):n?at(0):yn(`${s} was not present in this execution`):wr(t,`${s} may still increase while the execution is active`)}function NA(t,e,r){return e==="unsupported"?_n("this observer does not report explicit waits"):e==="unknown"?Gt("wait coverage is not declared"):e==="partial"?wr(t,"this observer reports explicit waits only partially"):!r||t.current?wr(t,"an explicit wait may still be open"):at(t)}function Cu(t,e,r){return t==="supported"?at(e):t==="partial"?wr(e,`this observer reports ${r} only partially`):t==="unsupported"?_n(`this observer does not report ${r}`):Gt(`coverage for ${r} is not declared`)}function ki(t,e){return t==="supported"?yn(`${e} was not present in this execution`):t==="partial"?wr(void 0,`this observer reports ${e} only partially`):t==="unsupported"?_n(`this observer does not report ${e}`):Gt(`coverage for ${e} is not declared`)}function at(t){return{state:"observed",value:t}}function Ao(t,e){return{state:"inferred",value:t,qualification:e}}function wr(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function _n(t){return{state:"unsupported",qualification:t}}function yn(t){return{state:"not-observed",qualification:t}}function Gt(t){return{state:"unknown",qualification:t}}function TA(t,e,r,n,s){const o=t.map(h=>({start:Math.max(r,h.start.at),end:Math.min(n,gt(h.end)??n),inferred:h.start.evidence==="inferred"||h.end.state==="inferred",partial:h.end.state!=="observed"&&h.end.state!=="inferred"})),i=un(o.map(h=>h.partial?"partial":h.inferred?"inferred":"observed")),a=Op(o),c=Np(o),u=t.filter(h=>h.lifecycle.state==="terminal"),l=u.flatMap(h=>{const g=gt(h.end);return g===void 0?[]:[{start:Math.max(r,h.start.at),end:Math.min(n,g),inferred:h.start.evidence==="inferred"||h.end.state==="inferred"}]}),d=un(u.map(h=>gt(h.end)===void 0?"unknown":h.start.evidence==="inferred"||h.end.state==="inferred"?"inferred":"observed")),m=Op(l),p=un(t.map(h=>h.lifecycle.state==="terminal"?"inferred":"partial"));return{executions:t.length,sessions:e.length,openExecutions:t.length-u.length,terminalExecutions:u.length,runningNow:t.filter(h=>h.lifecycle.state==="running").length,waitingNow:Gn(t.map($A)),idleNow:t.filter(h=>h.lifecycle.state==="idle").length,completed:zc(u,"completed"),failed:zc(u,"failed"),interrupted:zc(u,"interrupted"),inFlight:{totalMs:ht(s.timeInFlight.value,p),openContributionMs:ht(Math.max(0,s.timeInFlight.value-m),p),parallelMs:ht(s.parallelTime.value,p),peak:ht({peak:s.peakConcurrency.value,at:s.peakConcurrency.value>0?s.peakConcurrencyAt.value:null},p),assumption:By},executionWallIntervalMs:ht(a,i),peakExecutionConcurrency:ht(c,i),executionDuration:Gc(t.map(h=>{const g=gt(h.end)??n,v=Math.max(0,g-h.start.at);return h.end.state!=="observed"&&h.end.state!=="inferred"?wr(v,"elapsed wall duration for an open execution"):h.start.evidence==="inferred"||h.end.state==="inferred"?Ao(v,"one or more execution bounds were inferred"):at(v)})),terminalExecutionDuration:Gc(u.map(h=>{const g=gt(h.end);if(g===void 0)return Gt("the terminal execution has no usable end bound");const v=Math.max(0,g-h.start.at);return h.start.evidence==="inferred"||h.end.state==="inferred"?Ao(v,"one or more execution bounds were inferred"):at(v)})),terminalExecutionIntervalMs:ht(m,d),overlappingTerminalIntervalMs:ht(MA(l),d),peakTerminalConcurrency:ht(Np(l),d),sessionExecutionCount:Gc(e.map(h=>at(h.executionRefs.length))),tokens:Gn(t.map(h=>h.measures.tokens.total)),toolInteractions:Gn(t.map(h=>h.measures.toolInteractions)),toolErrors:Gn(t.map(h=>h.measures.toolErrors)),waits:BA(t.map(h=>h.wait)),usageByModel:_A(t),executionsWithoutModel:t.filter(h=>gt(h.model)===void 0).length,modelMix:Cp(t,h=>Ip(h.model)),executorMix:Cp(t,h=>Ip(h.executor))}}function gt(t){return"value"in t?t.value:void 0}function Ip(t){return gt(t)??`[${t.state}]`}function un(t){const e={records:t.length,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0};for(const r of t)r==="not-observed"?e.notObserved++:e[r]++;return e}function ht(t,e){return e.partial+e.unsupported+e.notObserved+e.unknown>0?{state:"partial",value:t,qualification:"coverage is incomplete",coverage:e}:e.inferred>0?{state:"inferred",value:t,qualification:"one or more bounds were inferred",coverage:e}:{state:"observed",value:t,coverage:e}}function Gn(t){const e=un(t.map(s=>s.state));let r=0,n=0;for(const s of t){const o=gt(s);o!==void 0&&(r+=o,n++)}return n>0?ht(r,e):e.records>0&&e.unsupported===e.records?{..._n("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...yn("no value was observed"),coverage:e}:{...Gt("no usable value was observed"),coverage:e}}function Gc(t){const e=un(t.map(n=>n.state)),r=t.map(gt).filter(n=>n!==void 0).sort((n,s)=>n-s);return r.length===0?{...Gt("no usable duration samples were observed"),coverage:e}:ht({samples:r.length,minimum:r[0],median:qc(r,.5),p75:qc(r,.75),p90:qc(r,.9),maximum:r[r.length-1]},e)}function qc(t,e){const r=(t.length-1)*e,n=Math.floor(r),s=Math.ceil(r);return n===s?t[n]:t[n]+(t[s]-t[n])*(r-n)}function $A(t){const e=gt(t.wait);return ug(t.wait,e?.current?1:0)}function zc(t,e){return t.length===0?ht(0,un([])):Gn(t.map(r=>{const n=gt(r.outcome);return ug(r.outcome,n===e?1:0)}))}function ug(t,e){switch(t.state){case"observed":return at(e);case"inferred":return Ao(e,t.qualification);case"partial":return wr("value"in t?e:void 0,t.qualification);case"unsupported":return _n(t.qualification);case"not-observed":return yn(t.qualification);case"unknown":return Gt(t.qualification)}}function BA(t){const e=un(t.map(s=>s.state));let r=0;const n={count:0,durationMs:0,openNow:0};for(const s of t){const o=gt(s);o&&(r++,n.count+=o.count,n.durationMs+=o.durationMs,o.current&&n.openNow++)}return r>0?ht(n,e):e.unsupported===e.records?{..._n("no observer reports explicit waits"),coverage:e}:{...Gt("no usable wait value was observed"),coverage:e}}function _A(t){const e=new Map;for(const r of t){const n=gt(r.model);if(!n)continue;const s=e.get(n)??[];s.push(r.measures.tokens.total),e.set(n,s)}return[...e.entries()].map(([r,n])=>({model:r,executions:n.length,tokens:Gn(n)})).sort((r,n)=>n.executions-r.executions||r.model.localeCompare(n.model))}function Cp(t,e){const r=new Map;for(const n of t){const s=e(n);r.set(s,(r.get(s)??0)+1)}return[...r.entries()].map(([n,s])=>({key:n,executions:s})).sort((n,s)=>s.executions-n.executions||n.key.localeCompare(s.key))}function Op(t){const e=t.filter(o=>o.end>o.start).map(o=>({start:o.start,end:o.end})).sort((o,i)=>o.start-i.start||o.end-i.end);let r=0,n,s=0;for(const o of e)n===void 0?(n=o.start,s=o.end):o.start<=s?s=Math.max(s,o.end):(r+=s-n,n=o.start,s=o.end);return r+(n===void 0?0:s-n)}function Np(t){const e=[];for(const o of t)o.end<=o.start||e.push({at:o.start,delta:1},{at:o.end,delta:-1});e.sort((o,i)=>o.at-i.at||o.delta-i.delta);let r=0,n=0,s=null;for(const o of e)r+=o.delta,r>n&&(n=r,s=o.at);return{peak:n,at:s}}function MA(t){const e=[];for(const o of t)o.end<=o.start||e.push({at:o.start,delta:1},{at:o.end,delta:-1});e.sort((o,i)=>o.at-i.at||o.delta-i.delta);let r=0,n,s=0;for(const o of e)n!==void 0&&r>=2&&(s+=o.at-n),r+=o.delta,n=o.at;return s}function ko(t,e){const r=t.window,n=Ot(e.continuity),s=e.continuity.state==="observed"&&n!==void 0&&n.from<=r.from&&n.to>=r.to,o=e.retention.state==="within-retention"||e.retention.state==="retained-indefinitely",i=t.executions.length,a=[];let c,u;o?s?(c="observed",u="comparable"):i>0?(c="partially-observed",u="partially-comparable",a.push("execution records are present, but historical observation continuity is unknown")):(c="unknown",u="not-comparable",a.push("zero execution records cannot distinguish a quiet period from an unobserved period")):(c="not-sufficiently-observed",u="not-comparable",a.push("the requested period is not wholly inside semantic retention"));const l=t.executions.map(v=>v.start.at),d=t.executions.map(v=>Ot(v.end)??v.start.at),m=i>0?yr({from:Math.min(...l),to:Math.max(...d)}):br("no execution records establish an observed span"),p=new Map;for(const v of t.executions){const b=p.get(v.observer)??[];b.push(v),p.set(v.observer,b)}const h=[...p.entries()].map(([v,b])=>({source:v,executionRecords:b.length,firstExecutionAt:Math.min(...b.map(_=>_.start.at)),lastExecutionAt:Math.max(...b.map(_=>_.start.at)),capabilities:e.capabilities.get(v)??VA()})).sort((v,b)=>b.executionRecords-v.executionRecords||v.source.localeCompare(b.source)),g=[Ms("tokens",t.summary.tokens),Ms("tool-interactions",t.summary.toolInteractions),Ms("tool-errors",t.summary.toolErrors),Ms("waits",t.summary.waits),Yc("outcomes",t.executions.map(v=>v.outcome)),Ms("bounds",HA(t.executions)),Yc("model",t.executions.map(v=>v.model)),Yc("executor",t.executions.map(v=>v.executor))];return{experimental:!0,period:r,observation:c,recordPresence:i>0?"present":"none",executionRecords:i,sessionRecords:t.sessions.length,continuity:e.continuity,observationGaps:s?yr([]):br("historical observation gaps are not retained"),unprojectedSourceWork:br("observers do not currently retain counts for source work omitted before a timed execution could be projected"),retention:e.retention,observedSpan:m,sources:h,measures:g,bounds:{observedStarts:t.executions.filter(v=>v.start.evidence==="observed").length,inferredStarts:t.executions.filter(v=>v.start.evidence==="inferred").length,observedEnds:t.executions.filter(v=>v.end.state==="observed").length,inferredEnds:t.executions.filter(v=>v.end.state==="inferred").length,openEnds:t.executions.filter(v=>v.end.state!=="observed"&&v.end.state!=="inferred").length},comparisonReadiness:u,reasons:a}}function RA(t,e){const r=ko(t,e),n=r.comparisonReadiness==="not-comparable"?jA(t.summary):t.summary;return{experimental:!0,period:t.window,availability:r,summary:n}}function jA(t){const e=r=>({state:"unknown",qualification:"the period was not sufficiently observed",coverage:r.coverage});return{...t,waitingNow:e(t.waitingNow),completed:e(t.completed),failed:e(t.failed),interrupted:e(t.interrupted),inFlight:{...t.inFlight,totalMs:e(t.inFlight.totalMs),openContributionMs:e(t.inFlight.openContributionMs),parallelMs:e(t.inFlight.parallelMs),peak:e(t.inFlight.peak)},executionWallIntervalMs:e(t.executionWallIntervalMs),peakExecutionConcurrency:e(t.peakExecutionConcurrency),executionDuration:e(t.executionDuration),terminalExecutionDuration:e(t.terminalExecutionDuration),terminalExecutionIntervalMs:e(t.terminalExecutionIntervalMs),overlappingTerminalIntervalMs:e(t.overlappingTerminalIntervalMs),peakTerminalConcurrency:e(t.peakTerminalConcurrency),sessionExecutionCount:e(t.sessionExecutionCount),tokens:e(t.tokens),toolInteractions:e(t.toolInteractions),toolErrors:e(t.toolErrors),waits:e(t.waits),usageByModel:t.usageByModel.map(r=>({...r,tokens:e(r.tokens)}))}}function DA(t,e,r){const n=new Map;for(const o of t.executions){const i=PA(o,r),a=n.get(i)??[];a.push(o),n.set(i,a)}const s=[...n.entries()].map(([o,i])=>LA(o,i)).sort((o,i)=>i.executions-o.executions||o.key.localeCompare(i.key));return{experimental:!0,period:t.window,dimension:r,availability:ko(t,e),items:s,qualification:r==="model"||r==="executor"?"Observed differences describe grouped records; they do not establish causal performance differences.":"Breakdown counts only privacy-reduced execution records present in this period."}}function lg(t,e,r,n){const s=ko(t,e),o=ko(r,n),i=UA(s.comparisonReadiness,o.comparisonReadiness),a=t.window.to-t.window.from===r.window.to-r.window.from,c=a?i:"not-comparable",u=[...s.reasons.map(d=>`period A: ${d}`),...o.reasons.map(d=>`period B: ${d}`),...a?[]:["the requested periods do not have equal duration"]],l=[Ds("execution records",ui(t.executions.length,s),ui(r.executions.length,o),c),Ds("session records",ui(t.sessions.length,s),ui(r.sessions.length,o),c),jt("median terminal execution duration",$p(t.summary.terminalExecutionDuration),$p(r.summary.terminalExecutionDuration),c,s,o),jt("terminal execution interval union",t.summary.terminalExecutionIntervalMs,r.summary.terminalExecutionIntervalMs,c,s,o),jt("overlapping terminal interval",t.summary.overlappingTerminalIntervalMs,r.summary.overlappingTerminalIntervalMs,c,s,o),jt("peak terminal concurrency",Ps(t.summary.peakTerminalConcurrency,d=>d.peak),Ps(r.summary.peakTerminalConcurrency,d=>d.peak),c,s,o),Ds("model mix",qn(yr(li(t.summary.modelMix)),s),qn(yr(li(r.summary.modelMix)),o),c),Ds("executor mix",qn(yr(li(t.summary.executorMix)),s),qn(yr(li(r.summary.executorMix)),o),c),jt("completed executions",t.summary.completed,r.summary.completed,c,s,o),jt("failed executions",t.summary.failed,r.summary.failed,c,s,o),jt("interrupted executions",t.summary.interrupted,r.summary.interrupted,c,s,o),jt("tokens",t.summary.tokens,r.summary.tokens,c,s,o),jt("tool interactions",t.summary.toolInteractions,r.summary.toolInteractions,c,s,o),jt("tool errors",t.summary.toolErrors,r.summary.toolErrors,c,s,o),jt("explicit wait count",Ps(t.summary.waits,d=>d.count),Ps(r.summary.waits,d=>d.count),c,s,o)];return{experimental:!0,eligibility:c,periodA:t.window,periodB:r.window,availabilityA:s,availabilityB:o,dimensions:l,reasons:u}}function PA(t,e){switch(e){case"model":return Ot(t.model)??`[${t.model.state}]`;case"executor":return Ot(t.executor)??`[${t.executor.state}]`;case"lifecycle":return t.lifecycle.state;case"outcome":return t.lifecycle.state==="terminal"?Ot(t.outcome)??"unknown":"open";case"session":return t.sessionRef;case"duration-band":{if(t.lifecycle.state!=="terminal")return"open";const r=Ot(t.end);if(r===void 0)return"[unknown-duration]";const n=Math.max(0,r-t.start.at);return n<6e4?"under-1m":n<3e5?"1m-to-5m":n<18e5?"5m-to-30m":"30m-or-more"}}}function LA(t,e){const r=e.filter(n=>n.lifecycle.state==="terminal");return{key:t,executions:e.length,terminalExecutions:r.length,terminalDuration:WA(r.map(n=>{const s=Ot(n.end);if(s===void 0)return br("the terminal execution has no usable end bound");const o=Math.max(0,s-n.start.at);return n.start.evidence==="inferred"||n.end.state==="inferred"?fg(o,"one or more execution bounds were inferred"):yr(o)})),tokens:di(e.map(n=>n.measures.tokens.total)),toolInteractions:di(e.map(n=>n.measures.toolInteractions)),toolErrors:di(e.map(n=>n.measures.toolErrors)),failed:di(r.map(n=>FA(n.outcome,"failed")))}}function ui(t,e){return e.observation==="observed"?yr(t):e.executionRecords>0?pg(t,"record count is known, but observation continuity is not"):br("the period was not sufficiently observed to interpret zero records as zero work")}function jt(t,e,r,n,s,o){return Ds(t,qn(e,s),qn(r,o),n)}function qn(t,e){return e.comparisonReadiness==="not-comparable"?br("the period was not sufficiently observed"):t}function Ds(t,e,r,n){const s=Ot(e)!==void 0&&Ot(r)!==void 0;let o;const i=[];return n==="not-comparable"?(o="not-comparable",i.push("one or both periods are not sufficiently observed")):!s||Tp(e.state)||Tp(r.state)?(o="not-comparable",i.push(`measure states are ${e.state} and ${r.state}`)):n==="partially-comparable"||e.state==="partial"||r.state==="partial"||e.state==="inferred"||r.state==="inferred"?(o="partially-comparable",i.push("the values are present, but period or measure coverage is qualified")):o="comparable",{dimension:t,eligibility:o,periodA:e,periodB:r,reasons:i}}function Tp(t){return t==="unsupported"||t==="not-observed"||t==="unknown"}function UA(t,e){return t==="not-comparable"||e==="not-comparable"?"not-comparable":t==="partially-comparable"||e==="partially-comparable"?"partially-comparable":"comparable"}function $p(t){return Ps(t,e=>e.median)}function Ps(t,e){switch(t.state){case"observed":return{state:"observed",value:e(t.value),coverage:t.coverage};case"inferred":return{state:"inferred",value:e(t.value),qualification:t.qualification,coverage:t.coverage};case"partial":return"value"in t&&t.value!==void 0?{state:"partial",value:e(t.value),qualification:t.qualification,coverage:t.coverage}:{state:"partial",qualification:t.qualification,coverage:t.coverage};case"unsupported":return{...t};case"not-observed":return{...t};case"unknown":return{...t}}}function li(t){return Object.fromEntries(t.map(e=>[e.key,e.executions]))}function Ms(t,e){return{dimension:t,state:e.state,coverage:e.coverage,qualification:dg(e.state)}}function Yc(t,e){const r=_a(e.map(s=>s.state)),n=KA(r);return{dimension:t,state:n,coverage:r,qualification:dg(n)}}function HA(t){const e=t.map(r=>r.end.state!=="observed"&&r.end.state!=="inferred"?"partial":r.start.evidence==="inferred"||r.end.state==="inferred"?"inferred":"observed");return Cd(e.length,_a(e))}function dg(t){switch(t){case"observed":return"all contributing records are observed for this dimension";case"inferred":return"one or more contributing values were inferred";case"partial":return"a subtotal is available, but one or more records are incomplete";case"unsupported":return"the contributing observers do not support this dimension";case"not-observed":return"the dimension is supported but no value was recorded";case"unknown":return"coverage cannot be established"}}function VA(){return{tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"}}function FA(t,e){const r=Ot(t);return qA(t,r===e?1:0)}function di(t){const e=_a(t.map(n=>n.state)),r=t.map(Ot).filter(n=>n!==void 0);return r.length>0?Cd(r.reduce((n,s)=>n+s,0),e):e.records>0&&e.unsupported===e.records?{...hg("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...mg("no value was observed"),coverage:e}:{...br("no usable value was observed"),coverage:e}}function WA(t){const e=_a(t.map(n=>n.state)),r=t.map(Ot).filter(n=>n!==void 0).sort((n,s)=>n-s);return r.length===0?{...br("no terminal duration samples were observed"),coverage:e}:Cd({samples:r.length,minimum:r[0],median:Xc(r,.5),p75:Xc(r,.75),p90:Xc(r,.9),maximum:r[r.length-1]},e)}function Xc(t,e){const r=(t.length-1)*e,n=Math.floor(r),s=Math.ceil(r);return n===s?t[n]:t[n]+(t[s]-t[n])*(r-n)}function Cd(t,e){return e.partial+e.unsupported+e.notObserved+e.unknown>0?{state:"partial",value:t,qualification:"coverage is incomplete",coverage:e}:e.inferred>0?{state:"inferred",value:t,qualification:"one or more values were inferred",coverage:e}:{state:"observed",value:t,coverage:e}}function KA(t){return t.records===0?"unknown":t.unsupported===t.records?"unsupported":t.notObserved===t.records?"not-observed":t.unknown===t.records?"unknown":t.partial+t.unsupported+t.notObserved+t.unknown>0?"partial":t.inferred>0?"inferred":"observed"}function _a(t){const e=GA();e.records=t.length;for(const r of t)r==="not-observed"?e.notObserved++:e[r]++;return e}function GA(){return{records:0,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0}}function Ot(t){return"value"in t?t.value:void 0}function qA(t,e){switch(t.state){case"observed":return yr(e);case"inferred":return fg(e,t.qualification);case"partial":return pg("value"in t?e:void 0,t.qualification);case"unsupported":return hg(t.qualification);case"not-observed":return mg(t.qualification);case"unknown":return br(t.qualification)}}function yr(t){return{state:"observed",value:t}}function fg(t,e){return{state:"inferred",value:t,qualification:e}}function pg(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function hg(t){return{state:"unsupported",qualification:t}}function mg(t){return{state:"not-observed",qualification:t}}function br(t){return{state:"unknown",qualification:t}}const nn="os",zA=(t,e)=>`os:${t}:${e.pid}:${e.startedAt}`;function YA(t,e){const r=/^os:[^:]+:(\d+):(\d+)$/.exec(t);return r?`os:${e}:${r[1]}:${r[2]}`:void 0}const XA=t=>`The process was present in one ${Math.round(t/1e3)}s snapshot and absent from the next, so it exited somewhere in that window. The recorded instant is the last moment it was observed alive — a lower bound on the true exit. A process that started and exited entirely within one interval is never observed at all.`,JA=250,ZA=8*1024*1024;function QA(t,e,r){const n={source:{id:nn,instance:r.host},observedAt:r.observedAt,clock:"wall",stratum:"machine"},s=[],o=new Map;for(const i of e){const a=zA(r.host,i);o.set(a,i);const c={ns:"os.process",parts:[r.host,i.pid],validFrom:i.startedAt,validTo:r.observedAt};if(!t.has(a)){s.push({...n,occurredAt:i.startedAt,kind:"began",subject:{type:"process",id:a},claims:[c],basis:"measured",core:{machineId:r.machineId,pid:i.pid,ppid:i.ppid,label:ek(i.command),executor:i.command,measures:{[z.cpuMs]:i.cpuMs}},attrs:{"os.pid":i.pid,"os.ppid":i.ppid,"os.command":i.command,"os.rssBytes":i.rssBytes}});continue}const u=t.get(a),l=i.cpuMs-u.cpuMs>=JA,d=Math.abs(i.rssBytes-u.rssBytes)>=ZA;(l||d)&&s.push({...n,occurredAt:r.observedAt,seq:`obs:${r.observedAt}`,kind:"observed",subject:{type:"process",id:a},claims:[c],basis:"measured",core:{measures:{[z.cpuMs]:i.cpuMs}},attrs:{"os.rssBytes":i.rssBytes}})}for(const[i,a]of t)o.has(i)||s.push({...n,occurredAt:r.observedAt-r.intervalMs,kind:"ended",subject:{type:"process",id:i},basis:"inferred",assumption:XA(r.intervalMs),core:{outcome:"completed",measures:{[z.cpuMs]:a.cpuMs}},attrs:{"os.pid":a.pid}});return{envelopes:s,next:o}}function ek(t){return(t.split("/").pop()??t).toUpperCase()}function yg(t,e,r,n,s){const o=s?vg(s):void 0,i=t.query(e,r,n),a=i.filter(E=>E.occurredAt<r),c=i.filter(E=>E.occurredAt===r&&E.subject.type==="execution"&&E.kind==="ended"),u=o?zn(a,o):a,l=!n||n.includes("execution")?t.executionCarry(e,r):[],d=o?zn(l,o):l,m=new Set,p=new Set,h=new Map,g=E=>{const I=`${E.subject.type}:${E.subject.id}`;E.kind==="began"?(m.add(I),h.set(I,E)):p.add(I),E.core?.sessionId&&p.add(`session:${E.core.sessionId}`),E.core?.machineId&&p.add(`machine:${E.core.machineId}`)};for(const E of[...d,...u,...c])g(E);const v=[];for(let E=0;E<4;E++){const I=[...p].filter(N=>!m.has(N));if(I.length===0)break;const k=t.begansFor(I).filter(N=>N.occurredAt<=r),w=o?zn(k,o):k;if(w.length===0)break;for(const N of w)h.set(`${N.subject.type}:${N.subject.id}`,N),v.push(N),g(N),m.add(`${N.subject.type}:${N.subject.id}`)}const b=E=>E.occurredAt<e?{...E,occurredAt:e}:E;return{events:[...v.map(b),...d.filter(E=>E.kind==="began").map(b),...u].sort((E,I)=>E.occurredAt-I.occurredAt||is(E)-is(I)),inWindow:u,history:[...v.filter(E=>E.occurredAt<e),...d],rightBounds:o?zn(c,o):c,declarations:[...h.values()],relationships:pw(t.claims(e,r,n)).relationships}}function gg(t,e,r,n,s){const o=performance.now(),{events:i,inWindow:a,history:c,rightBounds:u,declarations:l,relationships:d}=yg(t,e,r,s,n),m=performance.now()-o,p=performance.now(),h=xa(e,r);hd(h,[...c,...i,...u].sort((I,k)=>I.occurredAt-k.occurredAt||is(I)-is(k))),$y(h,r);const g=new Set(a.filter(I=>I.subject.type==="execution").map(I=>I.subject.id)),v=new Map;for(const I of a){if(I.subject.type!=="execution"||!I.core?.measures)continue;const k=v.get(I.subject.id)??{};yo(k,I.core.measures),v.set(I.subject.id,k)}const b=new Map;for(const I of h.executions.values()){if(!g.has(I.id)&&I.status!=="waiting"&&I.status!=="running"&&I.endedAt!==r||I.startedAt>=r)continue;const k=I.waits.map(w=>({start:Math.max(e,w.start),end:Math.min(r,w.end)})).filter(w=>w.end>w.start);b.set(I.id,{...I,measures:v.get(I.id)??{},waits:k,waitingMs:k.reduce((w,N)=>w+N.end-N.start,0),waitingSince:I.waitingSince===void 0?void 0:Math.max(e,I.waitingSince)})}h.executions=b,h.active=new Set([...h.active].filter(I=>b.has(I)));const _=new Set(a.flatMap(I=>I.subject.type==="session"?[I.subject.id]:I.core?.sessionId?[I.core.sessionId]:[]));for(const I of h.sessions.values())I.executionIds=I.executionIds.filter(k=>b.has(k)),I.executionIds.length===0&&!_.has(I.id)&&h.sessions.delete(I.id);const E=performance.now()-p;return{state:h,events:i,declarations:l,relationships:d,meta:{events:i.length,readMs:Math.round(m*10)/10,deriveMs:Math.round(E*10)/10}}}function tk(t,e,r,n){const s=n?vg(n):void 0,o=t.subjectEvents("execution",e).filter(l=>l.occurredAt<=r),i=s?zn(o,s):o,a=new Set;for(const l of i)l.core?.sessionId&&a.add(`session:${l.core.sessionId}`),l.core?.machineId&&a.add(`machine:${l.core.machineId}`);let c=t.begansFor([...a]).filter(l=>l.occurredAt<=r);s&&(c=zn(c,s));const u=xa(i[0]?.occurredAt??r,r);return hd(u,[...c,...i].sort((l,d)=>l.occurredAt-d.occurredAt||is(l)-is(d))),$y(u,r),u}function Bp(t,e,r,n,s){const o=gg(t,e,r,n,s),i=performance.now();return{world:H0(o.state,o.relationships),state:o.state,declarations:o.declarations,relationships:o.relationships,meta:{...o.meta,serializeMs:Math.round((performance.now()-i)*10)/10}}}function vg(t){const e=Ew(t);return r=>{if(r.subject.type==="machine")return r.subject.id!==t&&yu(r.subject.id)?null:r;const n=r.core?.machineId;if(!n||n===t||!yu(n))return r;const s=r.subject.type==="process"&&e?YA(r.subject.id,e):void 0;return{...r,...s?{subject:{...r.subject,id:s}}:{},core:{...r.core,machineId:t}}}}function zn(t,e){const r=[];for(const n of t){const s=e(n);s&&r.push(s)}return r}function is(t){if(t.kind==="ended")return 5;switch(t.subject.type){case"machine":return 0;case"session":return 1;case"execution":case"process":return t.kind==="began"?2:3;default:return 4}}const rk=[[cd,gw],[_i,$w],[an,Fw],[oo,t0],[ns,g0],[ao,I0]],Ma=new Map(rk);function bg(t,e,r,n,s){const o=gg(t,e,r,n,["machine","session","execution"]);return ag({state:vo(o.state,s),declarations:o.declarations,relationships:o.relationships,capabilities:Ma,from:e,to:r})}function wg(t,e,r,n=Date.now(),s){const o=new Map,i=c=>{const u=`${c.from}:${c.to}`,l=o.get(u);if(l)return l;const d=bg(t,c.from,c.to,r,s);return o.set(u,d),d},a=c=>Ou(c,e,n);return{summary(c){return RA(i(c),a(c))},availability(c){return ko(i(c),a(c))},compare(c,u){return lg(i(c),a(c),i(u),a(u))},breakdown(c,u){return DA(i(c),a(c),u)}}}function Ou(t,e,r){const n=e.eventDays===0?null:r-e.eventDays*864e5,s=n===null?"retained-indefinitely":t.to<n?"outside-retention":t.from<n?"partially-within-retention":"within-retention";return{capabilities:Ma,continuity:{state:"unknown",qualification:"057 does not retain historical source-health continuity for this period"},retention:{state:s,semanticFrom:n,qualification:n===null?"semantic history is configured to be retained indefinitely":s==="within-retention"?"the requested period is inside the configured semantic retention window":s==="partially-within-retention"?"the requested period crosses the configured semantic retention boundary":"the requested period precedes the configured semantic retention window"}}}const nk=3e4;function sk(t,e,r){const n=Ba(t.path);try{const s=r.at??t.now?.()??Date.now(),o=wg(n,t.retention,t.machineId,s,r.projectKey);return ZS(o,e,s,r)}finally{n.close()}}function ok(t,e){return JSON.stringify([t.query,t.scope,t.focus,t.by,e.view,e.timeZone,e.projectKey,e.at,e.period])}function Sg(t){const e=new Map;return{async read(r,n){const s=t.now?.()??Date.now(),o=ok(r,n),i=e.get(o);if(i&&s-i.at<nk)return i.reading;const a=sk(t,r,n);if(e.set(o,{at:s,reading:a}),e.size>32){const c=e.keys().next().value;c!==void 0&&e.delete(c)}return a},close(){e.clear()}}}function ik(t,e){let r=null,n=1;const s=new Map,o=a=>{for(const c of s.values())c.reject(a);s.clear()},i=()=>{const a={o57:"activity-reader",path:e.path,retention:e.retention,machineId:e.machineId},c=new ny(new URL(t),{workerData:a,execArgv:["--disable-warning=ExperimentalWarning"]});return c.unref(),c.on("message",u=>{const l=s.get(u.id);l&&(s.delete(u.id),u.reading?l.resolve(u.reading):l.reject(new Error(u.error??"the reading failed")))}),c.on("error",u=>{r=null,o(u instanceof Error?u:new Error(String(u)))}),c.on("exit",u=>{r===c&&(r=null),s.size>0&&o(new Error(`the reading worker stopped (${u})`))}),c};return{read(a,c){r??=i();const u=n++,l={id:u,request:a,context:c};return new Promise((d,m)=>{s.set(u,{resolve:d,reject:m}),r?.postMessage(l)})},close(){o(new Error("the Core is stopping")),r?.terminate(),r=null}}}function ak(t){const e=Sg(t);Jn?.on("message",r=>{e.read(r.request,r.context).then(n=>Jn?.postMessage({id:r.id,reading:n}),n=>Jn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)}))})}!ry&&Ni?.o57==="activity-reader"&&ak(Ni);const Od={[Di]:go};function Nd(t){return`${t}.core.json`}function Ag(t){const e=Nd(t);if(!ve(e))return null;try{const r=JSON.parse(ad(e,"utf8"));return typeof r.pid!="number"||typeof r.url!="string"?null:r}catch{return null}}function ck(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function uk(t,e=1500){const r=Ag(t);if(!r||r.pid===process.pid||!ck(r.pid))return null;try{const n=await fetch(`${r.url}/api/health`,{signal:AbortSignal.timeout(e)});return n.ok&&(await n.json()).pid===r.pid?r:null}catch{return null}}function lk(t,e){if(t===":memory:")return;const r=Nd(t),n=`${r}.${process.pid}.tmp`;od(n,`${JSON.stringify(e,null,1)}
102
+ `,{mode:384}),id(n,r)}function dk(t,e=process.pid){if(t===":memory:")return;const r=Ag(t);r&&r.pid===e&&ey(Nd(t),{force:!0})}class Td extends Error{constructor(e){super(`057 is already observing ${e.store} at ${e.url} (pid ${e.pid})`),this.record=e}record}const fk=rw(ew);function pk(){return oy()}function hk(t){const e=[];for(const r of t.split(`
103
+ `)){const n=r.trim();if(!n)continue;const s=n.match(/^(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+([\d:.]+)\s+(\d+)\s+(.*)$/);if(!s)continue;const[,o,i,a,c,u,l]=s,d=Date.parse(a);Number.isFinite(d)&&e.push({pid:Number(o),ppid:Number(i),startedAt:d,cpuMs:mk(c),rssBytes:Number(u)*1024,command:l.trim()})}return e}function mk(t){const[e,r]=t.includes("-")?t.split("-"):["0",t],n=r.split(":").map(Number);let s=0;for(const o of n)s=s*60+(Number.isFinite(o)?o:0);return Math.round((s+Number(e)*86400)*1e3)}async function yk(){const{stdout:t}=await fk("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return hk(t)}const _p=5e3;function gk(t,e){const r=pk();let n=new Map,s=null,o=0,i=null,a,c=!1;async function u(){if(c)return[];c=!0;try{const l=await yk(),d=Date.now(),{envelopes:m,next:p}=QA(n,l,{machineId:e,host:r,observedAt:d,intervalMs:_p}),h=m.map(Wt);return t.append(h),n=p,o++,i=d,a=void 0,h}catch(l){return a=l instanceof Error?l.message:String(l),[]}finally{c=!1}}return{sample:u,start(){s||(u(),s=setInterval(()=>{u()},_p),s.unref?.())},stop(){s&&clearInterval(s),s=null},get running(){return s!==null},stats(){return{samples:o,tracked:n.size,lastSampleAt:i,lastError:a}}}}const xt="machine-pulse",vk=t=>`machine-pulse:${t.machine.key.slice(0,24)}`,Mp=(t,e)=>`machine-pulse:${t.machine.key.slice(0,16)}:${t.machine.bootKey.slice(0,16)}:${e.pid}:${e.startTicks}`,fi=t=>`${t.pid}:${t.startTicks}`,Yn=(t,e)=>t===void 0||e===void 0||e<t?void 0:e-t,bk="CPU utilization is inferred from the change in Linux aggregate busy ticks divided by the change in total ticks between two successful snapshots. It describes the whole machine over that interval, not a process or task, and is unavailable across reconnects, counter resets or reboots.",wk=t=>`The process was present in one successful Linux procfs snapshot and absent from the next, ${Math.max(1,Math.round(t))} ms later. Its recorded end is the last instant it was observed present, not an exact exit time. Processes that start and end between snapshots are absent.`;function Sk(t,e,r){const n=vk(e),o={source:{id:xt,instance:e.machine.key.slice(0,24)},observedAt:r.receivedAt,clock:"wall",stratum:"machine"},i=[{...o,occurredAt:0,kind:"began",subject:{type:"machine",id:n},basis:"measured",core:{machineName:e.machine.name,machineKind:"server"},attrs:{"machine-pulse.kernel":e.machine.kernel,"machine-pulse.logicalCpus":e.machine.logicalCpus},seq:"machine"},{...o,occurredAt:r.receivedAt,kind:"observed",subject:{type:"machine",id:n},basis:"measured",attrs:Ak(e),seq:`snapshot:${e.collectorSession}:${e.sequence}`}];let a;const c=t&&t.machine.key===e.machine.key&&t.machine.bootKey===e.machine.bootKey&&t.machine.clockTicks===e.machine.clockTicks&&t.collectorSession===e.collectorSession&&e.sequence>t.sequence&&e.captured.monotonicMs>t.captured.monotonicMs;if(t&&c&&r.allowActivity!==!1){const d=Yn(t.aggregate.cpu.totalTicks,e.aggregate.cpu.totalTicks),m=Yn(t.aggregate.cpu.busyTicks,e.aggregate.cpu.busyTicks),p=e.captured.monotonicMs-t.captured.monotonicMs;if(d!==void 0&&m!==void 0&&d>0&&m<=d){const h=m/d;a={utilization:h,intervalMs:p},i.push({...o,occurredAt:r.receivedAt,kind:"observed",subject:{type:"machine",id:n},basis:"inferred",assumption:bk,core:{measures:{[z.cpuUtilization]:h},measureValidityMs:r.validityMs??6e3},attrs:kk(t,e,p),seq:`activity:${e.collectorSession}:${e.sequence}`})}}const u=new Map((c?t.processes:[]).map(d=>[fi(d),d])),l=new Map(e.processes.map(d=>[fi(d),d]));for(const d of e.processes){const m=fi(d),p=u.get(m),h=Mp(e,d),g=e.machine.bootWallMs+d.startTicks/e.machine.clockTicks*1e3,v=d.cpuTicks/e.machine.clockTicks*1e3,b={ns:"os.process",parts:[n,d.pid],validFrom:g,validTo:e.captured.wallMs};p||i.push({...o,occurredAt:g,kind:"began",subject:{type:"process",id:h},claims:[b],basis:"measured",core:{machineId:n,pid:d.pid,ppid:d.ppid,label:d.command.toUpperCase(),executor:d.command},attrs:{"machine-pulse.pid":d.pid,"machine-pulse.startTicks":d.startTicks}}),(!p||d.cpuTicks!==p.cpuTicks||d.rssBytes!==p.rssBytes||d.readBytes!==p.readBytes||d.writeBytes!==p.writeBytes)&&i.push({...o,occurredAt:r.receivedAt,kind:"observed",subject:{type:"process",id:h},claims:[b],basis:"measured",core:{measures:{[z.cpuMs]:v}},attrs:Ek(d),seq:`snapshot:${e.collectorSession}:${e.sequence}`})}if(t&&c&&r.allowEnds&&t.capabilities.processes==="available"&&e.capabilities.processes==="available"){const d=e.captured.monotonicMs-t.captured.monotonicMs;for(const m of t.processes)l.has(fi(m))||i.push({...o,occurredAt:t.captured.wallMs,kind:"ended",subject:{type:"process",id:Mp(t,m)},basis:"inferred",assumption:wk(d),core:{outcome:"completed",measures:{[z.cpuMs]:m.cpuTicks/t.machine.clockTicks*1e3}},attrs:{"machine-pulse.pid":m.pid}})}return{envelopes:i,activity:a}}function Ak(t){return{"machine-pulse.remoteWallMs":t.captured.wallMs,"machine-pulse.remoteMonotonicMs":t.captured.monotonicMs,"machine-pulse.probe":t.probe,"machine-pulse.memoryTotalBytes":t.aggregate.memory.totalBytes,"machine-pulse.memoryAvailableBytes":t.aggregate.memory.availableBytes,"machine-pulse.cpuTotalTicks":t.aggregate.cpu.totalTicks,"machine-pulse.cpuBusyTicks":t.aggregate.cpu.busyTicks,"machine-pulse.pressure":t.aggregate.pressure,"machine-pulse.rootDisk":t.aggregate.rootDisk,"machine-pulse.network":t.aggregate.network,"machine-pulse.cgroup":t.aggregate.cgroup,"machine-pulse.capabilities":t.capabilities,"machine-pulse.errors":t.errors}}function kk(t,e,r){return{"machine-pulse.intervalMs":r,"machine-pulse.rootDiskReadBytes":Yn(t.aggregate.rootDisk?.readBytes,e.aggregate.rootDisk?.readBytes),"machine-pulse.rootDiskWriteBytes":Yn(t.aggregate.rootDisk?.writeBytes,e.aggregate.rootDisk?.writeBytes),"machine-pulse.networkReceiveBytes":Yn(t.aggregate.network?.receiveBytes,e.aggregate.network?.receiveBytes),"machine-pulse.networkTransmitBytes":Yn(t.aggregate.network?.transmitBytes,e.aggregate.network?.transmitBytes)}}function Ek(t){return{"machine-pulse.pid":t.pid,"machine-pulse.ppid":t.ppid,"machine-pulse.command":t.command,"machine-pulse.rssBytes":t.rssBytes,"machine-pulse.readBytes":t.readBytes,"machine-pulse.writeBytes":t.writeBytes}}const xk=String.raw`import errno
104
+ import hashlib
105
+ import json
106
+ import os
107
+ import platform
108
+ import resource
109
+ import sys
110
+ import time
111
+
112
+ PROTOCOL = "057.machine-pulse/v1"
113
+ session = sys.argv[1]
114
+ sequence = int(sys.argv[2])
115
+ errors = []
116
+ probe_started = time.monotonic_ns()
117
+
118
+ def safe_error(surface, error):
119
+ code = errno.errorcode.get(getattr(error, "errno", 0), "ERROR")
120
+ item = {"surface": surface, "code": code}
121
+ if item not in errors:
122
+ errors.append(item)
123
+
124
+ def read_text(path, surface):
125
+ try:
126
+ with open(path, "r", encoding="utf-8", errors="replace") as handle:
127
+ return handle.read()
128
+ except OSError as error:
129
+ safe_error(surface, error)
130
+ return None
131
+
132
+ def digest(text):
133
+ return hashlib.sha256(text.strip().encode("utf-8")).hexdigest()
134
+
135
+ def key_values(text):
136
+ out = {}
137
+ for line in text.splitlines():
138
+ if ":" not in line:
139
+ continue
140
+ key, value = line.split(":", 1)
141
+ out[key] = value.strip().split()[0]
142
+ return out
143
+
144
+ machine_raw = read_text("/etc/machine-id", "machine.identity")
145
+ boot_raw = read_text("/proc/sys/kernel/random/boot_id", "machine.boot")
146
+ proc_stat = read_text("/proc/stat", "procfs.cpu")
147
+ meminfo_raw = read_text("/proc/meminfo", "procfs.memory")
148
+ if machine_raw is None or boot_raw is None or proc_stat is None or meminfo_raw is None:
149
+ raise SystemExit(2)
150
+
151
+ clock_ticks = int(os.sysconf("SC_CLK_TCK"))
152
+ page_size = int(os.sysconf("SC_PAGE_SIZE"))
153
+ logical_cpus = int(os.cpu_count() or 1)
154
+ wall_ms = time.time_ns() // 1_000_000
155
+ monotonic_ms = time.monotonic_ns() / 1_000_000
156
+
157
+ cpu_line = next(line for line in proc_stat.splitlines() if line.startswith("cpu "))
158
+ cpu_fields = [int(value) for value in cpu_line.split()[1:]]
159
+ # guest and guest_nice are already included in user and nice respectively.
160
+ total_ticks = sum(cpu_fields[:8])
161
+ idle_ticks = cpu_fields[3] + (cpu_fields[4] if len(cpu_fields) > 4 else 0)
162
+ busy_ticks = total_ticks - idle_ticks
163
+ btime_line = next(line for line in proc_stat.splitlines() if line.startswith("btime "))
164
+ boot_wall_ms = int(btime_line.split()[1]) * 1000
165
+
166
+ meminfo = key_values(meminfo_raw)
167
+ memory = {
168
+ "totalBytes": int(meminfo["MemTotal"]) * 1024,
169
+ "availableBytes": int(meminfo["MemAvailable"]) * 1024,
170
+ }
171
+
172
+ capabilities = {
173
+ "procfs": "available",
174
+ "processes": "available",
175
+ "processIo": "unavailable",
176
+ "pressure": "unavailable",
177
+ "cgroupV2": "unavailable",
178
+ "rootDisk": "unavailable",
179
+ "network": "unavailable",
180
+ }
181
+ aggregate = {"cpu": {"totalTicks": total_ticks, "busyTicks": busy_ticks}, "memory": memory}
182
+
183
+ def pressure_total(path, kind):
184
+ text = read_text(path, "procfs.pressure")
185
+ if text is None:
186
+ return None
187
+ for line in text.splitlines():
188
+ fields = line.split()
189
+ if fields and fields[0] == kind:
190
+ for field in fields[1:]:
191
+ if field.startswith("total="):
192
+ return int(field.split("=", 1)[1])
193
+ return None
194
+
195
+ pressure_values = {
196
+ "cpuSomeUs": pressure_total("/proc/pressure/cpu", "some"),
197
+ "memorySomeUs": pressure_total("/proc/pressure/memory", "some"),
198
+ "memoryFullUs": pressure_total("/proc/pressure/memory", "full"),
199
+ "ioSomeUs": pressure_total("/proc/pressure/io", "some"),
200
+ "ioFullUs": pressure_total("/proc/pressure/io", "full"),
201
+ }
202
+ if all(value is not None for value in pressure_values.values()):
203
+ aggregate["pressure"] = pressure_values
204
+ capabilities["pressure"] = "available"
205
+
206
+ try:
207
+ root_device = os.stat("/").st_dev
208
+ root_major = os.major(root_device)
209
+ root_minor = os.minor(root_device)
210
+ diskstats = read_text("/proc/diskstats", "procfs.root-disk")
211
+ if diskstats is not None:
212
+ for line in diskstats.splitlines():
213
+ fields = line.split()
214
+ if len(fields) >= 14 and int(fields[0]) == root_major and int(fields[1]) == root_minor:
215
+ aggregate["rootDisk"] = {
216
+ "readBytes": int(fields[5]) * 512,
217
+ "writeBytes": int(fields[9]) * 512,
218
+ }
219
+ capabilities["rootDisk"] = "available"
220
+ break
221
+ except OSError as error:
222
+ safe_error("procfs.root-disk", error)
223
+
224
+ network_raw = read_text("/proc/net/dev", "procfs.network")
225
+ if network_raw is not None:
226
+ receive = 0
227
+ transmit = 0
228
+ for line in network_raw.splitlines()[2:]:
229
+ if ":" not in line:
230
+ continue
231
+ name, values = line.split(":", 1)
232
+ if name.strip() == "lo":
233
+ continue
234
+ fields = values.split()
235
+ if len(fields) >= 16:
236
+ receive += int(fields[0])
237
+ transmit += int(fields[8])
238
+ aggregate["network"] = {"receiveBytes": receive, "transmitBytes": transmit}
239
+ capabilities["network"] = "available"
240
+
241
+ def cgroup_value(path, key=None):
242
+ text = read_text(path, "cgroup.v2")
243
+ if text is None:
244
+ return None
245
+ if key is None:
246
+ return int(text.strip())
247
+ for line in text.splitlines():
248
+ fields = line.split()
249
+ if fields and fields[0] == key:
250
+ return int(fields[1])
251
+ return None
252
+
253
+ if os.path.exists("/sys/fs/cgroup/cgroup.controllers"):
254
+ cpu_usec = cgroup_value("/sys/fs/cgroup/cpu.stat", "usage_usec")
255
+ memory_bytes = cgroup_value("/sys/fs/cgroup/memory.current")
256
+ io_raw = read_text("/sys/fs/cgroup/io.stat", "cgroup.v2")
257
+ if cpu_usec is not None or memory_bytes is not None or io_raw is not None:
258
+ capabilities["cgroupV2"] = "partial"
259
+ cgroup = {}
260
+ if cpu_usec is not None:
261
+ cgroup["cpuUsec"] = cpu_usec
262
+ if memory_bytes is not None:
263
+ cgroup["memoryBytes"] = memory_bytes
264
+ if io_raw is not None:
265
+ read_bytes = 0
266
+ write_bytes = 0
267
+ for line in io_raw.splitlines():
268
+ for field in line.split()[1:]:
269
+ if field.startswith("rbytes="):
270
+ read_bytes += int(field.split("=", 1)[1])
271
+ elif field.startswith("wbytes="):
272
+ write_bytes += int(field.split("=", 1)[1])
273
+ cgroup["readBytes"] = read_bytes
274
+ cgroup["writeBytes"] = write_bytes
275
+ if cgroup:
276
+ aggregate["cgroup"] = cgroup
277
+ if len(cgroup) == 4:
278
+ capabilities["cgroupV2"] = "available"
279
+
280
+ processes = []
281
+ process_failures = 0
282
+ io_success = 0
283
+ io_failures = 0
284
+ for entry in os.listdir("/proc"):
285
+ if not entry.isdigit():
286
+ continue
287
+ pid = int(entry)
288
+ try:
289
+ stat_raw = read_text("/proc/" + entry + "/stat", "procfs.process")
290
+ if stat_raw is None:
291
+ process_failures += 1
292
+ continue
293
+ open_paren = stat_raw.find("(")
294
+ close_paren = stat_raw.rfind(")")
295
+ if open_paren < 0 or close_paren <= open_paren:
296
+ process_failures += 1
297
+ continue
298
+ command = stat_raw[open_paren + 1:close_paren]
299
+ fields = stat_raw[close_paren + 2:].split()
300
+ sample = {
301
+ "pid": pid,
302
+ "ppid": int(fields[1]),
303
+ "startTicks": int(fields[19]),
304
+ "cpuTicks": int(fields[11]) + int(fields[12]),
305
+ "rssBytes": max(0, int(fields[21])) * page_size,
306
+ "command": command,
307
+ }
308
+ io_raw = read_text("/proc/" + entry + "/io", "procfs.process-io")
309
+ if io_raw is not None:
310
+ io = key_values(io_raw)
311
+ if "read_bytes" in io and "write_bytes" in io:
312
+ sample["readBytes"] = int(io["read_bytes"])
313
+ sample["writeBytes"] = int(io["write_bytes"])
314
+ io_success += 1
315
+ else:
316
+ io_failures += 1
317
+ processes.append(sample)
318
+ except (OSError, ValueError, IndexError) as error:
319
+ process_failures += 1
320
+ if isinstance(error, OSError):
321
+ safe_error("procfs.process", error)
322
+
323
+ if process_failures:
324
+ capabilities["processes"] = "partial" if processes else "failed"
325
+ if io_success:
326
+ capabilities["processIo"] = "partial" if io_failures else "available"
327
+
328
+ snapshot = {
329
+ "protocol": PROTOCOL,
330
+ "type": "snapshot",
331
+ "collectorSession": session,
332
+ "sequence": sequence,
333
+ "captured": {"wallMs": wall_ms, "monotonicMs": monotonic_ms},
334
+ "machine": {
335
+ "key": digest(machine_raw),
336
+ "bootKey": digest(boot_raw),
337
+ "name": platform.node(),
338
+ "kernel": platform.release(),
339
+ "logicalCpus": logical_cpus,
340
+ "clockTicks": clock_ticks,
341
+ "pageSize": page_size,
342
+ "bootWallMs": boot_wall_ms,
343
+ },
344
+ "capabilities": capabilities,
345
+ "aggregate": aggregate,
346
+ "processes": processes,
347
+ "errors": errors[:128],
348
+ }
349
+ usage = resource.getrusage(resource.RUSAGE_SELF)
350
+ snapshot["probe"] = {
351
+ "elapsedMs": (time.monotonic_ns() - probe_started) / 1_000_000,
352
+ "userCpuMs": usage.ru_utime * 1000,
353
+ "systemCpuMs": usage.ru_stime * 1000,
354
+ "maxRssBytes": int(usage.ru_maxrss) * 1024,
355
+ }
356
+ sys.stdout.write(json.dumps(snapshot, separators=(",", ":")) + "\n")
357
+ `,Rp="057.machine-pulse/v1",Ik=new Set(["available","partial","unavailable","failed"]),Et=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ls(t,e){if(typeof t!="number"||!Number.isFinite(t)||t<0)throw new Error(`MACHINE PULSE protocol: ${e} must be a nonnegative finite number`);return t}function Ee(t,e,r=0){const n=Ls(t,e);if(!Number.isSafeInteger(n)||n<r)throw new Error(`MACHINE PULSE protocol: ${e} must be an integer >= ${r}`);return n}function rn(t,e,r){if(typeof t!="string"||t.length===0||t.length>r)throw new Error(`MACHINE PULSE protocol: ${e} must be 1..${r} characters`);return t}function jp(t,e){const r=rn(t,e,64);if(!/^[a-f0-9]{64}$/.test(r))throw new Error(`MACHINE PULSE protocol: ${e} must be a SHA-256 digest`);return r}function Zr(t,e){if(typeof t!="string"||!Ik.has(t))throw new Error(`MACHINE PULSE protocol: ${e} is not a capability state`);return t}function Un(t,e){return t===void 0?void 0:Ee(t,e)}function Ck(t){if(Buffer.byteLength(t)>8*1024*1024)throw new Error("MACHINE PULSE protocol: snapshot exceeds 8 MiB");let e;try{e=JSON.parse(t)}catch{throw new Error("MACHINE PULSE protocol: snapshot is not JSON")}if(!Et(e))throw new Error("MACHINE PULSE protocol: snapshot must be an object");if(e.protocol!==Rp)throw new Error("MACHINE PULSE protocol: unsupported version");if(e.type!=="snapshot")throw new Error("MACHINE PULSE protocol: unsupported record type");if(!Et(e.captured)||!Et(e.probe)||!Et(e.machine)||!Et(e.capabilities))throw new Error("MACHINE PULSE protocol: snapshot header is incomplete");if(!Et(e.aggregate)||!Et(e.aggregate.cpu)||!Et(e.aggregate.memory))throw new Error("MACHINE PULSE protocol: aggregate counters are incomplete");if(!Array.isArray(e.processes)||e.processes.length>1e5)throw new Error("MACHINE PULSE protocol: processes must be an array of at most 100000 rows");if(!Array.isArray(e.errors)||e.errors.length>128)throw new Error("MACHINE PULSE protocol: errors must be an array of at most 128 rows");const r=e.processes.map((a,c)=>{if(!Et(a))throw new Error(`MACHINE PULSE protocol: processes[${c}] is invalid`);const u=rn(a.command,`processes[${c}].command`,256);if(new RegExp("\\p{Cc}","u").test(u))throw new Error(`MACHINE PULSE protocol: processes[${c}].command has control characters`);return{pid:Ee(a.pid,`processes[${c}].pid`,1),ppid:Ee(a.ppid,`processes[${c}].ppid`),startTicks:Ee(a.startTicks,`processes[${c}].startTicks`),cpuTicks:Ee(a.cpuTicks,`processes[${c}].cpuTicks`),rssBytes:Ee(a.rssBytes,`processes[${c}].rssBytes`),readBytes:Un(a.readBytes,`processes[${c}].readBytes`),writeBytes:Un(a.writeBytes,`processes[${c}].writeBytes`),command:u}});if(new Set(r.map(a=>a.pid)).size!==r.length)throw new Error("MACHINE PULSE protocol: duplicate process PID");const n={procfs:Zr(e.capabilities.procfs,"capabilities.procfs"),processes:Zr(e.capabilities.processes,"capabilities.processes"),processIo:Zr(e.capabilities.processIo,"capabilities.processIo"),pressure:Zr(e.capabilities.pressure,"capabilities.pressure"),cgroupV2:Zr(e.capabilities.cgroupV2,"capabilities.cgroupV2"),rootDisk:Zr(e.capabilities.rootDisk,"capabilities.rootDisk"),network:Zr(e.capabilities.network,"capabilities.network")},s={cpu:{totalTicks:Ee(e.aggregate.cpu.totalTicks,"aggregate.cpu.totalTicks"),busyTicks:Ee(e.aggregate.cpu.busyTicks,"aggregate.cpu.busyTicks")},memory:{totalBytes:Ee(e.aggregate.memory.totalBytes,"aggregate.memory.totalBytes"),availableBytes:Ee(e.aggregate.memory.availableBytes,"aggregate.memory.availableBytes")}},o=e.aggregate.pressure;if(s.cpu.busyTicks>s.cpu.totalTicks||s.memory.availableBytes>s.memory.totalBytes)throw new Error("MACHINE PULSE protocol: inconsistent aggregate counters");if(o!==void 0){if(!Et(o))throw new Error("MACHINE PULSE protocol: aggregate.pressure is invalid");s.pressure={cpuSomeUs:Ee(o.cpuSomeUs,"aggregate.pressure.cpuSomeUs"),memorySomeUs:Ee(o.memorySomeUs,"aggregate.pressure.memorySomeUs"),memoryFullUs:Ee(o.memoryFullUs,"aggregate.pressure.memoryFullUs"),ioSomeUs:Ee(o.ioSomeUs,"aggregate.pressure.ioSomeUs"),ioFullUs:Ee(o.ioFullUs,"aggregate.pressure.ioFullUs")}}for(const a of["rootDisk","network","cgroup"]){const c=e.aggregate[a];if(c!==void 0){if(!Et(c))throw new Error(`MACHINE PULSE protocol: aggregate.${a} is invalid`);a==="rootDisk"?s.rootDisk={readBytes:Ee(c.readBytes,"aggregate.rootDisk.readBytes"),writeBytes:Ee(c.writeBytes,"aggregate.rootDisk.writeBytes")}:a==="network"?s.network={receiveBytes:Ee(c.receiveBytes,"aggregate.network.receiveBytes"),transmitBytes:Ee(c.transmitBytes,"aggregate.network.transmitBytes")}:s.cgroup={cpuUsec:Un(c.cpuUsec,"aggregate.cgroup.cpuUsec"),memoryBytes:Un(c.memoryBytes,"aggregate.cgroup.memoryBytes"),readBytes:Un(c.readBytes,"aggregate.cgroup.readBytes"),writeBytes:Un(c.writeBytes,"aggregate.cgroup.writeBytes")}}}const i=e.errors.map((a,c)=>{if(!Et(a))throw new Error(`MACHINE PULSE protocol: errors[${c}] is invalid`);const u=rn(a.surface,`errors[${c}].surface`,64),l=rn(a.code,`errors[${c}].code`,64);if(!/^[A-Za-z0-9_.-]+$/.test(u)||!/^[A-Z0-9_]+$/.test(l))throw new Error(`MACHINE PULSE protocol: errors[${c}] is not sanitized`);return{surface:u,code:l}});return{protocol:Rp,type:"snapshot",collectorSession:rn(e.collectorSession,"collectorSession",64),sequence:Ee(e.sequence,"sequence"),captured:{wallMs:Ee(e.captured.wallMs,"captured.wallMs"),monotonicMs:Ls(e.captured.monotonicMs,"captured.monotonicMs")},probe:{elapsedMs:Ls(e.probe.elapsedMs,"probe.elapsedMs"),userCpuMs:Ls(e.probe.userCpuMs,"probe.userCpuMs"),systemCpuMs:Ls(e.probe.systemCpuMs,"probe.systemCpuMs"),maxRssBytes:Ee(e.probe.maxRssBytes,"probe.maxRssBytes")},machine:{key:jp(e.machine.key,"machine.key"),bootKey:jp(e.machine.bootKey,"machine.bootKey"),name:rn(e.machine.name,"machine.name",255),kernel:rn(e.machine.kernel,"machine.kernel",255),logicalCpus:Ee(e.machine.logicalCpus,"machine.logicalCpus",1),clockTicks:Ee(e.machine.clockTicks,"machine.clockTicks",1),pageSize:Ee(e.machine.pageSize,"machine.pageSize",1),bootWallMs:Ee(e.machine.bootWallMs,"machine.bootWallMs")},capabilities:n,aggregate:s,processes:r,errors:i}}const Dp=8e3,Ok=8*1024*1024,Nk=(t,e,r,n)=>new Promise((s,o)=>{if(!/^[A-Za-z0-9_-]{1,64}$/.test(e)||!Number.isSafeInteger(r)||r<0){o(new Error("MACHINE PULSE transport failed: invalid request identity"));return}if(n?.aborted){o(new Error("MACHINE PULSE transport failed: cancelled"));return}const i=tw("/usr/bin/ssh",["-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ControlMaster=no","-o","ControlPath=none","-o","ControlPersist=no","-o",`ConnectTimeout=${Math.ceil(Dp/1e3)}`,"--",t,"python3","-",e,String(r)],{stdio:["pipe","pipe","pipe"]});let a="",c="",u=!1;const l=()=>{i.kill("SIGKILL")};n?.addEventListener("abort",l,{once:!0});const d=setTimeout(()=>i.kill("SIGKILL"),Dp);d.unref?.(),i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",m=>{if(Buffer.byteLength(a)+Buffer.byteLength(m)>Ok){u=!0,i.kill("SIGKILL");return}a+=m}),i.stderr.on("data",m=>{c.length<1&&(c=m.slice(0,1))}),i.on("error",m=>{clearTimeout(d),o(new Error(`MACHINE PULSE transport failed: ${m.code??"ERROR"}`))}),i.on("close",(m,p)=>{clearTimeout(d),u?o(new Error("MACHINE PULSE transport failed: snapshot exceeded 8 MiB")):n?.aborted?o(new Error("MACHINE PULSE transport failed: cancelled")):p?o(new Error("MACHINE PULSE transport failed: timeout")):m!==0?o(new Error(`MACHINE PULSE transport failed: ssh exited ${m??"unknown"}${c?" with stderr":""}`)):s(a.trim())}),i.stdin.on("error",()=>{}),i.once("close",()=>n?.removeEventListener("abort",l)),i.stdin.end(xk)});async function Tk(t,e,r,n=Nk,s){const o=await n(t,e,r,s),i=Ck(o);if(i.collectorSession!==e||i.sequence!==r)throw new Error("MACHINE PULSE protocol: response does not match the requested sample");return i}const $k=2e3,Hi=2147483647;function Bk(t=process.env){const e=t.O57_MACHINE_PULSE_SSH?.trim();if(!e)return;const r=t.O57_MACHINE_PULSE_INTERVAL_MS?.trim(),n=r?Number(r):void 0;if(n!==void 0&&(!Number.isFinite(n)||n<250||n>Hi))throw new Error(`O57_MACHINE_PULSE_INTERVAL_MS must be at least 250 and at most ${Hi}`);return{target:e,intervalMs:n}}function _k(t,e){const r=e.intervalMs??$k;if(!Number.isFinite(r)||r<250||r>Hi)throw new Error(`MACHINE PULSE interval must be at least 250 and at most ${Hi} ms`);if(!/^[^\s\p{Cc}]{1,255}$/u.test(e.target))throw new Error("MACHINE PULSE SSH target is invalid");const n=e.collectorSession??pn(16).toString("hex");let s=0,o,i=null,a=!1,c=!1,u,l=!1,d=0,m=0,p=0,h=0,g=0,v=null,b=null,_=null,E,I;async function k(){if(a||c)return[];a=!0;const w=new AbortController;u=w;const N=performance.now();try{const $=await Tk(e.target,n,s++,e.runner,w.signal);if(w.signal.aborted)return[];const P=Date.now();if(o&&$.machine.key!==o.machine.key)throw new Error("MACHINE PULSE protocol: SSH target changed machine identity");const C=o?.machine.bootKey===$.machine.bootKey;if(C&&o&&$.captured.monotonicMs<=o.captured.monotonicMs)throw new Error("MACHINE PULSE protocol: remote monotonic clock did not advance");const T=o!==void 0&&$.captured.monotonicMs-o.captured.monotonicMs>r*3,H=Sk(o,$,{receivedAt:P,allowEnds:!l&&!T&&C,allowActivity:!l&&!T,validityMs:r*3}).envelopes.map(Wt),U=t.append(H);return m+=U.inserted,p+=U.duplicate,(l||T||o&&!C)&&h++,l=!1,o=$,d++,g=$.processes.length,v=P,b=performance.now()-N,_=Buffer.byteLength(JSON.stringify($)),E=$.capabilities,I=void 0,H}catch($){return w.signal.aborted?[]:(l=!0,b=performance.now()-N,I=$ instanceof Error?$.message:String($),[])}finally{a=!1,u===w&&(u=void 0)}}return{sample:k,start(){i||(c=!1,k(),i=setInterval(()=>{k()},r),i.unref?.())},stop(){i&&clearInterval(i),i=null,c=!0,u?.abort(),l=!0},get running(){return i!==null},stats(){return{samples:d,inserted:m,duplicates:p,gaps:h,tracked:g,lastSampleAt:v,lastDurationMs:b,lastBytes:_,capabilities:E,lastError:I}}}}const kg={info:t=>console.log(t),warn:t=>console.warn(t),error:t=>console.error(t)},Mk=36e5,Rk=15e3,jk=3;function Eg(t={}){const e=t.log??kg,r=t.path??Na(),n=t.retention??ng(),s=AA(r),o=s.stats();e.info(o.events>0?`[057] store ${r}: opened with ${o.events} events`:`[057] store ${r}: NEW EMPTY STORE — if history existed before, it was lost, not carried`);const i=rg();i&&e.warn(`[057] a store from a previous layout exists at ${i} and is NOT in use. Run 057 with O57_STORE=${i} to keep using it, or move it to ${r}.`);const a=Gr();s.append([Wt({source:{id:"host",instance:a.id},occurredAt:0,observedAt:Date.now(),clock:"wall",kind:"began",stratum:"machine",subject:{type:"machine",id:a.id},basis:"measured",core:{machineName:a.name,machineKind:a.kind},seq:"host"})]);const c=gk(s,a.id),u=t.machinePulse?_k(s,t.machinePulse):void 0,l=new Map;function d(E){for(const I of E){const k=l.get(I.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};I.ok?(k.consecutiveFailures=0,k.failing=!1,k.failingSince=void 0,k.lastSuccessAt=Date.now()):(k.consecutiveFailures===0&&(k.failingSince=Date.now()),k.consecutiveFailures++,k.totalFailures++,k.lastFailureAt=Date.now(),k.lastError=I.error,k.consecutiveFailures>=jk&&!k.failing&&(k.failing=!0,e.warn(`[057] source ${I.id} has failed ${k.consecutiveFailures} collection rounds in a row: ${I.error??"unknown error"}`))),l.set(I.id,k)}}const m=Pp(r);let p=null;function h(E){return p||(p=E,e.error(`[057] ${E.message} — ${E.remedy}`),c.stop(),u?.stop()),p}function g(){if(p)return p;if(r===":memory:")return null;if(!ve(r))return h({kind:"unlinked",message:`the store at ${r} no longer exists on disk; captured events are going to an orphaned file and will be lost`,remedy:"Stop 057 and start it again. It will open a new store at the same path.",since:Date.now()});const E=Pp(r);return m!==null&&E!==null&&E!==m?h({kind:"replaced",message:`the store at ${r} was replaced by a different file while 057 was running; captured events are going to the old one`,remedy:"Stop 057 and start it again so it opens the file that is actually there.",since:Date.now()}):null}t.observe!==!1&&(c.start(),u?.start());const v=s.sweep(n);v.processEvents+v.otherEvents>0&&e.info(`[057] retention: removed ${v.processEvents} process and ${v.otherEvents} semantic events (${$a(n)})`);const b=setInterval(()=>{if(!p)try{s.sweep(n),xu(r)}catch(E){e.warn(`[057] retention sweep failed: ${String(E)}`)}},Mk);b.unref?.();const _=setInterval(()=>{g()},Rk);return _.unref?.(),{store:s,machine:a,os:c,machinePulse:u,path:r,retention:n,fault:()=>p,sweep:E=>s.sweep(n,E),checkStore:g,recordCollection:d,collectionHealth:()=>Object.fromEntries(l),stop(){clearInterval(b),clearInterval(_),c.stop(),u?.stop(),s.close()}}}function Pp(t){try{return ka(t).ino}catch{return null}}function xg(t,e){const r=new Map;for(const s of e)s.kind==="began"&&s.subject.type==="execution"&&r.set(s.subject.id,s.source.id);const n=[];for(const s of t.executions.keys()){const o=r.get(s),i=o?Ma.get(o)?.waits:void 0;(i==="supported"||i==="partial")&&n.push(s)}return n}function Dk(t,e){return{reported:xg(t,e).length,runs:t.executions.size}}function Ig(t,e,r){let n={from:r.from,to:r.to},s=r.label,o=Bp(t,n.from,n.to,e,r.subjectTypes);if(r.widenFrom!==void 0&&o.world.executions.length===0&&o.world.sessions.length===0){const a=Bp(t,r.widenFrom,r.to,e,r.subjectTypes);(a.world.executions.length>0||a.world.sessions.length>0)&&(n={from:r.widenFrom,to:r.to},s=r.widenedLabel??s,o=a)}let i;if(r.comparison){const{projectKey:a,scope:c,retention:u,evaluatedAt:l}=r.comparison,d=vo(o.state,a),m=ag({state:d,declarations:o.declarations,relationships:o.relationships,capabilities:Ma,...n}),p=r.comparison.basis==="calendar"?Fy(n,c==="today"?1:7):xd(n),h=bg(t,p.from,p.to,e,a),g=lg(m,Ou(n,u,l),h,Ou(p,u,l));i=Wy({query:"compare",scope:c},{comparison:g},{projectKey:a,period:n})}return{...n,label:s,comparison:i,world:o.world,meta:o.meta,waits:Dk(o.state,o.declarations),executionStarts:Object.fromEntries(o.declarations.filter(a=>a.subject.type==="execution"&&a.kind==="began").map(a=>[a.subject.id,{at:a.occurredAt,basis:a.basis,assumption:a.assumption}])),waitReportedIds:xg(o.state,o.declarations)}}function Lp(t,e){return{async read(r,n){if(n?.aborted)throw new Error("analytical read cancelled");return Ig(t,e,r)},close(){}}}function Up(t,e){let r=null,n=1,s=null;const o=new Map,i=u=>{for(const l of o.values())l.detach(),l.reject(u);o.clear(),s=null},a=()=>{const u={o57:"landscape-reader",...e},l=new ny(new URL(t),{workerData:u,execArgv:["--disable-warning=ExperimentalWarning"]});return l.unref(),l.on("message",d=>{if(r!==l)return;const m=o.get(d.id);o.delete(d.id),s===d.id&&(s=null),m&&(m.detach(),d.snapshot?m.resolve(d.snapshot):m.reject(new Error(d.error??"the landscape read failed"))),c()}),l.on("error",d=>{r===l&&(r=null,i(d instanceof Error?d:new Error(String(d))))}),l.on("exit",d=>{r===l&&(r=null,i(new Error(`the landscape worker stopped (${d})`)))}),l},c=()=>{if(s!==null)return;const u=o.entries().next().value;if(!u)return;const[l,d]=u;r??=a(),s=l,r.postMessage({id:l,request:d.request})};return{read(u,l){if(l?.aborted)return Promise.reject(new Error("analytical read cancelled"));if(o.size>=32)return Promise.reject(new Error("Too many analytical reads; retry the selected window."));const d=n++;return new Promise((p,h)=>{const g=()=>{o.delete(d),l?.removeEventListener("abort",g),h(new Error("analytical read cancelled"))};o.set(d,{request:u,resolve:p,reject:h,detach:()=>l?.removeEventListener("abort",g)}),l?.addEventListener("abort",g,{once:!0}),c()})},close(){i(new Error("the Core is stopping")),r?.terminate(),r=null}}}function Pk(t){const e=Ba(t.path);Jn?.on("message",r=>{try{Jn?.postMessage({id:r.id,snapshot:Ig(e,t.machineId,r.request)})}catch(n){Jn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)})}})}!ry&&Ni?.o57==="landscape-reader"&&Pk(Ni);function Lk(t,e,r,n=()=>Date.now()){const s=new Map;let o=!1;return{async read(i){if(o)throw new Error("the Core is stopping");const a=JSON.stringify([i.from,i.label,i.widenFrom!==void 0,i.subjectTypes]);let c=s.get(a);if(!c){if(s.size>=4){const b=s.keys().next().value;b!==void 0&&s.delete(b)}c={},s.set(a,c)}const u=c;if(!u.pending){const b=t.read(i);u.pending=b,b.then(_=>{o||(u.snapshot=_,u.failure=void 0)},_=>{u.failure=_}).finally(()=>{u.pending=void 0})}const l=u.pending;await Promise.resolve();const d=u.snapshot&&i.to>=u.snapshot.to&&i.to-u.snapshot.to<=6e4&&!u.failure?u.snapshot:await l,m=n(),p=xa(d.from,m);for(const b of d.world.machines)p.machines.set(b.id,{...b});const h=e.query(Math.min(d.to,m),m,["machine"]).filter(b=>b.subject.id===r||!yu(b.subject.id)),g=[...new Set(h.filter(b=>!p.machines.has(b.subject.id)).map(b=>`machine:${b.subject.id}`))],v=e.begansFor(g).filter(b=>b.occurredAt<=m);return hd(p,[...v,...h]),{...d,world:{...d.world,now:m,machines:[...p.machines.values()]}}},close(){o=!0,s.clear(),t.close()}}}const Nu=[{id:cd,collect:(t,e)=>Tw(t,e)},{id:_i,collect:(t,e)=>Vw(t,e)},{id:an,collect:(t,e)=>e0(t,e)},{id:oo,collect:(t,e)=>y0(t,e)},{id:ns,collect:(t,e)=>x0(t,e)},{id:ao,collect:(t,e)=>D0(t,e)}],Hp=[...Nu.map(t=>t.id),nn];function Vp(t){return t.machinePulse?[...Hp,xt]:Hp}const Fp=10*365*24*36e5,pi=2e5,Uk=24*36e5;function Wp(t){const e=new AbortController;return t.once("close",()=>{t.writableEnded||e.abort()}),e.signal}const Kp=72*36e5;function Gp(t){const e=new Date(t);return e.setHours(0,0,0,0),{from:e.getTime(),to:t}}function Jc(t){const e=t.collectionHealth(),r=t.machinePulse?.stats(),n=Object.entries(e).filter(([u,l])=>l.failing&&u!==xt),s=n.map(([u])=>u);r?.lastError&&!s.includes(xt)&&s.push(xt);const o=t.store.health(),i=t.os.stats(),a=t.fault();let c=null;for(const u of Object.values(e))u.lastSuccessAt&&(c===null||u.lastSuccessAt>c)&&(c=u.lastSuccessAt);return{ok:s.length===0&&o.ok&&!a&&!i.lastError&&!r?.lastError,fault:a??void 0,failingSources:s,errors:{...Object.fromEntries(n.map(([u,l])=>[u,l.lastError??"failing"])),...r?.lastError?{[xt]:r.lastError}:{}},failing:Object.fromEntries(n.map(([u,l])=>[u,{since:l.failingSince??null,rounds:l.consecutiveFailures}])),store:{ok:o.ok,remedy:o.remedy},os:{running:t.os.running,lastSampleAt:i.lastSampleAt,lastError:i.lastError},machinePulse:t.machinePulse?{running:t.machinePulse.running,lastSampleAt:r?.lastSampleAt??null,lastError:r?.lastError}:void 0,lastCollectionAt:c,sources:{total:Vp(t).length,reported:Vp(t).filter(u=>e[u]!==void 0).length}}}function Hk(t,e,r){const n=e.startsWith("/api/");if(r){const a=(t.headers.host??"").toLowerCase(),c=a.startsWith("[")?a.slice(0,a.indexOf("]")+1):a.split(":")[0];if(!r.includes(c))return`refusing a request for host "${a}"; 057 answers only on ${r.join(", ")}`}const s=t.headers.origin;if(typeof s=="string"&&s!=="null"){const a=(t.headers.host??"").toLowerCase();let c="";try{c=new URL(s).host.toLowerCase()}catch{return"refusing a request with an unparseable Origin"}if(c!==a)return`refusing a cross-origin request from ${s}`}const o=t.headers["sec-fetch-site"],i=String(t.headers["sec-fetch-dest"]??"");if(Fk.has(i))return`refusing to be embedded as ${i}`;if(typeof o=="string"&&o!==""){if(o!=="same-origin"&&o!=="none")return`refusing a ${o} request`;if(o==="none"&&n)return"refusing a directly-navigated API request"}else if(n&&e==="/api/collect"&&!t.headers[Vk])return"refusing a state-changing request that carries no fetch metadata";return null}const Vk="x-057-client",Fk=new Set(["iframe","frame","embed","object","fencedframe"]);function $d(t){t.setHeader("x-frame-options","DENY"),t.setHeader("content-security-policy","frame-ancestors 'none'")}function Wk(t,e){const r=(o,i)=>{const a=t.get(o);if(a===null||a==="")return i;const c=Number(a);return Number.isSafeInteger(c)?c:null},n=r("from",e-864e5),s=r("to",e);return n===null||s===null?{error:"from and to must be integer epoch millis"}:s<n?{error:"to must not precede from"}:s>e+Uk?{error:"to is too far in the future"}:s-n>Fp?{error:`window must not exceed ${Fp} ms`}:{from:n,to:s}}function be(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),$d(t),t.end(JSON.stringify(r))}function Kk(t){const e=t.problems.filter(r=>r.path.includes("/sessions/")).length;return{identity:t.identityAvailable?e===0?"available":t.registryEntries>0?"partial":"failed":"unavailable","stored-semantics":t.storedAvailable?t.transcriptsFailed===0?"available":t.transcriptsRead>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function Zc(t){return{"stored-semantics":t.storedAvailable?t.failed===0?"available":t.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function Gk(t){return t.error?"failed":t.available?"observing":t.present?"installed-no-data":"not-installed"}function qk(t){const e=t.home??t.globalStorage;if(typeof e=="string")return e;const r=t.roots;return Array.isArray(r)?r.join(", "):void 0}function Qr(t){return{available:t.available,present:t.present??!1,presence:Gk(t),origin:qk(t),error:t.error}}function zk(t){const{runtime:e,log:r}=t,n=t.activity??Sg({path:e.path,retention:e.retention,machineId:e.machine.id}),s=t.landscape??Lp(e.store,e.machine.id),o=Lk(s,e.store,e.machine.id),i=t.analytics??Lp(e.store,e.machine.id);let a=null;const c=new Map,u=new Map,l=new Map;async function d(p,h,g,v,b,_="previous"){const E=b??Eu(p,h),I=JSON.stringify([p,b??(p==="today"?E.from:null),g??null,g!==void 0,_]),k=c.get(I);if(k&&h>=k.asOf&&h-k.asOf<(p==="today"?5e3:6e4)&&(p!=="today"||k.period.from===E.from))return k;const w=l.get(I);if(w&&!w.controller.signal.aborted)return $f(w,v);const N=sw(async P=>{const C=b?"SELECTED PERIOD":p==="today"?"TODAY":"LAST 7 DAYS",T=await i.read({...E,label:`ANALYTICS · ${C}`,subjectTypes:["machine","session","execution"],comparison:g===void 0?void 0:{scope:p,projectKey:g??void 0,retention:e.retention,evaluatedAt:h,basis:_}},P);if(P.aborted)throw new Error("analytical read cancelled");const R=Dc(T.world),H={period:{scope:p,label:C,...E,fixed:b!==void 0},asOf:h,world:R,landscape:Lc(R),waits:T.waits,waitReportedIds:T.waitReportedIds,executionStarts:T.executionStarts,comparison:T.comparison};if(c.set(I,H),u.set(JSON.stringify([p,E.from,E.to,h]),H),u.size>16){const U=u.keys().next().value;U!==void 0&&u.delete(U)}if(c.size>16){const U=c.keys().next().value;U!==void 0&&c.delete(U)}return H});l.set(I,N);const $=()=>{l.get(I)===N&&l.delete(I)};return N.promise.then($,$),$f(N,v)}async function m(p){if(!a||p-a.at>6e4){const h=Gp(p),g=await o.read({...h,label:"TODAY",widenFrom:p-Kp,widenedLabel:"LAST 72H"}),v=Dc(g.world);a={at:p,label:g.label,world:v,landscape:Lc(v),waits:g.waits}}return a}return async function(h,g){const v=h.url??"";if(!v.startsWith("/api/"))return!1;const b=new URL(v,"http://localhost"),_=Hk(h,b.pathname,t.allowedHosts);if(_)return r.warn(`[057] ${_}`),be(g,403,{error:_}),!0;const E=e.store,I=Date.now(),k=Wk(b.searchParams,I);if("error"in k)return be(g,400,{error:k.error}),!0;const{from:w,to:N}=k,$=b.searchParams.has("from")||b.searchParams.has("to"),P=$?{from:w,to:N}:void 0;if(["/api/analytics","/api/activity","/api/inspect"].includes(b.pathname)&&$&&(!/^\d+$/.test(b.searchParams.get("from")??"")||!/^\d+$/.test(b.searchParams.get("to")??"")||N<=w||N>I||N-w>31*864e5))return be(g,400,{error:"analytical bounds need from < to, no future end, and at most 31 days"}),!0;try{if(b.pathname==="/api/state"){const[C,T,R,H,U,L]=await Promise.all([Pf().catch(Se=>({available:!1,error:String(Se)})),Vf().catch(Se=>({available:!1,error:String(Se)})),Wf().catch(Se=>({available:!1,error:String(Se)})),Kf().catch(Se=>({available:!1,error:String(Se)})),Yf().catch(Se=>({available:!1,error:String(Se)})),Jf().catch(Se=>({available:!1,error:String(Se)}))]),[G,te,ne,ge]=await Promise.all([hy(w,N).catch(()=>null),gy(w,N).catch(()=>null),wy(w,N).catch(()=>null),Ey(w,N).catch(()=>null)]),we={strata:{"stored-semantics":"failed"}},Pe={"claude-code":G?{strata:Kk(G),registryEntries:G.registryEntries,transcriptsRead:G.transcriptsRead,transcriptsFailed:G.transcriptsFailed,problems:G.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:te?{strata:Zc({storedAvailable:te.storedAvailable,read:te.rolloutsRead,failed:te.rolloutsFailed}),rolloutsRead:te.rolloutsRead,rolloutsFailed:te.rolloutsFailed,problems:te.problems.slice(0,20)}:we,cursor:ne?{strata:Zc({storedAvailable:ne.storedAvailable,read:ne.composersRead,failed:ne.composersFailed}),composersRead:ne.composersRead,composersFailed:ne.composersFailed,problems:ne.problems.slice(0,20)}:we,gemini:ge?{strata:Zc({storedAvailable:ge.storedAvailable,read:ge.sessionsRead,failed:ge.sessionsFailed}),sessionsRead:ge.sessionsRead,sessionsFailed:ge.sessionsFailed,problems:ge.problems.slice(0,20)}:we},Oe={deepseek:Qr(C),"0x2f":Qr(T),"claude-code":Qr(R),codex:Qr(H),cursor:Qr(U),gemini:Qr(L)},Q=e.collectionHealth();for(const[Se,dr]of Object.entries(Oe)){const zt=Q[Se];zt?.failing&&(dr.presence="failed",dr.error??=zt.lastError)}const Ae=e.os.stats(),Ne=e.machinePulse?.stats();e.machinePulse&&Ne&&(Oe[xt]={available:Ne.samples>0&&!Ne.lastError,present:!0,presence:Ne.lastError?"failed":Ne.samples>0?"observing":"installed-no-data",error:Ne.lastError});const ae=Object.values(Oe).filter(Se=>Se.available).length>0?"observing":Ae.samples>0?"os-only":"empty",me=Jc(e).failingSources,_t=E.health(),lr={ok:me.length===0&&_t.ok&&!e.fault()&&!Ae.lastError&&!Ne?.lastError,failingSources:me,collection:Q,store:_t,os:Ae.lastError?{failing:!0,lastError:Ae.lastError}:{failing:!1},machinePulse:Ne?.lastError?{failing:!0,lastError:Ne.lastError}:e.machinePulse?{failing:!1}:void 0};return be(g,200,{machine:e.machine,mode:ae,fault:e.fault()??void 0,health:lr,store:{...E.stats(),path:E.path,schemaVersion:E.schemaVersion,bytes:E.sizeBytes(),retention:{...e.retention,description:$a(e.retention)}},os:{...Ae,running:e.os.running,source:nn},machinePulse:e.machinePulse&&Ne?{...Ne,running:e.machinePulse.running,source:xt}:void 0,sources:Oe,observation:Pe}),!0}if(b.pathname==="/api/collect"){const C=e.checkStore();if(C)return be(g,503,{error:C.message,fault:C}),!0;const T=await hw(E,Nu,w,N,U=>e.recordCollection([U])),R=await e.os.sample();e.recordCollection([{id:nn,ok:!e.os.stats().lastError,error:e.os.stats().lastError}]);const H=e.machinePulse?await e.machinePulse.sample():[];if(e.machinePulse){const U=e.machinePulse.stats();e.recordCollection([{id:xt,ok:!U.lastError,error:U.lastError}])}return be(g,200,{...T,sources:[...T.sources,{id:nn,ok:!e.os.stats().lastError,collected:R.length,inserted:R.length,duplicate:0,error:e.os.stats().lastError,ms:0},...e.machinePulse?[{id:xt,ok:!e.machinePulse.stats().lastError,collected:H.length,inserted:H.length,duplicate:0,error:e.machinePulse.stats().lastError,ms:e.machinePulse.stats().lastDurationMs??0}]:[]]}),!0}if(b.pathname==="/api/world"){const C=b.searchParams.get("window")==="live",T=await(C?o:s).read({from:w,to:N,label:C?"LIVE WORLD":"WINDOW"});return be(g,200,{from:T.from,to:T.to,now:C?T.world.now:I,world:T.world,meta:T.meta,waits:T.waits}),!0}if(b.pathname==="/api/health")return be(g,200,{pid:process.pid,version:t.version??"dev",contract:Od,store:e.path,health:Jc(e)}),!0;if(b.pathname==="/api/landscape"){const C=b.searchParams.get("window")==="live",T=C?Gp(I):{from:w,to:N},R=await(C?o:s).read({...T,label:C?"TODAY":"WINDOW",...C?{widenFrom:I-Kp,widenedLabel:"LAST 72H"}:{}}),H=Dc(R.world),U=Lc(H);return C&&(a={at:I,label:R.label,world:H,landscape:U,waits:R.waits}),be(g,200,{from:R.from,to:R.to,now:C?R.world.now:I,window:R.label,meta:R.meta,health:Jc(e),...rS(U)}),!0}if(b.pathname==="/api/analytics"){const C=b.searchParams.get("scope")??"today";if(C!=="today"&&C!=="last-7d")return be(g,400,{error:"analytics needs scope=today|last-7d"}),!0;const T=b.searchParams.get("project")??void 0;if(T!==void 0&&!wi(T))return be(g,400,{error:"invalid project key"}),!0;const R=b.searchParams.get("comparison");if(R!==null&&R!=="previous"&&R!=="calendar")return be(g,400,{error:"comparison must be previous|calendar"}),!0;const H=R==="calendar"?"calendar":"previous",U=await d(C,I,R?T??null:void 0,Wp(g),P,H),L=vo(U.world,T),G={runs:L.executions.size,reported:U.waitReportedIds.filter(Oe=>L.executions.has(Oe)).length},te=a?.landscape??{disturbances:[],strata:[]},ne=fp(L,G,P?N-w<=25*36e5?"today":"last-7d":C),ge=CS(U.world,T),we=H==="calendar"?C==="today"?"same local hours one day earlier":"same local bounds one week earlier":`previous ${fe(U.period.to-U.period.from)}`,Pe={period:U.period,asOf:U.asOf,project:ge,today:ne,comparison:U.comparison,comparisonLabel:we};return be(g,200,{summaryText:pp(Pe),privateSummaryText:pp(Pe,!0),period:U.period,asOf:U.asOf,comparisonPeriod:R?H==="calendar"?Fy(U.period,C==="today"?1:7):xd(U.period):void 0,comparisonLabel:we,comparisonBasis:H,projects:IS(U.world),project:ge,projectKey:T??null,comparison:U.comparison,today:{window:U.period.label,...ne},log:{window:U.period.label,...Vc(L,te,{starts:U.executionStarts,waitReportedIds:U.waitReportedIds})}}),!0}if(b.pathname==="/api/today"||b.pathname==="/api/log"){const C=await m(I);return be(g,200,b.pathname==="/api/today"?{window:C.label,...fp(C.world,C.waits)}:{window:C.label,...Vc(C.world,C.landscape)}),!0}if(b.pathname==="/api/inspect"){const C=b.searchParams.get("kind")??"",T=b.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(C)||!T||T.length>512)return be(g,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;const R=b.searchParams.get("scope");if(R!==null&&R!=="today"&&R!=="last-7d")return be(g,400,{error:"inspect needs scope=today|last-7d"}),!0;const H=b.searchParams.get("project")??void 0;if(H!==void 0&&(!R||!wi(H)))return be(g,400,{error:"project inspection needs a scope and a valid project key"}),!0;const U=b.searchParams.get("at"),L=U===null?I:Number(U);if(!Number.isSafeInteger(L)||L>I||L<I-6e5)return be(g,400,{error:"refresh the analytical snapshot before inspecting it"}),!0;const G=R?P??Eu(R,L):void 0,ne=(R&&U!==null&&G?u.get(JSON.stringify([R,G.from,G.to,L])):void 0)??(R?await d(R,L,void 0,Wp(g),P):await m(I)),ge=(Oe,Q)=>{for(const Ae of E.subjectEvents(Oe,Q))if(Ae.provenance?.path)return Ae.provenance.path},we=vo(ne.world,H);let Pe=lp(we,ne.landscape,C,T,ge,R&&"executionStarts"in ne?ne.executionStarts:void 0);if(R&&Pe&&we.executions.has(T)){const Oe=tk(E,T,we.now,e.machine.id),Q=lp(Oe,ne.landscape,C,T,ge),Ae=Vc(we,ne.landscape).rows.find(Ne=>Ne.id===T);if(Q&&Ae){for(const Ne of Q.groups)for(const A of Ne.rows)A.key==="ELAPSED"&&(A.note=[A.note,`Full retained record as of ${new Date(we.now).toISOString()}; may include time outside the selected period.`].filter(Boolean).join(" "));Pe={...Q,groups:[{title:"IN SELECTED PERIOD",metadata:!0,rows:[{key:"RUN TIME",value:fe(Ae.durationMs),note:"Clipped to the selected period; trailing idle silence excluded. Parallel runs add together."},{key:"TOKENS",value:Ae.tokens===null?"not reported":Ye(Ae.tokens),note:"Only accounting events recorded in the selected period."},{key:"TOOL CALLS",value:Ae.tools===null?"not reported":String(Ae.tools)},{key:"WAITING",value:"waitReportedIds"in ne&&ne.waitReportedIds.includes(T)?fe(Ae.waitedMs):"not reported",note:"Includes an explicit wait still open at the snapshot."}]},...Q.groups]}}}return Pe?(be(g,200,Pe),!0):(be(g,404,{error:"not in the current world"}),!0)}if(b.pathname==="/api/activity"){const C=b.searchParams,T=JS({query:C.get("query"),scope:C.get("scope"),focus:C.get("focus"),by:C.get("by")});if("error"in T)return be(g,400,T),!0;const R=C.get("project")??void 0,H=C.get("at"),U=H===null?void 0:Number(H);if(R!==void 0&&!wi(R))return be(g,400,{error:"invalid project key"}),!0;if(U!==void 0&&(!H?.match(/^\d+$/)||!Number.isSafeInteger(U)||U>I||U<I-6e5))return be(g,400,{error:"reading snapshot must be within the last ten minutes; refresh the analytical view"}),!0;const L=C.get("view")==="live"?a?.label??(await m(I)).label:void 0;return be(g,200,await n.read(T,{...L?{view:L}:{},projectKey:R,at:U,period:P})),!0}if(b.pathname==="/api/sources"){const C=await Promise.all([Pf().catch(L=>({available:!1,error:String(L)})),Vf().catch(L=>({available:!1,error:String(L)})),Wf().catch(L=>({available:!1,error:String(L)})),Kf().catch(L=>({available:!1,error:String(L)})),Yf().catch(L=>({available:!1,error:String(L)})),Jf().catch(L=>({available:!1,error:String(L)}))]),T=e.collectionHealth(),R=e.os.stats(),H=e.machinePulse?.stats(),U=Nu.map((L,G)=>{const te=Qr(C[G]),ne=T[L.id];return{id:L.id,presence:ne?.failing?"failed":te.presence,origin:te.origin,error:ne?.failing?ne.lastError??te.error:te.error,consecutiveFailures:ne?.consecutiveFailures??0,lastSuccessAt:ne?.lastSuccessAt}});return U.push({id:nn,presence:R.lastError?"failed":R.samples>0?"observing":"installed-no-data",origin:void 0,error:R.lastError,consecutiveFailures:T[nn]?.consecutiveFailures??0,lastSuccessAt:R.lastSampleAt??void 0}),e.machinePulse&&H&&U.push({id:xt,presence:H.lastError?"failed":H.samples>0?"observing":"installed-no-data",origin:void 0,error:H.lastError,consecutiveFailures:T[xt]?.consecutiveFailures??0,lastSuccessAt:H.lastSampleAt??void 0}),be(g,200,{sources:U}),!0}if(b.pathname==="/api/detail"){const C=b.searchParams.get("type")??"",T=b.searchParams.get("id")??"";if(!Bf.includes(C)||!T)return be(g,400,{error:"detail needs type=<entity type> and id"}),!0;if(T.length>512)return be(g,400,{error:"id is too long"}),!0;const R=E.subjectEvents(C,T);return be(g,200,{type:C,id:T,events:R.slice(0,pi),truncated:R.length>pi}),!0}if(b.pathname==="/api/events"){const C=b.searchParams.get("subject"),T=C?C.split(",").filter(H=>Bf.includes(H)):void 0,R=yg(E,w,N,T,e.machine.id);return be(g,200,{from:w,to:N,now:I,events:R.events.slice(0,pi),truncated:R.events.length>pi,relationships:R.relationships}),!0}return be(g,404,{error:"unknown endpoint"}),!0}catch(C){return g.destroyed||(r.error(`[057] ${String(C)}`),be(g,500,{error:String(C)})),!0}}}var qp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},zp={};var Yp;function Yk(){if(Yp)return zp;Yp=1;var t;return(function(e){(function(r){var n=typeof globalThis=="object"?globalThis:typeof qp=="object"?qp:typeof self=="object"?self:typeof this=="object"?this:c(),s=o(e);typeof n.Reflect<"u"&&(s=o(n.Reflect,s)),r(s,n),typeof n.Reflect>"u"&&(n.Reflect=e);function o(u,l){return function(d,m){Object.defineProperty(u,d,{configurable:!0,writable:!0,value:m}),l&&l(d,m)}}function i(){try{return Function("return this;")()}catch{}}function a(){try{return(0,eval)("(function() { return this; })()")}catch{}}function c(){return i()||a()}})(function(r,n){var s=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",i=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",a=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",c=typeof Object.create=="function",u={__proto__:[]}instanceof Array,l=!c&&!u,d={create:c?function(){return _c(Object.create(null))}:u?function(){return _c({__proto__:null})}:function(){return _c({})},has:l?function(x,O){return s.call(x,O)}:function(x,O){return O in x},get:l?function(x,O){return s.call(x,O)?x[O]:void 0}:function(x,O){return x[O]}},m=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Pb(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Lb(),g=typeof WeakMap=="function"?WeakMap:Ub(),v=o?Symbol.for("@reflect-metadata:registry"):void 0,b=Rb(),_=jb(b);function E(x,O,M,F){if(Q(M)){if(!dr(x))throw new TypeError;if(!Yt(O))throw new TypeError;return H(x,O)}else{if(!dr(x))throw new TypeError;if(!A(O))throw new TypeError;if(!A(F)&&!Q(F)&&!Ae(F))throw new TypeError;return Ae(F)&&(F=void 0),M=Se(M),U(x,O,M,F)}}r("decorate",E);function I(x,O){function M(F,se){if(!A(F))throw new TypeError;if(!Q(se)&&!$r(se))throw new TypeError;ge(x,O,F,se)}return M}r("metadata",I);function k(x,O,M,F){if(!A(M))throw new TypeError;return Q(F)||(F=Se(F)),ge(x,O,M,F)}r("defineMetadata",k);function w(x,O,M){if(!A(O))throw new TypeError;return Q(M)||(M=Se(M)),L(x,O,M)}r("hasMetadata",w);function N(x,O,M){if(!A(O))throw new TypeError;return Q(M)||(M=Se(M)),G(x,O,M)}r("hasOwnMetadata",N);function $(x,O,M){if(!A(O))throw new TypeError;return Q(M)||(M=Se(M)),te(x,O,M)}r("getMetadata",$);function P(x,O,M){if(!A(O))throw new TypeError;return Q(M)||(M=Se(M)),ne(x,O,M)}r("getOwnMetadata",P);function C(x,O){if(!A(x))throw new TypeError;return Q(O)||(O=Se(O)),we(x,O)}r("getMetadataKeys",C);function T(x,O){if(!A(x))throw new TypeError;return Q(O)||(O=Se(O)),Pe(x,O)}r("getOwnMetadataKeys",T);function R(x,O,M){if(!A(O))throw new TypeError;if(Q(M)||(M=Se(M)),!A(O))throw new TypeError;Q(M)||(M=Se(M));var F=Bs(O,M,!1);return Q(F)?!1:F.OrdinaryDeleteMetadata(x,O,M)}r("deleteMetadata",R);function H(x,O){for(var M=x.length-1;M>=0;--M){var F=x[M],se=F(O);if(!Q(se)&&!Ae(se)){if(!Yt(se))throw new TypeError;O=se}}return O}function U(x,O,M,F){for(var se=x.length-1;se>=0;--se){var Fe=x[se],Le=Fe(O,M,F);if(!Q(Le)&&!Ae(Le)){if(!A(Le))throw new TypeError;F=Le}}return F}function L(x,O,M){var F=G(x,O,M);if(F)return!0;var se=Bc(O);return Ae(se)?!1:L(x,se,M)}function G(x,O,M){var F=Bs(O,M,!1);return Q(F)?!1:_t(F.OrdinaryHasOwnMetadata(x,O,M))}function te(x,O,M){var F=G(x,O,M);if(F)return ne(x,O,M);var se=Bc(O);if(!Ae(se))return te(x,se,M)}function ne(x,O,M){var F=Bs(O,M,!1);if(!Q(F))return F.OrdinaryGetOwnMetadata(x,O,M)}function ge(x,O,M,F){var se=Bs(M,F,!0);se.OrdinaryDefineOwnMetadata(x,O,M,F)}function we(x,O){var M=Pe(x,O),F=Bc(x);if(F===null)return M;var se=we(F,O);if(se.length<=0)return M;if(M.length<=0)return se;for(var Fe=new h,Le=[],le=0,q=M;le<q.length;le++){var X=q[le],Z=Fe.has(X);Z||(Fe.add(X),Le.push(X))}for(var re=0,de=se;re<de.length;re++){var X=de[re],Z=Fe.has(X);Z||(Fe.add(X),Le.push(X))}return Le}function Pe(x,O){var M=Bs(x,O,!1);return M?M.OrdinaryOwnMetadataKeys(x,O):[]}function Oe(x){if(x===null)return 1;switch(typeof x){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return x===null?1:6;default:return 6}}function Q(x){return x===void 0}function Ae(x){return x===null}function Ne(x){return typeof x=="symbol"}function A(x){return typeof x=="object"?x!==null:typeof x=="function"}function ae(x,O){switch(Oe(x)){case 0:return x;case 1:return x;case 2:return x;case 3:return x;case 4:return x;case 5:return x}var M="string",F=xf(x,i);if(F!==void 0){var se=F.call(x,M);if(A(se))throw new TypeError;return se}return me(x)}function me(x,O){var M,F;{var se=x.toString;if(zt(se)){var F=se.call(x);if(!A(F))return F}var M=x.valueOf;if(zt(M)){var F=M.call(x);if(!A(F))return F}}throw new TypeError}function _t(x){return!!x}function lr(x){return""+x}function Se(x){var O=ae(x);return Ne(O)?O:lr(O)}function dr(x){return Array.isArray?Array.isArray(x):x instanceof Object?x instanceof Array:Object.prototype.toString.call(x)==="[object Array]"}function zt(x){return typeof x=="function"}function Yt(x){return typeof x=="function"}function $r(x){switch(Oe(x)){case 3:return!0;case 4:return!0;default:return!1}}function $c(x,O){return x===O||x!==x&&O!==O}function xf(x,O){var M=x[O];if(M!=null){if(!zt(M))throw new TypeError;return M}}function If(x){var O=xf(x,a);if(!zt(O))throw new TypeError;var M=O.call(x);if(!A(M))throw new TypeError;return M}function Cf(x){return x.value}function Of(x){var O=x.next();return O.done?!1:O}function Nf(x){var O=x.return;O&&O.call(x)}function Bc(x){var O=Object.getPrototypeOf(x);if(typeof x!="function"||x===m||O!==m)return O;var M=x.prototype,F=M&&Object.getPrototypeOf(M);if(F==null||F===Object.prototype)return O;var se=F.constructor;return typeof se!="function"||se===x?O:se}function Mb(){var x;!Q(v)&&typeof n.Reflect<"u"&&!(v in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(x=Db(n.Reflect));var O,M,F,se=new g,Fe={registerProvider:Le,getProvider:q,setProvider:Z};return Fe;function Le(re){if(!Object.isExtensible(Fe))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case x===re:break;case Q(O):O=re;break;case O===re:break;case Q(M):M=re;break;case M===re:break;default:F===void 0&&(F=new h),F.add(re);break}}function le(re,de){if(!Q(O)){if(O.isProviderFor(re,de))return O;if(!Q(M)){if(M.isProviderFor(re,de))return O;if(!Q(F))for(var Ie=If(F);;){var Re=Of(Ie);if(!Re)return;var Mt=Cf(Re);if(Mt.isProviderFor(re,de))return Nf(Ie),Mt}}}if(!Q(x)&&x.isProviderFor(re,de))return x}function q(re,de){var Ie=se.get(re),Re;return Q(Ie)||(Re=Ie.get(de)),Q(Re)&&(Re=le(re,de),Q(Re)||(Q(Ie)&&(Ie=new p,se.set(re,Ie)),Ie.set(de,Re))),Re}function X(re){if(Q(re))throw new TypeError;return O===re||M===re||!Q(F)&&F.has(re)}function Z(re,de,Ie){if(!X(Ie))throw new Error("Metadata provider not registered.");var Re=q(re,de);if(Re!==Ie){if(!Q(Re))return!1;var Mt=se.get(re);Q(Mt)&&(Mt=new p,se.set(re,Mt)),Mt.set(de,Ie)}return!0}}function Rb(){var x;return!Q(v)&&A(n.Reflect)&&Object.isExtensible(n.Reflect)&&(x=n.Reflect[v]),Q(x)&&(x=Mb()),!Q(v)&&A(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,v,{enumerable:!1,configurable:!1,writable:!1,value:x}),x}function jb(x){var O=new g,M={isProviderFor:function(X,Z){var re=O.get(X);return Q(re)?!1:re.has(Z)},OrdinaryDefineOwnMetadata:Le,OrdinaryHasOwnMetadata:se,OrdinaryGetOwnMetadata:Fe,OrdinaryOwnMetadataKeys:le,OrdinaryDeleteMetadata:q};return b.registerProvider(M),M;function F(X,Z,re){var de=O.get(X),Ie=!1;if(Q(de)){if(!re)return;de=new p,O.set(X,de),Ie=!0}var Re=de.get(Z);if(Q(Re)){if(!re)return;if(Re=new p,de.set(Z,Re),!x.setProvider(X,Z,M))throw de.delete(Z),Ie&&O.delete(X),new Error("Wrong provider for target.")}return Re}function se(X,Z,re){var de=F(Z,re,!1);return Q(de)?!1:_t(de.has(X))}function Fe(X,Z,re){var de=F(Z,re,!1);if(!Q(de))return de.get(X)}function Le(X,Z,re,de){var Ie=F(re,de,!0);Ie.set(X,Z)}function le(X,Z){var re=[],de=F(X,Z,!1);if(Q(de))return re;for(var Ie=de.keys(),Re=If(Ie),Mt=0;;){var Tf=Of(Re);if(!Tf)return re.length=Mt,re;var Hb=Cf(Tf);try{re[Mt]=Hb}catch(Vb){try{Nf(Re)}finally{throw Vb}}Mt++}}function q(X,Z,re){var de=F(Z,re,!1);if(Q(de)||!de.delete(X))return!1;if(de.size===0){var Ie=O.get(Z);Q(Ie)||(Ie.delete(re),Ie.size===0&&O.delete(Ie))}return!0}}function Db(x){var O=x.defineMetadata,M=x.hasOwnMetadata,F=x.getOwnMetadata,se=x.getOwnMetadataKeys,Fe=x.deleteMetadata,Le=new g,le={isProviderFor:function(q,X){var Z=Le.get(q);return!Q(Z)&&Z.has(X)?!0:se(q,X).length?(Q(Z)&&(Z=new h,Le.set(q,Z)),Z.add(X),!0):!1},OrdinaryDefineOwnMetadata:O,OrdinaryHasOwnMetadata:M,OrdinaryGetOwnMetadata:F,OrdinaryOwnMetadataKeys:se,OrdinaryDeleteMetadata:Fe};return le}function Bs(x,O,M){var F=b.getProvider(x,O);if(!Q(F))return F;if(M){if(b.setProvider(x,O,_))return _;throw new Error("Illegal state.")}}function Pb(){var x={},O=[],M=(function(){function le(q,X,Z){this._index=0,this._keys=q,this._values=X,this._selector=Z}return le.prototype["@@iterator"]=function(){return this},le.prototype[a]=function(){return this},le.prototype.next=function(){var q=this._index;if(q>=0&&q<this._keys.length){var X=this._selector(this._keys[q],this._values[q]);return q+1>=this._keys.length?(this._index=-1,this._keys=O,this._values=O):this._index++,{value:X,done:!1}}return{value:void 0,done:!0}},le.prototype.throw=function(q){throw this._index>=0&&(this._index=-1,this._keys=O,this._values=O),q},le.prototype.return=function(q){return this._index>=0&&(this._index=-1,this._keys=O,this._values=O),{value:q,done:!0}},le})(),F=(function(){function le(){this._keys=[],this._values=[],this._cacheKey=x,this._cacheIndex=-2}return Object.defineProperty(le.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),le.prototype.has=function(q){return this._find(q,!1)>=0},le.prototype.get=function(q){var X=this._find(q,!1);return X>=0?this._values[X]:void 0},le.prototype.set=function(q,X){var Z=this._find(q,!0);return this._values[Z]=X,this},le.prototype.delete=function(q){var X=this._find(q,!1);if(X>=0){for(var Z=this._keys.length,re=X+1;re<Z;re++)this._keys[re-1]=this._keys[re],this._values[re-1]=this._values[re];return this._keys.length--,this._values.length--,$c(q,this._cacheKey)&&(this._cacheKey=x,this._cacheIndex=-2),!0}return!1},le.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=x,this._cacheIndex=-2},le.prototype.keys=function(){return new M(this._keys,this._values,se)},le.prototype.values=function(){return new M(this._keys,this._values,Fe)},le.prototype.entries=function(){return new M(this._keys,this._values,Le)},le.prototype["@@iterator"]=function(){return this.entries()},le.prototype[a]=function(){return this.entries()},le.prototype._find=function(q,X){if(!$c(this._cacheKey,q)){this._cacheIndex=-1;for(var Z=0;Z<this._keys.length;Z++)if($c(this._keys[Z],q)){this._cacheIndex=Z;break}}return this._cacheIndex<0&&X&&(this._cacheIndex=this._keys.length,this._keys.push(q),this._values.push(void 0)),this._cacheIndex},le})();return F;function se(le,q){return le}function Fe(le,q){return q}function Le(le,q){return[le,q]}}function Lb(){var x=(function(){function O(){this._map=new p}return Object.defineProperty(O.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),O.prototype.has=function(M){return this._map.has(M)},O.prototype.add=function(M){return this._map.set(M,M),this},O.prototype.delete=function(M){return this._map.delete(M)},O.prototype.clear=function(){this._map.clear()},O.prototype.keys=function(){return this._map.keys()},O.prototype.values=function(){return this._map.keys()},O.prototype.entries=function(){return this._map.entries()},O.prototype["@@iterator"]=function(){return this.keys()},O.prototype[a]=function(){return this.keys()},O})();return x}function Ub(){var x=16,O=d.create(),M=F();return(function(){function q(){this._key=F()}return q.prototype.has=function(X){var Z=se(X,!1);return Z!==void 0?d.has(Z,this._key):!1},q.prototype.get=function(X){var Z=se(X,!1);return Z!==void 0?d.get(Z,this._key):void 0},q.prototype.set=function(X,Z){var re=se(X,!0);return re[this._key]=Z,this},q.prototype.delete=function(X){var Z=se(X,!1);return Z!==void 0?delete Z[this._key]:!1},q.prototype.clear=function(){this._key=F()},q})();function F(){var q;do q="@@WeakMap@@"+le();while(d.has(O,q));return O[q]=!0,q}function se(q,X){if(!s.call(q,M)){if(!X)return;Object.defineProperty(q,M,{value:d.create()})}return q[M]}function Fe(q,X){for(var Z=0;Z<X;++Z)q[Z]=Math.random()*255|0;return q}function Le(q){if(typeof Uint8Array=="function"){var X=new Uint8Array(q);return typeof crypto<"u"?crypto.getRandomValues(X):typeof msCrypto<"u"?msCrypto.getRandomValues(X):Fe(X,q),X}return Fe(new Array(q),q)}function le(){var q=Le(x);q[6]=q[6]&79|64,q[8]=q[8]&191|128;for(var X="",Z=0;Z<x;++Z){var re=q[Z];(Z===4||Z===6||Z===8)&&(X+="-"),re<16&&(X+="0"),X+=re.toString(16).toLowerCase()}return X}}function _c(x){return x.__=void 0,delete x.__,x}})})(t||(t={})),zp}Yk();const Xk="[object ArrayBuffer]";class K{static isArrayBuffer(e){return Object.prototype.toString.call(e)===Xk}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,r){if(e.constructor===r)return e;if(this.isArrayBuffer(e))return new r(e);if(this.isArrayBufferView(e))return new r(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,r){const n=K.toUint8Array(e),s=K.toUint8Array(r);if(n.length!==s.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==s[o])return!1;return!0}static concat(...e){let r;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?r=e[0]:e[e.length-1]instanceof Function?r=e.slice(0,e.length-1):r=e;let n=0;for(const i of r)n+=i.byteLength;const s=new Uint8Array(n);let o=0;for(const i of r){const a=this.toUint8Array(i);s.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(s,e[e.length-1]):s.buffer}}const Qc="string",Jk=/^[0-9a-f\s]+$/i,Zk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Qk=/^[a-zA-Z0-9-_]+$/;class Xp{static fromString(e){const r=unescape(encodeURIComponent(e)),n=new Uint8Array(r.length);for(let s=0;s<r.length;s++)n[s]=r.charCodeAt(s);return n.buffer}static toString(e){const r=K.toUint8Array(e);let n="";for(let o=0;o<r.length;o++)n+=String.fromCharCode(r[o]);return decodeURIComponent(escape(n))}}class Xt{static toString(e,r=!1){const n=K.toArrayBuffer(e),s=new DataView(n);let o="";for(let i=0;i<n.byteLength;i+=2){const a=s.getUint16(i,r);o+=String.fromCharCode(a)}return o}static fromString(e,r=!1){const n=new ArrayBuffer(e.length*2),s=new DataView(n);for(let o=0;o<e.length;o++)s.setUint16(o*2,e.charCodeAt(o),r);return n}}class ee{static isHex(e){return typeof e===Qc&&Jk.test(e)}static isBase64(e){return typeof e===Qc&&Zk.test(e)}static isBase64Url(e){return typeof e===Qc&&Qk.test(e)}static ToString(e,r="utf8"){const n=K.toUint8Array(e);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Xt.toString(n,!0);case"utf16":case"utf16be":return Xt.toString(n);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromString(e,r="utf8"){if(!e)return new ArrayBuffer(0);switch(r.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return Xt.fromString(e,!0);case"utf16":case"utf16be":return Xt.fromString(e);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToBase64(e){const r=K.toUint8Array(e);if(typeof btoa<"u"){const n=this.ToString(r,"binary");return btoa(n)}else return Buffer.from(r).toString("base64")}static FromBase64(e){const r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!ee.isBase64(r))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(r)):new Uint8Array(Buffer.from(r,"base64")).buffer}static FromBase64Url(e){const r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!ee.isBase64Url(r))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(r.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,r=ee.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.FromBinary(e);case"utf8":return Xp.fromString(e);case"utf16":case"utf16be":return Xt.fromString(e);case"utf16le":case"usc2":return Xt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToUtf8String(e,r=ee.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.ToBinary(e);case"utf8":return Xp.toString(e);case"utf16":case"utf16be":return Xt.toString(e);case"utf16le":case"usc2":return Xt.toString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static FromBinary(e){const r=e.length,n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e.charCodeAt(s);return n.buffer}static ToBinary(e){const r=K.toUint8Array(e);let n="";for(let s=0;s<r.length;s++)n+=String.fromCharCode(r[s]);return n}static ToHex(e){const r=K.toUint8Array(e);let n="";const s=r.length;for(let o=0;o<s;o++){const i=r[o];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(e){let r=this.formatString(e);if(!r)return new ArrayBuffer(0);if(!ee.isHex(r))throw new TypeError("Argument 'hexString' is not HEX encoded");r.length%2&&(r=`0${r}`);const n=new Uint8Array(r.length/2);for(let s=0;s<r.length;s=s+2){const o=r.slice(s,s+2);n[s/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,r=!1){return Xt.toString(e,r)}static FromUtf16String(e,r=!1){return Xt.fromString(e,r)}static Base64Padding(e){const r=4-e.length%4;if(r<4)for(let n=0;n<r;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}}ee.DEFAULT_UTF8_ENCODING="utf8";function eE(...t){const e=t.map(s=>s.byteLength).reduce((s,o)=>s+o),r=new Uint8Array(e);let n=0;return t.map(s=>new Uint8Array(s)).forEach(s=>{for(const o of s)r[n++]=o}),r.buffer}function tE(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let s=0;s<t.byteLength;s++)if(r[s]!==n[s])return!1;return!0}function as(t,e){let r=0;if(t.length===1)return t[0];for(let n=t.length-1;n>=0;n--)r+=t[t.length-1-n]*Math.pow(2,e*n);return r}function gn(t,e,r=-1){const n=r;let s=t,o=0,i=Math.pow(2,e);for(let a=1;a<8;a++){if(t<i){let c;if(n<0)c=new ArrayBuffer(a),o=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),o=n}const u=new Uint8Array(c);for(let l=a-1;l>=0;l--){const d=Math.pow(2,l*e);u[o-l-1]=Math.floor(s/d),s-=u[o-l-1]*d}return c}i*=Math.pow(2,e)}return new ArrayBuffer(0)}function Tu(...t){let e=0,r=0;for(const o of t)e+=o.length;const n=new ArrayBuffer(e),s=new Uint8Array(n);for(const o of t)s.set(o,r),r+=o.length;return s}function Cg(){const t=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const a=t[0]===255&&t[1]&128,c=t[0]===0&&(t[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}const e=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(e);for(let a=0;a<this.valueHex.byteLength;a++)r[a]=0;r[0]=t[0]&128;const n=as(r,8),s=new ArrayBuffer(this.valueHex.byteLength),o=new Uint8Array(s);for(let a=0;a<this.valueHex.byteLength;a++)o[a]=t[a];return o[0]&=127,as(o,8)-n}function rE(t){const e=t<0?t*-1:t;let r=128;for(let n=1;n<8;n++){if(e<=r){if(t<0){const i=r-e,a=gn(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let s=gn(e,8,n),o=new Uint8Array(s);if(o[0]&128){const i=s.slice(0),a=new Uint8Array(i);s=new ArrayBuffer(s.byteLength+1),o=new Uint8Array(s);for(let c=0;c<i.byteLength;c++)o[c+1]=a[c];o[0]=0}return s}r*=Math.pow(2,8)}return new ArrayBuffer(0)}function nE(t,e){if(t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let s=0;s<r.length;s++)if(r[s]!==n[s])return!1;return!0}function mt(t,e){const r=t.toString(10);if(e<r.length)return"";const n=e-r.length,s=Array.from({length:n});for(let i=0;i<n;i++)s[i]="0";return s.join("").concat(r)}function Vi(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Bd(t){let e=0,r=0;for(let s=0;s<t.length;s++){const o=t[s];e+=o.byteLength}const n=new Uint8Array(e);for(let s=0;s<t.length;s++){const o=t[s];n.set(new Uint8Array(o),r),r+=o.byteLength}return n.buffer}function Cr(t,e,r,n){return e instanceof Uint8Array?e.byteLength?r<0?(t.error="Wrong parameter: inputOffset less than zero",!1):n<0?(t.error="Wrong parameter: inputLength less than zero",!1):e.byteLength-r-n<0?(t.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(t.error="Wrong parameter: inputBuffer has zero length",!1):(t.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class Ra{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Bd(this.items)}}const Rs=[new Uint8Array([1])],Jp="0123456789",eu="name",Zp="valueHexView",sE="isHexOnly",oE="idBlock",iE="tagClass",aE="tagNumber",cE="isConstructed",uE="fromBER",lE="toBER",dE="local",ot="",ir=new ArrayBuffer(0),ja=new Uint8Array(0),Eo="EndOfContent",Og="OCTET STRING",Ng="BIT STRING";function ar(t){var e;return e=class extends t{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}constructor(...n){var s;super(...n);const o=n[0]||{};this.isHexOnly=(s=o.isHexOnly)!==null&&s!==void 0?s:!1,this.valueHexView=o.valueHex?K.toUint8Array(o.valueHex):ja}fromBER(n,s,o,i){const a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!Cr(this,a,s,o))return-1;const c=s+o;return this.valueHexView=a.subarray(s,c),this.valueHexView.length?(this.blockLength=o,c):(this.warnings.push("Zero buffer length"),s)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ir)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:ee.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}class Mn{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:r=ot,warnings:n=[],valueBeforeDecode:s=ja}={}){this.blockLength=e,this.error=r,this.warnings=n,this.valueBeforeDecodeView=K.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:ee.ToHex(this.valueBeforeDecodeView)}}}Mn.NAME="baseBlock";class Je extends Mn{fromBER(e,r,n,s){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Je.NAME="valueBlock";class Tg extends ar(Mn){constructor({idBlock:e={}}={}){var r,n,s,o;super(),e?(this.isHexOnly=(r=e.isHexOnly)!==null&&r!==void 0?r:!1,this.valueHexView=e.valueHex?K.toUint8Array(e.valueHex):ja,this.tagClass=(n=e.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(s=e.tagNumber)!==null&&s!==void 0?s:-1,this.isConstructed=(o=e.isConstructed)!==null&&o!==void 0?o:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let r=0;switch(this.tagClass){case 1:r|=0;break;case 2:r|=64;break;case 3:r|=128;break;case 4:r|=192;break;default:return this.error="Unknown tag class",ir}if(this.isConstructed&&(r|=32),this.tagNumber<31&&!this.isHexOnly){const s=new Uint8Array(1);if(!e){let o=this.tagNumber;o&=31,r|=o,s[0]=r}return s.buffer}if(!this.isHexOnly){const s=gn(this.tagNumber,7),o=new Uint8Array(s),i=s.byteLength,a=new Uint8Array(i+1);if(a[0]=r|31,!e){for(let c=0;c<i-1;c++)a[c+1]=o[c]|128;a[i]=o[i-1]}return a.buffer}const n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=r|31,!e){const s=this.valueHexView;for(let o=0;o<s.length-1;o++)n[o+1]=s[o]|128;n[this.valueHexView.byteLength]=s[s.length-1]}return n.buffer}fromBER(e,r,n){const s=K.toUint8Array(e);if(!Cr(this,s,r,n))return-1;const o=s.subarray(r,r+n);if(o.length===0)return this.error="Zero buffer length",-1;switch(o[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(o[0]&32)===32,this.isHexOnly=!1;const a=o[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=0;for(;;){const l=c+1;if(l>=o.length)return this.error="End of input reached before message was fully decoded",-1;if(c++,(o[l]&128)===0)break}this.blockLength=c+1;const u=this.valueHexView=new Uint8Array(c);for(let l=0;l<c;l++)u[l]=o[l+1]&127;this.blockLength<=9?this.tagNumber=as(u,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return r+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}Tg.NAME="identificationBlock";class $g extends Mn{constructor({lenBlock:e={}}={}){var r,n,s;super(),this.isIndefiniteForm=(r=e.isIndefiniteForm)!==null&&r!==void 0?r:!1,this.longFormUsed=(n=e.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(s=e.length)!==null&&s!==void 0?s:0}fromBER(e,r,n){const s=K.toUint8Array(e);if(!Cr(this,s,r,n))return-1;const o=s.subarray(r,r+n);if(o.length===0)return this.error="Zero buffer length",-1;if(o[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=o[0]===128,this.isIndefiniteForm)return this.blockLength=1,r+this.blockLength;if(this.longFormUsed=!!(o[0]&128),this.longFormUsed===!1)return this.length=o[0],this.blockLength=1,r+this.blockLength;const i=o[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>o.length)return this.error="End of input reached before message was fully decoded",-1;const a=r+1,c=s.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=as(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,r+this.blockLength}toBER(e=!1){let r,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=128),r;if(this.longFormUsed){const s=gn(this.length,8);if(s.byteLength>127)return this.error="Too big length",ir;if(r=new ArrayBuffer(s.byteLength+1),e)return r;const o=new Uint8Array(s);n=new Uint8Array(r),n[0]=s.byteLength|128;for(let i=0;i<s.byteLength;i++)n[i+1]=o[i];return r}return r=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(r),n[0]=this.length),r}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}$g.NAME="lengthBlock";const Y={};class We extends Mn{constructor({name:e=ot,optional:r=!1,primitiveSchema:n,...s}={},o){super(s),this.name=e,this.optional=r,n&&(this.primitiveSchema=n),this.idBlock=new Tg(s),this.lenBlock=new $g(s),this.valueBlock=o?new o(s):new Je(s)}fromBER(e,r,n,s){const o=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(e,r){const n=r||new Ra;r||Bg(this);const s=this.idBlock.toBER(e);if(n.write(s),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{const o=this.valueBlock.toBER(e);this.lenBlock.length=o.byteLength;const i=this.lenBlock.toBER(e);n.write(i),n.write(o)}return r?ir:n.final()}toJSON(){const e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return e==="ascii"?this.onAsciiEncoding():ee.ToHex(this.toBER())}onAsciiEncoding(){const e=this.constructor.NAME,r=ee.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${r}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;const r=this.toBER(),n=e.toBER();return nE(r,n)}}We.NAME="BaseBlock";function Bg(t){var e;if(t instanceof Y.Constructed)for(const r of t.valueBlock.value)Bg(r)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}class _d extends We{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=ot,...r}={},n){super(r,n),e&&this.fromString(e)}fromBER(e,r,n){const s=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return s===-1?(this.error=this.valueBlock.error,s):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),s)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}_d.NAME="BaseStringBlock";class _g extends ar(Je){constructor({isHexOnly:e=!0,...r}={}){super(r),this.isHexOnly=e}}_g.NAME="PrimitiveValueBlock";var Mg;class Ho extends We{constructor(e={}){super(e,_g),this.idBlock.isConstructed=!1}}Mg=Ho;Y.Primitive=Mg;Ho.NAME="PRIMITIVE";const Rg=100,jg=1e4,Dg=16*1024*1024,fE="Maximum ASN.1 nesting depth exceeded",pE="Maximum ASN.1 node count exceeded",hE="Maximum ASN.1 content length exceeded";function Vo(t={}){var e,r,n;return{depth:0,maxDepth:(e=t.maxDepth)!==null&&e!==void 0?e:Rg,nodesCount:0,maxNodes:(r=t.maxNodes)!==null&&r!==void 0?r:jg,maxContentLength:(n=t.maxContentLength)!==null&&n!==void 0?n:Dg}}function mE(t){const e=new We({},Je);return e.error=t,{offset:-1,result:e}}function yE(t){if(t.nodesCount+=1,t.nodesCount>t.maxNodes)return pE}function gE(t,e){if(t>e.maxContentLength)return hE}function Md(t,e,r,n){const s=n.depth+1;if(s>n.maxDepth)return mE(fE);n.depth=s;try{return Da(t,e,r,n)}finally{n.depth-=1}}function vE(t,e){if(t instanceof e)return t;const r=new e;return r.idBlock=t.idBlock,r.lenBlock=t.lenBlock,r.warnings=t.warnings,r.valueBeforeDecodeView=t.valueBeforeDecodeView,r}function Da(t,e=0,r=t.length,n=Vo()){const s=e;let o=new We({},Je);const i=new Mn;if(!Cr(i,t,e,r))return o.error=i.error,{offset:-1,result:o};if(!t.subarray(e,e+r).length)return o.error="Zero buffer length",{offset:-1,result:o};const c=yE(n);if(c)return o.error=c,{offset:-1,result:o};let u=o.idBlock.fromBER(t,e,r);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),u===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(e=u,r-=o.idBlock.blockLength,u=o.lenBlock.fromBER(t,e,r),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),u===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};e=u,r-=o.lenBlock.blockLength;const l=o.lenBlock.isIndefiniteForm?r:o.lenBlock.length,d=gE(l,n);if(d)return o.error=d,{offset:-1,result:o};if(!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let m=We;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};m=Y.EndOfContent;break;case 1:m=Y.Boolean;break;case 2:m=Y.Integer;break;case 3:m=Y.BitString;break;case 4:m=Y.OctetString;break;case 5:m=Y.Null;break;case 6:m=Y.ObjectIdentifier;break;case 10:m=Y.Enumerated;break;case 12:m=Y.Utf8String;break;case 13:m=Y.RelativeObjectIdentifier;break;case 14:m=Y.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:m=Y.Sequence;break;case 17:m=Y.Set;break;case 18:m=Y.NumericString;break;case 19:m=Y.PrintableString;break;case 20:m=Y.TeletexString;break;case 21:m=Y.VideotexString;break;case 22:m=Y.IA5String;break;case 23:m=Y.UTCTime;break;case 24:m=Y.GeneralizedTime;break;case 25:m=Y.GraphicString;break;case 26:m=Y.VisibleString;break;case 27:m=Y.GeneralString;break;case 28:m=Y.UniversalString;break;case 29:m=Y.CharacterString;break;case 30:m=Y.BmpString;break;case 31:m=Y.DATE;break;case 32:m=Y.TimeOfDay;break;case 33:m=Y.DateTime;break;case 34:m=Y.Duration;break;default:{const p=o.idBlock.isConstructed?new Y.Constructed:new Y.Primitive;p.idBlock=o.idBlock,p.lenBlock=o.lenBlock,p.warnings=o.warnings,o=p}}break;default:m=o.idBlock.isConstructed?Y.Constructed:Y.Primitive}return o=vE(o,m),u=o.fromBER(t,e,l,n),o.valueBeforeDecodeView=t.subarray(s,s+o.blockLength),{offset:u,result:o}}function es(t,e={}){if(!t.byteLength){const r=new We({},Je);return r.error="Input buffer has zero length",{offset:-1,result:r}}return Da(K.toUint8Array(t).slice(),0,t.byteLength,Vo(e))}function bE(t,e){return t?1:e}class Pr extends Je{constructor({value:e=[],isIndefiniteForm:r=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=r}fromBER(e,r,n,s){const o=K.toUint8Array(e),i=s??Vo();if(!Cr(this,o,r,n))return-1;if(this.valueBeforeDecodeView=o.subarray(r,r+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),r;let a=r;for(;bE(this.isIndefiniteForm,n)>0;){const c=Md(o,a,n,i);if(c.offset===-1)return this.error=c.result.error,this.warnings.concat(c.result.warnings),-1;if(a=c.offset,this.blockLength+=c.result.blockLength,n-=c.result.blockLength,this.value.push(c.result),this.isIndefiniteForm&&c.result.constructor.NAME===Eo)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Eo?this.value.pop():this.warnings.push("No EndOfContent block encoded")),a}toBER(e,r){const n=r||new Ra;for(let s=0;s<this.value.length;s++)this.value[s].toBER(e,n);return r?ir:n.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const r of this.value)e.value.push(r.toJSON());return e}}Pr.NAME="ConstructedValueBlock";var Pg;class rt extends We{constructor(e={}){super(e,Pr),this.idBlock.isConstructed=!0}fromBER(e,r,n,s){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;const o=this.valueBlock.fromBER(e,r,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,s);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){const e=[];for(const n of this.valueBlock.value)e.push(n.toString("ascii").split(`
358
+ `).map(s=>` ${s}`).join(`
103
359
  `));const r=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${r} :
104
360
  ${e.join(`
105
- `)}`:`${r} :`}}Ag=et;Y.Constructed=Ag;et.NAME="CONSTRUCTED";class Sg extends Xe{fromBER(e,r,n){return r}toBER(e){return nr}}Sg.override="EndOfContentValueBlock";var kg;class wd extends Ve{constructor(e={}){super(e,Sg),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}kg=wd;Y.EndOfContent=kg;wd.NAME=ys;var Eg;class dn extends Ve{constructor(e={}){super(e,Xe),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,r,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,r+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):r+n}toBER(e,r){const n=new ArrayBuffer(2);if(!e){const o=new Uint8Array(n);o[0]=5,o[1]=0}return r&&r.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}}Eg=dn;Y.Null=Eg;dn.NAME="NULL";class xg extends or(Xe){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...r}={}){super(r),r.valueHex?this.valueHexView=K.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,r,n){const o=K.toUint8Array(e);return Sr(this,o,r,n)?(this.valueHexView=o.subarray(r,r+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,lg.call(this),this.blockLength=n,r+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}xg.NAME="BooleanValueBlock";var Ig;let Ia=class extends Ve{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,xg),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Ig=Ia;Y.Boolean=Ig;Ia.NAME="BOOLEAN";class Og extends or(Rr){constructor({isConstructed:e=!1,...r}={}){super(r),this.isConstructed=e}fromBER(e,r,n,o){let s=0;if(this.isConstructed){if(this.isHexOnly=!1,s=Rr.prototype.fromBER.call(this,e,r,n,o),s===-1)return s;for(let i=0;i<this.value.length;i++){const a=this.value[i].constructor.NAME;if(a===ys){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==dg)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,s=super.fromBER(e,r,n),this.blockLength=n;return s}toBER(e,r){return this.isConstructed?Rr.prototype.toBER.call(this,e,r):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Og.NAME="OctetStringValueBlock";var Ad;let nn=class extends Ve{constructor({idBlock:e={},lenBlock:r={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},Og),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,r,n,o){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),r;if(!this.valueBlock.isConstructed){const i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(r,r+n);try{if(i.byteLength){const a=o??Ms(),c=bd(i,0,i.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,r,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return et.prototype.onAsciiEncoding.call(this);const e=this.constructor.NAME,r=ee.ToHex(this.valueBlock.valueHexView);return`${e} : ${r}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const r of this.valueBlock.value)r instanceof Ad&&e.push(r.valueBlock.valueHexView);return K.concat(e)}};Ad=nn;Y.OctetString=Ad;nn.NAME=dg;class Cg extends or(Rr){constructor({unusedBits:e=0,isConstructed:r=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=r,this.blockLength=this.valueHexView.byteLength}fromBER(e,r,n,o){if(!n)return r;let s=-1;if(this.isConstructed){if(s=Rr.prototype.fromBER.call(this,e,r,n,o),s===-1)return s;for(const c of this.value){const u=c.constructor.NAME;if(u===ys){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(u!==fg)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const d=c.valueBlock;if(this.unusedBits>0&&d.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=d.unusedBits}return s}const i=K.toUint8Array(e);if(!Sr(this,i,r,n))return-1;const a=i.subarray(r,r+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const c=a.subarray(1);try{if(c.byteLength){const u=o??Ms(),d=bd(c,0,c.byteLength,u);d.offset!==-1&&d.offset===n-1&&(this.value=[d.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,r+n}toBER(e,r){if(this.isConstructed)return Rr.prototype.toBER.call(this,e,r);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){const o=new Uint8Array(1);return o[0]=0,o.buffer}const n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}Cg.NAME="BitStringValueBlock";var Ng;let on=class extends Ve{constructor({idBlock:e={},lenBlock:r={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},Cg),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,r,n,o){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,r,n,o)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return et.prototype.onAsciiEncoding.call(this);{const e=[],r=this.valueBlock.valueHexView;for(const i of r)e.push(i.toString(2).padStart(8,"0"));const n=e.join(""),o=this.constructor.NAME,s=n.substring(0,n.length-this.valueBlock.unusedBits);return`${o} : ${s}`}}};Ng=on;Y.BitString=Ng;on.NAME=fg;var Tg;function Lk(t,e){const r=new Uint8Array([0]),n=new Uint8Array(t),o=new Uint8Array(e);let s=n.slice(0);const i=s.length-1,a=o.slice(0),c=a.length-1;let u=0;const d=c<i?i:c;let l=0;for(let m=d;m>=0;m--,l++)!0===l<a.length?u=s[i-l]+a[c-l]+r[0]:u=s[i-l]+r[0],r[0]=u/10,!0===l>=s.length?s=mu(new Uint8Array([u%10]),s):s[i-l]=u%10;return r[0]>0&&(s=mu(r,s)),s}function jp(t){if(t>=No.length)for(let e=No.length;e<=t;e++){const r=new Uint8Array([0]);let n=No[e-1].slice(0);for(let o=n.length-1;o>=0;o--){const s=new Uint8Array([(n[o]<<1)+r[0]]);r[0]=s[0]/10,n[o]=s[0]%10}r[0]>0&&(n=mu(r,n)),No.push(n)}return No[t]}function Pk(t,e){let r=0;const n=new Uint8Array(t),o=new Uint8Array(e),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1;let u,d=0;for(let l=c;l>=0;l--,d++)u=s[i-d]-a[c-d]-r,!0===u<0?(r=1,s[i-d]=u+10):(r=0,s[i-d]=u);if(r>0)for(let l=i-c+1;l>=0;l--,d++)if(u=s[i-d]-r,u<0)r=1,s[i-d]=u+10;else{r=0,s[i-d]=u;break}return s.slice()}class Sd extends or(Xe){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=lg.call(this)))}constructor({value:e,...r}={}){super(r),this._valueDec=0,r.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(wk(e))}get valueDec(){return this._valueDec}fromDER(e,r,n,o=0){const s=this.fromBER(e,r,n);if(s===-1)return s;const i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(e=!1){const r=this.valueHexView;switch(!0){case(r[0]&128)!==0:{const n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(r,1),this.valueHexView=n}break;case(r[0]===0&&(r[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,r,n){const o=super.fromBER(e,r,n);return o===-1||this.setValueHex(),o}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=this.valueHexView.length*8-1;let r=new Uint8Array(this.valueHexView.length*8/3),n=0,o;const s=this.valueHexView;let i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let u=0;u<8;u++)(o&1)===1&&(n===e?(r=Pk(jp(n),r),i="-"):r=Lk(r,jp(n))),n++,o>>=1}for(let c=0;c<r.length;c++)r[c]&&(a=!0),a&&(i+=Mp.charAt(r[c]));return a===!1&&(i+=Mp.charAt(0)),i}}Tg=Sd;Sd.NAME="IntegerValueBlock";Object.defineProperty(Tg.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var ts;class mo extends Ve{constructor(e={}){super(e,Sd),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return $i(),BigInt(this.valueBlock.toString())}static fromBigInt(e){$i();const r=BigInt(e),n=new ka,o=r.toString(16).replace(/^-/,""),s=new Uint8Array(ee.FromHex(o));if(r<0){const a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;const u=BigInt(`0x${ee.ToHex(a)}`)+r,d=K.toUint8Array(ee.FromHex(u.toString(16)));d[0]|=128,n.write(d)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new ts({valueHex:n.final()})}convertToDER(){const e=new ts({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new ts({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}ts=mo;Y.Integer=ts;mo.NAME="INTEGER";var $g;class Oa extends mo{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}$g=Oa;Y.Enumerated=$g;Oa.NAME="ENUMERATED";class yu extends or(Xe){constructor({valueDec:e=-1,isFirstSid:r=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=r}fromBER(e,r,n){if(!n)return r;const o=K.toUint8Array(e);if(!Sr(this,o,r,n))return-1;const s=o.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);const i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=eo(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}set valueBigInt(e){$i();let r=BigInt(e).toString(2);for(;r.length%7;)r="0"+r;const n=new Uint8Array(r.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(r.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}const r=ln(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",nr;const n=new Uint8Array(r.byteLength);if(!e){const o=new Uint8Array(r),s=r.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let e="";if(this.isHexOnly)e=ee.ToHex(this.valueHexView);else if(this.isFirstSid){let r=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",r-=40):(e="2.",r-=80),e+=r.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}yu.NAME="sidBlock";class Bg extends Xe{constructor({value:e=ot,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let o=r;for(;n>0;){const s=new yu;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e){const r=[];for(let n=0;n<this.value.length;n++){const o=this.value[n].toBER(e);if(o.byteLength===0)return this.error=this.value[n].error,nr;r.push(o)}return gd(r)}fromString(e){this.value=[];let r=0,n=0,o="",s=!1;do if(n=e.indexOf(".",r),n===-1?o=e.substring(r):o=e.substring(r,n),r=n+1,s){const i=this.value[0];let a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}const c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{const i=new yu;if(o>Number.MAX_SAFE_INTEGER){$i();const a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),r?(o=`{${o}}`,this.value[n].isFirstSid?e=`2.{${o} - 80}`:e+=o):e+=o}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Bg.NAME="ObjectIdentifierValueBlock";var Rg;class Ca extends Ve{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Bg),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Rg=Ca;Y.ObjectIdentifier=Rg;Ca.NAME="OBJECT IDENTIFIER";class gu extends or(On){constructor({valueDec:e=0,...r}={}){super(r),this.valueDec=e}fromBER(e,r,n){if(n===0)return r;const o=K.toUint8Array(e);if(!Sr(this,o,r,n))return-1;const s=o.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,(s[a]&128)!==0);a++);const i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(s[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=eo(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}const r=ln(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",nr;const n=new Uint8Array(r.byteLength);if(!e){const o=new Uint8Array(r),s=r.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ee.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}gu.NAME="relativeSidBlock";class Mg extends Xe{constructor({value:e=ot,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let o=r;for(;n>0;){const s=new gu;if(o=s.fromBER(e,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(e,r){const n=[];for(let o=0;o<this.value.length;o++){const s=this.value[o].toBER(e);if(s.byteLength===0)return this.error=this.value[o].error,nr;n.push(s)}return gd(n)}fromString(e){this.value=[];let r=0,n=0,o="";do{n=e.indexOf(".",r),n===-1?o=e.substring(r):o=e.substring(r,n),r=n+1;const s=new gu;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(e=`${e}.`),r&&(o=`{${o}}`),e+=o}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Mg.NAME="RelativeObjectIdentifierValueBlock";var _g;class Na extends Ve{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Mg),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}_g=Na;Y.RelativeObjectIdentifier=_g;Na.NAME="RelativeObjectIdentifier";var jg;class Pt extends et{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}jg=Pt;Y.Sequence=jg;Pt.NAME="SEQUENCE";var Dg;let Jt=class extends et{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Dg=Jt;Y.Set=Dg;Jt.NAME="SET";class Lg extends or(Xe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ot}toJSON(){return{...super.toJSON(),value:this.value}}}Lg.NAME="StringValueBlock";class Pg extends Lg{}Pg.NAME="SimpleStringValueBlock";class wt extends vd{constructor({...e}={}){super(e,Pg)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,K.toUint8Array(e))}fromString(e){const r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r);for(let o=0;o<r;o++)n[o]=e.charCodeAt(o);this.valueBlock.value=e}}wt.NAME="SIMPLE STRING";class Ug extends wt{fromBuffer(e){this.valueBlock.valueHexView=K.toUint8Array(e);try{this.valueBlock.value=ee.ToUtf8String(e)}catch(r){this.warnings.push(`Error during "decodeURIComponent": ${r}, using raw string`),this.valueBlock.value=ee.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ee.FromUtf8String(e)),this.valueBlock.value=e}}Ug.NAME="Utf8StringValueBlock";var Vg;class kr extends Ug{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}Vg=kr;Y.Utf8String=Vg;kr.NAME="UTF8String";class Hg extends wt{fromBuffer(e){this.valueBlock.value=ee.ToUtf16String(e),this.valueBlock.valueHexView=K.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ee.FromUtf16String(e))}}Hg.NAME="BmpStringValueBlock";var Fg;class Ta extends Hg{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}Fg=Ta;Y.BmpString=Fg;Ta.NAME="BMPString";class Wg extends wt{fromBuffer(e){const r=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(r);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(r))}fromString(e){const r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r*4);for(let o=0;o<r;o++){const s=ln(e.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;const a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=e}}Wg.NAME="UniversalStringValueBlock";var Kg;class $a extends Wg{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Kg=$a;Y.UniversalString=Kg;$a.NAME="UniversalString";var Gg;class Ba extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Gg=Ba;Y.NumericString=Gg;Ba.NAME="NumericString";var qg;class Ra extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}qg=Ra;Y.PrintableString=qg;Ra.NAME="PrintableString";var zg;class Ma extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}zg=Ma;Y.TeletexString=zg;Ma.NAME="TeletexString";var Yg;class _a extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Yg=_a;Y.VideotexString=Yg;_a.NAME="VideotexString";var Xg;class ja extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Xg=ja;Y.IA5String=Xg;ja.NAME="IA5String";var Jg;class Da extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Jg=Da;Y.GraphicString=Jg;Da.NAME="GraphicString";var Zg;class _s extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}Zg=_s;Y.VisibleString=Zg;_s.NAME="VisibleString";var Qg;class La extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}Qg=La;Y.GeneralString=Qg;La.NAME="GeneralString";var ev;class Pa extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}ev=Pa;Y.CharacterString=ev;Pa.NAME="CharacterString";var tv;class js extends _s{constructor({value:e,valueDate:r,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let o=0;o<e.length;o++)this.valueBlock.valueHexView[o]=e.charCodeAt(o)}r&&(this.fromDate(r),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,K.toUint8Array(e)))}toBuffer(){const e=this.toString(),r=new ArrayBuffer(e.length),n=new Uint8Array(r);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return r}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}const o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){const r=new Array(7);return r[0]=ht(this.year<2e3?this.year-1900:this.year-2e3,2),r[1]=ht(this.month,2),r[2]=ht(this.day,2),r[3]=ht(this.hour,2),r[4]=ht(this.minute,2),r[5]=ht(this.second,2),r[6]="Z",r.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}tv=js;Y.UTCTime=tv;js.NAME="UTCTime";var rv;class Ua extends js{constructor(e={}){var r;super(e),(r=this.millisecond)!==null&&r!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let r=!1,n="",o="",s=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),r=!0;else{const l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let l=1,m=n.indexOf("+"),p="";if(m===-1&&(m=n.indexOf("-"),l=-1),m!==-1){if(p=n.substring(m+1),n=n.substring(0,m),p.length!==2&&p.length!==4)throw new Error("Wrong input string for conversion");let h=parseInt(p.substring(0,2),10);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");if(a=l*h,p.length===4){if(h=parseInt(p.substring(2,4),10),isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");c=l*h}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){const l=new Number(`0${n.substring(u)}`);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");s=l.valueOf(),o=n.substring(0,u)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.minute=Math.floor(l),l=60*(l-this.minute),this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let l=60*s;this.second=Math.floor(l),l=1e3*(l-this.second),this.millisecond=Math.floor(l)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){const l=1e3*s;this.millisecond=Math.floor(l)}break;default:throw new Error("Wrong input string for conversion")}const d=i.exec(o);if(d===null)throw new Error("Wrong input string for conversion");for(let l=1;l<d.length;l++)switch(l){case 1:this.year=parseInt(d[l],10);break;case 2:this.month=parseInt(d[l],10);break;case 3:this.day=parseInt(d[l],10);break;case 4:this.hour=parseInt(d[l],10)+a;break;case 5:this.minute=parseInt(d[l],10)+c;break;case 6:this.second=parseInt(d[l],10);break;default:throw new Error("Wrong input string for conversion")}if(r===!1){const l=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=l.getUTCFullYear(),this.month=l.getUTCMonth(),this.day=l.getUTCDay(),this.hour=l.getUTCHours(),this.minute=l.getUTCMinutes(),this.second=l.getUTCSeconds(),this.millisecond=l.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){const r=[];return r.push(ht(this.year,4)),r.push(ht(this.month,2)),r.push(ht(this.day,2)),r.push(ht(this.hour,2)),r.push(ht(this.minute,2)),r.push(ht(this.second,2)),this.millisecond!==0&&(r.push("."),r.push(ht(this.millisecond,3))),r.push("Z"),r.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}rv=Ua;Y.GeneralizedTime=rv;Ua.NAME="GeneralizedTime";var nv;class kd extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}nv=kd;Y.DATE=nv;kd.NAME="DATE";var ov;class Ed extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}ov=Ed;Y.TimeOfDay=ov;Ed.NAME="TimeOfDay";var sv;class xd extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}sv=xd;Y.DateTime=sv;xd.NAME="DateTime";var iv;class Id extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}iv=Id;Y.Duration=iv;Id.NAME="Duration";var av;class Od extends kr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}av=Od;Y.TIME=av;Od.NAME="TIME";class fn{constructor({name:e=ot,optional:r=!1}={}){this.name=e,this.optional=r}}class Cd extends fn{constructor({value:e=[],...r}={}){super(r),this.value=e}}class Bi extends fn{constructor({value:e=new fn,local:r=!1,...n}={}){super(n),this.value=e,this.local=r}}class Uk{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=K.toUint8Array(e)}constructor({data:e=Ea}={}){this.dataView=K.toUint8Array(e)}fromBER(e,r,n){const o=r+n;return this.dataView=K.toUint8Array(e).subarray(r,o),o}toBER(e){return this.dataView.slice().buffer}}function Tr(t,e,r){if(r instanceof Cd){for(const s of r.value)if(Tr(t,e,s).verified)return{verified:!0,result:t};{const s={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Vc)&&(s.name=r.name),s}}if(r instanceof fn)return r.hasOwnProperty(Vc)&&(t[r.name]=e),{verified:!0,result:t};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(kk in r))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(Ok in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(Ck in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const n=r.idBlock.toBER(!1);if(n.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(r.idBlock.fromBER(n,0,n.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(r.idBlock.hasOwnProperty(Ek)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(xk)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(Ik)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(Sk in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:t};if(r.idBlock.isHexOnly){if(!(_p in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const s=r.idBlock.valueHexView,i=e.idBlock.valueHexView;if(s.length!==i.length)return{verified:!1,result:t};for(let a=0;a<s.length;a++)if(s[a]!==i[1])return{verified:!1,result:t}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(t[r.name]=e)),r instanceof Y.Constructed){let s=0,i={verified:!1,result:{error:"Unknown error"}},a=r.valueBlock.value.length;if(a>0&&r.valueBlock.value[0]instanceof Bi&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:t};if(e.valueBlock.value.length===0&&r.valueBlock.value.length!==0){let c=!0;for(let u=0;u<r.valueBlock.value.length;u++)c=c&&(r.valueBlock.value[u].optional||!1);return c?{verified:!0,result:t}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&delete t[r.name]),t.error="Inconsistent object length",{verified:!1,result:t})}for(let c=0;c<a;c++)if(c-s>=e.valueBlock.value.length){if(r.valueBlock.value[c].optional===!1){const u={verified:!1,result:t};return t.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(delete t[r.name],u.name=r.name)),u}}else if(r.valueBlock.value[0]instanceof Bi){if(i=Tr(t,e.valueBlock.value[c],r.valueBlock.value[0].value),i.verified===!1)if(r.valueBlock.value[0].optional)s++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&delete t[r.name]),i;if(Vc in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let u={};Nk in r.valueBlock.value[0]&&r.valueBlock.value[0].local?u=e:u=t,typeof u[r.valueBlock.value[0].name]>"u"&&(u[r.valueBlock.value[0].name]=[]),u[r.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(i=Tr(t,e.valueBlock.value[c-s],r.valueBlock.value[c]),i.verified===!1)if(r.valueBlock.value[c].optional)s++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&delete t[r.name]),i;if(i.verified===!1){const c={verified:!1,result:t};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(delete t[r.name],c.name=r.name)),c}return{verified:!0,result:t}}if(r.primitiveSchema&&_p in e.valueBlock){const s=xa(e.valueBlock.valueHexView);if(s.offset===-1){const i={verified:!1,result:s.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(delete t[r.name],i.name=r.name)),i}return Tr(t,s.result,r.primitiveSchema)}return{verified:!0,result:t}}function Vk(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=xa(K.toUint8Array(t));return r.offset===-1?{verified:!1,result:r.result}:Tr(r.result,r.result,e)}const cv=Object.freeze(Object.defineProperty({__proto__:null,Any:fn,BaseBlock:Ve,BaseStringBlock:vd,BitString:on,BmpString:Ta,Boolean:Ia,CharacterString:Pa,Choice:Cd,Constructed:et,DATE:kd,DEFAULT_MAX_CONTENT_LENGTH:wg,DEFAULT_MAX_DEPTH:vg,DEFAULT_MAX_NODES:bg,DateTime:xd,Duration:Id,EndOfContent:wd,Enumerated:Oa,GeneralString:La,GeneralizedTime:Ua,GraphicString:Da,HexBlock:or,IA5String:ja,Integer:mo,Null:dn,NumericString:Ba,ObjectIdentifier:Ca,OctetString:nn,Primitive:Rs,PrintableString:Ra,RawData:Uk,RelativeObjectIdentifier:Na,Repeated:Bi,Sequence:Pt,Set:Jt,TIME:Od,TeletexString:Ma,TimeOfDay:Ed,UTCTime:js,UniversalString:$a,Utf8String:kr,ValueBlock:Xe,VideotexString:_a,ViewWriter:ka,VisibleString:_s,compareSchema:Tr,fromBER:Gn,verifySchema:Vk},Symbol.toStringTag,{value:"Module"})),Hk="[object ArrayBuffer]",Fk="[object SharedArrayBuffer]";function uv(t){return Object.prototype.toString.call(t)}function Wk(t){if(ArrayBuffer.isView(t))return!0;if(!t||typeof t!="object")return!1;const e=t;return typeof e.byteOffset=="number"&&typeof e.byteLength=="number"&&Nd(e.buffer)}function lv(t){return uv(t)===Hk}function Kk(t){return typeof SharedArrayBuffer<"u"&&uv(t)===Fk}function Nd(t){return lv(t)||Kk(t)}function Gk(t){return Wk(t)}function Va(t){return Nd(t)||Gk(t)}function dv(t){if(!Va(t))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function pn(t){return dv(t),Nd(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function Nt(t){if(dv(t),lv(t))return t;const e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(pn(t)),e}function qk(t,e,r={}){const n=pn(t),o=pn(e);if(!r.constantTime&&n.byteLength!==o.byteLength)return!1;const s=Math.max(n.byteLength,o.byteLength);let i=n.byteLength^o.byteLength;for(let a=0;a<s;a++)i|=(n[a]??0)^(o[a]??0);return i===0}function fv(t){const e=pn(t);let r="";for(const n of e)r+=String.fromCharCode(n);return r}function pv(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r)&255;return e}function zk(t){return typeof t=="string"}const Yk=/^[0-9a-f]$/i,Xk=[" "," ",`
106
- `,"\r",":","-","."];function Jk(t){return t.separators==="none"?[]:!t.separators||t.separators==="common"?Xk:t.separators}function Zk(t){if(!t)throw new TypeError("Hex separators must be non-empty strings")}function Qk(t,e,r){for(const n of r)if(t.startsWith(n,e))return n}function eE(t){const e=/[A-F]/.test(t),r=/[a-f]/.test(t);return e&&!r?"upper":"lower"}function tE(t){const e=/\r\n|\n/.exec(t);if(e)return e[0]===`\r
361
+ `)}`:`${r} :`}}Pg=rt;Y.Constructed=Pg;rt.NAME="CONSTRUCTED";class Lg extends Je{fromBER(e,r,n){return r}toBER(e){return ir}}Lg.override="EndOfContentValueBlock";var Ug;class Rd extends We{constructor(e={}){super(e,Lg),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Ug=Rd;Y.EndOfContent=Ug;Rd.NAME=Eo;var Hg;class vn extends We{constructor(e={}){super(e,Je),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,r,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,r+n>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):r+n}toBER(e,r){const n=new ArrayBuffer(2);if(!e){const s=new Uint8Array(n);s[0]=5,s[1]=0}return r&&r.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}}Hg=vn;Y.Null=Hg;vn.NAME="NULL";class Vg extends ar(Je){get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...r}={}){super(r),r.valueHex?this.valueHexView=K.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,r,n){const s=K.toUint8Array(e);return Cr(this,s,r,n)?(this.valueHexView=s.subarray(r,r+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Cg.call(this),this.blockLength=n,r+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Vg.NAME="BooleanValueBlock";var Fg;let Pa=class extends We{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Vg),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Fg=Pa;Y.Boolean=Fg;Pa.NAME="BOOLEAN";class Wg extends ar(Pr){constructor({isConstructed:e=!1,...r}={}){super(r),this.isConstructed=e}fromBER(e,r,n,s){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=Pr.prototype.fromBER.call(this,e,r,n,s),o===-1)return o;for(let i=0;i<this.value.length;i++){const a=this.value[i].constructor.NAME;if(a===Eo){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(a!==Og)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(e,r,n),this.blockLength=n;return o}toBER(e,r){return this.isConstructed?Pr.prototype.toBER.call(this,e,r):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Wg.NAME="OctetStringValueBlock";var jd;let ln=class extends We{constructor({idBlock:e={},lenBlock:r={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},Wg),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,r,n,s){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),r;if(!this.valueBlock.isConstructed){const i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(r,r+n);try{if(i.byteLength){const a=s??Vo(),c=Md(i,0,i.byteLength,a);c.offset!==-1&&c.offset===n&&(this.valueBlock.value=[c.result])}}catch{}}return super.fromBER(e,r,n,s)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return rt.prototype.onAsciiEncoding.call(this);const e=this.constructor.NAME,r=ee.ToHex(this.valueBlock.valueHexView);return`${e} : ${r}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;const e=[];for(const r of this.valueBlock.value)r instanceof jd&&e.push(r.valueBlock.valueHexView);return K.concat(e)}};jd=ln;Y.OctetString=jd;ln.NAME=Og;class Kg extends ar(Pr){constructor({unusedBits:e=0,isConstructed:r=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=r,this.blockLength=this.valueHexView.byteLength}fromBER(e,r,n,s){if(!n)return r;let o=-1;if(this.isConstructed){if(o=Pr.prototype.fromBER.call(this,e,r,n,s),o===-1)return o;for(const c of this.value){const u=c.constructor.NAME;if(u===Eo){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(u!==Ng)return this.error="BIT STRING may consists of BIT STRINGs only",-1;const l=c.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}const i=K.toUint8Array(e);if(!Cr(this,i,r,n))return-1;const a=i.subarray(r,r+n);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const c=a.subarray(1);try{if(c.byteLength){const u=s??Vo(),l=Md(c,0,c.byteLength,u);l.offset!==-1&&l.offset===n-1&&(this.value=[l.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,r+n}toBER(e,r){if(this.isConstructed)return Pr.prototype.toBER.call(this,e,r);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){const s=new Uint8Array(1);return s[0]=0,s.buffer}const n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}Kg.NAME="BitStringValueBlock";var Gg;let dn=class extends We{constructor({idBlock:e={},lenBlock:r={},...n}={}){var s,o;(s=n.isConstructed)!==null&&s!==void 0||(n.isConstructed=!!(!((o=n.value)===null||o===void 0)&&o.length)),super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...r,isIndefiniteForm:!!n.isIndefiniteForm},...n},Kg),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,r,n,s){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,r,n,s)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return rt.prototype.onAsciiEncoding.call(this);{const e=[],r=this.valueBlock.valueHexView;for(const i of r)e.push(i.toString(2).padStart(8,"0"));const n=e.join(""),s=this.constructor.NAME,o=n.substring(0,n.length-this.valueBlock.unusedBits);return`${s} : ${o}`}}};Gg=dn;Y.BitString=Gg;dn.NAME=Ng;var qg;function wE(t,e){const r=new Uint8Array([0]),n=new Uint8Array(t),s=new Uint8Array(e);let o=n.slice(0);const i=o.length-1,a=s.slice(0),c=a.length-1;let u=0;const l=c<i?i:c;let d=0;for(let m=l;m>=0;m--,d++)!0===d<a.length?u=o[i-d]+a[c-d]+r[0]:u=o[i-d]+r[0],r[0]=u/10,!0===d>=o.length?o=Tu(new Uint8Array([u%10]),o):o[i-d]=u%10;return r[0]>0&&(o=Tu(r,o)),o}function Qp(t){if(t>=Rs.length)for(let e=Rs.length;e<=t;e++){const r=new Uint8Array([0]);let n=Rs[e-1].slice(0);for(let s=n.length-1;s>=0;s--){const o=new Uint8Array([(n[s]<<1)+r[0]]);r[0]=o[0]/10,n[s]=o[0]%10}r[0]>0&&(n=Tu(r,n)),Rs.push(n)}return Rs[t]}function SE(t,e){let r=0;const n=new Uint8Array(t),s=new Uint8Array(e),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1;let u,l=0;for(let d=c;d>=0;d--,l++)u=o[i-l]-a[c-l]-r,!0===u<0?(r=1,o[i-l]=u+10):(r=0,o[i-l]=u);if(r>0)for(let d=i-c+1;d>=0;d--,l++)if(u=o[i-l]-r,u<0)r=1,o[i-l]=u+10;else{r=0,o[i-l]=u;break}return o.slice()}class Dd extends ar(Je){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Cg.call(this)))}constructor({value:e,...r}={}){super(r),this._valueDec=0,r.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(rE(e))}get valueDec(){return this._valueDec}fromDER(e,r,n,s=0){const o=this.fromBER(e,r,n);if(o===-1)return o;const i=this.valueHexView;return i[0]===0&&(i[1]&128)!==0?this.valueHexView=i.subarray(1):s!==0&&i.length<s&&(s-i.length>1&&(s=i.length+1),this.valueHexView=i.subarray(s-i.length)),o}toDER(e=!1){const r=this.valueHexView;switch(!0){case(r[0]&128)!==0:{const n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(r,1),this.valueHexView=n}break;case(r[0]===0&&(r[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(e)}fromBER(e,r,n){const s=super.fromBER(e,r,n);return s===-1||this.setValueHex(),s}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=this.valueHexView.length*8-1;let r=new Uint8Array(this.valueHexView.length*8/3),n=0,s;const o=this.valueHexView;let i="",a=!1;for(let c=o.byteLength-1;c>=0;c--){s=o[c];for(let u=0;u<8;u++)(s&1)===1&&(n===e?(r=SE(Qp(n),r),i="-"):r=wE(r,Qp(n))),n++,s>>=1}for(let c=0;c<r.length;c++)r[c]&&(a=!0),a&&(i+=Jp.charAt(r[c]));return a===!1&&(i+=Jp.charAt(0)),i}}qg=Dd;Dd.NAME="IntegerValueBlock";Object.defineProperty(qg.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var co;class Ss extends We{constructor(e={}){super(e,Dd),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Vi(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Vi();const r=BigInt(e),n=new Ra,s=r.toString(16).replace(/^-/,""),o=new Uint8Array(ee.FromHex(s));if(r<0){const a=new Uint8Array(o.length+(o[0]&128?1:0));a[0]|=128;const u=BigInt(`0x${ee.ToHex(a)}`)+r,l=K.toUint8Array(ee.FromHex(u.toString(16)));l[0]|=128,n.write(l)}else o[0]&128&&n.write(new Uint8Array([0])),n.write(o);return new co({valueHex:n.final()})}convertToDER(){const e=new co({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new co({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}co=Ss;Y.Integer=co;Ss.NAME="INTEGER";var zg;class La extends Ss{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}zg=La;Y.Enumerated=zg;La.NAME="ENUMERATED";class $u extends ar(Je){constructor({valueDec:e=-1,isFirstSid:r=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=r}fromBER(e,r,n){if(!n)return r;const s=K.toUint8Array(e);if(!Cr(this,s,r,n))return-1;const o=s.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);const i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=as(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}set valueBigInt(e){Vi();let r=BigInt(e).toString(2);for(;r.length%7;)r="0"+r;const n=new Uint8Array(r.length/7);for(let s=0;s<n.length;s++)n[s]=parseInt(r.slice(s*7,s*7+7),2)+(s+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}const r=gn(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",ir;const n=new Uint8Array(r.byteLength);if(!e){const s=new Uint8Array(r),o=r.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n}toString(){let e="";if(this.isHexOnly)e=ee.ToHex(this.valueHexView);else if(this.isFirstSid){let r=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",r-=40):(e="2.",r-=80),e+=r.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}$u.NAME="sidBlock";class Yg extends Je{constructor({value:e=ot,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let s=r;for(;n>0;){const o=new $u;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.value.length===0&&(o.isFirstSid=!0),this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e){const r=[];for(let n=0;n<this.value.length;n++){const s=this.value[n].toBER(e);if(s.byteLength===0)return this.error=this.value[n].error,ir;r.push(s)}return Bd(r)}fromString(e){this.value=[];let r=0,n=0,s="",o=!1;do if(n=e.indexOf(".",r),n===-1?s=e.substring(r):s=e.substring(r,n),r=n+1,o){const i=this.value[0];let a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}const c=parseInt(s,10);if(isNaN(c))return;i.valueDec=c+a,o=!1}else{const i=new $u;if(s>Number.MAX_SAFE_INTEGER){Vi();const a=BigInt(s);i.valueBigInt=a}else if(i.valueDec=parseInt(s,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,o=!0),this.value.push(i)}while(n!==-1)}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),r?(s=`{${s}}`,this.value[n].isFirstSid?e=`2.{${s} - 80}`:e+=s):e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Yg.NAME="ObjectIdentifierValueBlock";var Xg;class Ua extends We{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Yg),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Xg=Ua;Y.ObjectIdentifier=Xg;Ua.NAME="OBJECT IDENTIFIER";class Bu extends ar(Mn){constructor({valueDec:e=0,...r}={}){super(r),this.valueDec=e}fromBER(e,r,n){if(n===0)return r;const s=K.toUint8Array(e);if(!Cr(this,s,r,n))return-1;const o=s.subarray(r,r+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=o[a]&127,this.blockLength++,(o[a]&128)!==0);a++);const i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,(o[this.blockLength-1]&128)!==0?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=as(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),r+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);const s=this.valueHexView,o=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)o[i]=s[i]|128;return o[this.blockLength-1]=s[this.blockLength-1],o.buffer}const r=gn(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",ir;const n=new Uint8Array(r.byteLength);if(!e){const s=new Uint8Array(r),o=r.byteLength-1;for(let i=0;i<o;i++)n[i]=s[i]|128;n[o]=s[o]}return n.buffer}toString(){let e="";return this.isHexOnly?e=ee.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Bu.NAME="relativeSidBlock";class Jg extends Je{constructor({value:e=ot,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let s=r;for(;n>0;){const o=new Bu;if(s=o.fromBER(e,s,n),s===-1)return this.blockLength=0,this.error=o.error,s;this.blockLength+=o.blockLength,n-=o.blockLength,this.value.push(o)}return s}toBER(e,r){const n=[];for(let s=0;s<this.value.length;s++){const o=this.value[s].toBER(e);if(o.byteLength===0)return this.error=this.value[s].error,ir;n.push(o)}return Bd(n)}fromString(e){this.value=[];let r=0,n=0,s="";do{n=e.indexOf(".",r),n===-1?s=e.substring(r):s=e.substring(r,n),r=n+1;const o=new Bu;if(o.valueDec=parseInt(s,10),isNaN(o.valueDec))return!0;this.value.push(o)}while(n!==-1);return!0}toString(){let e="",r=!1;for(let n=0;n<this.value.length;n++){r=this.value[n].isHexOnly;let s=this.value[n].toString();n!==0&&(e=`${e}.`),r&&(s=`{${s}}`),e+=s}return e}toJSON(){const e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let r=0;r<this.value.length;r++)e.sidArray.push(this.value[r].toJSON());return e}}Jg.NAME="RelativeObjectIdentifierValueBlock";var Zg;class Ha extends We{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Jg),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Zg=Ha;Y.RelativeObjectIdentifier=Zg;Ha.NAME="RelativeObjectIdentifier";var Qg;class Vt extends rt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}Qg=Vt;Y.Sequence=Qg;Vt.NAME="SEQUENCE";var ev;let tr=class extends rt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};ev=tr;Y.Set=ev;tr.NAME="SET";class tv extends ar(Je){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=ot}toJSON(){return{...super.toJSON(),value:this.value}}}tv.NAME="StringValueBlock";class rv extends tv{}rv.NAME="SimpleStringValueBlock";class wt extends _d{constructor({...e}={}){super(e,rv)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,K.toUint8Array(e))}fromString(e){const r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e.charCodeAt(s);this.valueBlock.value=e}}wt.NAME="SIMPLE STRING";class nv extends wt{fromBuffer(e){this.valueBlock.valueHexView=K.toUint8Array(e);try{this.valueBlock.value=ee.ToUtf8String(e)}catch(r){this.warnings.push(`Error during "decodeURIComponent": ${r}, using raw string`),this.valueBlock.value=ee.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(ee.FromUtf8String(e)),this.valueBlock.value=e}}nv.NAME="Utf8StringValueBlock";var sv;class Or extends nv{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}sv=Or;Y.Utf8String=sv;Or.NAME="UTF8String";class ov extends wt{fromBuffer(e){this.valueBlock.value=ee.ToUtf16String(e),this.valueBlock.valueHexView=K.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(ee.FromUtf16String(e))}}ov.NAME="BmpStringValueBlock";var iv;class Va extends ov{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}iv=Va;Y.BmpString=iv;Va.NAME="BMPString";class av extends wt{fromBuffer(e){const r=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(r);for(let s=0;s<n.length;s+=4)n[s]=n[s+3],n[s+1]=n[s+2],n[s+2]=0,n[s+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(r))}fromString(e){const r=e.length,n=this.valueBlock.valueHexView=new Uint8Array(r*4);for(let s=0;s<r;s++){const o=gn(e.charCodeAt(s),8),i=new Uint8Array(o);if(i.length>4)continue;const a=4-i.length;for(let c=i.length-1;c>=0;c--)n[s*4+c+a]=i[c]}this.valueBlock.value=e}}av.NAME="UniversalStringValueBlock";var cv;class Fa extends av{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}cv=Fa;Y.UniversalString=cv;Fa.NAME="UniversalString";var uv;class Wa extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}uv=Wa;Y.NumericString=uv;Wa.NAME="NumericString";var lv;class Ka extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}lv=Ka;Y.PrintableString=lv;Ka.NAME="PrintableString";var dv;class Ga extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}dv=Ga;Y.TeletexString=dv;Ga.NAME="TeletexString";var fv;class qa extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}fv=qa;Y.VideotexString=fv;qa.NAME="VideotexString";var pv;class za extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}pv=za;Y.IA5String=pv;za.NAME="IA5String";var hv;class Ya extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}hv=Ya;Y.GraphicString=hv;Ya.NAME="GraphicString";var mv;class Fo extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}mv=Fo;Y.VisibleString=mv;Fo.NAME="VisibleString";var yv;class Xa extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}yv=Xa;Y.GeneralString=yv;Xa.NAME="GeneralString";var gv;class Ja extends wt{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}gv=Ja;Y.CharacterString=gv;Ja.NAME="CharacterString";var vv;class Wo extends Fo{constructor({value:e,valueDate:r,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let s=0;s<e.length;s++)this.valueBlock.valueHexView[s]=e.charCodeAt(s)}r&&(this.fromDate(r),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,K.toUint8Array(e)))}toBuffer(){const e=this.toString(),r=new ArrayBuffer(e.length),n=new Uint8Array(r);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return r}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){const n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(n===null){this.error="Wrong input string for conversion";return}const s=parseInt(n[1],10);s>=50?this.year=1900+s:this.year=2e3+s,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(e="iso"){if(e==="iso"){const r=new Array(7);return r[0]=mt(this.year<2e3?this.year-1900:this.year-2e3,2),r[1]=mt(this.month,2),r[2]=mt(this.day,2),r[3]=mt(this.hour,2),r[4]=mt(this.minute,2),r[5]=mt(this.second,2),r[6]="Z",r.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}vv=Wo;Y.UTCTime=vv;Wo.NAME="UTCTime";var bv;class Za extends Wo{constructor(e={}){var r;super(e),(r=this.millisecond)!==null&&r!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){const e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let r=!1,n="",s="",o=0,i,a=0,c=0;if(e[e.length-1]==="Z")n=e.substring(0,e.length-1),r=!0;else{const d=new Number(e[e.length-1]);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let d=1,m=n.indexOf("+"),p="";if(m===-1&&(m=n.indexOf("-"),d=-1),m!==-1){if(p=n.substring(m+1),n=n.substring(0,m),p.length!==2&&p.length!==4)throw new Error("Wrong input string for conversion");let h=parseInt(p.substring(0,2),10);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");if(a=d*h,p.length===4){if(h=parseInt(p.substring(2,4),10),isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");c=d*h}}}let u=n.indexOf(".");if(u===-1&&(u=n.indexOf(",")),u!==-1){const d=new Number(`0${n.substring(u)}`);if(isNaN(d.valueOf()))throw new Error("Wrong input string for conversion");o=d.valueOf(),s=n.substring(0,u)}else s=n;switch(!0){case s.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,u!==-1)throw new Error("Wrong input string for conversion");break;case s.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let d=60*o;this.minute=Math.floor(d),d=60*(d-this.minute),this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case s.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){let d=60*o;this.second=Math.floor(d),d=1e3*(d-this.second),this.millisecond=Math.floor(d)}break;case s.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,u!==-1){const d=1e3*o;this.millisecond=Math.floor(d)}break;default:throw new Error("Wrong input string for conversion")}const l=i.exec(s);if(l===null)throw new Error("Wrong input string for conversion");for(let d=1;d<l.length;d++)switch(d){case 1:this.year=parseInt(l[d],10);break;case 2:this.month=parseInt(l[d],10);break;case 3:this.day=parseInt(l[d],10);break;case 4:this.hour=parseInt(l[d],10)+a;break;case 5:this.minute=parseInt(l[d],10)+c;break;case 6:this.second=parseInt(l[d],10);break;default:throw new Error("Wrong input string for conversion")}if(r===!1){const d=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=d.getUTCFullYear(),this.month=d.getUTCMonth(),this.day=d.getUTCDay(),this.hour=d.getUTCHours(),this.minute=d.getUTCMinutes(),this.second=d.getUTCSeconds(),this.millisecond=d.getUTCMilliseconds()}}toString(e="iso"){if(e==="iso"){const r=[];return r.push(mt(this.year,4)),r.push(mt(this.month,2)),r.push(mt(this.day,2)),r.push(mt(this.hour,2)),r.push(mt(this.minute,2)),r.push(mt(this.second,2)),this.millisecond!==0&&(r.push("."),r.push(mt(this.millisecond,3))),r.push("Z"),r.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}bv=Za;Y.GeneralizedTime=bv;Za.NAME="GeneralizedTime";var wv;class Pd extends Or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}wv=Pd;Y.DATE=wv;Pd.NAME="DATE";var Sv;class Ld extends Or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}Sv=Ld;Y.TimeOfDay=Sv;Ld.NAME="TimeOfDay";var Av;class Ud extends Or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}Av=Ud;Y.DateTime=Av;Ud.NAME="DateTime";var kv;class Hd extends Or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}kv=Hd;Y.Duration=kv;Hd.NAME="Duration";var Ev;class Vd extends Or{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Ev=Vd;Y.TIME=Ev;Vd.NAME="TIME";class bn{constructor({name:e=ot,optional:r=!1}={}){this.name=e,this.optional=r}}class Fd extends bn{constructor({value:e=[],...r}={}){super(r),this.value=e}}class Fi extends bn{constructor({value:e=new bn,local:r=!1,...n}={}){super(n),this.value=e,this.local=r}}class AE{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=K.toUint8Array(e)}constructor({data:e=ja}={}){this.dataView=K.toUint8Array(e)}fromBER(e,r,n){const s=r+n;return this.dataView=K.toUint8Array(e).subarray(r,s),s}toBER(e){return this.dataView.slice().buffer}}function Rr(t,e,r){if(r instanceof Fd){for(const o of r.value)if(Rr(t,e,o).verified)return{verified:!0,result:t};{const o={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(eu)&&(o.name=r.name),o}}if(r instanceof bn)return r.hasOwnProperty(eu)&&(t[r.name]=e),{verified:!0,result:t};if(!(t instanceof Object))return{verified:!1,result:{error:"Wrong root object"}};if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(!(r instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(oE in r))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(uE in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(lE in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const n=r.idBlock.toBER(!1);if(n.byteLength===0)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(r.idBlock.fromBER(n,0,n.byteLength)===-1)return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(r.idBlock.hasOwnProperty(iE)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==e.idBlock.tagClass)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(aE)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==e.idBlock.tagNumber)return{verified:!1,result:t};if(r.idBlock.hasOwnProperty(cE)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(sE in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==e.idBlock.isHexOnly)return{verified:!1,result:t};if(r.idBlock.isHexOnly){if(!(Zp in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};const o=r.idBlock.valueHexView,i=e.idBlock.valueHexView;if(o.length!==i.length)return{verified:!1,result:t};for(let a=0;a<o.length;a++)if(o[a]!==i[1])return{verified:!1,result:t}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(t[r.name]=e)),r instanceof Y.Constructed){let o=0,i={verified:!1,result:{error:"Unknown error"}},a=r.valueBlock.value.length;if(a>0&&r.valueBlock.value[0]instanceof Fi&&(a=e.valueBlock.value.length),a===0)return{verified:!0,result:t};if(e.valueBlock.value.length===0&&r.valueBlock.value.length!==0){let c=!0;for(let u=0;u<r.valueBlock.value.length;u++)c=c&&(r.valueBlock.value[u].optional||!1);return c?{verified:!0,result:t}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&delete t[r.name]),t.error="Inconsistent object length",{verified:!1,result:t})}for(let c=0;c<a;c++)if(c-o>=e.valueBlock.value.length){if(r.valueBlock.value[c].optional===!1){const u={verified:!1,result:t};return t.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(delete t[r.name],u.name=r.name)),u}}else if(r.valueBlock.value[0]instanceof Fi){if(i=Rr(t,e.valueBlock.value[c],r.valueBlock.value[0].value),i.verified===!1)if(r.valueBlock.value[0].optional)o++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&delete t[r.name]),i;if(eu in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let u={};dE in r.valueBlock.value[0]&&r.valueBlock.value[0].local?u=e:u=t,typeof u[r.valueBlock.value[0].name]>"u"&&(u[r.valueBlock.value[0].name]=[]),u[r.valueBlock.value[0].name].push(e.valueBlock.value[c])}}else if(i=Rr(t,e.valueBlock.value[c-o],r.valueBlock.value[c]),i.verified===!1)if(r.valueBlock.value[c].optional)o++;else return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&delete t[r.name]),i;if(i.verified===!1){const c={verified:!1,result:t};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(delete t[r.name],c.name=r.name)),c}return{verified:!0,result:t}}if(r.primitiveSchema&&Zp in e.valueBlock){const o=Da(e.valueBlock.valueHexView);if(o.offset===-1){const i={verified:!1,result:o.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,ot),r.name&&(delete t[r.name],i.name=r.name)),i}return Rr(t,o.result,r.primitiveSchema)}return{verified:!0,result:t}}function kE(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=Da(K.toUint8Array(t));return r.offset===-1?{verified:!1,result:r.result}:Rr(r.result,r.result,e)}const xv=Object.freeze(Object.defineProperty({__proto__:null,Any:bn,BaseBlock:We,BaseStringBlock:_d,BitString:dn,BmpString:Va,Boolean:Pa,CharacterString:Ja,Choice:Fd,Constructed:rt,DATE:Pd,DEFAULT_MAX_CONTENT_LENGTH:Dg,DEFAULT_MAX_DEPTH:Rg,DEFAULT_MAX_NODES:jg,DateTime:Ud,Duration:Hd,EndOfContent:Rd,Enumerated:La,GeneralString:Xa,GeneralizedTime:Za,GraphicString:Ya,HexBlock:ar,IA5String:za,Integer:Ss,Null:vn,NumericString:Wa,ObjectIdentifier:Ua,OctetString:ln,Primitive:Ho,PrintableString:Ka,RawData:AE,RelativeObjectIdentifier:Ha,Repeated:Fi,Sequence:Vt,Set:tr,TIME:Vd,TeletexString:Ga,TimeOfDay:Ld,UTCTime:Wo,UniversalString:Fa,Utf8String:Or,ValueBlock:Je,VideotexString:qa,ViewWriter:Ra,VisibleString:Fo,compareSchema:Rr,fromBER:es,verifySchema:kE},Symbol.toStringTag,{value:"Module"})),EE="[object ArrayBuffer]",xE="[object SharedArrayBuffer]";function Iv(t){return Object.prototype.toString.call(t)}function IE(t){if(ArrayBuffer.isView(t))return!0;if(!t||typeof t!="object")return!1;const e=t;return typeof e.byteOffset=="number"&&typeof e.byteLength=="number"&&Wd(e.buffer)}function Cv(t){return Iv(t)===EE}function CE(t){return typeof SharedArrayBuffer<"u"&&Iv(t)===xE}function Wd(t){return Cv(t)||CE(t)}function OE(t){return IE(t)}function Qa(t){return Wd(t)||OE(t)}function Ov(t){if(!Qa(t))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function wn(t){return Ov(t),Wd(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function $t(t){if(Ov(t),Cv(t))return t;const e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(wn(t)),e}function NE(t,e,r={}){const n=wn(t),s=wn(e);if(!r.constantTime&&n.byteLength!==s.byteLength)return!1;const o=Math.max(n.byteLength,s.byteLength);let i=n.byteLength^s.byteLength;for(let a=0;a<o;a++)i|=(n[a]??0)^(s[a]??0);return i===0}function Nv(t){const e=wn(t);let r="";for(const n of e)r+=String.fromCharCode(n);return r}function Tv(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r)&255;return e}function TE(t){return typeof t=="string"}const $E=/^[0-9a-f]$/i,BE=[" "," ",`
362
+ `,"\r",":","-","."];function _E(t){return t.separators==="none"?[]:!t.separators||t.separators==="common"?BE:t.separators}function ME(t){if(!t)throw new TypeError("Hex separators must be non-empty strings")}function RE(t,e,r){for(const n of r)if(t.startsWith(n,e))return n}function jE(t){const e=/[A-F]/.test(t),r=/[a-f]/.test(t);return e&&!r?"upper":"lower"}function DE(t){const e=/\r\n|\n/.exec(t);if(e)return e[0]===`\r
107
363
  `?`\r
108
364
  `:`
109
- `}function Dp(t){return t.replace(/[^0-9a-f]/gi,"")}function rE(t){const e=t.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;const r=e.filter((i,a)=>a%2===0),n=e.filter((i,a)=>a%2===1),o=n[0];if(!o||n.some(i=>i!==o)||r.some(i=>i.length===0||i.length%2!==0))return;const s=r[0]?.length??0;if(s&&!r.slice(0,-1).some(i=>i.length!==s)&&!((r[r.length-1]?.length??0)>s))return{size:s/2,separator:o}}function nE(t){const e=t.trim(),r=/^0x/i.test(e)?"0x":"",n=r?e.slice(2):e,o=tE(n),s=n.split(/\r\n|\n/).filter(u=>u.length>0),i=s[0]?.trim()??"",a=rE(i),c={case:eE(e),prefix:r};if(a&&(c.group=a),o&&s.length>1){const u=Dp(s[0]??"").length/2;u>0&&s.slice(0,-1).every(d=>Dp(d).length/2===u)&&(c.line={bytesPerLine:u,separator:o})}return c}function oE(t,e){const r=e.allowPrefix??!0,n=[...Jk(e)].sort((a,c)=>c.length-a.length);for(const a of n)Zk(a);let o=t.trim();if(/^0x/i.test(o)){if(!r)throw new TypeError("Hexadecimal text must not include a 0x prefix");o=o.slice(2)}let s="",i=!1;for(let a=0;a<o.length;){const c=o[a]??"";if(Yk.test(c)){s+=c,i=!1,a+=1;continue}const u=Qk(o,a,n);if(!u)throw new TypeError("Input is not valid hexadecimal text");if(e.strict&&(i||s.length===0))throw new TypeError("Hexadecimal text contains misplaced separators");i=!0,a+=u.length}if(e.strict&&i&&s.length>0)throw new TypeError("Hexadecimal text must not end with a separator");if(s.length%2!==0){if(!e.allowOddLength)throw new TypeError("Hexadecimal text must contain an even number of characters");s=`0${s}`}return s.toLowerCase()}function Lp(t,e){if(!e)return t.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");const r=[];for(let n=0;n<t.length;n+=e.size)r.push(t.slice(n,n+e.size).join(""));return r.join(e.separator)}function Ha(t,e={}){return oE(t,e)}function sE(t,e={}){if(typeof t!="string")return!1;try{return Ha(t,e),!0}catch{return!1}}function Fa(t,e={}){const r=pn(t),n=e.case??"lower",o=Array.from(r,i=>{const a=i.toString(16).padStart(2,"0");return n==="upper"?a.toUpperCase():a});let s="";if(e.line){const i=e.line.bytesPerLine;if(!Number.isInteger(i)||i<1)throw new RangeError("Hex bytesPerLine must be a positive integer");const a=e.line.separator??`
110
- `,c=[];for(let u=0;u<o.length;u+=i)c.push(Lp(o.slice(u,u+i),e.group));s=c.join(a)}else s=Lp(o,e.group);return`${e.prefix??""}${s}`}function hv(t,e={}){const r=Ha(t,e),n=new Uint8Array(r.length/2);for(let o=0;o<r.length;o+=2)n[o/2]=Number.parseInt(r.slice(o,o+2),16);return n}function iE(t,e={}){const r=Ha(t,e);return{bytes:hv(r),format:nE(t),normalized:r}}function aE(t,e){return Fa(t,e)}function cE(t){return new TextEncoder().encode(t)}function uE(t){return new TextDecoder("utf-8",{fatal:!1}).decode(pn(t))}function mv(t,e={}){const r=new ArrayBuffer(t.length*2),n=new DataView(r);for(let o=0;o<t.length;o++)n.setUint16(o*2,t.charCodeAt(o),e.littleEndian??!1);return new Uint8Array(r)}function yv(t,e={}){const r=Nt(t),n=new DataView(r);let o="";for(let s=0;s<r.byteLength;s+=2)o+=String.fromCharCode(n.getUint16(s,e.littleEndian??!1));return o}const lE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function gv(){return globalThis.Buffer}function Wa(t){return t.replace(/[\n\r\t ]/g,"")}function dE(t){const e=t.length%4;return e?t+"=".repeat(4-e):t}function Td(t){if(typeof t!="string")return!1;const e=Wa(t);return e===""||lE.test(e)}function vv(t,e){const r=pn(t),n=gv();return n?n.from(r).toString("base64"):btoa(fv(r))}function bv(t,e){const r=Wa(t);if(!Td(r))throw new TypeError("Input is not valid Base64 text");const n=gv();return n?new Uint8Array(n.from(r,"base64")):pv(atob(r))}const gs={encode:vv,decode:bv,is:Td,normalize:Wa,pad:dE},fE=/^[A-Za-z0-9_-]*$/;function $d(t){return t.replace(/[\n\r\t ]/g,"")}function wv(t){return typeof t=="string"&&fE.test($d(t))}function pE(t,e){return gs.encode(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function hE(t,e){const r=$d(t);if(!wv(r))throw new TypeError("Input is not valid Base64Url text");return gs.decode(gs.pad(r.replace(/-/g,"+").replace(/_/g,"/")))}const mE=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,Pp=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function Av(t){if(!mE.test(t))throw new TypeError(`Invalid PEM label '${t}'`)}function yE(t,e){const r=[];for(let n=0;n<t.length;n+=e)r.push(t.slice(n,n+e));return r}function gE(t){const r=t.trim().replace(/\r\n/g,`
365
+ `}function eh(t){return t.replace(/[^0-9a-f]/gi,"")}function PE(t){const e=t.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(e.length<3)return;const r=e.filter((i,a)=>a%2===0),n=e.filter((i,a)=>a%2===1),s=n[0];if(!s||n.some(i=>i!==s)||r.some(i=>i.length===0||i.length%2!==0))return;const o=r[0]?.length??0;if(o&&!r.slice(0,-1).some(i=>i.length!==o)&&!((r[r.length-1]?.length??0)>o))return{size:o/2,separator:s}}function LE(t){const e=t.trim(),r=/^0x/i.test(e)?"0x":"",n=r?e.slice(2):e,s=DE(n),o=n.split(/\r\n|\n/).filter(u=>u.length>0),i=o[0]?.trim()??"",a=PE(i),c={case:jE(e),prefix:r};if(a&&(c.group=a),s&&o.length>1){const u=eh(o[0]??"").length/2;u>0&&o.slice(0,-1).every(l=>eh(l).length/2===u)&&(c.line={bytesPerLine:u,separator:s})}return c}function UE(t,e){const r=e.allowPrefix??!0,n=[..._E(e)].sort((a,c)=>c.length-a.length);for(const a of n)ME(a);let s=t.trim();if(/^0x/i.test(s)){if(!r)throw new TypeError("Hexadecimal text must not include a 0x prefix");s=s.slice(2)}let o="",i=!1;for(let a=0;a<s.length;){const c=s[a]??"";if($E.test(c)){o+=c,i=!1,a+=1;continue}const u=RE(s,a,n);if(!u)throw new TypeError("Input is not valid hexadecimal text");if(e.strict&&(i||o.length===0))throw new TypeError("Hexadecimal text contains misplaced separators");i=!0,a+=u.length}if(e.strict&&i&&o.length>0)throw new TypeError("Hexadecimal text must not end with a separator");if(o.length%2!==0){if(!e.allowOddLength)throw new TypeError("Hexadecimal text must contain an even number of characters");o=`0${o}`}return o.toLowerCase()}function th(t,e){if(!e)return t.join("");if(!Number.isInteger(e.size)||e.size<1)throw new RangeError("Hex group size must be a positive integer");const r=[];for(let n=0;n<t.length;n+=e.size)r.push(t.slice(n,n+e.size).join(""));return r.join(e.separator)}function ec(t,e={}){return UE(t,e)}function HE(t,e={}){if(typeof t!="string")return!1;try{return ec(t,e),!0}catch{return!1}}function tc(t,e={}){const r=wn(t),n=e.case??"lower",s=Array.from(r,i=>{const a=i.toString(16).padStart(2,"0");return n==="upper"?a.toUpperCase():a});let o="";if(e.line){const i=e.line.bytesPerLine;if(!Number.isInteger(i)||i<1)throw new RangeError("Hex bytesPerLine must be a positive integer");const a=e.line.separator??`
366
+ `,c=[];for(let u=0;u<s.length;u+=i)c.push(th(s.slice(u,u+i),e.group));o=c.join(a)}else o=th(s,e.group);return`${e.prefix??""}${o}`}function $v(t,e={}){const r=ec(t,e),n=new Uint8Array(r.length/2);for(let s=0;s<r.length;s+=2)n[s/2]=Number.parseInt(r.slice(s,s+2),16);return n}function VE(t,e={}){const r=ec(t,e);return{bytes:$v(r),format:LE(t),normalized:r}}function FE(t,e){return tc(t,e)}function WE(t){return new TextEncoder().encode(t)}function KE(t){return new TextDecoder("utf-8",{fatal:!1}).decode(wn(t))}function Bv(t,e={}){const r=new ArrayBuffer(t.length*2),n=new DataView(r);for(let s=0;s<t.length;s++)n.setUint16(s*2,t.charCodeAt(s),e.littleEndian??!1);return new Uint8Array(r)}function _v(t,e={}){const r=$t(t),n=new DataView(r);let s="";for(let o=0;o<r.byteLength;o+=2)s+=String.fromCharCode(n.getUint16(o,e.littleEndian??!1));return s}const GE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function Mv(){return globalThis.Buffer}function rc(t){return t.replace(/[\n\r\t ]/g,"")}function qE(t){const e=t.length%4;return e?t+"=".repeat(4-e):t}function Kd(t){if(typeof t!="string")return!1;const e=rc(t);return e===""||GE.test(e)}function Rv(t,e){const r=wn(t),n=Mv();return n?n.from(r).toString("base64"):btoa(Nv(r))}function jv(t,e){const r=rc(t);if(!Kd(r))throw new TypeError("Input is not valid Base64 text");const n=Mv();return n?new Uint8Array(n.from(r,"base64")):Tv(atob(r))}const xo={encode:Rv,decode:jv,is:Kd,normalize:rc,pad:qE},zE=/^[A-Za-z0-9_-]*$/;function Gd(t){return t.replace(/[\n\r\t ]/g,"")}function Dv(t){return typeof t=="string"&&zE.test(Gd(t))}function YE(t,e){return xo.encode(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function XE(t,e){const r=Gd(t);if(!Dv(r))throw new TypeError("Input is not valid Base64Url text");return xo.decode(xo.pad(r.replace(/-/g,"+").replace(/_/g,"/")))}const JE=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,rh=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function Pv(t){if(!JE.test(t))throw new TypeError(`Invalid PEM label '${t}'`)}function ZE(t,e){const r=[];for(let n=0;n<t.length;n+=e)r.push(t.slice(n,n+e));return r}function QE(t){const r=t.trim().replace(/\r\n/g,`
111
367
  `).split(`
112
- `).map(s=>s.trim()).filter(Boolean),n={};let o=0;for(;o<r.length;o++){const s=r[o],i=s.indexOf(":");if(i<=0)break;n[s.slice(0,i).trim()]=s.slice(i+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:r.slice(o),base64Text:r.slice(o).join("")}}function vE(t){return/\r\n/.test(t)?`\r
368
+ `).map(o=>o.trim()).filter(Boolean),n={};let s=0;for(;s<r.length;s++){const o=r[s],i=o.indexOf(":");if(i<=0)break;n[o.slice(0,i).trim()]=o.slice(i+1).trim()}return{headers:Object.keys(n).length?n:void 0,base64Lines:r.slice(s),base64Text:r.slice(s).join("")}}function ex(t){return/\r\n/.test(t)?`\r
113
369
  `:`
114
- `}function Sv(t,e={}){const r=[],n=e.label;let o;for(Pp.lastIndex=0;o=Pp.exec(t);){const s=o[1].trim();if(n&&s!==n)continue;Av(s);const i=gE(o[2]);r.push({label:s,data:gs.decode(i.base64Text),headers:i.headers,lineLength:i.base64Lines[0]?.length??64,newline:vE(o[0])})}if(e.strict&&r.length===0)throw new TypeError(n?`No PEM block with label '${n}' was found`:"No PEM blocks were found");return r}function Bd(t,e,r={}){Av(t);const n=r.lineLength??64;if(!Number.isInteger(n)||n<1)throw new RangeError("PEM lineLength must be a positive integer");const o=r.newline??`
115
- `,s=[`-----BEGIN ${t}-----`];if(r.headers){for(const[i,a]of Object.entries(r.headers))s.push(`${i}: ${a}`);s.push("")}return s.push(...yE(gs.encode(e),n)),s.push(`-----END ${t}-----`),`${s.join(o)}${o}`}function bE(t,e={}){return Sv(t,e).map(({lineLength:r,newline:n,...o})=>o)}function wE(t,e){const[r]=bE(t,{label:e,strict:!0});return r.data}function AE(t,e={}){const[r]=Sv(t,{...e,strict:!0}),n={label:r.label,headers:r.headers,lineLength:r.lineLength,newline:r.newline};return{bytes:r.data,format:n,normalized:Bd(r.label,r.data,n)}}function SE(t,e){return Bd(e.label,t,e)}const kE={name:"pem",encode:(t,e)=>{if(!e?.label)throw new TypeError("PEM label is required");return Bd(e.label,t,e)},decode:(t,e)=>wE(t,e?.label),format:SE,is:t=>typeof t=="string"&&/-----BEGIN [^-]+-----/.test(t),parse:AE};function zt(t){return t.trim().toLowerCase()}function EE(t){return t instanceof Error?t:new Error(String(t))}function Up(t,e,r){for(const n of[r.name,...r.aliases??[]])t.delete(zt(n));e.delete(zt(r.name))}function Hc(t,e,r){const n=t[r];if(typeof n!="function")throw new Error(`Converter '${e}' does not support ${r}()`);return n}function xE(t,e,r){const n=zt(r.name||t),o=e.trim();if(!o)return 0;let s=!1;r.is&&(s=r.is(e));let i=!1;try{r.decode(e),i=!0}catch{i=!1}if(!s&&!i)return 0;switch(n){case"pem":return/-----BEGIN [^-]+-----/.test(e)?1:0;case"hex":{const a=o.replace(/^0x/i,"").replace(/[\s:.-]/g,"");return!a||/[^0-9a-f]/i.test(a)||a.length%2!==0?0:/^0x/i.test(o)||/[:\s.-]/.test(o)?.95:/[a-f]/.test(o)||/[A-F]/.test(o)?.8:.45}case"base64url":return/[-_]/.test(o)?.95:/=/.test(o)?.1:.6;case"base64":return/[+/=]/.test(o)?.9:.55;case"binary":case"utf8":case"utf16be":case"utf16le":return 0;default:return s&&i?.75:.5}}function IE(t=[]){const e=new Map,r=new Set,n={register(o,s={}){if(!o.name||!zt(o.name))throw new TypeError("Converter name is required");const i=[...new Set([o.name,...o.aliases??[]].map(zt))],a=new Set;for(const c of i){const u=e.get(c);if(u){if(!s.override)throw new Error(`Converter '${c}' is already registered`);a.add(u)}}for(const c of a)Up(e,r,c);for(const c of i)e.set(c,o);return r.add(zt(o.name)),this},unregister(o){const s=e.get(zt(o));return s?(Up(e,r,s),!0):!1},has(o){return e.has(zt(o))},get(o){const s=e.get(zt(o));if(!s)throw new Error(`Converter '${o}' is not registered`);return s},list(){return[...r].map(o=>this.get(o))},encode(o,s,i){return this.get(o).encode(s,i)},decode(o,s,i){return this.get(o).decode(s,i)},tryDecode(o,s,i){try{return{ok:!0,bytes:this.decode(o,s,i)}}catch(a){return{ok:!1,error:EE(a)}}},normalize(o,s,i){const a=this.get(o);return Hc(a,o,"normalize").call(a,s,i)},parse(o,s,i){const a=this.get(o);return Hc(a,o,"parse").call(a,s,i)},format(o,s,i){const a=this.get(o);return Hc(a,o,"format").call(a,s,i)},transcode(o,s){const i=this.decode(s.from,o,s.fromOptions);return this.encode(s.to,i,s.toOptions)},detect(o,s={}){const i=s.formats?.length?s.formats.map(c=>String(c)):this.list().map(c=>c.name).filter(c=>!["binary","utf8","utf16be","utf16le"].includes(zt(c))),a=new Map;for(const c of i){const u=this.get(c),d=xE(c,o,u);if(d<=0)continue;const l=u.name,m=a.get(l);(!m||d>m.confidence)&&a.set(l,{format:l,confidence:d})}return[...a.values()].sort((c,u)=>u.confidence-c.confidence)}};for(const o of t)n.register(o);return n}const OE={name:"binary",aliases:["latin1"],encode:fv,decode:pv,is:zk},CE={name:"hex",encode:Fa,decode:hv,format:aE,is:sE,normalize:Ha,parse:iE},NE={name:"base64",aliases:["b64"],encode:vv,decode:bv,is:Td,normalize:Wa},TE={name:"base64url",aliases:["base64-url","b64url"],encode:pE,decode:hE,is:wv,normalize:$d},$E={name:"utf8",aliases:["utf-8"],encode:t=>uE(t),decode:t=>cE(t),is:t=>typeof t=="string"},BE={name:"utf16be",aliases:["utf16","utf-16","utf-16be"],encode:t=>yv(t),decode:t=>mv(t),is:t=>typeof t=="string"},RE={name:"utf16le",aliases:["utf-16le","ucs2","usc2"],encode:t=>yv(t,{littleEndian:!0}),decode:t=>mv(t,{littleEndian:!0}),is:t=>typeof t=="string"},ME=[OE,CE,NE,TE,$E,BE,RE,kE];IE(ME);var R;(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})(R||(R={}));var b;(function(t){t[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null",t[t.RelativeObjectIdentifier=28]="RelativeObjectIdentifier"})(b||(b={}));class Ka{unusedBits=0;value=new ArrayBuffer(0);constructor(e,r=0){if(e)if(typeof e=="number")this.fromNumber(e);else if(Va(e))this.unusedBits=r,this.value=Nt(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof on))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=Nt(e.valueBlock.valueHex),this}toASN(){return new on({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new on({name:e})}toNumber(){let e="";const r=new Uint8Array(this.value);for(const n of r)e+=n.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let r=e.toString(2);const n=r.length+7>>3;this.unusedBits=(n<<3)-r.length;const o=new Uint8Array(n);r=r.padStart(n<<3,"0").split("").reverse().join("");let s=0;for(;s<n;)o[s]=parseInt(r.slice(s<<3,(s<<3)+8),2),s++;this.value=o.buffer}}class he{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):Va(e)?this.buffer=Nt(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof nn))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=Nt(e.valueBlock.valueHex),this}toASN(){return new nn({valueHex:this.buffer})}toSchema(e){return new nn({name:e})}}const _E={fromASN:t=>t instanceof dn?null:Nt(t.valueBeforeDecodeView),toASN:t=>{if(t===null)return new dn;const e=Gn(t);if(e.result.error)throw new Error(e.result.error);return e.result}},jE={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new mo({value:+t})},DE={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new Oa({value:t})},xe={fromASN:t=>Nt(t.valueBlock.valueHexView),toASN:t=>new mo({valueHex:t})},LE={fromASN:t=>Nt(t.valueBlock.valueHexView),toASN:t=>new on({valueHex:t})},PE={fromASN:t=>t.valueBlock.toString(),toASN:t=>new Ca({value:t})},UE={fromASN:t=>t.valueBlock.toString(),toASN:t=>new Na({value:t})},VE={fromASN:t=>t.valueBlock.value,toASN:t=>new Ia({value:t})},Ri={fromASN:t=>Nt(t.valueBlock.valueHexView),toASN:t=>new nn({valueHex:t})},HE={fromASN:t=>new he(t.getValue()),toASN:t=>t.toASN()};function Tt(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}const kv=Tt(kr),FE=Tt(Ta),WE=Tt($a),KE=Tt(Ba),GE=Tt(Ra),qE=Tt(Ma),zE=Tt(_a),YE=Tt(ja),XE=Tt(Da),JE=Tt(_s),ZE=Tt(La),QE=Tt(Pa),ex={fromASN:t=>t.toDate(),toASN:t=>new js({valueDate:t})},tx={fromASN:t=>t.toDate(),toASN:t=>new Ua({valueDate:t})},rx={fromASN:()=>null,toASN:()=>new dn};function rs(t){switch(t){case b.Any:return _E;case b.BitString:return LE;case b.BmpString:return FE;case b.Boolean:return VE;case b.CharacterString:return QE;case b.Enumerated:return DE;case b.GeneralString:return ZE;case b.GeneralizedTime:return tx;case b.GraphicString:return XE;case b.IA5String:return YE;case b.Integer:return jE;case b.Null:return rx;case b.NumericString:return KE;case b.ObjectIdentifier:return PE;case b.RelativeObjectIdentifier:return UE;case b.OctetString:return Ri;case b.PrintableString:return GE;case b.TeletexString:return qE;case b.UTCTime:return ex;case b.UniversalString:return WE;case b.Utf8String:return kv;case b.VideotexString:return zE;case b.VisibleString:return JE;default:return null}}function fr(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:fr(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function Ev(t){if(t){const e=Object.getPrototypeOf(t);return e?.prototype?.constructor===Array?!0:Ev(e)}return!1}function nx(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let o=0;o<t.byteLength;o++)if(r[o]!==n[o])return!1;return!0}class ox{items=new WeakMap;has(e){return this.items.has(e)}get(e,r=!1){const n=this.items.get(e);if(!n)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(r&&!n.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){const r=this.get(e);r.schema||(r.schema=this.create(e,!0))}createDefault(e){const r={type:R.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(r,n),r.items=Object.assign({},r.items,n.items)),r}create(e,r){const n=this.items.get(e)||this.createDefault(e),o=[];for(const s in n.items){const i=n.items[s],a=r?s:"";let c;if(typeof i.type=="number"){const d=b[i.type],l=cv[d];if(!l)throw new Error(`Cannot get ASN1 class by name '${d}'`);c=new l({name:a})}else fr(i.type)?c=new i.type().toSchema(a):i.optional?this.get(i.type).type===R.Choice?c=new fn({name:a}):(c=this.create(i.type,!1),c.name=a):c=new fn({name:a});const u=!!i.optional||i.defaultValue!==void 0;if(i.repeated){c.name="";const d=i.repeated==="set"?Jt:Pt;c=new d({name:"",value:[new Bi({name:a,value:c})]})}if(i.context!==null&&i.context!==void 0)if(i.implicit)if(typeof i.type=="number"||fr(i.type)){const d=i.repeated?et:Rs;o.push(new d({name:a,optional:u,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);const d=!!i.repeated;let l=d?c:this.get(i.type,!0).schema;l="valueBlock"in l?l.valueBlock.value:l.value,o.push(new et({name:d?"":a,optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:l}))}else o.push(new et({optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:[c]}));else c.optional=u,o.push(c)}switch(n.type){case R.Sequence:return new Pt({value:o,name:""});case R.Set:return new Jt({value:o,name:""});case R.Choice:return new Cd({value:o,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,r){return this.items.set(e,r),this}findParentSchema(e){const r=Object.getPrototypeOf(e);return r?this.items.get(r)||this.findParentSchema(r):null}}const Fe=new ox,j=t=>e=>{let r;Fe.has(e)?r=Fe.get(e):(r=Fe.createDefault(e),Fe.set(e,r)),Object.assign(r,t)},y=t=>(e,r)=>{let n;Fe.has(e.constructor)?n=Fe.get(e.constructor):(n=Fe.createDefault(e.constructor),Fe.set(e.constructor,n));const o=Object.assign({},t);if(typeof o.type=="number"&&!o.converter){const s=rs(t.type);if(!s)throw new Error(`Cannot get default converter for property '${r}' of ${e.constructor.name}`);o.converter=s}o.raw=t.raw,n.items[r]=o};class To extends Error{schemas=[]}class sx{static parse(e,r,n){const o=Gn(Nt(e),n?.berOptions);if(o.result.error)throw new Error(o.result.error);return this.fromASN(o.result,r,n)}static fromASN(e,r,n){try{if(fr(r))return new r().fromASN(e);const o=Fe.get(r);Fe.cache(r);let s=o.schema;const i=this.handleChoiceTypes(e,o,r,s,n);if(i?.result)return i.result;i?.targetSchema&&(s=i.targetSchema);const a=this.handleSequenceTypes(e,o,r,s),c=new r;return Ev(r)?this.handleArrayTypes(e,o,r,n):(this.processSchemaItems(o,a,c,n),c)}catch(o){throw o instanceof To&&o.schemas.push(r.name),o}}static handleChoiceTypes(e,r,n,o,s){if(e.constructor===et&&r.type===R.Choice&&e.idBlock.tagClass===3)for(const i in r.items){const a=r.items[i];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&Fe.has(a.type)){const c=Fe.get(a.type);if(c&&c.type===R.Sequence){const u=new Pt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in u.valueBlock){u.valueBlock.value=e.valueBlock.value;const d=this.fromASN(u,a.type,s),l=new n;return l[i]=d,{result:l}}}}}else if(e.constructor===et&&r.type!==R.Choice){const i=new et({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:r.schema.valueBlock.value});for(const a in r.items)delete e[a];return{targetSchema:i}}return null}static handleSequenceTypes(e,r,n,o){if(r.type===R.Sequence){const s=Tr({},e,o);if(!s.verified)throw new To(`Data does not match to ${n.name} ASN1 schema.${s.result.error?` ${s.result.error}`:""}`);return s}else{const s=Tr({},e,o);if(!s.verified)throw new To(`Data does not match to ${n.name} ASN1 schema.${s.result.error?` ${s.result.error}`:""}`);return s}}static processRepeatedField(e,r,n){let o=e.slice(r);if(o.length===1&&o[0].constructor.name==="Sequence"){const s=o[0];s.valueBlock&&s.valueBlock.value&&Array.isArray(s.valueBlock.value)&&(o=s.valueBlock.value)}if(typeof n.type=="number"){const s=rs(n.type);if(!s)throw new Error(`No converter for ASN.1 type ${n.type}`);return o.filter(i=>i&&i.valueBlock).map(i=>{try{return s.fromASN(i)}catch{return}}).filter(i=>i!==void 0)}else return o.filter(s=>s&&s.valueBlock).map(s=>{try{return this.fromASN(s,n.type)}catch{return}}).filter(s=>s!==void 0)}static processPrimitiveField(e,r){const n=rs(r.type);if(!n)throw new Error(`No converter for ASN.1 type ${r.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&Fe.has(e.type)&&Fe.get(e.type).type===R.Choice}static processOptionalChoiceField(e,r){try{return{processed:!0,value:this.fromASN(e,r.type)}}catch(n){if(n instanceof To&&/Wrong values for Choice type/.test(n.message))return{processed:!1};throw n}}static handleArrayTypes(e,r,n,o){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const s=r.itemType;if(typeof s=="number"){const i=rs(s);if(!i)throw new Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,a=>i.fromASN(a))}else return n.from(e.valueBlock.value,i=>this.fromASN(i,s,o))}static processSchemaItems(e,r,n,o){for(const s in e.items){const i=r.result[s];if(!i)continue;const a=e.items[s],c=a.type;let u;typeof c=="number"||fr(c)?u=this.processPrimitiveSchemaItem(i,a,c,o):u=this.processComplexSchemaItem(i,a,c,o),u&&typeof u=="object"&&"value"in u&&"raw"in u?(n[s]=u.value,n[`${s}Raw`]=u.raw):n[s]=u}}static processPrimitiveSchemaItem(e,r,n,o){const s=r.converter??(fr(n)?new n:null);if(!s)throw new Error("Converter is empty");return r.repeated?this.processRepeatedPrimitiveItem(e,r,s,o):this.processSinglePrimitiveItem(e,r,n,s,o)}static processRepeatedPrimitiveItem(e,r,n,o){if(r.implicit){const s=r.repeated==="sequence"?Pt:Jt,i=new s;i.valueBlock=e.valueBlock;const a=Gn(i.toBER(!1),o?.berOptions);if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const c=a.result.valueBlock.value;return Array.from(c,u=>n.fromASN(u))}else return Array.from(e,s=>n.fromASN(s))}static processSinglePrimitiveItem(e,r,n,o,s){let i=e;if(r.implicit){let a;if(fr(n))a=new n().toSchema("");else{const c=b[n],u=cv[c];if(!u)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new u}a.valueBlock=i.valueBlock,i=Gn(a.toBER(!1),s?.berOptions).result}return o.fromASN(i)}static processComplexSchemaItem(e,r,n,o){if(r.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,s=>this.fromASN(s,n,o))}else{const s=this.handleImplicitTagging(e,r,n);if(this.isOptionalChoiceField(r))try{return this.fromASN(s,n,o)}catch(i){if(i instanceof To&&/Wrong values for Choice type/.test(i.message))return;throw i}else{const i=this.fromASN(s,n,o);return r.raw?{value:i,raw:e.valueBeforeDecodeView}:i}}}static handleImplicitTagging(e,r,n){if(r.implicit&&typeof r.context=="number"){const o=Fe.get(n);if(o.type===R.Sequence){const s=new Pt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in s.valueBlock)return s.valueBlock.value=e.valueBlock.value,s}else if(o.type===R.Set){const s=new Jt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in s.valueBlock)return s.valueBlock.value=e.valueBlock.value,s}}return e}}class Rd{static serialize(e){return e instanceof Ve?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&fr(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");const r=e.constructor,n=Fe.get(r);Fe.cache(r);let o=[];if(n.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof n.itemType=="number"){const i=rs(n.itemType);if(!i)throw new Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);o=e.map(a=>i.toASN(a))}else o=e.map(i=>this.toAsnItem({type:n.itemType},"[]",r,i))}else for(const i in n.items){const a=n.items[i],c=e[i];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&nx(this.serialize(a.defaultValue),this.serialize(c)))continue;const u=Rd.toAsnItem(a,i,r,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||fr(a.type))){const d={};d.valueHex=u instanceof dn?Nt(u.valueBeforeDecodeView):u.valueBlock.toBER(),o.push(new Rs({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...d}))}else o.push(new et({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:u.valueBlock.value}));else o.push(new et({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[u]}));else a.repeated?o=o.concat(u):o.push(u)}let s;switch(n.type){case R.Sequence:s=new Pt({value:o});break;case R.Set:s=new Jt({value:o});break;case R.Choice:if(!o[0])throw new Error(`Schema '${r.name}' has wrong data. Choice cannot be empty.`);s=o[0];break}return s}static toAsnItem(e,r,n,o){let s;if(typeof e.type=="number"){const i=e.converter;if(!i)throw new Error(`Property '${r}' doesn't have converter for type ${b[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(o))throw new TypeError("Parameter 'objProp' should be type of Array.");const a=Array.from(o,u=>i.toASN(u)),c=e.repeated==="sequence"?Pt:Jt;s=new c({value:a})}else s=i.toASN(o)}else if(e.repeated){if(!Array.isArray(o))throw new TypeError("Parameter 'objProp' should be type of Array.");const i=Array.from(o,c=>this.toASN(c)),a=e.repeated==="sequence"?Pt:Jt;s=new a({value:i})}else s=this.toASN(o);return s}}class pe extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(const r of e)this.push(r)}}}class H{static serialize(e){return Rd.serialize(e)}static parse(e,r,n){return sx.parse(e,r,n)}static toString(e,r){const n=Va(e)?Nt(e):H.serialize(e),o=Gn(n,r?.berOptions);if(o.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${o.result.error}`);return o.result.toString()}}function f(t,e,r,n){var o=arguments.length,s=o<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(s=(o<3?i(s):o>3?i(e,r,s):i(e,r))||s);return o>3&&s&&Object.defineProperty(e,r,s),s}function oe(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function ke(t,e,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(t,r):o?o.value=r:e.set(t,r),r}class Vp{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const r=e.split(".");if(r.length!==4)throw new Error("Invalid IPv4 address");return r.map(n=>{const o=parseInt(n,10);if(isNaN(o)||o<0||o>255)throw new Error("Invalid IPv4 address part");return o})}static parseIPv6(e){const n=this.expandIPv6(e).split(":");if(n.length!==8)throw new Error("Invalid IPv6 address");return n.reduce((o,s)=>{const i=parseInt(s,16);if(isNaN(i)||i<0||i>65535)throw new Error("Invalid IPv6 address part");return o.push(i>>8&255),o.push(i&255),o},[])}static expandIPv6(e){if(!e.includes("::"))return e;const r=e.split("::");if(r.length>2)throw new Error("Invalid IPv6 address");const n=r[0]?r[0].split(":"):[],o=r[1]?r[1].split(":"):[],s=8-(n.length+o.length);if(s<0)throw new Error("Invalid IPv6 address");return[...n,...Array(s).fill("0"),...o].join(":")}static formatIPv6(e){const r=[];for(let n=0;n<16;n+=2)r.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(r.join(":"))}static compressIPv6(e){const r=e.split(":");let n=-1,o=0,s=-1,i=0;for(let a=0;a<r.length;a++)r[a]==="0"?(s===-1&&(s=a),i++):(i>o&&(n=s,o=i),s=-1,i=0);if(i>o&&(n=s,o=i),o>1){const a=r.slice(0,n).join(":"),c=r.slice(n+o).join(":");return`${a}::${c}`}return e}static parseCIDR(e){const[r,n]=e.split("/"),o=parseInt(n,10);if(this.isIPv4(r)){if(o<0||o>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(r),o]}else{if(o<0||o>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(r),o]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;const r=parseInt(e.slice(8),16).toString(2).split("").reduce((o,s)=>o+ +s,0);let n=e.slice(0,8).replace(/(.{2})/g,o=>`${parseInt(o,16)}.`);return n=n.slice(0,-1),`${n}/${r}`}static toString(e){const r=new Uint8Array(e);if(r.length===4)return Array.from(r).join(".");if(r.length===16)return this.formatIPv6(r);if(r.length===8||r.length===32){const n=r.length/2,o=r.slice(0,n),s=r.slice(n);if(r.every(c=>c===0))return r.length===8?"0.0.0.0/0":"::/0";const a=s.reduce((c,u)=>c+(u.toString(2).match(/1/g)||[]).length,0);return r.length===8?`${Array.from(o).join(".")}/${a}`:`${this.formatIPv6(o)}/${a}`}return this.decodeIP(Fa(e))}static fromString(e){if(e.includes("/")){const[n,o]=this.parseCIDR(e),s=new Uint8Array(n.length);let i=o;for(let c=0;c<s.length;c++)i>=8?(s[c]=255,i-=8):i>0&&(s[c]=255<<8-i,i=0);const a=new Uint8Array(n.length*2);return a.set(n,0),a.set(s,n.length),a.buffer}const r=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(r).buffer}}var vu,bu,wu;let Ge=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};f([y({type:b.TeletexString})],Ge.prototype,"teletexString",void 0);f([y({type:b.PrintableString})],Ge.prototype,"printableString",void 0);f([y({type:b.UniversalString})],Ge.prototype,"universalString",void 0);f([y({type:b.Utf8String})],Ge.prototype,"utf8String",void 0);f([y({type:b.BmpString})],Ge.prototype,"bmpString",void 0);Ge=f([j({type:R.Choice})],Ge);let to=class extends Ge{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Fa(this.anyValue):super.toString())}};f([y({type:b.IA5String})],to.prototype,"ia5String",void 0);f([y({type:b.Any})],to.prototype,"anyValue",void 0);to=f([j({type:R.Choice})],to);class Ga{type="";value=new to;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Ga.prototype,"type",void 0);f([y({type:to})],Ga.prototype,"value",void 0);let ro=vu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,vu.prototype)}};ro=vu=f([j({type:R.Set,itemType:Ga})],ro);let Au=bu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,bu.prototype)}};Au=bu=f([j({type:R.Sequence,itemType:ro})],Au);let Re=wu=class extends Au{constructor(e){super(e),Object.setPrototypeOf(this,wu.prototype)}};Re=wu=f([j({type:R.Sequence})],Re);const ix={fromASN:t=>Vp.toString(Ri.fromASN(t)),toASN:t=>Ri.toASN(Vp.fromString(t))};class vs{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],vs.prototype,"typeId",void 0);f([y({type:b.Any,context:0})],vs.prototype,"value",void 0);class Md{nameAssigner;partyName=new Ge;constructor(e={}){Object.assign(this,e)}}f([y({type:Ge,optional:!0,context:0,implicit:!0})],Md.prototype,"nameAssigner",void 0);f([y({type:Ge,context:1,implicit:!0})],Md.prototype,"partyName",void 0);let ie=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};f([y({type:vs,context:0,implicit:!0})],ie.prototype,"otherName",void 0);f([y({type:b.IA5String,context:1,implicit:!0})],ie.prototype,"rfc822Name",void 0);f([y({type:b.IA5String,context:2,implicit:!0})],ie.prototype,"dNSName",void 0);f([y({type:b.Any,context:3,implicit:!0})],ie.prototype,"x400Address",void 0);f([y({type:Re,context:4,implicit:!1})],ie.prototype,"directoryName",void 0);f([y({type:Md,context:5})],ie.prototype,"ediPartyName",void 0);f([y({type:b.IA5String,context:6,implicit:!0})],ie.prototype,"uniformResourceIdentifier",void 0);f([y({type:b.OctetString,context:7,implicit:!0,converter:ix})],ie.prototype,"iPAddress",void 0);f([y({type:b.ObjectIdentifier,context:8,implicit:!0})],ie.prototype,"registeredID",void 0);ie=f([j({type:R.Choice})],ie);const _d="1.3.6.1.5.5.7",ax=`${_d}.1`,yo=`${_d}.3`,qa=`${_d}.48`,Hp=`${qa}.1`,Fp=`${qa}.2`,Wp=`${qa}.3`,Kp=`${qa}.5`,Er="2.5.29";var Su;const ku=`${ax}.1`;class Ds{accessMethod="";accessLocation=new ie;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Ds.prototype,"accessMethod",void 0);f([y({type:ie})],Ds.prototype,"accessLocation",void 0);let Hn=Su=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Su.prototype)}};Hn=Su=f([j({type:R.Sequence,itemType:Ds})],Hn);const Eu=`${Er}.35`;class jd extends he{}class Qr{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}}f([y({type:jd,context:0,optional:!0,implicit:!0})],Qr.prototype,"keyIdentifier",void 0);f([y({type:ie,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Qr.prototype,"authorityCertIssuer",void 0);f([y({type:b.Integer,context:2,optional:!0,implicit:!0,converter:xe})],Qr.prototype,"authorityCertSerialNumber",void 0);const xv=`${Er}.19`;class Mi{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Boolean,defaultValue:!1})],Mi.prototype,"cA",void 0);f([y({type:b.Integer,optional:!0})],Mi.prototype,"pathLenConstraint",void 0);var xu;let Ye=xu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,xu.prototype)}};Ye=xu=f([j({type:R.Sequence,itemType:ie})],Ye);var Iu;let Gp=Iu=class extends Ye{constructor(e){super(e),Object.setPrototypeOf(this,Iu.prototype)}};Gp=Iu=f([j({type:R.Sequence})],Gp);var Ou;const Iv=`${Er}.32`;let yr=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};f([y({type:b.IA5String})],yr.prototype,"ia5String",void 0);f([y({type:b.VisibleString})],yr.prototype,"visibleString",void 0);f([y({type:b.BmpString})],yr.prototype,"bmpString",void 0);f([y({type:b.Utf8String})],yr.prototype,"utf8String",void 0);yr=f([j({type:R.Choice})],yr);class Dd{organization=new yr;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}}f([y({type:yr})],Dd.prototype,"organization",void 0);f([y({type:b.Integer,repeated:"sequence"})],Dd.prototype,"noticeNumbers",void 0);class Ld{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}}f([y({type:Dd,optional:!0})],Ld.prototype,"noticeRef",void 0);f([y({type:yr,optional:!0})],Ld.prototype,"explicitText",void 0);let _i=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};f([y({type:b.IA5String})],_i.prototype,"cPSuri",void 0);f([y({type:Ld})],_i.prototype,"userNotice",void 0);_i=f([j({type:R.Choice})],_i);class Pd{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Pd.prototype,"policyQualifierId",void 0);f([y({type:b.Any})],Pd.prototype,"qualifier",void 0);class za{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],za.prototype,"policyIdentifier",void 0);f([y({type:Pd,repeated:"sequence",optional:!0})],za.prototype,"policyQualifiers",void 0);let ji=Ou=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ou.prototype)}};ji=Ou=f([j({type:R.Sequence,itemType:za})],ji);let Di=class{value;constructor(e=0){this.value=e}};f([y({type:b.Integer})],Di.prototype,"value",void 0);Di=f([j({type:R.Choice})],Di);let qp=class extends Di{};qp=f([j({type:R.Choice})],qp);var Cu;const Nu=`${Er}.31`;var Mt;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(Mt||(Mt={}));class Ov extends Ka{toJSON(){const e=[],r=this.toNumber();return r&Mt.aACompromise&&e.push("aACompromise"),r&Mt.affiliationChanged&&e.push("affiliationChanged"),r&Mt.cACompromise&&e.push("cACompromise"),r&Mt.certificateHold&&e.push("certificateHold"),r&Mt.cessationOfOperation&&e.push("cessationOfOperation"),r&Mt.keyCompromise&&e.push("keyCompromise"),r&Mt.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&Mt.superseded&&e.push("superseded"),r&Mt.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let hn=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};f([y({type:ie,context:0,repeated:"sequence",implicit:!0})],hn.prototype,"fullName",void 0);f([y({type:ro,context:1,implicit:!0})],hn.prototype,"nameRelativeToCRLIssuer",void 0);hn=f([j({type:R.Choice})],hn);class go{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}}f([y({type:hn,context:0,optional:!0})],go.prototype,"distributionPoint",void 0);f([y({type:Ov,context:1,optional:!0,implicit:!0})],go.prototype,"reasons",void 0);f([y({type:ie,context:2,optional:!0,repeated:"sequence",implicit:!0})],go.prototype,"cRLIssuer",void 0);let qn=Cu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Cu.prototype)}};qn=Cu=f([j({type:R.Sequence,itemType:go})],qn);var Tu;let zp=Tu=class extends qn{constructor(e){super(e),Object.setPrototypeOf(this,Tu.prototype)}};zp=Tu=f([j({type:R.Sequence,itemType:go})],zp);class Qe{static ONLY=!1;distributionPoint;onlyContainsUserCerts=Qe.ONLY;onlyContainsCACerts=Qe.ONLY;onlySomeReasons;indirectCRL=Qe.ONLY;onlyContainsAttributeCerts=Qe.ONLY;constructor(e={}){Object.assign(this,e)}}f([y({type:hn,context:0,optional:!0})],Qe.prototype,"distributionPoint",void 0);f([y({type:b.Boolean,context:1,defaultValue:Qe.ONLY,implicit:!0})],Qe.prototype,"onlyContainsUserCerts",void 0);f([y({type:b.Boolean,context:2,defaultValue:Qe.ONLY,implicit:!0})],Qe.prototype,"onlyContainsCACerts",void 0);f([y({type:Ov,context:3,optional:!0,implicit:!0})],Qe.prototype,"onlySomeReasons",void 0);f([y({type:b.Boolean,context:4,defaultValue:Qe.ONLY,implicit:!0})],Qe.prototype,"indirectCRL",void 0);f([y({type:b.Boolean,context:5,defaultValue:Qe.ONLY,implicit:!0})],Qe.prototype,"onlyContainsAttributeCerts",void 0);var ns;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(ns||(ns={}));let $u=class{reason=ns.unspecified;constructor(e=ns.unspecified){this.reason=e}toJSON(){return ns[this.reason]}toString(){return this.toJSON()}};f([y({type:b.Enumerated})],$u.prototype,"reason",void 0);$u=f([j({type:R.Choice})],$u);var Bu;const Cv=`${Er}.37`;let Li=Bu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Bu.prototype)}};Li=Bu=f([j({type:R.Sequence,itemType:b.ObjectIdentifier})],Li);const cx=`${yo}.1`,ux=`${yo}.2`,lx=`${yo}.3`,dx=`${yo}.4`,fx=`${yo}.8`,px=`${yo}.9`;let Ru=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};f([y({type:b.Integer,converter:xe})],Ru.prototype,"value",void 0);Ru=f([j({type:R.Choice})],Ru);let Mu=class{value=new Date;constructor(e){e&&(this.value=e)}};f([y({type:b.GeneralizedTime})],Mu.prototype,"value",void 0);Mu=f([j({type:R.Choice})],Mu);var _u;const Nv=`${Er}.18`;let Yp=_u=class extends Ye{constructor(e){super(e),Object.setPrototypeOf(this,_u.prototype)}};Yp=_u=f([j({type:R.Sequence})],Yp);const Tv=`${Er}.15`;var _t;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(_t||(_t={}));class Fc extends Ka{toJSON(){const e=this.toNumber(),r=[];return e&_t.cRLSign&&r.push("crlSign"),e&_t.dataEncipherment&&r.push("dataEncipherment"),e&_t.decipherOnly&&r.push("decipherOnly"),e&_t.digitalSignature&&r.push("digitalSignature"),e&_t.encipherOnly&&r.push("encipherOnly"),e&_t.keyAgreement&&r.push("keyAgreement"),e&_t.keyCertSign&&r.push("keyCertSign"),e&_t.keyEncipherment&&r.push("keyEncipherment"),e&_t.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}}var ju;class Ya{base=new ie;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}}f([y({type:ie})],Ya.prototype,"base",void 0);f([y({type:b.Integer,context:0,defaultValue:0,implicit:!0})],Ya.prototype,"minimum",void 0);f([y({type:b.Integer,context:1,optional:!0,implicit:!0})],Ya.prototype,"maximum",void 0);let Pi=ju=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,ju.prototype)}};Pi=ju=f([j({type:R.Sequence,itemType:Ya})],Pi);class $v{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}}f([y({type:Pi,context:0,optional:!0,implicit:!0})],$v.prototype,"permittedSubtrees",void 0);f([y({type:Pi,context:1,optional:!0,implicit:!0})],$v.prototype,"excludedSubtrees",void 0);class Bv{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,context:0,implicit:!0,optional:!0,converter:xe})],Bv.prototype,"requireExplicitPolicy",void 0);f([y({type:b.Integer,context:1,implicit:!0,optional:!0,converter:xe})],Bv.prototype,"inhibitPolicyMapping",void 0);var Du;class Ud{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Ud.prototype,"issuerDomainPolicy",void 0);f([y({type:b.ObjectIdentifier})],Ud.prototype,"subjectDomainPolicy",void 0);let Xp=Du=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Du.prototype)}};Xp=Du=f([j({type:R.Sequence,itemType:Ud})],Xp);var Lu;const Rv=`${Er}.17`;let Pu=Lu=class extends Ye{constructor(e){super(e),Object.setPrototypeOf(this,Lu.prototype)}};Pu=Lu=f([j({type:R.Sequence})],Pu);let gr=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],gr.prototype,"type",void 0);f([y({type:b.Any,repeated:"set"})],gr.prototype,"values",void 0);var Uu;let Jp=Uu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Uu.prototype)}};Jp=Uu=f([j({type:R.Sequence,itemType:gr})],Jp);const Mv=`${Er}.14`;class Mr extends jd{}class _v{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}}f([y({type:b.GeneralizedTime,context:0,implicit:!0,optional:!0})],_v.prototype,"notBefore",void 0);f([y({type:b.GeneralizedTime,context:1,implicit:!0,optional:!0})],_v.prototype,"notAfter",void 0);var os;(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(os||(os={}));class jv extends Ka{toJSON(){const e=[],r=this.toNumber();return r&os.pKIXCertificate&&e.push("pKIXCertificate"),r&os.newExtensions&&e.push("newExtensions"),r&os.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class Dv{entrustVers="";entrustInfoFlags=new jv;constructor(e={}){Object.assign(this,e)}}f([y({type:b.GeneralString})],Dv.prototype,"entrustVers",void 0);f([y({type:jv})],Dv.prototype,"entrustInfoFlags",void 0);var Vu;let Zp=Vu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Vu.prototype)}};Zp=Vu=f([j({type:R.Sequence,itemType:Ds})],Zp);class W{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof W&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&qk(e.parameters,this.parameters)||e.parameters===this.parameters)}}f([y({type:b.ObjectIdentifier})],W.prototype,"algorithm",void 0);f([y({type:b.Any,optional:!0})],W.prototype,"parameters",void 0);class Ot{algorithm=new W;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:W})],Ot.prototype,"algorithm",void 0);f([y({type:b.BitString})],Ot.prototype,"subjectPublicKey",void 0);let We=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){const r=new Date(e);r.setMilliseconds(0),r.getUTCFullYear()>2049?this.generalTime=r:this.utcTime=r}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};f([y({type:b.UTCTime})],We.prototype,"utcTime",void 0);f([y({type:b.GeneralizedTime})],We.prototype,"generalTime",void 0);We=f([j({type:R.Choice})],We);class Ls{notBefore=new We(new Date);notAfter=new We(new Date);constructor(e){e&&(this.notBefore=new We(e.notBefore),this.notAfter=new We(e.notAfter))}}f([y({type:We})],Ls.prototype,"notBefore",void 0);f([y({type:We})],Ls.prototype,"notAfter",void 0);var Hu;let Vt=class Lv{static CRITICAL=!1;extnID="";critical=Lv.CRITICAL;extnValue=new he;constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],Vt.prototype,"extnID",void 0);f([y({type:b.Boolean,defaultValue:Vt.CRITICAL})],Vt.prototype,"critical",void 0);f([y({type:he})],Vt.prototype,"extnValue",void 0);let Dr=Hu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Hu.prototype)}};Dr=Hu=f([j({type:R.Sequence,itemType:Vt})],Dr);var mn;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(mn||(mn={}));class At{version=mn.v1;serialNumber=new ArrayBuffer(0);signature=new W;issuer=new Re;validity=new Ls;subject=new Re;subjectPublicKeyInfo=new Ot;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,context:0,defaultValue:mn.v1})],At.prototype,"version",void 0);f([y({type:b.Integer,converter:xe})],At.prototype,"serialNumber",void 0);f([y({type:W})],At.prototype,"signature",void 0);f([y({type:Re})],At.prototype,"issuer",void 0);f([y({type:Ls})],At.prototype,"validity",void 0);f([y({type:Re})],At.prototype,"subject",void 0);f([y({type:Ot})],At.prototype,"subjectPublicKeyInfo",void 0);f([y({type:b.BitString,context:1,implicit:!0,optional:!0})],At.prototype,"issuerUniqueID",void 0);f([y({type:b.BitString,context:2,implicit:!0,optional:!0})],At.prototype,"subjectUniqueID",void 0);f([y({type:Dr,context:3,optional:!0})],At.prototype,"extensions",void 0);class yn{tbsCertificate=new At;tbsCertificateRaw;signatureAlgorithm=new W;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:At,raw:!0})],yn.prototype,"tbsCertificate",void 0);f([y({type:W})],yn.prototype,"signatureAlgorithm",void 0);f([y({type:b.BitString})],yn.prototype,"signatureValue",void 0);class Xa{userCertificate=new ArrayBuffer(0);revocationDate=new We;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,converter:xe})],Xa.prototype,"userCertificate",void 0);f([y({type:We})],Xa.prototype,"revocationDate",void 0);f([y({type:Vt,optional:!0,repeated:"sequence"})],Xa.prototype,"crlEntryExtensions",void 0);class xr{version;signature=new W;issuer=new Re;thisUpdate=new We;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,optional:!0})],xr.prototype,"version",void 0);f([y({type:W})],xr.prototype,"signature",void 0);f([y({type:Re})],xr.prototype,"issuer",void 0);f([y({type:We})],xr.prototype,"thisUpdate",void 0);f([y({type:We,optional:!0})],xr.prototype,"nextUpdate",void 0);f([y({type:Xa,repeated:"sequence",optional:!0})],xr.prototype,"revokedCertificates",void 0);f([y({type:Vt,optional:!0,context:0,repeated:"sequence"})],xr.prototype,"crlExtensions",void 0);class Vd{tbsCertList=new xr;tbsCertListRaw;signatureAlgorithm=new W;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:xr,raw:!0})],Vd.prototype,"tbsCertList",void 0);f([y({type:W})],Vd.prototype,"signatureAlgorithm",void 0);f([y({type:b.BitString})],Vd.prototype,"signature",void 0);class vo{issuer=new Re;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Re})],vo.prototype,"issuer",void 0);f([y({type:b.Integer,converter:xe})],vo.prototype,"serialNumber",void 0);let no=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:Mr,context:0,implicit:!0})],no.prototype,"subjectKeyIdentifier",void 0);f([y({type:vo})],no.prototype,"issuerAndSerialNumber",void 0);no=f([j({type:R.Choice})],no);var vr;(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(vr||(vr={}));let bs=class extends W{};bs=f([j({type:R.Sequence})],bs);let Ui=class extends W{};Ui=f([j({type:R.Sequence})],Ui);let Qt=class extends W{};Qt=f([j({type:R.Sequence})],Qt);let Vi=class extends W{};Vi=f([j({type:R.Sequence})],Vi);let Qp=class extends W{};Qp=f([j({type:R.Sequence})],Qp);let Fu=class extends W{};Fu=f([j({type:R.Sequence})],Fu);let bo=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],bo.prototype,"attrType",void 0);f([y({type:b.Any,repeated:"set"})],bo.prototype,"attrValues",void 0);var Wu;class sr{version=vr.v0;sid=new no;digestAlgorithm=new bs;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Ui;signature=new he;unsignedAttrs;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],sr.prototype,"version",void 0);f([y({type:no})],sr.prototype,"sid",void 0);f([y({type:bs})],sr.prototype,"digestAlgorithm",void 0);f([y({type:bo,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],sr.prototype,"signedAttrs",void 0);f([y({type:Ui})],sr.prototype,"signatureAlgorithm",void 0);f([y({type:he})],sr.prototype,"signature",void 0);f([y({type:bo,repeated:"set",context:1,implicit:!0,optional:!0})],sr.prototype,"unsignedAttrs",void 0);let Hi=Wu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Wu.prototype)}};Hi=Wu=f([j({type:R.Set,itemType:sr})],Hi);let eh=class extends sr{};eh=f([j({type:R.Sequence})],eh);let th=class extends We{};th=f([j({type:R.Choice})],th);class Hd{acIssuer=new ie;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}}f([y({type:ie})],Hd.prototype,"acIssuer",void 0);f([y({type:b.Integer})],Hd.prototype,"acSerial",void 0);f([y({type:gr,repeated:"sequence"})],Hd.prototype,"attrs",void 0);var Ku;let Fi=Ku=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ku.prototype)}};Fi=Ku=f([j({type:R.Sequence,itemType:b.ObjectIdentifier})],Fi);class Ja{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,optional:!0})],Ja.prototype,"pathLenConstraint",void 0);f([y({type:Fi,implicit:!0,context:0,optional:!0})],Ja.prototype,"permittedAttrs",void 0);f([y({type:Fi,implicit:!0,context:1,optional:!0})],Ja.prototype,"excludedAttrs",void 0);f([y({type:b.Boolean,defaultValue:!0})],Ja.prototype,"permitUnSpecified",void 0);class Cn{issuer=new Ye;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Ye})],Cn.prototype,"issuer",void 0);f([y({type:b.Integer,converter:xe})],Cn.prototype,"serial",void 0);f([y({type:b.BitString,optional:!0})],Cn.prototype,"issuerUID",void 0);var Gu;(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(Gu||(Gu={}));class Nn{digestedObjectType=Gu.publicKey;otherObjectTypeID;digestAlgorithm=new W;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.Enumerated})],Nn.prototype,"digestedObjectType",void 0);f([y({type:b.ObjectIdentifier,optional:!0})],Nn.prototype,"otherObjectTypeID",void 0);f([y({type:W})],Nn.prototype,"digestAlgorithm",void 0);f([y({type:b.BitString})],Nn.prototype,"objectDigest",void 0);class Za{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:Ye,optional:!0})],Za.prototype,"issuerName",void 0);f([y({type:Cn,context:0,implicit:!0,optional:!0})],Za.prototype,"baseCertificateID",void 0);f([y({type:Nn,context:1,implicit:!0,optional:!0})],Za.prototype,"objectDigestInfo",void 0);let oo=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};f([y({type:ie,repeated:"sequence"})],oo.prototype,"v1Form",void 0);f([y({type:Za,context:0,implicit:!0})],oo.prototype,"v2Form",void 0);oo=f([j({type:R.Choice})],oo);class Qa{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}}f([y({type:b.GeneralizedTime})],Qa.prototype,"notBeforeTime",void 0);f([y({type:b.GeneralizedTime})],Qa.prototype,"notAfterTime",void 0);class Ps{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:Cn,implicit:!0,context:0,optional:!0})],Ps.prototype,"baseCertificateID",void 0);f([y({type:Ye,implicit:!0,context:1,optional:!0})],Ps.prototype,"entityName",void 0);f([y({type:Nn,implicit:!0,context:2,optional:!0})],Ps.prototype,"objectDigestInfo",void 0);var qu;(function(t){t[t.v2=1]="v2"})(qu||(qu={}));class Ft{version=qu.v2;holder=new Ps;issuer=new oo;signature=new W;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new Qa;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Ft.prototype,"version",void 0);f([y({type:Ps})],Ft.prototype,"holder",void 0);f([y({type:oo})],Ft.prototype,"issuer",void 0);f([y({type:W})],Ft.prototype,"signature",void 0);f([y({type:b.Integer,converter:xe})],Ft.prototype,"serialNumber",void 0);f([y({type:Qa})],Ft.prototype,"attrCertValidityPeriod",void 0);f([y({type:gr,repeated:"sequence"})],Ft.prototype,"attributes",void 0);f([y({type:b.BitString,optional:!0})],Ft.prototype,"issuerUniqueID",void 0);f([y({type:Dr,optional:!0})],Ft.prototype,"extensions",void 0);class ec{acinfo=new Ft;signatureAlgorithm=new W;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Ft})],ec.prototype,"acinfo",void 0);f([y({type:W})],ec.prototype,"signatureAlgorithm",void 0);f([y({type:b.BitString})],ec.prototype,"signatureValue",void 0);var Wi;(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(Wi||(Wi={}));class zu extends Ka{}class Fd{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier,implicit:!0,context:0})],Fd.prototype,"type",void 0);f([y({type:b.Any,implicit:!0,context:1})],Fd.prototype,"value",void 0);class Wd{policyId="";classList=new zu(Wi.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Wd.prototype,"policyId",void 0);f([y({type:zu,defaultValue:new zu(Wi.unclassified)})],Wd.prototype,"classList",void 0);f([y({type:Fd,repeated:"set"})],Wd.prototype,"securityCategories",void 0);class tc{cotets;oid;string;constructor(e={}){Object.assign(this,e)}}f([y({type:he})],tc.prototype,"cotets",void 0);f([y({type:b.ObjectIdentifier})],tc.prototype,"oid",void 0);f([y({type:b.Utf8String})],tc.prototype,"string",void 0);class Pv{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}}f([y({type:Ye,implicit:!0,context:0,optional:!0})],Pv.prototype,"policyAuthority",void 0);f([y({type:tc,repeated:"sequence"})],Pv.prototype,"values",void 0);var Yu;class rc{targetCertificate=new Cn;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:Cn})],rc.prototype,"targetCertificate",void 0);f([y({type:ie,optional:!0})],rc.prototype,"targetName",void 0);f([y({type:Nn,optional:!0})],rc.prototype,"certDigestInfo",void 0);let so=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};f([y({type:ie,context:0,implicit:!0})],so.prototype,"targetName",void 0);f([y({type:ie,context:1,implicit:!0})],so.prototype,"targetGroup",void 0);f([y({type:rc,context:2,implicit:!0})],so.prototype,"targetCert",void 0);so=f([j({type:R.Choice})],so);let Xu=Yu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Yu.prototype)}};Xu=Yu=f([j({type:R.Sequence,itemType:so})],Xu);var Ju;let rh=Ju=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ju.prototype)}};rh=Ju=f([j({type:R.Sequence,itemType:Xu})],rh);class Uv{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}}f([y({type:Ye,implicit:!0,context:0,optional:!0})],Uv.prototype,"roleAuthority",void 0);f([y({type:ie,implicit:!0,context:1})],Uv.prototype,"roleName",void 0);class Kd{service=new ie;ident=new ie;authInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:ie})],Kd.prototype,"service",void 0);f([y({type:ie})],Kd.prototype,"ident",void 0);f([y({type:he,optional:!0})],Kd.prototype,"authInfo",void 0);var Zu;class Gd{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Gd.prototype,"otherCertFormat",void 0);f([y({type:b.Any})],Gd.prototype,"otherCert",void 0);let io=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};f([y({type:yn})],io.prototype,"certificate",void 0);f([y({type:ec,context:2,implicit:!0})],io.prototype,"v2AttrCert",void 0);f([y({type:Gd,context:3,implicit:!0})],io.prototype,"other",void 0);io=f([j({type:R.Choice})],io);let Ki=Zu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Zu.prototype)}};Ki=Zu=f([j({type:R.Set,itemType:io})],Ki);class wo{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],wo.prototype,"contentType",void 0);f([y({type:b.Any,context:0})],wo.prototype,"content",void 0);let ws=class{single;any;constructor(e={}){Object.assign(this,e)}};f([y({type:he})],ws.prototype,"single",void 0);f([y({type:b.Any})],ws.prototype,"any",void 0);ws=f([j({type:R.Choice})],ws);class nc{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],nc.prototype,"eContentType",void 0);f([y({type:ws,context:0,optional:!0})],nc.prototype,"eContent",void 0);let As=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};f([y({type:he,context:0,implicit:!0,optional:!0})],As.prototype,"value",void 0);f([y({type:he,converter:HE,context:0,implicit:!0,optional:!0,repeated:"sequence"})],As.prototype,"constructedValue",void 0);As=f([j({type:R.Choice})],As);class Us{contentType="";contentEncryptionAlgorithm=new Vi;encryptedContent;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Us.prototype,"contentType",void 0);f([y({type:Vi})],Us.prototype,"contentEncryptionAlgorithm",void 0);f([y({type:As,optional:!0})],Us.prototype,"encryptedContent",void 0);class oc{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],oc.prototype,"keyAttrId",void 0);f([y({type:b.Any,optional:!0})],oc.prototype,"keyAttr",void 0);var Qu;class sc{subjectKeyIdentifier=new Mr;date;other;constructor(e={}){Object.assign(this,e)}}f([y({type:Mr})],sc.prototype,"subjectKeyIdentifier",void 0);f([y({type:b.GeneralizedTime,optional:!0})],sc.prototype,"date",void 0);f([y({type:oc,optional:!0})],sc.prototype,"other",void 0);let ao=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:sc,context:0,implicit:!0,optional:!0})],ao.prototype,"rKeyId",void 0);f([y({type:vo,optional:!0})],ao.prototype,"issuerAndSerialNumber",void 0);ao=f([j({type:R.Choice})],ao);class qd{rid=new ao;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:ao})],qd.prototype,"rid",void 0);f([y({type:he})],qd.prototype,"encryptedKey",void 0);let Gi=Qu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Qu.prototype)}};Gi=Qu=f([j({type:R.Sequence,itemType:qd})],Gi);class zd{algorithm=new W;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:W})],zd.prototype,"algorithm",void 0);f([y({type:b.BitString})],zd.prototype,"publicKey",void 0);let gn=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:Mr,context:0,implicit:!0,optional:!0})],gn.prototype,"subjectKeyIdentifier",void 0);f([y({type:zd,context:1,implicit:!0,optional:!0})],gn.prototype,"originatorKey",void 0);f([y({type:vo,optional:!0})],gn.prototype,"issuerAndSerialNumber",void 0);gn=f([j({type:R.Choice})],gn);class Ao{version=vr.v3;originator=new gn;ukm;keyEncryptionAlgorithm=new Qt;recipientEncryptedKeys=new Gi;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Ao.prototype,"version",void 0);f([y({type:gn,context:0})],Ao.prototype,"originator",void 0);f([y({type:he,context:1,optional:!0})],Ao.prototype,"ukm",void 0);f([y({type:Qt})],Ao.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:Gi})],Ao.prototype,"recipientEncryptedKeys",void 0);let co=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:Mr,context:0,implicit:!0})],co.prototype,"subjectKeyIdentifier",void 0);f([y({type:vo})],co.prototype,"issuerAndSerialNumber",void 0);co=f([j({type:R.Choice})],co);class Vs{version=vr.v0;rid=new co;keyEncryptionAlgorithm=new Qt;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Vs.prototype,"version",void 0);f([y({type:co})],Vs.prototype,"rid",void 0);f([y({type:Qt})],Vs.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:he})],Vs.prototype,"encryptedKey",void 0);class Hs{keyIdentifier=new he;date;other;constructor(e={}){Object.assign(this,e)}}f([y({type:he})],Hs.prototype,"keyIdentifier",void 0);f([y({type:b.GeneralizedTime,optional:!0})],Hs.prototype,"date",void 0);f([y({type:oc,optional:!0})],Hs.prototype,"other",void 0);class Fs{version=vr.v4;kekid=new Hs;keyEncryptionAlgorithm=new Qt;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Fs.prototype,"version",void 0);f([y({type:Hs})],Fs.prototype,"kekid",void 0);f([y({type:Qt})],Fs.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:he})],Fs.prototype,"encryptedKey",void 0);class Ws{version=vr.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Qt;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Ws.prototype,"version",void 0);f([y({type:Fu,context:0,optional:!0})],Ws.prototype,"keyDerivationAlgorithm",void 0);f([y({type:Qt})],Ws.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:he})],Ws.prototype,"encryptedKey",void 0);class Yd{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Yd.prototype,"oriType",void 0);f([y({type:b.Any})],Yd.prototype,"oriValue",void 0);let Lr=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};f([y({type:Vs,optional:!0})],Lr.prototype,"ktri",void 0);f([y({type:Ao,context:1,implicit:!0,optional:!0})],Lr.prototype,"kari",void 0);f([y({type:Fs,context:2,implicit:!0,optional:!0})],Lr.prototype,"kekri",void 0);f([y({type:Ws,context:3,implicit:!0,optional:!0})],Lr.prototype,"pwri",void 0);f([y({type:Yd,context:4,implicit:!0,optional:!0})],Lr.prototype,"ori",void 0);Lr=f([j({type:R.Choice})],Lr);var el;let qi=el=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,el.prototype)}};qi=el=f([j({type:R.Set,itemType:Lr})],qi);var tl;class ic{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],ic.prototype,"otherRevInfoFormat",void 0);f([y({type:b.Any})],ic.prototype,"otherRevInfo",void 0);let zi=class{other=new ic;constructor(e={}){Object.assign(this,e)}};f([y({type:ic,context:1,implicit:!0})],zi.prototype,"other",void 0);zi=f([j({type:R.Choice})],zi);let Yi=tl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,tl.prototype)}};Yi=tl=f([j({type:R.Set,itemType:zi})],Yi);class Xd{certs;crls;constructor(e={}){Object.assign(this,e)}}f([y({type:Ki,context:0,implicit:!0,optional:!0})],Xd.prototype,"certs",void 0);f([y({type:Yi,context:1,implicit:!0,optional:!0})],Xd.prototype,"crls",void 0);var rl;let nl=rl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,rl.prototype)}};nl=rl=f([j({type:R.Set,itemType:bo})],nl);class Ks{version=vr.v0;originatorInfo;recipientInfos=new qi;encryptedContentInfo=new Us;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Ks.prototype,"version",void 0);f([y({type:Xd,context:0,implicit:!0,optional:!0})],Ks.prototype,"originatorInfo",void 0);f([y({type:qi})],Ks.prototype,"recipientInfos",void 0);f([y({type:Us})],Ks.prototype,"encryptedContentInfo",void 0);f([y({type:nl,context:1,implicit:!0,optional:!0})],Ks.prototype,"unprotectedAttrs",void 0);const hx="1.2.840.113549.1.7.2";var ol;let Xi=ol=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,ol.prototype)}};Xi=ol=f([j({type:R.Set,itemType:bs})],Xi);class So{version=vr.v0;digestAlgorithms=new Xi;encapContentInfo=new nc;certificates;crls;signerInfos=new Hi;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],So.prototype,"version",void 0);f([y({type:Xi})],So.prototype,"digestAlgorithms",void 0);f([y({type:nc})],So.prototype,"encapContentInfo",void 0);f([y({type:Ki,context:0,implicit:!0,optional:!0})],So.prototype,"certificates",void 0);f([y({type:Yi,context:1,implicit:!0,optional:!0})],So.prototype,"crls",void 0);f([y({type:Hi})],So.prototype,"signerInfos",void 0);const Ss="1.2.840.10045.2.1",Jd="1.2.840.10045.4.1",Vv="1.2.840.10045.4.3.1",Zd="1.2.840.10045.4.3.2",Qd="1.2.840.10045.4.3.3",ef="1.2.840.10045.4.3.4",nh="1.2.840.10045.3.1.7",oh="1.3.132.0.34",sh="1.3.132.0.35";function Gs(t){return new W({algorithm:t})}const mx=Gs(Jd);Gs(Vv);const yx=Gs(Zd),gx=Gs(Qd),vx=Gs(ef);let ks=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],ks.prototype,"fieldType",void 0);f([y({type:b.Any})],ks.prototype,"parameters",void 0);ks=f([j({type:R.Sequence})],ks);class bx extends he{}let uo=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};f([y({type:b.OctetString})],uo.prototype,"a",void 0);f([y({type:b.OctetString})],uo.prototype,"b",void 0);f([y({type:b.BitString,optional:!0})],uo.prototype,"seed",void 0);uo=f([j({type:R.Sequence})],uo);var sl;(function(t){t[t.ecpVer1=1]="ecpVer1"})(sl||(sl={}));let br=class{version=sl.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};f([y({type:b.Integer})],br.prototype,"version",void 0);f([y({type:ks})],br.prototype,"fieldID",void 0);f([y({type:uo})],br.prototype,"curve",void 0);f([y({type:bx})],br.prototype,"base",void 0);f([y({type:b.Integer,converter:xe})],br.prototype,"order",void 0);f([y({type:b.Integer,optional:!0})],br.prototype,"cofactor",void 0);br=f([j({type:R.Sequence})],br);let Pr=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};f([y({type:b.ObjectIdentifier})],Pr.prototype,"namedCurve",void 0);f([y({type:b.Null})],Pr.prototype,"implicitCurve",void 0);f([y({type:br})],Pr.prototype,"specifiedCurve",void 0);Pr=f([j({type:R.Choice})],Pr);class ac{version=1;privateKey=new he;parameters;publicKey;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],ac.prototype,"version",void 0);f([y({type:he})],ac.prototype,"privateKey",void 0);f([y({type:Pr,context:0,optional:!0})],ac.prototype,"parameters",void 0);f([y({type:b.BitString,context:1,optional:!0})],ac.prototype,"publicKey",void 0);class Ji{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,converter:xe})],Ji.prototype,"r",void 0);f([y({type:b.Integer,converter:xe})],Ji.prototype,"s",void 0);const ut="1.2.840.113549.1.1",vn=`${ut}.1`,wx=`${ut}.7`,Ax=`${ut}.9`,ss=`${ut}.10`,Sx=`${ut}.2`,kx=`${ut}.4`,Zi=`${ut}.5`,Ex=`${ut}.14`,il=`${ut}.11`,Qi=`${ut}.12`,ea=`${ut}.13`,Hv=`${ut}.15`,Fv=`${ut}.16`,ta="1.3.14.3.2.26",Wv="2.16.840.1.101.3.4.2.4",ra="2.16.840.1.101.3.4.2.1",na="2.16.840.1.101.3.4.2.2",oa="2.16.840.1.101.3.4.2.3",xx="2.16.840.1.101.3.4.2.5",Ix="2.16.840.1.101.3.4.2.6",Ox="1.2.840.113549.2.2",Cx="1.2.840.113549.2.5",cc=`${ut}.8`;function Pe(t){return new W({algorithm:t,parameters:null})}Pe(Ox);Pe(Cx);const bn=Pe(ta);Pe(Wv);Pe(ra);Pe(na);Pe(oa);Pe(xx);Pe(Ix);const Kv=new W({algorithm:cc,parameters:H.serialize(bn)}),Gv=new W({algorithm:Ax,parameters:H.serialize(Ri.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});Pe(vn);Pe(Sx);Pe(kx);Pe(Zi);Pe(Hv);Pe(Fv);Pe(Qi);Pe(ea);Pe(Hv);Pe(Fv);class uc{hashAlgorithm=new W(bn);maskGenAlgorithm=new W({algorithm:cc,parameters:H.serialize(bn)});pSourceAlgorithm=new W(Gv);constructor(e={}){Object.assign(this,e)}}f([y({type:W,context:0,defaultValue:bn})],uc.prototype,"hashAlgorithm",void 0);f([y({type:W,context:1,defaultValue:Kv})],uc.prototype,"maskGenAlgorithm",void 0);f([y({type:W,context:2,defaultValue:Gv})],uc.prototype,"pSourceAlgorithm",void 0);new W({algorithm:wx,parameters:H.serialize(new uc)});class wn{hashAlgorithm=new W(bn);maskGenAlgorithm=new W({algorithm:cc,parameters:H.serialize(bn)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}}f([y({type:W,context:0,defaultValue:bn})],wn.prototype,"hashAlgorithm",void 0);f([y({type:W,context:1,defaultValue:Kv})],wn.prototype,"maskGenAlgorithm",void 0);f([y({type:b.Integer,context:2,defaultValue:20})],wn.prototype,"saltLength",void 0);f([y({type:b.Integer,context:3,defaultValue:1})],wn.prototype,"trailerField",void 0);new W({algorithm:ss,parameters:H.serialize(new wn)});class lc{digestAlgorithm=new W;digest=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:W})],lc.prototype,"digestAlgorithm",void 0);f([y({type:he})],lc.prototype,"digest",void 0);var al;class dc{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,converter:xe})],dc.prototype,"prime",void 0);f([y({type:b.Integer,converter:xe})],dc.prototype,"exponent",void 0);f([y({type:b.Integer,converter:xe})],dc.prototype,"coefficient",void 0);let cl=al=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,al.prototype)}};cl=al=f([j({type:R.Sequence,itemType:dc})],cl);class ir{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],ir.prototype,"version",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"modulus",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"publicExponent",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"privateExponent",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"prime1",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"prime2",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"exponent1",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"exponent2",void 0);f([y({type:b.Integer,converter:xe})],ir.prototype,"coefficient",void 0);f([y({type:cl,optional:!0})],ir.prototype,"otherPrimeInfos",void 0);class tf{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer,converter:xe})],tf.prototype,"modulus",void 0);f([y({type:b.Integer,converter:xe})],tf.prototype,"publicExponent",void 0);var ul;(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(ul||(ul={}));const nt=ul;var ll=function(t,e){return ll=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var o in n)n.hasOwnProperty(o)&&(r[o]=n[o])},ll(t,e)};function rf(t,e){ll(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Nx(t,e,r,n){function o(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(d){try{u(n.next(d))}catch(l){i(l)}}function c(d){try{u(n.throw(d))}catch(l){i(l)}}function u(d){d.done?s(d.value):o(d.value).then(a,c)}u((n=n.apply(t,[])).next())})}function Tx(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,o,s,i;return i={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(u){return function(d){return c([u,d])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,o&&(s=u[0]&2?o.return:u[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,u[1])).done)return s;switch(o=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,o=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(d){u=[6,d],o=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function oi(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function sa(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return s}function Zr(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(sa(arguments[e]));return t}var $x="injectionTokens";function Bx(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata($x,t)||{};return Object.keys(r).forEach(function(n){e[+n]=r[n]}),e}function qv(t){return!!t.useClass}function dl(t){return!!t.useFactory}var zv=(function(){function t(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return t.prototype.createProxy=function(e){var r=this,n={},o=!1,s,i=function(){return o||(s=e(r.wrap()),o=!0),s};return new Proxy(n,this.createHandler(i))},t.prototype.createHandler=function(e){var r={},n=function(o){r[o]=function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];s[0]=e();var a=Reflect[o];return a.apply(void 0,Zr(s))}};return this.reflectMethods.forEach(n),r},t})();function Mn(t){return typeof t=="string"||typeof t=="symbol"}function Rx(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function ih(t){return typeof t=="object"&&"token"in t&&"transform"in t}function Mx(t){return typeof t=="function"||t instanceof zv}function hi(t){return!!t.useToken}function mi(t){return t.useValue!=null}function _x(t){return qv(t)||mi(t)||hi(t)||dl(t)}var nf=(function(){function t(){this._registryMap=new Map}return t.prototype.entries=function(){return this._registryMap.entries()},t.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},t.prototype.get=function(e){this.ensure(e);var r=this._registryMap.get(e);return r[r.length-1]||null},t.prototype.set=function(e,r){this.ensure(e),this._registryMap.get(e).push(r)},t.prototype.setAll=function(e,r){this._registryMap.set(e,r)},t.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},t.prototype.clear=function(){this._registryMap.clear()},t.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},t})(),jx=(function(t){rf(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(nf),si=(function(){function t(){this.scopedResolutions=new Map}return t})();function Dx(t,e){if(t===null)return"at position #"+e;var r=t.split(",")[e].trim();return'"'+r+'" at position #'+e}function Lx(t,e,r){return r===void 0&&(r=" "),Zr([t],e.message.split(`
370
+ `}function Lv(t,e={}){const r=[],n=e.label;let s;for(rh.lastIndex=0;s=rh.exec(t);){const o=s[1].trim();if(n&&o!==n)continue;Pv(o);const i=QE(s[2]);r.push({label:o,data:xo.decode(i.base64Text),headers:i.headers,lineLength:i.base64Lines[0]?.length??64,newline:ex(s[0])})}if(e.strict&&r.length===0)throw new TypeError(n?`No PEM block with label '${n}' was found`:"No PEM blocks were found");return r}function qd(t,e,r={}){Pv(t);const n=r.lineLength??64;if(!Number.isInteger(n)||n<1)throw new RangeError("PEM lineLength must be a positive integer");const s=r.newline??`
371
+ `,o=[`-----BEGIN ${t}-----`];if(r.headers){for(const[i,a]of Object.entries(r.headers))o.push(`${i}: ${a}`);o.push("")}return o.push(...ZE(xo.encode(e),n)),o.push(`-----END ${t}-----`),`${o.join(s)}${s}`}function tx(t,e={}){return Lv(t,e).map(({lineLength:r,newline:n,...s})=>s)}function rx(t,e){const[r]=tx(t,{label:e,strict:!0});return r.data}function nx(t,e={}){const[r]=Lv(t,{...e,strict:!0}),n={label:r.label,headers:r.headers,lineLength:r.lineLength,newline:r.newline};return{bytes:r.data,format:n,normalized:qd(r.label,r.data,n)}}function sx(t,e){return qd(e.label,t,e)}const ox={name:"pem",encode:(t,e)=>{if(!e?.label)throw new TypeError("PEM label is required");return qd(e.label,t,e)},decode:(t,e)=>rx(t,e?.label),format:sx,is:t=>typeof t=="string"&&/-----BEGIN [^-]+-----/.test(t),parse:nx};function Zt(t){return t.trim().toLowerCase()}function ix(t){return t instanceof Error?t:new Error(String(t))}function nh(t,e,r){for(const n of[r.name,...r.aliases??[]])t.delete(Zt(n));e.delete(Zt(r.name))}function tu(t,e,r){const n=t[r];if(typeof n!="function")throw new Error(`Converter '${e}' does not support ${r}()`);return n}function ax(t,e,r){const n=Zt(r.name||t),s=e.trim();if(!s)return 0;let o=!1;r.is&&(o=r.is(e));let i=!1;try{r.decode(e),i=!0}catch{i=!1}if(!o&&!i)return 0;switch(n){case"pem":return/-----BEGIN [^-]+-----/.test(e)?1:0;case"hex":{const a=s.replace(/^0x/i,"").replace(/[\s:.-]/g,"");return!a||/[^0-9a-f]/i.test(a)||a.length%2!==0?0:/^0x/i.test(s)||/[:\s.-]/.test(s)?.95:/[a-f]/.test(s)||/[A-F]/.test(s)?.8:.45}case"base64url":return/[-_]/.test(s)?.95:/=/.test(s)?.1:.6;case"base64":return/[+/=]/.test(s)?.9:.55;case"binary":case"utf8":case"utf16be":case"utf16le":return 0;default:return o&&i?.75:.5}}function cx(t=[]){const e=new Map,r=new Set,n={register(s,o={}){if(!s.name||!Zt(s.name))throw new TypeError("Converter name is required");const i=[...new Set([s.name,...s.aliases??[]].map(Zt))],a=new Set;for(const c of i){const u=e.get(c);if(u){if(!o.override)throw new Error(`Converter '${c}' is already registered`);a.add(u)}}for(const c of a)nh(e,r,c);for(const c of i)e.set(c,s);return r.add(Zt(s.name)),this},unregister(s){const o=e.get(Zt(s));return o?(nh(e,r,o),!0):!1},has(s){return e.has(Zt(s))},get(s){const o=e.get(Zt(s));if(!o)throw new Error(`Converter '${s}' is not registered`);return o},list(){return[...r].map(s=>this.get(s))},encode(s,o,i){return this.get(s).encode(o,i)},decode(s,o,i){return this.get(s).decode(o,i)},tryDecode(s,o,i){try{return{ok:!0,bytes:this.decode(s,o,i)}}catch(a){return{ok:!1,error:ix(a)}}},normalize(s,o,i){const a=this.get(s);return tu(a,s,"normalize").call(a,o,i)},parse(s,o,i){const a=this.get(s);return tu(a,s,"parse").call(a,o,i)},format(s,o,i){const a=this.get(s);return tu(a,s,"format").call(a,o,i)},transcode(s,o){const i=this.decode(o.from,s,o.fromOptions);return this.encode(o.to,i,o.toOptions)},detect(s,o={}){const i=o.formats?.length?o.formats.map(c=>String(c)):this.list().map(c=>c.name).filter(c=>!["binary","utf8","utf16be","utf16le"].includes(Zt(c))),a=new Map;for(const c of i){const u=this.get(c),l=ax(c,s,u);if(l<=0)continue;const d=u.name,m=a.get(d);(!m||l>m.confidence)&&a.set(d,{format:d,confidence:l})}return[...a.values()].sort((c,u)=>u.confidence-c.confidence)}};for(const s of t)n.register(s);return n}const ux={name:"binary",aliases:["latin1"],encode:Nv,decode:Tv,is:TE},lx={name:"hex",encode:tc,decode:$v,format:FE,is:HE,normalize:ec,parse:VE},dx={name:"base64",aliases:["b64"],encode:Rv,decode:jv,is:Kd,normalize:rc},fx={name:"base64url",aliases:["base64-url","b64url"],encode:YE,decode:XE,is:Dv,normalize:Gd},px={name:"utf8",aliases:["utf-8"],encode:t=>KE(t),decode:t=>WE(t),is:t=>typeof t=="string"},hx={name:"utf16be",aliases:["utf16","utf-16","utf-16be"],encode:t=>_v(t),decode:t=>Bv(t),is:t=>typeof t=="string"},mx={name:"utf16le",aliases:["utf-16le","ucs2","usc2"],encode:t=>_v(t,{littleEndian:!0}),decode:t=>Bv(t,{littleEndian:!0}),is:t=>typeof t=="string"},yx=[ux,lx,dx,fx,px,hx,mx,ox];cx(yx);var B;(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})(B||(B={}));var S;(function(t){t[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null",t[t.RelativeObjectIdentifier=28]="RelativeObjectIdentifier"})(S||(S={}));class nc{unusedBits=0;value=new ArrayBuffer(0);constructor(e,r=0){if(e)if(typeof e=="number")this.fromNumber(e);else if(Qa(e))this.unusedBits=r,this.value=$t(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof dn))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=$t(e.valueBlock.valueHex),this}toASN(){return new dn({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new dn({name:e})}toNumber(){let e="";const r=new Uint8Array(this.value);for(const n of r)e+=n.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let r=e.toString(2);const n=r.length+7>>3;this.unusedBits=(n<<3)-r.length;const s=new Uint8Array(n);r=r.padStart(n<<3,"0").split("").reverse().join("");let o=0;for(;o<n;)s[o]=parseInt(r.slice(o<<3,(o<<3)+8),2),o++;this.value=s.buffer}}class he{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):Qa(e)?this.buffer=$t(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof ln))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=$t(e.valueBlock.valueHex),this}toASN(){return new ln({valueHex:this.buffer})}toSchema(e){return new ln({name:e})}}const gx={fromASN:t=>t instanceof vn?null:$t(t.valueBeforeDecodeView),toASN:t=>{if(t===null)return new vn;const e=es(t);if(e.result.error)throw new Error(e.result.error);return e.result}},vx={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new Ss({value:+t})},bx={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new La({value:t})},Ce={fromASN:t=>$t(t.valueBlock.valueHexView),toASN:t=>new Ss({valueHex:t})},wx={fromASN:t=>$t(t.valueBlock.valueHexView),toASN:t=>new dn({valueHex:t})},Sx={fromASN:t=>t.valueBlock.toString(),toASN:t=>new Ua({value:t})},Ax={fromASN:t=>t.valueBlock.toString(),toASN:t=>new Ha({value:t})},kx={fromASN:t=>t.valueBlock.value,toASN:t=>new Pa({value:t})},Wi={fromASN:t=>$t(t.valueBlock.valueHexView),toASN:t=>new ln({valueHex:t})},Ex={fromASN:t=>new he(t.getValue()),toASN:t=>t.toASN()};function Bt(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}const Uv=Bt(Or),xx=Bt(Va),Ix=Bt(Fa),Cx=Bt(Wa),Ox=Bt(Ka),Nx=Bt(Ga),Tx=Bt(qa),$x=Bt(za),Bx=Bt(Ya),_x=Bt(Fo),Mx=Bt(Xa),Rx=Bt(Ja),jx={fromASN:t=>t.toDate(),toASN:t=>new Wo({valueDate:t})},Dx={fromASN:t=>t.toDate(),toASN:t=>new Za({valueDate:t})},Px={fromASN:()=>null,toASN:()=>new vn};function uo(t){switch(t){case S.Any:return gx;case S.BitString:return wx;case S.BmpString:return xx;case S.Boolean:return kx;case S.CharacterString:return Rx;case S.Enumerated:return bx;case S.GeneralString:return Mx;case S.GeneralizedTime:return Dx;case S.GraphicString:return Bx;case S.IA5String:return $x;case S.Integer:return vx;case S.Null:return Px;case S.NumericString:return Cx;case S.ObjectIdentifier:return Sx;case S.RelativeObjectIdentifier:return Ax;case S.OctetString:return Wi;case S.PrintableString:return Ox;case S.TeletexString:return Nx;case S.UTCTime:return jx;case S.UniversalString:return Ix;case S.Utf8String:return Uv;case S.VideotexString:return Tx;case S.VisibleString:return _x;default:return null}}function gr(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:gr(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function Hv(t){if(t){const e=Object.getPrototypeOf(t);return e?.prototype?.constructor===Array?!0:Hv(e)}return!1}function Lx(t,e){if(!(t&&e)||t.byteLength!==e.byteLength)return!1;const r=new Uint8Array(t),n=new Uint8Array(e);for(let s=0;s<t.byteLength;s++)if(r[s]!==n[s])return!1;return!0}class Ux{items=new WeakMap;has(e){return this.items.has(e)}get(e,r=!1){const n=this.items.get(e);if(!n)throw new Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(r&&!n.schema)throw new Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){const r=this.get(e);r.schema||(r.schema=this.create(e,!0))}createDefault(e){const r={type:B.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(r,n),r.items=Object.assign({},r.items,n.items)),r}create(e,r){const n=this.items.get(e)||this.createDefault(e),s=[];for(const o in n.items){const i=n.items[o],a=r?o:"";let c;if(typeof i.type=="number"){const l=S[i.type],d=xv[l];if(!d)throw new Error(`Cannot get ASN1 class by name '${l}'`);c=new d({name:a})}else gr(i.type)?c=new i.type().toSchema(a):i.optional?this.get(i.type).type===B.Choice?c=new bn({name:a}):(c=this.create(i.type,!1),c.name=a):c=new bn({name:a});const u=!!i.optional||i.defaultValue!==void 0;if(i.repeated){c.name="";const l=i.repeated==="set"?tr:Vt;c=new l({name:"",value:[new Fi({name:a,value:c})]})}if(i.context!==null&&i.context!==void 0)if(i.implicit)if(typeof i.type=="number"||gr(i.type)){const l=i.repeated?rt:Ho;s.push(new l({name:a,optional:u,idBlock:{tagClass:3,tagNumber:i.context}}))}else{this.cache(i.type);const l=!!i.repeated;let d=l?c:this.get(i.type,!0).schema;d="valueBlock"in d?d.valueBlock.value:d.value,s.push(new rt({name:l?"":a,optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:d}))}else s.push(new rt({optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:[c]}));else c.optional=u,s.push(c)}switch(n.type){case B.Sequence:return new Vt({value:s,name:""});case B.Set:return new tr({value:s,name:""});case B.Choice:return new Fd({value:s,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,r){return this.items.set(e,r),this}findParentSchema(e){const r=Object.getPrototypeOf(e);return r?this.items.get(r)||this.findParentSchema(r):null}}const Ke=new Ux,D=t=>e=>{let r;Ke.has(e)?r=Ke.get(e):(r=Ke.createDefault(e),Ke.set(e,r)),Object.assign(r,t)},y=t=>(e,r)=>{let n;Ke.has(e.constructor)?n=Ke.get(e.constructor):(n=Ke.createDefault(e.constructor),Ke.set(e.constructor,n));const s=Object.assign({},t);if(typeof s.type=="number"&&!s.converter){const o=uo(t.type);if(!o)throw new Error(`Cannot get default converter for property '${r}' of ${e.constructor.name}`);s.converter=o}s.raw=t.raw,n.items[r]=s};class js extends Error{schemas=[]}class Hx{static parse(e,r,n){const s=es($t(e),n?.berOptions);if(s.result.error)throw new Error(s.result.error);return this.fromASN(s.result,r,n)}static fromASN(e,r,n){try{if(gr(r))return new r().fromASN(e);const s=Ke.get(r);Ke.cache(r);let o=s.schema;const i=this.handleChoiceTypes(e,s,r,o,n);if(i?.result)return i.result;i?.targetSchema&&(o=i.targetSchema);const a=this.handleSequenceTypes(e,s,r,o),c=new r;return Hv(r)?this.handleArrayTypes(e,s,r,n):(this.processSchemaItems(s,a,c,n),c)}catch(s){throw s instanceof js&&s.schemas.push(r.name),s}}static handleChoiceTypes(e,r,n,s,o){if(e.constructor===rt&&r.type===B.Choice&&e.idBlock.tagClass===3)for(const i in r.items){const a=r.items[i];if(a.context===e.idBlock.tagNumber&&a.implicit&&typeof a.type=="function"&&Ke.has(a.type)){const c=Ke.get(a.type);if(c&&c.type===B.Sequence){const u=new Vt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in u.valueBlock){u.valueBlock.value=e.valueBlock.value;const l=this.fromASN(u,a.type,o),d=new n;return d[i]=l,{result:d}}}}}else if(e.constructor===rt&&r.type!==B.Choice){const i=new rt({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:r.schema.valueBlock.value});for(const a in r.items)delete e[a];return{targetSchema:i}}return null}static handleSequenceTypes(e,r,n,s){if(r.type===B.Sequence){const o=Rr({},e,s);if(!o.verified)throw new js(`Data does not match to ${n.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}else{const o=Rr({},e,s);if(!o.verified)throw new js(`Data does not match to ${n.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}}static processRepeatedField(e,r,n){let s=e.slice(r);if(s.length===1&&s[0].constructor.name==="Sequence"){const o=s[0];o.valueBlock&&o.valueBlock.value&&Array.isArray(o.valueBlock.value)&&(s=o.valueBlock.value)}if(typeof n.type=="number"){const o=uo(n.type);if(!o)throw new Error(`No converter for ASN.1 type ${n.type}`);return s.filter(i=>i&&i.valueBlock).map(i=>{try{return o.fromASN(i)}catch{return}}).filter(i=>i!==void 0)}else return s.filter(o=>o&&o.valueBlock).map(o=>{try{return this.fromASN(o,n.type)}catch{return}}).filter(o=>o!==void 0)}static processPrimitiveField(e,r){const n=uo(r.type);if(!n)throw new Error(`No converter for ASN.1 type ${r.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type=="function"&&Ke.has(e.type)&&Ke.get(e.type).type===B.Choice}static processOptionalChoiceField(e,r){try{return{processed:!0,value:this.fromASN(e,r.type)}}catch(n){if(n instanceof js&&/Wrong values for Choice type/.test(n.message))return{processed:!1};throw n}}static handleArrayTypes(e,r,n,s){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const o=r.itemType;if(typeof o=="number"){const i=uo(o);if(!i)throw new Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,a=>i.fromASN(a))}else return n.from(e.valueBlock.value,i=>this.fromASN(i,o,s))}static processSchemaItems(e,r,n,s){for(const o in e.items){const i=r.result[o];if(!i)continue;const a=e.items[o],c=a.type;let u;typeof c=="number"||gr(c)?u=this.processPrimitiveSchemaItem(i,a,c,s):u=this.processComplexSchemaItem(i,a,c,s),u&&typeof u=="object"&&"value"in u&&"raw"in u?(n[o]=u.value,n[`${o}Raw`]=u.raw):n[o]=u}}static processPrimitiveSchemaItem(e,r,n,s){const o=r.converter??(gr(n)?new n:null);if(!o)throw new Error("Converter is empty");return r.repeated?this.processRepeatedPrimitiveItem(e,r,o,s):this.processSinglePrimitiveItem(e,r,n,o,s)}static processRepeatedPrimitiveItem(e,r,n,s){if(r.implicit){const o=r.repeated==="sequence"?Vt:tr,i=new o;i.valueBlock=e.valueBlock;const a=es(i.toBER(!1),s?.berOptions);if(a.offset===-1)throw new Error(`Cannot parse the child item. ${a.result.error}`);if(!("value"in a.result.valueBlock&&Array.isArray(a.result.valueBlock.value)))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");const c=a.result.valueBlock.value;return Array.from(c,u=>n.fromASN(u))}else return Array.from(e,o=>n.fromASN(o))}static processSinglePrimitiveItem(e,r,n,s,o){let i=e;if(r.implicit){let a;if(gr(n))a=new n().toSchema("");else{const c=S[n],u=xv[c];if(!u)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new u}a.valueBlock=i.valueBlock,i=es(a.toBER(!1),o?.berOptions).result}return s.fromASN(i)}static processComplexSchemaItem(e,r,n,s){if(r.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,o=>this.fromASN(o,n,s))}else{const o=this.handleImplicitTagging(e,r,n);if(this.isOptionalChoiceField(r))try{return this.fromASN(o,n,s)}catch(i){if(i instanceof js&&/Wrong values for Choice type/.test(i.message))return;throw i}else{const i=this.fromASN(o,n,s);return r.raw?{value:i,raw:e.valueBeforeDecodeView}:i}}}static handleImplicitTagging(e,r,n){if(r.implicit&&typeof r.context=="number"){const s=Ke.get(n);if(s.type===B.Sequence){const o=new Vt;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in o.valueBlock)return o.valueBlock.value=e.valueBlock.value,o}else if(s.type===B.Set){const o=new tr;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in o.valueBlock)return o.valueBlock.value=e.valueBlock.value,o}}return e}}class zd{static serialize(e){return e instanceof We?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&gr(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");const r=e.constructor,n=Ke.get(r);Ke.cache(r);let s=[];if(n.itemType){if(!Array.isArray(e))throw new TypeError("Parameter 1 should be type of Array.");if(typeof n.itemType=="number"){const i=uo(n.itemType);if(!i)throw new Error(`Cannot get default converter for array item of ${r.name} ASN1 schema`);s=e.map(a=>i.toASN(a))}else s=e.map(i=>this.toAsnItem({type:n.itemType},"[]",r,i))}else for(const i in n.items){const a=n.items[i],c=e[i];if(c===void 0||a.defaultValue===c||typeof a.defaultValue=="object"&&typeof c=="object"&&Lx(this.serialize(a.defaultValue),this.serialize(c)))continue;const u=zd.toAsnItem(a,i,r,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||gr(a.type))){const l={};l.valueHex=u instanceof vn?$t(u.valueBeforeDecodeView):u.valueBlock.toBER(),s.push(new Ho({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...l}))}else s.push(new rt({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:u.valueBlock.value}));else s.push(new rt({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:[u]}));else a.repeated?s=s.concat(u):s.push(u)}let o;switch(n.type){case B.Sequence:o=new Vt({value:s});break;case B.Set:o=new tr({value:s});break;case B.Choice:if(!s[0])throw new Error(`Schema '${r.name}' has wrong data. Choice cannot be empty.`);o=s[0];break}return o}static toAsnItem(e,r,n,s){let o;if(typeof e.type=="number"){const i=e.converter;if(!i)throw new Error(`Property '${r}' doesn't have converter for type ${S[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const a=Array.from(s,u=>i.toASN(u)),c=e.repeated==="sequence"?Vt:tr;o=new c({value:a})}else o=i.toASN(s)}else if(e.repeated){if(!Array.isArray(s))throw new TypeError("Parameter 'objProp' should be type of Array.");const i=Array.from(s,c=>this.toASN(c)),a=e.repeated==="sequence"?Vt:tr;o=new a({value:i})}else o=this.toASN(s);return o}}class pe extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(const r of e)this.push(r)}}}class V{static serialize(e){return zd.serialize(e)}static parse(e,r,n){return Hx.parse(e,r,n)}static toString(e,r){const n=Qa(e)?$t(e):V.serialize(e),s=es(n,r?.berOptions);if(s.offset===-1)throw new Error(`Cannot decode ASN.1 data. ${s.result.error}`);return s.result.toString()}}function f(t,e,r,n){var s=arguments.length,o=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(i=t[a])&&(o=(s<3?i(o):s>3?i(e,r,o):i(e,r))||o);return s>3&&o&&Object.defineProperty(e,r,o),o}function oe(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function xe(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}class sh{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){const r=e.split(".");if(r.length!==4)throw new Error("Invalid IPv4 address");return r.map(n=>{const s=parseInt(n,10);if(isNaN(s)||s<0||s>255)throw new Error("Invalid IPv4 address part");return s})}static parseIPv6(e){const n=this.expandIPv6(e).split(":");if(n.length!==8)throw new Error("Invalid IPv6 address");return n.reduce((s,o)=>{const i=parseInt(o,16);if(isNaN(i)||i<0||i>65535)throw new Error("Invalid IPv6 address part");return s.push(i>>8&255),s.push(i&255),s},[])}static expandIPv6(e){if(!e.includes("::"))return e;const r=e.split("::");if(r.length>2)throw new Error("Invalid IPv6 address");const n=r[0]?r[0].split(":"):[],s=r[1]?r[1].split(":"):[],o=8-(n.length+s.length);if(o<0)throw new Error("Invalid IPv6 address");return[...n,...Array(o).fill("0"),...s].join(":")}static formatIPv6(e){const r=[];for(let n=0;n<16;n+=2)r.push((e[n]<<8|e[n+1]).toString(16));return this.compressIPv6(r.join(":"))}static compressIPv6(e){const r=e.split(":");let n=-1,s=0,o=-1,i=0;for(let a=0;a<r.length;a++)r[a]==="0"?(o===-1&&(o=a),i++):(i>s&&(n=o,s=i),o=-1,i=0);if(i>s&&(n=o,s=i),s>1){const a=r.slice(0,n).join(":"),c=r.slice(n+s).join(":");return`${a}::${c}`}return e}static parseCIDR(e){const[r,n]=e.split("/"),s=parseInt(n,10);if(this.isIPv4(r)){if(s<0||s>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(r),s]}else{if(s<0||s>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(r),s]}}static decodeIP(e){if(e.length===64&&parseInt(e,16)===0)return"::/0";if(e.length!==16)return e;const r=parseInt(e.slice(8),16).toString(2).split("").reduce((s,o)=>s+ +o,0);let n=e.slice(0,8).replace(/(.{2})/g,s=>`${parseInt(s,16)}.`);return n=n.slice(0,-1),`${n}/${r}`}static toString(e){const r=new Uint8Array(e);if(r.length===4)return Array.from(r).join(".");if(r.length===16)return this.formatIPv6(r);if(r.length===8||r.length===32){const n=r.length/2,s=r.slice(0,n),o=r.slice(n);if(r.every(c=>c===0))return r.length===8?"0.0.0.0/0":"::/0";const a=o.reduce((c,u)=>c+(u.toString(2).match(/1/g)||[]).length,0);return r.length===8?`${Array.from(s).join(".")}/${a}`:`${this.formatIPv6(s)}/${a}`}return this.decodeIP(tc(e))}static fromString(e){if(e.includes("/")){const[n,s]=this.parseCIDR(e),o=new Uint8Array(n.length);let i=s;for(let c=0;c<o.length;c++)i>=8?(o[c]=255,i-=8):i>0&&(o[c]=255<<8-i,i=0);const a=new Uint8Array(n.length*2);return a.set(n,0),a.set(o,n.length),a.buffer}const r=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(r).buffer}}var _u,Mu,Ru;let ze=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};f([y({type:S.TeletexString})],ze.prototype,"teletexString",void 0);f([y({type:S.PrintableString})],ze.prototype,"printableString",void 0);f([y({type:S.UniversalString})],ze.prototype,"universalString",void 0);f([y({type:S.Utf8String})],ze.prototype,"utf8String",void 0);f([y({type:S.BmpString})],ze.prototype,"bmpString",void 0);ze=f([D({type:B.Choice})],ze);let cs=class extends ze{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?tc(this.anyValue):super.toString())}};f([y({type:S.IA5String})],cs.prototype,"ia5String",void 0);f([y({type:S.Any})],cs.prototype,"anyValue",void 0);cs=f([D({type:B.Choice})],cs);class sc{type="";value=new cs;constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],sc.prototype,"type",void 0);f([y({type:cs})],sc.prototype,"value",void 0);let us=_u=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,_u.prototype)}};us=_u=f([D({type:B.Set,itemType:sc})],us);let ju=Mu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Mu.prototype)}};ju=Mu=f([D({type:B.Sequence,itemType:us})],ju);let je=Ru=class extends ju{constructor(e){super(e),Object.setPrototypeOf(this,Ru.prototype)}};je=Ru=f([D({type:B.Sequence})],je);const Vx={fromASN:t=>sh.toString(Wi.fromASN(t)),toASN:t=>Wi.toASN(sh.fromString(t))};class Io{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],Io.prototype,"typeId",void 0);f([y({type:S.Any,context:0})],Io.prototype,"value",void 0);class Yd{nameAssigner;partyName=new ze;constructor(e={}){Object.assign(this,e)}}f([y({type:ze,optional:!0,context:0,implicit:!0})],Yd.prototype,"nameAssigner",void 0);f([y({type:ze,context:1,implicit:!0})],Yd.prototype,"partyName",void 0);let ie=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};f([y({type:Io,context:0,implicit:!0})],ie.prototype,"otherName",void 0);f([y({type:S.IA5String,context:1,implicit:!0})],ie.prototype,"rfc822Name",void 0);f([y({type:S.IA5String,context:2,implicit:!0})],ie.prototype,"dNSName",void 0);f([y({type:S.Any,context:3,implicit:!0})],ie.prototype,"x400Address",void 0);f([y({type:je,context:4,implicit:!1})],ie.prototype,"directoryName",void 0);f([y({type:Yd,context:5})],ie.prototype,"ediPartyName",void 0);f([y({type:S.IA5String,context:6,implicit:!0})],ie.prototype,"uniformResourceIdentifier",void 0);f([y({type:S.OctetString,context:7,implicit:!0,converter:Vx})],ie.prototype,"iPAddress",void 0);f([y({type:S.ObjectIdentifier,context:8,implicit:!0})],ie.prototype,"registeredID",void 0);ie=f([D({type:B.Choice})],ie);const Xd="1.3.6.1.5.5.7",Fx=`${Xd}.1`,As=`${Xd}.3`,oc=`${Xd}.48`,oh=`${oc}.1`,ih=`${oc}.2`,ah=`${oc}.3`,ch=`${oc}.5`,Nr="2.5.29";var Du;const Pu=`${Fx}.1`;class Ko{accessMethod="";accessLocation=new ie;constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],Ko.prototype,"accessMethod",void 0);f([y({type:ie})],Ko.prototype,"accessLocation",void 0);let Xn=Du=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Du.prototype)}};Xn=Du=f([D({type:B.Sequence,itemType:Ko})],Xn);const Lu=`${Nr}.35`;class Jd extends he{}class on{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}}f([y({type:Jd,context:0,optional:!0,implicit:!0})],on.prototype,"keyIdentifier",void 0);f([y({type:ie,context:1,optional:!0,implicit:!0,repeated:"sequence"})],on.prototype,"authorityCertIssuer",void 0);f([y({type:S.Integer,context:2,optional:!0,implicit:!0,converter:Ce})],on.prototype,"authorityCertSerialNumber",void 0);const Vv=`${Nr}.19`;class Ki{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Boolean,defaultValue:!1})],Ki.prototype,"cA",void 0);f([y({type:S.Integer,optional:!0})],Ki.prototype,"pathLenConstraint",void 0);var Uu;let Xe=Uu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Uu.prototype)}};Xe=Uu=f([D({type:B.Sequence,itemType:ie})],Xe);var Hu;let uh=Hu=class extends Xe{constructor(e){super(e),Object.setPrototypeOf(this,Hu.prototype)}};uh=Hu=f([D({type:B.Sequence})],uh);var Vu;const Fv=`${Nr}.32`;let Sr=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};f([y({type:S.IA5String})],Sr.prototype,"ia5String",void 0);f([y({type:S.VisibleString})],Sr.prototype,"visibleString",void 0);f([y({type:S.BmpString})],Sr.prototype,"bmpString",void 0);f([y({type:S.Utf8String})],Sr.prototype,"utf8String",void 0);Sr=f([D({type:B.Choice})],Sr);class Zd{organization=new Sr;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}}f([y({type:Sr})],Zd.prototype,"organization",void 0);f([y({type:S.Integer,repeated:"sequence"})],Zd.prototype,"noticeNumbers",void 0);class Qd{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}}f([y({type:Zd,optional:!0})],Qd.prototype,"noticeRef",void 0);f([y({type:Sr,optional:!0})],Qd.prototype,"explicitText",void 0);let Gi=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};f([y({type:S.IA5String})],Gi.prototype,"cPSuri",void 0);f([y({type:Qd})],Gi.prototype,"userNotice",void 0);Gi=f([D({type:B.Choice})],Gi);class ef{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],ef.prototype,"policyQualifierId",void 0);f([y({type:S.Any})],ef.prototype,"qualifier",void 0);class ic{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],ic.prototype,"policyIdentifier",void 0);f([y({type:ef,repeated:"sequence",optional:!0})],ic.prototype,"policyQualifiers",void 0);let qi=Vu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Vu.prototype)}};qi=Vu=f([D({type:B.Sequence,itemType:ic})],qi);let zi=class{value;constructor(e=0){this.value=e}};f([y({type:S.Integer})],zi.prototype,"value",void 0);zi=f([D({type:B.Choice})],zi);let lh=class extends zi{};lh=f([D({type:B.Choice})],lh);var Fu;const Wu=`${Nr}.31`;var Dt;(function(t){t[t.unused=1]="unused",t[t.keyCompromise=2]="keyCompromise",t[t.cACompromise=4]="cACompromise",t[t.affiliationChanged=8]="affiliationChanged",t[t.superseded=16]="superseded",t[t.cessationOfOperation=32]="cessationOfOperation",t[t.certificateHold=64]="certificateHold",t[t.privilegeWithdrawn=128]="privilegeWithdrawn",t[t.aACompromise=256]="aACompromise"})(Dt||(Dt={}));class Wv extends nc{toJSON(){const e=[],r=this.toNumber();return r&Dt.aACompromise&&e.push("aACompromise"),r&Dt.affiliationChanged&&e.push("affiliationChanged"),r&Dt.cACompromise&&e.push("cACompromise"),r&Dt.certificateHold&&e.push("certificateHold"),r&Dt.cessationOfOperation&&e.push("cessationOfOperation"),r&Dt.keyCompromise&&e.push("keyCompromise"),r&Dt.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&Dt.superseded&&e.push("superseded"),r&Dt.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let Sn=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};f([y({type:ie,context:0,repeated:"sequence",implicit:!0})],Sn.prototype,"fullName",void 0);f([y({type:us,context:1,implicit:!0})],Sn.prototype,"nameRelativeToCRLIssuer",void 0);Sn=f([D({type:B.Choice})],Sn);class ks{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}}f([y({type:Sn,context:0,optional:!0})],ks.prototype,"distributionPoint",void 0);f([y({type:Wv,context:1,optional:!0,implicit:!0})],ks.prototype,"reasons",void 0);f([y({type:ie,context:2,optional:!0,repeated:"sequence",implicit:!0})],ks.prototype,"cRLIssuer",void 0);let ts=Fu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Fu.prototype)}};ts=Fu=f([D({type:B.Sequence,itemType:ks})],ts);var Ku;let dh=Ku=class extends ts{constructor(e){super(e),Object.setPrototypeOf(this,Ku.prototype)}};dh=Ku=f([D({type:B.Sequence,itemType:ks})],dh);class tt{static ONLY=!1;distributionPoint;onlyContainsUserCerts=tt.ONLY;onlyContainsCACerts=tt.ONLY;onlySomeReasons;indirectCRL=tt.ONLY;onlyContainsAttributeCerts=tt.ONLY;constructor(e={}){Object.assign(this,e)}}f([y({type:Sn,context:0,optional:!0})],tt.prototype,"distributionPoint",void 0);f([y({type:S.Boolean,context:1,defaultValue:tt.ONLY,implicit:!0})],tt.prototype,"onlyContainsUserCerts",void 0);f([y({type:S.Boolean,context:2,defaultValue:tt.ONLY,implicit:!0})],tt.prototype,"onlyContainsCACerts",void 0);f([y({type:Wv,context:3,optional:!0,implicit:!0})],tt.prototype,"onlySomeReasons",void 0);f([y({type:S.Boolean,context:4,defaultValue:tt.ONLY,implicit:!0})],tt.prototype,"indirectCRL",void 0);f([y({type:S.Boolean,context:5,defaultValue:tt.ONLY,implicit:!0})],tt.prototype,"onlyContainsAttributeCerts",void 0);var lo;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(lo||(lo={}));let Gu=class{reason=lo.unspecified;constructor(e=lo.unspecified){this.reason=e}toJSON(){return lo[this.reason]}toString(){return this.toJSON()}};f([y({type:S.Enumerated})],Gu.prototype,"reason",void 0);Gu=f([D({type:B.Choice})],Gu);var qu;const Kv=`${Nr}.37`;let Yi=qu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,qu.prototype)}};Yi=qu=f([D({type:B.Sequence,itemType:S.ObjectIdentifier})],Yi);const Wx=`${As}.1`,Kx=`${As}.2`,Gx=`${As}.3`,qx=`${As}.4`,zx=`${As}.8`,Yx=`${As}.9`;let zu=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};f([y({type:S.Integer,converter:Ce})],zu.prototype,"value",void 0);zu=f([D({type:B.Choice})],zu);let Yu=class{value=new Date;constructor(e){e&&(this.value=e)}};f([y({type:S.GeneralizedTime})],Yu.prototype,"value",void 0);Yu=f([D({type:B.Choice})],Yu);var Xu;const Gv=`${Nr}.18`;let fh=Xu=class extends Xe{constructor(e){super(e),Object.setPrototypeOf(this,Xu.prototype)}};fh=Xu=f([D({type:B.Sequence})],fh);const qv=`${Nr}.15`;var Pt;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(Pt||(Pt={}));class ru extends nc{toJSON(){const e=this.toNumber(),r=[];return e&Pt.cRLSign&&r.push("crlSign"),e&Pt.dataEncipherment&&r.push("dataEncipherment"),e&Pt.decipherOnly&&r.push("decipherOnly"),e&Pt.digitalSignature&&r.push("digitalSignature"),e&Pt.encipherOnly&&r.push("encipherOnly"),e&Pt.keyAgreement&&r.push("keyAgreement"),e&Pt.keyCertSign&&r.push("keyCertSign"),e&Pt.keyEncipherment&&r.push("keyEncipherment"),e&Pt.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}}var Ju;class ac{base=new ie;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}}f([y({type:ie})],ac.prototype,"base",void 0);f([y({type:S.Integer,context:0,defaultValue:0,implicit:!0})],ac.prototype,"minimum",void 0);f([y({type:S.Integer,context:1,optional:!0,implicit:!0})],ac.prototype,"maximum",void 0);let Xi=Ju=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ju.prototype)}};Xi=Ju=f([D({type:B.Sequence,itemType:ac})],Xi);class zv{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}}f([y({type:Xi,context:0,optional:!0,implicit:!0})],zv.prototype,"permittedSubtrees",void 0);f([y({type:Xi,context:1,optional:!0,implicit:!0})],zv.prototype,"excludedSubtrees",void 0);class Yv{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer,context:0,implicit:!0,optional:!0,converter:Ce})],Yv.prototype,"requireExplicitPolicy",void 0);f([y({type:S.Integer,context:1,implicit:!0,optional:!0,converter:Ce})],Yv.prototype,"inhibitPolicyMapping",void 0);var Zu;class tf{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],tf.prototype,"issuerDomainPolicy",void 0);f([y({type:S.ObjectIdentifier})],tf.prototype,"subjectDomainPolicy",void 0);let ph=Zu=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Zu.prototype)}};ph=Zu=f([D({type:B.Sequence,itemType:tf})],ph);var Qu;const Xv=`${Nr}.17`;let el=Qu=class extends Xe{constructor(e){super(e),Object.setPrototypeOf(this,Qu.prototype)}};el=Qu=f([D({type:B.Sequence})],el);let Ar=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};f([y({type:S.ObjectIdentifier})],Ar.prototype,"type",void 0);f([y({type:S.Any,repeated:"set"})],Ar.prototype,"values",void 0);var tl;let hh=tl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,tl.prototype)}};hh=tl=f([D({type:B.Sequence,itemType:Ar})],hh);const Jv=`${Nr}.14`;class Lr extends Jd{}class Zv{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}}f([y({type:S.GeneralizedTime,context:0,implicit:!0,optional:!0})],Zv.prototype,"notBefore",void 0);f([y({type:S.GeneralizedTime,context:1,implicit:!0,optional:!0})],Zv.prototype,"notAfter",void 0);var fo;(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(fo||(fo={}));class Qv extends nc{toJSON(){const e=[],r=this.toNumber();return r&fo.pKIXCertificate&&e.push("pKIXCertificate"),r&fo.newExtensions&&e.push("newExtensions"),r&fo.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class eb{entrustVers="";entrustInfoFlags=new Qv;constructor(e={}){Object.assign(this,e)}}f([y({type:S.GeneralString})],eb.prototype,"entrustVers",void 0);f([y({type:Qv})],eb.prototype,"entrustInfoFlags",void 0);var rl;let mh=rl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,rl.prototype)}};mh=rl=f([D({type:B.Sequence,itemType:Ko})],mh);class W{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof W&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&NE(e.parameters,this.parameters)||e.parameters===this.parameters)}}f([y({type:S.ObjectIdentifier})],W.prototype,"algorithm",void 0);f([y({type:S.Any,optional:!0})],W.prototype,"parameters",void 0);class Nt{algorithm=new W;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:W})],Nt.prototype,"algorithm",void 0);f([y({type:S.BitString})],Nt.prototype,"subjectPublicKey",void 0);let Ge=class{utcTime;generalTime;constructor(e){if(e)if(typeof e=="string"||typeof e=="number"||e instanceof Date){const r=new Date(e);r.setMilliseconds(0),r.getUTCFullYear()>2049?this.generalTime=r:this.utcTime=r}else Object.assign(this,e)}getTime(){const e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};f([y({type:S.UTCTime})],Ge.prototype,"utcTime",void 0);f([y({type:S.GeneralizedTime})],Ge.prototype,"generalTime",void 0);Ge=f([D({type:B.Choice})],Ge);class Go{notBefore=new Ge(new Date);notAfter=new Ge(new Date);constructor(e){e&&(this.notBefore=new Ge(e.notBefore),this.notAfter=new Ge(e.notAfter))}}f([y({type:Ge})],Go.prototype,"notBefore",void 0);f([y({type:Ge})],Go.prototype,"notAfter",void 0);var nl;let Kt=class tb{static CRITICAL=!1;extnID="";critical=tb.CRITICAL;extnValue=new he;constructor(e={}){Object.assign(this,e)}};f([y({type:S.ObjectIdentifier})],Kt.prototype,"extnID",void 0);f([y({type:S.Boolean,defaultValue:Kt.CRITICAL})],Kt.prototype,"critical",void 0);f([y({type:he})],Kt.prototype,"extnValue",void 0);let Vr=nl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,nl.prototype)}};Vr=nl=f([D({type:B.Sequence,itemType:Kt})],Vr);var An;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(An||(An={}));class St{version=An.v1;serialNumber=new ArrayBuffer(0);signature=new W;issuer=new je;validity=new Go;subject=new je;subjectPublicKeyInfo=new Nt;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer,context:0,defaultValue:An.v1})],St.prototype,"version",void 0);f([y({type:S.Integer,converter:Ce})],St.prototype,"serialNumber",void 0);f([y({type:W})],St.prototype,"signature",void 0);f([y({type:je})],St.prototype,"issuer",void 0);f([y({type:Go})],St.prototype,"validity",void 0);f([y({type:je})],St.prototype,"subject",void 0);f([y({type:Nt})],St.prototype,"subjectPublicKeyInfo",void 0);f([y({type:S.BitString,context:1,implicit:!0,optional:!0})],St.prototype,"issuerUniqueID",void 0);f([y({type:S.BitString,context:2,implicit:!0,optional:!0})],St.prototype,"subjectUniqueID",void 0);f([y({type:Vr,context:3,optional:!0})],St.prototype,"extensions",void 0);class kn{tbsCertificate=new St;tbsCertificateRaw;signatureAlgorithm=new W;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:St,raw:!0})],kn.prototype,"tbsCertificate",void 0);f([y({type:W})],kn.prototype,"signatureAlgorithm",void 0);f([y({type:S.BitString})],kn.prototype,"signatureValue",void 0);class cc{userCertificate=new ArrayBuffer(0);revocationDate=new Ge;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer,converter:Ce})],cc.prototype,"userCertificate",void 0);f([y({type:Ge})],cc.prototype,"revocationDate",void 0);f([y({type:Kt,optional:!0,repeated:"sequence"})],cc.prototype,"crlEntryExtensions",void 0);class Tr{version;signature=new W;issuer=new je;thisUpdate=new Ge;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer,optional:!0})],Tr.prototype,"version",void 0);f([y({type:W})],Tr.prototype,"signature",void 0);f([y({type:je})],Tr.prototype,"issuer",void 0);f([y({type:Ge})],Tr.prototype,"thisUpdate",void 0);f([y({type:Ge,optional:!0})],Tr.prototype,"nextUpdate",void 0);f([y({type:cc,repeated:"sequence",optional:!0})],Tr.prototype,"revokedCertificates",void 0);f([y({type:Kt,optional:!0,context:0,repeated:"sequence"})],Tr.prototype,"crlExtensions",void 0);class rf{tbsCertList=new Tr;tbsCertListRaw;signatureAlgorithm=new W;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Tr,raw:!0})],rf.prototype,"tbsCertList",void 0);f([y({type:W})],rf.prototype,"signatureAlgorithm",void 0);f([y({type:S.BitString})],rf.prototype,"signature",void 0);class Es{issuer=new je;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:je})],Es.prototype,"issuer",void 0);f([y({type:S.Integer,converter:Ce})],Es.prototype,"serialNumber",void 0);let ls=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:Lr,context:0,implicit:!0})],ls.prototype,"subjectKeyIdentifier",void 0);f([y({type:Es})],ls.prototype,"issuerAndSerialNumber",void 0);ls=f([D({type:B.Choice})],ls);var kr;(function(t){t[t.v0=0]="v0",t[t.v1=1]="v1",t[t.v2=2]="v2",t[t.v3=3]="v3",t[t.v4=4]="v4",t[t.v5=5]="v5"})(kr||(kr={}));let Co=class extends W{};Co=f([D({type:B.Sequence})],Co);let Ji=class extends W{};Ji=f([D({type:B.Sequence})],Ji);let rr=class extends W{};rr=f([D({type:B.Sequence})],rr);let Zi=class extends W{};Zi=f([D({type:B.Sequence})],Zi);let yh=class extends W{};yh=f([D({type:B.Sequence})],yh);let sl=class extends W{};sl=f([D({type:B.Sequence})],sl);let xs=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};f([y({type:S.ObjectIdentifier})],xs.prototype,"attrType",void 0);f([y({type:S.Any,repeated:"set"})],xs.prototype,"attrValues",void 0);var ol;class cr{version=kr.v0;sid=new ls;digestAlgorithm=new Co;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Ji;signature=new he;unsignedAttrs;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],cr.prototype,"version",void 0);f([y({type:ls})],cr.prototype,"sid",void 0);f([y({type:Co})],cr.prototype,"digestAlgorithm",void 0);f([y({type:xs,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],cr.prototype,"signedAttrs",void 0);f([y({type:Ji})],cr.prototype,"signatureAlgorithm",void 0);f([y({type:he})],cr.prototype,"signature",void 0);f([y({type:xs,repeated:"set",context:1,implicit:!0,optional:!0})],cr.prototype,"unsignedAttrs",void 0);let Qi=ol=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,ol.prototype)}};Qi=ol=f([D({type:B.Set,itemType:cr})],Qi);let gh=class extends cr{};gh=f([D({type:B.Sequence})],gh);let vh=class extends Ge{};vh=f([D({type:B.Choice})],vh);class nf{acIssuer=new ie;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}}f([y({type:ie})],nf.prototype,"acIssuer",void 0);f([y({type:S.Integer})],nf.prototype,"acSerial",void 0);f([y({type:Ar,repeated:"sequence"})],nf.prototype,"attrs",void 0);var il;let ea=il=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,il.prototype)}};ea=il=f([D({type:B.Sequence,itemType:S.ObjectIdentifier})],ea);class uc{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer,optional:!0})],uc.prototype,"pathLenConstraint",void 0);f([y({type:ea,implicit:!0,context:0,optional:!0})],uc.prototype,"permittedAttrs",void 0);f([y({type:ea,implicit:!0,context:1,optional:!0})],uc.prototype,"excludedAttrs",void 0);f([y({type:S.Boolean,defaultValue:!0})],uc.prototype,"permitUnSpecified",void 0);class Rn{issuer=new Xe;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Xe})],Rn.prototype,"issuer",void 0);f([y({type:S.Integer,converter:Ce})],Rn.prototype,"serial",void 0);f([y({type:S.BitString,optional:!0})],Rn.prototype,"issuerUID",void 0);var al;(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(al||(al={}));class jn{digestedObjectType=al.publicKey;otherObjectTypeID;digestAlgorithm=new W;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.Enumerated})],jn.prototype,"digestedObjectType",void 0);f([y({type:S.ObjectIdentifier,optional:!0})],jn.prototype,"otherObjectTypeID",void 0);f([y({type:W})],jn.prototype,"digestAlgorithm",void 0);f([y({type:S.BitString})],jn.prototype,"objectDigest",void 0);class lc{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:Xe,optional:!0})],lc.prototype,"issuerName",void 0);f([y({type:Rn,context:0,implicit:!0,optional:!0})],lc.prototype,"baseCertificateID",void 0);f([y({type:jn,context:1,implicit:!0,optional:!0})],lc.prototype,"objectDigestInfo",void 0);let ds=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};f([y({type:ie,repeated:"sequence"})],ds.prototype,"v1Form",void 0);f([y({type:lc,context:0,implicit:!0})],ds.prototype,"v2Form",void 0);ds=f([D({type:B.Choice})],ds);class dc{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}}f([y({type:S.GeneralizedTime})],dc.prototype,"notBeforeTime",void 0);f([y({type:S.GeneralizedTime})],dc.prototype,"notAfterTime",void 0);class qo{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:Rn,implicit:!0,context:0,optional:!0})],qo.prototype,"baseCertificateID",void 0);f([y({type:Xe,implicit:!0,context:1,optional:!0})],qo.prototype,"entityName",void 0);f([y({type:jn,implicit:!0,context:2,optional:!0})],qo.prototype,"objectDigestInfo",void 0);var cl;(function(t){t[t.v2=1]="v2"})(cl||(cl={}));class qt{version=cl.v2;holder=new qo;issuer=new ds;signature=new W;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new dc;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],qt.prototype,"version",void 0);f([y({type:qo})],qt.prototype,"holder",void 0);f([y({type:ds})],qt.prototype,"issuer",void 0);f([y({type:W})],qt.prototype,"signature",void 0);f([y({type:S.Integer,converter:Ce})],qt.prototype,"serialNumber",void 0);f([y({type:dc})],qt.prototype,"attrCertValidityPeriod",void 0);f([y({type:Ar,repeated:"sequence"})],qt.prototype,"attributes",void 0);f([y({type:S.BitString,optional:!0})],qt.prototype,"issuerUniqueID",void 0);f([y({type:Vr,optional:!0})],qt.prototype,"extensions",void 0);class fc{acinfo=new qt;signatureAlgorithm=new W;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:qt})],fc.prototype,"acinfo",void 0);f([y({type:W})],fc.prototype,"signatureAlgorithm",void 0);f([y({type:S.BitString})],fc.prototype,"signatureValue",void 0);var ta;(function(t){t[t.unmarked=1]="unmarked",t[t.unclassified=2]="unclassified",t[t.restricted=4]="restricted",t[t.confidential=8]="confidential",t[t.secret=16]="secret",t[t.topSecret=32]="topSecret"})(ta||(ta={}));class ul extends nc{}class sf{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier,implicit:!0,context:0})],sf.prototype,"type",void 0);f([y({type:S.Any,implicit:!0,context:1})],sf.prototype,"value",void 0);class of{policyId="";classList=new ul(ta.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],of.prototype,"policyId",void 0);f([y({type:ul,defaultValue:new ul(ta.unclassified)})],of.prototype,"classList",void 0);f([y({type:sf,repeated:"set"})],of.prototype,"securityCategories",void 0);class pc{cotets;oid;string;constructor(e={}){Object.assign(this,e)}}f([y({type:he})],pc.prototype,"cotets",void 0);f([y({type:S.ObjectIdentifier})],pc.prototype,"oid",void 0);f([y({type:S.Utf8String})],pc.prototype,"string",void 0);class rb{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}}f([y({type:Xe,implicit:!0,context:0,optional:!0})],rb.prototype,"policyAuthority",void 0);f([y({type:pc,repeated:"sequence"})],rb.prototype,"values",void 0);var ll;class hc{targetCertificate=new Rn;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:Rn})],hc.prototype,"targetCertificate",void 0);f([y({type:ie,optional:!0})],hc.prototype,"targetName",void 0);f([y({type:jn,optional:!0})],hc.prototype,"certDigestInfo",void 0);let fs=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};f([y({type:ie,context:0,implicit:!0})],fs.prototype,"targetName",void 0);f([y({type:ie,context:1,implicit:!0})],fs.prototype,"targetGroup",void 0);f([y({type:hc,context:2,implicit:!0})],fs.prototype,"targetCert",void 0);fs=f([D({type:B.Choice})],fs);let dl=ll=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,ll.prototype)}};dl=ll=f([D({type:B.Sequence,itemType:fs})],dl);var fl;let bh=fl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,fl.prototype)}};bh=fl=f([D({type:B.Sequence,itemType:dl})],bh);class nb{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}}f([y({type:Xe,implicit:!0,context:0,optional:!0})],nb.prototype,"roleAuthority",void 0);f([y({type:ie,implicit:!0,context:1})],nb.prototype,"roleName",void 0);class af{service=new ie;ident=new ie;authInfo;constructor(e={}){Object.assign(this,e)}}f([y({type:ie})],af.prototype,"service",void 0);f([y({type:ie})],af.prototype,"ident",void 0);f([y({type:he,optional:!0})],af.prototype,"authInfo",void 0);var pl;class cf{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],cf.prototype,"otherCertFormat",void 0);f([y({type:S.Any})],cf.prototype,"otherCert",void 0);let ps=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};f([y({type:kn})],ps.prototype,"certificate",void 0);f([y({type:fc,context:2,implicit:!0})],ps.prototype,"v2AttrCert",void 0);f([y({type:cf,context:3,implicit:!0})],ps.prototype,"other",void 0);ps=f([D({type:B.Choice})],ps);let ra=pl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,pl.prototype)}};ra=pl=f([D({type:B.Set,itemType:ps})],ra);class Is{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],Is.prototype,"contentType",void 0);f([y({type:S.Any,context:0})],Is.prototype,"content",void 0);let Oo=class{single;any;constructor(e={}){Object.assign(this,e)}};f([y({type:he})],Oo.prototype,"single",void 0);f([y({type:S.Any})],Oo.prototype,"any",void 0);Oo=f([D({type:B.Choice})],Oo);class mc{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],mc.prototype,"eContentType",void 0);f([y({type:Oo,context:0,optional:!0})],mc.prototype,"eContent",void 0);let No=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};f([y({type:he,context:0,implicit:!0,optional:!0})],No.prototype,"value",void 0);f([y({type:he,converter:Ex,context:0,implicit:!0,optional:!0,repeated:"sequence"})],No.prototype,"constructedValue",void 0);No=f([D({type:B.Choice})],No);class zo{contentType="";contentEncryptionAlgorithm=new Zi;encryptedContent;constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],zo.prototype,"contentType",void 0);f([y({type:Zi})],zo.prototype,"contentEncryptionAlgorithm",void 0);f([y({type:No,optional:!0})],zo.prototype,"encryptedContent",void 0);class yc{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],yc.prototype,"keyAttrId",void 0);f([y({type:S.Any,optional:!0})],yc.prototype,"keyAttr",void 0);var hl;class gc{subjectKeyIdentifier=new Lr;date;other;constructor(e={}){Object.assign(this,e)}}f([y({type:Lr})],gc.prototype,"subjectKeyIdentifier",void 0);f([y({type:S.GeneralizedTime,optional:!0})],gc.prototype,"date",void 0);f([y({type:yc,optional:!0})],gc.prototype,"other",void 0);let hs=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:gc,context:0,implicit:!0,optional:!0})],hs.prototype,"rKeyId",void 0);f([y({type:Es,optional:!0})],hs.prototype,"issuerAndSerialNumber",void 0);hs=f([D({type:B.Choice})],hs);class uf{rid=new hs;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:hs})],uf.prototype,"rid",void 0);f([y({type:he})],uf.prototype,"encryptedKey",void 0);let na=hl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,hl.prototype)}};na=hl=f([D({type:B.Sequence,itemType:uf})],na);class lf{algorithm=new W;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:W})],lf.prototype,"algorithm",void 0);f([y({type:S.BitString})],lf.prototype,"publicKey",void 0);let En=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:Lr,context:0,implicit:!0,optional:!0})],En.prototype,"subjectKeyIdentifier",void 0);f([y({type:lf,context:1,implicit:!0,optional:!0})],En.prototype,"originatorKey",void 0);f([y({type:Es,optional:!0})],En.prototype,"issuerAndSerialNumber",void 0);En=f([D({type:B.Choice})],En);class Cs{version=kr.v3;originator=new En;ukm;keyEncryptionAlgorithm=new rr;recipientEncryptedKeys=new na;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],Cs.prototype,"version",void 0);f([y({type:En,context:0})],Cs.prototype,"originator",void 0);f([y({type:he,context:1,optional:!0})],Cs.prototype,"ukm",void 0);f([y({type:rr})],Cs.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:na})],Cs.prototype,"recipientEncryptedKeys",void 0);let ms=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([y({type:Lr,context:0,implicit:!0})],ms.prototype,"subjectKeyIdentifier",void 0);f([y({type:Es})],ms.prototype,"issuerAndSerialNumber",void 0);ms=f([D({type:B.Choice})],ms);class Yo{version=kr.v0;rid=new ms;keyEncryptionAlgorithm=new rr;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],Yo.prototype,"version",void 0);f([y({type:ms})],Yo.prototype,"rid",void 0);f([y({type:rr})],Yo.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:he})],Yo.prototype,"encryptedKey",void 0);class Xo{keyIdentifier=new he;date;other;constructor(e={}){Object.assign(this,e)}}f([y({type:he})],Xo.prototype,"keyIdentifier",void 0);f([y({type:S.GeneralizedTime,optional:!0})],Xo.prototype,"date",void 0);f([y({type:yc,optional:!0})],Xo.prototype,"other",void 0);class Jo{version=kr.v4;kekid=new Xo;keyEncryptionAlgorithm=new rr;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],Jo.prototype,"version",void 0);f([y({type:Xo})],Jo.prototype,"kekid",void 0);f([y({type:rr})],Jo.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:he})],Jo.prototype,"encryptedKey",void 0);class Zo{version=kr.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new rr;encryptedKey=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],Zo.prototype,"version",void 0);f([y({type:sl,context:0,optional:!0})],Zo.prototype,"keyDerivationAlgorithm",void 0);f([y({type:rr})],Zo.prototype,"keyEncryptionAlgorithm",void 0);f([y({type:he})],Zo.prototype,"encryptedKey",void 0);class df{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],df.prototype,"oriType",void 0);f([y({type:S.Any})],df.prototype,"oriValue",void 0);let Fr=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};f([y({type:Yo,optional:!0})],Fr.prototype,"ktri",void 0);f([y({type:Cs,context:1,implicit:!0,optional:!0})],Fr.prototype,"kari",void 0);f([y({type:Jo,context:2,implicit:!0,optional:!0})],Fr.prototype,"kekri",void 0);f([y({type:Zo,context:3,implicit:!0,optional:!0})],Fr.prototype,"pwri",void 0);f([y({type:df,context:4,implicit:!0,optional:!0})],Fr.prototype,"ori",void 0);Fr=f([D({type:B.Choice})],Fr);var ml;let sa=ml=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,ml.prototype)}};sa=ml=f([D({type:B.Set,itemType:Fr})],sa);var yl;class vc{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],vc.prototype,"otherRevInfoFormat",void 0);f([y({type:S.Any})],vc.prototype,"otherRevInfo",void 0);let oa=class{other=new vc;constructor(e={}){Object.assign(this,e)}};f([y({type:vc,context:1,implicit:!0})],oa.prototype,"other",void 0);oa=f([D({type:B.Choice})],oa);let ia=yl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,yl.prototype)}};ia=yl=f([D({type:B.Set,itemType:oa})],ia);class ff{certs;crls;constructor(e={}){Object.assign(this,e)}}f([y({type:ra,context:0,implicit:!0,optional:!0})],ff.prototype,"certs",void 0);f([y({type:ia,context:1,implicit:!0,optional:!0})],ff.prototype,"crls",void 0);var gl;let vl=gl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,gl.prototype)}};vl=gl=f([D({type:B.Set,itemType:xs})],vl);class Qo{version=kr.v0;originatorInfo;recipientInfos=new sa;encryptedContentInfo=new zo;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],Qo.prototype,"version",void 0);f([y({type:ff,context:0,implicit:!0,optional:!0})],Qo.prototype,"originatorInfo",void 0);f([y({type:sa})],Qo.prototype,"recipientInfos",void 0);f([y({type:zo})],Qo.prototype,"encryptedContentInfo",void 0);f([y({type:vl,context:1,implicit:!0,optional:!0})],Qo.prototype,"unprotectedAttrs",void 0);const Xx="1.2.840.113549.1.7.2";var bl;let aa=bl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,bl.prototype)}};aa=bl=f([D({type:B.Set,itemType:Co})],aa);class Os{version=kr.v0;digestAlgorithms=new aa;encapContentInfo=new mc;certificates;crls;signerInfos=new Qi;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],Os.prototype,"version",void 0);f([y({type:aa})],Os.prototype,"digestAlgorithms",void 0);f([y({type:mc})],Os.prototype,"encapContentInfo",void 0);f([y({type:ra,context:0,implicit:!0,optional:!0})],Os.prototype,"certificates",void 0);f([y({type:ia,context:1,implicit:!0,optional:!0})],Os.prototype,"crls",void 0);f([y({type:Qi})],Os.prototype,"signerInfos",void 0);const To="1.2.840.10045.2.1",pf="1.2.840.10045.4.1",sb="1.2.840.10045.4.3.1",hf="1.2.840.10045.4.3.2",mf="1.2.840.10045.4.3.3",yf="1.2.840.10045.4.3.4",wh="1.2.840.10045.3.1.7",Sh="1.3.132.0.34",Ah="1.3.132.0.35";function ei(t){return new W({algorithm:t})}const Jx=ei(pf);ei(sb);const Zx=ei(hf),Qx=ei(mf),eI=ei(yf);let $o=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};f([y({type:S.ObjectIdentifier})],$o.prototype,"fieldType",void 0);f([y({type:S.Any})],$o.prototype,"parameters",void 0);$o=f([D({type:B.Sequence})],$o);class tI extends he{}let ys=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};f([y({type:S.OctetString})],ys.prototype,"a",void 0);f([y({type:S.OctetString})],ys.prototype,"b",void 0);f([y({type:S.BitString,optional:!0})],ys.prototype,"seed",void 0);ys=f([D({type:B.Sequence})],ys);var wl;(function(t){t[t.ecpVer1=1]="ecpVer1"})(wl||(wl={}));let Er=class{version=wl.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};f([y({type:S.Integer})],Er.prototype,"version",void 0);f([y({type:$o})],Er.prototype,"fieldID",void 0);f([y({type:ys})],Er.prototype,"curve",void 0);f([y({type:tI})],Er.prototype,"base",void 0);f([y({type:S.Integer,converter:Ce})],Er.prototype,"order",void 0);f([y({type:S.Integer,optional:!0})],Er.prototype,"cofactor",void 0);Er=f([D({type:B.Sequence})],Er);let Wr=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};f([y({type:S.ObjectIdentifier})],Wr.prototype,"namedCurve",void 0);f([y({type:S.Null})],Wr.prototype,"implicitCurve",void 0);f([y({type:Er})],Wr.prototype,"specifiedCurve",void 0);Wr=f([D({type:B.Choice})],Wr);class bc{version=1;privateKey=new he;parameters;publicKey;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],bc.prototype,"version",void 0);f([y({type:he})],bc.prototype,"privateKey",void 0);f([y({type:Wr,context:0,optional:!0})],bc.prototype,"parameters",void 0);f([y({type:S.BitString,context:1,optional:!0})],bc.prototype,"publicKey",void 0);class ca{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer,converter:Ce})],ca.prototype,"r",void 0);f([y({type:S.Integer,converter:Ce})],ca.prototype,"s",void 0);const lt="1.2.840.113549.1.1",xn=`${lt}.1`,rI=`${lt}.7`,nI=`${lt}.9`,po=`${lt}.10`,sI=`${lt}.2`,oI=`${lt}.4`,ua=`${lt}.5`,iI=`${lt}.14`,Sl=`${lt}.11`,la=`${lt}.12`,da=`${lt}.13`,ob=`${lt}.15`,ib=`${lt}.16`,fa="1.3.14.3.2.26",ab="2.16.840.1.101.3.4.2.4",pa="2.16.840.1.101.3.4.2.1",ha="2.16.840.1.101.3.4.2.2",ma="2.16.840.1.101.3.4.2.3",aI="2.16.840.1.101.3.4.2.5",cI="2.16.840.1.101.3.4.2.6",uI="1.2.840.113549.2.2",lI="1.2.840.113549.2.5",wc=`${lt}.8`;function Ve(t){return new W({algorithm:t,parameters:null})}Ve(uI);Ve(lI);const In=Ve(fa);Ve(ab);Ve(pa);Ve(ha);Ve(ma);Ve(aI);Ve(cI);const cb=new W({algorithm:wc,parameters:V.serialize(In)}),ub=new W({algorithm:nI,parameters:V.serialize(Wi.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});Ve(xn);Ve(sI);Ve(oI);Ve(ua);Ve(ob);Ve(ib);Ve(la);Ve(da);Ve(ob);Ve(ib);class Sc{hashAlgorithm=new W(In);maskGenAlgorithm=new W({algorithm:wc,parameters:V.serialize(In)});pSourceAlgorithm=new W(ub);constructor(e={}){Object.assign(this,e)}}f([y({type:W,context:0,defaultValue:In})],Sc.prototype,"hashAlgorithm",void 0);f([y({type:W,context:1,defaultValue:cb})],Sc.prototype,"maskGenAlgorithm",void 0);f([y({type:W,context:2,defaultValue:ub})],Sc.prototype,"pSourceAlgorithm",void 0);new W({algorithm:rI,parameters:V.serialize(new Sc)});class Cn{hashAlgorithm=new W(In);maskGenAlgorithm=new W({algorithm:wc,parameters:V.serialize(In)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}}f([y({type:W,context:0,defaultValue:In})],Cn.prototype,"hashAlgorithm",void 0);f([y({type:W,context:1,defaultValue:cb})],Cn.prototype,"maskGenAlgorithm",void 0);f([y({type:S.Integer,context:2,defaultValue:20})],Cn.prototype,"saltLength",void 0);f([y({type:S.Integer,context:3,defaultValue:1})],Cn.prototype,"trailerField",void 0);new W({algorithm:po,parameters:V.serialize(new Cn)});class Ac{digestAlgorithm=new W;digest=new he;constructor(e={}){Object.assign(this,e)}}f([y({type:W})],Ac.prototype,"digestAlgorithm",void 0);f([y({type:he})],Ac.prototype,"digest",void 0);var Al;class kc{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer,converter:Ce})],kc.prototype,"prime",void 0);f([y({type:S.Integer,converter:Ce})],kc.prototype,"exponent",void 0);f([y({type:S.Integer,converter:Ce})],kc.prototype,"coefficient",void 0);let kl=Al=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Al.prototype)}};kl=Al=f([D({type:B.Sequence,itemType:kc})],kl);class ur{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],ur.prototype,"version",void 0);f([y({type:S.Integer,converter:Ce})],ur.prototype,"modulus",void 0);f([y({type:S.Integer,converter:Ce})],ur.prototype,"publicExponent",void 0);f([y({type:S.Integer,converter:Ce})],ur.prototype,"privateExponent",void 0);f([y({type:S.Integer,converter:Ce})],ur.prototype,"prime1",void 0);f([y({type:S.Integer,converter:Ce})],ur.prototype,"prime2",void 0);f([y({type:S.Integer,converter:Ce})],ur.prototype,"exponent1",void 0);f([y({type:S.Integer,converter:Ce})],ur.prototype,"exponent2",void 0);f([y({type:S.Integer,converter:Ce})],ur.prototype,"coefficient",void 0);f([y({type:kl,optional:!0})],ur.prototype,"otherPrimeInfos",void 0);class gf{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer,converter:Ce})],gf.prototype,"modulus",void 0);f([y({type:S.Integer,converter:Ce})],gf.prototype,"publicExponent",void 0);var El;(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(El||(El={}));const st=El;var xl=function(t,e){return xl=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var s in n)n.hasOwnProperty(s)&&(r[s]=n[s])},xl(t,e)};function vf(t,e){xl(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function dI(t,e,r,n){function s(o){return o instanceof r?o:new r(function(i){i(o)})}return new(r||(r=Promise))(function(o,i){function a(l){try{u(n.next(l))}catch(d){i(d)}}function c(l){try{u(n.throw(l))}catch(d){i(d)}}function u(l){l.done?o(l.value):s(l.value).then(a,c)}u((n=n.apply(t,[])).next())})}function fI(t,e){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,s,o,i;return i={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,s&&(o=u[0]&2?s.return:u[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,u[1])).done)return o;switch(s=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,s=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){r.label=u[1];break}if(u[0]===6&&r.label<o[1]){r.label=o[1],o=u;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(u);break}o[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],s=0}finally{n=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function hi(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function ya(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(i)throw i.error}}return o}function sn(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(ya(arguments[e]));return t}var pI="injectionTokens";function hI(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata(pI,t)||{};return Object.keys(r).forEach(function(n){e[+n]=r[n]}),e}function lb(t){return!!t.useClass}function Il(t){return!!t.useFactory}var db=(function(){function t(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return t.prototype.createProxy=function(e){var r=this,n={},s=!1,o,i=function(){return s||(o=e(r.wrap()),s=!0),o};return new Proxy(n,this.createHandler(i))},t.prototype.createHandler=function(e){var r={},n=function(s){r[s]=function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];o[0]=e();var a=Reflect[s];return a.apply(void 0,sn(o))}};return this.reflectMethods.forEach(n),r},t})();function Hn(t){return typeof t=="string"||typeof t=="symbol"}function mI(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function kh(t){return typeof t=="object"&&"token"in t&&"transform"in t}function yI(t){return typeof t=="function"||t instanceof db}function Ei(t){return!!t.useToken}function xi(t){return t.useValue!=null}function gI(t){return lb(t)||xi(t)||Ei(t)||Il(t)}var bf=(function(){function t(){this._registryMap=new Map}return t.prototype.entries=function(){return this._registryMap.entries()},t.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},t.prototype.get=function(e){this.ensure(e);var r=this._registryMap.get(e);return r[r.length-1]||null},t.prototype.set=function(e,r){this.ensure(e),this._registryMap.get(e).push(r)},t.prototype.setAll=function(e,r){this._registryMap.set(e,r)},t.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},t.prototype.clear=function(){this._registryMap.clear()},t.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},t})(),vI=(function(t){vf(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(bf),mi=(function(){function t(){this.scopedResolutions=new Map}return t})();function bI(t,e){if(t===null)return"at position #"+e;var r=t.split(",")[e].trim();return'"'+r+'" at position #'+e}function wI(t,e,r){return r===void 0&&(r=" "),sn([t],e.message.split(`
116
372
  `).map(function(n){return r+n})).join(`
117
- `)}function Px(t,e,r){var n=sa(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),o=n[1],s=o===void 0?null:o,i=Dx(s,e);return Lx("Cannot inject the dependency "+i+' of "'+t.name+'" constructor. Reason:',r)}function Ux(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var Vx=(function(t){rf(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(nf),Hx=(function(t){rf(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(nf),Fx=(function(){function t(){this.preResolution=new Vx,this.postResolution=new Hx}return t})(),Yv=new Map,Wx=(function(){function t(e){this.parent=e,this._registry=new jx,this.interceptors=new Fx,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,r,n){n===void 0&&(n={lifecycle:nt.Transient}),this.ensureNotDisposed();var o;if(_x(r)?o=r:o={useClass:r},hi(o))for(var s=[e],i=o;i!=null;){var a=i.useToken;if(s.includes(a))throw new Error("Token registration cycle detected! "+Zr(s,[a]).join(" -> "));s.push(a);var c=this._registry.get(a);c&&hi(c.provider)?i=c.provider:i=null}if((n.lifecycle===nt.Singleton||n.lifecycle==nt.ContainerScoped||n.lifecycle==nt.ResolutionScoped)&&(mi(o)||dl(o)))throw new Error('Cannot use lifecycle "'+nt[n.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:o,options:n}),this},t.prototype.registerType=function(e,r){return this.ensureNotDisposed(),Mn(r)?this.register(e,{useToken:r}):this.register(e,{useClass:r})},t.prototype.registerInstance=function(e,r){return this.ensureNotDisposed(),this.register(e,{useValue:r})},t.prototype.registerSingleton=function(e,r){if(this.ensureNotDisposed(),Mn(e)){if(Mn(r))return this.register(e,{useToken:r},{lifecycle:nt.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:nt.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var n=e;return r&&!Mn(r)&&(n=r),this.register(e,{useClass:n},{lifecycle:nt.Singleton})},t.prototype.resolve=function(e,r,n){r===void 0&&(r=new si),n===void 0&&(n=!1),this.ensureNotDisposed();var o=this.getRegistration(e);if(!o&&Mn(e)){if(n)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),o){var s=this.resolveRegistration(o,r);return this.executePostResolutionInterceptor(e,s,"Single"),s}if(Mx(e)){var s=this.construct(e,r);return this.executePostResolutionInterceptor(e,s,"Single"),s}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},t.prototype.executePreResolutionInterceptor=function(e,r){var n,o;if(this.interceptors.preResolution.has(e)){var s=[];try{for(var i=oi(this.interceptors.preResolution.getAll(e)),a=i.next();!a.done;a=i.next()){var c=a.value;c.options.frequency!="Once"&&s.push(c),c.callback(e,r)}}catch(u){n={error:u}}finally{try{a&&!a.done&&(o=i.return)&&o.call(i)}finally{if(n)throw n.error}}this.interceptors.preResolution.setAll(e,s)}},t.prototype.executePostResolutionInterceptor=function(e,r,n){var o,s;if(this.interceptors.postResolution.has(e)){var i=[];try{for(var a=oi(this.interceptors.postResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var u=c.value;u.options.frequency!="Once"&&i.push(u),u.callback(e,r,n)}}catch(d){o={error:d}}finally{try{c&&!c.done&&(s=a.return)&&s.call(a)}finally{if(o)throw o.error}}this.interceptors.postResolution.setAll(e,i)}},t.prototype.resolveRegistration=function(e,r){if(this.ensureNotDisposed(),e.options.lifecycle===nt.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);var n=e.options.lifecycle===nt.Singleton,o=e.options.lifecycle===nt.ContainerScoped,s=n||o,i;return mi(e.provider)?i=e.provider.useValue:hi(e.provider)?i=s?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):qv(e.provider)?i=s?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):dl(e.provider)?i=e.provider.useFactory(this):i=this.construct(e.provider,r),e.options.lifecycle===nt.ResolutionScoped&&r.scopedResolutions.set(e,i),i},t.prototype.resolveAll=function(e,r,n){var o=this;r===void 0&&(r=new si),n===void 0&&(n=!1),this.ensureNotDisposed();var s=this.getAllRegistrations(e);if(!s&&Mn(e)){if(n)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),s){var i=s.map(function(c){return o.resolveRegistration(c,r)});return this.executePostResolutionInterceptor(e,i,"All"),i}var a=[this.construct(e,r)];return this.executePostResolutionInterceptor(e,a,"All"),a},t.prototype.isRegistered=function(e,r){return r===void 0&&(r=!1),this.ensureNotDisposed(),this._registry.has(e)||r&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},t.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},t.prototype.clearInstances=function(){var e,r;this.ensureNotDisposed();try{for(var n=oi(this._registry.entries()),o=n.next();!o.done;o=n.next()){var s=sa(o.value,2),i=s[0],a=s[1];this._registry.setAll(i,a.filter(function(c){return!mi(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}},t.prototype.createChildContainer=function(){var e,r;this.ensureNotDisposed();var n=new t(this);try{for(var o=oi(this._registry.entries()),s=o.next();!s.done;s=o.next()){var i=sa(s.value,2),a=i[0],c=i[1];c.some(function(u){var d=u.options;return d.lifecycle===nt.ContainerScoped})&&n._registry.setAll(a,c.map(function(u){return u.options.lifecycle===nt.ContainerScoped?{provider:u.provider,options:u.options}:u}))}}catch(u){e={error:u}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return n},t.prototype.beforeResolution=function(e,r,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:r,options:n})},t.prototype.afterResolution=function(e,r,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:r,options:n})},t.prototype.dispose=function(){return Nx(this,void 0,void 0,function(){var e;return Tx(this,function(r){switch(r.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(n){var o=n.dispose();o&&e.push(o)}),[4,Promise.all(e)];case 1:return r.sent(),[2]}})})},t.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},t.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},t.prototype.construct=function(e,r){var n=this;if(e instanceof zv)return e.createProxy(function(s){return n.resolve(s,r)});var o=(function(){var s=Yv.get(e);if(!s||s.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=s.map(n.resolveParams(r,e));return new(e.bind.apply(e,Zr([void 0],i)))})();return Ux(o)&&this.disposables.add(o),o},t.prototype.resolveParams=function(e,r){var n=this;return function(o,s){var i,a,c;try{return Rx(o)?ih(o)?o.multiple?(i=n.resolve(o.transform)).transform.apply(i,Zr([n.resolveAll(o.token,new si,o.isOptional)],o.transformArgs)):(a=n.resolve(o.transform)).transform.apply(a,Zr([n.resolve(o.token,e,o.isOptional)],o.transformArgs)):o.multiple?n.resolveAll(o.token,new si,o.isOptional):n.resolve(o.token,e,o.isOptional):ih(o)?(c=n.resolve(o.transform,e)).transform.apply(c,Zr([n.resolve(o.token,e)],o.transformArgs)):n.resolve(o,e)}catch(u){throw new Error(Px(r,s,u))}}},t.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},t})(),Le=new Wx;function ko(t){return function(e){Yv.set(e,Bx(e))}}if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var fl;class fc{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}}f([y({type:b.ObjectIdentifier})],fc.prototype,"attrId",void 0);f([y({type:b.Any,repeated:"set"})],fc.prototype,"attrValues",void 0);let ah=fl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,fl.prototype)}};ah=fl=f([j({type:R.Sequence,itemType:fc})],ah);var pl;let ch=pl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,pl.prototype)}};ch=pl=f([j({type:R.Sequence,itemType:wo})],ch);class Xv{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Xv.prototype,"certId",void 0);f([y({type:b.Any,context:0})],Xv.prototype,"certValue",void 0);class Jv{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],Jv.prototype,"crlId",void 0);f([y({type:b.Any,context:0})],Jv.prototype,"crltValue",void 0);class Zv extends he{}let pc=class{encryptionAlgorithm=new W;encryptedData=new Zv;constructor(e={}){Object.assign(this,e)}};f([y({type:W})],pc.prototype,"encryptionAlgorithm",void 0);f([y({type:Zv})],pc.prototype,"encryptedData",void 0);var hl,ml;(function(t){t[t.v1=0]="v1"})(ml||(ml={}));class Qv extends he{}let ia=hl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,hl.prototype)}};ia=hl=f([j({type:R.Sequence,itemType:gr})],ia);let qs=class{version=ml.v1;privateKeyAlgorithm=new W;privateKey=new Qv;attributes;constructor(e={}){Object.assign(this,e)}};f([y({type:b.Integer})],qs.prototype,"version",void 0);f([y({type:W})],qs.prototype,"privateKeyAlgorithm",void 0);f([y({type:Qv})],qs.prototype,"privateKey",void 0);f([y({type:ia,implicit:!0,context:0,optional:!0})],qs.prototype,"attributes",void 0);let uh=class extends qs{};uh=f([j({type:R.Sequence})],uh);let lh=class extends pc{};lh=f([j({type:R.Sequence})],lh);class eb{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],eb.prototype,"secretTypeId",void 0);f([y({type:b.Any,context:0})],eb.prototype,"secretValue",void 0);class zs{mac=new lc;macSalt=new he;iterations=1;constructor(e={}){Object.assign(this,e)}}f([y({type:lc})],zs.prototype,"mac",void 0);f([y({type:he})],zs.prototype,"macSalt",void 0);f([y({type:b.Integer,defaultValue:1})],zs.prototype,"iterations",void 0);class hc{version=3;authSafe=new wo;macData=new zs;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],hc.prototype,"version",void 0);f([y({type:wo})],hc.prototype,"authSafe",void 0);f([y({type:zs,optional:!0})],hc.prototype,"macData",void 0);var yl;class mc{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}}f([y({type:b.ObjectIdentifier})],mc.prototype,"bagId",void 0);f([y({type:b.Any,context:0})],mc.prototype,"bagValue",void 0);f([y({type:fc,repeated:"set",optional:!0})],mc.prototype,"bagAttributes",void 0);let dh=yl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,yl.prototype)}};dh=yl=f([j({type:R.Sequence,itemType:mc})],dh);var gl,vl,bl;const tb="1.2.840.113549.1.9",rb=`${tb}.7`,of=`${tb}.14`;let aa=class extends Ge{ia5String;constructor(e={}){super(e)}toString(){return this.ia5String||super.toString()}};f([y({type:b.IA5String})],aa.prototype,"ia5String",void 0);aa=f([j({type:R.Choice})],aa);let fh=class extends wo{};fh=f([j({type:R.Sequence})],fh);let ph=class extends hc{};ph=f([j({type:R.Sequence})],ph);let hh=class extends pc{};hh=f([j({type:R.Sequence})],hh);let wl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:b.IA5String})],wl.prototype,"value",void 0);wl=f([j({type:R.Choice})],wl);let mh=class extends aa{};mh=f([j({type:R.Choice})],mh);let yh=class extends Ge{};yh=f([j({type:R.Choice})],yh);let Al=class{value;constructor(e=new Date){this.value=e}};f([y({type:b.GeneralizedTime})],Al.prototype,"value",void 0);Al=f([j({type:R.Choice})],Al);let gh=class extends Ge{};gh=f([j({type:R.Choice})],gh);let Sl=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};f([y({type:b.PrintableString})],Sl.prototype,"value",void 0);Sl=f([j({type:R.Choice})],Sl);let ca=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:b.PrintableString})],ca.prototype,"value",void 0);ca=f([j({type:R.Choice})],ca);let vh=class extends ca{};vh=f([j({type:R.Choice})],vh);let bh=class extends Ge{};bh=f([j({type:R.Choice})],bh);let kl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:b.ObjectIdentifier})],kl.prototype,"value",void 0);kl=f([j({type:R.Choice})],kl);let wh=class extends We{};wh=f([j({type:R.Choice})],wh);let El=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};f([y({type:b.Integer})],El.prototype,"value",void 0);El=f([j({type:R.Choice})],El);let Ah=class extends sr{};Ah=f([j({type:R.Sequence})],Ah);let ua=class extends Ge{};ua=f([j({type:R.Choice})],ua);let Sh=gl=class extends Dr{constructor(e){super(e),Object.setPrototypeOf(this,gl.prototype)}};Sh=gl=f([j({type:R.Sequence})],Sh);let kh=vl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,vl.prototype)}};kh=vl=f([j({type:R.Set,itemType:bo})],kh);let xl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:b.BmpString})],xl.prototype,"value",void 0);xl=f([j({type:R.Choice})],xl);let Il=class extends W{};Il=f([j({type:R.Sequence})],Il);let Eh=bl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,bl.prototype)}};Eh=bl=f([j({type:R.Sequence,itemType:Il})],Eh);var Ol,Cl;let xh=Ol=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ol.prototype)}};xh=Ol=f([j({type:R.Sequence,itemType:W})],xh);let Ih=Cl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Cl.prototype)}};Ih=Cl=f([j({type:R.Sequence,itemType:b.BitString})],Ih);var Nl,Tl;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2"})(Tl||(Tl={}));let Oh=class extends W{};Oh=f([j({type:R.Sequence})],Oh);let er=class{version=Tl.v1;privateKeyAlgorithm=new W;privateKey=new ArrayBuffer(0);attributes;publicKey};f([y({type:b.Integer})],er.prototype,"version",void 0);f([y({type:W})],er.prototype,"privateKeyAlgorithm",void 0);f([y({type:b.OctetString})],er.prototype,"privateKey",void 0);f([y({type:ia,context:0,implicit:!0,optional:!0})],er.prototype,"attributes",void 0);f([y({type:b.BitString,context:1,implicit:!0,optional:!0})],er.prototype,"publicKey",void 0);er=f([j({type:R.Sequence})],er);let Ch=class extends er{};Ch=f([j({type:R.Sequence})],Ch);let Nh=Nl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Nl.prototype)}};Nh=Nl=f([j({type:R.Sequence,itemType:er})],Nh);var $l,Bl;let Th=class extends W{};Th=f([j({type:R.Sequence})],Th);let $h=$l=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,$l.prototype)}};$h=$l=f([j({type:R.Sequence,itemType:Ot})],$h);let Bh=Bl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Bl.prototype)}};Bh=Bl=f([j({type:R.Sequence,itemType:er})],Bh);const tt="2.16.840.1.101.3.4.3",Rh=`${tt}.17`,Mh=`${tt}.18`,_h=`${tt}.19`,jh=`${tt}.20`,Dh=`${tt}.21`,Lh=`${tt}.22`,Ph=`${tt}.23`,Uh=`${tt}.24`,Vh=`${tt}.25`,Hh=`${tt}.26`,Fh=`${tt}.27`,Wh=`${tt}.28`,Kh=`${tt}.29`,Gh=`${tt}.30`,qh=`${tt}.31`;var Rl;let la=Rl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Rl.prototype)}};la=Rl=f([j({type:R.Sequence,itemType:gr})],la);class Eo{version=0;subject=new Re;subjectPKInfo=new Ot;attributes=new la;constructor(e={}){Object.assign(this,e)}}f([y({type:b.Integer})],Eo.prototype,"version",void 0);f([y({type:Re})],Eo.prototype,"subject",void 0);f([y({type:Ot})],Eo.prototype,"subjectPKInfo",void 0);f([y({type:la,implicit:!0,context:0,optional:!0})],Eo.prototype,"attributes",void 0);class Es{certificationRequestInfo=new Eo;certificationRequestInfoRaw;signatureAlgorithm=new W;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Eo,raw:!0})],Es.prototype,"certificationRequestInfo",void 0);f([y({type:W})],Es.prototype,"signatureAlgorithm",void 0);f([y({type:b.BitString})],Es.prototype,"signature",void 0);const Tn="crypto.algorithm";class Kx{getAlgorithms(){return Le.resolveAll(Tn)}toAsnAlgorithm(e){const r={...e};r.hash&&typeof r.hash=="string"&&(r.hash={name:r.hash});for(const n of this.getAlgorithms()){const o=n.toAsnAlgorithm(r);if(o)return o}if(/^[0-9.]+$/.test(e.name)){const n=new W({algorithm:e.name});if("parameters"in e){const o=e;n.parameters=o.parameters}return n}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const n of this.getAlgorithms()){const o=n.toWebAlgorithm(e);if(o)return o}return{name:e.algorithm,parameters:e.parameters}}}const An="crypto.algorithmProvider";Le.registerSingleton(An,Kx);var yi;const lt="1.3.36.3.3.2.8.1.1",zh=`${lt}.1`,Yh=`${lt}.2`,Xh=`${lt}.3`,Jh=`${lt}.4`,Zh=`${lt}.5`,Qh=`${lt}.6`,em=`${lt}.7`,tm=`${lt}.8`,rm=`${lt}.9`,nm=`${lt}.10`,om=`${lt}.11`,sm=`${lt}.12`,im=`${lt}.13`,am=`${lt}.14`,cm="brainpoolP160r1",um="brainpoolP160t1",lm="brainpoolP192r1",dm="brainpoolP192t1",fm="brainpoolP224r1",pm="brainpoolP224t1",hm="brainpoolP256r1",mm="brainpoolP256t1",ym="brainpoolP320r1",gm="brainpoolP320t1",vm="brainpoolP384r1",bm="brainpoolP384t1",wm="brainpoolP512r1",Am="brainpoolP512t1",Oe="ECDSA";let xs=yi=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case Oe.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return mx;case"sha-256":return yx;case"sha-384":return gx;case"sha-512":return vx}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=nh;break;case"K-256":r=yi.SECP256K1;break;case"P-384":r=oh;break;case"P-521":r=sh;break;case cm:r=zh;break;case um:r=Yh;break;case lm:r=Xh;break;case dm:r=Jh;break;case fm:r=Zh;break;case pm:r=Qh;break;case hm:r=em;break;case mm:r=tm;break;case ym:r=rm;break;case gm:r=nm;break;case vm:r=om;break;case bm:r=sm;break;case wm:r=im;break;case Am:r=am;break}if(r)return new W({algorithm:Ss,parameters:H.serialize(new Pr({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Jd:return{name:Oe,hash:{name:"SHA-1"}};case Zd:return{name:Oe,hash:{name:"SHA-256"}};case Qd:return{name:Oe,hash:{name:"SHA-384"}};case ef:return{name:Oe,hash:{name:"SHA-512"}};case Ss:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(H.parse(e.parameters,Pr).namedCurve){case nh:return{name:Oe,namedCurve:"P-256"};case yi.SECP256K1:return{name:Oe,namedCurve:"K-256"};case oh:return{name:Oe,namedCurve:"P-384"};case sh:return{name:Oe,namedCurve:"P-521"};case zh:return{name:Oe,namedCurve:cm};case Yh:return{name:Oe,namedCurve:um};case Xh:return{name:Oe,namedCurve:lm};case Jh:return{name:Oe,namedCurve:dm};case Zh:return{name:Oe,namedCurve:fm};case Qh:return{name:Oe,namedCurve:pm};case em:return{name:Oe,namedCurve:hm};case tm:return{name:Oe,namedCurve:mm};case rm:return{name:Oe,namedCurve:ym};case nm:return{name:Oe,namedCurve:gm};case om:return{name:Oe,namedCurve:vm};case sm:return{name:Oe,namedCurve:bm};case im:return{name:Oe,namedCurve:wm};case am:return{name:Oe,namedCurve:Am}}}}return null}};xs.SECP256K1="1.3.132.0.10";xs=yi=f([ko()],xs);Le.registerSingleton(Tn,xs);const nb=Symbol("name"),ob=Symbol("value");class me{constructor(e,r={},n=""){this[nb]=e,this[ob]=n;for(const o in r)this[o]=r[o]}}me.NAME=nb;me.VALUE=ob;class Gx{static toTextObject(e){const r=new me("Algorithm Identifier",{},Wr.toString(e.algorithm));if(e.parameters)if(e.algorithm===Ss){const n=new xs().toWebAlgorithm(e);n&&"namedCurve"in n?r["Named Curve"]=n.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}}class Wr{static toString(e){const r=this.items[e];return r||e}}Wr.items={[ta]:"sha1",[Wv]:"sha224",[ra]:"sha256",[na]:"sha384",[oa]:"sha512",[vn]:"rsaEncryption",[Zi]:"sha1WithRSAEncryption",[Ex]:"sha224WithRSAEncryption",[il]:"sha256WithRSAEncryption",[Qi]:"sha384WithRSAEncryption",[ea]:"sha512WithRSAEncryption",[Ss]:"ecPublicKey",[Jd]:"ecdsaWithSHA1",[Vv]:"ecdsaWithSHA224",[Zd]:"ecdsaWithSHA256",[Qd]:"ecdsaWithSHA384",[ef]:"ecdsaWithSHA512",[cx]:"TLS WWW server authentication",[ux]:"TLS WWW client authentication",[lx]:"Code Signing",[dx]:"E-mail Protection",[fx]:"Time Stamping",[px]:"OCSP Signing",[hx]:"Signed Data"};class Sn{static serialize(e){return this.serializeObj(e).join(`
118
- `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){const n=[];let o=this.pad(r++),s="";const i=e[me.VALUE];i&&(s=` ${i}`),n.push(`${o}${e[me.NAME]}:${s}`),o=this.pad(r);for(const a in e){if(typeof a=="symbol")continue;const c=e[a],u=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")n.push(`${o}${u}${c}`);else if(c instanceof Date)n.push(`${o}${u}${c.toUTCString()}`);else if(Array.isArray(c))for(const d of c)d[me.NAME]=a,n.push(...this.serializeObj(d,r));else if(c instanceof me)c[me.NAME]=a,n.push(...this.serializeObj(c,r));else if(K.isBufferSource(c))a?(n.push(`${o}${u}`),n.push(...this.serializeBufferSource(c,r+1))):n.push(...this.serializeBufferSource(c,r));else if("toTextObject"in c){const d=c.toTextObject();d[me.NAME]=a,n.push(...this.serializeObj(d,r))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return n}static serializeBufferSource(e,r=0){const n=this.pad(r),o=K.toUint8Array(e),s=[];for(let i=0;i<o.length;){const a=[];for(let c=0;c<16&&i<o.length;c++){c===8&&a.push("");const u=o[i++].toString(16).padStart(2,"0");a.push(u)}s.push(`${n}${a.join(" ")}`)}return s}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}Sn.oidSerializer=Wr;Sn.algorithmSerializer=Gx;var _n,jn;class Kr{get parseOptions(){return oe(this,jn,"f")}get rawData(){return oe(this,_n,"f")||ke(this,_n,H.serialize(this.asn),"f"),oe(this,_n,"f")}constructor(...e){_n.set(this,void 0),jn.set(this,void 0),K.isBufferSource(e[0])?(ke(this,jn,e[2],"f"),this.asn=H.parse(e[0],e[1],e[2]),ke(this,_n,K.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(ke(this,jn,e[1],"f"),this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof Kr?bk(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return H.toString(this.rawData,oe(this,jn,"f"));case"text":return Sn.serialize(this.toTextObject());case"hex":return ee.ToHex(this.rawData);case"base64":return ee.ToBase64(this.rawData);case"base64url":return ee.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new me(this.getTextName(),{},e)}}_n=new WeakMap,jn=new WeakMap;Kr.NAME="ASN";class St extends Kr{constructor(...e){let r,n;K.isBufferSource(e[0])?(r=K.toArrayBuffer(e[0]),n=e[1]):r=H.serialize(new Vt({extnID:e[0],critical:e[1],extnValue:new he(K.toArrayBuffer(e[2]))})),super(r,Vt,n)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[me.NAME]===St.NAME&&(e[me.NAME]=Wr.toString(this.type)),e}}var sb;class $r{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[sb]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set($r.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set($r.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,r){return this.items.forEach(e,r)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=$r.DEFAULT){const r=this.items.get(e.toLowerCase());if(!r)throw new Error(`Cannot get Crypto by name '${e}'`);return r}set(e,r){if(typeof e=="string"){if(!r)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),r)}else this.items.set($r.DEFAULT,e);return this}}sb=Symbol.toStringTag;$r.DEFAULT="default";const at=new $r,qx=/^[0-2](?:\.[1-9][0-9]*)+$/;function zx(t){return new RegExp(qx).test(t)}class ib{constructor(e={}){this.items={};for(const r in e)this.register(r,e[r])}get(e){return this.items[e]||null}findId(e){return zx(e)?e:this.get(e)}register(e,r){this.items[e]=r,this.items[r]=e}}const ct=new ib;ct.register("CN","2.5.4.3");ct.register("L","2.5.4.7");ct.register("ST","2.5.4.8");ct.register("O","2.5.4.10");ct.register("OU","2.5.4.11");ct.register("C","2.5.4.6");ct.register("DC","0.9.2342.19200300.100.1.25");ct.register("E","1.2.840.113549.1.9.1");ct.register("G","2.5.4.42");ct.register("I","2.5.4.43");ct.register("SN","2.5.4.4");ct.register("T","2.5.4.12");function Yx(t,e){return`\\${ee.ToHex(ee.FromUtf8String(e)).toUpperCase()}`}function Xx(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,Yx)}class Dt{static isASCII(e){for(let r=0;r<e.length;r++)if(e.charCodeAt(r)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,r={}){this.extraNames=new ib,this.asn=new Re;for(const n in r)if(Object.prototype.hasOwnProperty.call(r,n)){const o=r[n];this.extraNames.register(n,o)}typeof e=="string"?this.asn=this.fromString(e):e instanceof Re?this.asn=e:K.isBufferSource(e)?this.asn=H.parse(e,Re):this.asn=this.fromJSON(e)}getField(e){const r=this.extraNames.findId(e)||ct.findId(e),n=[];for(const o of this.asn)for(const s of o)s.type===r&&n.push(s.value.toString());return n}getName(e){return this.extraNames.get(e)||ct.get(e)}toString(){return this.asn.map(e=>e.map(r=>{const n=this.getName(r.type)||r.type,o=r.value.anyValue?`#${ee.ToHex(r.value.anyValue)}`:Xx(r.value.toString());return`${n}=${o}`}).join("+")).join(", ")}toJSON(){var e;const r=[];for(const n of this.asn){const o={};for(const s of n){const i=this.getName(s.type)||s.type;(e=o[i])!==null&&e!==void 0||(o[i]=[]),o[i].push(s.value.anyValue?`#${ee.ToHex(s.value.anyValue)}`:s.value.toString())}r.push(o)}return r}fromString(e){const r=new Re,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let o=null,s=",";for(;o=n.exec(`${e},`);){let[,i,a]=o;const c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),o[3]=c);const u=o[3];i=this.getTypeOid(i);const d=this.createAttribute(i,a);s==="+"?r[r.length-1].push(d):r.push(new ro([d])),s=u}return r}fromJSON(e){const r=new Re;for(const n of e){const o=new ro;for(const s in n){const i=this.getTypeOid(s),a=n[s];for(const c of a){const u=this.createAttribute(i,c);o.push(u)}}r.push(o)}return r}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,r){const n=new Ga({type:e});if(typeof r=="object")for(const o in r)switch(o){case"ia5String":n.value.ia5String=r[o];break;case"utf8String":n.value.utf8String=r[o];break;case"universalString":n.value.universalString=r[o];break;case"bmpString":n.value.bmpString=r[o];break;case"printableString":n.value.printableString=r[o];break}else if(r[0]==="#")n.value.anyValue=ee.FromHex(r.slice(1));else{const o=this.processStringValue(r);e===this.getName("E")||e===this.getName("DC")?n.value.ia5String=o:Dt.isPrintableString(o)?n.value.printableString=o:n.value.utf8String=o}return n}processStringValue(e){const r=/"(.*?[^\\])?"/.exec(e);return r&&(e=r[1]),e.replace(/\\0a/gi,`
119
- `).replace(/\\0d/gi,"\r").replace(/\\0g/gi," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return H.serialize(this.asn)}async getThumbprint(e,r){let n,o="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(o=e,n=r)),n??(n=at.get()),await n.subtle.digest(o,this.toArrayBuffer())}}const ab="Cannot initialize GeneralName from ASN.1 data.",Sm=`${ab} Unsupported string format in use.`,Jx=`${ab} Value doesn't match to GUID regular expression.`,km=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Em="1.3.6.1.4.1.311.25.1",xm="1.3.6.1.4.1.311.20.2.3",Wc="dns",Kc="dn",Gc="email",qc="ip",zc="url",Yc="guid",Xc="upn",ii="id";class Br extends Kr{constructor(...e){let r;if(e.length===2)switch(e[0]){case Kc:{const n=new Dt(e[1]).toArrayBuffer(),o=H.parse(n,Re);r=new ie({directoryName:o});break}case Wc:r=new ie({dNSName:e[1]});break;case Gc:r=new ie({rfc822Name:e[1]});break;case Yc:{const n=new RegExp(km,"i").exec(e[1]);if(!n)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const o=n.slice(1).map((s,i)=>i<3?ee.ToHex(new Uint8Array(ee.FromHex(s)).reverse()):s).join("");r=new ie({otherName:new vs({typeId:Em,value:H.serialize(new he(ee.FromHex(o)))})});break}case qc:r=new ie({iPAddress:e[1]});break;case ii:r=new ie({registeredID:e[1]});break;case Xc:{r=new ie({otherName:new vs({typeId:xm,value:H.serialize(kv.toASN(e[1]))})});break}case zc:r=new ie({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else K.isBufferSource(e[0])?r=H.parse(e[0],ie):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=Wc,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Gc,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=qc,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=zc,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=ii,this.value=e.registeredID;else if(e.directoryName!=null)this.type=Kc,this.value=new Dt(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===Em){this.type=Yc;const r=H.parse(e.otherName.value,he),n=new RegExp(km,"i").exec(ee.ToHex(r));if(!n)throw new Error(Jx);this.value=n.slice(1).map((o,s)=>s<3?ee.ToHex(new Uint8Array(ee.FromHex(o)).reverse()):o).join("-")}else if(e.otherName.typeId===xm)this.type=Xc,this.value=H.parse(e.otherName.value,Ge).toString();else throw new Error(Sm);else throw new Error(Sm)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Kc:case Wc:case Yc:case qc:case ii:case Xc:case zc:e=this.type.toUpperCase();break;case Gc:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===ii&&(r=Wr.toString(r)),new me(e,void 0,r)}}class kn extends Kr{constructor(e){let r;if(e instanceof Ye)r=e;else if(Array.isArray(e)){const n=[];for(const o of e)if(o instanceof ie)n.push(o);else{const s=H.parse(new Br(o.type,o.value).rawData,ie);n.push(s)}r=new Ye(n)}else if(K.isBufferSource(e))r=H.parse(e,Ye);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(r)}onInit(e){const r=[];for(const n of e){let o=null;try{o=new Br(n)}catch{continue}r.push(o)}this.items=r}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const r of this.items){const n=r.toTextObject();let o=e[n[me.NAME]];Array.isArray(o)||(o=[],e[n[me.NAME]]=o),o.push(n)}return e}}kn.NAME="GeneralNames";const is="-{5}",Is="\\n",Zx=`[^${Is}]+`,Qx=`${is}BEGIN (${Zx}(?=${is}))${is}`,eI=`${is}END \\1${is}`,lo="\\n",tI=`[^:${Is}]+`,rI=`(?:[^${Is}]+${lo}(?: +[^${Is}]+${lo})*)`,nI="[a-zA-Z0-9=+/]+",oI=`(?:${nI}${lo})+`,Im=`${Qx}${lo}(?:((?:${tI}: ${rI})+))?${lo}?(${oI})${eI}`,sI=new RegExp(`[${Is}]+`,"g");class gt{static isPem(e){return typeof e=="string"&&new RegExp(Im,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const r=new RegExp(Im,"g"),n=[];let o=null;for(;o=r.exec(e);){const s=o[3].replace(sI,""),i={type:o[1],headers:[],rawData:ee.FromBase64(s)},a=o[2];if(a){const c=a.split(new RegExp(lo,"g"));let u=null;for(const d of c){const[l,m]=d.split(/:(.*)/);if(m===void 0){if(!u)throw new Error("Cannot parse PEM string. Incorrect header value");u.value+=l.trim()}else u&&i.headers.push(u),u={key:l,value:m.trim()}}u&&i.headers.push(u)}n.push(i)}return n}static decode(e){return this.decodeWithHeaders(e).map(n=>n.rawData)}static decodeFirst(e){const r=this.decode(e);if(!r.length)throw new RangeError("PEM string doesn't contain any objects");return r[0]}static encode(e,r){if(Array.isArray(e)){const n=new Array;return r?e.forEach(o=>{if(!K.isBufferSource(o))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");n.push(this.encodeStruct({type:r,rawData:K.toArrayBuffer(o)}))}):e.forEach(o=>{if(!("type"in o))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");n.push(this.encodeStruct(o))}),n.join(`
120
- `)}else{if(!r)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:r,rawData:K.toArrayBuffer(e)})}}static encodeStruct(e){var r;const n=e.type.toLocaleUpperCase(),o=[];if(o.push(`-----BEGIN ${n}-----`),!((r=e.headers)===null||r===void 0)&&r.length){for(const i of e.headers)o.push(`${i.key}: ${i.value}`);o.push("")}const s=ee.ToBase64(e.rawData);for(let i=0;i<s.length;i+=64)o.push(s.substring(i,i+64));return o.push(`-----END ${n}-----`),o.join(`
121
- `)}}gt.CertificateTag="CERTIFICATE";gt.CrlTag="CRL";gt.CertificateRequestTag="CERTIFICATE REQUEST";gt.PublicKeyTag="PUBLIC KEY";gt.PrivateKeyTag="PRIVATE KEY";class wr extends Kr{static isAsnEncoded(e){return K.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(gt.isPem(e))return gt.decode(e)[0];if(ee.isHex(e))return ee.FromHex(e);if(ee.isBase64(e))return ee.FromBase64(e);if(ee.isBase64Url(e))return ee.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{const r=K.toUint8Array(e);if(r.length>0&&r[0]===48)return K.toArrayBuffer(e);const n=ee.ToBinary(e);if(gt.isPem(n))return gt.decode(n)[0];if(ee.isHex(n))return ee.FromHex(n);if(ee.isBase64(n))return ee.FromBase64(n);if(ee.isBase64Url(n))return ee.FromBase64Url(n);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){wr.isAsnEncoded(e[0])?super(wr.toArrayBuffer(e[0]),e[1],e[2]):super(e[0],e[1])}toString(e="pem"){return e==="pem"?gt.encode(this.rawData,this.tag):super.toString(e)}}class Ut extends wr{static async create(e,r=at.get()){if(e instanceof Ut)return e;if($r.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");const n=await r.subtle.exportKey("spki",e);return new Ut(n)}else{if(e.publicKey)return e.publicKey;if(K.isBufferSource(e))return new Ut(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e,r){wr.isAsnEncoded(e)?super(e,Ot,r):super(e,r),this.tag=gt.PublicKeyTag}async export(e,r,n){let o,s=["verify"],i={hash:"SHA-256",...this.algorithm};r?(i=e,s=r,o=n):o=e,o??(o=at.get());let a=this.rawData;const c=H.parse(this.rawData,Ot,this.parseOptions);return c.algorithm.algorithm===ss&&(a=iI(c,a)),o.subtle.importKey("spki",a,i,!0,s)}onInit(e){const r=Le.resolve(An),n=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===vn){const o=H.parse(e.subjectPublicKey,tf,this.parseOptions),s=K.toUint8Array(o.modulus);n.publicExponent=K.toUint8Array(o.publicExponent),n.modulusLength=(s[0]?s:s.slice(1)).byteLength<<3}}async getThumbprint(e,r){let n,o="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(o=e,n=r)),n??(n=at.get()),await n.subtle.digest(o,this.rawData)}async getKeyIdentifier(e,r){let n,o="SHA-1";e&&(typeof e=="object"&&"subtle"in e?n=e:(o=e,n=r)),n??(n=at.get());const s=H.parse(this.rawData,Ot,this.parseOptions);return await n.subtle.digest(o,s.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),r=H.parse(this.rawData,Ot,this.parseOptions);switch(e.Algorithm=Sn.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case Ss:e["EC Point"]=r.subjectPublicKey;break;case vn:default:e["Raw Data"]=r.subjectPublicKey}return e}}function iI(t,e){return t.algorithm=new W({algorithm:vn,parameters:null}),e=H.serialize(t),e}class En extends St{static async create(e,r=!1,n=at.get()){if("name"in e&&"serialNumber"in e)return new En(e,r);const s=await(await Ut.create(e,n)).getKeyIdentifier(n);return new En(ee.ToHex(s),r)}constructor(...e){if(K.isBufferSource(e[0]))super(e[0],e[1]);else if(typeof e[0]=="string"){const r=new Qr({keyIdentifier:new jd(ee.FromHex(e[0]))});super(Eu,e[1],H.serialize(r))}else{const r=e[0],n=r.name instanceof kn?H.parse(r.name.rawData,Ye):r.name,o=new Qr({authorityCertIssuer:n,authorityCertSerialNumber:ee.FromHex(r.serialNumber)});super(Eu,e[1],H.serialize(o))}}onInit(e){super.onInit(e);const r=H.parse(e.extnValue,Qr,this.parseOptions);r.keyIdentifier&&(this.keyId=ee.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?ee.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),r=H.parse(this.value,Qr,this.parseOptions);return r.authorityCertIssuer&&(e["Authority Issuer"]=new kn(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}}En.NAME="Authority Key Identifier";class Os extends St{constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=H.parse(this.value,Mi,this.parseOptions);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{const r=new Mi({cA:e[0],pathLenConstraint:e[1]});super(xv,e[2],H.serialize(r)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}}Os.NAME="Basic Constraints";var Om;(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(Om||(Om={}));class yc extends St{constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=H.parse(this.value,Li,this.parseOptions);this.usages=r.map(n=>n)}else{const r=new Li(e[0]);super(Cv,e[1],H.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>Wr.toString(r)).join(", "),e}}yc.NAME="Extended Key Usages";var zn;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(zn||(zn={}));class Cs extends St{constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=H.parse(this.value,Fc,this.parseOptions);this.usages=r.toNumber()}else{const r=new Fc(e[0]);super(Tv,e[1],H.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=H.parse(this.value,Fc,this.parseOptions);return e[""]=r.toJSON().join(", "),e}}Cs.NAME="Key Usages";class Ys extends St{static async create(e,r=!1,n=at.get()){const s=await(await Ut.create(e,n)).getKeyIdentifier(n);return new Ys(ee.ToHex(s),r)}constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=H.parse(this.value,Mr,this.parseOptions);this.keyId=ee.ToHex(r)}else{const r=typeof e[0]=="string"?ee.FromHex(e[0]):e[0],n=new Mr(r);super(Mv,e[1],H.serialize(n)),this.keyId=ee.ToHex(r)}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=H.parse(this.value,Mr,this.parseOptions);return e[""]=r,e}}Ys.NAME="Subject Key Identifier";class sf extends St{constructor(...e){K.isBufferSource(e[0])?super(e[0],e[1]):super(Rv,e[1],new kn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=H.parse(e.extnValue,Pu,this.parseOptions);this.names=new kn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}sf.NAME="Subject Alternative Name";class kt{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new St(e,r),o=this.items.get(n.type);return o?new o(e,r):n}}kt.items=new Map;class cb extends St{constructor(...e){var r;if(K.isBufferSource(e[0])){super(e[0],e[1]);const n=H.parse(this.value,ji,this.parseOptions);this.policies=n.map(o=>o.policyIdentifier)}else{const n=e[0],o=(r=e[1])!==null&&r!==void 0?r:!1,s=new ji(n.map(i=>new za({policyIdentifier:i})));super(Iv,o,H.serialize(s)),this.policies=n}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new me("",{},Wr.toString(r))),e}}cb.NAME="Certificate Policies";kt.register(Iv,cb);class ub extends St{constructor(...e){var r;if(K.isBufferSource(e[0]))super(e[0],e[1]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){const o=e[0].map(i=>new go({distributionPoint:new hn({fullName:[new ie({uniformResourceIdentifier:i})]})})),s=new qn(o);super(Nu,e[1],H.serialize(s))}else{const n=new qn(e[0]);super(Nu,e[1],H.serialize(n))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);const r=H.parse(e.extnValue,qn,this.parseOptions);this.distributionPoints=r}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var n;const o=new me("");return!((n=r.distributionPoint)===null||n===void 0)&&n.fullName&&(o[""]=r.distributionPoint.fullName.map(s=>new Br(s).toString()).join(", ")),r.reasons&&(o.Reasons=r.reasons.toString()),r.cRLIssuer&&(o["CRL Issuer"]=r.cRLIssuer.map(s=>s.toString()).join(", ")),o}),e}}ub.NAME="CRL Distribution Points";class lb extends St{constructor(...e){var r,n,o,s;if(K.isBufferSource(e[0]))super(e[0],e[1]);else if(e[0]instanceof Hn){const i=new Hn(e[0]);super(ku,e[1],H.serialize(i))}else{const i=e[0],a=new Hn;ci(a,i,Hp,"ocsp"),ci(a,i,Fp,"caIssuers"),ci(a,i,Wp,"timeStamping"),ci(a,i,Kp,"caRepository"),super(ku,e[1],H.serialize(a))}(r=this.ocsp)!==null&&r!==void 0||(this.ocsp=[]),(n=this.caIssuers)!==null&&n!==void 0||(this.caIssuers=[]),(o=this.timeStamping)!==null&&o!==void 0||(this.timeStamping=[]),(s=this.caRepository)!==null&&s!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],H.parse(e.extnValue,Hn,this.parseOptions).forEach(n=>{switch(n.accessMethod){case Hp:this.ocsp.push(new Br(n.accessLocation));break;case Fp:this.caIssuers.push(new Br(n.accessLocation));break;case Wp:this.timeStamping.push(new Br(n.accessLocation));break;case Kp:this.caRepository.push(new Br(n.accessLocation));break}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&ai(e,"OCSP",this.ocsp),this.caIssuers.length&&ai(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&ai(e,"Time Stamping",this.timeStamping),this.caRepository.length&&ai(e,"CA Repository",this.caRepository),e}}lb.NAME="Authority Info Access";function ai(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{const n=new me("");r.forEach((o,s)=>{const i=o.toTextObject(),a=`${i[me.NAME]} ${s+1}`;let c=n[a];Array.isArray(c)||(c=[],n[a]=c),c.push(i)}),t[e]=n}}function ci(t,e,r,n){const o=e[n];o&&(Array.isArray(o)?o:[o]).forEach(i=>{typeof i=="string"&&(i=new Br("url",i)),t.push(new Ds({accessMethod:r,accessLocation:H.parse(i.rawData,ie)}))})}class db extends St{constructor(...e){K.isBufferSource(e[0])?super(e[0],e[1]):super(Nv,e[1],new kn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=H.parse(e.extnValue,Ye,this.parseOptions);this.names=new kn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}db.NAME="Issuer Alternative Name";class xo extends Kr{constructor(...e){let r,n;if(K.isBufferSource(e[0]))r=K.toArrayBuffer(e[0]),n=e[1];else{const o=e[0],s=Array.isArray(e[1])?e[1].map(i=>K.toArrayBuffer(i)):[];r=H.serialize(new gr({type:o,values:s}))}super(r,gr,n)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new me("",{"":r})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[me.NAME]===xo.NAME&&(e[me.NAME]=Wr.toString(this.type)),e}}xo.NAME="Attribute";class fb extends xo{constructor(...e){var r;if(K.isBufferSource(e[0]))super(e[0],e[1]);else{const n=new ua({printableString:e[0]});super(rb,[H.serialize(n)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const r=H.parse(this.values[0],ua,this.parseOptions);this.password=r.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[me.VALUE]=this.password,e}}fb.NAME="Challenge Password";class af extends xo{constructor(...e){var r;if(K.isBufferSource(e[0]))super(e[0],e[1]);else{const n=e[0],o=new Dr;for(const s of n)o.push(H.parse(s.rawData,Vt));super(of,[H.serialize(o)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const r=H.parse(this.values[0],Dr,this.parseOptions);this.items=r.map(n=>kt.create(H.serialize(n),this.parseOptions))}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.items.map(n=>n.toTextObject());for(const n of r)e[n[me.NAME]]=n;return e}}af.NAME="Extensions";class gc{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new xo(e,r),o=this.items.get(n.type);return o?new o(e,r):n}}gc.items=new Map;const Xs="crypto.signatureFormatter";class aI{toAsnSignature(e,r){return K.toArrayBuffer(r)}toWebSignature(e,r){return K.toArrayBuffer(r)}}var gi;let Ml=gi=class{static createPssParams(e,r){const n=gi.getHashAlgorithm(e);return n?new wn({hashAlgorithm:n,maskGenAlgorithm:new W({algorithm:cc,parameters:H.serialize(n)}),saltLength:r}):null}static getHashAlgorithm(e){const r=Le.resolve(An);return typeof e=="string"?r.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?r.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let r;if(typeof e.hash=="string")r=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")r=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new W({algorithm:Zi,parameters:null});case"sha-256":return new W({algorithm:il,parameters:null});case"sha-384":return new W({algorithm:Qi,parameters:null});case"sha-512":return new W({algorithm:ea,parameters:null})}}else return new W({algorithm:vn,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");const r=gi.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new W({algorithm:ss,parameters:H.serialize(r)})}else return new W({algorithm:ss,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case vn:return{name:"RSASSA-PKCS1-v1_5"};case Zi:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case il:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Qi:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case ea:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case ss:if(e.parameters){const r=H.parse(e.parameters,wn);return{name:"RSA-PSS",hash:Le.resolve(An).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};Ml=gi=f([ko()],Ml);Le.registerSingleton(Tn,Ml);let _l=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new W({algorithm:ta});case"sha-256":return new W({algorithm:ra});case"sha-384":return new W({algorithm:na});case"sha-512":return new W({algorithm:oa})}return null}toWebAlgorithm(e){switch(e.algorithm){case ta:return{name:"SHA-1"};case ra:return{name:"SHA-256"};case na:return{name:"SHA-384"};case oa:return{name:"SHA-512"}}return null}};_l=f([ko()],_l);Le.registerSingleton(Tn,_l);class Ct{addPadding(e,r){const n=K.toUint8Array(r),o=new Uint8Array(e);return o.set(n,e-n.length),o.buffer}removePadding(e,r=!1){let n=K.toUint8Array(e);for(let o=0;o<n.length;o++)if(n[o]){n=n.slice(o);break}if(r&&n[0]>127){const o=new Uint8Array(n.length+1);return o.set(n,1),o.buffer}return n.buffer}toAsnSignature(e,r){if(e.name==="ECDSA"){const n=e.namedCurve,o=Ct.namedCurveSize.get(n)||Ct.defaultNamedCurveSize,s=new Ji,i=K.toUint8Array(r);return s.r=this.removePadding(i.slice(0,o),!0),s.s=this.removePadding(i.slice(o,o+o),!0),H.serialize(s)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){const n=H.parse(r,Ji),o=e.namedCurve,s=Ct.namedCurveSize.get(o)||Ct.defaultNamedCurveSize,i=this.addPadding(s,this.removePadding(n.r)),a=this.addPadding(s,this.removePadding(n.s));return vk(i,a)}return null}}Ct.namedCurveSize=new Map;Ct.defaultNamedCurveSize=32;const Jc="1.3.101.110",Cm="1.3.101.111",Zc="1.3.101.112",Nm="1.3.101.113";let jl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=Zc;break;case"x25519":r=Jc;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=Zc;break;case"ed448":r=Nm;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=Jc;break;case"x448":r=Cm;break}}return r?new W({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case Zc:return{name:"Ed25519"};case Nm:return{name:"EdDSA",namedCurve:"Ed448"};case Jc:return{name:"X25519"};case Cm:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};jl=f([ko()],jl);Le.registerSingleton(Tn,jl);let Dl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ml-dsa-44":r=Rh;break;case"ml-dsa-65":r=Mh;break;case"ml-dsa-87":r=_h;break}return r?new W({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case Rh:return{name:"ML-DSA-44"};case Mh:return{name:"ML-DSA-65"};case _h:return{name:"ML-DSA-87"}}return null}};Dl=f([ko()],Dl);Le.registerSingleton(Tn,Dl);let Ll=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"slh-dsa-sha2-128s":r=jh;break;case"slh-dsa-sha2-128f":r=Dh;break;case"slh-dsa-sha2-192s":r=Lh;break;case"slh-dsa-sha2-192f":r=Ph;break;case"slh-dsa-sha2-256s":r=Uh;break;case"slh-dsa-sha2-256f":r=Vh;break;case"slh-dsa-shake-128s":r=Hh;break;case"slh-dsa-shake-128f":r=Fh;break;case"slh-dsa-shake-192s":r=Wh;break;case"slh-dsa-shake-192f":r=Kh;break;case"slh-dsa-shake-256s":r=Gh;break;case"slh-dsa-shake-256f":r=qh;break}return r?new W({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case jh:return{name:"SLH-DSA-SHA2-128s"};case Dh:return{name:"SLH-DSA-SHA2-128f"};case Lh:return{name:"SLH-DSA-SHA2-192s"};case Ph:return{name:"SLH-DSA-SHA2-192f"};case Uh:return{name:"SLH-DSA-SHA2-256s"};case Vh:return{name:"SLH-DSA-SHA2-256f"};case Hh:return{name:"SLH-DSA-SHAKE-128s"};case Fh:return{name:"SLH-DSA-SHAKE-128f"};case Wh:return{name:"SLH-DSA-SHAKE-192s"};case Kh:return{name:"SLH-DSA-SHAKE-192f"};case Gh:return{name:"SLH-DSA-SHAKE-256s"};case qh:return{name:"SLH-DSA-SHAKE-256f"}}return null}};Ll=f([ko()],Ll);Le.registerSingleton(Tn,Ll);var Ro,Mo,_o,jo,Do,Lo,Po,Dn;class cI extends wr{get subjectName(){return oe(this,Mo,"f")||ke(this,Mo,new Dt(this.asn.certificationRequestInfo.subject),"f"),oe(this,Mo,"f")}get subject(){return oe(this,_o,"f")||ke(this,_o,this.subjectName.toString(),"f"),oe(this,_o,"f")}get signatureAlgorithm(){if(!oe(this,jo,"f")){const e=Le.resolve(An);ke(this,jo,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return oe(this,jo,"f")}get signature(){return oe(this,Do,"f")||ke(this,Do,this.asn.signature,"f"),oe(this,Do,"f")}get publicKey(){return oe(this,Lo,"f")||ke(this,Lo,new Ut(this.asn.certificationRequestInfo.subjectPKInfo,this.parseOptions),"f"),oe(this,Lo,"f")}get attributes(){return oe(this,Po,"f")||ke(this,Po,this.asn.certificationRequestInfo.attributes.map(e=>gc.create(H.serialize(e),this.parseOptions)),"f"),oe(this,Po,"f")}get extensions(){if(!oe(this,Dn,"f")){ke(this,Dn,[],"f");const e=this.getAttribute(of);e instanceof af&&ke(this,Dn,e.items,"f")}return oe(this,Dn,"f")}get tbs(){return oe(this,Ro,"f")||ke(this,Ro,this.asn.certificationRequestInfoRaw||H.serialize(this.asn.certificationRequestInfo),"f"),oe(this,Ro,"f")}constructor(e,r){const n=wr.isAsnEncoded(e)?[e,Es,r]:[e,r];super(n[0],n[1],n[2]),Ro.set(this,void 0),Mo.set(this,void 0),_o.set(this,void 0),jo.set(this,void 0),Do.set(this,void 0),Lo.set(this,void 0),Po.set(this,void 0),Dn.set(this,void 0),this.tag=gt.CertificateRequestTag}onInit(e){}getAttribute(e){for(const r of this.attributes)if(r.type===e)return r;return null}getAttributes(e){return this.attributes.filter(r=>r.type===e)}getExtension(e){for(const r of this.extensions)if(r.type===e)return r;return null}getExtensions(e){return this.extensions.filter(r=>r.type===e)}async verify(e=at.get()){const r={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(r,["verify"],e),o=Le.resolveAll(Xs).reverse();let s=null;for(const a of o)if(s=a.toWebSignature(r,this.signature),s)break;if(!s)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,n,s,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),r=H.parse(this.rawData,Es,this.parseOptions),n=r.certificationRequestInfo,o=new me("",{Version:`${mn[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const s=new me("");for(const i of this.attributes){const a=i.toTextObject();s[a[me.NAME]]=a}o.Attributes=s}return e.Data=o,e.Signature=new me("",{Algorithm:Sn.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}}Ro=new WeakMap,Mo=new WeakMap,_o=new WeakMap,jo=new WeakMap,Do=new WeakMap,Lo=new WeakMap,Po=new WeakMap,Dn=new WeakMap;cI.NAME="PKCS#10 Certificate Request";function uI(t){let e=0;for(;e<t.length-1&&t[e]===0;)e++;let r=t.slice(e);if(r.length||(r=new Uint8Array([0])),r[0]>127){const n=new Uint8Array(r.length+1);n[0]=0,n.set(r,1),r=n}return r.buffer}function lI(t,e=at.get()){const r=K.toUint8Array(ee.FromHex(t||"")),n=r.length&&r.some(o=>o>0)?r:e.getRandomValues(new Uint8Array(16));return uI(n)}function dI(t){let e=K.toUint8Array(t);return e.length>1&&e[0]===0&&e[1]>127&&(e=e.slice(1)),ee.ToHex(e)}var Uo,Vo,Ho,Fo,Wo,Ko,Go,qo,zo,Yo,Ln,Xo;class pb extends wr{get publicKey(){return oe(this,Xo,"f")||ke(this,Xo,new Ut(this.asn.tbsCertificate.subjectPublicKeyInfo,this.parseOptions),"f"),oe(this,Xo,"f")}get serialNumber(){return oe(this,Vo,"f")||ke(this,Vo,dI(this.asn.tbsCertificate.serialNumber),"f"),oe(this,Vo,"f")}get subjectName(){return oe(this,Ho,"f")||ke(this,Ho,new Dt(this.asn.tbsCertificate.subject),"f"),oe(this,Ho,"f")}get subject(){return oe(this,Fo,"f")||ke(this,Fo,this.subjectName.toString(),"f"),oe(this,Fo,"f")}get issuerName(){return oe(this,Wo,"f")||ke(this,Wo,new Dt(this.asn.tbsCertificate.issuer),"f"),oe(this,Wo,"f")}get issuer(){return oe(this,Ko,"f")||ke(this,Ko,this.issuerName.toString(),"f"),oe(this,Ko,"f")}get notBefore(){if(!oe(this,Go,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");ke(this,Go,e,"f")}return oe(this,Go,"f")}get notAfter(){if(!oe(this,qo,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");ke(this,qo,e,"f")}return oe(this,qo,"f")}get signatureAlgorithm(){if(!oe(this,zo,"f")){const e=Le.resolve(An);ke(this,zo,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return oe(this,zo,"f")}get signature(){return oe(this,Yo,"f")||ke(this,Yo,this.asn.signatureValue,"f"),oe(this,Yo,"f")}get extensions(){return oe(this,Ln,"f")||(ke(this,Ln,[],"f"),this.asn.tbsCertificate.extensions&&ke(this,Ln,this.asn.tbsCertificate.extensions.map(e=>kt.create(H.serialize(e),this.parseOptions)),"f")),oe(this,Ln,"f")}get tbs(){return oe(this,Uo,"f")||ke(this,Uo,this.asn.tbsCertificateRaw||H.serialize(this.asn.tbsCertificate),"f"),oe(this,Uo,"f")}constructor(e,r){const n=wr.isAsnEncoded(e)?[e,yn,r]:[e,r];super(n[0],n[1],n[2]),Uo.set(this,void 0),Vo.set(this,void 0),Ho.set(this,void 0),Fo.set(this,void 0),Wo.set(this,void 0),Ko.set(this,void 0),Go.set(this,void 0),qo.set(this,void 0),zo.set(this,void 0),Yo.set(this,void 0),Ln.set(this,void 0),Xo.set(this,void 0),this.tag=gt.CertificateTag}onInit(e){}getExtension(e){for(const r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e={},r=at.get()){let n,o;const s=e.publicKey;try{if(!s)n={...this.publicKey.algorithm,...this.signatureAlgorithm},o=await this.publicKey.export(n,["verify"],r);else if("publicKey"in s)n={...s.publicKey.algorithm,...this.signatureAlgorithm},o=await s.publicKey.export(n,["verify"],r);else if(s instanceof Ut)n={...s.algorithm,...this.signatureAlgorithm},o=await s.export(n,["verify"],r);else if(K.isBufferSource(s)){const u=new Ut(s);n={...u.algorithm,...this.signatureAlgorithm},o=await u.export(n,["verify"],r)}else n={...s.algorithm,...this.signatureAlgorithm},o=s}catch{return!1}const i=Le.resolveAll(Xs).reverse();let a=null;for(const u of i)if(a=u.toWebSignature(n,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const c=await r.subtle.verify(this.signatureAlgorithm,o,a,this.tbs);if(e.signatureOnly)return c;{const d=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<d&&d<this.notAfter.getTime()}}async getThumbprint(e,r){let n,o="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(o=e,n=r)),n??(n=at.get()),await n.subtle.digest(o,this.rawData)}async isSelfSigned(e=at.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),r=H.parse(this.rawData,yn,this.parseOptions),n=r.tbsCertificate,o=new me("",{Version:`${mn[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":Sn.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new me("",{"Not Before":n.validity.notBefore.getTime(),"Not After":n.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(n.issuerUniqueID&&(o["Issuer Unique ID"]=n.issuerUniqueID),n.subjectUniqueID&&(o["Subject Unique ID"]=n.subjectUniqueID),this.extensions.length){const s=new me("");for(const i of this.extensions){const a=i.toTextObject();s[a[me.NAME]]=a}o.Extensions=s}return e.Data=o,e.Signature=new me("",{Algorithm:Sn.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}}Uo=new WeakMap,Vo=new WeakMap,Ho=new WeakMap,Fo=new WeakMap,Wo=new WeakMap,Ko=new WeakMap,Go=new WeakMap,qo=new WeakMap,zo=new WeakMap,Yo=new WeakMap,Ln=new WeakMap,Xo=new WeakMap;pb.NAME="Certificate";class Pl{static async createSelfSigned(e,r=at.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}static async create(e,r=at.get()){var n;let o;e.publicKey instanceof Ut?o=e.publicKey.rawData:"publicKey"in e.publicKey?o=e.publicKey.publicKey.rawData:K.isBufferSource(e.publicKey)?o=e.publicKey:o=await r.subtle.exportKey("spki",e.publicKey);const s=lI(e.serialNumber,r),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),c=new yn({tbsCertificate:new At({version:mn.v3,serialNumber:s,validity:new Ls({notBefore:i,notAfter:a}),extensions:new Dr(((n=e.extensions)===null||n===void 0?void 0:n.map(g=>H.parse(g.rawData,Vt)))||[]),subjectPublicKeyInfo:H.parse(o,Ot)})});if(e.subject){const g=e.subject instanceof Dt?e.subject:new Dt(e.subject);c.tbsCertificate.subject=H.parse(g.toArrayBuffer(),Re)}if(e.issuer){const g=e.issuer instanceof Dt?e.issuer:new Dt(e.issuer);c.tbsCertificate.issuer=H.parse(g.toArrayBuffer(),Re)}const u={hash:"SHA-256"},d="signingKey"in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},l=Le.resolve(An);c.tbsCertificate.signature=c.signatureAlgorithm=l.toAsnAlgorithm(d);const m=H.serialize(c.tbsCertificate),p="signingKey"in e?await r.subtle.sign(d,e.signingKey,m):e.signature,h=Le.resolveAll(Xs).reverse();let v=null;for(const g of h)if(v=g.toAsnSignature(d,p),v)break;if(!v)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=v,new pb(H.serialize(c))}}var Tm;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(Tm||(Tm={}));kt.register(xv,Os);kt.register(Cv,yc);kt.register(Tv,Cs);kt.register(Mv,Ys);kt.register(Eu,En);kt.register(Rv,sf);kt.register(Nu,ub);kt.register(ku,lb);kt.register(Nv,db);gc.register(rb,fb);gc.register(of,af);Le.registerSingleton(Xs,aI);Le.registerSingleton(Xs,Ct);Ct.namedCurveSize.set("P-256",32);Ct.namedCurveSize.set("K-256",32);Ct.namedCurveSize.set("P-384",48);Ct.namedCurveSize.set("P-521",66);const st=Bb,Ul={name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"},Ns={name:"ECDSA",namedCurve:"P-256"},fI="1.3.6.1.5.5.7.3.1",pI="1.3.6.1.5.5.7.3.2",Vl=6e4,Hl=864e5;function hb(t){return`${t}.display`}function hI(t,e){const r=Buffer.from(e).toString("base64").match(/.{1,64}/g)?.join(`
373
+ `)}function SI(t,e,r){var n=ya(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),s=n[1],o=s===void 0?null:s,i=bI(o,e);return wI("Cannot inject the dependency "+i+' of "'+t.name+'" constructor. Reason:',r)}function AI(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var kI=(function(t){vf(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(bf),EI=(function(t){vf(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(bf),xI=(function(){function t(){this.preResolution=new kI,this.postResolution=new EI}return t})(),fb=new Map,II=(function(){function t(e){this.parent=e,this._registry=new vI,this.interceptors=new xI,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,r,n){n===void 0&&(n={lifecycle:st.Transient}),this.ensureNotDisposed();var s;if(gI(r)?s=r:s={useClass:r},Ei(s))for(var o=[e],i=s;i!=null;){var a=i.useToken;if(o.includes(a))throw new Error("Token registration cycle detected! "+sn(o,[a]).join(" -> "));o.push(a);var c=this._registry.get(a);c&&Ei(c.provider)?i=c.provider:i=null}if((n.lifecycle===st.Singleton||n.lifecycle==st.ContainerScoped||n.lifecycle==st.ResolutionScoped)&&(xi(s)||Il(s)))throw new Error('Cannot use lifecycle "'+st[n.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:s,options:n}),this},t.prototype.registerType=function(e,r){return this.ensureNotDisposed(),Hn(r)?this.register(e,{useToken:r}):this.register(e,{useClass:r})},t.prototype.registerInstance=function(e,r){return this.ensureNotDisposed(),this.register(e,{useValue:r})},t.prototype.registerSingleton=function(e,r){if(this.ensureNotDisposed(),Hn(e)){if(Hn(r))return this.register(e,{useToken:r},{lifecycle:st.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:st.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var n=e;return r&&!Hn(r)&&(n=r),this.register(e,{useClass:n},{lifecycle:st.Singleton})},t.prototype.resolve=function(e,r,n){r===void 0&&(r=new mi),n===void 0&&(n=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&Hn(e)){if(n)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),s){var o=this.resolveRegistration(s,r);return this.executePostResolutionInterceptor(e,o,"Single"),o}if(yI(e)){var o=this.construct(e,r);return this.executePostResolutionInterceptor(e,o,"Single"),o}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},t.prototype.executePreResolutionInterceptor=function(e,r){var n,s;if(this.interceptors.preResolution.has(e)){var o=[];try{for(var i=hi(this.interceptors.preResolution.getAll(e)),a=i.next();!a.done;a=i.next()){var c=a.value;c.options.frequency!="Once"&&o.push(c),c.callback(e,r)}}catch(u){n={error:u}}finally{try{a&&!a.done&&(s=i.return)&&s.call(i)}finally{if(n)throw n.error}}this.interceptors.preResolution.setAll(e,o)}},t.prototype.executePostResolutionInterceptor=function(e,r,n){var s,o;if(this.interceptors.postResolution.has(e)){var i=[];try{for(var a=hi(this.interceptors.postResolution.getAll(e)),c=a.next();!c.done;c=a.next()){var u=c.value;u.options.frequency!="Once"&&i.push(u),u.callback(e,r,n)}}catch(l){s={error:l}}finally{try{c&&!c.done&&(o=a.return)&&o.call(a)}finally{if(s)throw s.error}}this.interceptors.postResolution.setAll(e,i)}},t.prototype.resolveRegistration=function(e,r){if(this.ensureNotDisposed(),e.options.lifecycle===st.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);var n=e.options.lifecycle===st.Singleton,s=e.options.lifecycle===st.ContainerScoped,o=n||s,i;return xi(e.provider)?i=e.provider.useValue:Ei(e.provider)?i=o?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):lb(e.provider)?i=o?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):Il(e.provider)?i=e.provider.useFactory(this):i=this.construct(e.provider,r),e.options.lifecycle===st.ResolutionScoped&&r.scopedResolutions.set(e,i),i},t.prototype.resolveAll=function(e,r,n){var s=this;r===void 0&&(r=new mi),n===void 0&&(n=!1),this.ensureNotDisposed();var o=this.getAllRegistrations(e);if(!o&&Hn(e)){if(n)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),o){var i=o.map(function(c){return s.resolveRegistration(c,r)});return this.executePostResolutionInterceptor(e,i,"All"),i}var a=[this.construct(e,r)];return this.executePostResolutionInterceptor(e,a,"All"),a},t.prototype.isRegistered=function(e,r){return r===void 0&&(r=!1),this.ensureNotDisposed(),this._registry.has(e)||r&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},t.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},t.prototype.clearInstances=function(){var e,r;this.ensureNotDisposed();try{for(var n=hi(this._registry.entries()),s=n.next();!s.done;s=n.next()){var o=ya(s.value,2),i=o[0],a=o[1];this._registry.setAll(i,a.filter(function(c){return!xi(c.provider)}).map(function(c){return c.instance=void 0,c}))}}catch(c){e={error:c}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(e)throw e.error}}},t.prototype.createChildContainer=function(){var e,r;this.ensureNotDisposed();var n=new t(this);try{for(var s=hi(this._registry.entries()),o=s.next();!o.done;o=s.next()){var i=ya(o.value,2),a=i[0],c=i[1];c.some(function(u){var l=u.options;return l.lifecycle===st.ContainerScoped})&&n._registry.setAll(a,c.map(function(u){return u.options.lifecycle===st.ContainerScoped?{provider:u.provider,options:u.options}:u}))}}catch(u){e={error:u}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(e)throw e.error}}return n},t.prototype.beforeResolution=function(e,r,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:r,options:n})},t.prototype.afterResolution=function(e,r,n){n===void 0&&(n={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:r,options:n})},t.prototype.dispose=function(){return dI(this,void 0,void 0,function(){var e;return fI(this,function(r){switch(r.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(n){var s=n.dispose();s&&e.push(s)}),[4,Promise.all(e)];case 1:return r.sent(),[2]}})})},t.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},t.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},t.prototype.construct=function(e,r){var n=this;if(e instanceof db)return e.createProxy(function(o){return n.resolve(o,r)});var s=(function(){var o=fb.get(e);if(!o||o.length===0){if(e.length===0)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=o.map(n.resolveParams(r,e));return new(e.bind.apply(e,sn([void 0],i)))})();return AI(s)&&this.disposables.add(s),s},t.prototype.resolveParams=function(e,r){var n=this;return function(s,o){var i,a,c;try{return mI(s)?kh(s)?s.multiple?(i=n.resolve(s.transform)).transform.apply(i,sn([n.resolveAll(s.token,new mi,s.isOptional)],s.transformArgs)):(a=n.resolve(s.transform)).transform.apply(a,sn([n.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?n.resolveAll(s.token,new mi,s.isOptional):n.resolve(s.token,e,s.isOptional):kh(s)?(c=n.resolve(s.transform,e)).transform.apply(c,sn([n.resolve(s.token,e)],s.transformArgs)):n.resolve(s,e)}catch(u){throw new Error(SI(r,o,u))}}},t.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},t})(),He=new II;function Ns(t){return function(e){fb.set(e,hI(e))}}if(typeof Reflect>"u"||!Reflect.getMetadata)throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);var Cl;class Ec{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}}f([y({type:S.ObjectIdentifier})],Ec.prototype,"attrId",void 0);f([y({type:S.Any,repeated:"set"})],Ec.prototype,"attrValues",void 0);let Eh=Cl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Cl.prototype)}};Eh=Cl=f([D({type:B.Sequence,itemType:Ec})],Eh);var Ol;let xh=Ol=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ol.prototype)}};xh=Ol=f([D({type:B.Sequence,itemType:Is})],xh);class pb{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],pb.prototype,"certId",void 0);f([y({type:S.Any,context:0})],pb.prototype,"certValue",void 0);class hb{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],hb.prototype,"crlId",void 0);f([y({type:S.Any,context:0})],hb.prototype,"crltValue",void 0);class mb extends he{}let xc=class{encryptionAlgorithm=new W;encryptedData=new mb;constructor(e={}){Object.assign(this,e)}};f([y({type:W})],xc.prototype,"encryptionAlgorithm",void 0);f([y({type:mb})],xc.prototype,"encryptedData",void 0);var Nl,Tl;(function(t){t[t.v1=0]="v1"})(Tl||(Tl={}));class yb extends he{}let ga=Nl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Nl.prototype)}};ga=Nl=f([D({type:B.Sequence,itemType:Ar})],ga);let ti=class{version=Tl.v1;privateKeyAlgorithm=new W;privateKey=new yb;attributes;constructor(e={}){Object.assign(this,e)}};f([y({type:S.Integer})],ti.prototype,"version",void 0);f([y({type:W})],ti.prototype,"privateKeyAlgorithm",void 0);f([y({type:yb})],ti.prototype,"privateKey",void 0);f([y({type:ga,implicit:!0,context:0,optional:!0})],ti.prototype,"attributes",void 0);let Ih=class extends ti{};Ih=f([D({type:B.Sequence})],Ih);let Ch=class extends xc{};Ch=f([D({type:B.Sequence})],Ch);class gb{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],gb.prototype,"secretTypeId",void 0);f([y({type:S.Any,context:0})],gb.prototype,"secretValue",void 0);class ri{mac=new Ac;macSalt=new he;iterations=1;constructor(e={}){Object.assign(this,e)}}f([y({type:Ac})],ri.prototype,"mac",void 0);f([y({type:he})],ri.prototype,"macSalt",void 0);f([y({type:S.Integer,defaultValue:1})],ri.prototype,"iterations",void 0);class Ic{version=3;authSafe=new Is;macData=new ri;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],Ic.prototype,"version",void 0);f([y({type:Is})],Ic.prototype,"authSafe",void 0);f([y({type:ri,optional:!0})],Ic.prototype,"macData",void 0);var $l;class Cc{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}}f([y({type:S.ObjectIdentifier})],Cc.prototype,"bagId",void 0);f([y({type:S.Any,context:0})],Cc.prototype,"bagValue",void 0);f([y({type:Ec,repeated:"set",optional:!0})],Cc.prototype,"bagAttributes",void 0);let Oh=$l=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,$l.prototype)}};Oh=$l=f([D({type:B.Sequence,itemType:Cc})],Oh);var Bl,_l,Ml;const vb="1.2.840.113549.1.9",bb=`${vb}.7`,wf=`${vb}.14`;let va=class extends ze{ia5String;constructor(e={}){super(e)}toString(){return this.ia5String||super.toString()}};f([y({type:S.IA5String})],va.prototype,"ia5String",void 0);va=f([D({type:B.Choice})],va);let Nh=class extends Is{};Nh=f([D({type:B.Sequence})],Nh);let Th=class extends Ic{};Th=f([D({type:B.Sequence})],Th);let $h=class extends xc{};$h=f([D({type:B.Sequence})],$h);let Rl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:S.IA5String})],Rl.prototype,"value",void 0);Rl=f([D({type:B.Choice})],Rl);let Bh=class extends va{};Bh=f([D({type:B.Choice})],Bh);let _h=class extends ze{};_h=f([D({type:B.Choice})],_h);let jl=class{value;constructor(e=new Date){this.value=e}};f([y({type:S.GeneralizedTime})],jl.prototype,"value",void 0);jl=f([D({type:B.Choice})],jl);let Mh=class extends ze{};Mh=f([D({type:B.Choice})],Mh);let Dl=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};f([y({type:S.PrintableString})],Dl.prototype,"value",void 0);Dl=f([D({type:B.Choice})],Dl);let ba=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:S.PrintableString})],ba.prototype,"value",void 0);ba=f([D({type:B.Choice})],ba);let Rh=class extends ba{};Rh=f([D({type:B.Choice})],Rh);let jh=class extends ze{};jh=f([D({type:B.Choice})],jh);let Pl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:S.ObjectIdentifier})],Pl.prototype,"value",void 0);Pl=f([D({type:B.Choice})],Pl);let Dh=class extends Ge{};Dh=f([D({type:B.Choice})],Dh);let Ll=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};f([y({type:S.Integer})],Ll.prototype,"value",void 0);Ll=f([D({type:B.Choice})],Ll);let Ph=class extends cr{};Ph=f([D({type:B.Sequence})],Ph);let wa=class extends ze{};wa=f([D({type:B.Choice})],wa);let Lh=Bl=class extends Vr{constructor(e){super(e),Object.setPrototypeOf(this,Bl.prototype)}};Lh=Bl=f([D({type:B.Sequence})],Lh);let Uh=_l=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,_l.prototype)}};Uh=_l=f([D({type:B.Set,itemType:xs})],Uh);let Ul=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([y({type:S.BmpString})],Ul.prototype,"value",void 0);Ul=f([D({type:B.Choice})],Ul);let Hl=class extends W{};Hl=f([D({type:B.Sequence})],Hl);let Hh=Ml=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Ml.prototype)}};Hh=Ml=f([D({type:B.Sequence,itemType:Hl})],Hh);var Vl,Fl;let Vh=Vl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Vl.prototype)}};Vh=Vl=f([D({type:B.Sequence,itemType:W})],Vh);let Fh=Fl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Fl.prototype)}};Fh=Fl=f([D({type:B.Sequence,itemType:S.BitString})],Fh);var Wl,Kl;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2"})(Kl||(Kl={}));let Wh=class extends W{};Wh=f([D({type:B.Sequence})],Wh);let nr=class{version=Kl.v1;privateKeyAlgorithm=new W;privateKey=new ArrayBuffer(0);attributes;publicKey};f([y({type:S.Integer})],nr.prototype,"version",void 0);f([y({type:W})],nr.prototype,"privateKeyAlgorithm",void 0);f([y({type:S.OctetString})],nr.prototype,"privateKey",void 0);f([y({type:ga,context:0,implicit:!0,optional:!0})],nr.prototype,"attributes",void 0);f([y({type:S.BitString,context:1,implicit:!0,optional:!0})],nr.prototype,"publicKey",void 0);nr=f([D({type:B.Sequence})],nr);let Kh=class extends nr{};Kh=f([D({type:B.Sequence})],Kh);let Gh=Wl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Wl.prototype)}};Gh=Wl=f([D({type:B.Sequence,itemType:nr})],Gh);var Gl,ql;let qh=class extends W{};qh=f([D({type:B.Sequence})],qh);let zh=Gl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,Gl.prototype)}};zh=Gl=f([D({type:B.Sequence,itemType:Nt})],zh);let Yh=ql=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,ql.prototype)}};Yh=ql=f([D({type:B.Sequence,itemType:nr})],Yh);const nt="2.16.840.1.101.3.4.3",Xh=`${nt}.17`,Jh=`${nt}.18`,Zh=`${nt}.19`,Qh=`${nt}.20`,em=`${nt}.21`,tm=`${nt}.22`,rm=`${nt}.23`,nm=`${nt}.24`,sm=`${nt}.25`,om=`${nt}.26`,im=`${nt}.27`,am=`${nt}.28`,cm=`${nt}.29`,um=`${nt}.30`,lm=`${nt}.31`;var zl;let Sa=zl=class extends pe{constructor(e){super(e),Object.setPrototypeOf(this,zl.prototype)}};Sa=zl=f([D({type:B.Sequence,itemType:Ar})],Sa);class Ts{version=0;subject=new je;subjectPKInfo=new Nt;attributes=new Sa;constructor(e={}){Object.assign(this,e)}}f([y({type:S.Integer})],Ts.prototype,"version",void 0);f([y({type:je})],Ts.prototype,"subject",void 0);f([y({type:Nt})],Ts.prototype,"subjectPKInfo",void 0);f([y({type:Sa,implicit:!0,context:0,optional:!0})],Ts.prototype,"attributes",void 0);class Bo{certificationRequestInfo=new Ts;certificationRequestInfoRaw;signatureAlgorithm=new W;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([y({type:Ts,raw:!0})],Bo.prototype,"certificationRequestInfo",void 0);f([y({type:W})],Bo.prototype,"signatureAlgorithm",void 0);f([y({type:S.BitString})],Bo.prototype,"signature",void 0);const Dn="crypto.algorithm";class CI{getAlgorithms(){return He.resolveAll(Dn)}toAsnAlgorithm(e){const r={...e};r.hash&&typeof r.hash=="string"&&(r.hash={name:r.hash});for(const n of this.getAlgorithms()){const s=n.toAsnAlgorithm(r);if(s)return s}if(/^[0-9.]+$/.test(e.name)){const n=new W({algorithm:e.name});if("parameters"in e){const s=e;n.parameters=s.parameters}return n}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(const n of this.getAlgorithms()){const s=n.toWebAlgorithm(e);if(s)return s}return{name:e.algorithm,parameters:e.parameters}}}const On="crypto.algorithmProvider";He.registerSingleton(On,CI);var Ii;const dt="1.3.36.3.3.2.8.1.1",dm=`${dt}.1`,fm=`${dt}.2`,pm=`${dt}.3`,hm=`${dt}.4`,mm=`${dt}.5`,ym=`${dt}.6`,gm=`${dt}.7`,vm=`${dt}.8`,bm=`${dt}.9`,wm=`${dt}.10`,Sm=`${dt}.11`,Am=`${dt}.12`,km=`${dt}.13`,Em=`${dt}.14`,xm="brainpoolP160r1",Im="brainpoolP160t1",Cm="brainpoolP192r1",Om="brainpoolP192t1",Nm="brainpoolP224r1",Tm="brainpoolP224t1",$m="brainpoolP256r1",Bm="brainpoolP256t1",_m="brainpoolP320r1",Mm="brainpoolP320t1",Rm="brainpoolP384r1",jm="brainpoolP384t1",Dm="brainpoolP512r1",Pm="brainpoolP512t1",Te="ECDSA";let _o=Ii=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case Te.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Jx;case"sha-256":return Zx;case"sha-384":return Qx;case"sha-512":return eI}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=wh;break;case"K-256":r=Ii.SECP256K1;break;case"P-384":r=Sh;break;case"P-521":r=Ah;break;case xm:r=dm;break;case Im:r=fm;break;case Cm:r=pm;break;case Om:r=hm;break;case Nm:r=mm;break;case Tm:r=ym;break;case $m:r=gm;break;case Bm:r=vm;break;case _m:r=bm;break;case Mm:r=wm;break;case Rm:r=Sm;break;case jm:r=Am;break;case Dm:r=km;break;case Pm:r=Em;break}if(r)return new W({algorithm:To,parameters:V.serialize(new Wr({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case pf:return{name:Te,hash:{name:"SHA-1"}};case hf:return{name:Te,hash:{name:"SHA-256"}};case mf:return{name:Te,hash:{name:"SHA-384"}};case yf:return{name:Te,hash:{name:"SHA-512"}};case To:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(V.parse(e.parameters,Wr).namedCurve){case wh:return{name:Te,namedCurve:"P-256"};case Ii.SECP256K1:return{name:Te,namedCurve:"K-256"};case Sh:return{name:Te,namedCurve:"P-384"};case Ah:return{name:Te,namedCurve:"P-521"};case dm:return{name:Te,namedCurve:xm};case fm:return{name:Te,namedCurve:Im};case pm:return{name:Te,namedCurve:Cm};case hm:return{name:Te,namedCurve:Om};case mm:return{name:Te,namedCurve:Nm};case ym:return{name:Te,namedCurve:Tm};case gm:return{name:Te,namedCurve:$m};case vm:return{name:Te,namedCurve:Bm};case bm:return{name:Te,namedCurve:_m};case wm:return{name:Te,namedCurve:Mm};case Sm:return{name:Te,namedCurve:Rm};case Am:return{name:Te,namedCurve:jm};case km:return{name:Te,namedCurve:Dm};case Em:return{name:Te,namedCurve:Pm}}}}return null}};_o.SECP256K1="1.3.132.0.10";_o=Ii=f([Ns()],_o);He.registerSingleton(Dn,_o);const wb=Symbol("name"),Sb=Symbol("value");class ye{constructor(e,r={},n=""){this[wb]=e,this[Sb]=n;for(const s in r)this[s]=r[s]}}ye.NAME=wb;ye.VALUE=Sb;class OI{static toTextObject(e){const r=new ye("Algorithm Identifier",{},Yr.toString(e.algorithm));if(e.parameters)if(e.algorithm===To){const n=new _o().toWebAlgorithm(e);n&&"namedCurve"in n?r["Named Curve"]=n.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}}class Yr{static toString(e){const r=this.items[e];return r||e}}Yr.items={[fa]:"sha1",[ab]:"sha224",[pa]:"sha256",[ha]:"sha384",[ma]:"sha512",[xn]:"rsaEncryption",[ua]:"sha1WithRSAEncryption",[iI]:"sha224WithRSAEncryption",[Sl]:"sha256WithRSAEncryption",[la]:"sha384WithRSAEncryption",[da]:"sha512WithRSAEncryption",[To]:"ecPublicKey",[pf]:"ecdsaWithSHA1",[sb]:"ecdsaWithSHA224",[hf]:"ecdsaWithSHA256",[mf]:"ecdsaWithSHA384",[yf]:"ecdsaWithSHA512",[Wx]:"TLS WWW server authentication",[Kx]:"TLS WWW client authentication",[Gx]:"Code Signing",[qx]:"E-mail Protection",[zx]:"Time Stamping",[Yx]:"OCSP Signing",[Xx]:"Signed Data"};class Nn{static serialize(e){return this.serializeObj(e).join(`
374
+ `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){const n=[];let s=this.pad(r++),o="";const i=e[ye.VALUE];i&&(o=` ${i}`),n.push(`${s}${e[ye.NAME]}:${o}`),s=this.pad(r);for(const a in e){if(typeof a=="symbol")continue;const c=e[a],u=a?`${a}: `:"";if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")n.push(`${s}${u}${c}`);else if(c instanceof Date)n.push(`${s}${u}${c.toUTCString()}`);else if(Array.isArray(c))for(const l of c)l[ye.NAME]=a,n.push(...this.serializeObj(l,r));else if(c instanceof ye)c[ye.NAME]=a,n.push(...this.serializeObj(c,r));else if(K.isBufferSource(c))a?(n.push(`${s}${u}`),n.push(...this.serializeBufferSource(c,r+1))):n.push(...this.serializeBufferSource(c,r));else if("toTextObject"in c){const l=c.toTextObject();l[ye.NAME]=a,n.push(...this.serializeObj(l,r))}else throw new TypeError("Cannot serialize data in text format. Unsupported type.")}return n}static serializeBufferSource(e,r=0){const n=this.pad(r),s=K.toUint8Array(e),o=[];for(let i=0;i<s.length;){const a=[];for(let c=0;c<16&&i<s.length;c++){c===8&&a.push("");const u=s[i++].toString(16).padStart(2,"0");a.push(u)}o.push(`${n}${a.join(" ")}`)}return o}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}Nn.oidSerializer=Yr;Nn.algorithmSerializer=OI;var Vn,Fn;class Xr{get parseOptions(){return oe(this,Fn,"f")}get rawData(){return oe(this,Vn,"f")||xe(this,Vn,V.serialize(this.asn),"f"),oe(this,Vn,"f")}constructor(...e){Vn.set(this,void 0),Fn.set(this,void 0),K.isBufferSource(e[0])?(xe(this,Fn,e[2],"f"),this.asn=V.parse(e[0],e[1],e[2]),xe(this,Vn,K.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(xe(this,Fn,e[1],"f"),this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof Xr?tE(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return V.toString(this.rawData,oe(this,Fn,"f"));case"text":return Nn.serialize(this.toTextObject());case"hex":return ee.ToHex(this.rawData);case"base64":return ee.ToBase64(this.rawData);case"base64url":return ee.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){const e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new ye(this.getTextName(),{},e)}}Vn=new WeakMap,Fn=new WeakMap;Xr.NAME="ASN";class At extends Xr{constructor(...e){let r,n;K.isBufferSource(e[0])?(r=K.toArrayBuffer(e[0]),n=e[1]):r=V.serialize(new Kt({extnID:e[0],critical:e[1],extnValue:new he(K.toArrayBuffer(e[2]))})),super(r,Kt,n)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[ye.NAME]===At.NAME&&(e[ye.NAME]=Yr.toString(this.type)),e}}var Ab;class jr{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[Ab]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(jr.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(jr.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,r){return this.items.forEach(e,r)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=jr.DEFAULT){const r=this.items.get(e.toLowerCase());if(!r)throw new Error(`Cannot get Crypto by name '${e}'`);return r}set(e,r){if(typeof e=="string"){if(!r)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),r)}else this.items.set(jr.DEFAULT,e);return this}}Ab=Symbol.toStringTag;jr.DEFAULT="default";const ct=new jr,NI=/^[0-2](?:\.[1-9][0-9]*)+$/;function TI(t){return new RegExp(NI).test(t)}class kb{constructor(e={}){this.items={};for(const r in e)this.register(r,e[r])}get(e){return this.items[e]||null}findId(e){return TI(e)?e:this.get(e)}register(e,r){this.items[e]=r,this.items[r]=e}}const ut=new kb;ut.register("CN","2.5.4.3");ut.register("L","2.5.4.7");ut.register("ST","2.5.4.8");ut.register("O","2.5.4.10");ut.register("OU","2.5.4.11");ut.register("C","2.5.4.6");ut.register("DC","0.9.2342.19200300.100.1.25");ut.register("E","1.2.840.113549.1.9.1");ut.register("G","2.5.4.42");ut.register("I","2.5.4.43");ut.register("SN","2.5.4.4");ut.register("T","2.5.4.12");function $I(t,e){return`\\${ee.ToHex(ee.FromUtf8String(e)).toUpperCase()}`}function BI(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,$I)}class Ut{static isASCII(e){for(let r=0;r<e.length;r++)if(e.charCodeAt(r)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,r={}){this.extraNames=new kb,this.asn=new je;for(const n in r)if(Object.prototype.hasOwnProperty.call(r,n)){const s=r[n];this.extraNames.register(n,s)}typeof e=="string"?this.asn=this.fromString(e):e instanceof je?this.asn=e:K.isBufferSource(e)?this.asn=V.parse(e,je):this.asn=this.fromJSON(e)}getField(e){const r=this.extraNames.findId(e)||ut.findId(e),n=[];for(const s of this.asn)for(const o of s)o.type===r&&n.push(o.value.toString());return n}getName(e){return this.extraNames.get(e)||ut.get(e)}toString(){return this.asn.map(e=>e.map(r=>{const n=this.getName(r.type)||r.type,s=r.value.anyValue?`#${ee.ToHex(r.value.anyValue)}`:BI(r.value.toString());return`${n}=${s}`}).join("+")).join(", ")}toJSON(){var e;const r=[];for(const n of this.asn){const s={};for(const o of n){const i=this.getName(o.type)||o.type;(e=s[i])!==null&&e!==void 0||(s[i]=[]),s[i].push(o.value.anyValue?`#${ee.ToHex(o.value.anyValue)}`:o.value.toString())}r.push(s)}return r}fromString(e){const r=new je,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let s=null,o=",";for(;s=n.exec(`${e},`);){let[,i,a]=s;const c=a[a.length-1];(c===","||c==="+")&&(a=a.slice(0,a.length-1),s[3]=c);const u=s[3];i=this.getTypeOid(i);const l=this.createAttribute(i,a);o==="+"?r[r.length-1].push(l):r.push(new us([l])),o=u}return r}fromJSON(e){const r=new je;for(const n of e){const s=new us;for(const o in n){const i=this.getTypeOid(o),a=n[o];for(const c of a){const u=this.createAttribute(i,c);s.push(u)}}r.push(s)}return r}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,r){const n=new sc({type:e});if(typeof r=="object")for(const s in r)switch(s){case"ia5String":n.value.ia5String=r[s];break;case"utf8String":n.value.utf8String=r[s];break;case"universalString":n.value.universalString=r[s];break;case"bmpString":n.value.bmpString=r[s];break;case"printableString":n.value.printableString=r[s];break}else if(r[0]==="#")n.value.anyValue=ee.FromHex(r.slice(1));else{const s=this.processStringValue(r);e===this.getName("E")||e===this.getName("DC")?n.value.ia5String=s:Ut.isPrintableString(s)?n.value.printableString=s:n.value.utf8String=s}return n}processStringValue(e){const r=/"(.*?[^\\])?"/.exec(e);return r&&(e=r[1]),e.replace(/\\0a/gi,`
375
+ `).replace(/\\0d/gi,"\r").replace(/\\0g/gi," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return V.serialize(this.asn)}async getThumbprint(e,r){let n,s="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(s=e,n=r)),n??(n=ct.get()),await n.subtle.digest(s,this.toArrayBuffer())}}const Eb="Cannot initialize GeneralName from ASN.1 data.",Lm=`${Eb} Unsupported string format in use.`,_I=`${Eb} Value doesn't match to GUID regular expression.`,Um=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Hm="1.3.6.1.4.1.311.25.1",Vm="1.3.6.1.4.1.311.20.2.3",nu="dns",su="dn",ou="email",iu="ip",au="url",cu="guid",uu="upn",yi="id";class Dr extends Xr{constructor(...e){let r;if(e.length===2)switch(e[0]){case su:{const n=new Ut(e[1]).toArrayBuffer(),s=V.parse(n,je);r=new ie({directoryName:s});break}case nu:r=new ie({dNSName:e[1]});break;case ou:r=new ie({rfc822Name:e[1]});break;case cu:{const n=new RegExp(Um,"i").exec(e[1]);if(!n)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const s=n.slice(1).map((o,i)=>i<3?ee.ToHex(new Uint8Array(ee.FromHex(o)).reverse()):o).join("");r=new ie({otherName:new Io({typeId:Hm,value:V.serialize(new he(ee.FromHex(s)))})});break}case iu:r=new ie({iPAddress:e[1]});break;case yi:r=new ie({registeredID:e[1]});break;case uu:{r=new ie({otherName:new Io({typeId:Vm,value:V.serialize(Uv.toASN(e[1]))})});break}case au:r=new ie({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else K.isBufferSource(e[0])?r=V.parse(e[0],ie):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=nu,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=ou,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=iu,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=au,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=yi,this.value=e.registeredID;else if(e.directoryName!=null)this.type=su,this.value=new Ut(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===Hm){this.type=cu;const r=V.parse(e.otherName.value,he),n=new RegExp(Um,"i").exec(ee.ToHex(r));if(!n)throw new Error(_I);this.value=n.slice(1).map((s,o)=>o<3?ee.ToHex(new Uint8Array(ee.FromHex(s)).reverse()):s).join("-")}else if(e.otherName.typeId===Vm)this.type=uu,this.value=V.parse(e.otherName.value,ze).toString();else throw new Error(Lm);else throw new Error(Lm)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case su:case nu:case cu:case iu:case yi:case uu:case au:e=this.type.toUpperCase();break;case ou:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===yi&&(r=Yr.toString(r)),new ye(e,void 0,r)}}class Tn extends Xr{constructor(e){let r;if(e instanceof Xe)r=e;else if(Array.isArray(e)){const n=[];for(const s of e)if(s instanceof ie)n.push(s);else{const o=V.parse(new Dr(s.type,s.value).rawData,ie);n.push(o)}r=new Xe(n)}else if(K.isBufferSource(e))r=V.parse(e,Xe);else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(r)}onInit(e){const r=[];for(const n of e){let s=null;try{s=new Dr(n)}catch{continue}r.push(s)}this.items=r}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){const e=super.toTextObjectEmpty();for(const r of this.items){const n=r.toTextObject();let s=e[n[ye.NAME]];Array.isArray(s)||(s=[],e[n[ye.NAME]]=s),s.push(n)}return e}}Tn.NAME="GeneralNames";const ho="-{5}",Mo="\\n",MI=`[^${Mo}]+`,RI=`${ho}BEGIN (${MI}(?=${ho}))${ho}`,jI=`${ho}END \\1${ho}`,gs="\\n",DI=`[^:${Mo}]+`,PI=`(?:[^${Mo}]+${gs}(?: +[^${Mo}]+${gs})*)`,LI="[a-zA-Z0-9=+/]+",UI=`(?:${LI}${gs})+`,Fm=`${RI}${gs}(?:((?:${DI}: ${PI})+))?${gs}?(${UI})${jI}`,HI=new RegExp(`[${Mo}]+`,"g");class vt{static isPem(e){return typeof e=="string"&&new RegExp(Fm,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const r=new RegExp(Fm,"g"),n=[];let s=null;for(;s=r.exec(e);){const o=s[3].replace(HI,""),i={type:s[1],headers:[],rawData:ee.FromBase64(o)},a=s[2];if(a){const c=a.split(new RegExp(gs,"g"));let u=null;for(const l of c){const[d,m]=l.split(/:(.*)/);if(m===void 0){if(!u)throw new Error("Cannot parse PEM string. Incorrect header value");u.value+=d.trim()}else u&&i.headers.push(u),u={key:d,value:m.trim()}}u&&i.headers.push(u)}n.push(i)}return n}static decode(e){return this.decodeWithHeaders(e).map(n=>n.rawData)}static decodeFirst(e){const r=this.decode(e);if(!r.length)throw new RangeError("PEM string doesn't contain any objects");return r[0]}static encode(e,r){if(Array.isArray(e)){const n=new Array;return r?e.forEach(s=>{if(!K.isBufferSource(s))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");n.push(this.encodeStruct({type:r,rawData:K.toArrayBuffer(s)}))}):e.forEach(s=>{if(!("type"in s))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");n.push(this.encodeStruct(s))}),n.join(`
376
+ `)}else{if(!r)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:r,rawData:K.toArrayBuffer(e)})}}static encodeStruct(e){var r;const n=e.type.toLocaleUpperCase(),s=[];if(s.push(`-----BEGIN ${n}-----`),!((r=e.headers)===null||r===void 0)&&r.length){for(const i of e.headers)s.push(`${i.key}: ${i.value}`);s.push("")}const o=ee.ToBase64(e.rawData);for(let i=0;i<o.length;i+=64)s.push(o.substring(i,i+64));return s.push(`-----END ${n}-----`),s.join(`
377
+ `)}}vt.CertificateTag="CERTIFICATE";vt.CrlTag="CRL";vt.CertificateRequestTag="CERTIFICATE REQUEST";vt.PublicKeyTag="PUBLIC KEY";vt.PrivateKeyTag="PRIVATE KEY";class xr extends Xr{static isAsnEncoded(e){return K.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(vt.isPem(e))return vt.decode(e)[0];if(ee.isHex(e))return ee.FromHex(e);if(ee.isBase64(e))return ee.FromBase64(e);if(ee.isBase64Url(e))return ee.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{const r=K.toUint8Array(e);if(r.length>0&&r[0]===48)return K.toArrayBuffer(e);const n=ee.ToBinary(e);if(vt.isPem(n))return vt.decode(n)[0];if(ee.isHex(n))return ee.FromHex(n);if(ee.isBase64(n))return ee.FromBase64(n);if(ee.isBase64Url(n))return ee.FromBase64Url(n);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){xr.isAsnEncoded(e[0])?super(xr.toArrayBuffer(e[0]),e[1],e[2]):super(e[0],e[1])}toString(e="pem"){return e==="pem"?vt.encode(this.rawData,this.tag):super.toString(e)}}class Ft extends xr{static async create(e,r=ct.get()){if(e instanceof Ft)return e;if(jr.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");const n=await r.subtle.exportKey("spki",e);return new Ft(n)}else{if(e.publicKey)return e.publicKey;if(K.isBufferSource(e))return new Ft(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e,r){xr.isAsnEncoded(e)?super(e,Nt,r):super(e,r),this.tag=vt.PublicKeyTag}async export(e,r,n){let s,o=["verify"],i={hash:"SHA-256",...this.algorithm};r?(i=e,o=r,s=n):s=e,s??(s=ct.get());let a=this.rawData;const c=V.parse(this.rawData,Nt,this.parseOptions);return c.algorithm.algorithm===po&&(a=VI(c,a)),s.subtle.importKey("spki",a,i,!0,o)}onInit(e){const r=He.resolve(On),n=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===xn){const s=V.parse(e.subjectPublicKey,gf,this.parseOptions),o=K.toUint8Array(s.modulus);n.publicExponent=K.toUint8Array(s.publicExponent),n.modulusLength=(o[0]?o:o.slice(1)).byteLength<<3}}async getThumbprint(e,r){let n,s="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(s=e,n=r)),n??(n=ct.get()),await n.subtle.digest(s,this.rawData)}async getKeyIdentifier(e,r){let n,s="SHA-1";e&&(typeof e=="object"&&"subtle"in e?n=e:(s=e,n=r)),n??(n=ct.get());const o=V.parse(this.rawData,Nt,this.parseOptions);return await n.subtle.digest(s,o.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),r=V.parse(this.rawData,Nt,this.parseOptions);switch(e.Algorithm=Nn.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case To:e["EC Point"]=r.subjectPublicKey;break;case xn:default:e["Raw Data"]=r.subjectPublicKey}return e}}function VI(t,e){return t.algorithm=new W({algorithm:xn,parameters:null}),e=V.serialize(t),e}class $n extends At{static async create(e,r=!1,n=ct.get()){if("name"in e&&"serialNumber"in e)return new $n(e,r);const o=await(await Ft.create(e,n)).getKeyIdentifier(n);return new $n(ee.ToHex(o),r)}constructor(...e){if(K.isBufferSource(e[0]))super(e[0],e[1]);else if(typeof e[0]=="string"){const r=new on({keyIdentifier:new Jd(ee.FromHex(e[0]))});super(Lu,e[1],V.serialize(r))}else{const r=e[0],n=r.name instanceof Tn?V.parse(r.name.rawData,Xe):r.name,s=new on({authorityCertIssuer:n,authorityCertSerialNumber:ee.FromHex(r.serialNumber)});super(Lu,e[1],V.serialize(s))}}onInit(e){super.onInit(e);const r=V.parse(e.extnValue,on,this.parseOptions);r.keyIdentifier&&(this.keyId=ee.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?ee.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),r=V.parse(this.value,on,this.parseOptions);return r.authorityCertIssuer&&(e["Authority Issuer"]=new Tn(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}}$n.NAME="Authority Key Identifier";class Ro extends At{constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=V.parse(this.value,Ki,this.parseOptions);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{const r=new Ki({cA:e[0],pathLenConstraint:e[1]});super(Vv,e[2],V.serialize(r)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e["Path Length"]=this.pathLength),e}}Ro.NAME="Basic Constraints";var Wm;(function(t){t.serverAuth="1.3.6.1.5.5.7.3.1",t.clientAuth="1.3.6.1.5.5.7.3.2",t.codeSigning="1.3.6.1.5.5.7.3.3",t.emailProtection="1.3.6.1.5.5.7.3.4",t.timeStamping="1.3.6.1.5.5.7.3.8",t.ocspSigning="1.3.6.1.5.5.7.3.9"})(Wm||(Wm={}));class Oc extends At{constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=V.parse(this.value,Yi,this.parseOptions);this.usages=r.map(n=>n)}else{const r=new Yi(e[0]);super(Kv,e[1],V.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>Yr.toString(r)).join(", "),e}}Oc.NAME="Extended Key Usages";var rs;(function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"})(rs||(rs={}));class jo extends At{constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=V.parse(this.value,ru,this.parseOptions);this.usages=r.toNumber()}else{const r=new ru(e[0]);super(qv,e[1],V.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=V.parse(this.value,ru,this.parseOptions);return e[""]=r.toJSON().join(", "),e}}jo.NAME="Key Usages";class ni extends At{static async create(e,r=!1,n=ct.get()){const o=await(await Ft.create(e,n)).getKeyIdentifier(n);return new ni(ee.ToHex(o),r)}constructor(...e){if(K.isBufferSource(e[0])){super(e[0],e[1]);const r=V.parse(this.value,Lr,this.parseOptions);this.keyId=ee.ToHex(r)}else{const r=typeof e[0]=="string"?ee.FromHex(e[0]):e[0],n=new Lr(r);super(Jv,e[1],V.serialize(n)),this.keyId=ee.ToHex(r)}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=V.parse(this.value,Lr,this.parseOptions);return e[""]=r,e}}ni.NAME="Subject Key Identifier";class Sf extends At{constructor(...e){K.isBufferSource(e[0])?super(e[0],e[1]):super(Xv,e[1],new Tn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=V.parse(e.extnValue,el,this.parseOptions);this.names=new Tn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}Sf.NAME="Subject Alternative Name";class kt{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new At(e,r),s=this.items.get(n.type);return s?new s(e,r):n}}kt.items=new Map;class xb extends At{constructor(...e){var r;if(K.isBufferSource(e[0])){super(e[0],e[1]);const n=V.parse(this.value,qi,this.parseOptions);this.policies=n.map(s=>s.policyIdentifier)}else{const n=e[0],s=(r=e[1])!==null&&r!==void 0?r:!1,o=new qi(n.map(i=>new ic({policyIdentifier:i})));super(Fv,s,V.serialize(o)),this.policies=n}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new ye("",{},Yr.toString(r))),e}}xb.NAME="Certificate Policies";kt.register(Fv,xb);class Ib extends At{constructor(...e){var r;if(K.isBufferSource(e[0]))super(e[0],e[1]);else if(Array.isArray(e[0])&&typeof e[0][0]=="string"){const s=e[0].map(i=>new ks({distributionPoint:new Sn({fullName:[new ie({uniformResourceIdentifier:i})]})})),o=new ts(s);super(Wu,e[1],V.serialize(o))}else{const n=new ts(e[0]);super(Wu,e[1],V.serialize(n))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);const r=V.parse(e.extnValue,ts,this.parseOptions);this.distributionPoints=r}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var n;const s=new ye("");return!((n=r.distributionPoint)===null||n===void 0)&&n.fullName&&(s[""]=r.distributionPoint.fullName.map(o=>new Dr(o).toString()).join(", ")),r.reasons&&(s.Reasons=r.reasons.toString()),r.cRLIssuer&&(s["CRL Issuer"]=r.cRLIssuer.map(o=>o.toString()).join(", ")),s}),e}}Ib.NAME="CRL Distribution Points";class Cb extends At{constructor(...e){var r,n,s,o;if(K.isBufferSource(e[0]))super(e[0],e[1]);else if(e[0]instanceof Xn){const i=new Xn(e[0]);super(Pu,e[1],V.serialize(i))}else{const i=e[0],a=new Xn;vi(a,i,oh,"ocsp"),vi(a,i,ih,"caIssuers"),vi(a,i,ah,"timeStamping"),vi(a,i,ch,"caRepository"),super(Pu,e[1],V.serialize(a))}(r=this.ocsp)!==null&&r!==void 0||(this.ocsp=[]),(n=this.caIssuers)!==null&&n!==void 0||(this.caIssuers=[]),(s=this.timeStamping)!==null&&s!==void 0||(this.timeStamping=[]),(o=this.caRepository)!==null&&o!==void 0||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],V.parse(e.extnValue,Xn,this.parseOptions).forEach(n=>{switch(n.accessMethod){case oh:this.ocsp.push(new Dr(n.accessLocation));break;case ih:this.caIssuers.push(new Dr(n.accessLocation));break;case ah:this.timeStamping.push(new Dr(n.accessLocation));break;case ch:this.caRepository.push(new Dr(n.accessLocation));break}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&gi(e,"OCSP",this.ocsp),this.caIssuers.length&&gi(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&gi(e,"Time Stamping",this.timeStamping),this.caRepository.length&&gi(e,"CA Repository",this.caRepository),e}}Cb.NAME="Authority Info Access";function gi(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{const n=new ye("");r.forEach((s,o)=>{const i=s.toTextObject(),a=`${i[ye.NAME]} ${o+1}`;let c=n[a];Array.isArray(c)||(c=[],n[a]=c),c.push(i)}),t[e]=n}}function vi(t,e,r,n){const s=e[n];s&&(Array.isArray(s)?s:[s]).forEach(i=>{typeof i=="string"&&(i=new Dr("url",i)),t.push(new Ko({accessMethod:r,accessLocation:V.parse(i.rawData,ie)}))})}class Ob extends At{constructor(...e){K.isBufferSource(e[0])?super(e[0],e[1]):super(Gv,e[1],new Tn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=V.parse(e.extnValue,Xe,this.parseOptions);this.names=new Tn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}Ob.NAME="Issuer Alternative Name";class $s extends Xr{constructor(...e){let r,n;if(K.isBufferSource(e[0]))r=K.toArrayBuffer(e[0]),n=e[1];else{const s=e[0],o=Array.isArray(e[1])?e[1].map(i=>K.toArrayBuffer(i)):[];r=V.serialize(new Ar({type:s,values:o}))}super(r,Ar,n)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new ye("",{"":r})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[ye.NAME]===$s.NAME&&(e[ye.NAME]=Yr.toString(this.type)),e}}$s.NAME="Attribute";class Nb extends $s{constructor(...e){var r;if(K.isBufferSource(e[0]))super(e[0],e[1]);else{const n=new wa({printableString:e[0]});super(bb,[V.serialize(n)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const r=V.parse(this.values[0],wa,this.parseOptions);this.password=r.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[ye.VALUE]=this.password,e}}Nb.NAME="Challenge Password";class Af extends $s{constructor(...e){var r;if(K.isBufferSource(e[0]))super(e[0],e[1]);else{const n=e[0],s=new Vr;for(const o of n)s.push(V.parse(o.rawData,Kt));super(wf,[V.serialize(s)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const r=V.parse(this.values[0],Vr,this.parseOptions);this.items=r.map(n=>kt.create(V.serialize(n),this.parseOptions))}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.items.map(n=>n.toTextObject());for(const n of r)e[n[ye.NAME]]=n;return e}}Af.NAME="Extensions";class Nc{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new $s(e,r),s=this.items.get(n.type);return s?new s(e,r):n}}Nc.items=new Map;const si="crypto.signatureFormatter";class FI{toAsnSignature(e,r){return K.toArrayBuffer(r)}toWebSignature(e,r){return K.toArrayBuffer(r)}}var Ci;let Yl=Ci=class{static createPssParams(e,r){const n=Ci.getHashAlgorithm(e);return n?new Cn({hashAlgorithm:n,maskGenAlgorithm:new W({algorithm:wc,parameters:V.serialize(n)}),saltLength:r}):null}static getHashAlgorithm(e){const r=He.resolve(On);return typeof e=="string"?r.toAsnAlgorithm({name:e}):typeof e=="object"&&e&&"name"in e?r.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if("hash"in e){let r;if(typeof e.hash=="string")r=e.hash;else if(e.hash&&typeof e.hash=="object"&&"name"in e.hash&&typeof e.hash.name=="string")r=e.hash.name.toUpperCase();else throw new Error("Cannot get hash algorithm name");switch(r.toLowerCase()){case"sha-1":return new W({algorithm:ua,parameters:null});case"sha-256":return new W({algorithm:Sl,parameters:null});case"sha-384":return new W({algorithm:la,parameters:null});case"sha-512":return new W({algorithm:da,parameters:null})}}else return new W({algorithm:xn,parameters:null});break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e&&typeof e.saltLength=="number"))throw new Error("Cannot get 'saltLength' from 'alg' argument");const r=Ci.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new W({algorithm:po,parameters:V.serialize(r)})}else return new W({algorithm:po,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case xn:return{name:"RSASSA-PKCS1-v1_5"};case ua:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Sl:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case la:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case da:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case po:if(e.parameters){const r=V.parse(e.parameters,Cn);return{name:"RSA-PSS",hash:He.resolve(On).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};Yl=Ci=f([Ns()],Yl);He.registerSingleton(Dn,Yl);let Xl=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new W({algorithm:fa});case"sha-256":return new W({algorithm:pa});case"sha-384":return new W({algorithm:ha});case"sha-512":return new W({algorithm:ma})}return null}toWebAlgorithm(e){switch(e.algorithm){case fa:return{name:"SHA-1"};case pa:return{name:"SHA-256"};case ha:return{name:"SHA-384"};case ma:return{name:"SHA-512"}}return null}};Xl=f([Ns()],Xl);He.registerSingleton(Dn,Xl);class Tt{addPadding(e,r){const n=K.toUint8Array(r),s=new Uint8Array(e);return s.set(n,e-n.length),s.buffer}removePadding(e,r=!1){let n=K.toUint8Array(e);for(let s=0;s<n.length;s++)if(n[s]){n=n.slice(s);break}if(r&&n[0]>127){const s=new Uint8Array(n.length+1);return s.set(n,1),s.buffer}return n.buffer}toAsnSignature(e,r){if(e.name==="ECDSA"){const n=e.namedCurve,s=Tt.namedCurveSize.get(n)||Tt.defaultNamedCurveSize,o=new ca,i=K.toUint8Array(r);return o.r=this.removePadding(i.slice(0,s),!0),o.s=this.removePadding(i.slice(s,s+s),!0),V.serialize(o)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){const n=V.parse(r,ca),s=e.namedCurve,o=Tt.namedCurveSize.get(s)||Tt.defaultNamedCurveSize,i=this.addPadding(o,this.removePadding(n.r)),a=this.addPadding(o,this.removePadding(n.s));return eE(i,a)}return null}}Tt.namedCurveSize=new Map;Tt.defaultNamedCurveSize=32;const lu="1.3.101.110",Km="1.3.101.111",du="1.3.101.112",Gm="1.3.101.113";let Jl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=du;break;case"x25519":r=lu;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=du;break;case"ed448":r=Gm;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=lu;break;case"x448":r=Km;break}}return r?new W({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case du:return{name:"Ed25519"};case Gm:return{name:"EdDSA",namedCurve:"Ed448"};case lu:return{name:"X25519"};case Km:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};Jl=f([Ns()],Jl);He.registerSingleton(Dn,Jl);let Zl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ml-dsa-44":r=Xh;break;case"ml-dsa-65":r=Jh;break;case"ml-dsa-87":r=Zh;break}return r?new W({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case Xh:return{name:"ML-DSA-44"};case Jh:return{name:"ML-DSA-65"};case Zh:return{name:"ML-DSA-87"}}return null}};Zl=f([Ns()],Zl);He.registerSingleton(Dn,Zl);let Ql=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"slh-dsa-sha2-128s":r=Qh;break;case"slh-dsa-sha2-128f":r=em;break;case"slh-dsa-sha2-192s":r=tm;break;case"slh-dsa-sha2-192f":r=rm;break;case"slh-dsa-sha2-256s":r=nm;break;case"slh-dsa-sha2-256f":r=sm;break;case"slh-dsa-shake-128s":r=om;break;case"slh-dsa-shake-128f":r=im;break;case"slh-dsa-shake-192s":r=am;break;case"slh-dsa-shake-192f":r=cm;break;case"slh-dsa-shake-256s":r=um;break;case"slh-dsa-shake-256f":r=lm;break}return r?new W({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case Qh:return{name:"SLH-DSA-SHA2-128s"};case em:return{name:"SLH-DSA-SHA2-128f"};case tm:return{name:"SLH-DSA-SHA2-192s"};case rm:return{name:"SLH-DSA-SHA2-192f"};case nm:return{name:"SLH-DSA-SHA2-256s"};case sm:return{name:"SLH-DSA-SHA2-256f"};case om:return{name:"SLH-DSA-SHAKE-128s"};case im:return{name:"SLH-DSA-SHAKE-128f"};case am:return{name:"SLH-DSA-SHAKE-192s"};case cm:return{name:"SLH-DSA-SHAKE-192f"};case um:return{name:"SLH-DSA-SHAKE-256s"};case lm:return{name:"SLH-DSA-SHAKE-256f"}}return null}};Ql=f([Ns()],Ql);He.registerSingleton(Dn,Ql);var Us,Hs,Vs,Fs,Ws,Ks,Gs,Wn;class WI extends xr{get subjectName(){return oe(this,Hs,"f")||xe(this,Hs,new Ut(this.asn.certificationRequestInfo.subject),"f"),oe(this,Hs,"f")}get subject(){return oe(this,Vs,"f")||xe(this,Vs,this.subjectName.toString(),"f"),oe(this,Vs,"f")}get signatureAlgorithm(){if(!oe(this,Fs,"f")){const e=He.resolve(On);xe(this,Fs,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return oe(this,Fs,"f")}get signature(){return oe(this,Ws,"f")||xe(this,Ws,this.asn.signature,"f"),oe(this,Ws,"f")}get publicKey(){return oe(this,Ks,"f")||xe(this,Ks,new Ft(this.asn.certificationRequestInfo.subjectPKInfo,this.parseOptions),"f"),oe(this,Ks,"f")}get attributes(){return oe(this,Gs,"f")||xe(this,Gs,this.asn.certificationRequestInfo.attributes.map(e=>Nc.create(V.serialize(e),this.parseOptions)),"f"),oe(this,Gs,"f")}get extensions(){if(!oe(this,Wn,"f")){xe(this,Wn,[],"f");const e=this.getAttribute(wf);e instanceof Af&&xe(this,Wn,e.items,"f")}return oe(this,Wn,"f")}get tbs(){return oe(this,Us,"f")||xe(this,Us,this.asn.certificationRequestInfoRaw||V.serialize(this.asn.certificationRequestInfo),"f"),oe(this,Us,"f")}constructor(e,r){const n=xr.isAsnEncoded(e)?[e,Bo,r]:[e,r];super(n[0],n[1],n[2]),Us.set(this,void 0),Hs.set(this,void 0),Vs.set(this,void 0),Fs.set(this,void 0),Ws.set(this,void 0),Ks.set(this,void 0),Gs.set(this,void 0),Wn.set(this,void 0),this.tag=vt.CertificateRequestTag}onInit(e){}getAttribute(e){for(const r of this.attributes)if(r.type===e)return r;return null}getAttributes(e){return this.attributes.filter(r=>r.type===e)}getExtension(e){for(const r of this.extensions)if(r.type===e)return r;return null}getExtensions(e){return this.extensions.filter(r=>r.type===e)}async verify(e=ct.get()){const r={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(r,["verify"],e),s=He.resolveAll(si).reverse();let o=null;for(const a of s)if(o=a.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await e.subtle.verify(this.signatureAlgorithm,n,o,this.tbs)}toTextObject(){const e=this.toTextObjectEmpty(),r=V.parse(this.rawData,Bo,this.parseOptions),n=r.certificationRequestInfo,s=new ye("",{Version:`${An[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const o=new ye("");for(const i of this.attributes){const a=i.toTextObject();o[a[ye.NAME]]=a}s.Attributes=o}return e.Data=s,e.Signature=new ye("",{Algorithm:Nn.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}}Us=new WeakMap,Hs=new WeakMap,Vs=new WeakMap,Fs=new WeakMap,Ws=new WeakMap,Ks=new WeakMap,Gs=new WeakMap,Wn=new WeakMap;WI.NAME="PKCS#10 Certificate Request";function KI(t){let e=0;for(;e<t.length-1&&t[e]===0;)e++;let r=t.slice(e);if(r.length||(r=new Uint8Array([0])),r[0]>127){const n=new Uint8Array(r.length+1);n[0]=0,n.set(r,1),r=n}return r.buffer}function GI(t,e=ct.get()){const r=K.toUint8Array(ee.FromHex(t||"")),n=r.length&&r.some(s=>s>0)?r:e.getRandomValues(new Uint8Array(16));return KI(n)}function qI(t){let e=K.toUint8Array(t);return e.length>1&&e[0]===0&&e[1]>127&&(e=e.slice(1)),ee.ToHex(e)}var qs,zs,Ys,Xs,Js,Zs,Qs,eo,to,ro,Kn,no;class Tb extends xr{get publicKey(){return oe(this,no,"f")||xe(this,no,new Ft(this.asn.tbsCertificate.subjectPublicKeyInfo,this.parseOptions),"f"),oe(this,no,"f")}get serialNumber(){return oe(this,zs,"f")||xe(this,zs,qI(this.asn.tbsCertificate.serialNumber),"f"),oe(this,zs,"f")}get subjectName(){return oe(this,Ys,"f")||xe(this,Ys,new Ut(this.asn.tbsCertificate.subject),"f"),oe(this,Ys,"f")}get subject(){return oe(this,Xs,"f")||xe(this,Xs,this.subjectName.toString(),"f"),oe(this,Xs,"f")}get issuerName(){return oe(this,Js,"f")||xe(this,Js,new Ut(this.asn.tbsCertificate.issuer),"f"),oe(this,Js,"f")}get issuer(){return oe(this,Zs,"f")||xe(this,Zs,this.issuerName.toString(),"f"),oe(this,Zs,"f")}get notBefore(){if(!oe(this,Qs,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");xe(this,Qs,e,"f")}return oe(this,Qs,"f")}get notAfter(){if(!oe(this,eo,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");xe(this,eo,e,"f")}return oe(this,eo,"f")}get signatureAlgorithm(){if(!oe(this,to,"f")){const e=He.resolve(On);xe(this,to,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return oe(this,to,"f")}get signature(){return oe(this,ro,"f")||xe(this,ro,this.asn.signatureValue,"f"),oe(this,ro,"f")}get extensions(){return oe(this,Kn,"f")||(xe(this,Kn,[],"f"),this.asn.tbsCertificate.extensions&&xe(this,Kn,this.asn.tbsCertificate.extensions.map(e=>kt.create(V.serialize(e),this.parseOptions)),"f")),oe(this,Kn,"f")}get tbs(){return oe(this,qs,"f")||xe(this,qs,this.asn.tbsCertificateRaw||V.serialize(this.asn.tbsCertificate),"f"),oe(this,qs,"f")}constructor(e,r){const n=xr.isAsnEncoded(e)?[e,kn,r]:[e,r];super(n[0],n[1],n[2]),qs.set(this,void 0),zs.set(this,void 0),Ys.set(this,void 0),Xs.set(this,void 0),Js.set(this,void 0),Zs.set(this,void 0),Qs.set(this,void 0),eo.set(this,void 0),to.set(this,void 0),ro.set(this,void 0),Kn.set(this,void 0),no.set(this,void 0),this.tag=vt.CertificateTag}onInit(e){}getExtension(e){for(const r of this.extensions)if(typeof e=="string"){if(r.type===e)return r}else if(r instanceof e)return r;return null}getExtensions(e){return this.extensions.filter(r=>typeof e=="string"?r.type===e:r instanceof e)}async verify(e={},r=ct.get()){let n,s;const o=e.publicKey;try{if(!o)n={...this.publicKey.algorithm,...this.signatureAlgorithm},s=await this.publicKey.export(n,["verify"],r);else if("publicKey"in o)n={...o.publicKey.algorithm,...this.signatureAlgorithm},s=await o.publicKey.export(n,["verify"],r);else if(o instanceof Ft)n={...o.algorithm,...this.signatureAlgorithm},s=await o.export(n,["verify"],r);else if(K.isBufferSource(o)){const u=new Ft(o);n={...u.algorithm,...this.signatureAlgorithm},s=await u.export(n,["verify"],r)}else n={...o.algorithm,...this.signatureAlgorithm},s=o}catch{return!1}const i=He.resolveAll(si).reverse();let a=null;for(const u of i)if(a=u.toWebSignature(n,this.signature),a)break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const c=await r.subtle.verify(this.signatureAlgorithm,s,a,this.tbs);if(e.signatureOnly)return c;{const l=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<l&&l<this.notAfter.getTime()}}async getThumbprint(e,r){let n,s="SHA-1";return e&&(typeof e=="object"&&"subtle"in e?n=e:(s=e,n=r)),n??(n=ct.get()),await n.subtle.digest(s,this.rawData)}async isSelfSigned(e=ct.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),r=V.parse(this.rawData,kn,this.parseOptions),n=r.tbsCertificate,s=new ye("",{Version:`${An[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":Nn.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new ye("",{"Not Before":n.validity.notBefore.getTime(),"Not After":n.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(n.issuerUniqueID&&(s["Issuer Unique ID"]=n.issuerUniqueID),n.subjectUniqueID&&(s["Subject Unique ID"]=n.subjectUniqueID),this.extensions.length){const o=new ye("");for(const i of this.extensions){const a=i.toTextObject();o[a[ye.NAME]]=a}s.Extensions=o}return e.Data=s,e.Signature=new ye("",{Algorithm:Nn.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}}qs=new WeakMap,zs=new WeakMap,Ys=new WeakMap,Xs=new WeakMap,Js=new WeakMap,Zs=new WeakMap,Qs=new WeakMap,eo=new WeakMap,to=new WeakMap,ro=new WeakMap,Kn=new WeakMap,no=new WeakMap;Tb.NAME="Certificate";class ed{static async createSelfSigned(e,r=ct.get()){if(!e.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},r)}static async create(e,r=ct.get()){var n;let s;e.publicKey instanceof Ft?s=e.publicKey.rawData:"publicKey"in e.publicKey?s=e.publicKey.publicKey.rawData:K.isBufferSource(e.publicKey)?s=e.publicKey:s=await r.subtle.exportKey("spki",e.publicKey);const o=GI(e.serialNumber,r),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),c=new kn({tbsCertificate:new St({version:An.v3,serialNumber:o,validity:new Go({notBefore:i,notAfter:a}),extensions:new Vr(((n=e.extensions)===null||n===void 0?void 0:n.map(v=>V.parse(v.rawData,Kt)))||[]),subjectPublicKeyInfo:V.parse(s,Nt)})});if(e.subject){const v=e.subject instanceof Ut?e.subject:new Ut(e.subject);c.tbsCertificate.subject=V.parse(v.toArrayBuffer(),je)}if(e.issuer){const v=e.issuer instanceof Ut?e.issuer:new Ut(e.issuer);c.tbsCertificate.issuer=V.parse(v.toArrayBuffer(),je)}const u={hash:"SHA-256"},l="signingKey"in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},d=He.resolve(On);c.tbsCertificate.signature=c.signatureAlgorithm=d.toAsnAlgorithm(l);const m=V.serialize(c.tbsCertificate),p="signingKey"in e?await r.subtle.sign(l,e.signingKey,m):e.signature,h=He.resolveAll(si).reverse();let g=null;for(const v of h)if(g=v.toAsnSignature(l,p),g)break;if(!g)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=g,new Tb(V.serialize(c))}}var qm;(function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"})(qm||(qm={}));kt.register(Vv,Ro);kt.register(Kv,Oc);kt.register(qv,jo);kt.register(Jv,ni);kt.register(Lu,$n);kt.register(Xv,Sf);kt.register(Wu,Ib);kt.register(Pu,Cb);kt.register(Gv,Ob);Nc.register(bb,Nb);Nc.register(wf,Af);He.registerSingleton(si,FI);He.registerSingleton(si,Tt);Tt.namedCurveSize.set("P-256",32);Tt.namedCurveSize.set("K-256",32);Tt.namedCurveSize.set("P-384",48);Tt.namedCurveSize.set("P-521",66);const it=Yb,td={name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"},Do={name:"ECDSA",namedCurve:"P-256"},zI="1.3.6.1.5.5.7.3.1",YI="1.3.6.1.5.5.7.3.2",rd=6e4,nd=864e5;function $b(t){return`${t}.display`}function XI(t,e){const r=Buffer.from(e).toString("base64").match(/.{1,64}/g)?.join(`
122
378
  `)??"";return`-----BEGIN ${t}-----
123
379
  ${r}
124
380
  -----END ${t}-----
125
- `}function mI(t,e){const r=`${t}.${process.pid}.tmp`;Wl(r,e,{mode:384}),Kl(r,t),pa(t,384)}async function $m(t){return{privateKey:await st.subtle.exportKey("jwk",t.privateKey),publicKey:await st.subtle.exportKey("jwk",t.publicKey)}}async function Bm(t){return{privateKey:await st.subtle.importKey("jwk",t.privateKey,Ns,!0,["sign"]),publicKey:await st.subtle.importKey("jwk",t.publicKey,Ns,!0,["verify"])}}function mb(t){const e=new Jo(t).publicKey.export({format:"jwk"});if(!e.x||!e.y)throw new Error("057 Display CA is not a P-256 key");const r=Buffer.concat([Buffer.from([4]),Buffer.from(e.x,"base64url"),Buffer.from(e.y,"base64url")]);return fo("sha256").update(r).digest("base64url")}async function yI(){const t=Date.now(),e=await st.subtle.generateKey(Ns,!0,["sign","verify"]),r=await Pl.createSelfSigned({name:"CN=057 Display Core",keys:e,serialNumber:Yn(16).toString("hex"),notBefore:new Date(t-5*Vl),notAfter:new Date(t+10*365*Hl),signingAlgorithm:Ul,extensions:[new Os(!0,0,!0),new Cs(zn.keyCertSign|zn.cRLSign,!0),await Ys.create(e.publicKey,!1,st)]},st),n=r.toString("pem"),o=mb(n),s=fo("sha256").update(o).digest("hex").slice(0,20),i=await st.subtle.generateKey(Ns,!0,["sign","verify"]),a=await Pl.create({subject:`CN=057 Display ${s}`,issuer:r.subject,publicKey:i.publicKey,signingKey:e.privateKey,serialNumber:Yn(16).toString("hex"),notBefore:new Date(t-5*Vl),notAfter:new Date(t+2*365*Hl),signingAlgorithm:Ul,extensions:[new Os(!1,void 0,!0),new Cs(zn.digitalSignature,!0),new yc([fI],!0),new sf([{type:"dns",value:"057-display.local"},{type:"ip",value:"127.0.0.1"}]),await En.create(e.publicKey,!1,st)]},st);return{version:1,coreId:s,caPin:o,caCertificate:n,serverCertificate:a.toString("pem"),caKeys:await $m(e),serverKeys:await $m(i)}}async function gI(t){if(t.caPin!==mb(t.caCertificate))throw new Error("057 Display CA pin does not match its certificate");const e=await Bm(t.caKeys),r=await Bm(t.serverKeys),n=hI("PRIVATE KEY",await st.subtle.exportKey("pkcs8",r.privateKey));return{coreId:t.coreId,caPin:t.caPin,serverPin:fo("sha256").update(new Jo(t.serverCertificate).raw).digest("base64url"),caCertificate:t.caCertificate,serverCertificate:t.serverCertificate,serverPrivateKey:n,async issueClient(o,s){const i=new ArrayBuffer(o.byteLength);new Uint8Array(i).set(o);const a=await st.subtle.importKey("raw",i,Ns,!0,["verify"]),c=Date.now(),u=c+5*365*Hl,l=(await Pl.create({subject:`CN=${s.replace(/[,+\"\\<>;]/g," ").slice(0,80)||"057 Display"}`,issuer:new Jo(t.caCertificate).subject,publicKey:a,signingKey:e.privateKey,serialNumber:Yn(16).toString("hex"),notBefore:new Date(c-5*Vl),notAfter:new Date(u),signingAlgorithm:Ul,extensions:[new Os(!1,void 0,!0),new Cs(zn.digitalSignature,!0),new yc([pI],!0),await En.create(e.publicKey,!1,st)]},st)).toString("pem"),m=new Jo(l);return{certificate:l,certificateDer:Buffer.from(m.raw).toString("base64"),serial:m.serialNumber.toLowerCase(),fingerprint:m.fingerprint256.replaceAll(":","").toLowerCase(),expiresAt:u}}}}async function vI(t){const e=hb(t),r=ue(e,"identity.json");eu(vi(e),{recursive:!0,mode:448}),eu(e,{recursive:!0,mode:448}),pa(e,448);let n;if(ge(r)){if(n=JSON.parse(Gl(r,"utf8")),n.version!==1)throw new Error(`unsupported 057 Display identity version ${String(n.version)}`)}else n=await yI(),mI(r,`${JSON.stringify(n)}
126
- `);return gI(n)}const bI=4e3,wI=8e3;function AI(t,e,r){t.statusCode=200,t.setHeader("content-type","text/event-stream; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("connection","keep-alive"),t.setHeader("x-content-type-options","nosniff"),t.flushHeaders();let n=!1,o=!1,s;const i=()=>{n=!0,clearInterval(c),clearInterval(u)},a=async()=>{if(!(n||o)){o=!0;try{const d=await e();if(n)return;d.wire!==s&&(s=d.wire,t.write(`id: ${d.id}
381
+ `}function JI(t,e){const r=`${t}.${process.pid}.tmp`;od(r,e,{mode:384}),id(r,t),Ea(t,384)}async function zm(t){return{privateKey:await it.subtle.exportKey("jwk",t.privateKey),publicKey:await it.subtle.exportKey("jwk",t.publicKey)}}async function Ym(t){return{privateKey:await it.subtle.importKey("jwk",t.privateKey,Do,!0,["sign"]),publicKey:await it.subtle.importKey("jwk",t.publicKey,Do,!0,["verify"])}}function Bb(t){const e=new so(t).publicKey.export({format:"jwk"});if(!e.x||!e.y)throw new Error("057 Display CA is not a P-256 key");const r=Buffer.concat([Buffer.from([4]),Buffer.from(e.x,"base64url"),Buffer.from(e.y,"base64url")]);return vs("sha256").update(r).digest("base64url")}async function ZI(){const t=Date.now(),e=await it.subtle.generateKey(Do,!0,["sign","verify"]),r=await ed.createSelfSigned({name:"CN=057 Display Core",keys:e,serialNumber:pn(16).toString("hex"),notBefore:new Date(t-5*rd),notAfter:new Date(t+10*365*nd),signingAlgorithm:td,extensions:[new Ro(!0,0,!0),new jo(rs.keyCertSign|rs.cRLSign,!0),await ni.create(e.publicKey,!1,it)]},it),n=r.toString("pem"),s=Bb(n),o=vs("sha256").update(s).digest("hex").slice(0,20),i=await it.subtle.generateKey(Do,!0,["sign","verify"]),a=await ed.create({subject:`CN=057 Display ${o}`,issuer:r.subject,publicKey:i.publicKey,signingKey:e.privateKey,serialNumber:pn(16).toString("hex"),notBefore:new Date(t-5*rd),notAfter:new Date(t+2*365*nd),signingAlgorithm:td,extensions:[new Ro(!1,void 0,!0),new jo(rs.digitalSignature,!0),new Oc([zI],!0),new Sf([{type:"dns",value:"057-display.local"},{type:"ip",value:"127.0.0.1"}]),await $n.create(e.publicKey,!1,it)]},it);return{version:1,coreId:o,caPin:s,caCertificate:n,serverCertificate:a.toString("pem"),caKeys:await zm(e),serverKeys:await zm(i)}}async function QI(t){if(t.caPin!==Bb(t.caCertificate))throw new Error("057 Display CA pin does not match its certificate");const e=await Ym(t.caKeys),r=await Ym(t.serverKeys),n=XI("PRIVATE KEY",await it.subtle.exportKey("pkcs8",r.privateKey));return{coreId:t.coreId,caPin:t.caPin,serverPin:vs("sha256").update(new so(t.serverCertificate).raw).digest("base64url"),caCertificate:t.caCertificate,serverCertificate:t.serverCertificate,serverPrivateKey:n,async issueClient(s,o){const i=new ArrayBuffer(s.byteLength);new Uint8Array(i).set(s);const a=await it.subtle.importKey("raw",i,Do,!0,["verify"]),c=Date.now(),u=c+5*365*nd,d=(await ed.create({subject:`CN=${o.replace(/[,+\"\\<>;]/g," ").slice(0,80)||"057 Display"}`,issuer:new so(t.caCertificate).subject,publicKey:a,signingKey:e.privateKey,serialNumber:pn(16).toString("hex"),notBefore:new Date(c-5*rd),notAfter:new Date(u),signingAlgorithm:td,extensions:[new Ro(!1,void 0,!0),new jo(rs.digitalSignature,!0),new Oc([YI],!0),await $n.create(e.publicKey,!1,it)]},it)).toString("pem"),m=new so(d);return{certificate:d,certificateDer:Buffer.from(m.raw).toString("base64"),serial:m.serialNumber.toLowerCase(),fingerprint:m.fingerprint256.replaceAll(":","").toLowerCase(),expiresAt:u}}}}async function e1(t){const e=$b(t),r=ue(e,"identity.json");pu(Oi(e),{recursive:!0,mode:448}),pu(e,{recursive:!0,mode:448}),Ea(e,448);let n;if(ve(r)){if(n=JSON.parse(ad(r,"utf8")),n.version!==1)throw new Error(`unsupported 057 Display identity version ${String(n.version)}`)}else n=await ZI(),JI(r,`${JSON.stringify(n)}
382
+ `);return QI(n)}const t1=4e3,r1=8e3;function n1(t,e,r){t.statusCode=200,t.setHeader("content-type","text/event-stream; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("connection","keep-alive"),t.setHeader("x-content-type-options","nosniff"),t.flushHeaders();let n=!1,s=!1,o;const i=()=>{n=!0,clearInterval(c),clearInterval(u)},a=async()=>{if(!(n||s)){s=!0;try{const l=await e();if(n)return;l.wire!==o&&(o=l.wire,t.write(`id: ${l.id}
127
383
  event: landscape
128
- data: ${d.wire}
384
+ data: ${l.wire}
129
385
 
130
- `))}catch(d){n||(r(d),i(),t.end())}finally{o=!1}}},c=setInterval(()=>{a()},bI),u=setInterval(()=>{n||t.write(`: 057
386
+ `))}catch(l){n||(r(l),i(),t.end())}finally{s=!1}}},c=setInterval(()=>{a()},t1),u=setInterval(()=>{n||t.write(`: 057
131
387
 
132
- `)},wI);t.once("close",i),a()}const da=1,SI=12e4;function kI(t,e){const r=`${t}.${process.pid}.tmp`;Wl(r,e,{mode:384}),Kl(r,t),pa(t,384)}class EI{path;state;constructor(e){if(this.path=ue(e,"trusted.json"),this.state=ge(this.path)?JSON.parse(Gl(this.path,"utf8")):{version:1,displays:[]},this.state.version!==1)throw new Error(`unsupported 057 Display trust version ${String(this.state.version)}`)}list(){return this.state.displays.map(e=>({...e}))}trusts(e){const r=e.replaceAll(":","").toLowerCase();return this.state.displays.some(n=>n.fingerprint===r&&n.revokedAt===void 0&&n.expiresAt>Date.now())}add(e,r){const n=this.state.displays.find(o=>o.deviceId===e.deviceId&&o.revokedAt===void 0);n&&(n.revokedAt=Date.now()),this.state.displays.push({deviceId:e.deviceId,name:e.deviceName.slice(0,80)||"iPhone",fingerprint:r.fingerprint,serial:r.serial,pairedAt:Date.now(),expiresAt:r.expiresAt}),this.save()}revoke(e){const r=this.state.displays.find(n=>n.deviceId===e&&n.revokedAt===void 0);return r?(r.revokedAt=Date.now(),this.save(),!0):!1}save(){kI(this.path,`${JSON.stringify(this.state,null,1)}
133
- `)}}function xI(t){return Buffer.concat([Buffer.from("057.display.pair.v1\0","utf8"),Buffer.from(t.grantId,"utf8"),Buffer.from([0]),Buffer.from(t.coreId,"utf8"),Buffer.from([0]),Buffer.from(t.deviceId,"utf8"),Buffer.from([0]),Buffer.from(t.publicKey,"base64")])}function II(t){if(t.length!==65||t[0]!==4)throw new Error("the Display public key is not an uncompressed P-256 point");return _b({key:{kty:"EC",crv:"P-256",x:t.subarray(1,33).toString("base64url"),y:t.subarray(33,65).toString("base64url")},format:"jwk"})}class OI{constructor(e){this.identity=e}identity;grants=new Map;create(e=Date.now()){this.grants.clear();const r={id:Yn(18).toString("base64url"),secret:Yn(32),expiresAt:e+SI};this.grants.set(r.id,r);const n={p:da,id:this.identity.coreId,pin:this.identity.caPin,sp:this.identity.serverPin,grant:r.id,secret:Buffer.from(r.secret).toString("base64url"),expires:r.expiresAt};return{payload:n,uri:`o57-display://pair#${Buffer.from(JSON.stringify(n)).toString("base64url")}`}}async redeem(e,r,n=Date.now()){if(e.protocol!==da)throw new Error("unsupported pairing protocol");if(e.coreId!==this.identity.coreId)throw new Error("pairing grant belongs to another Core");const o=this.grants.get(e.grantId);if(!o||o.expiresAt<=n)throw this.grants.delete(e.grantId),new Error("pairing grant is missing or expired");const s=Buffer.from(e.secret,"base64url");if(s.length!==o.secret.length||!Rb(s,o.secret))throw new Error("pairing grant is invalid");this.grants.delete(e.grantId);const i=Buffer.from(e.publicKey,"base64"),a=Buffer.from(e.signature,"base64");if(!Mb("sha256",xI(e),II(i),a))throw new Error("Display did not prove possession of its private key");const c=await this.identity.issueClient(i,e.deviceName);return r.add(e,c),c}}const Fl="127.0.0.1",CI="0.0.0.0",NI=16*1024;function Rm(t,e,r){return new Promise((n,o)=>{t.once("error",o),t.listen(e,r,()=>{t.off("error",o);const s=t.address();if(!s||typeof s=="string")return o(new Error("Display listener has no TCP address"));n(s.port)})})}function Qc(t){return new Promise(e=>{t.close(()=>e()),t.closeAllConnections?.()})}function qt(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),t.end(`${JSON.stringify(r)}
134
- `)}async function TI(t){let e=0;const r=[];for await(const n of t){const o=Buffer.isBuffer(n)?n:Buffer.from(n);if(e+=o.length,e>NI)throw new Error("request body is too large");r.push(o)}return JSON.parse(Buffer.concat(r).toString("utf8"))}function $I(t){if(!t||typeof t!="object")throw new Error("pairing request must be an object");const e=t;for(const r of["coreId","grantId","secret","deviceId","deviceName","publicKey","signature"])if(typeof e[r]!="string"||e[r].length===0)throw new Error(`pairing request has no ${r}`);if(typeof e.protocol!="number")throw new Error("pairing request has no protocol version");if(e.deviceId.length>128||e.deviceName.length>128)throw new Error("Display identity is too long");return e}function BI(t){const e=t.socket;return e.authorized?e.getPeerCertificate().fingerprint256?.replaceAll(":","").toLowerCase()??null:null}async function RI(t){const e=await fetch(`${t}/api/landscape?window=live`,{headers:{"x-057-client":"display-delivery"},signal:AbortSignal.timeout(6e4)});if(!e.ok)throw new Error(`private Core returned ${e.status}`);const r=await e.json();if(r.contract!==Oi||r.version!==us||!r.landscape)throw new Error("private Core returned an incompatible landscape envelope");const n={contract:Oi,version:us,landscape:r.landscape};return{wire:JSON.stringify(n),envelope:n}}function MI(t,e,r){AI(t,async()=>{const n=await RI(e),o=fo("sha256").update(n.wire).digest("base64url").slice(0,16);return{wire:n.wire,id:o}},n=>r.warn(`[057] Display landscape delivery failed: ${String(n)}`))}function _I(t,e){const r=t.socket.remoteAddress;return(r===Fl||r==="::1"||r==="::ffff:127.0.0.1")&&t.headers.authorization===`Bearer ${e}`}async function jI(t){const e=await vI(t.storePath),r=new EI(hb(t.storePath)),n=new OI(e),o=Pb({key:e.serverPrivateKey,cert:`${e.serverCertificate.trimEnd()}
135
- ${e.caCertificate.trimStart()}`,ca:e.caCertificate,minVersion:"TLSv1.3",maxVersion:"TLSv1.3",requestCert:!0,rejectUnauthorized:!1},(d,l)=>{(async()=>{const m=new URL(d.url??"/","https://057-display.local");if(d.method==="POST"&&m.pathname==="/v1/pair"){try{const p=$I(await TI(d)),h=await n.redeem(p,r);qt(l,201,{protocol:da,coreId:e.coreId,caPin:e.caPin,caCertificate:Buffer.from(new Jo(e.caCertificate).raw).toString("base64"),clientCertificate:h.certificateDer,expiresAt:h.expiresAt})}catch(p){t.log.warn(`[057] Display pairing refused: ${String(p)}`),qt(l,403,{error:p instanceof Error?p.message:String(p)})}return}if(d.method==="GET"&&m.pathname==="/v1/landscape"){const p=BI(d);if(!p||!r.trusts(p)){qt(l,401,{error:"trusted Display certificate required"});return}MI(l,t.loopbackUrl,t.log);return}qt(l,404,{error:"not found"})})().catch(m=>{t.log.error(`[057] Display request failed: ${String(m)}`),l.headersSent?l.end():qt(l,500,{error:"Display request failed"})})});o.requestTimeout=15e3,o.headersTimeout=15e3;const s=await Rm(o,t.port??0,CI),i=Yn(32).toString("base64url"),a=Lm((d,l)=>{(async()=>{if(!_I(d,i)){qt(l,403,{error:"local Display control token required"});return}const m=new URL(d.url??"/","http://localhost");if(d.method==="POST"&&m.pathname==="/v1/grants"){qt(l,201,n.create());return}if(d.method==="GET"&&m.pathname==="/v1/displays"){qt(l,200,{displays:r.list()});return}if(d.method==="DELETE"&&m.pathname.startsWith("/v1/displays/")){const p=decodeURIComponent(m.pathname.slice(13));qt(l,r.revoke(p)?200:404,{revoked:p});return}qt(l,404,{error:"not found"})})()}),c=await Rm(a,0,Fl).catch(async d=>{throw await Qc(o),d}),u={protocol:da,landscape:us,coreId:e.coreId,caPin:e.caPin,port:s,controlUrl:`http://${Fl}:${c}`,controlToken:i};return t.log.info(`[057] Display delivery ${e.coreId} listening securely on port ${s}`),{info:u,async close(){await Promise.all([Qc(a),Qc(o)])}}}const cf=5057,pr="127.0.0.1",DI=["localhost","127.0.0.1","[::1]","::1"],LI=10,PI={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".woff2":"font/woff2",".png":"image/png",".ico":"image/vnd.microsoft.icon"};function Mm(t,e,r){let n;try{n=decodeURIComponent(e)}catch{return!1}if(n.includes("\0"))return!1;const o=$s(t,`.${Ob(n)}`);if(o!==t&&!o.startsWith(t+ru)||!ge(o)||!fa(o).isFile())return!1;const s=PI[Cb(o).toLowerCase()]??"application/octet-stream";return r.statusCode=200,r.setHeader("content-type",s),r.setHeader("x-content-type-options","nosniff"),yd(r),r.setHeader("cache-control",e.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),jm(o).pipe(r),!0}function UI(t,e,r,n){return new Promise((o,s)=>{let i=n,a=e;const c=u=>{if(u.code==="EADDRINUSE"&&i>1){i--,a++,t.listen(a,r);return}t.off("error",c),s(u)};t.on("error",c),t.once("listening",()=>{t.off("error",c);const u=t.address();o(typeof u=="object"&&u?u.port:a)}),t.listen(a,r)})}function VI(t,e){const r=String(t.headers["sec-fetch-dest"]??"");if(HI.has(r))return`refusing to be embedded as ${r}`;const n=t.headers["sec-fetch-site"];return typeof n=="string"&&n!==""&&n!=="same-origin"&&n!=="none"?`refusing a ${n} request for ${e}`:null}const HI=new Set(["iframe","frame","embed","object","fencedframe"]);async function yb(t){const e=t.log??ig,r=$s(t.root),n=t.host??pr,o=n===pr||n==="::1"||n==="localhost",s=t.runtime?.path??t.storePath??ga();if(!t.runtime){const v=await WS(s);if(v)throw new md(v)}const i=t.runtime??ag({path:t.storePath,log:e,retention:t.retention,observe:t.observe}),a=import.meta.url.endsWith(".mjs")?VS(import.meta.url,{path:i.path,retention:i.retention,machineId:i.machine.id}):void 0,c=import.meta.url.endsWith(".mjs")?kp(import.meta.url,{path:i.path,machineId:i.machine.id}):void 0,u=import.meta.url.endsWith(".mjs")?kp(import.meta.url,{path:i.path,machineId:i.machine.id}):void 0,d=fk({runtime:i,log:e,version:t.version,activity:a,landscape:c,analytics:u,allowedHosts:o?DI:null}),l=Lm((v,g)=>{(async()=>{try{if(await d(v,g))return;if(v.method!=="GET"&&v.method!=="HEAD"){g.statusCode=405,g.setHeader("allow","GET, HEAD"),g.end();return}const I=new URL(v.url??"/","http://localhost").pathname,N=VI(v,I);if(N){e.warn(`[057] ${N}`),g.statusCode=403,g.setHeader("content-type","text/plain; charset=utf-8"),yd(g),g.end(`${N}
136
- `);return}if(Mm(r,I==="/"?"/index.html":I,g)||!I.startsWith("/assets/")&&Mm(r,"/index.html",g))return;g.statusCode=404,g.setHeader("content-type","text/plain; charset=utf-8"),g.end(`not found
137
- `)}catch(I){e.error(`[057] request failed: ${String(I)}`),g.headersSent||(g.statusCode=500),g.end()}})()}),m=await UI(l,t.port??cf,n,LI).catch(v=>{throw i.stop(),v}),p=o?"localhost":n;let h;if(t.display)try{h=await jI({storePath:i.path,loopbackUrl:`http://${pr}:${m}`,log:e})}catch(v){e.error(`[057] authenticated Display delivery could not start: ${String(v)}`)}return KS(i.path,{pid:process.pid,url:`http://${o?pr:n}:${m}`,version:t.version??"dev",contract:pd,store:i.path,startedAt:Date.now(),owner:t.owner??"cli",...h?{display:h.info}:{}}),{url:`http://${p}:${m}`,port:m,host:n,runtime:i,server:l,display:h?.info,close(){GS(i.path),a?.close(),c?.close(),u?.close();const v=new Promise(g=>l.close(()=>g()));return l.closeAllConnections?.(),Promise.all([v,h?.close()]).then(()=>i.stop())}}}function FI(t){return $s(Nb(new URL(".",t)),"..","dist")}function WI(t,e){switch(e.operation){case"summary":return{operation:"summary",result:t.summary(e.period)};case"availability":return{operation:"availability",result:t.availability(e.period)};case"compare":return{operation:"compare",result:t.compare(e.periodA,e.periodB)};case"breakdown":return{operation:"breakdown",result:t.breakdown(e.period,e.dimension)}}}const Ts="1.3.0";function KI(t){const e={command:"serve",activityOperation:"summary",activityPrevious:!1,activityAscii:!1,open:!1,yes:!1,desktop:!1},r=[...t],n=r[0];if(n&&!n.startsWith("-"))if(n==="status"||n==="compact"||n==="reset")e.command=n,r.shift();else if(n==="activity"){e.command="activity",r.shift();const o=r[0];if(o&&!o.startsWith("-")){const s=t1(o);if(s)e.activityOperation=s.operation,e.activityDimension=s.dimension,e.activityItemFilter=s.itemFilter;else if(o==="today")e.activityOperation="summary";else if(xA.includes(o))e.activityOperation=o;else return{...e,command:"help",error:`unknown activity operation: ${o}`};r.shift()}}else return{...e,command:"help",error:`unknown command: ${n}`};for(;r.length;){const o=r.shift(),[s,i]=o.includes("=")?GI(o,"="):[o,void 0],a=()=>i??r.shift();switch(s){case"-h":case"--help":e.command="help";break;case"-v":case"--version":e.command="version";break;case"--open":e.open=!0;break;case"--yes":case"-y":e.yes=!0;break;case"--desktop":e.desktop=!0;break;case"--last":{const c=a(),u=c?.match(/^(\d+)d$/),d=u?Number(u[1]):NaN;if(!Number.isInteger(d)||d<1)return{...e,command:"help",error:`--last needs a positive duration such as 7d, got ${c}`};e.activityLastDays=d;break}case"--previous":e.activityPrevious=!0;break;case"--by":{const c=a(),u=["model","executor","lifecycle","outcome","session","duration-band"];if(!c||!u.includes(c))return{...e,command:"help",error:`--by needs one of: ${u.join(", ")}`};e.activityDimension=c;break}case"--width":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<1)return{...e,command:"help",error:`--width needs a positive number of columns, got ${c}`};e.activityWidth=u;break}case"--color":{const c=a();if(c!=="always"&&c!=="never"&&c!=="auto")return{...e,command:"help",error:`--color needs always, never or auto, got ${c}`};e.activityColor=c;break}case"--ascii":e.activityAscii=!0;break;case"--port":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<0||u>65535)return{...e,command:"help",error:`--port needs a port number, got ${c}`};e.port=u;break}case"--host":{const c=a();if(!c)return{...e,command:"help",error:"--host needs a value"};e.host=c;break}case"--store":{const c=a();if(!c)return{...e,command:"help",error:"--store needs a path"};e.store=c;break}default:return{...e,command:"help",error:`unknown option: ${s}`}}}return e}function GI(t,e){const r=t.indexOf(e);return[t.slice(0,r),t.slice(r+1)]}const qI=`057 — a spatial interface for observing the shape of a computational workday
388
+ `)},r1);t.once("close",i),a()}const Aa=1,s1=12e4;function o1(t,e){const r=`${t}.${process.pid}.tmp`;od(r,e,{mode:384}),id(r,t),Ea(t,384)}class i1{path;state;constructor(e){if(this.path=ue(e,"trusted.json"),this.state=ve(this.path)?JSON.parse(ad(this.path,"utf8")):{version:1,displays:[]},this.state.version!==1)throw new Error(`unsupported 057 Display trust version ${String(this.state.version)}`)}list(){return this.state.displays.map(e=>({...e}))}trusts(e){const r=e.replaceAll(":","").toLowerCase();return this.state.displays.some(n=>n.fingerprint===r&&n.revokedAt===void 0&&n.expiresAt>Date.now())}add(e,r){const n=this.state.displays.find(s=>s.deviceId===e.deviceId&&s.revokedAt===void 0);n&&(n.revokedAt=Date.now()),this.state.displays.push({deviceId:e.deviceId,name:e.deviceName.slice(0,80)||"iPhone",fingerprint:r.fingerprint,serial:r.serial,pairedAt:Date.now(),expiresAt:r.expiresAt}),this.save()}revoke(e){const r=this.state.displays.find(n=>n.deviceId===e&&n.revokedAt===void 0);return r?(r.revokedAt=Date.now(),this.save(),!0):!1}save(){o1(this.path,`${JSON.stringify(this.state,null,1)}
389
+ `)}}function a1(t){return Buffer.concat([Buffer.from("057.display.pair.v1\0","utf8"),Buffer.from(t.grantId,"utf8"),Buffer.from([0]),Buffer.from(t.coreId,"utf8"),Buffer.from([0]),Buffer.from(t.deviceId,"utf8"),Buffer.from([0]),Buffer.from(t.publicKey,"base64")])}function c1(t){if(t.length!==65||t[0]!==4)throw new Error("the Display public key is not an uncompressed P-256 point");return Zb({key:{kty:"EC",crv:"P-256",x:t.subarray(1,33).toString("base64url"),y:t.subarray(33,65).toString("base64url")},format:"jwk"})}class u1{constructor(e){this.identity=e}identity;grants=new Map;create(e=Date.now()){this.grants.clear();const r={id:pn(18).toString("base64url"),secret:pn(32),expiresAt:e+s1};this.grants.set(r.id,r);const n={p:Aa,id:this.identity.coreId,pin:this.identity.caPin,sp:this.identity.serverPin,grant:r.id,secret:Buffer.from(r.secret).toString("base64url"),expires:r.expiresAt};return{payload:n,uri:`o57-display://pair#${Buffer.from(JSON.stringify(n)).toString("base64url")}`}}async redeem(e,r,n=Date.now()){if(e.protocol!==Aa)throw new Error("unsupported pairing protocol");if(e.coreId!==this.identity.coreId)throw new Error("pairing grant belongs to another Core");const s=this.grants.get(e.grantId);if(!s||s.expiresAt<=n)throw this.grants.delete(e.grantId),new Error("pairing grant is missing or expired");const o=Buffer.from(e.secret,"base64url");if(o.length!==s.secret.length||!Xb(o,s.secret))throw new Error("pairing grant is invalid");this.grants.delete(e.grantId);const i=Buffer.from(e.publicKey,"base64"),a=Buffer.from(e.signature,"base64");if(!Jb("sha256",a1(e),c1(i),a))throw new Error("Display did not prove possession of its private key");const c=await this.identity.issueClient(i,e.deviceName);return r.add(e,c),c}}const sd="127.0.0.1",l1="0.0.0.0",d1=16*1024;function Xm(t,e,r){return new Promise((n,s)=>{t.once("error",s),t.listen(e,r,()=>{t.off("error",s);const o=t.address();if(!o||typeof o=="string")return s(new Error("Display listener has no TCP address"));n(o.port)})})}function fu(t){return new Promise(e=>{t.close(()=>e()),t.closeAllConnections?.()})}function Jt(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json; charset=utf-8"),t.setHeader("cache-control","no-store"),t.setHeader("x-content-type-options","nosniff"),t.end(`${JSON.stringify(r)}
390
+ `)}async function f1(t){let e=0;const r=[];for await(const n of t){const s=Buffer.isBuffer(n)?n:Buffer.from(n);if(e+=s.length,e>d1)throw new Error("request body is too large");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}function p1(t){if(!t||typeof t!="object")throw new Error("pairing request must be an object");const e=t;for(const r of["coreId","grantId","secret","deviceId","deviceName","publicKey","signature"])if(typeof e[r]!="string"||e[r].length===0)throw new Error(`pairing request has no ${r}`);if(typeof e.protocol!="number")throw new Error("pairing request has no protocol version");if(e.deviceId.length>128||e.deviceName.length>128)throw new Error("Display identity is too long");return e}function h1(t){const e=t.socket;return e.authorized?e.getPeerCertificate().fingerprint256?.replaceAll(":","").toLowerCase()??null:null}async function m1(t){const e=await fetch(`${t}/api/landscape?window=live`,{headers:{"x-057-client":"display-delivery"},signal:AbortSignal.timeout(6e4)});if(!e.ok)throw new Error(`private Core returned ${e.status}`);const r=await e.json();if(r.contract!==Di||r.version!==go||!r.landscape)throw new Error("private Core returned an incompatible landscape envelope");const n={contract:Di,version:go,landscape:r.landscape};return{wire:JSON.stringify(n),envelope:n}}function y1(t,e,r){n1(t,async()=>{const n=await m1(e),s=vs("sha256").update(n.wire).digest("base64url").slice(0,16);return{wire:n.wire,id:s}},n=>r.warn(`[057] Display landscape delivery failed: ${String(n)}`))}function g1(t,e){const r=t.socket.remoteAddress;return(r===sd||r==="::1"||r==="::ffff:127.0.0.1")&&t.headers.authorization===`Bearer ${e}`}async function v1(t){const e=await e1(t.storePath),r=new i1($b(t.storePath)),n=new u1(e),s=nw({key:e.serverPrivateKey,cert:`${e.serverCertificate.trimEnd()}
391
+ ${e.caCertificate.trimStart()}`,ca:e.caCertificate,minVersion:"TLSv1.3",maxVersion:"TLSv1.3",requestCert:!0,rejectUnauthorized:!1},(l,d)=>{(async()=>{const m=new URL(l.url??"/","https://057-display.local");if(l.method==="POST"&&m.pathname==="/v1/pair"){try{const p=p1(await f1(l)),h=await n.redeem(p,r);Jt(d,201,{protocol:Aa,coreId:e.coreId,caPin:e.caPin,caCertificate:Buffer.from(new so(e.caCertificate).raw).toString("base64"),clientCertificate:h.certificateDer,expiresAt:h.expiresAt})}catch(p){t.log.warn(`[057] Display pairing refused: ${String(p)}`),Jt(d,403,{error:p instanceof Error?p.message:String(p)})}return}if(l.method==="GET"&&m.pathname==="/v1/landscape"){const p=h1(l);if(!p||!r.trusts(p)){Jt(d,401,{error:"trusted Display certificate required"});return}y1(d,t.loopbackUrl,t.log);return}Jt(d,404,{error:"not found"})})().catch(m=>{t.log.error(`[057] Display request failed: ${String(m)}`),d.headersSent?d.end():Jt(d,500,{error:"Display request failed"})})});s.requestTimeout=15e3,s.headersTimeout=15e3;const o=await Xm(s,t.port??0,l1),i=pn(32).toString("base64url"),a=ty((l,d)=>{(async()=>{if(!g1(l,i)){Jt(d,403,{error:"local Display control token required"});return}const m=new URL(l.url??"/","http://localhost");if(l.method==="POST"&&m.pathname==="/v1/grants"){Jt(d,201,n.create());return}if(l.method==="GET"&&m.pathname==="/v1/displays"){Jt(d,200,{displays:r.list()});return}if(l.method==="DELETE"&&m.pathname.startsWith("/v1/displays/")){const p=decodeURIComponent(m.pathname.slice(13));Jt(d,r.revoke(p)?200:404,{revoked:p});return}Jt(d,404,{error:"not found"})})()}),c=await Xm(a,0,sd).catch(async l=>{throw await fu(s),l}),u={protocol:Aa,landscape:go,coreId:e.coreId,caPin:e.caPin,port:o,controlUrl:`http://${sd}:${c}`,controlToken:i};return t.log.info(`[057] Display delivery ${e.coreId} listening securely on port ${o}`),{info:u,async close(){await Promise.all([fu(a),fu(s)])}}}const kf=5057,vr="127.0.0.1",b1=["localhost","127.0.0.1","[::1]","::1"],w1=10,S1={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".woff2":"font/woff2",".png":"image/png",".ico":"image/vnd.microsoft.icon"};function Jm(t,e,r){let n;try{n=decodeURIComponent(e)}catch{return!1}if(n.includes("\0"))return!1;const s=Lo(t,`.${Wb(n)}`);if(s!==t&&!s.startsWith(t+mu)||!ve(s)||!ka(s).isFile())return!1;const o=S1[Kb(s).toLowerCase()]??"application/octet-stream";return r.statusCode=200,r.setHeader("content-type",o),r.setHeader("x-content-type-options","nosniff"),$d(r),r.setHeader("cache-control",e.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),Qm(s).pipe(r),!0}function A1(t,e,r,n){return new Promise((s,o)=>{let i=n,a=e;const c=u=>{if(u.code==="EADDRINUSE"&&i>1){i--,a++,t.listen(a,r);return}t.off("error",c),o(u)};t.on("error",c),t.once("listening",()=>{t.off("error",c);const u=t.address();s(typeof u=="object"&&u?u.port:a)}),t.listen(a,r)})}function k1(t,e){const r=String(t.headers["sec-fetch-dest"]??"");if(E1.has(r))return`refusing to be embedded as ${r}`;const n=t.headers["sec-fetch-site"];return typeof n=="string"&&n!==""&&n!=="same-origin"&&n!=="none"?`refusing a ${n} request for ${e}`:null}const E1=new Set(["iframe","frame","embed","object","fencedframe"]);async function _b(t){const e=t.log??kg,r=Lo(t.root),n=t.host??vr,s=n===vr||n==="::1"||n==="localhost",o=t.runtime?.path??t.storePath??Na();if(!t.runtime){const g=await uk(o);if(g)throw new Td(g)}const i=t.runtime??Eg({path:t.storePath,log:e,retention:t.retention,observe:t.observe,machinePulse:t.machinePulse}),a=import.meta.url.endsWith(".mjs")?ik(import.meta.url,{path:i.path,retention:i.retention,machineId:i.machine.id}):void 0,c=import.meta.url.endsWith(".mjs")?Up(import.meta.url,{path:i.path,machineId:i.machine.id}):void 0,u=import.meta.url.endsWith(".mjs")?Up(import.meta.url,{path:i.path,machineId:i.machine.id}):void 0,l=zk({runtime:i,log:e,version:t.version,activity:a,landscape:c,analytics:u,allowedHosts:s?b1:null}),d=ty((g,v)=>{(async()=>{try{if(await l(g,v))return;if(g.method!=="GET"&&g.method!=="HEAD"){v.statusCode=405,v.setHeader("allow","GET, HEAD"),v.end();return}const b=new URL(g.url??"/","http://localhost").pathname,_=k1(g,b);if(_){e.warn(`[057] ${_}`),v.statusCode=403,v.setHeader("content-type","text/plain; charset=utf-8"),$d(v),v.end(`${_}
392
+ `);return}if(Jm(r,b==="/"?"/index.html":b,v)||!b.startsWith("/assets/")&&Jm(r,"/index.html",v))return;v.statusCode=404,v.setHeader("content-type","text/plain; charset=utf-8"),v.end(`not found
393
+ `)}catch(b){e.error(`[057] request failed: ${String(b)}`),v.headersSent||(v.statusCode=500),v.end()}})()}),m=await A1(d,t.port??kf,n,w1).catch(g=>{throw i.stop(),g}),p=s?"localhost":n;let h;if(t.display)try{h=await v1({storePath:i.path,loopbackUrl:`http://${vr}:${m}`,log:e})}catch(g){e.error(`[057] authenticated Display delivery could not start: ${String(g)}`)}return lk(i.path,{pid:process.pid,url:`http://${s?vr:n}:${m}`,version:t.version??"dev",contract:Od,store:i.path,startedAt:Date.now(),owner:t.owner??"cli",...h?{display:h.info}:{}}),{url:`http://${p}:${m}`,port:m,host:n,runtime:i,server:d,display:h?.info,close(){dk(i.path),a?.close(),c?.close(),u?.close();const g=new Promise(v=>d.close(()=>v()));return d.closeAllConnections?.(),Promise.all([g,h?.close()]).then(()=>i.stop())}}}function x1(t){return Lo(Gb(new URL(".",t)),"..","dist")}function I1(t,e){switch(e.operation){case"summary":return{operation:"summary",result:t.summary(e.period)};case"availability":return{operation:"availability",result:t.availability(e.period)};case"compare":return{operation:"compare",result:t.compare(e.periodA,e.periodB)};case"breakdown":return{operation:"breakdown",result:t.breakdown(e.period,e.dimension)}}}const Po="1.4.0";function C1(t){const e={command:"serve",activityOperation:"summary",activityPrevious:!1,activityAscii:!1,open:!1,yes:!1,desktop:!1},r=[...t],n=r[0];if(n&&!n.startsWith("-"))if(n==="status"||n==="compact"||n==="reset")e.command=n,r.shift();else if(n==="activity"){e.command="activity",r.shift();const s=r[0];if(s&&!s.startsWith("-")){const o=D1(s);if(o)e.activityOperation=o.operation,e.activityDimension=o.dimension,e.activityItemFilter=o.itemFilter;else if(s==="today")e.activityOperation="summary";else if(WS.includes(s))e.activityOperation=s;else return{...e,command:"help",error:`unknown activity operation: ${s}`};r.shift()}}else return{...e,command:"help",error:`unknown command: ${n}`};for(;r.length;){const s=r.shift(),[o,i]=s.includes("=")?O1(s,"="):[s,void 0],a=()=>i??r.shift();switch(o){case"-h":case"--help":e.command="help";break;case"-v":case"--version":e.command="version";break;case"--open":e.open=!0;break;case"--yes":case"-y":e.yes=!0;break;case"--desktop":e.desktop=!0;break;case"--last":{const c=a(),u=c?.match(/^(\d+)d$/),l=u?Number(u[1]):NaN;if(!Number.isInteger(l)||l<1)return{...e,command:"help",error:`--last needs a positive duration such as 7d, got ${c}`};e.activityLastDays=l;break}case"--previous":e.activityPrevious=!0;break;case"--by":{const c=a(),u=["model","executor","lifecycle","outcome","session","duration-band"];if(!c||!u.includes(c))return{...e,command:"help",error:`--by needs one of: ${u.join(", ")}`};e.activityDimension=c;break}case"--width":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<1)return{...e,command:"help",error:`--width needs a positive number of columns, got ${c}`};e.activityWidth=u;break}case"--color":{const c=a();if(c!=="always"&&c!=="never"&&c!=="auto")return{...e,command:"help",error:`--color needs always, never or auto, got ${c}`};e.activityColor=c;break}case"--ascii":e.activityAscii=!0;break;case"--port":{const c=a(),u=Number(c);if(!Number.isInteger(u)||u<0||u>65535)return{...e,command:"help",error:`--port needs a port number, got ${c}`};e.port=u;break}case"--host":{const c=a();if(!c)return{...e,command:"help",error:"--host needs a value"};e.host=c;break}case"--store":{const c=a();if(!c)return{...e,command:"help",error:"--store needs a path"};e.store=c;break}default:return{...e,command:"help",error:`unknown option: ${o}`}}}return e}function O1(t,e){const r=t.indexOf(e);return[t.slice(0,r),t.slice(r+1)]}const N1=`057 — a spatial interface for observing the shape of a computational workday
138
394
 
139
395
  057 observe this machine and serve the interface
140
396
  057 status where the store is, what it holds, what is observed
@@ -150,8 +406,8 @@ ${e.caCertificate.trimStart()}`,ca:e.caCertificate,minVersion:"TLSv1.3",maxVersi
150
406
  057 reset delete the local store
151
407
 
152
408
  Options
153
- --port <n> port to serve on (default ${cf}; the next free one if taken)
154
- --host <addr> address to bind (default ${pr}; read the warning below first)
409
+ --port <n> port to serve on (default ${kf}; the next free one if taken)
410
+ --host <addr> address to bind (default ${vr}; read the warning below first)
155
411
  --store <path> store file to use (same as O57_STORE)
156
412
  --open open the interface in the default browser — the running
157
413
  057's, if one (or 057.app) already observes the store
@@ -167,6 +423,8 @@ Environment
167
423
  NO_COLOR, FORCE_COLOR colour for 057 activity (on for a terminal unless NO_COLOR is set)
168
424
  O57_RETAIN_PROCESS_DAYS days of OS process observations to keep (default 7, 0 = forever)
169
425
  O57_RETAIN_DAYS days of session/execution history to keep (default 90, 0 = forever)
426
+ O57_MACHINE_PULSE_SSH experimental read-only Linux observer, as user@host
427
+ O57_MACHINE_PULSE_INTERVAL_MS snapshot interval (default 2000, minimum 250)
170
428
  WORK_ROOTS colon-separated workspace roots to look for 0x2F task state in
171
429
  DSH_HOME CLAUDE_HOME CODEX_HOME GEMINI_HOME CURSOR_GLOBAL_STORAGE
172
430
  override where each source is read from
@@ -177,41 +435,41 @@ to that trusted device on your local network. Reset deletes the SQLite store and
177
435
 
178
436
  --host binds beyond the loopback interface and serves your telemetry, unauthenticated, to
179
437
  anything that can reach that address. Do not do it on a network you do not control.
180
- `;function Nr(t){return process.stdout.isTTY?`\x1B[2m${t}\x1B[0m`:t}function as(t){return t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:t<1024**3?`${(t/1024**2).toFixed(1)} MB`:`${(t/1024**3).toFixed(2)} GB`}function zI(t,e,r,n){const o=["",` 057 ${Ts}`,` ${t}`,"",Nr(" observing this machine only — its process table, and any AI runtime state it finds"),Nr(` storing ${e}`),Nr(` keeping ${r}`),Nr(" sending local only to a paired Display; no account, no cloud, no analytics."),Nr(" resetting 057 reset")];return n!==pr&&o.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),o.push(""),o.join(`
181
- `)}async function YI(t){if(!process.stdin.isTTY)return!1;const e=Ib({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>e.question(`${t} [y/N] `,n))).trim().toLowerCase()==="y"}finally{e.close()}}async function XI(t,e){const r=KI(t);if(r.command==="version")return console.log(Ts),0;if(r.command==="help")return r.error&&console.error(`057: ${r.error}
182
- `),(r.error?console.error:console.log)(qI),r.error?2:0;r.store&&(process.env.O57_STORE=r.store);const n=ga(),o=Uy();if(r.command==="status")return n1(n,o);if(r.command==="activity")return JI(n,o,r);if(r.command==="compact")return o1(n);if(r.command==="reset")return s1(n,r.yes);if(r.desktop)return r1(e,n,o,r.port??0);const s=r.port??i1(process.env.O57_PORT)??cf,i=r.host??process.env.O57_HOST??pr;let a;try{a=await yb({root:e,port:s,host:i,storePath:n,retention:o,log:uf(),version:Ts,display:!0})}catch(d){if(d instanceof md){const l=d.record;return r.open?(console.log(`
183
- ${d.message}${l.owner==="desktop"?" — 057.app":""}.
184
- Opening ${l.url}
185
- `),await _m(l.url),0):(console.error(`
438
+ `;function Mr(t){return process.stdout.isTTY?`\x1B[2m${t}\x1B[0m`:t}function mo(t){return t<1024?`${t} B`:t<1024**2?`${(t/1024).toFixed(1)} KB`:t<1024**3?`${(t/1024**2).toFixed(1)} MB`:`${(t/1024**3).toFixed(2)} GB`}function T1(t,e,r,n){const s=["",` 057 ${Po}`,` ${t}`,"",Mr(" observing this machine only — its process table, and any AI runtime state it finds"),Mr(` storing ${e}`),Mr(` keeping ${r}`),Mr(" sending local only to a paired Display; no account, no cloud, no analytics."),Mr(" resetting 057 reset")];return n!==vr&&s.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),s.push(""),s.join(`
439
+ `)}async function $1(t){if(!process.stdin.isTTY)return!1;const e=Fb({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>e.question(`${t} [y/N] `,n))).trim().toLowerCase()==="y"}finally{e.close()}}async function B1(t,e){const r=C1(t);if(r.command==="version")return console.log(Po),0;if(r.command==="help")return r.error&&console.error(`057: ${r.error}
440
+ `),(r.error?console.error:console.log)(N1),r.error?2:0;r.store&&(process.env.O57_STORE=r.store);const n=Na(),s=ng(),o=Bk();if(r.command==="status")return L1(n,s);if(r.command==="activity")return _1(n,s,r);if(r.command==="compact")return U1(n);if(r.command==="reset")return H1(n,r.yes);if(r.desktop)return P1(e,n,s,r.port??0,o);const i=r.port??V1(process.env.O57_PORT)??kf,a=r.host??process.env.O57_HOST??vr;let c;try{c=await _b({root:e,port:i,host:a,storePath:n,retention:s,machinePulse:o,log:Ef(),version:Po,display:!0})}catch(d){if(d instanceof Td){const m=d.record;return r.open?(console.log(`
441
+ ${d.message}${m.owner==="desktop"?" — 057.app":""}.
442
+ Opening ${m.url}
443
+ `),await Zm(m.url),0):(console.error(`
186
444
  ${d.message}.
187
- Open ${l.url} (\`057 --open\`), or stop that 057 before starting another.
188
- `),1)}return vc(d)}console.log(zI(a.url,n,ba(o),i)),r.open&&await _m(a.url);let c=!1;const u=()=>{c||(c=!0,console.log(`
445
+ Open ${m.url} (\`057 --open\`), or stop that 057 before starting another.
446
+ `),1)}return Tc(d)}console.log(T1(c.url,n,$a(s),a)),r.open&&await Zm(c.url);let u=!1;const l=()=>{u||(u=!0,console.log(`
189
447
  057 stopping — history is on disk
190
- `),a.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}function JI(t,e,r){let n;try{n=wa(t)}catch(o){return vc(o)}try{const o=Date.now(),s=QI(o,r.activityLastDays),i=ng(n,e,Vr().id,o);if(r.activityOperation==="compare"&&!r.activityPrevious)return console.error(`057: activity compare currently requires --previous
191
- `),2;let a;if(r.activityOperation==="compare")a={operation:"compare",periodA:s,periodB:e1(s)};else if(r.activityOperation==="breakdown"){if(!r.activityDimension)return console.error(`057: activity breakdown requires --by <dimension>
192
- `),2;a={operation:"breakdown",period:s,dimension:r.activityDimension}}else r.activityOperation==="availability"?a={operation:"availability",period:s}:a={operation:"summary",period:s};return process.stdout.write(tr(WI(i,a),r.activityItemFilter,ZI(r,process.stdout,process.env))),0}finally{n.close()}}function ZI(t,e,r){const n=e.isTTY===!0,o=t.activityWidth??(n&&e.columns?e.columns:80),s=r.FORCE_COLOR!==void 0&&r.FORCE_COLOR!=="0"&&r.FORCE_COLOR!=="false",i=t.activityColor??(s?"always":"auto"),a=i==="always"||i==="auto"&&n&&!r.NO_COLOR&&r.TERM!=="dumb",c=r.LC_ALL||r.LC_CTYPE||r.LANG,u=!c||/utf-?8/i.test(c);return{width:o,color:a,ascii:t.activityAscii||!u}}function QI(t,e){if(e!==void 0)return{from:t-e*864e5,to:t};const r=new Date(t);return r.setHours(0,0,0,0),{from:r.getTime(),to:t}}function e1(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function t1(t){switch(t){case"running":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"running"};case"waiting":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"waiting"};case"failed":return{operation:"breakdown",dimension:"outcome",itemFilter:"failed"};case"sessions":return{operation:"breakdown",dimension:"session"};case"usage":case"concurrency":return{operation:"summary"};default:return}}async function r1(t,e,r,n){const o=c=>{process.stdout.write(`${JSON.stringify(c)}
193
- `)};let s;try{s=await yb({root:t,port:n,host:pr,storePath:e,retention:r,log:uf(),version:Ts,owner:"desktop",display:!0})}catch(c){if(c instanceof md){const u=c.record;return o({event:"running",url:u.url,pid:u.pid,version:u.version,owner:u.owner,contract:u.contract}),0}return c instanceof xt?(o({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(o({event:"error",kind:"start",message:c instanceof Error?c.message:String(c)}),1)}let i=!1;const a=c=>{i||(i=!0,process.stderr.write(`[057] stopping (${c}) — history is on disk
194
- `),s.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>a("SIGINT")),process.on("SIGTERM",()=>a("SIGTERM")),process.stdin.on("end",()=>a("app closed its pipe")),process.stdin.on("close",()=>a("app closed its pipe")),process.stdin.resume(),o({event:"ready",url:`http://${pr}:${s.port}`,pid:process.pid,version:Ts,store:e,contract:pd,display:s.display}),new Promise(()=>{})}function n1(t,e){let r=null;if(t!==":memory:"&&ge(t))try{r=wa(t)}catch(n){return vc(n)}try{const n=r?.stats()??{events:0,claims:0,bySource:[],earliest:null,latest:null},o=r?.sizeBytes()??{db:0,wal:0,shm:0,total:0},s=va(t).map(a=>dd(a)).filter(a=>a!==null).map(a=>"0"+a.toString(8)).join(" ");if(console.log(`
195
- store ${t}${Dy()?" (from O57_STORE)":""}
448
+ `),c.close().then(()=>process.exit(0)))};return process.on("SIGINT",l),process.on("SIGTERM",l),new Promise(()=>{})}function _1(t,e,r){let n;try{n=Ba(t)}catch(s){return Tc(s)}try{const s=Date.now(),o=R1(s,r.activityLastDays),i=wg(n,e,Gr().id,s);if(r.activityOperation==="compare"&&!r.activityPrevious)return console.error(`057: activity compare currently requires --previous
449
+ `),2;let a;if(r.activityOperation==="compare")a={operation:"compare",periodA:o,periodB:j1(o)};else if(r.activityOperation==="breakdown"){if(!r.activityDimension)return console.error(`057: activity breakdown requires --by <dimension>
450
+ `),2;a={operation:"breakdown",period:o,dimension:r.activityDimension}}else r.activityOperation==="availability"?a={operation:"availability",period:o}:a={operation:"summary",period:o};return process.stdout.write(sr(I1(i,a),r.activityItemFilter,M1(r,process.stdout,process.env))),0}finally{n.close()}}function M1(t,e,r){const n=e.isTTY===!0,s=t.activityWidth??(n&&e.columns?e.columns:80),o=r.FORCE_COLOR!==void 0&&r.FORCE_COLOR!=="0"&&r.FORCE_COLOR!=="false",i=t.activityColor??(o?"always":"auto"),a=i==="always"||i==="auto"&&n&&!r.NO_COLOR&&r.TERM!=="dumb",c=r.LC_ALL||r.LC_CTYPE||r.LANG,u=!c||/utf-?8/i.test(c);return{width:s,color:a,ascii:t.activityAscii||!u}}function R1(t,e){if(e!==void 0)return{from:t-e*864e5,to:t};const r=new Date(t);return r.setHours(0,0,0,0),{from:r.getTime(),to:t}}function j1(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function D1(t){switch(t){case"running":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"running"};case"waiting":return{operation:"breakdown",dimension:"lifecycle",itemFilter:"waiting"};case"failed":return{operation:"breakdown",dimension:"outcome",itemFilter:"failed"};case"sessions":return{operation:"breakdown",dimension:"session"};case"usage":case"concurrency":return{operation:"summary"};default:return}}async function P1(t,e,r,n,s){const o=u=>{process.stdout.write(`${JSON.stringify(u)}
451
+ `)};let i;try{i=await _b({root:t,port:n,host:vr,storePath:e,retention:r,machinePulse:s,log:Ef(),version:Po,owner:"desktop",display:!0})}catch(u){if(u instanceof Td){const l=u.record;return o({event:"running",url:l.url,pid:l.pid,version:l.version,owner:l.owner,contract:l.contract}),0}return u instanceof Ct?(o({event:"error",kind:"store",message:u.message,remedy:u.remedy}),1):(o({event:"error",kind:"start",message:u instanceof Error?u.message:String(u)}),1)}let a=!1;const c=u=>{a||(a=!0,process.stderr.write(`[057] stopping (${u}) — history is on disk
452
+ `),i.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>c("SIGINT")),process.on("SIGTERM",()=>c("SIGTERM")),process.stdin.on("end",()=>c("app closed its pipe")),process.stdin.on("close",()=>c("app closed its pipe")),process.stdin.resume(),o({event:"ready",url:`http://${vr}:${i.port}`,pid:process.pid,version:Po,store:e,contract:Od,display:i.display}),new Promise(()=>{})}function L1(t,e){let r=null;if(t!==":memory:"&&ve(t))try{r=Ba(t)}catch(n){return Tc(n)}try{const n=r?.stats()??{events:0,claims:0,bySource:[],earliest:null,latest:null},s=r?.sizeBytes()??{db:0,wal:0,shm:0,total:0},o=Ta(t).map(a=>Id(a)).filter(a=>a!==null).map(a=>"0"+a.toString(8)).join(" ");if(console.log(`
453
+ store ${t}${eg()?" (from O57_STORE)":""}
196
454
  schema ${r?r.schemaVersion:"none"}
197
- size ${as(o.total)} ${Nr(`(db ${as(o.db)}, wal ${as(o.wal)})`)}
455
+ size ${mo(s.total)} ${Mr(`(db ${mo(s.db)}, wal ${mo(s.wal)})`)}
198
456
  events ${n.events.toLocaleString()}
199
457
  claims ${n.claims.toLocaleString()}
200
- keeping ${ba(e)}
201
- permissions ${s||"none — no store yet"}
458
+ keeping ${$a(e)}
459
+ permissions ${o||"none — no store yet"}
202
460
  `),n.bySource.length===0)console.log(` nothing has been captured yet
203
- `);else{for(const a of n.bySource){const c=`${new Date(a.first).toISOString().slice(0,10)} → ${new Date(a.last).toISOString().slice(0,10)}`;console.log(` ${a.source.padEnd(20)}${String(a.events).padStart(10)} events ${Nr(c)}`)}console.log("")}const i=Py();return i&&console.log(` a store from a previous layout is at ${i} and is not in use
204
- `),0}finally{r?.close()}}function o1(t){let e;try{e=ag({path:t,observe:!1,log:uf()})}catch(r){return vc(r)}try{const r=e.store.sizeBytes().total,n=e.sweep();e.store.compact();const o=e.store.sizeBytes().total;return console.log(`
461
+ `);else{for(const a of n.bySource){const c=`${new Date(a.first).toISOString().slice(0,10)} → ${new Date(a.last).toISOString().slice(0,10)}`;console.log(` ${a.source.padEnd(20)}${String(a.events).padStart(10)} events ${Mr(c)}`)}console.log("")}const i=rg();return i&&console.log(` a store from a previous layout is at ${i} and is not in use
462
+ `),0}finally{r?.close()}}function U1(t){let e;try{e=Eg({path:t,observe:!1,log:Ef()})}catch(r){return Tc(r)}try{const r=e.store.sizeBytes().total,n=e.sweep();e.store.compact();const s=e.store.sizeBytes().total;return console.log(`
205
463
  removed ${n.processEvents+n.otherEvents} expired events
206
- ${as(r)} → ${as(o)}
207
- `),0}finally{e.stop()}}async function s1(t,e){const r=ZA(t);console.log(`
464
+ ${mo(r)} → ${mo(s)}
465
+ `),0}finally{e.stop()}}async function H1(t,e){const r=gA(t);console.log(`
208
466
  this deletes, permanently:
209
- `);for(const n of r)console.log(` ${n}`);if(console.log(""),!e&&!await YI(" delete the local store?"))return console.log(` nothing was deleted
210
- `),1;for(const n of r)Dm(n,{recursive:!0,force:!0});return console.log(` deleted. the next run starts a new store.
211
- `),0}function uf(){return{info:t=>{process.stderr.write(`${Nr(t)}
467
+ `);for(const n of r)console.log(` ${n}`);if(console.log(""),!e&&!await $1(" delete the local store?"))return console.log(` nothing was deleted
468
+ `),1;for(const n of r)ey(n,{recursive:!0,force:!0});return console.log(` deleted. the next run starts a new store.
469
+ `),0}function Ef(){return{info:t=>{process.stderr.write(`${Mr(t)}
212
470
  `)},warn:t=>{process.stderr.write(`${t}
213
471
  `)},error:t=>{process.stderr.write(`${t}
214
- `)}}}function vc(t){if(t instanceof xt)return console.error(`
472
+ `)}}}function Tc(t){if(t instanceof Ct)return console.error(`
215
473
  057: ${t.message}
216
474
  ${t.remedy}
217
475
  `),1;const e=t?.code;return e==="EADDRINUSE"?(console.error(`
@@ -220,4 +478,4 @@ anything that can reach that address. Do not do it on a network you do not contr
220
478
  057: cannot bind that address or port (${e}).
221
479
  `),1):(console.error(`
222
480
  057: ${t instanceof Error?t.message:String(t)}
223
- `),1)}function i1(t){if(!t)return;const e=Number(t);return Number.isInteger(e)&&e>=0&&e<=65535?e:void 0}async function _m(t){const e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:r}=await import("node:child_process");try{r(e,[t],{stdio:"ignore",detached:!0}).unref()}catch{}}async function TC(t){const e=await XI(t,FI(import.meta.url));e!==0&&process.exit(e)}export{FI as defaultRoot,TC as main,XI as run};
481
+ `),1)}function V1(t){if(!t)return;const e=Number(t);return Number.isInteger(e)&&e>=0&&e<=65535?e:void 0}async function Zm(t){const e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:r}=await import("node:child_process");try{r(e,[t],{stdio:"ignore",detached:!0}).unref()}catch{}}async function fN(t){const e=await B1(t,x1(import.meta.url));e!==0&&process.exit(e)}export{x1 as defaultRoot,fN as main,B1 as run};