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
@@ -0,0 +1,231 @@
1
+ import { cutText, cleanText, now, ApiError, bad } from '../platform/index.js'
2
+
3
+ export function createObservation(platform) {
4
+ const { db, inTx, bus, broadcast, spendStorage, ensureRoom, quota } = platform
5
+ const eventKeptMs = () => quota('event_hours', Number(process.env.OBSERVE_TTL_HOURS ?? 24)) * 60 * 60 * 1000
6
+
7
+ const MAX_EVENTS = Number(process.env.PISHA_MAX_EVENTS ?? 1_000_000) // observation events kept, in all
8
+
9
+ // Each session's plugin posts what it's doing (hook events + transcript). The
10
+ // server keeps 24h of events, derives a current state per session, and pushes
11
+ // everything to dashboard clients as it happens.
12
+ const EVENT_KINDS = new Set([
13
+ 'observe_start', 'session_start', 'prompt', 'tool_start', 'tool_end', 'text', 'usage',
14
+ 'notification', 'subagent_start', 'subagent_stop', 'stop', 'compact', 'compacted', 'session_end', 'tokens',
15
+ ])
16
+ const MAX_EVENT_JSON = 20_000
17
+ const activity = new Map() // name -> derived state
18
+ const BUSY = ['working', 'tool', 'compacting'] // (at work: not idle, waiting or ended)
19
+
20
+ // An event as seen by the dashboard. The plugin's own "id" (tool use id or
21
+ // subagent id) is exposed as "ref"; "id" is always the event's row id.
22
+ // What each kind of event may carry, and of which type. Anything else is
23
+ // dropped — the dashboard renders these fields, so nothing a session sends
24
+ // reaches it untyped (and no event can pass itself off as a message).
25
+ // (Cut before cleaning too: cleaning costs the whole text.)
26
+ const STR = max => v => (typeof v === 'string' ? cutText(cleanText(v.slice(0, max * 2)), max) : undefined)
27
+ const INT = v => (Number.isSafeInteger(v) && v >= 0 ? v : undefined)
28
+ const PCT = v => (Number.isFinite(v) ? Math.max(0, Math.min(100, Math.round(v))) : undefined)
29
+ const BOOL = v => (typeof v === 'boolean' ? v : undefined)
30
+ const EVENT_COMMON = { cwd: STR(1000), agent: STR(100) }
31
+ const EVENT_SCHEMA = {
32
+ observe_start: { level: STR(20) },
33
+ session_start: { source: STR(40), model: STR(100) },
34
+ prompt: { text: STR(20_000), channel: BOOL },
35
+ tool_start: { id: STR(100), tool: STR(200), summary: STR(2000), what: STR(300), detail: STR(20_000) },
36
+ tool_end: { id: STR(100), tool: STR(200), ok: BOOL, interrupted: BOOL, summary: STR(2000), duration_ms: INT, detail: STR(20_000) },
37
+ text: { text: STR(20_000) },
38
+ usage: { context_tokens: INT, model: STR(100), context_window: INT, compact_at: INT, context_pct: PCT },
39
+ notification: { type: STR(60), text: STR(1000) },
40
+ subagent_start: { id: STR(100) },
41
+ subagent_stop: { id: STR(100), text: STR(20_000) },
42
+ stop: { background_tasks: INT },
43
+ compact: { trigger: STR(20) },
44
+ compacted: { trigger: STR(20), summary: STR(20_000) },
45
+ session_end: { reason: STR(100) },
46
+ // A model call's tokens (or a turn's, for an agent that keeps them by the
47
+ // turn): kept added up by the usage module, not as an event.
48
+ tokens: { model: STR(100), input: INT, cache_read: INT, cache_write: INT, output: INT, calls: INT, sub: BOOL, cause: STR(20), msg: INT, task: STR(40) },
49
+ }
50
+ function cleanEvent(kind, data) {
51
+ const out = {}
52
+ const schema = { ...EVENT_COMMON, ...(EVENT_SCHEMA[kind] ?? {}) }
53
+ if (!data || typeof data !== 'object') return out
54
+ for (const [k, check] of Object.entries(schema)) {
55
+ if (!Object.hasOwn(data, k)) continue
56
+ const v = check(data[k])
57
+ if (v !== undefined) out[k] = v
58
+ }
59
+ return out
60
+ }
61
+
62
+ // (Stored events were cleaned when they came in: read back as they are,
63
+ // never cleaned again — that would cost the whole text on every read.)
64
+ function eventView(rowId, session, ts, kind, data, { stored = false } = {}) {
65
+ const { id: ref, ...rest } = stored ? (data && typeof data === 'object' ? data : {}) : cleanEvent(kind, data)
66
+ return { ...rest, ...(ref != null ? { ref } : {}), id: rowId, session, ts, kind }
67
+ }
68
+
69
+ function activityOf(name) {
70
+ if (!activity.has(name)) activity.set(name, { state: 'unknown', since: null, last_event_at: null })
71
+ return activity.get(name)
72
+ }
73
+
74
+ function applyEvent(name, ev) {
75
+ const a = activityOf(name)
76
+ // (busy_since: when it set to work, kept while it goes from tool to text and
77
+ // back; it ends when it stops, waits on someone or ends.)
78
+ const set = state => {
79
+ if (a.state === state) return
80
+ const was = BUSY.includes(a.state)
81
+ a.state = state; a.since = ev.ts
82
+ if (!BUSY.includes(state)) a.busy_since = null
83
+ else if (!was || a.busy_since == null) a.busy_since = ev.ts
84
+ }
85
+ a.last_event_at = Math.max(a.last_event_at ?? 0, ev.ts)
86
+ if (typeof ev.cwd === 'string') a.cwd = ev.cwd
87
+ switch (ev.kind) {
88
+ case 'observe_start': a.observe = ev.level; if (ev.cwd) a.cwd = ev.cwd; if (a.state === 'unknown' || a.state === 'ended') set('idle'); break
89
+ case 'session_start':
90
+ if (ev.cwd) a.cwd = ev.cwd
91
+ if (ev.model) a.model = ev.model
92
+ // (Cleared: a fresh context, its size unknown until the next response.)
93
+ if (ev.source === 'clear') { a.context_tokens = null; a.context_pct = null; a.context_warned = false }
94
+ set('idle')
95
+ break
96
+ case 'prompt': set('working'); break
97
+ case 'tool_start':
98
+ if (ev.agent) break // tools run by subagents: the main session is inside its Task/Agent tool
99
+ a.tool = { id: ev.ref, name: ev.tool, summary: ev.summary, ...(ev.what ? { what: ev.what } : {}), since: ev.ts }
100
+ set('tool')
101
+ break
102
+ case 'tool_end':
103
+ if (ev.agent) break
104
+ if (!a.tool || !ev.ref || a.tool.id === ev.ref) { a.tool = null; set('working') }
105
+ break
106
+ // (Claude's text is read from its transcript, so the last one of a turn
107
+ // can arrive after the turn ended: one written before that end doesn't
108
+ // make the session "working" again.)
109
+ case 'text': if (a.state !== 'waiting' && !(a.state === 'idle' && a.stopped_at && ev.ts <= a.stopped_at)) set('working'); break
110
+ case 'usage':
111
+ a.context_tokens = ev.context_tokens
112
+ if (ev.model) a.model = ev.model
113
+ if (ev.compact_at) { a.compact_at = ev.compact_at; a.context_window = ev.context_window; a.context_pct = ev.context_pct }
114
+ break
115
+ case 'notification':
116
+ if (['permission_prompt', 'elicitation_dialog', 'agent_needs_input', 'elicitation_url_dialog'].includes(ev.type)) { a.waiting = ev.text; set('waiting') }
117
+ else if (ev.type === 'idle_prompt') set('idle')
118
+ break
119
+ case 'stop': a.tool = null; a.stopped_at = ev.ts; set('idle'); break
120
+ case 'compact': set('compacting'); break
121
+ case 'compacted':
122
+ // Fresh context: the size is unknown until the next model response.
123
+ a.context_tokens = null; a.context_pct = null; a.context_warned = false
124
+ if (a.state === 'compacting') set('working')
125
+ break
126
+ case 'session_end': a.tool = null; set('ended'); break
127
+ }
128
+ if (a.state !== 'waiting') a.waiting = null
129
+ }
130
+
131
+ // Per identity: at most 120 observe calls and 3000 events a minute.
132
+ const observeLog = new Map() // name -> [{ t, n }]
133
+
134
+ function observeBudget(name, n) {
135
+ // And at most 30 000 events an hour per session: the events kept in all are
136
+ // capped, and one session must not push everybody else's out.
137
+ // (The per-minute limit first: a call it refuses doesn't use up the hour's.)
138
+ const t = now()
139
+ const recent = (observeLog.get(name) ?? []).filter(x => t - x.t < 60_000)
140
+ const events = recent.reduce((sum, x) => sum + x.n, 0)
141
+ if (recent.length >= 120 || events + n > 3000) throw new ApiError(429, 'Too Many Requests: observation rate limit', { parameters: { retry_after: 10 } })
142
+ spendStorage('eventcount', name, n, 30_000)
143
+ recent.push({ t, n })
144
+ observeLog.set(name, recent)
145
+ }
146
+
147
+ function observe(name, p) {
148
+ const events = Array.isArray(p.events) ? p.events : null
149
+ if (!events || events.length > 200) throw bad('events must be an array of at most 200 items')
150
+ ensureRoom()
151
+ observeBudget(name, events.length)
152
+ const insert = db.prepare('INSERT INTO events (session, ts, kind, data) VALUES (?, ?, ?, ?)')
153
+ // The whole batch is checked first, then stored at once: all of it or none
154
+ // (a refusal halfway would store part of it and the retry would repeat it).
155
+ const batch = [], tokens = []
156
+ for (const ev of events) {
157
+ if (!ev || typeof ev !== 'object' || !EVENT_KINDS.has(ev.kind)) continue
158
+ // Whole milliseconds within the events' lifetime: the history cursor relies on it.
159
+ // (Tokens are kept far longer than events: one reported late keeps its day, up to 30 back.)
160
+ const oldest = ev.kind === 'tokens' ? now() - 30 * 24 * 3600_000 : now() - eventKeptMs()
161
+ const ts = Number.isSafeInteger(ev.ts) ? Math.max(oldest, Math.min(ev.ts, now() + 5000)) : now()
162
+ const kind = ev.kind
163
+ const rest = cleanEvent(kind, ev)
164
+ if (kind === 'tokens') { tokens.push({ ...rest, ts }); continue }
165
+ const data = JSON.stringify(rest)
166
+ if (data.length > MAX_EVENT_JSON) continue
167
+ batch.push({ ts, kind, rest, data })
168
+ }
169
+ // Charged on what was sent, not on what is kept: text cleaned away (it
170
+ // cost the cleaning all the same) counts too.
171
+ spendStorage('events', name, Math.max(batch.reduce((n, e) => n + e.data.length, 0), Math.min(JSON.stringify(events).length, 1_048_576)))
172
+ let stored = 0
173
+ inTx(() => { for (const { ts, kind, rest, data } of batch) {
174
+ const info = insert.run(name, ts, kind, data)
175
+ const view = eventView(Number(info.lastInsertRowid), name, ts, kind, rest, { stored: true })
176
+ const before = activityOf(name)
177
+ const wasWarned = !!before.context_warned
178
+ applyEvent(name, view)
179
+ contextNotices(name, view, wasWarned)
180
+ if (kind === 'session_start' && rest.source === 'clear') bus.emit('context-cleared', name)
181
+ broadcast('event', view)
182
+ stored++
183
+ } })
184
+ if (stored) bus.emit('session-changed', name)
185
+ if (tokens.length) bus.emit('tokens', name, tokens)
186
+ return { stored: stored + tokens.length }
187
+ }
188
+
189
+ // Tell a worker's coordinator when its context is nearly full (once per fill-up)
190
+ // and when it compacts. Only live events, never the startup replay.
191
+ const CONTEXT_WARN_PCT = 80
192
+ const NOTICE_COOLDOWN_MS = Number(process.env.PISHA_NOTICE_COOLDOWN_MS ?? 5 * 60_000) // per worker, per kind
193
+ function contextNotices(name, ev, wasWarned) {
194
+ const a = activityOf(name)
195
+ if (ev.kind === 'usage' && ev.context_pct != null && ev.context_pct >= CONTEXT_WARN_PCT && !wasWarned) {
196
+ a.context_warned = true
197
+ // Its own cooldown too: compaction events reset the flag.
198
+ if (now() - (a.context_notice_at ?? 0) < NOTICE_COOLDOWN_MS) return
199
+ a.context_notice_at = now()
200
+ bus.emit('notice', name, `📈 ${name} has used ${ev.context_pct}% of its context; it will auto-compact soon. Avoid giving it a large new task now, or prefer a worker with more room.`)
201
+ }
202
+ if (ev.kind === 'compacted') {
203
+ // At most one compaction notice every 5 minutes per worker: alternating
204
+ // usage/compacted events must not flood the coordinator.
205
+ if (now() - (a.compact_notice_at ?? 0) < NOTICE_COOLDOWN_MS) return
206
+ a.compact_notice_at = now()
207
+ bus.emit('notice', name, `🗜️ ${name} compacted its context (${ev.trigger === 'manual' ? 'manual' : 'automatic'}). Its Pisha role and the latest messages it received were restored; if its task depends on details only you know, send them to it again.`)
208
+ }
209
+ }
210
+
211
+ const observationMethods = {
212
+ observe,
213
+ }
214
+
215
+ function cleanupEvents() {
216
+ const t = now()
217
+ db.prepare('DELETE FROM events WHERE ts < ?').run(t - eventKeptMs())
218
+ // Over the cap: the oldest go first.
219
+ db.prepare('DELETE FROM events WHERE id <= (SELECT id FROM events ORDER BY id DESC LIMIT 1 OFFSET ?)').run(quota('max_events', MAX_EVENTS))
220
+ for (const [k, v] of observeLog) if (!v.some(x => t - x.t < 60_000)) observeLog.delete(k)
221
+ }
222
+
223
+ // Rebuild each session's derived state from the stored events (last 24h).
224
+ function restoreActivity() {
225
+ for (const r of db.prepare('SELECT * FROM events ORDER BY id').iterate()) {
226
+ applyEvent(r.session, eventView(r.id, r.session, r.ts, r.kind, JSON.parse(r.data), { stored: true }))
227
+ }
228
+ }
229
+
230
+ return { observationMethods, cleanupEvents, restoreActivity, cleanEvent, activityOf, activity, eventView }
231
+ }
@@ -0,0 +1 @@
1
+ export { createOrganization } from './organization.js'
@@ -0,0 +1,218 @@
1
+ import { bad, unix, now, cleanText, oneLine } from '../platform/index.js'
2
+
3
+ export function createOrganization(platform, { sessions, messaging, observation, machines }) {
4
+ const { db, broadcast, inTx, bus, readLimit, log } = platform
5
+ const {
6
+ roleOf, isOnline, presenceOf, personaView, NAME_RE, linkKey, linked, linksOf, identityExists,
7
+ } = sessions
8
+ const { related } = messaging
9
+ const { activity } = observation
10
+ const { PERSONA_ID_RE, hostRow, hostLinks, askHost } = machines
11
+
12
+ const organizationMethods = {
13
+ // A coordinator's own squad, as the user described it in the dashboard:
14
+ // its name and goal, and what the coordinator itself is for. Nothing for
15
+ // workers: their coordinator gives them the context each task needs.
16
+ // (With how many of its workers are connected: with none, it does its
17
+ // squad's work itself.)
18
+ squadBrief(name) {
19
+ readLimit(name, 'brief')
20
+ if (roleOf(name) !== 'coordinator') return null
21
+ const sq = squadInfo(name)
22
+ const description = db.prepare('SELECT description FROM identities WHERE name = ?').get(name)?.description || null
23
+ const workers = db.prepare("SELECT name FROM identities WHERE role = 'worker' AND coordinator = ?").all(name).filter(r => isOnline(r.name)).length
24
+ return { title: sq?.title ?? null, goal: sq?.goal ?? null, description, workers_online: workers }
25
+ },
26
+
27
+ // A session sees who exists (and when it was registered, for the
28
+ // coordinator pin), but presence, queue and context only of sessions it
29
+ // talks to: messages both ways, or a group they share.
30
+ getChat(name, p) {
31
+ readLimit(name, 'chat') // its own budget: other reads can't use it up
32
+ const id = String(p.chat_id ?? '')
33
+ if (id.startsWith('#')) {
34
+ const members = db.prepare('SELECT name FROM group_members WHERE group_id = ?').all(id).map(r => r.name)
35
+ if (!members.includes(name)) throw bad('chat not found')
36
+ return { id, type: 'group', title: id, members }
37
+ }
38
+ const ident = db.prepare('SELECT created_at, epoch FROM identities WHERE name = ?').get(id)
39
+ if (!ident) throw bad('chat not found')
40
+ // Writing to a session isn't enough (anyone can): it has to have written back.
41
+ // (Only messages since both current identities exist: a name deleted and
42
+ // registered again starts with no relations.)
43
+ if (!related(name, id)) return { id, type: 'private', username: id, created_at: unix(ident.created_at), pisha_identity: ident.epoch, presence_hidden: true }
44
+ const a = activity.get(id)
45
+ return {
46
+ id, type: 'private', username: id, created_at: unix(ident.created_at), pisha_identity: ident.epoch, ...presenceOf(id),
47
+ context: a?.context_pct != null ? { pct: a.context_pct, tokens: a.context_tokens, compact_at: a.compact_at } : null,
48
+ persona: personaView(id),
49
+ // What the dashboard says it is for, and of its squad when it leads
50
+ // one: for coordinators only (workers get their context from theirs).
51
+ ...(roleOf(name) === 'coordinator' ? {
52
+ // (Busy or free: whether to give it work now.)
53
+ state: ['idle', 'working', 'tool', 'waiting', 'compacting', 'ended'].includes(a?.state) ? a.state : null,
54
+ description: db.prepare('SELECT description FROM identities WHERE name = ?').get(id)?.description || null,
55
+ squad: roleOf(id) === 'coordinator' ? squadInfo(id) : null,
56
+ } : {}),
57
+ }
58
+ },
59
+ }
60
+
61
+ // Squad templates: a coordinator and its workers (name, folder, persona,
62
+ // compact window each), saved to open them all again in one go. Only what
63
+ // the dashboard asks a machine for anyway, one session at a time: each
64
+ // machine still checks every session against its own rules.
65
+ const TEMPLATE_NAME_RE = /^[\p{L}\p{N} ._-]{1,40}$/u
66
+ const TEMPLATES_MAX = 50
67
+ function templateMember(m, role) {
68
+ if (!m || typeof m !== 'object') throw bad('each member of a template needs a name and a folder')
69
+ const name = String(m.name ?? '')
70
+ if (!NAME_RE.test(name)) throw bad(`invalid session name "${cleanText(name.slice(0, 40))}" in the template`)
71
+ const folder = typeof m.folder === 'string' ? m.folder.trim() : ''
72
+ if (!folder.startsWith('/') || folder.length > 4096 || /[\x00-\x1f\x7f]/.test(folder)) throw bad(`"${name}" needs an absolute folder`)
73
+ const persona = m.persona == null || m.persona === '' ? null : String(m.persona)
74
+ if (persona && !PERSONA_ID_RE.test(persona)) throw bad(`invalid persona for "${name}"`)
75
+ const compact = m.compact_window == null || m.compact_window === '' ? null : Number(m.compact_window)
76
+ if (compact !== null && !(Number.isInteger(compact) && compact >= 50_000 && compact <= 1_000_000)) throw bad(`invalid compact window for "${name}"`)
77
+ return { name, role, folder, persona, compact_window: compact }
78
+ }
79
+ function saveTemplate(p) {
80
+ const name = String(p.name ?? '').trim()
81
+ if (!TEMPLATE_NAME_RE.test(name)) throw bad('the template name may have letters, digits, spaces, dots, dashes and underscores (max 40)')
82
+ const host = p.host == null || p.host === '' ? null : String(p.host)
83
+ if (host && !hostRow(host)) throw bad('host not found')
84
+ const coordinator = templateMember(p.coordinator, 'coordinator')
85
+ const workers = (Array.isArray(p.workers) ? p.workers : []).map(w => templateMember(w, 'worker'))
86
+ if (workers.length > 30) throw bad('a template has at most 30 workers')
87
+ const names = [coordinator.name, ...workers.map(w => w.name)]
88
+ if (new Set(names).size !== names.length) throw bad('every session in a template needs its own name')
89
+ const exists = db.prepare('SELECT 1 FROM squad_templates WHERE name = ?').get(name)
90
+ if (!exists && db.prepare('SELECT COUNT(*) AS n FROM squad_templates').get().n >= TEMPLATES_MAX) throw bad(`at most ${TEMPLATES_MAX} templates`)
91
+ const spec = { host, coordinator, workers }
92
+ db.prepare('INSERT INTO squad_templates (name, spec, created_at) VALUES (?, ?, ?) ON CONFLICT(name) DO UPDATE SET spec = excluded.spec').run(name, JSON.stringify(spec), now())
93
+ broadcast('templates', listTemplates())
94
+ return { name, ...spec }
95
+ }
96
+ function deleteTemplate(name) {
97
+ if (!db.prepare('DELETE FROM squad_templates WHERE name = ?').run(name).changes) throw bad('template not found')
98
+ broadcast('templates', listTemplates())
99
+ return { name, deleted: true }
100
+ }
101
+ function listTemplates() {
102
+ return db.prepare('SELECT name, spec, created_at FROM squad_templates ORDER BY name').all().map(r => {
103
+ let spec = {}
104
+ try { spec = JSON.parse(r.spec) } catch {}
105
+ return { name: r.name, created_at: r.created_at, host: spec.host ?? null, coordinator: spec.coordinator ?? null, workers: Array.isArray(spec.workers) ? spec.workers : [] }
106
+ })
107
+ }
108
+
109
+ // Links between squads: two coordinators that may message each other. Set
110
+ // here; each coordinator's machine is told (its plugin lets the other one in
111
+ // while the session runs) and checks it against its own rules.
112
+ const LINKS_MAX = 100
113
+ const LINKS_PER_COORDINATOR = 20
114
+ const isCoordinator = name => {
115
+ const r = db.prepare('SELECT role, opened_role FROM identities WHERE name = ?').get(name)
116
+ return !!r && (r.role === 'coordinator' || (r.role == null && r.opened_role === 'coordinator'))
117
+ }
118
+ function listLinks() {
119
+ // (With when they last wrote to each other, within the hour: the org chart
120
+ // shows how busy each link is, next to the cap.)
121
+ const since = now() - 3600_000
122
+ const recent = db.prepare('SELECT created_at FROM messages WHERE ((from_name = ? AND target = ?) OR (from_name = ? AND target = ?)) AND system = 0 AND auto = 0 AND created_at >= ? ORDER BY created_at DESC LIMIT 100')
123
+ return db.prepare('SELECT a, b, created_at FROM squad_links ORDER BY a, b').all()
124
+ .map(l => ({ ...l, recent: recent.all(l.a, l.b, l.b, l.a, since).map(r => r.created_at) }))
125
+ }
126
+ async function changeLink(p, add) {
127
+ const x = String(p.a ?? ''), y = String(p.b ?? '')
128
+ if (!NAME_RE.test(x) || !NAME_RE.test(y)) throw bad('two session names are needed')
129
+ if (x === y) throw bad('a coordinator is not linked with itself')
130
+ const [a, b] = linkKey(x, y)
131
+ if (add) {
132
+ for (const n of [a, b]) if (!isCoordinator(n)) throw bad(`"${n}" is not a coordinator`)
133
+ if (linked(a, b)) throw bad(`"${a}" and "${b}" are already linked`)
134
+ if (db.prepare('SELECT COUNT(*) AS n FROM squad_links').get().n >= LINKS_MAX) throw bad(`at most ${LINKS_MAX} links`)
135
+ for (const n of [a, b]) if (linksOf(n).length >= LINKS_PER_COORDINATOR) throw bad(`"${n}" already has ${LINKS_PER_COORDINATOR} links`)
136
+ db.prepare('INSERT INTO squad_links (a, b, created_at) VALUES (?, ?, ?)').run(a, b, now())
137
+ } else if (!db.prepare('DELETE FROM squad_links WHERE a = ? AND b = ?').run(a, b).changes) {
138
+ throw bad('those two are not linked')
139
+ }
140
+ broadcast('links', listLinks())
141
+ log(`${add ? 'linked' : 'unlinked'} coordinators "${a}" and "${b}"`)
142
+ // (A machine that refuses, or isn't connected: said, the link stays.)
143
+ const warnings = (await Promise.all([a, b].map(pushLinks))).filter(Boolean)
144
+ return { a, b, linked: add, warnings }
145
+ }
146
+
147
+ // Tell the machine running this coordinator what it is linked with now.
148
+ // Returns a warning, or null.
149
+ bus.on('machine-listed', (hostId, info) => {
150
+ for (const t of info?.terminals ?? []) if (t.role === 'coordinator') void pushLinks(t.id)
151
+ })
152
+ async function pushLinks(name) {
153
+ const host = db.prepare('SELECT host_id FROM identities WHERE name = ?').get(name)?.host_id
154
+ if (!host) return null
155
+ // (Only the plugin enforces links: until its machine hears, the old ones hold.)
156
+ if (!hostLinks.get(host)?.info?.terminals?.some(t => t.id === name)) return `${name}: its machine isn't connected or isn't running it: it will be told when it connects`
157
+ try {
158
+ await askHost(host, { t: 'links', name, coordinators: linksOf(name) })
159
+ return null
160
+ } catch (err) {
161
+ return `${name}: ${err.message.replace(/^Bad Request: /, '')}`
162
+ }
163
+ }
164
+
165
+ // The org chart: each squad's title and goal, where its card is, and what
166
+ // each session is for. Written in the dashboard; a coordinator sees the goal
167
+ // of the squads it is linked with (getChat), as data.
168
+ const SQUAD_POS_MAX = 20_000
169
+ function listSquads() {
170
+ return db.prepare('SELECT coordinator, title, goal, x, y FROM squads ORDER BY coordinator').all()
171
+ .map(r => ({ coordinator: r.coordinator, title: r.title || null, goal: r.goal || null, x: r.x, y: r.y }))
172
+ }
173
+ function squadInfo(coordinator) {
174
+ const r = db.prepare('SELECT title, goal FROM squads WHERE coordinator = ?').get(coordinator)
175
+ return r && (r.title || r.goal) ? { title: r.title || null, goal: r.goal || null } : null
176
+ }
177
+ function describeSquad(p) {
178
+ const coordinator = String(p.coordinator ?? '')
179
+ if (!NAME_RE.test(coordinator) || !isCoordinator(coordinator)) throw bad(`"${cleanText(coordinator.slice(0, 40))}" is not a coordinator`)
180
+ const title = oneLine(p.title, 40), goal = oneLine(p.goal, 300)
181
+ db.prepare(`INSERT INTO squads (coordinator, title, goal, updated_at) VALUES (?, ?, ?, ?)
182
+ ON CONFLICT(coordinator) DO UPDATE SET title = excluded.title, goal = excluded.goal, updated_at = excluded.updated_at`).run(coordinator, title || null, goal || null, now())
183
+ broadcast('squads', listSquads())
184
+ return { coordinator, title: title || null, goal: goal || null }
185
+ }
186
+ function placeSquads(p) {
187
+ const list = Array.isArray(p.positions) ? p.positions : null
188
+ if (!list || !list.length || list.length > 200) throw bad('positions: a list of 1 to 200 {coordinator, x, y}')
189
+ const clamp = v => Math.round(Math.min(SQUAD_POS_MAX, Math.max(0, v)))
190
+ const rows = list.map(q => {
191
+ const coordinator = String(q?.coordinator ?? '')
192
+ if (!NAME_RE.test(coordinator) || !isCoordinator(coordinator)) throw bad(`"${cleanText(coordinator.slice(0, 40))}" is not a coordinator`)
193
+ if (!Number.isFinite(q.x) || !Number.isFinite(q.y)) throw bad('x and y must be numbers')
194
+ return [coordinator, clamp(q.x), clamp(q.y)]
195
+ })
196
+ inTx(() => {
197
+ for (const [c, x, y] of rows) {
198
+ db.prepare(`INSERT INTO squads (coordinator, x, y, updated_at) VALUES (?, ?, ?, ?)
199
+ ON CONFLICT(coordinator) DO UPDATE SET x = excluded.x, y = excluded.y, updated_at = excluded.updated_at`).run(c, x, y, now())
200
+ }
201
+ })
202
+ broadcast('squads', listSquads())
203
+ return { placed: rows.length }
204
+ }
205
+ function describeSession(p) {
206
+ const name = String(p.name ?? '')
207
+ if (!NAME_RE.test(name) || !identityExists(name)) throw bad('session not found')
208
+ const description = oneLine(p.description, 300)
209
+ db.prepare('UPDATE identities SET description = ? WHERE name = ?').run(description || null, name)
210
+ bus.emit('session-changed', name)
211
+ return { name, description: description || null }
212
+ }
213
+
214
+ return {
215
+ organizationMethods, listTemplates, listLinks, listSquads, pushLinks, saveTemplate, deleteTemplate,
216
+ changeLink, describeSquad, placeSquads, describeSession,
217
+ }
218
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "pisha-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.12",
4
+ "description": "Pisha: run teams of AI coding agents (Claude Code, Codex, Grok) from a self-hosted dashboard, with an inbox for your decisions",
5
+ "keywords": [
6
+ "pisha",
7
+ "claude-code",
8
+ "agents",
9
+ "multi-agent",
10
+ "orchestration",
11
+ "self-hosted",
12
+ "dashboard"
13
+ ],
14
+ "type": "module",
15
+ "license": "MIT",
16
+ "engines": {
17
+ "node": ">=22.13"
18
+ },
19
+ "bin": {
20
+ "pisha-server": "./server.js"
21
+ },
22
+ "files": [
23
+ "*.js",
24
+ "accounts",
25
+ "boards",
26
+ "dashboard",
27
+ "machines",
28
+ "messaging",
29
+ "observation",
30
+ "organization",
31
+ "permissions",
32
+ "platform",
33
+ "sessions",
34
+ "ui",
35
+ "usage",
36
+ "vendor",
37
+ "install",
38
+ "pisha-host.mjs",
39
+ "pisha-host.mjs.sig",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "scripts": {
44
+ "start": "node server.js",
45
+ "prepack": "node ../scripts/stage-server.mjs",
46
+ "postpack": "node ../scripts/stage-server.mjs --undo"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/roke22/pisha.git",
54
+ "directory": "server"
55
+ },
56
+ "homepage": "https://github.com/roke22/pisha"
57
+ }
@@ -0,0 +1 @@
1
+ export { createPermissions, CAPABILITIES, CAPABILITY_IDS, BUILTIN_PROFILES, RULE_RE } from './permissions.js'