@duct-sdk/sdk 0.1.7 → 0.1.13

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.
Files changed (58) hide show
  1. package/README.md +3 -3
  2. package/dist/adapters/next/index.d.ts +1 -1
  3. package/dist/adapters/next/shell.d.ts +55 -1
  4. package/dist/adapters/next/shell.js +100 -17
  5. package/dist/adapters/react/index.d.ts +5 -1
  6. package/dist/adapters/react/index.js +2 -0
  7. package/dist/adapters/react/shell.d.ts +61 -1
  8. package/dist/adapters/react/shell.js +110 -16
  9. package/dist/adapters/react/use-page-context.d.ts +32 -0
  10. package/dist/adapters/react/use-page-context.js +99 -0
  11. package/dist/cli/agents/api-agent.d.ts +9 -3
  12. package/dist/cli/agents/api-agent.js +163 -69
  13. package/dist/cli/agents/auth-agent.d.ts +2 -1
  14. package/dist/cli/agents/auth-agent.js +38 -24
  15. package/dist/cli/agents/deeplink-agent.js +71 -49
  16. package/dist/cli/agents/llm.d.ts +1 -1
  17. package/dist/cli/agents/llm.js +48 -15
  18. package/dist/cli/agents/pipeline.d.ts +16 -0
  19. package/dist/cli/agents/pipeline.js +18 -5
  20. package/dist/cli/agents/reviewer-agent.js +46 -46
  21. package/dist/cli/agents/route-agent.d.ts +3 -1
  22. package/dist/cli/agents/route-agent.js +70 -44
  23. package/dist/cli/detectors/topology.d.ts +26 -0
  24. package/dist/cli/detectors/topology.js +310 -0
  25. package/dist/cli/drift.d.ts +11 -0
  26. package/dist/cli/drift.js +147 -2
  27. package/dist/cli/fs/sandbox.d.ts +2 -0
  28. package/dist/cli/fs/sandbox.js +22 -8
  29. package/dist/cli/generators/config.d.ts +13 -0
  30. package/dist/cli/generators/config.js +200 -50
  31. package/dist/cli/generators/receiver.js +728 -601
  32. package/dist/cli/generators/shell.js +532 -490
  33. package/dist/cli/index.js +502 -19
  34. package/dist/cli/init.d.ts +11 -1
  35. package/dist/cli/init.js +367 -31
  36. package/dist/cli/processors/postprocess.d.ts +22 -0
  37. package/dist/cli/processors/postprocess.js +107 -0
  38. package/dist/cli/processors/prisma-parser.d.ts +35 -0
  39. package/dist/cli/processors/prisma-parser.js +117 -0
  40. package/dist/cli/processors/zod-extractor.d.ts +27 -0
  41. package/dist/cli/processors/zod-extractor.js +153 -0
  42. package/dist/cli/prompts/review.d.ts +32 -0
  43. package/dist/cli/prompts/review.js +240 -0
  44. package/dist/cli/selectors/index.d.ts +22 -0
  45. package/dist/cli/selectors/index.js +274 -0
  46. package/dist/core/config.d.ts +18 -18
  47. package/dist/core/endpoints.d.ts +1 -0
  48. package/dist/core/endpoints.js +4 -0
  49. package/dist/core/introspect.d.ts +47 -0
  50. package/dist/core/introspect.js +94 -0
  51. package/dist/core/status.d.ts +39 -0
  52. package/dist/core/status.js +40 -0
  53. package/dist/core/token.d.ts +36 -1
  54. package/dist/core/token.js +43 -2
  55. package/dist/core/types.d.ts +114 -0
  56. package/dist/index.d.ts +9 -2
  57. package/dist/index.js +6 -1
  58. package/package.json +84 -84
package/dist/cli/index.js CHANGED
@@ -8,7 +8,7 @@ import ora from "ora";
8
8
  import inquirer from "inquirer";
9
9
  import { runInit } from "./init.js";
10
10
  import { SandboxFS } from "./fs/sandbox.js";
11
- import { getCandidateAuthBases, getConfiguredDashboard, getManifestApiBases, getActiveApiBase, getAuthUrl, getShellRuntimeUrl, } from "../core/endpoints.js";
11
+ import { getCandidateAuthBases, getConfiguredDashboard, getManifestApiBases, getActiveApiBase, getActiveAuthBase, getAuthUrl, getShellRuntimeUrl, } from "../core/endpoints.js";
12
12
  import * as fs from "fs/promises";
13
13
  import * as path from "path";
14
14
  import * as os from "os";
@@ -46,18 +46,45 @@ function loadEnvFileSync(envPath) {
46
46
  // File doesn't exist — that's fine, move on
47
47
  }
48
48
  }
49
+ // Walk up from startDir until we find a directory that looks like the project
50
+ // root (contains duct.config.ts, .git, or package.json). Returns all
51
+ // directories from root down to startDir so that files closer to the user's
52
+ // cwd take priority (loaded last = highest priority among .env files).
53
+ function resolveEnvSearchDirs(startDir) {
54
+ const dirs = [];
55
+ let dir = startDir;
56
+ for (let i = 0; i < 10; i++) {
57
+ dirs.unshift(dir); // prepend so we get root→cwd order
58
+ const isDuctRoot = require("fs").existsSync(require("path").join(dir, "duct.config.ts")) ||
59
+ require("fs").existsSync(require("path").join(dir, "duct.config.js")) ||
60
+ require("fs").existsSync(require("path").join(dir, ".git"));
61
+ if (isDuctRoot) {
62
+ break;
63
+ }
64
+ const parent = require("path").dirname(dir);
65
+ if (parent === dir)
66
+ break; // filesystem root
67
+ dir = parent;
68
+ }
69
+ // Deduplicate while preserving order (root first, cwd last)
70
+ return [...new Set(dirs)];
71
+ }
49
72
  function loadAllEnvFilesSync() {
50
73
  const cwd = process.cwd();
51
74
  const nodeEnv = process.env["NODE_ENV"] ?? "";
52
- // Standard dotenv priority order (lowest → highest priority)
53
- const candidates = [
75
+ const suffixes = [
54
76
  ".env",
55
77
  ".env.local",
56
78
  nodeEnv ? `.env.${nodeEnv}` : null,
57
79
  nodeEnv ? `.env.${nodeEnv}.local` : null,
58
80
  ].filter((f) => Boolean(f));
59
- for (const file of candidates) {
60
- loadEnvFileSync(path.join(cwd, file));
81
+ // Load from each ancestor directory (root → cwd), so keys from directories
82
+ // closer to cwd override those from parent directories, but never override
83
+ // keys already set in the shell environment.
84
+ for (const dir of resolveEnvSearchDirs(cwd)) {
85
+ for (const suffix of suffixes) {
86
+ loadEnvFileSync(path.join(dir, suffix));
87
+ }
61
88
  }
62
89
  }
63
90
  // Load all .env files synchronously at startup (before any commands run)
@@ -207,8 +234,15 @@ async function readAuth() {
207
234
  }
208
235
  }
209
236
  async function saveAuth(auth) {
210
- await fs.mkdir(path.dirname(DUCT_AUTH_FILE), { recursive: true });
237
+ const dir = path.dirname(DUCT_AUTH_FILE);
238
+ await fs.mkdir(dir, { recursive: true });
211
239
  await fs.writeFile(DUCT_AUTH_FILE, JSON.stringify(auth, null, 2), "utf-8");
240
+ // Restrict to owner-only on Unix/macOS so the API key isn't world-readable.
241
+ // Windows silently ignores this, which is acceptable (NTFS ACLs govern access there).
242
+ try {
243
+ await fs.chmod(DUCT_AUTH_FILE, 0o600);
244
+ }
245
+ catch { /* non-fatal on Windows or restricted filesystems */ }
212
246
  }
213
247
  async function clearAuth() {
214
248
  try {
@@ -262,16 +296,26 @@ program
262
296
  .option("--framework <name>", "Skip framework detection (next-app|next-pages|remix|vite-react)")
263
297
  .option("--no-agents", "Skip AI pipeline, open blank template", false)
264
298
  .option("--update", "Re-run agents on existing duct.config.ts", false)
265
- .option("-y, --yes", "Auto-approve all prompts", false)
299
+ .option("-y, --yes", "Auto-approve all prompts (CI/scripted use)", false)
300
+ .option("--no-interactive", "Write unresolved review decisions to duct-review.json instead of prompting", false)
301
+ .option("--manual", "Run topology + file selection only (no LLM). Generates a pre-filled template with empty actions/routes.", false)
302
+ .option("--api-spec <path>", "Path to an OpenAPI/Swagger spec file — skips Route + API agents for instant, high-accuracy init")
303
+ .option("--api-url <url>", "Separate API base URL when your API runs on a different domain (e.g., https://api.example.com)")
304
+ .option("--industry <category>", "Product industry for better modality routing (e.g., fintech, ecommerce, saas, ai)")
266
305
  .action(async (opts) => {
267
306
  try {
268
307
  await runInit({
269
308
  cwd: process.cwd(),
270
309
  dryRun: opts.dryRun,
271
310
  framework: opts.framework,
272
- noAgents: Boolean(opts.noAgents),
311
+ noAgents: Boolean(opts.noAgents) || Boolean(opts.manual),
312
+ manual: Boolean(opts.manual),
273
313
  update: opts.update,
274
314
  yes: opts.yes,
315
+ noInteractive: Boolean(opts.noInteractive),
316
+ apiSpec: opts.apiSpec,
317
+ apiUrl: opts.apiUrl,
318
+ industry: opts.industry,
275
319
  });
276
320
  }
277
321
  catch (err) {
@@ -280,6 +324,73 @@ program
280
324
  process.exit(1);
281
325
  }
282
326
  });
327
+ // Mirror of buildDependsOnPlan() in services/shell-runtime/app/api/chat/route.ts — keep in sync.
328
+ function buildDependsOnOrder(targetId, actions, visited = new Set()) {
329
+ if (visited.has(targetId) || visited.size > 4)
330
+ return [];
331
+ visited.add(targetId);
332
+ const action = actions.find((a) => a.id === targetId);
333
+ const order = [];
334
+ if (action?.dependsOn) {
335
+ for (const dep of action.dependsOn) {
336
+ order.push(...buildDependsOnOrder(dep.actionId, actions, visited));
337
+ }
338
+ }
339
+ order.push(targetId);
340
+ return order;
341
+ }
342
+ function computePrecomputedWorkflows(config) {
343
+ const workflows = [];
344
+ const actions = (Array.isArray(config.actions) ? config.actions : []);
345
+ const dataModel = config.dataModel;
346
+ const dataModelEntities = dataModel?.entities ?? [];
347
+ const seen = new Set();
348
+ // 1. dataModel entity chains: discoveryAction → fetchAction
349
+ for (const entity of dataModelEntities) {
350
+ if (entity.discoveryAction === entity.fetchAction)
351
+ continue;
352
+ const hasDiscovery = actions.some((a) => a.id === entity.discoveryAction);
353
+ const hasFetch = actions.some((a) => a.id === entity.fetchAction);
354
+ if (!hasDiscovery || !hasFetch)
355
+ continue;
356
+ const wfId = `wf_list_fetch_${entity.id}`;
357
+ if (seen.has(wfId))
358
+ continue;
359
+ seen.add(wfId);
360
+ const entityLabel = entity.label ?? entity.id;
361
+ workflows.push({
362
+ id: wfId,
363
+ name: `List and fetch ${entityLabel}`,
364
+ steps: [{ action_id: entity.discoveryAction }, { action_id: entity.fetchAction }],
365
+ intent_patterns: [
366
+ `show me ${entityLabel}`,
367
+ `find ${entityLabel}`,
368
+ `get ${entityLabel}`,
369
+ `list ${entityLabel}`,
370
+ ],
371
+ });
372
+ }
373
+ // 2. dependsOn chains: topological sort of each action's dependency DAG
374
+ for (const action of actions) {
375
+ if (!action.dependsOn || action.dependsOn.length === 0)
376
+ continue;
377
+ const wfId = `wf_dep_${action.id}`;
378
+ if (seen.has(wfId))
379
+ continue;
380
+ seen.add(wfId);
381
+ const order = buildDependsOnOrder(action.id, actions, new Set());
382
+ if (order.length <= 1)
383
+ continue;
384
+ const actionLabel = action.name ?? action.id;
385
+ workflows.push({
386
+ id: wfId,
387
+ name: `Execute ${actionLabel}`,
388
+ steps: order.slice(0, 4).map((id) => ({ action_id: id })),
389
+ intent_patterns: action.description ? [action.description] : [actionLabel],
390
+ });
391
+ }
392
+ return workflows;
393
+ }
283
394
  // ----------------------------------------------------------------
284
395
  // duct push
285
396
  // ----------------------------------------------------------------
@@ -312,6 +423,13 @@ program
312
423
  process.exit(1);
313
424
  }
314
425
  spinner.succeed("Config loaded");
426
+ // Warn on weak DUCT_SECRET_KEY — must be ≥ 32 chars for adequate HMAC entropy
427
+ const secretKey = process.env["DUCT_SECRET_KEY"];
428
+ if (secretKey && secretKey.length < 32) {
429
+ console.log(chalk.yellow(`\n ⚠ DUCT_SECRET_KEY is only ${secretKey.length} characters.\n` +
430
+ ` Use at least 32 random characters for adequate HMAC-SHA256 entropy.\n` +
431
+ ` Generate one: openssl rand -hex 32\n`));
432
+ }
315
433
  if (opts.dryRun) {
316
434
  console.log(chalk.green("\n✓ Config is valid (dry-run)\n"));
317
435
  console.log(JSON.stringify(config, null, 2).slice(0, 500) + "\n...\n");
@@ -328,6 +446,20 @@ program
328
446
  console.log("Run `npx duct login` first.\n");
329
447
  process.exit(1);
330
448
  }
449
+ // ── Pre-compute workflows from dataModel + dependsOn graph ───────────────
450
+ // Walk the entity DAG to generate named workflow stubs that the shell can
451
+ // execute without a per-step LLM routing call.
452
+ const precomputedWorkflows = computePrecomputedWorkflows(config);
453
+ if (precomputedWorkflows.length > 0) {
454
+ console.log(chalk.gray(`\n ◆ ${precomputedWorkflows.length} workflow(s) pre-computed from dataModel + dependsOn graph`));
455
+ for (const wf of precomputedWorkflows) {
456
+ const stepNames = wf.steps.map((s) => s.action_id).join(" → ");
457
+ console.log(chalk.gray(` • ${wf.name} (${stepNames})`));
458
+ }
459
+ console.log();
460
+ // Embed into the manifest so agent-proxy stores them alongside actions
461
+ config = { ...config, precomputedWorkflows };
462
+ }
331
463
  const pushSpinner = ora("Pushing to Duct cloud...").start();
332
464
  const shellId = config["shellId"] ?? "unknown";
333
465
  const auth = await readAuth();
@@ -356,9 +488,40 @@ program
356
488
  continue;
357
489
  }
358
490
  pushSpinner.fail("Push failed");
359
- console.error(chalk.red(`\n${lastError}`));
360
- console.log(chalk.gray(" Tip: Check DUCT_URL is set and services are running."));
361
- console.log(chalk.gray(" Run npx duct checkup to diagnose connectivity.\n"));
491
+ // Parse the error body and surface the real cause clearly.
492
+ // The proxy may wrap inner service errors as a JSON string inside `message`.
493
+ let outerErr = {};
494
+ let innerErr = {};
495
+ try {
496
+ outerErr = JSON.parse(body);
497
+ }
498
+ catch { /* raw string error */ }
499
+ if (typeof outerErr["message"] === "string") {
500
+ try {
501
+ innerErr = JSON.parse(outerErr["message"]);
502
+ }
503
+ catch { /* not JSON */ }
504
+ }
505
+ const innerCode = (innerErr["error"] ?? outerErr["error"] ?? "");
506
+ const retryAfter = innerErr["retry_after"];
507
+ if (innerCode === "too_many_requests") {
508
+ const wait = retryAfter ? ` Try again in ${retryAfter}s.` : " Try again shortly.";
509
+ console.error(chalk.red("\n Auth service rate-limited: too many failed token validation attempts."));
510
+ console.log(chalk.yellow(` This usually means DUCT_SECRET_KEY was missing or invalid on previous runs.${wait}`));
511
+ console.log(chalk.gray(" 1. Confirm DUCT_SECRET_KEY is set in your .env (at the same level as duct.config.ts)"));
512
+ console.log(chalk.gray(" 2. Run `npx duct login` if your session token is stale"));
513
+ console.log(chalk.gray(" 3. Run `npx duct checkup` to verify env vars are loaded\n"));
514
+ }
515
+ else if (response.status === 401) {
516
+ const hint = outerErr["message"] ?? body;
517
+ console.error(chalk.red(`\n Authentication failed: ${hint}`));
518
+ console.log(chalk.gray(" Run `npx duct login` to refresh your credentials, then retry.\n"));
519
+ }
520
+ else {
521
+ console.error(chalk.red(`\n${lastError}`));
522
+ console.log(chalk.gray(" Tip: Check DUCT_URL is set and services are running."));
523
+ console.log(chalk.gray(" Run npx duct checkup to diagnose connectivity.\n"));
524
+ }
362
525
  process.exit(1);
363
526
  }
364
527
  if (!success) {
@@ -439,10 +602,13 @@ program
439
602
  }
440
603
  spinner.succeed(`Logged in as ${chalk.bold(auth.email)} (${auth.slug})`);
441
604
  console.log(chalk.gray(` API base: ${auth.apiBase}`));
442
- console.log(chalk.gray(` Credentials saved to ${DUCT_AUTH_FILE}\n`));
443
- // Best-effort: fetch and display provisioned shells for this account
605
+ console.log(chalk.gray(` Credentials saved to ${DUCT_AUTH_FILE} (mode 600)\n`));
606
+ console.log(chalk.yellow(` ⚠ Keep this file private — it contains your API key.\n Add ${DUCT_AUTH_FILE} to your global .gitignore.\n`));
607
+ // Best-effort: fetch and display provisioned shells for this account.
608
+ // Account/identity endpoints live on the auth service, NOT agent-proxy.
444
609
  try {
445
- const shellsRes = await fetch(`${auth.apiBase}/v1/shells`, {
610
+ const authBase = getActiveAuthBase(auth);
611
+ const shellsRes = await fetch(`${authBase}/v1/account/shells`, {
446
612
  headers: { Authorization: `Bearer ${rawKey}` },
447
613
  signal: AbortSignal.timeout(4000),
448
614
  });
@@ -455,8 +621,8 @@ program
455
621
  const status = s.status === "active"
456
622
  ? chalk.green("active")
457
623
  : chalk.yellow(s.status ?? "unknown");
458
- const name = s.name ? chalk.gray(` — ${s.name}`) : "";
459
- console.log(` ${chalk.cyan(s.id)}${name} ${status}`);
624
+ const env = s.environment ? chalk.gray(` — ${s.environment}`) : "";
625
+ console.log(` ${chalk.cyan(s.id)}${env} ${status}`);
460
626
  }
461
627
  console.log();
462
628
  }
@@ -464,9 +630,13 @@ program
464
630
  console.log(chalk.gray(" No shells provisioned yet — visit the dashboard to create one.\n"));
465
631
  }
466
632
  }
633
+ else {
634
+ console.log(chalk.gray(` Could not list shells (HTTP ${shellsRes.status} from ${authBase}/v1/account/shells)\n`));
635
+ }
467
636
  }
468
- catch {
469
- // Shell list fetch is non-critical — ignore errors silently
637
+ catch (err) {
638
+ const message = err instanceof Error ? err.message : String(err);
639
+ console.log(chalk.gray(` Could not list shells: ${message}\n`));
470
640
  }
471
641
  }
472
642
  catch (err) {
@@ -546,10 +716,11 @@ program
546
716
  .description("Probe live API endpoints against duct.config.ts and report drift")
547
717
  .option("--config <path>", "Path to duct.config.ts", "duct.config.ts")
548
718
  .option("--json", "Output results as JSON", false)
719
+ .option("--manifest-diff", "Diff current duct.config.ts against last pushed snapshot (.duct-manifest.json) — no HTTP probing, CI-safe", false)
549
720
  .action(async (opts) => {
550
721
  const cwd = process.cwd();
551
722
  const sandboxFs = new SandboxFS(cwd);
552
- console.log(chalk.bold("\n ◆ Duct · manifest update\n"));
723
+ console.log(chalk.bold("\n ◆ Duct · scan\n"));
553
724
  // Check config exists
554
725
  const configExists = await sandboxFs.exists(opts.config);
555
726
  if (!configExists) {
@@ -567,6 +738,108 @@ program
567
738
  console.log(chalk.yellow("Could not load config. Ensure duct.config.ts is valid and exports defineDuctConfig({...}).\n"));
568
739
  process.exit(1);
569
740
  }
741
+ // --manifest-diff: compare current duct.config.ts with last pushed snapshot
742
+ if (opts.manifestDiff) {
743
+ const snapshotPath = path.resolve(cwd, ".duct-manifest.json");
744
+ let snapshot = null;
745
+ try {
746
+ const raw = await fs.readFile(snapshotPath, "utf-8");
747
+ snapshot = JSON.parse(raw);
748
+ }
749
+ catch {
750
+ console.log(chalk.yellow(" No .duct-manifest.json snapshot found. Run `npx duct init` or `npx duct push` first.\n"));
751
+ process.exit(1);
752
+ }
753
+ const snapshotActions = new Map((snapshot.actions ?? []).map((a) => [`${a.method}:${a.path}`, a]));
754
+ const currentActions = new Map((config.actions ?? []).map((a) => [`${a.method}:${a.path}`, a]));
755
+ const added = [];
756
+ const removed = [];
757
+ const changed = [];
758
+ for (const [key, current] of currentActions) {
759
+ if (!snapshotActions.has(key)) {
760
+ added.push(current);
761
+ }
762
+ else {
763
+ const before = snapshotActions.get(key);
764
+ const reasons = [];
765
+ if (before.description !== current.description)
766
+ reasons.push("description");
767
+ if (before.requiresAuth !== current.requiresAuth)
768
+ reasons.push("requiresAuth");
769
+ if (before.sensitivityLevel !== current.sensitivityLevel)
770
+ reasons.push("sensitivityLevel");
771
+ if (before.agentAccessible !== current.agentAccessible)
772
+ reasons.push("agentAccessible");
773
+ if (JSON.stringify(before.params) !== JSON.stringify(current.params))
774
+ reasons.push("params");
775
+ if (JSON.stringify(before.inputSchema) !== JSON.stringify(current.inputSchema))
776
+ reasons.push("inputSchema");
777
+ if (reasons.length > 0)
778
+ changed.push({ before, after: current, reason: reasons.join(", ") });
779
+ }
780
+ }
781
+ for (const [key, snap] of snapshotActions) {
782
+ if (!currentActions.has(key))
783
+ removed.push(snap);
784
+ }
785
+ const snapshotRoutes = new Map((snapshot.routes ?? []).map((r) => [r.path, r]));
786
+ const currentRoutes = new Map((config.routes ?? []).map((r) => [r.path, r]));
787
+ const addedRoutes = [...currentRoutes.keys()].filter((k) => !snapshotRoutes.has(k));
788
+ const removedRoutes = [...snapshotRoutes.keys()].filter((k) => !currentRoutes.has(k));
789
+ const hasDrift = added.length > 0 || removed.length > 0 || changed.length > 0 || addedRoutes.length > 0 || removedRoutes.length > 0;
790
+ const diffReport = { hasDrift, added, removed, changed, addedRoutes, removedRoutes, checkedAt: new Date().toISOString() };
791
+ if (opts.json) {
792
+ console.log(JSON.stringify(diffReport, null, 2));
793
+ }
794
+ else {
795
+ if (!hasDrift) {
796
+ console.log(chalk.green(" ✓ No manifest drift — duct.config.ts matches last pushed state\n"));
797
+ }
798
+ else {
799
+ if (added.length > 0) {
800
+ console.log(chalk.bold(" New actions (not in last push):"));
801
+ for (const a of added)
802
+ console.log(` ${chalk.green("+")} ${a.method} ${a.path}`);
803
+ console.log();
804
+ }
805
+ if (removed.length > 0) {
806
+ console.log(chalk.bold(" Removed actions (in last push, not in current config):"));
807
+ for (const a of removed)
808
+ console.log(` ${chalk.red("-")} ${a.method} ${a.path}`);
809
+ console.log();
810
+ }
811
+ if (changed.length > 0) {
812
+ console.log(chalk.bold(" Changed actions:"));
813
+ for (const c of changed)
814
+ console.log(` ${chalk.yellow("~")} ${c.after.method} ${c.after.path} ${chalk.gray(c.reason)}`);
815
+ console.log();
816
+ }
817
+ if (addedRoutes.length > 0) {
818
+ console.log(chalk.bold(" New routes:"));
819
+ for (const r of addedRoutes)
820
+ console.log(` ${chalk.green("+")} ${r}`);
821
+ console.log();
822
+ }
823
+ if (removedRoutes.length > 0) {
824
+ console.log(chalk.bold(" Removed routes:"));
825
+ for (const r of removedRoutes)
826
+ console.log(` ${chalk.red("-")} ${r}`);
827
+ console.log();
828
+ }
829
+ console.log(chalk.gray(" Run `npx duct push` to sync changes with Duct cloud.\n"));
830
+ }
831
+ }
832
+ // Write drift.json report
833
+ try {
834
+ await fs.writeFile(path.join(cwd, "duct-drift.json"), JSON.stringify(diffReport, null, 2) + "\n", "utf-8");
835
+ if (!opts.json)
836
+ console.log(chalk.gray(" Report written to duct-drift.json\n"));
837
+ }
838
+ catch { /* non-fatal */ }
839
+ if (hasDrift)
840
+ process.exitCode = 1;
841
+ return;
842
+ }
570
843
  const { runDriftCheck, printDriftReport } = await import("./drift.js");
571
844
  try {
572
845
  const report = await runDriftCheck(config);
@@ -586,6 +859,216 @@ program
586
859
  }
587
860
  });
588
861
  // ----------------------------------------------------------------
862
+ // duct pull — restore a manifest version from push history
863
+ // ----------------------------------------------------------------
864
+ program
865
+ .command("pull <hash>")
866
+ .description("Restore a manifest version from push history (e.g. duct pull a3f9b12)")
867
+ .option("--config <path>", "Path to write duct.config.ts", "duct.config.ts")
868
+ .option("--shell-id <shellId>", "Override shell ID (reads from duct.config.ts by default)")
869
+ .action(async (hash, opts) => {
870
+ const spinner = ora("Fetching push record…").start();
871
+ try {
872
+ // Load API key
873
+ let apiKey = process.env["DUCT_API_KEY"];
874
+ if (!apiKey) {
875
+ const auth = await readAuth();
876
+ apiKey = auth?.token;
877
+ }
878
+ if (!apiKey) {
879
+ spinner.fail("Not logged in");
880
+ console.log(chalk.yellow("\nRun `npx duct login` first.\n"));
881
+ process.exit(1);
882
+ }
883
+ // Resolve shell ID
884
+ let shellId = opts.shellId;
885
+ if (!shellId) {
886
+ const cwd = process.cwd();
887
+ const configPath = path.resolve(cwd, opts.config);
888
+ try {
889
+ const config = await loadDuctConfig(configPath);
890
+ shellId = config["shellId"];
891
+ }
892
+ catch {
893
+ // config may not exist yet — will ask
894
+ }
895
+ }
896
+ if (!shellId) {
897
+ spinner.stop();
898
+ const { id } = await inquirer.prompt([
899
+ { type: "input", name: "id", message: "Shell ID (shell_...):", validate: (v) => v.startsWith("shell_") || "Must start with shell_" },
900
+ ]);
901
+ shellId = id;
902
+ }
903
+ const auth = await readAuth();
904
+ const manifestBases = getManifestApiBases(auth);
905
+ let record = null;
906
+ let lastError = "";
907
+ for (const base of manifestBases) {
908
+ const res = await fetch(`${base}/v1/shells/${shellId}/manifest/history/${hash}`, { headers: { Authorization: `Bearer ${apiKey}` } });
909
+ if (res.ok) {
910
+ record = await res.json();
911
+ break;
912
+ }
913
+ lastError = `${res.status} at ${base}`;
914
+ if (res.status === 404)
915
+ continue;
916
+ break;
917
+ }
918
+ if (!record) {
919
+ spinner.fail(`Push record '${hash}' not found`);
920
+ console.error(chalk.red(`\n${lastError || "No manifest API responded"}`));
921
+ process.exit(1);
922
+ }
923
+ spinner.succeed(`Found record ${chalk.cyan(hash)} — ${record.action_count ?? 0} actions, pushed ${new Date(record.pushed_at ?? "").toLocaleString()}`);
924
+ const manifest = record.manifest;
925
+ if (!manifest) {
926
+ console.error(chalk.red("\nNo manifest data in record.\n"));
927
+ process.exit(1);
928
+ }
929
+ // Write as duct.config.ts
930
+ const configPath = path.resolve(process.cwd(), opts.config);
931
+ // Check if file exists
932
+ let shouldOverwrite = true;
933
+ try {
934
+ await fs.access(configPath);
935
+ const { confirm } = await inquirer.prompt([
936
+ {
937
+ type: "confirm",
938
+ name: "confirm",
939
+ message: `${opts.config} already exists. Overwrite with hash ${hash}?`,
940
+ default: false,
941
+ },
942
+ ]);
943
+ shouldOverwrite = confirm;
944
+ }
945
+ catch {
946
+ // File doesn't exist — safe to write
947
+ }
948
+ if (!shouldOverwrite) {
949
+ console.log(chalk.yellow("\nAborted — file not overwritten.\n"));
950
+ process.exit(0);
951
+ }
952
+ const configContent = `// Restored from push history — hash: ${hash}
953
+ // Pushed at: ${record.pushed_at ?? "unknown"}
954
+ // Run \`npx duct push\` to re-sync this version to Duct cloud.
955
+ import { defineDuctConfig } from '@duct/sdk';
956
+
957
+ export default defineDuctConfig(${JSON.stringify(manifest, null, 2)});
958
+ `;
959
+ await fs.writeFile(configPath, configContent, "utf-8");
960
+ console.log(chalk.green(`\n ◆ ${opts.config} restored from ${hash}\n`));
961
+ console.log(chalk.gray(` Run \`npx duct push\` to re-sync this version to Duct cloud.\n`));
962
+ }
963
+ catch (err) {
964
+ spinner.fail("Pull failed");
965
+ const message = err instanceof Error ? err.message : String(err);
966
+ console.error(chalk.red(`\nError: ${message}\n`));
967
+ process.exit(1);
968
+ }
969
+ });
970
+ // ----------------------------------------------------------------
971
+ // duct rollback — activate a historical push directly on Duct cloud
972
+ // Unlike `duct pull` (which writes duct.config.ts locally), rollback
973
+ // immediately sets the live manifest to the stored snapshot without
974
+ // touching any local files. Run `duct pull <hash>` afterwards if you
975
+ // also want your local config to reflect the change.
976
+ // ----------------------------------------------------------------
977
+ program
978
+ .command("rollback <hash>")
979
+ .description("Set a historical push as the active manifest on Duct cloud (no local file changes)")
980
+ .option("--shell-id <shellId>", "Override shell ID (reads from duct.config.ts by default)")
981
+ .option("--config <path>", "Path to duct.config.ts (used only to read shellId)", "duct.config.ts")
982
+ .option("--yes", "Skip confirmation prompt", false)
983
+ .action(async (hash, opts) => {
984
+ const spinner = ora("Resolving shell…").start();
985
+ try {
986
+ // Load API key
987
+ let apiKey = process.env["DUCT_API_KEY"];
988
+ if (!apiKey) {
989
+ const auth = await readAuth();
990
+ apiKey = auth?.token;
991
+ }
992
+ if (!apiKey) {
993
+ spinner.fail("Not logged in");
994
+ console.log(chalk.yellow("\nRun `npx duct login` first.\n"));
995
+ process.exit(1);
996
+ }
997
+ // Resolve shell ID
998
+ let shellId = opts.shellId;
999
+ if (!shellId) {
1000
+ const cwd = process.cwd();
1001
+ const configPath = path.resolve(cwd, opts.config);
1002
+ try {
1003
+ const config = await loadDuctConfig(configPath);
1004
+ shellId = config["shellId"];
1005
+ }
1006
+ catch { /* config may not exist */ }
1007
+ }
1008
+ if (!shellId) {
1009
+ spinner.stop();
1010
+ const { id } = await inquirer.prompt([
1011
+ {
1012
+ type: "input",
1013
+ name: "id",
1014
+ message: "Shell ID (shell_...):",
1015
+ validate: (v) => v.startsWith("shell_") || "Must start with shell_",
1016
+ },
1017
+ ]);
1018
+ shellId = id;
1019
+ }
1020
+ spinner.succeed(`Shell: ${chalk.cyan(shellId)}`);
1021
+ if (!opts.yes) {
1022
+ const { confirm } = await inquirer.prompt([
1023
+ {
1024
+ type: "confirm",
1025
+ name: "confirm",
1026
+ message: chalk.yellow(`Activate hash ${chalk.bold(hash)} as the live manifest for ${shellId}?`),
1027
+ default: false,
1028
+ },
1029
+ ]);
1030
+ if (!confirm) {
1031
+ console.log(chalk.gray("\nRollback cancelled.\n"));
1032
+ process.exit(0);
1033
+ }
1034
+ }
1035
+ const activateSpinner = ora(`Activating ${hash}…`).start();
1036
+ const auth = await readAuth();
1037
+ const manifestBases = getManifestApiBases(auth);
1038
+ let success = false;
1039
+ let lastError = "";
1040
+ for (const base of manifestBases) {
1041
+ const res = await fetch(`${base}/v1/shells/${shellId}/manifest/activate/${encodeURIComponent(hash)}`, {
1042
+ method: "POST",
1043
+ headers: { Authorization: `Bearer ${apiKey}` },
1044
+ });
1045
+ if (res.ok) {
1046
+ success = true;
1047
+ break;
1048
+ }
1049
+ const body = await res.text();
1050
+ lastError = `${res.status} at ${base}: ${body}`;
1051
+ if (res.status === 404)
1052
+ continue;
1053
+ break;
1054
+ }
1055
+ if (!success) {
1056
+ activateSpinner.fail(`Rollback failed`);
1057
+ console.error(chalk.red(`\n${lastError || "No manifest API responded"}`));
1058
+ process.exit(1);
1059
+ }
1060
+ activateSpinner.succeed(`Hash ${chalk.cyan(hash)} is now the live manifest for ${chalk.cyan(shellId)}`);
1061
+ console.log(chalk.green("\n ◆ Rollback complete\n"));
1062
+ console.log(chalk.gray(` Tip: Run \`npx duct pull ${hash}\` to also restore duct.config.ts locally.\n`));
1063
+ }
1064
+ catch (err) {
1065
+ spinner.fail("Rollback failed");
1066
+ const message = err instanceof Error ? err.message : String(err);
1067
+ console.error(chalk.red(`\nError: ${message}\n`));
1068
+ process.exit(1);
1069
+ }
1070
+ });
1071
+ // ----------------------------------------------------------------
589
1072
  // Error handling
590
1073
  // ----------------------------------------------------------------
591
1074
  program.exitOverride();
@@ -9,8 +9,18 @@ export interface InitOptions {
9
9
  framework?: string;
10
10
  /** Re-run agents on an existing duct.config.ts */
11
11
  update?: boolean;
12
- /** Non-interactive mode (auto-approve) */
12
+ /** Auto-approve all review prompts — for CI / scripted use */
13
13
  yes?: boolean;
14
+ /** Write unresolved review decisions to duct-review.json instead of prompting interactively */
15
+ noInteractive?: boolean;
16
+ /** Manual mode — topology + file selection only, no LLM. Generates a pre-filled template. */
17
+ manual?: boolean;
18
+ /** Path to an OpenAPI/Swagger spec file — skips Route + API agents */
19
+ apiSpec?: string;
20
+ /** Separate API base URL (for APIs on a different domain from the frontend) */
21
+ apiUrl?: string;
22
+ /** Industry/category override (e.g., fintech, ecommerce, saas) */
23
+ industry?: string;
14
24
  }
15
25
  export interface GeneratedFiles {
16
26
  configPath: string;