Open History to see the last commit
1/**
2 * A session setting a plugin declares, for example the model or the
3 * thinking level. Hosts render it from this description, for example a
4 * picker in the CLI. `serveAcp` does not send config options yet. A change
5 * applies at the next turn.
6 */
7export type ConfigOption =
8 | {
9 type: 'select'
10 options: ReadonlyArray<string>
11 default: string
12 description?: string
13 /**
14 * A kind for hosts that group settings, for example `'model'` or
15 * `'thought_level'`. `serveAcp` does not send it yet.
16 */
17 category?: string
18 }
19 | { type: 'boolean'; default: boolean; description?: string }
20 | { type: 'text'; default: string; description?: string }
21 | {
22 type: 'number'
23 default: number
24 min?: number
25 max?: number
26 description?: string
27 }
28
29type Without<T, K extends keyof T> = Omit<T, K>
30type Option<TType extends ConfigOption['type']> = Extract<
31 ConfigOption,
32 { type: TType }
33>
34
35/** Helpers to declare {@link ConfigOption}s. */
36export const configOption = {
37 select: (option: Without<Option<'select'>, 'type'>): Option<'select'> => {
38 if (!option.options.includes(option.default)) {
39 throw new Error(
40 `configOption.select: the default "${option.default}" is not an option.`,
41 )
42 }
43 return { type: 'select', ...option }
44 },
45 boolean: (option: Without<Option<'boolean'>, 'type'>): Option<'boolean'> => ({
46 type: 'boolean',
47 ...option,
48 }),
49 text: (option: Without<Option<'text'>, 'type'>): Option<'text'> => ({
50 type: 'text',
51 ...option,
52 }),
53 number: (option: Without<Option<'number'>, 'type'>): Option<'number'> => ({
54 type: 'number',
55 ...option,
56 }),
57}
58
59/** Check a value for an option. Returns the value, or throws with a reason. */
60export function checkConfigValue(
61 key: string,
62 option: ConfigOption,
63 value: unknown,
64): unknown {
65 const fail = (expected: string): never => {
66 throw new Error(
67 `Config "${key}" expects ${expected}, got ${JSON.stringify(value)}.`,
68 )
69 }
70 switch (option.type) {
71 case 'select':
72 if (typeof value !== 'string' || !option.options.includes(value)) {
73 fail(`one of ${option.options.join(', ')}`)
74 }
75 return value
76 case 'boolean':
77 if (typeof value !== 'boolean') fail('true or false')
78 return value
79 case 'text':
80 if (typeof value !== 'string') fail('text')
81 return value
82 case 'number': {
83 if (typeof value !== 'number' || !Number.isFinite(value))
84 return fail('a number')
85 if (option.min !== undefined && value < option.min)
86 fail(`a number >= ${option.min}`)
87 if (option.max !== undefined && value > option.max)
88 fail(`a number <= ${option.max}`)
89 return value
90 }
91 }
92}