@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
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// ============================================================
|
|
3
|
+
// @duct/sdk — CLI Entry Point
|
|
4
|
+
// ============================================================
|
|
5
|
+
import { Command } from "commander";
|
|
6
|
+
import chalk from "chalk";
|
|
7
|
+
import ora from "ora";
|
|
8
|
+
import inquirer from "inquirer";
|
|
9
|
+
import { runInit } from "./init.js";
|
|
10
|
+
import { SandboxFS } from "./fs/sandbox.js";
|
|
11
|
+
import { getCandidateAuthBases, getConfiguredDashboard, getManifestApiBases, getActiveApiBase, getAuthUrl, getShellRuntimeUrl, } from "../core/endpoints.js";
|
|
12
|
+
import * as fs from "fs/promises";
|
|
13
|
+
import * as path from "path";
|
|
14
|
+
import * as os from "os";
|
|
15
|
+
import * as vm from "node:vm";
|
|
16
|
+
import { pathToFileURL, fileURLToPath } from "node:url";
|
|
17
|
+
import { readFileSync } from "fs";
|
|
18
|
+
// ----------------------------------------------------------------
|
|
19
|
+
// Load all standard .env files in dotenv priority order
|
|
20
|
+
// Priority (last-loaded wins when key already set by earlier file):
|
|
21
|
+
// .env < .env.local < .env.<NODE_ENV> < .env.<NODE_ENV>.local
|
|
22
|
+
// We do NOT overwrite keys already in process.env (shell env takes priority).
|
|
23
|
+
// ----------------------------------------------------------------
|
|
24
|
+
function loadEnvFileSync(envPath) {
|
|
25
|
+
try {
|
|
26
|
+
const content = require("fs").readFileSync(envPath, "utf-8");
|
|
27
|
+
for (const line of content.split("\n")) {
|
|
28
|
+
const trimmed = line.trim();
|
|
29
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
30
|
+
continue;
|
|
31
|
+
const eqIndex = trimmed.indexOf("=");
|
|
32
|
+
if (eqIndex === -1)
|
|
33
|
+
continue;
|
|
34
|
+
const key = trimmed.substring(0, eqIndex).trim();
|
|
35
|
+
const raw = trimmed.substring(eqIndex + 1).trim();
|
|
36
|
+
// Strip surrounding quotes if present
|
|
37
|
+
const value = /^["'].*["']$/.test(raw) ? raw.slice(1, -1) : raw;
|
|
38
|
+
// Later files override earlier ones (dotenv priority: .env.local beats .env)
|
|
39
|
+
// BUT we never override keys already set in the actual shell/process environment
|
|
40
|
+
if (key && !(key in process.env)) {
|
|
41
|
+
process.env[key] = value;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
// File doesn't exist — that's fine, move on
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function loadAllEnvFilesSync() {
|
|
50
|
+
const cwd = process.cwd();
|
|
51
|
+
const nodeEnv = process.env["NODE_ENV"] ?? "";
|
|
52
|
+
// Standard dotenv priority order (lowest → highest priority)
|
|
53
|
+
const candidates = [
|
|
54
|
+
".env",
|
|
55
|
+
".env.local",
|
|
56
|
+
nodeEnv ? `.env.${nodeEnv}` : null,
|
|
57
|
+
nodeEnv ? `.env.${nodeEnv}.local` : null,
|
|
58
|
+
].filter((f) => Boolean(f));
|
|
59
|
+
for (const file of candidates) {
|
|
60
|
+
loadEnvFileSync(path.join(cwd, file));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// Load all .env files synchronously at startup (before any commands run)
|
|
64
|
+
loadAllEnvFilesSync();
|
|
65
|
+
// ----------------------------------------------------------------
|
|
66
|
+
// Config loader helpers
|
|
67
|
+
// ----------------------------------------------------------------
|
|
68
|
+
function toCompiledCandidates(configPath) {
|
|
69
|
+
const ext = path.extname(configPath).toLowerCase();
|
|
70
|
+
if (ext !== ".ts" && ext !== ".tsx") {
|
|
71
|
+
return [configPath];
|
|
72
|
+
}
|
|
73
|
+
const jsSibling = configPath.replace(/\.(ts|tsx)$/i, ".js");
|
|
74
|
+
const mjsSibling = configPath.replace(/\.(ts|tsx)$/i, ".mjs");
|
|
75
|
+
const cjsSibling = configPath.replace(/\.(ts|tsx)$/i, ".cjs");
|
|
76
|
+
const distStyle = configPath
|
|
77
|
+
.replace(/([\\/])src([\\/])/g, "$1dist$2")
|
|
78
|
+
.replace(/\.(ts|tsx)$/i, ".js");
|
|
79
|
+
return [...new Set([jsSibling, mjsSibling, cjsSibling, distStyle])];
|
|
80
|
+
}
|
|
81
|
+
function extractConfigObjectLiteral(source) {
|
|
82
|
+
const marker = "defineDuctConfig(";
|
|
83
|
+
const markerIndex = source.indexOf(marker);
|
|
84
|
+
if (markerIndex === -1)
|
|
85
|
+
return null;
|
|
86
|
+
const startSearch = markerIndex + marker.length;
|
|
87
|
+
let objectStart = -1;
|
|
88
|
+
for (let i = startSearch; i < source.length; i++) {
|
|
89
|
+
const ch = source[i];
|
|
90
|
+
if (!/\s/.test(ch)) {
|
|
91
|
+
if (ch !== "{")
|
|
92
|
+
return null;
|
|
93
|
+
objectStart = i;
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (objectStart === -1)
|
|
98
|
+
return null;
|
|
99
|
+
let depth = 0;
|
|
100
|
+
let inSingle = false;
|
|
101
|
+
let inDouble = false;
|
|
102
|
+
let inTemplate = false;
|
|
103
|
+
let inLineComment = false;
|
|
104
|
+
let inBlockComment = false;
|
|
105
|
+
for (let i = objectStart; i < source.length; i++) {
|
|
106
|
+
const ch = source[i];
|
|
107
|
+
const next = source[i + 1] ?? "";
|
|
108
|
+
const prev = source[i - 1] ?? "";
|
|
109
|
+
if (inLineComment) {
|
|
110
|
+
if (ch === "\n")
|
|
111
|
+
inLineComment = false;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (inBlockComment) {
|
|
115
|
+
if (prev === "*" && ch === "/")
|
|
116
|
+
inBlockComment = false;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (!inSingle && !inDouble && !inTemplate) {
|
|
120
|
+
if (ch === "/" && next === "/") {
|
|
121
|
+
inLineComment = true;
|
|
122
|
+
i++;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (ch === "/" && next === "*") {
|
|
126
|
+
inBlockComment = true;
|
|
127
|
+
i++;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (!inDouble && !inTemplate && ch === "'" && prev !== "\\") {
|
|
132
|
+
inSingle = !inSingle;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (!inSingle && !inTemplate && ch === '"' && prev !== "\\") {
|
|
136
|
+
inDouble = !inDouble;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (!inSingle && !inDouble && ch === "`" && prev !== "\\") {
|
|
140
|
+
inTemplate = !inTemplate;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (inSingle || inDouble || inTemplate) {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (ch === "{")
|
|
147
|
+
depth++;
|
|
148
|
+
if (ch === "}") {
|
|
149
|
+
depth--;
|
|
150
|
+
if (depth === 0) {
|
|
151
|
+
return source.slice(objectStart, i + 1);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
async function loadConfigFromSource(configPath) {
|
|
158
|
+
const source = await fs.readFile(configPath, "utf-8");
|
|
159
|
+
const objectLiteral = extractConfigObjectLiteral(source);
|
|
160
|
+
if (!objectLiteral) {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
const script = new vm.Script(`(${objectLiteral})`, { filename: configPath });
|
|
164
|
+
const evaluated = script.runInNewContext({ process, Math, Date, JSON }, { timeout: 1000 });
|
|
165
|
+
if (!evaluated || typeof evaluated !== "object") {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
return evaluated;
|
|
169
|
+
}
|
|
170
|
+
async function loadDuctConfig(configPath) {
|
|
171
|
+
const candidates = toCompiledCandidates(configPath);
|
|
172
|
+
for (const candidate of candidates) {
|
|
173
|
+
try {
|
|
174
|
+
await fs.access(candidate);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
const module = await import(pathToFileURL(candidate).href);
|
|
181
|
+
const loaded = module.default ?? module;
|
|
182
|
+
if (loaded && typeof loaded === "object") {
|
|
183
|
+
return loaded;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// Try next candidate or source fallback.
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const sourceLoaded = await loadConfigFromSource(configPath);
|
|
191
|
+
if (sourceLoaded) {
|
|
192
|
+
return sourceLoaded;
|
|
193
|
+
}
|
|
194
|
+
throw new Error("CONFIG_LOAD_FAILED");
|
|
195
|
+
}
|
|
196
|
+
// ----------------------------------------------------------------
|
|
197
|
+
// Auth helpers — ~/.duct/auth.json
|
|
198
|
+
// ----------------------------------------------------------------
|
|
199
|
+
const DUCT_AUTH_FILE = path.join(os.homedir(), ".duct", "auth.json");
|
|
200
|
+
async function readAuth() {
|
|
201
|
+
try {
|
|
202
|
+
const raw = await fs.readFile(DUCT_AUTH_FILE, "utf-8");
|
|
203
|
+
return JSON.parse(raw);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async function saveAuth(auth) {
|
|
210
|
+
await fs.mkdir(path.dirname(DUCT_AUTH_FILE), { recursive: true });
|
|
211
|
+
await fs.writeFile(DUCT_AUTH_FILE, JSON.stringify(auth, null, 2), "utf-8");
|
|
212
|
+
}
|
|
213
|
+
async function clearAuth() {
|
|
214
|
+
try {
|
|
215
|
+
await fs.unlink(DUCT_AUTH_FILE);
|
|
216
|
+
}
|
|
217
|
+
catch { /* already gone */ }
|
|
218
|
+
}
|
|
219
|
+
async function validateAndSaveToken(rawKey, ductApiBase, dashboardUrl) {
|
|
220
|
+
const response = await fetch(`${ductApiBase}/v1/auth/validate`, {
|
|
221
|
+
headers: { Authorization: `Bearer ${rawKey}` },
|
|
222
|
+
});
|
|
223
|
+
if (!response.ok)
|
|
224
|
+
throw new Error("Invalid API key");
|
|
225
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
226
|
+
if (!contentType.includes("application/json")) {
|
|
227
|
+
throw new Error(`Unexpected response from ${ductApiBase} (expected JSON)`);
|
|
228
|
+
}
|
|
229
|
+
const data = await response.json();
|
|
230
|
+
const auth = {
|
|
231
|
+
token: rawKey,
|
|
232
|
+
email: data.email ?? "unknown",
|
|
233
|
+
companyId: data.company_id ?? "",
|
|
234
|
+
slug: data.slug ?? "",
|
|
235
|
+
apiBase: ductApiBase,
|
|
236
|
+
dashboardUrl,
|
|
237
|
+
savedAt: new Date().toISOString(),
|
|
238
|
+
};
|
|
239
|
+
await saveAuth(auth);
|
|
240
|
+
return auth;
|
|
241
|
+
}
|
|
242
|
+
// ----------------------------------------------------------------
|
|
243
|
+
// Version from package.json
|
|
244
|
+
// ----------------------------------------------------------------
|
|
245
|
+
const pkgPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../package.json");
|
|
246
|
+
const VERSION = JSON.parse(readFileSync(pkgPath, "utf-8")).version;
|
|
247
|
+
// ----------------------------------------------------------------
|
|
248
|
+
// Program setup
|
|
249
|
+
// ----------------------------------------------------------------
|
|
250
|
+
const program = new Command();
|
|
251
|
+
program
|
|
252
|
+
.name("duct")
|
|
253
|
+
.description("SDK for the Duct shell — Shell infrastructure for humans and agents.")
|
|
254
|
+
.version(VERSION);
|
|
255
|
+
// ----------------------------------------------------------------
|
|
256
|
+
// duct init
|
|
257
|
+
// ----------------------------------------------------------------
|
|
258
|
+
program
|
|
259
|
+
.command("init")
|
|
260
|
+
.description("Initialize Duct in your project — runs AI agent pipeline to generate config")
|
|
261
|
+
.option("--dry-run", "Print generated files without writing them", false)
|
|
262
|
+
.option("--framework <name>", "Skip framework detection (next-app|next-pages|remix|vite-react)")
|
|
263
|
+
.option("--no-agents", "Skip AI pipeline, open blank template", false)
|
|
264
|
+
.option("--update", "Re-run agents on existing duct.config.ts", false)
|
|
265
|
+
.option("-y, --yes", "Auto-approve all prompts", false)
|
|
266
|
+
.action(async (opts) => {
|
|
267
|
+
try {
|
|
268
|
+
await runInit({
|
|
269
|
+
cwd: process.cwd(),
|
|
270
|
+
dryRun: opts.dryRun,
|
|
271
|
+
framework: opts.framework,
|
|
272
|
+
noAgents: Boolean(opts.noAgents),
|
|
273
|
+
update: opts.update,
|
|
274
|
+
yes: opts.yes,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
catch (err) {
|
|
278
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
279
|
+
console.error(chalk.red(`\nError: ${message}\n`));
|
|
280
|
+
process.exit(1);
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
// ----------------------------------------------------------------
|
|
284
|
+
// duct push
|
|
285
|
+
// ----------------------------------------------------------------
|
|
286
|
+
program
|
|
287
|
+
.command("push")
|
|
288
|
+
.description("Push your duct.config.ts manifest to Duct cloud")
|
|
289
|
+
.option("--config <path>", "Path to duct.config.ts", "duct.config.ts")
|
|
290
|
+
.option("--dry-run", "Validate without pushing", false)
|
|
291
|
+
.action(async (opts) => {
|
|
292
|
+
const spinner = ora("Reading config...").start();
|
|
293
|
+
try {
|
|
294
|
+
const cwd = process.cwd();
|
|
295
|
+
const configPath = path.resolve(cwd, opts.config);
|
|
296
|
+
// Check config file exists
|
|
297
|
+
try {
|
|
298
|
+
await fs.access(configPath);
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
spinner.fail(`Config file not found: ${opts.config}`);
|
|
302
|
+
console.log(chalk.yellow("\nRun `npx duct init` first to generate your config.\n"));
|
|
303
|
+
process.exit(1);
|
|
304
|
+
}
|
|
305
|
+
let config;
|
|
306
|
+
try {
|
|
307
|
+
config = await loadDuctConfig(configPath);
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
spinner.fail("Could not load config");
|
|
311
|
+
console.log(chalk.gray("\nTip: Ensure duct.config.ts exports `defineDuctConfig({...})` and does not depend on project-only runtime imports.\n"));
|
|
312
|
+
process.exit(1);
|
|
313
|
+
}
|
|
314
|
+
spinner.succeed("Config loaded");
|
|
315
|
+
if (opts.dryRun) {
|
|
316
|
+
console.log(chalk.green("\n✓ Config is valid (dry-run)\n"));
|
|
317
|
+
console.log(JSON.stringify(config, null, 2).slice(0, 500) + "\n...\n");
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
// Load API key: env var takes precedence, then ~/.duct/auth.json
|
|
321
|
+
let apiKey = process.env["DUCT_API_KEY"];
|
|
322
|
+
if (!apiKey) {
|
|
323
|
+
const auth = await readAuth();
|
|
324
|
+
apiKey = auth?.token;
|
|
325
|
+
}
|
|
326
|
+
if (!apiKey) {
|
|
327
|
+
console.error(chalk.red("\nNot logged in.\n"));
|
|
328
|
+
console.log("Run `npx duct login` first.\n");
|
|
329
|
+
process.exit(1);
|
|
330
|
+
}
|
|
331
|
+
const pushSpinner = ora("Pushing to Duct cloud...").start();
|
|
332
|
+
const shellId = config["shellId"] ?? "unknown";
|
|
333
|
+
const auth = await readAuth();
|
|
334
|
+
const manifestBases = getManifestApiBases(auth);
|
|
335
|
+
let success = false;
|
|
336
|
+
let lastError = "";
|
|
337
|
+
const attemptedBases = [];
|
|
338
|
+
for (const base of manifestBases) {
|
|
339
|
+
attemptedBases.push(base);
|
|
340
|
+
const response = await fetch(`${base}/v1/shells/${shellId}/manifest`, {
|
|
341
|
+
method: "PUT",
|
|
342
|
+
headers: {
|
|
343
|
+
"Content-Type": "application/json",
|
|
344
|
+
Authorization: `Bearer ${apiKey}`,
|
|
345
|
+
},
|
|
346
|
+
body: JSON.stringify({ config }),
|
|
347
|
+
});
|
|
348
|
+
if (response.ok) {
|
|
349
|
+
success = true;
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
const body = await response.text();
|
|
353
|
+
lastError = `API error (${response.status}) at ${base}: ${body}`;
|
|
354
|
+
// Keep probing in case this host doesn't expose manifest endpoints.
|
|
355
|
+
if (response.status === 404) {
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
pushSpinner.fail("Push failed");
|
|
359
|
+
console.error(chalk.red(`\n${lastError}`));
|
|
360
|
+
console.log(chalk.gray(" Tip: Check DUCT_URL is set and services are running."));
|
|
361
|
+
console.log(chalk.gray(" Run npx duct checkup to diagnose connectivity.\n"));
|
|
362
|
+
process.exit(1);
|
|
363
|
+
}
|
|
364
|
+
if (!success) {
|
|
365
|
+
pushSpinner.fail("Push failed");
|
|
366
|
+
console.error(chalk.red(`\n${lastError || "No manifest API endpoint responded"}`));
|
|
367
|
+
console.log(chalk.gray(" Tip: Check that DUCT_URL is set and services are reachable."));
|
|
368
|
+
console.log(chalk.gray(" Run npx duct checkup to diagnose connectivity.\n"));
|
|
369
|
+
process.exit(1);
|
|
370
|
+
}
|
|
371
|
+
pushSpinner.succeed(`Manifest synced for shell: ${chalk.cyan(shellId)}`);
|
|
372
|
+
console.log(chalk.green("\n ◆ Manifest synced\n"));
|
|
373
|
+
}
|
|
374
|
+
catch (err) {
|
|
375
|
+
spinner.fail("Push failed");
|
|
376
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
377
|
+
console.error(chalk.red(`\nError: ${message}\n`));
|
|
378
|
+
process.exit(1);
|
|
379
|
+
}
|
|
380
|
+
});
|
|
381
|
+
// ----------------------------------------------------------------
|
|
382
|
+
// duct login
|
|
383
|
+
// ----------------------------------------------------------------
|
|
384
|
+
program
|
|
385
|
+
.command("login")
|
|
386
|
+
.description("Authenticate with Duct — get your API key from the Duct Web App")
|
|
387
|
+
.option("--token <token>", "Authenticate with a Duct API key directly (dk_live_...)")
|
|
388
|
+
.option("--logout", "Clear stored credentials")
|
|
389
|
+
.action(async (opts) => {
|
|
390
|
+
const existingAuth = await readAuth();
|
|
391
|
+
const dashboardHint = getConfiguredDashboard(existingAuth);
|
|
392
|
+
const registerHint = `${dashboardHint}/register`;
|
|
393
|
+
const attemptedBases = [];
|
|
394
|
+
// duct login --logout
|
|
395
|
+
if (opts.logout) {
|
|
396
|
+
await clearAuth();
|
|
397
|
+
console.log(chalk.green("\n✓ Logged out — credentials cleared\n"));
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
let rawKey;
|
|
401
|
+
if (opts.token) {
|
|
402
|
+
rawKey = opts.token;
|
|
403
|
+
}
|
|
404
|
+
else {
|
|
405
|
+
console.log(chalk.bold("\n ◆ Duct Login\n"));
|
|
406
|
+
console.log(" Get your API key from " +
|
|
407
|
+
chalk.cyan(registerHint) +
|
|
408
|
+
" → after signup it is shown once.\n");
|
|
409
|
+
const { apiKey } = await inquirer.prompt([
|
|
410
|
+
{
|
|
411
|
+
type: "password",
|
|
412
|
+
name: "apiKey",
|
|
413
|
+
message: "Paste your Duct API key (dk_live_...):",
|
|
414
|
+
mask: "*",
|
|
415
|
+
validate: (v) => v.startsWith("dk_live_") || "Key must start with dk_live_",
|
|
416
|
+
},
|
|
417
|
+
]);
|
|
418
|
+
rawKey = apiKey;
|
|
419
|
+
}
|
|
420
|
+
const spinner = ora("Validating key…").start();
|
|
421
|
+
try {
|
|
422
|
+
const candidateBases = getCandidateAuthBases(existingAuth);
|
|
423
|
+
let auth = null;
|
|
424
|
+
let lastError;
|
|
425
|
+
for (const base of candidateBases) {
|
|
426
|
+
attemptedBases.push(base);
|
|
427
|
+
try {
|
|
428
|
+
const dashboardUrl = getConfiguredDashboard(existingAuth);
|
|
429
|
+
auth = await validateAndSaveToken(rawKey, base, dashboardUrl);
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
catch (err) {
|
|
433
|
+
lastError = err;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
if (!auth) {
|
|
437
|
+
const message = lastError instanceof Error ? lastError.message : "Invalid API key";
|
|
438
|
+
throw new Error(message);
|
|
439
|
+
}
|
|
440
|
+
spinner.succeed(`Logged in as ${chalk.bold(auth.email)} (${auth.slug})`);
|
|
441
|
+
console.log(chalk.gray(` API base: ${auth.apiBase}`));
|
|
442
|
+
console.log(chalk.gray(` Credentials saved to ${DUCT_AUTH_FILE}\n`));
|
|
443
|
+
// Best-effort: fetch and display provisioned shells for this account
|
|
444
|
+
try {
|
|
445
|
+
const shellsRes = await fetch(`${auth.apiBase}/v1/shells`, {
|
|
446
|
+
headers: { Authorization: `Bearer ${rawKey}` },
|
|
447
|
+
signal: AbortSignal.timeout(4000),
|
|
448
|
+
});
|
|
449
|
+
if (shellsRes.ok) {
|
|
450
|
+
const shellsData = await shellsRes.json();
|
|
451
|
+
const shells = shellsData.shells ?? [];
|
|
452
|
+
if (shells.length > 0) {
|
|
453
|
+
console.log(chalk.bold(` Provisioned shells (${shells.length}):`));
|
|
454
|
+
for (const s of shells) {
|
|
455
|
+
const status = s.status === "active"
|
|
456
|
+
? chalk.green("active")
|
|
457
|
+
: chalk.yellow(s.status ?? "unknown");
|
|
458
|
+
const name = s.name ? chalk.gray(` — ${s.name}`) : "";
|
|
459
|
+
console.log(` ${chalk.cyan(s.id)}${name} ${status}`);
|
|
460
|
+
}
|
|
461
|
+
console.log();
|
|
462
|
+
}
|
|
463
|
+
else {
|
|
464
|
+
console.log(chalk.gray(" No shells provisioned yet — visit the dashboard to create one.\n"));
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
catch {
|
|
469
|
+
// Shell list fetch is non-critical — ignore errors silently
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
catch (err) {
|
|
473
|
+
spinner.fail("Login failed");
|
|
474
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
475
|
+
console.error(chalk.red(` ${message}`));
|
|
476
|
+
if (attemptedBases.length > 0) {
|
|
477
|
+
console.log(chalk.gray(` Tried: ${attemptedBases.join(", ")}`));
|
|
478
|
+
}
|
|
479
|
+
console.log(chalk.gray(" Tip: Set DUCT_URL and make sure your Duct stack is running."));
|
|
480
|
+
console.log(chalk.gray(" Run npx duct checkup to diagnose connectivity."));
|
|
481
|
+
console.log(chalk.gray(` Get your API key from ${dashboardHint}\n`));
|
|
482
|
+
process.exit(1);
|
|
483
|
+
}
|
|
484
|
+
});
|
|
485
|
+
// ----------------------------------------------------------------
|
|
486
|
+
// duct checkup — validate env + service connectivity
|
|
487
|
+
// ----------------------------------------------------------------
|
|
488
|
+
program
|
|
489
|
+
.command("checkup")
|
|
490
|
+
.description("Check your environment config and verify connectivity to all Duct services")
|
|
491
|
+
.action(async () => {
|
|
492
|
+
const auth = await readAuth();
|
|
493
|
+
const authUrl = getAuthUrl();
|
|
494
|
+
const apiBase = getActiveApiBase(auth);
|
|
495
|
+
const shellUrl = getShellRuntimeUrl();
|
|
496
|
+
const dashUrl = getConfiguredDashboard(auth);
|
|
497
|
+
const shellId = process.env["DUCT_SHELL_ID"];
|
|
498
|
+
const secretKey = process.env["DUCT_SECRET_KEY"];
|
|
499
|
+
const ductUrl = process.env["DUCT_URL"] ?? "";
|
|
500
|
+
console.log(chalk.bold(`\n ◆ Duct · checkup\n`));
|
|
501
|
+
// — Env summary —
|
|
502
|
+
console.log(chalk.bold(" Environment"));
|
|
503
|
+
console.log(chalk.gray(` DUCT_URL : ${ductUrl || chalk.yellow("(not set — using localhost defaults)")}`));
|
|
504
|
+
console.log(chalk.gray(` DUCT_SHELL_ID : ${shellId || chalk.yellow("(not set)")}`));
|
|
505
|
+
console.log(chalk.gray(` DUCT_SECRET_KEY : ${secretKey ? "sk_..." + secretKey.slice(-4) : chalk.yellow("(not set)")}`));
|
|
506
|
+
console.log(chalk.gray(` Auth profile : ${auth ? `${auth.email} (${auth.slug})` : chalk.yellow("(not logged in)")}`));
|
|
507
|
+
console.log();
|
|
508
|
+
// — Service connectivity —
|
|
509
|
+
console.log(chalk.bold(" Services"));
|
|
510
|
+
const checks = [
|
|
511
|
+
{ label: "Auth", url: `${authUrl}/health` },
|
|
512
|
+
{ label: "Agent Proxy", url: `${apiBase}/health` },
|
|
513
|
+
{ label: "Shell Runtime", url: `${shellUrl}/api/health` },
|
|
514
|
+
{ label: "Dashboard", url: `${dashUrl}/api/health` },
|
|
515
|
+
];
|
|
516
|
+
for (const { label, url } of checks) {
|
|
517
|
+
try {
|
|
518
|
+
const controller = new AbortController();
|
|
519
|
+
const timer = setTimeout(() => controller.abort(), 3000);
|
|
520
|
+
const res = await fetch(url, { signal: controller.signal });
|
|
521
|
+
clearTimeout(timer);
|
|
522
|
+
if (res.ok) {
|
|
523
|
+
console.log(` ${chalk.green("✓")} ${label.padEnd(16)} ${chalk.gray(url)}`);
|
|
524
|
+
}
|
|
525
|
+
else {
|
|
526
|
+
console.log(` ${chalk.red("✗")} ${label.padEnd(16)} ${chalk.red(`${res.status}`)} ${chalk.gray(url)}`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
catch {
|
|
530
|
+
console.log(` ${chalk.red("✗")} ${label.padEnd(16)} ${chalk.red("unreachable")} ${chalk.gray(url)}`);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
console.log();
|
|
534
|
+
if (!auth) {
|
|
535
|
+
console.log(chalk.yellow(" ⚠ Not logged in — run: npx duct login\n"));
|
|
536
|
+
}
|
|
537
|
+
else {
|
|
538
|
+
console.log(chalk.green(" ✓ All checks complete\n"));
|
|
539
|
+
}
|
|
540
|
+
});
|
|
541
|
+
// ----------------------------------------------------------------
|
|
542
|
+
// duct scan (diagnostic / drift detection)
|
|
543
|
+
// ----------------------------------------------------------------
|
|
544
|
+
program
|
|
545
|
+
.command("scan")
|
|
546
|
+
.description("Probe live API endpoints against duct.config.ts and report drift")
|
|
547
|
+
.option("--config <path>", "Path to duct.config.ts", "duct.config.ts")
|
|
548
|
+
.option("--json", "Output results as JSON", false)
|
|
549
|
+
.action(async (opts) => {
|
|
550
|
+
const cwd = process.cwd();
|
|
551
|
+
const sandboxFs = new SandboxFS(cwd);
|
|
552
|
+
console.log(chalk.bold("\n ◆ Duct · manifest update\n"));
|
|
553
|
+
// Check config exists
|
|
554
|
+
const configExists = await sandboxFs.exists(opts.config);
|
|
555
|
+
if (!configExists) {
|
|
556
|
+
console.log(chalk.yellow(`No ${opts.config} found. Run \`npx duct init\` first.\n`));
|
|
557
|
+
process.exit(1);
|
|
558
|
+
}
|
|
559
|
+
// Load config from compiled JS if available, otherwise parse TypeScript source.
|
|
560
|
+
let config;
|
|
561
|
+
try {
|
|
562
|
+
const configPath = path.resolve(cwd, opts.config);
|
|
563
|
+
const raw = await loadDuctConfig(configPath);
|
|
564
|
+
config = raw;
|
|
565
|
+
}
|
|
566
|
+
catch {
|
|
567
|
+
console.log(chalk.yellow("Could not load config. Ensure duct.config.ts is valid and exports defineDuctConfig({...}).\n"));
|
|
568
|
+
process.exit(1);
|
|
569
|
+
}
|
|
570
|
+
const { runDriftCheck, printDriftReport } = await import("./drift.js");
|
|
571
|
+
try {
|
|
572
|
+
const report = await runDriftCheck(config);
|
|
573
|
+
if (opts.json) {
|
|
574
|
+
console.log(JSON.stringify(report, null, 2));
|
|
575
|
+
}
|
|
576
|
+
else {
|
|
577
|
+
printDriftReport(report);
|
|
578
|
+
}
|
|
579
|
+
if (report.hasDrift)
|
|
580
|
+
process.exitCode = 1;
|
|
581
|
+
}
|
|
582
|
+
catch (err) {
|
|
583
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
584
|
+
console.error(chalk.red(`\nScan failed: ${message}\n`));
|
|
585
|
+
process.exit(1);
|
|
586
|
+
}
|
|
587
|
+
});
|
|
588
|
+
// ----------------------------------------------------------------
|
|
589
|
+
// Error handling
|
|
590
|
+
// ----------------------------------------------------------------
|
|
591
|
+
program.exitOverride();
|
|
592
|
+
try {
|
|
593
|
+
program.parse(process.argv);
|
|
594
|
+
}
|
|
595
|
+
catch (err) {
|
|
596
|
+
if (err.code === "commander.helpDisplayed" ||
|
|
597
|
+
err.code === "commander.version") {
|
|
598
|
+
process.exit(0);
|
|
599
|
+
}
|
|
600
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
601
|
+
console.error(chalk.red(`Error: ${message}`));
|
|
602
|
+
process.exit(1);
|
|
603
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface InitOptions {
|
|
2
|
+
/** Project root directory */
|
|
3
|
+
cwd?: string;
|
|
4
|
+
/** Skip the agent pipeline (open blank template) */
|
|
5
|
+
noAgents?: boolean;
|
|
6
|
+
/** Only print output, don't write files */
|
|
7
|
+
dryRun?: boolean;
|
|
8
|
+
/** Force framework detection result */
|
|
9
|
+
framework?: string;
|
|
10
|
+
/** Re-run agents on an existing duct.config.ts */
|
|
11
|
+
update?: boolean;
|
|
12
|
+
/** Non-interactive mode (auto-approve) */
|
|
13
|
+
yes?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface GeneratedFiles {
|
|
16
|
+
configPath: string;
|
|
17
|
+
receiverPath: string;
|
|
18
|
+
tokenRoutePath: string;
|
|
19
|
+
shellComponentPath: string;
|
|
20
|
+
envTemplatePath: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Run the Duct init command.
|
|
24
|
+
* This is the main entry point for `npx duct init`.
|
|
25
|
+
*/
|
|
26
|
+
export declare function runInit(opts?: InitOptions): Promise<void>;
|