pisha-server 0.0.0-stage → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/accounts/accounts.js +754 -0
  4. package/accounts/index.js +1 -0
  5. package/accounts/passwords.js +41 -0
  6. package/accounts/totp.js +54 -0
  7. package/boards/boards.js +1087 -0
  8. package/boards/github.js +212 -0
  9. package/boards/index.js +1 -0
  10. package/boards/sync.js +980 -0
  11. package/companies.js +294 -0
  12. package/company-export.js +101 -0
  13. package/company.js +82 -0
  14. package/dashboard/dashboard.js +408 -0
  15. package/dashboard/index.js +1 -0
  16. package/data-upgrade.js +69 -0
  17. package/install/linux.sh +181 -0
  18. package/install/macos.sh +121 -0
  19. package/install/windows.bat +54 -0
  20. package/machines/index.js +3 -0
  21. package/machines/machines.js +910 -0
  22. package/messaging/inbox.js +252 -0
  23. package/messaging/index.js +3 -0
  24. package/messaging/messaging.js +551 -0
  25. package/messaging/plans.js +67 -0
  26. package/observation/index.js +1 -0
  27. package/observation/observation.js +231 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +55 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3303 -0
  34. package/pisha-host.mjs.sig +1 -0
  35. package/platform/acme.js +207 -0
  36. package/platform/basics.js +14 -0
  37. package/platform/config.js +154 -0
  38. package/platform/control.js +93 -0
  39. package/platform/credentials.js +151 -0
  40. package/platform/database.js +251 -0
  41. package/platform/errors.js +13 -0
  42. package/platform/files.js +50 -0
  43. package/platform/http.js +207 -0
  44. package/platform/index.js +58 -0
  45. package/platform/limits.js +122 -0
  46. package/platform/listen.js +183 -0
  47. package/platform/roles.js +6 -0
  48. package/platform/stream.js +19 -0
  49. package/platform/text.js +83 -0
  50. package/platform/ws.js +186 -0
  51. package/routes.js +405 -0
  52. package/server.js +65 -0
  53. package/sessions/index.js +1 -0
  54. package/sessions/sessions.js +533 -0
  55. package/ui/LICENSE-affectui.txt +26 -0
  56. package/ui/addmachine.js +151 -0
  57. package/ui/api.js +20 -0
  58. package/ui/app.js +143 -0
  59. package/ui/attention.js +78 -0
  60. package/ui/back.js +168 -0
  61. package/ui/boards.js +958 -0
  62. package/ui/chat.js +388 -0
  63. package/ui/content.js +157 -0
  64. package/ui/dialogs.js +135 -0
  65. package/ui/doing.js +112 -0
  66. package/ui/dom.js +6 -0
  67. package/ui/ds-base.css +146 -0
  68. package/ui/ds-components.css +229 -0
  69. package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
  70. package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
  71. package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  72. package/ui/format.js +25 -0
  73. package/ui/i18n.js +2145 -0
  74. package/ui/icons/apple-touch-icon.png +0 -0
  75. package/ui/icons/icon-192.png +0 -0
  76. package/ui/icons/icon-512.png +0 -0
  77. package/ui/icons/maskable-512.png +0 -0
  78. package/ui/icons.js +41 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +105 -0
  81. package/ui/machines.js +261 -0
  82. package/ui/manifest.webmanifest +16 -0
  83. package/ui/mosaic.js +189 -0
  84. package/ui/nav.js +142 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +669 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +180 -0
  89. package/ui/people.js +371 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +173 -0
  93. package/ui/routes.js +47 -0
  94. package/ui/screen-boards.css +241 -0
  95. package/ui/screen-inbox.css +201 -0
  96. package/ui/screen-machines.css +76 -0
  97. package/ui/screen-mosaic.css +26 -0
  98. package/ui/screen-newteam.css +90 -0
  99. package/ui/screen-org.css +119 -0
  100. package/ui/screen-session.css +99 -0
  101. package/ui/screen-signin.css +28 -0
  102. package/ui/screen-team.css +80 -0
  103. package/ui/screen-teams.css +41 -0
  104. package/ui/screen-usage.css +60 -0
  105. package/ui/session.js +42 -0
  106. package/ui/shell.css +122 -0
  107. package/ui/signin.js +120 -0
  108. package/ui/squads.js +371 -0
  109. package/ui/state.js +59 -0
  110. package/ui/stream.js +269 -0
  111. package/ui/styles.css +343 -0
  112. package/ui/team.js +115 -0
  113. package/ui/teams.js +58 -0
  114. package/ui/terminal.js +261 -0
  115. package/ui/theme.js +32 -0
  116. package/ui/timeline.js +163 -0
  117. package/ui/topbar.js +211 -0
  118. package/ui/usage.js +175 -0
  119. package/ui/voice-parse.js +98 -0
  120. package/ui/voice.js +320 -0
  121. package/usage/index.js +1 -0
  122. package/usage/usage.js +127 -0
  123. package/vendor/InterVariable.woff2 +0 -0
  124. package/vendor/LICENSE-inter +92 -0
  125. package/vendor/LICENSE-xterm +21 -0
  126. package/vendor/README.md +8 -0
  127. package/vendor/addon-fit.js +2 -0
  128. package/vendor/xterm.css +218 -0
  129. package/vendor/xterm.js +2 -0
package/pisha-host.mjs ADDED
@@ -0,0 +1,3303 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pisha-host — opens Claude Code sessions on this machine for the Pisha
4
+ * dashboard, and lets the dashboard see and type into their terminals.
5
+ *
6
+ * Security model: the server can only ask for a session *spec* — a name, a
7
+ * role, a folder, the auto-compact window and the id of a persona (a skill or
8
+ * agent this machine found in that folder) — never a command. Every field is
9
+ * validated here, against limits that live in this machine's settings file
10
+ * (allowed folders, maximum sessions, whether the web terminal may type), so a
11
+ * compromised server cannot widen them. The command is always the same:
12
+ *
13
+ * claude --dangerously-load-development-channels plugin:pisha@pisha [--resume <its own conversation>]
14
+ * [--append-system-prompt-file <its private copy of the skill> | --agent <name>]
15
+ *
16
+ * Typing in a session's terminal from the dashboard is, by nature, the same as
17
+ * sitting at this machine: anyone holding the dashboard can make Claude run
18
+ * things. Turn it off with "allow_input": false in settings.json if you only
19
+ * want to watch.
20
+ *
21
+ * Sessions run in tmux (a private server: tmux -L pisha), so they survive
22
+ * restarts of this program and can be attached locally:
23
+ * tmux -L pisha attach -t sq-<name>
24
+ *
25
+ * A machine can serve several companies: one copy of this program per company
26
+ * (--company=<id>, which the dashboard's command says), with its own folder,
27
+ * tmux server, Claude Code configuration and service. Apart for accidents only
28
+ * under one system user: to separate them for real, use one user per company.
29
+ *
30
+ * Requirements: Node >= 22.13, tmux >= 3.2 and Claude Code. No npm dependencies.
31
+ * Runs on Linux and macOS. On Windows, run it inside WSL (it needs tmux).
32
+ */
33
+
34
+ import { execFile, execFileSync, spawn } from 'node:child_process'
35
+ import { appendFileSync, linkSync, readdirSync, readFileSync, writeFileSync, mkdirSync, existsSync, realpathSync, statSync, lstatSync, readlinkSync, openSync, readSync, closeSync, renameSync, copyFileSync, rmSync, chmodSync, accessSync, constants as FS } from 'node:fs'
36
+ import { homedir, hostname, platform, arch, userInfo, tmpdir } from 'node:os'
37
+ import { join, resolve, sep, isAbsolute, dirname, basename } from 'node:path'
38
+ import { fileURLToPath } from 'node:url'
39
+ import { createCipheriv, createDecipheriv, createHash, createPrivateKey, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes, sign, verify } from 'node:crypto'
40
+ import { promisify } from 'node:util'
41
+
42
+ const VERSION = '0.0.12'
43
+ // Who signs releases (scripts/release-sign.mjs): `update` only installs what
44
+ // this key signed. Empty: this copy has no key to check with.
45
+ const RELEASE_PUBLIC_KEY = 'MCowBQYDK2VwAyEA49ojJq4r4KLiWcRJiDxui2HzSZYpZA1qCBI4LLtOOyo'
46
+ const run = promisify(execFile)
47
+ // Never talk to the server without checking its certificate.
48
+ delete process.env.NODE_TLS_REJECT_UNAUTHORIZED
49
+
50
+ // The company this copy serves. (None: the server's first company, or a server
51
+ // without companies, with everything where it always was.)
52
+ const UNDER_SESSION = !!process.env.TMUX // (sessions never get the variable below: see tmuxEnv)
53
+ const COMPANY = process.argv.slice(2).find(a => a.startsWith('--company='))?.slice('--company='.length) ?? (UNDER_SESSION ? '' : process.env.PISHA_COMPANY) ?? ''
54
+ if (COMPANY && !/^[a-z0-9]{8}$/.test(COMPANY)) {
55
+ process.stderr.write('pisha-host: --company must be the 8 characters the dashboard gives\n')
56
+ process.exit(2)
57
+ }
58
+ if (COMPANY) process.env.PISHA_COMPANY = COMPANY // (for what this program starts again)
59
+ const BASE_DIR = join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'pisha-host')
60
+ const CONFIG_DIR = process.env.PISHA_HOST_DIR ?? (COMPANY ? join(BASE_DIR, 'companies', COMPANY) : BASE_DIR)
61
+ // Its own Claude Code: another login, history, skills and plugin settings. Always
62
+ // this one: run from inside another company's session, that session's isn't this
63
+ // copy's. And without a company, not a company's folder, for the same reason.
64
+ if (COMPANY) process.env.CLAUDE_CONFIG_DIR = join(CONFIG_DIR, 'claude')
65
+ else if (process.env.CLAUDE_CONFIG_DIR && resolve(process.env.CLAUDE_CONFIG_DIR).startsWith(join(BASE_DIR, 'companies') + sep)) delete process.env.CLAUDE_CONFIG_DIR
66
+ const CREDENTIALS_FILE = join(CONFIG_DIR, 'credentials.json')
67
+ const HOST_KEY_FILE = join(CONFIG_DIR, 'host-key.json')
68
+ const SETTINGS_FILE = join(CONFIG_DIR, 'settings.json')
69
+ const INSTALLED_SCRIPT = join(CONFIG_DIR, 'pisha-host.mjs')
70
+
71
+ // A setup of its own (PISHA_HOST_DIR) has its own tmux server too. And each
72
+ // copy marks its sessions: sharing a socket by hand, none takes another's.
73
+ // (No mark: from before there were any, so the plain copy's on its plain socket.)
74
+ const OWNER_TAG = createHash('sha256').update(CONFIG_DIR).digest('hex').slice(0, 12)
75
+ const OWN_SETUP = process.env.PISHA_HOST_DIR != null || process.env.PISHA_TMUX_SOCKET != null
76
+ const TMUX_SOCKET = process.env.PISHA_TMUX_SOCKET ?? `${COMPANY ? `pisha-${COMPANY}` : 'pisha'}${process.env.PISHA_HOST_DIR ? `-${OWNER_TAG}` : ''}`
77
+ const PREFIX = 'sq-'
78
+ const NAME_RE = /^[A-Za-z0-9_-]{1,32}$/
79
+ const COMPACT_MIN = 50_000
80
+ const COMPACT_MAX = 1_000_000
81
+ const DEFAULT_SETTINGS = { folders: [], max_sessions: 8, allow_input: true, claude_command: 'claude' }
82
+ // The user's home from the user database (not $HOME).
83
+ const HOME = (() => { try { return userInfo().homedir || homedir() } catch { return homedir() } })()
84
+ // Never allowed as a place to open sessions, whatever settings.json says:
85
+ // a folder where credentials, caches or this program's configuration live,
86
+ // a system or shared temporary folder, or any folder that CONTAINS one of
87
+ // those or your home (/home, /Users…).
88
+ const FORBIDDEN_TREES = [
89
+ '.claude', '.ssh', '.config', '.aws', '.gnupg', '.kube', '.docker', '.azure', '.local', '.cache', 'Library',
90
+ '.mozilla', '.cargo', '.password-store', '.m2', 'snap', '.var', '.gradle', '.terraform.d',
91
+ ].map(d => join(HOME, d)).concat([
92
+ CONFIG_DIR, process.env.CLAUDE_CONFIG_DIR, process.env.XDG_CONFIG_HOME,
93
+ '/etc', '/root', '/proc', '/sys', '/dev', '/boot', '/usr', '/bin', '/sbin', '/lib', '/opt/homebrew', '/System', '/Library',
94
+ '/var/root', '/var/lib', '/var/log', '/var/run', '/var/spool', '/private/etc', '/private/var/root',
95
+ // Shared temporary folders (other users can plant a repository there).
96
+ // PISHA_HOST_TEST_ALLOW_TMP=1 lifts this, for the test suite only.
97
+ ...(process.env.PISHA_HOST_TEST_ALLOW_TMP === '1' ? [] : ['/tmp', '/var/tmp', '/private/tmp', '/var/folders', '/private/var/folders', tmpdir()]),
98
+ // (Not this user's own home, though: run as root — --allow-root —, /root is
99
+ // where its projects are, judged like any home: the folders inside it are
100
+ // fine, the whole of it only with --allow-home, its credentials never.)
101
+ ].filter(d => d && resolve(d) !== resolve(HOME)))
102
+ const realOr = p => { try { return realpathSync.native(p) } catch { return resolve(p) } }
103
+ // macOS file systems ignore case: compare that way there.
104
+ const norm = p => (platform() === 'darwin' ? p.toLowerCase() : p)
105
+ const within = (path, dir) => norm(path) === norm(dir) || norm(path).startsWith(norm(dir.endsWith(sep) ? dir : dir + sep))
106
+ // A path's real one: the nearest folder that exists, resolved, plus the part
107
+ // that doesn't exist yet. (The plugin's: both must pick the same folder.)
108
+ function realNearest(p) {
109
+ const tail = []
110
+ for (let d = resolve(p); ; d = dirname(d)) {
111
+ try { return join(realpathSync(d), ...tail.reverse()) } catch {}
112
+ if (dirname(d) === d) return resolve(p)
113
+ tail.push(basename(d))
114
+ }
115
+ }
116
+ // The same, also by the folders' identity (device and inode), as the plugin
117
+ // judges CLAUDE_CONFIG_DIR: where case or Unicode normalization is ignored
118
+ // (WSL's /mnt/c, casefold folders, macOS) two spellings are one folder.
119
+ function withinById(path, dir) {
120
+ if (within(path, dir)) return true
121
+ let id
122
+ try { const st = statSync(dir, { bigint: true }); id = `${st.dev}:${st.ino}` } catch { return false }
123
+ for (let x = path; ; x = dirname(x)) {
124
+ try { const st = statSync(x, { bigint: true }); if (`${st.dev}:${st.ino}` === id && st.ino !== 0n) return true } catch {}
125
+ if (dirname(x) === x) return false
126
+ }
127
+ }
128
+ // Only by identity: for what is allowed, where a spelling that looks alike must
129
+ // not count. A Mac's volume can tell case apart: Proj and PROJ, two folders.
130
+ function insideByIdentity(path, dir) {
131
+ let root
132
+ try { root = statSync(dir) } catch { return false }
133
+ for (let x = path; ; x = dirname(x)) {
134
+ try { const st = statSync(x); if (st.dev === root.dev && st.ino === root.ino && st.ino !== 0) return true } catch {}
135
+ if (dirname(x) === x) return false
136
+ }
137
+ }
138
+ // The home folder itself (not a folder inside it).
139
+ const isHome = real => [HOME, realOr(HOME)].some(h => withinById(real, h) && withinById(h, real))
140
+ // allowHome: the home folder itself is fine (started with --allow-home);
141
+ // a folder that contains it, and the credentials folders inside it, never.
142
+ function forbiddenFolder(real, { allowHome = false } = {}) {
143
+ const home = allowHome && isHome(real)
144
+ if (real === '/' || (!home && (withinById(HOME, real) || withinById(realOr(HOME), real)))) return allowHome ? 'a folder that contains your home' : 'your whole home, or a folder that contains it (start pisha-host with --allow-home to allow the home folder itself)'
145
+ const trees = FORBIDDEN_TREES.map(realOr)
146
+ if (trees.some(d => withinById(real, d))) return 'a system, temporary, credentials or configuration folder'
147
+ if (!home && trees.some(d => withinById(d, real))) return 'a folder that contains a system or credentials folder'
148
+ // Someone else's folder, or one anyone can write to (a shared drop-box) —
149
+ // the folder itself or any folder above it, where someone else could swap
150
+ // it for another one.
151
+ const me = typeof process.getuid === 'function' ? process.getuid() : null
152
+ for (let dir = real, first = true; ; first = false) {
153
+ let st
154
+ try { st = statSync(dir) } catch { return 'a folder that cannot be checked' }
155
+ if (me !== null && st.uid !== me && (first || st.uid !== 0)) return first ? 'a folder owned by another user' : 'inside a folder owned by another user'
156
+ if ((st.mode & 0o002) && (first || !(st.mode & 0o1000))) return first ? 'a folder anyone can write to' : 'inside a folder anyone can write to'
157
+ // Writable by a group that isn't this user's own: its members could plant
158
+ // hooks there (folders owned by root above it are fine).
159
+ // (On macOS everyone's own group is "staff", shared: there no group-writable
160
+ // folder counts as private. Root's folders above aren't exempt either.)
161
+ // (The sticky bit only protects what is inside a folder, never the session's own.)
162
+ if ((st.mode & 0o020) && (first || !(st.mode & 0o1000)) && !privateGroup(st.gid)) {
163
+ return `${first ? 'a folder another group can write to' : 'inside a folder another group can write to'} (if that group is only yours: chmod g-w ${dir})`
164
+ }
165
+ // Others given write access with an ACL (the mode bits don't show it).
166
+ // (The session's own folder: any ACL, even a default one that only
167
+ // what is created inside will get.)
168
+ if (aclGrantsWrite(dir, st, { always: first })) return first ? 'a folder with an ACL that lets others write to it' : 'inside a folder with an ACL that lets others write to it'
169
+ const up = dirname(dir)
170
+ if (up === dir) break
171
+ dir = up
172
+ }
173
+ return null
174
+ }
175
+
176
+ // The other copies of this program for this system user: each serves another
177
+ // company. (Not for a custom PISHA_HOST_DIR: a setup of its own, like the tests'.)
178
+ function otherInstances() {
179
+ if (process.env.PISHA_HOST_DIR) return []
180
+ const dirs = [BASE_DIR]
181
+ try { for (const d of readdirSync(join(BASE_DIR, 'companies'))) dirs.push(join(BASE_DIR, 'companies', d)) } catch {}
182
+ return dirs.filter(d => resolve(d) !== resolve(CONFIG_DIR))
183
+ }
184
+ const sharesUser = () => otherInstances().some(d => existsSync(join(d, 'credentials.json')))
185
+ // A folder belongs to one company on a machine: two would share its repository
186
+ // and its .claude/, each without knowing. (The settings of each say which, also
187
+ // of a copy that left its server: what it opened may still run. One that can't
188
+ // be read says nothing it can be trusted for, so it counts as saying yes.)
189
+ function folderOfAnotherCompany(real) {
190
+ for (const dir of otherInstances()) {
191
+ let list
192
+ try { list = JSON.parse(readFileSync(join(dir, 'settings.json'), 'utf8')).folders } catch (err) {
193
+ if (err.code === 'ENOENT') continue
194
+ return true
195
+ }
196
+ for (const f of Array.isArray(list) ? list : []) {
197
+ if (typeof f === 'string' && (withinById(real, realOr(f)) || withinById(realOr(f), real))) return true
198
+ }
199
+ }
200
+ return false
201
+ }
202
+
203
+ // Text that came from the server, printed on this terminal: no control
204
+ // characters (no escape sequences).
205
+ const plain = v => String(v ?? '').replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, '?')
206
+
207
+ const log = m => process.stderr.write(`pisha-host: ${m}\n`)
208
+ const die = (m, code = 1) => { process.stderr.write(`pisha-host: ${m}\n`); process.exit(code) }
209
+
210
+ // --- files ------------------------------------------------------------------------
211
+
212
+ function readJson(file, fallback) {
213
+ try { return JSON.parse(readFileSync(file, 'utf8')) } catch { return fallback }
214
+ }
215
+ function writeJson(file, data, mode = 0o600) {
216
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 })
217
+ // Whole or not at all: a crash here can't leave half a credentials file.
218
+ // (Still the file it was: a link stays a link, and a read-only one stays locked.)
219
+ const target = realOr(file)
220
+ if (existsSync(target)) accessSync(target, FS.W_OK)
221
+ const tmp = `${target}.${process.pid}.tmp`
222
+ rmSync(tmp, { force: true })
223
+ writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode, flag: 'wx' })
224
+ chmodSync(tmp, mode)
225
+ renameSync(tmp, target)
226
+ }
227
+
228
+ // Settings are this machine's own rules. The server can read them (to offer
229
+ // the right folders); from the dashboard only the folders can be changed, and
230
+ // only within the rules below (unless folders_from_dashboard is false).
231
+ // folders where sessions may be opened (and anything inside)
232
+ // folders_from_dashboard whether the dashboard may add and remove folders (same as allow_input by default)
233
+ // allow_home whether the whole home folder may be one of them (default
234
+ // false; set by starting with --allow-home). Sessions opened
235
+ // there never get their permission prompts answered remotely
236
+ // allow_resume whether a session may continue its own last conversation (same as allow_input by default)
237
+ // max_sessions at most this many at once
238
+ // allow_input whether the dashboard may type in the terminals
239
+ // permission_relay whether a session's coordinator may answer its permission
240
+ // prompts from another session (default: same as allow_input)
241
+ // allow_clear whether a worker's coordinator may have its context cleared
242
+ // (/clear) before a new task (default: same as allow_input)
243
+ // coordinators if set, the only coordinator names a worker may be given
244
+ // (and a coordinator here may be linked with)
245
+ // permissions_from_dashboard how far a permission profile from the
246
+ // dashboard goes in the sessions it opens: "allow" (its rules
247
+ // that allow, ask and forbid), "restrict" (only those that
248
+ // ask or forbid: what it allows is left out) or "off" (none:
249
+ // a session that follows one isn't opened). Default: "allow"
250
+ // if allow_input, else "restrict". Whatever it says, nothing
251
+ // from the dashboard allows sudo, any command at all or an
252
+ // interpreter with any arguments, or writing outside the
253
+ // session's folder.
254
+ // claude_command the Claude Code executable
255
+ // codex_command the Codex CLI executable (default "codex")
256
+ // grok_command the Grok CLI executable (default "grok")
257
+ // Each warning about settings.json once (until the file changes), not on
258
+ // every message.
259
+ const settingsWarned = new Set()
260
+ function warnSettings(msg) {
261
+ let tag = ''
262
+ try { tag = String(statSync(SETTINGS_FILE).mtimeMs) } catch {}
263
+ if (settingsWarned.has(tag + msg)) return
264
+ if (settingsWarned.size > 100) settingsWarned.clear()
265
+ settingsWarned.add(tag + msg)
266
+ log(msg)
267
+ }
268
+
269
+ // Refuses every coordinator: in a list, no name can be this. (An empty list means no pin.)
270
+ const NO_COORDINATOR = ['(invalid "coordinators" setting)']
271
+ function loadSettings() {
272
+ let raw = {}
273
+ try { raw = JSON.parse(readFileSync(SETTINGS_FILE, 'utf8')) } catch (err) {
274
+ // Settings that exist but can't be read: the strictest ones, never the defaults.
275
+ if (err.code !== 'ENOENT') {
276
+ if (!loadSettings.warned) { loadSettings.warned = true; log(`⚠️ cannot read ${SETTINGS_FILE} (${err.message}): no folders, no typing, no permission relay until it is fixed`) }
277
+ return { ...DEFAULT_SETTINGS, folders: [], allow_input: false, permission_relay: false, allow_resume: false, allow_clear: false, allow_home: false, folders_from_dashboard: false, permissions_from_dashboard: 'off', coordinators: NO_COORDINATOR }
278
+ }
279
+ }
280
+ loadSettings.warned = false
281
+ const strict = { ...DEFAULT_SETTINGS, folders: [], allow_input: false, permission_relay: false, allow_resume: false, allow_clear: false, allow_home: false, folders_from_dashboard: false, permissions_from_dashboard: 'off', coordinators: NO_COORDINATOR }
282
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
283
+ warnSettings(`⚠️ ${SETTINGS_FILE} must hold a JSON object: no folders, no typing, no permission relay until it is fixed`)
284
+ return strict
285
+ }
286
+ const s = { ...DEFAULT_SETTINGS, ...raw }
287
+ s.allow_home = raw.allow_home === true
288
+ s.folders = (Array.isArray(s.folders) ? s.folders : []).slice(0, MAX_FOLDERS)
289
+ .filter(f => typeof f === 'string' && isAbsolute(f) && !forbiddenFolder(realOr(f), { allowHome: s.allow_home }))
290
+ if (raw.max_sessions === undefined) s.max_sessions = DEFAULT_SETTINGS.max_sessions
291
+ else if (Number.isInteger(s.max_sessions) && s.max_sessions >= 0) s.max_sessions = Math.min(s.max_sessions, 64)
292
+ else { warnSettings(`⚠️ max_sessions in ${SETTINGS_FILE} must be a whole number: no sessions until it is fixed`); s.max_sessions = 0 }
293
+ // A value of the wrong type is read as the strict choice, never as "on".
294
+ const bool = (k, dflt) => {
295
+ if (s[k] === undefined) return dflt
296
+ if (typeof s[k] === 'boolean') return s[k]
297
+ warnSettings(`⚠️ ${k} in ${SETTINGS_FILE} must be true or false: taken as false`)
298
+ return false
299
+ }
300
+ s.allow_input = bool('allow_input', true)
301
+ s.permission_relay = bool('permission_relay', s.allow_input)
302
+ s.allow_clear = bool('allow_clear', s.allow_input)
303
+ s.allow_resume = bool('allow_resume', s.allow_input)
304
+ s.folders_from_dashboard = bool('folders_from_dashboard', s.allow_input)
305
+ // (A value it doesn't know is read as the strict one that still opens sessions.)
306
+ if (s.permissions_from_dashboard === undefined) s.permissions_from_dashboard = s.allow_input ? 'allow' : 'restrict'
307
+ else if (!['allow', 'restrict', 'off'].includes(s.permissions_from_dashboard)) {
308
+ warnSettings(`⚠️ permissions_from_dashboard in ${SETTINGS_FILE} must be "allow", "restrict" or "off": taken as "restrict"`)
309
+ s.permissions_from_dashboard = 'restrict'
310
+ }
311
+ // A coordinators pin that can't be read refuses every coordinator (it
312
+ // never turns into "any").
313
+ if (s.coordinators === undefined || (Array.isArray(s.coordinators) && s.coordinators.length === 0)) s.coordinators = []
314
+ else if (Array.isArray(s.coordinators) && s.coordinators.every(c => typeof c === 'string' && NAME_RE.test(c))) s.coordinators = [...s.coordinators]
315
+ else {
316
+ warnSettings(`⚠️ coordinators in ${SETTINGS_FILE} must be a list of session names: no coordinator is accepted until it is fixed`)
317
+ s.coordinators = NO_COORDINATOR
318
+ }
319
+ s.claude_command = typeof s.claude_command === 'string' && s.claude_command ? s.claude_command : 'claude'
320
+ s.codex_command = typeof s.codex_command === 'string' && s.codex_command ? s.codex_command : 'codex'
321
+ s.grok_command = typeof s.grok_command === 'string' && s.grok_command ? s.grok_command : 'grok'
322
+ return s
323
+ }
324
+
325
+ // Version managers' shims (volta, asdf, nodenv) pick the program from the
326
+ // folder they run in — a session's folder is a repository, which could name
327
+ // its own. Such a shim is replaced by the program it picks from the home
328
+ // folder (`volta which`, `asdf which`, `nodenv which`), checked like any other.
329
+ const dispatcherCache = new Map() // path -> { at, real }
330
+ function dispatcherOf(p) {
331
+ const real = realOr(p)
332
+ if (/(^|\/)volta-shim$/.test(real)) return { tool: 'volta', args: ['which'] }
333
+ // (Only its first 64 KB: node or a native claude are 100+ MB; an asdf
334
+ // shim lists every installed version before its exec line.)
335
+ let head = ''
336
+ try {
337
+ const fd = openSync(real, 'r')
338
+ try { const buf = Buffer.alloc(65536); head = buf.toString('latin1', 0, readSync(fd, buf, 0, 65536, 0)) } finally { closeSync(fd) }
339
+ } catch {}
340
+ if (/^#!/.test(head)) {
341
+ if (/\basdf\b[^\n]*\bexec\b/.test(head) || /^# asdf-plugin:/m.test(head)) return { tool: 'asdf', args: ['which'] }
342
+ if (/\bnodenv\b[^\n]*\bexec\b/.test(head)) return { tool: 'nodenv', args: ['which'] }
343
+ }
344
+ return null
345
+ }
346
+ function throughDispatcher(p, name) {
347
+ const d = dispatcherOf(p)
348
+ if (!d) return p
349
+ const cached = dispatcherCache.get(p)
350
+ if (cached && Date.now() - cached.at < 60_000) return cached.real
351
+ let found = ''
352
+ try {
353
+ // (volta sits next to volta-shim itself: ~/.volta/bin holds only the
354
+ // shims when volta comes from Homebrew, a distribution or cargo.)
355
+ // (The version manager itself passes the same checks as any program run here.)
356
+ const tool = d.tool === 'volta' ? join(dirname(realOr(p)), 'volta') : findTrusted(d.tool)
357
+ if (!tool || untrustedExecutable(tool)) throw new Error(`no trusted ${d.tool}`)
358
+ found = execFileSync(tool, [...d.args, name], { cwd: HOME, encoding: 'utf8', timeout: 10_000, env: { ...process.env, PATH: computeTrustedFolders() } }).trim().split('\n')[0]
359
+ } catch {}
360
+ if (!found || !isAbsolute(found)) throw new Error(`${p} is a ${d.tool} shim (it picks the program from the session's folder) and the real ${name} couldn't be found: set claude_command in ${SETTINGS_FILE} to the real executable`)
361
+ const why = untrustedExecutable(found) ?? (dispatcherOf(found) ? 'it is another shim' : null)
362
+ if (why) throw new Error(`refusing ${found} (from the ${d.tool} shim ${p}): ${why}`)
363
+ if (dispatcherCache.size > 50) dispatcherCache.clear()
364
+ dispatcherCache.set(p, { at: Date.now(), real: found })
365
+ return found
366
+ }
367
+
368
+ // A program this machine runs: it and its folder must belong to you or root,
369
+ // nobody else may be able to change them, and it can't come from a folder
370
+ // where sessions are opened (a repository could ship its own "claude").
371
+ // A group only this user is in: its own group, with no other member listed
372
+ // in /etc/group and no other account having it as its main group. On macOS
373
+ // (where everyone's group is "staff") never. If it can't be told: not private.
374
+ // A group is private when it is named after this user (the "user private
375
+ // group" convention) and no one else is in it: every /etc/group line with that
376
+ // gid, and no other account in /etc/passwd with it as its main group. For an
377
+ // account from a directory service (LDAP, sssd) that isn't in /etc/passwd,
378
+ // only its own group whose gid is its uid, as getent reports it with no
379
+ // other member. On macOS (where everyone's group is "staff") never.
380
+ const privateGroupCache = new Map() // gid -> { ok, at }
381
+ function privateGroup(gid) {
382
+ if (typeof process.getgid !== 'function' || gid !== process.getgid() || platform() === 'darwin') return false
383
+ const cached = privateGroupCache.get(gid)
384
+ if (cached && Date.now() - cached.at < 60_000) return cached.ok
385
+ let ok = false
386
+ try {
387
+ const me = userInfo().username
388
+ const lines = text => text.split('\n').map(l => l.split(':')).filter(f => f.length > 3 && Number(f[2]) === gid)
389
+ const alone = groups => groups.length > 0 && groups.every(f => f[0] === me && f[3].split(',').map(x => x.trim()).filter(Boolean).every(m => m === me))
390
+ const local = lines(readFileSync('/etc/group', 'utf8'))
391
+ const passwd = readFileSync('/etc/passwd', 'utf8').split('\n').map(l => l.split(':'))
392
+ const others = passwd.filter(f => f.length > 3 && Number(f[3]) === gid && f[0] !== me)
393
+ if (passwd.some(f => f[0] === me)) ok = alone(local) && others.length === 0
394
+ else if (gid === process.getuid() && others.length === 0 && local.every(f => f[0] === me)) {
395
+ const getent = ['/usr/bin/getent', '/bin/getent', '/run/current-system/sw/bin/getent'].find(f => existsSync(f))
396
+ if (getent) ok = alone(lines(execFileSync(getent, ['group', String(gid)], { encoding: 'utf8', timeout: 5000 })))
397
+ }
398
+ } catch {}
399
+ privateGroupCache.set(gid, { ok, at: Date.now() })
400
+ return ok
401
+ }
402
+
403
+ // Whether an ACL lets someone other than this user write there. On Linux an
404
+ // ACL shows in the mode bits as group-write (its mask), so it is looked for
405
+ // only then; on macOS it never shows, so it is always looked for. Read with
406
+ // the system's ls; if that can't be done, assumed to.
407
+ const aclCache = new Map() // path -> { key, grants }
408
+ function aclGrantsWrite(path, st, { always = false } = {}) {
409
+ const mac = platform() === 'darwin'
410
+ if (!mac && !always && !(st.mode & 0o020)) return false
411
+ if (platform() !== 'linux' && !mac) return false
412
+ const key = `${st.ino}:${st.ctimeMs}:${always}`
413
+ const c = aclCache.get(path)
414
+ if (c && c.key === key) return c.grants
415
+ let grants = true
416
+ try {
417
+ // (Where the system's ls is: NixOS and Guix keep it under /run/current-system.)
418
+ const ls = ['/bin/ls', '/usr/bin/ls', '/run/current-system/sw/bin/ls', '/run/current-system/profile/bin/ls'].find(f => existsSync(f))
419
+ const out = execFileSync(ls, mac ? ['-lde', '--', path] : ['-ld', '--', path], { encoding: 'utf8', timeout: 5000 })
420
+ if (!mac) grants = out[10] === '+'
421
+ else {
422
+ const me = userInfo().username
423
+ grants = out.split('\n').slice(1).some(l => {
424
+ const m = /^\s*\d+:\s+(.+?)\s+(?:inherited\s+)?allow\s+(\S+)/.exec(l)
425
+ return !!m && m[1] !== `user:${me}` && /(^|,)(write|append|add_file|add_subdirectory|delete_child|delete|writeattr|writeextattr|writesecurity|chown)(,|$)/.test(m[2])
426
+ })
427
+ }
428
+ } catch {}
429
+ if (aclCache.size > 1000) aclCache.clear()
430
+ aclCache.set(path, { key, grants })
431
+ return grants
432
+ }
433
+
434
+ // Programs (and PATH folders) are used by the path as written — version
435
+ // managers' shims and Homebrew's opt/ links keep working — but only when
436
+ // nobody else can change where that path leads: walking it from "/", every
437
+ // folder on the way and every symlink belongs to this user or root and
438
+ // nobody else can change it (writable only by this user's private group,
439
+ // root's, or macOS's "admin" — Homebrew, whose members can use sudo
440
+ // anyway); sticky folders on the way are fine (what is in them is checked),
441
+ // but not the folder that holds the program, nor the PATH folder itself.
442
+ const okGroup = gid => privateGroup(gid) || gid === 0 || (platform() === 'darwin' && gid === 80)
443
+ function entryProblem(path, st, strict) {
444
+ const me = typeof process.getuid === 'function' ? process.getuid() : null
445
+ if (me !== null && st.uid !== me && st.uid !== 0) return 'it belongs to another user'
446
+ if ((st.mode & 0o002) && (strict || !(st.mode & 0o1000))) return 'anyone can change it'
447
+ if ((st.mode & 0o020) && (strict || !(st.mode & 0o1000)) && !okGroup(st.gid)) return 'a group can change it'
448
+ if (aclGrantsWrite(path, st)) return 'an ACL lets others change it'
449
+ return null
450
+ }
451
+ function trustedChain(p, { dir = false } = {}) {
452
+ const me = typeof process.getuid === 'function' ? process.getuid() : null
453
+ const check = (path, strict) => {
454
+ let st
455
+ try { st = statSync(path) } catch { return `${path} cannot be checked` }
456
+ const why = entryProblem(path, st, strict)
457
+ return why ? `${path}: ${why}` : null
458
+ }
459
+ let why = check('/', false)
460
+ if (why) return { why }
461
+ const parts = String(p).split('/').filter(x => x && x !== '.')
462
+ let cur = '/'
463
+ let hops = 0
464
+ while (parts.length) {
465
+ const name = parts.shift()
466
+ if (name === '..') { cur = dirname(cur); continue }
467
+ const next = cur === '/' ? `/${name}` : `${cur}/${name}`
468
+ let l
469
+ try { l = lstatSync(next) } catch { return { why: `${next} cannot be checked` } }
470
+ if (l.isSymbolicLink()) {
471
+ if (++hops > 40) return { why: `${p}: too many symlinks` }
472
+ if (me !== null && l.uid !== me && l.uid !== 0) return { why: `${next}: a symlink of another user` }
473
+ let target
474
+ try { target = readlinkSync(next) } catch { return { why: `${next} cannot be read` } }
475
+ parts.unshift(...target.split('/').filter(x => x && x !== '.'))
476
+ if (target.startsWith('/')) cur = '/'
477
+ continue
478
+ }
479
+ why = check(next, false)
480
+ if (why) return { why }
481
+ cur = next
482
+ }
483
+ // Nobody else may add names where it ends: the PATH folder itself, or
484
+ // the program and the folder holding it.
485
+ why = check(cur, true) || (dir ? null : check(dirname(cur), true))
486
+ return why ? { why } : { real: cur }
487
+ }
488
+ const untrustedFolder = dir => trustedChain(dir, { dir: true }).why ?? null
489
+
490
+ // The folders where sessions are opened, for "never a program or PATH
491
+ // folder from there" (a repository could bring its own). Not the home
492
+ // folder itself (allowed with --allow-home): what is installed in it
493
+ // (~/.local/bin, nvm's node, Claude Code) is the user's own. Project
494
+ // folders inside it, allowed on their own, still count.
495
+ function sessionRoots() {
496
+ let folders = []
497
+ try { folders = JSON.parse(readFileSync(SETTINGS_FILE, 'utf8')).folders ?? [] } catch {}
498
+ return (Array.isArray(folders) ? folders : []).filter(f => typeof f === 'string' && isAbsolute(f)).map(realOr).filter(r => !isHome(r))
499
+ }
500
+
501
+ // A program this machine runs: the path given (as written) is what runs,
502
+ // and nothing on the way to it can be changed by anyone else.
503
+ function untrustedExecutable(p) {
504
+ const { real, why } = trustedChain(p)
505
+ if (why) return why
506
+ try { if (!statSync(real).isFile()) return 'it is not a file' } catch { return 'the program cannot be checked' }
507
+ if (sessionRoots().some(r => within(real, r))) return 'it is inside a folder where sessions are opened'
508
+ return null
509
+ }
510
+ // The PATH given to Claude Code and the sessions: only absolute folders that
511
+ // pass the same checks (Claude Code's "#!/usr/bin/env node" looks up node
512
+ // there, before any trust dialog), and none where sessions are opened.
513
+ let trustedPathCache = null
514
+ function trustedPath() {
515
+ if (trustedPathCache && Date.now() - trustedPathCache.at < 10_000) return trustedPathCache.path
516
+ const path = computeTrustedPath()
517
+ trustedPathCache = { path, at: Date.now() }
518
+ return path
519
+ }
520
+ // A program by name, from the trusted PATH folders, that passes the same
521
+ // checks as claude itself (not only its folder).
522
+ function findTrusted(name) {
523
+ for (const dir of computeTrustedFolders().split(':')) {
524
+ const p = join(dir, name)
525
+ try { accessSync(p, FS.X_OK) } catch { continue }
526
+ if (!untrustedExecutable(p)) return p
527
+ }
528
+ return null
529
+ }
530
+ const shimFailures = new Map() // shim path -> when resolving it last failed
531
+ function computeTrustedPath() {
532
+ const dirs = computeTrustedFolders().split(':')
533
+ // Claude Code installed with npm starts with "#!/usr/bin/env node": if the
534
+ // first node on the PATH is a version manager's shim, the folder of the
535
+ // node it picks from the home folder goes first (not the repository's).
536
+ // If that can't be found, the shim's folder is left out: a shim that picks
537
+ // by folder never comes first.
538
+ // (If a real node comes later on the PATH, the shim's folder only moves
539
+ // after it, keeping its other tools; the failure is remembered a minute.)
540
+ const moved = []
541
+ for (let k = 0; k < dirs.length; k++) {
542
+ const p = join(dirs[k], 'node')
543
+ try { accessSync(p, FS.X_OK) } catch { continue }
544
+ if (!dispatcherOf(p)) {
545
+ // The node Claude Code would start with passes the same checks as any
546
+ // program run here (a link to someone else's file doesn't).
547
+ if (!untrustedExecutable(p)) break
548
+ moved.push(...dirs.splice(k, 1))
549
+ k--
550
+ continue
551
+ }
552
+ const failedAt = shimFailures.get(p) ?? 0
553
+ if (Date.now() - failedAt > 60_000) {
554
+ try { return [dirname(throughDispatcher(p, 'node')), ...dirs, ...moved].join(':') } catch {
555
+ if (!shimFailures.has(p)) log(`${p} is a version manager's shim and the node it picks from your home folder couldn't be found: it isn't used first for sessions`)
556
+ shimFailures.set(p, Date.now())
557
+ }
558
+ }
559
+ moved.push(...dirs.splice(k, 1))
560
+ k--
561
+ }
562
+ // A real node later on: the shim folders go after everything else.
563
+ // None at all: they are left out (a shim that picks by folder never decides).
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'
566
+ }
567
+ function computeTrustedFolders() {
568
+ const roots = sessionRoots()
569
+ // (As written: nothing on the way to each one can be changed by others.)
570
+ const seen = new Set()
571
+ return String(process.env.PATH ?? '').split(':').filter(d => {
572
+ if (!isAbsolute(d) || seen.has(d)) return false
573
+ seen.add(d)
574
+ try { if (!statSync(d).isDirectory()) return false } catch { return false }
575
+ const real = realOr(d)
576
+ return !untrustedFolder(d) && !roots.some(r => within(real, r))
577
+ }).join(':') || '/usr/bin:/bin'
578
+ }
579
+ // --- tmux ---------------------------------------------------------------------------
580
+
581
+ // UTF-8 always: tmux runs with -u (without it "é" becomes "_" and folder
582
+ // names would no longer match).
583
+ const tmuxEnv = () => {
584
+ const e = { ...process.env, PATH: trustedPath() }
585
+ delete e.TMUX; delete e.TMUX_PANE
586
+ // (This program's own note to itself: no business of a session, nor of what it runs.)
587
+ delete e.PISHA_COMPANY
588
+ // (tmux -u already handles UTF-8; a locale is only added when there is none at all, on Linux.)
589
+ if (!e.LC_ALL && !e.LC_CTYPE && !e.LANG && platform() !== 'darwin') e.LC_CTYPE = 'C.UTF-8'
590
+ return e
591
+ }
592
+ // tmux by absolute path (only absolute PATH entries), like claude.
593
+ let TMUX_BIN = null
594
+ function tmuxBin() {
595
+ // Checked again on every use: a tmux replaced after startup isn't run.
596
+ if (TMUX_BIN && !untrustedExecutable(TMUX_BIN)) return TMUX_BIN
597
+ TMUX_BIN = null
598
+ for (const dir of String(process.env.PATH ?? '').split(':')) {
599
+ if (!isAbsolute(dir)) continue
600
+ const p = join(dir, 'tmux')
601
+ try { accessSync(p, FS.X_OK) } catch { continue }
602
+ if (!untrustedExecutable(p)) return (TMUX_BIN = p)
603
+ }
604
+ return 'tmux-not-found'
605
+ }
606
+ // (30 s at most: a hung tmux can't block opening sessions for good.)
607
+ const tmux = (args, opts = {}) => run(tmuxBin(), ['-u', '-L', TMUX_SOCKET, '-f', '/dev/null', ...args], { env: tmuxEnv(), maxBuffer: 16 * 1024 * 1024, cwd: HOME, timeout: 30_000, ...opts })
608
+
609
+ async function tmuxVersion() {
610
+ try {
611
+ const { stdout } = await run(tmuxBin(), ['-V'])
612
+ const m = /(\d+)\.(\d+)/.exec(stdout)
613
+ return m ? { text: stdout.trim(), major: Number(m[1]), minor: Number(m[2]) } : { text: stdout.trim(), major: 0, minor: 0 }
614
+ } catch { return null }
615
+ }
616
+
617
+ // Sessions this program opened: tmux sessions named sq-<name> carrying their
618
+ // spec in the @pisha option, so they are found again after a restart.
619
+ async function listTerminals() {
620
+ let out
621
+ try {
622
+ // tmux prints control characters (tabs too) as "_": separate with spaces,
623
+ // which neither the name nor the date have, and keep the spec last.
624
+ ({ stdout: out } = await tmux(['list-sessions', '-F', '#{session_name} #{session_created} #{@pisha}']))
625
+ } catch { return [] } // no tmux server: no sessions
626
+ const list = []
627
+ for (const line of out.split('\n')) {
628
+ const m = /^(\S+) (\d+) ?(.*)$/.exec(line)
629
+ if (!m) continue
630
+ const [, tname, created, meta] = m
631
+ if (!tname?.startsWith(PREFIX) || !NAME_RE.test(tname.slice(PREFIX.length))) continue
632
+ let spec = {}
633
+ try { spec = JSON.parse(meta || '{}') } catch {}
634
+ if (spec.owner ? spec.owner !== OWNER_TAG : OWN_SETUP) continue
635
+ list.push({
636
+ id: tname.slice(PREFIX.length),
637
+ name: tname.slice(PREFIX.length),
638
+ role: spec.role ?? null,
639
+ coordinator: spec.coordinator ?? null,
640
+ folder: spec.folder ?? null,
641
+ compact_window: spec.compact_window ?? null,
642
+ persona: spec.persona ?? null,
643
+ agent: AGENT_IDS.includes(spec.agent) ? spec.agent : 'claude',
644
+ profile: typeof spec.profile === 'string' ? spec.profile : null,
645
+ created_at: Number(created) * 1000,
646
+ })
647
+ }
648
+ return list
649
+ }
650
+
651
+ // --- validation of what the server asks for -------------------------------------------
652
+
653
+ function insideAllowed(real, folders) {
654
+ for (const f of folders) {
655
+ let root
656
+ try { root = realpathSync.native(f) } catch { continue }
657
+ if (insideByIdentity(real, root)) return true
658
+ }
659
+ return false
660
+ }
661
+
662
+ // The only thing a server can ask for. Anything unexpected is refused.
663
+ export function validateSpec(spec, settings, current) {
664
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) throw new Error('invalid request')
665
+ const allowed = new Set(['name', 'role', 'coordinator', 'folder', 'compact_window', 'resume', 'identity', 'persona', 'links', 'agent', 'permissions'])
666
+ for (const k of Object.keys(spec)) if (!allowed.has(k)) throw new Error(`unknown field "${plain(k).slice(0, 40)}"`)
667
+ const name = String(spec.name ?? '')
668
+ if (!NAME_RE.test(name)) throw new Error('name must match [A-Za-z0-9_-]{1,32}')
669
+ const role = spec.role
670
+ // (solo: a plain Claude Code session, outside any squad.)
671
+ if (role !== 'coordinator' && role !== 'worker' && role !== 'solo') throw new Error('role must be coordinator, worker or solo')
672
+ let coordinator = null
673
+ if (role === 'worker') {
674
+ coordinator = spec.coordinator == null || spec.coordinator === '' ? 'coord' : String(spec.coordinator)
675
+ if (!NAME_RE.test(coordinator)) throw new Error('invalid coordinator name')
676
+ if (coordinator === name) throw new Error('a worker cannot be its own coordinator')
677
+ // The coordinator gives the worker its instructions: this machine may pin who that can be.
678
+ if (settings.coordinators.length && !settings.coordinators.includes(coordinator)) {
679
+ throw new Error(`this machine only accepts these coordinators: ${settings.coordinators.join(', ')}`)
680
+ }
681
+ } else if (spec.coordinator != null && spec.coordinator !== '') {
682
+ throw new Error(`a ${role === 'solo' ? 'standalone session' : 'coordinator'} has no coordinator`)
683
+ }
684
+ let compact = null
685
+ if (spec.compact_window != null && spec.compact_window !== '') {
686
+ compact = Number(spec.compact_window)
687
+ if (!Number.isInteger(compact) || compact < COMPACT_MIN || compact > COMPACT_MAX) {
688
+ throw new Error(`compact_window must be a whole number of tokens between ${COMPACT_MIN} and ${COMPACT_MAX}`)
689
+ }
690
+ }
691
+ if (spec.resume != null && typeof spec.resume !== 'boolean') throw new Error('resume must be true or false')
692
+ // Only if this machine allows continuing a conversation.
693
+ if (spec.resume === true && !settings.allow_resume) throw new Error('this machine does not allow continuing earlier conversations ("allow_resume": false in its settings.json)')
694
+ // The session's identity secret, when the server reserved the name for this machine.
695
+ if (spec.identity != null && !(typeof spec.identity === 'string' && /^sq_[A-Za-z0-9_-]{20,64}$/.test(spec.identity))) throw new Error('invalid identity')
696
+ // Only the id of a skill or agent listed for that folder: the machine looks
697
+ // it up again when the session opens (see personas below).
698
+ if (spec.persona != null && spec.persona !== '' && !(typeof spec.persona === 'string' && PERSONA_RE.test(spec.persona))) throw new Error('invalid persona')
699
+ // The agent it runs: Claude Code unless it says another this machine has.
700
+ const agent = spec.agent == null || spec.agent === '' ? 'claude' : spec.agent
701
+ if (!AGENT_IDS.includes(agent)) throw new Error(`agent must be one of ${AGENT_IDS.join(', ')}`)
702
+ // A coordinator's links: coordinators of other squads it may talk with.
703
+ const links = spec.links == null ? [] : checkLinks(spec.links, name, role, settings)
704
+ // What it may do without asking, from its permission profile (Claude Code only).
705
+ const permissions = spec.permissions == null ? null : checkPermissions(spec.permissions, settings, agent)
706
+ const real = checkFolder(spec.folder, settings)
707
+ if (current.some(t => t.name === name)) throw new Error(`a session named "${name}" is already open on this machine`)
708
+ if (current.length >= settings.max_sessions) throw new Error(`this machine allows at most ${settings.max_sessions} sessions`)
709
+ // Which folder exactly (device and inode), to check after the start that
710
+ // the session is in this one and not in another put at the same path.
711
+ const id = statSync(real)
712
+ return { name, role, coordinator, folder: real, folderId: `${id.dev}:${id.ino}`, compact_window: compact, resume: spec.resume === true, identity: spec.identity ?? null, persona: spec.persona || null, links, home: isHome(real), agent, permissions }
713
+ }
714
+
715
+ // A permission profile from the dashboard: Claude Code's own rules, checked
716
+ // one by one, and only as far as this machine takes them
717
+ // (permissions_from_dashboard). Some are never taken from the dashboard,
718
+ // whatever it says: an allow for sudo, for any command at all or an
719
+ // interpreter with any arguments, or for files outside the session's folder.
720
+ // A rule Claude Code would read differently from how it looks (a path
721
+ // anchored to where its settings file is, an MCP rule with arguments) is
722
+ // refused too. Returns what the session gets, or null for nothing.
723
+ const RULE_RE = /^(?:(?:Bash|PowerShell|Read|Edit|Write|NotebookEdit|WebFetch|WebSearch|Glob|Grep|Agent|Skill)(?:\((?:[^()\x00-\x1f\x7f]|\([^()\x00-\x1f\x7f]*\)){1,300}\))?|mcp__[A-Za-z0-9_-]+(?:__(?:[A-Za-z0-9_-]+|\*))?)$/
724
+ const PERMISSION_RULES_MAX = 300
725
+ const NEVER_ALLOWED = [
726
+ [/^(?:Bash|PowerShell)$|^(?:Bash|PowerShell)\(\s*[*:]/, 'any command at all'],
727
+ [/^(?:Bash|PowerShell)\(\s*(?:sudo|su|doas|pkexec|run0)\b/, 'sudo'],
728
+ [/^(?:Bash|PowerShell)\(\s*(?:bash|sh|zsh|dash|fish|ksh|python[\d.]*|node|nodejs|ruby|perl|php|deno|bun|lua|eval|exec|env|xargs|ssh|nohup|npx|pwsh|powershell)\s*(?::\*|\*)\s*\)$/, 'an interpreter with any arguments'],
729
+ [/^(?:Edit|Write|NotebookEdit|Read)\(\s*(?:\/\/|~|\$)|^(?:Edit|Write|NotebookEdit|Read)\((?:[^)]*\/)?\.\.(?:\/|\))/, 'files outside its folder'],
730
+ ]
731
+ export function checkPermissions(p, settings, agent) {
732
+ if (!p || typeof p !== 'object' || Array.isArray(p)) throw new Error('invalid permissions')
733
+ for (const k of Object.keys(p)) if (!['profile', 'allow', 'ask', 'deny', 'notes'].includes(k)) throw new Error(`unknown field "permissions.${plain(k).slice(0, 40)}"`)
734
+ const profile = typeof p.profile === 'string' ? p.profile.replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, 40) : ''
735
+ if (!profile) throw new Error('the permission profile has no name')
736
+ if (agent !== 'claude') throw new Error(`a permission profile ("${plain(profile)}") is only for Claude Code sessions`)
737
+ if (settings.permissions_from_dashboard === 'off') throw new Error(`this machine takes no permission profiles from the dashboard ("permissions_from_dashboard": "off" in its settings.json), and this session follows "${plain(profile)}"`)
738
+ const list = (what) => {
739
+ const v = p[what] ?? []
740
+ if (!Array.isArray(v) || v.length > PERMISSION_RULES_MAX) throw new Error(`permissions.${what} must be a list of at most ${PERMISSION_RULES_MAX} rules`)
741
+ return v.map(r => {
742
+ if (typeof r !== 'string' || !RULE_RE.test(r)) throw new Error(`"${plain(String(r)).slice(0, 80)}" is not a permission rule`)
743
+ if (/^(?:Edit|Write|NotebookEdit|Read)\(\s*\/(?!\/)/.test(r)) throw new Error(`${plain(r).slice(0, 80)}: write ./path for its folder or //path for an absolute one (Claude Code reads /path from where its settings file is)`)
744
+ return r
745
+ })
746
+ }
747
+ const deny = list('deny'), ask = list('ask')
748
+ let allow = list('allow')
749
+ for (const r of allow) for (const [re, what] of NEVER_ALLOWED) if (re.test(r)) throw new Error(`the permission profile "${plain(profile)}" allows ${what} (${plain(r).slice(0, 80)}): this machine never takes that from the dashboard`)
750
+ // (Only what asks or forbids: less than the profile says it allows, never less than it forbids.)
751
+ if (settings.permissions_from_dashboard === 'restrict') allow = []
752
+ const notes = typeof p.notes === 'string' ? p.notes.replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ' ').trim().slice(0, 2000) : ''
753
+ return { profile, allow, ask, deny, notes, restricted: settings.permissions_from_dashboard === 'restrict' && (p.allow ?? []).length > 0 }
754
+ }
755
+
756
+ // The coordinators of other squads a coordinator is linked with (each one
757
+ // can give it work, as its user could): names only, and only the ones this
758
+ // machine accepts as coordinators when it pins them ("coordinators").
759
+ const LINKS_MAX = 20
760
+ export function checkLinks(links, name, role, settings) {
761
+ if (!Array.isArray(links) || links.length > LINKS_MAX) throw new Error(`links must be a list of at most ${LINKS_MAX} session names`)
762
+ if (links.length && role !== 'coordinator') throw new Error('only a coordinator is linked with other squads')
763
+ const out = []
764
+ for (const l of links) {
765
+ if (typeof l !== 'string' || !NAME_RE.test(l)) throw new Error('invalid name in links')
766
+ if (l === name) throw new Error('a coordinator is not linked with itself')
767
+ if (settings.coordinators.length && !settings.coordinators.includes(l)) {
768
+ throw new Error(`this machine only accepts these coordinators: ${settings.coordinators.join(', ')} (not "${l}")`)
769
+ }
770
+ if (!out.includes(l)) out.push(l)
771
+ }
772
+ return out
773
+ }
774
+
775
+ // A folder the server names (to open a session there, or to list its
776
+ // personas): inside the allowed folders, and none of the forbidden ones.
777
+ // Returns where it really is.
778
+ function checkFolder(folder, settings) {
779
+ if (typeof folder !== 'string' || !isAbsolute(folder) || folder.length > 4096) throw new Error('folder must be an absolute path')
780
+ // Nothing outside the allowed folders is even looked at (no "exists / not
781
+ // a folder" answers about the rest of the machine).
782
+ const asWritten = resolve(folder)
783
+ if (!settings.folders.some(f => within(asWritten, resolve(f)) || within(asWritten, realOr(f)))) {
784
+ throw new Error(`that folder is not inside the folders this machine allows (${settings.folders.join(', ') || 'none configured'})`)
785
+ }
786
+ // tmux expands #{…} and #(…) in some arguments and splits commands on ";":
787
+ // such paths are refused outright.
788
+ if (/[#;\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/.test(folder)) throw new Error('folder contains characters that are not allowed (#, ; or control characters)')
789
+ // Where it really leads is checked against the allowed folders before
790
+ // anything else is said about it: a symlink inside them (to "/") can't be
791
+ // used to ask what exists elsewhere. One answer for missing, not a folder,
792
+ // or outside.
793
+ const notOpenable = () => new Error(`folder ${folder} is not a folder inside the folders this machine allows (${settings.folders.join(', ') || 'none configured'})`)
794
+ let real
795
+ try { real = realpathSync.native(resolve(folder)) } catch { throw notOpenable() }
796
+ if (!insideAllowed(real, settings.folders)) throw notOpenable()
797
+ try { if (!statSync(real).isDirectory()) throw notOpenable() } catch { throw notOpenable() }
798
+ if (/[#;\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/.test(real)) throw new Error('folder contains characters that are not allowed (#, ; or control characters)')
799
+ const why = forbiddenFolder(real, { allowHome: settings.allow_home })
800
+ if (why) throw new Error(`sessions cannot be opened in ${real}: it is ${why}`)
801
+ if (folderOfAnotherCompany(real)) throw new Error(`sessions cannot be opened in ${real}: it belongs to another company on this machine`)
802
+ return real
803
+ }
804
+
805
+ // The agents a session can run (see Claude Code, and Codex CLI and Grok CLI, below).
806
+ const AGENT_IDS = ['claude', 'codex', 'grok']
807
+
808
+ // A persona as the server asks for it (see Claude Code, below).
809
+ const PERSONA_RE = /^(skill|agent):(project|user):[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
810
+
811
+ // "0.0.1" < "0.0.2" (numeric parts; anything unreadable is not "older").
812
+ function olderVersion(a, b) {
813
+ const p = v => String(v).split('.').map(x => Number.parseInt(x, 10))
814
+ const [x, y] = [p(a), p(b)]
815
+ if (x.some(Number.isNaN) || y.some(Number.isNaN)) return false
816
+ for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0)
817
+ return false
818
+ }
819
+
820
+ // --- Claude Code --------------------------------------------------------------------
821
+ //
822
+ // All this program knows about the agent its sessions run. The rest of the file
823
+ // uses it only through the claudeCode object at the end of this section (a test
824
+ // checks that): another agent would be a second object like it.
825
+
826
+ // The Claude Code executable as an absolute path. A bare name is looked up
827
+ // only in absolute PATH entries, so a "." in PATH can never make a session
828
+ // run a "claude" file from the project folder.
829
+ function claudeBinary(cmd = loadSettings().claude_command) {
830
+ const ok = p => { try { accessSync(p, FS.X_OK); return statSync(p).isFile() } catch { return false } }
831
+ if (cmd.includes('/')) {
832
+ if (!isAbsolute(cmd) || !ok(cmd)) throw new Error(`claude_command must be an absolute path to an executable: ${cmd}`)
833
+ const why = untrustedExecutable(cmd)
834
+ if (why) throw new Error(`refusing ${cmd} as Claude Code: ${why}`)
835
+ return throughDispatcher(cmd, 'claude')
836
+ }
837
+ for (const dir of String(process.env.PATH ?? '').split(':')) {
838
+ if (!isAbsolute(dir)) continue
839
+ const p = join(dir, cmd)
840
+ if (ok(p) && !untrustedExecutable(p)) return throughDispatcher(p, 'claude')
841
+ }
842
+ throw new Error(`"${cmd}" (Claude Code) was not found on the PATH (in a folder only you or root can change)`)
843
+ }
844
+
845
+ const runClaude = (cmd, args, opts = {}) => run(cmd, args, { cwd: HOME, ...opts, env: { ...process.env, PATH: trustedPath() } })
846
+ const claudeOrNull = () => { try { return claudeBinary() } catch { return null } }
847
+
848
+
849
+ async function claudeVersion(cmd) {
850
+ try {
851
+ const { stdout } = await runClaude(cmd, ['--version'], { timeout: 10_000 })
852
+ return stdout.trim().split('\n')[0].slice(0, 80)
853
+ } catch { return null }
854
+ }
855
+
856
+ // --- personas: a skill or agent a session follows -----------------------------------
857
+ //
858
+ // The dashboard offers the skills and agents found for a session's folder —
859
+ // the project's (<folder>/.claude/skills/<dir>/SKILL.md, <folder>/.claude/agents/<name>.md)
860
+ // and this user's (~/.claude/skills, ~/.claude/agents) — and sends back only
861
+ // the id of the one picked, never a path or a text. The machine looks it up
862
+ // again when the session opens: a skill's text goes into the system prompt
863
+ // (--append-system-prompt-file), an agent starts the session with --agent.
864
+ // Either way it is part of the system prompt, so it holds for the whole
865
+ // session: compactions don't summarize it away, and skills loaded later add
866
+ // to it, they don't replace it.
867
+ const PERSONA_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
868
+ const PERSONA_MAX_BYTES = 256 * 1024
869
+ const PERSONAS_MAX = 200
870
+ // The Pisha tools, as an agent's "tools" list names them.
871
+ const PISHA_TOOLS_PREFIX = 'mcp__plugin_pisha_pisha'
872
+
873
+ // The frontmatter of a SKILL.md or an agent file (the YAML between the
874
+ // leading "---" lines): top-level "key: value" pairs, quoted values, block
875
+ // scalars (| and >) and lists ("- item"). Enough for name, description and
876
+ // tools; anything else is ignored.
877
+ export function frontmatter(text) {
878
+ const m = /^?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text)
879
+ if (!m) return { data: {}, body: text }
880
+ const data = {}
881
+ const lines = m[1].split(/\r?\n/)
882
+ const unquote = v => {
883
+ v = v.trim()
884
+ if (/^"(.*)"$/.test(v)) { try { return JSON.parse(v) } catch { return v.slice(1, -1) } }
885
+ if (/^'(.*)'$/.test(v)) return v.slice(1, -1).replace(/''/g, "'")
886
+ return v
887
+ }
888
+ for (let i = 0; i < lines.length; i++) {
889
+ const kv = /^([A-Za-z_][\w-]*):[ \t]*(.*)$/.exec(lines[i])
890
+ if (!kv) continue
891
+ const [, key, raw] = kv
892
+ const more = []
893
+ while (i + 1 < lines.length && (/^[ \t]/.test(lines[i + 1]) || lines[i + 1].trim() === '')) more.push(lines[++i])
894
+ if (/^[|>][+-]?$/.test(raw.trim())) {
895
+ const parts = more.map(l => l.trim())
896
+ data[key] = (raw.trim()[0] === '>' ? parts.join(' ').replace(/\s+/g, ' ') : parts.join('\n')).trim()
897
+ } else if (!raw.trim() && more.some(l => /^\s*-\s/.test(l))) {
898
+ data[key] = more.filter(l => /^\s*-\s/.test(l)).map(l => unquote(l.replace(/^\s*-\s/, '')))
899
+ } else data[key] = unquote([raw, ...more.map(l => l.trim())].join(' '))
900
+ }
901
+ return { data, body: text.slice(m[0].length) }
902
+ }
903
+
904
+ // A persona's file, read only when it really is under its base folder (no
905
+ // symlink out of the project or out of ~/.claude), is this user's and isn't
906
+ // huge. null otherwise.
907
+ function readPersonaFile(path, base) {
908
+ try {
909
+ const real = realpathSync.native(path)
910
+ if (!within(real, realOr(base))) return null
911
+ const st = statSync(real)
912
+ if (!st.isFile() || st.size > PERSONA_MAX_BYTES) return null
913
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) return null
914
+ return { real, text: readFileSync(real, 'utf8') }
915
+ } catch { return null }
916
+ }
917
+
918
+ // One line of text for the dashboard: no control characters, at most n characters.
919
+ const oneLine = (v, n) => String(v ?? '').replace(/[\x00-\x1f\x7f-\x9f​-‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, n)
920
+
921
+ // Every persona for sessions opened in this folder (its real path).
922
+ export function listPersonas(folder, home = claudeHome()) {
923
+ // [scope, its .claude folder, where its files may really be]
924
+ const scopes = [['project', join(folder, '.claude'), folder], ['user', home, home]]
925
+ // (A session in the home folder: its project's .claude is the user's.)
926
+ if (realOr(scopes[0][1]) === realOr(home)) scopes.shift()
927
+ const out = []
928
+ const agentNames = new Set()
929
+ const entries = dir => { try { return readdirSync(dir, { withFileTypes: true }).filter(e => PERSONA_FILE_RE.test(e.name)).sort((a, b) => a.name.localeCompare(b.name)) } catch { return [] } }
930
+ for (const [scope, dot, base] of scopes) {
931
+ for (const e of entries(join(dot, 'skills'))) {
932
+ const f = readPersonaFile(join(dot, 'skills', e.name, 'SKILL.md'), base)
933
+ if (!f) continue
934
+ const { data } = frontmatter(f.text)
935
+ out.push({ id: `skill:${scope}:${e.name}`, kind: 'skill', scope, name: oneLine(data.name || e.name, 64), description: oneLine(data.description, 300), file: f.real, base })
936
+ }
937
+ for (const e of entries(join(dot, 'agents'))) {
938
+ if (!e.name.endsWith('.md')) continue
939
+ const f = readPersonaFile(join(dot, 'agents', e.name), base)
940
+ if (!f) continue
941
+ const { data } = frontmatter(f.text)
942
+ const name = String(data.name ?? '')
943
+ // Claude Code finds an agent by its name, the project's first: a user's
944
+ // agent with the name of one of the project's is never the one used.
945
+ // (Never with a dash first: it goes to Claude Code's command line.)
946
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name) || agentNames.has(name)) continue
947
+ agentNames.add(name)
948
+ const tools = Array.isArray(data.tools) ? data.tools : typeof data.tools === 'string' && data.tools.trim() ? data.tools.split(',') : null
949
+ // An agent limited to some tools, none of them Pisha's, can't message its squad.
950
+ const noPisha = !!tools && !tools.map(t => String(t).trim()).some(t => t === '*' || t.startsWith(PISHA_TOOLS_PREFIX))
951
+ out.push({ id: `agent:${scope}:${name}`, kind: 'agent', scope, name, description: oneLine(data.description, 300), no_pisha_tools: noPisha, file: f.real, base })
952
+ }
953
+ }
954
+ return out.slice(0, PERSONAS_MAX)
955
+ }
956
+
957
+ // What the dashboard sees of them (never a path or a text).
958
+ const personaView = p => ({ id: p.id, kind: p.kind, scope: p.scope, name: p.name, description: p.description, ...(p.no_pisha_tools ? { no_pisha_tools: true } : {}) })
959
+
960
+ // The persona a session opens with, looked up again in its folder now.
961
+ // (Agents other than Claude Code don't apply an agent's list of tools: toolsApply false.)
962
+ function findPersona(folder, id, role, { toolsApply = true } = {}) {
963
+ const p = listPersonas(folder).find(x => x.id === id)
964
+ if (!p) throw new Error(`the persona "${plain(id)}" is not in ${folder}/.claude or in this user's ${claudeHome()} any more: pick another one`)
965
+ if (p.no_pisha_tools && role !== 'solo' && toolsApply) {
966
+ throw new Error(`the agent "${p.name}" only allows some tools, none of them Pisha's: as a ${role} it could not message its squad. Add ${PISHA_TOOLS_PREFIX}__reply (and the other Pisha tools) to its "tools", or open it as a standalone session`)
967
+ }
968
+ return p
969
+ }
970
+
971
+ // A skill's text as the session's system prompt gets it: what it is, that
972
+ // it holds for the whole session, and where its own files are.
973
+ function skillPrompt(p) {
974
+ const f = readPersonaFile(p.file, p.base)
975
+ if (!f) throw new Error(`the skill "${p.name}" could not be read`)
976
+ return [
977
+ `# Persona of this session: the "${p.name}" skill`,
978
+ '',
979
+ 'The user opened this session to follow the skill below in all of its work, for as long as it runs: before and after any context compaction, and also when other skills are loaded later (they add to it, they never replace it). It never overrides what the user asks in this terminal, nor the Pisha rules (trust, access, permissions).',
980
+ `The skill's own files (references, scripts, templates) are in: ${dirname(f.real)}`,
981
+ '',
982
+ frontmatter(f.text).body.trim(),
983
+ '',
984
+ ].join('\n')
985
+ }
986
+
987
+ // Any persona's text, for agents that only take instructions (Codex CLI, Grok
988
+ // CLI): a skill as above, an agent's file as its own instructions (its tools
989
+ // and model are Claude Code's, not applied there).
990
+ function personaPrompt(p) {
991
+ if (p.kind === 'skill') return skillPrompt(p)
992
+ const f = readPersonaFile(p.file, p.base)
993
+ if (!f) throw new Error(`the agent "${p.name}" could not be read`)
994
+ return [
995
+ `# Persona of this session: the "${p.name}" agent`,
996
+ '',
997
+ 'The user opened this session to act as the agent below in all of its work, for as long as it runs, also after any context compaction. It never overrides what the user asks in this terminal, nor the Pisha rules (trust, access, permissions).',
998
+ '',
999
+ frontmatter(f.text).body.trim(),
1000
+ '',
1001
+ ].join('\n')
1002
+ }
1003
+
1004
+ // --- the Pisha plugin on this machine ----------------------------------------------
1005
+ //
1006
+ // Sessions need the plugin installed in this machine's Claude Code. Where it
1007
+ // comes from is fixed here on purpose: the server never decides what gets
1008
+ // installed on this machine.
1009
+
1010
+ const PLUGIN_ID = 'pisha@pisha'
1011
+ const PLUGIN_REPO = 'roke22/pisha'
1012
+ const ourRepo = repo => PLUGIN_REPO.toLowerCase() === String(repo ?? '').toLowerCase()
1013
+ // The plugin version that goes with this program: a release tag, not whatever
1014
+ // the default branch holds today.
1015
+ const PLUGIN_MARKETPLACE = `${PLUGIN_REPO}#v${VERSION}`
1016
+ const PLUGIN_COMMANDS = `claude plugin marketplace add ${PLUGIN_MARKETPLACE} && claude plugin install ${PLUGIN_ID}`
1017
+
1018
+ // The "pisha" marketplace, as Claude Code has it (or null).
1019
+ // A marketplace called "pisha" that isn't this project's would be trusted
1020
+ // blindly by "plugin install pisha@pisha": refuse it.
1021
+ async function checkMarketplace(cmd) {
1022
+ let list = []
1023
+ try { list = JSON.parse((await runClaude(cmd, ['plugin', 'marketplace', 'list', '--json'], { timeout: 30_000, cwd: HOME })).stdout) } catch { return null }
1024
+ const m = Array.isArray(list) ? list.find(x => x?.name === 'pisha') : null
1025
+ if (m && !ourRepo(m.repo)) {
1026
+ throw new Error(`a different marketplace named "pisha" is installed (${plain(m.repo ?? m.source ?? 'unknown source')}). Remove it with: claude plugin marketplace remove pisha`)
1027
+ }
1028
+ return m ?? null
1029
+ }
1030
+
1031
+ // A marketplace added without a version (or another one) follows whatever the
1032
+ // repository holds: replace it with this program's release tag. Removing a
1033
+ // marketplace uninstalls its plugins, so the plugin is installed again after.
1034
+ async function pinMarketplace(cmd, opts) {
1035
+ const m = await checkMarketplace(cmd)
1036
+ // (Only an unpinned or older marketplace moves: a newer one is left alone.)
1037
+ const ref = String(m?.ref ?? '')
1038
+ // (A version tag in any spelling — v0.0.3, 0.0.3, V0.0.3-beta.1 — by its numbers.)
1039
+ const tag = /^v?(\d+(?:\.\d+)*)(?:-.*)?$/i.exec(ref)
1040
+ // (The repository's old name moves too, to this version's tag under the new one.)
1041
+ const oldName = String(m?.repo ?? '').toLowerCase() !== PLUGIN_REPO.toLowerCase()
1042
+ if (!m || (!oldName && (ref === `v${VERSION}` || (tag && !olderVersion(tag[1], VERSION))))) return false
1043
+ // Removing the marketplace uninstalls the plugin: first make sure the
1044
+ // release tag can be fetched, so a missing tag or no network changes nothing.
1045
+ // (PISHA_HOST_TEST_SKIP_TAG_CHECK=1: the test suite only.)
1046
+ if (process.env.PISHA_HOST_TEST_SKIP_TAG_CHECK !== '1') try {
1047
+ const git = findTrusted('git')
1048
+ if (!git) throw new Error('git was not found in a folder only you or root can change')
1049
+ const { stdout } = await run(git, ['ls-remote', '--tags', `https://github.com/${PLUGIN_REPO}.git`, `refs/tags/v${VERSION}`], { cwd: HOME, timeout: 30_000, env: { ...process.env, PATH: trustedPath(), GIT_TERMINAL_PROMPT: '0' } })
1050
+ if (!stdout.trim()) throw new Error(`the release tag v${VERSION} is not published`)
1051
+ } catch (err) {
1052
+ throw new Error(`cannot move the Pisha marketplace to v${VERSION} (${String(err.message).split('\n')[0]}): nothing was changed`)
1053
+ }
1054
+ await runClaude(cmd, ['plugin', 'marketplace', 'remove', 'pisha'], opts)
1055
+ try {
1056
+ await runClaude(cmd, ['plugin', 'marketplace', 'add', PLUGIN_MARKETPLACE], opts)
1057
+ } catch (err) {
1058
+ // (The one it had goes back, so the machine isn't left without the plugin.)
1059
+ const before = `${m.repo || PLUGIN_REPO}${m.ref ? `#${m.ref}` : ''}`
1060
+ let restored = false
1061
+ try { await runClaude(cmd, ['plugin', 'marketplace', 'add', before], opts); await runClaude(cmd, ['plugin', 'install', PLUGIN_ID], opts); restored = true } catch {}
1062
+ throw new Error(`could not add ${PLUGIN_MARKETPLACE} (${err.message.split('\n')[0]}); ${restored ? `the marketplace was put back as ${before}` : `putting back ${before} failed too: run "claude plugin marketplace add ${before} && claude plugin install ${PLUGIN_ID}" once the network is back`}`)
1063
+ }
1064
+ await runClaude(cmd, ['plugin', 'install', PLUGIN_ID], opts)
1065
+ log(`Pisha marketplace pinned to v${VERSION} (it was ${m.ref ? `at ${plain(m.ref)}` : 'following the default branch'})`)
1066
+ return true
1067
+ }
1068
+
1069
+ async function pluginStatus(cmd = claudeOrNull()) {
1070
+ if (!cmd) return null
1071
+ try {
1072
+ const { stdout } = await runClaude(cmd, ['plugin', 'list', '--json'], { timeout: 30_000, cwd: HOME })
1073
+ const p = JSON.parse(stdout).find(x => x?.id === PLUGIN_ID)
1074
+ return p ? { installed: true, version: typeof p.version === 'string' ? p.version : null, enabled: p.enabled !== false } : { installed: false, version: null, enabled: false }
1075
+ } catch {
1076
+ return null // Claude Code missing, or too old to list plugins as JSON
1077
+ }
1078
+ }
1079
+
1080
+ // Install the plugin if it's missing (or enable it), or update it if it's there.
1081
+ async function ensurePlugin({ update = false } = {}) {
1082
+ const cmd = claudeBinary()
1083
+ const opts = { timeout: 180_000, cwd: HOME }
1084
+ let st = await pluginStatus(cmd)
1085
+ if (st === null) throw new Error(`cannot run "${cmd} plugin list": install Claude Code (or set claude_command in ${SETTINGS_FILE})`)
1086
+ if (await pinMarketplace(cmd, opts)) {
1087
+ st = await pluginStatus(cmd)
1088
+ } else if (!st.installed) {
1089
+ // "add" fails if the marketplace is already there: the install decides.
1090
+ try { await runClaude(cmd, ['plugin', 'marketplace', 'add', PLUGIN_MARKETPLACE], opts) } catch {}
1091
+ await runClaude(cmd, ['plugin', 'install', PLUGIN_ID], opts)
1092
+ } else if (update) {
1093
+ await runClaude(cmd, ['plugin', 'marketplace', 'update', 'pisha'], opts)
1094
+ await runClaude(cmd, ['plugin', 'update', PLUGIN_ID], opts)
1095
+ }
1096
+ st = await pluginStatus(cmd)
1097
+ if (st?.installed && !st.enabled) { await runClaude(cmd, ['plugin', 'enable', PLUGIN_ID], opts); st = await pluginStatus(cmd) }
1098
+ if (!st?.installed) throw new Error('the plugin did not install')
1099
+ PLUGIN = st
1100
+ return st
1101
+ }
1102
+
1103
+ // Claude Code's config folder, as the plugin takes it: an empty or relative
1104
+ // CLAUDE_CONFIG_DIR counts as unset.
1105
+ const claudeHome = () => { const c = process.env.CLAUDE_CONFIG_DIR; return c && isAbsolute(c) ? c : join(HOME, '.claude') }
1106
+
1107
+ // The plugin's settings on this machine (its .env), read like the plugin does.
1108
+ function pluginEnv() {
1109
+ const out = {}
1110
+ try {
1111
+ for (const line of readFileSync(join(claudeHome(), 'channels', 'pisha', '.env'), 'utf8').split(/\r?\n/)) {
1112
+ const m = line.match(/^(\w+)=(.*)$/)
1113
+ if (m) out[m[1].replace(/^SWARM_/, 'PISHA_')] = m[2]
1114
+ }
1115
+ } catch {}
1116
+ return out
1117
+ }
1118
+ // A machine enrolled with --insecure before the plugin asked to be told too.
1119
+ function acceptPlainHttpInPlugin(server) {
1120
+ if (!server.startsWith('http://') || pluginEnv().PISHA_INSECURE === '1' || pluginServerUrl() !== server.replace(/\/+$/, '')) return
1121
+ let fd
1122
+ try {
1123
+ fd = openSync(join(claudeHome(), 'channels', 'pisha', '.env'), FS.O_WRONLY | FS.O_APPEND | (FS.O_NOFOLLOW ?? 0))
1124
+ appendFileSync(fd, 'PISHA_INSECURE=1\n')
1125
+ } catch {} finally { if (fd !== undefined) closeSync(fd) }
1126
+ }
1127
+ const pluginServerUrl = () => { const u = pluginEnv().PISHA_URL; return u && /^https?:\/\/\S+$/.test(u) ? u.replace(/\/+$/, '') : null }
1128
+ // The plugin's rule for its own folders (paths.js safeChain): the folder is
1129
+ // this user's and nobody else can write to it (a private group is fine), and
1130
+ // every folder above is this user's or root's and nobody else can rename what
1131
+ // is in it (sticky is fine; a shared group isn't); no symlink on the way.
1132
+ // Missing folders count by the nearest one above that exists.
1133
+ function privateChain(path, upTo = path) {
1134
+ const me = typeof process.getuid === 'function' ? process.getuid() : null
1135
+ // (Up to upTo, included: the strict rule. The same text as the plugin's safeChain.)
1136
+ let below = true
1137
+ for (let d = resolve(path); ; d = dirname(d)) {
1138
+ let st = null
1139
+ try { st = lstatSync(d) } catch (err) { if (err.code !== 'ENOENT') return false }
1140
+ if (st) {
1141
+ if (st.isSymbolicLink() || !st.isDirectory()) return false
1142
+ }
1143
+ if (st) {
1144
+ if (below) {
1145
+ const groupOk = !(st.mode & 0o020) || privateGroup(st.gid)
1146
+ if ((me !== null && st.uid !== me) || (st.mode & 0o002) || !groupOk) return false
1147
+ } else {
1148
+ const sticky = !!(st.mode & 0o1000)
1149
+ const groupOk = !(st.mode & 0o020) || sticky || privateGroup(st.gid) || st.gid === 0 || (platform() === 'darwin' && st.gid === 80)
1150
+ if ((me !== null && st.uid !== me && st.uid !== 0) || ((st.mode & 0o002) && !sticky) || !groupOk) return false
1151
+ }
1152
+ }
1153
+ if (d === resolve(upTo)) below = false
1154
+ if (dirname(d) === d) return true
1155
+ }
1156
+ }
1157
+
1158
+ function pluginStateDir(name) {
1159
+ // The same folder the plugin uses: one per name, also inside a custom state folder.
1160
+ // (The plugin only accepts a custom folder that is this user's and that
1161
+ // others can't write to: the same rule here, or the two would disagree.)
1162
+ let custom = pluginEnv().PISHA_STATE_DIR
1163
+ if (custom && isAbsolute(custom)) custom = privateChain(realNearest(custom)) ? realNearest(custom) : null
1164
+ else custom = null
1165
+ return join(custom ?? join(claudeHome(), 'channels', 'pisha'), name)
1166
+ }
1167
+
1168
+ // What must hold before a session opens here. It returns the program to run.
1169
+ async function prepareSession(s, settings) {
1170
+ const claude = claudeBinary(settings.claude_command)
1171
+ // Without the plugin the session would start, but never join Pisha.
1172
+ // Checked every time (opening a session is rare): it may have been removed.
1173
+ const st = await pluginStatus(claude)
1174
+ if (st) PLUGIN = st
1175
+ if (st && (!st.installed || !st.enabled)) {
1176
+ throw new Error(`the Pisha plugin is ${PLUGIN.installed ? 'disabled' : 'not installed'} in Claude Code on this machine. Run "${cli()} plugin" there, or: ${PLUGIN_COMMANDS}`)
1177
+ }
1178
+ // An older plugin can't talk to this server (it doesn't send its session id).
1179
+ if (st?.version && olderVersion(st.version, VERSION)) {
1180
+ throw new Error(`the Pisha plugin on this machine is ${plain(st.version)}, older than this pisha-host (${VERSION}): run "${cli()} plugin" there, then open the session again`)
1181
+ }
1182
+ checkPluginState(s)
1183
+ // The persona, looked up again in the folder now (it may have changed since
1184
+ // the dashboard listed it).
1185
+ s.personaInfo = s.persona ? findPersona(s.folder, s.persona, s.role) : null
1186
+ return claude
1187
+ }
1188
+
1189
+ // Where the plugin keeps its state and which server it talks to, checked
1190
+ // before any session opens, whatever its agent (they all run this plugin).
1191
+ function checkPluginState(s) {
1192
+ // The plugin ignores a CLAUDE_CONFIG_DIR inside the highest folder above the
1193
+ // session's folder that doesn't contain the home (a repository could plant
1194
+ // one): it would never find what is written here. Said now, not silently.
1195
+ if (process.env.CLAUDE_CONFIG_DIR && isAbsolute(process.env.CLAUDE_CONFIG_DIR)) {
1196
+ const cfg = realOr(process.env.CLAUDE_CONFIG_DIR)
1197
+ let top = null
1198
+ const home = realOr(HOME)
1199
+ for (let d = s.folder; !withinById(home, d) && !withinById(HOME, d); d = dirname(d)) { top = d; if (dirname(d) === d) break }
1200
+ if (top && withinById(cfg, top)) throw new Error(`CLAUDE_CONFIG_DIR (${cfg}) is inside ${top}, like the session's folder: the Pisha plugin would ignore it. Move it, or open sessions in folders elsewhere`)
1201
+ // Nor one that isn't private, it or a folder above it (the plugin
1202
+ // ignores that too: the same rule).
1203
+ const state = realNearest(join(cfg, 'channels', 'pisha'))
1204
+ if (!privateChain(state, withinById(state, cfg) ? cfg : state)) throw new Error(`CLAUDE_CONFIG_DIR (${cfg}) must be a folder of this user that others can't write to, inside folders nobody else can change`)
1205
+ }
1206
+ // The secret the server reserved goes only to that server: the plugin
1207
+ // here must be configured for it (same origin), or the session isn't opened.
1208
+ const origin = u => { try { return new URL(u).origin } catch { return null } }
1209
+ if (s.identity && CREDS_SERVER && origin(pluginServerUrl()) !== origin(CREDS_SERVER)) {
1210
+ throw new Error(`the Pisha plugin on this machine is configured for ${pluginServerUrl() ?? 'no server'}, but this machine belongs to ${CREDS_SERVER}: set PISHA_URL=${CREDS_SERVER} in ${join(claudeHome(), 'channels', 'pisha', '.env')}`)
1211
+ }
1212
+ }
1213
+
1214
+ // What a session's process is started with, besides what is Pisha's.
1215
+ function sessionEnv(s) {
1216
+ const env = {}
1217
+ if (s.compact_window) env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = String(s.compact_window)
1218
+ // Claude Code's config folder is this program's, not the one the tmux
1219
+ // server started with (it outlives restarts of this program).
1220
+ const cfg = process.env.CLAUDE_CONFIG_DIR
1221
+ if (cfg && isAbsolute(cfg)) env.CLAUDE_CONFIG_DIR = cfg
1222
+ return env
1223
+ }
1224
+
1225
+ // The conversation a session was last in, as its plugin noted it, if it can be
1226
+ // continued: in the same folder and still saved. Never --continue: that takes
1227
+ // the folder's last conversation, which can be another session's.
1228
+ // matches(id, transcript): whether the transcript is that conversation's, by
1229
+ // where its agent keeps them (Claude Code's, unless said).
1230
+ function ownConversation(dir, folder, matches = (id, transcript) => transcript.endsWith(`${sep}${id}.jsonl`)) {
1231
+ try {
1232
+ // (A session can write here: a pipe or a device would stop this program.)
1233
+ const file = join(dir, 'conversation.json')
1234
+ const st = lstatSync(file)
1235
+ if (!st.isFile() || st.size > 8192) return null
1236
+ const c = JSON.parse(readFileSync(file, 'utf8'))
1237
+ if (typeof c.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(c.id)) return null
1238
+ if (typeof c.transcript !== 'string' || !matches(c.id, c.transcript) || !statSync(c.transcript).isFile()) return null
1239
+ return realpathSync(c.folder) === folder ? c.id : null
1240
+ } catch { return null }
1241
+ }
1242
+
1243
+ // The command a session runs, after the "env" that starts it. env: the one
1244
+ // sessionEnv gave. dir: the plugin's folder for this session.
1245
+ // What the user wrote in the dashboard about what this session may do.
1246
+ function permissionNotes(p) {
1247
+ return `PERMISSIONS. This session follows the permission profile "${p.profile}", set by the user in the Pisha dashboard. Claude Code's permission rules enforce it; what the user wrote about it, as the reason (quoted):\n${JSON.stringify(p.notes)}\nWork within it: don't look for another way to do what it rules out. If a task needs it, say so in your report instead.`
1248
+ }
1249
+
1250
+ function sessionCommand(s, claude, dir, env) {
1251
+ // (A standalone session takes no messages: no development channel, and so
1252
+ // no dialog about it at every start. The plugin still reports its activity.)
1253
+ const argv = [...(env.CLAUDE_CONFIG_DIR ? [] : ['-u', 'CLAUDE_CONFIG_DIR']), claude, ...(s.role === 'solo' ? [] : ['--dangerously-load-development-channels', 'plugin:pisha@pisha'])]
1254
+ if (s.resume) {
1255
+ const conversation = ownConversation(dir, s.folder)
1256
+ if (conversation) argv.push('--resume', conversation)
1257
+ else log(`"${s.name}" has no conversation of its own to continue: it starts a new one`)
1258
+ }
1259
+ // The persona, in the system prompt: a skill's text from a private copy
1260
+ // (what the session reads is what was checked, not the file as it may be
1261
+ // later), an agent by its name. And what the user wrote about its
1262
+ // permissions, after it: the reason for the rules below.
1263
+ const promptFile = join(dir, 'persona.md')
1264
+ const prompt = [
1265
+ ...(s.personaInfo?.kind === 'skill' ? [skillPrompt(s.personaInfo)] : []),
1266
+ ...(s.permissions?.notes ? [permissionNotes(s.permissions)] : []),
1267
+ ].join('\n\n')
1268
+ const writePrivate = (file, text) => {
1269
+ ensurePrivateDir(dir)
1270
+ const tmp = join(dir, `.${basename(file)}.${process.pid}.${Date.now()}`)
1271
+ writeFileSync(tmp, text, { mode: 0o600, flag: 'wx' })
1272
+ renameSync(tmp, file)
1273
+ }
1274
+ if (prompt) {
1275
+ writePrivate(promptFile, prompt)
1276
+ argv.push('--append-system-prompt-file', promptFile)
1277
+ } else rmSync(promptFile, { force: true })
1278
+ if (s.personaInfo?.kind === 'agent') argv.push('--agent', s.personaInfo.name)
1279
+ // Its permission profile, as Claude Code's own rules: they are added to the
1280
+ // user's and the project's, and a rule that forbids wins over any that
1281
+ // allows, wherever each one is.
1282
+ 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 })
1287
+ return argv
1288
+ }
1289
+
1290
+ // One line typed in a session's input and sent, as the user would.
1291
+ async function typeLine(target, line, landed) {
1292
+ // What the server knows comes from hooks; the screen says what Enter would do.
1293
+ // On a question from Claude Code it would answer it: a permission prompt's
1294
+ // highlighted option is "Yes".
1295
+ const screen = async () => (await tmux(['capture-pane', '-p', '-J', '-t', target])).stdout.split('\n').filter(l => l.trim()).slice(-20).join('\n')
1296
+ if (ASKING_ON_SCREEN.test(await screen())) throw new Error('it is waiting for an answer on its screen')
1297
+ // (Typed, then Enter a moment later: as one burst the menu of commands
1298
+ // could still be completing "/clear" when Enter arrives.)
1299
+ await tmux(['send-keys', '-t', target, '-l', line])
1300
+ await new Promise(r => setTimeout(r, 300))
1301
+ // (Only if it landed where things are typed.)
1302
+ if (!landed.test(await screen())) throw new Error("what was typed didn't reach its input")
1303
+ await tmux(['send-keys', '-t', target, 'Enter'])
1304
+ }
1305
+
1306
+ const clearContext = target => typeLine(target, '/clear', /(^|\s)\/clear\s*$/m)
1307
+
1308
+ // The user's answer to a question its coordinator left in their inbox: one
1309
+ // line (Enter would send the rest as another message), checked by its end.
1310
+ async function typeAnswer(target, text) {
1311
+ const line = String(text).replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/\s+/g, ' ').trim()
1312
+ if (!line || line.length > 2200) throw new Error('the answer must be one line of up to 2200 characters')
1313
+ await typeLine(target, line, { test: screen => answerLanded(screen, line) })
1314
+ }
1315
+
1316
+ // Whether a typed answer reached the input: its end is there, or the paste
1317
+ // Claude Code shows a long one as instead ("[Pasted text #1 +3 lines]").
1318
+ export function answerLanded(screen, line) {
1319
+ const end = String(line).split(' ').pop().slice(-20).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
1320
+ return new RegExp(`(${end}|\\[Pasted text #\\d+[^\\]\\n]*\\])\\s*│?\\s*$`, 'm').test(screen)
1321
+ }
1322
+
1323
+ const ASKING_ON_SCREEN = /^\s*❯\s*\d+\.\s|Esc to cancel|Enter to confirm/m
1324
+
1325
+ const claudeCode = {
1326
+ // Where the program is (checked, see claudeBinary), and which version.
1327
+ program: claudeBinary,
1328
+ programOrNull: claudeOrNull,
1329
+ version: claudeVersion,
1330
+ // Its config folder.
1331
+ home: claudeHome,
1332
+ // Opening a session, resuming its conversation or with a persona included.
1333
+ prepareSession,
1334
+ sessionEnv,
1335
+ sessionCommand,
1336
+ // Typed in a session's terminal, as the user would.
1337
+ clearContext,
1338
+ typeAnswer,
1339
+ // The skills and agents a session opened in this folder could follow, as the dashboard sees them.
1340
+ personas: folder => listPersonas(folder).map(personaView),
1341
+ // For the other agents: a persona found again, and its text; the conversation a session can continue.
1342
+ findPersona,
1343
+ personaPrompt,
1344
+ conversation: ownConversation,
1345
+ // The Pisha plugin in its config: installed, and how it is set up.
1346
+ plugin: {
1347
+ status: pluginStatus,
1348
+ ensure: ensurePlugin,
1349
+ commands: PLUGIN_COMMANDS,
1350
+ checkState: checkPluginState,
1351
+ serverUrl: pluginServerUrl,
1352
+ stateDir: pluginStateDir,
1353
+ acceptPlainHttp: acceptPlainHttpInPlugin,
1354
+ },
1355
+ }
1356
+
1357
+ // --- Codex CLI and Grok CLI -----------------------------------------------------------
1358
+ //
1359
+ // Sessions can also run Codex CLI or Grok CLI. Both run the same Pisha
1360
+ // plugin (they read Claude Code's plugin format), installed with their own
1361
+ // plugin commands from the same release tag, but they have no channels: the
1362
+ // plugin leaves what arrives in <state>/pending-input/, and this program types
1363
+ // it in the session's terminal while the agent waits for input (see
1364
+ // typeWaiting). The rest of the file uses them only through the codexCli and
1365
+ // grokCli objects at the end of this section, and AGENTS.
1366
+
1367
+ // An executable by name (from the trusted PATH folders) or by absolute path,
1368
+ // checked like Claude Code's. null when it isn't there.
1369
+ function typedProgram(cmd) {
1370
+ const ok = p => { try { accessSync(p, FS.X_OK); return statSync(p).isFile() } catch { return false } }
1371
+ if (cmd.includes('/')) return isAbsolute(cmd) && ok(cmd) && !untrustedExecutable(cmd) ? throughDispatcher(cmd, basename(cmd)) : null
1372
+ for (const dir of String(process.env.PATH ?? '').split(':')) {
1373
+ if (!isAbsolute(dir)) continue
1374
+ const p = join(dir, cmd)
1375
+ if (ok(p) && !untrustedExecutable(p)) return throughDispatcher(p, cmd)
1376
+ }
1377
+ return null
1378
+ }
1379
+ const runTyped = (cmd, args, opts = {}) => run(cmd, args, { cwd: HOME, timeout: 30_000, ...opts, env: { ...process.env, PATH: trustedPath() } })
1380
+
1381
+ async function typedVersion(cmd) {
1382
+ try { return (await runTyped(cmd, ['--version'], { timeout: 10_000 })).stdout.trim().split('\n')[0].slice(0, 80) } catch { return null }
1383
+ }
1384
+
1385
+ // Where the plugin comes from: this project's repository at this program's
1386
+ // release tag, never what the server says.
1387
+ const TYPED_REPO = 'roke22/pisha'
1388
+ const ourSource = src => typeof src === 'string' && (isAbsolute(src) || src.toLowerCase().includes(TYPED_REPO.toLowerCase()))
1389
+
1390
+ // Codex's config folder.
1391
+ const codexHome = () => { const c = process.env.CODEX_HOME; return c && isAbsolute(c) ? c : join(HOME, '.codex') }
1392
+
1393
+ async function codexPluginStatus(cmd = typedProgram(loadSettings().codex_command)) {
1394
+ if (!cmd) return null
1395
+ try {
1396
+ // (Only this marketplace: signed in, the whole list also fetches OpenAI's
1397
+ // remote catalog, about a minute.)
1398
+ const list = JSON.parse((await runTyped(cmd, ['plugin', 'list', '--marketplace', 'pisha', '--json'])).stdout)
1399
+ const p = (list?.installed ?? []).find(x => x?.pluginId === 'pisha@pisha')
1400
+ if (!p) return { installed: false, version: null, enabled: false, root: null }
1401
+ // A plugin called pisha from somewhere else is not ours.
1402
+ if (!ourSource(p.marketplaceSource?.source)) throw new Error(`a different marketplace named "pisha" is installed in Codex (${plain(p.marketplaceSource?.source ?? 'unknown source')}). Remove it with: codex plugin marketplace remove pisha`)
1403
+ const version = typeof p.version === 'string' ? p.version : null
1404
+ const root = p.source?.source === 'local' && isAbsolute(String(p.source.path ?? '')) ? p.source.path : version && /^[\w.-]+$/.test(version) ? join(codexHome(), 'plugins', 'cache', 'pisha', 'pisha', version) : null
1405
+ return { installed: p.installed !== false, version, enabled: p.enabled !== false, root }
1406
+ } catch (err) {
1407
+ if (/different marketplace/.test(err.message)) throw err
1408
+ return null
1409
+ }
1410
+ }
1411
+
1412
+ async function ensureCodexPlugin({ update = false } = {}) {
1413
+ const cmd = typedProgram(loadSettings().codex_command)
1414
+ if (!cmd) throw new Error('Codex CLI ("codex") was not found on the PATH')
1415
+ let st = await codexPluginStatus(cmd)
1416
+ if (st === null) throw new Error(`cannot run "${cmd} plugin list --json": update Codex CLI`)
1417
+ if (!st.installed || update || (st.version && olderVersion(st.version, VERSION))) {
1418
+ // ("add" fails if the marketplace is there already: the plugin install decides.)
1419
+ try { await runTyped(cmd, ['plugin', 'marketplace', 'add', TYPED_REPO, '--ref', `v${VERSION}`], { timeout: 180_000 }) } catch {}
1420
+ if (st.installed) { try { await runTyped(cmd, ['plugin', 'marketplace', 'upgrade', 'pisha'], { timeout: 180_000 }) } catch {} }
1421
+ await runTyped(cmd, ['plugin', 'add', 'pisha@pisha'], { timeout: 180_000 })
1422
+ st = await codexPluginStatus(cmd)
1423
+ }
1424
+ if (!st?.installed) throw new Error('the plugin did not install in Codex')
1425
+ return st
1426
+ }
1427
+
1428
+ async function grokPluginStatus(cmd = typedProgram(loadSettings().grok_command)) {
1429
+ if (!cmd) return null
1430
+ try {
1431
+ const list = JSON.parse((await runTyped(cmd, ['plugin', 'list', '--json'])).stdout)
1432
+ const p = (Array.isArray(list) ? list : []).find(x => x?.name === 'pisha')
1433
+ if (!p) return { installed: false, version: null, enabled: false, root: null }
1434
+ if (!ourSource(p.source)) throw new Error(`a different plugin named "pisha" is installed in Grok (${plain(p.source ?? 'unknown source')}). Remove it with: grok plugin uninstall pisha`)
1435
+ return { installed: true, version: typeof p.version === 'string' ? p.version : null, enabled: p.status !== 'disabled', root: typeof p.path === 'string' ? p.path : null }
1436
+ } catch (err) {
1437
+ if (/different plugin/.test(err.message)) throw err
1438
+ return null
1439
+ }
1440
+ }
1441
+
1442
+ async function ensureGrokPlugin({ update = false } = {}) {
1443
+ const cmd = typedProgram(loadSettings().grok_command)
1444
+ if (!cmd) throw new Error('Grok CLI ("grok") was not found on the PATH')
1445
+ let st = await grokPluginStatus(cmd)
1446
+ if (st === null) throw new Error(`cannot run "${cmd} plugin list --json": update Grok CLI`)
1447
+ if (st.installed && (update || (st.version && olderVersion(st.version, VERSION)))) {
1448
+ await runTyped(cmd, ['plugin', 'uninstall', 'pisha'], { timeout: 180_000 })
1449
+ st = { installed: false }
1450
+ }
1451
+ if (!st.installed) {
1452
+ // (The plugin is a folder of the repository: #subdir.)
1453
+ await runTyped(cmd, ['plugin', 'install', `${TYPED_REPO}@v${VERSION}#plugins/pisha`, '--trust'], { timeout: 180_000 })
1454
+ st = await grokPluginStatus(cmd)
1455
+ }
1456
+ if (st?.installed && !st.enabled) { await runTyped(cmd, ['plugin', 'enable', 'pisha'], { timeout: 60_000 }); st = await grokPluginStatus(cmd) }
1457
+ if (!st?.installed) throw new Error('the plugin did not install in Grok')
1458
+ return st
1459
+ }
1460
+
1461
+ // What must hold before a session opens: the program, and the plugin in it
1462
+ // (installed now if it is missing: sessions opened from the dashboard must
1463
+ // work unattended). Returns { program, root }.
1464
+ async function prepareTyped(a, s) {
1465
+ const program = typedProgram(a.command(loadSettings()))
1466
+ if (!program) throw new Error(`${a.name} ("${a.command(loadSettings())}") was not found on this machine`)
1467
+ // The same plugin as Claude Code's: the same rules for its state and server.
1468
+ claudeCode.plugin.checkState(s)
1469
+ // The persona, looked up again in the folder now; its text goes in as
1470
+ // instructions (see personaArg).
1471
+ s.personaInfo = s.persona ? claudeCode.findPersona(s.folder, s.persona, s.role, { toolsApply: false }) : null
1472
+ let st = await a.plugin.status(program)
1473
+ if (!st?.installed || !st.enabled || (st.version && olderVersion(st.version, VERSION))) {
1474
+ log(`installing the Pisha plugin in ${a.name}`)
1475
+ st = await a.plugin.ensure()
1476
+ }
1477
+ return { program, root: st.root }
1478
+ }
1479
+
1480
+ // TOML strings for Codex's -c (JSON's escapes are TOML's).
1481
+ const toml = v => JSON.stringify(String(v))
1482
+
1483
+ // A persona is longer than the commands tmux takes: its text is left in a
1484
+ // private file of the session (what the agent gets is what was checked now)
1485
+ // and a fixed shell line adds it as one argument when the agent starts (an
1486
+ // argument holds up to 128 KB). argv without a persona as it is.
1487
+ const PERSONA_ARG_MAX = 100 * 1024
1488
+ function personaArg(s, dir, argv, flag, text) {
1489
+ const file = join(dir, 'persona.arg')
1490
+ if (!s.personaInfo) { rmSync(file, { force: true }); return argv }
1491
+ const value = text(claudeCode.personaPrompt(s.personaInfo))
1492
+ if (Buffer.byteLength(value) > PERSONA_ARG_MAX) throw new Error(`the persona "${plain(s.personaInfo.name)}" is too long for this agent (over ${PERSONA_ARG_MAX / 1024} KB)`)
1493
+ ensurePrivateDir(dir)
1494
+ const tmp = join(dir, `.persona.arg.${process.pid}.${Date.now()}`)
1495
+ writeFileSync(tmp, value, { mode: 0o600, flag: 'wx' })
1496
+ renameSync(tmp, file)
1497
+ return ['/bin/sh', '-c', `f=$1; shift; exec "$@" ${flag} "$(cat "$f")"`, 'sh', file, ...argv]
1498
+ }
1499
+
1500
+ // The conversation a session can continue (its own, as Claude Code's), if it asked to.
1501
+ function typedConversation(s, dir, matches) {
1502
+ if (!s.resume) return null
1503
+ const id = claudeCode.conversation(dir, s.folder, matches)
1504
+ if (!id) log(`"${plain(s.name)}" has no conversation of its own to continue: it starts a new one`)
1505
+ return id
1506
+ }
1507
+
1508
+ // The command a session runs, after the "env" that starts it. env: the
1509
+ // session's variables (the plugin needs them: Codex gives an MCP server only
1510
+ // what it is told). dir: the plugin's folder for this session.
1511
+ function codexCommand(s, prep, env, dir) {
1512
+ const server = join(String(prep.root ?? ''), 'server.js')
1513
+ if (!prep.root || !existsSync(server)) throw new Error(`the Pisha plugin in Codex is not where expected (${server}): run "${cli()} plugin"`)
1514
+ const mcpEnv = Object.entries(env).filter(([k]) => /^(PISHA_[A-Z_]+|CLAUDE_CONFIG_DIR)$/.test(k))
1515
+ // (Codex keeps each conversation in <home>/sessions/…/rollout-<date>-<id>.jsonl.)
1516
+ const conversation = typedConversation(s, dir, (id, t) => t.endsWith(`-${id}.jsonl`) && within(t, join(codexHome(), 'sessions')))
1517
+ // Codex doesn't expand ${CLAUDE_PLUGIN_ROOT} in the plugin's own server, so
1518
+ // the server is given here, under the same name (it replaces that one), and
1519
+ // its tools need no approval (they only message the squad).
1520
+ const argv = [prep.program, ...(conversation ? ['resume'] : []),
1521
+ '-c', `mcp_servers.pisha.command=${toml(process.execPath)}`,
1522
+ '-c', `mcp_servers.pisha.args=[${toml(server)}]`,
1523
+ '-c', `mcp_servers.pisha.env={${mcpEnv.map(([k, v]) => `${k}=${toml(v)}`).join(',')}}`,
1524
+ // (enabled too: a project's own config could turn it off.)
1525
+ '-c', 'mcp_servers.pisha.enabled=true',
1526
+ '-c', 'mcp_servers.pisha.default_tools_approval_mode="approve"',
1527
+ '-c', 'mcp_servers.pisha.startup_timeout_sec=30',
1528
+ ...(conversation ? [conversation] : []),
1529
+ ]
1530
+ // (The persona as developer instructions: they last the whole session.)
1531
+ return personaArg(s, dir, argv, '-c', text => `developer_instructions=${toml(text)}`)
1532
+ }
1533
+
1534
+ // Grok's config folder.
1535
+ const grokHome = () => join(HOME, '.grok')
1536
+
1537
+ // Grok runs the plugin's server itself (it sets CLAUDE_PLUGIN_ROOT); its
1538
+ // tools are allowed without asking (they only message the squad).
1539
+ // A project file defining an MCP server named pisha (from the folder up to
1540
+ // its git root, where Grok looks): Grok would run it instead of the plugin's,
1541
+ // the session would never join, and its tools would get the --allow below.
1542
+ export function grokProjectPisha(folder) {
1543
+ const defines = file => {
1544
+ try {
1545
+ const st = lstatSync(file)
1546
+ if (!st.isFile() || st.size > 1024 * 1024) return false
1547
+ const text = readFileSync(file, 'utf8')
1548
+ if (file.endsWith('.json')) { const j = JSON.parse(text); return !!j && typeof j === 'object' && j.mcpServers && Object.hasOwn(j.mcpServers, 'pisha') }
1549
+ return /^\s*\[\s*mcp_servers\s*\.\s*"?pisha"?\s*[\].]|^\s*mcp_servers\s*\.\s*"?pisha"?\s*[.=]|^\s*pisha\s*=\s*\{/m.test(text) && /mcp_servers/.test(text)
1550
+ } catch { return false }
1551
+ }
1552
+ for (let d = folder; ; d = dirname(d)) {
1553
+ for (const f of [join(d, '.mcp.json'), join(d, '.grok', 'config.toml'), join(d, '.cursor', 'mcp.json')]) if (defines(f)) return f
1554
+ if (existsSync(join(d, '.git')) || dirname(d) === d || withinById(HOME, d) && withinById(d, HOME)) return null
1555
+ }
1556
+ }
1557
+
1558
+ function grokCommand(s, prep, env, dir) {
1559
+ const planted = grokProjectPisha(s.folder)
1560
+ if (planted) throw new Error(`${planted} defines an MCP server named "pisha": Grok CLI would run it instead of the Pisha plugin. Remove it from that file to open Grok sessions in this folder`)
1561
+ // (Grok keeps each conversation in <home>/sessions/<folder>/<id>/updates.jsonl.)
1562
+ const conversation = typedConversation(s, dir, (id, t) => t.endsWith(`${sep}${id}${sep}updates.jsonl`) && within(t, join(grokHome(), 'sessions')))
1563
+ const argv = [prep.program, '--allow', 'MCPTool(pisha__*)', ...(conversation ? ['--resume', conversation] : [])]
1564
+ // (The persona as rules added to its system prompt.)
1565
+ return personaArg(s, dir, argv, '--rules', text => text)
1566
+ }
1567
+
1568
+ // The screen of a session (its last lines).
1569
+ const screenOf = async target => (await tmux(['capture-pane', '-p', '-J', '-t', target])).stdout.split('\n').filter(l => l.trim()).slice(-24).join('\n')
1570
+
1571
+ // Text pasted in a session's input, then sent: as a paste, so its lines stay
1572
+ // one message (Codex and Grok take bracketed paste).
1573
+ async function pasteAndSend(target, text) {
1574
+ const buffer = `sq-${randomBytes(6).toString('hex')}`
1575
+ ensurePrivateDir(join(CONFIG_DIR, 'paste'))
1576
+ const file = join(CONFIG_DIR, 'paste', `${buffer}.txt`)
1577
+ writeFileSync(file, text, { mode: 0o600, flag: 'wx' })
1578
+ try {
1579
+ await tmux(['load-buffer', '-b', buffer, file])
1580
+ await tmux(['paste-buffer', '-p', '-d', '-b', buffer, '-t', target])
1581
+ } finally { rmSync(file, { force: true }) }
1582
+ await new Promise(r => setTimeout(r, 500))
1583
+ await tmux(['send-keys', '-t', target, 'Enter'])
1584
+ }
1585
+
1586
+ // What the plugin left for the terminal (see plugins/pisha/typed), typed
1587
+ // when the agent waits for input. Oldest first, a few at a time.
1588
+ const PENDING_RE = /^\d{14}-\d{6}-\d+\.txt$/
1589
+ const typingNow = new Set()
1590
+ async function typeWaiting(t, a) {
1591
+ if (typingNow.has(t.id)) return
1592
+ typingNow.add(t.id)
1593
+ try {
1594
+ const target = `=${PREFIX}${t.id}:`
1595
+ await typePermissionAnswers(t, a, target)
1596
+ const dir = join(claudeCode.plugin.stateDir(t.id), 'pending-input')
1597
+ let files
1598
+ try { files = readdirSync(dir).filter(f => PENDING_RE.test(f)).sort().slice(0, 10) } catch { return }
1599
+ if (!files.length) return
1600
+ if (!a.waiting(await screenOf(target))) return
1601
+ const parts = []
1602
+ for (const f of files) {
1603
+ // (A session can write there: only small plain files are read.)
1604
+ try { const st = lstatSync(join(dir, f)); if (st.isFile() && st.size <= 64 * 1024) parts.push(readFileSync(join(dir, f), 'utf8').trim()) } catch {}
1605
+ }
1606
+ const text = parts.filter(Boolean).join('\n\n')
1607
+ if (text) await pasteAndSend(target, text)
1608
+ for (const f of files) rmSync(join(dir, f), { force: true })
1609
+ if (text) log(`typed ${files.length} Pisha message${files.length === 1 ? '' : 's'} in "${plain(t.id)}" (${a.name})`)
1610
+ } catch (err) {
1611
+ log(`could not type the messages of "${plain(t.id)}": ${err.message}`)
1612
+ } finally { typingNow.delete(t.id) }
1613
+ }
1614
+
1615
+ // Answers to permission prompts (see plugins/pisha/typed): typed when the
1616
+ // prompt on screen shows the very call they answer, never otherwise. Dropped
1617
+ // after two minutes (it was answered in the terminal, or never came).
1618
+ const ANSWER_RE = /^\d{14}-[a-km-z]{5}\.json$/
1619
+ const ANSWER_KEEP_MS = 2 * 60_000
1620
+ async function typePermissionAnswers(t, a, target) {
1621
+ const dir = join(claudeCode.plugin.stateDir(t.id), 'permission-answers')
1622
+ let files
1623
+ try { files = readdirSync(dir).filter(f => ANSWER_RE.test(f)).sort().slice(0, 5) } catch { return }
1624
+ for (const f of files) {
1625
+ const file = join(dir, f)
1626
+ let ans = null
1627
+ // (A session can write there: only small plain files are read.)
1628
+ try { const st = lstatSync(file); if (st.isFile() && st.size <= 64 * 1024) ans = JSON.parse(readFileSync(file, 'utf8')) } catch {}
1629
+ const age = Date.now() - Number(f.slice(0, 14))
1630
+ const keys = ans && typeof ans === 'object' && age <= ANSWER_KEEP_MS && age >= -60_000 ? a.permissionKeys(await screenOf(target), ans) : null
1631
+ if (!keys) {
1632
+ // (Its prompt may still come: an agent asks for calls it makes together
1633
+ // one after another. Only that exact call is ever answered.)
1634
+ if (ans && typeof ans === 'object' && age <= ANSWER_KEEP_MS && age >= -60_000) continue
1635
+ rmSync(file, { force: true })
1636
+ if (ans) log(`the answer to the permission prompt ${f.slice(15, 20)} of "${plain(t.id)}" was not typed: its prompt is not on the screen, or shows its call over several lines (answer it there)`)
1637
+ continue
1638
+ }
1639
+ for (const k of keys) await tmux(['send-keys', '-t', target, k])
1640
+ rmSync(file, { force: true })
1641
+ log(`typed "${ans.behavior === 'allow' ? 'yes' : 'no'}" to the permission prompt ${f.slice(15, 20)} of "${plain(t.id)}" (${a.name})`)
1642
+ }
1643
+ }
1644
+
1645
+ // Whether the prompt's own call line shows exactly the call an answer is for:
1646
+ // the whole command, or the file it changes, spaces included (only blanks at
1647
+ // the ends aside). Never the reason or description around it, which the agent
1648
+ // writes. A call over several lines (its own, or the terminal's wrapping) is
1649
+ // never matched: "./build/*" and "./build/ *" could look the same wrapped.
1650
+ function promptShows(callLines, ans) {
1651
+ const i = ans.input && typeof ans.input === 'object' ? ans.input : {}
1652
+ const what = typeof i.command === 'string' ? i.command : [i.file_path, i.path, i.notebook_path].find(v => typeof v === 'string')
1653
+ if (typeof what !== 'string' || !what.trim() || /[\r\n]/.test(what) || callLines.length !== 1) return false
1654
+ return callLines[0].trim() === what.trim()
1655
+ }
1656
+
1657
+ // The keys that answer the prompt on screen, if it is the one asked about.
1658
+ // Codex: "Would you like to run …?" with the call on its "$ " line (y: yes;
1659
+ // Esc: no). Grok: numbered options in a box, the call on its "│" lines (the
1660
+ // number picks and confirms).
1661
+ export function codexPermissionKeys(screen, ans) {
1662
+ const at = screen.lastIndexOf('Would you like to')
1663
+ if (at < 0 || !/Press enter to confirm/i.test(screen.slice(at))) return null
1664
+ const lines = screen.slice(at).split('\n')
1665
+ const start = lines.findIndex(l => /^\s*\$ /.test(l))
1666
+ if (start < 0) return null
1667
+ const end = lines.findIndex((l, k) => k > start && /^\s*›?\s*\d+\. /.test(l))
1668
+ if (end < 0) return null
1669
+ const call = lines.slice(start, end).map((l, k) => k === 0 ? l.replace(/^\s*\$ /, '') : l)
1670
+ if (!promptShows(call, ans)) return null
1671
+ return ans.behavior === 'allow' ? ['y'] : ['Escape']
1672
+ }
1673
+ export function grokPermissionKeys(screen, ans) {
1674
+ const box = screen.split('\n').filter(l => /^\s*┃/.test(l))
1675
+ const text = box.join('\n')
1676
+ const yes = /(\d) \([○●]\) Yes, proceed/.exec(text), no = /(\d) \([○●]\) No, reject/.exec(text)
1677
+ const call = box.filter(l => /^\s*┃\s*│ /.test(l)).map(l => l.replace(/^\s*┃\s*│ /, ''))
1678
+ if (!yes || !no || !promptShows(call, ans)) return null
1679
+ return [ans.behavior === 'allow' ? yes[1] : no[1]]
1680
+ }
1681
+
1682
+ // When each one waits for input: its input box shows, it isn't working, and
1683
+ // it isn't asking anything (a menu, a permission, a trust question).
1684
+ const codexWaiting = screen => /^\s*›/m.test(screen) && !/esc to interrupt/i.test(screen) &&
1685
+ !/enter to submit|enter confirm|esc to cancel|Hooks need review|\(y\/n\)|press enter/i.test(screen)
1686
+ const grokWaiting = screen => /│ ❯/.test(screen) && !/\[stop\]|Ctrl\+c:cancel|Waiting for response/i.test(screen) &&
1687
+ !/Tab:next option|\d+\/\d+:select|Do you trust|Yes, proceed|\(y\/n\)/i.test(screen)
1688
+
1689
+ // A line typed in a session (an answer from the user's inbox, /clear), as the user would.
1690
+ async function typeTypedLine(a, target, line) {
1691
+ if (!a.waiting(await screenOf(target))) throw new Error('it is busy or waiting for an answer on its screen')
1692
+ await tmux(['send-keys', '-t', target, '-l', line])
1693
+ await new Promise(r => setTimeout(r, 300))
1694
+ await tmux(['send-keys', '-t', target, 'Enter'])
1695
+ }
1696
+ function typedAnswer(a) {
1697
+ return (target, text) => {
1698
+ const line = String(text).replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/\s+/g, ' ').trim()
1699
+ if (!line || line.length > 2200) throw new Error('the answer must be one line of up to 2200 characters')
1700
+ return typeTypedLine(a, target, line)
1701
+ }
1702
+ }
1703
+
1704
+ const codexCli = {
1705
+ id: 'codex',
1706
+ name: 'Codex CLI',
1707
+ command: settings => settings.codex_command,
1708
+ program: () => typedProgram(loadSettings().codex_command),
1709
+ version: typedVersion,
1710
+ prepare: s => prepareTyped(codexCli, s),
1711
+ sessionCommand: codexCommand,
1712
+ waiting: codexWaiting,
1713
+ waitingNow: async target => codexWaiting(await screenOf(target)),
1714
+ permissionKeys: codexPermissionKeys,
1715
+ typeWaiting: t => typeWaiting(t, codexCli),
1716
+ typeAnswer: null,
1717
+ plugin: { status: codexPluginStatus, ensure: ensureCodexPlugin, commands: `codex plugin marketplace add ${TYPED_REPO} --ref v${VERSION} && codex plugin add pisha@pisha` },
1718
+ }
1719
+ codexCli.typeAnswer = typedAnswer(codexCli)
1720
+
1721
+ const grokCli = {
1722
+ id: 'grok',
1723
+ name: 'Grok CLI',
1724
+ command: settings => settings.grok_command,
1725
+ program: () => typedProgram(loadSettings().grok_command),
1726
+ version: typedVersion,
1727
+ prepare: s => prepareTyped(grokCli, s),
1728
+ sessionCommand: grokCommand,
1729
+ waiting: grokWaiting,
1730
+ waitingNow: async target => grokWaiting(await screenOf(target)),
1731
+ permissionKeys: grokPermissionKeys,
1732
+ typeWaiting: t => typeWaiting(t, grokCli),
1733
+ typeAnswer: null,
1734
+ plugin: { status: grokPluginStatus, ensure: ensureGrokPlugin, commands: `grok plugin install ${TYPED_REPO}@v${VERSION}#plugins/pisha --trust` },
1735
+ }
1736
+ grokCli.typeAnswer = typedAnswer(grokCli)
1737
+
1738
+ // The agents a session can run besides Claude Code, by id.
1739
+ const TYPED = { codex: codexCli, grok: grokCli }
1740
+
1741
+ // --- opening and closing sessions -----------------------------------------------------
1742
+
1743
+ // A private file in a private folder, never through a symlink: written to a
1744
+ // new temporary file, then renamed over the old one (a rename replaces a
1745
+ // symlink itself, it doesn't write where it points).
1746
+ function ensurePrivateDir(dir) {
1747
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
1748
+ const st = lstatSync(dir)
1749
+ if (!st.isDirectory() || st.isSymbolicLink()) throw new Error(`${dir} is not a plain folder`)
1750
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) throw new Error(`${dir} belongs to another user`)
1751
+ }
1752
+ // Images pasted in the dashboard's terminal: saved here (kept a day), and
1753
+ // their path pasted into Claude Code, which attaches an image file whose
1754
+ // path is pasted (as when one is dragged into a terminal).
1755
+ const PASTE_DIR = join(CONFIG_DIR, 'pasted')
1756
+ const IMAGE_TYPES = {
1757
+ 'image/png': ['png', b => b[0] === 0x89 && b.toString('latin1', 1, 4) === 'PNG'],
1758
+ 'image/jpeg': ['jpg', b => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff],
1759
+ 'image/gif': ['gif', b => b.toString('latin1', 0, 4) === 'GIF8'],
1760
+ 'image/webp': ['webp', b => b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP'],
1761
+ }
1762
+ function savePastedImage(term, type, data) {
1763
+ const kind = typeof type === 'string' && Object.hasOwn(IMAGE_TYPES, type) ? IMAGE_TYPES[type] : null
1764
+ if (!kind || typeof data !== 'string' || data.length > 800_000 || !/^[A-Za-z0-9+/]*={0,2}$/.test(data)) return null
1765
+ const buf = Buffer.from(data, 'base64')
1766
+ if (buf.length < 12 || buf.length > 600_000 || !kind[1](buf)) return null
1767
+ ensurePrivateDir(PASTE_DIR)
1768
+ try {
1769
+ for (const f of readdirSync(PASTE_DIR)) {
1770
+ const p = join(PASTE_DIR, f)
1771
+ try { const st = lstatSync(p); if (st.isFile() && Date.now() - st.mtimeMs > 86_400_000) rmSync(p, { force: true }) } catch {}
1772
+ }
1773
+ } catch {}
1774
+ const file = join(PASTE_DIR, `${term}-${Date.now()}-${randomBytes(4).toString('hex')}.${kind[0]}`)
1775
+ writeFileSync(file, buf, { mode: 0o600, flag: 'wx' })
1776
+ return file
1777
+ }
1778
+
1779
+ function writePrivate(dir, file, data) {
1780
+ ensurePrivateDir(dir)
1781
+ const tmp = join(dir, `.${file}.${process.pid}.${Date.now()}`)
1782
+ writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
1783
+ renameSync(tmp, join(dir, file))
1784
+ }
1785
+
1786
+ // One open at a time: the session limit is checked against what is running,
1787
+ // so concurrent requests must not all pass the same check.
1788
+ let openQueue = Promise.resolve()
1789
+ let openPending = 0
1790
+ function openTerminal(spec) {
1791
+ // At most a few waiting: a server can't pile up requests (and their specs) here.
1792
+ if (openPending >= 3) return Promise.reject(new Error('this machine is busy opening sessions; try again'))
1793
+ openPending++
1794
+ const run = openQueue.then(() => openTerminalNow(spec)).finally(() => { openPending-- })
1795
+ openQueue = run.catch(() => {})
1796
+ return run
1797
+ }
1798
+
1799
+ async function openTerminalNow(spec) {
1800
+ const settings = loadSettings()
1801
+ const s = validateSpec(spec, settings, await listTerminals())
1802
+ // Codex CLI or Grok CLI (see their section), or Claude Code.
1803
+ const typed = s.agent === 'claude' ? null : TYPED[s.agent]
1804
+ const claude = typed ? await typed.prepare(s) : await claudeCode.prepareSession(s, settings)
1805
+ // Where the plugin keeps this name's state: its launch file (role and
1806
+ // coordinator, read instead of environment variables) and, when the server
1807
+ // reserved the name for this machine, its identity.
1808
+ const dir = claudeCode.plugin.stateDir(s.name)
1809
+ writeLaunch(s, settings, dir, typed)
1810
+ // (Its links, kept while it runs: the dashboard can change them, see "links".)
1811
+ if (s.role === 'coordinator') writePrivate(dir, 'links.json', { name: s.name, coordinators: s.links })
1812
+ else rmSync(join(dir, 'links.json'), { force: true })
1813
+ // If anything below fails, no ticket (launch.json) is left for a later start.
1814
+ try { return await startSession(s, settings, claude, dir, typed) } catch (err) {
1815
+ rmSync(join(dir, 'launch.json'), { force: true })
1816
+ throw err
1817
+ }
1818
+ }
1819
+
1820
+ // The ticket the plugin reads at this start (launch.json): role, coordinator,
1821
+ // persona, agent, valid only for the start it names.
1822
+ function writeLaunch(s, settings, dir, typed) {
1823
+ // (A session in the home folder reaches everything of this user: its
1824
+ // permission prompts are answered only in its own terminal.)
1825
+ const relay = settings.permission_relay && !s.home && s.role !== 'solo'
1826
+ // (The plugin tells the session's squad which persona it follows.)
1827
+ const persona = s.personaInfo ? { kind: s.personaInfo.kind, name: s.personaInfo.name, description: s.personaInfo.description } : null
1828
+ s.launchStart = randomBytes(16).toString('hex')
1829
+ writePrivate(dir, 'launch.json', { name: s.name, role: s.role, coordinator: s.coordinator, start: s.launchStart, ...(relay ? {} : { permission_relay: false }), ...(persona ? { persona } : {}), ...(typed ? { agent: s.agent } : {}) })
1830
+ }
1831
+
1832
+ // What a session's process starts with: its variables and its command.
1833
+ function launchCommand(s, settings, claude, dir, typed) {
1834
+ const env = { PISHA_NAME: s.name, PISHA_LAUNCH_START: s.launchStart, ...claudeCode.sessionEnv(s) }
1835
+ // (Always said: a session started again in its terminal keeps the variables
1836
+ // it was first opened with, unless they are given again.)
1837
+ env.PISHA_PERMISSION_RELAY = !settings.permission_relay || s.home || s.role === 'solo' ? 'off' : 'on'
1838
+ if (typed) env.PISHA_AGENT = s.agent
1839
+ // Fixed command. Two or more arguments make tmux exec it directly, no shell.
1840
+ // "env -u TMUX" hides the tmux server from the session: its tools can't
1841
+ // simply run "tmux send-keys" into another session. (They run as the same
1842
+ // user, so this is a speed bump, not a wall: see the README.)
1843
+ const argv = ['/usr/bin/env', '-u', 'TMUX', '-u', 'TMUX_PANE', ...(typed ? typed.sessionCommand(s, claude, env, dir) : claudeCode.sessionCommand(s, claude, dir, env))]
1844
+ return { env, argv, envArgs: Object.entries(env).flatMap(([k, v]) => ['-e', `${k}=${v}`]) }
1845
+ }
1846
+
1847
+ async function startSession(s, settings, claude, dir, typed) {
1848
+ if (s.identity) writePrivate(dir, 'identity.json', { name: s.name, secret: s.identity, server: claudeCode.plugin.serverUrl() })
1849
+ const tname = PREFIX + s.name
1850
+ const { argv, envArgs } = launchCommand(s, settings, claude, dir, typed)
1851
+ const meta = JSON.stringify({ owner: OWNER_TAG, role: s.role, coordinator: s.coordinator, folder: s.folder, compact_window: s.compact_window, persona: s.personaInfo ? { id: s.personaInfo.id, kind: s.personaInfo.kind, name: s.personaInfo.name } : null, ...(typed ? { agent: s.agent } : {}), ...(s.permissions ? { profile: s.permissions.profile } : {}) })
1852
+ await tmux([
1853
+ 'start-server', ';',
1854
+ 'set-option', '-g', 'history-limit', '10000', ';',
1855
+ 'set-option', '-g', 'exit-empty', 'off', ';',
1856
+ 'new-session', '-d', '-s', tname, '-x', '120', '-y', '36', '-c', s.folder,
1857
+ ...envArgs,
1858
+ ...argv, ';',
1859
+ 'set-option', '-t', `=${tname}:`, 'status', 'off', ';',
1860
+ 'set-option', '-t', `=${tname}:`, '@pisha', meta,
1861
+ ])
1862
+ await checkStartedWhere(tname, s, dir)
1863
+ log(`opened "${plain(s.name)}" (${s.role}${typed ? `, ${typed.name}` : ''}${s.personaInfo ? `, ${s.personaInfo.kind} "${plain(s.personaInfo.name)}"` : ''}${s.permissions ? `, permission profile "${plain(s.permissions.profile)}"` : ''}) in ${s.folder}`)
1864
+ if (s.permissions?.restricted) log(` what its profile allows was left out: this machine takes only what asks or forbids from the dashboard ("permissions_from_dashboard": "restrict")`)
1865
+ return { id: s.name, name: s.name }
1866
+ }
1867
+
1868
+ // A Codex CLI or Grok CLI session started again in its own terminal, with a
1869
+ // new conversation: that is how they are cleared. (Their /new and /clear start
1870
+ // a second plugin process while the first keeps the session's name.) The old
1871
+ // plugin exits with the agent and frees the name; the new one joins with a new
1872
+ // ticket, as at the first start.
1873
+ async function restartTyped(t, typed) {
1874
+ const settings = loadSettings()
1875
+ const tname = PREFIX + t.id
1876
+ if (!(await typed.waitingNow(`=${tname}:`))) throw new Error('it is busy or waiting for an answer on its screen')
1877
+ // Everything checked again, as when it was opened (the folder may have changed).
1878
+ const folder = checkFolder(t.folder, settings)
1879
+ const st = statSync(folder)
1880
+ const s = { name: t.id, role: t.role, coordinator: t.coordinator, folder, folderId: `${st.dev}:${st.ino}`, compact_window: t.compact_window, home: isHome(folder), agent: t.agent, resume: false, persona: t.persona?.id ?? null }
1881
+ const prep = await typed.prepare(s)
1882
+ const dir = claudeCode.plugin.stateDir(s.name)
1883
+ writeLaunch(s, settings, dir, typed)
1884
+ try {
1885
+ const { argv, envArgs } = launchCommand(s, settings, prep, dir, typed)
1886
+ await tmux(['respawn-pane', '-k', '-t', `=${tname}:`, '-c', s.folder, ...envArgs, ...argv])
1887
+ await checkStartedWhere(tname, s, dir)
1888
+ } catch (err) {
1889
+ rmSync(join(dir, 'launch.json'), { force: true })
1890
+ throw err
1891
+ }
1892
+ }
1893
+
1894
+ // The folder could have been swapped (e.g. for a symlink) between the check
1895
+ // and the start: make sure the session really is where it was allowed.
1896
+ // If that can't be checked, the session is closed too.
1897
+ async function checkStartedWhere(tname, s, dir) {
1898
+ // (Right after the start, until the command has really begun, tmux
1899
+ // reports its own folder: asked again for a few seconds.)
1900
+ let where = null, whereId = null
1901
+ for (let i = 0; i < 30; i++) {
1902
+ where = null; whereId = null
1903
+ try { where = realOr((await tmux(['display-message', '-p', '-t', `=${tname}:`, '#{pane_current_path}'])).stdout.replace(/\r?\n$/, '')) } catch {}
1904
+ try { const st = statSync(where); whereId = `${st.dev}:${st.ino}` } catch {}
1905
+ if (where === s.folder && whereId === s.folderId) break
1906
+ await new Promise(r => setTimeout(r, 100))
1907
+ }
1908
+ if (where !== s.folder || whereId !== s.folderId) {
1909
+ await tmux(['kill-session', '-t', `=${tname}`]).catch(() => {})
1910
+ rmSync(join(dir, 'launch.json'), { force: true }) // no ticket left for a later start
1911
+ throw new Error(where ? `the session started in ${where} instead of ${s.folder}; closed it` : 'could not check where the session started; closed it')
1912
+ }
1913
+ }
1914
+
1915
+ // The links of a coordinator running on this machine, changed from the
1916
+ // dashboard: its plugin reads links.json again (only a session this machine
1917
+ // started does).
1918
+ async function setLinks(name, coordinators) {
1919
+ if (!NAME_RE.test(String(name))) throw new Error('invalid session')
1920
+ const t = (await listTerminals()).find(x => x.id === name)
1921
+ if (!t) throw new Error('no such session on this machine')
1922
+ if (t.role !== 'coordinator') throw new Error('only a coordinator is linked with other squads')
1923
+ const links = checkLinks(coordinators, name, 'coordinator', loadSettings())
1924
+ writePrivate(claudeCode.plugin.stateDir(name), 'links.json', { name, coordinators: links })
1925
+ log(`links of "${plain(name)}": ${links.map(plain).join(', ') || '(none)'}`)
1926
+ return { name, links }
1927
+ }
1928
+
1929
+ // A worker the dashboard opened for a coordinator this machine started: its
1930
+ // plugin approves it as /pisha:access pair does, from a file left in its own
1931
+ // private folder (like links.json; only a session this machine started reads it).
1932
+ // identity: the registration of that worker the dashboard opened (the
1933
+ // coordinator pins it), when the server says.
1934
+ async function approveWorker(coordinator, worker, identity) {
1935
+ if (!NAME_RE.test(String(coordinator)) || !NAME_RE.test(String(worker)) || coordinator === worker) throw new Error('invalid session')
1936
+ if (identity != null && !(typeof identity === 'string' && /^[0-9a-f]{16,64}$/.test(identity))) throw new Error('invalid identity')
1937
+ const t = (await listTerminals()).find(x => x.id === coordinator)
1938
+ if (!t) throw new Error('no such session on this machine')
1939
+ if (t.role !== 'coordinator') throw new Error('only a coordinator approves workers')
1940
+ writePrivate(join(claudeCode.plugin.stateDir(coordinator), 'dashboard-approved'), worker, { worker, at: Date.now(), ...(identity ? { identity } : {}) })
1941
+ log(`"${plain(worker)}" approved for "${plain(coordinator)}" from the dashboard`)
1942
+ return { approved: worker }
1943
+ }
1944
+
1945
+ // The user answers from the dashboard a question its coordinator left in their
1946
+ // inbox: typed in that coordinator's terminal, as they would. It is typing from
1947
+ // the dashboard, so only if this machine allows that (allow_input).
1948
+ async function answerSession(id, text) {
1949
+ if (!NAME_RE.test(String(id))) throw new Error('invalid session')
1950
+ if (!loadSettings().allow_input) throw new Error('this machine does not let the dashboard type in its sessions ("allow_input": false in its settings.json)')
1951
+ const t = (await listTerminals()).find(x => x.id === id)
1952
+ if (!t) throw new Error('no such session on this machine')
1953
+ if (t.role !== 'coordinator') throw new Error(`"${id}" is not a coordinator`)
1954
+ await (TYPED[t.agent] ?? claudeCode).typeAnswer(`=${PREFIX}${id}:`, text)
1955
+ log(`typed an answer from the user's inbox in "${plain(id)}"`)
1956
+ return { typed: true }
1957
+ }
1958
+
1959
+ // /clear typed in a worker's terminal, as the user would, when its
1960
+ // coordinator gives it a new task unrelated to the last one (Claude can't
1961
+ // clear its own context). Only a worker this machine opened for that very
1962
+ // coordinator, and only if this machine allows it (allow_clear).
1963
+ async function clearSession(id, coordinator) {
1964
+ if (!NAME_RE.test(String(id)) || !NAME_RE.test(String(coordinator))) throw new Error('invalid session')
1965
+ if (!loadSettings().allow_clear) throw new Error('this machine does not let coordinators clear its sessions ("allow_clear": false in its settings.json)')
1966
+ const t = (await listTerminals()).find(x => x.id === id)
1967
+ if (!t) throw new Error('no such session on this machine')
1968
+ if (t.role !== 'worker' || t.coordinator !== coordinator) throw new Error(`"${id}" is not a worker of "${coordinator}" on this machine`)
1969
+ // (Codex CLI and Grok CLI: started again, see restartTyped. The server then
1970
+ // takes its new start as the confirmation.)
1971
+ if (TYPED[t.agent]) {
1972
+ await restartTyped(t, TYPED[t.agent])
1973
+ log(`started "${plain(id)}" again with a new conversation for its coordinator "${plain(coordinator)}"`)
1974
+ return { cleared: true, restarted: true }
1975
+ }
1976
+ await claudeCode.clearContext(`=${PREFIX}${id}:`)
1977
+ log(`cleared the context of "${plain(id)}" for its coordinator "${plain(coordinator)}"`)
1978
+ return { cleared: true }
1979
+ }
1980
+
1981
+ async function killTerminal(id) {
1982
+ if (!NAME_RE.test(String(id))) throw new Error('invalid session')
1983
+ const list = await listTerminals()
1984
+ if (!list.some(t => t.id === id)) throw new Error('no such session on this machine')
1985
+ await tmux(['kill-session', '-t', `=${PREFIX}${id}`]) // "=": exactly this name, never a prefix match
1986
+ try { rmSync(join(claudeCode.plugin.stateDir(id), 'launch.json'), { force: true }) } catch {} // if it never got to use it
1987
+ try { rmSync(join(claudeCode.plugin.stateDir(id), 'links.json'), { force: true }) } catch {}
1988
+ log(`closed "${id}"`)
1989
+ return true
1990
+ }
1991
+
1992
+ // --- live terminal: tmux control mode --------------------------------------------------
1993
+ //
1994
+ // While someone watches a session, a control-mode client is attached to it:
1995
+ // tmux reports everything the pane prints (%output) and takes keys and size
1996
+ // changes on stdin.
1997
+
1998
+ function decodeOutput(buf) {
1999
+ // Bytes below 0x20 and backslash come as \ooo (octal); everything else raw.
2000
+ const out = Buffer.alloc(buf.length)
2001
+ let n = 0
2002
+ for (let i = 0; i < buf.length; i++) {
2003
+ const c = buf[i]
2004
+ if (c === 0x5c && i + 3 < buf.length && buf[i + 1] >= 0x30 && buf[i + 1] <= 0x37) {
2005
+ out[n++] = ((buf[i + 1] - 48) << 6) | ((buf[i + 2] - 48) << 3) | (buf[i + 3] - 48)
2006
+ i += 3
2007
+ } else out[n++] = c
2008
+ }
2009
+ return out.subarray(0, n)
2010
+ }
2011
+
2012
+ // The biggest piece of terminal output sent in one message (the server takes
2013
+ // up to 8 MB per message; base64 adds a third).
2014
+ const SCREEN_MAX_BYTES = 1024 * 1024
2015
+
2016
+ // The pane's modes that tmux knows (its format, then what sets the mode on and
2017
+ // off in a terminal that was just reset), so the dashboard's terminal behaves
2018
+ // as the program asked: with Claude Code's full-screen view, the mouse wheel
2019
+ // goes to Claude Code instead of scrolling an empty buffer. The first one,
2020
+ // the alternate screen, goes before the screen is drawn.
2021
+ const MODE_FLAGS = [
2022
+ ['alternate_on'],
2023
+ ['mouse_standard_flag', '\x1b[?1000h', ''],
2024
+ ['mouse_button_flag', '\x1b[?1002h', ''],
2025
+ ['mouse_all_flag', '\x1b[?1003h', ''],
2026
+ ['mouse_sgr_flag', '\x1b[?1006h', ''],
2027
+ ['mouse_utf8_flag', '\x1b[?1005h', ''],
2028
+ ['keypad_cursor_flag', '\x1b[?1h', ''],
2029
+ ['keypad_flag', '\x1b=', ''],
2030
+ ['cursor_flag', '', '\x1b[?25l'],
2031
+ ]
2032
+ // tmux doesn't say whether the program asked for bracketed paste. Claude Code
2033
+ // always does, and without it a text of several lines pasted in the dashboard
2034
+ // would reach it one line (one Enter) at a time.
2035
+ const PASTE_MODE = '\x1b[?2004h'
2036
+
2037
+ class Viewer {
2038
+ constructor(id, send, congested = () => false) {
2039
+ // congested(): the connection to the server isn't keeping up (it stopped
2040
+ // reading): output is dropped and a fresh screen sent once it drains.
2041
+ this.congested = congested
2042
+ this.id = id
2043
+ this.send = send
2044
+ this.tname = PREFIX + id
2045
+ this.ready = false
2046
+ this.held = [] // output that arrives while a screen snapshot is being taken
2047
+ this.cols = 120
2048
+ this.rows = 36
2049
+ // Read-only (-r) when this machine doesn't allow typing from the dashboard.
2050
+ // (A control-mode client can still send commands: what really stops
2051
+ // typing is the allow_input check on every message, in connect().)
2052
+ const ro = loadSettings().allow_input ? [] : ['-r']
2053
+ this.proc = spawn(tmuxBin(), ['-u', '-L', TMUX_SOCKET, '-f', '/dev/null', '-C', 'attach-session', ...ro, '-t', `=${this.tname}`], { env: tmuxEnv(), stdio: ['pipe', 'pipe', 'ignore'], cwd: HOME })
2054
+ this.proc.on('error', err => { log(`terminal of "${id}": ${err.message}`); this.closed = true; this.onExit?.() })
2055
+ this.proc.stdin.on('error', () => {})
2056
+ let pending = Buffer.alloc(0)
2057
+ this.proc.stdout.on('data', chunk => {
2058
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk
2059
+ let i
2060
+ while ((i = pending.indexOf(0x0a)) >= 0) {
2061
+ const line = pending.subarray(0, i)
2062
+ pending = pending.subarray(i + 1)
2063
+ this.onLine(line)
2064
+ }
2065
+ })
2066
+ this.proc.on('exit', () => { this.closed = true; this.onExit?.() })
2067
+ }
2068
+
2069
+ onLine(line) {
2070
+ if (line.subarray(0, 8).toString('latin1') === '%output ') {
2071
+ const sp = line.indexOf(0x20, 8)
2072
+ if (sp < 0) return
2073
+ const data = decodeOutput(line.subarray(sp + 1))
2074
+ if (!data.length) return
2075
+ if (!this.ready) {
2076
+ // Kept while a screen is captured: at most SCREEN_MAX_BYTES, the oldest goes first.
2077
+ this.held.push(data)
2078
+ this.heldBytes = (this.heldBytes ?? 0) + data.length
2079
+ while (this.heldBytes > SCREEN_MAX_BYTES && this.held.length > 1) this.heldBytes -= this.held.shift().length
2080
+ return
2081
+ }
2082
+ if (this.congested()) { this.stale = true; return }
2083
+ if (this.stale) { this.stale = false; void this.screen().catch(() => {}); return }
2084
+ this.send({ t: 'out', term: this.id, data: data.toString('base64') })
2085
+ } else if (line.subarray(0, 5).toString('latin1') === '%exit') {
2086
+ this.proc.stdin.end()
2087
+ }
2088
+ }
2089
+
2090
+ command(cmd) {
2091
+ if (!this.closed) this.proc.stdin.write(cmd + '\n')
2092
+ }
2093
+
2094
+ resize(cols, rows) {
2095
+ // Without typing allowed, the dashboard can't resize the session either
2096
+ // (it would shrink it for whoever uses it on this machine).
2097
+ if (!loadSettings().allow_input) return
2098
+ cols = Math.floor(Math.max(20, Math.min(Number(cols) || 120, 500)))
2099
+ rows = Math.floor(Math.max(5, Math.min(Number(rows) || 36, 200)))
2100
+ this.cols = cols; this.rows = rows
2101
+ this.command(`refresh-client -C ${cols}x${rows}`)
2102
+ }
2103
+
2104
+ input(text) {
2105
+ const bytes = Buffer.from(String(text), 'utf8')
2106
+ for (let i = 0; i < bytes.length; i += 256) {
2107
+ const hex = [...bytes.subarray(i, i + 256)].map(b => b.toString(16).padStart(2, '0')).join(' ')
2108
+ this.command(`send-keys -t =${this.tname}: -H ${hex}`)
2109
+ }
2110
+ }
2111
+
2112
+ // The current screen (plus some scrollback), redrawn from scratch.
2113
+ async screen() {
2114
+ // At most one capture a second per terminal (each one runs two tmux processes).
2115
+ const wait = 1000 - (Date.now() - (this.lastScreen ?? 0))
2116
+ if (wait > 0) {
2117
+ if (this.screenTimer) return
2118
+ this.screenTimer = setTimeout(() => { this.screenTimer = null; if (!this.closed) void this.screen().catch(() => {}) }, wait)
2119
+ this.screenTimer.unref?.()
2120
+ return
2121
+ }
2122
+ this.lastScreen = Date.now()
2123
+ this.ready = false
2124
+ await new Promise(r => setTimeout(r, 120)) // let the program redraw at the new size
2125
+ this.held = [] // what came before the capture is in it; what comes during it is sent after
2126
+ this.heldBytes = 0
2127
+ try {
2128
+ const { stdout: info } = await tmux(['display-message', '-p', '-t', `=${this.tname}:`, `#{history_size} #{pane_height} #{cursor_x} #{cursor_y} ${MODE_FLAGS.map(([f]) => `#{${f}}`).join(' ')}`])
2129
+ const [hist, height, cx, cy, ...flags] = info.trim().split(' ').map(Number)
2130
+ const back = Math.min(hist, 1000)
2131
+ const { stdout } = await tmux(['capture-pane', '-p', '-e', '-t', `=${this.tname}:`, '-S', String(-back), '-E', String(height - 1)], { encoding: 'buffer' })
2132
+ let lines = stdout.toString('utf8').split('\n')
2133
+ if (lines.at(-1) === '') lines.pop()
2134
+ // At most SCREEN_MAX_BYTES (very colourful output can be huge): the
2135
+ // oldest scrollback lines go first.
2136
+ let size = lines.reduce((n, l) => n + Buffer.byteLength(l) + 6, 0)
2137
+ let start = 0
2138
+ while (size > SCREEN_MAX_BYTES && start < lines.length - 1) size -= Buffer.byteLength(lines[start++]) + 6
2139
+ lines = lines.slice(start).map(l => (Buffer.byteLength(l) > SCREEN_MAX_BYTES ? Buffer.from(l).subarray(0, SCREEN_MAX_BYTES).toString('utf8') : l))
2140
+ // (The dashboard resets its terminal before drawing this: the program's
2141
+ // modes go too, so they are set again after it.)
2142
+ const alt = flags[0] === 1
2143
+ const modes = MODE_FLAGS.slice(1).map(([, on, off], i) => (flags[i + 1] === 1 ? on : off)).join('')
2144
+ const data = (alt ? '\x1b[?1049h' : '') + '\x1b[0m\x1b[H\x1b[2J\x1b[3J' + lines.join('\x1b[0m\r\n') + `\x1b[${cy + 1};${cx + 1}H` + modes + PASTE_MODE
2145
+ if (this.congested()) this.stale = true
2146
+ else this.send({ t: 'screen', term: this.id, data: Buffer.from(data, 'utf8').toString('base64'), cols: this.cols, rows: this.rows })
2147
+ } finally {
2148
+ const held = Buffer.concat(this.held)
2149
+ this.held = []
2150
+ this.heldBytes = 0
2151
+ if (!this.stale) for (let i = 0; i < held.length; i += SCREEN_MAX_BYTES) this.send({ t: 'out', term: this.id, data: held.subarray(i, i + SCREEN_MAX_BYTES).toString('base64') })
2152
+ this.ready = true
2153
+ }
2154
+ }
2155
+
2156
+ close() {
2157
+ if (this.closed) return
2158
+ this.command('detach-client')
2159
+ setTimeout(() => this.proc.kill(), 500).unref()
2160
+ }
2161
+ }
2162
+
2163
+ // --- connection to the server ------------------------------------------------------------
2164
+
2165
+ function wsUrl(server) {
2166
+ const u = new URL(server)
2167
+ u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:'
2168
+ u.pathname = u.pathname.replace(/\/+$/, '') + '/host/connect'
2169
+ return u.toString()
2170
+ }
2171
+
2172
+ // Which machine this is, for showing the copies on it together: never for
2173
+ // deciding anything, since it is only this program's word.
2174
+ let MACHINE = null
2175
+ function machineId() {
2176
+ if (MACHINE) return MACHINE
2177
+ let id = ''
2178
+ for (const f of ['/etc/machine-id', '/var/lib/dbus/machine-id']) { try { id ||= readFileSync(f, 'utf8').trim() } catch {} }
2179
+ if (!id && platform() === 'darwin') {
2180
+ try { id = /"IOPlatformUUID" = "([^"]+)"/.exec(execFileSync('/usr/sbin/ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice'], { encoding: 'utf8', timeout: 5000 }))?.[1] ?? '' } catch {}
2181
+ }
2182
+ MACHINE = createHash('sha256').update(`pisha-machine|${id || hostname()}`).digest('hex').slice(0, 32)
2183
+ return MACHINE
2184
+ }
2185
+
2186
+ async function hostInfo() {
2187
+ const settings = loadSettings()
2188
+ const tv = await tmuxVersion()
2189
+ return {
2190
+ hostname: hostname(),
2191
+ machine: machineId(),
2192
+ os_user: (() => { try { return userInfo().username } catch { return null } })(),
2193
+ // Another company runs here under this same system user: apart for accidents only.
2194
+ shares_user: sharesUser(),
2195
+ platform: platform(),
2196
+ arch: arch(),
2197
+ node: process.version,
2198
+ tmux: tv?.text ?? null,
2199
+ claude: CLAUDE_VERSION,
2200
+ // The agents sessions can run here, each with its version.
2201
+ agents: [...(CLAUDE_VERSION ? [{ id: 'claude', version: CLAUDE_VERSION }] : []), ...Object.entries(TYPED_VERSIONS).filter(([, v]) => v).map(([id, version]) => ({ id, version }))],
2202
+ plugin: PLUGIN,
2203
+ version: VERSION,
2204
+ folders: settings.folders,
2205
+ // Which of them is the home folder (allowed only with --allow-home), and
2206
+ // whether the dashboard may change them.
2207
+ home: settings.allow_home ? HOME : null,
2208
+ folders_from_dashboard: settings.folders_from_dashboard,
2209
+ max_sessions: settings.max_sessions,
2210
+ allow_input: settings.allow_input,
2211
+ // (Whether a session may be opened again continuing its conversation.)
2212
+ allow_resume: settings.allow_resume,
2213
+ // (It types answers from the user's inbox: older copies don't.)
2214
+ answers: true,
2215
+ // How far it takes permission profiles from the dashboard.
2216
+ permission_profiles: settings.permissions_from_dashboard,
2217
+ terminals: await listTerminals(),
2218
+ }
2219
+ }
2220
+
2221
+ let PLUGIN = null // { installed, version, enabled }, or null when it can't be told
2222
+
2223
+ // Every second, the messages waiting for the Codex and Grok sessions (only on
2224
+ // a machine that has one of them).
2225
+ let typePendingBusy = false
2226
+ async function typePending() {
2227
+ if (typePendingBusy || !Object.values(TYPED_VERSIONS).some(Boolean)) return
2228
+ typePendingBusy = true
2229
+ try {
2230
+ for (const t of await listTerminals()) if (TYPED[t.agent]) await TYPED[t.agent].typeWaiting(t)
2231
+ } catch {} finally { typePendingBusy = false }
2232
+ }
2233
+ let CLAUDE_VERSION = null
2234
+ // Codex CLI's and Grok CLI's versions (null: not on this machine).
2235
+ const TYPED_VERSIONS = { codex: null, grok: null }
2236
+ async function readTypedVersions() {
2237
+ for (const [id, a] of Object.entries(TYPED)) { const p = a.program(); TYPED_VERSIONS[id] = p ? await a.version(p) : null }
2238
+ }
2239
+
2240
+ let CREDS_SERVER = null // the server this machine is enrolled with
2241
+ async function connect(creds) {
2242
+ CREDS_SERVER = creds.server
2243
+ const viewers = new Map() // terminal id -> Viewer
2244
+ const reattaches = new Map() // terminal id -> recent automatic re-attaches
2245
+ let ws = null
2246
+ let link = null // the encrypted link with the server (see openLink)
2247
+ let backoff = 1000
2248
+ let connectedAt = 0
2249
+ let termMsgs = []
2250
+ const TERM_MSG_MAX = 300
2251
+ // The session list for a burst of attaches: one tmux call a second at most.
2252
+ let termCache = null
2253
+ const listTerminalsCached = async () => {
2254
+ if (!termCache || Date.now() - termCache.at > 1000) termCache = { at: Date.now(), list: listTerminals() }
2255
+ return termCache.list
2256
+ }
2257
+ let lastTerminals = ''
2258
+
2259
+ // A server that stops reading can't make this program hold its replies
2260
+ // forever: past 16 MB waiting, the connection is dropped (and made again).
2261
+ const send = msg => {
2262
+ if (ws?.readyState !== 1) return
2263
+ if (ws.bufferedAmount > 16 * 1024 * 1024) return dropConnection('the server is not reading')
2264
+ const text = JSON.stringify(msg)
2265
+ ws.send(link ? link.seal(text) : text)
2266
+ }
2267
+ // Give up on this connection and reconnect: closed, and the loop moves on
2268
+ // even if the close never completes (a server that stopped reading).
2269
+ let settleNow = null
2270
+ let diagnosed = false // (reset once connected)
2271
+ let lastFromServer = Date.now()
2272
+ const dropConnection = reason => {
2273
+ try { ws?.close(4008, String(reason).slice(0, 100)) } catch {}
2274
+ const settle = settleNow
2275
+ setTimeout(() => settle?.({ code: 0, reason }), 2000).unref()
2276
+ }
2277
+ // The server answers every ping (25 s): nothing from it for 90 s means it
2278
+ // silently went away (network change, sleep, a stalled proxy).
2279
+ // And a handshake that gets no answer in 30 to 45 s (looked at every 15) is
2280
+ // given up (the socket's own wait is 300 s, one more left hanging per retry):
2281
+ // its handlers go first, so closing it can't fire them, and a late open just
2282
+ // closes it. Node 22 doesn't let go of such a socket, not even after those
2283
+ // 300 s: after many of them this program ends with an error (the sessions
2284
+ // stay). Soon with a service, which starts it again; without one, only before
2285
+ // it runs out of files, which would end it anyway.
2286
+ let abandoned = 0
2287
+ setInterval(() => {
2288
+ if (ws?.readyState === 1 && Date.now() - lastFromServer > 90_000) dropConnection('nothing from the server for 90 seconds')
2289
+ if (ws?.readyState === 0 && settleNow && Date.now() - lastFromServer > 30_000) {
2290
+ const sock = ws, settle = settleNow
2291
+ sock.onmessage = sock.onerror = sock.onclose = null
2292
+ sock.onopen = () => { try { sock.close(1000) } catch {} }
2293
+ try { sock.close() } catch {}
2294
+ if (++abandoned >= (UNDER_SERVICE ? 20 : 500)) die(`${abandoned} connections to the server were never answered: starting again to let go of them`, 1)
2295
+ settle({ code: 0, reason: 'the server did not answer the connection in 30 seconds' })
2296
+ }
2297
+ }, 15_000).unref()
2298
+
2299
+ // One at a time: overlapping calls share the one running (plus one more
2300
+ // after it), so nothing can make it start many tmux processes at once.
2301
+ let infoRunning = null, infoAgain = false, infoForce = false
2302
+ const pushInfo = (force = false) => {
2303
+ infoForce ||= force
2304
+ if (infoRunning) { infoAgain = true; return infoRunning }
2305
+ infoRunning = (async () => {
2306
+ try {
2307
+ do { infoAgain = false; const f = infoForce; infoForce = false; await pushInfoNow(f) } while (infoAgain)
2308
+ } finally { infoRunning = null }
2309
+ })()
2310
+ return infoRunning
2311
+ }
2312
+ const pushInfoNow = async (force = false) => {
2313
+ const info = await hostInfo()
2314
+ const key = JSON.stringify(info)
2315
+ if (force || key !== lastTerminals) { lastTerminals = key; send({ t: 'info', info }) }
2316
+ // Viewers of sessions that ended.
2317
+ for (const [id, v] of viewers) if (!info.terminals.some(t => t.id === id)) { v.close(); viewers.delete(id); send({ t: 'exit', term: id }) }
2318
+ }
2319
+
2320
+ const handlers = {
2321
+ // Push the info either way: a refusal may have found the plugin missing.
2322
+ async open(m) { try { return await openTerminal(m.spec) } finally { await pushInfo() } },
2323
+ async kill(m) { const r = await killTerminal(m.term); await pushInfo(); return r },
2324
+ // The skills and agents a session opened in this folder could follow.
2325
+ async personas(m) { return { personas: claudeCode.personas(checkFolder(m.folder, loadSettings())) } },
2326
+ // The dashboard linked or unlinked a coordinator running here.
2327
+ async links(m) { return setLinks(m.name, m.coordinators) },
2328
+ // A worker's coordinator wants it to start its next task from a clean context.
2329
+ async clear(m) { return clearSession(m.term, m.coordinator) },
2330
+ // The user answered from their inbox a question this coordinator asked.
2331
+ async answer(m) { return answerSession(m.term, m.text) },
2332
+ // A worker opened from the dashboard for a coordinator running here.
2333
+ async approve(m) { return approveWorker(m.term, m.worker, m.identity) },
2334
+ // The dashboard adds or removes an allowed folder: the same checks as
2335
+ // here, unless this machine keeps its folders to itself.
2336
+ async folders(m) {
2337
+ if (!loadSettings().folders_from_dashboard) throw new Error(`this machine doesn't let the dashboard change its folders ("folders_from_dashboard": false): change them there with "pisha-host folders add <path>"`)
2338
+ let list
2339
+ try { list = changeFolders(m.action, m.path) } catch (err) {
2340
+ if (!(err instanceof FolderRefused)) throw err
2341
+ log(`folder refused from the dashboard: ${err.message}`)
2342
+ throw new Error('that folder can\'t be allowed on this machine: it may not exist, not be a folder, or be off limits (this machine\'s pisha-host log says which; your whole home folder needs --allow-home)')
2343
+ }
2344
+ log(`folder ${m.action === 'add' ? 'allowed' : 'removed'} from the dashboard: ${plain(m.path)}`)
2345
+ await pushInfo()
2346
+ return { folders: list }
2347
+ },
2348
+ }
2349
+
2350
+ async function onMessage(m) {
2351
+ if (!m || typeof m !== 'object' || Array.isArray(m) || typeof m.t !== 'string') return
2352
+ // Every message from the server counts (each one can start tmux):
2353
+ // at most TERM_MSG_MAX every 10 seconds, the rest is dropped.
2354
+ const now = Date.now()
2355
+ termMsgs = termMsgs.filter(t => now - t < 10_000)
2356
+ if (termMsgs.length >= TERM_MSG_MAX) return
2357
+ termMsgs.push(now)
2358
+ if (m.t === 'welcome') {
2359
+ diagnosed = false
2360
+ abandoned = 0
2361
+ if (connectedAt) return // once per connection
2362
+ log(`connected to ${creds.server} as "${plain(m.host?.name).slice(0, 64)}"`); connectedAt = Date.now(); return pushInfo(true)
2363
+ }
2364
+ if (Object.hasOwn(handlers, m.t)) {
2365
+ if (!Number.isSafeInteger(m.req)) return // replies echo only a request number
2366
+ try { send({ t: 'reply', req: m.req, ok: true, result: await handlers[m.t](m) }) }
2367
+ catch (err) { send({ t: 'reply', req: m.req, ok: false, error: String(err.message).slice(0, 500) }) }
2368
+ return
2369
+ }
2370
+ const id = String(m.term ?? '')
2371
+ if (!NAME_RE.test(id)) return // session ids also end up in tmux commands
2372
+ if (m.t === 'attach') {
2373
+ let v = viewers.get(id)
2374
+ // Already watched: just a new size and a fresh screen (rate-limited).
2375
+ if (v) { v.resize(m.cols, m.rows); return v.screen().catch(() => {}) }
2376
+ if (!(await listTerminalsCached()).some(t => t.id === id)) return send({ t: 'exit', term: id })
2377
+ v = viewers.get(id)
2378
+ if (!v) {
2379
+ v = new Viewer(id, send, () => (ws?.bufferedAmount ?? 0) > 4 * 1024 * 1024)
2380
+ // tmux ends the control client when the session ends: tell the viewers.
2381
+ v.onExit = async () => {
2382
+ const ours = viewers.get(id) === v
2383
+ if (ours) viewers.delete(id)
2384
+ const alive = (await listTerminals()).some(t => t.id === id)
2385
+ if (!alive) send({ t: 'exit', term: id })
2386
+ // Its viewing client ended but the session didn't (detached on
2387
+ // the machine itself): watched again, a few times a minute at most.
2388
+ else if (ours && !v.unwanted) {
2389
+ const t = Date.now()
2390
+ reattaches.set(id, (reattaches.get(id) ?? []).filter(x => t - x < 60_000).concat(t))
2391
+ if (reattaches.get(id).length <= 3) void onMessage({ t: 'attach', term: id, cols: v.cols, rows: v.rows }).catch(() => {})
2392
+ else send({ t: 'notice', term: id, text: 'the terminal view stopped (the session was detached on the machine): open it again' })
2393
+ }
2394
+ void pushInfo()
2395
+ }
2396
+ viewers.set(id, v)
2397
+ }
2398
+ v.resize(m.cols, m.rows)
2399
+ return v.screen().catch(err => log(`screen of "${id}": ${err.message}`))
2400
+ }
2401
+ const v = viewers.get(id)
2402
+ if (!v) return
2403
+ if (m.t === 'detach') { v.unwanted = true; v.close(); viewers.delete(id); return }
2404
+ if (m.t === 'resize') { v.resize(m.cols, m.rows); return }
2405
+ if (m.t === 'refresh') return v.screen().catch(() => {})
2406
+ if (m.t === 'in') {
2407
+ if (!loadSettings().allow_input) return send({ t: 'notice', term: id, text: 'typing from the dashboard is turned off on this machine (allow_input: false)' })
2408
+ if (typeof m.data === 'string' && m.data.length <= 64 * 1024) v.input(m.data)
2409
+ }
2410
+ if (m.t === 'image') {
2411
+ if (!loadSettings().allow_input) return send({ t: 'notice', term: id, text: 'typing from the dashboard is turned off on this machine (allow_input: false)' })
2412
+ let file = null
2413
+ try { file = savePastedImage(id, m.type, m.data) } catch (err) { log(`pasted image for "${id}": ${err.message}`) }
2414
+ if (!file) return send({ t: 'notice', term: id, text: 'the pasted image could not be used (PNG, JPEG, GIF or WebP, up to 600 KB)' })
2415
+ // Pasted as tmux pastes (bracketed when the program asked for it), so
2416
+ // Claude Code sees a paste and attaches the image.
2417
+ await tmux(['set-buffer', '-b', 'pisha-image', file, ';', 'paste-buffer', '-p', '-d', '-b', 'pisha-image', '-t', `=${PREFIX}${id}:`]).catch(err => log(`pasting an image into "${id}": ${err.message}`))
2418
+ }
2419
+ }
2420
+
2421
+ setInterval(() => { if (ws?.readyState === 1) void pushInfo().catch(() => {}) }, 3000).unref()
2422
+ setInterval(() => send({ t: 'ping' }), 25_000).unref()
2423
+ // Viewers that missed output while the connection was congested: a fresh
2424
+ // screen once it has drained.
2425
+ setInterval(() => {
2426
+ if ((ws?.bufferedAmount ?? 0) > 4 * 1024 * 1024) return
2427
+ for (const v of viewers.values()) if (v.stale) { v.stale = false; void v.screen().catch(() => {}) }
2428
+ }, 1000).unref()
2429
+
2430
+ for (;;) {
2431
+ // The secret goes in an Authorization header, for a ticket of one use: what
2432
+ // travels in the WebSocket's own headers can end up in a proxy's logs.
2433
+ // (A server older than this program has no tickets, and takes the secret.)
2434
+ let credential = creds.secret
2435
+ let refused = null
2436
+ link = null
2437
+ try {
2438
+ // First of all, before its secret goes anywhere: is this our server?
2439
+ const proved = await serverIdentity(creds.server)
2440
+ if (creds.server_key && proved?.key !== creds.server_key) {
2441
+ refused = { code: 0, reason: `⚠️ this is not the server this machine knows (it expects the key ${serverFingerprint(creds.server_key)}, and this ${proved ? `one has ${serverFingerprint(proved.key)}` : 'one proves none'}). Its secret was not sent. It may be an impostor; if the server's key was really replaced, add this machine again from the dashboard` }
2442
+ } else {
2443
+ if (proved && !creds.server_key) {
2444
+ creds.server_key = proved.key
2445
+ writeJson(CREDENTIALS_FILE, creds)
2446
+ log(`this server's key is ${serverFingerprint(proved.key)}: remembered`)
2447
+ }
2448
+ if (proved) pinServerKeyForPlugin(creds.server, proved.key)
2449
+ const exchange = proved ? startLink(creds.id, proved) : null
2450
+ const res = await fetch(`${creds.server}/host/ticket`, {
2451
+ method: 'POST',
2452
+ headers: { Authorization: `Bearer ${creds.secret}`, ...(exchange ? { 'Content-Type': 'application/json' } : {}) },
2453
+ ...(exchange ? { body: JSON.stringify(exchange.request) } : {}),
2454
+ redirect: 'error',
2455
+ signal: AbortSignal.timeout(20_000),
2456
+ })
2457
+ // (A server older than this program has no tickets, and takes the secret:
2458
+ // it answers 401 or 404, and only says who it knows on the socket.)
2459
+ if (!proved && (res.status === 401 || res.status === 404)) credential = creds.secret
2460
+ else if (res.status === 401) refused = { code: 4001, reason: 'unknown or disconnected host' }
2461
+ else if (res.ok) {
2462
+ const answer = (await res.json()).result
2463
+ credential = answer.ticket
2464
+ if (exchange) {
2465
+ link = openLink(exchange, proved, answer)
2466
+ if (!link) refused = { code: 0, reason: '⚠️ the answer to the ticket request is not from this server: nothing was opened' }
2467
+ }
2468
+ } else if (res.status === 403) refused = { code: 0, reason: plain((await res.json().catch(() => ({}))).description ?? 'the server refuses this machine\'s key') }
2469
+ else refused = { code: 0, reason: `the server answered HTTP ${res.status} to the ticket request` }
2470
+ }
2471
+ } catch (err) {
2472
+ refused = { code: 0, reason: await diagnose(creds.server).catch(() => err.message) }
2473
+ }
2474
+ const closed = refused ?? await new Promise(resolveOnce => {
2475
+ // Settled once, by whichever comes first: a failed handshake fires only
2476
+ // "error" (never "close") in Node 22's WebSocket, and nothing else would
2477
+ // keep this program alive — it would end quietly and never reconnect.
2478
+ let settled = false
2479
+ const resolveClose = r => { if (!settled) { settled = true; settleNow = null; resolveOnce(r) } }
2480
+ settleNow = resolveClose
2481
+ lastFromServer = Date.now()
2482
+ // The credential goes with the request (as a subprotocol): the server
2483
+ // accepts no socket it can't authenticate first.
2484
+ // (Each handler with its own socket: one given up on can still fire late,
2485
+ // when "ws" is already the next one.)
2486
+ let mine
2487
+ try { mine = ws = new WebSocket(wsUrl(creds.server), ['pisha', `auth.${credential}`]) } catch (err) { return resolveClose({ code: 0, reason: err.message }) }
2488
+ mine.onopen = async () => {
2489
+ // A server that doesn't speak this protocol (older than this program).
2490
+ if (mine.protocol !== 'pisha') { try { mine.close(1000) } catch {} ; return resolveClose({ code: 0, reason: 'the server is older than this pisha-host: update the server' }) }
2491
+ // A small hello: the full info follows the server's welcome.
2492
+ send({ t: 'hello', id: creds.id })
2493
+ }
2494
+ const thisLink = link
2495
+ mine.onmessage = ev => {
2496
+ if (mine !== ws) return
2497
+ lastFromServer = Date.now()
2498
+ // Nothing the server legitimately sends is this big (once encrypted, a third more).
2499
+ if (typeof ev.data !== 'string' || ev.data.length > (thisLink ? 1.5 : 1) * 1024 * 1024) { try { mine.close(4009, 'message too big') } catch {} ; return }
2500
+ const text = thisLink ? thisLink.open(ev.data) : ev.data
2501
+ // Changed, repeated or dropped on the way: this connection can't be trusted any more.
2502
+ if (text === null) { log('⚠️ a message from the server does not check: reconnecting'); try { mine.close(4003, 'a message that does not check') } catch {} ; return }
2503
+ let m
2504
+ try { m = JSON.parse(text) } catch { return }
2505
+ onMessage(m).catch(err => log(`${plain(m?.t)}: ${err.message}`))
2506
+ }
2507
+ // (From Node 24 "close" follows the "error": it waits for what is being asked.)
2508
+ let diagnosing = false
2509
+ mine.onerror = ev => {
2510
+ mine.onerror = null // (closing it fires "error" again)
2511
+ const opened = mine.readyState === 1 || mine.readyState === 2
2512
+ const reason = ev?.message ?? ev?.error?.message ?? 'could not connect'
2513
+ try { mine.close() } catch {}
2514
+ // The handshake failed: WebSocket doesn't say why, so the server is
2515
+ // asked plainly once (per run of failures) to tell what's wrong.
2516
+ if (opened || diagnosed) return resolveClose({ code: 0, reason })
2517
+ diagnosed = diagnosing = true
2518
+ diagnose(creds.server).then(why => resolveClose({ code: 0, reason: why ?? reason }), () => resolveClose({ code: 0, reason }))
2519
+ }
2520
+ mine.onclose = ev => { if (!diagnosing) resolveClose({ code: ev.code, reason: ev.reason }) }
2521
+ })
2522
+ for (const v of viewers.values()) v.close()
2523
+ viewers.clear()
2524
+ // Exit 0: the service manager doesn't start it again (it would be refused forever).
2525
+ if (closed.code === 4001) die('the server no longer accepts this machine (it was disconnected from the dashboard). Enroll it again with a new command from the dashboard.', 0)
2526
+ // Back to a short wait only after a connection that lasted: a server
2527
+ // that drops (or crashes) this program right after it connects is retried
2528
+ // more and more slowly.
2529
+ if (connectedAt && Date.now() - connectedAt > 60_000) backoff = 1000
2530
+ connectedAt = 0
2531
+ log(`connection lost${closed.reason ? ` (${plain(closed.reason)})` : ''}; retrying in ${Math.round(backoff / 1000)} s`)
2532
+ await new Promise(r => setTimeout(r, backoff))
2533
+ backoff = Math.min(backoff * 2, 30_000)
2534
+ }
2535
+ }
2536
+
2537
+ // Why a connection can't be made, in words: the server's own answer to a
2538
+ // plain request (its version, or an HTTP status), or the network/TLS error.
2539
+ async function diagnose(server) {
2540
+ try {
2541
+ const res = await fetch(`${String(server).replace(/\/+$/, '')}/health`, { signal: AbortSignal.timeout(10_000), redirect: 'error' })
2542
+ if (!res.ok) return `the server answered HTTP ${res.status}`
2543
+ const j = await res.json().catch(() => null)
2544
+ const v = typeof j?.version === 'string' ? j.version : null
2545
+ if (v && olderVersion(v, VERSION)) return `the server is version ${plain(v)}, older than this pisha-host (${VERSION}): update the server`
2546
+ return `the server is up${v ? ` (version ${plain(v)})` : ''} but refused the connection (it may be limiting connections, or this machine may no longer be enrolled there)`
2547
+ } catch (err) {
2548
+ const c = err?.cause
2549
+ return `cannot reach the server: ${plain(c?.code ?? '')} ${plain(c?.message ?? err?.message ?? '')}`.trim()
2550
+ }
2551
+ }
2552
+
2553
+ // --- commands ------------------------------------------------------------------------------
2554
+
2555
+ const USAGE = `Usage: pisha-host [command] [options]
2556
+
2557
+ pisha-host Connect to the server (the service does this for you)
2558
+ pisha-host status This machine's server, settings and sessions
2559
+ pisha-host folders Folders where sessions may be opened (also from the dashboard)
2560
+ pisha-host folders add <path> Allow one more (folders remove <path> to take one away)
2561
+ pisha-host update Update pisha-host and the plugin to the server's version
2562
+ (only a release signed with this program's key, and not an older
2563
+ one; --allow-unsigned and --allow-downgrade to override that)
2564
+ pisha-host plugin Install or update the Pisha plugin in Claude Code
2565
+ pisha-host service Run in the background and start with the computer
2566
+ (service remove: stop doing that; service print: show the file)
2567
+ pisha-host forget Delete this machine's credential (with --close-sessions, if any are open)
2568
+ pisha-host --company=<id> ... The same, for that company's copy on this machine (each has its own
2569
+ folder, tmux, Claude Code login and service)
2570
+ pisha-host enroll <server> --code-file=<file> Join a Pisha server: the dashboard gives you this
2571
+ (with --server-key=<hash>, the key that server must prove)
2572
+ command in Machines → + Add machine. It also installs the
2573
+ plugin, this command and the service
2574
+
2575
+ Options:
2576
+ --allow-home allow your whole home folder for sessions (--no-allow-home to undo).
2577
+ Sessions there reach all your files; their permission prompts are
2578
+ answered only in their own terminal
2579
+ --insecure (enroll) accept a plain http server, on a trusted private network only
2580
+ --no-plugin (enroll) don't install the Pisha plugin
2581
+ --no-service (enroll) don't install the service: run in this terminal
2582
+
2583
+ Settings: ${SETTINGS_FILE}
2584
+ folders sessions can only be opened inside these folders
2585
+ folders_from_dashboard whether the dashboard may change them (default: allow_input)
2586
+ max_sessions at most this many sessions at once (default 8)
2587
+ allow_input whether the dashboard may type in the terminals (default true)
2588
+ allow_resume whether a session may continue its own last conversation (default: allow_input)
2589
+ permission_relay whether a worker's coordinator may answer its permission prompts
2590
+ from another session (default: same as allow_input)
2591
+ allow_clear whether a worker's coordinator may have its context cleared (/clear)
2592
+ before giving it a new task (default: same as allow_input)
2593
+ permissions_from_dashboard how far a permission profile from the dashboard goes: "allow",
2594
+ "restrict" (only what asks or forbids) or "off" (default: "allow"
2595
+ if allow_input, else "restrict")
2596
+ coordinators if set, the only coordinator names workers here may be given
2597
+ (and coordinators here may be linked with)
2598
+ claude_command the Claude Code executable (default "claude")
2599
+ `
2600
+
2601
+ // Plain http only to this machine, or when asked for explicitly: otherwise
2602
+ // anyone on the way could read the credentials or swap what the server says.
2603
+ function checkScheme(server, insecure) {
2604
+ let u
2605
+ try { u = new URL(server) } catch { die(`invalid server URL: ${plain(server)}`, 2) }
2606
+ if (u.protocol !== 'https:' && u.protocol !== 'http:') die('the server URL must start with https:// (or http:// on this machine)', 2)
2607
+ const loopback = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(u.hostname)
2608
+ if (u.protocol === 'http:' && !loopback && !insecure) {
2609
+ die(`refusing plain http to ${u.host}: credentials and terminals would travel unencrypted. Use https. On a trusted private network: enroll with --insecure, or, for a machine already enrolled, add "insecure": true to ${CREDENTIALS_FILE}.`, 2)
2610
+ }
2611
+ }
2612
+
2613
+ // --- this server and this machine, each proving who it is -----------------------------------
2614
+
2615
+ const serverKeyHash = key => createHash('sha256').update(String(key)).digest('hex')
2616
+ const serverFingerprint = key => serverKeyHash(key).slice(0, 16).replace(/(.{4})(?=.)/g, '$1 ')
2617
+
2618
+ // The server proves it holds its key, on a nonce of ours. Null: a server older
2619
+ // than this program, which has none to prove.
2620
+ async function serverIdentity(server) {
2621
+ const nonce = randomBytes(18).toString('base64url')
2622
+ const res = await fetch(`${server}/server-identity?nonce=${nonce}`, { redirect: 'error', signal: AbortSignal.timeout(20_000) })
2623
+ if (res.status === 401 || res.status === 404) return null
2624
+ if (!res.ok) throw new Error(`the server answered HTTP ${res.status} when asked for its key`)
2625
+ const { key, challenge, sig } = (await res.json()).result ?? {}
2626
+ if (typeof key !== 'string' || typeof challenge !== 'string' || !serverSigned(key, ['pisha-server-identity-1', nonce, challenge], sig)) throw new Error('the server did not prove its key')
2627
+ return { key, challenge }
2628
+ }
2629
+ function serverSigned(publicKeyText, fields, sig) {
2630
+ try {
2631
+ const publicKey = createPublicKey({ key: Buffer.from(String(publicKeyText), 'base64url'), format: 'der', type: 'spki' })
2632
+ return publicKey.asymmetricKeyType === 'ed25519' && verify(null, Buffer.from(JSON.stringify(fields)), publicKey, Buffer.from(String(sig), 'base64url'))
2633
+ } catch {
2634
+ return false
2635
+ }
2636
+ }
2637
+
2638
+ // This machine's own key: made once, and only ever used from here.
2639
+ function hostKey() {
2640
+ const saved = readJson(HOST_KEY_FILE, null)
2641
+ try {
2642
+ const privateKey = createPrivateKey({ key: Buffer.from(String(saved.private), 'base64url'), format: 'der', type: 'pkcs8' })
2643
+ if (privateKey.asymmetricKeyType === 'ed25519') return { privateKey, public: createPublicKey(privateKey).export({ format: 'der', type: 'spki' }).toString('base64url') }
2644
+ } catch {}
2645
+ const { privateKey, publicKey } = generateKeyPairSync('ed25519')
2646
+ const pub = publicKey.export({ format: 'der', type: 'spki' }).toString('base64url')
2647
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 })
2648
+ writeJson(HOST_KEY_FILE, { private: privateKey.export({ format: 'der', type: 'pkcs8' }).toString('base64url'), public: pub })
2649
+ return { privateKey, public: pub }
2650
+ }
2651
+
2652
+ // The link with the server is encrypted between the two of them, whatever is on
2653
+ // the way, even something with a certificate for its name that passes everything
2654
+ // along: the keys come from an exchange each side signs. Only the server's
2655
+ // signature opens it, and only this machine's gets it a ticket.
2656
+ function startLink(id, proved) {
2657
+ const me = hostKey()
2658
+ const ephemeral = generateKeyPairSync('x25519')
2659
+ const eph = ephemeral.publicKey.export({ format: 'der', type: 'spki' }).toString('base64url')
2660
+ const proof = sign(null, Buffer.from(JSON.stringify(['pisha-client-proof-1', proved.key, 'host-ticket', id, proved.challenge, eph])), me.privateKey).toString('base64url')
2661
+ return { ephemeral, eph, request: { key: me.public, challenge: proved.challenge, eph, proof } }
2662
+ }
2663
+ // What the two sides share, or null if the answer isn't the server's.
2664
+ function openLink(exchange, proved, answer) {
2665
+ if (typeof answer?.ticket !== 'string' || typeof answer.eph !== 'string') return null
2666
+ if (!serverSigned(proved.key, ['pisha-link-1', exchange.eph, answer.eph, proved.challenge, answer.ticket], answer.sig)) return null
2667
+ let shared
2668
+ try {
2669
+ const peer = createPublicKey({ key: Buffer.from(answer.eph, 'base64url'), format: 'der', type: 'spki' })
2670
+ shared = diffieHellman({ privateKey: exchange.ephemeral.privateKey, publicKey: peer })
2671
+ } catch { return null }
2672
+ const okm = Buffer.from(hkdfSync('sha256', shared, proved.challenge, `pisha-link-1|${exchange.eph}|${answer.eph}`, 64))
2673
+ const toServer = okm.subarray(0, 32), fromServer = okm.subarray(32)
2674
+ // AES-256-GCM, numbered by its place in each direction (the server's encryptSocket).
2675
+ const iv = n => { const b = Buffer.alloc(12); b.writeBigUInt64BE(n, 4); return b }
2676
+ let sent = 0n, received = 0n
2677
+ return {
2678
+ seal(text) {
2679
+ const c = createCipheriv('aes-256-gcm', toServer, iv(sent++))
2680
+ const body = Buffer.concat([c.update(text, 'utf8'), c.final()])
2681
+ return Buffer.concat([body, c.getAuthTag()]).toString('base64')
2682
+ },
2683
+ open(raw) {
2684
+ try {
2685
+ const all = Buffer.from(raw, 'base64')
2686
+ const d = createDecipheriv('aes-256-gcm', fromServer, iv(received++))
2687
+ d.setAuthTag(all.subarray(-16))
2688
+ return Buffer.concat([d.update(all.subarray(0, -16)), d.final()]).toString('utf8')
2689
+ } catch { return null }
2690
+ },
2691
+ }
2692
+ }
2693
+
2694
+ // The plugin on this machine remembers the same key (it does so by itself on a
2695
+ // machine with no pisha-host), per server. Never over one it already has.
2696
+ function pinServerKeyForPlugin(server, key) {
2697
+ if (claudeCode.plugin.serverUrl() !== server.replace(/\/+$/, '')) return
2698
+ const dir = join(claudeCode.home(), 'channels', 'pisha', '.server-keys')
2699
+ const file = join(dir, serverKeyHash(server.replace(/\/+$/, '')).slice(0, 16))
2700
+ if (existsSync(file)) return
2701
+ try {
2702
+ ensurePrivateDir(dir)
2703
+ writeFileSync(file, `${key}\n`, { mode: 0o600, flag: 'wx' })
2704
+ } catch (err) { if (err.code !== 'EEXIST') log(`could not tell the plugin this server's key: ${err.message}`) }
2705
+ }
2706
+
2707
+ // Returns true when it left pisha-host running in the background (service).
2708
+ async function enroll(server, code, { plugin = true, insecure = false, service = true, serverKey = null, keepSessions = false } = {}) {
2709
+ if (!server || !code) die(`enroll needs the server URL and a code.\n\n${USAGE}`, 2)
2710
+ // (Before the code is spent: its secret could not be kept.)
2711
+ try { if (existsSync(CREDENTIALS_FILE)) accessSync(realOr(CREDENTIALS_FILE), FS.W_OK) } catch { die(`${CREDENTIALS_FILE} can't be written: nothing was done`, 2) }
2712
+ server = server.replace(/\/+$/, '')
2713
+ checkScheme(server, insecure)
2714
+ // Already another server's: its sessions would go on running here, and appear
2715
+ // in the new one. Only by asking for it, and never by accident.
2716
+ const enrolled = readJson(CREDENTIALS_FILE, null)
2717
+ // Nor another company's (written by an older version, with no copy of its own):
2718
+ // its sessions would appear in this one. Its secret says whose it is.
2719
+ const heldBy = enrolled?.company ?? /^sh_([a-z0-9]{8})_/.exec(String(enrolled?.secret ?? ''))?.[1] ?? ''
2720
+ if (enrolled?.secret && heldBy !== COMPANY) die(`this copy of pisha-host already belongs to another company: nothing was done. To leave it first: ${cli()} forget`, 2)
2721
+ if (enrolled?.server && enrolled.server !== server) die(`this machine already belongs to ${plain(enrolled.server)}: nothing was done. To leave it first: ${cli()} forget`, 2)
2722
+ // Sessions with no server here: they would appear in this one, as its own.
2723
+ if (!enrolled?.secret && !keepSessions) {
2724
+ const open = (await listTerminals()).map(t => t.id)
2725
+ if (open.length) die(`sessions are open on this copy (${open.map(plain).join(', ')}) and they would go to ${plain(server)}, which can then read and type in them: nothing was done. Close them, or add --keep-sessions if that is what you want`, 2)
2726
+ }
2727
+ // The dashboard's command says which server this should be: with it, nothing
2728
+ // here depends on who answers first.
2729
+ let proved = null
2730
+ try { proved = await serverIdentity(server) } catch (err) { die(`cannot check ${server}: ${err.cause?.message ?? err.message}`) }
2731
+ if (serverKey && serverKeyHash(proved?.key ?? '') !== serverKey) die(`this is not the server the dashboard's command is for: ${proved ? `its key is ${serverFingerprint(proved.key)}` : 'it proves no key'}. Nothing was sent to it. Check the address, and that you copied the whole command`)
2732
+ const info = await hostInfo()
2733
+ let res
2734
+ try {
2735
+ res = await fetch(`${server}/host/enroll`, {
2736
+ method: 'POST',
2737
+ headers: { 'Content-Type': 'application/json' },
2738
+ // (The server refuses a code of another company before spending it.)
2739
+ body: JSON.stringify({ code: code.trim().toUpperCase(), company: COMPANY || 'default', info }),
2740
+ redirect: 'error',
2741
+ })
2742
+ } catch (err) { die(`cannot reach ${server}: ${err.cause?.message ?? err.message}`) }
2743
+ const j = await res.json().catch(() => ({}))
2744
+ if (!j.ok) die(`enrollment refused: ${plain(j.description ?? `HTTP ${res.status}`)}`)
2745
+ const r = j.result ?? {}
2746
+ if (typeof r.id !== 'string' || !/^h_[0-9a-f]{8,64}$/.test(r.id) || typeof r.secret !== 'string' || !/^sh_[A-Za-z0-9_-]{20,200}$/.test(r.secret)) {
2747
+ die('the server answered the enrollment with something unexpected')
2748
+ }
2749
+ writeJson(CREDENTIALS_FILE, { server, id: r.id, secret: r.secret, insecure, ...(COMPANY ? { company: COMPANY } : {}), ...(proved ? { server_key: proved.key } : {}) })
2750
+ ensureClaudeHome()
2751
+ // No folder is allowed until the user says which (folders add): enrolling
2752
+ // from wherever the script was downloaded must not open that place up.
2753
+ if (!existsSync(SETTINGS_FILE)) writeJson(SETTINGS_FILE, { ...DEFAULT_SETTINGS, settings_version: SETTINGS_VERSION })
2754
+ // Keep a copy of this program next to its settings, for the service.
2755
+ const self = fileURLToPath(import.meta.url)
2756
+ if (resolve(self) !== resolve(INSTALLED_SCRIPT)) { try { copyFileSync(self, INSTALLED_SCRIPT) } catch {} }
2757
+ // Configure the Pisha plugin on this machine if it isn't yet.
2758
+ const pluginEnvFile = join(claudeCode.home(), 'channels', 'pisha', '.env')
2759
+ // Only a well-formed URL and token: anything else (a line break, say) could
2760
+ // add settings of its own to the plugin's .env.
2761
+ const pu = r.plugin?.url, pt = r.plugin?.token
2762
+ // Same server as the one enrolled with (no other origin, no http downgrade).
2763
+ const urlOk = typeof pu === 'string' && /^https?:\/\/[^\s]+$/.test(pu) && (() => { try { return new URL(pu).origin === new URL(server).origin } catch { return false } })()
2764
+ const tokenOk = pt == null || (typeof pt === 'string' && /^[\x21-\x7e]{16,256}$/.test(pt))
2765
+ if (r.plugin && (!urlOk || !tokenOk)) log('⚠️ the server sent an invalid plugin configuration: ignored')
2766
+ else if (r.plugin && pu && !existsSync(pluginEnvFile)) {
2767
+ // The server address always; the join token only if the dashboard
2768
+ // offered it (sessions opened from the dashboard don't need it).
2769
+ ensurePrivateDir(join(pluginEnvFile, '..'))
2770
+ // (Enrolled with --insecure: the plugin needs to be told the same, or it refuses plain http.)
2771
+ writeFileSync(pluginEnvFile, `PISHA_URL=${pu}\n${pt ? `PISHA_SERVER_TOKEN=${pt}\n` : ''}${insecure ? 'PISHA_INSECURE=1\n' : ''}`, { mode: 0o600, flag: 'wx' }) // never through a symlink
2772
+ log(`Pisha plugin configured for ${pu} (${pluginEnvFile})${pt ? '' : ', without a join token: only sessions opened from the dashboard can join'}`)
2773
+ }
2774
+ if (proved) pinServerKeyForPlugin(server, proved.key)
2775
+ // Install the plugin itself, so sessions opened from the dashboard work unattended.
2776
+ if (plugin && info.claude) {
2777
+ try {
2778
+ const before = await claudeCode.plugin.status()
2779
+ const st = await claudeCode.plugin.ensure()
2780
+ log(before?.installed && before.enabled ? `Pisha plugin ${st.version ?? ''} already installed in Claude Code` : `Pisha plugin ${st.version ?? ''} installed in Claude Code`)
2781
+ } catch (err) {
2782
+ log(`⚠️ could not install the Pisha plugin (${err.message.split('\n')[0]}). Install it with: ${claudeCode.plugin.commands}`)
2783
+ }
2784
+ }
2785
+ // And in Codex CLI and Grok CLI, if this machine has them.
2786
+ if (plugin) {
2787
+ await readTypedVersions()
2788
+ for (const [id, a] of Object.entries(TYPED)) {
2789
+ if (!TYPED_VERSIONS[id]) continue
2790
+ try { const st = await a.plugin.ensure(); log(`Pisha plugin ${st.version ?? ''} ready in ${a.name}`) }
2791
+ catch (err) { log(`⚠️ could not install the Pisha plugin in ${a.name} (${err.message.split('\n')[0]}). Install it with: ${a.plugin.commands}`) }
2792
+ }
2793
+ }
2794
+ // The "pisha-host" command and the service (not for a custom
2795
+ // PISHA_HOST_DIR: a second, separate setup, such as the tests').
2796
+ let launcher = null, svc = null
2797
+ if (process.env.PISHA_HOST_DIR) service = false
2798
+ else {
2799
+ // (Not the tests': they would leave it in the real home.)
2800
+ if (process.env.PISHA_HOST_TEST_ALLOW_TMP !== '1') try { launcher = installLauncher() } catch (err) { log(`⚠️ could not add the pisha-host command (${err.message})`) }
2801
+ const other = someoneElsesService()
2802
+ if (service && other) log(`the service on this machine (${other}) runs another pisha-host: left as it is`)
2803
+ else if (service) { try { svc = await installService() } catch (err) { svc = { ok: false, why: err.message } } }
2804
+ }
2805
+ if (!info.tmux) log(`⚠️ tmux is not installed: install it (${TMUX_INSTALL}) before opening sessions.`)
2806
+ if (!info.claude && !Object.values(TYPED_VERSIONS).some(Boolean)) log(`⚠️ No agent was found (Claude Code, Codex CLI or Grok CLI is not on the PATH). Install one, then run: ${cli()} plugin`)
2807
+ if (svc && !svc.ok) log(`⚠️ could not leave it running in the background (${svc.why}): it runs here while this terminal stays open.`)
2808
+ process.stderr.write(`
2809
+ pisha-host: this machine is now "${plain(r.name)}" on ${server}.
2810
+ ${svc?.ok ? `It runs in the background as ${svc.how}.` : 'It keeps running while this terminal stays open.'}
2811
+ Next, in the dashboard: Add folder on the Add machine page, or under this machine in Machines, to choose where sessions may be opened.
2812
+ ${COMPANY ? `This company has its own Claude Code login. Sign in once: CLAUDE_CONFIG_DIR='${process.env.CLAUDE_CONFIG_DIR}' claude, then /login.\n ` : ''} ${launcher?.onPath === false ? `The ${SERVICE_NAME} command is in ${dirname(LAUNCHER)}: open a new terminal to use it (or add that folder to your PATH).` : launcher?.skipped ? `${LAUNCHER} already exists and isn't this program's: use node ${INSTALLED_SCRIPT}.` : `Commands: ${SERVICE_NAME} status · ${SERVICE_NAME} help`}
2813
+
2814
+ `)
2815
+ return !!svc?.ok
2816
+ }
2817
+
2818
+ // A company's Claude Code folder, private like everything of this program's.
2819
+ function ensureClaudeHome() {
2820
+ if (COMPANY && process.env.CLAUDE_CONFIG_DIR) mkdirSync(process.env.CLAUDE_CONFIG_DIR, { recursive: true, mode: 0o700 })
2821
+ }
2822
+
2823
+ // The settings file as written (for changing it), or an error if it can't be
2824
+ // read: a settings file that can't be read is never rewritten from the
2825
+ // defaults (that would turn typing and the relay back on).
2826
+ function rawSettings() {
2827
+ let raw = {}
2828
+ try { raw = JSON.parse(readFileSync(SETTINGS_FILE, 'utf8')) } catch (err) {
2829
+ if (err.code !== 'ENOENT') throw new Error(`cannot read ${SETTINGS_FILE} (${err.message}): fix it by hand first`)
2830
+ }
2831
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`${SETTINGS_FILE} must hold a JSON object: fix it by hand first`)
2832
+ const s = { ...DEFAULT_SETTINGS, ...raw }
2833
+ s.folders = Array.isArray(s.folders) ? s.folders.filter(f => typeof f === 'string') : []
2834
+ return s
2835
+ }
2836
+
2837
+ // Add or remove an allowed folder (from this machine, or from the dashboard).
2838
+ // "~" and "~/…" are the home folder. Returns the folders now allowed.
2839
+ // What depends on the disk (FolderRefused) is told in full here, and only as a
2840
+ // refusal to the dashboard: whoever controls the server can't probe what exists.
2841
+ class FolderRefused extends Error {}
2842
+ const MAX_FOLDERS = 50
2843
+ function changeFolders(action, path) {
2844
+ if (action !== 'add' && action !== 'remove') throw new Error('the action must be add or remove')
2845
+ if (typeof path !== 'string' || !path.trim() || path.length > 4096) throw new Error('a folder path is needed')
2846
+ // (Spaces around it are a slip, unless they are in the name of an allowed folder.)
2847
+ if (!rawSettings().folders.includes(path)) path = path.trim()
2848
+ if (/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/.test(path)) throw new Error('the path contains control characters')
2849
+ if (path === '~' || path.startsWith('~/')) path = join(HOME, path.slice(1))
2850
+ if (!isAbsolute(path)) throw new Error(`${plain(path)} is not an absolute path (start it with / or ~/)`)
2851
+ const s = rawSettings()
2852
+ const abs = resolve(path)
2853
+ if (action === 'add') {
2854
+ if (/[#;]/.test(abs)) throw new Error('folders with # or ; in their path cannot be used')
2855
+ let st = null
2856
+ try { st = statSync(abs) } catch {}
2857
+ if (!st) throw new FolderRefused(`${plain(abs)} does not exist on this machine`)
2858
+ if (!st.isDirectory()) throw new FolderRefused(`${plain(abs)} is not a folder`)
2859
+ const why = forbiddenFolder(realOr(abs), { allowHome: s.allow_home === true })
2860
+ if (why) throw new FolderRefused(`${plain(abs)} can't be allowed: it is ${why}`)
2861
+ if (folderOfAnotherCompany(realOr(abs))) throw new FolderRefused(`${plain(abs)} can't be allowed: it belongs to another company on this machine`)
2862
+ if (!s.folders.includes(abs)) {
2863
+ if (s.folders.length >= MAX_FOLDERS) throw new Error(`at most ${MAX_FOLDERS} folders: remove one first`)
2864
+ s.folders.push(abs)
2865
+ }
2866
+ } else {
2867
+ const before = s.folders.length
2868
+ s.folders = s.folders.filter(f => f !== abs && resolve(f) !== abs)
2869
+ if (s.folders.length === before) throw new Error(`${plain(abs)} is not one of the allowed folders`)
2870
+ }
2871
+ writeJson(SETTINGS_FILE, s)
2872
+ return loadSettings().folders
2873
+ }
2874
+
2875
+ function folders(action, path) {
2876
+ try {
2877
+ const list = action === 'add' || action === 'remove' ? changeFolders(action, path) : loadSettings().folders
2878
+ process.stdout.write((list.length ? list.join('\n') : '(no folders: no session can be opened)') + '\n')
2879
+ } catch (err) { die(err.message, 2) }
2880
+ }
2881
+
2882
+ const TMUX_INSTALL = platform() === 'darwin' ? 'brew install tmux' : 'sudo apt install tmux (or your distribution\'s package)'
2883
+
2884
+ // systemd: a quoted word, with % (specifiers) escaped.
2885
+ // Environment= is different: "$" means nothing there (only \\, " and % are special).
2886
+ const sdEnv = v => `"${String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`
2887
+ const sd = v => `"${String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"`
2888
+ // PATH for the service, without relative entries.
2889
+ const absolutePath = () => String(process.env.PATH ?? '').split(':').filter(d => isAbsolute(d)).join(':')
2890
+ // And where this program and Claude Code keep their files, when they aren't
2891
+ // the defaults (the service would otherwise look in the default places).
2892
+ const serviceEnv = () => {
2893
+ const env = [['PATH', absolutePath()], ['PISHA_SERVICE', '1']]
2894
+ if (COMPANY) env.push(['PISHA_COMPANY', COMPANY])
2895
+ for (const k of ['PISHA_HOST_DIR', 'XDG_CONFIG_HOME', 'CLAUDE_CONFIG_DIR']) {
2896
+ const v = process.env[k]
2897
+ if (v && isAbsolute(v) && !/[\x00-\x1f\x7f]/.test(v)) env.push([k, v])
2898
+ }
2899
+ return env
2900
+ }
2901
+
2902
+ // --- running in the background ----------------------------------------------------
2903
+ //
2904
+ // The enrollment installs and starts a service, so the machine keeps working
2905
+ // after a restart with nothing else to do: a systemd user service on Linux
2906
+ // (also WSL with systemd), a launchd agent on macOS.
2907
+
2908
+ // (Run as root — installed with --allow-root —: a system service, since root
2909
+ // rarely has a systemd user session.)
2910
+ const AS_ROOT = typeof process.getuid === 'function' && process.getuid() === 0
2911
+ // (One per company, so each starts and stops by itself.)
2912
+ const SERVICE_NAME = COMPANY ? `pisha-host-${COMPANY}` : 'pisha-host'
2913
+ const SYSTEMD_UNIT = AS_ROOT ? `/etc/systemd/system/${SERVICE_NAME}.service` : join(process.env.XDG_CONFIG_HOME && isAbsolute(process.env.XDG_CONFIG_HOME) ? process.env.XDG_CONFIG_HOME : join(HOME, '.config'), 'systemd', 'user', `${SERVICE_NAME}.service`)
2914
+ const userFlag = AS_ROOT ? [] : ['--user']
2915
+ const LAUNCHD_LABEL = COMPANY ? `com.pisha.host.${COMPANY}` : 'com.pisha.host'
2916
+ const LAUNCHD_PLIST = join(HOME, 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`)
2917
+ // System tools only from the system's own folders.
2918
+ const systemTool = name => ['/usr/bin', '/bin', '/usr/sbin', '/sbin'].map(d => join(d, name)).find(f => { try { accessSync(f, FS.X_OK); return true } catch { return false } }) ?? null
2919
+
2920
+ function serviceFile() {
2921
+ const node = process.execPath
2922
+ if (platform() === 'darwin') {
2923
+ const logFile = join(HOME, 'Library', 'Logs', `${SERVICE_NAME}.log`)
2924
+ const x = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
2925
+ return { path: LAUNCHD_PLIST, script: x(INSTALLED_SCRIPT), text: `<?xml version="1.0" encoding="UTF-8"?>
2926
+ <!-- Written by pisha-host. Log: ${x(logFile)} -->
2927
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2928
+ <plist version="1.0">
2929
+ <dict>
2930
+ <key>Label</key><string>${LAUNCHD_LABEL}</string>
2931
+ <key>ProgramArguments</key>
2932
+ <array><string>${x(node)}</string><string>${x(INSTALLED_SCRIPT)}</string></array>
2933
+ <key>EnvironmentVariables</key>
2934
+ <dict>${serviceEnv().map(([k, v]) => `<key>${x(k)}</key><string>${x(v)}</string>`).join('')}</dict>
2935
+ <key>RunAtLoad</key><true/>
2936
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
2937
+ <key>AbandonProcessGroup</key><true/>
2938
+ <key>StandardErrorPath</key><string>${x(logFile)}</string>
2939
+ </dict>
2940
+ </plist>
2941
+ ` }
2942
+ }
2943
+ return { path: SYSTEMD_UNIT, script: sd(INSTALLED_SCRIPT), text: `# Written by pisha-host.
2944
+ [Unit]
2945
+ Description=Pisha host${COMPANY ? ` (company ${COMPANY})` : ''}
2946
+ After=network-online.target
2947
+
2948
+ [Service]
2949
+ ${AS_ROOT ? `User=root\nEnvironment=${sdEnv(`HOME=${HOME}`)}\n` : ''}ExecStart=${sd(node)} ${sd(INSTALLED_SCRIPT)}
2950
+ Restart=on-failure
2951
+ RestartSec=5
2952
+ # (Stopping or restarting it leaves the sessions it opened running: tmux
2953
+ # started from here would otherwise be stopped along with it.)
2954
+ KillMode=process
2955
+ # (2: not enrolled, or what it needs is missing: starting it again won't help.
2956
+ # Refused for good by the server, it ends with 0.)
2957
+ RestartPreventExitStatus=2
2958
+ ${serviceEnv().map(([k, v]) => `Environment=${sdEnv(`${k}=${v}`)}`).join('\n')}
2959
+
2960
+ [Install]
2961
+ WantedBy=${AS_ROOT ? 'multi-user.target' : 'default.target'}
2962
+ ` }
2963
+ }
2964
+
2965
+ // Install (or update) the service and (re)start it. { ok, how } or { ok: false, why }.
2966
+ async function installService() {
2967
+ const f = serviceFile()
2968
+ const write = () => {
2969
+ mkdirSync(dirname(f.path), { recursive: true })
2970
+ const tmp = `${f.path}.${process.pid}.tmp`
2971
+ writeFileSync(tmp, f.text, { mode: 0o644, flag: 'wx' })
2972
+ renameSync(tmp, f.path)
2973
+ }
2974
+ if (platform() === 'darwin') {
2975
+ const launchctl = systemTool('launchctl')
2976
+ if (!launchctl || typeof process.getuid !== 'function') return { ok: false, why: 'launchctl was not found' }
2977
+ write()
2978
+ const target = `gui/${process.getuid()}`
2979
+ await run(launchctl, ['bootout', target, f.path], { timeout: 30_000 }).catch(() => {}) // (an older copy, if loaded)
2980
+ try { await run(launchctl, ['bootstrap', target, f.path], { timeout: 30_000 }) } catch (err) { return { ok: false, why: `launchctl bootstrap failed (${String(err.stderr || err.message).trim().split('\n')[0]})` } }
2981
+ return { ok: true, how: `a launchd agent (${f.path}); it runs while you are logged in` }
2982
+ }
2983
+ const systemctl = systemTool('systemctl')
2984
+ if (!systemctl) return { ok: false, why: 'systemd was not found' }
2985
+ if (!AS_ROOT) {
2986
+ try { await run(systemctl, ['--user', 'show-environment'], { timeout: 15_000 }) } catch {
2987
+ return { ok: false, why: `there is no systemd user session here: run "sudo loginctl enable-linger ${userInfo().username}" and log in as this user directly (ssh), not with su (on WSL, enable systemd in /etc/wsl.conf)` }
2988
+ }
2989
+ }
2990
+ write()
2991
+ try {
2992
+ await run(systemctl, [...userFlag, 'daemon-reload'], { timeout: 30_000 })
2993
+ await run(systemctl, [...userFlag, 'enable', SERVICE_NAME], { timeout: 30_000 })
2994
+ await run(systemctl, [...userFlag, 'restart', SERVICE_NAME], { timeout: 30_000 })
2995
+ } catch (err) { return { ok: false, why: `systemctl failed (${String(err.stderr || err.message).trim().split('\n')[0]})` } }
2996
+ if (AS_ROOT) return { ok: true, how: `a system service (${f.path}); it starts with the machine` }
2997
+ // Running also while you are logged out (may need an administrator: optional).
2998
+ const loginctl = systemTool('loginctl')
2999
+ let linger = false
3000
+ if (loginctl) {
3001
+ try { await run(loginctl, ['enable-linger'], { timeout: 15_000 }); linger = true } catch {
3002
+ // (Not allowed to ask, but it may be on already: the installer does it for a user of its own.)
3003
+ try { linger = /Linger=yes/.test((await run(loginctl, ['show-user', userInfo().username, '-p', 'Linger'], { timeout: 15_000 })).stdout) } catch {}
3004
+ }
3005
+ }
3006
+ return { ok: true, how: `a systemd user service (${f.path})${linger ? '; it also runs while you are logged out' : '; it runs while you are logged in (for always: loginctl enable-linger $USER)'}` }
3007
+ }
3008
+
3009
+ async function removeService() {
3010
+ if (platform() === 'darwin') {
3011
+ const launchctl = systemTool('launchctl')
3012
+ if (launchctl && typeof process.getuid === 'function') await run(launchctl, ['bootout', `gui/${process.getuid()}`, LAUNCHD_PLIST], { timeout: 30_000 }).catch(() => {})
3013
+ rmSync(LAUNCHD_PLIST, { force: true })
3014
+ return
3015
+ }
3016
+ const systemctl = systemTool('systemctl')
3017
+ if (systemctl) await run(systemctl, [...userFlag, 'disable', '--now', SERVICE_NAME], { timeout: 30_000 }).catch(() => {})
3018
+ rmSync(SYSTEMD_UNIT, { force: true })
3019
+ if (systemctl) await run(systemctl, [...userFlag, 'daemon-reload'], { timeout: 30_000 }).catch(() => {})
3020
+ }
3021
+
3022
+ // The service on this machine, if it runs another copy of this program (one
3023
+ // with its own PISHA_HOST_DIR, say). There is only one: it isn't ours to change.
3024
+ function someoneElsesService() {
3025
+ const f = serviceFile()
3026
+ try { return readFileSync(f.path, 'utf8').includes(f.script) ? null : f.path } catch { return null }
3027
+ }
3028
+
3029
+ async function service(action) {
3030
+ if (action === 'print') return process.stdout.write(serviceFile().text)
3031
+ const other = someoneElsesService()
3032
+ if (other) die(`the service on this machine (${other}) runs another pisha-host, from another configuration folder: nothing was changed. Run this from that one (with its PISHA_HOST_DIR), or delete that file to use this one`, 2)
3033
+ if (action === 'remove') { await removeService(); return log(`service removed: it no longer starts by itself (run it with: ${cli()})`) }
3034
+ if (action && action !== 'install') die(`service ${plain(action)}: use "service", "service remove" or "service print"`, 2)
3035
+ const r = await installService()
3036
+ if (!r.ok) die(`could not install the service: ${r.why}. Run "${cli()}" in a terminal instead (it must stay open), or set it up by hand from "${cli()} service print".`)
3037
+ log(`running in the background as ${r.how}`)
3038
+ }
3039
+
3040
+ // The "pisha-host" command: a small launcher in ~/.local/bin (in the PATH
3041
+ // of most systems), so nobody has to type the path of this program.
3042
+ const LAUNCHER = typeof process.getuid === 'function' && process.getuid() === 0 ? `/usr/local/bin/${SERVICE_NAME}` : join(HOME, '.local', 'bin', SERVICE_NAME)
3043
+ const LAUNCHER_MARK = '# pisha-host launcher (written by pisha-host)'
3044
+ const launcherOnPath = () => String(process.env.PATH ?? '').split(':').some(d => d && resolve(d) === dirname(LAUNCHER))
3045
+ const cli = () => (existsSync(LAUNCHER) && launcherOnPath() ? SERVICE_NAME : `node ${INSTALLED_SCRIPT}${COMPANY ? ` --company=${COMPANY}` : ''}`)
3046
+ function installLauncher() {
3047
+ const q = v => `'${String(v).replace(/'/g, `'\\''`)}'`
3048
+ // (Someone else's, or one that can't be read: left alone.)
3049
+ try { if (!readFileSync(LAUNCHER, 'utf8').includes(LAUNCHER_MARK)) return { skipped: true } } catch (err) { if (err.code !== 'ENOENT') return { skipped: true } }
3050
+ mkdirSync(dirname(LAUNCHER), { recursive: true, mode: 0o755 })
3051
+ const tmp = `${LAUNCHER}.${process.pid}.tmp`
3052
+ writeFileSync(tmp, `#!/bin/sh\n${LAUNCHER_MARK}\nN=${q(process.execPath)}\n[ -x "$N" ] || N=node\nexec "$N" ${q(INSTALLED_SCRIPT)}${COMPANY ? ` --company=${COMPANY}` : ''} "$@"\n`, { mode: 0o755, flag: 'wx' })
3053
+ renameSync(tmp, LAUNCHER)
3054
+ return { onPath: launcherOnPath() }
3055
+ }
3056
+
3057
+ // One pisha-host at a time per machine (two would keep replacing each
3058
+ // other's connection): the one running says so in a pid file.
3059
+ const PID_FILE = join(CONFIG_DIR, 'pisha-host.pid')
3060
+ // Started by its service, which starts it again if it ends. (Its own mark: a
3061
+ // terminal started by systemd looks just like a service from its environment.)
3062
+ const UNDER_SERVICE = process.env.PISHA_SERVICE === '1'
3063
+ delete process.env.PISHA_SERVICE
3064
+ function runningInstance() {
3065
+ let pid
3066
+ try { pid = Number(readFileSync(PID_FILE, 'utf8').trim()) } catch { return null }
3067
+ if (!Number.isSafeInteger(pid) || pid <= 1 || pid === process.pid) return null
3068
+ try { process.kill(pid, 0) } catch (err) { if (err.code === 'ESRCH') return null }
3069
+ // (On Linux a thread answers as a process, with the program's command line:
3070
+ // in a container, where numbers repeat at every start, it can be one of ours.)
3071
+ try { if (Number(/^Tgid:\s*(\d+)/m.exec(readFileSync(`/proc/${pid}/status`, 'utf8'))?.[1]) !== pid) return null } catch {}
3072
+ // (A pid reused by another program isn't this one.)
3073
+ let cmd = ''
3074
+ try { cmd = readFileSync(`/proc/${pid}/cmdline`, 'utf8') } catch {
3075
+ try { cmd = execFileSync(systemTool('ps') ?? '/bin/ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8', timeout: 5000 }) } catch {}
3076
+ }
3077
+ // (Only this program itself, not anything with the name in its arguments:
3078
+ // an editor on this file, a tail of its log.)
3079
+ // (From ps, one line: a path can have spaces.)
3080
+ const args = cmd.split('\0')
3081
+ const itself = cmd.includes('\0')
3082
+ ? /(^|\/)node[^/]*$/.test(args[0]) && /pisha-host[^/]*\.mjs$/.test(args[1] ?? '')
3083
+ : /(^|\/)node[^/\s]*\s+(.*\/)?pisha-host[^/]*\.mjs(\s|$)/.test(cmd.trim())
3084
+ return itself ? pid : null
3085
+ }
3086
+ async function claimInstance() {
3087
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 })
3088
+ // (Under a service, losing starts it again: the other one may not last.)
3089
+ const lost = () => die('another pisha-host is starting on this machine: nothing to do', UNDER_SERVICE ? 1 : 2)
3090
+ // Linked into place whole: nobody can read it empty and take it for one left behind.
3091
+ const tmp = `${PID_FILE}.${process.pid}.tmp`
3092
+ writeFileSync(tmp, `${process.pid}\n`, { mode: 0o600 })
3093
+ const claim = () => { try { linkSync(tmp, PID_FILE) } catch (err) { if (err.code === 'EEXIST') throw err; writeFileSync(PID_FILE, `${process.pid}\n`, { mode: 0o600, flag: 'wx' }) } }
3094
+ try {
3095
+ try { claim() } catch (err) {
3096
+ // One left behind is replaced; another that just took it, not.
3097
+ if (err.code !== 'EEXIST' || runningInstance()) lost()
3098
+ rmSync(PID_FILE, { force: true })
3099
+ try { claim() } catch { lost() }
3100
+ }
3101
+ } finally { rmSync(tmp, { force: true }) }
3102
+ // Whoever removed one left behind may have removed this one: the last still there stays.
3103
+ await new Promise(r => setTimeout(r, 200))
3104
+ try { if (readFileSync(PID_FILE, 'utf8').trim() !== String(process.pid)) lost() } catch { lost() }
3105
+ const release = () => { try { if (readFileSync(PID_FILE, 'utf8').trim() === String(process.pid)) rmSync(PID_FILE, { force: true }) } catch {} }
3106
+ process.on('exit', release)
3107
+ for (const sig of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(sig, () => { release(); process.exit(0) })
3108
+ }
3109
+
3110
+ // pisha-host update: this program as the server has it now, then the
3111
+ // plugin that goes with it and the service restarted (the sessions stay).
3112
+ // Why a program from the server isn't a release signed with our key, or ''.
3113
+ function unsignedReason(body, signature) {
3114
+ if (!RELEASE_PUBLIC_KEY) return 'this pisha-host has no release key to check it with'
3115
+ if (!signature) return 'the server has no signature for it'
3116
+ try {
3117
+ const key = createPublicKey({ key: Buffer.from(RELEASE_PUBLIC_KEY, 'base64url'), format: 'der', type: 'spki' })
3118
+ // (One per line: while a new key takes over, a release is signed with both.)
3119
+ return signature.split(/\s+/).some(s => verify(null, body, key, Buffer.from(s, 'base64url'))) ? '' : 'its signature does not match'
3120
+ } catch {
3121
+ return 'its signature can\'t be read'
3122
+ }
3123
+ }
3124
+
3125
+ async function update({ allowUnsigned = false, allowDowngrade = false } = {}) {
3126
+ const creds = readJson(CREDENTIALS_FILE, null)
3127
+ if (!creds?.server) die('this machine is not enrolled: there is no server to update from', 2)
3128
+ checkScheme(creds.server, creds.insecure === true)
3129
+ let body
3130
+ try {
3131
+ const res = await fetch(`${creds.server}/host/pisha-host.mjs`, { redirect: 'error', signal: AbortSignal.timeout(60_000) })
3132
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
3133
+ body = Buffer.from(await res.arrayBuffer())
3134
+ } catch (err) { die(`cannot download pisha-host from ${creds.server}: ${err.cause?.message ?? err.message}`) }
3135
+ // What is about to run here comes from the server: only a signed release,
3136
+ // and not an older one (it could bring back what a later one fixed).
3137
+ let signature = ''
3138
+ try {
3139
+ const res = await fetch(`${creds.server}/host/pisha-host.mjs.sig`, { redirect: 'error', signal: AbortSignal.timeout(60_000) })
3140
+ if (res.ok) signature = (await res.text()).slice(0, 1024).trim()
3141
+ } catch {}
3142
+ const unsigned = unsignedReason(body, signature)
3143
+ if (unsigned && !allowUnsigned) die(`not installing what ${creds.server} sent: ${unsigned}. Nothing was changed. If you built or trust this server's copy yourself, run: ${cli()} update --allow-unsigned`)
3144
+ if (unsigned) log(`⚠️ installing an unsigned pisha-host because you asked to: ${unsigned}`)
3145
+ const v = body.length < 4 * 1024 * 1024 ? /^const VERSION = '([0-9][0-9A-Za-z.-]{0,30})'$/m.exec(body.toString('utf8'))?.[1] : null
3146
+ if (!v) die('the server did not send pisha-host: nothing was changed')
3147
+ if (olderVersion(v, VERSION) && !allowDowngrade) die(`the server has pisha-host ${plain(v)}, older than this one (${VERSION}): nothing was changed. If you did mean to go back, run: ${cli()} update --allow-downgrade`)
3148
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 })
3149
+ // (.mjs: what is checked is read as what it will run as.)
3150
+ const tmp = `${INSTALLED_SCRIPT}.${process.pid}.tmp.mjs`
3151
+ writeFileSync(tmp, body, { mode: 0o600, flag: 'wx' })
3152
+ try { execFileSync(process.execPath, ['--check', tmp], { stdio: 'ignore', timeout: 60_000 }) } catch {
3153
+ rmSync(tmp, { force: true })
3154
+ die('what the server sent is not a program that can run: nothing was changed')
3155
+ }
3156
+ // The copy this replaces stays next to it, to go back to.
3157
+ const backup = `${INSTALLED_SCRIPT}.bak`
3158
+ if (existsSync(INSTALLED_SCRIPT)) copyFileSync(INSTALLED_SCRIPT, backup)
3159
+ renameSync(tmp, INSTALLED_SCRIPT)
3160
+ log(v === VERSION ? `pisha-host ${v} is the server's version` : `pisha-host updated: ${VERSION} → ${plain(v)}`)
3161
+ // (The new copy does the rest: its plugin version, its service file.)
3162
+ const failed = []
3163
+ const again = args => { try { execFileSync(process.execPath, [INSTALLED_SCRIPT, ...(COMPANY ? [`--company=${COMPANY}`] : []), ...args], { stdio: 'inherit', timeout: 600_000 }) } catch { failed.push(args[0]) } }
3164
+ again(['plugin'])
3165
+ const other = someoneElsesService()
3166
+ if (other) log(`the service on this machine (${other}) runs another pisha-host: left as it is`)
3167
+ else if (existsSync(serviceFile().path)) again(['service'])
3168
+ else if (runningInstance()) log('restart pisha-host to use the new version')
3169
+ try { installLauncher() } catch {}
3170
+ if (failed.length) die(`the update is installed, but this step failed: ${failed.join(', ')}. Run "${cli()} ${failed[0]}" to try again${existsSync(backup) ? `; the previous program is in ${backup}` : ''}`)
3171
+ }
3172
+
3173
+ // settings.json written by an older version: what were only its defaults
3174
+ // then become today's (once; "settings_version" says it was done). Up to
3175
+ // 0.0.2 every file was written with "allow_resume": false, the old default;
3176
+ // up to 0.0.7, true, which now follows allow_input.
3177
+ const SETTINGS_VERSION = 4
3178
+ function migrateSettings() {
3179
+ let raw
3180
+ try { raw = JSON.parse(readFileSync(SETTINGS_FILE, 'utf8')) } catch { return }
3181
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw) || raw.settings_version >= SETTINGS_VERSION) return
3182
+ if (raw.allow_resume === true && raw.settings_version === 3) delete raw.allow_resume
3183
+ if (raw.allow_resume === false && !Number.isInteger(raw.settings_version)) { delete raw.allow_resume; log('settings.json: continuing the last conversation is now allowed (the new default; set "allow_resume": false to turn it off)') }
3184
+ raw.settings_version = SETTINGS_VERSION
3185
+ try { writeJson(SETTINGS_FILE, raw) } catch {}
3186
+ }
3187
+
3188
+ // --allow-home / --no-allow-home: the home folder itself as a place for
3189
+ // sessions (kept in settings.json, so the service keeps it too).
3190
+ function setAllowHome(on) {
3191
+ if (on && folderOfAnotherCompany(realOr(HOME))) throw new Error('your home folder holds a folder of another company on this machine: it can\'t be allowed here')
3192
+ const s = rawSettings()
3193
+ s.allow_home = on
3194
+ s.folders = s.folders.filter(f => !isHome(realOr(f)))
3195
+ if (on) s.folders.push(HOME)
3196
+ writeJson(SETTINGS_FILE, s)
3197
+ if (on) log(`your home folder (${HOME}) is now allowed for sessions. Sessions opened there can reach all of this user's files; their permission prompts are answered only in their own terminal, never by a coordinator. To undo it: pisha-host --no-allow-home`)
3198
+ else log('your home folder is no longer allowed for sessions')
3199
+ }
3200
+
3201
+ async function main() {
3202
+ if (platform() === 'win32') die('pisha-host does not run on native Windows (it needs tmux). Run it inside WSL, for example Ubuntu, together with Claude Code: see "Windows (WSL)" in docs/reference.md.')
3203
+ const argv = process.argv.slice(2).filter(a => !a.startsWith('--company='))
3204
+ if (['-h', '--help', 'help'].includes(argv[0])) return process.stdout.write(USAGE)
3205
+ if (['-v', '--version', 'version'].includes(argv[0])) return process.stdout.write(`pisha-host ${VERSION}\n`)
3206
+ migrateSettings()
3207
+ const flags = new Set(argv.filter(a => a.startsWith('--')))
3208
+ const [cmd = 'run', ...rest] = argv.filter(a => !a.startsWith('--'))
3209
+ const known = ['--allow-home', '--no-allow-home', '--insecure', '--no-plugin', '--no-service', '--allow-unsigned', '--allow-downgrade', '--close-sessions', '--keep-sessions']
3210
+ const serverKeyArg = argv.find(a => a.startsWith('--server-key='))?.slice('--server-key='.length)
3211
+ if (serverKeyArg !== undefined && !/^[0-9a-f]{64}$/.test(serverKeyArg)) die('--server-key must be the 64 hex characters the dashboard gives', 2)
3212
+ for (const f of flags) if (!known.includes(f) && !f.startsWith('--server-key=') && !f.startsWith('--code-file=')) die(`unknown option ${plain(f)}\n\n${USAGE}`, 2)
3213
+ if (flags.has('--allow-home') && flags.has('--no-allow-home')) die('--allow-home or --no-allow-home, not both', 2)
3214
+ if (flags.has('--allow-home') || flags.has('--no-allow-home')) {
3215
+ try { setAllowHome(flags.has('--allow-home')) } catch (err) { die(err.message, 2) }
3216
+ // Already running (as the service, say): it reads its settings as it goes.
3217
+ const other = runningInstance()
3218
+ if (cmd === 'run' && other) return log(`pisha-host is already running (pid ${other}): it uses this from now on`)
3219
+ }
3220
+ if (cmd === 'folders') return folders(rest[0], rest[1])
3221
+ if (cmd === 'service') return service(rest[0])
3222
+ if (cmd === 'update') return update({ allowUnsigned: flags.has('--allow-unsigned'), allowDowngrade: flags.has('--allow-downgrade') })
3223
+ if (cmd === 'forget') {
3224
+ // What is open here would go to whichever server this copy joins next.
3225
+ const open = (await listTerminals()).map(t => t.id)
3226
+ if (open.length && !flags.has('--close-sessions')) die(`sessions are still open here (${open.map(plain).join(', ')}): the next server this copy joins would get them. Close them first, or run: ${cli()} forget --close-sessions`, 2)
3227
+ for (const id of open) await killTerminal(id)
3228
+ rmSync(CREDENTIALS_FILE, { force: true })
3229
+ log('credential deleted')
3230
+ if (runningInstance()) log('pisha-host is still running with it, and stays connected until it is stopped')
3231
+ if (loadSettings().folders.length) log(`the allowed folders stay in ${SETTINGS_FILE}: the next server gets them too`)
3232
+ return
3233
+ }
3234
+ if (cmd === 'status') {
3235
+ const creds = readJson(CREDENTIALS_FILE, null)
3236
+ process.stdout.write(JSON.stringify({ server: creds?.server ?? null, tmux_socket: TMUX_SOCKET, owner: OWNER_TAG, ...(COMPANY ? { company: COMPANY } : {}), running: runningInstance() ? { pid: runningInstance() } : false, service: existsSync(serviceFile().path) ? serviceFile().path : null, settings: loadSettings(), terminals: await listTerminals() }, null, 2) + '\n')
3237
+ return
3238
+ }
3239
+ if (typeof WebSocket !== 'function') die(`Node ${process.version} has no WebSocket: use Node 22 or newer`, 2)
3240
+ const tv = await tmuxVersion()
3241
+ if (tv && (tv.major < 3 || (tv.major === 3 && tv.minor < 2))) die(`${tv.text} is too old: pisha-host needs tmux 3.2 or newer`, 2)
3242
+ CLAUDE_VERSION = claudeCode.programOrNull() ? await claudeCode.version(claudeCode.programOrNull()) : null
3243
+ await readTypedVersions()
3244
+ if (cmd === 'plugin') {
3245
+ // In each agent this machine has.
3246
+ let failed = false
3247
+ if (CLAUDE_VERSION || !Object.values(TYPED_VERSIONS).some(Boolean)) {
3248
+ try { const st = await claudeCode.plugin.ensure({ update: true }); log(`Pisha plugin ${st.version ?? ''} is installed and up to date in Claude Code.`) }
3249
+ catch (err) { failed = true; log(`${err.message.split('\n')[0]}\nInstall it by hand with: ${claudeCode.plugin.commands}`) }
3250
+ }
3251
+ for (const [id, a] of Object.entries(TYPED)) {
3252
+ if (!TYPED_VERSIONS[id]) continue
3253
+ try { const st = await a.plugin.ensure({ update: true }); log(`Pisha plugin ${st.version ?? ''} is installed and up to date in ${a.name}.`) }
3254
+ catch (err) { failed = true; log(`${err.message.split('\n')[0]}\nInstall it by hand with: ${a.plugin.commands}`) }
3255
+ }
3256
+ if (failed) die('the plugin could not be installed everywhere')
3257
+ return log('Restart open sessions to use a new version.')
3258
+ }
3259
+ if (cmd === 'enroll') {
3260
+ // Enrolled and left running as a service: nothing more to do here.
3261
+ // (In a file, so it is in no program's arguments: read and gone at once.)
3262
+ const codeFile = argv.find(a => a.startsWith('--code-file='))?.slice('--code-file='.length)
3263
+ let code = rest[1]
3264
+ if (codeFile) {
3265
+ try { code = readFileSync(codeFile, 'utf8').trim(); rmSync(codeFile, { force: true }) } catch (err) { die(`--code-file: ${plain(err.message)}`, 2) }
3266
+ }
3267
+ if (await enroll(rest[0], code, { plugin: !flags.has('--no-plugin'), insecure: flags.has('--insecure'), service: !flags.has('--no-service'), serverKey: serverKeyArg ?? null, keepSessions: flags.has('--keep-sessions') })) return
3268
+ }
3269
+ else if (cmd !== 'run') die(`unknown command "${plain(cmd)}"\n\n${USAGE}`, 2)
3270
+ {
3271
+ const other = runningInstance()
3272
+ // A service waits its turn: one started by hand may end, and nothing would start it after that.
3273
+ if (other && UNDER_SERVICE) {
3274
+ log(`another pisha-host is running here (pid ${other}): waiting for it to end`)
3275
+ while (runningInstance()) await new Promise(r => setTimeout(r, 10_000))
3276
+ } else if (other) die(`pisha-host is already running here for this company (pid ${other}${existsSync(serviceFile().path) ? ', as a service' : ''}): nothing to do. To stop the service: ${cli()} service remove`, 2)
3277
+ await claimInstance()
3278
+ }
3279
+ ensureClaudeHome()
3280
+ // (Exit 2 is "not enrolled", for good. A file that can't be read just now is not that.)
3281
+ let creds = null
3282
+ try { creds = JSON.parse(readFileSync(CREDENTIALS_FILE, 'utf8')) } catch (err) { if (err.code !== 'ENOENT') die(`cannot read ${CREDENTIALS_FILE}: ${err.message}`, 1) }
3283
+ if (creds?.server) checkScheme(creds.server, creds.insecure === true)
3284
+ if (creds?.insecure) claudeCode.plugin.acceptPlainHttp(creds.server)
3285
+ if (!creds?.server || !creds?.secret) die(`this machine is not enrolled yet. In the dashboard, open Machines → + Add machine and run the command it shows.\n\n${USAGE}`, 2)
3286
+ if (!tv) log(`⚠️ tmux is not installed: sessions cannot be opened until it is (${TMUX_INSTALL}).`)
3287
+ PLUGIN = await claudeCode.plugin.status()
3288
+ if (PLUGIN && !PLUGIN.installed) log(`⚠️ the Pisha plugin is not installed in Claude Code: sessions cannot be opened until it is. Run: ${cli()} plugin`)
3289
+ // Keep what the dashboard shows about the plugin current (installed or updated by hand).
3290
+ setInterval(async () => { const st = await claudeCode.plugin.status(); if (st) PLUGIN = st; await readTypedVersions() }, 5 * 60_000).unref()
3291
+ // What arrives for Codex and Grok sessions is typed in their terminals.
3292
+ setInterval(typePending, 1000).unref()
3293
+ await connect(creds)
3294
+ }
3295
+
3296
+ // (Node runs a program by its real path: reached through a link, like anything
3297
+ // in /var on macOS, it is still this one.)
3298
+ if (process.argv[1] && realOr(process.argv[1]) === realOr(fileURLToPath(import.meta.url))) {
3299
+ // A bad message must never take the host down.
3300
+ process.on('unhandledRejection', err => log(`error: ${err?.message ?? err}`))
3301
+ process.on('uncaughtException', err => log(`error: ${err?.stack ?? err}`))
3302
+ main().catch(err => die(err.stack ?? err.message))
3303
+ }