-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
4625 lines (4332 loc) · 199 KB
/
Copy pathplugin.js
File metadata and controls
4625 lines (4332 loc) · 199 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Ledgerline: live cost and session intelligence for Hermes Desktop.
*
* One file, loaded uncompiled by the desktop's disk plugin door. Three rules
* keep it loadable on every desktop build:
*
* 1. Import the SDK as a namespace. The runtime shim exports
* `export const { a, b } = m`, so a named import of a member an older SDK
* lacks is a link-time SyntaxError for the whole file. Newer members are
* read off `sdk.*` behind a feature check instead.
* 2. Everything between the pure markers has no imports and receives its
* dependencies as arguments (`host`, `bridge`, `sdk`). Tests load that
* slice under node and pass fakes. UI and registration live below it.
* 3. No hardcoded colours, no polling faster than 30 s, no writes to the
* gateway host outside Hermes' own commands.
*
* Module map:
* capabilities what this desktop / gateway can do, probed once
* data rpc / coreRest / cli adapters with typed errors, plus the
* session reads and analysis rungs built on them
* sessions pure shaping: normalize rows, filter, sort, format
* true cost parent plus children, receipt lines, live estimate
* ui React components built from the SDK kit
* register contributions (page, nav, palette, keybind, statusbar chip)
*/
import * as sdk from '@hermes/plugin-sdk'
import { useEffect, useMemo, useRef, useState } from 'react'
import { jsx, jsxs } from 'react/jsx-runtime'
/* @ledgerline:pure-start */
const PLUGIN_ID = 'ledgerline'
const PLUGIN_NAME = 'Ledgerline'
const ROUTE = '/ledgerline'
const VERSION = '0.1.4'
const PAGE_SIZE = 100
const KNOWN_ROWS_CAP = 1000
// Enough daily rows to cover the 1st of a 31-day month on its 31st.
const MONTH_DAYS = 31
const WHATIF_MIN_USD = 0.05
const MESSAGE_PAGE = 500
const MESSAGE_PAGES = 6
// Parent + children + grandchildren. Deeper chains stop here.
const TREE_DEPTH = 3
// ---------------------------------------------------------------------------
// errors
//
// Every adapter throws a LedgerlineError so the UI can branch on `kind` and
// `code` without string matching. `kind` is where it came from, `code` is the
// most specific machine-readable reason we have.
// ---------------------------------------------------------------------------
class LedgerlineError extends Error {
constructor(kind, code, message, cause) {
super(message)
this.name = 'LedgerlineError'
this.kind = kind // 'rpc' | 'rest' | 'cli'
this.code = code // number for JSON-RPC, string otherwise
this.cause = cause
}
}
// ---------------------------------------------------------------------------
// capabilities
//
// Interface: describeCapabilities({ sdk, host, bridge }) -> Capabilities
// Sync, pure, no I/O. Answers "which doors exist on this desktop build".
// Backend-side facts (is core REST reachable, backend version) are async and
// live in the data layer's probeBackend().
// ---------------------------------------------------------------------------
function describeCapabilities({ sdk, host, bridge }) {
const has = (obj, key) => !!obj && typeof obj[key] === 'function'
return {
openWorkspace: has(host, 'openWorkspace'),
paneVisibility: has(host, 'paneVisibility'),
profileRoutes: has(host, 'profileRoutes'),
activeConnectionId: has(host, 'activeConnectionId'),
openSession: has(host, 'openSession'),
requestProfile: has(host, 'requestProfile'),
usePluginI18n: has(sdk, 'usePluginI18n'),
compactNumber: has(sdk, 'compactNumber'),
streamdown: !!(sdk && sdk.Streamdown),
bridgeApi: has(bridge, 'api'),
bridgeVersion: has(bridge, 'getVersion')
}
}
// ---------------------------------------------------------------------------
// data
//
// Interface: createDataLayer({ host, bridge }) -> {
// rpc(method, params) -> result | throws LedgerlineError('rpc', code)
// coreRest(path, opts) -> json | throws LedgerlineError('rest', code)
// cli(argv, { timeout }) -> { code, output } | throws LedgerlineError('cli', code)
// probeBackend() -> BackendProbe, never throws
// listSessions({ pages, order, archived }) -> { rows: Session[], total, source: 'rest' | 'rpc' }
// }
//
// coreRest is the one door outside the SDK contract: the desktop's own
// bridge, the same function ctx.rest calls one line deeper. If it is
// missing, coreRest throws 'bridge-missing' and callers fall back to RPC
// where one exists.
// ---------------------------------------------------------------------------
function createDataLayer({ host, bridge }) {
async function rpc(method, params = {}, route = null) {
const useRoute = !!(route && host && typeof host.requestProfile === 'function')
if (!host || (useRoute ? typeof host.requestProfile !== 'function' : typeof host.request !== 'function')) {
throw new LedgerlineError('rpc', useRoute ? 'route-missing' : 'host-missing', useRoute ? 'host.requestProfile is unavailable' : 'host.request is unavailable')
}
try {
return useRoute ? await host.requestProfile(route, method, params) : await host.request(method, params)
} catch (error) {
const code = error && typeof error.code === 'number' ? error.code : 'rpc-failed'
throw new LedgerlineError('rpc', code, (error && error.message) || String(error), error)
}
}
async function coreRest(path, opts = {}) {
if (!bridge || typeof bridge.api !== 'function') {
throw new LedgerlineError('rest', 'bridge-missing', 'desktop bridge unavailable')
}
if (typeof path !== 'string' || !path.startsWith('/api/')) {
throw new LedgerlineError('rest', 'bad-path', `coreRest path must start with /api/: ${path}`)
}
try {
const request = {
path,
method: opts.method,
body: opts.body,
timeoutMs: opts.timeoutMs
}
// Route to a profile's own backend, the way the desktop does for the
// profile the live gateway is on. Only set when the caller asks.
if (opts.profile) request.profile = opts.profile
return await bridge.api(request)
} catch (error) {
const message = (error && error.message) || String(error)
const code = /\b404\b/.test(message) ? 'not-found' : /\b40[13]\b/.test(message) ? 'unauthorized' : 'rest-failed'
throw new LedgerlineError('rest', code, message, error)
}
}
async function cli(argv, opts = {}) {
const result = await rpc('cli.exec', { argv, timeout: opts.timeout || 60 })
if (result && result.blocked) {
throw new LedgerlineError('cli', 'blocked', result.hint || 'command blocked by the gateway')
}
return { code: result ? result.code : -1, output: result ? result.output : '' }
}
// BackendProbe = {
// gateway: { ok, version, releaseDate, hermesHome, error }
// coreRest: { ok, code }
// cliExec: { ok, code }
// }
async function probeBackend() {
const probe = {
gateway: { ok: false, version: '', releaseDate: '', hermesHome: '', error: '' },
coreRest: { ok: false, code: '' },
cliExec: { ok: false, code: '' }
}
try {
const status = host && typeof host.status === 'function' ? await host.status() : null
probe.gateway = {
ok: !!status,
version: (status && status.version) || '',
releaseDate: (status && status.release_date) || '',
hermesHome: (status && status.hermes_home) || '',
error: status ? '' : 'host.status unavailable'
}
} catch (error) {
probe.gateway.error = (error && error.message) || String(error)
}
try {
await coreRest('/api/status', { timeoutMs: 8000 })
probe.coreRest = { ok: true, code: '' }
} catch (error) {
probe.coreRest = { ok: false, code: error.code || 'rest-failed' }
}
try {
const r = await cli(['version'], { timeout: 30 })
probe.cliExec = { ok: r.code === 0, code: r.code === 0 ? '' : `exit-${r.code}` }
} catch (error) {
probe.cliExec = { ok: false, code: error.code || 'cli-failed' }
}
return probe
}
// A Scope says whose data a read is about:
// { kind: 'active', profile } the profile the live gateway is on
// { kind: 'profile', profile } one named profile, read from disk by the primary
// { kind: 'all' } every profile the primary can see
// scopeRest() turns it into the query suffix and bridge options a route needs.
function scopeRest(scope) {
const sc = scope || { kind: 'active', profile: '' }
if (sc.kind === 'profile' && sc.profile) return { query: `&profile=${encodeURIComponent(sc.profile)}`, opts: {} }
if (sc.kind === 'active' && sc.profile && sc.profile !== 'default') return { query: '', opts: { profile: sc.profile } }
return { query: '', opts: {} }
}
// Sessions come from core REST when it answers (rows carry tokens and cost)
// and from the session.list RPC otherwise (rows carry neither). `pages` is
// how many PAGE_SIZE pages to fetch from the top of the list. Under the
// 'all' scope the unified cross-profile route is used and rows carry
// their profile.
async function listSessions({ pages = 1, order = 'recent', archived = 'exclude', scope } = {}) {
const sc = scope || { kind: 'active', profile: '' }
try {
const results = await Promise.all(
Array.from({ length: pages }, (_, i) => {
if (sc.kind === 'all') {
return coreRest(`/api/profiles/sessions?limit=${PAGE_SIZE}&offset=${i * PAGE_SIZE}&order=${order}&archived=${archived}&min_messages=1&profile=all`, { timeoutMs: 30000 })
}
const { query, opts } = scopeRest(sc)
return coreRest(`/api/sessions?limit=${PAGE_SIZE}&offset=${i * PAGE_SIZE}&order=${order}&archived=${archived}&min_messages=1${query}`, { timeoutMs: 20000, ...opts })
})
)
const rows = results.flatMap(r => (r && Array.isArray(r.sessions) ? r.sessions : [])).map(r => normalizeRestSession(r, sc.kind === 'profile' ? sc.profile : ''))
const total = results.length && typeof results[0].total === 'number' ? results[0].total : rows.length
return { rows, total, source: 'rest' }
} catch (error) {
if (!(error instanceof LedgerlineError) || error.kind !== 'rest') throw error
const r = await rpc('session.list', { limit: pages * PAGE_SIZE, ...(sc.kind === 'profile' && sc.profile ? { profile: sc.profile } : {}) })
const rows = (r && Array.isArray(r.sessions) ? r.sessions : []).map(normalizeRpcSession)
// session.list has no cross-profile form: under the all-profiles
// scope this is the active profile only, and the caller must say so.
return { rows, total: rows.length, source: 'rpc', scopeLost: sc.kind === 'all' }
}
}
// Profile names the gateway knows, cheapest form (no per-profile session probe).
async function listProfiles() {
const r = await rpc('profiles.list', { include_sessions: false })
const rows = r && Array.isArray(r.profiles) ? r.profiles : Array.isArray(r) ? r : []
return rows.map(p => ({ name: String(p.name || ''), displayName: String(p.display_name || p.name || ''), isDefault: !!p.is_default, model: p.model || '' })).filter(p => p.name)
}
// One stored session by id, same shape as a list row. REST only.
async function getSession(id, scope) {
const { query, opts } = scopeRest(scope)
const row = await coreRest(`/api/sessions/${encodeURIComponent(id)}?full=0${query}`, { timeoutMs: 15000, ...opts })
return normalizeRestSession(row, scope && scope.kind === 'profile' ? scope.profile : '')
}
// Every message row of a session in order, walking REST pages of
// MESSAGE_PAGE rows up to MESSAGE_PAGES pages. Returns { messages, truncated }.
async function getMessages(id, scope) {
const { query, opts } = scopeRest(scope)
const messages = []
for (let page = 0; page < MESSAGE_PAGES; page++) {
const r = await coreRest(
`/api/sessions/${encodeURIComponent(id)}/messages?limit=${MESSAGE_PAGE}&offset=${page * MESSAGE_PAGE}&order=oldest${query}`,
{ timeoutMs: 20000, ...opts }
)
const rows = r && Array.isArray(r.messages) ? r.messages : []
messages.push(...rows)
if (rows.length < MESSAGE_PAGE) return { messages, truncated: false }
}
// Every page came back full: there may be more rows we did not read.
return { messages, truncated: true }
}
// Full-text search over message content, one hit per session lineage.
// -> [{ id, title, source, model, profile, startedAt, snippet }]
function mapSearchHit(x, fallbackProfile = '') {
return {
id: String(x.id || x.session_id || ''),
title: x.title || '',
source: x.source || '',
model: x.model || '',
profile: String(x.profile || fallbackProfile || ''),
startedAt: num(x.started_at) || num(x.session_started),
snippet: String(x.snippet || '').replace(/>>>/g, '“').replace(/<<</g, '”')
}
}
async function searchOne(q, limit, scope) {
const sr = scopeRest(scope)
const r = await coreRest(`/api/sessions/search?q=${encodeURIComponent(q)}&limit=${limit}${sr.query}`, { timeoutMs: 20000, ...sr.opts })
const fallback = scope && scope.kind === 'profile' ? scope.profile : ''
return (r && Array.isArray(r.results) ? r.results : []).map(x => mapSearchHit(x, fallback))
}
async function searchSessions(query, limit = 25, scope) {
const q = String(query || '').trim()
if (!q) return []
const sc = scope || { kind: 'active', profile: '' }
if (sc.kind === 'all') {
const profiles = await listProfiles()
const parts = await Promise.all(
profiles.map(async p => {
try {
return await searchOne(q, limit, { kind: 'profile', profile: p.name })
} catch {
return []
}
})
)
return mergeSearchHits(parts, limit)
}
return searchOne(q, limit, sc)
}
// Usage analytics for the last `days` days, from the gateway's own
// aggregation over sessions and session_model_usage. REST only.
// /api/analytics/usage has no per-model cache reads, /api/analytics/models
// does, so the second call fills that column in. It is best effort: if it
// fails the rows just have no cacheRead and what-ifs price input only.
async function fetchAnalytics(d, query, opts) {
const [raw, models] = await Promise.all([
coreRest(`/api/analytics/usage?days=${d}${query}`, { timeoutMs: 30000, ...opts }),
coreRest(`/api/analytics/models?days=${d}${query}`, { timeoutMs: 30000, ...opts }).catch(() => null)
])
return normalizeAnalytics(raw, d, models)
}
async function getAnalytics(days = 30, scope) {
const d = Math.max(1, Math.min(365, Math.floor(days)))
const sc = scope || { kind: 'active', profile: '' }
if (sc.kind === 'all') {
const profiles = await listProfiles()
const parts = await Promise.all(
profiles.map(async p => {
try {
return { profile: p.name, analytics: await fetchAnalytics(d, `&profile=${encodeURIComponent(p.name)}`, {}) }
} catch {
return { profile: p.name, analytics: null }
}
})
)
return mergeAnalytics(parts, d)
}
const { query, opts } = scopeRest(sc)
return fetchAnalytics(d, query, opts)
}
// Messaging targets the gateway can send to right now, from `hermes send
// --list --json` on the gateway host. -> [{ platform, target, label }]
async function listSendTargets() {
const r = await cli(['send', '--list', '--json'], { timeout: 60 })
return parseSendTargets(r.output)
}
// Send a plain message through a configured platform. No model involved.
async function sendMessage(target, message) {
const r = await cli(['send', '--to', target, '--json', message], { timeout: 60 })
if (r.code !== 0) throw new LedgerlineError('cli', `exit-${r.code}`, (r.output || '').slice(0, 300) || 'hermes send failed')
return r
}
// Cron delivery targets with home-channel state. REST first, else derived
// from the send list.
async function listDeliveryTargets() {
try {
const r = await coreRest('/api/cron/delivery-targets', { timeoutMs: 15000 })
return (r && Array.isArray(r.targets) ? r.targets : []).map(t => ({ id: String(t.id || ''), name: String(t.name || t.id || ''), homeSet: t.home_target_set !== false }))
} catch (error) {
if (!(error instanceof LedgerlineError) || error.kind !== 'rest') throw error
const targets = await listSendTargets()
const platforms = Array.from(new Set(targets.map(t => t.platform)))
return [{ id: 'local', name: 'Local (save only)', homeSet: true }, ...platforms.map(pl => ({ id: pl, name: pl, homeSet: true }))]
}
}
// Scheduled jobs from the gateway's cron store, ours flagged.
async function listCronJobs() {
const r = await rpc('cron.manage', { action: 'list', include_disabled: true })
const jobs = r && Array.isArray(r.jobs) ? r.jobs : []
return jobs.map(normalizeCronJob)
}
// Create a job with a delivery target. REST carries `deliver`; the RPC does
// not, so the CLI is the fallback.
async function createCronJob({ name, schedule, prompt, deliver }) {
try {
const r = await coreRest('/api/cron/jobs', { method: 'POST', body: { name, schedule, prompt, deliver }, timeoutMs: 20000 })
return normalizeCronJob(r && r.job ? r.job : r)
} catch (error) {
if (!(error instanceof LedgerlineError) || error.kind !== 'rest') throw error
const r = await cli(['cron', 'create', schedule, prompt, '--name', name, '--deliver', deliver], { timeout: 60 })
if (r.code !== 0) throw new LedgerlineError('cli', `exit-${r.code}`, (r.output || '').slice(0, 300) || 'hermes cron create failed')
return { name, schedule, deliver, created: true }
}
}
async function cronAction(action, jobId) {
return rpc('cron.manage', { action, name: jobId })
}
return {
rpc,
coreRest,
cli,
probeBackend,
listSessions,
getSession,
getMessages,
getAnalytics,
listProfiles,
searchSessions,
listSendTargets,
sendMessage,
listDeliveryTargets,
listCronJobs,
createCronJob,
cronAction,
quickExplain,
fullAudit,
backgroundAudit
}
async function quickExplain(digest, route) {
const r = await rpc(
'llm.oneshot',
{
instructions: EXPLAIN_INSTRUCTIONS,
input: wrapDigest(digest),
max_tokens: 800,
temperature: 0.2
},
route
)
return (r && r.text) || ''
}
async function fullAudit(session, digest, route) {
const created = await rpc(
'session.create',
{
title: `Audit: ${sessionLabel(session).slice(0, 60)}`,
messages: [{ role: 'system', content: wrapDigest(digest) }]
},
route
)
const runtimeId = created && created.session_id
if (!runtimeId) throw new LedgerlineError('rpc', 'no-session', 'session.create returned no session id')
await rpc('prompt.submit', { session_id: runtimeId, text: auditPrompt(session.id) }, route)
return { runtimeId, storedId: (created && created.stored_session_id) || '' }
}
async function backgroundAudit(session, digest, liveId, route) {
if (!liveId) throw new LedgerlineError('rpc', 'no-live', 'no live focused session')
const r = await rpc('prompt.background', { session_id: liveId, text: `${auditPrompt(session.id)}\n\n${wrapDigest(digest)}` }, route)
return { taskId: (r && r.task_id) || '', runtimeId: liveId }
}
}
// ---------------------------------------------------------------------------
// mode
//
// Interface: resolveMode(capabilities, backendProbe) -> 'full' | 'rpc-only'
// One place decides how much of the UI is on. Everything else reads the mode.
// ---------------------------------------------------------------------------
function resolveMode(capabilities, probe) {
return capabilities.bridgeApi && probe && probe.coreRest && probe.coreRest.ok ? 'full' : 'rpc-only'
}
function pickRoute(routes, { profile, connectionId }) {
const conn = connectionId || 'local'
const matches = (routes || []).filter(r => (r.profile || '') === profile && (r.connectionId || 'local') === conn)
return matches.length === 1 ? { ...matches[0] } : null
}
function routeStillHeld(routes, route) {
if (!route) return false
return !!pickRoute(routes, { profile: route.profile, connectionId: route.connectionId })
}
function mergeKnownRows(prev, prevScope, incoming, nextScope, cap) {
const next = incoming || []
if (prevScope !== nextScope) return { rows: next.slice(0, cap), scope: nextScope }
const seen = new Set(next.map(r => r.id))
const kept = (prev || []).filter(r => r && r.id && !seen.has(r.id)).slice(0, cap)
return { rows: next.concat(kept).slice(0, cap), scope: nextScope }
}
function mergeSearchHits(parts, limit) {
const seen = new Set()
const out = []
for (const hit of (parts || []).flat()) {
if (!hit || !hit.id || seen.has(hit.id)) continue
seen.add(hit.id)
out.push(hit)
if (out.length >= limit) break
}
return out
}
// ---------------------------------------------------------------------------
// sessions
//
// One Session shape for the whole UI, whatever the row came from:
// { id, title, preview, source, model, startedAt, endedAt, lastActive,
// messageCount, toolCalls, apiCalls, tokens: { input, output, cacheRead,
// cacheWrite, reasoning }, cost: { estimated, actual, status }, hasUsage,
// parentId, cwd, isActive, pinned, archived }
// `hasUsage` is false for RPC rows, which carry no token or cost columns.
// ---------------------------------------------------------------------------
const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
const numOrNull = v => (typeof v === 'number' && Number.isFinite(v) ? v : null)
function normalizeRestSession(row, fallbackProfile = '') {
const r = row || {}
return {
id: String(r.id || ''),
profile: String(r.profile || fallbackProfile || ''),
title: r.title || '',
preview: r.preview || '',
source: r.source || '',
model: r.model || '',
startedAt: num(r.started_at),
endedAt: numOrNull(r.ended_at),
lastActive: num(r.last_active) || num(r.last_activity_at) || num(r.started_at),
messageCount: num(r.message_count),
toolCalls: num(r.tool_call_count),
apiCalls: num(r.api_call_count),
tokens: {
input: num(r.input_tokens),
output: num(r.output_tokens),
cacheRead: num(r.cache_read_tokens),
cacheWrite: num(r.cache_write_tokens),
reasoning: num(r.reasoning_tokens)
},
cost: {
estimated: numOrNull(r.estimated_cost_usd),
actual: numOrNull(r.actual_cost_usd),
status: r.cost_status || ''
},
hasUsage: true,
parentId: r.parent_session_id || null,
cwd: r.cwd || '',
isActive: !!r.is_active,
pinned: !!r.pinned,
archived: !!r.archived
}
}
function normalizeRpcSession(row) {
const r = row || {}
return {
id: String(r.id || ''),
profile: '',
title: r.title || '',
preview: r.preview || '',
source: r.source || '',
model: '',
startedAt: num(r.started_at),
endedAt: null,
lastActive: num(r.started_at),
messageCount: num(r.message_count),
toolCalls: 0,
apiCalls: 0,
tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 },
cost: { estimated: null, actual: null, status: '' },
hasUsage: false,
parentId: null,
cwd: '',
isActive: false,
pinned: false,
archived: false
}
}
// Spend to show: billed if the provider reported it (including $0), else
// the estimate. A subscription-included route with no billed amount is $0.
// Unknown pricing stays null so it never reads as free.
function sessionCost(session) {
const c = session.cost || {}
if (c.actual !== null && c.actual !== undefined) return c.actual
if (c.estimated) return c.estimated
if (c.status === 'included') return 0
return null
}
// Cache hit rate over prompt tokens: reads served from cache divided by all
// prompt tokens (fresh input plus cache reads). null when nothing was sent.
// Share of prompt tokens served from cache. Cache writes count as prompt
// tokens too (Anthropic bills them at 1.25x input), so a session that writes
// its whole context every call is not a 99% hit just because plain input is
// tiny. The analytics route has no write column, so rates built from it
// (daily bars, fallbacks) are reads over input plus reads only.
function cacheHitRate(tokens) {
const t = tokens || {}
const prompt = num(t.input) + num(t.cacheRead) + num(t.cacheWrite)
return prompt > 0 ? num(t.cacheRead) / prompt : null
}
// Cache hit rate over the session rows that started inside the window,
// grouped by profile when asked. Rows carry cache writes, analytics do not,
// so this is the figure the Overview shows when rows are available.
function rowsCacheRate(rows, days, now = Date.now(), profile = null) {
const since = now / 1000 - days * 86400
const acc = { input: 0, cacheRead: 0, cacheWrite: 0 }
let n = 0
for (const r of rows || []) {
if (!r || !r.hasUsage || num(r.startedAt) < since) continue
if (profile !== null && (r.profile || '') !== profile) continue
acc.input += num(r.tokens && r.tokens.input)
acc.cacheRead += num(r.tokens && r.tokens.cacheRead)
acc.cacheWrite += num(r.tokens && r.tokens.cacheWrite)
n++
}
return n ? cacheHitRate(acc) : null
}
function sameModel(a, b) {
const x = String(a || ''), y = String(b || '')
return !!x && !!y && (x === y || x.endsWith(`/${y}`) || y.endsWith(`/${x}`))
}
// Cache writes for one model over the window, summed from the session rows
// (the analytics routes have no write column). `partial` is true when the
// rows we hold do not reach back to the start of the window, so the sum is
// a floor, not the total.
// `expected` is the session count the analytics row reports for the model;
// when fewer rows matched (child sessions are not in the list), the sum is
// also a floor.
function modelRowWrites(rows, days, model, now = Date.now(), expected = 0) {
const since = now / 1000 - days * 86400
let writes = 0
let matched = 0
let oldest = Infinity
for (const r of rows || []) {
if (!r || !r.hasUsage) continue
if (num(r.startedAt) < oldest) oldest = num(r.startedAt)
if (num(r.startedAt) < since || !sameModel(r.model, model)) continue
writes += num(r.tokens && r.tokens.cacheWrite)
matched++
}
return { writes, partial: ((rows || []).length > 0 && oldest > since) || matched < num(expected) }
}
// Tooltip text for a by-model row: the token split, the recorded cost, and
// when the gateway lists prices for the model, the split in dollars at list
// price (cache writes at 1.25x input, the Anthropic convention, marked est).
function modelRowTip(row, writes, rates) {
const parts = [
`${fmtCount(row.input)} input`,
`${fmtCount(row.cacheRead)} cache read`,
writes.writes ? `${writes.partial ? '\u2265' : ''}${fmtCount(writes.writes)} cache write` : null,
`${fmtCount(row.output)} output`
].filter(Boolean)
const lines = [parts.join(' \u00b7 '), `recorded ${fmtUsd(row.estimated)}`]
const key = Object.keys(rates || {}).find(k => sameModel(k, row.model))
const r = key ? rates[key] : null
if (r && (r.input || r.output)) {
const cacheRate = r.cache === null || r.cache === undefined ? r.input : r.cache
const split = [
`input ${fmtUsd(row.input * r.input)}`,
`cache read ${fmtUsd(num(row.cacheRead) * cacheRate)}`,
writes.writes ? `cache write ${fmtUsd(writes.writes * r.input * 1.25)} est` : null,
`output ${fmtUsd(row.output * r.output)}`
].filter(Boolean)
lines.push(`at list price: ${split.join(', ')}`)
}
return lines.join(' \u2014 ')
}
function tokenTotal(tokens) {
const t = tokens || {}
return num(t.input) + num(t.output) + num(t.cacheRead) + num(t.cacheWrite) + num(t.reasoning)
}
function sessionLabel(session) {
if (session.title) return session.title
if (session.preview) return session.preview.slice(0, 60)
if (session.parentId) return 'Subagent'
return session.id.slice(0, 12)
}
function durationSeconds(session) {
const end = session.endedAt || session.lastActive || session.startedAt
return Math.max(0, num(end) - num(session.startedAt))
}
// filters = { query, source, model, hasCost }
function filterSessions(rows, filters = {}) {
const q = (filters.query || '').trim().toLowerCase()
return rows.filter(s => {
if (filters.source && s.source !== filters.source) return false
if (filters.model && s.model !== filters.model) return false
if (filters.hasCost && sessionCost(s) === null) return false
if (q && !(s.title.toLowerCase().includes(q) || s.id.toLowerCase().includes(q) || s.preview.toLowerCase().includes(q))) {
return false
}
return true
})
}
// sort = 'recent' | 'costliest' | 'tokens' | 'tools'
// `index` is childIndex(rows). Costliest ranks by list-tree true cost.
function sortSessions(rows, sort = 'recent', index) {
const copy = rows.slice()
const tree = index || (sort === 'costliest' ? childIndex(rows) : null)
const by = fn => copy.sort((a, b) => fn(b) - fn(a) || b.lastActive - a.lastActive)
if (sort === 'costliest') return by(s => listTreeCost({ session: s, index: tree }) || 0)
if (sort === 'tokens') return by(s => tokenTotal(s.tokens))
if (sort === 'tools') return by(s => s.toolCalls)
return by(s => s.lastActive)
}
function distinct(rows, key) {
const seen = new Set()
for (const r of rows) if (r[key]) seen.add(r[key])
return Array.from(seen).sort()
}
// ---------------------------------------------------------------------------
// format
// ---------------------------------------------------------------------------
function fmtUsd(value) {
if (value === null || value === undefined) return 'n/a'
const v = Number(value)
if (!Number.isFinite(v)) return 'n/a'
if (v === 0) return '$0.00'
if (v < 0.0001) return '<$0.0001'
if (v < 0.01) return `$${v.toFixed(4)}`
if (v < 1) return `$${v.toFixed(3)}`
return `$${v.toFixed(2)}`
}
function localDayKey(date) {
const d = date instanceof Date ? date : new Date(date)
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}-${m}-${day}`
}
// One row per calendar day in the window so a short history still
// occupies the full tape instead of four lonely bars.
function fillDailyRange(daily, days, now = new Date()) {
const map = new Map((daily || []).map(d => [String(d.day || ''), d]))
const out = []
const n = Math.max(1, num(days) || 30)
const end = new Date(now.getFullYear(), now.getMonth(), now.getDate())
for (let i = n - 1; i >= 0; i--) {
const d = new Date(end.getFullYear(), end.getMonth(), end.getDate() - i)
const key = localDayKey(d)
const row = map.get(key)
out.push(
row || { day: key, actual: 0, estimated: 0, input: 0, cacheRead: 0, output: 0, sessions: 0 }
)
}
return out
}
function fmtCount(value) {
const v = num(value)
if (v < 1000) return String(v)
if (v < 1_000_000) return `${(v / 1000).toFixed(v < 10_000 ? 1 : 0)}k`
return `${(v / 1_000_000).toFixed(1)}M`
}
function fmtPct(ratio) {
if (ratio === null || ratio === undefined) return 'n/a'
return `${Math.round(ratio * 100)}%`
}
function fmtDuration(seconds) {
const s = Math.max(0, Math.round(num(seconds)))
if (s < 60) return `${s}s`
if (s < 3600) return `${Math.round(s / 60)}m`
return `${(s / 3600).toFixed(1)}h`
}
function fmtWhen(epochSeconds, now = Date.now() / 1000) {
const ts = num(epochSeconds)
if (!ts) return ''
const diff = Math.max(0, now - ts)
if (diff < 60) return 'just now'
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`
if (diff < 7 * 86400) return `${Math.floor(diff / 86400)}d ago`
const d = new Date(ts * 1000)
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}
// ---------------------------------------------------------------------------
// analysis
//
// Interface: analyzeMessages(messages) -> Analysis
// Pure. Takes raw message rows (role, content, tool_calls, tool_call_id,
// tool_name, timestamp) and returns everything the detail view shows:
// { calls, breakdown, failures, files, subagents, about, summary, counts }
// classifyToolResult() follows the rules the Hermes CLI itself uses to mark a
// tool line red, but splits the weakest rule (a bare "error" substring) into
// its own 'suspected' verdict so false positives never count as failures.
// ---------------------------------------------------------------------------
const FILE_TOOLS = new Set(['read_file', 'write_file', 'patch', 'search_files'])
const WRITE_TOOLS = new Set(['write_file', 'patch'])
const ARTIFACT_TOOLS = new Set(['image_generate', 'text_to_speech'])
const ABOUT_SKIP = ['[ASYNC DELEGATION', '[CONTEXT COMPACTION', '[System']
function safeJson(text) {
if (typeof text !== 'string') return null
const t = text.trim()
if (!t.startsWith('{') && !t.startsWith('[')) return null
try {
return JSON.parse(t)
} catch {
return null
}
}
function trimError(message, max = 120) {
const m = String(message || '').trim().replace(/\s+/g, ' ')
return m.length > max ? `${m.slice(0, max - 1)}…` : m
}
// -> { verdict: 'ok' | 'failed' | 'suspected', error }
function classifyToolResult(name, result) {
if (result === null || result === undefined) return { verdict: 'ok', error: '' }
const text = typeof result === 'string' ? result : null
const data = text !== null ? safeJson(text) : typeof result === 'object' ? result : null
const isObj = !!data && typeof data === 'object' && !Array.isArray(data)
if (isObj && !data.error) {
if (name === 'write_file' && 'bytes_written' in data) return { verdict: 'ok', error: '' }
if (name === 'patch' && data.success === true) return { verdict: 'ok', error: '' }
}
if (name === 'terminal') {
if (isObj && data.exit_code !== null && data.exit_code !== undefined && data.exit_code !== 0) {
return { verdict: 'failed', error: data.error ? trimError(data.error) : `exit ${data.exit_code}` }
}
return { verdict: 'ok', error: '' }
}
if (name === 'memory' && isObj && data.success === false && String(data.error || '').includes('exceed the limit')) {
return { verdict: 'failed', error: 'memory store full' }
}
if (isObj) {
const err = data.error || data.message
if (err && (data.success === false || data.error)) return { verdict: 'failed', error: trimError(err) }
}
if (text === null) return { verdict: 'ok', error: '' }
const lower = text.slice(0, 500).toLowerCase()
if (lower.includes('"error"') || lower.includes('"failed"') || text.startsWith('Error')) {
return { verdict: 'suspected', error: trimError(text.split('\n')[0]) }
}
return { verdict: 'ok', error: '' }
}
function parseArgs(raw) {
if (raw && typeof raw === 'object') return raw
if (typeof raw !== 'string' || !raw) return {}
const parsed = safeJson(raw)
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : { raw }
}
function filePathOf(name, args) {
if (FILE_TOOLS.has(name)) return args.path || args.file_path || args.workdir || ''
if (ARTIFACT_TOOLS.has(name)) {
const p = args.output_path || args.image_url || ''
return typeof p === 'string' && (p.startsWith('/') || p.startsWith('~') || /^[A-Za-z]:[\\/]/.test(p)) ? p : ''
}
return ''
}
// One line that says what a call did: the command, the path, the query.
// Falls back to the first short string arguments, so unknown tools still
// read as something rather than "{...}".
function callSummary(name, args) {
const a = args && typeof args === 'object' ? args : {}
const str = v => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim() : '')
const pick = (...keys) => {
for (const k of keys) if (str(a[k])) return str(a[k])
return ''
}
let out = ''
if (name === 'terminal' || name === 'process') out = pick('command', 'cmd', 'input')
else if (FILE_TOOLS.has(name)) {
const path = pick('path', 'file_path', 'workdir')
const pattern = pick('pattern', 'query')
out = name === 'search_files' ? `${pattern}${path ? ` in ${path}` : ''}` : path
} else if (name === 'web_search' || name === 'web_extract' || name === 'browser_navigate') out = pick('query', 'url', 'urls')
else if (name === 'delegate_task') {
const tasks = Array.isArray(a.tasks) ? a.tasks.map(x => str(x && x.goal)).filter(Boolean) : []
out = tasks.length ? `${tasks.length} tasks: ${tasks.join(' | ')}` : pick('goal')
} else if (name === 'session_search' || name === 'memory' || name === 'skills_list' || name === 'skill_view') out = pick('query', 'content', 'name', 'action')
if (!out) {
out = Object.values(a)
.filter(v => typeof v === 'string' && v.length <= 120)
.map(str)
.filter(Boolean)
.slice(0, 3)
.join(' · ')
}
return out.length > 160 ? `${out.slice(0, 157)}...` : out
}
// Child session id from a delegate_task result row or a live subagent
// payload. `subagent_id` is a delegation key, not a session id, so it
// is left out. Empty string when nothing matches.
function pickChildSessionId(entry) {
if (!entry || typeof entry !== 'object') return ''
const keys = ['child_session_id', 'session_id', 'stored_session_id', 'stored_id', 'childSessionId', 'sessionId']
for (const k of keys) {
const v = entry[k]
if (typeof v === 'string' && v.trim()) return v.trim()
}
const nested = entry.session
if (nested && typeof nested === 'object') {
const inner = pickChildSessionId(nested)
if (inner) return inner
}
return ''
}
// delegate_task results carry one entry per child; goals live in the call args.
function subagentsFromCall(call) {
const data = safeJson(typeof call.result === 'string' ? call.result : '') || (call.result && typeof call.result === 'object' ? call.result : null)
if (!data) return []
const entries = Array.isArray(data.results) ? data.results : data.status || data.summary ? [data] : []
const tasks = Array.isArray(call.args.tasks) ? call.args.tasks : null
return entries.map((e, i) => {
const goalFromTask = tasks && tasks[typeof e.task_index === 'number' ? e.task_index : i]
return {
goal: (goalFromTask && goalFromTask.goal) || call.args.goal || '',
status: e.status || 'unknown',
summary: typeof e.summary === 'string' ? e.summary.slice(0, 400) : '',
model: e.model || '',
apiCalls: num(e.api_calls),
durationSeconds: num(e.duration_seconds),
tokens: { input: num(e.tokens && e.tokens.input), output: num(e.tokens && e.tokens.output) },
costUsd: numOrNull(e.cost_usd),
costStatus: e.cost_status || '',
error: e.error ? trimError(e.error) : '',
childId: pickChildSessionId(e),
dispatchedAt: call.timestamp
}
})
}
function analyzeMessages(messages) {
const rows = Array.isArray(messages) ? messages : []
const resultsById = new Map()
for (const m of rows) {
if (m && m.role === 'tool' && m.tool_call_id) resultsById.set(m.tool_call_id, m)
}
const calls = []
let about = ''
for (const m of rows) {
if (!m) continue
if (!about && m.role === 'user' && typeof m.content === 'string') {
const c = m.content.trim()
if (c && !ABOUT_SKIP.some(p => c.startsWith(p))) about = c.slice(0, 400)
}
if (m.role !== 'assistant' || !Array.isArray(m.tool_calls)) continue
for (const tc of m.tool_calls) {
if (!tc) continue
const fn = tc.function || {}
const name = fn.name || tc.name || 'unknown'
const id = tc.id || ''
const resultRow = id ? resultsById.get(id) : null
const result = resultRow ? resultRow.content : null
const { verdict, error } = classifyToolResult(name, result)
calls.push({
id,
name,
args: parseArgs(fn.arguments !== undefined ? fn.arguments : tc.arguments),
timestamp: num(m.timestamp),
result,
verdict,
error
})
}
}
const byName = new Map()
for (const c of calls) {
const b = byName.get(c.name) || { name: c.name, count: 0, failed: 0, suspected: 0 }
b.count += 1
if (c.verdict === 'failed') b.failed += 1
if (c.verdict === 'suspected') b.suspected += 1
byName.set(c.name, b)
}
const breakdown = Array.from(byName.values()).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name))
const byPath = new Map()
for (const c of calls) {
const path = filePathOf(c.name, c.args)
if (!path) continue
const f = byPath.get(path) || { path, reads: 0, writes: 0, tools: [], artifact: false }
if (WRITE_TOOLS.has(c.name) || ARTIFACT_TOOLS.has(c.name)) f.writes += 1
else f.reads += 1
if (ARTIFACT_TOOLS.has(c.name)) f.artifact = true