@duct-sdk/sdk 0.1.13 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,30 @@
1
+ # Changelog — @duct-sdk/sdk
2
+
3
+ Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
+
5
+ ## [0.2.1] — 2026-06-06
6
+
7
+ ### Changed
8
+ - Smaller published package (removed unused bundled image asset)
9
+
10
+ ## [0.2.0] — 2026-06-06
11
+
12
+ ### Added
13
+ - `duct init --manual` — commented `duct.config.ts` template without LLM
14
+ - `duct init --update` — re-scan only files changed since last push
15
+ - `duct promote --from <id> --to <id>` — copy manifest between environment shells
16
+ - Interactive init review with confidence scores for detected routes and actions
17
+
18
+ ### Changed
19
+ - `allowedCallers` is canonical; legacy `allowedAgents` removed from config types
20
+ - Generated configs and examples use environment-configurable base URLs
21
+
22
+ ## [0.1.13] — 2026-06-05
23
+
24
+ ### Fixed
25
+ - More stable generator output for empty manifests
26
+
27
+ ## [0.1.0] — 2026-03-15
28
+
29
+ ### Added
30
+ - Initial publish: `login`, `init`, `push`, `pull`, framework adapters (Next, Remix, Vite, SvelteKit, React)
package/README.md CHANGED
@@ -1,19 +1,21 @@
1
1
  # @duct-sdk/sdk
2
2
 
3
- An intelligent execution shell for your product — lets humans and agents act on your backend without touching your UI.
3
+ **Let agents use your product safely.**
4
4
 
5
- > A shell (like terminal) that knows when to talk, when to show, and when to hand off.
5
+ The Duct SDK scans your codebase, generates a manifest, and provides embed components so humans and agents can call your existing APIs through one permissioned surface.
6
6
 
7
- - **Humans** type what they want, Duct executes it, navigates, or surfaces structured data inline.
8
- - **Agents** get a permissioned, structured API surface — no scraping, no computer use.
7
+ - **Humans** — chat or use an embedded shell; Duct runs actions or hands off via signed deeplinks
8
+ - **Agents** — structured, permissioned API access from the same manifest — no scraping, no screen automation
9
9
 
10
- Credentials and shell provisioning are managed by **duct**.
10
+ Credentials and shell provisioning are managed by Duct.
11
+
12
+ Release notes for each version are in [`CHANGELOG.md`](CHANGELOG.md) (included in the published npm package).
11
13
 
12
14
  ---
13
15
 
14
16
  ## Quickstart
15
17
 
16
- **1. Create your account and get your API key**
18
+ **1. Create your account** in the Duct dashboard and copy your API key.
17
19
 
18
20
  **2. Authenticate:**
19
21
 
@@ -21,24 +23,30 @@ Credentials and shell provisioning are managed by **duct**.
21
23
  npx @duct-sdk/sdk login
22
24
  ```
23
25
 
24
- **3. Run setup in the root of your project:**
26
+ **3. Generate a manifest** (recommended path for first setup):
27
+
28
+ ```bash
29
+ npx @duct-sdk/sdk init --manual
30
+ ```
31
+
32
+ For AI-assisted scanning once your API surface is stable:
25
33
 
26
34
  ```bash
27
35
  npx @duct-sdk/sdk init
28
36
  ```
29
37
 
30
- This scans your codebase, detects your API surface, and generates:
38
+ This produces:
31
39
  - `duct.config.ts` — your shell manifest
32
40
  - A receiver route (`/duct/receive`) — handles deeplink handoffs
33
41
  - A shell widget component — drop into your layout
34
42
 
35
- **4. Push your manifest to Duct cloud:**
43
+ **4. Push your manifest:**
36
44
 
37
45
  ```bash
38
46
  npx @duct-sdk/sdk push
39
47
  ```
40
48
 
41
- **5. Add the shell to your layout** (Next.js example):
49
+ **5. Embed the shell** (Next.js example):
42
50
 
43
51
  ```tsx
44
52
  import { DuctShell } from '@duct-sdk/sdk/next';
@@ -55,23 +63,26 @@ export default function Layout({ children }) {
55
63
 
56
64
  ---
57
65
 
58
- ## CLI Reference
66
+ ## CLI reference
59
67
 
60
68
  | Command | Description |
61
69
  |---|---|
62
70
  | `npx @duct-sdk/sdk login` | Authenticate with your Duct API key |
63
- | `npx @duct-sdk/sdk init` | Scan codebase and generate config + shell files |
64
- | `npx @duct-sdk/sdk init --no-agents` | Skip AI scan and start from a blank template |
65
- | `npx @duct-sdk/sdk push` | Push `duct.config.ts` manifest to Duct cloud |
71
+ | `npx @duct-sdk/sdk init` | AI-assisted scan — generates config + shell files |
72
+ | `npx @duct-sdk/sdk init --manual` | Instant template without LLM (recommended first run) |
73
+ | `npx @duct-sdk/sdk init --update` | Re-scan only files changed since last push |
74
+ | `npx @duct-sdk/sdk init --no-agents` | Skip AI scan; blank template |
75
+ | `npx @duct-sdk/sdk push` | Push `duct.config.ts` to Duct |
66
76
  | `npx @duct-sdk/sdk pull <hash>` | Restore a manifest version from push history |
67
- | `npx @duct-sdk/sdk init --update` | Incremental re-scan against git diff |
68
- | `npx @duct-sdk/sdk init --manual` | Generate a config template without LLM (instant) |
77
+ | `npx @duct-sdk/sdk promote --from <id> --to <id>` | Copy manifest to another environment shell |
69
78
  | `npx @duct-sdk/sdk scan` | Detect drift between live API and manifest |
70
79
  | `npx @duct-sdk/sdk checkup` | Check env config and service connectivity |
71
80
 
72
- Once installed globally (`npm i -g @duct-sdk/sdk`), all commands shorten to `duct login`, `duct init`, `duct pull`, etc.
81
+ Once installed globally (`npm i -g @duct-sdk/sdk`), commands shorten to `duct login`, `duct init`, etc.
82
+
83
+ ---
73
84
 
74
- ## Framework Support
85
+ ## Framework support
75
86
 
76
87
  | Framework | Import |
77
88
  |---|---|
@@ -81,12 +92,12 @@ Once installed globally (`npm i -g @duct-sdk/sdk`), all commands shorten to `duc
81
92
  | SvelteKit | `@duct-sdk/sdk/sveltekit` |
82
93
  | React Embed | `@duct-sdk/sdk/react` |
83
94
 
84
- > Your API endpoints stay yours. Duct reads your manifest, routes intent, and calls your existing endpoints — nothing is proxied or stored.
95
+ Your API endpoints stay yours. Duct reads your manifest and calls your existing routes — nothing is proxied or stored.
85
96
 
86
97
  ---
87
98
 
88
99
  ## Security
89
100
 
90
- - Keep secrets server-side and never expose them in client code
91
- - Use least privilege when marking actions as agent-accessible
92
- - Store credentials in environment variables and rotate them in the Duct dashboard when needed
101
+ - Keep secrets server-side; never expose them in client code
102
+ - Use least privilege when marking actions as `agentAccessible`
103
+ - Store credentials in environment variables; rotate keys in the dashboard when needed
@@ -55,7 +55,7 @@ export interface DuctShellProps {
55
55
  /**
56
56
  * Duct shell host URL.
57
57
  * For local dev: http://localhost:3000
58
- * For production: https://shell.duct.sh
58
+ * For production: your Duct shell host URL (local default: http://localhost:3000)
59
59
  */
60
60
  shellHost?: string;
61
61
  /**
@@ -55,7 +55,7 @@ export interface DuctShellProps {
55
55
  /**
56
56
  * Duct shell host URL.
57
57
  * For local dev: http://localhost:3000
58
- * For production: https://shell.duct.sh
58
+ * For production: your Duct shell host URL (local default: http://localhost:3000)
59
59
  */
60
60
  shellHost?: string;
61
61
  /**
@@ -106,7 +106,7 @@ export interface ShellStatusResult {
106
106
  *
107
107
  * @example
108
108
  * ```tsx
109
- * const { status } = useShellStatus('shell_acme_prod', 'https://shell.duct.sh');
109
+ * const { status } = useShellStatus('shell_acme_prod', 'http://localhost:3000');
110
110
  * if (status !== 'live') return null;
111
111
  * ```
112
112
  */
@@ -11,7 +11,7 @@ import React, { useEffect, useRef, useCallback, useState, } from "react";
11
11
  *
12
12
  * @example
13
13
  * ```tsx
14
- * const { status } = useShellStatus('shell_acme_prod', 'https://shell.duct.sh');
14
+ * const { status } = useShellStatus('shell_acme_prod', 'http://localhost:3000');
15
15
  * if (status !== 'live') return null;
16
16
  * ```
17
17
  */
@@ -1,7 +1,7 @@
1
1
  import type { DuctPageContext } from "../../core/types.js";
2
2
  export interface UseDuctPageContextOptions {
3
3
  /**
4
- * The Duct shell host URL (e.g. "https://shell.duct.sh" or "http://localhost:3000").
4
+ * The Duct shell host URL (e.g. "http://localhost:3000" in local dev).
5
5
  * When provided, the hook validates event.origin against this value — only the
6
6
  * Duct iframe can request page context, blocking arbitrary cross-origin access.
7
7
  * When omitted, the hook accepts requests from any origin (useful in dev/test).
@@ -9,6 +9,16 @@ export interface TopoResult {
9
9
  routeRoot: string;
10
10
  /** Relative path to the API directory (e.g. "app/api", "pages/api", "routes") */
11
11
  apiRoot: string;
12
+ /** All candidate API root directories (plural — for selectors) */
13
+ apiRoots: string[];
14
+ /** All candidate route root directories (plural — for selectors) */
15
+ routeRoots: string[];
16
+ /** Detected package manager */
17
+ packageManager: "npm" | "yarn" | "pnpm" | "pip" | "unknown";
18
+ /** Absolute path to the project root */
19
+ projectRoot: string;
20
+ /** Detection confidence 0–1 (1 = all signals confirmed) */
21
+ confidence: number;
12
22
  /** Auth library detected from deps / config files */
13
23
  authLib: AuthStrategy;
14
24
  /** Whether this looks like a monorepo (multiple package.json dirs) */
@@ -24,3 +34,13 @@ export interface TopoResult {
24
34
  * Must run before any agent or selector.
25
35
  */
26
36
  export declare function discoverTopology(projectRoot: string): Promise<TopoResult>;
37
+ /**
38
+ * Detect project topology for the selector pipeline (Phase 0).
39
+ *
40
+ * Returns an enriched TopoResult with plural `apiRoots`, `routeRoots`,
41
+ * `packageManager`, `projectRoot`, and `confidence` in addition to the
42
+ * existing fields from `discoverTopology()`.
43
+ *
44
+ * No LLM — pure filesystem reads only.
45
+ */
46
+ export declare function detectTopology(projectRoot: string): Promise<TopoResult>;
@@ -179,6 +179,50 @@ async function inferRoots(projectRoot, framework, topLevel) {
179
179
  return { routeRoot, apiRoot, refinedFramework: framework };
180
180
  }
181
181
  // ----------------------------------------------------------------
182
+ // Package manager detection
183
+ // ----------------------------------------------------------------
184
+ async function detectPackageManager(projectRoot, topLevel) {
185
+ const files = topLevel.filter((e) => !e.isDir).map((e) => e.name);
186
+ if (files.includes("pnpm-lock.yaml") || files.includes("pnpm-workspace.yaml"))
187
+ return "pnpm";
188
+ if (files.includes("yarn.lock"))
189
+ return "yarn";
190
+ if (files.includes("package-lock.json"))
191
+ return "npm";
192
+ if (files.includes("package.json")) {
193
+ // Check packageManager field in package.json
194
+ const pkg = await readJsonFile(path.join(projectRoot, "package.json"));
195
+ const pm = pkg?.packageManager;
196
+ if (pm?.startsWith("pnpm"))
197
+ return "pnpm";
198
+ if (pm?.startsWith("yarn"))
199
+ return "yarn";
200
+ if (pm?.startsWith("npm"))
201
+ return "npm";
202
+ return "npm"; // has package.json — default to npm
203
+ }
204
+ if (files.includes("requirements.txt") || files.includes("pyproject.toml") || files.includes("setup.py")) {
205
+ return "pip";
206
+ }
207
+ return "unknown";
208
+ }
209
+ // ----------------------------------------------------------------
210
+ // Confidence scoring
211
+ // ----------------------------------------------------------------
212
+ function computeConfidence(framework, apiRoots, routeRoots, packageManagerKnown) {
213
+ if (framework === "unknown")
214
+ return 0.3;
215
+ let score = 0.5; // base — framework detected
216
+ // Bonus for confirmed directory structure
217
+ if (apiRoots.length > 0)
218
+ score += 0.2;
219
+ if (routeRoots.length > 0)
220
+ score += 0.15;
221
+ if (packageManagerKnown)
222
+ score += 0.15;
223
+ return Math.min(score, 1.0);
224
+ }
225
+ // ----------------------------------------------------------------
182
226
  // Language detection
183
227
  // ----------------------------------------------------------------
184
228
  async function detectLanguage(_projectRoot, topLevel) {
@@ -298,13 +342,76 @@ export async function discoverTopology(projectRoot) {
298
342
  framework = refinedFramework;
299
343
  // 7. Detect monorepo
300
344
  const { isMonorepo, packageDirs } = await detectMonorepo(resolvedRoot, pkg, topLevel);
345
+ // 8. Detect package manager
346
+ const packageManager = await detectPackageManager(resolvedRoot, topLevel);
347
+ // 9. Build plural root arrays for selectors
348
+ const routeRoots = buildRouteRoots(framework, routeRoot);
349
+ const apiRoots = buildApiRoots(framework, apiRoot);
350
+ // 10. Compute confidence
351
+ const confidence = computeConfidence(framework, apiRoots, routeRoots, packageManager !== "unknown");
301
352
  return {
302
353
  framework,
303
354
  language,
304
355
  routeRoot,
305
356
  apiRoot,
357
+ apiRoots,
358
+ routeRoots,
359
+ packageManager,
360
+ projectRoot: resolvedRoot,
361
+ confidence,
306
362
  authLib,
307
363
  isMonorepo,
308
364
  packageDirs,
309
365
  };
310
366
  }
367
+ // ----------------------------------------------------------------
368
+ // Plural roots helpers
369
+ // ----------------------------------------------------------------
370
+ function buildRouteRoots(framework, routeRoot) {
371
+ switch (framework) {
372
+ case "next-app":
373
+ return ["app", "src/app"].filter((d) => d === routeRoot || routeRoot.includes(d.replace("src/", "")));
374
+ case "next-pages":
375
+ return ["pages", "src/pages"].filter((d) => d === routeRoot || routeRoot.includes(d.replace("src/", "")));
376
+ case "remix":
377
+ return ["app/routes", "app"];
378
+ case "sveltekit":
379
+ return ["src/routes"];
380
+ case "nuxt":
381
+ return ["pages"];
382
+ default:
383
+ return routeRoot ? [routeRoot] : [];
384
+ }
385
+ }
386
+ function buildApiRoots(framework, apiRoot) {
387
+ switch (framework) {
388
+ case "next-app":
389
+ return ["app/api", "src/app/api"].filter((d) => d === apiRoot || apiRoot.includes("api"));
390
+ case "next-pages":
391
+ return ["pages/api", "src/pages/api"].filter((d) => d === apiRoot || apiRoot.includes("api"));
392
+ case "remix":
393
+ return ["app/routes"];
394
+ case "sveltekit":
395
+ return ["src/routes/api", "src/routes"];
396
+ default: {
397
+ const candidates = ["routes", "src/routes", "api", "routers", "controllers", "handlers"];
398
+ const found = candidates.filter((c) => apiRoot === c || apiRoot.startsWith(c));
399
+ return found.length > 0 ? found : (apiRoot ? [apiRoot] : []);
400
+ }
401
+ }
402
+ }
403
+ // ----------------------------------------------------------------
404
+ // detectTopology — spec-compliant alias
405
+ // ----------------------------------------------------------------
406
+ /**
407
+ * Detect project topology for the selector pipeline (Phase 0).
408
+ *
409
+ * Returns an enriched TopoResult with plural `apiRoots`, `routeRoots`,
410
+ * `packageManager`, `projectRoot`, and `confidence` in addition to the
411
+ * existing fields from `discoverTopology()`.
412
+ *
413
+ * No LLM — pure filesystem reads only.
414
+ */
415
+ export async function detectTopology(projectRoot) {
416
+ return discoverTopology(projectRoot);
417
+ }
@@ -156,8 +156,8 @@ function generateAgentPermissions(perms, indentSpaces) {
156
156
  if (perms.allowedActions && perms.allowedActions.length > 0) {
157
157
  lines.push(`${pad} allowedActions: ${formatStringArray(perms.allowedActions, indentSpaces + 2)},`);
158
158
  }
159
- if (perms.allowedAgents && perms.allowedAgents.length > 0) {
160
- lines.push(`${pad} allowedAgents: ${formatStringArray(perms.allowedAgents, indentSpaces + 2)},`);
159
+ if (perms.allowedCallers && perms.allowedCallers.length > 0) {
160
+ lines.push(`${pad} allowedCallers: ${formatStringArray(perms.allowedCallers, indentSpaces + 2)},`);
161
161
  }
162
162
  if (perms.actionOverrides && Object.keys(perms.actionOverrides).length > 0) {
163
163
  lines.push(`${pad} actionOverrides: ${jsonValue(perms.actionOverrides, indentSpaces + 2)},`);
@@ -209,7 +209,7 @@ export function generateManualTemplate(opts) {
209
209
  *
210
210
  * to sync this manifest with Duct cloud.
211
211
  *
212
- * Docs: https://docs.duct.sh/config
212
+ * Docs: see your Duct deployment /docs (local default: http://localhost:3005/docs)
213
213
  */
214
214
 
215
215
  import { defineDuctConfig } from "@duct-sdk/sdk";
@@ -377,7 +377,7 @@ export function generateConfigFile(config) {
377
377
  if (config.widget) {
378
378
  sections.push("", `${i}// Shell widget display configuration`, `${i}${generateWidget(config.widget, 2)}`);
379
379
  }
380
- let docsBase = 'https://docs.duct.sh';
380
+ let docsBase = 'http://localhost:3005/docs';
381
381
  if (config.product?.baseUrl) {
382
382
  try {
383
383
  const hostname = new URL(config.product.baseUrl).hostname;
@@ -12,7 +12,7 @@ function generateReactShellComponent(config) {
12
12
  const height = config.widget?.height ?? 620;
13
13
  const docsBase = config.product?.baseUrl
14
14
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
15
- : 'https://docs.duct.sh';
15
+ : 'http://localhost:3005/docs';
16
16
  return `/**
17
17
  * Duct Shell Widget — auto-generated by \`npx duct init\`
18
18
  *
@@ -156,7 +156,7 @@ function generateRemixShellComponent(config) {
156
156
  const position = config.widget?.position ?? "bottom-right";
157
157
  const docsBase = config.product?.baseUrl
158
158
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
159
- : 'https://docs.duct.sh';
159
+ : 'http://localhost:3005/docs';
160
160
  return `/**
161
161
  * Duct Shell Widget — auto-generated by \`npx duct init\`
162
162
  *
@@ -214,7 +214,7 @@ function generateViteShellComponent(config) {
214
214
  const position = config.widget?.position ?? "bottom-right";
215
215
  const docsBase = config.product?.baseUrl
216
216
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
217
- : 'https://docs.duct.sh';
217
+ : 'http://localhost:3005/docs';
218
218
  return `/**
219
219
  * Duct Shell Widget — auto-generated by \`npx duct init\`
220
220
  *
@@ -330,7 +330,7 @@ export function getEnvTemplateName(framework) {
330
330
  function generateSvelteKitShellComponent(config) {
331
331
  const docsBase = config.product?.baseUrl
332
332
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
333
- : 'https://docs.duct.sh';
333
+ : 'http://localhost:3005/docs';
334
334
  return `<!--
335
335
  Duct Shell Widget — auto-generated by \`npx duct init\`
336
336
 
@@ -438,7 +438,7 @@ function generateVue3ShellComponent(config) {
438
438
  const height = config.widget?.height ?? 620;
439
439
  const docsBase = config.product?.baseUrl
440
440
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
441
- : 'https://docs.duct.sh';
441
+ : 'http://localhost:3005/docs';
442
442
  const positionStyle = position === "bottom-left"
443
443
  ? "bottom: 24px; left: 24px;"
444
444
  : "bottom: 24px; right: 24px;";
@@ -557,7 +557,7 @@ function generateNuxtShellComponent(config) {
557
557
  const height = config.widget?.height ?? 620;
558
558
  const docsBase = config.product?.baseUrl
559
559
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
560
- : 'https://docs.duct.sh';
560
+ : 'http://localhost:3005/docs';
561
561
  const positionStyle = position === "bottom-left"
562
562
  ? "bottom: 24px; left: 24px;"
563
563
  : "bottom: 24px; right: 24px;";
package/dist/cli/index.js CHANGED
@@ -324,7 +324,7 @@ program
324
324
  process.exit(1);
325
325
  }
326
326
  });
327
- // Mirror of buildDependsOnPlan() in services/shell-runtime/app/api/chat/route.ts — keep in sync.
327
+ // Topological order for action dependsOn chains (max depth 4).
328
328
  function buildDependsOnOrder(targetId, actions, visited = new Set()) {
329
329
  if (visited.has(targetId) || visited.size > 4)
330
330
  return [];
@@ -457,7 +457,7 @@ program
457
457
  console.log(chalk.gray(` • ${wf.name} (${stepNames})`));
458
458
  }
459
459
  console.log();
460
- // Embed into the manifest so agent-proxy stores them alongside actions
460
+ // Embed into the manifest so Duct stores them alongside actions
461
461
  config = { ...config, precomputedWorkflows };
462
462
  }
463
463
  const pushSpinner = ora("Pushing to Duct cloud...").start();
@@ -532,6 +532,13 @@ program
532
532
  process.exit(1);
533
533
  }
534
534
  pushSpinner.succeed(`Manifest synced for shell: ${chalk.cyan(shellId)}`);
535
+ // Keep .duct-manifest.json in sync so `duct scan --manifest-diff` always
536
+ // diffs against what was actually last pushed, not just what `duct init` wrote.
537
+ try {
538
+ const snapshotPath = path.resolve(cwd, ".duct-manifest.json");
539
+ await fs.writeFile(snapshotPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
540
+ }
541
+ catch { /* non-fatal — snapshot is a local convenience file */ }
535
542
  console.log(chalk.green("\n ◆ Manifest synced\n"));
536
543
  }
537
544
  catch (err) {
@@ -605,7 +612,7 @@ program
605
612
  console.log(chalk.gray(` Credentials saved to ${DUCT_AUTH_FILE} (mode 600)\n`));
606
613
  console.log(chalk.yellow(` ⚠ Keep this file private — it contains your API key.\n Add ${DUCT_AUTH_FILE} to your global .gitignore.\n`));
607
614
  // Best-effort: fetch and display provisioned shells for this account.
608
- // Account/identity endpoints live on the auth service, NOT agent-proxy.
615
+ // Account/identity endpoints use the auth base URL, not the API base URL.
609
616
  try {
610
617
  const authBase = getActiveAuthBase(auth);
611
618
  const shellsRes = await fetch(`${authBase}/v1/account/shells`, {
@@ -1069,6 +1076,137 @@ program
1069
1076
  }
1070
1077
  });
1071
1078
  // ----------------------------------------------------------------
1079
+ // duct promote --from <source> --to <target>
1080
+ // Copies the live manifest of the source shell to the target shell,
1081
+ // implementing the dev → staging → production promotion workflow.
1082
+ // ----------------------------------------------------------------
1083
+ program
1084
+ .command("promote")
1085
+ .description("Promote the live manifest of one shell to another (e.g. dev → prod)")
1086
+ .requiredOption("--from <shellId>", "Source shell ID to promote from")
1087
+ .requiredOption("--to <shellId>", "Target shell ID to promote to")
1088
+ .option("--yes", "Skip confirmation prompt", false)
1089
+ .action(async (opts) => {
1090
+ const spinner = ora("Authenticating…").start();
1091
+ try {
1092
+ // Load API key
1093
+ let apiKey = process.env["DUCT_API_KEY"];
1094
+ if (!apiKey) {
1095
+ const auth = await readAuth();
1096
+ apiKey = auth?.token;
1097
+ }
1098
+ if (!apiKey) {
1099
+ spinner.fail("Not logged in");
1100
+ console.log(chalk.yellow("\nRun `npx duct login` first.\n"));
1101
+ process.exit(1);
1102
+ }
1103
+ const auth = await readAuth();
1104
+ const manifestBases = getManifestApiBases(auth);
1105
+ // ── Step 1: Fetch source manifest ─────────────────────────
1106
+ spinner.text = `Fetching manifest from ${chalk.cyan(opts.from)}…`;
1107
+ let sourceManifest = null;
1108
+ for (const base of manifestBases) {
1109
+ const res = await fetch(`${base}/v1/shells/${opts.from}/manifest`, {
1110
+ method: "GET",
1111
+ headers: { Authorization: `Bearer ${apiKey}` },
1112
+ });
1113
+ if (res.ok) {
1114
+ const data = (await res.json());
1115
+ sourceManifest = (data.manifest ?? null);
1116
+ if (sourceManifest)
1117
+ break;
1118
+ }
1119
+ if (res.status === 404)
1120
+ continue;
1121
+ const body = await res.text();
1122
+ spinner.fail(`Failed to fetch source manifest`);
1123
+ console.error(chalk.red(`\n ${res.status} at ${base}: ${body}\n`));
1124
+ process.exit(1);
1125
+ }
1126
+ if (!sourceManifest) {
1127
+ spinner.fail(`Shell '${opts.from}' not found or has no manifest`);
1128
+ process.exit(1);
1129
+ }
1130
+ const actionCount = Array.isArray(sourceManifest["actions"])
1131
+ ? sourceManifest["actions"].length
1132
+ : 0;
1133
+ spinner.succeed(`Fetched manifest from ${chalk.cyan(opts.from)} (${actionCount} action${actionCount === 1 ? "" : "s"})`);
1134
+ // ── Step 2: Confirmation ───────────────────────────────────
1135
+ console.log(chalk.dim(`\n Promoting: ${chalk.cyan(opts.from)} → ${chalk.cyan(opts.to)}\n`));
1136
+ if (!opts.yes) {
1137
+ const { confirm } = await inquirer.prompt([
1138
+ {
1139
+ type: "confirm",
1140
+ name: "confirm",
1141
+ message: chalk.yellow(`Push the ${chalk.bold(opts.from)} manifest (${actionCount} actions) to ${chalk.bold(opts.to)}?`),
1142
+ default: false,
1143
+ },
1144
+ ]);
1145
+ if (!confirm) {
1146
+ console.log(chalk.gray("\nPromotion cancelled.\n"));
1147
+ process.exit(0);
1148
+ }
1149
+ }
1150
+ // ── Step 3: Push to target ─────────────────────────────────
1151
+ const pushSpinner = ora(`Pushing to ${chalk.cyan(opts.to)}…`).start();
1152
+ // Rewrite shellId in the manifest to match the target
1153
+ const promotedManifest = {
1154
+ ...sourceManifest,
1155
+ shellId: opts.to,
1156
+ };
1157
+ let pushed = false;
1158
+ let pushError = "";
1159
+ let pushHash = "";
1160
+ let pushChecksum = "";
1161
+ for (const base of manifestBases) {
1162
+ const res = await fetch(`${base}/v1/shells/${opts.to}/manifest`, {
1163
+ method: "PUT",
1164
+ headers: {
1165
+ "Content-Type": "application/json",
1166
+ Authorization: `Bearer ${apiKey}`,
1167
+ },
1168
+ body: JSON.stringify({ config: promotedManifest }),
1169
+ });
1170
+ if (res.ok) {
1171
+ const data = (await res.json());
1172
+ pushed = true;
1173
+ pushHash = data.push_hash ?? "";
1174
+ pushChecksum = (data.config_checksum ?? "").slice(0, 7);
1175
+ break;
1176
+ }
1177
+ const body = await res.text();
1178
+ pushError = `${res.status} at ${base}: ${body}`;
1179
+ if (res.status === 404)
1180
+ continue;
1181
+ break;
1182
+ }
1183
+ if (!pushed) {
1184
+ pushSpinner.fail(`Promote failed`);
1185
+ console.error(chalk.red(`\n${pushError || "No manifest API responded"}\n`));
1186
+ process.exit(1);
1187
+ }
1188
+ pushSpinner.succeed(`Manifest pushed to ${chalk.cyan(opts.to)}`);
1189
+ console.log(chalk.green("\n ◆ Promotion complete\n"));
1190
+ if (pushHash)
1191
+ console.log(chalk.dim(` Hash: ${chalk.cyan(pushHash)}`));
1192
+ if (pushChecksum)
1193
+ console.log(chalk.dim(` Checksum: ${pushChecksum}`));
1194
+ console.log(chalk.dim(`\n Tip: Run \`npx duct scan --shell-id ${opts.to}\` to verify the promoted shell.\n`));
1195
+ // Persist promoted manifest locally as snapshot so --update diffs correctly
1196
+ try {
1197
+ const snapshotPath = path.resolve(process.cwd(), ".duct-manifest.json");
1198
+ await fs.writeFile(snapshotPath, JSON.stringify(promotedManifest, null, 2) + "\n", "utf-8");
1199
+ }
1200
+ catch { /* non-fatal — snapshot is a local convenience */ }
1201
+ }
1202
+ catch (err) {
1203
+ spinner.fail("Promotion failed");
1204
+ const message = err instanceof Error ? err.message : String(err);
1205
+ console.error(chalk.red(`\nError: ${message}\n`));
1206
+ process.exit(1);
1207
+ }
1208
+ });
1209
+ // ----------------------------------------------------------------
1072
1210
  // Error handling
1073
1211
  // ----------------------------------------------------------------
1074
1212
  program.exitOverride();
package/dist/cli/init.js CHANGED
@@ -42,7 +42,7 @@ async function loadAuth() {
42
42
  * Fetch the company's provisioned shells from the Duct auth service.
43
43
  *
44
44
  * Account/identity endpoints live on the auth service (port 3001 locally,
45
- * auth.<host> in prod), NOT on the agent-proxy. Calling the wrong service
45
+ * auth.<host> in prod), NOT the API host. Calling the wrong base URL
46
46
  * was the root cause of a "No shells provisioned" false negative bug.
47
47
  */
48
48
  async function fetchAccountShells(apiKey, authBase) {
@@ -585,10 +585,9 @@ export async function runInit(opts = {}) {
585
585
  }
586
586
  console.log(chalk.gray(` Authenticated as ${auth.email} (${auth.slug})\n`));
587
587
  // Use saved auth endpoints (or production defaults).
588
- // Account/identity endpoints live on the auth service, not agent-proxy.
588
+ // Account/identity endpoints use the auth base URL.
589
589
  const ductAuthBase = getActiveAuthBase(auth);
590
590
  // Fetch company's provisioned shells from the auth service.
591
- // (Account/identity endpoints live on auth, not on agent-proxy.)
592
591
  let accountShells;
593
592
  try {
594
593
  accountShells = await fetchAccountShells(auth.token, ductAuthBase);