@duct-sdk/sdk 0.4.4 → 0.5.1

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 (60) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +36 -1
  3. package/TOKEN_SPEC.md +237 -0
  4. package/dist/adapters/react/page-context-guard.d.ts +7 -0
  5. package/dist/adapters/react/page-context-guard.js +26 -0
  6. package/dist/adapters/react/page-context-guard.test.d.ts +1 -0
  7. package/dist/adapters/react/page-context-guard.test.js +15 -0
  8. package/dist/adapters/react/shell.js +110 -37
  9. package/dist/adapters/react/use-page-context.d.ts +1 -1
  10. package/dist/adapters/react/use-page-context.js +6 -16
  11. package/dist/cli/agents/reviewer-agent.d.ts +3 -1
  12. package/dist/cli/agents/reviewer-agent.js +29 -21
  13. package/dist/cli/config-loader.d.ts +15 -0
  14. package/dist/cli/config-loader.js +187 -0
  15. package/dist/cli/config-loader.test.d.ts +1 -0
  16. package/dist/cli/config-loader.test.js +63 -0
  17. package/dist/cli/detectors/framework.d.ts +1 -1
  18. package/dist/cli/detectors/framework.js +40 -0
  19. package/dist/cli/generators/receiver.js +206 -76
  20. package/dist/cli/generators/shell.js +50 -4
  21. package/dist/cli/generators/shell.test.d.ts +1 -0
  22. package/dist/cli/generators/shell.test.js +73 -0
  23. package/dist/cli/generators/token-route.d.ts +1 -0
  24. package/dist/cli/generators/token-route.js +108 -5
  25. package/dist/cli/generators/wiring-snippets.d.ts +14 -0
  26. package/dist/cli/generators/wiring-snippets.js +180 -16
  27. package/dist/cli/generators/wiring-snippets.test.js +15 -1
  28. package/dist/cli/index.js +108 -151
  29. package/dist/cli/init.js +110 -17
  30. package/dist/cli/manifest-diff.d.ts +21 -0
  31. package/dist/cli/manifest-diff.js +158 -0
  32. package/dist/cli/manifest-diff.test.d.ts +1 -0
  33. package/dist/cli/manifest-diff.test.js +104 -0
  34. package/dist/cli/output-paths.d.ts +2 -0
  35. package/dist/cli/output-paths.js +22 -4
  36. package/dist/cli/processors/integration-audit.js +1 -1
  37. package/dist/core/config-policy.test.d.ts +1 -0
  38. package/dist/core/config-policy.test.js +101 -0
  39. package/dist/core/config.d.ts +86 -1
  40. package/dist/core/config.js +120 -2
  41. package/dist/core/invariants.test.d.ts +1 -0
  42. package/dist/core/invariants.test.js +217 -0
  43. package/dist/core/jcs.d.ts +5 -0
  44. package/dist/core/jcs.js +21 -0
  45. package/dist/core/receipt.d.ts +70 -0
  46. package/dist/core/receipt.js +86 -0
  47. package/dist/core/receipt.test.d.ts +1 -0
  48. package/dist/core/receipt.test.js +75 -0
  49. package/dist/core/replay-store.d.ts +51 -0
  50. package/dist/core/replay-store.js +65 -0
  51. package/dist/core/token.d.ts +14 -0
  52. package/dist/core/token.js +50 -18
  53. package/dist/core/token.test.d.ts +1 -0
  54. package/dist/core/token.test.js +66 -0
  55. package/dist/core/types.d.ts +72 -0
  56. package/dist/index.d.ts +6 -4
  57. package/dist/index.js +4 -2
  58. package/dist/server.d.ts +6 -4
  59. package/dist/server.js +4 -2
  60. package/package.json +91 -90
package/dist/cli/index.js CHANGED
@@ -16,10 +16,12 @@ import { getCandidateAuthBases, getConfiguredDashboard, getManifestApiBases, get
16
16
  import * as fs from "fs/promises";
17
17
  import * as path from "path";
18
18
  import * as os from "os";
19
- import * as vm from "node:vm";
20
- import { pathToFileURL, fileURLToPath } from "node:url";
19
+ import { fileURLToPath } from "node:url";
21
20
  import { readFileSync } from "fs";
22
- import { DuctConfigSchema } from "../core/config.js";
21
+ import { DuctConfigSchema, crossValidateDuctConfig } from "../core/config.js";
22
+ import { runAgentSafetyChecks } from "./agents/reviewer-agent.js";
23
+ import { ConfigRuntimeReferenceError, loadDuctConfig, } from "./config-loader.js";
24
+ import { computeManifestPrivilegeDiff, fetchLiveManifestConfig, formatManifestPrivilegeDiff, } from "./manifest-diff.js";
23
25
  // ----------------------------------------------------------------
24
26
  // Load all standard .env files in dotenv priority order
25
27
  // Priority (last-loaded wins when key already set by earlier file):
@@ -95,137 +97,6 @@ function loadAllEnvFilesSync() {
95
97
  // Load all .env files synchronously at startup (before any commands run)
96
98
  loadAllEnvFilesSync();
97
99
  // ----------------------------------------------------------------
98
- // Config loader helpers
99
- // ----------------------------------------------------------------
100
- function toCompiledCandidates(configPath) {
101
- const ext = path.extname(configPath).toLowerCase();
102
- if (ext !== ".ts" && ext !== ".tsx") {
103
- return [configPath];
104
- }
105
- const jsSibling = configPath.replace(/\.(ts|tsx)$/i, ".js");
106
- const mjsSibling = configPath.replace(/\.(ts|tsx)$/i, ".mjs");
107
- const cjsSibling = configPath.replace(/\.(ts|tsx)$/i, ".cjs");
108
- const distStyle = configPath
109
- .replace(/([\\/])src([\\/])/g, "$1dist$2")
110
- .replace(/\.(ts|tsx)$/i, ".js");
111
- return [...new Set([jsSibling, mjsSibling, cjsSibling, distStyle])];
112
- }
113
- function extractConfigObjectLiteral(source) {
114
- const marker = "defineDuctConfig(";
115
- const markerIndex = source.indexOf(marker);
116
- if (markerIndex === -1)
117
- return null;
118
- const startSearch = markerIndex + marker.length;
119
- let objectStart = -1;
120
- for (let i = startSearch; i < source.length; i++) {
121
- const ch = source[i];
122
- if (!/\s/.test(ch)) {
123
- if (ch !== "{")
124
- return null;
125
- objectStart = i;
126
- break;
127
- }
128
- }
129
- if (objectStart === -1)
130
- return null;
131
- let depth = 0;
132
- let inSingle = false;
133
- let inDouble = false;
134
- let inTemplate = false;
135
- let inLineComment = false;
136
- let inBlockComment = false;
137
- for (let i = objectStart; i < source.length; i++) {
138
- const ch = source[i];
139
- const next = source[i + 1] ?? "";
140
- const prev = source[i - 1] ?? "";
141
- if (inLineComment) {
142
- if (ch === "\n")
143
- inLineComment = false;
144
- continue;
145
- }
146
- if (inBlockComment) {
147
- if (prev === "*" && ch === "/")
148
- inBlockComment = false;
149
- continue;
150
- }
151
- if (!inSingle && !inDouble && !inTemplate) {
152
- if (ch === "/" && next === "/") {
153
- inLineComment = true;
154
- i++;
155
- continue;
156
- }
157
- if (ch === "/" && next === "*") {
158
- inBlockComment = true;
159
- i++;
160
- continue;
161
- }
162
- }
163
- if (!inDouble && !inTemplate && ch === "'" && prev !== "\\") {
164
- inSingle = !inSingle;
165
- continue;
166
- }
167
- if (!inSingle && !inTemplate && ch === '"' && prev !== "\\") {
168
- inDouble = !inDouble;
169
- continue;
170
- }
171
- if (!inSingle && !inDouble && ch === "`" && prev !== "\\") {
172
- inTemplate = !inTemplate;
173
- continue;
174
- }
175
- if (inSingle || inDouble || inTemplate) {
176
- continue;
177
- }
178
- if (ch === "{")
179
- depth++;
180
- if (ch === "}") {
181
- depth--;
182
- if (depth === 0) {
183
- return source.slice(objectStart, i + 1);
184
- }
185
- }
186
- }
187
- return null;
188
- }
189
- async function loadConfigFromSource(configPath) {
190
- const source = await fs.readFile(configPath, "utf-8");
191
- const objectLiteral = extractConfigObjectLiteral(source);
192
- if (!objectLiteral) {
193
- return null;
194
- }
195
- const script = new vm.Script(`(${objectLiteral})`, { filename: configPath });
196
- const evaluated = script.runInNewContext({ process, Math, Date, JSON }, { timeout: 1000 });
197
- if (!evaluated || typeof evaluated !== "object") {
198
- return null;
199
- }
200
- return evaluated;
201
- }
202
- async function loadDuctConfig(configPath) {
203
- const candidates = toCompiledCandidates(configPath);
204
- for (const candidate of candidates) {
205
- try {
206
- await fs.access(candidate);
207
- }
208
- catch {
209
- continue;
210
- }
211
- try {
212
- const module = await import(pathToFileURL(candidate).href);
213
- const loaded = module.default ?? module;
214
- if (loaded && typeof loaded === "object") {
215
- return loaded;
216
- }
217
- }
218
- catch {
219
- // Try next candidate or source fallback.
220
- }
221
- }
222
- const sourceLoaded = await loadConfigFromSource(configPath);
223
- if (sourceLoaded) {
224
- return sourceLoaded;
225
- }
226
- throw new Error("CONFIG_LOAD_FAILED");
227
- }
228
- // ----------------------------------------------------------------
229
100
  // Auth helpers — ~/.duct/auth.json
230
101
  // ----------------------------------------------------------------
231
102
  const DUCT_AUTH_FILE = path.join(os.homedir(), ".duct", "auth.json");
@@ -242,8 +113,9 @@ async function saveAuth(auth) {
242
113
  const dir = path.dirname(DUCT_AUTH_FILE);
243
114
  await fs.mkdir(dir, { recursive: true });
244
115
  await fs.writeFile(DUCT_AUTH_FILE, JSON.stringify(auth, null, 2), "utf-8");
245
- // Restrict to owner-only on Unix/macOS so the API key isn't world-readable.
246
- // Windows silently ignores this, which is acceptable (NTFS ACLs govern access there).
116
+ // Restrict to owner-only on Unix/macOS (mode 600).
117
+ // On Windows, chmod is typically ignored; access is governed by NTFS ACLs for
118
+ // the user's profile directory (~/.duct/). Keep the credentials file private.
247
119
  try {
248
120
  await fs.chmod(DUCT_AUTH_FILE, 0o600);
249
121
  }
@@ -405,7 +277,8 @@ program
405
277
  .command("push")
406
278
  .description("Push your duct.config.ts manifest to Duct cloud")
407
279
  .option("--config <path>", "Path to duct.config.ts", "duct.config.ts")
408
- .option("--dry-run", "Validate without pushing", false)
280
+ .option("--dry-run", "Print manifest privilege diff and exit without pushing", false)
281
+ .option("--yes", "Skip safety warnings (required in CI to override)", false)
409
282
  .action(async (opts) => {
410
283
  const spinner = ora("Reading config...").start();
411
284
  try {
@@ -424,9 +297,15 @@ program
424
297
  try {
425
298
  config = await loadDuctConfig(configPath);
426
299
  }
427
- catch {
300
+ catch (err) {
428
301
  spinner.fail("Could not load config");
429
- console.log(chalk.gray("\nTip: Ensure duct.config.ts exports `defineDuctConfig({...})` and does not depend on project-only runtime imports.\n"));
302
+ if (err instanceof ConfigRuntimeReferenceError) {
303
+ console.log(chalk.red(`\n${err.message}\n`));
304
+ }
305
+ else {
306
+ console.log(chalk.gray("\nTip: Ensure duct.config.ts exports `defineDuctConfig({...})` with static literals only.\n" +
307
+ "Only run `duct push` on trusted repositories.\n"));
308
+ }
430
309
  process.exit(1);
431
310
  }
432
311
  spinner.succeed("Config loaded");
@@ -441,6 +320,51 @@ program
441
320
  process.exit(1);
442
321
  }
443
322
  config = validation.data;
323
+ const validated = validation.data;
324
+ const crossIssues = crossValidateDuctConfig(validated);
325
+ const crossErrors = crossIssues.filter((i) => i.severity === "error");
326
+ if (crossErrors.length > 0) {
327
+ spinner.fail("Config cross-validation failed");
328
+ console.log(chalk.red("\nCross-field errors:\n"));
329
+ for (const issue of crossErrors) {
330
+ console.log(chalk.red(` • [${issue.area}] ${issue.issue}`));
331
+ console.log(chalk.gray(` Fix: ${issue.fix}`));
332
+ }
333
+ console.log();
334
+ process.exit(1);
335
+ }
336
+ const safetyIssues = runAgentSafetyChecks({
337
+ routes: validated.routes,
338
+ actions: validated.actions,
339
+ auth: validated.auth,
340
+ deeplinks: validated.deeplinks,
341
+ });
342
+ const safetyErrors = safetyIssues.filter((i) => i.severity === "error");
343
+ const safetyWarnings = safetyIssues.filter((i) => i.severity === "warning");
344
+ if (safetyErrors.length > 0) {
345
+ spinner.fail("Config failed agent-safety review");
346
+ console.log(chalk.red("\nAgent-safety errors (must fix before push):\n"));
347
+ for (const issue of safetyErrors) {
348
+ console.log(chalk.red(` • ${issue.message}`));
349
+ if (issue.suggestion)
350
+ console.log(chalk.gray(` ${issue.suggestion}`));
351
+ }
352
+ console.log();
353
+ process.exit(1);
354
+ }
355
+ if (safetyWarnings.length > 0) {
356
+ console.log(chalk.yellow("\n Agent-safety warnings:\n"));
357
+ for (const issue of safetyWarnings) {
358
+ console.log(chalk.yellow(` ⚠ ${issue.message}`));
359
+ if (issue.suggestion)
360
+ console.log(chalk.gray(` ${issue.suggestion}`));
361
+ }
362
+ if (!opts.yes) {
363
+ console.log(chalk.yellow("\n Push blocked. Re-run with --yes to acknowledge warnings (CI override).\n"));
364
+ process.exit(1);
365
+ }
366
+ console.log(chalk.gray("\n Continuing with --yes.\n"));
367
+ }
444
368
  // Warn on weak DUCT_SECRET_KEY — must be ≥ 32 chars for adequate HMAC entropy
445
369
  const secretKey = process.env["DUCT_SECRET_KEY"];
446
370
  if (secretKey && secretKey.length < 32) {
@@ -448,16 +372,46 @@ program
448
372
  ` Use at least 32 random characters for adequate HMAC-SHA256 entropy.\n` +
449
373
  ` Generate one: openssl rand -hex 32\n`));
450
374
  }
451
- if (opts.dryRun) {
452
- console.log(chalk.green("\n✓ Config is valid (dry-run)\n"));
453
- console.log(JSON.stringify(config, null, 2).slice(0, 500) + "\n...\n");
454
- return;
455
- }
456
- // Load API key: env var takes precedence, then ~/.duct/auth.json
375
+ const shellId = validated.shellId;
376
+ // ── Live manifest diff (privilege deltas) ───────────────────────────────
457
377
  let apiKey = process.env["DUCT_API_KEY"];
378
+ const authProfile = await readAuth();
458
379
  if (!apiKey) {
459
- const auth = await readAuth();
460
- apiKey = auth?.token;
380
+ apiKey = authProfile?.token;
381
+ }
382
+ let liveConfig = null;
383
+ if (apiKey) {
384
+ const liveSpinner = ora("Fetching live manifest for diff…").start();
385
+ liveConfig = await fetchLiveManifestConfig(shellId, apiKey, authProfile);
386
+ liveSpinner.stop();
387
+ }
388
+ else {
389
+ try {
390
+ const snapshotPath = path.resolve(cwd, ".duct-manifest.json");
391
+ const snapshotRaw = await fs.readFile(snapshotPath, "utf-8");
392
+ liveConfig = JSON.parse(snapshotRaw);
393
+ console.log(chalk.gray("\n Using .duct-manifest.json as diff baseline (not logged in).\n"));
394
+ }
395
+ catch {
396
+ console.log(chalk.gray("\n No live manifest baseline (first push or run `npx duct login`).\n"));
397
+ }
398
+ }
399
+ const privilegeDiff = computeManifestPrivilegeDiff(validated, liveConfig);
400
+ const diffLines = formatManifestPrivilegeDiff(privilegeDiff);
401
+ console.log(chalk.bold("\n Manifest privilege diff:\n"));
402
+ for (const line of diffLines) {
403
+ const color = privilegeDiff.hasPrivilegeIncrease ? chalk.red : chalk.green;
404
+ console.log(color(` ${line}`));
405
+ }
406
+ console.log();
407
+ if (privilegeDiff.hasPrivilegeIncrease && !opts.yes) {
408
+ console.log(chalk.red("\n Push blocked — privilege-increasing changes require explicit confirmation.\n" +
409
+ " Re-run with --yes to acknowledge (CI override).\n"));
410
+ process.exit(1);
411
+ }
412
+ if (opts.dryRun) {
413
+ console.log(chalk.green("✓ Dry-run complete — manifest not pushed.\n"));
414
+ return;
461
415
  }
462
416
  if (!apiKey) {
463
417
  console.error(chalk.red("\nNot logged in.\n"));
@@ -479,8 +433,7 @@ program
479
433
  config = { ...config, precomputedWorkflows };
480
434
  }
481
435
  const pushSpinner = ora("Pushing to Duct cloud...").start();
482
- const shellId = config["shellId"] ?? "unknown";
483
- const auth = await readAuth();
436
+ const auth = authProfile;
484
437
  const manifestBases = getManifestApiBases(auth);
485
438
  let success = false;
486
439
  let lastError = "";
@@ -587,6 +540,8 @@ program
587
540
  }
588
541
  let rawKey;
589
542
  if (opts.token) {
543
+ console.log(chalk.yellow("\n ⚠ Passing --token on the command line stores the key in your shell history.\n" +
544
+ " Prefer interactive login (masked prompt) or set DUCT_API_KEY in the environment.\n"));
590
545
  rawKey = opts.token;
591
546
  }
592
547
  else {
@@ -627,7 +582,9 @@ program
627
582
  }
628
583
  spinner.succeed(`Logged in as ${chalk.bold(auth.email)} (${auth.slug})`);
629
584
  console.log(chalk.gray(` API base: ${auth.apiBase}`));
630
- console.log(chalk.gray(` Credentials saved to ${DUCT_AUTH_FILE} (mode 600)\n`));
585
+ console.log(chalk.gray(` Credentials saved to ${DUCT_AUTH_FILE}\n` +
586
+ " Storage: JSON file with your API key (dk_live_…). Unix/macOS: file mode 600.\n" +
587
+ " Windows: NTFS ACLs on your user profile govern access — keep ~/.duct private.\n"));
631
588
  console.log(chalk.yellow(` ⚠ Keep this file private — it contains your API key.\n Add ${DUCT_AUTH_FILE} to your global .gitignore.\n`));
632
589
  // Best-effort: fetch and display provisioned shells for this account.
633
590
  // Account/identity endpoints use the auth base URL, not the API base URL.
@@ -1013,7 +970,7 @@ program
1013
970
  const configContent = `// Restored from push history — hash: ${hash}
1014
971
  // Pushed at: ${record.pushed_at ?? "unknown"}
1015
972
  // Run \`npx duct push\` to re-sync this version to Duct cloud.
1016
- import { defineDuctConfig } from '@duct/sdk';
973
+ import { defineDuctConfig } from '@duct-sdk/sdk';
1017
974
 
1018
975
  export default defineDuctConfig(${JSON.stringify(manifest, null, 2)});
1019
976
  `;
package/dist/cli/init.js CHANGED
@@ -22,7 +22,7 @@ import { runInteractiveReview } from "./prompts/review.js";
22
22
  import { generateConfigFile, generateManualTemplate } from "./generators/config.js";
23
23
  import { generateReceiver, generateTokenRoute, } from "./generators/receiver.js";
24
24
  import { generateShell, generateEnvTemplateForFramework, } from "./generators/shell.js";
25
- import { getGeneratedOutputPaths } from "./output-paths.js";
25
+ import { getGeneratedOutputPaths, frameworkHasShellComponent } from "./output-paths.js";
26
26
  import { buildWiringPlan, sideEffectActionsApproved, } from "./generators/wiring-snippets.js";
27
27
  import { integrationAuditFailed, printIntegrationAuditIssues, runIntegrationAudit, } from "./processors/integration-audit.js";
28
28
  import { getActiveAuthBase, getConfiguredDashboard, getDocsUrl, getManifestApiBases, } from "../core/endpoints.js";
@@ -309,6 +309,43 @@ async function writeFile(filePath, content, dryRun) {
309
309
  await fs.mkdir(path.dirname(filePath), { recursive: true });
310
310
  await fs.writeFile(filePath, content, "utf-8");
311
311
  }
312
+ async function resolveGeneratedFileWriteMode(filePaths, yes, dryRun) {
313
+ const existing = [];
314
+ for (const filePath of filePaths) {
315
+ if (await fileExists(filePath)) {
316
+ existing.push(filePath);
317
+ }
318
+ }
319
+ if (existing.length === 0 || dryRun) {
320
+ return "all";
321
+ }
322
+ if (yes) {
323
+ console.log(chalk.gray(` Skipping ${existing.length} existing generated file(s) (--yes merge-safe mode).\n`));
324
+ return "skip-existing";
325
+ }
326
+ console.log(chalk.yellow("\n Existing generated files detected:\n"));
327
+ for (const filePath of existing) {
328
+ console.log(chalk.yellow(` • ${filePath}`));
329
+ }
330
+ const { action } = await inquirer.prompt([
331
+ {
332
+ type: "list",
333
+ name: "action",
334
+ message: "How should init handle existing files?",
335
+ choices: [
336
+ { name: "Skip existing files (merge-safe — recommended)", value: "skip-existing" },
337
+ { name: "Overwrite all generated files", value: "all" },
338
+ { name: "Abort without writing", value: "abort" },
339
+ ],
340
+ default: "skip-existing",
341
+ },
342
+ ]);
343
+ if (action === "abort") {
344
+ console.log(chalk.yellow("\n Aborted. No files written.\n"));
345
+ return "abort";
346
+ }
347
+ return action;
348
+ }
312
349
  async function fileExists(filePath) {
313
350
  try {
314
351
  await fs.access(filePath);
@@ -318,6 +355,13 @@ async function fileExists(filePath) {
318
355
  return false;
319
356
  }
320
357
  }
358
+ async function writeGeneratedFile(filePath, content, dryRun, writeMode) {
359
+ if (writeMode === "skip-existing" && (await fileExists(filePath))) {
360
+ console.log(chalk.gray(` Skipped (exists): ${path.relative(process.cwd(), filePath)}`));
361
+ return;
362
+ }
363
+ await writeFile(filePath, content, dryRun);
364
+ }
321
365
  /**
322
366
  * Returns relative paths of files changed in git since HEAD.
323
367
  * Combines unstaged changes, staged changes, and untracked files.
@@ -363,6 +407,8 @@ function frameworkPriority(name) {
363
407
  sveltekit: 80,
364
408
  nuxt: 78,
365
409
  vue3: 75,
410
+ express: 60,
411
+ fastapi: 55,
366
412
  unknown: 0,
367
413
  };
368
414
  return map[name];
@@ -665,10 +711,32 @@ export async function runInit(opts = {}) {
665
711
  console.log(chalk.gray(` Using manual framework: ${frameworkDisplay(framework)}`));
666
712
  }
667
713
  }
668
- if (framework.name === "unknown") {
669
- framework = frameworkFromName("next-app", projectRoot);
670
- console.log(chalk.yellow(" Falling back to Next.js App Router. Re-run init and choose a stack manually if this is incorrect."));
671
- }
714
+ // No silent fallback to Next.js — an unrecognized stack is caught by the
715
+ // framework support gate below. Writing Next.js files into a non-Next repo
716
+ // (Express/Python/Vue) produced broken, unrunnable output.
717
+ }
718
+ // ---- Framework support gate ----
719
+ // Only these frameworks have complete, tested receiver + token-route + shell
720
+ // generators. Nuxt/Vue3/Express/Python fall through the generators and emit
721
+ // Next.js-shaped or misnamed files, so stop with clear guidance instead of guessing.
722
+ const FULLY_SUPPORTED_FRAMEWORKS = [
723
+ "next-app",
724
+ "next-pages",
725
+ "remix",
726
+ "sveltekit",
727
+ "vite-react",
728
+ "nuxt",
729
+ "vue3",
730
+ "express",
731
+ "fastapi",
732
+ ];
733
+ if (!FULLY_SUPPORTED_FRAMEWORKS.includes(framework.name)) {
734
+ console.log(chalk.red(`\n ✗ Couldn't detect a supported framework in this project.\n`));
735
+ console.log(chalk.gray(" Supported: Next.js (App/Pages Router), Remix, SvelteKit, Vite + React, Nuxt, Vue 3, Express, FastAPI.\n"));
736
+ console.log(" Options:");
737
+ console.log(` • Force your stack: ${chalk.cyan("npx duct init --framework <next-app|next-pages|remix|sveltekit|vite-react|nuxt|vue3|express|fastapi>")}`);
738
+ console.log(` • See the integration guide: ${chalk.cyan(getDocsUrl() + "/quickstart")}\n`);
739
+ process.exit(1);
672
740
  }
673
741
  // ---- Step 2: Project structure + auth detection ----
674
742
  const sandboxFs = new SandboxFS(projectRoot);
@@ -1019,7 +1087,9 @@ export async function runInit(opts = {}) {
1019
1087
  console.log(chalk.gray(` ${path.relative(cwd, outputPaths.configPath).padEnd(22)} manifest`));
1020
1088
  console.log(chalk.gray(` ${path.relative(cwd, outputPaths.receiverPath).padEnd(22)} receiver route`));
1021
1089
  console.log(chalk.gray(` ${path.relative(cwd, outputPaths.tokenRoutePath).padEnd(22)} token route`));
1022
- console.log(chalk.gray(` ${path.relative(cwd, outputPaths.shellComponentPath).padEnd(22)} widget component`));
1090
+ if (frameworkHasShellComponent(framework)) {
1091
+ console.log(chalk.gray(` ${path.relative(cwd, outputPaths.shellComponentPath).padEnd(22)} widget component`));
1092
+ }
1023
1093
  console.log(chalk.gray(` ${path.relative(cwd, outputPaths.envTemplatePath).padEnd(22)} environment template\n`));
1024
1094
  console.log(chalk.gray(" All files are yours to edit. Duct cloud reads duct.config.ts on deploy."));
1025
1095
  // ---- Step 6: Prompt for approval ----
@@ -1121,15 +1191,33 @@ export async function runInit(opts = {}) {
1121
1191
  : generateConfigFile(config);
1122
1192
  const receiverContent = generateReceiver(config, framework);
1123
1193
  const tokenRouteContent = generateTokenRoute(config, framework);
1124
- const shellContent = generateShell(config, framework);
1194
+ // Backend-only stacks (Express API, FastAPI) have no embeddable widget.
1195
+ const hasShell = frameworkHasShellComponent(framework);
1196
+ const shellContent = hasShell ? generateShell(config, framework) : "";
1125
1197
  const envContent = generateEnvTemplateForFramework(config, framework);
1126
- await writeFile(outputPaths.configPath, configContent, dryRun);
1127
- await writeFile(outputPaths.receiverPath, receiverContent, dryRun);
1128
- await writeFile(outputPaths.tokenRoutePath, tokenRouteContent, dryRun);
1129
- await writeFile(outputPaths.shellComponentPath, shellContent, dryRun);
1130
- await writeFile(path.join(projectRoot, wiringPlan.middlewareSnippetPath), wiringPlan.middlewareSnippet, dryRun);
1198
+ const generatedPaths = [
1199
+ outputPaths.configPath,
1200
+ outputPaths.receiverPath,
1201
+ outputPaths.tokenRoutePath,
1202
+ ...(hasShell ? [outputPaths.shellComponentPath] : []),
1203
+ path.join(projectRoot, wiringPlan.middlewareSnippetPath),
1204
+ ...(wiringPlan.uctSnippetPath
1205
+ ? [path.join(projectRoot, wiringPlan.uctSnippetPath)]
1206
+ : []),
1207
+ ];
1208
+ const writeMode = await resolveGeneratedFileWriteMode(generatedPaths, yes, dryRun);
1209
+ if (writeMode === "abort") {
1210
+ return;
1211
+ }
1212
+ await writeGeneratedFile(outputPaths.configPath, configContent, dryRun, writeMode);
1213
+ await writeGeneratedFile(outputPaths.receiverPath, receiverContent, dryRun, writeMode);
1214
+ await writeGeneratedFile(outputPaths.tokenRoutePath, tokenRouteContent, dryRun, writeMode);
1215
+ if (hasShell) {
1216
+ await writeGeneratedFile(outputPaths.shellComponentPath, shellContent, dryRun, writeMode);
1217
+ }
1218
+ await writeGeneratedFile(path.join(projectRoot, wiringPlan.middlewareSnippetPath), wiringPlan.middlewareSnippet, dryRun, writeMode);
1131
1219
  if (wiringPlan.uctSnippet && wiringPlan.uctSnippetPath) {
1132
- await writeFile(path.join(projectRoot, wiringPlan.uctSnippetPath), wiringPlan.uctSnippet, dryRun);
1220
+ await writeGeneratedFile(path.join(projectRoot, wiringPlan.uctSnippetPath), wiringPlan.uctSnippet, dryRun, writeMode);
1133
1221
  }
1134
1222
  // Safely append to the env template
1135
1223
  const envExists = await fileExists(outputPaths.envTemplatePath);
@@ -1232,10 +1320,15 @@ export async function runInit(opts = {}) {
1232
1320
  console.log(` Manifest synced · ${config.routes?.length ?? 0} routes · ${config.actions?.length ?? 0} actions · ${config.deeplinks?.length ?? 0} deeplinks`);
1233
1321
  console.log(` Status registered with Duct cloud\n`);
1234
1322
  console.log(` Next:`);
1235
- console.log(` 1. Review duct.config.ts — set agentAccessible flags on your actions`);
1236
- console.log(` 2. Mount <DuctShell /> in your root layout (see ${path.relative(projectRoot, outputPaths.shellComponentPath)})`);
1237
- console.log(` 3. Wire verifyDuctToken from ${wiringPlan.middlewareSnippetPath} into ${authDetection.middlewarePath ?? "your API middleware"}`);
1238
- console.log(` 4. Run \`npx duct checkup\` to re-run the integration audit\n`);
1323
+ console.log(` 1. Set secrets: copy ${path.relative(projectRoot, outputPaths.envTemplatePath)} into your env file, then paste`);
1324
+ console.log(` ${chalk.cyan("DUCT_SECRET_KEY")} from Dashboard → Shell → Settings ${chalk.gray("(generated routes return HTTP 500 until it is set)")}`);
1325
+ console.log(` 2. Review duct.config.ts — set agentAccessible flags on your actions`);
1326
+ console.log(frameworkHasShellComponent(framework)
1327
+ ? ` 3. Mount <DuctShell /> in your root layout (see ${path.relative(projectRoot, outputPaths.shellComponentPath)})`
1328
+ : ` 3. Embed <DuctShell /> in your frontend app — this backend only verifies Duct tokens; the widget lives in your UI`);
1329
+ console.log(` 4. Wire verifyDuctToken from ${wiringPlan.middlewareSnippetPath} into ${authDetection.middlewarePath ?? "your API middleware"}`);
1330
+ console.log(` 5. Before deploying, set ${chalk.cyan("NEXT_PUBLIC_DUCT_SHELL_HOST")} to your Duct shell host origin ${chalk.gray("(defaults to http://localhost:3000)")}`);
1331
+ console.log(` 6. Run \`npx duct checkup\` to re-run the integration audit\n`);
1239
1332
  console.log(` Docs ${docsBase}/quickstart`);
1240
1333
  console.log(` Support ${dashboard}/discord`);
1241
1334
  console.log(chalk.gray(` ─────────────────────────────────────────────────────────────\n`));
@@ -0,0 +1,21 @@
1
+ import type { DuctConfig } from "../core/types.js";
2
+ import type { EndpointProfile } from "../core/endpoints.js";
3
+ export type ManifestPrivilegeDeltaKind = "agent_accessible_enabled" | "side_effects_enabled" | "sensitivity_downgrade" | "base_url_change" | "allowed_callers_widened" | "intershell_enabled" | "registry_public" | "new_agent_accessible_action";
4
+ export interface ManifestPrivilegeDelta {
5
+ kind: ManifestPrivilegeDeltaKind;
6
+ path: string;
7
+ message: string;
8
+ }
9
+ export interface ManifestPrivilegeDiff {
10
+ isFirstPush: boolean;
11
+ deltas: ManifestPrivilegeDelta[];
12
+ hasPrivilegeIncrease: boolean;
13
+ }
14
+ /**
15
+ * Compare a candidate manifest against the live (or last-pushed) manifest and
16
+ * return privilege-increasing deltas operators must acknowledge before push.
17
+ */
18
+ export declare function computeManifestPrivilegeDiff(candidate: DuctConfig, live: DuctConfig | null | undefined): ManifestPrivilegeDiff;
19
+ /** Fetch the live manifest config from Duct cloud (null when shell has no manifest yet). */
20
+ export declare function fetchLiveManifestConfig(shellId: string, apiKey: string, profile?: EndpointProfile | null): Promise<DuctConfig | null>;
21
+ export declare function formatManifestPrivilegeDiff(diff: ManifestPrivilegeDiff): string[];