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.
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/accounts/accounts.js +754 -0
- package/accounts/index.js +1 -0
- package/accounts/passwords.js +41 -0
- package/accounts/totp.js +54 -0
- package/boards/boards.js +1079 -0
- package/boards/github.js +212 -0
- package/boards/index.js +1 -0
- package/boards/sync.js +980 -0
- package/companies.js +294 -0
- package/company-export.js +101 -0
- package/company.js +79 -0
- package/dashboard/dashboard.js +407 -0
- package/dashboard/index.js +1 -0
- package/data-upgrade.js +69 -0
- package/install/linux.sh +181 -0
- package/install/macos.sh +121 -0
- package/install/windows.bat +54 -0
- package/machines/index.js +3 -0
- package/machines/machines.js +910 -0
- package/messaging/inbox.js +252 -0
- package/messaging/index.js +3 -0
- package/messaging/messaging.js +551 -0
- package/messaging/plans.js +67 -0
- package/observation/index.js +1 -0
- package/observation/observation.js +224 -0
- package/organization/index.js +1 -0
- package/organization/organization.js +218 -0
- package/package.json +54 -4
- package/permissions/index.js +1 -0
- package/permissions/permissions.js +211 -0
- package/pisha-host.mjs +3297 -0
- package/pisha-host.mjs.sig +1 -0
- package/platform/acme.js +207 -0
- package/platform/basics.js +14 -0
- package/platform/config.js +154 -0
- package/platform/control.js +93 -0
- package/platform/credentials.js +151 -0
- package/platform/database.js +251 -0
- package/platform/errors.js +13 -0
- package/platform/files.js +50 -0
- package/platform/http.js +207 -0
- package/platform/index.js +58 -0
- package/platform/limits.js +122 -0
- package/platform/listen.js +183 -0
- package/platform/roles.js +6 -0
- package/platform/stream.js +19 -0
- package/platform/text.js +83 -0
- package/platform/ws.js +186 -0
- package/routes.js +405 -0
- package/server.js +65 -0
- package/sessions/index.js +1 -0
- package/sessions/sessions.js +533 -0
- package/ui/LICENSE-affectui.txt +26 -0
- package/ui/addmachine.js +151 -0
- package/ui/api.js +20 -0
- package/ui/app.js +143 -0
- package/ui/attention.js +78 -0
- package/ui/back.js +166 -0
- package/ui/boards.js +958 -0
- package/ui/chat.js +388 -0
- package/ui/content.js +157 -0
- package/ui/dialogs.js +135 -0
- package/ui/doing.js +112 -0
- package/ui/dom.js +6 -0
- package/ui/ds-base.css +146 -0
- package/ui/ds-components.css +229 -0
- package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
- package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
- package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
- package/ui/format.js +25 -0
- package/ui/i18n.js +2093 -0
- package/ui/icons/apple-touch-icon.png +0 -0
- package/ui/icons/icon-192.png +0 -0
- package/ui/icons/icon-512.png +0 -0
- package/ui/icons/maskable-512.png +0 -0
- package/ui/icons.js +40 -0
- package/ui/inbox.js +535 -0
- package/ui/index.html +103 -0
- package/ui/machines.js +261 -0
- package/ui/manifest.webmanifest +16 -0
- package/ui/mosaic.js +189 -0
- package/ui/nav.js +141 -0
- package/ui/newteam.js +223 -0
- package/ui/org.js +653 -0
- package/ui/overlays.css +126 -0
- package/ui/palette.js +179 -0
- package/ui/people.js +370 -0
- package/ui/permissions.js +202 -0
- package/ui/qr.js +158 -0
- package/ui/router.js +171 -0
- package/ui/routes.js +46 -0
- package/ui/screen-boards.css +241 -0
- package/ui/screen-inbox.css +201 -0
- package/ui/screen-machines.css +76 -0
- package/ui/screen-mosaic.css +26 -0
- package/ui/screen-newteam.css +90 -0
- package/ui/screen-org.css +113 -0
- package/ui/screen-session.css +99 -0
- package/ui/screen-signin.css +28 -0
- package/ui/screen-team.css +80 -0
- package/ui/screen-teams.css +41 -0
- package/ui/session.js +42 -0
- package/ui/shell.css +122 -0
- package/ui/signin.js +120 -0
- package/ui/squads.js +370 -0
- package/ui/state.js +59 -0
- package/ui/stream.js +268 -0
- package/ui/styles.css +343 -0
- package/ui/team.js +115 -0
- package/ui/teams.js +58 -0
- package/ui/terminal.js +261 -0
- package/ui/theme.js +32 -0
- package/ui/timeline.js +163 -0
- package/ui/topbar.js +205 -0
- package/ui/voice-parse.js +98 -0
- package/ui/voice.js +320 -0
- package/vendor/InterVariable.woff2 +0 -0
- package/vendor/LICENSE-inter +92 -0
- package/vendor/LICENSE-xterm +21 -0
- package/vendor/README.md +8 -0
- package/vendor/addon-fit.js +2 -0
- package/vendor/xterm.css +218 -0
- package/vendor/xterm.js +2 -0
|
@@ -0,0 +1,224 @@
|
|
|
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',
|
|
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
|
+
}
|
|
47
|
+
function cleanEvent(kind, data) {
|
|
48
|
+
const out = {}
|
|
49
|
+
const schema = { ...EVENT_COMMON, ...(EVENT_SCHEMA[kind] ?? {}) }
|
|
50
|
+
if (!data || typeof data !== 'object') return out
|
|
51
|
+
for (const [k, check] of Object.entries(schema)) {
|
|
52
|
+
if (!Object.hasOwn(data, k)) continue
|
|
53
|
+
const v = check(data[k])
|
|
54
|
+
if (v !== undefined) out[k] = v
|
|
55
|
+
}
|
|
56
|
+
return out
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// (Stored events were cleaned when they came in: read back as they are,
|
|
60
|
+
// never cleaned again — that would cost the whole text on every read.)
|
|
61
|
+
function eventView(rowId, session, ts, kind, data, { stored = false } = {}) {
|
|
62
|
+
const { id: ref, ...rest } = stored ? (data && typeof data === 'object' ? data : {}) : cleanEvent(kind, data)
|
|
63
|
+
return { ...rest, ...(ref != null ? { ref } : {}), id: rowId, session, ts, kind }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function activityOf(name) {
|
|
67
|
+
if (!activity.has(name)) activity.set(name, { state: 'unknown', since: null, last_event_at: null })
|
|
68
|
+
return activity.get(name)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function applyEvent(name, ev) {
|
|
72
|
+
const a = activityOf(name)
|
|
73
|
+
// (busy_since: when it set to work, kept while it goes from tool to text and
|
|
74
|
+
// back; it ends when it stops, waits on someone or ends.)
|
|
75
|
+
const set = state => {
|
|
76
|
+
if (a.state === state) return
|
|
77
|
+
const was = BUSY.includes(a.state)
|
|
78
|
+
a.state = state; a.since = ev.ts
|
|
79
|
+
if (!BUSY.includes(state)) a.busy_since = null
|
|
80
|
+
else if (!was || a.busy_since == null) a.busy_since = ev.ts
|
|
81
|
+
}
|
|
82
|
+
a.last_event_at = Math.max(a.last_event_at ?? 0, ev.ts)
|
|
83
|
+
if (typeof ev.cwd === 'string') a.cwd = ev.cwd
|
|
84
|
+
switch (ev.kind) {
|
|
85
|
+
case 'observe_start': a.observe = ev.level; if (ev.cwd) a.cwd = ev.cwd; if (a.state === 'unknown' || a.state === 'ended') set('idle'); break
|
|
86
|
+
case 'session_start':
|
|
87
|
+
if (ev.cwd) a.cwd = ev.cwd
|
|
88
|
+
if (ev.model) a.model = ev.model
|
|
89
|
+
// (Cleared: a fresh context, its size unknown until the next response.)
|
|
90
|
+
if (ev.source === 'clear') { a.context_tokens = null; a.context_pct = null; a.context_warned = false }
|
|
91
|
+
set('idle')
|
|
92
|
+
break
|
|
93
|
+
case 'prompt': set('working'); break
|
|
94
|
+
case 'tool_start':
|
|
95
|
+
if (ev.agent) break // tools run by subagents: the main session is inside its Task/Agent tool
|
|
96
|
+
a.tool = { id: ev.ref, name: ev.tool, summary: ev.summary, ...(ev.what ? { what: ev.what } : {}), since: ev.ts }
|
|
97
|
+
set('tool')
|
|
98
|
+
break
|
|
99
|
+
case 'tool_end':
|
|
100
|
+
if (ev.agent) break
|
|
101
|
+
if (!a.tool || !ev.ref || a.tool.id === ev.ref) { a.tool = null; set('working') }
|
|
102
|
+
break
|
|
103
|
+
// (Claude's text is read from its transcript, so the last one of a turn
|
|
104
|
+
// can arrive after the turn ended: one written before that end doesn't
|
|
105
|
+
// make the session "working" again.)
|
|
106
|
+
case 'text': if (a.state !== 'waiting' && !(a.state === 'idle' && a.stopped_at && ev.ts <= a.stopped_at)) set('working'); break
|
|
107
|
+
case 'usage':
|
|
108
|
+
a.context_tokens = ev.context_tokens
|
|
109
|
+
if (ev.model) a.model = ev.model
|
|
110
|
+
if (ev.compact_at) { a.compact_at = ev.compact_at; a.context_window = ev.context_window; a.context_pct = ev.context_pct }
|
|
111
|
+
break
|
|
112
|
+
case 'notification':
|
|
113
|
+
if (['permission_prompt', 'elicitation_dialog', 'agent_needs_input', 'elicitation_url_dialog'].includes(ev.type)) { a.waiting = ev.text; set('waiting') }
|
|
114
|
+
else if (ev.type === 'idle_prompt') set('idle')
|
|
115
|
+
break
|
|
116
|
+
case 'stop': a.tool = null; a.stopped_at = ev.ts; set('idle'); break
|
|
117
|
+
case 'compact': set('compacting'); break
|
|
118
|
+
case 'compacted':
|
|
119
|
+
// Fresh context: the size is unknown until the next model response.
|
|
120
|
+
a.context_tokens = null; a.context_pct = null; a.context_warned = false
|
|
121
|
+
if (a.state === 'compacting') set('working')
|
|
122
|
+
break
|
|
123
|
+
case 'session_end': a.tool = null; set('ended'); break
|
|
124
|
+
}
|
|
125
|
+
if (a.state !== 'waiting') a.waiting = null
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Per identity: at most 120 observe calls and 3000 events a minute.
|
|
129
|
+
const observeLog = new Map() // name -> [{ t, n }]
|
|
130
|
+
|
|
131
|
+
function observeBudget(name, n) {
|
|
132
|
+
// And at most 30 000 events an hour per session: the events kept in all are
|
|
133
|
+
// capped, and one session must not push everybody else's out.
|
|
134
|
+
// (The per-minute limit first: a call it refuses doesn't use up the hour's.)
|
|
135
|
+
const t = now()
|
|
136
|
+
const recent = (observeLog.get(name) ?? []).filter(x => t - x.t < 60_000)
|
|
137
|
+
const events = recent.reduce((sum, x) => sum + x.n, 0)
|
|
138
|
+
if (recent.length >= 120 || events + n > 3000) throw new ApiError(429, 'Too Many Requests: observation rate limit', { parameters: { retry_after: 10 } })
|
|
139
|
+
spendStorage('eventcount', name, n, 30_000)
|
|
140
|
+
recent.push({ t, n })
|
|
141
|
+
observeLog.set(name, recent)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function observe(name, p) {
|
|
145
|
+
const events = Array.isArray(p.events) ? p.events : null
|
|
146
|
+
if (!events || events.length > 200) throw bad('events must be an array of at most 200 items')
|
|
147
|
+
ensureRoom()
|
|
148
|
+
observeBudget(name, events.length)
|
|
149
|
+
const insert = db.prepare('INSERT INTO events (session, ts, kind, data) VALUES (?, ?, ?, ?)')
|
|
150
|
+
// The whole batch is checked first, then stored at once: all of it or none
|
|
151
|
+
// (a refusal halfway would store part of it and the retry would repeat it).
|
|
152
|
+
const batch = []
|
|
153
|
+
for (const ev of events) {
|
|
154
|
+
if (!ev || typeof ev !== 'object' || !EVENT_KINDS.has(ev.kind)) continue
|
|
155
|
+
// Whole milliseconds within the events' lifetime: the history cursor relies on it.
|
|
156
|
+
const ts = Number.isSafeInteger(ev.ts) ? Math.max(now() - eventKeptMs(), Math.min(ev.ts, now() + 5000)) : now()
|
|
157
|
+
const kind = ev.kind
|
|
158
|
+
const rest = cleanEvent(kind, ev)
|
|
159
|
+
const data = JSON.stringify(rest)
|
|
160
|
+
if (data.length > MAX_EVENT_JSON) continue
|
|
161
|
+
batch.push({ ts, kind, rest, data })
|
|
162
|
+
}
|
|
163
|
+
// Charged on what was sent, not on what is kept: text cleaned away (it
|
|
164
|
+
// cost the cleaning all the same) counts too.
|
|
165
|
+
spendStorage('events', name, Math.max(batch.reduce((n, e) => n + e.data.length, 0), Math.min(JSON.stringify(events).length, 1_048_576)))
|
|
166
|
+
let stored = 0
|
|
167
|
+
inTx(() => { for (const { ts, kind, rest, data } of batch) {
|
|
168
|
+
const info = insert.run(name, ts, kind, data)
|
|
169
|
+
const view = eventView(Number(info.lastInsertRowid), name, ts, kind, rest, { stored: true })
|
|
170
|
+
const before = activityOf(name)
|
|
171
|
+
const wasWarned = !!before.context_warned
|
|
172
|
+
applyEvent(name, view)
|
|
173
|
+
contextNotices(name, view, wasWarned)
|
|
174
|
+
if (kind === 'session_start' && rest.source === 'clear') bus.emit('context-cleared', name)
|
|
175
|
+
broadcast('event', view)
|
|
176
|
+
stored++
|
|
177
|
+
} })
|
|
178
|
+
if (stored) bus.emit('session-changed', name)
|
|
179
|
+
return { stored }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Tell a worker's coordinator when its context is nearly full (once per fill-up)
|
|
183
|
+
// and when it compacts. Only live events, never the startup replay.
|
|
184
|
+
const CONTEXT_WARN_PCT = 80
|
|
185
|
+
const NOTICE_COOLDOWN_MS = Number(process.env.PISHA_NOTICE_COOLDOWN_MS ?? 5 * 60_000) // per worker, per kind
|
|
186
|
+
function contextNotices(name, ev, wasWarned) {
|
|
187
|
+
const a = activityOf(name)
|
|
188
|
+
if (ev.kind === 'usage' && ev.context_pct != null && ev.context_pct >= CONTEXT_WARN_PCT && !wasWarned) {
|
|
189
|
+
a.context_warned = true
|
|
190
|
+
// Its own cooldown too: compaction events reset the flag.
|
|
191
|
+
if (now() - (a.context_notice_at ?? 0) < NOTICE_COOLDOWN_MS) return
|
|
192
|
+
a.context_notice_at = now()
|
|
193
|
+
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.`)
|
|
194
|
+
}
|
|
195
|
+
if (ev.kind === 'compacted') {
|
|
196
|
+
// At most one compaction notice every 5 minutes per worker: alternating
|
|
197
|
+
// usage/compacted events must not flood the coordinator.
|
|
198
|
+
if (now() - (a.compact_notice_at ?? 0) < NOTICE_COOLDOWN_MS) return
|
|
199
|
+
a.compact_notice_at = now()
|
|
200
|
+
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.`)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const observationMethods = {
|
|
205
|
+
observe,
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function cleanupEvents() {
|
|
209
|
+
const t = now()
|
|
210
|
+
db.prepare('DELETE FROM events WHERE ts < ?').run(t - eventKeptMs())
|
|
211
|
+
// Over the cap: the oldest go first.
|
|
212
|
+
db.prepare('DELETE FROM events WHERE id <= (SELECT id FROM events ORDER BY id DESC LIMIT 1 OFFSET ?)').run(quota('max_events', MAX_EVENTS))
|
|
213
|
+
for (const [k, v] of observeLog) if (!v.some(x => t - x.t < 60_000)) observeLog.delete(k)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Rebuild each session's derived state from the stored events (last 24h).
|
|
217
|
+
function restoreActivity() {
|
|
218
|
+
for (const r of db.prepare('SELECT * FROM events ORDER BY id').iterate()) {
|
|
219
|
+
applyEvent(r.session, eventView(r.id, r.session, r.ts, r.kind, JSON.parse(r.data), { stored: true }))
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return { observationMethods, cleanupEvents, restoreActivity, cleanEvent, activityOf, activity, eventView }
|
|
224
|
+
}
|
|
@@ -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,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pisha-server",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.11",
|
|
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
|
+
"vendor",
|
|
36
|
+
"install",
|
|
37
|
+
"pisha-host.mjs",
|
|
38
|
+
"pisha-host.mjs.sig",
|
|
39
|
+
"README.md",
|
|
40
|
+
"LICENSE"
|
|
41
|
+
],
|
|
42
|
+
"scripts": {
|
|
43
|
+
"start": "node server.js",
|
|
44
|
+
"prepack": "node ../scripts/stage-server.mjs",
|
|
45
|
+
"postpack": "node ../scripts/stage-server.mjs --undo"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "git+https://github.com/roke22/pisha.git",
|
|
53
|
+
"directory": "server"
|
|
54
|
+
},
|
|
55
|
+
"homepage": "https://github.com/roke22/pisha"
|
|
56
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createPermissions, CAPABILITIES, CAPABILITY_IDS, BUILTIN_PROFILES, RULE_RE } from './permissions.js'
|