@duct-sdk/sdk 0.5.3 → 0.5.9

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 CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog — @duct-sdk/sdk
2
2
 
3
+ ## [0.5.9] — 2026-07-18
4
+
5
+ ### Added
6
+ - **SDK-01 profile discovery** — `duct profile` commands (`show`, `list`, `use`, `init`) and auto-load from `~/.duct/profile.json`. Built-in `local` and `hosted` presets map service URLs; `DUCT_PROFILE` env still wins. Localhost guard respects `profile=local`.
7
+ - **Profile resolution tests** — `profile.test.ts` covers file load, env precedence, and protected shell keys.
8
+ - **Consumer-safe contracts packaging** — release tarballs declare the contracts semver and bundle the matching runtime schemas; publish smoke installs the packed SDK in a clean project.
9
+
10
+ ## [0.5.8] — 2026-07-18
11
+
12
+ ### Added
13
+ - **CLI diagnostics** — `duct whoami`, `duct logout`, and `duct env --redact` for account and endpoint inspection with secret redaction.
14
+ - **Hosted localhost guard** — `init`, `login`, `push`, and `checkup` fail in hosted mode when service URLs resolve to localhost unless `DUCT_PROFILE=local` or `DUCT_ALLOW_LOCALHOST=true`.
15
+
16
+ ## [0.5.7] — 2026-07-18
17
+
18
+ ### Added
19
+ - **READINESS-01 (partial)** — shared `readiness-checks` schema (Zod) plus `duct checkup --json` machine-readable report (env signals, auth/API/shell/dashboard health, docs URL). Dashboard go-live section reuses the same check definitions.
20
+
21
+ ## [0.5.6] — 2026-07-18
22
+
23
+ ### Fixed
24
+ - **Config schema parity** — `DuctConfigSchema` now accepts documented manifest fields that were previously stripped by Zod parse: action `inputSchema`, `dependsOn`, semantic metadata (`semanticType`, `outputSchema`, `paramMappings`, `navigatesTo`), `searchHint`/`alwaysInclude`/`interruptBehavior`, route `searchAction`, `dataModel`, and widget loop limits (`compactionTurns`, `maxToolIterations`, `maxPlanSteps`).
25
+
26
+ ## [0.5.5] — 2026-07-18
27
+
28
+ ### Fixed
29
+ - **CLI ESM crash** — Replaced `require()` calls in the CLI entry point with ESM `import`/`readFileSync`/`existsSync` so `npx @duct-sdk/sdk --help` works from the published tarball (`"type": "module"`).
30
+ - **`.env` precedence** — `.env.local` now correctly overrides `.env` for the same key; shell/process environment still wins over both.
31
+
32
+ ## [0.5.4] — 2026-07-17
33
+
34
+ ### Added
35
+ - **Host panel close (loading)** — `DuctShell` renders a close control on the panel chrome until the iframe posts `DUCT_READY`, so users can dismiss the panel while the shell is still connecting. After the shell is live, close stays inside the embedded shell UI (`DUCT_CLOSE`).
36
+
3
37
  ## [0.5.3] — 2026-07-17
4
38
 
5
39
  ### Security
package/README.md CHANGED
@@ -1,13 +1,17 @@
1
- <p align="center">
2
- <img src="./assets/duct-wordmark.svg" alt="DUCT" width="420" />
3
- </p>
1
+ ```
2
+ ██████╗ ██╗ ██╗ ╔██████ ████████╗
3
+ ██╔══██╗ ██║ ██║ ╚════╗██ ╚══██╔══╝
4
+ ██║ ██║ ██║ ██║ ║██ ██║
5
+ ██║ ██║ ██║ ██║ ║██ ██║
6
+ ██████╔╝ ╚██████╔╝ ╔██████╝ ██║
7
+ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝
8
+ ```
4
9
 
5
10
  # @duct-sdk/sdk
6
11
 
7
12
  **Let agents use your product safely.**
8
13
 
9
- [npm version](https://www.npmjs.com/package/@duct-sdk/sdk)
10
- [Node](https://www.npmjs.com/package/@duct-sdk/sdk)
14
+ [npm version](https://www.npmjs.com/package/@duct-sdk/sdk) | [Node 20+](https://nodejs.org/)
11
15
 
12
16
  The official Duct SDK and CLI. Scan your codebase, declare a manifest, push it to Duct, and embed a permissioned chat shell — so humans and AI agents call your **existing APIs** through one audited surface.
13
17
 
@@ -16,33 +20,29 @@ The official Duct SDK and CLI. Scan your codebase, declare a manifest, push it t
16
20
  | ------------- | ----------------------------------------------------------------------------------------------- |
17
21
  | **Humans** | Embedded chat shell, structured results, signed deeplink handoff into your app |
18
22
  | **Agents** | Permissioned API access from the same manifest — no scraping or screen automation |
19
- | **Operators** | Shell credentials, action tiers, and usage from the [Duct dashboard](https://ductai.vercel.app) |
23
+ | **Operators** | Shell credentials, action tiers, and usage from the configured Duct dashboard |
20
24
 
21
25
 
22
26
  ---
23
27
 
24
-
25
-
26
28
  ## Documentation
27
29
 
28
30
 
29
- | Resource | Description |
30
- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
31
- | [Developer docs](https://ductai.vercel.app/docs) | Quickstart, CLI, frameworks, agents, threat model |
32
- | [AI integration prompt](https://ductai.vercel.app/docs/integration-prompt) | Full `DUCT_CONFIG_PROMPT.md` — copy into Cursor, Claude Code, Codex, or any agentic IDE |
33
- | [TOKEN_SPEC.md](./TOKEN_SPEC.md) | Token prefixes, claims, TTLs, and cross-language verify snippets |
34
- | [CHANGELOG.md](./CHANGELOG.md) | Release notes |
31
+ | Resource | Description |
32
+ | --- | --- |
33
+ | Developer docs (`SITE_URL/docs`) | Quickstart, CLI, frameworks, agents, threat model |
34
+ | AI integration prompt (`SITE_URL/docs/integration-prompt`) | Full `DUCT_CONFIG_PROMPT.md` — copy into Cursor, Claude Code, Codex, or any agentic IDE |
35
+ | [TOKEN_SPEC.md](./TOKEN_SPEC.md) | Token prefixes, claims, TTLs, and cross-language verify snippets |
36
+ | Changelog (`SITE_URL/changelog`) | Platform release notes (includes SDK) |
35
37
 
36
38
 
37
39
  ---
38
40
 
39
-
40
-
41
41
  ## AI-assisted integration
42
42
 
43
43
  Duct ships a single integration prompt (`DUCT_CONFIG_PROMPT.md`) for greenfield setup or auditing an existing `duct.config.ts`. Paste it into your coding assistant with the product repo open; the agent generates or reviews manifest fields, the four wiring points, env vars, and a ship checklist.
44
44
 
45
- **Get the prompt:** [ductai.vercel.app/docs/integration-prompt](https://ductai.vercel.app/docs/integration-prompt) — expandable, copy-ready, with URLs resolved for your environment.
45
+ **Get the prompt:** open `SITE_URL/docs/integration-prompt` on your configured deployment. The page is expandable and copy-ready, with platform URLs resolved for that environment.
46
46
 
47
47
  Typical flow:
48
48
 
@@ -52,8 +52,6 @@ Typical flow:
52
52
 
53
53
  ---
54
54
 
55
-
56
-
57
55
  ## Install
58
56
 
59
57
  ```bash
@@ -69,8 +67,6 @@ Global CLI (optional): `npm i -g @duct-sdk/sdk` → `duct <command>`.
69
67
 
70
68
  ---
71
69
 
72
-
73
-
74
70
  ## Quickstart
75
71
 
76
72
  **1. Create a shell** in the Duct dashboard and copy your API key.
@@ -125,8 +121,6 @@ export default function RootLayout({ children }) {
125
121
  }
126
122
  ```
127
123
 
128
-
129
-
130
124
  ### Four wiring points
131
125
 
132
126
  Duct does not replace your API. You add four integration points in **your** codebase:
@@ -144,8 +138,6 @@ Duct does not replace your API. You add four integration points in **your** code
144
138
 
145
139
  ---
146
140
 
147
-
148
-
149
141
  ## Import guide
150
142
 
151
143
  Use the **subpath** that matches your runtime. The root export pulls React adapters and will crash plain Node servers.
@@ -169,8 +161,6 @@ import { generateDuctToken, verifyDuctToken } from '@duct-sdk/sdk/server';
169
161
 
170
162
  ---
171
163
 
172
-
173
-
174
164
  ## CLI
175
165
 
176
166
 
@@ -190,8 +180,6 @@ import { generateDuctToken, verifyDuctToken } from '@duct-sdk/sdk/server';
190
180
 
191
181
  ---
192
182
 
193
-
194
-
195
183
  ## Frameworks
196
184
 
197
185
 
@@ -205,8 +193,6 @@ import { generateDuctToken, verifyDuctToken } from '@duct-sdk/sdk/server';
205
193
  | Express / Fastify / Node | `@duct-sdk/sdk/server` | — (server only) |
206
194
 
207
195
 
208
-
209
-
210
196
  ### Vite + Express
211
197
 
212
198
  ```ts
@@ -229,8 +215,6 @@ Keep secrets in server `.env` only (`DUCT_SECRET_KEY`, `DUCT_SHELL_ID`). Client
229
215
 
230
216
  ---
231
217
 
232
-
233
-
234
218
  ## Deeplinks & replay protection
235
219
 
236
220
  Declare deeplinks only for routes you have inventoried in `routes[]`. The receiver must verify signed tokens server-side — never trust raw query params.
@@ -258,29 +242,23 @@ Details: [TOKEN_SPEC.md](./TOKEN_SPEC.md).
258
242
 
259
243
  ---
260
244
 
261
-
262
-
263
245
  ## Webhooks
264
246
 
265
247
  Webhook URLs and signing secrets are configured in the **dashboard → Shell → Settings → Webhooks**, not in `duct.config.ts`. Your endpoint verifies `X-Duct-Signature` (HMAC-SHA256). Webhooks are optional for chat and actions.
266
248
 
267
249
  ---
268
250
 
269
-
270
-
271
251
  ## Security
272
252
 
273
253
  - Keep `DUCT_SECRET_KEY` server-side — never in `NEXT_PUBLIC_*`, `VITE_*`, or client bundles
274
254
  - Default mutations to `agentAccessible: false` and `sideEffects: true` where appropriate
275
255
  - Rotate keys in the dashboard if credentials are exposed
276
- - Review agent-accessible actions before production — use the [integration prompt](https://ductai.vercel.app/docs/integration-prompt) audit checklist
256
+ - Review agent-accessible actions before production — use the integration prompt at `SITE_URL/docs/integration-prompt`
277
257
 
278
258
  ---
279
259
 
280
-
281
-
282
260
  ## Support
283
261
 
284
- - Docs: [ductai.vercel.app/docs](https://ductai.vercel.app/docs)
262
+ - Docs: `SITE_URL/docs` on your configured deployment
285
263
  - npm: [@duct-sdk/sdk](https://www.npmjs.com/package/@duct-sdk/sdk)
286
264
 
@@ -1,16 +1,16 @@
1
1
  <svg xmlns="http://www.w3.org/2000/svg" role="img" aria-label="DUCT" viewBox="0 0 380 98">
2
2
  <text
3
- fill="#B84A22"
3
+ fill="#E8622A"
4
4
  font-family="ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"
5
5
  font-size="13"
6
6
  font-weight="700"
7
7
  xml:space="preserve"
8
8
  >
9
- <tspan x="0" y="14">██████╗ ██╗ ██╗ ╔██████ ████████╗</tspan>
10
- <tspan x="0" dy="14">██╔══██╗ ██║ ██║ ╚════╗██ ╚══██╔══╝</tspan>
11
- <tspan x="0" dy="14">██║ ██║ ██║ ██║ ║██ ██║</tspan>
12
- <tspan x="0" dy="14">██║ ██║ ██║ ██║ ║██ ██║</tspan>
13
- <tspan x="0" dy="14">██████╔╝ ╚██████╔╝ ╔██████╝ ██║</tspan>
14
- <tspan x="0" dy="14">╚═════╝ ╚═════╝ ╚═════╝ ╚═╝</tspan>
9
+ <tspan x="0" y="14">??????? ??? ??? ??????? ?????????</tspan>
10
+ <tspan x="0" dy="14">???????? ??? ??? ???????? ?????????</tspan>
11
+ <tspan x="0" dy="14">??? ??? ??? ??? ??? ???</tspan>
12
+ <tspan x="0" dy="14">??? ??? ??? ??? ??? ???</tspan>
13
+ <tspan x="0" dy="14">???????? ????????? ???????? ???</tspan>
14
+ <tspan x="0" dy="14">??????? ??????? ??????? ???</tspan>
15
15
  </text>
16
16
  </svg>
@@ -116,6 +116,34 @@ function ShellDragHandle({ onPointerDown, isDragging, isDark, label = "Drag to m
116
116
  : "0 8px 24px rgba(12,11,9,0.12)",
117
117
  }, children: label }))] }));
118
118
  }
119
+ /** Close control on the host panel chrome — visible until the iframe posts DUCT_READY. */
120
+ function ShellPanelCloseButton({ onClick, isDark, }) {
121
+ const [hovered, setHovered] = useState(false);
122
+ const color = isDark ? (hovered ? "#C4BFB8" : "#9C9790") : (hovered ? "#524E48" : "#635F59");
123
+ const bg = hovered ? (isDark ? "rgba(255,255,255,0.06)" : "rgba(12,11,9,0.06)") : "transparent";
124
+ return (_jsx("button", { type: "button", "aria-label": "Close shell", onClick: onClick, onMouseEnter: () => setHovered(true), onMouseLeave: () => setHovered(false), style: {
125
+ position: "absolute",
126
+ top: 8,
127
+ right: 8,
128
+ zIndex: 3,
129
+ width: 28,
130
+ height: 28,
131
+ padding: 0,
132
+ margin: 0,
133
+ border: "none",
134
+ borderRadius: 8,
135
+ cursor: "pointer",
136
+ display: "flex",
137
+ alignItems: "center",
138
+ justifyContent: "center",
139
+ fontSize: 18,
140
+ lineHeight: 1,
141
+ color,
142
+ background: bg,
143
+ boxShadow: "none",
144
+ transition: "color 150ms ease, background-color 150ms ease",
145
+ }, children: "\u00D7" }));
146
+ }
119
147
  function shellLayoutStorageKey(shellId) {
120
148
  return `duct-shell-pos:${shellId}`;
121
149
  }
@@ -291,6 +319,10 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
291
319
  // userContext is delivered via postMessage on DUCT_READY — embedding it in the
292
320
  // URL would reload the iframe whenever the host page context changes.
293
321
  const shellUrl = useMemo(() => buildShellUrl(shellHost, shellId), [shellHost, shellId]);
322
+ // Reset liveness when the embedded shell identity or URL changes.
323
+ useEffect(() => {
324
+ setIsReady(false);
325
+ }, [shellId, shellUrl]);
294
326
  const shellOrigin = (() => {
295
327
  try {
296
328
  return new URL(shellHost).origin;
@@ -778,7 +810,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
778
810
  e.currentTarget.style.transform = "scale(1.07)";
779
811
  }, onMouseLeave: (e) => {
780
812
  e.currentTarget.style.transform = "scale(1)";
781
- }, children: bubbleIcon })), _jsxs("div", { ref: panelRef, style: panelStyle, "data-duct-shell": shellId, children: [draggable && panelOpen && (_jsx(ShellDragHandle, { onPointerDown: onPanelPointerDown, isDragging: isPanelDragging, isDark: isDarkChrome, label: "Drag to move" })), _jsx("iframe", { ref: iframeRef, src: shellUrl, title: "Duct Shell", sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", allow: "clipboard-write", referrerPolicy: "no-referrer-when-downgrade", style: {
813
+ }, children: bubbleIcon })), _jsxs("div", { ref: panelRef, style: panelStyle, "data-duct-shell": shellId, children: [draggable && panelOpen && (_jsx(ShellDragHandle, { onPointerDown: onPanelPointerDown, isDragging: isPanelDragging, isDark: isDarkChrome, label: "Drag to move" })), panelOpen && !isReady && (_jsx(ShellPanelCloseButton, { onClick: closePanel, isDark: isDarkChrome })), _jsx("iframe", { ref: iframeRef, src: shellUrl, title: "Duct Shell", sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", allow: "clipboard-write", referrerPolicy: "no-referrer-when-downgrade", style: {
782
814
  width: "100%",
783
815
  height: "100%",
784
816
  border: "none",
package/dist/cli/index.js CHANGED
@@ -12,25 +12,31 @@ import { detectFramework } from "./detectors/framework.js";
12
12
  import { detectAuth } from "./detectors/auth.js";
13
13
  import { getGeneratedOutputPaths } from "./output-paths.js";
14
14
  import { integrationAuditFailed, printIntegrationAuditIssues, runIntegrationAudit, } from "./processors/integration-audit.js";
15
- import { getCandidateAuthBases, getConfiguredDashboard, getManifestApiBases, getActiveApiBase, getActiveAuthBase, getAuthUrl, getShellRuntimeUrl, } from "../core/endpoints.js";
15
+ import { getCandidateAuthBases, getConfiguredDashboard, getManifestApiBases, getActiveApiBase, getActiveAuthBase, getAuthUrl, getShellRuntimeUrl, getDocsUrl, } from "../core/endpoints.js";
16
+ import { assertHostedEndpointsNotLocalhost } from "../core/endpoint-guard.js";
17
+ import { formatEnvDiagnostics } from "../core/env-diagnostics.js";
18
+ import { buildCliReadinessReport } from "../core/readiness-checks.js";
16
19
  import * as fs from "fs/promises";
17
20
  import * as path from "path";
18
21
  import * as os from "os";
19
22
  import { fileURLToPath } from "node:url";
20
- import { readFileSync } from "fs";
23
+ import { readFileSync, existsSync } from "fs";
21
24
  import { DuctConfigSchema, crossValidateDuctConfig } from "../core/config.js";
22
25
  import { runAgentSafetyChecks } from "./agents/reviewer-agent.js";
23
26
  import { ConfigRuntimeReferenceError, loadDuctConfig, } from "./config-loader.js";
24
27
  import { computeManifestPrivilegeDiff, fetchLiveManifestConfig, formatManifestPrivilegeDiff, } from "./manifest-diff.js";
28
+ import { applyActiveProfileEnvSync, ensureProfileExists, getDuctProfileFilePath, listProfileNames, readProfileFileSync, resolveActiveProfileName, resolveProfileUrls, setActiveProfileSync, } from "../core/profile.js";
25
29
  // ----------------------------------------------------------------
26
30
  // Load all standard .env files in dotenv priority order
27
- // Priority (last-loaded wins when key already set by earlier file):
31
+ // Priority: shell env > later files > earlier files
28
32
  // .env < .env.local < .env.<NODE_ENV> < .env.<NODE_ENV>.local
29
- // We do NOT overwrite keys already in process.env (shell env takes priority).
33
+ // Keys from the shell environment are never overwritten by file loads.
30
34
  // ----------------------------------------------------------------
35
+ // Snapshot keys present before any .env file is read (shell/process env wins).
36
+ const shellEnvKeys = new Set(Object.keys(process.env));
31
37
  function loadEnvFileSync(envPath) {
32
38
  try {
33
- const content = require("fs").readFileSync(envPath, "utf-8");
39
+ const content = readFileSync(envPath, "utf-8");
34
40
  for (const line of content.split("\n")) {
35
41
  const trimmed = line.trim();
36
42
  if (!trimmed || trimmed.startsWith("#"))
@@ -42,9 +48,9 @@ function loadEnvFileSync(envPath) {
42
48
  const raw = trimmed.substring(eqIndex + 1).trim();
43
49
  // Strip surrounding quotes if present
44
50
  const value = /^["'].*["']$/.test(raw) ? raw.slice(1, -1) : raw;
45
- // Later files override earlier ones (dotenv priority: .env.local beats .env)
46
- // BUT we never override keys already set in the actual shell/process environment
47
- if (key && !(key in process.env)) {
51
+ // Later files override earlier ones (.env.local beats .env), but shell env
52
+ // keys captured at startup always win.
53
+ if (key && !shellEnvKeys.has(key)) {
48
54
  process.env[key] = value;
49
55
  }
50
56
  }
@@ -62,13 +68,13 @@ function resolveEnvSearchDirs(startDir) {
62
68
  let dir = startDir;
63
69
  for (let i = 0; i < 10; i++) {
64
70
  dirs.unshift(dir); // prepend so we get root→cwd order
65
- const isDuctRoot = require("fs").existsSync(require("path").join(dir, "duct.config.ts")) ||
66
- require("fs").existsSync(require("path").join(dir, "duct.config.js")) ||
67
- require("fs").existsSync(require("path").join(dir, ".git"));
71
+ const isDuctRoot = existsSync(path.join(dir, "duct.config.ts")) ||
72
+ existsSync(path.join(dir, "duct.config.js")) ||
73
+ existsSync(path.join(dir, ".git"));
68
74
  if (isDuctRoot) {
69
75
  break;
70
76
  }
71
- const parent = require("path").dirname(dir);
77
+ const parent = path.dirname(dir);
72
78
  if (parent === dir)
73
79
  break; // filesystem root
74
80
  dir = parent;
@@ -96,6 +102,9 @@ function loadAllEnvFilesSync() {
96
102
  }
97
103
  // Load all .env files synchronously at startup (before any commands run)
98
104
  loadAllEnvFilesSync();
105
+ // Apply ~/.duct/profile.json (named profiles: local, hosted, custom) before commands run.
106
+ // Shell env keys captured at startup always win over profile defaults.
107
+ applyActiveProfileEnvSync({ protectedKeys: shellEnvKeys });
99
108
  // ----------------------------------------------------------------
100
109
  // Auth helpers — ~/.duct/auth.json
101
110
  // ----------------------------------------------------------------
@@ -160,8 +169,9 @@ const VERSION = JSON.parse(readFileSync(pkgPath, "utf-8")).version;
160
169
  // ----------------------------------------------------------------
161
170
  const program = new Command();
162
171
  program
163
- .name("duct")
172
+ .name("@duct-sdk/sdk")
164
173
  .description("SDK for the Duct shell — Shell infrastructure for humans and agents.")
174
+ .addHelpText("after", "\nRun via: npx @duct-sdk/sdk <command> (bin alias: duct)\n")
165
175
  .version(VERSION);
166
176
  // ----------------------------------------------------------------
167
177
  // duct init
@@ -182,6 +192,7 @@ program
182
192
  .option("--industry <category>", "Product industry for better modality routing (e.g., fintech, ecommerce, saas, ai)")
183
193
  .action(async (opts) => {
184
194
  try {
195
+ assertHostedEndpointsNotLocalhost();
185
196
  await runInit({
186
197
  cwd: process.cwd(),
187
198
  dryRun: opts.dryRun,
@@ -282,6 +293,8 @@ program
282
293
  .action(async (opts) => {
283
294
  const spinner = ora("Reading config...").start();
284
295
  try {
296
+ const authProfile = await readAuth();
297
+ assertHostedEndpointsNotLocalhost(authProfile);
285
298
  const cwd = process.cwd();
286
299
  const configPath = path.resolve(cwd, opts.config);
287
300
  // Check config file exists
@@ -375,7 +388,6 @@ program
375
388
  const shellId = validated.shellId;
376
389
  // ── Live manifest diff (privilege deltas) ───────────────────────────────
377
390
  let apiKey = process.env["DUCT_API_KEY"];
378
- const authProfile = await readAuth();
379
391
  if (!apiKey) {
380
392
  apiKey = authProfile?.token;
381
393
  }
@@ -532,6 +544,9 @@ program
532
544
  const dashboardHint = getConfiguredDashboard(existingAuth);
533
545
  const registerHint = `${dashboardHint}/register`;
534
546
  const attemptedBases = [];
547
+ if (!opts.logout) {
548
+ assertHostedEndpointsNotLocalhost(existingAuth);
549
+ }
535
550
  // duct login --logout
536
551
  if (opts.logout) {
537
552
  await clearAuth();
@@ -640,8 +655,22 @@ program
640
655
  program
641
656
  .command("checkup")
642
657
  .description("Check your environment config and verify connectivity to all Duct services")
643
- .action(async () => {
658
+ .option("--json", "Output machine-readable readiness report as JSON", false)
659
+ .action(async (opts) => {
644
660
  const auth = await readAuth();
661
+ try {
662
+ assertHostedEndpointsNotLocalhost(auth);
663
+ }
664
+ catch (err) {
665
+ const message = err instanceof Error ? err.message : String(err);
666
+ if (opts.json) {
667
+ console.log(JSON.stringify({ ok: false, error: message }, null, 2));
668
+ }
669
+ else {
670
+ console.error(chalk.red(`\n${message}\n`));
671
+ }
672
+ process.exit(1);
673
+ }
645
674
  const authUrl = getAuthUrl();
646
675
  const apiBase = getActiveApiBase(auth);
647
676
  const shellUrl = getShellRuntimeUrl();
@@ -649,6 +678,29 @@ program
649
678
  const shellId = process.env["DUCT_SHELL_ID"];
650
679
  const secretKey = process.env["DUCT_SECRET_KEY"];
651
680
  const ductUrl = process.env["DUCT_URL"] ?? "";
681
+ const docsUrl = getDocsUrl();
682
+ const report = await buildCliReadinessReport({
683
+ env: {
684
+ ductUrl: ductUrl || undefined,
685
+ shellId,
686
+ secretKey,
687
+ authEmail: auth?.email,
688
+ authSlug: auth?.slug,
689
+ },
690
+ endpoints: {
691
+ authHealthUrl: `${authUrl}/health`,
692
+ apiHealthUrl: `${apiBase}/health`,
693
+ shellHealthUrl: `${shellUrl}/api/health`,
694
+ dashboardHealthUrl: `${dashUrl}/api/health`,
695
+ docsUrl,
696
+ },
697
+ });
698
+ if (opts.json) {
699
+ console.log(JSON.stringify(report, null, 2));
700
+ if (!report.ok)
701
+ process.exit(1);
702
+ return;
703
+ }
652
704
  console.log(chalk.bold(`\n ◆ Duct · checkup\n`));
653
705
  // — Env summary —
654
706
  console.log(chalk.bold(" Environment"));
@@ -656,39 +708,30 @@ program
656
708
  console.log(chalk.gray(` DUCT_SHELL_ID : ${shellId || chalk.yellow("(not set)")}`));
657
709
  console.log(chalk.gray(` DUCT_SECRET_KEY : ${secretKey ? "sk_..." + secretKey.slice(-4) : chalk.yellow("(not set)")}`));
658
710
  console.log(chalk.gray(` Auth profile : ${auth ? `${auth.email} (${auth.slug})` : chalk.yellow("(not logged in)")}`));
711
+ console.log(chalk.gray(` Docs URL : ${docsUrl}`));
659
712
  console.log();
660
713
  // — Service connectivity —
661
714
  console.log(chalk.bold(" Services"));
662
- const checks = [
663
- { label: "Auth", url: `${authUrl}/health` },
664
- { label: "Agent Proxy", url: `${apiBase}/health` },
665
- { label: "Shell Runtime", url: `${shellUrl}/api/health` },
666
- { label: "Dashboard", url: `${dashUrl}/api/health` },
667
- ];
668
- for (const { label, url } of checks) {
669
- try {
670
- const controller = new AbortController();
671
- const timer = setTimeout(() => controller.abort(), 3000);
672
- const res = await fetch(url, { signal: controller.signal });
673
- clearTimeout(timer);
674
- if (res.ok) {
675
- console.log(` ${chalk.green("✓")} ${label.padEnd(16)} ${chalk.gray(url)}`);
676
- }
677
- else {
678
- console.log(` ${chalk.red("✗")} ${label.padEnd(16)} ${chalk.red(`${res.status}`)} ${chalk.gray(url)}`);
679
- }
715
+ const serviceChecks = report.checks.filter((c) => ["auth_reachable", "api_reachable", "shell_reachable", "dashboard_reachable"].includes(c.id));
716
+ for (const check of serviceChecks) {
717
+ const url = check.url ?? "";
718
+ if (check.status === "pass") {
719
+ console.log(` ${chalk.green("✓")} ${check.label.padEnd(16)} ${chalk.gray(url)}`);
680
720
  }
681
- catch {
682
- console.log(` ${chalk.red("✗")} ${label.padEnd(16)} ${chalk.red("unreachable")} ${chalk.gray(url)}`);
721
+ else {
722
+ console.log(` ${chalk.red("✗")} ${check.label.padEnd(16)} ${chalk.red(check.message ?? "failed")} ${chalk.gray(url)}`);
683
723
  }
684
724
  }
685
725
  console.log();
686
726
  if (!auth) {
687
727
  console.log(chalk.yellow(" ⚠ Not logged in — run: npx duct login\n"));
688
728
  }
689
- else {
729
+ else if (report.ok) {
690
730
  console.log(chalk.green(" ✓ Service connectivity checks complete\n"));
691
731
  }
732
+ else {
733
+ console.log(chalk.red(" ✗ One or more service checks failed\n"));
734
+ }
692
735
  const cwd = process.cwd();
693
736
  const configPath = path.resolve(cwd, "duct.config.ts");
694
737
  const hasConfig = await fs.access(configPath).then(() => true).catch(() => false);
@@ -727,6 +770,106 @@ program
727
770
  }
728
771
  });
729
772
  // ----------------------------------------------------------------
773
+ // duct profile — named platform URL profiles (~/.duct/profile.json)
774
+ // ----------------------------------------------------------------
775
+ const profileCmd = program
776
+ .command("profile")
777
+ .description("Manage named Duct platform profiles (local, hosted, custom)");
778
+ profileCmd
779
+ .command("show", { isDefault: true })
780
+ .description("Show the active profile and resolved service URLs")
781
+ .argument("[name]", "Profile name (default: active)")
782
+ .action((name) => {
783
+ const file = readProfileFileSync();
784
+ const active = resolveActiveProfileName(file);
785
+ const profileName = (name ?? active).trim();
786
+ const urls = resolveProfileUrls(profileName, file);
787
+ console.log(chalk.bold("\n ◆ Duct · profile\n"));
788
+ console.log(` active : ${active}`);
789
+ console.log(` showing : ${profileName}`);
790
+ console.log(` file : ${getDuctProfileFilePath()}`);
791
+ console.log();
792
+ console.log(chalk.bold(" URLs"));
793
+ for (const [key, value] of Object.entries(urls)) {
794
+ if (value)
795
+ console.log(` ${key.padEnd(14)} ${value}`);
796
+ }
797
+ if (Object.keys(urls).length === 0) {
798
+ console.log(chalk.gray(" (no overrides — set DUCT_URL or add profiles.local in profile.json)"));
799
+ }
800
+ console.log();
801
+ });
802
+ profileCmd
803
+ .command("list")
804
+ .description("List built-in and custom profile names")
805
+ .action(() => {
806
+ const file = readProfileFileSync();
807
+ const active = resolveActiveProfileName(file);
808
+ const names = listProfileNames(file);
809
+ console.log(chalk.bold("\n ◆ Duct · profile list\n"));
810
+ for (const name of names) {
811
+ const marker = name === active ? chalk.green(" (active)") : "";
812
+ console.log(` ${name}${marker}`);
813
+ }
814
+ console.log();
815
+ });
816
+ profileCmd
817
+ .command("use <name>")
818
+ .description("Set the active profile in ~/.duct/profile.json")
819
+ .action((name) => {
820
+ setActiveProfileSync(name.trim());
821
+ applyActiveProfileEnvSync({ protectedKeys: shellEnvKeys });
822
+ console.log(chalk.green(`\n✓ Active profile set to "${name.trim()}"\n`));
823
+ });
824
+ profileCmd
825
+ .command("init <name>")
826
+ .description("Create or update a custom profile with optional DUCT_URL")
827
+ .option("--duct-url <url>", "Platform base URL (DUCT_URL)")
828
+ .action((name, opts) => {
829
+ const profileName = name.trim();
830
+ const urls = opts.ductUrl ? { ductUrl: opts.ductUrl.trim() } : {};
831
+ ensureProfileExists(profileName, urls);
832
+ console.log(chalk.green(`\n✓ Profile "${profileName}" saved to ${getDuctProfileFilePath()}\n`));
833
+ });
834
+ // ----------------------------------------------------------------
835
+ // duct whoami / logout / env
836
+ // ----------------------------------------------------------------
837
+ program
838
+ .command("whoami")
839
+ .description("Show the logged-in Duct account from ~/.duct/auth.json")
840
+ .action(async () => {
841
+ const auth = await readAuth();
842
+ if (!auth) {
843
+ console.error(chalk.red("\nNot logged in. Run `npx duct login`.\n"));
844
+ process.exit(1);
845
+ }
846
+ console.log(chalk.bold("\n ◆ Duct · whoami\n"));
847
+ console.log(` email : ${auth.email}`);
848
+ console.log(` slug : ${auth.slug}`);
849
+ console.log(` company_id : ${auth.companyId || "(unknown)"}`);
850
+ console.log(` api_base : ${auth.apiBase ?? getActiveApiBase(auth)}`);
851
+ console.log(` dashboard : ${auth.dashboardUrl ?? getConfiguredDashboard(auth)}`);
852
+ console.log(` saved_at : ${auth.savedAt}`);
853
+ console.log();
854
+ });
855
+ program
856
+ .command("logout")
857
+ .description("Clear stored CLI credentials (~/.duct/auth.json)")
858
+ .action(async () => {
859
+ await clearAuth();
860
+ console.log(chalk.green("\n✓ Logged out — credentials cleared\n"));
861
+ });
862
+ program
863
+ .command("env")
864
+ .description("Print resolved Duct endpoints and tracked env vars")
865
+ .option("--redact", "Redact secret-like values", false)
866
+ .action(async (opts) => {
867
+ const auth = await readAuth();
868
+ console.log(chalk.bold("\n ◆ Duct · env\n"));
869
+ console.log(formatEnvDiagnostics(auth, { redact: Boolean(opts.redact) }));
870
+ console.log();
871
+ });
872
+ // ----------------------------------------------------------------
730
873
  // duct scan (diagnostic / drift detection)
731
874
  // ----------------------------------------------------------------
732
875
  program
@@ -0,0 +1 @@
1
+ export {};