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,122 @@
1
+ import { statfsSync } from 'node:fs'
2
+ import { now } from './basics.js'
3
+ import { ApiError } from './errors.js'
4
+
5
+ // Storage limits, so no session (or set of sessions) can fill the disk:
6
+ const STORED_BYTES_PER_HOUR = 30 * 1024 * 1024 // per identity: observation events, and message text, each
7
+ const RATE_LIMIT_PER_MIN = 120 // messages per sender per minute
8
+
9
+ // What is kept free: past either, what sessions add is refused, while deleting
10
+ // and signing in go on working, so there is a way out of it.
11
+ const DATABASE_MB = 20 * 1024 // per company (quota max_db_mb)
12
+ const MIN_FREE_MB = 500 // on the volume (PISHA_MIN_FREE_MB; 0 turns it off)
13
+
14
+ // Why a company can't take more right now, or null. By the pages in use, not
15
+ // the file's size: what was deleted leaves room in a file that doesn't shrink.
16
+ export function whyNoRoom(db, dir, maxDbMb = DATABASE_MB) {
17
+ const pragma = what => Object.values(db.prepare(`PRAGMA ${what}`).get())[0]
18
+ if ((pragma('page_count') - pragma('freelist_count')) * pragma('page_size') > maxDbMb * 1024 ** 2) return 'this company has reached the most it can keep'
19
+ const minFree = Number(process.env.PISHA_MIN_FREE_MB ?? MIN_FREE_MB)
20
+ // (A disk that can't say how much it has isn't refused for that.)
21
+ let free = Infinity
22
+ try { const fs = statfsSync(dir); free = fs.bavail * fs.bsize } catch {}
23
+ if (free < minFree * 1024 ** 2) return 'the server is running out of disk'
24
+ return null
25
+ }
26
+
27
+ // IPv6 clients are counted per /64 (one machine usually has a whole /64).
28
+ export function ipKey(ip) {
29
+ const raw = String(ip ?? '?')
30
+ // IPv4 (also as ::ffff:a.b.c.d) as it is; IPv6 by its /64, written out in
31
+ // full first ("2600:3c03::1" and "2600:3c03:0:0::2" are the same network).
32
+ const v4 = /^(?:::ffff:)?(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(raw)
33
+ if (v4) return v4[1]
34
+ if (!raw.includes(':')) return raw
35
+ const a = raw.replace(/%.*$/, '').toLowerCase()
36
+ const [head, tail] = a.includes('::') ? a.split('::') : [a, null]
37
+ const h = head ? head.split(':') : []
38
+ const t = tail ? tail.split(':') : []
39
+ const groups = tail === null ? h : [...h, ...Array(Math.max(0, 8 - h.length - t.length)).fill('0'), ...t]
40
+ return groups.slice(0, 4).map(g => (parseInt(g, 16) || 0).toString(16)).join(':') + '::/64'
41
+ }
42
+
43
+ // What a company's sessions may spend. Each company counts its own: a name
44
+ // means nothing outside its company.
45
+ export function createLimits() {
46
+ const sendLog = new Map() // name -> timestamps (ms) of recent sends (messages, edits, reactions, groups)
47
+
48
+ // A sliding-window counter: at most `max` hits per `windowMs` for a key.
49
+ const windows = new Map() // bucket -> Map(key -> timestamps)
50
+ function allow(bucket, key, max, windowMs = 60_000) {
51
+ const t = now()
52
+ if (!windows.has(bucket)) windows.set(bucket, new Map())
53
+ const m = windows.get(bucket)
54
+ const recent = (m.get(key) ?? []).filter(x => t - x < windowMs)
55
+ if (recent.length >= max) { m.set(key, recent); return false }
56
+ recent.push(t)
57
+ m.set(key, recent)
58
+ return true
59
+ }
60
+
61
+ // What has been counted, without counting this: for what only failures use up.
62
+ function counted(bucket, key, windowMs = 60_000) {
63
+ const t = now()
64
+ return (windows.get(bucket)?.get(key) ?? []).filter(x => t - x < windowMs).length
65
+ }
66
+
67
+ // Reads (getMe, getChat, getFile, chat actions, polls that don't wait): a
68
+ // generous budget, so one session can't keep the server busy with them.
69
+ function readLimit(name, bucket = 'read') {
70
+ if (!allow(bucket, name, 600)) throw new ApiError(429, 'Too Many Requests: retry in a minute', { parameters: { retry_after: 60 } })
71
+ }
72
+
73
+ // Joining and inviting: 60 a minute per session, apart from the sending
74
+ // budget (a plugin retrying invites to names that don't exist yet must not
75
+ // keep its session from sending).
76
+ function groupLimit(name) {
77
+ if (!allow('group-ops', name, 60)) throw new ApiError(429, 'Too Many Requests: retry in a minute', { parameters: { retry_after: 60 } })
78
+ }
79
+ function rateLimit(name) {
80
+ const t = now()
81
+ const recent = (sendLog.get(name) ?? []).filter(x => t - x < 60_000)
82
+ if (recent.length >= RATE_LIMIT_PER_MIN) {
83
+ const retry = Math.ceil((60_000 - (t - recent[0])) / 1000)
84
+ throw new ApiError(429, `Too Many Requests: retry after ${retry}`, { parameters: { retry_after: retry } })
85
+ }
86
+ recent.push(t)
87
+ sendLog.set(name, recent)
88
+ }
89
+
90
+ // Bytes stored per identity in the last hour, per kind (events, text).
91
+ const storedLog = new Map() // `${kind}:${name}` -> [{ t, bytes }]
92
+
93
+ // Kept per minute (at most 60 buckets per key), so checking costs the same
94
+ // however much a session sends.
95
+ function spendStorage(kind, name, bytes, max = STORED_BYTES_PER_HOUR) {
96
+ const t = now()
97
+ const minute = Math.floor(t / 60_000)
98
+ const key = `${kind}:${name}`
99
+ const buckets = (storedLog.get(key) ?? []).filter(b => minute - b.m < 60)
100
+ const used = buckets.reduce((s, b) => s + b.bytes, 0)
101
+ if (used + bytes > max) throw new ApiError(429, `Too Many Requests: storage budget for this hour used up (${kind})`, { parameters: { retry_after: 600 } })
102
+ const last = buckets[buckets.length - 1]
103
+ if (last && last.m === minute) last.bytes += bytes
104
+ else buckets.push({ m: minute, bytes })
105
+ storedLog.set(key, buckets)
106
+ }
107
+
108
+ function cleanupLimits() {
109
+ const t = now()
110
+ for (const m of windows.values()) for (const [k, v] of m) if (!v.some(x => t - x < 3600_000)) m.delete(k)
111
+ for (const [k, v] of storedLog) if (!v.some(b => Math.floor(t / 60_000) - b.m < 60)) storedLog.delete(k)
112
+ for (const [k, v] of sendLog) if (!v.some(x => t - x < 60_000)) sendLog.delete(k)
113
+ }
114
+
115
+ return { allow, counted, readLimit, groupLimit, rateLimit, spendStorage, cleanupLimits }
116
+ }
117
+
118
+ // What belongs to no company: addresses, and this process's log.
119
+ const serverLimits = createLimits()
120
+ export const allowServerWide = serverLimits.allow
121
+ export const countedServerWide = serverLimits.counted
122
+ export const cleanupServerLimits = serverLimits.cleanupLimits
@@ -0,0 +1,183 @@
1
+ import { createServer as createHttpsServer } from 'node:https'
2
+ import { createServer as createHttpServer } from 'node:http'
3
+ import { readFileSync, watchFile } from 'node:fs'
4
+ import { createAcme } from './acme.js'
5
+ import { join } from 'node:path'
6
+ import {
7
+ HOST, PUBLIC_URL, PORT, VERSION, DATA_DIR, TRUST_PROXY, TLS, TLS_MODE, TLS_KEY, TLS_CERT, DOMAIN,
8
+ ACME_EMAIL, ACME_DIRECTORY, HTTP_PORT,
9
+ } from './config.js'
10
+ import { refuseSocket, guardRequest } from './http.js'
11
+ import { ipKey, allowServerWide } from './limits.js'
12
+
13
+ export async function startListening(server, { nowServing, joinToken, handle, onUpgrade }) {
14
+ const { TOKEN_SOURCE, SERVER_TOKEN, SERVER_KEY, SERVER_KEY_FILE } = server
15
+
16
+ const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost'])
17
+ const servers = []
18
+
19
+ const isNewToken = source => source.endsWith('(new)')
20
+ function startupBanner(scheme) {
21
+ nowServing()
22
+ const everywhere = HOST === '0.0.0.0' || HOST === '::'
23
+ const url = PUBLIC_URL || `${scheme}://${everywhere ? '<this-machine-ip>' : HOST}:${PORT}`
24
+ const lines = [
25
+ `pisha-server v${VERSION}: listening on ${scheme}://${HOST}:${PORT}${everywhere ? ' (all interfaces)' : ''} (data: ${DATA_DIR})`,
26
+ '',
27
+ // (The tokens themselves only the time they are made, not at every start:
28
+ // logs are kept, and read, by more than whoever holds these.)
29
+ ...(isNewToken(TOKEN_SOURCE)
30
+ ? [` Server token — creates the first owner, recovers access, and always works on /admin and /register (${TOKEN_SOURCE}). It is only shown this once:`, ` ${SERVER_TOKEN}`]
31
+ : [` Server token — creates the first owner, recovers access, and always works on /admin and /register. It is in ${TOKEN_SOURCE}.`]),
32
+ '',
33
+ ` Join token — for machines: registers new sessions, nothing else (${joinToken().source}).`,
34
+ ' Configure each machine from Claude Code with:',
35
+ ` /pisha:configure ${url} ${isNewToken(joinToken().source) ? joinToken().token : '<join-token>'}`,
36
+ ` Dashboard: ${url}/`,
37
+ '',
38
+ ` Server key: ${SERVER_KEY.fingerprint} (${SERVER_KEY_FILE}). Machines and sessions remember it: back this`,
39
+ ' file up with the data. Without it they refuse this server until they are added again.',
40
+ ]
41
+ if (TRUST_PROXY && !PUBLIC_URL) {
42
+ lines.push('', ' ⚠️ --trust-proxy without --public-url: set the public address so enrollment commands',
43
+ ' and machines use it (forwarded Host headers are never trusted for that).')
44
+ }
45
+ if (!TLS && !PUBLIC_URL && !everywhere && LOOPBACK.has(HOST)) {
46
+ lines.push('', ' Only reachable from this machine. To serve your domain over HTTPS, start with',
47
+ ' --domain your-domain (automatic Let\'s Encrypt certificate). See --help.')
48
+ }
49
+ if (!TLS && !LOOPBACK.has(HOST) && !PUBLIC_URL.startsWith('https://')) {
50
+ lines.push('', ' ⚠️ Listening beyond this machine over plain HTTP: the server token, session secrets and',
51
+ ' everything the dashboard shows travel unencrypted. Use --domain (built-in HTTPS),',
52
+ ' a TLS reverse proxy (see deploy/), or a private network such as Tailscale.')
53
+ }
54
+ process.stderr.write(lines.join('\n') + '\n\n')
55
+ }
56
+
57
+ // Connections per address: at most 256 at once, room for several machines
58
+ // behind one NAT with many sessions each (behind a trusted proxy all come
59
+ // from it, so then none is counted). A connection idle for 2 minutes is
60
+ // closed (long polls answer within 50 s, the dashboard's stream pings every
61
+ // 20 s, and WebSockets turn this off for themselves).
62
+ const connectionsByIp = new Map()
63
+ function listen(srv, port, host) {
64
+ // A malformed request only closes its own connection.
65
+ srv.on('clientError', (err, socket) => refuseSocket(socket, '400 Bad Request'))
66
+ srv.timeout = 120_000
67
+ srv.on('connection', socket => {
68
+ if (TRUST_PROXY) return
69
+ const ip = ipKey(socket.remoteAddress)
70
+ const n = (connectionsByIp.get(ip) ?? 0) + 1
71
+ connectionsByIp.set(ip, n)
72
+ socket.once('close', () => { const m = (connectionsByIp.get(ip) ?? 1) - 1; if (m > 0) connectionsByIp.set(ip, m); else connectionsByIp.delete(ip) })
73
+ if (n > 256) {
74
+ // (Said in the log, at most once a minute: behind a tunnel or proxy
75
+ // without --trust-proxy every client shares one address.)
76
+ if (allowServerWide('conn-cap-log', 'all', 1)) process.stderr.write(`pisha-server: ${ip} has 256 connections open: refusing more (behind a reverse proxy or tunnel? start with --trust-proxy)\n`)
77
+ socket.destroy()
78
+ }
79
+ })
80
+ return new Promise((resolve, reject) => {
81
+ srv.once('error', reject)
82
+ srv.listen(port, host, () => { srv.off('error', reject); resolve() })
83
+ })
84
+ }
85
+
86
+ function failListen(err, port) {
87
+ const hint = err.code === 'EACCES' && port < 1024
88
+ ? ` Ports below 1024 need privileges: run as root, grant it with "sudo setcap cap_net_bind_service=+ep $(command -v node)", or use Docker with -p ${port}:${port}.`
89
+ : err.code === 'EADDRINUSE' ? ' Something else is already using that port.' : ''
90
+ process.stderr.write(`pisha-server: cannot listen on port ${port}: ${err.message}.${hint}\n`)
91
+ process.exit(1)
92
+ }
93
+
94
+ function httpsServer(creds) {
95
+ const srv = createHttpsServer({ key: creds.key, cert: creds.cert }, handle)
96
+ srv.requestTimeout = 0 // long polls and big uploads manage their own limits
97
+ srv.on('upgrade', onUpgrade)
98
+ servers.push(srv)
99
+ return srv
100
+ }
101
+
102
+ if (TLS_MODE === 'http') {
103
+ const srv = createHttpServer(handle)
104
+ srv.requestTimeout = 0
105
+ srv.on('upgrade', onUpgrade)
106
+ servers.push(srv)
107
+ listen(srv, PORT, HOST).then(() => startupBanner('http'), err => failListen(err, PORT))
108
+ } else if (TLS_MODE === 'files') {
109
+ const read = () => ({ key: readFileSync(TLS_KEY), cert: readFileSync(TLS_CERT) })
110
+ let creds
111
+ try { creds = read() } catch (err) {
112
+ process.stderr.write(`pisha-server: cannot read the certificate: ${err.message}\n`)
113
+ process.exit(2)
114
+ }
115
+ const srv = httpsServer(creds)
116
+ listen(srv, PORT, HOST).then(() => startupBanner('https'), err => failListen(err, PORT))
117
+ // Renewed by certbot or similar: pick the new files up without restarting.
118
+ for (const f of [TLS_CERT, TLS_KEY]) {
119
+ watchFile(f, { interval: 60_000 }, () => {
120
+ try { srv.setSecureContext(read()); process.stderr.write('pisha-server: certificate reloaded\n') }
121
+ catch (err) { process.stderr.write(`pisha-server: certificate reload failed: ${err.message}\n`) }
122
+ }).unref?.()
123
+ }
124
+ } else {
125
+ // Automatic certificate. Port 80 answers ACME challenges and redirects
126
+ // everything else to HTTPS; HTTPS starts as soon as a certificate is ready.
127
+ const acme = createAcme({
128
+ domain: DOMAIN,
129
+ email: ACME_EMAIL,
130
+ directory: ACME_DIRECTORY,
131
+ dir: join(DATA_DIR, 'tls'),
132
+ log: m => process.stderr.write(`pisha-server: ${m}\n`),
133
+ })
134
+ const challengeServer = createHttpServer((req, res) => {
135
+ if (!guardRequest(req, res)) return
136
+ const m = /^\/\.well-known\/acme-challenge\/([A-Za-z0-9_-]+)$/.exec(req.url ?? '')
137
+ if (m) {
138
+ const answer = acme.challenge(m[1])
139
+ res.writeHead(answer ? 200 : 404, { 'Content-Type': 'text/plain' })
140
+ return res.end(answer ?? 'not found')
141
+ }
142
+ res.writeHead(301, { Location: `${PUBLIC_URL}${req.url ?? '/'}` })
143
+ res.end()
144
+ })
145
+ servers.push(challengeServer)
146
+ await listen(challengeServer, HTTP_PORT, HOST).catch(err => failListen(err, HTTP_PORT))
147
+
148
+ let https = null
149
+ const obtain = async () => {
150
+ for (let attempt = 1; ; attempt++) {
151
+ try { return await acme.ensureCertificate() } catch (err) {
152
+ const delay = Math.min(60_000 * attempt, 30 * 60_000)
153
+ process.stderr.write(`pisha-server: could not get a certificate for ${DOMAIN}: ${err.message}\n` +
154
+ ` Check that the domain's DNS points to this machine and that port ${HTTP_PORT} is reachable from the internet. Retrying in ${delay / 60_000} min.\n`)
155
+ await new Promise(r => setTimeout(r, delay))
156
+ }
157
+ }
158
+ }
159
+ // A stored certificate that is still valid is served right away, even if
160
+ // it is due for renewal: renewing (below) must not keep HTTPS down while
161
+ // the certificate authority can't be reached.
162
+ const kept = acme.storedCertificate()
163
+ const creds = kept && Date.now() < kept.expires - 60_000 ? kept : await obtain()
164
+ https = httpsServer(creds)
165
+ await listen(https, PORT, HOST).catch(err => failListen(err, PORT))
166
+ startupBanner('https')
167
+ if (creds === kept && Date.now() >= kept.renewAt) {
168
+ acme.ensureCertificate().then(c => { if (c.renewed) { https.setSecureContext({ key: c.key, cert: c.cert }); process.stderr.write('pisha-server: certificate renewed\n') } },
169
+ err => process.stderr.write(`pisha-server: certificate renewal failed (will retry): ${err.message}\n`))
170
+ }
171
+ // Check twice a day; renew 30 days before expiry and swap it in live.
172
+ setInterval(async () => {
173
+ try {
174
+ const c = await acme.ensureCertificate()
175
+ if (c.renewed) { https.setSecureContext({ key: c.key, cert: c.cert }); process.stderr.write('pisha-server: certificate renewed\n') }
176
+ } catch (err) {
177
+ process.stderr.write(`pisha-server: certificate renewal failed (will retry): ${err.message}\n`)
178
+ }
179
+ }, 12 * 60 * 60 * 1000).unref()
180
+ }
181
+
182
+ return { servers }
183
+ }
@@ -0,0 +1,6 @@
1
+ // What a user is in a company, from less to more. (The table of what each can
2
+ // do is next to each action: see server/dashboard/dashboard.js.)
3
+ export const ROLES = ['observer', 'operator', 'manager', 'owner']
4
+ // The agents a session can run: Claude Code, Codex CLI or Grok CLI.
5
+ export const AGENTS = ['claude', 'codex', 'grok']
6
+ export const atLeast = (role, needed) => ROLES.includes(needed) && ROLES.indexOf(role) >= ROLES.indexOf(needed)
@@ -0,0 +1,19 @@
1
+ import { now } from './basics.js'
2
+
3
+ export function createStream(every) {
4
+ const sseClients = new Set()
5
+
6
+ function broadcast(type, data) {
7
+ if (sseClients.size === 0) return
8
+ const chunk = `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`
9
+ for (const res of sseClients) {
10
+ if (res.writableEnded) { sseClients.delete(res); continue }
11
+ // A dashboard that stopped reading: drop it (it reconnects and reloads).
12
+ if (res.writableLength > 8 * 1024 * 1024) { sseClients.delete(res); res.destroy(); continue }
13
+ res.write(chunk)
14
+ }
15
+ }
16
+ every(20_000, () => broadcast('ping', { t: now() }))
17
+
18
+ return { sseClients, broadcast }
19
+ }
@@ -0,0 +1,83 @@
1
+ // One line of text written in the dashboard (a title, a goal, a
2
+ // description): clean, at most n characters.
3
+ export const oneLine = (v, n) => (typeof v === 'string' ? cleanText(v.slice(0, n * 2)).replace(/\s+/g, ' ').trim().slice(0, n) : '')
4
+
5
+ // Control characters (except newline and tab), bidi overrides and blank
6
+ // fillers: invisible
7
+ // in the dashboard, but they survive copy and paste into a terminal.
8
+ const UNSAFE_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u00ad\u034f\u061c\u180e\u200b-\u200f\u2028\u2029\u202a-\u202e\u2060-\u2064\u2066-\u2069\u115f\u1160\u17b4\u17b5\u2065\u2800\u3164\uffa0\ufeff\ufff9-\ufffb\u{1d173}-\u{1d17a}\u{e0000}-\u{e007f}\u180b-\u180f\ufe00-\ufe0f\u{e0100}-\u{e01ef}\p{Cf}]/gu
9
+
10
+ // Some of them are part of real text, and are kept where they are: a joiner
11
+ // (ZWJ/ZWNJ) between two non-ASCII letters or emoji (👩‍💻, Persian, Sinhala);
12
+ // one variation selector right after the character it varies (葛󠄀, Mongolian);
13
+ // the tags of a subdivision flag (🏴 England); the format marks that start
14
+ // Arabic, Syriac or Kaithi numbers or join hieroglyphs and shorthand.
15
+ const isBase = c => c > 0x7f && /[\p{L}\p{M}\p{N}\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\uFE0F\u20E3]/u.test(String.fromCodePoint(c))
16
+
17
+ // (Only the subdivision flags emoji actually has: England, Scotland, Wales.)
18
+ const FLAG_TAGS = /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}/gu
19
+
20
+ // Each mark only before a character of its own kind (an invisible one
21
+ // can't sit before an ASCII letter).
22
+ const KEPT_MARKS = [
23
+ [/^[\u0600-\u0605\u06dd\u0890\u0891\u08e2]$/u, /^\p{Nd}$/u], // Arabic number signs (they are drawn)
24
+ [/^[\u{110bd}\u{110cd}]$/u, /^(?![0-9])\p{Nd}$/u], // Kaithi number signs
25
+ [/^\u070f$/u, /^\p{Script=Syriac}$/u],
26
+ [/^[\u{13430}-\u{1343f}]$/u, /^\p{Script=Egyptian_Hieroglyphs}$/u],
27
+ [/^[\u{1bca0}-\u{1bca3}]$/u, /^\p{Script=Duployan}$/u],
28
+ ]
29
+ function keptInContext(ch, at, text) {
30
+ const c = ch.codePointAt(0)
31
+ const before = at > 0 ? text.codePointAt(at - 1 - (at > 1 && /[\udc00-\udfff]/.test(text[at - 1]) ? 1 : 0)) : null
32
+ const after = text.codePointAt(at + ch.length) ?? null
33
+ if (c === 0x200c || c === 0x200d) return before !== null && after !== null && isBase(before) && isBase(after)
34
+ const vs = x => (x >= 0xfe00 && x <= 0xfe0f) || (x >= 0xe0100 && x <= 0xe01ef) || (x >= 0x180b && x <= 0x180d) || x === 0x180f
35
+ // (A keycap: 1️⃣ is "1", U+FE0F, U+20E3.)
36
+ if (c === 0xfe0f && before !== null && /^[0-9#*]$/.test(String.fromCodePoint(before)) && after === 0x20e3) return true
37
+ if (vs(c)) return before !== null && isBase(before) && !vs(before)
38
+ const mark = KEPT_MARKS.find(([m]) => m.test(ch))
39
+ if (mark) return after !== null && mark[1].test(String.fromCodePoint(after))
40
+ return false
41
+ }
42
+
43
+ // Two passes: first what is never kept goes, then the rest is judged by
44
+ // its neighbours as they are now (a filler can't make a joiner look kept).
45
+ const MAYBE_KEPT = /^[\u200c\u200d\ufe00-\ufe0f\u{e0100}-\u{e01ef}\u180b-\u180d\u180f\u{e0020}-\u{e007f}\u0600-\u0605\u06dd\u070f\u0890\u0891\u08e2\u{110bd}\u{110cd}\u{13430}-\u{1343f}\u{1bca0}-\u{1bca3}]$/u
46
+
47
+ // Then again until nothing changes (what one pass drops can leave another
48
+ // character without the neighbour it was kept for); after a few passes,
49
+ // whatever is left of them goes, except subdivision flags.
50
+ function contextPass(text, keep) {
51
+ // (The tags of the subdivision flags are text. Matches come in order: one
52
+ // pointer over the flags, so it stays linear.)
53
+ const flags = [...text.matchAll(FLAG_TAGS)].map(m => [m.index, m.index + m[0].length])
54
+ let f = 0
55
+ return text.replace(UNSAFE_CHARS, (ch, at, all) => {
56
+ while (f < flags.length && flags[f][1] <= at) f++
57
+ const inFlag = f < flags.length && at >= flags[f][0]
58
+ return inFlag || (keep && keptInContext(ch, at, all)) ? ch : ''
59
+ })
60
+ }
61
+
62
+ // Cut clean text to n characters without leaving anything dangling at the
63
+ // cut: half a surrogate pair, or a joiner or selector with nothing after it.
64
+ export function cutText(t, n) {
65
+ let s = t.length > n ? t.slice(0, n) : t
66
+ for (let i = 0; i < 4 && /(?:[\u200c\u200d\ufe00-\ufe0f\ud800-\udbff]|\udb40[\udd00-\uddef])$/.test(s); i++) s = s.replace(/(?:[\u200c\u200d\ufe00-\ufe0f\ud800-\udbff]|\udb40[\udd00-\uddef])$/, '')
67
+ return s
68
+ }
69
+ export const cleanText = t => {
70
+ if (typeof t !== 'string') return t
71
+ let maybe = 0
72
+ let out = t.replace(UNSAFE_CHARS, ch => (MAYBE_KEPT.test(ch) ? (maybe++, ch) : ''))
73
+ // Judging each one by its neighbours costs more than the rest of the text:
74
+ // a text with this many of them (no real one has) loses them all, except
75
+ // subdivision flags.
76
+ if (maybe > 20_000) return contextPass(out, false)
77
+ for (let i = 0; i < 4; i++) {
78
+ const next = contextPass(out, true)
79
+ if (next === out) return out
80
+ out = next
81
+ }
82
+ return contextPass(out, false)
83
+ }
package/platform/ws.js ADDED
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Minimal WebSocket server side (RFC 6455) for pisha-server: text frames,
3
+ * ping/pong and close, with fragmented messages reassembled. Only Node
4
+ * built-ins — no dependencies.
5
+ *
6
+ * server.on('upgrade', (req, socket, head) => {
7
+ * const ws = acceptWebSocket(req, socket, head)
8
+ * if (!ws) return
9
+ * ws.onmessage = text => …
10
+ * ws.onclose = () => …
11
+ * ws.send('hello')
12
+ * })
13
+ */
14
+
15
+ import { createHash } from 'node:crypto'
16
+
17
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
18
+ const MAX_MESSAGE = 2 * 1024 * 1024 // per message, after reassembly
19
+
20
+ export function acceptWebSocket(req, socket, head, { maxMessage = MAX_MESSAGE, protocol = null, log = m => process.stderr.write(`${m}\n`) } = {}) {
21
+ const key = req.headers['sec-websocket-key']
22
+ if (req.headers.upgrade?.toLowerCase() !== 'websocket' || !key) {
23
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
24
+ setTimeout(() => socket.destroy(), 1000).unref() // (never left half open)
25
+ return null
26
+ }
27
+ const accept = createHash('sha1').update(key + GUID).digest('base64')
28
+ socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n' +
29
+ `Sec-WebSocket-Accept: ${accept}\r\n` + (protocol ? `Sec-WebSocket-Protocol: ${protocol}\r\n` : '') + '\r\n')
30
+ socket.setNoDelay(true)
31
+ socket.setTimeout(0)
32
+
33
+ // Incoming bytes as a list of chunks: joined only once a whole frame is
34
+ // there, so a frame trickled in tiny pieces costs no repeated copying.
35
+ const chunks = head?.length ? [Buffer.from(head)] : []
36
+ let buffered = chunks.reduce((n, c) => n + c.length, 0)
37
+ let fragments = []
38
+ let fragmentsSize = 0
39
+ let fragmentOpcode = 0
40
+ let closed = false
41
+
42
+ const ws = {
43
+ onmessage: () => {},
44
+ onclose: () => {},
45
+ // Largest message accepted; the server raises it once a client has authenticated.
46
+ maxMessage,
47
+ get open() { return !closed },
48
+ send(text) {
49
+ if (closed) return false
50
+ // A peer that doesn't read can't make the server hold its output:
51
+ // past 16 MB waiting, the connection goes.
52
+ if (socket.writableLength > 16 * 1024 * 1024) { ws.close(4008, 'not reading'); return false }
53
+ socket.write(frame(0x1, Buffer.from(String(text), 'utf8')))
54
+ return true
55
+ },
56
+ close(code = 1000, reason = '') {
57
+ if (closed) return
58
+ const r = Buffer.from(String(reason).slice(0, 120), 'utf8')
59
+ const body = Buffer.alloc(2 + r.length)
60
+ body.writeUInt16BE(code, 0)
61
+ r.copy(body, 2)
62
+ try { socket.write(frame(0x8, body)) } catch {}
63
+ finish()
64
+ setTimeout(() => socket.destroy(), 1000).unref()
65
+ socket.end()
66
+ },
67
+ // Bytes waiting to be written: used to drop output for slow viewers.
68
+ get buffered() { return socket.writableLength },
69
+ }
70
+
71
+ function finish() {
72
+ if (closed) return
73
+ closed = true
74
+ chunks.length = 0; buffered = 0; fragments = []
75
+ try { ws.onclose() } catch {}
76
+ }
77
+
78
+ function fail(code, reason) { ws.close(code, reason) }
79
+
80
+ socket.on('data', chunk => {
81
+ if (closed) return
82
+ try { ws.onactivity?.() } catch {} // (any bytes: a big message still arriving is a sign of life)
83
+ chunks.push(chunk)
84
+ buffered += chunk.length
85
+ parse()
86
+ })
87
+ socket.on('close', finish)
88
+ socket.on('error', finish)
89
+ // The peer closed its side without a close frame (it crashed): closed here
90
+ // too, at once (the socket would otherwise stay half open).
91
+ socket.on('end', () => ws.close(1001, 'connection ended'))
92
+ if (buffered) setImmediate(parse)
93
+
94
+ // The first n buffered bytes (joining chunks only as far as needed).
95
+ function peek(n) {
96
+ if (chunks[0].length < n) {
97
+ const joined = Buffer.concat(chunks)
98
+ chunks.length = 0
99
+ chunks.push(joined)
100
+ }
101
+ return chunks[0]
102
+ }
103
+ function take(n) {
104
+ const first = peek(n)
105
+ const out = first.subarray(0, n)
106
+ if (first.length === n) chunks.shift(); else chunks[0] = first.subarray(n)
107
+ buffered -= n
108
+ return out
109
+ }
110
+
111
+ function parse() {
112
+ while (!closed && buffered >= 2) {
113
+ const h = peek(Math.min(buffered, 14))
114
+ const b0 = h[0], b1 = h[1]
115
+ const fin = (b0 & 0x80) !== 0
116
+ const opcode = b0 & 0x0f
117
+ const masked = (b1 & 0x80) !== 0
118
+ let len = b1 & 0x7f
119
+ let off = 2
120
+ if (len === 126) {
121
+ if (buffered < 4) return
122
+ len = h.readUInt16BE(2); off = 4
123
+ } else if (len === 127) {
124
+ if (buffered < 10) return
125
+ const big = h.readBigUInt64BE(2)
126
+ if (big > BigInt(ws.maxMessage)) return fail(1009, 'message too big')
127
+ len = Number(big); off = 10
128
+ }
129
+ if (!masked) return fail(1002, 'client frames must be masked')
130
+ // Control frames: at most 125 bytes and never fragmented (RFC 6455 5.5).
131
+ if (opcode >= 0x8 && (len > 125 || !fin)) return fail(1002, 'invalid control frame')
132
+ if (len > ws.maxMessage) return fail(1009, 'message too big')
133
+ if (buffered < off + 4 + len) return
134
+ const raw = take(off + 4 + len)
135
+ const mask = raw.subarray(off, off + 4)
136
+ const payload = Buffer.from(raw.subarray(off + 4))
137
+ for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3]
138
+
139
+ if (opcode === 0x8) { // close
140
+ const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1000
141
+ ws.close(code === 1005 || code === 1006 ? 1000 : code)
142
+ return
143
+ }
144
+ if (opcode === 0x9) { // ping → pong, unless the client isn't reading what we send
145
+ if (socket.writableLength > 64 * 1024) return fail(1008, 'not reading')
146
+ socket.write(frame(0xA, payload))
147
+ continue
148
+ }
149
+ if (opcode === 0xA) continue // pong
150
+ if (opcode === 0x1 || opcode === 0x2) {
151
+ if (fragments.length) return fail(1002, 'expected a continuation frame')
152
+ fragmentOpcode = opcode
153
+ } else if (opcode !== 0x0) {
154
+ return fail(1002, 'unknown opcode')
155
+ } else if (!fragments.length) {
156
+ return fail(1002, 'unexpected continuation frame')
157
+ }
158
+ fragments.push(payload)
159
+ fragmentsSize += payload.length
160
+ // Empty fragments cost memory too: a message has at most 1024 pieces.
161
+ if (fragmentsSize > ws.maxMessage || fragments.length > 1024) return fail(1009, 'message too big')
162
+ if (!fin) continue
163
+ const data = Buffer.concat(fragments)
164
+ fragments = []; fragmentsSize = 0
165
+ if (fragmentOpcode === 0x1) {
166
+ // (A handler error goes to the caller's log, which limits how often it writes.)
167
+ try { ws.onmessage(data.toString('utf8')) } catch (err) { log(`websocket handler: ${err?.stack ?? err}`) }
168
+ }
169
+ }
170
+ }
171
+
172
+ return ws
173
+ }
174
+
175
+ function frame(opcode, payload) {
176
+ const len = payload.length
177
+ let header
178
+ if (len < 126) {
179
+ header = Buffer.from([0x80 | opcode, len])
180
+ } else if (len < 65536) {
181
+ header = Buffer.alloc(4); header[0] = 0x80 | opcode; header[1] = 126; header.writeUInt16BE(len, 2)
182
+ } else {
183
+ header = Buffer.alloc(10); header[0] = 0x80 | opcode; header[1] = 127; header.writeBigUInt64BE(BigInt(len), 2)
184
+ }
185
+ return Buffer.concat([header, payload])
186
+ }