kordexa 0.4.2 → 0.4.4

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/bin/kordexa.js CHANGED
@@ -1,8 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { main } from "../src/cli.js";
3
3
 
4
+ const FOLDER_ERRORS = {
5
+ EACCES: "Kordexa doesn't have permission to write in this folder. Try a folder you own.",
6
+ EPERM: "Kordexa doesn't have permission to write in this folder. Try a folder you own.",
7
+ EROFS: "This folder is read-only. Try a folder you can write to.",
8
+ ENOSPC: "Your disk is full. Free up some space and try again."
9
+ };
10
+
4
11
  main(process.argv.slice(2)).catch((error) => {
5
- console.error(error?.message || error);
12
+ console.error(FOLDER_ERRORS[error?.code] || error?.message || error);
6
13
  process.exitCode = 1;
7
14
  });
8
-
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kordexa",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "Universal AI agent skill and daily learning orchestrator for job-role learners.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -1,18 +1,48 @@
1
1
  import fs from "node:fs";
2
+ import os from "node:os";
2
3
  import path from "node:path";
3
4
  import { writeAgentAdapters } from "./adapters.js";
4
5
  import { appendGitignore, loadConfig, loadEnvFile, readJson, resolveDataDir, saveConfig, writeJson, writeLocalEnv, validateConfig, CONFIG_FILE } from "./config.js";
5
6
  import { createCoursePack, saveCoursePack } from "./courses.js";
6
- import { sendMail, smtpConfigFromEnv } from "./email.js";
7
+ import { dailyEmailKey, resendConfigFromEnv, sendMail, sendWithResend, smtpConfigFromEnv } from "./email.js";
7
8
  import { createHarness, saveHarness } from "./harness.js";
8
9
  import { generate30DayPlan, renderDailyEmail } from "./planner.js";
9
10
  import { buildProgressionCard, copyDefaultTerminalCard, saveProgressionCard } from "./progression-card.js";
10
11
  import { appendProgress, createWeeklySummary, planStatus, reviewProgress } from "./progress.js";
11
- import { collectOnboarding } from "./prompts.js";
12
+ import { SetupCancelled, askEmailDelivery, collectOnboarding, createTerminalIO } from "./prompts.js";
12
13
  import { appendResearchIndex, createResearchDigest, enrichDigestLinks, saveResearchDigest } from "./research.js";
14
+ import { parsePlanDays } from "./setup-answers.js";
15
+ import { renderView, terminalSupportsColor } from "./terminal-view.js";
13
16
  import { workflowStatus, writeGithubWorkflow } from "./workflow.js";
14
17
 
18
+ const COMMANDS = ["plan", "status", "harness", "courses", "research", "links", "send-today", "log-progress", "weekly-summary", "recommend-next", "progress-card", "terminal-card", "setup-email", "setup-secrets", "doctor", "help"];
19
+ const SETUP_VALUE_FLAGS = {
20
+ "--name": "name",
21
+ "--email": "email",
22
+ "--role": "targetRole",
23
+ "--target-role": "targetRole",
24
+ "--current-learning": "currentLearning",
25
+ "--skill": "focusSkill",
26
+ "--focus-skill": "focusSkill",
27
+ "--stage": "currentStage",
28
+ "--current-stage": "currentStage",
29
+ "--weekly-hours": "weeklyHours",
30
+ "--days": "planDays",
31
+ "--time": "dailyEmailTime",
32
+ "--timezone": "timezone",
33
+ "--smtp-host": "smtpHost",
34
+ "--smtp-port": "smtpPort",
35
+ "--smtp-user": "smtpUser",
36
+ "--smtp-pass": "smtpPass",
37
+ "--smtp-from": "smtpFrom"
38
+ };
39
+ const SETUP_SWITCHES = ["--yes", "--non-interactive", "--offline", "--restart", "--allow-home", "--json"];
40
+
41
+ // People at a terminal get readable results. Agents, scripts and --json get JSON.
42
+ let jsonOutput = true;
43
+
15
44
  export async function main(argv = []) {
45
+ jsonOutput = argv.includes("--json") || !process.stdout.isTTY;
16
46
  const command = normalizeCommand(argv[0]);
17
47
  if (command === "send-today") return sendToday(argv.slice(1));
18
48
  if (command === "plan") return regeneratePlan(argv.slice(1));
@@ -26,9 +56,11 @@ export async function main(argv = []) {
26
56
  if (command === "recommend-next") return recommendNext();
27
57
  if (command === "progress-card") return progressCard();
28
58
  if (command === "terminal-card") return terminalCard();
59
+ if (command === "setup-email") return setupEmail();
29
60
  if (command === "setup-secrets") return setupSecrets();
30
61
  if (command === "doctor") return doctor();
31
62
  if (command === "help") return printHelp();
63
+ if (command !== "init" && !command.startsWith("-")) throw new Error(unknownCommandMessage(command));
32
64
  return init(argv);
33
65
  }
34
66
 
@@ -38,11 +70,72 @@ function normalizeCommand(value) {
38
70
  return value;
39
71
  }
40
72
 
73
+ function unknownCommandMessage(command) {
74
+ const closest = COMMANDS.map((name) => [name, editDistance(command, name)]).sort((a, b) => a[1] - b[1])[0];
75
+ const suggestion = closest[1] <= 3 ? ` Did you mean "${closest[0]}"?` : "";
76
+ return `Unknown command "${command}".${suggestion} Run npx kordexa --help to see every command.`;
77
+ }
78
+
79
+ function editDistance(first, second) {
80
+ let previous = Array.from({ length: second.length + 1 }, (_, index) => index);
81
+ for (let row = 1; row <= first.length; row += 1) {
82
+ const current = [row];
83
+ for (let column = 1; column <= second.length; column += 1) {
84
+ const cost = first[row - 1] === second[column - 1] ? 0 : 1;
85
+ current[column] = Math.min(previous[column] + 1, current[column - 1] + 1, previous[column - 1] + cost);
86
+ }
87
+ previous = current;
88
+ }
89
+ return previous[second.length];
90
+ }
91
+
92
+ function isHomeOrRootFolder() {
93
+ const here = fs.realpathSync(process.cwd());
94
+ return here === path.parse(here).root || here === fs.realpathSync(os.homedir());
95
+ }
96
+
97
+ // Setup writes several files, so a learner's home folder needs a clear yes.
98
+ async function confirmProjectFolder({ io, allowHome }) {
99
+ if (allowHome || !isHomeOrRootFolder()) return;
100
+ const advice = "Create a project folder first: mkdir my-learning && cd my-learning";
101
+ if (!io) throw new Error(`Kordexa won't add files to your home folder. ${advice}`);
102
+ io.say("");
103
+ io.say("You're in your home folder, and Kordexa will add its files here.");
104
+ io.say(` ${advice}`);
105
+ const answer = (await io.ask("Continue here anyway? [y/N] ")).trim().toLowerCase();
106
+ if (answer !== "y" && answer !== "yes") throw new SetupCancelled("Setup stopped. Nothing was saved.");
107
+ }
108
+
109
+ function assertKnownSetupOptions(argv) {
110
+ const start = argv[0] && !argv[0].startsWith("-") ? 1 : 0;
111
+ for (let index = start; index < argv.length; index += 1) {
112
+ const option = argv[index];
113
+ if (SETUP_SWITCHES.includes(option)) continue;
114
+ if (!SETUP_VALUE_FLAGS[option]) throw new Error(`Unknown option "${option}". Run npx kordexa --help to see the options.`);
115
+ const value = argv[index + 1];
116
+ if (value === undefined || value.startsWith("--")) throw new Error(`Please add a value after ${option}.`);
117
+ index += 1;
118
+ }
119
+ }
120
+
41
121
  async function init(argv) {
122
+ assertKnownSetupOptions(argv);
42
123
  const nonInteractive = argv.includes("--yes") || argv.includes("--non-interactive");
43
124
  const overrides = parseKeyValues(argv);
44
125
  const existing = existingSetup();
45
- const answers = await collectOnboarding({ defaults: existing.defaults, nonInteractive, overrides });
126
+ const io = nonInteractive ? null : createTerminalIO();
127
+ let answers;
128
+ try {
129
+ await confirmProjectFolder({ io, allowHome: argv.includes("--allow-home") });
130
+ answers = await collectOnboarding({ defaults: existing.defaults, nonInteractive, overrides, io });
131
+ } catch (error) {
132
+ if (!(error instanceof SetupCancelled)) throw error;
133
+ console.log(`\n${error.message}`);
134
+ process.exitCode = 130;
135
+ return;
136
+ } finally {
137
+ io?.close();
138
+ }
46
139
  const config = {
47
140
  version: 1,
48
141
  command: "/kordexa",
@@ -80,6 +173,10 @@ async function init(argv) {
80
173
  appendResearchIndex(config, digestPath, digest);
81
174
  const workflowPath = writeGithubWorkflow(config);
82
175
  const { warnings } = workflowStatus();
176
+ if ((!nonInteractive || !jsonOutput) && !argv.includes("--json")) {
177
+ printSetupComplete(config, plan, answers.emailConnected, warnings);
178
+ return;
179
+ }
83
180
  outputJson({
84
181
  status: "initialized",
85
182
  command: "/kordexa",
@@ -97,6 +194,39 @@ async function init(argv) {
97
194
  });
98
195
  }
99
196
 
197
+ function printSetupComplete(config, plan, emailConnected, warnings) {
198
+ const { learner, schedule } = config;
199
+ console.log("");
200
+ console.log(`You're all set, ${learner.name}.`);
201
+ console.log(` Plan: ${plan.days.length} days toward ${learner.targetRole}`);
202
+ console.log(` First skill: ${learner.focusSkill}`);
203
+ console.log(` Daily email: ${schedule.dailyEmailTime} ${schedule.timezone}${emailConnected ? "" : " (not connected yet)"}`);
204
+ console.log(` Saved in: ${process.cwd()}`);
205
+ console.log("");
206
+ console.log("Next steps:");
207
+ console.log(" npx kordexa send-today --dry-run Preview today's plan");
208
+ if (!emailConnected) console.log(" npx kordexa setup-email Connect your email");
209
+ console.log(" npx kordexa status See your progress");
210
+ for (const warning of warnings) console.log(`\nWarning: ${warning}`);
211
+ }
212
+
213
+ async function setupEmail() {
214
+ const config = loadConfig();
215
+ const env = loadEnvFile(path.join(process.cwd(), ".env.local"));
216
+ const io = createTerminalIO();
217
+ try {
218
+ const email = await askEmailDelivery(io, { email: config.learner.email, smtpUser: env.SMTP_USER, smtpPass: env.SMTP_PASS });
219
+ writeLocalEnv({ SMTP_HOST: email.smtpHost, SMTP_PORT: email.smtpPort, SMTP_USER: email.smtpUser, SMTP_PASS: email.smtpPass, SMTP_FROM: email.smtpFrom });
220
+ if (email.smtpUser) console.log("\nEmail settings saved. Preview your plan with: npx kordexa send-today --dry-run");
221
+ } catch (error) {
222
+ if (!(error instanceof SetupCancelled)) throw error;
223
+ console.log("\nEmail setup stopped. Nothing was changed.");
224
+ process.exitCode = 130;
225
+ } finally {
226
+ io.close();
227
+ }
228
+ }
229
+
100
230
  // Re-running setup must not reset a learner's profile, email login or schedule.
101
231
  function existingSetup() {
102
232
  let config = null;
@@ -138,12 +268,16 @@ function regeneratePlan(argv) {
138
268
  if (focusSkill) config.learner.focusSkill = focusSkill;
139
269
  const currentLearning = valueAfter(argv, "--current-learning");
140
270
  if (currentLearning) config.learner.currentLearning = currentLearning;
141
- const days = Number.parseInt(valueAfter(argv, "--days") || "", 10);
142
- if (days) config.learner.planDays = Math.max(30, days);
271
+ const daysArg = valueAfter(argv, "--days");
272
+ if (daysArg !== undefined) {
273
+ const days = parsePlanDays(daysArg);
274
+ if (!days.ok) throw new Error(days.error);
275
+ config.learner.planDays = days.value;
276
+ }
143
277
  const plan = generate30DayPlan(config.learner);
144
278
  writeDataJson(config, "30-day-plan.json", plan);
145
279
  saveConfig(config);
146
- outputJson({ status: "saved", plan: "data/30-day-plan.json", days: plan.days.length });
280
+ present("plan", { status: "saved", plan: "data/30-day-plan.json", days: plan.days.length }, { plan });
147
281
  }
148
282
 
149
283
  async function sendToday(argv) {
@@ -160,7 +294,7 @@ async function sendToday(argv) {
160
294
  recommendation: plan.nextSkillRecommendation
161
295
  };
162
296
  writeDataJson(config, "latest-email.json", { generatedAt: new Date().toISOString(), ...result });
163
- outputJson(result);
297
+ present("skipped", result);
164
298
  return;
165
299
  }
166
300
  const progressReview = reviewProgress(config, plan);
@@ -180,9 +314,22 @@ async function sendToday(argv) {
180
314
  const env = { ...process.env, ...loadEnvFile(path.join(process.cwd(), ".env.local")) };
181
315
  const smtp = smtpConfigFromEnv(env);
182
316
  const message = renderDailyEmail(config, plan, day, { progressReview, researchDigest: digest, progressionCard, coursePack });
183
- const result = await sendMail({ smtp, message, dryRun });
317
+ const resend = resendConfigFromEnv(env);
318
+ const result = resend && !dryRun
319
+ ? await sendWithResend({ resend, message, idempotencyKey: dailyEmailKey(message.to, config.schedule?.startDate, day) })
320
+ : await sendMail({ smtp, message, dryRun });
184
321
  writeDataJson(config, "latest-email.json", { generatedAt: new Date().toISOString(), researchDigest: digestPath, ...result });
185
- outputJson(result);
322
+ const previewPath = path.join(config.dataDir || "data", "email-preview.html");
323
+ if (dryRun) fs.writeFileSync(path.join(process.cwd(), previewPath), message.html, "utf8");
324
+ present("email", result, {
325
+ day: plan.days.find((entry) => entry.day === day) || plan.days[0],
326
+ digest,
327
+ review: progressReview,
328
+ totalDays: plan.days.length,
329
+ completedDays: progressReview.completedDays,
330
+ previewPath,
331
+ emailConnected: Boolean(resend || (smtp.host && smtp.user && smtp.pass))
332
+ });
186
333
  }
187
334
 
188
335
  export function resolveScheduledDay(config, plan, now = new Date()) {
@@ -196,23 +343,23 @@ export function resolveScheduledDay(config, plan, now = new Date()) {
196
343
 
197
344
  function showStatus() {
198
345
  const { config, plan } = loadRuntime();
199
- outputJson(planStatus(config, plan));
346
+ present("status", planStatus(config, plan));
200
347
  }
201
348
 
202
349
  async function research(argv) {
203
350
  const { config, plan } = loadRuntime();
204
- const day = Number.parseInt(valueAfter(argv, "--day") || "1", 10);
351
+ const day = parsePositiveDay(valueAfter(argv, "--day") ?? "1", plan);
205
352
  const topic = valueAfter(argv, "--topic") || plan.days.find((entry) => entry.day === day)?.title || config.learner.targetRole;
206
353
  const digest = createResearchDigest({ config, topic, day, roleKey: plan.roleKey });
207
354
  await enrichDigestLinks(digest, { offline: argv.includes("--offline") });
208
355
  const digestPath = saveResearchDigest(config, digest);
209
356
  appendResearchIndex(config, digestPath, digest);
210
- outputJson({ status: "saved", path: digestPath, digest });
357
+ present("research", { status: "saved", path: digestPath, digest });
211
358
  }
212
359
 
213
360
  async function links(argv) {
214
361
  const { config, plan } = loadRuntime();
215
- const day = Number.parseInt(valueAfter(argv, "--day") || "1", 10);
362
+ const day = parsePositiveDay(valueAfter(argv, "--day") ?? "1", plan);
216
363
  const topic = valueAfter(argv, "--topic") || plan.days.find((entry) => entry.day === day)?.title || config.learner.targetRole;
217
364
  const digest = createResearchDigest({ config, topic, day, roleKey: plan.roleKey });
218
365
  await enrichDigestLinks(digest, { offline: argv.includes("--offline"), limit: 3 });
@@ -228,7 +375,7 @@ async function links(argv) {
228
375
  repos: digest.repos || []
229
376
  };
230
377
  writeDataJson(config, "links.json", payload);
231
- outputJson({ status: "resolved", path: "data/links.json", ...payload });
378
+ present("links", { status: "resolved", path: "data/links.json", ...payload });
232
379
  }
233
380
 
234
381
  function harness(argv) {
@@ -236,22 +383,31 @@ function harness(argv) {
236
383
  const mode = valueAfter(argv, "--mode") || "daily";
237
384
  const payload = createHarness(config, plan, mode);
238
385
  const paths = saveHarness(config, payload);
239
- outputJson({ status: "saved", ...paths, harness: payload });
386
+ present("harness", { status: "saved", ...paths, harness: payload });
240
387
  }
241
388
 
242
389
  function courses() {
243
390
  const { config, plan } = loadRuntime();
244
391
  const pack = createCoursePack(config, plan);
245
392
  const paths = saveCoursePack(config, pack);
246
- outputJson({ status: "saved", ...paths, learningSources: pack });
393
+ present("courses", { status: "saved", ...paths, learningSources: pack });
247
394
  }
248
395
 
249
396
  function logProgress(argv) {
250
397
  const { config, plan } = loadRuntime();
398
+ const completed = valueAfter(argv, "--completed")?.trim();
399
+ const evidence = valueAfter(argv, "--evidence")?.trim();
400
+ if (!completed || !evidence) {
401
+ throw new Error('Please say what you finished and link your proof: npx kordexa log-progress --completed "Built the demo" --evidence "github.com/me/demo"');
402
+ }
403
+ const dayArg = valueAfter(argv, "--day");
404
+ if (dayArg !== undefined) parsePositiveDay(dayArg, plan);
405
+ assertWholeNumber(valueAfter(argv, "--minutes"), "--minutes", 0, 1440);
406
+ assertWholeNumber(valueAfter(argv, "--confidence"), "--confidence", 1, 5);
251
407
  const entry = appendProgress(config, {
252
- day: valueAfter(argv, "--day"),
253
- completed: valueAfter(argv, "--completed"),
254
- evidence: valueAfter(argv, "--evidence"),
408
+ day: dayArg,
409
+ completed,
410
+ evidence,
255
411
  minutes: valueAfter(argv, "--minutes"),
256
412
  confidence: valueAfter(argv, "--confidence"),
257
413
  blocker: valueAfter(argv, "--blocker")
@@ -259,15 +415,16 @@ function logProgress(argv) {
259
415
  const review = reviewProgress(config, plan);
260
416
  const cardPaths = saveProgressionCard(config, buildProgressionCard(config, plan));
261
417
  writeDataJson(config, "latest-review.json", review);
262
- outputJson({ status: "logged", entry, review, progressionCard: cardPaths.markdownPath });
418
+ present("logged", { status: "logged", entry, review, progressionCard: cardPaths.markdownPath });
263
419
  }
264
420
 
265
421
  function weeklySummary(argv) {
266
422
  const { config, plan } = loadRuntime();
267
- const week = Number.parseInt(valueAfter(argv, "--week") || "1", 10);
423
+ const totalWeeks = Math.ceil(plan.days.length / 7);
424
+ const week = assertWholeNumber(valueAfter(argv, "--week") ?? "1", "--week", 1, totalWeeks);
268
425
  const summary = createWeeklySummary(config, plan, week);
269
426
  writeDataJson(config, `weekly-summary-${week}.json`, summary);
270
- outputJson(summary);
427
+ present("weekly", summary);
271
428
  }
272
429
 
273
430
  function recommendNext() {
@@ -289,21 +446,21 @@ function recommendNext() {
289
446
  ...recommendation
290
447
  };
291
448
  writeDataJson(config, "next-skill-recommendation.json", payload);
292
- outputJson(payload);
449
+ present("recommendation", payload);
293
450
  }
294
451
 
295
452
  function progressCard() {
296
453
  const { config, plan } = loadRuntime();
297
454
  const card = buildProgressionCard(config, plan);
298
455
  const paths = saveProgressionCard(config, card);
299
- outputJson({ status: "saved", ...paths, card });
456
+ present("card", { status: "saved", ...paths, card });
300
457
  }
301
458
 
302
459
  function terminalCard() {
303
460
  const { config, plan } = loadRuntime();
304
461
  const card = buildProgressionCard(config, plan);
305
462
  const paths = saveProgressionCard(config, card);
306
- outputJson({
463
+ present("terminalCard", {
307
464
  status: "saved",
308
465
  terminalSvgPath: paths.terminalSvgPath,
309
466
  terminalLines: card.terminalLines
@@ -313,7 +470,7 @@ function terminalCard() {
313
470
  function setupSecrets() {
314
471
  const config = loadConfig();
315
472
  const env = loadEnvFile(path.join(process.cwd(), ".env.local"));
316
- const commands = [
473
+ const commands = env.RESEND_API_KEY ? ["gh secret set RESEND_API_KEY"] : [
317
474
  secretCommand("SMTP_HOST", env.SMTP_HOST || "<smtp-host>"),
318
475
  secretCommand("SMTP_PORT", env.SMTP_PORT || "465"),
319
476
  secretCommand("SMTP_USER", env.SMTP_USER || "<smtp-user>"),
@@ -325,7 +482,7 @@ function setupSecrets() {
325
482
  note: "Run these after gh auth login. Secrets are not committed.",
326
483
  commands
327
484
  };
328
- outputJson(payload);
485
+ present("secrets", payload);
329
486
  return payload;
330
487
  }
331
488
 
@@ -341,7 +498,7 @@ function doctor() {
341
498
 
342
499
  const scheduled = workflowStatus();
343
500
  const localSettings = { ...process.env, ...loadEnvFile(path.join(process.cwd(), ".env.local")) };
344
- const missingEmailSettings = ["SMTP_HOST", "SMTP_USER", "SMTP_PASS"].filter((key) => !localSettings[key]);
501
+ const missingEmailSettings = localSettings.RESEND_API_KEY ? [] : ["SMTP_HOST", "SMTP_USER", "SMTP_PASS"].filter((key) => !localSettings[key]);
345
502
 
346
503
  const checks = {
347
504
  agentsMd: fs.existsSync(path.join(process.cwd(), "AGENTS.md")),
@@ -359,7 +516,7 @@ function doctor() {
359
516
  const nextSteps = [];
360
517
  if (!setupComplete || (!workflow && !scheduled.outdated)) nextSteps.push("Run npx kordexa to finish setup.");
361
518
  if (needsUpgrade) nextSteps.push("Run npx kordexa --yes to update the scheduled workflow. Your profile, email settings, progress and start date are kept.");
362
- if (!localEmail) nextSteps.push(`Add ${missingEmailSettings.join(", ")} to .env.local to send email from this machine. For scheduled email, run npx kordexa setup-secrets.`);
519
+ if (!localEmail) nextSteps.push(`Add ${missingEmailSettings.join(", ")} to .env.local, or run npx kordexa setup-email to connect your email. For scheduled email, run npx kordexa setup-secrets.`);
363
520
  let status = "ready";
364
521
  if (!setupComplete || (!workflow && !scheduled.outdated)) status = "needs-setup";
365
522
  else if (needsUpgrade) status = "needs-upgrade";
@@ -371,7 +528,7 @@ function doctor() {
371
528
  ...(scheduled.warnings.length ? { warnings: scheduled.warnings } : {}),
372
529
  ...(configValidation.errors.length > 0 && configExists ? { configErrors: configValidation.errors } : {})
373
530
  };
374
- outputJson(result);
531
+ present("doctor", result);
375
532
  return result;
376
533
  }
377
534
 
@@ -395,52 +552,43 @@ Commands:
395
552
  npx kordexa recommend-next
396
553
  npx kordexa progress-card
397
554
  npx kordexa terminal-card
555
+ npx kordexa setup-email
398
556
  npx kordexa setup-secrets
399
557
  npx kordexa doctor
400
558
 
559
+ Add --json to any command to get machine-readable output.
401
560
  Note: /eduorchestrate stays available inside agents as a legacy alias for /kordexa.
402
561
  `);
403
562
  }
404
563
 
405
564
  function parseKeyValues(argv) {
406
- const map = {
407
- "--name": "name",
408
- "--email": "email",
409
- "--role": "targetRole",
410
- "--target-role": "targetRole",
411
- "--current-learning": "currentLearning",
412
- "--skill": "focusSkill",
413
- "--focus-skill": "focusSkill",
414
- "--stage": "currentStage",
415
- "--current-stage": "currentStage",
416
- "--weekly-hours": "weeklyHours",
417
- "--days": "planDays",
418
- "--time": "dailyEmailTime",
419
- "--timezone": "timezone",
420
- "--smtp-host": "smtpHost",
421
- "--smtp-port": "smtpPort",
422
- "--smtp-user": "smtpUser",
423
- "--smtp-pass": "smtpPass",
424
- "--smtp-from": "smtpFrom"
425
- };
426
565
  const overrides = {};
427
566
  for (let index = 0; index < argv.length; index += 1) {
428
- const key = map[argv[index]];
567
+ const key = SETUP_VALUE_FLAGS[argv[index]];
429
568
  if (key && argv[index + 1]) overrides[key] = argv[index + 1];
430
569
  }
431
570
  return overrides;
432
571
  }
433
572
 
573
+ function assertWholeNumber(value, flag, min, max) {
574
+ if (value === undefined) return undefined;
575
+ const number = Number(value);
576
+ if (!/^\d+$/.test(String(value)) || number < min || number > max) {
577
+ throw new Error(`${flag} must be a whole number from ${min} to ${max}.`);
578
+ }
579
+ return number;
580
+ }
581
+
434
582
  function valueAfter(argv, flag) {
435
583
  const index = argv.indexOf(flag);
436
584
  return index >= 0 ? argv[index + 1] : undefined;
437
585
  }
438
586
 
439
587
  function parsePositiveDay(value, plan) {
440
- if (!/^\d+$/.test(String(value || ""))) throw new Error(`Invalid day: ${value}`);
588
+ const lastDay = plan?.days?.length || 1;
441
589
  const day = Number.parseInt(value, 10);
442
- if (!Number.isInteger(day) || day < 1) throw new Error(`Invalid day: ${value}`);
443
- if (plan?.days?.length && day > plan.days.length) throw new Error(`Day ${day} is outside this ${plan.days.length}-day plan.`);
590
+ if (!/^\d+$/.test(String(value || "")) || day < 1) throw new Error(`--day must be a whole number from 1 to ${lastDay}.`);
591
+ if (plan?.days?.length && day > lastDay) throw new Error(`Day ${day} is outside this ${lastDay}-day plan.`);
444
592
  return day;
445
593
  }
446
594
 
@@ -500,6 +648,14 @@ function writeDataJson(config, fileName, payload) {
500
648
  writeJson(path.join(resolveDataDir(config), fileName), payload);
501
649
  }
502
650
 
651
+ function present(view, payload, context) {
652
+ if (jsonOutput) {
653
+ outputJson(payload);
654
+ return;
655
+ }
656
+ console.log(`\n${renderView(view, payload, context, { color: terminalSupportsColor(), width: process.stdout.columns })}\n`);
657
+ }
658
+
503
659
  function outputJson(payload) {
504
660
  console.log(JSON.stringify(payload, null, 2));
505
661
  }
package/src/email.js CHANGED
@@ -12,6 +12,74 @@ export function smtpConfigFromEnv(env = process.env) {
12
12
  };
13
13
  }
14
14
 
15
+ const RESEND_ENDPOINT = "https://api.resend.com/emails";
16
+ const RESEND_TEST_SENDER = "Kordexa <onboarding@resend.dev>";
17
+ const RESEND_TIMEOUT_MS = 15000;
18
+ const RESEND_MAX_ATTEMPTS = 3;
19
+
20
+ export function resendConfigFromEnv(env = process.env) {
21
+ if (!env.RESEND_API_KEY) return null;
22
+ return { apiKey: env.RESEND_API_KEY, from: env.RESEND_FROM || RESEND_TEST_SENDER };
23
+ }
24
+
25
+ // The key stays the same for one learner's plan day, so a retry can't send twice.
26
+ export function dailyEmailKey(to, startDate, day) {
27
+ const learner = crypto.createHash("sha256").update(String(to).toLowerCase()).digest("hex").slice(0, 24);
28
+ return `kordexa-${learner}-${startDate || "unscheduled"}-day-${day}`;
29
+ }
30
+
31
+ export async function sendWithResend({ resend, message, idempotencyKey, wait = delay }) {
32
+ for (let attempt = 1; ; attempt += 1) {
33
+ let response;
34
+ try {
35
+ response = await fetch(RESEND_ENDPOINT, {
36
+ method: "POST",
37
+ signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),
38
+ headers: {
39
+ authorization: `Bearer ${resend.apiKey}`,
40
+ "content-type": "application/json",
41
+ "user-agent": "kordexa-cli",
42
+ ...(idempotencyKey ? { "idempotency-key": idempotencyKey } : {})
43
+ },
44
+ body: JSON.stringify({ from: resend.from, to: [message.to], subject: message.subject, html: message.html, text: message.text })
45
+ });
46
+ } catch {
47
+ if (attempt < RESEND_MAX_ATTEMPTS) {
48
+ await wait(attempt * 1000);
49
+ continue;
50
+ }
51
+ throw new Error("Couldn't reach Resend. Check your internet connection and try again.");
52
+ }
53
+ if (response.ok) {
54
+ const { id } = await response.json();
55
+ return { sent: true, to: message.to, subject: message.subject, transport: "resend", id };
56
+ }
57
+ if ((response.status === 429 || response.status >= 500) && attempt < RESEND_MAX_ATTEMPTS) {
58
+ const retryAfter = Number(response.headers?.get?.("retry-after"));
59
+ await wait(Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : attempt * 1000);
60
+ continue;
61
+ }
62
+ throw new Error(await resendErrorMessage(response, message.to));
63
+ }
64
+ }
65
+
66
+ async function resendErrorMessage(response, to) {
67
+ const details = await response.json().catch(() => ({}));
68
+ const reason = String(details.message || "");
69
+ if (response.status === 401 || /api key/i.test(reason)) {
70
+ return "Resend didn't accept the API key. Create a new key at resend.com/api-keys and update RESEND_API_KEY in .env.local.";
71
+ }
72
+ if (response.status === 403 && /testing emails|verify a domain/i.test(reason)) {
73
+ return `Resend's free test sender can only email the address on your Resend account, so it can't send to ${to}. Use that address, or verify a domain in Resend.`;
74
+ }
75
+ if (response.status === 429) return "Resend's sending limit was reached. Please try again later.";
76
+ return `Resend couldn't send this email (error ${response.status}). ${reason}`.trim();
77
+ }
78
+
79
+ function delay(ms) {
80
+ return new Promise((resolve) => setTimeout(resolve, ms));
81
+ }
82
+
15
83
  export async function sendMail({ smtp, message, dryRun = false }) {
16
84
  if (dryRun) {
17
85
  return { dryRun: true, message };