@duct-sdk/sdk 0.5.13 → 0.6.0

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 (160) hide show
  1. package/CHANGELOG.md +385 -344
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -243
  4. package/dist/cli/add.d.ts +7 -0
  5. package/dist/cli/add.js +152 -0
  6. package/dist/cli/agent-prompt.d.ts +3 -0
  7. package/dist/cli/agent-prompt.js +39 -0
  8. package/dist/cli/api-sources.d.ts +26 -0
  9. package/dist/cli/api-sources.js +222 -0
  10. package/dist/cli/cloud.d.ts +133 -0
  11. package/dist/cli/cloud.js +298 -0
  12. package/dist/cli/config-loader.d.ts +14 -0
  13. package/dist/cli/config-loader.js +56 -7
  14. package/dist/cli/device-login.d.ts +17 -0
  15. package/dist/cli/device-login.js +75 -0
  16. package/dist/cli/drift.js +6 -6
  17. package/dist/cli/generators/any-stack.d.ts +3 -0
  18. package/dist/cli/generators/any-stack.js +97 -0
  19. package/dist/cli/generators/config.js +3 -2
  20. package/dist/cli/generators/receiver.js +7 -7
  21. package/dist/cli/generators/shell.js +12 -12
  22. package/dist/cli/generators/token-route.js +245 -245
  23. package/dist/cli/index.js +396 -611
  24. package/dist/cli/mcp-core.d.ts +42 -0
  25. package/dist/cli/mcp-core.js +161 -0
  26. package/dist/cli/mcp-setup.d.ts +4 -0
  27. package/dist/cli/mcp-setup.js +360 -0
  28. package/dist/cli/mcp.d.ts +2 -0
  29. package/dist/cli/mcp.js +457 -0
  30. package/dist/cli/migrate-intershell.js +5 -5
  31. package/dist/cli/policy-defaults.d.ts +37 -0
  32. package/dist/cli/policy-defaults.js +127 -0
  33. package/dist/cli/processors/integration-audit.js +2 -2
  34. package/dist/cli/processors/openapi-parser.d.ts +5 -0
  35. package/dist/cli/processors/openapi-parser.js +8 -3
  36. package/dist/cli/project-loader.d.ts +58 -0
  37. package/dist/cli/project-loader.js +198 -0
  38. package/dist/cli/project-writer.d.ts +23 -0
  39. package/dist/cli/project-writer.js +171 -0
  40. package/dist/cli/push.d.ts +43 -0
  41. package/dist/cli/push.js +276 -0
  42. package/dist/cli/safety-checks.d.ts +9 -0
  43. package/dist/cli/safety-checks.js +29 -0
  44. package/dist/cli/setup.d.ts +20 -0
  45. package/dist/cli/setup.js +349 -0
  46. package/dist/cli/shell-name.d.ts +8 -0
  47. package/dist/cli/shell-name.js +29 -0
  48. package/dist/cli/shells.d.ts +22 -0
  49. package/dist/cli/shells.js +122 -0
  50. package/dist/cli/split.d.ts +7 -0
  51. package/dist/cli/split.js +71 -0
  52. package/dist/cli/sync.d.ts +25 -0
  53. package/dist/cli/sync.js +120 -0
  54. package/dist/cli/test-runner.d.ts +21 -0
  55. package/dist/cli/test-runner.js +281 -0
  56. package/dist/core/compile.d.ts +43 -0
  57. package/dist/core/compile.js +510 -0
  58. package/dist/core/config.d.ts +464 -1
  59. package/dist/core/config.js +14 -14
  60. package/dist/core/login-handoff.d.ts +1 -1
  61. package/dist/core/login-handoff.js +1 -1
  62. package/dist/core/project.d.ts +1798 -0
  63. package/dist/core/project.js +278 -0
  64. package/dist/core/readiness-checks.js +2 -2
  65. package/dist/core/types.d.ts +1 -1
  66. package/dist/index.d.ts +2 -0
  67. package/dist/index.js +1 -0
  68. package/dist/project.d.ts +4 -0
  69. package/dist/project.js +8 -0
  70. package/dist/server.d.ts +2 -0
  71. package/dist/server.js +1 -0
  72. package/package.json +94 -95
  73. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  74. package/dist/adapters/react/page-context-guard.test.js +0 -15
  75. package/dist/cli/agents/api-agent.d.ts +0 -22
  76. package/dist/cli/agents/api-agent.js +0 -761
  77. package/dist/cli/agents/auth-agent.d.ts +0 -7
  78. package/dist/cli/agents/auth-agent.js +0 -212
  79. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  80. package/dist/cli/agents/deeplink-agent.js +0 -285
  81. package/dist/cli/agents/llm.d.ts +0 -33
  82. package/dist/cli/agents/llm.js +0 -309
  83. package/dist/cli/agents/pipeline.d.ts +0 -72
  84. package/dist/cli/agents/pipeline.js +0 -421
  85. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  86. package/dist/cli/agents/reviewer-agent.js +0 -450
  87. package/dist/cli/agents/route-agent.d.ts +0 -17
  88. package/dist/cli/agents/route-agent.js +0 -383
  89. package/dist/cli/config-loader.test.d.ts +0 -1
  90. package/dist/cli/config-loader.test.js +0 -63
  91. package/dist/cli/detectors/topology.d.ts +0 -46
  92. package/dist/cli/detectors/topology.js +0 -417
  93. package/dist/cli/generators/config.test.d.ts +0 -1
  94. package/dist/cli/generators/config.test.js +0 -222
  95. package/dist/cli/generators/shell.test.d.ts +0 -1
  96. package/dist/cli/generators/shell.test.js +0 -73
  97. package/dist/cli/generators/token-route.test.d.ts +0 -1
  98. package/dist/cli/generators/token-route.test.js +0 -53
  99. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  100. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  101. package/dist/cli/init.d.ts +0 -32
  102. package/dist/cli/init.js +0 -1336
  103. package/dist/cli/manifest-diff.test.d.ts +0 -1
  104. package/dist/cli/manifest-diff.test.js +0 -144
  105. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  106. package/dist/cli/processors/curl-parser.test.js +0 -24
  107. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  108. package/dist/cli/processors/integration-audit.test.js +0 -154
  109. package/dist/cli/processors/postprocess.d.ts +0 -22
  110. package/dist/cli/processors/postprocess.js +0 -107
  111. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  112. package/dist/cli/processors/prisma-parser.js +0 -117
  113. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  114. package/dist/cli/processors/verify-discovery.js +0 -193
  115. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  116. package/dist/cli/processors/verify-discovery.test.js +0 -153
  117. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  118. package/dist/cli/processors/zod-extractor.js +0 -153
  119. package/dist/cli/prompts/review.d.ts +0 -61
  120. package/dist/cli/prompts/review.js +0 -410
  121. package/dist/cli/selectors/express.d.ts +0 -12
  122. package/dist/cli/selectors/express.js +0 -117
  123. package/dist/cli/selectors/fastapi.d.ts +0 -12
  124. package/dist/cli/selectors/fastapi.js +0 -122
  125. package/dist/cli/selectors/generic.d.ts +0 -10
  126. package/dist/cli/selectors/generic.js +0 -74
  127. package/dist/cli/selectors/index.d.ts +0 -37
  128. package/dist/cli/selectors/index.js +0 -315
  129. package/dist/cli/selectors/next.d.ts +0 -12
  130. package/dist/cli/selectors/next.js +0 -130
  131. package/dist/core/config-policy.test.d.ts +0 -1
  132. package/dist/core/config-policy.test.js +0 -101
  133. package/dist/core/config-roundtrip.test.d.ts +0 -1
  134. package/dist/core/config-roundtrip.test.js +0 -180
  135. package/dist/core/endpoint-guard.test.d.ts +0 -1
  136. package/dist/core/endpoint-guard.test.js +0 -57
  137. package/dist/core/env-diagnostics.test.d.ts +0 -1
  138. package/dist/core/env-diagnostics.test.js +0 -31
  139. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  140. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  141. package/dist/core/evidence-bundle.test.d.ts +0 -1
  142. package/dist/core/evidence-bundle.test.js +0 -58
  143. package/dist/core/invariants.test.d.ts +0 -1
  144. package/dist/core/invariants.test.js +0 -217
  145. package/dist/core/login-handoff.test.d.ts +0 -1
  146. package/dist/core/login-handoff.test.js +0 -31
  147. package/dist/core/profile.test.d.ts +0 -1
  148. package/dist/core/profile.test.js +0 -95
  149. package/dist/core/readiness-checks.test.d.ts +0 -1
  150. package/dist/core/readiness-checks.test.js +0 -106
  151. package/dist/core/receipt.test.d.ts +0 -1
  152. package/dist/core/receipt.test.js +0 -75
  153. package/dist/core/sdk-entrypoint.test.d.ts +0 -1
  154. package/dist/core/sdk-entrypoint.test.js +0 -8
  155. package/dist/core/side-effects-review.test.d.ts +0 -1
  156. package/dist/core/side-effects-review.test.js +0 -28
  157. package/dist/core/token.conformance.test.d.ts +0 -1
  158. package/dist/core/token.conformance.test.js +0 -43
  159. package/dist/core/token.test.d.ts +0 -1
  160. package/dist/core/token.test.js +0 -66
package/README.md CHANGED
@@ -1,264 +1,418 @@
1
- ```
2
- ██████╗ ██╗ ██╗ ╔██████ ████████╗
3
- ██╔══██╗ ██║ ██║ ╚════╗██ ╚══██╔══╝
4
- ██║ ██║ ██║ ██║ ║██ ██║
5
- ██║ ██║ ██║ ██║ ║██ ██║
6
- ██████╔╝ ╚██████╔╝ ╔██████╝ ██║
7
- ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝
8
- ```
9
-
10
- # @duct-sdk/sdk
11
-
12
- **Let agents use your product safely.**
13
-
14
- [npm version](https://www.npmjs.com/package/@duct-sdk/sdk) | [Node 20+](https://nodejs.org/)
15
-
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.
17
-
18
-
19
- | Audience | What you get |
20
- | ------------- | ----------------------------------------------------------------------------------------------- |
21
- | **Humans** | Embedded chat shell, structured results, signed deeplink handoff into your app |
22
- | **Agents** | Permissioned API access from the same manifest — no scraping or screen automation |
23
- | **Operators** | Shell credentials, action tiers, and usage from the configured Duct dashboard |
24
-
25
-
26
- ---
27
-
28
- ## Documentation
29
-
30
-
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
-
38
-
39
- ---
40
-
41
- ## AI-assisted integration
42
-
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
-
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
-
47
- Typical flow:
48
-
49
- 1. Run `duct init` or `duct init --manual` for a first draft.
50
- 2. Paste `DUCT_CONFIG_PROMPT.md` from the docs page to audit wiring and permissions.
51
- 3. `duct push`, embed `<DuctShell>`, smoke-test in the dashboard playground.
52
-
53
- ---
54
-
55
- ## Install
56
-
57
- ```bash
58
- npm install @duct-sdk/sdk
59
- # or run without installing:
60
- npx @duct-sdk/sdk <command>
61
- ```
62
-
63
- Global CLI (optional): `npm i -g @duct-sdk/sdk` → `duct <command>`.
64
-
65
- > **Node 22+:** if the CLI exits with `ERR_REQUIRE_ESM`, use
66
- > `node --experimental-require-module $(npx --no which duct) <command>` or install globally.
67
-
68
- ---
69
-
70
- ## Quickstart
71
-
72
- **1. Create a shell** in the Duct dashboard and copy your API key.
73
-
74
- **2. Log in:**
75
-
76
- ```bash
77
- npx @duct-sdk/sdk login
78
- ```
79
-
80
- **3. Generate a manifest:**
81
-
82
- ```bash
83
- npx @duct-sdk/sdk init --manual # instant template (recommended first run)
84
- npx @duct-sdk/sdk init # AI-assisted scan when your API is stable
85
- npx @duct-sdk/sdk init --api-spec openapi.yaml
86
- ```
87
-
88
- **4. Push:**
89
-
90
- ```bash
91
- npx @duct-sdk/sdk push
92
- ```
93
-
94
- **5. Embed** (Next.js App Router example):
95
-
96
- ```tsx
97
- import { DuctShell } from '@duct-sdk/sdk/next';
98
-
99
- export default function RootLayout({ children }) {
100
- return (
101
- <html>
102
- <body>
103
- {children}
104
- <DuctShell
105
- shellId={process.env.NEXT_PUBLIC_DUCT_SHELL_ID!}
106
- shellHost={process.env.NEXT_PUBLIC_DUCT_SHELL_HOST}
107
- onTokenRequest={async () => {
108
- const res = await fetch('/api/duct/token', {
109
- method: 'POST',
110
- credentials: 'include',
111
- });
112
- return (await res.json()).token ?? '';
113
- }}
114
- preset="tall"
115
- position="bottom-right"
116
- theme="system"
117
- />
118
- </body>
119
- </html>
120
- );
121
- }
122
- ```
123
-
124
- ### Four wiring points
125
-
126
- Duct does not replace your API. You add four integration points in **your** codebase:
127
-
128
-
129
- | # | What | Where |
130
- | --- | ----------------- | ----------------------------------------------------------------- |
131
- | 1 | Token minting | `POST /api/duct/token` → `generateDuctToken` |
132
- | 2 | API auth | Existing middleware also accepts `verifyDuctToken` delegated JWTs |
133
- | 3 | Deeplink receiver | `POST /api/duct/receive` → `verifyDeeplinkToken` |
134
- | 4 | Widget embed | `<DuctShell>` in root layout with `onTokenRequest` |
135
-
136
-
137
- `duct.config.ts` declares routes, actions, deeplinks, and agent permissions. `duct push` uploads it; your business logic stays unchanged.
138
-
139
- ---
140
-
141
- ## Import guide
142
-
143
- Use the **subpath** that matches your runtime. The root export pulls React adapters and will crash plain Node servers.
144
-
145
-
146
- | Import | Use when |
147
- | ------------------------- | ------------------------------------------------------------------- |
148
- | `@duct-sdk/sdk/server` | **Any Node / Edge backend** — tokens, config, introspect. No React. |
149
- | `@duct-sdk/sdk/next` | Next.js App Router (React) |
150
- | `@duct-sdk/sdk/react` | React without Next |
151
- | `@duct-sdk/sdk/vite` | Vite + Express (React) |
152
- | `@duct-sdk/sdk/remix` | Remix (React) |
153
- | `@duct-sdk/sdk/sveltekit` | SvelteKit |
154
- | `@duct-sdk/sdk` | React SSR frontends only — **not** Express/Fastify APIs |
155
-
156
-
157
- ```ts
158
- // Server route (Express, Next.js route handler, Remix loader, …)
159
- import { generateDuctToken, verifyDuctToken } from '@duct-sdk/sdk/server';
160
- ```
161
-
162
- ---
163
-
164
- ## CLI
165
-
166
-
167
- | Command | Description |
168
- | ------------------------------------ | ---------------------------------------- |
169
- | `duct login` | Authenticate with your Duct API key |
170
- | `duct init` | AI-assisted scan → config + shell files |
171
- | `duct init --manual` | Template without LLM |
172
- | `duct init --update` | Re-scan files changed since last push |
173
- | `duct init --api-spec <path>` | Manifest from OpenAPI / Swagger |
174
- | `duct push` | Upload `duct.config.ts` to Duct |
175
- | `duct pull <hash>` | Restore a manifest version from history |
176
- | `duct promote --from <id> --to <id>` | Copy manifest between environment shells |
177
- | `duct scan` | Drift between live API and manifest |
178
- | `duct checkup` | Env config and service connectivity |
179
-
180
-
181
- ---
182
-
183
- ## Frameworks
184
-
185
-
186
- | Framework | Import | Client env vars |
187
- | ------------------------ | ------------------------- | ---------------------------------------------------------- |
188
- | Next.js (App Router) | `@duct-sdk/sdk/next` | `NEXT_PUBLIC_DUCT_SHELL_ID`, `NEXT_PUBLIC_DUCT_SHELL_HOST` |
189
- | Vite | `@duct-sdk/sdk/vite` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
190
- | Remix | `@duct-sdk/sdk/remix` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
191
- | SvelteKit | `@duct-sdk/sdk/sveltekit` | `PUBLIC_DUCT_SHELL_ID`, `PUBLIC_DUCT_SHELL_HOST` |
192
- | React (generic) | `@duct-sdk/sdk/react` | framework-specific |
193
- | Express / Fastify / Node | `@duct-sdk/sdk/server` | — (server only) |
194
-
195
-
196
- ### Vite + Express
197
-
198
- ```ts
199
- import express from 'express';
200
- import { generateDuctToken, verifyDuctToken } from '@duct-sdk/sdk/server';
201
-
202
- router.post('/api/duct/token', express.json(), async (req, res) => {
203
- if (!req.user) return res.status(401).json({ error: 'unauthenticated' });
204
- const { token } = await generateDuctToken({
205
- secretKey: process.env.DUCT_SECRET_KEY!,
206
- shellId: process.env.DUCT_SHELL_ID!,
207
- userSession: { id: req.user.id, email: req.user.email },
208
- expirySeconds: 300,
209
- });
210
- res.json({ token });
211
- });
212
- ```
213
-
214
- Keep secrets in server `.env` only (`DUCT_SECRET_KEY`, `DUCT_SHELL_ID`). Client bundles use public `VITE_*` shell ID / host vars.
215
-
216
- ---
217
-
218
- ## Deeplinks & replay protection
219
-
220
- Declare deeplinks only for routes you have inventoried in `routes[]`. The receiver must verify signed tokens server-side — never trust raw query params.
221
-
222
- Deeplink JWTs include a `jti` claim. Pass a `replayStore` to `verifyDeeplinkToken` so each token is single-use:
223
-
224
- ```ts
225
- import {
226
- verifyDeeplinkToken,
227
- createDevReplayStore,
228
- RedisReplayStore,
229
- } from '@duct-sdk/sdk/server';
230
-
231
- const replayStore = createDevReplayStore(); // dev / single instance
232
- // const replayStore = new RedisReplayStore(redisClient, 'duct:jti:'); // production
233
-
234
- const result = await verifyDeeplinkToken(token, {
235
- secretKey: process.env.DUCT_SECRET_KEY!,
236
- expectedShellId: ductConfig.shellId,
237
- replayStore,
238
- });
239
- ```
240
-
241
- Details: [TOKEN_SPEC.md](./TOKEN_SPEC.md).
242
-
243
- ---
244
-
245
- ## Webhooks
246
-
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.
248
-
249
- ---
250
-
251
- ## Security
252
-
253
- - Keep `DUCT_SECRET_KEY` server-side — never in `NEXT_PUBLIC_*`, `VITE_*`, or client bundles
254
- - Default mutations to `agentAccessible: false` and `sideEffects: true` where appropriate
255
- - Rotate keys in the dashboard if credentials are exposed
256
- - Review agent-accessible actions before production — use the integration prompt at `SITE_URL/docs/integration-prompt`
257
-
258
- ---
259
-
260
- ## Support
261
-
262
- - Docs: `SITE_URL/docs` on your configured deployment
263
- - npm: [@duct-sdk/sdk](https://www.npmjs.com/package/@duct-sdk/sdk)
264
-
1
+ ```
2
+ ██████╗ ██╗ ██╗ ╔██████ ████████╗
3
+ ██╔══██╗ ██║ ██║ ╚════╗██ ╚══██╔══╝
4
+ ██║ ██║ ██║ ██║ ║██ ██║
5
+ ██║ ██║ ██║ ██║ ║██ ██║
6
+ ██████╔╝ ╚██████╔╝ ╔██████╝ ██║
7
+ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝
8
+ ```
9
+
10
+ # @duct-sdk/sdk
11
+
12
+ **Let AI agents use your product's API, under a policy you own.**
13
+
14
+ Duct sits between your existing API and everything that wants to act on it: AI agents, partner integrations, and (optionally) an embedded chat shell for your users. You describe what your API can do and what each caller may do; Duct enforces it on every call, asks a person before anything irreversible, and records an audit trail you can verify.
15
+
16
+ This package is the CLI and the SDK:
17
+
18
+ - **CLI** (`npx @duct-sdk/sdk`) connects your API to Duct, checks your policy, and publishes it.
19
+ - **SDK** helpers for your server (tokens, deep links, receipts) and components for your frontend (the chat shell).
20
+
21
+ Your API and business logic stay where they are. The CLI never calls an LLM and never asks for a model API key.
22
+
23
+ Requires Node.js 20 or later.
24
+
25
+ ---
26
+
27
+ ## Contents
28
+
29
+ - [Quickstart](#quickstart)
30
+ - [Set up with your coding assistant (MCP)](#set-up-with-your-coding-assistant-mcp)
31
+ - [The duct/ project](#the-duct-project)
32
+ - [Act for signed-in users and embed the shell](#act-for-signed-in-users-and-embed-the-shell)
33
+ - [Imports](#imports)
34
+ - [CLI reference](#cli-reference)
35
+ - [Frameworks](#frameworks)
36
+ - [Deep links](#deep-links)
37
+ - [Webhooks](#webhooks)
38
+ - [Receipts and audit evidence](#receipts-and-audit-evidence)
39
+ - [Connecting to your Duct deployment](#connecting-to-your-duct-deployment)
40
+ - [Security](#security)
41
+ - [Troubleshooting](#troubleshooting)
42
+
43
+ ---
44
+
45
+ ## Quickstart
46
+
47
+ From your product's repository:
48
+
49
+ ```bash
50
+ npx @duct-sdk/sdk
51
+ ```
52
+
53
+ That one command:
54
+
55
+ 1. **Signs you in**: it opens your browser to approve this machine.
56
+ 2. **Finds your API description**: an OpenAPI file in the repo, the spec your running API serves, or a Postman collection.
57
+ 3. **Writes `duct/`** with safe defaults:
58
+ - agents may read, with the user's consent;
59
+ - writes stay off for agents until you allow them, and then each one waits for a person to approve;
60
+ - deletes are denied;
61
+ - everything is rate limited.
62
+ 4. **Checks it with Duct**: your policy is evaluated by the same engine that enforces it, and your API is probed for reachability.
63
+ 5. **Publishes it** once the checks pass.
64
+
65
+ No OpenAPI spec? Run `npx @duct-sdk/sdk prompt` and give the instructions it prints to your coding assistant. Or connect the assistant directly over [MCP](#set-up-with-your-coding-assistant-mcp).
66
+
67
+ To change what agents may do later, edit `duct/policy.ts`, then:
68
+
69
+ ```bash
70
+ npx @duct-sdk/sdk test # Duct evaluates the policy you are about to publish
71
+ npx @duct-sdk/sdk push # shows what changes, then publishes
72
+ ```
73
+
74
+ Install it instead of using `npx` if you prefer:
75
+
76
+ ```bash
77
+ npm install @duct-sdk/sdk # in your project; `npx duct <command>`
78
+ npm install -g @duct-sdk/sdk # globally; `duct <command>`
79
+ ```
80
+
81
+ ---
82
+
83
+ ## Set up with your coding assistant (MCP)
84
+
85
+ Two local MCP servers let your coding assistant do the setup with you. They are separate so the assistant only loads the tools it needs at each moment.
86
+
87
+ | Server | Start with | What it does |
88
+ | --- | --- | --- |
89
+ | **duct-onboarding** | `npx @duct-sdk/sdk mcp` | Connects your codebase: finds your API (or reads your routes when there is no spec), writes `duct/`, runs the checks, and publishes after you approve. |
90
+ | **duct-setup** | `npx @duct-sdk/sdk mcp-setup` | Covers the dashboard side: webhook and sign-in URLs, the webhook signing secret, partner profiles, and connection checks. |
91
+
92
+ **Claude Code**
93
+
94
+ ```bash
95
+ claude mcp add duct-onboarding -- npx -y @duct-sdk/sdk mcp
96
+ claude mcp add duct-setup -- npx -y @duct-sdk/sdk mcp-setup
97
+ # On Windows, put `cmd /c` before `npx`.
98
+ ```
99
+
100
+ **Cursor** (`.cursor/mcp.json`) and most other clients:
101
+
102
+ ```json
103
+ {
104
+ "mcpServers": {
105
+ "duct-onboarding": { "command": "npx", "args": ["-y", "@duct-sdk/sdk", "mcp"] },
106
+ "duct-setup": { "command": "npx", "args": ["-y", "@duct-sdk/sdk", "mcp-setup"] }
107
+ }
108
+ }
109
+ ```
110
+
111
+ **VS Code** (`.vscode/mcp.json`):
112
+
113
+ ```json
114
+ {
115
+ "servers": {
116
+ "duct-onboarding": { "type": "stdio", "command": "npx", "args": ["-y", "@duct-sdk/sdk", "mcp"] },
117
+ "duct-setup": { "type": "stdio", "command": "npx", "args": ["-y", "@duct-sdk/sdk", "mcp-setup"] }
118
+ }
119
+ }
120
+ ```
121
+
122
+ Then ask: *"Connect this repo to Duct."* Claude Code also offers it as the `onboard` prompt.
123
+
124
+ **duct-onboarding tools**
125
+
126
+ | Tool | What it does |
127
+ | --- | --- |
128
+ | `duct_status` | Reports whether you are signed in, your shells, any existing `duct/`, and the API specs found. Ends with the next step. |
129
+ | `duct_setup` | Writes `duct/` with safe defaults. It never publishes. |
130
+ | `duct_check` | Runs validation and the Duct checks, and returns a structured report. |
131
+ | `duct_push` | Shows what would change, including warnings. Publishes only when called again with `confirm: true` and that preview's token, after you approve. If `duct/` changed in between, it asks for a new preview. |
132
+ | `duct_add` | Generates the identity or embed wiring for your stack. |
133
+
134
+ **duct-setup tools**
135
+
136
+ | Tool | What it does |
137
+ | --- | --- |
138
+ | `setup_status` | Shows what is configured and what is missing. |
139
+ | `setup_configure` | Sets webhook and sign-in URLs, or creates a signing secret. Previews first, applies after you approve. |
140
+ | `setup_partner` | Creates a partner agent profile with the access you choose. |
141
+ | `setup_check` | Sends test requests to your API and webhooks and explains any failure. |
142
+
143
+ **What the assistant never sees**
144
+
145
+ - **Your key.** Sign in once with `npx @duct-sdk/sdk login` in your own terminal. The key stays on your machine.
146
+ - **Signing secrets.** They are written to a git-ignored `.env.duct.<shell>` file, not shown in the conversation.
147
+
148
+ The assistant never loosens your policy on its own: every change is previewed and applied only after you approve it.
149
+
150
+ ---
151
+
152
+ ## The duct/ project
153
+
154
+ ```
155
+ duct/
156
+ project.ts shell ID, product name, where your API lives
157
+ capabilities.json what your API can do (generated from your spec)
158
+ policy.ts what agents may do (yours to edit)
159
+ tests.ts expectations that `duct test` checks
160
+ ```
161
+
162
+ ```ts
163
+ // duct/policy.ts
164
+ import { definePolicy } from '@duct-sdk/sdk/project';
165
+
166
+ export default definePolicy({
167
+ agents: { access: 'read', deny: ['delete_*'], userConsent: true },
168
+ approveWhen: { create_refund: { amount: { gt: 500 } } },
169
+ limits: { '*': { perMinute: 60 }, send_email: { perHour: 50 } },
170
+ });
171
+ ```
172
+
173
+ - `agents.access`: what agents may do by default: `none`, `read` (the default) or `write`; `deny` blocks actions by name or pattern.
174
+ - `userConsent`: agents act for a user only after that user agrees.
175
+ - `approveWhen`: a person must approve before the action runs, when the condition matches.
176
+ - `limits`: per-action rate limits.
177
+
178
+ `duct push` compiles `duct/` into the manifest Duct enforces. It shows the privilege changes first and refuses to widen agent access unless you pass `--yes`.
179
+
180
+ `duct sync` refreshes `capabilities.json` from your spec and keeps the fields you reviewed. A legacy single-file `duct.config.ts` still works; `duct split` moves it into `duct/` and verifies that enforcement is identical.
181
+
182
+ ---
183
+
184
+ ## Act for signed-in users and embed the shell
185
+
186
+ Agents only need the `duct/` project. Two optional layers add more:
187
+
188
+ ```bash
189
+ npx @duct-sdk/sdk add identity # agents act for your signed-in users
190
+ npx @duct-sdk/sdk add shell # embed the chat shell in your app
191
+ ```
192
+
193
+ They generate up to four pieces in your codebase:
194
+
195
+ | | What | Where |
196
+ | --- | --- | --- |
197
+ | 1 | Token minting | `POST /api/duct/token`, using `generateDuctToken` |
198
+ | 2 | API auth | Your existing auth middleware also accepts Duct's delegated tokens (`verifyDuctToken`) |
199
+ | 3 | Deep link receiver | `POST /api/duct/receive`, using `verifyDeeplinkToken` |
200
+ | 4 | Chat shell | `<DuctShell>` in your root layout |
201
+
202
+ **Embedding the shell by hand** (Next.js App Router):
203
+
204
+ ```tsx
205
+ import { DuctShell } from '@duct-sdk/sdk/next';
206
+
207
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
208
+ return (
209
+ <html>
210
+ <body>
211
+ {children}
212
+ <DuctShell
213
+ shellId={process.env.NEXT_PUBLIC_DUCT_SHELL_ID!}
214
+ shellHost={process.env.NEXT_PUBLIC_DUCT_SHELL_HOST}
215
+ onTokenRequest={async () => {
216
+ const res = await fetch('/api/duct/token', { method: 'POST', credentials: 'include' });
217
+ return (await res.json()).token ?? '';
218
+ }}
219
+ preset="tall"
220
+ position="bottom-right"
221
+ theme="system"
222
+ />
223
+ </body>
224
+ </html>
225
+ );
226
+ }
227
+ ```
228
+
229
+ The shell ID is not a secret, so it may be exposed to the browser under your framework's public prefix ([Frameworks](#frameworks)). The secret key never is.
230
+
231
+ ---
232
+
233
+ ## Imports
234
+
235
+ Use the subpath that matches where the code runs. The root export includes React components and will fail in a plain Node server.
236
+
237
+ | Import | Use for |
238
+ | --- | --- |
239
+ | `@duct-sdk/sdk/project` | `duct/*.ts` files: `defineProject`, `definePolicy`, `defineShell`, `defineTests`. No React. |
240
+ | `@duct-sdk/sdk/server` | Any Node or Edge backend: tokens, deep links, receipts, evidence. No React. |
241
+ | `@duct-sdk/sdk/next` | Next.js App Router |
242
+ | `@duct-sdk/sdk/react` | React without Next.js |
243
+ | `@duct-sdk/sdk/vite` | Vite with an Express backend |
244
+ | `@duct-sdk/sdk/remix` | Remix |
245
+ | `@duct-sdk/sdk/sveltekit` | SvelteKit |
246
+ | `@duct-sdk/sdk` | React server-rendered frontends only; not Express or Fastify APIs |
247
+
248
+ ---
249
+
250
+ ## CLI reference
251
+
252
+ Run any command with `npx @duct-sdk/sdk <command>`, or `duct <command>` when installed.
253
+
254
+ **Connect and publish**
255
+
256
+ | Command | What it does |
257
+ | --- | --- |
258
+ | `duct` / `duct setup` | Find your API, write `duct/`, check it, and publish |
259
+ | `duct test` | Duct checks: reachability, guardrails, and your policy tests |
260
+ | `duct validate` | Local checks only, no network. Fast; good for pre-commit hooks |
261
+ | `duct push` | Compile and publish; shows privilege changes and blocks escalations without `--yes` |
262
+ | `duct sync` | Refresh `capabilities.json` from your spec, keeping reviewed fields |
263
+ | `duct add identity` / `add shell` | Optional layers: act for signed-in users / embed the chat shell |
264
+ | `duct prompt` | Instructions for your coding assistant when there is no OpenAPI spec |
265
+ | `duct split` | Move a legacy `duct.config.ts` into `duct/` (verified identical enforcement) |
266
+
267
+ **Coding assistants**
268
+
269
+ | Command | What it does |
270
+ | --- | --- |
271
+ | `duct mcp` | Start the duct-onboarding MCP server (stdio) |
272
+ | `duct mcp-setup` | Start the duct-setup MCP server (stdio) |
273
+
274
+ **Shells and versions**
275
+
276
+ | Command | What it does |
277
+ | --- | --- |
278
+ | `duct shells list` | List the shells in your workspace |
279
+ | `duct shells create <name>` | Create a shell (prod, staging, dev, or a custom name); credentials go to a git-ignored `.env.duct.<name>` |
280
+ | `duct pull <hash>` | Restore a published version into `duct/` |
281
+ | `duct rollback <hash>` | Make a published version live again, without changing local files |
282
+ | `duct promote --from <shell> --to <shell>` | Copy the live version from one shell to another, for example dev to prod |
283
+
284
+ **Account and environment**
285
+
286
+ | Command | What it does |
287
+ | --- | --- |
288
+ | `duct login` | Sign in through the browser; each machine gets its own key. In CI, set `DUCT_API_KEY` |
289
+ | `duct whoami` / `duct logout` | Show or clear the signed-in account (`~/.duct/auth.json`) |
290
+ | `duct profile` | Switch between Duct deployments (`show`, `list`, `use`, `init`) |
291
+ | `duct env` | Print the resolved Duct service URLs and relevant environment variables |
292
+ | `duct checkup` | Check your environment and connectivity to every Duct service |
293
+ | `duct scan` | Probe your live API and report drift from `duct/` |
294
+ | `duct verify-evidence` | Verify an exported audit evidence bundle offline |
295
+
296
+ `duct init` is deprecated and runs `setup`.
297
+
298
+ ---
299
+
300
+ ## Frameworks
301
+
302
+ | Framework | Import | Public env vars for the browser |
303
+ | --- | --- | --- |
304
+ | Next.js (App Router) | `@duct-sdk/sdk/next` | `NEXT_PUBLIC_DUCT_SHELL_ID`, `NEXT_PUBLIC_DUCT_SHELL_HOST` |
305
+ | Vite | `@duct-sdk/sdk/vite` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
306
+ | Remix | `@duct-sdk/sdk/remix` | `VITE_DUCT_SHELL_ID`, `VITE_DUCT_SHELL_HOST` |
307
+ | SvelteKit | `@duct-sdk/sdk/sveltekit` | `PUBLIC_DUCT_SHELL_ID`, `PUBLIC_DUCT_SHELL_HOST` |
308
+ | React | `@duct-sdk/sdk/react` | Your bundler's public prefix |
309
+ | Express, Fastify, Node | `@duct-sdk/sdk/server` | None; server only |
310
+
311
+ On the server, use `DUCT_SHELL_ID` and `DUCT_SECRET_KEY`. Only the shell ID and host ever get a public prefix.
312
+
313
+ **Token route** (Express):
314
+
315
+ ```ts
316
+ import express from 'express';
317
+ import { generateDuctToken } from '@duct-sdk/sdk/server';
318
+
319
+ router.post('/api/duct/token', express.json(), async (req, res) => {
320
+ if (!req.user) return res.status(401).json({ error: 'unauthenticated' });
321
+ const { token } = await generateDuctToken({
322
+ secretKey: process.env.DUCT_SECRET_KEY!,
323
+ shellId: process.env.DUCT_SHELL_ID!,
324
+ userSession: { id: req.user.id, email: req.user.email },
325
+ expirySeconds: 300,
326
+ });
327
+ res.json({ token });
328
+ });
329
+ ```
330
+
331
+ ---
332
+
333
+ ## Deep links
334
+
335
+ Deep links hand a user from the shell, or from an agent, into the right page of your app. Declare them only for routes you have listed in your project. Your receiver verifies the signed token on the server; never trust raw query parameters.
336
+
337
+ Each token carries a `jti` claim. Pass a `replayStore` so every token works only once:
338
+
339
+ ```ts
340
+ import { verifyDeeplinkToken, createDevReplayStore, RedisReplayStore } from '@duct-sdk/sdk/server';
341
+
342
+ const replayStore = createDevReplayStore(); // development, single instance
343
+ // const replayStore = new RedisReplayStore(redisClient, 'duct:jti:'); // production
344
+
345
+ const result = await verifyDeeplinkToken(token, {
346
+ secretKey: process.env.DUCT_SECRET_KEY!,
347
+ expectedShellId: process.env.DUCT_SHELL_ID!,
348
+ replayStore,
349
+ });
350
+ ```
351
+
352
+ ---
353
+
354
+ ## Webhooks
355
+
356
+ Webhook URLs and the signing secret are set in the dashboard, under the shell's **Settings** and **Credentials**, or by your assistant through `duct-setup`. They are not part of `duct/`.
357
+
358
+ Duct signs each webhook body with HMAC-SHA256 and sends it as `X-Duct-Signature: sha256=<hex>`. Verify it against the raw request body:
359
+
360
+ ```ts
361
+ import { createHmac, timingSafeEqual } from 'node:crypto';
362
+
363
+ function isFromDuct(rawBody: string, header: string | undefined, secret: string): boolean {
364
+ const expected = `sha256=${createHmac('sha256', secret).update(rawBody).digest('hex')}`;
365
+ const a = Buffer.from(header ?? '');
366
+ const b = Buffer.from(expected);
367
+ return a.length === b.length && timingSafeEqual(a, b);
368
+ }
369
+ ```
370
+
371
+ Webhooks are optional; chat and actions work without them.
372
+
373
+ ---
374
+
375
+ ## Receipts and audit evidence
376
+
377
+ Every action Duct runs gets a signed outcome receipt (`rcpt_…`) that you or a partner can check independently:
378
+
379
+ ```ts
380
+ import { verifyReceipt } from '@duct-sdk/sdk/server';
381
+ ```
382
+
383
+ Audit evidence exported from the dashboard can be verified offline with `duct verify-evidence` or `verifyEvidenceBundle()`.
384
+
385
+ Token formats, claims, lifetimes, and verification in other languages are in [TOKEN_SPEC.md](./TOKEN_SPEC.md).
386
+
387
+ ---
388
+
389
+ ## Connecting to your Duct deployment
390
+
391
+ `duct login` saves the deployment's address together with your key, so most people never configure anything else. To point the CLI elsewhere:
392
+
393
+ - **One base URL**: set `DUCT_URL`; service URLs are derived from it.
394
+ - **Individual services**: `DUCT_API_URL`, `DUCT_AUTH_URL`, `DUCT_SHELL_URL`, `DUCT_REGISTRY_URL`, `DUCT_DASHBOARD_URL`.
395
+ - **Several deployments**: `duct profile` (for example `local` and `hosted`).
396
+
397
+ With nothing set, the CLI talks to a local Duct stack. `duct env` shows what it resolved.
398
+
399
+ ---
400
+
401
+ ## Security
402
+
403
+ - **`DUCT_SECRET_KEY` stays on your server.** Never put it in a public env var (`NEXT_PUBLIC_*`, `VITE_*`, `PUBLIC_*`) or a client bundle.
404
+ - **Keep agent access narrow.** Start from the generated defaults and widen it one action at a time. `duct test` shows exactly what agents can reach.
405
+ - **Make irreversible actions wait for a person.** Use `approveWhen` for anything that moves money or deletes data.
406
+ - **Rotate exposed keys right away.** The dashboard's Credentials page rotates the secret key and replaces the webhook signing secret.
407
+
408
+ ---
409
+
410
+ ## Troubleshooting
411
+
412
+ - **`ERR_REQUIRE_ESM` on Node 22**: install the CLI globally (`npm i -g @duct-sdk/sdk`), or run `node --experimental-require-module $(npx --no which duct) <command>`.
413
+ - **"Not signed in"**: run `npx @duct-sdk/sdk login`. In CI, set `DUCT_API_KEY`.
414
+ - **Cannot reach Duct**: run `npx @duct-sdk/sdk checkup` to see which service is unreachable and which URL the CLI used.
415
+
416
+ ---
417
+
418
+ [npm](https://www.npmjs.com/package/@duct-sdk/sdk) · [Changelog](./CHANGELOG.md) · [Token specification](./TOKEN_SPEC.md)