@duct-sdk/sdk 0.3.8 → 0.3.9

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,15 @@
2
2
 
3
3
  Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
4
 
5
+ ## [0.3.9] — 2026-06-14
6
+
7
+ ### Added
8
+ - **`duct init --curl-collection`** — import actions from curl scripts or Postman Collection v2.1 JSON (deterministic, no LLM)
9
+ - **`core/auth-boundaries.ts`** — shared helpers for action-definition fingerprints and risk-tiered scope checks (aligned with Duct platform auth validation)
10
+
11
+ ### Improved
12
+ - **OpenAPI import** — `$ref` resolution for requestBody schemas; tag-based action ID derivation; collision suffixes; lower confidence when `operationId` is absent
13
+
5
14
  ## [0.3.8] — 2026-06-11
6
15
 
7
16
  ### 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.
@@ -536,6 +536,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
536
536
  });
537
537
  const widthVal = typeof presetDims.width === "number" ? `${presetDims.width}px` : presetDims.width;
538
538
  const heightVal = typeof presetDims.height === "number" ? `${presetDims.height}px` : presetDims.height;
539
+ const panelWidthInset = SHELL_PANEL_VIEWPORT_INSETS.width;
540
+ const panelHeightInset = SHELL_PANEL_VIEWPORT_INSETS.height;
539
541
  // Bubble + panel placement. When the bubble has been dragged we anchor the
540
542
  // panel to the bubble; otherwise we use the default corner.
541
543
  const dragged = bubblePos !== null;
@@ -562,8 +564,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
562
564
  const panelStyle = {
563
565
  position: "fixed",
564
566
  ...(panelPos ? { left: `${panelPos.x}px`, top: `${panelPos.y}px` } : panelAnchor),
565
- width: `min(${widthVal}, calc(100vw - 32px))`,
566
- height: `min(${heightVal}, calc(100dvh - 96px))`,
567
+ width: `min(${widthVal}, calc(100vw - ${panelWidthInset}px))`,
568
+ height: `min(${heightVal}, calc(100dvh - ${panelHeightInset}px))`,
567
569
  zIndex: 9998,
568
570
  borderRadius: "16px",
569
571
  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([
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.9",
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",