pisha-server 0.0.0-stage → 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.
Files changed (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/accounts/accounts.js +754 -0
  4. package/accounts/index.js +1 -0
  5. package/accounts/passwords.js +41 -0
  6. package/accounts/totp.js +54 -0
  7. package/boards/boards.js +1087 -0
  8. package/boards/github.js +212 -0
  9. package/boards/index.js +1 -0
  10. package/boards/sync.js +980 -0
  11. package/companies.js +294 -0
  12. package/company-export.js +101 -0
  13. package/company.js +82 -0
  14. package/dashboard/dashboard.js +408 -0
  15. package/dashboard/index.js +1 -0
  16. package/data-upgrade.js +69 -0
  17. package/install/linux.sh +181 -0
  18. package/install/macos.sh +121 -0
  19. package/install/windows.bat +54 -0
  20. package/machines/index.js +3 -0
  21. package/machines/machines.js +910 -0
  22. package/messaging/inbox.js +252 -0
  23. package/messaging/index.js +3 -0
  24. package/messaging/messaging.js +551 -0
  25. package/messaging/plans.js +67 -0
  26. package/observation/index.js +1 -0
  27. package/observation/observation.js +231 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +55 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3303 -0
  34. package/pisha-host.mjs.sig +1 -0
  35. package/platform/acme.js +207 -0
  36. package/platform/basics.js +14 -0
  37. package/platform/config.js +154 -0
  38. package/platform/control.js +93 -0
  39. package/platform/credentials.js +151 -0
  40. package/platform/database.js +251 -0
  41. package/platform/errors.js +13 -0
  42. package/platform/files.js +50 -0
  43. package/platform/http.js +207 -0
  44. package/platform/index.js +58 -0
  45. package/platform/limits.js +122 -0
  46. package/platform/listen.js +183 -0
  47. package/platform/roles.js +6 -0
  48. package/platform/stream.js +19 -0
  49. package/platform/text.js +83 -0
  50. package/platform/ws.js +186 -0
  51. package/routes.js +405 -0
  52. package/server.js +65 -0
  53. package/sessions/index.js +1 -0
  54. package/sessions/sessions.js +533 -0
  55. package/ui/LICENSE-affectui.txt +26 -0
  56. package/ui/addmachine.js +151 -0
  57. package/ui/api.js +20 -0
  58. package/ui/app.js +143 -0
  59. package/ui/attention.js +78 -0
  60. package/ui/back.js +168 -0
  61. package/ui/boards.js +958 -0
  62. package/ui/chat.js +388 -0
  63. package/ui/content.js +157 -0
  64. package/ui/dialogs.js +135 -0
  65. package/ui/doing.js +112 -0
  66. package/ui/dom.js +6 -0
  67. package/ui/ds-base.css +146 -0
  68. package/ui/ds-components.css +229 -0
  69. package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
  70. package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
  71. package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  72. package/ui/format.js +25 -0
  73. package/ui/i18n.js +2145 -0
  74. package/ui/icons/apple-touch-icon.png +0 -0
  75. package/ui/icons/icon-192.png +0 -0
  76. package/ui/icons/icon-512.png +0 -0
  77. package/ui/icons/maskable-512.png +0 -0
  78. package/ui/icons.js +41 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +105 -0
  81. package/ui/machines.js +261 -0
  82. package/ui/manifest.webmanifest +16 -0
  83. package/ui/mosaic.js +189 -0
  84. package/ui/nav.js +142 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +669 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +180 -0
  89. package/ui/people.js +371 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +173 -0
  93. package/ui/routes.js +47 -0
  94. package/ui/screen-boards.css +241 -0
  95. package/ui/screen-inbox.css +201 -0
  96. package/ui/screen-machines.css +76 -0
  97. package/ui/screen-mosaic.css +26 -0
  98. package/ui/screen-newteam.css +90 -0
  99. package/ui/screen-org.css +119 -0
  100. package/ui/screen-session.css +99 -0
  101. package/ui/screen-signin.css +28 -0
  102. package/ui/screen-team.css +80 -0
  103. package/ui/screen-teams.css +41 -0
  104. package/ui/screen-usage.css +60 -0
  105. package/ui/session.js +42 -0
  106. package/ui/shell.css +122 -0
  107. package/ui/signin.js +120 -0
  108. package/ui/squads.js +371 -0
  109. package/ui/state.js +59 -0
  110. package/ui/stream.js +269 -0
  111. package/ui/styles.css +343 -0
  112. package/ui/team.js +115 -0
  113. package/ui/teams.js +58 -0
  114. package/ui/terminal.js +261 -0
  115. package/ui/theme.js +32 -0
  116. package/ui/timeline.js +163 -0
  117. package/ui/topbar.js +211 -0
  118. package/ui/usage.js +175 -0
  119. package/ui/voice-parse.js +98 -0
  120. package/ui/voice.js +320 -0
  121. package/usage/index.js +1 -0
  122. package/usage/usage.js +127 -0
  123. package/vendor/InterVariable.woff2 +0 -0
  124. package/vendor/LICENSE-inter +92 -0
  125. package/vendor/LICENSE-xterm +21 -0
  126. package/vendor/README.md +8 -0
  127. package/vendor/addon-fit.js +2 -0
  128. package/vendor/xterm.css +218 -0
  129. package/vendor/xterm.js +2 -0
package/ui/topbar.js ADDED
@@ -0,0 +1,211 @@
1
+ import { $, store } from './dom.js'
2
+ import { T } from './i18n.js'
3
+ import { sessions, state, linksOf, hosts, can } from './state.js'
4
+ import { esc, kfmt } from './format.js'
5
+ import { sortedSessions, status, agentMark } from './content.js'
6
+ import { setHtml } from './nav.js'
7
+ import { currentRoute } from './router.js'
8
+ import { applyCols, buildMosaic } from './mosaic.js'
9
+ import { runAction, openMenu } from './dialogs.js'
10
+ import { terminalOf, hostLine, hostAction } from './machines.js'
11
+ import { reopenable, reopen, addWorkerTo, saveTemplateDialog } from './squads.js'
12
+ import { orgSquads, orgZoom, linksDialog } from './org.js'
13
+ import { renderBack } from './back.js'
14
+ import { voiceButton } from './voice.js'
15
+ import { boardsHead, boardsTopClick } from './boards.js'
16
+ import { usageHead } from './usage.js'
17
+
18
+ // The terminal a session view shows (null: its chat).
19
+ // (An observer has no terminals: its chat instead.)
20
+ export const sessionTerm = r => (r.view === 'session' && !r.chat && state.role !== 'observer' ? terminalOf(r.name) : null)
21
+
22
+ // The Pisha session behind a machine's terminal: only one that machine
23
+ // opened (a machine could list any name; it can't make it its own).
24
+ export function sessionOn(hostId, term) {
25
+ const s = sessions.get(term)
26
+ return s && s.host_id === hostId ? s : null
27
+ }
28
+
29
+ export function roleTag(role) {
30
+ return role ? `<span class="role-tag ${role}">${role === 'coordinator' ? T.roleCoordinator : role === 'solo' ? T.roleSolo : T.roleWorker}</span>` : ''
31
+ }
32
+
33
+ // A task's final report (done, blocked, failed, question), or information
34
+ // that needs none (fyi), on a message.
35
+ export function msgTag(it) {
36
+ if (['done', 'blocked', 'failed', 'question'].includes(it.report)) return ` <span class="rep ${it.report}">${T.reportTag[it.report]}</span>`
37
+ return it.fyi ? ` <span class="rep fyi">${T.fyiTag}</span>` : ''
38
+ }
39
+
40
+ // The persona (skill or agent) a session follows.
41
+ export function personaTag(p) {
42
+ return p?.name ? `<span class="persona-tag" title="${esc(`${p.kind === 'agent' ? T.personaAgent : T.personaSkill} ${p.name}${p.description ? ` — ${p.description}` : ''}`)}">${esc(p.name)}</span>` : ''
43
+ }
44
+
45
+ // Teams can be seen three ways: every session, the coordinators with their
46
+ // teams, or the org chart.
47
+ const teamsSeg = view => `<nav class="seg" aria-label="${esc(T.teams)}">${[['teams', '#/teams', T.viewList], ['org', '#/org', T.org], ['mosaic', '#/mosaic', T.viewMosaic]]
48
+ .map(([v, href, label]) => `<a href="${href}"${v === view ? ' class="on" aria-current="page"' : ''}>${esc(label)}</a>`).join('')}</nav>`
49
+
50
+ export function renderTop() {
51
+ renderHead()
52
+ renderBack()
53
+ }
54
+
55
+ function renderHead() {
56
+ const r = currentRoute()
57
+ // (Only the teams views and the inbox have a selector; a squad's own view is
58
+ // one team. The inbox's, with its counts, is its own: see renderInbox.)
59
+ if (!['org', 'teams', 'inbox'].includes(r.view) && !(r.view === 'mosaic' && !r.squad)) setHtml($('topTabs'), '')
60
+ if (r.view === 'inbox') {
61
+ // (Its subtitle, how many wait on you, is the inbox's own: see renderInbox.)
62
+ setHtml($('topTitle'), esc(T.inbox))
63
+ // (Hands-free: what waits on you, read aloud and answered by voice.)
64
+ setHtml($('topRight'), voiceButton())
65
+ return
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
+ }
72
+ if (r.view === 'boards' || r.view === 'board') {
73
+ // (Its subtitle, how many boards or tasks, is the board's own: see renderBoards.)
74
+ const h = boardsHead(r)
75
+ setHtml($('topTitle'), h.title); setHtml($('topTabs'), h.tabs); setHtml($('topRight'), h.right)
76
+ return
77
+ }
78
+ if (r.view === 'teams') {
79
+ // (Its subtitle, how many teams and sessions, is the list's own: see renderTeams.)
80
+ setHtml($('topTitle'), esc(T.teams)); setHtml($('topTabs'), teamsSeg('teams'))
81
+ setHtml($('topRight'), can('operator') ? `<button class="btn primary" data-newteam>${esc(T.newTeam)}</button>` : '')
82
+ return
83
+ }
84
+ if (r.view === 'addmachine') {
85
+ setHtml($('topTitle'), esc(T.addTitle))
86
+ $('topSub').textContent = ''
87
+ setHtml($('topRight'), `<a class="btn plain" href="#/hosts" data-amcancel data-back>${esc(T.cancel)}</a>`)
88
+ return
89
+ }
90
+ if (r.view === 'newteam') {
91
+ setHtml($('topTitle'), esc(T.newTeam))
92
+ $('topSub').textContent = ''
93
+ setHtml($('topRight'), `<a class="btn plain" href="#/teams" data-back>${esc(T.cancel)}</a>`)
94
+ return
95
+ }
96
+ if (r.view === 'team') {
97
+ const name = r.squad
98
+ const meta = state.squadMeta.get(name)
99
+ // (Its subtitle, who is connected, is the page's own: see renderTeam.)
100
+ setHtml($('topTitle'), esc(meta?.title || name))
101
+ setHtml($('topRight'), `<a class="btn wide-only" href="#/q/${encodeURIComponent(name)}/live">${esc(T.tqLive)}</a>${can('operator') ? `<button class="btn" data-addworker="${esc(name)}">${esc(T.tqAddWorker)}</button>` : ''}<a class="btn primary" href="#/s/${encodeURIComponent(name)}">${esc(T.tqGiveOrder)}</a>`)
102
+ return
103
+ }
104
+ if (r.view === 'org') {
105
+ const { squads } = orgSquads()
106
+ setHtml($('topTitle'), esc(T.teams)); setHtml($('topTabs'), teamsSeg('org'))
107
+ $('topSub').textContent = T.orgSub(squads.length, squads.reduce((t, q) => t + 1 + q.workers.length, 0), state.links.length)
108
+ setHtml($('topRight'), `<span class="seg"><button data-orgzoom="-" aria-label="${esc(T.orgZoomOut)}">−</button><button data-orgzoom="1" title="${esc(T.orgZoomReset)}">${Math.round(orgZoom * 100)}%</button><button data-orgzoom="+" aria-label="${esc(T.orgZoomIn)}">+</button></span>${can('manager') ? `<button class="btn" data-orgact="arrange" title="${esc(T.orgArrangeTitle)}">${T.orgArrange}</button>` : ''}${can('operator') ? `<button class="btn primary" data-orgact="newsquad">${T.orgNewSquad}</button>` : ''}`)
109
+ return
110
+ }
111
+ if (r.view === 'leads') {
112
+ const cs = sortedSessions().filter(s => s.role === 'coordinator')
113
+ const ws = sortedSessions().filter(s => s.role !== 'coordinator' && cs.some(c => c.name === s.coordinator))
114
+ setHtml($('topTitle'), esc(T.leads))
115
+ $('topSub').textContent = T.leadsSub(cs.length, ws.length)
116
+ setHtml($('topRight'), `<span class="seg" id="colsSeg" role="group" aria-label="${esc(T.columns)}" title="${esc(T.columns)}">${['auto', '1', '2', '3', '4'].map(n => `<button data-c="${n}" class="${n === state.cols ? 'on' : ''}">${n === 'auto' ? T.auto : n}</button>`).join('')}</span>`)
117
+ return
118
+ }
119
+ if (r.view === 'mosaic') {
120
+ // (Who has no terminals has nothing to choose.)
121
+ const modeSeg = !can('operator') ? '' : `<span class="seg" id="modeSeg">${['terms', 'chats'].map(m => `<button data-mode="${m}" class="${m === state.mosaicMode ? 'on' : ''}">${m === 'terms' ? T.modeTerms : T.modeChats}</button>`).join('')}</span>`
122
+ const colsSeg = `${modeSeg}<span class="seg" id="colsSeg" role="group" aria-label="${esc(T.columns)}" title="${esc(T.columns)}">${['auto', '2', '3', '4', '5', '6'].map(n => `<button data-c="${n}" class="${n === state.cols ? 'on' : ''}">${n === 'auto' ? T.auto : n}</button>`).join('')}</span>`
123
+ if (r.squad) {
124
+ const c = sessions.get(r.squad)
125
+ const ws = sortedSessions().filter(s => s.role !== 'coordinator' && s.coordinator === r.squad)
126
+ setHtml($('topTitle'), esc(T.tqLiveTitle(state.squadMeta.get(r.squad)?.title || r.squad)))
127
+ const linked = linksOf(r.squad)
128
+ $('topSub').textContent = [T.squadCount(ws.filter(w => w.online).length, ws.length), linked.length ? T.linkedWith(linked.join(', ')) : ''].filter(Boolean).join(' · ')
129
+ setHtml($('topRight'), `${colsSeg}${can('operator') ? `<button class="btn" data-addworker="${esc(r.squad)}">${esc(T.addWorker)}</button>` : ''}`)
130
+ return
131
+ }
132
+ setHtml($('topTitle'), esc(T.teams)); setHtml($('topTabs'), teamsSeg('mosaic'))
133
+ $('topSub').textContent = ''
134
+ setHtml($('topRight'), colsSeg)
135
+ } else if (r.view === 'hosts') {
136
+ const h = r.host && hosts.get(r.host)
137
+ const all = [...hosts.values()]
138
+ setHtml($('topTitle'), h ? `<span class="dot ${h.online ? 'ok' : 'off'}" aria-hidden="true"></span>${esc(h.name)}` : esc(T.machines))
139
+ $('topSub').textContent = h ? hostLine(h) : all.length ? T.mcOnline(all.filter(x => x.online).length, all.length) : ''
140
+ setHtml($('topRight'), `${can('manager') ? `<button class="btn" data-hact="add">${T.addMachine}</button>` : ''}${can('operator') ? `<button class="btn" data-hact="templates">${T.templates}</button><button class="btn primary" data-hact="new"${h ? ` data-h="${esc(h.id)}"` : ''}>${T.newSession}</button>` : ''}`)
141
+ } else if (r.view === 'terminal') {
142
+ const h = hosts.get(r.host)
143
+ const t = h?.info?.terminals?.find(x => x.id === r.term)
144
+ const s = sessionOn(r.host, r.term)
145
+ setHtml($('topTitle'), `<span class="dot ${s ? status(s).dot : ''}"></span>⌨ ${esc(r.term)} ${roleTag(s?.role ?? t?.role)} ${personaTag(s?.persona ?? t?.persona)}`)
146
+ $('topSub').textContent = [h ? T.onHost(h.name) : '', t?.folder ?? '', h?.info && !t ? T.notListed : ''].filter(Boolean).join(' · ')
147
+ const acts = []
148
+ if (s) acts.push(`<button class="btn" data-go="#/s/${encodeURIComponent(r.term)}/chat">${T.chat}</button>`)
149
+ acts.push(`<button class="btn" data-tact="redraw">${T.redraw}</button>`)
150
+ if (t && h?.online) acts.push(`<button class="btn danger" data-tact="kill">${T.closeSession}</button>`)
151
+ setHtml($('topRight'), acts.join(''))
152
+ } else if (r.view === 'archived') {
153
+ setHtml($('topTitle'), T.archivedTitle)
154
+ $('topSub').textContent = T.archivedSub
155
+ setHtml($('topRight'), '')
156
+ } else {
157
+ const s = sessions.get(r.name)
158
+ const st = status(s)
159
+ const role = s?.role === 'coordinator' ? 'coord' : s?.role === 'solo' ? 'solo' : 'worker'
160
+ const team = s?.role === 'coordinator' ? s.name : s?.coordinator
161
+ const teamName = team ? state.squadMeta.get(team)?.title || team : ''
162
+ setHtml($('topTitle'), `<span class="role ${role}" aria-hidden="true"></span>${agentMark(r.name)}<span class="sv-name">${esc(r.name)}</span>${s?.archived_at ? ` <span class="tag">${esc(T.archivedTag)}</span>` : ''}`)
163
+ $('topSub').textContent = [s ? T.roleName[s.role] ?? T.roleName.worker : '', teamName, st.text].filter(Boolean).join(' · ')
164
+ // Its conversation, or its live terminal when it has one.
165
+ const where = terminalOf(r.name)
166
+ const termOn = !!(where && !r.chat && can('operator'))
167
+ if (where && can('operator')) setHtml($('topTabs'), `<nav class="seg" aria-label="${esc(r.name)}"><a href="#/s/${encodeURIComponent(r.name)}/chat"${termOn ? '' : ' class="on" aria-current="page"'}>${esc(T.svChat)}</a><a href="#/s/${encodeURIComponent(r.name)}"${termOn ? ' class="on" aria-current="page"' : ''}>${esc(T.terminal)}</a></nav>`)
168
+ else setHtml($('topTabs'), '')
169
+ const acts = []
170
+ if (reopenable(s) && can('operator')) acts.push(`<button class="btn primary" data-reopen="${esc(r.name)}">${T.reopen}</button>`)
171
+ if (s?.approval_pending && can('manager')) acts.push(`<button class="btn primary ok" data-act="approve" data-s="${esc(s.name)}">${T.approve}</button>`)
172
+ if (termOn) acts.push(`<button class="btn quiet" data-tact="redraw">${esc(T.redraw)}</button><button class="btn quiet danger" data-tact="kill">${esc(T.closeSession)}</button>`)
173
+ if (s && !termOn && !s.online && can('operator')) acts.push(s.archived_at
174
+ ? `<button class="btn" data-act="unarchive" data-s="${esc(s.name)}">${T.unarchive}</button>`
175
+ : `<button class="btn" data-act="archive" data-s="${esc(s.name)}">${T.archive}</button>`)
176
+ if (s) acts.push(`<button class="btn quiet" data-menu="${esc(s.name)}" aria-haspopup="menu" aria-label="${esc(T.svMore(s.name))}">${esc(T.svMoreShort)}</button>`)
177
+ setHtml($('topRight'), acts.join(''))
178
+ }
179
+ }
180
+
181
+ $('topRight').addEventListener('click', e => {
182
+ if (boardsTopClick(e)) return
183
+ const c = e.target.closest('[data-c]')
184
+ if (c) { state.cols = c.dataset.c; store.set('pishaCols', state.cols); applyCols(); renderTop() }
185
+ const ro = e.target.closest('[data-reopen]')
186
+ if (ro) return reopen(ro.dataset.reopen)
187
+ const md = e.target.closest('[data-mode]')
188
+ if (md) { state.mosaicMode = md.dataset.mode === 'chats' ? 'chats' : 'terms'; store.set('pishaMosaicMode', state.mosaicMode); buildMosaic(); renderTop() }
189
+ const go = e.target.closest('[data-go]')
190
+ if (go) location.hash = go.dataset.go
191
+ const act = e.target.closest('[data-act]')
192
+ if (act) runAction(act.dataset.act, act.dataset.s)
193
+ const hact = e.target.closest('[data-hact]')
194
+ if (hact) hostAction(hact.dataset.hact, hact.dataset.h)
195
+ if (e.target.closest('[data-newteam]')) { location.hash = '#/new'; return }
196
+ const aw = e.target.closest('[data-addworker]')
197
+ if (aw) addWorkerTo(aw.dataset.addworker)
198
+ const stp = e.target.closest('[data-savetpl]')
199
+ if (stp) saveTemplateDialog(stp.dataset.savetpl)
200
+ const lk = e.target.closest('[data-links]')
201
+ if (lk) linksDialog(lk.dataset.links)
202
+ const menu = e.target.closest('[data-menu]')
203
+ if (menu) return openMenu(menu, menu.dataset.menu)
204
+ const tact = e.target.closest('[data-tact]')
205
+ if (tact) {
206
+ const r = currentRoute()
207
+ const st = sessionTerm(r)
208
+ if (tact.dataset.tact === 'redraw') state.termView?.refresh()
209
+ if (tact.dataset.tact === 'kill') hostAction('kill', r.host ?? st?.host.id, r.term ?? r.name)
210
+ }
211
+ })
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
+ })
@@ -0,0 +1,98 @@
1
+ // What was said, while the inbox is read aloud: a command, an option (with
2
+ // whatever detail follows it), or an answer in the user's own words. In
3
+ // Spanish and in English alike, whatever the dashboard's language: people mix.
4
+ // (No DOM here: the tests load it on its own.)
5
+
6
+ // Lower case, without accents or punctuation around the words.
7
+ export const normalize = text => String(text ?? '')
8
+ .toLowerCase()
9
+ .normalize('NFD').replace(/[̀-ͯ]/g, '')
10
+ .replace(/[¿¡!?.,;:"«»()]/g, ' ')
11
+ .replace(/\s+/g, ' ')
12
+ .trim()
13
+
14
+ // Said on their own, these steer the reading instead of answering.
15
+ const COMMANDS = {
16
+ stop: ['para', 'parar', 'salir', 'sal', 'cuelga', 'colgar', 'termina', 'terminar', 'fin', 'stop', 'exit', 'quit', 'hang up', 'end'],
17
+ next: ['siguiente', 'salta', 'saltar', 'saltala', 'luego', 'despues', 'mas tarde', 'pasa', 'next', 'skip', 'later'],
18
+ repeat: ['repite', 'repitelo', 'repitela', 'otra vez', 'como', 'que', 'repeat', 'again', 'say again', 'what'],
19
+ done: ['hecho', 'leido', 'entendido', 'visto', 'done', 'read', 'got it', 'seen'],
20
+ dismiss: ['descarta', 'descartar', 'descartala', 'dismiss'],
21
+ }
22
+ const YES = ['si', 'vale', 'envia', 'enviala', 'envialo', 'de acuerdo', 'ok', 'okay', 'correcto', 'eso es', 'adelante', 'yes', 'yeah', 'yep', 'send', 'send it', 'sure', 'correct', 'go ahead']
23
+ const NO = ['no', 'cambia', 'cambiar', 'cambialo', 'espera', 'nope', 'change', 'change it', 'wait']
24
+
25
+ // The option's number, said as a word or a digit.
26
+ const NUMBERS = [
27
+ ['1', 'uno', 'una', 'primera', 'primero', 'one', 'first'],
28
+ ['2', 'dos', 'segunda', 'segundo', 'two', 'second'],
29
+ ['3', 'tres', 'tercera', 'tercero', 'three', 'third'],
30
+ ['4', 'cuatro', 'cuarta', 'cuarto', 'four', 'fourth'],
31
+ ['5', 'cinco', 'quinta', 'quinto', 'five', 'fifth'],
32
+ ['6', 'seis', 'sexta', 'sexto', 'six', 'sixth'],
33
+ ]
34
+ const NUMBER_OF = new Map(NUMBERS.flatMap((words, n) => words.map(w => [w, n])))
35
+ // Words before the choice ("la dos", "opción 2", "the second one", "number three").
36
+ const LEAD = new Set(['la', 'el', 'lo', 'opcion', 'numero', 'quiero', 'elijo', 'option', 'number', 'the', 'choose', 'pick', 'i'])
37
+ const AFTER = new Set(['one', 'option', 'opcion'])
38
+ const RECOMMENDED = [['recomendada'], ['recomendado'], ['que', 'recomiendas'], ['que', 'recomienda'], ['recommended'], ['what', 'you', 'recommend']]
39
+ // Words that only join the detail to the choice ("la dos, y que sea el lunes").
40
+ const JOINERS = new Set(['y', 'e', 'pero', 'con', 'and', 'but', 'with'])
41
+ const ARTICLES = new Set(['una', 'uno', 'one'])
42
+
43
+ // yes / no / null, for the question "do I send it?"
44
+ export function yesNo(text) {
45
+ const t = normalize(text)
46
+ if (YES.includes(t) || YES.some(w => t.startsWith(`${w} `))) return true
47
+ if (NO.includes(t) || NO.some(w => t.startsWith(`${w} `))) return false
48
+ return null
49
+ }
50
+
51
+ // { kind: 'command', cmd } | { kind: 'option', n, detail } | { kind: 'free', text } | { kind: 'empty' }
52
+ // The detail and the free text keep what was said as it was said, only trimmed.
53
+ export function parseUtterance(text, { options = 0, recommended = -1 } = {}) {
54
+ const said = String(text ?? '').trim()
55
+ const t = normalize(said)
56
+ if (!t) return { kind: 'empty' }
57
+ for (const [cmd, words] of Object.entries(COMMANDS)) if (words.includes(t)) return { kind: 'command', cmd }
58
+ if (options) {
59
+ // Each word as said, with how it reads (punctuation alone is no word).
60
+ const words = said.split(/\s+/).map(raw => ({ raw, n: normalize(raw) })).filter(w => w.n)
61
+ let i = 0
62
+ while (i < words.length && LEAD.has(words[i].n)) i++
63
+ let n = NUMBER_OF.get(words[i]?.n)
64
+ let next = i + 1
65
+ // ("una cosa más", "one more thing": an article, not a choice, unless it is introduced or alone.)
66
+ if (ARTICLES.has(words[i]?.n) && i === 0 && words.length > 1 && !JOINERS.has(words[1].n) && !AFTER.has(words[1].n) && !/[,.;:]$/.test(words[0].raw)) n = null
67
+ if (n == null && recommended >= 0) {
68
+ const p = RECOMMENDED.find(p => p.every((w, k) => words[i + k]?.n === w))
69
+ if (p) { n = recommended; next = i + p.length }
70
+ }
71
+ if (n != null && n < options) {
72
+ if (AFTER.has(words[next]?.n)) next++
73
+ return { kind: 'option', n, detail: tidy(words.slice(next)) }
74
+ }
75
+ }
76
+ return { kind: 'free', text: said }
77
+ }
78
+
79
+ // What follows the choice, without the words that only join it.
80
+ function tidy(words) {
81
+ let k = 0
82
+ while (k < words.length && JOINERS.has(words[k].n)) k++
83
+ return words.slice(k).map(w => w.raw).join(' ').replace(/^[\s,.;:—–-]+/, '').trim()
84
+ }
85
+
86
+ // Text to be read aloud: no markdown, no links spelled out, no long paths.
87
+ export function speakable(text, { link = 'a link', path = 'a file' } = {}) {
88
+ return String(text ?? '')
89
+ .replace(/```[\s\S]*?```/g, ' ')
90
+ .replace(/`([^`]*)`/g, '$1')
91
+ .replace(/https?:\/\/\S+/g, link)
92
+ .replace(/(?:^|\s)(?:\/[\w.-]+){2,}\/?/g, ` ${path}`)
93
+ .replace(/\*\*|__|[*_]/g, '')
94
+ .replace(/[#>|]/g, ' ')
95
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
96
+ .replace(/\s+/g, ' ')
97
+ .trim()
98
+ }