@duct-sdk/sdk 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +92 -0
- package/dist/adapters/next/index.d.ts +4 -0
- package/dist/adapters/next/index.js +5 -0
- package/dist/adapters/next/receiver.d.ts +44 -0
- package/dist/adapters/next/receiver.js +162 -0
- package/dist/adapters/next/shell.d.ts +88 -0
- package/dist/adapters/next/shell.js +255 -0
- package/dist/adapters/react/index.d.ts +2 -0
- package/dist/adapters/react/index.js +4 -0
- package/dist/adapters/react/shell.d.ts +88 -0
- package/dist/adapters/react/shell.js +255 -0
- package/dist/adapters/remix/index.d.ts +2 -0
- package/dist/adapters/remix/index.js +4 -0
- package/dist/adapters/remix/receiver.d.ts +44 -0
- package/dist/adapters/remix/receiver.js +153 -0
- package/dist/adapters/sveltekit/index.d.ts +2 -0
- package/dist/adapters/sveltekit/index.js +4 -0
- package/dist/adapters/sveltekit/receiver.d.ts +56 -0
- package/dist/adapters/sveltekit/receiver.js +154 -0
- package/dist/adapters/vite/index.d.ts +2 -0
- package/dist/adapters/vite/index.js +4 -0
- package/dist/adapters/vite/receiver.d.ts +82 -0
- package/dist/adapters/vite/receiver.js +164 -0
- package/dist/assets/logo.d.ts +1 -0
- package/dist/assets/logo.js +1 -0
- package/dist/cli/agents/api-agent.d.ts +14 -0
- package/dist/cli/agents/api-agent.js +656 -0
- package/dist/cli/agents/auth-agent.d.ts +6 -0
- package/dist/cli/agents/auth-agent.js +198 -0
- package/dist/cli/agents/deeplink-agent.d.ts +6 -0
- package/dist/cli/agents/deeplink-agent.js +263 -0
- package/dist/cli/agents/llm.d.ts +33 -0
- package/dist/cli/agents/llm.js +276 -0
- package/dist/cli/agents/pipeline.d.ts +51 -0
- package/dist/cli/agents/pipeline.js +236 -0
- package/dist/cli/agents/reviewer-agent.d.ts +11 -0
- package/dist/cli/agents/reviewer-agent.js +442 -0
- package/dist/cli/agents/route-agent.d.ts +13 -0
- package/dist/cli/agents/route-agent.js +346 -0
- package/dist/cli/detectors/auth.d.ts +18 -0
- package/dist/cli/detectors/auth.js +273 -0
- package/dist/cli/detectors/framework.d.ts +22 -0
- package/dist/cli/detectors/framework.js +242 -0
- package/dist/cli/drift.d.ts +39 -0
- package/dist/cli/drift.js +247 -0
- package/dist/cli/fs/sandbox.d.ts +77 -0
- package/dist/cli/fs/sandbox.js +295 -0
- package/dist/cli/generators/config.d.ts +7 -0
- package/dist/cli/generators/config.js +255 -0
- package/dist/cli/generators/receiver.d.ts +12 -0
- package/dist/cli/generators/receiver.js +683 -0
- package/dist/cli/generators/shell.d.ts +18 -0
- package/dist/cli/generators/shell.js +672 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +603 -0
- package/dist/cli/init.d.ts +26 -0
- package/dist/cli/init.js +835 -0
- package/dist/core/action.d.ts +37 -0
- package/dist/core/action.js +140 -0
- package/dist/core/config.d.ts +514 -0
- package/dist/core/config.js +221 -0
- package/dist/core/endpoints.d.ts +17 -0
- package/dist/core/endpoints.js +128 -0
- package/dist/core/token.d.ts +70 -0
- package/dist/core/token.js +174 -0
- package/dist/core/types.d.ts +450 -0
- package/dist/core/types.js +11 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +9 -0
- package/package.json +84 -0
package/dist/cli/init.js
ADDED
|
@@ -0,0 +1,835 @@
|
|
|
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 { SandboxFS } from "./fs/sandbox.js";
|
|
13
|
+
import { detectFramework } from "./detectors/framework.js";
|
|
14
|
+
import { detectAuth } from "./detectors/auth.js";
|
|
15
|
+
import { runAgentPipeline, DuctPipelineEmitter, } from "./agents/pipeline.js";
|
|
16
|
+
import { generateConfigFile } from "./generators/config.js";
|
|
17
|
+
import { generateReceiver, generateTokenRoute, } from "./generators/receiver.js";
|
|
18
|
+
import { generateShell, generateEnvTemplateForFramework, getEnvTemplateName, } from "./generators/shell.js";
|
|
19
|
+
import { getActiveApiBase, getConfiguredDashboard, getManifestApiBases, } from "../core/endpoints.js";
|
|
20
|
+
import { fileURLToPath } from "node:url";
|
|
21
|
+
const pkgPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../package.json");
|
|
22
|
+
const VERSION = JSON.parse(await fs.readFile(pkgPath, "utf-8")).version;
|
|
23
|
+
// ----------------------------------------------------------------
|
|
24
|
+
// Auth — read stored ~/.duct/auth.json
|
|
25
|
+
// ----------------------------------------------------------------
|
|
26
|
+
const DUCT_AUTH_FILE = path.join(os.homedir(), ".duct", "auth.json");
|
|
27
|
+
async function loadAuth() {
|
|
28
|
+
try {
|
|
29
|
+
const raw = await fs.readFile(DUCT_AUTH_FILE, "utf-8");
|
|
30
|
+
return JSON.parse(raw);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Fetch the company's provisioned shells from the Duct API. */
|
|
37
|
+
async function fetchAccountShells(apiKey, ductApiBase) {
|
|
38
|
+
const res = await fetch(`${ductApiBase}/v1/account/shells`, {
|
|
39
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
40
|
+
});
|
|
41
|
+
if (!res.ok)
|
|
42
|
+
return [];
|
|
43
|
+
const data = await res.json();
|
|
44
|
+
return data.shells ?? [];
|
|
45
|
+
}
|
|
46
|
+
// ----------------------------------------------------------------
|
|
47
|
+
// Helpers
|
|
48
|
+
// ----------------------------------------------------------------
|
|
49
|
+
function frameworkDisplay(framework) {
|
|
50
|
+
const map = {
|
|
51
|
+
"next-app": "Next.js (App Router)",
|
|
52
|
+
"next-pages": "Next.js (Pages Router)",
|
|
53
|
+
remix: "Remix",
|
|
54
|
+
"vite-react": "Vite + React",
|
|
55
|
+
sveltekit: "SvelteKit",
|
|
56
|
+
unknown: "Unknown",
|
|
57
|
+
};
|
|
58
|
+
return map[framework.name] ?? framework.name;
|
|
59
|
+
}
|
|
60
|
+
function authDisplay(system) {
|
|
61
|
+
const map = {
|
|
62
|
+
nextauth: "NextAuth.js",
|
|
63
|
+
clerk: "Clerk",
|
|
64
|
+
auth0: "Auth0",
|
|
65
|
+
"custom-jwt": "Custom JWT",
|
|
66
|
+
"session-cookie": "Session Cookie",
|
|
67
|
+
none: "No auth",
|
|
68
|
+
unknown: "Unknown",
|
|
69
|
+
};
|
|
70
|
+
return map[system] ?? system;
|
|
71
|
+
}
|
|
72
|
+
function frameworkFromName(name, srcDir) {
|
|
73
|
+
return {
|
|
74
|
+
name,
|
|
75
|
+
version: "unknown",
|
|
76
|
+
hasAppRouter: name === "next-app",
|
|
77
|
+
hasPagesRouter: name === "next-pages",
|
|
78
|
+
packageManager: "unknown",
|
|
79
|
+
srcDir,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function hasAnyLlmCredential() {
|
|
83
|
+
const keys = [
|
|
84
|
+
"ANTHROPIC_API_KEY",
|
|
85
|
+
"OPENAI_API_KEY",
|
|
86
|
+
"GEMINI_API_KEY",
|
|
87
|
+
"GROQ_API_KEY",
|
|
88
|
+
"OPENROUTER_API_KEY",
|
|
89
|
+
"DUCT_API_KEY",
|
|
90
|
+
];
|
|
91
|
+
return keys.some((key) => Boolean(process.env[key]?.trim()));
|
|
92
|
+
}
|
|
93
|
+
async function checkLlmCredentialsAndPrompt(noAgents, yes) {
|
|
94
|
+
if (noAgents) {
|
|
95
|
+
return false; // User explicitly requested blank template
|
|
96
|
+
}
|
|
97
|
+
if (hasAnyLlmCredential()) {
|
|
98
|
+
return true; // User has at least one LLM credential
|
|
99
|
+
}
|
|
100
|
+
// No LLM credentials found — warn and ask
|
|
101
|
+
console.log(chalk.yellow("\n ⚠ No LLM API key detected\n"));
|
|
102
|
+
console.log(chalk.gray(" The AI agent pipeline requires one LLM provider key:"));
|
|
103
|
+
console.log(chalk.gray(" • ANTHROPIC_API_KEY (Anthropic Claude)"));
|
|
104
|
+
console.log(chalk.gray(" • OPENAI_API_KEY (OpenAI)"));
|
|
105
|
+
console.log(chalk.gray(" • GEMINI_API_KEY (Google Gemini)"));
|
|
106
|
+
console.log(chalk.gray(" • GROQ_API_KEY (Groq)"));
|
|
107
|
+
console.log(chalk.gray(" • OPENROUTER_API_KEY (OpenRouter)"));
|
|
108
|
+
console.log(chalk.gray(" • DUCT_API_KEY (Duct hosted)"));
|
|
109
|
+
console.log(chalk.gray(" Set LLM_MODEL to the model name you want to use.\n"));
|
|
110
|
+
if (yes) {
|
|
111
|
+
// In --yes mode, auto-proceed with blank template
|
|
112
|
+
console.log(chalk.gray(" Proceeding in blank-template mode (-y flag)\n"));
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
const { continueAnyway } = await inquirer.prompt([
|
|
116
|
+
{
|
|
117
|
+
type: "confirm",
|
|
118
|
+
name: "continueAnyway",
|
|
119
|
+
message: "Continue with blank template (no AI analysis)?",
|
|
120
|
+
default: true,
|
|
121
|
+
},
|
|
122
|
+
]);
|
|
123
|
+
if (!continueAnyway) {
|
|
124
|
+
console.log(chalk.cyan("\n Set an LLM provider key and re-run: npx duct init\n"));
|
|
125
|
+
process.exit(0);
|
|
126
|
+
}
|
|
127
|
+
return false; // User confirmed they want blank template
|
|
128
|
+
}
|
|
129
|
+
function displayIssues(issues) {
|
|
130
|
+
const errors = issues.filter((i) => i.severity === "error");
|
|
131
|
+
const warnings = issues.filter((i) => i.severity === "warning");
|
|
132
|
+
if (errors.length > 0) {
|
|
133
|
+
for (const issue of errors) {
|
|
134
|
+
console.log(chalk.red(`\n ✗ ${issue.message}`));
|
|
135
|
+
if (issue.suggestion) {
|
|
136
|
+
console.log(chalk.gray(` ${issue.suggestion}`));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (warnings.length > 0) {
|
|
141
|
+
for (const issue of warnings) {
|
|
142
|
+
console.log(chalk.yellow(`\n ⚠ ${issue.message}`));
|
|
143
|
+
if (issue.suggestion) {
|
|
144
|
+
console.log(chalk.gray(` ${issue.suggestion}`));
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Try to auto-detect the product logo from common favicon locations in `public/`.
|
|
151
|
+
* Returns a relative path string if found, or undefined.
|
|
152
|
+
*/
|
|
153
|
+
async function detectLogoUrl(projectRoot) {
|
|
154
|
+
const candidates = [
|
|
155
|
+
"public/logo.svg",
|
|
156
|
+
"public/logo.png",
|
|
157
|
+
"public/icon.svg",
|
|
158
|
+
"public/icon.png",
|
|
159
|
+
"public/favicon.svg",
|
|
160
|
+
"public/apple-touch-icon.png",
|
|
161
|
+
"public/favicon-32x32.png",
|
|
162
|
+
"public/favicon-16x16.png",
|
|
163
|
+
"public/favicon.png",
|
|
164
|
+
];
|
|
165
|
+
for (const rel of candidates) {
|
|
166
|
+
try {
|
|
167
|
+
await fs.access(path.join(projectRoot, rel));
|
|
168
|
+
// Return the public-relative URL (served at /logo.svg etc.)
|
|
169
|
+
return `/${rel.replace(/^public\//, "")}`;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// not found — try next
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logoUrl) {
|
|
178
|
+
return {
|
|
179
|
+
shellId,
|
|
180
|
+
product: {
|
|
181
|
+
name: productName,
|
|
182
|
+
description: `${productName} — AI-powered interaction shell`,
|
|
183
|
+
baseUrl,
|
|
184
|
+
...(logoUrl ? { logoUrl } : {}),
|
|
185
|
+
},
|
|
186
|
+
auth: result.auth,
|
|
187
|
+
routes: result.routes,
|
|
188
|
+
actions: result.actions,
|
|
189
|
+
deeplinks: result.deeplinks,
|
|
190
|
+
agentPermissions: {
|
|
191
|
+
defaultLevel: "none",
|
|
192
|
+
requireUserConsent: true,
|
|
193
|
+
},
|
|
194
|
+
widget: {
|
|
195
|
+
position: "bottom-right",
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
async function writeFile(filePath, content, dryRun) {
|
|
200
|
+
if (dryRun) {
|
|
201
|
+
console.log(chalk.cyan(`\n[dry-run] Would write: ${filePath}`));
|
|
202
|
+
console.log(chalk.gray("─".repeat(60)));
|
|
203
|
+
console.log(content.slice(0, 500) + (content.length > 500 ? "\n..." : ""));
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
207
|
+
await fs.writeFile(filePath, content, "utf-8");
|
|
208
|
+
}
|
|
209
|
+
async function fileExists(filePath) {
|
|
210
|
+
try {
|
|
211
|
+
await fs.access(filePath);
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function isIgnoredScanDir(name) {
|
|
219
|
+
return [
|
|
220
|
+
".git",
|
|
221
|
+
"node_modules",
|
|
222
|
+
".next",
|
|
223
|
+
"dist",
|
|
224
|
+
"build",
|
|
225
|
+
"out",
|
|
226
|
+
"coverage",
|
|
227
|
+
".turbo",
|
|
228
|
+
".vercel",
|
|
229
|
+
".cache",
|
|
230
|
+
"tmp",
|
|
231
|
+
"temp",
|
|
232
|
+
].includes(name);
|
|
233
|
+
}
|
|
234
|
+
function frameworkPriority(name) {
|
|
235
|
+
const map = {
|
|
236
|
+
"next-app": 100,
|
|
237
|
+
"next-pages": 95,
|
|
238
|
+
remix: 90,
|
|
239
|
+
"vite-react": 85,
|
|
240
|
+
sveltekit: 80,
|
|
241
|
+
nuxt: 78,
|
|
242
|
+
vue3: 75,
|
|
243
|
+
unknown: 0,
|
|
244
|
+
};
|
|
245
|
+
return map[name];
|
|
246
|
+
}
|
|
247
|
+
function rankCandidateRoot(candidateRoot, framework, depth) {
|
|
248
|
+
let score = frameworkPriority(framework.name);
|
|
249
|
+
// Prefer conventional frontend folder names when framework confidence is similar.
|
|
250
|
+
const normalized = candidateRoot.replace(/\\/g, "/").toLowerCase();
|
|
251
|
+
if (/(^|\/)((apps|app|web|frontend|client|site))(\/|$)/.test(normalized)) {
|
|
252
|
+
score += 6;
|
|
253
|
+
}
|
|
254
|
+
if (framework.hasAppRouter)
|
|
255
|
+
score += 3;
|
|
256
|
+
if (framework.hasPagesRouter)
|
|
257
|
+
score += 1;
|
|
258
|
+
// Keep closer folders slightly preferred over deep nested paths.
|
|
259
|
+
score -= depth;
|
|
260
|
+
return score;
|
|
261
|
+
}
|
|
262
|
+
async function discoverFrameworkRoot(startDir, maxDepth = 3) {
|
|
263
|
+
const rootFramework = await detectFramework(startDir);
|
|
264
|
+
let best = {
|
|
265
|
+
framework: rootFramework,
|
|
266
|
+
projectRoot: startDir,
|
|
267
|
+
score: rankCandidateRoot(startDir, rootFramework, 0),
|
|
268
|
+
};
|
|
269
|
+
async function scanDirectory(dirPath, depth) {
|
|
270
|
+
if (depth > maxDepth) {
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
let entries = [];
|
|
274
|
+
try {
|
|
275
|
+
entries = await fs.readdir(dirPath, { withFileTypes: true });
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const hasPackageJson = entries.some((entry) => entry.isFile() && entry.name === "package.json");
|
|
281
|
+
if (hasPackageJson && dirPath !== startDir) {
|
|
282
|
+
const framework = await detectFramework(dirPath);
|
|
283
|
+
if (framework.name !== "unknown") {
|
|
284
|
+
const score = rankCandidateRoot(dirPath, framework, depth);
|
|
285
|
+
if (score > best.score) {
|
|
286
|
+
best = { framework, projectRoot: dirPath, score };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (depth === maxDepth) {
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const childDirs = entries
|
|
294
|
+
.filter((entry) => entry.isDirectory() && !isIgnoredScanDir(entry.name))
|
|
295
|
+
.map((entry) => path.join(dirPath, entry.name));
|
|
296
|
+
await Promise.all(childDirs.map((childDir) => scanDirectory(childDir, depth + 1)));
|
|
297
|
+
}
|
|
298
|
+
await scanDirectory(startDir, 0);
|
|
299
|
+
return {
|
|
300
|
+
framework: best.framework,
|
|
301
|
+
projectRoot: best.projectRoot,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
function getOutputPaths(cwd, framework) {
|
|
305
|
+
const isNextApp = framework.hasAppRouter || framework.name === "next-app";
|
|
306
|
+
const isNextPages = framework.hasPagesRouter || framework.name === "next-pages";
|
|
307
|
+
const configPath = path.join(cwd, "duct.config.ts");
|
|
308
|
+
let receiverPath;
|
|
309
|
+
let tokenRoutePath;
|
|
310
|
+
if (isNextApp) {
|
|
311
|
+
receiverPath = path.join(cwd, "app", "api", "duct", "receive", "route.ts");
|
|
312
|
+
tokenRoutePath = path.join(cwd, "app", "api", "duct", "token", "route.ts");
|
|
313
|
+
}
|
|
314
|
+
else if (isNextPages) {
|
|
315
|
+
receiverPath = path.join(cwd, "pages", "api", "duct", "receive.ts");
|
|
316
|
+
tokenRoutePath = path.join(cwd, "pages", "api", "duct", "token.ts");
|
|
317
|
+
}
|
|
318
|
+
else if (framework.name === "remix") {
|
|
319
|
+
receiverPath = path.join(cwd, "app", "routes", "api.duct.receive.ts");
|
|
320
|
+
tokenRoutePath = path.join(cwd, "app", "routes", "api.duct.token.ts");
|
|
321
|
+
}
|
|
322
|
+
else if (framework.name === "sveltekit") {
|
|
323
|
+
receiverPath = path.join(cwd, "src", "routes", "api", "duct", "receive", "+server.ts");
|
|
324
|
+
tokenRoutePath = path.join(cwd, "src", "routes", "api", "duct", "token", "+server.ts");
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
receiverPath = path.join(cwd, "server", "routes", "duct-receive.ts");
|
|
328
|
+
tokenRoutePath = path.join(cwd, "server", "routes", "duct-token.ts");
|
|
329
|
+
}
|
|
330
|
+
const shellComponentPath = isNextApp || isNextPages
|
|
331
|
+
? path.join(cwd, "components", "DuctShell.tsx")
|
|
332
|
+
: framework.name === "remix"
|
|
333
|
+
? path.join(cwd, "app", "components", "DuctShell.tsx")
|
|
334
|
+
: framework.name === "sveltekit"
|
|
335
|
+
? path.join(cwd, "src", "lib", "components", "DuctShell.svelte")
|
|
336
|
+
: path.join(cwd, "src", "components", "DuctShell.tsx");
|
|
337
|
+
const envTemplatePath = path.join(cwd, getEnvTemplateName(framework));
|
|
338
|
+
return {
|
|
339
|
+
configPath,
|
|
340
|
+
receiverPath,
|
|
341
|
+
tokenRoutePath,
|
|
342
|
+
shellComponentPath,
|
|
343
|
+
envTemplatePath,
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
// ----------------------------------------------------------------
|
|
347
|
+
// pushManifest
|
|
348
|
+
// ----------------------------------------------------------------
|
|
349
|
+
async function pushManifest(config, apiKey, authProfile) {
|
|
350
|
+
const manifestBases = getManifestApiBases(authProfile);
|
|
351
|
+
const attemptedBases = [];
|
|
352
|
+
let lastError = "";
|
|
353
|
+
for (const base of manifestBases) {
|
|
354
|
+
attemptedBases.push(base);
|
|
355
|
+
const response = await fetch(`${base}/v1/shells/${config.shellId}/manifest`, {
|
|
356
|
+
method: "PUT",
|
|
357
|
+
headers: {
|
|
358
|
+
"Content-Type": "application/json",
|
|
359
|
+
Authorization: `Bearer ${apiKey}`,
|
|
360
|
+
},
|
|
361
|
+
body: JSON.stringify({ config }),
|
|
362
|
+
});
|
|
363
|
+
if (response.ok) {
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const body = await response.text();
|
|
367
|
+
lastError = `Duct API error (${response.status}) at ${base}: ${body}`;
|
|
368
|
+
// Keep probing in case this host doesn't expose manifest endpoints.
|
|
369
|
+
if (response.status === 404) {
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
throw new Error(`${lastError}\nTried: ${attemptedBases.join(", ")}`);
|
|
373
|
+
}
|
|
374
|
+
throw new Error(`${lastError || "No manifest API endpoint responded"}\nTried: ${attemptedBases.join(", ")}`);
|
|
375
|
+
}
|
|
376
|
+
// ----------------------------------------------------------------
|
|
377
|
+
// Monorepo detection helpers
|
|
378
|
+
// ----------------------------------------------------------------
|
|
379
|
+
/** Frontend subdirectory candidates to probe for a monorepo structure. */
|
|
380
|
+
const FRONTEND_CANDIDATES = ["frontend", "web", "client"];
|
|
381
|
+
/** Backend subdirectory candidates to probe for a monorepo structure. */
|
|
382
|
+
const BACKEND_CANDIDATES = ["backend", "server", "api"];
|
|
383
|
+
/**
|
|
384
|
+
* Detect whether the project looks like a monorepo with separate frontend/backend dirs.
|
|
385
|
+
* Returns the matched pair, or null if it's not a monorepo.
|
|
386
|
+
*/
|
|
387
|
+
async function detectMonorepoRoots(cwd) {
|
|
388
|
+
let detectedFrontend = null;
|
|
389
|
+
let detectedBackend = null;
|
|
390
|
+
// Check for a frontend directory that has a package.json
|
|
391
|
+
for (const dir of FRONTEND_CANDIDATES) {
|
|
392
|
+
const dirPath = path.join(cwd, dir);
|
|
393
|
+
const pkgPath = path.join(dirPath, "package.json");
|
|
394
|
+
try {
|
|
395
|
+
await fs.access(pkgPath);
|
|
396
|
+
detectedFrontend = dir;
|
|
397
|
+
break;
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
// not found, try next
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (!detectedFrontend)
|
|
404
|
+
return null;
|
|
405
|
+
// Check for a backend directory
|
|
406
|
+
for (const dir of BACKEND_CANDIDATES) {
|
|
407
|
+
const dirPath = path.join(cwd, dir);
|
|
408
|
+
try {
|
|
409
|
+
await fs.access(dirPath);
|
|
410
|
+
detectedBackend = dir;
|
|
411
|
+
break;
|
|
412
|
+
}
|
|
413
|
+
catch {
|
|
414
|
+
// not found, try next
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
if (!detectedBackend)
|
|
418
|
+
return null;
|
|
419
|
+
return { frontendRoot: detectedFrontend, backendRoot: detectedBackend };
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Prompt the user to confirm detected monorepo roots using readline (non-inquirer).
|
|
423
|
+
* Returns the confirmed roots, or null if the user declined.
|
|
424
|
+
*/
|
|
425
|
+
async function promptMonorepoRoots(frontendRoot, backendRoot) {
|
|
426
|
+
return new Promise((resolve) => {
|
|
427
|
+
const rl = readline.createInterface({
|
|
428
|
+
input: process.stdin,
|
|
429
|
+
output: process.stdout,
|
|
430
|
+
});
|
|
431
|
+
console.log(chalk.bold("\n Detected monorepo structure."));
|
|
432
|
+
console.log(chalk.gray(` Frontend: ${frontendRoot}/`));
|
|
433
|
+
console.log(chalk.gray(` Backend: ${backendRoot}/\n`));
|
|
434
|
+
rl.question(" Continue with these roots? (Y/n): ", (answer) => {
|
|
435
|
+
rl.close();
|
|
436
|
+
const trimmed = answer.trim().toLowerCase();
|
|
437
|
+
if (trimmed === "" || trimmed === "y" || trimmed === "yes") {
|
|
438
|
+
resolve({ frontendRoot, backendRoot });
|
|
439
|
+
}
|
|
440
|
+
else {
|
|
441
|
+
resolve(null);
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
// ----------------------------------------------------------------
|
|
447
|
+
// runInit
|
|
448
|
+
// ----------------------------------------------------------------
|
|
449
|
+
/**
|
|
450
|
+
* Run the Duct init command.
|
|
451
|
+
* This is the main entry point for `npx duct init`.
|
|
452
|
+
*/
|
|
453
|
+
export async function runInit(opts = {}) {
|
|
454
|
+
const { cwd = process.cwd(), noAgents = false, dryRun = false, yes = false, } = opts;
|
|
455
|
+
console.log(chalk.bold(`\n ◆ Duct · v${VERSION}`));
|
|
456
|
+
console.log(chalk.gray(" Shell infrastructure for humans and agents."));
|
|
457
|
+
console.log(chalk.gray(" ─────────────────────────────────────────────────────────────\n"));
|
|
458
|
+
// ---- Pre-flight: Block execution from build/output directories ----
|
|
459
|
+
const blockedDirs = ["node_modules", "dist", ".next", "build", "out", ".turbo", "coverage"];
|
|
460
|
+
for (const blocked of blockedDirs) {
|
|
461
|
+
if (cwd.includes(`/${blocked}/`) ||
|
|
462
|
+
cwd.includes(`\\${blocked}\\`) ||
|
|
463
|
+
cwd.endsWith(`/${blocked}`) ||
|
|
464
|
+
cwd.endsWith(`\\${blocked}`)) {
|
|
465
|
+
console.error(`\n ❌ duct init cannot run inside ${blocked}/. Run from your project root.\n`);
|
|
466
|
+
process.exit(1);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
// ---- Pre-flight: Detect monorepo structure ----
|
|
470
|
+
if (!yes) {
|
|
471
|
+
const monoRepoRoots = await detectMonorepoRoots(cwd);
|
|
472
|
+
if (monoRepoRoots) {
|
|
473
|
+
const confirmed = await promptMonorepoRoots(monoRepoRoots.frontendRoot, monoRepoRoots.backendRoot);
|
|
474
|
+
if (confirmed) {
|
|
475
|
+
// Persist the confirmed roots to duct.workspace.json at the project root
|
|
476
|
+
const workspace = {
|
|
477
|
+
frontendRoot: confirmed.frontendRoot,
|
|
478
|
+
backendRoot: confirmed.backendRoot,
|
|
479
|
+
detectedAt: new Date().toISOString(),
|
|
480
|
+
};
|
|
481
|
+
const workspacePath = path.join(cwd, "duct.workspace.json");
|
|
482
|
+
if (!dryRun) {
|
|
483
|
+
await fs.writeFile(workspacePath, JSON.stringify(workspace, null, 2) + "\n", "utf-8");
|
|
484
|
+
console.log(chalk.gray(` Saved monorepo config to duct.workspace.json\n`));
|
|
485
|
+
}
|
|
486
|
+
else {
|
|
487
|
+
console.log(chalk.cyan(`\n[dry-run] Would write: ${workspacePath}`));
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
else {
|
|
491
|
+
console.log(chalk.gray(" Continuing without monorepo configuration.\n"));
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
// ---- Step 0: Verify authentication ----
|
|
496
|
+
const auth = await loadAuth();
|
|
497
|
+
// Resolve dashboard URL from env / saved auth (never hardcoded)
|
|
498
|
+
const dashboardBase = getConfiguredDashboard(auth);
|
|
499
|
+
if (!auth) {
|
|
500
|
+
console.log(chalk.red(" Not logged in.\n"));
|
|
501
|
+
console.log(" Run " +
|
|
502
|
+
chalk.cyan("npx duct login") +
|
|
503
|
+
" first, or register at " +
|
|
504
|
+
chalk.cyan(`${dashboardBase}/register`) +
|
|
505
|
+
"\n");
|
|
506
|
+
process.exit(1);
|
|
507
|
+
}
|
|
508
|
+
console.log(chalk.gray(` Authenticated as ${auth.email} (${auth.slug})\n`));
|
|
509
|
+
// Use saved auth endpoints (or production defaults)
|
|
510
|
+
const ductApiBase = getActiveApiBase(auth);
|
|
511
|
+
// Fetch company's provisioned shells
|
|
512
|
+
const accountShells = await fetchAccountShells(auth.token, ductApiBase);
|
|
513
|
+
// ---- Step 0.5: Check LLM credentials and prompt if missing ----
|
|
514
|
+
if (!noAgents) {
|
|
515
|
+
const shouldRunAgents = await checkLlmCredentialsAndPrompt(noAgents, yes);
|
|
516
|
+
if (!shouldRunAgents) {
|
|
517
|
+
// User either explicitly requested no agents or confirmed blank template mode
|
|
518
|
+
// (in checkLlmCredentialsAndPrompt, if no credentials and not already noAgents,
|
|
519
|
+
// we already prompted and the user confirmed or declined)
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
// ---- Step 1: Detect framework ----
|
|
523
|
+
const frameworkSpinner = ora("Detecting framework...").start();
|
|
524
|
+
let framework;
|
|
525
|
+
let projectRoot = cwd;
|
|
526
|
+
if (opts.framework) {
|
|
527
|
+
framework = frameworkFromName(opts.framework, cwd);
|
|
528
|
+
frameworkSpinner.succeed(`Framework: ${frameworkDisplay(framework)} (forced)`);
|
|
529
|
+
}
|
|
530
|
+
else {
|
|
531
|
+
const discovered = await discoverFrameworkRoot(cwd);
|
|
532
|
+
framework = discovered.framework;
|
|
533
|
+
projectRoot = discovered.projectRoot;
|
|
534
|
+
if (framework.name === "unknown") {
|
|
535
|
+
frameworkSpinner.warn("Framework not detected automatically");
|
|
536
|
+
}
|
|
537
|
+
else {
|
|
538
|
+
frameworkSpinner.succeed(`Framework detected: ${frameworkDisplay(framework)}`);
|
|
539
|
+
}
|
|
540
|
+
if (projectRoot !== cwd) {
|
|
541
|
+
console.log(chalk.gray(` Project root: ${path.relative(cwd, projectRoot)}`));
|
|
542
|
+
}
|
|
543
|
+
if (!yes) {
|
|
544
|
+
const relativeRoot = path.relative(cwd, projectRoot) || ".";
|
|
545
|
+
const detectedLabel = frameworkDisplay(framework);
|
|
546
|
+
const { isDetectedFrameworkCorrect } = await inquirer.prompt([
|
|
547
|
+
{
|
|
548
|
+
type: "confirm",
|
|
549
|
+
name: "isDetectedFrameworkCorrect",
|
|
550
|
+
message: `Detected ${detectedLabel} at ${relativeRoot}. Is this correct?`,
|
|
551
|
+
default: framework.name !== "unknown",
|
|
552
|
+
},
|
|
553
|
+
]);
|
|
554
|
+
if (!isDetectedFrameworkCorrect) {
|
|
555
|
+
const { selectedFramework } = await inquirer.prompt([
|
|
556
|
+
{
|
|
557
|
+
type: "list",
|
|
558
|
+
name: "selectedFramework",
|
|
559
|
+
message: "Select your framework stack:",
|
|
560
|
+
choices: [
|
|
561
|
+
{ name: "Next.js (App Router)", value: "next-app" },
|
|
562
|
+
{ name: "Next.js (Pages Router)", value: "next-pages" },
|
|
563
|
+
{ name: "Vite + React", value: "vite-react" },
|
|
564
|
+
{ name: "Remix", value: "remix" },
|
|
565
|
+
{ name: "SvelteKit", value: "sveltekit" },
|
|
566
|
+
],
|
|
567
|
+
},
|
|
568
|
+
]);
|
|
569
|
+
framework = frameworkFromName(selectedFramework, projectRoot);
|
|
570
|
+
console.log(chalk.gray(` Using manual framework: ${frameworkDisplay(framework)}`));
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
if (framework.name === "unknown") {
|
|
574
|
+
framework = frameworkFromName("next-app", projectRoot);
|
|
575
|
+
console.log(chalk.yellow(" Falling back to Next.js App Router. Re-run init and choose a stack manually if this is incorrect."));
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
// ---- Step 2: Detect auth (fast, no LLM) ----
|
|
579
|
+
const authSpinner = ora("Detecting auth system...").start();
|
|
580
|
+
const sandboxFs = new SandboxFS(projectRoot);
|
|
581
|
+
const authDetection = await detectAuth(sandboxFs);
|
|
582
|
+
authSpinner.succeed(`Auth detected: ${authDisplay(authDetection.system)}`);
|
|
583
|
+
// ---- Step 3: Gather basic info ----
|
|
584
|
+
let shellId;
|
|
585
|
+
let productName;
|
|
586
|
+
let baseUrl;
|
|
587
|
+
// Try to read from existing config if updating
|
|
588
|
+
if (opts.update) {
|
|
589
|
+
const existingConfigPath = path.join(projectRoot, "duct.config.ts");
|
|
590
|
+
if (await fileExists(existingConfigPath)) {
|
|
591
|
+
console.log(chalk.gray(" Updating existing duct.config.ts..."));
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
const pkg = await sandboxFs.readJSON("package.json");
|
|
595
|
+
const defaultProductName = pkg?.name?.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) ??
|
|
596
|
+
"My App";
|
|
597
|
+
// ---- Resolve shell ID from Duct account (never user-typed) ----
|
|
598
|
+
if (!auth) {
|
|
599
|
+
console.log(chalk.red(" Not logged in.\n"));
|
|
600
|
+
console.log(" Run " +
|
|
601
|
+
chalk.cyan("npx duct login") +
|
|
602
|
+
" first, or register at " +
|
|
603
|
+
chalk.cyan(`${dashboardBase}/register`) +
|
|
604
|
+
"\n");
|
|
605
|
+
process.exit(1);
|
|
606
|
+
}
|
|
607
|
+
if (accountShells.length === 0) {
|
|
608
|
+
console.log(chalk.yellow(" No shells provisioned for your account.\n"));
|
|
609
|
+
console.log(" Go to " +
|
|
610
|
+
chalk.cyan(`${dashboardBase}/shells/new`) +
|
|
611
|
+
" to provision a shell first, then re-run `npx duct init`.\n");
|
|
612
|
+
process.exit(1);
|
|
613
|
+
}
|
|
614
|
+
let selectedShell;
|
|
615
|
+
if (accountShells.length === 1 || yes) {
|
|
616
|
+
selectedShell = accountShells[0];
|
|
617
|
+
console.log(chalk.gray(` Using shell: ${chalk.bold(selectedShell.id)}\n`));
|
|
618
|
+
}
|
|
619
|
+
else {
|
|
620
|
+
const { chosenShellId } = await inquirer.prompt([
|
|
621
|
+
{
|
|
622
|
+
type: "list",
|
|
623
|
+
name: "chosenShellId",
|
|
624
|
+
message: "Which shell are you initialising?",
|
|
625
|
+
choices: accountShells.map((s) => ({
|
|
626
|
+
name: `${s.id} ${chalk.gray(`(${s.environment} — ${s.registered_domain})`)}`,
|
|
627
|
+
value: s.id,
|
|
628
|
+
})),
|
|
629
|
+
},
|
|
630
|
+
]);
|
|
631
|
+
selectedShell = accountShells.find((s) => s.id === chosenShellId);
|
|
632
|
+
}
|
|
633
|
+
shellId = selectedShell.id;
|
|
634
|
+
// Product name and base URL
|
|
635
|
+
if (yes) {
|
|
636
|
+
productName = defaultProductName;
|
|
637
|
+
baseUrl = pkg?.homepage ?? selectedShell.registered_domain;
|
|
638
|
+
}
|
|
639
|
+
else {
|
|
640
|
+
const answers = await inquirer.prompt([
|
|
641
|
+
{
|
|
642
|
+
type: "input",
|
|
643
|
+
name: "productName",
|
|
644
|
+
message: "Product name:",
|
|
645
|
+
default: defaultProductName,
|
|
646
|
+
},
|
|
647
|
+
{
|
|
648
|
+
type: "input",
|
|
649
|
+
name: "baseUrl",
|
|
650
|
+
message: "Product base URL:",
|
|
651
|
+
default: pkg?.homepage ?? selectedShell.registered_domain,
|
|
652
|
+
validate: (v) => {
|
|
653
|
+
try {
|
|
654
|
+
new URL(v);
|
|
655
|
+
return true;
|
|
656
|
+
}
|
|
657
|
+
catch {
|
|
658
|
+
return "Must be a valid URL (e.g., https://app.example.com)";
|
|
659
|
+
}
|
|
660
|
+
},
|
|
661
|
+
},
|
|
662
|
+
]);
|
|
663
|
+
productName = answers.productName;
|
|
664
|
+
baseUrl = answers.baseUrl;
|
|
665
|
+
}
|
|
666
|
+
// ---- Step 4: Run agent pipeline ----
|
|
667
|
+
let pipelineResult;
|
|
668
|
+
if (noAgents) {
|
|
669
|
+
console.log(chalk.yellow("\n Skipping agent pipeline (--no-agents)"));
|
|
670
|
+
console.log(chalk.gray(" You'll get a blank template to fill in manually.\n"));
|
|
671
|
+
pipelineResult = {
|
|
672
|
+
routes: [],
|
|
673
|
+
actions: [],
|
|
674
|
+
auth: {
|
|
675
|
+
strategy: authDetection.system,
|
|
676
|
+
sessionFields: authDetection.sessionFields,
|
|
677
|
+
guestAllowed: authDetection.guestAllowed,
|
|
678
|
+
tokenExpirySeconds: 300,
|
|
679
|
+
tokenEndpoint: "/api/duct/token",
|
|
680
|
+
},
|
|
681
|
+
deeplinks: [],
|
|
682
|
+
review: {
|
|
683
|
+
passed: true,
|
|
684
|
+
confidenceScore: 0,
|
|
685
|
+
issues: [],
|
|
686
|
+
suggestions: [
|
|
687
|
+
"Add your routes manually to duct.config.ts",
|
|
688
|
+
"Enable agentAccessible: true on safe read-only actions",
|
|
689
|
+
],
|
|
690
|
+
summary: "Blank template — fill in manually",
|
|
691
|
+
},
|
|
692
|
+
confidenceScore: 0,
|
|
693
|
+
durationMs: 0,
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
else {
|
|
697
|
+
console.log(chalk.bold(" Starting agent pipeline — read-only, sandboxed, 5 agents"));
|
|
698
|
+
console.log(chalk.gray(" Your codebase will not be modified during this step.\n"));
|
|
699
|
+
const emitter = new DuctPipelineEmitter();
|
|
700
|
+
const formatAgentName = (name) => {
|
|
701
|
+
if (!name)
|
|
702
|
+
return "[ Unknown Agent ]";
|
|
703
|
+
if (name === "RouteAgent")
|
|
704
|
+
return "[ Route Agent ]";
|
|
705
|
+
if (name === "ApiAgent")
|
|
706
|
+
return "[ API Agent ]";
|
|
707
|
+
if (name === "AuthAgent")
|
|
708
|
+
return "[ Auth Agent ]";
|
|
709
|
+
if (name === "DeeplinkAgent")
|
|
710
|
+
return "[ Deeplink Agent ]";
|
|
711
|
+
if (name === "ReviewerAgent")
|
|
712
|
+
return "[ Reviewer Agent ]";
|
|
713
|
+
return `[ ${name} ]`.padEnd(20);
|
|
714
|
+
};
|
|
715
|
+
emitter.on("event", (event) => {
|
|
716
|
+
const label = formatAgentName(event.agent);
|
|
717
|
+
if (event.type === "agent:start" && event.agent) {
|
|
718
|
+
process.stdout.write(chalk.gray(` ${label} ${event.message ?? "working..."}\n`));
|
|
719
|
+
}
|
|
720
|
+
if (event.type === "agent:complete" && event.agent) {
|
|
721
|
+
process.stdout.write(chalk.bold(` ${label}`) + chalk.green(` ✓ ${event.message ?? "done"}\n`));
|
|
722
|
+
}
|
|
723
|
+
if (event.type === "agent:error" && event.agent) {
|
|
724
|
+
process.stdout.write(chalk.yellow(` ${label} ⚠ ${event.error?.message ?? "failed"}\n`));
|
|
725
|
+
}
|
|
726
|
+
});
|
|
727
|
+
const pipelineSpinner = ora({ text: "Running pipeline...", prefixText: " " }).start();
|
|
728
|
+
try {
|
|
729
|
+
pipelineResult = await runAgentPipeline(sandboxFs, { emitter });
|
|
730
|
+
pipelineSpinner.stop();
|
|
731
|
+
}
|
|
732
|
+
catch (err) {
|
|
733
|
+
pipelineSpinner.fail("Pipeline failed");
|
|
734
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
735
|
+
console.error(chalk.red(`\n Error: ${message}\n`));
|
|
736
|
+
process.exit(1);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
// ---- Step 5: Show review results ----
|
|
740
|
+
const { review } = pipelineResult;
|
|
741
|
+
console.log(chalk.bold("\n Review Results:"));
|
|
742
|
+
console.log(` ${review.passed ? chalk.green("✓ Passed") : chalk.red("✗ Failed")}`);
|
|
743
|
+
console.log(chalk.gray(` ${review.summary}`));
|
|
744
|
+
if (review.issues.length > 0) {
|
|
745
|
+
displayIssues(review.issues);
|
|
746
|
+
}
|
|
747
|
+
if (review.suggestions.length > 0) {
|
|
748
|
+
console.log(chalk.blue("\n Suggestions:"));
|
|
749
|
+
for (const suggestion of review.suggestions) {
|
|
750
|
+
console.log(chalk.blue(` • ${suggestion}`));
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
// Show what will be generated
|
|
754
|
+
const outputPaths = getOutputPaths(projectRoot, framework);
|
|
755
|
+
console.log(chalk.bold("\n Writing files to your project\n"));
|
|
756
|
+
console.log(chalk.gray(` ${path.relative(cwd, outputPaths.configPath).padEnd(22)} manifest`));
|
|
757
|
+
console.log(chalk.gray(` ${path.relative(cwd, outputPaths.receiverPath).padEnd(22)} receiver route`));
|
|
758
|
+
console.log(chalk.gray(` ${path.relative(cwd, outputPaths.tokenRoutePath).padEnd(22)} token route`));
|
|
759
|
+
console.log(chalk.gray(` ${path.relative(cwd, outputPaths.shellComponentPath).padEnd(22)} widget component`));
|
|
760
|
+
console.log(chalk.gray(` ${path.relative(cwd, outputPaths.envTemplatePath).padEnd(22)} environment template\n`));
|
|
761
|
+
console.log(chalk.gray(" All files are yours to edit. Duct cloud reads duct.config.ts on deploy."));
|
|
762
|
+
// ---- Step 6: Prompt for approval ----
|
|
763
|
+
if (!yes && !dryRun) {
|
|
764
|
+
const { proceed } = await inquirer.prompt([
|
|
765
|
+
{
|
|
766
|
+
type: "confirm",
|
|
767
|
+
name: "proceed",
|
|
768
|
+
message: "Generate these files?",
|
|
769
|
+
default: review.passed,
|
|
770
|
+
},
|
|
771
|
+
]);
|
|
772
|
+
if (!proceed) {
|
|
773
|
+
console.log(chalk.yellow("\n Aborted. No files written."));
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
// ---- Step 7: Write files ----
|
|
778
|
+
const logoUrl = await detectLogoUrl(cwd);
|
|
779
|
+
const config = buildDuctConfigFromPipeline(pipelineResult, shellId, productName, baseUrl, logoUrl);
|
|
780
|
+
const configContent = generateConfigFile(config);
|
|
781
|
+
const receiverContent = generateReceiver(config, framework);
|
|
782
|
+
const tokenRouteContent = generateTokenRoute(config, framework);
|
|
783
|
+
const shellContent = generateShell(config, framework);
|
|
784
|
+
const envContent = generateEnvTemplateForFramework(config, framework);
|
|
785
|
+
await writeFile(outputPaths.configPath, configContent, dryRun);
|
|
786
|
+
await writeFile(outputPaths.receiverPath, receiverContent, dryRun);
|
|
787
|
+
await writeFile(outputPaths.tokenRoutePath, tokenRouteContent, dryRun);
|
|
788
|
+
await writeFile(outputPaths.shellComponentPath, shellContent, dryRun);
|
|
789
|
+
// Safely append to the env template
|
|
790
|
+
const envExists = await fileExists(outputPaths.envTemplatePath);
|
|
791
|
+
if (envExists) {
|
|
792
|
+
const existingEnv = await fs.readFile(outputPaths.envTemplatePath, "utf-8");
|
|
793
|
+
if (!existingEnv.includes("DUCT_SHELL_ID")) {
|
|
794
|
+
if (dryRun) {
|
|
795
|
+
console.log(chalk.cyan(`\n[dry-run] Would append to: ${outputPaths.envTemplatePath}`));
|
|
796
|
+
}
|
|
797
|
+
else {
|
|
798
|
+
await fs.appendFile(outputPaths.envTemplatePath, "\n" + envContent, "utf-8");
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
else {
|
|
803
|
+
await writeFile(outputPaths.envTemplatePath, envContent, dryRun);
|
|
804
|
+
}
|
|
805
|
+
if (!dryRun) {
|
|
806
|
+
console.log(chalk.green("\n ✓ Files written successfully!\n"));
|
|
807
|
+
const apiKey = process.env["DUCT_API_KEY"];
|
|
808
|
+
if (apiKey) {
|
|
809
|
+
try {
|
|
810
|
+
await pushManifest(config, apiKey, auth);
|
|
811
|
+
}
|
|
812
|
+
catch (err) {
|
|
813
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
814
|
+
console.log(chalk.yellow(`\n ⚠ Could not push to Duct cloud: ${message}`));
|
|
815
|
+
console.log(chalk.gray(" Run `npx duct push` manually when ready."));
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
else {
|
|
819
|
+
console.log(chalk.yellow("\n ⚠ Set DUCT_API_KEY to auto-push, or run `npx duct push` manually."));
|
|
820
|
+
}
|
|
821
|
+
const dashboard = getConfiguredDashboard(auth);
|
|
822
|
+
const docsBase = dashboard.replace(/(app|dashboard)\./, "docs.");
|
|
823
|
+
console.log(chalk.bold(`\n ◆ Shell is live\n`));
|
|
824
|
+
console.log(` Shell ID ${chalk.cyan(shellId)}`);
|
|
825
|
+
console.log(` Manifest synced · ${config.routes?.length ?? 0} routes · ${config.actions?.length ?? 0} actions · ${config.deeplinks?.length ?? 0} deeplinks`);
|
|
826
|
+
console.log(` Status registered with Duct cloud\n`);
|
|
827
|
+
console.log(` Next:`);
|
|
828
|
+
console.log(` 1. Review duct.config.ts — set agentAccessible flags on your actions`);
|
|
829
|
+
console.log(` 2. Mount <DuctShell /> in your root layout (see duct/shell.tsx)`);
|
|
830
|
+
console.log(` 3. Confirm the receiver route is reachable at /duct/receive\n`);
|
|
831
|
+
console.log(` Docs ${docsBase}/quickstart`);
|
|
832
|
+
console.log(` Support ${dashboard}/discord`);
|
|
833
|
+
console.log(chalk.gray(` ─────────────────────────────────────────────────────────────\n`));
|
|
834
|
+
}
|
|
835
|
+
}
|