@llm4ts/shell 3.2.6 → 3.3.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.
Files changed (48) hide show
  1. package/dist/Cli.d.ts +11 -3
  2. package/dist/Cli.d.ts.map +1 -1
  3. package/dist/Cli.js +125 -38
  4. package/dist/Cli.js.map +1 -1
  5. package/dist/Config.d.ts +238 -0
  6. package/dist/Config.d.ts.map +1 -0
  7. package/dist/Config.js +594 -0
  8. package/dist/Config.js.map +1 -0
  9. package/dist/ConfigCommand.d.ts +180 -0
  10. package/dist/ConfigCommand.d.ts.map +1 -0
  11. package/dist/ConfigCommand.js +903 -0
  12. package/dist/ConfigCommand.js.map +1 -0
  13. package/dist/ConfigEdit.d.ts +79 -0
  14. package/dist/ConfigEdit.d.ts.map +1 -0
  15. package/dist/ConfigEdit.js +110 -0
  16. package/dist/ConfigEdit.js.map +1 -0
  17. package/dist/ConfigTrust.d.ts +45 -0
  18. package/dist/ConfigTrust.d.ts.map +1 -0
  19. package/dist/ConfigTrust.js +72 -0
  20. package/dist/ConfigTrust.js.map +1 -0
  21. package/dist/FlowLaunch.d.ts +2 -3
  22. package/dist/FlowLaunch.d.ts.map +1 -1
  23. package/dist/FlowLaunch.js +1 -5
  24. package/dist/FlowLaunch.js.map +1 -1
  25. package/dist/FlowProcess.d.ts +3 -1
  26. package/dist/FlowProcess.d.ts.map +1 -1
  27. package/dist/FlowProcess.js.map +1 -1
  28. package/dist/Menu.d.ts +1 -1
  29. package/dist/Menu.d.ts.map +1 -1
  30. package/dist/Menu.js +33 -6
  31. package/dist/Menu.js.map +1 -1
  32. package/dist/RunSupervisor.d.ts +4 -3
  33. package/dist/RunSupervisor.d.ts.map +1 -1
  34. package/dist/RunSupervisor.js +26 -13
  35. package/dist/RunSupervisor.js.map +1 -1
  36. package/kits/j2ee-nextjs/README.md +2 -1
  37. package/kits/j2ee-nextjs/fixtures/demo-bank/RUNBOOK.md +32 -14
  38. package/kits/j2ee-nextjs/fixtures/demo-bank/reset-demo.mjs +3 -1
  39. package/package.json +8 -4
  40. package/src/Cli.ts +173 -45
  41. package/src/Config.ts +868 -0
  42. package/src/ConfigCommand.ts +1423 -0
  43. package/src/ConfigEdit.ts +180 -0
  44. package/src/ConfigTrust.ts +145 -0
  45. package/src/FlowLaunch.ts +3 -8
  46. package/src/FlowProcess.ts +3 -1
  47. package/src/Menu.ts +40 -7
  48. package/src/RunSupervisor.ts +26 -14
@@ -0,0 +1,1423 @@
1
+ // `llm4ts config show | set | unset | init | edit | trust | untrust`: the
2
+ // config files seen, edited and accepted from the command line. Every renderer is pure and never prints a secret.
3
+ import { resolve } from "node:path"
4
+ import * as Console from "effect/Console"
5
+ import * as Effect from "effect/Effect"
6
+ import * as Result from "effect/Result"
7
+ import { Argument, Command, Flag, Prompt } from "effect/cli"
8
+ import type { ProcessExecutorShape } from "@llm4ts/core/ProcessExecutor"
9
+ import type { PlainFileStoreShape } from "@llm4ts/flow/Persistence"
10
+ import {
11
+ closestSettingName,
12
+ groupTitles,
13
+ isSettingName,
14
+ readSetting,
15
+ type Environment,
16
+ type SettingFacts,
17
+ type SettingName
18
+ } from "@llm4ts/flow/Settings"
19
+ import { nodePlainFileStore } from "@llm4ts/runner/NodePlainFileStore"
20
+ import { nodeProcessExecutor } from "@llm4ts/runner/NodeProcessExecutor"
21
+ import { coderChoices, findOnPath } from "./CoderChoice.ts"
22
+ import {
23
+ expandPath,
24
+ globalConfigPath,
25
+ homeOf,
26
+ loadConfig,
27
+ parseConfigFile,
28
+ planSet,
29
+ projectConfigPath,
30
+ registryFacts,
31
+ writeConfig,
32
+ type ConfigChange,
33
+ type ConfigFile,
34
+ type FileLayer,
35
+ type Layered,
36
+ type LoadedConfig,
37
+ type Source
38
+ } from "./Config.ts"
39
+ import {
40
+ configTrustPath,
41
+ contentHash,
42
+ forgetTrust,
43
+ loadTrustStore,
44
+ recordTrust,
45
+ trustCommand,
46
+ trustDecision,
47
+ writeRefusal,
48
+ type Distrust
49
+ } from "./ConfigTrust.ts"
50
+ import {
51
+ editRequest,
52
+ environmentNote,
53
+ pickerRows,
54
+ saveTargets,
55
+ sessionSummary,
56
+ settingActions,
57
+ targetTitles,
58
+ unlistedHint,
59
+ valuePrompt,
60
+ type SessionChange,
61
+ type SettingAction
62
+ } from "./ConfigEdit.ts"
63
+ import { ShellUsageError } from "./ShellErrors.ts"
64
+
65
+ /** Provider keys the connectors read. `config show` says set or unset, never more. */
66
+ export const foreignCredentials: ReadonlyArray<string> = [
67
+ "ANTHROPIC_API_KEY",
68
+ "OPENAI_API_KEY",
69
+ "GEMINI_API_KEY",
70
+ "GOOGLE_API_KEY",
71
+ "TYPESAFE_API_KEY"
72
+ ]
73
+
74
+ export interface ConfigView {
75
+ readonly loaded: LoadedConfig
76
+ readonly environment: Environment
77
+ readonly globalPath: string
78
+ readonly projectPath: string
79
+ readonly repo: string
80
+ readonly home: string
81
+ }
82
+
83
+ const facts = new Map<string, SettingFacts>(registryFacts.map((fact) => [fact.name, fact]))
84
+
85
+ const tilde = (path: string, home: string): string =>
86
+ path === home ? "~" : path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path
87
+
88
+ const table = (rows: ReadonlyArray<ReadonlyArray<string>>, indent = ""): ReadonlyArray<string> => {
89
+ const widths: Array<number> = []
90
+ for (const row of rows) {
91
+ row.forEach((cell, index) => {
92
+ widths[index] = Math.max(widths[index] ?? 0, cell.length)
93
+ })
94
+ }
95
+ return rows.map((row) =>
96
+ `${indent}${row.map((cell, index) => cell.padEnd(widths[index] ?? 0)).join(" ")}`.trimEnd()
97
+ )
98
+ }
99
+
100
+ const sourceLabel = (source: Source): string =>
101
+ source.layer === "flag" || source.layer === "environment"
102
+ ? source.layer
103
+ : `${source.layer}:${source.line}`
104
+
105
+ const shown = (raw: string, secret: boolean): string =>
106
+ secret ? "(secret, set)" : raw.length === 0 ? "(empty)" : raw
107
+
108
+ const suppliedBy = (view: ConfigView, layer: FileLayer): number =>
109
+ [...view.loaded.resolution.settings.values()].filter((setting) =>
110
+ [setting, ...setting.shadowed].some((layered) => layered.source.layer === layer)
111
+ ).length
112
+
113
+ const counted = (count: number): string => (count === 1 ? "1 setting" : `${count} settings`)
114
+
115
+ type FileState = "absent" | "present" | Distrust
116
+
117
+ const fileStates = (
118
+ view: ConfigView
119
+ ): ReadonlyArray<{
120
+ readonly layer: FileLayer
121
+ readonly path: string
122
+ readonly state: FileState
123
+ readonly settings: number
124
+ }> => [
125
+ {
126
+ layer: "global",
127
+ path: view.globalPath,
128
+ state: view.loaded.global === undefined ? "absent" : "present",
129
+ settings: suppliedBy(view, "global")
130
+ },
131
+ {
132
+ layer: "project",
133
+ path: view.projectPath,
134
+ state: view.loaded.projectTrust === "trusted" ? "present" : view.loaded.projectTrust,
135
+ settings: suppliedBy(view, "project")
136
+ }
137
+ ]
138
+
139
+ const stateText = (file: { readonly state: FileState; readonly settings: number }): string =>
140
+ file.state === "untrusted"
141
+ ? "not trusted"
142
+ : file.state === "changed"
143
+ ? "changed since trusted"
144
+ : file.state === "absent"
145
+ ? "absent"
146
+ : counted(file.settings)
147
+
148
+ const fileRows = (view: ConfigView): ReadonlyArray<ReadonlyArray<string>> =>
149
+ fileStates(view).map((file) => [file.layer, tilde(file.path, view.home), stateText(file)])
150
+
151
+ const credentialSet = (environment: Environment, name: string): boolean =>
152
+ (environment[name] ?? "").trim().length > 0
153
+
154
+ const atDefault = (view: ConfigView): ReadonlyArray<SettingFacts> =>
155
+ view.loaded.resolution.facts.filter((fact) => !view.loaded.resolution.settings.has(fact.name))
156
+
157
+ /** Pure: the files, every setting some layer sets, credentials, warnings, the default count. */
158
+ export const renderShow = (view: ConfigView, options: { readonly all: boolean }): string => {
159
+ const { resolution } = view.loaded
160
+ const lines: Array<string> = ["files", ...table(fileRows(view), " ")]
161
+ if (resolution.settings.size > 0) {
162
+ lines.push(
163
+ "",
164
+ ...table([
165
+ ["setting", "value", "from"],
166
+ ...[...resolution.settings.values()].map((setting) => {
167
+ const below = setting.shadowed[0]
168
+ return [
169
+ setting.name,
170
+ shown(setting.raw, setting.secret),
171
+ sourceLabel(setting.source),
172
+ ...(below === undefined
173
+ ? []
174
+ : [
175
+ setting.secret
176
+ ? `(${sourceLabel(below.source)} sets it too)`
177
+ : `(${sourceLabel(below.source)} has ${shown(below.raw, false)})`
178
+ ])
179
+ ]
180
+ })
181
+ ])
182
+ )
183
+ }
184
+ lines.push(
185
+ "",
186
+ "credentials",
187
+ ...table(
188
+ foreignCredentials.map((name) => [
189
+ name,
190
+ credentialSet(view.environment, name) ? "set" : "unset"
191
+ ]),
192
+ " "
193
+ )
194
+ )
195
+ const warnings = resolution.problems.filter((problem) => problem.kind !== "shadowed")
196
+ if (warnings.length > 0) {
197
+ lines.push("", "warnings", ...warnings.map((problem) => ` ${problem.message}`))
198
+ }
199
+ const defaults = atDefault(view)
200
+ if (options.all) {
201
+ for (const [group, title] of groupTitles) {
202
+ const rows = defaults.filter((fact) => fact.group === group)
203
+ if (rows.length > 0) {
204
+ lines.push(
205
+ "",
206
+ title,
207
+ ...table(
208
+ rows.map((fact) => [fact.name, fact.fallback.text, "default"]),
209
+ " "
210
+ )
211
+ )
212
+ }
213
+ }
214
+ }
215
+ lines.push(
216
+ "",
217
+ options.all
218
+ ? `${counted(defaults.length)} at their defaults · one in full: llm4ts config show <NAME>`
219
+ : `${counted(defaults.length)} at their defaults: llm4ts config show --all · one in full: llm4ts config show <NAME>`
220
+ )
221
+ return lines.join("\n")
222
+ }
223
+
224
+ const belongsIn = {
225
+ global: "the global file",
226
+ project: "the project file",
227
+ run: "a run (llm4ts run --set)",
228
+ secret: "the environment only",
229
+ internal: "nowhere: llm4ts sets it"
230
+ }
231
+
232
+ /** Pure: one setting in full: each layer, the default, its doc, grammar and home. */
233
+ export const renderSetting = (view: ConfigView, name: SettingName): string => {
234
+ const fact = facts.get(name)
235
+ const setting = view.loaded.resolution.settings.get(name)
236
+ const secret = fact?.scope === "secret"
237
+ const layers: ReadonlyArray<Layered> = setting === undefined ? [] : [setting, ...setting.shadowed]
238
+ const valueAt = (layer: Source["layer"]): string => {
239
+ const found = layers.find((layered) => layered.source.layer === layer)
240
+ return found === undefined ? "—" : shown(found.raw, secret)
241
+ }
242
+ const where = (source: Source): string =>
243
+ source.layer === "flag"
244
+ ? source.flag
245
+ : source.layer === "environment"
246
+ ? "the environment"
247
+ : `${source.layer} ${tilde(source.path, view.home)}:${source.line}`
248
+ return [
249
+ setting === undefined
250
+ ? `${name} is at its default`
251
+ : `${name} = ${shown(setting.raw, secret)} from ${where(setting.source)}`,
252
+ ...table(
253
+ [
254
+ ["flag", valueAt("flag")],
255
+ ["environment", valueAt("environment")],
256
+ ["project", valueAt("project")],
257
+ ["global", valueAt("global")],
258
+ ["default", fact?.fallback.text ?? ""]
259
+ ],
260
+ " "
261
+ ),
262
+ fact?.doc ?? "",
263
+ [
264
+ `value: ${fact?.grammar ?? ""}`,
265
+ `belongs in: ${fact === undefined ? "" : belongsIn[fact.scope]}`,
266
+ `group: ${fact?.group ?? ""}`,
267
+ ...(fact?.flag === undefined ? [] : [`flag: ${fact.flag}`]),
268
+ ...(fact === undefined || fact.requiredBy.length === 0
269
+ ? []
270
+ : [`required by: ${fact.requiredBy.join(", ")}`])
271
+ ].join(" · ")
272
+ ].join("\n")
273
+ }
274
+
275
+ const layerJson = (layered: Layered, secret: boolean) => ({
276
+ source: layered.source.layer,
277
+ ...(layered.source.layer === "project" || layered.source.layer === "global"
278
+ ? { path: layered.source.path, line: layered.source.line }
279
+ : {}),
280
+ ...(layered.source.layer === "flag" ? { flag: layered.source.flag } : {}),
281
+ ...(secret ? {} : { value: layered.raw })
282
+ })
283
+
284
+ /** Pure: every setting, set or not, as JSON. A secret carries `set`, never a value. */
285
+ export const renderShowJson = (view: ConfigView): string => {
286
+ const { resolution } = view.loaded
287
+ return JSON.stringify(
288
+ {
289
+ files: fileStates(view),
290
+ settings: resolution.facts.map((fact) => {
291
+ const setting = resolution.settings.get(fact.name)
292
+ const secret = fact.scope === "secret"
293
+ return {
294
+ name: fact.name,
295
+ group: fact.group,
296
+ scope: fact.scope,
297
+ set: setting !== undefined,
298
+ ...(setting === undefined
299
+ ? { source: "default" }
300
+ : {
301
+ ...layerJson(setting, secret),
302
+ shadowed: setting.shadowed.map((layered) => layerJson(layered, secret))
303
+ }),
304
+ default: fact.fallback.text,
305
+ grammar: fact.grammar,
306
+ doc: fact.doc
307
+ }
308
+ }),
309
+ credentials: foreignCredentials.map((name) => ({
310
+ name,
311
+ set: credentialSet(view.environment, name)
312
+ })),
313
+ problems: resolution.problems.map((problem) => ({
314
+ severity: problem.severity,
315
+ kind: problem.kind,
316
+ message: problem.message,
317
+ ...(problem.name === undefined ? {} : { name: problem.name }),
318
+ ...(problem.closest === undefined ? {} : { closest: problem.closest })
319
+ }))
320
+ },
321
+ undefined,
322
+ 2
323
+ )
324
+ }
325
+
326
+ /**
327
+ * Pure: doctor's section: both files, how many settings each supplies, what
328
+ * blocks a run: every error, and a project file that is not trusted.
329
+ */
330
+ export const renderDoctorConfig = (view: ConfigView): string =>
331
+ [
332
+ "config:",
333
+ ...table(
334
+ fileStates(view).map((file) => [
335
+ file.state === "present" ? "✔" : file.state === "absent" ? "·" : "✖",
336
+ file.layer,
337
+ tilde(file.path, view.home),
338
+ stateText(file)
339
+ ]),
340
+ " "
341
+ ),
342
+ ...view.loaded.resolution.problems
343
+ .filter((problem) => problem.severity === "error" || problem.kind === "untrusted")
344
+ .map((problem) => ` ✖ ${problem.message}`)
345
+ ].join("\n")
346
+
347
+ export interface FileChanges {
348
+ readonly layer: FileLayer
349
+ readonly path: string
350
+ /** A line and what happened to it: `new`, `changed`, `unchanged`, `removed (was 2)`. */
351
+ readonly rows: ReadonlyArray<readonly [string, string]>
352
+ }
353
+
354
+ /** Pure: per file, each line `set`, `unset` or `init` touched; then the notes. */
355
+ export const renderChanges = (
356
+ files: ReadonlyArray<FileChanges>,
357
+ notes: ReadonlyArray<string>,
358
+ home: string
359
+ ): string =>
360
+ [
361
+ ...files.flatMap((file) => [
362
+ `${file.layer.padEnd(7)} ${tilde(file.path, home)}`,
363
+ ...table(file.rows, " ")
364
+ ]),
365
+ ...notes
366
+ ].join("\n")
367
+
368
+ /** `NAME=value` split at the first `=`. The failure never repeats the argument: it may hold a secret. */
369
+ export const parseAssignment = (
370
+ text: string
371
+ ): Result.Result<{ readonly name: string; readonly value: string }, string> => {
372
+ const at = text.indexOf("=")
373
+ return at <= 0
374
+ ? Result.fail(
375
+ at < 0
376
+ ? "expected NAME=value, got an argument with no ="
377
+ : "expected NAME=value, got a value with no name"
378
+ )
379
+ : Result.succeed({ name: text.slice(0, at).trim(), value: text.slice(at + 1) })
380
+ }
381
+
382
+ const lastValue = (file: ConfigFile | undefined, name: string): string | undefined => {
383
+ let value: string | undefined
384
+ for (const line of file?.lines ?? []) {
385
+ if (line._tag === "Entry" && line.name === name) {
386
+ value = line.value
387
+ }
388
+ }
389
+ return value
390
+ }
391
+
392
+ /** The settings whose value is passed to a coding agent's command line. */
393
+ export const seatFlagSettings: ReadonlyArray<SettingName> = [
394
+ "LLM4TS_CODER_FLAGS",
395
+ "LLM4TS_REASONING_FLAGS"
396
+ ]
397
+
398
+ // A file under review is not the user's yet: a control or direction
399
+ // character in it could repaint the terminal and hide a line.
400
+ const visible = (text: string): string =>
401
+ text.replace(
402
+ /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu,
403
+ (character) => `\\u${(character.codePointAt(0) ?? 0).toString(16).padStart(4, "0")}`
404
+ )
405
+
406
+ const plural = (count: number, one: string, many: string): string =>
407
+ count === 1 ? `1 ${one}` : `${count} ${many}`
408
+
409
+ /**
410
+ * Pure: what `config trust` asks the user to accept: the file's path, every
411
+ * setting line with its value, tagged when llm4ts runs the value as a
412
+ * command or hands it to a coding agent as flags, and every line the parser
413
+ * rejects. A secret's value is not printed.
414
+ */
415
+ export const renderTrustListing = (text: string, projectPath: string): string => {
416
+ const raw = text.split("\n")
417
+ const file = parseConfigFile(text, projectPath)
418
+ const rows = file.lines.flatMap((line): ReadonlyArray<ReadonlyArray<string>> => {
419
+ if (line._tag === "Other") {
420
+ return []
421
+ }
422
+ if (line._tag === "Malformed") {
423
+ return [
424
+ [
425
+ `line ${line.line}`,
426
+ visible((raw[line.line - 1] ?? "").trim()),
427
+ "[rejected: not a NAME=value line]"
428
+ ]
429
+ ]
430
+ }
431
+ const fact = facts.get(line.name)
432
+ const tag =
433
+ fact === undefined
434
+ ? "[not a setting: ignored]"
435
+ : fact.scope === "secret"
436
+ ? "[a secret: ignored in a file]"
437
+ : fact.runs
438
+ ? "[runs as a command]"
439
+ : seatFlagSettings.includes(fact.name)
440
+ ? "[flags for a coding agent]"
441
+ : ""
442
+ return [
443
+ [
444
+ line.name,
445
+ fact?.scope === "secret"
446
+ ? "(value hidden)"
447
+ : line.value.length === 0
448
+ ? "(empty)"
449
+ : visible(line.value),
450
+ tag
451
+ ]
452
+ ]
453
+ })
454
+ const entries = file.lines.filter((line) => line._tag === "Entry")
455
+ const running = entries.filter((line) => facts.get(line.name)?.runs === true).length
456
+ return [
457
+ `project file ${projectPath}`,
458
+ ...table(rows, " "),
459
+ rows.length === 0
460
+ ? "it sets nothing"
461
+ : `${plural(entries.length, "setting", "settings")}; llm4ts runs ${plural(running, "value", "values")} as a command`
462
+ ].join("\n")
463
+ }
464
+
465
+ const distrustOf = (loaded: LoadedConfig): Distrust | undefined =>
466
+ loaded.projectTrust === "untrusted" || loaded.projectTrust === "changed"
467
+ ? loaded.projectTrust
468
+ : undefined
469
+
470
+ const projectRefusal = (view: ConfigView): string | undefined => {
471
+ const distrust = distrustOf(view.loaded)
472
+ return distrust === undefined ? undefined : writeRefusal(view.projectPath, view.repo, distrust)
473
+ }
474
+
475
+ export interface ConfigDeps {
476
+ readonly files: PlainFileStoreShape
477
+ readonly executor: ProcessExecutorShape
478
+ readonly environment: Environment
479
+ readonly cwd: string
480
+ }
481
+
482
+ const usage = (message: string): ShellUsageError => new ShellUsageError({ message })
483
+
484
+ const viewOf = Effect.fn("@llm4ts/shell/ConfigCommand.viewOf")(function* (
485
+ deps: ConfigDeps,
486
+ repo: string
487
+ ): Effect.fn.Return<ConfigView, ShellUsageError> {
488
+ const loaded = yield* loadConfig({
489
+ repo,
490
+ environment: deps.environment,
491
+ flags: [],
492
+ files: deps.files
493
+ }).pipe(Effect.mapError((error) => usage(error.message)))
494
+ return {
495
+ loaded,
496
+ environment: deps.environment,
497
+ globalPath: globalConfigPath(deps.environment),
498
+ projectPath: projectConfigPath(repo),
499
+ repo,
500
+ home: homeOf(deps.environment)
501
+ }
502
+ })
503
+
504
+ /** The view `doctor` and `config show` render, for `repo`. */
505
+ export const configView = viewOf
506
+
507
+ const readParsed = (deps: ConfigDeps, path: string) =>
508
+ deps.files.read(path).pipe(
509
+ Effect.map((text) => (text === undefined ? undefined : parseConfigFile(text, path))),
510
+ Effect.mapError((error) => usage(`cannot read ${path}: ${error.message}`))
511
+ )
512
+
513
+ const pathOf = (view: ConfigView, layer: FileLayer): string =>
514
+ layer === "project" ? view.projectPath : view.globalPath
515
+
516
+ const trust = (deps: ConfigDeps, repo: string, hash: string) =>
517
+ recordTrust(deps.files, configTrustPath(deps.environment), repo, hash).pipe(
518
+ Effect.mapError((error) => usage(`cannot record trust: ${error.message}`))
519
+ )
520
+
521
+ /**
522
+ * Writing is trusting: what llm4ts writes to the project file on the user's
523
+ * word is recorded as trusted. The write goes through only while the file
524
+ * still holds the content `view` judged.
525
+ */
526
+ const write = Effect.fn("@llm4ts/shell/ConfigCommand.write")(function* (
527
+ deps: ConfigDeps,
528
+ view: ConfigView,
529
+ layer: FileLayer,
530
+ changes: ReadonlyArray<ConfigChange>
531
+ ): Effect.fn.Return<void, ShellUsageError> {
532
+ const written = yield* writeConfig({
533
+ files: deps.files,
534
+ path: pathOf(view, layer),
535
+ changes,
536
+ ...(layer === "project" ? { expect: { hash: view.loaded.projectHash } } : {})
537
+ }).pipe(Effect.mapError((error) => usage(error.message)))
538
+ if (layer === "project" && written !== undefined) {
539
+ yield* trust(deps, view.repo, contentHash(written))
540
+ }
541
+ })
542
+
543
+ const fileLayers: ReadonlyArray<FileLayer> = ["project", "global"]
544
+
545
+ /** A path value made absolute the way `config set` writes it. */
546
+ const assignmentOf = (
547
+ deps: ConfigDeps,
548
+ name: string,
549
+ value: string
550
+ ): { readonly name: string; readonly value: string } => ({
551
+ name,
552
+ value:
553
+ facts.get(name)?.path === true && value.trim().length > 0
554
+ ? expandPath(value, deps.cwd, homeOf(deps.environment))
555
+ : value
556
+ })
557
+
558
+ export const runConfigShow = Effect.fn("@llm4ts/shell/ConfigCommand.show")(function* (
559
+ deps: ConfigDeps,
560
+ options: {
561
+ readonly repo: string
562
+ readonly name?: string
563
+ readonly all: boolean
564
+ readonly json: boolean
565
+ }
566
+ ): Effect.fn.Return<string, ShellUsageError> {
567
+ const view = yield* viewOf(deps, options.repo)
568
+ if (options.name === undefined) {
569
+ return options.json ? renderShowJson(view) : renderShow(view, { all: options.all })
570
+ }
571
+ if (!isSettingName(options.name)) {
572
+ const closest = closestSettingName(options.name)
573
+ return yield* usage(
574
+ closest === undefined
575
+ ? `unknown setting ${options.name}`
576
+ : `unknown setting ${options.name}; did you mean ${closest}?`
577
+ )
578
+ }
579
+ return renderSetting(view, options.name)
580
+ })
581
+
582
+ export const runConfigSet = Effect.fn("@llm4ts/shell/ConfigCommand.set")(function* (
583
+ deps: ConfigDeps,
584
+ options: {
585
+ readonly repo: string
586
+ readonly pairs: ReadonlyArray<string>
587
+ readonly target?: FileLayer
588
+ }
589
+ ): Effect.fn.Return<string, ShellUsageError> {
590
+ if (options.pairs.length === 0) {
591
+ return yield* usage("config set needs NAME=value")
592
+ }
593
+ const home = homeOf(deps.environment)
594
+ const parsed = options.pairs.map(parseAssignment)
595
+ const malformed = parsed.flatMap((pair) => (Result.isFailure(pair) ? [pair.failure] : []))
596
+ if (malformed.length > 0) {
597
+ return yield* usage(malformed.join("\n"))
598
+ }
599
+ const assignments = parsed
600
+ .flatMap((pair) => (Result.isSuccess(pair) ? [pair.success] : []))
601
+ .map(({ name, value }) => assignmentOf(deps, name, value))
602
+ const planned = planSet(registryFacts, assignments, options.target)
603
+ if (Result.isFailure(planned)) {
604
+ return yield* usage(planned.failure.join("\n"))
605
+ }
606
+ const view = yield* viewOf(deps, options.repo)
607
+ const refusal = projectRefusal(view)
608
+ if (refusal !== undefined && planned.success.some((set) => set.target === "project")) {
609
+ return yield* usage(refusal)
610
+ }
611
+ const reports: Array<FileChanges> = []
612
+ for (const layer of fileLayers) {
613
+ const sets = planned.success.filter((set) => set.target === layer)
614
+ if (sets.length === 0) {
615
+ continue
616
+ }
617
+ const path = pathOf(view, layer)
618
+ const before = yield* readParsed(deps, path)
619
+ reports.push({
620
+ layer,
621
+ path,
622
+ rows: sets.map((set) => {
623
+ const current = lastValue(before, set.name)
624
+ return [
625
+ `${set.name}=${set.value}`,
626
+ current === undefined ? "new" : current === set.value ? "unchanged" : "changed"
627
+ ]
628
+ })
629
+ })
630
+ yield* write(deps, view, layer, sets)
631
+ }
632
+ const after = yield* viewOf(deps, options.repo)
633
+ const written = new Set<string>(planned.success.map((set) => set.name))
634
+ return renderChanges(
635
+ reports,
636
+ after.loaded.resolution.problems
637
+ .filter(
638
+ (problem) =>
639
+ problem.kind === "shadowed" && problem.name !== undefined && written.has(problem.name)
640
+ )
641
+ .map(
642
+ (problem) =>
643
+ `note: ${problem.name} is also exported in this shell, which wins over the file`
644
+ ),
645
+ home
646
+ )
647
+ })
648
+
649
+ export const runConfigUnset = Effect.fn("@llm4ts/shell/ConfigCommand.unset")(function* (
650
+ deps: ConfigDeps,
651
+ options: {
652
+ readonly repo: string
653
+ readonly names: ReadonlyArray<string>
654
+ readonly target?: FileLayer
655
+ }
656
+ ): Effect.fn.Return<string, ShellUsageError> {
657
+ if (options.names.length === 0) {
658
+ return yield* usage("config unset needs a setting name")
659
+ }
660
+ const view = yield* viewOf(deps, options.repo)
661
+ const refusal = projectRefusal(view)
662
+ if (refusal !== undefined && options.target === "project") {
663
+ return yield* usage(refusal)
664
+ }
665
+ const layers = (options.target === undefined ? fileLayers : [options.target]).filter(
666
+ (layer) => layer !== "project" || refusal === undefined
667
+ )
668
+ const reports: Array<FileChanges> = []
669
+ const found = new Set<string>()
670
+ for (const layer of layers) {
671
+ const path = pathOf(view, layer)
672
+ const before = yield* readParsed(deps, path)
673
+ const held = options.names.flatMap((name): ReadonlyArray<readonly [string, string]> => {
674
+ const current = lastValue(before, name)
675
+ if (current === undefined) {
676
+ return []
677
+ }
678
+ const scope = facts.get(name)?.scope
679
+ return [
680
+ [name, scope === "global" || scope === "project" ? `removed (was ${current})` : "removed"]
681
+ ]
682
+ })
683
+ if (held.length === 0) {
684
+ continue
685
+ }
686
+ for (const [name] of held) {
687
+ found.add(name)
688
+ }
689
+ reports.push({ layer, path, rows: held })
690
+ yield* write(
691
+ deps,
692
+ view,
693
+ layer,
694
+ held.map(([name]) => ({ name, value: undefined }))
695
+ )
696
+ }
697
+ return renderChanges(
698
+ reports,
699
+ [
700
+ ...options.names
701
+ .filter((name) => !found.has(name))
702
+ .map((name) => {
703
+ const closest = isSettingName(name) ? undefined : closestSettingName(name)
704
+ return closest === undefined
705
+ ? `${name} is not set in a config file`
706
+ : `${name} is not set in a config file; did you mean ${closest}?`
707
+ }),
708
+ ...(refusal === undefined ? [] : [`left alone: ${refusal}`])
709
+ ],
710
+ view.home
711
+ )
712
+ })
713
+
714
+ export type SeatAnswers = ReadonlyArray<{ readonly name: SettingName; readonly value: string }>
715
+
716
+ export interface InitWrite {
717
+ readonly layer: FileLayer
718
+ readonly name: SettingName
719
+ readonly value: string
720
+ readonly origin: "environment" | "answer"
721
+ }
722
+
723
+ export interface InitPlan {
724
+ readonly writes: ReadonlyArray<InitWrite>
725
+ readonly skipped: ReadonlyArray<string>
726
+ /** Exports a file now covers with the same value. */
727
+ readonly removable: ReadonlyArray<string>
728
+ }
729
+
730
+ /**
731
+ * Pure: what `config init` writes. Every `LLM4TS_*` the environment sets goes
732
+ * to the file its scope belongs in unless that file already has a line for
733
+ * it; run-scoped, secret, internal, unreadable and unknown names are skipped
734
+ * with the reason, and so is a project setting while the project file is not
735
+ * trusted. `answers` fill only names nothing sets yet.
736
+ */
737
+ export const planInit = (input: {
738
+ readonly environment: Environment
739
+ readonly global: ConfigFile | undefined
740
+ readonly project: ConfigFile | undefined
741
+ /** Why nothing may be written to the project file; absent when it may. */
742
+ readonly projectRefusal?: string
743
+ readonly cwd: string
744
+ readonly home: string
745
+ readonly answers: SeatAnswers
746
+ }): InitPlan => {
747
+ const writes: Array<InitWrite> = []
748
+ const skipped: Array<string> = []
749
+ const removable: Array<string> = []
750
+ const fileOf = (layer: FileLayer) => (layer === "project" ? input.project : input.global)
751
+ for (const fact of registryFacts) {
752
+ const raw = input.environment[fact.name]
753
+ if (raw === undefined) {
754
+ continue
755
+ }
756
+ const read = readSetting(fact.name, raw)
757
+ if (Result.isSuccess(read) && read.success === undefined) {
758
+ continue
759
+ }
760
+ const value = fact.path ? expandPath(raw, input.cwd, input.home) : raw
761
+ const planned = planSet(registryFacts, [{ name: fact.name, value }])
762
+ const [set] = Result.isSuccess(planned) ? planned.success : []
763
+ if (set === undefined) {
764
+ skipped.push(`skipped ${Result.isFailure(planned) ? planned.failure.join("; ") : fact.name}`)
765
+ continue
766
+ }
767
+ if (set.target === "project" && input.projectRefusal !== undefined) {
768
+ skipped.push(`skipped ${fact.name}: ${input.projectRefusal}`)
769
+ continue
770
+ }
771
+ const current = lastValue(fileOf(set.target), fact.name)
772
+ if (current === undefined) {
773
+ writes.push({ layer: set.target, name: fact.name, value, origin: "environment" })
774
+ removable.push(fact.name)
775
+ } else if (current === value) {
776
+ removable.push(fact.name)
777
+ } else {
778
+ skipped.push(`kept ${fact.name}: the ${set.target} file already sets another value`)
779
+ }
780
+ }
781
+ for (const name of Object.keys(input.environment).sort()) {
782
+ if (
783
+ name.startsWith("LLM4TS_") &&
784
+ !isSettingName(name) &&
785
+ input.environment[name] !== undefined
786
+ ) {
787
+ const closest = closestSettingName(name)
788
+ skipped.push(
789
+ closest === undefined
790
+ ? `skipped ${name}: not a setting`
791
+ : `skipped ${name}: not a setting; did you mean ${closest}?`
792
+ )
793
+ }
794
+ }
795
+ for (const answer of input.answers) {
796
+ const layer = facts.get(answer.name)?.scope
797
+ if (
798
+ (layer === "global" || layer === "project") &&
799
+ !writes.some((write) => write.name === answer.name) &&
800
+ lastValue(fileOf(layer), answer.name) === undefined &&
801
+ input.environment[answer.name] === undefined
802
+ ) {
803
+ writes.push({ layer, name: answer.name, value: answer.value, origin: "answer" })
804
+ }
805
+ }
806
+ return { writes, skipped, removable }
807
+ }
808
+
809
+ /** Pure: what `init` wrote per file, what it skipped, and which exports can go. */
810
+ export const renderInit = (
811
+ plan: InitPlan,
812
+ paths: { readonly global: string; readonly project: string; readonly home: string }
813
+ ): string => {
814
+ const lines = fileLayers.flatMap((layer) => {
815
+ const writes = plan.writes.filter((write) => write.layer === layer)
816
+ return writes.length === 0
817
+ ? []
818
+ : [
819
+ `wrote ${tilde(layer === "project" ? paths.project : paths.global, paths.home)} (${layer})`,
820
+ ...table(
821
+ writes.map((write) => [
822
+ `${write.name}=${write.value}`,
823
+ ...(write.origin === "environment" ? ["from the environment"] : [])
824
+ ]),
825
+ " "
826
+ )
827
+ ]
828
+ })
829
+ return [
830
+ ...lines,
831
+ ...plan.skipped,
832
+ ...(plan.writes.length === 0
833
+ ? ["nothing to do: the config files hold every setting the environment sets"]
834
+ : []),
835
+ ...(plan.removable.length === 0
836
+ ? []
837
+ : [`these exports can now go from your shell profile: ${plan.removable.join(" ")}`]),
838
+ ...(plan.writes.length === 0 ? [] : ["check: llm4ts config show"])
839
+ ].join("\n")
840
+ }
841
+
842
+ export const runConfigInit = Effect.fn("@llm4ts/shell/ConfigCommand.init")(function* <
843
+ E = never,
844
+ R = never
845
+ >(
846
+ deps: ConfigDeps,
847
+ options: {
848
+ readonly repo: string
849
+ /** Asked only when there is no global file yet; absent off a terminal. */
850
+ readonly ask?: Effect.Effect<SeatAnswers, E, R>
851
+ }
852
+ ): Effect.fn.Return<string, ShellUsageError | E, R> {
853
+ const view = yield* viewOf(deps, options.repo)
854
+ const answers =
855
+ view.loaded.global === undefined && options.ask !== undefined ? yield* options.ask : []
856
+ const refusal = projectRefusal(view)
857
+ const plan = planInit({
858
+ environment: deps.environment,
859
+ global: view.loaded.global,
860
+ project: view.loaded.project,
861
+ ...(refusal === undefined ? {} : { projectRefusal: refusal }),
862
+ cwd: deps.cwd,
863
+ home: view.home,
864
+ answers
865
+ })
866
+ for (const layer of fileLayers) {
867
+ const changes = plan.writes.filter((entry) => entry.layer === layer)
868
+ if (changes.length > 0) {
869
+ yield* write(deps, view, layer, changes)
870
+ }
871
+ }
872
+ return renderInit(plan, {
873
+ global: view.globalPath,
874
+ project: view.projectPath,
875
+ home: view.home
876
+ })
877
+ })
878
+
879
+ export type ProjectReview =
880
+ | { readonly _tag: "Absent"; readonly projectPath: string }
881
+ | { readonly _tag: "Trusted"; readonly projectPath: string }
882
+ | {
883
+ readonly _tag: "Pending"
884
+ readonly projectPath: string
885
+ readonly repo: string
886
+ /** The hash of the text `listing` was rendered from: what accepting records. */
887
+ readonly hash: string
888
+ readonly listing: string
889
+ }
890
+
891
+ /** Reads the project file of `repo` once: how it stands, and what there is to accept. */
892
+ export const reviewProject = Effect.fn("@llm4ts/shell/ConfigCommand.reviewProject")(function* (
893
+ deps: ConfigDeps,
894
+ repo: string
895
+ ): Effect.fn.Return<ProjectReview, ShellUsageError> {
896
+ const projectPath = projectConfigPath(repo)
897
+ const text = yield* deps.files
898
+ .read(projectPath)
899
+ .pipe(Effect.mapError((error) => usage(`cannot read ${projectPath}: ${error.message}`)))
900
+ if (text === undefined) {
901
+ return { _tag: "Absent", projectPath }
902
+ }
903
+ const hash = contentHash(text)
904
+ const store = yield* loadTrustStore(deps.files, configTrustPath(deps.environment))
905
+ return trustDecision(store, repo, hash) === "trusted"
906
+ ? { _tag: "Trusted", projectPath }
907
+ : { _tag: "Pending", projectPath, repo, hash, listing: renderTrustListing(text, projectPath) }
908
+ })
909
+
910
+ /** Records the reviewed content as trusted; the line that says so. */
911
+ export const acceptProject = Effect.fn("@llm4ts/shell/ConfigCommand.acceptProject")(function* (
912
+ deps: ConfigDeps,
913
+ review: Extract<ProjectReview, { readonly _tag: "Pending" }>
914
+ ): Effect.fn.Return<string, ShellUsageError> {
915
+ yield* trust(deps, review.repo, review.hash)
916
+ return `trusted: ${review.projectPath} (llm4ts reads it until its content changes)`
917
+ })
918
+
919
+ export type TrustStep =
920
+ | { readonly kind: "done"; readonly line: string }
921
+ | { readonly kind: "record" }
922
+ | { readonly kind: "ask" }
923
+ | { readonly kind: "refuse"; readonly line: string }
924
+
925
+ /** Pure: what `config trust` does with a review: nothing, record, ask, or stop unrecorded. */
926
+ export const trustStep = (
927
+ review: ProjectReview,
928
+ options: { readonly yes: boolean; readonly interactive: boolean }
929
+ ): TrustStep =>
930
+ review._tag === "Absent"
931
+ ? { kind: "done", line: `no project file at ${review.projectPath}: nothing to trust` }
932
+ : review._tag === "Trusted"
933
+ ? { kind: "done", line: `${review.projectPath} is already trusted` }
934
+ : options.yes
935
+ ? { kind: "record" }
936
+ : options.interactive
937
+ ? { kind: "ask" }
938
+ : {
939
+ kind: "refuse",
940
+ line: `not recorded: review the listing, then ${trustCommand(review.repo)} --yes, or answer on a terminal`
941
+ }
942
+
943
+ export const trustQuestion = "Trust this file? llm4ts will read it, and run what it says to run"
944
+
945
+ export const declinedLine = "not trusted: nothing was recorded"
946
+
947
+ export const runConfigUntrust = Effect.fn("@llm4ts/shell/ConfigCommand.untrust")(function* (
948
+ deps: ConfigDeps,
949
+ options: { readonly repo: string }
950
+ ): Effect.fn.Return<string, ShellUsageError> {
951
+ const removed = yield* forgetTrust(
952
+ deps.files,
953
+ configTrustPath(deps.environment),
954
+ options.repo
955
+ ).pipe(Effect.mapError((error) => usage(`cannot record trust: ${error.message}`)))
956
+ const projectPath = projectConfigPath(options.repo)
957
+ return removed
958
+ ? `no longer trusted: ${projectPath}`
959
+ : `${projectPath} was not trusted: nothing to remove`
960
+ })
961
+
962
+ const seatChoices = (environment: Environment): Array<Prompt.SelectChoice<string>> =>
963
+ coderChoices.map((choice) => ({
964
+ title:
965
+ findOnPath(choice.executable, environment) === undefined
966
+ ? choice.token
967
+ : `${choice.token} ✓ found`,
968
+ value: choice.token
969
+ }))
970
+
971
+ const askSeats = (environment: Environment) =>
972
+ Effect.gen(function* () {
973
+ const coder = yield* Prompt.run(
974
+ Prompt.Select({
975
+ message: "Which coding agent edits files?",
976
+ choices: seatChoices(environment)
977
+ })
978
+ )
979
+ const reasoner = yield* Prompt.run(
980
+ Prompt.Select({
981
+ message: "Which agent plans, reviews and judges?",
982
+ choices: seatChoices(environment)
983
+ })
984
+ )
985
+ const answers: SeatAnswers = [
986
+ { name: "LLM4TS_CODER", value: coder },
987
+ { name: "LLM4TS_REASONER", value: reasoner }
988
+ ]
989
+ return answers
990
+ })
991
+
992
+ const onTerminal = (): boolean => process.stdin.isTTY === true && process.stdout.isTTY === true
993
+
994
+ const nodeDeps = (): ConfigDeps => ({
995
+ files: nodePlainFileStore,
996
+ executor: nodeProcessExecutor,
997
+ environment: process.env,
998
+ cwd: process.cwd()
999
+ })
1000
+
1001
+ const repoFlag = Flag.String("repo").pipe(
1002
+ Flag.optional,
1003
+ Flag.withDescription(
1004
+ "Repository whose .llm4ts/config.env is the project file (defaults to the current directory)"
1005
+ )
1006
+ )
1007
+
1008
+ const repoOf = (
1009
+ repo: { readonly _tag: "Some"; readonly value: string } | { readonly _tag: "None" }
1010
+ ) => resolve(repo._tag === "Some" ? repo.value : process.cwd())
1011
+
1012
+ const targetFlags = {
1013
+ global: Flag.Boolean("global").pipe(
1014
+ Flag.withDefault(false),
1015
+ Flag.withDescription("Use the global file, whatever file the setting belongs in")
1016
+ ),
1017
+ project: Flag.Boolean("project").pipe(
1018
+ Flag.withDefault(false),
1019
+ Flag.withDescription("Use the project file, whatever file the setting belongs in")
1020
+ )
1021
+ }
1022
+
1023
+ const targetOf = (flags: {
1024
+ readonly global: boolean
1025
+ readonly project: boolean
1026
+ }): Effect.Effect<FileLayer | undefined, ShellUsageError> =>
1027
+ flags.global && flags.project
1028
+ ? Effect.fail(usage("use --global or --project, not both"))
1029
+ : Effect.succeed(flags.global ? "global" : flags.project ? "project" : undefined)
1030
+
1031
+ const showCommand = Command.make(
1032
+ "show",
1033
+ {
1034
+ name: Argument.String("name").pipe(
1035
+ Argument.optional,
1036
+ Argument.withDescription("One setting in full: each layer, its doc and grammar")
1037
+ ),
1038
+ all: Flag.Boolean("all").pipe(
1039
+ Flag.withDefault(false),
1040
+ Flag.withDescription("Also list every setting at its default, by group")
1041
+ ),
1042
+ json: Flag.Boolean("json").pipe(
1043
+ Flag.withDefault(false),
1044
+ Flag.withDescription("Every setting as JSON")
1045
+ ),
1046
+ repo: repoFlag
1047
+ },
1048
+ (config) =>
1049
+ Effect.gen(function* () {
1050
+ yield* Console.log(
1051
+ yield* runConfigShow(nodeDeps(), {
1052
+ repo: repoOf(config.repo),
1053
+ ...(config.name._tag === "Some" ? { name: config.name.value } : {}),
1054
+ all: config.all,
1055
+ json: config.json
1056
+ })
1057
+ )
1058
+ })
1059
+ ).pipe(Command.withDescription("Each setting's effective value and where it comes from"))
1060
+
1061
+ const setCommand = Command.make(
1062
+ "set",
1063
+ {
1064
+ pairs: Argument.String("NAME=value").pipe(
1065
+ Argument.variadic(),
1066
+ Argument.withDescription("Settings to write, each to the file it belongs in")
1067
+ ),
1068
+ ...targetFlags,
1069
+ repo: repoFlag
1070
+ },
1071
+ (config) =>
1072
+ Effect.gen(function* () {
1073
+ const target = yield* targetOf(config)
1074
+ yield* Console.log(
1075
+ yield* runConfigSet(nodeDeps(), {
1076
+ repo: repoOf(config.repo),
1077
+ pairs: config.pairs,
1078
+ ...(target === undefined ? {} : { target })
1079
+ })
1080
+ )
1081
+ })
1082
+ ).pipe(
1083
+ Command.withDescription(
1084
+ "Write settings to the config files; every pair is checked before anything is written"
1085
+ )
1086
+ )
1087
+
1088
+ const unsetCommand = Command.make(
1089
+ "unset",
1090
+ {
1091
+ names: Argument.String("NAME").pipe(
1092
+ Argument.variadic(),
1093
+ Argument.withDescription("Settings to remove from the config files")
1094
+ ),
1095
+ ...targetFlags,
1096
+ repo: repoFlag
1097
+ },
1098
+ (config) =>
1099
+ Effect.gen(function* () {
1100
+ const target = yield* targetOf(config)
1101
+ yield* Console.log(
1102
+ yield* runConfigUnset(nodeDeps(), {
1103
+ repo: repoOf(config.repo),
1104
+ names: config.names,
1105
+ ...(target === undefined ? {} : { target })
1106
+ })
1107
+ )
1108
+ })
1109
+ ).pipe(Command.withDescription("Remove settings from the config files"))
1110
+
1111
+ const initCommand = Command.make("init", { repo: repoFlag }, (config) =>
1112
+ Effect.gen(function* () {
1113
+ const deps = nodeDeps()
1114
+ const interactive = onTerminal()
1115
+ yield* Console.log(
1116
+ yield* runConfigInit(deps, {
1117
+ repo: repoOf(config.repo),
1118
+ ...(interactive ? { ask: askSeats(deps.environment) } : {})
1119
+ })
1120
+ )
1121
+ })
1122
+ ).pipe(
1123
+ Command.withDescription(
1124
+ "Write the LLM4TS_* settings the environment exports into the config files; on a new machine, ask coder and reasoner first"
1125
+ )
1126
+ )
1127
+
1128
+ const insideRepository = (deps: ConfigDeps, repo: string): Effect.Effect<boolean> =>
1129
+ deps.executor.run(["git", "rev-parse", "--is-inside-work-tree"], repo, {}).pipe(
1130
+ Effect.map((result) => result.exitCode === 0),
1131
+ Effect.orElseSucceed(() => false)
1132
+ )
1133
+
1134
+ const heldIn = (view: ConfigView, name: SettingName): ReadonlyArray<FileLayer> =>
1135
+ fileLayers.filter(
1136
+ (layer) =>
1137
+ lastValue(layer === "project" ? view.loaded.project : view.loaded.global, name) !== undefined
1138
+ )
1139
+
1140
+ const backChoice = { title: "back", value: undefined }
1141
+
1142
+ const askText = (deps: ConfigDeps, fact: SettingFacts, current: string | undefined) =>
1143
+ Prompt.run(
1144
+ Prompt.String({
1145
+ message:
1146
+ current === undefined
1147
+ ? `${fact.name} (${fact.grammar}; empty cancels)`
1148
+ : `${fact.name} (${fact.grammar}; Tab takes the current value, empty cancels)`,
1149
+ ...(current === undefined ? {} : { default: current }),
1150
+ validate: (answer) => {
1151
+ const value = answer.trim()
1152
+ if (value.length === 0) {
1153
+ return Effect.succeed("")
1154
+ }
1155
+ const planned = planSet(registryFacts, [assignmentOf(deps, fact.name, value)])
1156
+ return Result.isFailure(planned)
1157
+ ? Effect.fail(planned.failure.join("; "))
1158
+ : Effect.succeed(value)
1159
+ }
1160
+ })
1161
+ ).pipe(Effect.map((value) => (value.length === 0 ? undefined : value)))
1162
+
1163
+ /** The new value, or `undefined` when the question was left unanswered. */
1164
+ const askValue = (deps: ConfigDeps, fact: SettingFacts, current: string | undefined) => {
1165
+ const asked = valuePrompt(fact)
1166
+ const select = (choices: ReadonlyArray<Prompt.SelectChoice<string | undefined>>) =>
1167
+ Prompt.run(Prompt.Select({ message: `${fact.name} (${fact.grammar})`, choices }))
1168
+ switch (asked.kind) {
1169
+ case "toggle": {
1170
+ return select([{ title: "on", value: "on" }, { title: "off", value: "off" }, backChoice])
1171
+ }
1172
+ case "choices": {
1173
+ return select([
1174
+ ...asked.choices.map((choice) => ({ title: choice, value: choice })),
1175
+ backChoice
1176
+ ])
1177
+ }
1178
+ case "seat": {
1179
+ return Effect.flatMap(
1180
+ select([
1181
+ ...seatChoices(deps.environment),
1182
+ { title: "another name, typed", value: "" },
1183
+ backChoice
1184
+ ]),
1185
+ (choice) => (choice === "" ? askText(deps, fact, current) : Effect.succeed(choice))
1186
+ )
1187
+ }
1188
+ case "text": {
1189
+ return askText(deps, fact, current)
1190
+ }
1191
+ }
1192
+ }
1193
+
1194
+ const editSetting = Effect.fn("@llm4ts/shell/ConfigCommand.editSetting")(function* (
1195
+ deps: ConfigDeps,
1196
+ options: { readonly repo: string; readonly inRepository: boolean },
1197
+ fact: SettingFacts,
1198
+ record: (change: SessionChange) => void
1199
+ ) {
1200
+ const view = yield* viewOf(deps, options.repo)
1201
+ const held = heldIn(view, fact.name)
1202
+ const fileValue = (within: ConfigView, layer: FileLayer): string | undefined =>
1203
+ lastValue(layer === "project" ? within.loaded.project : within.loaded.global, fact.name)
1204
+ const note = environmentNote(view.loaded.resolution, fact.name)
1205
+ yield* Console.log(
1206
+ ["", renderSetting(view, fact.name), ...(note === undefined ? [] : [note]), ""].join("\n")
1207
+ )
1208
+ const action = yield* Prompt.run(
1209
+ Prompt.Select<SettingAction>({
1210
+ message: fact.name,
1211
+ choices: settingActions(held).map((choice) => ({ title: choice.title, value: choice.action }))
1212
+ })
1213
+ )
1214
+ if (action.kind === "back") {
1215
+ return
1216
+ }
1217
+ if (action.kind === "remove") {
1218
+ yield* Console.log(
1219
+ yield* runConfigUnset(deps, { repo: options.repo, names: [fact.name], target: action.layer })
1220
+ )
1221
+ record({ name: fact.name, layer: action.layer, kind: "removed" })
1222
+ return
1223
+ }
1224
+ const first = held[0]
1225
+ const value = yield* askValue(
1226
+ deps,
1227
+ fact,
1228
+ first === undefined ? undefined : fileValue(view, first)
1229
+ )
1230
+ if (value === undefined) {
1231
+ yield* Console.log(`${fact.name} left as it was`)
1232
+ return
1233
+ }
1234
+ const targets = saveTargets(fact, {
1235
+ inRepository: options.inRepository,
1236
+ projectRefused: distrustOf(view.loaded) !== undefined,
1237
+ held
1238
+ })
1239
+ const [only = "global", ...others] = targets
1240
+ const target =
1241
+ others.length === 0
1242
+ ? only
1243
+ : yield* Prompt.run(
1244
+ Prompt.Select<FileLayer>({
1245
+ message: "Save it for",
1246
+ choices: targets.map((layer) => ({ title: targetTitles[layer], value: layer }))
1247
+ })
1248
+ )
1249
+ yield* Console.log(
1250
+ yield* runConfigSet(deps, { repo: options.repo, pairs: [`${fact.name}=${value}`], target })
1251
+ )
1252
+ const after = yield* viewOf(deps, options.repo)
1253
+ if (fileValue(after, target) !== fileValue(view, target)) {
1254
+ record({ name: fact.name, layer: target, kind: "set" })
1255
+ }
1256
+ })
1257
+
1258
+ /**
1259
+ * The guided editor: pick a setting, see it in full, change or remove it,
1260
+ * back to the list. `name` opens that one setting and ends after it. Ends on
1261
+ * "done" or Ctrl-C with one line on what the session changed.
1262
+ */
1263
+ export const editSession = Effect.fn("@llm4ts/shell/ConfigCommand.editSession")(function* (
1264
+ deps: ConfigDeps,
1265
+ options: { readonly repo: string; readonly name?: SettingName }
1266
+ ) {
1267
+ const changes: Array<SessionChange> = []
1268
+ const record = (change: SessionChange): void => {
1269
+ changes.push(change)
1270
+ }
1271
+ const inRepository = yield* insideRepository(deps, options.repo)
1272
+ const review = yield* reviewProject(deps, options.repo)
1273
+ if (review._tag === "Pending") {
1274
+ yield* Console.log(review.listing)
1275
+ const accepted = yield* Prompt.run(
1276
+ Prompt.Confirm({ message: trustQuestion, initial: false })
1277
+ ).pipe(Effect.catchTag("QuitError", () => Effect.succeed(false)))
1278
+ yield* Console.log(
1279
+ accepted
1280
+ ? yield* acceptProject(deps, review)
1281
+ : `${declinedLine}; the editor saves to the global file only, and a save to the project file is refused`
1282
+ )
1283
+ }
1284
+ const pick = Effect.gen(function* () {
1285
+ const view = yield* viewOf(deps, options.repo)
1286
+ return yield* Prompt.run(
1287
+ Prompt.AutoComplete<SettingName | undefined>({
1288
+ message: "Which setting?",
1289
+ maxPerPage: 12,
1290
+ choices: [
1291
+ { title: "done", value: undefined, description: "leave the editor" },
1292
+ ...pickerRows(view.loaded.resolution).map((row) => ({
1293
+ title: row.title,
1294
+ value: row.name,
1295
+ description: row.description
1296
+ }))
1297
+ ]
1298
+ })
1299
+ )
1300
+ })
1301
+ const open = (name: SettingName) => {
1302
+ const fact = facts.get(name)
1303
+ return fact === undefined
1304
+ ? Effect.void
1305
+ : editSetting(deps, { repo: options.repo, inRepository }, fact, record)
1306
+ }
1307
+ const session =
1308
+ options.name === undefined
1309
+ ? Effect.gen(function* () {
1310
+ yield* Console.log(unlistedHint)
1311
+ while (true) {
1312
+ const name = yield* pick
1313
+ if (name === undefined) {
1314
+ return
1315
+ }
1316
+ yield* open(name).pipe(
1317
+ Effect.catchTag("ShellUsage", (error) => Console.error(error.message))
1318
+ )
1319
+ }
1320
+ })
1321
+ : open(options.name)
1322
+ // Ctrl-C leaves the cursor at the end of the prompt's last line.
1323
+ yield* session.pipe(Effect.catchTag("QuitError", () => Console.log("")))
1324
+ yield* Console.log(sessionSummary(changes))
1325
+ })
1326
+
1327
+ /** The editor for `repo`, on this process's files and environment. */
1328
+ export const openConfigEditor = (repo: string) => editSession(nodeDeps(), { repo })
1329
+
1330
+ const editCommand = Command.make(
1331
+ "edit",
1332
+ {
1333
+ name: Argument.String("name").pipe(
1334
+ Argument.optional,
1335
+ Argument.withDescription("Open this setting instead of the list")
1336
+ ),
1337
+ repo: repoFlag
1338
+ },
1339
+ (config) =>
1340
+ Effect.gen(function* () {
1341
+ const request = editRequest(registryFacts, {
1342
+ ...(config.name._tag === "Some" ? { name: config.name.value } : {}),
1343
+ interactive: onTerminal()
1344
+ })
1345
+ if (Result.isFailure(request)) {
1346
+ return yield* usage(request.failure)
1347
+ }
1348
+ yield* editSession(nodeDeps(), {
1349
+ repo: repoOf(config.repo),
1350
+ ...(request.success === undefined ? {} : { name: request.success })
1351
+ })
1352
+ })
1353
+ ).pipe(
1354
+ Command.withDescription(
1355
+ "Guided editor on a terminal: pick a setting, see its value and where it comes from, change or remove it"
1356
+ )
1357
+ )
1358
+
1359
+ const trustCommandLine = Command.make(
1360
+ "trust",
1361
+ {
1362
+ yes: Flag.Boolean("yes").pipe(
1363
+ Flag.withDefault(false),
1364
+ Flag.withDescription("Record without asking, after you have read the listing")
1365
+ ),
1366
+ repo: repoFlag
1367
+ },
1368
+ (config) =>
1369
+ Effect.gen(function* () {
1370
+ const deps = nodeDeps()
1371
+ const review = yield* reviewProject(deps, repoOf(config.repo))
1372
+ const step = trustStep(review, { yes: config.yes, interactive: onTerminal() })
1373
+ if (step.kind === "done") {
1374
+ return yield* Console.log(step.line)
1375
+ }
1376
+ if (review._tag !== "Pending") {
1377
+ return
1378
+ }
1379
+ yield* Console.log(review.listing)
1380
+ if (step.kind === "refuse") {
1381
+ return yield* usage(step.line)
1382
+ }
1383
+ const accepted =
1384
+ step.kind === "record" ||
1385
+ (yield* Prompt.run(Prompt.Confirm({ message: trustQuestion, initial: false })).pipe(
1386
+ Effect.catchTag("QuitError", () => Effect.succeed(false))
1387
+ ))
1388
+ yield* Console.log(accepted ? yield* acceptProject(deps, review) : declinedLine)
1389
+ })
1390
+ ).pipe(
1391
+ Command.withDescription(
1392
+ "Review the project file and accept it: llm4ts reads a project file only while its content is the one you trusted"
1393
+ )
1394
+ )
1395
+
1396
+ const untrustCommand = Command.make("untrust", { repo: repoFlag }, (config) =>
1397
+ Effect.gen(function* () {
1398
+ yield* Console.log(yield* runConfigUntrust(nodeDeps(), { repo: repoOf(config.repo) }))
1399
+ })
1400
+ ).pipe(Command.withDescription("Forget the trust recorded for this repository's project file"))
1401
+
1402
+ export const configCommand = Command.make("config", {}, () =>
1403
+ onTerminal()
1404
+ ? openConfigEditor(process.cwd())
1405
+ : Effect.fail(
1406
+ usage(
1407
+ "try `llm4ts config show`, `llm4ts config set NAME=value`, `llm4ts config unset NAME`, `llm4ts config init`, `llm4ts config trust`, or `llm4ts config edit` on a terminal"
1408
+ )
1409
+ )
1410
+ ).pipe(
1411
+ Command.withDescription(
1412
+ "The config files (~/.config/llm4ts/config.env, <repo>/.llm4ts/config.env): show, set, unset, init, edit, trust, untrust (ADR 0049)"
1413
+ ),
1414
+ Command.withSubcommands([
1415
+ showCommand,
1416
+ setCommand,
1417
+ unsetCommand,
1418
+ initCommand,
1419
+ editCommand,
1420
+ trustCommandLine,
1421
+ untrustCommand
1422
+ ])
1423
+ )