kordexa 0.4.2 → 0.4.3

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/prompts.js CHANGED
@@ -1,55 +1,438 @@
1
- import readline from "node:readline/promises";
2
- import { stdin as input, stdout as output } from "node:process";
3
-
4
- export async function collectOnboarding({ defaults = {}, nonInteractive = false, overrides = {} } = {}) {
5
- const fallback = {
6
- name: "Learner",
7
- email: "learner@example.com",
8
- targetRole: "Agentic AI and LLM Engineer",
9
- currentLearning: "not started yet",
10
- focusSkill: "RAG and agent workflows",
11
- currentStage: "beginner",
12
- weeklyHours: "8",
13
- planDays: "30",
14
- dailyEmailTime: "08:00",
15
- timezone: "UTC",
16
- smtpHost: "smtp.gmail.com",
17
- smtpPort: "465",
18
- smtpUser: "",
19
- smtpPass: "",
20
- smtpFrom: ""
1
+ import readline from "node:readline";
2
+ import { Writable } from "node:stream";
3
+ import {
4
+ ROLE_OPTIONS,
5
+ STAGE_OPTIONS,
6
+ cleanText,
7
+ detectTimezone,
8
+ parseCurrentLearning,
9
+ parseEmail,
10
+ parseEmailTime,
11
+ parseGmailAppPassword,
12
+ parseName,
13
+ parsePlanDays,
14
+ parseRole,
15
+ parseSkill,
16
+ parseSmtpHost,
17
+ parseSmtpPort,
18
+ parseSmtpUser,
19
+ parseStage,
20
+ parseTimezone,
21
+ parseWeeklyHours,
22
+ recommendedSkill,
23
+ skillSuggestions
24
+ } from "./setup-answers.js";
25
+
26
+ const FALLBACK = {
27
+ name: "Learner",
28
+ email: "learner@example.com",
29
+ targetRole: ROLE_OPTIONS[0],
30
+ currentLearning: "not started yet",
31
+ currentStage: "beginner",
32
+ weeklyHours: 8,
33
+ planDays: 30,
34
+ dailyEmailTime: "08:00",
35
+ timezone: "UTC",
36
+ smtpHost: "smtp.gmail.com",
37
+ smtpPort: 465,
38
+ smtpUser: "",
39
+ smtpPass: "",
40
+ smtpFrom: ""
41
+ };
42
+
43
+ const FLAG_CHECKS = {
44
+ name: ["--name", parseName],
45
+ email: ["--email", parseEmail],
46
+ targetRole: ["--role", parseRole],
47
+ currentLearning: ["--current-learning", parseCurrentLearning],
48
+ currentStage: ["--stage", parseStage],
49
+ weeklyHours: ["--weekly-hours", parseWeeklyHours],
50
+ planDays: ["--days", parsePlanDays],
51
+ dailyEmailTime: ["--time", parseEmailTime],
52
+ timezone: ["--timezone", parseTimezone],
53
+ smtpHost: ["--smtp-host", parseSmtpHost],
54
+ smtpPort: ["--smtp-port", parseSmtpPort],
55
+ smtpUser: ["--smtp-user", parseSmtpUser],
56
+ smtpFrom: ["--smtp-from", parseEmail]
57
+ };
58
+
59
+ export class SetupCancelled extends Error {
60
+ constructor(message = "Setup stopped. Nothing was saved.") {
61
+ super(message);
62
+ this.name = "SetupCancelled";
63
+ }
64
+ }
65
+
66
+ // Reads one answer at a time. Piped answers are queued so none are lost, and
67
+ // closing the input stops setup instead of leaving it waiting forever.
68
+ export function createTerminalIO({ input = process.stdin, output = process.stdout } = {}) {
69
+ let muted = false;
70
+ let closed = false;
71
+ let waiting = null;
72
+ const queued = [];
73
+ const visible = new Writable({
74
+ write(chunk, encoding, done) {
75
+ if (!muted) output.write(chunk, encoding);
76
+ done();
77
+ }
78
+ });
79
+ const rl = readline.createInterface({ input, output: visible, terminal: Boolean(input.isTTY && output.isTTY), historySize: 0 });
80
+
81
+ rl.on("line", (line) => {
82
+ if (!waiting) {
83
+ queued.push(line);
84
+ return;
85
+ }
86
+ const { resolve } = waiting;
87
+ waiting = null;
88
+ resolve(line);
89
+ });
90
+ rl.on("SIGINT", () => rl.close());
91
+ rl.on("close", () => {
92
+ closed = true;
93
+ if (!waiting) return;
94
+ const { reject } = waiting;
95
+ waiting = null;
96
+ reject(new SetupCancelled());
97
+ });
98
+
99
+ const nextLine = () => {
100
+ if (queued.length) return Promise.resolve(queued.shift());
101
+ if (closed) return Promise.reject(new SetupCancelled());
102
+ return new Promise((resolve, reject) => {
103
+ waiting = { resolve, reject };
104
+ });
21
105
  };
22
- const values = { ...fallback, ...defaults, ...overrides };
23
- if (nonInteractive) return normalizeAnswers(values);
24
106
 
25
- const rl = readline.createInterface({ input, output });
107
+ return {
108
+ say: (text = "") => output.write(`${text}\n`),
109
+ ask(label) {
110
+ if (closed && !queued.length) return Promise.reject(new SetupCancelled());
111
+ if (closed) {
112
+ output.write(`${label}\n`);
113
+ return nextLine();
114
+ }
115
+ rl.setPrompt(label);
116
+ rl.prompt();
117
+ return nextLine();
118
+ },
119
+ async askHidden(label) {
120
+ output.write(label);
121
+ muted = true;
122
+ try {
123
+ return await nextLine();
124
+ } finally {
125
+ muted = false;
126
+ output.write("\n");
127
+ }
128
+ },
129
+ close: () => rl.close()
130
+ };
131
+ }
132
+
133
+ export async function collectOnboarding({ defaults = {}, nonInteractive = false, overrides = {}, io } = {}) {
134
+ const flags = checkFlags(overrides);
135
+ const saved = usableSavedAnswers(defaults);
136
+ const known = { ...saved, ...flags };
137
+ if (nonInteractive) {
138
+ const targetRole = known.targetRole || FALLBACK.targetRole;
139
+ return normalizeAnswers({ ...FALLBACK, focusSkill: recommendedSkill(targetRole), ...known });
140
+ }
141
+ const terminal = io || createTerminalIO();
26
142
  try {
27
- const ask = async (key, label) => {
28
- const shown = key === "smtpPass" && values[key] ? "saved" : values[key];
29
- const answer = await rl.question(`${label} [${shown}]: `);
30
- values[key] = answer.trim() || values[key];
31
- };
32
- await ask("name", "Your name");
33
- await ask("email", "Email for daily plans");
34
- await ask("targetRole", "Target/searching role");
35
- await ask("currentLearning", "What are you learning right now in this role");
36
- await ask("focusSkill", "First skill you want to focus on");
37
- await ask("currentStage", "Current stage");
38
- await ask("weeklyHours", "Weekly learning hours");
39
- await ask("planDays", "Plan length in days, minimum fixed at 30");
40
- await ask("dailyEmailTime", "Daily email time, 24h HH:MM");
41
- await ask("timezone", "Timezone");
42
- await ask("smtpHost", "SMTP host");
43
- await ask("smtpPort", "SMTP port");
44
- await ask("smtpUser", "SMTP username");
45
- await ask("smtpPass", "SMTP password or app password");
46
- await ask("smtpFrom", "From email");
47
- return normalizeAnswers(values);
143
+ return normalizeAnswers(await guidedSetup(terminal, { saved, flags }));
48
144
  } finally {
49
- rl.close();
145
+ if (!io) terminal.close();
146
+ }
147
+ }
148
+
149
+ function checkFlags(overrides) {
150
+ const checked = {};
151
+ const problems = [];
152
+ for (const [key, value] of Object.entries(overrides)) {
153
+ if (key === "smtpPass") {
154
+ checked.smtpPass = value;
155
+ } else if (key === "focusSkill") {
156
+ const result = parseSkill(value, overrides.targetRole);
157
+ if (result.ok) checked.focusSkill = result.value;
158
+ else problems.push(`--skill: ${result.error}`);
159
+ } else if (FLAG_CHECKS[key]) {
160
+ const [flag, parse] = FLAG_CHECKS[key];
161
+ const result = parse(value);
162
+ if (result.ok) checked[key] = result.value;
163
+ else problems.push(`${flag}: ${result.error}`);
164
+ }
165
+ }
166
+ if (problems.length) throw new Error(`Please fix these setup options:\n- ${problems.join("\n- ")}`);
167
+ return checked;
168
+ }
169
+
170
+ // Older projects may hold values that are no longer valid, so those are asked again.
171
+ function usableSavedAnswers(defaults) {
172
+ const usable = {};
173
+ for (const [key, value] of Object.entries(defaults)) {
174
+ if (key === "focusSkill" || key === "smtpPass") {
175
+ usable[key] = value;
176
+ } else if (FLAG_CHECKS[key]) {
177
+ const result = FLAG_CHECKS[key][1](value);
178
+ if (result.ok) usable[key] = result.value;
179
+ }
180
+ }
181
+ return usable;
182
+ }
183
+
184
+ function buildFields(saved) {
185
+ const savedEmail = saved.email && parseEmail(saved.email, { allowPlaceholder: false }).ok ? saved.email : undefined;
186
+ return [
187
+ {
188
+ key: "name",
189
+ summary: "Name",
190
+ title: "What's your name?",
191
+ fallback: () => (saved.name && saved.name !== FALLBACK.name ? saved.name : undefined),
192
+ parse: parseName
193
+ },
194
+ {
195
+ key: "email",
196
+ summary: "Email",
197
+ title: "Which email should receive your daily plan?",
198
+ hint: "Example: name@gmail.com",
199
+ fallback: () => savedEmail,
200
+ parse: (raw) => parseEmail(raw, { allowPlaceholder: false })
201
+ },
202
+ {
203
+ key: "targetRole",
204
+ summary: "Target role",
205
+ title: "Which job are you preparing for?",
206
+ hint: "Choose a number, or type another job title.",
207
+ options: () => ROLE_OPTIONS,
208
+ fallback: () => saved.targetRole || ROLE_OPTIONS[0],
209
+ parse: parseRole
210
+ },
211
+ {
212
+ key: "currentLearning",
213
+ summary: "Learning now",
214
+ title: "What are you learning right now?",
215
+ hint: "Press Enter if you haven't started yet.",
216
+ fallback: () => saved.currentLearning || FALLBACK.currentLearning,
217
+ parse: parseCurrentLearning
218
+ },
219
+ {
220
+ key: "focusSkill",
221
+ summary: "First skill",
222
+ title: "Which skill should your plan start with?",
223
+ hint: "Not sure? Press Enter and Kordexa will use the recommended skill.",
224
+ options: (values) => skillSuggestions(values.targetRole),
225
+ fallback: (values) => (values.targetRole === saved.targetRole && saved.focusSkill) || recommendedSkill(values.targetRole),
226
+ parse: (raw, values) => parseSkill(raw, values.targetRole)
227
+ },
228
+ {
229
+ key: "currentStage",
230
+ summary: "Level",
231
+ title: "What's your current level?",
232
+ options: () => STAGE_OPTIONS.map((stage) => stage[0].toUpperCase() + stage.slice(1)),
233
+ fallback: () => saved.currentStage || FALLBACK.currentStage,
234
+ parse: parseStage
235
+ },
236
+ {
237
+ key: "weeklyHours",
238
+ summary: "Hours per week",
239
+ title: "How many hours can you study each week?",
240
+ fallback: () => saved.weeklyHours || FALLBACK.weeklyHours,
241
+ parse: parseWeeklyHours
242
+ },
243
+ {
244
+ key: "planDays",
245
+ summary: "Plan length",
246
+ title: "How many days should your plan last?",
247
+ hint: "The shortest plan is 30 days.",
248
+ fallback: () => saved.planDays || FALLBACK.planDays,
249
+ parse: parsePlanDays
250
+ },
251
+ {
252
+ key: "dailyEmailTime",
253
+ summary: "Email time",
254
+ title: "What time should your daily plan arrive?",
255
+ hint: "Examples: 20:00 or 8pm",
256
+ fallback: () => saved.dailyEmailTime || FALLBACK.dailyEmailTime,
257
+ parse: parseEmailTime
258
+ },
259
+ {
260
+ key: "timezone",
261
+ summary: "Timezone",
262
+ title: "What's your timezone?",
263
+ hint: "Type a city or code, like Chennai, London or IST.",
264
+ fallback: () => saved.timezone || detectTimezone(),
265
+ parse: parseTimezone
266
+ }
267
+ ];
268
+ }
269
+
270
+ async function guidedSetup(io, { saved, flags }) {
271
+ const values = { ...FALLBACK, ...saved, ...flags };
272
+ const fields = buildFields(saved).filter((field) => flags[field.key] === undefined);
273
+ const totalSteps = fields.length + 1;
274
+
275
+ io.say("");
276
+ io.say("Welcome to Kordexa. This takes about a minute.");
277
+ io.say("Press Enter to use the answer in [brackets]. Nothing is saved until the final step.");
278
+
279
+ for (const [index, field] of fields.entries()) {
280
+ values[field.key] = await askField(io, field, values, `${index + 1}/${totalSteps}`);
281
+ }
282
+ Object.assign(values, await askEmailDelivery(io, values, `${totalSteps}/${totalSteps}`));
283
+
284
+ for (;;) {
285
+ printReview(io, fields, values);
286
+ const answer = cleanText(await io.ask("Press Enter to save, or type a number to change that answer: ")).toLowerCase();
287
+ if (!answer || ["y", "yes", "save", "ok"].includes(answer)) return values;
288
+ throwIfCancelled(answer);
289
+ const choice = Number(answer);
290
+ if (Number.isInteger(choice) && choice === fields.length + 1) {
291
+ Object.assign(values, await askEmailDelivery(io, values));
292
+ } else if (Number.isInteger(choice) && fields[choice - 1]) {
293
+ const field = fields[choice - 1];
294
+ const previousRole = values.targetRole;
295
+ values[field.key] = await askField(io, field, values);
296
+ const skillField = fields.find((item) => item.key === "focusSkill");
297
+ if (field.key === "targetRole" && values.targetRole !== previousRole && skillField) {
298
+ values.focusSkill = await askField(io, skillField, values);
299
+ }
300
+ } else {
301
+ io.say(` ! Please choose a number from 1 to ${fields.length + 1}, or press Enter to save.`);
302
+ }
303
+ }
304
+ }
305
+
306
+ function throwIfCancelled(answer) {
307
+ if (["quit", "exit", "cancel"].includes(answer.toLowerCase())) throw new SetupCancelled();
308
+ }
309
+
310
+ async function askField(io, field, values, step) {
311
+ const fallback = field.fallback?.(values);
312
+ const options = field.options?.(values) || [];
313
+ io.say("");
314
+ io.say(step ? `[${step}] ${field.title}` : field.title);
315
+ if (field.hint) io.say(` ${field.hint}`);
316
+ options.forEach((option, index) => io.say(` ${index + 1}. ${option}`));
317
+ const prompt = fallback === undefined ? "> " : `> [${fallback}] `;
318
+
319
+ for (;;) {
320
+ const answer = cleanText(await io.ask(prompt));
321
+ throwIfCancelled(answer);
322
+ if (answer === "?" || answer.toLowerCase() === "help") {
323
+ io.say(` ${field.hint || "Type your answer and press Enter."}`);
324
+ continue;
325
+ }
326
+ if (!answer && fallback !== undefined) return fallback;
327
+ const result = field.parse(answer, values);
328
+ if (result.ok) {
329
+ if (result.note) io.say(` ${result.note}`);
330
+ return result.value;
331
+ }
332
+ io.say(` ! ${result.error}`);
333
+ }
334
+ }
335
+
336
+ // Asks in plain language, so learners never need to know what SMTP means.
337
+ export async function askEmailDelivery(io, values, step) {
338
+ const hasSavedLogin = Boolean(values.smtpUser && values.smtpPass);
339
+ const choices = [
340
+ ...(hasSavedLogin ? [["keep", `Keep my current email login (${values.smtpUser})`]] : []),
341
+ ["gmail", "Connect Gmail"],
342
+ ["other", "Connect another email provider"],
343
+ ...(hasSavedLogin ? [] : [["skip", "Skip for now (you can preview plans and connect email later)"]])
344
+ ];
345
+ const defaultChoice = hasSavedLogin ? 1 : choices.length;
346
+
347
+ io.say("");
348
+ io.say(`${step ? `[${step}] ` : ""}How should Kordexa send your daily plan?`);
349
+ io.say(" Plans are sent from your own email account. Your login stays on this computer.");
350
+ choices.forEach(([, label], index) => io.say(` ${index + 1}. ${label}`));
351
+
352
+ for (;;) {
353
+ const answer = cleanText(await io.ask(`> [${defaultChoice}] `)).toLowerCase();
354
+ throwIfCancelled(answer);
355
+ const number = answer ? Number(answer) : defaultChoice;
356
+ const selected = choices[number - 1]?.[0] || choices.find(([id]) => id === answer)?.[0];
357
+ if (!selected) {
358
+ io.say(` ! Please choose a number from 1 to ${choices.length}.`);
359
+ continue;
360
+ }
361
+ if (selected === "keep") return {};
362
+ if (selected === "skip") return skipEmail(io);
363
+ return selected === "gmail" ? connectGmail(io, values) : connectOtherProvider(io, values);
364
+ }
365
+ }
366
+
367
+ function skipEmail(io) {
368
+ io.say(" No problem. Connect email any time with: npx kordexa setup-email");
369
+ return {};
370
+ }
371
+
372
+ async function askUntilValid(io, label, parse, fallback) {
373
+ for (;;) {
374
+ const answer = cleanText(await io.ask(label));
375
+ throwIfCancelled(answer);
376
+ if (!answer && fallback !== undefined) return fallback;
377
+ const result = parse(answer);
378
+ if (result.ok) return result.value;
379
+ io.say(` ! ${result.error}`);
50
380
  }
51
381
  }
52
382
 
383
+ async function connectGmail(io, values) {
384
+ const isGmail = /@(gmail|googlemail)\.com$/i.test(values.email || "");
385
+ const account = isGmail
386
+ ? values.email
387
+ : await askUntilValid(io, "Gmail address: ", (raw) => parseEmail(raw, { allowPlaceholder: false }));
388
+
389
+ io.say("");
390
+ io.say(" Gmail needs an app password, which is different from your normal password:");
391
+ io.say(" 1. Turn on 2-Step Verification for your Google account.");
392
+ io.say(" 2. Open https://myaccount.google.com/apppasswords");
393
+ io.say(" 3. Create an app password named Kordexa and paste it below.");
394
+ for (;;) {
395
+ const answer = await io.askHidden("App password (hidden as you type, press Enter to skip): ");
396
+ if (!answer.trim()) return skipEmail(io);
397
+ const result = parseGmailAppPassword(answer);
398
+ if (result.ok) {
399
+ io.say(" Gmail connected.");
400
+ return { smtpHost: "smtp.gmail.com", smtpPort: 465, smtpUser: account, smtpPass: result.value, smtpFrom: account };
401
+ }
402
+ io.say(` ! ${result.error}`);
403
+ }
404
+ }
405
+
406
+ async function connectOtherProvider(io, values) {
407
+ io.say("");
408
+ io.say(" Your email provider's help pages list these settings. Search for its \"SMTP settings\".");
409
+ const hostLabel = "Mail server address (press Enter to skip): ";
410
+ let host;
411
+ for (;;) {
412
+ const answer = cleanText(await io.ask(hostLabel));
413
+ throwIfCancelled(answer);
414
+ if (!answer) return skipEmail(io);
415
+ host = parseSmtpHost(answer);
416
+ if (host.ok) break;
417
+ io.say(` ! ${host.error}`);
418
+ }
419
+ const port = await askUntilValid(io, "Port [587]: ", parseSmtpPort, 587);
420
+ const user = await askUntilValid(io, `Email login [${values.email}]: `, parseSmtpUser, values.email);
421
+ const password = await io.askHidden("Password (hidden as you type, press Enter to skip): ");
422
+ if (!password.trim()) return skipEmail(io);
423
+ io.say(" Email provider connected.");
424
+ return { smtpHost: host.value, smtpPort: port, smtpUser: user, smtpPass: password.trim(), smtpFrom: user };
425
+ }
426
+
427
+ function printReview(io, fields, values) {
428
+ io.say("");
429
+ io.say("Review your answers");
430
+ fields.forEach((field, index) => io.say(` ${index + 1}. ${field.summary}: ${values[field.key]}`));
431
+ const delivery = values.smtpUser && values.smtpPass ? `Connected (${values.smtpUser})` : "Not connected yet";
432
+ io.say(` ${fields.length + 1}. Email sending: ${delivery}`);
433
+ io.say("");
434
+ }
435
+
53
436
  export function normalizeAnswers(values) {
54
437
  return {
55
438
  learner: {
@@ -59,8 +442,8 @@ export function normalizeAnswers(values) {
59
442
  currentLearning: values.currentLearning,
60
443
  focusSkill: values.focusSkill,
61
444
  currentStage: values.currentStage,
62
- weeklyHours: Number.parseInt(values.weeklyHours, 10) || 8,
63
- planDays: Math.max(30, Number.parseInt(values.planDays, 10) || 30)
445
+ weeklyHours: Number.parseInt(values.weeklyHours, 10) || FALLBACK.weeklyHours,
446
+ planDays: Math.max(30, Number.parseInt(values.planDays, 10) || FALLBACK.planDays)
64
447
  },
65
448
  schedule: {
66
449
  dailyEmailTime: values.dailyEmailTime,
@@ -68,10 +451,11 @@ export function normalizeAnswers(values) {
68
451
  },
69
452
  smtp: {
70
453
  host: values.smtpHost,
71
- port: Number.parseInt(values.smtpPort, 10) || 465,
454
+ port: Number.parseInt(values.smtpPort, 10) || FALLBACK.smtpPort,
72
455
  user: values.smtpUser,
73
456
  pass: values.smtpPass,
74
457
  from: values.smtpFrom || values.smtpUser || values.email
75
- }
458
+ },
459
+ emailConnected: Boolean(values.smtpUser && values.smtpPass)
76
460
  };
77
461
  }
package/src/research.js CHANGED
@@ -257,12 +257,19 @@ export function appendResearchIndex(config, digestPath, digest) {
257
257
  writeJson(indexPath, existing);
258
258
  }
259
259
 
260
+ const ROLE_PATTERNS = [
261
+ [/agentic|llm|ai engineer|artificial intelligence|machine learning/i, "agentic-ai"],
262
+ [/full.?stack|frontend|backend|web/i, "full-stack"],
263
+ [/cyber|security|soc|threat/i, "cybersecurity"],
264
+ [/data scientist|data science|analytics|ml engineer/i, "data-science"]
265
+ ];
266
+
267
+ export function hasRoleMatch(role) {
268
+ return ROLE_PATTERNS.some(([pattern]) => pattern.test(role));
269
+ }
270
+
260
271
  export function inferRoleKey(role) {
261
- if (/agentic|llm|ai engineer|artificial intelligence|machine learning/i.test(role)) return "agentic-ai";
262
- if (/full.?stack|frontend|backend|web/i.test(role)) return "full-stack";
263
- if (/cyber|security|soc|threat/i.test(role)) return "cybersecurity";
264
- if (/data scientist|data science|analytics|ml engineer/i.test(role)) return "data-science";
265
- return "agentic-ai";
272
+ return ROLE_PATTERNS.find(([pattern]) => pattern.test(role))?.[1] || "agentic-ai";
266
273
  }
267
274
 
268
275
  function seedSources(key) {