@rhizogrip/spore-cli 1.35.0 → 1.37.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/bin/spore.js CHANGED
@@ -14,8 +14,9 @@ import { basename, resolve } from 'node:path'
14
14
 
15
15
  import minimist from 'minimist'
16
16
 
17
- import { differingDocs, fork, follow, followingDocs, grantOf, isWorkspace, lastEventSeq, loadEnvironment, mimeOf, readConfig, readInbox, RUNNING, send, stateOf, stop, turnOfMessage, turnSummary, watch, workspaceFor } from '@rhizogrip/spore'
17
+ import { differingDocs, fork, follow, followingDocs, grantOf, isWorkspace, lastEventSeq, loadEnvironment, mimeOf, readConfig, readInbox, RUNNING, send, stateOf, stop, turnOfMessage, turnSummary, watch, workspaceFor, errorText } from '@rhizogrip/spore'
18
18
  import { renderHeader } from '../src/dispatch.js'
19
+ import { SERVICES } from '../src/services.js'
19
20
 
20
21
  // Detaching is neither success nor failure: the turn is still going, and 0 would claim it
21
22
  // answered. `spore show` says what actually happened once it has.
@@ -25,8 +26,8 @@ const DEFAULT_TAIL = 50
25
26
 
26
27
  const argv = minimist(process.argv.slice(2), {
27
28
  string: ['_', 'definition', 'from', 'sporangium', 'at', 'model', 'plugin', 'attach', 'request-id', 'after', 'since', 'until', 'tz', 'by', 'n', 'lines'],
28
- boolean: ['debug', 'help', 'version', 'unsafe', 'yes', 'replay', 'json', 'all', 'outdated', 'f', 'clear'],
29
- alias: { h: 'help' }
29
+ boolean: ['debug', 'help', 'version', 'yes', 'replay', 'json', 'all', 'outdated', 'f', 'clear'],
30
+ alias: { h: 'help', n: 'lines' }
30
31
  })
31
32
 
32
33
  const VERBS = `Usage:
@@ -61,7 +62,6 @@ const VERBS = `Usage:
61
62
  spore sql [<name> [<query>|-]] its records, read with SQL; .tables lists the views, - the query on stdin
62
63
  spore usage [<name>] [--days 7] what it spent per day, by origin, model, outcome, precursor
63
64
  spore usage --since <d> [--until <d>] over those local days; --tz <zone>, --by <axis>, every spore without a name
64
- spore precursor ls [<name>] what it can delegate to
65
65
  spore upgrade <name>|--all its root docs replaced by what is installed
66
66
  spore plugin ls plugins installed beside spore, and which are allowed
67
67
  spore plugin allow <plugin> [k=v …] checked, then recorded in config.json; disallow undoes it
@@ -76,7 +76,7 @@ const VERBS = `Usage:
76
76
  spore job stop <name> <job> ask a running job's supervisor to stop it
77
77
  spore pause [why] stop every turn and job of your spores, and start none
78
78
  spore unpause let turns start again; what waited goes at the next tick
79
- spore service ls the services spore ships (webhook, tick, api, ssh-agent, sluice) and its plugins offer
79
+ spore service ls the services spore ships (${Object.keys(SERVICES).join(', ')}) and its plugins offer
80
80
  spore service define <svc> write its systemd user unit, checked first
81
81
  spore service start|stop|restart <svc> now; enable|disable: at every login
82
82
  spore service restart --outdated every service running older code than is installed
@@ -112,7 +112,6 @@ ${VERBS}
112
112
  --definition the .cmk to give it, instead of your default
113
113
  --from the spore to cut it from: what it can do, never what it did
114
114
  --json for a program: the answer as JSON, with the same exit code
115
- --unsafe no Landlock sandbox and no namespaces: no confinement at all
116
115
  --debug verbose logging on stderr
117
116
 
118
117
  send, attach and fork exit 0 when the turn answered, 1 when it ended with no answer,
@@ -133,8 +132,8 @@ const ALL = Infinity
133
132
  // subcommand for a verb that has them, `bare` being the one it runs without. A message, a
134
133
  // query, a reason to pause and a plugin's settings take every word left.
135
134
  const SHAPES = {
136
- send: { flags: ['attach', 'request-id', 'json', 'unsafe', 'debug'], most: ALL },
137
- fork: { flags: ['at', 'definition', 'replay', 'unsafe', 'debug'], most: 2 },
135
+ send: { flags: ['attach', 'request-id', 'json', 'debug'], most: ALL },
136
+ fork: { flags: ['at', 'definition', 'replay', 'debug'], most: 2 },
138
137
  attach: { flags: ['n', 'lines', 'json', 'after'], most: 1 },
139
138
  stop: { flags: [], most: 1 },
140
139
  extend: withJson(3),
@@ -149,7 +148,6 @@ const SHAPES = {
149
148
  show: withJson(1),
150
149
  log: withJson(1),
151
150
  sql: withJson(ALL),
152
- precursor: { bare: 'ls', subs: { ls: withJson(1) } },
153
151
  upgrade: withJson(1, 'all'),
154
152
  plugin: { bare: 'ls', subs: { ls: withJson(0), show: withJson(1), allow: withJson(ALL), disallow: withJson(1) } },
155
153
  schedule: { bare: 'ls', subs: { set: withJson(3), rm: withJson(2), ls: withJson(1) } },
@@ -230,6 +228,7 @@ if (shape) {
230
228
  if (unknown.length) {
231
229
  fail(`unknown option ${unknown.map(dashed).join(', ')} — ${label} takes ${shape.flags.length ? shape.flags.map(dashed).join(', ') : 'no option'}`)
232
230
  }
231
+ if (argv.n !== undefined && !/^\d+$/.test(argv.n)) fail(`-n ${argv.n} is not a number of lines`)
233
232
  const extra = argv._.slice(subs ? 2 : 1).slice(shape.most)
234
233
  if (extra.length) {
235
234
  const most = shape.most === 0 ? 'no argument' : shape.most === 1 ? 'at most one argument' : `at most ${shape.most} arguments`
@@ -240,7 +239,7 @@ if (shape) {
240
239
  try {
241
240
  loadEnvironment()
242
241
  } catch (err) {
243
- if (verb !== 'doctor') fail(`${err.message} — ${err.detail}`)
242
+ if (verb !== 'doctor') fail(errorText(err))
244
243
  }
245
244
 
246
245
  if (verb === 'tui') {
@@ -254,14 +253,14 @@ if (verb === 'tui') {
254
253
  if (verb === 'setup') {
255
254
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
256
255
  fail('setup asks questions, and this is not a terminal — the same steps are spore config set home <dir>, ' +
257
- 'mo onboard <provider>, spore config set model <provider>/<name>, spore config set spendPerDay <dollars>, spore doctor')
256
+ 'mo onboard <provider>, spore config set model <provider>/<name>, spore doctor')
258
257
  }
259
258
  const { setup } = await import('../src/setup.js')
260
259
  try {
261
260
  process.exit(await setup())
262
261
  } catch (err) {
263
262
  if (!err.type) throw err
264
- fail(err.detail ? `${err.message} — ${err.detail}` : err.message)
263
+ fail(errorText(err))
265
264
  }
266
265
  }
267
266
 
@@ -271,7 +270,7 @@ if (verb === 'here') {
271
270
  process.exit(await here({ dir: argv._[1], sporangium: argv.sporangium, model: argv.model, git: argv.git !== false }))
272
271
  } catch (err) {
273
272
  if (!err.type) throw err
274
- fail(err.detail ? `${err.message} — ${err.detail}` : err.message)
273
+ fail(errorText(err))
275
274
  }
276
275
  }
277
276
 
@@ -338,7 +337,7 @@ function spore (name, { needed = true } = {}) {
338
337
  try {
339
338
  target = workspaceFor(name)
340
339
  } catch (err) {
341
- fail(`${err.message} — ${err.detail}`)
340
+ fail(errorText(err))
342
341
  }
343
342
  if (needed && !isWorkspace(target.path)) {
344
343
  fail(target.named
@@ -370,9 +369,9 @@ if (verb === 'fork') {
370
369
  if (!asked || !argv.at || !into) fail('fork needs a spore, a call and somewhere new — spore fork <name> --at <call> <new> [--definition <f>] [--replay]')
371
370
  let made
372
371
  try {
373
- made = fork({ run: spore(asked), at: argv.at, into: workspaceFor(into).path, definition: argv.definition, replay: argv.replay, unsafe: argv.unsafe, debug: argv.debug })
372
+ made = fork({ run: spore(asked), at: argv.at, into: workspaceFor(into).path, definition: argv.definition, replay: argv.replay, debug: argv.debug })
374
373
  } catch (err) {
375
- fail(err.detail ? `${err.message} — ${err.detail}` : err.message)
374
+ fail(errorText(err))
376
375
  }
377
376
  console.error(`spore: forked ${made.from} at ${made.at}, round ${made.rounds} — carrying it on in ${made.ws}`)
378
377
  renderHeader(made.ws, grantOf(made.ws))
@@ -394,8 +393,7 @@ if (verb === 'attach') {
394
393
  process.exit(await events(ws, after) ? DETACHED : exitFor(ws))
395
394
  }
396
395
  if (argv.after !== undefined) fail('--after is for --json — spore attach <name> --json --after <seq>')
397
- const tail = argv.n ?? argv.lines
398
- if (tail !== undefined && !/^\d+$/.test(tail)) fail(`-n ${tail} is not a number of lines`)
396
+ const tail = argv.n
399
397
  const running = stateOf(ws).state === RUNNING
400
398
  const ended = await follow(ws, { lines: tail !== undefined ? Number(tail) : running ? 0 : DEFAULT_TAIL, status: true })
401
399
  process.exit(ended === 'detached' ? DETACHED : exitFor(ws))
@@ -423,7 +421,7 @@ try {
423
421
  differs = differingDocs(ws)
424
422
  followed = followingDocs(readConfig())
425
423
  } catch (err) {
426
- fail(err.detail ? `${err.message} — ${err.detail}` : err.message)
424
+ fail(errorText(err))
427
425
  }
428
426
  if (differs.length && !followed) console.error(`spore: ${differs.map(d => d.file).join(', ')} differ from what is installed — spore upgrade ${asked}`)
429
427
 
@@ -434,9 +432,9 @@ let grant
434
432
  let sent
435
433
  try {
436
434
  grant = grantOf(ws)
437
- sent = send(ws, message, { attach, requestId, replyTo: 'terminal', unsafe: argv.unsafe, debug: argv.debug })
435
+ sent = send(ws, message, { attach, requestId, replyTo: 'terminal', debug: argv.debug })
438
436
  } catch (err) {
439
- fail(err.detail ? `${err.message} — ${err.detail}` : err.message)
437
+ fail(errorText(err))
440
438
  }
441
439
 
442
440
  // Sent before under this request id and already ended: nothing runs, and what it got is on
@@ -446,10 +444,6 @@ const settled = sent.repeated && !sent.started && stateOf(ws).state !== RUNNING
446
444
  const dreaming = !sent.started && !settled && stateOf(ws).dreaming
447
445
  if (dreaming) console.error('spore: it is dreaming — your message waits for it to wake, and the turn after the dream reads it')
448
446
 
449
- if (argv.unsafe && !sent.started && !settled) {
450
- console.error('spore: --unsafe took no effect — the message went to the turn already running, which keeps the confinement it was started with')
451
- }
452
-
453
447
  if (argv.json) {
454
448
  line({ event: 'sent', inbox: sent.inbox, started: sent.started, repeated: sent.repeated })
455
449
  if (!settled && await events(ws, after)) process.exit(DETACHED)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rhizogrip/spore-cli",
3
- "version": "1.35.0",
3
+ "version": "1.37.0",
4
4
  "author": {
5
5
  "name": "Christophe Le Bars",
6
6
  "email": "clb@toort.net"
@@ -50,7 +50,7 @@
50
50
  "tui": "node bin/spore.js tui"
51
51
  },
52
52
  "dependencies": {
53
- "@rhizogrip/spore": "1.35.0",
53
+ "@rhizogrip/spore": "1.37.0",
54
54
  "chalk": "^6.0.1",
55
55
  "minimist": "^1.2.8"
56
56
  },
package/src/dispatch.js CHANGED
@@ -1,6 +1,6 @@
1
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.
2
+ * Rendering for every verb but the ones that run a turn. Parsing lives in `bin/spore.js`, the
3
+ * answers live in the library's verbs, and this is only the part that decides what a person sees.
4
4
  *
5
5
  * `--json` prints the library's own shape, one object, so anything scripting against this
6
6
  * reads the same thing an embedder would and does not parse a table. A verb's exit code is a
@@ -13,12 +13,7 @@ import { readFileSync } from 'node:fs'
13
13
  import { homedir } from 'node:os'
14
14
  import { basename, join, resolve } from 'node:path'
15
15
 
16
- import {
17
- addTo, allowPlugin, annotate, billingFor, changeText, define, defaultModel, disallowPlugin, durationText,
18
- edit, extend, getKey, jobs, list, listApprovals, listPlugins, log, pause, precursors, remake, remove,
19
- removeFrom, removeSchedule, requestApproval, runningLines, schedules, setDefaultModel, setKey, setSchedule, settings,
20
- show, showPlugin, sql, stateWord, stopJob, switchModel, tick, tickReport, unmetered, unpause, upgrade, usage, wrap, CONFIG_FILE, DEFAULT_SPORANGIUM
21
- } from '@rhizogrip/spore'
16
+ import { addTo, allowPlugin, annotate, billingFor, bytesText, changeText, define, defaultModel, disallowPlugin, durationText, edit, extend, getKey, jobs, list, listApprovals, listPlugins, log, pause, remake, remove, removeFrom, removeSchedule, requestApproval, runningLines, schedules, setDefaultModel, setKey, setSchedule, settings, show, showPlugin, sql, stateWord, stopJob, switchModel, tick, tickReport, unmetered, unpause, upgrade, usage, wrap, CONFIG_FILE, DEFAULT_SPORANGIUM, errorText } from '@rhizogrip/spore'
22
17
  import { diagnose, renderDoctor } from './doctor.js'
23
18
  import { hook } from './hooks.js'
24
19
  import { createServices } from './services.js'
@@ -26,17 +21,6 @@ import { saidBy, saidText } from '../tui/conversation.js'
26
21
 
27
22
  const STATE_WIDTH = 9
28
23
 
29
- const size = (bytes) => {
30
- const units = ['B', 'KB', 'MB', 'GB', 'TB']
31
- let value = bytes
32
- let unit = 0
33
- while (value >= 1024 && unit < units.length - 1) {
34
- value /= 1024
35
- unit++
36
- }
37
- return `${unit ? value.toFixed(1) : value}${units[unit]}`
38
- }
39
-
40
24
  const tilde = (path) => (path === homedir() || path.startsWith(homedir() + '/') ? `~${path.slice(homedir().length)}` : path)
41
25
 
42
26
  const line = (row, under) => {
@@ -44,7 +28,7 @@ const line = (row, under) => {
44
28
  const spend = row.treeUsd ? `$${row.treeUsd.toFixed(4)}` : ''
45
29
  const works = row.definitionError ? ' (its spore.cmk does not parse)' : row.writes.map(path => ` → ${tilde(path)}`).join('')
46
30
  const over = row.historyOver ? ' (history over its bound)' : ''
47
- return ` ${stateWord(row).padEnd(STATE_WIDTH)} ${String(row.lastTurnNo).padStart(4)} turns ${spend.padStart(9)} ${size(row.bytes).padStart(8)} ${where}${works}${over}`
31
+ return ` ${stateWord(row).padEnd(STATE_WIDTH)} ${String(row.lastTurnNo).padStart(4)} turns ${spend.padStart(9)} ${bytesText(row.bytes).padStart(8)} ${where}${works}${over}`
48
32
  }
49
33
 
50
34
  const block = (title, rows, under) => {
@@ -63,8 +47,6 @@ function renderList (result) {
63
47
  }
64
48
  for (const skip of result.missing) console.error(`spore: skipped ${skip.path} — ${skip.why}`)
65
49
  if (result.paused) console.log(`your spores are ${pausedText(result.paused)} — no turn starts until spore unpause\n`)
66
- const limited = spendText(result.spend)
67
- if (limited) console.log(`your spores have spent ${limited}\n`)
68
50
  if (!result.contain) console.log('turns are not contained (contain off): each sees every other spore\'s processes\n')
69
51
 
70
52
  const home = result.workspaces.filter(row => row.from === result.home)
@@ -82,17 +64,6 @@ function renderList (result) {
82
64
 
83
65
  const listExit = (result) => (result.configured ? 0 : 2)
84
66
 
85
- /** `today $4.12 of $20.00 · October $81.30 of $300.00`, the windows a limit is set on; null with none. */
86
- const spendText = ({ date, day, month, limits }) => {
87
- const of = (spent, limit) => `$${spent.toFixed(2)} of $${limit.toFixed(2)}${spent >= limit ? ' — reached, no turn starts' : ''}`
88
- const monthName = new Date(`${date}T00:00:00Z`).toLocaleDateString('en-US', { month: 'long', timeZone: 'UTC' })
89
- const parts = [
90
- limits.day === null ? null : `today ${of(day, limits.day)}`,
91
- limits.month === null ? null : `${monthName} ${of(month, limits.month)}`
92
- ].filter(Boolean)
93
- return parts.length ? parts.join(' · ') : null
94
- }
95
-
96
67
  function renderModels ({ model, models }) {
97
68
  console.log(`runs on ${model}`)
98
69
  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')
@@ -131,7 +102,7 @@ const modelLine = (model, billing) => `${model}${billing === null ? ' (a provid
131
102
  export function renderHeader (ws, grant) {
132
103
  console.error([
133
104
  `spore ${ws}`,
134
- ` ${modelLine(grant.model, grant.billing)} · tools: ${grant.tools.join(', ')}`,
105
+ ` ${modelLine(grant.model, grant.billing)} · tools: ${grant.tools.join(', ')}${grant.unconfined ? ' · unconfined' : ''}`,
135
106
  ` limits: ${bounds(grant.limits, grant.billing)} (soft wraps, hard stops)`
136
107
  ].join('\n'))
137
108
  }
@@ -147,6 +118,7 @@ function renderShow (result) {
147
118
  if (result.models.length) line('or', result.models.join(', '))
148
119
  if (result.cellModels.length) line('cell models', result.cellModels.map(named => `${named.name}=${named.model}`).join(', '))
149
120
  line('tools', result.tools.length ? result.tools.join(', ') : 'none')
121
+ if (result.unconfined) line('confined', 'no — its spore.cmk says unconfined: true, so its turns run with no Landlock, seccomp or namespaces')
150
122
  line('limits', bounds(result.limits, result.billing))
151
123
  if (result.turnLimits) for (const [i, one] of runningLines(result.turnLimits, result.extend).entries()) line(i ? '' : 'this turn', one)
152
124
  if (result.sources?.length) {
@@ -156,6 +128,7 @@ function renderShow (result) {
156
128
  }).join(', '))
157
129
  }
158
130
  if (result.reads?.length) line('reads', result.reads.map(r => `${r.name} → ${r.path}`).join(', '))
131
+ if (result.prepare) line('prepare', `${result.prepare.steps.map(step => `${step.origin} by ${step.plugin}/${step.program}`).join(', ')} — up to ${durationText(result.prepare.timeout)}, ${result.prepare.attach.files} files`)
159
132
  if (result.writes?.length) line('writes', result.writes.map(w => `${w.name} → ${w.path}`).join(', '))
160
133
  if (result.memory) line('memory', `${result.memory.backend} push ${result.memory.push} pull ${result.memory.pull}`)
161
134
  line('messages', `${result.messages}${result.waiting ? ` (${result.waiting} waiting)` : ''}`)
@@ -185,7 +158,7 @@ function renderShow (result) {
185
158
  if (result.plugins.length) line('plugins', result.plugins.join(', '))
186
159
  if (result.differs.length) line('docs', `${result.differs.join(', ')} differ from what is installed — spore upgrade ${basename(result.ws)}`)
187
160
  const { disk } = result
188
- 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)}`)
161
+ line('disk', `${bytesText(disk.total)} — data ${bytesText(disk.data)} · records ${bytesText(disk.state)} · streams ${bytesText(disk.calls)} · sent ${bytesText(disk.inbox)} · other ${bytesText(disk.other)}`)
189
162
  for (const [i, one] of result.schedules.entries()) line(i ? '' : 'schedules', scheduleLine(one))
190
163
  if (result.scheduleBound) {
191
164
  const b = result.scheduleBound
@@ -444,11 +417,7 @@ async function service (argv, emit) {
444
417
  return emit(services.remove(name, { yes: argv.yes }), (r) => { for (const unit of r.units) console.log(`removed ${unit}`) })
445
418
  }
446
419
  if (sub === 'log') {
447
- const lines = argv.n ?? argv.lines ?? '50'
448
- if (!/^\d+$/.test(lines)) {
449
- console.error(`spore: -n ${lines} is not a number of lines`)
450
- return 2
451
- }
420
+ const lines = argv.n ?? '50'
452
421
  const unit = services.log(name)
453
422
  return spawnSync('journalctl', ['--user', '-u', unit, '-n', lines, '--no-pager', '-o', 'short-iso', ...(argv.f ? ['-f'] : [])], { stdio: 'inherit' }).status ?? 1
454
423
  }
@@ -477,7 +446,6 @@ function renderPlugin (result) {
477
446
  line(i ? '' : 'settings', `${key} (${kind})${result.configured?.[key] === undefined ? '' : ` = ${result.configured[key]}`}`)
478
447
  }
479
448
  for (const [i, [name, path]] of Object.entries(result.programs).entries()) line(i ? '' : 'programs', `${name} → ${path}`)
480
- for (const [i, [name, path]] of Object.entries(result.routes).entries()) line(i ? '' : 'routes', `${name} → ${path}, an owner's router (hooks.json)`)
481
449
  for (const [i, [name, value]] of Object.entries(result.env).entries()) line(i ? '' : 'env', `${name}=${value}`)
482
450
  if (result.contain) line('contain', result.contain.keep ? `${result.contain.keep}, and nothing else of ${result.contain.hide}` : `nothing of ${result.contain.hide}`)
483
451
  if (result.modules.length) line('modules', `${result.modules.join(', ')} → node_modules/, for the agent's programs`)
@@ -588,8 +556,6 @@ function renderUsage (result, by) {
588
556
  unsettled.turns ? `${plural(unsettled.turns, 'turn')} unsettled, not summed` : null
589
557
  ].filter(Boolean)
590
558
  console.log([result.ws ? basename(result.ws) : 'every spore', `${window.since} – ${window.until} ${window.tz}`, dollars(totals.micros), ...notes].join(' · '))
591
- const limited = result.spend ? spendText(result.spend) : null
592
- if (limited) console.log(`your spores have spent ${limited}`)
593
559
  if (!totals.turns && !totals.cells) {
594
560
  console.log('\nnothing ran in this window')
595
561
  return
@@ -724,7 +690,7 @@ export async function manage (verb, argv) {
724
690
  stopped = stopJob({ ws, name })
725
691
  } catch (err) {
726
692
  if (err.type !== 'JOB_NOT_RUNNING') throw err
727
- console.error(`spore: ${err.message} — ${err.detail}`)
693
+ console.error(`spore: ${errorText(err)}`)
728
694
  return 1
729
695
  }
730
696
  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`) })
@@ -774,7 +740,7 @@ export async function manage (verb, argv) {
774
740
  return 2
775
741
  }
776
742
  return emit(remove({ ws: name, yes: argv.yes }), (r) => {
777
- console.log(`removed ${r.ws} — ${r.turns} turn(s), $${r.treeUsd.toFixed(4)}, ${size(r.bytes)}`)
743
+ console.log(`removed ${r.ws} — ${r.turns} turn(s), $${r.treeUsd.toFixed(4)}, ${bytesText(r.bytes)}`)
778
744
  })
779
745
  }
780
746
  if (verb === 'usage') {
@@ -786,19 +752,8 @@ export async function manage (verb, argv) {
786
752
  }
787
753
  if (verb === 'ls') return emit(list({ where: argv._[1], disk: true }), renderList, listExit)
788
754
  if (verb === 'show') return emit(show({ ws: argv._[1] }), renderShow)
789
- if (verb === 'precursor') {
790
- const sub = argv._[1]
791
- if (sub && sub !== 'ls') {
792
- console.error(`spore: precursor has no "${sub}" — only ls`)
793
- return 2
794
- }
795
- return emit(precursors({ ws: argv._[2] }), (result) => {
796
- for (const name of result.precursors) console.log(name)
797
- if (!result.precursors.length) console.log('none — this workspace delegates to nothing')
798
- })
799
- }
800
755
  } catch (err) {
801
- console.error(`spore: ${err.detail ? `${err.message} — ${err.detail}` : err.message}`)
756
+ console.error(`spore: ${errorText(err)}`)
802
757
  return 2
803
758
  }
804
759
  }
package/src/here.js CHANGED
@@ -62,15 +62,18 @@ export function snapshot (dir, { spore, session }) {
62
62
  return ref
63
63
  }
64
64
 
65
+ const KEPT = 3
66
+
65
67
  /**
66
- * Drops all but the newest `keep` of `spore`'s session snapshots, so what an old one holds — an
67
- * untracked file since deleted — leaves `.git` with it; the refs dropped, oldest first. Session
68
+ * Drops all but the newest `KEPT` of `spore`'s session snapshots, so what an old one holds — an
69
+ * untracked file since deleted — leaves `.git` with it; the refs dropped, oldest first. A session
70
+ * reads only its own; more than one is kept for another session of the spore still open. Session
68
71
  * names are UTC times, so their order is their names'.
69
72
  */
70
- export function pruneSnapshots (dir, { spore, keep }) {
73
+ export function pruneSnapshots (dir, { spore }) {
71
74
  const top = workTreeOf(dir)
72
75
  const refs = git(top, ['for-each-ref', '--sort=refname', '--format=%(refname)', `refs/spore/${spore}/`]).split('\n').filter(Boolean)
73
- const dropped = refs.slice(0, Math.max(0, refs.length - keep))
76
+ const dropped = refs.slice(0, Math.max(0, refs.length - KEPT))
74
77
  for (const ref of dropped) git(top, ['update-ref', '-d', ref])
75
78
  return dropped
76
79
  }
package/src/hooks.js CHANGED
@@ -1,4 +1,4 @@
1
- import { durationText, listHooks, showHook } from '@rhizogrip/spore'
1
+ import { durationText, listHooks, showHook, sizeSpelling } from '@rhizogrip/spore'
2
2
 
3
3
  import { createServices } from './services.js'
4
4
 
@@ -6,8 +6,6 @@ const JOURNAL_LINES = 20
6
6
  const ANSWER_CHARS = 120
7
7
  const UNAVAILABLE = new Set(['SERVICE_NO_SYSTEMD', 'SERVICE_NOT_DEFINED'])
8
8
 
9
- const kb = (bytes) => bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)}MB` : `${Math.round(bytes / 1024)}KB`
10
-
11
9
  const verifyText = ({ method, header }) => header ? `${method} on ${header}` : method
12
10
 
13
11
  const acceptText = (accept) => [
@@ -46,15 +44,11 @@ function renderHook (hook) {
46
44
  console.log(`${hook.name} — ${hook.path}`)
47
45
  console.log(` verify ${verifyText(hook.verify)}`)
48
46
  if (hook.accept) console.log(` accepts ${acceptText(hook.accept)}`)
49
- console.log(` bounds ${kb(hook.maxBytes)} a request · ${hook.perHour} turns an hour · ${hook.maxWait ? `waits up to ${durationText(hook.maxWait)} · ${hook.perDay} triage cells a day` : 'released at once'}`)
50
- if (hook.owner) {
51
- const { plugin, name, timeoutMs, attach, reads } = hook.owner
52
- console.log(` router ${plugin}/${name}, the owner's: attaches up to ${attach.files} files and ${kb(attach.bytes)} within ${durationText(timeoutMs)}${reads === 'spore' ? ', reading what the spore\'s reads: grant' : reads.length ? `, reading ${reads.join(', ')}` : ''}`)
53
- }
47
+ console.log(` bounds ${sizeSpelling(hook.maxBytes)} a request · ${hook.perHour} turns an hour · ${hook.maxWait ? `waits up to ${durationText(hook.maxWait)}` : 'never waits'} · ${hook.perDay} triage cells a day`)
54
48
  for (const spore of hook.spores) {
55
49
  console.log(`\n${sporeLine(spore, spore.name.length)}`)
56
50
  if (!spore.ws) continue
57
- if (spore.router) console.log(` router ${spore.router}${hook.owner ? ', not run: the owner\'s router is' : ''}`)
51
+ if (spore.router) console.log(` router ${spore.router}`)
58
52
  if (spore.triage) console.log(` triage ${spore.triage}`)
59
53
  for (const held of spore.held) console.log(` held since ${held.at}, released ${held.releaseAt}, at the latest ${held.deadline}${held.summary ? ` — ${held.summary}` : ''}`)
60
54
  for (const d of spore.deliveries) {
package/src/services.js CHANGED
@@ -14,12 +14,12 @@
14
14
  */
15
15
 
16
16
  import { spawnSync } from 'node:child_process'
17
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
17
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
18
18
  import { createRequire } from 'node:module'
19
19
  import { homedir, userInfo } from 'node:os'
20
20
  import { dirname, join } from 'node:path'
21
21
 
22
- import { CONFIG_DIR, pluginRoots, pluginServices, SERVICE_STATE_DIR, SporeError, versionAt } from '@rhizogrip/spore'
22
+ import { CONFIG_DIR, instanceFile, instanceNames, instancesDir, NAMES, pluginRoots, pluginServices, SERVICE_STATE_DIR, SporeError, versionAt } from '@rhizogrip/spore'
23
23
 
24
24
  const SPORE_PACKAGE = '@rhizogrip/spore'
25
25
  const ROOT = dirname(createRequire(import.meta.url).resolve(`${SPORE_PACKAGE}/package.json`))
@@ -33,12 +33,30 @@ const MARKER = 'X-Spore-Service'
33
33
 
34
34
  const quoted = (path) => `"${path}"`
35
35
 
36
+ /** A Node program's unit, restarted when it fails and never after it refuses with exit 2. */
37
+ const nodeUnit = ({ description, marker, node, program, args = '' }) => [
38
+ '[Unit]',
39
+ `Description=${description}`,
40
+ `${MARKER}=${marker}`,
41
+ '',
42
+ '[Service]',
43
+ `ExecStart=${quoted(node)} ${quoted(program)}${args}`,
44
+ 'Restart=on-failure',
45
+ 'RestartPreventExitStatus=2',
46
+ 'KillMode=process',
47
+ '',
48
+ '[Install]',
49
+ 'WantedBy=default.target'
50
+ ]
51
+
36
52
  /**
37
53
  * The keys the ssh-agent service loads: every private key in this folder beside `config.json`,
38
54
  * never inside a workspace, so no spore can read one. Adding or retiring a key is putting it in
39
55
  * or taking it out, then restarting the service.
40
56
  */
41
57
  export const SSH_KEYS_DIR = join(CONFIG_DIR, 'ssh')
58
+
59
+ const INSTALL = { node: process.execPath, root: ROOT, keys: SSH_KEYS_DIR }
42
60
  export const SSH_AGENT_SOCKET = 'spore-ssh-agent.socket'
43
61
 
44
62
  const sshKeysCheck = (keys) => [
@@ -70,7 +88,7 @@ const sluiceCheck = (binary, rules) => [
70
88
  * service's own start-up checks and exits, so one that cannot start is refused before its unit
71
89
  * is written.
72
90
  *
73
- * A service with `instances` runs once per file in that folder beside `config.json`, as
91
+ * A service with `instances` runs once per `<instance>.json` in the folder named after it beside `config.json`, as
74
92
  * `<name>@<instance>`: one template unit, and an instance of it per file, each started, enabled and
75
93
  * logged on its own.
76
94
  */
@@ -83,20 +101,7 @@ export const SERVICES = Object.freeze({
83
101
  check: ({ node, root }) => [node, [join(root, 'bin', 'spore-webhook.js'), '--check']],
84
102
  next: () => 'give each sender http://<host>/hook/<name> through your reverse proxy — it listens on 127.0.0.1:8742, or SPORE_WEBHOOK_LISTEN in environment',
85
103
  units: ({ node, root }) => ({
86
- 'spore-webhook.service': [
87
- '[Unit]',
88
- 'Description=spore-webhook: webhooks as messages to spores',
89
- `${MARKER}=webhook`,
90
- '',
91
- '[Service]',
92
- `ExecStart=${quoted(node)} ${quoted(join(root, 'bin', 'spore-webhook.js'))}`,
93
- 'Restart=on-failure',
94
- 'RestartPreventExitStatus=2',
95
- 'KillMode=process',
96
- '',
97
- '[Install]',
98
- 'WantedBy=default.target'
99
- ]
104
+ 'spore-webhook.service': nodeUnit({ description: 'spore-webhook: webhooks as messages to spores', marker: 'webhook', node, program: join(root, 'bin', 'spore-webhook.js') })
100
105
  })
101
106
  },
102
107
  api: {
@@ -107,20 +112,7 @@ export const SERVICES = Object.freeze({
107
112
  check: ({ node, root }) => [node, [join(root, 'bin', 'spore-api.js'), '--check']],
108
113
  next: () => 'give each caller its token and the socket or address api.json names',
109
114
  units: ({ node, root }) => ({
110
- 'spore-api.service': [
111
- '[Unit]',
112
- 'Description=spore-api: the library\'s verbs over HTTP',
113
- `${MARKER}=api`,
114
- '',
115
- '[Service]',
116
- `ExecStart=${quoted(node)} ${quoted(join(root, 'bin', 'spore-api.js'))}`,
117
- 'Restart=on-failure',
118
- 'RestartPreventExitStatus=2',
119
- 'KillMode=process',
120
- '',
121
- '[Install]',
122
- 'WantedBy=default.target'
123
- ]
115
+ 'spore-api.service': nodeUnit({ description: 'spore-api: the library\'s verbs over HTTP', marker: 'api', node, program: join(root, 'bin', 'spore-api.js') })
124
116
  })
125
117
  },
126
118
  'ssh-agent': {
@@ -218,20 +210,7 @@ function fromPlugin (found) {
218
210
  runs: named,
219
211
  check: found.check && (({ node, instance }) => [node, [found.program, ...(instance === null ? [] : [instance]), ...found.check]]),
220
212
  units: ({ node }) => ({
221
- [unit]: [
222
- '[Unit]',
223
- `Description=spore-${found.name}${instance}: ${found.what.replaceAll('%', '%%')}`,
224
- `${MARKER}=${found.name}`,
225
- '',
226
- '[Service]',
227
- `ExecStart=${quoted(node)} ${quoted(found.program)}${instance}`,
228
- 'Restart=on-failure',
229
- 'RestartPreventExitStatus=2',
230
- 'KillMode=process',
231
- '',
232
- '[Install]',
233
- 'WantedBy=default.target'
234
- ]
213
+ [unit]: nodeUnit({ description: `spore-${found.name}${instance}: ${found.what.replaceAll('%', '%%')}`, marker: found.name, node, program: found.program, args: instance })
235
214
  })
236
215
  }
237
216
  }
@@ -257,9 +236,9 @@ function catalogOf (roots) {
257
236
  }
258
237
 
259
238
  /** The unit files of a service, as they are written. */
260
- export function renderUnits (name, { node = process.execPath, root = ROOT, keys = SSH_KEYS_DIR, roots = pluginRoots() } = {}) {
239
+ export function renderUnits (name, { roots = pluginRoots() } = {}) {
261
240
  const { base, service } = parsed(name, catalogOf(roots).services, { instanceOptional: true, verb: 'define' })
262
- return Object.fromEntries(Object.entries(service.units({ node, root, keys }))
241
+ return Object.fromEntries(Object.entries(service.units(INSTALL))
263
242
  .map(([file, lines]) => [file, `# Written by \`spore service define ${base}\`. Change it with that command, not by hand.\n${lines.join('\n')}\n`]))
264
243
  }
265
244
 
@@ -274,8 +253,6 @@ function serviceOf (name, catalog) {
274
253
  return service
275
254
  }
276
255
 
277
- const INSTANCE = /^[a-z0-9][a-z0-9._-]*$/i
278
-
279
256
  /**
280
257
  * `telegram@reviewer` is the service `telegram`, its instance `reviewer`. `verb` is the `spore
281
258
  * service` subcommand it was named to, for the command a refusal suggests.
@@ -291,11 +268,11 @@ function parsed (name, catalog, { instanceOptional = false, verb } = {}) {
291
268
  if (service.instances && instance === null && !instanceOptional) {
292
269
  throw new SporeError(`${base} runs once per ${service.instances.called}: name one`, {
293
270
  type: 'SERVICE_NEEDS_INSTANCE',
294
- detail: `spore service ${verb} ${base}@<${service.instances.called}>, for the ${service.instances.called} in ${service.instances.dir}/<${service.instances.called}>${service.instances.ext} beside config.json`
271
+ detail: `spore service ${verb} ${base}@<${service.instances.called}>, for the ${service.instances.called} in ${base}/<${service.instances.called}>.json beside config.json`
295
272
  })
296
273
  }
297
- if (instance !== null && !INSTANCE.test(instance)) {
298
- throw new SporeError(`"${instance}" cannot be a ${service.instances.called}'s name`, { type: 'SERVICE_UNKNOWN', detail: 'letters, digits, ., - and _' })
274
+ if (instance !== null && !NAMES.bot.pattern.test(instance)) {
275
+ throw new SporeError(`"${instance}" cannot be a ${service.instances.called}'s name`, { type: 'SERVICE_UNKNOWN', detail: NAMES.bot.says })
299
276
  }
300
277
  return { base, instance, service }
301
278
  }
@@ -317,15 +294,11 @@ const procCmdline = (pid) => {
317
294
  }
318
295
  }
319
296
 
320
- /**
321
- * `run(command, args)` answers `{ status, stdout, stderr }`; it is injected so the verbs can
322
- * be exercised without a user bus.
323
- */
324
- export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf = procCmdline, node = process.execPath, root = ROOT, user = userInfo().username, uid = process.getuid(), keys = SSH_KEYS_DIR, stateDir = SERVICE_STATE_DIR, configDir = CONFIG_DIR, roots = pluginRoots() } = {}) {
297
+ export function createServices ({ roots = pluginRoots() } = {}) {
325
298
  const { services: catalog, problems } = catalogOf(roots)
326
299
  const parse = (name, options) => parsed(name, catalog, options)
327
300
  const systemctl = (...args) => {
328
- const ran = run('systemctl', ['--user', ...args])
301
+ const ran = systemRun('systemctl', ['--user', ...args])
329
302
  if (ran.status !== 0) {
330
303
  throw new SporeError(`systemctl --user ${args.join(' ')} failed`, {
331
304
  type: 'SERVICE_COMMAND_FAILED',
@@ -336,7 +309,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
336
309
  }
337
310
 
338
311
  const requireSystemd = () => {
339
- const ran = run('systemctl', ['--user', 'show-environment'])
312
+ const ran = systemRun('systemctl', ['--user', 'show-environment'])
340
313
  if (ran.status !== 0) {
341
314
  throw new SporeError('no systemd user session to run services in', {
342
315
  type: 'SERVICE_NO_SYSTEMD',
@@ -345,21 +318,15 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
345
318
  }
346
319
  }
347
320
 
348
- const pathOf = (file) => join(unitDir, file)
349
- const unitsOf = (service) => service.units({ node, root, keys })
321
+ const pathOf = (file) => join(UNIT_DIR, file)
322
+ const unitsOf = (service) => service.units(INSTALL)
350
323
  const ours = (base, file) => {
351
324
  const path = pathOf(file)
352
325
  return existsSync(path) && readFileSync(path, 'utf8').split('\n').includes(`${MARKER}=${base}`)
353
326
  }
354
327
  const written = ({ base, service }) => Object.keys(unitsOf(service)).every(file => ours(base, file))
355
328
 
356
- const instanceFile = ({ service, instance }) => join(configDir, service.instances.dir, `${instance}${service.instances.ext}`)
357
- const instancesOf = (service) => {
358
- const dir = join(configDir, service.instances.dir)
359
- if (!existsSync(dir)) return []
360
- return readdirSync(dir).filter(file => file.endsWith(service.instances.ext)).map(file => file.slice(0, -service.instances.ext.length)).sort()
361
- }
362
- const defined = (one) => written(one) && (one.instance === null || existsSync(instanceFile(one)))
329
+ const defined = (one) => written(one) && (one.instance === null || existsSync(instanceFile(one.base, one.instance)))
363
330
 
364
331
  const foreign = ({ base, service }) => Object.keys(unitsOf(service))
365
332
  .find(file => existsSync(pathOf(file)) && !ours(base, file)) ?? null
@@ -379,8 +346,8 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
379
346
  if (!defined(one)) {
380
347
  throw new SporeError(`${name} is not defined`, {
381
348
  type: 'SERVICE_NOT_DEFINED',
382
- detail: one.instance !== null && !existsSync(instanceFile(one))
383
- ? `there is no ${instanceFile(one)}`
349
+ detail: one.instance !== null && !existsSync(instanceFile(one.base, one.instance))
350
+ ? `there is no ${instanceFile(one.base, one.instance)}`
384
351
  : `spore service define ${name} writes its unit`
385
352
  })
386
353
  }
@@ -398,7 +365,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
398
365
 
399
366
  // A process started before its unit was last written runs what the unit used to name.
400
367
  const unitChanged = (one, pid) => {
401
- const argv = pid && cmdlineOf(pid)
368
+ const argv = pid && procCmdline(pid)
402
369
  return Boolean(argv) && !execPaths(one).every(path => argv.includes(path))
403
370
  }
404
371
 
@@ -419,11 +386,11 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
419
386
  // one installed — of spore, of the plugin that offers it, or of the spore that plugin loads.
420
387
  // A service that recorded nothing, or a record left by an earlier process, says nothing either way.
421
388
  const outdated = (name, { service }, pid) => {
422
- const record = join(stateDir, `${name}.json`)
389
+ const record = join(SERVICE_STATE_DIR, `${name}.json`)
423
390
  if (!service.records || !pid || !existsSync(record)) return null
424
391
  const started = JSON.parse(readFileSync(record, 'utf8'))
425
392
  if (started.pid !== pid) return null
426
- const installed = service.plugin ? service.version : versionAt(root)
393
+ const installed = service.plugin ? service.version : versionAt(ROOT)
427
394
  if (started.version !== installed) return { from: service.package ?? 'spore', running: started.version, installed }
428
395
  if (!service.plugin || started.spore === undefined) return null
429
396
  const loads = versionAt(sporeOf(service.dir))
@@ -444,9 +411,9 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
444
411
  const rows = (base) => {
445
412
  const service = serviceOf(base, catalog)
446
413
  if (!service.instances) return [row(base)]
447
- const names = instancesOf(service)
414
+ const names = instanceNames(base)
448
415
  if (!names.length) {
449
- return [{ name: base, what: service.what, defined: false, none: `no ${service.instances.called} yet — ${join(configDir, service.instances.dir)}/<${service.instances.called}>${service.instances.ext}, then spore service define ${base}@<${service.instances.called}>` }]
416
+ return [{ name: base, what: service.what, defined: false, none: `no ${service.instances.called} yet — ${instancesDir(base)}/<${service.instances.called}>.json, then spore service define ${base}@<${service.instances.called}>` }]
450
417
  }
451
418
  return names.map(instance => row(`${base}@${instance}`))
452
419
  }
@@ -455,7 +422,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
455
422
  list () {
456
423
  requireSystemd()
457
424
  return {
458
- linger: existsSync(join('/var/lib/systemd/linger', user)),
425
+ linger: existsSync(join('/var/lib/systemd/linger', userInfo().username)),
459
426
  services: Object.keys(catalog).flatMap(rows),
460
427
  problems
461
428
  }
@@ -467,7 +434,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
467
434
  const shown = row(name)
468
435
  if (!shown.defined) return shown
469
436
  const units = Object.keys(unitsOf(one.service)).map(pathOf)
470
- const log = run('journalctl', ['--user', '-u', unitOf('runs', one), '-n', '10', '--no-pager', '-o', 'short-iso']).stdout.trim()
437
+ const log = systemRun('journalctl', ['--user', '-u', unitOf('runs', one), '-n', '10', '--no-pager', '-o', 'short-iso']).stdout.trim()
471
438
  return { ...shown, units, log }
472
439
  },
473
440
 
@@ -477,8 +444,8 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
477
444
  requireSystemd()
478
445
  refuseForeign(one, name)
479
446
  if (service.check) {
480
- const [command, args] = service.check({ node, root, keys, instance })
481
- const checked = run(command, args)
447
+ const [command, args] = service.check({ ...INSTALL, instance })
448
+ const checked = systemRun(command, args)
482
449
  if (checked.status !== 0) {
483
450
  throw new SporeError(`${name} would not start`, {
484
451
  type: 'SERVICE_NOT_READY',
@@ -486,14 +453,14 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
486
453
  })
487
454
  }
488
455
  }
489
- mkdirSync(unitDir, { recursive: true })
456
+ mkdirSync(UNIT_DIR, { recursive: true })
490
457
  const units = []
491
- for (const [file, text] of Object.entries(renderUnits(one.base, { node, root, keys, roots }))) {
458
+ for (const [file, text] of Object.entries(renderUnits(one.base, { roots }))) {
492
459
  writeFileSync(pathOf(file), text)
493
460
  units.push(pathOf(file))
494
461
  }
495
462
  systemctl('daemon-reload')
496
- return { name, units, next: service.next ? service.next({ uid }) : null }
463
+ return { name, units, next: service.next ? service.next({ uid: process.getuid() }) : null }
497
464
  },
498
465
 
499
466
  act (verb, name) {
@@ -529,7 +496,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
529
496
  throw new SporeError(`${name} is not defined`, { type: 'SERVICE_NOT_DEFINED', detail: `spore service define ${name}${service.instances ? `@<${service.instances.called}>` : ''} writes its unit` })
530
497
  }
531
498
  }
532
- const instances = instance !== null ? [instance] : service.instances ? instancesOf(service) : [null]
499
+ const instances = instance !== null ? [instance] : service.instances ? instanceNames(one.base) : [null]
533
500
  const running = instances.filter(each => !['inactive', 'failed'].includes(stateOf(unitOf('primary', { service, instance: each })).active))
534
501
  if (running.length && !yes) {
535
502
  const named = running.map(each => (each === null ? one.base : `${one.base}@${each}`))
@@ -560,7 +527,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
560
527
  /** The last `lines` journal lines of a service matching `grep`, a PCRE2 pattern. */
561
528
  journal (name, { grep, lines }) {
562
529
  const unit = this.log(name)
563
- const ran = run('journalctl', ['--user', '-u', unit, '--grep', grep, '-n', String(lines), '--no-pager', '-o', 'short-iso'])
530
+ const ran = systemRun('journalctl', ['--user', '-u', unit, '--grep', grep, '-n', String(lines), '--no-pager', '-o', 'short-iso'])
564
531
  const printed = ran.stdout.trim()
565
532
  if (printed === '-- No entries --') return ''
566
533
  if (ran.status !== 0) {
package/src/setup.js CHANGED
@@ -9,7 +9,7 @@ import { createInterface } from 'node:readline/promises'
9
9
 
10
10
  import {
11
11
  checkSqlite, CONFIG_FILE, defaultModel, define, doctor, list, loadMohdelEnvironment, MO,
12
- modelReadiness, modelsOf, providerReadiness, readConfig, setDefaultModel, setKey, settings
12
+ modelReadiness, modelsOf, providerReadiness, readConfig, setDefaultModel, setKey
13
13
  } from '@rhizogrip/spore'
14
14
 
15
15
  import { createServices } from './services.js'
@@ -31,7 +31,8 @@ const SHOWN = 20
31
31
  * A pick from a numbered list on the plain terminal, so setup runs where the screen is not installed:
32
32
  * a number picks, words narrow the list, empty leaves it. The value picked, or null when left.
33
33
  */
34
- export async function pickFromList ({ title, header = [], items }, { prompt = ask, say = console.log } = {}) {
34
+ export async function pickFromList ({ title, header = [], items }) {
35
+ const say = console.log
35
36
  say('')
36
37
  say(title)
37
38
  for (const line of header) say(` ${line}`)
@@ -40,7 +41,7 @@ export async function pickFromList ({ title, header = [], items }, { prompt = as
40
41
  const width = String(Math.min(shown.length, SHOWN)).length
41
42
  shown.slice(0, SHOWN).forEach((item, i) => say(` ${String(i + 1).padStart(width)} ${item.label}${item.description ? ` — ${item.description}` : ''}`))
42
43
  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
+ const answer = await ask('a number, or words to narrow the list — empty to leave:')
44
45
  if (!answer) return null
45
46
  if (/^\d+$/.test(answer)) {
46
47
  const chosen = shown.slice(0, SHOWN)[Number(answer) - 1]
@@ -67,33 +68,23 @@ export async function ask (question, preset = '') {
67
68
 
68
69
  export const onboardWithMo = (provider) => spawnSync(process.execPath, [MO, 'onboard', ...(provider ? [provider] : [])], { stdio: 'inherit' }).status
69
70
 
70
- const readings = { loadKeys: loadMohdelEnvironment, modelReadiness, modelsOf, providerReadiness }
71
-
72
71
  const billingText = ({ billing, priced }) => billing === 'plan'
73
72
  ? 'your plan — not metered'
74
- : priced === false ? 'no prices: its calls count as $0 against cost and spend limits' : billing
73
+ : priced === false ? 'no prices: its calls count as $0 against cost' : billing
75
74
 
76
75
  /**
77
76
  * Resolves with the exit code: 0 once every step is done, 1 when one stops, saying what to do
78
77
  * before running it again.
79
78
  */
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]`))
79
+ export async function setup () {
80
+ const say = console.log
81
+ const services = createServices()
82
+ const yes = async (question) => /^y(es)?$/i.test(await ask(`${question} [y/N]`))
92
83
  const line = (label, text) => say(`${label.padEnd(10)}${text}`)
93
84
 
94
- line('node', `${process.version}, SQLite ${sqlite()}`)
85
+ line('node', `${process.version}, SQLite ${checkSqlite()}`)
95
86
 
96
- const found = examine().findings
87
+ const found = doctor().findings
97
88
  const config = found.find(one => one.subject === CONFIG_FILE && one.severity === 'problem')
98
89
  if (config) {
99
90
  line('config', `${config.problem} — ${config.fix}`)
@@ -124,27 +115,18 @@ export async function setup ({
124
115
  if (home) {
125
116
  line('home', home)
126
117
  } else {
127
- const dir = await prompt('where should your spores live?', '~/.spore')
118
+ const dir = await ask('where should your spores live?', '~/.spore')
128
119
  setKey('home', dir)
129
120
  line('home', `${readConfig().home} — spore config set home <dir> moves where new ones are made`)
130
121
  }
131
122
 
132
- const model = await chooseModel({ line, say, pick, onboard, mohdel })
123
+ const model = await chooseModel({ line, say })
133
124
  if (model === null) return 1
134
125
 
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
126
  await tickTimer({ line, yes, services })
145
127
 
146
128
  say('')
147
- const diagnosed = await report({ services })
129
+ const diagnosed = await diagnose({ services })
148
130
  if (diagnosed.findings.length) renderDoctor(diagnosed)
149
131
  else line('checked', 'this machine, your config and your spores — nothing to fix')
150
132
  say('')
@@ -181,16 +163,16 @@ function otherModels (say, provider) {
181
163
  }
182
164
 
183
165
  /** 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()
166
+ async function chooseModel ({ line, say }) {
167
+ loadMohdelEnvironment()
186
168
  const current = defaultModel().model
187
169
  if (current) {
188
- let ready = await mohdel.modelReadiness(current)
170
+ let ready = await modelReadiness(current)
189
171
  if (!ready.ready) {
190
172
  line('model', `${current} is not ready — mohdel sets it up`)
191
- onboard(providerOf(current))
192
- mohdel.loadKeys()
193
- ready = await mohdel.modelReadiness(current)
173
+ onboardWithMo(providerOf(current))
174
+ loadMohdelEnvironment()
175
+ ready = await modelReadiness(current)
194
176
  if (!ready.ready) {
195
177
  line('model', `${current} is still not ready — ${ready.fix}, then spore setup again`)
196
178
  return null
@@ -201,15 +183,15 @@ async function chooseModel ({ line, say, pick, onboard, mohdel }) {
201
183
  return current
202
184
  }
203
185
 
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 })
186
+ const provider = await pickFromList({ 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
187
  if (!provider) return null
206
188
  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)
189
+ onboardWithMo(null)
190
+ loadMohdelEnvironment()
191
+ } else if (!(await providerReadiness(provider)).ready) {
192
+ onboardWithMo(provider)
193
+ loadMohdelEnvironment()
194
+ const ready = await providerReadiness(provider)
213
195
  if (!ready.ready) {
214
196
  line('model', `${provider} is not ready — ${ready.fix}, then spore setup again`)
215
197
  return null
@@ -218,16 +200,16 @@ async function chooseModel ({ line, say, pick, onboard, mohdel }) {
218
200
 
219
201
  const credentials = new Map()
220
202
  const usable = []
221
- for (const one of await mohdel.modelsOf(provider === ANOTHER ? null : provider)) {
203
+ for (const one of await modelsOf(provider === ANOTHER ? null : provider)) {
222
204
  const named = providerOf(one.model)
223
- if (!credentials.has(named)) credentials.set(named, (await mohdel.providerReadiness(named)).credential)
205
+ if (!credentials.has(named)) credentials.set(named, (await providerReadiness(named)).credential)
224
206
  if (credentials.get(named)) usable.push(one)
225
207
  }
226
208
  if (!usable.length) {
227
209
  line('model', 'no provider has a model ready yet — mo onboard <provider>, then spore setup again')
228
210
  return null
229
211
  }
230
- const model = await pick({
212
+ const model = await pickFromList({
231
213
  title: 'the model new spores run on',
232
214
  header: ['spore model <name> <model> changes one spore\'s later'],
233
215
  items: usable.map(one => ({ value: one.model, label: one.model, description: billingText(one) }))
@@ -4,15 +4,14 @@
4
4
  * events arrive. Pure: records and events in, items out.
5
5
  */
6
6
 
7
+ import { asked, originLabel } from '@rhizogrip/spore'
8
+
7
9
  import { printable } from './printable.js'
8
10
 
9
- /** Who said an entry, when that is known: a person by name, or the schedule, webhook or job. */
11
+ /** Who said an entry, when that is known: a person by name, or what said it when no person did. */
10
12
  export function saidBy (entry) {
11
13
  if (entry.fromName) return printable(entry.fromName)
12
- if (entry.schedule) return `schedule "${entry.schedule}"`
13
- if (entry.hook) return `webhook "${entry.hook}"`
14
- if (entry.job) return `job "${entry.job}"`
15
- return null
14
+ return originLabel(entry)
16
15
  }
17
16
 
18
17
  export function originOf (entry) {
@@ -33,7 +32,7 @@ const said = (entry) => ({ kind: 'said', inboxNo: entry.inboxNo, origin: originO
33
32
  export function history ({ turns, inbox }) {
34
33
  const items = []
35
34
  for (const turn of turns) {
36
- for (const entry of inbox.filter(e => e.inboxNo > turn.inboxFrom && e.inboxNo <= turn.inboxTo && !e.setAside && !e.overheard)) items.push(said(entry))
35
+ for (const entry of asked(turn, inbox)) items.push(said(entry))
37
36
  if (turn.output) items.push({ kind: 'answer', text: printable(turn.output) })
38
37
  items.push({
39
38
  kind: 'end',
@@ -46,7 +45,7 @@ export function history ({ turns, inbox }) {
46
45
  durationMs: turn.startedAt && turn.endedAt ? Date.parse(turn.endedAt) - Date.parse(turn.startedAt) : null
47
46
  })
48
47
  }
49
- for (const entry of inbox.filter(e => !e.consumed && !e.setAside && !e.overheard)) items.push({ ...said(entry), waiting: true })
48
+ for (const entry of inbox.filter(e => !e.consumed && e.asks)) items.push({ ...said(entry), waiting: true })
50
49
  return items
51
50
  }
52
51
 
package/tui/here.js CHANGED
@@ -2,7 +2,7 @@ import { spawnSync } from 'node:child_process'
2
2
  import { realpathSync, statSync } from 'node:fs'
3
3
  import { basename, resolve } from 'node:path'
4
4
 
5
- import { defaultModel, define, hereSnapshots, isWorkspace, readConfig, SporeError, sporangia, workspaceFor } from '@rhizogrip/spore'
5
+ import { defaultModel, define, isWorkspace, SporeError, sporangia, workspaceFor } from '@rhizogrip/spore'
6
6
 
7
7
  import { changesSince, diffArgs, gitStateText, pruneSnapshots, snapshot, sporeNameFor, undoTo, workTreeOf } from '../src/here.js'
8
8
  import { choose, runTui } from './index.js'
@@ -12,7 +12,7 @@ const WHAT = { M: 'restore', D: 'bring back', A: 'remove' }
12
12
  function gitCommands (dir, spore) {
13
13
  const session = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+/, '')
14
14
  const since = snapshot(dir, { spore, session })
15
- pruneSnapshots(dir, { spore, keep: hereSnapshots(readConfig()) })
15
+ pruneSnapshots(dir, { spore })
16
16
  return [
17
17
  {
18
18
  name: 'diff',
package/tui/index.js CHANGED
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
4
4
  import { basename, dirname, join } from 'node:path'
5
5
 
6
6
  import { CombinedAutocompleteProvider, Input, isKeyRelease, Markdown, matchesKey, ProcessTerminal, ScrollView, SelectList, truncateToWidth, TuiAltScreen, visibleWidth, VStack, wrapTextWithAnsi } from '@earendil-works/pi-tui'
7
- import { applyEvent, changeText, createLive, curate, durationText, extendTurn, grantOf, list, liveIn, loadMohdelEnvironment, outbox, pause, paused, readInbox, readTurns, RUNNING, send, SERVICE_STATE_DIR, show, sporePaths, stateOf, stop, switchModel, unpause, upstream, watchAll, wrapTurn } from '@rhizogrip/spore'
7
+ import { applyEvent, changeText, createLive, curate, durationText, errorText, extendTurn, grantOf, list, liveIn, loadMohdelEnvironment, outbox, pause, paused, readInbox, readTurns, RUNNING, send, SERVICE_STATE_DIR, show, sporePaths, stateOf, stop, switchModel, unpause, upstream, watchAll, wrapTurn } from '@rhizogrip/spore'
8
8
  import chalk from 'chalk'
9
9
 
10
10
  import { runningJob, scheduleLine } from '../src/dispatch.js'
@@ -421,7 +421,7 @@ export async function runTui ({ ws, commands = [], renderTool = null, greeting =
421
421
  try {
422
422
  sent = send(state.ws, text, { replyTo: 'terminal' })
423
423
  } catch (err) {
424
- return notice(err.detail ? `${err.message} — ${err.detail}` : err.message)
424
+ return notice(errorText(err))
425
425
  }
426
426
  editor.addToHistory(text)
427
427
  notice(sent.started ? 'started a turn' : 'heard — the running turn reads it next')
@@ -435,7 +435,7 @@ export async function runTui ({ ws, commands = [], renderTool = null, greeting =
435
435
  state.limits = show({ ws: state.ws }).turnLimits
436
436
  refresh()
437
437
  } catch (err) {
438
- notice(err.detail ? `${err.message} — ${err.detail}` : err.message)
438
+ notice(errorText(err))
439
439
  }
440
440
  }
441
441
 
@@ -453,7 +453,7 @@ export async function runTui ({ ws, commands = [], renderTool = null, greeting =
453
453
  notice(switched.was === switched.model ? `already runs on ${switched.model}` : `runs on ${switched.model} from the next turn`)
454
454
  refresh()
455
455
  } catch (err) {
456
- notice(err.detail ? `${err.message} — ${err.detail}` : err.message)
456
+ notice(errorText(err))
457
457
  }
458
458
  }
459
459
  if (args.length) return switchTo(args[0])