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/voice.js ADDED
@@ -0,0 +1,320 @@
1
+ // The inbox read aloud, and answered by voice: hands-free, for a phone.
2
+ // It reads each decision that can be answered from here, with its options,
3
+ // listens for the answer, says back what it understood and sends it only
4
+ // once the user says yes. Then what there is to know, which can be replied
5
+ // to or marked done. Everything runs in the browser: its speech recognition
6
+ // and its voices (Chrome on Android sends the audio to Google to recognise it:
7
+ // the user is told before the first time).
8
+
9
+ import { $ } from './dom.js'
10
+ import { T, LANG, LOCALE } from './i18n.js'
11
+ import { state, can, sessions } from './state.js'
12
+ import { esc } from './format.js'
13
+ import { postJson } from './machines.js'
14
+ import { alertBox } from './mosaic.js'
15
+ import { confirmDialog } from './dialogs.js'
16
+ import { replaceHash } from './back.js'
17
+ import { currentRoute } from './router.js'
18
+ import { cantAnswer } from './inbox.js'
19
+ import { icon } from './icons.js'
20
+ import { parseUtterance, yesNo, speakable } from './voice-parse.js'
21
+
22
+ const Recognition = window.SpeechRecognition ?? window.webkitSpeechRecognition
23
+ const SPEECH_LANG = LANG === 'es' ? 'es-ES' : 'en-GB'
24
+ const CONSENT = 'pisha.voice-ok'
25
+ const HEARD_TRIES = 2 // silences in a row before moving on
26
+ // How fast it reads, as on a voice message: a tap on the chip, the next one.
27
+ // (Small steps: past 1.2 the voices get hard to follow.)
28
+ const RATES = [1, 1.1, 1.2]
29
+ const RATE_KEY = 'pisha.voice-rate'
30
+ let rate = (() => { try { const r = Number(localStorage.getItem(RATE_KEY)); return RATES.includes(r) ? r : 1 } catch { return 1 } })()
31
+ // (Said in words, normal, fast, faster: a number says little about a voice.)
32
+ const rateLabel = r => T.vRates[RATES.indexOf(r)] ?? `${r.toLocaleString(LOCALE)}×`
33
+
34
+ export const voiceSupported = () => !!Recognition && 'speechSynthesis' in window
35
+ export const voiceButton = () => (can('operator') ? `<button type="button" class="btn" data-voice aria-pressed="${!!run}">${icon('mic')}<span>${esc(run ? T.vStop : T.vListen)}</span></button>` : '')
36
+
37
+ let run = null // the reading going on: { stopped, utterance, recognition, lock }
38
+
39
+ // --- speaking and listening -------------------------------------------------
40
+
41
+ function voiceFor() {
42
+ const voices = speechSynthesis.getVoices()
43
+ return voices.find(v => v.lang === SPEECH_LANG) ?? voices.find(v => v.lang?.startsWith(LANG)) ?? null
44
+ }
45
+
46
+ // Said aloud; resolves when it ends, is cut short (a tap) or the reading stops.
47
+ // A new speed takes effect at once: the sentence it was in is said again, faster
48
+ // or slower (where it is going comes from the voice's word boundaries, when it
49
+ // gives them; if not, from the start).
50
+ function say(text) {
51
+ if (!run || run.stopped) return Promise.resolve()
52
+ show(text, 'speaking')
53
+ return new Promise(resolve => {
54
+ const from = start => {
55
+ const u = new SpeechSynthesisUtterance(text.slice(start))
56
+ u.lang = SPEECH_LANG
57
+ u.rate = rate
58
+ const v = voiceFor(); if (v) u.voice = v
59
+ u.onboundary = e => { if (run) run.at = start + (e.charIndex ?? 0) }
60
+ u.onend = u.onerror = () => {
61
+ if (u.replaced) return
62
+ if (run?.utterance === u) { run.utterance = null; run.again = null }
63
+ resolve()
64
+ }
65
+ run.utterance = u
66
+ run.at = start
67
+ run.again = () => {
68
+ u.replaced = true
69
+ speechSynthesis.cancel()
70
+ // (A moment for the voice to stop: some drop what is said right after a cancel.)
71
+ setTimeout(() => { if (run && !run.stopped) from(sentenceStart(text, run.at ?? start)); else resolve() }, 60)
72
+ }
73
+ speechSynthesis.speak(u)
74
+ }
75
+ from(0)
76
+ })
77
+ }
78
+ // Where the sentence that has position at begins.
79
+ function sentenceStart(text, at) {
80
+ let s = 0
81
+ for (const m of text.slice(0, at).matchAll(/[.?!…:]\s+/g)) s = m.index + m[0].length
82
+ return s
83
+ }
84
+
85
+ // What the user says next ('' after a silence, or once the reading stops).
86
+ function listen() {
87
+ if (!run || run.stopped) return Promise.resolve('')
88
+ show('', 'listening')
89
+ return new Promise(resolve => {
90
+ const r = new Recognition()
91
+ r.lang = SPEECH_LANG
92
+ r.interimResults = true
93
+ r.maxAlternatives = 1
94
+ let heard = ''
95
+ r.onresult = e => {
96
+ heard = [...e.results].map(x => x[0].transcript).join(' ').trim()
97
+ show(heard, 'listening')
98
+ }
99
+ r.onerror = e => { if (e.error === 'not-allowed' || e.error === 'service-not-allowed') stop(T.vMicDenied) }
100
+ r.onend = () => { if (run?.recognition === r) run.recognition = null; resolve(heard) }
101
+ run.recognition = r
102
+ try { r.start() } catch { resolve('') }
103
+ })
104
+ }
105
+
106
+ // --- the bar at the bottom: what is said, what was heard ---------------------
107
+
108
+ function show(text, mode) {
109
+ let bar = $('voiceBar')
110
+ if (!bar) {
111
+ bar = document.createElement('div')
112
+ bar.id = 'voiceBar'
113
+ bar.className = 'voice-bar'
114
+ bar.setAttribute('role', 'status')
115
+ bar.innerHTML = `<div class="voice-head"><span class="voice-mode"></span><button type="button" class="voice-speed" data-voicespeed></button></div>
116
+ <button type="button" class="voice-say" data-voicecut><span class="voice-text"></span></button>
117
+ <div class="voice-actions"><button type="button" class="btn" data-voicenext>${esc(T.vNext)}</button><button type="button" class="btn danger" data-voicestop>${esc(T.vStop)}</button></div>`
118
+ document.body.appendChild(bar)
119
+ }
120
+ bar.dataset.mode = mode
121
+ const label = mode === 'listening' ? T.vListening : mode === 'sending' ? T.vSending : T.vSpeaking
122
+ bar.querySelector('.voice-mode').textContent = label
123
+ bar.querySelector('.voice-text').textContent = text
124
+ showRate(bar)
125
+ }
126
+ function showRate(bar = $('voiceBar')) {
127
+ const b = bar?.querySelector('[data-voicespeed]')
128
+ if (!b) return
129
+ b.textContent = rateLabel(rate)
130
+ b.setAttribute('aria-label', T.vSpeed(rateLabel(rate)))
131
+ }
132
+
133
+ // A tap while it speaks cuts it short; "next" skips what is being read.
134
+ document.addEventListener('click', e => {
135
+ if (e.target.closest('[data-voicespeed]')) {
136
+ rate = RATES[(RATES.indexOf(rate) + 1) % RATES.length]
137
+ try { localStorage.setItem(RATE_KEY, String(rate)) } catch {}
138
+ showRate()
139
+ run?.again?.()
140
+ return
141
+ }
142
+ if (e.target.closest('[data-voicecut]') && run?.utterance) { speechSynthesis.cancel(); return }
143
+ if (e.target.closest('[data-voicenext]') && run) { run.skip = true; cutShort(); return }
144
+ if (e.target.closest('[data-voicestop]')) { stop(); return }
145
+ if (e.target.closest('[data-voice]')) { run ? stop() : start(); return }
146
+ })
147
+ function cutShort() {
148
+ speechSynthesis.cancel()
149
+ try { run?.recognition?.abort() } catch {}
150
+ }
151
+
152
+ // --- what is read ----------------------------------------------------------
153
+
154
+ // What can be done here: decisions answered from the dashboard, then notes.
155
+ // (A decision that has to be answered in its session is only mentioned.)
156
+ function queue(skipped) {
157
+ const open = state.inbox.filter(i => !i.resolved_at && !skipped.has(i.id))
158
+ const asks = open.filter(i => i.kind === 'ask').sort((a, b) => a.id - b.id)
159
+ const tells = open.filter(i => i.kind === 'tell').sort((a, b) => a.id - b.id)
160
+ return [...asks, ...tells]
161
+ }
162
+ const team = name => state.squadMeta.get(sessions.get(name)?.role === 'coordinator' ? name : sessions.get(name)?.coordinator)?.title || name
163
+ const clean = text => speakable(text, { link: T.vLink, path: T.vPath })
164
+ // (Each part ends as a sentence, so the voice pauses before the next.)
165
+ const sentence = text => (/[.?!…:]$/.test(text) ? text : `${text}.`)
166
+ const recIndexOf = i => {
167
+ const rec = String(i.recommended ?? '').trim().toLowerCase()
168
+ return rec ? i.options.findIndex(o => { const t = o.trim().toLowerCase(); return rec === t || (rec.startsWith(t) && /^[\s:.,;—–-]/.test(rec.slice(t.length))) }) : -1
169
+ }
170
+
171
+ function readAsk(i) {
172
+ const rec = recIndexOf(i)
173
+ const opts = i.options.map((o, n) => T.vOption(n + 1, clean(o))).join(' ')
174
+ return [T.vAskFrom(i.session, team(i.session)), sentence(clean(i.text)), opts, rec >= 0 ? T.vRecommends(rec + 1) : '', i.options.length ? T.vHowAnswerOptions : T.vHowAnswer].filter(Boolean).join(' ')
175
+ }
176
+ const readTell = i => [T.vTellFrom(i.session, team(i.session)), sentence(clean(i.text)), cantAnswer(i) ? T.vHowDoneOnly : T.vHowTell].join(' ')
177
+
178
+ // "Stop" or "next" said where a yes or a no was expected: they still apply.
179
+ // true: it was one of them (and done).
180
+ async function steered(heard) {
181
+ const p = parseUtterance(heard)
182
+ if (p.kind !== 'command') return false
183
+ if (p.cmd === 'stop') { stop(); return true }
184
+ if (p.cmd === 'next') { if (run) run.skip = true; await say(T.vSkipped); return true }
185
+ return false
186
+ }
187
+
188
+ // The answer read back, and sent only on a yes. true: sent.
189
+ async function confirmAndSend(i, answer, what) {
190
+ await say(T.vConfirm(what))
191
+ for (let k = 0; k < HEARD_TRIES && !run?.stopped && !run?.skip; k++) {
192
+ const heard = await listen()
193
+ if (await steered(heard)) return false
194
+ const yn = yesNo(heard)
195
+ if (yn === true) {
196
+ show(what, 'sending')
197
+ try {
198
+ await postJson('/api/inbox/answer', { id: i.id, version: i.version, answer })
199
+ await say(T.vSent)
200
+ return true
201
+ } catch (err) {
202
+ await say(err.reason === 'changed' ? T.vChanged : T.vFailed(err.message))
203
+ return false
204
+ }
205
+ }
206
+ if (yn === false) { await say(T.vSayAgain); return false }
207
+ await say(T.vYesOrNo)
208
+ }
209
+ return false
210
+ }
211
+
212
+ async function handle(i) {
213
+ // Fresh from the inbox: it may have changed, or closed, while another was read.
214
+ const now = () => state.inbox.find(x => x.id === i.id)
215
+ replaceHash(`#/inbox/i${i.id}`)
216
+ const ask = i.kind === 'ask'
217
+ if (ask && cantAnswer(i)) { await say(`${T.vAskFrom(i.session, team(i.session))} ${sentence(clean(i.text))} ${T.vAnswerInSession}`); return }
218
+ await say(ask ? readAsk(i) : readTell(i))
219
+ let silences = 0
220
+ while (run && !run.stopped && !run.skip) {
221
+ const cur = now()
222
+ if (!cur || cur.resolved_at) return
223
+ if (cur.version !== i.version) { i = cur; await say(`${T.vChanged} ${ask ? readAsk(i) : readTell(i)}`); continue }
224
+ const heard = await listen()
225
+ if (!run || run.stopped || run.skip) return
226
+ const p = parseUtterance(heard, { options: ask ? i.options.length : 0, recommended: ask ? recIndexOf(i) : -1 })
227
+ if (p.kind === 'empty') {
228
+ if (++silences >= HEARD_TRIES) { await say(T.vMovingOn); return }
229
+ await say(T.vDidntHear); continue
230
+ }
231
+ silences = 0
232
+ if (p.kind === 'command') {
233
+ if (p.cmd === 'stop') return stop()
234
+ if (p.cmd === 'next') return say(T.vSkipped)
235
+ if (p.cmd === 'repeat') { await say(ask ? readAsk(i) : readTell(i)); continue }
236
+ if (p.cmd === 'done' && !ask) {
237
+ try { await postJson('/api/inbox/resolve', { id: i.id }); await say(T.vMarkedDone) } catch (err) { await say(T.vFailed(err.message)) }
238
+ return
239
+ }
240
+ if (p.cmd === 'dismiss' && ask) {
241
+ await say(T.vConfirmDismiss)
242
+ const heard = await listen()
243
+ if (await steered(heard)) return
244
+ if (yesNo(heard) === true) {
245
+ try { await postJson('/api/inbox/dismiss', { id: i.id }); await say(T.vDismissed) } catch (err) { await say(T.vFailed(err.message)) }
246
+ return
247
+ }
248
+ await say(T.vSayAgain); continue
249
+ }
250
+ }
251
+ if (!ask && cantAnswer(i)) { await say(T.vHowDoneOnly); continue }
252
+ if (p.kind === 'option') {
253
+ const choice = i.options[p.n]
254
+ const answer = p.detail ? `${choice}. ${p.detail}` : choice
255
+ if (await confirmAndSend(i, answer, T.vOptionSaid(p.n + 1, choice, p.detail))) return
256
+ continue
257
+ }
258
+ // In their own words (also a command that doesn't apply here, as said).
259
+ const text = p.kind === 'free' ? p.text : heard
260
+ if (await confirmAndSend(i, text, T.vWordsSaid(text))) return
261
+ }
262
+ }
263
+
264
+ // --- starting and stopping ---------------------------------------------------
265
+
266
+ async function start() {
267
+ if (!window.isSecureContext) return alertBox(T.vNeedsHttps)
268
+ if (!voiceSupported()) return alertBox(T.vUnsupported)
269
+ let ok = false
270
+ try { ok = localStorage.getItem(CONSENT) === '1' } catch {}
271
+ if (!ok) {
272
+ return confirmDialog({ title: T.vConsentTitle, text: esc(T.vConsent), confirm: T.vConsentOk, settles: true, run: async () => {
273
+ try { localStorage.setItem(CONSENT, '1') } catch {}
274
+ setTimeout(begin) // (after the dialog closes: its button was the gesture that lets it speak)
275
+ } })
276
+ }
277
+ begin()
278
+ }
279
+
280
+ async function begin() {
281
+ if (run) return
282
+ run = { stopped: false, skip: false, utterance: null, recognition: null, lock: null }
283
+ refreshButton()
284
+ try { run.lock = await navigator.wakeLock?.request('screen') } catch {}
285
+ const skipped = new Set()
286
+ const first = queue(skipped)
287
+ const asks = first.filter(i => i.kind === 'ask').length
288
+ await say(first.length ? T.vStart(asks, first.length - asks) : T.vNothing)
289
+ while (run && !run.stopped) {
290
+ const next = queue(skipped)[0]
291
+ if (!next) break
292
+ skipped.add(next.id) // (read once each time round; what is left open stays open)
293
+ run.skip = false
294
+ await handle(next)
295
+ }
296
+ if (run && !run.stopped && first.length) await say(queue(new Set()).length ? T.vEndSome : T.vEnd)
297
+ stop()
298
+ }
299
+
300
+ export function stop(why = '') {
301
+ if (!run) return
302
+ run.stopped = true
303
+ cutShort()
304
+ try { run.lock?.release() } catch {}
305
+ run = null
306
+ $('voiceBar')?.remove()
307
+ refreshButton()
308
+ if (why) alertBox(why)
309
+ }
310
+
311
+ function refreshButton() {
312
+ for (const b of document.querySelectorAll('[data-voice]')) {
313
+ b.setAttribute('aria-pressed', String(!!run))
314
+ b.querySelector('span').textContent = run ? T.vStop : T.vListen
315
+ }
316
+ }
317
+
318
+ // Leaving the inbox, or the page, ends it.
319
+ window.addEventListener('hashchange', () => { if (run && currentRoute().view !== 'inbox') stop() })
320
+ window.addEventListener('pagehide', () => stop())
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
+ }
Binary file
@@ -0,0 +1,92 @@
1
+ Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+ -----------------------------------------------------------
8
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
9
+ -----------------------------------------------------------
10
+
11
+ PREAMBLE
12
+ The goals of the Open Font License (OFL) are to stimulate worldwide
13
+ development of collaborative font projects, to support the font creation
14
+ efforts of academic and linguistic communities, and to provide a free and
15
+ open framework in which fonts may be shared and improved in partnership
16
+ with others.
17
+
18
+ The OFL allows the licensed fonts to be used, studied, modified and
19
+ redistributed freely as long as they are not sold by themselves. The
20
+ fonts, including any derivative works, can be bundled, embedded,
21
+ redistributed and/or sold with any software provided that any reserved
22
+ names are not used by derivative works. The fonts and derivatives,
23
+ however, cannot be released under any other type of license. The
24
+ requirement for fonts to remain under this license does not apply
25
+ to any document created using the fonts or their derivatives.
26
+
27
+ DEFINITIONS
28
+ "Font Software" refers to the set of files released by the Copyright
29
+ Holder(s) under this license and clearly marked as such. This may
30
+ include source files, build scripts and documentation.
31
+
32
+ "Reserved Font Name" refers to any names specified as such after the
33
+ copyright statement(s).
34
+
35
+ "Original Version" refers to the collection of Font Software components as
36
+ distributed by the Copyright Holder(s).
37
+
38
+ "Modified Version" refers to any derivative made by adding to, deleting,
39
+ or substituting -- in part or in whole -- any of the components of the
40
+ Original Version, by changing formats or by porting the Font Software to a
41
+ new environment.
42
+
43
+ "Author" refers to any designer, engineer, programmer, technical
44
+ writer or other person who contributed to the Font Software.
45
+
46
+ PERMISSION AND CONDITIONS
47
+ Permission is hereby granted, free of charge, to any person obtaining
48
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
49
+ redistribute, and sell modified and unmodified copies of the Font
50
+ Software, subject to the following conditions:
51
+
52
+ 1) Neither the Font Software nor any of its individual components,
53
+ in Original or Modified Versions, may be sold by itself.
54
+
55
+ 2) Original or Modified Versions of the Font Software may be bundled,
56
+ redistributed and/or sold with any software, provided that each copy
57
+ contains the above copyright notice and this license. These can be
58
+ included either as stand-alone text files, human-readable headers or
59
+ in the appropriate machine-readable metadata fields within text or
60
+ binary files as long as those fields can be easily viewed by the user.
61
+
62
+ 3) No Modified Version of the Font Software may use the Reserved Font
63
+ Name(s) unless explicit written permission is granted by the corresponding
64
+ Copyright Holder. This restriction only applies to the primary font name as
65
+ presented to the users.
66
+
67
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
68
+ Software shall not be used to promote, endorse or advertise any
69
+ Modified Version, except to acknowledge the contribution(s) of the
70
+ Copyright Holder(s) and the Author(s) or with their explicit written
71
+ permission.
72
+
73
+ 5) The Font Software, modified or unmodified, in part or in whole,
74
+ must be distributed entirely under this license, and must not be
75
+ distributed under any other license. The requirement for fonts to
76
+ remain under this license does not apply to any document created
77
+ using the Font Software.
78
+
79
+ TERMINATION
80
+ This license becomes null and void if any of the above conditions are
81
+ not met.
82
+
83
+ DISCLAIMER
84
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
85
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
86
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
87
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
88
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
89
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
90
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
91
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
92
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,21 @@
1
+ Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
2
+ Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
3
+ Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,8 @@
1
+ xterm.js 5.5.0 and @xterm/addon-fit 0.10.0, unmodified, from the npm registry
2
+ (npm pack integrity: xterm sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==,
3
+ addon-fit sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==).
4
+ Served by pisha-server so the dashboard loads no third-party scripts. MIT license: LICENSE-xterm.
5
+
6
+ Inter 4 (InterVariable.woff2, the variable font), unmodified, from https://rsms.me/inter/font-files/InterVariable.woff2
7
+ (sha256 693b77d4f32ee9b8bfc995589b5fad5e99adf2832738661f5402f9978429a8e3).
8
+ The dashboard's typeface, served here for the same reason. SIL Open Font License 1.1: LICENSE-inter.
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FitAddon=t():e.FitAddon=t()}(self,(()=>(()=>{"use strict";var e={};return(()=>{var t=e;Object.defineProperty(t,"__esModule",{value:!0}),t.FitAddon=void 0,t.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal)return;if(!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core,t=e._renderService.dimensions;if(0===t.css.cell.width||0===t.css.cell.height)return;const r=0===this._terminal.options.scrollback?0:e.viewport.scrollBarWidth,i=window.getComputedStyle(this._terminal.element.parentElement),o=parseInt(i.getPropertyValue("height")),s=Math.max(0,parseInt(i.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),l=o-(parseInt(n.getPropertyValue("padding-top"))+parseInt(n.getPropertyValue("padding-bottom"))),a=s-(parseInt(n.getPropertyValue("padding-right"))+parseInt(n.getPropertyValue("padding-left")))-r;return{cols:Math.max(2,Math.floor(a/t.css.cell.width)),rows:Math.max(1,Math.floor(l/t.css.cell.height))}}}})(),e})()));
2
+ //# sourceMappingURL=addon-fit.js.map