@duct-sdk/sdk 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,7 @@
5
5
  "use client";
6
6
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
7
7
  import React, { useEffect, useRef, useCallback, useState, } from "react";
8
+ import { resolveShellDimensions, } from "../../core/types.js";
8
9
  /**
9
10
  * Hook that polls the shell status endpoint once on mount.
10
11
  * Use when you need to conditionally render UI based on shell liveness.
@@ -48,6 +49,19 @@ export function useShellStatus(shellId, shellHost) {
48
49
  const DUCT_SHELL_HOST_DEFAULT = (typeof process !== "undefined" && process.env?.["DUCT_SHELL_HOST"]) ||
49
50
  "http://localhost:3000";
50
51
  const DUCT_LAUNCHER_ICON_LOCAL_FALLBACK = "/assets/logo.png";
52
+ const BUBBLE_SIZE = 56;
53
+ /** Keep the bubble fully inside the viewport (with a small margin). */
54
+ function clampBubble(x, y) {
55
+ if (typeof window === "undefined")
56
+ return { x, y };
57
+ const margin = 8;
58
+ const maxX = window.innerWidth - BUBBLE_SIZE - margin;
59
+ const maxY = window.innerHeight - BUBBLE_SIZE - margin;
60
+ return {
61
+ x: Math.min(Math.max(margin, x), Math.max(margin, maxX)),
62
+ y: Math.min(Math.max(margin, y), Math.max(margin, maxY)),
63
+ };
64
+ }
51
65
  /**
52
66
  * DuctShell — a self-contained floating launcher button + chat panel.
53
67
  *
@@ -69,7 +83,7 @@ const DUCT_LAUNCHER_ICON_LOCAL_FALLBACK = "/assets/logo.png";
69
83
  * />
70
84
  * ```
71
85
  */
72
- 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, }) {
86
+ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, onPageContext, open, onOpenChange, defaultOpen = false, shellHost = DUCT_SHELL_HOST_DEFAULT, position = "bottom-right", preset, theme = "system", draggable = true, panelWidth = 420, panelHeight = 640, style, className, launcherIconSrc, readyCheck = false, }) {
73
87
  const iframeRef = useRef(null);
74
88
  const [isReady, setIsReady] = useState(false);
75
89
  const [isOpen, setIsOpen] = useState(defaultOpen);
@@ -79,6 +93,13 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
79
93
  // Dynamic panel size — overridden by DUCT_PANEL_SIZE message from shell (manifest widget config)
80
94
  const [dynamicWidth, setDynamicWidth] = useState(undefined);
81
95
  const [dynamicHeight, setDynamicHeight] = useState(undefined);
96
+ const [dynamicPreset, setDynamicPreset] = useState(undefined);
97
+ // Free-drag bubble position (px from top-left of viewport). null = default corner.
98
+ const [bubblePos, setBubblePos] = useState(null);
99
+ const [isDragging, setIsDragging] = useState(false);
100
+ const dragState = useRef(null);
101
+ // Resolve theme for the launcher chrome (light/dark surface).
102
+ const [isDarkChrome, setIsDarkChrome] = useState(theme === "dark");
82
103
  // Shell liveness — only checked when readyCheck=true
83
104
  const [shellLive, setShellLive] = useState(!readyCheck);
84
105
  const pendingTokenRequests = useRef(new Map());
@@ -108,7 +129,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
108
129
  })();
109
130
  const iconCandidates = launcherIconSrc
110
131
  ? [launcherIconSrc]
111
- : [`${shellOrigin}/duct-logo.png`, DUCT_LAUNCHER_ICON_LOCAL_FALLBACK];
132
+ : [`${shellOrigin}/duct-text-no-bg.png`, `${shellOrigin}/duct-logo.png`, DUCT_LAUNCHER_ICON_LOCAL_FALLBACK];
112
133
  const currentIconSrc = iconCandidates[Math.min(iconCandidateIndex, iconCandidates.length - 1)];
113
134
  // Send a message to the iframe
114
135
  const postToShell = useCallback((message) => {
@@ -134,10 +155,27 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
134
155
  setIsAnimating(false);
135
156
  }, 220);
136
157
  }, [setOpen]);
158
+ const isAllowedDeeplinkUrl = useCallback((url) => {
159
+ if (!url || url.startsWith("//"))
160
+ return false;
161
+ if (url.startsWith("/"))
162
+ return true;
163
+ try {
164
+ const parsed = new URL(url);
165
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
166
+ return false;
167
+ return parsed.origin === window.location.origin;
168
+ }
169
+ catch {
170
+ return false;
171
+ }
172
+ }, []);
137
173
  // Handle inbound messages from the iframe
138
174
  const handleMessage = useCallback(async (event) => {
139
175
  if (event.origin !== shellOrigin)
140
176
  return;
177
+ if (event.source !== iframeRef.current?.contentWindow)
178
+ return;
141
179
  if (typeof event.data !== "object" || !event.data?.type)
142
180
  return;
143
181
  const msg = event.data;
@@ -185,6 +223,8 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
185
223
  }
186
224
  case "DUCT_DEEPLINK_NAVIGATE": {
187
225
  const { url } = msg;
226
+ if (!isAllowedDeeplinkUrl(url))
227
+ break;
188
228
  postToShell({ type: "DUCT_NAVIGATE_CONFIRMED", url });
189
229
  closePanel();
190
230
  // Delay navigation until after the close animation (220ms) so the panel
@@ -200,7 +240,9 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
200
240
  break;
201
241
  }
202
242
  case "DUCT_PANEL_SIZE": {
203
- // Shell communicates its preferred dimensions from manifest widget config.
243
+ // Shell communicates its preferred dimensions/preset from manifest widget config.
244
+ if (msg.preset !== undefined)
245
+ setDynamicPreset(msg.preset);
204
246
  if (msg.width !== undefined)
205
247
  setDynamicWidth(msg.width);
206
248
  if (msg.height !== undefined)
@@ -216,7 +258,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
216
258
  break;
217
259
  }
218
260
  }
219
- }, [shellOrigin, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel]);
261
+ }, [shellOrigin, isAllowedDeeplinkUrl, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel]);
220
262
  useEffect(() => {
221
263
  window.addEventListener("message", handleMessage);
222
264
  return () => window.removeEventListener("message", handleMessage);
@@ -246,6 +288,83 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
246
288
  }
247
289
  setIconLoadFailed(true);
248
290
  }, [iconCandidateIndex, iconCandidates.length]);
291
+ // Resolve light/dark chrome for the bubble (follows system when theme="system").
292
+ useEffect(() => {
293
+ if (theme === "dark") {
294
+ setIsDarkChrome(true);
295
+ return;
296
+ }
297
+ if (theme === "light") {
298
+ setIsDarkChrome(false);
299
+ return;
300
+ }
301
+ if (typeof window === "undefined" || !window.matchMedia)
302
+ return;
303
+ const mq = window.matchMedia("(prefers-color-scheme: dark)");
304
+ setIsDarkChrome(mq.matches);
305
+ const handler = (e) => setIsDarkChrome(e.matches);
306
+ mq.addEventListener("change", handler);
307
+ return () => mq.removeEventListener("change", handler);
308
+ }, [theme]);
309
+ // Restore a previously dragged bubble position.
310
+ useEffect(() => {
311
+ if (!draggable || typeof window === "undefined")
312
+ return;
313
+ try {
314
+ const raw = window.localStorage.getItem(`duct-shell-pos:${shellId}`);
315
+ if (raw) {
316
+ const parsed = JSON.parse(raw);
317
+ if (typeof parsed.x === "number" && typeof parsed.y === "number") {
318
+ setBubblePos(clampBubble(parsed.x, parsed.y));
319
+ }
320
+ }
321
+ }
322
+ catch { /* ignore corrupt storage */ }
323
+ }, [shellId, draggable]);
324
+ // Free drag — pointer move/up handlers attached to window during a drag.
325
+ useEffect(() => {
326
+ if (!isDragging)
327
+ return;
328
+ const onMove = (e) => {
329
+ const st = dragState.current;
330
+ if (!st)
331
+ return;
332
+ if (Math.abs(e.clientX - st.startX) > 4 || Math.abs(e.clientY - st.startY) > 4) {
333
+ st.moved = true;
334
+ }
335
+ setBubblePos(clampBubble(e.clientX - st.dx, e.clientY - st.dy));
336
+ };
337
+ const onUp = () => {
338
+ setIsDragging(false);
339
+ const st = dragState.current;
340
+ dragState.current = null;
341
+ if (st && !st.moved) {
342
+ // Treat as a click → open the panel.
343
+ openPanel();
344
+ }
345
+ else if (bubblePos) {
346
+ try {
347
+ window.localStorage.setItem(`duct-shell-pos:${shellId}`, JSON.stringify(bubblePos));
348
+ }
349
+ catch { /* ignore */ }
350
+ }
351
+ };
352
+ window.addEventListener("pointermove", onMove);
353
+ window.addEventListener("pointerup", onUp);
354
+ return () => {
355
+ window.removeEventListener("pointermove", onMove);
356
+ window.removeEventListener("pointerup", onUp);
357
+ };
358
+ }, [isDragging, bubblePos, openPanel, shellId]);
359
+ const onBubblePointerDown = useCallback((e) => {
360
+ if (!draggable)
361
+ return;
362
+ const rect = e.currentTarget.getBoundingClientRect();
363
+ dragState.current = { dx: e.clientX - rect.left, dy: e.clientY - rect.top, startX: e.clientX, startY: e.clientY, moved: false };
364
+ // Seed bubblePos from current rect so the first drag frame is smooth.
365
+ setBubblePos((prev) => prev ?? clampBubble(rect.left, rect.top));
366
+ setIsDragging(true);
367
+ }, [draggable]);
249
368
  if (!shellId) {
250
369
  console.error("[DuctShell] shellId prop is required");
251
370
  return null;
@@ -255,62 +374,93 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
255
374
  return null;
256
375
  const isRight = position === "bottom-right";
257
376
  const panelVisible = panelOpen || isAnimating;
258
- // Responsive: full-screen on small viewports.
259
- // Dynamic size overrides prop-level size when the shell sends DUCT_PANEL_SIZE
260
- // (manifest widget.width / widget.height configured in Duct dashboard).
261
- const resolvedWidth = dynamicWidth ?? panelWidth;
262
- const resolvedHeight = dynamicHeight ?? panelHeight;
263
- const widthVal = typeof resolvedWidth === "number" ? `${resolvedWidth}px` : resolvedWidth;
264
- const heightVal = typeof resolvedHeight === "number" ? `${resolvedHeight}px` : resolvedHeight;
377
+ // Resolve panel size. Priority: live DUCT_PANEL_SIZE (preset > width/height)
378
+ // from the shell's manifest, then the SDK preset/panelWidth props.
379
+ const sizePreset = dynamicPreset ?? preset;
380
+ const presetDims = resolveShellDimensions({
381
+ preset: sizePreset,
382
+ width: dynamicWidth ?? panelWidth,
383
+ height: dynamicHeight ?? panelHeight,
384
+ });
385
+ const widthVal = typeof presetDims.width === "number" ? `${presetDims.width}px` : presetDims.width;
386
+ const heightVal = typeof presetDims.height === "number" ? `${presetDims.height}px` : presetDims.height;
387
+ // Bubble + panel placement. When the bubble has been dragged we anchor the
388
+ // panel to the bubble; otherwise we use the default corner.
389
+ const dragged = bubblePos !== null;
390
+ const bubbleStyle = dragged
391
+ ? { position: "fixed", left: `${bubblePos.x}px`, top: `${bubblePos.y}px` }
392
+ : { position: "fixed", bottom: "16px", [isRight ? "right" : "left"]: "16px" };
393
+ const panelAnchor = (() => {
394
+ if (!dragged) {
395
+ return { bottom: "80px", [isRight ? "right" : "left"]: "16px" };
396
+ }
397
+ // Open the panel toward whichever side has the most room.
398
+ const vw = typeof window !== "undefined" ? window.innerWidth : 1280;
399
+ const vh = typeof window !== "undefined" ? window.innerHeight : 800;
400
+ const openLeft = bubblePos.x > vw / 2;
401
+ const openUp = bubblePos.y > vh / 2;
402
+ const horiz = openLeft
403
+ ? { right: `${Math.max(16, vw - (bubblePos.x + BUBBLE_SIZE))}px` }
404
+ : { left: `${Math.max(16, bubblePos.x)}px` };
405
+ const vert = openUp
406
+ ? { bottom: `${Math.max(16, vh - bubblePos.y + 12)}px` }
407
+ : { top: `${Math.max(16, bubblePos.y + BUBBLE_SIZE + 12)}px` };
408
+ return { ...horiz, ...vert };
409
+ })();
265
410
  const panelStyle = {
266
411
  position: "fixed",
267
- bottom: "80px",
268
- [isRight ? "right" : "left"]: "16px",
412
+ ...panelAnchor,
269
413
  width: `min(${widthVal}, calc(100vw - 32px))`,
270
414
  height: `min(${heightVal}, calc(100dvh - 96px))`,
271
415
  zIndex: 9998,
272
416
  borderRadius: "16px",
273
417
  overflow: "hidden",
274
418
  boxShadow: "0 24px 64px rgba(0,0,0,0.18), 0 8px 24px rgba(0,0,0,0.10)",
275
- // Slide-in / slide-out animation
276
- // Opens: slides up from below (translateY(100%) → translateY(0))
277
- // Closes: slides back down
278
419
  opacity: panelOpen && !isAnimating ? 1 : 0,
279
- transform: panelOpen && !isAnimating
280
- ? "translateY(0)"
281
- : "translateY(100%)",
420
+ transform: panelOpen && !isAnimating ? "translateY(0)" : "translateY(12px)",
282
421
  transition: "opacity 220ms cubic-bezier(0.16,1,0.3,1), transform 0.25s cubic-bezier(0.16, 1, 0.3, 1)",
283
422
  pointerEvents: panelOpen ? "auto" : "none",
284
423
  visibility: panelVisible ? "visible" : "hidden",
285
424
  ...style,
286
425
  };
426
+ // Theme-aware launcher chrome — light surface in light mode, dark in dark mode.
427
+ const bubbleBg = isDarkChrome ? "#0C0B09" : "#FFFFFF";
428
+ const bubbleBorder = isDarkChrome ? "1px solid rgba(255,255,255,0.08)" : "1px solid rgba(12,11,9,0.08)";
429
+ const bubbleShadow = isDarkChrome
430
+ ? "0 4px 16px rgba(0,0,0,0.40), 0 2px 8px rgba(0,0,0,0.20)"
431
+ : "0 4px 16px rgba(12,11,9,0.16), 0 2px 8px rgba(12,11,9,0.08)";
287
432
  const buttonStyle = {
288
- position: "fixed",
289
- bottom: "16px",
290
- [isRight ? "right" : "left"]: "16px",
433
+ ...bubbleStyle,
291
434
  zIndex: 9999,
292
- width: "56px",
293
- height: "56px",
435
+ width: `${BUBBLE_SIZE}px`,
436
+ height: `${BUBBLE_SIZE}px`,
294
437
  borderRadius: "50%",
295
- border: "none",
296
- cursor: "pointer",
438
+ border: bubbleBorder,
439
+ cursor: isDragging ? "grabbing" : "pointer",
297
440
  display: "flex",
298
441
  alignItems: "center",
299
442
  justifyContent: "center",
300
- backgroundColor: "#0C0B09",
301
- boxShadow: "0 4px 16px rgba(0,0,0,0.40), 0 2px 8px rgba(0,0,0,0.20)",
443
+ backgroundColor: bubbleBg,
444
+ boxShadow: bubbleShadow,
302
445
  padding: 0,
303
- transition: "transform 150ms ease, box-shadow 150ms ease",
446
+ touchAction: "none",
447
+ transition: isDragging ? "none" : "transform 150ms ease, box-shadow 150ms ease",
304
448
  };
305
- return (_jsxs(_Fragment, { children: [!panelOpen && (_jsx("button", { type: "button", style: buttonStyle, onClick: openPanel, "aria-label": "Open Duct Shell", className: className, onMouseEnter: (e) => {
449
+ return (_jsxs(_Fragment, { children: [!panelOpen && (_jsx("button", { type: "button", style: buttonStyle, onClick: (e) => {
450
+ // Suppress click when a drag just happened.
451
+ if (dragState.current?.moved) {
452
+ e.preventDefault();
453
+ return;
454
+ }
455
+ if (!draggable)
456
+ openPanel();
457
+ }, onPointerDown: onBubblePointerDown, "aria-label": "Open Duct Shell", className: className, onMouseEnter: (e) => {
458
+ if (isDragging)
459
+ return;
306
460
  e.currentTarget.style.transform = "scale(1.07)";
307
- e.currentTarget.style.boxShadow =
308
- "0 6px 20px rgba(0,0,0,0.50), 0 2px 8px rgba(0,0,0,0.20)";
309
461
  }, onMouseLeave: (e) => {
310
462
  e.currentTarget.style.transform = "scale(1)";
311
- e.currentTarget.style.boxShadow =
312
- "0 4px 16px rgba(0,0,0,0.40), 0 2px 8px rgba(0,0,0,0.20)";
313
- }, 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: {
463
+ }, children: !iconLoadFailed ? (_jsx("img", { src: currentIconSrc, alt: "Duct", width: 30, height: 30, draggable: false, onError: handleIconError, style: { width: "30px", height: "30px", objectFit: "contain", pointerEvents: "none" } })) : (_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: isDarkChrome ? "#E8622A" : "#E8622A" }) })) })), _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: {
314
464
  width: "100%",
315
465
  height: "100%",
316
466
  border: "none",
@@ -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.
@@ -7,9 +7,7 @@
7
7
  // ----------------------------------------------------------------
8
8
  function generateReactShellComponent(config) {
9
9
  const position = config.widget?.position ?? "bottom-right";
10
- const welcomeMessage = config.widget?.welcomeMessage ?? `Hi! I'm ${config.product.name}'s AI assistant.`;
11
- const width = config.widget?.width ?? 380;
12
- const height = config.widget?.height ?? 620;
10
+ const preset = config.widget?.preset ?? "tall";
13
11
  const docsBase = config.product?.baseUrl
14
12
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
15
13
  : 'http://localhost:3005/docs';
@@ -36,6 +34,9 @@ export function DuctShellEmbed() {
36
34
  shellId={process.env.NEXT_PUBLIC_DUCT_SHELL_ID!}
37
35
  shellHost={shellHost}
38
36
  position="${position}"
37
+ preset="${preset}"
38
+ // Size preset: "tall" (vertical), "square" (Copilot-style), or "large".
39
+ // The bubble is draggable; \`position\` only sets the starting corner.
39
40
  // Optional: provide user context (not sensitive — this is metadata for the shell UI)
40
41
  // userContext={{ theme: "light", locale: "en-US" }}
41
42
  onTokenRequest={async (shellId) => {
@@ -56,13 +57,6 @@ export function DuctShellEmbed() {
56
57
  const data = await res.json() as { token?: string };
57
58
  return data.token ?? "";
58
59
  }}
59
- style={{
60
- width: typeof ${width} === "number" ? \`\${${width}}px\` : "${width}",
61
- height: typeof ${height} === "number" ? \`\${${height}}px\` : "${height}",
62
- maxWidth: "calc(100vw - 32px)",
63
- maxHeight: "calc(100vh - 110px)",
64
- zIndex: 9999,
65
- }}
66
60
  />
67
61
  );
68
62
  }
@@ -83,7 +77,7 @@ export function DuctShellEmbed() {
83
77
  // }
84
78
  //
85
79
  // Shell ID: ${config.shellId}
86
- // Welcome message: "${welcomeMessage}"
80
+ // Size preset: "${preset}" (configure welcome message, theme, etc. in duct.config.ts → widget)
87
81
  //
88
82
  // ── Page Context Protocol (optional but recommended) ──────────────
89
83
  //
@@ -154,6 +148,7 @@ export default function RootLayout({
154
148
  // ----------------------------------------------------------------
155
149
  function generateRemixShellComponent(config) {
156
150
  const position = config.widget?.position ?? "bottom-right";
151
+ const preset = config.widget?.preset ?? "tall";
157
152
  const docsBase = config.product?.baseUrl
158
153
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
159
154
  : 'http://localhost:3005/docs';
@@ -178,6 +173,7 @@ export function DuctShellEmbed() {
178
173
  shellId={import.meta.env.VITE_DUCT_SHELL_ID}
179
174
  shellHost={shellHost}
180
175
  position="${position}"
176
+ preset="${preset}"
181
177
  onTokenRequest={async (shellId) => {
182
178
  const res = await fetch("/api/duct/token", {
183
179
  method: "POST",
@@ -189,13 +185,6 @@ export function DuctShellEmbed() {
189
185
  const data = await res.json() as { token?: string };
190
186
  return data.token ?? "";
191
187
  }}
192
- style={{
193
- width: "380px",
194
- height: "620px",
195
- maxWidth: "calc(100vw - 32px)",
196
- maxHeight: "calc(100vh - 110px)",
197
- zIndex: 9999,
198
- }}
199
188
  />
200
189
  );
201
190
  }
@@ -212,6 +201,7 @@ export function DuctShellEmbed() {
212
201
  // ----------------------------------------------------------------
213
202
  function generateViteShellComponent(config) {
214
203
  const position = config.widget?.position ?? "bottom-right";
204
+ const preset = config.widget?.preset ?? "tall";
215
205
  const docsBase = config.product?.baseUrl
216
206
  ? `https://docs.${new URL(config.product.baseUrl).hostname.split('.').slice(-2).join('.')}`
217
207
  : 'http://localhost:3005/docs';
@@ -236,6 +226,7 @@ export function DuctShellEmbed() {
236
226
  shellId={import.meta.env.VITE_DUCT_SHELL_ID}
237
227
  shellHost={shellHost}
238
228
  position="${position}"
229
+ preset="${preset}"
239
230
  onTokenRequest={async (shellId) => {
240
231
  const res = await fetch("/api/duct/token", {
241
232
  method: "POST",
@@ -247,13 +238,6 @@ export function DuctShellEmbed() {
247
238
  const data = await res.json() as { token?: string };
248
239
  return data.token ?? "";
249
240
  }}
250
- style={{
251
- width: "380px",
252
- height: "620px",
253
- maxWidth: "calc(100vw - 32px)",
254
- maxHeight: "calc(100vh - 110px)",
255
- zIndex: 9999,
256
- }}
257
241
  />
258
242
  );
259
243
  }