@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.
@@ -0,0 +1,736 @@
1
+ /**
2
+ * Rendering for the read-only verbs. Parsing lives in `bin/spore.js`, the answers live in
3
+ * `verbs.js`, and this is only the part that decides what a person sees.
4
+ *
5
+ * `--json` prints the library's own shape, one object, so anything scripting against this
6
+ * reads the same thing an embedder would and does not parse a table. A verb's exit code is a
7
+ * function of that object, so it is the same with `--json` as without.
8
+ */
9
+
10
+ import { spawnSync } from 'node:child_process'
11
+ import { createInterface } from 'node:readline/promises'
12
+ import { readFileSync } from 'node:fs'
13
+ import { homedir } from 'node:os'
14
+ import { basename, join, resolve } from 'node:path'
15
+
16
+ import {
17
+ addTo, allowPlugin, billingFor, changeText, define, defaultModel, disallowPlugin, durationText,
18
+ edit, extend, getKey, jobs, list, listPlugins, log, pause, precursors, remake, remove,
19
+ removeFrom, removeSchedule, runningLines, saidOf, schedules, setDefaultModel, setKey, setSchedule, settings,
20
+ show, showPlugin, sql, stopJob, switchModel, tick, tickReport, unmetered, unpause, upgrade, usage, wrap, CONFIG_FILE, DEFAULT_SPORANGIUM
21
+ } from '@rhizogrip/spore'
22
+ import { diagnose, renderDoctor } from './doctor.js'
23
+ import { hook } from './hooks.js'
24
+ import { createServices } from './services.js'
25
+
26
+ const STATE_WIDTH = 9
27
+
28
+ const size = (bytes) => {
29
+ const units = ['B', 'KB', 'MB', 'GB', 'TB']
30
+ let value = bytes
31
+ let unit = 0
32
+ while (value >= 1024 && unit < units.length - 1) {
33
+ value /= 1024
34
+ unit++
35
+ }
36
+ return `${unit ? value.toFixed(1) : value}${units[unit]}`
37
+ }
38
+
39
+ const tilde = (path) => (path === homedir() || path.startsWith(homedir() + '/') ? `~${path.slice(homedir().length)}` : path)
40
+
41
+ const line = (row, under) => {
42
+ const where = under && row.ws.startsWith(under) ? row.ws.slice(under.length + 1) || '.' : row.ws
43
+ const spend = row.treeUsd ? `$${row.treeUsd.toFixed(4)}` : ''
44
+ const works = row.definitionError ? ' (its spore.cmk does not parse)' : row.writes.map(path => ` → ${tilde(path)}`).join('')
45
+ return ` ${row.state.padEnd(STATE_WIDTH)} ${String(row.lastTurnNo).padStart(4)} turns ${spend.padStart(9)} ${size(row.bytes).padStart(8)} ${where}${works}`
46
+ }
47
+
48
+ const block = (title, rows, under) => {
49
+ if (!rows.length) return
50
+ console.log(title)
51
+ for (const row of rows.sort((a, b) => a.ws.localeCompare(b.ws))) console.log(line(row, under))
52
+ }
53
+
54
+ function renderList (result) {
55
+ if (!result.configured) {
56
+ console.error(`spore: no ${result.file}\n` +
57
+ ' it names where workspaces live and nothing else — "home" is the directory\n' +
58
+ ' spores are made in, "workspaces" lists any that live outside it\n' +
59
+ ' spore config set home <dir>')
60
+ return
61
+ }
62
+ for (const skip of result.missing) console.error(`spore: skipped ${skip.path} — ${skip.why}`)
63
+ if (result.paused) console.log(`your spores are ${pausedText(result.paused)} — no turn starts until spore unpause\n`)
64
+ const limited = spendText(result.spend)
65
+ if (limited) console.log(`your spores have spent ${limited}\n`)
66
+ if (!result.contain) console.log('turns are not contained (contain off): each sees every other spore\'s processes\n')
67
+
68
+ const home = result.workspaces.filter(row => row.from === result.home)
69
+ const outside = result.workspaces.filter(row => row.from !== result.home)
70
+
71
+ if (!result.workspaces.length) {
72
+ if (result.home) console.log(`no spores yet — spore define <name> makes one in ${result.home}`)
73
+ else console.log('nowhere configured to look — spore config set home <dir>')
74
+ return
75
+ }
76
+ block(result.home, home, result.home)
77
+ block('outside home', outside, null)
78
+ }
79
+
80
+ const listExit = (result) => (result.configured ? 0 : 2)
81
+
82
+ /** `today $4.12 of $20.00 · October $81.30 of $300.00`, the windows a limit is set on; null with none. */
83
+ const spendText = ({ date, day, month, limits }) => {
84
+ const of = (spent, limit) => `$${spent.toFixed(2)} of $${limit.toFixed(2)}${spent >= limit ? ' — reached, no turn starts' : ''}`
85
+ const monthName = new Date(`${date}T00:00:00Z`).toLocaleDateString('en-US', { month: 'long', timeZone: 'UTC' })
86
+ const parts = [
87
+ limits.day === null ? null : `today ${of(day, limits.day)}`,
88
+ limits.month === null ? null : `${monthName} ${of(month, limits.month)}`
89
+ ].filter(Boolean)
90
+ return parts.length ? parts.join(' · ') : null
91
+ }
92
+
93
+ function renderModels ({ model, models }) {
94
+ console.log(`runs on ${model}`)
95
+ console.log(models.length ? `or: ${models.join(', ')} — spore model <name> <model> switches from the next turn` : 'offers no other — models: [<provider>/<name>, …] in its spore.cmk adds some')
96
+ }
97
+
98
+ function renderSwitch ({ model, was }) {
99
+ console.log(model === was ? `already runs on ${model}` : `runs on ${model} from the next turn — it ran on ${was}`)
100
+ }
101
+
102
+ function renderDefine (result) {
103
+ if (result.seeded) {
104
+ console.error(`spore: seeded ${result.seeded} from the package's default sporangium\n` +
105
+ ' every spore is made over it — edit it to change them')
106
+ }
107
+ if (result.redefined) console.error(`spore: redefined ${result.redefined.from} → ${result.redefined.to}, keeping the conversation`)
108
+ if (result.already) console.error('spore: already defined — pass --definition to replace what it is, or edit its spore.cmk')
109
+ if (result.cloned) {
110
+ const { precursors, programs } = result.cloned
111
+ console.error(`spore: cut from ${result.cloned.from}\n` +
112
+ ` carried ${precursors.length} precursor(s) and ${programs.length} program(s); the conversation stayed behind`)
113
+ }
114
+ if (result.sporangium && result.sporangium !== DEFAULT_SPORANGIUM && !result.cloned) console.error(`spore: made from the sporangium ${result.sporangium}`)
115
+ if (result.remembered) console.error(`spore: recorded in ${result.file}, so spore ls finds it outside home`)
116
+ console.log(result.ws)
117
+ }
118
+
119
+ const bounds = (l, billing) => {
120
+ const money = unmetered(billing)
121
+ ? `not metered · ${billing.label}${billing.usage ? `, ${billing.usage}` : ''}`
122
+ : `$${l.cost.soft.toFixed(2)}/$${l.cost.hard.toFixed(2)}`
123
+ return `${l.rounds.soft}/${l.rounds.hard} rounds · ${money} · ${l.wall.soft / 60000}/${l.wall.hard / 60000}m`
124
+ }
125
+
126
+ const modelLine = (model, billing) => `${model}${billing === null ? ' (a provider mohdel does not know)' : ''}`
127
+
128
+ export function renderHeader (ws, grant) {
129
+ console.error([
130
+ `spore ${ws}`,
131
+ ` ${modelLine(grant.model, grant.billing)} · tools: ${grant.tools.join(', ')}`,
132
+ ` limits: ${bounds(grant.limits, grant.billing)} (soft wraps, hard stops)`
133
+ ].join('\n'))
134
+ }
135
+
136
+ function renderShow (result) {
137
+ const line = (label, value) => console.log(` ${label.padEnd(10)} ${value}`)
138
+ console.log(result.ws)
139
+ line('state', `${result.state}${result.pid ? ` pid ${result.pid} since ${result.startedAt}` : ''}`)
140
+ line('name', result.name)
141
+ if (result.description) line('description', result.description)
142
+ line('sporangium', result.sporangium)
143
+ line('model', modelLine(result.model, result.billing))
144
+ if (result.models.length) line('or', result.models.join(', '))
145
+ if (result.cellModels.length) line('cell models', result.cellModels.map(named => `${named.name}=${named.model}`).join(', '))
146
+ line('tools', result.tools.length ? result.tools.join(', ') : 'none')
147
+ line('limits', bounds(result.limits, result.billing))
148
+ if (result.turnLimits) for (const [i, one] of runningLines(result.turnLimits, result.extend).entries()) line(i ? '' : 'this turn', one)
149
+ if (result.sources?.length) {
150
+ line('sources', result.sources.map(name => {
151
+ const narrowed = Object.entries(result.scopes?.[name] || {}).map(([p, v]) => `${p}=${v.join('|')}`)
152
+ return narrowed.length ? `${name} (${narrowed.join(' ')})` : name
153
+ }).join(', '))
154
+ }
155
+ if (result.reads?.length) line('reads', result.reads.map(r => `${r.name} → ${r.path}`).join(', '))
156
+ if (result.writes?.length) line('writes', result.writes.map(w => `${w.name} → ${w.path}`).join(', '))
157
+ if (result.memory) line('memory', `${result.memory.backend} push ${result.memory.push} pull ${result.memory.pull}`)
158
+ line('messages', `${result.messages}${result.waiting ? ` (${result.waiting} waiting)` : ''}`)
159
+ if (result.paused) line('spores', `${pausedText(result.paused)} — no turn starts until spore unpause`)
160
+ if (result.held.length) {
161
+ const next = result.held.reduce((first, one) => (one.releaseAt < first.releaseAt ? one : first))
162
+ line('held', `${result.held.length} deliveries routed to wait — next at ${next.releaseAt} (${next.origin})`)
163
+ }
164
+ if (result.cells.runs) {
165
+ const by = Object.entries(result.cells.origins).map(([origin, runs]) => `${origin} ${runs}`).join(', ')
166
+ line('cells', `${result.cells.runs} outside turns in the last day, $${result.cells.costUsd.toFixed(4)} — ${by}`)
167
+ }
168
+ if (result.jobs.grant || result.jobs.running.length) {
169
+ if (!result.jobs.running.length) line('jobs', `none running — ${jobGrant(result.jobs.grant)}`)
170
+ for (const [i, job] of result.jobs.running.entries()) line(i ? '' : 'jobs', runningJob(job))
171
+ }
172
+ line('turns', `${result.lastTurnNo}${result.last?.stopReason ? ` last ${result.last.stopReason}` : ''}${result.endedAt ? ` ${result.endedAt}` : ''}`)
173
+ line('spend', unmetered(result.billing) ? `not metered · ${result.billing.label}` : `$${result.treeUsd.toFixed(6)}`)
174
+ line('work', `${result.workUnits} units (${result.workUnitsOwn} own rounds, ${result.workUnitsChildren} in cells)`)
175
+ if (result.produced.length) {
176
+ const shown = result.produced.slice(0, 5).map(f => `${f.path} (${f.mime}, ${f.bytes}b)`)
177
+ const rest = result.produced.length - shown.length + result.producedMore
178
+ line('produced', shown.join('\n' + ' '.repeat(13)) + (rest ? `\n${' '.repeat(13)}…and ${rest} more` : ''))
179
+ }
180
+ if (result.precursors.length) line('precursors', result.precursors.join(', '))
181
+ if (result.plugins.length) line('plugins', result.plugins.join(', '))
182
+ if (result.differs.length) line('docs', `${result.differs.join(', ')} differ from what is installed — spore upgrade ${basename(result.ws)}`)
183
+ const { disk } = result
184
+ line('disk', `${size(disk.total)} — data ${size(disk.data)} · records ${size(disk.state)} · streams ${size(disk.calls)} · sent ${size(disk.inbox)} · other ${size(disk.other)}`)
185
+ for (const [i, one] of result.schedules.entries()) line(i ? '' : 'schedules', scheduleLine(one))
186
+ if (result.scheduleBound) {
187
+ const b = result.scheduleBound
188
+ line('clock', `may keep ${b.count}, ${b.interval / 60000}m apart at the closest — at most ${b.perDay} turns a day, $${b.nominalCost.toFixed(2)} nominal`)
189
+ line('', 'a turn stops taking model calls at its hard cost, and pays for the ones still running then')
190
+ }
191
+ }
192
+
193
+ // One line per schedule a pass did something about, for the journal a timer writes to. A
194
+ // schedule that is not due yet, or will never fire again, is left out: every pass would
195
+ // repeat it.
196
+ function renderEdit (result) {
197
+ if (!result.edited) {
198
+ const why = {
199
+ unchanged: 'no change',
200
+ editor: `the editor exited ${result.status}; spore.cmk is as it was`,
201
+ refused: 'not saved; spore.cmk is as it was'
202
+ }[result.why]
203
+ console.error(`spore: ${why}`)
204
+ return
205
+ }
206
+ console.log(`edited ${join(result.ws, 'spore.cmk')}`)
207
+ for (const line of result.changes) console.log(` ${line}`)
208
+ if (result.running) console.log('a turn is running: this applies from the next one, and extend.* to spore extend at once')
209
+ }
210
+
211
+ const editExit = (result) => (result.edited || result.why === 'unchanged' ? 0 : 1)
212
+
213
+ function openInEditor (file) {
214
+ const editor = process.env.VISUAL || process.env.EDITOR || 'vi'
215
+ return spawnSync('sh', ['-c', `${editor} "$1"`, 'sh', file], { stdio: 'inherit' }).status ?? 1
216
+ }
217
+
218
+ async function editAgain (error) {
219
+ console.error(`spore: ${error}`)
220
+ if (!process.stdin.isTTY) return false
221
+ const prompt = createInterface({ input: process.stdin, output: process.stderr })
222
+ const answer = await prompt.question('edit again? [Y/n] ')
223
+ prompt.close()
224
+ return !/^n/i.test(answer.trim())
225
+ }
226
+
227
+ function renderChange (answer) {
228
+ if (answer.refused) {
229
+ console.error(`spore: ${changeText(answer)}`)
230
+ return
231
+ }
232
+ console.log(changeText(answer))
233
+ }
234
+
235
+ const changeExit = (answer) => (answer.refused ? 1 : 0)
236
+
237
+ const pausedText = (mark) => `paused${mark.at ? ` since ${mark.at}` : ''}${mark.why ? ` (${mark.why})` : ''}`
238
+
239
+ function renderPause (result) {
240
+ console.log(result.already ? `already ${pausedText(result.mark)}` : pausedText(result.mark))
241
+ for (const ws of result.turns) console.log(` stopping the turn in ${ws}`)
242
+ for (const job of result.jobs) console.log(` stopping the job ${job.name} in ${job.ws}`)
243
+ if (!result.turns.length && !result.jobs.length) console.log(' nothing was running')
244
+ console.log('no turn starts until spore unpause — messages and webhooks are refused meanwhile, schedules wait')
245
+ }
246
+
247
+ function renderUnpause (result) {
248
+ if (!result.unpaused) {
249
+ console.error('spore: your spores are not paused')
250
+ return
251
+ }
252
+ console.log(`unpaused — it was ${pausedText(result.mark)}; held deliveries and due schedules go at the next spore tick`)
253
+ }
254
+
255
+ const unpauseExit = (result) => (result.unpaused ? 0 : 1)
256
+
257
+ function renderTick (result) {
258
+ for (const line of tickReport(result).lines) console.log(line)
259
+ }
260
+
261
+ export function scheduleLine (one) {
262
+ const when = one.at ? `at ${one.at}` : `${one.when} ${one.tz}`
263
+ const where = one.why ? ` ${one.why}` : one.next ? ` next ${one.next}` : one.slot ? ` for ${one.slot}` : ''
264
+ return `${one.name} ${when} ${one.state}${where}`
265
+ }
266
+
267
+ const jobGrant = (grant) => grant
268
+ ? `${grant.count} at once, ${durationText(grant.wall)} each${grant.maxWait ? `, routed within ${durationText(grant.maxWait)}` : ''}${grant.perDay ? `, ${grant.perDay} triage cells a day` : ''}`
269
+ : 'none granted'
270
+
271
+ export const runningJob = (job) => `${job.name} · ${durationText(Date.now() - Date.parse(job.startedAt))} of ${durationText(job.wallMs)}${job.progress ? ` · ${job.progress}` : ''}`
272
+
273
+ function renderJobs (result) {
274
+ console.log(`granted: ${jobGrant(result.grant)}`)
275
+ for (const job of result.jobs) {
276
+ const how = job.status === 'running'
277
+ ? runningJob(job)
278
+ : `${job.name} · ${job.status}${job.exit !== null ? ` ${job.exit}` : job.signal ? ` ${job.signal}` : ''} after ${durationText(Date.parse(job.endedAt) - Date.parse(job.startedAt))}`
279
+ console.log(` ${when(job.startedAt)} ${how}`)
280
+ }
281
+ if (!result.jobs.length) console.log(' none has run here')
282
+ }
283
+
284
+ function renderSchedules (result) {
285
+ for (const one of result.schedules) console.log(scheduleLine(one))
286
+ if (!result.schedules.length) console.log('none — nothing here is said by the clock')
287
+ }
288
+
289
+ async function readStdin () {
290
+ if (process.stdin.isTTY) return ''
291
+ const chunks = []
292
+ for await (const chunk of process.stdin) chunks.push(chunk)
293
+ return Buffer.concat(chunks).toString('utf8')
294
+ }
295
+
296
+ const when = (iso) => (iso ? iso.replace('T', ' ').slice(0, 19) : '—'.padEnd(19))
297
+
298
+ const quoted = (said) => (said.length ? said.map(one => JSON.stringify(one.length > 60 ? one.slice(0, 57) + '…' : one)).join(' ') : '')
299
+
300
+ function renderLog (result) {
301
+ if (!result.turns.length && !result.waiting.length && !result.held.length) {
302
+ console.log('nothing has been said here yet')
303
+ return
304
+ }
305
+ const why = (turn) => {
306
+ if (!turn.error) return ''
307
+ const detail = turn.detail ? ` — ${turn.detail.split('\n')[0]}` : ''
308
+ const text = `${turn.error}${detail}`
309
+ return `${text.length > 100 ? `${text.slice(0, 99)}…` : text} `
310
+ }
311
+ for (const turn of result.turns) {
312
+ console.log(` ${when(turn.endedAt)} ${(turn.stopReason || '—').padEnd(12)} ${String(turn.rounds).padStart(3)}r ` +
313
+ `${('$' + turn.treeUsd.toFixed(4)).padStart(9)} ${String(turn.workUnits).padStart(4)}u ${why(turn)}${quoted(turn.asked)}`)
314
+ }
315
+ // The time column is when a turn ended, and a waiting message has not been answered by
316
+ // one. Blank says that; when it was said is in the record for anyone who needs it.
317
+ for (const entry of result.waiting) {
318
+ console.log(` ${' '.repeat(19)} ${'waiting'.padEnd(12)} ${' '.repeat(19)} ${quoted([saidOf(entry)])}`)
319
+ }
320
+ for (const one of result.held) {
321
+ console.log(` ${' '.repeat(19)} ${one.state.padEnd(12)} ${' '.repeat(19)} schedule ${one.name} — ${one.why}`)
322
+ }
323
+ }
324
+
325
+ function renderSettings (rows) {
326
+ const width = Math.max(...rows.map(row => row.key.length))
327
+ for (const { key, value, from } of rows) {
328
+ const shown = Array.isArray(value) ? (value.length ? value.join(', ') : '(none)') : (value ?? '—')
329
+ const note = from === 'set' ? '' : from === 'default' ? ' (default)' : from === 'unset' ? ' (not set)' : ` (${from})`
330
+ console.log(`${key.padEnd(width)} ${shown}${note}`)
331
+ }
332
+ }
333
+
334
+ function renderConfig (value) {
335
+ const entries = Object.entries(value)
336
+ if (!entries.length) {
337
+ console.log('nothing configured')
338
+ return
339
+ }
340
+ for (const [key, held] of entries) {
341
+ if (Array.isArray(held)) {
342
+ console.log(`${key}:`)
343
+ for (const item of held) console.log(` ${item}`)
344
+ if (!held.length) console.log(' (none)')
345
+ } else if (key === 'plugins') {
346
+ console.log(`${key}:`)
347
+ for (const [name, allowed] of Object.entries(held)) console.log(` ${name} ${allowed.version}`)
348
+ } else if (typeof held === 'object' && held !== null) {
349
+ console.log(`${key}:`)
350
+ for (const [name, place] of Object.entries(held)) console.log(` ${name} → ${place}`)
351
+ } else console.log(`${key}: ${held}`)
352
+ }
353
+ }
354
+
355
+ const stateText = (row) => {
356
+ if (row.foreign) return `not spore's — ${row.foreign}`
357
+ if (row.none) return row.none
358
+ if (!row.defined) return 'not defined'
359
+ return `${row.active} (${row.sub}) · ${row.enabled ? 'enabled' : 'disabled'}${row.pid ? ` · pid ${row.pid}` : ''}${row.since ? ` · since ${row.since}` : ''}`
360
+ }
361
+
362
+ function renderServices (result) {
363
+ for (const row of result.services) {
364
+ const width = Math.max(10, ...result.services.map(one => one.name.length))
365
+ console.log(` ${row.name.padEnd(width)} ${stateText(row)}`)
366
+ console.log(` ${''.padEnd(width)} ${row.what}`)
367
+ for (const gone of row.stale ?? []) console.log(` ${''.padEnd(width)} ${gone} is gone — spore service define ${row.name}`)
368
+ if (row.outdated) console.log(` ${''.padEnd(width)} running ${row.outdated.from} ${row.outdated.running}, ${row.outdated.installed} is installed — spore service restart ${row.name}`)
369
+ if (row.unitChanged) console.log(` ${''.padEnd(width)} pid ${row.pid} runs what the unit named before it was last written — spore service restart ${row.name}`)
370
+ }
371
+ for (const { plugin, problem } of result.problems) console.log(` plugin ${plugin} offers no service: ${problem}`)
372
+ console.log(result.linger
373
+ ? '\n lingering is on: services keep running after you log out'
374
+ : '\n lingering is off: services stop when you log out — loginctl enable-linger to keep them')
375
+ const behind = result.services.filter(row => row.outdated).length
376
+ if (behind) console.log(` ${behind === 1 ? '1 service runs' : `${behind} services run`} older code than is installed — spore service restart --outdated`)
377
+ }
378
+
379
+ function renderService (row) {
380
+ console.log(`${row.name} — ${row.what}`)
381
+ console.log(` ${stateText(row)}`)
382
+ for (const gone of row.stale ?? []) console.log(` ${gone} is gone — spore service define ${row.name}`)
383
+ if (row.outdated) console.log(` running ${row.outdated.from} ${row.outdated.running}, ${row.outdated.installed} is installed — spore service restart ${row.name}`)
384
+ for (const unit of row.units ?? []) console.log(` unit ${unit}`)
385
+ if (row.log) console.log(`\n${row.log}`)
386
+ }
387
+
388
+ async function service (argv, emit) {
389
+ const [, sub, name] = argv._
390
+ const services = createServices()
391
+ if (!sub || sub === 'ls') return emit(services.list(), renderServices)
392
+ if (sub === 'restart' && argv.outdated && !name) {
393
+ return emit(services.restartOutdated(), (restarted) => {
394
+ if (!restarted.length) console.log('every service runs what is installed')
395
+ for (const r of restarted) console.log(`restarted ${r.unit} — ${r.was} → ${r.now}, ${stateText({ ...r, defined: true })}`)
396
+ })
397
+ }
398
+ if (!name) {
399
+ console.error(`spore: service ${sub} needs a service — spore service ${sub} <svc>, from spore service ls${sub === 'restart' ? ', or --outdated for every one running older code than is installed' : ''}`)
400
+ return 2
401
+ }
402
+ if (sub === 'show') return emit(services.show(name), renderService)
403
+ if (sub === 'define') {
404
+ return emit(services.define(name), (r) => {
405
+ for (const unit of r.units) console.log(`wrote ${unit}`)
406
+ console.log(`spore service start ${name} starts it; spore service enable ${name} starts it at every login`)
407
+ if (r.next) console.log(`then: ${r.next}`)
408
+ })
409
+ }
410
+ if (['start', 'stop', 'restart', 'enable', 'disable'].includes(sub)) {
411
+ return emit(services.act(sub, name), (r) => { console.log(`${r.verb} ${r.unit} — ${stateText({ ...r, defined: true })}`) })
412
+ }
413
+ if (sub === 'rm') {
414
+ return emit(services.remove(name, { yes: argv.yes }), (r) => { for (const unit of r.units) console.log(`removed ${unit}`) })
415
+ }
416
+ if (sub === 'log') {
417
+ const lines = argv.n ?? argv.lines ?? '50'
418
+ if (!/^\d+$/.test(lines)) {
419
+ console.error(`spore: -n ${lines} is not a number of lines`)
420
+ return 2
421
+ }
422
+ const unit = services.log(name)
423
+ return spawnSync('journalctl', ['--user', '-u', unit, '-n', lines, '--no-pager', '-o', 'short-iso', ...(argv.f ? ['-f'] : [])], { stdio: 'inherit' }).status ?? 1
424
+ }
425
+ console.error(`spore: service has no "${sub}" — ls, show, define, start, stop, restart, enable, disable, log, rm`)
426
+ return 2
427
+ }
428
+
429
+ function renderPlugins (result) {
430
+ if (!result.plugins.length && !result.missing.length) {
431
+ console.log(`no plugins installed beside spore — ${result.roots.join(', ') || 'no node_modules found'}`)
432
+ return
433
+ }
434
+ for (const p of result.plugins.sort((a, b) => a.name.localeCompare(b.name))) {
435
+ console.log(` ${(p.allowed ? 'allowed' : 'installed').padEnd(STATE_WIDTH)} ${p.name.padEnd(12)} ${p.package}${p.version ? ` ${p.version}` : ''}`)
436
+ if (p.problem) console.log(` ${''.padEnd(STATE_WIDTH)} ${''.padEnd(12)} ${p.problem}`)
437
+ }
438
+ for (const name of result.missing) console.log(` ${'missing'.padEnd(STATE_WIDTH)} ${name.padEnd(12)} allowed, and not installed beside spore`)
439
+ }
440
+
441
+ function renderPlugin (result) {
442
+ const line = (label, value) => console.log(` ${label.padEnd(10)} ${value}`)
443
+ console.log(`${result.name} — ${result.package} ${result.version} ${result.dir}`)
444
+ line('state', result.allowed ? 'allowed' : 'installed, not allowed')
445
+ line('works', `with @rhizogrip/spore ${result.works}`)
446
+ for (const [i, [key, kind]] of Object.entries(result.settings).entries()) {
447
+ line(i ? '' : 'settings', `${key} (${kind})${result.configured?.[key] === undefined ? '' : ` = ${result.configured[key]}`}`)
448
+ }
449
+ for (const [i, [name, path]] of Object.entries(result.programs).entries()) line(i ? '' : 'programs', `${name} → ${path}`)
450
+ for (const [i, [name, value]] of Object.entries(result.env).entries()) line(i ? '' : 'env', `${name}=${value}`)
451
+ if (result.modules.length) line('modules', `${result.modules.join(', ')} → node_modules/, for the agent's programs`)
452
+ if (result.sources.length) line('sources', `${result.sources.join(', ')} — granted with the plugin, held by the runner`)
453
+ if (result.reference) line('reference', `${result.reference} → plugins/${result.name}.md`)
454
+ if (result.precursors.length) line('precursors', result.precursors.join(', '))
455
+ for (const [i, dir] of result.reads.entries()) line(i ? '' : 'reads', dir)
456
+ if (result.services.length) line('services', `${result.services.join(', ')} — spore service ls`)
457
+ }
458
+
459
+ function plugin (argv, emit) {
460
+ const [, sub, name, ...pairs] = argv._
461
+ if (!sub || sub === 'ls') return emit(listPlugins(), renderPlugins)
462
+ if (!['show', 'allow', 'disallow'].includes(sub)) {
463
+ console.error(`spore: plugin has no "${sub}" — ls, show, allow, disallow`)
464
+ return 2
465
+ }
466
+ if (!name) {
467
+ console.error(`spore: plugin ${sub} needs a plugin — spore plugin ${sub} <plugin>${sub === 'allow' ? ' [k=v …]' : ''}`)
468
+ return 2
469
+ }
470
+ if (sub === 'show') return emit(showPlugin(name), renderPlugin)
471
+ if (sub === 'disallow') return emit(disallowPlugin(name), (r) => { console.log(`disallowed ${r.name} — a spore whose spore.cmk still names it is refused at its next send`) })
472
+ return emit(allowPlugin(name, pairs), (r) => { renderPlugin(r); console.log(`\nallowed — a spore uses it once its spore.cmk says plugins: [${r.name}]`) })
473
+ }
474
+
475
+ function config (argv, emit) {
476
+ const [, sub, key, value] = argv._
477
+ if (key === 'model' && sub === 'get') {
478
+ return emit(defaultModel(), (r) => { console.log(r.model ?? `none yet — spore config set model <provider>/<name> writes it into ${r.path}`) })
479
+ }
480
+ if (key === 'model' && sub === 'set' && value !== undefined) {
481
+ return emit(setDefaultModel(value), (r) => { console.log(`model: ${r.model} — new spores are cut with it, from ${r.path}`) })
482
+ }
483
+ if (!sub || sub === 'get') {
484
+ if (key !== undefined) getKey(key)
485
+ const model = defaultModel()
486
+ const rows = settings().concat({ key: 'model', value: model.model, from: model.model ? model.path : 'unset' })
487
+ return emit(key === undefined ? rows : rows.filter(row => row.key === key), renderSettings)
488
+ }
489
+ if (sub === 'path') return emit({ file: CONFIG_FILE }, (v) => { console.log(v.file) })
490
+ if (sub === 'set') {
491
+ if (key === undefined || value === undefined) {
492
+ console.error('spore: config set needs a key and a value')
493
+ return 2
494
+ }
495
+ return emit(setKey(key, value), renderConfig)
496
+ }
497
+ if (sub === 'add') {
498
+ if (key === undefined || value === undefined) {
499
+ console.error('spore: config add needs a key and a value')
500
+ return 2
501
+ }
502
+ return emit(addTo(key, value), renderConfig)
503
+ }
504
+ if (sub === 'rm') {
505
+ if (key === undefined) {
506
+ console.error('spore: config rm needs a key, and a value to drop just one of a list')
507
+ return 2
508
+ }
509
+ return emit(removeFrom(key, value), renderConfig)
510
+ }
511
+ console.error(`spore: config has no "${sub}" — get, set, add, rm, path`)
512
+ return 2
513
+ }
514
+
515
+ const USAGE_AXES = ['day', 'spore', 'origin', 'model', 'outcome', 'precursor']
516
+ const BAR_WIDTH = 24
517
+ const EIGHTHS = ' ▏▎▍▌▋▊▉'
518
+
519
+ const dollars = (micros) => `$${(micros / 1e6).toFixed(4)}`
520
+ const count = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(n))
521
+ const plural = (n, one) => `${n} ${one}${n === 1 ? '' : 's'}`
522
+
523
+ const bar = (micros, most) => {
524
+ const eighths = most ? Math.round(micros / most * BAR_WIDTH * 8) : 0
525
+ return ('█'.repeat(Math.floor(eighths / 8)) + (eighths % 8 ? EIGHTHS[eighths % 8] : '')).padEnd(BAR_WIDTH)
526
+ }
527
+
528
+ const NULL_KEYS = { model: 'unrecorded', outcome: 'unrecorded', precursor: '(the turns)' }
529
+
530
+ const keyText = (axis, row) => {
531
+ if (row.key === null) return NULL_KEYS[axis]
532
+ if (axis === 'model' && row.unmetered) return `${row.key} not metered (${billingFor(row.key).label})`
533
+ return row.key
534
+ }
535
+
536
+ function renderUsageTable (axis, rows, total) {
537
+ const keys = rows.map(row => keyText(axis, row))
538
+ const width = Math.max(axis.length, ...keys.map(key => key.length))
539
+ console.log(` ${axis.padEnd(width)} turns cells spend share`)
540
+ for (const [i, row] of rows.entries()) {
541
+ const share = total ? `${Math.round(row.micros / total * 100)}%` : ''
542
+ console.log(` ${keys[i].padEnd(width)} ${String(row.turns).padStart(5)} ${String(row.cells).padStart(5)} ${dollars(row.micros).padStart(10)} ${share.padStart(5)}`)
543
+ }
544
+ }
545
+
546
+ function renderUsage (result, by) {
547
+ const { window, totals, unsettled } = result
548
+ const notes = [
549
+ totals.unmetered ? `${plural(totals.unmetered, 'turn')} not metered` : null,
550
+ unsettled.turns ? `${plural(unsettled.turns, 'turn')} unsettled, not summed` : null
551
+ ].filter(Boolean)
552
+ console.log([result.ws ? basename(result.ws) : 'every spore', `${window.since} – ${window.until} ${window.tz}`, dollars(totals.micros), ...notes].join(' · '))
553
+ const limited = result.spend ? spendText(result.spend) : null
554
+ if (limited) console.log(`your spores have spent ${limited}`)
555
+ if (!totals.turns && !totals.cells) {
556
+ console.log('\nnothing ran in this window')
557
+ return
558
+ }
559
+ if (!by || by === 'day') {
560
+ const most = Math.max(...result.days.map(day => day.micros))
561
+ console.log('')
562
+ for (const day of result.days) {
563
+ const label = new Date(Date.parse(day.day)).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
564
+ const ran = day.turns || day.cells
565
+ ? `${plural(day.turns, 'turn')}${day.cells ? ` + ${plural(day.cells, 'cell')}` : ''} ${count(day.inputTokens)} in · ${count(day.outputTokens)} out · ${count(day.cacheReadTokens)} cache read`
566
+ : ''
567
+ console.log(` ${label.padEnd(6)} ${bar(day.micros, most)} ${dollars(day.micros).padStart(10)} ${ran}`.trimEnd())
568
+ }
569
+ }
570
+ const axes = by ? [by].filter(axis => axis !== 'day') : USAGE_AXES.slice(1)
571
+ for (const axis of axes) {
572
+ const rows = result.by[axis]
573
+ if (!by && axis === 'spore' && result.ws) continue
574
+ if (!by && axis === 'precursor' && rows.every(row => row.key === null)) continue
575
+ console.log('')
576
+ renderUsageTable(axis, rows, totals.micros)
577
+ }
578
+ }
579
+
580
+ export async function manage (verb, argv) {
581
+ const emit = (value, render, exit = () => 0) => {
582
+ if (argv.json) console.log(JSON.stringify(value, null, 2))
583
+ else render(value)
584
+ return exit(value)
585
+ }
586
+
587
+ try {
588
+ if (verb === 'config') return config(argv, emit)
589
+ if (verb === 'plugin') return plugin(argv, emit)
590
+ if (verb === 'hook') return hook(argv, emit)
591
+ if (verb === 'remake') {
592
+ const name = argv._[1]
593
+ if (!name) {
594
+ console.error('spore: remake needs a spore — spore remake <name>')
595
+ return 2
596
+ }
597
+ return emit(remake({ ws: name }), (r) => {
598
+ console.error(`spore: made ${r.ws} again from the sporangium ${r.sporangium}, keeping ${r.moved.join(', ')}\n` +
599
+ ` its database, trail and inbox are in ${r.aside} — remove that once you have looked`)
600
+ console.log(r.ws)
601
+ })
602
+ }
603
+ if (verb === 'upgrade') {
604
+ const name = argv._[1]
605
+ if (!name && !argv.all) {
606
+ console.error('spore: upgrade needs a spore, or --all — spore upgrade <name>')
607
+ return 2
608
+ }
609
+ return emit(upgrade({ ws: name, all: argv.all }), (r) => {
610
+ for (const one of r.upgraded) console.log(`${one.ws} ${one.replaced.length ? `replaced ${one.replaced.join(', ')}` : 'current'}`)
611
+ })
612
+ }
613
+ if (verb === 'service') return await service(argv, emit)
614
+ if (verb === 'doctor') {
615
+ return emit(await diagnose(), renderDoctor, (report) => (report.findings.some(found => found.severity === 'problem') ? 1 : 0))
616
+ }
617
+ if (verb === 'define') {
618
+ // No default to the current directory, unlike the read verbs: those answer about
619
+ // where you are, and this one makes something. A bare `define` in a directory that
620
+ // happens to hold a spore.cmk reported that it was already defined, which is an
621
+ // answer to a question nobody asked.
622
+ const name = argv._[1]
623
+ if (!name) {
624
+ console.error('spore: define needs a name — spore define <name>, or . for the directory you are in')
625
+ return 2
626
+ }
627
+ return emit(define({ ws: name, definition: argv.definition, from: argv.from, sporangium: argv.sporangium, model: argv.model, plugins: [].concat(argv.plugin ?? []).map(String) }), renderDefine)
628
+ }
629
+ if (verb === 'log') return emit(log({ ws: argv._[1] }), renderLog)
630
+ if (verb === 'sql') {
631
+ const [, name, ...words] = argv._.map(String)
632
+ const piped = words.length === 1 && words[0] === '-'
633
+ const query = piped ? await readStdin() : words.join(' ')
634
+ if (piped && !query.trim()) {
635
+ console.error('spore: sql - read an empty query from stdin')
636
+ return 2
637
+ }
638
+ const { lines } = sql({ ws: name, query: query || undefined, json: Boolean(argv.json) })
639
+ for (const line of lines) console.log(line)
640
+ return 0
641
+ }
642
+ if (verb === 'tick') return emit(tick(), renderTick, (result) => tickReport(result).exit)
643
+ if (verb === 'pause') return emit(pause({ why: argv._.slice(1).join(' ') || undefined }), renderPause)
644
+ if (verb === 'unpause') return emit(unpause(), renderUnpause, unpauseExit)
645
+ if (verb === 'edit') return emit(await edit({ ws: argv._[1], open: openInEditor, again: editAgain }), renderEdit, editExit)
646
+ if (verb === 'model') {
647
+ const [, ws, model] = argv._.map(String)
648
+ if (model) return emit(switchModel({ ws, model }), renderSwitch)
649
+ const shown = show({ ws })
650
+ return emit({ ws: shown.ws, model: shown.model, models: shown.models }, renderModels)
651
+ }
652
+ if (verb === 'extend') {
653
+ const [, ws, dimension, amount] = argv._.map(String)
654
+ if (!ws || !dimension || !amount) {
655
+ console.error('spore: extend needs a spore, a limit and an amount — spore extend <name> wall 30m|cost 1.50|rounds 20')
656
+ return 2
657
+ }
658
+ return emit(extend({ ws, dimension, amount }), renderChange, changeExit)
659
+ }
660
+ if (verb === 'wrap') {
661
+ const [, ws, wait] = argv._.map(String)
662
+ if (!ws) {
663
+ console.error('spore: wrap needs a spore — spore wrap <name> [10m]')
664
+ return 2
665
+ }
666
+ return emit(wrap({ ws, wait }), renderChange, changeExit)
667
+ }
668
+ if (verb === 'job') {
669
+ const [, sub, ws, name] = argv._
670
+ if (!sub || sub === 'ls') return emit(jobs({ ws }), renderJobs)
671
+ if (sub !== 'stop' || !ws || !name) {
672
+ console.error('spore: job has ls and stop — spore job ls [<name>], spore job stop <name> <job>')
673
+ return 2
674
+ }
675
+ let stopped
676
+ try {
677
+ stopped = stopJob({ ws, name })
678
+ } catch (err) {
679
+ if (err.type !== 'JOB_NOT_RUNNING') throw err
680
+ console.error(`spore: ${err.message} — ${err.detail}`)
681
+ return 1
682
+ }
683
+ return emit(stopped, (r) => { console.log(`asked the supervisor of ${r.name} (pid ${r.pid}) to stop it — how it ended is said to the spore`) })
684
+ }
685
+ if (verb === 'schedule') {
686
+ const [, sub, ws, name, from] = argv._
687
+ if (!sub || sub === 'ls') return emit(schedules({ ws }), renderSchedules)
688
+ if (sub !== 'set' && sub !== 'rm') {
689
+ console.error(`spore: schedule has no "${sub}" — set, rm, ls`)
690
+ return 2
691
+ }
692
+ if (!ws || !name) {
693
+ console.error(`spore: schedule ${sub} needs a spore and a schedule — spore schedule ${sub} <name> <sched>${sub === 'set' ? ' [<file>|-]' : ''}`)
694
+ return 2
695
+ }
696
+ if (sub === 'rm') {
697
+ return emit(removeSchedule({ ws, name }), (r) => { console.log(`removed ${r.name} — ${r.path}`) })
698
+ }
699
+ const source = !from || from === '-' ? await readStdin() : readFileSync(resolve(from), 'utf8')
700
+ return emit(setSchedule({ ws, name, source }), (r) => { console.log(`scheduled ${r.name} — ${r.path}`) })
701
+ }
702
+ if (verb === 'rm') {
703
+ const name = argv._[1]
704
+ if (!name) {
705
+ console.error('spore: rm needs a spore — spore rm <name> [--yes]')
706
+ return 2
707
+ }
708
+ return emit(remove({ ws: name, yes: argv.yes }), (r) => {
709
+ console.log(`removed ${r.ws} — ${r.turns} turn(s), $${r.treeUsd.toFixed(4)}, ${size(r.bytes)}`)
710
+ })
711
+ }
712
+ if (verb === 'usage') {
713
+ if (argv.by !== undefined && !USAGE_AXES.includes(argv.by)) {
714
+ console.error(`spore: usage --by is one of ${USAGE_AXES.join(', ')}`)
715
+ return 2
716
+ }
717
+ return emit(usage({ ws: argv._[1], days: argv.days, since: argv.since, until: argv.until, tz: argv.tz }), (r) => renderUsage(r, argv.by))
718
+ }
719
+ if (verb === 'ls') return emit(list({ where: argv._[1], disk: true }), renderList, listExit)
720
+ if (verb === 'show') return emit(show({ ws: argv._[1] }), renderShow)
721
+ if (verb === 'precursor') {
722
+ const sub = argv._[1]
723
+ if (sub && sub !== 'ls') {
724
+ console.error(`spore: precursor has no "${sub}" — only ls`)
725
+ return 2
726
+ }
727
+ return emit(precursors({ ws: argv._[2] }), (result) => {
728
+ for (const name of result.precursors) console.log(name)
729
+ if (!result.precursors.length) console.log('none — this workspace delegates to nothing')
730
+ })
731
+ }
732
+ } catch (err) {
733
+ console.error(`spore: ${err.detail ? `${err.message} — ${err.detail}` : err.message}`)
734
+ return 2
735
+ }
736
+ }