@probnaya/057-cli 1.2.3 → 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,14 +1,18 @@
1
- import{existsSync as fe,createReadStream as dm,statSync as Qi,mkdirSync as Dc,chmodSync as ea,writeFileSync as El,renameSync as Il,rmSync as fm,readFileSync as Cl}from"node:fs";import{createInterface as Yv}from"node:readline";import{createServer as pm}from"node:http";import{join as se,isAbsolute as Pc,relative as cc,sep as Lc,dirname as ii,resolve as yo,normalize as Xv,extname as Jv}from"node:path";import{fileURLToPath as Zv}from"node:url";import{stat as zr,readdir as Ge,readFile as Nr}from"node:fs/promises";import{hostname as Qv,homedir as hn}from"node:os";import eb from"node:zlib";import{createHash as Qn,webcrypto as tb,randomBytes as Dn,X509Certificate as js,timingSafeEqual as rb,verify as nb,createPublicKey as sb}from"node:crypto";import{execFileSync as ob,execFile as ib}from"node:child_process";import{DatabaseSync as go}from"node:sqlite";import{isMainThread as hm,workerData as ai,parentPort as Bn,Worker as mm}from"node:worker_threads";import{promisify as ab}from"node:util";import{createServer as cb}from"node:https";const Yd=["machine","session","execution","process","artifact"];function ub(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"},lb=[{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 Xd(t,e){for(const r of lb){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 db=(t,e)=>t.validFrom<=e.validTo&&e.validFrom<=t.validTo;function fb(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 pb=.5;function hb(t,e){return db(t,e)?fb(t,e)>=pb?2:1:0}const xt=t=>`${t.subjectType}:${t.subjectId}`,mb="inferred",yb="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 gb(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 y=xt(p),v=a.get(y);if(!v){a.set(y,{...p});continue}v.validFrom=Math.min(v.validFrom,p.validFrom),v.validTo=Math.max(v.validTo,p.validTo)}const c=[...a.values()].sort((p,y)=>xt(p)<xt(y)?-1:1);if(c.length<2){s++;continue}const u=[];let l=!1;for(let p=0;p<c.length;p++)for(let y=p+1;y<c.length;y++){const v=c[p],g=c[y];if(v.sourceId===g.sourceId)continue;const C=hb(v,g);if(C!==0){if(!Xd(v,g)){l=!0;continue}u.push({x:v,y:g,tier:C})}}const d=new Map;for(const p of u)for(const y of[p.x,p.y]){const v=xt(y);d.set(v,Math.max(d.get(v)??0,p.tier))}const m=new Map;for(const p of u)for(const y of[p.x,p.y]){const v=xt(y);d.get(v)===p.tier&&m.set(v,(m.get(v)??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,tier:v}of u){if(d.get(xt(p))!==v||d.get(xt(y))!==v)continue;if(m.get(xt(p))!==1||m.get(xt(y))!==1){n.push({key:o,reason:"multiple-candidates",subjects:[xt(p),xt(y)].sort()});continue}const g=Xd(p,y);r.push({from:{type:g.from.subjectType,id:g.from.subjectId},to:{type:g.to.subjectType,id:g.to.subjectId},kind:g.kind,basis:mb,assumption:yb,via:o})}}return{relationships:r,ambiguous:n,unmatched:s,considered:e.size}}async function vb(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 ym=1e3,Jd=60*ym;function We(t){if(!Number.isFinite(t)||t<=0)return"0m";if(t<Jd)return`${Math.max(1,Math.round(t/ym))}s`;const e=Math.round(t/Jd),r=Math.floor(e/60),n=e%60;return r===0?`${n}m`:n===0?`${r}h`:`${r}h ${n}m`}function Qe(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 bb(t,e="NOT OBSERVED"){return t===void 0?e:Qe(t)}function wb(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 Po(t){const e=new Date(t);return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}function Ce(t){const e=t.split("/").filter(Boolean);return e[e.length-1]??t}const Ol="deepseek-harness",Ab={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"supported",waits:"supported",model:"supported",context:"supported",outcome:"supported"},Oe=t=>typeof t=="number"&&Number.isFinite(t)?t:0,ot=t=>typeof t=="string"?t:void 0;function Sb(t){const e=t.split("/").filter(Boolean);return(e[e.length-1]??t).toUpperCase()}function kb(t,e){const r=[],n=t[0];if(!n||n.type!=="session"||!n.id)return r;const s=n.id,o=n.cwd??"",i=Oe(n.createdAt),a=Oe(n.delegationDepth),c=Sb(o);let u="deepseek",l,d;for(const k of t)if(k.type==="request/context"&&k.data?(u=ot(k.data.provider)??u,l=ot(k.data.model)??l):k.type==="session/title"&&k.data&&(d=ot(k.data.title)??d),l&&d)break;const p={source:{id:Ol,instance:e.instance},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let y=i;for(const k of t){const T=Oe(k.time);T>y&&(y=T)}const v={ns:"fs.cwd",parts:[e.host,o],validFrom:i,validTo:Math.max(i,y)};r.push({...p,occurredAt:i,seq:"session",kind:"began",subject:{type:"session",id:s},claims:o?[v]:void 0,core:{machineId:e.machine.id,label:d,projectLabel:o?Ce(o):void 0,taskLabel:d,executor:u,model:l,depth:a},attrs:{context:o,"dsh.delegationDepth":a}});const g=k=>`${s}:turn:${k}`;let C=null;const A=new Map,I=new Map;let B=i;for(const k of t){const T=Oe(k.time)||B;if(T<i)continue;B=T;const S=k.data??{},E=k.seq??`t${T}`,R=j=>({type:"execution",id:g(j)});switch(k.type){case"turn/start":{const j=Oe(S.turn);C=j,r.push({...p,occurredAt:T,seq:E,kind:"began",subject:R(j),core:{machineId:e.machine.id,sessionId:s,label:d?`${c} · ${d}`:c,executor:u,model:l,depth:a},attrs:{"dsh.turn":j}});break}case"turn/end":{const j=Oe(S.turn),M=S.reason,J=M?.kind;if(J==="error"){const le=M?.error??{};r.push({...p,occurredAt:T,seq:E,kind:"ended",subject:R(j),core:{outcome:"error",failureCode:ot(le.code)??"ERROR",failureMessage:ot(le.message)??"Run failed"},attrs:{"dsh.endReason":J}})}else r.push({...p,occurredAt:T,seq:E,kind:"ended",subject:R(j),core:{outcome:J==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":J??"completed"}});C===j&&(C=null);break}case"assistant/message":{const j=Oe(S.turn),M=S.usage;if(!M)break;const J={[z.tokensInput]:Oe(M.inputTokens),[z.tokensOutput]:Oe(M.outputTokens),[z.tokensCacheRead]:Oe(M.cacheReadTokens),[z.tokensReasoning]:Oe(M.reasoningTokens),[z.steps]:1};r.push({...p,occurredAt:T,seq:E,kind:"progressed",subject:R(j),core:{measures:J},attrs:{"dsh.inputTokens":Oe(M.inputTokens),"dsh.outputTokens":Oe(M.outputTokens),"dsh.cacheReadTokens":Oe(M.cacheReadTokens),"dsh.reasoningTokens":Oe(M.reasoningTokens)}});break}case"tool/call":{r.push({...p,occurredAt:T,seq:E,kind:"progressed",subject:R(Oe(S.turn)),core:{measures:{[z.interactions]:1}},attrs:{"dsh.tool":ot(S.name)}});break}case"tool/result":{const j=S.message;let M=!1;for(const J of j?.content??[])J.isError===!0&&(M=!0);M&&r.push({...p,occurredAt:T,seq:E,kind:"progressed",subject:R(Oe(S.turn)),core:{measures:{[z.errors]:1}}});break}case"llm/retry":{r.push({...p,occurredAt:T,seq:E,kind:"progressed",subject:R(Oe(S.turn)),core:{measures:{[z.retries]:1}}});break}case"approval/asked":{const j=ot(S.id);if(C===null)break;j&&A.set(j,C),r.push({...p,occurredAt:T,seq:E,kind:"blocked",subject:R(C),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":j}});break}case"approval/decided":{const j=ot(S.id),M=j?A.get(j):C;if(M==null)break;A.delete(j??""),r.push({...p,occurredAt:T,seq:E,kind:"resumed",subject:R(M),attrs:{"dsh.approvalId":j}});break}case"tool-workflow/agent-start":{if(C===null)break;const j=ot(S.childId);if(!j)break;const M=`${s}:agent:${j}`;I.set(`${ot(S.runId)}:${Oe(S.seq)}`,M),r.push({...p,occurredAt:T,seq:E,kind:"began",subject:{type:"execution",id:M},core:{machineId:e.machine.id,sessionId:s,label:ot(S.label)??`${c} · SUB`,executor:u,model:l,parentId:g(C),depth:a+1},attrs:{"dsh.childId":j}});break}case"tool-workflow/agent-end":{const j=`${ot(S.runId)}:${Oe(S.seq)}`,M=I.get(j);if(!M)break;I.delete(j);const J=ot(S.outcome);r.push({...p,occurredAt:T,seq:E,kind:"ended",subject:{type:"execution",id:M},core:J==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:J??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":J}});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.";C!==null&&r.push({...p,occurredAt:B,seq:"close:turn",kind:"ended",subject:{type:"execution",id:g(C)},core:{outcome:"interrupted"},basis:"inferred",assumption:k});for(const T of I.values())r.push({...p,occurredAt:B,seq:`close:${T}`,kind:"ended",subject:{type:"execution",id:T},core:{outcome:"interrupted"},basis:"inferred",assumption:k});r.push({...p,occurredAt:B,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 xb(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 Eb(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,ci(t.core),ci(t.attrs)]);return Qn("sha256").update(e).digest("hex").slice(0,32)}function ci(t){if(t==null)return null;if(Array.isArray(t))return t.map(ci);if(typeof t!="object")return t;const e={};for(const r of Object.keys(t).sort())e[r]=ci(t[r]);return e}function Wt(t){const{seq:e,...r}=t;return{id:Eb(t),...r}}let Zd;function Ib(){try{const t=ob("/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 gm(){return Zd??=Ib()??Qv().replace(/\.local$/i,""),Zd}const ui="host:";function Cb(t){return`${ui}${t}`}function Ob(t){return t.startsWith(ui)?t.slice(ui.length):void 0}function Qd(t){return t.startsWith(ui)}const Nb=4247762216,Tb=407710288,Bb=407710303;function $b(t){const e=[];for(let s=0;s+4<=t.length;s++){const o=t.readUInt32LE(s);(o===Nb||o>=Tb&&o<=Bb)&&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=eb.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 Nl(){return process.env.DSH_HOME||se(hn(),".dsh")}function Rr(){return gm()}function _r(){const t=Rr();return{id:Cb(t),name:t.toUpperCase(),kind:"laptop",firstSeenAt:0}}const ef=new Map;async function vm(){const t=se(Nl(),"sessions");if(!fe(t))return[];const e=[];for(const r of await Ge(t)){const n=se(t,r);let s;try{s=await Ge(n)}catch{continue}for(const o of s){const i=se(n,o,"session.jsonl.zstd");fe(i)&&e.push({path:i,workspace:r,sessionId:o})}}return e}const Tl=10*6e4;async function Rb(t,e){const r=await zr(t.path),n=ef.get(t.path);if(n&&n.mtimeMs===r.mtimeMs&&n.size===r.size)return n.envelopes;const s=await Nr(t.path),o=$b(s).toString("utf8"),i=xb(o),a=Date.now()-r.mtimeMs>Tl,u=kb(i,{machine:e,host:Rr(),instance:Nl(),observedAt:Date.now(),closeOpenTurns:a}).map(Wt);return ef.set(t.path,{mtimeMs:r.mtimeMs,size:r.size,envelopes:u}),u}async function _b(t,e){const r=_r(),n=await vm(),s=[];for(const o of n){let i;try{i=await zr(o.path)}catch{continue}if(!(i.mtimeMs<t))for(const a of await Rb(o,r))a.occurredAt>=t&&a.occurredAt<=e&&s.push(a)}return s}async function tf(){const t=await vm(),e=Nl();return{available:t.length>0,present:fe(e),home:e,sessions:t.length}}const li="0x2f",Mb={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"supported",model:"partial",context:"supported",outcome:"supported"},er=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0},bm=(t,e)=>`2f:${t}#${e}`,jb=(t,e,r)=>`${bm(t,e)}:run:${r}`;function rf(t){return t?.type==="permission"?"approval":"input"}function Db(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 Pb(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 Lb(t,e){return Array.isArray(t.runs)&&t.runs.length?t.runs:[Pb(t,e)]}function Ub(t,e,r){if(typeof t.id!="number")return[];const n=bm(r.base,t.id),s=Lb(t,e),o=Ce(r.base).toUpperCase(),i=t.title,a=t.execution?.provider??s.at(-1)?.provider??li,c=er(t.createdAt)??s.map(g=>er(g.startedAt)).find(g=>g!==void 0);if(c===void 0)return[];const l={source:{id:li,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:Ce(r.base),taskLabel:i,executor:a,model:t.execution?.model},attrs:{context:r.base,"0x2f.taskId":t.id,"0x2f.status":t.status}}],m=Db(e),p=e.filter(g=>g.type==="task.answered"),y=e.find(g=>g.type==="task.closed"),v=s.at(-1);for(let g=0;g<s.length;g++){const C=s[g],A=er(C.startedAt);if(A===void 0)continue;const I=jb(r.base,t.id,C.run),B=C.provider??a,k=er(C.completedAt),T=k??r.now,S=[{ns:"fs.cwd",parts:[r.host,r.base],validFrom:A,validTo:T}];typeof C.externalSessionId=="string"&&C.externalSessionId&&S.push({ns:"agent.session",parts:[B,C.externalSessionId],validFrom:A,validTo:T}),C===v&&typeof t.pid=="number"&&S.push({ns:"os.process",parts:[r.host,t.pid],validFrom:A,validTo:T}),d.push({...l,occurredAt:A,seq:`run:${C.run}`,kind:"began",subject:{type:"execution",id:I},claims:S,core:{machineId:r.machine.id,sessionId:n,label:i?`${o} · ${i} · RUN ${C.run}`:`${o} · RUN ${C.run}`,executor:B,model:C.model??t.execution?.model,depth:0},attrs:{"0x2f.run":C.run,"0x2f.provider":B,"0x2f.workspace":r.base,...C.requestedProvider?{"0x2f.requestedProvider":C.requestedProvider}:{},...t.pid!==void 0&&C===v?{"0x2f.workerPid":t.pid}:{}}});let E=!1,R=0;for(const M of m.get(C.run)??[]){R++;const J=er(M.at);if(J===void 0||J<A)continue;const le=`run:${C.run}:${R}`;if(M.type==="tool.started")d.push({...l,occurredAt:J,seq:le,kind:"progressed",subject:{type:"execution",id:I},core:{measures:{[z.interactions]:1}},attrs:{"0x2f.tool":M.name}});else if(M.type==="progress")d.push({...l,occurredAt:J,seq:le,kind:"progressed",subject:{type:"execution",id:I}});else if(M.type==="needs_user"&&M.blockedOn){if(E)continue;E=!0,d.push({...l,occurredAt:J,seq:le,kind:"blocked",subject:{type:"execution",id:I},core:{blockedOn:rf(M.blockedOn)},attrs:{"0x2f.blockedOn":M.blockedOn.type}})}else if(M.type==="permission.resolved"||M.type==="task.updated"&&typeof M.grant=="string"){if(!E)continue;E=!1,d.push({...l,occurredAt:J,seq:le,kind:"resumed",subject:{type:"execution",id:I},attrs:{"0x2f.grant":M.grant}})}}const j=(M,J,le)=>d.push({...l,occurredAt:M,seq:le,kind:"ended",subject:{type:"execution",id:I},core:J});if(C.outcome==="ready"&&k!==void 0)j(k,{outcome:"completed"},`run:${C.run}:end`);else if(C.outcome==="failed"&&k!==void 0)j(k,{outcome:"error",failureCode:(C.failure?.kind??t.failure?.kind??"unclassified").toUpperCase(),failureMessage:C.error??t.error??"Run failed"},`run:${C.run}:end`);else if(C.outcome==="needs_you"&&k!==void 0){E||(E=!0,d.push({...l,occurredAt:k,seq:`run:${C.run}:block`,kind:"blocked",subject:{type:"execution",id:I},core:{blockedOn:rf(C.blockedOn)}}));const M=Vb(k,p,s[g+1],y);M!==void 0&&j(M,{outcome:"interrupted"},`run:${C.run}:end`)}}if(y){const g=er(y.at);g!==void 0&&d.push({...l,occurredAt:g,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return d}function Vb(t,e,r,n){const s=[...e.map(i=>er(i.at)),er(r?.startedAt),er(n?.at)];let o;for(const i of s)i===void 0||i<t||(o===void 0||i<o)&&(o=i);return o}function Hb(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 wm=".work";function Am(){const t=process.env.WORK_ROOTS;return t?t.split(/[:,]/).map(e=>e.trim()).filter(Boolean):[hn()]}const nf=t=>fe(se(t,wm,"tasks")),Fb=new Set(["Desktop","Documents","Downloads"]);async function Sm(){const t=new Set,e=!process.env.WORK_ROOTS;for(const r of Am()){if(nf(r)){t.add(r);continue}let n;try{n=await Ge(r,{withFileTypes:!0})}catch{continue}for(const s of n){if(!s.isDirectory()||s.name.startsWith(".")||e&&Fb.has(s.name))continue;const o=se(r,s.name);nf(o)&&t.add(o)}}return[...t].sort()}async function Wb(){const t=[];for(const e of await Sm()){const r=se(e,wm,"tasks");let n;try{n=await Ge(r,{withFileTypes:!0})}catch{continue}for(const s of n){if(!s.isDirectory())continue;const o=se(r,s.name,"task.json");fe(o)&&t.push({base:e,slug:s.name,taskPath:o,eventsPath:se(r,s.name,"events.jsonl")})}}return t}const sf=new Map;async function Kb(t,e,r){let n;try{n=await zr(t.taskPath)}catch{return null}const s=await zr(t.eventsPath).catch(()=>null),o=Math.max(n.mtimeMs,s?.mtimeMs??0),i=`${n.mtimeMs}:${n.size}:${s?.mtimeMs??0}:${s?.size??0}`,a=sf.get(t.taskPath);if(a&&a.stamp===i)return{envelopes:a.envelopes,touchedAt:o};let c;try{c=JSON.parse(await Nr(t.taskPath,"utf8"))}catch{return null}let u=[];try{u=Hb(await Nr(t.eventsPath,"utf8"))}catch{}const l=Ub(c,u,{machine:e,base:t.base,host:Rr(),observedAt:Date.now(),now:r}).map(Wt);return sf.set(t.taskPath,{stamp:i,envelopes:l}),{envelopes:l,touchedAt:o}}async function Gb(t,e){const r=_r(),n=await Wb(),s=[];for(const o of n){const i=await Kb(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 of(){const t=Am(),e=await Sm();return{available:e.length>0,present:t.some(r=>fe(r)),roots:t,workspaces:e}}const Kr="claude-code",qb={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"partial"},km="claude-code";class sr extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const xm=t=>`claude:${t}`;function zb(t,e){const r=t,n=typeof r?.version=="string"?r.version:void 0;if(!r||typeof r!="object")throw new sr("registry entry is not an object",e,n);if(typeof r.sessionId!="string"||!r.sessionId)throw new sr("registry entry has no sessionId",e,n);if(typeof r.pid!="number"||!Number.isFinite(r.pid))throw new sr("registry entry has no numeric pid",e,n);if(typeof r.startedAt!="number"||!Number.isFinite(r.startedAt))throw new sr("registry entry has no numeric startedAt",e,n);return r}function Yb(t,e,r){const n=[{ns:"agent.session",parts:[km,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:Kr,instance:r.host},occurredAt:t.startedAt,observedAt:r.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:xm(t.sessionId)},claims:n,basis:"measured",core:{machineId:r.machine.id,label:t.name??Ce(t.cwd??"").toUpperCase(),projectLabel:t.cwd?Ce(t.cwd):void 0,taskLabel:t.name,executor:Kr},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 Xb=new Set(["stop_hook_summary","turn_duration"]),Jb="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.",tr=t=>typeof t=="number"&&Number.isFinite(t)?t:0,wn=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function Zb(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 Qb(t){if(!t)return{};const e=t.output_tokens_details;return{[z.tokensInput]:tr(t.input_tokens)+tr(t.cache_creation_input_tokens),[z.tokensOutput]:tr(t.output_tokens),[z.tokensCacheRead]:tr(t.cache_read_input_tokens),[z.tokensReasoning]:tr(e?.thinking_tokens),[z.steps]:1}}function e0(t,e){const r=t.filter(A=>wn(A.timestamp)!==void 0);if(r.length===0)throw new sr("transcript has no timestamped records",e.path);const n=t.find(A=>typeof A.sessionId=="string")?.sessionId;if(n&&n!==e.sessionId)throw new sr(`transcript names session ${n} but is filed under ${e.sessionId}`,e.path);const s=t.find(A=>typeof A.version=="string")?.version,o=t.find(A=>typeof A.cwd=="string")?.cwd??"",i=t.find(A=>typeof A.gitBranch=="string")?.gitBranch,a=t.find(A=>typeof A.entrypoint=="string")?.entrypoint,c=Ce(o).toUpperCase(),u=e.sessionId,l=xm(u),d=wn(r[0].timestamp),m=wn(r[r.length-1].timestamp),y={source:{id:Kr,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},v=(A,I)=>({path:e.path,...A?{recordId:A}:{},...I!==void 0?{index:I}:{},...s?{sourceVersion:s}:{}}),g=[{...y,occurredAt:d,kind:"began",subject:{type:"session",id:l},claims:[{ns:"agent.session",parts:[km,u],validFrom:d,validTo:m}],core:{machineId:e.machine.id,label:c,projectLabel:o?Ce(o):void 0,executor:Kr},attrs:{context:o,"claude.sessionId":u,"claude.gitBranch":i,"claude.entrypoint":a,"claude.version":s},provenance:v(u),seq:"session"}],C=[];for(let A=0;A<t.length;A++){const I=t[A];I.type==="user"&&typeof I.promptSource=="string"&&wn(I.timestamp)!==void 0&&C.push(A)}if(C.length===0)throw new sr(`transcript has ${t.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,e.path,s);for(let A=0;A<C.length;A++){const I=C[A],B=A+1<C.length?C[A+1]:t.length,k=A+1,T=`${l}:turn:${k}`,S=wn(t[I].timestamp),E=t.slice(I,B).some(F=>F.isSidechain===!0);let R,j=S,M,J=!1;const le=[];for(let F=I;F<B;F++){const W=t[F],ee=wn(W.timestamp);if(ee===void 0)continue;const he=W.type==="assistant"||W.type==="user"&&Array.isArray(W.message?.content);if(he&&ee>j&&(j=ee),he?(M=W,J=!1):W.type==="system"&&Xb.has(W.subtype??"")&&(J=!0),W.type==="assistant"&&W.message){R??=W.message.model;const Me=(Array.isArray(W.message.content)?W.message.content:[]).filter(pe=>!!pe&&typeof pe=="object"&&pe.type==="tool_use"),Qt={...Qb(W.message.usage)};Me.length&&(Qt[z.interactions]=Me.length),le.push({...y,occurredAt:ee,kind:"progressed",subject:{type:"execution",id:T},core:{measures:Qt},attrs:{...Me.length?{"claude.tools":Me.map(pe=>pe.name??"unknown")}:{},...W.message.model?{"claude.model":W.message.model}:{},...W.requestId?{"claude.requestId":W.requestId}:{},...W.message.stop_reason?{"claude.stopReason":W.message.stop_reason}:{},...W.message.usage?{"claude.usage.inputTokens":tr(W.message.usage.input_tokens),"claude.usage.outputTokens":tr(W.message.usage.output_tokens),"claude.usage.cacheReadTokens":tr(W.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":tr(W.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":W.message.usage.service_tier}:{}},provenance:v(W.uuid,F),seq:W.uuid??`a${F}`})}else if(W.type==="user"&&W.message&&Array.isArray(W.message.content)){const $e=W.message.content.filter(Me=>!!Me&&typeof Me=="object"&&Me.is_error===!0).length;$e&&le.push({...y,occurredAt:ee,kind:"progressed",subject:{type:"execution",id:T},core:{measures:{[z.errors]:$e}},provenance:v(W.uuid,F),seq:W.uuid??`e${F}`})}}if(g.push({...y,occurredAt:S,kind:"began",subject:{type:"execution",id:T},core:{machineId:e.machine.id,sessionId:l,label:`${c} · TURN ${k}`,executor:Kr,model:R,depth:E?1:0},attrs:{"claude.turn":k,"claude.promptSource":t[I].promptSource,"claude.promptId":t[I].promptId,...E?{"claude.isSidechain":!0}:{}},provenance:v(t[I].uuid,I),seq:`turn:${k}`}),g.push(...le),A+1<C.length||J)g.push({...y,occurredAt:j,kind:"ended",subject:{type:"execution",id:T},core:{outcome:"completed"},provenance:v(t[I].uuid,I),seq:`turn:${k}:end`});else if(e.closeOpenTurns){const F=M?.type==="assistant"&&(M.message?.stop_reason==="end_turn"||M.message?.stop_reason==="stop_sequence");g.push({...y,occurredAt:j,kind:"ended",subject:{type:"execution",id:T},core:{outcome:F?"completed":"interrupted"},basis:"inferred",assumption:Jb,provenance:v(t[I].uuid,I),seq:`turn:${k}:end`})}}return g}function Bl(){return process.env.CLAUDE_HOME||se(hn(),".claude")}const Uc=()=>se(Bl(),"sessions"),t0=()=>se(Bl(),"projects"),af=new Map;async function r0(t,e,r){const n=Uc();if(!fe(n))return;r.identityAvailable=!0;let s;try{s=await Ge(n)}catch(o){r.problems.push({path:n,message:String(o)});return}for(const o of s){if(!o.endsWith(".json"))continue;const i=se(n,o);try{const a=zb(JSON.parse(await Nr(i,"utf8")),i);r.envelopes.push(Wt(Yb(a,i,{machine:t,host:Rr(),observedAt:e,now:e}))),r.registryEntries++}catch(a){r.problems.push({path:i,message:a instanceof Error?a.message:String(a),sourceVersion:a instanceof sr?a.sourceVersion:void 0})}}}async function Em(){const t=t0();if(!fe(t))return[];const e=[];let r;try{r=await Ge(t)}catch{return e}for(const n of r){let s;try{s=await Ge(se(t,n))}catch{continue}for(const o of s)o.endsWith(".jsonl")&&e.push({path:se(t,n,o),sessionId:o.slice(0,-6),project:n})}return e}async function n0(t,e,r,n){const s=await Em();if(s.length!==0){n.storedAvailable=!0;for(const o of s){let i;try{i=await zr(o.path)}catch{continue}if(i.mtimeMs<e)continue;const a=Date.now()-i.mtimeMs>Tl,c=`${i.mtimeMs}:${i.size}:${a}`,u=af.get(o.path);let l;if(u&&u.stamp===c)l=u.envelopes;else try{const d=Zb(await Nr(o.path,"utf8"));l=e0(d,{machine:t,host:Rr(),observedAt:Date.now(),path:o.path,sessionId:o.sessionId,closeOpenTurns:a}).map(Wt),af.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 sr?d.sourceVersion:void 0});continue}n.transcriptsRead++;for(const d of l)d.occurredAt>=e&&d.occurredAt<=r&&n.envelopes.push(d)}}}async function Im(t,e){const r=_r(),n=Date.now(),s={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await r0(r,n,s),await n0(r,t,e,s),s}async function s0(t,e){return(await Im(t,e)).envelopes}async function cf(){const t=Bl(),e=fe(Uc())?(await Ge(Uc()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,r=(await Em()).length;return{available:e>0||r>0,present:fe(t),home:t,registry:e,transcripts:r}}const Ds="codex",o0={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"supported"},i0="codex",a0=10*6e4;class kn extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const c0=t=>`codex:${t}`,Vt=t=>typeof t=="number"&&Number.isFinite(t)?t:0,ye=t=>typeof t=="string"&&t?t:void 0,uc=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function u0(t){const e=Vt(t.input_tokens),r=Vt(t.cached_input_tokens);return{[z.tokensInput]:Math.max(0,e-r),[z.tokensOutput]:Vt(t.output_tokens),[z.tokensCacheRead]:r,[z.tokensReasoning]:Vt(t.reasoning_output_tokens),[z.steps]:1}}function l0(t,e){const r=t.find(A=>A.type==="session_meta");if(!r||!r.payload)throw new kn("rollout has no session_meta record",e.path);const n=r.payload,s=ye(n.cli_version),o=ye(n.session_id)??ye(n.id);if(o&&o!==e.sessionId)throw new kn(`rollout names session ${o} but is filed under ${e.sessionId}`,e.path,s);const i=ye(n.cwd)??"",a=uc(n.timestamp)??uc(r.timestamp);if(a===void 0)throw new kn("session_meta has no parseable timestamp",e.path,s);const c=Ce(i).toUpperCase(),u=c0(e.sessionId),d={source:{id:Ds,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},m=(A,I)=>({path:e.path,...A?{recordId:A}:{},...I!==void 0?{index:I}:{},...s?{sourceVersion:s}:{}}),p=[];let y=null,v=a,g=0;for(let A=0;A<t.length;A++){const I=t[A],B=uc(I.timestamp);B!==void 0&&B>v&&(v=B);const k=I.payload;if(!k)continue;if(I.type==="turn_context"){y&&ye(k.turn_id)===y.turnId&&(y.model??=ye(k.model),y.effort??=ye(k.effort));continue}if(I.type!=="event_msg")continue;const T=ye(k.type);if(T==="task_started"){const E=ye(k.turn_id);if(!E||B===void 0)throw new kn(`task_started at ordinal ${I.ordinal} is missing turn_id or timestamp`,e.path,s);y={turnId:E,startedAt:B,interior:[],lastAt:B},p.push(y);continue}if(T==="task_complete"){const E=ye(k.turn_id),R=p.find(j=>j.turnId===E)??y;if(R&&B!==void 0){R.completedAt=B;const j=k.error;R.outcome=j?"error":"completed",R.failureMessage=j?ye(j.message):void 0,R.lastAt=Math.max(R.lastAt,B)}R===y&&(y=null);continue}if(T==="token_count"||T==="item_completed"){if(!y){g++;continue}if(B===void 0)continue}else continue;const S=`${u}:turn:${y.turnId}`;if(T==="token_count"){const R=k.info?.last_token_usage;if(!R)continue;y.lastAt=Math.max(y.lastAt,B),y.interior.push({...d,occurredAt:B,kind:"progressed",subject:{type:"execution",id:S},core:{measures:u0(R)},attrs:{"codex.usage.inputTokens":Vt(R.input_tokens),"codex.usage.cachedInputTokens":Vt(R.cached_input_tokens),"codex.usage.cacheWriteInputTokens":Vt(R.cache_write_input_tokens),"codex.usage.outputTokens":Vt(R.output_tokens),"codex.usage.reasoningOutputTokens":Vt(R.reasoning_output_tokens)},provenance:m(void 0,I.ordinal),seq:`o${I.ordinal??A}`});continue}if(T==="item_completed"){const E=k.item,R=ye(E?.type);if(!E||!R)continue;y.lastAt=Math.max(y.lastAt,B);let j,M;if(R==="CommandExecution"){const J=Vt(E.exit_code);j={[z.interactions]:1,...J!==0?{[z.errors]:1}:{}},M={"codex.itemType":R,"codex.exitCode":J,...E.process_id!==void 0?{"codex.processId":E.process_id}:{},...ye(E.status)?{"codex.status":E.status}:{}}}else if(R==="McpToolCall"){const J=ye(E.status)==="failed"||ye(E.status)==="error";j={[z.interactions]:1,...J?{[z.errors]:1}:{}},M={"codex.itemType":R,"codex.tool":[ye(E.server),ye(E.tool)].filter(Boolean).join("."),...ye(E.status)?{"codex.status":E.status}:{}}}else if(R==="WebSearch")j={[z.interactions]:1},M={"codex.itemType":R};else if(R==="FileChange"){const J=E.changes;j={[z.interactions]:1},M={"codex.itemType":R,...J&&typeof J=="object"?{"codex.fileChanges":Object.entries(J).map(([le,re])=>({path:le,kind:ye(re?.type)}))}:{}}}else continue;y.interior.push({...d,occurredAt:B,kind:"progressed",subject:{type:"execution",id:S},core:{measures:j},attrs:M,provenance:m(ye(E.id),I.ordinal),seq:`o${I.ordinal??A}`})}}if(p.length===0&&g>0)throw new kn(`rollout has ${g} work records but no task_started marker`,e.path,s);const C=[{...d,occurredAt:a,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[i0,e.sessionId],validFrom:a,validTo:v}],core:{machineId:e.machine.id,label:c,projectLabel:e.projectLabel??(i?Ce(i):void 0),taskLabel:e.taskLabel,executor:Ds},attrs:{context:i,"codex.sessionId":e.sessionId,"codex.cliVersion":s,"codex.originator":ye(n.originator),"codex.source":ye(n.source),"codex.modelProvider":ye(n.model_provider),...d0(n.git)},provenance:m(e.sessionId,r.ordinal),seq:"session"}];for(let A=0;A<p.length;A++){const I=p[A],B=`${u}:turn:${I.turnId}`;C.push({...d,occurredAt:I.startedAt,kind:"began",subject:{type:"execution",id:B},core:{machineId:e.machine.id,sessionId:u,label:`${c} · TURN ${A+1}`,executor:Ds,model:I.model,depth:0},attrs:{"codex.turnId":I.turnId,...I.effort?{"codex.effort":I.effort}:{}},provenance:m(I.turnId),seq:`turn:${I.turnId}`}),C.push(...I.interior),I.completedAt!==void 0?C.push({...d,occurredAt:I.completedAt,kind:"ended",subject:{type:"execution",id:B},core:{outcome:I.outcome??"completed",...I.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:I.failureMessage??"turn failed"}:{}},provenance:m(I.turnId),seq:`turn:${I.turnId}:end`}):e.now-v>a0&&C.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:I.lastAt,kind:"ended",subject:{type:"execution",id:B},core:{outcome:"interrupted"},provenance:m(I.turnId),seq:`turn:${I.turnId}:end`})}return C}function d0(t){if(!t||typeof t!="object")return{};const e=t;return{...ye(e.branch)?{"codex.gitBranch":e.branch}:{},...ye(e.commit_hash)?{"codex.gitCommit":e.commit_hash}:{},...ye(e.repository_url)?{"codex.gitOriginUrl":e.repository_url}:{}}}function $l(){return process.env.CODEX_HOME||se(hn(),".codex")}const Cm=()=>se($l(),"sessions"),f0=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,lc=new Map,p0=new Set(["CommandExecution","McpToolCall","WebSearch","FileChange"]);function h0(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")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||!p0.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 m0(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 y=h0(p);y&&r.push(y)}catch{}};for await(const c of dm(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 y0(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 g0(t,e=$l()){const r=se(e,"state_5.sqlite");if(!fe(r))return new Map;let n;try{n=new go(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
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=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 v0(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function b0(t,e){if(e?.trim())return e.trim();const r=t.find(o=>o.type==="session_meta"),n=v0(r?.payload?.cwd);if(!n)return;if(fe(se(n,".git")))return Ce(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(!Pc(c))continue;const u=cc(n,c);if(!u||u===".."||u.startsWith(`..${Lc}`)||Pc(u))continue;const l=u.split(Lc).filter(Boolean)[0];if(!l||l.startsWith("."))continue;const d=se(n,l);let m;if(fe(se(d,".git")))m=d;else{let y=ii(c);for(;y!==n&&cc(n,y)&&!cc(n,y).startsWith("..");){fe(se(y,".git"))&&(m=y);const v=ii(y);if(v===y)break;y=v}}const p=m?Ce(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]??Ce(n)}async function Om(){const t=Cm();if(!fe(t))return[];const e=[];let r;try{r=await Ge(t)}catch{return e}for(const n of r){let s;try{s=await Ge(se(t,n))}catch{continue}for(const o of s){let i;try{i=await Ge(se(t,n,o))}catch{continue}for(const a of i){let c;try{c=await Ge(se(t,n,o,a))}catch{continue}for(const u of c){const l=f0.exec(u);l&&e.push({path:se(t,n,o,a,u),sessionId:l[1]})}}}}return e}async function Nm(t,e){const r=_r(),n=Date.now(),s={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},o=await Om();if(o.length===0)return s.storedAvailable=fe(Cm()),s;s.storedAvailable=!0;const i=g0(o);for(const a of o){let c;try{c=await zr(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=i.get(a.sessionId),l=`${u?.projectLabel??""}:${u?.taskLabel??""}`;let d=lc.get(a.path);d&&c.size<d.offset&&(lc.delete(a.path),d=void 0);let m;const p=await m0(a.path,d?.offset??0),y=d?p.records.length>0?[...d.records,...p.records]:d.records:p.records,v=!d||p.offset!==d.offset;if(d&&!v&&d.annotationStamp===l)m=d.envelopes;else try{const g=b0(y,u?.projectLabel);m=l0(y,{machine:r,host:Rr(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n,projectLabel:g,taskLabel:u?.taskLabel}).map(Wt),lc.set(a.path,{offset:p.offset,records:y,annotationStamp:l,envelopes:m})}catch(g){s.rolloutsFailed++,s.problems.push({path:a.path,message:g instanceof Error?g.message:String(g),sourceVersion:g instanceof kn?g.sourceVersion:void 0});continue}s.rolloutsRead++;for(const g of m)y0(g,t,e)&&s.envelopes.push(g)}return s}async function w0(t,e){return(await Nm(t,e)).envelopes}async function uf(){const t=$l(),e=(await Om()).length;return{available:e>0,present:fe(t),home:t,rollouts:e}}const Pn="cursor",A0={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"unsupported",context:"partial",outcome:"partial"},S0="cursor";class Jo extends Error{constructor(e,r,n){super(e),this.path=r,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const Vc=t=>`cursor:${t}`,Vr=t=>typeof t=="string"&&t?t:void 0,Lo=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,lf=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function Tm(t,e){if(typeof t.composerId!="string"||!t.composerId)throw new Jo("composer header has no composerId",e);if(typeof t.createdAt!="number"||!Number.isFinite(t.createdAt))throw new Jo("composer header has no numeric createdAt",e);if(typeof t.lastUpdatedAt!="number"||!Number.isFinite(t.lastUpdatedAt))throw new Jo("composer header has no numeric lastUpdatedAt",e)}function k0(t,e){Tm(t,e.path);const r=t.value??{},n=r.subagentInfo,s=n?Vr(n.parentComposerId):void 0,o=e.workspacePath??"",i=Vr(r.name)?.toUpperCase()??(o?Ce(o).toUpperCase():"CURSOR");return{source:{id:Pn,instance:e.host},occurredAt:t.createdAt,observedAt:e.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:Vc(t.composerId)},claims:[{ns:"agent.session",parts:[S0,t.composerId],validFrom:t.createdAt,validTo:t.lastUpdatedAt}],basis:"measured",core:{machineId:e.machine.id,label:i,projectLabel:o?Ce(o):void 0,taskLabel:Vr(r.name),executor:Pn,...s?{parentId:Vc(s)}:{}},attrs:{context:o,"cursor.composerId":t.composerId,"cursor.workspaceId":t.workspaceId,"cursor.isSubagent":t.isSubagent,...n?{"cursor.parentComposerId":Vr(n.parentComposerId),"cursor.subagentType":Vr(n.subagentTypeName)}:{},...Lo(r.totalLinesAdded)!==void 0?{"cursor.linesAdded":r.totalLinesAdded}:{},...Lo(r.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":r.totalLinesRemoved}:{},...Lo(r.filesChangedCount)!==void 0?{"cursor.filesChanged":r.filesChangedCount}:{},...Vr(r.unifiedMode)?{"cursor.mode":r.unifiedMode}:{},...Lo(r._v)!==void 0?{"cursor.schemaVersion":r._v}:{}},provenance:{path:e.path,recordId:t.composerId},seq:"composer"}}const df="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 x0(t,e,r){Tm(t,r.path);const n=Vc(t.composerId),o={source:{id:Pn,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,y=e.slice(d,m),v=y.map(k=>({bubble:k,at:lf(k.createdAt)})).filter(k=>k.at!==void 0);if(v.length<2){u++;continue}const g=Math.min(...v.map(k=>k.at)),C=Math.max(...v.map(k=>k.at)),A=`${n}:turn:${p}`,I=y.filter(k=>k.toolName&&lf(k.createdAt)===void 0),B=I.filter(k=>k.toolStatus==="error").length;c.push({...o,occurredAt:g,kind:"began",subject:{type:"execution",id:A},basis:"inferred",assumption:df,core:{machineId:r.machine.id,sessionId:n,label:`${Vr(t.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${p}`,executor:Pn,depth:t.isSubagent?1:0,...I.length?{measures:{[z.interactions]:I.length,...B?{[z.errors]:B}:{}}}:{}},attrs:{"cursor.turn":p},provenance:i(e[d].bubbleId),seq:`turn:${p}`});for(const{bubble:k,at:T}of v){if(!k.toolName)continue;const S=k.toolStatus==="error",E={[z.interactions]:1,...S?{[z.errors]:1}:{}};c.push({...o,occurredAt:T,kind:"progressed",subject:{type:"execution",id:A},basis:"measured",core:{measures:E},attrs:{"cursor.tool":k.toolName,...k.toolStatus?{"cursor.toolStatus":k.toolStatus}:{}},provenance:i(k.bubbleId),seq:k.bubbleId})}c.push({...o,occurredAt:C,kind:"ended",subject:{type:"execution",id:A},basis:"inferred",assumption:df,core:{outcome:"completed"},provenance:i(e[d].bubbleId),seq:`turn:${p}:end`})}return{drafts:c,turns:a.length,untimedTurns:u}}function Ps(){return process.env.CURSOR_GLOBAL_STORAGE||se(hn(),"Library","Application Support","Cursor","User","globalStorage")}function E0(){return process.env.CURSOR_WORKSPACE_STORAGE||se(Ps(),"..","workspaceStorage")}const Bm=()=>se(Ps(),"state.vscdb"),ff=new Map;async function I0(){const t=new Map,e=E0();if(!fe(e))return t;let r;try{r=await Ge(e)}catch{return t}for(const n of r)try{const s=JSON.parse(await Nr(se(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 C0(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 Jo(`composer ${t.composerId} has no numeric createdAt/lastUpdatedAt`,e);return o}function O0(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 $m(t,e){const r=_r(),n=Date.now(),s=Bm(),o={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!fe(s))return o;o.storedAvailable=!0;const i=await I0();let a;try{a=new go(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=C0(u,s);if(l.lastUpdatedAt<t)continue;const d={machine:r,host:Rr(),observedAt:n,path:s,workspacePath:l.workspaceId?i.get(l.workspaceId):void 0};o.envelopes.push(Wt(k0(l,d)));const m=`${l.lastUpdatedAt}`,p=ff.get(l.composerId);let y;if(p&&p.stamp===m)y=p.envelopes;else{const v=O0(a,l.composerId),{drafts:g}=x0(l,v,d);y=g.map(Wt),ff.set(l.composerId,{stamp:m,envelopes:y})}for(const v of y)v.occurredAt>=t&&v.occurredAt<=e&&o.envelopes.push(v);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 N0(t,e){return(await $m(t,e)).envelopes}async function pf(){const t=Bm();if(!fe(t))return{available:!1,present:!1,globalStorage:Ps()};try{const e=new go(t,{readOnly:!0});try{const r=e.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:r.n>0,present:!0,globalStorage:Ps(),composers:r.n}}finally{e.close()}}catch{return{available:!1,present:!0,globalStorage:Ps()}}}const Ls="gemini",T0={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"unsupported",model:"supported",context:"partial",outcome:"partial"},B0="gemini";class di extends Error{constructor(e,r){super(e),this.path=r,this.name="GeminiFormatError"}path}const $0="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 R0(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 _0=t=>`gemini:${t}`,Ht=t=>typeof t=="number"&&Number.isFinite(t)?t:0,Uo=t=>typeof t=="string"&&t?t:void 0,An=t=>{if(typeof t!="string")return;const e=Date.parse(t);return Number.isFinite(e)?e:void 0};function M0(t,e){const r=t.split(`
9
- `).filter(a=>a.trim());if(r.length===0)throw new di("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 di("session file has no header with a sessionId",e);return{header:n,messages:s.map(a=>o.get(a))}}const Rm=t=>Array.isArray(t.content)&&t.content.some(e=>!!e&&typeof e=="object"&&"functionResponse"in e);function j0(t){if(t.type!=="user"||Rm(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 D0(t){const e=Ht(t.input),r=Ht(t.cached);return{[z.tokensInput]:Math.max(0,e-r),[z.tokensOutput]:Ht(t.output)+Ht(t.thoughts),[z.tokensCacheRead]:r,[z.tokensReasoning]:Ht(t.thoughts),[z.steps]:1}}function P0(t,e){const{header:r,messages:n}=t,s=r.sessionId,o=An(r.startTime);if(o===void 0)throw new di("session header has no parseable startTime",e.path);const i=n.filter(g=>An(g.timestamp)!==void 0),a=i.length?Math.max(...i.map(g=>An(g.timestamp))):o,c=e.workspacePath??"",u=c?Ce(c).toUpperCase():"GEMINI",l=_0(s),m={source:{id:Ls,instance:e.host},observedAt:e.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},p=g=>({path:e.path,...g?{recordId:g}:{}}),y=[{...m,occurredAt:o,kind:"began",subject:{type:"session",id:l},claims:[{ns:"agent.session",parts:[B0,s],validFrom:o,validTo:a}],core:{machineId:e.machine.id,label:u,projectLabel:c?Ce(c):void 0,executor:Ls},attrs:{context:c,"gemini.sessionId":s,"gemini.projectHash":r.projectHash,...Uo(r.kind)?{"gemini.kind":r.kind}:{}},provenance:p(s),seq:"session"}],v=[];for(let g=0;g<n.length;g++)j0(n[g])&&An(n[g].timestamp)!==void 0&&v.push(g);if(v.length===0){if(n.some(g=>g.type==="gemini"))throw new di(`session has ${n.length} messages including model output but no recognisable user prompt`,e.path);return y}for(let g=0;g<v.length;g++){const C=v[g],A=g+1<v.length?v[g+1]:n.length,I=g+1,B=`${l}:turn:${I}`,k=An(n[C].timestamp);let T=k,S,E;const R=[];for(let re=C;re<A;re++){const F=n[re],W=An(F.timestamp);if(W===void 0||F.type!=="gemini"&&F.type!=="error"&&!(F.type==="user"&&Rm(F))||(W>T&&(T=W),E=F,F.type!=="gemini"))continue;S??=Uo(F.model);const ee=Array.isArray(F.toolCalls)?F.toolCalls:[],he=F.tokens?D0(F.tokens):{};ee.length&&(he[z.interactions]=ee.length),Object.keys(he).length!==0&&R.push({...m,occurredAt:W,kind:"progressed",subject:{type:"execution",id:B},core:{measures:he},attrs:{...ee.length?{"gemini.tools":ee.map($e=>Uo($e.name)??"unknown")}:{},...Uo(F.model)?{"gemini.model":F.model}:{},...F.tokens?{"gemini.usage.input":Ht(F.tokens.input),"gemini.usage.output":Ht(F.tokens.output),"gemini.usage.cached":Ht(F.tokens.cached),"gemini.usage.thoughts":Ht(F.tokens.thoughts),"gemini.usage.tool":Ht(F.tokens.tool)}:{}},provenance:p(F.id),seq:F.id})}y.push({...m,occurredAt:k,kind:"began",subject:{type:"execution",id:B},core:{machineId:e.machine.id,sessionId:l,label:`${u} · TURN ${I}`,executor:Ls,model:S,depth:0},attrs:{"gemini.turn":I},provenance:p(n[C].id),seq:`turn:${I}`}),y.push(...R);const j=E?.type==="error",M=E?.type==="gemini"&&!(Array.isArray(E.toolCalls)&&E.toolCalls.length),J=g+1<v.length,le=(re,F)=>({...m,occurredAt:T,kind:"ended",subject:{type:"execution",id:B},core:re,...F?{basis:"inferred",assumption:$0}:{},provenance:p(n[C].id),seq:`turn:${I}:end`});j?y.push(le({outcome:"error",failureMessage:R0(E)},!1)):J||M&&e.settled?y.push(le({outcome:"completed"},!1)):e.closeOpenTurns&&y.push(le({outcome:M?"completed":"interrupted"},!0))}return y}const L0=3e3;function Rl(){return process.env.GEMINI_HOME||se(hn(),".gemini")}const _m=()=>se(Rl(),"tmp"),hf=new Map;async function U0(){const t=new Map;try{const e=JSON.parse(await Nr(se(Rl(),"projects.json"),"utf8"));for(const[r,n]of Object.entries(e.projects??{}))typeof n=="string"&&t.set(n,r)}catch{}return t}async function Mm(){const t=_m();if(!fe(t))return[];const e=[];let r;try{r=await Ge(t)}catch{return e}for(const n of r){let s;try{s=await Ge(se(t,n,"chats"))}catch{continue}for(const o of s)o.startsWith("session-")&&o.endsWith(".jsonl")&&e.push({path:se(t,n,"chats",o),slug:n})}return e}async function jm(t,e){const r=_r(),n=Date.now(),s={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},o=await Mm();if(o.length===0)return s.storedAvailable=fe(_m()),s;s.storedAvailable=!0;const i=await U0();for(const a of o){let c;try{c=await zr(a.path)}catch{continue}if(c.mtimeMs<t)continue;const u=Date.now()-c.mtimeMs,l=u>L0,d=u>Tl,m=`${c.mtimeMs}:${c.size}:${l}:${d}`,p=hf.get(a.path);let y;if(p&&p.stamp===m)y=p.envelopes;else try{const v=M0(await Nr(a.path,"utf8"),a.path);y=P0(v,{machine:r,host:Rr(),observedAt:n,path:a.path,workspacePath:i.get(a.slug),settled:l,closeOpenTurns:d}).map(Wt),hf.set(a.path,{stamp:m,envelopes:y})}catch(v){s.sessionsFailed++,s.problems.push({path:a.path,message:v instanceof Error?v.message:String(v)});continue}s.sessionsRead++;for(const v of y)v.occurredAt>=t&&v.occurredAt<=e&&s.envelopes.push(v)}return s}async function V0(t,e){return(await jm(t,e)).envelopes}async function mf(){const t=Rl(),e=(await Mm()).length;return{available:e>0,present:fe(t),home:t,sessions:e}}const H0=new Set(["running","waiting"]);function Dm(t){return H0.has(t)}function Pm(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 F0=5*6e4;function W0(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-F0,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,...W0(t.sessions.values())]}}function yf(t){const e=Pm(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),Dm(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 Ot(t,e){const r=t[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function fi(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 G0=[z.tokensInput,z.tokensOutput,z.tokensCacheRead];function ur(t){let e=0,r=!1;for(const n of G0){const s=Ot(t,n);s!==void 0&&(r=!0,e+=s)}return r?e:void 0}function Lm(t){return{input:Ot(t,z.tokensInput)??0,output:Ot(t,z.tokensOutput)??0,cacheRead:Ot(t,z.tokensCacheRead)??0,reasoning:Ot(t,z.tokensReasoning)??0}}function Um(t){const e=ur(t.measures);if(e!==void 0)return gf(e/1e3,200);const r=Ot(t.measures,z.cpuMs);if(r!==void 0)return gf(r/1e3,200)}function es(t){return Ot(t.measures,z.interactions)}function Vm(t){return Ot(t.measures,z.steps)??0}function Hc(t){return Ot(t.measures,z.errors)??0}function Fc(t){return Ot(t.measures,z.retries)??0}function gf(t,e){return Math.min(1,Math.log1p(Math.max(0,t))/Math.log1p(e))}function q0(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 pi(t,e=0){return q0(t+"#"+e)%1e5/1e5}const dc=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function z0(t){if(t<dc.length)return dc[t];const r=-.9+(t-dc.length)*1.15;return{x:620+Math.cos(r)*520,y:300+Math.sin(r)*250,extentX:150,extentY:94}}function Y0(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 vf(t,e){const r=pi(e,1),n=pi(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}}const bf=30,X0=74;function J0(t){return bf+t*(X0-bf)}const wf=64,Z0=8,Q0=8,Af=16,Sf=.45;function ew(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 kf=.32;function tw(t){const e=Um(t),r=t.depth>0?.62:1;return e===void 0?kf*r:Math.min(1,(kf+.68*e)*r)}function rw(t,e){const r=Math.max(1,(t.endedAt??e)-t.startedAt),n=(es(t)??0)/(r/6e4);return Math.min(1,.25+n/24)}function xf(t){return(t.status==="failed"?3:t.status==="waiting"?2:t.status==="running"?1:0)*1e15+t.lastActivityAt}function nw(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 sw(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=Um(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 Ef(t){let e=1;for(const r of t)e*=1-Math.min(1,Math.max(0,r));return 1-e}function If(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 Cf(t){const e=t.now,r=Y0(t.machines.values()).slice(0,Z0),n=new Map,s=[];let o=1;const i=new Map;for(const S of t.executions.values()){const E=(i.get(S.machineId)??0)+1;i.set(S.machineId,E),E>o&&(o=E)}r.forEach((S,E)=>{const R=z0(E);n.set(S.id,R),s.push({id:S.id,name:S.name,kind:S.kind,x:R.x,y:R.y,extentX:R.extentX,extentY:R.extentY,prominence:(i.get(S.id)??0)/o,seed:pi(S.id,7)})});const a=45e3,c=[];for(const S of t.executions.values())(S.status==="completed"||S.status==="failed")&&e-(S.endedAt??e)>a||S.status==="idle"&&e-S.lastActivityAt>a*4||n.has(S.machineId)&&c.push(S);c.length>wf&&(c.sort((S,E)=>xf(E)-xf(S)),c.length=wf);const u=nw(t),l=S=>{const E=n.get(S.machineId),{x:R,y:j}=vf(E,S.id),M=t.sessions.get(S.sessionId);return{id:S.id,massId:S.machineId,sessionId:S.sessionId,x:R,y:j,extent:tw(S),energy:ew(S,e),rate:rw(S,e),phase:pi(S.id,3)*Math.PI*2,status:S.status,label:S.label,projectLabel:M?.projectLabel,taskLabel:M?.taskLabel,statusSince:S.waitingSince??S.endedAt??S.startedAt,articulation:sw(S,u),shoulder:0,observers:1}},d=new Set(c.map(S=>S.id)),m=new Set,p=[],y=S=>[S.startedAt,S.endedAt??e];for(const S of[...c].sort((E,R)=>E.id<R.id?-1:1)){if(m.has(S.id))continue;const E=[S];m.add(S.id);for(let re=0;re<E.length;re++)for(const F of u.sameExecution.get(E[re].id)??[])!d.has(F)||m.has(F)||(m.add(F),E.push(t.executions.get(F)));if(E.length===1){p.push(l(S));continue}const R=E.map(l),j=R.reduce((re,F)=>F.articulation>re.articulation||F.articulation===re.articulation&&F.id<re.id?F:re);let M=1;const[J,le]=y(t.executions.get(j.id));for(const re of E){const[F,W]=y(re);M=Math.min(M,If(J,le,F,W))}p.push({...j,extent:Math.max(...R.map(re=>re.extent)),energy:Math.max(...R.map(re=>re.energy)),articulation:Ef(R.map(re=>re.articulation)),shoulder:Math.min(Sf,1-M),observers:E.length})}const v=new Map;for(const S of p){if(u.runObservesSession.has(S.id))continue;const E=v.get(S.sessionId);E?E.push(S):v.set(S.sessionId,[S])}const g=new Map,C=[];for(const S of p){const E=u.runObservesSession.get(S.id),R=E?v.get(E):void 0;if(!E||!R||R.length===0){if(C.push(S),E){const W=v.get(S.sessionId);W?W.push(S):v.set(S.sessionId,[S])}continue}const j=t.executions.get(S.id);let M=1/0,J=-1/0;for(const W of R){const[ee,he]=y(t.executions.get(W.id));M=Math.min(M,ee),J=Math.max(J,he)}const[le,re]=y(j),F=g.get(E)??{articulations:[],coincidence:1};F.articulations.push(S.articulation),F.coincidence=Math.min(F.coincidence,If(le,re,M,J)),g.set(E,F)}const A=[];for(const S of[...v.keys()].sort()){const E=v.get(S),R=t.sessions.get(S);if(!R||E.length===0)continue;let j=0,M=0;for(const W of E)j+=W.x,M+=W.y;j/=E.length,M/=E.length;let J=0,le=0;for(const W of E){const ee=J0(W.extent);J=Math.max(J,Math.abs(W.x-j)+ee*1.5),le=Math.max(le,Math.abs(W.y-M)+ee)}const re=g.get(S),F=Math.max(...E.map(W=>W.articulation));A.push({id:S,massId:E[0].massId,x:j,y:M,extentX:Math.max(J,52),extentY:Math.max(le,36),presence:1,articulation:re?Ef([F,...re.articulations]):F,parentId:R.parentId,empty:!1,shoulder:re?Math.min(Sf,1-re.coincidence):0,observers:1+(re?.articulations.length??0),label:R.label??R.executor??S,projectLabel:R.projectLabel,taskLabel:R.taskLabel})}for(const S of[...t.sessions.values()].sort((E,R)=>E.id<R.id?-1:1)){if(S.executionIds.length>0||S.endedAt!==void 0&&e-S.endedAt>a)continue;const E=n.get(S.machineId);if(!E)continue;const{x:R,y:j}=vf(E,`session-presence:${S.id}`);A.push({id:S.id,massId:S.machineId,x:R,y:j,extentX:64,extentY:42,presence:1,articulation:u.sessionsWithProcess.has(S.id)?.5:.25,parentId:S.parentId,empty:!0,shoulder:0,observers:1,label:S.label??S.executor??S.id,projectLabel:S.projectLabel,taskLabel:S.taskLabel})}if(A.length>Af){const S=E=>E.empty?0:v.get(E.id)?.length??0;A.sort((E,R)=>S(R)-S(E)||(E.id<R.id?-1:1)),A.length=Af}const I=[];for(const S of t.transfers.values())if(S.endedAt===void 0&&!(!n.has(S.fromMachineId)||!n.has(S.toMachineId))){if(I.length>=Q0)break;I.push({id:S.id,fromMassId:S.fromMachineId,toMassId:S.toMachineId,energy:1,label:S.label})}const B=new Map;r.forEach((S,E)=>B.set(S.id,E));const k=Math.max(1,t.dayEnd-t.dayStart),T=[];for(const S of t.executions.values()){const E=B.get(S.machineId);if(E===void 0)continue;const R=(S.startedAt-t.dayStart)/k,j=((S.endedAt??e)-t.dayStart)/k;T.push({id:S.id,massId:S.machineId,lane:E,startFraction:Math.max(0,Math.min(1,R)),endFraction:Math.max(0,Math.min(1,j)),status:S.status,label:S.label})}return{time:e,masses:s,disturbances:C,plinths:A,couplings:I,strata:T}}const hi="057.landscape",qs=1;function ow(t){return{contract:hi,version:qs,landscape:t}}const _l="SHAPES FIELD",Ml="METADATA — DOES NOT SHAPE FIELD";function Hm(t){const e=new Date(t),r=n=>String(n).padStart(2,"0");return`${r(e.getHours())}:${r(e.getMinutes())}:${r(e.getSeconds())}`}function iw(t){return We(t).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function aw(t,e,r,n,s=()=>{}){if(r==="mass")return lw(t,e,n);if(r==="coupling")return dw(t,n);const o=t.executions.get(n);return o?cw(t,e,o,r,s("execution",n)):null}function cw(t,e,r,n,s){const o=t.sessions.get(r.sessionId),i=t.machines.get(r.machineId),c=e.disturbances.find(g=>g.id===r.id)?.statusSince??r.endedAt??r.startedAt,u=r.startBasis==="inferred"||r.endBasis==="inferred",l=ur(r.measures),d=[{key:"MACHINE",value:(i?.name??r.machineId).toUpperCase()},{key:"STATE",value:r.status.toUpperCase(),tone:r.status},{key:"SINCE",value:Hm(c)},l===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:Qe(l)}];if(o){const g=o.executionIds.indexOf(r.id),C=e.plinths.some(I=>I.id===o.id),A=g>=0?`${g+1} OF ${o.executionIds.length}`:`OF ${o.executionIds.length}`;d.push({key:"SESSION",value:C?`${A} · PLINTH`:A})}const m=uw(t,r.id),p=[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?.context&&p.push({key:"PROJECT",value:Ce(o.context),note:o.context}),p.push({key:"SOURCE",value:[r.executor,m===void 0?void 0:`pid ${m}`].filter(Boolean).join(" · "),note:s}),p.push({key:"REQUESTS",value:String(Vm(r))});const y=es(r);if(p.push(y===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:bb(y)}),p.push({key:"ELAPSED",value:`${We((r.endedAt??t.now)-r.startedAt)}${u?" · inferred":""}`,note:u?r.boundsAssumption:void 0}),l!==void 0){const g=Lm(r.measures);p.push({key:"INPUT",value:Qe(g.input)},{key:"OUTPUT",value:Qe(g.output)}),p.push({key:"CACHE READ",value:Qe(g.cacheRead)},{key:"REASONING",value:Qe(g.reasoning)})}Hc(r)>0&&p.push({key:"TOOL ERRORS",value:String(Hc(r)),tone:"failed"}),Fc(r)>0&&p.push({key:"RETRIES",value:String(Fc(r)),tone:"waiting",note:"Provider retries."}),(r.waits.length>0||r.waitingMs>0)&&p.push({key:"BLOCKED",value:`${We(r.waitingMs)} on you · ${r.waits.length||1}×`,tone:"waiting"}),r.depth>0&&p.push({key:"SUB-AGENT",value:`depth ${r.depth}`});const v=r.status==="running"||r.status==="waiting";return{id:r.id,eyebrow:n==="stratum"||!v?"SELECTED · RUN":"SELECTED · PROCESS",title:r.label.toUpperCase(),state:{text:v?`${r.status.toUpperCase()} · ${iw(t.now-c)}`:r.status.toUpperCase(),status:r.status},groups:[{title:_l,metadata:!1,rows:d},{title:Ml,metadata:!0,rows:p}],failure:r.failure?`${r.failure.code}: ${r.failure.message}`:void 0,reveal:s}}function uw(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 lw(t,e,r){const n=t.machines.get(r);if(!n)return null;let s=0,o=0,i=0,a;for(const p of t.executions.values()){if(p.machineId!==n.id)continue;const y=ur(p.measures);y!==void 0&&(a=(a??0)+y),p.status==="running"?s++:p.status==="waiting"?o++:i++}const u=[{key:"KIND",value:(e.masses.find(p=>p.id===r)?.kind??n.kind).toUpperCase()},{key:"RUNNING",value:String(s),tone:s>0?"running":void 0}];o>0&&u.push({key:"WAITING",value:String(o),tone:"waiting"}),u.push({key:"RAN TODAY",value:String(i)});const l=[a===void 0?{key:"TOKENS",value:"not observed",tone:"absent",note:"No execution in this window reported token accounting."}:{key:"TOKENS",value:Qe(a)}],d=t.processTotals;if(d){const p=new Set;for(const y of t.relationships)y.kind==="ran-as"&&(y.from.type==="process"&&p.add(y.from.id),y.to.type==="process"&&p.add(y.to.id));l.push({key:"PROCESSES",value:`${d.observed} observed`}),l.push({key:"LAST 5 MIN",value:`${d.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."}),l.push({key:"ATTRIBUTED",value:`${p.size} of ${d.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const m=s+o;return{id:r,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:m>0?{text:`${m} ACTIVE`,status:s>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:_l,metadata:!1,rows:u},{title:Ml,metadata:!0,rows:l}]}}function dw(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:_l,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:s.toUpperCase()},{key:"SINCE",value:Hm(r.startedAt)}]},{title:Ml,metadata:!0,rows:[{key:"WHAT",value:r.label},{key:"SIZE",value:wb(r.bytes)}]}]}}const it=t=>({value:t,basis:"measured"}),Vo=(t,e)=>({value:t,basis:"inferred",assumption:e});function jl(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 Of(t){let e=0;for(const r of t)e+=r.end-r.start;return e}function fw(t,e){const r=[];let n=0,s=0;for(;n<t.length&&s<e.length;){const o=Math.max(t[n].start,e[s].start),i=Math.min(t[n].end,e[s].end);o<i&&r.push({start:o,end:i}),t[n].end<e[s].end?n++:s++}return r}function Fm(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 pw(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}const Wm=6e4;function ta(t,e){return t.endedAt!==void 0?{start:t.startedAt,end:t.endedAt}:{start:t.startedAt,end:t.status==="idle"?Math.max(t.startedAt,t.lastActivityAt):e}}function hw(t){const e=[];for(const r of t.executions.values()){r.depth===0&&e.push({start:r.startedAt-Wm,end:r.startedAt});for(const n of r.waits)e.push({start:n.start,end:n.end});r.waitingSince!==void 0&&e.push({start:r.waitingSince,end:t.now})}return jl(e)}function mw(t){const e=t.now,r=[...t.executions.values()];let n=0,s=0,o=0,i=0,a=0,c=0,u=0,l=0;const d=[],m=new Map;for(const T of r){n+=Vm(T),s+=ur(T.measures)??0,o+=es(T)??0,T.status==="completed"?i++:T.status==="failed"?a++:T.status==="waiting"?c++:T.status==="idle"&&u++;const S=ta(T,e);d.push(S),l+=T.waitingMs,T.waitingSince!==void 0&&(l+=Math.max(0,e-T.waitingSince));let E=m.get(T.machineId);E||(E={machineId:T.machineId,executions:0,tokens:0,computeTime:0},m.set(T.machineId,E)),E.executions++,E.tokens+=ur(T.measures)??0,E.computeTime+=S.end-S.start}const p=jl(d.map(T=>({...T}))),y=hw(t),v=Of(fw(p,y)),{peak:g,at:C}=Fm(d),A=yw(t),I=Math.max(0,A.length-1);let B=null;for(const T of A)(!B||T.end-T.start>B.end-B.start)&&(B=T);let k=0;for(const T of t.sessions.values())T.executionIds.some(S=>t.executions.has(S))&&k++;return{requests:it(n),sessions:it(k),executions:it(r.length),tokens:it(s),toolCalls:it(o),timeInFlight:Vo(Of(p),"Wall-clock time during which at least one run was in flight, merged so parallel runs are not double-counted. A run still open counts to now while it is running or waiting, and only to its last output once it has gone idle. In flight is not computing: it includes a run waiting on a tool, a model or a person."),humanAgentOverlap:Vo(v,`Time in flight intersecting a window when you were plausibly present: the ${Wm/1e3}s before you sent a message, and any approval from ask to answer.`),peakConcurrency:it(g),peakConcurrencyAt:it(C),contextSwitches:Vo(I,"Transitions between working directories, ordered by time. A directory is the closest thing the source has to a project."),longestFocus:Vo(B,"Longest unbroken stretch spent in one working directory."),waitingOnYou:it(l),completed:it(i),failed:it(a),waiting:it(c),idle:it(u),byMachine:m,contextSpans:A,transfers:it(t.transfers.size)}}function yw(t){const e=[];for(const n of t.executions.values()){const s=t.sessions.get(n.sessionId);s&&e.push({context:s.context,...ta(n,t.now)})}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<=gw?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 gw=15*6e4;function vw(t){return{key:t,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function fc(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=vw(o),r.set(o,i)),i.runs++;const a=ur(s.measures);if(a!==void 0&&(i.tokens+=a,i.tokenRuns++,s.endedAt!==void 0)){let u=n.get(o);u||(u=[],n.set(o,u)),u.push(a)}const c=ta(s,t.now);i.computeMs+=c.end-c.start,i.waitingMs+=s.waitingMs,i.toolCalls+=es(s)??0,s.status==="failed"&&i.failed++}for(const[s,o]of n){const i=r.get(s);i&&(i.medianTokens=pw(o),i.medianRuns=o.length)}return[...r.values()].sort((s,o)=>o.computeMs-s.computeMs)}function bw(t){const e={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const r of t.executions.values()){const n=Lm(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.reasoning,e}function ww(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.openNow++;const n=t.now-r.waitingSince;e.totalMs+=n,n>e.longestMs&&(e.longestMs=n)}}return e}function Aw(t){const e={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const r of t.executions.values())e.toolCalls+=es(r)??0,e.toolErrors+=Hc(r),e.retries+=Fc(r),r.status==="failed"?e.failed++:r.outcome==="interrupted"?e.interrupted++:r.outcome==="completed"&&e.completed++;return e}function Sw(t){const e=[];for(const o of t.executions.values())e.push(ta(o,t.now));if(e.length===0)return[];const r=jl(e.map(o=>({...o}))),n=new Date(t.dayStart);n.setMinutes(0,0,0);const s=[];for(let o=n.getTime();o<t.now;o+=36e5){const i=o+36e5;let a=0;for(const l of r){const d=Math.max(l.start,o),m=Math.min(l.end,i);m>d&&(a+=m-d)}let c=0;const u=[];for(const l of e)l.start<i&&l.end>o&&(c++,u.push({start:Math.max(l.start,o),end:Math.min(l.end,i)}));s.push({hour:new Date(o).getHours(),runs:c,computeMs:a,peak:Fm(u).peak})}return s}const Zo=6e4,kw=60*Zo;function xw(t,e){const r=[],n=e.contextSpans,s=e.longestFocus.value,o=Math.max(1,t.now-t.dayStart),i=e.timeInFlight.value/o;let a;if(e.executions.value===0)return{headline:"QUIET",clauses:["No runs observed in this window."]};if(e.peakConcurrency.value>=3?a="PARALLEL":n.length>=6?a="FRAGMENTED":s&&s.end-s.start>2*kw?a="SUSTAINED":i<.15?a="SPARSE":a="SERIAL",e.peakConcurrency.value>=2?r.push(`Up to ${e.peakConcurrency.value} runs in flight at once; ${We(e.timeInFlight.value)} of wall-clock time had a run in flight.`):r.push(`Runs happened one at a time, across ${We(e.timeInFlight.value)} of wall-clock time.`),s&&r.push(`The longest unbroken stretch was ${We(s.end-s.start)} in ${Ce(s.context)}.`),n.length>1){const c=new Set(n.map(u=>u.context)).size;r.push(`Attention moved ${e.contextSwitches.value} ${e.contextSwitches.value===1?"time":"times"} across ${c} ${c===1?"context":"contexts"}.`)}if(e.waitingOnYou.value>Zo&&r.push(`${We(e.waitingOnYou.value)} was spent with a run waiting on your answer.`),e.humanAgentOverlap.value>Zo){const c=Math.round(e.humanAgentOverlap.value/Math.max(1,e.timeInFlight.value)*100);r.push(`About ${c}% of that time overlapped a window when you were present; no presence was observed in the rest.`)}else e.timeInFlight.value>5*Zo&&r.push("Runs were in flight almost entirely outside the moments you were observably present.");if(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 c=[...e.byMachine.values()].sort((u,l)=>l.computeTime-u.computeTime).map(u=>`${t.machines.get(u.machineId)?.name??u.machineId} ${We(u.computeTime)}`);r.push(`Compute was split across ${c.join(", ")}.`)}return{headline:a,clauses:r}}const Nf="(no model)";function Ew(t){if(t.medianTokens===void 0)return{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 ${Qe(t.medianTokens)}`,title:"One eligible run, so this is that run's figure, not a median. Same window as the rest of TODAY.",absent:!1};const e=t.medianRuns===t.runs?`${t.runs}`:`${t.medianRuns} of ${t.runs}`;return{text:`median ${Qe(t.medianTokens)} over ${e} runs`,title:`Median billed tokens per run, over the runs in this group 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. Runs whose source persists no accounting are excluded: absence is not zero. Same window as the rest of TODAY.`,absent:!1}}function Iw(t,e,r){if(r&&r.runs>0&&r.reported===0)return at("WAITING ON YOU","—",void 0,{note:"not reported by today's sources"});const n=e.count>0?`${e.count} ${e.count===1?"block":"blocks"} · longest ${We(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 at("WAITING ON YOU",We(t.value),t,{tone:t.value>0?"waiting":void 0,note:[n,s].filter(Boolean).join(" · ")||void 0})}function at(t,e,r,n={}){const s=r?.basis==="inferred";return{key:t,value:e,inferred:s,assumption:s?r?.assumption:void 0,...n}}function pc(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?` · ${Qe(s.tokens)} tok`:""} · ${We(s.computeMs)}`,failed:s.failed,fraction:n>0?s.computeMs/n:0,median:r?Ew(s):void 0}))}function Cw(t,e){const r=mw(t),n=xw(t,r),s=bw(t),o=ww(t),i=Aw(t),a=Sw(t),c=fc(t,(k,T)=>T?.context),u=fc(t,k=>k.model??Nf),l=fc(t,k=>k.machineId),d=[...t.executions.values()],m=d.filter(k=>ur(k.measures)===void 0).length,p=d.filter(k=>k.depth>0).length,y=r.longestFocus.value,v=Math.round(r.humanAgentOverlap.value/Math.max(1,r.timeInFlight.value)*100),g=[at("REQUESTS",Qe(r.requests.value),r.requests),at("RUNS",String(r.executions.value),r.executions,{note:p>0?`${p} of them sub-agents`:void 0}),at("SESSIONS",String(r.sessions.value),r.sessions),at("TOKENS",Qe(r.tokens.value),r.tokens,{note:`${Math.round(s.cacheRead/Math.max(1,s.total)*100)}% cache reads`+(m>0?` · ${m} ${m===1?"run reports":"runs report"} no accounting`:"")}),at("TOOL CALLS",Qe(i.toolCalls),r.toolCalls,{note:i.toolErrors>0?`${i.toolErrors} failed`:void 0}),at("TIME IN FLIGHT",We(r.timeInFlight.value),r.timeInFlight),at("HUMAN + AGENT OVERLAP",We(r.humanAgentOverlap.value),r.humanAgentOverlap,{note:`${v}% of time in flight`}),at("PEAK CONCURRENCY",r.peakConcurrency.value>0?`${r.peakConcurrency.value} · ${Po(r.peakConcurrencyAt.value)}`:"0",r.peakConcurrency),at("CONTEXT SWITCHES",String(r.contextSwitches.value),r.contextSwitches,{note:`across ${c.length} ${c.length===1?"context":"contexts"}`}),at("LONGEST FOCUS",y?We(y.end-y.start):"—",r.longestFocus,{note:y?`${Ce(y.context)} · ${Po(y.start)}–${Po(y.end)}`:void 0}),Iw(r.waitingOnYou,o,e),at("FAILED",String(i.failed),void 0,{tone:i.failed>0?"failed":void 0,note:i.interrupted>0||i.retries>0?`${i.interrupted} stopped · ${i.retries} retries`:void 0})],C=a.length>0?a.reduce((k,T)=>T.computeMs>k.computeMs?T:k,a[0]):void 0,A=k=>`${String(k).padStart(2,"0")}:00`,I=[{title:"WHERE THE TIME WENT",rows:pc(c,Ce,!1)}];l.length>0&&I.push({title:"BY MACHINE",rows:pc(l,k=>t.machines.get(k)?.name??k,!1)}),u.length>0&&I.push({title:"BY MODEL",rows:pc(u,k=>k===Nf?"model not observed":k,!0)});const B=k=>k/Math.max(1,s.total);return{headline:n.headline,clauses:[...n.clauses],measures:g,hours:a.map(k=>({hour:k.hour,computeMs:k.computeMs,runs:k.runs,peak:k.peak})),busiest:C?`busiest ${A(C.hour)} · ${We(C.computeMs)} of that hour`:void 0,groups:I,tokens:[["CACHE READS",s.cacheRead],["INPUT",s.input],["OUTPUT",s.output],["REASONING",s.reasoning]].map(([k,T])=>({key:k,value:Qe(T),percent:Math.round(B(T)*100),fraction:B(T)})),tokensNote:"Cache reads are context replayed into each request, not work generated. They dominate the total, which is why the headline token figure is much larger than it feels.",failures:d.filter(k=>k.status==="failed").sort((k,T)=>T.startedAt-k.startedAt).slice(0,12).map(k=>({id:k.id,at:Po(k.startedAt),label:k.label,reason:k.failure?`${k.failure.code}: ${k.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."}]}}function Ow(t,e){const r=new Set(e.disturbances.map(o=>o.id)),n=new Set(e.strata.map(o=>o.id)),s=[...t.executions.values()].sort((o,i)=>i.startedAt-o.startedAt).map(o=>{const i=t.sessions.get(o.sessionId);return{id:o.id,startedAt:o.startedAt,label:o.label,depth:o.depth,context:i?.context?Ce(i.context):null,model:o.model??null,status:o.status,stopped:o.outcome==="interrupted",durationMs:(o.endedAt??t.now)-o.startedAt,inferred:o.startBasis==="inferred"||o.endBasis==="inferred",tokens:ur(o.measures)??null,tools:es(o)??null,waitedMs:o.waitingMs,inField:r.has(o.id)?"disturbance":n.has(o.id)?"stratum":null}});return{now:t.now,rows:s}}const Dl={width:80,color:!1,ascii:!1},Nw={dim:"2",bold:"1",yellow:"33","bold-yellow":"1;33"};class Tw{segments=[];length=0;text(e,r){return e.length>0&&(this.segments.push({text:e,role:r}),this.length+=ke(e)),this}at(e,r,n){return this.padTo(e),this.text(r,n)}right(e,r,n){return this.at(e-ke(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 Tw}function ra(t,e){return`${t.map(r=>Bw(r,e.color)).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
+ `)+`
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(`
10
12
  `)}
11
- `}function Bw(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[${Nw[n.role]}m${o}\x1B[0m${" ".repeat(i)}`}).join("")}function ke(t){return[...t].length}function $w(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:ke(s)+1+ke(o)<=e?s+=` ${o}`:(n.push(s),s=o);return(s.length>0||n.length===0)&&n.push(s),n}function $n(t,e,r,n,s,o){const i=Math.max(12,s-Math.max(e,r)),a=$w(n,i),c=[t.at(e,a[0],o)];for(const u of a.slice(1))c.push(_().at(r,u,o));return c}function Yr(t){return t.ascii?{sep:", ",dash:"--",arrow:"->",range:"-"}:{sep:" · ",dash:"—",arrow:"→",range:"–"}}function Bt(t,e){const r=Yr(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 G(t){return t.replace(/-/g," ")}function Ke(t){return t==="observed"?"dim":void 0}function ie(t){return"value"in t?t.value:void 0}function Ue(t,e){return t===1?e:`${e}s`}function Se(t){return Number.isInteger(t)?t.toLocaleString("en-US"):t.toLocaleString("en-US",{minimumFractionDigits:1,maximumFractionDigits:1})}function Nt(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 Pe(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 Km(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 Gm(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 Rn(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:Rw(t,e)}}function Rw(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 zs(t,e){const r=Yr(e),n=Rn(t.from,e.timeZone),s=Rn(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 Wc(t,e,r){const n=Rn(t,r.timeZone);return Rn(e.from,r.timeZone).day===Rn(e.to,r.timeZone).day?n.time:`${n.day} ${n.time}`}function Pl(t,e){const r=Rn(t,e.timeZone);return`${r.day} ${r.time} ${r.zone}`}function na(t,e){const r=_().text("057","dim").text(" ").text("COMPUTATIONAL ACTIVITY","bold");return r.length+2+ke(t)<=e?[r.right(e-1,t,"dim")]:[r,_().right(e-1,t,"dim")]}function Ll(t,e,r,n){const s=zs(t,n),o=_();return e.forEach((i,a)=>{a>0&&Bt(o,n),o.text(i.text,i.role)}),e.length===0?[_().text(s)]:ke(s)+2+o.length<=r?[_().text(s).padTo(r-o.length).append(o)]:[_().text(s),o]}function Ys(t){return t==="observed"?void 0:"yellow"}function qm(t){return t==="within-retention"||t==="retained-indefinitely"?void 0:"yellow"}function dt(t,e){const r=t.match(/^\[(.+)\]$/);if(!r)return{text:t,pseudo:!1};const n=G(r[1]);return{text:e==="model"||e==="executor"?`${e} ${n}`:n,pseudo:!0}}function _w(t,e=Dl){const r=Mw(e.width),{summary:n,availability:s}=t,o=[...na("SUMMARY",r.measure),...Ll(t.period,[{text:G(s.observation),role:Ys(s.observation)},{text:G(s.retention.state),role:qm(s.retention.state)}],r.measure,e),Bt(_().text(String(n.executions),"bold").text(` ${Ue(n.executions,"execution")}`),e).text(String(n.sessions),"bold").text(` ${Ue(n.sessions,"session")}`)];for(const i of jw(t,e)){o.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)o.push(...Dw(c,r,a,e))}return ra(o,e)}function Mw(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 jw(t,e){const{summary:r,availability:n}=t,s=Yr(e).dash,o=(v,g,C,A)=>{const I=ie(g);return I===void 0?{kind:"figure",label:v,figure:s,dash:!0,evidence:g.state}:{kind:"figure",label:v,figure:C(I),dash:!1,tail:A?.(I),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),o("waiting",r.waitingNow,String),i("idle",r.idleNow)]},c=r.terminalExecutionDuration,u=ie(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:Bt(Bt(_().text("median ").text(Pe(u.median),"bold"),e).text("p90 ").text(Pe(u.p90),"bold"),e).text("max ").text(Pe(u.maximum),"bold")},d=r.usageByModel.map(v=>{const g=ie(v.tokens);return{kind:"model",label:v.model,pseudo:!1,executions:v.executions,tokens:g===void 0?s:Nt(g),dash:g===void 0,evidence:v.tokens.state}}),m=r.modelMix.filter(v=>dt(v.key,"model").pseudo);if(m.reduce((v,g)=>v+g.executions,0)===r.executionsWithoutModel)for(const v of m)d.push({kind:"model",label:dt(v.key,"model").text,pseudo:!0,executions:v.executions});else r.executionsWithoutModel>0&&d.push({kind:"model",label:"model not observed",pseudo:!0,executions:r.executionsWithoutModel});const y=[a,{head:"OUTCOMES",rows:[o("completed",r.completed,String),o("failed",r.failed,String),o("interrupted",r.interrupted,String)]},{head:"DURATION",rows:[l,o("terminal interval",r.terminalExecutionIntervalMs,Pe),o("overlapping interval",r.overlappingTerminalIntervalMs,Pe),o("peak concurrency",r.peakTerminalConcurrency,v=>String(v.peak),v=>v.at===null?_():_().text(`at ${Wc(v.at,t.period,e)}`))]},{head:"USAGE",rows:[o("tokens",r.tokens,Nt),o("tool interactions",r.toolInteractions,Nt),o("tool errors",r.toolErrors,Nt),o("explicit waits",r.waits,v=>String(v.count),v=>{const g=_().text("for ").text(Pe(v.durationMs),"bold");return v.openNow>0?Bt(g,e).text(String(v.openNow),"bold").text(" open"):g})]}];return d.length>0&&y.push({head:"BY MODEL",rows:d}),y}function Dw(t,e,r,n){const s=(o,i)=>i===void 0?o:o.at(e.evidenceCol,G(i),Ke(i));switch(t.kind){case"prose":return[_().at(2,t.text)];case"figure":{const o=t.dash?void 0:"bold";if(e.stacked){const c=_().at(4,t.figure,o);return t.tail&&t.tail.length>0&&c.text(" ").append(t.tail),[s(_().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,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(_().at(2,t.label),t.evidence),_().at(4,"").append(t.value)];const o=[],i=_();return t.label.length>e.labelMax?o.push(_().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?` ${Ue(t.executions,"execution")}`:` ${Ue(t.executions,"execution").padEnd(10)}`,a=l=>(l.text(String(t.executions),"bold").text(i),t.tokens===void 0?l:Bt(l,n).text(t.tokens.padStart(r),t.dash?void 0:"bold").text(" tokens"));if(e.split){const l=_().padTo(7-String(t.executions).length);return[s(_().at(2,t.label,o),t.evidence),a(l)]}const c=[],u=_();return t.label.length>e.labelMax?c.push(_().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 Xs={"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 Pw(t,e){const r=Yr(e).dash,n=[],s=[];for(const u of t.dimensions)if(Lw(u)){const l=u.dimension.replace(/ mix$/,"");s.push({head:u.dimension.toUpperCase(),subject:l,a:Tf(u.periodA,l),b:Tf(u.periodB,l),result:G(u.eligibility)})}else{const l=Xs[u.dimension],d=m=>{const p=ie(m);return typeof p!="number"?{value:r,dash:!0,evidence:m.state}:{value:l?.duration?Gm(p):Se(p),dash:!1,evidence:m.state}};n.push({label:l?.label??u.dimension,a:d(u.periodA),b:d(u.periodB),result:G(u.eligibility)})}const o=Vw(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=[...na("COMPARISON",a)];return c.push(...Bf("A",t.periodA,t.availabilityA.observation,a,e)),c.push(...Bf("B",t.periodB,t.availabilityB.observation,a,e)),c.push(_(),...Uw(t,a)),c.push(_()),i==="wide"?c.push(...Hw(n,s,o,r)):i==="paired"?c.push(...Fw(n,s)):c.push(...Ww(n,s)),ra(c,e)}function Lw(t){const e=ie(t.periodA)??ie(t.periodB);return t.dimension.endsWith(" mix")||e!==void 0&&typeof e=="object"}function Tf(t,e){const r=ie(t);return r===void 0||typeof r=="number"?{evidence:t.state}:{evidence:t.state,items:Object.entries(r).map(([n,s])=>{const o=dt(n,e);return{key:o.text,pseudo:o.pseudo,count:s}})}}function Bf(t,e,r,n,s){const o=zs(e,s),i=G(r),a=Math.max(46,3+ke(o)+3),c=_().text(t,"bold").at(3,o);return a+ke(i)<=n?[c.at(a,i,Ys(r))]:[c,_().at(3,i,Ys(r))]}function Uw(t,e){const r=[_().text(G(t.eligibility).toUpperCase(),t.eligibility==="comparable"?"bold":"bold-yellow")];for(const s of t.reasons){const o=s.match(/^period ([AB]): (.*)$/);o?r.push(...$n(_().at(2,o[1],"dim"),5,5,o[2],e)):r.push(...$n(_(),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(Xs[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(...$n(_(),2,2,`${i}: ${s}.`,e))}return r}function Vw(t,e){const r=p=>e.flatMap(y=>y[p].items?.map(v=>Se(v.count))??[]),n=(p,y)=>Math.max(y,...p.map(ke)),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=>[G(p.a.evidence),G(p.b.evidence)]),...e.flatMap(p=>[G(p.a.evidence),G(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 mi(t){return t.dash?void 0:"bold"}function Kc(t,e,r,n){return ke(t)>e?{lead:[_().at(r,t,n)],row:_()}:{lead:[],row:_().at(r,t,n)}}function Hw(t,e,r,n){const s=[_().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}=Kc(o.label,25,2);s.push(...i,a.right(r.aEnd,o.a.value,mi(o.a)).at(r.aEvidence,G(o.a.evidence),Ke(o.a.evidence)).right(r.bEnd,o.b.value,mi(o.b)).at(r.bEvidence,G(o.b.evidence),Ke(o.b.evidence)).at(r.result,o.result))}for(const o of e){s.push(_(),_().text(o.head,"dim").at(r.aEvidence,G(o.a.evidence),Ke(o.a.evidence)).at(r.bEvidence,G(o.b.evidence),Ke(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}=Kc(a,25,2,c.pseudo?"dim":void 0);o.a.items&&l.right(r.aEnd,c.a===void 0?n:Se(c.a),c.a===void 0?void 0:"bold"),o.b.items&&l.right(r.bEnd,c.b===void 0?n:Se(c.b),c.b===void 0?void 0:"bold"),s.push(...u,l)}}return s}function Fw(t,e){const r=[_().text("MEASURES","dim").right(78,"COMPARISON","dim")],n=(s,o,i,a)=>s.at(i,o,"dim").right(i+15,a.value,mi(a)).at(i+18,G(a.evidence),Ke(a.evidence));for(const s of t)r.push(_().at(2,s.label).right(78,s.result)),r.push(n(n(_(),"A",4,s.a),"B",40,s.b));for(const s of e)r.push(_(),_().text(s.head,"dim").right(78,s.result)),r.push(...zm(s,29));return r}function Ww(t,e){const r=[_().text("MEASURES","dim")],n=(s,o)=>_().at(4,s,"dim").right(28,o.value,mi(o)).at(31,G(o.evidence),Ke(o.evidence));t.forEach((s,o)=>{o>0&&r.push(_()),r.push(_().at(2,s.label),n("A",s.a),n("B",s.b),_().at(4,"comparison","dim").at(16,s.result))});for(const s of e)r.push(_(),_().text(s.head,"dim"),...zm(s,28)),r.push(_().at(2,"comparison","dim").at(16,s.result));return r}function zm(t,e){const r=[];for(const[n,s]of[["A",t.a],["B",t.b]]){r.push(_().at(2,n,"dim").at(5,G(s.evidence),Ke(s.evidence)));for(const o of s.items??[]){const{lead:i,row:a}=Kc(o.key,e-5-1-ke(Se(o.count)),5,o.pseudo?"dim":void 0);r.push(...i,a.right(e,Se(o.count),"bold"))}}return r}const Kw=["summary","availability","compare","breakdown"];function qt(t,e,r=Dl){switch(t.operation){case"summary":return _w(t.result,r);case"availability":return Gw(t.result,r);case"compare":return Pw(t.result,r);case"breakdown":return qw(t.result,e,r)}}const Ym={"tool-interactions":"tool interactions","tool-errors":"tool errors"};function Gw(t,e){const r=e.width>=80,n=e.width<56,s=r?79:Math.max(1,e.width-1),o=25,i=[...na("AVAILABILITY",s),...Ll(t.period,[],s,e)],a=(m,p)=>n?[_().at(2,m),_().padTo(4).append(p)]:[_().at(2,m).padTo(o).append(p)],c=(m,p)=>_().text(m,p),u=m=>i.push(_(),_().text(m,"dim"));u("OBSERVATION"),i.push(...a("state",c(G(t.observation),Ys(t.observation))),...a("records",Bt(_().text(String(t.executionRecords),"bold").text(` ${Ue(t.executionRecords,"execution")}`),e).text(String(t.sessionRecords),"bold").text(` ${Ue(t.sessionRecords,"session")}`)),...a("continuity",c(G(t.continuity.state),Ke(t.continuity.state))),...a("observation gaps",c(G(t.observationGaps.state),Ke(t.observationGaps.state))),...a("unprojected work",c(G(t.unprojectedSourceWork.state),Ke(t.unprojectedSourceWork.state)))),u("RETENTION"),i.push(...a("state",c(G(t.retention.state),qm(t.retention.state)))),t.retention.semanticFrom!==null&&i.push(...a("semantic history from",c(Pl(t.retention.semanticFrom,e),"bold")));const l=t.bounds;if(s>=51)i.push(_(),_().text("BOUNDS","dim").right(32,"observed","dim").right(42,"inferred","dim").right(50,"open","dim"),_().at(2,"starts").right(32,String(l.observedStarts),"bold").right(42,String(l.inferredStarts),"bold"),_().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 y=_().padTo(4);return p.forEach(([v,g],C)=>{C>0&&Bt(y,e),y.text(String(v),"bold").text(` ${g}`)}),y};u("BOUNDS"),i.push(_().at(2,"starts"),m([[l.observedStarts,"observed"],[l.inferredStarts,"inferred"]]),_().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(G(t.comparisonReadiness),d))),t.reasons.forEach((m,p)=>{const y=p===0?"because":"";n?(y&&i.push(_().at(2,y)),i.push(...$n(_(),4,4,m,s))):i.push(...$n(_().at(2,y),o,o,m,s))}),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(o,"state","dim").right(s-1,"records","dim"));for(const m of t.measures){const p=Ym[m.dimension]??G(m.dimension),y=G(m.state),v=_().text("/","dim").text(" ").text(String(m.coverage.records),"bold");if(r){const g=_().at(2,p).at(21,y,Ke(m.state));i.push(...$f(g,35,78,m.coverage,v,e))}else i.push(_().at(2,p).at(o,y,Ke(m.state))),i.push(...$f(_(),4,s-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),y=`execution ${Ue(m.executionRecords,"record")}`;if(29+ke(y)>s){i.push(_().at(2,m.source),_().at(4,p,"bold").text(` ${y}`));continue}const v=g=>g.right(27,p,"bold").at(29,y);ke(m.source)>22?i.push(_().at(2,m.source),v(_())):i.push(v(_().at(2,m.source)))}return ra(i,e)}function $f(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])=>_().text(String(m),"bold").text(" ").text(G(p),Ke(p))),c=Yr(o).sep,u=r-s.length,l=[[]];let d=e;for(const m of a){const p=l[l.length-1],y=d+(p.length>0?c.length:0)+m.length;p.length>0&&y>u?(l.push([m]),d=e+m.length):(p.push(m),d=y)}return l.map((m,p)=>{const y=p===0?t.padTo(e):_().padTo(e);if(m.forEach((v,g)=>{g>0&&Bt(y,o),y.append(v)}),p<l.length-1){const v=c.trim();return y.text(c.slice(0,c.indexOf(v))).text(v,"dim"),y}return y.padTo(r-s.length+1).append(s)})}function qw(t,e,r){const n=Yr(r).dash,s=l=>{const d=ie(l);return d===void 0?{value:n,dash:!0,evidence:l.state}:{value:Se(d),dash:!1,evidence:l.state}},o=t.items.filter(l=>e===void 0||l.key===e).map(l=>{const d=dt(l.key,t.dimension),m=ie(l.terminalDuration);return{key:d.text,pseudo:d.pseudo,executions:Se(l.executions),singular:l.executions===1,terminal:Se(l.terminalExecutions),median:m===void 0?n:Km(m.median),medianDash:m===void 0,tokens:s(l.tokens),tools:s(l.toolInteractions),errors:s(l.toolErrors),failed:s(l.failed)}}),i=zw(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=[...na(`BREAKDOWN${Yr(r).sep}${G(t.dimension).toUpperCase()}`,c),...Ll(t.period,[{text:G(t.availability.observation),role:Ys(t.availability.observation)}],c,r),_()];if(o.length===0)u.push(_().text("none observed"));else if(a==="table")u.push(...i.lines);else{const l=a==="records"?Yw(o):null;o.forEach((d,m)=>{m>0&&u.push(_()),u.push(...l?Xw(d,l,r):Jw(d,o,r))})}return u.push(_(),...$n(_(),0,0,t.qualification,c,"dim")),ra(u,r)}function yi(t){return t.pseudo?"dim":"bold"}function gi(t,e,r){return r.evidence===void 0?t:t.at(e,G(r.evidence),Ke(r.evidence))}function zw(t,e){const r=G(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(ke));let i=Math.max(ke(r),o(t.map(m=>m.key))),a=ke(r)-1;const c=n.map(m=>{const p=i+2+Math.max(ke(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 y=i+2+o(p.map(v=>v.value))-1;return y=Math.max(y,a+2+ke(m.caption)),i=y+3+o(p.map(v=>G(v.evidence??""))),a=y,y}),l=_().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=_().text(m.key,yi(m));n.forEach((y,v)=>p.right(c[v],y.value(m),"bold")),s.forEach((y,v)=>{const g=y.value(m);gi(p.right(u[v],g.value,g.dash?void 0:"bold"),u[v]+3,g)}),d.push(p)}return{measure:i,lines:d}}function Xm(t){const e=r=>Math.max(3,...t.map(n=>ke(r(n))));return{countWidth:e(r=>r.executions),terminalWidth:e(r=>r.terminal),medianWidth:e(r=>r.median)}}function Yw(t){const e=s=>Math.max(1,...t.flatMap(o=>s(o).map(i=>ke(i.value)))),r=Math.max(24,10+e(s=>[s.tokens,s.errors])-1),n=Math.max(44,r+3+12+2);return{...Xm(t),countEnd:34,leftEnd:r,rightLabel:n,rightEnd:Math.max(61,n+6+2+e(s=>[s.tools,s.failed])-1)}}function Jm(t,e,r,n){return t.text(e.executions.padStart(r.countWidth),"bold").text(` ${(e.singular?"execution":"executions").padEnd(10)}`),Bt(t,n).text(e.terminal.padStart(r.terminalWidth),"bold").text(" terminal"),Bt(t,n).text("median "),t.text(e.median.padStart(r.medianWidth),e.medianDash?void 0:"bold")}function Xw(t,e,r){const n=[],s=e.countEnd-e.countWidth+1,o=_();ke(t.key)>=s?n.push(_().text(t.key,yi(t))):o.text(t.key,yi(t)),n.push(Jm(o.padTo(s),t,e,r));const i=(a,c,u,l)=>{const d=_().at(2,a);return gi(d.right(e.leftEnd,c.value,c.dash?void 0:"bold"),e.leftEnd+3,c),d.at(e.rightLabel,u),gi(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 Jw(t,e,r){const n=Math.max(1,...e.flatMap(i=>[i.tokens,i.tools,i.errors,i.failed].map(a=>ke(a.value)))),s=Math.max(24,10+n-1),o=(i,a)=>gi(_().at(2,i).right(s,a.value,a.dash?void 0:"bold"),s+3,a);return[_().text(t.key,yi(t)),Jm(_().padTo(2),t,Xm(e),r),o("tokens",t.tokens),o("tools",t.tools),o("errors",t.errors),o("failed",t.failed)]}const Rf=["summary","availability","compare","breakdown"],_f=["lifecycle","duration","tokens","waits","errors"],Mf=["model","executor"],jf=["today","last-7d"];function Zw(t){const e=Rf.find(a=>a===t.query),r=jf.find(a=>a===(t.scope??"today"));if(!e)return{error:`query must be one of ${Rf.join(", ")}`};if(!r)return{error:`scope must be one of ${jf.join(", ")}`};const n=t.focus?_f.find(a=>a===t.focus):void 0,s=t.by?Mf.find(a=>a===t.by):void 0;if(t.focus&&!n)return{error:`focus must be one of ${_f.join(", ")}`};if(t.by&&!s)return{error:`by must be one of ${Mf.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 Qw(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 eA(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function tA(t,e,r,n={}){const s=Qw(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,eA(s));break}return rA(e,o,n)}function rA(t,e,r={}){const n={...Dl,timeZone:r.timeZone};switch(t.query){case"summary":{const s=Lr(e.summary,"summary");return t.focus==="duration"?oA(t,s,r,n):t.focus==="lifecycle"?sA(t,s,r,n):nA(t,s,r,n)}case"availability":{const s=Lr(e.availability,"availability");return t.focus==="tokens"?aA(t,Lr(e.summary,"summary"),r,n):t.focus==="waits"?cA(t,Lr(e.summary,"summary"),r,n):iA(t,s,r,n)}case"breakdown":{const s=Lr(e.breakdown,"breakdown");return t.focus==="errors"?lA(t,s,Lr(e.summary,"summary"),r,n):uA(t,s,r,n)}case"compare":return dA(t,Lr(e.comparison,"comparison"),n)}}function nA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"SUMMARY",o,!0,r,n),a=qt({operation:"summary",result:e},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=[Zm(e)],u=ie(s.completed),l=ie(s.failed);u!==void 0&&l!==void 0&&c.push(`${u} completed and ${l} failed${iy([s.completed,s.failed])}.`);const d=Xr(o,"waits");d&&Ln(d.coverage,"unsupported")&&c.push(`Waits are unsupported for all ${s.executions}.`);const m=[...i.observation,Ul(o)],p=yA(o);return p&&m.push(p),m.push({k:"ENDS",v:ny(o)}),{...i,finding:c.join(" "),observation:m,evidence:[...Qm(e,"lifecycle",t),je("completed",s.completed,String,Ae(t,"summary","lifecycle")),je("failed",s.failed,String,Ae(t,"summary","lifecycle")),je("interrupted",s.interrupted,String,Ae(t,"summary","lifecycle")),je("terminal interval",s.terminalExecutionIntervalMs,Pe,Ae(t,"summary","duration")),je("overlapping interval",s.overlappingTerminalIntervalMs,Pe,Ae(t,"summary","duration")),je("tokens",s.tokens,Nt,Ae(t,"availability","tokens")),je("tool interactions",s.toolInteractions,Nt,Ae(t,"breakdown","errors")),je("tool errors",s.toolErrors,Nt,Ae(t,"breakdown","errors")),ey(e,Ae(t,"availability","waits"))],command:zt("summary",t.scope),text:a}}function sA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"SUMMARY · LIFECYCLE",o,!0,r,n),a=qt({operation:"summary",result:e},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=[Zm(e)],u=[s.completed,s.failed,s.interrupted],[l,d,m]=u.map(C=>ie(C));l!==void 0&&d!==void 0&&m!==void 0&&c.push(`${l} completed, ${d} failed and ${m} interrupted${iy(u)}.`),Ln(s.waitingNow.coverage,"unsupported")&&c.push(`Waiting is unsupported for all ${s.executions}.`);const p=Xr(o,"outcomes"),y=[...i.observation];p&&y.push({k:"OUTCOMES",v:Js(p.state,p.coverage)}),y.push({k:"ENDS",v:ny(o)});const v=s.terminalExecutionDuration,g=ie(v);return{...i,finding:c.join(" "),observation:y,evidence:[...Qm(e,void 0,t),je("completed",s.completed,String),je("failed",s.failed,String),je("interrupted",s.interrupted,String),{k:"terminal execution",...g?{t:oy(g)}:{},v:g?"":"—",e:G(v.state),focus:Ae(t,"summary","duration")}],command:zt("summary",t.scope),text:a}}function oA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"SUMMARY · DURATION",o,!0,r,n),a=qt({operation:"summary",result:e},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=ie(s.terminalExecutionIntervalMs),u=ie(s.overlappingTerminalIntervalMs),l=ie(s.peakTerminalConcurrency),d=[];c!==void 0&&u!==void 0&&c>0?(d.push(u===0?"Sequential.":u*2<c?"Mostly sequential.":"Mostly overlapping."),d.push(`Two or more executions were in flight for ${Pe(u)} of the ${Pe(c)} covered by terminal executions.`),l&&l.at!==null&&d.push(`The peak was ${l.peak}, at ${Wc(l.at,e.period,n)}.`)):d.push("No terminal execution covers any of this period, so there is no interval to divide.");const m=[...i.observation];o.bounds.openEnds>0&&m.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"&&m.push({k:"CONTINUITY",v:`${G(o.continuity.state)} — time 057 did not observe is in neither figure`});const p=s.terminalExecutionDuration,y=ie(p);return{...i,finding:d.join(" "),observation:m,evidence:[je("terminal interval",s.terminalExecutionIntervalMs,Pe),je("overlapping interval",s.overlappingTerminalIntervalMs,Pe),{...je("peak concurrency",s.peakTerminalConcurrency,v=>String(v.peak)),...l&&l.at!==null?{t:`at ${Wc(l.at,e.period,n)}`}:{}},{k:"terminal execution",...y?{t:oy(y)}:{},v:y?"":"—",e:G(p.state)},{k:"executions",v:String(s.executions),e:"",focus:Ae(t,"summary","lifecycle")},{k:"sessions",v:String(s.sessions),e:"",focus:Ae(t,"summary","lifecycle")}],command:zt("summary",t.scope),text:a}}function Zm(t){const{summary:e}=t,r=ie(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} ${Ue(e.executions,"execution")} across ${e.sessions} ${Ue(e.sessions,"session")}`;return n.length>0?`${s}; ${Un(n)}.`:`${s}.`}function Qm(t,e,r){const{summary:n}=t,s=e?Ae(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),je("waiting",n.waitingNow,String,s),o("idle",n.idleNow)]}function ey(t,e){const r=t.summary.waits,n=ie(r);return{k:"explicit waits",...n?{t:`for ${Pe(n.durationMs)}${n.openNow>0?` · ${n.openNow} open`:""}`}:{},v:n?String(n.count):"—",e:G(r.state),...e?{focus:e}:{}}}function iA(t,e,r,n){const s=Mr(t,"AVAILABILITY",e,!1,r,n),o=qt({operation:"availability",result:e},void 0,n),i=e.executionRecords;if(yr(e))return jr(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=Un(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=>Ln(p.coverage,"unsupported"));if(d.length>0){const p=Un(d.map(y=>hc(y.dimension)));a.push(`${p[0].toUpperCase()}${p.slice(1)} ${d.length===1?"is":"are"} unsupported for all ${i}.`)}const m=[...e.measures].filter(p=>!Ln(p.coverage,"unsupported")&&p.coverage.notObserved>0).sort((p,y)=>y.coverage.notObserved-p.coverage.notObserved)[0];m&&a.push(`The ${hc(m.dimension)} is not observed for ${m.coverage.notObserved} of ${i}.`)}const u=[...s.observation,{k:"RETENTION",v:sy(e,n)},{k:"COMPARISON",v:G(e.comparisonReadiness)}],l=[{k:"continuity",v:G(e.continuity.state),e:""},{k:"observation gaps",v:G(e.observationGaps.state),e:""},{k:"unprojected work",v:G(e.unprojectedSourceWork.state),e:""},{k:"execution records",v:String(i),e:""},...e.measures.map(d=>{const m=pA(t,d.dimension);return{k:hc(d.dimension),...d.coverage.records>0?{t:ry(d.coverage)}:{},v:"",e:G(d.state),...m?{focus:m}:{}}})];return{...s,finding:a.join(" ")||void 0,observation:u,evidenceCaption:"COVERAGE",evidence:l,command:zt("availability",t.scope),text:o}}function aA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"AVAILABILITY · TOKENS",o,!1,r,n),a=qt({operation:"availability",result:o},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=Xr(o,"tokens"),u=Xr(o,"model"),l=ie(s.tokens),d=[];if(l!==void 0&&c){const p=c.coverage,y=[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);d.push(y.length===0?`${Nt(l)} is fully observed for all ${p.records} executions.`:`${Nt(l)} is fully observed for ${p.observed} of ${p.records} executions; ${Un(y)}.`)}else d.push(`Tokens are ${G(s.tokens.state)} for this period.`);s.executionsWithoutModel>0&&d.push(`${s.executionsWithoutModel} ${Ue(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:Js(c.state,c.coverage)}),u&&m.push({k:"MODEL",v:Js(u.state,u.coverage)}),m.push(Ul(o)),{...i,finding:d.join(" "),observation:m,evidence:[je("tokens",s.tokens,Nt),...fA(e)],command:zt("availability",t.scope),text:a}}function cA(t,e,r,n){const{summary:s,availability:o}=e,i=Mr(t,"AVAILABILITY · WAITS",o,!1,r,n),a=qt({operation:"availability",result:o},void 0,n);if(s.executions===0||yr(o))return jr(i,o,a,n);const c=Xr(o,"waits"),u=s.executions,l=ie(s.waits);let d,m;const p=c&&(Ln(c.coverage,"unsupported")||Ln(c.coverage,"notObserved"));!l||p?(d="NOT OBSERVED",m=`Wait behaviour is ${G(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 ${Ue(l.count,"wait")} for ${Pe(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 y=[...i.observation];return c&&y.push({k:"WAITS",v:Js(c.state,c.coverage)}),y.push({k:"SOURCES",v:o.sources.map(v=>`${v.source} ${v.executionRecords}`).join(" · ")}),{...i,...d?{verdict:d}:{},finding:m,observation:y,evidence:[ey(e),{...je("waiting",s.waitingNow,String),t:"recorded lifecycle"},{k:"executions",v:String(u),e:""}],command:zt("availability",t.scope),text:a}}function uA(t,e,r,n){const s=t.by??"model",o=Mr(t,`BREAKDOWN · ${s.toUpperCase()}`,e.availability,!1,r,n),i=qt({operation:"breakdown",result:e},void 0,n),a=e.availability.executionRecords;if(a===0||yr(e.availability))return jr(o,e.availability,i,n);const c=e.items.filter(p=>!dt(p.key,s).pseudo),u=e.items.filter(p=>dt(p.key,s).pseudo),l=[];if(s==="executor")l.push(`${Un(c.map(p=>`${p.key} ${p.executions}`))} execution ${Ue(c.reduce((p,y)=>p+y.executions,0),"record")}.`);else if(c[0]){const p=c[0],y=ie(p.tokens);l.push(`${p.key} accounts for ${p.executions} of ${a} executions${y!==void 0?` and ${Se(y)} tokens`:""}.`)}for(const p of u)l.push(`${p.executions} ${Ue(p.executions,"execution")} ${p.executions===1?"carries":"carry"} ${gA(p.key,s)}.`);const d=Xr(e.availability,s),m=[...o.observation];return d&&m.push({k:s.toUpperCase(),v:Js(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 y=ie(p.terminalDuration),v=ie(p.tokens);return{k:dt(p.key,s).text,t:`${Se(p.executions)} ${Ue(p.executions,"execution")}${y?` · median ${Km(y.median)}`:""}`,v:v===void 0?"—":Se(v),e:G(p.tokens.state)}}),command:zt("breakdown",t.scope,s),text:i}}function lA(t,e,r,n,s){const o=Mr(t,"BREAKDOWN · MODEL · ERRORS",e.availability,!1,n,s),i=qt({operation:"breakdown",result:e},void 0,s);if(e.availability.executionRecords===0||yr(e.availability))return jr(o,e.availability,i,s);const a=[...e.items].sort((v,g)=>(ie(g.toolErrors)??-1)-(ie(v.toolErrors)??-1)||g.executions-v.executions),c=ie(r.summary.toolErrors),u=a.filter(v=>!dt(v.key,"model").pseudo&&ie(v.toolErrors)!==void 0),l=[],d=v=>{const g=ie(v.toolInteractions);return g===void 0?"":`, across ${Se(g)} tool interactions`};if(c===void 0)l.push(`Tool errors are ${G(r.summary.toolErrors.state)} for this period.`);else if(c===0)l.push("No tool errors were recorded.");else if(u[0]){const[v,g]=u,C=ie(v.toolErrors)??0;if(l.push(C*2>c?`Tool errors are concentrated in ${v.key}: ${Se(C)} of ${Se(c)} recorded errors${d(v)}.`:`Tool errors are spread across models: ${v.key} recorded ${Se(C)} of ${Se(c)}${d(v)}.`),g){const A=ie(g.toolInteractions);l.push(`${g.key} recorded ${Se(ie(g.toolErrors)??0)}${A===void 0?"":` across ${Se(A)}`}.`)}}const m=[...o.observation],p=e.items.filter(v=>v.toolErrors.state==="unsupported").map(v=>dt(v.key,"model").text);p.length>0&&m.push({k:"ERRORS",v:`unsupported for ${Un(p)}`}),m.push({k:"CAUSALITY",v:"grouped records; not a causal performance difference"});const y=(v,g)=>{const C=ie(v),A=ie(g);return`${C===void 0?"—":Se(C)} / ${A===void 0?"—":Se(A)}`};return{...o,finding:l.join(" "),observation:m,evidenceCaption:"ERRORS / TOOLS",evidence:[{k:"all executions",v:y(r.summary.toolErrors,r.summary.toolInteractions),e:G(r.summary.toolErrors.state)},...a.map(v=>({k:dt(v.key,"model").text,v:y(v.toolErrors,v.toolInteractions),e:G(v.toolErrors.state)}))],command:zt("breakdown",t.scope,"model"),text:i}}function dA(t,e,r){const n=[{k:"A",w:zs(e.periodA,r),s:G(e.availabilityA.observation)},{k:"B",w:zs(e.periodB,r),s:G(e.availabilityB.observation)}],s=[...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}))],o=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(d=>d.eligibility===l).length,G(l)]).filter(([l])=>l>0).map(([l,d])=>`${l} ${d}`).join(" · ")}],u=(l,d)=>{const m=ie(d);return typeof m!="number"?"—":Xs[l]?.duration?Gm(m):Se(m)};return{request:t,title:ty(t.scope),resolution:`COMPARISON · AGAINST PREVIOUS${t.scope==="last-7d"?" 7D":""}`,periods:n,partial:e.availabilityA.observation!=="observed"||e.availabilityB.observation!=="observed",verdict:G(e.eligibility).toUpperCase(),reasons:s,observation:c,evidenceCaption:"A · B",evidence:o.map(l=>{const d=hA(t,l.dimension);return{k:Xs[l.dimension]?.label??l.dimension,t:`B ${u(l.dimension,l.periodB)} ${G(l.periodB.state)}`,v:u(l.dimension,l.periodA),e:G(l.periodA.state),...d?{focus:d}:{}}}),command:zt("compare",t.scope),text:qt({operation:"compare",result:e},void 0,r)}}function Mr(t,e,r,n,s,o){const i=[G(r.observation),...n?[G(r.retention.state)]:[]].join(" · "),a=[],c=ty(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:zs(r.period,o),qualification:i,partial:r.observation!=="observed",reasons:[],observation:a}}function jr(t,e,r,n){const s=t.request,o=zt(s.query,s.scope,s.by);if(yr(e)){const i=e.retention.semanticFrom;return{...t,verdict:"OUTSIDE RETENTION",finding:i===null?"This period precedes semantic history.":`Semantic history starts at ${Pl(i,n)}; this period precedes it.`,observation:[...t.observation,{k:"RETENTION",v:sy(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,Ul(e)],evidence:[{k:"execution records",v:"0",e:""}],command:o,text:r}}function fA(t){const{summary:e}=t,r=e.usageByModel.map(s=>{const o=ie(s.tokens);return{k:s.model,t:`${s.executions} ${Ue(s.executions,"execution")}`,v:o===void 0?"—":Nt(o),e:G(s.tokens.state)}}),n=e.modelMix.filter(s=>dt(s.key,"model").pseudo);if(n.reduce((s,o)=>s+o.executions,0)===e.executionsWithoutModel)for(const s of n)r.push({k:dt(s.key,"model").text,t:`${s.executions} ${Ue(s.executions,"execution")}`,v:"",e:""});else e.executionsWithoutModel>0&&r.push({k:"model not observed",t:`${e.executionsWithoutModel} ${Ue(e.executionsWithoutModel,"execution")}`,v:"",e:""});return r}function je(t,e,r,n){const s=ie(e);return{k:t,v:s===void 0?"—":r(s),e:G(e.state),...n?{focus:n}:{}}}function Ae(t,e,r){const n=e==="breakdown"?{query:e,scope:t.scope,focus:r,by:"model"}:{query:e,scope:t.scope,focus:r};return mA(n,t)?void 0:n}function pA(t,e){switch(e){case"tokens":return Ae(t,"availability","tokens");case"waits":return Ae(t,"availability","waits");case"tool-errors":case"tool-interactions":return Ae(t,"breakdown","errors");case"outcomes":return Ae(t,"summary","lifecycle");case"bounds":return Ae(t,"summary","duration");case"model":return{query:"breakdown",scope:t.scope,by:"model"};case"executor":return{query:"breakdown",scope:t.scope,by:"executor"}}}function hA(t,e){return e==="tokens"?Ae(t,"availability","tokens"):e==="explicit wait count"?Ae(t,"availability","waits"):e==="tool interactions"||e==="tool errors"?Ae(t,"breakdown","errors"):Xs[e]?.duration||e==="peak terminal concurrency"?Ae(t,"summary","duration"):Ae(t,"summary","lifecycle")}function mA(t,e){return t.query===e.query&&t.scope===e.scope&&t.focus===e.focus&&t.by===e.by}function zt(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 ty(t){return t==="last-7d"?"LAST 7D":"TODAY"}function Xr(t,e){return t.measures.find(r=>r.dimension===e)}function hc(t){return Ym[t]??t}function yr(t){return t.retention.state==="outside-retention"}function Ln(t,e){return t.records>0&&t[e]===t.records}function ry(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 Js(t,e){return e.records===0?G(t):`${G(t)} · ${ry(e)} / ${e.records}`}function Ul(t){return{k:"CONTINUITY",v:G(t.continuity.state)}}function yA(t){const e=Xr(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 ny(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 sy(t,e){const r=t.retention.semanticFrom;return`${G(t.retention.state)}${r===null?"":` · from ${Pl(r,e)}`}`}function oy(t){return`median ${Pe(t.median)} · p90 ${Pe(t.p90)} · max ${Pe(t.maximum)}`}function iy(t){const e=new Set(t.map(n=>n.state));if(e.size!==1)return` (${t.map(n=>G(n.state)).join(", ")})`;const[r]=[...e];return r==="observed"?"":`, ${t.length===2?"both":"all"} ${G(r)}`}function gA(t,e){const r=dt(t,e).text.replace(`${e} `,"");return r==="not observed"?`no observed ${e}`:`a ${e} that is ${r}`}function Un(t){return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`}function Lr(t,e){if(t===void 0)throw new Error(`the ${e} result is missing`);return t}const Df=448,vA=384;function bA(){return se(hn(),".057")}function sa(){const t=process.env.O57_STORE;return t&&t.length>0?t===":memory:"||Pc(t)?t:yo(process.cwd(),t):se(bA(),"events.db")}function ay(){const t=process.env.O57_STORE;return typeof t=="string"&&t.length>0}function oa(t){return[t,`${t}-wal`,`${t}-shm`]}function wA(t){return t===":memory:"?[]:[...oa(t),`${t}.display`]}function AA(t){if(t===":memory:")return;const e=ii(t);Dc(e,{recursive:!0,mode:Df}),cy(e,Df)}function Gc(t){if(t===":memory:")return[];const e=[];for(const r of oa(t))if(fe(r)&&!cy(r,vA)){const n=Vl(r);n!==null&&(n&63)!==0&&e.push({path:r,mode:n})}return e}function Vl(t){try{return Qi(t).mode&511}catch{return null}}function cy(t,e){if(process.platform==="win32")return!1;const r=Vl(t);if(r===null)return!1;if((r&~e)===0)return!0;try{return ea(t,e),!0}catch{return!1}}function uy(){if(ay())return null;const t=yo(process.cwd(),".057","events.db");return fe(t)&&t!==sa()?t:null}const qc={processDays:7,eventDays:90},SA=["machine"],Pf=["process"],mc={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},kA=["execution","session","artifact"];function ly(t=process.env){return{processDays:Lf(t.O57_RETAIN_PROCESS_DAYS,qc.processDays),eventDays:Lf(t.O57_RETAIN_DAYS,qc.eventDays)}}function Lf(t,e){if(t===void 0||t.trim()==="")return e;const r=Number(t);return Number.isFinite(r)&&r>=0?r:e}function ia(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 xA=`-- 057 local store.
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
+
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.
12
16
  --
13
17
  -- \`events\` is the only durable truth. \`claims\` is denormalized out of events so identity
14
18
  -- resolution is one indexed read rather than a scan; it is rebuildable from events at any time.
@@ -44,6 +48,8 @@ CREATE INDEX IF NOT EXISTS events_source ON events(source_id, occurred_at);
44
48
  -- 057 took to start listening. With it, 0.13 s. An index, not a schema change: older builds open a
45
49
  -- store that has it, so user_version stays where it is.
46
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);
47
53
  -- Window hydration needs every declaration, including later annotations, but no observations.
48
54
  -- The general subject index visits a subject's entire history just to reject non-began rows;
49
55
  -- on a long-lived session this delayed the first Display frame by more than 20 seconds.
@@ -64,59 +70,327 @@ CREATE TABLE IF NOT EXISTS claims (
64
70
  CREATE INDEX IF NOT EXISTS claims_key ON claims(key, valid_from, valid_to);
65
71
  CREATE INDEX IF NOT EXISTS claims_window ON claims(valid_to, valid_from);
66
72
  CREATE INDEX IF NOT EXISTS claims_event ON claims(event_id);
67
- `,rr=1;class gt extends Error{constructor(e,r,n){super(e),this.kind=r,this.remedy=n,this.name="StoreError"}kind;remedy}function Qo(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 yc(t,e){const r=e instanceof Error?e.message:String(e);return new gt(`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 EA(t){AA(t);let e;try{e=new go(t)}catch(p){throw Qo(p)?yc(t,p):new gt(`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(),Qo(p)?yc(t,p):new gt(`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>rr)throw e.close(),new gt(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${rr})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{e.exec(xA);const p=new Set(e.prepare("PRAGMA table_info(events)").all().map(y=>String(y.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!==rr&&e.exec(`PRAGMA user_version = ${rr}`)}catch(p){e.close();const y=p instanceof Error?p.message:String(p);throw Qo(p)?yc(t,p):new gt(`store ${t} could not be prepared: ${y}`,"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.")}Gc(t);const n=1e3,s=new Set,o=new Set;let i=null;const a=(p,y)=>{o.add(p),i??=Date.now(),s.size<n&&s.add(y)},c=p=>py(p,a),u=e.prepare(`INSERT OR IGNORE INTO events
73
+ -- Semantic readings need claims sharing their subjects' keys, not every unrelated OS sample.
74
+ CREATE INDEX IF NOT EXISTS claims_subject_window ON claims(subject_type, valid_to, valid_from, key);
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
68
76
  (id, source_id, source_instance, occurred_at, observed_at, clock, kind,
69
77
  subject_type, subject_id, core, attrs, basis, assumption, stratum, provenance)
70
78
  VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),l=e.prepare(`INSERT INTO claims
71
79
  (event_id, key, ns, subject_type, subject_id, source_id, valid_from, valid_to)
72
- VALUES (?,?,?,?,?,?,?,?)`),d=dy(e,c),m={path:t,schemaVersion:rr,append(p){let y=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}y++;for(const A of g.claims??[])l.run(g.id,ub(A),A.ns,g.subject.type,g.subject.id,g.source.id,A.validFrom,A.validTo)}e.exec("COMMIT")}catch(g){throw e.exec("ROLLBACK"),g}return{inserted:y,duplicate:v}},query:d.query,claims:d.claims,stats:d.stats,begansFor:d.begansFor,subjectEvents(p,y){return e.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(p,y).map(c)},latestFor(p){return e.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(p)?.hi??null},sweep(p=qc,y=Date.now()){const v=p.processDays>0?y-p.processDays*864e5:null,g=p.eventDays>0?y-p.eventDays*864e5:null;if(v===null&&g===null)return{...mc};const C=ee=>SA.includes(ee)?null:Pf.includes(ee)?v:g,A=e.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
73
- FROM events GROUP BY subject_type, subject_id`).all().map(ee=>{const he=ee;return{type:String(he.t),id:String(he.i),last:Number(he.last)}}),I=(ee,he)=>`${ee}:${he}`,B=new Set,k=new Map;for(const ee of A){const he=C(ee.type);he===null||ee.last>=he?B.add(I(ee.type,ee.id)):k.set(I(ee.type,ee.id),{type:ee.type,id:ee.id})}if(k.size===0)return{...mc,processBefore:v,otherBefore:g};const T=[...kA],S=e.prepare(`SELECT DISTINCT core FROM events
74
- WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),E=new Set(T);let R=[...B].filter(ee=>E.has(ee.slice(0,ee.indexOf(":"))));const j=new Set(R);let M=0;for(let ee=0;ee<4&&R.length>0;ee++){const he=[];for(const $e of R){const Me=$e.indexOf(":");for(const Qt of S.all($e.slice(0,Me),$e.slice(Me+1))){const pe=ei(Qt.core);if(pe)for(const[Z,yt]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const jo=pe[Z];if(typeof jo!="string")continue;const me=I(yt,jo);k.has(me)&&(k.delete(me),B.add(me),M++,!j.has(me)&&E.has(yt)&&(j.add(me),he.push(me)))}}}R=he}if(k.size===0)return{...mc,retainedByDependents:M,processBefore:v,otherBefore:g};const J=e.prepare(`DELETE FROM claims WHERE event_id IN
75
- (SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),le=e.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let re=0,F=0,W=0;e.exec("BEGIN");try{for(const{type:ee,id:he}of k.values()){W+=Number(J.run(ee,he).changes);const $e=Number(le.run(ee,he).changes);Pf.includes(ee)?re+=$e:F+=$e}e.exec("COMMIT")}catch(ee){throw e.exec("ROLLBACK"),ee}return re+F>0&&m.checkpoint(),{processEvents:re,otherEvents:F,claims:W,subjects:k.size,retainedByDependents:M,processBefore:v,otherBefore:g}},checkpoint(){try{e.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes:()=>fy(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(),Gc(t)},close(){m.checkpoint(),e.close()}};return m}function aa(t){if(t===":memory:"||!fe(t))throw new gt(`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 go(t,{readOnly:!0})}catch(s){throw Uf(t,s)}try{e.exec("PRAGMA query_only = ON"),r=Number(e.prepare("PRAGMA user_version").get().user_version)}catch(s){throw e.close(),Uf(t,s)}if(r!==rr)throw e.close(),r>rr?new gt(`store ${t} was written by a newer 057 (schema ${r}, this build understands ${rr})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified."):new gt(`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=dy(e,s=>py(s));return{path:t,schemaVersion:rr,...n,sizeBytes:()=>fy(t),close(){e.close()}}}function Uf(t,e){const r=e instanceof Error?e.message:String(e);return Qo(e)?new gt(`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 gt(`store ${t} is not a readable database: ${r}`,"unreadable","The store was not modified. Check that O57_STORE names a 057 store.")}function dy(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 key, ns, subject_type, subject_id, source_id, valid_from, valid_to
76
- FROM claims WHERE valid_from <= ? AND valid_to >= ?`);return{query(o,i,a){if(!a||a.length===0)return r.all(o,i).map(e);const c=[...a].sort().join(",");let u=n.get(c);if(!u){const l=a.map(()=>"?").join(",");u=t.prepare(`SELECT * FROM events
77
- WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${l})
78
- ORDER BY occurred_at, id`),n.set(c,u)}return u.all(o,i,...a).map(e)},claims(o,i){return s.all(i,o).map(a=>{const c=a;return{key:String(c.key),subjectType:c.subject_type,subjectId:String(c.subject_id),sourceId:String(c.source_id),validFrom:Number(c.valid_from),validTo:Number(c.valid_to)}})},stats(){const o=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),i=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),a=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),c=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
79
- FROM events GROUP BY source_id ORDER BY s`).all().map(u=>{const l=u;return{source:String(l.s),events:Number(l.c),first:Number(l.lo),last:Number(l.hi)}});return{events:o,claims:i,bySource:c,earliest:a.lo,latest:a.hi}},begansFor(o){const i=[],a=t.prepare(`SELECT * FROM events
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
84
+ FROM claims WHERE valid_from <= ? AND valid_to >= ?`),i=new Map,a=t.prepare(`
85
+ SELECT subject_id FROM events WHERE subject_type = 'execution' AND occurred_at >= ? AND occurred_at < ?
86
+ UNION
87
+ SELECT b.subject_id FROM events b WHERE b.subject_type = 'execution' AND b.kind = 'began' AND b.occurred_at < ?
88
+ AND (SELECT z.id FROM events z WHERE z.subject_type = 'execution' AND z.subject_id = b.subject_id
89
+ AND z.kind = 'ended' AND z.occurred_at < ? AND (z.basis = 'measured' OR NOT EXISTS (
90
+ SELECT 1 FROM events n WHERE n.subject_type = 'execution' AND n.subject_id = z.subject_id
91
+ AND n.occurred_at > z.occurred_at AND n.occurred_at < ? AND n.kind IN ('progressed','blocked','resumed')))
92
+ ORDER BY z.occurred_at DESC LIMIT 1) IS NULL`),c=t.prepare(`SELECT * FROM events
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}
94
+ WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${h})
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
96
+ FROM claims INDEXED BY claims_key WHERE key IN (
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
80
100
  WHERE kind = 'began' AND subject_type = ? AND subject_id = ?
81
- ORDER BY occurred_at, id`);for(const c of o){const u=c.indexOf(":");if(u<0)continue;const l=a.all(c.slice(0,u),c.slice(u+1));for(const d of l)i.push(e(d))}return i}}}function fy(t){const[e,r,n]=oa(t).map(IA);return{db:e,wal:r,shm:n,total:e+r+n}}function IA(t){try{return Qi(t).size}catch{return 0}}function ei(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 py(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:ei(r.core,"core",n),attrs:ei(r.attrs,"attrs",n),basis:r.basis,assumption:r.assumption?String(r.assumption):void 0,stratum:r.stratum?r.stratum:void 0,provenance:ei(r.provenance,"provenance",n)}}const Vf={tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"};function CA(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=>OA(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:Sr("session",o.id),executionRefs:o.executionIds.map(i=>Sr("execution",i)).filter(i=>n.has(i)).sort(),spawnedBy:o.parentId?et({ref:Sr("session",o.parentId)}):Jr("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:_A(r,s,t.from,t.to)}}function OA(t,e,r){const n=r.get(`execution:${t.id}`),s=n?.source.id,o=s?e.capabilities.get(s)??Vf:Vf,i=e.state.sessions.get(t.sessionId),a=e.state.machines.get(t.machineId),c=t.status==="completed"||t.status==="failed",u=TA(n?.occurredAt??t.startedAt,n?.basis??t.startBasis),l=e.relationships.filter(y=>y.kind==="ran-as"&&(y.from.type==="execution"&&y.from.id===t.id&&y.to.type==="process"||y.to.type==="execution"&&y.to.id===t.id&&y.from.type==="process")).map(y=>{const v=y.from.type==="process"?y.from:y.to;return{kind:"ran-as",target:{type:"process",ref:Sr("process",v.id)},evidence:NA(y.basis),...y.basis==="inferred"?{qualification:"resolved from overlapping identity claims"}:{}}}).sort((y,v)=>y.target.ref.localeCompare(v.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:Sr("execution",t.id),observer:s??"unknown-observer",sessionRef:Sr("session",t.sessionId),machine:t.machineId?et({ref:Sr("machine",t.machineId),...a?{kind:a.kind}:{}}):Jr("no machine was reported"),context:d?zc(o.context,{ref:Sr("context",d)},"context"):ti(o.context,"context"),executor:t.executor&&t.executor!=="unknown"?et(t.executor):Jr("no executor was reported"),model:m?zc(o.model,m,"model"):ti(o.model,"model"),start:u,end:t.endedAt===void 0?lr(e.to,"the execution is open; query time is an elapsed wall bound, not a terminal end"):t.endBasis==="inferred"?Zs(t.endedAt,"the terminal bound was inferred by its observer"):et(t.endedAt),lifecycle:BA(t),outcome:$A(t,o.outcome),measures:{tokens:{input:Ar(t,z.tokensInput,o.tokens,c,!1,"token input"),output:Ar(t,z.tokensOutput,o.tokens,c,!1,"token output"),cacheRead:Ar(t,z.tokensCacheRead,o.tokens,c,!1,"cache-read tokens"),reasoning:Ar(t,z.tokensReasoning,o.tokens,c,!1,"reasoning tokens"),total:hy(ur(t.measures),o.tokens,c,!1,"token total")},requests:Ar(t,z.steps,o.requests,c,!0,"requests"),toolInteractions:Ar(t,z.interactions,o.toolInteractions,c,!0,"tool interactions"),toolErrors:Ar(t,z.errors,o.toolErrors,c,!0,"tool errors"),retries:Ar(t,z.retries,o.retries,c,!0,"retries")},wait:RA(p,o.waits,c),failure:t.status==="failed"?et("execution-failed"):c?o.outcome==="supported"?et("none"):ti(o.outcome,"failure state"):Mt("the execution is not terminal"),depth:t.depth,relationships:l}}function Sr(t,e){const r=Qn("sha256").update(`057-activity\0${t}\0${e}`).digest("hex").slice(0,16);return`${t}_${r}`}function NA(t){return t==="inferred"?"inferred":"observed"}function TA(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 BA(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 $A(t,e){if(t.status!=="completed"&&t.status!=="failed")return Mt("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"?Zs(r,"the terminal outcome follows an inferred terminal bound"):zc(e,r,"outcome"):ti(e,"outcome")}function Ar(t,e,r,n,s,o){return hy(Ot(t.measures,e),r,n,s,o)}function hy(t,e,r,n,s){return e==="unsupported"?mn(`this observer does not report ${s}`):e==="unknown"?Mt(`coverage for ${s} is not declared`):e==="partial"?lr(t,`this observer reports ${s} only partially`):r?t!==void 0?et(t):n?et(0):Jr(`${s} was not present in this execution`):lr(t,`${s} may still increase while the execution is active`)}function RA(t,e,r){return e==="unsupported"?mn("this observer does not report explicit waits"):e==="unknown"?Mt("wait coverage is not declared"):e==="partial"?lr(t,"this observer reports explicit waits only partially"):!r||t.current?lr(t,"an explicit wait may still be open"):et(t)}function zc(t,e,r){return t==="supported"?et(e):t==="partial"?lr(e,`this observer reports ${r} only partially`):t==="unsupported"?mn(`this observer does not report ${r}`):Mt(`coverage for ${r} is not declared`)}function ti(t,e){return t==="supported"?Jr(`${e} was not present in this execution`):t==="partial"?lr(void 0,`this observer reports ${e} only partially`):t==="unsupported"?mn(`this observer does not report ${e}`):Mt(`coverage for ${e} is not declared`)}function et(t){return{state:"observed",value:t}}function Zs(t,e){return{state:"inferred",value:t,qualification:e}}function lr(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function mn(t){return{state:"unsupported",qualification:t}}function Jr(t){return{state:"not-observed",qualification:t}}function Mt(t){return{state:"unknown",qualification:t}}function _A(t,e,r,n){const s=t.map(d=>({start:Math.max(r,d.start.at),end:Math.min(n,ut(d.end)??n),inferred:d.start.evidence==="inferred"||d.end.state==="inferred",partial:d.end.state!=="observed"&&d.end.state!=="inferred"})),o=Vn(s.map(d=>d.partial?"partial":d.inferred?"inferred":"observed")),i=Wf(s),a=Kf(s),c=t.filter(d=>d.lifecycle.state==="terminal"),u=c.flatMap(d=>{const m=ut(d.end);return m===void 0?[]:[{start:Math.max(r,d.start.at),end:Math.min(n,m),inferred:d.start.evidence==="inferred"||d.end.state==="inferred"}]}),l=Vn(c.map(d=>ut(d.end)===void 0?"unknown":d.start.evidence==="inferred"||d.end.state==="inferred"?"inferred":"observed"));return{executions:t.length,sessions:e.length,openExecutions:t.length-c.length,terminalExecutions:c.length,runningNow:t.filter(d=>d.lifecycle.state==="running").length,waitingNow:On(t.map(MA)),idleNow:t.filter(d=>d.lifecycle.state==="idle").length,completed:bc(c,"completed"),failed:bc(c,"failed"),interrupted:bc(c,"interrupted"),executionWallIntervalMs:nr(i,o),peakExecutionConcurrency:nr(a,o),executionDuration:gc(t.map(d=>{const m=ut(d.end)??n,p=Math.max(0,m-d.start.at);return d.end.state!=="observed"&&d.end.state!=="inferred"?lr(p,"elapsed wall duration for an open execution"):d.start.evidence==="inferred"||d.end.state==="inferred"?Zs(p,"one or more execution bounds were inferred"):et(p)})),terminalExecutionDuration:gc(c.map(d=>{const m=ut(d.end);if(m===void 0)return Mt("the terminal execution has no usable end bound");const p=Math.max(0,m-d.start.at);return d.start.evidence==="inferred"||d.end.state==="inferred"?Zs(p,"one or more execution bounds were inferred"):et(p)})),terminalExecutionIntervalMs:nr(Wf(u),l),overlappingTerminalIntervalMs:nr(PA(u),l),peakTerminalConcurrency:nr(Kf(u),l),sessionExecutionCount:gc(e.map(d=>et(d.executionRefs.length))),tokens:On(t.map(d=>d.measures.tokens.total)),toolInteractions:On(t.map(d=>d.measures.toolInteractions)),toolErrors:On(t.map(d=>d.measures.toolErrors)),waits:jA(t.map(d=>d.wait)),usageByModel:DA(t),executionsWithoutModel:t.filter(d=>ut(d.model)===void 0).length,modelMix:Ff(t,d=>Hf(d.model)),executorMix:Ff(t,d=>Hf(d.executor))}}function ut(t){return"value"in t?t.value:void 0}function Hf(t){return ut(t)??`[${t.state}]`}function Vn(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 nr(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 On(t){const e=Vn(t.map(s=>s.state));let r=0,n=0;for(const s of t){const o=ut(s);o!==void 0&&(r+=o,n++)}return n>0?nr(r,e):e.records>0&&e.unsupported===e.records?{...mn("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...Jr("no value was observed"),coverage:e}:{...Mt("no usable value was observed"),coverage:e}}function gc(t){const e=Vn(t.map(n=>n.state)),r=t.map(ut).filter(n=>n!==void 0).sort((n,s)=>n-s);return r.length===0?{...Mt("no usable duration samples were observed"),coverage:e}:nr({samples:r.length,minimum:r[0],median:vc(r,.5),p75:vc(r,.75),p90:vc(r,.9),maximum:r[r.length-1]},e)}function vc(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 MA(t){const e=ut(t.wait);return my(t.wait,e?.current?1:0)}function bc(t,e){return t.length===0?nr(0,Vn([])):On(t.map(r=>{const n=ut(r.outcome);return my(r.outcome,n===e?1:0)}))}function my(t,e){switch(t.state){case"observed":return et(e);case"inferred":return Zs(e,t.qualification);case"partial":return lr("value"in t?e:void 0,t.qualification);case"unsupported":return mn(t.qualification);case"not-observed":return Jr(t.qualification);case"unknown":return Mt(t.qualification)}}function jA(t){const e=Vn(t.map(s=>s.state));let r=0;const n={count:0,durationMs:0,openNow:0};for(const s of t){const o=ut(s);o&&(r++,n.count+=o.count,n.durationMs+=o.durationMs,o.current&&n.openNow++)}return r>0?nr(n,e):e.unsupported===e.records?{...mn("no observer reports explicit waits"),coverage:e}:{...Mt("no usable wait value was observed"),coverage:e}}function DA(t){const e=new Map;for(const r of t){const n=ut(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:On(n)})).sort((r,n)=>n.executions-r.executions||r.model.localeCompare(n.model))}function Ff(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 Wf(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 Kf(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 PA(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 Qs(t,e){const r=t.window,n=vt(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(g=>g.start.at),d=t.executions.map(g=>vt(g.end)??g.start.at),m=i>0?or({from:Math.min(...l),to:Math.max(...d)}):cr("no execution records establish an observed span"),p=new Map;for(const g of t.executions){const C=p.get(g.observer)??[];C.push(g),p.set(g.observer,C)}const y=[...p.entries()].map(([g,C])=>({source:g,executionRecords:C.length,firstExecutionAt:Math.min(...C.map(A=>A.start.at)),lastExecutionAt:Math.max(...C.map(A=>A.start.at)),capabilities:e.capabilities.get(g)??qA()})).sort((g,C)=>C.executionRecords-g.executionRecords||g.source.localeCompare(C.source)),v=[ps("tokens",t.summary.tokens),ps("tool-interactions",t.summary.toolInteractions),ps("tool-errors",t.summary.toolErrors),ps("waits",t.summary.waits),wc("outcomes",t.executions.map(g=>g.outcome)),ps("bounds",GA(t.executions)),wc("model",t.executions.map(g=>g.model)),wc("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:s?or([]):cr("historical observation gaps are not retained"),unprojectedSourceWork:cr("observers do not currently retain counts for source work omitted before a timed execution could be projected"),retention:e.retention,observedSpan:m,sources:y,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 LA(t,e){const r=Qs(t,e),n=r.comparisonReadiness==="not-comparable"?UA(t.summary):t.summary;return{experimental:!0,period:t.window,availability:r,summary:n}}function UA(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),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 VA(t,e,r){const n=new Map;for(const o of t.executions){const i=FA(o,r),a=n.get(i)??[];a.push(o),n.set(i,a)}const s=[...n.entries()].map(([o,i])=>WA(o,i)).sort((o,i)=>i.executions-o.executions||o.key.localeCompare(i.key));return{experimental:!0,period:t.window,dimension:r,availability:Qs(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 HA(t,e,r,n){const s=Qs(t,e),o=Qs(r,n),i=KA(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=[ys("execution records",Ho(t.executions.length,s),Ho(r.executions.length,o),c),ys("session records",Ho(t.sessions.length,s),Ho(r.sessions.length,o),c),Et("median terminal execution duration",qf(t.summary.terminalExecutionDuration),qf(r.summary.terminalExecutionDuration),c,s,o),Et("terminal execution interval union",t.summary.terminalExecutionIntervalMs,r.summary.terminalExecutionIntervalMs,c,s,o),Et("overlapping terminal interval",t.summary.overlappingTerminalIntervalMs,r.summary.overlappingTerminalIntervalMs,c,s,o),Et("peak terminal concurrency",gs(t.summary.peakTerminalConcurrency,d=>d.peak),gs(r.summary.peakTerminalConcurrency,d=>d.peak),c,s,o),ys("model mix",Nn(or(Fo(t.summary.modelMix)),s),Nn(or(Fo(r.summary.modelMix)),o),c),ys("executor mix",Nn(or(Fo(t.summary.executorMix)),s),Nn(or(Fo(r.summary.executorMix)),o),c),Et("completed executions",t.summary.completed,r.summary.completed,c,s,o),Et("failed executions",t.summary.failed,r.summary.failed,c,s,o),Et("interrupted executions",t.summary.interrupted,r.summary.interrupted,c,s,o),Et("tokens",t.summary.tokens,r.summary.tokens,c,s,o),Et("tool interactions",t.summary.toolInteractions,r.summary.toolInteractions,c,s,o),Et("tool errors",t.summary.toolErrors,r.summary.toolErrors,c,s,o),Et("explicit wait count",gs(t.summary.waits,d=>d.count),gs(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 FA(t,e){switch(e){case"model":return vt(t.model)??`[${t.model.state}]`;case"executor":return vt(t.executor)??`[${t.executor.state}]`;case"lifecycle":return t.lifecycle.state;case"outcome":return t.lifecycle.state==="terminal"?vt(t.outcome)??"unknown":"open";case"session":return t.sessionRef;case"duration-band":{if(t.lifecycle.state!=="terminal")return"open";const r=vt(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 WA(t,e){const r=e.filter(n=>n.lifecycle.state==="terminal");return{key:t,executions:e.length,terminalExecutions:r.length,terminalDuration:YA(r.map(n=>{const s=vt(n.end);if(s===void 0)return cr("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"?gy(o,"one or more execution bounds were inferred"):or(o)})),tokens:Wo(e.map(n=>n.measures.tokens.total)),toolInteractions:Wo(e.map(n=>n.measures.toolInteractions)),toolErrors:Wo(e.map(n=>n.measures.toolErrors)),failed:Wo(r.map(n=>zA(n.outcome,"failed")))}}function Ho(t,e){return e.observation==="observed"?or(t):e.executionRecords>0?vy(t,"record count is known, but observation continuity is not"):cr("the period was not sufficiently observed to interpret zero records as zero work")}function Et(t,e,r,n,s,o){return ys(t,Nn(e,s),Nn(r,o),n)}function Nn(t,e){return e.comparisonReadiness==="not-comparable"?cr("the period was not sufficiently observed"):t}function ys(t,e,r,n){const s=vt(e)!==void 0&&vt(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||Gf(e.state)||Gf(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 Gf(t){return t==="unsupported"||t==="not-observed"||t==="unknown"}function KA(t,e){return t==="not-comparable"||e==="not-comparable"?"not-comparable":t==="partially-comparable"||e==="partially-comparable"?"partially-comparable":"comparable"}function qf(t){return gs(t,e=>e.median)}function gs(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 Fo(t){return Object.fromEntries(t.map(e=>[e.key,e.executions]))}function ps(t,e){return{dimension:t,state:e.state,coverage:e.coverage,qualification:yy(e.state)}}function wc(t,e){const r=ca(e.map(s=>s.state)),n=XA(r);return{dimension:t,state:n,coverage:r,qualification:yy(n)}}function GA(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 Hl(e.length,ca(e))}function yy(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 qA(){return{tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"}}function zA(t,e){const r=vt(t);return ZA(t,r===e?1:0)}function Wo(t){const e=ca(t.map(n=>n.state)),r=t.map(vt).filter(n=>n!==void 0);return r.length>0?Hl(r.reduce((n,s)=>n+s,0),e):e.records>0&&e.unsupported===e.records?{...by("no observer supports this measure"),coverage:e}:e.records>0&&e.notObserved===e.records?{...wy("no value was observed"),coverage:e}:{...cr("no usable value was observed"),coverage:e}}function YA(t){const e=ca(t.map(n=>n.state)),r=t.map(vt).filter(n=>n!==void 0).sort((n,s)=>n-s);return r.length===0?{...cr("no terminal duration samples were observed"),coverage:e}:Hl({samples:r.length,minimum:r[0],median:Ac(r,.5),p75:Ac(r,.75),p90:Ac(r,.9),maximum:r[r.length-1]},e)}function Ac(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 Hl(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 XA(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 ca(t){const e=JA();e.records=t.length;for(const r of t)r==="not-observed"?e.notObserved++:e[r]++;return e}function JA(){return{records:0,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0}}function vt(t){return"value"in t?t.value:void 0}function ZA(t,e){switch(t.state){case"observed":return or(e);case"inferred":return gy(e,t.qualification);case"partial":return vy("value"in t?e:void 0,t.qualification);case"unsupported":return by(t.qualification);case"not-observed":return wy(t.qualification);case"unknown":return cr(t.qualification)}}function or(t){return{state:"observed",value:t}}function gy(t,e){return{state:"inferred",value:t,qualification:e}}function vy(t,e){return t===void 0?{state:"partial",qualification:e}:{state:"partial",value:t,qualification:e}}function by(t){return{state:"unsupported",qualification:t}}function wy(t){return{state:"not-observed",qualification:t}}function cr(t){return{state:"unknown",qualification:t}}const Hr="os",QA=(t,e)=>`os:${t}:${e.pid}:${e.startedAt}`;function eS(t,e){const r=/^os:[^:]+:(\d+):(\d+)$/.exec(t);return r?`os:${e}:${r[1]}:${r[2]}`:void 0}const tS=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.`,rS=250,nS=8*1024*1024;function sS(t,e,r){const n={source:{id:Hr,instance:r.host},observedAt:r.observedAt,clock:"wall",stratum:"machine"},s=[],o=new Map;for(const i of e){const a=QA(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,label:oS(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>=rS,d=Math.abs(i.rssBytes-u.rssBytes)>=nS;(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:tS(r.intervalMs),core:{outcome:"completed",measures:{[z.cpuMs]:a.cpuMs}},attrs:{"os.pid":a.pid}});return{envelopes:s,next:o}}function oS(t){return(t.split("/").pop()??t).toUpperCase()}const iS=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 aS(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 cS(t,e){if(t.seen.has(e.id))return;t.seen.add(e.id),e.occurredAt>t.now&&(t.now=e.occurredAt),aS(t,e);const r=e.core??{},n=e.occurredAt;switch(e.subject.type){case"machine":{if(t.machines.has(e.subject.id))break;const s={id:e.subject.id,name:r.machineName??e.subject.id,kind:r.machineKind??"laptop",parentId:r.parentId,firstSeenAt:n};t.machines.set(s.id,s);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":uS(t,e,n);break;case"process":lS(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 uS(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&&fi(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(e.kind){case"progressed":{n.measures&&fi(o.measures,n.measures),o.lastActivityAt=r,o.status==="idle"&&(o.status="running",t.active.add(s));break}case"blocked":{if(!Dm(o.status))break;o.status="waiting",o.waitingSince=r,o.waitReason=n.blockedOn??"input",o.lastActivityAt=r;break}case"resumed":{zf(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"}),zf(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 lS(t,e,r){const n=e.core??{},s=e.subject.id,o=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: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&&fi(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;fi(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 dS(t,e){for(let r=0;r<e.length;r++)cS(t,e[r])}function fS(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>iS&&(n.status="idle")}}function Ay(t,e,r,n,s){const o=s?pS(s):void 0,i=o?Xf(t.query(e,r,n),o):t.query(e,r,n),a=new Set,c=new Set,u=new Map,l=p=>{const y=`${p.subject.type}:${p.subject.id}`;p.kind==="began"?(a.add(y),u.set(y,p)):c.add(y),p.core?.sessionId&&c.add(`session:${p.core.sessionId}`),p.core?.machineId&&c.add(`machine:${p.core.machineId}`)};for(const p of i)l(p);const d=[];for(let p=0;p<4;p++){const y=[...c].filter(g=>!a.has(g));if(y.length===0)break;const v=o?Xf(t.begansFor(y),o):t.begansFor(y);if(v.length===0)break;for(const g of v)u.set(`${g.subject.type}:${g.subject.id}`,g),d.push(g.occurredAt<e?{...g,occurredAt:e}:g),l(g),a.add(`${g.subject.type}:${g.subject.id}`)}return{events:[...d,...i].sort((p,y)=>p.occurredAt-y.occurredAt||Jf(p)-Jf(y)),declarations:[...u.values()],relationships:gb(t.claims(e,r)).relationships}}function Sy(t,e,r,n,s){const o=performance.now(),{events:i,declarations:a,relationships:c}=Ay(t,e,r,s,n),u=performance.now()-o,l=performance.now(),d=Pm(e,r);dS(d,i),fS(d,r);const m=performance.now()-l;return{state:d,events:i,declarations:a,relationships:c,meta:{events:i.length,readMs:Math.round(u*10)/10,deriveMs:Math.round(m*10)/10}}}function Yf(t,e,r,n){const s=Sy(t,e,r,n),o=performance.now();return{world:K0(s.state,s.relationships),state:s.state,declarations:s.declarations,meta:{...s.meta,serializeMs:Math.round((performance.now()-o)*10)/10}}}function pS(t){const e=Ob(t);return r=>{if(r.subject.type==="machine")return r.subject.id!==t&&Qd(r.subject.id)?null:r;const n=r.core?.machineId;if(!n||n===t||!Qd(n))return r;const s=r.subject.type==="process"&&e?eS(r.subject.id,e):void 0;return{...r,...s?{subject:{...r.subject,id:s}}:{},core:{...r.core,machineId:t}}}}function Xf(t,e){const r=[];for(const n of t){const s=e(n);s&&r.push(s)}return r}function Jf(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 hS=[[Ol,Ab],[li,Mb],[Kr,qb],[Ds,o0],[Pn,A0],[Ls,T0]],Fl=new Map(hS);function mS(t,e,r,n){const s=Sy(t,e,r,n,["machine","session","execution"]);return CA({state:s.state,declarations:s.declarations,relationships:s.relationships,capabilities:Fl,from:e,to:r})}function ky(t,e,r,n=Date.now()){const s=new Map,o=a=>{const c=`${a.from}:${a.to}`,u=s.get(c);if(u)return u;const l=mS(t,a.from,a.to,r);return s.set(c,l),l},i=a=>yS(a,e,n);return{summary(a){return LA(o(a),i(a))},availability(a){return Qs(o(a),i(a))},compare(a,c){return HA(o(a),i(a),o(c),i(c))},breakdown(a,c){return VA(o(a),i(a),c)}}}function yS(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:Fl,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 gS=3e4;function vS(t,e,r){const n=aa(t.path);try{const s=t.now?.()??Date.now(),o=ky(n,t.retention,t.machineId,s);return tA(o,e,s,r)}finally{n.close()}}function bS(t,e){return JSON.stringify([t.query,t.scope,t.focus,t.by,e.view,e.timeZone])}function xy(t){const e=new Map;return{async read(r,n){const s=t.now?.()??Date.now(),o=bS(r,n),i=e.get(o);if(i&&s-i.at<gS)return i.reading;const a=vS(t,r,n);return e.set(o,{at:s,reading:a}),a},close(){e.clear()}}}function wS(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 mm(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 AS(t){const e=xy(t);Bn?.on("message",r=>{e.read(r.request,r.context).then(n=>Bn?.postMessage({id:r.id,reading:n}),n=>Bn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)}))})}!hm&&ai?.o57==="activity-reader"&&AS(ai);const Wl={[hi]:qs};function Kl(t){return`${t}.core.json`}function Ey(t){const e=Kl(t);if(!fe(e))return null;try{const r=JSON.parse(Cl(e,"utf8"));return typeof r.pid!="number"||typeof r.url!="string"?null:r}catch{return null}}function SS(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function kS(t,e=1500){const r=Ey(t);if(!r||r.pid===process.pid||!SS(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 xS(t,e){if(t===":memory:")return;const r=Kl(t),n=`${r}.${process.pid}.tmp`;El(n,`${JSON.stringify(e,null,1)}
82
- `,{mode:384}),Il(n,r)}function ES(t,e=process.pid){if(t===":memory:")return;const r=Ey(t);r&&r.pid===e&&fm(Kl(t),{force:!0})}class Gl extends Error{constructor(e){super(`057 is already observing ${e.store} at ${e.url} (pid ${e.pid})`),this.record=e}record}const IS=ab(ib);function CS(){return gm()}function OS(t){const e=[];for(const r of t.split(`
83
- `)){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:NS(c),rssBytes:Number(u)*1024,command:l.trim()})}return e}function NS(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 TS(){const{stdout:t}=await IS("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return OS(t)}const Zf=5e3;function BS(t,e){const r=CS();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 TS(),d=Date.now(),{envelopes:m,next:p}=sS(n,l,{machineId:e,host:r,observedAt:d,intervalMs:Zf}),y=m.map(Wt);return t.append(y),n=p,o++,i=d,a=void 0,y}catch(l){return a=l instanceof Error?l.message:String(l),[]}finally{c=!1}}return{sample:u,start(){s||(u(),s=setInterval(()=>{u()},Zf),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 Iy={info:t=>console.log(t),warn:t=>console.warn(t),error:t=>console.error(t)},$S=36e5,RS=15e3,_S=3;function Cy(t={}){const e=t.log??Iy,r=t.path??sa(),n=t.retention??ly(),s=EA(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=uy();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=_r();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=BS(s,a.id),u=new Map;function l(A){for(const I of A){const B=u.get(I.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};I.ok?(B.consecutiveFailures=0,B.failing=!1,B.failingSince=void 0,B.lastSuccessAt=Date.now()):(B.consecutiveFailures===0&&(B.failingSince=Date.now()),B.consecutiveFailures++,B.totalFailures++,B.lastFailureAt=Date.now(),B.lastError=I.error,B.consecutiveFailures>=_S&&!B.failing&&(B.failing=!0,e.warn(`[057] source ${I.id} has failed ${B.consecutiveFailures} collection rounds in a row: ${I.error??"unknown error"}`))),u.set(I.id,B)}}const d=Qf(r);let m=null;function p(A){return m||(m=A,e.error(`[057] ${A.message} — ${A.remedy}`),c.stop()),m}function y(){if(m)return m;if(r===":memory:")return null;if(!fe(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 A=Qf(r);return d!==null&&A!==null&&A!==d?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=s.sweep(n);v.processEvents+v.otherEvents>0&&e.info(`[057] retention: removed ${v.processEvents} process and ${v.otherEvents} semantic events (${ia(n)})`);const g=setInterval(()=>{if(!m)try{s.sweep(n),Gc(r)}catch(A){e.warn(`[057] retention sweep failed: ${String(A)}`)}},$S);g.unref?.();const C=setInterval(()=>{y()},RS);return C.unref?.(),{store:s,machine:a,os:c,path:r,retention:n,fault:()=>m,sweep:A=>s.sweep(n,A),checkStore:y,recordCollection:l,collectionHealth:()=>Object.fromEntries(u),stop(){clearInterval(g),clearInterval(C),c.stop(),s.close()}}}function Qf(t){try{return Qi(t).ino}catch{return null}}function MS(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);let n=0;for(const s of t.executions.keys()){const o=r.get(s),i=o?Fl.get(o)?.waits:void 0;(i==="supported"||i==="partial")&&n++}return{reported:n,runs:t.executions.size}}function Oy(t,e,r){let n={from:r.from,to:r.to},s=r.label,o=Yf(t,n.from,n.to,e);if(r.widenFrom!==void 0&&o.world.executions.length===0&&o.world.sessions.length===0){const i=Yf(t,r.widenFrom,r.to,e);(i.world.executions.length>0||i.world.sessions.length>0)&&(n={from:r.widenFrom,to:r.to},s=r.widenedLabel??s,o=i)}return{...n,label:s,world:o.world,meta:o.meta,waits:MS(o.state,o.declarations)}}function jS(t,e){return{async read(r){return Oy(t,e,r)},close(){}}}function DS(t,e){let r=null,n=1,s=null;const o=new Map,i=c=>{for(const u of o.values())u.reject(c);o.clear()},a=()=>{const c={o57:"landscape-reader",...e},u=new mm(new URL(t),{workerData:c,execArgv:["--disable-warning=ExperimentalWarning"]});return u.unref(),u.on("message",l=>{const d=o.get(l.id);d&&(o.delete(l.id),l.snapshot?d.resolve(l.snapshot):d.reject(new Error(l.error??"the landscape read failed")))}),u.on("error",l=>{r=null,i(l instanceof Error?l:new Error(String(l)))}),u.on("exit",l=>{r===u&&(r=null),o.size>0&&i(new Error(`the landscape worker stopped (${l})`))}),u};return{read(c){if(c.label==="TODAY"&&s)return s;r??=a();const u=n++,l=new Promise((d,m)=>{o.set(u,{resolve:d,reject:m}),r?.postMessage({id:u,request:c})});return c.label!=="TODAY"?l:(s=l.finally(()=>{s=null}),s)},close(){i(new Error("the Core is stopping")),r?.terminate(),r=null,s=null}}}function PS(t){const e=aa(t.path);Bn?.on("message",r=>{try{Bn?.postMessage({id:r.id,snapshot:Oy(e,t.machineId,r.request)})}catch(n){Bn?.postMessage({id:r.id,error:String(n instanceof Error?n.message:n)})}})}!hm&&ai?.o57==="landscape-reader"&&PS(ai);const Yc=[{id:Ol,collect:(t,e)=>_b(t,e)},{id:li,collect:(t,e)=>Gb(t,e)},{id:Kr,collect:(t,e)=>s0(t,e)},{id:Ds,collect:(t,e)=>w0(t,e)},{id:Pn,collect:(t,e)=>N0(t,e)},{id:Ls,collect:(t,e)=>V0(t,e)}],ep=[...Yc.map(t=>t.id),Hr],tp=10*365*24*36e5,Ko=2e5,LS=24*36e5,rp=72*36e5;function np(t){const e=new Date(t);return e.setHours(0,0,0,0),{from:e.getTime(),to:t}}function sp(t){const e=t.collectionHealth(),r=Object.entries(e).filter(([,a])=>a.failing).map(([a])=>a),n=t.store.health(),s=t.os.stats(),o=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&&!o&&!s.lastError,fault:o??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:s.lastSampleAt,lastError:s.lastError},lastCollectionAt:i,sources:{total:ep.length,reported:ep.filter(a=>e[a]!==void 0).length}}}function US(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(HS.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[VS])return"refusing a state-changing request that carries no fetch metadata";return null}const VS="x-057-client",HS=new Set(["iframe","frame","embed","object","fencedframe"]);function ql(t){t.setHeader("x-frame-options","DENY"),t.setHeader("content-security-policy","frame-ancestors 'none'")}function FS(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+LS?{error:"to is too far in the future"}:s-n>tp?{error:`window must not exceed ${tp} ms`}:{from:n,to:s}}function Ee(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"),ql(t),t.end(JSON.stringify(r))}function WS(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 Sc(t){return{"stored-semantics":t.storedAvailable?t.failed===0?"available":t.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function KS(t){return t.error?"failed":t.available?"observing":t.present?"installed-no-data":"not-installed"}function GS(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 Ur(t){return{available:t.available,present:t.present??!1,presence:KS(t),origin:GS(t),error:t.error}}function qS(t){const{runtime:e,log:r}=t,n=t.activity??xy({path:e.path,retention:e.retention,machineId:e.machine.id}),s=t.landscape??jS(e.store,e.machine.id);let o=null;async function i(a){if(!o||a-o.at>6e4){const c=np(a),u=await s.read({...c,label:"TODAY",widenFrom:a-rp,widenedLabel:"LAST 72H"}),l=yf(u.world);o={at:a,label:u.label,world:l,landscape:Cf(l),waits:u.waits}}return o}return async function(c,u){const l=c.url??"";if(!l.startsWith("/api/"))return!1;const d=new URL(l,"http://localhost"),m=US(c,d.pathname,t.allowedHosts);if(m)return r.warn(`[057] ${m}`),Ee(u,403,{error:m}),!0;const p=e.store,y=Date.now(),v=FS(d.searchParams,y);if("error"in v)return Ee(u,400,{error:v.error}),!0;const{from:g,to:C}=v;try{if(d.pathname==="/api/state"){const[A,I,B,k,T,S]=await Promise.all([tf().catch(pe=>({available:!1,error:String(pe)})),of().catch(pe=>({available:!1,error:String(pe)})),cf().catch(pe=>({available:!1,error:String(pe)})),uf().catch(pe=>({available:!1,error:String(pe)})),pf().catch(pe=>({available:!1,error:String(pe)})),mf().catch(pe=>({available:!1,error:String(pe)}))]),[E,R,j,M]=await Promise.all([Im(g,C).catch(()=>null),Nm(g,C).catch(()=>null),$m(g,C).catch(()=>null),jm(g,C).catch(()=>null)]),J={strata:{"stored-semantics":"failed"}},le={"claude-code":E?{strata:WS(E),registryEntries:E.registryEntries,transcriptsRead:E.transcriptsRead,transcriptsFailed:E.transcriptsFailed,problems:E.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:R?{strata:Sc({storedAvailable:R.storedAvailable,read:R.rolloutsRead,failed:R.rolloutsFailed}),rolloutsRead:R.rolloutsRead,rolloutsFailed:R.rolloutsFailed,problems:R.problems.slice(0,20)}:J,cursor:j?{strata:Sc({storedAvailable:j.storedAvailable,read:j.composersRead,failed:j.composersFailed}),composersRead:j.composersRead,composersFailed:j.composersFailed,problems:j.problems.slice(0,20)}:J,gemini:M?{strata:Sc({storedAvailable:M.storedAvailable,read:M.sessionsRead,failed:M.sessionsFailed}),sessionsRead:M.sessionsRead,sessionsFailed:M.sessionsFailed,problems:M.problems.slice(0,20)}:J},re={deepseek:Ur(A),"0x2f":Ur(I),"claude-code":Ur(B),codex:Ur(k),cursor:Ur(T),gemini:Ur(S)},F=e.collectionHealth();for(const[pe,Z]of Object.entries(re)){const yt=F[pe];yt?.failing&&(Z.presence="failed",Z.error??=yt.lastError)}const W=e.os.stats(),he=Object.values(re).filter(pe=>pe.available).length>0?"observing":W.samples>0?"os-only":"empty",$e=Object.entries(F).filter(([,pe])=>pe.failing).map(([pe])=>pe),Me=p.health(),Qt={ok:$e.length===0&&Me.ok&&!e.fault()&&!W.lastError,failingSources:$e,collection:F,store:Me,os:W.lastError?{failing:!0,lastError:W.lastError}:{failing:!1}};return Ee(u,200,{machine:e.machine,mode:he,fault:e.fault()??void 0,health:Qt,store:{...p.stats(),path:p.path,schemaVersion:p.schemaVersion,bytes:p.sizeBytes(),retention:{...e.retention,description:ia(e.retention)}},os:{...W,running:e.os.running,source:Hr},sources:re,observation:le}),!0}if(d.pathname==="/api/collect"){const A=e.checkStore();if(A)return Ee(u,503,{error:A.message,fault:A}),!0;const I=await vb(p,Yc,g,C,k=>e.recordCollection([k])),B=await e.os.sample();return e.recordCollection([{id:Hr,ok:!e.os.stats().lastError,error:e.os.stats().lastError}]),Ee(u,200,{...I,sources:[...I.sources,{id:Hr,ok:!e.os.stats().lastError,collected:B.length,inserted:B.length,duplicate:0,error:e.os.stats().lastError,ms:0}]}),!0}if(d.pathname==="/api/world"){const A=await s.read({from:g,to:C,label:"WINDOW"});return Ee(u,200,{from:g,to:C,now:y,world:A.world,meta:A.meta,waits:A.waits}),!0}if(d.pathname==="/api/health")return Ee(u,200,{pid:process.pid,version:t.version??"dev",contract:Wl,store:e.path,health:sp(e)}),!0;if(d.pathname==="/api/landscape"){const A=d.searchParams.get("window")==="live",I=A?np(y):{from:g,to:C},B=await s.read({...I,label:A?"TODAY":"WINDOW",...A?{widenFrom:y-rp,widenedLabel:"LAST 72H"}:{}}),k=yf(B.world),T=Cf(k);return A&&(o={at:y,label:B.label,world:k,landscape:T,waits:B.waits}),Ee(u,200,{from:B.from,to:B.to,now:y,window:B.label,meta:B.meta,health:sp(e),...ow(T)}),!0}if(d.pathname==="/api/today"||d.pathname==="/api/log"){const A=await i(y);return Ee(u,200,d.pathname==="/api/today"?{window:A.label,...Cw(A.world,A.waits)}:{window:A.label,...Ow(A.world,A.landscape)}),!0}if(d.pathname==="/api/inspect"){const A=d.searchParams.get("kind")??"",I=d.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(A)||!I||I.length>512)return Ee(u,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;if(await i(y),!o)return!0;const B=(T,S)=>{for(const E of p.subjectEvents(T,S))if(E.provenance?.path)return E.provenance.path},k=aw(o.world,o.landscape,A,I,B);return k?(Ee(u,200,k),!0):(Ee(u,404,{error:"not in the current world"}),!0)}if(d.pathname==="/api/activity"){const A=d.searchParams,I=Zw({query:A.get("query"),scope:A.get("scope"),focus:A.get("focus"),by:A.get("by")});if("error"in I)return Ee(u,400,I),!0;const B=A.get("view")==="live"?o?.label??(await i(y)).label:void 0;return Ee(u,200,await n.read(I,B?{view:B}:{})),!0}if(d.pathname==="/api/sources"){const A=await Promise.all([tf().catch(T=>({available:!1,error:String(T)})),of().catch(T=>({available:!1,error:String(T)})),cf().catch(T=>({available:!1,error:String(T)})),uf().catch(T=>({available:!1,error:String(T)})),pf().catch(T=>({available:!1,error:String(T)})),mf().catch(T=>({available:!1,error:String(T)}))]),I=e.collectionHealth(),B=e.os.stats(),k=Yc.map((T,S)=>{const E=Ur(A[S]),R=I[T.id];return{id:T.id,presence:R?.failing?"failed":E.presence,origin:E.origin,error:R?.failing?R.lastError??E.error:E.error,consecutiveFailures:R?.consecutiveFailures??0,lastSuccessAt:R?.lastSuccessAt}});return k.push({id:Hr,presence:B.lastError?"failed":B.samples>0?"observing":"installed-no-data",origin:void 0,error:B.lastError,consecutiveFailures:I[Hr]?.consecutiveFailures??0,lastSuccessAt:B.lastSampleAt??void 0}),Ee(u,200,{sources:k}),!0}if(d.pathname==="/api/detail"){const A=d.searchParams.get("type")??"",I=d.searchParams.get("id")??"";if(!Yd.includes(A)||!I)return Ee(u,400,{error:"detail needs type=<entity type> and id"}),!0;if(I.length>512)return Ee(u,400,{error:"id is too long"}),!0;const B=p.subjectEvents(A,I);return Ee(u,200,{type:A,id:I,events:B.slice(0,Ko),truncated:B.length>Ko}),!0}if(d.pathname==="/api/events"){const A=d.searchParams.get("subject"),I=A?A.split(",").filter(k=>Yd.includes(k)):void 0,B=Ay(p,g,C,I,e.machine.id);return Ee(u,200,{from:g,to:C,now:y,events:B.events.slice(0,Ko),truncated:B.events.length>Ko,relationships:B.relationships}),!0}return Ee(u,404,{error:"unknown endpoint"}),!0}catch(A){return r.error(`[057] ${String(A)}`),Ee(u,500,{error:String(A)}),!0}}}var op=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ip={};var ap;function zS(){if(ap)return ip;ap=1;var t;return(function(e){(function(r){var n=typeof globalThis=="object"?globalThis:typeof op=="object"?op: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 ac(Object.create(null))}:u?function(){return ac({__proto__:null})}:function(){return ac({})},has:l?function(w,x){return s.call(w,x)}:function(w,x){return x in w},get:l?function(w,x){return s.call(w,x)?w[x]:void 0}:function(w,x){return w[x]}},m=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Wv(),y=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Kv(),v=typeof WeakMap=="function"?WeakMap:Gv(),g=o?Symbol.for("@reflect-metadata:registry"):void 0,C=Vv(),A=Hv(C);function I(w,x,N,P){if(Z(N)){if(!Vd(w))throw new TypeError;if(!Hd(x))throw new TypeError;return le(w,x)}else{if(!Vd(w))throw new TypeError;if(!me(x))throw new TypeError;if(!me(P)&&!Z(P)&&!yt(P))throw new TypeError;return yt(P)&&(P=void 0),N=Dt(N),re(w,x,N,P)}}r("decorate",I);function B(w,x){function N(P,Q){if(!me(P))throw new TypeError;if(!Z(Q)&&!Lv(Q))throw new TypeError;$e(w,x,P,Q)}return N}r("metadata",B);function k(w,x,N,P){if(!me(N))throw new TypeError;return Z(P)||(P=Dt(P)),$e(w,x,N,P)}r("defineMetadata",k);function T(w,x,N){if(!me(x))throw new TypeError;return Z(N)||(N=Dt(N)),F(w,x,N)}r("hasMetadata",T);function S(w,x,N){if(!me(x))throw new TypeError;return Z(N)||(N=Dt(N)),W(w,x,N)}r("hasOwnMetadata",S);function E(w,x,N){if(!me(x))throw new TypeError;return Z(N)||(N=Dt(N)),ee(w,x,N)}r("getMetadata",E);function R(w,x,N){if(!me(x))throw new TypeError;return Z(N)||(N=Dt(N)),he(w,x,N)}r("getOwnMetadata",R);function j(w,x){if(!me(w))throw new TypeError;return Z(x)||(x=Dt(x)),Me(w,x)}r("getMetadataKeys",j);function M(w,x){if(!me(w))throw new TypeError;return Z(x)||(x=Dt(x)),Qt(w,x)}r("getOwnMetadataKeys",M);function J(w,x,N){if(!me(x))throw new TypeError;if(Z(N)||(N=Dt(N)),!me(x))throw new TypeError;Z(N)||(N=Dt(N));var P=fs(x,N,!1);return Z(P)?!1:P.OrdinaryDeleteMetadata(w,x,N)}r("deleteMetadata",J);function le(w,x){for(var N=w.length-1;N>=0;--N){var P=w[N],Q=P(x);if(!Z(Q)&&!yt(Q)){if(!Hd(Q))throw new TypeError;x=Q}}return x}function re(w,x,N,P){for(var Q=w.length-1;Q>=0;--Q){var Re=w[Q],Ne=Re(x,N,P);if(!Z(Ne)&&!yt(Ne)){if(!me(Ne))throw new TypeError;P=Ne}}return P}function F(w,x,N){var P=W(w,x,N);if(P)return!0;var Q=ic(x);return yt(Q)?!1:F(w,Q,N)}function W(w,x,N){var P=fs(x,N,!1);return Z(P)?!1:Ud(P.OrdinaryHasOwnMetadata(w,x,N))}function ee(w,x,N){var P=W(w,x,N);if(P)return he(w,x,N);var Q=ic(x);if(!yt(Q))return ee(w,Q,N)}function he(w,x,N){var P=fs(x,N,!1);if(!Z(P))return P.OrdinaryGetOwnMetadata(w,x,N)}function $e(w,x,N,P){var Q=fs(N,P,!0);Q.OrdinaryDefineOwnMetadata(w,x,N,P)}function Me(w,x){var N=Qt(w,x),P=ic(w);if(P===null)return N;var Q=Me(P,x);if(Q.length<=0)return N;if(N.length<=0)return Q;for(var Re=new y,Ne=[],oe=0,V=N;oe<V.length;oe++){var K=V[oe],q=Re.has(K);q||(Re.add(K),Ne.push(K))}for(var X=0,ae=Q;X<ae.length;X++){var K=ae[X],q=Re.has(K);q||(Re.add(K),Ne.push(K))}return Ne}function Qt(w,x){var N=fs(w,x,!1);return N?N.OrdinaryOwnMetadataKeys(w,x):[]}function pe(w){if(w===null)return 1;switch(typeof w){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return w===null?1:6;default:return 6}}function Z(w){return w===void 0}function yt(w){return w===null}function jo(w){return typeof w=="symbol"}function me(w){return typeof w=="object"?w!==null:typeof w=="function"}function jv(w,x){switch(pe(w)){case 0:return w;case 1:return w;case 2:return w;case 3:return w;case 4:return w;case 5:return w}var N="string",P=Fd(w,i);if(P!==void 0){var Q=P.call(w,N);if(me(Q))throw new TypeError;return Q}return Dv(w)}function Dv(w,x){var N,P;{var Q=w.toString;if(Do(Q)){var P=Q.call(w);if(!me(P))return P}var N=w.valueOf;if(Do(N)){var P=N.call(w);if(!me(P))return P}}throw new TypeError}function Ud(w){return!!w}function Pv(w){return""+w}function Dt(w){var x=jv(w);return jo(x)?x:Pv(x)}function Vd(w){return Array.isArray?Array.isArray(w):w instanceof Object?w instanceof Array:Object.prototype.toString.call(w)==="[object Array]"}function Do(w){return typeof w=="function"}function Hd(w){return typeof w=="function"}function Lv(w){switch(pe(w)){case 3:return!0;case 4:return!0;default:return!1}}function oc(w,x){return w===x||w!==w&&x!==x}function Fd(w,x){var N=w[x];if(N!=null){if(!Do(N))throw new TypeError;return N}}function Wd(w){var x=Fd(w,a);if(!Do(x))throw new TypeError;var N=x.call(w);if(!me(N))throw new TypeError;return N}function Kd(w){return w.value}function Gd(w){var x=w.next();return x.done?!1:x}function qd(w){var x=w.return;x&&x.call(w)}function ic(w){var x=Object.getPrototypeOf(w);if(typeof w!="function"||w===m||x!==m)return x;var N=w.prototype,P=N&&Object.getPrototypeOf(N);if(P==null||P===Object.prototype)return x;var Q=P.constructor;return typeof Q!="function"||Q===w?x:Q}function Uv(){var w;!Z(g)&&typeof n.Reflect<"u"&&!(g in n.Reflect)&&typeof n.Reflect.defineMetadata=="function"&&(w=Fv(n.Reflect));var x,N,P,Q=new v,Re={registerProvider:Ne,getProvider:V,setProvider:q};return Re;function Ne(X){if(!Object.isExtensible(Re))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case w===X:break;case Z(x):x=X;break;case x===X:break;case Z(N):N=X;break;case N===X:break;default:P===void 0&&(P=new y),P.add(X);break}}function oe(X,ae){if(!Z(x)){if(x.isProviderFor(X,ae))return x;if(!Z(N)){if(N.isProviderFor(X,ae))return x;if(!Z(P))for(var ve=Wd(P);;){var xe=Gd(ve);if(!xe)return;var kt=Kd(xe);if(kt.isProviderFor(X,ae))return qd(ve),kt}}}if(!Z(w)&&w.isProviderFor(X,ae))return w}function V(X,ae){var ve=Q.get(X),xe;return Z(ve)||(xe=ve.get(ae)),Z(xe)&&(xe=oe(X,ae),Z(xe)||(Z(ve)&&(ve=new p,Q.set(X,ve)),ve.set(ae,xe))),xe}function K(X){if(Z(X))throw new TypeError;return x===X||N===X||!Z(P)&&P.has(X)}function q(X,ae,ve){if(!K(ve))throw new Error("Metadata provider not registered.");var xe=V(X,ae);if(xe!==ve){if(!Z(xe))return!1;var kt=Q.get(X);Z(kt)&&(kt=new p,Q.set(X,kt)),kt.set(ae,ve)}return!0}}function Vv(){var w;return!Z(g)&&me(n.Reflect)&&Object.isExtensible(n.Reflect)&&(w=n.Reflect[g]),Z(w)&&(w=Uv()),!Z(g)&&me(n.Reflect)&&Object.isExtensible(n.Reflect)&&Object.defineProperty(n.Reflect,g,{enumerable:!1,configurable:!1,writable:!1,value:w}),w}function Hv(w){var x=new v,N={isProviderFor:function(K,q){var X=x.get(K);return Z(X)?!1:X.has(q)},OrdinaryDefineOwnMetadata:Ne,OrdinaryHasOwnMetadata:Q,OrdinaryGetOwnMetadata:Re,OrdinaryOwnMetadataKeys:oe,OrdinaryDeleteMetadata:V};return C.registerProvider(N),N;function P(K,q,X){var ae=x.get(K),ve=!1;if(Z(ae)){if(!X)return;ae=new p,x.set(K,ae),ve=!0}var xe=ae.get(q);if(Z(xe)){if(!X)return;if(xe=new p,ae.set(q,xe),!w.setProvider(K,q,N))throw ae.delete(q),ve&&x.delete(K),new Error("Wrong provider for target.")}return xe}function Q(K,q,X){var ae=P(q,X,!1);return Z(ae)?!1:Ud(ae.has(K))}function Re(K,q,X){var ae=P(q,X,!1);if(!Z(ae))return ae.get(K)}function Ne(K,q,X,ae){var ve=P(X,ae,!0);ve.set(K,q)}function oe(K,q){var X=[],ae=P(K,q,!1);if(Z(ae))return X;for(var ve=ae.keys(),xe=Wd(ve),kt=0;;){var zd=Gd(xe);if(!zd)return X.length=kt,X;var qv=Kd(zd);try{X[kt]=qv}catch(zv){try{qd(xe)}finally{throw zv}}kt++}}function V(K,q,X){var ae=P(q,X,!1);if(Z(ae)||!ae.delete(K))return!1;if(ae.size===0){var ve=x.get(q);Z(ve)||(ve.delete(X),ve.size===0&&x.delete(ve))}return!0}}function Fv(w){var x=w.defineMetadata,N=w.hasOwnMetadata,P=w.getOwnMetadata,Q=w.getOwnMetadataKeys,Re=w.deleteMetadata,Ne=new v,oe={isProviderFor:function(V,K){var q=Ne.get(V);return!Z(q)&&q.has(K)?!0:Q(V,K).length?(Z(q)&&(q=new y,Ne.set(V,q)),q.add(K),!0):!1},OrdinaryDefineOwnMetadata:x,OrdinaryHasOwnMetadata:N,OrdinaryGetOwnMetadata:P,OrdinaryOwnMetadataKeys:Q,OrdinaryDeleteMetadata:Re};return oe}function fs(w,x,N){var P=C.getProvider(w,x);if(!Z(P))return P;if(N){if(C.setProvider(w,x,A))return A;throw new Error("Illegal state.")}}function Wv(){var w={},x=[],N=(function(){function oe(V,K,q){this._index=0,this._keys=V,this._values=K,this._selector=q}return oe.prototype["@@iterator"]=function(){return this},oe.prototype[a]=function(){return this},oe.prototype.next=function(){var V=this._index;if(V>=0&&V<this._keys.length){var K=this._selector(this._keys[V],this._values[V]);return V+1>=this._keys.length?(this._index=-1,this._keys=x,this._values=x):this._index++,{value:K,done:!1}}return{value:void 0,done:!0}},oe.prototype.throw=function(V){throw this._index>=0&&(this._index=-1,this._keys=x,this._values=x),V},oe.prototype.return=function(V){return this._index>=0&&(this._index=-1,this._keys=x,this._values=x),{value:V,done:!0}},oe})(),P=(function(){function oe(){this._keys=[],this._values=[],this._cacheKey=w,this._cacheIndex=-2}return Object.defineProperty(oe.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),oe.prototype.has=function(V){return this._find(V,!1)>=0},oe.prototype.get=function(V){var K=this._find(V,!1);return K>=0?this._values[K]:void 0},oe.prototype.set=function(V,K){var q=this._find(V,!0);return this._values[q]=K,this},oe.prototype.delete=function(V){var K=this._find(V,!1);if(K>=0){for(var q=this._keys.length,X=K+1;X<q;X++)this._keys[X-1]=this._keys[X],this._values[X-1]=this._values[X];return this._keys.length--,this._values.length--,oc(V,this._cacheKey)&&(this._cacheKey=w,this._cacheIndex=-2),!0}return!1},oe.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=w,this._cacheIndex=-2},oe.prototype.keys=function(){return new N(this._keys,this._values,Q)},oe.prototype.values=function(){return new N(this._keys,this._values,Re)},oe.prototype.entries=function(){return new N(this._keys,this._values,Ne)},oe.prototype["@@iterator"]=function(){return this.entries()},oe.prototype[a]=function(){return this.entries()},oe.prototype._find=function(V,K){if(!oc(this._cacheKey,V)){this._cacheIndex=-1;for(var q=0;q<this._keys.length;q++)if(oc(this._keys[q],V)){this._cacheIndex=q;break}}return this._cacheIndex<0&&K&&(this._cacheIndex=this._keys.length,this._keys.push(V),this._values.push(void 0)),this._cacheIndex},oe})();return P;function Q(oe,V){return oe}function Re(oe,V){return V}function Ne(oe,V){return[oe,V]}}function Kv(){var w=(function(){function x(){this._map=new p}return Object.defineProperty(x.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),x.prototype.has=function(N){return this._map.has(N)},x.prototype.add=function(N){return this._map.set(N,N),this},x.prototype.delete=function(N){return this._map.delete(N)},x.prototype.clear=function(){this._map.clear()},x.prototype.keys=function(){return this._map.keys()},x.prototype.values=function(){return this._map.keys()},x.prototype.entries=function(){return this._map.entries()},x.prototype["@@iterator"]=function(){return this.keys()},x.prototype[a]=function(){return this.keys()},x})();return w}function Gv(){var w=16,x=d.create(),N=P();return(function(){function V(){this._key=P()}return V.prototype.has=function(K){var q=Q(K,!1);return q!==void 0?d.has(q,this._key):!1},V.prototype.get=function(K){var q=Q(K,!1);return q!==void 0?d.get(q,this._key):void 0},V.prototype.set=function(K,q){var X=Q(K,!0);return X[this._key]=q,this},V.prototype.delete=function(K){var q=Q(K,!1);return q!==void 0?delete q[this._key]:!1},V.prototype.clear=function(){this._key=P()},V})();function P(){var V;do V="@@WeakMap@@"+oe();while(d.has(x,V));return x[V]=!0,V}function Q(V,K){if(!s.call(V,N)){if(!K)return;Object.defineProperty(V,N,{value:d.create()})}return V[N]}function Re(V,K){for(var q=0;q<K;++q)V[q]=Math.random()*255|0;return V}function Ne(V){if(typeof Uint8Array=="function"){var K=new Uint8Array(V);return typeof crypto<"u"?crypto.getRandomValues(K):typeof msCrypto<"u"?msCrypto.getRandomValues(K):Re(K,V),K}return Re(new Array(V),V)}function oe(){var V=Ne(w);V[6]=V[6]&79|64,V[8]=V[8]&191|128;for(var K="",q=0;q<w;++q){var X=V[q];(q===4||q===6||q===8)&&(K+="-"),X<16&&(K+="0"),K+=X.toString(16).toLowerCase()}return K}}function ac(w){return w.__=void 0,delete w.__,w}})})(t||(t={})),ip}zS();const YS="[object ArrayBuffer]";class U{static isArrayBuffer(e){return Object.prototype.toString.call(e)===YS}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=U.toUint8Array(e),s=U.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 kc="string",XS=/^[0-9a-f\s]+$/i,JS=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ZS=/^[a-zA-Z0-9-_]+$/;class cp{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=U.toUint8Array(e);let n="";for(let o=0;o<r.length;o++)n+=String.fromCharCode(r[o]);return decodeURIComponent(escape(n))}}class Pt{static toString(e,r=!1){const n=U.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 Y{static isHex(e){return typeof e===kc&&XS.test(e)}static isBase64(e){return typeof e===kc&&JS.test(e)}static isBase64Url(e){return typeof e===kc&&ZS.test(e)}static ToString(e,r="utf8"){const n=U.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 Pt.toString(n,!0);case"utf16":case"utf16be":return Pt.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 Pt.fromString(e,!0);case"utf16":case"utf16be":return Pt.fromString(e);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToBase64(e){const r=U.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(!Y.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(!Y.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=Y.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.FromBinary(e);case"utf8":return cp.fromString(e);case"utf16":case"utf16be":return Pt.fromString(e);case"utf16le":case"usc2":return Pt.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${r}'`)}}static ToUtf8String(e,r=Y.DEFAULT_UTF8_ENCODING){switch(r){case"ascii":return this.ToBinary(e);case"utf8":return cp.toString(e);case"utf16":case"utf16be":return Pt.toString(e);case"utf16le":case"usc2":return Pt.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=U.toUint8Array(e);let n="";for(let s=0;s<r.length;s++)n+=String.fromCharCode(r[s]);return n}static ToHex(e){const r=U.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(!Y.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 Pt.toString(e,r)}static FromUtf16String(e,r=!1){return Pt.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,"")||""}}Y.DEFAULT_UTF8_ENCODING="utf8";function QS(...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 ek(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 Hn(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 Zr(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 Xc(...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 Ny(){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=Hn(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,Hn(o,8)-n}function tk(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=Zr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let s=Zr(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 rk(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 ct(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 zl(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 gr(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 ua{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return zl(this.items)}}const hs=[new Uint8Array([1])],up="0123456789",xc="name",lp="valueHexView",nk="isHexOnly",sk="idBlock",ok="tagClass",ik="tagNumber",ak="isConstructed",ck="fromBER",uk="toBER",lk="local",Je="",Yt=new ArrayBuffer(0),la=new Uint8Array(0),eo="EndOfContent",Ty="OCTET STRING",By="BIT STRING";function Xt(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?U.toUint8Array(o.valueHex):la}fromBER(n,s,o,i){const a=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!gr(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",Yt)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Y.ToHex(this.valueHexView)}}},e.NAME="hexBlock",e}class yn{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=Je,warnings:n=[],valueBeforeDecode:s=la}={}){this.blockLength=e,this.error=r,this.warnings=n,this.valueBeforeDecodeView=U.toUint8Array(s)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Y.ToHex(this.valueBeforeDecodeView)}}}yn.NAME="baseBlock";class Fe extends yn{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'")}}Fe.NAME="valueBlock";class $y extends Xt(yn){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?U.toUint8Array(e.valueHex):la,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",Yt}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=Zr(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=U.toUint8Array(e);if(!gr(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=Hn(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}}}$y.NAME="identificationBlock";class Ry extends yn{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=U.toUint8Array(e);if(!gr(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=Hn(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=Zr(this.length,8);if(s.byteLength>127)return this.error="Too big length",Yt;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}}}Ry.NAME="lengthBlock";const H={};class _e extends yn{constructor({name:e=Je,optional:r=!1,primitiveSchema:n,...s}={},o){super(s),this.name=e,this.optional=r,n&&(this.primitiveSchema=n),this.idBlock=new $y(s),this.lenBlock=new Ry(s),this.valueBlock=o?new o(s):new Fe(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 ua;r||_y(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?Yt: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():Y.ToHex(this.toBER())}onAsciiEncoding(){const e=this.constructor.NAME,r=Y.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 rk(r,n)}}_e.NAME="BaseBlock";function _y(t){var e;if(t instanceof H.Constructed)for(const r of t.valueBlock.value)_y(r)&&(t.lenBlock.isIndefiniteForm=!0);return!!(!((e=t.lenBlock)===null||e===void 0)&&e.isIndefiniteForm)}class Yl extends _e{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=Je,...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}'`}}Yl.NAME="BaseStringBlock";class My extends Xt(Fe){constructor({isHexOnly:e=!0,...r}={}){super(r),this.isHexOnly=e}}My.NAME="PrimitiveValueBlock";var jy;class vo extends _e{constructor(e={}){super(e,My),this.idBlock.isConstructed=!1}}jy=vo;H.Primitive=jy;vo.NAME="PRIMITIVE";const Dy=100,Py=1e4,Ly=16*1024*1024,dk="Maximum ASN.1 nesting depth exceeded",fk="Maximum ASN.1 node count exceeded",pk="Maximum ASN.1 content length exceeded";function bo(t={}){var e,r,n;return{depth:0,maxDepth:(e=t.maxDepth)!==null&&e!==void 0?e:Dy,nodesCount:0,maxNodes:(r=t.maxNodes)!==null&&r!==void 0?r:Py,maxContentLength:(n=t.maxContentLength)!==null&&n!==void 0?n:Ly}}function hk(t){const e=new _e({},Fe);return e.error=t,{offset:-1,result:e}}function mk(t){if(t.nodesCount+=1,t.nodesCount>t.maxNodes)return fk}function yk(t,e){if(t>e.maxContentLength)return pk}function Xl(t,e,r,n){const s=n.depth+1;if(s>n.maxDepth)return hk(dk);n.depth=s;try{return da(t,e,r,n)}finally{n.depth-=1}}function gk(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=bo()){const s=e;let o=new _e({},Fe);const i=new yn;if(!gr(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=mk(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=yk(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=_e;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=H.EndOfContent;break;case 1:m=H.Boolean;break;case 2:m=H.Integer;break;case 3:m=H.BitString;break;case 4:m=H.OctetString;break;case 5:m=H.Null;break;case 6:m=H.ObjectIdentifier;break;case 10:m=H.Enumerated;break;case 12:m=H.Utf8String;break;case 13:m=H.RelativeObjectIdentifier;break;case 14:m=H.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:m=H.Sequence;break;case 17:m=H.Set;break;case 18:m=H.NumericString;break;case 19:m=H.PrintableString;break;case 20:m=H.TeletexString;break;case 21:m=H.VideotexString;break;case 22:m=H.IA5String;break;case 23:m=H.UTCTime;break;case 24:m=H.GeneralizedTime;break;case 25:m=H.GraphicString;break;case 26:m=H.VisibleString;break;case 27:m=H.GeneralString;break;case 28:m=H.UniversalString;break;case 29:m=H.CharacterString;break;case 30:m=H.BmpString;break;case 31:m=H.DATE;break;case 32:m=H.TimeOfDay;break;case 33:m=H.DateTime;break;case 34:m=H.Duration;break;default:{const p=o.idBlock.isConstructed?new H.Constructed:new H.Primitive;p.idBlock=o.idBlock,p.lenBlock=o.lenBlock,p.warnings=o.warnings,o=p}}break;default:m=o.idBlock.isConstructed?H.Constructed:H.Primitive}return o=gk(o,m),u=o.fromBER(t,e,l,n),o.valueBeforeDecodeView=t.subarray(s,s+o.blockLength),{offset:u,result:o}}function _n(t,e={}){if(!t.byteLength){const r=new _e({},Fe);return r.error="Input buffer has zero length",{offset:-1,result:r}}return da(U.toUint8Array(t).slice(),0,t.byteLength,bo(e))}function vk(t,e){return t?1:e}class Cr extends Fe{constructor({value:e=[],isIndefiniteForm:r=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=r}fromBER(e,r,n,s){const o=U.toUint8Array(e),i=s??bo();if(!gr(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(;vk(this.isIndefiniteForm,n)>0;){const c=Xl(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 ua;for(let s=0;s<this.value.length;s++)this.value[s].toBER(e,n);return r?Yt:n.final()}toJSON(){const e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(const r of this.value)e.value.push(r.toJSON());return e}}Cr.NAME="ConstructedValueBlock";var Uy;class ze extends _e{constructor(e={}){super(e,Cr),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(`
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(`
84
358
  `).map(s=>` ${s}`).join(`
85
359
  `));const r=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${r} :
86
360
  ${e.join(`
87
- `)}`:`${r} :`}}Uy=ze;H.Constructed=Uy;ze.NAME="CONSTRUCTED";class Vy extends Fe{fromBER(e,r,n){return r}toBER(e){return Yt}}Vy.override="EndOfContentValueBlock";var Hy;class Jl extends _e{constructor(e={}){super(e,Vy),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Hy=Jl;H.EndOfContent=Hy;Jl.NAME=eo;var Fy;class Qr extends _e{constructor(e={}){super(e,Fe),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}`}}Fy=Qr;H.Null=Fy;Qr.NAME="NULL";class Wy extends Xt(Fe){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=U.toUint8Array(r.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,r,n){const s=U.toUint8Array(e);return gr(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,Ny.call(this),this.blockLength=n,r+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}Wy.NAME="BooleanValueBlock";var Ky;let fa=class extends _e{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,Wy),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};Ky=fa;H.Boolean=Ky;fa.NAME="BOOLEAN";class Gy extends Xt(Cr){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=Cr.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!==Ty)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?Cr.prototype.toBER.call(this,e,r):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}Gy.NAME="OctetStringValueBlock";var Zl;let Gr=class extends _e{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},Gy),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??bo(),c=Xl(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 ze.prototype.onAsciiEncoding.call(this);const e=this.constructor.NAME,r=Y.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 Zl&&e.push(r.valueBlock.valueHexView);return U.concat(e)}};Zl=Gr;H.OctetString=Zl;Gr.NAME=Ty;class qy extends Xt(Cr){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=Cr.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!==By)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=U.toUint8Array(e);if(!gr(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??bo(),l=Xl(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 Cr.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}}}qy.NAME="BitStringValueBlock";var zy;let qr=class extends _e{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},qy),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 ze.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}`}}};zy=qr;H.BitString=zy;qr.NAME=By;var Yy;function bk(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=Xc(new Uint8Array([u%10]),o):o[i-d]=u%10;return r[0]>0&&(o=Xc(r,o)),o}function dp(t){if(t>=hs.length)for(let e=hs.length;e<=t;e++){const r=new Uint8Array([0]);let n=hs[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=Xc(r,n)),hs.push(n)}return hs[t]}function wk(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 Ql extends Xt(Fe){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=Ny.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(tk(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=wk(dp(n),r),i="-"):r=bk(r,dp(n))),n++,s>>=1}for(let c=0;c<r.length;c++)r[c]&&(a=!0),a&&(i+=up.charAt(r[c]));return a===!1&&(i+=up.charAt(0)),i}}Yy=Ql;Ql.NAME="IntegerValueBlock";Object.defineProperty(Yy.prototype,"valueHex",{set:function(t){this.valueHexView=new Uint8Array(t),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Us;class ts extends _e{constructor(e={}){super(e,Ql),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 ua,s=r.toString(16).replace(/^-/,""),o=new Uint8Array(Y.FromHex(s));if(r<0){const a=new Uint8Array(o.length+(o[0]&128?1:0));a[0]|=128;const u=BigInt(`0x${Y.ToHex(a)}`)+r,l=U.toUint8Array(Y.FromHex(u.toString(16)));l[0]|=128,n.write(l)}else o[0]&128&&n.write(new Uint8Array([0])),n.write(o);return new Us({valueHex:n.final()})}convertToDER(){const e=new Us({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Us({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}Us=ts;H.Integer=Us;ts.NAME="INTEGER";var Xy;class pa extends ts{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Xy=pa;H.Enumerated=Xy;pa.NAME="ENUMERATED";class Jc extends Xt(Fe){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=U.toUint8Array(e);if(!gr(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=Hn(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=Zr(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Yt;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=Y.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}}}Jc.NAME="sidBlock";class Jy extends Fe{constructor({value:e=Je,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let s=r;for(;n>0;){const o=new Jc;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,Yt;r.push(s)}return zl(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 Jc;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}}Jy.NAME="ObjectIdentifierValueBlock";var Zy;class ha extends _e{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Jy),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}Zy=ha;H.ObjectIdentifier=Zy;ha.NAME="OBJECT IDENTIFIER";class Zc extends Xt(yn){constructor({valueDec:e=0,...r}={}){super(r),this.valueDec=e}fromBER(e,r,n){if(n===0)return r;const s=U.toUint8Array(e);if(!gr(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=Hn(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=Zr(this.valueDec,7);if(r.byteLength===0)return this.error="Error during encoding SID value",Yt;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=Y.ToHex(this.valueHexView):e=this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}Zc.NAME="relativeSidBlock";class Qy extends Fe{constructor({value:e=Je,...r}={}){super(r),this.value=[],e&&this.fromString(e)}fromBER(e,r,n){let s=r;for(;n>0;){const o=new Zc;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,Yt;n.push(o)}return zl(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 Zc;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}}Qy.NAME="RelativeObjectIdentifierValueBlock";var eg;class ma extends _e{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,Qy),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}eg=ma;H.RelativeObjectIdentifier=eg;ma.NAME="RelativeObjectIdentifier";var tg;class $t extends ze{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}tg=$t;H.Sequence=tg;$t.NAME="SEQUENCE";var rg;let Ft=class extends ze{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};rg=Ft;H.Set=rg;Ft.NAME="SET";class ng extends Xt(Fe){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=Je}toJSON(){return{...super.toJSON(),value:this.value}}}ng.NAME="StringValueBlock";class sg extends ng{}sg.NAME="SimpleStringValueBlock";class ft extends Yl{constructor({...e}={}){super(e,sg)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,U.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}}ft.NAME="SIMPLE STRING";class og extends ft{fromBuffer(e){this.valueBlock.valueHexView=U.toUint8Array(e);try{this.valueBlock.value=Y.ToUtf8String(e)}catch(r){this.warnings.push(`Error during "decodeURIComponent": ${r}, using raw string`),this.valueBlock.value=Y.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(Y.FromUtf8String(e)),this.valueBlock.value=e}}og.NAME="Utf8StringValueBlock";var ig;class vr extends og{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}ig=vr;H.Utf8String=ig;vr.NAME="UTF8String";class ag extends ft{fromBuffer(e){this.valueBlock.value=Y.ToUtf16String(e),this.valueBlock.valueHexView=U.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(Y.FromUtf16String(e))}}ag.NAME="BmpStringValueBlock";var cg;class ya extends ag{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}cg=ya;H.BmpString=cg;ya.NAME="BMPString";class ug extends ft{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=Zr(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}}ug.NAME="UniversalStringValueBlock";var lg;class ga extends ug{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}lg=ga;H.UniversalString=lg;ga.NAME="UniversalString";var dg;class va extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}dg=va;H.NumericString=dg;va.NAME="NumericString";var fg;class ba extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}fg=ba;H.PrintableString=fg;ba.NAME="PrintableString";var pg;class wa extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}pg=wa;H.TeletexString=pg;wa.NAME="TeletexString";var hg;class Aa extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}hg=Aa;H.VideotexString=hg;Aa.NAME="VideotexString";var mg;class Sa extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}mg=Sa;H.IA5String=mg;Sa.NAME="IA5String";var yg;class ka extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}yg=ka;H.GraphicString=yg;ka.NAME="GraphicString";var gg;class wo extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}gg=wo;H.VisibleString=gg;wo.NAME="VisibleString";var vg;class xa extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}vg=xa;H.GeneralString=vg;xa.NAME="GeneralString";var bg;class Ea extends ft{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}bg=Ea;H.CharacterString=bg;Ea.NAME="CharacterString";var wg;class Ao extends wo{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,U.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]=ct(this.year<2e3?this.year-1900:this.year-2e3,2),r[1]=ct(this.month,2),r[2]=ct(this.day,2),r[3]=ct(this.hour,2),r[4]=ct(this.minute,2),r[5]=ct(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}}}wg=Ao;H.UTCTime=wg;Ao.NAME="UTCTime";var Ag;class Ia extends Ao{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 y=parseInt(p.substring(0,2),10);if(isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");if(a=d*y,p.length===4){if(y=parseInt(p.substring(2,4),10),isNaN(y.valueOf()))throw new Error("Wrong input string for conversion");c=d*y}}}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(ct(this.year,4)),r.push(ct(this.month,2)),r.push(ct(this.day,2)),r.push(ct(this.hour,2)),r.push(ct(this.minute,2)),r.push(ct(this.second,2)),this.millisecond!==0&&(r.push("."),r.push(ct(this.millisecond,3))),r.push("Z"),r.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}Ag=Ia;H.GeneralizedTime=Ag;Ia.NAME="GeneralizedTime";var Sg;class ed extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}Sg=ed;H.DATE=Sg;ed.NAME="DATE";var kg;class td extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}kg=td;H.TimeOfDay=kg;td.NAME="TimeOfDay";var xg;class rd extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}xg=rd;H.DateTime=xg;rd.NAME="DateTime";var Eg;class nd extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Eg=nd;H.Duration=Eg;nd.NAME="Duration";var Ig;class sd extends vr{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Ig=sd;H.TIME=Ig;sd.NAME="TIME";class en{constructor({name:e=Je,optional:r=!1}={}){this.name=e,this.optional=r}}class od extends en{constructor({value:e=[],...r}={}){super(r),this.value=e}}class bi extends en{constructor({value:e=new en,local:r=!1,...n}={}){super(n),this.value=e,this.local=r}}class Ak{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=U.toUint8Array(e)}constructor({data:e=la}={}){this.dataView=U.toUint8Array(e)}fromBER(e,r,n){const s=r+n;return this.dataView=U.toUint8Array(e).subarray(r,s),s}toBER(e){return this.dataView.slice().buffer}}function xr(t,e,r){if(r instanceof od){for(const o of r.value)if(xr(t,e,o).verified)return{verified:!0,result:t};{const o={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(xc)&&(o.name=r.name),o}}if(r instanceof en)return r.hasOwnProperty(xc)&&(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(!(sk in r))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(ck in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(!(uk 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(ok)===!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(ik)===!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(ak)===!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==e.idBlock.isConstructed)return{verified:!1,result:t};if(!(nk 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(!(lp 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,Je),r.name&&(t[r.name]=e)),r instanceof H.Constructed){let o=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,Je),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,Je),r.name&&(delete t[r.name],u.name=r.name)),u}}else if(r.valueBlock.value[0]instanceof bi){if(i=xr(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,Je),r.name&&delete t[r.name]),i;if(xc in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){let u={};lk 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=xr(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,Je),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,Je),r.name&&(delete t[r.name],c.name=r.name)),c}return{verified:!0,result:t}}if(r.primitiveSchema&&lp 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,Je),r.name&&(delete t[r.name],i.name=r.name)),i}return xr(t,o.result,r.primitiveSchema)}return{verified:!0,result:t}}function Sk(t,e){if(!(e instanceof Object))return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};const r=da(U.toUint8Array(t));return r.offset===-1?{verified:!1,result:r.result}:xr(r.result,r.result,e)}const Cg=Object.freeze(Object.defineProperty({__proto__:null,Any:en,BaseBlock:_e,BaseStringBlock:Yl,BitString:qr,BmpString:ya,Boolean:fa,CharacterString:Ea,Choice:od,Constructed:ze,DATE:ed,DEFAULT_MAX_CONTENT_LENGTH:Ly,DEFAULT_MAX_DEPTH:Dy,DEFAULT_MAX_NODES:Py,DateTime:rd,Duration:nd,EndOfContent:Jl,Enumerated:pa,GeneralString:xa,GeneralizedTime:Ia,GraphicString:ka,HexBlock:Xt,IA5String:Sa,Integer:ts,Null:Qr,NumericString:va,ObjectIdentifier:ha,OctetString:Gr,Primitive:vo,PrintableString:ba,RawData:Ak,RelativeObjectIdentifier:ma,Repeated:bi,Sequence:$t,Set:Ft,TIME:sd,TeletexString:wa,TimeOfDay:td,UTCTime:Ao,UniversalString:ga,Utf8String:vr,ValueBlock:Fe,VideotexString:Aa,ViewWriter:ua,VisibleString:wo,compareSchema:xr,fromBER:_n,verifySchema:Sk},Symbol.toStringTag,{value:"Module"})),kk="[object ArrayBuffer]",xk="[object SharedArrayBuffer]";function Og(t){return Object.prototype.toString.call(t)}function Ek(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"&&id(e.buffer)}function Ng(t){return Og(t)===kk}function Ik(t){return typeof SharedArrayBuffer<"u"&&Og(t)===xk}function id(t){return Ng(t)||Ik(t)}function Ck(t){return Ek(t)}function Ca(t){return id(t)||Ck(t)}function Tg(t){if(!Ca(t))throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function tn(t){return Tg(t),id(t)?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function At(t){if(Tg(t),Ng(t))return t;const e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(tn(t)),e}function Ok(t,e,r={}){const n=tn(t),s=tn(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 Bg(t){const e=tn(t);let r="";for(const n of e)r+=String.fromCharCode(n);return r}function $g(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r)&255;return e}function Nk(t){return typeof t=="string"}const Tk=/^[0-9a-f]$/i,Bk=[" "," ",`
88
- `,"\r",":","-","."];function $k(t){return t.separators==="none"?[]:!t.separators||t.separators==="common"?Bk:t.separators}function Rk(t){if(!t)throw new TypeError("Hex separators must be non-empty strings")}function _k(t,e,r){for(const n of r)if(t.startsWith(n,e))return n}function Mk(t){const e=/[A-F]/.test(t),r=/[a-f]/.test(t);return e&&!r?"upper":"lower"}function jk(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
89
363
  `?`\r
90
364
  `:`
91
- `}function fp(t){return t.replace(/[^0-9a-f]/gi,"")}function Dk(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 Pk(t){const e=t.trim(),r=/^0x/i.test(e)?"0x":"",n=r?e.slice(2):e,s=jk(n),o=n.split(/\r\n|\n/).filter(u=>u.length>0),i=o[0]?.trim()??"",a=Dk(i),c={case:Mk(e),prefix:r};if(a&&(c.group=a),s&&o.length>1){const u=fp(o[0]??"").length/2;u>0&&o.slice(0,-1).every(l=>fp(l).length/2===u)&&(c.line={bytesPerLine:u,separator:s})}return c}function Lk(t,e){const r=e.allowPrefix??!0,n=[...$k(e)].sort((a,c)=>c.length-a.length);for(const a of n)Rk(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(Tk.test(c)){o+=c,i=!1,a+=1;continue}const u=_k(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 pp(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 Oa(t,e={}){return Lk(t,e)}function Uk(t,e={}){if(typeof t!="string")return!1;try{return Oa(t,e),!0}catch{return!1}}function Na(t,e={}){const r=tn(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??`
92
- `,c=[];for(let u=0;u<s.length;u+=i)c.push(pp(s.slice(u,u+i),e.group));o=c.join(a)}else o=pp(s,e.group);return`${e.prefix??""}${o}`}function Rg(t,e={}){const r=Oa(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 Vk(t,e={}){const r=Oa(t,e);return{bytes:Rg(r),format:Pk(t),normalized:r}}function Hk(t,e){return Na(t,e)}function Fk(t){return new TextEncoder().encode(t)}function Wk(t){return new TextDecoder("utf-8",{fatal:!1}).decode(tn(t))}function _g(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 Mg(t,e={}){const r=At(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 Kk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function jg(){return globalThis.Buffer}function Ta(t){return t.replace(/[\n\r\t ]/g,"")}function Gk(t){const e=t.length%4;return e?t+"=".repeat(4-e):t}function ad(t){if(typeof t!="string")return!1;const e=Ta(t);return e===""||Kk.test(e)}function Dg(t,e){const r=tn(t),n=jg();return n?n.from(r).toString("base64"):btoa(Bg(r))}function Pg(t,e){const r=Ta(t);if(!ad(r))throw new TypeError("Input is not valid Base64 text");const n=jg();return n?new Uint8Array(n.from(r,"base64")):$g(atob(r))}const to={encode:Dg,decode:Pg,is:ad,normalize:Ta,pad:Gk},qk=/^[A-Za-z0-9_-]*$/;function cd(t){return t.replace(/[\n\r\t ]/g,"")}function Lg(t){return typeof t=="string"&&qk.test(cd(t))}function zk(t,e){return to.encode(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Yk(t,e){const r=cd(t);if(!Lg(r))throw new TypeError("Input is not valid Base64Url text");return to.decode(to.pad(r.replace(/-/g,"+").replace(/_/g,"/")))}const Xk=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,hp=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function Ug(t){if(!Xk.test(t))throw new TypeError(`Invalid PEM label '${t}'`)}function Jk(t,e){const r=[];for(let n=0;n<t.length;n+=e)r.push(t.slice(n,n+e));return r}function Zk(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,`
93
367
  `).split(`
94
- `).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 Qk(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
95
369
  `:`
96
- `}function Vg(t,e={}){const r=[],n=e.label;let s;for(hp.lastIndex=0;s=hp.exec(t);){const o=s[1].trim();if(n&&o!==n)continue;Ug(o);const i=Zk(s[2]);r.push({label:o,data:to.decode(i.base64Text),headers:i.headers,lineLength:i.base64Lines[0]?.length??64,newline:Qk(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 ud(t,e,r={}){Ug(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??`
97
- `,o=[`-----BEGIN ${t}-----`];if(r.headers){for(const[i,a]of Object.entries(r.headers))o.push(`${i}: ${a}`);o.push("")}return o.push(...Jk(to.encode(e),n)),o.push(`-----END ${t}-----`),`${o.join(s)}${s}`}function ex(t,e={}){return Vg(t,e).map(({lineLength:r,newline:n,...s})=>s)}function tx(t,e){const[r]=ex(t,{label:e,strict:!0});return r.data}function rx(t,e={}){const[r]=Vg(t,{...e,strict:!0}),n={label:r.label,headers:r.headers,lineLength:r.lineLength,newline:r.newline};return{bytes:r.data,format:n,normalized:ud(r.label,r.data,n)}}function nx(t,e){return ud(e.label,t,e)}const sx={name:"pem",encode:(t,e)=>{if(!e?.label)throw new TypeError("PEM label is required");return ud(e.label,t,e)},decode:(t,e)=>tx(t,e?.label),format:nx,is:t=>typeof t=="string"&&/-----BEGIN [^-]+-----/.test(t),parse:rx};function Ut(t){return t.trim().toLowerCase()}function ox(t){return t instanceof Error?t:new Error(String(t))}function mp(t,e,r){for(const n of[r.name,...r.aliases??[]])t.delete(Ut(n));e.delete(Ut(r.name))}function Ec(t,e,r){const n=t[r];if(typeof n!="function")throw new Error(`Converter '${e}' does not support ${r}()`);return n}function ix(t,e,r){const n=Ut(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 ax(t=[]){const e=new Map,r=new Set,n={register(s,o={}){if(!s.name||!Ut(s.name))throw new TypeError("Converter name is required");const i=[...new Set([s.name,...s.aliases??[]].map(Ut))],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)mp(e,r,c);for(const c of i)e.set(c,s);return r.add(Ut(s.name)),this},unregister(s){const o=e.get(Ut(s));return o?(mp(e,r,o),!0):!1},has(s){return e.has(Ut(s))},get(s){const o=e.get(Ut(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:ox(a)}}},normalize(s,o,i){const a=this.get(s);return Ec(a,s,"normalize").call(a,o,i)},parse(s,o,i){const a=this.get(s);return Ec(a,s,"parse").call(a,o,i)},format(s,o,i){const a=this.get(s);return Ec(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(Ut(c))),a=new Map;for(const c of i){const u=this.get(c),l=ix(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 cx={name:"binary",aliases:["latin1"],encode:Bg,decode:$g,is:Nk},ux={name:"hex",encode:Na,decode:Rg,format:Hk,is:Uk,normalize:Oa,parse:Vk},lx={name:"base64",aliases:["b64"],encode:Dg,decode:Pg,is:ad,normalize:Ta},dx={name:"base64url",aliases:["base64-url","b64url"],encode:zk,decode:Yk,is:Lg,normalize:cd},fx={name:"utf8",aliases:["utf-8"],encode:t=>Wk(t),decode:t=>Fk(t),is:t=>typeof t=="string"},px={name:"utf16be",aliases:["utf16","utf-16","utf-16be"],encode:t=>Mg(t),decode:t=>_g(t),is:t=>typeof t=="string"},hx={name:"utf16le",aliases:["utf-16le","ucs2","usc2"],encode:t=>Mg(t,{littleEndian:!0}),decode:t=>_g(t,{littleEndian:!0}),is:t=>typeof t=="string"},mx=[cx,ux,lx,dx,fx,px,hx,sx];ax(mx);var O;(function(t){t[t.Sequence=0]="Sequence",t[t.Set=1]="Set",t[t.Choice=2]="Choice"})(O||(O={}));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 Ba{unusedBits=0;value=new ArrayBuffer(0);constructor(e,r=0){if(e)if(typeof e=="number")this.fromNumber(e);else if(Ca(e))this.unusedBits=r,this.value=At(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof qr))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=At(e.valueBlock.valueHex),this}toASN(){return new qr({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new qr({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 ue{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){typeof e=="number"?this.buffer=new ArrayBuffer(e):Ca(e)?this.buffer=At(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Gr))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=At(e.valueBlock.valueHex),this}toASN(){return new Gr({valueHex:this.buffer})}toSchema(e){return new Gr({name:e})}}const yx={fromASN:t=>t instanceof Qr?null:At(t.valueBeforeDecodeView),toASN:t=>{if(t===null)return new Qr;const e=_n(t);if(e.result.error)throw new Error(e.result.error);return e.result}},gx={fromASN:t=>t.valueBlock.valueHexView.byteLength>=4?t.valueBlock.toString():t.valueBlock.valueDec,toASN:t=>new ts({value:+t})},vx={fromASN:t=>t.valueBlock.valueDec,toASN:t=>new pa({value:t})},be={fromASN:t=>At(t.valueBlock.valueHexView),toASN:t=>new ts({valueHex:t})},bx={fromASN:t=>At(t.valueBlock.valueHexView),toASN:t=>new qr({valueHex:t})},wx={fromASN:t=>t.valueBlock.toString(),toASN:t=>new ha({value:t})},Ax={fromASN:t=>t.valueBlock.toString(),toASN:t=>new ma({value:t})},Sx={fromASN:t=>t.valueBlock.value,toASN:t=>new fa({value:t})},wi={fromASN:t=>At(t.valueBlock.valueHexView),toASN:t=>new Gr({valueHex:t})},kx={fromASN:t=>new ue(t.getValue()),toASN:t=>t.toASN()};function St(t){return{fromASN:e=>e.valueBlock.value,toASN:e=>new t({value:e})}}const Hg=St(vr),xx=St(ya),Ex=St(ga),Ix=St(va),Cx=St(ba),Ox=St(wa),Nx=St(Aa),Tx=St(Sa),Bx=St(ka),$x=St(wo),Rx=St(xa),_x=St(Ea),Mx={fromASN:t=>t.toDate(),toASN:t=>new Ao({valueDate:t})},jx={fromASN:t=>t.toDate(),toASN:t=>new Ia({valueDate:t})},Dx={fromASN:()=>null,toASN:()=>new Qr};function Vs(t){switch(t){case b.Any:return yx;case b.BitString:return bx;case b.BmpString:return xx;case b.Boolean:return Sx;case b.CharacterString:return _x;case b.Enumerated:return vx;case b.GeneralString:return Rx;case b.GeneralizedTime:return jx;case b.GraphicString:return Bx;case b.IA5String:return Tx;case b.Integer:return gx;case b.Null:return Dx;case b.NumericString:return Ix;case b.ObjectIdentifier:return wx;case b.RelativeObjectIdentifier:return Ax;case b.OctetString:return wi;case b.PrintableString:return Cx;case b.TeletexString:return Ox;case b.UTCTime:return Mx;case b.UniversalString:return Ex;case b.Utf8String:return Hg;case b.VideotexString:return Nx;case b.VisibleString:return $x;default:return null}}function ir(t){return typeof t=="function"&&t.prototype?t.prototype.toASN&&t.prototype.fromASN?!0:ir(t.prototype):!!(t&&typeof t=="object"&&"toASN"in t&&"fromASN"in t)}function Fg(t){if(t){const e=Object.getPrototypeOf(t);return e?.prototype?.constructor===Array?!0:Fg(e)}return!1}function Px(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 Lx{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:O.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=b[i.type],d=Cg[l];if(!d)throw new Error(`Cannot get ASN1 class by name '${l}'`);c=new d({name:a})}else ir(i.type)?c=new i.type().toSchema(a):i.optional?this.get(i.type).type===O.Choice?c=new en({name:a}):(c=this.create(i.type,!1),c.name=a):c=new en({name:a});const u=!!i.optional||i.defaultValue!==void 0;if(i.repeated){c.name="";const l=i.repeated==="set"?Ft:$t;c=new l({name:"",value:[new bi({name:a,value:c})]})}if(i.context!==null&&i.context!==void 0)if(i.implicit)if(typeof i.type=="number"||ir(i.type)){const l=i.repeated?ze:vo;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 ze({name:l?"":a,optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:d}))}else s.push(new ze({optional:u,idBlock:{tagClass:3,tagNumber:i.context},value:[c]}));else c.optional=u,s.push(c)}switch(n.type){case O.Sequence:return new $t({value:s,name:""});case O.Set:return new Ft({value:s,name:""});case O.Choice:return new od({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 De=new Lx,$=t=>e=>{let r;De.has(e)?r=De.get(e):(r=De.createDefault(e),De.set(e,r)),Object.assign(r,t)},h=t=>(e,r)=>{let n;De.has(e.constructor)?n=De.get(e.constructor):(n=De.createDefault(e.constructor),De.set(e.constructor,n));const s=Object.assign({},t);if(typeof s.type=="number"&&!s.converter){const o=Vs(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 ms extends Error{schemas=[]}class Ux{static parse(e,r,n){const s=_n(At(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(ir(r))return new r().fromASN(e);const s=De.get(r);De.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 Fg(r)?this.handleArrayTypes(e,s,r,n):(this.processSchemaItems(s,a,c,n),c)}catch(s){throw s instanceof ms&&s.schemas.push(r.name),s}}static handleChoiceTypes(e,r,n,s,o){if(e.constructor===ze&&r.type===O.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"&&De.has(a.type)){const c=De.get(a.type);if(c&&c.type===O.Sequence){const u=new $t;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===ze&&r.type!==O.Choice){const i=new ze({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===O.Sequence){const o=xr({},e,s);if(!o.verified)throw new ms(`Data does not match to ${n.name} ASN1 schema.${o.result.error?` ${o.result.error}`:""}`);return o}else{const o=xr({},e,s);if(!o.verified)throw new ms(`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=Vs(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=Vs(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"&&De.has(e.type)&&De.get(e.type).type===O.Choice}static processOptionalChoiceField(e,r){try{return{processed:!0,value:this.fromASN(e,r.type)}}catch(n){if(n instanceof ms&&/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=Vs(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"||ir(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??(ir(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"?$t:Ft,i=new o;i.valueBlock=e.valueBlock;const a=_n(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(ir(n))a=new n().toSchema("");else{const c=b[n],u=Cg[c];if(!u)throw new Error(`Cannot get '${c}' class from asn1js module`);a=new u}a.valueBlock=i.valueBlock,i=_n(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 ms&&/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=De.get(n);if(s.type===O.Sequence){const o=new $t;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===O.Set){const o=new Ft;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 ld{static serialize(e){return e instanceof _e?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){if(e&&typeof e=="object"&&ir(e))return e.toASN();if(!(e&&typeof e=="object"))throw new TypeError("Parameter 1 should be type of Object.");const r=e.constructor,n=De.get(r);De.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=Vs(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"&&Px(this.serialize(a.defaultValue),this.serialize(c)))continue;const u=ld.toAsnItem(a,i,r,c);if(typeof a.context=="number")if(a.implicit)if(!a.repeated&&(typeof a.type=="number"||ir(a.type))){const l={};l.valueHex=u instanceof Qr?At(u.valueBeforeDecodeView):u.valueBlock.toBER(),s.push(new vo({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},...l}))}else s.push(new ze({optional:a.optional,idBlock:{tagClass:3,tagNumber:a.context},value:u.valueBlock.value}));else s.push(new ze({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 O.Sequence:o=new $t({value:s});break;case O.Set:o=new Ft({value:s});break;case O.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 ${b[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"?$t:Ft;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"?$t:Ft;o=new a({value:i})}else o=this.toASN(s);return o}}class ce extends Array{constructor(e=[]){if(typeof e=="number")super(e);else{super();for(const r of e)this.push(r)}}}class D{static serialize(e){return ld.serialize(e)}static parse(e,r,n){return Ux.parse(e,r,n)}static toString(e,r){const n=Ca(e)?At(e):D.serialize(e),s=_n(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 te(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 ge(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 yp{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(Na(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 Qc,eu,tu;let Ve=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([h({type:b.TeletexString})],Ve.prototype,"teletexString",void 0);f([h({type:b.PrintableString})],Ve.prototype,"printableString",void 0);f([h({type:b.UniversalString})],Ve.prototype,"universalString",void 0);f([h({type:b.Utf8String})],Ve.prototype,"utf8String",void 0);f([h({type:b.BmpString})],Ve.prototype,"bmpString",void 0);Ve=f([$({type:O.Choice})],Ve);let Fn=class extends Ve{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?Na(this.anyValue):super.toString())}};f([h({type:b.IA5String})],Fn.prototype,"ia5String",void 0);f([h({type:b.Any})],Fn.prototype,"anyValue",void 0);Fn=f([$({type:O.Choice})],Fn);class $a{type="";value=new Fn;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],$a.prototype,"type",void 0);f([h({type:Fn})],$a.prototype,"value",void 0);let Wn=Qc=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Qc.prototype)}};Wn=Qc=f([$({type:O.Set,itemType:$a})],Wn);let ru=eu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,eu.prototype)}};ru=eu=f([$({type:O.Sequence,itemType:Wn})],ru);let Ie=tu=class extends ru{constructor(e){super(e),Object.setPrototypeOf(this,tu.prototype)}};Ie=tu=f([$({type:O.Sequence})],Ie);const Vx={fromASN:t=>yp.toString(wi.fromASN(t)),toASN:t=>wi.toASN(yp.fromString(t))};class ro{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],ro.prototype,"typeId",void 0);f([h({type:b.Any,context:0})],ro.prototype,"value",void 0);class dd{nameAssigner;partyName=new Ve;constructor(e={}){Object.assign(this,e)}}f([h({type:Ve,optional:!0,context:0,implicit:!0})],dd.prototype,"nameAssigner",void 0);f([h({type:Ve,context:1,implicit:!0})],dd.prototype,"partyName",void 0);let ne=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};f([h({type:ro,context:0,implicit:!0})],ne.prototype,"otherName",void 0);f([h({type:b.IA5String,context:1,implicit:!0})],ne.prototype,"rfc822Name",void 0);f([h({type:b.IA5String,context:2,implicit:!0})],ne.prototype,"dNSName",void 0);f([h({type:b.Any,context:3,implicit:!0})],ne.prototype,"x400Address",void 0);f([h({type:Ie,context:4,implicit:!1})],ne.prototype,"directoryName",void 0);f([h({type:dd,context:5})],ne.prototype,"ediPartyName",void 0);f([h({type:b.IA5String,context:6,implicit:!0})],ne.prototype,"uniformResourceIdentifier",void 0);f([h({type:b.OctetString,context:7,implicit:!0,converter:Vx})],ne.prototype,"iPAddress",void 0);f([h({type:b.ObjectIdentifier,context:8,implicit:!0})],ne.prototype,"registeredID",void 0);ne=f([$({type:O.Choice})],ne);const fd="1.3.6.1.5.5.7",Hx=`${fd}.1`,rs=`${fd}.3`,Ra=`${fd}.48`,gp=`${Ra}.1`,vp=`${Ra}.2`,bp=`${Ra}.3`,wp=`${Ra}.5`,br="2.5.29";var nu;const su=`${Hx}.1`;class So{accessMethod="";accessLocation=new ne;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],So.prototype,"accessMethod",void 0);f([h({type:ne})],So.prototype,"accessLocation",void 0);let Tn=nu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,nu.prototype)}};Tn=nu=f([$({type:O.Sequence,itemType:So})],Tn);const ou=`${br}.35`;class pd extends ue{}class Wr{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}}f([h({type:pd,context:0,optional:!0,implicit:!0})],Wr.prototype,"keyIdentifier",void 0);f([h({type:ne,context:1,optional:!0,implicit:!0,repeated:"sequence"})],Wr.prototype,"authorityCertIssuer",void 0);f([h({type:b.Integer,context:2,optional:!0,implicit:!0,converter:be})],Wr.prototype,"authorityCertSerialNumber",void 0);const Wg=`${br}.19`;class Ai{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Boolean,defaultValue:!1})],Ai.prototype,"cA",void 0);f([h({type:b.Integer,optional:!0})],Ai.prototype,"pathLenConstraint",void 0);var iu;let He=iu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,iu.prototype)}};He=iu=f([$({type:O.Sequence,itemType:ne})],He);var au;let Ap=au=class extends He{constructor(e){super(e),Object.setPrototypeOf(this,au.prototype)}};Ap=au=f([$({type:O.Sequence})],Ap);var cu;const Kg=`${br}.32`;let dr=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};f([h({type:b.IA5String})],dr.prototype,"ia5String",void 0);f([h({type:b.VisibleString})],dr.prototype,"visibleString",void 0);f([h({type:b.BmpString})],dr.prototype,"bmpString",void 0);f([h({type:b.Utf8String})],dr.prototype,"utf8String",void 0);dr=f([$({type:O.Choice})],dr);class hd{organization=new dr;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}}f([h({type:dr})],hd.prototype,"organization",void 0);f([h({type:b.Integer,repeated:"sequence"})],hd.prototype,"noticeNumbers",void 0);class md{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}}f([h({type:hd,optional:!0})],md.prototype,"noticeRef",void 0);f([h({type:dr,optional:!0})],md.prototype,"explicitText",void 0);let Si=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};f([h({type:b.IA5String})],Si.prototype,"cPSuri",void 0);f([h({type:md})],Si.prototype,"userNotice",void 0);Si=f([$({type:O.Choice})],Si);class yd{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],yd.prototype,"policyQualifierId",void 0);f([h({type:b.Any})],yd.prototype,"qualifier",void 0);class _a{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],_a.prototype,"policyIdentifier",void 0);f([h({type:yd,repeated:"sequence",optional:!0})],_a.prototype,"policyQualifiers",void 0);let ki=cu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,cu.prototype)}};ki=cu=f([$({type:O.Sequence,itemType:_a})],ki);let xi=class{value;constructor(e=0){this.value=e}};f([h({type:b.Integer})],xi.prototype,"value",void 0);xi=f([$({type:O.Choice})],xi);let Sp=class extends xi{};Sp=f([$({type:O.Choice})],Sp);var uu;const lu=`${br}.31`;var It;(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"})(It||(It={}));class Gg extends Ba{toJSON(){const e=[],r=this.toNumber();return r&It.aACompromise&&e.push("aACompromise"),r&It.affiliationChanged&&e.push("affiliationChanged"),r&It.cACompromise&&e.push("cACompromise"),r&It.certificateHold&&e.push("certificateHold"),r&It.cessationOfOperation&&e.push("cessationOfOperation"),r&It.keyCompromise&&e.push("keyCompromise"),r&It.privilegeWithdrawn&&e.push("privilegeWithdrawn"),r&It.superseded&&e.push("superseded"),r&It.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let rn=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};f([h({type:ne,context:0,repeated:"sequence",implicit:!0})],rn.prototype,"fullName",void 0);f([h({type:Wn,context:1,implicit:!0})],rn.prototype,"nameRelativeToCRLIssuer",void 0);rn=f([$({type:O.Choice})],rn);class ns{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}}f([h({type:rn,context:0,optional:!0})],ns.prototype,"distributionPoint",void 0);f([h({type:Gg,context:1,optional:!0,implicit:!0})],ns.prototype,"reasons",void 0);f([h({type:ne,context:2,optional:!0,repeated:"sequence",implicit:!0})],ns.prototype,"cRLIssuer",void 0);let Mn=uu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,uu.prototype)}};Mn=uu=f([$({type:O.Sequence,itemType:ns})],Mn);var du;let kp=du=class extends Mn{constructor(e){super(e),Object.setPrototypeOf(this,du.prototype)}};kp=du=f([$({type:O.Sequence,itemType:ns})],kp);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([h({type:rn,context:0,optional:!0})],qe.prototype,"distributionPoint",void 0);f([h({type:b.Boolean,context:1,defaultValue:qe.ONLY,implicit:!0})],qe.prototype,"onlyContainsUserCerts",void 0);f([h({type:b.Boolean,context:2,defaultValue:qe.ONLY,implicit:!0})],qe.prototype,"onlyContainsCACerts",void 0);f([h({type:Gg,context:3,optional:!0,implicit:!0})],qe.prototype,"onlySomeReasons",void 0);f([h({type:b.Boolean,context:4,defaultValue:qe.ONLY,implicit:!0})],qe.prototype,"indirectCRL",void 0);f([h({type:b.Boolean,context:5,defaultValue:qe.ONLY,implicit:!0})],qe.prototype,"onlyContainsAttributeCerts",void 0);var Hs;(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"})(Hs||(Hs={}));let fu=class{reason=Hs.unspecified;constructor(e=Hs.unspecified){this.reason=e}toJSON(){return Hs[this.reason]}toString(){return this.toJSON()}};f([h({type:b.Enumerated})],fu.prototype,"reason",void 0);fu=f([$({type:O.Choice})],fu);var pu;const qg=`${br}.37`;let Ei=pu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,pu.prototype)}};Ei=pu=f([$({type:O.Sequence,itemType:b.ObjectIdentifier})],Ei);const Fx=`${rs}.1`,Wx=`${rs}.2`,Kx=`${rs}.3`,Gx=`${rs}.4`,qx=`${rs}.8`,zx=`${rs}.9`;let hu=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};f([h({type:b.Integer,converter:be})],hu.prototype,"value",void 0);hu=f([$({type:O.Choice})],hu);let mu=class{value=new Date;constructor(e){e&&(this.value=e)}};f([h({type:b.GeneralizedTime})],mu.prototype,"value",void 0);mu=f([$({type:O.Choice})],mu);var yu;const zg=`${br}.18`;let xp=yu=class extends He{constructor(e){super(e),Object.setPrototypeOf(this,yu.prototype)}};xp=yu=f([$({type:O.Sequence})],xp);const Yg=`${br}.15`;var Ct;(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"})(Ct||(Ct={}));class Ic extends Ba{toJSON(){const e=this.toNumber(),r=[];return e&Ct.cRLSign&&r.push("crlSign"),e&Ct.dataEncipherment&&r.push("dataEncipherment"),e&Ct.decipherOnly&&r.push("decipherOnly"),e&Ct.digitalSignature&&r.push("digitalSignature"),e&Ct.encipherOnly&&r.push("encipherOnly"),e&Ct.keyAgreement&&r.push("keyAgreement"),e&Ct.keyCertSign&&r.push("keyCertSign"),e&Ct.keyEncipherment&&r.push("keyEncipherment"),e&Ct.nonRepudiation&&r.push("nonRepudiation"),r}toString(){return`[${this.toJSON().join(", ")}]`}}var gu;class Ma{base=new ne;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}}f([h({type:ne})],Ma.prototype,"base",void 0);f([h({type:b.Integer,context:0,defaultValue:0,implicit:!0})],Ma.prototype,"minimum",void 0);f([h({type:b.Integer,context:1,optional:!0,implicit:!0})],Ma.prototype,"maximum",void 0);let Ii=gu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,gu.prototype)}};Ii=gu=f([$({type:O.Sequence,itemType:Ma})],Ii);class Xg{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}}f([h({type:Ii,context:0,optional:!0,implicit:!0})],Xg.prototype,"permittedSubtrees",void 0);f([h({type:Ii,context:1,optional:!0,implicit:!0})],Xg.prototype,"excludedSubtrees",void 0);class Jg{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,context:0,implicit:!0,optional:!0,converter:be})],Jg.prototype,"requireExplicitPolicy",void 0);f([h({type:b.Integer,context:1,implicit:!0,optional:!0,converter:be})],Jg.prototype,"inhibitPolicyMapping",void 0);var vu;class gd{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],gd.prototype,"issuerDomainPolicy",void 0);f([h({type:b.ObjectIdentifier})],gd.prototype,"subjectDomainPolicy",void 0);let Ep=vu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,vu.prototype)}};Ep=vu=f([$({type:O.Sequence,itemType:gd})],Ep);var bu;const Zg=`${br}.17`;let wu=bu=class extends He{constructor(e){super(e),Object.setPrototypeOf(this,bu.prototype)}};wu=bu=f([$({type:O.Sequence})],wu);let fr=class{type="";values=[];constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],fr.prototype,"type",void 0);f([h({type:b.Any,repeated:"set"})],fr.prototype,"values",void 0);var Au;let Ip=Au=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Au.prototype)}};Ip=Au=f([$({type:O.Sequence,itemType:fr})],Ip);const Qg=`${br}.14`;class Or extends pd{}class ev{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}}f([h({type:b.GeneralizedTime,context:0,implicit:!0,optional:!0})],ev.prototype,"notBefore",void 0);f([h({type:b.GeneralizedTime,context:1,implicit:!0,optional:!0})],ev.prototype,"notAfter",void 0);var Fs;(function(t){t[t.keyUpdateAllowed=1]="keyUpdateAllowed",t[t.newExtensions=2]="newExtensions",t[t.pKIXCertificate=4]="pKIXCertificate"})(Fs||(Fs={}));class tv extends Ba{toJSON(){const e=[],r=this.toNumber();return r&Fs.pKIXCertificate&&e.push("pKIXCertificate"),r&Fs.newExtensions&&e.push("newExtensions"),r&Fs.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class rv{entrustVers="";entrustInfoFlags=new tv;constructor(e={}){Object.assign(this,e)}}f([h({type:b.GeneralString})],rv.prototype,"entrustVers",void 0);f([h({type:tv})],rv.prototype,"entrustInfoFlags",void 0);var Su;let Cp=Su=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Su.prototype)}};Cp=Su=f([$({type:O.Sequence,itemType:So})],Cp);class L{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof L&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&Ok(e.parameters,this.parameters)||e.parameters===this.parameters)}}f([h({type:b.ObjectIdentifier})],L.prototype,"algorithm",void 0);f([h({type:b.Any,optional:!0})],L.prototype,"parameters",void 0);class bt{algorithm=new L;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:L})],bt.prototype,"algorithm",void 0);f([h({type:b.BitString})],bt.prototype,"subjectPublicKey",void 0);let Le=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([h({type:b.UTCTime})],Le.prototype,"utcTime",void 0);f([h({type:b.GeneralizedTime})],Le.prototype,"generalTime",void 0);Le=f([$({type:O.Choice})],Le);class ko{notBefore=new Le(new Date);notAfter=new Le(new Date);constructor(e){e&&(this.notBefore=new Le(e.notBefore),this.notAfter=new Le(e.notAfter))}}f([h({type:Le})],ko.prototype,"notBefore",void 0);f([h({type:Le})],ko.prototype,"notAfter",void 0);var ku;let _t=class nv{static CRITICAL=!1;extnID="";critical=nv.CRITICAL;extnValue=new ue;constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],_t.prototype,"extnID",void 0);f([h({type:b.Boolean,defaultValue:_t.CRITICAL})],_t.prototype,"critical",void 0);f([h({type:ue})],_t.prototype,"extnValue",void 0);let Tr=ku=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,ku.prototype)}};Tr=ku=f([$({type:O.Sequence,itemType:_t})],Tr);var nn;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2",t[t.v3=2]="v3"})(nn||(nn={}));class pt{version=nn.v1;serialNumber=new ArrayBuffer(0);signature=new L;issuer=new Ie;validity=new ko;subject=new Ie;subjectPublicKeyInfo=new bt;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,context:0,defaultValue:nn.v1})],pt.prototype,"version",void 0);f([h({type:b.Integer,converter:be})],pt.prototype,"serialNumber",void 0);f([h({type:L})],pt.prototype,"signature",void 0);f([h({type:Ie})],pt.prototype,"issuer",void 0);f([h({type:ko})],pt.prototype,"validity",void 0);f([h({type:Ie})],pt.prototype,"subject",void 0);f([h({type:bt})],pt.prototype,"subjectPublicKeyInfo",void 0);f([h({type:b.BitString,context:1,implicit:!0,optional:!0})],pt.prototype,"issuerUniqueID",void 0);f([h({type:b.BitString,context:2,implicit:!0,optional:!0})],pt.prototype,"subjectUniqueID",void 0);f([h({type:Tr,context:3,optional:!0})],pt.prototype,"extensions",void 0);class sn{tbsCertificate=new pt;tbsCertificateRaw;signatureAlgorithm=new L;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:pt,raw:!0})],sn.prototype,"tbsCertificate",void 0);f([h({type:L})],sn.prototype,"signatureAlgorithm",void 0);f([h({type:b.BitString})],sn.prototype,"signatureValue",void 0);class ja{userCertificate=new ArrayBuffer(0);revocationDate=new Le;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,converter:be})],ja.prototype,"userCertificate",void 0);f([h({type:Le})],ja.prototype,"revocationDate",void 0);f([h({type:_t,optional:!0,repeated:"sequence"})],ja.prototype,"crlEntryExtensions",void 0);class wr{version;signature=new L;issuer=new Ie;thisUpdate=new Le;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,optional:!0})],wr.prototype,"version",void 0);f([h({type:L})],wr.prototype,"signature",void 0);f([h({type:Ie})],wr.prototype,"issuer",void 0);f([h({type:Le})],wr.prototype,"thisUpdate",void 0);f([h({type:Le,optional:!0})],wr.prototype,"nextUpdate",void 0);f([h({type:ja,repeated:"sequence",optional:!0})],wr.prototype,"revokedCertificates",void 0);f([h({type:_t,optional:!0,context:0,repeated:"sequence"})],wr.prototype,"crlExtensions",void 0);class vd{tbsCertList=new wr;tbsCertListRaw;signatureAlgorithm=new L;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:wr,raw:!0})],vd.prototype,"tbsCertList",void 0);f([h({type:L})],vd.prototype,"signatureAlgorithm",void 0);f([h({type:b.BitString})],vd.prototype,"signature",void 0);class ss{issuer=new Ie;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:Ie})],ss.prototype,"issuer",void 0);f([h({type:b.Integer,converter:be})],ss.prototype,"serialNumber",void 0);let Kn=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([h({type:Or,context:0,implicit:!0})],Kn.prototype,"subjectKeyIdentifier",void 0);f([h({type:ss})],Kn.prototype,"issuerAndSerialNumber",void 0);Kn=f([$({type:O.Choice})],Kn);var pr;(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"})(pr||(pr={}));let no=class extends L{};no=f([$({type:O.Sequence})],no);let Ci=class extends L{};Ci=f([$({type:O.Sequence})],Ci);let Kt=class extends L{};Kt=f([$({type:O.Sequence})],Kt);let Oi=class extends L{};Oi=f([$({type:O.Sequence})],Oi);let Op=class extends L{};Op=f([$({type:O.Sequence})],Op);let xu=class extends L{};xu=f([$({type:O.Sequence})],xu);let os=class{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],os.prototype,"attrType",void 0);f([h({type:b.Any,repeated:"set"})],os.prototype,"attrValues",void 0);var Eu;class Jt{version=pr.v0;sid=new Kn;digestAlgorithm=new no;signedAttrs;signedAttrsRaw;signatureAlgorithm=new Ci;signature=new ue;unsignedAttrs;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],Jt.prototype,"version",void 0);f([h({type:Kn})],Jt.prototype,"sid",void 0);f([h({type:no})],Jt.prototype,"digestAlgorithm",void 0);f([h({type:os,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],Jt.prototype,"signedAttrs",void 0);f([h({type:Ci})],Jt.prototype,"signatureAlgorithm",void 0);f([h({type:ue})],Jt.prototype,"signature",void 0);f([h({type:os,repeated:"set",context:1,implicit:!0,optional:!0})],Jt.prototype,"unsignedAttrs",void 0);let Ni=Eu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Eu.prototype)}};Ni=Eu=f([$({type:O.Set,itemType:Jt})],Ni);let Np=class extends Jt{};Np=f([$({type:O.Sequence})],Np);let Tp=class extends Le{};Tp=f([$({type:O.Choice})],Tp);class bd{acIssuer=new ne;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}}f([h({type:ne})],bd.prototype,"acIssuer",void 0);f([h({type:b.Integer})],bd.prototype,"acSerial",void 0);f([h({type:fr,repeated:"sequence"})],bd.prototype,"attrs",void 0);var Iu;let Ti=Iu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Iu.prototype)}};Ti=Iu=f([$({type:O.Sequence,itemType:b.ObjectIdentifier})],Ti);class Da{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,optional:!0})],Da.prototype,"pathLenConstraint",void 0);f([h({type:Ti,implicit:!0,context:0,optional:!0})],Da.prototype,"permittedAttrs",void 0);f([h({type:Ti,implicit:!0,context:1,optional:!0})],Da.prototype,"excludedAttrs",void 0);f([h({type:b.Boolean,defaultValue:!0})],Da.prototype,"permitUnSpecified",void 0);class gn{issuer=new He;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:He})],gn.prototype,"issuer",void 0);f([h({type:b.Integer,converter:be})],gn.prototype,"serial",void 0);f([h({type:b.BitString,optional:!0})],gn.prototype,"issuerUID",void 0);var Cu;(function(t){t[t.publicKey=0]="publicKey",t[t.publicKeyCert=1]="publicKeyCert",t[t.otherObjectTypes=2]="otherObjectTypes"})(Cu||(Cu={}));class vn{digestedObjectType=Cu.publicKey;otherObjectTypeID;digestAlgorithm=new L;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.Enumerated})],vn.prototype,"digestedObjectType",void 0);f([h({type:b.ObjectIdentifier,optional:!0})],vn.prototype,"otherObjectTypeID",void 0);f([h({type:L})],vn.prototype,"digestAlgorithm",void 0);f([h({type:b.BitString})],vn.prototype,"objectDigest",void 0);class Pa{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([h({type:He,optional:!0})],Pa.prototype,"issuerName",void 0);f([h({type:gn,context:0,implicit:!0,optional:!0})],Pa.prototype,"baseCertificateID",void 0);f([h({type:vn,context:1,implicit:!0,optional:!0})],Pa.prototype,"objectDigestInfo",void 0);let Gn=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};f([h({type:ne,repeated:"sequence"})],Gn.prototype,"v1Form",void 0);f([h({type:Pa,context:0,implicit:!0})],Gn.prototype,"v2Form",void 0);Gn=f([$({type:O.Choice})],Gn);class La{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}}f([h({type:b.GeneralizedTime})],La.prototype,"notBeforeTime",void 0);f([h({type:b.GeneralizedTime})],La.prototype,"notAfterTime",void 0);class xo{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}f([h({type:gn,implicit:!0,context:0,optional:!0})],xo.prototype,"baseCertificateID",void 0);f([h({type:He,implicit:!0,context:1,optional:!0})],xo.prototype,"entityName",void 0);f([h({type:vn,implicit:!0,context:2,optional:!0})],xo.prototype,"objectDigestInfo",void 0);var Ou;(function(t){t[t.v2=1]="v2"})(Ou||(Ou={}));class jt{version=Ou.v2;holder=new xo;issuer=new Gn;signature=new L;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new La;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],jt.prototype,"version",void 0);f([h({type:xo})],jt.prototype,"holder",void 0);f([h({type:Gn})],jt.prototype,"issuer",void 0);f([h({type:L})],jt.prototype,"signature",void 0);f([h({type:b.Integer,converter:be})],jt.prototype,"serialNumber",void 0);f([h({type:La})],jt.prototype,"attrCertValidityPeriod",void 0);f([h({type:fr,repeated:"sequence"})],jt.prototype,"attributes",void 0);f([h({type:b.BitString,optional:!0})],jt.prototype,"issuerUniqueID",void 0);f([h({type:Tr,optional:!0})],jt.prototype,"extensions",void 0);class Ua{acinfo=new jt;signatureAlgorithm=new L;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:jt})],Ua.prototype,"acinfo",void 0);f([h({type:L})],Ua.prototype,"signatureAlgorithm",void 0);f([h({type:b.BitString})],Ua.prototype,"signatureValue",void 0);var Bi;(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"})(Bi||(Bi={}));class Nu extends Ba{}class wd{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier,implicit:!0,context:0})],wd.prototype,"type",void 0);f([h({type:b.Any,implicit:!0,context:1})],wd.prototype,"value",void 0);class Ad{policyId="";classList=new Nu(Bi.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Ad.prototype,"policyId",void 0);f([h({type:Nu,defaultValue:new Nu(Bi.unclassified)})],Ad.prototype,"classList",void 0);f([h({type:wd,repeated:"set"})],Ad.prototype,"securityCategories",void 0);class Va{cotets;oid;string;constructor(e={}){Object.assign(this,e)}}f([h({type:ue})],Va.prototype,"cotets",void 0);f([h({type:b.ObjectIdentifier})],Va.prototype,"oid",void 0);f([h({type:b.Utf8String})],Va.prototype,"string",void 0);class sv{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}}f([h({type:He,implicit:!0,context:0,optional:!0})],sv.prototype,"policyAuthority",void 0);f([h({type:Va,repeated:"sequence"})],sv.prototype,"values",void 0);var Tu;class Ha{targetCertificate=new gn;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}}f([h({type:gn})],Ha.prototype,"targetCertificate",void 0);f([h({type:ne,optional:!0})],Ha.prototype,"targetName",void 0);f([h({type:vn,optional:!0})],Ha.prototype,"certDigestInfo",void 0);let qn=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};f([h({type:ne,context:0,implicit:!0})],qn.prototype,"targetName",void 0);f([h({type:ne,context:1,implicit:!0})],qn.prototype,"targetGroup",void 0);f([h({type:Ha,context:2,implicit:!0})],qn.prototype,"targetCert",void 0);qn=f([$({type:O.Choice})],qn);let Bu=Tu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Tu.prototype)}};Bu=Tu=f([$({type:O.Sequence,itemType:qn})],Bu);var $u;let Bp=$u=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,$u.prototype)}};Bp=$u=f([$({type:O.Sequence,itemType:Bu})],Bp);class ov{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}}f([h({type:He,implicit:!0,context:0,optional:!0})],ov.prototype,"roleAuthority",void 0);f([h({type:ne,implicit:!0,context:1})],ov.prototype,"roleName",void 0);class Sd{service=new ne;ident=new ne;authInfo;constructor(e={}){Object.assign(this,e)}}f([h({type:ne})],Sd.prototype,"service",void 0);f([h({type:ne})],Sd.prototype,"ident",void 0);f([h({type:ue,optional:!0})],Sd.prototype,"authInfo",void 0);var Ru;class kd{otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],kd.prototype,"otherCertFormat",void 0);f([h({type:b.Any})],kd.prototype,"otherCert",void 0);let zn=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};f([h({type:sn})],zn.prototype,"certificate",void 0);f([h({type:Ua,context:2,implicit:!0})],zn.prototype,"v2AttrCert",void 0);f([h({type:kd,context:3,implicit:!0})],zn.prototype,"other",void 0);zn=f([$({type:O.Choice})],zn);let $i=Ru=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Ru.prototype)}};$i=Ru=f([$({type:O.Set,itemType:zn})],$i);class is{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],is.prototype,"contentType",void 0);f([h({type:b.Any,context:0})],is.prototype,"content",void 0);let so=class{single;any;constructor(e={}){Object.assign(this,e)}};f([h({type:ue})],so.prototype,"single",void 0);f([h({type:b.Any})],so.prototype,"any",void 0);so=f([$({type:O.Choice})],so);class Fa{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Fa.prototype,"eContentType",void 0);f([h({type:so,context:0,optional:!0})],Fa.prototype,"eContent",void 0);let oo=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};f([h({type:ue,context:0,implicit:!0,optional:!0})],oo.prototype,"value",void 0);f([h({type:ue,converter:kx,context:0,implicit:!0,optional:!0,repeated:"sequence"})],oo.prototype,"constructedValue",void 0);oo=f([$({type:O.Choice})],oo);class Eo{contentType="";contentEncryptionAlgorithm=new Oi;encryptedContent;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Eo.prototype,"contentType",void 0);f([h({type:Oi})],Eo.prototype,"contentEncryptionAlgorithm",void 0);f([h({type:oo,optional:!0})],Eo.prototype,"encryptedContent",void 0);class Wa{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Wa.prototype,"keyAttrId",void 0);f([h({type:b.Any,optional:!0})],Wa.prototype,"keyAttr",void 0);var _u;class Ka{subjectKeyIdentifier=new Or;date;other;constructor(e={}){Object.assign(this,e)}}f([h({type:Or})],Ka.prototype,"subjectKeyIdentifier",void 0);f([h({type:b.GeneralizedTime,optional:!0})],Ka.prototype,"date",void 0);f([h({type:Wa,optional:!0})],Ka.prototype,"other",void 0);let Yn=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([h({type:Ka,context:0,implicit:!0,optional:!0})],Yn.prototype,"rKeyId",void 0);f([h({type:ss,optional:!0})],Yn.prototype,"issuerAndSerialNumber",void 0);Yn=f([$({type:O.Choice})],Yn);class xd{rid=new Yn;encryptedKey=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:Yn})],xd.prototype,"rid",void 0);f([h({type:ue})],xd.prototype,"encryptedKey",void 0);let Ri=_u=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,_u.prototype)}};Ri=_u=f([$({type:O.Sequence,itemType:xd})],Ri);class Ed{algorithm=new L;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:L})],Ed.prototype,"algorithm",void 0);f([h({type:b.BitString})],Ed.prototype,"publicKey",void 0);let on=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([h({type:Or,context:0,implicit:!0,optional:!0})],on.prototype,"subjectKeyIdentifier",void 0);f([h({type:Ed,context:1,implicit:!0,optional:!0})],on.prototype,"originatorKey",void 0);f([h({type:ss,optional:!0})],on.prototype,"issuerAndSerialNumber",void 0);on=f([$({type:O.Choice})],on);class as{version=pr.v3;originator=new on;ukm;keyEncryptionAlgorithm=new Kt;recipientEncryptedKeys=new Ri;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],as.prototype,"version",void 0);f([h({type:on,context:0})],as.prototype,"originator",void 0);f([h({type:ue,context:1,optional:!0})],as.prototype,"ukm",void 0);f([h({type:Kt})],as.prototype,"keyEncryptionAlgorithm",void 0);f([h({type:Ri})],as.prototype,"recipientEncryptedKeys",void 0);let Xn=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};f([h({type:Or,context:0,implicit:!0})],Xn.prototype,"subjectKeyIdentifier",void 0);f([h({type:ss})],Xn.prototype,"issuerAndSerialNumber",void 0);Xn=f([$({type:O.Choice})],Xn);class Io{version=pr.v0;rid=new Xn;keyEncryptionAlgorithm=new Kt;encryptedKey=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],Io.prototype,"version",void 0);f([h({type:Xn})],Io.prototype,"rid",void 0);f([h({type:Kt})],Io.prototype,"keyEncryptionAlgorithm",void 0);f([h({type:ue})],Io.prototype,"encryptedKey",void 0);class Co{keyIdentifier=new ue;date;other;constructor(e={}){Object.assign(this,e)}}f([h({type:ue})],Co.prototype,"keyIdentifier",void 0);f([h({type:b.GeneralizedTime,optional:!0})],Co.prototype,"date",void 0);f([h({type:Wa,optional:!0})],Co.prototype,"other",void 0);class Oo{version=pr.v4;kekid=new Co;keyEncryptionAlgorithm=new Kt;encryptedKey=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],Oo.prototype,"version",void 0);f([h({type:Co})],Oo.prototype,"kekid",void 0);f([h({type:Kt})],Oo.prototype,"keyEncryptionAlgorithm",void 0);f([h({type:ue})],Oo.prototype,"encryptedKey",void 0);class No{version=pr.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new Kt;encryptedKey=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],No.prototype,"version",void 0);f([h({type:xu,context:0,optional:!0})],No.prototype,"keyDerivationAlgorithm",void 0);f([h({type:Kt})],No.prototype,"keyEncryptionAlgorithm",void 0);f([h({type:ue})],No.prototype,"encryptedKey",void 0);class Id{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Id.prototype,"oriType",void 0);f([h({type:b.Any})],Id.prototype,"oriValue",void 0);let Br=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};f([h({type:Io,optional:!0})],Br.prototype,"ktri",void 0);f([h({type:as,context:1,implicit:!0,optional:!0})],Br.prototype,"kari",void 0);f([h({type:Oo,context:2,implicit:!0,optional:!0})],Br.prototype,"kekri",void 0);f([h({type:No,context:3,implicit:!0,optional:!0})],Br.prototype,"pwri",void 0);f([h({type:Id,context:4,implicit:!0,optional:!0})],Br.prototype,"ori",void 0);Br=f([$({type:O.Choice})],Br);var Mu;let _i=Mu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Mu.prototype)}};_i=Mu=f([$({type:O.Set,itemType:Br})],_i);var ju;class Ga{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],Ga.prototype,"otherRevInfoFormat",void 0);f([h({type:b.Any})],Ga.prototype,"otherRevInfo",void 0);let Mi=class{other=new Ga;constructor(e={}){Object.assign(this,e)}};f([h({type:Ga,context:1,implicit:!0})],Mi.prototype,"other",void 0);Mi=f([$({type:O.Choice})],Mi);let ji=ju=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,ju.prototype)}};ji=ju=f([$({type:O.Set,itemType:Mi})],ji);class Cd{certs;crls;constructor(e={}){Object.assign(this,e)}}f([h({type:$i,context:0,implicit:!0,optional:!0})],Cd.prototype,"certs",void 0);f([h({type:ji,context:1,implicit:!0,optional:!0})],Cd.prototype,"crls",void 0);var Du;let Pu=Du=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Du.prototype)}};Pu=Du=f([$({type:O.Set,itemType:os})],Pu);class To{version=pr.v0;originatorInfo;recipientInfos=new _i;encryptedContentInfo=new Eo;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],To.prototype,"version",void 0);f([h({type:Cd,context:0,implicit:!0,optional:!0})],To.prototype,"originatorInfo",void 0);f([h({type:_i})],To.prototype,"recipientInfos",void 0);f([h({type:Eo})],To.prototype,"encryptedContentInfo",void 0);f([h({type:Pu,context:1,implicit:!0,optional:!0})],To.prototype,"unprotectedAttrs",void 0);const Yx="1.2.840.113549.1.7.2";var Lu;let Di=Lu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Lu.prototype)}};Di=Lu=f([$({type:O.Set,itemType:no})],Di);class cs{version=pr.v0;digestAlgorithms=new Di;encapContentInfo=new Fa;certificates;crls;signerInfos=new Ni;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],cs.prototype,"version",void 0);f([h({type:Di})],cs.prototype,"digestAlgorithms",void 0);f([h({type:Fa})],cs.prototype,"encapContentInfo",void 0);f([h({type:$i,context:0,implicit:!0,optional:!0})],cs.prototype,"certificates",void 0);f([h({type:ji,context:1,implicit:!0,optional:!0})],cs.prototype,"crls",void 0);f([h({type:Ni})],cs.prototype,"signerInfos",void 0);const io="1.2.840.10045.2.1",Od="1.2.840.10045.4.1",iv="1.2.840.10045.4.3.1",Nd="1.2.840.10045.4.3.2",Td="1.2.840.10045.4.3.3",Bd="1.2.840.10045.4.3.4",$p="1.2.840.10045.3.1.7",Rp="1.3.132.0.34",_p="1.3.132.0.35";function Bo(t){return new L({algorithm:t})}const Xx=Bo(Od);Bo(iv);const Jx=Bo(Nd),Zx=Bo(Td),Qx=Bo(Bd);let ao=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],ao.prototype,"fieldType",void 0);f([h({type:b.Any})],ao.prototype,"parameters",void 0);ao=f([$({type:O.Sequence})],ao);class eE extends ue{}let Jn=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};f([h({type:b.OctetString})],Jn.prototype,"a",void 0);f([h({type:b.OctetString})],Jn.prototype,"b",void 0);f([h({type:b.BitString,optional:!0})],Jn.prototype,"seed",void 0);Jn=f([$({type:O.Sequence})],Jn);var Uu;(function(t){t[t.ecpVer1=1]="ecpVer1"})(Uu||(Uu={}));let hr=class{version=Uu.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};f([h({type:b.Integer})],hr.prototype,"version",void 0);f([h({type:ao})],hr.prototype,"fieldID",void 0);f([h({type:Jn})],hr.prototype,"curve",void 0);f([h({type:eE})],hr.prototype,"base",void 0);f([h({type:b.Integer,converter:be})],hr.prototype,"order",void 0);f([h({type:b.Integer,optional:!0})],hr.prototype,"cofactor",void 0);hr=f([$({type:O.Sequence})],hr);let $r=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};f([h({type:b.ObjectIdentifier})],$r.prototype,"namedCurve",void 0);f([h({type:b.Null})],$r.prototype,"implicitCurve",void 0);f([h({type:hr})],$r.prototype,"specifiedCurve",void 0);$r=f([$({type:O.Choice})],$r);class qa{version=1;privateKey=new ue;parameters;publicKey;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],qa.prototype,"version",void 0);f([h({type:ue})],qa.prototype,"privateKey",void 0);f([h({type:$r,context:0,optional:!0})],qa.prototype,"parameters",void 0);f([h({type:b.BitString,context:1,optional:!0})],qa.prototype,"publicKey",void 0);class Pi{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,converter:be})],Pi.prototype,"r",void 0);f([h({type:b.Integer,converter:be})],Pi.prototype,"s",void 0);const nt="1.2.840.113549.1.1",an=`${nt}.1`,tE=`${nt}.7`,rE=`${nt}.9`,Ws=`${nt}.10`,nE=`${nt}.2`,sE=`${nt}.4`,Li=`${nt}.5`,oE=`${nt}.14`,Vu=`${nt}.11`,Ui=`${nt}.12`,Vi=`${nt}.13`,av=`${nt}.15`,cv=`${nt}.16`,Hi="1.3.14.3.2.26",uv="2.16.840.1.101.3.4.2.4",Fi="2.16.840.1.101.3.4.2.1",Wi="2.16.840.1.101.3.4.2.2",Ki="2.16.840.1.101.3.4.2.3",iE="2.16.840.1.101.3.4.2.5",aE="2.16.840.1.101.3.4.2.6",cE="1.2.840.113549.2.2",uE="1.2.840.113549.2.5",za=`${nt}.8`;function Be(t){return new L({algorithm:t,parameters:null})}Be(cE);Be(uE);const cn=Be(Hi);Be(uv);Be(Fi);Be(Wi);Be(Ki);Be(iE);Be(aE);const lv=new L({algorithm:za,parameters:D.serialize(cn)}),dv=new L({algorithm:rE,parameters:D.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))});Be(an);Be(nE);Be(sE);Be(Li);Be(av);Be(cv);Be(Ui);Be(Vi);Be(av);Be(cv);class Ya{hashAlgorithm=new L(cn);maskGenAlgorithm=new L({algorithm:za,parameters:D.serialize(cn)});pSourceAlgorithm=new L(dv);constructor(e={}){Object.assign(this,e)}}f([h({type:L,context:0,defaultValue:cn})],Ya.prototype,"hashAlgorithm",void 0);f([h({type:L,context:1,defaultValue:lv})],Ya.prototype,"maskGenAlgorithm",void 0);f([h({type:L,context:2,defaultValue:dv})],Ya.prototype,"pSourceAlgorithm",void 0);new L({algorithm:tE,parameters:D.serialize(new Ya)});class un{hashAlgorithm=new L(cn);maskGenAlgorithm=new L({algorithm:za,parameters:D.serialize(cn)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}}f([h({type:L,context:0,defaultValue:cn})],un.prototype,"hashAlgorithm",void 0);f([h({type:L,context:1,defaultValue:lv})],un.prototype,"maskGenAlgorithm",void 0);f([h({type:b.Integer,context:2,defaultValue:20})],un.prototype,"saltLength",void 0);f([h({type:b.Integer,context:3,defaultValue:1})],un.prototype,"trailerField",void 0);new L({algorithm:Ws,parameters:D.serialize(new un)});class Xa{digestAlgorithm=new L;digest=new ue;constructor(e={}){Object.assign(this,e)}}f([h({type:L})],Xa.prototype,"digestAlgorithm",void 0);f([h({type:ue})],Xa.prototype,"digest",void 0);var Hu;class Ja{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,converter:be})],Ja.prototype,"prime",void 0);f([h({type:b.Integer,converter:be})],Ja.prototype,"exponent",void 0);f([h({type:b.Integer,converter:be})],Ja.prototype,"coefficient",void 0);let Fu=Hu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Hu.prototype)}};Fu=Hu=f([$({type:O.Sequence,itemType:Ja})],Fu);class Zt{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([h({type:b.Integer})],Zt.prototype,"version",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"modulus",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"publicExponent",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"privateExponent",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"prime1",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"prime2",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"exponent1",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"exponent2",void 0);f([h({type:b.Integer,converter:be})],Zt.prototype,"coefficient",void 0);f([h({type:Fu,optional:!0})],Zt.prototype,"otherPrimeInfos",void 0);class $d{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer,converter:be})],$d.prototype,"modulus",void 0);f([h({type:b.Integer,converter:be})],$d.prototype,"publicExponent",void 0);var Wu;(function(t){t[t.Transient=0]="Transient",t[t.Singleton=1]="Singleton",t[t.ResolutionScoped=2]="ResolutionScoped",t[t.ContainerScoped=3]="ContainerScoped"})(Wu||(Wu={}));const Xe=Wu;var Ku=function(t,e){return Ku=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])},Ku(t,e)};function Rd(t,e){Ku(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function lE(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 dE(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 Go(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 Gi(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 Fr(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Gi(arguments[e]));return t}var fE="injectionTokens";function pE(t){var e=Reflect.getMetadata("design:paramtypes",t)||[],r=Reflect.getOwnMetadata(fE,t)||{};return Object.keys(r).forEach(function(n){e[+n]=r[n]}),e}function fv(t){return!!t.useClass}function Gu(t){return!!t.useFactory}var pv=(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,Fr(o))}};return this.reflectMethods.forEach(n),r},t})();function Sn(t){return typeof t=="string"||typeof t=="symbol"}function hE(t){return typeof t=="object"&&"token"in t&&"multiple"in t}function Mp(t){return typeof t=="object"&&"token"in t&&"transform"in t}function mE(t){return typeof t=="function"||t instanceof pv}function ri(t){return!!t.useToken}function ni(t){return t.useValue!=null}function yE(t){return fv(t)||ni(t)||ri(t)||Gu(t)}var _d=(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})(),gE=(function(t){Rd(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(_d),qo=(function(){function t(){this.scopedResolutions=new Map}return t})();function vE(t,e){if(t===null)return"at position #"+e;var r=t.split(",")[e].trim();return'"'+r+'" at position #'+e}function bE(t,e,r){return r===void 0&&(r=" "),Fr([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(`
98
372
  `).map(function(n){return r+n})).join(`
99
- `)}function wE(t,e,r){var n=Gi(t.toString().match(/constructor\(([\w, ]+)\)/)||[],2),s=n[1],o=s===void 0?null:s,i=vE(o,e);return bE("Cannot inject the dependency "+i+' of "'+t.name+'" constructor. Reason:',r)}function AE(t){if(typeof t.dispose!="function")return!1;var e=t.dispose;return!(e.length>0)}var SE=(function(t){Rd(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(_d),kE=(function(t){Rd(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e})(_d),xE=(function(){function t(){this.preResolution=new SE,this.postResolution=new kE}return t})(),hv=new Map,EE=(function(){function t(e){this.parent=e,this._registry=new gE,this.interceptors=new xE,this.disposed=!1,this.disposables=new Set}return t.prototype.register=function(e,r,n){n===void 0&&(n={lifecycle:Xe.Transient}),this.ensureNotDisposed();var s;if(yE(r)?s=r:s={useClass:r},ri(s))for(var o=[e],i=s;i!=null;){var a=i.useToken;if(o.includes(a))throw new Error("Token registration cycle detected! "+Fr(o,[a]).join(" -> "));o.push(a);var c=this._registry.get(a);c&&ri(c.provider)?i=c.provider:i=null}if((n.lifecycle===Xe.Singleton||n.lifecycle==Xe.ContainerScoped||n.lifecycle==Xe.ResolutionScoped)&&(ni(s)||Gu(s)))throw new Error('Cannot use lifecycle "'+Xe[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(),Sn(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(),Sn(e)){if(Sn(r))return this.register(e,{useToken:r},{lifecycle:Xe.Singleton});if(r)return this.register(e,{useClass:r},{lifecycle:Xe.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var n=e;return r&&!Sn(r)&&(n=r),this.register(e,{useClass:n},{lifecycle:Xe.Singleton})},t.prototype.resolve=function(e,r,n){r===void 0&&(r=new qo),n===void 0&&(n=!1),this.ensureNotDisposed();var s=this.getRegistration(e);if(!s&&Sn(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(mE(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=Go(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=Go(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===Xe.ResolutionScoped&&r.scopedResolutions.has(e))return r.scopedResolutions.get(e);var n=e.options.lifecycle===Xe.Singleton,s=e.options.lifecycle===Xe.ContainerScoped,o=n||s,i;return ni(e.provider)?i=e.provider.useValue:ri(e.provider)?i=o?e.instance||(e.instance=this.resolve(e.provider.useToken,r)):this.resolve(e.provider.useToken,r):fv(e.provider)?i=o?e.instance||(e.instance=this.construct(e.provider.useClass,r)):this.construct(e.provider.useClass,r):Gu(e.provider)?i=e.provider.useFactory(this):i=this.construct(e.provider,r),e.options.lifecycle===Xe.ResolutionScoped&&r.scopedResolutions.set(e,i),i},t.prototype.resolveAll=function(e,r,n){var s=this;r===void 0&&(r=new qo),n===void 0&&(n=!1),this.ensureNotDisposed();var o=this.getAllRegistrations(e);if(!o&&Sn(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=Go(this._registry.entries()),s=n.next();!s.done;s=n.next()){var o=Gi(s.value,2),i=o[0],a=o[1];this._registry.setAll(i,a.filter(function(c){return!ni(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=Go(this._registry.entries()),o=s.next();!o.done;o=s.next()){var i=Gi(o.value,2),a=i[0],c=i[1];c.some(function(u){var l=u.options;return l.lifecycle===Xe.ContainerScoped})&&n._registry.setAll(a,c.map(function(u){return u.options.lifecycle===Xe.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 lE(this,void 0,void 0,function(){var e;return dE(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 pv)return e.createProxy(function(o){return n.resolve(o,r)});var s=(function(){var o=hv.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,Fr([void 0],i)))})();return AE(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 hE(s)?Mp(s)?s.multiple?(i=n.resolve(s.transform)).transform.apply(i,Fr([n.resolveAll(s.token,new qo,s.isOptional)],s.transformArgs)):(a=n.resolve(s.transform)).transform.apply(a,Fr([n.resolve(s.token,e,s.isOptional)],s.transformArgs)):s.multiple?n.resolveAll(s.token,new qo,s.isOptional):n.resolve(s.token,e,s.isOptional):Mp(s)?(c=n.resolve(s.transform,e)).transform.apply(c,Fr([n.resolve(s.token,e)],s.transformArgs)):n.resolve(s,e)}catch(u){throw new Error(wE(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})(),Te=new EE;function us(t){return function(e){hv.set(e,pE(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 qu;class Za{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}}f([h({type:b.ObjectIdentifier})],Za.prototype,"attrId",void 0);f([h({type:b.Any,repeated:"set"})],Za.prototype,"attrValues",void 0);let jp=qu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,qu.prototype)}};jp=qu=f([$({type:O.Sequence,itemType:Za})],jp);var zu;let Dp=zu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,zu.prototype)}};Dp=zu=f([$({type:O.Sequence,itemType:is})],Dp);class mv{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],mv.prototype,"certId",void 0);f([h({type:b.Any,context:0})],mv.prototype,"certValue",void 0);class yv{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],yv.prototype,"crlId",void 0);f([h({type:b.Any,context:0})],yv.prototype,"crltValue",void 0);class gv extends ue{}let Qa=class{encryptionAlgorithm=new L;encryptedData=new gv;constructor(e={}){Object.assign(this,e)}};f([h({type:L})],Qa.prototype,"encryptionAlgorithm",void 0);f([h({type:gv})],Qa.prototype,"encryptedData",void 0);var Yu,Xu;(function(t){t[t.v1=0]="v1"})(Xu||(Xu={}));class vv extends ue{}let qi=Yu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Yu.prototype)}};qi=Yu=f([$({type:O.Sequence,itemType:fr})],qi);let $o=class{version=Xu.v1;privateKeyAlgorithm=new L;privateKey=new vv;attributes;constructor(e={}){Object.assign(this,e)}};f([h({type:b.Integer})],$o.prototype,"version",void 0);f([h({type:L})],$o.prototype,"privateKeyAlgorithm",void 0);f([h({type:vv})],$o.prototype,"privateKey",void 0);f([h({type:qi,implicit:!0,context:0,optional:!0})],$o.prototype,"attributes",void 0);let Pp=class extends $o{};Pp=f([$({type:O.Sequence})],Pp);let Lp=class extends Qa{};Lp=f([$({type:O.Sequence})],Lp);class bv{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],bv.prototype,"secretTypeId",void 0);f([h({type:b.Any,context:0})],bv.prototype,"secretValue",void 0);class Ro{mac=new Xa;macSalt=new ue;iterations=1;constructor(e={}){Object.assign(this,e)}}f([h({type:Xa})],Ro.prototype,"mac",void 0);f([h({type:ue})],Ro.prototype,"macSalt",void 0);f([h({type:b.Integer,defaultValue:1})],Ro.prototype,"iterations",void 0);class ec{version=3;authSafe=new is;macData=new Ro;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],ec.prototype,"version",void 0);f([h({type:is})],ec.prototype,"authSafe",void 0);f([h({type:Ro,optional:!0})],ec.prototype,"macData",void 0);var Ju;class tc{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}}f([h({type:b.ObjectIdentifier})],tc.prototype,"bagId",void 0);f([h({type:b.Any,context:0})],tc.prototype,"bagValue",void 0);f([h({type:Za,repeated:"set",optional:!0})],tc.prototype,"bagAttributes",void 0);let Up=Ju=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Ju.prototype)}};Up=Ju=f([$({type:O.Sequence,itemType:tc})],Up);var Zu,Qu,el;const wv="1.2.840.113549.1.9",Av=`${wv}.7`,Md=`${wv}.14`;let zi=class extends Ve{ia5String;constructor(e={}){super(e)}toString(){return this.ia5String||super.toString()}};f([h({type:b.IA5String})],zi.prototype,"ia5String",void 0);zi=f([$({type:O.Choice})],zi);let Vp=class extends is{};Vp=f([$({type:O.Sequence})],Vp);let Hp=class extends ec{};Hp=f([$({type:O.Sequence})],Hp);let Fp=class extends Qa{};Fp=f([$({type:O.Sequence})],Fp);let tl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([h({type:b.IA5String})],tl.prototype,"value",void 0);tl=f([$({type:O.Choice})],tl);let Wp=class extends zi{};Wp=f([$({type:O.Choice})],Wp);let Kp=class extends Ve{};Kp=f([$({type:O.Choice})],Kp);let rl=class{value;constructor(e=new Date){this.value=e}};f([h({type:b.GeneralizedTime})],rl.prototype,"value",void 0);rl=f([$({type:O.Choice})],rl);let Gp=class extends Ve{};Gp=f([$({type:O.Choice})],Gp);let nl=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};f([h({type:b.PrintableString})],nl.prototype,"value",void 0);nl=f([$({type:O.Choice})],nl);let Yi=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([h({type:b.PrintableString})],Yi.prototype,"value",void 0);Yi=f([$({type:O.Choice})],Yi);let qp=class extends Yi{};qp=f([$({type:O.Choice})],qp);let zp=class extends Ve{};zp=f([$({type:O.Choice})],zp);let sl=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([h({type:b.ObjectIdentifier})],sl.prototype,"value",void 0);sl=f([$({type:O.Choice})],sl);let Yp=class extends Le{};Yp=f([$({type:O.Choice})],Yp);let ol=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};f([h({type:b.Integer})],ol.prototype,"value",void 0);ol=f([$({type:O.Choice})],ol);let Xp=class extends Jt{};Xp=f([$({type:O.Sequence})],Xp);let Xi=class extends Ve{};Xi=f([$({type:O.Choice})],Xi);let Jp=Zu=class extends Tr{constructor(e){super(e),Object.setPrototypeOf(this,Zu.prototype)}};Jp=Zu=f([$({type:O.Sequence})],Jp);let Zp=Qu=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,Qu.prototype)}};Zp=Qu=f([$({type:O.Set,itemType:os})],Zp);let il=class{value;constructor(e=""){this.value=e}toString(){return this.value}};f([h({type:b.BmpString})],il.prototype,"value",void 0);il=f([$({type:O.Choice})],il);let al=class extends L{};al=f([$({type:O.Sequence})],al);let Qp=el=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,el.prototype)}};Qp=el=f([$({type:O.Sequence,itemType:al})],Qp);var cl,ul;let eh=cl=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,cl.prototype)}};eh=cl=f([$({type:O.Sequence,itemType:L})],eh);let th=ul=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,ul.prototype)}};th=ul=f([$({type:O.Sequence,itemType:b.BitString})],th);var ll,dl;(function(t){t[t.v1=0]="v1",t[t.v2=1]="v2"})(dl||(dl={}));let rh=class extends L{};rh=f([$({type:O.Sequence})],rh);let Gt=class{version=dl.v1;privateKeyAlgorithm=new L;privateKey=new ArrayBuffer(0);attributes;publicKey};f([h({type:b.Integer})],Gt.prototype,"version",void 0);f([h({type:L})],Gt.prototype,"privateKeyAlgorithm",void 0);f([h({type:b.OctetString})],Gt.prototype,"privateKey",void 0);f([h({type:qi,context:0,implicit:!0,optional:!0})],Gt.prototype,"attributes",void 0);f([h({type:b.BitString,context:1,implicit:!0,optional:!0})],Gt.prototype,"publicKey",void 0);Gt=f([$({type:O.Sequence})],Gt);let nh=class extends Gt{};nh=f([$({type:O.Sequence})],nh);let sh=ll=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,ll.prototype)}};sh=ll=f([$({type:O.Sequence,itemType:Gt})],sh);var fl,pl;let oh=class extends L{};oh=f([$({type:O.Sequence})],oh);let ih=fl=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,fl.prototype)}};ih=fl=f([$({type:O.Sequence,itemType:bt})],ih);let ah=pl=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,pl.prototype)}};ah=pl=f([$({type:O.Sequence,itemType:Gt})],ah);const Ye="2.16.840.1.101.3.4.3",ch=`${Ye}.17`,uh=`${Ye}.18`,lh=`${Ye}.19`,dh=`${Ye}.20`,fh=`${Ye}.21`,ph=`${Ye}.22`,hh=`${Ye}.23`,mh=`${Ye}.24`,yh=`${Ye}.25`,gh=`${Ye}.26`,vh=`${Ye}.27`,bh=`${Ye}.28`,wh=`${Ye}.29`,Ah=`${Ye}.30`,Sh=`${Ye}.31`;var hl;let Ji=hl=class extends ce{constructor(e){super(e),Object.setPrototypeOf(this,hl.prototype)}};Ji=hl=f([$({type:O.Sequence,itemType:fr})],Ji);class ls{version=0;subject=new Ie;subjectPKInfo=new bt;attributes=new Ji;constructor(e={}){Object.assign(this,e)}}f([h({type:b.Integer})],ls.prototype,"version",void 0);f([h({type:Ie})],ls.prototype,"subject",void 0);f([h({type:bt})],ls.prototype,"subjectPKInfo",void 0);f([h({type:Ji,implicit:!0,context:0,optional:!0})],ls.prototype,"attributes",void 0);class co{certificationRequestInfo=new ls;certificationRequestInfoRaw;signatureAlgorithm=new L;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}f([h({type:ls,raw:!0})],co.prototype,"certificationRequestInfo",void 0);f([h({type:L})],co.prototype,"signatureAlgorithm",void 0);f([h({type:b.BitString})],co.prototype,"signature",void 0);const bn="crypto.algorithm";class IE{getAlgorithms(){return Te.resolveAll(bn)}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 L({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 ln="crypto.algorithmProvider";Te.registerSingleton(ln,IE);var si;const st="1.3.36.3.3.2.8.1.1",kh=`${st}.1`,xh=`${st}.2`,Eh=`${st}.3`,Ih=`${st}.4`,Ch=`${st}.5`,Oh=`${st}.6`,Nh=`${st}.7`,Th=`${st}.8`,Bh=`${st}.9`,$h=`${st}.10`,Rh=`${st}.11`,_h=`${st}.12`,Mh=`${st}.13`,jh=`${st}.14`,Dh="brainpoolP160r1",Ph="brainpoolP160t1",Lh="brainpoolP192r1",Uh="brainpoolP192t1",Vh="brainpoolP224r1",Hh="brainpoolP224t1",Fh="brainpoolP256r1",Wh="brainpoolP256t1",Kh="brainpoolP320r1",Gh="brainpoolP320t1",qh="brainpoolP384r1",zh="brainpoolP384t1",Yh="brainpoolP512r1",Xh="brainpoolP512t1",we="ECDSA";let uo=si=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case we.toLowerCase():if("hash"in e)switch((typeof e.hash=="string"?e.hash:e.hash.name).toLowerCase()){case"sha-1":return Xx;case"sha-256":return Jx;case"sha-384":return Zx;case"sha-512":return Qx}else if("namedCurve"in e){let r="";switch(e.namedCurve){case"P-256":r=$p;break;case"K-256":r=si.SECP256K1;break;case"P-384":r=Rp;break;case"P-521":r=_p;break;case Dh:r=kh;break;case Ph:r=xh;break;case Lh:r=Eh;break;case Uh:r=Ih;break;case Vh:r=Ch;break;case Hh:r=Oh;break;case Fh:r=Nh;break;case Wh:r=Th;break;case Kh:r=Bh;break;case Gh:r=$h;break;case qh:r=Rh;break;case zh:r=_h;break;case Yh:r=Mh;break;case Xh:r=jh;break}if(r)return new L({algorithm:io,parameters:D.serialize(new $r({namedCurve:r}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case Od:return{name:we,hash:{name:"SHA-1"}};case Nd:return{name:we,hash:{name:"SHA-256"}};case Td:return{name:we,hash:{name:"SHA-384"}};case Bd:return{name:we,hash:{name:"SHA-512"}};case io:{if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(D.parse(e.parameters,$r).namedCurve){case $p:return{name:we,namedCurve:"P-256"};case si.SECP256K1:return{name:we,namedCurve:"K-256"};case Rp:return{name:we,namedCurve:"P-384"};case _p:return{name:we,namedCurve:"P-521"};case kh:return{name:we,namedCurve:Dh};case xh:return{name:we,namedCurve:Ph};case Eh:return{name:we,namedCurve:Lh};case Ih:return{name:we,namedCurve:Uh};case Ch:return{name:we,namedCurve:Vh};case Oh:return{name:we,namedCurve:Hh};case Nh:return{name:we,namedCurve:Fh};case Th:return{name:we,namedCurve:Wh};case Bh:return{name:we,namedCurve:Kh};case $h:return{name:we,namedCurve:Gh};case Rh:return{name:we,namedCurve:qh};case _h:return{name:we,namedCurve:zh};case Mh:return{name:we,namedCurve:Yh};case jh:return{name:we,namedCurve:Xh}}}}return null}};uo.SECP256K1="1.3.132.0.10";uo=si=f([us()],uo);Te.registerSingleton(bn,uo);const Sv=Symbol("name"),kv=Symbol("value");class de{constructor(e,r={},n=""){this[Sv]=e,this[kv]=n;for(const s in r)this[s]=r[s]}}de.NAME=Sv;de.VALUE=kv;class CE{static toTextObject(e){const r=new de("Algorithm Identifier",{},Dr.toString(e.algorithm));if(e.parameters)if(e.algorithm===io){const n=new uo().toWebAlgorithm(e);n&&"namedCurve"in n?r["Named Curve"]=n.namedCurve:r.Parameters=e.parameters}else r.Parameters=e.parameters;return r}}class Dr{static toString(e){const r=this.items[e];return r||e}}Dr.items={[Hi]:"sha1",[uv]:"sha224",[Fi]:"sha256",[Wi]:"sha384",[Ki]:"sha512",[an]:"rsaEncryption",[Li]:"sha1WithRSAEncryption",[oE]:"sha224WithRSAEncryption",[Vu]:"sha256WithRSAEncryption",[Ui]:"sha384WithRSAEncryption",[Vi]:"sha512WithRSAEncryption",[io]:"ecPublicKey",[Od]:"ecdsaWithSHA1",[iv]:"ecdsaWithSHA224",[Nd]:"ecdsaWithSHA256",[Td]:"ecdsaWithSHA384",[Bd]:"ecdsaWithSHA512",[Fx]:"TLS WWW server authentication",[Wx]:"TLS WWW client authentication",[Kx]:"Code Signing",[Gx]:"E-mail Protection",[qx]:"Time Stamping",[zx]:"OCSP Signing",[Yx]:"Signed Data"};class dn{static serialize(e){return this.serializeObj(e).join(`
100
- `)}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,r=0){const n=[];let s=this.pad(r++),o="";const i=e[de.VALUE];i&&(o=` ${i}`),n.push(`${s}${e[de.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[de.NAME]=a,n.push(...this.serializeObj(l,r));else if(c instanceof de)c[de.NAME]=a,n.push(...this.serializeObj(c,r));else if(U.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[de.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=U.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)}}dn.oidSerializer=Dr;dn.algorithmSerializer=CE;var xn,En;class Pr{get parseOptions(){return te(this,En,"f")}get rawData(){return te(this,xn,"f")||ge(this,xn,D.serialize(this.asn),"f"),te(this,xn,"f")}constructor(...e){xn.set(this,void 0),En.set(this,void 0),U.isBufferSource(e[0])?(ge(this,En,e[2],"f"),this.asn=D.parse(e[0],e[1],e[2]),ge(this,xn,U.toArrayBuffer(e[0]),"f"),this.onInit(this.asn)):(ge(this,En,e[1],"f"),this.asn=e[0],this.onInit(this.asn))}equal(e){return e instanceof Pr?ek(e.rawData,this.rawData):!1}toString(e="text"){switch(e){case"asn":return D.toString(this.rawData,te(this,En,"f"));case"text":return dn.serialize(this.toTextObject());case"hex":return Y.ToHex(this.rawData);case"base64":return Y.ToBase64(this.rawData);case"base64url":return Y.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 de(this.getTextName(),{},e)}}xn=new WeakMap,En=new WeakMap;Pr.NAME="ASN";class ht extends Pr{constructor(...e){let r,n;U.isBufferSource(e[0])?(r=U.toArrayBuffer(e[0]),n=e[1]):r=D.serialize(new _t({extnID:e[0],critical:e[1],extnValue:new ue(U.toArrayBuffer(e[2]))})),super(r,_t,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[de.NAME]===ht.NAME&&(e[de.NAME]=Dr.toString(this.type)),e}}var xv;class Er{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[xv]="CryptoProvider",typeof self<"u"&&typeof crypto<"u"?this.set(Er.DEFAULT,crypto):typeof global<"u"&&global.crypto&&global.crypto.subtle&&this.set(Er.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=Er.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(Er.DEFAULT,e);return this}}xv=Symbol.toStringTag;Er.DEFAULT="default";const tt=new Er,OE=/^[0-2](?:\.[1-9][0-9]*)+$/;function NE(t){return new RegExp(OE).test(t)}class Ev{constructor(e={}){this.items={};for(const r in e)this.register(r,e[r])}get(e){return this.items[e]||null}findId(e){return NE(e)?e:this.get(e)}register(e,r){this.items[e]=r,this.items[r]=e}}const rt=new Ev;rt.register("CN","2.5.4.3");rt.register("L","2.5.4.7");rt.register("ST","2.5.4.8");rt.register("O","2.5.4.10");rt.register("OU","2.5.4.11");rt.register("C","2.5.4.6");rt.register("DC","0.9.2342.19200300.100.1.25");rt.register("E","1.2.840.113549.1.9.1");rt.register("G","2.5.4.42");rt.register("I","2.5.4.43");rt.register("SN","2.5.4.4");rt.register("T","2.5.4.12");function TE(t,e){return`\\${Y.ToHex(Y.FromUtf8String(e)).toUpperCase()}`}function BE(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,TE)}class Tt{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 Ev,this.asn=new Ie;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 Ie?this.asn=e:U.isBufferSource(e)?this.asn=D.parse(e,Ie):this.asn=this.fromJSON(e)}getField(e){const r=this.extraNames.findId(e)||rt.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)||rt.get(e)}toString(){return this.asn.map(e=>e.map(r=>{const n=this.getName(r.type)||r.type,s=r.value.anyValue?`#${Y.ToHex(r.value.anyValue)}`:BE(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?`#${Y.ToHex(o.value.anyValue)}`:o.value.toString())}r.push(s)}return r}fromString(e){const r=new Ie,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 Wn([l])),o=u}return r}fromJSON(e){const r=new Ie;for(const n of e){const s=new Wn;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 $a({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=Y.FromHex(r.slice(1));else{const s=this.processStringValue(r);e===this.getName("E")||e===this.getName("DC")?n.value.ia5String=s:Tt.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,`
101
- `).replace(/\\0d/gi,"\r").replace(/\\0g/gi," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return D.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=tt.get()),await n.subtle.digest(s,this.toArrayBuffer())}}const Iv="Cannot initialize GeneralName from ASN.1 data.",Jh=`${Iv} Unsupported string format in use.`,$E=`${Iv} Value doesn't match to GUID regular expression.`,Zh=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Qh="1.3.6.1.4.1.311.25.1",em="1.3.6.1.4.1.311.20.2.3",Cc="dns",Oc="dn",Nc="email",Tc="ip",Bc="url",$c="guid",Rc="upn",zo="id";class Ir extends Pr{constructor(...e){let r;if(e.length===2)switch(e[0]){case Oc:{const n=new Tt(e[1]).toArrayBuffer(),s=D.parse(n,Ie);r=new ne({directoryName:s});break}case Cc:r=new ne({dNSName:e[1]});break;case Nc:r=new ne({rfc822Name:e[1]});break;case $c:{const n=new RegExp(Zh,"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?Y.ToHex(new Uint8Array(Y.FromHex(o)).reverse()):o).join("");r=new ne({otherName:new ro({typeId:Qh,value:D.serialize(new ue(Y.FromHex(s)))})});break}case Tc:r=new ne({iPAddress:e[1]});break;case zo:r=new ne({registeredID:e[1]});break;case Rc:{r=new ne({otherName:new ro({typeId:em,value:D.serialize(Hg.toASN(e[1]))})});break}case Bc:r=new ne({uniformResourceIdentifier:e[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else U.isBufferSource(e[0])?r=D.parse(e[0],ne):r=e[0];super(r)}onInit(e){if(e.dNSName!=null)this.type=Cc,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Nc,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=Tc,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=Bc,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=zo,this.value=e.registeredID;else if(e.directoryName!=null)this.type=Oc,this.value=new Tt(e.directoryName).toString();else if(e.otherName!=null)if(e.otherName.typeId===Qh){this.type=$c;const r=D.parse(e.otherName.value,ue),n=new RegExp(Zh,"i").exec(Y.ToHex(r));if(!n)throw new Error($E);this.value=n.slice(1).map((s,o)=>o<3?Y.ToHex(new Uint8Array(Y.FromHex(s)).reverse()):s).join("-")}else if(e.otherName.typeId===em)this.type=Rc,this.value=D.parse(e.otherName.value,Ve).toString();else throw new Error(Jh);else throw new Error(Jh)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case Oc:case Cc:case $c:case Tc:case zo:case Rc:case Bc:e=this.type.toUpperCase();break;case Nc:e="Email";break;default:throw new Error("Unsupported GeneralName type")}let r=this.value;return this.type===zo&&(r=Dr.toString(r)),new de(e,void 0,r)}}class fn extends Pr{constructor(e){let r;if(e instanceof He)r=e;else if(Array.isArray(e)){const n=[];for(const s of e)if(s instanceof ne)n.push(s);else{const o=D.parse(new Ir(s.type,s.value).rawData,ne);n.push(o)}r=new He(n)}else if(U.isBufferSource(e))r=D.parse(e,He);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 Ir(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[de.NAME]];Array.isArray(s)||(s=[],e[n[de.NAME]]=s),s.push(n)}return e}}fn.NAME="GeneralNames";const Ks="-{5}",lo="\\n",RE=`[^${lo}]+`,_E=`${Ks}BEGIN (${RE}(?=${Ks}))${Ks}`,ME=`${Ks}END \\1${Ks}`,Zn="\\n",jE=`[^:${lo}]+`,DE=`(?:[^${lo}]+${Zn}(?: +[^${lo}]+${Zn})*)`,PE="[a-zA-Z0-9=+/]+",LE=`(?:${PE}${Zn})+`,tm=`${_E}${Zn}(?:((?:${jE}: ${DE})+))?${Zn}?(${LE})${ME}`,UE=new RegExp(`[${lo}]+`,"g");class lt{static isPem(e){return typeof e=="string"&&new RegExp(tm,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");const r=new RegExp(tm,"g"),n=[];let s=null;for(;s=r.exec(e);){const o=s[3].replace(UE,""),i={type:s[1],headers:[],rawData:Y.FromBase64(o)},a=s[2];if(a){const c=a.split(new RegExp(Zn,"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(!U.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:U.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(`
102
- `)}else{if(!r)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:r,rawData:U.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=Y.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(`
103
- `)}}lt.CertificateTag="CERTIFICATE";lt.CrlTag="CRL";lt.CertificateRequestTag="CERTIFICATE REQUEST";lt.PublicKeyTag="PUBLIC KEY";lt.PrivateKeyTag="PRIVATE KEY";class mr extends Pr{static isAsnEncoded(e){return U.isBufferSource(e)||typeof e=="string"}static toArrayBuffer(e){if(typeof e=="string"){if(lt.isPem(e))return lt.decode(e)[0];if(Y.isHex(e))return Y.FromHex(e);if(Y.isBase64(e))return Y.FromBase64(e);if(Y.isBase64Url(e))return Y.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}else{const r=U.toUint8Array(e);if(r.length>0&&r[0]===48)return U.toArrayBuffer(e);const n=Y.ToBinary(e);if(lt.isPem(n))return lt.decode(n)[0];if(Y.isHex(n))return Y.FromHex(n);if(Y.isBase64(n))return Y.FromBase64(n);if(Y.isBase64Url(n))return Y.FromBase64Url(n);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){mr.isAsnEncoded(e[0])?super(mr.toArrayBuffer(e[0]),e[1],e[2]):super(e[0],e[1])}toString(e="pem"){return e==="pem"?lt.encode(this.rawData,this.tag):super.toString(e)}}class Rt extends mr{static async create(e,r=tt.get()){if(e instanceof Rt)return e;if(Er.isCryptoKey(e)){if(e.type!=="public")throw new TypeError("Public key is required");const n=await r.subtle.exportKey("spki",e);return new Rt(n)}else{if(e.publicKey)return e.publicKey;if(U.isBufferSource(e))return new Rt(e);throw new TypeError("Unsupported PublicKeyType")}}constructor(e,r){mr.isAsnEncoded(e)?super(e,bt,r):super(e,r),this.tag=lt.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=tt.get());let a=this.rawData;const c=D.parse(this.rawData,bt,this.parseOptions);return c.algorithm.algorithm===Ws&&(a=VE(c,a)),s.subtle.importKey("spki",a,i,!0,o)}onInit(e){const r=Te.resolve(ln),n=this.algorithm=r.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===an){const s=D.parse(e.subjectPublicKey,$d,this.parseOptions),o=U.toUint8Array(s.modulus);n.publicExponent=U.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=tt.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=tt.get());const o=D.parse(this.rawData,bt,this.parseOptions);return await n.subtle.digest(s,o.subjectPublicKey)}toTextObject(){const e=this.toTextObjectEmpty(),r=D.parse(this.rawData,bt,this.parseOptions);switch(e.Algorithm=dn.serializeAlgorithm(r.algorithm),r.algorithm.algorithm){case io:e["EC Point"]=r.subjectPublicKey;break;case an:default:e["Raw Data"]=r.subjectPublicKey}return e}}function VE(t,e){return t.algorithm=new L({algorithm:an,parameters:null}),e=D.serialize(t),e}class pn extends ht{static async create(e,r=!1,n=tt.get()){if("name"in e&&"serialNumber"in e)return new pn(e,r);const o=await(await Rt.create(e,n)).getKeyIdentifier(n);return new pn(Y.ToHex(o),r)}constructor(...e){if(U.isBufferSource(e[0]))super(e[0],e[1]);else if(typeof e[0]=="string"){const r=new Wr({keyIdentifier:new pd(Y.FromHex(e[0]))});super(ou,e[1],D.serialize(r))}else{const r=e[0],n=r.name instanceof fn?D.parse(r.name.rawData,He):r.name,s=new Wr({authorityCertIssuer:n,authorityCertSerialNumber:Y.FromHex(r.serialNumber)});super(ou,e[1],D.serialize(s))}}onInit(e){super.onInit(e);const r=D.parse(e.extnValue,Wr,this.parseOptions);r.keyIdentifier&&(this.keyId=Y.ToHex(r.keyIdentifier)),(r.authorityCertIssuer||r.authorityCertSerialNumber)&&(this.certId={name:r.authorityCertIssuer||[],serialNumber:r.authorityCertSerialNumber?Y.ToHex(r.authorityCertSerialNumber):""})}toTextObject(){const e=this.toTextObjectWithoutValue(),r=D.parse(this.value,Wr,this.parseOptions);return r.authorityCertIssuer&&(e["Authority Issuer"]=new fn(r.authorityCertIssuer).toTextObject()),r.authorityCertSerialNumber&&(e["Authority Serial Number"]=r.authorityCertSerialNumber),r.keyIdentifier&&(e[""]=r.keyIdentifier),e}}pn.NAME="Authority Key Identifier";class fo extends ht{constructor(...e){if(U.isBufferSource(e[0])){super(e[0],e[1]);const r=D.parse(this.value,Ai,this.parseOptions);this.ca=r.cA,this.pathLength=r.pathLenConstraint}else{const r=new Ai({cA:e[0],pathLenConstraint:e[1]});super(Wg,e[2],D.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}}fo.NAME="Basic Constraints";var rm;(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"})(rm||(rm={}));class rc extends ht{constructor(...e){if(U.isBufferSource(e[0])){super(e[0],e[1]);const r=D.parse(this.value,Ei,this.parseOptions);this.usages=r.map(n=>n)}else{const r=new Ei(e[0]);super(qg,e[1],D.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(r=>Dr.toString(r)).join(", "),e}}rc.NAME="Extended Key Usages";var jn;(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"})(jn||(jn={}));class po extends ht{constructor(...e){if(U.isBufferSource(e[0])){super(e[0],e[1]);const r=D.parse(this.value,Ic,this.parseOptions);this.usages=r.toNumber()}else{const r=new Ic(e[0]);super(Yg,e[1],D.serialize(r)),this.usages=e[0]}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=D.parse(this.value,Ic,this.parseOptions);return e[""]=r.toJSON().join(", "),e}}po.NAME="Key Usages";class _o extends ht{static async create(e,r=!1,n=tt.get()){const o=await(await Rt.create(e,n)).getKeyIdentifier(n);return new _o(Y.ToHex(o),r)}constructor(...e){if(U.isBufferSource(e[0])){super(e[0],e[1]);const r=D.parse(this.value,Or,this.parseOptions);this.keyId=Y.ToHex(r)}else{const r=typeof e[0]=="string"?Y.FromHex(e[0]):e[0],n=new Or(r);super(Qg,e[1],D.serialize(n)),this.keyId=Y.ToHex(r)}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=D.parse(this.value,Or,this.parseOptions);return e[""]=r,e}}_o.NAME="Subject Key Identifier";class jd extends ht{constructor(...e){U.isBufferSource(e[0])?super(e[0],e[1]):super(Zg,e[1],new fn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=D.parse(e.extnValue,wu,this.parseOptions);this.names=new fn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}jd.NAME="Subject Alternative Name";class mt{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new ht(e,r),s=this.items.get(n.type);return s?new s(e,r):n}}mt.items=new Map;class Cv extends ht{constructor(...e){var r;if(U.isBufferSource(e[0])){super(e[0],e[1]);const n=D.parse(this.value,ki,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 ki(n.map(i=>new _a({policyIdentifier:i})));super(Kg,s,D.serialize(o)),this.policies=n}}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(r=>new de("",{},Dr.toString(r))),e}}Cv.NAME="Certificate Policies";mt.register(Kg,Cv);class Ov extends ht{constructor(...e){var r;if(U.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 ns({distributionPoint:new rn({fullName:[new ne({uniformResourceIdentifier:i})]})})),o=new Mn(s);super(lu,e[1],D.serialize(o))}else{const n=new Mn(e[0]);super(lu,e[1],D.serialize(n))}(r=this.distributionPoints)!==null&&r!==void 0||(this.distributionPoints=[])}onInit(e){super.onInit(e);const r=D.parse(e.extnValue,Mn,this.parseOptions);this.distributionPoints=r}toTextObject(){const e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(r=>{var n;const s=new de("");return!((n=r.distributionPoint)===null||n===void 0)&&n.fullName&&(s[""]=r.distributionPoint.fullName.map(o=>new Ir(o).toString()).join(", ")),r.reasons&&(s.Reasons=r.reasons.toString()),r.cRLIssuer&&(s["CRL Issuer"]=r.cRLIssuer.map(o=>o.toString()).join(", ")),s}),e}}Ov.NAME="CRL Distribution Points";class Nv extends ht{constructor(...e){var r,n,s,o;if(U.isBufferSource(e[0]))super(e[0],e[1]);else if(e[0]instanceof Tn){const i=new Tn(e[0]);super(su,e[1],D.serialize(i))}else{const i=e[0],a=new Tn;Xo(a,i,gp,"ocsp"),Xo(a,i,vp,"caIssuers"),Xo(a,i,bp,"timeStamping"),Xo(a,i,wp,"caRepository"),super(su,e[1],D.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=[],D.parse(e.extnValue,Tn,this.parseOptions).forEach(n=>{switch(n.accessMethod){case gp:this.ocsp.push(new Ir(n.accessLocation));break;case vp:this.caIssuers.push(new Ir(n.accessLocation));break;case bp:this.timeStamping.push(new Ir(n.accessLocation));break;case wp:this.caRepository.push(new Ir(n.accessLocation));break}})}toTextObject(){const e=this.toTextObjectWithoutValue();return this.ocsp.length&&Yo(e,"OCSP",this.ocsp),this.caIssuers.length&&Yo(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&Yo(e,"Time Stamping",this.timeStamping),this.caRepository.length&&Yo(e,"CA Repository",this.caRepository),e}}Nv.NAME="Authority Info Access";function Yo(t,e,r){if(r.length===1)t[e]=r[0].toTextObject();else{const n=new de("");r.forEach((s,o)=>{const i=s.toTextObject(),a=`${i[de.NAME]} ${o+1}`;let c=n[a];Array.isArray(c)||(c=[],n[a]=c),c.push(i)}),t[e]=n}}function Xo(t,e,r,n){const s=e[n];s&&(Array.isArray(s)?s:[s]).forEach(i=>{typeof i=="string"&&(i=new Ir("url",i)),t.push(new So({accessMethod:r,accessLocation:D.parse(i.rawData,ne)}))})}class Tv extends ht{constructor(...e){U.isBufferSource(e[0])?super(e[0],e[1]):super(zg,e[1],new fn(e[0]||[]).rawData)}onInit(e){super.onInit(e);const r=D.parse(e.extnValue,He,this.parseOptions);this.names=new fn(r)}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.names.toTextObject();for(const n in r)e[n]=r[n];return e}}Tv.NAME="Issuer Alternative Name";class ds extends Pr{constructor(...e){let r,n;if(U.isBufferSource(e[0]))r=U.toArrayBuffer(e[0]),n=e[1];else{const s=e[0],o=Array.isArray(e[1])?e[1].map(i=>U.toArrayBuffer(i)):[];r=D.serialize(new fr({type:s,values:o}))}super(r,fr,n)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){const e=this.toTextObjectWithoutValue();return e.Value=this.values.map(r=>new de("",{"":r})),e}toTextObjectWithoutValue(){const e=this.toTextObjectEmpty();return e[de.NAME]===ds.NAME&&(e[de.NAME]=Dr.toString(this.type)),e}}ds.NAME="Attribute";class Bv extends ds{constructor(...e){var r;if(U.isBufferSource(e[0]))super(e[0],e[1]);else{const n=new Xi({printableString:e[0]});super(Av,[D.serialize(n)])}(r=this.password)!==null&&r!==void 0||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){const r=D.parse(this.values[0],Xi,this.parseOptions);this.password=r.toString()}}toTextObject(){const e=this.toTextObjectWithoutValue();return e[de.VALUE]=this.password,e}}Bv.NAME="Challenge Password";class Dd extends ds{constructor(...e){var r;if(U.isBufferSource(e[0]))super(e[0],e[1]);else{const n=e[0],s=new Tr;for(const o of n)s.push(D.parse(o.rawData,_t));super(Md,[D.serialize(s)])}(r=this.items)!==null&&r!==void 0||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){const r=D.parse(this.values[0],Tr,this.parseOptions);this.items=r.map(n=>mt.create(D.serialize(n),this.parseOptions))}}toTextObject(){const e=this.toTextObjectWithoutValue(),r=this.items.map(n=>n.toTextObject());for(const n of r)e[n[de.NAME]]=n;return e}}Dd.NAME="Extensions";class nc{static register(e,r){this.items.set(e,r)}static create(e,r){const n=new ds(e,r),s=this.items.get(n.type);return s?new s(e,r):n}}nc.items=new Map;const Mo="crypto.signatureFormatter";class HE{toAsnSignature(e,r){return U.toArrayBuffer(r)}toWebSignature(e,r){return U.toArrayBuffer(r)}}var oi;let ml=oi=class{static createPssParams(e,r){const n=oi.getHashAlgorithm(e);return n?new un({hashAlgorithm:n,maskGenAlgorithm:new L({algorithm:za,parameters:D.serialize(n)}),saltLength:r}):null}static getHashAlgorithm(e){const r=Te.resolve(ln);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 L({algorithm:Li,parameters:null});case"sha-256":return new L({algorithm:Vu,parameters:null});case"sha-384":return new L({algorithm:Ui,parameters:null});case"sha-512":return new L({algorithm:Vi,parameters:null})}}else return new L({algorithm:an,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=oi.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new L({algorithm:Ws,parameters:D.serialize(r)})}else return new L({algorithm:Ws,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case an:return{name:"RSASSA-PKCS1-v1_5"};case Li:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case Vu:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Ui:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Vi:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case Ws:if(e.parameters){const r=D.parse(e.parameters,un);return{name:"RSA-PSS",hash:Te.resolve(ln).toWebAlgorithm(r.hashAlgorithm),saltLength:r.saltLength}}else return{name:"RSA-PSS"}}return null}};ml=oi=f([us()],ml);Te.registerSingleton(bn,ml);let yl=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new L({algorithm:Hi});case"sha-256":return new L({algorithm:Fi});case"sha-384":return new L({algorithm:Wi});case"sha-512":return new L({algorithm:Ki})}return null}toWebAlgorithm(e){switch(e.algorithm){case Hi:return{name:"SHA-1"};case Fi:return{name:"SHA-256"};case Wi:return{name:"SHA-384"};case Ki:return{name:"SHA-512"}}return null}};yl=f([us()],yl);Te.registerSingleton(bn,yl);class wt{addPadding(e,r){const n=U.toUint8Array(r),s=new Uint8Array(e);return s.set(n,e-n.length),s.buffer}removePadding(e,r=!1){let n=U.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=wt.namedCurveSize.get(n)||wt.defaultNamedCurveSize,o=new Pi,i=U.toUint8Array(r);return o.r=this.removePadding(i.slice(0,s),!0),o.s=this.removePadding(i.slice(s,s+s),!0),D.serialize(o)}return null}toWebSignature(e,r){if(e.name==="ECDSA"){const n=D.parse(r,Pi),s=e.namedCurve,o=wt.namedCurveSize.get(s)||wt.defaultNamedCurveSize,i=this.addPadding(o,this.removePadding(n.r)),a=this.addPadding(o,this.removePadding(n.s));return QS(i,a)}return null}}wt.namedCurveSize=new Map;wt.defaultNamedCurveSize=32;const _c="1.3.101.110",nm="1.3.101.111",Mc="1.3.101.112",sm="1.3.101.113";let gl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ed25519":r=Mc;break;case"x25519":r=_c;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":r=Mc;break;case"ed448":r=sm;break}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":r=_c;break;case"x448":r=nm;break}}return r?new L({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case Mc:return{name:"Ed25519"};case sm:return{name:"EdDSA",namedCurve:"Ed448"};case _c:return{name:"X25519"};case nm:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};gl=f([us()],gl);Te.registerSingleton(bn,gl);let vl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"ml-dsa-44":r=ch;break;case"ml-dsa-65":r=uh;break;case"ml-dsa-87":r=lh;break}return r?new L({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case ch:return{name:"ML-DSA-44"};case uh:return{name:"ML-DSA-65"};case lh:return{name:"ML-DSA-87"}}return null}};vl=f([us()],vl);Te.registerSingleton(bn,vl);let bl=class{toAsnAlgorithm(e){let r=null;switch(e.name.toLowerCase()){case"slh-dsa-sha2-128s":r=dh;break;case"slh-dsa-sha2-128f":r=fh;break;case"slh-dsa-sha2-192s":r=ph;break;case"slh-dsa-sha2-192f":r=hh;break;case"slh-dsa-sha2-256s":r=mh;break;case"slh-dsa-sha2-256f":r=yh;break;case"slh-dsa-shake-128s":r=gh;break;case"slh-dsa-shake-128f":r=vh;break;case"slh-dsa-shake-192s":r=bh;break;case"slh-dsa-shake-192f":r=wh;break;case"slh-dsa-shake-256s":r=Ah;break;case"slh-dsa-shake-256f":r=Sh;break}return r?new L({algorithm:r}):null}toWebAlgorithm(e){switch(e.algorithm){case dh:return{name:"SLH-DSA-SHA2-128s"};case fh:return{name:"SLH-DSA-SHA2-128f"};case ph:return{name:"SLH-DSA-SHA2-192s"};case hh:return{name:"SLH-DSA-SHA2-192f"};case mh:return{name:"SLH-DSA-SHA2-256s"};case yh:return{name:"SLH-DSA-SHA2-256f"};case gh:return{name:"SLH-DSA-SHAKE-128s"};case vh:return{name:"SLH-DSA-SHAKE-128f"};case bh:return{name:"SLH-DSA-SHAKE-192s"};case wh:return{name:"SLH-DSA-SHAKE-192f"};case Ah:return{name:"SLH-DSA-SHAKE-256s"};case Sh:return{name:"SLH-DSA-SHAKE-256f"}}return null}};bl=f([us()],bl);Te.registerSingleton(bn,bl);var vs,bs,ws,As,Ss,ks,xs,In;class FE extends mr{get subjectName(){return te(this,bs,"f")||ge(this,bs,new Tt(this.asn.certificationRequestInfo.subject),"f"),te(this,bs,"f")}get subject(){return te(this,ws,"f")||ge(this,ws,this.subjectName.toString(),"f"),te(this,ws,"f")}get signatureAlgorithm(){if(!te(this,As,"f")){const e=Te.resolve(ln);ge(this,As,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return te(this,As,"f")}get signature(){return te(this,Ss,"f")||ge(this,Ss,this.asn.signature,"f"),te(this,Ss,"f")}get publicKey(){return te(this,ks,"f")||ge(this,ks,new Rt(this.asn.certificationRequestInfo.subjectPKInfo,this.parseOptions),"f"),te(this,ks,"f")}get attributes(){return te(this,xs,"f")||ge(this,xs,this.asn.certificationRequestInfo.attributes.map(e=>nc.create(D.serialize(e),this.parseOptions)),"f"),te(this,xs,"f")}get extensions(){if(!te(this,In,"f")){ge(this,In,[],"f");const e=this.getAttribute(Md);e instanceof Dd&&ge(this,In,e.items,"f")}return te(this,In,"f")}get tbs(){return te(this,vs,"f")||ge(this,vs,this.asn.certificationRequestInfoRaw||D.serialize(this.asn.certificationRequestInfo),"f"),te(this,vs,"f")}constructor(e,r){const n=mr.isAsnEncoded(e)?[e,co,r]:[e,r];super(n[0],n[1],n[2]),vs.set(this,void 0),bs.set(this,void 0),ws.set(this,void 0),As.set(this,void 0),Ss.set(this,void 0),ks.set(this,void 0),xs.set(this,void 0),In.set(this,void 0),this.tag=lt.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=tt.get()){const r={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(r,["verify"],e),s=Te.resolveAll(Mo).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=D.parse(this.rawData,co,this.parseOptions),n=r.certificationRequestInfo,s=new de("",{Version:`${nn[n.version]} (${n.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const o=new de("");for(const i of this.attributes){const a=i.toTextObject();o[a[de.NAME]]=a}s.Attributes=o}return e.Data=s,e.Signature=new de("",{Algorithm:dn.serializeAlgorithm(r.signatureAlgorithm),"":r.signature}),e}}vs=new WeakMap,bs=new WeakMap,ws=new WeakMap,As=new WeakMap,Ss=new WeakMap,ks=new WeakMap,xs=new WeakMap,In=new WeakMap;FE.NAME="PKCS#10 Certificate Request";function WE(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 KE(t,e=tt.get()){const r=U.toUint8Array(Y.FromHex(t||"")),n=r.length&&r.some(s=>s>0)?r:e.getRandomValues(new Uint8Array(16));return WE(n)}function GE(t){let e=U.toUint8Array(t);return e.length>1&&e[0]===0&&e[1]>127&&(e=e.slice(1)),Y.ToHex(e)}var Es,Is,Cs,Os,Ns,Ts,Bs,$s,Rs,_s,Cn,Ms;class $v extends mr{get publicKey(){return te(this,Ms,"f")||ge(this,Ms,new Rt(this.asn.tbsCertificate.subjectPublicKeyInfo,this.parseOptions),"f"),te(this,Ms,"f")}get serialNumber(){return te(this,Is,"f")||ge(this,Is,GE(this.asn.tbsCertificate.serialNumber),"f"),te(this,Is,"f")}get subjectName(){return te(this,Cs,"f")||ge(this,Cs,new Tt(this.asn.tbsCertificate.subject),"f"),te(this,Cs,"f")}get subject(){return te(this,Os,"f")||ge(this,Os,this.subjectName.toString(),"f"),te(this,Os,"f")}get issuerName(){return te(this,Ns,"f")||ge(this,Ns,new Tt(this.asn.tbsCertificate.issuer),"f"),te(this,Ns,"f")}get issuer(){return te(this,Ts,"f")||ge(this,Ts,this.issuerName.toString(),"f"),te(this,Ts,"f")}get notBefore(){if(!te(this,Bs,"f")){const e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw new Error("Cannot get 'notBefore' value");ge(this,Bs,e,"f")}return te(this,Bs,"f")}get notAfter(){if(!te(this,$s,"f")){const e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw new Error("Cannot get 'notAfter' value");ge(this,$s,e,"f")}return te(this,$s,"f")}get signatureAlgorithm(){if(!te(this,Rs,"f")){const e=Te.resolve(ln);ge(this,Rs,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return te(this,Rs,"f")}get signature(){return te(this,_s,"f")||ge(this,_s,this.asn.signatureValue,"f"),te(this,_s,"f")}get extensions(){return te(this,Cn,"f")||(ge(this,Cn,[],"f"),this.asn.tbsCertificate.extensions&&ge(this,Cn,this.asn.tbsCertificate.extensions.map(e=>mt.create(D.serialize(e),this.parseOptions)),"f")),te(this,Cn,"f")}get tbs(){return te(this,Es,"f")||ge(this,Es,this.asn.tbsCertificateRaw||D.serialize(this.asn.tbsCertificate),"f"),te(this,Es,"f")}constructor(e,r){const n=mr.isAsnEncoded(e)?[e,sn,r]:[e,r];super(n[0],n[1],n[2]),Es.set(this,void 0),Is.set(this,void 0),Cs.set(this,void 0),Os.set(this,void 0),Ns.set(this,void 0),Ts.set(this,void 0),Bs.set(this,void 0),$s.set(this,void 0),Rs.set(this,void 0),_s.set(this,void 0),Cn.set(this,void 0),Ms.set(this,void 0),this.tag=lt.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=tt.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 Rt)n={...o.algorithm,...this.signatureAlgorithm},s=await o.export(n,["verify"],r);else if(U.isBufferSource(o)){const u=new Rt(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=Te.resolveAll(Mo).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=tt.get()),await n.subtle.digest(s,this.rawData)}async isSelfSigned(e=tt.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){const e=this.toTextObjectEmpty(),r=D.parse(this.rawData,sn,this.parseOptions),n=r.tbsCertificate,s=new de("",{Version:`${nn[n.version]} (${n.version})`,"Serial Number":n.serialNumber,"Signature Algorithm":dn.serializeAlgorithm(n.signature),Issuer:this.issuer,Validity:new de("",{"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 de("");for(const i of this.extensions){const a=i.toTextObject();o[a[de.NAME]]=a}s.Extensions=o}return e.Data=s,e.Signature=new de("",{Algorithm:dn.serializeAlgorithm(r.signatureAlgorithm),"":r.signatureValue}),e}}Es=new WeakMap,Is=new WeakMap,Cs=new WeakMap,Os=new WeakMap,Ns=new WeakMap,Ts=new WeakMap,Bs=new WeakMap,$s=new WeakMap,Rs=new WeakMap,_s=new WeakMap,Cn=new WeakMap,Ms=new WeakMap;$v.NAME="Certificate";class wl{static async createSelfSigned(e,r=tt.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=tt.get()){var n;let s;e.publicKey instanceof Rt?s=e.publicKey.rawData:"publicKey"in e.publicKey?s=e.publicKey.publicKey.rawData:U.isBufferSource(e.publicKey)?s=e.publicKey:s=await r.subtle.exportKey("spki",e.publicKey);const o=KE(e.serialNumber,r),i=e.notBefore||new Date,a=e.notAfter||new Date(i.getTime()+31536e6),c=new sn({tbsCertificate:new pt({version:nn.v3,serialNumber:o,validity:new ko({notBefore:i,notAfter:a}),extensions:new Tr(((n=e.extensions)===null||n===void 0?void 0:n.map(g=>D.parse(g.rawData,_t)))||[]),subjectPublicKeyInfo:D.parse(s,bt)})});if(e.subject){const g=e.subject instanceof Tt?e.subject:new Tt(e.subject);c.tbsCertificate.subject=D.parse(g.toArrayBuffer(),Ie)}if(e.issuer){const g=e.issuer instanceof Tt?e.issuer:new Tt(e.issuer);c.tbsCertificate.issuer=D.parse(g.toArrayBuffer(),Ie)}const u={hash:"SHA-256"},l="signingKey"in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},d=Te.resolve(ln);c.tbsCertificate.signature=c.signatureAlgorithm=d.toAsnAlgorithm(l);const m=D.serialize(c.tbsCertificate),p="signingKey"in e?await r.subtle.sign(l,e.signingKey,m):e.signature,y=Te.resolveAll(Mo).reverse();let v=null;for(const g of y)if(v=g.toAsnSignature(l,p),v)break;if(!v)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=v,new $v(D.serialize(c))}}var om;(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"})(om||(om={}));mt.register(Wg,fo);mt.register(qg,rc);mt.register(Yg,po);mt.register(Qg,_o);mt.register(ou,pn);mt.register(Zg,jd);mt.register(lu,Ov);mt.register(su,Nv);mt.register(zg,Tv);nc.register(Av,Bv);nc.register(Md,Dd);Te.registerSingleton(Mo,HE);Te.registerSingleton(Mo,wt);wt.namedCurveSize.set("P-256",32);wt.namedCurveSize.set("K-256",32);wt.namedCurveSize.set("P-384",48);wt.namedCurveSize.set("P-521",66);const Ze=tb,Al={name:"ECDSA",namedCurve:"P-256",hash:"SHA-256"},ho={name:"ECDSA",namedCurve:"P-256"},qE="1.3.6.1.5.5.7.3.1",zE="1.3.6.1.5.5.7.3.2",Sl=6e4,kl=864e5;function Rv(t){return`${t}.display`}function YE(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(`
104
378
  `)??"";return`-----BEGIN ${t}-----
105
379
  ${r}
106
380
  -----END ${t}-----
107
- `}function XE(t,e){const r=`${t}.${process.pid}.tmp`;El(r,e,{mode:384}),Il(r,t),ea(t,384)}async function im(t){return{privateKey:await Ze.subtle.exportKey("jwk",t.privateKey),publicKey:await Ze.subtle.exportKey("jwk",t.publicKey)}}async function am(t){return{privateKey:await Ze.subtle.importKey("jwk",t.privateKey,ho,!0,["sign"]),publicKey:await Ze.subtle.importKey("jwk",t.publicKey,ho,!0,["verify"])}}function _v(t){const e=new js(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 Qn("sha256").update(r).digest("base64url")}async function JE(){const t=Date.now(),e=await Ze.subtle.generateKey(ho,!0,["sign","verify"]),r=await wl.createSelfSigned({name:"CN=057 Display Core",keys:e,serialNumber:Dn(16).toString("hex"),notBefore:new Date(t-5*Sl),notAfter:new Date(t+10*365*kl),signingAlgorithm:Al,extensions:[new fo(!0,0,!0),new po(jn.keyCertSign|jn.cRLSign,!0),await _o.create(e.publicKey,!1,Ze)]},Ze),n=r.toString("pem"),s=_v(n),o=Qn("sha256").update(s).digest("hex").slice(0,20),i=await Ze.subtle.generateKey(ho,!0,["sign","verify"]),a=await wl.create({subject:`CN=057 Display ${o}`,issuer:r.subject,publicKey:i.publicKey,signingKey:e.privateKey,serialNumber:Dn(16).toString("hex"),notBefore:new Date(t-5*Sl),notAfter:new Date(t+2*365*kl),signingAlgorithm:Al,extensions:[new fo(!1,void 0,!0),new po(jn.digitalSignature,!0),new rc([qE],!0),new jd([{type:"dns",value:"057-display.local"},{type:"ip",value:"127.0.0.1"}]),await pn.create(e.publicKey,!1,Ze)]},Ze);return{version:1,coreId:o,caPin:s,caCertificate:n,serverCertificate:a.toString("pem"),caKeys:await im(e),serverKeys:await im(i)}}async function ZE(t){if(t.caPin!==_v(t.caCertificate))throw new Error("057 Display CA pin does not match its certificate");const e=await am(t.caKeys),r=await am(t.serverKeys),n=YE("PRIVATE KEY",await Ze.subtle.exportKey("pkcs8",r.privateKey));return{coreId:t.coreId,caPin:t.caPin,serverPin:Qn("sha256").update(new js(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 Ze.subtle.importKey("raw",i,ho,!0,["verify"]),c=Date.now(),u=c+5*365*kl,d=(await wl.create({subject:`CN=${o.replace(/[,+\"\\<>;]/g," ").slice(0,80)||"057 Display"}`,issuer:new js(t.caCertificate).subject,publicKey:a,signingKey:e.privateKey,serialNumber:Dn(16).toString("hex"),notBefore:new Date(c-5*Sl),notAfter:new Date(u),signingAlgorithm:Al,extensions:[new fo(!1,void 0,!0),new po(jn.digitalSignature,!0),new rc([zE],!0),await pn.create(e.publicKey,!1,Ze)]},Ze)).toString("pem"),m=new js(d);return{certificate:d,certificateDer:Buffer.from(m.raw).toString("base64"),serial:m.serialNumber.toLowerCase(),fingerprint:m.fingerprint256.replaceAll(":","").toLowerCase(),expiresAt:u}}}}async function QE(t){const e=Rv(t),r=se(e,"identity.json");Dc(ii(e),{recursive:!0,mode:448}),Dc(e,{recursive:!0,mode:448}),ea(e,448);let n;if(fe(r)){if(n=JSON.parse(Cl(r,"utf8")),n.version!==1)throw new Error(`unsupported 057 Display identity version ${String(n.version)}`)}else n=await JE(),XE(r,`${JSON.stringify(n)}
108
- `);return ZE(n)}const e1=4e3,t1=8e3;function r1(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}
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}
109
383
  event: landscape
110
384
  data: ${l.wire}
111
385
 
112
- `))}catch(l){n||(r(l),i(),t.end())}finally{s=!1}}},c=setInterval(()=>{a()},e1),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
113
387
 
114
- `)},t1);t.once("close",i),a()}const Zi=1,n1=12e4;function s1(t,e){const r=`${t}.${process.pid}.tmp`;El(r,e,{mode:384}),Il(r,t),ea(t,384)}class o1{path;state;constructor(e){if(this.path=se(e,"trusted.json"),this.state=fe(this.path)?JSON.parse(Cl(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(){s1(this.path,`${JSON.stringify(this.state,null,1)}
115
- `)}}function i1(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 a1(t){if(t.length!==65||t[0]!==4)throw new Error("the Display public key is not an uncompressed P-256 point");return sb({key:{kty:"EC",crv:"P-256",x:t.subarray(1,33).toString("base64url"),y:t.subarray(33,65).toString("base64url")},format:"jwk"})}class c1{constructor(e){this.identity=e}identity;grants=new Map;create(e=Date.now()){this.grants.clear();const r={id:Dn(18).toString("base64url"),secret:Dn(32),expiresAt:e+n1};this.grants.set(r.id,r);const n={p:Zi,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!==Zi)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||!rb(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(!nb("sha256",i1(e),a1(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 xl="127.0.0.1",u1="0.0.0.0",l1=16*1024;function cm(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 jc(t){return new Promise(e=>{t.close(()=>e()),t.closeAllConnections?.()})}function Lt(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)}
116
- `)}async function d1(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>l1)throw new Error("request body is too large");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}function f1(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 p1(t){const e=t.socket;return e.authorized?e.getPeerCertificate().fingerprint256?.replaceAll(":","").toLowerCase()??null:null}async function h1(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!==hi||r.version!==qs||!r.landscape)throw new Error("private Core returned an incompatible landscape envelope");const n={contract:hi,version:qs,landscape:r.landscape};return{wire:JSON.stringify(n),envelope:n}}function m1(t,e,r){r1(t,async()=>{const n=await h1(e),s=Qn("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 y1(t,e){const r=t.socket.remoteAddress;return(r===xl||r==="::1"||r==="::ffff:127.0.0.1")&&t.headers.authorization===`Bearer ${e}`}async function g1(t){const e=await QE(t.storePath),r=new o1(Rv(t.storePath)),n=new c1(e),s=cb({key:e.serverPrivateKey,cert:`${e.serverCertificate.trimEnd()}
117
- ${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=f1(await d1(l)),y=await n.redeem(p,r);Lt(d,201,{protocol:Zi,coreId:e.coreId,caPin:e.caPin,caCertificate:Buffer.from(new js(e.caCertificate).raw).toString("base64"),clientCertificate:y.certificateDer,expiresAt:y.expiresAt})}catch(p){t.log.warn(`[057] Display pairing refused: ${String(p)}`),Lt(d,403,{error:p instanceof Error?p.message:String(p)})}return}if(l.method==="GET"&&m.pathname==="/v1/landscape"){const p=p1(l);if(!p||!r.trusts(p)){Lt(d,401,{error:"trusted Display certificate required"});return}m1(d,t.loopbackUrl,t.log);return}Lt(d,404,{error:"not found"})})().catch(m=>{t.log.error(`[057] Display request failed: ${String(m)}`),d.headersSent?d.end():Lt(d,500,{error:"Display request failed"})})});s.requestTimeout=15e3,s.headersTimeout=15e3;const o=await cm(s,t.port??0,u1),i=Dn(32).toString("base64url"),a=pm((l,d)=>{(async()=>{if(!y1(l,i)){Lt(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"){Lt(d,201,n.create());return}if(l.method==="GET"&&m.pathname==="/v1/displays"){Lt(d,200,{displays:r.list()});return}if(l.method==="DELETE"&&m.pathname.startsWith("/v1/displays/")){const p=decodeURIComponent(m.pathname.slice(13));Lt(d,r.revoke(p)?200:404,{revoked:p});return}Lt(d,404,{error:"not found"})})()}),c=await cm(a,0,xl).catch(async l=>{throw await jc(s),l}),u={protocol:Zi,landscape:qs,coreId:e.coreId,caPin:e.caPin,port:o,controlUrl:`http://${xl}:${c}`,controlToken:i};return t.log.info(`[057] Display delivery ${e.coreId} listening securely on port ${o}`),{info:u,async close(){await Promise.all([jc(a),jc(s)])}}}const Pd=5057,ar="127.0.0.1",v1=["localhost","127.0.0.1","[::1]","::1"],b1=10,w1={".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 um(t,e,r){let n;try{n=decodeURIComponent(e)}catch{return!1}if(n.includes("\0"))return!1;const s=yo(t,`.${Xv(n)}`);if(s!==t&&!s.startsWith(t+Lc)||!fe(s)||!Qi(s).isFile())return!1;const o=w1[Jv(s).toLowerCase()]??"application/octet-stream";return r.statusCode=200,r.setHeader("content-type",o),r.setHeader("x-content-type-options","nosniff"),ql(r),r.setHeader("cache-control",e.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),dm(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 S1(t,e){const r=String(t.headers["sec-fetch-dest"]??"");if(k1.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 k1=new Set(["iframe","frame","embed","object","fencedframe"]);async function Mv(t){const e=t.log??Iy,r=yo(t.root),n=t.host??ar,s=n===ar||n==="::1"||n==="localhost",o=t.runtime?.path??t.storePath??sa();if(!t.runtime){const y=await kS(o);if(y)throw new Gl(y)}const i=t.runtime??Cy({path:t.storePath,log:e,retention:t.retention,observe:t.observe}),a=import.meta.url.endsWith(".mjs")?wS(import.meta.url,{path:i.path,retention:i.retention,machineId:i.machine.id}):void 0,c=import.meta.url.endsWith(".mjs")?DS(import.meta.url,{path:i.path,machineId:i.machine.id}):void 0,u=qS({runtime:i,log:e,version:t.version,activity:a,landscape:c,allowedHosts:s?v1:null}),l=pm((y,v)=>{(async()=>{try{if(await u(y,v))return;if(y.method!=="GET"&&y.method!=="HEAD"){v.statusCode=405,v.setHeader("allow","GET, HEAD"),v.end();return}const g=new URL(y.url??"/","http://localhost").pathname,C=S1(y,g);if(C){e.warn(`[057] ${C}`),v.statusCode=403,v.setHeader("content-type","text/plain; charset=utf-8"),ql(v),v.end(`${C}
118
- `);return}if(um(r,g==="/"?"/index.html":g,v)||!g.startsWith("/assets/")&&um(r,"/index.html",v))return;v.statusCode=404,v.setHeader("content-type","text/plain; charset=utf-8"),v.end(`not found
119
- `)}catch(g){e.error(`[057] request failed: ${String(g)}`),v.headersSent||(v.statusCode=500),v.end()}})()}),d=await A1(l,t.port??Pd,n,b1).catch(y=>{throw i.stop(),y}),m=s?"localhost":n;let p;if(t.display)try{p=await g1({storePath:i.path,loopbackUrl:`http://${ar}:${d}`,log:e})}catch(y){e.error(`[057] authenticated Display delivery could not start: ${String(y)}`)}return xS(i.path,{pid:process.pid,url:`http://${s?ar:n}:${d}`,version:t.version??"dev",contract:Wl,store:i.path,startedAt:Date.now(),owner:t.owner??"cli",...p?{display:p.info}:{}}),{url:`http://${m}:${d}`,port:d,host:n,runtime:i,server:l,display:p?.info,close(){ES(i.path),a?.close(),c?.close();const y=new Promise(v=>l.close(()=>v()));return l.closeAllConnections?.(),Promise.all([y,p?.close()]).then(()=>i.stop())}}}function x1(t){return yo(Zv(new URL(".",t)),"..","dist")}function E1(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 mo="1.2.3";function I1(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=j1(s);if(o)e.activityOperation=o.operation,e.activityDimension=o.dimension,e.activityItemFilter=o.itemFilter;else if(s==="today")e.activityOperation="summary";else if(Kw.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("=")?C1(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 C1(t,e){const r=t.indexOf(e);return[t.slice(0,r),t.slice(r+1)]}const O1=`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
120
394
 
121
395
  057 observe this machine and serve the interface
122
396
  057 status where the store is, what it holds, what is observed
@@ -132,8 +406,8 @@ ${e.caCertificate.trimStart()}`,ca:e.caCertificate,minVersion:"TLSv1.3",maxVersi
132
406
  057 reset delete the local store
133
407
 
134
408
  Options
135
- --port <n> port to serve on (default ${Pd}; the next free one if taken)
136
- --host <addr> address to bind (default ${ar}; 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)
137
411
  --store <path> store file to use (same as O57_STORE)
138
412
  --open open the interface in the default browser — the running
139
413
  057's, if one (or 057.app) already observes the store
@@ -149,6 +423,8 @@ Environment
149
423
  NO_COLOR, FORCE_COLOR colour for 057 activity (on for a terminal unless NO_COLOR is set)
150
424
  O57_RETAIN_PROCESS_DAYS days of OS process observations to keep (default 7, 0 = forever)
151
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)
152
428
  WORK_ROOTS colon-separated workspace roots to look for 0x2F task state in
153
429
  DSH_HOME CLAUDE_HOME CODEX_HOME GEMINI_HOME CURSOR_GLOBAL_STORAGE
154
430
  override where each source is read from
@@ -159,41 +435,41 @@ to that trusted device on your local network. Reset deletes the SQLite store and
159
435
 
160
436
  --host binds beyond the loopback interface and serves your telemetry, unauthenticated, to
161
437
  anything that can reach that address. Do not do it on a network you do not control.
162
- `;function kr(t){return process.stdout.isTTY?`\x1B[2m${t}\x1B[0m`:t}function Gs(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 N1(t,e,r,n){const s=["",` 057 ${mo}`,` ${t}`,"",kr(" observing this machine only — its process table, and any AI runtime state it finds"),kr(` storing ${e}`),kr(` keeping ${r}`),kr(" sending local only to a paired Display; no account, no cloud, no analytics."),kr(" resetting 057 reset")];return n!==ar&&s.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),s.push(""),s.join(`
163
- `)}async function T1(t){if(!process.stdin.isTTY)return!1;const e=Yv({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=I1(t);if(r.command==="version")return console.log(mo),0;if(r.command==="help")return r.error&&console.error(`057: ${r.error}
164
- `),(r.error?console.error:console.log)(O1),r.error?2:0;r.store&&(process.env.O57_STORE=r.store);const n=sa(),s=ly();if(r.command==="status")return P1(n,s);if(r.command==="activity")return $1(n,s,r);if(r.command==="compact")return L1(n);if(r.command==="reset")return U1(n,r.yes);if(r.desktop)return D1(e,n,s,r.port??0);const o=r.port??V1(process.env.O57_PORT)??Pd,i=r.host??process.env.O57_HOST??ar;let a;try{a=await Mv({root:e,port:o,host:i,storePath:n,retention:s,log:Ld(),version:mo,display:!0})}catch(l){if(l instanceof Gl){const d=l.record;return r.open?(console.log(`
165
- ${l.message}${d.owner==="desktop"?" — 057.app":""}.
166
- Opening ${d.url}
167
- `),await lm(d.url),0):(console.error(`
168
- ${l.message}.
169
- Open ${d.url} (\`057 --open\`), or stop that 057 before starting another.
170
- `),1)}return sc(l)}console.log(N1(a.url,n,ia(s),i)),r.open&&await lm(a.url);let c=!1;const u=()=>{c||(c=!0,console.log(`
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(`
444
+ ${d.message}.
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(`
171
447
  057 stopping — history is on disk
172
- `),a.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}function $1(t,e,r){let n;try{n=aa(t)}catch(s){return sc(s)}try{const s=Date.now(),o=_1(s,r.activityLastDays),i=ky(n,e,_r().id,s);if(r.activityOperation==="compare"&&!r.activityPrevious)return console.error(`057: activity compare currently requires --previous
173
- `),2;let a;if(r.activityOperation==="compare")a={operation:"compare",periodA:o,periodB:M1(o)};else if(r.activityOperation==="breakdown"){if(!r.activityDimension)return console.error(`057: activity breakdown requires --by <dimension>
174
- `),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(qt(E1(i,a),r.activityItemFilter,R1(r,process.stdout,process.env))),0}finally{n.close()}}function R1(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 _1(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 M1(t){const e=t.to-t.from;return{from:t.from-e,to:t.from}}function j1(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 D1(t,e,r,n){const s=c=>{process.stdout.write(`${JSON.stringify(c)}
175
- `)};let o;try{o=await Mv({root:t,port:n,host:ar,storePath:e,retention:r,log:Ld(),version:mo,owner:"desktop",display:!0})}catch(c){if(c instanceof Gl){const u=c.record;return s({event:"running",url:u.url,pid:u.pid,version:u.version,owner:u.owner,contract:u.contract}),0}return c instanceof gt?(s({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(s({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
176
- `),o.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(),s({event:"ready",url:`http://${ar}:${o.port}`,pid:process.pid,version:mo,store:e,contract:Wl,display:o.display}),new Promise(()=>{})}function P1(t,e){let r=null;if(t!==":memory:"&&fe(t))try{r=aa(t)}catch(n){return sc(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=oa(t).map(a=>Vl(a)).filter(a=>a!==null).map(a=>"0"+a.toString(8)).join(" ");if(console.log(`
177
- store ${t}${ay()?" (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)":""}
178
454
  schema ${r?r.schemaVersion:"none"}
179
- size ${Gs(s.total)} ${kr(`(db ${Gs(s.db)}, wal ${Gs(s.wal)})`)}
455
+ size ${mo(s.total)} ${Mr(`(db ${mo(s.db)}, wal ${mo(s.wal)})`)}
180
456
  events ${n.events.toLocaleString()}
181
457
  claims ${n.claims.toLocaleString()}
182
- keeping ${ia(e)}
458
+ keeping ${$a(e)}
183
459
  permissions ${o||"none — no store yet"}
184
460
  `),n.bySource.length===0)console.log(` nothing has been captured yet
185
- `);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 ${kr(c)}`)}console.log("")}const i=uy();return i&&console.log(` a store from a previous layout is at ${i} and is not in use
186
- `),0}finally{r?.close()}}function L1(t){let e;try{e=Cy({path:t,observe:!1,log:Ld()})}catch(r){return sc(r)}try{const r=e.store.sizeBytes().total,n=e.sweep();e.store.compact();const s=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(`
187
463
  removed ${n.processEvents+n.otherEvents} expired events
188
- ${Gs(r)} → ${Gs(s)}
189
- `),0}finally{e.stop()}}async function U1(t,e){const r=wA(t);console.log(`
464
+ ${mo(r)} → ${mo(s)}
465
+ `),0}finally{e.stop()}}async function H1(t,e){const r=gA(t);console.log(`
190
466
  this deletes, permanently:
191
- `);for(const n of r)console.log(` ${n}`);if(console.log(""),!e&&!await T1(" delete the local store?"))return console.log(` nothing was deleted
192
- `),1;for(const n of r)fm(n,{recursive:!0,force:!0});return console.log(` deleted. the next run starts a new store.
193
- `),0}function Ld(){return{info:t=>{process.stderr.write(`${kr(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)}
194
470
  `)},warn:t=>{process.stderr.write(`${t}
195
471
  `)},error:t=>{process.stderr.write(`${t}
196
- `)}}}function sc(t){if(t instanceof gt)return console.error(`
472
+ `)}}}function Tc(t){if(t instanceof Ct)return console.error(`
197
473
  057: ${t.message}
198
474
  ${t.remedy}
199
475
  `),1;const e=t?.code;return e==="EADDRINUSE"?(console.error(`
@@ -202,4 +478,4 @@ anything that can reach that address. Do not do it on a network you do not contr
202
478
  057: cannot bind that address or port (${e}).
203
479
  `),1):(console.error(`
204
480
  057: ${t instanceof Error?t.message:String(t)}
205
- `),1)}function V1(t){if(!t)return;const e=Number(t);return Number.isInteger(e)&&e>=0&&e<=65535?e:void 0}async function lm(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 dO(t){const e=await B1(t,x1(import.meta.url));e!==0&&process.exit(e)}export{x1 as defaultRoot,dO as main,B1 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};