dotmem 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -22
- package/OVERVIEW.md +3 -1
- package/README.md +11 -11
- package/agent.cjs +19624 -142
- package/agent.js +19613 -142
- package/bin/cli.cjs +98 -1
- package/bin/cli.js +89 -1
- package/bin/dotmem-burst-stats.cjs +850 -9
- package/bin/dotmem-burst-stats.js +827 -9
- package/bin/mcp.cjs +26 -1
- package/bin/mcp.js +20 -1
- package/built-in-context.json +2 -2
- package/cli.cjs +32979 -325
- package/cli.js +32924 -323
- package/env.cjs +6 -1
- package/env.js +4 -1
- package/global.cjs +19412 -142
- package/global.js +19379 -142
- package/index.cjs +24369 -176
- package/index.js +24309 -176
- package/mcp.cjs +26852 -211
- package/mcp.js +26813 -211
- package/package.json +1 -1
- package/types/global-types.d.ts +2 -0
- package/crew/CREW-CERTIFICATION-REPORT.md +0 -52
- package/crew/PHASE-1-DISCOVERY.md +0 -74
- package/crew/PHASE-2-SURFACE-ANALYSIS.md +0 -74
- package/crew/PHASE-3-IMPLEMENTATION-REPORT.md +0 -40
|
@@ -1,5 +1,726 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as k from'fs';import*as E from'path';var ae=Object.defineProperty;var c=(e,t)=>ae(e,"name",{value:t,configurable:true});function v(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?e>0&&e<1e12?Math.round(e*1e3):Math.round(e):null;if(e instanceof Date){let t=e.getTime();return Number.isFinite(t)?t:null}if(typeof e=="string"){let t=e.trim();if(t==="")return null;if(/^-?\d+(\.\d+)?$/.test(t)){let n=Number(t);return Number.isFinite(n)?n>0&&n<1e12?Math.round(n*1e3):Math.round(n):null}let s=Date.parse(t);return Number.isFinite(s)?s:null}return null}c(v,"normalizeTimestamp");function y(e){if(e==null||typeof e=="boolean")return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}c(y,"toFiniteNumber");function le(e){return v(e.timestamp)}c(le,"tsMs");function ue(e){let t=[],s=0;for(let n of e){let o=le(n);if(o===null){s++;continue}t.push({ev:n,ts:o});}return t.sort((n,o)=>n.ts-o.ts),{valid:t.map(n=>n.ev),invalid:s}}c(ue,"sortEvents");function A(e,t){let{valid:s,invalid:n}=ue(e),o=t.gapMin*60*1e3,a=[],r=[],m=s.map(l=>({ev:l,ts:v(l.timestamp)}));for(let l=0;l<m.length;l++){let p=m[l];if(r.length===0){r.push(p);continue}let d=r[r.length-1],f=p.ts-d.ts,i=p.ev.sessionId!=null&&d.ev.sessionId!=null&&p.ev.sessionId!==d.ev.sessionId,h=p.ev.projectId!=null&&d.ev.projectId!=null&&p.ev.projectId!==d.ev.projectId;f>o||i||h?(a.push({events:r.map(C=>C.ev),startMs:r[0].ts,endMs:r[r.length-1].ts}),r=[p]):r.push(p);}return r.length>0&&a.push({events:r.map(l=>l.ev),startMs:r[0].ts,endMs:r[r.length-1].ts}),{bursts:a.map(l=>({...l})),invalidTimestamps:n}}c(A,"partitionIntoBursts");function ce(e,t){if(!(!e||typeof e!="object")){for(let s of t)if(s.includes(".")){let n=s.split("."),o=e,a=true;for(let r of n)if(o&&typeof o=="object"&&r in o)o=o[r];else {a=false;break}if(a&&o!==void 0)return o}else if(Object.prototype.hasOwnProperty.call(e,s))return e[s]}}c(ce,"getField");function pe(e){return typeof e=="string"&&/dotmem/i.test(e)}c(pe,"isDotmemToolName");function P(e){let t=e.match(/Output too large \(([\d.]+)\s*(KB|MB|B)?\)/i);if(!t)return null;let s=Number(t[1]);if(!Number.isFinite(s))return null;let n=(t[2]||"KB").toUpperCase();return Math.round(n==="MB"?s*1024*1024:n==="KB"?s*1024:s)}c(P,"parseOutputTooLarge");var N=class{static{c(this,"GenericJsonlAdapter");}name;fieldMap;constructor(t){this.name=t?.name||"generic",this.fieldMap=t?.fieldMap||{};}detect(t,s){let n=s||[];if(n.length===0)return t?/\.(jsonl|ndjson|json)$/i.test(t):false;let o=0;for(let a of n){let r=a.trim();if(r!=="")try{JSON.parse(r),o++;}catch{return false}}return o>0}parse(t){let s=[],n=t.split(/\r?\n/);for(let o of n){let a=o.trim();if(a==="")continue;let r;try{r=JSON.parse(a);}catch{continue}s.push(this.mapObject(r));}return s}mapObject(t){let s=this.fieldMap,n=c((l,p)=>{let d=s[l],f=d?Array.isArray(d)?d:[d]:p;return ce(t,f)},"get"),o=n("toolName",["toolName","tool_name","name","function.name","tool.name"]),a=y(n("resultBytes",["resultBytes","result_bytes","bytes","size","result.size"])),r=n("resultContent",["result","output","content","toolResult","tool_result"]);if(a===null&&typeof r=="string"){let l=P(r);a=l!==null?l:Buffer.byteLength(r,"utf8");}if(typeof r=="string"&&/Output too large/i.test(r)){let l=P(r);l!==null&&(a=l);}let m=n("eventType",["eventType","event_type","type","role","kind"]);if(typeof m=="string"){let l=m.toLowerCase();l==="user"||l==="human"?m="user turn":l==="assistant"||l==="ai"||l==="model"?m="assistant message":l==="tool"||l==="tool_use"||l==="tool-use"?m="tool call":(l==="tool_result"||l==="tool-result")&&(m="tool result");}return !m&&o&&(m="tool call"),{timestamp:n("timestamp",["timestamp","ts","time","createdAt","created_at","date","startTime"]),sessionId:n("sessionId",["sessionId","session_id","conversationId","conversation_id"])??null,projectId:n("projectId",["projectId","project_id","project"])??null,eventType:m??null,messageId:n("messageId",["messageId","message_id","id","uuid"])??null,toolCallId:n("toolCallId",["toolCallId","tool_call_id","toolUseId","tool_use_id","callId","call_id"])??null,toolName:o??null,inputTokens:y(n("inputTokens",["inputTokens","input_tokens","usage.input_tokens","usage.inputTokens","tokens.input"])),outputTokens:y(n("outputTokens",["outputTokens","output_tokens","usage.output_tokens","usage.outputTokens","tokens.output"])),cacheCreationTokens:y(n("cacheCreationTokens",["cacheCreationTokens","cache_creation_tokens","usage.cache_creation_input_tokens"])),cacheReadTokens:y(n("cacheReadTokens",["cacheReadTokens","cache_read_tokens","usage.cache_read_input_tokens"])),resultBytes:a,isSidechain:n("isSidechain",["isSidechain","is_sidechain"])??null}}async parseFile(t){let s=await import('fs'),n=await import('readline'),o=s.createReadStream(t,{encoding:"utf8"}),a=n.createInterface({input:o,crlfDelay:1/0}),r=[];for await(let m of a){let l=m.trim();if(l!=="")try{let p=JSON.parse(l);r.push(this.mapObject(p));}catch{}}return r}},z=new N({name:"generic"}),me=new N({name:"jsonl"}),B={generic:z,jsonl:me};function U(){return Object.keys(B)}c(U,"listAdapters");function G(e){if(!e)return z;let t=B[e.toLowerCase()];if(t)return t;throw new Error(`Unknown adapter: ${e}`)}c(G,"getAdapter");function H(e,t){for(let s of Object.keys(B)){let n=B[s];if(n.detect&&n.detect(t||"",e))return n}return z}c(H,"detectAdapter");function w(e){return pe(e)}c(w,"isDotmemToolNamePublic");var de=c(e=>w(e),"DOTMEM");function fe(e){return (e.eventType||"").toLowerCase().includes("user")}c(fe,"isUserEvent");function he(e){let t=(e.eventType||"").toLowerCase();return t.includes("tool")&&t.includes("call")}c(he,"isToolCallEvent");function ge(e){let t=(e.eventType||"").toLowerCase();return t.includes("tool")&&t.includes("result")}c(ge,"isToolResultEvent");function ke(e){let t=e[0],s=-1;for(let n of e){let o=0;n.outputTokens!==null&&n.outputTokens!==void 0&&o++,n.inputTokens!==null&&n.inputTokens!==void 0&&o++,n.cacheCreationTokens!==null&&n.cacheCreationTokens!==void 0&&o++,n.cacheReadTokens!==null&&n.cacheReadTokens!==void 0&&o++,o>s&&(s=o,t=n);}return t}c(ke,"pickBestTokenEvent");function J(e,t){let s=new Map,n=[];for(let u of e)u.messageId?(s.has(u.messageId)||s.set(u.messageId,[]),s.get(u.messageId).push(u)):n.push(u);let o=[];for(let u of s.values())o.push(ke(u));o.push(...n);let a=null,r=null,m=null,l=null,p=false,d=false,f=false,i=false;for(let u of o)u.outputTokens!==null&&u.outputTokens!==void 0&&(a=(a||0)+u.outputTokens,p=true),u.inputTokens!==null&&u.inputTokens!==void 0&&(r=(r||0)+u.inputTokens,d=true),u.cacheCreationTokens!==null&&u.cacheCreationTokens!==void 0&&(m=(m||0)+u.cacheCreationTokens,f=true),u.cacheReadTokens!==null&&u.cacheReadTokens!==void 0&&(l=(l||0)+u.cacheReadTokens,i=true);p||(a=null),d||(r=null),f||(m=null),i||(l=null);let h=new Set,C=0;for(let u of e)if(fe(u)){if(u.messageId){if(h.has(u.messageId))continue;h.add(u.messageId);}C++;}let b=new Map,O=[];for(let u of e)if(de(u.toolName))if(u.toolCallId)b.has(u.toolCallId)||b.set(u.toolCallId,[]),b.get(u.toolCallId).push(u);else {if(ge(u)&&!he(u))continue;O.push(u);}let ne=b.size+O.length,_=0;for(let u of b.values()){let T=null;for(let R of u)R.resultBytes!==null&&R.resultBytes!==void 0&&(T=(T===null?0:T)+R.resultBytes);T!==null&&(_+=T);}for(let u of O)u.resultBytes!==null&&u.resultBytes!==void 0&&(_+=u.resultBytes);let M=e.map(u=>v(u.timestamp)).filter(u=>u!==null).sort((u,T)=>u-T),x=M.length?M[0]:0,j=M.length?M[M.length-1]:x,se=Te(e,t.capMin),oe=x===j?0:(j-x)/6e4,re=e.length?e[0].sessionId??null:null,ie=e.length?e[0].projectId??null:null;return {sessionId:re,projectId:ie,activeMin:se,wallMin:oe,turns:C,outputTokens:a,inputTokens:r,cacheCreationTokens:m,cacheReadTokens:l,dotmemCalls:ne,dotmemBytes:_,hasOutputTokens:p,hasInputTokens:d,hasCacheCreationTokens:f,hasCacheReadTokens:i,startMs:x,endMs:j}}c(J,"computeBurstMetrics");function Te(e,t){let s=e.map(a=>v(a.timestamp)).filter(a=>a!==null).sort((a,r)=>a-r),n=t*60*1e3,o=0;for(let a=0;a<s.length-1;a++){let r=s[a+1]-s[a];r<0||(o+=Math.min(r,n));}return o/6e4}c(Te,"computeActiveMinExport");function K(e,t){return e<t.shortMax?"SHORT":e<=t.longMax?"MEDIUM":"LONG"}c(K,"classifyBurst");function F(e){return {gapMin:e?.gapMin??15,capMin:e?.capMin??5,shortMax:e?.shortMax??10,longMax:e?.longMax??45}}c(F,"resolveOptions");function W(e,t){let s=F(t),{bursts:n}=A(e,s),o=[];for(let a of n){let r=J(a.events,s),m={sessionId:r.sessionId,projectId:r.projectId,events:a.events,startMs:r.startMs,endMs:r.endMs,wallMin:r.wallMin,activeMin:r.activeMin,turns:r.turns,outputTokens:r.outputTokens,inputTokens:r.inputTokens,cacheCreationTokens:r.cacheCreationTokens,cacheReadTokens:r.cacheReadTokens,dotmemCalls:r.dotmemCalls,dotmemBytes:r.dotmemBytes,hasOutputTokens:r.hasOutputTokens,hasInputTokens:r.hasInputTokens,hasCacheCreationTokens:r.hasCacheCreationTokens,hasCacheReadTokens:r.hasCacheReadTokens};o.push(m);}return o}c(W,"reconstructBursts");function S(e,t){if(e.length===0)return null;if(e.length===1)return e[0];let s=[...e].sort((r,m)=>r-m),n=t/100*(s.length-1),o=Math.floor(n),a=Math.ceil(n);return o===a?s[o]:s[o]+(s[a]-s[o])*(n-o)}c(S,"percentile");function g(e){return S(e,50)}c(g,"median");function I(e){let t=0,s=false;for(let n of e)n!=null&&(t+=n,s=true);return s?t:null}c(I,"sumNumbers");function ve(e){let t=e.length,s=e.map(i=>i.activeMin),n=e.map(i=>i.wallMin),o=e.map(i=>i.dotmemCalls),a=e.map(i=>i.dotmemBytes),r=e.map(i=>i.turns),m=e.filter(i=>i.hasOutputTokens).map(i=>i.outputTokens),l=e.filter(i=>i.hasInputTokens).map(i=>i.inputTokens),p=e.filter(i=>i.hasCacheCreationTokens).map(i=>i.cacheCreationTokens),d=e.filter(i=>i.hasCacheReadTokens).map(i=>i.cacheReadTokens),f={SHORT:0,MEDIUM:0,LONG:0};for(let i of e)i.activeMin<10?f.SHORT++:i.activeMin<=45?f.MEDIUM++:f.LONG++;return {burstCount:t,sampleSize:t,activeMin:{median:g(s),p25:S(s,25),p75:S(s,75),sampleSize:t,reliable:t>=5},wallMin:{median:g(n),total:I(n)},classes:f,dotmem:{calls:{mean:o.length?o.reduce((i,h)=>i+h,0)/o.length:null,median:g(o),total:o.reduce((i,h)=>i+h,0)},bytes:{median:g(a),total:a.reduce((i,h)=>i+h,0)}},turns:{median:g(r),total:r.reduce((i,h)=>i+h,0)},outputTokens:{median:m.length?g(m):null,total:I(e.map(i=>i.outputTokens)),available:e.some(i=>i.hasOutputTokens)},inputTokens:{median:l.length?g(l):null,total:I(e.map(i=>i.inputTokens)),available:e.some(i=>i.hasInputTokens)},cacheCreationTokens:{median:p.length?g(p):null,total:I(e.map(i=>i.cacheCreationTokens)),available:e.some(i=>i.hasCacheCreationTokens)},cacheReadTokens:{median:d.length?g(d):null,total:I(e.map(i=>i.cacheReadTokens)),available:e.some(i=>i.hasCacheReadTokens)}}}c(ve,"aggregateOne");function q(e,t){let s=F(t),n=ve(e),o={SHORT:0,MEDIUM:0,LONG:0};for(let a of e){let r=K(a.activeMin,s);o[r]++;}return n.classes=o,n}c(q,"aggregateBursts");function V(e,t,s){let n=F(t),o=e;t?.projectFilter&&(o=e.filter(d=>(d.projectId??null)===t.projectFilter));let a=W(o,n),{invalidTimestamps:r}=A(o,n),m=q(a,n),l=new Map;for(let d of o){let f=d.projectId??"unknown";l.has(f)||l.set(f,[]),l.get(f).push(d);}let p={};for(let[d,f]of l){let i=W(f,n);p[d]=q(i,n);}return {schemaVersion:"1.0.0",generatedAt:new Date().toISOString(),parameters:{...n,project:t?.projectFilter??null},source:s||{paths:[],adapter:"generic"},global:m,projects:p,invalidTimestamps:r,totalEvents:o.length}}c(V,"analyzeEvents");function ye(e){try{return k.statSync(e).isDirectory()}catch{return false}}c(ye,"isDirectory");function be(e){try{return k.statSync(e).isFile()}catch{return false}}c(be,"isFile");function Z(e){let t=[];if(be(e))return [e];if(!ye(e))return [];let s=[e];for(;s.length;){let n=s.pop(),o;try{o=k.readdirSync(n,{withFileTypes:!0});}catch{continue}for(let a of o){let r=E.join(n,a.name);a.isDirectory()?s.push(r):a.isFile()&&t.push(r);}}return t}c(Z,"walkFiles");function ee(e,t=5){try{return k.readFileSync(e,"utf8").split(/\r?\n/).slice(0,t)}catch{return []}}c(ee,"readSampleLines");async function te(e,t){if(typeof e.parseFile=="function")return e.parseFile(t);let s=k.readFileSync(t,"utf8");return e.parse(s)}c(te,"readFileEvents");function Q(e){let t={};for(let s=0;s<e.length;s++){let n=e[s],o=c(()=>e[++s],"next");switch(n){case "--source":t.source=o();break;case "--adapter":t.adapter=o();break;case "--gap-min":t.gapMin=Number(o());break;case "--cap-min":t.capMin=Number(o());break;case "--short-max":t.shortMax=Number(o());break;case "--long-max":t.longMax=Number(o());break;case "--project":t.project=o();break;case "--format":t.format=o();break;case "--output":t.output=o();break;case "--list-adapters":t.listAdapters=true;break;case "--help":case "-h":t.help=true;break;default:!n.startsWith("--")&&!t.source&&(t.source=n);break}}return t}c(Q,"parseArgs");function X(){return `Dotmem Burst Stats
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
import * as path2 from 'path';
|
|
4
|
+
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
+
|
|
8
|
+
// core/burst-stats/normalize.ts
|
|
9
|
+
function normalizeTimestamp(value) {
|
|
10
|
+
if (value === null || value === void 0) return null;
|
|
11
|
+
if (typeof value === "number") {
|
|
12
|
+
if (!Number.isFinite(value)) return null;
|
|
13
|
+
if (value > 0 && value < 1e12) return Math.round(value * 1e3);
|
|
14
|
+
return Math.round(value);
|
|
15
|
+
}
|
|
16
|
+
if (value instanceof Date) {
|
|
17
|
+
const t = value.getTime();
|
|
18
|
+
return Number.isFinite(t) ? t : null;
|
|
19
|
+
}
|
|
20
|
+
if (typeof value === "string") {
|
|
21
|
+
const trimmed = value.trim();
|
|
22
|
+
if (trimmed === "") return null;
|
|
23
|
+
if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
|
|
24
|
+
const n = Number(trimmed);
|
|
25
|
+
if (!Number.isFinite(n)) return null;
|
|
26
|
+
if (n > 0 && n < 1e12) return Math.round(n * 1e3);
|
|
27
|
+
return Math.round(n);
|
|
28
|
+
}
|
|
29
|
+
const parsed = Date.parse(trimmed);
|
|
30
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
__name(normalizeTimestamp, "normalizeTimestamp");
|
|
36
|
+
function toFiniteNumber(value) {
|
|
37
|
+
if (value === null || value === void 0) return null;
|
|
38
|
+
if (typeof value === "boolean") return null;
|
|
39
|
+
const n = typeof value === "number" ? value : Number(value);
|
|
40
|
+
if (!Number.isFinite(n)) return null;
|
|
41
|
+
return n;
|
|
42
|
+
}
|
|
43
|
+
__name(toFiniteNumber, "toFiniteNumber");
|
|
44
|
+
|
|
45
|
+
// core/burst-stats/bursts.ts
|
|
46
|
+
function tsMs(ev) {
|
|
47
|
+
return normalizeTimestamp(ev.timestamp);
|
|
48
|
+
}
|
|
49
|
+
__name(tsMs, "tsMs");
|
|
50
|
+
function sortEvents(events) {
|
|
51
|
+
const valid = [];
|
|
52
|
+
let invalid = 0;
|
|
53
|
+
for (const ev of events) {
|
|
54
|
+
const t = tsMs(ev);
|
|
55
|
+
if (t === null) {
|
|
56
|
+
invalid++;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
valid.push({ ev, ts: t });
|
|
60
|
+
}
|
|
61
|
+
valid.sort((a, b) => a.ts - b.ts);
|
|
62
|
+
return { valid: valid.map((v) => v.ev), invalid };
|
|
63
|
+
}
|
|
64
|
+
__name(sortEvents, "sortEvents");
|
|
65
|
+
function partitionIntoBursts(events, opts) {
|
|
66
|
+
const { valid, invalid } = sortEvents(events);
|
|
67
|
+
const gapMs = opts.gapMin * 60 * 1e3;
|
|
68
|
+
const bursts = [];
|
|
69
|
+
let current = [];
|
|
70
|
+
const stamped = valid.map((ev) => ({ ev, ts: normalizeTimestamp(ev.timestamp) }));
|
|
71
|
+
for (let i = 0; i < stamped.length; i++) {
|
|
72
|
+
const item = stamped[i];
|
|
73
|
+
if (current.length === 0) {
|
|
74
|
+
current.push(item);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const prev = current[current.length - 1];
|
|
78
|
+
const delta = item.ts - prev.ts;
|
|
79
|
+
const sessionChanged = item.ev.sessionId != null && prev.ev.sessionId != null && item.ev.sessionId !== prev.ev.sessionId;
|
|
80
|
+
const projectChanged = item.ev.projectId != null && prev.ev.projectId != null && item.ev.projectId !== prev.ev.projectId;
|
|
81
|
+
if (delta > gapMs || sessionChanged || projectChanged) {
|
|
82
|
+
bursts.push({
|
|
83
|
+
events: current.map((c) => c.ev),
|
|
84
|
+
startMs: current[0].ts,
|
|
85
|
+
endMs: current[current.length - 1].ts
|
|
86
|
+
});
|
|
87
|
+
current = [item];
|
|
88
|
+
} else {
|
|
89
|
+
current.push(item);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (current.length > 0) {
|
|
93
|
+
bursts.push({
|
|
94
|
+
events: current.map((c) => c.ev),
|
|
95
|
+
startMs: current[0].ts,
|
|
96
|
+
endMs: current[current.length - 1].ts
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return { bursts: bursts.map((b) => ({ ...b })), invalidTimestamps: invalid };
|
|
100
|
+
}
|
|
101
|
+
__name(partitionIntoBursts, "partitionIntoBursts");
|
|
102
|
+
|
|
103
|
+
// core/burst-stats/adapters.ts
|
|
104
|
+
function getField(obj, candidates) {
|
|
105
|
+
if (!obj || typeof obj !== "object") return void 0;
|
|
106
|
+
for (const c of candidates) {
|
|
107
|
+
if (c.includes(".")) {
|
|
108
|
+
const parts = c.split(".");
|
|
109
|
+
let cur = obj;
|
|
110
|
+
let ok = true;
|
|
111
|
+
for (const p of parts) {
|
|
112
|
+
if (cur && typeof cur === "object" && p in cur) cur = cur[p];
|
|
113
|
+
else {
|
|
114
|
+
ok = false;
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (ok && cur !== void 0) return cur;
|
|
119
|
+
} else if (Object.prototype.hasOwnProperty.call(obj, c)) {
|
|
120
|
+
return obj[c];
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return void 0;
|
|
124
|
+
}
|
|
125
|
+
__name(getField, "getField");
|
|
126
|
+
function isDotmemToolName(name) {
|
|
127
|
+
return typeof name === "string" && /dotmem/i.test(name);
|
|
128
|
+
}
|
|
129
|
+
__name(isDotmemToolName, "isDotmemToolName");
|
|
130
|
+
function parseOutputTooLarge(text) {
|
|
131
|
+
const m = text.match(/Output too large \(([\d.]+)\s*(KB|MB|B)?\)/i);
|
|
132
|
+
if (!m) return null;
|
|
133
|
+
const n = Number(m[1]);
|
|
134
|
+
if (!Number.isFinite(n)) return null;
|
|
135
|
+
const unit = (m[2] || "KB").toUpperCase();
|
|
136
|
+
if (unit === "MB") return Math.round(n * 1024 * 1024);
|
|
137
|
+
if (unit === "KB") return Math.round(n * 1024);
|
|
138
|
+
return Math.round(n);
|
|
139
|
+
}
|
|
140
|
+
__name(parseOutputTooLarge, "parseOutputTooLarge");
|
|
141
|
+
var GenericJsonlAdapter = class {
|
|
142
|
+
static {
|
|
143
|
+
__name(this, "GenericJsonlAdapter");
|
|
144
|
+
}
|
|
145
|
+
name;
|
|
146
|
+
fieldMap;
|
|
147
|
+
constructor(options) {
|
|
148
|
+
this.name = options?.name || "generic";
|
|
149
|
+
this.fieldMap = options?.fieldMap || {};
|
|
150
|
+
}
|
|
151
|
+
detect(filePath, sampleLines) {
|
|
152
|
+
const lines = sampleLines || [];
|
|
153
|
+
if (lines.length === 0) return filePath ? /\.(jsonl|ndjson|json)$/i.test(filePath) : false;
|
|
154
|
+
let valid = 0;
|
|
155
|
+
for (const l of lines) {
|
|
156
|
+
const t = l.trim();
|
|
157
|
+
if (t === "") continue;
|
|
158
|
+
try {
|
|
159
|
+
JSON.parse(t);
|
|
160
|
+
valid++;
|
|
161
|
+
} catch {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return valid > 0;
|
|
166
|
+
}
|
|
167
|
+
parse(content) {
|
|
168
|
+
const events = [];
|
|
169
|
+
const lines = content.split(/\r?\n/);
|
|
170
|
+
for (const line of lines) {
|
|
171
|
+
const t = line.trim();
|
|
172
|
+
if (t === "") continue;
|
|
173
|
+
let obj;
|
|
174
|
+
try {
|
|
175
|
+
obj = JSON.parse(t);
|
|
176
|
+
} catch {
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
events.push(this.mapObject(obj));
|
|
180
|
+
}
|
|
181
|
+
return events;
|
|
182
|
+
}
|
|
183
|
+
mapObject(obj) {
|
|
184
|
+
const fm = this.fieldMap;
|
|
185
|
+
const get = /* @__PURE__ */ __name((key, defaults) => {
|
|
186
|
+
const mapped = fm[key];
|
|
187
|
+
const cands = mapped ? Array.isArray(mapped) ? mapped : [mapped] : defaults;
|
|
188
|
+
return getField(obj, cands);
|
|
189
|
+
}, "get");
|
|
190
|
+
const toolName = get("toolName", ["toolName", "tool_name", "name", "function.name", "tool.name"]);
|
|
191
|
+
let resultBytes = toFiniteNumber(get("resultBytes", ["resultBytes", "result_bytes", "bytes", "size", "result.size"]));
|
|
192
|
+
const resultContent = get("resultContent", ["result", "output", "content", "toolResult", "tool_result"]);
|
|
193
|
+
if (resultBytes === null && typeof resultContent === "string") {
|
|
194
|
+
const parsed = parseOutputTooLarge(resultContent);
|
|
195
|
+
resultBytes = parsed !== null ? parsed : Buffer.byteLength(resultContent, "utf8");
|
|
196
|
+
}
|
|
197
|
+
if (typeof resultContent === "string" && /Output too large/i.test(resultContent)) {
|
|
198
|
+
const parsed = parseOutputTooLarge(resultContent);
|
|
199
|
+
if (parsed !== null) resultBytes = parsed;
|
|
200
|
+
}
|
|
201
|
+
let eventType = get("eventType", ["eventType", "event_type", "type", "role", "kind"]);
|
|
202
|
+
if (typeof eventType === "string") {
|
|
203
|
+
const lower = eventType.toLowerCase();
|
|
204
|
+
if (lower === "user" || lower === "human") eventType = "user turn";
|
|
205
|
+
else if (lower === "assistant" || lower === "ai" || lower === "model") eventType = "assistant message";
|
|
206
|
+
else if (lower === "tool" || lower === "tool_use" || lower === "tool-use") eventType = "tool call";
|
|
207
|
+
else if (lower === "tool_result" || lower === "tool-result") eventType = "tool result";
|
|
208
|
+
}
|
|
209
|
+
if (!eventType && toolName) eventType = "tool call";
|
|
210
|
+
return {
|
|
211
|
+
timestamp: get("timestamp", ["timestamp", "ts", "time", "createdAt", "created_at", "date", "startTime"]),
|
|
212
|
+
sessionId: get("sessionId", ["sessionId", "session_id", "conversationId", "conversation_id"]) ?? null,
|
|
213
|
+
projectId: get("projectId", ["projectId", "project_id", "project"]) ?? null,
|
|
214
|
+
eventType: eventType ?? null,
|
|
215
|
+
messageId: get("messageId", ["messageId", "message_id", "id", "uuid"]) ?? null,
|
|
216
|
+
toolCallId: get("toolCallId", ["toolCallId", "tool_call_id", "toolUseId", "tool_use_id", "callId", "call_id"]) ?? null,
|
|
217
|
+
toolName: toolName ?? null,
|
|
218
|
+
inputTokens: toFiniteNumber(get("inputTokens", ["inputTokens", "input_tokens", "usage.input_tokens", "usage.inputTokens", "tokens.input"])),
|
|
219
|
+
outputTokens: toFiniteNumber(get("outputTokens", ["outputTokens", "output_tokens", "usage.output_tokens", "usage.outputTokens", "tokens.output"])),
|
|
220
|
+
cacheCreationTokens: toFiniteNumber(get("cacheCreationTokens", ["cacheCreationTokens", "cache_creation_tokens", "usage.cache_creation_input_tokens"])),
|
|
221
|
+
cacheReadTokens: toFiniteNumber(get("cacheReadTokens", ["cacheReadTokens", "cache_read_tokens", "usage.cache_read_input_tokens"])),
|
|
222
|
+
resultBytes,
|
|
223
|
+
isSidechain: get("isSidechain", ["isSidechain", "is_sidechain"]) ?? null
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
async parseFile(filePath) {
|
|
227
|
+
const fs3 = await import('fs');
|
|
228
|
+
const readline = await import('readline');
|
|
229
|
+
const stream = fs3.createReadStream(filePath, { encoding: "utf8" });
|
|
230
|
+
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
231
|
+
const events = [];
|
|
232
|
+
for await (const line of rl) {
|
|
233
|
+
const t = line.trim();
|
|
234
|
+
if (t === "") continue;
|
|
235
|
+
try {
|
|
236
|
+
const obj = JSON.parse(t);
|
|
237
|
+
events.push(this.mapObject(obj));
|
|
238
|
+
} catch {
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return events;
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
var genericAdapter = new GenericJsonlAdapter({ name: "generic" });
|
|
245
|
+
var jsonlAdapter = new GenericJsonlAdapter({ name: "jsonl" });
|
|
246
|
+
var adapters = {
|
|
247
|
+
generic: genericAdapter,
|
|
248
|
+
jsonl: jsonlAdapter
|
|
249
|
+
};
|
|
250
|
+
function listAdapters() {
|
|
251
|
+
return Object.keys(adapters);
|
|
252
|
+
}
|
|
253
|
+
__name(listAdapters, "listAdapters");
|
|
254
|
+
function getAdapter(name) {
|
|
255
|
+
if (!name) return genericAdapter;
|
|
256
|
+
const a = adapters[name.toLowerCase()];
|
|
257
|
+
if (a) return a;
|
|
258
|
+
throw new Error(`Unknown adapter: ${name}`);
|
|
259
|
+
}
|
|
260
|
+
__name(getAdapter, "getAdapter");
|
|
261
|
+
function detectAdapter(sampleLines, filePath) {
|
|
262
|
+
for (const name of Object.keys(adapters)) {
|
|
263
|
+
const a = adapters[name];
|
|
264
|
+
if (a.detect && a.detect(filePath || "", sampleLines)) return a;
|
|
265
|
+
}
|
|
266
|
+
return genericAdapter;
|
|
267
|
+
}
|
|
268
|
+
__name(detectAdapter, "detectAdapter");
|
|
269
|
+
function isDotmemToolNamePublic(name) {
|
|
270
|
+
return isDotmemToolName(name);
|
|
271
|
+
}
|
|
272
|
+
__name(isDotmemToolNamePublic, "isDotmemToolNamePublic");
|
|
273
|
+
|
|
274
|
+
// core/burst-stats/metrics.ts
|
|
275
|
+
var DOTMEM = /* @__PURE__ */ __name((name) => isDotmemToolNamePublic(name), "DOTMEM");
|
|
276
|
+
function isUserEvent(ev) {
|
|
277
|
+
const t = (ev.eventType || "").toLowerCase();
|
|
278
|
+
return t.includes("user");
|
|
279
|
+
}
|
|
280
|
+
__name(isUserEvent, "isUserEvent");
|
|
281
|
+
function isToolCallEvent(ev) {
|
|
282
|
+
const t = (ev.eventType || "").toLowerCase();
|
|
283
|
+
return t.includes("tool") && t.includes("call");
|
|
284
|
+
}
|
|
285
|
+
__name(isToolCallEvent, "isToolCallEvent");
|
|
286
|
+
function isToolResultEvent(ev) {
|
|
287
|
+
const t = (ev.eventType || "").toLowerCase();
|
|
288
|
+
return t.includes("tool") && t.includes("result");
|
|
289
|
+
}
|
|
290
|
+
__name(isToolResultEvent, "isToolResultEvent");
|
|
291
|
+
function pickBestTokenEvent(group) {
|
|
292
|
+
let best = group[0];
|
|
293
|
+
let bestScore = -1;
|
|
294
|
+
for (const ev of group) {
|
|
295
|
+
let score = 0;
|
|
296
|
+
if (ev.outputTokens !== null && ev.outputTokens !== void 0) score++;
|
|
297
|
+
if (ev.inputTokens !== null && ev.inputTokens !== void 0) score++;
|
|
298
|
+
if (ev.cacheCreationTokens !== null && ev.cacheCreationTokens !== void 0) score++;
|
|
299
|
+
if (ev.cacheReadTokens !== null && ev.cacheReadTokens !== void 0) score++;
|
|
300
|
+
if (score > bestScore) {
|
|
301
|
+
bestScore = score;
|
|
302
|
+
best = ev;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return best;
|
|
306
|
+
}
|
|
307
|
+
__name(pickBestTokenEvent, "pickBestTokenEvent");
|
|
308
|
+
function computeBurstMetrics(events, opts) {
|
|
309
|
+
const groups = /* @__PURE__ */ new Map();
|
|
310
|
+
const noId = [];
|
|
311
|
+
for (const ev of events) {
|
|
312
|
+
if (ev.messageId) {
|
|
313
|
+
if (!groups.has(ev.messageId)) groups.set(ev.messageId, []);
|
|
314
|
+
groups.get(ev.messageId).push(ev);
|
|
315
|
+
} else {
|
|
316
|
+
noId.push(ev);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const selected = [];
|
|
320
|
+
for (const g of groups.values()) selected.push(pickBestTokenEvent(g));
|
|
321
|
+
selected.push(...noId);
|
|
322
|
+
let outputTokens = null;
|
|
323
|
+
let inputTokens = null;
|
|
324
|
+
let cacheCreationTokens = null;
|
|
325
|
+
let cacheReadTokens = null;
|
|
326
|
+
let hasOutput = false;
|
|
327
|
+
let hasInput = false;
|
|
328
|
+
let hasCacheCreation = false;
|
|
329
|
+
let hasCacheRead = false;
|
|
330
|
+
for (const ev of selected) {
|
|
331
|
+
if (ev.outputTokens !== null && ev.outputTokens !== void 0) {
|
|
332
|
+
outputTokens = (outputTokens || 0) + ev.outputTokens;
|
|
333
|
+
hasOutput = true;
|
|
334
|
+
}
|
|
335
|
+
if (ev.inputTokens !== null && ev.inputTokens !== void 0) {
|
|
336
|
+
inputTokens = (inputTokens || 0) + ev.inputTokens;
|
|
337
|
+
hasInput = true;
|
|
338
|
+
}
|
|
339
|
+
if (ev.cacheCreationTokens !== null && ev.cacheCreationTokens !== void 0) {
|
|
340
|
+
cacheCreationTokens = (cacheCreationTokens || 0) + ev.cacheCreationTokens;
|
|
341
|
+
hasCacheCreation = true;
|
|
342
|
+
}
|
|
343
|
+
if (ev.cacheReadTokens !== null && ev.cacheReadTokens !== void 0) {
|
|
344
|
+
cacheReadTokens = (cacheReadTokens || 0) + ev.cacheReadTokens;
|
|
345
|
+
hasCacheRead = true;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (!hasOutput) outputTokens = null;
|
|
349
|
+
if (!hasInput) inputTokens = null;
|
|
350
|
+
if (!hasCacheCreation) cacheCreationTokens = null;
|
|
351
|
+
if (!hasCacheRead) cacheReadTokens = null;
|
|
352
|
+
const seenUserMsg = /* @__PURE__ */ new Set();
|
|
353
|
+
let turns = 0;
|
|
354
|
+
for (const ev of events) {
|
|
355
|
+
if (!isUserEvent(ev)) continue;
|
|
356
|
+
if (ev.messageId) {
|
|
357
|
+
if (seenUserMsg.has(ev.messageId)) continue;
|
|
358
|
+
seenUserMsg.add(ev.messageId);
|
|
359
|
+
}
|
|
360
|
+
turns++;
|
|
361
|
+
}
|
|
362
|
+
const dotmemGroups = /* @__PURE__ */ new Map();
|
|
363
|
+
const dotmemNoId = [];
|
|
364
|
+
for (const ev of events) {
|
|
365
|
+
if (!DOTMEM(ev.toolName)) continue;
|
|
366
|
+
if (ev.toolCallId) {
|
|
367
|
+
if (!dotmemGroups.has(ev.toolCallId)) dotmemGroups.set(ev.toolCallId, []);
|
|
368
|
+
dotmemGroups.get(ev.toolCallId).push(ev);
|
|
369
|
+
} else {
|
|
370
|
+
if (isToolResultEvent(ev) && !isToolCallEvent(ev)) continue;
|
|
371
|
+
dotmemNoId.push(ev);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
let dotmemCalls = dotmemGroups.size + dotmemNoId.length;
|
|
375
|
+
let dotmemBytes = 0;
|
|
376
|
+
for (const g of dotmemGroups.values()) {
|
|
377
|
+
let bytes = null;
|
|
378
|
+
for (const ev of g) {
|
|
379
|
+
if (ev.resultBytes !== null && ev.resultBytes !== void 0) {
|
|
380
|
+
bytes = (bytes === null ? 0 : bytes) + ev.resultBytes;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (bytes !== null) dotmemBytes += bytes;
|
|
384
|
+
}
|
|
385
|
+
for (const ev of dotmemNoId) {
|
|
386
|
+
if (ev.resultBytes !== null && ev.resultBytes !== void 0) dotmemBytes += ev.resultBytes;
|
|
387
|
+
}
|
|
388
|
+
const stamped = events.map((ev) => normalizeTimestamp(ev.timestamp)).filter((t) => t !== null).sort((a, b) => a - b);
|
|
389
|
+
const startMs = stamped.length ? stamped[0] : 0;
|
|
390
|
+
const endMs = stamped.length ? stamped[stamped.length - 1] : startMs;
|
|
391
|
+
const activeMin = computeActiveMinExport(events, opts.capMin);
|
|
392
|
+
const wallMin = startMs === endMs ? 0 : (endMs - startMs) / 6e4;
|
|
393
|
+
const sessionId = events.length ? events[0].sessionId ?? null : null;
|
|
394
|
+
const projectId = events.length ? events[0].projectId ?? null : null;
|
|
395
|
+
return {
|
|
396
|
+
sessionId,
|
|
397
|
+
projectId,
|
|
398
|
+
activeMin,
|
|
399
|
+
wallMin,
|
|
400
|
+
turns,
|
|
401
|
+
outputTokens,
|
|
402
|
+
inputTokens,
|
|
403
|
+
cacheCreationTokens,
|
|
404
|
+
cacheReadTokens,
|
|
405
|
+
dotmemCalls,
|
|
406
|
+
dotmemBytes,
|
|
407
|
+
hasOutputTokens: hasOutput,
|
|
408
|
+
hasInputTokens: hasInput,
|
|
409
|
+
hasCacheCreationTokens: hasCacheCreation,
|
|
410
|
+
hasCacheReadTokens: hasCacheRead,
|
|
411
|
+
startMs,
|
|
412
|
+
endMs
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
__name(computeBurstMetrics, "computeBurstMetrics");
|
|
416
|
+
function computeActiveMinExport(events, capMin) {
|
|
417
|
+
const stamped = events.map((ev) => normalizeTimestamp(ev.timestamp)).filter((t) => t !== null).sort((a, b) => a - b);
|
|
418
|
+
const capMs = capMin * 60 * 1e3;
|
|
419
|
+
let total = 0;
|
|
420
|
+
for (let i = 0; i < stamped.length - 1; i++) {
|
|
421
|
+
const delta = stamped[i + 1] - stamped[i];
|
|
422
|
+
if (delta < 0) continue;
|
|
423
|
+
total += Math.min(delta, capMs);
|
|
424
|
+
}
|
|
425
|
+
return total / 6e4;
|
|
426
|
+
}
|
|
427
|
+
__name(computeActiveMinExport, "computeActiveMinExport");
|
|
428
|
+
function classifyBurst(activeMin, opts) {
|
|
429
|
+
if (activeMin < opts.shortMax) return "SHORT";
|
|
430
|
+
if (activeMin <= opts.longMax) return "MEDIUM";
|
|
431
|
+
return "LONG";
|
|
432
|
+
}
|
|
433
|
+
__name(classifyBurst, "classifyBurst");
|
|
434
|
+
|
|
435
|
+
// core/burst-stats/index.ts
|
|
436
|
+
function resolveOptions(opts) {
|
|
437
|
+
return {
|
|
438
|
+
gapMin: opts?.gapMin ?? 15,
|
|
439
|
+
capMin: opts?.capMin ?? 5,
|
|
440
|
+
shortMax: opts?.shortMax ?? 10,
|
|
441
|
+
longMax: opts?.longMax ?? 45
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
__name(resolveOptions, "resolveOptions");
|
|
445
|
+
function reconstructBursts(events, opts) {
|
|
446
|
+
const ro = resolveOptions(opts);
|
|
447
|
+
const { bursts: parts } = partitionIntoBursts(events, ro);
|
|
448
|
+
const result = [];
|
|
449
|
+
for (const p of parts) {
|
|
450
|
+
const m = computeBurstMetrics(p.events, ro);
|
|
451
|
+
const burst = {
|
|
452
|
+
sessionId: m.sessionId,
|
|
453
|
+
projectId: m.projectId,
|
|
454
|
+
events: p.events,
|
|
455
|
+
startMs: m.startMs,
|
|
456
|
+
endMs: m.endMs,
|
|
457
|
+
wallMin: m.wallMin,
|
|
458
|
+
activeMin: m.activeMin,
|
|
459
|
+
turns: m.turns,
|
|
460
|
+
outputTokens: m.outputTokens,
|
|
461
|
+
inputTokens: m.inputTokens,
|
|
462
|
+
cacheCreationTokens: m.cacheCreationTokens,
|
|
463
|
+
cacheReadTokens: m.cacheReadTokens,
|
|
464
|
+
dotmemCalls: m.dotmemCalls,
|
|
465
|
+
dotmemBytes: m.dotmemBytes,
|
|
466
|
+
hasOutputTokens: m.hasOutputTokens,
|
|
467
|
+
hasInputTokens: m.hasInputTokens,
|
|
468
|
+
hasCacheCreationTokens: m.hasCacheCreationTokens,
|
|
469
|
+
hasCacheReadTokens: m.hasCacheReadTokens
|
|
470
|
+
};
|
|
471
|
+
result.push(burst);
|
|
472
|
+
}
|
|
473
|
+
return result;
|
|
474
|
+
}
|
|
475
|
+
__name(reconstructBursts, "reconstructBursts");
|
|
476
|
+
function percentile(sorted, p) {
|
|
477
|
+
if (sorted.length === 0) return null;
|
|
478
|
+
if (sorted.length === 1) return sorted[0];
|
|
479
|
+
const arr = [...sorted].sort((a, b) => a - b);
|
|
480
|
+
const rank = p / 100 * (arr.length - 1);
|
|
481
|
+
const lo = Math.floor(rank);
|
|
482
|
+
const hi = Math.ceil(rank);
|
|
483
|
+
if (lo === hi) return arr[lo];
|
|
484
|
+
return arr[lo] + (arr[hi] - arr[lo]) * (rank - lo);
|
|
485
|
+
}
|
|
486
|
+
__name(percentile, "percentile");
|
|
487
|
+
function median(arr) {
|
|
488
|
+
return percentile(arr, 50);
|
|
489
|
+
}
|
|
490
|
+
__name(median, "median");
|
|
491
|
+
function sumNumbers(arr) {
|
|
492
|
+
let total = 0;
|
|
493
|
+
let has = false;
|
|
494
|
+
for (const v of arr) {
|
|
495
|
+
if (v !== null && v !== void 0) {
|
|
496
|
+
total += v;
|
|
497
|
+
has = true;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return has ? total : null;
|
|
501
|
+
}
|
|
502
|
+
__name(sumNumbers, "sumNumbers");
|
|
503
|
+
function aggregateOne(bursts) {
|
|
504
|
+
const n = bursts.length;
|
|
505
|
+
const activeArr = bursts.map((b) => b.activeMin);
|
|
506
|
+
const wallArr = bursts.map((b) => b.wallMin);
|
|
507
|
+
const dotmemCallsArr = bursts.map((b) => b.dotmemCalls);
|
|
508
|
+
const dotmemBytesArr = bursts.map((b) => b.dotmemBytes);
|
|
509
|
+
const turnsArr = bursts.map((b) => b.turns);
|
|
510
|
+
const outputArr = bursts.filter((b) => b.hasOutputTokens).map((b) => b.outputTokens);
|
|
511
|
+
const inputArr = bursts.filter((b) => b.hasInputTokens).map((b) => b.inputTokens);
|
|
512
|
+
const cacheCreationArr = bursts.filter((b) => b.hasCacheCreationTokens).map((b) => b.cacheCreationTokens);
|
|
513
|
+
const cacheReadArr = bursts.filter((b) => b.hasCacheReadTokens).map((b) => b.cacheReadTokens);
|
|
514
|
+
const classes = { SHORT: 0, MEDIUM: 0, LONG: 0 };
|
|
515
|
+
for (const b of bursts) {
|
|
516
|
+
if (b.activeMin < 10) classes.SHORT++;
|
|
517
|
+
else if (b.activeMin <= 45) classes.MEDIUM++;
|
|
518
|
+
else classes.LONG++;
|
|
519
|
+
}
|
|
520
|
+
return {
|
|
521
|
+
burstCount: n,
|
|
522
|
+
sampleSize: n,
|
|
523
|
+
activeMin: {
|
|
524
|
+
median: median(activeArr),
|
|
525
|
+
p25: percentile(activeArr, 25),
|
|
526
|
+
p75: percentile(activeArr, 75),
|
|
527
|
+
sampleSize: n,
|
|
528
|
+
reliable: n >= 5
|
|
529
|
+
},
|
|
530
|
+
wallMin: {
|
|
531
|
+
median: median(wallArr),
|
|
532
|
+
total: sumNumbers(wallArr)
|
|
533
|
+
},
|
|
534
|
+
classes,
|
|
535
|
+
dotmem: {
|
|
536
|
+
calls: {
|
|
537
|
+
mean: dotmemCallsArr.length ? dotmemCallsArr.reduce((a, b) => a + b, 0) / dotmemCallsArr.length : null,
|
|
538
|
+
median: median(dotmemCallsArr),
|
|
539
|
+
total: dotmemCallsArr.reduce((a, b) => a + b, 0)
|
|
540
|
+
},
|
|
541
|
+
bytes: {
|
|
542
|
+
median: median(dotmemBytesArr),
|
|
543
|
+
total: dotmemBytesArr.reduce((a, b) => a + b, 0)
|
|
544
|
+
}
|
|
545
|
+
},
|
|
546
|
+
turns: {
|
|
547
|
+
median: median(turnsArr),
|
|
548
|
+
total: turnsArr.reduce((a, b) => a + b, 0)
|
|
549
|
+
},
|
|
550
|
+
outputTokens: {
|
|
551
|
+
median: outputArr.length ? median(outputArr) : null,
|
|
552
|
+
total: sumNumbers(bursts.map((b) => b.outputTokens)),
|
|
553
|
+
available: bursts.some((b) => b.hasOutputTokens)
|
|
554
|
+
},
|
|
555
|
+
inputTokens: {
|
|
556
|
+
median: inputArr.length ? median(inputArr) : null,
|
|
557
|
+
total: sumNumbers(bursts.map((b) => b.inputTokens)),
|
|
558
|
+
available: bursts.some((b) => b.hasInputTokens)
|
|
559
|
+
},
|
|
560
|
+
cacheCreationTokens: {
|
|
561
|
+
median: cacheCreationArr.length ? median(cacheCreationArr) : null,
|
|
562
|
+
total: sumNumbers(bursts.map((b) => b.cacheCreationTokens)),
|
|
563
|
+
available: bursts.some((b) => b.hasCacheCreationTokens)
|
|
564
|
+
},
|
|
565
|
+
cacheReadTokens: {
|
|
566
|
+
median: cacheReadArr.length ? median(cacheReadArr) : null,
|
|
567
|
+
total: sumNumbers(bursts.map((b) => b.cacheReadTokens)),
|
|
568
|
+
available: bursts.some((b) => b.hasCacheReadTokens)
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
__name(aggregateOne, "aggregateOne");
|
|
573
|
+
function aggregateBursts(bursts, opts) {
|
|
574
|
+
const ro = resolveOptions(opts);
|
|
575
|
+
const stats = aggregateOne(bursts);
|
|
576
|
+
const classes = { SHORT: 0, MEDIUM: 0, LONG: 0 };
|
|
577
|
+
for (const b of bursts) {
|
|
578
|
+
const c = classifyBurst(b.activeMin, ro);
|
|
579
|
+
classes[c]++;
|
|
580
|
+
}
|
|
581
|
+
stats.classes = classes;
|
|
582
|
+
return stats;
|
|
583
|
+
}
|
|
584
|
+
__name(aggregateBursts, "aggregateBursts");
|
|
585
|
+
function analyzeEvents(events, opts, source) {
|
|
586
|
+
const ro = resolveOptions(opts);
|
|
587
|
+
let filteredEvents = events;
|
|
588
|
+
if (opts?.projectFilter) {
|
|
589
|
+
filteredEvents = events.filter((e) => (e.projectId ?? null) === opts.projectFilter);
|
|
590
|
+
}
|
|
591
|
+
const bursts = reconstructBursts(filteredEvents, ro);
|
|
592
|
+
const { invalidTimestamps } = partitionIntoBursts(filteredEvents, ro);
|
|
593
|
+
const global = aggregateBursts(bursts, ro);
|
|
594
|
+
const byProject = /* @__PURE__ */ new Map();
|
|
595
|
+
for (const ev of filteredEvents) {
|
|
596
|
+
const key = ev.projectId ?? "unknown";
|
|
597
|
+
if (!byProject.has(key)) byProject.set(key, []);
|
|
598
|
+
byProject.get(key).push(ev);
|
|
599
|
+
}
|
|
600
|
+
const projects = {};
|
|
601
|
+
for (const [pid, evs] of byProject) {
|
|
602
|
+
const bs = reconstructBursts(evs, ro);
|
|
603
|
+
projects[pid] = aggregateBursts(bs, ro);
|
|
604
|
+
}
|
|
605
|
+
return {
|
|
606
|
+
schemaVersion: "1.0.0",
|
|
607
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
608
|
+
parameters: { ...ro, project: opts?.projectFilter ?? null },
|
|
609
|
+
source: source || { paths: [], adapter: "generic" },
|
|
610
|
+
global,
|
|
611
|
+
projects,
|
|
612
|
+
invalidTimestamps,
|
|
613
|
+
totalEvents: filteredEvents.length
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
__name(analyzeEvents, "analyzeEvents");
|
|
617
|
+
function isDirectory(p) {
|
|
618
|
+
try {
|
|
619
|
+
return fs.statSync(p).isDirectory();
|
|
620
|
+
} catch {
|
|
621
|
+
return false;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
__name(isDirectory, "isDirectory");
|
|
625
|
+
function isFile(p) {
|
|
626
|
+
try {
|
|
627
|
+
return fs.statSync(p).isFile();
|
|
628
|
+
} catch {
|
|
629
|
+
return false;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
__name(isFile, "isFile");
|
|
633
|
+
function walkFiles(root) {
|
|
634
|
+
const out = [];
|
|
635
|
+
if (isFile(root)) return [root];
|
|
636
|
+
if (!isDirectory(root)) return [];
|
|
637
|
+
const stack = [root];
|
|
638
|
+
while (stack.length) {
|
|
639
|
+
const dir = stack.pop();
|
|
640
|
+
let entries;
|
|
641
|
+
try {
|
|
642
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
643
|
+
} catch {
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
for (const e of entries) {
|
|
647
|
+
const full = path2.join(dir, e.name);
|
|
648
|
+
if (e.isDirectory()) stack.push(full);
|
|
649
|
+
else if (e.isFile()) out.push(full);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
return out;
|
|
653
|
+
}
|
|
654
|
+
__name(walkFiles, "walkFiles");
|
|
655
|
+
function readSampleLines(filePath, n = 5) {
|
|
656
|
+
try {
|
|
657
|
+
const content = fs.readFileSync(filePath, "utf8");
|
|
658
|
+
return content.split(/\r?\n/).slice(0, n);
|
|
659
|
+
} catch {
|
|
660
|
+
return [];
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
__name(readSampleLines, "readSampleLines");
|
|
664
|
+
async function readFileEvents(adapter, filePath) {
|
|
665
|
+
if (typeof adapter.parseFile === "function") {
|
|
666
|
+
return adapter.parseFile(filePath);
|
|
667
|
+
}
|
|
668
|
+
const content = fs.readFileSync(filePath, "utf8");
|
|
669
|
+
return adapter.parse(content);
|
|
670
|
+
}
|
|
671
|
+
__name(readFileEvents, "readFileEvents");
|
|
672
|
+
|
|
673
|
+
// core/burst-stats/cli.ts
|
|
674
|
+
function parseArgs(argv) {
|
|
675
|
+
const opts = {};
|
|
676
|
+
for (let i = 0; i < argv.length; i++) {
|
|
677
|
+
const a = argv[i];
|
|
678
|
+
const next = /* @__PURE__ */ __name(() => argv[++i], "next");
|
|
679
|
+
switch (a) {
|
|
680
|
+
case "--source":
|
|
681
|
+
opts.source = next();
|
|
682
|
+
break;
|
|
683
|
+
case "--adapter":
|
|
684
|
+
opts.adapter = next();
|
|
685
|
+
break;
|
|
686
|
+
case "--gap-min":
|
|
687
|
+
opts.gapMin = Number(next());
|
|
688
|
+
break;
|
|
689
|
+
case "--cap-min":
|
|
690
|
+
opts.capMin = Number(next());
|
|
691
|
+
break;
|
|
692
|
+
case "--short-max":
|
|
693
|
+
opts.shortMax = Number(next());
|
|
694
|
+
break;
|
|
695
|
+
case "--long-max":
|
|
696
|
+
opts.longMax = Number(next());
|
|
697
|
+
break;
|
|
698
|
+
case "--project":
|
|
699
|
+
opts.project = next();
|
|
700
|
+
break;
|
|
701
|
+
case "--format":
|
|
702
|
+
opts.format = next();
|
|
703
|
+
break;
|
|
704
|
+
case "--output":
|
|
705
|
+
opts.output = next();
|
|
706
|
+
break;
|
|
707
|
+
case "--list-adapters":
|
|
708
|
+
opts.listAdapters = true;
|
|
709
|
+
break;
|
|
710
|
+
case "--help":
|
|
711
|
+
case "-h":
|
|
712
|
+
opts.help = true;
|
|
713
|
+
break;
|
|
714
|
+
default:
|
|
715
|
+
if (!a.startsWith("--") && !opts.source) opts.source = a;
|
|
716
|
+
break;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return opts;
|
|
720
|
+
}
|
|
721
|
+
__name(parseArgs, "parseArgs");
|
|
722
|
+
function printHelp() {
|
|
723
|
+
return `Dotmem Burst Stats
|
|
3
724
|
|
|
4
725
|
Usage: dotmem-burst-stats [options]
|
|
5
726
|
|
|
@@ -15,11 +736,108 @@ Options:
|
|
|
15
736
|
--output <path> Output destination
|
|
16
737
|
--list-adapters List available adapters
|
|
17
738
|
--help Show help
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
739
|
+
`;
|
|
740
|
+
}
|
|
741
|
+
__name(printHelp, "printHelp");
|
|
742
|
+
async function runBurstStatsCli(argv = process.argv.slice(2)) {
|
|
743
|
+
const opts = parseArgs(argv);
|
|
744
|
+
if (opts.help) {
|
|
745
|
+
process.stdout.write(printHelp());
|
|
746
|
+
return 0;
|
|
747
|
+
}
|
|
748
|
+
if (opts.listAdapters) {
|
|
749
|
+
process.stdout.write(listAdapters().join("\n") + "\n");
|
|
750
|
+
return 0;
|
|
751
|
+
}
|
|
752
|
+
if (!opts.source) {
|
|
753
|
+
process.stderr.write("Error: --source is required\n");
|
|
754
|
+
return 2;
|
|
755
|
+
}
|
|
756
|
+
const sourcePath = path2.resolve(opts.source);
|
|
757
|
+
const files = walkFiles(sourcePath);
|
|
758
|
+
if (files.length === 0) {
|
|
759
|
+
process.stderr.write("Error: no files found\n");
|
|
760
|
+
return 2;
|
|
761
|
+
}
|
|
762
|
+
const allEvents = [];
|
|
763
|
+
const usedAdapters = /* @__PURE__ */ new Set();
|
|
764
|
+
const sourcePaths = [];
|
|
765
|
+
for (const f of files) {
|
|
766
|
+
const sample = readSampleLines(f);
|
|
767
|
+
let adapter;
|
|
768
|
+
if (opts.adapter) adapter = getAdapter(opts.adapter);
|
|
769
|
+
else adapter = detectAdapter(sample, f);
|
|
770
|
+
if (!adapter) continue;
|
|
771
|
+
try {
|
|
772
|
+
const evs = await readFileEvents(adapter, f);
|
|
773
|
+
if (evs && evs.length > 0) {
|
|
774
|
+
allEvents.push(...evs);
|
|
775
|
+
usedAdapters.add(adapter.name);
|
|
776
|
+
sourcePaths.push(f);
|
|
777
|
+
}
|
|
778
|
+
} catch (e) {
|
|
779
|
+
process.stderr.write(`Warning: failed to parse ${f}: ${e instanceof Error ? e.message : String(e)}
|
|
780
|
+
`);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
const adapterName = opts.adapter || (usedAdapters.size === 1 ? [...usedAdapters][0] : "auto");
|
|
784
|
+
const result = analyzeEvents(allEvents, {
|
|
785
|
+
gapMin: opts.gapMin,
|
|
786
|
+
capMin: opts.capMin,
|
|
787
|
+
shortMax: opts.shortMax,
|
|
788
|
+
longMax: opts.longMax,
|
|
789
|
+
projectFilter: opts.project ?? null
|
|
790
|
+
}, { paths: sourcePaths.map((p) => path2.basename(p)), adapter: adapterName });
|
|
791
|
+
if (opts.format === "json") {
|
|
792
|
+
const json = JSON.stringify(result, null, 2);
|
|
793
|
+
if (opts.output) fs.writeFileSync(opts.output, json);
|
|
794
|
+
else process.stdout.write(json + "\n");
|
|
795
|
+
} else {
|
|
796
|
+
const text = renderText(result);
|
|
797
|
+
if (opts.output) fs.writeFileSync(opts.output, text);
|
|
798
|
+
else process.stdout.write(text);
|
|
799
|
+
}
|
|
800
|
+
return 0;
|
|
801
|
+
}
|
|
802
|
+
__name(runBurstStatsCli, "runBurstStatsCli");
|
|
803
|
+
function renderText(result, _opts) {
|
|
804
|
+
const g = result.global;
|
|
805
|
+
const lines = [];
|
|
806
|
+
lines.push("Dotmem Burst Stats");
|
|
807
|
+
lines.push("");
|
|
808
|
+
lines.push(`Source: local transcripts`);
|
|
809
|
+
lines.push(`Adapter: ${result.source.adapter}`);
|
|
810
|
+
lines.push(`Bursts: ${g.burstCount}`);
|
|
811
|
+
lines.push(`Gap: ${result.parameters.gapMin} min`);
|
|
812
|
+
lines.push(`Interval cap: ${result.parameters.capMin} min`);
|
|
813
|
+
lines.push("");
|
|
814
|
+
lines.push("Active time");
|
|
815
|
+
lines.push(` Median: ${fmt(g.activeMin.median)} min`);
|
|
816
|
+
lines.push(` P25: ${fmt(g.activeMin.p25)} min`);
|
|
817
|
+
lines.push(` P75: ${fmt(g.activeMin.p75)} min`);
|
|
818
|
+
lines.push("");
|
|
819
|
+
lines.push("Burst classes");
|
|
820
|
+
lines.push(` SHORT: ${g.classes.SHORT}`);
|
|
821
|
+
lines.push(` MEDIUM: ${g.classes.MEDIUM}`);
|
|
822
|
+
lines.push(` LONG: ${g.classes.LONG}`);
|
|
823
|
+
lines.push("");
|
|
824
|
+
lines.push("Dotmem");
|
|
825
|
+
lines.push(` Calls: ${g.dotmem.calls.total}`);
|
|
826
|
+
lines.push(` Bytes: ${g.dotmem.bytes.total}`);
|
|
827
|
+
lines.push("");
|
|
828
|
+
lines.push(`Output tokens: ${g.outputTokens.total ?? 0}`);
|
|
829
|
+
lines.push("");
|
|
830
|
+
return lines.join("\n");
|
|
831
|
+
}
|
|
832
|
+
__name(renderText, "renderText");
|
|
833
|
+
function fmt(n) {
|
|
834
|
+
if (n === null || n === void 0) return "n/a";
|
|
835
|
+
return Number(n).toFixed(1);
|
|
836
|
+
}
|
|
837
|
+
__name(fmt, "fmt");
|
|
838
|
+
|
|
839
|
+
// bin/dotmem-burst-stats.ts
|
|
840
|
+
void (async () => {
|
|
841
|
+
const code = await runBurstStatsCli(process.argv.slice(2));
|
|
842
|
+
process.exit(code);
|
|
843
|
+
})();
|