@rhizogrip/spore-cli 0.0.0-stage → 1.0.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 +202 -0
- package/NOTICE +2 -0
- package/README.md +20 -2
- package/bin/spore.js +521 -0
- package/package.json +50 -4
- package/src/dispatch.js +736 -0
- package/src/doctor.js +75 -0
- package/src/here.js +105 -0
- package/src/hooks.js +89 -0
- package/src/services.js +567 -0
- package/src/setup.js +265 -0
- package/tui/README.md +49 -0
- package/tui/commands.js +22 -0
- package/tui/conversation.js +89 -0
- package/tui/diff.js +71 -0
- package/tui/here.js +86 -0
- package/tui/index.js +598 -0
- package/tui/printable.js +13 -0
- package/tui/status.js +62 -0
package/src/setup.js
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `spore setup`: a person's first run, as one path through what the commands already do. Each step
|
|
3
|
+
* looks first and says what it found, so a second run is a check; it keeps no state of its own.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { spawnSync } from 'node:child_process'
|
|
7
|
+
import { basename } from 'node:path'
|
|
8
|
+
import { createInterface } from 'node:readline/promises'
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
checkSqlite, CONFIG_FILE, defaultModel, define, doctor, list, loadMohdelEnvironment, MO,
|
|
12
|
+
modelReadiness, modelsOf, providerReadiness, readConfig, setDefaultModel, setKey, settings
|
|
13
|
+
} from '@rhizogrip/spore'
|
|
14
|
+
|
|
15
|
+
import { createServices } from './services.js'
|
|
16
|
+
import { diagnose, renderDoctor } from './doctor.js'
|
|
17
|
+
|
|
18
|
+
const ANOTHER = 'another'
|
|
19
|
+
|
|
20
|
+
const PROVIDERS = [
|
|
21
|
+
{ value: 'chatgpt', label: 'ChatGPT', description: 'sign in to your ChatGPT plan — its calls are not metered' },
|
|
22
|
+
{ value: 'openrouter', label: 'OpenRouter', description: 'one key for many providers\' models, priced by mohdel' },
|
|
23
|
+
{ value: ANOTHER, label: 'another provider', description: 'mohdel\'s own setup, every provider it knows' }
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
const providerOf = (model) => model.split('/')[0]
|
|
27
|
+
|
|
28
|
+
const SHOWN = 20
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A pick from a numbered list on the plain terminal, so setup runs where the screen is not installed:
|
|
32
|
+
* a number picks, words narrow the list, empty leaves it. The value picked, or null when left.
|
|
33
|
+
*/
|
|
34
|
+
export async function pickFromList ({ title, header = [], items }, { prompt = ask, say = console.log } = {}) {
|
|
35
|
+
say('')
|
|
36
|
+
say(title)
|
|
37
|
+
for (const line of header) say(` ${line}`)
|
|
38
|
+
let shown = items
|
|
39
|
+
while (true) {
|
|
40
|
+
const width = String(Math.min(shown.length, SHOWN)).length
|
|
41
|
+
shown.slice(0, SHOWN).forEach((item, i) => say(` ${String(i + 1).padStart(width)} ${item.label}${item.description ? ` — ${item.description}` : ''}`))
|
|
42
|
+
if (shown.length > SHOWN) say(` … and ${shown.length - SHOWN} more — words narrow the list`)
|
|
43
|
+
const answer = await prompt('a number, or words to narrow the list — empty to leave:')
|
|
44
|
+
if (!answer) return null
|
|
45
|
+
if (/^\d+$/.test(answer)) {
|
|
46
|
+
const chosen = shown.slice(0, SHOWN)[Number(answer) - 1]
|
|
47
|
+
if (chosen) return chosen.value
|
|
48
|
+
say(` ${answer} is not in the list`)
|
|
49
|
+
continue
|
|
50
|
+
}
|
|
51
|
+
const words = answer.toLowerCase().split(/\s+/)
|
|
52
|
+
const narrowed = items.filter(item => words.every(word => `${item.label} ${item.description ?? ''}`.toLowerCase().includes(word)))
|
|
53
|
+
if (narrowed.length) shown = narrowed
|
|
54
|
+
else say(` nothing matches ${answer}`)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function ask (question, preset = '') {
|
|
59
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout })
|
|
60
|
+
prompt.on('SIGINT', () => process.exit(130))
|
|
61
|
+
try {
|
|
62
|
+
return (await prompt.question(preset ? `${question} [${preset}] ` : `${question} `)).trim() || preset
|
|
63
|
+
} finally {
|
|
64
|
+
prompt.close()
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const onboardWithMo = (provider) => spawnSync(process.execPath, [MO, 'onboard', ...(provider ? [provider] : [])], { stdio: 'inherit' }).status
|
|
69
|
+
|
|
70
|
+
const readings = { loadKeys: loadMohdelEnvironment, modelReadiness, modelsOf, providerReadiness }
|
|
71
|
+
|
|
72
|
+
const billingText = ({ billing, priced }) => billing === 'plan'
|
|
73
|
+
? 'your plan — not metered'
|
|
74
|
+
: priced === false ? 'no prices: its calls count as $0 against cost and spend limits' : billing
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Resolves with the exit code: 0 once every step is done, 1 when one stops, saying what to do
|
|
78
|
+
* before running it again.
|
|
79
|
+
*/
|
|
80
|
+
export async function setup ({
|
|
81
|
+
say = console.log,
|
|
82
|
+
prompt = ask,
|
|
83
|
+
pick = (menu) => pickFromList(menu, { prompt, say }),
|
|
84
|
+
onboard = onboardWithMo,
|
|
85
|
+
mohdel = readings,
|
|
86
|
+
services = createServices(),
|
|
87
|
+
examine = doctor,
|
|
88
|
+
report = diagnose,
|
|
89
|
+
sqlite = checkSqlite
|
|
90
|
+
} = {}) {
|
|
91
|
+
const yes = async (question) => /^y(es)?$/i.test(await prompt(`${question} [y/N]`))
|
|
92
|
+
const line = (label, text) => say(`${label.padEnd(10)}${text}`)
|
|
93
|
+
|
|
94
|
+
line('node', `${process.version}, SQLite ${sqlite()}`)
|
|
95
|
+
|
|
96
|
+
const found = examine().findings
|
|
97
|
+
const config = found.find(one => one.subject === CONFIG_FILE && one.severity === 'problem')
|
|
98
|
+
if (config) {
|
|
99
|
+
line('config', `${config.problem} — ${config.fix}`)
|
|
100
|
+
return 1
|
|
101
|
+
}
|
|
102
|
+
const machine = found.filter(one => one.area === 'machine')
|
|
103
|
+
for (const one of machine.filter(one => one.subject !== 'processes')) {
|
|
104
|
+
line(one.subject, `${one.problem} — ${one.fix}`)
|
|
105
|
+
if (one.severity === 'problem') return 1
|
|
106
|
+
}
|
|
107
|
+
const processes = machine.find(one => one.subject === 'processes')
|
|
108
|
+
if (processes?.severity === 'problem') {
|
|
109
|
+
line('processes', processes.problem)
|
|
110
|
+
say(`${''.padEnd(10)}without them, a turn sees the processes and command lines of every other spore of yours —\n${''.padEnd(10)}which matters only when spores of other people run as this user`)
|
|
111
|
+
if (!await yes('run your spores uncontained?')) {
|
|
112
|
+
say(`${''.padEnd(10)}${processes.fix}, then spore setup again`)
|
|
113
|
+
return 1
|
|
114
|
+
}
|
|
115
|
+
setKey('contain', 'off')
|
|
116
|
+
line('processes', 'contain off — spore config set contain on when this host gives namespaces')
|
|
117
|
+
} else if (processes) {
|
|
118
|
+
line('processes', processes.problem)
|
|
119
|
+
} else {
|
|
120
|
+
line('kernel', 'Landlock confines every turn, each in namespaces of its own')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const { home } = readConfig()
|
|
124
|
+
if (home) {
|
|
125
|
+
line('home', home)
|
|
126
|
+
} else {
|
|
127
|
+
const dir = await prompt('where should your spores live?', '~/spores')
|
|
128
|
+
setKey('home', dir)
|
|
129
|
+
line('home', `${readConfig().home} — spore config set home <dir> moves where new ones are made`)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const model = await chooseModel({ line, say, pick, onboard, mohdel })
|
|
133
|
+
if (model === null) return 1
|
|
134
|
+
|
|
135
|
+
const spend = settings().find(row => row.key === 'spendPerDay')
|
|
136
|
+
if (spend.from === 'set') {
|
|
137
|
+
line('spend', `at most $${spend.value} a day`)
|
|
138
|
+
} else {
|
|
139
|
+
const dollars = await prompt('a daily spend limit for your spores, in dollars — empty for none:')
|
|
140
|
+
if (dollars) setKey('spendPerDay', dollars)
|
|
141
|
+
line('spend', dollars ? `at most $${dollars} a day` : 'no daily limit — spore config set spendPerDay <dollars> sets one')
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
await tickTimer({ line, yes, services })
|
|
145
|
+
|
|
146
|
+
say('')
|
|
147
|
+
const diagnosed = await report({ services })
|
|
148
|
+
if (diagnosed.findings.length) renderDoctor(diagnosed)
|
|
149
|
+
else line('checked', 'this machine, your config and your spores — nothing to fix')
|
|
150
|
+
say('')
|
|
151
|
+
if (diagnosed.findings.some(one => one.severity === 'problem')) {
|
|
152
|
+
say('fix those, then spore setup again — spore doctor checks just that part')
|
|
153
|
+
return 1
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const names = list().workspaces.map(({ ws }) => basename(ws))
|
|
157
|
+
if (names.length) {
|
|
158
|
+
line('spores', names.join(', '))
|
|
159
|
+
} else {
|
|
160
|
+
const made = define({ ws: 'main' })
|
|
161
|
+
names.push('main')
|
|
162
|
+
line('made', `main, your first spore, in ${made.ws}`)
|
|
163
|
+
}
|
|
164
|
+
const first = names.includes('main') ? 'main' : names[0]
|
|
165
|
+
say('')
|
|
166
|
+
say('next')
|
|
167
|
+
for (const [command, what] of [
|
|
168
|
+
[`spore tui ${first}`, `talk to ${first} in a terminal screen`],
|
|
169
|
+
[`spore send ${first} "…"`, 'or send it one message; the answer is printed'],
|
|
170
|
+
['cd <project> && spore here', 'a spore that works on that project\'s files — git undoes what it changes'],
|
|
171
|
+
['spore', 'every command']
|
|
172
|
+
]) say(` ${command.padEnd(30)}${what}`)
|
|
173
|
+
return 0
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Where another model comes from, and how a spore is given it: said, never done, by setup. */
|
|
177
|
+
function otherModels (say, provider) {
|
|
178
|
+
const pad = ''.padEnd(10)
|
|
179
|
+
say(`${pad}another model: /curate in spore tui, or mo curate ${provider}, adds it to your catalog —`)
|
|
180
|
+
say(`${pad}then spore config set model <provider>/<name> for new spores, or spore edit <spore> and add it to models:`)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The default model, ready to run: the one set, or a provider set up through mohdel and one of its models picked. Null stops setup. */
|
|
184
|
+
async function chooseModel ({ line, say, pick, onboard, mohdel }) {
|
|
185
|
+
mohdel.loadKeys()
|
|
186
|
+
const current = defaultModel().model
|
|
187
|
+
if (current) {
|
|
188
|
+
let ready = await mohdel.modelReadiness(current)
|
|
189
|
+
if (!ready.ready) {
|
|
190
|
+
line('model', `${current} is not ready — mohdel sets it up`)
|
|
191
|
+
onboard(providerOf(current))
|
|
192
|
+
mohdel.loadKeys()
|
|
193
|
+
ready = await mohdel.modelReadiness(current)
|
|
194
|
+
if (!ready.ready) {
|
|
195
|
+
line('model', `${current} is still not ready — ${ready.fix}, then spore setup again`)
|
|
196
|
+
return null
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
line('model', `${current}, ${ready.priced === false ? `${billingText(ready)} — ${ready.fix}` : 'ready'}`)
|
|
200
|
+
otherModels(say, providerOf(current))
|
|
201
|
+
return current
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const provider = await pick({ title: 'the models your spores run on', header: ['mohdel calls them; a provider set up here is set up for mo as well'], items: PROVIDERS })
|
|
205
|
+
if (!provider) return null
|
|
206
|
+
if (provider === ANOTHER) {
|
|
207
|
+
onboard(null)
|
|
208
|
+
mohdel.loadKeys()
|
|
209
|
+
} else if (!(await mohdel.providerReadiness(provider)).ready) {
|
|
210
|
+
onboard(provider)
|
|
211
|
+
mohdel.loadKeys()
|
|
212
|
+
const ready = await mohdel.providerReadiness(provider)
|
|
213
|
+
if (!ready.ready) {
|
|
214
|
+
line('model', `${provider} is not ready — ${ready.fix}, then spore setup again`)
|
|
215
|
+
return null
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const credentials = new Map()
|
|
220
|
+
const usable = []
|
|
221
|
+
for (const one of await mohdel.modelsOf(provider === ANOTHER ? null : provider)) {
|
|
222
|
+
const named = providerOf(one.model)
|
|
223
|
+
if (!credentials.has(named)) credentials.set(named, (await mohdel.providerReadiness(named)).credential)
|
|
224
|
+
if (credentials.get(named)) usable.push(one)
|
|
225
|
+
}
|
|
226
|
+
if (!usable.length) {
|
|
227
|
+
line('model', 'no provider has a model ready yet — mo onboard <provider>, then spore setup again')
|
|
228
|
+
return null
|
|
229
|
+
}
|
|
230
|
+
const model = await pick({
|
|
231
|
+
title: 'the model new spores run on',
|
|
232
|
+
header: ['spore model <name> <model> changes one spore\'s later'],
|
|
233
|
+
items: usable.map(one => ({ value: one.model, label: one.model, description: billingText(one) }))
|
|
234
|
+
})
|
|
235
|
+
if (!model) return null
|
|
236
|
+
const chosen = usable.find(one => one.model === model)
|
|
237
|
+
setDefaultModel(model)
|
|
238
|
+
line('model', `${model}, ${chosen.priced === false ? `${billingText(chosen)} — mo model instructions ${providerOf(model)} fills them` : 'ready'}`)
|
|
239
|
+
say(`${''.padEnd(10)}new spores run on it`)
|
|
240
|
+
otherModels(say, providerOf(model))
|
|
241
|
+
return model
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function tickTimer ({ line, yes, services }) {
|
|
245
|
+
let tick
|
|
246
|
+
try {
|
|
247
|
+
tick = services.show('tick')
|
|
248
|
+
} catch (err) {
|
|
249
|
+
if (err.type !== 'SERVICE_NO_SYSTEMD') throw err
|
|
250
|
+
line('tick', 'no systemd user session here: a schedule fires only when something runs spore tick each minute')
|
|
251
|
+
return
|
|
252
|
+
}
|
|
253
|
+
if (tick.defined && tick.enabled) {
|
|
254
|
+
line('tick', 'on — schedules fire')
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
if (!await yes('a spore acts on a schedule only with the tick timer — turn it on?')) {
|
|
258
|
+
line('tick', 'off — spore service define tick, then enable it, once a spore has a schedule')
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
if (!tick.defined) services.define('tick')
|
|
262
|
+
services.act('enable', 'tick')
|
|
263
|
+
services.act('start', 'tick')
|
|
264
|
+
line('tick', 'on — schedules fire')
|
|
265
|
+
}
|
package/tui/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# spore tui
|
|
2
|
+
|
|
3
|
+
One spore at a time, in a terminal screen.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
spore tui [<name>] # the last one opened, without a name
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
enter send; to a running turn, it lands between its rounds
|
|
11
|
+
alt+enter a new line
|
|
12
|
+
↑ ↓ earlier messages
|
|
13
|
+
ctrl+p open another spore
|
|
14
|
+
ctrl+o tool calls in full — an edit or a write as its diff
|
|
15
|
+
ctrl+g write the message in $EDITOR
|
|
16
|
+
esc esc stop the running turn; when none runs, clear the line
|
|
17
|
+
ctrl+c clear the line
|
|
18
|
+
ctrl+d leave, on an empty line
|
|
19
|
+
/ commands: /stop /wrap /extend /model /curate /pause /unpause /spores /status /copy /help /quit
|
|
20
|
+
//text a message that starts with /
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
The status line names the spore, its model, its state and the running turn's limits. When
|
|
24
|
+
another spore answers or asks, the status line says so and the terminal gets a notification
|
|
25
|
+
(OSC 9); so does the open one when a turn ran longer than a minute.
|
|
26
|
+
|
|
27
|
+
## In a directory
|
|
28
|
+
|
|
29
|
+
`spore here [<dir>]` opens the spore that works in that directory, in place, making it the first
|
|
30
|
+
time from a sporangium you pick. It adds two commands:
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
/diff what changed here since this session opened, in git's pager — your changes too
|
|
34
|
+
/undo put the directory back as this session found it, after showing what that changes
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Embedding it
|
|
38
|
+
|
|
39
|
+
`runTui({ ws, commands, renderTool })` from `@rhizogrip/spore-cli/tui/index.js` is the same
|
|
40
|
+
screen, with an application's own slash commands added and its own way of drawing a tool call;
|
|
41
|
+
[INTEGRATION.md](../../../INTEGRATION.md#a-terminal-for-your-application) has its options. It is
|
|
42
|
+
not a declared entry point yet, so the path may change in a release.
|
|
43
|
+
|
|
44
|
+
## What it is not
|
|
45
|
+
|
|
46
|
+
It is an **application against the package**, not part of the runtime. Everything it does
|
|
47
|
+
goes through `@rhizogrip/spore`'s exports, and it knows nothing the library does not export.
|
|
48
|
+
If it ever needs something it cannot get that way, the gap is in the library rather than
|
|
49
|
+
here.
|
package/tui/commands.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const COMMANDS = [
|
|
2
|
+
{ name: 'stop', description: 'stop the running turn' },
|
|
3
|
+
{ name: 'wrap', description: 'ask the running turn to wrap up, now or in a while', argumentHint: '[10m]' },
|
|
4
|
+
{ name: 'extend', description: 'give the running turn more, as far as its spore.cmk allows', argumentHint: '<rounds|cost|wall> <amount>' },
|
|
5
|
+
{ name: 'model', description: 'switch the model this spore runs on, from the next turn — a list to pick from, or one named', argumentHint: '[<model>]' },
|
|
6
|
+
{ name: 'curate', description: 'add a model a provider lists to your mohdel catalog — this spore\'s provider unless one is named', argumentHint: '[<provider>]' },
|
|
7
|
+
{ name: 'pause', description: 'stop every turn and job of your spores, and start none' },
|
|
8
|
+
{ name: 'unpause', description: 'let turns start again' },
|
|
9
|
+
{ name: 'spores', description: 'open another spore (Ctrl+P)' },
|
|
10
|
+
{ name: 'status', description: 'jobs, schedules, held deliveries, answers waiting to be delivered' },
|
|
11
|
+
{ name: 'copy', description: 'copy the last answer' },
|
|
12
|
+
{ name: 'help', description: 'keys and commands' },
|
|
13
|
+
{ name: 'quit', description: 'leave (Ctrl+D)' }
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
/** `/name args…` as `{ name, args }`; null for a message — `//…` being one that starts with `/`. */
|
|
17
|
+
export function parseCommand (text) {
|
|
18
|
+
const trimmed = text.trim()
|
|
19
|
+
if (!trimmed.startsWith('/') || trimmed.startsWith('//')) return null
|
|
20
|
+
const [name, ...args] = trimmed.slice(1).split(/\s+/)
|
|
21
|
+
return name ? { name: name.toLowerCase(), args } : null
|
|
22
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A spore's conversation as the terminal shows it: what was said to it and where from, what
|
|
3
|
+
* it answered, and how each turn ended — read from its records — and the running turn as its
|
|
4
|
+
* events arrive. Pure: records and events in, items out.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { printable } from './printable.js'
|
|
8
|
+
|
|
9
|
+
export function originOf (entry) {
|
|
10
|
+
if (entry.schedule) return `schedule "${entry.schedule}"`
|
|
11
|
+
if (entry.hook) return `webhook "${entry.hook}"`
|
|
12
|
+
if (entry.job) return `job "${entry.job}"`
|
|
13
|
+
if (entry.replyTo) return entry.replyTo.split(':')[0]
|
|
14
|
+
return 'elsewhere'
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function saidText (entry) {
|
|
18
|
+
const text = entry.text ?? (entry.bodyPath ? `${entry.bodyHead}…` : '')
|
|
19
|
+
const files = (entry.files ?? []).map(file => `[${file.name}]`)
|
|
20
|
+
return printable([text, ...files].filter(Boolean).join(' '))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const said = (entry) => ({ kind: 'said', inboxNo: entry.inboxNo, origin: originOf(entry), text: saidText(entry), at: entry.at })
|
|
24
|
+
|
|
25
|
+
/** The finished turns, then what no turn has read yet. */
|
|
26
|
+
export function history ({ turns, inbox }) {
|
|
27
|
+
const items = []
|
|
28
|
+
for (const turn of turns) {
|
|
29
|
+
for (const entry of inbox.filter(e => e.inboxNo > turn.inboxFrom && e.inboxNo <= turn.inboxTo)) items.push(said(entry))
|
|
30
|
+
if (turn.output) items.push({ kind: 'answer', text: printable(turn.output) })
|
|
31
|
+
items.push({
|
|
32
|
+
kind: 'end',
|
|
33
|
+
turnNo: turn.turnNo,
|
|
34
|
+
stopReason: turn.stopReason,
|
|
35
|
+
error: turn.error,
|
|
36
|
+
detail: turn.detail ?? null,
|
|
37
|
+
rounds: turn.rounds,
|
|
38
|
+
treeUsd: turn.treeUsd,
|
|
39
|
+
durationMs: turn.startedAt && turn.endedAt ? Date.parse(turn.endedAt) - Date.parse(turn.startedAt) : null
|
|
40
|
+
})
|
|
41
|
+
}
|
|
42
|
+
for (const entry of inbox.filter(e => !e.consumed)) items.push({ ...said(entry), waiting: true })
|
|
43
|
+
return items
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const createLive = () => ({ text: '', notes: [], tools: [], rounds: 0, input: null, cost: 0, complete: null })
|
|
47
|
+
|
|
48
|
+
/** False when the event changes nothing shown. Text written before a tool call is a note: the answer is what comes last. */
|
|
49
|
+
export function applyEvent (live, event) {
|
|
50
|
+
switch (event.event) {
|
|
51
|
+
case 'round':
|
|
52
|
+
live.rounds = event.index + 1
|
|
53
|
+
return true
|
|
54
|
+
case 'stream':
|
|
55
|
+
if (event.kind !== 'message') return false
|
|
56
|
+
live.text += event.delta
|
|
57
|
+
return true
|
|
58
|
+
case 'tool_start':
|
|
59
|
+
if (live.text.trim()) live.notes.push({ kind: 'thought', text: printable(live.text.trim()) })
|
|
60
|
+
live.text = ''
|
|
61
|
+
live.tools.push({ callId: event.callId, name: event.name, args: event.args ?? {}, done: false })
|
|
62
|
+
return true
|
|
63
|
+
case 'tool_end': {
|
|
64
|
+
const tool = live.tools.find(t => t.callId === event.callId)
|
|
65
|
+
if (!tool) return false
|
|
66
|
+
Object.assign(tool, { done: true, durationMs: event.durationMs, error: Boolean(event.error) })
|
|
67
|
+
return true
|
|
68
|
+
}
|
|
69
|
+
case 'usage':
|
|
70
|
+
live.input = event.input
|
|
71
|
+
live.cost += event.cost
|
|
72
|
+
return true
|
|
73
|
+
case 'interject':
|
|
74
|
+
live.notes.push({ kind: 'note', text: 'a message arrived mid-turn' })
|
|
75
|
+
return true
|
|
76
|
+
case 'wrap':
|
|
77
|
+
live.notes.push({ kind: 'note', text: `wrapping up — reached its ${event.dimension} limit` })
|
|
78
|
+
return true
|
|
79
|
+
case 'compaction':
|
|
80
|
+
live.notes.push({ kind: 'note', text: 'earlier turns summarized' })
|
|
81
|
+
return true
|
|
82
|
+
case 'complete':
|
|
83
|
+
live.complete = { stopReason: event.stopReason ?? 'answer', output: event.output == null ? null : printable(event.output) }
|
|
84
|
+
if (live.complete.output) live.text = live.complete.output
|
|
85
|
+
return true
|
|
86
|
+
default:
|
|
87
|
+
return false
|
|
88
|
+
}
|
|
89
|
+
}
|
package/tui/diff.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
const MOST_CELLS = 250_000
|
|
2
|
+
const CONTEXT = 2
|
|
3
|
+
|
|
4
|
+
const linesOf = (text) => (text === '' ? [] : String(text).replace(/\n$/, '').split('\n'))
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `before` to `after`, line by line: `{ op, text }` with op ' ', '-' or '+'. Past a size where the
|
|
8
|
+
* table would be slow, the changed middle is shown removed then added, which is still true.
|
|
9
|
+
*/
|
|
10
|
+
export function lineDiff (before, after) {
|
|
11
|
+
const a = linesOf(before)
|
|
12
|
+
const b = linesOf(after)
|
|
13
|
+
let start = 0
|
|
14
|
+
while (start < a.length && start < b.length && a[start] === b[start]) start++
|
|
15
|
+
let end = 0
|
|
16
|
+
while (end < a.length - start && end < b.length - start && a[a.length - 1 - end] === b[b.length - 1 - end]) end++
|
|
17
|
+
const head = a.slice(0, start).map(text => ({ op: ' ', text }))
|
|
18
|
+
const tail = a.slice(a.length - end).map(text => ({ op: ' ', text }))
|
|
19
|
+
const x = a.slice(start, a.length - end)
|
|
20
|
+
const y = b.slice(start, b.length - end)
|
|
21
|
+
if (x.length * y.length > MOST_CELLS) {
|
|
22
|
+
return [...head, ...x.map(text => ({ op: '-', text })), ...y.map(text => ({ op: '+', text })), ...tail]
|
|
23
|
+
}
|
|
24
|
+
const longest = Array.from({ length: x.length + 1 }, () => new Uint32Array(y.length + 1))
|
|
25
|
+
for (let i = x.length - 1; i >= 0; i--) {
|
|
26
|
+
for (let j = y.length - 1; j >= 0; j--) {
|
|
27
|
+
longest[i][j] = x[i] === y[j] ? longest[i + 1][j + 1] + 1 : Math.max(longest[i + 1][j], longest[i][j + 1])
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const middle = []
|
|
31
|
+
let i = 0
|
|
32
|
+
let j = 0
|
|
33
|
+
while (i < x.length || j < y.length) {
|
|
34
|
+
if (i < x.length && j < y.length && x[i] === y[j]) {
|
|
35
|
+
middle.push({ op: ' ', text: x[i++] })
|
|
36
|
+
j++
|
|
37
|
+
} else if (i < x.length && (j === y.length || longest[i + 1][j] >= longest[i][j + 1])) {
|
|
38
|
+
middle.push({ op: '-', text: x[i++] })
|
|
39
|
+
} else {
|
|
40
|
+
middle.push({ op: '+', text: y[j++] })
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return [...head, ...middle, ...tail]
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const counts = (diff) => ({
|
|
47
|
+
added: diff.filter(line => line.op === '+').length,
|
|
48
|
+
removed: diff.filter(line => line.op === '-').length
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
/** The changed lines with `CONTEXT` unchanged ones around each run; a longer gap is one `…`. */
|
|
52
|
+
export function hunks (diff) {
|
|
53
|
+
const near = diff.map((line, at) => line.op !== ' ' || diff.slice(Math.max(0, at - CONTEXT), at + CONTEXT + 1).some(other => other.op !== ' '))
|
|
54
|
+
const shown = []
|
|
55
|
+
for (let at = 0; at < diff.length; at++) {
|
|
56
|
+
if (near[at]) shown.push(diff[at])
|
|
57
|
+
else if (shown.at(-1)?.op !== '…') shown.push({ op: '…', text: '' })
|
|
58
|
+
}
|
|
59
|
+
return shown
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function changeOf (tool) {
|
|
63
|
+
const { path, old, content } = tool.args
|
|
64
|
+
if (tool.name === 'edit' && typeof old === 'string' && typeof tool.args.new === 'string') {
|
|
65
|
+
return { path, diff: lineDiff(old, tool.args.new), whole: false }
|
|
66
|
+
}
|
|
67
|
+
if (tool.name === 'write' && typeof content === 'string') {
|
|
68
|
+
return { path, diff: linesOf(content).map(text => ({ op: '+', text })), whole: true }
|
|
69
|
+
}
|
|
70
|
+
return null
|
|
71
|
+
}
|
package/tui/here.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process'
|
|
2
|
+
import { realpathSync, statSync } from 'node:fs'
|
|
3
|
+
import { basename, resolve } from 'node:path'
|
|
4
|
+
|
|
5
|
+
import { defaultModel, define, hereSnapshots, isWorkspace, readConfig, SporeError, sporangia, workspaceFor } from '@rhizogrip/spore'
|
|
6
|
+
|
|
7
|
+
import { changesSince, diffArgs, gitStateText, pruneSnapshots, snapshot, sporeNameFor, undoTo, workTreeOf } from '../src/here.js'
|
|
8
|
+
import { choose, runTui } from './index.js'
|
|
9
|
+
|
|
10
|
+
const WHAT = { M: 'restore', D: 'bring back', A: 'remove' }
|
|
11
|
+
|
|
12
|
+
function gitCommands (dir, spore) {
|
|
13
|
+
const session = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+/, '')
|
|
14
|
+
const since = snapshot(dir, { spore, session })
|
|
15
|
+
pruneSnapshots(dir, { spore, keep: hereSnapshots(readConfig()) })
|
|
16
|
+
return [
|
|
17
|
+
{
|
|
18
|
+
name: 'diff',
|
|
19
|
+
description: 'what changed here since this session opened — your own changes too',
|
|
20
|
+
run: (args, { outside, notice }) => {
|
|
21
|
+
if (!changesSince(dir, since).length) return notice('nothing has changed since this session opened')
|
|
22
|
+
const { cwd, args: diff } = diffArgs(dir, since)
|
|
23
|
+
outside(() => spawnSync('git', diff, { cwd, stdio: 'inherit' }))
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
name: 'undo',
|
|
28
|
+
description: 'put this directory back as it was when this session opened',
|
|
29
|
+
run: async (args, { running, confirm, notice }) => {
|
|
30
|
+
if (running()) return notice('a turn is running — stop it first (esc twice)')
|
|
31
|
+
const changes = changesSince(dir, since)
|
|
32
|
+
if (!changes.length) return notice('nothing to undo — the directory is as this session found it')
|
|
33
|
+
const agreed = await confirm('undo this session', changes.map(c => `${WHAT[c.status]} ${c.path}`).join('\n'), 'put it back')
|
|
34
|
+
if (!agreed) return
|
|
35
|
+
undoTo(dir, since)
|
|
36
|
+
notice(`put back ${changes.length} file${changes.length > 1 ? 's' : ''}`)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Opens the spore `dir` is worked in by, making it the first time from the sporangium picked —
|
|
44
|
+
* or named, which is the only way without a terminal. Resolves with the exit code.
|
|
45
|
+
*/
|
|
46
|
+
export async function here ({ dir = '.', sporangium = null, model = null, git = true, interactive = process.stdin.isTTY }) {
|
|
47
|
+
const target = realpathSync(resolve(dir))
|
|
48
|
+
if (!statSync(target).isDirectory()) throw new SporeError(`${target} is not a directory`, { type: 'HERE_REFUSED', detail: 'spore here works in a directory' })
|
|
49
|
+
const tree = workTreeOf(target)
|
|
50
|
+
if (!tree && git) {
|
|
51
|
+
throw new SporeError(`${target} is not in a git repository`, {
|
|
52
|
+
type: 'HERE_REFUSED',
|
|
53
|
+
detail: 'git is what undoes what the spore changes — git init there, or --no-git to work without it'
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
const name = sporeNameFor(target)
|
|
57
|
+
const { path: ws } = workspaceFor(name)
|
|
58
|
+
if (isWorkspace(ws) && (sporangium || model)) {
|
|
59
|
+
throw new SporeError(`${target} already has its spore, ${name}`, {
|
|
60
|
+
type: 'DEFINE_FILLS_ONLY_NEW',
|
|
61
|
+
detail: `--sporangium and --model make a new one; this one exists, so spore edit ${name} changes it`
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
if (!isWorkspace(ws)) {
|
|
65
|
+
let chosen = sporangium
|
|
66
|
+
if (!chosen) {
|
|
67
|
+
if (!interactive) {
|
|
68
|
+
throw new SporeError(`${target} has no spore yet, and without a terminal there is no picker`, { type: 'HERE_REFUSED', detail: 'name one: --sporangium <name>' })
|
|
69
|
+
}
|
|
70
|
+
if (!model && !defaultModel().model) {
|
|
71
|
+
throw new SporeError(`new spores run on your default model, and ${defaultModel().path} names none`, {
|
|
72
|
+
type: 'HERE_REFUSED',
|
|
73
|
+
detail: 'spore config set model <provider>/<name>, or spore here --model <provider>/<name> — "mo ls" lists your catalog'
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
chosen = await choose({
|
|
77
|
+
title: `a spore for ${basename(target)}`,
|
|
78
|
+
header: [`writes ${target}`, tree ? gitStateText(target) : 'not a git repository — nothing can be undone'],
|
|
79
|
+
items: sporangia().map(s => ({ value: s.name, label: s.name, description: s.error ?? s.description ?? '' }))
|
|
80
|
+
})
|
|
81
|
+
if (!chosen) return 0
|
|
82
|
+
}
|
|
83
|
+
define({ ws: name, sporangium: chosen, model, writes: [`here=${target}`] })
|
|
84
|
+
}
|
|
85
|
+
return runTui({ ws, commands: tree ? gitCommands(target, name) : [], greeting: `${name} works in ${target} — its workspace is ${ws}` })
|
|
86
|
+
}
|