@duct-sdk/sdk 0.3.1 → 0.3.3

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
@@ -2,6 +2,23 @@
2
2
 
3
3
  Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
4
 
5
+ ## [0.3.3] — 2026-06-09
6
+
7
+ ### Fixed
8
+ - **Stable iframe `src`** — `userContext` is no longer embedded in the shell iframe URL; context is delivered via `DUCT_READY` postMessage instead. Prevents full iframe reloads when the host page navigates after a deeplink handoff.
9
+
10
+ ## [0.3.2] — 2026-06-09
11
+
12
+ ### Added
13
+ - **`@duct-sdk/sdk/server` subpath** — backend-safe entry point with token helpers (`generateDuctToken`, `verifyDuctToken`, `verifyDeeplinkToken`), config, and introspect handlers. No React dependency. Safe in Express, Fastify, Next.js API routes, Remix loaders, SvelteKit hooks, and any Node.js/Edge runtime. The root `@duct-sdk/sdk` export pulls React adapters and **crashes** plain Node backends where React is not installed; use `/server` for all backend code.
14
+
15
+ ### Fixed
16
+ - **Panel re-anchors to bubble after drag** — dragging the bubble to a new screen position now clears the previous panel position, so opening the shell always places the panel near the bubble's current location rather than the old dragged spot.
17
+ - **Token retry after mid-session login** — if the first token request returned empty (user not yet logged in), each subsequent message now retries the token fetch instead of silently staying unauthenticated for the life of the session.
18
+ - **Sticky "Working on it…" spinner** — the router progress indicator is now cleared when any terminal event arrives (`text_done`, `error`, deeplink, generative UI, clarification). Previously the spinner persisted alongside the final answer.
19
+ - **Hydration mismatch on shell embed** — messages and session ID are now loaded from `localStorage` in `useEffect` (post-hydration) instead of during initial `useState`, eliminating the React SSR/client HTML mismatch error in the shell iframe.
20
+ - **`+New` button unclickable** — the panel drag overlay was covering the full header including the `+New` and close buttons. The overlay now ends before the header action cluster so buttons are always clickable.
21
+
5
22
  ## [0.3.1] — 2026-06-09
6
23
 
7
24
  ### Added
package/README.md CHANGED
@@ -7,67 +7,107 @@ The Duct SDK scans your codebase, generates a manifest, and provides embed compo
7
7
  - **Humans** — chat or use an embedded shell; Duct runs actions or hands off via signed deeplinks
8
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 the Duct dashboard.
11
11
 
12
- Release notes for each version are in [`CHANGELOG.md`](CHANGELOG.md) (included in the published npm package).
12
+ ---
13
+
14
+ ## What integration looks like
15
+
16
+ Duct does not replace your API or rewrite your product. You wire four things in your codebase, and Duct does the rest:
17
+
18
+ | What you add | Where |
19
+ |---|---|
20
+ | Token minting endpoint | `POST /api/duct/token` — one server route |
21
+ | Auth middleware fallback | `verifyDuctToken` added to your existing Bearer-token check |
22
+ | Deeplink receiver | `POST /api/duct/receive` — verifies signed nav tokens |
23
+ | Widget embed | `<DuctShell>` once in your root layout |
24
+
25
+ The manifest (`duct.config.ts`) declares which routes, actions, and deeplinks exist. `duct push` uploads it to Duct. Your API stays unchanged.
13
26
 
14
27
  ---
15
28
 
16
29
  ## Quickstart
17
30
 
18
- **1. Create your account** in the Duct dashboard and copy your API key.
31
+ **1. Create your shell** in the Duct dashboard and copy your API key.
19
32
 
20
- **2. Authenticate:**
33
+ **2. Authenticate the CLI:**
21
34
 
22
35
  ```bash
23
36
  npx @duct-sdk/sdk login
24
37
  ```
25
38
 
26
- **3. Generate a manifest** (recommended path for first setup):
39
+ > **Node 22+ note:** if the CLI exits with an ERR_REQUIRE_ESM error, run with
40
+ > `node --experimental-require-module $(npx --no which duct) <command>` or install the
41
+ > package globally with `npm i -g @duct-sdk/sdk` and use `duct <command>`.
42
+
43
+ **3. Generate a manifest:**
27
44
 
28
45
  ```bash
46
+ # Recommended first run — instant editable template, no LLM required
29
47
  npx @duct-sdk/sdk init --manual
30
- ```
31
48
 
32
- For AI-assisted scanning once your API surface is stable:
33
-
34
- ```bash
49
+ # AI-assisted scan of your codebase once your API surface is stable
35
50
  npx @duct-sdk/sdk init
36
- ```
37
51
 
38
- This produces:
39
- - `duct.config.ts` — your shell manifest
40
- - A receiver route (`/duct/receive`) — handles deeplink handoffs
41
- - A shell widget component — drop into your layout
52
+ # From an existing OpenAPI / Swagger spec
53
+ npx @duct-sdk/sdk init --api-spec openapi.yaml
54
+ ```
42
55
 
43
- **4. Push your manifest:**
56
+ **4. Push:**
44
57
 
45
58
  ```bash
46
59
  npx @duct-sdk/sdk push
47
60
  ```
48
61
 
49
- **5. Embed the shell** (Next.js example):
62
+ **5. Embed the shell:**
50
63
 
51
64
  ```tsx
65
+ // Next.js App Router (root layout)
52
66
  import { DuctShell } from '@duct-sdk/sdk/next';
53
67
 
54
- export default function Layout({ children }) {
68
+ export default function RootLayout({ children }) {
55
69
  return (
56
- <>
57
- {children}
58
- <DuctShell
59
- shellId={process.env.NEXT_PUBLIC_DUCT_SHELL_ID}
60
- preset="tall" // "tall" | "square" | "large"
61
- position="bottom-right" // starting corner; bubble + opened panel are draggable
62
- theme="system" // "system" | "light" | "dark"
63
- />
64
- </>
70
+ <html>
71
+ <body>
72
+ {children}
73
+ <DuctShell
74
+ shellId={process.env.NEXT_PUBLIC_DUCT_SHELL_ID!}
75
+ shellHost={process.env.NEXT_PUBLIC_DUCT_SHELL_HOST}
76
+ onTokenRequest={async () => {
77
+ const res = await fetch('/api/duct/token', { method: 'POST', credentials: 'include' });
78
+ return (await res.json()).token ?? '';
79
+ }}
80
+ preset="tall" // "tall" | "square" | "large"
81
+ position="bottom-right" // starting corner; bubble + panel are draggable
82
+ theme="system" // "system" | "light" | "dark"
83
+ />
84
+ </body>
85
+ </html>
65
86
  );
66
87
  }
67
88
  ```
68
89
 
69
- The launcher bubble and opened panel are **draggable** (drop the bubble anywhere — position persists per shell) and **theme-aware**. Use `preset`
70
- to size the panel, or pass `panelWidth`/`panelHeight` for a custom size. Set `draggable={false}` to pin the bubble.
90
+ ---
91
+
92
+ ## Import guide — use the right subpath
93
+
94
+ | Import | Use when |
95
+ |---|---|
96
+ | `@duct-sdk/sdk/server` | **Any Node.js / Edge backend** — token helpers, config, introspect. No React. Safe in Express, Fastify, Next.js API routes, Remix loaders, SvelteKit hooks. |
97
+ | `@duct-sdk/sdk/next` | Next.js App Router frontend (requires React) |
98
+ | `@duct-sdk/sdk/react` | Plain React or non-Next frameworks (requires React) |
99
+ | `@duct-sdk/sdk/vite` | Vite + Express (requires React) |
100
+ | `@duct-sdk/sdk/remix` | Remix (requires React) |
101
+ | `@duct-sdk/sdk/sveltekit` | SvelteKit |
102
+ | `@duct-sdk/sdk` (root) | Full bundle — only in React SSR frontends where React is already installed. **Crashes plain Express/Fastify backends.** |
103
+
104
+ ```ts
105
+ // ✅ Correct — server route (Express, Next.js API, Remix loader, etc.)
106
+ import { generateDuctToken, verifyDuctToken } from '@duct-sdk/sdk/server';
107
+
108
+ // ❌ Wrong — pulls in React adapters, crashes if React is not installed
109
+ import { generateDuctToken } from '@duct-sdk/sdk';
110
+ ```
71
111
 
72
112
  ---
73
113
 
@@ -75,37 +115,106 @@ to size the panel, or pass `panelWidth`/`panelHeight` for a custom size. Set `dr
75
115
 
76
116
  | Command | Description |
77
117
  |---|---|
78
- | `npx @duct-sdk/sdk login` | Authenticate with your Duct API key |
79
- | `npx @duct-sdk/sdk init` | AI-assisted scan — generates config + shell files |
80
- | `npx @duct-sdk/sdk init --manual` | Instant template without LLM (recommended first run) |
81
- | `npx @duct-sdk/sdk init --update` | Re-scan only files changed since last push |
82
- | `npx @duct-sdk/sdk init --no-agents` | Skip AI scan; blank template |
83
- | `npx @duct-sdk/sdk push` | Push `duct.config.ts` to Duct |
84
- | `npx @duct-sdk/sdk pull <hash>` | Restore a manifest version from push history |
85
- | `npx @duct-sdk/sdk promote --from <id> --to <id>` | Copy manifest to another environment shell |
86
- | `npx @duct-sdk/sdk scan` | Detect drift between live API and manifest |
87
- | `npx @duct-sdk/sdk checkup` | Check env config and service connectivity |
88
-
89
- Once installed globally (`npm i -g @duct-sdk/sdk`), commands shorten to `duct login`, `duct init`, etc.
118
+ | `duct login` | Authenticate with your Duct API key |
119
+ | `duct init` | AI-assisted scan — generates config + shell files |
120
+ | `duct init --manual` | Instant template without LLM (recommended first run) |
121
+ | `duct init --update` | Re-scan only files changed since last push |
122
+ | `duct init --api-spec <path>` | Generate manifest from OpenAPI / Swagger spec |
123
+ | `duct init --no-agents` | Skip AI scan; blank template |
124
+ | `duct push` | Push `duct.config.ts` to Duct |
125
+ | `duct pull <hash>` | Restore a manifest version from push history |
126
+ | `duct promote --from <id> --to <id>` | Copy manifest to another environment shell |
127
+ | `duct scan` | Detect drift between live API and manifest |
128
+ | `duct checkup` | Check env config and service connectivity |
129
+
130
+ Install globally to drop the `npx`: `npm i -g @duct-sdk/sdk`.
90
131
 
91
132
  ---
92
133
 
93
134
  ## Framework support
94
135
 
95
- | Framework | Import |
96
- |---|---|
97
- | Next.js (App Router) | `@duct-sdk/sdk/next` |
98
- | Remix | `@duct-sdk/sdk/remix` |
99
- | Vite | `@duct-sdk/sdk/vite` |
100
- | SvelteKit | `@duct-sdk/sdk/sveltekit` |
101
- | React Embed | `@duct-sdk/sdk/react` |
136
+ | Framework | Import | Client env vars |
137
+ |---|---|---|
138
+ | Next.js (App Router) | `@duct-sdk/sdk/next` | `NEXT_PUBLIC_DUCT_SHELL_ID`, `NEXT_PUBLIC_DUCT_SHELL_HOST` |
139
+ | Vite | `@duct-sdk/sdk/vite` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
140
+ | Remix | `@duct-sdk/sdk/remix` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
141
+ | SvelteKit | `@duct-sdk/sdk/sveltekit` | `PUBLIC_DUCT_SHELL_ID`, `PUBLIC_DUCT_SHELL_HOST` |
142
+ | React (generic) | `@duct-sdk/sdk/react` | any |
143
+ | Express / Fastify / other Node | `@duct-sdk/sdk/server` | — (server only) |
144
+
145
+ ### Vite + Express
146
+
147
+ Keep environment variables in three files:
148
+
149
+ ```
150
+ /.env → DUCT_SECRET_KEY, DUCT_SHELL_ID (server, never commit)
151
+ /backend/.env → same values for the Express process if run separately
152
+ /frontend/.env → VITE_DUCT_SHELL_ID, VITE_DUCT_SHELL_HOST (public)
153
+ ```
154
+
155
+ Express token route:
156
+
157
+ ```ts
158
+ import express from 'express';
159
+ import { generateDuctToken } from '@duct-sdk/sdk/server'; // ← /server, not root
160
+
161
+ const router = express.Router();
162
+ router.post('/api/duct/token', express.json(), async (req, res) => {
163
+ if (!req.user) return res.status(401).json({ error: 'unauthenticated' });
164
+ const { token } = await generateDuctToken({
165
+ secretKey: process.env.DUCT_SECRET_KEY!,
166
+ shellId: process.env.DUCT_SHELL_ID!,
167
+ userSession: { id: req.user.id, email: req.user.email },
168
+ expirySeconds: 300,
169
+ });
170
+ res.json({ token });
171
+ });
172
+ ```
173
+
174
+ API auth middleware:
175
+
176
+ ```ts
177
+ import { verifyDuctToken } from '@duct-sdk/sdk/server';
178
+
179
+ app.use(async (req, res, next) => {
180
+ const header = req.headers.authorization ?? '';
181
+ if (!header.startsWith('Bearer ')) return res.status(401).end();
182
+ const raw = header.slice(7);
183
+ // Try your own JWT first
184
+ const mine = await verifyMyJwt(raw).catch(() => null);
185
+ if (mine) { req.user = mine; return next(); }
186
+ // Fall back to Duct delegated token
187
+ const duct = await verifyDuctToken(raw, { secretKey: process.env.DUCT_SECRET_KEY! });
188
+ if (duct.valid) { req.user = duct.payload!.session; return next(); }
189
+ res.status(401).end();
190
+ });
191
+ ```
192
+
193
+ ---
194
+
195
+ ## Webhook configuration
196
+
197
+ Webhook URLs (deeplink callback, event stream) and the signing secret are **not** part of `duct.config.ts` and are **not** pushed via `duct push`. Configure them in the **Duct dashboard → Shell → Settings → Webhooks**.
198
+
199
+ Your endpoint receives a POST with an `X-Duct-Signature` HMAC-SHA256 header for verification. Webhooks are optional — the shell, widget, and action flow work without them.
200
+
201
+ ---
202
+
203
+ ## Deeplinks — route inventory first
204
+
205
+ Before declaring deeplinks, inventory every navigable page in your app:
206
+
207
+ 1. List all routes where a user lands with identity-specific state (order ID, document ID, profile slug).
208
+ 2. Mark which of those a conversation could meaningfully route to.
209
+ 3. Declare only those in `deeplinks[]` with matching `stateFields`.
102
210
 
103
- Your API endpoints stay yours. Duct reads your manifest and calls your existing routes — nothing is proxied or stored.
211
+ A `targetRoute` must match an entry in `routes[]`. The deeplink receiver must verify the signed token server-side before using any state value — never trust raw query params.
104
212
 
105
213
  ---
106
214
 
107
215
  ## Security
108
216
 
109
- - Keep secrets server-side; never expose them in client code
110
- - Use least privilege when marking actions as `agentAccessible`
111
- - Store credentials in environment variables; rotate keys in the dashboard when needed
217
+ - Keep `DUCT_SECRET_KEY` server-side only — never in client bundles or `NEXT_PUBLIC_*` / `VITE_*` vars
218
+ - Use least privilege when marking actions `agentAccessible: true`
219
+ - `sideEffects: true` on any action that creates, updates, deletes, or charges
220
+ - Rotate keys in the dashboard if credentials are exposed
@@ -4,7 +4,7 @@
4
4
  // ============================================================
5
5
  "use client";
6
6
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
7
- import React, { useEffect, useRef, useCallback, useState, } from "react";
7
+ import React, { useEffect, useRef, useCallback, useMemo, useState, } from "react";
8
8
  import { resolveShellDimensions, } from "../../core/types.js";
9
9
  /**
10
10
  * Hook that polls the shell status endpoint once on mount.
@@ -135,7 +135,10 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
135
135
  }, [readyCheck, shellId, shellHost]);
136
136
  const controlled = open !== undefined;
137
137
  const panelOpen = controlled ? open : isOpen;
138
- const shellUrl = buildShellUrl(shellHost, shellId, userContext);
138
+ // Keep iframe src stable across parent-page navigations (deeplink handoff).
139
+ // userContext is delivered via postMessage on DUCT_READY — embedding it in the
140
+ // URL would reload the iframe whenever the host page context changes.
141
+ const shellUrl = useMemo(() => buildShellUrl(shellHost, shellId), [shellHost, shellId]);
139
142
  const shellOrigin = (() => {
140
143
  try {
141
144
  return new URL(shellHost).origin;
@@ -364,6 +367,9 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
364
367
  window.localStorage.setItem(`duct-shell-pos:${shellId}`, JSON.stringify(bubblePos));
365
368
  }
366
369
  catch { /* ignore */ }
370
+ // Bubble moved to a new location — clear any panel position so the panel
371
+ // re-anchors near the bubble on the next open instead of the old dragged spot.
372
+ setPanelPos(null);
367
373
  }
368
374
  };
369
375
  window.addEventListener("pointermove", onMove);
@@ -516,7 +522,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
516
522
  position: "absolute",
517
523
  top: 0,
518
524
  left: 0,
519
- right: 44,
525
+ // Leave the header control cluster (+ New, close) clickable inside the iframe.
526
+ right: 140,
520
527
  height: 44,
521
528
  zIndex: 2,
522
529
  cursor: isPanelDragging ? "grabbing" : "grab",
package/dist/index.js CHANGED
@@ -1,5 +1,9 @@
1
1
  // ============================================================
2
- // @duct/sdk — Main Package Exports
2
+ // @duct-sdk/sdk — Main Package Exports
3
+ //
4
+ // ⚠️ Backend / Node.js usage: import from "@duct-sdk/sdk/server"
5
+ // instead. The root export includes React adapters which crash
6
+ // runtimes where React is not installed (e.g. plain Express).
3
7
  // ============================================================
4
8
  // Core config
5
9
  export { defineDuctConfig, DuctConfigSchema } from "./core/config.js";
@@ -0,0 +1,11 @@
1
+ export { defineDuctConfig, DuctConfigSchema } from "./core/config.js";
2
+ export type { ValidatedDuctConfig } from "./core/config.js";
3
+ export { generateDuctToken, verifyDuctToken, generateDeeplinkToken, verifyDeeplinkToken, } from "./core/token.js";
4
+ export type { GenerateTokenOptions, GenerateTokenResult, VerifyTokenOptions, VerifyTokenResult, GenerateDeeplinkTokenOptions, GenerateDeeplinkTokenResult, VerifyDeeplinkTokenOptions, VerifyDeeplinkResult, } from "./core/token.js";
5
+ export { createIntrospectHandler, createIntrospectPageHandler, createIntrospectExpressHandler, } from "./core/introspect.js";
6
+ export type { IntrospectEntity, IntrospectResult, IntrospectContext, IntrospectResolver, IntrospectHandlerOptions, } from "./core/introspect.js";
7
+ export { buildAction, checkActionPermission, buildActionSearchIndex, shouldDeferActions, } from "./core/action.js";
8
+ export type { ActionSearchEntry } from "./core/action.js";
9
+ export { checkShellStatus } from "./core/status.js";
10
+ export type { ShellStatus, ShellStatusWidget, CheckShellStatusOptions } from "./core/status.js";
11
+ export type { DuctConfig, DuctTokenPayload, DeeplinkTokenPayload, ActionManifest, ActionParam, RouteManifest, RouteParam, QueryParam, AuthSchema, AuthStrategy, DeeplinkDefinition, StateField, ShellManifest, ProductConfig, AgentPermissions, AgentPermissionLevel, WidgetConfig, SensitivityLevel, SessionContext, DuctAdapter, ReceiverOptions, } from "./core/types.js";
package/dist/server.js ADDED
@@ -0,0 +1,21 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk/server — Backend-safe entry point
3
+ //
4
+ // Safe to import in any Node.js / Edge runtime (Express, Fastify,
5
+ // Next.js API routes, Remix loaders, SvelteKit hooks, etc.)
6
+ // without installing React or react-dom.
7
+ //
8
+ // Do NOT import from "@duct-sdk/sdk" in backend code — the root
9
+ // export re-exports React hooks which crash runtimes where React
10
+ // is not installed.
11
+ // ============================================================
12
+ // Config
13
+ export { defineDuctConfig, DuctConfigSchema } from "./core/config.js";
14
+ // Token utilities — mint delegated JWTs, verify them, handle deeplinks
15
+ export { generateDuctToken, verifyDuctToken, generateDeeplinkToken, verifyDeeplinkToken, } from "./core/token.js";
16
+ // Introspect handler factories
17
+ export { createIntrospectHandler, createIntrospectPageHandler, createIntrospectExpressHandler, } from "./core/introspect.js";
18
+ // Action utilities (permission checking, search index)
19
+ export { buildAction, checkActionPermission, buildActionSearchIndex, shouldDeferActions, } from "./core/action.js";
20
+ // Shell status check (server-side polling)
21
+ export { checkShellStatus } from "./core/status.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duct-sdk/sdk",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "type": "module",
5
5
  "description": "Duct SDK — A shell (like terminal) that knows when to talk, when to show, and when to hand off.",
6
6
  "main": "dist/index.js",
@@ -10,6 +10,7 @@
10
10
  },
11
11
  "exports": {
12
12
  ".": "./dist/index.js",
13
+ "./server": "./dist/server.js",
13
14
  "./next": "./dist/adapters/next/index.js",
14
15
  "./remix": "./dist/adapters/remix/index.js",
15
16
  "./vite": "./dist/adapters/vite/index.js",