pisha-server 0.0.11 → 0.0.13

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/boards/boards.js CHANGED
@@ -108,6 +108,14 @@ export function createBoards(platform, { sessions, messaging, members }) {
108
108
 
109
109
  const prefix = () => db.prepare("SELECT v FROM board_settings WHERE k = 'prefix'").get()?.v ?? 'SQ'
110
110
  const taskId = seq => `${prefix()}-${seq}`
111
+ // The first of this company's tasks a text names ("SQ-12", with its prefix), or null.
112
+ function taskIn(text) {
113
+ const p = prefix()
114
+ for (const m of String(text ?? '').slice(0, 20_000).matchAll(/\b([A-Z][A-Z0-9]{0,5})-(\d{1,9})\b/g)) {
115
+ if (m[1] === p && db.prepare('SELECT 1 FROM tasks WHERE seq = ? AND deleted_at IS NULL').get(Number(m[2]))) return `${p}-${Number(m[2])}`
116
+ }
117
+ return null
118
+ }
111
119
  // "SQ-12", "sq-12", "#12" or 12.
112
120
  function seqOf(id) {
113
121
  const m = /^(?:[A-Za-z][A-Za-z0-9]{0,5}-|#)?(\d{1,9})$/.exec(String(id ?? '').trim())
@@ -1075,5 +1083,5 @@ export function createBoards(platform, { sessions, messaging, members }) {
1075
1083
  restore: t => restoreTasks(t, { by: FROM_GITHUB(), github: true }),
1076
1084
  })
1077
1085
 
1078
- return { boardReads, boardActions, boardMethods, boardList, forget, BOARD_SENDER }
1086
+ return { boardReads, boardActions, boardMethods, boardList, forget, taskIn, BOARD_SENDER }
1079
1087
  }
package/companies.js CHANGED
@@ -15,8 +15,8 @@ const COMPANY_NAME = /^[\p{L}\p{N} ._&-]{1,80}$/u
15
15
  const CREDENTIAL_COMPANY = /^s[qjh]_([a-z0-9]{8})_/
16
16
 
17
17
  // What a company may keep, when it isn't what the server starts with.
18
- const QUOTAS = ['max_sessions', 'max_messages', 'max_events', 'max_updates', 'max_files_gb', 'max_db_mb', 'stored_text_mb_hour', 'retention_days', 'event_hours', 'inbox_days']
19
- const RETENTION = ['retention_days', 'event_hours', 'inbox_days']
18
+ const QUOTAS = ['max_sessions', 'max_messages', 'max_events', 'max_updates', 'max_files_gb', 'max_db_mb', 'stored_text_mb_hour', 'retention_days', 'event_hours', 'inbox_days', 'usage_days']
19
+ const RETENTION = ['retention_days', 'event_hours', 'inbox_days', 'usage_days']
20
20
 
21
21
  // How long a company waits after being deleted, in case it was a mistake.
22
22
  const GRACE_MS = Number(process.env.PISHA_COMPANY_GRACE_MS ?? 30 * 24 * 3600_000)
@@ -226,17 +226,17 @@ export function createCompanies(server) {
226
226
  },
227
227
  'company/retention': {
228
228
  role: 'manager', method: 'GET',
229
- run: ({ company }) => ({ retention_days: company.platform.quota('retention_days', 7), event_hours: company.platform.quota('event_hours', Number(process.env.OBSERVE_TTL_HOURS ?? 24)), inbox_days: company.platform.quota('inbox_days', 90) }),
229
+ run: ({ company }) => ({ retention_days: company.platform.quota('retention_days', 7), event_hours: company.platform.quota('event_hours', Number(process.env.OBSERVE_TTL_HOURS ?? 24)), inbox_days: company.platform.quota('inbox_days', 90), usage_days: company.platform.quota('usage_days', 400) }),
230
230
  },
231
231
  'company/retention/set': {
232
232
  role: 'owner', method: 'POST',
233
233
  run({ company, params }) {
234
234
  const wanted = Object.fromEntries(RETENTION.filter(k => params[k] != null).map(k => [k, params[k]]))
235
235
  const limits = { ...quotasOf(row(company.id)), ...cleanQuotas(wanted) }
236
- if ((limits.retention_days ?? 0) > 3650 || (limits.event_hours ?? 0) > 8760 || (limits.inbox_days ?? 0) > 3650) throw bad('at most 3650 days of messages or of the inbox, and 8760 hours of activity')
236
+ if ((limits.retention_days ?? 0) > 3650 || (limits.event_hours ?? 0) > 8760 || (limits.inbox_days ?? 0) > 3650 || (limits.usage_days ?? 0) > 3650) throw bad('at most 3650 days of messages, of the inbox or of token usage, and 8760 hours of activity')
237
237
  control.prepare('UPDATE companies SET limits_json = ? WHERE id = ?').run(JSON.stringify(limits), company.id)
238
238
  company.platform.setQuotas(limits)
239
- return { retention_days: limits.retention_days ?? 7, event_hours: limits.event_hours ?? null, inbox_days: limits.inbox_days ?? 90 }
239
+ return { retention_days: limits.retention_days ?? 7, event_hours: limits.event_hours ?? null, inbox_days: limits.inbox_days ?? 90, usage_days: limits.usage_days ?? 400 }
240
240
  },
241
241
  },
242
242
  // (It answers by itself: a whole company goes down the response as it is read.)
package/company.js CHANGED
@@ -7,6 +7,8 @@ import { createMachines } from './machines/index.js'
7
7
  import { createOrganization } from './organization/index.js'
8
8
  import { createDashboard } from './dashboard/index.js'
9
9
  import { createBoards } from './boards/index.js'
10
+ import { createUsage } from './usage/index.js'
11
+ import { createWebhooks } from './webhooks/index.js'
10
12
  import { upgradeStoredData } from './data-upgrade.js'
11
13
  import { cleanExports } from './company-export.js'
12
14
 
@@ -22,6 +24,7 @@ import { cleanExports } from './company-export.js'
22
24
  // machines pisha-host: joining, its link, terminals
23
25
  // organization squads, links between them, templates
24
26
  // boards task boards: people's and agents' tasks
27
+ // webhooks what other services send a department, and what came of it
25
28
  // dashboard what the dashboard reads and does
26
29
  export function createCompany(server, options) {
27
30
  const platform = createPlatform(server, options)
@@ -34,12 +37,15 @@ export function createCompany(server, options) {
34
37
  const machines = createMachines(platform, { sessions, observation, permissions })
35
38
  const organization = createOrganization(platform, { sessions, messaging, observation, machines })
36
39
  const boards = createBoards(platform, { sessions, messaging, members: options.members ?? (() => []) })
37
- const dashboard = createDashboard(platform, { sessions, messaging, inbox, plans, observation, machines, organization, permissions, boards })
40
+ const usage = createUsage(platform, { sessions, boards })
41
+ const webhooks = createWebhooks(platform, { sessions, messaging })
42
+ const dashboard = createDashboard(platform, { sessions, messaging, inbox, plans, observation, machines, organization, permissions, boards, usage, webhooks })
38
43
 
39
44
  // What a session can ask for, by its name in the request.
40
45
  const methods = {
41
46
  ...observation.observationMethods, ...machines.machineMethods, ...organization.organizationMethods,
42
47
  ...sessions.sessionMethods, ...messaging.messagingMethods, ...inbox.inboxMethods, ...plans.planMethods, ...boards.boardMethods,
48
+ ...webhooks.webhookMethods,
43
49
  }
44
50
 
45
51
  function cleanup() {
@@ -47,6 +53,8 @@ export function createCompany(server, options) {
47
53
  inbox.cleanupInbox()
48
54
  sessions.cleanupUpdates()
49
55
  observation.cleanupEvents()
56
+ usage.cleanupUsage()
57
+ webhooks.cleanupWebhooks()
50
58
  platform.cleanupLimits()
51
59
  platform.cleanupAudit()
52
60
  platform.truncateLogHourly()
@@ -75,5 +83,5 @@ export function createCompany(server, options) {
75
83
  try { platform.db.close() } catch {}
76
84
  }
77
85
 
78
- return { id: options.id, platform, sessions, messaging, observation, machines, organization, boards, dashboard, methods, dropClients, close }
86
+ return { id: options.id, platform, sessions, messaging, observation, machines, organization, boards, webhooks, dashboard, methods, dropClients, close }
79
87
  }
@@ -2,7 +2,7 @@ import { rmSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { unix, now, guarded, bad, ApiError, VERSION, ROLES, AGENTS } from '../platform/index.js'
4
4
 
5
- export function createDashboard(platform, { sessions, observation, machines, messaging, inbox, plans, organization, permissions, boards }) {
5
+ export function createDashboard(platform, { sessions, observation, machines, messaging, inbox, plans, organization, permissions, boards, usage, webhooks }) {
6
6
  const { rotateJoinToken, db, bus, broadcast, sseClients, truncateLog, dataDir, log, every } = platform
7
7
  const {
8
8
  register, approveSession, presenceOf, personaView, identityCreatedAt, identityExists, isOnline, linksOf,
@@ -166,6 +166,8 @@ export function createDashboard(platform, { sessions, observation, machines, mes
166
166
  'boards/tasks': q => boards.boardReads.tasks(q),
167
167
  'boards/task': q => boards.boardReads.task(q),
168
168
  'boards/trash': q => boards.boardReads.trash(q),
169
+ usage: q => usage.usageReads.usage(q),
170
+ ...webhooks.webhookReads,
169
171
  events(q) {
170
172
  const limit = Math.max(1, Math.min(Number(q.get('limit') ?? 300) || 300, 1000))
171
173
  const before = Number(q.get('before') ?? Number.MAX_SAFE_INTEGER)
@@ -368,12 +370,13 @@ export function createDashboard(platform, { sessions, observation, machines, mes
368
370
  'inbox/answer': (p, req) => answerFromInbox(p, req.actor),
369
371
  'inbox/dismiss': (p, req) => dismissFromInbox(p, req.actor),
370
372
  ...Object.fromEntries(Object.entries(boards.boardActions).map(([k, fn]) => [k, (p, req) => fn(p, req.actor ?? null)])),
373
+ ...webhooks.webhookActions,
371
374
  }
372
375
 
373
376
  // Who may do each thing, at least. Whatever isn't here nobody may do, and the
374
377
  // server refuses to start (see the end): every new action says who it is for.
375
378
  const dashboardRoles = {
376
- reads: { inbox: 'observer', 'inbox/done': 'observer', timeline: 'observer', state: 'observer', events: 'observer', hosts: 'observer', messages: 'observer', stream: 'observer', boards: 'observer', 'boards/tasks': 'observer', 'boards/task': 'observer', 'boards/trash': 'manager' },
379
+ reads: { inbox: 'observer', 'inbox/done': 'observer', timeline: 'observer', state: 'observer', events: 'observer', hosts: 'observer', messages: 'observer', stream: 'observer', boards: 'observer', 'boards/tasks': 'observer', 'boards/task': 'observer', 'boards/trash': 'manager', usage: 'observer', webhooks: 'observer', 'webhooks/deliveries': 'observer', 'webhooks/delivery': 'observer' },
377
380
  actions: {
378
381
  'inbox/resolve': 'operator', 'inbox/read-all': 'operator', 'inbox/answer': 'operator', 'inbox/dismiss': 'operator', kick: 'operator', clear: 'operator', archive: 'operator', unarchive: 'operator',
379
382
  'terminals/open': 'operator', 'terminals/kill': 'operator', 'terminal/ticket': 'operator', 'hosts/personas': 'operator',
@@ -384,6 +387,7 @@ export function createDashboard(platform, { sessions, observation, machines, mes
384
387
  'permissions/save': 'manager', 'permissions/delete': 'manager', 'permissions/assign': 'manager',
385
388
  'tasks/create': 'operator', 'tasks/update': 'operator', 'tasks/comment': 'operator', 'tasks/notify': 'operator',
386
389
  'tasks/delete': 'manager', 'tasks/restore': 'manager', 'boards/create': 'manager', 'boards/update': 'manager', 'boards/delete': 'manager', 'boards/prefix': 'manager', 'boards/flow': 'manager', 'boards/github': 'manager', 'boards/github-off': 'manager', 'boards/github-merge': 'manager', 'boards/github-sync': 'operator', 'boards/github-watch': 'observer',
390
+ 'webhooks/create': 'manager', 'webhooks/update': 'manager', 'webhooks/secret': 'manager', 'webhooks/delete': 'manager', 'webhooks/test': 'manager', 'webhooks/redeliver': 'manager',
387
391
  },
388
392
  }
389
393
  for (const [table, roles] of [[dashboardActions, dashboardRoles.actions], [{ ...dashboardReads, stream: true }, dashboardRoles.reads]]) {
@@ -296,6 +296,8 @@ export function createMachines(platform, { sessions, observation, permissions })
296
296
  created_at: Number.isFinite(t?.created_at) ? t.created_at : null,
297
297
  // The permission profile it was opened with, by name (only for showing).
298
298
  profile: str(t?.profile, 40),
299
+ // Why its plugin didn't log in, as the machine read it (only for showing).
300
+ login_error: str(t?.login_error, 600),
299
301
  })).filter(t => t.id && NAME_RE.test(t.id))
300
302
  return {
301
303
  hostname: str(info.hostname, 100),
@@ -1,3 +1,3 @@
1
- export { createMessaging } from './messaging.js'
1
+ export { createMessaging, WEBHOOK_SENDER } from './messaging.js'
2
2
  export { createInbox } from './inbox.js'
3
3
  export { createPlans } from './plans.js'
@@ -1,10 +1,13 @@
1
1
  import { extname, join } from 'node:path'
2
- import { randomBytes } from 'node:crypto'
3
- import { rmSync } from 'node:fs'
2
+ import { createHash, randomBytes } from 'node:crypto'
3
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
4
4
  import {
5
5
  unix, now, cutText, cleanText, bad, ApiError, readBodyToFile,
6
6
  } from '../platform/index.js'
7
7
 
8
+ // The server's own sender of what a webhook brought (see server/webhooks).
9
+ export const WEBHOOK_SENDER = 'pisha:webhook'
10
+
8
11
  export function createMessaging(platform, { sessions }) {
9
12
  const {
10
13
  db, signAsServer, broadcast, inTx, bus, dataDir, allow, counted, rateLimit, spendStorage, ensureRoom, readLimit, groupLimit, quota,
@@ -225,6 +228,7 @@ export function createMessaging(platform, { sessions }) {
225
228
  // (A notice about a worker counts as the worker's: it shares that worker's
226
229
  // queue cap and goes when the worker is deleted.)
227
230
  inTx(() => { for (const r of recipients) if (!skip.has(r)) pushUpdate(r, { message: msg }, from) })
231
+ bus.emit('message-stored', row)
228
232
  // Tell the sender who isn't connected: queued (coordinators) or, in a group,
229
233
  // skipped (workers).
230
234
  return offline.length ? { ...msg, pisha_offline_recipients: offline } : msg
@@ -544,8 +548,30 @@ export function createMessaging(platform, { sessions }) {
544
548
  // such, from a sender no session can be (see server/boards).
545
549
  const boardNotice = (coordinator, text) => storeMessage('pisha:board', coordinator, { text, system: true })
546
550
 
551
+ // From a webhook to its department's coordinator: what an outside service
552
+ // sent, as it came, in an attached file; and the server's words about it
553
+ // (which name the file and its sha256: they are what is signed, so the
554
+ // plugin checks the file against them). See server/webhooks.
555
+ function webhookNotice(coordinator, textFor, { name, bytes }) {
556
+ ensureRoom()
557
+ if (db.prepare('SELECT COALESCE(SUM(size), 0) AS n FROM files').get().n + bytes.length > quota('max_files_gb', MAX_FILES_GB) * 1024 ** 3) throw new ApiError(507, 'Insufficient Storage: the server keeps no more attachments until old ones expire')
558
+ const fileId = `f_${randomBytes(12).toString('base64url')}`
559
+ const rel = `files/${fileId}.json`
560
+ mkdirSync(join(dataDir, 'files'), { recursive: true })
561
+ writeFileSync(join(dataDir, rel), bytes, { mode: 0o600, flag: 'wx' })
562
+ try {
563
+ db.prepare('INSERT INTO files (file_id, file_unique_id, path, name, mime, size, owner, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
564
+ .run(fileId, randomBytes(6).toString('hex'), rel, name.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120), 'application/json', bytes.length, WEBHOOK_SENDER, now())
565
+ return storeMessage(WEBHOOK_SENDER, coordinator, { text: textFor(fileId, createHash('sha256').update(bytes).digest('hex')), fileId, fileKind: 'document', system: true })
566
+ } catch (err) {
567
+ db.prepare('DELETE FROM files WHERE file_id = ?').run(fileId)
568
+ rmSync(join(dataDir, rel), { force: true })
569
+ throw err
570
+ }
571
+ }
572
+
547
573
  return {
548
- boardNotice, messagingMethods, cleanupMessages, upload, uploadMime, canSeeFile, related, messageView, closeGroup,
574
+ boardNotice, webhookNotice, messagingMethods, cleanupMessages, upload, uploadMime, canSeeFile, related, messageView, closeGroup,
549
575
  handOverGroup, fileRow,
550
576
  }
551
577
  }
@@ -11,7 +11,7 @@ export function createObservation(platform) {
11
11
  // everything to dashboard clients as it happens.
12
12
  const EVENT_KINDS = new Set([
13
13
  'observe_start', 'session_start', 'prompt', 'tool_start', 'tool_end', 'text', 'usage',
14
- 'notification', 'subagent_start', 'subagent_stop', 'stop', 'compact', 'compacted', 'session_end',
14
+ 'notification', 'subagent_start', 'subagent_stop', 'stop', 'compact', 'compacted', 'session_end', 'tokens',
15
15
  ])
16
16
  const MAX_EVENT_JSON = 20_000
17
17
  const activity = new Map() // name -> derived state
@@ -43,6 +43,9 @@ export function createObservation(platform) {
43
43
  compact: { trigger: STR(20) },
44
44
  compacted: { trigger: STR(20), summary: STR(20_000) },
45
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) },
46
49
  }
47
50
  function cleanEvent(kind, data) {
48
51
  const out = {}
@@ -123,8 +126,26 @@ export function createObservation(platform) {
123
126
  case 'session_end': a.tool = null; set('ended'); break
124
127
  }
125
128
  if (a.state !== 'waiting') a.waiting = null
129
+ // (Its prompt was answered, wherever: no longer with its coordinator.)
130
+ if (a.relayed_to && ((ev.kind === 'tool_end' && !ev.agent) || ev.kind === 'stop' || ev.kind === 'session_end' || (ev.kind === 'prompt' && !ev.channel))) a.relayed_to = null
126
131
  }
127
132
 
133
+ // A worker's permission prompt relayed to its coordinator (the plugin's
134
+ // "🔐 Permission:" message): the dashboard shows it as being decided there,
135
+ // until the call runs or the request is withdrawn. (Only what the dashboard
136
+ // shows: who may answer is the plugin's business.)
137
+ bus.on('message-stored', row => {
138
+ const text = String(row?.text ?? '')
139
+ if (!text.startsWith('🔐 Permission')) return
140
+ const coordinator = db.prepare("SELECT coordinator FROM identities WHERE name = ? AND role = 'worker'").get(row.from_name)?.coordinator
141
+ if (!coordinator || coordinator !== row.target) return
142
+ const a = activityOf(row.from_name)
143
+ const relayed = text.startsWith('🔐 Permission: ') ? coordinator : null
144
+ if ((a.relayed_to ?? null) === relayed) return
145
+ a.relayed_to = relayed
146
+ bus.emit('session-changed', row.from_name)
147
+ })
148
+
128
149
  // Per identity: at most 120 observe calls and 3000 events a minute.
129
150
  const observeLog = new Map() // name -> [{ t, n }]
130
151
 
@@ -149,13 +170,16 @@ export function createObservation(platform) {
149
170
  const insert = db.prepare('INSERT INTO events (session, ts, kind, data) VALUES (?, ?, ?, ?)')
150
171
  // The whole batch is checked first, then stored at once: all of it or none
151
172
  // (a refusal halfway would store part of it and the retry would repeat it).
152
- const batch = []
173
+ const batch = [], tokens = []
153
174
  for (const ev of events) {
154
175
  if (!ev || typeof ev !== 'object' || !EVENT_KINDS.has(ev.kind)) continue
155
176
  // 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()
177
+ // (Tokens are kept far longer than events: one reported late keeps its day, up to 30 back.)
178
+ const oldest = ev.kind === 'tokens' ? now() - 30 * 24 * 3600_000 : now() - eventKeptMs()
179
+ const ts = Number.isSafeInteger(ev.ts) ? Math.max(oldest, Math.min(ev.ts, now() + 5000)) : now()
157
180
  const kind = ev.kind
158
181
  const rest = cleanEvent(kind, ev)
182
+ if (kind === 'tokens') { tokens.push({ ...rest, ts }); continue }
159
183
  const data = JSON.stringify(rest)
160
184
  if (data.length > MAX_EVENT_JSON) continue
161
185
  batch.push({ ts, kind, rest, data })
@@ -176,7 +200,9 @@ export function createObservation(platform) {
176
200
  stored++
177
201
  } })
178
202
  if (stored) bus.emit('session-changed', name)
179
- return { stored }
203
+ if (batch.length) bus.emit('observed', name, batch.map(({ ts, kind, rest }) => ({ ...rest, ts, kind })))
204
+ if (tokens.length) bus.emit('tokens', name, tokens)
205
+ return { stored: stored + tokens.length }
180
206
  }
181
207
 
182
208
  // Tell a worker's coordinator when its context is nearly full (once per fill-up)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pisha-server",
3
- "version": "0.0.11",
3
+ "version": "0.0.13",
4
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
5
  "keywords": [
6
6
  "pisha",
@@ -32,7 +32,9 @@
32
32
  "platform",
33
33
  "sessions",
34
34
  "ui",
35
+ "usage",
35
36
  "vendor",
37
+ "webhooks",
36
38
  "install",
37
39
  "pisha-host.mjs",
38
40
  "pisha-host.mjs.sig",
package/pisha-host.mjs CHANGED
@@ -39,7 +39,7 @@ import { fileURLToPath } from 'node:url'
39
39
  import { createCipheriv, createDecipheriv, createHash, createPrivateKey, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes, sign, verify } from 'node:crypto'
40
40
  import { promisify } from 'node:util'
41
41
 
42
- const VERSION = '0.0.11'
42
+ const VERSION = '0.0.13'
43
43
  // Who signs releases (scripts/release-sign.mjs): `update` only installs what
44
44
  // this key signed. Empty: this copy has no key to check with.
45
45
  const RELEASE_PUBLIC_KEY = 'MCowBQYDK2VwAyEA49ojJq4r4KLiWcRJiDxui2HzSZYpZA1qCBI4LLtOOyo'
@@ -562,7 +562,16 @@ function computeTrustedPath() {
562
562
  // A real node later on: the shim folders go after everything else.
563
563
  // None at all: they are left out (a shim that picks by folder never decides).
564
564
  const realNode = dirs.some(d => { const p = join(d, 'node'); try { accessSync(p, FS.X_OK) } catch { return false } return !dispatcherOf(p) && !untrustedExecutable(p) })
565
- return [...dirs, ...(realNode ? moved : [])].join(':') || '/usr/bin:/bin'
565
+ const path = [...dirs, ...(realNode ? moved : [])]
566
+ // No usable node on the PATH at all (a version manager's not loaded where
567
+ // this was started, a ~/.bashrc the installer couldn't write): the one this
568
+ // program runs on, which its launcher chose, or the plugin and its hooks
569
+ // couldn't start in any session.
570
+ if (!realNode) {
571
+ const own = dirname(process.execPath)
572
+ if (isAbsolute(own) && !untrustedFolder(own) && !untrustedExecutable(process.execPath) && !sessionRoots().some(r => within(realOr(own), r))) path.push(own)
573
+ }
574
+ return path.join(':') || '/usr/bin:/bin'
566
575
  }
567
576
  function computeTrustedFolders() {
568
577
  const roots = sessionRoots()
@@ -643,11 +652,13 @@ async function listTerminals() {
643
652
  agent: AGENT_IDS.includes(spec.agent) ? spec.agent : 'claude',
644
653
  profile: typeof spec.profile === 'string' ? spec.profile : null,
645
654
  created_at: Number(created) * 1000,
655
+ ...claudeCode.loginError(tname.slice(PREFIX.length), Number(created) * 1000),
646
656
  })
647
657
  }
648
658
  return list
649
659
  }
650
660
 
661
+
651
662
  // --- validation of what the server asks for -------------------------------------------
652
663
 
653
664
  function insideAllowed(real, folders) {
@@ -1278,12 +1289,15 @@ function sessionCommand(s, claude, dir, env) {
1278
1289
  if (s.personaInfo?.kind === 'agent') argv.push('--agent', s.personaInfo.name)
1279
1290
  // Its permission profile, as Claude Code's own rules: they are added to the
1280
1291
  // user's and the project's, and a rule that forbids wins over any that
1281
- // allows, wherever each one is.
1292
+ // allows, wherever each one is. Always with the session's own inbox, where
1293
+ // the plugin saves what other sessions and webhooks attach: it is outside
1294
+ // the working folder, and reading it must not wait for an absent user.
1295
+ // ("//" starts an absolute path in a rule.)
1282
1296
  const permissionsFile = join(dir, 'permissions.json')
1283
- if (s.permissions) {
1284
- writePrivate(permissionsFile, JSON.stringify({ permissions: { allow: s.permissions.allow, ask: s.permissions.ask, deny: s.permissions.deny } }, null, 2) + '\n')
1285
- argv.push('--settings', permissionsFile)
1286
- } else rmSync(permissionsFile, { force: true })
1297
+ const inbox = `Read(/${join(dir, 'inbox')}/**)`
1298
+ const p = s.permissions ?? { allow: [], ask: [], deny: [] }
1299
+ writePrivate(permissionsFile, JSON.stringify({ permissions: { allow: [inbox, ...p.allow], ask: p.ask, deny: p.deny } }, null, 2) + '\n')
1300
+ argv.push('--settings', permissionsFile)
1287
1301
  return argv
1288
1302
  }
1289
1303
 
@@ -1310,12 +1324,31 @@ const clearContext = target => typeLine(target, '/clear', /(^|\s)\/clear\s*$/m)
1310
1324
  async function typeAnswer(target, text) {
1311
1325
  const line = String(text).replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/\s+/g, ' ').trim()
1312
1326
  if (!line || line.length > 2200) throw new Error('the answer must be one line of up to 2200 characters')
1313
- const end = line.split(' ').pop().slice(-20).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1314
- await typeLine(target, line, new RegExp(`${end}\\s*│?\\s*$`, 'm'))
1327
+ await typeLine(target, line, { test: screen => answerLanded(screen, line) })
1328
+ }
1329
+
1330
+ // Whether a typed answer reached the input: its end is there, or the paste
1331
+ // Claude Code shows a long one as instead ("[Pasted text #1 +3 lines]").
1332
+ export function answerLanded(screen, line) {
1333
+ const end = String(line).split(' ').pop().slice(-20).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1334
+ return new RegExp(`(${end}|\\[Pasted text #\\d+[^\\]\\n]*\\])\\s*│?\\s*$`, 'm').test(screen)
1315
1335
  }
1316
1336
 
1317
1337
  const ASKING_ON_SCREEN = /^\s*❯\s*\d+\.\s|Esc to cancel|Enter to confirm/m
1318
1338
 
1339
+ // Why the plugin of a session didn't log in, if it said so since this start
1340
+ // (<state>/login-error.json): only the plugin's stderr knows otherwise, and
1341
+ // the dashboard would just show the session as disconnected.
1342
+ function loginError(name, since) {
1343
+ try {
1344
+ const file = join(pluginStateDir(name), 'login-error.json')
1345
+ const st = lstatSync(file)
1346
+ if (!st.isFile() || st.size > 4096 || st.mtimeMs < since - 2000) return {}
1347
+ const message = JSON.parse(readFileSync(file, 'utf8'))?.message
1348
+ return typeof message === 'string' && message ? { login_error: plain(message.replace(/\s+/g, ' ')).slice(0, 600) } : {}
1349
+ } catch { return {} }
1350
+ }
1351
+
1319
1352
  const claudeCode = {
1320
1353
  // Where the program is (checked, see claudeBinary), and which version.
1321
1354
  program: claudeBinary,
@@ -1336,6 +1369,8 @@ const claudeCode = {
1336
1369
  findPersona,
1337
1370
  personaPrompt,
1338
1371
  conversation: ownConversation,
1372
+ // Why its plugin didn't log in, if it said so (for the dashboard).
1373
+ loginError,
1339
1374
  // The Pisha plugin in its config: installed, and how it is set up.
1340
1375
  plugin: {
1341
1376
  status: pluginStatus,
@@ -1 +1 @@
1
- stnwU7f_BWFK8fWnHhNqphYUwM7ZGB7RcefscQJlTRsEo2ieCJsn-X7vJqngdDLuVBdVzyatJykReFBnRLMkAw
1
+ ECnPFf64Gg00O6lfuvrVGylNFyyPcZxNnSjJXpPzQGJLYFkSHhpnI8q12o0voylVyULcoRHgj66Wrvx5S0h2Cg
package/platform/http.js CHANGED
@@ -86,6 +86,8 @@ const bodyPools = {
86
86
  main: { bytes: 0, cap: BODY_BYTES_IN_FLIGHT, free: 64 * 1024 },
87
87
  // (A registration's body, at most 4 KB, never counts: enrollments can't block it.)
88
88
  public: { bytes: 0, cap: 4 * 1024 * 1024, free: 4096, deadline: 10_000 },
89
+ // Webhooks from other services: anyone can send them too, and they are bigger.
90
+ hooks: { bytes: 0, cap: 16 * 1024 * 1024, free: 0, deadline: 10_000 },
89
91
  }
90
92
 
91
93
  // An upload, straight to its file: the same limits as readBody (size, idle
@@ -121,7 +123,7 @@ export function readBodyToFile(req, max, path) {
121
123
  req.on('close', () => { if (finish(false)) reject(new ApiError(400, 'Bad Request: connection closed')) })
122
124
  })
123
125
  }
124
- function readBody(req, max, { pool: poolName = 'main' } = {}) {
126
+ export function readBody(req, max, { pool: poolName = 'main' } = {}) {
125
127
  const pool = bodyPools[poolName]
126
128
  return new Promise((resolve, reject) => {
127
129
  if (Number(req.headers['content-length'] ?? 0) > max) {
package/platform/index.js CHANGED
@@ -29,6 +29,9 @@ export const FIRST_COMPANY = 'default'
29
29
  // session-changed (name) what the dashboard shows of it changed
30
30
  // notice (worker, text) its coordinator should hear this
31
31
  // context-cleared (name) /clear took effect in that session
32
+ // observed (name, events) what a session reported doing, as it was stored
33
+ // tokens (name, list) what it spent, and on what
34
+ // message-stored (row) a message, as it was stored
32
35
  export function createPlatform(server, { id, dir, quotas, routeEnrollment }) {
33
36
  // What repeats while this company runs, and stops with it.
34
37
  const timers = new Set()
package/routes.js CHANGED
@@ -3,7 +3,7 @@ import { statSync, createReadStream } from 'node:fs'
3
3
  import {
4
4
  guardRequest, sendJson, clientIp, readParams, bearer, own, sendError, VERSION, UI_FILE, VENDOR_FILES, APP_FILES,
5
5
  MAX_JSON_BODY, cachedFile, pageHeaders, ApiError, allowServerWide, ipKey, sha256, refuseSocket, logError,
6
- ALLOW_TOKEN_API, atLeast, pathTooLong, cleanText, trimSlashes,
6
+ ALLOW_TOKEN_API, atLeast, pathTooLong, cleanText, trimSlashes, countedServerWide,
7
7
  } from './platform/index.js'
8
8
  import {
9
9
  INSTALLERS, installer, hostScript, hostSignature, checkEnrollRate, enrollmentKey, offeredCredential,
@@ -228,6 +228,20 @@ export function createRoutes(server, companies, accounts) {
228
228
  return sendJson(res, 200, { ok: true, result })
229
229
  }
230
230
 
231
+ // A webhook from another service: anyone can send one, and only its
232
+ // secret makes it count (server/webhooks). Its path says nothing of
233
+ // the company: each one's webhooks are looked through.
234
+ if (path.startsWith('/hooks/')) {
235
+ if (req.method !== 'POST') throw new ApiError(405, 'Method Not Allowed')
236
+ const id = path.slice('/hooks/'.length)
237
+ const ip = ipKey(clientIp(req))
238
+ // (Guessing paths: a few misses a minute per address, then nothing.)
239
+ if (countedServerWide('webhook-miss', ip) >= 30) throw new ApiError(429, 'Too Many Requests: retry in a minute')
240
+ const company = companies.all().find(c => c.webhooks.has(id))
241
+ if (!company) { allowServerWide('webhook-miss', ip, 30); throw new ApiError(404, 'Not Found') }
242
+ return await company.webhooks.receive(id, req, res)
243
+ }
244
+
231
245
  const token = bearer(req)
232
246
 
233
247
  // A machine's secret stays in an Authorization header, which proxies hide
package/ui/addmachine.js CHANGED
@@ -86,6 +86,13 @@ export function renderAddMachine() {
86
86
  export const refreshAddMachine = () => { if (currentRoute().view === 'addmachine' && !$('addmachine').hidden) renderAddMachine() }
87
87
  // Done with it (a session or team opened from it, or cancelled): the next visit starts afresh.
88
88
  export const forgetAddMachine = () => { clearTimeout(draft?.slowTimer); draft = null }
89
+ // Coming to add a machine (the sidebar's "+", the palette, a link): one
90
+ // already added, or a code that expired unused, isn't shown again as if it
91
+ // were the new one. Halfway, it is kept. (Before the router draws the page:
92
+ // this module's listener was added first.)
93
+ window.addEventListener('hashchange', e => {
94
+ if (location.hash === '#/hosts/new' && !/#\/hosts\/new$/.test(e.oldURL) && draft && (draft.joined || expired())) forgetAddMachine()
95
+ })
89
96
 
90
97
  async function generate() {
91
98
  draft.generating = true
package/ui/back.js CHANGED
@@ -59,6 +59,8 @@ export function parentOf(r) {
59
59
  case 'hosts': return r.host ? '#/hosts' : null
60
60
  case 'addmachine': return '#/hosts'
61
61
  case 'boards': return null
62
+ case 'usage': return null
63
+ case 'webhooks': return r.team ? `#/q/${enc(r.team)}` : null
62
64
  case 'board': return r.task ? `#/b/${r.board}` : '#/boards'
63
65
  case 'terminal': return `#/h/${enc(r.host)}`
64
66
  case 'session': {
@@ -90,6 +92,8 @@ export function placeName(hash) {
90
92
  case 'newteam': return T.newTeam
91
93
  case 'addmachine': return T.addTitle
92
94
  case 'boards': return T.boards
95
+ case 'usage': return T.usage
96
+ case 'webhooks': return r.team ? T.whLogOf(team(r.team)) : T.whTitle
93
97
  case 'board': return state.boards.find(b => b.id === r.board)?.name ?? T.boards
94
98
  default: return T.leads
95
99
  }
package/ui/content.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { store } from './dom.js'
2
2
  import { T, COLLATOR } from './i18n.js'
3
- import { sessions, companyPref } from './state.js'
3
+ import { sessions, hosts, companyPref } from './state.js'
4
4
  import { esc, dur, now } from './format.js'
5
5
  import { nowPhrase } from './doing.js'
6
6
 
@@ -105,12 +105,24 @@ function md(src) {
105
105
  // The tool and its exact arguments, for a tooltip.
106
106
  const toolLine = t => [t?.name, t?.summary].filter(Boolean).join(' · ')
107
107
 
108
+ // Why the plugin of a session its machine runs didn't log in, as the machine
109
+ // read it (only on the machine the server opened it on).
110
+ export function loginError(s) {
111
+ const h = s?.host_id ? hosts.get(s.host_id) : null
112
+ return (h?.online && h.info?.terminals?.find(t => t.id === s.name)?.login_error) || null
113
+ }
114
+
108
115
  // session status (sidebar, pane headers, status bars). title: the detail
109
116
  // behind text, when there is more (the command it runs).
110
117
  export function status(s) {
111
118
  if (!s) return { dot: '', text: '' }
112
119
  const a = s.activity ?? {}
113
- if (!s.online) return { dot: '', text: T.offline(s.last_seen_at ? dur(now() - s.last_seen_at * 1000) : '—') }
120
+ if (!s.online) {
121
+ // Running on its machine, but its plugin said why it didn't log in.
122
+ const why = loginError(s)
123
+ if (why) return { dot: 'err', text: T.notJoined, title: why, why }
124
+ return { dot: '', text: T.offline(s.last_seen_at ? dur(now() - s.last_seen_at * 1000) : '—') }
125
+ }
114
126
  switch (a.state) {
115
127
  // (A phrase, not the command: the command itself is in the tooltip.)
116
128
  case 'tool': return { dot: 'ok pulse', text: `${nowPhrase(a.tool)} · ${dur(now() - (a.tool?.since ?? now()))}`, title: toolLine(a.tool) }