@rhizogrip/spore-cli 1.56.0 → 1.57.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/spore.js CHANGED
@@ -36,6 +36,7 @@ const argv = minimist(process.argv.slice(2), {
36
36
 
37
37
  const VERBS = `Usage:
38
38
  spore setup the first run: this machine, your models, a first spore
39
+ spore setup model pick a recommended model for new spores, from any provider
39
40
  spore vm start|stop the Linux vm spore runs in, where spore setup made one
40
41
  spore define <name> say what a spore is; . for here
41
42
  spore define <name> --model <m> --plugin <p> the same, with its model and plugins filled in
@@ -187,7 +188,7 @@ const SHAPES = {
187
188
  hook: { bare: 'ls', subs: { ls: withJson(0), show: withJson(1) } },
188
189
  tui: { flags: [], most: 1 },
189
190
  here: { flags: ['sporangium', 'model', 'no-git'], most: 1 },
190
- setup: { flags: [], most: 0 },
191
+ setup: { flags: [], most: 1 },
191
192
  vm: { subs: { start: { flags: [], most: 0 }, stop: { flags: [], most: 0 } } }
192
193
  }
193
194
  const verb = argv._[0]
@@ -262,13 +263,14 @@ if (verb === 'tui') {
262
263
  }
263
264
 
264
265
  if (verb === 'setup') {
266
+ if (argv._[1] && argv._[1] !== 'model') fail(`setup takes model or nothing — not "${argv._[1]}"`)
265
267
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
266
268
  fail('setup asks questions, and this is not a terminal — the same steps are spore config set home <dir>, ' +
267
269
  'mo onboard <provider>, spore config set model <provider>/<name>, spore doctor')
268
270
  }
269
- const { setup } = await import('../src/setup.js')
271
+ const { setup, setupModel } = await import('../src/setup.js')
270
272
  try {
271
- process.exit(await setup())
273
+ process.exit(await (argv._[1] ? setupModel() : setup()))
272
274
  } catch (err) {
273
275
  if (!err.type) throw err
274
276
  fail(errorText(err))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rhizogrip/spore-cli",
3
- "version": "1.56.0",
3
+ "version": "1.57.1",
4
4
  "author": {
5
5
  "name": "Christophe Le Bars",
6
6
  "email": "clb@toort.net"
@@ -49,12 +49,12 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@clack/prompts": "^1.8.1",
52
- "@earendil-works/pi-tui": "1.2.0",
52
+ "@earendil-works/pi-tui": "1.5.0",
53
53
  "chalk": "^6.0.1",
54
54
  "minimist": "^1.2.8"
55
55
  },
56
56
  "optionalDependencies": {
57
- "@rhizogrip/spore": "1.56.0"
57
+ "@rhizogrip/spore": "1.57.1"
58
58
  },
59
59
  "license": "Apache-2.0"
60
60
  }
package/src/setup.js CHANGED
@@ -6,23 +6,24 @@
6
6
  import { spawnSync } from 'node:child_process'
7
7
  import { basename } from 'node:path'
8
8
 
9
- import { autocomplete, cancel, confirm, isCancel, log, note, outro, text } from '@clack/prompts'
9
+ import { autocomplete, cancel, confirm, intro, isCancel, log, note, outro, text } from '@clack/prompts'
10
10
 
11
11
  import {
12
- checkSqlite, CONFIG_FILE, defaultModel, define, doctor, list, loadMohdelEnvironment, MO,
13
- modelReadiness, modelsOf, providerReadiness, readConfig, setDefaultModel, setKey
12
+ addFromMohdex, checkSqlite, CONFIG_FILE, defaultModel, define, doctor, list, loadMohdelEnvironment,
13
+ MO, modelReadiness, modelsOf, mohdexEntries, mohdexRecommended, PROVIDER_INFO, providerReadiness,
14
+ readConfig, setDefaultModel, setKey, tagModel
14
15
  } from '@rhizogrip/spore'
15
16
 
16
17
  import { createServices } from './services.js'
17
18
  import { diagnose, renderDoctor } from './doctor.js'
18
19
 
19
- const ANOTHER = 'another'
20
+ const EXPERT = 'expert'
21
+ const ANOTHER_MODEL = 'another model'
20
22
 
21
- const PROVIDERS = [
22
- { value: 'chatgpt', label: 'ChatGPT', description: 'sign in to your ChatGPT plan — its calls are not metered' },
23
- { value: 'openrouter', label: 'OpenRouter', description: 'one key for many providers\' models, priced by mohdel' },
24
- { value: ANOTHER, label: 'another provider', description: 'mohdel\'s own setup, every provider it knows' }
25
- ]
23
+ const TAG = 'spore'
24
+
25
+ // The two tiers the page at mohdex.dev/spore judges on.
26
+ const BAR = ['tier:core', 'tier:identity']
26
27
 
27
28
  const providerOf = (model) => model.split('/')[0]
28
29
 
@@ -59,12 +60,31 @@ async function yes (message) {
59
60
  return answer
60
61
  }
61
62
 
62
- export const onboardWithMo = (provider) => spawnSync(process.execPath, [MO, 'onboard', ...(provider ? [provider] : []), '--caller', 'spore'], { stdio: 'inherit' }).status
63
+ export const onboardWithMo = (provider, { credentialOnly = false } = {}) => spawnSync(process.execPath, [
64
+ MO, 'onboard', provider, '--caller', 'spore', ...(credentialOnly ? ['--credential-only'] : [])
65
+ ], { stdio: 'inherit' }).status
66
+
67
+ const curateWithMo = (provider) => spawnSync(process.execPath, [MO, 'curate', provider], { stdio: 'inherit' }).status
68
+
69
+ const foundText = (provider, credential) => credential ? (provider === 'chatgpt' ? 'signed in' : 'key found') : null
63
70
 
64
71
  const billingText = ({ billing, priced }) => billing === 'plan'
65
72
  ? 'your plan — not metered'
66
73
  : priced === false ? 'no prices: its calls count as $0 against cost' : billing
67
74
 
75
+ /** A price is one number, or one per context size, `{ default: 1, '>272000': 2 }`. Infinity when there is none. */
76
+ const basePrice = (price) => (typeof price === 'object' ? price?.default : price) ?? Infinity
77
+
78
+ const hasPrices = (entry) => basePrice(entry?.inputPrice) !== Infinity && basePrice(entry?.outputPrice) !== Infinity
79
+
80
+ const tierText = (price) => {
81
+ const sizes = Object.keys(Object(price)).filter(key => key.startsWith('>')).map(key => Number(key.slice(1)))
82
+ return sizes.length ? `, more above ${Math.round(Math.min(...sizes) / 1000)}k` : ''
83
+ }
84
+
85
+ const priceText = ({ inputPrice, outputPrice }) =>
86
+ `$${basePrice(inputPrice).toFixed(2)} / $${basePrice(outputPrice).toFixed(2)} per M${tierText(inputPrice)}`
87
+
68
88
  /**
69
89
  * Resolves with the exit code: 0 once every step is done, 1 when one stops, saying what to do
70
90
  * before running it again.
@@ -142,6 +162,7 @@ export async function setup () {
142
162
  [`spore tui ${first}`, `talk to ${first} in a terminal screen`],
143
163
  [`spore send ${first} "…"`, 'or send it one message; the answer is printed'],
144
164
  ['cd <project> && spore here', 'a spore that works on that project\'s files — git undoes what it changes'],
165
+ ['spore setup model', 'another recommended model, from any provider'],
145
166
  ['spore', 'every command']
146
167
  ].map(([command, what]) => `${command.padEnd(30)}${what}`).join('\n'), 'next')
147
168
  outro('spore setup again checks all of this')
@@ -151,12 +172,38 @@ export async function setup () {
151
172
  /** Where another model comes from, and how a spore is given it: said, never done, by setup. */
152
173
  function otherModels (provider) {
153
174
  log.message([
154
- `another model: /curate in spore tui, or mo curate ${provider}, adds it to your catalog —`,
175
+ 'another model: spore setup model offers the recommended ones, from any provider —',
176
+ `or /curate in spore tui, or mo curate ${provider}, adds any other ${provider} model,`,
155
177
  'then spore config set model <provider>/<name> for new spores, or spore edit <spore> and add it to models:'
156
178
  ])
157
179
  }
158
180
 
159
- /** 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. */
181
+ /** One line when the model set is not among those mohdex recommends. Nothing here stops setup. */
182
+ async function sayWhenNotRecommended (current) {
183
+ let recommended
184
+ try {
185
+ recommended = await mohdexRecommended({ tool: 'spore', bar: BAR })
186
+ } catch (err) {
187
+ log.warn(`could not reach mohdex.dev, so setup can't say whether ${current} is recommended (${err.message})`)
188
+ return
189
+ }
190
+ const key = current.split(/[:@]/)[0]
191
+ if (recommended.length && !recommended.some(one => one.key === key)) {
192
+ line('model', `${current} is not among the models spore recommends — spore setup model offers them`)
193
+ }
194
+ }
195
+
196
+ async function settle (chosen) {
197
+ const { model, priced } = chosen
198
+ await tagModel(model, TAG)
199
+ setDefaultModel(model)
200
+ line('model', `${model}, ${priced === false ? `${billingText(chosen)} — mo model instructions ${providerOf(model)} fills them` : 'ready'}`)
201
+ log.message('new spores run on it')
202
+ otherModels(providerOf(model))
203
+ return model
204
+ }
205
+
206
+ /** The default model, ready to run: the one set, or one of the recommended models, or any model of any provider. Null stops setup. */
160
207
  async function chooseModel () {
161
208
  loadMohdelEnvironment()
162
209
  const current = defaultModel().model
@@ -173,48 +220,149 @@ async function chooseModel () {
173
220
  }
174
221
  }
175
222
  line('model', `${current}, ${ready.priced === false ? `${billingText(ready)} — ${ready.fix}` : 'ready'}`)
223
+ await sayWhenNotRecommended(current)
176
224
  otherModels(providerOf(current))
177
225
  return current
178
226
  }
227
+ return chooseRecommended()
228
+ }
229
+
230
+ /** One of the recommended models, whatever is set now: provider, credential, model. Null stops. */
231
+ async function chooseRecommended () {
232
+ let recommended
233
+ try {
234
+ recommended = await mohdexRecommended({ tool: 'spore', bar: BAR })
235
+ } catch (err) {
236
+ log.warn(`could not reach mohdex.dev, so setup can't say which models spore recommends (${err.message}) — every provider follows`)
237
+ return chooseAnyModel()
238
+ }
239
+ // The list is live and the mohdel spore pins is not, so mohdex can name a provider this mohdel does not know.
240
+ const keys = recommended.map(one => one.key).filter(key => PROVIDER_INFO[providerOf(key)])
241
+ if (!keys.length) {
242
+ log.warn('mohdex.dev recommends no model for spore right now — every provider follows')
243
+ return chooseAnyModel()
244
+ }
179
245
 
180
- const provider = await pickFromList({ title: 'which provider should they come from?', header: ['mohdel calls the models your spores run on — a provider set up here is set up for mo as well'], items: PROVIDERS })
246
+ const provider = await pickProvider(keys)
181
247
  if (!provider) return null
182
- if (provider === ANOTHER) {
183
- onboardWithMo(null)
184
- loadMohdelEnvironment()
185
- } else if (!(await providerReadiness(provider)).ready) {
186
- onboardWithMo(provider)
187
- loadMohdelEnvironment()
188
- const ready = await providerReadiness(provider)
189
- if (!ready.ready) {
190
- line('model', `${provider} is not ready — ${ready.fix}, then spore setup again`)
191
- return null
192
- }
248
+ if (provider === EXPERT) return chooseAnyModel()
249
+
250
+ if (onboardWithMo(provider, { credentialOnly: true }) !== 0) {
251
+ line('model', `${provider} has no working credential — mo onboard ${provider}, then spore setup again`)
252
+ return null
193
253
  }
254
+ loadMohdelEnvironment()
194
255
 
195
- const credentials = new Map()
196
- const usable = []
197
- for (const one of await modelsOf(provider === ANOTHER ? null : provider)) {
198
- const named = providerOf(one.model)
199
- if (!credentials.has(named)) credentials.set(named, (await providerReadiness(named)).credential)
200
- if (credentials.get(named)) usable.push(one)
256
+ let entries
257
+ try {
258
+ entries = await mohdexEntries(provider)
259
+ } catch (err) {
260
+ log.warn(`could not reach mohdex.dev, so setup can't say what ${provider}'s models cost (${err.message}) — every provider follows`)
261
+ return chooseAnyModel()
201
262
  }
202
- if (!usable.length) {
203
- line('model', 'no provider has a model ready yet — mo onboard <provider>, then spore setup again')
204
- return null
263
+ const offers = await offersOf(keys.filter(key => providerOf(key) === provider), entries, provider)
264
+ if (!offers.length) {
265
+ log.warn(`mohdex.dev has no entry for ${provider}'s recommended models — every provider follows`)
266
+ return chooseAnyModel()
205
267
  }
206
268
  const model = await pickFromList({
207
- title: 'the model new spores run on',
269
+ title: 'which model should new spores run on?',
208
270
  header: ['later, spore model <name> <model> changes the model of one spore'],
209
- items: usable.map(one => ({ value: one.model, label: one.model, description: billingText(one) }))
271
+ items: offers.map(one => ({ value: one.model, label: one.model, description: one.description }))
210
272
  })
211
273
  if (!model) return null
212
- const chosen = usable.find(one => one.model === model)
213
- setDefaultModel(model)
214
- line('model', `${model}, ${chosen.priced === false ? `${billingText(chosen)} — mo model instructions ${providerOf(model)} fills them` : 'ready'}`)
215
- log.message('new spores run on it')
216
- otherModels(providerOf(model))
217
- return model
274
+ const chosen = offers.find(one => one.model === model)
275
+ if (!chosen.inCatalog) {
276
+ try {
277
+ await addFromMohdex([{ key: model, entry: entries[model] }])
278
+ } catch (err) {
279
+ log.warn(`${model} could not go in the catalog: ${err.message} — every provider follows`)
280
+ return chooseAnyModel()
281
+ }
282
+ }
283
+ return settle(chosen)
284
+ }
285
+
286
+ /** The providers of the recommended models, ChatGPT first, the rest by label, then the way to any model. */
287
+ async function pickProvider (keys) {
288
+ const items = []
289
+ for (const provider of new Set(keys.map(providerOf))) {
290
+ const count = keys.filter(key => providerOf(key) === provider).length
291
+ const { credential } = await providerReadiness(provider)
292
+ const found = foundText(provider, credential)
293
+ items.push({ value: provider, label: PROVIDER_INFO[provider].label, description: `${count} ${count === 1 ? 'model' : 'models'} recommended${found ? `, ${found}` : ''}` })
294
+ }
295
+ items.sort((a, b) => (b.value === 'chatgpt') - (a.value === 'chatgpt') || a.label.localeCompare(b.label))
296
+ return pickFromList({
297
+ title: 'which provider should they come from?',
298
+ header: ['mohdel calls the models your spores run on — a provider set up here is set up for mo as well'],
299
+ items: [...items, { value: EXPERT, label: EXPERT, description: 'any model, any provider' }]
300
+ })
301
+ }
302
+
303
+ /** The recommended models this setup can offer, cheapest first: each has a mohdex entry to add, or is in the catalog already. */
304
+ async function offersOf (keys, entries, provider) {
305
+ const held = new Map((await modelsOf(provider)).map(one => [one.model, one]))
306
+ const offers = []
307
+ for (const key of keys.filter(one => entries[one] || held.has(one))) {
308
+ const entry = entries[key]
309
+ const { billing } = await modelReadiness(key)
310
+ const inCatalog = held.has(key)
311
+ const priced = billing === 'plan' ? null : inCatalog ? held.get(key).priced : hasPrices(entry)
312
+ const description = billing !== 'plan' && hasPrices(entry) ? priceText(entry) : billingText({ billing, priced })
313
+ offers.push({ model: key, billing, priced, inCatalog, entry, description })
314
+ }
315
+ const price = (one, field) => basePrice(one.entry?.[field])
316
+ return offers.sort((a, b) => price(a, 'inputPrice') - price(b, 'inputPrice') || price(a, 'outputPrice') - price(b, 'outputPrice'))
317
+ }
318
+
319
+ /** Expert: any provider mohdel knows, its full setup, then its text models and the way to one the catalog lacks. */
320
+ async function chooseAnyModel () {
321
+ const items = []
322
+ for (const [provider, { label, description }] of Object.entries(PROVIDER_INFO)) {
323
+ const { credential } = await providerReadiness(provider)
324
+ items.push({ value: provider, label, description: foundText(provider, credential) ?? description })
325
+ }
326
+ const provider = await pickFromList({
327
+ title: 'which provider should they come from?',
328
+ items: items.sort((a, b) => a.label.localeCompare(b.label))
329
+ })
330
+ if (!provider) return null
331
+
332
+ onboardWithMo(provider)
333
+ loadMohdelEnvironment()
334
+ const { credential, fix } = await providerReadiness(provider)
335
+ if (!credential) {
336
+ line('model', `${provider} is not ready — ${fix}, then spore setup again`)
337
+ return null
338
+ }
339
+
340
+ const chosenBefore = (one) => one.tags.includes(TAG)
341
+ while (true) {
342
+ const models = (await modelsOf(provider))
343
+ .filter(one => one.type === 'model')
344
+ .sort((a, b) => chosenBefore(b) - chosenBefore(a))
345
+ const model = await pickFromList({
346
+ title: 'which model should new spores run on?',
347
+ header: ['later, spore model <name> <model> changes the model of one spore'],
348
+ items: [
349
+ ...models.map(one => ({ value: one.model, label: one.model, description: `${billingText(one)}${chosenBefore(one) ? ', chosen before' : ''}` })),
350
+ { value: ANOTHER_MODEL, label: `another ${provider} model`, description: `mo curate ${provider} adds it to your catalog` }
351
+ ]
352
+ })
353
+ if (!model) return null
354
+ if (model !== ANOTHER_MODEL) return settle(models.find(one => one.model === model))
355
+ curateWithMo(provider)
356
+ }
357
+ }
358
+
359
+ /** `spore setup model`: resolves with the exit code, 0 once a recommended model is the default. */
360
+ export async function setupModel () {
361
+ intro('spore setup model')
362
+ loadMohdelEnvironment()
363
+ if (await chooseRecommended() === null) return 1
364
+ outro('spores you already have keep their model — spore model <name> <model> moves one')
365
+ return 0
218
366
  }
219
367
 
220
368
  async function tickTimer ({ services }) {
@@ -230,7 +378,7 @@ async function tickTimer ({ services }) {
230
378
  line('tick', 'on — schedules fire')
231
379
  return
232
380
  }
233
- if (!await yes('a spore acts on a schedule only with the tick timer — turn it on?')) {
381
+ if (list().workspaces.length || !await yes('a spore acts on a schedule only with the tick timer — turn it on?')) {
234
382
  line('tick', 'off — spore service define tick, then enable it, once a spore has a schedule')
235
383
  return
236
384
  }
package/src/vm.js CHANGED
@@ -171,11 +171,12 @@ function setupVm (named) {
171
171
  * else to a vm `vm.json` names, and returns only when the command runs here.
172
172
  */
173
173
  export async function host (args) {
174
- const [verb] = args
174
+ const [verb, second] = args
175
+ const firstRun = verb === 'setup' && second === undefined
175
176
  const vm = vmNamed()
176
177
  if (verb === 'vm') vmVerb(vm, args)
177
- if (verb === 'setup' && !vm && process.stdin.isTTY && process.stdout.isTTY) intro('spore setup')
178
- if (verb === 'setup' && (vm || await wantsVm())) setupVm(vm)
178
+ if (firstRun && !vm && process.stdin.isTTY && process.stdout.isTTY) intro('spore setup')
179
+ if (firstRun && (vm || await wantsVm())) setupVm(vm)
179
180
  if (vm) {
180
181
  running(vm)
181
182
  forward(vm, args)
package/tui/answer.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { Markdown } from '@earendil-works/pi-tui'
2
2
 
3
3
  /**
4
- * An answer as pi-tui draws it, keeping the code blocks it drew: `blocks` is each one's text
4
+ * An answer as pi-tui draws it, keeping the code blocks it drew: `codeBlocks` is each one's text
5
5
  * exactly as written, in the order shown. Labelled, each opening fence says how to copy it.
6
+ * It reads them line by line through `codeBlock` because pi-tui remembers what `highlightCode`
7
+ * returned, so that hook is not called again on a later pass.
6
8
  */
7
9
  export class Answer extends Markdown {
8
10
  constructor (text, theme, { labelled = false } = {}) {
@@ -10,12 +12,12 @@ export class Answer extends Markdown {
10
12
  this.theme = {
11
13
  ...theme,
12
14
  codeBlockBorder: (fence) => this.fence(fence),
13
- highlightCode: (code, lang) => this.code(code, lang)
15
+ codeBlock: (line) => this.codeLine(line)
14
16
  }
15
17
  this.base = theme
16
18
  this.labelled = labelled
17
- this.blocks = []
18
- this.inBlock = false
19
+ this.codeBlocks = []
20
+ this.opened = null
19
21
  }
20
22
 
21
23
  label (on) {
@@ -26,23 +28,24 @@ export class Answer extends Markdown {
26
28
 
27
29
  render (width) {
28
30
  if (this.cachedText !== this.text || this.cachedWidth !== width) {
29
- this.blocks = []
30
- this.inBlock = false
31
+ this.codeBlocks = []
32
+ this.opened = null
31
33
  }
32
34
  return super.render(width)
33
35
  }
34
36
 
35
37
  fence (fence) {
36
- if (this.inBlock) {
37
- this.inBlock = false
38
+ if (this.opened) {
39
+ this.codeBlocks.push({ lang: this.opened.lang, text: this.opened.lines.join('\n') })
40
+ this.opened = null
38
41
  return this.base.codeBlockBorder(fence)
39
42
  }
40
- this.inBlock = true
41
- return this.base.codeBlockBorder(this.labelled ? `${fence} · /copy ${this.blocks.length + 1}` : fence)
43
+ this.opened = { lang: fence.replace(/^`+/, ''), lines: [] }
44
+ return this.base.codeBlockBorder(this.labelled ? `${fence} · /copy ${this.codeBlocks.length + 1}` : fence)
42
45
  }
43
46
 
44
- code (text, lang) {
45
- this.blocks.push({ lang: lang ?? '', text })
46
- return text.split('\n').map(line => this.base.codeBlock(line))
47
+ codeLine (line) {
48
+ this.opened.lines.push(line)
49
+ return this.base.codeBlock(line)
47
50
  }
48
51
  }
package/tui/index.js CHANGED
@@ -114,7 +114,7 @@ class Conversation {
114
114
  /** The code blocks of the last answer, numbered on screen from 1. */
115
115
  lastBlocks () {
116
116
  const last = this.lastAnswer()
117
- return last ? this.markdown(last).blocks : []
117
+ return last ? this.markdown(last).codeBlocks : []
118
118
  }
119
119
 
120
120
  render (width) {
package/tui/links.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The `· /copy <n>` label on a code block's opening fence, made a link. It is drawn as an OSC 8
3
- * hyperlink — which kitty underlines on hover — so a click on it reaches pi-tui's `openUrl` with a
3
+ * hyperlink, so a click on it reaches pi-tui's `openUrl` with a
4
4
  * URL this module reads back into the number of the block to copy. The label's own look is
5
5
  * unchanged, and the link adds no width to the line.
6
6
  */