@duct-sdk/sdk 0.3.8 → 0.3.11

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,25 @@
2
2
 
3
3
  Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
4
 
5
+ ## [0.3.11] — 2026-06-16
6
+
7
+ ### Fixed
8
+ - **Panel drag handle (light theme)** — grab bar uses a solid mid-gray with subtle shadow instead of 20% black, so it stays visible on light shell headers.
9
+
10
+ ## [0.3.10] — 2026-06-16
11
+
12
+ ### Improved
13
+ - **`duct init` shell generator** — `DuctShellEmbed` now passes `theme` from `duct.config.ts` → `widget.theme`; Svelte/Vue/Nuxt iframe URLs include `?theme=` so the hosted shell matches before push.
14
+
15
+ ## [0.3.9] — 2026-06-14
16
+
17
+ ### Added
18
+ - **`duct init --curl-collection`** — import actions from curl scripts or Postman Collection v2.1 JSON (deterministic, no LLM)
19
+ - **`core/auth-boundaries.ts`** — shared helpers for action-definition fingerprints and risk-tiered scope checks (aligned with Duct platform auth validation)
20
+
21
+ ### Improved
22
+ - **OpenAPI import** — `$ref` resolution for requestBody schemas; tag-based action ID derivation; collision suffixes; lower confidence when `operationId` is absent
23
+
5
24
  ## [0.3.8] — 2026-06-11
6
25
 
7
26
  ### Fixed
@@ -5,7 +5,7 @@
5
5
  "use client";
6
6
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
7
7
  import React, { useEffect, useRef, useCallback, useMemo, useState, } from "react";
8
- import { resolveShellDimensions, } from "../../core/types.js";
8
+ import { resolveShellDimensions, SHELL_PANEL_VIEWPORT_INSETS, } from "../../core/types.js";
9
9
  /**
10
10
  * Hook that polls the shell status endpoint once on mount.
11
11
  * Use when you need to conditionally render UI based on shell liveness.
@@ -62,10 +62,16 @@ function clampBubble(x, y) {
62
62
  y: Math.min(Math.max(margin, y), Math.max(margin, maxY)),
63
63
  };
64
64
  }
65
+ /** Visible grab-bar on light panels (solid beats low-alpha rgba on variable iframe headers). */
66
+ function dragHandleBarColor(isDark, hovered) {
67
+ if (isDark)
68
+ return hovered ? "rgba(255,255,255,0.38)" : "rgba(255,255,255,0.32)";
69
+ return hovered ? "#524E48" : "#635F59";
70
+ }
65
71
  /** Top grab handle for the open panel — with theme-aware hover tooltip. */
66
72
  function ShellDragHandle({ onPointerDown, isDragging, isDark, label = "Drag to move", style, }) {
67
73
  const [hovered, setHovered] = useState(false);
68
- const barColor = isDark ? "rgba(255,255,255,0.28)" : "rgba(12,11,9,0.20)";
74
+ const barColor = dragHandleBarColor(isDark, hovered);
69
75
  const showTip = hovered && !isDragging;
70
76
  return (_jsxs("div", { role: "button", tabIndex: -1, onPointerDown: onPointerDown, "aria-label": label, onMouseEnter: () => setHovered(true), onMouseLeave: () => setHovered(false), style: {
71
77
  position: "absolute",
@@ -84,9 +90,10 @@ function ShellDragHandle({ onPointerDown, isDragging, isDark, label = "Drag to m
84
90
  ...style,
85
91
  }, children: [_jsx("div", { "aria-hidden": "true", style: {
86
92
  width: 32,
87
- height: 4,
93
+ height: isDark ? 4 : 5,
88
94
  borderRadius: 2,
89
95
  backgroundColor: barColor,
96
+ boxShadow: isDark ? undefined : "0 1px 2px rgba(12,11,9,0.12)",
90
97
  } }), showTip && (_jsx("div", { role: "tooltip", style: {
91
98
  position: "absolute",
92
99
  top: "100%",
@@ -536,6 +543,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
536
543
  });
537
544
  const widthVal = typeof presetDims.width === "number" ? `${presetDims.width}px` : presetDims.width;
538
545
  const heightVal = typeof presetDims.height === "number" ? `${presetDims.height}px` : presetDims.height;
546
+ const panelWidthInset = SHELL_PANEL_VIEWPORT_INSETS.width;
547
+ const panelHeightInset = SHELL_PANEL_VIEWPORT_INSETS.height;
539
548
  // Bubble + panel placement. When the bubble has been dragged we anchor the
540
549
  // panel to the bubble; otherwise we use the default corner.
541
550
  const dragged = bubblePos !== null;
@@ -562,8 +571,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
562
571
  const panelStyle = {
563
572
  position: "fixed",
564
573
  ...(panelPos ? { left: `${panelPos.x}px`, top: `${panelPos.y}px` } : panelAnchor),
565
- width: `min(${widthVal}, calc(100vw - 32px))`,
566
- height: `min(${heightVal}, calc(100dvh - 96px))`,
574
+ width: `min(${widthVal}, calc(100vw - ${panelWidthInset}px))`,
575
+ height: `min(${heightVal}, calc(100dvh - ${panelHeightInset}px))`,
567
576
  zIndex: 9998,
568
577
  borderRadius: "16px",
569
578
  overflow: "hidden",
@@ -22,6 +22,11 @@ export interface PipelineOptions {
22
22
  apiSpecContent?: string;
23
23
  /** Path label for the spec file (used in prompt context). */
24
24
  apiSpecPath?: string;
25
+ /**
26
+ * Raw content of a cURL script or Postman collection (from --curl-collection flag).
27
+ */
28
+ curlCollectionContent?: string;
29
+ curlCollectionPath?: string;
25
30
  /** Options passed to the deterministic post-processing step. */
26
31
  postProcess?: PostProcessOptions;
27
32
  }
@@ -10,6 +10,7 @@ import { runDeeplinkAgent } from "./deeplink-agent.js";
10
10
  import { runReviewerAgent } from "./reviewer-agent.js";
11
11
  import { applyDeterministicRules } from "../processors/postprocess.js";
12
12
  import { parseOpenApiSpec } from "../processors/openapi-parser.js";
13
+ import { parseCurlCollection } from "../processors/curl-parser.js";
13
14
  // ----------------------------------------------------------------
14
15
  // Default emitter (uses Node EventEmitter)
15
16
  // ----------------------------------------------------------------
@@ -95,7 +96,7 @@ function defaultReview() {
95
96
  * @returns PipelineResult with all agent outputs
96
97
  */
97
98
  export async function runAgentPipeline(sandboxFs, opts = {}) {
98
- const { skipAgents: skipAgentsInput = [], emitter, agentTimeout = 120_000, readList, apiSpecContent, apiSpecPath, postProcess = {}, } = opts;
99
+ const { skipAgents: skipAgentsInput = [], emitter, agentTimeout = 120_000, readList, apiSpecContent, apiSpecPath, curlCollectionContent, curlCollectionPath, postProcess = {}, } = opts;
99
100
  const skipAgents = skipAgentsInput;
100
101
  const startTime = Date.now();
101
102
  emitter?.emitEvent({ type: "start", message: "Starting Duct agent pipeline...", progress: 0 });
@@ -103,7 +104,64 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
103
104
  let routes;
104
105
  let actions;
105
106
  let auth;
106
- if (apiSpecContent) {
107
+ if (curlCollectionContent) {
108
+ const [curlResult, authResult] = await Promise.all([
109
+ (async () => {
110
+ emitter?.emitEvent({
111
+ type: "agent:start",
112
+ agent: "ApiAgent",
113
+ message: `Parsing cURL collection (${curlCollectionPath ?? "curl"})…`,
114
+ progress: 5,
115
+ });
116
+ try {
117
+ const parsed = await parseCurlCollection(curlCollectionContent, curlCollectionPath ?? "curl-collection.sh");
118
+ emitter?.emitEvent({
119
+ type: "agent:complete",
120
+ agent: "ApiAgent",
121
+ message: `Parsed ${parsed.actions.length} actions from ${parsed.requestCount} requests`,
122
+ result: parsed.actions,
123
+ progress: 30,
124
+ });
125
+ return { routes: parsed.routes, actions: parsed.actions };
126
+ }
127
+ catch (err) {
128
+ const error = err instanceof Error ? err : new Error(String(err));
129
+ emitter?.emitEvent({ type: "agent:error", agent: "ApiAgent", error, progress: 30 });
130
+ return { routes: defaultRoutes(), actions: defaultActions() };
131
+ }
132
+ })(),
133
+ (async () => {
134
+ if (skipAgentsInput.includes("auth"))
135
+ return defaultAuth();
136
+ emitter?.emitEvent({
137
+ type: "agent:start",
138
+ agent: "AuthAgent",
139
+ message: "Analyzing auth configuration…",
140
+ progress: 5,
141
+ });
142
+ try {
143
+ const result = await withTimeout(() => runAuthAgent(sandboxFs, readList?.authFiles), agentTimeout, "AuthAgent");
144
+ emitter?.emitEvent({
145
+ type: "agent:complete",
146
+ agent: "AuthAgent",
147
+ message: `Detected auth: ${result.strategy}`,
148
+ result,
149
+ progress: 30,
150
+ });
151
+ return result;
152
+ }
153
+ catch (err) {
154
+ const error = err instanceof Error ? err : new Error(String(err));
155
+ emitter?.emitEvent({ type: "agent:error", agent: "AuthAgent", error, progress: 30 });
156
+ return defaultAuth();
157
+ }
158
+ })(),
159
+ ]);
160
+ routes = curlResult.routes;
161
+ actions = curlResult.actions;
162
+ auth = authResult;
163
+ }
164
+ else if (apiSpecContent) {
107
165
  // ── Spec mode: parse deterministically (no LLM needed for routes/actions) ──────
108
166
  // Auth agent still runs in parallel since it reads project source files.
109
167
  const [specResult, authResult] = await Promise.all([
@@ -2,12 +2,27 @@
2
2
  // @duct/sdk — Shell Component Generator
3
3
  // Generates framework-specific shell embed components
4
4
  // ============================================================
5
+ function widgetTheme(config) {
6
+ const t = config.widget?.theme;
7
+ if (t === "light" || t === "dark" || t === "system")
8
+ return t;
9
+ return "system";
10
+ }
11
+ /** DuctShell `theme` prop line — launcher chrome; chat surface uses manifest.widget.theme from duct push. */
12
+ function ductShellThemeProp(config, indent = " ") {
13
+ return `${indent}theme="${widgetTheme(config)}"`;
14
+ }
15
+ /** Iframe src query string so hosted shell matches widget.theme before/at push time. */
16
+ function shellThemeQuery(config) {
17
+ return `?theme=${widgetTheme(config)}`;
18
+ }
5
19
  // ----------------------------------------------------------------
6
20
  // Next.js / React shell component
7
21
  // ----------------------------------------------------------------
8
22
  function generateReactShellComponent(config) {
9
23
  const position = config.widget?.position ?? "bottom-right";
10
24
  const preset = config.widget?.preset ?? "tall";
25
+ const themeProp = ductShellThemeProp(config);
11
26
  const docsBase = config.product?.baseUrl
12
27
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
13
28
  : 'http://localhost:3005/docs';
@@ -35,6 +50,7 @@ export function DuctShellEmbed() {
35
50
  shellHost={shellHost}
36
51
  position="${position}"
37
52
  preset="${preset}"
53
+ ${themeProp}
38
54
  // Size preset: "tall" (vertical), "square" (Copilot-style), or "large".
39
55
  // The bubble and opened panel are draggable; \`position\` only sets the starting corner.
40
56
  // Optional: provide user context (not sensitive — this is metadata for the shell UI)
@@ -149,6 +165,7 @@ export default function RootLayout({
149
165
  function generateRemixShellComponent(config) {
150
166
  const position = config.widget?.position ?? "bottom-right";
151
167
  const preset = config.widget?.preset ?? "tall";
168
+ const themeProp = ductShellThemeProp(config);
152
169
  const docsBase = config.product?.baseUrl
153
170
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
154
171
  : 'http://localhost:3005/docs';
@@ -174,6 +191,7 @@ export function DuctShellEmbed() {
174
191
  shellHost={shellHost}
175
192
  position="${position}"
176
193
  preset="${preset}"
194
+ ${themeProp}
177
195
  onTokenRequest={async (shellId) => {
178
196
  const res = await fetch("/api/duct/token", {
179
197
  method: "POST",
@@ -202,6 +220,7 @@ export function DuctShellEmbed() {
202
220
  function generateViteShellComponent(config) {
203
221
  const position = config.widget?.position ?? "bottom-right";
204
222
  const preset = config.widget?.preset ?? "tall";
223
+ const themeProp = ductShellThemeProp(config);
205
224
  const docsBase = config.product?.baseUrl
206
225
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
207
226
  : 'http://localhost:3005/docs';
@@ -227,6 +246,7 @@ export function DuctShellEmbed() {
227
246
  shellHost={shellHost}
228
247
  position="${position}"
229
248
  preset="${preset}"
249
+ ${themeProp}
230
250
  onTokenRequest={async (shellId) => {
231
251
  const res = await fetch("/api/duct/token", {
232
252
  method: "POST",
@@ -312,6 +332,7 @@ export function getEnvTemplateName(framework) {
312
332
  // SvelteKit shell component
313
333
  // ----------------------------------------------------------------
314
334
  function generateSvelteKitShellComponent(config) {
335
+ const themeQuery = shellThemeQuery(config);
315
336
  const docsBase = config.product?.baseUrl
316
337
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
317
338
  : 'http://localhost:3005/docs';
@@ -333,7 +354,7 @@ function generateSvelteKitShellComponent(config) {
333
354
 
334
355
  const shellId = env.PUBLIC_DUCT_SHELL_ID ?? "";
335
356
  const shellHost = env.PUBLIC_DUCT_SHELL_HOST ?? "http://localhost:3000";
336
- const shellUrl = \`\${shellHost}/\${shellId}\`;
357
+ const shellUrl = \`\${shellHost}/\${shellId}${themeQuery}\`;
337
358
 
338
359
  async function getToken(): Promise<string> {
339
360
  const res = await fetch("/api/duct/token", {
@@ -420,6 +441,7 @@ function generateVue3ShellComponent(config) {
420
441
  const position = config.widget?.position ?? "bottom-right";
421
442
  const width = config.widget?.width ?? 380;
422
443
  const height = config.widget?.height ?? 620;
444
+ const themeQuery = shellThemeQuery(config);
423
445
  const docsBase = config.product?.baseUrl
424
446
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
425
447
  : 'http://localhost:3005/docs';
@@ -474,7 +496,7 @@ const iframeRef = ref<HTMLIFrameElement | null>(null);
474
496
 
475
497
  const shellId = import.meta.env.VITE_DUCT_SHELL_ID as string ?? '';
476
498
  const shellHost = import.meta.env.VITE_DUCT_SHELL_HOST as string ?? 'http://localhost:3000';
477
- const shellUrl = computed(() => \`\${shellHost}/\${shellId}\`);
499
+ const shellUrl = computed(() => \`\${shellHost}/\${shellId}${themeQuery}\`);
478
500
 
479
501
  async function getToken(): Promise<string> {
480
502
  try {
@@ -539,6 +561,7 @@ function generateNuxtShellComponent(config) {
539
561
  const position = config.widget?.position ?? "bottom-right";
540
562
  const width = config.widget?.width ?? 380;
541
563
  const height = config.widget?.height ?? 620;
564
+ const themeQuery = shellThemeQuery(config);
542
565
  const docsBase = config.product?.baseUrl
543
566
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
544
567
  : 'http://localhost:3005/docs';
@@ -593,7 +616,7 @@ const iframeRef = ref<HTMLIFrameElement | null>(null);
593
616
  const config = useRuntimeConfig();
594
617
  const shellId = (config.public.ductShellId as string) ?? '';
595
618
  const shellHost = (config.public.ductShellHost as string) ?? 'http://localhost:3000';
596
- const shellUrl = computed(() => \`\${shellHost}/\${shellId}\`);
619
+ const shellUrl = computed(() => \`\${shellHost}/\${shellId}${themeQuery}\`);
597
620
 
598
621
  async function getToken(): Promise<string> {
599
622
  try {
package/dist/cli/index.js CHANGED
@@ -301,6 +301,7 @@ program
301
301
  .option("--no-interactive", "Write unresolved review decisions to duct-review.json instead of prompting", false)
302
302
  .option("--manual", "Run topology + file selection only (no LLM). Generates a pre-filled template with empty actions/routes.", false)
303
303
  .option("--api-spec <path>", "Path to an OpenAPI/Swagger spec file — skips Route + API agents for instant, high-accuracy init")
304
+ .option("--curl-collection <path>", "Path to a cURL script or Postman collection JSON — skips Route + API agents")
304
305
  .option("--api-url <url>", "Separate API base URL when your API runs on a different domain (e.g., https://api.example.com)")
305
306
  .option("--industry <category>", "Product industry for better modality routing (e.g., fintech, ecommerce, saas, ai)")
306
307
  .action(async (opts) => {
@@ -315,6 +316,7 @@ program
315
316
  yes: opts.yes,
316
317
  noInteractive: Boolean(opts.noInteractive),
317
318
  apiSpec: opts.apiSpec,
319
+ curlCollection: opts.curlCollection,
318
320
  apiUrl: opts.apiUrl,
319
321
  industry: opts.industry,
320
322
  });
@@ -17,6 +17,8 @@ export interface InitOptions {
17
17
  manual?: boolean;
18
18
  /** Path to an OpenAPI/Swagger spec file — skips Route + API agents */
19
19
  apiSpec?: string;
20
+ /** Path to a cURL script or Postman collection — skips Route + API agents */
21
+ curlCollection?: string;
20
22
  /** Separate API base URL (for APIs on a different domain from the frontend) */
21
23
  apiUrl?: string;
22
24
  /** Industry/category override (e.g., fintech, ecommerce, saas) */
package/dist/cli/init.js CHANGED
@@ -601,7 +601,8 @@ export async function runInit(opts = {}) {
601
601
  // Skip the LLM check when --api-spec is provided: the deterministic parser
602
602
  // does not require any LLM key, so the pipeline can run without credentials.
603
603
  const hasApiSpec = Boolean(opts.apiSpec);
604
- if (!noAgents && !hasApiSpec) {
604
+ const hasCurlCollection = Boolean(opts.curlCollection);
605
+ if (!noAgents && !hasApiSpec && !hasCurlCollection) {
605
606
  const canRunAgents = await checkLlmCredentialsAndPrompt(noAgents, yes);
606
607
  if (!canRunAgents) {
607
608
  noAgents = true;
@@ -819,6 +820,17 @@ export async function runInit(opts = {}) {
819
820
  console.log(chalk.yellow(` ⚠ Could not read --api-spec file: ${opts.apiSpec}. Falling back to agent scan.\n`));
820
821
  }
821
822
  }
823
+ let curlCollectionContent;
824
+ const curlCollectionPath = opts.curlCollection ? path.resolve(cwd, opts.curlCollection) : undefined;
825
+ if (curlCollectionPath) {
826
+ try {
827
+ curlCollectionContent = await fs.readFile(curlCollectionPath, "utf-8");
828
+ console.log(chalk.gray(` Using cURL collection: ${path.relative(cwd, curlCollectionPath)} — deterministic parse, no LLM needed\n`));
829
+ }
830
+ catch {
831
+ console.log(chalk.yellow(` ⚠ Could not read --curl-collection file: ${opts.curlCollection}. Falling back to agent scan.\n`));
832
+ }
833
+ }
822
834
  // Build a bounded file list before running agents so each agent
823
835
  // receives targeted files as priority context instead of scanning broadly.
824
836
  let readList = !noAgents ? await buildReadList(topo, sandboxFs) : undefined;
@@ -919,6 +931,7 @@ export async function runInit(opts = {}) {
919
931
  emitter,
920
932
  readList,
921
933
  ...(apiSpecContent ? { apiSpecContent, apiSpecPath: opts.apiSpec } : {}),
934
+ ...(curlCollectionContent ? { curlCollectionContent, curlCollectionPath: opts.curlCollection } : {}),
922
935
  postProcess: { yesMode: yes },
923
936
  });
924
937
  pipelineSpinner.stop();
@@ -0,0 +1,21 @@
1
+ import type { ActionManifest, RouteManifest } from "../../core/types.js";
2
+ export interface CurlParseResult {
3
+ actions: ActionManifest[];
4
+ routes: RouteManifest[];
5
+ requestCount: number;
6
+ sourceLabel: string;
7
+ }
8
+ interface ParsedRequest {
9
+ method: string;
10
+ path: string;
11
+ url: string;
12
+ body?: Record<string, unknown>;
13
+ name?: string;
14
+ }
15
+ /** Parse one curl command line (may span continuation with \\). */
16
+ export declare function parseCurlCommand(raw: string): ParsedRequest | null;
17
+ /**
18
+ * Parse a `.sh` curl script, raw curl text, or Postman Collection v2.1 JSON.
19
+ */
20
+ export declare function parseCurlCollection(content: string, filePath?: string): Promise<CurlParseResult>;
21
+ export {};
@@ -0,0 +1,186 @@
1
+ // ============================================================
2
+ // @duct/sdk — Deterministic cURL / Postman collection parser
3
+ // ============================================================
4
+ function toSnakeCase(str) {
5
+ return str
6
+ .toLowerCase()
7
+ .replace(/[^a-z0-9]/g, "_")
8
+ .replace(/_+/g, "_")
9
+ .replace(/^_|_$/g, "");
10
+ }
11
+ function pathFromUrl(rawUrl) {
12
+ try {
13
+ const normalized = rawUrl.replace(/\\'/g, "'").replace(/\\"/g, '"');
14
+ const url = new URL(normalized.startsWith("http") ? normalized : `https://${normalized}`);
15
+ return { path: url.pathname || "/", host: url.host };
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ function deriveActionId(method, path, name, used) {
22
+ const base = toSnakeCase(name?.trim() || `${method}_${path}`);
23
+ let id = base || "request";
24
+ let n = 2;
25
+ while (used.has(id)) {
26
+ id = `${base}_${n}`;
27
+ n += 1;
28
+ }
29
+ used.add(id);
30
+ return id;
31
+ }
32
+ /** Parse one curl command line (may span continuation with \\). */
33
+ export function parseCurlCommand(raw) {
34
+ const line = raw.replace(/\s\\\s*\n/g, " ").trim();
35
+ if (!/^curl\b/i.test(line))
36
+ return null;
37
+ const methodMatch = line.match(/(?:^|\s)-X\s+([A-Z]+)/i);
38
+ const method = (methodMatch?.[1] ?? "GET").toUpperCase();
39
+ const urlMatch = line.match(/(?:^|\s)(?:'([^']+)'|"([^"]+)"|(https?:\/\/[^\s'"]+))/i);
40
+ const url = urlMatch?.[1] ?? urlMatch?.[2] ?? urlMatch?.[3];
41
+ if (!url)
42
+ return null;
43
+ const parsed = pathFromUrl(url);
44
+ if (!parsed)
45
+ return null;
46
+ let body;
47
+ const dataMatch = line.match(/(?:^|\s)(?:-d|--data(?:-raw|-binary)?)\s+('([^']*)'|"([^"]*)"|(\S+))/i);
48
+ const dataRaw = dataMatch?.[2] ?? dataMatch?.[3] ?? dataMatch?.[4];
49
+ if (dataRaw) {
50
+ try {
51
+ const parsedBody = JSON.parse(dataRaw);
52
+ if (typeof parsedBody === "object" && parsedBody !== null && !Array.isArray(parsedBody)) {
53
+ body = parsedBody;
54
+ }
55
+ }
56
+ catch {
57
+ // non-JSON body — skip schema inference
58
+ }
59
+ }
60
+ return {
61
+ method,
62
+ path: parsed.path,
63
+ url,
64
+ body,
65
+ name: `${method} ${parsed.path}`,
66
+ };
67
+ }
68
+ function parseShellCurls(content) {
69
+ const chunks = content.split(/\n(?=curl\b)/i);
70
+ const out = [];
71
+ for (const chunk of chunks) {
72
+ const req = parseCurlCommand(chunk.trim());
73
+ if (req)
74
+ out.push(req);
75
+ }
76
+ return out;
77
+ }
78
+ function parsePostmanCollection(content) {
79
+ let json;
80
+ try {
81
+ json = JSON.parse(content);
82
+ }
83
+ catch {
84
+ return [];
85
+ }
86
+ const out = [];
87
+ const walk = (items) => {
88
+ if (!Array.isArray(items))
89
+ return;
90
+ for (const item of items) {
91
+ if (typeof item !== "object" || item === null)
92
+ continue;
93
+ const obj = item;
94
+ if (Array.isArray(obj.item)) {
95
+ walk(obj.item);
96
+ continue;
97
+ }
98
+ const request = obj.request;
99
+ if (!request)
100
+ continue;
101
+ const method = String(request.method ?? "GET").toUpperCase();
102
+ const urlRaw = request.url;
103
+ let urlStr = "";
104
+ if (typeof urlRaw === "string")
105
+ urlStr = urlRaw;
106
+ else if (typeof urlRaw === "object" && urlRaw !== null) {
107
+ const u = urlRaw;
108
+ if (typeof u.raw === "string")
109
+ urlStr = u.raw;
110
+ else if (Array.isArray(u.path)) {
111
+ urlStr = `https://example.com/${u.path.join("/")}`;
112
+ }
113
+ }
114
+ const parsed = pathFromUrl(urlStr);
115
+ if (!parsed)
116
+ continue;
117
+ out.push({
118
+ method,
119
+ path: parsed.path,
120
+ url: urlStr,
121
+ name: typeof obj.name === "string" ? obj.name : `${method} ${parsed.path}`,
122
+ });
123
+ }
124
+ };
125
+ walk(json.item);
126
+ return out;
127
+ }
128
+ function requestsToManifests(requests, sourceLabel) {
129
+ const used = new Set();
130
+ const actions = [];
131
+ const routes = [];
132
+ for (const req of requests) {
133
+ const id = deriveActionId(req.method, req.path, req.name, used);
134
+ const sideEffects = ["POST", "PUT", "PATCH", "DELETE"].includes(req.method);
135
+ actions.push({
136
+ id,
137
+ name: req.name ?? id,
138
+ description: `${req.method} ${req.path} (imported from ${sourceLabel})`,
139
+ method: req.method,
140
+ path: req.path,
141
+ agentAccessible: false,
142
+ sideEffects,
143
+ sensitivityLevel: "low",
144
+ params: [],
145
+ inputSchema: req.body ? { type: "object", properties: Object.fromEntries(Object.keys(req.body).map((k) => [k, { type: typeof req.body[k] }])) } : undefined,
146
+ requiresAuth: false,
147
+ confidence: 0.9,
148
+ evidence: [sourceLabel],
149
+ });
150
+ if (req.method === "GET") {
151
+ routes.push({
152
+ path: req.path,
153
+ name: req.name ?? id,
154
+ description: `${req.method} ${req.path}`,
155
+ params: [],
156
+ queryParams: [],
157
+ uiStateHint: "list",
158
+ requiresAuth: false,
159
+ deeplinkable: false,
160
+ confidence: 0.9,
161
+ evidence: [sourceLabel],
162
+ });
163
+ }
164
+ }
165
+ return { actions, routes, requestCount: requests.length, sourceLabel };
166
+ }
167
+ /**
168
+ * Parse a `.sh` curl script, raw curl text, or Postman Collection v2.1 JSON.
169
+ */
170
+ export async function parseCurlCollection(content, filePath = "curl-collection.sh") {
171
+ const trimmed = content.trim();
172
+ const lower = filePath.toLowerCase();
173
+ let requests = [];
174
+ if (lower.endsWith(".json") && trimmed.startsWith("{")) {
175
+ requests = parsePostmanCollection(trimmed);
176
+ }
177
+ else {
178
+ requests = parseShellCurls(trimmed);
179
+ if (requests.length === 0 && trimmed.includes("curl")) {
180
+ const single = parseCurlCommand(trimmed);
181
+ if (single)
182
+ requests = [single];
183
+ }
184
+ }
185
+ return requestsToManifests(requests, filePath);
186
+ }
@@ -22,15 +22,56 @@ function toSnakeCase(str) {
22
22
  .replace(/_+/g, "_")
23
23
  .replace(/^_|_$/g, "");
24
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}`);
25
+ function deriveActionId(operationId, method, path, tags, usedIds) {
26
+ let base;
27
+ if (operationId?.trim()) {
28
+ base = toSnakeCase(operationId.trim());
29
+ }
30
+ else if (tags?.length) {
31
+ const pathPart = path
32
+ .replace(/\{([^}]+)\}/g, (_, name) => name)
33
+ .replace(/[^a-zA-Z0-9]+/g, "_")
34
+ .replace(/^_|_$/g, "");
35
+ base = toSnakeCase(`${tags[0]}_${method}_${pathPart}`);
36
+ }
37
+ else {
38
+ const pathPart = path
39
+ .replace(/\{([^}]+)\}/g, (_, name) => name)
40
+ .replace(/[^a-zA-Z0-9]+/g, "_")
41
+ .replace(/^_|_$/g, "");
42
+ base = toSnakeCase(`${method}_${pathPart}`);
43
+ }
44
+ if (!usedIds)
45
+ return base;
46
+ let id = base || "operation";
47
+ let n = 2;
48
+ while (usedIds.has(id)) {
49
+ id = `${base}_${n}`;
50
+ n += 1;
51
+ }
52
+ usedIds.add(id);
53
+ return id;
54
+ }
55
+ function resolveRef(ref, spec) {
56
+ if (!ref.startsWith("#/"))
57
+ return undefined;
58
+ const parts = ref.slice(2).split("/");
59
+ let node = spec;
60
+ for (const part of parts) {
61
+ if (typeof node !== "object" || node === null)
62
+ return undefined;
63
+ node = node[part];
64
+ }
65
+ return typeof node === "object" && node !== null ? node : undefined;
66
+ }
67
+ function dereferenceSchema(schema, spec, depth = 0) {
68
+ if (!schema || depth > 8)
69
+ return schema;
70
+ if (schema.$ref) {
71
+ const resolved = resolveRef(schema.$ref, spec);
72
+ return resolved ? dereferenceSchema(resolved, spec, depth + 1) : undefined;
73
+ }
74
+ return schema;
34
75
  }
35
76
  function inferSensitivityLevel(path, description, xDuctSensitivity) {
36
77
  if (xDuctSensitivity && VALID_SENSITIVITY_LEVELS.has(xDuctSensitivity)) {
@@ -96,7 +137,7 @@ function operationHasSecurityRequirement(operation, spec) {
96
137
  Object.keys(spec.securityDefinitions).length > 0);
97
138
  return hasGlobalSchemes;
98
139
  }
99
- function extractParams(parameters, requestBody) {
140
+ function extractParams(parameters, requestBody, spec) {
100
141
  const params = [];
101
142
  let inputSchema;
102
143
  for (const param of parameters) {
@@ -130,7 +171,9 @@ function extractParams(parameters, requestBody) {
130
171
  // OpenAPI 3.x requestBody
131
172
  if (requestBody?.content) {
132
173
  const jsonContent = requestBody.content["application/json"];
133
- const schema = jsonContent?.schema;
174
+ const schema = spec
175
+ ? dereferenceSchema(jsonContent?.schema, spec)
176
+ : jsonContent?.schema;
134
177
  if (schema) {
135
178
  inputSchema = schema;
136
179
  if (schema.properties) {
@@ -212,6 +255,7 @@ export async function parseOpenApiSpec(content, filePath = "openapi.json") {
212
255
  const actions = [];
213
256
  const routes = [];
214
257
  const seen = new Set(); // deduplicate by METHOD:path
258
+ const usedActionIds = new Set();
215
259
  let operationCount = 0;
216
260
  const paths = (spec.paths ?? {});
217
261
  for (const [rawPath, pathItem] of Object.entries(paths)) {
@@ -247,10 +291,10 @@ export async function parseOpenApiSpec(content, filePath = "openapi.json") {
247
291
  const description = operation.summary ??
248
292
  operation.description ??
249
293
  `${upperMethod} ${normalizedPath}`;
250
- const { params, inputSchema } = extractParams(mergedParams, operation.requestBody);
251
- const id = deriveActionId(operation.operationId, method, normalizedPath);
294
+ const { params, inputSchema } = extractParams(mergedParams, operation.requestBody, spec);
295
+ const id = deriveActionId(operation.operationId, method, normalizedPath, operation.tags, usedActionIds);
252
296
  const sideEffects = SIDE_EFFECT_METHODS.has(upperMethod);
253
- const confidence = operation.operationId?.trim() ? 1.0 : 0.95;
297
+ const confidence = operation.operationId?.trim() ? 1.0 : 0.85;
254
298
  const sensitivityLevel = inferSensitivityLevel(normalizedPath, description, operation["x-duct-sensitivity"]);
255
299
  const requiresAuth = operationHasSecurityRequirement(operation, spec);
256
300
  const dedupeKey = `${upperMethod}:${normalizedPath}`;
@@ -0,0 +1,13 @@
1
+ import type { ActionManifest } from "./types.js";
2
+ export interface ActionDefinitionGrant {
3
+ actionId: string;
4
+ definitionHash: string;
5
+ }
6
+ export declare function computeActionDefinitionFingerprint(action: Pick<ActionManifest, "method" | "path" | "sideEffects" | "sensitivityLevel">): string;
7
+ export declare function buildActionDefinitionGrants(actionIds: string[], actionsById: Record<string, Pick<ActionManifest, "method" | "path" | "sideEffects" | "sensitivityLevel">>): ActionDefinitionGrant[];
8
+ export type ActionRiskTier = "read" | "write" | "delete";
9
+ export declare function classifyActionRiskTier(action: Pick<ActionManifest, "method" | "sideEffects">): ActionRiskTier;
10
+ export declare function checkAgentScope(scopes: string[], action: Pick<ActionManifest, "id" | "method" | "path" | "sideEffects" | "sensitivityLevel">, params?: Record<string, unknown>): {
11
+ allowed: boolean;
12
+ error?: string;
13
+ };
@@ -0,0 +1,51 @@
1
+ import { createHash } from "node:crypto";
2
+ export function computeActionDefinitionFingerprint(action) {
3
+ const canonical = JSON.stringify({
4
+ method: (action.method ?? "GET").toUpperCase(),
5
+ path: action.path ?? "",
6
+ sideEffects: Boolean(action.sideEffects),
7
+ sensitivityLevel: action.sensitivityLevel ?? "low",
8
+ });
9
+ return createHash("sha256").update(canonical).digest("hex").slice(0, 16);
10
+ }
11
+ export function buildActionDefinitionGrants(actionIds, actionsById) {
12
+ return actionIds.map((actionId) => ({
13
+ actionId,
14
+ definitionHash: computeActionDefinitionFingerprint(actionsById[actionId] ?? { method: "GET", path: "/", sideEffects: false, sensitivityLevel: "low" }),
15
+ }));
16
+ }
17
+ export function classifyActionRiskTier(action) {
18
+ const method = (action.method ?? "GET").toUpperCase();
19
+ if (method === "DELETE")
20
+ return "delete";
21
+ if (action.sideEffects || ["POST", "PUT", "PATCH"].includes(method))
22
+ return "write";
23
+ return "read";
24
+ }
25
+ export function checkAgentScope(scopes, action, params = {}) {
26
+ if (scopes.includes("*"))
27
+ return { allowed: true };
28
+ const tier = classifyActionRiskTier(action);
29
+ if (scopes.includes(action.id))
30
+ return { allowed: true };
31
+ if (tier === "read") {
32
+ if (scopes.includes("read:*") || scopes.includes(`read:${action.id}`)) {
33
+ return { allowed: true };
34
+ }
35
+ return { allowed: false, error: "read_not_in_agent_scope" };
36
+ }
37
+ if (tier === "write") {
38
+ if (scopes.includes(`write:${action.id}`))
39
+ return { allowed: true };
40
+ return { allowed: false, error: "write_not_in_agent_scope" };
41
+ }
42
+ for (const key of ["id", "recordId", "record_id"]) {
43
+ const val = params[key];
44
+ if (val != null && scopes.includes(`delete:${action.id}:${String(val)}`)) {
45
+ return { allowed: true };
46
+ }
47
+ }
48
+ if (scopes.includes(`delete:${action.id}`))
49
+ return { allowed: true };
50
+ return { allowed: false, error: "delete_not_in_agent_scope" };
51
+ }
@@ -211,6 +211,23 @@ export declare const SHELL_PRESET_DIMENSIONS: Record<ShellPreset, {
211
211
  height: number;
212
212
  }>;
213
213
  export declare const DEFAULT_SHELL_PRESET: ShellPreset;
214
+ /** Viewport margins applied to the opened shell panel (matches DuctShell CSS). */
215
+ export declare const SHELL_PANEL_VIEWPORT_INSETS: {
216
+ readonly width: 32;
217
+ readonly height: 96;
218
+ };
219
+ export type ShellPanelViewportInsets = typeof SHELL_PANEL_VIEWPORT_INSETS;
220
+ /**
221
+ * Cap requested panel dimensions so tall/large presets fit inside a viewport
222
+ * (or bounded preview stage) without clipping below the fold.
223
+ */
224
+ export declare function fitShellPanelDimensions(width: number, height: number, viewportWidth: number, viewportHeight: number, insets?: {
225
+ width: number;
226
+ height: number;
227
+ }): {
228
+ width: number;
229
+ height: number;
230
+ };
214
231
  /**
215
232
  * Resolve the effective panel dimensions from a preset and/or explicit
216
233
  * width/height. Explicit width/height win only when no preset is provided.
@@ -9,6 +9,21 @@ export const SHELL_PRESET_DIMENSIONS = {
9
9
  large: { width: 560, height: 720 },
10
10
  };
11
11
  export const DEFAULT_SHELL_PRESET = 'tall';
12
+ /** Viewport margins applied to the opened shell panel (matches DuctShell CSS). */
13
+ export const SHELL_PANEL_VIEWPORT_INSETS = {
14
+ width: 32,
15
+ height: 96,
16
+ };
17
+ /**
18
+ * Cap requested panel dimensions so tall/large presets fit inside a viewport
19
+ * (or bounded preview stage) without clipping below the fold.
20
+ */
21
+ export function fitShellPanelDimensions(width, height, viewportWidth, viewportHeight, insets = SHELL_PANEL_VIEWPORT_INSETS) {
22
+ return {
23
+ width: Math.min(width, Math.max(0, viewportWidth - insets.width)),
24
+ height: Math.min(height, Math.max(0, viewportHeight - insets.height)),
25
+ };
26
+ }
12
27
  /**
13
28
  * Resolve the effective panel dimensions from a preset and/or explicit
14
29
  * width/height. Explicit width/height win only when no preset is provided.
package/dist/index.d.ts CHANGED
@@ -8,6 +8,8 @@ export { checkShellStatus } from "./core/status.js";
8
8
  export type { ShellStatus, ShellStatusWidget, CheckShellStatusOptions } from "./core/status.js";
9
9
  export { createIntrospectHandler, createIntrospectPageHandler, createIntrospectExpressHandler, } from "./core/introspect.js";
10
10
  export type { IntrospectEntity, IntrospectResult, IntrospectContext, IntrospectResolver, IntrospectHandlerOptions, } from "./core/introspect.js";
11
+ export { SHELL_PRESET_DIMENSIONS, DEFAULT_SHELL_PRESET, SHELL_PANEL_VIEWPORT_INSETS, resolveShellDimensions, fitShellPanelDimensions, } from "./core/types.js";
12
+ export type { ShellPreset, ShellPanelViewportInsets } from "./core/types.js";
11
13
  export type { DuctPageContext } from "./core/types.js";
12
14
  export { useDuctPageContext } from "./adapters/react/use-page-context.js";
13
15
  export type { UseDuctPageContextOptions } from "./adapters/react/use-page-context.js";
package/dist/index.js CHANGED
@@ -15,4 +15,6 @@ export { buildAction, checkActionPermission, buildActionSearchIndex, shouldDefer
15
15
  export { checkShellStatus } from "./core/status.js";
16
16
  // Introspect handler factory (/duct/introspect)
17
17
  export { createIntrospectHandler, createIntrospectPageHandler, createIntrospectExpressHandler, } from "./core/introspect.js";
18
+ // Shell embed layout (presets + viewport fitting)
19
+ export { SHELL_PRESET_DIMENSIONS, DEFAULT_SHELL_PRESET, SHELL_PANEL_VIEWPORT_INSETS, resolveShellDimensions, fitShellPanelDimensions, } from "./core/types.js";
18
20
  export { useDuctPageContext } from "./adapters/react/use-page-context.js";
package/dist/server.d.ts CHANGED
@@ -10,4 +10,6 @@ export { sendIntershellAction, sendIntershellQuery } from "./core/intershell.js"
10
10
  export type { IntershellClientOptions, IntershellMessage, IntershellActionResult, } from "./core/intershell.js";
11
11
  export { checkShellStatus } from "./core/status.js";
12
12
  export type { ShellStatus, ShellStatusWidget, CheckShellStatusOptions } from "./core/status.js";
13
+ export { SHELL_PRESET_DIMENSIONS, DEFAULT_SHELL_PRESET, SHELL_PANEL_VIEWPORT_INSETS, resolveShellDimensions, fitShellPanelDimensions, } from "./core/types.js";
14
+ export type { ShellPreset, ShellPanelViewportInsets } from "./core/types.js";
13
15
  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 CHANGED
@@ -21,3 +21,5 @@ export { buildAction, checkActionPermission, buildActionSearchIndex, shouldDefer
21
21
  export { sendIntershellAction, sendIntershellQuery } from "./core/intershell.js";
22
22
  // Shell status check (server-side polling)
23
23
  export { checkShellStatus } from "./core/status.js";
24
+ // Shell embed layout (presets + viewport fitting)
25
+ export { SHELL_PRESET_DIMENSIONS, DEFAULT_SHELL_PRESET, SHELL_PANEL_VIEWPORT_INSETS, resolveShellDimensions, fitShellPanelDimensions, } from "./core/types.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duct-sdk/sdk",
3
- "version": "0.3.8",
3
+ "version": "0.3.11",
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",