@probnaya/057-cli 0.1.2 → 1.0.0

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