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
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 Eli Dickinson
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,166 @@
1
- # Temporary Holding Version
1
+ # afield
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The full [pi coding agent](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) in a phone or browser.**
4
+
5
+ - `afield` runs a small server that streams the terminal.
6
+ - Full pi TUI, not a limited HTML/CSS interface. Custom extensions, commands, etc. should all work.
7
+ - Multiplayer: several devices can watch and type into a pi session at the same time.
8
+ - Connect from a browser/PWA or run `afield attach` on your computer to access the pi session in the terminal.
9
+ - Sessions can keep running while you're not connected, as long as the server stays up.
10
+ - Optional tabs for switching between multiple running pi sessions.
11
+ - Can also run a plain terminal or many other apps besides pi.
12
+
13
+
14
+ <p>
15
+ <img src="docs/screenshot-keyboard.png" width="300" alt="Terminal view with the iOS keyboard up: pi's transcript and own input box above the key bar">
16
+ &nbsp;
17
+ <img src="docs/screenshot-scrollback.png" width="300" alt="Scrolled back through a transcript, with a ↓ latest button offering the way back">
18
+ </p>
19
+
20
+ ## Requirements
21
+
22
+ - **Node 22+** on macOS or Linux.
23
+ - **Trusted tunnel/VPN/network** App does not have E2E encryption. Plan to use Tailscale, Cloudflare Tunnel, etc. in production.
24
+ - **pi** is not strictly required. Run `serve --no-pi` to offer only shell terminals to clients.
25
+
26
+ ## Getting started
27
+
28
+ In the folder you want pi to start in, run one of:
29
+ ```sh
30
+ # To test just on your local computer
31
+ npx afield
32
+
33
+ # To share with your network (not encrypted - trusted networks only!)
34
+ npx afield --bind 0.0.0.0
35
+
36
+ # To run through a disposable Cloudflare Tunnel
37
+ npx afield --quick-tunnel
38
+ ```
39
+
40
+ Leave that terminal open. Use the URL or QR code to access pi in a browser.
41
+
42
+ In another terminal run `npx afield attach` to access the pi session from the command line.
43
+
44
+ ## Remote access & security
45
+
46
+ Afield requires signing in by default, but the app does not provide end-to-end encryption nor a public relay service. You should use it with Tailscale, Cloudflare Tunnel, VPN, or similar to secure access.
47
+
48
+ - **Just trying it out:** `afield serve --quick-tunnel` gives a temporary public URL, no account needed. The address will change with each restart.
49
+ - **Public URL:** the app checks the Origin of client requests so the server needs to know the address of the HTTPS tunnel or proxy, `serve --hostname afield.example.com`
50
+
51
+ ### Remote access option: Tailscale
52
+
53
+ Install Tailscale on both devices. Bind the server to the tailnet address from `tailscale ip -4`, not to all interfaces:
54
+
55
+ ```sh
56
+ afield serve --bind <tailnet-IP>
57
+ ```
58
+
59
+ Scan the printed QR code. With MagicDNS add `--hostname <machine-name>`; the QR code then uses that name.
60
+
61
+ ### Remote access option: Cloudflare tunnel
62
+
63
+ For a Cloudflare tunnel you need `cloudflared` and a zone (domain) set up on Cloudflare. Once:
64
+
65
+ ```sh
66
+ cloudflared tunnel login
67
+ cloudflared tunnel create afield
68
+ cloudflared tunnel route dns afield pi.example.com
69
+ ```
70
+
71
+ Then, in two terminals:
72
+
73
+ ```sh
74
+ cloudflared tunnel run --url http://127.0.0.1:7681 afield
75
+ afield serve --hostname pi.example.com
76
+ ```
77
+
78
+ Signing in protects the connection, but I strongly recommend adding **Cloudflare Access** on top - it's free and makes the entire server inaccessible if you aren't authorized.
79
+
80
+ Behind a proxy, pass the public DNS name you will use with `--hostname` or set it with `AFIELD_HOSTNAME`. Browser connections require this name to match. (`afield attach` and non-browser clients don't care about the hostname, and IP addresses or `localhost` should work from anywhere.)
81
+
82
+
83
+ ### Signing in
84
+
85
+ Each browser signs in once with a **pairing key**. `serve` prints one with a QR code: scan it, or type the key into the sign-in page (capitals, spaces and dashes don't matter). A pairing key signs in one browser, and `serve` then prints the next.
86
+
87
+ Signed-in browsers stay signed in across server restarts. Their sign-in comes from a **server key** that is made on first use, kept in `~/.config/afield/key` (or under `$XDG_CONFIG_HOME`), and never shown. To sign every device out, run `afield reset-key` and restart the server. `serve --no-sign-in` lets every connection in.
88
+
89
+ Be careful with plain HTTP: with something like `--bind 0.0.0.0`, anyone who can see your network traffic can read the pairing key and the sign-in cookie.
90
+
91
+ ## Using afield
92
+
93
+ Run `afield --help` for every command and option. The core commands:
94
+
95
+ ```sh
96
+ afield # start the server
97
+ afield sessions # list running sessions and viewer counts
98
+ afield new # start a fresh pi in this folder and attach
99
+ afield new --shell # start a terminal running your $SHELL instead
100
+ afield attach NAME # join a session in this terminal, Ctrl-] detaches
101
+ afield end NAME # stop a session after confirmation
102
+ ```
103
+
104
+ Bare `afield` starts the server, the same as `afield serve`. `NAME` matches a session's label, folder, path or ID, ignoring case. Omit it to choose from a list, or give a number to select that row from `afield sessions`.
105
+
106
+ ### Sessions
107
+
108
+ - In the browser, use `≡` to start, join, switch, or end sessions.
109
+ - Sessions keep running when you leave, switch, or disconnect.
110
+ - New sessions default to the folder where you ran `serve`; `--new-dir DIR` changes this.
111
+ - Terminals are not saved after they exit.
112
+ - The default limit is 10 running sessions; `--cap N` changes it.
113
+
114
+ ### Phone controls
115
+
116
+ | Control | Action |
117
+ |---|---|
118
+ | `⌃`, `⇧`, `⌥` | Sticky modifiers. Tap `⌃`, then `c` for Ctrl-C |
119
+ | `⌨` | Toggle the keyboard |
120
+ | `≡` | Menu: Sessions, display options, and diagnostics |
121
+ | **↓ latest** | Jump to the newest output |
122
+
123
+ Drag to scroll. Hold Backspace or an arrow to repeat. `⚡` means connecting or disconnected; short disconnects preserve the screen and replay your keystrokes after reconnecting.
124
+
125
+ ### Configuration
126
+
127
+ `AFIELD_PORT`, `AFIELD_BIND`, `AFIELD_HOSTNAME`, `AFIELD_THEME` and `AFIELD_NEW_DIR` work like the matching flags. pi history is read from `~/.pi/agent/sessions`, or `PI_CODING_AGENT_SESSION_DIR` if set.
128
+
129
+ ## Limitations
130
+
131
+ - **No alternate screen app support** including vim and Claude Code.
132
+ - **Primarily tested on iPhone Safari and desktop Chrome/Firefox.** Android seems to work OK though.
133
+ - **Scrollback defaults to 10,000 lines** (`--scrollback N` to change), kept across reconnects. Exceeding 100k is likely to cause problems on mobile.
134
+ - **Viewers share one terminal size.** The narrowest connected viewer sets the width for everyone watching.
135
+ - **Stopping the server ends all sessions.** After a restart, an open page reopens the same conversation, minus any reply in progress.
136
+
137
+ ## Known issues
138
+
139
+ - **iPhone home-screen app: keyboard occassionally covers the terminal instead of shrinking it.** This is appears to be [a Safari bug](https://bugs.webkit.org/show_bug.cgi?id=218983). Rotate the phone again to fix it.
140
+
141
+ ## Optional pi footer extension
142
+
143
+ **Elastic footer** replaces pi's footer with one that fits a phone-width terminal. As the screen narrows it drops the cache token counts first, then the token counts, etc. It applies wherever pi runs, not just in afield. If you have installed afield with npm, you can add the extension like `pi install "$(npm root -g)/afield/pi-extensions/elastic-footer.ts"`
144
+
145
+ (The other extension, `afield-session.ts`, does not need to be installed. It is loaded automatically to help afield track what session a pi instance has open.)
146
+
147
+ ## Development
148
+
149
+ ```sh
150
+ git clone https://github.com/elidickinson/afield && cd afield
151
+ npm install
152
+ ./afield serve
153
+ ```
154
+
155
+ There is no build step. Client edits need a page reload. Server edits need a restart, which ends running sessions. Install extensions from `./pi-extensions/`.
156
+
157
+ ```sh
158
+ npm test # unit tests and snapshot round-trips
159
+ npm run typecheck # vendored TypeScript renderer
160
+ npm run test:e2e # WebKit with fake pi
161
+ npm run test:integrity # verify viewers receive no gaps
162
+ npm run test:smoke # real pi, no prompts or token costs
163
+ npm run test:real-pi # real pi, resized mid-draw
164
+ ```
165
+
166
+ See [design and architecture](docs/design.md) for how it works and why.
package/afield ADDED
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env node
2
+ // The entry point: reads the command line and runs one command. `serve` holds
3
+ // every session in the foreground until it is stopped (Ctrl-C here ends all of
4
+ // them at once); the other commands talk to a server that is already running.
5
+ import { attach } from './server/attach.js'
6
+ import { keyPath, resetKey } from './server/auth.js'
7
+ import { end, sessions, start } from './server/control.js'
8
+ import { serve } from './server/serve.js'
9
+ import { accessSync, constants, existsSync, readFileSync, statSync } from 'node:fs'
10
+ import { isIP } from 'node:net'
11
+ import { homedir } from 'node:os'
12
+ import { delimiter, join, resolve } from 'node:path'
13
+ import { parseArgs } from 'node:util'
14
+
15
+ const USAGE = `Usage: afield [command] [options] [-- program args...]
16
+
17
+ serve serve the terminal (the default with no command)
18
+ sessions list running sessions
19
+ attach [NAME] attach this terminal to a session; prompts if several match
20
+ attach - reattach to the last session attached from this machine
21
+ new [--shell] start a fresh pi or a terminal here, and attach to it
22
+ end [NAME] end a running session after confirmation (--yes skips it)
23
+ reset-key make a new server key, which signs every device out
24
+
25
+ Options
26
+
27
+ --bind ADDR listen on, or find the server at, one address
28
+ (default 127.0.0.1, or $AFIELD_BIND)
29
+ --port N default 7681, or $AFIELD_PORT
30
+ --version print the version
31
+
32
+ serve only
33
+
34
+ --hostname NAME the name a proxy in front of this presents, e.g. the
35
+ Cloudflare or tailnet hostname (or $AFIELD_HOSTNAME)
36
+ --quick-tunnel reach this from anywhere through a Cloudflare quick tunnel,
37
+ for trying afield out: a new random name every run
38
+ --cap N how many sessions run at once (default 10); at the limit,
39
+ starting or joining asks which running session to end
40
+ --theme NAME dark (default) or light, or $AFIELD_THEME
41
+ --scrollback N lines of history kept and re-sent on reconnect
42
+ (default 10000)
43
+ --new-dir DIR where the phone's "new session" starts (default: this
44
+ folder, or $AFIELD_NEW_DIR)
45
+ --no-pi offer only terminals, for a machine without pi
46
+ --no-sign-in let every connection in without a pairing key
47
+
48
+ The program after -- is what pi sessions run, pi by default:
49
+ afield serve -- pi --model MODEL
50
+
51
+ Loopback is the default, for this machine and for a tunnel or proxy running on it. Use --bind 0.0.0.0 to reach it from a phone on the same wifi.
52
+
53
+ Sessions keep running when you look away; Ctrl-C in the terminal serving them ends every session at once. NAME matches a session's label, folder, path or ID, or is a row number from \`afield sessions\`.
54
+
55
+ Every browser signs in once with a pairing key that serve prints, typed or scanned from its QR code. Each pairing key signs in one browser, and serve then prints the next. Signed-in browsers stay signed in until reset-key replaces the server key in ~/.config/afield/key and serve restarts.
56
+
57
+ Sockets are refused unless their Origin matches the address they connected to. Reaching the server by address needs nothing; by name needs --hostname.
58
+ `
59
+
60
+ const usageError = message => { console.error(`afield: ${message}`); process.exit(2) }
61
+ const die = message => { console.error(`afield: ${message}`); process.exit(1) }
62
+
63
+ // What finds a server; serve also listens there.
64
+ const where = {
65
+ bind: { type: 'string', default: process.env.AFIELD_BIND || '127.0.0.1' },
66
+ port: { type: 'string', default: process.env.AFIELD_PORT || '7681' },
67
+ }
68
+ const COMMANDS = {
69
+ serve: {
70
+ options: {
71
+ ...where,
72
+ hostname: { type: 'string', default: process.env.AFIELD_HOSTNAME || undefined },
73
+ 'quick-tunnel': { type: 'boolean' },
74
+ cap: { type: 'string' },
75
+ theme: { type: 'string', default: process.env.AFIELD_THEME || 'dark' },
76
+ scrollback: { type: 'string' },
77
+ 'new-dir': { type: 'string', default: process.env.AFIELD_NEW_DIR || '.' },
78
+ 'no-pi': { type: 'boolean' },
79
+ 'no-sign-in': { type: 'boolean' },
80
+ },
81
+ names: 0,
82
+ },
83
+ sessions: { options: where, names: 0 },
84
+ attach: { options: where, names: 1 },
85
+ new: { options: { ...where, shell: { type: 'boolean' } }, names: 0 },
86
+ end: { options: { ...where, yes: { type: 'boolean' } }, names: 1 },
87
+ 'reset-key': { options: {}, names: 0 },
88
+ }
89
+
90
+ // Everything after `--` belongs to the program, so a flag of its own (pi has
91
+ // its own --theme, say) never reads as one of ours.
92
+ const argv = process.argv.slice(2)
93
+ const split = argv.indexOf('--')
94
+ const ours = split === -1 ? argv : argv.slice(0, split)
95
+ const program = split === -1 ? [] : argv.slice(split + 1)
96
+ if (ours[0] === 'help') { console.log(USAGE); process.exit(0) }
97
+ const explicit = Object.hasOwn(COMMANDS, ours[0])
98
+ const cmd = explicit ? ours.shift() : 'serve'
99
+
100
+ let values, names
101
+ try {
102
+ ;({ values, positionals: names } = parseArgs({
103
+ args: ours,
104
+ options: { ...COMMANDS[cmd].options, help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' } },
105
+ allowPositionals: true,
106
+ }))
107
+ } catch (err) {
108
+ if (!err.code?.startsWith('ERR_PARSE_ARGS')) throw err
109
+ usageError(err.message)
110
+ }
111
+ if (values.help) { console.log(USAGE); process.exit(0) }
112
+ if (values.version) {
113
+ console.log(JSON.parse(readFileSync(new URL('./package.json', import.meta.url))).version)
114
+ process.exit(0)
115
+ }
116
+ const allowed = COMMANDS[cmd].names
117
+ if (names.length > allowed) {
118
+ const extra = names[allowed]
119
+ if (Object.hasOwn(COMMANDS, extra)) usageError(`the command goes first: afield ${extra} ...`)
120
+ if (!explicit) usageError(`unknown command: ${extra}`)
121
+ usageError(`${cmd} takes ${allowed ? 'at most one name' : 'no arguments'}`)
122
+ }
123
+ if (program.length > 0 && cmd !== 'serve') usageError('only serve runs a program (after --)')
124
+
125
+ // A typo would otherwise reach node-pty or xterm as NaN and fail somewhere far
126
+ // from the mistake.
127
+ const whole = name => {
128
+ const raw = values[name]
129
+ if (raw === undefined) return undefined
130
+ const n = Number(raw)
131
+ if (!Number.isInteger(n) || n < 0) usageError(`--${name} needs a whole number, got ${JSON.stringify(raw)}`)
132
+ return n
133
+ }
134
+
135
+ if (cmd === 'reset-key') {
136
+ resetKey()
137
+ console.log(`Made a new server key in ${keyPath()}. Restart serve to use it; that signs every device out.`)
138
+ } else if (cmd === 'serve') {
139
+ await serve(checkServe())
140
+ } else {
141
+ const url = `ws://${isIP(values.bind) === 6 ? `[${values.bind}]` : values.bind}:${whole('port')}`
142
+ if (cmd === 'sessions') await sessions(url)
143
+ else if (cmd === 'end') await end(url, { match: names[0], yes: values.yes })
144
+ else if (cmd === 'attach') {
145
+ await attach(names[0] === '-' ? { url: `${url}/ws`, previous: true } : { url: `${url}/ws`, match: names[0] })
146
+ } else {
147
+ const started = await start(url, { cwd: process.cwd(), kind: values.shell ? 'shell' : undefined })
148
+ if (started) await attach({ url: started.wsUrl, session: started.processId })
149
+ }
150
+ }
151
+
152
+ /** serve's options, checked here so a mistake is said before anything starts. */
153
+ function checkServe() {
154
+ const { bind, hostname, theme } = values
155
+ const [port, cap, scrollback] = ['port', 'cap', 'scrollback'].map(whole)
156
+ if (!['dark', 'light'].includes(theme)) usageError(`${theme} is not a theme (dark or light)`)
157
+
158
+ // A quoted or environment ~ reaches here unexpanded.
159
+ const newDir = resolve(values['new-dir'].replace(/^~(?=$|\/)/, homedir()))
160
+ if (!(existsSync(newDir) && statSync(newDir).isDirectory())) usageError(`no such directory: ${newDir}`)
161
+
162
+ // Terminals run your login shell, the one a desktop terminal would.
163
+ const shell = process.env.SHELL || undefined
164
+ let pi
165
+ if (values['no-pi']) {
166
+ if (program.length > 0) usageError('--no-pi takes no program')
167
+ if (!shell) usageError('--no-pi leaves only terminals, and there is no $SHELL for them to run')
168
+ } else {
169
+ const [command, ...args] = program.length > 0 ? program : ['pi']
170
+ // A program that cannot run is said here rather than on the phone, where
171
+ // node-pty's only sign of it is a session that exits at once. A path is
172
+ // made absolute, since sessions start in other folders.
173
+ if (command.includes('/')) {
174
+ if (!runnable(resolve(command))) die(`${resolve(command)} is not an executable file`)
175
+ pi = { command: resolve(command), args }
176
+ } else {
177
+ if (!process.env.PATH?.split(delimiter).some(dir => runnable(join(dir, command)))) {
178
+ die(`${command} is not on PATH${command === 'pi'
179
+ ? ' -- install it: npm install -g @earendil-works/pi-coding-agent, or serve --no-pi for terminals only' : ''}`)
180
+ }
181
+ pi = { command, args }
182
+ }
183
+ }
184
+
185
+ const quickTunnel = values['quick-tunnel']
186
+ if (quickTunnel) {
187
+ if (hostname) usageError('--quick-tunnel picks its own hostname; drop --hostname (or AFIELD_HOSTNAME)')
188
+ if (values['no-sign-in']) usageError('--quick-tunnel puts this on the internet, so it needs sign-in')
189
+ if (!(bind === 'localhost' || bind === '::1' || bind.startsWith('127.'))) usageError('--quick-tunnel needs a loopback --bind')
190
+ }
191
+
192
+ return {
193
+ port,
194
+ bind,
195
+ hostname,
196
+ quickTunnel,
197
+ cap,
198
+ theme,
199
+ scrollback,
200
+ newDir,
201
+ signIn: !values['no-sign-in'],
202
+ pi,
203
+ shell,
204
+ }
205
+ }
206
+
207
+ function runnable(path) {
208
+ try {
209
+ accessSync(path, constants.X_OK)
210
+ } catch {
211
+ return false
212
+ }
213
+ return statSync(path).isFile()
214
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "afield",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Access full TUI apps like Pi from your phone or browser",
5
+ "bin": {
6
+ "afield": "afield"
7
+ },
8
+ "files": [
9
+ "afield",
10
+ "pi-extensions",
11
+ "server",
12
+ "src",
13
+ "tsconfig.json",
14
+ "vendor"
15
+ ],
16
+ "engines": {
17
+ "node": ">=22"
18
+ },
19
+ "scripts": {
20
+ "test": "node --test --test-timeout=60000 'tests/unit/**/*.test.js'",
21
+ "test:integrity": "node --test 'tests/integrity/*.test.js'",
22
+ "test:real-pi": "node --test 'tests/real-pi/*.test.js'",
23
+ "test:e2e": "playwright test",
24
+ "test:smoke": "playwright test -c playwright.smoke.config.js",
25
+ "typecheck": "tsc --noEmit"
26
+ },
27
+ "license": "ISC",
28
+ "type": "module",
29
+ "devDependencies": {
30
+ "@earendil-works/pi-coding-agent": "^1.7.0",
31
+ "@playwright/test": "^1.62.1",
32
+ "@types/node": "^26.6.5",
33
+ "typescript": "^7.0.2"
34
+ },
35
+ "dependencies": {
36
+ "@lydell/node-pty": "1.2.0-beta.18",
37
+ "@wterm/core": "0.5.10",
38
+ "@xterm/addon-serialize": "^0.14.0",
39
+ "@xterm/headless": "^6.0.0",
40
+ "esbuild": "^0.28.2",
41
+ "uqr": "0.1.3",
42
+ "ws": "^8.21.3"
43
+ }
44
+ }
@@ -0,0 +1,59 @@
1
+ // Report the conversation currently open in this pi process. The PTY keeps its
2
+ // own identity when /new or /resume replaces the conversation inside it.
3
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ import { readFileSync, readdirSync, realpathSync, renameSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, join } from "node:path";
6
+
7
+ /**
8
+ * The canonical transcript path.
9
+ *
10
+ * Pi mints the file and writes its header with the first entry, so at
11
+ * session_start the file itself may not exist yet — the folder it will live in
12
+ * does, and that is what realpath has to resolve. The file is never a symlink,
13
+ * so the folder's real path plus the name is what realpath would answer.
14
+ */
15
+ const canonical = (file: string) => join(realpathSync(dirname(file)), basename(file));
16
+
17
+ export default function (pi: ExtensionAPI) {
18
+ const out = process.env.AFIELD_IDENTITY;
19
+ if (!out) return;
20
+
21
+ // A transcript another supervised terminal has open is not openable here.
22
+ // Two writers on one transcript are tolerated — pi appends, and this is not
23
+ // worth a lock — but a silent second owner would be a surprise, so the
24
+ // switch is refused rather than the two of them interleaving.
25
+ //
26
+ // Only /resume carries a target; /new has no file yet to collide over.
27
+ pi.on("session_before_switch", (event, ctx) => {
28
+ if (!event.targetSessionFile) return;
29
+ const target = realpathSync(event.targetSessionFile);
30
+ for (const name of readdirSync(dirname(out))) {
31
+ const other = join(dirname(out), name);
32
+ if (!name.endsWith(".identity") || other === out) continue;
33
+ let state;
34
+ try {
35
+ state = JSON.parse(readFileSync(other, "utf8"));
36
+ } catch (err) {
37
+ // A sibling that exited between the listing and this read.
38
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") continue;
39
+ throw err;
40
+ }
41
+ if (state.file !== target) continue;
42
+ ctx.ui.notify("That conversation is already open in another terminal", "warning");
43
+ return { cancel: true };
44
+ }
45
+ });
46
+
47
+ pi.on("session_start", (_event, ctx) => {
48
+ ctx.ui.setStatus("afield", ctx.ui.theme.fg("accent", "afield"));
49
+ const file = ctx.sessionManager.getSessionFile();
50
+ const state = {
51
+ id: ctx.sessionManager.getSessionId(),
52
+ cwd: realpathSync(ctx.sessionManager.getCwd()),
53
+ file: file ? canonical(file) : undefined,
54
+ at: Date.now(),
55
+ };
56
+ writeFileSync(`${out}.tmp`, JSON.stringify(state));
57
+ renameSync(`${out}.tmp`, out);
58
+ });
59
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Built-in footer minus "(auto)" and "(sub)".
3
+ * On narrow screens the R/W cache token counts are dropped first, then the ↑/↓ token counts,
4
+ * then the provider, then the cost, then the model is truncated.
5
+ * /footer shows all parts regardless of width.
6
+ */
7
+
8
+ import type { AssistantMessage, Usage } from "@earendil-works/pi-ai";
9
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
11
+
12
+ // Parts dropped from line 2, in this order, until it fits
13
+ const DROP_ORDER = ["cache", "tokens", "provider", "cost"] as const;
14
+
15
+ function formatTokens(n: number): string {
16
+ if (n < 1000) return n.toString();
17
+ if (n < 10000) return `${(n / 1000).toFixed(1)}k`;
18
+ if (n < 1000000) return `${Math.round(n / 1000)}k`;
19
+ if (n < 10000000) return `${(n / 1000000).toFixed(1)}M`;
20
+ return `${Math.round(n / 1000000)}M`;
21
+ }
22
+
23
+ function sessionStats(ctx: ExtensionContext) {
24
+ let input = 0;
25
+ let output = 0;
26
+ let cacheRead = 0;
27
+ let cacheWrite = 0;
28
+ let cost = 0;
29
+ let cacheHit: number | undefined;
30
+ let latest: AssistantMessage | undefined;
31
+ const add = (u: Usage) => {
32
+ input += u.input;
33
+ output += u.output;
34
+ cacheRead += u.cacheRead;
35
+ cacheWrite += u.cacheWrite;
36
+ cost += u.cost.total;
37
+ };
38
+ for (const e of ctx.sessionManager.getEntries()) {
39
+ if (e.type === "usage") add(e.usage);
40
+ else if ((e.type === "branch_summary" || e.type === "compaction") && e.usage) add(e.usage);
41
+ else if (e.type === "message" && e.message.role === "toolResult" && e.message.usage) add(e.message.usage);
42
+ else if (e.type === "message" && e.message.role === "assistant") {
43
+ const u = e.message.usage;
44
+ add(u);
45
+ const prompt = u.input + u.cacheRead + u.cacheWrite;
46
+ cacheHit = prompt > 0 ? (u.cacheRead / prompt) * 100 : undefined;
47
+ }
48
+ }
49
+ // Latest successful response on the current branch: the physical model behind a virtual selection
50
+ for (const e of ctx.sessionManager.getBranch()) {
51
+ if (e.type === "message" && e.message.role === "assistant" && e.message.stopReason !== "error" && e.message.stopReason !== "aborted") {
52
+ latest = e.message;
53
+ }
54
+ }
55
+ return { input, output, cacheRead, cacheWrite, cost, cacheHit, latest, usage: ctx.getContextUsage() };
56
+ }
57
+
58
+ export default function (pi: ExtensionAPI) {
59
+ // Full (un-dropped) footer lines from the latest render, for /footer
60
+ let full: string[] = [];
61
+ pi.registerCommand("footer", {
62
+ description: "Show all footer stats, even parts hidden by narrow width",
63
+ handler: async (_args, ctx) => {
64
+ ctx.ui.notify(full.join("\n"), "info");
65
+ },
66
+ });
67
+
68
+ pi.on("session_start", (_event, ctx) => {
69
+ ctx.ui.setFooter((tui, theme, footerData) => {
70
+ const unsub = footerData.onBranchChange(() => tui.requestRender());
71
+ let cacheKey = "";
72
+ let cachedModel: ExtensionContext["model"];
73
+ let cached: ReturnType<typeof sessionStats>;
74
+
75
+ return {
76
+ dispose: unsub,
77
+ invalidate() {},
78
+ render(width: number): string[] {
79
+ const sm = ctx.sessionManager;
80
+ const model = ctx.model;
81
+ // Every append moves the leaf. Avoid getEntries(), which copies the session on every frame.
82
+ const key = `${sm.getSessionId()}:${sm.getLeafId()}`;
83
+ if (key !== cacheKey || model !== cachedModel) {
84
+ cached = sessionStats(ctx);
85
+ cacheKey = key;
86
+ cachedModel = model;
87
+ }
88
+ const { input, output, cacheRead, cacheWrite, cost, cacheHit, latest, usage } = cached;
89
+
90
+ // Line 1: cwd (branch) • session name
91
+ let pwd = sm.getCwd();
92
+ const home = process.env.HOME;
93
+ if (home && (pwd === home || pwd.startsWith(`${home}/`))) pwd = `~${pwd.slice(home.length)}`;
94
+ const branch = footerData.getGitBranch();
95
+ if (branch) pwd += ` (${branch})`;
96
+ const name = sm.getSessionName();
97
+ if (name) pwd += ` • ${name}`;
98
+
99
+ // Line 2 left: ↑↓, R/W, CH, cost, context
100
+ const pct = usage?.percent ?? 0;
101
+ const window = usage?.contextWindow ?? model?.contextWindow ?? 0;
102
+ const pctStr = usage?.percent != null ? `${pct.toFixed(1)}%` : "?";
103
+ let ctxStr = `${pctStr}/${formatTokens(window)}`;
104
+ if (pct > 90) ctxStr = theme.fg("error", ctxStr);
105
+ else if (pct > 70) ctxStr = theme.fg("warning", ctxStr);
106
+ const ch = (cacheRead > 0 || cacheWrite > 0) && cacheHit !== undefined ? `CH${cacheHit.toFixed(1)}%` : undefined;
107
+ const costStr = cost ? `$${cost.toFixed(3)}` : undefined;
108
+ const inStr = input ? `↑${formatTokens(input)}` : undefined;
109
+ const outStr = output ? `↓${formatTokens(output)}` : undefined;
110
+ const readStr = cacheRead ? `R${formatTokens(cacheRead)}` : undefined;
111
+ const writeStr = cacheWrite ? `W${formatTokens(cacheWrite)}` : undefined;
112
+ const dropped = new Set<(typeof DROP_ORDER)[number]>();
113
+ const left = () =>
114
+ [
115
+ !dropped.has("tokens") && inStr,
116
+ !dropped.has("tokens") && outStr,
117
+ !dropped.has("cache") && readStr,
118
+ !dropped.has("cache") && writeStr,
119
+ ch,
120
+ !dropped.has("cost") && costStr,
121
+ ctxStr,
122
+ ].filter(Boolean).join(" ");
123
+
124
+ // Line 2 right: model • thinking [→ routed • thinking]
125
+ let right = model?.id ?? "no-model";
126
+ if (model?.reasoning) {
127
+ const level = pi.getThinkingLevel();
128
+ right += level === "off" ? " • thinking off" : ` • ${level}`;
129
+ }
130
+ if (model?.api === "pi-virtual" && latest) {
131
+ right += ` → ${latest.model}${latest.thinkingLevel ? ` • ${latest.thinkingLevel}` : ""}`;
132
+ }
133
+ const withProvider = model && footerData.getAvailableProviderCount() > 1 ? `(${model.provider}) ${right}` : right;
134
+ full = [pwd, left(), withProvider];
135
+
136
+ const fits = (l: string, r: string) => visibleWidth(l) + 2 + visibleWidth(r) <= width;
137
+ const build = () => ({ l: left(), r: dropped.has("provider") ? right : withProvider });
138
+ let { l, r } = build();
139
+ for (const part of DROP_ORDER) {
140
+ if (fits(l, r)) break;
141
+ dropped.add(part);
142
+ ({ l, r } = build());
143
+ }
144
+ l = truncateToWidth(l, width, "...");
145
+ const room = width - visibleWidth(l) - 2;
146
+ r = room > 0 ? truncateToWidth(r, room, "") : "";
147
+ const pad = " ".repeat(Math.max(0, width - visibleWidth(l) - visibleWidth(r)));
148
+ // Dim each part separately: a colored context % ends with a reset that would clear an outer dim
149
+ const lines = [
150
+ truncateToWidth(theme.fg("dim", pwd), width, theme.fg("dim", "...")),
151
+ theme.fg("dim", l) + theme.fg("dim", pad + r),
152
+ ];
153
+
154
+ const statuses = footerData.getExtensionStatuses();
155
+ if (statuses.size > 0) {
156
+ const text = [...statuses.entries()]
157
+ .sort(([a], [b]) => a.localeCompare(b))
158
+ .map(([, t]) => t.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim())
159
+ .join(" ");
160
+ lines.push(truncateToWidth(text, width, theme.fg("dim", "...")));
161
+ }
162
+ return lines;
163
+ },
164
+ };
165
+ });
166
+ });
167
+ }