@rhizogrip/spore-cli 1.36.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
@@ -16,6 +16,7 @@ import minimist from 'minimist'
16
16
 
17
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`
@@ -254,7 +253,7 @@ 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 {
@@ -370,7 +369,7 @@ 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
374
  fail(errorText(err))
376
375
  }
@@ -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))
@@ -434,7 +432,7 @@ 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
437
  fail(errorText(err))
440
438
  }
@@ -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.36.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.36.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,7 +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 { addTo, allowPlugin, annotate, billingFor, bytesText, changeText, define, defaultModel, disallowPlugin, durationText, edit, extend, getKey, jobs, list, listApprovals, listPlugins, log, pause, precursors, 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'
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'
17
17
  import { diagnose, renderDoctor } from './doctor.js'
18
18
  import { hook } from './hooks.js'
19
19
  import { createServices } from './services.js'
@@ -47,8 +47,6 @@ function renderList (result) {
47
47
  }
48
48
  for (const skip of result.missing) console.error(`spore: skipped ${skip.path} — ${skip.why}`)
49
49
  if (result.paused) console.log(`your spores are ${pausedText(result.paused)} — no turn starts until spore unpause\n`)
50
- const limited = spendText(result.spend)
51
- if (limited) console.log(`your spores have spent ${limited}\n`)
52
50
  if (!result.contain) console.log('turns are not contained (contain off): each sees every other spore\'s processes\n')
53
51
 
54
52
  const home = result.workspaces.filter(row => row.from === result.home)
@@ -66,17 +64,6 @@ function renderList (result) {
66
64
 
67
65
  const listExit = (result) => (result.configured ? 0 : 2)
68
66
 
69
- /** `today $4.12 of $20.00 · October $81.30 of $300.00`, the windows a limit is set on; null with none. */
70
- const spendText = ({ date, day, month, limits }) => {
71
- const of = (spent, limit) => `$${spent.toFixed(2)} of $${limit.toFixed(2)}${spent >= limit ? ' — reached, no turn starts' : ''}`
72
- const monthName = new Date(`${date}T00:00:00Z`).toLocaleDateString('en-US', { month: 'long', timeZone: 'UTC' })
73
- const parts = [
74
- limits.day === null ? null : `today ${of(day, limits.day)}`,
75
- limits.month === null ? null : `${monthName} ${of(month, limits.month)}`
76
- ].filter(Boolean)
77
- return parts.length ? parts.join(' · ') : null
78
- }
79
-
80
67
  function renderModels ({ model, models }) {
81
68
  console.log(`runs on ${model}`)
82
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')
@@ -115,7 +102,7 @@ const modelLine = (model, billing) => `${model}${billing === null ? ' (a provid
115
102
  export function renderHeader (ws, grant) {
116
103
  console.error([
117
104
  `spore ${ws}`,
118
- ` ${modelLine(grant.model, grant.billing)} · tools: ${grant.tools.join(', ')}`,
105
+ ` ${modelLine(grant.model, grant.billing)} · tools: ${grant.tools.join(', ')}${grant.unconfined ? ' · unconfined' : ''}`,
119
106
  ` limits: ${bounds(grant.limits, grant.billing)} (soft wraps, hard stops)`
120
107
  ].join('\n'))
121
108
  }
@@ -131,6 +118,7 @@ function renderShow (result) {
131
118
  if (result.models.length) line('or', result.models.join(', '))
132
119
  if (result.cellModels.length) line('cell models', result.cellModels.map(named => `${named.name}=${named.model}`).join(', '))
133
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')
134
122
  line('limits', bounds(result.limits, result.billing))
135
123
  if (result.turnLimits) for (const [i, one] of runningLines(result.turnLimits, result.extend).entries()) line(i ? '' : 'this turn', one)
136
124
  if (result.sources?.length) {
@@ -429,11 +417,7 @@ async function service (argv, emit) {
429
417
  return emit(services.remove(name, { yes: argv.yes }), (r) => { for (const unit of r.units) console.log(`removed ${unit}`) })
430
418
  }
431
419
  if (sub === 'log') {
432
- const lines = argv.n ?? argv.lines ?? '50'
433
- if (!/^\d+$/.test(lines)) {
434
- console.error(`spore: -n ${lines} is not a number of lines`)
435
- return 2
436
- }
420
+ const lines = argv.n ?? '50'
437
421
  const unit = services.log(name)
438
422
  return spawnSync('journalctl', ['--user', '-u', unit, '-n', lines, '--no-pager', '-o', 'short-iso', ...(argv.f ? ['-f'] : [])], { stdio: 'inherit' }).status ?? 1
439
423
  }
@@ -572,8 +556,6 @@ function renderUsage (result, by) {
572
556
  unsettled.turns ? `${plural(unsettled.turns, 'turn')} unsettled, not summed` : null
573
557
  ].filter(Boolean)
574
558
  console.log([result.ws ? basename(result.ws) : 'every spore', `${window.since} – ${window.until} ${window.tz}`, dollars(totals.micros), ...notes].join(' · '))
575
- const limited = result.spend ? spendText(result.spend) : null
576
- if (limited) console.log(`your spores have spent ${limited}`)
577
559
  if (!totals.turns && !totals.cells) {
578
560
  console.log('\nnothing ran in this window')
579
561
  return
@@ -770,17 +752,6 @@ export async function manage (verb, argv) {
770
752
  }
771
753
  if (verb === 'ls') return emit(list({ where: argv._[1], disk: true }), renderList, listExit)
772
754
  if (verb === 'show') return emit(show({ ws: argv._[1] }), renderShow)
773
- if (verb === 'precursor') {
774
- const sub = argv._[1]
775
- if (sub && sub !== 'ls') {
776
- console.error(`spore: precursor has no "${sub}" — only ls`)
777
- return 2
778
- }
779
- return emit(precursors({ ws: argv._[2] }), (result) => {
780
- for (const name of result.precursors) console.log(name)
781
- if (!result.precursors.length) console.log('none — this workspace delegates to nothing')
782
- })
783
- }
784
755
  } catch (err) {
785
756
  console.error(`spore: ${errorText(err)}`)
786
757
  return 2
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/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, NAMES, 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`))
@@ -55,6 +55,8 @@ const nodeUnit = ({ description, marker, node, program, args = '' }) => [
55
55
  * or taking it out, then restarting the service.
56
56
  */
57
57
  export const SSH_KEYS_DIR = join(CONFIG_DIR, 'ssh')
58
+
59
+ const INSTALL = { node: process.execPath, root: ROOT, keys: SSH_KEYS_DIR }
58
60
  export const SSH_AGENT_SOCKET = 'spore-ssh-agent.socket'
59
61
 
60
62
  const sshKeysCheck = (keys) => [
@@ -86,7 +88,7 @@ const sluiceCheck = (binary, rules) => [
86
88
  * service's own start-up checks and exits, so one that cannot start is refused before its unit
87
89
  * is written.
88
90
  *
89
- * 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
90
92
  * `<name>@<instance>`: one template unit, and an instance of it per file, each started, enabled and
91
93
  * logged on its own.
92
94
  */
@@ -234,9 +236,9 @@ function catalogOf (roots) {
234
236
  }
235
237
 
236
238
  /** The unit files of a service, as they are written. */
237
- export function renderUnits (name, { node = process.execPath, root = ROOT, keys = SSH_KEYS_DIR, roots = pluginRoots() } = {}) {
239
+ export function renderUnits (name, { roots = pluginRoots() } = {}) {
238
240
  const { base, service } = parsed(name, catalogOf(roots).services, { instanceOptional: true, verb: 'define' })
239
- return Object.fromEntries(Object.entries(service.units({ node, root, keys }))
241
+ return Object.fromEntries(Object.entries(service.units(INSTALL))
240
242
  .map(([file, lines]) => [file, `# Written by \`spore service define ${base}\`. Change it with that command, not by hand.\n${lines.join('\n')}\n`]))
241
243
  }
242
244
 
@@ -266,7 +268,7 @@ function parsed (name, catalog, { instanceOptional = false, verb } = {}) {
266
268
  if (service.instances && instance === null && !instanceOptional) {
267
269
  throw new SporeError(`${base} runs once per ${service.instances.called}: name one`, {
268
270
  type: 'SERVICE_NEEDS_INSTANCE',
269
- 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`
270
272
  })
271
273
  }
272
274
  if (instance !== null && !NAMES.bot.pattern.test(instance)) {
@@ -292,15 +294,11 @@ const procCmdline = (pid) => {
292
294
  }
293
295
  }
294
296
 
295
- /**
296
- * `run(command, args)` answers `{ status, stdout, stderr }`; it is injected so the verbs can
297
- * be exercised without a user bus.
298
- */
299
- 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() } = {}) {
300
298
  const { services: catalog, problems } = catalogOf(roots)
301
299
  const parse = (name, options) => parsed(name, catalog, options)
302
300
  const systemctl = (...args) => {
303
- const ran = run('systemctl', ['--user', ...args])
301
+ const ran = systemRun('systemctl', ['--user', ...args])
304
302
  if (ran.status !== 0) {
305
303
  throw new SporeError(`systemctl --user ${args.join(' ')} failed`, {
306
304
  type: 'SERVICE_COMMAND_FAILED',
@@ -311,7 +309,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
311
309
  }
312
310
 
313
311
  const requireSystemd = () => {
314
- const ran = run('systemctl', ['--user', 'show-environment'])
312
+ const ran = systemRun('systemctl', ['--user', 'show-environment'])
315
313
  if (ran.status !== 0) {
316
314
  throw new SporeError('no systemd user session to run services in', {
317
315
  type: 'SERVICE_NO_SYSTEMD',
@@ -320,21 +318,15 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
320
318
  }
321
319
  }
322
320
 
323
- const pathOf = (file) => join(unitDir, file)
324
- const unitsOf = (service) => service.units({ node, root, keys })
321
+ const pathOf = (file) => join(UNIT_DIR, file)
322
+ const unitsOf = (service) => service.units(INSTALL)
325
323
  const ours = (base, file) => {
326
324
  const path = pathOf(file)
327
325
  return existsSync(path) && readFileSync(path, 'utf8').split('\n').includes(`${MARKER}=${base}`)
328
326
  }
329
327
  const written = ({ base, service }) => Object.keys(unitsOf(service)).every(file => ours(base, file))
330
328
 
331
- const instanceFile = ({ service, instance }) => join(configDir, service.instances.dir, `${instance}${service.instances.ext}`)
332
- const instancesOf = (service) => {
333
- const dir = join(configDir, service.instances.dir)
334
- if (!existsSync(dir)) return []
335
- return readdirSync(dir).filter(file => file.endsWith(service.instances.ext)).map(file => file.slice(0, -service.instances.ext.length)).sort()
336
- }
337
- 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)))
338
330
 
339
331
  const foreign = ({ base, service }) => Object.keys(unitsOf(service))
340
332
  .find(file => existsSync(pathOf(file)) && !ours(base, file)) ?? null
@@ -354,8 +346,8 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
354
346
  if (!defined(one)) {
355
347
  throw new SporeError(`${name} is not defined`, {
356
348
  type: 'SERVICE_NOT_DEFINED',
357
- detail: one.instance !== null && !existsSync(instanceFile(one))
358
- ? `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)}`
359
351
  : `spore service define ${name} writes its unit`
360
352
  })
361
353
  }
@@ -373,7 +365,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
373
365
 
374
366
  // A process started before its unit was last written runs what the unit used to name.
375
367
  const unitChanged = (one, pid) => {
376
- const argv = pid && cmdlineOf(pid)
368
+ const argv = pid && procCmdline(pid)
377
369
  return Boolean(argv) && !execPaths(one).every(path => argv.includes(path))
378
370
  }
379
371
 
@@ -394,11 +386,11 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
394
386
  // one installed — of spore, of the plugin that offers it, or of the spore that plugin loads.
395
387
  // A service that recorded nothing, or a record left by an earlier process, says nothing either way.
396
388
  const outdated = (name, { service }, pid) => {
397
- const record = join(stateDir, `${name}.json`)
389
+ const record = join(SERVICE_STATE_DIR, `${name}.json`)
398
390
  if (!service.records || !pid || !existsSync(record)) return null
399
391
  const started = JSON.parse(readFileSync(record, 'utf8'))
400
392
  if (started.pid !== pid) return null
401
- const installed = service.plugin ? service.version : versionAt(root)
393
+ const installed = service.plugin ? service.version : versionAt(ROOT)
402
394
  if (started.version !== installed) return { from: service.package ?? 'spore', running: started.version, installed }
403
395
  if (!service.plugin || started.spore === undefined) return null
404
396
  const loads = versionAt(sporeOf(service.dir))
@@ -419,9 +411,9 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
419
411
  const rows = (base) => {
420
412
  const service = serviceOf(base, catalog)
421
413
  if (!service.instances) return [row(base)]
422
- const names = instancesOf(service)
414
+ const names = instanceNames(base)
423
415
  if (!names.length) {
424
- 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}>` }]
425
417
  }
426
418
  return names.map(instance => row(`${base}@${instance}`))
427
419
  }
@@ -430,7 +422,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
430
422
  list () {
431
423
  requireSystemd()
432
424
  return {
433
- linger: existsSync(join('/var/lib/systemd/linger', user)),
425
+ linger: existsSync(join('/var/lib/systemd/linger', userInfo().username)),
434
426
  services: Object.keys(catalog).flatMap(rows),
435
427
  problems
436
428
  }
@@ -442,7 +434,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
442
434
  const shown = row(name)
443
435
  if (!shown.defined) return shown
444
436
  const units = Object.keys(unitsOf(one.service)).map(pathOf)
445
- 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()
446
438
  return { ...shown, units, log }
447
439
  },
448
440
 
@@ -452,8 +444,8 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
452
444
  requireSystemd()
453
445
  refuseForeign(one, name)
454
446
  if (service.check) {
455
- const [command, args] = service.check({ node, root, keys, instance })
456
- const checked = run(command, args)
447
+ const [command, args] = service.check({ ...INSTALL, instance })
448
+ const checked = systemRun(command, args)
457
449
  if (checked.status !== 0) {
458
450
  throw new SporeError(`${name} would not start`, {
459
451
  type: 'SERVICE_NOT_READY',
@@ -461,14 +453,14 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
461
453
  })
462
454
  }
463
455
  }
464
- mkdirSync(unitDir, { recursive: true })
456
+ mkdirSync(UNIT_DIR, { recursive: true })
465
457
  const units = []
466
- 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 }))) {
467
459
  writeFileSync(pathOf(file), text)
468
460
  units.push(pathOf(file))
469
461
  }
470
462
  systemctl('daemon-reload')
471
- return { name, units, next: service.next ? service.next({ uid }) : null }
463
+ return { name, units, next: service.next ? service.next({ uid: process.getuid() }) : null }
472
464
  },
473
465
 
474
466
  act (verb, name) {
@@ -504,7 +496,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
504
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` })
505
497
  }
506
498
  }
507
- const instances = instance !== null ? [instance] : service.instances ? instancesOf(service) : [null]
499
+ const instances = instance !== null ? [instance] : service.instances ? instanceNames(one.base) : [null]
508
500
  const running = instances.filter(each => !['inactive', 'failed'].includes(stateOf(unitOf('primary', { service, instance: each })).active))
509
501
  if (running.length && !yes) {
510
502
  const named = running.map(each => (each === null ? one.base : `${one.base}@${each}`))
@@ -535,7 +527,7 @@ export function createServices ({ unitDir = UNIT_DIR, run = systemRun, cmdlineOf
535
527
  /** The last `lines` journal lines of a service matching `grep`, a PCRE2 pattern. */
536
528
  journal (name, { grep, lines }) {
537
529
  const unit = this.log(name)
538
- 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'])
539
531
  const printed = ran.stdout.trim()
540
532
  if (printed === '-- No entries --') return ''
541
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) }))
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',