@probnaya/057-cli 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -20
- package/dist-server/057.mjs +47 -45
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,16 +9,20 @@ A spatial interface for observing the shape of a computational workday.
|
|
|
9
9
|
|
|
10
10
|
**Infrastructure is permanent. Activity is temporary. The field remembers.**
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
One instrument, two ways in:
|
|
13
|
+
|
|
14
|
+
- **Download for macOS** — 057.app, at <https://057.probnaya.work/download/macos>. Apple silicon,
|
|
15
|
+
macOS 14 or later.
|
|
16
|
+
- **Install with npm** — the web / CLI surface:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npx @probnaya/057-cli
|
|
20
|
+
```
|
|
15
21
|
|
|
16
|
-
Then open the URL it prints.
|
|
22
|
+
Then open the URL it prints.
|
|
17
23
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
> and a WebGPU browser**, and nothing else honestly. The store format may change between 0.x
|
|
21
|
-
> releases. Read *Experimental limitations* before you rely on it.
|
|
24
|
+
Nothing else is needed — no account, no configuration, no network. Both run the same Core, read the
|
|
25
|
+
same store and mean the same things; 057 runs on **macOS only**, and honestly nothing else.
|
|
22
26
|
|
|
23
27
|
## What it is
|
|
24
28
|
|
|
@@ -38,6 +42,19 @@ anywhere, because token counts are reported and money mostly is not.
|
|
|
38
42
|
|
|
39
43
|
## Run it
|
|
40
44
|
|
|
45
|
+
### 057 for macOS
|
|
46
|
+
|
|
47
|
+
Download the disk image from <https://057.probnaya.work/download/macos>, drag 057 to Applications
|
|
48
|
+
and open it. The app carries its own Core — no Node, npm or terminal — and starts observing when it
|
|
49
|
+
opens. Closing the window leaves it observing from the menu bar; quitting the app stops it. It is
|
|
50
|
+
signed with Developer ID and notarized by Apple.
|
|
51
|
+
|
|
52
|
+
**Open in Browser** (the menu-bar menu, or View) opens the browser surface its Core serves. The
|
|
53
|
+
**057** menu has **Notifications**, off by default; on, 057 tells you only when its Core fails or a
|
|
54
|
+
source has failed for ten minutes.
|
|
55
|
+
|
|
56
|
+
### The web / CLI surface
|
|
57
|
+
|
|
41
58
|
```bash
|
|
42
59
|
npx @probnaya/057-cli
|
|
43
60
|
```
|
|
@@ -57,18 +74,22 @@ npm install -g @probnaya/057-cli
|
|
|
57
74
|
057 --help
|
|
58
75
|
```
|
|
59
76
|
|
|
60
|
-
|
|
61
|
-
and nothing is installed into your login items. If `5057` is busy it takes the next free
|
|
62
|
-
prints it.
|
|
77
|
+
The command runs in the foreground and stops when you stop it. There is no daemon, no background
|
|
78
|
+
service, and nothing is installed into your login items. If `5057` is busy it takes the next free
|
|
79
|
+
port and prints it.
|
|
80
|
+
|
|
81
|
+
One store has one observer. If 057.app is already running, `057` says so and names the URL its Core
|
|
82
|
+
serves, and `057 --open` opens it; the history is the same either way.
|
|
63
83
|
|
|
64
84
|
## Requirements
|
|
65
85
|
|
|
66
86
|
| | |
|
|
67
87
|
| --- | --- |
|
|
88
|
+
| **macOS app** | Apple silicon, macOS 14 or later. Nothing else to install. |
|
|
68
89
|
| **OS** | **macOS only.** The package declares `"os": ["darwin"]` and npm will refuse to install elsewhere — the process sampler reads a BSD process table and the Cursor reader looks in a macOS path. A 057 that silently mis-parsed your process table would be worse than one that will not start. |
|
|
69
90
|
| **Node** | 24.x. The package declares `>=22.5.0`, where the built-in SQLite the store needs first exists, but only 24 has been exercised. |
|
|
70
91
|
| **Browser** | A WebGPU browser: Chrome 113+, Edge 113+, or Safari 26+. Without WebGPU the interface says so plainly rather than falling back to something that is not FIELD. |
|
|
71
|
-
| **Network** | Only to download the package. Running 057 needs none. |
|
|
92
|
+
| **Network** | Only to download the app or the package. Running 057 needs none. |
|
|
72
93
|
|
|
73
94
|
## What it reads, and what it keeps
|
|
74
95
|
|
|
@@ -77,7 +98,7 @@ coding runtimes on your machine have already written for their own purposes. 057
|
|
|
77
98
|
processes, does not read process memory, and does not watch your keyboard, screen, network or
|
|
78
99
|
filesystem at large.
|
|
79
100
|
|
|
80
|
-
**Stored:**
|
|
101
|
+
**Stored:** the machine's name; working-directory and workspace paths; process and command
|
|
81
102
|
names; session and execution labels as the runtime recorded them; models, tools, token counts,
|
|
82
103
|
statuses and timings; and a timeline of when your machine was working.
|
|
83
104
|
|
|
@@ -152,13 +173,14 @@ how to delete it, and what it is licensed under. The full manual is at
|
|
|
152
173
|
| [Reading FIELD](https://057.probnaya.work/docs/field) | How to read the interface. |
|
|
153
174
|
| [Troubleshooting](https://057.probnaya.work/docs/troubleshooting) | Failure modes, and which ones are safe to act on. |
|
|
154
175
|
|
|
155
|
-
##
|
|
176
|
+
## Limitations
|
|
156
177
|
|
|
157
|
-
Stated plainly
|
|
178
|
+
Stated plainly.
|
|
158
179
|
|
|
159
|
-
- **macOS only
|
|
160
|
-
|
|
161
|
-
|
|
180
|
+
- **macOS only.** The browser surface needs WebGPU; the app needs Apple silicon. Neither is a
|
|
181
|
+
"coming soon"; both are refusals to pretend.
|
|
182
|
+
- **The store format is versioned** and upgrades in place, and a store from a newer 057 is refused
|
|
183
|
+
rather than downgraded.
|
|
162
184
|
- **Exits are inferred.** The process sampler is a five-second snapshot, not a kernel hook: it
|
|
163
185
|
cannot see an exit, only stop seeing a process, and everything derived from that says so. A
|
|
164
186
|
process that starts and exits within one interval is never observed at all.
|
|
@@ -180,7 +202,7 @@ by design, because adding accounts to a local instrument would be adding the exa
|
|
|
180
202
|
product does not have.
|
|
181
203
|
|
|
182
204
|
**Do not put 057 behind a reverse proxy, and do not set `O57_HOST` on a network you do not control.**
|
|
183
|
-
Either publishes an unauthenticated read of your
|
|
205
|
+
Either publishes an unauthenticated read of your machine's name, your project paths, your session labels,
|
|
184
206
|
your models and a record of when you were at your machine, to anything that can reach that address.
|
|
185
207
|
057 warns you at startup if you do it. There is no auth to turn on.
|
|
186
208
|
|
|
@@ -189,7 +211,7 @@ metadata rather than opening it publicly.
|
|
|
189
211
|
|
|
190
212
|
## Licence
|
|
191
213
|
|
|
192
|
-
057 is publicly installable, but
|
|
214
|
+
057 is publicly installable, but it is not an open-source release. It is distributed under the
|
|
193
215
|
PolyForm Internal Use License 1.0.0: personal use and internal business or workplace use are
|
|
194
216
|
permitted, redistribution is not, and private modifications for permitted purposes remain governed
|
|
195
217
|
by the licence. See `LICENSE.md` for the terms. Third-party components retain their own licences as
|
package/dist-server/057.mjs
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import{existsSync as
|
|
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
|
|
3
|
-
`))if(s.trim())try{const n=JSON.parse(s);n&&typeof n.type=="string"&&t.push(n)}catch{}return t}const
|
|
4
|
-
`))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function
|
|
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
|
-
|
|
1
|
+
import{existsSync as L,writeFileSync as vn,renameSync as yn,rmSync as Ms,readFileSync as wn,statSync as qe,mkdirSync as An,chmodSync as Sn,createReadStream as En}from"node:fs";import{createInterface as kn}from"node:readline";import{createServer as In}from"node:http";import{join as D,isAbsolute as Tn,resolve as Re,dirname as Mn,normalize as On,sep as $n,extname as Rn}from"node:path";import{fileURLToPath as xn}from"node:url";import{stat as me,readdir as W,readFile as ie}from"node:fs/promises";import{hostname as Nn,homedir as he}from"node:os";import _n from"node:zlib";import{createHash as Cn}from"node:crypto";import{execFileSync as jn,execFile as Dn}from"node:child_process";import{DatabaseSync as ft}from"node:sqlite";import{promisify as Fn}from"node:util";const Nt=["machine","session","execution","process","artifact"];function Ln(e){return`${e.ns}|${e.parts.join("|")}`}const R={interactions:"interactions",steps:"steps",errors:"errors",retries:"retries",cpuMs:"cpu.ms",tokensInput:"tokens.input",tokensOutput:"tokens.output",tokensCacheRead:"tokens.cacheRead",tokensReasoning:"tokens.reasoning"},Un=[{a:"execution",b:"process",kind:"ran-as"},{a:"session",b:"process",kind:"ran-as"},{a:"execution",b:"session",kind:"ran-as"},{a:"session",b:"session",kind:"same-as"},{a:"execution",b:"execution",kind:"same-as"},{a:"machine",b:"machine",kind:"same-as"},{a:"process",b:"process",kind:"same-as"}];function _t(e,t){for(const s of Un){if(e.subjectType===s.a&&t.subjectType===s.b)return{kind:s.kind,from:e,to:t};if(t.subjectType===s.a&&e.subjectType===s.b)return{kind:s.kind,from:t,to:e}}return null}const Pn=(e,t)=>e.validFrom<=t.validTo&&t.validFrom<=e.validTo;function Bn(e,t){const s=Math.max(e.validFrom,t.validFrom),n=Math.min(e.validTo,t.validTo);if(n<s)return 0;const o=Math.max(e.validTo,t.validTo)-Math.min(e.validFrom,t.validFrom);return o<=0?1:(n-s)/o}const Hn=.5;function Wn(e,t){return Pn(e,t)?Bn(e,t)>=Hn?2:1:0}const J=e=>`${e.subjectType}:${e.subjectId}`,Xn="inferred",Gn="Two observers asserted the same identity claim over overlapping validity windows, and each was the other's only candidate at the strongest available evidence tier (two lifetimes that substantially coincide beat a bare overlap). The claims themselves are measured; the identification is inferred.";function qn(e){const t=new Map;for(const r of e){const a=t.get(r.key);a?a.push(r):t.set(r.key,[r])}const s=[],n=[];let o=0;for(const[r,a]of[...t.entries()].sort(([i],[c])=>i<c?-1:1)){const i=new Map;for(const b of a){const w=J(b),p=i.get(w);if(!p){i.set(w,{...b});continue}p.validFrom=Math.min(p.validFrom,b.validFrom),p.validTo=Math.max(p.validTo,b.validTo)}const c=[...i.values()].sort((b,w)=>J(b)<J(w)?-1:1);if(c.length<2){o++;continue}const u=[];let h=!1;for(let b=0;b<c.length;b++)for(let w=b+1;w<c.length;w++){const p=c[b],m=c[w];if(p.sourceId===m.sourceId)continue;const v=Wn(p,m);if(v!==0){if(!_t(p,m)){h=!0;continue}u.push({x:p,y:m,tier:v})}}const f=new Map;for(const b of u)for(const w of[b.x,b.y]){const p=J(w);f.set(p,Math.max(f.get(p)??0,b.tier))}const E=new Map;for(const b of u)for(const w of[b.x,b.y]){const p=J(w);f.get(p)===b.tier&&E.set(p,(E.get(p)??0)+1)}if(u.length===0){n.push({key:r,reason:h?"no-pairing-defined":"no-window-overlap",subjects:[...i.keys()].sort()});continue}for(const{x:b,y:w,tier:p}of u){if(f.get(J(b))!==p||f.get(J(w))!==p)continue;if(E.get(J(b))!==1||E.get(J(w))!==1){n.push({key:r,reason:"multiple-candidates",subjects:[J(b),J(w)].sort()});continue}const m=_t(b,w);s.push({from:{type:m.from.subjectType,id:m.from.subjectId},to:{type:m.to.subjectType,id:m.to.subjectId},kind:m.kind,basis:Xn,assumption:Gn,via:r})}}return{relationships:s,ambiguous:n,unmatched:o,considered:t.size}}async function Yn(e,t,s,n,o){const r=[];let a=0,i=0;for(const c of t){const u=Date.now();try{const h=await c.collect(s,n),f=e.append(h);a+=f.inserted,i+=f.duplicate,r.push({id:c.id,ok:!0,collected:h.length,inserted:f.inserted,duplicate:f.duplicate,ms:Date.now()-u})}catch(h){r.push({id:c.id,ok:!1,collected:0,inserted:0,duplicate:0,error:h instanceof Error?h.message:String(h),ms:Date.now()-u})}o?.(r[r.length-1])}return{sources:r,inserted:a,duplicate:i}}function Vn(e,t,s){return qn(e.claims(t,s))}const Os="deepseek-harness",P=e=>typeof e=="number"&&Number.isFinite(e)?e:0,q=e=>typeof e=="string"?e:void 0;function zn(e){const t=e.split("/").filter(Boolean);return(t[t.length-1]??e).toUpperCase()}function Kn(e,t){const s=[],n=e[0];if(!n||n.type!=="session"||!n.id)return s;const o=n.id,r=n.cwd??"",a=P(n.createdAt),i=P(n.delegationDepth),c=zn(r);let u="deepseek",h,f;for(const y of e)if(y.type==="request/context"&&y.data?(u=q(y.data.provider)??u,h=q(y.data.model)??h):y.type==="session/title"&&y.data&&(f=q(y.data.title)??f),h&&f)break;const b={source:{id:Os,instance:t.instance},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let w=a;for(const y of e){const M=P(y.time);M>w&&(w=M)}const p={ns:"fs.cwd",parts:[t.host,r],validFrom:a,validTo:Math.max(a,w)};s.push({...b,occurredAt:a,seq:"session",kind:"began",subject:{type:"session",id:o},claims:r?[p]:void 0,core:{machineId:t.machine.id,label:f,executor:u,model:h,depth:i},attrs:{context:r,"dsh.delegationDepth":i}});const m=y=>`${o}:turn:${y}`;let v=null;const d=new Map,A=new Map;let g=a;for(const y of e){const M=P(y.time)||g;if(M<a)continue;g=M;const l=y.data??{},S=y.seq??`t${M}`,k=T=>({type:"execution",id:m(T)});switch(y.type){case"turn/start":{const T=P(l.turn);v=T,s.push({...b,occurredAt:M,seq:S,kind:"began",subject:k(T),core:{machineId:t.machine.id,sessionId:o,label:f?`${c} · ${f}`:c,executor:u,model:h,depth:i},attrs:{"dsh.turn":T}});break}case"turn/end":{const T=P(l.turn),I=l.reason,x=I?.kind;if(x==="error"){const C=I?.error??{};s.push({...b,occurredAt:M,seq:S,kind:"ended",subject:k(T),core:{outcome:"error",failureCode:q(C.code)??"ERROR",failureMessage:q(C.message)??"Run failed"},attrs:{"dsh.endReason":x}})}else s.push({...b,occurredAt:M,seq:S,kind:"ended",subject:k(T),core:{outcome:x==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":x??"completed"}});v===T&&(v=null);break}case"assistant/message":{const T=P(l.turn),I=l.usage;if(!I)break;const x={[R.tokensInput]:P(I.inputTokens),[R.tokensOutput]:P(I.outputTokens),[R.tokensCacheRead]:P(I.cacheReadTokens),[R.tokensReasoning]:P(I.reasoningTokens),[R.steps]:1};s.push({...b,occurredAt:M,seq:S,kind:"progressed",subject:k(T),core:{measures:x},attrs:{"dsh.inputTokens":P(I.inputTokens),"dsh.outputTokens":P(I.outputTokens),"dsh.cacheReadTokens":P(I.cacheReadTokens),"dsh.reasoningTokens":P(I.reasoningTokens)}});break}case"tool/call":{s.push({...b,occurredAt:M,seq:S,kind:"progressed",subject:k(P(l.turn)),core:{measures:{[R.interactions]:1}},attrs:{"dsh.tool":q(l.name)}});break}case"tool/result":{const T=l.message;let I=!1;for(const x of T?.content??[])x.isError===!0&&(I=!0);I&&s.push({...b,occurredAt:M,seq:S,kind:"progressed",subject:k(P(l.turn)),core:{measures:{[R.errors]:1}}});break}case"llm/retry":{s.push({...b,occurredAt:M,seq:S,kind:"progressed",subject:k(P(l.turn)),core:{measures:{[R.retries]:1}}});break}case"approval/asked":{const T=q(l.id);if(v===null)break;T&&d.set(T,v),s.push({...b,occurredAt:M,seq:S,kind:"blocked",subject:k(v),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":T}});break}case"approval/decided":{const T=q(l.id),I=T?d.get(T):v;if(I==null)break;d.delete(T??""),s.push({...b,occurredAt:M,seq:S,kind:"resumed",subject:k(I),attrs:{"dsh.approvalId":T}});break}case"tool-workflow/agent-start":{if(v===null)break;const T=q(l.childId);if(!T)break;const I=`${o}:agent:${T}`;A.set(`${q(l.runId)}:${P(l.seq)}`,I),s.push({...b,occurredAt:M,seq:S,kind:"began",subject:{type:"execution",id:I},core:{machineId:t.machine.id,sessionId:o,label:q(l.label)??`${c} · SUB`,executor:u,model:h,parentId:m(v),depth:i+1},attrs:{"dsh.childId":T}});break}case"tool-workflow/agent-end":{const T=`${q(l.runId)}:${P(l.seq)}`,I=A.get(T);if(!I)break;A.delete(T);const x=q(l.outcome);s.push({...b,occurredAt:M,seq:S,kind:"ended",subject:{type:"execution",id:I},core:x==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:x??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":x}});break}}}if(t.closeOpenTurns){const y="The session log has not been written to for longer than the live window, so the process that owned it is gone and any turn left open was cut off rather than still running.";v!==null&&s.push({...b,occurredAt:g,seq:"close:turn",kind:"ended",subject:{type:"execution",id:m(v)},core:{outcome:"interrupted"},basis:"inferred",assumption:y});for(const M of A.values())s.push({...b,occurredAt:g,seq:`close:${M}`,kind:"ended",subject:{type:"execution",id:M},core:{outcome:"interrupted"},basis:"inferred",assumption:y});s.push({...b,occurredAt:g,seq:"close:session",kind:"ended",subject:{type:"session",id:o},basis:"inferred",assumption:y})}return t.since!==void 0?s.filter(y=>y.occurredAt>=t.since):s}function Jn(e){const t=[];let s=0;for(;s<e.length;){let n=e.indexOf(`
|
|
2
|
+
`,s);n===-1&&(n=e.length);const o=e.slice(s,n);if(s=n+1,o.length!==0&&!(o.startsWith('{"type":"reasoning-chunks"')||o.startsWith('{"type":"text-chunks"')||o.startsWith('{"type":"tool-call-chunks"')||o.startsWith('{"type":"assistant/chunk"')))try{t.push(JSON.parse(o))}catch{}}return t}function Qn(e){const t=JSON.stringify([e.source.id,e.source.instance,e.occurredAt,e.clock,e.kind,e.subject.type,e.subject.id,e.basis,e.seq??null,Be(e.core),Be(e.attrs)]);return Cn("sha256").update(t).digest("hex").slice(0,32)}function Be(e){if(e==null)return null;if(Array.isArray(e))return e.map(Be);if(typeof e!="object")return e;const t={};for(const s of Object.keys(e).sort())t[s]=Be(e[s]);return t}function se(e){const{seq:t,...s}=e;return{id:Qn(e),...s}}let Ct;function Zn(){try{const e=jn("/usr/sbin/scutil",["--get","LocalHostName"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();return/^[A-Za-z0-9-]{1,63}$/.test(e)?e:void 0}catch{return}}function $s(){return Ct??=Zn()??Nn().replace(/\.local$/i,""),Ct}const He="host:";function eo(e){return`${He}${e}`}function to(e){return e.startsWith(He)?e.slice(He.length):void 0}function jt(e){return e.startsWith(He)}const so=4247762216,no=407710288,oo=407710303;function ro(e){const t=[];for(let o=0;o+4<=e.length;o++){const r=e.readUInt32LE(o);(r===so||r>=no&&r<=oo)&&t.push(o)}if(t.length===0)return Buffer.alloc(0);const s=[];let n=0;for(;n<t.length;){let o=n+1,r=null;for(;;){const a=o<t.length?t[o]:e.length;try{r=_n.zstdDecompressSync(e.subarray(t[n],a));break}catch{if(o>=t.length)break;o++}}r?(s.push(r),n=o):n++}return Buffer.concat(s)}function mt(){return process.env.DSH_HOME||D(he(),".dsh")}function de(){return $s()}function ge(){const e=de();return{id:eo(e),name:e.toUpperCase(),kind:"laptop",firstSeenAt:0}}const Dt=new Map;async function Rs(){const e=D(mt(),"sessions");if(!L(e))return[];const t=[];for(const s of await W(e)){const n=D(e,s);let o;try{o=await W(n)}catch{continue}for(const r of o){const a=D(n,r,"session.jsonl.zstd");L(a)&&t.push({path:a,workspace:s,sessionId:r})}}return t}const ht=10*6e4;async function io(e,t){const s=await me(e.path),n=Dt.get(e.path);if(n&&n.mtimeMs===s.mtimeMs&&n.size===s.size)return n.envelopes;const o=await ie(e.path),r=ro(o).toString("utf8"),a=Jn(r),i=Date.now()-s.mtimeMs>ht,u=Kn(a,{machine:t,host:de(),instance:mt(),observedAt:Date.now(),closeOpenTurns:i}).map(se);return Dt.set(e.path,{mtimeMs:s.mtimeMs,size:s.size,envelopes:u}),u}async function ao(e,t){const s=ge(),n=await Rs(),o=[];for(const r of n){let a;try{a=await me(r.path)}catch{continue}if(!(a.mtimeMs<e))for(const i of await io(r,s))i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function Ft(){const e=await Rs(),t=mt();return{available:e.length>0,present:L(t),home:t,sessions:e.length}}const xs=1e3,Lt=60*xs;function H(e){if(!Number.isFinite(e)||e<=0)return"0m";if(e<Lt)return`${Math.max(1,Math.round(e/xs))}s`;const t=Math.round(e/Lt),s=Math.floor(t/60),n=t%60;return s===0?`${n}m`:n===0?`${s}h`:`${s}h ${n}m`}function G(e){if(!Number.isFinite(e))return"—";const t=Math.abs(e);return t>=1e9?`${(e/1e9).toFixed(t>=1e10?0:2)}B`:t>=1e6?`${(e/1e6).toFixed(t>=1e7?0:2)}M`:t>=1e3?`${(e/1e3).toFixed(t>=1e4?0:1)}k`:String(Math.round(e))}function co(e,t="NOT OBSERVED"){return e===void 0?t:G(e)}function uo(e){return e===void 0||!Number.isFinite(e)?"—":e>=1e9?`${(e/1e9).toFixed(1)} GB`:e>=1e6?`${(e/1e6).toFixed(0)} MB`:e>=1e3?`${(e/1e3).toFixed(0)} KB`:`${e} B`}function xe(e){const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function Q(e){const t=e.split("/").filter(Boolean);return t[t.length-1]??e}const rt="0x2f",ne=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0},Ns=(e,t)=>`2f:${e}#${t}`,lo=(e,t,s)=>`${Ns(e,t)}:run:${s}`;function Ut(e){return e?.type==="permission"?"approval":"input"}function po(e){const t=new Map;for(const s of e){const n=typeof s.run=="number"?s.run:1,o=t.get(n);o?o.push(s):t.set(n,[s])}return t}function fo(e,t){const s=t.find(r=>r.type==="run.started");let n;for(let r=t.length-1;r>=0;r--){const a=t[r];if(a.type==="run.completed"||a.type==="run.failed"||a.type==="needs_user"&&a.blockedOn){n=a;break}}let o;return n?.type==="run.completed"?o="ready":n?.type==="run.failed"?o="failed":n?o="needs_you":e.status==="needs_you"||e.status==="ready"||e.status==="failed"?o=e.status:e.status==="working"?o="working":o=e.error?"failed":"ready",{run:1,provider:e.execution?.provider??null,node:e.execution?.node??null,model:e.execution?.model,externalSessionId:e.execution?.externalSessionId,attempts:e.execution?.attempts??1,startedAt:s?.at,completedAt:n?.at,outcome:o,error:e.error??(n?.type==="run.failed"?n.error:void 0),blockedOn:n?.type==="needs_user"?n.blockedOn:void 0,failure:e.failure}}function mo(e,t){return Array.isArray(e.runs)&&e.runs.length?e.runs:[fo(e,t)]}function ho(e,t,s){if(typeof e.id!="number")return[];const n=Ns(s.base,e.id),o=mo(e,t),r=Q(s.base).toUpperCase(),a=e.title,i=e.execution?.provider??o.at(-1)?.provider??rt,c=ne(e.createdAt)??o.map(m=>ne(m.startedAt)).find(m=>m!==void 0);if(c===void 0)return[];const h={source:{id:rt,instance:s.base},observedAt:s.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},f=[{...h,occurredAt:c,kind:"began",subject:{type:"session",id:n},core:{machineId:s.machine.id,label:a,executor:i,model:e.execution?.model},attrs:{context:s.base,"0x2f.taskId":e.id,"0x2f.status":e.status}}],E=po(t),b=t.filter(m=>m.type==="task.answered"),w=t.find(m=>m.type==="task.closed"),p=o.at(-1);for(let m=0;m<o.length;m++){const v=o[m],d=ne(v.startedAt);if(d===void 0)continue;const A=lo(s.base,e.id,v.run),g=v.provider??i,y=ne(v.completedAt),M=y??s.now,l=[{ns:"fs.cwd",parts:[s.host,s.base],validFrom:d,validTo:M}];typeof v.externalSessionId=="string"&&v.externalSessionId&&l.push({ns:"agent.session",parts:[g,v.externalSessionId],validFrom:d,validTo:M}),v===p&&typeof e.pid=="number"&&l.push({ns:"os.process",parts:[s.host,e.pid],validFrom:d,validTo:M}),f.push({...h,occurredAt:d,seq:`run:${v.run}`,kind:"began",subject:{type:"execution",id:A},claims:l,core:{machineId:s.machine.id,sessionId:n,label:a?`${r} · ${a} · RUN ${v.run}`:`${r} · RUN ${v.run}`,executor:g,model:v.model??e.execution?.model,depth:0},attrs:{"0x2f.run":v.run,"0x2f.provider":g,"0x2f.workspace":s.base,...v.requestedProvider?{"0x2f.requestedProvider":v.requestedProvider}:{},...e.pid!==void 0&&v===p?{"0x2f.workerPid":e.pid}:{}}});let S=!1,k=0;for(const I of E.get(v.run)??[]){k++;const x=ne(I.at);if(x===void 0||x<d)continue;const C=`run:${v.run}:${k}`;if(I.type==="tool.started")f.push({...h,occurredAt:x,seq:C,kind:"progressed",subject:{type:"execution",id:A},core:{measures:{[R.interactions]:1}},attrs:{"0x2f.tool":I.name}});else if(I.type==="progress")f.push({...h,occurredAt:x,seq:C,kind:"progressed",subject:{type:"execution",id:A}});else if(I.type==="needs_user"&&I.blockedOn){if(S)continue;S=!0,f.push({...h,occurredAt:x,seq:C,kind:"blocked",subject:{type:"execution",id:A},core:{blockedOn:Ut(I.blockedOn)},attrs:{"0x2f.blockedOn":I.blockedOn.type}})}else if(I.type==="permission.resolved"||I.type==="task.updated"&&typeof I.grant=="string"){if(!S)continue;S=!1,f.push({...h,occurredAt:x,seq:C,kind:"resumed",subject:{type:"execution",id:A},attrs:{"0x2f.grant":I.grant}})}}const T=(I,x,C)=>f.push({...h,occurredAt:I,seq:C,kind:"ended",subject:{type:"execution",id:A},core:x});if(v.outcome==="ready"&&y!==void 0)T(y,{outcome:"completed"},`run:${v.run}:end`);else if(v.outcome==="failed"&&y!==void 0)T(y,{outcome:"error",failureCode:(v.failure?.kind??e.failure?.kind??"unclassified").toUpperCase(),failureMessage:v.error??e.error??"Run failed"},`run:${v.run}:end`);else if(v.outcome==="needs_you"&&y!==void 0){S||(S=!0,f.push({...h,occurredAt:y,seq:`run:${v.run}:block`,kind:"blocked",subject:{type:"execution",id:A},core:{blockedOn:Ut(v.blockedOn)}}));const I=go(y,b,o[m+1],w);I!==void 0&&T(I,{outcome:"interrupted"},`run:${v.run}:end`)}}if(w){const m=ne(w.at);m!==void 0&&f.push({...h,occurredAt:m,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return f}function go(e,t,s,n){const o=[...t.map(a=>ne(a.at)),ne(s?.startedAt),ne(n?.at)];let r;for(const a of o)a===void 0||a<e||(r===void 0||a<r)&&(r=a);return r}function bo(e){const t=[];for(const s of e.split(`
|
|
3
|
+
`))if(s.trim())try{const n=JSON.parse(s);n&&typeof n.type=="string"&&t.push(n)}catch{}return t}const _s=".work";function Cs(){const e=process.env.WORK_ROOTS;return e?e.split(/[:,]/).map(t=>t.trim()).filter(Boolean):[he()]}const Pt=e=>L(D(e,_s,"tasks")),vo=new Set(["Desktop","Documents","Downloads"]);async function js(){const e=new Set,t=!process.env.WORK_ROOTS;for(const s of Cs()){if(Pt(s)){e.add(s);continue}let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory()||o.name.startsWith(".")||t&&vo.has(o.name))continue;const r=D(s,o.name);Pt(r)&&e.add(r)}}return[...e].sort()}async function yo(){const e=[];for(const t of await js()){const s=D(t,_s,"tasks");let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory())continue;const r=D(s,o.name,"task.json");L(r)&&e.push({base:t,slug:o.name,taskPath:r,eventsPath:D(s,o.name,"events.jsonl")})}}return e}const Bt=new Map;async function wo(e,t,s){let n;try{n=await me(e.taskPath)}catch{return null}const o=await me(e.eventsPath).catch(()=>null),r=Math.max(n.mtimeMs,o?.mtimeMs??0),a=`${n.mtimeMs}:${n.size}:${o?.mtimeMs??0}:${o?.size??0}`,i=Bt.get(e.taskPath);if(i&&i.stamp===a)return{envelopes:i.envelopes,touchedAt:r};let c;try{c=JSON.parse(await ie(e.taskPath,"utf8"))}catch{return null}let u=[];try{u=bo(await ie(e.eventsPath,"utf8"))}catch{}const h=ho(c,u,{machine:t,base:e.base,host:de(),observedAt:Date.now(),now:s}).map(se);return Bt.set(e.taskPath,{stamp:a,envelopes:h}),{envelopes:h,touchedAt:r}}async function Ao(e,t){const s=ge(),n=await yo(),o=[];for(const r of n){const a=await wo(r,s,t);if(a&&!(a.touchedAt<e))for(const i of a.envelopes)i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function Ht(){const e=Cs(),t=await js();return{available:t.length>0,present:e.some(s=>L(s)),roots:e,workspaces:t}}const Se="claude-code",Ds="claude-code";class re extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const Fs=e=>`claude:${e}`;function So(e,t){const s=e,n=typeof s?.version=="string"?s.version:void 0;if(!s||typeof s!="object")throw new re("registry entry is not an object",t,n);if(typeof s.sessionId!="string"||!s.sessionId)throw new re("registry entry has no sessionId",t,n);if(typeof s.pid!="number"||!Number.isFinite(s.pid))throw new re("registry entry has no numeric pid",t,n);if(typeof s.startedAt!="number"||!Number.isFinite(s.startedAt))throw new re("registry entry has no numeric startedAt",t,n);return s}function Eo(e,t,s){const n=[{ns:"agent.session",parts:[Ds,e.sessionId],validFrom:e.startedAt,validTo:s.now},{ns:"os.process",parts:[s.host,e.pid],validFrom:e.startedAt,validTo:s.now}];return{source:{id:Se,instance:s.host},occurredAt:e.startedAt,observedAt:s.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:Fs(e.sessionId)},claims:n,basis:"measured",core:{machineId:s.machine.id,label:e.name??Q(e.cwd??"").toUpperCase(),executor:Se},attrs:{context:e.cwd,"claude.sessionId":e.sessionId,"claude.pid":e.pid,"claude.procStart":e.procStart,"claude.version":e.version,"claude.kind":e.kind,"claude.entrypoint":e.entrypoint,"claude.status":e.status,"claude.waitingFor":e.waitingFor},provenance:{path:t,recordId:e.sessionId,sourceVersion:e.version},seq:"registry"}}const ko=new Set(["stop_hook_summary","turn_duration"]),Io="The transcript has not been written to for longer than the live window, so the process that owned it is gone and the turn ended at its last record.",oe=e=>typeof e=="number"&&Number.isFinite(e)?e:0,ve=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function To(e){const t=[];for(const s of e.split(`
|
|
4
|
+
`))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function Mo(e){if(!e)return{};const t=e.output_tokens_details;return{[R.tokensInput]:oe(e.input_tokens)+oe(e.cache_creation_input_tokens),[R.tokensOutput]:oe(e.output_tokens),[R.tokensCacheRead]:oe(e.cache_read_input_tokens),[R.tokensReasoning]:oe(t?.thinking_tokens),[R.steps]:1}}function Oo(e,t){const s=e.filter(d=>ve(d.timestamp)!==void 0);if(s.length===0)throw new re("transcript has no timestamped records",t.path);const n=e.find(d=>typeof d.sessionId=="string")?.sessionId;if(n&&n!==t.sessionId)throw new re(`transcript names session ${n} but is filed under ${t.sessionId}`,t.path);const o=e.find(d=>typeof d.version=="string")?.version,r=e.find(d=>typeof d.cwd=="string")?.cwd??"",a=e.find(d=>typeof d.gitBranch=="string")?.gitBranch,i=e.find(d=>typeof d.entrypoint=="string")?.entrypoint,c=Q(r).toUpperCase(),u=t.sessionId,h=Fs(u),f=ve(s[0].timestamp),E=ve(s[s.length-1].timestamp),w={source:{id:Se,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},p=(d,A)=>({path:t.path,...d?{recordId:d}:{},...A!==void 0?{index:A}:{},...o?{sourceVersion:o}:{}}),m=[{...w,occurredAt:f,kind:"began",subject:{type:"session",id:h},claims:[{ns:"agent.session",parts:[Ds,u],validFrom:f,validTo:E}],core:{machineId:t.machine.id,label:c,executor:Se},attrs:{context:r,"claude.sessionId":u,"claude.gitBranch":a,"claude.entrypoint":i,"claude.version":o},provenance:p(u),seq:"session"}],v=[];for(let d=0;d<e.length;d++){const A=e[d];A.type==="user"&&typeof A.promptSource=="string"&&ve(A.timestamp)!==void 0&&v.push(d)}if(v.length===0)throw new re(`transcript has ${e.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,t.path,o);for(let d=0;d<v.length;d++){const A=v[d],g=d+1<v.length?v[d+1]:e.length,y=d+1,M=`${h}:turn:${y}`,l=ve(e[A].timestamp),S=e.slice(A,g).some($=>$.isSidechain===!0);let k,T=l,I,x=!1;const C=[];for(let $=A;$<g;$++){const O=e[$],U=ve(O.timestamp);if(U===void 0)continue;const X=O.type==="assistant"||O.type==="user"&&Array.isArray(O.message?.content);if(X&&U>T&&(T=U),X?(I=O,x=!1):O.type==="system"&&ko.has(O.subtype??"")&&(x=!0),O.type==="assistant"&&O.message){k??=O.message.model;const N=(Array.isArray(O.message.content)?O.message.content:[]).filter(K=>!!K&&typeof K=="object"&&K.type==="tool_use"),V={...Mo(O.message.usage)};N.length&&(V[R.interactions]=N.length),C.push({...w,occurredAt:U,kind:"progressed",subject:{type:"execution",id:M},core:{measures:V},attrs:{...N.length?{"claude.tools":N.map(K=>K.name??"unknown")}:{},...O.message.model?{"claude.model":O.message.model}:{},...O.requestId?{"claude.requestId":O.requestId}:{},...O.message.stop_reason?{"claude.stopReason":O.message.stop_reason}:{},...O.message.usage?{"claude.usage.inputTokens":oe(O.message.usage.input_tokens),"claude.usage.outputTokens":oe(O.message.usage.output_tokens),"claude.usage.cacheReadTokens":oe(O.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":oe(O.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":O.message.usage.service_tier}:{}},provenance:p(O.uuid,$),seq:O.uuid??`a${$}`})}else if(O.type==="user"&&O.message&&Array.isArray(O.message.content)){const j=O.message.content.filter(N=>!!N&&typeof N=="object"&&N.is_error===!0).length;j&&C.push({...w,occurredAt:U,kind:"progressed",subject:{type:"execution",id:M},core:{measures:{[R.errors]:j}},provenance:p(O.uuid,$),seq:O.uuid??`e${$}`})}}if(m.push({...w,occurredAt:l,kind:"began",subject:{type:"execution",id:M},core:{machineId:t.machine.id,sessionId:h,label:`${c} · TURN ${y}`,executor:Se,model:k,depth:S?1:0},attrs:{"claude.turn":y,"claude.promptSource":e[A].promptSource,"claude.promptId":e[A].promptId,...S?{"claude.isSidechain":!0}:{}},provenance:p(e[A].uuid,A),seq:`turn:${y}`}),m.push(...C),d+1<v.length||x)m.push({...w,occurredAt:T,kind:"ended",subject:{type:"execution",id:M},core:{outcome:"completed"},provenance:p(e[A].uuid,A),seq:`turn:${y}:end`});else if(t.closeOpenTurns){const $=I?.type==="assistant"&&(I.message?.stop_reason==="end_turn"||I.message?.stop_reason==="stop_sequence");m.push({...w,occurredAt:T,kind:"ended",subject:{type:"execution",id:M},core:{outcome:$?"completed":"interrupted"},basis:"inferred",assumption:Io,provenance:p(e[A].uuid,A),seq:`turn:${y}:end`})}}return m}function gt(){return process.env.CLAUDE_HOME||D(he(),".claude")}const it=()=>D(gt(),"sessions"),$o=()=>D(gt(),"projects"),Wt=new Map;async function Ro(e,t,s){const n=it();if(!L(n))return;s.identityAvailable=!0;let o;try{o=await W(n)}catch(r){s.problems.push({path:n,message:String(r)});return}for(const r of o){if(!r.endsWith(".json"))continue;const a=D(n,r);try{const i=So(JSON.parse(await ie(a,"utf8")),a);s.envelopes.push(se(Eo(i,a,{machine:e,host:de(),observedAt:t,now:t}))),s.registryEntries++}catch(i){s.problems.push({path:a,message:i instanceof Error?i.message:String(i),sourceVersion:i instanceof re?i.sourceVersion:void 0})}}}async function Ls(){const e=$o();if(!L(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(D(e,n))}catch{continue}for(const r of o)r.endsWith(".jsonl")&&t.push({path:D(e,n,r),sessionId:r.slice(0,-6),project:n})}return t}async function xo(e,t,s,n){const o=await Ls();if(o.length!==0){n.storedAvailable=!0;for(const r of o){let a;try{a=await me(r.path)}catch{continue}if(a.mtimeMs<t)continue;const i=Date.now()-a.mtimeMs>ht,c=`${a.mtimeMs}:${a.size}:${i}`,u=Wt.get(r.path);let h;if(u&&u.stamp===c)h=u.envelopes;else try{const f=To(await ie(r.path,"utf8"));h=Oo(f,{machine:e,host:de(),observedAt:Date.now(),path:r.path,sessionId:r.sessionId,closeOpenTurns:i}).map(se),Wt.set(r.path,{stamp:c,envelopes:h})}catch(f){n.transcriptsFailed++,n.problems.push({path:r.path,message:f instanceof Error?f.message:String(f),sourceVersion:f instanceof re?f.sourceVersion:void 0});continue}n.transcriptsRead++;for(const f of h)f.occurredAt>=t&&f.occurredAt<=s&&n.envelopes.push(f)}}}async function Us(e,t){const s=ge(),n=Date.now(),o={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await Ro(s,n,o),await xo(s,e,t,o),o}async function No(e,t){return(await Us(e,t)).envelopes}async function Xt(){const e=gt(),t=L(it())?(await W(it()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,s=(await Ls()).length;return{available:t>0||s>0,present:L(e),home:e,registry:t,transcripts:s}}const De="codex",_o="codex",Co=10*6e4;class we extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const jo=e=>`codex:${e}`,Z=e=>typeof e=="number"&&Number.isFinite(e)?e:0,F=e=>typeof e=="string"&&e?e:void 0,Je=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function Do(e){const t=[];for(const s of e.split(`
|
|
5
|
+
`))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function Fo(e){const t=Z(e.input_tokens),s=Z(e.cached_input_tokens);return{[R.tokensInput]:Math.max(0,t-s),[R.tokensOutput]:Z(e.output_tokens),[R.tokensCacheRead]:s,[R.tokensReasoning]:Z(e.reasoning_output_tokens),[R.steps]:1}}function Lo(e,t){const s=e.find(d=>d.type==="session_meta");if(!s||!s.payload)throw new we("rollout has no session_meta record",t.path);const n=s.payload,o=F(n.cli_version),r=F(n.session_id)??F(n.id);if(r&&r!==t.sessionId)throw new we(`rollout names session ${r} but is filed under ${t.sessionId}`,t.path,o);const a=F(n.cwd)??"",i=Je(n.timestamp)??Je(s.timestamp);if(i===void 0)throw new we("session_meta has no parseable timestamp",t.path,o);const c=Q(a).toUpperCase(),u=jo(t.sessionId),f={source:{id:De,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},E=(d,A)=>({path:t.path,...d?{recordId:d}:{},...A!==void 0?{index:A}:{},...o?{sourceVersion:o}:{}}),b=[];let w=null,p=i,m=0;for(let d=0;d<e.length;d++){const A=e[d],g=Je(A.timestamp);g!==void 0&&g>p&&(p=g);const y=A.payload;if(!y)continue;if(A.type==="turn_context"){w&&F(y.turn_id)===w.turnId&&(w.model??=F(y.model),w.effort??=F(y.effort));continue}if(A.type!=="event_msg")continue;const M=F(y.type);if(M==="task_started"){const S=F(y.turn_id);if(!S||g===void 0)throw new we(`task_started at ordinal ${A.ordinal} is missing turn_id or timestamp`,t.path,o);w={turnId:S,startedAt:g,interior:[],lastAt:g},b.push(w);continue}if(M==="task_complete"){const S=F(y.turn_id),k=b.find(T=>T.turnId===S)??w;if(k&&g!==void 0){k.completedAt=g;const T=y.error;k.outcome=T?"error":"completed",k.failureMessage=T?F(T.message):void 0,k.lastAt=Math.max(k.lastAt,g)}k===w&&(w=null);continue}if(M==="token_count"||M==="item_completed"){if(!w){m++;continue}if(g===void 0)continue}else continue;const l=`${u}:turn:${w.turnId}`;if(M==="token_count"){const k=y.info?.last_token_usage;if(!k)continue;w.lastAt=Math.max(w.lastAt,g),w.interior.push({...f,occurredAt:g,kind:"progressed",subject:{type:"execution",id:l},core:{measures:Fo(k)},attrs:{"codex.usage.inputTokens":Z(k.input_tokens),"codex.usage.cachedInputTokens":Z(k.cached_input_tokens),"codex.usage.cacheWriteInputTokens":Z(k.cache_write_input_tokens),"codex.usage.outputTokens":Z(k.output_tokens),"codex.usage.reasoningOutputTokens":Z(k.reasoning_output_tokens)},provenance:E(void 0,A.ordinal),seq:`o${A.ordinal??d}`});continue}if(M==="item_completed"){const S=y.item,k=F(S?.type);if(!S||!k)continue;w.lastAt=Math.max(w.lastAt,g);let T,I;if(k==="CommandExecution"){const x=Z(S.exit_code);T={[R.interactions]:1,...x!==0?{[R.errors]:1}:{}},I={"codex.itemType":k,"codex.exitCode":x,...S.process_id!==void 0?{"codex.processId":S.process_id}:{},...F(S.status)?{"codex.status":S.status}:{}}}else if(k==="McpToolCall"){const x=F(S.status)==="failed"||F(S.status)==="error";T={[R.interactions]:1,...x?{[R.errors]:1}:{}},I={"codex.itemType":k,"codex.tool":[F(S.server),F(S.tool)].filter(Boolean).join("."),...F(S.status)?{"codex.status":S.status}:{}}}else if(k==="WebSearch")T={[R.interactions]:1},I={"codex.itemType":k};else if(k==="FileChange"){const x=S.changes;T={[R.interactions]:1},I={"codex.itemType":k,...x&&typeof x=="object"?{"codex.fileChanges":Object.entries(x).map(([C,_])=>({path:C,kind:F(_?.type)}))}:{}}}else continue;w.interior.push({...f,occurredAt:g,kind:"progressed",subject:{type:"execution",id:l},core:{measures:T},attrs:I,provenance:E(F(S.id),A.ordinal),seq:`o${A.ordinal??d}`})}}if(b.length===0&&m>0)throw new we(`rollout has ${m} work records but no task_started marker`,t.path,o);const v=[{...f,occurredAt:i,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[_o,t.sessionId],validFrom:i,validTo:p}],core:{machineId:t.machine.id,label:c,executor:De},attrs:{context:a,"codex.sessionId":t.sessionId,"codex.cliVersion":o,"codex.originator":F(n.originator),"codex.source":F(n.source),"codex.modelProvider":F(n.model_provider),...Uo(n.git)},provenance:E(t.sessionId,s.ordinal),seq:"session"}];for(let d=0;d<b.length;d++){const A=b[d],g=`${u}:turn:${A.turnId}`;v.push({...f,occurredAt:A.startedAt,kind:"began",subject:{type:"execution",id:g},core:{machineId:t.machine.id,sessionId:u,label:`${c} · TURN ${d+1}`,executor:De,model:A.model,depth:0},attrs:{"codex.turnId":A.turnId,...A.effort?{"codex.effort":A.effort}:{}},provenance:E(A.turnId),seq:`turn:${A.turnId}`}),v.push(...A.interior),A.completedAt!==void 0?v.push({...f,occurredAt:A.completedAt,kind:"ended",subject:{type:"execution",id:g},core:{outcome:A.outcome??"completed",...A.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:A.failureMessage??"turn failed"}:{}},provenance:E(A.turnId),seq:`turn:${A.turnId}:end`}):t.now-p>Co&&v.push({...f,basis:"inferred",assumption:"A rollout untouched for 10 minutes belongs to a dead process, so a turn left open in it was interrupted, not still running. Its end is the last instant the rollout moved.",occurredAt:A.lastAt,kind:"ended",subject:{type:"execution",id:g},core:{outcome:"interrupted"},provenance:E(A.turnId),seq:`turn:${A.turnId}:end`})}return v}function Uo(e){if(!e||typeof e!="object")return{};const t=e;return{...F(t.branch)?{"codex.gitBranch":t.branch}:{},...F(t.commit_hash)?{"codex.gitCommit":t.commit_hash}:{},...F(t.repository_url)?{"codex.gitOriginUrl":t.repository_url}:{}}}function Ps(){return process.env.CODEX_HOME||D(he(),".codex")}const Bs=()=>D(Ps(),"sessions"),Po=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,Gt=new Map;async function Hs(){const e=Bs();if(!L(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(D(e,n))}catch{continue}for(const r of o){let a;try{a=await W(D(e,n,r))}catch{continue}for(const i of a){let c;try{c=await W(D(e,n,r,i))}catch{continue}for(const u of c){const h=Po.exec(u);h&&t.push({path:D(e,n,r,i,u),sessionId:h[1]})}}}}return t}async function Ws(e,t){const s=ge(),n=Date.now(),o={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},r=await Hs();if(r.length===0)return o.storedAvailable=L(Bs()),o;o.storedAvailable=!0;for(const a of r){let i;try{i=await me(a.path)}catch{continue}if(i.mtimeMs<e)continue;const c=`${i.mtimeMs}:${i.size}`,u=Gt.get(a.path);let h;if(u&&u.stamp===c)h=u.envelopes;else try{const f=Do(await ie(a.path,"utf8"));h=Lo(f,{machine:s,host:de(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n}).map(se),Gt.set(a.path,{stamp:c,envelopes:h})}catch(f){o.rolloutsFailed++,o.problems.push({path:a.path,message:f instanceof Error?f.message:String(f),sourceVersion:f instanceof we?f.sourceVersion:void 0});continue}o.rolloutsRead++;for(const f of h)f.occurredAt>=e&&f.occurredAt<=t&&o.envelopes.push(f)}return o}async function Bo(e,t){return(await Ws(e,t)).envelopes}async function qt(){const e=Ps(),t=(await Hs()).length;return{available:t>0,present:L(e),home:e,rollouts:t}}const Oe="cursor",Ho="cursor";class Fe extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const at=e=>`cursor:${e}`,Ae=e=>typeof e=="string"&&e?e:void 0,Ne=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Yt=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function Xs(e,t){if(typeof e.composerId!="string"||!e.composerId)throw new Fe("composer header has no composerId",t);if(typeof e.createdAt!="number"||!Number.isFinite(e.createdAt))throw new Fe("composer header has no numeric createdAt",t);if(typeof e.lastUpdatedAt!="number"||!Number.isFinite(e.lastUpdatedAt))throw new Fe("composer header has no numeric lastUpdatedAt",t)}function Wo(e,t){Xs(e,t.path);const s=e.value??{},n=s.subagentInfo,o=n?Ae(n.parentComposerId):void 0,r=t.workspacePath??"",a=Ae(s.name)?.toUpperCase()??(r?Q(r).toUpperCase():"CURSOR");return{source:{id:Oe,instance:t.host},occurredAt:e.createdAt,observedAt:t.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:at(e.composerId)},claims:[{ns:"agent.session",parts:[Ho,e.composerId],validFrom:e.createdAt,validTo:e.lastUpdatedAt}],basis:"measured",core:{machineId:t.machine.id,label:a,executor:Oe,...o?{parentId:at(o)}:{}},attrs:{context:r,"cursor.composerId":e.composerId,"cursor.workspaceId":e.workspaceId,"cursor.isSubagent":e.isSubagent,...n?{"cursor.parentComposerId":Ae(n.parentComposerId),"cursor.subagentType":Ae(n.subagentTypeName)}:{},...Ne(s.totalLinesAdded)!==void 0?{"cursor.linesAdded":s.totalLinesAdded}:{},...Ne(s.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":s.totalLinesRemoved}:{},...Ne(s.filesChangedCount)!==void 0?{"cursor.filesChanged":s.filesChangedCount}:{},...Ae(s.unifiedMode)?{"cursor.mode":s.unifiedMode}:{},...Ne(s._v)!==void 0?{"cursor.schemaVersion":s._v}:{}},provenance:{path:t.path,recordId:e.composerId},seq:"composer"}}const Vt="Cursor persists no turn timing: the bounds are the first and last timestamped records inside the turn, untimestamped activity may extend beyond them, and the turn is taken as completed because Cursor records no turn outcome.";function Xo(e,t,s){Xs(e,s.path);const n=at(e.composerId),r={source:{id:Oe,instance:s.host},observedAt:s.observedAt,clock:"wall",stratum:"stored-semantics"},a=h=>({path:s.path,...h?{recordId:h}:{}}),i=[];for(let h=0;h<t.length;h++)t[h].type===1&&i.push(h);const c=[];let u=0;for(let h=0;h<i.length;h++){const f=i[h],E=h+1<i.length?i[h+1]:t.length,b=h+1,w=t.slice(f,E),p=w.map(y=>({bubble:y,at:Yt(y.createdAt)})).filter(y=>y.at!==void 0);if(p.length<2){u++;continue}const m=Math.min(...p.map(y=>y.at)),v=Math.max(...p.map(y=>y.at)),d=`${n}:turn:${b}`,A=w.filter(y=>y.toolName&&Yt(y.createdAt)===void 0),g=A.filter(y=>y.toolStatus==="error").length;c.push({...r,occurredAt:m,kind:"began",subject:{type:"execution",id:d},basis:"inferred",assumption:Vt,core:{machineId:s.machine.id,sessionId:n,label:`${Ae(e.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${b}`,executor:Oe,depth:e.isSubagent?1:0,...A.length?{measures:{[R.interactions]:A.length,...g?{[R.errors]:g}:{}}}:{}},attrs:{"cursor.turn":b},provenance:a(t[f].bubbleId),seq:`turn:${b}`});for(const{bubble:y,at:M}of p){if(!y.toolName)continue;const l=y.toolStatus==="error",S={[R.interactions]:1,...l?{[R.errors]:1}:{}};c.push({...r,occurredAt:M,kind:"progressed",subject:{type:"execution",id:d},basis:"measured",core:{measures:S},attrs:{"cursor.tool":y.toolName,...y.toolStatus?{"cursor.toolStatus":y.toolStatus}:{}},provenance:a(y.bubbleId),seq:y.bubbleId})}c.push({...r,occurredAt:v,kind:"ended",subject:{type:"execution",id:d},basis:"inferred",assumption:Vt,core:{outcome:"completed"},provenance:a(t[f].bubbleId),seq:`turn:${b}:end`})}return{drafts:c,turns:i.length,untimedTurns:u}}function Te(){return process.env.CURSOR_GLOBAL_STORAGE||D(he(),"Library","Application Support","Cursor","User","globalStorage")}function Go(){return process.env.CURSOR_WORKSPACE_STORAGE||D(Te(),"..","workspaceStorage")}const Gs=()=>D(Te(),"state.vscdb"),zt=new Map;async function qo(){const e=new Map,t=Go();if(!L(t))return e;let s;try{s=await W(t)}catch{return e}for(const n of s)try{const o=JSON.parse(await ie(D(t,n,"workspace.json"),"utf8"));typeof o.folder=="string"&&o.folder.startsWith("file://")&&e.set(n,decodeURIComponent(o.folder.slice(7)))}catch{continue}return e}function Yo(e,t){let s;if(e.value)try{s=JSON.parse(e.value)}catch{s=void 0}const n=a=>typeof a=="number"&&Number.isFinite(a)?a:void 0,o=e.lastUpdatedAt??n(s?.lastUpdatedAt)??n(s?.conversationCheckpointLastUpdatedAt)??e.createdAt??NaN,r={composerId:e.composerId,workspaceId:e.workspaceId??void 0,createdAt:e.createdAt??NaN,lastUpdatedAt:o,isSubagent:e.isSubagent===1,value:s};if(!Number.isFinite(r.createdAt)||!Number.isFinite(r.lastUpdatedAt))throw new Fe(`composer ${e.composerId} has no numeric createdAt/lastUpdatedAt`,t);return r}function Vo(e,t){const s=e.prepare("SELECT value FROM cursorDiskKV WHERE key = ?").get(`composerData:${t}`);if(!s?.value)return[];const n=typeof s.value=="string"?s.value:Buffer.from(s.value).toString("utf8"),r=JSON.parse(n).fullConversationHeadersOnly??[],a=e.prepare("SELECT key, value FROM cursorDiskKV WHERE key >= ? AND key < ?").all(`bubbleId:${t}:`,`bubbleId:${t};`),i=new Map;for(const c of a){const u=c.key.slice(`bubbleId:${t}:`.length);try{const h=typeof c.value=="string"?c.value:Buffer.from(c.value).toString("utf8"),f=JSON.parse(h);i.set(u,{bubbleId:u,type:f.type,createdAt:typeof f.createdAt=="string"&&f.createdAt?f.createdAt:void 0,toolName:f.toolFormerData?.name,toolStatus:f.toolFormerData?.status})}catch{continue}}return r.filter(c=>typeof c.bubbleId=="string").map(c=>i.get(c.bubbleId)??{bubbleId:c.bubbleId,type:c.type})}async function qs(e,t){const s=ge(),n=Date.now(),o=Gs(),r={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!L(o))return r;r.storedAvailable=!0;const a=await qo();let i;try{i=new ft(o,{readOnly:!0})}catch(c){return r.problems.push({path:o,message:`cannot open read-only: ${String(c)}`}),r}try{let c;try{c=i.prepare("SELECT composerId, workspaceId, createdAt, lastUpdatedAt, isSubagent, value FROM composerHeaders WHERE (lastUpdatedAt >= ? OR lastUpdatedAt IS NULL) AND createdAt <= ?").all(e,t)}catch(u){return r.problems.push({path:o,message:`composerHeaders unreadable: ${String(u)}`}),r}for(const u of c)try{const h=Yo(u,o);if(h.lastUpdatedAt<e)continue;const f={machine:s,host:de(),observedAt:n,path:o,workspacePath:h.workspaceId?a.get(h.workspaceId):void 0};r.envelopes.push(se(Wo(h,f)));const E=`${h.lastUpdatedAt}`,b=zt.get(h.composerId);let w;if(b&&b.stamp===E)w=b.envelopes;else{const p=Vo(i,h.composerId),{drafts:m}=Xo(h,p,f);w=m.map(se),zt.set(h.composerId,{stamp:E,envelopes:w})}for(const p of w)p.occurredAt>=e&&p.occurredAt<=t&&r.envelopes.push(p);r.composersRead++}catch(h){r.composersFailed++,r.problems.push({path:o,message:`${u.composerId}: ${h instanceof Error?h.message:String(h)}`})}}finally{i.close()}return r}async function zo(e,t){return(await qs(e,t)).envelopes}async function Kt(){const e=Gs();if(!L(e))return{available:!1,present:!1,globalStorage:Te()};try{const t=new ft(e,{readOnly:!0});try{const s=t.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:s.n>0,present:!0,globalStorage:Te(),composers:s.n}}finally{t.close()}}catch{return{available:!1,present:!0,globalStorage:Te()}}}const Le="gemini",Ko="gemini";class We extends Error{constructor(t,s){super(t),this.path=s,this.name="GeminiFormatError"}path}const Jo="The session file has not been written to for longer than the live window, so the runtime that owned it is gone and the turn ended at its last message.";function Qo(e){return(typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(s=>s?.text).filter(s=>typeof s=="string").join(`
|
|
6
|
+
`):"").split(`
|
|
7
|
+
`)[0].trim().slice(0,200)||"Gemini reported an error"}const Zo=e=>`gemini:${e}`,ee=e=>typeof e=="number"&&Number.isFinite(e)?e:0,_e=e=>typeof e=="string"&&e?e:void 0,ye=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function er(e,t){const s=e.split(`
|
|
8
|
+
`).filter(i=>i.trim());if(s.length===0)throw new We("session file is empty",t);let n=null;const o=[],r=new Map,a=i=>{const c=i;!c||typeof c!="object"||typeof c.id!="string"||(r.has(c.id)||o.push(c.id),r.set(c.id,c))};for(const i of s){let c;try{c=JSON.parse(i)}catch{continue}if(!c||typeof c!="object")continue;const u=c;if(!n&&typeof u.sessionId=="string"){n=u;continue}const h=u.$set;if(h){const f=h.messages;if(Array.isArray(f))for(const E of f)a(E);continue}typeof u.id=="string"&&a(u)}if(!n||!n.sessionId)throw new We("session file has no header with a sessionId",t);return{header:n,messages:o.map(i=>r.get(i))}}const Ys=e=>Array.isArray(e.content)&&e.content.some(t=>!!t&&typeof t=="object"&&"functionResponse"in t);function tr(e){if(e.type!=="user"||Ys(e))return!1;const t=Array.isArray(e.content)?e.content.map(n=>n?.text).filter(n=>typeof n=="string"):[];if(t.length===0)return!1;const s=t[0];return!s.startsWith("<session_context>")&&!s.startsWith("[System:")}function sr(e){const t=ee(e.input),s=ee(e.cached);return{[R.tokensInput]:Math.max(0,t-s),[R.tokensOutput]:ee(e.output)+ee(e.thoughts),[R.tokensCacheRead]:s,[R.tokensReasoning]:ee(e.thoughts),[R.steps]:1}}function nr(e,t){const{header:s,messages:n}=e,o=s.sessionId,r=ye(s.startTime);if(r===void 0)throw new We("session header has no parseable startTime",t.path);const a=n.filter(m=>ye(m.timestamp)!==void 0),i=a.length?Math.max(...a.map(m=>ye(m.timestamp))):r,c=t.workspacePath??"",u=c?Q(c).toUpperCase():"GEMINI",h=Zo(o),E={source:{id:Le,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},b=m=>({path:t.path,...m?{recordId:m}:{}}),w=[{...E,occurredAt:r,kind:"began",subject:{type:"session",id:h},claims:[{ns:"agent.session",parts:[Ko,o],validFrom:r,validTo:i}],core:{machineId:t.machine.id,label:u,executor:Le},attrs:{context:c,"gemini.sessionId":o,"gemini.projectHash":s.projectHash,..._e(s.kind)?{"gemini.kind":s.kind}:{}},provenance:b(o),seq:"session"}],p=[];for(let m=0;m<n.length;m++)tr(n[m])&&ye(n[m].timestamp)!==void 0&&p.push(m);if(p.length===0){if(n.some(m=>m.type==="gemini"))throw new We(`session has ${n.length} messages including model output but no recognisable user prompt`,t.path);return w}for(let m=0;m<p.length;m++){const v=p[m],d=m+1<p.length?p[m+1]:n.length,A=m+1,g=`${h}:turn:${A}`,y=ye(n[v].timestamp);let M=y,l,S;const k=[];for(let _=v;_<d;_++){const $=n[_],O=ye($.timestamp);if(O===void 0||$.type!=="gemini"&&$.type!=="error"&&!($.type==="user"&&Ys($))||(O>M&&(M=O),S=$,$.type!=="gemini"))continue;l??=_e($.model);const U=Array.isArray($.toolCalls)?$.toolCalls:[],X=$.tokens?sr($.tokens):{};U.length&&(X[R.interactions]=U.length),Object.keys(X).length!==0&&k.push({...E,occurredAt:O,kind:"progressed",subject:{type:"execution",id:g},core:{measures:X},attrs:{...U.length?{"gemini.tools":U.map(j=>_e(j.name)??"unknown")}:{},..._e($.model)?{"gemini.model":$.model}:{},...$.tokens?{"gemini.usage.input":ee($.tokens.input),"gemini.usage.output":ee($.tokens.output),"gemini.usage.cached":ee($.tokens.cached),"gemini.usage.thoughts":ee($.tokens.thoughts),"gemini.usage.tool":ee($.tokens.tool)}:{}},provenance:b($.id),seq:$.id})}w.push({...E,occurredAt:y,kind:"began",subject:{type:"execution",id:g},core:{machineId:t.machine.id,sessionId:h,label:`${u} · TURN ${A}`,executor:Le,model:l,depth:0},attrs:{"gemini.turn":A},provenance:b(n[v].id),seq:`turn:${A}`}),w.push(...k);const T=S?.type==="error",I=S?.type==="gemini"&&!(Array.isArray(S.toolCalls)&&S.toolCalls.length),x=m+1<p.length,C=(_,$)=>({...E,occurredAt:M,kind:"ended",subject:{type:"execution",id:g},core:_,...$?{basis:"inferred",assumption:Jo}:{},provenance:b(n[v].id),seq:`turn:${A}:end`});T?w.push(C({outcome:"error",failureMessage:Qo(S)},!1)):x||I&&t.settled?w.push(C({outcome:"completed"},!1)):t.closeOpenTurns&&w.push(C({outcome:I?"completed":"interrupted"},!0))}return w}const or=3e3;function bt(){return process.env.GEMINI_HOME||D(he(),".gemini")}const Vs=()=>D(bt(),"tmp"),Jt=new Map;async function rr(){const e=new Map;try{const t=JSON.parse(await ie(D(bt(),"projects.json"),"utf8"));for(const[s,n]of Object.entries(t.projects??{}))typeof n=="string"&&e.set(n,s)}catch{}return e}async function zs(){const e=Vs();if(!L(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(D(e,n,"chats"))}catch{continue}for(const r of o)r.startsWith("session-")&&r.endsWith(".jsonl")&&t.push({path:D(e,n,"chats",r),slug:n})}return t}async function Ks(e,t){const s=ge(),n=Date.now(),o={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},r=await zs();if(r.length===0)return o.storedAvailable=L(Vs()),o;o.storedAvailable=!0;const a=await rr();for(const i of r){let c;try{c=await me(i.path)}catch{continue}if(c.mtimeMs<e)continue;const u=Date.now()-c.mtimeMs,h=u>or,f=u>ht,E=`${c.mtimeMs}:${c.size}:${h}:${f}`,b=Jt.get(i.path);let w;if(b&&b.stamp===E)w=b.envelopes;else try{const p=er(await ie(i.path,"utf8"),i.path);w=nr(p,{machine:s,host:de(),observedAt:n,path:i.path,workspacePath:a.get(i.slug),settled:h,closeOpenTurns:f}).map(se),Jt.set(i.path,{stamp:E,envelopes:w})}catch(p){o.sessionsFailed++,o.problems.push({path:i.path,message:p instanceof Error?p.message:String(p)});continue}o.sessionsRead++;for(const p of w)p.occurredAt>=e&&p.occurredAt<=t&&o.envelopes.push(p)}return o}async function ir(e,t){return(await Ks(e,t)).envelopes}async function Qt(){const e=bt(),t=(await zs()).length;return{available:t>0,present:L(e),home:e,sessions:t}}const pe="os",ar=(e,t)=>`os:${e}:${t.pid}:${t.startedAt}`;function cr(e,t){const s=/^os:[^:]+:(\d+):(\d+)$/.exec(e);return s?`os:${t}:${s[1]}:${s[2]}`:void 0}const ur=e=>`The process was present in one ${Math.round(e/1e3)}s snapshot and absent from the next, so it exited somewhere in that window. The recorded instant is the last moment it was observed alive — a lower bound on the true exit. A process that started and exited entirely within one interval is never observed at all.`,dr=250,lr=8*1024*1024;function pr(e,t,s){const n={source:{id:pe,instance:s.host},observedAt:s.observedAt,clock:"wall",stratum:"machine"},o=[],r=new Map;for(const a of t){const i=ar(s.host,a);r.set(i,a);const c={ns:"os.process",parts:[s.host,a.pid],validFrom:a.startedAt,validTo:s.observedAt};if(!e.has(i)){o.push({...n,occurredAt:a.startedAt,kind:"began",subject:{type:"process",id:i},claims:[c],basis:"measured",core:{machineId:s.machineId,label:fr(a.command),executor:a.command,measures:{[R.cpuMs]:a.cpuMs}},attrs:{"os.pid":a.pid,"os.ppid":a.ppid,"os.command":a.command,"os.rssBytes":a.rssBytes}});continue}const u=e.get(i),h=a.cpuMs-u.cpuMs>=dr,f=Math.abs(a.rssBytes-u.rssBytes)>=lr;(h||f)&&o.push({...n,occurredAt:s.observedAt,seq:`obs:${s.observedAt}`,kind:"observed",subject:{type:"process",id:i},claims:[c],basis:"measured",core:{measures:{[R.cpuMs]:a.cpuMs}},attrs:{"os.rssBytes":a.rssBytes}})}for(const[a,i]of e)r.has(a)||o.push({...n,occurredAt:s.observedAt-s.intervalMs,kind:"ended",subject:{type:"process",id:a},basis:"inferred",assumption:ur(s.intervalMs),core:{outcome:"completed",measures:{[R.cpuMs]:i.cpuMs}},attrs:{"os.pid":i.pid}});return{envelopes:o,next:r}}function fr(e){return(e.split("/").pop()??e).toUpperCase()}function te(e,t){const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:void 0}function Xe(e,t){for(const[s,n]of Object.entries(t)){if(typeof n!="number"||!Number.isFinite(n))continue;const o=s;e[o]=(e[o]??0)+n}}const mr=[R.tokensInput,R.tokensOutput,R.tokensCacheRead];function ue(e){let t=0,s=!1;for(const n of mr){const o=te(e,n);o!==void 0&&(s=!0,t+=o)}return s?t:void 0}function Js(e){return{input:te(e,R.tokensInput)??0,output:te(e,R.tokensOutput)??0,cacheRead:te(e,R.tokensCacheRead)??0,reasoning:te(e,R.tokensReasoning)??0}}function Qs(e){const t=ue(e.measures);if(t!==void 0)return Zt(t/1e3,200);const s=te(e.measures,R.cpuMs);if(s!==void 0)return Zt(s/1e3,200)}function Ee(e){return te(e.measures,R.interactions)}function Zs(e){return te(e.measures,R.steps)??0}function ct(e){return te(e.measures,R.errors)??0}function ut(e){return te(e.measures,R.retries)??0}function Zt(e,t){return Math.min(1,Math.log1p(Math.max(0,e))/Math.log1p(t))}const hr=new Set(["running","waiting"]);function en(e){return hr.has(e)}function tn(e,t){return{now:e,dayStart:e,dayEnd:t,machines:new Map,sources:new Map,sessions:new Map,executions:new Map,processes:new Map,artifacts:new Map,transfers:new Map,relationships:[],active:new Set,seen:new Set}}const gr=9e4;function es(e,t){if(e.waitingSince===void 0)return;const s=e.waitingSince,n=Math.max(s,t);e.waitingMs+=n-s,e.waits.push({start:s,end:n})}function br(e,t){const s=`${t.source.id}:${t.source.instance}`;let n=e.sources.get(s);n||(n={id:t.source.id,instance:t.source.instance,origin:t.source.instance,firstSeenAt:t.occurredAt,lastSeenAt:t.occurredAt,events:0,strata:{}},e.sources.set(s,n)),n.events++,t.occurredAt<n.firstSeenAt&&(n.firstSeenAt=t.occurredAt),t.occurredAt>n.lastSeenAt&&(n.lastSeenAt=t.occurredAt),t.stratum&&(n.strata[t.stratum]=(n.strata[t.stratum]??0)+1);const o=t.provenance?.sourceVersion;o&&(n.sourceVersions?n.sourceVersions.includes(o)||n.sourceVersions.push(o):n.sourceVersions=[o])}function vr(e,t){if(e.seen.has(t.id))return;e.seen.add(t.id),t.occurredAt>e.now&&(e.now=t.occurredAt),br(e,t);const s=t.core??{},n=t.occurredAt;switch(t.subject.type){case"machine":{if(e.machines.has(t.subject.id))break;const o={id:t.subject.id,name:s.machineName??t.subject.id,kind:s.machineKind??"laptop",parentId:s.parentId,firstSeenAt:n};e.machines.set(o.id,o);break}case"session":{if(t.kind==="began"){const o=e.sessions.get(t.subject.id);if(o){o.parentId===void 0&&s.parentId&&(o.parentId=s.parentId);break}const r={id:t.subject.id,machineId:s.machineId??"",label:s.label,context:t.attrs?.context??s.label??"",executor:s.executor,model:s.model,startedAt:n,executionIds:[],parentId:s.parentId};e.sessions.set(r.id,r)}else if(t.kind==="ended"){const o=e.sessions.get(t.subject.id);o&&(o.endedAt=n)}break}case"execution":yr(e,t,n);break;case"process":wr(e,t,n);break;case"artifact":{if(e.artifacts.has(t.subject.id))break;e.artifacts.set(t.subject.id,{id:t.subject.id,kind:"file",path:s.label??t.subject.id,firstSeenAt:n});break}}}function yr(e,t,s){const n=t.core??{},o=t.subject.id;if(t.kind==="began"){if(e.executions.has(o))return;const a={id:o,sessionId:n.sessionId??n.parentId??"",machineId:n.machineId??"",label:n.label??o,executor:n.executor??"unknown",model:n.model,status:"running",startedAt:s,lastActivityAt:s,measures:{},waitingMs:0,waits:[],parentId:n.parentId,depth:n.depth??0,startBasis:t.basis,boundsAssumption:t.assumption};n.measures&&Xe(a.measures,n.measures),e.executions.set(o,a),e.active.add(o),e.sessions.get(a.sessionId)?.executionIds.push(o);return}const r=e.executions.get(o);if(r)switch(t.kind){case"progressed":{n.measures&&Xe(r.measures,n.measures),r.lastActivityAt=s,r.status==="idle"&&(r.status="running",e.active.add(o));break}case"blocked":{if(!en(r.status))break;r.status="waiting",r.waitingSince=s,r.waitReason=n.blockedOn??"input",r.lastActivityAt=s;break}case"resumed":{es(r,s),r.status="running",r.waitingSince=void 0,r.waitReason=void 0,r.lastActivityAt=s,e.active.add(o);break}case"ended":{const a=n.outcome==="error";r.status=a?"failed":"completed",r.endedAt=s,r.endBasis=t.basis,t.assumption&&!r.boundsAssumption&&(r.boundsAssumption=t.assumption),r.lastActivityAt=s,r.outcome=n.outcome??"completed",a&&(r.failure={code:n.failureCode??"ERROR",message:n.failureMessage??"Execution failed"}),es(r,s),r.waitingSince=void 0,r.waitReason=void 0,e.active.delete(o);break}case"observed":r.lastActivityAt=Math.max(r.lastActivityAt,s);break}}function wr(e,t,s){const n=t.core??{},o=t.subject.id,r=Number(t.attrs?.["os.pid"]??0);if(t.kind==="began"){if(e.processes.has(o))return;const i={id:o,machineId:n.machineId??"",pid:r,ppid:typeof t.attrs?.["os.ppid"]=="number"?t.attrs["os.ppid"]:void 0,command:n.label??n.executor??String(r),startedAt:s,lastSeenAt:s,status:"running",measures:{}};n.measures&&Xe(i.measures,n.measures),e.processes.set(o,i);return}const a=e.processes.get(o);if(a)if(t.kind==="observed"||t.kind==="progressed"){if(a.lastSeenAt=Math.max(a.lastSeenAt,s),n.measures){const i=n.measures[R.cpuMs];typeof i=="number"&&(a.measures[R.cpuMs]=i);const{[R.cpuMs]:c,...u}=n.measures;Xe(a.measures,u)}}else t.kind==="ended"&&(a.endedAt=s,a.lastSeenAt=Math.max(a.lastSeenAt,s),a.status="exited",a.endInferred=t.basis==="inferred")}function Ar(e,t){for(let s=0;s<t.length;s++)vr(e,t[s])}function Sr(e,t){if(!(t<=e.now)){e.now=t;for(const s of e.active){const n=e.executions.get(s);if(!n){e.active.delete(s);continue}n.status==="running"&&t-n.lastActivityAt>gr&&(n.status="idle")}}}const Er=5*6e4;function kr(e){const t=[];for(const s of e)s.parentId&&t.push({from:{type:"session",id:s.parentId},to:{type:"session",id:s.id},kind:"spawned",basis:"measured",via:"recorded by the child session's own runtime"});return t}function Ir(e,t){const s=e.now-Er,n=new Set;for(const i of t)i.from.type==="process"&&n.add(i.from.id),i.to.type==="process"&&n.add(i.to.id);const o=[];let r=0,a=0;for(const i of e.processes.values())i.lastSeenAt>=s&&r++,i.endInferred&&a++,n.has(i.id)&&o.push(i);return{now:e.now,dayStart:e.dayStart,dayEnd:e.dayEnd,machines:[...e.machines.values()],sources:[...e.sources.values()],sessions:[...e.sessions.values()],executions:[...e.executions.values()],processes:o,processTotals:{observed:e.processes.size,recentlySeen:r,exitsInferred:a},relationships:[...t,...kr(e.sessions.values())]}}function ts(e){const t=tn(e.dayStart,e.dayEnd);t.now=e.now;for(const s of e.machines)t.machines.set(s.id,s);for(const s of e.sources)t.sources.set(`${s.id}:${s.instance}`,s);for(const s of e.sessions)t.sessions.set(s.id,s);for(const s of e.executions)t.executions.set(s.id,s),en(s.status)&&t.active.add(s.id);for(const s of e.processes)t.processes.set(s.id,s);return t.processTotals=e.processTotals,t.relationships=e.relationships,t}function Tr(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=Math.imul(t,16777619);return t>>>0}function Ge(e,t=0){return Tr(e+"#"+t)%1e5/1e5}const Qe=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function Mr(e){if(e<Qe.length)return Qe[e];const s=-.9+(e-Qe.length)*1.15;return{x:620+Math.cos(s)*520,y:300+Math.sin(s)*250,extentX:150,extentY:94}}function Or(e){const t=s=>s==="laptop"?0:s==="desktop"?1:2;return[...e].sort((s,n)=>t(s.kind)-t(n.kind)||s.firstSeenAt-n.firstSeenAt||(s.id<n.id?-1:s.id>n.id?1:0))}function ss(e,t){const s=Ge(t,1),n=Ge(t,2),o=s*Math.PI*2+n*2.399963,r=.34+.46*Math.sqrt(n);return{x:e.x+Math.cos(o)*e.extentX*r,y:e.y+Math.sin(o)*e.extentY*r}}const ns=30,$r=74;function Rr(e){return ns+e*($r-ns)}const os=64,xr=8,Nr=8,rs=16,is=.45;function _r(e,t){switch(e.status){case"running":{const s=t-e.lastActivityAt;return .55+.45*Math.exp(-s/45e3)}case"waiting":return .08;case"failed":return .9;case"completed":return 0;case"idle":return .03}}const as=.32;function Cr(e){const t=Qs(e),s=e.depth>0?.62:1;return t===void 0?as*s:Math.min(1,(as+.68*t)*s)}function jr(e,t){const s=Math.max(1,(e.endedAt??t)-e.startedAt),n=(Ee(e)??0)/(s/6e4);return Math.min(1,.25+n/24)}function cs(e){return(e.status==="failed"?3:e.status==="waiting"?2:e.status==="running"?1:0)*1e15+e.lastActivityAt}function Dr(e){const t=new Set,s=new Set,n=new Map,o=new Map,r=(a,i,c)=>{const u=a.get(i);u?u.push(c):a.set(i,[c])};for(const a of e.relationships){const{from:i,to:c,kind:u}=a;u==="ran-as"?(i.type==="execution"&&t.add(i.id),c.type==="execution"&&t.add(c.id),i.type==="session"&&c.type==="process"&&s.add(i.id),c.type==="session"&&i.type==="process"&&s.add(c.id),i.type==="execution"&&c.type==="session"?n.set(i.id,c.id):i.type==="session"&&c.type==="execution"&&n.set(c.id,i.id)):u==="same-as"&&i.type==="execution"&&c.type==="execution"&&(t.add(i.id),t.add(c.id),r(o,i.id,c.id),r(o,c.id,i.id))}return{resolvedExecutions:t,sessionsWithProcess:s,runObservesSession:n,sameExecution:o}}function Fr(e,t){const n=e.startBasis===void 0?.5:e.startBasis==="measured"?1:0,o=e.endBasis===void 0?.5:e.endBasis==="measured"?1:0,r=e.endedAt===void 0?n:(n+o)/2,a=Qs(e)===void 0?0:1,i=t.resolvedExecutions.has(e.id)||t.sessionsWithProcess.has(e.sessionId)?1:0;return(1+r+a+i)/4}function us(e){let t=1;for(const s of e)t*=1-Math.min(1,Math.max(0,s));return 1-t}function ds(e,t,s,n){const o=Math.max(e,s),r=Math.min(t,n);if(r<o)return 0;const a=Math.max(t,n)-Math.min(e,s);return a<=0?1:(r-o)/a}function ls(e){const t=e.now,s=Or(e.machines.values()).slice(0,xr),n=new Map,o=[];let r=1;const a=new Map;for(const l of e.executions.values()){const S=(a.get(l.machineId)??0)+1;a.set(l.machineId,S),S>r&&(r=S)}s.forEach((l,S)=>{const k=Mr(S);n.set(l.id,k),o.push({id:l.id,name:l.name,kind:l.kind,x:k.x,y:k.y,extentX:k.extentX,extentY:k.extentY,prominence:(a.get(l.id)??0)/r,seed:Ge(l.id,7)})});const i=45e3,c=[];for(const l of e.executions.values())(l.status==="completed"||l.status==="failed")&&t-(l.endedAt??t)>i||l.status==="idle"&&t-l.lastActivityAt>i*4||n.has(l.machineId)&&c.push(l);c.length>os&&(c.sort((l,S)=>cs(S)-cs(l)),c.length=os);const u=Dr(e),h=l=>{const S=n.get(l.machineId),{x:k,y:T}=ss(S,l.id);return{id:l.id,massId:l.machineId,sessionId:l.sessionId,x:k,y:T,extent:Cr(l),energy:_r(l,t),rate:jr(l,t),phase:Ge(l.id,3)*Math.PI*2,status:l.status,label:l.label,statusSince:l.waitingSince??l.endedAt??l.startedAt,articulation:Fr(l,u),shoulder:0,observers:1}},f=new Set(c.map(l=>l.id)),E=new Set,b=[],w=l=>[l.startedAt,l.endedAt??t];for(const l of[...c].sort((S,k)=>S.id<k.id?-1:1)){if(E.has(l.id))continue;const S=[l];E.add(l.id);for(let _=0;_<S.length;_++)for(const $ of u.sameExecution.get(S[_].id)??[])!f.has($)||E.has($)||(E.add($),S.push(e.executions.get($)));if(S.length===1){b.push(h(l));continue}const k=S.map(h),T=k.reduce((_,$)=>$.articulation>_.articulation||$.articulation===_.articulation&&$.id<_.id?$:_);let I=1;const[x,C]=w(e.executions.get(T.id));for(const _ of S){const[$,O]=w(_);I=Math.min(I,ds(x,C,$,O))}b.push({...T,extent:Math.max(...k.map(_=>_.extent)),energy:Math.max(...k.map(_=>_.energy)),articulation:us(k.map(_=>_.articulation)),shoulder:Math.min(is,1-I),observers:S.length})}const p=new Map;for(const l of b){if(u.runObservesSession.has(l.id))continue;const S=p.get(l.sessionId);S?S.push(l):p.set(l.sessionId,[l])}const m=new Map,v=[];for(const l of b){const S=u.runObservesSession.get(l.id),k=S?p.get(S):void 0;if(!S||!k||k.length===0){if(v.push(l),S){const O=p.get(l.sessionId);O?O.push(l):p.set(l.sessionId,[l])}continue}const T=e.executions.get(l.id);let I=1/0,x=-1/0;for(const O of k){const[U,X]=w(e.executions.get(O.id));I=Math.min(I,U),x=Math.max(x,X)}const[C,_]=w(T),$=m.get(S)??{articulations:[],coincidence:1};$.articulations.push(l.articulation),$.coincidence=Math.min($.coincidence,ds(C,_,I,x)),m.set(S,$)}const d=[];for(const l of[...p.keys()].sort()){const S=p.get(l),k=e.sessions.get(l);if(!k||S.length===0)continue;let T=0,I=0;for(const O of S)T+=O.x,I+=O.y;T/=S.length,I/=S.length;let x=0,C=0;for(const O of S){const U=Rr(O.extent);x=Math.max(x,Math.abs(O.x-T)+U*1.5),C=Math.max(C,Math.abs(O.y-I)+U)}const _=m.get(l),$=Math.max(...S.map(O=>O.articulation));d.push({id:l,massId:S[0].massId,x:T,y:I,extentX:Math.max(x,52),extentY:Math.max(C,36),presence:1,articulation:_?us([$,..._.articulations]):$,parentId:k.parentId,empty:!1,shoulder:_?Math.min(is,1-_.coincidence):0,observers:1+(_?.articulations.length??0),label:k.label??k.executor??l})}for(const l of[...e.sessions.values()].sort((S,k)=>S.id<k.id?-1:1)){if(l.executionIds.length>0||l.endedAt!==void 0&&t-l.endedAt>i)continue;const S=n.get(l.machineId);if(!S)continue;const{x:k,y:T}=ss(S,`session-presence:${l.id}`);d.push({id:l.id,massId:l.machineId,x:k,y:T,extentX:64,extentY:42,presence:1,articulation:u.sessionsWithProcess.has(l.id)?.5:.25,parentId:l.parentId,empty:!0,shoulder:0,observers:1,label:l.label??l.executor??l.id})}if(d.length>rs){const l=S=>S.empty?0:p.get(S.id)?.length??0;d.sort((S,k)=>l(k)-l(S)||(S.id<k.id?-1:1)),d.length=rs}const A=[];for(const l of e.transfers.values())if(l.endedAt===void 0&&!(!n.has(l.fromMachineId)||!n.has(l.toMachineId))){if(A.length>=Nr)break;A.push({id:l.id,fromMassId:l.fromMachineId,toMassId:l.toMachineId,energy:1,label:l.label})}const g=new Map;s.forEach((l,S)=>g.set(l.id,S));const y=Math.max(1,e.dayEnd-e.dayStart),M=[];for(const l of e.executions.values()){const S=g.get(l.machineId);if(S===void 0)continue;const k=(l.startedAt-e.dayStart)/y,T=((l.endedAt??t)-e.dayStart)/y;M.push({id:l.id,massId:l.machineId,lane:S,startFraction:Math.max(0,Math.min(1,k)),endFraction:Math.max(0,Math.min(1,T)),status:l.status,label:l.label})}return{time:t,masses:o,disturbances:v,plinths:d,couplings:A,strata:M}}const sn="057.landscape",nn=1;function Lr(e){return{contract:sn,version:nn,landscape:e}}const vt="SHAPES FIELD",yt="METADATA — DOES NOT SHAPE FIELD";function on(e){const t=new Date(e),s=n=>String(n).padStart(2,"0");return`${s(t.getHours())}:${s(t.getMinutes())}:${s(t.getSeconds())}`}function Ur(e){return H(e).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function Pr(e,t,s,n,o=()=>{}){if(s==="mass")return Wr(e,t,n);if(s==="coupling")return Xr(e,n);const r=e.executions.get(n);return r?Br(e,t,r,s,o("execution",n)):null}function Br(e,t,s,n,o){const r=e.sessions.get(s.sessionId),a=e.machines.get(s.machineId),c=t.disturbances.find(m=>m.id===s.id)?.statusSince??s.endedAt??s.startedAt,u=s.startBasis==="inferred"||s.endBasis==="inferred",h=ue(s.measures),f=[{key:"MACHINE",value:(a?.name??s.machineId).toUpperCase()},{key:"STATE",value:s.status.toUpperCase(),tone:s.status},{key:"SINCE",value:on(c)},h===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:G(h)}];if(r){const m=r.executionIds.indexOf(s.id),v=t.plinths.some(A=>A.id===r.id),d=m>=0?`${m+1} OF ${r.executionIds.length}`:`OF ${r.executionIds.length}`;f.push({key:"SESSION",value:v?`${d} · PLINTH`:d})}const E=Hr(e,s.id),b=[s.model??r?.model?{key:"MODEL",value:s.model??r?.model}:{key:"MODEL",value:"not observed",tone:"absent",note:"This source does not record the model."}];r?.context&&b.push({key:"PROJECT",value:Q(r.context),note:r.context}),b.push({key:"SOURCE",value:[s.executor,E===void 0?void 0:`pid ${E}`].filter(Boolean).join(" · "),note:o}),b.push({key:"REQUESTS",value:String(Zs(s))});const w=Ee(s);if(b.push(w===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:co(w)}),b.push({key:"ELAPSED",value:`${H((s.endedAt??e.now)-s.startedAt)}${u?" · inferred":""}`,note:u?s.boundsAssumption:void 0}),h!==void 0){const m=Js(s.measures);b.push({key:"INPUT",value:G(m.input)},{key:"OUTPUT",value:G(m.output)}),b.push({key:"CACHE READ",value:G(m.cacheRead)},{key:"REASONING",value:G(m.reasoning)})}ct(s)>0&&b.push({key:"TOOL ERRORS",value:String(ct(s)),tone:"failed"}),ut(s)>0&&b.push({key:"RETRIES",value:String(ut(s)),tone:"waiting",note:"Provider retries."}),(s.waits.length>0||s.waitingMs>0)&&b.push({key:"BLOCKED",value:`${H(s.waitingMs)} on you · ${s.waits.length||1}×`,tone:"waiting"}),s.depth>0&&b.push({key:"SUB-AGENT",value:`depth ${s.depth}`});const p=s.status==="running"||s.status==="waiting";return{id:s.id,eyebrow:n==="stratum"||!p?"SELECTED · RUN":"SELECTED · PROCESS",title:s.label.toUpperCase(),state:{text:p?`${s.status.toUpperCase()} · ${Ur(e.now-c)}`:s.status.toUpperCase(),status:s.status},groups:[{title:vt,metadata:!1,rows:f},{title:yt,metadata:!0,rows:b}],failure:s.failure?`${s.failure.code}: ${s.failure.message}`:void 0,reveal:o}}function Hr(e,t){for(const s of e.relationships){if(s.kind!=="ran-as")continue;const n=s.from.type==="execution"&&s.from.id===t&&s.to.type==="process"?s.to.id:s.to.type==="execution"&&s.to.id===t&&s.from.type==="process"?s.from.id:void 0;if(n)return e.processes.get(n)?.pid}}function Wr(e,t,s){const n=e.machines.get(s);if(!n)return null;let o=0,r=0,a=0,i;for(const b of e.executions.values()){if(b.machineId!==n.id)continue;const w=ue(b.measures);w!==void 0&&(i=(i??0)+w),b.status==="running"?o++:b.status==="waiting"?r++:a++}const u=[{key:"KIND",value:(t.masses.find(b=>b.id===s)?.kind??n.kind).toUpperCase()},{key:"RUNNING",value:String(o),tone:o>0?"running":void 0}];r>0&&u.push({key:"WAITING",value:String(r),tone:"waiting"}),u.push({key:"RAN TODAY",value:String(a)});const h=[i===void 0?{key:"TOKENS",value:"not observed",tone:"absent",note:"No execution in this window reported token accounting."}:{key:"TOKENS",value:G(i)}],f=e.processTotals;if(f){const b=new Set;for(const w of e.relationships)w.kind==="ran-as"&&(w.from.type==="process"&&b.add(w.from.id),w.to.type==="process"&&b.add(w.to.id));h.push({key:"PROCESSES",value:`${f.observed} observed`}),h.push({key:"LAST 5 MIN",value:`${f.recentlySeen} seen`,note:"Processes with a liveness observation in the last five minutes. The sampler never witnesses an exit, so recency is the honest liveness signal."}),h.push({key:"ATTRIBUTED",value:`${b.size} of ${f.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const E=o+r;return{id:s,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:E>0?{text:`${E} ACTIVE`,status:o>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:vt,metadata:!1,rows:u},{title:yt,metadata:!0,rows:h}]}}function Xr(e,t){const s=e.transfers.get(t);if(!s)return null;const n=e.machines.get(s.fromMachineId)?.name??s.fromMachineId,o=e.machines.get(s.toMachineId)?.name??s.toMachineId;return{id:t,eyebrow:"SELECTED · TRANSFER",title:`${n} → ${o}`.toUpperCase(),state:{text:"TRANSFERRING",status:"running"},groups:[{title:vt,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:o.toUpperCase()},{key:"SINCE",value:on(s.startedAt)}]},{title:yt,metadata:!0,rows:[{key:"WHAT",value:s.label},{key:"SIZE",value:uo(s.bytes)}]}]}}const Y=e=>({value:e,basis:"measured"}),Ce=(e,t)=>({value:e,basis:"inferred",assumption:t});function wt(e){if(e.length===0)return[];e.sort((s,n)=>s.start-n.start);const t=[{start:e[0].start,end:e[0].end}];for(let s=1;s<e.length;s++){const n=e[s],o=t[t.length-1];n.start<=o.end?n.end>o.end&&(o.end=n.end):t.push({start:n.start,end:n.end})}return t}function ps(e){let t=0;for(const s of e)t+=s.end-s.start;return t}function Gr(e,t){const s=[];let n=0,o=0;for(;n<e.length&&o<t.length;){const r=Math.max(e[n].start,t[o].start),a=Math.min(e[n].end,t[o].end);r<a&&s.push({start:r,end:a}),e[n].end<t[o].end?n++:o++}return s}function rn(e){if(e.length===0)return{peak:0,at:0};const t=[];for(const r of e)t.push({t:r.start,d:1}),t.push({t:r.end,d:-1});t.sort((r,a)=>r.t-a.t||r.d-a.d);let s=0,n=0,o=t[0].t;for(const r of t)s+=r.d,s>n&&(n=s,o=r.t);return{peak:n,at:o}}function qr(e){if(e.length===0)return;const t=[...e].sort((n,o)=>n-o),s=t.length>>1;return t.length%2?t[s]:(t[s-1]+t[s])/2}const an=6e4;function Yr(e,t){return{start:e.startedAt,end:e.endedAt??t}}function Vr(e){const t=[];for(const s of e.executions.values()){s.depth===0&&t.push({start:s.startedAt-an,end:s.startedAt});for(const n of s.waits)t.push({start:n.start,end:n.end});s.waitingSince!==void 0&&t.push({start:s.waitingSince,end:e.now})}return wt(t)}function zr(e){const t=e.now,s=[...e.executions.values()];let n=0,o=0,r=0,a=0,i=0,c=0,u=0,h=0;const f=[],E=new Map;for(const y of s){n+=Zs(y),o+=ue(y.measures)??0,r+=Ee(y)??0,y.status==="completed"?a++:y.status==="failed"?i++:y.status==="waiting"?c++:y.status==="idle"&&u++;const M=Yr(y,t);f.push(M),h+=y.waitingMs,y.waitingSince!==void 0&&(h+=Math.max(0,t-y.waitingSince));let l=E.get(y.machineId);l||(l={machineId:y.machineId,executions:0,tokens:0,computeTime:0},E.set(y.machineId,l)),l.executions++,l.tokens+=ue(y.measures)??0,l.computeTime+=M.end-M.start}const b=wt(f.map(y=>({...y}))),w=Vr(e),p=ps(Gr(b,w)),{peak:m,at:v}=rn(f),d=Kr(e),A=Math.max(0,d.length-1);let g=null;for(const y of d)(!g||y.end-y.start>g.end-g.start)&&(g=y);return{requests:Y(n),sessions:Y(e.sessions.size),executions:Y(s.length),tokens:Y(o),toolCalls:Y(r),autonomousCompute:Ce(ps(b),"Wall-clock time during which at least one run was in flight, merged so parallel runs are not double-counted."),humanAgentOverlap:Ce(p,`Compute time intersecting a window when you were plausibly present: the ${an/1e3}s before you sent a message, and any approval from ask to answer.`),peakConcurrency:Y(m),peakConcurrencyAt:Y(v),contextSwitches:Ce(A,"Transitions between working directories, ordered by time. A directory is the closest thing the source has to a project."),longestFocus:Ce(g,"Longest unbroken stretch spent in one working directory."),waitingOnYou:Y(h),completed:Y(a),failed:Y(i),waiting:Y(c),idle:Y(u),byMachine:E,contextSpans:d,transfers:Y(e.transfers.size)}}function Kr(e){const t=[];for(const n of e.executions.values()){const o=e.sessions.get(n.sessionId);o&&t.push({context:o.context,start:n.startedAt,end:n.endedAt??e.now})}t.sort((n,o)=>n.start-o.start);const s=[];for(const n of t){const o=s[s.length-1];o&&o.context===n.context&&n.start<=o.end?n.end>o.end&&(o.end=n.end):o&&o.context===n.context?n.start-o.end<=Jr?o.end=Math.max(o.end,n.end):s.push({context:n.context,start:n.start,end:n.end}):s.push({context:n.context,start:n.start,end:n.end})}return s}const Jr=15*6e4;function Qr(e){return{key:e,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function Ze(e,t){const s=new Map,n=new Map;for(const o of e.executions.values()){const r=t(o,e.sessions.get(o.sessionId));if(r===void 0)continue;let a=s.get(r);a||(a=Qr(r),s.set(r,a)),a.runs++;const i=ue(o.measures);if(i!==void 0&&(a.tokens+=i,a.tokenRuns++,o.endedAt!==void 0)){let c=n.get(r);c||(c=[],n.set(r,c)),c.push(i)}a.computeMs+=(o.endedAt??e.now)-o.startedAt,a.waitingMs+=o.waitingMs,a.toolCalls+=Ee(o)??0,o.status==="failed"&&a.failed++}for(const[o,r]of n){const a=s.get(o);a&&(a.medianTokens=qr(r),a.medianRuns=r.length)}return[...s.values()].sort((o,r)=>r.computeMs-o.computeMs)}function Zr(e){const t={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const s of e.executions.values()){const n=Js(s.measures);t.input+=n.input,t.output+=n.output,t.cacheRead+=n.cacheRead,t.reasoning+=n.reasoning}return t.total=t.input+t.output+t.cacheRead+t.reasoning,t}function ei(e){const t={count:0,totalMs:0,longestMs:0,openNow:0};for(const s of e.executions.values()){for(const n of s.waits){t.count++;const o=n.end-n.start;t.totalMs+=o,o>t.longestMs&&(t.longestMs=o)}if(s.waitingSince!==void 0){t.openNow++;const n=e.now-s.waitingSince;t.totalMs+=n,n>t.longestMs&&(t.longestMs=n)}}return t}function ti(e){const t={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const s of e.executions.values())t.toolCalls+=Ee(s)??0,t.toolErrors+=ct(s),t.retries+=ut(s),s.status==="failed"?t.failed++:s.outcome==="interrupted"?t.interrupted++:s.outcome==="completed"&&t.completed++;return t}function si(e){const t=[];for(const r of e.executions.values())t.push({start:r.startedAt,end:r.endedAt??e.now});if(t.length===0)return[];const s=wt(t.map(r=>({...r}))),n=new Date(e.dayStart);n.setMinutes(0,0,0);const o=[];for(let r=n.getTime();r<e.now;r+=36e5){const a=r+36e5;let i=0;for(const h of s){const f=Math.max(h.start,r),E=Math.min(h.end,a);E>f&&(i+=E-f)}let c=0;const u=[];for(const h of t)h.start<a&&h.end>r&&(c++,u.push({start:Math.max(h.start,r),end:Math.min(h.end,a)}));o.push({hour:new Date(r).getHours(),runs:c,computeMs:i,peak:rn(u).peak})}return o}const Ue=6e4,ni=60*Ue;function oi(e,t){const s=[],n=t.contextSpans,o=t.longestFocus.value,r=Math.max(1,e.now-e.dayStart),a=t.autonomousCompute.value/r;let i;if(t.executions.value===0)return{headline:"QUIET",clauses:["No computation observed in this window."]};if(t.peakConcurrency.value>=3?i="PARALLEL":n.length>=6?i="FRAGMENTED":o&&o.end-o.start>2*ni?i="SUSTAINED":a<.15?i="SPARSE":i="SERIAL",t.peakConcurrency.value>=2?s.push(`Up to ${t.peakConcurrency.value} runs in flight at once; ${H(t.autonomousCompute.value)} of wall-clock time had computation running.`):s.push(`Runs happened one at a time, across ${H(t.autonomousCompute.value)} of wall-clock time.`),o&&s.push(`The longest unbroken stretch was ${H(o.end-o.start)} in ${Q(o.context)}.`),n.length>1){const c=new Set(n.map(u=>u.context)).size;s.push(`Attention moved ${t.contextSwitches.value} ${t.contextSwitches.value===1?"time":"times"} across ${c} ${c===1?"context":"contexts"}.`)}if(t.waitingOnYou.value>Ue&&s.push(`${H(t.waitingOnYou.value)} was spent with a run waiting on your answer.`),t.humanAgentOverlap.value>Ue){const c=Math.round(t.humanAgentOverlap.value/Math.max(1,t.autonomousCompute.value)*100);s.push(`About ${c}% of that computation overlapped a window when you were present; the rest ran without you.`)}else t.autonomousCompute.value>5*Ue&&s.push("Computation ran almost entirely outside the moments you were present.");if(t.failed.value>0&&s.push(`${t.failed.value} of ${t.executions.value} runs ended in failure; ${t.completed.value} completed.`),t.byMachine.size>1){const c=[...t.byMachine.values()].sort((u,h)=>h.computeTime-u.computeTime).map(u=>`${e.machines.get(u.machineId)?.name??u.machineId} ${H(u.computeTime)}`);s.push(`Compute was split across ${c.join(", ")}.`)}return{headline:i,clauses:s}}const fs="(no model)";function ri(e){if(e.medianTokens===void 0)return{text:"no token accounting",title:"No run in this group reports token accounting, so there is no figure — not a figure of zero.",absent:!0};if(e.medianRuns===1)return{text:`single run ${G(e.medianTokens)}`,title:"One eligible run, so this is that run's figure, not a median. Same window as the rest of TODAY.",absent:!1};const t=e.medianRuns===e.runs?`${e.runs}`:`${e.medianRuns} of ${e.runs}`;return{text:`median ${G(e.medianTokens)} over ${t} runs`,title:`Median billed tokens per run, over the runs in this group that have ended and whose source reports token accounting — ${e.medianRuns} of ${e.runs} here. Runs still in flight are excluded: their totals are partial. Runs whose source persists no accounting are excluded: absence is not zero. Same window as the rest of TODAY.`,absent:!1}}function z(e,t,s,n={}){const o=s?.basis==="inferred";return{key:e,value:t,inferred:o,assumption:o?s?.assumption:void 0,...n}}function et(e,t,s){const n=e[0]?.computeMs??0;return e.map(o=>({key:o.key,label:t(o.key),detail:`${o.runs} ${o.runs===1?"run":"runs"}${o.tokenRuns>0?` · ${G(o.tokens)} tok`:""} · ${H(o.computeMs)}`,failed:o.failed,fraction:n>0?o.computeMs/n:0,median:s?ri(o):void 0}))}function ii(e){const t=zr(e),s=oi(e,t),n=Zr(e),o=ei(e),r=ti(e),a=si(e),i=Ze(e,(g,y)=>y?.context),c=Ze(e,g=>g.model??fs),u=Ze(e,g=>g.machineId),h=[...e.executions.values()],f=h.filter(g=>ue(g.measures)===void 0).length,E=h.filter(g=>g.depth>0).length,b=t.longestFocus.value,w=Math.round(t.humanAgentOverlap.value/Math.max(1,t.autonomousCompute.value)*100),p=[z("REQUESTS",G(t.requests.value),t.requests),z("RUNS",String(t.executions.value),t.executions,{note:E>0?`${E} of them sub-agents`:void 0}),z("SESSIONS",String(t.sessions.value),t.sessions),z("TOKENS",G(t.tokens.value),t.tokens,{note:`${Math.round(n.cacheRead/Math.max(1,n.total)*100)}% cache reads`+(f>0?` · ${f} ${f===1?"run reports":"runs report"} no accounting`:"")}),z("TOOL CALLS",G(r.toolCalls),t.toolCalls,{note:r.toolErrors>0?`${r.toolErrors} failed`:void 0}),z("AUTONOMOUS COMPUTE",H(t.autonomousCompute.value),t.autonomousCompute),z("HUMAN + AGENT OVERLAP",H(t.humanAgentOverlap.value),t.humanAgentOverlap,{note:`${w}% of compute`}),z("PEAK CONCURRENCY",t.peakConcurrency.value>0?`${t.peakConcurrency.value} · ${xe(t.peakConcurrencyAt.value)}`:"0",t.peakConcurrency),z("CONTEXT SWITCHES",String(t.contextSwitches.value),t.contextSwitches,{note:`across ${i.length} ${i.length===1?"context":"contexts"}`}),z("LONGEST FOCUS",b?H(b.end-b.start):"—",t.longestFocus,{note:b?`${Q(b.context)} · ${xe(b.start)}–${xe(b.end)}`:void 0}),z("WAITING ON YOU",H(t.waitingOnYou.value),t.waitingOnYou,{tone:t.waitingOnYou.value>0?"waiting":void 0,note:o.count>0?`${o.count} ${o.count===1?"block":"blocks"} · longest ${H(o.longestMs)}`:void 0}),z("FAILED",String(r.failed),void 0,{tone:r.failed>0?"failed":void 0,note:r.interrupted>0||r.retries>0?`${r.interrupted} stopped · ${r.retries} retries`:void 0})],m=a.length>0?a.reduce((g,y)=>y.computeMs>g.computeMs?y:g,a[0]):void 0,v=g=>`${String(g).padStart(2,"0")}:00`,d=[{title:"WHERE THE TIME WENT",rows:et(i,Q,!1)}];u.length>0&&d.push({title:"BY MACHINE",rows:et(u,g=>e.machines.get(g)?.name??g,!1)}),c.length>0&&d.push({title:"BY MODEL",rows:et(c,g=>g===fs?"model not observed":g,!0)});const A=g=>g/Math.max(1,n.total);return{headline:s.headline,clauses:[...s.clauses],measures:p,hours:a.map(g=>({hour:g.hour,computeMs:g.computeMs,runs:g.runs,peak:g.peak})),busiest:m?`busiest ${v(m.hour)} · ${H(m.computeMs)} of that hour`:void 0,groups:d,tokens:[["CACHE READS",n.cacheRead],["INPUT",n.input],["OUTPUT",n.output],["REASONING",n.reasoning]].map(([g,y])=>({key:g,value:G(y),percent:Math.round(A(y)*100),fraction:A(y)})),tokensNote:"Cache reads are context replayed into each request, not work generated. They dominate the total, which is why the headline token figure is much larger than it feels.",failures:h.filter(g=>g.status==="failed").sort((g,y)=>y.startedAt-g.startedAt).slice(0,12).map(g=>({id:g.id,at:xe(g.startedAt),label:g.label,reason:g.failure?`${g.failure.code}: ${g.failure.message}`:"failed"})),notAvailable:[{key:"COST",text:"Every source here reports tokens or CPU time; none reports money. Converting one to the other needs a price table 057 does not have, so no cost figure is shown anywhere."},{key:"TOKENS, FROM SOME SOURCES",text:"Cursor persists no usage and 0x2F records none; their runs read NOT OBSERVED rather than 0, and the token totals sum only the runs that report."},{key:"MACHINE-TO-MACHINE TRANSFER",text:"Every observed source is single-host. Transfers are modelled and the field renders them, but no real adapter emits one; only the synthetic source does."},{key:"PROCESS EXITS",text:"The OS collector samples; an exit is inferred from disappearance between samples, never witnessed."},{key:"OUTCOME QUALITY",text:"The log records that a run completed, not whether the work was any good."}]}}function ai(e,t){const s=new Set(t.disturbances.map(r=>r.id)),n=new Set(t.strata.map(r=>r.id)),o=[...e.executions.values()].sort((r,a)=>a.startedAt-r.startedAt).map(r=>{const a=e.sessions.get(r.sessionId);return{id:r.id,startedAt:r.startedAt,label:r.label,depth:r.depth,context:a?.context?Q(a.context):null,model:r.model??null,status:r.status,stopped:r.outcome==="interrupted",durationMs:(r.endedAt??e.now)-r.startedAt,inferred:r.startBasis==="inferred"||r.endBasis==="inferred",tokens:ue(r.measures)??null,tools:Ee(r)??null,waitedMs:r.waitingMs,inField:s.has(r.id)?"disturbance":n.has(r.id)?"stratum":null}});return{now:e.now,rows:o}}const At={[sn]:nn};function St(e){return`${e}.core.json`}function cn(e){const t=St(e);if(!L(t))return null;try{const s=JSON.parse(wn(t,"utf8"));return typeof s.pid!="number"||typeof s.url!="string"?null:s}catch{return null}}function ci(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function ui(e,t=1500){const s=cn(e);if(!s||s.pid===process.pid||!ci(s.pid))return null;try{const n=await fetch(`${s.url}/api/health`,{signal:AbortSignal.timeout(t)});return n.ok&&(await n.json()).pid===s.pid?s:null}catch{return null}}function di(e,t){if(e===":memory:")return;const s=St(e),n=`${s}.${process.pid}.tmp`;vn(n,`${JSON.stringify(t,null,1)}
|
|
9
|
+
`,{mode:384}),yn(n,s)}function li(e,t=process.pid){if(e===":memory:")return;const s=cn(e);s&&s.pid===t&&Ms(St(e),{force:!0})}class Et extends Error{constructor(t){super(`057 is already observing ${t.store} at ${t.url} (pid ${t.pid})`),this.record=t}record}const dt={processDays:7,eventDays:90},pi=["machine"],ms=["process"],tt={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},fi=["execution","session","artifact"];function un(e=process.env){return{processDays:hs(e.O57_RETAIN_PROCESS_DAYS,dt.processDays),eventDays:hs(e.O57_RETAIN_DAYS,dt.eventDays)}}function hs(e,t){if(e===void 0||e.trim()==="")return t;const s=Number(e);return Number.isFinite(s)&&s>=0?s:t}function Ye(e){const t=(s,n)=>s===0?`${n} kept indefinitely`:`${n} ${s}d`;return`${t(e.processDays,"processes")}, ${t(e.eventDays,"sessions/executions")}, machines never expire`}const gs=448,mi=384;function hi(){return D(he(),".057")}function Ve(){const e=process.env.O57_STORE;return e&&e.length>0?e===":memory:"||Tn(e)?e:Re(process.cwd(),e):D(hi(),"events.db")}function dn(){const e=process.env.O57_STORE;return typeof e=="string"&&e.length>0}function ze(e){return[e,`${e}-wal`,`${e}-shm`]}function gi(e){if(e===":memory:")return;const t=Mn(e);An(t,{recursive:!0,mode:gs}),ln(t,gs)}function lt(e){if(e===":memory:")return[];const t=[];for(const s of ze(e))if(L(s)&&!ln(s,mi)){const n=kt(s);n!==null&&(n&63)!==0&&t.push({path:s,mode:n})}return t}function kt(e){try{return qe(e).mode&511}catch{return null}}function ln(e,t){if(process.platform==="win32")return!1;const s=kt(e);if(s===null)return!1;if((s&~t)===0)return!0;try{return Sn(e,t),!0}catch{return!1}}function pn(){if(dn())return null;const e=Re(process.cwd(),".057","events.db");return L(e)&&e!==Ve()?e:null}const bi=`-- 057 local store.
|
|
8
10
|
--
|
|
9
11
|
-- \`events\` is the only durable truth. \`claims\` is denormalized out of events so identity
|
|
10
12
|
-- resolution is one indexed read rather than a scan; it is rebuildable from events at any time.
|
|
@@ -55,24 +57,24 @@ CREATE TABLE IF NOT EXISTS claims (
|
|
|
55
57
|
CREATE INDEX IF NOT EXISTS claims_key ON claims(key, valid_from, valid_to);
|
|
56
58
|
CREATE INDEX IF NOT EXISTS claims_window ON claims(valid_to, valid_from);
|
|
57
59
|
CREATE INDEX IF NOT EXISTS claims_event ON claims(event_id);
|
|
58
|
-
`,ke=1;class
|
|
60
|
+
`,ke=1;class fe extends Error{constructor(t,s,n){super(t),this.kind=s,this.remedy=n,this.name="StoreError"}kind;remedy}function st(e){const t=e?.code;if(t==="EACCES"||t==="EPERM"||t==="EROFS")return!0;const s=e instanceof Error?e.message:String(e);return/readonly|read-only|attempt to write a readonly database|unable to open database file|permission denied|SQLITE_(READONLY|PERM|CANTOPEN)/i.test(s)}function nt(e,t){const s=t instanceof Error?t.message:String(t);return new fe(`store ${e} cannot be written: ${s}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory and that both are writable (057 needs 0600 on the store and 0700 on its directory), or point O57_STORE at a writable path.")}function vi(e){gi(e);let t;try{t=new ft(e)}catch(p){throw st(p)?nt(e,p):new fe(`cannot open the store at ${e}: ${p instanceof Error?p.message:String(p)}`,"unreadable","Check that the path exists and names a file 057 can open, or point O57_STORE elsewhere.")}let s;try{s=Number(t.prepare("PRAGMA user_version").get().user_version)}catch(p){throw t.close(),st(p)?nt(e,p):new fe(`store ${e} is not a readable database: ${p instanceof Error?p.message:String(p)}`,"unreadable","The file exists but is not a 057 store. Move it aside and 057 will start a new one; `057 reset` does that for you. Back it up first if it might be data you want.")}if(s>ke)throw t.close(),new fe(`store ${e} was written by a newer 057 (schema ${s}, this build understands ${ke})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{t.exec(bi);const p=new Set(t.prepare("PRAGMA table_info(events)").all().map(m=>String(m.name)));p.has("stratum")||t.exec("ALTER TABLE events ADD COLUMN stratum TEXT"),p.has("provenance")||t.exec("ALTER TABLE events ADD COLUMN provenance TEXT"),s!==ke&&t.exec(`PRAGMA user_version = ${ke}`)}catch(p){t.close();const m=p instanceof Error?p.message:String(p);throw st(p)?nt(e,p):new fe(`store ${e} could not be prepared: ${m}`,"unreadable","The file may be corrupt. Back it up, then move it aside and 057 will start a new store; `057 reset` does that for you.")}lt(e);const n=1e3,o=new Set,r=new Set;let a=null;const i=(p,m)=>{r.add(p),a??=Date.now(),o.size<n&&o.add(m)},c=p=>wi(p,i),u=t.prepare(`INSERT OR IGNORE INTO events
|
|
59
61
|
(id, source_id, source_instance, occurred_at, observed_at, clock, kind,
|
|
60
62
|
subject_type, subject_id, core, attrs, basis, assumption, stratum, provenance)
|
|
61
|
-
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),
|
|
63
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),h=t.prepare(`INSERT INTO claims
|
|
62
64
|
(event_id, key, ns, subject_type, subject_id, source_id, valid_from, valid_to)
|
|
63
|
-
VALUES (?,?,?,?,?,?,?,?)`),
|
|
64
|
-
FROM claims WHERE valid_from <= ? AND valid_to >= ?`),
|
|
65
|
+
VALUES (?,?,?,?,?,?,?,?)`),f=t.prepare("SELECT * FROM events WHERE occurred_at >= ? AND occurred_at <= ? ORDER BY occurred_at, id"),E=new Map,b=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
|
|
66
|
+
FROM claims WHERE valid_from <= ? AND valid_to >= ?`),w={path:e,schemaVersion:ke,append(p){let m=0,v=0;t.exec("BEGIN");try{for(const d of p){if(u.run(d.id,d.source.id,d.source.instance,d.occurredAt,d.observedAt,d.clock,d.kind,d.subject.type,d.subject.id,d.core?JSON.stringify(d.core):null,d.attrs?JSON.stringify(d.attrs):null,d.basis,d.assumption??null,d.stratum??null,d.provenance?JSON.stringify(d.provenance):null).changes===0){v++;continue}m++;for(const g of d.claims??[])h.run(d.id,Ln(g),g.ns,d.subject.type,d.subject.id,d.source.id,g.validFrom,g.validTo)}t.exec("COMMIT")}catch(d){throw t.exec("ROLLBACK"),d}return{inserted:m,duplicate:v}},query(p,m,v){if(!v||v.length===0)return f.all(p,m).map(c);const d=[...v].sort().join(",");let A=E.get(d);if(!A){const g=v.map(()=>"?").join(",");A=t.prepare(`SELECT * FROM events
|
|
65
67
|
WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${g})
|
|
66
|
-
ORDER BY occurred_at, id`),E.set(
|
|
67
|
-
FROM events GROUP BY source_id ORDER BY s`).all().map(
|
|
68
|
+
ORDER BY occurred_at, id`),E.set(d,A)}return A.all(p,m,...v).map(c)},claims(p,m){return b.all(m,p).map(v=>{const d=v;return{key:String(d.key),subjectType:d.subject_type,subjectId:String(d.subject_id),sourceId:String(d.source_id),validFrom:Number(d.valid_from),validTo:Number(d.valid_to)}})},stats(){const p=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),m=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),v=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),d=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
|
|
69
|
+
FROM events GROUP BY source_id ORDER BY s`).all().map(A=>{const g=A;return{source:String(g.s),events:Number(g.c),first:Number(g.lo),last:Number(g.hi)}});return{events:p,claims:m,bySource:d,earliest:v.lo,latest:v.hi}},begansFor(p){const m=[],v=t.prepare(`SELECT * FROM events
|
|
68
70
|
WHERE kind = 'began' AND subject_type = ? AND subject_id = ?
|
|
69
|
-
ORDER BY occurred_at LIMIT 1`);for(const
|
|
70
|
-
FROM events GROUP BY subject_type, subject_id`).all().map(
|
|
71
|
-
WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),
|
|
72
|
-
(SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`)
|
|
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(
|
|
75
|
-
`)}catch(b){t.error(`[057] request failed: ${String(b)}`),E.headersSent||(E.statusCode=500),E.end()}})()}),
|
|
71
|
+
ORDER BY occurred_at LIMIT 1`);for(const d of p){const A=d.indexOf(":");if(A<0)continue;const g=v.get(d.slice(0,A),d.slice(A+1));g&&m.push(c(g))}return m},subjectEvents(p,m){return t.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(p,m).map(c)},latestFor(p){return t.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(p)?.hi??null},sweep(p=dt,m=Date.now()){const v=p.processDays>0?m-p.processDays*864e5:null,d=p.eventDays>0?m-p.eventDays*864e5:null;if(v===null&&d===null)return{...tt};const A=j=>pi.includes(j)?null:ms.includes(j)?v:d,g=t.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
|
|
72
|
+
FROM events GROUP BY subject_type, subject_id`).all().map(j=>{const N=j;return{type:String(N.t),id:String(N.i),last:Number(N.last)}}),y=(j,N)=>`${j}:${N}`,M=new Set,l=new Map;for(const j of g){const N=A(j.type);N===null||j.last>=N?M.add(y(j.type,j.id)):l.set(y(j.type,j.id),{type:j.type,id:j.id})}if(l.size===0)return{...tt,processBefore:v,otherBefore:d};const S=[...fi],k=t.prepare(`SELECT DISTINCT core FROM events
|
|
73
|
+
WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),T=new Set(S);let I=[...M].filter(j=>T.has(j.slice(0,j.indexOf(":"))));const x=new Set(I);let C=0;for(let j=0;j<4&&I.length>0;j++){const N=[];for(const V of I){const K=V.indexOf(":");for(const gn of k.all(V.slice(0,K),V.slice(K+1))){const $t=Pe(gn.core);if($t)for(const[bn,Rt]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const xt=$t[bn];if(typeof xt!="string")continue;const be=y(Rt,xt);l.has(be)&&(l.delete(be),M.add(be),C++,!x.has(be)&&T.has(Rt)&&(x.add(be),N.push(be)))}}}I=N}if(l.size===0)return{...tt,retainedByDependents:C,processBefore:v,otherBefore:d};const _=t.prepare(`DELETE FROM claims WHERE event_id IN
|
|
74
|
+
(SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),$=t.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let O=0,U=0,X=0;t.exec("BEGIN");try{for(const{type:j,id:N}of l.values()){X+=Number(_.run(j,N).changes);const V=Number($.run(j,N).changes);ms.includes(j)?O+=V:U+=V}t.exec("COMMIT")}catch(j){throw t.exec("ROLLBACK"),j}return O+U>0&&w.checkpoint(),{processEvents:O,otherEvents:U,claims:X,subjects:l.size,retainedByDependents:C,processBefore:v,otherBefore:d}},checkpoint(){try{t.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes(){const[p,m,v]=ze(e).map(yi);return{db:p,wal:m,shm:v,total:p+m+v}},health(){const p=o.size;return p===0?{ok:!0,malformedRows:0,columns:[],since:null}:{ok:!1,malformedRows:p,columns:[...r].sort(),since:a,remedy:`${p} stored row(s) could not be read as JSON and lost their ${[...r].sort().join("/")} channel. Everything else is being used normally and nothing has been deleted. Run \`057 compact\` to rewrite the store; if the count keeps growing, back the store up and run \`057 reset\` to start a new one.`}},compact(){t.exec("VACUUM"),w.checkpoint(),lt(e)},close(){w.checkpoint(),t.close()}};return w}function yi(e){try{return qe(e).size}catch{return 0}}function Pe(e,t,s){if(e!=null)try{const n=JSON.parse(String(e));if(n&&typeof n=="object")return n;t&&s?.(t);return}catch{t&&s?.(t);return}}function wi(e,t){const s=e,n=t?o=>t(o,String(s.id)):void 0;return{id:String(s.id),source:{id:String(s.source_id),instance:String(s.source_instance)},occurredAt:Number(s.occurred_at),observedAt:Number(s.observed_at),clock:s.clock,kind:s.kind,subject:{type:s.subject_type,id:String(s.subject_id)},core:Pe(s.core,"core",n),attrs:Pe(s.attrs,"attrs",n),basis:s.basis,assumption:s.assumption?String(s.assumption):void 0,stratum:s.stratum?s.stratum:void 0,provenance:Pe(s.provenance,"provenance",n)}}const Ai=Fn(Dn);function Si(){return $s()}function Ei(e){const t=[];for(const s of e.split(`
|
|
75
|
+
`)){const n=s.trim();if(!n)continue;const o=n.match(/^(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+([\d:.]+)\s+(\d+)\s+(.*)$/);if(!o)continue;const[,r,a,i,c,u,h]=o,f=Date.parse(i);Number.isFinite(f)&&t.push({pid:Number(r),ppid:Number(a),startedAt:f,cpuMs:ki(c),rssBytes:Number(u)*1024,command:h.trim()})}return t}function ki(e){const[t,s]=e.includes("-")?e.split("-"):["0",e],n=s.split(":").map(Number);let o=0;for(const r of n)o=o*60+(Number.isFinite(r)?r:0);return Math.round((o+Number(t)*86400)*1e3)}async function Ii(){const{stdout:e}=await Ai("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return Ei(e)}const bs=5e3;function Ti(e,t){const s=Si();let n=new Map,o=null,r=0,a=null,i,c=!1;async function u(){if(c)return[];c=!0;try{const h=await Ii(),f=Date.now(),{envelopes:E,next:b}=pr(n,h,{machineId:t,host:s,observedAt:f,intervalMs:bs}),w=E.map(se);return e.append(w),n=b,r++,a=f,i=void 0,w}catch(h){return i=h instanceof Error?h.message:String(h),[]}finally{c=!1}}return{sample:u,start(){o||(u(),o=setInterval(()=>{u()},bs),o.unref?.())},stop(){o&&clearInterval(o),o=null},get running(){return o!==null},stats(){return{samples:r,tracked:n.size,lastSampleAt:a,lastError:i}}}}const fn={info:e=>console.log(e),warn:e=>console.warn(e),error:e=>console.error(e)},Mi=36e5,Oi=15e3,$i=3;function It(e={}){const t=e.log??fn,s=e.path??Ve(),n=e.retention??un(),o=vi(s),r=o.stats();t.info(r.events>0?`[057] store ${s}: opened with ${r.events} events`:`[057] store ${s}: NEW EMPTY STORE — if history existed before, it was lost, not carried`);const a=pn();a&&t.warn(`[057] a store from a previous layout exists at ${a} and is NOT in use. Run 057 with O57_STORE=${a} to keep using it, or move it to ${s}.`);const i=ge();o.append([se({source:{id:"host",instance:i.id},occurredAt:0,observedAt:Date.now(),clock:"wall",kind:"began",stratum:"machine",subject:{type:"machine",id:i.id},basis:"measured",core:{machineName:i.name,machineKind:i.kind},seq:"host"})]);const c=Ti(o,i.id),u=new Map;function h(d){for(const A of d){const g=u.get(A.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};A.ok?(g.consecutiveFailures=0,g.failing=!1,g.failingSince=void 0,g.lastSuccessAt=Date.now()):(g.consecutiveFailures===0&&(g.failingSince=Date.now()),g.consecutiveFailures++,g.totalFailures++,g.lastFailureAt=Date.now(),g.lastError=A.error,g.consecutiveFailures>=$i&&!g.failing&&(g.failing=!0,t.warn(`[057] source ${A.id} has failed ${g.consecutiveFailures} collection rounds in a row: ${A.error??"unknown error"}`))),u.set(A.id,g)}}const f=vs(s);let E=null;function b(d){return E||(E=d,t.error(`[057] ${d.message} — ${d.remedy}`),c.stop()),E}function w(){if(E)return E;if(s===":memory:")return null;if(!L(s))return b({kind:"unlinked",message:`the store at ${s} no longer exists on disk; captured events are going to an orphaned file and will be lost`,remedy:"Stop 057 and start it again. It will open a new store at the same path.",since:Date.now()});const d=vs(s);return f!==null&&d!==null&&d!==f?b({kind:"replaced",message:`the store at ${s} was replaced by a different file while 057 was running; captured events are going to the old one`,remedy:"Stop 057 and start it again so it opens the file that is actually there.",since:Date.now()}):null}e.observe!==!1&&c.start();const p=o.sweep(n);p.processEvents+p.otherEvents>0&&t.info(`[057] retention: removed ${p.processEvents} process and ${p.otherEvents} semantic events (${Ye(n)})`);const m=setInterval(()=>{if(!E)try{o.sweep(n),lt(s)}catch(d){t.warn(`[057] retention sweep failed: ${String(d)}`)}},Mi);m.unref?.();const v=setInterval(()=>{w()},Oi);return v.unref?.(),{store:o,machine:i,os:c,path:s,retention:n,fault:()=>E,sweep:d=>o.sweep(n,d),checkStore:w,recordCollection:h,collectionHealth:()=>Object.fromEntries(u),stop(){clearInterval(m),clearInterval(v),c.stop(),o.close()}}}function vs(e){try{return qe(e).ino}catch{return null}}const pt=[{id:Os,collect:(e,t)=>ao(e,t)},{id:rt,collect:(e,t)=>Ao(e,t)},{id:Se,collect:(e,t)=>No(e,t)},{id:De,collect:(e,t)=>Bo(e,t)},{id:Oe,collect:(e,t)=>zo(e,t)},{id:Le,collect:(e,t)=>ir(e,t)}],ys=[...pt.map(e=>e.id),pe],ws=10*365*24*36e5,je=2e5,Ri=24*36e5,xi=72*36e5;function As(e){const t=new Date(e);return t.setHours(0,0,0,0),{from:t.getTime(),to:e}}function Ss(e){const t=e.collectionHealth(),s=Object.entries(t).filter(([,i])=>i.failing).map(([i])=>i),n=e.store.health(),o=e.os.stats(),r=e.fault();let a=null;for(const i of Object.values(t))i.lastSuccessAt&&(a===null||i.lastSuccessAt>a)&&(a=i.lastSuccessAt);return{ok:s.length===0&&n.ok&&!r&&!o.lastError,fault:r??void 0,failingSources:s,errors:Object.fromEntries(Object.entries(t).filter(([,i])=>i.failing).map(([i,c])=>[i,c.lastError??"failing"])),failing:Object.fromEntries(Object.entries(t).filter(([,i])=>i.failing).map(([i,c])=>[i,{since:c.failingSince??null,rounds:c.consecutiveFailures}])),store:{ok:n.ok,remedy:n.remedy},os:{running:e.os.running,lastSampleAt:o.lastSampleAt,lastError:o.lastError},lastCollectionAt:a,sources:{total:ys.length,reported:ys.filter(i=>t[i]!==void 0).length}}}function Ni(e,t,s){const n=t.startsWith("/api/");if(s){const i=(e.headers.host??"").toLowerCase(),c=i.startsWith("[")?i.slice(0,i.indexOf("]")+1):i.split(":")[0];if(!s.includes(c))return`refusing a request for host "${i}"; 057 answers only on ${s.join(", ")}`}const o=e.headers.origin;if(typeof o=="string"&&o!=="null"){const i=(e.headers.host??"").toLowerCase();let c="";try{c=new URL(o).host.toLowerCase()}catch{return"refusing a request with an unparseable Origin"}if(c!==i)return`refusing a cross-origin request from ${o}`}const r=e.headers["sec-fetch-site"],a=String(e.headers["sec-fetch-dest"]??"");if(Ci.has(a))return`refusing to be embedded as ${a}`;if(typeof r=="string"&&r!==""){if(r!=="same-origin"&&r!=="none")return`refusing a ${r} request`;if(r==="none"&&n)return"refusing a directly-navigated API request"}else if(n&&t==="/api/collect"&&!e.headers[_i])return"refusing a state-changing request that carries no fetch metadata";return null}const _i="x-057-client",Ci=new Set(["iframe","frame","embed","object","fencedframe"]);function Tt(e){e.setHeader("x-frame-options","DENY"),e.setHeader("content-security-policy","frame-ancestors 'none'")}function ji(e,t){const s=(r,a)=>{const i=e.get(r);if(i===null||i==="")return a;const c=Number(i);return Number.isSafeInteger(c)?c:null},n=s("from",t-864e5),o=s("to",t);return n===null||o===null?{error:"from and to must be integer epoch millis"}:o<n?{error:"to must not precede from"}:o>t+Ri?{error:"to is too far in the future"}:o-n>ws?{error:`window must not exceed ${ws} ms`}:{from:n,to:o}}function B(e,t,s){e.statusCode=t,e.setHeader("content-type","application/json"),e.setHeader("cache-control","no-store"),e.setHeader("x-content-type-options","nosniff"),Tt(e),e.end(JSON.stringify(s))}function mn(e,t,s,n,o){const r=o?Di(o):void 0,a=r?Es(e.query(t,s,n),r):e.query(t,s,n),i=new Set,c=new Set,u=E=>{const b=`${E.subject.type}:${E.subject.id}`;E.kind==="began"?i.add(b):c.add(b),E.core?.sessionId&&c.add(`session:${E.core.sessionId}`),E.core?.machineId&&c.add(`machine:${E.core.machineId}`)};for(const E of a)u(E);const h=[];for(let E=0;E<4;E++){const b=[...c].filter(p=>!i.has(p));if(b.length===0)break;const w=r?Es(e.begansFor(b),r):e.begansFor(b);if(w.length===0)break;for(const p of w)h.push(p.occurredAt<t?{...p,occurredAt:t}:p),u(p),i.add(`${p.subject.type}:${p.subject.id}`)}return{events:[...h,...a].sort((E,b)=>E.occurredAt-b.occurredAt||ks(E)-ks(b)),relationships:Vn(e,t,s).relationships}}function Di(e){const t=to(e);return s=>{if(s.subject.type==="machine")return s.subject.id!==e&&jt(s.subject.id)?null:s;const n=s.core?.machineId;if(!n||n===e||!jt(n))return s;const o=s.subject.type==="process"&&t?cr(s.subject.id,t):void 0;return{...s,...o?{subject:{...s.subject,id:o}}:{},core:{...s.core,machineId:e}}}}function Es(e,t){const s=[];for(const n of e){const o=t(n);o&&s.push(o)}return s}function Ie(e,t,s,n){const o=performance.now(),{events:r,relationships:a}=mn(e,t,s,void 0,n),i=performance.now()-o,c=performance.now(),u=tn(t,s);Ar(u,r),Sr(u,s);const h=performance.now()-c,f=performance.now(),E=Ir(u,a),b=performance.now()-f;return{world:E,meta:{events:r.length,readMs:Math.round(i*10)/10,deriveMs:Math.round(h*10)/10,serializeMs:Math.round(b*10)/10}}}function ks(e){if(e.kind==="ended")return 5;switch(e.subject.type){case"machine":return 0;case"session":return 1;case"execution":case"process":return e.kind==="began"?2:3;default:return 4}}function Fi(e){const t=e.problems.filter(s=>s.path.includes("/sessions/")).length;return{identity:e.identityAvailable?t===0?"available":e.registryEntries>0?"partial":"failed":"unavailable","stored-semantics":e.storedAvailable?e.transcriptsFailed===0?"available":e.transcriptsRead>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function ot(e){return{"stored-semantics":e.storedAvailable?e.failed===0?"available":e.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function Li(e){return e.error?"failed":e.available?"observing":e.present?"installed-no-data":"not-installed"}function Ui(e){const t=e.home??e.globalStorage;if(typeof t=="string")return t;const s=e.roots;return Array.isArray(s)?s.join(", "):void 0}function le(e){return{available:e.available,present:e.present??!1,presence:Li(e),origin:Ui(e),error:e.error}}function Pi(e){const{runtime:t,log:s}=e;let n=null;function o(r){if(!n||r-n.at>6e4){const a=As(r),i=ts(Ie(t.store,a.from,a.to,t.machine.id).world);n={at:r,label:"TODAY",world:i,landscape:ls(i)}}return n}return async function(a,i){const c=a.url??"";if(!c.startsWith("/api/"))return!1;const u=new URL(c,"http://localhost"),h=Ni(a,u.pathname,e.allowedHosts);if(h)return s.warn(`[057] ${h}`),B(i,403,{error:h}),!0;const f=t.store,E=Date.now(),b=ji(u.searchParams,E);if("error"in b)return B(i,400,{error:b.error}),!0;const{from:w,to:p}=b;try{if(u.pathname==="/api/state"){const[m,v,d,A,g,y]=await Promise.all([Ft().catch(N=>({available:!1,error:String(N)})),Ht().catch(N=>({available:!1,error:String(N)})),Xt().catch(N=>({available:!1,error:String(N)})),qt().catch(N=>({available:!1,error:String(N)})),Kt().catch(N=>({available:!1,error:String(N)})),Qt().catch(N=>({available:!1,error:String(N)}))]),[M,l,S,k]=await Promise.all([Us(w,p).catch(()=>null),Ws(w,p).catch(()=>null),qs(w,p).catch(()=>null),Ks(w,p).catch(()=>null)]),T={strata:{"stored-semantics":"failed"}},I={"claude-code":M?{strata:Fi(M),registryEntries:M.registryEntries,transcriptsRead:M.transcriptsRead,transcriptsFailed:M.transcriptsFailed,problems:M.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:l?{strata:ot({storedAvailable:l.storedAvailable,read:l.rolloutsRead,failed:l.rolloutsFailed}),rolloutsRead:l.rolloutsRead,rolloutsFailed:l.rolloutsFailed,problems:l.problems.slice(0,20)}:T,cursor:S?{strata:ot({storedAvailable:S.storedAvailable,read:S.composersRead,failed:S.composersFailed}),composersRead:S.composersRead,composersFailed:S.composersFailed,problems:S.problems.slice(0,20)}:T,gemini:k?{strata:ot({storedAvailable:k.storedAvailable,read:k.sessionsRead,failed:k.sessionsFailed}),sessionsRead:k.sessionsRead,sessionsFailed:k.sessionsFailed,problems:k.problems.slice(0,20)}:T},x={deepseek:le(m),"0x2f":le(v),"claude-code":le(d),codex:le(A),cursor:le(g),gemini:le(y)},C=t.collectionHealth();for(const[N,V]of Object.entries(x)){const K=C[N];K?.failing&&(V.presence="failed",V.error??=K.lastError)}const _=t.os.stats(),O=Object.values(x).filter(N=>N.available).length>0?"observing":_.samples>0?"os-only":"empty",U=Object.entries(C).filter(([,N])=>N.failing).map(([N])=>N),X=f.health(),j={ok:U.length===0&&X.ok&&!t.fault()&&!_.lastError,failingSources:U,collection:C,store:X,os:_.lastError?{failing:!0,lastError:_.lastError}:{failing:!1}};return B(i,200,{machine:t.machine,mode:O,fault:t.fault()??void 0,health:j,store:{...f.stats(),path:f.path,schemaVersion:f.schemaVersion,bytes:f.sizeBytes(),retention:{...t.retention,description:Ye(t.retention)}},os:{..._,running:t.os.running,source:pe},sources:x,observation:I}),!0}if(u.pathname==="/api/collect"){const m=t.checkStore();if(m)return B(i,503,{error:m.message,fault:m}),!0;const v=await Yn(f,pt,w,p,A=>t.recordCollection([A])),d=await t.os.sample();return t.recordCollection([{id:pe,ok:!t.os.stats().lastError,error:t.os.stats().lastError}]),B(i,200,{...v,sources:[...v.sources,{id:pe,ok:!t.os.stats().lastError,collected:d.length,inserted:d.length,duplicate:0,error:t.os.stats().lastError,ms:0}]}),!0}if(u.pathname==="/api/world")return B(i,200,{from:w,to:p,now:E,...Ie(f,w,p,t.machine.id)}),!0;if(u.pathname==="/api/health")return B(i,200,{pid:process.pid,version:e.version??"dev",contract:At,store:t.path,health:Ss(t)}),!0;if(u.pathname==="/api/landscape"){let m={from:w,to:p},v="WINDOW",d;if(u.searchParams.get("window")==="live"){if(m=As(E),v="TODAY",d=Ie(f,m.from,m.to,t.machine.id),d.world.executions.length===0&&d.world.sessions.length===0){const y={from:E-xi,to:E},M=Ie(f,y.from,y.to,t.machine.id);(M.world.executions.length>0||M.world.sessions.length>0)&&(m=y,v="LAST 72H",d=M)}}else d=Ie(f,w,p,t.machine.id);const A=ts(d.world),g=ls(A);return u.searchParams.get("window")==="live"&&(n={at:E,label:v,world:A,landscape:g}),B(i,200,{...m,now:E,window:v,meta:d.meta,health:Ss(t),...Lr(g)}),!0}if(u.pathname==="/api/today"||u.pathname==="/api/log"){const m=o(E);return B(i,200,u.pathname==="/api/today"?{window:m.label,...ii(m.world)}:{window:m.label,...ai(m.world,m.landscape)}),!0}if(u.pathname==="/api/inspect"){const m=u.searchParams.get("kind")??"",v=u.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(m)||!v||v.length>512)return B(i,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;if(o(E),!n)return!0;const d=(g,y)=>{for(const M of f.subjectEvents(g,y))if(M.provenance?.path)return M.provenance.path},A=Pr(n.world,n.landscape,m,v,d);return A?(B(i,200,A),!0):(B(i,404,{error:"not in the current world"}),!0)}if(u.pathname==="/api/sources"){const m=await Promise.all([Ft().catch(g=>({available:!1,error:String(g)})),Ht().catch(g=>({available:!1,error:String(g)})),Xt().catch(g=>({available:!1,error:String(g)})),qt().catch(g=>({available:!1,error:String(g)})),Kt().catch(g=>({available:!1,error:String(g)})),Qt().catch(g=>({available:!1,error:String(g)}))]),v=t.collectionHealth(),d=t.os.stats(),A=pt.map((g,y)=>{const M=le(m[y]),l=v[g.id];return{id:g.id,presence:l?.failing?"failed":M.presence,origin:M.origin,error:l?.failing?l.lastError??M.error:M.error,consecutiveFailures:l?.consecutiveFailures??0,lastSuccessAt:l?.lastSuccessAt}});return A.push({id:pe,presence:d.lastError?"failed":d.samples>0?"observing":"installed-no-data",origin:void 0,error:d.lastError,consecutiveFailures:v[pe]?.consecutiveFailures??0,lastSuccessAt:d.lastSampleAt??void 0}),B(i,200,{sources:A}),!0}if(u.pathname==="/api/detail"){const m=u.searchParams.get("type")??"",v=u.searchParams.get("id")??"";if(!Nt.includes(m)||!v)return B(i,400,{error:"detail needs type=<entity type> and id"}),!0;if(v.length>512)return B(i,400,{error:"id is too long"}),!0;const d=f.subjectEvents(m,v);return B(i,200,{type:m,id:v,events:d.slice(0,je),truncated:d.length>je}),!0}if(u.pathname==="/api/events"){const m=u.searchParams.get("subject"),v=m?m.split(",").filter(A=>Nt.includes(A)):void 0,d=mn(f,w,p,v,t.machine.id);return B(i,200,{from:w,to:p,now:E,events:d.events.slice(0,je),truncated:d.events.length>je,relationships:d.relationships}),!0}return B(i,404,{error:"unknown endpoint"}),!0}catch(m){return s.error(`[057] ${String(m)}`),B(i,500,{error:String(m)}),!0}}}const Mt=5057,ce="127.0.0.1",Bi=["localhost","127.0.0.1","[::1]","::1"],Hi=10,Wi={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".woff2":"font/woff2",".png":"image/png",".ico":"image/vnd.microsoft.icon"};function Is(e,t,s){let n;try{n=decodeURIComponent(t)}catch{return!1}if(n.includes("\0"))return!1;const o=Re(e,`.${On(n)}`);if(o!==e&&!o.startsWith(e+$n)||!L(o)||!qe(o).isFile())return!1;const r=Wi[Rn(o).toLowerCase()]??"application/octet-stream";return s.statusCode=200,s.setHeader("content-type",r),s.setHeader("x-content-type-options","nosniff"),Tt(s),s.setHeader("cache-control",t.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),En(o).pipe(s),!0}function Xi(e,t,s,n){return new Promise((o,r)=>{let a=n,i=t;const c=u=>{if(u.code==="EADDRINUSE"&&a>1){a--,i++,e.listen(i,s);return}e.off("error",c),r(u)};e.on("error",c),e.once("listening",()=>{e.off("error",c);const u=e.address();o(typeof u=="object"&&u?u.port:i)}),e.listen(i,s)})}function Gi(e,t){const s=String(e.headers["sec-fetch-dest"]??"");if(qi.has(s))return`refusing to be embedded as ${s}`;const n=e.headers["sec-fetch-site"];return typeof n=="string"&&n!==""&&n!=="same-origin"&&n!=="none"?`refusing a ${n} request for ${t}`:null}const qi=new Set(["iframe","frame","embed","object","fencedframe"]);async function hn(e){const t=e.log??fn,s=Re(e.root),n=e.host??ce,o=n===ce||n==="::1"||n==="localhost",r=e.runtime?.path??e.storePath??Ve();if(!e.runtime){const f=await ui(r);if(f)throw new Et(f)}const a=e.runtime??It({path:e.storePath,log:t,retention:e.retention,observe:e.observe}),i=Pi({runtime:a,log:t,version:e.version,allowedHosts:o?Bi:null}),c=In((f,E)=>{(async()=>{try{if(await i(f,E))return;if(f.method!=="GET"&&f.method!=="HEAD"){E.statusCode=405,E.setHeader("allow","GET, HEAD"),E.end();return}const b=new URL(f.url??"/","http://localhost").pathname,w=Gi(f,b);if(w){t.warn(`[057] ${w}`),E.statusCode=403,E.setHeader("content-type","text/plain; charset=utf-8"),Tt(E),E.end(`${w}
|
|
76
|
+
`);return}if(Is(s,b==="/"?"/index.html":b,E)||!b.startsWith("/assets/")&&Is(s,"/index.html",E))return;E.statusCode=404,E.setHeader("content-type","text/plain; charset=utf-8"),E.end(`not found
|
|
77
|
+
`)}catch(b){t.error(`[057] request failed: ${String(b)}`),E.headersSent||(E.statusCode=500),E.end()}})()}),u=await Xi(c,e.port??Mt,n,Hi).catch(f=>{throw a.stop(),f}),h=o?"localhost":n;return di(a.path,{pid:process.pid,url:`http://${o?ce:n}:${u}`,version:e.version??"dev",contract:At,store:a.path,startedAt:Date.now(),owner:e.owner??"cli"}),{url:`http://${h}:${u}`,port:u,host:n,runtime:a,server:c,close(){return new Promise(f=>{li(a.path),c.close(()=>{a.stop(),f()}),c.closeAllConnections?.()})}}}function Yi(e){return Re(xn(new URL(".",e)),"..","dist")}const $e="1.0.1";function Vi(e){const t={command:"serve",open:!1,yes:!1,desktop:!1},s=[...e],n=s[0];if(n&&!n.startsWith("-"))if(n==="status"||n==="compact"||n==="reset")t.command=n,s.shift();else return{...t,command:"help",error:`unknown command: ${n}`};for(;s.length;){const o=s.shift(),[r,a]=o.includes("=")?zi(o,"="):[o,void 0],i=()=>a??s.shift();switch(r){case"-h":case"--help":t.command="help";break;case"-v":case"--version":t.command="version";break;case"--open":t.open=!0;break;case"--yes":case"-y":t.yes=!0;break;case"--desktop":t.desktop=!0;break;case"--port":{const c=i(),u=Number(c);if(!Number.isInteger(u)||u<0||u>65535)return{...t,command:"help",error:`--port needs a port number, got ${c}`};t.port=u;break}case"--host":{const c=i();if(!c)return{...t,command:"help",error:"--host needs a value"};t.host=c;break}case"--store":{const c=i();if(!c)return{...t,command:"help",error:"--store needs a path"};t.store=c;break}default:return{...t,command:"help",error:`unknown option: ${r}`}}}return t}function zi(e,t){const s=e.indexOf(t);return[e.slice(0,s),e.slice(s+1)]}const Ki=`057 — a spatial interface for observing the shape of a computational workday
|
|
76
78
|
|
|
77
79
|
057 observe this machine and serve the interface
|
|
78
80
|
057 status where the store is, what it holds, what is observed
|
|
@@ -80,8 +82,8 @@ CREATE INDEX IF NOT EXISTS claims_event ON claims(event_id);
|
|
|
80
82
|
057 reset delete the local store
|
|
81
83
|
|
|
82
84
|
Options
|
|
83
|
-
--port <n> port to serve on (default ${
|
|
84
|
-
--host <addr> address to bind (default ${
|
|
85
|
+
--port <n> port to serve on (default ${Mt}; the next free one if taken)
|
|
86
|
+
--host <addr> address to bind (default ${ce}; read the warning below first)
|
|
85
87
|
--store <path> store file to use (same as O57_STORE)
|
|
86
88
|
--open open the interface in the default browser — the running
|
|
87
89
|
057's, if one (or 057.app) already observes the store
|
|
@@ -105,39 +107,39 @@ anywhere. Everything it learns is in one SQLite file you can read or delete.
|
|
|
105
107
|
|
|
106
108
|
--host binds beyond the loopback interface and serves your telemetry, unauthenticated, to
|
|
107
109
|
anything that can reach that address. Do not do it on a network you do not control.
|
|
108
|
-
`;function
|
|
109
|
-
`)}async function
|
|
110
|
-
`),(s.error?console.error:console.log)(
|
|
111
|
-
${
|
|
112
|
-
Opening ${
|
|
113
|
-
`),await
|
|
114
|
-
${
|
|
115
|
-
Open ${
|
|
116
|
-
`),1)}return
|
|
110
|
+
`;function ae(e){return process.stdout.isTTY?`\x1B[2m${e}\x1B[0m`:e}function Me(e){return e<1024?`${e} B`:e<1024**2?`${(e/1024).toFixed(1)} KB`:e<1024**3?`${(e/1024**2).toFixed(1)} MB`:`${(e/1024**3).toFixed(2)} GB`}function Ji(e,t,s,n){const o=["",` 057 ${$e}`,` ${e}`,"",ae(" observing this machine only — its process table, and any AI runtime state it finds"),ae(` storing ${t}`),ae(` keeping ${s}`),ae(" sending nothing. no account, no cloud, no analytics."),ae(" resetting 057 reset")];return n!==ce&&o.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),o.push(""),o.join(`
|
|
111
|
+
`)}async function Qi(e){if(!process.stdin.isTTY)return!1;const t=kn({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>t.question(`${e} [y/N] `,n))).trim().toLowerCase()==="y"}finally{t.close()}}async function Zi(e,t){const s=Vi(e);if(s.command==="version")return console.log($e),0;if(s.command==="help")return s.error&&console.error(`057: ${s.error}
|
|
112
|
+
`),(s.error?console.error:console.log)(Ki),s.error?2:0;s.store&&(process.env.O57_STORE=s.store);const n=Ve(),o=un();if(s.command==="status")return ta(n,o);if(s.command==="compact")return sa(n);if(s.command==="reset")return na(n,s.yes);if(s.desktop)return ea(t,n,o,s.port??0);const r=s.port??oa(process.env.O57_PORT)??Mt,a=s.host??process.env.O57_HOST??ce;let i;try{i=await hn({root:t,port:r,host:a,storePath:n,retention:o,log:Ke(),version:$e})}catch(h){if(h instanceof Et){const f=h.record;return s.open?(console.log(`
|
|
113
|
+
${h.message}${f.owner==="desktop"?" — 057.app":""}.
|
|
114
|
+
Opening ${f.url}
|
|
115
|
+
`),await Ts(f.url),0):(console.error(`
|
|
116
|
+
${h.message}.
|
|
117
|
+
Open ${f.url} (\`057 --open\`), or stop that 057 before starting another.
|
|
118
|
+
`),1)}return Ot(h)}console.log(Ji(i.url,n,Ye(o),a)),s.open&&await Ts(i.url);let c=!1;const u=()=>{c||(c=!0,console.log(`
|
|
117
119
|
057 stopping — history is on disk
|
|
118
|
-
`),i.close().then(()=>process.exit(0)))};return process.on("SIGINT",
|
|
119
|
-
`)};let r;try{r=await
|
|
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://${
|
|
121
|
-
store ${e}${
|
|
120
|
+
`),i.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}async function ea(e,t,s,n){const o=c=>{process.stdout.write(`${JSON.stringify(c)}
|
|
121
|
+
`)};let r;try{r=await hn({root:e,port:n,host:ce,storePath:t,retention:s,log:Ke(),version:$e,owner:"desktop"})}catch(c){if(c instanceof Et){const u=c.record;return o({event:"running",url:u.url,pid:u.pid,version:u.version,owner:u.owner,contract:u.contract}),0}return c instanceof fe?(o({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(o({event:"error",kind:"start",message:c instanceof Error?c.message:String(c)}),1)}let a=!1;const i=c=>{a||(a=!0,process.stderr.write(`[057] stopping (${c}) — history is on disk
|
|
122
|
+
`),r.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),process.stdin.on("end",()=>i("app closed its pipe")),process.stdin.on("close",()=>i("app closed its pipe")),process.stdin.resume(),o({event:"ready",url:`http://${ce}:${r.port}`,pid:process.pid,version:$e,store:t,contract:At}),new Promise(()=>{})}function ta(e,t){let s;try{s=It({path:e,retention:t,observe:!1,log:Ke()})}catch(n){return Ot(n)}try{const n=s.store.stats(),o=s.store.sizeBytes(),r=ze(e).map(i=>kt(i)).filter(i=>i!==null).map(i=>"0"+i.toString(8)).join(" ");if(console.log(`
|
|
123
|
+
store ${e}${dn()?" (from O57_STORE)":""}
|
|
122
124
|
schema ${s.store.schemaVersion}
|
|
123
|
-
size ${Me(o.total)} ${
|
|
125
|
+
size ${Me(o.total)} ${ae(`(db ${Me(o.db)}, wal ${Me(o.wal)})`)}
|
|
124
126
|
events ${n.events.toLocaleString()}
|
|
125
127
|
claims ${n.claims.toLocaleString()}
|
|
126
|
-
keeping ${
|
|
128
|
+
keeping ${Ye(t)}
|
|
127
129
|
permissions ${r||"none — no store yet"}
|
|
128
130
|
`),n.bySource.length===0)console.log(` nothing has been captured yet
|
|
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 ${
|
|
130
|
-
`),0}finally{s.stop()}}function
|
|
131
|
+
`);else{for(const i of n.bySource){const c=`${new Date(i.first).toISOString().slice(0,10)} → ${new Date(i.last).toISOString().slice(0,10)}`;console.log(` ${i.source.padEnd(20)}${String(i.events).padStart(10)} events ${ae(c)}`)}console.log("")}const a=pn();return a&&console.log(` a store from a previous layout is at ${a} and is not in use
|
|
132
|
+
`),0}finally{s.stop()}}function sa(e){let t;try{t=It({path:e,observe:!1,log:Ke()})}catch(s){return Ot(s)}try{const s=t.store.sizeBytes().total,n=t.sweep();t.store.compact();const o=t.store.sizeBytes().total;return console.log(`
|
|
131
133
|
removed ${n.processEvents+n.otherEvents} expired events
|
|
132
134
|
${Me(s)} → ${Me(o)}
|
|
133
|
-
`),0}finally{t.stop()}}async function
|
|
135
|
+
`),0}finally{t.stop()}}async function na(e,t){const s=ze(e);console.log(`
|
|
134
136
|
this deletes, permanently:
|
|
135
|
-
`);for(const n of s)console.log(` ${n}`);if(console.log(""),!t&&!await
|
|
136
|
-
`),1;for(const n of s)
|
|
137
|
-
`),0}function
|
|
137
|
+
`);for(const n of s)console.log(` ${n}`);if(console.log(""),!t&&!await Qi(" delete the local store?"))return console.log(` nothing was deleted
|
|
138
|
+
`),1;for(const n of s)Ms(n,{force:!0});return console.log(` deleted. the next run starts a new store.
|
|
139
|
+
`),0}function Ke(){return{info:e=>{process.stderr.write(`${ae(e)}
|
|
138
140
|
`)},warn:e=>{process.stderr.write(`${e}
|
|
139
141
|
`)},error:e=>{process.stderr.write(`${e}
|
|
140
|
-
`)}}}function
|
|
142
|
+
`)}}}function Ot(e){if(e instanceof fe)return console.error(`
|
|
141
143
|
057: ${e.message}
|
|
142
144
|
${e.remedy}
|
|
143
145
|
`),1;const t=e?.code;return t==="EADDRINUSE"?(console.error(`
|
|
@@ -146,4 +148,4 @@ anything that can reach that address. Do not do it on a network you do not contr
|
|
|
146
148
|
057: cannot bind that address or port (${t}).
|
|
147
149
|
`),1):(console.error(`
|
|
148
150
|
057: ${e instanceof Error?e.message:String(e)}
|
|
149
|
-
`),1)}function
|
|
151
|
+
`),1)}function oa(e){if(!e)return;const t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}async function Ts(e){const t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:s}=await import("node:child_process");try{s(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function ba(e){const t=await Zi(e,Yi(import.meta.url));t!==0&&process.exit(t)}export{Yi as defaultRoot,ba as main,Zi as run};
|