@duct-sdk/sdk 0.5.13 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -243
  4. package/dist/cli/action-confusion-format.d.ts +17 -0
  5. package/dist/cli/action-confusion-format.js +24 -0
  6. package/dist/cli/add.d.ts +7 -0
  7. package/dist/cli/add.js +152 -0
  8. package/dist/cli/agent-prompt.d.ts +3 -0
  9. package/dist/cli/agent-prompt.js +39 -0
  10. package/dist/cli/api-sources.d.ts +26 -0
  11. package/dist/cli/api-sources.js +222 -0
  12. package/dist/cli/cloud.d.ts +162 -0
  13. package/dist/cli/cloud.js +306 -0
  14. package/dist/cli/config-loader.d.ts +14 -0
  15. package/dist/cli/config-loader.js +56 -7
  16. package/dist/cli/device-login.d.ts +17 -0
  17. package/dist/cli/device-login.js +75 -0
  18. package/dist/cli/drift.js +6 -6
  19. package/dist/cli/generators/any-stack.d.ts +3 -0
  20. package/dist/cli/generators/any-stack.js +97 -0
  21. package/dist/cli/generators/config.js +3 -2
  22. package/dist/cli/generators/receiver.js +7 -7
  23. package/dist/cli/generators/shell.js +12 -12
  24. package/dist/cli/generators/token-route.js +245 -245
  25. package/dist/cli/generators/wiring-snippets.d.ts +0 -14
  26. package/dist/cli/generators/wiring-snippets.js +188 -305
  27. package/dist/cli/index.js +396 -611
  28. package/dist/cli/mcp-core.d.ts +42 -0
  29. package/dist/cli/mcp-core.js +161 -0
  30. package/dist/cli/mcp-setup.d.ts +4 -0
  31. package/dist/cli/mcp-setup.js +352 -0
  32. package/dist/cli/mcp.d.ts +2 -0
  33. package/dist/cli/mcp.js +457 -0
  34. package/dist/cli/migrate-intershell.js +5 -5
  35. package/dist/cli/policy-defaults.d.ts +37 -0
  36. package/dist/cli/policy-defaults.js +127 -0
  37. package/dist/cli/policy-replay-format.d.ts +9 -0
  38. package/dist/cli/policy-replay-format.js +46 -0
  39. package/dist/cli/processors/integration-audit.js +2 -2
  40. package/dist/cli/processors/openapi-parser.d.ts +5 -0
  41. package/dist/cli/processors/openapi-parser.js +8 -3
  42. package/dist/cli/project-loader.d.ts +58 -0
  43. package/dist/cli/project-loader.js +198 -0
  44. package/dist/cli/project-writer.d.ts +23 -0
  45. package/dist/cli/project-writer.js +171 -0
  46. package/dist/cli/push.d.ts +43 -0
  47. package/dist/cli/push.js +308 -0
  48. package/dist/cli/safety-checks.d.ts +9 -0
  49. package/dist/cli/safety-checks.js +29 -0
  50. package/dist/cli/setup.d.ts +20 -0
  51. package/dist/cli/setup.js +349 -0
  52. package/dist/cli/shell-name.d.ts +8 -0
  53. package/dist/cli/shell-name.js +29 -0
  54. package/dist/cli/shells.d.ts +22 -0
  55. package/dist/cli/shells.js +122 -0
  56. package/dist/cli/split.d.ts +7 -0
  57. package/dist/cli/split.js +71 -0
  58. package/dist/cli/sync.d.ts +25 -0
  59. package/dist/cli/sync.js +120 -0
  60. package/dist/cli/test-runner.d.ts +21 -0
  61. package/dist/cli/test-runner.js +281 -0
  62. package/dist/core/compile.d.ts +43 -0
  63. package/dist/core/compile.js +512 -0
  64. package/dist/core/config.d.ts +538 -19
  65. package/dist/core/config.js +22 -14
  66. package/dist/core/login-handoff.d.ts +1 -1
  67. package/dist/core/login-handoff.js +1 -1
  68. package/dist/core/project.d.ts +1864 -0
  69. package/dist/core/project.js +291 -0
  70. package/dist/core/readiness-checks.js +2 -2
  71. package/dist/core/types.d.ts +10 -1
  72. package/dist/index.d.ts +2 -0
  73. package/dist/index.js +1 -0
  74. package/dist/project.d.ts +4 -0
  75. package/dist/project.js +8 -0
  76. package/dist/server.d.ts +2 -0
  77. package/dist/server.js +1 -0
  78. package/package.json +94 -95
  79. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  80. package/dist/adapters/react/page-context-guard.test.js +0 -15
  81. package/dist/cli/agents/api-agent.d.ts +0 -22
  82. package/dist/cli/agents/api-agent.js +0 -761
  83. package/dist/cli/agents/auth-agent.d.ts +0 -7
  84. package/dist/cli/agents/auth-agent.js +0 -212
  85. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  86. package/dist/cli/agents/deeplink-agent.js +0 -285
  87. package/dist/cli/agents/llm.d.ts +0 -33
  88. package/dist/cli/agents/llm.js +0 -309
  89. package/dist/cli/agents/pipeline.d.ts +0 -72
  90. package/dist/cli/agents/pipeline.js +0 -421
  91. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  92. package/dist/cli/agents/reviewer-agent.js +0 -450
  93. package/dist/cli/agents/route-agent.d.ts +0 -17
  94. package/dist/cli/agents/route-agent.js +0 -383
  95. package/dist/cli/config-loader.test.d.ts +0 -1
  96. package/dist/cli/config-loader.test.js +0 -63
  97. package/dist/cli/detectors/topology.d.ts +0 -46
  98. package/dist/cli/detectors/topology.js +0 -417
  99. package/dist/cli/generators/config.test.d.ts +0 -1
  100. package/dist/cli/generators/config.test.js +0 -222
  101. package/dist/cli/generators/shell.test.d.ts +0 -1
  102. package/dist/cli/generators/shell.test.js +0 -73
  103. package/dist/cli/generators/token-route.test.d.ts +0 -1
  104. package/dist/cli/generators/token-route.test.js +0 -53
  105. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  106. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  107. package/dist/cli/init.d.ts +0 -32
  108. package/dist/cli/init.js +0 -1336
  109. package/dist/cli/manifest-diff.test.d.ts +0 -1
  110. package/dist/cli/manifest-diff.test.js +0 -144
  111. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  112. package/dist/cli/processors/curl-parser.test.js +0 -24
  113. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  114. package/dist/cli/processors/integration-audit.test.js +0 -154
  115. package/dist/cli/processors/postprocess.d.ts +0 -22
  116. package/dist/cli/processors/postprocess.js +0 -107
  117. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  118. package/dist/cli/processors/prisma-parser.js +0 -117
  119. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  120. package/dist/cli/processors/verify-discovery.js +0 -193
  121. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  122. package/dist/cli/processors/verify-discovery.test.js +0 -153
  123. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  124. package/dist/cli/processors/zod-extractor.js +0 -153
  125. package/dist/cli/prompts/review.d.ts +0 -61
  126. package/dist/cli/prompts/review.js +0 -410
  127. package/dist/cli/selectors/express.d.ts +0 -12
  128. package/dist/cli/selectors/express.js +0 -117
  129. package/dist/cli/selectors/fastapi.d.ts +0 -12
  130. package/dist/cli/selectors/fastapi.js +0 -122
  131. package/dist/cli/selectors/generic.d.ts +0 -10
  132. package/dist/cli/selectors/generic.js +0 -74
  133. package/dist/cli/selectors/index.d.ts +0 -37
  134. package/dist/cli/selectors/index.js +0 -315
  135. package/dist/cli/selectors/next.d.ts +0 -12
  136. package/dist/cli/selectors/next.js +0 -130
  137. package/dist/core/config-policy.test.d.ts +0 -1
  138. package/dist/core/config-policy.test.js +0 -101
  139. package/dist/core/config-roundtrip.test.d.ts +0 -1
  140. package/dist/core/config-roundtrip.test.js +0 -180
  141. package/dist/core/endpoint-guard.test.d.ts +0 -1
  142. package/dist/core/endpoint-guard.test.js +0 -57
  143. package/dist/core/env-diagnostics.test.d.ts +0 -1
  144. package/dist/core/env-diagnostics.test.js +0 -31
  145. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  146. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  147. package/dist/core/evidence-bundle.test.d.ts +0 -1
  148. package/dist/core/evidence-bundle.test.js +0 -58
  149. package/dist/core/invariants.test.d.ts +0 -1
  150. package/dist/core/invariants.test.js +0 -217
  151. package/dist/core/login-handoff.test.d.ts +0 -1
  152. package/dist/core/login-handoff.test.js +0 -31
  153. package/dist/core/profile.test.d.ts +0 -1
  154. package/dist/core/profile.test.js +0 -95
  155. package/dist/core/readiness-checks.test.d.ts +0 -1
  156. package/dist/core/readiness-checks.test.js +0 -106
  157. package/dist/core/receipt.test.d.ts +0 -1
  158. package/dist/core/receipt.test.js +0 -75
  159. package/dist/core/sdk-entrypoint.test.d.ts +0 -1
  160. package/dist/core/sdk-entrypoint.test.js +0 -8
  161. package/dist/core/side-effects-review.test.d.ts +0 -1
  162. package/dist/core/side-effects-review.test.js +0 -28
  163. package/dist/core/token.conformance.test.d.ts +0 -1
  164. package/dist/core/token.conformance.test.js +0 -43
  165. package/dist/core/token.test.d.ts +0 -1
  166. package/dist/core/token.test.js +0 -66
package/dist/cli/init.js DELETED
@@ -1,1336 +0,0 @@
1
- // ============================================================
2
- // @duct/sdk — Init Command
3
- // Main orchestrator for `duct init`
4
- // ============================================================
5
- import * as fs from "fs/promises";
6
- import * as path from "path";
7
- import * as os from "os";
8
- import * as readline from "readline";
9
- import ora from "ora";
10
- import chalk from "chalk";
11
- import inquirer from "inquirer";
12
- import { validateDuctConfigStrict, } from "../core/config.js";
13
- import { normalizeDuctConfigForCodegen } from "./generators/normalize.js";
14
- import { SandboxFS } from "./fs/sandbox.js";
15
- import { detectFramework } from "./detectors/framework.js";
16
- import { detectAuth } from "./detectors/auth.js";
17
- import { discoverTopology } from "./detectors/topology.js";
18
- import { buildReadList } from "./selectors/index.js";
19
- import { parsePrismaSchema, buildDataModelFromPrisma } from "./processors/prisma-parser.js";
20
- import { runAgentPipeline, DuctPipelineEmitter, } from "./agents/pipeline.js";
21
- import { runInteractiveReview } from "./prompts/review.js";
22
- import { generateConfigFile, generateManualTemplate } from "./generators/config.js";
23
- import { generateReceiver, generateTokenRoute, } from "./generators/receiver.js";
24
- import { generateShell, generateEnvTemplateForFramework, } from "./generators/shell.js";
25
- import { getGeneratedOutputPaths, frameworkHasShellComponent } from "./output-paths.js";
26
- import { buildWiringPlan, sideEffectActionsApproved, } from "./generators/wiring-snippets.js";
27
- import { integrationAuditFailed, printIntegrationAuditIssues, runIntegrationAudit, } from "./processors/integration-audit.js";
28
- import { getActiveAuthBase, getConfiguredDashboard, getDocsUrl, getManifestApiBases, } from "../core/endpoints.js";
29
- import { fileURLToPath } from "node:url";
30
- import { exec } from "child_process";
31
- const pkgPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../package.json");
32
- const VERSION = JSON.parse(await fs.readFile(pkgPath, "utf-8")).version;
33
- // ----------------------------------------------------------------
34
- // Auth — read stored ~/.duct/auth.json
35
- // ----------------------------------------------------------------
36
- const DUCT_AUTH_FILE = path.join(os.homedir(), ".duct", "auth.json");
37
- async function loadAuth() {
38
- try {
39
- const raw = await fs.readFile(DUCT_AUTH_FILE, "utf-8");
40
- return JSON.parse(raw);
41
- }
42
- catch {
43
- return null;
44
- }
45
- }
46
- /**
47
- * Fetch the company's provisioned shells from the Duct auth service.
48
- *
49
- * Account/identity endpoints live on the auth service (port 3001 locally,
50
- * auth.<host> in prod), NOT the API host. Calling the wrong base URL
51
- * was the root cause of a "No shells provisioned" false negative bug.
52
- */
53
- async function fetchAccountShells(apiKey, authBase) {
54
- const url = `${authBase}/v1/account/shells`;
55
- let res;
56
- try {
57
- res = await fetch(url, {
58
- headers: { Authorization: `Bearer ${apiKey}` },
59
- });
60
- }
61
- catch (err) {
62
- const message = err instanceof Error ? err.message : String(err);
63
- throw new Error(`Could not reach Duct auth service at ${authBase} (${message})`);
64
- }
65
- if (res.status === 401 || res.status === 403) {
66
- throw new Error(`Duct auth rejected your API key (HTTP ${res.status}). ` +
67
- `Re-run \`npx duct login\` to refresh credentials.`);
68
- }
69
- if (!res.ok) {
70
- const body = await res.text().catch(() => "");
71
- throw new Error(`Duct auth returned HTTP ${res.status} from ${url}` +
72
- (body ? ` — ${body.slice(0, 200)}` : ""));
73
- }
74
- const data = await res.json();
75
- return data.shells ?? [];
76
- }
77
- // ----------------------------------------------------------------
78
- // Helpers
79
- // ----------------------------------------------------------------
80
- function printWiringPlan(projectRoot, wiringPlan) {
81
- console.log(chalk.bold("\n Wiring plan\n"));
82
- for (const item of wiringPlan.items) {
83
- const relPath = path.relative(projectRoot, item.path);
84
- const tag = item.action === "create"
85
- ? chalk.green("create")
86
- : item.action === "modify"
87
- ? chalk.yellow("modify")
88
- : chalk.blue("verify");
89
- console.log(` ${tag.padEnd(8)} ${chalk.gray(relPath.padEnd(36))} ${item.summary}`);
90
- }
91
- console.log(chalk.gray(`\n Middleware snippet: ${wiringPlan.middlewareSnippetPath}` +
92
- (wiringPlan.uctSnippetPath ? ` · consent snippet: ${wiringPlan.uctSnippetPath}` : "")));
93
- console.log("");
94
- }
95
- function frameworkDisplay(framework) {
96
- const map = {
97
- "next-app": "Next.js (App Router)",
98
- "next-pages": "Next.js (Pages Router)",
99
- remix: "Remix",
100
- "vite-react": "Vite + React",
101
- sveltekit: "SvelteKit",
102
- unknown: "Unknown",
103
- };
104
- return map[framework.name] ?? framework.name;
105
- }
106
- function authDisplay(system) {
107
- const map = {
108
- nextauth: "NextAuth.js",
109
- clerk: "Clerk",
110
- auth0: "Auth0",
111
- "custom-jwt": "Custom JWT",
112
- "session-cookie": "Session Cookie",
113
- none: "No auth",
114
- unknown: "Unknown",
115
- };
116
- return map[system] ?? system;
117
- }
118
- function frameworkFromName(name, srcDir) {
119
- return {
120
- name,
121
- version: "unknown",
122
- hasAppRouter: name === "next-app",
123
- hasPagesRouter: name === "next-pages",
124
- packageManager: "unknown",
125
- srcDir,
126
- };
127
- }
128
- function hasAnyLlmCredential() {
129
- const keys = [
130
- "ANTHROPIC_API_KEY",
131
- "OPENAI_API_KEY",
132
- "GEMINI_API_KEY",
133
- "GROQ_API_KEY",
134
- "XAI_API_KEY",
135
- "OPENROUTER_API_KEY",
136
- "DUCT_API_KEY",
137
- ];
138
- return keys.some((key) => Boolean(process.env[key]?.trim()));
139
- }
140
- async function checkLlmCredentialsAndPrompt(noAgents, yes) {
141
- if (noAgents) {
142
- return false; // User explicitly requested blank template
143
- }
144
- if (hasAnyLlmCredential()) {
145
- return true; // User has at least one LLM credential
146
- }
147
- // No LLM credentials found — warn and ask
148
- console.log(chalk.yellow("\n ⚠ No LLM API key detected\n"));
149
- console.log(chalk.gray(" The AI agent pipeline requires one LLM provider key:"));
150
- console.log(chalk.gray(" • ANTHROPIC_API_KEY (Anthropic Claude)"));
151
- console.log(chalk.gray(" • OPENAI_API_KEY (OpenAI)"));
152
- console.log(chalk.gray(" • GEMINI_API_KEY (Google Gemini)"));
153
- console.log(chalk.gray(" • GROQ_API_KEY (Groq — groq.com)"));
154
- console.log(chalk.gray(" • XAI_API_KEY (Grok — xAI / api.x.ai)"));
155
- console.log(chalk.gray(" • OPENROUTER_API_KEY (OpenRouter)"));
156
- console.log(chalk.gray(" • DUCT_API_KEY (Duct hosted)"));
157
- console.log(chalk.gray(" Set LLM_MODEL to the model name you want to use.\n"));
158
- if (yes) {
159
- // In --yes mode, auto-proceed with blank template
160
- console.log(chalk.gray(" Proceeding in blank-template mode (-y flag)\n"));
161
- return false;
162
- }
163
- const { continueAnyway } = await inquirer.prompt([
164
- {
165
- type: "confirm",
166
- name: "continueAnyway",
167
- message: "Continue with blank template (no AI analysis)?",
168
- default: true,
169
- },
170
- ]);
171
- if (!continueAnyway) {
172
- console.log(chalk.cyan("\n Set an LLM provider key and re-run: npx duct init\n"));
173
- process.exit(0);
174
- }
175
- return false; // User confirmed they want blank template
176
- }
177
- function displayIssues(issues) {
178
- const errors = issues.filter((i) => i.severity === "error");
179
- const warnings = issues.filter((i) => i.severity === "warning");
180
- if (errors.length > 0) {
181
- for (const issue of errors) {
182
- console.log(chalk.red(`\n ✗ ${issue.message}`));
183
- if (issue.suggestion) {
184
- console.log(chalk.gray(` ${issue.suggestion}`));
185
- }
186
- }
187
- }
188
- if (warnings.length > 0) {
189
- for (const issue of warnings) {
190
- console.log(chalk.yellow(`\n ⚠ ${issue.message}`));
191
- if (issue.suggestion) {
192
- console.log(chalk.gray(` ${issue.suggestion}`));
193
- }
194
- }
195
- }
196
- }
197
- /**
198
- * Try to auto-detect the product logo from common favicon locations in `public/`.
199
- * Returns a relative path string if found, or undefined.
200
- */
201
- async function detectLogoUrl(projectRoot) {
202
- const candidates = [
203
- "public/logo.svg",
204
- "public/logo.png",
205
- "public/icon.svg",
206
- "public/icon.png",
207
- "public/favicon.svg",
208
- "public/apple-touch-icon.png",
209
- "public/favicon-32x32.png",
210
- "public/favicon-16x16.png",
211
- "public/favicon.png",
212
- ];
213
- for (const rel of candidates) {
214
- try {
215
- await fs.access(path.join(projectRoot, rel));
216
- // Return the public-relative URL (served at /logo.svg etc.)
217
- return `/${rel.replace(/^public\//, "")}`;
218
- }
219
- catch {
220
- // not found — try next
221
- }
222
- }
223
- return undefined;
224
- }
225
- /**
226
- * Auto-detect the product industry from package.json dependencies.
227
- * Returns a best-guess string or undefined when nothing matches.
228
- */
229
- function detectIndustryFromDeps(deps) {
230
- const allDeps = Object.keys(deps).join(" ").toLowerCase();
231
- if (/stripe|braintree|adyen|plaid|square|paypal|razorpay|lemon/.test(allDeps))
232
- return "fintech";
233
- if (/shopify|woocommerce|medusa|saleor|commercetools|stripe.*checkout/.test(allDeps))
234
- return "ecommerce";
235
- if (/contentful|sanity|prismic|strapi|payload/.test(allDeps))
236
- return "cms";
237
- if (/sendgrid|postmark|mailchimp|resend|nodemailer/.test(allDeps))
238
- return "email-saas";
239
- if (/twilio|vonage|messagebird|telnyx/.test(allDeps))
240
- return "communications";
241
- if (/aws-sdk|@aws-sdk|firebase|supabase/.test(allDeps))
242
- return "saas";
243
- if (/openai|anthropic|langchain|huggingface/.test(allDeps))
244
- return "ai";
245
- if (/segment|mixpanel|amplitude|posthog/.test(allDeps))
246
- return "analytics";
247
- return undefined;
248
- }
249
- function resolveProductLogoUrl(baseUrl, logoUrl) {
250
- if (!logoUrl?.trim())
251
- return undefined;
252
- const trimmed = logoUrl.trim();
253
- if (/^https?:\/\//i.test(trimmed))
254
- return trimmed;
255
- const base = baseUrl.replace(/\/$/, '');
256
- const path = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
257
- return `${base}${path}`;
258
- }
259
- function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logoUrl, apiBaseUrl, industry, dataModel) {
260
- return normalizeDuctConfigForCodegen({
261
- shellId,
262
- product: {
263
- name: productName,
264
- description: `${productName} — AI-powered interaction shell`,
265
- baseUrl,
266
- ...(apiBaseUrl ? { apiBaseUrl } : {}),
267
- ...(industry ? { industry } : {}),
268
- ...(logoUrl ? { logoUrl: resolveProductLogoUrl(baseUrl, logoUrl) } : {}),
269
- },
270
- auth: result.auth,
271
- routes: result.routes,
272
- actions: result.actions,
273
- deeplinks: result.deeplinks,
274
- agentPermissions: {
275
- defaultLevel: "none",
276
- requireUserConsent: true,
277
- },
278
- widget: {
279
- position: "bottom-right",
280
- },
281
- ...(result.intershell_enabled !== undefined ||
282
- result.registry_visibility !== undefined
283
- ? {
284
- intershell_enabled: result.intershell_enabled ?? false,
285
- registry_visibility: result.registry_visibility ?? "private",
286
- }
287
- : {}),
288
- ...(dataModel && dataModel.entities.length > 0 ? { dataModel } : {}),
289
- });
290
- }
291
- function displayConfigValidationIssues(issues) {
292
- console.log(chalk.red("\n Manifest validation failed:\n"));
293
- for (const issue of issues) {
294
- const severityLabel = issue.severity === "error"
295
- ? chalk.red(`[${issue.severity}]`)
296
- : chalk.yellow(`[${issue.severity}]`);
297
- console.log(` ${severityLabel} ${chalk.bold(issue.area)} — ${issue.issue}`);
298
- console.log(chalk.gray(` Fix: ${issue.fix}`));
299
- }
300
- console.log("");
301
- }
302
- async function writeFile(filePath, content, dryRun) {
303
- if (dryRun) {
304
- console.log(chalk.cyan(`\n[dry-run] Would write: ${filePath}`));
305
- console.log(chalk.gray("─".repeat(60)));
306
- console.log(content.slice(0, 500) + (content.length > 500 ? "\n..." : ""));
307
- return;
308
- }
309
- await fs.mkdir(path.dirname(filePath), { recursive: true });
310
- await fs.writeFile(filePath, content, "utf-8");
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
- }
349
- async function fileExists(filePath) {
350
- try {
351
- await fs.access(filePath);
352
- return true;
353
- }
354
- catch {
355
- return false;
356
- }
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
- }
365
- /**
366
- * Returns relative paths of files changed in git since HEAD.
367
- * Combines unstaged changes, staged changes, and untracked files.
368
- * Returns null if the directory is not a git repo or git is unavailable.
369
- */
370
- async function getGitChangedFiles(cwd) {
371
- return new Promise((resolve) => {
372
- exec("git diff --name-only HEAD && git ls-files --others --exclude-standard", { cwd, timeout: 10_000 }, (err, stdout) => {
373
- if (err) {
374
- resolve(null);
375
- return;
376
- }
377
- const files = stdout
378
- .split("\n")
379
- .map((f) => f.trim())
380
- .filter(Boolean);
381
- resolve(files.length > 0 ? files : null);
382
- });
383
- });
384
- }
385
- function isIgnoredScanDir(name) {
386
- return [
387
- ".git",
388
- "node_modules",
389
- ".next",
390
- "dist",
391
- "build",
392
- "out",
393
- "coverage",
394
- ".turbo",
395
- ".vercel",
396
- ".cache",
397
- "tmp",
398
- "temp",
399
- ].includes(name);
400
- }
401
- function frameworkPriority(name) {
402
- const map = {
403
- "next-app": 100,
404
- "next-pages": 95,
405
- remix: 90,
406
- "vite-react": 85,
407
- sveltekit: 80,
408
- nuxt: 78,
409
- vue3: 75,
410
- express: 60,
411
- fastapi: 55,
412
- unknown: 0,
413
- };
414
- return map[name];
415
- }
416
- function rankCandidateRoot(candidateRoot, framework, depth) {
417
- let score = frameworkPriority(framework.name);
418
- // Prefer conventional frontend folder names when framework confidence is similar.
419
- const normalized = candidateRoot.replace(/\\/g, "/").toLowerCase();
420
- if (/(^|\/)((apps|app|web|frontend|client|site))(\/|$)/.test(normalized)) {
421
- score += 6;
422
- }
423
- if (framework.hasAppRouter)
424
- score += 3;
425
- if (framework.hasPagesRouter)
426
- score += 1;
427
- // Keep closer folders slightly preferred over deep nested paths.
428
- score -= depth;
429
- return score;
430
- }
431
- async function discoverFrameworkRoot(startDir, maxDepth = 3) {
432
- const rootFramework = await detectFramework(startDir);
433
- let best = {
434
- framework: rootFramework,
435
- projectRoot: startDir,
436
- score: rankCandidateRoot(startDir, rootFramework, 0),
437
- };
438
- async function scanDirectory(dirPath, depth) {
439
- if (depth > maxDepth) {
440
- return;
441
- }
442
- let entries = [];
443
- try {
444
- entries = await fs.readdir(dirPath, { withFileTypes: true });
445
- }
446
- catch {
447
- return;
448
- }
449
- const hasPackageJson = entries.some((entry) => entry.isFile() && entry.name === "package.json");
450
- if (hasPackageJson && dirPath !== startDir) {
451
- const framework = await detectFramework(dirPath);
452
- if (framework.name !== "unknown") {
453
- const score = rankCandidateRoot(dirPath, framework, depth);
454
- if (score > best.score) {
455
- best = { framework, projectRoot: dirPath, score };
456
- }
457
- }
458
- }
459
- if (depth === maxDepth) {
460
- return;
461
- }
462
- const childDirs = entries
463
- .filter((entry) => entry.isDirectory() && !isIgnoredScanDir(entry.name))
464
- .map((entry) => path.join(dirPath, entry.name));
465
- await Promise.all(childDirs.map((childDir) => scanDirectory(childDir, depth + 1)));
466
- }
467
- await scanDirectory(startDir, 0);
468
- return {
469
- framework: best.framework,
470
- projectRoot: best.projectRoot,
471
- };
472
- }
473
- // ----------------------------------------------------------------
474
- // pushManifest
475
- // ----------------------------------------------------------------
476
- async function pushManifest(config, apiKey, authProfile) {
477
- const manifestBases = getManifestApiBases(authProfile);
478
- const attemptedBases = [];
479
- let lastError = "";
480
- for (const base of manifestBases) {
481
- attemptedBases.push(base);
482
- const response = await fetch(`${base}/v1/shells/${config.shellId}/manifest`, {
483
- method: "PUT",
484
- headers: {
485
- "Content-Type": "application/json",
486
- Authorization: `Bearer ${apiKey}`,
487
- },
488
- body: JSON.stringify({ config }),
489
- });
490
- if (response.ok) {
491
- return;
492
- }
493
- const body = await response.text();
494
- lastError = `Duct API error (${response.status}) at ${base}: ${body}`;
495
- // Keep probing in case this host doesn't expose manifest endpoints.
496
- if (response.status === 404) {
497
- continue;
498
- }
499
- throw new Error(`${lastError}\nTried: ${attemptedBases.join(", ")}`);
500
- }
501
- throw new Error(`${lastError || "No manifest API endpoint responded"}\nTried: ${attemptedBases.join(", ")}`);
502
- }
503
- // ----------------------------------------------------------------
504
- // Monorepo detection helpers
505
- // ----------------------------------------------------------------
506
- /** Frontend subdirectory candidates to probe for a monorepo structure. */
507
- const FRONTEND_CANDIDATES = ["frontend", "web", "client"];
508
- /** Backend subdirectory candidates to probe for a monorepo structure. */
509
- const BACKEND_CANDIDATES = ["backend", "server", "api"];
510
- /**
511
- * Detect whether the project looks like a monorepo with separate frontend/backend dirs.
512
- * Returns the matched pair, or null if it's not a monorepo.
513
- */
514
- async function detectMonorepoRoots(cwd) {
515
- let detectedFrontend = null;
516
- let detectedBackend = null;
517
- // Check for a frontend directory that has a package.json
518
- for (const dir of FRONTEND_CANDIDATES) {
519
- const dirPath = path.join(cwd, dir);
520
- const pkgPath = path.join(dirPath, "package.json");
521
- try {
522
- await fs.access(pkgPath);
523
- detectedFrontend = dir;
524
- break;
525
- }
526
- catch {
527
- // not found, try next
528
- }
529
- }
530
- if (!detectedFrontend)
531
- return null;
532
- // Check for a backend directory
533
- for (const dir of BACKEND_CANDIDATES) {
534
- const dirPath = path.join(cwd, dir);
535
- try {
536
- await fs.access(dirPath);
537
- detectedBackend = dir;
538
- break;
539
- }
540
- catch {
541
- // not found, try next
542
- }
543
- }
544
- if (!detectedBackend)
545
- return null;
546
- return { frontendRoot: detectedFrontend, backendRoot: detectedBackend };
547
- }
548
- /**
549
- * Prompt the user to confirm detected monorepo roots using readline (non-inquirer).
550
- * Returns the confirmed roots, or null if the user declined.
551
- */
552
- async function promptMonorepoRoots(frontendRoot, backendRoot) {
553
- return new Promise((resolve) => {
554
- const rl = readline.createInterface({
555
- input: process.stdin,
556
- output: process.stdout,
557
- });
558
- console.log(chalk.bold("\n Detected monorepo structure."));
559
- console.log(chalk.gray(` Frontend: ${frontendRoot}/`));
560
- console.log(chalk.gray(` Backend: ${backendRoot}/\n`));
561
- rl.question(" Continue with these roots? (Y/n): ", (answer) => {
562
- rl.close();
563
- const trimmed = answer.trim().toLowerCase();
564
- if (trimmed === "" || trimmed === "y" || trimmed === "yes") {
565
- resolve({ frontendRoot, backendRoot });
566
- }
567
- else {
568
- resolve(null);
569
- }
570
- });
571
- });
572
- }
573
- // ----------------------------------------------------------------
574
- // runInit
575
- // ----------------------------------------------------------------
576
- /**
577
- * Run the Duct init command.
578
- * This is the main entry point for `npx duct init`.
579
- */
580
- export async function runInit(opts = {}) {
581
- const { cwd = process.cwd(), dryRun = false, yes = false, noInteractive = false, } = opts;
582
- // noAgents is mutable: manual mode implies no agents, and LLM credential check can
583
- // downgrade to no-agents when credentials are missing and user confirms blank template.
584
- let noAgents = (opts.noAgents ?? false) || (opts.manual ?? false);
585
- console.log(chalk.bold(`\n ◆ Duct · v${VERSION}`));
586
- console.log(chalk.gray(" Shell infrastructure for humans and agents."));
587
- console.log(chalk.gray(" ─────────────────────────────────────────────────────────────\n"));
588
- // ---- Pre-flight: Block execution from build/output directories ----
589
- const blockedDirs = ["node_modules", "dist", ".next", "build", "out", ".turbo", "coverage"];
590
- for (const blocked of blockedDirs) {
591
- if (cwd.includes(`/${blocked}/`) ||
592
- cwd.includes(`\\${blocked}\\`) ||
593
- cwd.endsWith(`/${blocked}`) ||
594
- cwd.endsWith(`\\${blocked}`)) {
595
- console.error(`\n ❌ duct init cannot run inside ${blocked}/. Run from your project root.\n`);
596
- process.exit(1);
597
- }
598
- }
599
- // ---- Pre-flight: Detect monorepo structure ----
600
- if (!yes) {
601
- const monoRepoRoots = await detectMonorepoRoots(cwd);
602
- if (monoRepoRoots) {
603
- const confirmed = await promptMonorepoRoots(monoRepoRoots.frontendRoot, monoRepoRoots.backendRoot);
604
- if (confirmed) {
605
- // Persist the confirmed roots to duct.workspace.json at the project root
606
- const workspace = {
607
- frontendRoot: confirmed.frontendRoot,
608
- backendRoot: confirmed.backendRoot,
609
- detectedAt: new Date().toISOString(),
610
- };
611
- const workspacePath = path.join(cwd, "duct.workspace.json");
612
- if (!dryRun) {
613
- await fs.writeFile(workspacePath, JSON.stringify(workspace, null, 2) + "\n", "utf-8");
614
- console.log(chalk.gray(` Saved monorepo config to duct.workspace.json\n`));
615
- }
616
- else {
617
- console.log(chalk.cyan(`\n[dry-run] Would write: ${workspacePath}`));
618
- }
619
- }
620
- else {
621
- console.log(chalk.gray(" Continuing without monorepo configuration.\n"));
622
- }
623
- }
624
- }
625
- // ---- Step 0: Verify authentication ----
626
- const auth = await loadAuth();
627
- // Resolve dashboard URL from env / saved auth (never hardcoded)
628
- const dashboardBase = getConfiguredDashboard(auth);
629
- if (!auth) {
630
- console.log(chalk.red(" Not logged in.\n"));
631
- console.log(" Run " +
632
- chalk.cyan("npx duct login") +
633
- " first, or register at " +
634
- chalk.cyan(`${dashboardBase}/register`) +
635
- "\n");
636
- process.exit(1);
637
- }
638
- console.log(chalk.gray(` Authenticated as ${auth.email} (${auth.slug})\n`));
639
- // Use saved auth endpoints (or production defaults).
640
- // Account/identity endpoints use the auth base URL.
641
- const ductAuthBase = getActiveAuthBase(auth);
642
- // Fetch company's provisioned shells from the auth service.
643
- let accountShells;
644
- try {
645
- accountShells = await fetchAccountShells(auth.token, ductAuthBase);
646
- }
647
- catch (err) {
648
- const message = err instanceof Error ? err.message : String(err);
649
- console.log(chalk.red(` Failed to list shells: ${message}\n`));
650
- process.exit(1);
651
- }
652
- // ---- Step 0.5: Check LLM credentials and prompt if missing ----
653
- // Skip the LLM check when --api-spec is provided: the deterministic parser
654
- // does not require any LLM key, so the pipeline can run without credentials.
655
- const hasApiSpec = Boolean(opts.apiSpec);
656
- const hasCurlCollection = Boolean(opts.curlCollection);
657
- if (!noAgents && !hasApiSpec && !hasCurlCollection) {
658
- const canRunAgents = await checkLlmCredentialsAndPrompt(noAgents, yes);
659
- if (!canRunAgents) {
660
- noAgents = true;
661
- }
662
- }
663
- // ---- Step 1: Detect framework ----
664
- const frameworkSpinner = ora("Detecting framework...").start();
665
- let framework;
666
- let projectRoot = cwd;
667
- if (opts.framework) {
668
- framework = frameworkFromName(opts.framework, cwd);
669
- frameworkSpinner.succeed(`Framework: ${frameworkDisplay(framework)} (forced)`);
670
- }
671
- else {
672
- const discovered = await discoverFrameworkRoot(cwd);
673
- framework = discovered.framework;
674
- projectRoot = discovered.projectRoot;
675
- if (framework.name === "unknown") {
676
- frameworkSpinner.warn("Framework not detected automatically");
677
- }
678
- else {
679
- frameworkSpinner.succeed(`Framework detected: ${frameworkDisplay(framework)}`);
680
- }
681
- if (projectRoot !== cwd) {
682
- console.log(chalk.gray(` Project root: ${path.relative(cwd, projectRoot)}`));
683
- }
684
- if (!yes) {
685
- const relativeRoot = path.relative(cwd, projectRoot) || ".";
686
- const detectedLabel = frameworkDisplay(framework);
687
- const { isDetectedFrameworkCorrect } = await inquirer.prompt([
688
- {
689
- type: "confirm",
690
- name: "isDetectedFrameworkCorrect",
691
- message: `Detected ${detectedLabel} at ${relativeRoot}. Is this correct?`,
692
- default: framework.name !== "unknown",
693
- },
694
- ]);
695
- if (!isDetectedFrameworkCorrect) {
696
- const { selectedFramework } = await inquirer.prompt([
697
- {
698
- type: "list",
699
- name: "selectedFramework",
700
- message: "Select your framework stack:",
701
- choices: [
702
- { name: "Next.js (App Router)", value: "next-app" },
703
- { name: "Next.js (Pages Router)", value: "next-pages" },
704
- { name: "Vite + React", value: "vite-react" },
705
- { name: "Remix", value: "remix" },
706
- { name: "SvelteKit", value: "sveltekit" },
707
- ],
708
- },
709
- ]);
710
- framework = frameworkFromName(selectedFramework, projectRoot);
711
- console.log(chalk.gray(` Using manual framework: ${frameworkDisplay(framework)}`));
712
- }
713
- }
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);
740
- }
741
- // ---- Step 2: Project structure + auth detection ----
742
- const sandboxFs = new SandboxFS(projectRoot);
743
- const topoSpinner = ora("Scanning project structure...").start();
744
- const topo = await discoverTopology(projectRoot);
745
- topoSpinner.succeed(`Detected: ${topo.language}${topo.isMonorepo ? " · monorepo" : ""}`);
746
- const authSpinner = ora("Detecting auth system...").start();
747
- const authDetection = await detectAuth(sandboxFs);
748
- authSpinner.succeed(`Auth detected: ${authDisplay(authDetection.system)}`);
749
- let thirdPartyAgentMode = "none";
750
- if (!yes && !opts.manual) {
751
- const { partnerAgents } = await inquirer.prompt([
752
- {
753
- type: "list",
754
- name: "partnerAgents",
755
- message: "Will third-party AI agents act on behalf of your users?",
756
- choices: [
757
- { name: "No — human shell only (default)", value: "none" },
758
- { name: "Yes — Duct consent tokens (uct_)", value: "duct-consent" },
759
- { name: "Yes — we use company OAuth delegation", value: "oauth" },
760
- ],
761
- default: "none",
762
- },
763
- ]);
764
- thirdPartyAgentMode = partnerAgents;
765
- }
766
- // ---- Step 3: Gather basic info ----
767
- let shellId;
768
- let productName;
769
- let baseUrl;
770
- let apiBaseUrl = opts.apiUrl;
771
- let industry = opts.industry;
772
- // ---- Update mode: restrict readList to files changed since last push ----
773
- // Uses `git diff --name-only HEAD` to find changed files, then filters the
774
- // full selector output to only those files. The pipeline then only sees
775
- // what changed — dramatically faster for large codebases.
776
- if (opts.update) {
777
- const existingConfigPath = path.join(projectRoot, "duct.config.ts");
778
- if (await fileExists(existingConfigPath)) {
779
- console.log(chalk.gray(" Updating existing duct.config.ts — scanning changed files...\n"));
780
- }
781
- }
782
- const pkg = await sandboxFs.readJSON("package.json");
783
- const defaultProductName = pkg?.name?.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) ??
784
- "My App";
785
- // Auto-detect industry from package.json deps if not provided
786
- if (!industry && pkg) {
787
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
788
- industry = detectIndustryFromDeps(allDeps);
789
- }
790
- // ---- Resolve shell ID from Duct account (never user-typed) ----
791
- if (!auth) {
792
- console.log(chalk.red(" Not logged in.\n"));
793
- console.log(" Run " +
794
- chalk.cyan("npx duct login") +
795
- " first, or register at " +
796
- chalk.cyan(`${dashboardBase}/register`) +
797
- "\n");
798
- process.exit(1);
799
- }
800
- if (accountShells.length === 0) {
801
- console.log(chalk.yellow(" No shells provisioned for your account.\n"));
802
- console.log(" Go to " +
803
- chalk.cyan(`${dashboardBase}/shells/new`) +
804
- " to provision a shell first, then re-run `npx duct init`.\n");
805
- process.exit(1);
806
- }
807
- let selectedShell;
808
- if (accountShells.length === 1 || yes) {
809
- selectedShell = accountShells[0];
810
- console.log(chalk.gray(` Using shell: ${chalk.bold(selectedShell.id)}\n`));
811
- }
812
- else {
813
- const { chosenShellId } = await inquirer.prompt([
814
- {
815
- type: "list",
816
- name: "chosenShellId",
817
- message: "Which shell are you initialising?",
818
- choices: accountShells.map((s) => ({
819
- name: `${s.id} ${chalk.gray(`(${s.environment} — ${s.registered_domain})`)}`,
820
- value: s.id,
821
- })),
822
- },
823
- ]);
824
- selectedShell = accountShells.find((s) => s.id === chosenShellId);
825
- }
826
- shellId = selectedShell.id;
827
- // Product name and base URL
828
- if (yes) {
829
- productName = defaultProductName;
830
- baseUrl = pkg?.homepage ?? selectedShell.registered_domain;
831
- }
832
- else {
833
- const answers = await inquirer.prompt([
834
- {
835
- type: "input",
836
- name: "productName",
837
- message: "Product name:",
838
- default: defaultProductName,
839
- },
840
- {
841
- type: "input",
842
- name: "baseUrl",
843
- message: "Product base URL:",
844
- default: pkg?.homepage ?? selectedShell.registered_domain,
845
- validate: (v) => {
846
- try {
847
- new URL(v);
848
- return true;
849
- }
850
- catch {
851
- return "Must be a valid URL (e.g., https://app.example.com)";
852
- }
853
- },
854
- },
855
- ]);
856
- productName = answers.productName;
857
- baseUrl = answers.baseUrl;
858
- // --api-url prompt: ask if the API is on a different domain (skip if --api-url already set)
859
- if (!apiBaseUrl) {
860
- const { hasSeparateApi } = await inquirer.prompt([
861
- {
862
- type: "confirm",
863
- name: "hasSeparateApi",
864
- message: "Is your API hosted on a different domain from the frontend?",
865
- default: false,
866
- },
867
- ]);
868
- if (hasSeparateApi) {
869
- const { enteredApiUrl } = await inquirer.prompt([
870
- {
871
- type: "input",
872
- name: "enteredApiUrl",
873
- message: "API base URL (e.g., https://api.example.com):",
874
- validate: (v) => {
875
- try {
876
- new URL(v);
877
- return true;
878
- }
879
- catch {
880
- return "Must be a valid URL";
881
- }
882
- },
883
- },
884
- ]);
885
- apiBaseUrl = enteredApiUrl;
886
- }
887
- }
888
- }
889
- // ---- Step 3.5: Auto-detect dataModel from Prisma schema (no LLM) ----
890
- let prismaDataModel;
891
- const prismaSchemaSource = await sandboxFs.readFile("prisma/schema.prisma");
892
- if (prismaSchemaSource) {
893
- const { models } = parsePrismaSchema(prismaSchemaSource);
894
- const entities = buildDataModelFromPrisma(models);
895
- if (entities.length > 0) {
896
- prismaDataModel = { entities };
897
- console.log(chalk.gray(` Prisma schema detected — auto-populated ${entities.length} dataModel entit${entities.length === 1 ? "y" : "ies"}\n`));
898
- }
899
- }
900
- // ---- Step 4: Run agent pipeline ----
901
- let pipelineResult;
902
- // Load --api-spec file content if provided
903
- let apiSpecContent;
904
- const apiSpecPath = opts.apiSpec ? path.resolve(cwd, opts.apiSpec) : undefined;
905
- if (apiSpecPath) {
906
- try {
907
- apiSpecContent = await fs.readFile(apiSpecPath, "utf-8");
908
- console.log(chalk.gray(` Using OpenAPI spec: ${path.relative(cwd, apiSpecPath)} — deterministic parse, no LLM needed\n`));
909
- }
910
- catch {
911
- console.log(chalk.yellow(` ⚠ Could not read --api-spec file: ${opts.apiSpec}. Falling back to agent scan.\n`));
912
- }
913
- }
914
- let curlCollectionContent;
915
- const curlCollectionPath = opts.curlCollection ? path.resolve(cwd, opts.curlCollection) : undefined;
916
- if (curlCollectionPath) {
917
- try {
918
- curlCollectionContent = await fs.readFile(curlCollectionPath, "utf-8");
919
- console.log(chalk.gray(` Using cURL collection: ${path.relative(cwd, curlCollectionPath)} — deterministic parse, no LLM needed\n`));
920
- }
921
- catch {
922
- console.log(chalk.yellow(` ⚠ Could not read --curl-collection file: ${opts.curlCollection}. Falling back to agent scan.\n`));
923
- }
924
- }
925
- // Build a bounded file list before running agents so each agent
926
- // receives targeted files as priority context instead of scanning broadly.
927
- let readList = !noAgents ? await buildReadList(topo, sandboxFs) : undefined;
928
- // In update mode, further restrict the readList to only files changed since HEAD.
929
- // This makes re-scans dramatically faster for large codebases.
930
- if (opts.update && readList) {
931
- const changedFiles = await getGitChangedFiles(projectRoot);
932
- if (changedFiles && changedFiles.length > 0) {
933
- const changedSet = new Set(changedFiles);
934
- const filter = (files) => files.filter((f) => changedSet.has(f) || changedSet.has(path.relative(projectRoot, f)));
935
- readList = {
936
- routeFiles: filter(readList.routeFiles),
937
- apiFiles: filter(readList.apiFiles),
938
- authFiles: filter(readList.authFiles),
939
- };
940
- const total = readList.routeFiles.length + readList.apiFiles.length + readList.authFiles.length;
941
- if (total === 0) {
942
- console.log(chalk.gray(" No changed files match your manifest file types — nothing to re-scan.\n"));
943
- }
944
- else {
945
- console.log(chalk.gray(` --update: scanning ${total} changed file(s) from git diff\n`));
946
- }
947
- }
948
- else {
949
- console.log(chalk.gray(" --update: no changed files detected (git diff is clean)\n"));
950
- }
951
- }
952
- if (noAgents) {
953
- const isManual = Boolean(opts.manual ?? false) || process.argv.includes("--manual");
954
- if (isManual) {
955
- console.log(chalk.yellow("\n Running in manual mode — no LLM agents"));
956
- console.log(chalk.gray(` Detected: ${topo.framework} · ${topo.language} · auth: ${topo.authLib}`));
957
- console.log(chalk.gray(" Generating pre-filled template. Review and run `duct push` when ready.\n"));
958
- }
959
- else {
960
- console.log(chalk.yellow("\n Skipping agent pipeline (--no-agents)"));
961
- console.log(chalk.gray(" You'll get a template with detected framework/auth pre-filled.\n"));
962
- }
963
- pipelineResult = {
964
- routes: [],
965
- actions: [],
966
- auth: {
967
- strategy: authDetection.system,
968
- sessionFields: authDetection.sessionFields,
969
- guestAllowed: authDetection.guestAllowed,
970
- tokenExpirySeconds: 300,
971
- tokenEndpoint: "/api/duct/token",
972
- },
973
- deeplinks: [],
974
- review: {
975
- passed: true,
976
- confidenceScore: 0,
977
- issues: [],
978
- suggestions: [
979
- "Add your routes manually to duct.config.ts",
980
- "Enable agentAccessible: true on safe read-only actions",
981
- ],
982
- summary: "Blank template — fill in manually",
983
- },
984
- confidenceScore: 0,
985
- durationMs: 0,
986
- };
987
- }
988
- else {
989
- console.log(chalk.bold(" Starting agent pipeline — read-only, sandboxed, 5 agents"));
990
- console.log(chalk.gray(" Your codebase will not be modified during this step.\n"));
991
- const emitter = new DuctPipelineEmitter();
992
- const formatAgentName = (name) => {
993
- if (!name)
994
- return "[ Unknown Agent ]";
995
- if (name === "RouteAgent")
996
- return "[ Route Agent ]";
997
- if (name === "ApiAgent")
998
- return "[ API Agent ]";
999
- if (name === "AuthAgent")
1000
- return "[ Auth Agent ]";
1001
- if (name === "DeeplinkAgent")
1002
- return "[ Deeplink Agent ]";
1003
- if (name === "ReviewerAgent")
1004
- return "[ Reviewer Agent ]";
1005
- return `[ ${name} ]`.padEnd(20);
1006
- };
1007
- emitter.on("event", (event) => {
1008
- const label = formatAgentName(event.agent);
1009
- if (event.type === "agent:start" && event.agent) {
1010
- process.stdout.write(chalk.gray(` ${label} ${event.message ?? "working..."}\n`));
1011
- }
1012
- if (event.type === "agent:complete" && event.agent) {
1013
- process.stdout.write(chalk.bold(` ${label}`) + chalk.green(` ✓ ${event.message ?? "done"}\n`));
1014
- }
1015
- if (event.type === "agent:error" && event.agent) {
1016
- process.stdout.write(chalk.yellow(` ${label} ⚠ ${event.error?.message ?? "failed"}\n`));
1017
- }
1018
- });
1019
- const pipelineSpinner = ora({ text: "Running pipeline...", prefixText: " " }).start();
1020
- try {
1021
- pipelineResult = await runAgentPipeline(sandboxFs, {
1022
- emitter,
1023
- readList,
1024
- ...(apiSpecContent ? { apiSpecContent, apiSpecPath: opts.apiSpec } : {}),
1025
- ...(curlCollectionContent ? { curlCollectionContent, curlCollectionPath: opts.curlCollection } : {}),
1026
- postProcess: { yesMode: yes },
1027
- });
1028
- pipelineSpinner.stop();
1029
- if (pipelineResult.actions.length === 0) {
1030
- const apiFileCount = readList?.apiFiles.length ?? 0;
1031
- console.log(chalk.yellow("\n ⚠ No API actions detected"));
1032
- console.log(chalk.gray(" The agents scanned your project but found no API endpoints."));
1033
- console.log(chalk.gray(" This often means your API files are in a non-standard location."));
1034
- console.log(chalk.gray("\n Suggestions:"));
1035
- console.log(chalk.gray(` • ${apiFileCount} API file(s) were scanned — check they contain handler functions`));
1036
- console.log(chalk.gray(" • Use --manual to fill in actions yourself (no AI needed)"));
1037
- console.log(chalk.gray(" • Ensure your route handlers are in app/api/, pages/api/, routes/, or controllers/"));
1038
- console.log(chalk.gray(" • Check that ANTHROPIC_API_KEY / LLM_MODEL are set correctly for better detection\n"));
1039
- }
1040
- }
1041
- catch (err) {
1042
- pipelineSpinner.fail("Pipeline failed");
1043
- const message = err instanceof Error ? err.message : String(err);
1044
- console.error(chalk.red(`\n Error: ${message}\n`));
1045
- process.exit(1);
1046
- }
1047
- }
1048
- // ---- Step 5: Show review results ----
1049
- const { review } = pipelineResult;
1050
- console.log(chalk.bold("\n Review Results:"));
1051
- console.log(` ${review.passed ? chalk.green("✓ Passed") : chalk.red("✗ Failed")}`);
1052
- console.log(chalk.gray(` ${review.summary}`));
1053
- if (review.issues.length > 0) {
1054
- displayIssues(review.issues);
1055
- }
1056
- if (review.suggestions.length > 0) {
1057
- console.log(chalk.blue("\n Suggestions:"));
1058
- for (const suggestion of review.suggestions) {
1059
- console.log(chalk.blue(` • ${suggestion}`));
1060
- }
1061
- }
1062
- // ---- Step 5.5: Per-action agent-accessibility review ----
1063
- // Run only when agents produced results (skip for blank template).
1064
- let reviewedPipelineResult = pipelineResult;
1065
- if (!noAgents && pipelineResult.actions.length > 0) {
1066
- const reviewed = await runInteractiveReview(pipelineResult, {
1067
- yes,
1068
- noInteractive,
1069
- cwd: projectRoot,
1070
- });
1071
- // Merge reviewed actions back into the pipeline result for file generation
1072
- reviewedPipelineResult = {
1073
- ...pipelineResult,
1074
- actions: reviewed.actions,
1075
- routes: reviewed.routes,
1076
- deeplinks: reviewed.deeplinks,
1077
- auth: reviewed.auth,
1078
- intershell_enabled: reviewed.intershell_enabled,
1079
- registry_visibility: reviewed.registry_visibility,
1080
- };
1081
- }
1082
- // Show what will be generated
1083
- const outputPaths = getGeneratedOutputPaths(projectRoot, framework);
1084
- const wiringPlan = buildWiringPlan(outputPaths, framework, authDetection, thirdPartyAgentMode);
1085
- printWiringPlan(projectRoot, wiringPlan);
1086
- console.log(chalk.bold("\n Writing files to your project\n"));
1087
- console.log(chalk.gray(` ${path.relative(cwd, outputPaths.configPath).padEnd(22)} manifest`));
1088
- console.log(chalk.gray(` ${path.relative(cwd, outputPaths.receiverPath).padEnd(22)} receiver route`));
1089
- console.log(chalk.gray(` ${path.relative(cwd, outputPaths.tokenRoutePath).padEnd(22)} token route`));
1090
- if (frameworkHasShellComponent(framework)) {
1091
- console.log(chalk.gray(` ${path.relative(cwd, outputPaths.shellComponentPath).padEnd(22)} widget component`));
1092
- }
1093
- console.log(chalk.gray(` ${path.relative(cwd, outputPaths.envTemplatePath).padEnd(22)} environment template\n`));
1094
- console.log(chalk.gray(" All files are yours to edit. Duct cloud reads duct.config.ts on deploy."));
1095
- // ---- Step 6: Prompt for approval ----
1096
- if (!yes && !dryRun) {
1097
- const { proceed } = await inquirer.prompt([
1098
- {
1099
- type: "confirm",
1100
- name: "proceed",
1101
- message: "Generate these files?",
1102
- default: review.passed,
1103
- },
1104
- ]);
1105
- if (!proceed) {
1106
- console.log(chalk.yellow("\n Aborted. No files written."));
1107
- return;
1108
- }
1109
- }
1110
- // ---- Step 6.5: Incremental merge for --update mode ----
1111
- // If a previous manifest snapshot exists, preserve unchanged items and
1112
- // only surface new/changed detections. This prevents a full overwrite of
1113
- // carefully-configured actions that were not in the changed-file set.
1114
- if (opts.update) {
1115
- const manifestSnapshotPath = path.join(projectRoot, ".duct-manifest.json");
1116
- let existingConfig = null;
1117
- try {
1118
- const raw = await fs.readFile(manifestSnapshotPath, "utf-8");
1119
- existingConfig = JSON.parse(raw);
1120
- }
1121
- catch { /* no snapshot yet — full write on first run */ }
1122
- if (existingConfig) {
1123
- // Build lookup keys for existing items
1124
- const existingActionKeys = new Map((existingConfig.actions ?? []).map((a) => [`${a.method}:${a.path}`, a]));
1125
- const existingRouteKeys = new Map((existingConfig.routes ?? []).map((r) => [r.path, r]));
1126
- const existingDeeplinkKeys = new Map((existingConfig.deeplinks ?? []).map((d) => [d.id, d]));
1127
- // Merge actions: new detections override by method+path; existing not in new detections are kept
1128
- const newActionKeys = new Set(reviewedPipelineResult.actions.map((a) => `${a.method}:${a.path}`));
1129
- const preservedActions = (existingConfig.actions ?? []).filter((a) => !newActionKeys.has(`${a.method}:${a.path}`));
1130
- // Count what changed for reporting
1131
- let newCount = 0;
1132
- let changedCount = 0;
1133
- for (const a of reviewedPipelineResult.actions) {
1134
- const key = `${a.method}:${a.path}`;
1135
- if (!existingActionKeys.has(key))
1136
- newCount++;
1137
- else
1138
- changedCount++;
1139
- }
1140
- const mergedActions = [...preservedActions, ...reviewedPipelineResult.actions];
1141
- // Merge routes: preserve routes not touched by scan; add/update scanned routes
1142
- const newRouteKeys = new Set(reviewedPipelineResult.routes.map((r) => r.path));
1143
- const preservedRoutes = (existingConfig.routes ?? []).filter((r) => !newRouteKeys.has(r.path));
1144
- const mergedRoutes = [...preservedRoutes, ...reviewedPipelineResult.routes];
1145
- // Merge deeplinks: preserve deeplinks not touched; add/update new ones
1146
- const newDeeplinkKeys = new Set(reviewedPipelineResult.deeplinks.map((d) => d.id));
1147
- const preservedDeeplinks = (existingConfig.deeplinks ?? []).filter((d) => !newDeeplinkKeys.has(d.id));
1148
- const mergedDeeplinks = [...preservedDeeplinks, ...reviewedPipelineResult.deeplinks];
1149
- // Preserve existing auth if pipeline didn't produce better detections
1150
- const mergedAuth = reviewedPipelineResult.auth.strategy !== "unknown"
1151
- ? reviewedPipelineResult.auth
1152
- : (existingConfig.auth ?? reviewedPipelineResult.auth);
1153
- reviewedPipelineResult = {
1154
- ...reviewedPipelineResult,
1155
- actions: mergedActions,
1156
- routes: mergedRoutes,
1157
- deeplinks: mergedDeeplinks,
1158
- auth: mergedAuth,
1159
- };
1160
- const totalDrift = newCount + changedCount;
1161
- if (totalDrift === 0) {
1162
- console.log(chalk.green("\n ✓ No drift detected — existing manifest is up to date.\n"));
1163
- return;
1164
- }
1165
- console.log(chalk.bold(`\n Merge results: ${newCount} new action(s), ${changedCount} updated, ${preservedActions.length} preserved\n`));
1166
- // Suppress unused variable warnings
1167
- void existingRouteKeys;
1168
- void existingDeeplinkKeys;
1169
- }
1170
- }
1171
- // ---- Step 7: Write files ----
1172
- const logoUrl = await detectLogoUrl(projectRoot);
1173
- const config = buildDuctConfigFromPipeline(reviewedPipelineResult, shellId, productName, baseUrl, logoUrl, apiBaseUrl, industry, prismaDataModel);
1174
- const validation = validateDuctConfigStrict(config);
1175
- if (!validation.ok) {
1176
- displayConfigValidationIssues(validation.issues);
1177
- console.log(chalk.red(" Aborted. The generated manifest failed validation — no files were written.\n" +
1178
- " Re-run init after fixing the detected issues, or use --manual for a template.\n"));
1179
- return;
1180
- }
1181
- const isManualMode = Boolean(opts.manual) || process.argv.includes("--manual");
1182
- const configContent = (noAgents && isManualMode)
1183
- ? generateManualTemplate({
1184
- shellId,
1185
- productName,
1186
- baseUrl,
1187
- authStrategy: authDetection.system,
1188
- framework: topo.framework,
1189
- logoUrl: logoUrl ? resolveProductLogoUrl(baseUrl, logoUrl) : undefined,
1190
- })
1191
- : generateConfigFile(config);
1192
- const receiverContent = generateReceiver(config, framework);
1193
- const tokenRouteContent = generateTokenRoute(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) : "";
1197
- const envContent = generateEnvTemplateForFramework(config, framework);
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);
1219
- if (wiringPlan.uctSnippet && wiringPlan.uctSnippetPath) {
1220
- await writeGeneratedFile(path.join(projectRoot, wiringPlan.uctSnippetPath), wiringPlan.uctSnippet, dryRun, writeMode);
1221
- }
1222
- // Safely append to the env template
1223
- const envExists = await fileExists(outputPaths.envTemplatePath);
1224
- if (envExists) {
1225
- const existingEnv = await fs.readFile(outputPaths.envTemplatePath, "utf-8");
1226
- if (!existingEnv.includes("DUCT_SHELL_ID")) {
1227
- if (dryRun) {
1228
- console.log(chalk.cyan(`\n[dry-run] Would append to: ${outputPaths.envTemplatePath}`));
1229
- }
1230
- else {
1231
- await fs.appendFile(outputPaths.envTemplatePath, "\n" + envContent, "utf-8");
1232
- }
1233
- }
1234
- }
1235
- else {
1236
- await writeFile(outputPaths.envTemplatePath, envContent, dryRun);
1237
- }
1238
- if (!dryRun) {
1239
- // ---- Write manifest snapshot for future --update runs ----
1240
- const manifestSnapshotPath = path.join(projectRoot, ".duct-manifest.json");
1241
- try {
1242
- await fs.writeFile(manifestSnapshotPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
1243
- }
1244
- catch { /* non-fatal */ }
1245
- // ---- Post-write validation: env var completeness ----
1246
- const isNextJs = framework.name === "next-app" || framework.name === "next-pages";
1247
- if (isNextJs) {
1248
- try {
1249
- const envContent2 = await fs.readFile(outputPaths.envTemplatePath, "utf-8");
1250
- if (!envContent2.includes("NEXT_PUBLIC_DUCT_SHELL_ID")) {
1251
- await fs.appendFile(outputPaths.envTemplatePath, "\n# Client-side shell ID (required for DuctShell component)\nNEXT_PUBLIC_DUCT_SHELL_ID=${DUCT_SHELL_ID}\n", "utf-8");
1252
- console.log(chalk.gray(" Added NEXT_PUBLIC_DUCT_SHELL_ID to env template.\n"));
1253
- }
1254
- }
1255
- catch { /* non-fatal */ }
1256
- }
1257
- // ---- Post-write validation: token endpoint path ----
1258
- const expectedTokenPath = "/api/duct/token";
1259
- const configuredTokenPath = config.auth.tokenEndpoint;
1260
- if (configuredTokenPath &&
1261
- !configuredTokenPath.endsWith(expectedTokenPath) &&
1262
- !configuredTokenPath.includes(`${expectedTokenPath}`)) {
1263
- console.log(chalk.yellow(` ⚠ Token endpoint mismatch: config says '${configuredTokenPath}' but generated route is at '${expectedTokenPath}'`));
1264
- console.log(chalk.gray(" Update auth.tokenEndpoint in duct.config.ts if this is intentional.\n"));
1265
- }
1266
- console.log(chalk.green("\n ✓ Files written successfully!\n"));
1267
- const auditIssues = await runIntegrationAudit(sandboxFs, {
1268
- projectRoot,
1269
- config,
1270
- framework,
1271
- outputPaths,
1272
- authDetection,
1273
- thirdPartyAgentMode,
1274
- });
1275
- printIntegrationAuditIssues(auditIssues);
1276
- if (integrationAuditFailed(auditIssues)) {
1277
- console.log(chalk.yellow(" ⚠ Integration audit found blocking issues — fix the items above before `duct push`.\n"));
1278
- }
1279
- if (sideEffectActionsApproved(config)) {
1280
- console.log(chalk.bold(" Webhooks (recommended):"));
1281
- console.log(chalk.gray(" Side-effect actions detected — configure confirmation webhooks in Dashboard → Shell → Settings → Webhooks.\n"));
1282
- }
1283
- // ---- Post-write validation: receiver route health check ----
1284
- if (baseUrl) {
1285
- const receiverUrl = `${baseUrl.replace(/\/$/, "")}/api/duct/receive`;
1286
- try {
1287
- const controller = new AbortController();
1288
- const timer = setTimeout(() => controller.abort(), 3000);
1289
- const res = await fetch(receiverUrl, { method: "HEAD", signal: controller.signal });
1290
- clearTimeout(timer);
1291
- if (res.ok || res.status === 405) {
1292
- console.log(chalk.green(` ✓ Receiver reachable at /api/duct/receive`));
1293
- }
1294
- else {
1295
- console.log(chalk.gray(` ⚠ Receiver returned ${res.status} at ${receiverUrl} — ensure dev server is running before duct push`));
1296
- }
1297
- }
1298
- catch {
1299
- console.log(chalk.gray(` ⚠ Could not reach receiver at ${receiverUrl} — start your dev server before running duct push`));
1300
- }
1301
- }
1302
- const apiKey = process.env["DUCT_API_KEY"];
1303
- if (apiKey) {
1304
- try {
1305
- await pushManifest(config, apiKey, auth);
1306
- }
1307
- catch (err) {
1308
- const message = err instanceof Error ? err.message : String(err);
1309
- console.log(chalk.yellow(`\n ⚠ Could not push to Duct cloud: ${message}`));
1310
- console.log(chalk.gray(" Run `npx duct push` manually when ready."));
1311
- }
1312
- }
1313
- else {
1314
- console.log(chalk.yellow("\n ⚠ Set DUCT_API_KEY to auto-push, or run `npx duct push` manually."));
1315
- }
1316
- const dashboard = getConfiguredDashboard(auth);
1317
- const docsBase = getDocsUrl();
1318
- console.log(chalk.bold(`\n ◆ Shell is live\n`));
1319
- console.log(` Shell ID ${chalk.cyan(shellId)}`);
1320
- console.log(` Manifest synced · ${config.routes?.length ?? 0} routes · ${config.actions?.length ?? 0} actions · ${config.deeplinks?.length ?? 0} deeplinks`);
1321
- console.log(` Status registered with Duct cloud\n`);
1322
- console.log(` Next:`);
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`);
1332
- console.log(` Docs ${docsBase}/quickstart`);
1333
- console.log(` Support ${dashboard}/discord`);
1334
- console.log(chalk.gray(` ─────────────────────────────────────────────────────────────\n`));
1335
- }
1336
- }