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.
- package/LICENSE +15 -0
- package/README.md +165 -2
- package/afield +214 -0
- package/package.json +42 -4
- package/pi-extensions/afield-session.ts +59 -0
- package/pi-extensions/elastic-footer.ts +167 -0
- package/server/attach.js +264 -0
- package/server/auth.js +169 -0
- package/server/client.js +64 -0
- package/server/control.js +65 -0
- package/server/identity.js +45 -0
- package/server/index.js +375 -0
- package/server/mirror.js +159 -0
- package/server/origin.js +51 -0
- package/server/picker.js +187 -0
- package/server/places.js +348 -0
- package/server/protocol.js +51 -0
- package/server/quick-tunnel.js +40 -0
- package/server/registry.js +190 -0
- package/server/serve.js +100 -0
- package/server/session-main.js +27 -0
- package/server/session.js +112 -0
- package/server/supervisor.js +432 -0
- package/server/viewer.js +65 -0
- package/src/app.js +1683 -0
- package/src/apple-touch-icon.png +0 -0
- package/src/index.html +96 -0
- package/src/keys.js +59 -0
- package/src/pi-icon.svg +13 -0
- package/src/style.css +559 -0
- package/src/transport.js +153 -0
- package/src/ttyd.js +51 -0
- package/src/viewport.js +168 -0
- package/tsconfig.json +14 -0
- package/vendor/wterm/LICENSE +191 -0
- package/vendor/wterm/README.md +7 -0
- package/vendor/wterm/packages/@wterm/dom/src/debug.ts +347 -0
- package/vendor/wterm/packages/@wterm/dom/src/hyperlink.ts +8 -0
- package/vendor/wterm/packages/@wterm/dom/src/index.ts +13 -0
- package/vendor/wterm/packages/@wterm/dom/src/input.ts +662 -0
- package/vendor/wterm/packages/@wterm/dom/src/renderer.ts +725 -0
- package/vendor/wterm/packages/@wterm/dom/src/terminal.css +195 -0
- package/vendor/wterm/packages/@wterm/dom/src/wterm.ts +609 -0
package/server/picker.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Furniture the terminal clients share for choosing a session: how a row is
|
|
2
|
+
// written, how a name-or-path fragment matches one, and the paged numbered
|
|
3
|
+
// prompt. The list this shows is exactly what the phone's menu shows, since
|
|
4
|
+
// both read `GET /places`.
|
|
5
|
+
import { createInterface } from 'node:readline/promises'
|
|
6
|
+
import { keyPath } from './auth.js'
|
|
7
|
+
|
|
8
|
+
// A url the supervisor answers over http: the same endpoint is reached by ws,
|
|
9
|
+
// wss, http and https depending on how the caller was told about it.
|
|
10
|
+
export const baseUrl = url => {
|
|
11
|
+
const target = new URL(url)
|
|
12
|
+
if (target.protocol === 'ws:') target.protocol = 'http:'
|
|
13
|
+
else if (target.protocol === 'wss:') target.protocol = 'https:'
|
|
14
|
+
return target
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// How many rows one page shows. Everything past it is one `more` away rather
|
|
18
|
+
// than one long wall of text.
|
|
19
|
+
export const PICK_ROWS = 10
|
|
20
|
+
|
|
21
|
+
/** One question on the terminal. Ctrl-C answers with a blank rather than
|
|
22
|
+
* the unhandled AbortError readline raises: a prompt you get out of is a
|
|
23
|
+
* prompt that heard "no", which a blank already means to every caller. */
|
|
24
|
+
export const ask = async question => {
|
|
25
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout })
|
|
26
|
+
try { return await rl.question(question) }
|
|
27
|
+
catch (err) { if (err.code === 'ABORT_ERR') return ''; throw err }
|
|
28
|
+
finally { rl.close() }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** `3m`, `2h`, `5d` — the same reading of last-active the menu shows. */
|
|
32
|
+
export const ago = at => {
|
|
33
|
+
if (!at) return ''
|
|
34
|
+
const s = Math.max(0, (Date.now() - at) / 1000)
|
|
35
|
+
if (s < 60) return 'now'
|
|
36
|
+
if (s < 3600) return `${s / 60 | 0}m`
|
|
37
|
+
if (s < 86400) return `${s / 3600 | 0}h`
|
|
38
|
+
return `${s / 86400 | 0}d`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One row of any listing: numbered when given an index, marked ● when the
|
|
42
|
+
* session is running, with its viewer count when available. */
|
|
43
|
+
export const placeRow = (s, i) =>
|
|
44
|
+
` ${i ? `${i}) ` : ' '}${s.running ? '●' : ' '} ${(s.label || s.name).slice(0, 60).padEnd(60)} ${s.path}` +
|
|
45
|
+
(s.viewers == null ? '' : ` ${s.viewers} watching`) +
|
|
46
|
+
(s.working ? ' working' : s.unread ? ' unread' : '') +
|
|
47
|
+
` ${ago(s.at)}`
|
|
48
|
+
|
|
49
|
+
/** The rows a name-or-path fragment picks out. Empty string matches nothing
|
|
50
|
+
* rather than everything: a filter that means "all" is spelled by leaving
|
|
51
|
+
* the argument off, not by passing a blank one. */
|
|
52
|
+
export const matching = (sessions, fragment) =>
|
|
53
|
+
fragment
|
|
54
|
+
? sessions.filter(s => `${s.label || ''} ${s.name} ${s.path} ${s.id}`.toLowerCase().includes(fragment.toLowerCase()))
|
|
55
|
+
: []
|
|
56
|
+
|
|
57
|
+
/** Bare decimal digit strings are indices; other numeric literals are invalid,
|
|
58
|
+
* and nonnumeric text remains a fragment. Zero is parsed for caller validation. */
|
|
59
|
+
export const indexArgument = arg => {
|
|
60
|
+
if (typeof arg !== 'string') return null
|
|
61
|
+
if (/^\d+$/.test(arg)) return Number(arg)
|
|
62
|
+
return /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(arg) ? Number.NaN : null
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The one running session to act on: a bare number over the list as given, a
|
|
67
|
+
* fragment naming exactly one, the only row there is, or a numbered prompt
|
|
68
|
+
* when none of those answers it. Says why when there is no match at all.
|
|
69
|
+
*/
|
|
70
|
+
export const pickTarget = async (rows, match, prompt = 'which session?') => {
|
|
71
|
+
const index = indexArgument(match)
|
|
72
|
+
if (index !== null) {
|
|
73
|
+
if (!Number.isSafeInteger(index) || index < 1 || index > rows.length) {
|
|
74
|
+
console.error(`no running session numbered ${match}`)
|
|
75
|
+
return null
|
|
76
|
+
}
|
|
77
|
+
return rows[index - 1]
|
|
78
|
+
}
|
|
79
|
+
if (match) {
|
|
80
|
+
const hits = matching(rows, match)
|
|
81
|
+
if (hits.length === 1) return hits[0]
|
|
82
|
+
if (hits.length === 0) {
|
|
83
|
+
console.error(`nothing running matches ${JSON.stringify(match)}`)
|
|
84
|
+
return null
|
|
85
|
+
}
|
|
86
|
+
console.error('more than one matches:')
|
|
87
|
+
return await pickFrom(hits, { ask, out: console.error })
|
|
88
|
+
}
|
|
89
|
+
if (rows.length === 1) return rows[0]
|
|
90
|
+
console.error(prompt)
|
|
91
|
+
return await pickFrom(rows, { ask, out: console.error })
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `GET /places`, with optional query params. Returns the parsed body, or null
|
|
95
|
+
* after reporting why the supervisor could not be read. */
|
|
96
|
+
export const fetchPlaces = async (url, { headers, params = {}, prefix = '', onNoServer } = {}) => {
|
|
97
|
+
const target = new URL('/places', baseUrl(url))
|
|
98
|
+
for (const [k, v] of Object.entries(params)) target.searchParams.set(k, v)
|
|
99
|
+
const res = await fetch(target, { headers }).catch(() => null)
|
|
100
|
+
if (!res) {
|
|
101
|
+
if (onNoServer) onNoServer()
|
|
102
|
+
else console.error(`${prefix}could not reach the server`)
|
|
103
|
+
return null
|
|
104
|
+
}
|
|
105
|
+
if (!res.ok) {
|
|
106
|
+
console.error(res.status === 401
|
|
107
|
+
? `${prefix}the server's key is not the one at ${keyPath()}`
|
|
108
|
+
: `${prefix}could not list sessions (HTTP ${res.status})`)
|
|
109
|
+
return null
|
|
110
|
+
}
|
|
111
|
+
return res.json()
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Confirm (unless `yes`) and end one running terminal. True once it is gone. */
|
|
115
|
+
export const deleteTerminal = async (url, target, { headers, yes = false, confirm = ask } = {}) => {
|
|
116
|
+
const name = target.label || target.name
|
|
117
|
+
if (!yes) {
|
|
118
|
+
const answer = (await confirm(`end "${name}"? [y/N] `)).trim().toLowerCase()
|
|
119
|
+
if (answer !== 'y' && answer !== 'yes') {
|
|
120
|
+
console.error('left it running')
|
|
121
|
+
return false
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const res = await fetch(new URL(`/terminal?process=${encodeURIComponent(target.processId)}`, baseUrl(url)), {
|
|
125
|
+
method: 'DELETE',
|
|
126
|
+
headers,
|
|
127
|
+
}).catch(() => null)
|
|
128
|
+
if (!res) {
|
|
129
|
+
console.error('could not reach the server')
|
|
130
|
+
return false
|
|
131
|
+
}
|
|
132
|
+
if (!res.ok && res.status !== 404) {
|
|
133
|
+
console.error(`could not end it (HTTP ${res.status})`)
|
|
134
|
+
return false
|
|
135
|
+
}
|
|
136
|
+
console.error(res.status === 404
|
|
137
|
+
? 'it was already gone (nothing was running under that name)'
|
|
138
|
+
: `ended: ${name}`)
|
|
139
|
+
return true
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The move a full pool forces: end one running session so the refused action
|
|
144
|
+
* can go through. Offers what is up in the order the server gives them up,
|
|
145
|
+
* confirms the choice, and asks for it to be ended. True once a terminal is
|
|
146
|
+
* gone, false when nothing was picked, confirmed or ended.
|
|
147
|
+
*/
|
|
148
|
+
export const endOne = async (url, headers, confirm = ask) => {
|
|
149
|
+
const data = await fetchPlaces(url, { headers, params: { running: '1' } })
|
|
150
|
+
if (!data) return false
|
|
151
|
+
if (data.sessions.length === 0) {
|
|
152
|
+
console.error('nothing is running to end')
|
|
153
|
+
return false
|
|
154
|
+
}
|
|
155
|
+
const target = await pickTarget(data.sessions, null, 'which session to end?')
|
|
156
|
+
if (!target) {
|
|
157
|
+
console.error('left it running')
|
|
158
|
+
return false
|
|
159
|
+
}
|
|
160
|
+
return deleteTerminal(url, target, { headers, confirm })
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The numbered prompt, ten rows at a time. Numbers stay global across pages,
|
|
165
|
+
* so `7` means the same thing however many `more`s came before it. Answers:
|
|
166
|
+
* a number on the list, `more` for the next page, anything else a refusal.
|
|
167
|
+
* Returns the chosen session, or null when the answer was none of these.
|
|
168
|
+
*/
|
|
169
|
+
export const pickFrom = async (candidates, { ask, out }) => {
|
|
170
|
+
let from = 0
|
|
171
|
+
for (;;) {
|
|
172
|
+
const page = candidates.slice(from, from + PICK_ROWS)
|
|
173
|
+
page.forEach((s, k) => out(placeRow(s, from + k + 1)))
|
|
174
|
+
const more = candidates.length - from - page.length
|
|
175
|
+
if (more > 0) out(` ... ${more} more (type 'more' to continue)`)
|
|
176
|
+
const answer = (await ask('> ')).trim()
|
|
177
|
+
if (answer === 'more') {
|
|
178
|
+
if (more === 0) { out('no more sessions'); return null }
|
|
179
|
+
from += page.length
|
|
180
|
+
continue
|
|
181
|
+
}
|
|
182
|
+
const pick = Number(answer)
|
|
183
|
+
const choice = Number.isInteger(pick) ? candidates[pick - 1] : undefined
|
|
184
|
+
if (!choice) { out('no such number on the list'); return null }
|
|
185
|
+
return choice
|
|
186
|
+
}
|
|
187
|
+
}
|
package/server/places.js
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
// The sessions you have used pi in, read out of pi's own session store.
|
|
2
|
+
//
|
|
3
|
+
// pi keys sessions by working directory and gives each one its own id:
|
|
4
|
+
// ~/.pi/agent/sessions/<slug>/*.jsonl, one directory per cwd, one file per
|
|
5
|
+
// session. The slug is lossy -- a path containing a dash is indistinguishable
|
|
6
|
+
// from a separator -- so the real path comes from the session file itself,
|
|
7
|
+
// whose first line is a header carrying both the cwd and the id verbatim.
|
|
8
|
+
//
|
|
9
|
+
// One row per session, not per folder: a folder used for several concurrent
|
|
10
|
+
// or historical conversations offers all of them, since a phone list can only
|
|
11
|
+
// usefully be sorted one way -- by how recently each one was touched.
|
|
12
|
+
// A session pi forked off another -- a subagent's run, or a /fork or /clone,
|
|
13
|
+
// which write the same header -- is no row of the list. An exact id still
|
|
14
|
+
// reaches a fork: `findPlace` answers it, so a caller that knows the id needs
|
|
15
|
+
// no menu row.
|
|
16
|
+
import { createInterface } from 'node:readline'
|
|
17
|
+
import { createReadStream } from 'node:fs'
|
|
18
|
+
import { open, readdir, realpath, stat } from 'node:fs/promises'
|
|
19
|
+
import { homedir } from 'node:os'
|
|
20
|
+
import { basename, dirname, join } from 'node:path'
|
|
21
|
+
|
|
22
|
+
// pi's own variable for moving its store, so a machine that has moved it is
|
|
23
|
+
// still described correctly here rather than by where it usually lives.
|
|
24
|
+
export const PI_SESSIONS = process.env.PI_CODING_AGENT_SESSION_DIR ||
|
|
25
|
+
join(homedir(), '.pi', 'agent', 'sessions')
|
|
26
|
+
|
|
27
|
+
// The header is the first line and is short — around 150 bytes. Reading a fixed
|
|
28
|
+
// window keeps a megabyte-long transcript from being pulled in to learn one
|
|
29
|
+
// field, and there are a hundred of these to sweep.
|
|
30
|
+
const HEADER_BYTES = 4096
|
|
31
|
+
|
|
32
|
+
// A session id becomes a file name (`afield-<id>.sock`) and part of a join URL;
|
|
33
|
+
// anything outside this shape would be either a path-traversal attempt or a
|
|
34
|
+
// name no client could have learned from this list in the first place.
|
|
35
|
+
const ID_SHAPE = /^[A-Za-z0-9_-]+$/
|
|
36
|
+
|
|
37
|
+
// The window a label read is allowed before it stops: renaming appends a new
|
|
38
|
+
// session_info at the end of a file, so a bounded read from the end catches it
|
|
39
|
+
// without walking the whole transcript. Sized like pi-fast-resume's: their
|
|
40
|
+
// measurement had every rename at EOF, 32KB covers a rename followed by dozens
|
|
41
|
+
// of turns of continued writing.
|
|
42
|
+
const TAIL_BYTES = 32 * 1024
|
|
43
|
+
|
|
44
|
+
/** A label is at most a phone row: long first asks are truncated on display. */
|
|
45
|
+
const LABEL_MAX = 80
|
|
46
|
+
|
|
47
|
+
const clip = text => {
|
|
48
|
+
const line = (text ?? '').trim().split('\n')[0]
|
|
49
|
+
return line.length > LABEL_MAX ? line.slice(0, LABEL_MAX - 1) + '…' : line
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** `~/projects/x` rather than `/Users/you/projects/x`: phone-width matters. */
|
|
53
|
+
export const shorten = path => {
|
|
54
|
+
const home = homedir()
|
|
55
|
+
if (path === home) return '~'
|
|
56
|
+
return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* How a folder is shown wherever it is named: a menu row, the header. One
|
|
61
|
+
* place does it, so a row and the frame that committed the place cannot
|
|
62
|
+
* disagree about the same folder.
|
|
63
|
+
*/
|
|
64
|
+
export const placeNames = cwd => ({ name: basename(cwd), path: shorten(cwd) })
|
|
65
|
+
|
|
66
|
+
const readSlice = async (file, offset, length) => {
|
|
67
|
+
const handle = await open(file, 'r')
|
|
68
|
+
try {
|
|
69
|
+
const { buffer, bytesRead } = await handle.read(Buffer.alloc(length), 0, length, offset)
|
|
70
|
+
return buffer.subarray(0, bytesRead).toString()
|
|
71
|
+
} finally {
|
|
72
|
+
await handle.close()
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const tryParse = line => {
|
|
77
|
+
try { return JSON.parse(line) } catch { return null }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* A session file's header, or null if it does not look like one.
|
|
82
|
+
*
|
|
83
|
+
* I/O errors are left to propagate — an unreadable store is worth hearing
|
|
84
|
+
* about. A line that does not parse, or lacks an id, is a different thing:
|
|
85
|
+
* the directory holds something this does not recognise, which is a fact
|
|
86
|
+
* about the file rather than a fault, and the answer is simply that there is
|
|
87
|
+
* no session here.
|
|
88
|
+
*/
|
|
89
|
+
const readHeader = async file => {
|
|
90
|
+
const [line] = (await readSlice(file, 0, HEADER_BYTES)).split('\n')
|
|
91
|
+
const header = tryParse(line)
|
|
92
|
+
if (header?.type === 'session' && typeof header.cwd === 'string' && typeof header.id === 'string') {
|
|
93
|
+
return header
|
|
94
|
+
}
|
|
95
|
+
return null
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The row's label: pi's own name for the session if it ever got one, else the
|
|
100
|
+
* first thing the user asked, else nothing.
|
|
101
|
+
*
|
|
102
|
+
* pi appends a `session_info` entry every time a session is named -- `/name`,
|
|
103
|
+
* `--name`, an extension setting one -- and the LAST one in file order is the
|
|
104
|
+
* name (an empty name is an explicit clear). Sessions are named either at
|
|
105
|
+
* once (named at start, the event sits in the first lines) or right after the
|
|
106
|
+
* first exchange, so the forward pass reads header + first user message + the
|
|
107
|
+
* reply that follows, stopping at the first name or a bit past it; a rename
|
|
108
|
+
* anywhere later is caught by a bounded read from the end of the file, which
|
|
109
|
+
* also catches renames the forward pass could never see. Further-past renames
|
|
110
|
+
* are accepted as showing the older name, the same tradeoff pi-fast-resume
|
|
111
|
+
* makes with the same size.
|
|
112
|
+
*/
|
|
113
|
+
const readLabel = async (file, size) => {
|
|
114
|
+
let named
|
|
115
|
+
let firstUser
|
|
116
|
+
let afterFirst = 0
|
|
117
|
+
let stop = false
|
|
118
|
+
const stream = createReadStream(file)
|
|
119
|
+
const rl = createInterface({ input: stream, crlfDelay: Infinity })
|
|
120
|
+
rl.on('line', line => {
|
|
121
|
+
if (stop) return
|
|
122
|
+
const entry = tryParse(line)
|
|
123
|
+
if (!entry) return
|
|
124
|
+
if (entry.type === 'session_info') {
|
|
125
|
+
// The latest name in file order wins. An empty name is an explicit
|
|
126
|
+
// clear — it unsets, and the label falls back to the first ask.
|
|
127
|
+
named = entry.name?.trim() || undefined
|
|
128
|
+
} else if (entry.type === 'message' && entry.message?.role === 'user') {
|
|
129
|
+
firstUser ??= entry.message.content
|
|
130
|
+
} else if (firstUser !== undefined && entry.type === 'message') {
|
|
131
|
+
// The reply to the first ask, then a little slack: pi names the session
|
|
132
|
+
// right after it, and renames ride the same window. A few entries past
|
|
133
|
+
// that, whatever the label is going to be is already on disk.
|
|
134
|
+
afterFirst++
|
|
135
|
+
if (afterFirst >= 4) { stop = true; rl.close() }
|
|
136
|
+
}
|
|
137
|
+
})
|
|
138
|
+
await new Promise(resolve => rl.on('close', resolve))
|
|
139
|
+
// A forward pass that stopped early leaves the stream short of its end, and
|
|
140
|
+
// a stream that never ends never closes its file. Every row of a listing
|
|
141
|
+
// pays this read, so one transcript left open per row is what fills the
|
|
142
|
+
// process's descriptor table and makes every later spawn fail.
|
|
143
|
+
stream.destroy()
|
|
144
|
+
|
|
145
|
+
// The tail can only hold a later name than anything the forward pass saw if
|
|
146
|
+
// it stopped short of EOF, and the read must then start past it.
|
|
147
|
+
if (stop && size > TAIL_BYTES) {
|
|
148
|
+
for (const line of (await readSlice(file, size - TAIL_BYTES, TAIL_BYTES)).split('\n')) {
|
|
149
|
+
const entry = tryParse(line)
|
|
150
|
+
// In the tail, later still wins — and an empty name is as much a
|
|
151
|
+
// "later" as a real one: a late clear has to unset, too, or an old
|
|
152
|
+
// title would outlive its own removal.
|
|
153
|
+
if (entry?.type === 'session_info') {
|
|
154
|
+
named = entry.name?.trim() || undefined
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// A name that was cleared falls back to the first ask, like a name that was
|
|
159
|
+
// never set: `named` is undefined both ways.
|
|
160
|
+
return clip(named ?? textOf(firstUser))
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The text of a user message, however pi chose to lay it out. */
|
|
164
|
+
const textOf = content => {
|
|
165
|
+
if (typeof content === 'string') return content
|
|
166
|
+
if (Array.isArray(content)) {
|
|
167
|
+
return content.filter(part => part.type === 'text').map(part => part.text).join(' ')
|
|
168
|
+
}
|
|
169
|
+
return content?.text ?? ''
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The one true path of an existing folder, or null if it is not one any more.
|
|
174
|
+
*
|
|
175
|
+
* Resolved rather than taken as written, because `/tmp/x` and `/private/tmp/x`
|
|
176
|
+
* are the same folder and a session recorded under one spelling should still
|
|
177
|
+
* display the way everything else on the list does.
|
|
178
|
+
*/
|
|
179
|
+
const canonical = async path => {
|
|
180
|
+
let real
|
|
181
|
+
try {
|
|
182
|
+
real = await realpath(path)
|
|
183
|
+
} catch (err) {
|
|
184
|
+
if (err.code === 'ENOENT') return null
|
|
185
|
+
throw err
|
|
186
|
+
}
|
|
187
|
+
return (await stat(real)).isDirectory() ? real : null
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export { canonical }
|
|
191
|
+
|
|
192
|
+
/** A folder path, or null: a link to a folder counts, a link to anything else
|
|
193
|
+
* does not, and neither does one whose target is gone. */
|
|
194
|
+
const asFolder = async (here, name) => {
|
|
195
|
+
const path = join(here, name)
|
|
196
|
+
try {
|
|
197
|
+
return (await stat(path)).isDirectory() ? path : null
|
|
198
|
+
} catch (err) {
|
|
199
|
+
if (err.code === 'ENOENT') return null
|
|
200
|
+
throw err
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** List non-hidden subfolders for the new-session walk. */
|
|
205
|
+
export const subfolders = async dir => {
|
|
206
|
+
const here = await canonical(dir)
|
|
207
|
+
if (!here) return null
|
|
208
|
+
const names = (await readdir(here)).filter(name => !name.startsWith('.'))
|
|
209
|
+
const dirs = (await Promise.all(names.map(name => asFolder(here, name)))).filter(Boolean).sort()
|
|
210
|
+
return { cwd: here, parent: here === '/' ? null : dirname(here), dirs }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Every `.jsonl` path in one folder, with its mtime and nothing else read.
|
|
215
|
+
*
|
|
216
|
+
* A stat is metadata only — no open, no content — which is what lets every
|
|
217
|
+
* candidate across the whole store be ranked before anything pays to parse
|
|
218
|
+
* one. Ranking first and reading second is the whole point of the split.
|
|
219
|
+
*/
|
|
220
|
+
const statEntry = async file => ({ file, at: (await stat(file)).mtimeMs })
|
|
221
|
+
|
|
222
|
+
const listFolder = async dir => {
|
|
223
|
+
const files = (await readdir(dir)).filter(name => name.endsWith('.jsonl'))
|
|
224
|
+
return Promise.all(files.map(name => statEntry(join(dir, name))))
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** A ranked candidate is a row of the list or it is not: the header says whose
|
|
228
|
+
* session it is, and the folder it names still has to exist. Checked before
|
|
229
|
+
* anything pays for a label, because most of a real store is forks and
|
|
230
|
+
* folders that are gone — and forks are written constantly, so they cluster
|
|
231
|
+
* at the top of the ranking where the newest writes are. */
|
|
232
|
+
const isRow = async ({ file, at }, { forks = false } = {}) => {
|
|
233
|
+
const header = await readHeader(file)
|
|
234
|
+
if (!header || !ID_SHAPE.test(header.id)) return null
|
|
235
|
+
// A subagent's run is filed as a session of its own naming its parent, and
|
|
236
|
+
// belongs to the session that spawned it rather than to the phone list.
|
|
237
|
+
// A caller that names an exact id wants whatever transcript that id names,
|
|
238
|
+
// fork or not, so the filter is the listing's, not the lookup's.
|
|
239
|
+
if (!forks && header.parentSession) return null
|
|
240
|
+
const cwd = await canonical(header.cwd)
|
|
241
|
+
return cwd ? { file, at, id: header.id, cwd } : null
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** A row with its label: a pass over the transcript plus a bounded tail, the
|
|
245
|
+
* one expensive read here, and so paid only for the rows returned. A
|
|
246
|
+
* transcript with no conversation in it yet has nothing to label it with;
|
|
247
|
+
* the folder name is the honest row then, and the only one there is. */
|
|
248
|
+
const labelled = async row => {
|
|
249
|
+
const { file, ...rest } = row
|
|
250
|
+
return {
|
|
251
|
+
...rest,
|
|
252
|
+
...placeNames(row.cwd),
|
|
253
|
+
label: await readLabel(file, (await stat(file)).size) || basename(row.cwd),
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Every `.jsonl` in the store, newest first, with nothing but a stat read.
|
|
259
|
+
*
|
|
260
|
+
* Sorted by recency because that is the only ordering a phone list can be
|
|
261
|
+
* scrolled by usefully: what you want is nearly always in the first few rows.
|
|
262
|
+
* A machine with months of history has thousands of these, so callers read
|
|
263
|
+
* headers down this ranking only until they have what they came for.
|
|
264
|
+
*/
|
|
265
|
+
const ranked = async sessionDir => {
|
|
266
|
+
// A null store is a server that runs no pi: it has no conversations at all.
|
|
267
|
+
if (sessionDir === null) return []
|
|
268
|
+
let entries
|
|
269
|
+
try {
|
|
270
|
+
entries = await readdir(sessionDir, { withFileTypes: true })
|
|
271
|
+
} catch (err) {
|
|
272
|
+
// No store is an answer rather than a fault: pi may simply never have run.
|
|
273
|
+
if (err.code === 'ENOENT') return []
|
|
274
|
+
throw err
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Slug folders per cwd, plus the store root itself: older stores may hold
|
|
278
|
+
// flat .jsonl files there, and the header's cwd is what says where each
|
|
279
|
+
// one belongs. The root's own .jsonl files are read directly — they are
|
|
280
|
+
// files, not a folder to list;
|
|
281
|
+
const folders = entries.filter(entry => entry.isDirectory())
|
|
282
|
+
const flat = entries.filter(entry => entry.isFile() && entry.name.endsWith('.jsonl'))
|
|
283
|
+
.map(entry => statEntry(join(sessionDir, entry.name)))
|
|
284
|
+
const found = await Promise.all([
|
|
285
|
+
...flat,
|
|
286
|
+
...folders.map(entry => listFolder(join(sessionDir, entry.name))),
|
|
287
|
+
])
|
|
288
|
+
return found.flat().sort((a, b) => b.at - a.at)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** A running terminal's row, labelled from the transcript its identity names.
|
|
292
|
+
* Pi writes that file with the first entry, so until then there is none and
|
|
293
|
+
* the folder name is the label, as for any transcript with nothing in it. */
|
|
294
|
+
const liveRow = async ({ file, ...running }) => {
|
|
295
|
+
let info
|
|
296
|
+
try {
|
|
297
|
+
info = file && await stat(file)
|
|
298
|
+
} catch (err) {
|
|
299
|
+
if (err.code !== 'ENOENT') throw err
|
|
300
|
+
}
|
|
301
|
+
if (!info) return running
|
|
302
|
+
return { ...running, at: Math.max(info.mtimeMs, running.at), label: await readLabel(file, info.size) || running.label }
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* A window on the list: `limit` rows from `offset`, and whether any lie past it.
|
|
307
|
+
*
|
|
308
|
+
* `live` is what the running terminals have open. Those lead the list -- what
|
|
309
|
+
* is alive is what is worth finding first -- and their transcripts are skipped
|
|
310
|
+
* further down, so a running session is one row in one place.
|
|
311
|
+
*
|
|
312
|
+
* `limit` counts ROWS rather than files. A cap on files would be spent almost
|
|
313
|
+
* entirely on forks and folders that are gone — the bulk of a real store, and
|
|
314
|
+
* the files written most often — and would come back holding whatever rows
|
|
315
|
+
* happened to sit among them. Headers are read down the ranking only until the
|
|
316
|
+
* window and one row past it are found; nothing counts the rest.
|
|
317
|
+
*/
|
|
318
|
+
const placeKey = ({ id, cwd }) => `${id}\0${cwd}`
|
|
319
|
+
|
|
320
|
+
export async function readPlaces({ sessionDir = PI_SESSIONS, offset = 0, limit = Infinity, live = [] } = {}) {
|
|
321
|
+
const rows = (await Promise.all(live.map(liveRow))).sort((a, b) => b.at - a.at)
|
|
322
|
+
const liveKeys = new Set(live.map(placeKey))
|
|
323
|
+
const end = offset + limit
|
|
324
|
+
for (const candidate of await ranked(sessionDir)) {
|
|
325
|
+
if (rows.length > end) break
|
|
326
|
+
const row = await isRow(candidate)
|
|
327
|
+
if (row && !liveKeys.has(placeKey(row))) rows.push(row)
|
|
328
|
+
}
|
|
329
|
+
const sessions = []
|
|
330
|
+
for (const row of rows.slice(offset, end)) {
|
|
331
|
+
sessions.push(row.file ? await labelled(row) : row)
|
|
332
|
+
}
|
|
333
|
+
return { sessions, more: rows.length > end }
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The one row for a conversation, wherever it falls in the ranking: a join
|
|
337
|
+
* names a session by id, and no listing window is where to look one thing
|
|
338
|
+
* up. Newest first, so the session just tapped is found at once. */
|
|
339
|
+
export async function findPlace({ sessionDir = PI_SESSIONS, id, cwd }) {
|
|
340
|
+
// An id outside this shape could never have come from a listing, and the
|
|
341
|
+
// sweep below reads headers across the whole store before giving up.
|
|
342
|
+
if (!ID_SHAPE.test(id ?? '')) return null
|
|
343
|
+
for (const candidate of await ranked(sessionDir)) {
|
|
344
|
+
const row = await isRow(candidate, { forks: true })
|
|
345
|
+
if (row?.id === id && (!cwd || row.cwd === cwd)) return labelled(row)
|
|
346
|
+
}
|
|
347
|
+
return null
|
|
348
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// The wire protocol, server side. `src/ttyd.js` is the client's half of this.
|
|
2
|
+
// Both ends are ours; the frame shape is ttyd's.
|
|
3
|
+
|
|
4
|
+
// client -> server
|
|
5
|
+
export const INPUT = 0x30 // '0'
|
|
6
|
+
export const RESIZE = 0x31 // '1'
|
|
7
|
+
|
|
8
|
+
// server -> client
|
|
9
|
+
export const OUTPUT = 0x30 // '0'
|
|
10
|
+
export const SET_TITLE = 0x31 // '1'
|
|
11
|
+
export const SET_SIZE = 0x33 // '3' the grid the PTY actually has
|
|
12
|
+
export const PROCESS = 0x35 // '5' this PTY's place: on admission, and again at every conversation change
|
|
13
|
+
|
|
14
|
+
// Lines of history a snapshot carries unless the server was told otherwise.
|
|
15
|
+
// The page tells the client's VT core to keep the same number.
|
|
16
|
+
export const DEFAULT_SCROLLBACK = 10_000
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A size off the wire, from either the handshake or a RESIZE frame.
|
|
20
|
+
*
|
|
21
|
+
* The handshake is a bare JSON object with no command byte and must be the first
|
|
22
|
+
* message on the socket; a RESIZE is the same payload behind a prefix. Both
|
|
23
|
+
* reach the PTY, so both get the same scrutiny. Returns null for anything
|
|
24
|
+
* unparseable or unreasonable, which closes that viewer rather than the server.
|
|
25
|
+
*/
|
|
26
|
+
const decodeDimensions = value => {
|
|
27
|
+
const { columns, rows } = value
|
|
28
|
+
if (!Number.isInteger(columns) || !Number.isInteger(rows)) return null
|
|
29
|
+
// The upper bound is not theatre: the grid is allocated server-side, in the
|
|
30
|
+
// mirror as well as the PTY.
|
|
31
|
+
if (columns < 1 || rows < 1 || columns > 1000 || rows > 1000) return null
|
|
32
|
+
return { cols: columns, rows }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const decodeHandshake = buf => {
|
|
36
|
+
try {
|
|
37
|
+
const value = JSON.parse(buf.toString())
|
|
38
|
+
const size = decodeDimensions(value)
|
|
39
|
+
return size && { ...size, client: value.client }
|
|
40
|
+
} catch {
|
|
41
|
+
return null
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const decodeSize = buf => {
|
|
46
|
+
try {
|
|
47
|
+
return decodeDimensions(JSON.parse(buf.toString()))
|
|
48
|
+
} catch {
|
|
49
|
+
return null
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// `serve --quick-tunnel`: a Cloudflare quick tunnel to this server, with no
|
|
2
|
+
// account or domain. cloudflared comes from npm, so nothing needs installing.
|
|
3
|
+
// The npm wrapper is pinned; the cloudflared it downloads on first use is the
|
|
4
|
+
// latest release.
|
|
5
|
+
import { spawn } from 'node:child_process'
|
|
6
|
+
import { tmpdir } from 'node:os'
|
|
7
|
+
import { createInterface } from 'node:readline'
|
|
8
|
+
|
|
9
|
+
const PACKAGE = 'cloudflared@0.7.3'
|
|
10
|
+
|
|
11
|
+
// A quick tunnel's name is random hyphenated words, which keeps
|
|
12
|
+
// api.trycloudflare.com in an error message from matching.
|
|
13
|
+
const NAME = /https:\/\/([a-z0-9]+(?:-[a-z0-9]+)+\.trycloudflare\.com)(?![\w.-])/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Starts a tunnel to `origin`. `onName` gets the public hostname once
|
|
17
|
+
* cloudflared announces it; `onExit` gets why cloudflared stopped, unless
|
|
18
|
+
* `stop()` stopped it.
|
|
19
|
+
*/
|
|
20
|
+
export function startQuickTunnel(origin, { onName, onExit }) {
|
|
21
|
+
// Run from the temp dir so a cloudflared in the caller's project is not the
|
|
22
|
+
// one npx picks. npx and the wrapper pass SIGTERM on to cloudflared.
|
|
23
|
+
const child = spawn('npx', ['--yes', PACKAGE, 'tunnel', '--no-autoupdate', '--url', origin],
|
|
24
|
+
{ cwd: tmpdir(), stdio: ['ignore', 'ignore', 'pipe'] })
|
|
25
|
+
let named = false
|
|
26
|
+
let stopped = false
|
|
27
|
+
const log = []
|
|
28
|
+
// Read to the end even once named, or cloudflared blocks when the pipe fills.
|
|
29
|
+
createInterface({ input: child.stderr }).on('line', line => {
|
|
30
|
+
if (named) return
|
|
31
|
+
log.push(line)
|
|
32
|
+
const name = line.match(NAME)?.[1]
|
|
33
|
+
if (name) { named = true; onName(name) }
|
|
34
|
+
})
|
|
35
|
+
// 'close', not 'exit': by then every line of the log has been read.
|
|
36
|
+
child.on('close', (code, signal) => {
|
|
37
|
+
if (!stopped) onExit(`cloudflared exited (${code ?? signal})${named ? '' : `:\n${log.join('\n')}`}`)
|
|
38
|
+
})
|
|
39
|
+
return { stop() { stopped = true; child.kill() } }
|
|
40
|
+
}
|