// @ts-nocheck — browser bundle source (never node-imported; client.mjs
// reads it as text). See src/lib/dashboard/client/**'s eslint.config.mjs
// override comment for why this directory isn't run through the node lib.
import { SESSION_HOST_LABELS, sessionProviderPresentation } from '../../session-surface.mjs';
import { surfaceDetailHtml } from './session-presentation.mjs';
import { formatLocalDateTime } from './datetime.mjs';
import { VIEWS, authHeaders, esc, setTab, syncHash } from './bootstrap.mjs';
import { ago } from './intelligence.mjs';
import { renderModelFacets, renderModelInventory, renderModelLifecycle } from './model-lifecycle.mjs';
import { bucketPercentile, bucketPositionPct, deltaChip, donut2, histogram, rankedRows, sparklineSvg, stackedDays } from './usage-rhythm.mjs';
import { hostInterplay, patternsPanel, promptKpis, provenancePanel, steerPanel, tapLengthPanel } from './usage-prompts.mjs';
import { activateUsageEvidenceView } from './usage-context-hooks.mjs';
import { renderUsage } from './usage-orchestrators.mjs';
// ══ Usage tab ══════════════════════════════════════════════════════════════
export var USAGE=null, usageLoaded=false, usageBusy=false, TRANSCRIPT=null;
export var MODELS=null,MODEL_PAGE=null,modelRows=[],modelSnapshotId=null,modelsBusy=false,modelRequestSeq=0,modelSearchTimer=null;
export var MODEL_LIMIT=50,modelSort="lifecycle",modelDirection="asc",modelRouteSort="model",modelRouteDirection="asc";
function fmtUsd(n){
n=Number(n)||0;
if(n>=1000)return "$"+Math.round(n).toLocaleString();
if(n>=10)return "$"+n.toFixed(0);
return "$"+n.toFixed(2);
}
// A POSITIVE figure that rounds away at two decimals is not $0.00 — printing
// it that way beside a caption about excluding $0-by-construction sessions
// reads as "the median session was free", which is a different claim from
// "the median session cost less than a cent". The threshold is derived from
// fmtUsd's own output rather than restating its rounding rule, so the two
// cannot disagree. A true zero is left alone: it is not less than a cent.
function fmtUsdMin(n){
var v=Number(n)||0,txt=fmtUsd(v);
return (v>0&&txt==="$0.00")?"<$0.01":txt;
}
export function fmtNum(n){return (Number(n)||0).toLocaleString();}
export function fmtTok(n){
n=Number(n)||0;
if(n>=1e9)return (n/1e9).toFixed(1)+"B";
if(n>=1e6)return (n/1e6).toFixed(1)+"M";
if(n>=1e3)return (n/1e3).toFixed(1)+"K";
return String(Math.round(n));
}
function fmtHours(sec){var h=(Number(sec)||0)/3600; return (h>=10?Math.round(h):h.toFixed(1))+"h";}
function fmtMins(m){m=Number(m)||0; return m>=60?Math.round(m/60)+"h":Math.round(m)+"m";}
function fld(v,k){
if(v==null)return 0;
if(typeof v==="number")return k==="cost"?v:0;
return Number(v[k])||0;
}
export function pct(a,b){return b?(a/b*100):0;}
function entries(map,key){
var out=[];
for(var k in (map||{}))out.push({name:k,v:map[k],cost:fld(map[k],key||"cost")});
out.sort(function(a,b){return b.cost-a.cost;});
return out;
}
// One pill per HOST, not per sourceHealth field: Codex carries two fields
// (its transcript root, plus the thread ledger that corrects subagent-replay
// token inflation) but is still one host, so the worse of the two drives the
// pill's status and both stay reachable via the status side's tooltip.
var SOURCE_HEALTH_GROUPS=[
{host:"claude",label:"Claude",title:"Claude Code — ~/.claude/projects/**/*.jsonl",parts:[{key:"claude"}]},
{host:"codex",label:"Codex",title:"Codex — ~/.codex/sessions/**/rollout-*.jsonl, plus Codex's own thread ledger",
parts:[{key:"codex",sub:"transcripts"},{key:"codexLedger",sub:"ledger"}]},
{host:"opencode",label:"OpenCode",title:"OpenCode — its SQLite session store",parts:[{key:"opencode"}]}
];
var SOURCE_HEALTH_RANK={degraded:0,"not-read":1,absent:2,ok:3}; // lower sorts first = worse
function sourceHealthRank(status){
var r=SOURCE_HEALTH_RANK[status];
return r===undefined?1:r;
}
// Same brand marks as the Observability Live view's hostIcon() (live/client.mjs)
// — reused verbatim so a host reads as the same glyph everywhere in the
// dashboard, not a second, subtly different icon set.
export function sourceHostIcon(host){
var view="0 0 16 16",body;
if(host==="claude")body='';
else if(host==="codex"){
view="146 227 268 267";
body='';
} else if(host==="opencode"){
view="0 0 300 300";
body='';
} else body='';
return'';
}
export function renderSourceHealth(health){
var el=document.getElementById("u-source-health");
if(!el)return;
health=health||{};
var pills=[],details=[];
for(var g=0; g'+esc(detail)+'');
pills.push(''
+''+sourceHostIcon(grp.host)+''
+''+esc(({ok:'Readable',degraded:'Partial data',absent:'No records','not-read':'Not checked'})[lead.status]||'Not checked')+''
+'');
}
el.hidden=pills.length===0;
el.innerHTML=pills.join("")+'
'+details.join("")+'
';
}
export function loadUsage(force){
if(usageBusy)return Promise.resolve();
usageBusy=true;
var jobs=[fetch("/api/usage?days="+usageDays,{cache:"no-store",headers:authHeaders()}).then(function(r){return r.json();})
.then(function(d){USAGE=d; usageLoaded=true;})];
if(usageView==="transcript"&&usageSession&&(force||!TRANSCRIPT||TRANSCRIPT.id!==usageSession))
jobs.push(loadTranscript(usageSession));
return Promise.all(jobs).catch(function(){
USAGE={error:"usage index unavailable"};
}).then(function(){usageBusy=false; renderUsage();});
}
function loadTranscript(id){
return fetch("/api/session/"+encodeURIComponent(id),{cache:"no-store",headers:authHeaders()})
.then(function(r){return r.json();})
.then(function(d){TRANSCRIPT=d&&!d.error?{id:id,meta:d.meta,turns:d.turns||[]}:{id:id,error:(d&&d.error)||"unreadable"};});
}
function modelJson(url){
return fetch(url,{cache:"no-store",headers:authHeaders()}).then(function(r){
return r.json().then(function(d){
if(!r.ok){var error=new Error(d&&d.error||"unavailable");error.status=r.status;throw error;}
return d;
});
});
}
export function modelFilters(){
function value(id){var el=document.getElementById(id);return el?String(el.value||"").trim():"";}
var evidenceField=value("mli-evidence-field"),evidenceValue=value("mli-evidence-value");
if(!evidenceField||!evidenceValue){evidenceField="";evidenceValue="";}
return {search:value("mli-search"),host:value("mli-host"),provider:value("mli-provider"),
relevance:value("mli-relevance")||"relevant",
lifecycle:value("mli-lifecycle"),evidenceField:evidenceField,evidenceValue:evidenceValue};
}
function modelInventoryUrl(offset){
var query=new URLSearchParams({view:"inventory",offset:String(offset||0),limit:String(MODEL_LIMIT),
sort:modelSort,direction:modelDirection}),filters=modelFilters();
if(modelSnapshotId)query.set("snapshotId",modelSnapshotId);
Object.keys(filters).forEach(function(key){if(filters[key])query.set(key,filters[key]);});
return "/api/models?"+query.toString();
}
function setModelsBusy(busy,message){
modelsBusy=busy;
var panel=document.getElementById("v-models"),status=document.getElementById("mli-load-status"),more=document.getElementById("mli-load-more");
if(panel)panel.setAttribute("aria-busy",busy?"true":"false");
if(more)more.disabled=busy;
if(status&&message)status.textContent=message;
}
export function loadModelInventory(offset,append,focusAfter){
var seq=++modelRequestSeq,priorLength=modelRows.length;
setModelsBusy(true,append?"Loading more model evidence.":"Loading model inventory evidence.");
return modelJson(modelInventoryUrl(offset)).then(function(d){
if(seq!==modelRequestSeq)return;
var nextSnapshotId=d&&d.snapshot&&d.snapshot.snapshotId||null;
if(modelSnapshotId&&nextSnapshotId!==modelSnapshotId){
modelSnapshotId=null;
return loadModelLifecycle(true,focusAfter,true);
}
modelSnapshotId=nextSnapshotId;
MODEL_PAGE=d&&d.inventory||{};
var items=Array.isArray(MODEL_PAGE.items)?MODEL_PAGE.items:[];
modelRows=append?modelRows.concat(items):items;
renderModelInventory();
renderModelFacets();
setModelsBusy(false,"Model lifecycle evidence loaded. "+modelRows.length+" rows shown.");
var more=document.getElementById("mli-load-more");if(more)more.textContent="Load 50 more";
if(focusAfter){
var headers=document.querySelectorAll("#mli-models tr > th[scope=row]");
var target=headers[append?priorLength:0],region=document.querySelector(".mli-table-wrap");
if(append&&more&&!more.hidden)more.focus();else if(target)target.focus();else if(region)region.focus();
}
}).catch(function(error){
if(seq!==modelRequestSeq)return;
if(error&&error.status===409){
modelSnapshotId=null;
setModelsBusy(true,"Model inventory changed; reloading its summary and first page.");
return loadModelLifecycle(true,focusAfter,true);
}
if(append){
var more=document.getElementById("mli-load-more");
if(more){more.hidden=false;more.disabled=false;more.textContent="Retry loading 50 more";more.focus();}
setModelsBusy(false,"More model lifecycle evidence is unavailable; prior rows were preserved.");
return;
}
MODEL_PAGE={items:[],total:0,filteredTotal:0,relevantTotal:0,offset:0,limit:MODEL_LIMIT,hasMore:false};
modelRows=[];modelSnapshotId=null;
renderModelInventory();
setModelsBusy(false,"Model lifecycle evidence is unavailable.");
});
}
export function loadModelLifecycle(force,focusAfter,recovering){
if(!recovering&&(modelsBusy||(!force&&MODELS)))return Promise.resolve();
setModelsBusy(true,"Loading model lifecycle summary.");
return modelJson("/api/models?view=summary&days="+usageDays).then(function(d){
MODELS=d;
modelSnapshotId=d&&d.snapshot&&d.snapshot.snapshotId||null;
renderModelLifecycle();
if(!LIMITS)loadLimits();
return loadModelInventory(0,false,!!focusAfter);
}).catch(function(){
MODELS={error:"model inventory unavailable"};MODEL_PAGE=null;modelRows=[];modelSnapshotId=null;
renderModelLifecycle();renderModelInventory();
setModelsBusy(false,"Model lifecycle evidence is unavailable.");
});
}
export function setUsageView(v,session){
usageView=v;
if(session!==undefined)usageSession=session;
var headings={score:["Usage scorecard","Token consumption, API-equivalent cost, efficiency, and trends."],limits:["Provider limits","Current provider windows, reset timing, and available capacity."],findings:["Usage findings","Actionable anomalies, efficiency opportunities, and evidence-backed recommendations."],prompts:["Prompt patterns","What you type across every host, which patterns repeat, and what to change — from fingerprints, with masked prompt text on demand."],context:["Context","Runtime-observed context pressure, conservative policy thresholds, and evidence coverage by host."],hooks:["Hooks","Read-only configuration assurance and separately evidenced runtime outcomes."],sessions:["Session usage","Browse retained sessions by project, category, duration, tokens, and cost."],models:["Models","Observed models in this window, configured routes, and the separate provider/local catalogue."],transcript:["Transcript detail","Inspect the selected session's locally retained, server-masked evidence."]},heading=headings[v]||headings.score;
document.getElementById("usage-view-title").textContent=heading[0];document.getElementById("usage-view-description").textContent=heading[1];
var btns=document.querySelectorAll("#usage-seg [data-view]");
for(var i=0;i=365){
var fallback=document.querySelector('#usage-days [data-days="30"]');
if(fallback)fallback.click();
}
}
// Explicit bridge from Observability metadata to the separately fetched,
// server-masked historical transcript. Returning false lets a caller keep its
// current selection when an untrusted/malformed identifier is supplied.
window.AKDashboardOpenTranscript=function(id){
id=String(id==null?"":id);
if(!/^[A-Za-z0-9._-]{1,128}$/.test(id)||id==="."||id==="..")return false;
setTab("usage");
setUsageView("transcript",id);
return true;
};
// titleTxt is optional and goes on the OUTER .kpi, so the whole card is the
// hover target — a tooltip anchored to the number alone would be a 40px
// target for a 200px card. Omitted entirely when not passed, so no card
// gains an empty title="".
export function kpi(k,v,d,cls,titleTxt){
return '
'+esc(k)+'
'+esc(v)+'
'
+'
'+d+"
";
}
function bar(label,valueTxt,subTxt,share,alt,extra){
return '
";
}
// ADR-0009 §4 — all three time tiers, as the asserted ordering
// engaged <= open <= summed. The visible KPI still leads with the honest
// figure; this is the SUPPORTING EVIDENCE for it, which is why it lives in a
// tooltip and not in the hero row. Hover is a weak channel (undiscoverable by
// accident, absent on touch) and the ADR records that trade-off: a reader who
// never hovers is less informed, not misled. Every figure comes from totals —
// nothing here is computed a second way.
function ladder(t){
return "engaged "+fmtHours(t.engagedSeconds)
+" ≤ open "+fmtHours(t.spanUnionSeconds)
+" ≤ summed "+fmtHours((Number(t.spanMinutes)||0)*60)+"\n"
+"engaged unions active sub-intervals split at 15-min silences; "
+"open unions whole session spans; summed double-counts overlap.";
}
// ── panels grafted onto the served scorecard markup ───────────────────────
// page.mjs renders the scorecard's containers. The panels below arrived
// after that markup shipped and build their own container instead of growing
// the served template with ids it has no other reason to know about. Every
// one is IDEMPOTENT: renderScore runs on each poll, so a second call finds
// the container the first call built rather than stacking a duplicate.
//
// scoreBlock walks up to the direct child of #v-score that owns `id`, which
// is the granularity the scorecard's own layout uses (a .strip, a .two pair,
// the .hero grid) — so an inserted panel lands between whole sections, never
// inside one.
function scoreBlock(id){
var el=document.getElementById(id),view=document.getElementById("v-score");
if(!el||!view)return null;
while(el&&el.parentNode&&el.parentNode!==view)el=el.parentNode;
return (el&&el.parentNode===view)?el:null;
}
function ensureBlock(probeId,html,afterId){
var existing=document.getElementById(probeId);
if(existing)return existing;
var anchor=scoreBlock(afterId);
if(!anchor)return null;
var host=document.createElement("div");
host.innerHTML=html;
var node=host.firstElementChild;
if(!node)return null;
anchor.parentNode.insertBefore(node,anchor.nextSibling);
return document.getElementById(probeId);
}
// The same heading grammar the served markup uses, so an inserted panel is
// indistinguishable from a static one. `note` is escaped: every caller
// passes a literal caption, and a panel's live figures belong in its body
// (rewritten each render) rather than in a header this builds once.
function stripHtml(bodyId,heading,note){
return '
'+esc(heading)+"
"
+''+esc(note)+"
"
+'';
}
// A legend the chart primitives do not draw for themselves. Reuses the
// scorecard's own .legend/.lg grammar so an external legend is the same
// object here as it is under the token bar. The label is always spelled out
// beside the swatch — the hue is a hint, never the only way to read a series.
function chartLegend(items){
return '
";
}
// byDay ascending. Shared by the day-bar strip and every per-day series
// below, so they cannot disagree about which days are in the window.
function dayRows(d){
var out=[],k;
for(k in (d.byDay||{}))out.push({day:k,v:d.byDay[k]});
out.sort(function(a,b){return a.day=10?String(Math.round(n)):n.toFixed(1);
}
// Durations that span four orders of magnitude (a 1.4s reply, a 3h session)
// in one compact token. A whole number of hours prints as "2h", not "2.0h":
// the extra digit claims a precision a bucket floor does not have.
function fmtSecs(sec){
sec=Number(sec)||0;
// <=60, not <60: the latency histogram's overflow bucket floor IS 60s, and
// that value has to read "60s" so "≥60s" names the bucket edge the reader
// can see on the axis. Rolling it up to "1m" renamed the boundary.
if(sec<=60)return (sec<10?Math.round(sec*10)/10:Math.round(sec))+"s";
if(sec<5400)return Math.round(sec/60)+"m";
var h=Math.round(sec/360)/10;
return (h%1===0?String(h):h.toFixed(1))+"h";
}
// A value from a histogram's OVERFLOW bucket has no upper edge to
// interpolate towards, so the percentile reports that bucket's FLOOR.
// Printing it bare would state a figure the counts cannot support, so it is
// prefixed and reads "at least this". `lastEdge` is that floor.
function fmtAtLeast(v,lastEdge,fmt){
if(v==null||!isFinite(v))return "—";
return (v>=lastEdge?"≥":"")+fmt(v);
}
// renderScore was one CC-41 function writing ~10 independent scorecard
// regions (hero KPIs, cost-per-day bars, host cards, token bar/legend,
// punchcard, models, OpenRouter, projects, categories) in sequence. Split
// by region; each keeps its original logic verbatim, so the rendered DOM
// and its ordering are unchanged.
// A hero tile's footer: the change against the previous equal-length window,
// and a per-day trend for the same figure. Both self-suppress when the data
// cannot support them (deltaChip is '' with no previous window, sparklineSvg
// is '' below two points), so a tile with neither renders exactly as it did
// before this row existed.
function kpiFoot(chip,spark){
return (chip||spark)?'
'+chip+spark+"
":"";
}
// The cache tile's own dollar claim. cacheSavedUsd is computed server-side
// as a DIFFERENCE — the same tokens priced as fresh input minus priced as
// cache reads, at the rate in effect on the day they were spent — so it
// cannot drift out of step with the pricing table the way a hardcoded
// discount factor would. Rendered only when there is a figure to render.
function cacheSubtitle(t){
var saved=Number(t.cacheSavedUsd)||0;
return "model-specific cache rates"
+(saved>0?'saved ≈ '+esc(fmtUsd(saved))+" vs uncached":"");
}
var CACHE_TIP="Share of this window's tokens that were cache reads. Higher is cheaper, so a rise "
+"is the good direction.\nsaved ≈ prices the same cache-read tokens as fresh input and takes the "
+"gap, at each day's own rate.\nThe trend is that share recomputed per day. A day that billed no "
+"tokens has no share to compute, so the line breaks across it rather than carrying a neighbour's "
+"value forward.";
// Engaged time is the ONE hero trend drawn from a different day set. Said on
// the tile, because the tiles otherwise look directly comparable and are not.
var ENGAGED_TREND_NOTE="\ntrend covers days you worked; the other tiles' trends cover billed days.";
function renderScoreHero(d){
var t=d.totals||{},p=(d.previous&&d.previous.totals)||{};
var rows=dayRows(d);
var cacheShare=pct(t.cacheRead,t.tokens),prevCacheShare=pct(p.cacheRead,p.tokens);
function spark(pick){return sparklineSvg(rows.map(pick),{});}
document.getElementById("u-hero").innerHTML=
kpi("sessions",fmtNum(t.sessions),esc(fmtNum(t.responses))+" assistant turns"
+kpiFoot(deltaChip(t.sessions,p.sessions,{}),
spark(function(x){return fld(x.v,"sessions");})),"")
+kpi("api-equivalent",fmtUsd(t.cost),"list price · not plan billing"
+kpiFoot(deltaChip(t.cost,p.cost,{downIsGood:true}),
spark(function(x){return fld(x.v,"cost");})),"accent")
+kpi("tokens",fmtTok(t.tokens),esc(fmtTok(t.output))+" out · "+esc(fmtTok(t.cacheRead))+" cached"
+kpiFoot(deltaChip(t.tokens,p.tokens,{neutral:true}),
spark(function(x){return fld(x.v,"tokens");})),"")
+kpi("engaged time",fmtHours(t.engagedSeconds),
esc(fmtMins(t.spanMinutes))+" summed"
+'sessions overlap'
+kpiFoot(deltaChip(t.engagedSeconds,p.engagedSeconds,{}),
sparklineSvg(mapRows(d.engagedByDay).map(function(x){return Number(x.v)||0;}),{})),
"",ladder(t)+ENGAGED_TREND_NOTE)
// Cache share is up-good, unlike the cost tile beside it: cache reads
// bill at 0.1× input, so a bigger share of them is a cheaper window.
// The delta is in percentage POINTS — a percent-of-a-percent would be
// read as a share change and is not what moved.
// A day that billed no tokens has no share to compute. It keeps its slot
// in the series as a null, which sparklineSvg draws as a BREAK — never a
// carried-forward value, which would state a figure for a day that has
// none, and never a dropped point, which would squeeze the time axis.
+kpi("cache read",cacheShare.toFixed(1)+"%",cacheSubtitle(t)
+kpiFoot(deltaChip(cacheShare,prevCacheShare,{unit:" pp"}),
spark(function(x){
var tok=fld(x.v,"tokens");
return tok?pct(fld(x.v,"cacheRead"),tok):null;
})),"warnv",CACHE_TIP);
document.getElementById("u-asof").textContent=d.pricesAsOf?("rates as of "+d.pricesAsOf):"";
}
// ── second KPI row: cadence, autonomy, unit economics ─────────────────────
var TIP_PER_DAY="Sessions ÷ active days.\nAn ACTIVE day is one this window actually billed tokens "
+"on — that is byDay's own contract, so a day worked but never billed is not counted and breaks "
+"the streak.\nStreak counts consecutive active days ending at the most recent one.\n"
+"Sessions INCLUDES delegated subagent sessions, which the harness dispatches rather than you — "
+"the how-you-run panel carries the main/subagent split.";
var TIP_AUTONOMY="Assistant responses ÷ recorded main-thread prompts — how far each prompt travels.\n"
+"Prompts are MAIN-THREAD only: a subagent's prompts are written by the harness, not by you, so "
+"counting them would inflate the denominator with work nobody asked for by hand.\nTouch rate is "
+"those same prompts per engaged hour.";
var TIP_PER_SESSION="Median api-equivalent cost of one session, and the 90th percentile of the same "
+"set.\nSessions with NO token evidence at all are excluded: they are structurally $0 (a Codex "
+"subagent rollout whose tokens were stripped as a double-count, say), not cheap, and folding "
+"them in would drag the median toward zero for a reason that is not about spend.\n<$0.01 means "
+"a real, positive figure smaller than a cent — not zero.";
var TIP_PER_HOUR="Api-equivalent cost ÷ engaged hours.\nEngaged time unions active sub-intervals "
+"split at 15-minute silences — not wall clock, and not the sum of session spans, which "
+"double-counts overlap.\n— when no engaged time was measured.";
function dayBefore(day){
var t=Date.parse(String(day)+"T00:00:00Z");
if(!isFinite(t))return null;
return new Date(t-86400000).toISOString().slice(0,10);
}
function activeStreak(days){
if(!days.length)return 0;
var n=1;
for(var i=days.length-1;i>0;i--){
if(dayBefore(days[i])!==days[i-1])break;
n++;
}
return n;
}
function cadenceCells(t,active,streak){
var perDay=active?(Number(t.sessions)||0)/active:null;
var auto=t.responsesPerPrompt,touch=t.humanPromptsPerHour;
var med=t.costPerSessionMedian,p90=t.costPerSessionP90,perHour=t.costPerEngagedHour;
return kpi("sessions / active day",fmtRatio(perDay),
esc(fmtNum(active))+" active day"+(active===1?"":"s")
+'streak '+esc(String(streak))+" day"+(streak===1?"":"s")+"","",TIP_PER_DAY)
+kpi("autonomy",auto==null?"—":fmtRatio(auto)+"×",
auto==null?"no recorded main-thread prompts in window"
:(touch==null?"touch rate not recorded"
:esc(fmtRatio(touch))+" prompts / engaged hour"),"",TIP_AUTONOMY)
+kpi("cost / session",med==null?"—":fmtUsdMin(med),
med==null?"no priced sessions in window"
:"median · excludes $0-by-construction"
+'P90 '+esc(p90==null?"—":fmtUsdMin(p90))+"","",TIP_PER_SESSION)
+kpi("cost / engaged hour",perHour==null?"—":fmtUsd(perHour),
perHour==null?"no engaged time measured":"engaged time, not wall clock","",TIP_PER_HOUR);
}
function renderScoreCadence(d){
var body=ensureBlock("u-cadence",'',"u-hero");
if(!body)return;
var days=dayRows(d).map(function(x){return x.day;});
body.innerHTML=cadenceCells(d.totals||{},days.length,activeStreak(days));
}
// ── rhythm: how long sessions run, how long replies take ──────────────────
// The edges are restated from usage-aggregate.mjs's exported
// LAT_BUCKET_EDGES/LEN_BUCKET_EDGES: the payload ships the COUNTS, never the
// edges they were binned on, and this file is read as text into a browser
// bundle that cannot import that module. A test pins the copies equal, so a
// change to either goes red instead of silently re-labelling every bucket.
var LAT_EDGES=[2,5,10,30,60];
var LAT_LABELS=["≤2s","≤5s","≤10s","≤30s","≤60s",">60s"];
var LEN_EDGES=[300,900,2700,7200];
var LEN_LABELS=["≤5m","≤15m","≤45m","≤2h",">2h"];
var LAT_TIP="Wall-clock gap between a prompt and the response that answered it.\n"
+"codex host-measured · claude/opencode derived from event gaps — not streaming TTFT.\n"
+"The last bucket has no upper edge, so a percentile landing in it reports that bucket's "
+"floor: printed with ≥, read as \"at least this\".\n"
+"INCLUDES delegated subagent responses — the how-you-run panel carries the split.";
var LEN_TIP="Engaged length of one session — the union of its active sub-intervals, split at "
+"15-minute silences, not its first-to-last span.\nThe last bucket has no upper edge, so a "
+"percentile landing in it is printed with ≥.\n"
+"INCLUDES delegated subagent sessions — the how-you-run panel carries the split.";
function histMarker(value,edges,label){
var at=bucketPositionPct(edges,value);
return at==null?null:{atPct:at,label:label};
}
function histCard(o){
var counts=Array.isArray(o.counts)?o.counts:[];
var total=counts.reduce(function(a,n){return a+(Number(n)||0);},0);
return '
";
}
function lengthCard(r){
var med=r.lenMedianSeconds,p90=r.lenP90Seconds;
var medTxt=fmtAtLeast(med,7200,fmtSecs),p90Txt=fmtAtLeast(p90,7200,fmtSecs);
return histCard({title:"session length",counts:r.lenHist,labels:LEN_LABELS,
markers:[histMarker(med,LEN_EDGES,"median "+medTxt),histMarker(p90,LEN_EDGES,"P90 "+p90Txt)],
note:"median "+medTxt+" · P90 "+p90Txt,tip:LEN_TIP,
emptyText:"no session lengths in window."});
}
function latencyCard(r){
var p50=r.latP50,p95=r.latP95,n=Number(r.latCount)||0;
var p50Txt=fmtAtLeast(p50,60,fmtSecs),p95Txt=fmtAtLeast(p95,60,fmtSecs);
return histCard({title:"response latency",counts:r.latHist,labels:LAT_LABELS,
markers:[histMarker(p50,LAT_EDGES,"p50 "+p50Txt),histMarker(p95,LAT_EDGES,"p95 "+p95Txt)],
note:"p50 "+p50Txt+" · p95 "+p95Txt+" · n "+fmtNum(n),tip:LAT_TIP,
emptyText:"no response latency measured in window."});
}
function renderScoreRhythm(d){
var body=ensureBlock("u-rhythm",
stripHtml("u-rhythm","Your rhythm","session length · response latency"),"u-daybars");
if(!body)return;
var r=d.rhythm||{};
body.innerHTML='
'+lengthCard(r)+latencyCard(r)+"
";
}
// ── how you run: posture, who drove, who served ───────────────────────────
// ADR-0038's closed posture vocabulary, ordered least to most permissive so
// the stack reads bottom-up as "how much rope was given", with the
// unobserved bucket at the base. Every color is a token AND is named in the
// legend beside the chart — the hue is a hint, never the only way to read it.
// 'not-recorded' is forced to the de-emphasis ink by the primitive itself,
// so it deliberately has no palette entry here.
var MODE_ORDER=["not-recorded","plan","guarded","auto-edit","unrestricted"];
var MODE_COLOR={plan:"var(--purple)",guarded:"var(--ok)","auto-edit":"var(--accent)",
unrestricted:"var(--fail)"};
function modeChart(d){
var byMode=d.byMode||{};
var present=MODE_ORDER.filter(function(k){
return Object.prototype.hasOwnProperty.call(byMode,k);
});
if(!present.length)return '
posture, by day
'
+'
no permission posture recorded in window.
';
var days=dayRows(d).map(function(x){return {day:x.day,parts:(x.v&&x.v.byMode)||{}};});
// Legend order is the stack read TOP-down, which is the reverse of the
// bottom-up paint order — so the entry your eye reaches first names the
// band your eye reaches first.
var legend=present.slice().reverse().map(function(k){
return {color:k==="not-recorded"?"var(--ink-dim)":(MODE_COLOR[k]||"var(--ink-dim)"),
label:k,value:fmtUsd(fld(byMode[k],"cost"))};
});
return '
Api-equivalent cost, stacked by the permission posture the transcript '
+'recorded. not-recorded is spend from a session that carried no posture evidence — '
+"held apart rather than folded into a real posture.
";
}
function sourceDonut(d){
var src=d.bySource||{};
var main=fld(src.main,"cost"),sub=fld(src.subagent,"cost"),total=main+sub;
return '
Share of api-equivalent cost; the ring reads main-thread. Subagent work '
+"is Claude's sidechain flag or Codex's ledger-backed thread source — either way, not a "
+"session a human was driving.
";
}
function renderScoreHowRun(d){
var body=ensureBlock("u-howrun",
stripHtml("u-howrun","How you run","permission posture · who drove"),"u-rhythm");
if(!body)return;
body.innerHTML='
'+modeChart(d)+"
"
+'
'+sourceDonut(d)+"
";
}
function renderScoreDayBars(d){
// cost per day
var days=dayRows(d);
var maxDay=0;
for(var i=0;i'
+''+esc(x.day.slice(8))+"";
}).join(""):'
no days in window.
';
}
function renderScoreHosts(d){
var k;
// Host and inference-provider are independent canonical axes. All three
// supported hosts always render (idle/grayed-out when a host has no
// sessions in this window) rather than appearing/disappearing based on
// setup state — the scorecard reflects observed transcript evidence, not
// which ak setup --host flags were ever run.
var prov=d.byHost||{};
var order=["claude","codex","opencode"];
for(k in prov)if(order.indexOf(k)<0)order.push(k);
var PDOT_CLASS={claude:"c",codex:"x",opencode:"o"};
var activeHosts=0;
document.getElementById("u-hosts").innerHTML=order.map(function(name){
var v=prov[name], cost=fld(v,"cost"), sess=fld(v,"sessions"), tok=fld(v,"tokens");
var idle=!sess&&!cost;
if(!idle)activeHosts++;
// hasOwnProperty, not a bare lookup: `name` comes from byHost's keys,
// which the loop above deliberately widens beyond the three known
// hosts, so `constructor`/`__proto__` would otherwise reach a
// prototype value and land unescaped inside a class attribute.
var dot=Object.prototype.hasOwnProperty.call(PDOT_CLASS,name)?PDOT_CLASS[name]:"c";
return '
'+esc(name)+"
"
+'
'+esc(fmtUsd(cost))+"
"
+'
'+(idle?"no sessions in window":esc(fmtNum(sess))+" sessions · "+esc(fmtTok(tok))+" tokens")+"
";
}).join("");
var hostsNoteEl=document.getElementById("u-hosts-note");
if(hostsNoteEl)hostsNoteEl.textContent=activeHosts+" active of "+order.length;
}
function renderScoreTokBar(d){
var t=d.totals||{};
var segs=[["cache read",t.cacheRead,"var(--warn)"],["cache write",t.cacheWrite,"var(--purple)"],
["output",t.output,"var(--accent)"],["input",t.input,"var(--ok)"]];
document.getElementById("u-tokbar").innerHTML=segs.map(function(sg){
return '';
}).join("");
document.getElementById("u-toklegend").innerHTML=segs.map(function(sg){
return ''+esc(sg[0])+" "+esc(fmtTok(sg[1]))+"";
}).join("");
}
function renderScorePunchcard(d){
// punchcard — dow 0 = Mon
var DOW=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"], pcMax=0, key;
for(key in (d.punchcard||{}))pcMax=Math.max(pcMax,Number(d.punchcard[key])||0);
var pcHtml="";
for(var dw=0;dw<7;dw++){
pcHtml+='
'+DOW[dw]+"";
for(var hr=0;hr<24;hr++){
var n=Number((d.punchcard||{})[dw+"-"+hr])||0;
var v=pcMax?(n/pcMax):0;
pcHtml+='';
}
pcHtml+="
";
var PUNCH_NOTE="Counts responses, not elapsed time, and INCLUDES delegated subagent responses "
+"— a long agentic run dispatching subagents fills these cells even when nobody was typing. "
+"The how-you-run panel carries the main/subagent split.";
document.getElementById("u-punch").innerHTML=pcMax
?pcHtml+'
'+esc(PUNCH_NOTE)+"
"
:'
no responses in window.
';
}
// ── tool mix and model mix over time ──────────────────────────────────────
var TOOL_TOP=8;
function toolRows(d){
var map=d.byTool||{},list=[],k;
for(k in map)list.push({name:k,n:Number(map[k])||0});
list.sort(function(a,b){return b.n-a.n;});
if(!list.length)return '
no tool calls recorded in window.
';
var top=list.slice(0,TOOL_TOP),tail=list.slice(TOOL_TOP);
var other=tail.reduce(function(s,x){return s+x.n;},0),max=top[0].n;
var rows=top.map(function(x){
return {label:x.name,value:fmtNum(x.n),share:pct(x.n,max),dim:false};
});
// The tail is FOLDED, never dropped: those calls happened, and a top-8
// list that quietly loses the rest misstates the total every share above
// it is read against. Dim, because Other is a residue, not a tool.
if(other>0)rows.push({label:"Other ("+tail.length+" tool"+(tail.length===1?"":"s")+")",
value:fmtNum(other),share:pct(other,max),dim:true});
return rankedRows(rows);
}
// Four series is the most a stacked day column can carry and still be read
// apart at this size; the rest fold into one de-emphasised band. Colors are
// assigned BY RANK, so the palette is deterministic rather than dependent on
// key order, and every band is named in the legend beside the chart.
var FAMILY_PALETTE=["var(--accent)","var(--purple)","var(--ok)","var(--warn)"];
var FAMILY_TOP=4;
function familyTotals(rows){
var tot={},i,k;
for(i=0;i=0)out[k]=(out[k]||0)+v; else out.other+=v;
}
return out;
}
function modelMix(d){
var rows=dayRows(d),tot=familyTotals(rows),keep=topFamilies(tot);
if(!keep.length&&!(tot.other>0))return '
no model spend in window.
';
var palette={};
keep.forEach(function(name,i){palette[name]=FAMILY_PALETTE[i%FAMILY_PALETTE.length];});
var days=rows.map(function(x){
return {day:x.day,parts:foldFamilies((x.v&&x.v.byModelFamily)||{},keep)};
});
var otherTotal=days.reduce(function(s,x){return s+(x.parts.other||0);},0);
var legend=keep.map(function(name){
return {color:palette[name],label:name,value:fmtUsd(tot[name])};
});
if(otherTotal>0)legend.push({color:"var(--ink-dim)",label:"other",value:fmtUsd(otherTotal)});
// Bottom-up: the fold sits at the base and the biggest family paints on
// top, so the legend read top-down is the stack read top-down.
return stackedDays({days:days,order:["other"].concat(keep.slice().reverse()),palette:palette})
+chartLegend(legend)
+'
Model ids are folded to a coarse family (opus, gpt-5, …). '
+"An id the fold does not recognise lands in other — never a guessed family, and never "
+"dropped, because its spend still has to land somewhere.
";
}
function renderScoreMix(d){
var pair=ensureBlock("u-toolmix",'
'
+stripHtml("u-toolmix","Tool mix","invocations · top 8, tail folded")
+stripHtml("u-modelmix","Model mix over time","api-equivalent cost by model family")
+"
Invocations as each host recorded them, under each host\'s own tool '
+"names — nothing is renamed to make two hosts line up. A host that records no tool calls "
+"contributes nothing here rather than a zero, so these totals are not a cross-host "
+"comparison of how much tooling each one did.
";
var mix=document.getElementById("u-modelmix");
if(mix)mix.innerHTML=modelMix(d);
}
// ── reliability ───────────────────────────────────────────────────────────
var REL_TIP="Turns that never resolved to a model — a dropped connection, a rate-limit rejection, "
+"an auth failure. They are excluded from the model list (there is no model to attribute them "
+"to) and surfaced here instead of vanishing.\nRate is exceptions ÷ responses × 1000.";
var ABORT_TIP="Turns the transcript recorded as interrupted — the answer was stopped mid-flight. "
+"Counted apart from exceptions: an abort is a choice, not a failure.\n"
+"CODEX AND OPENCODE ONLY. Codex rollouts (turn_aborted) and opencode messages "
+"(MessageAbortedError) carry an interrupt signal; claude transcripts record nothing when you "
+"stop a turn. So the count and its rate are over codex and opencode responses alone, and a "
+"window with neither shows — (not 0), because nothing in it could have recorded an interrupt.";
// The per-day series rides the SAME first-billed-day attribution the session
// count uses, which is not the moment a turn dropped: a session that spans
// midnight lands all of its exceptions on one day. Said on the panel, because
// a reader will otherwise take a peak as "something broke that afternoon".
var REL_TREND_NOTE="Attributed to the day each session first billed — not the moment a turn "
+"dropped, so a session spanning midnight lands all of its exceptions on one day. A session that "
+"never billed has no day to attribute to and appears in neither this line nor the counts above.";
function relRate(t){
var r=Number(t&&t.responses)||0;
return r?(Number(t.exceptions)||0)/r*1000:null;
}
// Direction is stated in WORDS and in a glyph as well as in color — a
// reader who cannot separate the warn and ok tokens still gets the finding.
function relFlag(cur,prev){
if(cur==null||prev==null)return "";
if(cur>prev)return '▲'
+"higher than the previous window";
if(cur▼'
+"lower than the previous window";
return '•'
+"unchanged from the previous window";
}
function relStat(o){
return '
";
}
// The single worst day, named. "Worst" is a fact the counts already carry —
// no threshold is invented to decide what counts as a spike, because any
// constant this file picked would be a judgement the data never made.
function relWorstDay(rows){
var worst=null;
for(var i=0;i0&&(!worst||n>worst.n))worst={day:rows[i].day,n:n};
}
return worst;
}
function relTrend(d){
var rows=dayRows(d),series=rows.map(function(x){return fld(x.v,"exceptions");});
var total=series.reduce(function(a,n){return a+n;},0);
if(!total)return '
exceptions by day
'
+'
no exceptions on any day in this window.
';
var worst=relWorstDay(rows);
// Icon, words and color together — the day is named in text, so the flag
// survives a reader who cannot separate the status tokens.
var flag=worst?'▲worst day '
+esc(worst.day.slice(5))+" · "+esc(fmtNum(worst.n))+" of "+esc(fmtNum(total))+"":"";
return '
exceptions by day
'
+sparklineSvg(series,{w:640,h:44})+flag+"
";
}
function renderScoreReliability(d){
var body=ensureBlock("u-reliability",
stripHtml("u-reliability","Reliability","turns that never landed"),"u-models");
if(!body)return;
var t=d.totals||{},p=(d.previous&&d.previous.totals)||null;
var cur=relRate(t),exc=Number(t.exceptions)||0,resp=Number(t.responses)||0;
// aborts is evidence only codex (turn_aborted) and opencode
// (MessageAbortedError) write, so a claude-only window renders "—", not a 0
// that reads as "you never interrupted a turn". The count and the rate's
// denominator are both over those hosts alone — dividing their aborts by
// every host's responses dilutes it by an arbitrary amount that depends on
// host mix.
var cx=(d.byHost&&d.byHost.codex)||{},oc=(d.byHost&&d.byHost.opencode)||{};
var abSess=(Number(cx.sessions)||0)+(Number(oc.sessions)||0);
var abResp=(Number(cx.responses)||0)+(Number(oc.responses)||0);
var ab=(Number(cx.aborts)||0)+(Number(oc.aborts)||0);
body.innerHTML='
'
+relStat({label:"exceptions / 1k responses",value:cur==null?"—":cur.toFixed(1),
sub:fmtNum(exc)+" of "+fmtNum(resp)+" responses",tip:REL_TIP,
flag:relFlag(cur,p?relRate(p):null)})
+relStat({label:"aborted turns",value:abSess?fmtNum(ab):"—",
sub:abSess
?(abResp?fmtRatio(ab/abResp*1000)+" per 1k codex/opencode responses":"no codex or opencode responses in window")
:"no codex or opencode sessions — claude records no interrupts",
tip:ABORT_TIP})
+"
"+relTrend(d)+'
'+esc(REL_TREND_NOTE)+"
";
}
function renderScoreModels(d){
var t=d.totals||{};
// models + projects
var models=entries(d.byModel), mMax=models.length?models[0].cost:0;
document.getElementById("u-models").innerHTML=models.length?models.map(function(m){
return bar(esc(m.name),fmtUsd(m.cost),fmtTok(fld(m.v,"tokens"))+" · "+fmtNum(fld(m.v,"responses"))+" resp",
pct(m.cost,mMax),false);
}).join(""):'
no models in window.
';
// Dropped-connection / rate-limit / auth-failure turns never resolve to a
// model — excluded from this list entirely rather than shown as a $0 row
// (see docs/usage-scorecard-metrics.md §10). Surfaced here instead, only
// when nonzero, so they stay visible rather than silently vanishing.
// On its own line (.n-sub), so no leading separator — a "·" would read as a
// continuation of the caption above rather than the start of a new fact.
var exc=fld(t,"exceptions");
document.getElementById("u-models-note").textContent=exc?(fmtNum(exc)+" dropped/errored turn"+(exc===1?"":"s")+" excluded"):"";
}
function renderScoreOpenRouter(d){
// Account analytics is explicitly fetched and cached by ak usage.
// OpenRouter does not provide session/host/project correlation here, so
// these numbers remain a separate block and never alter t/byHost/byModel.
var ora=d.providerAnalytics&&d.providerAnalytics.openrouter;
if(!ora){
document.getElementById("u-openrouter-note").textContent="not refreshed · offline";
document.getElementById("u-openrouter").innerHTML=
'
No OpenRouter account cache. Run ak usage refresh openrouter explicitly.
';
}else{
var ot=ora.totals||{}, cov=ora.coverage||{}, oms=ora.byModel||[];
document.getElementById("u-openrouter-note").textContent=
"cached "+ago(Math.max(0,Math.round((Date.now()-Date.parse(ora.fetchedAt))/1000)))+" · "
+(cov.from||"no activity")+" → "+(cov.through||"no activity")
+" · never merged into transcript totals";
var oMax=oms.reduce(function(m,x){return Math.max(m,fld(x,"requests"));},0);
var cards='
'
+'
OpenRouter requests
'+esc(fmtNum(ot.requests))+'
'
+'
'+esc(fmtTok(fld(ot,"promptTokens")+fld(ot,"completionTokens")))+" tokens · 30 completed UTC days
";
}
}
function renderScoreProjects(d){
var target=document.getElementById('u-projects'),note=document.getElementById('u-projects-note');
if(!Array.isArray(d.gitProjects)){
note.textContent='';target.innerHTML='
Refresh usage to identify Git projects.
';return;
}
var projects=d.gitProjects.slice().sort(function(a,b){return b.cost-a.cost||String(a.label).localeCompare(String(b.label));});
var max=projects.length?projects[0].cost:0,shown=projects.slice(0,10);
note.textContent=projects.length>10?'top 10 of '+projects.length:projects.length+' project'+(projects.length===1?'':'s');
target.innerHTML=shown.length?shown.map(function(project){
return bar(esc(project.label),fmtUsd(project.cost),fmtNum(project.sessions)+' sess · '+fmtMins(project.minutes),pct(project.cost,max),true);
}).join(''):'
No Git-project usage in this timeframe.
';
}
function renderScoreCategories(d){
// categories — confidence is DISPLAYED, and Unclassified is never hidden.
var cats=entries(d.byCategory), cMax=cats.length?cats[0].cost:0;
document.getElementById("u-cats").innerHTML=cats.length?cats.map(function(c){
var sess=fld(c.v,"sessions")||1, conf=fld(c.v,"confidence");
var uncl=(c.name==="Unclassified");
var dot=uncl?"":'';
return '";
}).join(""):'
nothing classified in window.
';
}
export function renderScore(d){
renderScoreHero(d);
renderScoreCadence(d);
renderScoreDayBars(d);
// Order is load-bearing here and nowhere else in this list: how-you-run
// anchors its container to the rhythm strip, which renderScoreRhythm has
// to have inserted first.
renderScoreRhythm(d);
renderScoreHowRun(d);
renderScoreHosts(d);
renderScoreTokBar(d);
renderScorePunchcard(d);
renderScoreMix(d);
renderScoreModels(d);
renderScoreReliability(d);
renderScoreOpenRouter(d);
renderScoreProjects(d);
renderScoreCategories(d);
}
// ══ Limits view (ADR-0010) ═════════════════════════════════════════════════
export var LIMITS=null, limitsBusy=false;
export function loadLimits(){
if(limitsBusy)return Promise.resolve();
limitsBusy=true;
return fetch("/api/limits?days="+usageDays,{cache:"no-store",headers:authHeaders()})
.then(function(r){return r.json();})
.then(function(d){LIMITS=d&&!d.error?d:{error:(d&&d.error)||"limits unavailable"};})
.catch(function(){LIMITS={error:"limits unavailable"};})
.then(function(){limitsBusy=false; renderLimits();if(usageView==="models")renderModelLifecycle();});
}
// "as of 3m ago" — an epoch-ms fetchedAt against the browser clock. Stale is
// LABELLED, never hidden: a yesterday's-number bar with no timestamp is a lie
// of omission.
export function limAge(ms){
if(!ms||!isFinite(ms))return "";
var m=Math.max(0,Math.round((Date.now()-ms)/60000));
if(m<1)return "just now";
if(m<60)return m+"m ago";
var h=Math.round(m/60);
return h<48?h+"h ago":Math.round(h/24)+"d ago";
}
function limStale(ms,freshMs){return !ms||!isFinite(ms)||(Date.now()-ms)>freshMs;}
function resetTxt(sec){
if(!sec||!isFinite(sec))return "";
var at=formatLocalDateTime(sec*1000);
return at?"resets "+at:"";
}
// Where this window's own CLOCK is, as a share of its duration — the mark a
// straight-line burn would be sitting on right now, which is what turns a
// level into "ahead of pace" or "behind". Both halves come from the limits
// payload the meter already reads: `resetsAt` (epoch seconds) says when the
// window ends, `windowMinutes` how long it runs, so elapsed = duration −
// remaining. Nothing is fetched and nothing is assumed about window length.
//
// null — not a clamp — whenever the arithmetic falls outside [0, duration]:
// the snapshot is then older than its own window (it has already reset) or
// the browser clock disagrees with the vendor's, and a tick pinned to 0% or
// 100% would state a position instead of admitting it cannot compute one.
function paceShare(resetSec,windowMinutes){
var mins=Number(windowMinutes);
if(!resetSec||!isFinite(resetSec)||!isFinite(mins)||mins<=0)return null;
var total=mins*60000,elapsed=total-(resetSec*1000-Date.now());
if(!isFinite(elapsed)||elapsed<0||elapsed>total)return null;
return elapsed/total*100;
}
function paceTick(resetSec,windowMinutes){
var at=paceShare(resetSec,windowMinutes);
if(at==null)return "";
return '';
}
// Rendered only when at least one row actually carries a tick, so the key
// never explains a mark that is not on screen.
var PACE_LEGEND='
'
+'tick = share of the window’s time elapsed · '
+"fill past it is ahead of a steady burn
";
// One utilization row on the shared .mrow grid; fill color says how close to
// the cap this window is (ok <70, warn ≥70, fail ≥90).
function limRow(label,usedPercent,resetSec,sub,windowMinutes){
var p=Math.max(0,Math.min(100,Number(usedPercent)||0));
var col=p>=90?"var(--fail)":(p>=70?"var(--warn)":"var(--ok)");
return '
";
}
// The channel describes the resolved settings context; local and managed
// settings can override the project and user settings.
var CLAUDE_PRECEDENCE="local or managed settings may override the project and user settings; the effective statusLine takes precedence";
var CLAUDE_SETUP="Set a project up with ak setup --project (ak sync keeps its footer current), then run a Pro/Max session there.";
var CLAUDE_EMPTY={
"kit-footer":"the effective statusLine carries the kit footer, so limits arrive after the first response "
+"of a Claude Code session on a Pro/Max plan. Run one session, then revisit.",
"custom":"the effective statusLine runs a custom script without the kit footer, so it does not report limits "
+"to ak. They arrive from sessions whose effective statusLine carries the footer: "+CLAUDE_PRECEDENCE+". "+CLAUDE_SETUP,
"none":"there is no effective statusLine, so only sessions whose effective statusLine carries the kit footer "
+"report limits. "+CLAUDE_SETUP,
"project-helper":"the effective statusLine runs each project’s own ruflo helper, so limits arrive from sessions "
+"in projects where that helper carries the kit footer. Run ak sync in such a project to re-inject it, "
+"then run a Pro/Max session there."
};
function claudeEmptyHtml(channel){
var why=Object.prototype.hasOwnProperty.call(CLAUDE_EMPTY,channel)?CLAUDE_EMPTY[channel]
:"it arrives while a Claude Code session on a Pro/Max plan runs a statusline that carries the kit footer; "
+CLAUDE_PRECEDENCE+", so a project set up with ak setup --project reports even when yours does not.";
return '
no Claude limit data yet — '+why+"
";
}
// renderLimits was one CC-28 function mixing the Claude window, the Codex
// lane, and the insights panel. Split by region; each keeps its original
// logic verbatim, so the rendered DOM is unchanged.
function renderLimitsClaude(){
var claudeEl=document.getElementById("u-lim-claude");
var c=LIMITS.claude;
var cn=document.getElementById("u-lim-claude-note");
if(c&&c.windows&&c.windows.length){
// Claude's tee is push-only: FRESH means a session wrote it in the last
// 10 minutes; anything older gets the stale badge rather than silence.
if(cn)cn.textContent="statusline tee · "+limAge(c.fetchedAt)+(limStale(c.fetchedAt,600000)?" · stale":"");
var paced=false;
claudeEl.innerHTML=c.windows.map(function(w){
if(paceShare(w.resetsAt,w.windowMinutes)!=null)paced=true;
return limRow("claude · "+(w.label||w.id),w.usedPercent,w.resetsAt,null,w.windowMinutes);
}).join("")+(paced?PACE_LEGEND:"");
}else{
if(cn)cn.textContent="no data";
claudeEl.innerHTML=claudeEmptyHtml(LIMITS.claudeChannel);
}
}
// Why the latest Codex refresh produced nothing (#238 P4). The server keeps
// only the failure class and a number (exit or JSON-RPC code) — never stderr
// or vendor text — and the panel names the cause instead of guessing
// "not installed, not logged in, or did not answer". Unknown classes (a
// newer server) fall back to that generic sentence.
function codexCode(n){return Number.isInteger(n)?String(n):"";}
var CODEX_WHY={
"not-installed":function(){return "the codex CLI was not found on the dashboard’s PATH, so app-server could not start. "
+"Check the Codex host row in ak status.";},
"spawn-failed":function(){return "codex app-server could not be started. Check the Codex host row in ak status.";},
"exited":function(u){var c=codexCode(u.exitCode);return "codex app-server exited before answering"+(c?" (exit code "+c+")":"")
+". An outdated codex CLI can reject the read-only flags; check codex --version and the Codex host row in ak status.";},
"timeout":function(){return "codex app-server did not answer in time. It is asked again on the next refresh.";},
"rpc-error":function(u){var c=codexCode(u.rpcCode);return "codex app-server refused the rate-limit request"+(c?" (RPC error "+c+")":"")
+", for example when codex is not signed in. Run codex login status.";},
"no-limit-windows":function(){return "codex answered but reported no plan limit window. Plan windows apply to a ChatGPT-plan "
+"sign-in; API-key use is billed at API rates. codex login status shows which one codex uses.";},
"host-not-found":function(){return "Codex is not installed on this machine (ak’s last host check did not find the codex CLI), "
+"so its quota is not requested.";},
"host-unconfirmed":function(){return "ak has not checked for Codex on this machine recently; the quota is requested once the "
+"dashboard’s status check finds it.";}
};
var CODEX_FAILED_SHORT={"not-installed":"codex not found","spawn-failed":"could not start","timeout":"timed out",
"no-limit-windows":"no plan windows","host-not-found":"codex not found","host-unconfirmed":"not checked yet"};
function codexWhy(u){
return u&&Object.prototype.hasOwnProperty.call(CODEX_WHY,u.reason)?CODEX_WHY[u.reason](u):null;
}
function codexFailedShort(u){
if(!u||!Object.prototype.hasOwnProperty.call(CODEX_WHY,u.reason))return "";
var c=u.reason==="exited"?codexCode(u.exitCode):u.reason==="rpc-error"?codexCode(u.rpcCode):"";
var label=u.reason==="exited"?"exited":u.reason==="rpc-error"?"refused (RPC)":CODEX_FAILED_SHORT[u.reason];
// host-not-found/host-unconfirmed never attempted a refresh (ADR-0010's
// presence gate skipped the spawn entirely) — "last refresh failed" would
// be false; every other reason DID attempt one.
var prefix=(u.reason==="host-not-found"||u.reason==="host-unconfirmed")?" · not refreshed: ":" · last refresh failed: ";
return prefix+label+(c?" (code "+c+")":"");
}
function renderLimitsCodex(){
var codexEl=document.getElementById("u-lim-codex");
var x=LIMITS.codex;
var xn=document.getElementById("u-lim-codex-note");
if(x&&x.lanes&&x.lanes.length){
if(xn)xn.textContent=(x.planType?("plan "+x.planType+" · "):"")+"app-server · "+limAge(x.fetchedAt)
+codexFailedShort(LIMITS.codexUnavailable);
var html="",paced=false;
for(var i=0;i0){
html+='
'
+esc(fmtNum(rc.availableCount))+" rate-limit reset credit"+(rc.availableCount===1?"":"s")
+" available · redeem via codex /usage
no Codex limit data — '
+(codexWhy(LIMITS.codexUnavailable)||"codex is not installed, not logged in, or app-server did not answer.")+"
";
}
}
function renderLimitsInsights(){
var ins=Array.isArray(LIMITS.insights)?LIMITS.insights:[];
document.getElementById("u-lim-insights").innerHTML=ins.length
?ins.map(insightCard).join("")
:'
no limit findings — nothing is ahead of pace and no arbitrage is open.
';
}
function renderLimits(){
var claudeEl=document.getElementById("u-lim-claude");
var codexEl=document.getElementById("u-lim-codex");
if(!claudeEl||!codexEl)return;
if(!LIMITS){claudeEl.innerHTML='
loading…
'; codexEl.innerHTML='
loading…
'; return;}
if(LIMITS.error){claudeEl.innerHTML='
'+esc(LIMITS.error)+"
"; codexEl.innerHTML=""; return;}
renderLimitsClaude();
renderLimitsCodex();
renderLimitsInsights();
}
// ══ Prompts view (METRICS.md §21) ══════════════════════════════════════════
// Panels are built by usage-prompts.mjs (pure string builders); this function
// owns only the DOM writes and the captions, which name the window every
// figure was computed over — a figure whose window is not stated is a figure
// a reader will attach to the wrong span.
export function renderPrompts(d){
var p=d&&d.prompts;
var kpis=document.getElementById("u-pr-kpis");
if(!kpis)return;
if(!p){
kpis.innerHTML='
this window carries no prompt-fingerprint layer — '
+'the sessions in it were parsed before prompt fingerprints shipped. Re-scan to populate it.
';
return;
}
var win=windowLabel();
kpis.innerHTML=promptKpis(p);
setText("u-pr-prov-note",win+" · every fingerprinted user-role turn");
document.getElementById("u-pr-provenance").innerHTML=provenancePanel(p);
setText("u-pr-steer-note",win+" · fingerprinted prompt-kind turns");
document.getElementById("u-pr-steer").innerHTML=steerPanel(p);
document.getElementById("u-pr-taps").innerHTML=tapLengthPanel(p);
setText("u-pr-patterns-note",win+" · deterministic clusters");
document.getElementById("u-pr-patterns").innerHTML=patternsPanel(p);
setText("u-pr-hosts-note",win+" · per host");
document.getElementById("u-pr-hosts").innerHTML=hostInterplay(p);
}
function setText(id,txt){var el=document.getElementById(id);if(el)el.textContent=txt;}
function windowLabel(){return usageDays>=365?"all history":"last "+usageDays+"d";}
export function renderFindings(d){
var ins=Array.isArray(d.insights)?d.insights:[];
var badge=document.getElementById("u-findings-n");
var warns=ins.filter(function(x){return x.severity==="warn";}).length;
if(badge){if(warns){badge.hidden=false; badge.textContent=String(warns);}else{badge.hidden=true;}}
document.getElementById("u-findings-note").innerHTML=
ins.length+" finding"+(ins.length===1?"":"s")+", ranked by estimated impact. A finding only claims a "
+"dollar figure when it can compute one from your data — the rest say no $ claimed rather "
+"than inventing a number. Recommendations that depend on model-capability claims carry their sources.";
document.getElementById("u-insights").innerHTML=ins.length
?ins.map(insightCard).join("")
:'
no findings — nothing in this window crossed a detector threshold.
';
}
// One finding card. Shared by the Findings view and the Limits view — both
// render the same Insight contract, so they must render it the same way.
function insightCard(f,i){
var imp=(typeof f.impact==="number")
? '~'+esc(fmtUsd(f.impact))+"/window"
: 'no $ claimed';
var cmd=f.command?' '+esc(f.command)+"":"";
var src="";
if(f.sources&&f.sources.length){
src='grounding — '+f.sources.length+" source"
+(f.sources.length===1?"":"s")+"
"
+f.sources.map(function(sc){
// Security review SEC-12: scheme-allowlist the href. `esc` does not
// touch ':', so `javascript:alert(1)` survived it intact. The only
// producer today is a hardcoded constant (MODEL_ROUTING_SOURCES),
// which is why the review ranked it LOW and called it latent — but
// the neighbouring prompts surface already gets this right with
// encodeURIComponent into a '#' fragment, and this one becomes live
// XSS the day a detector cites a data-derived URL. A source that is
// not plainly http(s) renders as TEXT, so it is still visible and
// still auditable; it just is not clickable.
var url=String(sc&&sc.url||"");
var label=esc(sc&&sc.label);
if(!/^https?:\/\//.test(url)) return "
"
+src+"";
}
// A missing signal renders as an em dash and is NEVER omitted: a line that
// disappears when the value is null teaches the reader that the field does
// not exist, when in fact it was measured and found absent (ADR-0009 §5).
function dash(v){return (v==null||v==="")?"—":String(v);}
function reportedIdentity(v){v=String(v==null?"":v).trim();return v&&!/^unknown$/i.test(v)?v:null;}
function identityName(v){return Object.hasOwn(SESSION_HOST_LABELS,v)?SESSION_HOST_LABELS[v]:'Unknown';}
// ── per-session chips ─────────────────────────────────────────────────────
// Evidence the row already carries, shown only where the transcript
// established it. An ABSENT chip is itself the signal that the fact was
// never recorded — a chip that appeared with a guessed value would be
// indistinguishable from one that was measured.
var LAT_CHIP_TIP="This session's median response latency, interpolated from its own latency "
+"histogram — the same bucket math the window's rhythm panel uses.\ncodex host-measured · "
+"claude/opencode derived from event gaps — not streaming TTFT.\nA value in the last bucket "
+"has no upper edge and is printed with ≥.";
function sessionP50(sx){
return Array.isArray(sx.latHist)?bucketPercentile(sx.latHist,LAT_EDGES,0.5):null;
}
// The posture the transcript recorded, and NOTHING when it recorded none: an
// unobserved or unmapped raw value is not a posture, and a badge that guessed
// one would read exactly like an observed one. `modeRaw` is the host's own
// spelling, projected onto the session row by v11Projection, and rides in
// this badge's tooltip; the row's detail strip is where an unmapped raw
// value is surfaced, since there is no classified name to put on a badge.
function modeBadge(sx){
var mode=reportedIdentity(sx.mode);
if(!mode)return "";
var raw=reportedIdentity(sx.modeRaw);
return ''+esc(mode)+"";
}
// Only paired normalized evidence supports a ratio; legacy fields may
// contain independent observations from different turns/windows.
function ctxChip(sx){
var pressure=sx.contextEvidence&&sx.contextEvidence.pressure;
if(!pressure||typeof pressure.lastBps!=="number"||!isFinite(pressure.lastBps))return "";
return 'ctx '+esc((pressure.lastBps/100).toFixed(0))+"%";
}
function sessionChips(sx){
var out="",len=Number(sx.lenSeconds)||0,p50=sessionP50(sx);
if(len>0)out+=''+esc(fmtSecs(len))+"";
if(p50!=null)out+='p50 '
+esc(fmtAtLeast(p50,60,fmtSecs))+"";
return out+modeBadge(sx)+ctxChip(sx);
}
// THREE states, not two. A transcript that recorded a posture the taxonomy
// does not map still recorded a posture: printing "no posture evidence in
// this transcript" over a modeRaw sitting on the same row is a fabrication
// in the opposite direction from the usual one — denying data that exists.
// The host's own spelling is shown instead, labelled unrecognized so it is
// never mistaken for a classified posture.
function postureLine(sx){
var modeRaw=reportedIdentity(sx.modeRaw),modeName=reportedIdentity(sx.mode);
if(modeName)return esc(modeName)+" ("
+esc(modeRaw?"recorded by the host as \""+modeRaw+"\"":"host spelling not recorded")+")";
return modeRaw
? "Unrecognized (host recorded \""+esc(modeRaw)+"\" — not in this taxonomy)"
: "Not recorded (no posture evidence in this transcript)";
}
/* The ten fields that shipped on the wire and rendered nowhere. Everything
here comes from the row the browser already holds — no route, no fetch. */
function sdetail(sx){
// basis is a STRING contract. Only null/empty falls back, so a non-string
// still renders as itself and trips the harness's [object Object] net —
// coercing it here would hide exactly the bug the net exists to catch.
var basis=(sx.basis==null||sx.basis==="")?"no signal":sx.basis;
var conf=(typeof sx.confidence==="number")
? ' (conf '+esc(sx.confidence.toFixed(2))+")" : "";
var modelList=(Array.isArray(sx.models)?sx.models:[]).filter(function(model){return reportedIdentity(model);});
var models=modelList.length?modelList.join(", "):"Not recorded";
var providerPresentation=sessionProviderPresentation(sx),provider=providerPresentation.label,providerContext=providerPresentation.basis;
var toks="in "+fmtTok(sx.input)+" · out "+fmtTok(sx.output)
+" · cache r "+fmtTok(sx.cacheRead)+" / w "+fmtTok(sx.cacheWrite)
// Codex-only detail: reasoning tokens are a SUBSET of output (they bill
// as output), so this annotates the split without changing any sum.
+((Number(sx.reasoningOutput)||0)>0?" · reasoning "+fmtTok(sx.reasoningOutput)+" (in out)":"");
var tmap=(sx.tools&&typeof sx.tools==="object"&&!Array.isArray(sx.tools))?sx.tools:{};
var tl=[],tk;
for(tk in tmap)tl.push({n:tk,c:Number(tmap[tk])||0});
tl.sort(function(a,b){return b.c-a.c;});
var tools=tl.length?tl.slice(0,6).map(function(x){return x.n+" "+x.c;}).join(" · "):"—";
var flags="skill "+dash(sx.skill)+" · plugin "+dash(sx.plugin)
+" · sidechain "+(sx.sidechain==null?"—":(sx.sidechain?"yes":"no"))
+" · worktree "+dash(sx.worktree);
// Posture and rhythm are the row's own v11 evidence, spelled out here
// where the chips only had room for a badge. Both follow this strip's
// never-omit-a-line rule: a fact that was measured and found absent reads
// "Not recorded"/"—", not silence, which would teach the reader the field
// does not exist (ADR-0009 §5).
var posture=postureLine(sx);
var p50=sessionP50(sx);
var rhythm="engaged "+((Number(sx.lenSeconds)||0)>0?fmtSecs(sx.lenSeconds):"—")
+" · p50 "+(p50==null?"—":fmtAtLeast(p50,60,fmtSecs))
+" · latency samples "+fmtNum(Number(sx.latCount)||0)
// Same capability rule as the reliability panel, applied per row: only a
// codex or opencode transcript can record an interrupt, so a claude row
// reads "not recorded" rather than a measured-looking 0.
+" · aborts "+(sx.host==="codex"||sx.host==="opencode"?fmtNum(Number(sx.aborts)||0):"not recorded for this host");
var rows=[["session surface",surfaceDetailHtml(sx.sessionOrigin||{})],["execution host",esc(identityName(sx.host))],["inference provider",esc(provider)+" ("+esc(providerContext)+")"],["models",esc(models)],["posture",posture],["rhythm",esc(rhythm)],["basis",esc(basis)+conf],["tokens",esc(toks)],
["tools",esc(tools)],["flags",esc(flags)]];
return '
'
+rows.map(function(r){
// The literal space is load-bearing, not formatting: adjacent
// inline-blocks with no whitespace between them collapse into one
// unbroken word in the rendered text ("FLAGSskill"), destroying the
// word boundary that anything reading it depends on.
return '
'+r[0]+''+r[1]+"
";
}).join("")+"
";
}
// Returns TWO siblings: the grid row, then its detail strip. The strip is a
// block-level sibling inside .pbody, not a grid child of .srow, so it spans
// the full width without joining the column layout.
export function sessionRow(sx){
var host=reportedIdentity(sx.host)||"unknown";
var provider=sessionProviderPresentation(sx).label;
var modelList=(Array.isArray(sx.models)?sx.models:[]).filter(function(model){return reportedIdentity(model);});
var identityTip="Execution host: "+identityName(host)+" · Inference provider: "+provider+" · Model: "+(modelList.length?modelList.join(", "):"Not recorded");
var cat=sx.category||"Unclassified";
var uncl=(cat==="Unclassified");
var weak=(typeof sx.confidence==="number"&&sx.confidence<0.6)?"0":"1";
var whenTxt=formatLocalDateTime(sx.start)||"—";
// Ids are derived from raw filesystem names (usage-index.mjs listClaude /
// listClaudeSubagents), NOT validated at index time — parseSessionId is a
// request-path validator that never runs here — and a namespaced subagent
// id contains '/', which the charset once claimed for them does not.
// POSIX filenames permit '"', '<' and '>', so esc() is LOAD-BEARING, not
// belt-and-braces: every render of sx.id must keep it, or a project
// directory named with a quote breaks out of these attributes and, under
// this page's script-src 'unsafe-inline', executes.
var sid=esc(sx.id);
var wt=sx.worktree!=null?'⑂'+esc(sx.worktree)+"":"";
return '
"+sdetail(sx);
}
export function renderSessions(d){
var tree=Array.isArray(d.projectTree)?d.projectTree:[];
var n=document.getElementById("u-sessions-n");
if(n)n.textContent=tree.length?" "+fmtNum((d.totals||{}).sessions):"";
document.getElementById("u-tree").innerHTML=tree.length?tree.map(function(g){
var chips="";
// usage-index emits categories as a COST-RANKED ARRAY of
// {category, sessions, cost} — already ordered, so no re-sort here. The
// keyed-map fallback below is for older cached payloads only; treating an
// array as a map yields Object.keys() === ["0","1"...] and renders
// "0 [object Object]", so the shape check is load-bearing, not defensive noise.
var cs=g.categories;
if(Array.isArray(cs)){
for(var i=0;i'+esc(c.category)+" "+esc(String(c.sessions))+"";
}
}else if(cs&&typeof cs==="object"){
var ck=Object.keys(cs).sort(function(a,b){return (cs[b]||0)-(cs[a]||0);}).slice(0,3);
for(var j=0;j'+esc(ck[j])+" "+esc(String(cs[ck[j]]))+"";
}
var rows=Array.isArray(g.rows)?g.rows:[];
var body=rows.length?rows.slice(0,25).map(sessionRow).join(""):'
showing '+Math.min(25,rows.length)+" of "+fmtNum(g.sessions)
+' ·
';
}
// Every project starts COLLAPSED. Auto-opening the first one pushed the
// remaining projects below the fold, which defeats the point of the
// aggregate view — the comparison across projects IS the top-level answer.
return '
'
+'"
+'
'+body+"
";
}).join(""):'
no sessions in window.
';
}
// Secrets are masked SERVER-side (ADR-0009 §8) — nothing here can un-redact
// what never left the process. This only makes the redactions visible as
// redactions, so a reader can see that something was withheld.
// The masker emits "…redacted" (sk-…redacted, Bearer …redacted).
// This used to hunt for ***, ••• or [REDACTED] — sentinels nothing ever
// produced — so no .masked span was ever created and the styling below was
// dead code. There is deliberately NO click-to-reveal: masking happens
// server-side and the original never reaches the browser, so there is nothing
// here to reveal. Marking it is the whole feature.
function markRedactions(text){
return esc(text).replace(/([A-Za-z_.-]*…redacted)/g,function(m){
return ''+m+"";
});
}
// Harness sentinel markup — the XML wrappers Claude Code writes into
// transcript text (, , ) —
// rendered as styled structure instead of literal angle-bracket soup.
// PRESENTATION ONLY: the wrapped content is kept verbatim (ADR-0009 §8's
// no-silent-alteration rule); only the wrapper tags become styling. Runs on
// ESCAPED html (after markRedactions), so patterns match <tag>. An
// unmatched tag (e.g. cut mid-sentinel by turn truncation) is left raw.
var H_TAGS={"system-reminder":"system reminder","local-command-caveat":"caveat",
"local-command-stdout":"command output","local-command-stderr":"command stderr",
"bash-stdout":"bash output","bash-stderr":"bash stderr","task-notification":"task notification"};
function fmtHarness(html){
return html
.replace(/<command-name>([\s\S]*?)<\/command-name>\s*(?:<command-message>([\s\S]*?)<\/command-message>\s*)?(?:<command-args>([\s\S]*?)<\/command-args>)?/g,
function(_,name,msg,args){
var n=name.trim(), a=(args||"").trim(), m=(msg||"").trim();
return ''+n+(a?" "+a:"")+"";
})
// bash-input is the person's own "! command" — a chip, prefixed so it
// reads as the shell invocation it was, not as prose.
.replace(/<bash-input>([\s\S]*?)<\/bash-input>/g,
function(_,cmd){return '! '+cmd.trim()+"";})
.replace(/<(system-reminder|local-command-caveat|local-command-stdout|local-command-stderr|bash-stdout|bash-stderr|task-notification)>\s*([\s\S]*?)\s*<\/\1>/g,
function(_,tag,body){
return ''+H_TAGS[tag]+""+body+"";
});
}
// ADR-0009 §8 — an abridged turn must not be readable as a complete one, and
// "truncated" alone is not enough: a reader who cannot tell 1% loss from 90%
// loss knows something is missing and nothing about whether it matters.
//
// The SHOWN figure is DERIVED, never hardcoded. MAX_TURN_CHARS lives in
// usage-index.mjs and the browser never sees it, so a literal 40000 here
// would silently desync the day someone changes the constant — which is the
// failure mode this whole ADR exists to prevent. We subtract the marker the
// producer appends from the text we actually received.
var TRUNC_MARK="\n…[truncated]";
function truncBadge(tn){
if(!tn||tn.truncated!==true)return "";
var shown=String(tn.text==null?"":tn.text);
var n=shown.length-(shown.slice(-TRUNC_MARK.length)===TRUNC_MARK?TRUNC_MARK.length:0);
// A cached payload can carry truncated:true with no originalChars. Say so,
// rather than inventing a denominator or dropping the badge — §6's rule
// about claiming a figure only when you can compute one.
if(typeof tn.originalChars!=="number"||!isFinite(tn.originalChars)||tn.originalChars<=0)
return 'truncated';
return 'truncated · '
+esc(fmtTok(n))+" of "+esc(fmtTok(tn.originalChars))+"";
}
export function renderTranscript(){
var crumb=document.getElementById("u-crumb"), body=document.getElementById("u-turns");
if(!usageSession){
crumb.innerHTML='no session selected';
body.innerHTML='
pick a session in the Sessions view to read it here.
';
return;
}
var t=TRANSCRIPT&&TRANSCRIPT.id===usageSession?TRANSCRIPT:null;
var m=(t&&t.meta)||{};
crumb.innerHTML=''
+''+esc(m.title||usageSession)+""
+''+esc([m.project,fmtMins(m.minutes),
(m.prompts||0)+" prompts / "+(m.responses||0)+" responses",fmtTok(m.tokens),fmtUsd(m.cost)]
.filter(Boolean).join(" · "))+"";
if(!t){body.innerHTML='
loading transcript…
'; return;}
if(t.error){body.innerHTML='
'+esc(t.error)+"
"; return;}
body.innerHTML=t.turns.length?t.turns.map(function(tn){
var user=(tn.role==="user");
var text=tn.text!=null?tn.text:(tn.body!=null?tn.body:(tn.content!=null?tn.content:""));
var tools=(tn.tools&&tn.tools.length)
?'
":"";
var meta=truncBadge(tn)
+(tn.output?''+esc(fmtNum(tn.output))+" out":"");
// role "user" ≠ "the human typed this": the Messages API records tool
// results and harness context injections under the user role, and the
// parser marks WHICH via tn.kind. Only kind "prompt" earns "you" — a
// tool result labeled "you" attributes the harness's work to the person.
// Fallback for a turn without kind: the prompt flag (false ⇒ tool
// feedback was the overwhelmingly dominant non-prompt case).
var kind=tn.kind||(user?(tn.prompt===false?"tool-result":"prompt"):"");
var who,cls,title="";
if(!user){who=tn.model||tn.role||"assistant"; cls="t-asst";}
else if(kind==="tool-result"){who="tool result"; cls="t-tool"; title="output returned to the model by the tooling — not typed by you";}
else if(kind==="context"){who="context"; cls="t-tool"; title="context injected by the harness — not typed by you";}
else{who="you"; cls="t-user";}
return '