@jjanczur/tyran 0.1.14 → 0.1.18

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.
@@ -78,6 +78,35 @@ h2{font-family:var(--display);color:var(--heading);font-size:1.05rem;margin:1.5r
78
78
  .card .note{color:var(--muted);font-size:.78rem;display:block}
79
79
  .empty{color:var(--hairline);font-size:.8rem}
80
80
  footer{margin-top:2rem;color:var(--muted);font-size:.75rem;border-top:1px solid var(--hairline-soft);padding-top:.6rem}
81
+ .spend-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:.8rem}
82
+ .toggle{display:flex;gap:.25rem;margin-left:auto}
83
+ .toggle button{font-family:var(--mono);font-size:.7rem;letter-spacing:.06em;text-transform:uppercase;background:var(--bg-raised);color:var(--muted);border:1px solid var(--hairline);border-radius:.35rem;padding:.2rem .6rem;cursor:pointer}
84
+ .toggle button[aria-pressed="true"]{background:var(--gold-low);border-color:var(--gold);color:var(--gold-bright)}
85
+ .toggle button:focus-visible{outline:2px solid var(--glow);outline-offset:2px}
86
+ .tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));gap:.6rem;margin:.6rem 0}
87
+ .stile{background:var(--bg-raised);border:1px solid var(--hairline);border-radius:.55rem;padding:.6rem .8rem}
88
+ .stile .lbl{display:block;font-family:var(--mono);font-size:.65rem;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}
89
+ .stile .big{display:block;font-family:var(--mono);font-size:1.35rem;color:var(--heading);font-variant-numeric:tabular-nums;line-height:1.25}
90
+ .stile .sub{display:block;font-family:var(--mono);font-size:.7rem;color:var(--muted)}
91
+ .stile.gold{background:var(--gold-low);border-color:var(--gold)}
92
+ .stile.gold .big{color:var(--gold-bright)}
93
+ .comp{display:flex;height:1.5rem;border:1px solid var(--hairline);border-radius:.35rem;overflow:hidden}
94
+ .comp span{display:flex;align-items:center;justify-content:center;font-family:var(--mono);font-size:.65rem;color:var(--bg);font-weight:700;white-space:nowrap;overflow:hidden}
95
+ .comp .s-cache_read{background:var(--gold)}
96
+ .comp .s-cache_write{background:var(--glow)}
97
+ .comp .s-output{background:var(--green)}
98
+ .comp .s-input{background:var(--muted)}
99
+ .compkey{display:flex;flex-wrap:wrap;gap:.9rem;font-family:var(--mono);font-size:.68rem;color:var(--muted);margin-top:.35rem}
100
+ .compkey i{display:inline-block;width:.6rem;height:.6rem;border-radius:.15rem;margin-right:.3rem}
101
+ .chart{display:flex;flex-direction:column;gap:.28rem;margin-top:.4rem}
102
+ .chartrow{display:grid;grid-template-columns:minmax(7rem,14rem) 1fr auto;gap:.6rem;align-items:center;font-size:.8rem}
103
+ .chartrow .rl{font-family:var(--mono);color:var(--heading);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
104
+ .chartrow .rb{background:var(--bg-sunken);border-radius:.25rem;height:.85rem;overflow:hidden}
105
+ .chartrow .rb i{display:block;height:100%;background:var(--gold);border-radius:.25rem}
106
+ .chartrow.dim .rl{color:var(--muted);font-style:italic}
107
+ .chartrow.dim .rb i{background:var(--hairline)}
108
+ .chartrow .rv{font-family:var(--mono);font-variant-numeric:tabular-nums;color:var(--text);min-width:5.5rem;text-align:right}
109
+ .caveat{color:var(--muted);font-size:.78rem;margin-top:.5rem}
81
110
  `;
82
111
 
83
112
  /**
@@ -187,6 +216,171 @@ if (data.schema !== 1) {
187
216
  });
188
217
  app.appendChild(lanesWrap);
189
218
 
219
+ var fmtTokens = function (n) {
220
+ if (n >= 1e9) return (n / 1e9).toFixed(2) + ' B';
221
+ if (n >= 1e6) return (n / 1e6).toFixed(1) + ' M';
222
+ if (n >= 1e3) return (n / 1e3).toFixed(1) + ' k';
223
+ return String(n);
224
+ };
225
+ // An amount that rounds to nothing still cost something. Printing $0.00
226
+ // there reads as free, which is the one reading that would change a
227
+ // routing decision for the wrong reason.
228
+ var fmtUsd = function (v) {
229
+ if (v === null || v === undefined) return '—';
230
+ if (v > 0 && v < 0.01) return '<$0.01';
231
+ return '$' + v.toFixed(2);
232
+ };
233
+
234
+ var tile = function (label, big, sub, cls) {
235
+ var box = el('div', cls ? 'stile ' + cls : 'stile');
236
+ box.appendChild(el('span', 'lbl', label));
237
+ box.appendChild(el('span', 'big', big));
238
+ box.appendChild(el('span', 'sub', sub));
239
+ return box;
240
+ };
241
+
242
+ // One ranked bar chart. The bar is the comparison; the number beside it is
243
+ // the fact. A row whose models have no rate shows no bar at all rather than
244
+ // a zero-length one, because "not priced" and "cost nothing" must not look
245
+ // the same.
246
+ var chart = function (allRows, key, metric, dimKeys) {
247
+ var box = el('div', 'chart');
248
+ // Ranked by the metric on screen, not by the one the server happened to
249
+ // sort by. In cost view a cheap-and-chatty row was being listed above an
250
+ // expensive-and-terse one — the precise inversion of the routing signal
251
+ // this view exists to give. Rows with no price sort last.
252
+ var valueOf = function (r) { return metric === 'usd' ? r.usd : r.tokens; };
253
+ var rows = allRows.slice().sort(function (a, b) {
254
+ var av = valueOf(a);
255
+ var bv = valueOf(b);
256
+ if (typeof av !== 'number' && typeof bv !== 'number') return 0;
257
+ if (typeof av !== 'number') return 1;
258
+ if (typeof bv !== 'number') return -1;
259
+ return bv - av || String(a[key]).localeCompare(String(b[key]));
260
+ });
261
+ var values = rows.map(valueOf);
262
+ var max = 0;
263
+ values.forEach(function (v) { if (typeof v === 'number' && v > max) max = v; });
264
+ rows.forEach(function (r, i) {
265
+ var value = values[i];
266
+ var unpriced = metric === 'usd' && (value === null || value === undefined);
267
+ var dim = unpriced || dimKeys.indexOf(r[key]) !== -1;
268
+ var row = el('div', dim ? 'chartrow dim' : 'chartrow');
269
+ row.appendChild(el('div', 'rl', r[key]));
270
+ var track = el('div', 'rb');
271
+ var fill = el('i');
272
+ fill.style.width = (max > 0 && typeof value === 'number' ? (value / max) * 100 : 0) + '%';
273
+ track.appendChild(fill);
274
+ row.appendChild(track);
275
+ row.appendChild(el('div', 'rv', metric === 'usd' ? fmtUsd(value) : fmtTokens(value)));
276
+ box.appendChild(row);
277
+ });
278
+ return box;
279
+ };
280
+
281
+ var renderSpend = function (into, cost, metric) {
282
+ while (into.firstChild) into.removeChild(into.firstChild);
283
+ var t = cost.totals || {};
284
+ var cov = cost.coverage || {};
285
+
286
+ var header = el('div', 'spend-head');
287
+ header.appendChild(el('h2', null, 'Spend'));
288
+ var toggle = el('div', 'toggle');
289
+ [['tokens', 'tokens'], ['usd', 'cost']].forEach(function (pair) {
290
+ var button = el('button', null, pair[1]);
291
+ button.setAttribute('type', 'button');
292
+ button.setAttribute('aria-pressed', metric === pair[0] ? 'true' : 'false');
293
+ button.addEventListener('click', function () { renderSpend(into, cost, pair[0]); });
294
+ toggle.appendChild(button);
295
+ });
296
+ header.appendChild(toggle);
297
+ into.appendChild(header);
298
+
299
+ var tiles = el('div', 'tiles');
300
+ tiles.appendChild(tile('tokens', fmtTokens(t.tokens || 0), (t.requests || 0) + ' requests'));
301
+ tiles.appendChild(tile(
302
+ 'cost through the API', fmtUsd(t.usd),
303
+ cost.rate_card ? 'rate card ' + cost.rate_card : 'no rate card set', 'gold'));
304
+ tiles.appendChild(tile(
305
+ 'conductor overhead', (t.conductor_token_share || 0) + '%', 'of tokens, no ticket'));
306
+ tiles.appendChild(tile(
307
+ 'attributed', (cov.attributed || 0) + ' / ' + (cov.agent_transcripts || 0),
308
+ (cov.unattributed || 0) + ' agent(s) without a ticket'));
309
+ into.appendChild(tiles);
310
+
311
+ // The composition is the point of the whole section: cache reads dominate
312
+ // the bill, so the lever is context size and turn count, not model price.
313
+ var comp = (cost.composition || []).slice().sort(function (a, b) {
314
+ return metric === 'usd' ? (b.usd || 0) - (a.usd || 0) : b.tokens - a.tokens;
315
+ });
316
+ var compTotal = 0;
317
+ comp.forEach(function (c) { compTotal += metric === 'usd' ? (c.usd || 0) : c.tokens; });
318
+ if (compTotal > 0) {
319
+ var bar = el('div', 'comp');
320
+ var key = el('div', 'compkey');
321
+ comp.forEach(function (c) {
322
+ var value = metric === 'usd' ? (c.usd || 0) : c.tokens;
323
+ if (value <= 0) return;
324
+ var pct = Math.round((value / compTotal) * 100);
325
+ var seg = el('span', 's-' + c.kind, pct >= 8 ? pct + '%' : '');
326
+ // Normalised to a share, not set to the raw value: flex-grow below 1
327
+ // does not fill its container, and dollar amounts are routinely
328
+ // fractions. Measured — the cost view drew a bar 13% of the width
329
+ // while the token view, whose values are thousands, filled it.
330
+ seg.style.flex = String((value / compTotal) * 100);
331
+ bar.appendChild(seg);
332
+ var legend = el('span', null);
333
+ var swatch = el('i', 's-' + c.kind);
334
+ legend.appendChild(swatch);
335
+ legend.appendChild(el('span', null,
336
+ c.kind.replace('_', ' ') + ' ' + (metric === 'usd' ? fmtUsd(c.usd) : fmtTokens(c.tokens))));
337
+ key.appendChild(legend);
338
+ });
339
+ into.appendChild(bar);
340
+ into.appendChild(key);
341
+ }
342
+
343
+ [['By model', cost.by_model || [], 'model', []],
344
+ ['By agent type', cost.by_agent_type || [], 'agent_type', ['conductor']],
345
+ ['By ticket', cost.by_ticket || [], 'ticket', ['conductor', 'unattributed']]].forEach(function (spec) {
346
+ into.appendChild(el('h3', null, spec[0]));
347
+ into.appendChild(chart(spec[1], spec[2], metric, spec[3]));
348
+ });
349
+
350
+ var notes = [];
351
+ notes.push('Conductor context is not attributable to any ticket; it is shown as its own row so the rows sum to the total.');
352
+ if ((cov.unattributed || 0) > 0) {
353
+ notes.push(cov.unattributed + ' agent(s) carry no ticket id in their task description and are grouped as unattributed.');
354
+ }
355
+ if ((cost.unpriced || []).length > 0) {
356
+ notes.push('Counted in tokens but absent from every amount, having no rate: ' + cost.unpriced.join(', ') + '.');
357
+ }
358
+ // A gap the page must never keep to itself: a transcript appended to while
359
+ // it is read ends in a partial record, so the number above is low by an
360
+ // amount only this line reports.
361
+ if ((cov.malformed || 0) > 0 || (cov.skipped_lines || 0) > 0) {
362
+ notes.push((cov.malformed || 0) + ' unparseable and ' + (cov.skipped_lines || 0) +
363
+ ' oversized record(s) were skipped; their tokens are missing from every figure here.');
364
+ }
365
+ into.appendChild(el('div', 'caveat', notes.join(' ')));
366
+ };
367
+
368
+ // Spend is FETCHED, never embedded. It is derived from transcripts under the
369
+ // operator's home directory — machine-local, different in every clone — so
370
+ // writing it into board.json would break the byte-exact --check contract and
371
+ // make two people with one journal disagree. Opened over file:// there is no
372
+ // server, the request fails, and the section simply never appears.
373
+ var spendAt = el('div');
374
+ app.appendChild(spendAt);
375
+ if (typeof fetch === 'function') {
376
+ fetch('cost.json', { headers: { accept: 'application/json' } })
377
+ .then(function (r) { return r.ok ? r.json() : null; })
378
+ .then(function (cost) {
379
+ if (cost && cost.schema === 1 && cost.transcripts_found) renderSpend(spendAt, cost, 'tokens');
380
+ })
381
+ .catch(function () { /* no server: the board is complete without it */ });
382
+ }
383
+
190
384
  // An initiative the board could not read is the one thing this page must
191
385
  // never omit: a missing card is indistinguishable from an initiative with
192
386
  // no work, which is the "all is well" reading the board exists to prevent.
package/scripts/board.mjs CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  } from './project.mjs';
42
42
  import { jsonEscapeInvisible } from './invisible.mjs';
43
43
  import { renderBoardHtml } from './board-html.mjs';
44
+ import { COST_SCHEMA, costJson, costReport } from './cost.mjs';
44
45
 
45
46
  export const BOARD_HTML_FILE = 'board.html';
46
47
 
@@ -98,7 +99,10 @@ export function readInitiativeBoards(tyranDir) {
98
99
  errors.push({ name, error: `0 readable events and ${damage} — the journal is damaged` });
99
100
  continue;
100
101
  }
101
- initiatives.push({ name, state, board: boardOf(state) });
102
+ // `journal` is returned, not re-derived by consumers: answer.mjs writes
103
+ // to the file this function already located, so there is one rule for
104
+ // where an initiative's journal lives (ADR-21).
105
+ initiatives.push({ name, journal, state, board: boardOf(state) });
102
106
  } catch (err) {
103
107
  errors.push({ name, error: String(err?.message ?? err) });
104
108
  }
@@ -258,8 +262,14 @@ function main() {
258
262
  const outDir = join(dir, 'state');
259
263
 
260
264
  if (flags.serve) {
261
- // Read-only, loopback-only, re-rendered per request so it is always
262
- // fresh. No filesystem path is ever derived from the URL.
265
+ // Loopback-only, re-rendered per request so it is always fresh. No
266
+ // filesystem path is ever derived from the URL.
267
+ //
268
+ // Not quite read-only, and the exception is worth stating rather than
269
+ // discovering: `/cost.json` refreshes the machine-local spend cache at
270
+ // `state/cost.json`. Nothing else is written, and that file is a
271
+ // gitignored runtime artefact — no journal, no projection, nothing
272
+ // committed.
263
273
  const server = createServer((req, res) => {
264
274
  try {
265
275
  // Binding to loopback is not enough on its own: any web page the
@@ -274,6 +284,28 @@ function main() {
274
284
  res.end('forbidden: this board answers to 127.0.0.1 only\n');
275
285
  return;
276
286
  }
287
+ // Spend is served, never rendered into the artefacts. It is derived
288
+ // from transcripts under the operator's home directory — machine-local
289
+ // by nature — so putting it in board.json would make two clones of one
290
+ // journal disagree and break the byte-exact `--check` contract. The
291
+ // page fetches this route and simply omits the section when the fetch
292
+ // fails, which is what happens over file://.
293
+ if (req.url === '/cost.json') {
294
+ let body;
295
+ try {
296
+ body = costJson(costReport({ tyranDir: dir }));
297
+ } catch (err) {
298
+ // A cost failure must never take the board down with it: the
299
+ // board answers "what is going on", and that answer does not
300
+ // depend on knowing what it cost.
301
+ res.writeHead(503, { 'content-type': 'application/json; charset=utf-8' });
302
+ res.end(JSON.stringify({ schema: COST_SCHEMA, error: String(err?.message ?? err) }) + '\n');
303
+ return;
304
+ }
305
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
306
+ res.end(body);
307
+ return;
308
+ }
277
309
  const { files } = renderAll(dir);
278
310
  if (req.url === '/' || req.url === '/index.html') {
279
311
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });