dracosh 0.7.0 → 0.9.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,95 +4,146 @@ 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 { createNotifier } from "./notify.js";
8
+ import { createPlayer, findPlayers } from "./player.js";
9
+ import { createSpeech } from "./speech.js";
10
+ import { speaksLanguage, speech } from "./voice.js";
7
11
 
8
12
  // 8-bit chiptune effects generated by scripts/make-sounds.js (see `npm run sounds`)
9
13
  const SOUND_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "assets", "sounds");
10
14
  const LADDER_STEPS = 6; // correct-0 … correct-5: the pitch climbs with your combo
11
15
 
12
- // Voices macOS has for a language (`say -v ?`), the novelty ones left out, the best first: a premium or
13
- // enhanced voice, then a plain named one. Read once, when the first word is spoken.
14
- const NOVELTY = new Set(["Albert", "Bad News", "Bahh", "Bells", "Boing", "Bubbles", "Cellos", "Good News", "Jester", "Organ", "Superstar", "Trinoids", "Whisper", "Wobble", "Zarvox", "Fred", "Junior", "Kathy", "Ralph", "Grandma", "Grandpa", "Rocko"]);
15
16
  const MAX_SPOKEN = 200; // characters: a long definition isn't read out whole
16
- const SPEECH_CODE = { no: "nb", nn: "nb" }; // macOS reads Norwegian as Bokmål
17
17
  const SPEAK_AFTER_MS = 500; // after the answer's chime, not over it
18
- let voices = null;
19
- function voicesOnce() {
20
- voices ??= new Promise((resolve) =>
21
- execFile("say", ["-v", "?"], (err, out) =>
22
- resolve(err ? [] : String(out).split("\n").map((line) => line.match(/^(.+?)\s+([a-z]{2,3})_([A-Za-z0-9]+)\s+#/)).filter(Boolean).map(([, name, lang, region]) => ({ name: name.trim(), lang, region })))
23
- )
24
- );
25
- return voices;
26
- }
27
- // the region most learners mean (English from the US or Britain, not India; Chinese from the mainland)
28
- const REGIONS = { en: ["US", "GB"], zh: ["CN", "TW"], pt: ["PT", "BR"], es: ["ES", "MX"], fr: ["FR"], de: ["DE"], nl: ["NL"] };
29
- const rank = (voice) => {
30
- const regions = REGIONS[voice.lang] ?? [];
31
- const region = regions.includes(voice.region) ? regions.indexOf(voice.region) : regions.length;
32
- const quality = /\((Premium|Enhanced)\)/.test(voice.name) ? 0 : /\(/.test(voice.name) ? 2 : 1;
33
- return region * 10 + quality;
18
+ const VOICE_WAIT_MS = 8_000; // a natural voice that takes longer gives the word to the system's
19
+ const LATE_MS = 2_000; // a word that would come this much after its moment isn't read at all
20
+
21
+ // a voice plays in the background: quitting right after an answer doesn't wait for it (the pipes would
22
+ // hold the app open too)
23
+ const runInBackground = (command, args, done) => {
24
+ const child = execFile(command, args, done);
25
+ for (const handle of [child, child.stdin, child.stdout, child.stderr]) handle?.unref?.();
26
+ return child;
34
27
  };
35
- export async function voiceFor(lang) {
36
- const code = SPEECH_CODE[lang] ?? lang;
37
- const found = (await voicesOnce()).filter((voice) => voice.lang === code && !NOVELTY.has(voice.name));
38
- return found.sort((a, b) => rank(a) - rank(b))[0]?.name ?? null;
39
- }
28
+ let spoken = 0; // numbers the words' temp files, so two in the same millisecond never share one
40
29
 
41
- export function createAlerts(initial = {}) {
42
- const enabled = process.platform === "darwin";
43
- const config = { sound: true, volume: 0.5, speak: false, ...initial };
30
+ // a voice that can't work until something is changed in /settings: not asked again this run
31
+ const VOICE_STOPS = new Set(["noKey", "badKey", "noCredit", "noVoice"]);
32
+
33
+ // player, notifier: what plays the sounds and shows notifications; voicePlayer: what plays a voice's
34
+ // file (a natural voice's is an mp3); system: the system's voices, null without any (tests give their own)
35
+ export function createAlerts({
36
+ player = createPlayer(),
37
+ voicePlayer = createPlayer({ players: findPlayers({ mp3: true }), run: runInBackground }),
38
+ system = createSpeech({ run: runInBackground }),
39
+ notifier = createNotifier(),
40
+ ...initial
41
+ } = {}) {
42
+ // espeak-ng's .wav plays like the sounds (aplay included); say's .aiff the way a voice's file does
43
+ const systemPlayer = system?.ext === "wav" ? player : voicePlayer;
44
+ // voice: settings.voice (null: the system's voices); onVoiceProblem(message): told once when it stops
45
+ const config = { sound: true, volume: 0.5, speak: false, voice: null, onVoiceProblem: null, ...initial };
44
46
  // one word at a time: a newer one (or switching pronunciation off) cancels the one waiting or playing
47
+ let turn = 0;
45
48
  let waiting = null;
46
49
  let speaking = null;
50
+ let fetching = null;
51
+ let voiceDown = false;
47
52
  const hush = () => {
53
+ turn += 1;
48
54
  clearTimeout(waiting);
49
55
  speaking?.kill();
50
- waiting = speaking = null;
56
+ fetching?.abort();
57
+ waiting = speaking = fetching = null;
51
58
  };
52
59
 
53
60
  const play = (name) => {
54
- if (!config.sound || !enabled) return;
55
- execFile("afplay", ["-v", String(config.volume), path.join(SOUND_DIR, `${name}.wav`)], () => {});
61
+ if (config.sound) player.play(path.join(SOUND_DIR, `${name}.wav`), config.volume);
62
+ };
63
+ const playVoice = (file, done) => {
64
+ speaking = voicePlayer.play(file, config.volume, done);
56
65
  };
57
66
 
67
+ // the word in the system's voice: rendered to a file, then played like the sounds are, so it follows
68
+ // the volume and can be cut off
69
+ async function sayIt(words, lang, mine, at) {
70
+ const voice = await system?.voiceFor(lang);
71
+ if (!voice || mine !== turn) return;
72
+ const file = path.join(tmpdir(), `dracosh-${process.pid}-${(spoken += 1)}.${system.ext}`);
73
+ const cleanUp = () => rm(file, { force: true }).catch(() => {});
74
+ waiting = setTimeout(() => {
75
+ waiting = null;
76
+ if (!config.speak || mine !== turn) return;
77
+ try {
78
+ const render = (speaking = system.render(voice, words, file, config.volume, (err) => {
79
+ if (err || speaking !== render) return void cleanUp();
80
+ speaking = systemPlayer.play(file, system.playVolume(config.volume), cleanUp);
81
+ }));
82
+ } catch {
83
+ speaking = null; // a word the system can't take as an argument: better unread than a crash
84
+ }
85
+ }, Math.max(0, at - Date.now()));
86
+ waiting.unref(); // quitting right after an answer doesn't wait for the word
87
+ }
88
+
58
89
  return {
59
90
  play,
60
91
  configure(patch) {
92
+ // a voice picked again in /settings (a new key, say) is a new object: tried again
93
+ if ("voice" in patch && patch.voice !== config.voice) voiceDown = false;
61
94
  Object.assign(config, patch);
62
95
  if (!config.speak) hush();
63
96
  },
64
- // a new question while you're in another window: sound plus a Notification Center banner
97
+ // an audio file played now at the set volume, whatever the settings (a voice heard while picking it)
98
+ playFile(file) {
99
+ hush();
100
+ playVoice(file);
101
+ },
102
+ // a new question while you're in another window: sound plus a notification (the terminal's bell
103
+ // only stands in for the sound when none plays, so the two don't ring together)
65
104
  ask() {
66
105
  play("ask");
67
- // the text goes to AppleScript as an argument, never into the script itself
68
- if (enabled) execFile("osascript", ["-e", "on run argv", "-e", 'display notification (item 1 of argv) with title "Dracosh"', "-e", "end run", t("alerts.newCard")], () => {});
106
+ notifier.notify(t("alerts.newCard"), { bell: !config.sound || Boolean(player.silent) });
69
107
  },
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).
108
+ // a word read aloud in its language (/settings → Pronunciation), after the answer's chime, not over
109
+ // it: in the natural voice when one is set, speaks the language and something can play it, else in
110
+ // the system's (nothing when the system has no voice for it). A natural voice that fails leaves the
111
+ // word to the system's.
76
112
  async speak(text, lang) {
77
113
  hush();
78
- 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
82
- 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
114
+ if (!config.speak || !text || !lang) return;
115
+ const mine = turn;
116
+ const at = Date.now() + SPEAK_AFTER_MS;
117
+ const words = text.replace(/\[\[|\]\]|[{}\\\0]/g, "").slice(0, MAX_SPOKEN); // [[…]] would be a command; cloze braces aren't words
118
+ if (!words.trim()) return;
119
+ // a voice that stopped working still plays the words it made before (no request: no key needed)
120
+ if (config.voice && speaksLanguage(lang) && !voicePlayer.silent) {
121
+ const controller = (fetching = new AbortController());
122
+ try {
123
+ const file = await speech(config.voice, words.trim(), lang, { signal: controller.signal, timeoutMs: VOICE_WAIT_MS, ...(voiceDown ? { key: null } : {}) });
124
+ if (mine !== turn) return;
125
+ fetching = null;
126
+ waiting = setTimeout(() => {
127
+ waiting = null;
128
+ if (config.speak && mine === turn) playVoice(file);
129
+ }, Math.max(0, at - Date.now()));
130
+ waiting.unref();
131
+ return;
132
+ } catch (err) {
133
+ if (controller.signal.aborted || mine !== turn) return;
134
+ fetching = null;
135
+ if (VOICE_STOPS.has(err.code) && !voiceDown) {
136
+ voiceDown = true;
137
+ config.onVoiceProblem?.(err.message);
138
+ }
139
+ if (Date.now() > at + LATE_MS) return; // the moment has passed: better quiet than late
140
+ }
141
+ }
142
+ await sayIt(words, lang, mine, at);
95
143
  },
144
+ // The biggest thing that just happened wins: evolution > goal > combo cheer > the answer itself.
145
+ // On a plain correct answer the pitch rises with the combo and resets on a miss. Badges ring
146
+ // on their own, each as its line lights up (see BadgeUnlock).
96
147
  result(result, { cheers = [], combo = 0 } = {}) {
97
148
  if (result === "wrong") return play("wrong");
98
149
  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
+ }
@@ -0,0 +1,63 @@
1
+ // Is the terminal's background light or dark? Asked once at start, for the auto theme.
2
+ //
3
+ // The terminal is asked for its background color (OSC 11) and then for its attributes (DA1). Every
4
+ // terminal answers DA1, and in order, so its answer means the color reply has come or never will:
5
+ // nothing is left to arrive later and show up as typed keys. A terminal that answers neither (an old
6
+ // console, a pipe) gets a short timeout, longer over SSH, where answers take a round trip. COLORFGBG,
7
+ // set by some terminals, is the fallback. Nothing here can stop the app: any failure means "not known".
8
+
9
+ const QUERY = "\x1b]11;?\x1b\\\x1b[c";
10
+ const COLOR = /\x1b\]11;rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i;
11
+ const ATTRIBUTES = /\x1b\[\?[\d;]*c/;
12
+ const TIMEOUT_MS = 200;
13
+ const SSH_TIMEOUT_MS = 1_000;
14
+
15
+ // "rgb:ffff/ffff/ffff" (1 to 4 hex digits per channel) to light or dark, by relative luminance
16
+ export function parseBackground(reply) {
17
+ const match = COLOR.exec(reply);
18
+ if (!match) return null;
19
+ const [r, g, b] = match.slice(1).map((hex) => {
20
+ const c = parseInt(hex, 16) / (16 ** hex.length - 1);
21
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
22
+ });
23
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.4 ? "light" : "dark";
24
+ }
25
+
26
+ // "15;0" (foreground;background, ANSI color numbers): 7 and 9 to 15 are light backgrounds
27
+ export function backgroundFromEnv(env = process.env) {
28
+ const last = env.COLORFGBG?.split(";").pop();
29
+ if (!last || !/^\d+$/.test(last)) return null;
30
+ const color = Number(last);
31
+ return color === 7 || (color >= 9 && color <= 15) ? "light" : "dark";
32
+ }
33
+
34
+ export function detectBackground({ stdin = process.stdin, stdout = process.stdout, env = process.env, timeoutMs = env.SSH_CONNECTION || env.SSH_TTY ? SSH_TIMEOUT_MS : TIMEOUT_MS } = {}) {
35
+ const fallback = backgroundFromEnv(env);
36
+ if (!stdin.isTTY || !stdout.isTTY || typeof stdin.setRawMode !== "function") return Promise.resolve(fallback);
37
+ return new Promise((resolve) => {
38
+ let reply = "";
39
+ const wasRaw = stdin.isRaw;
40
+ const finish = () => {
41
+ clearTimeout(timer);
42
+ stdin.removeListener("data", onData);
43
+ try {
44
+ stdin.setRawMode(wasRaw);
45
+ stdin.pause();
46
+ } catch {}
47
+ resolve(parseBackground(reply) ?? fallback);
48
+ };
49
+ const onData = (chunk) => {
50
+ reply += chunk.toString("latin1");
51
+ if (ATTRIBUTES.test(reply)) finish();
52
+ };
53
+ const timer = setTimeout(finish, timeoutMs);
54
+ try {
55
+ stdin.setRawMode(true);
56
+ stdin.on("data", onData);
57
+ stdin.resume();
58
+ stdout.write(QUERY);
59
+ } catch {
60
+ finish();
61
+ }
62
+ });
63
+ }
package/src/bug.js ADDED
@@ -0,0 +1,112 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { arch, release, version as osVersion } from "node:os";
4
+ import { checkAll, report } from "./doctor.js";
5
+ import { language, setLanguage } from "./i18n.js";
6
+
7
+ // `dracosh bug`: a new GitHub issue, filled in with the version, the system, Node, the terminal and the
8
+ // doctor's report, in English. Nothing personal: the report's safe lines carry no paths, addresses, names
9
+ // or what a server said. Nothing is sent: the browser opens the issue, and the person reads it and decides.
10
+
11
+ export const ISSUES = "https://github.com/lynthius/dracosh/issues/new";
12
+ const PACKAGE = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
13
+
14
+ const quiet = (command, args) => {
15
+ try {
16
+ return execFileSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3_000 }).trim();
17
+ } catch {
18
+ return "";
19
+ }
20
+ };
21
+
22
+ // "macOS 15.2", "Ubuntu 24.04.1 LTS", "Windows 11 Pro", with the kernel and the processor
23
+ export function systemName({ platform = process.platform, run = quiet, readOsRelease = () => readFileSync("/etc/os-release", "utf8") } = {}) {
24
+ let name = "";
25
+ if (platform === "darwin") {
26
+ const version = run("sw_vers", ["-productVersion"]);
27
+ name = version && `macOS ${version}`;
28
+ } else if (platform === "win32") name = osVersion();
29
+ else {
30
+ try {
31
+ name = readOsRelease().match(/^PRETTY_NAME="?([^"\n]*)"?/m)?.[1] ?? "";
32
+ } catch {}
33
+ }
34
+ return `${name || platform} (${platform} ${release()}, ${arch()})`;
35
+ }
36
+
37
+ // what the terminal says it is: iTerm, Apple Terminal, VS Code, kitty, Windows Terminal…
38
+ export function terminalName(env = process.env) {
39
+ if (env.WT_SESSION) return "Windows Terminal";
40
+ if (env.TERM_PROGRAM) return [env.TERM_PROGRAM, env.TERM_PROGRAM_VERSION].filter(Boolean).join(" ");
41
+ if (env.KITTY_WINDOW_ID) return "kitty";
42
+ if (env.ALACRITTY_SOCKET || env.ALACRITTY_LOG) return "Alacritty";
43
+ if (env.GNOME_TERMINAL_SCREEN || env.VTE_VERSION) return `VTE ${env.VTE_VERSION ?? ""}`.trim();
44
+ return env.TERM || "unknown";
45
+ }
46
+
47
+ export async function issueBody(settings, { system = systemName(), terminal = terminalName(), node = process.versions.node, checks } = {}) {
48
+ const own = language();
49
+ setLanguage("en"); // the report is read by the person fixing it
50
+ try {
51
+ const doctor = report(checks ?? (await checkAll(settings)), { safe: true });
52
+ return [
53
+ "**What happened?**",
54
+ "",
55
+ "",
56
+ "**What did you expect instead?**",
57
+ "",
58
+ "",
59
+ "**Steps to get there**",
60
+ "1. ",
61
+ "",
62
+ "**System**",
63
+ `- Dracosh ${PACKAGE.version}`,
64
+ `- ${system}`,
65
+ `- Node ${node}`,
66
+ `- Terminal: ${terminal}`,
67
+ `- App language: ${own}`,
68
+ "",
69
+ "**dracosh doctor**",
70
+ "```",
71
+ doctor,
72
+ "```"
73
+ ].join("\n");
74
+ } finally {
75
+ setLanguage(own);
76
+ }
77
+ }
78
+
79
+ // GitHub answers an address much longer than this with an error: the report then stays out
80
+ const MAX_URL = 7_000;
81
+ export function issueUrl(body) {
82
+ const url = (text) => `${ISSUES}?${new URLSearchParams({ labels: "bug", body: text })}`;
83
+ const full = url(body);
84
+ return full.length <= MAX_URL ? full : url(body.replace(/\*\*dracosh doctor\*\*[\s\S]*$/, "**dracosh doctor**\n(paste what `dracosh doctor` prints)"));
85
+ }
86
+
87
+ // The browser, the system's own way: open (macOS), xdg-open (Linux), the URL handler (Windows). Not over
88
+ // SSH (it would open on the other computer) or on Linux with no desktop (xdg-open would start a text
89
+ // browser in this terminal): the address is printed either way. The browser is left to start on its
90
+ // own; a program still running after a moment counts as opened.
91
+ const OPENERS = { darwin: ["open", []], win32: ["rundll32.exe", ["url.dll,FileProtocolHandler"]] };
92
+ const SETTLE_MS = 3_000;
93
+ export function canOpen({ platform = process.platform, env = process.env } = {}) {
94
+ if (env.SSH_CONNECTION || env.SSH_TTY) return false;
95
+ return platform === "darwin" || platform === "win32" || Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
96
+ }
97
+ export function openInBrowser(url, { platform = process.platform, env = process.env, run = spawn } = {}) {
98
+ if (!canOpen({ platform, env })) return Promise.resolve(false);
99
+ const [command, args] = OPENERS[platform] ?? ["xdg-open", []];
100
+ return new Promise((resolve) => {
101
+ try {
102
+ const child = run(command, [...args, url], { detached: true, stdio: "ignore", windowsHide: true });
103
+ const timer = setTimeout(() => resolve(true), SETTLE_MS);
104
+ timer.unref();
105
+ child.once("error", () => (clearTimeout(timer), resolve(false)));
106
+ child.once("exit", (code) => (clearTimeout(timer), resolve(code === 0)));
107
+ child.unref();
108
+ } catch {
109
+ resolve(false);
110
+ }
111
+ });
112
+ }