@probnaya/057-cli 1.1.0 → 1.1.1

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.
Files changed (2) hide show
  1. package/dist-server/057.mjs +46 -62
  2. package/package.json +1 -1
@@ -1,12 +1,12 @@
1
- import{existsSync as F,writeFileSync as Vn,renameSync as Yn,rmSync as Qs,readFileSync as Gn,statSync as at,mkdirSync as zn,chmodSync as Kn,createReadStream as Jn}from"node:fs";import{createInterface as Qn}from"node:readline";import{createServer as Zn}from"node:http";import{join as D,isAbsolute as eo,resolve as qe,dirname as to,normalize as so,sep as no,extname as oo}from"node:path";import{fileURLToPath as ro}from"node:url";import{stat as we,readdir as W,readFile as ue}from"node:fs/promises";import{hostname as io,homedir as Ee}from"node:os";import ao from"node:zlib";import{createHash as Zs}from"node:crypto";import{execFileSync as co,execFile as uo}from"node:child_process";import{DatabaseSync as Ct}from"node:sqlite";import{promisify as lo}from"node:util";const es=["machine","session","execution","process","artifact"];function po(e){return`${e.ns}|${e.parts.join("|")}`}const M={interactions:"interactions",steps:"steps",errors:"errors",retries:"retries",cpuMs:"cpu.ms",tokensInput:"tokens.input",tokensOutput:"tokens.output",tokensCacheRead:"tokens.cacheRead",tokensReasoning:"tokens.reasoning"},fo=[{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 ts(e,t){for(const s of fo){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 mo=(e,t)=>e.validFrom<=t.validTo&&t.validFrom<=e.validTo;function ho(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 go=.5;function bo(e,t){return mo(e,t)?ho(e,t)>=go?2:1:0}const J=e=>`${e.subjectType}:${e.subjectId}`,vo="inferred",yo="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 wo(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 g=J(b),f=i.get(g);if(!f){i.set(g,{...b});continue}f.validFrom=Math.min(f.validFrom,b.validFrom),f.validTo=Math.max(f.validTo,b.validTo)}const c=[...i.values()].sort((b,g)=>J(b)<J(g)?-1:1);if(c.length<2){o++;continue}const u=[];let h=!1;for(let b=0;b<c.length;b++)for(let g=b+1;g<c.length;g++){const f=c[b],p=c[g];if(f.sourceId===p.sourceId)continue;const y=bo(f,p);if(y!==0){if(!ts(f,p)){h=!0;continue}u.push({x:f,y:p,tier:y})}}const m=new Map;for(const b of u)for(const g of[b.x,b.y]){const f=J(g);m.set(f,Math.max(m.get(f)??0,b.tier))}const k=new Map;for(const b of u)for(const g of[b.x,b.y]){const f=J(g);m.get(f)===b.tier&&k.set(f,(k.get(f)??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:g,tier:f}of u){if(m.get(J(b))!==f||m.get(J(g))!==f)continue;if(k.get(J(b))!==1||k.get(J(g))!==1){n.push({key:r,reason:"multiple-candidates",subjects:[J(b),J(g)].sort()});continue}const p=ts(b,g);s.push({from:{type:p.from.subjectType,id:p.from.subjectId},to:{type:p.to.subjectType,id:p.to.subjectId},kind:p.kind,basis:vo,assumption:yo,via:r})}}return{relationships:s,ambiguous:n,unmatched:o,considered:t.size}}async function Ao(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),m=e.append(h);a+=m.inserted,i+=m.duplicate,r.push({id:c.id,ok:!0,collected:h.length,inserted:m.inserted,duplicate:m.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}}const jt="deepseek-harness",So={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"supported",waits:"supported",model:"supported",context:"supported",outcome:"supported"},P=e=>typeof e=="number"&&Number.isFinite(e)?e:0,V=e=>typeof e=="string"?e:void 0;function ko(e){const t=e.split("/").filter(Boolean);return(t[t.length-1]??e).toUpperCase()}function Eo(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=ko(r);let u="deepseek",h,m;for(const w of e)if(w.type==="request/context"&&w.data?(u=V(w.data.provider)??u,h=V(w.data.model)??h):w.type==="session/title"&&w.data&&(m=V(w.data.title)??m),h&&m)break;const b={source:{id:jt,instance:t.instance},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let g=a;for(const w of e){const $=P(w.time);$>g&&(g=$)}const f={ns:"fs.cwd",parts:[t.host,r],validFrom:a,validTo:Math.max(a,g)};s.push({...b,occurredAt:a,seq:"session",kind:"began",subject:{type:"session",id:o},claims:r?[f]:void 0,core:{machineId:t.machine.id,label:m,executor:u,model:h,depth:i},attrs:{context:r,"dsh.delegationDepth":i}});const p=w=>`${o}:turn:${w}`;let y=null;const d=new Map,A=new Map;let v=a;for(const w of e){const $=P(w.time)||v;if($<a)continue;v=$;const l=w.data??{},S=w.seq??`t${$}`,E=T=>({type:"execution",id:p(T)});switch(w.type){case"turn/start":{const T=P(l.turn);y=T,s.push({...b,occurredAt:$,seq:S,kind:"began",subject:E(T),core:{machineId:t.machine.id,sessionId:o,label:m?`${c} · ${m}`:c,executor:u,model:h,depth:i},attrs:{"dsh.turn":T}});break}case"turn/end":{const T=P(l.turn),I=l.reason,N=I?.kind;if(N==="error"){const C=I?.error??{};s.push({...b,occurredAt:$,seq:S,kind:"ended",subject:E(T),core:{outcome:"error",failureCode:V(C.code)??"ERROR",failureMessage:V(C.message)??"Run failed"},attrs:{"dsh.endReason":N}})}else s.push({...b,occurredAt:$,seq:S,kind:"ended",subject:E(T),core:{outcome:N==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":N??"completed"}});y===T&&(y=null);break}case"assistant/message":{const T=P(l.turn),I=l.usage;if(!I)break;const N={[M.tokensInput]:P(I.inputTokens),[M.tokensOutput]:P(I.outputTokens),[M.tokensCacheRead]:P(I.cacheReadTokens),[M.tokensReasoning]:P(I.reasoningTokens),[M.steps]:1};s.push({...b,occurredAt:$,seq:S,kind:"progressed",subject:E(T),core:{measures:N},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:$,seq:S,kind:"progressed",subject:E(P(l.turn)),core:{measures:{[M.interactions]:1}},attrs:{"dsh.tool":V(l.name)}});break}case"tool/result":{const T=l.message;let I=!1;for(const N of T?.content??[])N.isError===!0&&(I=!0);I&&s.push({...b,occurredAt:$,seq:S,kind:"progressed",subject:E(P(l.turn)),core:{measures:{[M.errors]:1}}});break}case"llm/retry":{s.push({...b,occurredAt:$,seq:S,kind:"progressed",subject:E(P(l.turn)),core:{measures:{[M.retries]:1}}});break}case"approval/asked":{const T=V(l.id);if(y===null)break;T&&d.set(T,y),s.push({...b,occurredAt:$,seq:S,kind:"blocked",subject:E(y),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":T}});break}case"approval/decided":{const T=V(l.id),I=T?d.get(T):y;if(I==null)break;d.delete(T??""),s.push({...b,occurredAt:$,seq:S,kind:"resumed",subject:E(I),attrs:{"dsh.approvalId":T}});break}case"tool-workflow/agent-start":{if(y===null)break;const T=V(l.childId);if(!T)break;const I=`${o}:agent:${T}`;A.set(`${V(l.runId)}:${P(l.seq)}`,I),s.push({...b,occurredAt:$,seq:S,kind:"began",subject:{type:"execution",id:I},core:{machineId:t.machine.id,sessionId:o,label:V(l.label)??`${c} · SUB`,executor:u,model:h,parentId:p(y),depth:i+1},attrs:{"dsh.childId":T}});break}case"tool-workflow/agent-end":{const T=`${V(l.runId)}:${P(l.seq)}`,I=A.get(T);if(!I)break;A.delete(T);const N=V(l.outcome);s.push({...b,occurredAt:$,seq:S,kind:"ended",subject:{type:"execution",id:I},core:N==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:N??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":N}});break}}}if(t.closeOpenTurns){const w="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.";y!==null&&s.push({...b,occurredAt:v,seq:"close:turn",kind:"ended",subject:{type:"execution",id:p(y)},core:{outcome:"interrupted"},basis:"inferred",assumption:w});for(const $ of A.values())s.push({...b,occurredAt:v,seq:`close:${$}`,kind:"ended",subject:{type:"execution",id:$},core:{outcome:"interrupted"},basis:"inferred",assumption:w});s.push({...b,occurredAt:v,seq:"close:session",kind:"ended",subject:{type:"session",id:o},basis:"inferred",assumption:w})}return t.since!==void 0?s.filter(w=>w.occurredAt>=t.since):s}function Io(e){const t=[];let s=0;for(;s<e.length;){let n=e.indexOf(`
2
- `,s);n===-1&&(n=e.length);const o=e.slice(s,n);if(s=n+1,o.length!==0&&!(o.startsWith('{"type":"reasoning-chunks"')||o.startsWith('{"type":"text-chunks"')||o.startsWith('{"type":"tool-call-chunks"')||o.startsWith('{"type":"assistant/chunk"')))try{t.push(JSON.parse(o))}catch{}}return t}function To(e){const t=JSON.stringify([e.source.id,e.source.instance,e.occurredAt,e.clock,e.kind,e.subject.type,e.subject.id,e.basis,e.seq??null,tt(e.core),tt(e.attrs)]);return Zs("sha256").update(t).digest("hex").slice(0,32)}function tt(e){if(e==null)return null;if(Array.isArray(e))return e.map(tt);if(typeof e!="object")return e;const t={};for(const s of Object.keys(e).sort())t[s]=tt(e[s]);return t}function oe(e){const{seq:t,...s}=e;return{id:To(e),...s}}let ss;function $o(){try{const e=co("/usr/sbin/scutil",["--get","LocalHostName"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();return/^[A-Za-z0-9-]{1,63}$/.test(e)?e:void 0}catch{return}}function en(){return ss??=$o()??io().replace(/\.local$/i,""),ss}const st="host:";function Mo(e){return`${st}${e}`}function Oo(e){return e.startsWith(st)?e.slice(st.length):void 0}function ns(e){return e.startsWith(st)}const Ro=4247762216,No=407710288,xo=407710303;function _o(e){const t=[];for(let o=0;o+4<=e.length;o++){const r=e.readUInt32LE(o);(r===Ro||r>=No&&r<=xo)&&t.push(o)}if(t.length===0)return Buffer.alloc(0);const s=[];let n=0;for(;n<t.length;){let o=n+1,r=null;for(;;){const a=o<t.length?t[o]:e.length;try{r=ao.zstdDecompressSync(e.subarray(t[n],a));break}catch{if(o>=t.length)break;o++}}r?(s.push(r),n=o):n++}return Buffer.concat(s)}function Dt(){return process.env.DSH_HOME||D(Ee(),".dsh")}function he(){return en()}function Ie(){const e=he();return{id:Mo(e),name:e.toUpperCase(),kind:"laptop",firstSeenAt:0}}const os=new Map;async function tn(){const e=D(Dt(),"sessions");if(!F(e))return[];const t=[];for(const s of await W(e)){const n=D(e,s);let o;try{o=await W(n)}catch{continue}for(const r of o){const a=D(n,r,"session.jsonl.zstd");F(a)&&t.push({path:a,workspace:s,sessionId:r})}}return t}const Lt=10*6e4;async function Co(e,t){const s=await we(e.path),n=os.get(e.path);if(n&&n.mtimeMs===s.mtimeMs&&n.size===s.size)return n.envelopes;const o=await ue(e.path),r=_o(o).toString("utf8"),a=Io(r),i=Date.now()-s.mtimeMs>Lt,u=Eo(a,{machine:t,host:he(),instance:Dt(),observedAt:Date.now(),closeOpenTurns:i}).map(oe);return os.set(e.path,{mtimeMs:s.mtimeMs,size:s.size,envelopes:u}),u}async function jo(e,t){const s=Ie(),n=await tn(),o=[];for(const r of n){let a;try{a=await we(r.path)}catch{continue}if(!(a.mtimeMs<e))for(const i of await Co(r,s))i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function rs(){const e=await tn(),t=Dt();return{available:e.length>0,present:F(t),home:t,sessions:e.length}}const sn=1e3,is=60*sn;function H(e){if(!Number.isFinite(e)||e<=0)return"0m";if(e<is)return`${Math.max(1,Math.round(e/sn))}s`;const t=Math.round(e/is),s=Math.floor(t/60),n=t%60;return s===0?`${n}m`:n===0?`${s}h`:`${s}h ${n}m`}function X(e){if(!Number.isFinite(e))return"—";const t=Math.abs(e);return t>=1e9?`${(e/1e9).toFixed(t>=1e10?0:2)}B`:t>=1e6?`${(e/1e6).toFixed(t>=1e7?0:2)}M`:t>=1e3?`${(e/1e3).toFixed(t>=1e4?0:1)}k`:String(Math.round(e))}function Do(e,t="NOT OBSERVED"){return e===void 0?t:X(e)}function Lo(e){return e===void 0||!Number.isFinite(e)?"—":e>=1e9?`${(e/1e9).toFixed(1)} GB`:e>=1e6?`${(e/1e6).toFixed(0)} MB`:e>=1e3?`${(e/1e3).toFixed(0)} KB`:`${e} B`}function Xe(e){const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function te(e){const t=e.split("/").filter(Boolean);return t[t.length-1]??e}const nt="0x2f",Fo={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"supported",model:"partial",context:"supported",outcome:"supported"},ie=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0},nn=(e,t)=>`2f:${e}#${t}`,Uo=(e,t,s)=>`${nn(e,t)}:run:${s}`;function as(e){return e?.type==="permission"?"approval":"input"}function Po(e){const t=new Map;for(const s of e){const n=typeof s.run=="number"?s.run:1,o=t.get(n);o?o.push(s):t.set(n,[s])}return t}function Bo(e,t){const s=t.find(r=>r.type==="run.started");let n;for(let r=t.length-1;r>=0;r--){const a=t[r];if(a.type==="run.completed"||a.type==="run.failed"||a.type==="needs_user"&&a.blockedOn){n=a;break}}let o;return n?.type==="run.completed"?o="ready":n?.type==="run.failed"?o="failed":n?o="needs_you":e.status==="needs_you"||e.status==="ready"||e.status==="failed"?o=e.status:e.status==="working"?o="working":o=e.error?"failed":"ready",{run:1,provider:e.execution?.provider??null,node:e.execution?.node??null,model:e.execution?.model,externalSessionId:e.execution?.externalSessionId,attempts:e.execution?.attempts??1,startedAt:s?.at,completedAt:n?.at,outcome:o,error:e.error??(n?.type==="run.failed"?n.error:void 0),blockedOn:n?.type==="needs_user"?n.blockedOn:void 0,failure:e.failure}}function Ho(e,t){return Array.isArray(e.runs)&&e.runs.length?e.runs:[Bo(e,t)]}function Wo(e,t,s){if(typeof e.id!="number")return[];const n=nn(s.base,e.id),o=Ho(e,t),r=te(s.base).toUpperCase(),a=e.title,i=e.execution?.provider??o.at(-1)?.provider??nt,c=ie(e.createdAt)??o.map(p=>ie(p.startedAt)).find(p=>p!==void 0);if(c===void 0)return[];const h={source:{id:nt,instance:s.base},observedAt:s.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},m=[{...h,occurredAt:c,kind:"began",subject:{type:"session",id:n},core:{machineId:s.machine.id,label:a,executor:i,model:e.execution?.model},attrs:{context:s.base,"0x2f.taskId":e.id,"0x2f.status":e.status}}],k=Po(t),b=t.filter(p=>p.type==="task.answered"),g=t.find(p=>p.type==="task.closed"),f=o.at(-1);for(let p=0;p<o.length;p++){const y=o[p],d=ie(y.startedAt);if(d===void 0)continue;const A=Uo(s.base,e.id,y.run),v=y.provider??i,w=ie(y.completedAt),$=w??s.now,l=[{ns:"fs.cwd",parts:[s.host,s.base],validFrom:d,validTo:$}];typeof y.externalSessionId=="string"&&y.externalSessionId&&l.push({ns:"agent.session",parts:[v,y.externalSessionId],validFrom:d,validTo:$}),y===f&&typeof e.pid=="number"&&l.push({ns:"os.process",parts:[s.host,e.pid],validFrom:d,validTo:$}),m.push({...h,occurredAt:d,seq:`run:${y.run}`,kind:"began",subject:{type:"execution",id:A},claims:l,core:{machineId:s.machine.id,sessionId:n,label:a?`${r} · ${a} · RUN ${y.run}`:`${r} · RUN ${y.run}`,executor:v,model:y.model??e.execution?.model,depth:0},attrs:{"0x2f.run":y.run,"0x2f.provider":v,"0x2f.workspace":s.base,...y.requestedProvider?{"0x2f.requestedProvider":y.requestedProvider}:{},...e.pid!==void 0&&y===f?{"0x2f.workerPid":e.pid}:{}}});let S=!1,E=0;for(const I of k.get(y.run)??[]){E++;const N=ie(I.at);if(N===void 0||N<d)continue;const C=`run:${y.run}:${E}`;if(I.type==="tool.started")m.push({...h,occurredAt:N,seq:C,kind:"progressed",subject:{type:"execution",id:A},core:{measures:{[M.interactions]:1}},attrs:{"0x2f.tool":I.name}});else if(I.type==="progress")m.push({...h,occurredAt:N,seq:C,kind:"progressed",subject:{type:"execution",id:A}});else if(I.type==="needs_user"&&I.blockedOn){if(S)continue;S=!0,m.push({...h,occurredAt:N,seq:C,kind:"blocked",subject:{type:"execution",id:A},core:{blockedOn:as(I.blockedOn)},attrs:{"0x2f.blockedOn":I.blockedOn.type}})}else if(I.type==="permission.resolved"||I.type==="task.updated"&&typeof I.grant=="string"){if(!S)continue;S=!1,m.push({...h,occurredAt:N,seq:C,kind:"resumed",subject:{type:"execution",id:A},attrs:{"0x2f.grant":I.grant}})}}const T=(I,N,C)=>m.push({...h,occurredAt:I,seq:C,kind:"ended",subject:{type:"execution",id:A},core:N});if(y.outcome==="ready"&&w!==void 0)T(w,{outcome:"completed"},`run:${y.run}:end`);else if(y.outcome==="failed"&&w!==void 0)T(w,{outcome:"error",failureCode:(y.failure?.kind??e.failure?.kind??"unclassified").toUpperCase(),failureMessage:y.error??e.error??"Run failed"},`run:${y.run}:end`);else if(y.outcome==="needs_you"&&w!==void 0){S||(S=!0,m.push({...h,occurredAt:w,seq:`run:${y.run}:block`,kind:"blocked",subject:{type:"execution",id:A},core:{blockedOn:as(y.blockedOn)}}));const I=qo(w,b,o[p+1],g);I!==void 0&&T(I,{outcome:"interrupted"},`run:${y.run}:end`)}}if(g){const p=ie(g.at);p!==void 0&&m.push({...h,occurredAt:p,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return m}function qo(e,t,s,n){const o=[...t.map(a=>ie(a.at)),ie(s?.startedAt),ie(n?.at)];let r;for(const a of o)a===void 0||a<e||(r===void 0||a<r)&&(r=a);return r}function Xo(e){const t=[];for(const s of e.split(`
3
- `))if(s.trim())try{const n=JSON.parse(s);n&&typeof n.type=="string"&&t.push(n)}catch{}return t}const on=".work";function rn(){const e=process.env.WORK_ROOTS;return e?e.split(/[:,]/).map(t=>t.trim()).filter(Boolean):[Ee()]}const cs=e=>F(D(e,on,"tasks")),Vo=new Set(["Desktop","Documents","Downloads"]);async function an(){const e=new Set,t=!process.env.WORK_ROOTS;for(const s of rn()){if(cs(s)){e.add(s);continue}let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory()||o.name.startsWith(".")||t&&Vo.has(o.name))continue;const r=D(s,o.name);cs(r)&&e.add(r)}}return[...e].sort()}async function Yo(){const e=[];for(const t of await an()){const s=D(t,on,"tasks");let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory())continue;const r=D(s,o.name,"task.json");F(r)&&e.push({base:t,slug:o.name,taskPath:r,eventsPath:D(s,o.name,"events.jsonl")})}}return e}const us=new Map;async function Go(e,t,s){let n;try{n=await we(e.taskPath)}catch{return null}const o=await we(e.eventsPath).catch(()=>null),r=Math.max(n.mtimeMs,o?.mtimeMs??0),a=`${n.mtimeMs}:${n.size}:${o?.mtimeMs??0}:${o?.size??0}`,i=us.get(e.taskPath);if(i&&i.stamp===a)return{envelopes:i.envelopes,touchedAt:r};let c;try{c=JSON.parse(await ue(e.taskPath,"utf8"))}catch{return null}let u=[];try{u=Xo(await ue(e.eventsPath,"utf8"))}catch{}const h=Wo(c,u,{machine:t,base:e.base,host:he(),observedAt:Date.now(),now:s}).map(oe);return us.set(e.taskPath,{stamp:a,envelopes:h}),{envelopes:h,touchedAt:r}}async function zo(e,t){const s=Ie(),n=await Yo(),o=[];for(const r of n){const a=await Go(r,s,t);if(a&&!(a.touchedAt<e))for(const i of a.envelopes)i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function ds(){const e=rn(),t=await an();return{available:t.length>0,present:e.some(s=>F(s)),roots:e,workspaces:t}}const ye="claude-code",Ko={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"partial"},cn="claude-code";class ce extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const un=e=>`claude:${e}`;function Jo(e,t){const s=e,n=typeof s?.version=="string"?s.version:void 0;if(!s||typeof s!="object")throw new ce("registry entry is not an object",t,n);if(typeof s.sessionId!="string"||!s.sessionId)throw new ce("registry entry has no sessionId",t,n);if(typeof s.pid!="number"||!Number.isFinite(s.pid))throw new ce("registry entry has no numeric pid",t,n);if(typeof s.startedAt!="number"||!Number.isFinite(s.startedAt))throw new ce("registry entry has no numeric startedAt",t,n);return s}function Qo(e,t,s){const n=[{ns:"agent.session",parts:[cn,e.sessionId],validFrom:e.startedAt,validTo:s.now},{ns:"os.process",parts:[s.host,e.pid],validFrom:e.startedAt,validTo:s.now}];return{source:{id:ye,instance:s.host},occurredAt:e.startedAt,observedAt:s.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:un(e.sessionId)},claims:n,basis:"measured",core:{machineId:s.machine.id,label:e.name??te(e.cwd??"").toUpperCase(),executor:ye},attrs:{context:e.cwd,"claude.sessionId":e.sessionId,"claude.pid":e.pid,"claude.procStart":e.procStart,"claude.version":e.version,"claude.kind":e.kind,"claude.entrypoint":e.entrypoint,"claude.status":e.status,"claude.waitingFor":e.waitingFor},provenance:{path:t,recordId:e.sessionId,sourceVersion:e.version},seq:"registry"}}const Zo=new Set(["stop_hook_summary","turn_duration"]),er="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.",ae=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Me=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function tr(e){const t=[];for(const s of e.split(`
4
- `))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function sr(e){if(!e)return{};const t=e.output_tokens_details;return{[M.tokensInput]:ae(e.input_tokens)+ae(e.cache_creation_input_tokens),[M.tokensOutput]:ae(e.output_tokens),[M.tokensCacheRead]:ae(e.cache_read_input_tokens),[M.tokensReasoning]:ae(t?.thinking_tokens),[M.steps]:1}}function nr(e,t){const s=e.filter(d=>Me(d.timestamp)!==void 0);if(s.length===0)throw new ce("transcript has no timestamped records",t.path);const n=e.find(d=>typeof d.sessionId=="string")?.sessionId;if(n&&n!==t.sessionId)throw new ce(`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=te(r).toUpperCase(),u=t.sessionId,h=un(u),m=Me(s[0].timestamp),k=Me(s[s.length-1].timestamp),g={source:{id:ye,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},f=(d,A)=>({path:t.path,...d?{recordId:d}:{},...A!==void 0?{index:A}:{},...o?{sourceVersion:o}:{}}),p=[{...g,occurredAt:m,kind:"began",subject:{type:"session",id:h},claims:[{ns:"agent.session",parts:[cn,u],validFrom:m,validTo:k}],core:{machineId:t.machine.id,label:c,executor:ye},attrs:{context:r,"claude.sessionId":u,"claude.gitBranch":a,"claude.entrypoint":i,"claude.version":o},provenance:f(u),seq:"session"}],y=[];for(let d=0;d<e.length;d++){const A=e[d];A.type==="user"&&typeof A.promptSource=="string"&&Me(A.timestamp)!==void 0&&y.push(d)}if(y.length===0)throw new ce(`transcript has ${e.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,t.path,o);for(let d=0;d<y.length;d++){const A=y[d],v=d+1<y.length?y[d+1]:e.length,w=d+1,$=`${h}:turn:${w}`,l=Me(e[A].timestamp),S=e.slice(A,v).some(R=>R.isSidechain===!0);let E,T=l,I,N=!1;const C=[];for(let R=A;R<v;R++){const O=e[R],U=Me(O.timestamp);if(U===void 0)continue;const q=O.type==="assistant"||O.type==="user"&&Array.isArray(O.message?.content);if(q&&U>T&&(T=U),q?(I=O,N=!1):O.type==="system"&&Zo.has(O.subtype??"")&&(N=!0),O.type==="assistant"&&O.message){E??=O.message.model;const x=(Array.isArray(O.message.content)?O.message.content:[]).filter(K=>!!K&&typeof K=="object"&&K.type==="tool_use"),G={...sr(O.message.usage)};x.length&&(G[M.interactions]=x.length),C.push({...g,occurredAt:U,kind:"progressed",subject:{type:"execution",id:$},core:{measures:G},attrs:{...x.length?{"claude.tools":x.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":ae(O.message.usage.input_tokens),"claude.usage.outputTokens":ae(O.message.usage.output_tokens),"claude.usage.cacheReadTokens":ae(O.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":ae(O.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":O.message.usage.service_tier}:{}},provenance:f(O.uuid,R),seq:O.uuid??`a${R}`})}else if(O.type==="user"&&O.message&&Array.isArray(O.message.content)){const j=O.message.content.filter(x=>!!x&&typeof x=="object"&&x.is_error===!0).length;j&&C.push({...g,occurredAt:U,kind:"progressed",subject:{type:"execution",id:$},core:{measures:{[M.errors]:j}},provenance:f(O.uuid,R),seq:O.uuid??`e${R}`})}}if(p.push({...g,occurredAt:l,kind:"began",subject:{type:"execution",id:$},core:{machineId:t.machine.id,sessionId:h,label:`${c} · TURN ${w}`,executor:ye,model:E,depth:S?1:0},attrs:{"claude.turn":w,"claude.promptSource":e[A].promptSource,"claude.promptId":e[A].promptId,...S?{"claude.isSidechain":!0}:{}},provenance:f(e[A].uuid,A),seq:`turn:${w}`}),p.push(...C),d+1<y.length||N)p.push({...g,occurredAt:T,kind:"ended",subject:{type:"execution",id:$},core:{outcome:"completed"},provenance:f(e[A].uuid,A),seq:`turn:${w}:end`});else if(t.closeOpenTurns){const R=I?.type==="assistant"&&(I.message?.stop_reason==="end_turn"||I.message?.stop_reason==="stop_sequence");p.push({...g,occurredAt:T,kind:"ended",subject:{type:"execution",id:$},core:{outcome:R?"completed":"interrupted"},basis:"inferred",assumption:er,provenance:f(e[A].uuid,A),seq:`turn:${w}:end`})}}return p}function Ft(){return process.env.CLAUDE_HOME||D(Ee(),".claude")}const It=()=>D(Ft(),"sessions"),or=()=>D(Ft(),"projects"),ls=new Map;async function rr(e,t,s){const n=It();if(!F(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=Jo(JSON.parse(await ue(a,"utf8")),a);s.envelopes.push(oe(Qo(i,a,{machine:e,host:he(),observedAt:t,now:t}))),s.registryEntries++}catch(i){s.problems.push({path:a,message:i instanceof Error?i.message:String(i),sourceVersion:i instanceof ce?i.sourceVersion:void 0})}}}async function dn(){const e=or();if(!F(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 ir(e,t,s,n){const o=await dn();if(o.length!==0){n.storedAvailable=!0;for(const r of o){let a;try{a=await we(r.path)}catch{continue}if(a.mtimeMs<t)continue;const i=Date.now()-a.mtimeMs>Lt,c=`${a.mtimeMs}:${a.size}:${i}`,u=ls.get(r.path);let h;if(u&&u.stamp===c)h=u.envelopes;else try{const m=tr(await ue(r.path,"utf8"));h=nr(m,{machine:e,host:he(),observedAt:Date.now(),path:r.path,sessionId:r.sessionId,closeOpenTurns:i}).map(oe),ls.set(r.path,{stamp:c,envelopes:h})}catch(m){n.transcriptsFailed++,n.problems.push({path:r.path,message:m instanceof Error?m.message:String(m),sourceVersion:m instanceof ce?m.sourceVersion:void 0});continue}n.transcriptsRead++;for(const m of h)m.occurredAt>=t&&m.occurredAt<=s&&n.envelopes.push(m)}}}async function ln(e,t){const s=Ie(),n=Date.now(),o={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await rr(s,n,o),await ir(s,e,t,o),o}async function ar(e,t){return(await ln(e,t)).envelopes}async function ps(){const e=Ft(),t=F(It())?(await W(It()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,s=(await dn()).length;return{available:t>0||s>0,present:F(e),home:e,registry:t,transcripts:s}}const Fe="codex",cr={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"supported"},ur="codex",dr=10*6e4;class Re extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const lr=e=>`codex:${e}`,se=e=>typeof e=="number"&&Number.isFinite(e)?e:0,L=e=>typeof e=="string"&&e?e:void 0,ht=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function pr(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 fr(e){const t=se(e.input_tokens),s=se(e.cached_input_tokens);return{[M.tokensInput]:Math.max(0,t-s),[M.tokensOutput]:se(e.output_tokens),[M.tokensCacheRead]:s,[M.tokensReasoning]:se(e.reasoning_output_tokens),[M.steps]:1}}function mr(e,t){const s=e.find(d=>d.type==="session_meta");if(!s||!s.payload)throw new Re("rollout has no session_meta record",t.path);const n=s.payload,o=L(n.cli_version),r=L(n.session_id)??L(n.id);if(r&&r!==t.sessionId)throw new Re(`rollout names session ${r} but is filed under ${t.sessionId}`,t.path,o);const a=L(n.cwd)??"",i=ht(n.timestamp)??ht(s.timestamp);if(i===void 0)throw new Re("session_meta has no parseable timestamp",t.path,o);const c=te(a).toUpperCase(),u=lr(t.sessionId),m={source:{id:Fe,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},k=(d,A)=>({path:t.path,...d?{recordId:d}:{},...A!==void 0?{index:A}:{},...o?{sourceVersion:o}:{}}),b=[];let g=null,f=i,p=0;for(let d=0;d<e.length;d++){const A=e[d],v=ht(A.timestamp);v!==void 0&&v>f&&(f=v);const w=A.payload;if(!w)continue;if(A.type==="turn_context"){g&&L(w.turn_id)===g.turnId&&(g.model??=L(w.model),g.effort??=L(w.effort));continue}if(A.type!=="event_msg")continue;const $=L(w.type);if($==="task_started"){const S=L(w.turn_id);if(!S||v===void 0)throw new Re(`task_started at ordinal ${A.ordinal} is missing turn_id or timestamp`,t.path,o);g={turnId:S,startedAt:v,interior:[],lastAt:v},b.push(g);continue}if($==="task_complete"){const S=L(w.turn_id),E=b.find(T=>T.turnId===S)??g;if(E&&v!==void 0){E.completedAt=v;const T=w.error;E.outcome=T?"error":"completed",E.failureMessage=T?L(T.message):void 0,E.lastAt=Math.max(E.lastAt,v)}E===g&&(g=null);continue}if($==="token_count"||$==="item_completed"){if(!g){p++;continue}if(v===void 0)continue}else continue;const l=`${u}:turn:${g.turnId}`;if($==="token_count"){const E=w.info?.last_token_usage;if(!E)continue;g.lastAt=Math.max(g.lastAt,v),g.interior.push({...m,occurredAt:v,kind:"progressed",subject:{type:"execution",id:l},core:{measures:fr(E)},attrs:{"codex.usage.inputTokens":se(E.input_tokens),"codex.usage.cachedInputTokens":se(E.cached_input_tokens),"codex.usage.cacheWriteInputTokens":se(E.cache_write_input_tokens),"codex.usage.outputTokens":se(E.output_tokens),"codex.usage.reasoningOutputTokens":se(E.reasoning_output_tokens)},provenance:k(void 0,A.ordinal),seq:`o${A.ordinal??d}`});continue}if($==="item_completed"){const S=w.item,E=L(S?.type);if(!S||!E)continue;g.lastAt=Math.max(g.lastAt,v);let T,I;if(E==="CommandExecution"){const N=se(S.exit_code);T={[M.interactions]:1,...N!==0?{[M.errors]:1}:{}},I={"codex.itemType":E,"codex.exitCode":N,...S.process_id!==void 0?{"codex.processId":S.process_id}:{},...L(S.status)?{"codex.status":S.status}:{}}}else if(E==="McpToolCall"){const N=L(S.status)==="failed"||L(S.status)==="error";T={[M.interactions]:1,...N?{[M.errors]:1}:{}},I={"codex.itemType":E,"codex.tool":[L(S.server),L(S.tool)].filter(Boolean).join("."),...L(S.status)?{"codex.status":S.status}:{}}}else if(E==="WebSearch")T={[M.interactions]:1},I={"codex.itemType":E};else if(E==="FileChange"){const N=S.changes;T={[M.interactions]:1},I={"codex.itemType":E,...N&&typeof N=="object"?{"codex.fileChanges":Object.entries(N).map(([C,_])=>({path:C,kind:L(_?.type)}))}:{}}}else continue;g.interior.push({...m,occurredAt:v,kind:"progressed",subject:{type:"execution",id:l},core:{measures:T},attrs:I,provenance:k(L(S.id),A.ordinal),seq:`o${A.ordinal??d}`})}}if(b.length===0&&p>0)throw new Re(`rollout has ${p} work records but no task_started marker`,t.path,o);const y=[{...m,occurredAt:i,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[ur,t.sessionId],validFrom:i,validTo:f}],core:{machineId:t.machine.id,label:c,executor:Fe},attrs:{context:a,"codex.sessionId":t.sessionId,"codex.cliVersion":o,"codex.originator":L(n.originator),"codex.source":L(n.source),"codex.modelProvider":L(n.model_provider),...hr(n.git)},provenance:k(t.sessionId,s.ordinal),seq:"session"}];for(let d=0;d<b.length;d++){const A=b[d],v=`${u}:turn:${A.turnId}`;y.push({...m,occurredAt:A.startedAt,kind:"began",subject:{type:"execution",id:v},core:{machineId:t.machine.id,sessionId:u,label:`${c} · TURN ${d+1}`,executor:Fe,model:A.model,depth:0},attrs:{"codex.turnId":A.turnId,...A.effort?{"codex.effort":A.effort}:{}},provenance:k(A.turnId),seq:`turn:${A.turnId}`}),y.push(...A.interior),A.completedAt!==void 0?y.push({...m,occurredAt:A.completedAt,kind:"ended",subject:{type:"execution",id:v},core:{outcome:A.outcome??"completed",...A.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:A.failureMessage??"turn failed"}:{}},provenance:k(A.turnId),seq:`turn:${A.turnId}:end`}):t.now-f>dr&&y.push({...m,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:v},core:{outcome:"interrupted"},provenance:k(A.turnId),seq:`turn:${A.turnId}:end`})}return y}function hr(e){if(!e||typeof e!="object")return{};const t=e;return{...L(t.branch)?{"codex.gitBranch":t.branch}:{},...L(t.commit_hash)?{"codex.gitCommit":t.commit_hash}:{},...L(t.repository_url)?{"codex.gitOriginUrl":t.repository_url}:{}}}function pn(){return process.env.CODEX_HOME||D(Ee(),".codex")}const fn=()=>D(pn(),"sessions"),gr=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,fs=new Map;async function mn(){const e=fn();if(!F(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=gr.exec(u);h&&t.push({path:D(e,n,r,i,u),sessionId:h[1]})}}}}return t}async function hn(e,t){const s=Ie(),n=Date.now(),o={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},r=await mn();if(r.length===0)return o.storedAvailable=F(fn()),o;o.storedAvailable=!0;for(const a of r){let i;try{i=await we(a.path)}catch{continue}if(i.mtimeMs<e)continue;const c=`${i.mtimeMs}:${i.size}`,u=fs.get(a.path);let h;if(u&&u.stamp===c)h=u.envelopes;else try{const m=pr(await ue(a.path,"utf8"));h=mr(m,{machine:s,host:he(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n}).map(oe),fs.set(a.path,{stamp:c,envelopes:h})}catch(m){o.rolloutsFailed++,o.problems.push({path:a.path,message:m instanceof Error?m.message:String(m),sourceVersion:m instanceof Re?m.sourceVersion:void 0});continue}o.rolloutsRead++;for(const m of h)m.occurredAt>=e&&m.occurredAt<=t&&o.envelopes.push(m)}return o}async function br(e,t){return(await hn(e,t)).envelopes}async function ms(){const e=pn(),t=(await mn()).length;return{available:t>0,present:F(e),home:e,rollouts:t}}const _e="cursor",vr={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"unsupported",context:"partial",outcome:"partial"},yr="cursor";class Je extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const Tt=e=>`cursor:${e}`,Ne=e=>typeof e=="string"&&e?e:void 0,Ve=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,hs=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function gn(e,t){if(typeof e.composerId!="string"||!e.composerId)throw new Je("composer header has no composerId",t);if(typeof e.createdAt!="number"||!Number.isFinite(e.createdAt))throw new Je("composer header has no numeric createdAt",t);if(typeof e.lastUpdatedAt!="number"||!Number.isFinite(e.lastUpdatedAt))throw new Je("composer header has no numeric lastUpdatedAt",t)}function wr(e,t){gn(e,t.path);const s=e.value??{},n=s.subagentInfo,o=n?Ne(n.parentComposerId):void 0,r=t.workspacePath??"",a=Ne(s.name)?.toUpperCase()??(r?te(r).toUpperCase():"CURSOR");return{source:{id:_e,instance:t.host},occurredAt:e.createdAt,observedAt:t.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:Tt(e.composerId)},claims:[{ns:"agent.session",parts:[yr,e.composerId],validFrom:e.createdAt,validTo:e.lastUpdatedAt}],basis:"measured",core:{machineId:t.machine.id,label:a,executor:_e,...o?{parentId:Tt(o)}:{}},attrs:{context:r,"cursor.composerId":e.composerId,"cursor.workspaceId":e.workspaceId,"cursor.isSubagent":e.isSubagent,...n?{"cursor.parentComposerId":Ne(n.parentComposerId),"cursor.subagentType":Ne(n.subagentTypeName)}:{},...Ve(s.totalLinesAdded)!==void 0?{"cursor.linesAdded":s.totalLinesAdded}:{},...Ve(s.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":s.totalLinesRemoved}:{},...Ve(s.filesChangedCount)!==void 0?{"cursor.filesChanged":s.filesChangedCount}:{},...Ne(s.unifiedMode)?{"cursor.mode":s.unifiedMode}:{},...Ve(s._v)!==void 0?{"cursor.schemaVersion":s._v}:{}},provenance:{path:t.path,recordId:e.composerId},seq:"composer"}}const gs="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 Ar(e,t,s){gn(e,s.path);const n=Tt(e.composerId),r={source:{id:_e,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 m=i[h],k=h+1<i.length?i[h+1]:t.length,b=h+1,g=t.slice(m,k),f=g.map(w=>({bubble:w,at:hs(w.createdAt)})).filter(w=>w.at!==void 0);if(f.length<2){u++;continue}const p=Math.min(...f.map(w=>w.at)),y=Math.max(...f.map(w=>w.at)),d=`${n}:turn:${b}`,A=g.filter(w=>w.toolName&&hs(w.createdAt)===void 0),v=A.filter(w=>w.toolStatus==="error").length;c.push({...r,occurredAt:p,kind:"began",subject:{type:"execution",id:d},basis:"inferred",assumption:gs,core:{machineId:s.machine.id,sessionId:n,label:`${Ne(e.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${b}`,executor:_e,depth:e.isSubagent?1:0,...A.length?{measures:{[M.interactions]:A.length,...v?{[M.errors]:v}:{}}}:{}},attrs:{"cursor.turn":b},provenance:a(t[m].bubbleId),seq:`turn:${b}`});for(const{bubble:w,at:$}of f){if(!w.toolName)continue;const l=w.toolStatus==="error",S={[M.interactions]:1,...l?{[M.errors]:1}:{}};c.push({...r,occurredAt:$,kind:"progressed",subject:{type:"execution",id:d},basis:"measured",core:{measures:S},attrs:{"cursor.tool":w.toolName,...w.toolStatus?{"cursor.toolStatus":w.toolStatus}:{}},provenance:a(w.bubbleId),seq:w.bubbleId})}c.push({...r,occurredAt:y,kind:"ended",subject:{type:"execution",id:d},basis:"inferred",assumption:gs,core:{outcome:"completed"},provenance:a(t[m].bubbleId),seq:`turn:${b}:end`})}return{drafts:c,turns:i.length,untimedTurns:u}}function Ue(){return process.env.CURSOR_GLOBAL_STORAGE||D(Ee(),"Library","Application Support","Cursor","User","globalStorage")}function Sr(){return process.env.CURSOR_WORKSPACE_STORAGE||D(Ue(),"..","workspaceStorage")}const bn=()=>D(Ue(),"state.vscdb"),bs=new Map;async function kr(){const e=new Map,t=Sr();if(!F(t))return e;let s;try{s=await W(t)}catch{return e}for(const n of s)try{const o=JSON.parse(await ue(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 Er(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 Je(`composer ${e.composerId} has no numeric createdAt/lastUpdatedAt`,t);return r}function Ir(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"),m=JSON.parse(h);i.set(u,{bubbleId:u,type:m.type,createdAt:typeof m.createdAt=="string"&&m.createdAt?m.createdAt:void 0,toolName:m.toolFormerData?.name,toolStatus:m.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 vn(e,t){const s=Ie(),n=Date.now(),o=bn(),r={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!F(o))return r;r.storedAvailable=!0;const a=await kr();let i;try{i=new Ct(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=Er(u,o);if(h.lastUpdatedAt<e)continue;const m={machine:s,host:he(),observedAt:n,path:o,workspacePath:h.workspaceId?a.get(h.workspaceId):void 0};r.envelopes.push(oe(wr(h,m)));const k=`${h.lastUpdatedAt}`,b=bs.get(h.composerId);let g;if(b&&b.stamp===k)g=b.envelopes;else{const f=Ir(i,h.composerId),{drafts:p}=Ar(h,f,m);g=p.map(oe),bs.set(h.composerId,{stamp:k,envelopes:g})}for(const f of g)f.occurredAt>=e&&f.occurredAt<=t&&r.envelopes.push(f);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 Tr(e,t){return(await vn(e,t)).envelopes}async function vs(){const e=bn();if(!F(e))return{available:!1,present:!1,globalStorage:Ue()};try{const t=new Ct(e,{readOnly:!0});try{const s=t.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:s.n>0,present:!0,globalStorage:Ue(),composers:s.n}}finally{t.close()}}catch{return{available:!1,present:!0,globalStorage:Ue()}}}const Pe="gemini",$r={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"unsupported",model:"supported",context:"partial",outcome:"partial"},Mr="gemini";class ot extends Error{constructor(t,s){super(t),this.path=s,this.name="GeminiFormatError"}path}const Or="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 Rr(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 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
+ `,s);n===-1&&(n=e.length);const o=e.slice(s,n);if(s=n+1,o.length!==0&&!(o.startsWith('{"type":"reasoning-chunks"')||o.startsWith('{"type":"text-chunks"')||o.startsWith('{"type":"tool-call-chunks"')||o.startsWith('{"type":"assistant/chunk"')))try{t.push(JSON.parse(o))}catch{}}return t}function Qn(e){const t=JSON.stringify([e.source.id,e.source.instance,e.occurredAt,e.clock,e.kind,e.subject.type,e.subject.id,e.basis,e.seq??null,Be(e.core),Be(e.attrs)]);return Cn("sha256").update(t).digest("hex").slice(0,32)}function Be(e){if(e==null)return null;if(Array.isArray(e))return e.map(Be);if(typeof e!="object")return e;const t={};for(const s of Object.keys(e).sort())t[s]=Be(e[s]);return t}function se(e){const{seq:t,...s}=e;return{id:Qn(e),...s}}let Ct;function Zn(){try{const e=jn("/usr/sbin/scutil",["--get","LocalHostName"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();return/^[A-Za-z0-9-]{1,63}$/.test(e)?e:void 0}catch{return}}function $s(){return Ct??=Zn()??Nn().replace(/\.local$/i,""),Ct}const He="host:";function eo(e){return`${He}${e}`}function to(e){return e.startsWith(He)?e.slice(He.length):void 0}function jt(e){return e.startsWith(He)}const so=4247762216,no=407710288,oo=407710303;function ro(e){const t=[];for(let o=0;o+4<=e.length;o++){const r=e.readUInt32LE(o);(r===so||r>=no&&r<=oo)&&t.push(o)}if(t.length===0)return Buffer.alloc(0);const s=[];let n=0;for(;n<t.length;){let o=n+1,r=null;for(;;){const a=o<t.length?t[o]:e.length;try{r=_n.zstdDecompressSync(e.subarray(t[n],a));break}catch{if(o>=t.length)break;o++}}r?(s.push(r),n=o):n++}return Buffer.concat(s)}function mt(){return process.env.DSH_HOME||D(he(),".dsh")}function de(){return $s()}function ge(){const e=de();return{id:eo(e),name:e.toUpperCase(),kind:"laptop",firstSeenAt:0}}const Dt=new Map;async function Rs(){const e=D(mt(),"sessions");if(!L(e))return[];const t=[];for(const s of await W(e)){const n=D(e,s);let o;try{o=await W(n)}catch{continue}for(const r of o){const a=D(n,r,"session.jsonl.zstd");L(a)&&t.push({path:a,workspace:s,sessionId:r})}}return t}const ht=10*6e4;async function io(e,t){const s=await me(e.path),n=Dt.get(e.path);if(n&&n.mtimeMs===s.mtimeMs&&n.size===s.size)return n.envelopes;const o=await ie(e.path),r=ro(o).toString("utf8"),a=Jn(r),i=Date.now()-s.mtimeMs>ht,u=Kn(a,{machine:t,host:de(),instance:mt(),observedAt:Date.now(),closeOpenTurns:i}).map(se);return Dt.set(e.path,{mtimeMs:s.mtimeMs,size:s.size,envelopes:u}),u}async function ao(e,t){const s=ge(),n=await Rs(),o=[];for(const r of n){let a;try{a=await me(r.path)}catch{continue}if(!(a.mtimeMs<e))for(const i of await io(r,s))i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function Ft(){const e=await Rs(),t=mt();return{available:e.length>0,present:L(t),home:t,sessions:e.length}}const xs=1e3,Lt=60*xs;function H(e){if(!Number.isFinite(e)||e<=0)return"0m";if(e<Lt)return`${Math.max(1,Math.round(e/xs))}s`;const t=Math.round(e/Lt),s=Math.floor(t/60),n=t%60;return s===0?`${n}m`:n===0?`${s}h`:`${s}h ${n}m`}function G(e){if(!Number.isFinite(e))return"—";const t=Math.abs(e);return t>=1e9?`${(e/1e9).toFixed(t>=1e10?0:2)}B`:t>=1e6?`${(e/1e6).toFixed(t>=1e7?0:2)}M`:t>=1e3?`${(e/1e3).toFixed(t>=1e4?0:1)}k`:String(Math.round(e))}function co(e,t="NOT OBSERVED"){return e===void 0?t:G(e)}function uo(e){return e===void 0||!Number.isFinite(e)?"—":e>=1e9?`${(e/1e9).toFixed(1)} GB`:e>=1e6?`${(e/1e6).toFixed(0)} MB`:e>=1e3?`${(e/1e3).toFixed(0)} KB`:`${e} B`}function xe(e){const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function Q(e){const t=e.split("/").filter(Boolean);return t[t.length-1]??e}const rt="0x2f",ne=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0},Ns=(e,t)=>`2f:${e}#${t}`,lo=(e,t,s)=>`${Ns(e,t)}:run:${s}`;function Ut(e){return e?.type==="permission"?"approval":"input"}function po(e){const t=new Map;for(const s of e){const n=typeof s.run=="number"?s.run:1,o=t.get(n);o?o.push(s):t.set(n,[s])}return t}function fo(e,t){const s=t.find(r=>r.type==="run.started");let n;for(let r=t.length-1;r>=0;r--){const a=t[r];if(a.type==="run.completed"||a.type==="run.failed"||a.type==="needs_user"&&a.blockedOn){n=a;break}}let o;return n?.type==="run.completed"?o="ready":n?.type==="run.failed"?o="failed":n?o="needs_you":e.status==="needs_you"||e.status==="ready"||e.status==="failed"?o=e.status:e.status==="working"?o="working":o=e.error?"failed":"ready",{run:1,provider:e.execution?.provider??null,node:e.execution?.node??null,model:e.execution?.model,externalSessionId:e.execution?.externalSessionId,attempts:e.execution?.attempts??1,startedAt:s?.at,completedAt:n?.at,outcome:o,error:e.error??(n?.type==="run.failed"?n.error:void 0),blockedOn:n?.type==="needs_user"?n.blockedOn:void 0,failure:e.failure}}function mo(e,t){return Array.isArray(e.runs)&&e.runs.length?e.runs:[fo(e,t)]}function ho(e,t,s){if(typeof e.id!="number")return[];const n=Ns(s.base,e.id),o=mo(e,t),r=Q(s.base).toUpperCase(),a=e.title,i=e.execution?.provider??o.at(-1)?.provider??rt,c=ne(e.createdAt)??o.map(m=>ne(m.startedAt)).find(m=>m!==void 0);if(c===void 0)return[];const h={source:{id:rt,instance:s.base},observedAt:s.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},f=[{...h,occurredAt:c,kind:"began",subject:{type:"session",id:n},core:{machineId:s.machine.id,label:a,executor:i,model:e.execution?.model},attrs:{context:s.base,"0x2f.taskId":e.id,"0x2f.status":e.status}}],E=po(t),b=t.filter(m=>m.type==="task.answered"),w=t.find(m=>m.type==="task.closed"),p=o.at(-1);for(let m=0;m<o.length;m++){const v=o[m],d=ne(v.startedAt);if(d===void 0)continue;const A=lo(s.base,e.id,v.run),g=v.provider??i,y=ne(v.completedAt),M=y??s.now,l=[{ns:"fs.cwd",parts:[s.host,s.base],validFrom:d,validTo:M}];typeof v.externalSessionId=="string"&&v.externalSessionId&&l.push({ns:"agent.session",parts:[g,v.externalSessionId],validFrom:d,validTo:M}),v===p&&typeof e.pid=="number"&&l.push({ns:"os.process",parts:[s.host,e.pid],validFrom:d,validTo:M}),f.push({...h,occurredAt:d,seq:`run:${v.run}`,kind:"began",subject:{type:"execution",id:A},claims:l,core:{machineId:s.machine.id,sessionId:n,label:a?`${r} · ${a} · RUN ${v.run}`:`${r} · RUN ${v.run}`,executor:g,model:v.model??e.execution?.model,depth:0},attrs:{"0x2f.run":v.run,"0x2f.provider":g,"0x2f.workspace":s.base,...v.requestedProvider?{"0x2f.requestedProvider":v.requestedProvider}:{},...e.pid!==void 0&&v===p?{"0x2f.workerPid":e.pid}:{}}});let S=!1,k=0;for(const I of E.get(v.run)??[]){k++;const x=ne(I.at);if(x===void 0||x<d)continue;const C=`run:${v.run}:${k}`;if(I.type==="tool.started")f.push({...h,occurredAt:x,seq:C,kind:"progressed",subject:{type:"execution",id:A},core:{measures:{[R.interactions]:1}},attrs:{"0x2f.tool":I.name}});else if(I.type==="progress")f.push({...h,occurredAt:x,seq:C,kind:"progressed",subject:{type:"execution",id:A}});else if(I.type==="needs_user"&&I.blockedOn){if(S)continue;S=!0,f.push({...h,occurredAt:x,seq:C,kind:"blocked",subject:{type:"execution",id:A},core:{blockedOn:Ut(I.blockedOn)},attrs:{"0x2f.blockedOn":I.blockedOn.type}})}else if(I.type==="permission.resolved"||I.type==="task.updated"&&typeof I.grant=="string"){if(!S)continue;S=!1,f.push({...h,occurredAt:x,seq:C,kind:"resumed",subject:{type:"execution",id:A},attrs:{"0x2f.grant":I.grant}})}}const T=(I,x,C)=>f.push({...h,occurredAt:I,seq:C,kind:"ended",subject:{type:"execution",id:A},core:x});if(v.outcome==="ready"&&y!==void 0)T(y,{outcome:"completed"},`run:${v.run}:end`);else if(v.outcome==="failed"&&y!==void 0)T(y,{outcome:"error",failureCode:(v.failure?.kind??e.failure?.kind??"unclassified").toUpperCase(),failureMessage:v.error??e.error??"Run failed"},`run:${v.run}:end`);else if(v.outcome==="needs_you"&&y!==void 0){S||(S=!0,f.push({...h,occurredAt:y,seq:`run:${v.run}:block`,kind:"blocked",subject:{type:"execution",id:A},core:{blockedOn:Ut(v.blockedOn)}}));const I=go(y,b,o[m+1],w);I!==void 0&&T(I,{outcome:"interrupted"},`run:${v.run}:end`)}}if(w){const m=ne(w.at);m!==void 0&&f.push({...h,occurredAt:m,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return f}function go(e,t,s,n){const o=[...t.map(a=>ne(a.at)),ne(s?.startedAt),ne(n?.at)];let r;for(const a of o)a===void 0||a<e||(r===void 0||a<r)&&(r=a);return r}function bo(e){const t=[];for(const s of e.split(`
3
+ `))if(s.trim())try{const n=JSON.parse(s);n&&typeof n.type=="string"&&t.push(n)}catch{}return t}const _s=".work";function Cs(){const e=process.env.WORK_ROOTS;return e?e.split(/[:,]/).map(t=>t.trim()).filter(Boolean):[he()]}const Pt=e=>L(D(e,_s,"tasks")),vo=new Set(["Desktop","Documents","Downloads"]);async function js(){const e=new Set,t=!process.env.WORK_ROOTS;for(const s of Cs()){if(Pt(s)){e.add(s);continue}let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory()||o.name.startsWith(".")||t&&vo.has(o.name))continue;const r=D(s,o.name);Pt(r)&&e.add(r)}}return[...e].sort()}async function yo(){const e=[];for(const t of await js()){const s=D(t,_s,"tasks");let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory())continue;const r=D(s,o.name,"task.json");L(r)&&e.push({base:t,slug:o.name,taskPath:r,eventsPath:D(s,o.name,"events.jsonl")})}}return e}const Bt=new Map;async function wo(e,t,s){let n;try{n=await me(e.taskPath)}catch{return null}const o=await me(e.eventsPath).catch(()=>null),r=Math.max(n.mtimeMs,o?.mtimeMs??0),a=`${n.mtimeMs}:${n.size}:${o?.mtimeMs??0}:${o?.size??0}`,i=Bt.get(e.taskPath);if(i&&i.stamp===a)return{envelopes:i.envelopes,touchedAt:r};let c;try{c=JSON.parse(await ie(e.taskPath,"utf8"))}catch{return null}let u=[];try{u=bo(await ie(e.eventsPath,"utf8"))}catch{}const h=ho(c,u,{machine:t,base:e.base,host:de(),observedAt:Date.now(),now:s}).map(se);return Bt.set(e.taskPath,{stamp:a,envelopes:h}),{envelopes:h,touchedAt:r}}async function Ao(e,t){const s=ge(),n=await yo(),o=[];for(const r of n){const a=await wo(r,s,t);if(a&&!(a.touchedAt<e))for(const i of a.envelopes)i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function Ht(){const e=Cs(),t=await js();return{available:t.length>0,present:e.some(s=>L(s)),roots:e,workspaces:t}}const Se="claude-code",Ds="claude-code";class re extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const Fs=e=>`claude:${e}`;function So(e,t){const s=e,n=typeof s?.version=="string"?s.version:void 0;if(!s||typeof s!="object")throw new re("registry entry is not an object",t,n);if(typeof s.sessionId!="string"||!s.sessionId)throw new re("registry entry has no sessionId",t,n);if(typeof s.pid!="number"||!Number.isFinite(s.pid))throw new re("registry entry has no numeric pid",t,n);if(typeof s.startedAt!="number"||!Number.isFinite(s.startedAt))throw new re("registry entry has no numeric startedAt",t,n);return s}function Eo(e,t,s){const n=[{ns:"agent.session",parts:[Ds,e.sessionId],validFrom:e.startedAt,validTo:s.now},{ns:"os.process",parts:[s.host,e.pid],validFrom:e.startedAt,validTo:s.now}];return{source:{id:Se,instance:s.host},occurredAt:e.startedAt,observedAt:s.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:Fs(e.sessionId)},claims:n,basis:"measured",core:{machineId:s.machine.id,label:e.name??Q(e.cwd??"").toUpperCase(),executor:Se},attrs:{context:e.cwd,"claude.sessionId":e.sessionId,"claude.pid":e.pid,"claude.procStart":e.procStart,"claude.version":e.version,"claude.kind":e.kind,"claude.entrypoint":e.entrypoint,"claude.status":e.status,"claude.waitingFor":e.waitingFor},provenance:{path:t,recordId:e.sessionId,sourceVersion:e.version},seq:"registry"}}const ko=new Set(["stop_hook_summary","turn_duration"]),Io="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.",oe=e=>typeof e=="number"&&Number.isFinite(e)?e:0,ve=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function To(e){const t=[];for(const s of e.split(`
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(`
6
6
  `):"").split(`
7
- `)[0].trim().slice(0,200)||"Gemini reported an error"}const Nr=e=>`gemini:${e}`,ne=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Ye=e=>typeof e=="string"&&e?e:void 0,Oe=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function xr(e,t){const s=e.split(`
8
- `).filter(i=>i.trim());if(s.length===0)throw new ot("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 m=h.messages;if(Array.isArray(m))for(const k of m)a(k);continue}typeof u.id=="string"&&a(u)}if(!n||!n.sessionId)throw new ot("session file has no header with a sessionId",t);return{header:n,messages:o.map(i=>r.get(i))}}const yn=e=>Array.isArray(e.content)&&e.content.some(t=>!!t&&typeof t=="object"&&"functionResponse"in t);function _r(e){if(e.type!=="user"||yn(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 Cr(e){const t=ne(e.input),s=ne(e.cached);return{[M.tokensInput]:Math.max(0,t-s),[M.tokensOutput]:ne(e.output)+ne(e.thoughts),[M.tokensCacheRead]:s,[M.tokensReasoning]:ne(e.thoughts),[M.steps]:1}}function jr(e,t){const{header:s,messages:n}=e,o=s.sessionId,r=Oe(s.startTime);if(r===void 0)throw new ot("session header has no parseable startTime",t.path);const a=n.filter(p=>Oe(p.timestamp)!==void 0),i=a.length?Math.max(...a.map(p=>Oe(p.timestamp))):r,c=t.workspacePath??"",u=c?te(c).toUpperCase():"GEMINI",h=Nr(o),k={source:{id:Pe,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},b=p=>({path:t.path,...p?{recordId:p}:{}}),g=[{...k,occurredAt:r,kind:"began",subject:{type:"session",id:h},claims:[{ns:"agent.session",parts:[Mr,o],validFrom:r,validTo:i}],core:{machineId:t.machine.id,label:u,executor:Pe},attrs:{context:c,"gemini.sessionId":o,"gemini.projectHash":s.projectHash,...Ye(s.kind)?{"gemini.kind":s.kind}:{}},provenance:b(o),seq:"session"}],f=[];for(let p=0;p<n.length;p++)_r(n[p])&&Oe(n[p].timestamp)!==void 0&&f.push(p);if(f.length===0){if(n.some(p=>p.type==="gemini"))throw new ot(`session has ${n.length} messages including model output but no recognisable user prompt`,t.path);return g}for(let p=0;p<f.length;p++){const y=f[p],d=p+1<f.length?f[p+1]:n.length,A=p+1,v=`${h}:turn:${A}`,w=Oe(n[y].timestamp);let $=w,l,S;const E=[];for(let _=y;_<d;_++){const R=n[_],O=Oe(R.timestamp);if(O===void 0||R.type!=="gemini"&&R.type!=="error"&&!(R.type==="user"&&yn(R))||(O>$&&($=O),S=R,R.type!=="gemini"))continue;l??=Ye(R.model);const U=Array.isArray(R.toolCalls)?R.toolCalls:[],q=R.tokens?Cr(R.tokens):{};U.length&&(q[M.interactions]=U.length),Object.keys(q).length!==0&&E.push({...k,occurredAt:O,kind:"progressed",subject:{type:"execution",id:v},core:{measures:q},attrs:{...U.length?{"gemini.tools":U.map(j=>Ye(j.name)??"unknown")}:{},...Ye(R.model)?{"gemini.model":R.model}:{},...R.tokens?{"gemini.usage.input":ne(R.tokens.input),"gemini.usage.output":ne(R.tokens.output),"gemini.usage.cached":ne(R.tokens.cached),"gemini.usage.thoughts":ne(R.tokens.thoughts),"gemini.usage.tool":ne(R.tokens.tool)}:{}},provenance:b(R.id),seq:R.id})}g.push({...k,occurredAt:w,kind:"began",subject:{type:"execution",id:v},core:{machineId:t.machine.id,sessionId:h,label:`${u} · TURN ${A}`,executor:Pe,model:l,depth:0},attrs:{"gemini.turn":A},provenance:b(n[y].id),seq:`turn:${A}`}),g.push(...E);const T=S?.type==="error",I=S?.type==="gemini"&&!(Array.isArray(S.toolCalls)&&S.toolCalls.length),N=p+1<f.length,C=(_,R)=>({...k,occurredAt:$,kind:"ended",subject:{type:"execution",id:v},core:_,...R?{basis:"inferred",assumption:Or}:{},provenance:b(n[y].id),seq:`turn:${A}:end`});T?g.push(C({outcome:"error",failureMessage:Rr(S)},!1)):N||I&&t.settled?g.push(C({outcome:"completed"},!1)):t.closeOpenTurns&&g.push(C({outcome:I?"completed":"interrupted"},!0))}return g}const Dr=3e3;function Ut(){return process.env.GEMINI_HOME||D(Ee(),".gemini")}const wn=()=>D(Ut(),"tmp"),ys=new Map;async function Lr(){const e=new Map;try{const t=JSON.parse(await ue(D(Ut(),"projects.json"),"utf8"));for(const[s,n]of Object.entries(t.projects??{}))typeof n=="string"&&e.set(n,s)}catch{}return e}async function An(){const e=wn();if(!F(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 Sn(e,t){const s=Ie(),n=Date.now(),o={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},r=await An();if(r.length===0)return o.storedAvailable=F(wn()),o;o.storedAvailable=!0;const a=await Lr();for(const i of r){let c;try{c=await we(i.path)}catch{continue}if(c.mtimeMs<e)continue;const u=Date.now()-c.mtimeMs,h=u>Dr,m=u>Lt,k=`${c.mtimeMs}:${c.size}:${h}:${m}`,b=ys.get(i.path);let g;if(b&&b.stamp===k)g=b.envelopes;else try{const f=xr(await ue(i.path,"utf8"),i.path);g=jr(f,{machine:s,host:he(),observedAt:n,path:i.path,workspacePath:a.get(i.slug),settled:h,closeOpenTurns:m}).map(oe),ys.set(i.path,{stamp:k,envelopes:g})}catch(f){o.sessionsFailed++,o.problems.push({path:i.path,message:f instanceof Error?f.message:String(f)});continue}o.sessionsRead++;for(const f of g)f.occurredAt>=e&&f.occurredAt<=t&&o.envelopes.push(f)}return o}async function Fr(e,t){return(await Sn(e,t)).envelopes}async function ws(){const e=Ut(),t=(await An()).length;return{available:t>0,present:F(e),home:e,sessions:t}}const Ur=new Set(["running","waiting"]);function kn(e){return Ur.has(e)}function En(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 Pr=5*6e4;function Br(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 Hr(e,t){const s=e.now-Pr,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,...Br(e.sessions.values())]}}function As(e){const t=En(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),kn(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 ee(e,t){const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:void 0}function rt(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 Wr=[M.tokensInput,M.tokensOutput,M.tokensCacheRead];function de(e){let t=0,s=!1;for(const n of Wr){const o=ee(e,n);o!==void 0&&(s=!0,t+=o)}return s?t:void 0}function In(e){return{input:ee(e,M.tokensInput)??0,output:ee(e,M.tokensOutput)??0,cacheRead:ee(e,M.tokensCacheRead)??0,reasoning:ee(e,M.tokensReasoning)??0}}function Tn(e){const t=de(e.measures);if(t!==void 0)return Ss(t/1e3,200);const s=ee(e.measures,M.cpuMs);if(s!==void 0)return Ss(s/1e3,200)}function Ce(e){return ee(e.measures,M.interactions)}function $n(e){return ee(e.measures,M.steps)??0}function $t(e){return ee(e.measures,M.errors)??0}function Mt(e){return ee(e.measures,M.retries)??0}function Ss(e,t){return Math.min(1,Math.log1p(Math.max(0,e))/Math.log1p(t))}function qr(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 it(e,t=0){return qr(e+"#"+t)%1e5/1e5}const gt=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function Xr(e){if(e<gt.length)return gt[e];const s=-.9+(e-gt.length)*1.15;return{x:620+Math.cos(s)*520,y:300+Math.sin(s)*250,extentX:150,extentY:94}}function Vr(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 ks(e,t){const s=it(t,1),n=it(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 Es=30,Yr=74;function Gr(e){return Es+e*(Yr-Es)}const Is=64,zr=8,Kr=8,Ts=16,$s=.45;function Jr(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 Ms=.32;function Qr(e){const t=Tn(e),s=e.depth>0?.62:1;return t===void 0?Ms*s:Math.min(1,(Ms+.68*t)*s)}function Zr(e,t){const s=Math.max(1,(e.endedAt??t)-e.startedAt),n=(Ce(e)??0)/(s/6e4);return Math.min(1,.25+n/24)}function Os(e){return(e.status==="failed"?3:e.status==="waiting"?2:e.status==="running"?1:0)*1e15+e.lastActivityAt}function ei(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 ti(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=Tn(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 Rs(e){let t=1;for(const s of e)t*=1-Math.min(1,Math.max(0,s));return 1-t}function Ns(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 xs(e){const t=e.now,s=Vr(e.machines.values()).slice(0,zr),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 E=Xr(S);n.set(l.id,E),o.push({id:l.id,name:l.name,kind:l.kind,x:E.x,y:E.y,extentX:E.extentX,extentY:E.extentY,prominence:(a.get(l.id)??0)/r,seed:it(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>Is&&(c.sort((l,S)=>Os(S)-Os(l)),c.length=Is);const u=ei(e),h=l=>{const S=n.get(l.machineId),{x:E,y:T}=ks(S,l.id);return{id:l.id,massId:l.machineId,sessionId:l.sessionId,x:E,y:T,extent:Qr(l),energy:Jr(l,t),rate:Zr(l,t),phase:it(l.id,3)*Math.PI*2,status:l.status,label:l.label,statusSince:l.waitingSince??l.endedAt??l.startedAt,articulation:ti(l,u),shoulder:0,observers:1}},m=new Set(c.map(l=>l.id)),k=new Set,b=[],g=l=>[l.startedAt,l.endedAt??t];for(const l of[...c].sort((S,E)=>S.id<E.id?-1:1)){if(k.has(l.id))continue;const S=[l];k.add(l.id);for(let _=0;_<S.length;_++)for(const R of u.sameExecution.get(S[_].id)??[])!m.has(R)||k.has(R)||(k.add(R),S.push(e.executions.get(R)));if(S.length===1){b.push(h(l));continue}const E=S.map(h),T=E.reduce((_,R)=>R.articulation>_.articulation||R.articulation===_.articulation&&R.id<_.id?R:_);let I=1;const[N,C]=g(e.executions.get(T.id));for(const _ of S){const[R,O]=g(_);I=Math.min(I,Ns(N,C,R,O))}b.push({...T,extent:Math.max(...E.map(_=>_.extent)),energy:Math.max(...E.map(_=>_.energy)),articulation:Rs(E.map(_=>_.articulation)),shoulder:Math.min($s,1-I),observers:S.length})}const f=new Map;for(const l of b){if(u.runObservesSession.has(l.id))continue;const S=f.get(l.sessionId);S?S.push(l):f.set(l.sessionId,[l])}const p=new Map,y=[];for(const l of b){const S=u.runObservesSession.get(l.id),E=S?f.get(S):void 0;if(!S||!E||E.length===0){if(y.push(l),S){const O=f.get(l.sessionId);O?O.push(l):f.set(l.sessionId,[l])}continue}const T=e.executions.get(l.id);let I=1/0,N=-1/0;for(const O of E){const[U,q]=g(e.executions.get(O.id));I=Math.min(I,U),N=Math.max(N,q)}const[C,_]=g(T),R=p.get(S)??{articulations:[],coincidence:1};R.articulations.push(l.articulation),R.coincidence=Math.min(R.coincidence,Ns(C,_,I,N)),p.set(S,R)}const d=[];for(const l of[...f.keys()].sort()){const S=f.get(l),E=e.sessions.get(l);if(!E||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 N=0,C=0;for(const O of S){const U=Gr(O.extent);N=Math.max(N,Math.abs(O.x-T)+U*1.5),C=Math.max(C,Math.abs(O.y-I)+U)}const _=p.get(l),R=Math.max(...S.map(O=>O.articulation));d.push({id:l,massId:S[0].massId,x:T,y:I,extentX:Math.max(N,52),extentY:Math.max(C,36),presence:1,articulation:_?Rs([R,..._.articulations]):R,parentId:E.parentId,empty:!1,shoulder:_?Math.min($s,1-_.coincidence):0,observers:1+(_?.articulations.length??0),label:E.label??E.executor??l})}for(const l of[...e.sessions.values()].sort((S,E)=>S.id<E.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:E,y:T}=ks(S,`session-presence:${l.id}`);d.push({id:l.id,massId:l.machineId,x:E,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>Ts){const l=S=>S.empty?0:f.get(S.id)?.length??0;d.sort((S,E)=>l(E)-l(S)||(S.id<E.id?-1:1)),d.length=Ts}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>=Kr)break;A.push({id:l.id,fromMassId:l.fromMachineId,toMassId:l.toMachineId,energy:1,label:l.label})}const v=new Map;s.forEach((l,S)=>v.set(l.id,S));const w=Math.max(1,e.dayEnd-e.dayStart),$=[];for(const l of e.executions.values()){const S=v.get(l.machineId);if(S===void 0)continue;const E=(l.startedAt-e.dayStart)/w,T=((l.endedAt??t)-e.dayStart)/w;$.push({id:l.id,massId:l.machineId,lane:S,startFraction:Math.max(0,Math.min(1,E)),endFraction:Math.max(0,Math.min(1,T)),status:l.status,label:l.label})}return{time:t,masses:o,disturbances:y,plinths:d,couplings:A,strata:$}}const Mn="057.landscape",On=1;function si(e){return{contract:Mn,version:On,landscape:e}}const Pt="SHAPES FIELD",Bt="METADATA — DOES NOT SHAPE FIELD";function Rn(e){const t=new Date(e),s=n=>String(n).padStart(2,"0");return`${s(t.getHours())}:${s(t.getMinutes())}:${s(t.getSeconds())}`}function ni(e){return H(e).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function oi(e,t,s,n,o=()=>{}){if(s==="mass")return ai(e,t,n);if(s==="coupling")return ci(e,n);const r=e.executions.get(n);return r?ri(e,t,r,s,o("execution",n)):null}function ri(e,t,s,n,o){const r=e.sessions.get(s.sessionId),a=e.machines.get(s.machineId),c=t.disturbances.find(p=>p.id===s.id)?.statusSince??s.endedAt??s.startedAt,u=s.startBasis==="inferred"||s.endBasis==="inferred",h=de(s.measures),m=[{key:"MACHINE",value:(a?.name??s.machineId).toUpperCase()},{key:"STATE",value:s.status.toUpperCase(),tone:s.status},{key:"SINCE",value:Rn(c)},h===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:X(h)}];if(r){const p=r.executionIds.indexOf(s.id),y=t.plinths.some(A=>A.id===r.id),d=p>=0?`${p+1} OF ${r.executionIds.length}`:`OF ${r.executionIds.length}`;m.push({key:"SESSION",value:y?`${d} · PLINTH`:d})}const k=ii(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:te(r.context),note:r.context}),b.push({key:"SOURCE",value:[s.executor,k===void 0?void 0:`pid ${k}`].filter(Boolean).join(" · "),note:o}),b.push({key:"REQUESTS",value:String($n(s))});const g=Ce(s);if(b.push(g===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:Do(g)}),b.push({key:"ELAPSED",value:`${H((s.endedAt??e.now)-s.startedAt)}${u?" · inferred":""}`,note:u?s.boundsAssumption:void 0}),h!==void 0){const p=In(s.measures);b.push({key:"INPUT",value:X(p.input)},{key:"OUTPUT",value:X(p.output)}),b.push({key:"CACHE READ",value:X(p.cacheRead)},{key:"REASONING",value:X(p.reasoning)})}$t(s)>0&&b.push({key:"TOOL ERRORS",value:String($t(s)),tone:"failed"}),Mt(s)>0&&b.push({key:"RETRIES",value:String(Mt(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 f=s.status==="running"||s.status==="waiting";return{id:s.id,eyebrow:n==="stratum"||!f?"SELECTED · RUN":"SELECTED · PROCESS",title:s.label.toUpperCase(),state:{text:f?`${s.status.toUpperCase()} · ${ni(e.now-c)}`:s.status.toUpperCase(),status:s.status},groups:[{title:Pt,metadata:!1,rows:m},{title:Bt,metadata:!0,rows:b}],failure:s.failure?`${s.failure.code}: ${s.failure.message}`:void 0,reveal:o}}function ii(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 ai(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 g=de(b.measures);g!==void 0&&(i=(i??0)+g),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:X(i)}],m=e.processTotals;if(m){const b=new Set;for(const g of e.relationships)g.kind==="ran-as"&&(g.from.type==="process"&&b.add(g.from.id),g.to.type==="process"&&b.add(g.to.id));h.push({key:"PROCESSES",value:`${m.observed} observed`}),h.push({key:"LAST 5 MIN",value:`${m.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 ${m.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const k=o+r;return{id:s,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:k>0?{text:`${k} ACTIVE`,status:o>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:Pt,metadata:!1,rows:u},{title:Bt,metadata:!0,rows:h}]}}function ci(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:Pt,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:o.toUpperCase()},{key:"SINCE",value:Rn(s.startedAt)}]},{title:Bt,metadata:!0,rows:[{key:"WHAT",value:s.label},{key:"SIZE",value:Lo(s.bytes)}]}]}}const Y=e=>({value:e,basis:"measured"}),Ge=(e,t)=>({value:e,basis:"inferred",assumption:t});function Ht(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 _s(e){let t=0;for(const s of e)t+=s.end-s.start;return t}function ui(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 Nn(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 di(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 xn=6e4;function li(e,t){return{start:e.startedAt,end:e.endedAt??t}}function pi(e){const t=[];for(const s of e.executions.values()){s.depth===0&&t.push({start:s.startedAt-xn,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 Ht(t)}function fi(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 m=[],k=new Map;for(const w of s){n+=$n(w),o+=de(w.measures)??0,r+=Ce(w)??0,w.status==="completed"?a++:w.status==="failed"?i++:w.status==="waiting"?c++:w.status==="idle"&&u++;const $=li(w,t);m.push($),h+=w.waitingMs,w.waitingSince!==void 0&&(h+=Math.max(0,t-w.waitingSince));let l=k.get(w.machineId);l||(l={machineId:w.machineId,executions:0,tokens:0,computeTime:0},k.set(w.machineId,l)),l.executions++,l.tokens+=de(w.measures)??0,l.computeTime+=$.end-$.start}const b=Ht(m.map(w=>({...w}))),g=pi(e),f=_s(ui(b,g)),{peak:p,at:y}=Nn(m),d=mi(e),A=Math.max(0,d.length-1);let v=null;for(const w of d)(!v||w.end-w.start>v.end-v.start)&&(v=w);return{requests:Y(n),sessions:Y(e.sessions.size),executions:Y(s.length),tokens:Y(o),toolCalls:Y(r),autonomousCompute:Ge(_s(b),"Wall-clock time during which at least one run was in flight, merged so parallel runs are not double-counted."),humanAgentOverlap:Ge(f,`Compute time intersecting a window when you were plausibly present: the ${xn/1e3}s before you sent a message, and any approval from ask to answer.`),peakConcurrency:Y(p),peakConcurrencyAt:Y(y),contextSwitches:Ge(A,"Transitions between working directories, ordered by time. A directory is the closest thing the source has to a project."),longestFocus:Ge(v,"Longest unbroken stretch spent in one working directory."),waitingOnYou:Y(h),completed:Y(a),failed:Y(i),waiting:Y(c),idle:Y(u),byMachine:k,contextSpans:d,transfers:Y(e.transfers.size)}}function mi(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<=hi?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 hi=15*6e4;function gi(e){return{key:e,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function bt(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=gi(r),s.set(r,a)),a.runs++;const i=de(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+=Ce(o)??0,o.status==="failed"&&a.failed++}for(const[o,r]of n){const a=s.get(o);a&&(a.medianTokens=di(r),a.medianRuns=r.length)}return[...s.values()].sort((o,r)=>r.computeMs-o.computeMs)}function bi(e){const t={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const s of e.executions.values()){const n=In(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 vi(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 yi(e){const t={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const s of e.executions.values())t.toolCalls+=Ce(s)??0,t.toolErrors+=$t(s),t.retries+=Mt(s),s.status==="failed"?t.failed++:s.outcome==="interrupted"?t.interrupted++:s.outcome==="completed"&&t.completed++;return t}function wi(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=Ht(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 m=Math.max(h.start,r),k=Math.min(h.end,a);k>m&&(i+=k-m)}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:Nn(u).peak})}return o}const Qe=6e4,Ai=60*Qe;function Si(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*Ai?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 ${te(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>Qe&&s.push(`${H(t.waitingOnYou.value)} was spent with a run waiting on your answer.`),t.humanAgentOverlap.value>Qe){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*Qe&&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 Cs="(no model)";function ki(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 ${X(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 ${X(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 vt(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?` · ${X(o.tokens)} tok`:""} · ${H(o.computeMs)}`,failed:o.failed,fraction:n>0?o.computeMs/n:0,median:s?ki(o):void 0}))}function Ei(e){const t=fi(e),s=Si(e,t),n=bi(e),o=vi(e),r=yi(e),a=wi(e),i=bt(e,(v,w)=>w?.context),c=bt(e,v=>v.model??Cs),u=bt(e,v=>v.machineId),h=[...e.executions.values()],m=h.filter(v=>de(v.measures)===void 0).length,k=h.filter(v=>v.depth>0).length,b=t.longestFocus.value,g=Math.round(t.humanAgentOverlap.value/Math.max(1,t.autonomousCompute.value)*100),f=[z("REQUESTS",X(t.requests.value),t.requests),z("RUNS",String(t.executions.value),t.executions,{note:k>0?`${k} of them sub-agents`:void 0}),z("SESSIONS",String(t.sessions.value),t.sessions),z("TOKENS",X(t.tokens.value),t.tokens,{note:`${Math.round(n.cacheRead/Math.max(1,n.total)*100)}% cache reads`+(m>0?` · ${m} ${m===1?"run reports":"runs report"} no accounting`:"")}),z("TOOL CALLS",X(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:`${g}% 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?`${te(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})],p=a.length>0?a.reduce((v,w)=>w.computeMs>v.computeMs?w:v,a[0]):void 0,y=v=>`${String(v).padStart(2,"0")}:00`,d=[{title:"WHERE THE TIME WENT",rows:vt(i,te,!1)}];u.length>0&&d.push({title:"BY MACHINE",rows:vt(u,v=>e.machines.get(v)?.name??v,!1)}),c.length>0&&d.push({title:"BY MODEL",rows:vt(c,v=>v===Cs?"model not observed":v,!0)});const A=v=>v/Math.max(1,n.total);return{headline:s.headline,clauses:[...s.clauses],measures:f,hours:a.map(v=>({hour:v.hour,computeMs:v.computeMs,runs:v.runs,peak:v.peak})),busiest:p?`busiest ${y(p.hour)} · ${H(p.computeMs)} of that hour`:void 0,groups:d,tokens:[["CACHE READS",n.cacheRead],["INPUT",n.input],["OUTPUT",n.output],["REASONING",n.reasoning]].map(([v,w])=>({key:v,value:X(w),percent:Math.round(A(w)*100),fraction:A(w)})),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(v=>v.status==="failed").sort((v,w)=>w.startedAt-v.startedAt).slice(0,12).map(v=>({id:v.id,at:Xe(v.startedAt),label:v.label,reason:v.failure?`${v.failure.code}: ${v.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 Ii(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?te(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:de(r.measures)??null,tools:Ce(r)??null,waitedMs:r.waitingMs,inField:s.has(r.id)?"disturbance":n.has(r.id)?"stratum":null}});return{now:e.now,rows:o}}const Wt={[Mn]:On};function qt(e){return`${e}.core.json`}function _n(e){const t=qt(e);if(!F(t))return null;try{const s=JSON.parse(Gn(t,"utf8"));return typeof s.pid!="number"||typeof s.url!="string"?null:s}catch{return null}}function Ti(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function $i(e,t=1500){const s=_n(e);if(!s||s.pid===process.pid||!Ti(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 Mi(e,t){if(e===":memory:")return;const s=qt(e),n=`${s}.${process.pid}.tmp`;Vn(n,`${JSON.stringify(t,null,1)}
9
- `,{mode:384}),Yn(n,s)}function Oi(e,t=process.pid){if(e===":memory:")return;const s=_n(e);s&&s.pid===t&&Qs(qt(e),{force:!0})}class Xt extends Error{constructor(t){super(`057 is already observing ${t.store} at ${t.url} (pid ${t.pid})`),this.record=t}record}const Ot={processDays:7,eventDays:90},Ri=["machine"],js=["process"],yt={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},Ni=["execution","session","artifact"];function Cn(e=process.env){return{processDays:Ds(e.O57_RETAIN_PROCESS_DAYS,Ot.processDays),eventDays:Ds(e.O57_RETAIN_DAYS,Ot.eventDays)}}function Ds(e,t){if(e===void 0||e.trim()==="")return t;const s=Number(e);return Number.isFinite(s)&&s>=0?s:t}function ct(e){const t=(s,n)=>s===0?`${n} kept indefinitely`:`${n} ${s}d`;return`${t(e.processDays,"processes")}, ${t(e.eventDays,"sessions/executions")}, machines never expire`}const Ls=448,xi=384;function _i(){return D(Ee(),".057")}function ut(){const e=process.env.O57_STORE;return e&&e.length>0?e===":memory:"||eo(e)?e:qe(process.cwd(),e):D(_i(),"events.db")}function jn(){const e=process.env.O57_STORE;return typeof e=="string"&&e.length>0}function dt(e){return[e,`${e}-wal`,`${e}-shm`]}function Ci(e){if(e===":memory:")return;const t=to(e);zn(t,{recursive:!0,mode:Ls}),Dn(t,Ls)}function Rt(e){if(e===":memory:")return[];const t=[];for(const s of dt(e))if(F(s)&&!Dn(s,xi)){const n=Vt(s);n!==null&&(n&63)!==0&&t.push({path:s,mode:n})}return t}function Vt(e){try{return at(e).mode&511}catch{return null}}function Dn(e,t){if(process.platform==="win32")return!1;const s=Vt(e);if(s===null)return!1;if((s&~t)===0)return!0;try{return Kn(e,t),!0}catch{return!1}}function Ln(){if(jn())return null;const e=qe(process.cwd(),".057","events.db");return F(e)&&e!==ut()?e:null}const ji=`-- 057 local store.
7
+ `)[0].trim().slice(0,200)||"Gemini reported an error"}const Zo=e=>`gemini:${e}`,ee=e=>typeof e=="number"&&Number.isFinite(e)?e:0,_e=e=>typeof e=="string"&&e?e:void 0,ye=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function er(e,t){const s=e.split(`
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
+ `,{mode:384}),yn(n,s)}function li(e,t=process.pid){if(e===":memory:")return;const s=cn(e);s&&s.pid===t&&Ms(St(e),{force:!0})}class Et extends Error{constructor(t){super(`057 is already observing ${t.store} at ${t.url} (pid ${t.pid})`),this.record=t}record}const dt={processDays:7,eventDays:90},pi=["machine"],ms=["process"],tt={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},fi=["execution","session","artifact"];function un(e=process.env){return{processDays:hs(e.O57_RETAIN_PROCESS_DAYS,dt.processDays),eventDays:hs(e.O57_RETAIN_DAYS,dt.eventDays)}}function hs(e,t){if(e===void 0||e.trim()==="")return t;const s=Number(e);return Number.isFinite(s)&&s>=0?s:t}function Ye(e){const t=(s,n)=>s===0?`${n} kept indefinitely`:`${n} ${s}d`;return`${t(e.processDays,"processes")}, ${t(e.eventDays,"sessions/executions")}, machines never expire`}const gs=448,mi=384;function hi(){return D(he(),".057")}function Ve(){const e=process.env.O57_STORE;return e&&e.length>0?e===":memory:"||Tn(e)?e:Re(process.cwd(),e):D(hi(),"events.db")}function dn(){const e=process.env.O57_STORE;return typeof e=="string"&&e.length>0}function ze(e){return[e,`${e}-wal`,`${e}-shm`]}function gi(e){if(e===":memory:")return;const t=Mn(e);An(t,{recursive:!0,mode:gs}),ln(t,gs)}function lt(e){if(e===":memory:")return[];const t=[];for(const s of ze(e))if(L(s)&&!ln(s,mi)){const n=kt(s);n!==null&&(n&63)!==0&&t.push({path:s,mode:n})}return t}function kt(e){try{return qe(e).mode&511}catch{return null}}function ln(e,t){if(process.platform==="win32")return!1;const s=kt(e);if(s===null)return!1;if((s&~t)===0)return!0;try{return Sn(e,t),!0}catch{return!1}}function pn(){if(dn())return null;const e=Re(process.cwd(),".057","events.db");return L(e)&&e!==Ve()?e:null}const bi=`-- 057 local store.
10
10
  --
11
11
  -- \`events\` is the only durable truth. \`claims\` is denormalized out of events so identity
12
12
  -- resolution is one indexed read rather than a scan; it is rebuildable from events at any time.
@@ -57,49 +57,33 @@ CREATE TABLE IF NOT EXISTS claims (
57
57
  CREATE INDEX IF NOT EXISTS claims_key ON claims(key, valid_from, valid_to);
58
58
  CREATE INDEX IF NOT EXISTS claims_window ON claims(valid_to, valid_from);
59
59
  CREATE INDEX IF NOT EXISTS claims_event ON claims(event_id);
60
- `,je=1;class ve extends Error{constructor(t,s,n){super(t),this.kind=s,this.remedy=n,this.name="StoreError"}kind;remedy}function wt(e){const t=e?.code;if(t==="EACCES"||t==="EPERM"||t==="EROFS")return!0;const s=e instanceof Error?e.message:String(e);return/readonly|read-only|attempt to write a readonly database|unable to open database file|permission denied|SQLITE_(READONLY|PERM|CANTOPEN)/i.test(s)}function At(e,t){const s=t instanceof Error?t.message:String(t);return new ve(`store ${e} cannot be written: ${s}`,"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 Di(e){Ci(e);let t;try{t=new Ct(e)}catch(f){throw wt(f)?At(e,f):new ve(`cannot open the store at ${e}: ${f instanceof Error?f.message:String(f)}`,"unreadable","Check that the path exists and names a file 057 can open, or point O57_STORE elsewhere.")}let s;try{s=Number(t.prepare("PRAGMA user_version").get().user_version)}catch(f){throw t.close(),wt(f)?At(e,f):new ve(`store ${e} is not a readable database: ${f instanceof Error?f.message:String(f)}`,"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(s>je)throw t.close(),new ve(`store ${e} was written by a newer 057 (schema ${s}, this build understands ${je})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{t.exec(ji);const f=new Set(t.prepare("PRAGMA table_info(events)").all().map(p=>String(p.name)));f.has("stratum")||t.exec("ALTER TABLE events ADD COLUMN stratum TEXT"),f.has("provenance")||t.exec("ALTER TABLE events ADD COLUMN provenance TEXT"),s!==je&&t.exec(`PRAGMA user_version = ${je}`)}catch(f){t.close();const p=f instanceof Error?f.message:String(f);throw wt(f)?At(e,f):new ve(`store ${e} could not be prepared: ${p}`,"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.")}Rt(e);const n=1e3,o=new Set,r=new Set;let a=null;const i=(f,p)=>{r.add(f),a??=Date.now(),o.size<n&&o.add(p)},c=f=>Fi(f,i),u=t.prepare(`INSERT OR IGNORE INTO events
60
+ `,ke=1;class fe extends Error{constructor(t,s,n){super(t),this.kind=s,this.remedy=n,this.name="StoreError"}kind;remedy}function st(e){const t=e?.code;if(t==="EACCES"||t==="EPERM"||t==="EROFS")return!0;const s=e instanceof Error?e.message:String(e);return/readonly|read-only|attempt to write a readonly database|unable to open database file|permission denied|SQLITE_(READONLY|PERM|CANTOPEN)/i.test(s)}function nt(e,t){const s=t instanceof Error?t.message:String(t);return new fe(`store ${e} cannot be written: ${s}`,"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 vi(e){gi(e);let t;try{t=new ft(e)}catch(p){throw st(p)?nt(e,p):new fe(`cannot open the store at ${e}: ${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 s;try{s=Number(t.prepare("PRAGMA user_version").get().user_version)}catch(p){throw t.close(),st(p)?nt(e,p):new fe(`store ${e} 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(s>ke)throw t.close(),new fe(`store ${e} was written by a newer 057 (schema ${s}, this build understands ${ke})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{t.exec(bi);const p=new Set(t.prepare("PRAGMA table_info(events)").all().map(m=>String(m.name)));p.has("stratum")||t.exec("ALTER TABLE events ADD COLUMN stratum TEXT"),p.has("provenance")||t.exec("ALTER TABLE events ADD COLUMN provenance TEXT"),s!==ke&&t.exec(`PRAGMA user_version = ${ke}`)}catch(p){t.close();const m=p instanceof Error?p.message:String(p);throw st(p)?nt(e,p):new fe(`store ${e} could not be prepared: ${m}`,"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.")}lt(e);const n=1e3,o=new Set,r=new Set;let a=null;const i=(p,m)=>{r.add(p),a??=Date.now(),o.size<n&&o.add(m)},c=p=>wi(p,i),u=t.prepare(`INSERT OR IGNORE INTO events
61
61
  (id, source_id, source_instance, occurred_at, observed_at, clock, kind,
62
62
  subject_type, subject_id, core, attrs, basis, assumption, stratum, provenance)
63
63
  VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),h=t.prepare(`INSERT INTO claims
64
64
  (event_id, key, ns, subject_type, subject_id, source_id, valid_from, valid_to)
65
- VALUES (?,?,?,?,?,?,?,?)`),m=t.prepare("SELECT * FROM events WHERE occurred_at >= ? AND occurred_at <= ? ORDER BY occurred_at, id"),k=new Map,b=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
66
- FROM claims WHERE valid_from <= ? AND valid_to >= ?`),g={path:e,schemaVersion:je,append(f){let p=0,y=0;t.exec("BEGIN");try{for(const d of f){if(u.run(d.id,d.source.id,d.source.instance,d.occurredAt,d.observedAt,d.clock,d.kind,d.subject.type,d.subject.id,d.core?JSON.stringify(d.core):null,d.attrs?JSON.stringify(d.attrs):null,d.basis,d.assumption??null,d.stratum??null,d.provenance?JSON.stringify(d.provenance):null).changes===0){y++;continue}p++;for(const v of d.claims??[])h.run(d.id,po(v),v.ns,d.subject.type,d.subject.id,d.source.id,v.validFrom,v.validTo)}t.exec("COMMIT")}catch(d){throw t.exec("ROLLBACK"),d}return{inserted:p,duplicate:y}},query(f,p,y){if(!y||y.length===0)return m.all(f,p).map(c);const d=[...y].sort().join(",");let A=k.get(d);if(!A){const v=y.map(()=>"?").join(",");A=t.prepare(`SELECT * FROM events
67
- WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${v})
68
- ORDER BY occurred_at, id`),k.set(d,A)}return A.all(f,p,...y).map(c)},claims(f,p){return b.all(p,f).map(y=>{const d=y;return{key:String(d.key),subjectType:d.subject_type,subjectId:String(d.subject_id),sourceId:String(d.source_id),validFrom:Number(d.valid_from),validTo:Number(d.valid_to)}})},stats(){const f=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),p=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),y=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),d=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
69
- FROM events GROUP BY source_id ORDER BY s`).all().map(A=>{const v=A;return{source:String(v.s),events:Number(v.c),first:Number(v.lo),last:Number(v.hi)}});return{events:f,claims:p,bySource:d,earliest:y.lo,latest:y.hi}},begansFor(f){const p=[],y=t.prepare(`SELECT * FROM events
65
+ VALUES (?,?,?,?,?,?,?,?)`),f=t.prepare("SELECT * FROM events WHERE occurred_at >= ? AND occurred_at <= ? ORDER BY occurred_at, id"),E=new Map,b=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
66
+ FROM claims WHERE valid_from <= ? AND valid_to >= ?`),w={path:e,schemaVersion:ke,append(p){let m=0,v=0;t.exec("BEGIN");try{for(const d of p){if(u.run(d.id,d.source.id,d.source.instance,d.occurredAt,d.observedAt,d.clock,d.kind,d.subject.type,d.subject.id,d.core?JSON.stringify(d.core):null,d.attrs?JSON.stringify(d.attrs):null,d.basis,d.assumption??null,d.stratum??null,d.provenance?JSON.stringify(d.provenance):null).changes===0){v++;continue}m++;for(const g of d.claims??[])h.run(d.id,Ln(g),g.ns,d.subject.type,d.subject.id,d.source.id,g.validFrom,g.validTo)}t.exec("COMMIT")}catch(d){throw t.exec("ROLLBACK"),d}return{inserted:m,duplicate:v}},query(p,m,v){if(!v||v.length===0)return f.all(p,m).map(c);const d=[...v].sort().join(",");let A=E.get(d);if(!A){const g=v.map(()=>"?").join(",");A=t.prepare(`SELECT * FROM events
67
+ WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${g})
68
+ ORDER BY occurred_at, id`),E.set(d,A)}return A.all(p,m,...v).map(c)},claims(p,m){return b.all(m,p).map(v=>{const d=v;return{key:String(d.key),subjectType:d.subject_type,subjectId:String(d.subject_id),sourceId:String(d.source_id),validFrom:Number(d.valid_from),validTo:Number(d.valid_to)}})},stats(){const p=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),m=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),v=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),d=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
69
+ FROM events GROUP BY source_id ORDER BY s`).all().map(A=>{const g=A;return{source:String(g.s),events:Number(g.c),first:Number(g.lo),last:Number(g.hi)}});return{events:p,claims:m,bySource:d,earliest:v.lo,latest:v.hi}},begansFor(p){const m=[],v=t.prepare(`SELECT * FROM events
70
70
  WHERE kind = 'began' AND subject_type = ? AND subject_id = ?
71
- ORDER BY occurred_at LIMIT 1`);for(const d of f){const A=d.indexOf(":");if(A<0)continue;const v=y.get(d.slice(0,A),d.slice(A+1));v&&p.push(c(v))}return p},subjectEvents(f,p){return t.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(f,p).map(c)},latestFor(f){return t.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(f)?.hi??null},sweep(f=Ot,p=Date.now()){const y=f.processDays>0?p-f.processDays*864e5:null,d=f.eventDays>0?p-f.eventDays*864e5:null;if(y===null&&d===null)return{...yt};const A=j=>Ri.includes(j)?null:js.includes(j)?y:d,v=t.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
72
- FROM events GROUP BY subject_type, subject_id`).all().map(j=>{const x=j;return{type:String(x.t),id:String(x.i),last:Number(x.last)}}),w=(j,x)=>`${j}:${x}`,$=new Set,l=new Map;for(const j of v){const x=A(j.type);x===null||j.last>=x?$.add(w(j.type,j.id)):l.set(w(j.type,j.id),{type:j.type,id:j.id})}if(l.size===0)return{...yt,processBefore:y,otherBefore:d};const S=[...Ni],E=t.prepare(`SELECT DISTINCT core FROM events
73
- WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),T=new Set(S);let I=[...$].filter(j=>T.has(j.slice(0,j.indexOf(":"))));const N=new Set(I);let C=0;for(let j=0;j<4&&I.length>0;j++){const x=[];for(const G of I){const K=G.indexOf(":");for(const qn of E.all(G.slice(0,K),G.slice(K+1))){const Jt=Ze(qn.core);if(Jt)for(const[Xn,Qt]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const Zt=Jt[Xn];if(typeof Zt!="string")continue;const $e=w(Qt,Zt);l.has($e)&&(l.delete($e),$.add($e),C++,!N.has($e)&&T.has(Qt)&&(N.add($e),x.push($e)))}}}I=x}if(l.size===0)return{...yt,retainedByDependents:C,processBefore:y,otherBefore:d};const _=t.prepare(`DELETE FROM claims WHERE event_id IN
74
- (SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),R=t.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let O=0,U=0,q=0;t.exec("BEGIN");try{for(const{type:j,id:x}of l.values()){q+=Number(_.run(j,x).changes);const G=Number(R.run(j,x).changes);js.includes(j)?O+=G:U+=G}t.exec("COMMIT")}catch(j){throw t.exec("ROLLBACK"),j}return O+U>0&&g.checkpoint(),{processEvents:O,otherEvents:U,claims:q,subjects:l.size,retainedByDependents:C,processBefore:y,otherBefore:d}},checkpoint(){try{t.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes(){const[f,p,y]=dt(e).map(Li);return{db:f,wal:p,shm:y,total:f+p+y}},health(){const f=o.size;return f===0?{ok:!0,malformedRows:0,columns:[],since:null}:{ok:!1,malformedRows:f,columns:[...r].sort(),since:a,remedy:`${f} stored row(s) could not be read as JSON and lost their ${[...r].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(){t.exec("VACUUM"),g.checkpoint(),Rt(e)},close(){g.checkpoint(),t.close()}};return g}function Li(e){try{return at(e).size}catch{return 0}}function Ze(e,t,s){if(e!=null)try{const n=JSON.parse(String(e));if(n&&typeof n=="object")return n;t&&s?.(t);return}catch{t&&s?.(t);return}}function Fi(e,t){const s=e,n=t?o=>t(o,String(s.id)):void 0;return{id:String(s.id),source:{id:String(s.source_id),instance:String(s.source_instance)},occurredAt:Number(s.occurred_at),observedAt:Number(s.observed_at),clock:s.clock,kind:s.kind,subject:{type:s.subject_type,id:String(s.subject_id)},core:Ze(s.core,"core",n),attrs:Ze(s.attrs,"attrs",n),basis:s.basis,assumption:s.assumption?String(s.assumption):void 0,stratum:s.stratum?s.stratum:void 0,provenance:Ze(s.provenance,"provenance",n)}}const be="os",Ui=(e,t)=>`os:${e}:${t.pid}:${t.startedAt}`;function Pi(e,t){const s=/^os:[^:]+:(\d+):(\d+)$/.exec(e);return s?`os:${t}:${s[1]}:${s[2]}`:void 0}const Bi=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.`,Hi=250,Wi=8*1024*1024;function qi(e,t,s){const n={source:{id:be,instance:s.host},observedAt:s.observedAt,clock:"wall",stratum:"machine"},o=[],r=new Map;for(const a of t){const i=Ui(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:Xi(a.command),executor:a.command,measures:{[M.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>=Hi,m=Math.abs(a.rssBytes-u.rssBytes)>=Wi;(h||m)&&o.push({...n,occurredAt:s.observedAt,seq:`obs:${s.observedAt}`,kind:"observed",subject:{type:"process",id:i},claims:[c],basis:"measured",core:{measures:{[M.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:Bi(s.intervalMs),core:{outcome:"completed",measures:{[M.cpuMs]:i.cpuMs}},attrs:{"os.pid":i.pid}});return{envelopes:o,next:r}}function Xi(e){return(e.split("/").pop()??e).toUpperCase()}const Vi=lo(uo);function Yi(){return en()}function Gi(e){const t=[];for(const s of e.split(`
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,m=Date.parse(i);Number.isFinite(m)&&t.push({pid:Number(r),ppid:Number(a),startedAt:m,cpuMs:zi(c),rssBytes:Number(u)*1024,command:h.trim()})}return t}function zi(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 Ki(){const{stdout:e}=await Vi("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return Gi(e)}const Fs=5e3;function Ji(e,t){const s=Yi();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 Ki(),m=Date.now(),{envelopes:k,next:b}=qi(n,h,{machineId:t,host:s,observedAt:m,intervalMs:Fs}),g=k.map(oe);return e.append(g),n=b,r++,a=m,i=void 0,g}catch(h){return i=h instanceof Error?h.message:String(h),[]}finally{c=!1}}return{sample:u,start(){o||(u(),o=setInterval(()=>{u()},Fs),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)},Qi=36e5,Zi=15e3,ea=3;function lt(e={}){const t=e.log??Fn,s=e.path??ut(),n=e.retention??Cn(),o=Di(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=Ln();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=Ie();o.append([oe({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=Ji(o,i.id),u=new Map;function h(d){for(const A of d){const v=u.get(A.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};A.ok?(v.consecutiveFailures=0,v.failing=!1,v.failingSince=void 0,v.lastSuccessAt=Date.now()):(v.consecutiveFailures===0&&(v.failingSince=Date.now()),v.consecutiveFailures++,v.totalFailures++,v.lastFailureAt=Date.now(),v.lastError=A.error,v.consecutiveFailures>=ea&&!v.failing&&(v.failing=!0,t.warn(`[057] source ${A.id} has failed ${v.consecutiveFailures} collection rounds in a row: ${A.error??"unknown error"}`))),u.set(A.id,v)}}const m=Us(s);let k=null;function b(d){return k||(k=d,t.error(`[057] ${d.message} — ${d.remedy}`),c.stop()),k}function g(){if(k)return k;if(s===":memory:")return null;if(!F(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=Us(s);return m!==null&&d!==null&&d!==m?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 f=o.sweep(n);f.processEvents+f.otherEvents>0&&t.info(`[057] retention: removed ${f.processEvents} process and ${f.otherEvents} semantic events (${ct(n)})`);const p=setInterval(()=>{if(!k)try{o.sweep(n),Rt(s)}catch(d){t.warn(`[057] retention sweep failed: ${String(d)}`)}},Qi);p.unref?.();const y=setInterval(()=>{g()},Zi);return y.unref?.(),{store:o,machine:i,os:c,path:s,retention:n,fault:()=>k,sweep:d=>o.sweep(n,d),checkStore:g,recordCollection:h,collectionHealth:()=>Object.fromEntries(u),stop(){clearInterval(p),clearInterval(y),c.stop(),o.close()}}}function Us(e){try{return at(e).ino}catch{return null}}const ta=9e4;function Ps(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 sa(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 na(e,t){if(e.seen.has(t.id))return;e.seen.add(t.id),t.occurredAt>e.now&&(e.now=t.occurredAt),sa(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":oa(e,t,n);break;case"process":ra(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 oa(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&&rt(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&&rt(r.measures,n.measures),r.lastActivityAt=s,r.status==="idle"&&(r.status="running",e.active.add(o));break}case"blocked":{if(!kn(r.status))break;r.status="waiting",r.waitingSince=s,r.waitReason=n.blockedOn??"input",r.lastActivityAt=s;break}case"resumed":{Ps(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"}),Ps(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 ra(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&&rt(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[M.cpuMs];typeof i=="number"&&(a.measures[M.cpuMs]=i);const{[M.cpuMs]:c,...u}=n.measures;rt(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 ia(e,t){for(let s=0;s<t.length;s++)na(e,t[s])}function aa(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>ta&&(n.status="idle")}}}function Un(e,t,s,n,o){const r=o?ca(o):void 0,a=r?Bs(e.query(t,s,n),r):e.query(t,s,n),i=new Set,c=new Set,u=new Map,h=b=>{const g=`${b.subject.type}:${b.subject.id}`;b.kind==="began"?(i.add(g),u.set(g,b)):c.add(g),b.core?.sessionId&&c.add(`session:${b.core.sessionId}`),b.core?.machineId&&c.add(`machine:${b.core.machineId}`)};for(const b of a)h(b);const m=[];for(let b=0;b<4;b++){const g=[...c].filter(p=>!i.has(p));if(g.length===0)break;const f=r?Bs(e.begansFor(g),r):e.begansFor(g);if(f.length===0)break;for(const p of f)u.set(`${p.subject.type}:${p.subject.id}`,p),m.push(p.occurredAt<t?{...p,occurredAt:t}:p),h(p),i.add(`${p.subject.type}:${p.subject.id}`)}return{events:[...m,...a].sort((b,g)=>b.occurredAt-g.occurredAt||Hs(b)-Hs(g)),declarations:[...u.values()],relationships:wo(e.claims(t,s)).relationships}}function Pn(e,t,s,n){const o=performance.now(),{events:r,declarations:a,relationships:i}=Un(e,t,s,void 0,n),c=performance.now()-o,u=performance.now(),h=En(t,s);ia(h,r),aa(h,s);const m=performance.now()-u;return{state:h,events:r,declarations:a,relationships:i,meta:{events:r.length,readMs:Math.round(c*10)/10,deriveMs:Math.round(m*10)/10}}}function De(e,t,s,n){const o=Pn(e,t,s,n),r=performance.now();return{world:Hr(o.state,o.relationships),meta:{...o.meta,serializeMs:Math.round((performance.now()-r)*10)/10}}}function ca(e){const t=Oo(e);return s=>{if(s.subject.type==="machine")return s.subject.id!==e&&ns(s.subject.id)?null:s;const n=s.core?.machineId;if(!n||n===e||!ns(n))return s;const o=s.subject.type==="process"&&t?Pi(s.subject.id,t):void 0;return{...s,...o?{subject:{...s.subject,id:o}}:{},core:{...s.core,machineId:e}}}}function Bs(e,t){const s=[];for(const n of e){const o=t(n);o&&s.push(o)}return s}function Hs(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}}const Nt=[{id:jt,collect:(e,t)=>jo(e,t)},{id:nt,collect:(e,t)=>zo(e,t)},{id:ye,collect:(e,t)=>ar(e,t)},{id:Fe,collect:(e,t)=>br(e,t)},{id:_e,collect:(e,t)=>Tr(e,t)},{id:Pe,collect:(e,t)=>Fr(e,t)}],Ws=[...Nt.map(e=>e.id),be],qs=10*365*24*36e5,ze=2e5,ua=24*36e5,da=72*36e5;function Xs(e){const t=new Date(e);return t.setHours(0,0,0,0),{from:t.getTime(),to:e}}function Vs(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:Ws.length,reported:Ws.filter(i=>t[i]!==void 0).length}}}function la(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(fa.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[pa])return"refusing a state-changing request that carries no fetch metadata";return null}const pa="x-057-client",fa=new Set(["iframe","frame","embed","object","fencedframe"]);function Yt(e){e.setHeader("x-frame-options","DENY"),e.setHeader("content-security-policy","frame-ancestors 'none'")}function ma(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+ua?{error:"to is too far in the future"}:o-n>qs?{error:`window must not exceed ${qs} 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"),Yt(e),e.end(JSON.stringify(s))}function ha(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 St(e){return{"stored-semantics":e.storedAvailable?e.failed===0?"available":e.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function ga(e){return e.error?"failed":e.available?"observing":e.present?"installed-no-data":"not-installed"}function ba(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 ge(e){return{available:e.available,present:e.present??!1,presence:ga(e),origin:ba(e),error:e.error}}function va(e){const{runtime:t,log:s}=e;let n=null;function o(r){if(!n||r-n.at>6e4){const a=Xs(r),i=As(De(t.store,a.from,a.to,t.machine.id).world);n={at:r,label:"TODAY",world:i,landscape:xs(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=la(a,u.pathname,e.allowedHosts);if(h)return s.warn(`[057] ${h}`),B(i,403,{error:h}),!0;const m=t.store,k=Date.now(),b=ma(u.searchParams,k);if("error"in b)return B(i,400,{error:b.error}),!0;const{from:g,to:f}=b;try{if(u.pathname==="/api/state"){const[p,y,d,A,v,w]=await Promise.all([rs().catch(x=>({available:!1,error:String(x)})),ds().catch(x=>({available:!1,error:String(x)})),ps().catch(x=>({available:!1,error:String(x)})),ms().catch(x=>({available:!1,error:String(x)})),vs().catch(x=>({available:!1,error:String(x)})),ws().catch(x=>({available:!1,error:String(x)}))]),[$,l,S,E]=await Promise.all([ln(g,f).catch(()=>null),hn(g,f).catch(()=>null),vn(g,f).catch(()=>null),Sn(g,f).catch(()=>null)]),T={strata:{"stored-semantics":"failed"}},I={"claude-code":$?{strata:ha($),registryEntries:$.registryEntries,transcriptsRead:$.transcriptsRead,transcriptsFailed:$.transcriptsFailed,problems:$.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:l?{strata:St({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:St({storedAvailable:S.storedAvailable,read:S.composersRead,failed:S.composersFailed}),composersRead:S.composersRead,composersFailed:S.composersFailed,problems:S.problems.slice(0,20)}:T,gemini:E?{strata:St({storedAvailable:E.storedAvailable,read:E.sessionsRead,failed:E.sessionsFailed}),sessionsRead:E.sessionsRead,sessionsFailed:E.sessionsFailed,problems:E.problems.slice(0,20)}:T},N={deepseek:ge(p),"0x2f":ge(y),"claude-code":ge(d),codex:ge(A),cursor:ge(v),gemini:ge(w)},C=t.collectionHealth();for(const[x,G]of Object.entries(N)){const K=C[x];K?.failing&&(G.presence="failed",G.error??=K.lastError)}const _=t.os.stats(),O=Object.values(N).filter(x=>x.available).length>0?"observing":_.samples>0?"os-only":"empty",U=Object.entries(C).filter(([,x])=>x.failing).map(([x])=>x),q=m.health(),j={ok:U.length===0&&q.ok&&!t.fault()&&!_.lastError,failingSources:U,collection:C,store:q,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:{...m.stats(),path:m.path,schemaVersion:m.schemaVersion,bytes:m.sizeBytes(),retention:{...t.retention,description:ct(t.retention)}},os:{..._,running:t.os.running,source:be},sources:N,observation:I}),!0}if(u.pathname==="/api/collect"){const p=t.checkStore();if(p)return B(i,503,{error:p.message,fault:p}),!0;const y=await Ao(m,Nt,g,f,A=>t.recordCollection([A])),d=await t.os.sample();return t.recordCollection([{id:be,ok:!t.os.stats().lastError,error:t.os.stats().lastError}]),B(i,200,{...y,sources:[...y.sources,{id:be,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:g,to:f,now:k,...De(m,g,f,t.machine.id)}),!0;if(u.pathname==="/api/health")return B(i,200,{pid:process.pid,version:e.version??"dev",contract:Wt,store:t.path,health:Vs(t)}),!0;if(u.pathname==="/api/landscape"){let p={from:g,to:f},y="WINDOW",d;if(u.searchParams.get("window")==="live"){if(p=Xs(k),y="TODAY",d=De(m,p.from,p.to,t.machine.id),d.world.executions.length===0&&d.world.sessions.length===0){const w={from:k-da,to:k},$=De(m,w.from,w.to,t.machine.id);($.world.executions.length>0||$.world.sessions.length>0)&&(p=w,y="LAST 72H",d=$)}}else d=De(m,g,f,t.machine.id);const A=As(d.world),v=xs(A);return u.searchParams.get("window")==="live"&&(n={at:k,label:y,world:A,landscape:v}),B(i,200,{...p,now:k,window:y,meta:d.meta,health:Vs(t),...si(v)}),!0}if(u.pathname==="/api/today"||u.pathname==="/api/log"){const p=o(k);return B(i,200,u.pathname==="/api/today"?{window:p.label,...Ei(p.world)}:{window:p.label,...Ii(p.world,p.landscape)}),!0}if(u.pathname==="/api/inspect"){const p=u.searchParams.get("kind")??"",y=u.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(p)||!y||y.length>512)return B(i,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;if(o(k),!n)return!0;const d=(v,w)=>{for(const $ of m.subjectEvents(v,w))if($.provenance?.path)return $.provenance.path},A=oi(n.world,n.landscape,p,y,d);return A?(B(i,200,A),!0):(B(i,404,{error:"not in the current world"}),!0)}if(u.pathname==="/api/sources"){const p=await Promise.all([rs().catch(v=>({available:!1,error:String(v)})),ds().catch(v=>({available:!1,error:String(v)})),ps().catch(v=>({available:!1,error:String(v)})),ms().catch(v=>({available:!1,error:String(v)})),vs().catch(v=>({available:!1,error:String(v)})),ws().catch(v=>({available:!1,error:String(v)}))]),y=t.collectionHealth(),d=t.os.stats(),A=Nt.map((v,w)=>{const $=ge(p[w]),l=y[v.id];return{id:v.id,presence:l?.failing?"failed":$.presence,origin:$.origin,error:l?.failing?l.lastError??$.error:$.error,consecutiveFailures:l?.consecutiveFailures??0,lastSuccessAt:l?.lastSuccessAt}});return A.push({id:be,presence:d.lastError?"failed":d.samples>0?"observing":"installed-no-data",origin:void 0,error:d.lastError,consecutiveFailures:y[be]?.consecutiveFailures??0,lastSuccessAt:d.lastSampleAt??void 0}),B(i,200,{sources:A}),!0}if(u.pathname==="/api/detail"){const p=u.searchParams.get("type")??"",y=u.searchParams.get("id")??"";if(!es.includes(p)||!y)return B(i,400,{error:"detail needs type=<entity type> and id"}),!0;if(y.length>512)return B(i,400,{error:"id is too long"}),!0;const d=m.subjectEvents(p,y);return B(i,200,{type:p,id:y,events:d.slice(0,ze),truncated:d.length>ze}),!0}if(u.pathname==="/api/events"){const p=u.searchParams.get("subject"),y=p?p.split(",").filter(A=>es.includes(A)):void 0,d=Un(m,g,f,y,t.machine.id);return B(i,200,{from:g,to:f,now:k,events:d.events.slice(0,ze),truncated:d.events.length>ze,relationships:d.relationships}),!0}return B(i,404,{error:"unknown endpoint"}),!0}catch(p){return s.error(`[057] ${String(p)}`),B(i,500,{error:String(p)}),!0}}}const Gt=5057,me="127.0.0.1",ya=["localhost","127.0.0.1","[::1]","::1"],wa=10,Aa={".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 Ys(e,t,s){let n;try{n=decodeURIComponent(t)}catch{return!1}if(n.includes("\0"))return!1;const o=qe(e,`.${so(n)}`);if(o!==e&&!o.startsWith(e+no)||!F(o)||!at(o).isFile())return!1;const r=Aa[oo(o).toLowerCase()]??"application/octet-stream";return s.statusCode=200,s.setHeader("content-type",r),s.setHeader("x-content-type-options","nosniff"),Yt(s),s.setHeader("cache-control",t.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),Jn(o).pipe(s),!0}function Sa(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 ka(e,t){const s=String(e.headers["sec-fetch-dest"]??"");if(Ea.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 Ea=new Set(["iframe","frame","embed","object","fencedframe"]);async function Bn(e){const t=e.log??Fn,s=qe(e.root),n=e.host??me,o=n===me||n==="::1"||n==="localhost",r=e.runtime?.path??e.storePath??ut();if(!e.runtime){const m=await $i(r);if(m)throw new Xt(m)}const a=e.runtime??lt({path:e.storePath,log:t,retention:e.retention,observe:e.observe}),i=va({runtime:a,log:t,version:e.version,allowedHosts:o?ya:null}),c=Zn((m,k)=>{(async()=>{try{if(await i(m,k))return;if(m.method!=="GET"&&m.method!=="HEAD"){k.statusCode=405,k.setHeader("allow","GET, HEAD"),k.end();return}const b=new URL(m.url??"/","http://localhost").pathname,g=ka(m,b);if(g){t.warn(`[057] ${g}`),k.statusCode=403,k.setHeader("content-type","text/plain; charset=utf-8"),Yt(k),k.end(`${g}
76
- `);return}if(Ys(s,b==="/"?"/index.html":b,k)||!b.startsWith("/assets/")&&Ys(s,"/index.html",k))return;k.statusCode=404,k.setHeader("content-type","text/plain; charset=utf-8"),k.end(`not found
77
- `)}catch(b){t.error(`[057] request failed: ${String(b)}`),k.headersSent||(k.statusCode=500),k.end()}})()}),u=await Sa(c,e.port??Gt,n,wa).catch(m=>{throw a.stop(),m}),h=o?"localhost":n;return Mi(a.path,{pid:process.pid,url:`http://${o?me:n}:${u}`,version:e.version??"dev",contract:Wt,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(m=>{Oi(a.path),c.close(()=>{a.stop(),m()}),c.closeAllConnections?.()})}}}function Ia(e){return qe(ro(new URL(".",e)),"..","dist")}function Ta(e){const{summary:t}=e,s=[`COMPUTATIONAL ACTIVITY · ${Ma(e.window.from)}`,`${t.executions} executions across ${t.sessions} sessions`,`NOW ${t.runningNow} running · ${Q(t.waitingNow,String)} waiting · ${t.idleNow} idle`,`OUTCOMES ${Q(t.completed,String)} completed · ${Q(t.failed,String)} failed · ${Q(t.interrupted,String)} interrupted`,`ACTIVE INTERVAL ${Q(t.observedExecutionMs,Gs)}`,`PEAK CONCURRENCY ${Q(t.peakConcurrency,n=>`${n.peak}${n.at===null?"":` at ${Oa(n.at)}`}`)}`,`TOKENS ${Q(t.tokens,Ke)}`,`TOOLS ${Q(t.toolInteractions,Ke)} interactions · ${Q(t.toolErrors,Ke)} errors`,`EXPLICIT WAITS ${Q(t.waits,n=>`${n.count} / ${Gs(n.durationMs)}${n.openNow?` / ${n.openNow} open`:""}`)}`];return t.usageByModel.length>0&&s.push(`MODELS ${t.usageByModel.map(n=>`${n.model}: ${n.executions} executions, ${Q(n.tokens,Ke)}`).join(" · ")}`),t.executionsWithoutModel>0&&s.push(`MODEL COVERAGE ${t.executionsWithoutModel} executions without an observed model`),`${s.join(`
78
- `)}
79
- `}function $a(e){return[`tokens: ${e.tokens.state}`,`tool interactions: ${e.toolInteractions.state}`,`tool errors: ${e.toolErrors.state}`,`waits: ${e.waits.state}`]}function Q(e,t){return"value"in e&&e.value!==void 0?`${t(e.value)} (${e.state})`:e.state}function Ke(e){return e<1e3?String(Math.round(e)):e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)}k`:`${(e/1e6).toFixed(e<1e7?1:0)}m`}function Gs(e){const t=Math.round(e/6e4);return t<1?`${Math.round(e/1e3)}s`:t<60?`${t}m`:`${Math.floor(t/60)}h ${t%60}m`}function Ma(e){const t=new Date(e);return`${t.getFullYear()}-${zs(t.getMonth()+1)}-${zs(t.getDate())}`}function Oa(e){return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function zs(e){return String(e).padStart(2,"0")}const Ra=["today","running","waiting","failed","sessions","usage","concurrency"];function Na(e,t){switch(t){case"today":return Ta(e);case"running":return kt("RUNNING",e.executions.filter(s=>s.lifecycle.state==="running"));case"waiting":return kt("WAITING",e.executions.filter(s=>s.lifecycle.state==="waiting"));case"failed":return kt("FAILED",e.executions.filter(s=>zt(s.outcome)==="failed"));case"sessions":return`${["SESSIONS",...e.sessions.map(s=>`${s.ref} ${s.executionRefs.length} executions spawned by ${xt(s.spawnedBy)}`)].join(`
80
- `)}
81
- `;case"usage":return`${["USAGE",`tokens ${Le(e.summary.tokens)}`,`tool interactions ${Le(e.summary.toolInteractions)}`,`tool errors ${Le(e.summary.toolErrors)}`,...e.summary.usageByModel.map(n=>`${n.model} ${n.executions} executions ${Le(n.tokens)} tokens`),"COVERAGE",...$a(e.summary)].join(`
82
- `)}
83
- `;case"concurrency":{const s=e.summary.peakConcurrency;return`CONCURRENCY
84
- peak ${"value"in s&&s.value?`${s.value.peak}${s.value.at===null?"":` at ${new Date(s.value.at).toISOString()}`}`:s.state} (${s.state})
85
- active interval ${Le(e.summary.observedExecutionMs)} ms
86
- `}}}function kt(e,t){return t.length===0?`${e}
87
- none observed
88
- `:`${[e,...t.map(s=>`${s.ref} ${s.lifecycle.state} executor ${xt(s.executor)} model ${xt(s.model)} started ${new Date(s.start.at).toISOString()}`)].join(`
89
- `)}
90
- `}function zt(e){return"value"in e?e.value:void 0}function xt(e){const t=zt(e);return t===void 0?e.state:typeof t=="object"&&t!==null&&"ref"in t?`${String(t.ref)} (${e.state})`:`${String(t)} (${e.state})`}function Le(e){const t=zt(e);return t===void 0?e.state:`${Math.round(t).toLocaleString()} (${e.state})`}const Ks={tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"};function xa(e){const t=new Map;for(const r of e.declarations)r.kind==="began"&&t.set(`${r.subject.type}:${r.subject.id}`,r);const s=[...e.state.executions.values()].map(r=>_a(r,e,t)).sort((r,a)=>r.start.at-a.start.at||r.ref.localeCompare(a.ref)),n=new Set(s.map(r=>r.ref)),o=[...e.state.sessions.values()].map(r=>({ref:pe("session",r.id),executionRefs:r.executionIds.map(a=>pe("execution",a)).filter(a=>n.has(a)).sort(),spawnedBy:r.parentId?Z({ref:pe("session",r.parentId)}):Se("no parent session was reported")})).filter(r=>r.executionRefs.length>0).sort((r,a)=>r.ref.localeCompare(a.ref));return{experimental:!0,window:{from:e.from,to:e.to},executions:s,sessions:o,summary:Ua(s,o,e.from,e.to)}}function _a(e,t,s){const n=s.get(`execution:${e.id}`),o=n?.source.id,r=o?t.capabilities.get(o)??Ks:Ks,a=t.state.sessions.get(e.sessionId),i=t.state.machines.get(e.machineId),c=e.status==="completed"||e.status==="failed",u=ja(n?.occurredAt??e.startedAt,n?.basis??e.startBasis),h=t.relationships.filter(g=>g.kind==="ran-as"&&(g.from.type==="execution"&&g.from.id===e.id&&g.to.type==="process"||g.to.type==="execution"&&g.to.id===e.id&&g.from.type==="process")).map(g=>{const f=g.from.type==="process"?g.from:g.to;return{kind:"ran-as",target:{type:"process",ref:pe("process",f.id)},evidence:Ca(g.basis),...g.basis==="inferred"?{qualification:"resolved from overlapping identity claims"}:{}}}).sort((g,f)=>g.target.ref.localeCompare(f.target.ref)),m=a?.context,k=e.model??a?.model,b={current:e.status==="waiting",...e.waitReason?{reason:e.waitReason}:{},count:e.waits.length+(e.waitingSince===void 0?0:1),durationMs:e.waitingMs+(e.waitingSince===void 0?0:Math.max(0,t.to-e.waitingSince))};return{ref:pe("execution",e.id),sessionRef:pe("session",e.sessionId),machine:e.machineId?Z({ref:pe("machine",e.machineId),...i?{kind:i.kind}:{}}):Se("no machine was reported"),context:m?_t(r.context,{ref:pe("context",m)},"context"):et(r.context,"context"),executor:e.executor&&e.executor!=="unknown"?Z(e.executor):Se("no executor was reported"),model:k?_t(r.model,k,"model"):et(r.model,"model"),start:u,end:e.endedAt===void 0?re("the execution is not terminal in this window"):e.endBasis==="inferred"?Kt(e.endedAt,"the terminal bound was inferred by its observer"):Z(e.endedAt),lifecycle:Da(e),outcome:La(e,r.outcome),measures:{tokens:{input:le(e,M.tokensInput,r.tokens,c,!1,"token input"),output:le(e,M.tokensOutput,r.tokens,c,!1,"token output"),cacheRead:le(e,M.tokensCacheRead,r.tokens,c,!1,"cache-read tokens"),reasoning:le(e,M.tokensReasoning,r.tokens,c,!1,"reasoning tokens"),total:Hn(de(e.measures),r.tokens,c,!1,"token total")},requests:le(e,M.steps,r.requests,c,!0,"requests"),toolInteractions:le(e,M.interactions,r.toolInteractions,c,!0,"tool interactions"),toolErrors:le(e,M.errors,r.toolErrors,c,!0,"tool errors"),retries:le(e,M.retries,r.retries,c,!0,"retries")},wait:Fa(b,r.waits,c),failure:e.status==="failed"?Z("execution-failed"):c?r.outcome==="supported"?Z("none"):et(r.outcome,"failure state"):re("the execution is not terminal"),depth:e.depth,relationships:h}}function pe(e,t){const s=Zs("sha256").update(`057-activity\0${e}\0${t}`).digest("hex").slice(0,16);return`${e}_${s}`}function Ca(e){return e==="inferred"?"inferred":"observed"}function ja(e,t){return t==="inferred"?{at:e,evidence:"inferred",qualification:"the observer inferred this temporal bound"}:t===void 0?{at:e,evidence:"inferred",qualification:"a legacy record did not declare its timing basis"}:{at:e,evidence:"observed"}}function Da(e){return e.status==="waiting"?{state:"waiting",evidence:"observed"}:e.status==="running"?{state:"running",evidence:"observed"}:e.status==="idle"?{state:"idle",evidence:"inferred",qualification:"no activity was observed for the idle threshold"}:{state:"terminal",evidence:e.endBasis==="inferred"?"inferred":"observed",...e.endBasis==="inferred"?{qualification:"the observer inferred the terminal bound"}:{}}}function La(e,t){if(e.status!=="completed"&&e.status!=="failed")return re("the execution is not terminal");const s=e.outcome==="error"?"failed":e.outcome==="interrupted"?"interrupted":e.outcome==="completed"?"completed":void 0;return s?e.endBasis==="inferred"?Kt(s,"the terminal outcome follows an inferred terminal bound"):_t(t,s,"outcome"):et(t,"outcome")}function le(e,t,s,n,o,r){return Hn(ee(e.measures,t),s,n,o,r)}function Hn(e,t,s,n,o){return t==="unsupported"?Te(`this observer does not report ${o}`):t==="unknown"?re(`coverage for ${o} is not declared`):t==="partial"?Ae(e,`this observer reports ${o} only partially`):s?e!==void 0?Z(e):n?Z(0):Se(`${o} was not present in this execution`):Ae(e,`${o} may still increase while the execution is active`)}function Fa(e,t,s){return t==="unsupported"?Te("this observer does not report explicit waits"):t==="unknown"?re("wait coverage is not declared"):t==="partial"?Ae(e,"this observer reports explicit waits only partially"):!s||e.current?Ae(e,"an explicit wait may still be open"):Z(e)}function _t(e,t,s){return e==="supported"?Z(t):e==="partial"?Ae(t,`this observer reports ${s} only partially`):e==="unsupported"?Te(`this observer does not report ${s}`):re(`coverage for ${s} is not declared`)}function et(e,t){return e==="supported"?Se(`${t} was not present in this execution`):e==="partial"?Ae(void 0,`this observer reports ${t} only partially`):e==="unsupported"?Te(`this observer does not report ${t}`):re(`coverage for ${t} is not declared`)}function Z(e){return{state:"observed",value:e}}function Kt(e,t){return{state:"inferred",value:e,qualification:t}}function Ae(e,t){return e===void 0?{state:"partial",qualification:t}:{state:"partial",value:e,qualification:t}}function Te(e){return{state:"unsupported",qualification:e}}function Se(e){return{state:"not-observed",qualification:e}}function re(e){return{state:"unknown",qualification:e}}function Ua(e,t,s,n){const o=e.map(u=>({start:Math.max(s,u.start.at),end:Math.min(n,ke(u.end)??n),inferred:u.start.evidence==="inferred"||u.end.state==="inferred",partial:u.end.state!=="observed"&&u.end.state!=="inferred"})),r=pt(o.map(u=>u.partial?"partial":u.inferred?"inferred":"observed")),a=Wa(o),i=qa(o),c=e.filter(u=>u.lifecycle.state==="terminal");return{executions:e.length,sessions:t.length,runningNow:e.filter(u=>u.lifecycle.state==="running").length,waitingNow:xe(e.map(Pa)),idleNow:e.filter(u=>u.lifecycle.state==="idle").length,completed:Et(c,"completed"),failed:Et(c,"failed"),interrupted:Et(c,"interrupted"),observedExecutionMs:He(a,r),peakConcurrency:He(i,r),tokens:xe(e.map(u=>u.measures.tokens.total)),toolInteractions:xe(e.map(u=>u.measures.toolInteractions)),toolErrors:xe(e.map(u=>u.measures.toolErrors)),waits:Ba(e.map(u=>u.wait)),usageByModel:Ha(e),executionsWithoutModel:e.filter(u=>ke(u.model)===void 0).length}}function ke(e){return"value"in e?e.value:void 0}function pt(e){const t={records:e.length,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0};for(const s of e)s==="not-observed"?t.notObserved++:t[s]++;return t}function He(e,t){return t.partial+t.unsupported+t.notObserved+t.unknown>0?{state:"partial",value:e,qualification:"coverage is incomplete",coverage:t}:t.inferred>0?{state:"inferred",value:e,qualification:"one or more bounds were inferred",coverage:t}:{state:"observed",value:e,coverage:t}}function xe(e){const t=pt(e.map(o=>o.state));let s=0,n=0;for(const o of e){const r=ke(o);r!==void 0&&(s+=r,n++)}return n>0?He(s,t):t.records>0&&t.unsupported===t.records?{...Te("no observer supports this measure"),coverage:t}:t.records>0&&t.notObserved===t.records?{...Se("no value was observed"),coverage:t}:{...re("no usable value was observed"),coverage:t}}function Pa(e){const t=ke(e.wait);return Wn(e.wait,t?.current?1:0)}function Et(e,t){return e.length===0?He(0,pt([])):xe(e.map(s=>{const n=ke(s.outcome);return Wn(s.outcome,n===t?1:0)}))}function Wn(e,t){switch(e.state){case"observed":return Z(t);case"inferred":return Kt(t,e.qualification);case"partial":return Ae("value"in e?t:void 0,e.qualification);case"unsupported":return Te(e.qualification);case"not-observed":return Se(e.qualification);case"unknown":return re(e.qualification)}}function Ba(e){const t=pt(e.map(o=>o.state));let s=0;const n={count:0,durationMs:0,openNow:0};for(const o of e){const r=ke(o);r&&(s++,n.count+=r.count,n.durationMs+=r.durationMs,r.current&&n.openNow++)}return s>0?He(n,t):t.unsupported===t.records?{...Te("no observer reports explicit waits"),coverage:t}:{...re("no usable wait value was observed"),coverage:t}}function Ha(e){const t=new Map;for(const s of e){const n=ke(s.model);if(!n)continue;const o=t.get(n)??[];o.push(s.measures.tokens.total),t.set(n,o)}return[...t.entries()].map(([s,n])=>({model:s,executions:n.length,tokens:xe(n)})).sort((s,n)=>n.executions-s.executions||s.model.localeCompare(n.model))}function Wa(e){const t=e.filter(r=>r.end>r.start).map(r=>({start:r.start,end:r.end})).sort((r,a)=>r.start-a.start||r.end-a.end);let s=0,n,o=0;for(const r of t)n===void 0?(n=r.start,o=r.end):r.start<=o?o=Math.max(o,r.end):(s+=o-n,n=r.start,o=r.end);return s+(n===void 0?0:o-n)}function qa(e){const t=[];for(const r of e)r.end<=r.start||t.push({at:r.start,delta:1},{at:r.end,delta:-1});t.sort((r,a)=>r.at-a.at||r.delta-a.delta);let s=0,n=0,o=null;for(const r of t)s+=r.delta,s>n&&(n=s,o=r.at);return{peak:n,at:o}}const Xa=[[jt,So],[nt,Fo],[ye,Ko],[Fe,cr],[_e,vr],[Pe,$r]],Va=new Map(Xa);function Ya(e,t,s,n){const o=Pn(e,t,s,n);return xa({state:o.state,declarations:o.declarations,relationships:o.relationships,capabilities:Va,from:t,to:s})}const We="1.1.0";function Ga(e){const t={command:"serve",activityQuery:"today",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 if(n==="activity"){t.command="activity",s.shift();const o=s[0];if(o&&!o.startsWith("-")){if(!Ra.includes(o))return{...t,command:"help",error:`unknown activity query: ${o}`};t.activityQuery=o,s.shift()}}else return{...t,command:"help",error:`unknown command: ${n}`};for(;s.length;){const o=s.shift(),[r,a]=o.includes("=")?za(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 za(e,t){const s=e.indexOf(t);return[e.slice(0,s),e.slice(s+1)]}const Ka=`057 — a spatial interface for observing the shape of a computational workday
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
+ FROM events GROUP BY subject_type, subject_id`).all().map(j=>{const N=j;return{type:String(N.t),id:String(N.i),last:Number(N.last)}}),y=(j,N)=>`${j}:${N}`,M=new Set,l=new Map;for(const j of g){const N=A(j.type);N===null||j.last>=N?M.add(y(j.type,j.id)):l.set(y(j.type,j.id),{type:j.type,id:j.id})}if(l.size===0)return{...tt,processBefore:v,otherBefore:d};const S=[...fi],k=t.prepare(`SELECT DISTINCT core FROM events
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
+ (SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),$=t.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let O=0,U=0,X=0;t.exec("BEGIN");try{for(const{type:j,id:N}of l.values()){X+=Number(_.run(j,N).changes);const V=Number($.run(j,N).changes);ms.includes(j)?O+=V:U+=V}t.exec("COMMIT")}catch(j){throw t.exec("ROLLBACK"),j}return O+U>0&&w.checkpoint(),{processEvents:O,otherEvents:U,claims:X,subjects:l.size,retainedByDependents:C,processBefore:v,otherBefore:d}},checkpoint(){try{t.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes(){const[p,m,v]=ze(e).map(yi);return{db:p,wal:m,shm:v,total:p+m+v}},health(){const p=o.size;return p===0?{ok:!0,malformedRows:0,columns:[],since:null}:{ok:!1,malformedRows:p,columns:[...r].sort(),since:a,remedy:`${p} stored row(s) could not be read as JSON and lost their ${[...r].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(){t.exec("VACUUM"),w.checkpoint(),lt(e)},close(){w.checkpoint(),t.close()}};return w}function yi(e){try{return qe(e).size}catch{return 0}}function Pe(e,t,s){if(e!=null)try{const n=JSON.parse(String(e));if(n&&typeof n=="object")return n;t&&s?.(t);return}catch{t&&s?.(t);return}}function wi(e,t){const s=e,n=t?o=>t(o,String(s.id)):void 0;return{id:String(s.id),source:{id:String(s.source_id),instance:String(s.source_instance)},occurredAt:Number(s.occurred_at),observedAt:Number(s.observed_at),clock:s.clock,kind:s.kind,subject:{type:s.subject_type,id:String(s.subject_id)},core:Pe(s.core,"core",n),attrs:Pe(s.attrs,"attrs",n),basis:s.basis,assumption:s.assumption?String(s.assumption):void 0,stratum:s.stratum?s.stratum:void 0,provenance:Pe(s.provenance,"provenance",n)}}const Ai=Fn(Dn);function Si(){return $s()}function Ei(e){const t=[];for(const s of e.split(`
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
+ `);return}if(Is(s,b==="/"?"/index.html":b,E)||!b.startsWith("/assets/")&&Is(s,"/index.html",E))return;E.statusCode=404,E.setHeader("content-type","text/plain; charset=utf-8"),E.end(`not found
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
91
78
 
92
79
  057 observe this machine and serve the interface
93
80
  057 status where the store is, what it holds, what is observed
94
- 057 activity [query] private computational activity (experimental)
95
- queries: today, running, waiting, failed, sessions,
96
- usage, concurrency
97
81
  057 compact reclaim disk freed by retention (rewrites the store)
98
82
  057 reset delete the local store
99
83
 
100
84
  Options
101
- --port <n> port to serve on (default ${Gt}; the next free one if taken)
102
- --host <addr> address to bind (default ${me}; read the warning below first)
85
+ --port <n> port to serve on (default ${Mt}; the next free one if taken)
86
+ --host <addr> address to bind (default ${ce}; read the warning below first)
103
87
  --store <path> store file to use (same as O57_STORE)
104
88
  --open open the interface in the default browser — the running
105
89
  057's, if one (or 057.app) already observes the store
@@ -123,39 +107,39 @@ anywhere. Everything it learns is in one SQLite file you can read or delete.
123
107
 
124
108
  --host binds beyond the loopback interface and serves your telemetry, unauthenticated, to
125
109
  anything that can reach that address. Do not do it on a network you do not control.
126
- `;function fe(e){return process.stdout.isTTY?`\x1B[2m${e}\x1B[0m`:e}function Be(e){return e<1024?`${e} B`:e<1024**2?`${(e/1024).toFixed(1)} KB`:e<1024**3?`${(e/1024**2).toFixed(1)} MB`:`${(e/1024**3).toFixed(2)} GB`}function Ja(e,t,s,n){const o=["",` 057 ${We}`,` ${e}`,"",fe(" observing this machine only — its process table, and any AI runtime state it finds"),fe(` storing ${t}`),fe(` keeping ${s}`),fe(" sending nothing. no account, no cloud, no analytics."),fe(" resetting 057 reset")];return n!==me&&o.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),o.push(""),o.join(`
127
- `)}async function Qa(e){if(!process.stdin.isTTY)return!1;const t=Qn({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>t.question(`${e} [y/N] `,n))).trim().toLowerCase()==="y"}finally{t.close()}}async function Za(e,t){const s=Ga(e);if(s.command==="version")return console.log(We),0;if(s.command==="help")return s.error&&console.error(`057: ${s.error}
128
- `),(s.error?console.error:console.log)(Ka),s.error?2:0;s.store&&(process.env.O57_STORE=s.store);const n=ut(),o=Cn();if(s.command==="status")return sc(n,o);if(s.command==="activity")return ec(n,o,s.activityQuery);if(s.command==="compact")return nc(n);if(s.command==="reset")return oc(n,s.yes);if(s.desktop)return tc(t,n,o,s.port??0);const r=s.port??ic(process.env.O57_PORT)??Gt,a=s.host??process.env.O57_HOST??me;let i;try{i=await Bn({root:t,port:r,host:a,storePath:n,retention:o,log:ft(),version:We})}catch(h){if(h instanceof Xt){const m=h.record;return s.open?(console.log(`
129
- ${h.message}${m.owner==="desktop"?" — 057.app":""}.
130
- Opening ${m.url}
131
- `),await Js(m.url),0):(console.error(`
110
+ `;function ae(e){return process.stdout.isTTY?`\x1B[2m${e}\x1B[0m`:e}function Me(e){return e<1024?`${e} B`:e<1024**2?`${(e/1024).toFixed(1)} KB`:e<1024**3?`${(e/1024**2).toFixed(1)} MB`:`${(e/1024**3).toFixed(2)} GB`}function Ji(e,t,s,n){const o=["",` 057 ${$e}`,` ${e}`,"",ae(" observing this machine only — its process table, and any AI runtime state it finds"),ae(` storing ${t}`),ae(` keeping ${s}`),ae(" sending nothing. no account, no cloud, no analytics."),ae(" resetting 057 reset")];return n!==ce&&o.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),o.push(""),o.join(`
111
+ `)}async function Qi(e){if(!process.stdin.isTTY)return!1;const t=kn({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>t.question(`${e} [y/N] `,n))).trim().toLowerCase()==="y"}finally{t.close()}}async function Zi(e,t){const s=Vi(e);if(s.command==="version")return console.log($e),0;if(s.command==="help")return s.error&&console.error(`057: ${s.error}
112
+ `),(s.error?console.error:console.log)(Ki),s.error?2:0;s.store&&(process.env.O57_STORE=s.store);const n=Ve(),o=un();if(s.command==="status")return ta(n,o);if(s.command==="compact")return sa(n);if(s.command==="reset")return na(n,s.yes);if(s.desktop)return ea(t,n,o,s.port??0);const r=s.port??oa(process.env.O57_PORT)??Mt,a=s.host??process.env.O57_HOST??ce;let i;try{i=await hn({root:t,port:r,host:a,storePath:n,retention:o,log:Ke(),version:$e})}catch(h){if(h instanceof Et){const f=h.record;return s.open?(console.log(`
113
+ ${h.message}${f.owner==="desktop"?" — 057.app":""}.
114
+ Opening ${f.url}
115
+ `),await Ts(f.url),0):(console.error(`
132
116
  ${h.message}.
133
- Open ${m.url} (\`057 --open\`), or stop that 057 before starting another.
134
- `),1)}return mt(h)}console.log(Ja(i.url,n,ct(o),a)),s.open&&await Js(i.url);let c=!1;const u=()=>{c||(c=!0,console.log(`
117
+ Open ${f.url} (\`057 --open\`), or stop that 057 before starting another.
118
+ `),1)}return Ot(h)}console.log(Ji(i.url,n,Ye(o),a)),s.open&&await Ts(i.url);let c=!1;const u=()=>{c||(c=!0,console.log(`
135
119
  057 stopping — history is on disk
136
- `),i.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}function ec(e,t,s){let n;try{n=lt({path:e,retention:t,observe:!1,log:rc()})}catch(o){return mt(o)}try{const o=Date.now(),r=new Date(o);r.setHours(0,0,0,0);const a=Ya(n.store,r.getTime(),o,n.machine.id);return process.stdout.write(Na(a,s)),0}finally{n.stop()}}async function tc(e,t,s,n){const o=c=>{process.stdout.write(`${JSON.stringify(c)}
137
- `)};let r;try{r=await Bn({root:e,port:n,host:me,storePath:t,retention:s,log:ft(),version:We,owner:"desktop"})}catch(c){if(c instanceof Xt){const u=c.record;return o({event:"running",url:u.url,pid:u.pid,version:u.version,owner:u.owner,contract:u.contract}),0}return c instanceof ve?(o({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(o({event:"error",kind:"start",message:c instanceof Error?c.message:String(c)}),1)}let a=!1;const i=c=>{a||(a=!0,process.stderr.write(`[057] stopping (${c}) — history is on disk
138
- `),r.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),process.stdin.on("end",()=>i("app closed its pipe")),process.stdin.on("close",()=>i("app closed its pipe")),process.stdin.resume(),o({event:"ready",url:`http://${me}:${r.port}`,pid:process.pid,version:We,store:t,contract:Wt}),new Promise(()=>{})}function sc(e,t){let s;try{s=lt({path:e,retention:t,observe:!1,log:ft()})}catch(n){return mt(n)}try{const n=s.store.stats(),o=s.store.sizeBytes(),r=dt(e).map(i=>Vt(i)).filter(i=>i!==null).map(i=>"0"+i.toString(8)).join(" ");if(console.log(`
139
- store ${e}${jn()?" (from O57_STORE)":""}
120
+ `),i.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}async function ea(e,t,s,n){const o=c=>{process.stdout.write(`${JSON.stringify(c)}
121
+ `)};let r;try{r=await hn({root:e,port:n,host:ce,storePath:t,retention:s,log:Ke(),version:$e,owner:"desktop"})}catch(c){if(c instanceof Et){const u=c.record;return o({event:"running",url:u.url,pid:u.pid,version:u.version,owner:u.owner,contract:u.contract}),0}return c instanceof fe?(o({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(o({event:"error",kind:"start",message:c instanceof Error?c.message:String(c)}),1)}let a=!1;const i=c=>{a||(a=!0,process.stderr.write(`[057] stopping (${c}) — history is on disk
122
+ `),r.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),process.stdin.on("end",()=>i("app closed its pipe")),process.stdin.on("close",()=>i("app closed its pipe")),process.stdin.resume(),o({event:"ready",url:`http://${ce}:${r.port}`,pid:process.pid,version:$e,store:t,contract:At}),new Promise(()=>{})}function ta(e,t){let s;try{s=It({path:e,retention:t,observe:!1,log:Ke()})}catch(n){return Ot(n)}try{const n=s.store.stats(),o=s.store.sizeBytes(),r=ze(e).map(i=>kt(i)).filter(i=>i!==null).map(i=>"0"+i.toString(8)).join(" ");if(console.log(`
123
+ store ${e}${dn()?" (from O57_STORE)":""}
140
124
  schema ${s.store.schemaVersion}
141
- size ${Be(o.total)} ${fe(`(db ${Be(o.db)}, wal ${Be(o.wal)})`)}
125
+ size ${Me(o.total)} ${ae(`(db ${Me(o.db)}, wal ${Me(o.wal)})`)}
142
126
  events ${n.events.toLocaleString()}
143
127
  claims ${n.claims.toLocaleString()}
144
- keeping ${ct(t)}
128
+ keeping ${Ye(t)}
145
129
  permissions ${r||"none — no store yet"}
146
130
  `),n.bySource.length===0)console.log(` nothing has been captured yet
147
- `);else{for(const i of n.bySource){const c=`${new Date(i.first).toISOString().slice(0,10)} → ${new Date(i.last).toISOString().slice(0,10)}`;console.log(` ${i.source.padEnd(20)}${String(i.events).padStart(10)} events ${fe(c)}`)}console.log("")}const a=Ln();return a&&console.log(` a store from a previous layout is at ${a} and is not in use
148
- `),0}finally{s.stop()}}function nc(e){let t;try{t=lt({path:e,observe:!1,log:ft()})}catch(s){return mt(s)}try{const s=t.store.sizeBytes().total,n=t.sweep();t.store.compact();const o=t.store.sizeBytes().total;return console.log(`
131
+ `);else{for(const i of n.bySource){const c=`${new Date(i.first).toISOString().slice(0,10)} → ${new Date(i.last).toISOString().slice(0,10)}`;console.log(` ${i.source.padEnd(20)}${String(i.events).padStart(10)} events ${ae(c)}`)}console.log("")}const a=pn();return a&&console.log(` a store from a previous layout is at ${a} and is not in use
132
+ `),0}finally{s.stop()}}function sa(e){let t;try{t=It({path:e,observe:!1,log:Ke()})}catch(s){return Ot(s)}try{const s=t.store.sizeBytes().total,n=t.sweep();t.store.compact();const o=t.store.sizeBytes().total;return console.log(`
149
133
  removed ${n.processEvents+n.otherEvents} expired events
150
- ${Be(s)} → ${Be(o)}
151
- `),0}finally{t.stop()}}async function oc(e,t){const s=dt(e);console.log(`
134
+ ${Me(s)} → ${Me(o)}
135
+ `),0}finally{t.stop()}}async function na(e,t){const s=ze(e);console.log(`
152
136
  this deletes, permanently:
153
- `);for(const n of s)console.log(` ${n}`);if(console.log(""),!t&&!await Qa(" delete the local store?"))return console.log(` nothing was deleted
154
- `),1;for(const n of s)Qs(n,{force:!0});return console.log(` deleted. the next run starts a new store.
155
- `),0}function ft(){return{info:e=>{process.stderr.write(`${fe(e)}
137
+ `);for(const n of s)console.log(` ${n}`);if(console.log(""),!t&&!await Qi(" delete the local store?"))return console.log(` nothing was deleted
138
+ `),1;for(const n of s)Ms(n,{force:!0});return console.log(` deleted. the next run starts a new store.
139
+ `),0}function Ke(){return{info:e=>{process.stderr.write(`${ae(e)}
156
140
  `)},warn:e=>{process.stderr.write(`${e}
157
141
  `)},error:e=>{process.stderr.write(`${e}
158
- `)}}}function rc(){return{info:()=>{},warn:()=>{},error:()=>{}}}function mt(e){if(e instanceof ve)return console.error(`
142
+ `)}}}function Ot(e){if(e instanceof fe)return console.error(`
159
143
  057: ${e.message}
160
144
  ${e.remedy}
161
145
  `),1;const t=e?.code;return t==="EADDRINUSE"?(console.error(`
@@ -164,4 +148,4 @@ anything that can reach that address. Do not do it on a network you do not contr
164
148
  057: cannot bind that address or port (${t}).
165
149
  `),1):(console.error(`
166
150
  057: ${e instanceof Error?e.message:String(e)}
167
- `),1)}function ic(e){if(!e)return;const t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}async function Js(e){const t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:s}=await import("node:child_process");try{s(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function yc(e){const t=await Za(e,Ia(import.meta.url));t!==0&&process.exit(t)}export{Ia as defaultRoot,yc as main,Za as run};
151
+ `),1)}function oa(e){if(!e)return;const t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}async function Ts(e){const t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:s}=await import("node:child_process");try{s(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function ba(e){const t=await Zi(e,Yi(import.meta.url));t!==0&&process.exit(t)}export{Yi as defaultRoot,ba as main,Zi as run};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@probnaya/057-cli",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "A spatial interface for observing the shape of a computational workday. Local-first, accountless, offline.",
5
5
  "keywords": [
6
6
  "observability",