@probnaya/057-cli 1.1.1 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE.md +112 -10
- package/README.md +19 -10
- package/dist/assets/index-BQjibITq.js +649 -0
- package/dist/index.html +1 -1
- package/dist-server/057.mjs +109 -60
- package/package.json +3 -2
- package/dist/assets/index-JB-esYG9.js +0 -646
package/dist-server/057.mjs
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
import{existsSync as L,writeFileSync as vn,renameSync as yn,rmSync as Ms,readFileSync as wn,statSync as qe,mkdirSync as An,chmodSync as Sn,createReadStream as En}from"node:fs";import{createInterface as kn}from"node:readline";import{createServer as In}from"node:http";import{join as D,isAbsolute as Tn,resolve as Re,dirname as Mn,normalize as On,sep as $n,extname as Rn}from"node:path";import{fileURLToPath as xn}from"node:url";import{stat as me,readdir as W,readFile as ie}from"node:fs/promises";import{hostname as Nn,homedir as he}from"node:os";import _n from"node:zlib";import{createHash as Cn}from"node:crypto";import{execFileSync as jn,execFile as Dn}from"node:child_process";import{DatabaseSync as ft}from"node:sqlite";import{promisify as Fn}from"node:util";const Nt=["machine","session","execution","process","artifact"];function Ln(e){return`${e.ns}|${e.parts.join("|")}`}const R={interactions:"interactions",steps:"steps",errors:"errors",retries:"retries",cpuMs:"cpu.ms",tokensInput:"tokens.input",tokensOutput:"tokens.output",tokensCacheRead:"tokens.cacheRead",tokensReasoning:"tokens.reasoning"},Un=[{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 _t(e,t){for(const s of Un){if(e.subjectType===s.a&&t.subjectType===s.b)return{kind:s.kind,from:e,to:t};if(t.subjectType===s.a&&e.subjectType===s.b)return{kind:s.kind,from:t,to:e}}return null}const Pn=(e,t)=>e.validFrom<=t.validTo&&t.validFrom<=e.validTo;function Bn(e,t){const s=Math.max(e.validFrom,t.validFrom),n=Math.min(e.validTo,t.validTo);if(n<s)return 0;const o=Math.max(e.validTo,t.validTo)-Math.min(e.validFrom,t.validFrom);return o<=0?1:(n-s)/o}const Hn=.5;function Wn(e,t){return Pn(e,t)?Bn(e,t)>=Hn?2:1:0}const J=e=>`${e.subjectType}:${e.subjectId}`,Xn="inferred",Gn="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 qn(e){const t=new Map;for(const r of e){const a=t.get(r.key);a?a.push(r):t.set(r.key,[r])}const s=[],n=[];let o=0;for(const[r,a]of[...t.entries()].sort(([i],[c])=>i<c?-1:1)){const i=new Map;for(const b of a){const w=J(b),p=i.get(w);if(!p){i.set(w,{...b});continue}p.validFrom=Math.min(p.validFrom,b.validFrom),p.validTo=Math.max(p.validTo,b.validTo)}const c=[...i.values()].sort((b,w)=>J(b)<J(w)?-1:1);if(c.length<2){o++;continue}const u=[];let h=!1;for(let b=0;b<c.length;b++)for(let w=b+1;w<c.length;w++){const p=c[b],m=c[w];if(p.sourceId===m.sourceId)continue;const v=Wn(p,m);if(v!==0){if(!_t(p,m)){h=!0;continue}u.push({x:p,y:m,tier:v})}}const f=new Map;for(const b of u)for(const w of[b.x,b.y]){const p=J(w);f.set(p,Math.max(f.get(p)??0,b.tier))}const E=new Map;for(const b of u)for(const w of[b.x,b.y]){const p=J(w);f.get(p)===b.tier&&E.set(p,(E.get(p)??0)+1)}if(u.length===0){n.push({key:r,reason:h?"no-pairing-defined":"no-window-overlap",subjects:[...i.keys()].sort()});continue}for(const{x:b,y:w,tier:p}of u){if(f.get(J(b))!==p||f.get(J(w))!==p)continue;if(E.get(J(b))!==1||E.get(J(w))!==1){n.push({key:r,reason:"multiple-candidates",subjects:[J(b),J(w)].sort()});continue}const m=_t(b,w);s.push({from:{type:m.from.subjectType,id:m.from.subjectId},to:{type:m.to.subjectType,id:m.to.subjectId},kind:m.kind,basis:Xn,assumption:Gn,via:r})}}return{relationships:s,ambiguous:n,unmatched:o,considered:t.size}}async function Yn(e,t,s,n,o){const r=[];let a=0,i=0;for(const c of t){const u=Date.now();try{const h=await c.collect(s,n),f=e.append(h);a+=f.inserted,i+=f.duplicate,r.push({id:c.id,ok:!0,collected:h.length,inserted:f.inserted,duplicate:f.duplicate,ms:Date.now()-u})}catch(h){r.push({id:c.id,ok:!1,collected:0,inserted:0,duplicate:0,error:h instanceof Error?h.message:String(h),ms:Date.now()-u})}o?.(r[r.length-1])}return{sources:r,inserted:a,duplicate:i}}function Vn(e,t,s){return qn(e.claims(t,s))}const Os="deepseek-harness",P=e=>typeof e=="number"&&Number.isFinite(e)?e:0,q=e=>typeof e=="string"?e:void 0;function zn(e){const t=e.split("/").filter(Boolean);return(t[t.length-1]??e).toUpperCase()}function Kn(e,t){const s=[],n=e[0];if(!n||n.type!=="session"||!n.id)return s;const o=n.id,r=n.cwd??"",a=P(n.createdAt),i=P(n.delegationDepth),c=zn(r);let u="deepseek",h,f;for(const y of e)if(y.type==="request/context"&&y.data?(u=q(y.data.provider)??u,h=q(y.data.model)??h):y.type==="session/title"&&y.data&&(f=q(y.data.title)??f),h&&f)break;const b={source:{id:Os,instance:t.instance},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let w=a;for(const y of e){const M=P(y.time);M>w&&(w=M)}const p={ns:"fs.cwd",parts:[t.host,r],validFrom:a,validTo:Math.max(a,w)};s.push({...b,occurredAt:a,seq:"session",kind:"began",subject:{type:"session",id:o},claims:r?[p]:void 0,core:{machineId:t.machine.id,label:f,executor:u,model:h,depth:i},attrs:{context:r,"dsh.delegationDepth":i}});const m=y=>`${o}:turn:${y}`;let v=null;const d=new Map,A=new Map;let g=a;for(const y of e){const M=P(y.time)||g;if(M<a)continue;g=M;const l=y.data??{},S=y.seq??`t${M}`,k=T=>({type:"execution",id:m(T)});switch(y.type){case"turn/start":{const T=P(l.turn);v=T,s.push({...b,occurredAt:M,seq:S,kind:"began",subject:k(T),core:{machineId:t.machine.id,sessionId:o,label:f?`${c} · ${f}`:c,executor:u,model:h,depth:i},attrs:{"dsh.turn":T}});break}case"turn/end":{const T=P(l.turn),I=l.reason,x=I?.kind;if(x==="error"){const C=I?.error??{};s.push({...b,occurredAt:M,seq:S,kind:"ended",subject:k(T),core:{outcome:"error",failureCode:q(C.code)??"ERROR",failureMessage:q(C.message)??"Run failed"},attrs:{"dsh.endReason":x}})}else s.push({...b,occurredAt:M,seq:S,kind:"ended",subject:k(T),core:{outcome:x==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":x??"completed"}});v===T&&(v=null);break}case"assistant/message":{const T=P(l.turn),I=l.usage;if(!I)break;const x={[R.tokensInput]:P(I.inputTokens),[R.tokensOutput]:P(I.outputTokens),[R.tokensCacheRead]:P(I.cacheReadTokens),[R.tokensReasoning]:P(I.reasoningTokens),[R.steps]:1};s.push({...b,occurredAt:M,seq:S,kind:"progressed",subject:k(T),core:{measures:x},attrs:{"dsh.inputTokens":P(I.inputTokens),"dsh.outputTokens":P(I.outputTokens),"dsh.cacheReadTokens":P(I.cacheReadTokens),"dsh.reasoningTokens":P(I.reasoningTokens)}});break}case"tool/call":{s.push({...b,occurredAt:M,seq:S,kind:"progressed",subject:k(P(l.turn)),core:{measures:{[R.interactions]:1}},attrs:{"dsh.tool":q(l.name)}});break}case"tool/result":{const T=l.message;let I=!1;for(const x of T?.content??[])x.isError===!0&&(I=!0);I&&s.push({...b,occurredAt:M,seq:S,kind:"progressed",subject:k(P(l.turn)),core:{measures:{[R.errors]:1}}});break}case"llm/retry":{s.push({...b,occurredAt:M,seq:S,kind:"progressed",subject:k(P(l.turn)),core:{measures:{[R.retries]:1}}});break}case"approval/asked":{const T=q(l.id);if(v===null)break;T&&d.set(T,v),s.push({...b,occurredAt:M,seq:S,kind:"blocked",subject:k(v),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":T}});break}case"approval/decided":{const T=q(l.id),I=T?d.get(T):v;if(I==null)break;d.delete(T??""),s.push({...b,occurredAt:M,seq:S,kind:"resumed",subject:k(I),attrs:{"dsh.approvalId":T}});break}case"tool-workflow/agent-start":{if(v===null)break;const T=q(l.childId);if(!T)break;const I=`${o}:agent:${T}`;A.set(`${q(l.runId)}:${P(l.seq)}`,I),s.push({...b,occurredAt:M,seq:S,kind:"began",subject:{type:"execution",id:I},core:{machineId:t.machine.id,sessionId:o,label:q(l.label)??`${c} · SUB`,executor:u,model:h,parentId:m(v),depth:i+1},attrs:{"dsh.childId":T}});break}case"tool-workflow/agent-end":{const T=`${q(l.runId)}:${P(l.seq)}`,I=A.get(T);if(!I)break;A.delete(T);const x=q(l.outcome);s.push({...b,occurredAt:M,seq:S,kind:"ended",subject:{type:"execution",id:I},core:x==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:x??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":x}});break}}}if(t.closeOpenTurns){const y="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.";v!==null&&s.push({...b,occurredAt:g,seq:"close:turn",kind:"ended",subject:{type:"execution",id:m(v)},core:{outcome:"interrupted"},basis:"inferred",assumption:y});for(const M of A.values())s.push({...b,occurredAt:g,seq:`close:${M}`,kind:"ended",subject:{type:"execution",id:M},core:{outcome:"interrupted"},basis:"inferred",assumption:y});s.push({...b,occurredAt:g,seq:"close:session",kind:"ended",subject:{type:"session",id:o},basis:"inferred",assumption:y})}return t.since!==void 0?s.filter(y=>y.occurredAt>=t.since):s}function Jn(e){const t=[];let s=0;for(;s<e.length;){let n=e.indexOf(`
|
|
2
|
-
`,
|
|
3
|
-
`))if(
|
|
4
|
-
`))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function Mo(e){if(!e)return{};const t=e.output_tokens_details;return{[R.tokensInput]:oe(e.input_tokens)+oe(e.cache_creation_input_tokens),[R.tokensOutput]:oe(e.output_tokens),[R.tokensCacheRead]:oe(e.cache_read_input_tokens),[R.tokensReasoning]:oe(t?.thinking_tokens),[R.steps]:1}}function Oo(e,t){const s=e.filter(d=>ve(d.timestamp)!==void 0);if(s.length===0)throw new re("transcript has no timestamped records",t.path);const n=e.find(d=>typeof d.sessionId=="string")?.sessionId;if(n&&n!==t.sessionId)throw new re(`transcript names session ${n} but is filed under ${t.sessionId}`,t.path);const o=e.find(d=>typeof d.version=="string")?.version,r=e.find(d=>typeof d.cwd=="string")?.cwd??"",a=e.find(d=>typeof d.gitBranch=="string")?.gitBranch,i=e.find(d=>typeof d.entrypoint=="string")?.entrypoint,c=Q(r).toUpperCase(),u=t.sessionId,h=Fs(u),f=ve(s[0].timestamp),E=ve(s[s.length-1].timestamp),w={source:{id:Se,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},p=(d,A)=>({path:t.path,...d?{recordId:d}:{},...A!==void 0?{index:A}:{},...o?{sourceVersion:o}:{}}),m=[{...w,occurredAt:f,kind:"began",subject:{type:"session",id:h},claims:[{ns:"agent.session",parts:[Ds,u],validFrom:f,validTo:E}],core:{machineId:t.machine.id,label:c,executor:Se},attrs:{context:r,"claude.sessionId":u,"claude.gitBranch":a,"claude.entrypoint":i,"claude.version":o},provenance:p(u),seq:"session"}],v=[];for(let d=0;d<e.length;d++){const A=e[d];A.type==="user"&&typeof A.promptSource=="string"&&ve(A.timestamp)!==void 0&&v.push(d)}if(v.length===0)throw new re(`transcript has ${e.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,t.path,o);for(let d=0;d<v.length;d++){const A=v[d],g=d+1<v.length?v[d+1]:e.length,y=d+1,M=`${h}:turn:${y}`,l=ve(e[A].timestamp),S=e.slice(A,g).some($=>$.isSidechain===!0);let k,T=l,I,x=!1;const C=[];for(let $=A;$<g;$++){const O=e[$],U=ve(O.timestamp);if(U===void 0)continue;const X=O.type==="assistant"||O.type==="user"&&Array.isArray(O.message?.content);if(X&&U>T&&(T=U),X?(I=O,x=!1):O.type==="system"&&ko.has(O.subtype??"")&&(x=!0),O.type==="assistant"&&O.message){k??=O.message.model;const N=(Array.isArray(O.message.content)?O.message.content:[]).filter(K=>!!K&&typeof K=="object"&&K.type==="tool_use"),V={...Mo(O.message.usage)};N.length&&(V[R.interactions]=N.length),C.push({...w,occurredAt:U,kind:"progressed",subject:{type:"execution",id:M},core:{measures:V},attrs:{...N.length?{"claude.tools":N.map(K=>K.name??"unknown")}:{},...O.message.model?{"claude.model":O.message.model}:{},...O.requestId?{"claude.requestId":O.requestId}:{},...O.message.stop_reason?{"claude.stopReason":O.message.stop_reason}:{},...O.message.usage?{"claude.usage.inputTokens":oe(O.message.usage.input_tokens),"claude.usage.outputTokens":oe(O.message.usage.output_tokens),"claude.usage.cacheReadTokens":oe(O.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":oe(O.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":O.message.usage.service_tier}:{}},provenance:p(O.uuid,$),seq:O.uuid??`a${$}`})}else if(O.type==="user"&&O.message&&Array.isArray(O.message.content)){const j=O.message.content.filter(N=>!!N&&typeof N=="object"&&N.is_error===!0).length;j&&C.push({...w,occurredAt:U,kind:"progressed",subject:{type:"execution",id:M},core:{measures:{[R.errors]:j}},provenance:p(O.uuid,$),seq:O.uuid??`e${$}`})}}if(m.push({...w,occurredAt:l,kind:"began",subject:{type:"execution",id:M},core:{machineId:t.machine.id,sessionId:h,label:`${c} · TURN ${y}`,executor:Se,model:k,depth:S?1:0},attrs:{"claude.turn":y,"claude.promptSource":e[A].promptSource,"claude.promptId":e[A].promptId,...S?{"claude.isSidechain":!0}:{}},provenance:p(e[A].uuid,A),seq:`turn:${y}`}),m.push(...C),d+1<v.length||x)m.push({...w,occurredAt:T,kind:"ended",subject:{type:"execution",id:M},core:{outcome:"completed"},provenance:p(e[A].uuid,A),seq:`turn:${y}:end`});else if(t.closeOpenTurns){const $=I?.type==="assistant"&&(I.message?.stop_reason==="end_turn"||I.message?.stop_reason==="stop_sequence");m.push({...w,occurredAt:T,kind:"ended",subject:{type:"execution",id:M},core:{outcome:$?"completed":"interrupted"},basis:"inferred",assumption:Io,provenance:p(e[A].uuid,A),seq:`turn:${y}:end`})}}return m}function gt(){return process.env.CLAUDE_HOME||D(he(),".claude")}const it=()=>D(gt(),"sessions"),$o=()=>D(gt(),"projects"),Wt=new Map;async function Ro(e,t,s){const n=it();if(!L(n))return;s.identityAvailable=!0;let o;try{o=await W(n)}catch(r){s.problems.push({path:n,message:String(r)});return}for(const r of o){if(!r.endsWith(".json"))continue;const a=D(n,r);try{const i=So(JSON.parse(await ie(a,"utf8")),a);s.envelopes.push(se(Eo(i,a,{machine:e,host:de(),observedAt:t,now:t}))),s.registryEntries++}catch(i){s.problems.push({path:a,message:i instanceof Error?i.message:String(i),sourceVersion:i instanceof re?i.sourceVersion:void 0})}}}async function Ls(){const e=$o();if(!L(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(D(e,n))}catch{continue}for(const r of o)r.endsWith(".jsonl")&&t.push({path:D(e,n,r),sessionId:r.slice(0,-6),project:n})}return t}async function xo(e,t,s,n){const o=await Ls();if(o.length!==0){n.storedAvailable=!0;for(const r of o){let a;try{a=await me(r.path)}catch{continue}if(a.mtimeMs<t)continue;const i=Date.now()-a.mtimeMs>ht,c=`${a.mtimeMs}:${a.size}:${i}`,u=Wt.get(r.path);let h;if(u&&u.stamp===c)h=u.envelopes;else try{const f=To(await ie(r.path,"utf8"));h=Oo(f,{machine:e,host:de(),observedAt:Date.now(),path:r.path,sessionId:r.sessionId,closeOpenTurns:i}).map(se),Wt.set(r.path,{stamp:c,envelopes:h})}catch(f){n.transcriptsFailed++,n.problems.push({path:r.path,message:f instanceof Error?f.message:String(f),sourceVersion:f instanceof re?f.sourceVersion:void 0});continue}n.transcriptsRead++;for(const f of h)f.occurredAt>=t&&f.occurredAt<=s&&n.envelopes.push(f)}}}async function Us(e,t){const s=ge(),n=Date.now(),o={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await Ro(s,n,o),await xo(s,e,t,o),o}async function No(e,t){return(await Us(e,t)).envelopes}async function Xt(){const e=gt(),t=L(it())?(await W(it()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,s=(await Ls()).length;return{available:t>0||s>0,present:L(e),home:e,registry:t,transcripts:s}}const De="codex",_o="codex",Co=10*6e4;class we extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const jo=e=>`codex:${e}`,Z=e=>typeof e=="number"&&Number.isFinite(e)?e:0,F=e=>typeof e=="string"&&e?e:void 0,Je=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function Do(e){const t=[];for(const s of e.split(`
|
|
5
|
-
`))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function Fo(e){const t=Z(e.input_tokens),s=Z(e.cached_input_tokens);return{[R.tokensInput]:Math.max(0,t-s),[R.tokensOutput]:Z(e.output_tokens),[R.tokensCacheRead]:s,[R.tokensReasoning]:Z(e.reasoning_output_tokens),[R.steps]:1}}function Lo(e,t){const s=e.find(d=>d.type==="session_meta");if(!s||!s.payload)throw new we("rollout has no session_meta record",t.path);const n=s.payload,o=F(n.cli_version),r=F(n.session_id)??F(n.id);if(r&&r!==t.sessionId)throw new we(`rollout names session ${r} but is filed under ${t.sessionId}`,t.path,o);const a=F(n.cwd)??"",i=Je(n.timestamp)??Je(s.timestamp);if(i===void 0)throw new we("session_meta has no parseable timestamp",t.path,o);const c=Q(a).toUpperCase(),u=jo(t.sessionId),f={source:{id:De,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},E=(d,A)=>({path:t.path,...d?{recordId:d}:{},...A!==void 0?{index:A}:{},...o?{sourceVersion:o}:{}}),b=[];let w=null,p=i,m=0;for(let d=0;d<e.length;d++){const A=e[d],g=Je(A.timestamp);g!==void 0&&g>p&&(p=g);const y=A.payload;if(!y)continue;if(A.type==="turn_context"){w&&F(y.turn_id)===w.turnId&&(w.model??=F(y.model),w.effort??=F(y.effort));continue}if(A.type!=="event_msg")continue;const M=F(y.type);if(M==="task_started"){const S=F(y.turn_id);if(!S||g===void 0)throw new we(`task_started at ordinal ${A.ordinal} is missing turn_id or timestamp`,t.path,o);w={turnId:S,startedAt:g,interior:[],lastAt:g},b.push(w);continue}if(M==="task_complete"){const S=F(y.turn_id),k=b.find(T=>T.turnId===S)??w;if(k&&g!==void 0){k.completedAt=g;const T=y.error;k.outcome=T?"error":"completed",k.failureMessage=T?F(T.message):void 0,k.lastAt=Math.max(k.lastAt,g)}k===w&&(w=null);continue}if(M==="token_count"||M==="item_completed"){if(!w){m++;continue}if(g===void 0)continue}else continue;const l=`${u}:turn:${w.turnId}`;if(M==="token_count"){const k=y.info?.last_token_usage;if(!k)continue;w.lastAt=Math.max(w.lastAt,g),w.interior.push({...f,occurredAt:g,kind:"progressed",subject:{type:"execution",id:l},core:{measures:Fo(k)},attrs:{"codex.usage.inputTokens":Z(k.input_tokens),"codex.usage.cachedInputTokens":Z(k.cached_input_tokens),"codex.usage.cacheWriteInputTokens":Z(k.cache_write_input_tokens),"codex.usage.outputTokens":Z(k.output_tokens),"codex.usage.reasoningOutputTokens":Z(k.reasoning_output_tokens)},provenance:E(void 0,A.ordinal),seq:`o${A.ordinal??d}`});continue}if(M==="item_completed"){const S=y.item,k=F(S?.type);if(!S||!k)continue;w.lastAt=Math.max(w.lastAt,g);let T,I;if(k==="CommandExecution"){const x=Z(S.exit_code);T={[R.interactions]:1,...x!==0?{[R.errors]:1}:{}},I={"codex.itemType":k,"codex.exitCode":x,...S.process_id!==void 0?{"codex.processId":S.process_id}:{},...F(S.status)?{"codex.status":S.status}:{}}}else if(k==="McpToolCall"){const x=F(S.status)==="failed"||F(S.status)==="error";T={[R.interactions]:1,...x?{[R.errors]:1}:{}},I={"codex.itemType":k,"codex.tool":[F(S.server),F(S.tool)].filter(Boolean).join("."),...F(S.status)?{"codex.status":S.status}:{}}}else if(k==="WebSearch")T={[R.interactions]:1},I={"codex.itemType":k};else if(k==="FileChange"){const x=S.changes;T={[R.interactions]:1},I={"codex.itemType":k,...x&&typeof x=="object"?{"codex.fileChanges":Object.entries(x).map(([C,_])=>({path:C,kind:F(_?.type)}))}:{}}}else continue;w.interior.push({...f,occurredAt:g,kind:"progressed",subject:{type:"execution",id:l},core:{measures:T},attrs:I,provenance:E(F(S.id),A.ordinal),seq:`o${A.ordinal??d}`})}}if(b.length===0&&m>0)throw new we(`rollout has ${m} work records but no task_started marker`,t.path,o);const v=[{...f,occurredAt:i,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[_o,t.sessionId],validFrom:i,validTo:p}],core:{machineId:t.machine.id,label:c,executor:De},attrs:{context:a,"codex.sessionId":t.sessionId,"codex.cliVersion":o,"codex.originator":F(n.originator),"codex.source":F(n.source),"codex.modelProvider":F(n.model_provider),...Uo(n.git)},provenance:E(t.sessionId,s.ordinal),seq:"session"}];for(let d=0;d<b.length;d++){const A=b[d],g=`${u}:turn:${A.turnId}`;v.push({...f,occurredAt:A.startedAt,kind:"began",subject:{type:"execution",id:g},core:{machineId:t.machine.id,sessionId:u,label:`${c} · TURN ${d+1}`,executor:De,model:A.model,depth:0},attrs:{"codex.turnId":A.turnId,...A.effort?{"codex.effort":A.effort}:{}},provenance:E(A.turnId),seq:`turn:${A.turnId}`}),v.push(...A.interior),A.completedAt!==void 0?v.push({...f,occurredAt:A.completedAt,kind:"ended",subject:{type:"execution",id:g},core:{outcome:A.outcome??"completed",...A.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:A.failureMessage??"turn failed"}:{}},provenance:E(A.turnId),seq:`turn:${A.turnId}:end`}):t.now-p>Co&&v.push({...f,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:A.lastAt,kind:"ended",subject:{type:"execution",id:g},core:{outcome:"interrupted"},provenance:E(A.turnId),seq:`turn:${A.turnId}:end`})}return v}function Uo(e){if(!e||typeof e!="object")return{};const t=e;return{...F(t.branch)?{"codex.gitBranch":t.branch}:{},...F(t.commit_hash)?{"codex.gitCommit":t.commit_hash}:{},...F(t.repository_url)?{"codex.gitOriginUrl":t.repository_url}:{}}}function Ps(){return process.env.CODEX_HOME||D(he(),".codex")}const Bs=()=>D(Ps(),"sessions"),Po=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,Gt=new Map;async function Hs(){const e=Bs();if(!L(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(D(e,n))}catch{continue}for(const r of o){let a;try{a=await W(D(e,n,r))}catch{continue}for(const i of a){let c;try{c=await W(D(e,n,r,i))}catch{continue}for(const u of c){const h=Po.exec(u);h&&t.push({path:D(e,n,r,i,u),sessionId:h[1]})}}}}return t}async function Ws(e,t){const s=ge(),n=Date.now(),o={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},r=await Hs();if(r.length===0)return o.storedAvailable=L(Bs()),o;o.storedAvailable=!0;for(const a of r){let i;try{i=await me(a.path)}catch{continue}if(i.mtimeMs<e)continue;const c=`${i.mtimeMs}:${i.size}`,u=Gt.get(a.path);let h;if(u&&u.stamp===c)h=u.envelopes;else try{const f=Do(await ie(a.path,"utf8"));h=Lo(f,{machine:s,host:de(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n}).map(se),Gt.set(a.path,{stamp:c,envelopes:h})}catch(f){o.rolloutsFailed++,o.problems.push({path:a.path,message:f instanceof Error?f.message:String(f),sourceVersion:f instanceof we?f.sourceVersion:void 0});continue}o.rolloutsRead++;for(const f of h)f.occurredAt>=e&&f.occurredAt<=t&&o.envelopes.push(f)}return o}async function Bo(e,t){return(await Ws(e,t)).envelopes}async function qt(){const e=Ps(),t=(await Hs()).length;return{available:t>0,present:L(e),home:e,rollouts:t}}const Oe="cursor",Ho="cursor";class Fe extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const at=e=>`cursor:${e}`,Ae=e=>typeof e=="string"&&e?e:void 0,Ne=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Yt=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function Xs(e,t){if(typeof e.composerId!="string"||!e.composerId)throw new Fe("composer header has no composerId",t);if(typeof e.createdAt!="number"||!Number.isFinite(e.createdAt))throw new Fe("composer header has no numeric createdAt",t);if(typeof e.lastUpdatedAt!="number"||!Number.isFinite(e.lastUpdatedAt))throw new Fe("composer header has no numeric lastUpdatedAt",t)}function Wo(e,t){Xs(e,t.path);const s=e.value??{},n=s.subagentInfo,o=n?Ae(n.parentComposerId):void 0,r=t.workspacePath??"",a=Ae(s.name)?.toUpperCase()??(r?Q(r).toUpperCase():"CURSOR");return{source:{id:Oe,instance:t.host},occurredAt:e.createdAt,observedAt:t.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:at(e.composerId)},claims:[{ns:"agent.session",parts:[Ho,e.composerId],validFrom:e.createdAt,validTo:e.lastUpdatedAt}],basis:"measured",core:{machineId:t.machine.id,label:a,executor:Oe,...o?{parentId:at(o)}:{}},attrs:{context:r,"cursor.composerId":e.composerId,"cursor.workspaceId":e.workspaceId,"cursor.isSubagent":e.isSubagent,...n?{"cursor.parentComposerId":Ae(n.parentComposerId),"cursor.subagentType":Ae(n.subagentTypeName)}:{},...Ne(s.totalLinesAdded)!==void 0?{"cursor.linesAdded":s.totalLinesAdded}:{},...Ne(s.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":s.totalLinesRemoved}:{},...Ne(s.filesChangedCount)!==void 0?{"cursor.filesChanged":s.filesChangedCount}:{},...Ae(s.unifiedMode)?{"cursor.mode":s.unifiedMode}:{},...Ne(s._v)!==void 0?{"cursor.schemaVersion":s._v}:{}},provenance:{path:t.path,recordId:e.composerId},seq:"composer"}}const Vt="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 Xo(e,t,s){Xs(e,s.path);const n=at(e.composerId),r={source:{id:Oe,instance:s.host},observedAt:s.observedAt,clock:"wall",stratum:"stored-semantics"},a=h=>({path:s.path,...h?{recordId:h}:{}}),i=[];for(let h=0;h<t.length;h++)t[h].type===1&&i.push(h);const c=[];let u=0;for(let h=0;h<i.length;h++){const f=i[h],E=h+1<i.length?i[h+1]:t.length,b=h+1,w=t.slice(f,E),p=w.map(y=>({bubble:y,at:Yt(y.createdAt)})).filter(y=>y.at!==void 0);if(p.length<2){u++;continue}const m=Math.min(...p.map(y=>y.at)),v=Math.max(...p.map(y=>y.at)),d=`${n}:turn:${b}`,A=w.filter(y=>y.toolName&&Yt(y.createdAt)===void 0),g=A.filter(y=>y.toolStatus==="error").length;c.push({...r,occurredAt:m,kind:"began",subject:{type:"execution",id:d},basis:"inferred",assumption:Vt,core:{machineId:s.machine.id,sessionId:n,label:`${Ae(e.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${b}`,executor:Oe,depth:e.isSubagent?1:0,...A.length?{measures:{[R.interactions]:A.length,...g?{[R.errors]:g}:{}}}:{}},attrs:{"cursor.turn":b},provenance:a(t[f].bubbleId),seq:`turn:${b}`});for(const{bubble:y,at:M}of p){if(!y.toolName)continue;const l=y.toolStatus==="error",S={[R.interactions]:1,...l?{[R.errors]:1}:{}};c.push({...r,occurredAt:M,kind:"progressed",subject:{type:"execution",id:d},basis:"measured",core:{measures:S},attrs:{"cursor.tool":y.toolName,...y.toolStatus?{"cursor.toolStatus":y.toolStatus}:{}},provenance:a(y.bubbleId),seq:y.bubbleId})}c.push({...r,occurredAt:v,kind:"ended",subject:{type:"execution",id:d},basis:"inferred",assumption:Vt,core:{outcome:"completed"},provenance:a(t[f].bubbleId),seq:`turn:${b}:end`})}return{drafts:c,turns:i.length,untimedTurns:u}}function Te(){return process.env.CURSOR_GLOBAL_STORAGE||D(he(),"Library","Application Support","Cursor","User","globalStorage")}function Go(){return process.env.CURSOR_WORKSPACE_STORAGE||D(Te(),"..","workspaceStorage")}const Gs=()=>D(Te(),"state.vscdb"),zt=new Map;async function qo(){const e=new Map,t=Go();if(!L(t))return e;let s;try{s=await W(t)}catch{return e}for(const n of s)try{const o=JSON.parse(await ie(D(t,n,"workspace.json"),"utf8"));typeof o.folder=="string"&&o.folder.startsWith("file://")&&e.set(n,decodeURIComponent(o.folder.slice(7)))}catch{continue}return e}function Yo(e,t){let s;if(e.value)try{s=JSON.parse(e.value)}catch{s=void 0}const n=a=>typeof a=="number"&&Number.isFinite(a)?a:void 0,o=e.lastUpdatedAt??n(s?.lastUpdatedAt)??n(s?.conversationCheckpointLastUpdatedAt)??e.createdAt??NaN,r={composerId:e.composerId,workspaceId:e.workspaceId??void 0,createdAt:e.createdAt??NaN,lastUpdatedAt:o,isSubagent:e.isSubagent===1,value:s};if(!Number.isFinite(r.createdAt)||!Number.isFinite(r.lastUpdatedAt))throw new Fe(`composer ${e.composerId} has no numeric createdAt/lastUpdatedAt`,t);return r}function Vo(e,t){const s=e.prepare("SELECT value FROM cursorDiskKV WHERE key = ?").get(`composerData:${t}`);if(!s?.value)return[];const n=typeof s.value=="string"?s.value:Buffer.from(s.value).toString("utf8"),r=JSON.parse(n).fullConversationHeadersOnly??[],a=e.prepare("SELECT key, value FROM cursorDiskKV WHERE key >= ? AND key < ?").all(`bubbleId:${t}:`,`bubbleId:${t};`),i=new Map;for(const c of a){const u=c.key.slice(`bubbleId:${t}:`.length);try{const h=typeof c.value=="string"?c.value:Buffer.from(c.value).toString("utf8"),f=JSON.parse(h);i.set(u,{bubbleId:u,type:f.type,createdAt:typeof f.createdAt=="string"&&f.createdAt?f.createdAt:void 0,toolName:f.toolFormerData?.name,toolStatus:f.toolFormerData?.status})}catch{continue}}return r.filter(c=>typeof c.bubbleId=="string").map(c=>i.get(c.bubbleId)??{bubbleId:c.bubbleId,type:c.type})}async function qs(e,t){const s=ge(),n=Date.now(),o=Gs(),r={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!L(o))return r;r.storedAvailable=!0;const a=await qo();let i;try{i=new ft(o,{readOnly:!0})}catch(c){return r.problems.push({path:o,message:`cannot open read-only: ${String(c)}`}),r}try{let c;try{c=i.prepare("SELECT composerId, workspaceId, createdAt, lastUpdatedAt, isSubagent, value FROM composerHeaders WHERE (lastUpdatedAt >= ? OR lastUpdatedAt IS NULL) AND createdAt <= ?").all(e,t)}catch(u){return r.problems.push({path:o,message:`composerHeaders unreadable: ${String(u)}`}),r}for(const u of c)try{const h=Yo(u,o);if(h.lastUpdatedAt<e)continue;const f={machine:s,host:de(),observedAt:n,path:o,workspacePath:h.workspaceId?a.get(h.workspaceId):void 0};r.envelopes.push(se(Wo(h,f)));const E=`${h.lastUpdatedAt}`,b=zt.get(h.composerId);let w;if(b&&b.stamp===E)w=b.envelopes;else{const p=Vo(i,h.composerId),{drafts:m}=Xo(h,p,f);w=m.map(se),zt.set(h.composerId,{stamp:E,envelopes:w})}for(const p of w)p.occurredAt>=e&&p.occurredAt<=t&&r.envelopes.push(p);r.composersRead++}catch(h){r.composersFailed++,r.problems.push({path:o,message:`${u.composerId}: ${h instanceof Error?h.message:String(h)}`})}}finally{i.close()}return r}async function zo(e,t){return(await qs(e,t)).envelopes}async function Kt(){const e=Gs();if(!L(e))return{available:!1,present:!1,globalStorage:Te()};try{const t=new ft(e,{readOnly:!0});try{const s=t.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:s.n>0,present:!0,globalStorage:Te(),composers:s.n}}finally{t.close()}}catch{return{available:!1,present:!0,globalStorage:Te()}}}const Le="gemini",Ko="gemini";class We extends Error{constructor(t,s){super(t),this.path=s,this.name="GeminiFormatError"}path}const Jo="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 Qo(e){return(typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(s=>s?.text).filter(s=>typeof s=="string").join(`
|
|
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
|
|
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
7
|
`):"").split(`
|
|
7
|
-
`)[0].trim().slice(0,200)||"Gemini reported an error"}const
|
|
8
|
-
`).filter(i=>i.trim());if(s.length===0)throw new We("session file is empty",t);let n=null;const o=[],r=new Map,a=i=>{const c=i;!c||typeof c!="object"||typeof c.id!="string"||(r.has(c.id)||o.push(c.id),r.set(c.id,c))};for(const i of s){let c;try{c=JSON.parse(i)}catch{continue}if(!c||typeof c!="object")continue;const u=c;if(!n&&typeof u.sessionId=="string"){n=u;continue}const h=u.$set;if(h){const f=h.messages;if(Array.isArray(f))for(const E of f)a(E);continue}typeof u.id=="string"&&a(u)}if(!n||!n.sessionId)throw new We("session file has no header with a sessionId",t);return{header:n,messages:o.map(i=>r.get(i))}}const Ys=e=>Array.isArray(e.content)&&e.content.some(t=>!!t&&typeof t=="object"&&"functionResponse"in t);function tr(e){if(e.type!=="user"||Ys(e))return!1;const t=Array.isArray(e.content)?e.content.map(n=>n?.text).filter(n=>typeof n=="string"):[];if(t.length===0)return!1;const s=t[0];return!s.startsWith("<session_context>")&&!s.startsWith("[System:")}function sr(e){const t=ee(e.input),s=ee(e.cached);return{[R.tokensInput]:Math.max(0,t-s),[R.tokensOutput]:ee(e.output)+ee(e.thoughts),[R.tokensCacheRead]:s,[R.tokensReasoning]:ee(e.thoughts),[R.steps]:1}}function nr(e,t){const{header:s,messages:n}=e,o=s.sessionId,r=ye(s.startTime);if(r===void 0)throw new We("session header has no parseable startTime",t.path);const a=n.filter(m=>ye(m.timestamp)!==void 0),i=a.length?Math.max(...a.map(m=>ye(m.timestamp))):r,c=t.workspacePath??"",u=c?Q(c).toUpperCase():"GEMINI",h=Zo(o),E={source:{id:Le,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},b=m=>({path:t.path,...m?{recordId:m}:{}}),w=[{...E,occurredAt:r,kind:"began",subject:{type:"session",id:h},claims:[{ns:"agent.session",parts:[Ko,o],validFrom:r,validTo:i}],core:{machineId:t.machine.id,label:u,executor:Le},attrs:{context:c,"gemini.sessionId":o,"gemini.projectHash":s.projectHash,..._e(s.kind)?{"gemini.kind":s.kind}:{}},provenance:b(o),seq:"session"}],p=[];for(let m=0;m<n.length;m++)tr(n[m])&&ye(n[m].timestamp)!==void 0&&p.push(m);if(p.length===0){if(n.some(m=>m.type==="gemini"))throw new We(`session has ${n.length} messages including model output but no recognisable user prompt`,t.path);return w}for(let m=0;m<p.length;m++){const v=p[m],d=m+1<p.length?p[m+1]:n.length,A=m+1,g=`${h}:turn:${A}`,y=ye(n[v].timestamp);let M=y,l,S;const k=[];for(let _=v;_<d;_++){const $=n[_],O=ye($.timestamp);if(O===void 0||$.type!=="gemini"&&$.type!=="error"&&!($.type==="user"&&Ys($))||(O>M&&(M=O),S=$,$.type!=="gemini"))continue;l??=_e($.model);const U=Array.isArray($.toolCalls)?$.toolCalls:[],X=$.tokens?sr($.tokens):{};U.length&&(X[R.interactions]=U.length),Object.keys(X).length!==0&&k.push({...E,occurredAt:O,kind:"progressed",subject:{type:"execution",id:g},core:{measures:X},attrs:{...U.length?{"gemini.tools":U.map(j=>_e(j.name)??"unknown")}:{},..._e($.model)?{"gemini.model":$.model}:{},...$.tokens?{"gemini.usage.input":ee($.tokens.input),"gemini.usage.output":ee($.tokens.output),"gemini.usage.cached":ee($.tokens.cached),"gemini.usage.thoughts":ee($.tokens.thoughts),"gemini.usage.tool":ee($.tokens.tool)}:{}},provenance:b($.id),seq:$.id})}w.push({...E,occurredAt:y,kind:"began",subject:{type:"execution",id:g},core:{machineId:t.machine.id,sessionId:h,label:`${u} · TURN ${A}`,executor:Le,model:l,depth:0},attrs:{"gemini.turn":A},provenance:b(n[v].id),seq:`turn:${A}`}),w.push(...k);const T=S?.type==="error",I=S?.type==="gemini"&&!(Array.isArray(S.toolCalls)&&S.toolCalls.length),x=m+1<p.length,C=(_,$)=>({...E,occurredAt:M,kind:"ended",subject:{type:"execution",id:g},core:_,...$?{basis:"inferred",assumption:Jo}:{},provenance:b(n[v].id),seq:`turn:${A}:end`});T?w.push(C({outcome:"error",failureMessage:Qo(S)},!1)):x||I&&t.settled?w.push(C({outcome:"completed"},!1)):t.closeOpenTurns&&w.push(C({outcome:I?"completed":"interrupted"},!0))}return w}const or=3e3;function bt(){return process.env.GEMINI_HOME||D(he(),".gemini")}const Vs=()=>D(bt(),"tmp"),Jt=new Map;async function rr(){const e=new Map;try{const t=JSON.parse(await ie(D(bt(),"projects.json"),"utf8"));for(const[s,n]of Object.entries(t.projects??{}))typeof n=="string"&&e.set(n,s)}catch{}return e}async function zs(){const e=Vs();if(!L(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(D(e,n,"chats"))}catch{continue}for(const r of o)r.startsWith("session-")&&r.endsWith(".jsonl")&&t.push({path:D(e,n,"chats",r),slug:n})}return t}async function Ks(e,t){const s=ge(),n=Date.now(),o={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},r=await zs();if(r.length===0)return o.storedAvailable=L(Vs()),o;o.storedAvailable=!0;const a=await rr();for(const i of r){let c;try{c=await me(i.path)}catch{continue}if(c.mtimeMs<e)continue;const u=Date.now()-c.mtimeMs,h=u>or,f=u>ht,E=`${c.mtimeMs}:${c.size}:${h}:${f}`,b=Jt.get(i.path);let w;if(b&&b.stamp===E)w=b.envelopes;else try{const p=er(await ie(i.path,"utf8"),i.path);w=nr(p,{machine:s,host:de(),observedAt:n,path:i.path,workspacePath:a.get(i.slug),settled:h,closeOpenTurns:f}).map(se),Jt.set(i.path,{stamp:E,envelopes:w})}catch(p){o.sessionsFailed++,o.problems.push({path:i.path,message:p instanceof Error?p.message:String(p)});continue}o.sessionsRead++;for(const p of w)p.occurredAt>=e&&p.occurredAt<=t&&o.envelopes.push(p)}return o}async function ir(e,t){return(await Ks(e,t)).envelopes}async function Qt(){const e=bt(),t=(await zs()).length;return{available:t>0,present:L(e),home:e,sessions:t}}const pe="os",ar=(e,t)=>`os:${e}:${t.pid}:${t.startedAt}`;function cr(e,t){const s=/^os:[^:]+:(\d+):(\d+)$/.exec(e);return s?`os:${t}:${s[1]}:${s[2]}`:void 0}const ur=e=>`The process was present in one ${Math.round(e/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.`,dr=250,lr=8*1024*1024;function pr(e,t,s){const n={source:{id:pe,instance:s.host},observedAt:s.observedAt,clock:"wall",stratum:"machine"},o=[],r=new Map;for(const a of t){const i=ar(s.host,a);r.set(i,a);const c={ns:"os.process",parts:[s.host,a.pid],validFrom:a.startedAt,validTo:s.observedAt};if(!e.has(i)){o.push({...n,occurredAt:a.startedAt,kind:"began",subject:{type:"process",id:i},claims:[c],basis:"measured",core:{machineId:s.machineId,label:fr(a.command),executor:a.command,measures:{[R.cpuMs]:a.cpuMs}},attrs:{"os.pid":a.pid,"os.ppid":a.ppid,"os.command":a.command,"os.rssBytes":a.rssBytes}});continue}const u=e.get(i),h=a.cpuMs-u.cpuMs>=dr,f=Math.abs(a.rssBytes-u.rssBytes)>=lr;(h||f)&&o.push({...n,occurredAt:s.observedAt,seq:`obs:${s.observedAt}`,kind:"observed",subject:{type:"process",id:i},claims:[c],basis:"measured",core:{measures:{[R.cpuMs]:a.cpuMs}},attrs:{"os.rssBytes":a.rssBytes}})}for(const[a,i]of e)r.has(a)||o.push({...n,occurredAt:s.observedAt-s.intervalMs,kind:"ended",subject:{type:"process",id:a},basis:"inferred",assumption:ur(s.intervalMs),core:{outcome:"completed",measures:{[R.cpuMs]:i.cpuMs}},attrs:{"os.pid":i.pid}});return{envelopes:o,next:r}}function fr(e){return(e.split("/").pop()??e).toUpperCase()}function te(e,t){const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:void 0}function Xe(e,t){for(const[s,n]of Object.entries(t)){if(typeof n!="number"||!Number.isFinite(n))continue;const o=s;e[o]=(e[o]??0)+n}}const mr=[R.tokensInput,R.tokensOutput,R.tokensCacheRead];function ue(e){let t=0,s=!1;for(const n of mr){const o=te(e,n);o!==void 0&&(s=!0,t+=o)}return s?t:void 0}function Js(e){return{input:te(e,R.tokensInput)??0,output:te(e,R.tokensOutput)??0,cacheRead:te(e,R.tokensCacheRead)??0,reasoning:te(e,R.tokensReasoning)??0}}function Qs(e){const t=ue(e.measures);if(t!==void 0)return Zt(t/1e3,200);const s=te(e.measures,R.cpuMs);if(s!==void 0)return Zt(s/1e3,200)}function Ee(e){return te(e.measures,R.interactions)}function Zs(e){return te(e.measures,R.steps)??0}function ct(e){return te(e.measures,R.errors)??0}function ut(e){return te(e.measures,R.retries)??0}function Zt(e,t){return Math.min(1,Math.log1p(Math.max(0,e))/Math.log1p(t))}const hr=new Set(["running","waiting"]);function en(e){return hr.has(e)}function tn(e,t){return{now:e,dayStart:e,dayEnd:t,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 gr=9e4;function es(e,t){if(e.waitingSince===void 0)return;const s=e.waitingSince,n=Math.max(s,t);e.waitingMs+=n-s,e.waits.push({start:s,end:n})}function br(e,t){const s=`${t.source.id}:${t.source.instance}`;let n=e.sources.get(s);n||(n={id:t.source.id,instance:t.source.instance,origin:t.source.instance,firstSeenAt:t.occurredAt,lastSeenAt:t.occurredAt,events:0,strata:{}},e.sources.set(s,n)),n.events++,t.occurredAt<n.firstSeenAt&&(n.firstSeenAt=t.occurredAt),t.occurredAt>n.lastSeenAt&&(n.lastSeenAt=t.occurredAt),t.stratum&&(n.strata[t.stratum]=(n.strata[t.stratum]??0)+1);const o=t.provenance?.sourceVersion;o&&(n.sourceVersions?n.sourceVersions.includes(o)||n.sourceVersions.push(o):n.sourceVersions=[o])}function vr(e,t){if(e.seen.has(t.id))return;e.seen.add(t.id),t.occurredAt>e.now&&(e.now=t.occurredAt),br(e,t);const s=t.core??{},n=t.occurredAt;switch(t.subject.type){case"machine":{if(e.machines.has(t.subject.id))break;const o={id:t.subject.id,name:s.machineName??t.subject.id,kind:s.machineKind??"laptop",parentId:s.parentId,firstSeenAt:n};e.machines.set(o.id,o);break}case"session":{if(t.kind==="began"){const o=e.sessions.get(t.subject.id);if(o){o.parentId===void 0&&s.parentId&&(o.parentId=s.parentId);break}const r={id:t.subject.id,machineId:s.machineId??"",label:s.label,context:t.attrs?.context??s.label??"",executor:s.executor,model:s.model,startedAt:n,executionIds:[],parentId:s.parentId};e.sessions.set(r.id,r)}else if(t.kind==="ended"){const o=e.sessions.get(t.subject.id);o&&(o.endedAt=n)}break}case"execution":yr(e,t,n);break;case"process":wr(e,t,n);break;case"artifact":{if(e.artifacts.has(t.subject.id))break;e.artifacts.set(t.subject.id,{id:t.subject.id,kind:"file",path:s.label??t.subject.id,firstSeenAt:n});break}}}function yr(e,t,s){const n=t.core??{},o=t.subject.id;if(t.kind==="began"){if(e.executions.has(o))return;const a={id:o,sessionId:n.sessionId??n.parentId??"",machineId:n.machineId??"",label:n.label??o,executor:n.executor??"unknown",model:n.model,status:"running",startedAt:s,lastActivityAt:s,measures:{},waitingMs:0,waits:[],parentId:n.parentId,depth:n.depth??0,startBasis:t.basis,boundsAssumption:t.assumption};n.measures&&Xe(a.measures,n.measures),e.executions.set(o,a),e.active.add(o),e.sessions.get(a.sessionId)?.executionIds.push(o);return}const r=e.executions.get(o);if(r)switch(t.kind){case"progressed":{n.measures&&Xe(r.measures,n.measures),r.lastActivityAt=s,r.status==="idle"&&(r.status="running",e.active.add(o));break}case"blocked":{if(!en(r.status))break;r.status="waiting",r.waitingSince=s,r.waitReason=n.blockedOn??"input",r.lastActivityAt=s;break}case"resumed":{es(r,s),r.status="running",r.waitingSince=void 0,r.waitReason=void 0,r.lastActivityAt=s,e.active.add(o);break}case"ended":{const a=n.outcome==="error";r.status=a?"failed":"completed",r.endedAt=s,r.endBasis=t.basis,t.assumption&&!r.boundsAssumption&&(r.boundsAssumption=t.assumption),r.lastActivityAt=s,r.outcome=n.outcome??"completed",a&&(r.failure={code:n.failureCode??"ERROR",message:n.failureMessage??"Execution failed"}),es(r,s),r.waitingSince=void 0,r.waitReason=void 0,e.active.delete(o);break}case"observed":r.lastActivityAt=Math.max(r.lastActivityAt,s);break}}function wr(e,t,s){const n=t.core??{},o=t.subject.id,r=Number(t.attrs?.["os.pid"]??0);if(t.kind==="began"){if(e.processes.has(o))return;const i={id:o,machineId:n.machineId??"",pid:r,ppid:typeof t.attrs?.["os.ppid"]=="number"?t.attrs["os.ppid"]:void 0,command:n.label??n.executor??String(r),startedAt:s,lastSeenAt:s,status:"running",measures:{}};n.measures&&Xe(i.measures,n.measures),e.processes.set(o,i);return}const a=e.processes.get(o);if(a)if(t.kind==="observed"||t.kind==="progressed"){if(a.lastSeenAt=Math.max(a.lastSeenAt,s),n.measures){const i=n.measures[R.cpuMs];typeof i=="number"&&(a.measures[R.cpuMs]=i);const{[R.cpuMs]:c,...u}=n.measures;Xe(a.measures,u)}}else t.kind==="ended"&&(a.endedAt=s,a.lastSeenAt=Math.max(a.lastSeenAt,s),a.status="exited",a.endInferred=t.basis==="inferred")}function Ar(e,t){for(let s=0;s<t.length;s++)vr(e,t[s])}function Sr(e,t){if(!(t<=e.now)){e.now=t;for(const s of e.active){const n=e.executions.get(s);if(!n){e.active.delete(s);continue}n.status==="running"&&t-n.lastActivityAt>gr&&(n.status="idle")}}}const Er=5*6e4;function kr(e){const t=[];for(const s of e)s.parentId&&t.push({from:{type:"session",id:s.parentId},to:{type:"session",id:s.id},kind:"spawned",basis:"measured",via:"recorded by the child session's own runtime"});return t}function Ir(e,t){const s=e.now-Er,n=new Set;for(const i of t)i.from.type==="process"&&n.add(i.from.id),i.to.type==="process"&&n.add(i.to.id);const o=[];let r=0,a=0;for(const i of e.processes.values())i.lastSeenAt>=s&&r++,i.endInferred&&a++,n.has(i.id)&&o.push(i);return{now:e.now,dayStart:e.dayStart,dayEnd:e.dayEnd,machines:[...e.machines.values()],sources:[...e.sources.values()],sessions:[...e.sessions.values()],executions:[...e.executions.values()],processes:o,processTotals:{observed:e.processes.size,recentlySeen:r,exitsInferred:a},relationships:[...t,...kr(e.sessions.values())]}}function ts(e){const t=tn(e.dayStart,e.dayEnd);t.now=e.now;for(const s of e.machines)t.machines.set(s.id,s);for(const s of e.sources)t.sources.set(`${s.id}:${s.instance}`,s);for(const s of e.sessions)t.sessions.set(s.id,s);for(const s of e.executions)t.executions.set(s.id,s),en(s.status)&&t.active.add(s.id);for(const s of e.processes)t.processes.set(s.id,s);return t.processTotals=e.processTotals,t.relationships=e.relationships,t}function Tr(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=Math.imul(t,16777619);return t>>>0}function Ge(e,t=0){return Tr(e+"#"+t)%1e5/1e5}const Qe=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function Mr(e){if(e<Qe.length)return Qe[e];const s=-.9+(e-Qe.length)*1.15;return{x:620+Math.cos(s)*520,y:300+Math.sin(s)*250,extentX:150,extentY:94}}function Or(e){const t=s=>s==="laptop"?0:s==="desktop"?1:2;return[...e].sort((s,n)=>t(s.kind)-t(n.kind)||s.firstSeenAt-n.firstSeenAt||(s.id<n.id?-1:s.id>n.id?1:0))}function ss(e,t){const s=Ge(t,1),n=Ge(t,2),o=s*Math.PI*2+n*2.399963,r=.34+.46*Math.sqrt(n);return{x:e.x+Math.cos(o)*e.extentX*r,y:e.y+Math.sin(o)*e.extentY*r}}const ns=30,$r=74;function Rr(e){return ns+e*($r-ns)}const os=64,xr=8,Nr=8,rs=16,is=.45;function _r(e,t){switch(e.status){case"running":{const s=t-e.lastActivityAt;return .55+.45*Math.exp(-s/45e3)}case"waiting":return .08;case"failed":return .9;case"completed":return 0;case"idle":return .03}}const as=.32;function Cr(e){const t=Qs(e),s=e.depth>0?.62:1;return t===void 0?as*s:Math.min(1,(as+.68*t)*s)}function jr(e,t){const s=Math.max(1,(e.endedAt??t)-e.startedAt),n=(Ee(e)??0)/(s/6e4);return Math.min(1,.25+n/24)}function cs(e){return(e.status==="failed"?3:e.status==="waiting"?2:e.status==="running"?1:0)*1e15+e.lastActivityAt}function Dr(e){const t=new Set,s=new Set,n=new Map,o=new Map,r=(a,i,c)=>{const u=a.get(i);u?u.push(c):a.set(i,[c])};for(const a of e.relationships){const{from:i,to:c,kind:u}=a;u==="ran-as"?(i.type==="execution"&&t.add(i.id),c.type==="execution"&&t.add(c.id),i.type==="session"&&c.type==="process"&&s.add(i.id),c.type==="session"&&i.type==="process"&&s.add(c.id),i.type==="execution"&&c.type==="session"?n.set(i.id,c.id):i.type==="session"&&c.type==="execution"&&n.set(c.id,i.id)):u==="same-as"&&i.type==="execution"&&c.type==="execution"&&(t.add(i.id),t.add(c.id),r(o,i.id,c.id),r(o,c.id,i.id))}return{resolvedExecutions:t,sessionsWithProcess:s,runObservesSession:n,sameExecution:o}}function Fr(e,t){const n=e.startBasis===void 0?.5:e.startBasis==="measured"?1:0,o=e.endBasis===void 0?.5:e.endBasis==="measured"?1:0,r=e.endedAt===void 0?n:(n+o)/2,a=Qs(e)===void 0?0:1,i=t.resolvedExecutions.has(e.id)||t.sessionsWithProcess.has(e.sessionId)?1:0;return(1+r+a+i)/4}function us(e){let t=1;for(const s of e)t*=1-Math.min(1,Math.max(0,s));return 1-t}function ds(e,t,s,n){const o=Math.max(e,s),r=Math.min(t,n);if(r<o)return 0;const a=Math.max(t,n)-Math.min(e,s);return a<=0?1:(r-o)/a}function ls(e){const t=e.now,s=Or(e.machines.values()).slice(0,xr),n=new Map,o=[];let r=1;const a=new Map;for(const l of e.executions.values()){const S=(a.get(l.machineId)??0)+1;a.set(l.machineId,S),S>r&&(r=S)}s.forEach((l,S)=>{const k=Mr(S);n.set(l.id,k),o.push({id:l.id,name:l.name,kind:l.kind,x:k.x,y:k.y,extentX:k.extentX,extentY:k.extentY,prominence:(a.get(l.id)??0)/r,seed:Ge(l.id,7)})});const i=45e3,c=[];for(const l of e.executions.values())(l.status==="completed"||l.status==="failed")&&t-(l.endedAt??t)>i||l.status==="idle"&&t-l.lastActivityAt>i*4||n.has(l.machineId)&&c.push(l);c.length>os&&(c.sort((l,S)=>cs(S)-cs(l)),c.length=os);const u=Dr(e),h=l=>{const S=n.get(l.machineId),{x:k,y:T}=ss(S,l.id);return{id:l.id,massId:l.machineId,sessionId:l.sessionId,x:k,y:T,extent:Cr(l),energy:_r(l,t),rate:jr(l,t),phase:Ge(l.id,3)*Math.PI*2,status:l.status,label:l.label,statusSince:l.waitingSince??l.endedAt??l.startedAt,articulation:Fr(l,u),shoulder:0,observers:1}},f=new Set(c.map(l=>l.id)),E=new Set,b=[],w=l=>[l.startedAt,l.endedAt??t];for(const l of[...c].sort((S,k)=>S.id<k.id?-1:1)){if(E.has(l.id))continue;const S=[l];E.add(l.id);for(let _=0;_<S.length;_++)for(const $ of u.sameExecution.get(S[_].id)??[])!f.has($)||E.has($)||(E.add($),S.push(e.executions.get($)));if(S.length===1){b.push(h(l));continue}const k=S.map(h),T=k.reduce((_,$)=>$.articulation>_.articulation||$.articulation===_.articulation&&$.id<_.id?$:_);let I=1;const[x,C]=w(e.executions.get(T.id));for(const _ of S){const[$,O]=w(_);I=Math.min(I,ds(x,C,$,O))}b.push({...T,extent:Math.max(...k.map(_=>_.extent)),energy:Math.max(...k.map(_=>_.energy)),articulation:us(k.map(_=>_.articulation)),shoulder:Math.min(is,1-I),observers:S.length})}const p=new Map;for(const l of b){if(u.runObservesSession.has(l.id))continue;const S=p.get(l.sessionId);S?S.push(l):p.set(l.sessionId,[l])}const m=new Map,v=[];for(const l of b){const S=u.runObservesSession.get(l.id),k=S?p.get(S):void 0;if(!S||!k||k.length===0){if(v.push(l),S){const O=p.get(l.sessionId);O?O.push(l):p.set(l.sessionId,[l])}continue}const T=e.executions.get(l.id);let I=1/0,x=-1/0;for(const O of k){const[U,X]=w(e.executions.get(O.id));I=Math.min(I,U),x=Math.max(x,X)}const[C,_]=w(T),$=m.get(S)??{articulations:[],coincidence:1};$.articulations.push(l.articulation),$.coincidence=Math.min($.coincidence,ds(C,_,I,x)),m.set(S,$)}const d=[];for(const l of[...p.keys()].sort()){const S=p.get(l),k=e.sessions.get(l);if(!k||S.length===0)continue;let T=0,I=0;for(const O of S)T+=O.x,I+=O.y;T/=S.length,I/=S.length;let x=0,C=0;for(const O of S){const U=Rr(O.extent);x=Math.max(x,Math.abs(O.x-T)+U*1.5),C=Math.max(C,Math.abs(O.y-I)+U)}const _=m.get(l),$=Math.max(...S.map(O=>O.articulation));d.push({id:l,massId:S[0].massId,x:T,y:I,extentX:Math.max(x,52),extentY:Math.max(C,36),presence:1,articulation:_?us([$,..._.articulations]):$,parentId:k.parentId,empty:!1,shoulder:_?Math.min(is,1-_.coincidence):0,observers:1+(_?.articulations.length??0),label:k.label??k.executor??l})}for(const l of[...e.sessions.values()].sort((S,k)=>S.id<k.id?-1:1)){if(l.executionIds.length>0||l.endedAt!==void 0&&t-l.endedAt>i)continue;const S=n.get(l.machineId);if(!S)continue;const{x:k,y:T}=ss(S,`session-presence:${l.id}`);d.push({id:l.id,massId:l.machineId,x:k,y:T,extentX:64,extentY:42,presence:1,articulation:u.sessionsWithProcess.has(l.id)?.5:.25,parentId:l.parentId,empty:!0,shoulder:0,observers:1,label:l.label??l.executor??l.id})}if(d.length>rs){const l=S=>S.empty?0:p.get(S.id)?.length??0;d.sort((S,k)=>l(k)-l(S)||(S.id<k.id?-1:1)),d.length=rs}const A=[];for(const l of e.transfers.values())if(l.endedAt===void 0&&!(!n.has(l.fromMachineId)||!n.has(l.toMachineId))){if(A.length>=Nr)break;A.push({id:l.id,fromMassId:l.fromMachineId,toMassId:l.toMachineId,energy:1,label:l.label})}const g=new Map;s.forEach((l,S)=>g.set(l.id,S));const y=Math.max(1,e.dayEnd-e.dayStart),M=[];for(const l of e.executions.values()){const S=g.get(l.machineId);if(S===void 0)continue;const k=(l.startedAt-e.dayStart)/y,T=((l.endedAt??t)-e.dayStart)/y;M.push({id:l.id,massId:l.machineId,lane:S,startFraction:Math.max(0,Math.min(1,k)),endFraction:Math.max(0,Math.min(1,T)),status:l.status,label:l.label})}return{time:t,masses:o,disturbances:v,plinths:d,couplings:A,strata:M}}const sn="057.landscape",nn=1;function Lr(e){return{contract:sn,version:nn,landscape:e}}const vt="SHAPES FIELD",yt="METADATA — DOES NOT SHAPE FIELD";function on(e){const t=new Date(e),s=n=>String(n).padStart(2,"0");return`${s(t.getHours())}:${s(t.getMinutes())}:${s(t.getSeconds())}`}function Ur(e){return H(e).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function Pr(e,t,s,n,o=()=>{}){if(s==="mass")return Wr(e,t,n);if(s==="coupling")return Xr(e,n);const r=e.executions.get(n);return r?Br(e,t,r,s,o("execution",n)):null}function Br(e,t,s,n,o){const r=e.sessions.get(s.sessionId),a=e.machines.get(s.machineId),c=t.disturbances.find(m=>m.id===s.id)?.statusSince??s.endedAt??s.startedAt,u=s.startBasis==="inferred"||s.endBasis==="inferred",h=ue(s.measures),f=[{key:"MACHINE",value:(a?.name??s.machineId).toUpperCase()},{key:"STATE",value:s.status.toUpperCase(),tone:s.status},{key:"SINCE",value:on(c)},h===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:G(h)}];if(r){const m=r.executionIds.indexOf(s.id),v=t.plinths.some(A=>A.id===r.id),d=m>=0?`${m+1} OF ${r.executionIds.length}`:`OF ${r.executionIds.length}`;f.push({key:"SESSION",value:v?`${d} · PLINTH`:d})}const E=Hr(e,s.id),b=[s.model??r?.model?{key:"MODEL",value:s.model??r?.model}:{key:"MODEL",value:"not observed",tone:"absent",note:"This source does not record the model."}];r?.context&&b.push({key:"PROJECT",value:Q(r.context),note:r.context}),b.push({key:"SOURCE",value:[s.executor,E===void 0?void 0:`pid ${E}`].filter(Boolean).join(" · "),note:o}),b.push({key:"REQUESTS",value:String(Zs(s))});const w=Ee(s);if(b.push(w===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:co(w)}),b.push({key:"ELAPSED",value:`${H((s.endedAt??e.now)-s.startedAt)}${u?" · inferred":""}`,note:u?s.boundsAssumption:void 0}),h!==void 0){const m=Js(s.measures);b.push({key:"INPUT",value:G(m.input)},{key:"OUTPUT",value:G(m.output)}),b.push({key:"CACHE READ",value:G(m.cacheRead)},{key:"REASONING",value:G(m.reasoning)})}ct(s)>0&&b.push({key:"TOOL ERRORS",value:String(ct(s)),tone:"failed"}),ut(s)>0&&b.push({key:"RETRIES",value:String(ut(s)),tone:"waiting",note:"Provider retries."}),(s.waits.length>0||s.waitingMs>0)&&b.push({key:"BLOCKED",value:`${H(s.waitingMs)} on you · ${s.waits.length||1}×`,tone:"waiting"}),s.depth>0&&b.push({key:"SUB-AGENT",value:`depth ${s.depth}`});const p=s.status==="running"||s.status==="waiting";return{id:s.id,eyebrow:n==="stratum"||!p?"SELECTED · RUN":"SELECTED · PROCESS",title:s.label.toUpperCase(),state:{text:p?`${s.status.toUpperCase()} · ${Ur(e.now-c)}`:s.status.toUpperCase(),status:s.status},groups:[{title:vt,metadata:!1,rows:f},{title:yt,metadata:!0,rows:b}],failure:s.failure?`${s.failure.code}: ${s.failure.message}`:void 0,reveal:o}}function Hr(e,t){for(const s of e.relationships){if(s.kind!=="ran-as")continue;const n=s.from.type==="execution"&&s.from.id===t&&s.to.type==="process"?s.to.id:s.to.type==="execution"&&s.to.id===t&&s.from.type==="process"?s.from.id:void 0;if(n)return e.processes.get(n)?.pid}}function Wr(e,t,s){const n=e.machines.get(s);if(!n)return null;let o=0,r=0,a=0,i;for(const b of e.executions.values()){if(b.machineId!==n.id)continue;const w=ue(b.measures);w!==void 0&&(i=(i??0)+w),b.status==="running"?o++:b.status==="waiting"?r++:a++}const u=[{key:"KIND",value:(t.masses.find(b=>b.id===s)?.kind??n.kind).toUpperCase()},{key:"RUNNING",value:String(o),tone:o>0?"running":void 0}];r>0&&u.push({key:"WAITING",value:String(r),tone:"waiting"}),u.push({key:"RAN TODAY",value:String(a)});const h=[i===void 0?{key:"TOKENS",value:"not observed",tone:"absent",note:"No execution in this window reported token accounting."}:{key:"TOKENS",value:G(i)}],f=e.processTotals;if(f){const b=new Set;for(const w of e.relationships)w.kind==="ran-as"&&(w.from.type==="process"&&b.add(w.from.id),w.to.type==="process"&&b.add(w.to.id));h.push({key:"PROCESSES",value:`${f.observed} observed`}),h.push({key:"LAST 5 MIN",value:`${f.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."}),h.push({key:"ATTRIBUTED",value:`${b.size} of ${f.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const E=o+r;return{id:s,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:E>0?{text:`${E} ACTIVE`,status:o>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:vt,metadata:!1,rows:u},{title:yt,metadata:!0,rows:h}]}}function Xr(e,t){const s=e.transfers.get(t);if(!s)return null;const n=e.machines.get(s.fromMachineId)?.name??s.fromMachineId,o=e.machines.get(s.toMachineId)?.name??s.toMachineId;return{id:t,eyebrow:"SELECTED · TRANSFER",title:`${n} → ${o}`.toUpperCase(),state:{text:"TRANSFERRING",status:"running"},groups:[{title:vt,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:o.toUpperCase()},{key:"SINCE",value:on(s.startedAt)}]},{title:yt,metadata:!0,rows:[{key:"WHAT",value:s.label},{key:"SIZE",value:uo(s.bytes)}]}]}}const Y=e=>({value:e,basis:"measured"}),Ce=(e,t)=>({value:e,basis:"inferred",assumption:t});function wt(e){if(e.length===0)return[];e.sort((s,n)=>s.start-n.start);const t=[{start:e[0].start,end:e[0].end}];for(let s=1;s<e.length;s++){const n=e[s],o=t[t.length-1];n.start<=o.end?n.end>o.end&&(o.end=n.end):t.push({start:n.start,end:n.end})}return t}function ps(e){let t=0;for(const s of e)t+=s.end-s.start;return t}function Gr(e,t){const s=[];let n=0,o=0;for(;n<e.length&&o<t.length;){const r=Math.max(e[n].start,t[o].start),a=Math.min(e[n].end,t[o].end);r<a&&s.push({start:r,end:a}),e[n].end<t[o].end?n++:o++}return s}function rn(e){if(e.length===0)return{peak:0,at:0};const t=[];for(const r of e)t.push({t:r.start,d:1}),t.push({t:r.end,d:-1});t.sort((r,a)=>r.t-a.t||r.d-a.d);let s=0,n=0,o=t[0].t;for(const r of t)s+=r.d,s>n&&(n=s,o=r.t);return{peak:n,at:o}}function qr(e){if(e.length===0)return;const t=[...e].sort((n,o)=>n-o),s=t.length>>1;return t.length%2?t[s]:(t[s-1]+t[s])/2}const an=6e4;function Yr(e,t){return{start:e.startedAt,end:e.endedAt??t}}function Vr(e){const t=[];for(const s of e.executions.values()){s.depth===0&&t.push({start:s.startedAt-an,end:s.startedAt});for(const n of s.waits)t.push({start:n.start,end:n.end});s.waitingSince!==void 0&&t.push({start:s.waitingSince,end:e.now})}return wt(t)}function zr(e){const t=e.now,s=[...e.executions.values()];let n=0,o=0,r=0,a=0,i=0,c=0,u=0,h=0;const f=[],E=new Map;for(const y of s){n+=Zs(y),o+=ue(y.measures)??0,r+=Ee(y)??0,y.status==="completed"?a++:y.status==="failed"?i++:y.status==="waiting"?c++:y.status==="idle"&&u++;const M=Yr(y,t);f.push(M),h+=y.waitingMs,y.waitingSince!==void 0&&(h+=Math.max(0,t-y.waitingSince));let l=E.get(y.machineId);l||(l={machineId:y.machineId,executions:0,tokens:0,computeTime:0},E.set(y.machineId,l)),l.executions++,l.tokens+=ue(y.measures)??0,l.computeTime+=M.end-M.start}const b=wt(f.map(y=>({...y}))),w=Vr(e),p=ps(Gr(b,w)),{peak:m,at:v}=rn(f),d=Kr(e),A=Math.max(0,d.length-1);let g=null;for(const y of d)(!g||y.end-y.start>g.end-g.start)&&(g=y);return{requests:Y(n),sessions:Y(e.sessions.size),executions:Y(s.length),tokens:Y(o),toolCalls:Y(r),autonomousCompute:Ce(ps(b),"Wall-clock time during which at least one run was in flight, merged so parallel runs are not double-counted."),humanAgentOverlap:Ce(p,`Compute time intersecting a window when you were plausibly present: the ${an/1e3}s before you sent a message, and any approval from ask to answer.`),peakConcurrency:Y(m),peakConcurrencyAt:Y(v),contextSwitches:Ce(A,"Transitions between working directories, ordered by time. A directory is the closest thing the source has to a project."),longestFocus:Ce(g,"Longest unbroken stretch spent in one working directory."),waitingOnYou:Y(h),completed:Y(a),failed:Y(i),waiting:Y(c),idle:Y(u),byMachine:E,contextSpans:d,transfers:Y(e.transfers.size)}}function Kr(e){const t=[];for(const n of e.executions.values()){const o=e.sessions.get(n.sessionId);o&&t.push({context:o.context,start:n.startedAt,end:n.endedAt??e.now})}t.sort((n,o)=>n.start-o.start);const s=[];for(const n of t){const o=s[s.length-1];o&&o.context===n.context&&n.start<=o.end?n.end>o.end&&(o.end=n.end):o&&o.context===n.context?n.start-o.end<=Jr?o.end=Math.max(o.end,n.end):s.push({context:n.context,start:n.start,end:n.end}):s.push({context:n.context,start:n.start,end:n.end})}return s}const Jr=15*6e4;function Qr(e){return{key:e,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function Ze(e,t){const s=new Map,n=new Map;for(const o of e.executions.values()){const r=t(o,e.sessions.get(o.sessionId));if(r===void 0)continue;let a=s.get(r);a||(a=Qr(r),s.set(r,a)),a.runs++;const i=ue(o.measures);if(i!==void 0&&(a.tokens+=i,a.tokenRuns++,o.endedAt!==void 0)){let c=n.get(r);c||(c=[],n.set(r,c)),c.push(i)}a.computeMs+=(o.endedAt??e.now)-o.startedAt,a.waitingMs+=o.waitingMs,a.toolCalls+=Ee(o)??0,o.status==="failed"&&a.failed++}for(const[o,r]of n){const a=s.get(o);a&&(a.medianTokens=qr(r),a.medianRuns=r.length)}return[...s.values()].sort((o,r)=>r.computeMs-o.computeMs)}function Zr(e){const t={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const s of e.executions.values()){const n=Js(s.measures);t.input+=n.input,t.output+=n.output,t.cacheRead+=n.cacheRead,t.reasoning+=n.reasoning}return t.total=t.input+t.output+t.cacheRead+t.reasoning,t}function ei(e){const t={count:0,totalMs:0,longestMs:0,openNow:0};for(const s of e.executions.values()){for(const n of s.waits){t.count++;const o=n.end-n.start;t.totalMs+=o,o>t.longestMs&&(t.longestMs=o)}if(s.waitingSince!==void 0){t.openNow++;const n=e.now-s.waitingSince;t.totalMs+=n,n>t.longestMs&&(t.longestMs=n)}}return t}function ti(e){const t={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const s of e.executions.values())t.toolCalls+=Ee(s)??0,t.toolErrors+=ct(s),t.retries+=ut(s),s.status==="failed"?t.failed++:s.outcome==="interrupted"?t.interrupted++:s.outcome==="completed"&&t.completed++;return t}function si(e){const t=[];for(const r of e.executions.values())t.push({start:r.startedAt,end:r.endedAt??e.now});if(t.length===0)return[];const s=wt(t.map(r=>({...r}))),n=new Date(e.dayStart);n.setMinutes(0,0,0);const o=[];for(let r=n.getTime();r<e.now;r+=36e5){const a=r+36e5;let i=0;for(const h of s){const f=Math.max(h.start,r),E=Math.min(h.end,a);E>f&&(i+=E-f)}let c=0;const u=[];for(const h of t)h.start<a&&h.end>r&&(c++,u.push({start:Math.max(h.start,r),end:Math.min(h.end,a)}));o.push({hour:new Date(r).getHours(),runs:c,computeMs:i,peak:rn(u).peak})}return o}const Ue=6e4,ni=60*Ue;function oi(e,t){const s=[],n=t.contextSpans,o=t.longestFocus.value,r=Math.max(1,e.now-e.dayStart),a=t.autonomousCompute.value/r;let i;if(t.executions.value===0)return{headline:"QUIET",clauses:["No computation observed in this window."]};if(t.peakConcurrency.value>=3?i="PARALLEL":n.length>=6?i="FRAGMENTED":o&&o.end-o.start>2*ni?i="SUSTAINED":a<.15?i="SPARSE":i="SERIAL",t.peakConcurrency.value>=2?s.push(`Up to ${t.peakConcurrency.value} runs in flight at once; ${H(t.autonomousCompute.value)} of wall-clock time had computation running.`):s.push(`Runs happened one at a time, across ${H(t.autonomousCompute.value)} of wall-clock time.`),o&&s.push(`The longest unbroken stretch was ${H(o.end-o.start)} in ${Q(o.context)}.`),n.length>1){const c=new Set(n.map(u=>u.context)).size;s.push(`Attention moved ${t.contextSwitches.value} ${t.contextSwitches.value===1?"time":"times"} across ${c} ${c===1?"context":"contexts"}.`)}if(t.waitingOnYou.value>Ue&&s.push(`${H(t.waitingOnYou.value)} was spent with a run waiting on your answer.`),t.humanAgentOverlap.value>Ue){const c=Math.round(t.humanAgentOverlap.value/Math.max(1,t.autonomousCompute.value)*100);s.push(`About ${c}% of that computation overlapped a window when you were present; the rest ran without you.`)}else t.autonomousCompute.value>5*Ue&&s.push("Computation ran almost entirely outside the moments you were present.");if(t.failed.value>0&&s.push(`${t.failed.value} of ${t.executions.value} runs ended in failure; ${t.completed.value} completed.`),t.byMachine.size>1){const c=[...t.byMachine.values()].sort((u,h)=>h.computeTime-u.computeTime).map(u=>`${e.machines.get(u.machineId)?.name??u.machineId} ${H(u.computeTime)}`);s.push(`Compute was split across ${c.join(", ")}.`)}return{headline:i,clauses:s}}const fs="(no model)";function ri(e){if(e.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(e.medianRuns===1)return{text:`single run ${G(e.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 t=e.medianRuns===e.runs?`${e.runs}`:`${e.medianRuns} of ${e.runs}`;return{text:`median ${G(e.medianTokens)} over ${t} runs`,title:`Median billed tokens per run, over the runs in this group that have ended and whose source reports token accounting — ${e.medianRuns} of ${e.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 z(e,t,s,n={}){const o=s?.basis==="inferred";return{key:e,value:t,inferred:o,assumption:o?s?.assumption:void 0,...n}}function et(e,t,s){const n=e[0]?.computeMs??0;return e.map(o=>({key:o.key,label:t(o.key),detail:`${o.runs} ${o.runs===1?"run":"runs"}${o.tokenRuns>0?` · ${G(o.tokens)} tok`:""} · ${H(o.computeMs)}`,failed:o.failed,fraction:n>0?o.computeMs/n:0,median:s?ri(o):void 0}))}function ii(e){const t=zr(e),s=oi(e,t),n=Zr(e),o=ei(e),r=ti(e),a=si(e),i=Ze(e,(g,y)=>y?.context),c=Ze(e,g=>g.model??fs),u=Ze(e,g=>g.machineId),h=[...e.executions.values()],f=h.filter(g=>ue(g.measures)===void 0).length,E=h.filter(g=>g.depth>0).length,b=t.longestFocus.value,w=Math.round(t.humanAgentOverlap.value/Math.max(1,t.autonomousCompute.value)*100),p=[z("REQUESTS",G(t.requests.value),t.requests),z("RUNS",String(t.executions.value),t.executions,{note:E>0?`${E} of them sub-agents`:void 0}),z("SESSIONS",String(t.sessions.value),t.sessions),z("TOKENS",G(t.tokens.value),t.tokens,{note:`${Math.round(n.cacheRead/Math.max(1,n.total)*100)}% cache reads`+(f>0?` · ${f} ${f===1?"run reports":"runs report"} no accounting`:"")}),z("TOOL CALLS",G(r.toolCalls),t.toolCalls,{note:r.toolErrors>0?`${r.toolErrors} failed`:void 0}),z("AUTONOMOUS COMPUTE",H(t.autonomousCompute.value),t.autonomousCompute),z("HUMAN + AGENT OVERLAP",H(t.humanAgentOverlap.value),t.humanAgentOverlap,{note:`${w}% of compute`}),z("PEAK CONCURRENCY",t.peakConcurrency.value>0?`${t.peakConcurrency.value} · ${xe(t.peakConcurrencyAt.value)}`:"0",t.peakConcurrency),z("CONTEXT SWITCHES",String(t.contextSwitches.value),t.contextSwitches,{note:`across ${i.length} ${i.length===1?"context":"contexts"}`}),z("LONGEST FOCUS",b?H(b.end-b.start):"—",t.longestFocus,{note:b?`${Q(b.context)} · ${xe(b.start)}–${xe(b.end)}`:void 0}),z("WAITING ON YOU",H(t.waitingOnYou.value),t.waitingOnYou,{tone:t.waitingOnYou.value>0?"waiting":void 0,note:o.count>0?`${o.count} ${o.count===1?"block":"blocks"} · longest ${H(o.longestMs)}`:void 0}),z("FAILED",String(r.failed),void 0,{tone:r.failed>0?"failed":void 0,note:r.interrupted>0||r.retries>0?`${r.interrupted} stopped · ${r.retries} retries`:void 0})],m=a.length>0?a.reduce((g,y)=>y.computeMs>g.computeMs?y:g,a[0]):void 0,v=g=>`${String(g).padStart(2,"0")}:00`,d=[{title:"WHERE THE TIME WENT",rows:et(i,Q,!1)}];u.length>0&&d.push({title:"BY MACHINE",rows:et(u,g=>e.machines.get(g)?.name??g,!1)}),c.length>0&&d.push({title:"BY MODEL",rows:et(c,g=>g===fs?"model not observed":g,!0)});const A=g=>g/Math.max(1,n.total);return{headline:s.headline,clauses:[...s.clauses],measures:p,hours:a.map(g=>({hour:g.hour,computeMs:g.computeMs,runs:g.runs,peak:g.peak})),busiest:m?`busiest ${v(m.hour)} · ${H(m.computeMs)} of that hour`:void 0,groups:d,tokens:[["CACHE READS",n.cacheRead],["INPUT",n.input],["OUTPUT",n.output],["REASONING",n.reasoning]].map(([g,y])=>({key:g,value:G(y),percent:Math.round(A(y)*100),fraction:A(y)})),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:h.filter(g=>g.status==="failed").sort((g,y)=>y.startedAt-g.startedAt).slice(0,12).map(g=>({id:g.id,at:xe(g.startedAt),label:g.label,reason:g.failure?`${g.failure.code}: ${g.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:"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 ai(e,t){const s=new Set(t.disturbances.map(r=>r.id)),n=new Set(t.strata.map(r=>r.id)),o=[...e.executions.values()].sort((r,a)=>a.startedAt-r.startedAt).map(r=>{const a=e.sessions.get(r.sessionId);return{id:r.id,startedAt:r.startedAt,label:r.label,depth:r.depth,context:a?.context?Q(a.context):null,model:r.model??null,status:r.status,stopped:r.outcome==="interrupted",durationMs:(r.endedAt??e.now)-r.startedAt,inferred:r.startBasis==="inferred"||r.endBasis==="inferred",tokens:ue(r.measures)??null,tools:Ee(r)??null,waitedMs:r.waitingMs,inField:s.has(r.id)?"disturbance":n.has(r.id)?"stratum":null}});return{now:e.now,rows:o}}const At={[sn]:nn};function St(e){return`${e}.core.json`}function cn(e){const t=St(e);if(!L(t))return null;try{const s=JSON.parse(wn(t,"utf8"));return typeof s.pid!="number"||typeof s.url!="string"?null:s}catch{return null}}function ci(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function ui(e,t=1500){const s=cn(e);if(!s||s.pid===process.pid||!ci(s.pid))return null;try{const n=await fetch(`${s.url}/api/health`,{signal:AbortSignal.timeout(t)});return n.ok&&(await n.json()).pid===s.pid?s:null}catch{return null}}function di(e,t){if(e===":memory:")return;const s=St(e),n=`${s}.${process.pid}.tmp`;vn(n,`${JSON.stringify(t,null,1)}
|
|
9
|
-
|
|
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(`
|
|
10
|
+
`)}
|
|
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.
|
|
10
12
|
--
|
|
11
13
|
-- \`events\` is the only durable truth. \`claims\` is denormalized out of events so identity
|
|
12
14
|
-- resolution is one indexed read rather than a scan; it is rebuildable from events at any time.
|
|
@@ -57,33 +59,76 @@ CREATE TABLE IF NOT EXISTS claims (
|
|
|
57
59
|
CREATE INDEX IF NOT EXISTS claims_key ON claims(key, valid_from, valid_to);
|
|
58
60
|
CREATE INDEX IF NOT EXISTS claims_window ON claims(valid_to, valid_from);
|
|
59
61
|
CREATE INDEX IF NOT EXISTS claims_event ON claims(event_id);
|
|
60
|
-
`,
|
|
62
|
+
`,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
|
|
61
63
|
(id, source_id, source_instance, occurred_at, observed_at, clock, kind,
|
|
62
64
|
subject_type, subject_id, core, attrs, basis, assumption, stratum, provenance)
|
|
63
|
-
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),
|
|
65
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),l=e.prepare(`INSERT INTO claims
|
|
64
66
|
(event_id, key, ns, subject_type, subject_id, source_id, valid_from, valid_to)
|
|
65
|
-
VALUES (?,?,?,?,?,?,?,?)`),
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
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
|
|
68
|
+
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
|
|
69
|
+
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
|
|
70
|
+
(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
|
|
71
|
+
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
|
|
72
|
+
WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${l})
|
|
73
|
+
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
|
|
74
|
+
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
|
|
70
75
|
WHERE kind = 'began' AND subject_type = ? AND subject_id = ?
|
|
71
|
-
ORDER BY occurred_at LIMIT 1`);for(const d of p){const A=d.indexOf(":");if(A<0)continue;const g=v.get(d.slice(0,A),d.slice(A+1));g&&m.push(c(g))}return m},subjectEvents(p,m){return t.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(p,m).map(c)},latestFor(p){return t.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(p)?.hi??null},sweep(p=dt,m=Date.now()){const v=p.processDays>0?m-p.processDays*864e5:null,d=p.eventDays>0?m-p.eventDays*864e5:null;if(v===null&&d===null)return{...tt};const A=j=>pi.includes(j)?null:ms.includes(j)?v:d,g=t.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
|
|
72
|
-
|
|
73
|
-
WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),T=new Set(S);let I=[...M].filter(j=>T.has(j.slice(0,j.indexOf(":"))));const x=new Set(I);let C=0;for(let j=0;j<4&&I.length>0;j++){const N=[];for(const V of I){const K=V.indexOf(":");for(const gn of k.all(V.slice(0,K),V.slice(K+1))){const $t=Pe(gn.core);if($t)for(const[bn,Rt]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const xt=$t[bn];if(typeof xt!="string")continue;const be=y(Rt,xt);l.has(be)&&(l.delete(be),M.add(be),C++,!x.has(be)&&T.has(Rt)&&(x.add(be),N.push(be)))}}}I=N}if(l.size===0)return{...tt,retainedByDependents:C,processBefore:v,otherBefore:d};const _=t.prepare(`DELETE FROM claims WHERE event_id IN
|
|
74
|
-
|
|
75
|
-
`)){const n=s.trim();if(!n)continue;const o=n.match(/^(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+([\d:.]+)\s+(\d+)\s+(.*)$/);if(!o)continue;const[,r,a,i,c,u,h]=o,f=Date.parse(i);Number.isFinite(f)&&t.push({pid:Number(r),ppid:Number(a),startedAt:f,cpuMs:ki(c),rssBytes:Number(u)*1024,command:h.trim()})}return t}function ki(e){const[t,s]=e.includes("-")?e.split("-"):["0",e],n=s.split(":").map(Number);let o=0;for(const r of n)o=o*60+(Number.isFinite(r)?r:0);return Math.round((o+Number(t)*86400)*1e3)}async function Ii(){const{stdout:e}=await Ai("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return Ei(e)}const bs=5e3;function Ti(e,t){const s=Si();let n=new Map,o=null,r=0,a=null,i,c=!1;async function u(){if(c)return[];c=!0;try{const h=await Ii(),f=Date.now(),{envelopes:E,next:b}=pr(n,h,{machineId:t,host:s,observedAt:f,intervalMs:bs}),w=E.map(se);return e.append(w),n=b,r++,a=f,i=void 0,w}catch(h){return i=h instanceof Error?h.message:String(h),[]}finally{c=!1}}return{sample:u,start(){o||(u(),o=setInterval(()=>{u()},bs),o.unref?.())},stop(){o&&clearInterval(o),o=null},get running(){return o!==null},stats(){return{samples:r,tracked:n.size,lastSampleAt:a,lastError:i}}}}const fn={info:e=>console.log(e),warn:e=>console.warn(e),error:e=>console.error(e)},Mi=36e5,Oi=15e3,$i=3;function It(e={}){const t=e.log??fn,s=e.path??Ve(),n=e.retention??un(),o=vi(s),r=o.stats();t.info(r.events>0?`[057] store ${s}: opened with ${r.events} events`:`[057] store ${s}: NEW EMPTY STORE — if history existed before, it was lost, not carried`);const a=pn();a&&t.warn(`[057] a store from a previous layout exists at ${a} and is NOT in use. Run 057 with O57_STORE=${a} to keep using it, or move it to ${s}.`);const i=ge();o.append([se({source:{id:"host",instance:i.id},occurredAt:0,observedAt:Date.now(),clock:"wall",kind:"began",stratum:"machine",subject:{type:"machine",id:i.id},basis:"measured",core:{machineName:i.name,machineKind:i.kind},seq:"host"})]);const c=Ti(o,i.id),u=new Map;function h(d){for(const A of d){const g=u.get(A.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};A.ok?(g.consecutiveFailures=0,g.failing=!1,g.failingSince=void 0,g.lastSuccessAt=Date.now()):(g.consecutiveFailures===0&&(g.failingSince=Date.now()),g.consecutiveFailures++,g.totalFailures++,g.lastFailureAt=Date.now(),g.lastError=A.error,g.consecutiveFailures>=$i&&!g.failing&&(g.failing=!0,t.warn(`[057] source ${A.id} has failed ${g.consecutiveFailures} collection rounds in a row: ${A.error??"unknown error"}`))),u.set(A.id,g)}}const f=vs(s);let E=null;function b(d){return E||(E=d,t.error(`[057] ${d.message} — ${d.remedy}`),c.stop()),E}function w(){if(E)return E;if(s===":memory:")return null;if(!L(s))return b({kind:"unlinked",message:`the store at ${s} 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 d=vs(s);return f!==null&&d!==null&&d!==f?b({kind:"replaced",message:`the store at ${s} 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}e.observe!==!1&&c.start();const p=o.sweep(n);p.processEvents+p.otherEvents>0&&t.info(`[057] retention: removed ${p.processEvents} process and ${p.otherEvents} semantic events (${Ye(n)})`);const m=setInterval(()=>{if(!E)try{o.sweep(n),lt(s)}catch(d){t.warn(`[057] retention sweep failed: ${String(d)}`)}},Mi);m.unref?.();const v=setInterval(()=>{w()},Oi);return v.unref?.(),{store:o,machine:i,os:c,path:s,retention:n,fault:()=>E,sweep:d=>o.sweep(n,d),checkStore:w,recordCollection:h,collectionHealth:()=>Object.fromEntries(u),stop(){clearInterval(m),clearInterval(v),c.stop(),o.close()}}}function vs(e){try{return qe(e).ino}catch{return null}}const pt=[{id:Os,collect:(e,t)=>ao(e,t)},{id:rt,collect:(e,t)=>Ao(e,t)},{id:Se,collect:(e,t)=>No(e,t)},{id:De,collect:(e,t)=>Bo(e,t)},{id:Oe,collect:(e,t)=>zo(e,t)},{id:Le,collect:(e,t)=>ir(e,t)}],ys=[...pt.map(e=>e.id),pe],ws=10*365*24*36e5,je=2e5,Ri=24*36e5,xi=72*36e5;function As(e){const t=new Date(e);return t.setHours(0,0,0,0),{from:t.getTime(),to:e}}function Ss(e){const t=e.collectionHealth(),s=Object.entries(t).filter(([,i])=>i.failing).map(([i])=>i),n=e.store.health(),o=e.os.stats(),r=e.fault();let a=null;for(const i of Object.values(t))i.lastSuccessAt&&(a===null||i.lastSuccessAt>a)&&(a=i.lastSuccessAt);return{ok:s.length===0&&n.ok&&!r&&!o.lastError,fault:r??void 0,failingSources:s,errors:Object.fromEntries(Object.entries(t).filter(([,i])=>i.failing).map(([i,c])=>[i,c.lastError??"failing"])),failing:Object.fromEntries(Object.entries(t).filter(([,i])=>i.failing).map(([i,c])=>[i,{since:c.failingSince??null,rounds:c.consecutiveFailures}])),store:{ok:n.ok,remedy:n.remedy},os:{running:e.os.running,lastSampleAt:o.lastSampleAt,lastError:o.lastError},lastCollectionAt:a,sources:{total:ys.length,reported:ys.filter(i=>t[i]!==void 0).length}}}function Ni(e,t,s){const n=t.startsWith("/api/");if(s){const i=(e.headers.host??"").toLowerCase(),c=i.startsWith("[")?i.slice(0,i.indexOf("]")+1):i.split(":")[0];if(!s.includes(c))return`refusing a request for host "${i}"; 057 answers only on ${s.join(", ")}`}const o=e.headers.origin;if(typeof o=="string"&&o!=="null"){const i=(e.headers.host??"").toLowerCase();let c="";try{c=new URL(o).host.toLowerCase()}catch{return"refusing a request with an unparseable Origin"}if(c!==i)return`refusing a cross-origin request from ${o}`}const r=e.headers["sec-fetch-site"],a=String(e.headers["sec-fetch-dest"]??"");if(Ci.has(a))return`refusing to be embedded as ${a}`;if(typeof r=="string"&&r!==""){if(r!=="same-origin"&&r!=="none")return`refusing a ${r} request`;if(r==="none"&&n)return"refusing a directly-navigated API request"}else if(n&&t==="/api/collect"&&!e.headers[_i])return"refusing a state-changing request that carries no fetch metadata";return null}const _i="x-057-client",Ci=new Set(["iframe","frame","embed","object","fencedframe"]);function Tt(e){e.setHeader("x-frame-options","DENY"),e.setHeader("content-security-policy","frame-ancestors 'none'")}function ji(e,t){const s=(r,a)=>{const i=e.get(r);if(i===null||i==="")return a;const c=Number(i);return Number.isSafeInteger(c)?c:null},n=s("from",t-864e5),o=s("to",t);return n===null||o===null?{error:"from and to must be integer epoch millis"}:o<n?{error:"to must not precede from"}:o>t+Ri?{error:"to is too far in the future"}:o-n>ws?{error:`window must not exceed ${ws} ms`}:{from:n,to:o}}function B(e,t,s){e.statusCode=t,e.setHeader("content-type","application/json"),e.setHeader("cache-control","no-store"),e.setHeader("x-content-type-options","nosniff"),Tt(e),e.end(JSON.stringify(s))}function mn(e,t,s,n,o){const r=o?Di(o):void 0,a=r?Es(e.query(t,s,n),r):e.query(t,s,n),i=new Set,c=new Set,u=E=>{const b=`${E.subject.type}:${E.subject.id}`;E.kind==="began"?i.add(b):c.add(b),E.core?.sessionId&&c.add(`session:${E.core.sessionId}`),E.core?.machineId&&c.add(`machine:${E.core.machineId}`)};for(const E of a)u(E);const h=[];for(let E=0;E<4;E++){const b=[...c].filter(p=>!i.has(p));if(b.length===0)break;const w=r?Es(e.begansFor(b),r):e.begansFor(b);if(w.length===0)break;for(const p of w)h.push(p.occurredAt<t?{...p,occurredAt:t}:p),u(p),i.add(`${p.subject.type}:${p.subject.id}`)}return{events:[...h,...a].sort((E,b)=>E.occurredAt-b.occurredAt||ks(E)-ks(b)),relationships:Vn(e,t,s).relationships}}function Di(e){const t=to(e);return s=>{if(s.subject.type==="machine")return s.subject.id!==e&&jt(s.subject.id)?null:s;const n=s.core?.machineId;if(!n||n===e||!jt(n))return s;const o=s.subject.type==="process"&&t?cr(s.subject.id,t):void 0;return{...s,...o?{subject:{...s.subject,id:o}}:{},core:{...s.core,machineId:e}}}}function Es(e,t){const s=[];for(const n of e){const o=t(n);o&&s.push(o)}return s}function Ie(e,t,s,n){const o=performance.now(),{events:r,relationships:a}=mn(e,t,s,void 0,n),i=performance.now()-o,c=performance.now(),u=tn(t,s);Ar(u,r),Sr(u,s);const h=performance.now()-c,f=performance.now(),E=Ir(u,a),b=performance.now()-f;return{world:E,meta:{events:r.length,readMs:Math.round(i*10)/10,deriveMs:Math.round(h*10)/10,serializeMs:Math.round(b*10)/10}}}function ks(e){if(e.kind==="ended")return 5;switch(e.subject.type){case"machine":return 0;case"session":return 1;case"execution":case"process":return e.kind==="began"?2:3;default:return 4}}function Fi(e){const t=e.problems.filter(s=>s.path.includes("/sessions/")).length;return{identity:e.identityAvailable?t===0?"available":e.registryEntries>0?"partial":"failed":"unavailable","stored-semantics":e.storedAvailable?e.transcriptsFailed===0?"available":e.transcriptsRead>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function ot(e){return{"stored-semantics":e.storedAvailable?e.failed===0?"available":e.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function Li(e){return e.error?"failed":e.available?"observing":e.present?"installed-no-data":"not-installed"}function Ui(e){const t=e.home??e.globalStorage;if(typeof t=="string")return t;const s=e.roots;return Array.isArray(s)?s.join(", "):void 0}function le(e){return{available:e.available,present:e.present??!1,presence:Li(e),origin:Ui(e),error:e.error}}function Pi(e){const{runtime:t,log:s}=e;let n=null;function o(r){if(!n||r-n.at>6e4){const a=As(r),i=ts(Ie(t.store,a.from,a.to,t.machine.id).world);n={at:r,label:"TODAY",world:i,landscape:ls(i)}}return n}return async function(a,i){const c=a.url??"";if(!c.startsWith("/api/"))return!1;const u=new URL(c,"http://localhost"),h=Ni(a,u.pathname,e.allowedHosts);if(h)return s.warn(`[057] ${h}`),B(i,403,{error:h}),!0;const f=t.store,E=Date.now(),b=ji(u.searchParams,E);if("error"in b)return B(i,400,{error:b.error}),!0;const{from:w,to:p}=b;try{if(u.pathname==="/api/state"){const[m,v,d,A,g,y]=await Promise.all([Ft().catch(N=>({available:!1,error:String(N)})),Ht().catch(N=>({available:!1,error:String(N)})),Xt().catch(N=>({available:!1,error:String(N)})),qt().catch(N=>({available:!1,error:String(N)})),Kt().catch(N=>({available:!1,error:String(N)})),Qt().catch(N=>({available:!1,error:String(N)}))]),[M,l,S,k]=await Promise.all([Us(w,p).catch(()=>null),Ws(w,p).catch(()=>null),qs(w,p).catch(()=>null),Ks(w,p).catch(()=>null)]),T={strata:{"stored-semantics":"failed"}},I={"claude-code":M?{strata:Fi(M),registryEntries:M.registryEntries,transcriptsRead:M.transcriptsRead,transcriptsFailed:M.transcriptsFailed,problems:M.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:l?{strata:ot({storedAvailable:l.storedAvailable,read:l.rolloutsRead,failed:l.rolloutsFailed}),rolloutsRead:l.rolloutsRead,rolloutsFailed:l.rolloutsFailed,problems:l.problems.slice(0,20)}:T,cursor:S?{strata:ot({storedAvailable:S.storedAvailable,read:S.composersRead,failed:S.composersFailed}),composersRead:S.composersRead,composersFailed:S.composersFailed,problems:S.problems.slice(0,20)}:T,gemini:k?{strata:ot({storedAvailable:k.storedAvailable,read:k.sessionsRead,failed:k.sessionsFailed}),sessionsRead:k.sessionsRead,sessionsFailed:k.sessionsFailed,problems:k.problems.slice(0,20)}:T},x={deepseek:le(m),"0x2f":le(v),"claude-code":le(d),codex:le(A),cursor:le(g),gemini:le(y)},C=t.collectionHealth();for(const[N,V]of Object.entries(x)){const K=C[N];K?.failing&&(V.presence="failed",V.error??=K.lastError)}const _=t.os.stats(),O=Object.values(x).filter(N=>N.available).length>0?"observing":_.samples>0?"os-only":"empty",U=Object.entries(C).filter(([,N])=>N.failing).map(([N])=>N),X=f.health(),j={ok:U.length===0&&X.ok&&!t.fault()&&!_.lastError,failingSources:U,collection:C,store:X,os:_.lastError?{failing:!0,lastError:_.lastError}:{failing:!1}};return B(i,200,{machine:t.machine,mode:O,fault:t.fault()??void 0,health:j,store:{...f.stats(),path:f.path,schemaVersion:f.schemaVersion,bytes:f.sizeBytes(),retention:{...t.retention,description:Ye(t.retention)}},os:{..._,running:t.os.running,source:pe},sources:x,observation:I}),!0}if(u.pathname==="/api/collect"){const m=t.checkStore();if(m)return B(i,503,{error:m.message,fault:m}),!0;const v=await Yn(f,pt,w,p,A=>t.recordCollection([A])),d=await t.os.sample();return t.recordCollection([{id:pe,ok:!t.os.stats().lastError,error:t.os.stats().lastError}]),B(i,200,{...v,sources:[...v.sources,{id:pe,ok:!t.os.stats().lastError,collected:d.length,inserted:d.length,duplicate:0,error:t.os.stats().lastError,ms:0}]}),!0}if(u.pathname==="/api/world")return B(i,200,{from:w,to:p,now:E,...Ie(f,w,p,t.machine.id)}),!0;if(u.pathname==="/api/health")return B(i,200,{pid:process.pid,version:e.version??"dev",contract:At,store:t.path,health:Ss(t)}),!0;if(u.pathname==="/api/landscape"){let m={from:w,to:p},v="WINDOW",d;if(u.searchParams.get("window")==="live"){if(m=As(E),v="TODAY",d=Ie(f,m.from,m.to,t.machine.id),d.world.executions.length===0&&d.world.sessions.length===0){const y={from:E-xi,to:E},M=Ie(f,y.from,y.to,t.machine.id);(M.world.executions.length>0||M.world.sessions.length>0)&&(m=y,v="LAST 72H",d=M)}}else d=Ie(f,w,p,t.machine.id);const A=ts(d.world),g=ls(A);return u.searchParams.get("window")==="live"&&(n={at:E,label:v,world:A,landscape:g}),B(i,200,{...m,now:E,window:v,meta:d.meta,health:Ss(t),...Lr(g)}),!0}if(u.pathname==="/api/today"||u.pathname==="/api/log"){const m=o(E);return B(i,200,u.pathname==="/api/today"?{window:m.label,...ii(m.world)}:{window:m.label,...ai(m.world,m.landscape)}),!0}if(u.pathname==="/api/inspect"){const m=u.searchParams.get("kind")??"",v=u.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(m)||!v||v.length>512)return B(i,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;if(o(E),!n)return!0;const d=(g,y)=>{for(const M of f.subjectEvents(g,y))if(M.provenance?.path)return M.provenance.path},A=Pr(n.world,n.landscape,m,v,d);return A?(B(i,200,A),!0):(B(i,404,{error:"not in the current world"}),!0)}if(u.pathname==="/api/sources"){const m=await Promise.all([Ft().catch(g=>({available:!1,error:String(g)})),Ht().catch(g=>({available:!1,error:String(g)})),Xt().catch(g=>({available:!1,error:String(g)})),qt().catch(g=>({available:!1,error:String(g)})),Kt().catch(g=>({available:!1,error:String(g)})),Qt().catch(g=>({available:!1,error:String(g)}))]),v=t.collectionHealth(),d=t.os.stats(),A=pt.map((g,y)=>{const M=le(m[y]),l=v[g.id];return{id:g.id,presence:l?.failing?"failed":M.presence,origin:M.origin,error:l?.failing?l.lastError??M.error:M.error,consecutiveFailures:l?.consecutiveFailures??0,lastSuccessAt:l?.lastSuccessAt}});return A.push({id:pe,presence:d.lastError?"failed":d.samples>0?"observing":"installed-no-data",origin:void 0,error:d.lastError,consecutiveFailures:v[pe]?.consecutiveFailures??0,lastSuccessAt:d.lastSampleAt??void 0}),B(i,200,{sources:A}),!0}if(u.pathname==="/api/detail"){const m=u.searchParams.get("type")??"",v=u.searchParams.get("id")??"";if(!Nt.includes(m)||!v)return B(i,400,{error:"detail needs type=<entity type> and id"}),!0;if(v.length>512)return B(i,400,{error:"id is too long"}),!0;const d=f.subjectEvents(m,v);return B(i,200,{type:m,id:v,events:d.slice(0,je),truncated:d.length>je}),!0}if(u.pathname==="/api/events"){const m=u.searchParams.get("subject"),v=m?m.split(",").filter(A=>Nt.includes(A)):void 0,d=mn(f,w,p,v,t.machine.id);return B(i,200,{from:w,to:p,now:E,events:d.events.slice(0,je),truncated:d.events.length>je,relationships:d.relationships}),!0}return B(i,404,{error:"unknown endpoint"}),!0}catch(m){return s.error(`[057] ${String(m)}`),B(i,500,{error:String(m)}),!0}}}const Mt=5057,ce="127.0.0.1",Bi=["localhost","127.0.0.1","[::1]","::1"],Hi=10,Wi={".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 Is(e,t,s){let n;try{n=decodeURIComponent(t)}catch{return!1}if(n.includes("\0"))return!1;const o=Re(e,`.${On(n)}`);if(o!==e&&!o.startsWith(e+$n)||!L(o)||!qe(o).isFile())return!1;const r=Wi[Rn(o).toLowerCase()]??"application/octet-stream";return s.statusCode=200,s.setHeader("content-type",r),s.setHeader("x-content-type-options","nosniff"),Tt(s),s.setHeader("cache-control",t.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),En(o).pipe(s),!0}function Xi(e,t,s,n){return new Promise((o,r)=>{let a=n,i=t;const c=u=>{if(u.code==="EADDRINUSE"&&a>1){a--,i++,e.listen(i,s);return}e.off("error",c),r(u)};e.on("error",c),e.once("listening",()=>{e.off("error",c);const u=e.address();o(typeof u=="object"&&u?u.port:i)}),e.listen(i,s)})}function Gi(e,t){const s=String(e.headers["sec-fetch-dest"]??"");if(qi.has(s))return`refusing to be embedded as ${s}`;const n=e.headers["sec-fetch-site"];return typeof n=="string"&&n!==""&&n!=="same-origin"&&n!=="none"?`refusing a ${n} request for ${t}`:null}const qi=new Set(["iframe","frame","embed","object","fencedframe"]);async function hn(e){const t=e.log??fn,s=Re(e.root),n=e.host??ce,o=n===ce||n==="::1"||n==="localhost",r=e.runtime?.path??e.storePath??Ve();if(!e.runtime){const f=await ui(r);if(f)throw new Et(f)}const a=e.runtime??It({path:e.storePath,log:t,retention:e.retention,observe:e.observe}),i=Pi({runtime:a,log:t,version:e.version,allowedHosts:o?Bi:null}),c=In((f,E)=>{(async()=>{try{if(await i(f,E))return;if(f.method!=="GET"&&f.method!=="HEAD"){E.statusCode=405,E.setHeader("allow","GET, HEAD"),E.end();return}const b=new URL(f.url??"/","http://localhost").pathname,w=Gi(f,b);if(w){t.warn(`[057] ${w}`),E.statusCode=403,E.setHeader("content-type","text/plain; charset=utf-8"),Tt(E),E.end(`${w}
|
|
76
|
-
|
|
77
|
-
`)}catch(b){t.error(`[057] request failed: ${String(b)}`),E.headersSent||(E.statusCode=500),E.end()}})()}),u=await Xi(c,e.port??Mt,n,Hi).catch(f=>{throw a.stop(),f}),h=o?"localhost":n;return di(a.path,{pid:process.pid,url:`http://${o?ce:n}:${u}`,version:e.version??"dev",contract:At,store:a.path,startedAt:Date.now(),owner:e.owner??"cli"}),{url:`http://${h}:${u}`,port:u,host:n,runtime:a,server:c,close(){return new Promise(f=>{li(a.path),c.close(()=>{a.stop(),f()}),c.closeAllConnections?.()})}}}function Yi(e){return Re(xn(new URL(".",e)),"..","dist")}const $e="1.1.1";function Vi(e){const t={command:"serve",open:!1,yes:!1,desktop:!1},s=[...e],n=s[0];if(n&&!n.startsWith("-"))if(n==="status"||n==="compact"||n==="reset")t.command=n,s.shift();else return{...t,command:"help",error:`unknown command: ${n}`};for(;s.length;){const o=s.shift(),[r,a]=o.includes("=")?zi(o,"="):[o,void 0],i=()=>a??s.shift();switch(r){case"-h":case"--help":t.command="help";break;case"-v":case"--version":t.command="version";break;case"--open":t.open=!0;break;case"--yes":case"-y":t.yes=!0;break;case"--desktop":t.desktop=!0;break;case"--port":{const c=i(),u=Number(c);if(!Number.isInteger(u)||u<0||u>65535)return{...t,command:"help",error:`--port needs a port number, got ${c}`};t.port=u;break}case"--host":{const c=i();if(!c)return{...t,command:"help",error:"--host needs a value"};t.host=c;break}case"--store":{const c=i();if(!c)return{...t,command:"help",error:"--store needs a path"};t.store=c;break}default:return{...t,command:"help",error:`unknown option: ${r}`}}}return t}function zi(e,t){const s=e.indexOf(t);return[e.slice(0,s),e.slice(s+1)]}const Ki=`057 — a spatial interface for observing the shape of a computational workday
|
|
76
|
+
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)}
|
|
77
|
+
`,{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(`
|
|
78
|
+
`)){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(`
|
|
79
|
+
`).map(s=>` ${s}`).join(`
|
|
80
|
+
`));const r=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${r} :
|
|
81
|
+
${e.join(`
|
|
82
|
+
`)}`:`${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=[" "," ",`
|
|
83
|
+
`,"\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
|
|
84
|
+
`?`\r
|
|
85
|
+
`:`
|
|
86
|
+
`}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??`
|
|
87
|
+
`,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,`
|
|
88
|
+
`).split(`
|
|
89
|
+
`).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
|
|
90
|
+
`:`
|
|
91
|
+
`}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??`
|
|
92
|
+
`,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(`
|
|
93
|
+
`).map(function(n){return r+n})).join(`
|
|
94
|
+
`)}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(`
|
|
95
|
+
`)}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,`
|
|
96
|
+
`).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(`
|
|
97
|
+
`)}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(`
|
|
98
|
+
`)}}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(`
|
|
99
|
+
`)??"";return`-----BEGIN ${t}-----
|
|
100
|
+
${r}
|
|
101
|
+
-----END ${t}-----
|
|
102
|
+
`}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)}
|
|
103
|
+
`);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}
|
|
104
|
+
event: landscape
|
|
105
|
+
data: ${l.wire}
|
|
106
|
+
|
|
107
|
+
`))}catch(l){n||(r(l),i(),t.end())}finally{s=!1}}},c=setInterval(()=>{a()},e1),u=setInterval(()=>{n||t.write(`: 057
|
|
108
|
+
|
|
109
|
+
`)},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)}
|
|
110
|
+
`)}}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)}
|
|
111
|
+
`)}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()}
|
|
112
|
+
${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}
|
|
113
|
+
`);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
|
|
114
|
+
`)}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.2";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
|
|
78
115
|
|
|
79
116
|
057 observe this machine and serve the interface
|
|
80
117
|
057 status where the store is, what it holds, what is observed
|
|
118
|
+
057 activity summary [--last Nd]
|
|
119
|
+
057 activity availability [--last Nd]
|
|
120
|
+
057 activity compare --last Nd --previous
|
|
121
|
+
057 activity breakdown [--last Nd] --by <dimension>
|
|
122
|
+
private computational activity (experimental)
|
|
123
|
+
dimensions: model, executor, lifecycle, outcome, session, duration-band
|
|
124
|
+
legacy aliases: today, running, waiting, failed, sessions, usage, concurrency
|
|
125
|
+
--width <n>, --color=always|never|auto, --ascii
|
|
81
126
|
057 compact reclaim disk freed by retention (rewrites the store)
|
|
82
127
|
057 reset delete the local store
|
|
83
128
|
|
|
84
129
|
Options
|
|
85
|
-
--port <n> port to serve on (default ${
|
|
86
|
-
--host <addr> address to bind (default ${
|
|
130
|
+
--port <n> port to serve on (default ${Pd}; the next free one if taken)
|
|
131
|
+
--host <addr> address to bind (default ${ar}; read the warning below first)
|
|
87
132
|
--store <path> store file to use (same as O57_STORE)
|
|
88
133
|
--open open the interface in the default browser — the running
|
|
89
134
|
057's, if one (or 057.app) already observes the store
|
|
@@ -96,56 +141,60 @@ Options
|
|
|
96
141
|
Environment
|
|
97
142
|
O57_STORE store file (default ~/.057/events.db)
|
|
98
143
|
O57_PORT, O57_HOST as --port / --host
|
|
144
|
+
NO_COLOR, FORCE_COLOR colour for 057 activity (on for a terminal unless NO_COLOR is set)
|
|
99
145
|
O57_RETAIN_PROCESS_DAYS days of OS process observations to keep (default 7, 0 = forever)
|
|
100
146
|
O57_RETAIN_DAYS days of session/execution history to keep (default 90, 0 = forever)
|
|
101
147
|
WORK_ROOTS colon-separated workspace roots to look for 0x2F task state in
|
|
102
148
|
DSH_HOME CLAUDE_HOME CODEX_HOME GEMINI_HOME CURSOR_GLOBAL_STORAGE
|
|
103
149
|
override where each source is read from
|
|
104
150
|
|
|
105
|
-
057 observes this machine only. It has no account, no cloud, no analytics
|
|
106
|
-
|
|
151
|
+
057 observes this machine only. It has no account, no cloud, and no analytics. Its browser API
|
|
152
|
+
stays on this Mac. If you pair a 057 Display, current FIELD labels and timing are sent directly
|
|
153
|
+
to that trusted device on your local network. Reset deletes the SQLite store and any Display trust.
|
|
107
154
|
|
|
108
155
|
--host binds beyond the loopback interface and serves your telemetry, unauthenticated, to
|
|
109
156
|
anything that can reach that address. Do not do it on a network you do not control.
|
|
110
|
-
`;function
|
|
111
|
-
`)}async function
|
|
112
|
-
`),(
|
|
113
|
-
${
|
|
114
|
-
Opening ${
|
|
115
|
-
`),await
|
|
116
|
-
${
|
|
117
|
-
Open ${
|
|
118
|
-
`),1)}return
|
|
157
|
+
`;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(`
|
|
158
|
+
`)}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}
|
|
159
|
+
`),(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(`
|
|
160
|
+
${l.message}${d.owner==="desktop"?" — 057.app":""}.
|
|
161
|
+
Opening ${d.url}
|
|
162
|
+
`),await lm(d.url),0):(console.error(`
|
|
163
|
+
${l.message}.
|
|
164
|
+
Open ${d.url} (\`057 --open\`), or stop that 057 before starting another.
|
|
165
|
+
`),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(`
|
|
119
166
|
057 stopping — history is on disk
|
|
120
|
-
`),
|
|
121
|
-
`)
|
|
122
|
-
`),r.
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
167
|
+
`),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
|
|
168
|
+
`),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>
|
|
169
|
+
`),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)}
|
|
170
|
+
`)};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
|
|
171
|
+
`),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(`
|
|
172
|
+
store ${t}${ay()?" (from O57_STORE)":""}
|
|
173
|
+
schema ${r?r.schemaVersion:"none"}
|
|
174
|
+
size ${Gs(s.total)} ${kr(`(db ${Gs(s.db)}, wal ${Gs(s.wal)})`)}
|
|
126
175
|
events ${n.events.toLocaleString()}
|
|
127
176
|
claims ${n.claims.toLocaleString()}
|
|
128
|
-
keeping ${
|
|
129
|
-
permissions ${
|
|
177
|
+
keeping ${ia(e)}
|
|
178
|
+
permissions ${o||"none — no store yet"}
|
|
130
179
|
`),n.bySource.length===0)console.log(` nothing has been captured yet
|
|
131
|
-
`);else{for(const
|
|
132
|
-
`),0}finally{
|
|
180
|
+
`);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
|
|
181
|
+
`),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(`
|
|
133
182
|
removed ${n.processEvents+n.otherEvents} expired events
|
|
134
|
-
${
|
|
135
|
-
`),0}finally{
|
|
183
|
+
${Gs(r)} → ${Gs(s)}
|
|
184
|
+
`),0}finally{e.stop()}}async function U1(t,e){const r=wA(t);console.log(`
|
|
136
185
|
this deletes, permanently:
|
|
137
|
-
`);for(const n of
|
|
138
|
-
`),1;for(const n of
|
|
139
|
-
`),0}function
|
|
140
|
-
`)},warn:
|
|
141
|
-
`)},error:
|
|
142
|
-
`)}}}function
|
|
143
|
-
057: ${
|
|
144
|
-
${
|
|
145
|
-
`),1;const t
|
|
186
|
+
`);for(const n of r)console.log(` ${n}`);if(console.log(""),!e&&!await T1(" delete the local store?"))return console.log(` nothing was deleted
|
|
187
|
+
`),1;for(const n of r)fm(n,{recursive:!0,force:!0});return console.log(` deleted. the next run starts a new store.
|
|
188
|
+
`),0}function Ld(){return{info:t=>{process.stderr.write(`${kr(t)}
|
|
189
|
+
`)},warn:t=>{process.stderr.write(`${t}
|
|
190
|
+
`)},error:t=>{process.stderr.write(`${t}
|
|
191
|
+
`)}}}function sc(t){if(t instanceof gt)return console.error(`
|
|
192
|
+
057: ${t.message}
|
|
193
|
+
${t.remedy}
|
|
194
|
+
`),1;const e=t?.code;return e==="EADDRINUSE"?(console.error(`
|
|
146
195
|
057: no free port was found. Try 057 --port <n>.
|
|
147
|
-
`),1):
|
|
148
|
-
057: cannot bind that address or port (${
|
|
196
|
+
`),1):e==="EACCES"||e==="EADDRNOTAVAIL"?(console.error(`
|
|
197
|
+
057: cannot bind that address or port (${e}).
|
|
149
198
|
`),1):(console.error(`
|
|
150
|
-
057: ${
|
|
151
|
-
`),1)}function
|
|
199
|
+
057: ${t instanceof Error?t.message:String(t)}
|
|
200
|
+
`),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};
|