@duct-sdk/sdk 0.5.4 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +10 -10
  3. package/dist/adapters/react/shell.d.ts +2 -2
  4. package/dist/adapters/react/shell.js +1 -2
  5. package/dist/cli/generators/config.test.js +3 -0
  6. package/dist/cli/index.js +216 -36
  7. package/dist/cli/prompts/review.js +14 -0
  8. package/dist/core/config-roundtrip.test.d.ts +1 -0
  9. package/dist/core/config-roundtrip.test.js +180 -0
  10. package/dist/core/config.d.ts +281 -25
  11. package/dist/core/config.js +51 -67
  12. package/dist/core/endpoint-guard.d.ts +27 -0
  13. package/dist/core/endpoint-guard.js +71 -0
  14. package/dist/core/endpoint-guard.test.d.ts +1 -0
  15. package/dist/core/endpoint-guard.test.js +57 -0
  16. package/dist/core/env-diagnostics.d.ts +13 -0
  17. package/dist/core/env-diagnostics.js +63 -0
  18. package/dist/core/env-diagnostics.test.d.ts +1 -0
  19. package/dist/core/env-diagnostics.test.js +31 -0
  20. package/dist/core/evidence-bundle.conformance.test.d.ts +1 -0
  21. package/dist/core/evidence-bundle.conformance.test.js +110 -0
  22. package/dist/core/evidence-bundle.d.ts +59 -0
  23. package/dist/core/evidence-bundle.js +68 -0
  24. package/dist/core/evidence-bundle.test.d.ts +1 -0
  25. package/dist/core/evidence-bundle.test.js +58 -0
  26. package/dist/core/profile.d.ts +44 -0
  27. package/dist/core/profile.js +128 -0
  28. package/dist/core/profile.test.d.ts +1 -0
  29. package/dist/core/profile.test.js +95 -0
  30. package/dist/core/readiness-checks.d.ts +131 -0
  31. package/dist/core/readiness-checks.js +162 -0
  32. package/dist/core/readiness-checks.test.d.ts +1 -0
  33. package/dist/core/readiness-checks.test.js +106 -0
  34. package/dist/core/receipt.d.ts +5 -1
  35. package/dist/core/types.d.ts +23 -0
  36. package/dist/core/types.js +3 -3
  37. package/dist/index.d.ts +4 -3
  38. package/dist/index.js +2 -1
  39. package/dist/server.d.ts +3 -2
  40. package/dist/server.js +2 -1
  41. package/package.json +94 -93
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # Changelog — @duct-sdk/sdk
2
2
 
3
+ ## [0.5.10] — 2026-07-19
4
+
5
+ ### Added
6
+ - **`duct verify-evidence`** — offline verification for `duct:audit-evidence:v1` bundles (receipt signatures, chain integrity, signed checkpoints); exported from `@duct-sdk/sdk` and `@duct-sdk/sdk/server`.
7
+ - **Intershell manifest validation** — `agentPermissions.allowedCallees` schema; `crossValidateDuctConfig` requires `webhooks.identityUrl` when `intershell_enabled` and protected actions coexist.
8
+
9
+ ### Improved
10
+ - **Readiness product URL probe** — `duct checkup` and shared readiness helpers now HTTP-probe `product.baseUrl` (with a Docker `host.docker.internal` fallback for loopback URLs) and optionally check the platform status page URL.
11
+
12
+ ### Changed
13
+ - **Shell panel defaults** — default `panelHeight` 640→680; preset heights +40px (`tall` 700, `square` 540, `large` 760) so trust footer does not shrink the chat area.
14
+ - **Launcher icon** — default closed-widget candidates prefer shell-origin Duct assets; removed host-relative `/duct-text-no-bg.png` first candidate that could show a host site's own file.
15
+
16
+ ## [0.5.9] — 2026-07-18
17
+
18
+ ### Added
19
+ - **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`.
20
+ - **Profile resolution tests** — `profile.test.ts` covers file load, env precedence, and protected shell keys.
21
+ - **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.
22
+
23
+ ## [0.5.8] — 2026-07-18
24
+
25
+ ### Added
26
+ - **CLI diagnostics** — `duct whoami`, `duct logout`, and `duct env --redact` for account and endpoint inspection with secret redaction.
27
+ - **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`.
28
+
29
+ ## [0.5.7] — 2026-07-18
30
+
31
+ ### Added
32
+ - **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.
33
+
34
+ ## [0.5.6] — 2026-07-18
35
+
36
+ ### Fixed
37
+ - **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`).
38
+
39
+ ## [0.5.5] — 2026-07-18
40
+
41
+ ### Fixed
42
+ - **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"`).
43
+ - **`.env` precedence** — `.env.local` now correctly overrides `.env` for the same key; shell/process environment still wins over both.
44
+
3
45
  ## [0.5.4] — 2026-07-17
4
46
 
5
47
  ### Added
package/README.md CHANGED
@@ -20,7 +20,7 @@ The official Duct SDK and CLI. Scan your codebase, declare a manifest, push it t
20
20
  | ------------- | ----------------------------------------------------------------------------------------------- |
21
21
  | **Humans** | Embedded chat shell, structured results, signed deeplink handoff into your app |
22
22
  | **Agents** | Permissioned API access from the same manifest — no scraping or screen automation |
23
- | **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 |
24
24
 
25
25
 
26
26
  ---
@@ -28,12 +28,12 @@ The official Duct SDK and CLI. Scan your codebase, declare a manifest, push it t
28
28
  ## Documentation
29
29
 
30
30
 
31
- | Resource | Description |
32
- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
33
- | [Developer docs](https://ductai.vercel.app/docs) | Quickstart, CLI, frameworks, agents, threat model |
34
- | [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 |
35
- | [TOKEN_SPEC.md](./TOKEN_SPEC.md) | Token prefixes, claims, TTLs, and cross-language verify snippets |
36
- | [Changelog](https://ductai.vercel.app/changelog) | Platform release notes (includes SDK) |
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) |
37
37
 
38
38
 
39
39
  ---
@@ -42,7 +42,7 @@ The official Duct SDK and CLI. Scan your codebase, declare a manifest, push it t
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
 
@@ -253,12 +253,12 @@ Webhook URLs and signing secrets are configured in the **dashboard → Shell →
253
253
  - Keep `DUCT_SECRET_KEY` server-side — never in `NEXT_PUBLIC_*`, `VITE_*`, or client bundles
254
254
  - Default mutations to `agentAccessible: false` and `sideEffects: true` where appropriate
255
255
  - Rotate keys in the dashboard if credentials are exposed
256
- - 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`
257
257
 
258
258
  ---
259
259
 
260
260
  ## Support
261
261
 
262
- - Docs: [ductai.vercel.app/docs](https://ductai.vercel.app/docs)
262
+ - Docs: `SITE_URL/docs` on your configured deployment
263
263
  - npm: [@duct-sdk/sdk](https://www.npmjs.com/package/@duct-sdk/sdk)
264
264
 
@@ -89,7 +89,7 @@ export interface DuctShellProps {
89
89
  panelWidth?: number;
90
90
  /**
91
91
  * Panel height in pixels. Ignored when `preset` is set.
92
- * @default 640
92
+ * @default 680
93
93
  */
94
94
  panelHeight?: number;
95
95
  /** Override container styles (wrapper div). */
@@ -97,7 +97,7 @@ export interface DuctShellProps {
97
97
  className?: string;
98
98
  /**
99
99
  * Optional launcher icon source.
100
- * When omitted, the SDK tries the host app's /duct-text-no-bg.png, then the shell host URL, then /assets/logo.png.
100
+ * When omitted, the SDK tries the shell host `/duct-text-no-bg.png`, then `/assets/logo.png`.
101
101
  */
102
102
  launcherIconSrc?: string;
103
103
  /**
@@ -269,7 +269,7 @@ function cancelRafUpdate(rafRef, pendingRef, commit) {
269
269
  * />
270
270
  * ```
271
271
  */
272
- export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, onPageContext, open, onOpenChange, defaultOpen = false, shellHost = DUCT_SHELL_HOST_DEFAULT, position = "bottom-right", preset, theme = "system", draggable = true, panelWidth = 420, panelHeight = 640, style, className, launcherIconSrc, readyCheck = false, }) {
272
+ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, onPageContext, open, onOpenChange, defaultOpen = false, shellHost = DUCT_SHELL_HOST_DEFAULT, position = "bottom-right", preset, theme = "system", draggable = true, panelWidth = 420, panelHeight = 680, style, className, launcherIconSrc, readyCheck = false, }) {
273
273
  const iframeRef = useRef(null);
274
274
  const panelRef = useRef(null);
275
275
  const [isReady, setIsReady] = useState(false);
@@ -334,7 +334,6 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
334
334
  const iconCandidates = launcherIconSrc
335
335
  ? [launcherIconSrc]
336
336
  : [
337
- "/duct-text-no-bg.png",
338
337
  `${shellOrigin}/duct-text-no-bg.png`,
339
338
  DUCT_LAUNCHER_ICON_LOCAL_FALLBACK,
340
339
  ];
@@ -60,6 +60,9 @@ function sampleConfig(overrides = {}) {
60
60
  },
61
61
  intershell_enabled: true,
62
62
  registry_visibility: "public",
63
+ webhooks: {
64
+ identityUrl: "https://app.acme.com/duct/identity",
65
+ },
63
66
  ...overrides,
64
67
  };
65
68
  }
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
@@ -1238,6 +1381,43 @@ migrateCmd
1238
1381
  }
1239
1382
  });
1240
1383
  // ----------------------------------------------------------------
1384
+ // duct verify-evidence — offline evidence bundle verification
1385
+ // ----------------------------------------------------------------
1386
+ program
1387
+ .command("verify-evidence")
1388
+ .description("Verify a duct:audit-evidence:v1 bundle offline")
1389
+ .requiredOption("--bundle <path>", "Path to evidence bundle JSON file")
1390
+ .option("--hmac-secret <secret>", "HMAC secret for legacy gate receipts")
1391
+ .action(async (opts) => {
1392
+ const { verifyEvidenceBundle } = await import("../core/evidence-bundle.js");
1393
+ const raw = await fs.readFile(path.resolve(opts.bundle), "utf-8");
1394
+ const bundle = JSON.parse(raw);
1395
+ const result = verifyEvidenceBundle(bundle, {
1396
+ hmacSecret: opts.hmacSecret ?? process.env.RECEIPT_SIGNING_KEY,
1397
+ });
1398
+ if (process.stdout.isTTY) {
1399
+ console.log(chalk.bold(result.valid ? "✓ Bundle verified" : "✗ Bundle failed verification"));
1400
+ console.log(chalk.dim(` Schema: ${result.schema}`));
1401
+ console.log(chalk.dim(` Completeness: ${result.completeness}`));
1402
+ console.log(chalk.dim(` Receipts verified: ${result.verified_receipts}`));
1403
+ if (result.warnings.length) {
1404
+ console.log(chalk.yellow("\nWarnings:"));
1405
+ for (const w of result.warnings)
1406
+ console.log(chalk.yellow(` • ${w}`));
1407
+ }
1408
+ if (result.failed_receipts.length) {
1409
+ console.log(chalk.red("\nFailed receipts:"));
1410
+ for (const f of result.failed_receipts) {
1411
+ console.log(chalk.red(` • ${f.receipt_id ?? "?"}: ${f.reason}`));
1412
+ }
1413
+ }
1414
+ }
1415
+ else {
1416
+ console.log(JSON.stringify(result, null, 2));
1417
+ }
1418
+ process.exit(result.valid ? 0 : 1);
1419
+ });
1420
+ // ----------------------------------------------------------------
1241
1421
  // Error handling
1242
1422
  // ----------------------------------------------------------------
1243
1423
  program.exitOverride();
@@ -40,6 +40,15 @@ function requiresPrompt(action) {
40
40
  const lowConfidence = (action.confidence ?? 0) < 0.85;
41
41
  return isSideEffect || lowConfidence;
42
42
  }
43
+ /**
44
+ * True when at least one agent-accessible action requires auth or has side effects —
45
+ * i.e. this shell needs `webhooks.identityUrl` configured before intershell callers
46
+ * can ever authorize it (see `crossValidateDuctConfig` in core/config.ts for the
47
+ * authoritative, enforced version of this check against the final assembled config).
48
+ */
49
+ function hasProtectedAgentAccessibleAction(actions) {
50
+ return actions.some((a) => a.agentAccessible && (a.requiresAuth || a.sideEffects));
51
+ }
43
52
  // ----------------------------------------------------------------
44
53
  // Single-action prompt (readline-based, not inquirer)
45
54
  // ----------------------------------------------------------------
@@ -276,6 +285,11 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
276
285
  }
277
286
  }
278
287
  }
288
+ if (hasProtectedAgentAccessibleAction(approvedActions)) {
289
+ console.log(chalk.yellow("\n [DUCT] intershell_enabled shells with protected actions must configure webhooks.identityUrl\n" +
290
+ " Set webhooks.identityUrl (Dashboard → Shell → Settings → Webhooks) or cross-shell\n" +
291
+ " callers will never be able to authorize these actions.\n"));
292
+ }
279
293
  }
280
294
  rl.close();
281
295
  const agentAccessibleCount = approvedActions.filter((a) => a.agentAccessible).length;
@@ -0,0 +1 @@
1
+ export {};