@duct-sdk/sdk 0.2.1 → 0.2.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,43 @@
2
2
 
3
3
  Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
4
 
5
+ ## [0.2.3] — 2026-06-08
6
+
7
+ ### Added
8
+ - `widget.maxToolIterations` and `widget.maxPlanSteps` on `DuctConfig` — configurable agent loop ceilings (defaults 12 / 8).
9
+ - `core/limits.ts` — exported default and hard-ceiling constants for manifest tooling.
10
+ - `duct init --api-spec <path>` now works end-to-end without requiring an LLM.
11
+ A new deterministic OpenAPI parser (`cli/processors/openapi-parser.ts`) maps
12
+ every path + method in an OpenAPI 3.x or Swagger 2.x spec directly to
13
+ `ActionManifest[]` and `RouteManifest[]`:
14
+ - GET operations → `agentAccessible: false` by default (interactive review applies)
15
+ - POST/PUT/PATCH/DELETE → `sideEffects: true`
16
+ - Operations with `operationId` → `confidence: 1.0`; without → `confidence: 0.95`
17
+ - Sensitivity inferred from path + description keywords
18
+ - `x-duct-sensitivity` extension accepted for manual override
19
+ - Internal Duct / NextAuth routes excluded automatically
20
+ - Path + query parameters extracted; `inputSchema` populated from `requestBody`
21
+ - YAML spec support (`.yaml` / `.yml`) via the new `yaml` dependency (v2.x, zero deps).
22
+
23
+ ### Fixed
24
+ - **SDK embed security:** React and Next.js `DuctShell` adapters now validate `event.source === iframe.contentWindow` and reject deeplink URLs that are not same-origin or relative paths.
25
+ - **`pipeline.ts` spec-mode bug:** when `--api-spec` was provided the API agent was
26
+ incorrectly added to the skip list, returning zero actions. The deterministic parser
27
+ now runs directly in the pipeline; the Auth agent still runs in parallel to detect
28
+ auth patterns from project source files.
29
+ - **`pipeline.ts`:** `skipAgents` scope bug — deeplink/review skip flags now work in spec-mode as well as normal mode.
30
+ - **`openapi-parser.ts`:** removed unused parameter.
31
+
32
+ ### Changed
33
+ - `pipeline.ts`: spec-mode and normal-mode are now separate branches in Stage 1.
34
+ Both paths feed the same Deeplink + Reviewer agents in Stage 2 and Stage 3.
35
+
36
+ ## [0.2.2] — 2026-06-07
37
+
38
+ ### Changed
39
+ - `RouteManifest.searchAction` docs updated — runtime now invokes the declared action in-shell for data queries instead of deeplink navigation
40
+ - `dataModel` field docs clarified; entity-resolution runtime wiring tracked separately
41
+
5
42
  ## [0.2.1] — 2026-06-06
6
43
 
7
44
  ### Changed
@@ -122,8 +122,7 @@ export declare function useShellStatus(shellId: string, shellHost?: string): She
122
122
  * const res = await fetch("/api/duct/token", { method: "POST" });
123
123
  * const { token } = await res.json();
124
124
  * return token;
125
- * }}
126
- * />
125
+ * }} />
127
126
  * ```
128
127
  */
129
128
  export declare function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, onPageContext, open, onOpenChange, defaultOpen, shellHost, position, panelWidth, panelHeight, style, className, launcherIconSrc, readyCheck, }: DuctShellProps): React.ReactElement | null;
@@ -58,8 +58,7 @@ const DUCT_LAUNCHER_ICON_LOCAL_FALLBACK = "/assets/logo.png";
58
58
  * const res = await fetch("/api/duct/token", { method: "POST" });
59
59
  * const { token } = await res.json();
60
60
  * return token;
61
- * }}
62
- * />
61
+ * }} />
63
62
  * ```
64
63
  */
65
64
  export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, onPageContext, open, onOpenChange, defaultOpen = false, shellHost = DUCT_SHELL_HOST_DEFAULT, position = "bottom-right", panelWidth = 420, panelHeight = 640, style, className, launcherIconSrc, readyCheck = false, }) {
@@ -127,10 +126,27 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
127
126
  setIsAnimating(false);
128
127
  }, 220);
129
128
  }, [setOpen]);
129
+ const isAllowedDeeplinkUrl = useCallback((url) => {
130
+ if (!url || url.startsWith("//"))
131
+ return false;
132
+ if (url.startsWith("/"))
133
+ return true;
134
+ try {
135
+ const parsed = new URL(url);
136
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
137
+ return false;
138
+ return parsed.origin === window.location.origin;
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }, []);
130
144
  // Handle inbound messages from the iframe
131
145
  const handleMessage = useCallback(async (event) => {
132
146
  if (event.origin !== shellOrigin)
133
147
  return;
148
+ if (event.source !== iframeRef.current?.contentWindow)
149
+ return;
134
150
  if (typeof event.data !== "object" || !event.data?.type)
135
151
  return;
136
152
  const msg = event.data;
@@ -176,6 +192,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
176
192
  }
177
193
  case "DUCT_DEEPLINK_NAVIGATE": {
178
194
  const { url } = msg;
195
+ if (!isAllowedDeeplinkUrl(url))
196
+ break;
179
197
  postToShell({ type: "DUCT_NAVIGATE_CONFIRMED", url });
180
198
  closePanel();
181
199
  // Delay navigation until after the close animation (220ms) so the panel
@@ -206,7 +224,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
206
224
  break;
207
225
  }
208
226
  }
209
- }, [shellOrigin, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel]);
227
+ }, [shellOrigin, isAllowedDeeplinkUrl, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel]);
210
228
  useEffect(() => {
211
229
  window.addEventListener("message", handleMessage);
212
230
  return () => window.removeEventListener("message", handleMessage);
@@ -299,12 +317,20 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
299
317
  e.currentTarget.style.transform = "scale(1)";
300
318
  e.currentTarget.style.boxShadow =
301
319
  "0 4px 16px rgba(0,0,0,0.40), 0 2px 8px rgba(0,0,0,0.20)";
302
- }, children: !iconLoadFailed ? (_jsx("img", { src: currentIconSrc, alt: "Duct", width: 28, height: 28, onError: handleIconError, style: { width: "28px", height: "28px", objectFit: "contain" } })) : (_jsx("svg", { width: "28", height: "28", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: _jsx("path", { d: "M18 12c0-3.3-2.2-5.5-5.5-5.5C9 6.5 7 8.7 7 12s2 5.5 5.5 5.5c2 0 3.6-.8 4.6-2.2l-2.2-1.6c-.6.8-1.4 1.3-2.4 1.3-1.6 0-2.8-1.2-2.8-3s1.2-3 2.8-3c1 0 1.8.5 2.3 1.3L18 12z", fill: "white" }) })) })), _jsx("div", { style: panelStyle, "data-duct-shell": shellId, children: _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: {
320
+ }, children: !iconLoadFailed ? (_jsx("img", { src: currentIconSrc, alt: "Duct", width: 28, height: 28, onError: handleIconError, style: { width: "28px", height: "28px", objectFit: "contain" } })) : (_jsx("svg", { width: "28", height: "28", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: _jsx("path", { d: "M18 12c0-3.3-2.2-5.5-5.5-5.5C9 6.5 7 8.7 7 12s2 5.5 5.5 5.5c2 0 3.6-.8 4.6-2.2l-2.2-1.6c-.6.8-1.4 1.3-2.4 1.3-1.6 0-2.8-1.2-2.8-3s1.2-3 2.8-3c1 0 1.8.5 2.3 1.3L18 12z", fill: "white" }) })) })), _jsx("div", { style: panelStyle, "data-duct-shell": shellId, children: React.createElement("iframe", {
321
+ ref: iframeRef,
322
+ src: shellUrl,
323
+ title: "Duct Shell",
324
+ sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
325
+ allow: "clipboard-write",
326
+ referrerPolicy: "no-referrer-when-downgrade",
327
+ style: {
303
328
  width: "100%",
304
329
  height: "100%",
305
330
  border: "none",
306
331
  display: "block",
307
- }, loading: "lazy" }) })] }));
332
+ },
333
+ }) })] }));
308
334
  }
309
335
  /**
310
336
  * Headless launch button — use when you want a custom trigger.
@@ -134,10 +134,27 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
134
134
  setIsAnimating(false);
135
135
  }, 220);
136
136
  }, [setOpen]);
137
+ const isAllowedDeeplinkUrl = useCallback((url) => {
138
+ if (!url || url.startsWith("//"))
139
+ return false;
140
+ if (url.startsWith("/"))
141
+ return true;
142
+ try {
143
+ const parsed = new URL(url);
144
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
145
+ return false;
146
+ return parsed.origin === window.location.origin;
147
+ }
148
+ catch {
149
+ return false;
150
+ }
151
+ }, []);
137
152
  // Handle inbound messages from the iframe
138
153
  const handleMessage = useCallback(async (event) => {
139
154
  if (event.origin !== shellOrigin)
140
155
  return;
156
+ if (event.source !== iframeRef.current?.contentWindow)
157
+ return;
141
158
  if (typeof event.data !== "object" || !event.data?.type)
142
159
  return;
143
160
  const msg = event.data;
@@ -185,6 +202,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
185
202
  }
186
203
  case "DUCT_DEEPLINK_NAVIGATE": {
187
204
  const { url } = msg;
205
+ if (!isAllowedDeeplinkUrl(url))
206
+ break;
188
207
  postToShell({ type: "DUCT_NAVIGATE_CONFIRMED", url });
189
208
  closePanel();
190
209
  // Delay navigation until after the close animation (220ms) so the panel
@@ -216,7 +235,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
216
235
  break;
217
236
  }
218
237
  }
219
- }, [shellOrigin, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel]);
238
+ }, [shellOrigin, isAllowedDeeplinkUrl, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel]);
220
239
  useEffect(() => {
221
240
  window.addEventListener("message", handleMessage);
222
241
  return () => window.removeEventListener("message", handleMessage);
@@ -315,7 +334,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
315
334
  height: "100%",
316
335
  border: "none",
317
336
  display: "block",
318
- }, loading: "lazy" }) })] }));
337
+ } }) })] }));
319
338
  }
320
339
  /**
321
340
  * Headless launch button — use when you want a custom trigger.
@@ -259,7 +259,7 @@ function rankApiFile(file) {
259
259
  score += 35;
260
260
  if (/route\.(ts|tsx|js|jsx|mjs|cjs)$/.test(normalized))
261
261
  score += 20;
262
- if (/(auth|session|token|profile|user|company|order|payment|checkout)/.test(normalized))
262
+ if (/(auth|session|token|profile|user|resource|entity|webhook|crud)/.test(normalized))
263
263
  score += 10;
264
264
  if (/(\.spec\.|\.test\.|\.mock\.|__tests__|fixtures|examples?)/.test(normalized))
265
265
  score -= 80;
@@ -9,6 +9,7 @@ import { runAuthAgent } from "./auth-agent.js";
9
9
  import { runDeeplinkAgent } from "./deeplink-agent.js";
10
10
  import { runReviewerAgent } from "./reviewer-agent.js";
11
11
  import { applyDeterministicRules } from "../processors/postprocess.js";
12
+ import { parseOpenApiSpec } from "../processors/openapi-parser.js";
12
13
  // ----------------------------------------------------------------
13
14
  // Default emitter (uses Node EventEmitter)
14
15
  // ----------------------------------------------------------------
@@ -95,89 +96,144 @@ function defaultReview() {
95
96
  */
96
97
  export async function runAgentPipeline(sandboxFs, opts = {}) {
97
98
  const { skipAgents: skipAgentsInput = [], emitter, agentTimeout = 120_000, readList, apiSpecContent, apiSpecPath, postProcess = {}, } = opts;
98
- // When an OpenAPI spec is provided, skip Route + API agents entirely —
99
- // the spec is the authoritative source for both routes and actions.
100
- const skipAgents = apiSpecContent
101
- ? [...new Set([...skipAgentsInput, "routes", "actions"])]
102
- : skipAgentsInput;
99
+ const skipAgents = skipAgentsInput;
103
100
  const startTime = Date.now();
104
101
  emitter?.emitEvent({ type: "start", message: "Starting Duct agent pipeline...", progress: 0 });
105
- // ---- Stage 1: Parallel agents ----
102
+ // ---- Stage 1: Routes + Actions + Auth ----
106
103
  let routes;
107
104
  let actions;
108
105
  let auth;
109
- const stage1Agents = [
110
- // Routes
111
- (async () => {
112
- if (skipAgents.includes("routes"))
113
- return defaultRoutes();
114
- emitter?.emitEvent({ type: "agent:start", agent: "RouteAgent", message: "Analyzing routes...", progress: 5 });
115
- try {
116
- const result = await withTimeout(() => runRouteAgent(sandboxFs, readList?.routeFiles), agentTimeout, "RouteAgent");
106
+ if (apiSpecContent) {
107
+ // ── Spec mode: parse deterministically (no LLM needed for routes/actions) ──────
108
+ // Auth agent still runs in parallel since it reads project source files.
109
+ const [specResult, authResult] = await Promise.all([
110
+ (async () => {
117
111
  emitter?.emitEvent({
118
- type: "agent:complete",
119
- agent: "RouteAgent",
120
- message: `Found ${result.length} routes`,
121
- result,
122
- progress: 30,
123
- });
124
- return result;
125
- }
126
- catch (err) {
127
- const error = err instanceof Error ? err : new Error(String(err));
128
- emitter?.emitEvent({ type: "agent:error", agent: "RouteAgent", error, progress: 30 });
129
- return defaultRoutes();
130
- }
131
- })(),
132
- // API/Actions
133
- (async () => {
134
- if (skipAgents.includes("actions"))
135
- return defaultActions();
136
- const apiMsg = apiSpecContent
137
- ? `Parsing OpenAPI spec (${apiSpecPath ?? "openapi"})...`
138
- : "Analyzing API endpoints...";
139
- emitter?.emitEvent({ type: "agent:start", agent: "ApiAgent", message: apiMsg, progress: 5 });
140
- try {
141
- const result = await withTimeout(() => runApiAgent(sandboxFs, readList?.apiFiles, apiSpecContent, apiSpecPath), agentTimeout, "ApiAgent");
142
- emitter?.emitEvent({
143
- type: "agent:complete",
112
+ type: "agent:start",
144
113
  agent: "ApiAgent",
145
- message: `Found ${result.length} actions`,
146
- result,
147
- progress: 30,
114
+ message: `Parsing OpenAPI spec (${apiSpecPath ?? "openapi"})…`,
115
+ progress: 5,
148
116
  });
149
- return result;
150
- }
151
- catch (err) {
152
- const error = err instanceof Error ? err : new Error(String(err));
153
- emitter?.emitEvent({ type: "agent:error", agent: "ApiAgent", error, progress: 30 });
154
- return defaultActions();
155
- }
156
- })(),
157
- // Auth
158
- (async () => {
159
- if (skipAgents.includes("auth"))
160
- return defaultAuth();
161
- emitter?.emitEvent({ type: "agent:start", agent: "AuthAgent", message: "Analyzing auth configuration...", progress: 5 });
162
- try {
163
- const result = await withTimeout(() => runAuthAgent(sandboxFs, readList?.authFiles), agentTimeout, "AuthAgent");
117
+ try {
118
+ const parsed = await parseOpenApiSpec(apiSpecContent, apiSpecPath ?? "openapi.json");
119
+ emitter?.emitEvent({
120
+ type: "agent:complete",
121
+ agent: "ApiAgent",
122
+ message: `Parsed ${parsed.actions.length} actions from OpenAPI ${parsed.specVersion} spec`,
123
+ result: parsed.actions,
124
+ progress: 30,
125
+ });
126
+ return { routes: parsed.routes, actions: parsed.actions };
127
+ }
128
+ catch (err) {
129
+ const error = err instanceof Error ? err : new Error(String(err));
130
+ emitter?.emitEvent({ type: "agent:error", agent: "ApiAgent", error, progress: 30 });
131
+ return { routes: defaultRoutes(), actions: defaultActions() };
132
+ }
133
+ })(),
134
+ (async () => {
135
+ if (skipAgentsInput.includes("auth"))
136
+ return defaultAuth();
164
137
  emitter?.emitEvent({
165
- type: "agent:complete",
138
+ type: "agent:start",
166
139
  agent: "AuthAgent",
167
- message: `Detected auth: ${result.strategy}`,
168
- result,
169
- progress: 30,
140
+ message: "Analyzing auth configuration…",
141
+ progress: 5,
170
142
  });
171
- return result;
172
- }
173
- catch (err) {
174
- const error = err instanceof Error ? err : new Error(String(err));
175
- emitter?.emitEvent({ type: "agent:error", agent: "AuthAgent", error, progress: 30 });
176
- return defaultAuth();
177
- }
178
- })(),
179
- ];
180
- [routes, actions, auth] = await Promise.all(stage1Agents);
143
+ try {
144
+ const result = await withTimeout(() => runAuthAgent(sandboxFs, readList?.authFiles), agentTimeout, "AuthAgent");
145
+ emitter?.emitEvent({
146
+ type: "agent:complete",
147
+ agent: "AuthAgent",
148
+ message: `Detected auth: ${result.strategy}`,
149
+ result,
150
+ progress: 30,
151
+ });
152
+ return result;
153
+ }
154
+ catch (err) {
155
+ const error = err instanceof Error ? err : new Error(String(err));
156
+ emitter?.emitEvent({ type: "agent:error", agent: "AuthAgent", error, progress: 30 });
157
+ return defaultAuth();
158
+ }
159
+ })(),
160
+ ]);
161
+ routes = specResult.routes;
162
+ actions = specResult.actions;
163
+ auth = authResult;
164
+ }
165
+ else {
166
+ // ── Normal mode: full 3-agent parallel stage ────────────────────────────────
167
+ const stage1Agents = [
168
+ // Routes
169
+ (async () => {
170
+ if (skipAgents.includes("routes"))
171
+ return defaultRoutes();
172
+ emitter?.emitEvent({ type: "agent:start", agent: "RouteAgent", message: "Analyzing routes...", progress: 5 });
173
+ try {
174
+ const result = await withTimeout(() => runRouteAgent(sandboxFs, readList?.routeFiles), agentTimeout, "RouteAgent");
175
+ emitter?.emitEvent({
176
+ type: "agent:complete",
177
+ agent: "RouteAgent",
178
+ message: `Found ${result.length} routes`,
179
+ result,
180
+ progress: 30,
181
+ });
182
+ return result;
183
+ }
184
+ catch (err) {
185
+ const error = err instanceof Error ? err : new Error(String(err));
186
+ emitter?.emitEvent({ type: "agent:error", agent: "RouteAgent", error, progress: 30 });
187
+ return defaultRoutes();
188
+ }
189
+ })(),
190
+ // API/Actions
191
+ (async () => {
192
+ if (skipAgents.includes("actions"))
193
+ return defaultActions();
194
+ emitter?.emitEvent({ type: "agent:start", agent: "ApiAgent", message: "Analyzing API endpoints...", progress: 5 });
195
+ try {
196
+ const result = await withTimeout(() => runApiAgent(sandboxFs, readList?.apiFiles), agentTimeout, "ApiAgent");
197
+ emitter?.emitEvent({
198
+ type: "agent:complete",
199
+ agent: "ApiAgent",
200
+ message: `Found ${result.length} actions`,
201
+ result,
202
+ progress: 30,
203
+ });
204
+ return result;
205
+ }
206
+ catch (err) {
207
+ const error = err instanceof Error ? err : new Error(String(err));
208
+ emitter?.emitEvent({ type: "agent:error", agent: "ApiAgent", error, progress: 30 });
209
+ return defaultActions();
210
+ }
211
+ })(),
212
+ // Auth
213
+ (async () => {
214
+ if (skipAgents.includes("auth"))
215
+ return defaultAuth();
216
+ emitter?.emitEvent({ type: "agent:start", agent: "AuthAgent", message: "Analyzing auth configuration...", progress: 5 });
217
+ try {
218
+ const result = await withTimeout(() => runAuthAgent(sandboxFs, readList?.authFiles), agentTimeout, "AuthAgent");
219
+ emitter?.emitEvent({
220
+ type: "agent:complete",
221
+ agent: "AuthAgent",
222
+ message: `Detected auth: ${result.strategy}`,
223
+ result,
224
+ progress: 30,
225
+ });
226
+ return result;
227
+ }
228
+ catch (err) {
229
+ const error = err instanceof Error ? err : new Error(String(err));
230
+ emitter?.emitEvent({ type: "agent:error", agent: "AuthAgent", error, progress: 30 });
231
+ return defaultAuth();
232
+ }
233
+ })(),
234
+ ];
235
+ [routes, actions, auth] = await Promise.all(stage1Agents);
236
+ }
181
237
  // Apply deterministic rules: enforce sideEffects from HTTP method,
182
238
  // derive sensitivityLevel from path/name keywords, and (in yesMode) auto-enable
183
239
  // agentAccessible on safe GET/HEAD with confidence ≥ 0.85.
package/dist/cli/index.js CHANGED
@@ -326,7 +326,7 @@ program
326
326
  });
327
327
  // Topological order for action dependsOn chains (max depth 4).
328
328
  function buildDependsOnOrder(targetId, actions, visited = new Set()) {
329
- if (visited.has(targetId) || visited.size > 4)
329
+ if (visited.has(targetId) || visited.size > 8)
330
330
  return [];
331
331
  visited.add(targetId);
332
332
  const action = actions.find((a) => a.id === targetId);
@@ -385,7 +385,7 @@ function computePrecomputedWorkflows(config) {
385
385
  workflows.push({
386
386
  id: wfId,
387
387
  name: `Execute ${actionLabel}`,
388
- steps: order.slice(0, 4).map((id) => ({ action_id: id })),
388
+ steps: order.slice(0, 8).map((id) => ({ action_id: id })),
389
389
  intent_patterns: action.description ? [action.description] : [actionLabel],
390
390
  });
391
391
  }
package/dist/cli/init.js CHANGED
@@ -598,7 +598,10 @@ export async function runInit(opts = {}) {
598
598
  process.exit(1);
599
599
  }
600
600
  // ---- Step 0.5: Check LLM credentials and prompt if missing ----
601
- if (!noAgents) {
601
+ // Skip the LLM check when --api-spec is provided: the deterministic parser
602
+ // does not require any LLM key, so the pipeline can run without credentials.
603
+ const hasApiSpec = Boolean(opts.apiSpec);
604
+ if (!noAgents && !hasApiSpec) {
602
605
  const canRunAgents = await checkLlmCredentialsAndPrompt(noAgents, yes);
603
606
  if (!canRunAgents) {
604
607
  noAgents = true;
@@ -810,7 +813,7 @@ export async function runInit(opts = {}) {
810
813
  if (apiSpecPath) {
811
814
  try {
812
815
  apiSpecContent = await fs.readFile(apiSpecPath, "utf-8");
813
- console.log(chalk.gray(` Using OpenAPI spec: ${path.relative(cwd, apiSpecPath)} — skipping Route + API agents\n`));
816
+ console.log(chalk.gray(` Using OpenAPI spec: ${path.relative(cwd, apiSpecPath)} — deterministic parse, no LLM needed\n`));
814
817
  }
815
818
  catch {
816
819
  console.log(chalk.yellow(` ⚠ Could not read --api-spec file: ${opts.apiSpec}. Falling back to agent scan.\n`));
@@ -0,0 +1,27 @@
1
+ import type { ActionManifest, RouteManifest } from "../../core/types.js";
2
+ export interface OpenApiParseResult {
3
+ actions: ActionManifest[];
4
+ routes: RouteManifest[];
5
+ /** Version string from the spec (e.g., "3.0.3" or "2.0") */
6
+ specVersion: string;
7
+ /** Total number of operations found in the spec */
8
+ operationCount: number;
9
+ /** Title from spec info block */
10
+ title?: string;
11
+ }
12
+ /**
13
+ * Parse an OpenAPI 3.x or Swagger 2.x spec file deterministically.
14
+ * No LLM is required — all results come directly from the spec structure.
15
+ *
16
+ * Rules applied:
17
+ * - GET operations → agentAccessible remains false (review step decides)
18
+ * - POST/PUT/PATCH/DELETE → sideEffects: true
19
+ * - Operations with operationId → confidence: 1.0
20
+ * - Operations without operationId → confidence: 0.95
21
+ * - Sensitivity inferred from path + description keywords
22
+ * - Internal Duct/NextAuth routes are excluded automatically
23
+ *
24
+ * @param content Raw spec content string (JSON or YAML)
25
+ * @param filePath File path — used for evidence labels and YAML detection
26
+ */
27
+ export declare function parseOpenApiSpec(content: string, filePath?: string): Promise<OpenApiParseResult>;
@@ -0,0 +1,309 @@
1
+ // ============================================================
2
+ // @duct/sdk — Deterministic OpenAPI Spec Parser
3
+ // Parses OpenAPI 3.x / Swagger 2.x specs into ActionManifest[]
4
+ // and RouteManifest[] without requiring an LLM.
5
+ //
6
+ // Supported formats: JSON (.json) and YAML (.yaml / .yml)
7
+ // YAML requires the `yaml` npm package (listed in dependencies).
8
+ // ============================================================
9
+ // ----------------------------------------------------------------
10
+ // Constants
11
+ // ----------------------------------------------------------------
12
+ const SUPPORTED_METHODS = ["get", "post", "put", "patch", "delete", "head"];
13
+ const SIDE_EFFECT_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
14
+ const VALID_SENSITIVITY_LEVELS = new Set(["none", "low", "medium", "high", "critical"]);
15
+ // ----------------------------------------------------------------
16
+ // Helpers
17
+ // ----------------------------------------------------------------
18
+ function toSnakeCase(str) {
19
+ return str
20
+ .toLowerCase()
21
+ .replace(/[^a-z0-9]/g, "_")
22
+ .replace(/_+/g, "_")
23
+ .replace(/^_|_$/g, "");
24
+ }
25
+ function deriveActionId(operationId, method, path) {
26
+ if (operationId?.trim())
27
+ return toSnakeCase(operationId.trim());
28
+ // Derive from method + path: GET /users/{userId}/orders → get_users_user_id_orders
29
+ const pathPart = path
30
+ .replace(/\{([^}]+)\}/g, (_, name) => name)
31
+ .replace(/[^a-zA-Z0-9]+/g, "_")
32
+ .replace(/^_|_$/g, "");
33
+ return toSnakeCase(`${method}_${pathPart}`);
34
+ }
35
+ function inferSensitivityLevel(path, description, xDuctSensitivity) {
36
+ if (xDuctSensitivity && VALID_SENSITIVITY_LEVELS.has(xDuctSensitivity)) {
37
+ return xDuctSensitivity;
38
+ }
39
+ const combined = `${path} ${description}`.toLowerCase();
40
+ if (/password|secret|ssn|credit[-.]?card|billing|private.key|api.key/.test(combined))
41
+ return "high";
42
+ if (/admin|sudo|superuser|impersonate/.test(combined))
43
+ return "high";
44
+ if (/payment|bank|invoice|subscription|financial.?(data|record|statement|transaction)/.test(combined))
45
+ return "medium";
46
+ if (/email|phone|address|profile|personal|pii/.test(combined))
47
+ return "medium";
48
+ return "low";
49
+ }
50
+ function mapJsonType(type) {
51
+ const t = Array.isArray(type)
52
+ ? (type.find((x) => x !== "null") ?? "string")
53
+ : (type ?? "string");
54
+ switch (t) {
55
+ case "integer":
56
+ case "number":
57
+ return "number";
58
+ case "boolean":
59
+ return "boolean";
60
+ case "object":
61
+ return "object";
62
+ case "array":
63
+ return "array";
64
+ default:
65
+ return "string";
66
+ }
67
+ }
68
+ function normalizePath(rawPath) {
69
+ return rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
70
+ }
71
+ function isInternalRoute(path) {
72
+ const p = path.toLowerCase();
73
+ return (p.startsWith("/api/auth/") ||
74
+ p.startsWith("/api/duct/") ||
75
+ p.startsWith("/_next/") ||
76
+ p === "/_next" ||
77
+ p.startsWith("/api/_"));
78
+ }
79
+ function isValidSpecPath(path) {
80
+ if (!path.startsWith("/"))
81
+ return false;
82
+ if (/\s/.test(path))
83
+ return false;
84
+ // Allow alphanumeric, hyphens, dots, slashes, colons, brackets (OpenAPI params)
85
+ return /^[\w\-./:{[\]()]+$/.test(path);
86
+ }
87
+ function operationHasSecurityRequirement(operation, spec) {
88
+ // Explicit empty array on operation = "no auth required" override
89
+ if (Array.isArray(operation.security)) {
90
+ return operation.security.length > 0;
91
+ }
92
+ // Fall back to global security definitions presence
93
+ const hasGlobalSchemes = (spec.components?.securitySchemes != null &&
94
+ Object.keys(spec.components.securitySchemes).length > 0) ||
95
+ (spec.securityDefinitions != null &&
96
+ Object.keys(spec.securityDefinitions).length > 0);
97
+ return hasGlobalSchemes;
98
+ }
99
+ function extractParams(parameters, requestBody) {
100
+ const params = [];
101
+ let inputSchema;
102
+ for (const param of parameters) {
103
+ if (param.in === "header" || param.in === "cookie")
104
+ continue;
105
+ // Swagger 2.x body/formData parameters — extract schema properties
106
+ if (param.in === "body" || param.in === "formData") {
107
+ if (param.schema?.properties) {
108
+ const requiredFields = new Set(param.schema.required ?? []);
109
+ inputSchema = param.schema;
110
+ for (const [name, propSchema] of Object.entries(param.schema.properties)) {
111
+ if (params.some((p) => p.name === name))
112
+ continue;
113
+ params.push({
114
+ name,
115
+ type: mapJsonType(propSchema.type),
116
+ required: requiredFields.has(name),
117
+ description: propSchema.description,
118
+ });
119
+ }
120
+ }
121
+ continue;
122
+ }
123
+ params.push({
124
+ name: param.name,
125
+ type: mapJsonType(param.schema?.type ?? param.type),
126
+ required: param.required ?? (param.in === "path"),
127
+ description: param.description,
128
+ });
129
+ }
130
+ // OpenAPI 3.x requestBody
131
+ if (requestBody?.content) {
132
+ const jsonContent = requestBody.content["application/json"];
133
+ const schema = jsonContent?.schema;
134
+ if (schema) {
135
+ inputSchema = schema;
136
+ if (schema.properties) {
137
+ const requiredFields = new Set(schema.required ?? []);
138
+ for (const [name, propSchema] of Object.entries(schema.properties)) {
139
+ if (params.some((p) => p.name === name))
140
+ continue;
141
+ params.push({
142
+ name,
143
+ type: mapJsonType(propSchema.type),
144
+ required: requiredFields.has(name) || (requestBody.required ?? false),
145
+ description: propSchema.description,
146
+ });
147
+ }
148
+ }
149
+ }
150
+ }
151
+ return { params, inputSchema };
152
+ }
153
+ // ----------------------------------------------------------------
154
+ // YAML / JSON content parser
155
+ // ----------------------------------------------------------------
156
+ async function parseContent(content, filePath) {
157
+ const lowerPath = filePath.toLowerCase();
158
+ const isYaml = lowerPath.endsWith(".yaml") || lowerPath.endsWith(".yml");
159
+ if (isYaml) {
160
+ try {
161
+ // Dynamic import so the yaml package is only loaded when needed
162
+ const yamlModule = await import("yaml");
163
+ const parsed = yamlModule.parse(content);
164
+ if (typeof parsed === "object" && parsed !== null) {
165
+ return parsed;
166
+ }
167
+ throw new Error("YAML parse produced a non-object value");
168
+ }
169
+ catch (yamlErr) {
170
+ // Attempt JSON fallback in case the file extension is misleading
171
+ try {
172
+ return JSON.parse(content);
173
+ }
174
+ catch {
175
+ // Re-throw the original YAML error for a clear message
176
+ throw yamlErr;
177
+ }
178
+ }
179
+ }
180
+ // JSON (or unrecognized extension — try JSON first)
181
+ return JSON.parse(content);
182
+ }
183
+ // ----------------------------------------------------------------
184
+ // parseOpenApiSpec — main entry point
185
+ // ----------------------------------------------------------------
186
+ /**
187
+ * Parse an OpenAPI 3.x or Swagger 2.x spec file deterministically.
188
+ * No LLM is required — all results come directly from the spec structure.
189
+ *
190
+ * Rules applied:
191
+ * - GET operations → agentAccessible remains false (review step decides)
192
+ * - POST/PUT/PATCH/DELETE → sideEffects: true
193
+ * - Operations with operationId → confidence: 1.0
194
+ * - Operations without operationId → confidence: 0.95
195
+ * - Sensitivity inferred from path + description keywords
196
+ * - Internal Duct/NextAuth routes are excluded automatically
197
+ *
198
+ * @param content Raw spec content string (JSON or YAML)
199
+ * @param filePath File path — used for evidence labels and YAML detection
200
+ */
201
+ export async function parseOpenApiSpec(content, filePath = "openapi.json") {
202
+ let raw;
203
+ try {
204
+ raw = await parseContent(content, filePath);
205
+ }
206
+ catch (err) {
207
+ throw new Error(`Could not parse OpenAPI spec "${filePath}": ${err instanceof Error ? err.message : String(err)}`);
208
+ }
209
+ const spec = raw;
210
+ const specVersion = spec.openapi ?? spec.swagger ?? "unknown";
211
+ const title = spec.info?.title;
212
+ const actions = [];
213
+ const routes = [];
214
+ const seen = new Set(); // deduplicate by METHOD:path
215
+ let operationCount = 0;
216
+ const paths = (spec.paths ?? {});
217
+ for (const [rawPath, pathItem] of Object.entries(paths)) {
218
+ if (typeof pathItem !== "object" || pathItem === null)
219
+ continue;
220
+ const normalizedPath = normalizePath(rawPath);
221
+ if (!isValidSpecPath(normalizedPath))
222
+ continue;
223
+ if (isInternalRoute(normalizedPath))
224
+ continue;
225
+ // Path-level parameters are merged with each operation's own params
226
+ const pathLevelParams = Array.isArray(pathItem.parameters)
227
+ ? pathItem.parameters
228
+ : [];
229
+ for (const method of SUPPORTED_METHODS) {
230
+ const operation = pathItem[method];
231
+ if (!operation || typeof operation !== "object")
232
+ continue;
233
+ operationCount++;
234
+ const upperMethod = method.toUpperCase();
235
+ // Merge path-level params (operation params override by name+in)
236
+ const opParams = Array.isArray(operation.parameters)
237
+ ? operation.parameters
238
+ : [];
239
+ const mergedParams = [...pathLevelParams];
240
+ for (const p of opParams) {
241
+ const idx = mergedParams.findIndex((mp) => mp.name === p.name && mp.in === p.in);
242
+ if (idx >= 0)
243
+ mergedParams[idx] = p;
244
+ else
245
+ mergedParams.push(p);
246
+ }
247
+ const description = operation.summary ??
248
+ operation.description ??
249
+ `${upperMethod} ${normalizedPath}`;
250
+ const { params, inputSchema } = extractParams(mergedParams, operation.requestBody);
251
+ const id = deriveActionId(operation.operationId, method, normalizedPath);
252
+ const sideEffects = SIDE_EFFECT_METHODS.has(upperMethod);
253
+ const confidence = operation.operationId?.trim() ? 1.0 : 0.95;
254
+ const sensitivityLevel = inferSensitivityLevel(normalizedPath, description, operation["x-duct-sensitivity"]);
255
+ const requiresAuth = operationHasSecurityRequirement(operation, spec);
256
+ const dedupeKey = `${upperMethod}:${normalizedPath}`;
257
+ if (seen.has(dedupeKey))
258
+ continue;
259
+ seen.add(dedupeKey);
260
+ const actionName = operation.summary ??
261
+ id.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
262
+ actions.push({
263
+ id,
264
+ name: actionName,
265
+ description,
266
+ method: upperMethod,
267
+ path: normalizedPath,
268
+ agentAccessible: false, // always off by default; interactive review step sets this
269
+ sideEffects,
270
+ sensitivityLevel,
271
+ params,
272
+ inputSchema,
273
+ requiresAuth,
274
+ confidence,
275
+ evidence: [`${filePath}#/paths${rawPath}/${method}`],
276
+ });
277
+ // Emit a RouteManifest for GET endpoints (navigable by the shell)
278
+ if (upperMethod === "GET") {
279
+ routes.push({
280
+ path: normalizedPath,
281
+ name: actionName,
282
+ description,
283
+ params: mergedParams
284
+ .filter((p) => p.in === "path")
285
+ .map((p) => ({
286
+ name: p.name,
287
+ type: "string",
288
+ required: true,
289
+ description: p.description,
290
+ })),
291
+ queryParams: mergedParams
292
+ .filter((p) => p.in === "query")
293
+ .map((p) => ({
294
+ name: p.name,
295
+ type: "string",
296
+ required: p.required ?? false,
297
+ description: p.description,
298
+ })),
299
+ uiStateHint: "list",
300
+ requiresAuth,
301
+ deeplinkable: false,
302
+ confidence,
303
+ evidence: [`${filePath}#/paths${rawPath}/get`],
304
+ });
305
+ }
306
+ }
307
+ }
308
+ return { actions, routes, specVersion, operationCount, title };
309
+ }
@@ -40,7 +40,7 @@ const MEDIUM_SENSITIVITY_PATTERNS = [
40
40
  /\bsettings\b/i,
41
41
  /\bpreferences\b/i,
42
42
  /\bsubscription\b/i,
43
- /\border\b/i,
43
+ /\b(purchase.?order|sales.?order|work.?order)\b/i,
44
44
  /\bcheckout\b/i,
45
45
  /\bpurchase\b/i,
46
46
  ];
@@ -0,0 +1,5 @@
1
+ /** Default agent loop ceilings used in widget manifest defaults. */
2
+ export declare const DEFAULT_MAX_TOOL_ITERATIONS = 12;
3
+ export declare const DEFAULT_MAX_PLAN_STEPS = 8;
4
+ export declare const HARD_CEILING_TOOL_ITERATIONS = 25;
5
+ export declare const HARD_CEILING_PLAN_STEPS = 12;
@@ -0,0 +1,5 @@
1
+ /** Default agent loop ceilings used in widget manifest defaults. */
2
+ export const DEFAULT_MAX_TOOL_ITERATIONS = 12;
3
+ export const DEFAULT_MAX_PLAN_STEPS = 8;
4
+ export const HARD_CEILING_TOOL_ITERATIONS = 25;
5
+ export const HARD_CEILING_PLAN_STEPS = 12;
@@ -38,8 +38,8 @@ export interface RouteManifest {
38
38
  evidence?: string[];
39
39
  /**
40
40
  * Maps URL query params to an action for structured data access.
41
- * Used by the shell to call a search action instead of scraping HTML.
42
- * [NOT YET IMPLEMENTED in shell runtime]
41
+ * When set, the shell invokes this action instead of firing a deeplink handoff
42
+ * for data_query intents on this route — keeping users in-shell with rich results.
43
43
  */
44
44
  searchAction?: {
45
45
  actionId: string;
@@ -221,6 +221,15 @@ export interface WidgetConfig {
221
221
  * Set to 0 to disable compaction entirely.
222
222
  */
223
223
  compactionTurns?: number;
224
+ /**
225
+ * Max tool-call loop iterations per user turn (default 12, hard ceiling 25).
226
+ * Loop also stops on duplicate invocations, stagnation, or wall-clock budget.
227
+ */
228
+ maxToolIterations?: number;
229
+ /**
230
+ * Max sequential plan / dependsOn steps per turn (default 8, hard ceiling 12).
231
+ */
232
+ maxPlanSteps?: number;
224
233
  /** Theme override — 'light' | 'dark' | 'system' */
225
234
  theme?: 'light' | 'dark' | 'system';
226
235
  }
@@ -321,9 +330,9 @@ export interface DuctConfig {
321
330
  /** Shell widget display config */
322
331
  widget?: WidgetConfig;
323
332
  /**
324
- * Backend data entity declarations for Backend Intelligence.
325
- * Links entity types to their discovery/fetch actions.
326
- * [NOT YET IMPLEMENTED in shell runtime — see BACKEND_INTELLIGENCE.md]
333
+ * Backend data entity declarations — links entity types to discovery/fetch actions.
334
+ * Powers automatic entity resolution in multi-step agent loops.
335
+ * Declare your entities now; runtime enforcement is in active development.
327
336
  */
328
337
  dataModel?: DataModel;
329
338
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duct-sdk/sdk",
3
- "version": "0.2.1",
3
+ "version": "0.2.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",
@@ -32,7 +32,8 @@
32
32
  "inquirer": "^9.0.0",
33
33
  "zod": "^3.0.0",
34
34
  "node-fetch": "^3.0.0",
35
- "glob": "^10.0.0"
35
+ "glob": "^10.0.0",
36
+ "yaml": "^2.0.0"
36
37
  },
37
38
  "devDependencies": {
38
39
  "typescript": "^5.0.0",