dracosh 0.7.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/alerts.js CHANGED
@@ -4,6 +4,7 @@ import path from "node:path";
4
4
  import { tmpdir } from "node:os";
5
5
  import { rm } from "node:fs/promises";
6
6
  import { fileURLToPath } from "node:url";
7
+ import { speaksLanguage, speech } from "./voice.js";
7
8
 
8
9
  // 8-bit chiptune effects generated by scripts/make-sounds.js (see `npm run sounds`)
9
10
  const SOUND_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "sounds");
@@ -15,6 +16,8 @@ const NOVELTY = new Set(["Albert", "Bad News", "Bahh", "Bells", "Boing", "Bubble
15
16
  const MAX_SPOKEN = 200; // characters: a long definition isn't read out whole
16
17
  const SPEECH_CODE = { no: "nb", nn: "nb" }; // macOS reads Norwegian as Bokmål
17
18
  const SPEAK_AFTER_MS = 500; // after the answer's chime, not over it
19
+ const VOICE_WAIT_MS = 8_000; // a natural voice that takes longer gives the word to the system's
20
+ const LATE_MS = 2_000; // a word that would come this much after its moment isn't read at all
18
21
  let voices = null;
19
22
  function voicesOnce() {
20
23
  voices ??= new Promise((resolve) =>
@@ -38,61 +41,112 @@ export async function voiceFor(lang) {
38
41
  return found.sort((a, b) => rank(a) - rank(b))[0]?.name ?? null;
39
42
  }
40
43
 
44
+ // a voice that can't work until something is changed in /settings: not asked again this run
45
+ const VOICE_STOPS = new Set(["noKey", "badKey", "noCredit", "noVoice"]);
46
+
41
47
  export function createAlerts(initial = {}) {
42
48
  const enabled = process.platform === "darwin";
43
- const config = { sound: true, volume: 0.5, speak: false, ...initial };
49
+ // voice: settings.voice (null: the system's voices); onVoiceProblem(message): told once when it stops
50
+ const config = { sound: true, volume: 0.5, speak: false, voice: null, onVoiceProblem: null, ...initial };
44
51
  // one word at a time: a newer one (or switching pronunciation off) cancels the one waiting or playing
52
+ let turn = 0;
45
53
  let waiting = null;
46
54
  let speaking = null;
55
+ let fetching = null;
56
+ let voiceDown = false;
47
57
  const hush = () => {
58
+ turn += 1;
48
59
  clearTimeout(waiting);
49
60
  speaking?.kill();
50
- waiting = speaking = null;
61
+ fetching?.abort();
62
+ waiting = speaking = fetching = null;
51
63
  };
52
64
 
53
65
  const play = (name) => {
54
66
  if (!config.sound || !enabled) return;
55
67
  execFile("afplay", ["-v", String(config.volume), path.join(SOUND_DIR, `${name}.wav`)], () => {});
56
68
  };
69
+ const playVoice = (file, done = () => {}) => {
70
+ const voiceOut = (speaking = execFile("afplay", ["-v", String(config.volume), file], done));
71
+ voiceOut.unref();
72
+ };
73
+
74
+ // the word in the system's voice: rendered to a file and played with afplay, so it follows the volume
75
+ // like the sounds do (say's own volume command is ignored by today's voices)
76
+ async function sayIt(words, lang, mine, at) {
77
+ const voice = await voiceFor(lang);
78
+ if (!voice || mine !== turn) return;
79
+ const file = path.join(tmpdir(), `dracosh-${process.pid}-${Date.now()}.aiff`);
80
+ waiting = setTimeout(() => {
81
+ waiting = null;
82
+ if (!config.speak || mine !== turn) return;
83
+ const render = (speaking = execFile("say", ["-v", voice, "-o", file, "--", words], (err) => {
84
+ if (err || speaking !== render) return void rm(file, { force: true }).catch(() => {});
85
+ playVoice(file, () => rm(file, { force: true }).catch(() => {}));
86
+ }));
87
+ render.unref();
88
+ }, Math.max(0, at - Date.now()));
89
+ waiting.unref(); // quitting right after an answer doesn't wait for the word
90
+ }
57
91
 
58
92
  return {
59
93
  play,
60
94
  configure(patch) {
95
+ // a voice picked again in /settings (a new key, say) is a new object: tried again
96
+ if ("voice" in patch && patch.voice !== config.voice) voiceDown = false;
61
97
  Object.assign(config, patch);
62
98
  if (!config.speak) hush();
63
99
  },
100
+ // an audio file played now at the set volume, whatever the settings (a voice heard while picking it)
101
+ playFile(file) {
102
+ if (!enabled) return;
103
+ hush();
104
+ playVoice(file);
105
+ },
64
106
  // a new question while you're in another window: sound plus a Notification Center banner
65
107
  ask() {
66
108
  play("ask");
67
109
  // the text goes to AppleScript as an argument, never into the script itself
68
110
  if (enabled) execFile("osascript", ["-e", "on run argv", "-e", 'display notification (item 1 of argv) with title "Dracosh"', "-e", "end run", t("alerts.newCard")], () => {});
69
111
  },
70
- // The biggest thing that just happened wins: evolution > goal > combo cheer > the answer itself.
71
- // On a plain correct answer the pitch rises with the combo and resets on a miss. Badges ring
72
- // on their own, each as its line lights up (see BadgeUnlock).
73
- // a word read aloud in its language (/settings → Pronunciation); nothing when macOS has no voice for it
74
- // Rendered to a file and played with afplay, so it follows the volume like the sounds do (say's own
75
- // volume command is ignored by today's voices).
112
+ // a word read aloud in its language (/settings → Pronunciation), after the answer's chime, not over
113
+ // it: in the natural voice when one is set and speaks the language, else in the system's (nothing
114
+ // when macOS has no voice for it). A natural voice that fails leaves the word to the system's.
76
115
  async speak(text, lang) {
77
116
  hush();
78
117
  if (!config.speak || !enabled || !text || !lang) return;
79
- const voice = await voiceFor(lang);
80
- if (!voice) return;
81
- hush(); // another word may have come meanwhile
118
+ const mine = turn;
119
+ const at = Date.now() + SPEAK_AFTER_MS;
82
120
  const words = text.replace(/\[\[|\]\]|[{}\\]/g, "").slice(0, MAX_SPOKEN); // [[…]] would be a command; cloze braces aren't words
83
- const file = path.join(tmpdir(), `dracosh-${process.pid}-${Date.now()}.aiff`);
84
- waiting = setTimeout(() => {
85
- waiting = null;
86
- if (!config.speak) return;
87
- const render = (speaking = execFile("say", ["-v", voice, "-o", file, "--", words], (err) => {
88
- if (err || speaking !== render) return void rm(file, { force: true }).catch(() => {});
89
- const voiceOut = (speaking = execFile("afplay", ["-v", String(config.volume), file], () => rm(file, { force: true }).catch(() => {})));
90
- voiceOut.unref();
91
- }));
92
- render.unref();
93
- }, SPEAK_AFTER_MS);
94
- waiting.unref(); // quitting right after an answer doesn't wait for the word
121
+ if (!words.trim()) return;
122
+ // a voice that stopped working still plays the words it made before (no request: no key needed)
123
+ if (config.voice && speaksLanguage(lang)) {
124
+ const controller = (fetching = new AbortController());
125
+ try {
126
+ const file = await speech(config.voice, words.trim(), lang, { signal: controller.signal, timeoutMs: VOICE_WAIT_MS, ...(voiceDown ? { key: null } : {}) });
127
+ if (mine !== turn) return;
128
+ fetching = null;
129
+ waiting = setTimeout(() => {
130
+ waiting = null;
131
+ if (config.speak && mine === turn) playVoice(file);
132
+ }, Math.max(0, at - Date.now()));
133
+ waiting.unref();
134
+ return;
135
+ } catch (err) {
136
+ if (controller.signal.aborted || mine !== turn) return;
137
+ fetching = null;
138
+ if (VOICE_STOPS.has(err.code) && !voiceDown) {
139
+ voiceDown = true;
140
+ config.onVoiceProblem?.(err.message);
141
+ }
142
+ if (Date.now() > at + LATE_MS) return; // the moment has passed: better quiet than late
143
+ }
144
+ }
145
+ await sayIt(words, lang, mine, at);
95
146
  },
147
+ // The biggest thing that just happened wins: evolution > goal > combo cheer > the answer itself.
148
+ // On a plain correct answer the pitch rises with the combo and resets on a miss. Badges ring
149
+ // on their own, each as its line lights up (see BadgeUnlock).
96
150
  result(result, { cheers = [], combo = 0 } = {}) {
97
151
  if (result === "wrong") return play("wrong");
98
152
  for (const kind of ["evolve", "goal", "combo"]) {
package/src/assist.js ADDED
@@ -0,0 +1,232 @@
1
+ import { ask, PROVIDERS, stream } from "./ai.js";
2
+ import { parseLine } from "./cardline.js";
3
+ import { isKnown, languageName } from "./language.js";
4
+
5
+ // What AI help writes for a card, and how it's asked. It completes what you start: the back (and an
6
+ // example) for a front you typed, in the style of the deck's own cards. Only that front and a few
7
+ // cards of the same deck are sent.
8
+ const EXAMPLES = 5; // cards of the deck shown to the model as the style to follow
9
+ const MAX_TEXT = 200; // a definition can be a sentence
10
+
11
+ const MAX_CARDS = 50; // a list asked for in one go
12
+ const AVOID = 80; // fronts of the deck the model is told not to repeat
13
+
14
+ const english = (code) => (isKnown(code) ? languageName(code, "en") : null);
15
+
16
+ // a line of text from the model, safe to put into a card line: one line, no separators of its own
17
+ const clean = (text) => String(text ?? "").replace(/\s+/g, " ").replace(/ = /g, " ").replace(/ \/\/ /g, " ").trim().slice(0, MAX_TEXT);
18
+ const answer = (text) => clean(text).replace(/;/g, ","); // one answer; ";" would split it in two
19
+
20
+ // the model's answer → { back: [...], example }; JSON when it followed the instructions, a card line
21
+ // ("cat; kitty // The cat sleeps.") when it didn't
22
+ // A reasoning model's thoughts aren't the answer: <think>…</think> goes, and so does everything before a
23
+ // lone </think> (some templates open the thoughts in the prompt)
24
+ const answerPart = (text) => {
25
+ const end = text.lastIndexOf("</think>");
26
+ return (end >= 0 ? text.slice(end + 8) : text).replace(/<think>[\s\S]*?(<\/think>|$)/g, "");
27
+ };
28
+
29
+ // the JSON object in a model's answer → the object, or null: the whole span from the first { to the
30
+ // last }, or when that isn't JSON (text with two objects), the last flat object that is
31
+ function jsonIn(text) {
32
+ const tries = [text.match(/\{[\s\S]*\}/)?.[0], ...(text.match(/\{[^{}]*\}/g) ?? []).reverse()].filter(Boolean);
33
+ for (const candidate of tries) {
34
+ try {
35
+ const data = JSON.parse(candidate);
36
+ if (data && typeof data === "object" && !Array.isArray(data)) return data;
37
+ } catch {}
38
+ }
39
+ return null;
40
+ }
41
+
42
+ export function readSuggestion(text) {
43
+ text = answerPart(String(text ?? ""));
44
+ const data = jsonIn(text);
45
+ if (data) {
46
+ const back = [data.back].flat().map(answer).filter(Boolean).slice(0, 3);
47
+ if (back.length) return { back, example: clean(data.example) };
48
+ }
49
+ const line = String(text ?? "").split(/\r?\n/).map((part) => part.trim()).find(Boolean) ?? "";
50
+ if (!line || line.startsWith("{")) return null;
51
+ const [backPart, example = ""] = line.split(" // ");
52
+ const back = backPart.split(";").map(clean).filter(Boolean).slice(0, 3);
53
+ return back.length ? { back, example: clean(example) } : null;
54
+ }
55
+
56
+ // What a deck holds, from its newest cards (the front being written, while it has none): "question"
57
+ // (most fronts ask something), "definition" (terms explained in one language) or "word". A deck in two
58
+ // languages is always words: its questions and sentences are to be translated, not answered.
59
+ export function deckKind({ front = "", languages = {}, cards = [] }) {
60
+ if (isKnown(languages.front) && isKnown(languages.back) && languages.front !== languages.back) return "word";
61
+ const recent = cards.filter((card) => !card.cloze && card.back?.length).slice(-10);
62
+ const asks = (text) => /\?\s*$/.test(text);
63
+ if (recent.length ? recent.filter((card) => asks(card.front)).length * 2 > recent.length : asks(front)) return "question";
64
+ const long = recent.length > 0 && recent.reduce((sum, card) => sum + card.back[0].length, 0) / recent.length > 30;
65
+ if ((isKnown(languages.front) && languages.front === languages.back) || long) return "definition";
66
+ return "word";
67
+ }
68
+
69
+ // `languages`: the deck's { front, back, learning } (codes, any of them unknown); `cards`: the deck's
70
+ // cards, the newest are the examples
71
+ export function suggestionPrompt({ front, languages = {}, cards = [] }) {
72
+ const frontLanguage = english(languages.front);
73
+ const backLanguage = english(languages.back);
74
+ const learning = english(languages.learning?.lang);
75
+ const examples = cards
76
+ .filter((card) => !card.cloze && card.back?.length)
77
+ .slice(-EXAMPLES)
78
+ .map((card) => JSON.stringify({ front: card.front, back: card.back, ...(card.example ? { example: card.example } : {}) }));
79
+ const withExamples = examples.some((line) => line.includes('"example"'));
80
+ const task = {
81
+ word: [
82
+ "You complete flashcards in a learner's vocabulary deck. Given the front of a card, write its back:",
83
+ "the usual translation or answer first, then up to two other accepted answers; keep each short, without",
84
+ "explanations. Add one short, natural example sentence that uses the word" + (learning ? ` in ${learning}.` : ".")
85
+ ],
86
+ definition: [
87
+ "You complete flashcards in a learner's deck of terms and their definitions. Given the term on the front,",
88
+ "write a short, accurate definition for the back: one sentence, at most about 20 words, the way a good",
89
+ "dictionary or textbook puts it, without repeating the term.",
90
+ withExamples ? "Add one short example sentence that uses the term." : 'Leave "example" empty.'
91
+ ],
92
+ question: [
93
+ "You complete flashcards in a learner's deck of questions and answers. Given the question on the front,",
94
+ "write its correct answer for the back: as short as it can be (a name, a number, a few words), then up to",
95
+ 'two other accepted forms of the same answer. Leave "example" empty.'
96
+ ]
97
+ }[deckKind({ front, languages, cards })];
98
+ const system = [
99
+ ...task,
100
+ frontLanguage || backLanguage ? `The deck's fronts are in ${frontLanguage ?? "the same language as the examples"}, its backs in ${backLanguage ?? "the same language as the examples"}.` : "Follow the languages of the deck's cards.",
101
+ "Match the deck's own cards: their articles, capitalisation and style.",
102
+ 'Reply with JSON only: {"back": ["..."], "example": "..."}'
103
+ ].join(" ");
104
+ const prompt = [examples.length ? `Cards already in the deck:\n${examples.join("\n")}` : "", `Front: ${front}`].filter(Boolean).join("\n\n");
105
+ return { system, prompt };
106
+ }
107
+
108
+ // → { back, example } or null when the answer had nothing usable
109
+ export async function suggestCard(ai, { front, languages, cards, signal }) {
110
+ const { system, prompt } = suggestionPrompt({ front, languages, cards });
111
+ // room for a reasoning model's thinking (paid only as used); a model on this computer may be slow to load
112
+ const local = PROVIDERS[ai.provider].local;
113
+ return readSuggestion(await ask(ai, { system, prompt, maxTokens: local ? 2000 : 800, signal, timeoutMs: local ? 60_000 : 20_000 }));
114
+ }
115
+
116
+ // How the deck is written, for the model: its languages and a few of its cards as JSON
117
+ function deckContext({ languages = {}, cards = [] }) {
118
+ const frontLanguage = english(languages.front);
119
+ const backLanguage = english(languages.back);
120
+ const examples = cards
121
+ .filter((card) => !card.cloze && card.back?.length)
122
+ .slice(-EXAMPLES)
123
+ .map((card) => JSON.stringify({ front: card.front, back: card.back, ...(card.example ? { example: card.example } : {}) }));
124
+ const sides = frontLanguage || backLanguage ? `Fronts are in ${frontLanguage ?? "the language of the deck's fronts"}, backs in ${backLanguage ?? "the language of the deck's backs"}.` : "";
125
+ return { sides, examples, learning: english(languages.learning?.lang) };
126
+ }
127
+
128
+ // A list of new cards on a topic: `request` as you typed it ("20 words for the kitchen")
129
+ export function listPrompt({ request, languages, cards = [] }) {
130
+ const { sides, examples, learning } = deckContext({ languages, cards });
131
+ const fronts = cards.filter((card) => !card.cloze).slice(-AVOID).map((card) => card.front);
132
+ const system = [
133
+ "You write flashcards for a learner's vocabulary deck, on the topic or list they ask for.",
134
+ `Write as many cards as asked; if no number is given, write 10; never more than ${MAX_CARDS}.`,
135
+ "One card per line, in exactly this format and nothing else:",
136
+ "front = main answer; other accepted answer // one short example sentence",
137
+ "No numbering, bullets, headings, markdown or explanations. Keep answers short.",
138
+ sides || "If the deck has cards, follow their languages; otherwise use the languages the request implies.",
139
+ learning ? `The example sentence is in ${learning}.` : "",
140
+ "Match the deck's own cards: their articles, capitalisation and style. Everyday, useful words first."
141
+ ].filter(Boolean).join(" ");
142
+ const prompt = [
143
+ examples.length ? `Cards already in the deck:\n${examples.join("\n")}` : "",
144
+ fronts.length ? `Don't repeat these fronts: ${fronts.join(", ")}` : "",
145
+ `Request: ${request}`
146
+ ].filter(Boolean).join("\n\n");
147
+ return { system, prompt };
148
+ }
149
+
150
+ // a line of the model's list → card fields, or null for anything that isn't a card
151
+ export function readListLine(line) {
152
+ const text = String(line ?? "").replace(/^\s*(?:[-*•]|\d+[.)])\s+/, "").replace(/\*\*/g, "").trim();
153
+ if (!text.includes(" = ") || /^```/.test(text)) return null;
154
+ const fields = parseLine(text);
155
+ if (!fields.front || !fields.back.length || fields.cloze) return null;
156
+ return { front: clean(fields.front), back: fields.back.map(answer).filter(Boolean).slice(0, 3), example: clean(fields.example) };
157
+ }
158
+
159
+ // Asks for a list, each card heard (`onCard`) as soon as its line is complete; thoughts of a reasoning
160
+ // model are skipped. → the number of cards
161
+ export async function suggestCards(ai, { request, languages, cards, signal, onCard }) {
162
+ const { system, prompt } = listPrompt({ request, languages, cards });
163
+ let sent = 0;
164
+ const enough = new AbortController(); // MAX_CARDS heard: the rest isn't read (or paid for)
165
+ const hear = (text, all = false) => {
166
+ const parts = answerPart(text).split(/\r\n|\r|\n/);
167
+ if (!all) {
168
+ parts.pop(); // the last line may still be coming
169
+ // prose before any </think> may be thoughts whose template opened them in the prompt: its
170
+ // cards wait for the end (a preamble like "Here are 10 words:" doesn't count)
171
+ if (!text.includes("</think>") && parts.some((line) => line.trim() && !readListLine(line) && !/:\s*$/.test(line))) return;
172
+ }
173
+ const found = parts.map(readListLine).filter(Boolean);
174
+ while (sent < found.length && sent < MAX_CARDS) onCard(found[sent++]);
175
+ if (sent >= MAX_CARDS) enough.abort();
176
+ };
177
+ const local = PROVIDERS[ai.provider].local;
178
+ try {
179
+ const whole = await stream(ai, { system, prompt, signal: signal ? AbortSignal.any([signal, enough.signal]) : enough.signal, maxTokens: local ? 6000 : 8000, timeoutMs: local ? 300_000 : 120_000, onText: (piece, sofar) => hear(sofar) });
180
+ hear(whole, true);
181
+ } catch (err) {
182
+ if (!enough.signal.aborted || signal?.aborted) throw err;
183
+ }
184
+ return sent;
185
+ }
186
+
187
+ // Checking a card that's already written: is it right? `language`: the code of the language Dracosh
188
+ // speaks, for the note. → { system, prompt }
189
+ export function checkPrompt({ card, languages, cards = [], language = "en" }) {
190
+ const { sides, examples } = deckContext({ languages, cards: cards.filter((other) => other.id !== card.id) });
191
+ const system = [
192
+ "You check one flashcard from a learner's deck for mistakes: a wrong translation, definition or answer,",
193
+ "a misspelling, a wrong article or gender, an example sentence with an error, or a question so unclear",
194
+ "that more than one answer would be right. Don't change what isn't wrong: other wording, style or a",
195
+ "missing synonym is fine.",
196
+ sides,
197
+ `Reply with JSON only. If the card is right: {"ok": true}. If not: {"ok": false, "note": "one short sentence`,
198
+ `in ${english(language) ?? "English"} on what is wrong", "front": "...", "back": ["..."], "example": "..."},`,
199
+ "the whole card with the mistake fixed, in the deck's own style."
200
+ ].filter(Boolean).join(" ");
201
+ const prompt = [examples.length ? `Other cards in the deck:\n${examples.join("\n")}` : "", `Card: ${JSON.stringify({ front: card.front, back: card.back, ...(card.example ? { example: card.example } : {}) })}`].filter(Boolean).join("\n\n");
202
+ return { system, prompt };
203
+ }
204
+
205
+ // the model's verdict → { ok: true } | { ok: false, note, fix } | null (unreadable). `fix`: the card
206
+ // as AI would have it, { front, back, example }, or null when it only says what's wrong. What the model
207
+ // gives back unchanged stays exactly as it was (not shortened or tidied).
208
+ export function readCheck(text, card) {
209
+ const data = jsonIn(answerPart(String(text ?? "")));
210
+ if (!data) return null;
211
+ if (data.ok === true || data.ok === "true") return { ok: true };
212
+ if (data.ok !== false && data.ok !== "false") return null;
213
+ const tidy = (value) => String(value).replace(/\s+/g, " ").trim();
214
+ const keep = (value, old, fresh) => (typeof value !== "string" || !value.trim() ? old : tidy(value) === tidy(old) ? old : fresh(value));
215
+ const given = (Array.isArray(data.back) ? data.back : typeof data.back === "string" ? data.back.split(";") : []).filter((value) => typeof value === "string" && value.trim());
216
+ const back = given.length ? given.map((value) => card.back.find((old) => tidy(old) === tidy(value)) ?? answer(value)).filter(Boolean) : card.back;
217
+ const fix = { front: keep(data.front, card.front, clean), back, example: data.example === undefined ? card.example ?? "" : keep(data.example, card.example ?? "", clean) };
218
+ if (data.example === "") fix.example = "";
219
+ const same = fix.front === card.front && fix.back.join("\n") === card.back.join("\n") && fix.example === (card.example ?? "");
220
+ const note = typeof data.note === "string" ? clean(data.note) : "";
221
+ if (same) return note ? { ok: false, note, fix: null } : { ok: true };
222
+ return { ok: false, note, fix };
223
+ }
224
+
225
+ // → the verdict on a card (see readCheck); throws AiError, or a plain one when the answer was unreadable
226
+ export async function checkCard(ai, { card, languages, cards, language, signal }) {
227
+ const { system, prompt } = checkPrompt({ card, languages, cards, language });
228
+ const local = PROVIDERS[ai.provider].local;
229
+ const verdict = readCheck(await ask(ai, { system, prompt, maxTokens: local ? 3000 : 1000, signal, timeoutMs: local ? 90_000 : 30_000 }), card);
230
+ if (!verdict) throw Object.assign(new Error("unreadable"), { code: "unreadable" });
231
+ return verdict;
232
+ }
package/src/cli.js CHANGED
@@ -154,7 +154,7 @@ async function main() {
154
154
 
155
155
  if (values.preview) {
156
156
  if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
157
- const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
157
+ const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak, voice: settings.voice });
158
158
  return render(React.createElement(Preview, { alerts })).waitUntilExit();
159
159
  }
160
160
 
@@ -179,7 +179,7 @@ async function main() {
179
179
  let active = deck.name; // /add can switch to your first own deck
180
180
  let mix = values.deck ? null : settings.mix; // decks practised together (/decks); --deck is one deck
181
181
  const session = createSession({ loadWords: () => loadWords(mix ?? active), loadAllWords, state, getSettings: () => current });
182
- const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
182
+ const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak, voice: settings.voice });
183
183
  const persistSettings = async (patch) => {
184
184
  current = { ...current, ...patch };
185
185
  await patchSettings(patch);
package/src/library.js CHANGED
@@ -260,7 +260,7 @@ export const frontIndex = (library, deckId) => new Map(cardsOf(library, deckId).
260
260
  // `index`: the deck's frontIndex, kept up to date here (see findDuplicate)
261
261
  // `guid`: the note in a Dracosh package it came from, so going back to Anki it's that note again;
262
262
  // `fromAnki`: it came from a note of Anki's own (see apkg.js), which Anki still has
263
- export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, guid, fromAnki = false, now = Date.now() }, index = null) {
263
+ export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, guid, fromAnki = false, ai = false, now = Date.now() }, index = null) {
264
264
  if (!library.decks.some((deck) => deck.id === deckId)) throw new Error("That deck doesn't exist.");
265
265
  const cleanFront = String(front ?? "").trim();
266
266
  const cleanBack = cleanList(back);
@@ -271,7 +271,7 @@ export function addCard(library, deckId, { front, back, example = "", tags = [],
271
271
  const duplicate = findDuplicate(library, deckId, cleanFront, index);
272
272
  if (duplicate) return { card: null, duplicate };
273
273
 
274
- const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), ...(isCloze && { cloze: true }), ...(guid && { guid: String(guid) }), ...(fromAnki && { fromAnki: true }), created: now, updated: now };
274
+ const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), ...(isCloze && { cloze: true }), ...(guid && { guid: String(guid) }), ...(fromAnki && { fromAnki: true }), ...(ai && { ai: true }), created: now, updated: now };
275
275
  if (id && library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
276
276
  library.cards.push(card);
277
277
  index?.set(frontKey(cleanFront), card);
@@ -293,10 +293,21 @@ export function updateCard(library, cardId, patch, now = Date.now()) {
293
293
  else delete card.cloze;
294
294
  if (patch.example !== undefined) card.example = String(patch.example).trim();
295
295
  if (patch.tags !== undefined) card.tags = cleanList(patch.tags);
296
+ // a card written by AI help stays marked (`ai`) until it's changed or checked
297
+ if (patch.ai) card.ai = true;
298
+ else delete card.ai;
296
299
  card.updated = now;
297
300
  return card;
298
301
  }
299
302
 
303
+ // a card written by AI help, looked over and found right: its mark goes
304
+ export function confirmCard(library, cardId) {
305
+ const card = library.cards.find((c) => c.id === cardId);
306
+ if (!card) throw new Error("That card doesn't exist.");
307
+ delete card.ai;
308
+ return card;
309
+ }
310
+
300
311
  // The quiz's word shape, so the scheduler and session keep working unchanged. A cloze card is asked one
301
312
  // gap at a time ("c1", "c2"…), whatever the deck's direction.
302
313
  export const toWords = (cards) =>
@@ -305,5 +316,6 @@ export const toWords = (cards) =>
305
316
  word: card.front,
306
317
  translations: card.back,
307
318
  example: card.example,
319
+ ...(card.ai && { ai: true }),
308
320
  ...(card.cloze && { cloze: gapsOf(card.front), directions: gapsOf(card.front).map((_, i) => `c${i + 1}`) })
309
321
  }));
package/src/lock.js CHANGED
@@ -59,6 +59,6 @@ export function acquireLock() {
59
59
  };
60
60
  process.on("exit", release);
61
61
  // with the lock held no other window writes here: temp files left by a crash can go
62
- for (const name of readdirSync(HOME)) if (/^(library|state|settings)\.json\.\d+\.tmp$/.test(name)) rmSync(join(HOME, name), { force: true });
62
+ for (const name of readdirSync(HOME)) if (/^(library|state|settings|keys)\.json\.\d+\.tmp$/.test(name)) rmSync(join(HOME, name), { force: true });
63
63
  return release;
64
64
  }
package/src/manage.js CHANGED
@@ -2,7 +2,7 @@ import { language as uiLanguage, t } from "./i18n.js";
2
2
  import { backupNow } from "./backup.js";
3
3
  import { seedLibrary } from "./starter.js";
4
4
  import { gapsOf } from "./cardline.js";
5
- import { addCard, cardsOf, createDeck, emptyLibrary, emptyOldTrash, findDeck, findDuplicate, moveCards as moveLibraryCards, removeDeck, renameDeck as renameLibraryDeck, restoreDeck, trashCards, setDirections as setLibraryDirections, setLanguages as setLibraryLanguages, trashDeck, trashedUntil, typedSides, updateCard } from "./library.js";
5
+ import { addCard, cardsOf, confirmCard, createDeck, emptyLibrary, emptyOldTrash, findDeck, findDuplicate, moveCards as moveLibraryCards, removeDeck, renameDeck as renameLibraryDeck, restoreDeck, trashCards, setDirections as setLibraryDirections, setLanguages as setLibraryLanguages, trashDeck, trashedUntil, typedSides, updateCard } from "./library.js";
6
6
  import { firstWords } from "./firstwords.js";
7
7
  import { applyImport, planImport } from "./importer.js";
8
8
  import { deckLanguages, homeLanguages, languageName, learningSide } from "./language.js";
@@ -194,8 +194,19 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
194
194
  return { added, duplicates };
195
195
  },
196
196
 
197
+ // a card written by AI help, checked: it loses its ✦
198
+ async confirmCardIn(deckName, cardId) {
199
+ const library = await load();
200
+ const deck = await deckNamed(library, deckName);
201
+ if (!cardsOf(library, deck.id).some((card) => card.id === cardId)) throw new Error("That card doesn't exist.");
202
+ const card = confirmCard(library, cardId);
203
+ await save(library);
204
+ return card;
205
+ },
206
+
197
207
  // A card fixed right after adding it (↑ in /add) → { card, staleKeys }: the progress keys it no
198
208
  // longer has (a gap removed, a cloze card turned plain or the other way round), for the session to drop
209
+
199
210
  async updateCardIn(deckName, cardId, fields) {
200
211
  const library = await load();
201
212
  const deck = await deckNamed(library, deckName);
@@ -263,7 +274,7 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
263
274
  // /cards: a deck's cards as they are now, in the order they were added
264
275
  async cardsIn(deckName) {
265
276
  const library = await load();
266
- return cardsOf(library, (await deckNamed(library, deckName)).id).map(({ id, front, back, example, cloze }) => ({ id, front, back, example: example ?? "", cloze: Boolean(cloze) }));
277
+ return cardsOf(library, (await deckNamed(library, deckName)).id).map(({ id, front, back, example, cloze, ai }) => ({ id, front, back, example: example ?? "", cloze: Boolean(cloze), ai: Boolean(ai) }));
267
278
  },
268
279
 
269
280
  // /cards → Delete: into the trash with their progress (`progressOf`, from the session); the deck stays,
@@ -352,4 +363,4 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
352
363
 
353
364
  // the app's own: reads and writes ~/.dracosh
354
365
  const actions = libraryActions();
355
- export const { allDecks, ownDecks, startDeck, startFirstWords, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, previewImport, importCards, renameDeck, deleteDeck, trash, restoreFromTrash, cardsIn, deleteCards, moveCards, mergeDecks, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
366
+ export const { allDecks, ownDecks, startDeck, startFirstWords, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, confirmCardIn, updateCardIn, previewImport, importCards, renameDeck, deleteDeck, trash, restoreFromTrash, cardsIn, deleteCards, moveCards, mergeDecks, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
package/src/settings.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { normalizeAi } from "./ai.js";
2
+ import { normalizeVoice } from "./voice.js";
1
3
  import { LANGUAGES, systemLanguage, t } from "./i18n.js";
2
4
 
3
- export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, speak: false, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null, mix: null, homeLanguage: null, learningLanguage: null };
5
+ export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, speak: false, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null, mix: null, homeLanguage: null, learningLanguage: null, ai: null, voice: null };
4
6
 
5
7
  export const INTERVALS = [60_000, 120_000, 300_000, 600_000, 900_000, 1_200_000, 1_800_000, 2_700_000, 3_600_000];
6
8
  export const GOALS = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200];
@@ -46,6 +48,8 @@ export function normalizeSettings(raw = {}) {
46
48
  // the language you speak and the one you're learning, from the welcome (codes; null: not said)
47
49
  homeLanguage: isLanguage(raw.homeLanguage) ? raw.homeLanguage : null,
48
50
  learningLanguage: isLanguage(raw.learningLanguage) ? raw.learningLanguage : null,
51
+ ai: normalizeAi(raw.ai), // AI help (/settings): provider, model and address; the key is kept apart
52
+ voice: normalizeVoice(raw.voice), // natural voice (/settings → Voice); null: the system's voices
49
53
  language: typeof raw.language === "string" && Object.hasOwn(LANGUAGES, raw.language) ? raw.language : systemLanguage() // until picked in /settings, the system's
50
54
  };
51
55
  }