dracosh 0.6.0 → 0.8.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/src/ui/Ai.js ADDED
@@ -0,0 +1,284 @@
1
+ import { Fragment, useEffect, useRef, useState } from "react";
2
+ import { Box, useInput } from "ink";
3
+ import { t } from "../i18n.js";
4
+ import { aiLabel, checkAi, cleanUrl, findKey, forgetKey, isSmallModel, isUrl, listModels, maskKey, PROVIDERS, providerName, saveKey, urlOf } from "../ai.js";
5
+ import { fold } from "../judge.js";
6
+ import { AnswerInput } from "./AnswerInput.js";
7
+ import { Choice, choiceHints } from "./Choice.js";
8
+ import { cutToWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
9
+
10
+ const ORDER = ["anthropic", "openai", "openrouter", "ollama", "lmstudio", "custom"];
11
+ const SHOWN = 8; // models listed at a time
12
+ const look = (text) => fold(text.toLowerCase());
13
+
14
+ // /settings → AI help: where it comes from (provider, the address for "other"), the key, the model, then
15
+ // a tiny request to check they work together; only then is anything saved. `current`: settings.ai.
16
+ // onSave(ai | null) keeps the choice (null: AI off). Esc goes back a step, from the first one it leaves.
17
+ export function AiSetup({ current, onSave, onClose, note = t("ai.note") }) {
18
+ const panel = usePanelWidth();
19
+ const [step, setStep] = useState("provider");
20
+ const [selected, setSelected] = useState(() => Math.max(0, ORDER.indexOf(current?.provider)));
21
+ const [draft, setDraft] = useState(current ?? {}); // { provider, url?, model }
22
+ const [key, setKey] = useState(null); // { key, from: "env" | "saved" | "typed", env? }
23
+ const [models, setModels] = useState(null);
24
+ const [query, setQuery] = useState("");
25
+ const [error, setError] = useState("");
26
+ const [message, setMessage] = useState("");
27
+ const history = useRef([]);
28
+ const job = useRef(0); // a newer step makes an older request's answer stale
29
+
30
+ // Esc goes back along the steps taken; going to a step taken before cuts the way back to it, and the
31
+ // passing steps (checking, failed) are never gone back to
32
+ const go = (next, pick = 0) => {
33
+ const at = history.current.indexOf(next);
34
+ if (at >= 0) history.current = history.current.slice(0, at);
35
+ else if (step !== next && step !== "checking" && step !== "failed") history.current.push(step);
36
+ setError("");
37
+ setMessage("");
38
+ setSelected(pick);
39
+ setStep(next);
40
+ };
41
+ const back = () => {
42
+ job.current += 1;
43
+ setError("");
44
+ setMessage("");
45
+ const last = history.current.pop();
46
+ if (!last) return onClose();
47
+ setSelected(last === "provider" ? Math.max(0, ORDER.indexOf(draft.provider)) : 0);
48
+ setStep(last);
49
+ };
50
+ // after a step's answer arrives: still the step it was asked on?
51
+ const stillOn = () => {
52
+ const mine = ++job.current;
53
+ return () => mine === job.current;
54
+ };
55
+
56
+ const preset = PROVIDERS[draft.provider];
57
+
58
+ async function pickProvider(index) {
59
+ if (index === ORDER.length) {
60
+ onSave(null);
61
+ return onClose(t("ai.turnedOff"));
62
+ }
63
+ const provider = ORDER[index];
64
+ const same = current?.provider === provider;
65
+ // a local server moved to another port keeps its address
66
+ const next = { provider, url: same ? current.url : undefined, model: same ? current.model : PROVIDERS[provider].model };
67
+ setDraft(next);
68
+ if (provider === "custom") return go("url");
69
+ if (PROVIDERS[provider].local) return setKey(null), loadModels(next, null);
70
+ await askForKey(next);
71
+ }
72
+
73
+ // the key: the environment's is used as it is, a saved one can stay, be replaced or go
74
+ async function askForKey(next) {
75
+ const fresh = stillOn();
76
+ const found = await findKey(next.provider, urlOf(next));
77
+ if (!fresh()) return;
78
+ setKey(found);
79
+ if (found?.from === "env") return loadModels(next, found);
80
+ go(found ? "keep-key" : "key");
81
+ }
82
+
83
+ async function loadModels(target = draft, withKey = key) {
84
+ go("models");
85
+ const fresh = stillOn();
86
+ setModels(null);
87
+ setQuery("");
88
+ try {
89
+ const list = await listModels(target, { key: withKey?.key ?? null });
90
+ if (!fresh()) return;
91
+ // where you pay per use, the small, cheap models come first
92
+ const sorted = !PROVIDERS[target.provider].needsKey ? list : [...list.filter(isSmallModel), ...list.filter((name) => !isSmallModel(name))];
93
+ setModels(sorted);
94
+ setSelected(Math.max(0, sorted.indexOf(target.model ?? PROVIDERS[target.provider].model)));
95
+ } catch (err) {
96
+ if (!fresh()) return;
97
+ // a key or an address to fix: back where it's typed, the reason with it
98
+ const fixAt = ["badKey", "noKey"].includes(err.code) && withKey?.from !== "env" && !PROVIDERS[target.provider].local ? "key" : err.code === "noApi" && target.provider === "custom" ? "url" : null;
99
+ setModels([]);
100
+ if (fixAt) {
101
+ const at = history.current.indexOf(fixAt);
102
+ if (at >= 0) history.current = history.current.slice(0, at);
103
+ setSelected(0);
104
+ setStep(fixAt);
105
+ }
106
+ setError(err.message);
107
+ }
108
+ }
109
+
110
+ async function check(model) {
111
+ const chosen = { provider: draft.provider, model, ...(draft.url ? { url: cleanUrl(draft.url) } : {}) };
112
+ setDraft(chosen);
113
+ go("checking");
114
+ const fresh = stillOn();
115
+ try {
116
+ await checkAi(chosen, { key: key?.key ?? null });
117
+ if (!fresh()) return;
118
+ if (key?.from === "typed") await saveKey(chosen.provider, key.key, urlOf(chosen));
119
+ onSave(chosen);
120
+ onClose(t("ai.ready", { label: aiLabel(chosen) }));
121
+ } catch (err) {
122
+ if (!fresh()) return;
123
+ setError(err.message);
124
+ setStep("failed");
125
+ setSelected(0);
126
+ }
127
+ }
128
+
129
+ const found = (models ?? []).filter((name) => !query || look(name).includes(look(query)));
130
+ const rows = [...found, null]; // null: type a name
131
+
132
+ useInput((input, key) => {
133
+ if ((step === "checking" || (step === "models" && models === null)) && key.escape) return back();
134
+ if (step !== "models" || models === null) return;
135
+ if (key.escape) return query ? (setQuery(""), setSelected(0)) : back();
136
+ if (key.upArrow) return setSelected((i) => Math.max(0, i - 1));
137
+ if (key.downArrow) return setSelected((i) => Math.min(rows.length - 1, i + 1));
138
+ if (key.return) return rows[selected] === null ? go("model-name") : check(rows[selected]);
139
+ if (key.backspace || key.delete) return query && (setQuery((q) => q.slice(0, -1)), setSelected(0));
140
+ const text = input.replace(/[\u0000-\u001f\u007f]/g, "");
141
+ if (text && !key.ctrl && !key.meta) {
142
+ setQuery((q) => q + text);
143
+ setSelected(0);
144
+ }
145
+ });
146
+
147
+ const problem = error && html`<${Box} marginTop=${1}><${Text} color=${theme.bad}>${error}<//><//>`;
148
+ const frame = (title, body, hints, { errorAbove = false } = {}) => html`
149
+ <${Fragment}>
150
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${panel}>
151
+ <${Text} bold color=${theme.accent}>${title}<//>
152
+ ${errorAbove && problem}
153
+ ${body}
154
+ ${message && html`<${Box} marginTop=${1}><${Text} color=${theme.good}>${message}<//><//>`}
155
+ ${!errorAbove && problem}
156
+ <//>
157
+ <${Box} paddingX=${1}><${KeyHints} text=${hints} /><//>
158
+ <//>
159
+ `;
160
+ const name = providerName(draft.provider);
161
+ const keyTitle = draft.provider === "custom" ? t("ai.keyTitleCustom") : t("ai.keyTitle", { provider: name });
162
+
163
+ if (step === "provider") {
164
+ const options = ORDER.map((provider) => ({ label: providerName(provider), note: t(`ai.providers.${provider}`) }));
165
+ if (current) options.push({ label: t("ai.turnOff"), danger: true });
166
+ return frame(
167
+ t("ai.title"),
168
+ html`
169
+ <${Box} flexDirection="column">
170
+ <${Text} dimColor>${note}<//>
171
+ ${current && html`<${Text} dimColor>${t("ai.now", { label: aiLabel(current) })}<//>`}
172
+ <${Box} marginTop=${1}><${Choice} options=${options} selected=${selected} onMove=${setSelected} onPick=${(i) => pickProvider(i).catch((err) => setError(err.message))} onCancel=${() => onClose()} /><//>
173
+ <//>
174
+ `,
175
+ choiceHints("back")
176
+ );
177
+ }
178
+
179
+ if (step === "url")
180
+ return frame(
181
+ t("ai.urlTitle"),
182
+ html`
183
+ <${Box} flexDirection="column">
184
+ <${Text} dimColor>${t("ai.urlNote")}<//>
185
+ <${Box} marginTop=${1}><${AnswerInput} key="url" plain escLeaves initial=${draft.url ?? ""} onChange=${() => setError("")} onExit=${back} onSubmit=${(text) => {
186
+ if (!isUrl(text)) return setError(t("ai.badUrl"));
187
+ const next = { ...draft, url: cleanUrl(text) };
188
+ setDraft(next);
189
+ askForKey(next).catch((err) => setError(err.message));
190
+ }} /><//>
191
+ <//>
192
+ `,
193
+ t("keyHints.importName")
194
+ );
195
+
196
+ if (step === "keep-key") {
197
+ const options = [{ label: t("ai.keepKey"), note: maskKey(key.key) }, { label: t("ai.newKey") }, { label: t("ai.forgetKey"), danger: true }];
198
+ return frame(
199
+ keyTitle,
200
+ html`<${Box} marginTop=${1}><${Choice} options=${options} selected=${selected} onMove=${setSelected} onPick=${(i) => {
201
+ if (i === 0) return loadModels();
202
+ if (i === 1) return go("key");
203
+ forgetKey(draft.provider, urlOf(draft)).then(() => {
204
+ setKey(null);
205
+ go("key");
206
+ setMessage(t("ai.keyForgotten", { provider: name }));
207
+ }, (err) => setError(err.message));
208
+ }} onCancel=${back} /><//>`,
209
+ choiceHints("back")
210
+ );
211
+ }
212
+
213
+ if (step === "key") {
214
+ const optional = !preset?.needsKey;
215
+ return frame(
216
+ keyTitle,
217
+ html`
218
+ <${Box} flexDirection="column">
219
+ <${Text} dimColor>${optional ? t("ai.keyOptional") : t("ai.keyNote", { env: preset.keyEnv, site: preset.site })}<//>
220
+ <${Box} marginTop=${1}><${AnswerInput} key="api-key" plain secret escLeaves onChange=${() => (setError(""), setMessage(""))} onExit=${back} onSubmit=${(text) => {
221
+ const typed = text.trim();
222
+ if (!typed && !optional) return setError(t("ai.needKey"));
223
+ const next = typed ? { key: typed, from: "typed" } : null;
224
+ setKey(next);
225
+ loadModels(draft, next);
226
+ }} /><//>
227
+ <//>
228
+ `,
229
+ t("keyHints.importName")
230
+ );
231
+ }
232
+
233
+ if (step === "model-name")
234
+ return frame(
235
+ t("ai.modelTitle"),
236
+ html`
237
+ <${Box} flexDirection="column">
238
+ <${Text} dimColor>${t("ai.modelNameNote", { provider: name })}<//>
239
+ <${Box} marginTop=${1}><${AnswerInput} key="model-name" plain escLeaves initial=${draft.model ?? ""} onChange=${() => setError("")} onExit=${back} onSubmit=${(text) => (text.trim() ? check(text.trim()) : setError(t("ai.needModel")))} /><//>
240
+ <//>
241
+ `,
242
+ t("keyHints.importName")
243
+ );
244
+
245
+ if (step === "models") {
246
+ const top = Math.max(0, Math.min(selected - Math.floor(SHOWN / 2), rows.length - SHOWN));
247
+ return frame(
248
+ t("ai.modelTitle"),
249
+ html`
250
+ <${Box} flexDirection="column">
251
+ <${Text} dimColor>${[key?.from === "env" && t("ai.keyFromEnv", { env: key.env }), preset.local ? t("ai.localNote", { url: urlOf(draft) }) : t("ai.modelNote")].filter(Boolean).join(" ")}<//>
252
+ ${models?.length === 0 && !error && html`<${Box} marginTop=${1}><${Text}>${preset.local ? t("ai.noModelsLocal") : t("ai.noModels")}<//><//>`}
253
+ ${models === null
254
+ ? html`<${Box} marginTop=${1}><${Text} dimColor>${t("ai.loadingModels", { provider: name })}<//><//>`
255
+ : html`
256
+ <${Box} flexDirection="column" marginTop=${1}>
257
+ ${(models.length > SHOWN || query) && html`<${Box}><${Box} flexShrink=${0}><${Text} dimColor>${t("languages.search")} <//><//><${Text} wrap="truncate-start">${query}<//><${Box} flexShrink=${0}><${Text} inverse> <//><//><//>`}
258
+ <${Text} dimColor>${top > 0 ? " ↑" : " "}<//>
259
+ ${rows.slice(top, top + SHOWN).map((row, i) => {
260
+ const on = top + i === selected;
261
+ return html`<${Text} key=${row ?? "type"} color=${on ? theme.accent : row === null ? theme.good : undefined} bold=${on} wrap="truncate-end">${on ? "❯" : " "} ${row === null ? t("ai.typeModel") : cutToWidth(row, panel - 12)} ${row && row === current?.model && draft.provider === current?.provider ? html`<${Text} dimColor>· ${t("ai.current")}<//>` : row && preset.needsKey && isSmallModel(row) ? html`<${Text} dimColor>· ${t("ai.small")}<//>` : ""}<//>`;
262
+ })}
263
+ <${Text} dimColor>${top + SHOWN < rows.length ? " ↓" : " "}<//>
264
+ <//>
265
+ `}
266
+ <//>
267
+ `,
268
+ models && models.length > SHOWN ? t("keyHints.modelPick") : choiceHints("back")
269
+ );
270
+ }
271
+
272
+ if (step === "checking")
273
+ return frame(t("ai.modelTitle"), html`<${Box} marginTop=${1}><${Text} dimColor>${t("ai.checking", { label: aiLabel(draft) })}<//><//>`, t("keyHints.back"));
274
+
275
+ // failed: what now
276
+ // a key from the environment is changed there, not here
277
+ const options = [{ label: t("ai.tryAgain") }, { label: t("ai.otherModel") }, ...(preset?.local || key?.from === "env" ? [] : [{ label: t("ai.otherKey") }])];
278
+ return frame(
279
+ t("ai.failedTitle", { label: aiLabel(draft) }),
280
+ html`<${Box} marginTop=${1}><${Choice} options=${options} selected=${selected} onMove=${setSelected} onPick=${(i) => (i === 0 ? check(draft.model) : i === 1 ? loadModels() : go("key"))} onCancel=${back} /><//>`,
281
+ choiceHints("back"),
282
+ { errorAbove: true }
283
+ );
284
+ }
@@ -25,10 +25,27 @@ const args = (value) => value.trim().split(/\s+/).slice(1).join(" ");
25
25
  // Answer line with a movable cursor (←/→, Ctrl+A/E). Typing "/" opens a command palette:
26
26
  // ↑/↓ choose, Tab completes, Enter runs.
27
27
  // `commandOnly` is the between-questions variant: it starts at "/" and Esc or erasing the "/" closes it.
28
- // `plain` is a text field with no commands at all ("and/or" is just text there).
28
+ // `plain` is a text field with no commands at all ("and/or" is just text there); `escLeaves`: Esc leaves
29
+ // it at once, typed text and all, instead of clearing it first (a name being changed, a path).
29
30
  // `onChange` hears every edit; `onRecall` is ↑ on an empty plain field (/add brings back the last card);
30
31
  // `onPaste` takes a paste of several lines, as it came (/add reviews them as cards); anything else is typed in.
31
- export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onChange, onRecall, onPaste, commands = COMMANDS, initial = "", commandOnly = false, plain = false }) {
32
+ // A card line's next part from the cursor: front → back → example → front again. A part that isn't
33
+ // there yet is started: "kot" → "kot = ", "kot = cat" → "kot = cat // ". → { value, cursor }
34
+ export function nextPart(value, cursor) {
35
+ const end = (text) => ({ value: text, cursor: text.length });
36
+ const eq = value.indexOf(" = ");
37
+ if (eq < 0) return end(`${value.trimEnd()} = `);
38
+ const example = value.indexOf(" // ", eq + 3);
39
+ if (cursor < eq + 3) return { value, cursor: eq + 3 };
40
+ if (example < 0) return end(`${value.trimEnd()} // `);
41
+ if (cursor < example + 4) return { value, cursor: example + 4 };
42
+ return { value, cursor: 0 };
43
+ }
44
+
45
+ // `cardLine`: the field holds a card line ("front = back // example"), and Tab goes to its next part,
46
+ // adding the " = " or " // " that starts it. `secret`: shown as dots (an API key). `ghost`: a suggestion
47
+ // shown dimmed after the text while the cursor is at its end; Tab or → takes it in (`onGhost` hears that)
48
+ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onChange, onRecall, onPaste, commands = COMMANDS, initial = "", commandOnly = false, plain = false, escLeaves = false, cardLine = false, secret = false, ghost = "", onGhost }) {
32
49
  const [value, setValue] = useState(initial);
33
50
  const [cursor, setCursor] = useState(initial.length);
34
51
  const [selected, setSelected] = useState(0);
@@ -54,7 +71,7 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onC
54
71
  usePaste(paste);
55
72
 
56
73
  useInput((input, key) => {
57
- if (key.escape) return commandOnly ? onCancel() : value ? edit("") : onExit();
74
+ if (key.escape) return commandOnly ? onCancel() : value && !escLeaves ? edit("") : onExit();
58
75
  if (key.return) {
59
76
  // no command starts like this: on a card it's simply the answer (some answers begin with "/")
60
77
  if (!isCommand || (!matches.length && !commandOnly)) return onSubmit(value);
@@ -62,6 +79,16 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onC
62
79
  edit("");
63
80
  return onCommand(matches[pick]?.name ?? token, rest.join(" "));
64
81
  }
82
+ const atEnd = cursor === value.length;
83
+ if (ghost && atEnd && (key.tab || key.rightArrow)) {
84
+ edit(value + ghost);
85
+ return onGhost?.();
86
+ }
87
+ if (key.tab && cardLine) {
88
+ if (!value.trim()) return;
89
+ const next = nextPart(value, cursor);
90
+ return next.value === value ? setCursor(next.cursor) : edit(next.value, next.cursor);
91
+ }
65
92
  if (key.tab) return matches.length ? edit(`${matches[pick].name}${args(value) ? ` ${args(value)}` : ""}`) : undefined;
66
93
  if (key.upArrow && !value && onRecall) return onRecall();
67
94
  if (key.upArrow) return setSelected(Math.max(0, pick - 1));
@@ -81,14 +108,15 @@ export function AnswerInput({ onSubmit, onCommand, onExit, onEdit, onCancel, onC
81
108
  if (input) paste(input);
82
109
  });
83
110
 
84
- const before = value.slice(0, cursor);
85
- const at = value[cursor] ?? " ";
86
- const after = value.slice(cursor + 1);
111
+ const shown = secret ? "•".repeat(value.length) : value;
112
+ const before = shown.slice(0, cursor);
113
+ const at = shown[cursor] ?? " ";
114
+ const after = shown.slice(cursor + 1);
87
115
  return html`
88
116
  <${Box} flexDirection="column">
89
117
  <${Box}>
90
118
  <${Box} flexShrink=${0}><${Text} color=${theme.accent}>❯ <//><//>
91
- <${Text}>${before}<${Text} inverse>${at}<//>${after}<//>
119
+ <${Text}>${before}${ghost && cursor === value.length ? html`<${Text} dimColor><${Text} inverse>${ghost[0]}<//>${ghost.slice(1)}<//>` : html`<${Text} inverse>${at}<//>`}${after}<//>
92
120
  <//>
93
121
  ${matches.length > 0 && html`<${Palette} matches=${matches} selected=${pick} />`}
94
122
  ${isCommand && matches.length === 0 && html`<${Box} marginTop=${1}>${commandOnly ? html`<${Text} color=${theme.bad}>${t("input.unknownCommand")}<//>` : html`<${Text} dimColor>${t("input.notACommand")}<//>`}<//>`}