afield 0.0.0-stage → 0.1.0

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 (43) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +165 -2
  3. package/afield +214 -0
  4. package/package.json +42 -4
  5. package/pi-extensions/afield-session.ts +59 -0
  6. package/pi-extensions/elastic-footer.ts +167 -0
  7. package/server/attach.js +264 -0
  8. package/server/auth.js +169 -0
  9. package/server/client.js +64 -0
  10. package/server/control.js +65 -0
  11. package/server/identity.js +45 -0
  12. package/server/index.js +375 -0
  13. package/server/mirror.js +159 -0
  14. package/server/origin.js +51 -0
  15. package/server/picker.js +187 -0
  16. package/server/places.js +348 -0
  17. package/server/protocol.js +51 -0
  18. package/server/quick-tunnel.js +40 -0
  19. package/server/registry.js +190 -0
  20. package/server/serve.js +100 -0
  21. package/server/session-main.js +27 -0
  22. package/server/session.js +112 -0
  23. package/server/supervisor.js +432 -0
  24. package/server/viewer.js +65 -0
  25. package/src/app.js +1683 -0
  26. package/src/apple-touch-icon.png +0 -0
  27. package/src/index.html +96 -0
  28. package/src/keys.js +59 -0
  29. package/src/pi-icon.svg +13 -0
  30. package/src/style.css +559 -0
  31. package/src/transport.js +153 -0
  32. package/src/ttyd.js +51 -0
  33. package/src/viewport.js +168 -0
  34. package/tsconfig.json +14 -0
  35. package/vendor/wterm/LICENSE +191 -0
  36. package/vendor/wterm/README.md +7 -0
  37. package/vendor/wterm/packages/@wterm/dom/src/debug.ts +347 -0
  38. package/vendor/wterm/packages/@wterm/dom/src/hyperlink.ts +8 -0
  39. package/vendor/wterm/packages/@wterm/dom/src/index.ts +13 -0
  40. package/vendor/wterm/packages/@wterm/dom/src/input.ts +662 -0
  41. package/vendor/wterm/packages/@wterm/dom/src/renderer.ts +725 -0
  42. package/vendor/wterm/packages/@wterm/dom/src/terminal.css +195 -0
  43. package/vendor/wterm/packages/@wterm/dom/src/wterm.ts +609 -0
@@ -0,0 +1,190 @@
1
+ // Live PTYs have their own stable IDs. Pi's conversation ID is only the
2
+ // initial transcript to open; /new and /resume can change it in the same PTY.
3
+ import { fork } from 'node:child_process'
4
+ import { randomUUID } from 'node:crypto'
5
+ import { readFileSync, rmSync, writeFileSync } from 'node:fs'
6
+ import { rm } from 'node:fs/promises'
7
+ import { join } from 'node:path'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { DEFAULT_SCROLLBACK } from './protocol.js'
10
+
11
+ const KILL_GRACE_MS = 2_000
12
+ // How many sessions may run at once. The one place the pool size is decided.
13
+ const CAP = 10
14
+ const SESSION_EXTENSION = fileURLToPath(new URL('../pi-extensions/afield-session.ts', import.meta.url))
15
+ // What each session's child process runs.
16
+ const SESSION_MAIN = fileURLToPath(new URL('./session-main.js', import.meta.url))
17
+
18
+ export class Registry {
19
+ #children = new Map() // processId -> child
20
+ #sessionMain
21
+ #pi
22
+ #shell
23
+ #socketDir
24
+ #cap
25
+ #scrollback
26
+ #count = 0
27
+ // Every process ID this registry hands out starts with this, so it can tell
28
+ // its own from those of an earlier run of the server.
29
+ #boot = randomUUID().slice(0, 8)
30
+
31
+ /** A session is one of two kinds. `pi` is `{ command, args }`, the pi to run:
32
+ * it owns every conversation. `shell` is the path of a login shell, a plain
33
+ * terminal with no conversation. Either may be absent, and that kind is
34
+ * then not offered. */
35
+ constructor({ sessionMain = SESSION_MAIN, pi, shell, socketDir, cap = CAP, scrollback = DEFAULT_SCROLLBACK }) {
36
+ this.#sessionMain = sessionMain
37
+ this.#pi = pi
38
+ this.#shell = shell
39
+ this.#socketDir = socketDir
40
+ this.#cap = cap
41
+ this.#scrollback = scrollback
42
+ }
43
+
44
+ /** How many sessions may run at once. */
45
+ get cap() { return this.#cap }
46
+
47
+ /** The kinds of session a start may ask for. */
48
+ get kinds() { return [...(this.#pi ? ['pi'] : []), ...(this.#shell ? ['shell'] : [])] }
49
+
50
+ child(processId) { return this.#children.get(processId) }
51
+
52
+ /** Whether this registry handed out the ID, running or long since ended. */
53
+ startedHere(processId) { return processId.startsWith(`${this.#boot}-`) }
54
+
55
+ /** The conversation this PTY currently has open. */
56
+ current(child) {
57
+ return JSON.parse(readFileSync(child.identityPath, 'utf8'))
58
+ }
59
+
60
+ owner(sessionId, cwd) {
61
+ return [...this.#children.values()].find(child => {
62
+ const current = this.current(child)
63
+ return current.id === sessionId && current.cwd === cwd
64
+ })
65
+ }
66
+
67
+ watch(processId, fn) {
68
+ const child = this.child(processId)
69
+ if (!child) { fn('terminal exited'); return () => {} }
70
+ child.sockets.push(fn)
71
+ return () => {
72
+ const at = child.sockets.indexOf(fn)
73
+ if (at === -1) return
74
+ child.sockets.splice(at, 1)
75
+ child.seenAt = Date.now()
76
+ }
77
+ }
78
+
79
+ running() {
80
+ return [...this.#children.values()].sort((a, b) => a.joinedAt - b.joinedAt)
81
+ }
82
+
83
+ /** Join a current conversation if it is live, otherwise start another PTY.
84
+ * Null when the cap is already reached: ending something is the user's
85
+ * call, made from the pick list, never this registry's. */
86
+ async ensure(sessionId, cwd, options) {
87
+ const existing = this.owner(sessionId, cwd)
88
+ if (existing) {
89
+ existing.joinedAt = Date.now()
90
+ return existing
91
+ }
92
+ return this.start(sessionId, cwd, options)
93
+ }
94
+
95
+ /** A shell's `sessionId` names no conversation; it only keeps the session
96
+ * apart from every other, so nothing downstream needs telling the kinds apart.
97
+ *
98
+ * `resume` says the conversation named by `sessionId` already exists — a
99
+ * saved one being reopened, from the menu or after a restart — and is the
100
+ * one case pi is handed `--session-id`, which opens that transcript. A
101
+ * fresh session is not: pi's own lookup
102
+ * would only warn that the id just minted for it is nowhere in the store,
103
+ * so pi mints the conversation id itself and the session extension reports
104
+ * the real one once it is open. */
105
+ async start(sessionId, cwd, { kind = 'pi', resume = false } = {}) {
106
+ if (!this.kinds.includes(kind)) throw new Error(`no ${kind} sessions here`)
107
+ if (this.#children.size >= this.#cap) return null
108
+ const n = ++this.#count
109
+ const processId = `${this.#boot}-${n}`
110
+ // Short, unique names within this supervisor's private directory. Neither
111
+ // transport nor runtime identity is derived from a Pi conversation ID.
112
+ const socketPath = join(this.#socketDir, `afield-${n}.sock`)
113
+ const identityPath = join(this.#socketDir, `afield-${n}.identity`)
114
+ // For a fresh pi this is afield's own handle, standing in until the
115
+ // session extension writes the conversation pi actually opened.
116
+ writeFileSync(identityPath, JSON.stringify({ id: sessionId, cwd, at: Date.now() }))
117
+ const [command, ...runtimeArgs] = kind === 'pi'
118
+ ? [this.#pi.command, ...this.#pi.args, '-e', SESSION_EXTENSION, ...(resume ? ['--session-id', sessionId] : [])]
119
+ : [this.#shell, '-l']
120
+ const startedAt = Date.now()
121
+ let proc
122
+ try {
123
+ proc = fork(this.#sessionMain, [socketPath, cwd, String(this.#scrollback), command, ...runtimeArgs], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'], env: { ...process.env, AFIELD_IDENTITY: identityPath, AFIELD_PROCESS_ID: processId, AFIELD_STARTED_AT: String(startedAt) } })
124
+ } catch (err) {
125
+ // spawn() itself failed -- no process, no exit to clean up after -- and
126
+ // the identity file written above would be the one thing left claiming
127
+ // this session exists. It is thrown on to the caller, which says it in
128
+ // as many words rather than answering as if the request were at fault.
129
+ rmSync(identityPath, { force: true })
130
+ throw err
131
+ }
132
+ const joinedAt = Date.now()
133
+ const child = { processId, sessionId, kind, proc, socketPath, identityPath, joinedAt, startedAt, seenAt: joinedAt, lastOutputAt: joinedAt, working: false, stoppedAt: 0, foreground: null, sockets: [] }
134
+ this.#children.set(processId, child)
135
+ let settled = false
136
+ let resolveGone
137
+ child.gone = new Promise(resolve => { resolveGone = resolve })
138
+ // 'error' and 'exit' can both arrive for one child, and the rest of the
139
+ // supervisor reads this map as "which PTYs exist": settling twice would
140
+ // drop an entry (and its identity file) out from under a live child.
141
+ const settle = () => {
142
+ if (settled) return
143
+ settled = true
144
+ if (this.child(processId) === child) this.#children.delete(processId)
145
+ for (const fn of child.sockets.splice(0)) fn(child.endReason ?? `${kind} exited`)
146
+ // The files go before `gone` resolves: a stale identity file still in
147
+ // the directory is one the next /resume would read as a live owner.
148
+ Promise.all([rm(socketPath, { force: true }), rm(identityPath, { force: true }), rm(`${identityPath}.tmp`, { force: true })])
149
+ .catch(err => console.error(`server: could not clean up terminal ${processId}`, err))
150
+ .finally(resolveGone)
151
+ }
152
+ proc.on('exit', settle)
153
+ // The child says when its PTY last printed, which orders the full-pool
154
+ // picker. It also says
155
+ // when its program starts and stops working, and stopping is what makes it
156
+ // unread.
157
+ proc.on('message', msg => {
158
+ if (msg.afield === 'activity') child.lastOutputAt = msg.at
159
+ if (msg.afield === 'foreground') child.foreground = msg.name
160
+ if (msg.afield === 'working') {
161
+ child.working = msg.working
162
+ if (!msg.working) child.stoppedAt = msg.stoppedAt
163
+ }
164
+ })
165
+ proc.on('error', err => {
166
+ // No pid means the fork itself failed and there is no exit to come.
167
+ // Anything else is a live child reporting a signal or IPC problem, which
168
+ // is not a reason to forget that it exists.
169
+ if (proc.pid) return void console.error(`server: terminal ${processId} reported an error`, err)
170
+ console.error(`server: terminal ${processId} could not start`, err)
171
+ settle()
172
+ })
173
+ return child
174
+ }
175
+
176
+ async end(processId, reason = 'ended by a terminal') {
177
+ const child = this.child(processId)
178
+ if (!child) return
179
+ child.endReason = reason
180
+ child.proc.kill('SIGTERM')
181
+ const escalate = setTimeout(() => child.proc.kill('SIGKILL'), KILL_GRACE_MS)
182
+ escalate.unref()
183
+ await child.gone
184
+ clearTimeout(escalate)
185
+ }
186
+
187
+ async endAll() {
188
+ await Promise.all([...this.#children.values()].map(child => this.end(child.processId, 'server stopped')))
189
+ }
190
+ }
@@ -0,0 +1,100 @@
1
+ // `afield serve`: start the supervisor, which holds every live session in the
2
+ // background until it is stopped, and print how to reach it.
3
+ import { ensureKey } from './auth.js'
4
+ import { startQuickTunnel } from './quick-tunnel.js'
5
+ import { createSupervisor } from './supervisor.js'
6
+ import { isIP } from 'node:net'
7
+ import { networkInterfaces } from 'node:os'
8
+ import { renderUnicodeCompact } from 'uqr'
9
+
10
+ // Drawn light-on-dark, the colours renderUnicodeCompact assumes, and pinned
11
+ // there so the code still scans in a light terminal.
12
+ const qr = text => renderUnicodeCompact(text, { border: 2 }).split('\n')
13
+ .map(line => ` \x1b[97;40m${line}\x1b[0m`).join('\n')
14
+
15
+ const urlHost = address => isIP(address) === 6 ? `[${address}]` : address
16
+
17
+ /** Options arrive checked: see afield. */
18
+ export async function serve({ port, bind, hostname, quickTunnel, cap, theme, scrollback, newDir, signIn, pi, shell }) {
19
+ // Whoever reaches the port gets a shell, so every connection signs in unless
20
+ // told not to.
21
+ const key = signIn ? ensureKey() : undefined
22
+ const wildcard = bind === '0.0.0.0' || bind === '::'
23
+ // Only decides what to print: a loopback address is no use to a phone,
24
+ // and a name in front of one is a proxy's, which serves https.
25
+ const local = bind === 'localhost' || bind === '::1' || bind.startsWith('127.')
26
+
27
+ const printLinks = (name, port) => {
28
+ if (key) printPairing(name, port)
29
+ console.log('\nCtrl+C to shutdown server')
30
+ }
31
+ // The name and port of the last pairing key's links, for the next one.
32
+ let pairedAt
33
+ const printPairing = (name, port) => {
34
+ pairedAt = [name, port]
35
+ const pairing = supervisor.pair()
36
+ // A wildcard address is not one a phone can open, so name the real ones.
37
+ const bases = name ? [local ? `https://${name}` : `http://${name}:${port}`]
38
+ : wildcard
39
+ ? Object.values(networkInterfaces()).flat()
40
+ .filter(net => net?.family === 'IPv4' && !net.internal).map(net => `http://${net.address}:${port}`)
41
+ : [`http://${urlHost(bind)}:${port}`]
42
+ const links = bases.map(base => `${base}/login#${pairing}`)
43
+ if (links.length > 0 && (name || !local)) console.log(`\n${qr(links[0])}\n`)
44
+ for (const link of links) console.log(` ${link}`)
45
+ console.log(`pairing key: ${pairing} (signs in one browser)`)
46
+ }
47
+
48
+ let tunnel
49
+ // The one way out, whatever the reason: the tunnel goes first, so nothing
50
+ // public is left pointing at a port this no longer holds.
51
+ const shutdown = exitCode => {
52
+ tunnel?.stop()
53
+ return supervisor.close().then(() => process.exit(exitCode))
54
+ }
55
+
56
+ const supervisor = createSupervisor({
57
+ port,
58
+ cap,
59
+ bind,
60
+ hostname,
61
+ theme,
62
+ scrollback,
63
+ newDir,
64
+ key,
65
+ pi,
66
+ shell,
67
+ onListen: ({ port, address }) => {
68
+ console.log(`listening on http://${urlHost(bind)}:${port}`)
69
+ if (wildcard) console.error('Warning: Traffic is unencrypted on your network. Only use on networks you trust.')
70
+ if (!quickTunnel) return printLinks(hostname, port)
71
+
72
+ console.log('\n\nNOTICE: --quick-tunnel is meant for trying afield out. For better security and\n' +
73
+ ' reliability, use Tailscale or a Cloudflare tunnel on your own domain;\n' +
74
+ ' see Remote Access in README.md for more.\n\n')
75
+ console.log('starting a Cloudflare quick tunnel...')
76
+ tunnel = startQuickTunnel(`http://${urlHost(address)}:${port}`, {
77
+ onName: name => {
78
+ supervisor.setHostname(name)
79
+ console.log(`tunnel: https://${name} (a new name can take a minute to start working)`)
80
+ printLinks(name, port)
81
+ },
82
+ onExit: detail => {
83
+ console.error(`quick tunnel: ${detail}`)
84
+ shutdown(1)
85
+ },
86
+ })
87
+ },
88
+ onPaired: () => {
89
+ console.log('\nA browser signed in. Next pairing key:')
90
+ printPairing(...pairedAt)
91
+ },
92
+ onExit: ({ exitCode }) => shutdown(exitCode ?? 0),
93
+ })
94
+
95
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
96
+ process.on(signal, () => shutdown(0))
97
+ }
98
+ // A crash skips shutdown(), and would leave the tunnel up.
99
+ process.on('exit', () => tunnel?.stop())
100
+ }
@@ -0,0 +1,27 @@
1
+ // One session's child process: server/registry.js forks this to serve one
2
+ // PTY on a Unix socket (server/index.js). Nothing outside the supervisor's own
3
+ // process tree is meant to run it.
4
+ import { createTerminalServer } from './index.js'
5
+
6
+ const [socketPath, cwd, scrollback, command, ...args] = process.argv.slice(2)
7
+
8
+ const server = createTerminalServer({
9
+ socketPath,
10
+ cwd,
11
+ scrollback: Number(scrollback),
12
+ command,
13
+ args,
14
+ // A session this holds ending — pi exiting on its own — is the session
15
+ // ending, same as it always was; the supervisor learns of it when this
16
+ // process exits and its socket stops answering.
17
+ onExit: ({ exitCode }) => server.close().then(() => process.exit(exitCode ?? 0)),
18
+ })
19
+ for (const signal of ['SIGINT', 'SIGTERM']) {
20
+ process.on(signal, () => server.close().then(() => process.exit(0)))
21
+ }
22
+ // The registry spawns this over fork(), which wires up an IPC channel for
23
+ // nothing else but this: the channel closing is how a child notices the
24
+ // supervisor is gone even when it never got the chance to ask nicely first
25
+ // (a crash, or a signal aimed at the wrong pid) — the one case a plain
26
+ // SIGTERM/SIGINT handler cannot cover, since nothing sent one.
27
+ process.on('disconnect', () => server.close().then(() => process.exit(0)))
@@ -0,0 +1,112 @@
1
+ // One PTY, N viewers.
2
+ //
3
+ // The session owns pi and every byte it produces. Viewers come and go; the PTY
4
+ // does not notice. Nothing here may drop a byte for a viewer that is still
5
+ // attached — that is the whole reason this exists rather than dtach, which
6
+ // abandons the unwritten tail of a read when a client socket fills.
7
+ import { basename } from 'node:path'
8
+ import { spawn } from '@lydell/node-pty'
9
+
10
+ // pi renders relatively and re-renders its whole transcript on SIGWINCH, so a
11
+ // resize is expensive and gets more so as the conversation grows. Only send one
12
+ // when the size actually changes.
13
+ const same = (a, b) => a.cols === b.cols && a.rows === b.rows
14
+
15
+ // The narrowest viewer wins, so without a floor any viewer could hand everyone
16
+ // a 1x1 grid. Nothing legible is narrower than this.
17
+ const MIN_COLS = 20
18
+ const MIN_ROWS = 8
19
+
20
+ export class Session {
21
+ constructor({ command, args = [], cwd = process.cwd(), env = process.env, cols = 80, rows = 24 }) {
22
+ this.viewers = new Set()
23
+ this.size = { cols, rows }
24
+ this.exited = false
25
+ this.resizeFailing = false
26
+ this.onData = null
27
+ this.onExit = null
28
+ this.onResize = null
29
+
30
+ this.pty = spawn(command, args, {
31
+ name: 'xterm-256color',
32
+ cols,
33
+ rows,
34
+ cwd,
35
+ env,
36
+ // Bytes, not strings: a multi-byte sequence split across reads must not be
37
+ // decoded here — the VT parsers at both ends reassemble it.
38
+ encoding: null,
39
+ })
40
+ this.pty.onData(data => this.onData?.(data))
41
+ this.pty.onExit(({ exitCode, signal }) => {
42
+ this.exited = true
43
+ this.onExit?.({ exitCode, signal })
44
+ })
45
+ }
46
+
47
+ write(bytes) { this.pty.write(bytes) }
48
+
49
+ /**
50
+ * The narrowest viewer wins.
51
+ *
52
+ * This is a phone-first tool: a desktop showing a phone-width column is
53
+ * legible, a phone showing a desktop-width screen is not. It also makes the
54
+ * common case free — the phone is already the narrowest, so nothing resizes.
55
+ */
56
+ fit() {
57
+ // Viewers can outlive the program by the moment it takes to close them, and
58
+ // resizing a closed PTY throws EBADF from a timer, where it would take the
59
+ // whole server down.
60
+ if (this.exited || this.viewers.size === 0) return
61
+ let cols = Infinity
62
+ let rows = Infinity
63
+ for (const v of this.viewers) {
64
+ if (v.size.cols > 0) cols = Math.min(cols, v.size.cols)
65
+ if (v.size.rows > 0) rows = Math.min(rows, v.size.rows)
66
+ }
67
+ if (!Number.isFinite(cols) || !Number.isFinite(rows)) return
68
+
69
+ const next = { cols: Math.max(cols, MIN_COLS), rows: Math.max(rows, MIN_ROWS) }
70
+ if (!same(next, this.size)) {
71
+ try {
72
+ this.pty.resize(next.cols, next.rows)
73
+ } catch (err) {
74
+ // `exited` is only set once the async exit event lands, and kill()
75
+ // can close the fd before that arrives — a viewer's socket dropping in
76
+ // that window reaches here with a pty that is already gone in every
77
+ // sense but the flag. Committing `size` before the attempt would leave
78
+ // it claiming a size the pty never reached, and `same()` would then
79
+ // skip every future resize back to it — so it moves here, after. Logged
80
+ // once, not on every retry: every viewer disconnecting in that same
81
+ // narrow window hits this too, and it is already the expected shape of
82
+ // "the pty is gone", not a fresh fault each time.
83
+ if (!this.resizeFailing) { console.error('server: pty resize failed', err); this.resizeFailing = true }
84
+ return
85
+ }
86
+ this.resizeFailing = false
87
+ this.size = next
88
+ this.onResize?.(next)
89
+ }
90
+ }
91
+
92
+ add(viewer) {
93
+ this.viewers.add(viewer)
94
+ this.fit()
95
+ }
96
+
97
+ remove(viewer) {
98
+ this.viewers.delete(viewer)
99
+ if (this.viewers.size > 0) this.fit()
100
+ }
101
+
102
+ // node-pty defaults to SIGHUP, which pi handles but which is a surprising
103
+ // thing for Ctrl-C on the server to turn into. Say what we mean.
104
+ kill() { this.pty.kill('SIGTERM') }
105
+
106
+ /** The foreground program on this PTY, or null once gone or unreadable. */
107
+ foreground() {
108
+ const name = this.exited ? null : this.pty.process
109
+ // A login shell's name is prefixed with '-'.
110
+ return name ? basename(name).replace(/^-/, '') : null
111
+ }
112
+ }