pisha-server 0.0.0-stage → 0.0.11

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 (125) 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 +1079 -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 +79 -0
  14. package/dashboard/dashboard.js +407 -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 +224 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +54 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3297 -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 +166 -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 +2093 -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 +40 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +103 -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 +141 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +653 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +179 -0
  89. package/ui/people.js +370 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +171 -0
  93. package/ui/routes.js +46 -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 +113 -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/session.js +42 -0
  105. package/ui/shell.css +122 -0
  106. package/ui/signin.js +120 -0
  107. package/ui/squads.js +370 -0
  108. package/ui/state.js +59 -0
  109. package/ui/stream.js +268 -0
  110. package/ui/styles.css +343 -0
  111. package/ui/team.js +115 -0
  112. package/ui/teams.js +58 -0
  113. package/ui/terminal.js +261 -0
  114. package/ui/theme.js +32 -0
  115. package/ui/timeline.js +163 -0
  116. package/ui/topbar.js +205 -0
  117. package/ui/voice-parse.js +98 -0
  118. package/ui/voice.js +320 -0
  119. package/vendor/InterVariable.woff2 +0 -0
  120. package/vendor/LICENSE-inter +92 -0
  121. package/vendor/LICENSE-xterm +21 -0
  122. package/vendor/README.md +8 -0
  123. package/vendor/addon-fit.js +2 -0
  124. package/vendor/xterm.css +218 -0
  125. package/vendor/xterm.js +2 -0
@@ -0,0 +1,407 @@
1
+ import { rmSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { unix, now, guarded, bad, ApiError, VERSION, ROLES, AGENTS } from '../platform/index.js'
4
+
5
+ export function createDashboard(platform, { sessions, observation, machines, messaging, inbox, plans, organization, permissions, boards }) {
6
+ const { rotateJoinToken, db, bus, broadcast, sseClients, truncateLog, dataDir, log, every } = platform
7
+ const {
8
+ register, approveSession, presenceOf, personaView, identityCreatedAt, identityExists, isOnline, linksOf,
9
+ forgetSession, leases, kickHolder, announceDown, dropLease,
10
+ } = sessions
11
+ const { activityOf, eventView, activity } = observation
12
+ const {
13
+ PERSONA_ID_RE, listHosts, createEnrollment, renameHost, removeHost, changeHostFolders, hostPersonas,
14
+ openTerminalOn, killTerminalOn, newTerminalTicket, typeAnswer,
15
+ } = machines
16
+ const { messageView, closeGroup, handOverGroup, fileRow } = messaging
17
+ const {
18
+ listTemplates, listLinks, listSquads, pushLinks, saveTemplate, deleteTemplate, changeLink, describeSquad,
19
+ placeSquads, describeSession,
20
+ } = organization
21
+
22
+ const adminMethods = {
23
+ register(p) {
24
+ return register(p.name, p.reset === true)
25
+ },
26
+ rotateJoinToken: () => rotateJoinToken(),
27
+ approveSession: p => approveSession(String(p.name ?? '')),
28
+ listIdentities() {
29
+ return db.prepare('SELECT name, created_at, last_seen_at FROM identities ORDER BY name').all()
30
+ .map(r => ({ name: r.name, created_at: unix(r.created_at), ...presenceOf(r.name) }))
31
+ },
32
+ deleteIdentity(p) {
33
+ return deleteSession(String(p.name ?? ''))
34
+ },
35
+ listGroups() {
36
+ return allGroups()
37
+ },
38
+ }
39
+
40
+ bus.on('session-changed', name => broadcast('session', sessionView(name)))
41
+
42
+ function sessionView(name) {
43
+ const row = db.prepare('SELECT name, role, coordinator, created_at, archived_at, cleared_at, host_id, opened_role, opened_persona, opened_coordinator, description, needs_approval, agent FROM identities WHERE name = ?').get(name)
44
+ if (!row) return { name, deleted: true }
45
+ const a = activityOf(name)
46
+ const openedRole = row.host_id && ['coordinator', 'worker', 'solo'].includes(row.opened_role) ? row.opened_role : null
47
+ // Until it first logs in, it is shown as what it was opened as, in the team
48
+ // it was opened in; from then on, as what it says.
49
+ const said = row.role != null
50
+ return {
51
+ name,
52
+ role: said ? row.role : openedRole,
53
+ coordinator: said ? row.coordinator ?? null : openedRole === 'worker' ? row.opened_coordinator ?? null : null,
54
+ persona: personaView(name),
55
+ agent: AGENTS.includes(row.agent) ? row.agent : 'claude', // Claude Code, Codex CLI or Grok CLI
56
+ archived_at: row.archived_at ?? null,
57
+ cleared_at: row.cleared_at ?? null,
58
+ host_id: row.host_id ?? null, // the machine that opened it from the dashboard
59
+ opened_role: openedRole, // and as what
60
+ opened_persona: row.host_id && PERSONA_ID_RE.test(String(row.opened_persona ?? '')) ? row.opened_persona : null, // and with which persona
61
+ description: row.description || null, // what it is for (org chart)
62
+ // Acts as a coordinator (or some worker expects it to) and nobody approved it yet.
63
+ approval_pending: !!row.needs_approval && (row.role === 'coordinator' || !!db.prepare('SELECT 1 FROM identities WHERE coordinator = ?').get(name)),
64
+ ...presenceOf(name),
65
+ activity: { ...a, tool: a.tool ? { ...a.tool } : null },
66
+ }
67
+ }
68
+
69
+ // Every group with its members, in one query.
70
+ function allGroups() {
71
+ const byId = new Map(db.prepare('SELECT id FROM groups ORDER BY id').all().map(g => [g.id, { id: g.id, members: [] }]))
72
+ for (const r of db.prepare('SELECT group_id, name FROM group_members').all()) byId.get(r.group_id)?.members.push(r.name)
73
+ return [...byId.values()]
74
+ }
75
+
76
+ // Presence and role changes don't come with events: watch them.
77
+ const lastSessionKey = new Map()
78
+ every(2000, guarded(() => {
79
+ if (sseClients.size === 0) return
80
+ for (const { name } of db.prepare('SELECT name FROM identities').all()) {
81
+ const v = sessionView(name)
82
+ const key = `${v.online}|${v.role}|${v.coordinator}|${v.pending_updates}|${v.archived_at}`
83
+ if (lastSessionKey.get(name) !== key) {
84
+ lastSessionKey.set(name, key)
85
+ broadcast('session', v)
86
+ }
87
+ }
88
+ }))
89
+
90
+ const dashboardReads = {
91
+ // One session's history for the chat view: its events and Pisha
92
+ // messages it sent or received, merged by time, newest page first. Paginate
93
+ // backwards with ?before=<next_before>. The cursor is exact (time, type, id),
94
+ // so items sharing a millisecond are never skipped or repeated.
95
+ // Order (newest first): ts DESC, then events before messages, then id DESC.
96
+ timeline(q) {
97
+ const session = q.get('session')
98
+ if (!session) throw bad('session is required')
99
+ const limit = Math.max(1, Math.min(Number(q.get('limit') ?? 150) || 150, 500))
100
+ let cts = Number.MAX_SAFE_INTEGER, crank = 2, cid = 0 // start: newer than anything
101
+ const raw = q.get('before')
102
+ if (raw) {
103
+ const m = /^(\d+):([01]):(\d+)$/.exec(raw)
104
+ if (!m) throw bad('invalid before cursor')
105
+ cts = Number(m[1]); crank = Number(m[2]); cid = Number(m[3])
106
+ }
107
+ // Strictly older than the cursor, per item type (event rank 1, message rank 0).
108
+ const evCond = crank === 2 ? 'ts <= ?' : crank === 1 ? '(ts < ? OR (ts = ? AND id < ?))' : 'ts < ?'
109
+ const evArgs = crank === 1 ? [cts, cts, cid] : [cts]
110
+ const msgCond = crank === 0 ? '(created_at < ? OR (created_at = ? AND id < ?))' : 'created_at <= ?'
111
+ const msgArgs = crank === 0 ? [cts, cts, cid] : [crank === 1 ? cts : cts]
112
+ // Nothing from before the chat was cleared.
113
+ const since = db.prepare('SELECT cleared_at FROM identities WHERE name = ?').get(session)?.cleared_at ?? 0
114
+ const evs = db.prepare(`SELECT * FROM events WHERE session = ? AND kind != 'usage' AND ts > ? AND ${evCond} ORDER BY ts DESC, id DESC LIMIT ?`)
115
+ .all(session, since, ...evArgs, limit)
116
+ .map(r => ({ ...eventView(r.id, r.session, r.ts, r.kind, JSON.parse(r.data), { stored: true }), t: 'event' }))
117
+ // What this session could see (canSeeMessage): nothing from before its
118
+ // identity was created (a name registered again starts empty), and in
119
+ // groups only what came after it joined.
120
+ const born = identityCreatedAt(session)
121
+ // One ordered, indexed query per source (sent, received, each group),
122
+ // each LIMITed, merged here: a page costs a page, not the whole history.
123
+ const floor = Math.max(since + 1, born === Infinity ? Number.MAX_SAFE_INTEGER : born)
124
+ // (Only ids and times per source; the rows themselves are read once, for the page.)
125
+ const page = (where, ...args) => db.prepare(`SELECT id, created_at FROM messages WHERE ${where} AND created_at >= ? AND ${msgCond} ORDER BY created_at DESC, id DESC LIMIT ?`).all(...args, floor, ...msgArgs, limit)
126
+ const keys = [...page('from_name = ?', session), ...page('target = ?', session)]
127
+ const inGroup = db.prepare(`SELECT id, created_at FROM messages WHERE target = ? AND from_name != ? AND created_at >= ? AND ${msgCond} ORDER BY created_at DESC, id DESC LIMIT ?`)
128
+ for (const g of db.prepare('SELECT group_id, joined_at FROM group_members WHERE name = ?').all(session)) {
129
+ keys.push(...inGroup.all(g.group_id, session, Math.max(floor, g.joined_at ?? 0), ...msgArgs, limit))
130
+ }
131
+ const seenIds = new Set()
132
+ const ids = keys.filter(r => !seenIds.has(r.id) && seenIds.add(r.id))
133
+ .sort((a, b) => b.created_at - a.created_at || b.id - a.id).slice(0, limit).map(r => r.id)
134
+ const byId = db.prepare('SELECT * FROM messages WHERE id = ?')
135
+ const msgs = ids.map(id => byId.get(id)).filter(Boolean)
136
+ .map(r => ({ t: 'message', ts: r.created_at, ...messageView(r) }))
137
+ const rank = x => (x.t === 'event' ? 1 : 0)
138
+ const merged = [...evs, ...msgs]
139
+ .sort((a, b) => b.ts - a.ts || rank(b) - rank(a) || b.id - a.id)
140
+ .slice(0, limit)
141
+ const last = merged[merged.length - 1]
142
+ return {
143
+ items: merged.reverse(),
144
+ next_before: last ? `${last.ts}:${rank(last)}:${last.id}` : null,
145
+ has_more: merged.length === limit,
146
+ }
147
+ },
148
+
149
+ state() {
150
+ return {
151
+ server_time: now(),
152
+ version: VERSION,
153
+ sessions: db.prepare('SELECT name FROM identities ORDER BY name').all().map(r => sessionView(r.name)),
154
+ hosts: listHosts(),
155
+ groups: allGroups(),
156
+ templates: listTemplates(),
157
+ links: listLinks(),
158
+ inbox: inbox.list(),
159
+ plans: plans.list(),
160
+ squads: listSquads(),
161
+ permissions: permissions.permissionsState(),
162
+ boards: boards.boardList(),
163
+ }
164
+ },
165
+ boards: () => boards.boardReads.boards(),
166
+ 'boards/tasks': q => boards.boardReads.tasks(q),
167
+ 'boards/task': q => boards.boardReads.task(q),
168
+ 'boards/trash': q => boards.boardReads.trash(q),
169
+ events(q) {
170
+ const limit = Math.max(1, Math.min(Number(q.get('limit') ?? 300) || 300, 1000))
171
+ const before = Number(q.get('before') ?? Number.MAX_SAFE_INTEGER)
172
+ const session = q.get('session')
173
+ const rows = session
174
+ ? db.prepare('SELECT * FROM events WHERE session = ? AND id < ? ORDER BY id DESC LIMIT ?').all(session, before, limit)
175
+ : db.prepare('SELECT * FROM events WHERE id < ? ORDER BY id DESC LIMIT ?').all(before, limit)
176
+ return rows.reverse().map(r => eventView(r.id, r.session, r.ts, r.kind, JSON.parse(r.data), { stored: true }))
177
+ },
178
+ hosts() {
179
+ return listHosts()
180
+ },
181
+ inbox() {
182
+ return inbox.list()
183
+ },
184
+ 'inbox/done'(q) {
185
+ return inbox.done({ before: q.get('before'), limit: q.get('limit'), team: q.get('team'), q: q.get('q') })
186
+ },
187
+ messages(q) {
188
+ const limit = Math.max(1, Math.min(Number(q.get('limit') ?? 200) || 200, 1000))
189
+ const before = Number(q.get('before') ?? Number.MAX_SAFE_INTEGER)
190
+ const session = q.get('session')
191
+ const rows = session
192
+ ? db.prepare(`SELECT * FROM messages WHERE id < ? AND (from_name = ? OR target = ? OR target IN (SELECT group_id FROM group_members WHERE name = ?)) ORDER BY id DESC LIMIT ?`).all(before, session, session, session, limit)
193
+ : db.prepare('SELECT * FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?').all(before, limit)
194
+ return rows.reverse().map(messageView)
195
+ },
196
+ }
197
+
198
+ // Clear a session's chat: its own activity is deleted; pisha messages stay
199
+ // (they're also part of the other side's chat) but are hidden from this one.
200
+ function clearChat(name) {
201
+ if (!identityExists(name)) throw bad('session not found')
202
+ const at = now()
203
+ db.prepare('DELETE FROM events WHERE session = ?').run(name)
204
+ db.prepare('UPDATE identities SET cleared_at = ? WHERE name = ?').run(at, name)
205
+ broadcast('cleared', { session: name, at })
206
+ return { session: name, cleared_at: at }
207
+ }
208
+
209
+ // Delete a session from the server. Only while it's disconnected: a live
210
+ // session would just come back. Its messages stay in other sessions' chats.
211
+ function deleteSession(name, { requireOffline = true } = {}) {
212
+ if (!identityExists(name)) throw bad('session not found')
213
+ if (requireOffline && isOnline(name)) {
214
+ throw new ApiError(409, `Conflict: "${name}" is connected; it can only be deleted when disconnected`, { parameters: { reason: 'session_online' } })
215
+ }
216
+ const groupsOf = db.prepare('SELECT group_id FROM group_members WHERE name = ?').all(name).map(r => r.group_id)
217
+ db.prepare('DELETE FROM identities WHERE name = ?').run(name)
218
+ // (Its open questions to the user: closed, never passed to a new session of that name.)
219
+ inbox.closeOrphans(name)
220
+ db.prepare('DELETE FROM group_members WHERE name = ?').run(name)
221
+ db.prepare('DELETE FROM group_invites WHERE name = ? OR invited_by = ?').run(name, name)
222
+ for (const g of groupsOf) if (!db.prepare('SELECT 1 FROM group_members WHERE group_id = ?').get(g)) closeGroup(g); else handOverGroup(g, name)
223
+ // Workers that pointed at it no longer do: a new session with this name
224
+ // won't receive their notices.
225
+ db.prepare('UPDATE identities SET coordinator = NULL WHERE coordinator = ?').run(name)
226
+ // Nor is it linked with other squads any more, nor its squad described.
227
+ if (db.prepare('DELETE FROM squads WHERE coordinator = ?').run(name).changes) broadcast('squads', listSquads())
228
+ plans.forget(name)
229
+ boards.forget(name)
230
+ const links = linksOf(name)
231
+ db.prepare('DELETE FROM squad_links WHERE a = ? OR b = ?').run(name, name)
232
+ if (links.length) { broadcast('links', listLinks()); for (const n of links) void pushLinks(n) }
233
+ db.prepare('DELETE FROM updates WHERE recipient = ?').run(name)
234
+ // What it queued for others goes too (it may be why it was deleted).
235
+ db.prepare('DELETE FROM updates WHERE sender = ?').run(name)
236
+ db.prepare('DELETE FROM events WHERE session = ?').run(name)
237
+ // Its conversations: what it wrote and what was written to it, also the
238
+ // attachments sent to it. Nothing of a deleted session waits to expire.
239
+ const sentToIt = db.prepare('SELECT file_id FROM messages WHERE target = ? AND file_id IS NOT NULL').all(name).map(r => r.file_id)
240
+ db.prepare('DELETE FROM reactions WHERE message_id IN (SELECT id FROM messages WHERE from_name = ? OR target = ?)').run(name, name)
241
+ db.prepare('DELETE FROM messages WHERE from_name = ? OR target = ?').run(name, name)
242
+ for (const id of sentToIt) {
243
+ const f = fileRow(id)
244
+ if (!f) continue
245
+ try { rmSync(join(dataDir, f.path), { force: true }) } catch {}
246
+ db.prepare('DELETE FROM files WHERE file_id = ?').run(id)
247
+ }
248
+ // Its attachments go too (they count against the server's total).
249
+ for (const f of db.prepare('SELECT file_id, path FROM files WHERE owner = ?').all(name)) {
250
+ try { rmSync(join(dataDir, f.path), { force: true }) } catch {}
251
+ db.prepare('DELETE FROM files WHERE file_id = ?').run(f.file_id)
252
+ }
253
+ forgetSession(name)
254
+ activity.delete(name)
255
+ lastSessionKey.delete(name)
256
+ broadcast('session', { name, deleted: true })
257
+ truncateLog()
258
+ return { session: name, deleted: true }
259
+ }
260
+
261
+ // Archive: hide a disconnected session from the main views, keeping its history.
262
+ function setArchived(name, archived) {
263
+ if (!identityExists(name)) throw bad('session not found')
264
+ if (archived && isOnline(name)) {
265
+ throw new ApiError(409, `Conflict: "${name}" is connected; it can only be archived when disconnected`, { parameters: { reason: 'session_online' } })
266
+ }
267
+ db.prepare('UPDATE identities SET archived_at = ? WHERE name = ?').run(archived ? now() : null, name)
268
+ const view = sessionView(name)
269
+ broadcast('session', view)
270
+ return view
271
+ }
272
+
273
+ // Disconnect a session from the dashboard: its secret is replaced (and the
274
+ // new one thrown away), so whoever holds a copy of the old one is out for
275
+ // good. The session can then be archived or deleted; to use the name again,
276
+ // open it again from the dashboard on its machine, or delete it.
277
+ function kickSession(name) {
278
+ if (!identityExists(name)) throw bad('session not found')
279
+ const lease = leases.get(name)
280
+ kickHolder(name)
281
+ // What it had queued for others isn't delivered — dropped first, so the
282
+ // notice that it left (queued as its own) still reaches its coordinator.
283
+ db.prepare('DELETE FROM updates WHERE sender = ?').run(name)
284
+ if (lease && !lease.downNotified) announceDown(name, 'logout')
285
+ dropLease(name)
286
+ register(name, true)
287
+ broadcast('session', sessionView(name))
288
+ log(`session "${name}" disconnected from the dashboard`)
289
+ return sessionView(name)
290
+ }
291
+
292
+ // (Said to come from the inbox: typed in the coordinator's terminal, it would
293
+ // look as if the user were following that session now, and the next question
294
+ // went to the chat.)
295
+ // (A reply to something it told them quotes more of it: what the reply is
296
+ // about may have left its context since. Never more than a machine types in
297
+ // one line: what is quoted gives way to what the user wrote.)
298
+ const TYPED_MAX = 2200
299
+ const fromInbox = (taken, what, max = 80) => {
300
+ const asked = taken.text.replace(/\s+/g, ' ')
301
+ const line = quote => `Inbox #${taken.id} ("${quote}"), ${what} [They are not following this session: anything else for them goes to ask_user or tell_user. Update your plan with update_plan.]`
302
+ const room = Math.max(0, Math.min(max, TYPED_MAX - line('…').length))
303
+ return line(asked.length > room ? `${asked.slice(0, room)}…` : asked)
304
+ }
305
+
306
+ // An answer from the inbox: closed as answered, then typed in the
307
+ // coordinator's terminal. If it can't be typed, it is open again.
308
+ async function answerFromInbox(p, actor) {
309
+ const taken = inbox.takeAnswer(p, actor?.email ?? 'server token')
310
+ try {
311
+ await typeAnswer(taken.session, taken.kind === 'tell'
312
+ ? fromInbox(taken, `you told the user this, and they reply from their inbox: ${taken.answer}`, 600)
313
+ : fromInbox(taken, `the user answers from their inbox: ${taken.answer}`))
314
+ } catch (err) {
315
+ inbox.giveBack(taken.id)
316
+ throw err
317
+ }
318
+ return { id: taken.id, answered: true }
319
+ }
320
+
321
+ // A question put away without an answer: closed, and its coordinator told
322
+ // not to wait for one. If that can't be typed it stays closed, and the
323
+ // dashboard says who wasn't told (it also learns if it tries to change it).
324
+ async function dismissFromInbox(p, actor) {
325
+ const taken = inbox.dismiss(Number(p.id), actor?.email ?? 'server token')
326
+ try {
327
+ await typeAnswer(taken.session, fromInbox(taken, 'the user dismissed it from their inbox without answering. Don\'t wait for an answer to it: carry on with the rest, or ask again differently if you still need a decision.'))
328
+ } catch (err) {
329
+ return { id: taken.id, dismissed: true, told: false, reason: err.extra?.parameters?.reason ?? null }
330
+ }
331
+ return { id: taken.id, dismissed: true, told: true }
332
+ }
333
+
334
+ const dashboardActions = {
335
+ kick: p => kickSession(String(p.session ?? '')),
336
+ approve: p => approveSession(String(p.session ?? '')),
337
+ clear: p => clearChat(String(p.session ?? '')),
338
+ delete: p => deleteSession(String(p.session ?? '')),
339
+ archive: p => setArchived(String(p.session ?? ''), true),
340
+ unarchive: p => setArchived(String(p.session ?? ''), false),
341
+ 'hosts/enroll': (p, req) => createEnrollment(p, req),
342
+ 'hosts/rename': p => renameHost(String(p.host ?? ''), p.name),
343
+ 'hosts/remove': p => {
344
+ const host = String(p.host ?? '')
345
+ // (Read first: removing it clears what says which ones it opened.)
346
+ const opened = p.disconnect_sessions === true ? db.prepare('SELECT name FROM identities WHERE host_id = ?').all(host).map(r => r.name) : []
347
+ const removed = removeHost(host)
348
+ for (const name of opened) kickSession(name)
349
+ return { ...removed, disconnected: opened }
350
+ },
351
+ 'hosts/folders': p => changeHostFolders(p),
352
+ 'hosts/personas': p => hostPersonas(p),
353
+ 'templates/save': p => saveTemplate(p),
354
+ 'templates/delete': p => deleteTemplate(String(p.name ?? '')),
355
+ 'links/add': p => changeLink(p, true),
356
+ 'links/delete': p => changeLink(p, false),
357
+ 'org/squad': p => describeSquad(p),
358
+ 'org/positions': p => placeSquads(p),
359
+ 'org/describe': p => describeSession(p),
360
+ 'permissions/save': p => permissions.saveProfile(p),
361
+ 'permissions/delete': p => permissions.deleteProfile(p),
362
+ 'permissions/assign': p => permissions.assignProfile(p),
363
+ 'terminals/open': (p, req) => openTerminalOn(p, req.actor),
364
+ 'terminals/kill': p => killTerminalOn(p),
365
+ 'terminal/ticket': (p, req) => newTerminalTicket(req.actor ?? null),
366
+ 'inbox/resolve': p => inbox.resolve(Number(p.id)),
367
+ 'inbox/read-all': p => inbox.resolveTells(Array.isArray(p.ids) ? p.ids.map(Number) : p.ids),
368
+ 'inbox/answer': (p, req) => answerFromInbox(p, req.actor),
369
+ 'inbox/dismiss': (p, req) => dismissFromInbox(p, req.actor),
370
+ ...Object.fromEntries(Object.entries(boards.boardActions).map(([k, fn]) => [k, (p, req) => fn(p, req.actor ?? null)])),
371
+ }
372
+
373
+ // Who may do each thing, at least. Whatever isn't here nobody may do, and the
374
+ // server refuses to start (see the end): every new action says who it is for.
375
+ const dashboardRoles = {
376
+ reads: { inbox: 'observer', 'inbox/done': 'observer', timeline: 'observer', state: 'observer', events: 'observer', hosts: 'observer', messages: 'observer', stream: 'observer', boards: 'observer', 'boards/tasks': 'observer', 'boards/task': 'observer', 'boards/trash': 'manager' },
377
+ actions: {
378
+ 'inbox/resolve': 'operator', 'inbox/read-all': 'operator', 'inbox/answer': 'operator', 'inbox/dismiss': 'operator', kick: 'operator', clear: 'operator', archive: 'operator', unarchive: 'operator',
379
+ 'terminals/open': 'operator', 'terminals/kill': 'operator', 'terminal/ticket': 'operator', 'hosts/personas': 'operator',
380
+ approve: 'manager', delete: 'manager',
381
+ 'hosts/enroll': 'manager', 'hosts/rename': 'manager', 'hosts/remove': 'manager', 'hosts/folders': 'manager',
382
+ 'templates/save': 'manager', 'templates/delete': 'manager', 'links/add': 'manager', 'links/delete': 'manager',
383
+ 'org/squad': 'manager', 'org/positions': 'manager', 'org/describe': 'manager',
384
+ 'permissions/save': 'manager', 'permissions/delete': 'manager', 'permissions/assign': 'manager',
385
+ 'tasks/create': 'operator', 'tasks/update': 'operator', 'tasks/comment': 'operator', 'tasks/notify': 'operator',
386
+ 'tasks/delete': 'manager', 'tasks/restore': 'manager', 'boards/create': 'manager', 'boards/update': 'manager', 'boards/delete': 'manager', 'boards/prefix': 'manager', 'boards/flow': 'manager', 'boards/github': 'manager', 'boards/github-off': 'manager', 'boards/github-merge': 'manager', 'boards/github-sync': 'operator', 'boards/github-watch': 'observer',
387
+ },
388
+ }
389
+ for (const [table, roles] of [[dashboardActions, dashboardRoles.actions], [{ ...dashboardReads, stream: true }, dashboardRoles.reads]]) {
390
+ for (const what of Object.keys(table)) if (!ROLES.includes(roles[what])) throw new Error(`"${what}" doesn't say who may do it`)
391
+ }
392
+
393
+ function openStream(req, res) {
394
+ res.writeHead(200, {
395
+ 'Content-Type': 'text/event-stream',
396
+ 'Cache-Control': 'no-cache, no-transform',
397
+ Connection: 'keep-alive',
398
+ 'X-Accel-Buffering': 'no', // don't let nginx/caddy buffer it
399
+ })
400
+ res.write(`event: hello\ndata: ${JSON.stringify(dashboardReads.state())}\n\n`)
401
+ res.actor = req.actor ?? null
402
+ sseClients.add(res)
403
+ req.on('close', () => sseClients.delete(res))
404
+ }
405
+
406
+ return { dashboardReads, dashboardActions, dashboardRoles, adminMethods, openStream }
407
+ }
@@ -0,0 +1 @@
1
+ export { createDashboard } from './dashboard.js'
@@ -0,0 +1,69 @@
1
+ import { now, cleanText } from './platform/index.js'
2
+
3
+ export function upgradeStoredData(platform, { observation, messaging, machines }) {
4
+ const { db, inTx, log } = platform
5
+ const { cleanEvent } = observation
6
+ const { uploadMime } = messaging
7
+ const { ownTerminals, sanitizeHostInfo } = machines
8
+
9
+ // Data stored by a version before 0.0.2 was cleaned with older rules (or
10
+ // none): cleaned again once, here, in batches, resuming where it stopped if
11
+ // the server is stopped meanwhile, and saying how far it got.
12
+ db.exec('CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)')
13
+ const metaGet = k => db.prepare('SELECT v FROM meta WHERE k = ?').get(k)?.v
14
+ const metaSet = (k, v) => db.prepare('INSERT OR REPLACE INTO meta (k, v) VALUES (?, ?)').run(k, String(v))
15
+ function recleanOnce(key, table, select, fix) {
16
+ if (metaGet(`${key}_done`)) return
17
+ // (The row id under its own name: in a table whose primary key is an
18
+ // INTEGER, "rowid" would come back named after that key instead.)
19
+ const page = db.prepare(`SELECT rowid AS rid_, ${select} FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT 1000`)
20
+ const saved = Number(metaGet(`${key}_last`))
21
+ let last = Number.isSafeInteger(saved) && saved > 0 ? saved : 0, done = 0
22
+ for (;;) {
23
+ const rows = page.all(last)
24
+ if (!rows.length) break
25
+ inTx(() => { for (const r of rows) fix(r); last = rows[rows.length - 1].rid_; metaSet(`${key}_last`, last) })
26
+ done += rows.length
27
+ if (done % 50_000 < 1000) log(`cleaning ${table} stored by an older version: ${done} done…`)
28
+ }
29
+ metaSet(`${key}_done`, now())
30
+ }
31
+ {
32
+ const upd = db.prepare('UPDATE events SET data = ?, ts = ? WHERE id = ?')
33
+ recleanOnce('events_cleaned_v2', 'events', 'id, kind, ts, data', r => {
34
+ let data
35
+ try { data = JSON.stringify(cleanEvent(r.kind, JSON.parse(r.data))) } catch { data = '{}' }
36
+ // (Whole milliseconds: the history cursor relies on it.)
37
+ const ts = Math.round(Number(r.ts) || 0)
38
+ if (data !== r.data || ts !== r.ts) upd.run(data, ts, r.id)
39
+ })
40
+ }
41
+ {
42
+ const upd = db.prepare('UPDATE messages SET text = ? WHERE id = ?')
43
+ recleanOnce('messages_cleaned_v2', 'messages', 'id, text', r => {
44
+ if (typeof r.text === 'string') { const t = cleanText(r.text); if (t !== r.text) upd.run(t, r.id) }
45
+ })
46
+ const updFile = db.prepare('UPDATE files SET name = ?, mime = ? WHERE file_id = ?')
47
+ recleanOnce('files_cleaned_v2', 'files', 'file_id, name, mime', r => {
48
+ const name = typeof r.name === 'string' ? cleanText(r.name).replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120) || 'file' : r.name
49
+ const mime = uploadMime(r.mime)
50
+ if (name !== r.name || mime !== r.mime) updFile.run(name, mime, r.file_id)
51
+ })
52
+ const updReaction = db.prepare('UPDATE reactions SET emoji = ? WHERE rowid = ?')
53
+ recleanOnce('reactions_cleaned_v2', 'reactions', 'emoji', r => {
54
+ if (typeof r.emoji === 'string') { const e = cleanText(r.emoji.slice(0, 64)).slice(0, 16); if (e !== r.emoji) updReaction.run(e, r.rid_) }
55
+ })
56
+ const updHost = db.prepare('UPDATE hosts SET info = ? WHERE id = ?')
57
+ recleanOnce('hosts_cleaned_v2', 'hosts', 'id, info', r => {
58
+ let info = null
59
+ try { info = JSON.stringify(ownTerminals(sanitizeHostInfo(JSON.parse(r.info ?? 'null')), r.id)) } catch {}
60
+ if (info !== r.info) updHost.run(info, r.id)
61
+ })
62
+ // Updates queued before senders were recorded: whose they are, from the
63
+ // message they carry (so a delete or a kick removes them too).
64
+ if (!metaGet('updates_sender_v2')) {
65
+ db.exec(`UPDATE updates SET sender = COALESCE(json_extract(payload, '$.message.from.id'), json_extract(payload, '$.edited_message.from.id'), json_extract(payload, '$.message_reaction.user.id')) WHERE sender IS NULL`)
66
+ metaSet('updates_sender_v2', now())
67
+ }
68
+ }
69
+ }
@@ -0,0 +1,181 @@
1
+ #!/usr/bin/env bash
2
+ # Pisha: prepare this machine (Linux, or Ubuntu on WSL) and join it to a
3
+ # Pisha server. The dashboard gives you the exact command, with your code. It
4
+ # downloads this script, checks it, and leaves the code in a file for it:
5
+ #
6
+ # bash install.sh https://your-server --code-file code [options]
7
+ #
8
+ # It installs what is missing (tmux, Node.js 22, and the agents chosen: Claude
9
+ # Code unless --no-claude, Codex CLI with --codex, Grok CLI with --grok), then
10
+ # pisha-host, which joins the machine, sets Pisha up in each agent, and
11
+ # installs the "pisha-host" command and a service that keeps it running.
12
+ # Options are passed to pisha-host: --allow-home, --insecure, --no-service.
13
+ # --allow-root: install and run it as root (sessions then have full control
14
+ # of this machine, to change the operating system).
15
+ set -eu
16
+
17
+ SELF="$0"
18
+
19
+ # (All in a function: piped into bash, the whole script is read before anything runs.)
20
+ main() {
21
+ SERVER="${1:-}"; [ $# -gt 0 ] && shift
22
+ # The code comes in a file, so it is in no program's arguments, which anyone
23
+ # on this machine can read (or after the URL, as older commands gave it).
24
+ CODE=""; CODE_FILE=""
25
+ case "${1:-}" in ""|-*) ;; *) CODE="$1"; shift ;; esac
26
+ SHA=""
27
+ ROOT_OK=""
28
+ OS_USER=""
29
+ WANT_CLAUDE=1; WANT_CODEX=""; WANT_GROK=""
30
+ AGENT_ARGS=()
31
+ ARGS=()
32
+ while [ $# -gt 0 ]; do
33
+ case "$1" in
34
+ --sha256) [ $# -ge 2 ] || { echo "--sha256 needs a value" >&2; exit 2; }; SHA="$2"; shift 2 ;;
35
+ --code-file) [ $# -ge 2 ] || { echo "--code-file needs a path" >&2; exit 2; }; CODE_FILE="$2"; shift 2 ;;
36
+ --server-key) ARGS+=("--server-key=${2:-}"); shift 2 ;; # (from windows.bat: no "=" there)
37
+ --company) ARGS+=("--company=${2:-}"); shift 2 ;;
38
+ --os-user) [ $# -ge 2 ] || { echo "--os-user needs a name" >&2; exit 2; }; OS_USER="$2"; shift 2 ;;
39
+ --os-user=*) OS_USER="${1#--os-user=}"; [ -n "$OS_USER" ] || { echo "--os-user needs a name" >&2; exit 2; }; shift ;;
40
+ --allow-root) ROOT_OK=1; shift ;;
41
+ # The agents to install (each kept for the run as another user, below).
42
+ --no-claude) WANT_CLAUDE=""; AGENT_ARGS+=("$1"); shift ;;
43
+ --codex) WANT_CODEX=1; AGENT_ARGS+=("$1"); shift ;;
44
+ --grok) WANT_GROK=1; AGENT_ARGS+=("$1"); shift ;;
45
+ *) ARGS+=("$1"); shift ;;
46
+ esac
47
+ done
48
+ if [ -n "$CODE_FILE" ]; then
49
+ [ -f "$CODE_FILE" ] || { echo "--code-file: $CODE_FILE is not there" >&2; exit 2; }
50
+ CODE="$(cat "$CODE_FILE")"
51
+ rm -f "$CODE_FILE"
52
+ fi
53
+ if [ -z "$SERVER" ] || [ -z "$CODE" ]; then
54
+ echo "usage: linux.sh <server-url> --code-file <file> [--allow-home] [--insecure] [--no-service] [--company <id>] [--os-user <name>]" >&2
55
+ exit 2
56
+ fi
57
+
58
+ say() { printf '\n\033[1m==> %s\033[0m\n' "$*"; }
59
+ as_root() { if [ "$(id -u)" -eq 0 ]; then "$@"; else sudo "$@"; fi }
60
+ install_pkg() {
61
+ if command -v apt-get >/dev/null 2>&1; then { as_root apt-get update -qq || true; } && as_root apt-get install -y "$@"
62
+ elif command -v dnf >/dev/null 2>&1; then as_root dnf install -y "$@"
63
+ elif command -v pacman >/dev/null 2>&1; then as_root pacman -S --needed --noconfirm "$@"
64
+ elif command -v zypper >/dev/null 2>&1; then as_root zypper install -y "$@"
65
+ else echo "Install $* with your package manager, then run this command again." >&2; exit 1
66
+ fi
67
+ }
68
+
69
+ # Another system user for this company's sessions, created if needed: what
70
+ # really keeps companies apart on one machine. The rest runs again as that user.
71
+ if [ -n "$OS_USER" ]; then
72
+ case "$OS_USER" in
73
+ ""|root|*[!a-z0-9_-]*|[!a-z_]*) echo "--os-user: \"$OS_USER\" is not a name for a new user (lowercase letters, digits, - and _)" >&2; exit 2 ;;
74
+ esac
75
+ [ "$(id -u)" -eq 0 ] || { echo "--os-user needs root: run this with sudo." >&2; exit 1; }
76
+ if ! id "$OS_USER" >/dev/null 2>&1; then
77
+ say "Creating the system user $OS_USER"
78
+ useradd -m -s /bin/bash "$OS_USER"
79
+ # (Many systems leave a new home readable by everyone: that isn't apart.)
80
+ chmod 700 "$(getent passwd "$OS_USER" | cut -d: -f6)"
81
+ elif [ "$(id -u "$OS_USER")" -lt 1000 ]; then
82
+ # (A system account: its sessions would have whatever rights it has.)
83
+ echo "--os-user: $OS_USER is an account of the system, not a person's or a company's: choose another name." >&2
84
+ exit 2
85
+ fi
86
+ if ! command -v tmux >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1; then install_pkg tmux curl; fi
87
+ # (So its service keeps running without anyone logged in as it.)
88
+ loginctl enable-linger "$OS_USER" 2>/dev/null || true
89
+ AS_USER_ENV=("HOME=$(getent passwd "$OS_USER" | cut -d: -f6)" "XDG_RUNTIME_DIR=/run/user/$(id -u "$OS_USER")" "PATH=$PATH")
90
+ SWITCH=(runuser -u "$OS_USER" --)
91
+ command -v runuser >/dev/null 2>&1 || SWITCH=(sudo -H -u "$OS_USER")
92
+ # This same script, already checked, and the code, in a folder of that user.
93
+ WORK="$(mktemp -d)"
94
+ if [ -f "$SELF" ] && [ "${BASH_SOURCE[0]:-}" = "$SELF" ]; then cp "$SELF" "$WORK/install.sh"
95
+ else curl -fsSLo "$WORK/install.sh" "${SERVER%/}/install/linux.sh" # (Piped in, as older commands did: there is no file to copy.)
96
+ fi
97
+ printf %s "$CODE" > "$WORK/code"
98
+ chown -R "$OS_USER" "$WORK"
99
+ RC=0
100
+ ( cd "$WORK" && "${SWITCH[@]}" env "${AS_USER_ENV[@]}" bash install.sh "$SERVER" --code-file code ${SHA:+--sha256 "$SHA"} ${AGENT_ARGS[@]+"${AGENT_ARGS[@]}"} ${ARGS[@]+"${ARGS[@]}"} ) || RC=$?
101
+ rm -rf "$WORK"
102
+ exit $RC
103
+ fi
104
+
105
+ if [ "$(id -u)" -eq 0 ] && [ -z "$ROOT_OK" ]; then
106
+ echo "This is root: sessions run as the user who installs them, so they would have full control of this machine." >&2
107
+ echo "Run it as your own user, or add --allow-root to the command if that is what you want (to let Claude change the system)." >&2
108
+ exit 1
109
+ fi
110
+ if [ "$(id -u)" -eq 0 ]; then
111
+ say "Installing as root: sessions will have full control of this machine"
112
+ fi
113
+
114
+ # 1. tmux (and curl, for what follows)
115
+ if ! command -v tmux >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1; then
116
+ say "Installing tmux (it may ask for your password)"
117
+ install_pkg tmux curl
118
+ fi
119
+
120
+ # 2. Node.js 22.13 or later (with nvm, in your home, if missing or older)
121
+ # (On WSL, what Windows installed isn't usable here: /mnt/c/…)
122
+ native() {
123
+ p="$(command -v "$1" 2>/dev/null)" || return 1
124
+ case "$(uname -r)" in *[Mm]icrosoft*) case "$p" in /mnt/*) return 1 ;; esac ;; esac
125
+ }
126
+ node_ok() { native node && node -e 'const [a,b]=process.versions.node.split(".").map(Number);process.exit(a>22||(a===22&&b>=13)?0:1)'; }
127
+ if ! node_ok; then
128
+ say "Installing Node.js 22 (with nvm, in your home folder)"
129
+ export NVM_DIR="$HOME/.nvm"
130
+ [ -s "$NVM_DIR/nvm.sh" ] || curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
131
+ set +eu; . "$NVM_DIR/nvm.sh"; nvm install 22 && nvm alias default 22; set -eu
132
+ node_ok || { echo "Node.js 22 could not be installed: install Node.js 22.13 or later, then run this command again." >&2; exit 1; }
133
+ fi
134
+
135
+ # 3. The agents chosen, each in this user's home (no sudo), each from its
136
+ # maker: Claude Code and Grok CLI with their own installers, Codex CLI from npm.
137
+ export PATH="$HOME/.local/bin:$PATH"
138
+ if [ -n "$WANT_CLAUDE" ] && ! native claude; then
139
+ say "Installing Claude Code"
140
+ curl -fsSL https://claude.ai/install.sh | bash
141
+ fi
142
+ if [ -n "$WANT_CODEX" ] && ! native codex; then
143
+ say "Installing Codex CLI"
144
+ npm install -g --prefix "$HOME/.local" @openai/codex
145
+ fi
146
+ if [ -n "$WANT_GROK" ] && ! native grok; then
147
+ say "Installing Grok CLI"
148
+ curl -fsSL https://x.ai/cli/install.sh | bash
149
+ fi
150
+
151
+ # New terminals find the agents and "pisha-host" in ~/.local/bin.
152
+ for rc in "$HOME/.bashrc" "$HOME/.zshrc"; do
153
+ if [ -f "$rc" ] && ! grep -q '\.local/bin' "$rc"; then
154
+ # (Managed elsewhere and read-only, as with home-manager: not worth stopping for.)
155
+ { printf '\n# Added by the Pisha installer\nexport PATH="$HOME/.local/bin:$PATH"\n' >> "$rc"; } 2>/dev/null || echo "Could not add ~/.local/bin to $rc: add it to your PATH yourself." >&2
156
+ fi
157
+ done
158
+
159
+ # 4. pisha-host: downloaded into a new private folder, checked, and run.
160
+ say "Joining this machine to $SERVER"
161
+ DIR="$(mktemp -d)"
162
+ cd "$DIR"
163
+ curl -fsSLo pisha-host.mjs "${SERVER%/}/host/pisha-host.mjs"
164
+ if [ -n "$SHA" ]; then
165
+ echo "$SHA pisha-host.mjs" | sha256sum -c - >/dev/null || { echo "pisha-host.mjs does not match the dashboard's checksum: stopped." >&2; exit 1; }
166
+ fi
167
+ printf %s "$CODE" > code
168
+ node pisha-host.mjs enroll "$SERVER" --code-file=code ${ARGS[@]+"${ARGS[@]}"}
169
+
170
+ say "Done"
171
+ case " ${ARGS[*]-} " in
172
+ *" --company="*) ;; # (It has said how: this company has its own login.)
173
+ *)
174
+ echo "If you haven't yet, sign in to each agent once in a terminal, so its sessions can start:"
175
+ [ -z "$WANT_CLAUDE" ] || echo " claude (then /login if it asks)"
176
+ [ -z "$WANT_CODEX" ] || echo " codex login"
177
+ [ -z "$WANT_GROK" ] || echo " grok login" ;;
178
+ esac
179
+ }
180
+
181
+ main "$@"