@rhizogrip/spore-cli 0.0.0-stage → 1.0.1

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/tui/index.js ADDED
@@ -0,0 +1,598 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { basename, dirname, join } from 'node:path'
5
+
6
+ import { CombinedAutocompleteProvider, Editor, Input, isKeyRelease, Markdown, matchesKey, ProcessTerminal, ScrollView, SelectList, truncateToWidth, TuiAltScreen, visibleWidth, VStack, wrapTextWithAnsi } from '@earendil-works/pi-tui'
7
+ import { changeText, curate, durationText, extendTurn, grantOf, list, loadMohdelEnvironment, outbox, pause, paused, readEvents, readInbox, readTurns, RUNNING, send, SERVICE_STATE_DIR, show, stateOf, stop, switchModel, unpause, upstream, watchAll, wrapTurn } from '@rhizogrip/spore'
8
+ import chalk from 'chalk'
9
+
10
+ import { runningJob, scheduleLine } from '../src/dispatch.js'
11
+ import { COMMANDS, parseCommand } from './commands.js'
12
+ import { applyEvent, createLive, history } from './conversation.js'
13
+ import { changeOf, counts, hunks } from './diff.js'
14
+ import { printable } from './printable.js'
15
+ import { matching, priceText, statusParts } from './status.js'
16
+
17
+ const REFRESH_MS = 1000
18
+ const TWICE_MS = 1500
19
+ const NOTICE_MS = 4000
20
+ const LONG_TURN_MS = 60_000
21
+ const REMEMBERED = join(dirname(SERVICE_STATE_DIR), 'tui.json')
22
+
23
+ const dim = chalk.dim
24
+ const selectTheme = {
25
+ selectedPrefix: chalk.cyan,
26
+ selectedText: chalk.bold,
27
+ description: dim,
28
+ scrollInfo: dim,
29
+ noMatch: dim
30
+ }
31
+ const editorTheme = { borderColor: dim, selectList: selectTheme }
32
+ const markdownTheme = {
33
+ heading: chalk.bold,
34
+ link: chalk.cyan,
35
+ linkUrl: dim,
36
+ code: chalk.yellow,
37
+ codeBlock: (s) => s,
38
+ codeBlockBorder: dim,
39
+ quote: chalk.italic,
40
+ quoteBorder: dim,
41
+ hr: dim,
42
+ listBullet: chalk.cyan,
43
+ bold: chalk.bold,
44
+ italic: chalk.italic,
45
+ strikethrough: chalk.strikethrough,
46
+ underline: chalk.underline
47
+ }
48
+
49
+ export function rememberedSpore () {
50
+ if (!existsSync(REMEMBERED)) return null
51
+ return JSON.parse(readFileSync(REMEMBERED, 'utf8')).ws
52
+ }
53
+
54
+ export function mostRecentSpore () {
55
+ const latest = (row) => row.last?.endedAt ?? ''
56
+ return list().workspaces.sort((a, b) => latest(b).localeCompare(latest(a)))[0]?.ws ?? null
57
+ }
58
+
59
+ const remember = (ws) => {
60
+ mkdirSync(dirname(REMEMBERED), { recursive: true })
61
+ writeFileSync(REMEMBERED, JSON.stringify({ ws }))
62
+ }
63
+
64
+ const lines = (text, width, style = (s) => s) => wrapTextWithAnsi(text, Math.max(1, width)).map(line => style(line))
65
+
66
+ const MOST_DIFF_LINES = 40
67
+ const DIFF_STYLE = { '+': chalk.green, '-': chalk.red, ' ': dim, '…': dim }
68
+
69
+ function changeLines (tool, change, { expanded, width, mark, time }) {
70
+ const { added, removed } = counts(change.diff)
71
+ const tally = [added ? chalk.green(`+${added}`) : '', removed ? chalk.red(`−${removed}`) : ''].filter(Boolean).join(' ')
72
+ const head = truncateToWidth(`${mark} ${tool.name} ${printable(change.path)} ${tally}${time}`, width)
73
+ if (!expanded) return [head]
74
+ const shown = change.whole ? change.diff : hunks(change.diff)
75
+ const body = shown.slice(0, MOST_DIFF_LINES).map(line => truncateToWidth(` ${DIFF_STYLE[line.op](line.op === '…' ? '…' : `${line.op} ${printable(line.text)}`)}`, width))
76
+ const more = shown.length > MOST_DIFF_LINES ? [dim(` … ${shown.length - MOST_DIFF_LINES} more lines`)] : []
77
+ return [head, ...body, ...more]
78
+ }
79
+
80
+ function toolLine (tool, { expanded, width }) {
81
+ const mark = !tool.done ? chalk.yellow('…') : tool.error ? chalk.red('✗') : chalk.green('✓')
82
+ const time = tool.done ? dim(` ${durationText(tool.durationMs)}`) : ''
83
+ const change = changeOf(tool)
84
+ if (change) return changeLines(tool, change, { expanded, width, mark, time })
85
+ const args = JSON.stringify(tool.args)
86
+ if (!expanded) return [truncateToWidth(`${mark} ${tool.name} ${dim(args)}${time}`, width)]
87
+ return [`${mark} ${tool.name}${time}`, ...lines(args, width - 4, dim).map(line => ` ${line}`)]
88
+ }
89
+
90
+ class Conversation {
91
+ constructor ({ renderTool }) {
92
+ this.items = []
93
+ this.live = null
94
+ this.expanded = false
95
+ this.renderTool = renderTool
96
+ this.answers = new WeakMap()
97
+ this.liveAnswer = new Markdown('', 0, 0, markdownTheme)
98
+ }
99
+
100
+ markdown (item) {
101
+ if (!this.answers.has(item)) this.answers.set(item, new Markdown(item.text, 0, 0, markdownTheme))
102
+ return this.answers.get(item)
103
+ }
104
+
105
+ render (width) {
106
+ const out = []
107
+ if (!this.items.length && !this.live) out.push(dim('nothing said yet — write below, / for commands'))
108
+ for (const item of this.items) {
109
+ if (item.kind === 'said') {
110
+ const from = item.origin === 'terminal' ? chalk.cyan('›') : chalk.cyan(`${item.origin} ›`)
111
+ out.push('', ...lines(`${from} ${item.text}${item.waiting && !this.live ? dim(' (not read yet)') : ''}`, width))
112
+ } else if (item.kind === 'answer') {
113
+ out.push('', ...this.markdown(item).render(width))
114
+ } else if (item.kind === 'end') {
115
+ const how = [item.stopReason, item.error].filter(Boolean).join(' · ')
116
+ const took = item.durationMs === null ? '' : ` · ${durationText(item.durationMs)}`
117
+ out.push(dim(truncateToWidth(`── turn ${item.turnNo} · ${how} · ${item.rounds ?? 0} rounds · $${(item.treeUsd ?? 0).toFixed(4)}${took}`, width)))
118
+ if (item.error && item.detail) out.push(...lines(` ${item.detail.split('\n')[0]}`, width, chalk.red))
119
+ }
120
+ }
121
+ if (this.live) {
122
+ out.push('')
123
+ for (const note of this.live.notes) out.push(...lines(note.text, width, note.kind === 'thought' ? chalk.italic : dim))
124
+ for (const tool of this.live.tools) out.push(...(this.renderTool?.(tool, { expanded: this.expanded, width }) ?? toolLine(tool, { expanded: this.expanded, width })))
125
+ if (this.live.text.trim()) {
126
+ this.liveAnswer.setText(this.live.text)
127
+ if (this.live.notes.length || this.live.tools.length) out.push('')
128
+ out.push(...this.liveAnswer.render(width))
129
+ } else if (!this.live.complete && this.live.tools.every(tool => tool.done)) {
130
+ out.push(dim(`thinking${'.'.repeat(1 + Math.floor(Date.now() / 1000) % 3)}`))
131
+ }
132
+ }
133
+ out.push('')
134
+ return out
135
+ }
136
+
137
+ invalidate () {
138
+ this.liveAnswer.invalidate()
139
+ }
140
+ }
141
+
142
+ class StatusLine {
143
+ constructor () {
144
+ this.notice = ''
145
+ this.parts = []
146
+ }
147
+
148
+ render (width) {
149
+ return [
150
+ ...(this.notice ? lines(this.notice, width, chalk.yellow) : []),
151
+ truncateToWidth(dim(this.parts.join(' · ')), width)
152
+ ]
153
+ }
154
+
155
+ invalidate () {}
156
+ }
157
+
158
+ function framed (title, body, footer, width) {
159
+ const inner = Math.max(1, width - 4)
160
+ const edge = (left, text, style, right) => {
161
+ const label = ` ${truncateToWidth(text, Math.max(1, width - 6), '')} `
162
+ return dim(`${left}─`) + style(label) + dim(`${'─'.repeat(Math.max(0, width - 3 - visibleWidth(label)))}${right}`)
163
+ }
164
+ const row = (line) => {
165
+ const fitted = truncateToWidth(line, inner, '')
166
+ return `${dim('│')} ${fitted}${' '.repeat(Math.max(0, inner - visibleWidth(fitted)))} ${dim('│')}`
167
+ }
168
+ return [edge('╭', title, chalk.bold, '╮'), row(''), ...body.map(row), row(''), edge('╰', footer, dim, '╯')]
169
+ }
170
+
171
+ class Picker {
172
+ constructor ({ title = 'open a spore', header = [], items, onSelect, onCancel }) {
173
+ this.title = title
174
+ this.header = header
175
+ this.items = items
176
+ this.onSelect = onSelect
177
+ this.onCancel = onCancel
178
+ this.filter = new Input({ prompt: '› ', placeholder: 'type to filter', placeholderStyle: dim })
179
+ this.filter.focused = true
180
+ this.list = this.listOf(items)
181
+ }
182
+
183
+ listOf (items) {
184
+ const list = new SelectList(items, 12, selectTheme, { minPrimaryColumnWidth: 16, maxPrimaryColumnWidth: 56 })
185
+ list.onSelect = this.onSelect
186
+ list.onCancel = this.onCancel
187
+ return list
188
+ }
189
+
190
+ handleInput (data) {
191
+ if (matchesKey(data, 'up') || matchesKey(data, 'down') || matchesKey(data, 'enter') || matchesKey(data, 'escape')) return this.list.handleInput(data)
192
+ this.filter.handleInput(data)
193
+ this.list = this.listOf(matching(this.items, this.filter.getValue()))
194
+ }
195
+
196
+ render (width) {
197
+ const inner = Math.max(1, width - 4)
198
+ const above = this.header.length ? [...this.header.flatMap(line => lines(line, inner, dim)), ''] : []
199
+ return framed(this.title, [...above, ...this.filter.render(inner), '', ...this.list.render(inner)], '↑↓ enter · esc', width)
200
+ }
201
+
202
+ invalidate () {
203
+ this.filter.invalidate()
204
+ this.list.invalidate()
205
+ }
206
+ }
207
+
208
+ class Panel {
209
+ constructor (title, text, onClose, { confirming = null, onConfirm = null } = {}) {
210
+ this.title = title
211
+ this.text = text
212
+ this.onClose = onClose
213
+ this.confirming = confirming
214
+ this.onConfirm = onConfirm
215
+ }
216
+
217
+ handleInput (data) {
218
+ if (this.onConfirm && matchesKey(data, 'enter')) return this.onConfirm()
219
+ if (matchesKey(data, 'escape') || matchesKey(data, 'enter') || matchesKey(data, 'q')) this.onClose()
220
+ }
221
+
222
+ render (width) {
223
+ const footer = this.onConfirm ? `enter to ${this.confirming} · esc to leave it` : 'esc to close'
224
+ return framed(this.title, this.text.split('\n').flatMap(line => lines(line, Math.max(1, width - 4))), footer, width)
225
+ }
226
+
227
+ invalidate () {}
228
+ }
229
+
230
+ /** A choice made before any spore is open: the value picked, or null when it was left. */
231
+ export function choose ({ title, header = [], items, terminal = new ProcessTerminal() }) {
232
+ const tui = new TuiAltScreen(terminal)
233
+ return new Promise(resolve => {
234
+ const done = (value) => {
235
+ tui.stop({ preserveScreen: true })
236
+ resolve(value)
237
+ }
238
+ const picker = new Picker({ title, header, items, onSelect: (item) => done(item.value), onCancel: () => done(null) })
239
+ tui.addInputListener((data) => {
240
+ if (matchesKey(data, 'ctrl+c') || matchesKey(data, 'ctrl+d')) {
241
+ done(null)
242
+ return { consume: true }
243
+ }
244
+ return undefined
245
+ })
246
+ tui.setLayoutRoot(new VStack([{ component: picker, basis: 'auto' }]))
247
+ tui.setFocus(picker)
248
+ tui.start()
249
+ })
250
+ }
251
+
252
+ const ago = (iso, now) => (iso ? `${durationText(now - Date.parse(iso))} ago` : 'never')
253
+
254
+ /**
255
+ * Runs the terminal on `ws` until it is left; resolves with the exit code. `commands` are added
256
+ * to the built-in ones, each `{ name, description, argumentHint?, run(args, context) }`, the
257
+ * context being `{ ws, notice, send, outside(fn), confirm(title, text, confirming), running() }`:
258
+ * `outside` runs `fn` on the bare terminal (a pager, an editor) and comes back, `confirm` resolves
259
+ * true on Enter. `renderTool(tool, { expanded, width })` draws a tool call as lines, or returns
260
+ * null for the default; `greeting` is a line shown as the screen opens.
261
+ */
262
+ export async function runTui ({ ws, commands = [], renderTool = null, greeting = null, terminal = new ProcessTerminal() }) {
263
+ const tui = new TuiAltScreen(terminal)
264
+ const conversation = new Conversation({ renderTool })
265
+ const status = new StatusLine()
266
+ const editor = new Editor(tui, editorTheme)
267
+ const view = new ScrollView(conversation, { follow: 'end', primary: true })
268
+ tui.setLayoutRoot(new VStack([
269
+ { component: view, basis: 0, grow: 1, minSize: 1 },
270
+ { component: status, basis: 'auto' },
271
+ { component: editor, basis: 'auto', shrink: 1, minSize: 3 }
272
+ ]))
273
+ const allCommands = [...COMMANDS, ...commands]
274
+ editor.setAutocompleteProvider(new CombinedAutocompleteProvider(allCommands.map(({ name, description, argumentHint }) => ({ name, description, argumentHint })), process.cwd()))
275
+ tui.setFocus(editor)
276
+
277
+ const following = new AbortController()
278
+ const state = { ws: null, grant: null, limits: null, shown: null, attention: new Map(), lastSeq: 0, overlay: null, pressed: {} }
279
+ let finish
280
+
281
+ const notice = (text) => {
282
+ status.notice = text
283
+ clearTimeout(state.noticeTimer)
284
+ state.noticeTimer = setTimeout(() => { status.notice = ''; tui.requestRender() }, Math.max(NOTICE_MS, text.length * 60))
285
+ tui.requestRender()
286
+ }
287
+ const notify = (text) => terminal.write(`\x1b]9;${printable(text).replace(/\n/g, ' ')}\x07`)
288
+
289
+ const refresh = () => {
290
+ const now = stateOf(state.ws)
291
+ if (now.state !== RUNNING) state.limits = null
292
+ else if (!state.limits) state.limits = show({ ws: state.ws }).turnLimits
293
+ state.shown = { ws: state.ws, model: state.grant.model, billing: state.grant.billing, ...now, turnLimits: state.limits }
294
+ const live = conversation.live ?? createLive()
295
+ status.parts = statusParts({ shown: state.shown, live, paused: Boolean(paused()), attention: [...state.attention.values()], now: Date.now() })
296
+ tui.requestRender()
297
+ }
298
+
299
+ const reload = () => {
300
+ conversation.items = history({ turns: readTurns(state.ws), inbox: readInbox(state.ws) })
301
+ conversation.live = null
302
+ state.limits = null
303
+ if (stateOf(state.ws).state === RUNNING) {
304
+ const ends = readEvents(state.ws, { event: 'turn_end' })
305
+ const live = createLive()
306
+ for (const event of readEvents(state.ws, { after: ends.at(-1)?.seq ?? 0 })) {
307
+ applyEvent(live, event)
308
+ state.lastSeq = event.seq
309
+ }
310
+ conversation.live = live
311
+ }
312
+ conversation.invalidate()
313
+ refresh()
314
+ }
315
+
316
+ const open = (ws) => {
317
+ state.ws = ws
318
+ state.attention.delete(ws)
319
+ state.grant = grantOf(ws)
320
+ state.lastSeq = 0
321
+ remember(ws)
322
+ reload()
323
+ view.scrollToEnd()
324
+ }
325
+
326
+ const closeOverlay = () => {
327
+ state.overlay?.hide()
328
+ state.overlay = null
329
+ tui.setFocus(editor)
330
+ tui.requestRender()
331
+ }
332
+
333
+ const overlay = (component) => {
334
+ closeOverlay()
335
+ state.overlay = tui.showOverlay(component, { width: '80%', maxHeight: '70%' })
336
+ }
337
+
338
+ const picker = () => {
339
+ const now = Date.now()
340
+ const rows = list().workspaces
341
+ overlay(new Picker({
342
+ items: rows.map(row => ({
343
+ value: row.ws,
344
+ label: `${state.attention.has(row.ws) ? '● ' : ''}${basename(row.ws)}`,
345
+ description: `${row.state} · ${row.lastTurnNo} turns · $${row.treeUsd.toFixed(4)} · ${ago(row.last?.endedAt, now)}`
346
+ })),
347
+ onSelect: (item) => { closeOverlay(); open(item.value) },
348
+ onCancel: closeOverlay
349
+ }))
350
+ }
351
+
352
+ const statusPanel = () => {
353
+ const shown = show({ ws: state.ws })
354
+ const waiting = outbox(state.ws, { state: 'pending' })
355
+ const refused = outbox(state.ws, { state: 'refused' }).slice(-3)
356
+ const sections = [
357
+ ['workspace', [state.ws]],
358
+ ['works in', shown.writes.map(w => `${w.name}/ → ${w.path}`)],
359
+ ['jobs', shown.jobs.running.map(runningJob)],
360
+ ['schedules', shown.schedules.map(scheduleLine)],
361
+ ['held', shown.held.map(h => `${h.origin}: until ${h.releaseAt}${h.summary ? ` — ${h.summary}` : ''}`)],
362
+ ['waiting to be delivered', waiting.map(e => `${e.recipient} · since ${e.at}`)],
363
+ ['refused', refused.map(e => `${e.recipient} · ${e.settledAt} — ${e.reason}`)],
364
+ ['docs that differ', shown.differs.length ? [`${shown.differs.join(', ')} — spore upgrade ${basename(state.ws)}`] : []]
365
+ ].filter(([, rows]) => rows.length)
366
+ overlay(new Panel(`${basename(state.ws)} · ${shown.model}`,
367
+ sections.map(([title, rows]) => `${title}\n${rows.map(row => ` ${row}`).join('\n')}`).join('\n\n'), closeOverlay))
368
+ }
369
+
370
+ const helpPanel = () => overlay(new Panel('keys and commands', [
371
+ 'enter send · alt+enter new line · ↑↓ earlier messages · tab complete',
372
+ 'ctrl+p open another spore · ctrl+o show tool calls in full · ctrl+g write in $EDITOR',
373
+ 'esc twice stop the running turn, or clear the line when none runs · ctrl+c clear · ctrl+d on an empty line leave',
374
+ '',
375
+ ...allCommands.map(c => `/${c.name}${c.argumentHint ? ` ${c.argumentHint}` : ''} — ${c.description}`)
376
+ ].join('\n'), closeOverlay))
377
+
378
+ const leave = () => {
379
+ following.abort()
380
+ clearInterval(ticking)
381
+ tui.stop({ preserveScreen: true })
382
+ finish(0)
383
+ }
384
+
385
+ const say = (text) => {
386
+ let sent
387
+ try {
388
+ sent = send(state.ws, text, { replyTo: 'terminal' })
389
+ } catch (err) {
390
+ return notice(err.detail ? `${err.message} — ${err.detail}` : err.message)
391
+ }
392
+ editor.addToHistory(text)
393
+ notice(sent.started ? 'started a turn' : 'heard — the running turn reads it next')
394
+ reload()
395
+ view.scrollToEnd()
396
+ }
397
+
398
+ const change = (act) => {
399
+ try {
400
+ notice(changeText(act()))
401
+ state.limits = show({ ws: state.ws }).turnLimits
402
+ refresh()
403
+ } catch (err) {
404
+ notice(err.detail ? `${err.message} — ${err.detail}` : err.message)
405
+ }
406
+ }
407
+
408
+ const run = async ({ name, args }) => {
409
+ if (name === 'stop') return notice(stop(state.ws).stopped ? 'stopping it' : 'nothing is running')
410
+ if (name === 'wrap') return change(() => wrapTurn(state.ws, args[0]))
411
+ if (name === 'extend') {
412
+ if (args.length < 2) return notice('/extend wall 30m, /extend cost 1.50 or /extend rounds 20')
413
+ return change(() => extendTurn(state.ws, args[0], args[1]))
414
+ }
415
+ if (name === 'model') {
416
+ const switchTo = (model) => {
417
+ try {
418
+ const switched = switchModel({ ws: state.ws, model })
419
+ notice(switched.was === switched.model ? `already runs on ${switched.model}` : `runs on ${switched.model} from the next turn`)
420
+ refresh()
421
+ } catch (err) {
422
+ notice(err.detail ? `${err.message} — ${err.detail}` : err.message)
423
+ }
424
+ }
425
+ if (args.length) return switchTo(args[0])
426
+ const { model, models } = show({ ws: state.ws })
427
+ if (!models.length) return notice(`runs on ${model} — add models: to its spore.cmk to offer others`)
428
+ return overlay(new Picker({
429
+ items: [model, ...models].map(one => ({ value: one, label: one, description: one === model ? 'now' : '' })),
430
+ onSelect: (item) => { closeOverlay(); switchTo(item.value) },
431
+ onCancel: closeOverlay
432
+ }))
433
+ }
434
+ if (name === 'curate') {
435
+ const provider = args[0] ?? show({ ws: state.ws }).model.split('/')[0]
436
+ loadMohdelEnvironment()
437
+ notice(`reading what ${provider} lists…`)
438
+ let listed
439
+ try {
440
+ listed = await upstream(provider)
441
+ } catch (err) {
442
+ return notice(err.message)
443
+ }
444
+ if (listed === null) return notice(`mohdel cannot list ${provider}'s models — without its key, mo onboard ${provider} sets it`)
445
+ if (!listed.length) return notice(`${provider} lists nothing your catalog does not already hold or exclude`)
446
+ const add = async (id) => {
447
+ try {
448
+ const [added] = await curate(provider, [id])
449
+ notice(`${added.model} is in your catalog${added.priced === false ? ', without prices: its calls count as $0' : ''} — ` +
450
+ `spore edit adds it to a spore's models:, spore config set model ${added.model} makes new spores run on it`)
451
+ } catch (err) {
452
+ notice(err.message)
453
+ }
454
+ }
455
+ return overlay(new Picker({
456
+ title: `a ${provider} model for your catalog`,
457
+ header: [`${listed.length} not in it yet — mohdel's catalog, shared with mo and every spore`],
458
+ items: listed.map(one => ({ value: one.id, label: one.id, description: priceText(one) })),
459
+ onSelect: (item) => { closeOverlay(); add(item.value) },
460
+ onCancel: closeOverlay
461
+ }))
462
+ }
463
+ if (name === 'pause') {
464
+ const done = pause({ why: args.join(' ') || undefined })
465
+ return notice(`paused${done.turns.length ? ` — stopped ${done.turns.length} turn${done.turns.length > 1 ? 's' : ''}` : ''}`)
466
+ }
467
+ if (name === 'unpause') return notice(unpause().unpaused ? 'turns start again' : 'it was not paused')
468
+ if (name === 'spores') return picker()
469
+ if (name === 'status') return statusPanel()
470
+ if (name === 'help') return helpPanel()
471
+ if (name === 'quit') return leave()
472
+ if (name === 'copy') {
473
+ const answer = conversation.live?.complete?.output ?? [...conversation.items].reverse().find(item => item.kind === 'answer')?.text
474
+ if (!answer) return notice('no answer to copy yet')
475
+ terminal.write(`\x1b]52;c;${Buffer.from(answer).toString('base64')}\x07`)
476
+ return notice('copied the last answer')
477
+ }
478
+ const added = commands.find(c => c.name === name)
479
+ if (!added) return notice(`no /${name} — /help lists them`)
480
+ try {
481
+ await added.run(args, { ws: state.ws, notice, send: say, outside, confirm, running: () => state.shown?.state === RUNNING })
482
+ } catch (err) {
483
+ notice(err.message)
484
+ }
485
+ }
486
+
487
+ editor.onSubmit = (text) => {
488
+ const trimmed = text.trim()
489
+ if (!trimmed) return
490
+ editor.setText('')
491
+ const command = parseCommand(trimmed)
492
+ if (command) return run(command)
493
+ say(trimmed.startsWith('//') ? trimmed.slice(1) : trimmed)
494
+ }
495
+
496
+ const twice = (key, first, then) => {
497
+ const now = Date.now()
498
+ if (now - (state.pressed[key] ?? 0) < TWICE_MS) {
499
+ state.pressed[key] = 0
500
+ return then()
501
+ }
502
+ state.pressed[key] = now
503
+ notice(first)
504
+ }
505
+
506
+ const outside = (fn) => {
507
+ tui.stop({ preserveScreen: true })
508
+ try {
509
+ return fn()
510
+ } finally {
511
+ tui.start()
512
+ tui.requestRender(true)
513
+ }
514
+ }
515
+
516
+ const confirm = (title, text, confirming) => new Promise(resolve => {
517
+ overlay(new Panel(title, text, () => { closeOverlay(); resolve(false) }, { confirming, onConfirm: () => { closeOverlay(); resolve(true) } }))
518
+ })
519
+
520
+ const compose = () => {
521
+ const directory = mkdtempSync(join(tmpdir(), 'spore-tui-'))
522
+ const file = join(directory, 'message.md')
523
+ writeFileSync(file, editor.getText())
524
+ const [command, ...flags] = (process.env.VISUAL || process.env.EDITOR || 'vi').split(' ')
525
+ const done = outside(() => spawnSync(command, [...flags, file], { stdio: 'inherit' }))
526
+ if (done.status === 0) editor.setText(readFileSync(file, 'utf8').replace(/\n$/, ''))
527
+ else notice(`${command} did not finish — the message is as it was`)
528
+ rmSync(directory, { recursive: true, force: true })
529
+ }
530
+
531
+ tui.addInputListener((data) => {
532
+ if (isKeyRelease(data)) return undefined
533
+ if (matchesKey(data, 'ctrl+c')) {
534
+ if (state.overlay) {
535
+ closeOverlay()
536
+ return { consume: true }
537
+ }
538
+ if (editor.getText()) {
539
+ editor.setText('')
540
+ tui.requestRender()
541
+ return { consume: true }
542
+ }
543
+ notice('ctrl+d to leave')
544
+ return { consume: true }
545
+ }
546
+ if (state.overlay) return undefined
547
+ if (matchesKey(data, 'ctrl+d') && !editor.getText()) {
548
+ leave()
549
+ return { consume: true }
550
+ }
551
+ if (matchesKey(data, 'ctrl+p')) { picker(); return { consume: true } }
552
+ if (matchesKey(data, 'ctrl+o')) { conversation.expanded = !conversation.expanded; tui.requestRender(); return { consume: true } }
553
+ if (matchesKey(data, 'ctrl+g')) { compose(); return { consume: true } }
554
+ if (matchesKey(data, 'escape') && !editor.isShowingAutocomplete()) {
555
+ if (state.shown?.state === RUNNING) {
556
+ twice('escape', editor.getText() ? 'esc again to stop the turn — ctrl+c clears the line' : 'esc again to stop the turn', () => notice(stop(state.ws).stopped ? 'stopping it' : 'nothing is running'))
557
+ return { consume: true }
558
+ }
559
+ if (!editor.getText()) return undefined
560
+ twice('escape', 'esc again to clear', () => { editor.setText(''); tui.requestRender() })
561
+ return { consume: true }
562
+ }
563
+ return undefined
564
+ })
565
+
566
+ const follow = async () => {
567
+ for await (const item of watchAll(() => list().workspaces.map(row => row.ws), { signal: following.signal })) {
568
+ if (item.ws === state.ws) {
569
+ if (item.event) {
570
+ if (item.event.seq <= state.lastSeq) continue
571
+ state.lastSeq = item.event.seq
572
+ const live = conversation.live ?? createLive()
573
+ if (applyEvent(live, item.event)) {
574
+ conversation.live = live
575
+ tui.requestRender()
576
+ }
577
+ continue
578
+ }
579
+ const { startedAt, endedAt } = item.turn.record
580
+ if (Date.parse(endedAt) - Date.parse(startedAt) > LONG_TURN_MS) notify(`${basename(item.ws)}: ${item.turn.record.stopReason}`)
581
+ reload()
582
+ continue
583
+ }
584
+ if (!item.turn) continue
585
+ const asked = item.turn.record.stopReason === 'question'
586
+ state.attention.set(item.ws, { name: basename(item.ws), asked })
587
+ notify(`${basename(item.ws)} ${asked ? 'asked' : 'answered'}`)
588
+ refresh()
589
+ }
590
+ }
591
+
592
+ open(ws)
593
+ if (greeting) notice(greeting)
594
+ tui.start()
595
+ const ticking = setInterval(refresh, REFRESH_MS)
596
+ follow().catch(err => notice(`stopped following the spores — ${err.message}`))
597
+ return new Promise(resolve => { finish = resolve })
598
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Text from a model or a tool, made safe to put on a terminal: no escape or control byte that
3
+ * the terminal would act on (a cursor move, a screen clear, an OSC 52 clipboard write), and no
4
+ * bidirectional override that would show it in another order than it reads. Newlines stay,
5
+ * since an answer is prose; a tab becomes spaces.
6
+ */
7
+
8
+ // C0 controls but newline and tab, DEL, the C1 block, and the bidi embeddings, overrides and
9
+ // isolates.
10
+ // eslint-disable-next-line no-control-regex
11
+ const UNPRINTABLE = /[\x00-\x08\x0b-\x1f\x7f-\x9f‪-‮⁦-⁩]/g
12
+
13
+ export const printable = (text) => String(text).replace(/\t/g, ' ').replace(UNPRINTABLE, '')
package/tui/status.js ADDED
@@ -0,0 +1,62 @@
1
+ import { basename } from 'node:path'
2
+
3
+ import { durationText, RUNNING } from '@rhizogrip/spore'
4
+
5
+ const thousands = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n))
6
+
7
+ const bound = ({ soft, hard }, used) => (used > soft ? hard : soft)
8
+
9
+ const unmetered = (shown) => shown.billing && shown.billing.kind !== 'metered'
10
+
11
+ export function stateText (shown, { paused, now }) {
12
+ if (paused) return 'paused'
13
+ if (shown.state !== RUNNING) return shown.state
14
+ if (shown.draining) return 'finishing'
15
+ if (shown.turnLimits?.limits.wall) return 'running'
16
+ return `running ${durationText(now - Date.parse(shown.startedAt))}`
17
+ }
18
+
19
+ export function limitsText ({ startedAt, limits }, { rounds, cost, now }) {
20
+ const parts = []
21
+ if (limits.rounds) parts.push(`round ${rounds}/${bound(limits.rounds, rounds)}`)
22
+ if (limits.wall) {
23
+ const elapsed = now - Date.parse(startedAt)
24
+ parts.push(`${durationText(elapsed)}/${durationText(bound(limits.wall, elapsed))}`)
25
+ }
26
+ if (limits.cost && cost !== null) parts.push(`≈$${cost.toFixed(4)}/$${bound(limits.cost, cost).toFixed(2)}`)
27
+ return parts.join(' · ')
28
+ }
29
+
30
+ export function spendText (shown) {
31
+ if (unmetered(shown)) return `not metered · ${shown.billing.label}`
32
+ return `$${shown.treeUsd.toFixed(4)}`
33
+ }
34
+
35
+ export const attentionText = (attention) => attention.map(({ name, asked }) => `${name} ${asked ? 'asked' : 'answered'}`).join(' · ')
36
+
37
+ export function statusParts ({ shown, live, paused, attention, now }) {
38
+ const parts = [basename(shown.ws), stateText(shown, { paused, now })]
39
+ if (attention.length) parts.push(`${attentionText(attention)} — Ctrl+P`)
40
+ const limited = Boolean(shown.turnLimits) && !shown.draining
41
+ if (limited) parts.push(limitsText(shown.turnLimits, { rounds: live.rounds, cost: unmetered(shown) ? null : live.cost, now }))
42
+ if (live.input !== null) parts.push(`${thousands(live.input)} in`)
43
+ if (!limited || unmetered(shown)) parts.push(spendText(shown))
44
+ parts.push(shown.model)
45
+ return parts
46
+ }
47
+
48
+ const perMillion = (price) => `$${Number(price.toPrecision(4))}`
49
+
50
+ /** A listed model's prices per million tokens, or that the listing gives none. */
51
+ export const priceText = ({ inputPrice, outputPrice }) => inputPrice === null || outputPrice === null
52
+ ? 'no prices'
53
+ : `${perMillion(inputPrice)} in · ${perMillion(outputPrice)} out per million tokens`
54
+
55
+ /** The items holding every word typed, in any order, anywhere in their label, value or description. */
56
+ export const matching = (items, typed) => {
57
+ const words = typed.toLowerCase().split(/\s+/).filter(Boolean)
58
+ return items.filter(item => {
59
+ const text = `${item.label} ${item.value} ${item.description ?? ''}`.toLowerCase()
60
+ return words.every(word => text.includes(word))
61
+ })
62
+ }