pisha-server 0.0.11 → 0.0.12

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/boards/boards.js CHANGED
@@ -108,6 +108,14 @@ export function createBoards(platform, { sessions, messaging, members }) {
108
108
 
109
109
  const prefix = () => db.prepare("SELECT v FROM board_settings WHERE k = 'prefix'").get()?.v ?? 'SQ'
110
110
  const taskId = seq => `${prefix()}-${seq}`
111
+ // The first of this company's tasks a text names ("SQ-12", with its prefix), or null.
112
+ function taskIn(text) {
113
+ const p = prefix()
114
+ for (const m of String(text ?? '').slice(0, 20_000).matchAll(/\b([A-Z][A-Z0-9]{0,5})-(\d{1,9})\b/g)) {
115
+ if (m[1] === p && db.prepare('SELECT 1 FROM tasks WHERE seq = ? AND deleted_at IS NULL').get(Number(m[2]))) return `${p}-${Number(m[2])}`
116
+ }
117
+ return null
118
+ }
111
119
  // "SQ-12", "sq-12", "#12" or 12.
112
120
  function seqOf(id) {
113
121
  const m = /^(?:[A-Za-z][A-Za-z0-9]{0,5}-|#)?(\d{1,9})$/.exec(String(id ?? '').trim())
@@ -1075,5 +1083,5 @@ export function createBoards(platform, { sessions, messaging, members }) {
1075
1083
  restore: t => restoreTasks(t, { by: FROM_GITHUB(), github: true }),
1076
1084
  })
1077
1085
 
1078
- return { boardReads, boardActions, boardMethods, boardList, forget, BOARD_SENDER }
1086
+ return { boardReads, boardActions, boardMethods, boardList, forget, taskIn, BOARD_SENDER }
1079
1087
  }
package/companies.js CHANGED
@@ -15,8 +15,8 @@ const COMPANY_NAME = /^[\p{L}\p{N} ._&-]{1,80}$/u
15
15
  const CREDENTIAL_COMPANY = /^s[qjh]_([a-z0-9]{8})_/
16
16
 
17
17
  // What a company may keep, when it isn't what the server starts with.
18
- const QUOTAS = ['max_sessions', 'max_messages', 'max_events', 'max_updates', 'max_files_gb', 'max_db_mb', 'stored_text_mb_hour', 'retention_days', 'event_hours', 'inbox_days']
19
- const RETENTION = ['retention_days', 'event_hours', 'inbox_days']
18
+ const QUOTAS = ['max_sessions', 'max_messages', 'max_events', 'max_updates', 'max_files_gb', 'max_db_mb', 'stored_text_mb_hour', 'retention_days', 'event_hours', 'inbox_days', 'usage_days']
19
+ const RETENTION = ['retention_days', 'event_hours', 'inbox_days', 'usage_days']
20
20
 
21
21
  // How long a company waits after being deleted, in case it was a mistake.
22
22
  const GRACE_MS = Number(process.env.PISHA_COMPANY_GRACE_MS ?? 30 * 24 * 3600_000)
@@ -226,17 +226,17 @@ export function createCompanies(server) {
226
226
  },
227
227
  'company/retention': {
228
228
  role: 'manager', method: 'GET',
229
- run: ({ company }) => ({ retention_days: company.platform.quota('retention_days', 7), event_hours: company.platform.quota('event_hours', Number(process.env.OBSERVE_TTL_HOURS ?? 24)), inbox_days: company.platform.quota('inbox_days', 90) }),
229
+ run: ({ company }) => ({ retention_days: company.platform.quota('retention_days', 7), event_hours: company.platform.quota('event_hours', Number(process.env.OBSERVE_TTL_HOURS ?? 24)), inbox_days: company.platform.quota('inbox_days', 90), usage_days: company.platform.quota('usage_days', 400) }),
230
230
  },
231
231
  'company/retention/set': {
232
232
  role: 'owner', method: 'POST',
233
233
  run({ company, params }) {
234
234
  const wanted = Object.fromEntries(RETENTION.filter(k => params[k] != null).map(k => [k, params[k]]))
235
235
  const limits = { ...quotasOf(row(company.id)), ...cleanQuotas(wanted) }
236
- if ((limits.retention_days ?? 0) > 3650 || (limits.event_hours ?? 0) > 8760 || (limits.inbox_days ?? 0) > 3650) throw bad('at most 3650 days of messages or of the inbox, and 8760 hours of activity')
236
+ if ((limits.retention_days ?? 0) > 3650 || (limits.event_hours ?? 0) > 8760 || (limits.inbox_days ?? 0) > 3650 || (limits.usage_days ?? 0) > 3650) throw bad('at most 3650 days of messages, of the inbox or of token usage, and 8760 hours of activity')
237
237
  control.prepare('UPDATE companies SET limits_json = ? WHERE id = ?').run(JSON.stringify(limits), company.id)
238
238
  company.platform.setQuotas(limits)
239
- return { retention_days: limits.retention_days ?? 7, event_hours: limits.event_hours ?? null, inbox_days: limits.inbox_days ?? 90 }
239
+ return { retention_days: limits.retention_days ?? 7, event_hours: limits.event_hours ?? null, inbox_days: limits.inbox_days ?? 90, usage_days: limits.usage_days ?? 400 }
240
240
  },
241
241
  },
242
242
  // (It answers by itself: a whole company goes down the response as it is read.)
package/company.js CHANGED
@@ -7,6 +7,7 @@ import { createMachines } from './machines/index.js'
7
7
  import { createOrganization } from './organization/index.js'
8
8
  import { createDashboard } from './dashboard/index.js'
9
9
  import { createBoards } from './boards/index.js'
10
+ import { createUsage } from './usage/index.js'
10
11
  import { upgradeStoredData } from './data-upgrade.js'
11
12
  import { cleanExports } from './company-export.js'
12
13
 
@@ -34,7 +35,8 @@ export function createCompany(server, options) {
34
35
  const machines = createMachines(platform, { sessions, observation, permissions })
35
36
  const organization = createOrganization(platform, { sessions, messaging, observation, machines })
36
37
  const boards = createBoards(platform, { sessions, messaging, members: options.members ?? (() => []) })
37
- const dashboard = createDashboard(platform, { sessions, messaging, inbox, plans, observation, machines, organization, permissions, boards })
38
+ const usage = createUsage(platform, { sessions, boards })
39
+ const dashboard = createDashboard(platform, { sessions, messaging, inbox, plans, observation, machines, organization, permissions, boards, usage })
38
40
 
39
41
  // What a session can ask for, by its name in the request.
40
42
  const methods = {
@@ -47,6 +49,7 @@ export function createCompany(server, options) {
47
49
  inbox.cleanupInbox()
48
50
  sessions.cleanupUpdates()
49
51
  observation.cleanupEvents()
52
+ usage.cleanupUsage()
50
53
  platform.cleanupLimits()
51
54
  platform.cleanupAudit()
52
55
  platform.truncateLogHourly()
@@ -2,7 +2,7 @@ import { rmSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { unix, now, guarded, bad, ApiError, VERSION, ROLES, AGENTS } from '../platform/index.js'
4
4
 
5
- export function createDashboard(platform, { sessions, observation, machines, messaging, inbox, plans, organization, permissions, boards }) {
5
+ export function createDashboard(platform, { sessions, observation, machines, messaging, inbox, plans, organization, permissions, boards, usage }) {
6
6
  const { rotateJoinToken, db, bus, broadcast, sseClients, truncateLog, dataDir, log, every } = platform
7
7
  const {
8
8
  register, approveSession, presenceOf, personaView, identityCreatedAt, identityExists, isOnline, linksOf,
@@ -166,6 +166,7 @@ export function createDashboard(platform, { sessions, observation, machines, mes
166
166
  'boards/tasks': q => boards.boardReads.tasks(q),
167
167
  'boards/task': q => boards.boardReads.task(q),
168
168
  'boards/trash': q => boards.boardReads.trash(q),
169
+ usage: q => usage.usageReads.usage(q),
169
170
  events(q) {
170
171
  const limit = Math.max(1, Math.min(Number(q.get('limit') ?? 300) || 300, 1000))
171
172
  const before = Number(q.get('before') ?? Number.MAX_SAFE_INTEGER)
@@ -373,7 +374,7 @@ export function createDashboard(platform, { sessions, observation, machines, mes
373
374
  // Who may do each thing, at least. Whatever isn't here nobody may do, and the
374
375
  // server refuses to start (see the end): every new action says who it is for.
375
376
  const dashboardRoles = {
376
- reads: { inbox: 'observer', 'inbox/done': 'observer', timeline: 'observer', state: 'observer', events: 'observer', hosts: 'observer', messages: 'observer', stream: 'observer', boards: 'observer', 'boards/tasks': 'observer', 'boards/task': 'observer', 'boards/trash': 'manager' },
377
+ reads: { inbox: 'observer', 'inbox/done': 'observer', timeline: 'observer', state: 'observer', events: 'observer', hosts: 'observer', messages: 'observer', stream: 'observer', boards: 'observer', 'boards/tasks': 'observer', 'boards/task': 'observer', 'boards/trash': 'manager', usage: 'observer' },
377
378
  actions: {
378
379
  'inbox/resolve': 'operator', 'inbox/read-all': 'operator', 'inbox/answer': 'operator', 'inbox/dismiss': 'operator', kick: 'operator', clear: 'operator', archive: 'operator', unarchive: 'operator',
379
380
  'terminals/open': 'operator', 'terminals/kill': 'operator', 'terminal/ticket': 'operator', 'hosts/personas': 'operator',
@@ -11,7 +11,7 @@ export function createObservation(platform) {
11
11
  // everything to dashboard clients as it happens.
12
12
  const EVENT_KINDS = new Set([
13
13
  'observe_start', 'session_start', 'prompt', 'tool_start', 'tool_end', 'text', 'usage',
14
- 'notification', 'subagent_start', 'subagent_stop', 'stop', 'compact', 'compacted', 'session_end',
14
+ 'notification', 'subagent_start', 'subagent_stop', 'stop', 'compact', 'compacted', 'session_end', 'tokens',
15
15
  ])
16
16
  const MAX_EVENT_JSON = 20_000
17
17
  const activity = new Map() // name -> derived state
@@ -43,6 +43,9 @@ export function createObservation(platform) {
43
43
  compact: { trigger: STR(20) },
44
44
  compacted: { trigger: STR(20), summary: STR(20_000) },
45
45
  session_end: { reason: STR(100) },
46
+ // A model call's tokens (or a turn's, for an agent that keeps them by the
47
+ // turn): kept added up by the usage module, not as an event.
48
+ tokens: { model: STR(100), input: INT, cache_read: INT, cache_write: INT, output: INT, calls: INT, sub: BOOL, cause: STR(20), msg: INT, task: STR(40) },
46
49
  }
47
50
  function cleanEvent(kind, data) {
48
51
  const out = {}
@@ -149,13 +152,16 @@ export function createObservation(platform) {
149
152
  const insert = db.prepare('INSERT INTO events (session, ts, kind, data) VALUES (?, ?, ?, ?)')
150
153
  // The whole batch is checked first, then stored at once: all of it or none
151
154
  // (a refusal halfway would store part of it and the retry would repeat it).
152
- const batch = []
155
+ const batch = [], tokens = []
153
156
  for (const ev of events) {
154
157
  if (!ev || typeof ev !== 'object' || !EVENT_KINDS.has(ev.kind)) continue
155
158
  // Whole milliseconds within the events' lifetime: the history cursor relies on it.
156
- const ts = Number.isSafeInteger(ev.ts) ? Math.max(now() - eventKeptMs(), Math.min(ev.ts, now() + 5000)) : now()
159
+ // (Tokens are kept far longer than events: one reported late keeps its day, up to 30 back.)
160
+ const oldest = ev.kind === 'tokens' ? now() - 30 * 24 * 3600_000 : now() - eventKeptMs()
161
+ const ts = Number.isSafeInteger(ev.ts) ? Math.max(oldest, Math.min(ev.ts, now() + 5000)) : now()
157
162
  const kind = ev.kind
158
163
  const rest = cleanEvent(kind, ev)
164
+ if (kind === 'tokens') { tokens.push({ ...rest, ts }); continue }
159
165
  const data = JSON.stringify(rest)
160
166
  if (data.length > MAX_EVENT_JSON) continue
161
167
  batch.push({ ts, kind, rest, data })
@@ -176,7 +182,8 @@ export function createObservation(platform) {
176
182
  stored++
177
183
  } })
178
184
  if (stored) bus.emit('session-changed', name)
179
- return { stored }
185
+ if (tokens.length) bus.emit('tokens', name, tokens)
186
+ return { stored: stored + tokens.length }
180
187
  }
181
188
 
182
189
  // Tell a worker's coordinator when its context is nearly full (once per fill-up)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pisha-server",
3
- "version": "0.0.11",
3
+ "version": "0.0.12",
4
4
  "description": "Pisha: run teams of AI coding agents (Claude Code, Codex, Grok) from a self-hosted dashboard, with an inbox for your decisions",
5
5
  "keywords": [
6
6
  "pisha",
@@ -32,6 +32,7 @@
32
32
  "platform",
33
33
  "sessions",
34
34
  "ui",
35
+ "usage",
35
36
  "vendor",
36
37
  "install",
37
38
  "pisha-host.mjs",
package/pisha-host.mjs CHANGED
@@ -39,7 +39,7 @@ import { fileURLToPath } from 'node:url'
39
39
  import { createCipheriv, createDecipheriv, createHash, createPrivateKey, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes, sign, verify } from 'node:crypto'
40
40
  import { promisify } from 'node:util'
41
41
 
42
- const VERSION = '0.0.11'
42
+ const VERSION = '0.0.12'
43
43
  // Who signs releases (scripts/release-sign.mjs): `update` only installs what
44
44
  // this key signed. Empty: this copy has no key to check with.
45
45
  const RELEASE_PUBLIC_KEY = 'MCowBQYDK2VwAyEA49ojJq4r4KLiWcRJiDxui2HzSZYpZA1qCBI4LLtOOyo'
@@ -1310,8 +1310,14 @@ const clearContext = target => typeLine(target, '/clear', /(^|\s)\/clear\s*$/m)
1310
1310
  async function typeAnswer(target, text) {
1311
1311
  const line = String(text).replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/\s+/g, ' ').trim()
1312
1312
  if (!line || line.length > 2200) throw new Error('the answer must be one line of up to 2200 characters')
1313
- const end = line.split(' ').pop().slice(-20).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1314
- await typeLine(target, line, new RegExp(`${end}\\s*│?\\s*$`, 'm'))
1313
+ await typeLine(target, line, { test: screen => answerLanded(screen, line) })
1314
+ }
1315
+
1316
+ // Whether a typed answer reached the input: its end is there, or the paste
1317
+ // Claude Code shows a long one as instead ("[Pasted text #1 +3 lines]").
1318
+ export function answerLanded(screen, line) {
1319
+ const end = String(line).split(' ').pop().slice(-20).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1320
+ return new RegExp(`(${end}|\\[Pasted text #\\d+[^\\]\\n]*\\])\\s*│?\\s*$`, 'm').test(screen)
1315
1321
  }
1316
1322
 
1317
1323
  const ASKING_ON_SCREEN = /^\s*❯\s*\d+\.\s|Esc to cancel|Enter to confirm/m
@@ -1 +1 @@
1
- stnwU7f_BWFK8fWnHhNqphYUwM7ZGB7RcefscQJlTRsEo2ieCJsn-X7vJqngdDLuVBdVzyatJykReFBnRLMkAw
1
+ mV_Xs4Zu1h2EiHAlvzx7Lj7eRnI0RG1Y1z1kc0yxIGSQ3hdikrXgyfb4m6o1k9YvjpZPLFSx_j_xsHLwnQMqDw
package/ui/back.js CHANGED
@@ -59,6 +59,7 @@ export function parentOf(r) {
59
59
  case 'hosts': return r.host ? '#/hosts' : null
60
60
  case 'addmachine': return '#/hosts'
61
61
  case 'boards': return null
62
+ case 'usage': return null
62
63
  case 'board': return r.task ? `#/b/${r.board}` : '#/boards'
63
64
  case 'terminal': return `#/h/${enc(r.host)}`
64
65
  case 'session': {
@@ -90,6 +91,7 @@ export function placeName(hash) {
90
91
  case 'newteam': return T.newTeam
91
92
  case 'addmachine': return T.addTitle
92
93
  case 'boards': return T.boards
94
+ case 'usage': return T.usage
93
95
  case 'board': return state.boards.find(b => b.id === r.board)?.name ?? T.boards
94
96
  default: return T.leads
95
97
  }
package/ui/i18n.js CHANGED
@@ -387,6 +387,7 @@ const I18N = {
387
387
  notifyBlocked: 'This browser blocks notices from this site: allow them in its settings.',
388
388
  notifyUnsupported: 'This browser can not show notices.',
389
389
  retentionInbox: 'Inbox, what is done (days)',
390
+ retentionUsage: 'Token usage (days)',
390
391
  ibxWaiting: n => (n === 1 ? '1 waiting on you' : `${n} waiting on you`),
391
392
  ibxNothingListed: 'Nothing here yet.',
392
393
  ibxEmptyHint: 'When a coordinator needs a decision, or has something for you, it shows up here.',
@@ -476,6 +477,31 @@ const I18N = {
476
477
  vRates: ['Normal', 'Fast', 'Faster'],
477
478
  // Task boards
478
479
  boards: 'Boards',
480
+ usage: 'Usage',
481
+ usageSub: 'Tokens spent by the agents',
482
+ usagePeriod: 'Period',
483
+ usageRanges: { today: 'Today', d7: '7 days', d30: '30 days', d90: '90 days' },
484
+ usageExport: 'Export CSV',
485
+ usageLoading: 'Loading…',
486
+ usageAllTeams: 'All teams',
487
+ usageAllAgents: 'All agents',
488
+ usageAllModels: 'All models',
489
+ usageNoTeam: '(no team)',
490
+ usageTotal: 'Tokens',
491
+ usageKinds: { input: 'Input', output: 'Output', cache_read: 'Cache read', cache_write: 'Cache write' },
492
+ usageCached: p => `${p} % of input from cache`,
493
+ usageCalls: n => `${n.toLocaleString('en-GB')} model call${n === 1 ? '' : 's'}`,
494
+ usageOverTime: 'Over time',
495
+ usageByTeam: 'By team',
496
+ usageByCause: 'By what started the work',
497
+ usageByTask: 'By board task',
498
+ usageByModel: 'By model',
499
+ usageBySession: 'By session',
500
+ usageNoTasks: 'Nothing spent on a board task in this period.',
501
+ usageEmpty: 'Nothing spent in this period',
502
+ usageEmptyHint: 'Each session reports the tokens it spends as it works: Claude Code, Codex CLI and Grok CLI.',
503
+ usageCauses: { user: 'Your orders', inbox: 'Your answers from the inbox', coordinator: 'From their coordinator', worker: 'Workers\' reports', link: 'Between linked teams', board: 'Board notices', system: 'Server notices', other: 'Other messages', self: 'On its own' },
504
+ usageCauseHints: { user: 'Turns started by what you typed in a session\'s terminal', inbox: 'Turns started by your answers from the inbox', coordinator: 'Workers\' turns on what their coordinator handed them', worker: 'Coordinators\' turns on their workers\' reports', link: 'Turns started by a message from a linked team', board: 'Turns started by the task board', system: 'Turns started by the server\'s notices', other: 'Turns started by another message', self: 'Before any prompt: a session starting, or after a compaction' },
479
505
  boardsCount: n => `${n} board${n === 1 ? '' : 's'}`,
480
506
  noBoards: 'No boards yet',
481
507
  noBoardsHint: 'A board keeps the company\'s tasks. People and agents work on them, and each team sees the boards it is given.',
@@ -1425,6 +1451,7 @@ const I18N = {
1425
1451
  notifyBlocked: 'Este navegador bloquea los avisos de este sitio: permítelos en sus ajustes.',
1426
1452
  notifyUnsupported: 'Este navegador no puede mostrar avisos.',
1427
1453
  retentionInbox: 'Bandeja, lo hecho (días)',
1454
+ retentionUsage: 'Consumo de tokens (días)',
1428
1455
  ibxWaiting: n => (n === 1 ? '1 te espera' : `${n} te esperan`),
1429
1456
  ibxNothingListed: 'Aún no hay nada.',
1430
1457
  ibxEmptyHint: 'Cuando un coordinador necesite una decisión, o tenga algo para ti, aparecerá aquí.',
@@ -1514,6 +1541,31 @@ const I18N = {
1514
1541
  vRates: ['Normal', 'Rápido', 'Muy rápido'],
1515
1542
  // Tableros de tareas
1516
1543
  boards: 'Tableros',
1544
+ usage: 'Consumo',
1545
+ usageSub: 'Los tokens que gastan los agentes',
1546
+ usagePeriod: 'Periodo',
1547
+ usageRanges: { today: 'Hoy', d7: '7 días', d30: '30 días', d90: '90 días' },
1548
+ usageExport: 'Exportar CSV',
1549
+ usageLoading: 'Cargando…',
1550
+ usageAllTeams: 'Todos los equipos',
1551
+ usageAllAgents: 'Todos los agentes',
1552
+ usageAllModels: 'Todos los modelos',
1553
+ usageNoTeam: '(sin equipo)',
1554
+ usageTotal: 'Tokens',
1555
+ usageKinds: { input: 'Entrada', output: 'Salida', cache_read: 'Lectura de caché', cache_write: 'Escritura de caché' },
1556
+ usageCached: p => `${p} % de la entrada, desde la caché`,
1557
+ usageCalls: n => `${n.toLocaleString('es-ES')} llamada${n === 1 ? '' : 's'} al modelo`,
1558
+ usageOverTime: 'En el tiempo',
1559
+ usageByTeam: 'Por equipo',
1560
+ usageByCause: 'Por lo que empezó el trabajo',
1561
+ usageByTask: 'Por tarea del tablero',
1562
+ usageByModel: 'Por modelo',
1563
+ usageBySession: 'Por sesión',
1564
+ usageNoTasks: 'Nada gastado en tareas del tablero en este periodo.',
1565
+ usageEmpty: 'Nada gastado en este periodo',
1566
+ usageEmptyHint: 'Cada sesión informa de los tokens que gasta mientras trabaja: Claude Code, Codex CLI y Grok CLI.',
1567
+ usageCauses: { user: 'Tus órdenes', inbox: 'Tus respuestas desde la bandeja', coordinator: 'De su coordinador', worker: 'Informes de los workers', link: 'Entre equipos enlazados', board: 'Avisos del tablero', system: 'Avisos del servidor', other: 'Otros mensajes', self: 'Por su cuenta' },
1568
+ usageCauseHints: { user: 'Turnos empezados por lo que escribiste en el terminal de una sesión', inbox: 'Turnos empezados por tus respuestas desde la bandeja', coordinator: 'Turnos de los workers con lo que les pasó su coordinador', worker: 'Turnos de los coordinadores con los informes de sus workers', link: 'Turnos empezados por un mensaje de un equipo enlazado', board: 'Turnos empezados por el tablero de tareas', system: 'Turnos empezados por avisos del servidor', other: 'Turnos empezados por otro mensaje', self: 'Antes de cualquier prompt: una sesión que empieza, o tras una compactación' },
1517
1569
  boardsCount: n => `${n} tablero${n === 1 ? '' : 's'}`,
1518
1570
  noBoards: 'Todavía no hay tableros',
1519
1571
  noBoardsHint: 'Un tablero guarda las tareas de la empresa. Personas y agentes trabajan en ellas, y cada equipo ve los tableros que se le asignan.',
package/ui/icons.js CHANGED
@@ -19,6 +19,7 @@ const PATHS = {
19
19
  more: '<circle cx="5" cy="12" r="1.4"/><circle cx="12" cy="12" r="1.4"/><circle cx="19" cy="12" r="1.4"/>',
20
20
  sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>',
21
21
  moon: '<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>',
22
+ usage: '<path d="M4 20h16"/><rect x="5" y="11" width="3" height="6" rx="1"/><rect x="10.5" y="6" width="3" height="11" rx="1"/><rect x="16" y="9" width="3" height="8" rx="1"/>',
22
23
  board: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M9 4v16M15 4v16"/><path d="M5.5 8h1.5M11 8h2M11 11h2M17 8h1.5"/>',
23
24
  pr: '<circle cx="6" cy="6" r="2.3"/><circle cx="6" cy="18" r="2.3"/><circle cx="18" cy="18" r="2.3"/><path d="M6 8.3v7.4M18 15.7V10a3 3 0 0 0-3-3h-4"/><path d="m13 4.5-2.5 2.5 2.5 2.5"/>',
24
25
  // (What an inbox entry is: a permission, someone to approve, a question, news, done.)
package/ui/index.html CHANGED
@@ -24,6 +24,7 @@
24
24
  <link rel="stylesheet" href="/ui/screen-teams.css">
25
25
  <link rel="stylesheet" href="/ui/screen-org.css">
26
26
  <link rel="stylesheet" href="/ui/screen-boards.css">
27
+ <link rel="stylesheet" href="/ui/screen-usage.css">
27
28
  <link rel="stylesheet" href="/ui/screen-team.css">
28
29
  <link rel="stylesheet" href="/ui/screen-session.css">
29
30
  <link rel="stylesheet" href="/ui/screen-machines.css">
@@ -81,6 +82,7 @@
81
82
  <div id="alerts" hidden></div>
82
83
  <div id="teams" hidden></div>
83
84
  <div id="boards" hidden></div>
85
+ <div id="usage" hidden></div>
84
86
  <div id="team" hidden></div>
85
87
  <div id="newteam" hidden></div>
86
88
  <div id="addmachine" hidden></div>
package/ui/nav.js CHANGED
@@ -98,6 +98,7 @@ export function renderNav() {
98
98
  <a href="#/"${here(r.view === 'inbox')}>${icon('inbox')}<span class="name">${esc(T.inbox)}</span>${inboxN ? `<span class="badge">${inboxN}</span>` : ''}</a>
99
99
  <a href="#/teams"${here(isTeams(r) && !r.squad)}>${icon('teams')}<span class="name">${esc(T.teams)}</span></a>
100
100
  <a href="#/boards"${here(isBoards(r))}>${icon('board')}<span class="name">${esc(T.boards)}</span>${boardsPending() ? `<span class="rail-count" title="${esc(T.pendingTitle)}">${boardsPending()}</span>` : ''}</a>
101
+ <a href="#/usage"${here(r.view === 'usage')}>${icon('usage')}<span class="name">${esc(T.usage)}</span></a>
101
102
  <div class="rail-row"><a href="#/hosts"${here(isMachines(r))}>${icon('machines')}<span class="name">${esc(T.machines)}</span>${machineList.length ? `<span class="rail-count">${esc(T.ofTotal(machinesOn, machineList.length))}</span>` : ''}</a>${can('manager') ? `<button type="button" class="icon-btn" id="addHostBtn" title="${esc(T.addTitle)}" aria-label="${esc(T.addTitle)}">${icon('plus')}</button>` : ''}</div>
102
103
  </div>`
103
104
 
package/ui/org.js CHANGED
@@ -109,6 +109,18 @@ function orgLinkPath(p, q) {
109
109
  const d = Math.max(30, Math.abs(y2 - y1) / 2) * (down ? 1 : -1)
110
110
  return { d: `M${pc} ${y1} C${pc} ${y1 + d} ${qc} ${y2 - d} ${qc} ${y2}`, mx: (pc + qc) / 2, my: (y1 + y2) / 2 }
111
111
  }
112
+ // A message between two linked coordinators: a light runs along their link,
113
+ // from the one who wrote to the other, and its count pulses.
114
+ const linkFlashes = new Map() // "from>to" -> when
115
+ const LINK_FLASH = 1800
116
+ export function flashLink(from, to) {
117
+ linkFlashes.set(`${from}>${to}`, now())
118
+ if (currentRoute().view !== 'org') return
119
+ soon(renderOrg)
120
+ setTimeout(() => { linkFlashes.delete(`${from}>${to}`); if (currentRoute().view === 'org') soon(renderOrg) }, LINK_FLASH + 100)
121
+ }
122
+ const flashing = (from, to) => now() - (linkFlashes.get(`${from}>${to}`) ?? 0) < LINK_FLASH
123
+
112
124
  function orgLinesHtml() {
113
125
  let paths = '', labels = ''
114
126
  for (const l of state.links) {
@@ -118,8 +130,9 @@ function orgLinesHtml() {
118
130
  const n = recentOf(l)
119
131
  // (Amber from three quarters of what two coordinators may send each other in an hour.)
120
132
  const cls = n >= 60 ? 'full' : n >= 45 ? 'warn' : ''
121
- paths += `<path class="l ${cls}" d="${d}"/><path class="hit" d="${d}" data-la="${esc(l.a)}" data-lb="${esc(l.b)}"/>`
122
- labels += `<button class="org-label ${cls}" style="left:${Math.round(mx)}px;top:${Math.round(my)}px" data-la="${esc(l.a)}" data-lb="${esc(l.b)}" title="${esc(T.orgLinkRecent(n))}">${n}</button>`
133
+ const runs = [[l.a, l.b, p, q], [l.b, l.a, q, p]].filter(([f, t]) => flashing(f, t)).map(([, , from, to]) => `<path class="run" pathLength="100" d="${orgLinkPath(from, to).d}"/>`).join('')
134
+ paths += `<path class="l ${cls}" d="${d}"/>${runs}<path class="hit" d="${d}" data-la="${esc(l.a)}" data-lb="${esc(l.b)}"/>`
135
+ labels += `<button class="org-label ${cls}${runs ? ' got' : ''}" style="left:${Math.round(mx)}px;top:${Math.round(my)}px" data-la="${esc(l.a)}" data-lb="${esc(l.b)}" title="${esc(T.orgLinkRecent(n))}">${n}</button>`
123
136
  }
124
137
  return { paths, labels }
125
138
  }
@@ -138,11 +151,14 @@ export function noteHandoff(m) {
138
151
  soon(renderOrg)
139
152
  setTimeout(() => { flashes.delete(m.target); if (currentRoute().view === 'org') soon(renderOrg) }, 2200)
140
153
  }
154
+ // A plan task's ref as a short tag: the board task or issue it names (SQ-12,
155
+ // #30), or none. A path or a link stays in the tooltip, not on the card.
156
+ const refId = ref => String(ref ?? '').match(/\b[A-Z][A-Z0-9]{0,5}-\d{1,9}\b|#\d{1,9}\b/)?.[0] ?? ''
141
157
  function taskOf(s, kind) {
142
158
  const coord = kind === 'coord' ? s.name : orgCoordOf(s)
143
159
  const plan = coord ? state.plans.get(coord) : null
144
160
  const t = plan?.tasks.find(x => x.who === s.name && x.state === 'doing')
145
- if (t) return { title: t.title, ref: t.ref, since: t.since }
161
+ if (t) return { title: t.title, ref: refId(t.ref), full: t.ref, since: t.since }
146
162
  const h = handed.get(s.name)
147
163
  if (h) return { title: h.text.replace(/\s+/g, ' '), from: h.from, since: h.at }
148
164
  if (kind === 'coord' && plan?.title) return { title: plan.title }
@@ -174,7 +190,7 @@ function orgAgent(s, kind) {
174
190
  <span class="oa-who"><span class="oa-nm"><b>${esc(s.name)}</b><span class="oa-st ${st.cls}">${st.cls === 'work' ? '<span class="oa-spin" aria-hidden="true"></span>' : st.cls ? '<span class="oa-pd" aria-hidden="true"></span>' : ''}${esc(st.label)}</span></span>
175
191
  ${model ? `<span class="oa-model">${esc(model)}</span>` : ''}${kind === 'coord' ? `<span class="oa-lead">${esc(T.roleName.coordinator)}</span>` : ''}</span>
176
192
  <button class="org-more" data-orgmenu="agent" data-name="${esc(s.name)}" aria-label="${esc(T.orgAgentMenu(s.name))}" aria-haspopup="menu">${icon('more')}</button></div>
177
- <div class="oa-task${task ? '' : ' none'}" title="${esc(task?.title ?? '')}">${task?.from ? `<span class="oa-from">↳ ${esc(task.from)}</span>` : ''}${task?.ref ? `<span class="oa-ref">${esc(task.ref)}</span>` : ''}<span class="oa-tt">${esc(task?.title ?? T.orgNoTask)}</span>${clockHtml(task?.since)}</div>
193
+ <div class="oa-task${task ? '' : ' none'}" title="${esc([task?.title, task?.full].filter(Boolean).join(' · '))}">${task?.from ? `<span class="oa-from">↳ ${esc(task.from)}</span>` : ''}${task?.ref ? `<span class="oa-ref">${esc(task.ref)}</span>` : ''}<span class="oa-tt">${esc(task?.title ?? T.orgNoTask)}</span>${clockHtml(task?.since)}</div>
178
194
  <div class="oa-now">${esc(status(s).text)}</div>
179
195
  ${Number.isFinite(pct) ? `<div class="oa-ctx" title="${esc(T.contextPct(Math.round(pct)))}"><span class="oa-bar"><i class="${pct >= 95 ? 'hot' : pct >= 80 ? 'warm' : ''}" style="width:${Math.max(2, Math.min(100, pct))}%"></i></span>${a.context_tokens && window ? `${kTokens(a.context_tokens)} / ${kTokens(window)}` : `${Math.round(pct)}%`}</div>` : ''}
180
196
  </div>`
package/ui/palette.js CHANGED
@@ -57,6 +57,7 @@ function candidates() {
57
57
  { group: 'screens', label: T.teams, lead: icon('teams'), go: '#/teams' },
58
58
  { group: 'screens', label: T.viewMosaic, sub: T.allSessions, lead: icon('teams'), go: '#/mosaic' },
59
59
  { group: 'screens', label: T.org, lead: icon('teams'), go: '#/org' },
60
+ { group: 'screens', label: T.usage, sub: T.usageSub, lead: icon('usage'), go: '#/usage' },
60
61
  { group: 'screens', label: T.machines, sub: hosts.size ? T.ofTotal([...hosts.values()].filter(h => h.online).length, hosts.size) : '', lead: icon('machines'), go: '#/hosts' },
61
62
  { group: 'screens', label: T.settings, lead: icon('settings'), run: async () => (await import('./people.js')).openSettings() },
62
63
  )
package/ui/people.js CHANGED
@@ -229,6 +229,7 @@ export function openSettings(start) {
229
229
  <div class="set-card"><form data-retention class="people-form"><label class="field"><span>${esc(T.retentionDays)}</span><input type="text" inputmode="numeric" name="retention_days" value="${esc(kept.retention_days)}"></label>
230
230
  <label class="field"><span>${esc(T.eventHours)}</span><input type="text" inputmode="numeric" name="event_hours" value="${esc(kept.event_hours)}"></label>
231
231
  <label class="field"><span>${esc(T.retentionInbox)}</span><input type="text" inputmode="numeric" name="inbox_days" value="${esc(kept.inbox_days ?? 90)}"></label>
232
+ <label class="field"><span>${esc(T.retentionUsage)}</span><input type="text" inputmode="numeric" name="usage_days" value="${esc(kept.usage_days ?? 400)}"></label>
232
233
  <button class="btn primary">${esc(T.save)}</button></form><p class="note" data-saved></p></div>
233
234
  <h4>${esc(T.exportTitle)}</h4><div class="set-card set-row"><p class="note">${esc(T.exportHint)}</p>
234
235
  <a class="btn" href="${esc(inCompany('/api/company/export'))}" download>${esc(T.exportBtn)}</a></div>
@@ -242,7 +243,7 @@ export function openSettings(start) {
242
243
  ok()
243
244
  const v = Object.fromEntries(new FormData(e.target))
244
245
  try {
245
- await call(inCompany('/api/company/retention/set'), { retention_days: Number(v.retention_days), event_hours: Number(v.event_hours), inbox_days: Number(v.inbox_days) })
246
+ await call(inCompany('/api/company/retention/set'), { retention_days: Number(v.retention_days), event_hours: Number(v.event_hours), inbox_days: Number(v.inbox_days), usage_days: Number(v.usage_days) })
246
247
  body.querySelector('[data-saved]').textContent = T.saved
247
248
  } catch (err) { fail(err) }
248
249
  }
package/ui/router.js CHANGED
@@ -10,6 +10,7 @@ import { buildMosaic, renderArchived } from './mosaic.js'
10
10
  import { renderInbox } from './inbox.js'
11
11
  import { renderTeams } from './teams.js'
12
12
  import { renderBoards } from './boards.js'
13
+ import { renderUsage } from './usage.js'
13
14
  import { renderTeam } from './team.js'
14
15
  import { renderSessionAside } from './session.js'
15
16
  import { renderNewTeam } from './newteam.js'
@@ -100,6 +101,7 @@ export function route() {
100
101
  $('inbox').hidden = r.view !== 'inbox'
101
102
  $('teams').hidden = r.view !== 'teams'
102
103
  $('boards').hidden = r.view !== 'boards' && r.view !== 'board'
104
+ $('usage').hidden = r.view !== 'usage'
103
105
  $('team').hidden = r.view !== 'team'
104
106
  $('newteam').hidden = r.view !== 'newteam'
105
107
  $('addmachine').hidden = r.view !== 'addmachine'
@@ -131,12 +133,12 @@ export function route() {
131
133
  $('session').hidden = true
132
134
  $('mosaic').hidden = false
133
135
  buildMosaic()
134
- } else if (r.view === 'archived' || r.view === 'org' || r.view === 'inbox' || r.view === 'teams' || r.view === 'boards' || r.view === 'board' || r.view === 'team' || r.view === 'newteam' || r.view === 'addmachine') {
136
+ } else if (r.view === 'archived' || r.view === 'org' || r.view === 'inbox' || r.view === 'teams' || r.view === 'boards' || r.view === 'board' || r.view === 'usage' || r.view === 'team' || r.view === 'newteam' || r.view === 'addmachine') {
135
137
  if (state.sessionView) { state.sessionView.destroy(); state.sessionView = null; $('session').innerHTML = '' }
136
138
  clearMosaic()
137
139
  $('session').hidden = true
138
140
  $('mosaic').hidden = true
139
- if (r.view === 'org') renderOrg(); else if (r.view === 'inbox') renderInbox(); else if (r.view === 'teams') renderTeams(); else if (r.view === 'boards' || r.view === 'board') renderBoards(); else if (r.view === 'team') renderTeam(); else if (r.view === 'newteam') renderNewTeam(); else if (r.view === 'addmachine') renderAddMachine(); else renderArchived()
141
+ if (r.view === 'org') renderOrg(); else if (r.view === 'inbox') renderInbox(); else if (r.view === 'teams') renderTeams(); else if (r.view === 'boards' || r.view === 'board') renderBoards(); else if (r.view === 'usage') renderUsage(); else if (r.view === 'team') renderTeam(); else if (r.view === 'newteam') renderNewTeam(); else if (r.view === 'addmachine') renderAddMachine(); else renderArchived()
140
142
  } else if (st) {
141
143
  // The session's live terminal, as in Machines: watch it and type to it.
142
144
  if (state.sessionView) { state.sessionView.destroy(); state.sessionView = null; $('session').innerHTML = '' }
package/ui/routes.js CHANGED
@@ -19,6 +19,7 @@ export function parseRoute(hash) {
19
19
  if (hash === '#/teams') return { view: 'teams' }
20
20
  // The task boards; one of them, with a task open beside it (or a new one).
21
21
  if (hash === '#/boards') return { view: 'boards' }
22
+ if (hash === '#/usage') return { view: 'usage' }
22
23
  const bd = hash.match(/^#\/b\/(\d{1,9})(?:\/(new|[A-Za-z][A-Za-z0-9]{0,5}-\d{1,9}))?$/)
23
24
  if (bd) return { view: 'board', board: Number(bd[1]), ...(bd[2] ? { task: bd[2] } : {}) }
24
25
  if (hash === '#/new') return { view: 'newteam' }
package/ui/screen-org.css CHANGED
@@ -87,7 +87,7 @@
87
87
  .oa-task { display: flex; align-items: baseline; gap: 6px; min-width: 0; color: var(--text); font-weight: 500; }
88
88
  .oa-task.none { color: var(--faint); font-weight: 400; }
89
89
  .oa-tt { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
90
- .oa-ref { flex: none; padding: 0 5px; border-radius: 5px; background: var(--tray); color: var(--muted); font: 500 11px/18px var(--mono); }
90
+ .oa-ref { flex: 0 1 auto; max-width: 40%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 0 5px; border-radius: 5px; background: var(--tray); color: var(--muted); font: 500 11px/18px var(--mono); }
91
91
  .oa-from { flex: none; color: var(--muted); font: 500 12px var(--mono); }
92
92
  .oa-clock { flex: none; color: var(--muted); font: 500 var(--fs-sm)/1 var(--sans); font-variant-numeric: tabular-nums; }
93
93
  .oa-now { color: var(--muted); font-size: var(--fs-sm); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -101,7 +101,13 @@
101
101
  .org-extra { border-radius: 18px; border: 1.5px dashed var(--line-2); background: none; padding: 8px; display: flex; flex-direction: column; gap: 8px; width: auto; }
102
102
  .org-extra .org-agent { width: 232px; }
103
103
 
104
- @media (prefers-reduced-motion: reduce) { .oa-wires .run, .org-agent.got, .oa-spin { animation: none; } }
104
+ /* A message between linked teams: a light along their link, and its count pulses. */
105
+ .org-lines .run { fill: none; stroke: var(--coord); stroke-width: 3.5; stroke-linecap: round; stroke-dasharray: 16 100; animation: org-link-run 1.6s cubic-bezier(.4, 0, .2, 1) both; filter: drop-shadow(0 0 4px color-mix(in srgb, var(--coord) 75%, transparent)); }
106
+ @keyframes org-link-run { from { stroke-dashoffset: 16; } to { stroke-dashoffset: -100; } }
107
+ .org-label.got { animation: org-label-got 1.6s ease-out; }
108
+ @keyframes org-label-got { 25%, 55% { transform: translate(-50%, -50%) scale(1.35); box-shadow: 0 0 0 6px color-mix(in srgb, var(--coord) 22%, transparent); } }
109
+
110
+ @media (prefers-reduced-motion: reduce) { .oa-wires .run, .org-agent.got, .oa-spin, .org-lines .run, .org-label.got { animation: none; } }
105
111
 
106
112
  @media (max-width: 900px) {
107
113
  .org-card { width: auto; }
@@ -0,0 +1,60 @@
1
+ /* Usage: what the agents spent, in tokens. The four kinds keep one colour
2
+ each everywhere on the screen (tiles, chart, bars). */
3
+
4
+ #usage { padding: 20px; }
5
+ .u-wrap { display: flex; flex-direction: column; gap: 16px; max-width: 1400px; margin: 0 auto; }
6
+ [data-k="input"] { --k: var(--info); }
7
+ [data-k="cache_write"] { --k: var(--warn); }
8
+ [data-k="cache_read"] { --k: color-mix(in srgb, var(--info) 38%, var(--panel)); }
9
+ [data-k="output"] { --k: var(--coord); }
10
+
11
+ .u-filters { display: flex; flex-wrap: wrap; gap: 8px; }
12
+ .u-filter select { height: 34px; padding: 0 30px 0 12px; border: 1px solid var(--line-2); border-radius: var(--r); background: var(--panel); color: var(--text); font: inherit; font-size: var(--fs-md); }
13
+
14
+ .u-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; }
15
+ .u-tile { display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border: 1px solid var(--line); border-radius: 14px; background: var(--panel); box-shadow: var(--shadow-card); }
16
+ .u-tl { display: inline-flex; align-items: center; gap: 7px; color: var(--muted); font-size: var(--fs-sm); }
17
+ .u-tl i { width: 9px; height: 9px; border-radius: 3px; background: var(--k); }
18
+ .u-tile b { font-size: 26px; font-weight: 650; letter-spacing: -.02em; font-variant-numeric: tabular-nums; }
19
+ .u-tn { color: var(--muted); font-size: var(--fs-xs); }
20
+
21
+ .u-card { padding: 14px 16px 16px; border-radius: 14px; }
22
+ .u-ch { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 12px; }
23
+ .u-ch h2 { margin: 0; font-size: var(--fs-md); font-weight: 600; }
24
+ .u-legend { display: flex; flex-wrap: wrap; gap: 12px; color: var(--muted); font-size: var(--fs-sm); }
25
+ .u-legend span { display: inline-flex; align-items: center; gap: 6px; }
26
+ .u-legend i { width: 9px; height: 9px; border-radius: 3px; background: var(--k); }
27
+
28
+ .u-chart { position: relative; padding: 18px 0 22px; }
29
+ .u-chart svg { display: block; width: 100%; height: 220px; overflow: visible; }
30
+ .u-chart rect[data-k] { fill: var(--k); }
31
+ .u-chart .u-hit { fill: transparent; }
32
+ .u-chart .u-bar:hover rect[data-k] { opacity: .8; }
33
+ .u-max { position: absolute; top: 0; left: 0; color: var(--faint); font-size: var(--fs-xs); font-variant-numeric: tabular-nums; }
34
+ .u-axis { position: relative; height: 16px; margin-top: 6px; color: var(--muted); font-size: var(--fs-xs); }
35
+ .u-axis span { position: absolute; transform: translateX(-50%); white-space: nowrap; }
36
+
37
+ .u-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 420px), 1fr)); gap: 16px; align-items: start; }
38
+ .u-card.wide { grid-column: 1 / -1; }
39
+ .u-rows { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
40
+ .u-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 12px; align-items: center; }
41
+ .u-name { display: flex; align-items: center; gap: 8px; min-width: 0; }
42
+ .u-name .agent { width: 20px; height: 20px; border-radius: 6px; font-size: 10px; flex: none; }
43
+ .u-nt { display: flex; flex-direction: column; min-width: 0; }
44
+ .u-nt b { font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
45
+ .u-nt b a, .u-nt b .linkish { color: var(--text); text-decoration: none; font: inherit; }
46
+ .u-nt b .linkish { padding: 0; border: 0; background: none; cursor: pointer; text-align: left; }
47
+ .u-nt b a:hover, .u-nt b .linkish:hover { text-decoration: underline; text-decoration-color: var(--line-2); text-underline-offset: 3px; }
48
+ .u-nt span { color: var(--muted); font-size: var(--fs-xs); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
49
+ .u-val { font-variant-numeric: tabular-nums; font-weight: 600; white-space: nowrap; }
50
+ .u-val small { margin-left: 6px; color: var(--muted); font-weight: 400; font-size: var(--fs-xs); }
51
+ .u-stack { grid-column: 1 / -1; display: flex; height: 6px; border-radius: 4px; background: var(--tray); overflow: hidden; }
52
+ .u-stack i { display: block; height: 100%; background: var(--k); }
53
+ .u-empty { padding: 60px 20px; }
54
+
55
+ @media (max-width: 900px) {
56
+ #usage { padding: 14px; }
57
+ .u-tiles { grid-template-columns: repeat(2, 1fr); }
58
+ .u-tiles > :first-child { grid-column: 1 / -1; }
59
+ .u-chart svg { height: 160px; }
60
+ }
package/ui/squads.js CHANGED
@@ -8,7 +8,7 @@ import { roleTag } from './topbar.js'
8
8
  import { alertBox } from './mosaic.js'
9
9
  import { dialog } from './dialogs.js'
10
10
  import { terminalOf, postJson, addFolderDialog, renderHosts } from './machines.js'
11
- import { renderOrg } from './org.js'
11
+ import { renderOrg, flashLink } from './org.js'
12
12
 
13
13
  // A worker for this coordinator's squad, by default on the coordinator's machine.
14
14
  // A session opened from here that ended (/quit, closed): open it again on
@@ -144,6 +144,7 @@ export function noteLinkMessage(m) {
144
144
  const l = state.links.find(x => (x.a === m.from && x.b === m.target) || (x.b === m.from && x.a === m.target))
145
145
  if (!l) return
146
146
  l.recent = [m.created_at, ...(l.recent ?? [])].slice(0, 100)
147
+ flashLink(m.from, m.target)
147
148
  if (currentRoute().view === 'org') soon(renderOrg)
148
149
  }
149
150
 
package/ui/stream.js CHANGED
@@ -103,6 +103,7 @@ function onStream(type, data) {
103
103
  if (type === 'plans') {
104
104
  state.plans = new Map((Array.isArray(data) ? data : []).map(p => [p.coordinator, p]))
105
105
  soon(refreshTeam); soon(refreshTeams); soon(refreshTimelines)
106
+ if (currentRoute().view === 'org') soon(renderOrg) // (what each agent is on comes from its coordinator's plan)
106
107
  }
107
108
  if (type === 'inbox') {
108
109
  state.inbox = Array.isArray(data) ? data : []
package/ui/topbar.js CHANGED
@@ -13,6 +13,7 @@ import { orgSquads, orgZoom, linksDialog } from './org.js'
13
13
  import { renderBack } from './back.js'
14
14
  import { voiceButton } from './voice.js'
15
15
  import { boardsHead, boardsTopClick } from './boards.js'
16
+ import { usageHead } from './usage.js'
16
17
 
17
18
  // The terminal a session view shows (null: its chat).
18
19
  // (An observer has no terminals: its chat instead.)
@@ -63,6 +64,11 @@ function renderHead() {
63
64
  setHtml($('topRight'), voiceButton())
64
65
  return
65
66
  }
67
+ if (r.view === 'usage') {
68
+ const h = usageHead()
69
+ setHtml($('topTitle'), h.title); setHtml($('topTabs'), h.tabs); setHtml($('topRight'), h.right)
70
+ return
71
+ }
66
72
  if (r.view === 'boards' || r.view === 'board') {
67
73
  // (Its subtitle, how many boards or tasks, is the board's own: see renderBoards.)
68
74
  const h = boardsHead(r)
package/ui/usage.js ADDED
@@ -0,0 +1,175 @@
1
+ import { $, store } from './dom.js'
2
+ import { T, LOCALE, COLLATOR } from './i18n.js'
3
+ import { state, companyPref } from './state.js'
4
+ import { esc } from './format.js'
5
+ import { api } from './api.js'
6
+ import { setHtml, soon } from './nav.js'
7
+ import { currentRoute } from './router.js'
8
+ import { agentMark } from './content.js'
9
+
10
+ // What the agents spent, in tokens: a period, filters, the totals, the
11
+ // spending over time, and by team, what started it, task, session and model.
12
+ // Read from /api/usage (kept by the hour on the server); counts only.
13
+ const KINDS = ['input', 'cache_write', 'cache_read', 'output']
14
+ const RANGES = { today: 0, d7: 7, d30: 30, d90: 90 }
15
+ const HOUR = 3600_000, DAY = 24 * HOUR
16
+ const COMPACT = new Intl.NumberFormat(LOCALE, { notation: 'compact', maximumFractionDigits: 1 })
17
+ const FULL = new Intl.NumberFormat(LOCALE)
18
+ const DAY_FMT = new Intl.DateTimeFormat(LOCALE, { day: 'numeric', month: 'short' })
19
+ const HOUR_FMT = new Intl.DateTimeFormat(LOCALE, { hour: '2-digit', minute: '2-digit', hour12: false })
20
+
21
+ let view = { range: store.get(companyPref('pishaUsageRange')) ?? 'd7', team: '', agent: '', model: '' }
22
+ let data = null, loading = 0, timer = null
23
+
24
+ const total = r => r.input + r.cache_read + r.cache_write + r.output
25
+ const num = n => COMPACT.format(n)
26
+ const period = () => {
27
+ const now = Date.now()
28
+ if (view.range === 'today') { const d = new Date(); d.setHours(0, 0, 0, 0); return { from: d.getTime(), to: now, bucket: 'hour' } }
29
+ return { from: now - (RANGES[view.range] ?? 7) * DAY, to: now, bucket: 'day' }
30
+ }
31
+
32
+ async function load() {
33
+ const seq = ++loading
34
+ const p = period()
35
+ const q = new URLSearchParams({ from: p.from, to: p.to, bucket: p.bucket, tz: -new Date().getTimezoneOffset() })
36
+ for (const k of ['team', 'agent', 'model']) if (view[k]) q.set(k, view[k])
37
+ try {
38
+ const r = await api(`/api/usage?${q}`)
39
+ if (seq !== loading) return
40
+ data = r
41
+ } catch (err) { if (seq === loading) data = { error: err.message } }
42
+ if (currentRoute().view === 'usage') draw()
43
+ }
44
+
45
+ export function renderUsage() {
46
+ if (!data) setHtml($('usage'), `<div class="u-wrap"><p class="dim-note">${esc(T.usageLoading)}</p></div>`)
47
+ void load()
48
+ clearInterval(timer)
49
+ // (While it is open: what is being spent now shows up within a minute.)
50
+ timer = setInterval(() => { if (currentRoute().view === 'usage' && !$('usage').hidden) void load(); else clearInterval(timer) }, 60_000)
51
+ }
52
+
53
+ // The header: the period, and the export.
54
+ export function usageHead() {
55
+ const seg = Object.keys(RANGES).map(k => `<button type="button" data-urange="${k}" class="${view.range === k ? 'on' : ''}" aria-pressed="${view.range === k}">${esc(T.usageRanges[k])}</button>`).join('')
56
+ return { title: esc(T.usage), tabs: `<span class="seg" role="group" aria-label="${esc(T.usagePeriod)}">${seg}</span>`, right: `<button type="button" class="btn" data-uexport>${esc(T.usageExport)}</button>` }
57
+ }
58
+
59
+ const teamName = t => (t ? state.squadMeta.get(t)?.title || t : T.usageNoTeam)
60
+
61
+ function draw() {
62
+ const box = $('usage')
63
+ if (data?.error) { setHtml(box, `<div class="u-wrap"><p class="err">${esc(data.error)}</p></div>`); return }
64
+ const d = data
65
+ const opts = (k, list, label, name = x => x) => `<label class="u-filter"><span class="sr-only">${esc(label)}</span><select data-ufilter="${k}"><option value="">${esc(label)}</option>${list.map(v => `<option value="${esc(v)}"${view[k] === v ? ' selected' : ''}>${esc(name(v))}</option>`).join('')}</select></label>`
66
+ const teams = [...new Set([...(view.team ? [view.team] : []), ...d.by.team.map(r => r.team).filter(Boolean)])].sort((a, b) => COLLATOR.compare(teamName(a), teamName(b)))
67
+ const agents = [...new Set([...(view.agent ? [view.agent] : []), ...d.by.agent.map(r => r.agent)])]
68
+ const models = [...new Set([...(view.model ? [view.model] : []), ...d.by.model.map(r => r.model).filter(Boolean)])]
69
+ const filters = `<div class="u-filters">${opts('team', teams, T.usageAllTeams, teamName)}${opts('agent', agents, T.usageAllAgents, a => T.agentName[a] ?? a)}${opts('model', models, T.usageAllModels)}</div>`
70
+ const t = d.totals, all = total(t)
71
+ if (!all) {
72
+ setHtml(box, `<div class="u-wrap">${filters}<div class="empty u-empty"><b>${esc(T.usageEmpty)}</b><span>${esc(T.usageEmptyHint)}</span></div></div>`)
73
+ return
74
+ }
75
+ const inAll = t.input + t.cache_read + t.cache_write
76
+ const cached = inAll ? Math.round(t.cache_read / inAll * 100) : 0
77
+ const tile = (k, label, value, note = '') => `<div class="u-tile"${k ? ` data-k="${k}"` : ''}><span class="u-tl">${k ? '<i aria-hidden="true"></i>' : ''}${esc(label)}</span><b title="${esc(FULL.format(value))}">${esc(num(value))}</b>${note ? `<span class="u-tn">${esc(note)}</span>` : ''}</div>`
78
+ const tiles = `<div class="u-tiles">
79
+ ${tile('', T.usageTotal, all, T.usageCalls(t.calls))}
80
+ ${tile('input', T.usageKinds.input, t.input)}
81
+ ${tile('output', T.usageKinds.output, t.output)}
82
+ ${tile('cache_read', T.usageKinds.cache_read, t.cache_read, T.usageCached(cached))}
83
+ ${tile('cache_write', T.usageKinds.cache_write, t.cache_write)}
84
+ </div>`
85
+ setHtml(box, `<div class="u-wrap">${filters}${tiles}
86
+ <section class="card u-card"><header class="u-ch"><h2>${esc(T.usageOverTime)}</h2>${legend()}</header>${chart(d)}</section>
87
+ <div class="u-grid">
88
+ ${breakdown(T.usageByTeam, d.by.team.map(r => ({ ...r, label: teamName(r.team), key: r.team })), 'team')}
89
+ ${breakdown(T.usageByCause, d.by.cause.map(r => ({ ...r, label: T.usageCauses[r.cause] ?? r.cause, hint: T.usageCauseHints[r.cause] ?? '' })))}
90
+ ${breakdown(T.usageByTask, d.by.task.filter(r => r.task).map(r => ({ ...r, label: r.task, href: taskHref(r.task) })), '', T.usageNoTasks)}
91
+ ${breakdown(T.usageByModel, d.by.model.map(r => ({ ...r, label: r.model || '?' })))}
92
+ ${breakdown(T.usageBySession, d.by.session.map(r => ({ ...r, label: r.session, sub: [teamName(r.team), T.roleName[r.role] ?? r.role].filter(Boolean).join(' · '), lead: agentMark({ agent: r.agent }), href: `#/s/${encodeURIComponent(r.session)}` })), '', '', true)}
93
+ </div>
94
+ </div>`)
95
+ }
96
+
97
+ const legend = () => `<span class="u-legend">${KINDS.map(k => `<span data-k="${k}"><i aria-hidden="true"></i>${esc(T.usageKinds[k])}</span>`).join('')}</span>`
98
+
99
+ // Stacked bars, one per hour or day of the period (empty ones too).
100
+ function chart(d) {
101
+ const p = period(), step = d.bucket === 'hour' ? HOUR : DAY
102
+ const start = d.bucket === 'hour' ? Math.floor(p.from / HOUR) * HOUR : (() => { const x = new Date(p.from); x.setHours(0, 0, 0, 0); return x.getTime() })()
103
+ const byT = new Map(d.series.map(s => [s.t, s]))
104
+ const buckets = []
105
+ for (let x = start; x <= p.to; x += step) {
106
+ // (Days by the calendar: a day with a clock change isn't 24 h.)
107
+ const key = d.bucket === 'hour' ? x : [...byT.keys()].find(k => Math.abs(k - x) < 3 * HOUR) ?? x
108
+ buckets.push({ t: x, ...(byT.get(key) ?? { input: 0, cache_read: 0, cache_write: 0, output: 0, calls: 0 }) })
109
+ if (d.bucket === 'day') { const n = new Date(x); n.setDate(n.getDate() + 1); x = n.getTime() - step }
110
+ }
111
+ const max = Math.max(1, ...buckets.map(total))
112
+ const W = 1000, H = 220, gap = buckets.length > 40 ? 1 : 3, bw = (W - gap * (buckets.length - 1)) / buckets.length
113
+ const fmt = d.bucket === 'hour' ? HOUR_FMT : DAY_FMT
114
+ const bars = buckets.map((b, i) => {
115
+ let y = H
116
+ const x = i * (bw + gap)
117
+ const parts = KINDS.map(k => { const h = b[k] / max * H; y -= h; return h > 0 ? `<rect data-k="${k}" x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${bw.toFixed(1)}" height="${h.toFixed(1)}"/>` : '' }).join('')
118
+ const tip = `${fmt.format(b.t)}: ${FULL.format(total(b))} · ${KINDS.map(k => `${T.usageKinds[k]} ${num(b[k])}`).join(' · ')}`
119
+ return `<g class="u-bar"><title>${esc(tip)}</title><rect class="u-hit" x="${x.toFixed(1)}" y="0" width="${bw.toFixed(1)}" height="${H}"/>${parts}</g>`
120
+ }).join('')
121
+ const every = Math.ceil(buckets.length / 8)
122
+ const labels = buckets.map((b, i) => (i % every ? '' : `<span style="left:${((i * (bw + gap) + bw / 2) / W * 100).toFixed(2)}%">${esc(fmt.format(b.t))}</span>`)).join('')
123
+ return `<div class="u-chart"><span class="u-max">${esc(num(max))}</span><svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="${esc(T.usageOverTime)}">${bars}</svg><div class="u-axis">${labels}</div></div>`
124
+ }
125
+
126
+ // One breakdown: a row per item with its share of the period and its kinds.
127
+ function breakdown(title, rows, filterKey = '', empty = '', wide = false) {
128
+ const max = Math.max(1, ...rows.map(total))
129
+ const sumAll = rows.reduce((n, r) => n + total(r), 0) || 1
130
+ const row = r => {
131
+ const name = r.href ? `<a href="${esc(r.href)}">${esc(r.label)}</a>` : filterKey && r.key ? `<button type="button" class="linkish" data-ufilter-set="${filterKey}" data-v="${esc(r.key)}">${esc(r.label)}</button>` : esc(r.label)
132
+ const bar = KINDS.map(k => (r[k] ? `<i data-k="${k}" style="width:${(r[k] / max * 100).toFixed(2)}%"></i>` : '')).join('')
133
+ return `<li class="u-row"${r.hint ? ` title="${esc(r.hint)}"` : ''}>
134
+ <span class="u-name">${r.lead ?? ''}<span class="u-nt"><b>${name}</b>${r.sub ? `<span>${esc(r.sub)}</span>` : ''}</span></span>
135
+ <span class="u-val" title="${esc(FULL.format(total(r)))} · ${esc(T.usageCalls(r.calls))}">${esc(num(total(r)))}<small>${Math.round(total(r) / sumAll * 100)}%</small></span>
136
+ <span class="u-stack">${bar}</span>
137
+ </li>`
138
+ }
139
+ return `<section class="card u-card${wide ? ' wide' : ''}"><header class="u-ch"><h2>${esc(title)}</h2></header>${rows.length ? `<ul class="u-rows">${rows.slice(0, 50).map(row).join('')}</ul>` : `<p class="dim-note">${esc(empty)}</p>`}</section>`
140
+ }
141
+
142
+ // A task's link: on the board it is on (the dashboard's first open one).
143
+ const taskHref = id => {
144
+ const b = state.boards.find(x => !x.archived_at) ?? state.boards[0]
145
+ return b ? `#/b/${b.id}/${encodeURIComponent(id)}` : ''
146
+ }
147
+
148
+ // The period's spending as CSV: by session, day or hour, with every column.
149
+ function exportCsv() {
150
+ if (!data?.by) return
151
+ const cell = v => (/[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v))
152
+ const head = ['session', 'team', 'role', 'agent', ...KINDS, 'total', 'calls']
153
+ const lines = [head.join(','), ...data.by.session.map(r => [r.session, r.team, r.role, r.agent, ...KINDS.map(k => r[k]), total(r), r.calls].map(cell).join(','))]
154
+ const a = document.createElement('a')
155
+ a.href = URL.createObjectURL(new Blob([lines.join('\n') + '\n'], { type: 'text/csv' }))
156
+ a.download = `pisha-usage-${new Date(data.from).toISOString().slice(0, 10)}-${new Date(data.to).toISOString().slice(0, 10)}.csv`
157
+ a.click()
158
+ setTimeout(() => URL.revokeObjectURL(a.href), 1000)
159
+ }
160
+
161
+ // Clicks and choices on the screen and in its header.
162
+ document.addEventListener('click', e => {
163
+ if (currentRoute().view !== 'usage') return
164
+ const r = e.target.closest('[data-urange]')
165
+ if (r) { view.range = r.dataset.urange; store.set(companyPref('pishaUsageRange'), view.range); soon(async () => (await import('./topbar.js')).renderTop()); void load(); return }
166
+ if (e.target.closest('[data-uexport]')) return exportCsv()
167
+ const f = e.target.closest('[data-ufilter-set]')
168
+ if (f) { view[f.dataset.ufilterSet] = f.dataset.v; void load() }
169
+ })
170
+ document.addEventListener('change', e => {
171
+ const f = e.target.closest?.('[data-ufilter]')
172
+ if (!f || currentRoute().view !== 'usage') return
173
+ view[f.dataset.ufilter] = f.value
174
+ void load()
175
+ })
package/usage/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createUsage, CAUSES } from './usage.js'
package/usage/usage.js ADDED
@@ -0,0 +1,127 @@
1
+ import { now, bad } from '../platform/index.js'
2
+
3
+ // What the agents spend, in tokens: each session's plugin reports its model
4
+ // calls (observation events of kind "tokens", see plugins/pisha/observe.js),
5
+ // and they are kept added up by the hour, with what each one was spent on:
6
+ // the session, its team and role then, its agent and model, what started the
7
+ // turn (the user, its coordinator, a linked team, the board…) and the board
8
+ // task it was about. Only counts, never what was said.
9
+ export const CAUSES = ['user', 'inbox', 'coordinator', 'worker', 'link', 'board', 'system', 'other', 'self']
10
+ const KINDS = ['input', 'cache_read', 'cache_write', 'output']
11
+ const HOUR = 3600_000
12
+ const DAY = 24 * HOUR
13
+
14
+ export function createUsage(platform, { sessions, boards }) {
15
+ const { db, bus, quota, log } = platform
16
+ db.exec(`
17
+ CREATE TABLE IF NOT EXISTS token_usage (
18
+ hour INTEGER NOT NULL, session TEXT NOT NULL, team TEXT NOT NULL DEFAULT '', role TEXT NOT NULL DEFAULT '',
19
+ agent TEXT NOT NULL DEFAULT 'claude', model TEXT NOT NULL DEFAULT '', cause TEXT NOT NULL DEFAULT 'self',
20
+ task TEXT NOT NULL DEFAULT '', sub INTEGER NOT NULL DEFAULT 0,
21
+ input INTEGER NOT NULL DEFAULT 0, cache_read INTEGER NOT NULL DEFAULT 0, cache_write INTEGER NOT NULL DEFAULT 0,
22
+ output INTEGER NOT NULL DEFAULT 0, calls INTEGER NOT NULL DEFAULT 0,
23
+ PRIMARY KEY (hour, session, team, role, agent, model, cause, task, sub)
24
+ );
25
+ CREATE INDEX IF NOT EXISTS token_usage_hour ON token_usage(hour);
26
+ `)
27
+ const keptMs = () => quota('usage_days', 400) * DAY
28
+
29
+ // Who a session is now: its role, team (a coordinator's own name, a
30
+ // worker's coordinator) and agent. (Until it first logs in, what it was opened as.)
31
+ function whoIs(name) {
32
+ const r = db.prepare('SELECT role, coordinator, agent, opened_role, opened_coordinator, host_id FROM identities WHERE name = ?').get(name)
33
+ if (!r) return { role: '', team: '', agent: 'claude' }
34
+ const role = r.role ?? (r.host_id ? r.opened_role : null) ?? ''
35
+ const team = role === 'coordinator' ? name : role === 'worker' ? (r.role ? r.coordinator : r.opened_coordinator) ?? '' : ''
36
+ return { role, team, agent: r.agent ?? 'claude' }
37
+ }
38
+
39
+ // What started a turn, from the message it began with: its sender as seen
40
+ // from this session (its coordinator, one of its workers, a linked team).
41
+ function causeOf(name, ev) {
42
+ if (ev.cause === 'user' || ev.cause === 'inbox' || ev.cause === 'self') return ev.cause
43
+ if (ev.cause === 'board') return 'board'
44
+ if (ev.cause === 'notice') return 'system'
45
+ if (ev.cause !== 'message' || !Number.isSafeInteger(ev.msg)) return 'other'
46
+ const m = db.prepare('SELECT from_name, target, system FROM messages WHERE id = ?').get(ev.msg)
47
+ if (!m) return 'other'
48
+ if (m.from_name === boards.BOARD_SENDER) return 'board'
49
+ if (m.system) return 'system'
50
+ const me = whoIs(name), them = whoIs(m.from_name)
51
+ if (me.role === 'worker' && me.team === m.from_name) return 'coordinator'
52
+ if (them.role === 'worker' && them.team === name) return 'worker'
53
+ if (me.role === 'coordinator' && them.role === 'coordinator' && sessions.linked(name, m.from_name)) return 'link'
54
+ return 'other'
55
+ }
56
+
57
+ const add = db.prepare(`INSERT INTO token_usage (hour, session, team, role, agent, model, cause, task, sub, input, cache_read, cache_write, output, calls)
58
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
59
+ ON CONFLICT(hour, session, team, role, agent, model, cause, task, sub) DO UPDATE SET
60
+ input = input + excluded.input, cache_read = cache_read + excluded.cache_read, cache_write = cache_write + excluded.cache_write,
61
+ output = output + excluded.output, calls = calls + excluded.calls`)
62
+
63
+ // A batch of model calls from one session (already checked by observation).
64
+ function record(name, list) {
65
+ const who = whoIs(name)
66
+ for (const ev of list) {
67
+ const counts = KINDS.map(k => ev[k] ?? 0)
68
+ if (!counts.some(n => n > 0)) continue
69
+ const task = typeof ev.task === 'string' ? boards.taskIn(ev.task) ?? '' : ''
70
+ try {
71
+ add.run(Math.floor(ev.ts / HOUR) * HOUR, name, who.team, who.role, who.agent, ev.model ?? '', causeOf(name, ev), task, ev.sub ? 1 : 0, ...counts, ev.calls || 1)
72
+ } catch (err) { log(`token usage of "${name}" not kept: ${err.message}`) }
73
+ }
74
+ }
75
+ bus.on('tokens', record)
76
+
77
+ function cleanupUsage() {
78
+ db.prepare('DELETE FROM token_usage WHERE hour < ?').run(now() - keptMs())
79
+ }
80
+
81
+ // --- the dashboard's read ------------------------------------------------------
82
+
83
+ const sum = (a, r) => { for (const k of [...KINDS, 'calls']) a[k] = (a[k] ?? 0) + r[k]; return a }
84
+ const zero = () => ({ input: 0, cache_read: 0, cache_write: 0, output: 0, calls: 0 })
85
+ const DIMENSIONS = ['team', 'session', 'cause', 'task', 'model', 'agent', 'role']
86
+
87
+ // From/to in ms (to excluded), by hour or by day in the viewer's time zone
88
+ // (tz: minutes east of UTC), filtered by team, session, agent or model.
89
+ // Totals, the series, and the totals by each dimension.
90
+ function usage(q) {
91
+ const to = Number(q.get('to')) || now()
92
+ const from = Number(q.get('from')) || to - 7 * DAY
93
+ if (!(from < to) || to - from > 400 * DAY) throw bad('from must be before to, at most 400 days apart')
94
+ const bucket = q.get('bucket') === 'hour' ? 'hour' : 'day'
95
+ const tz = Math.max(-840, Math.min(840, Number(q.get('tz')) || 0)) * 60_000
96
+ const where = ['hour >= ?', 'hour < ?'], args = [Math.floor(from / HOUR) * HOUR, to]
97
+ for (const k of ['team', 'session', 'agent', 'model', 'cause']) {
98
+ const v = q.get(k)
99
+ if (v != null && v !== '') { where.push(`${k} = ?`); args.push(String(v).slice(0, 200)) }
100
+ }
101
+ const rows = db.prepare(`SELECT * FROM token_usage WHERE ${where.join(' AND ')}`).all(...args)
102
+ const totals = zero(), series = new Map(), by = Object.fromEntries(DIMENSIONS.map(d => [d, new Map()]))
103
+ for (const r of rows) {
104
+ sum(totals, r)
105
+ const t = bucket === 'hour' ? r.hour : Math.floor((r.hour + tz) / DAY) * DAY - tz
106
+ sum(series.get(t) ?? series.set(t, zero()).get(t), r)
107
+ for (const d of DIMENSIONS) {
108
+ const key = d === 'session' ? `${r.session}\u0000${r.team}\u0000${r.role}\u0000${r.agent}` : String(r[d] ?? '')
109
+ const m = by[d]
110
+ sum(m.get(key) ?? m.set(key, zero()).get(key), r)
111
+ }
112
+ }
113
+ const total = r => r.input + r.cache_read + r.cache_write + r.output
114
+ const list = (d, m) => [...m].map(([key, v]) => {
115
+ if (d !== 'session') return { [d]: key, ...v }
116
+ const [session, team, role, agent] = key.split('\u0000')
117
+ return { session, team, role, agent, ...v }
118
+ }).sort((a, b) => total(b) - total(a))
119
+ return {
120
+ from, to, bucket, totals,
121
+ series: [...series].sort((a, b) => a[0] - b[0]).map(([t, v]) => ({ t, ...v })),
122
+ by: Object.fromEntries(DIMENSIONS.map(d => [d, list(d, by[d])])),
123
+ }
124
+ }
125
+
126
+ return { usageReads: { usage }, cleanupUsage, record }
127
+ }