@duct-sdk/sdk 0.1.7 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +3 -3
  2. package/dist/adapters/next/index.d.ts +1 -1
  3. package/dist/adapters/next/shell.d.ts +55 -1
  4. package/dist/adapters/next/shell.js +100 -17
  5. package/dist/adapters/react/index.d.ts +5 -1
  6. package/dist/adapters/react/index.js +2 -0
  7. package/dist/adapters/react/shell.d.ts +61 -1
  8. package/dist/adapters/react/shell.js +110 -16
  9. package/dist/adapters/react/use-page-context.d.ts +32 -0
  10. package/dist/adapters/react/use-page-context.js +99 -0
  11. package/dist/cli/agents/api-agent.d.ts +9 -3
  12. package/dist/cli/agents/api-agent.js +163 -69
  13. package/dist/cli/agents/auth-agent.d.ts +2 -1
  14. package/dist/cli/agents/auth-agent.js +38 -24
  15. package/dist/cli/agents/deeplink-agent.js +71 -49
  16. package/dist/cli/agents/llm.d.ts +1 -1
  17. package/dist/cli/agents/llm.js +48 -15
  18. package/dist/cli/agents/pipeline.d.ts +16 -0
  19. package/dist/cli/agents/pipeline.js +18 -5
  20. package/dist/cli/agents/reviewer-agent.js +46 -46
  21. package/dist/cli/agents/route-agent.d.ts +3 -1
  22. package/dist/cli/agents/route-agent.js +70 -44
  23. package/dist/cli/detectors/topology.d.ts +26 -0
  24. package/dist/cli/detectors/topology.js +310 -0
  25. package/dist/cli/drift.d.ts +11 -0
  26. package/dist/cli/drift.js +147 -2
  27. package/dist/cli/fs/sandbox.d.ts +2 -0
  28. package/dist/cli/fs/sandbox.js +22 -8
  29. package/dist/cli/generators/config.d.ts +13 -0
  30. package/dist/cli/generators/config.js +200 -50
  31. package/dist/cli/generators/receiver.js +728 -601
  32. package/dist/cli/generators/shell.js +532 -490
  33. package/dist/cli/index.js +502 -19
  34. package/dist/cli/init.d.ts +11 -1
  35. package/dist/cli/init.js +367 -31
  36. package/dist/cli/processors/postprocess.d.ts +22 -0
  37. package/dist/cli/processors/postprocess.js +107 -0
  38. package/dist/cli/processors/prisma-parser.d.ts +35 -0
  39. package/dist/cli/processors/prisma-parser.js +117 -0
  40. package/dist/cli/processors/zod-extractor.d.ts +27 -0
  41. package/dist/cli/processors/zod-extractor.js +153 -0
  42. package/dist/cli/prompts/review.d.ts +32 -0
  43. package/dist/cli/prompts/review.js +240 -0
  44. package/dist/cli/selectors/index.d.ts +22 -0
  45. package/dist/cli/selectors/index.js +274 -0
  46. package/dist/core/config.d.ts +18 -18
  47. package/dist/core/endpoints.d.ts +1 -0
  48. package/dist/core/endpoints.js +4 -0
  49. package/dist/core/introspect.d.ts +47 -0
  50. package/dist/core/introspect.js +94 -0
  51. package/dist/core/status.d.ts +39 -0
  52. package/dist/core/status.js +40 -0
  53. package/dist/core/token.d.ts +36 -1
  54. package/dist/core/token.js +43 -2
  55. package/dist/core/types.d.ts +114 -0
  56. package/dist/index.d.ts +9 -2
  57. package/dist/index.js +6 -1
  58. package/package.json +84 -84
package/README.md CHANGED
@@ -63,13 +63,13 @@ export default function Layout({ children }) {
63
63
  | `npx @duct-sdk/sdk init` | Scan codebase and generate config + shell files |
64
64
  | `npx @duct-sdk/sdk init --no-agents` | Skip AI scan and start from a blank template |
65
65
  | `npx @duct-sdk/sdk push` | Push `duct.config.ts` manifest to Duct cloud |
66
+ | `npx @duct-sdk/sdk pull <hash>` | Restore a manifest version from push history |
66
67
  | `npx @duct-sdk/sdk init --update` | Incremental re-scan against git diff |
67
68
  | `npx @duct-sdk/sdk init --manual` | Generate a config template without LLM (instant) |
68
69
  | `npx @duct-sdk/sdk scan` | Detect drift between live API and manifest |
70
+ | `npx @duct-sdk/sdk checkup` | Check env config and service connectivity |
69
71
 
70
- Once installed globally (`npm i -g @duct-sdk/sdk`), all commands shorten to `duct login`, `duct init`, etc.
71
-
72
- ---
72
+ Once installed globally (`npm i -g @duct-sdk/sdk`), all commands shorten to `duct login`, `duct init`, `duct pull`, etc.
73
73
 
74
74
  ## Framework Support
75
75
 
@@ -1,4 +1,4 @@
1
1
  export { DuctReceiver } from "./receiver.js";
2
2
  export type { DuctReceiverOptions, ReceiverResult } from "./receiver.js";
3
3
  export { DuctShell, DuctShellButton } from "./shell.js";
4
- export type { DuctShellProps, DuctShellButtonProps } from "./shell.js";
4
+ export type { DuctShellProps, DuctShellButtonProps, DuctPageContext } from "./shell.js";
@@ -1,4 +1,24 @@
1
1
  import React, { type CSSProperties } from "react";
2
+ export interface DuctPageContext {
3
+ route?: string;
4
+ /** Only `type` is required — use whatever key names your data model has */
5
+ entity?: {
6
+ type: string;
7
+ [key: string]: unknown;
8
+ };
9
+ errorState?: {
10
+ code?: string;
11
+ message?: string;
12
+ field?: string;
13
+ };
14
+ /** Only `type` is required — use whatever key your model uses for identifiers */
15
+ selection?: {
16
+ type: string;
17
+ [key: string]: unknown;
18
+ };
19
+ formState?: Record<string, unknown>;
20
+ meta?: Record<string, unknown>;
21
+ }
2
22
  export interface DuctShellProps {
3
23
  /** Your Duct shell ID (e.g., "shell_acme_prod") */
4
24
  shellId: string;
@@ -15,6 +35,17 @@ export interface DuctShellProps {
15
35
  onTokenRequest?: (shellId: string) => Promise<string>;
16
36
  /** Called when the shell requests navigation to a URL (deeplink handoff) */
17
37
  onNavigate?: (url: string) => void;
38
+ /**
39
+ * Page Context Protocol — called when the shell needs to understand what
40
+ * the user is currently viewing (triggered by deictic references like "this",
41
+ * "that order", "the error on screen"). Return structured data about the
42
+ * current page state so the shell can resolve on-screen references without
43
+ * screenshots or computer-use techniques.
44
+ *
45
+ * Alternatively, use the `useDuctPageContext` hook in page-level components
46
+ * when this component is in a layout that doesn't have access to page state.
47
+ */
48
+ onPageContext?: () => DuctPageContext | Promise<DuctPageContext>;
18
49
  /** Controlled open state */
19
50
  open?: boolean;
20
51
  /** Called whenever shell open state changes */
@@ -50,7 +81,30 @@ export interface DuctShellProps {
50
81
  * When omitted, the SDK tries cloud-hosted icon first, then local /assets/logo.png.
51
82
  */
52
83
  launcherIconSrc?: string;
84
+ /**
85
+ * When true, the launcher is hidden until the shell status endpoint confirms
86
+ * the shell is live. Prevents showing the button before `duct push` has been run.
87
+ * @default false
88
+ */
89
+ readyCheck?: boolean;
90
+ }
91
+ export interface ShellStatusResult {
92
+ status: 'live' | 'not_ready' | 'suspended' | 'loading';
93
+ manifestReady: boolean;
94
+ widget?: {
95
+ welcomeMessage?: string;
96
+ placeholder?: string;
97
+ theme?: string;
98
+ primaryColor?: string;
99
+ width?: number | string;
100
+ height?: number | string;
101
+ };
53
102
  }
103
+ /**
104
+ * Hook that polls the shell status endpoint once on mount.
105
+ * Use when you need to conditionally render UI based on shell liveness.
106
+ */
107
+ export declare function useShellStatus(shellId: string, shellHost?: string): ShellStatusResult;
54
108
  /**
55
109
  * DuctShell — a self-contained floating launcher button + chat panel.
56
110
  *
@@ -72,7 +126,7 @@ export interface DuctShellProps {
72
126
  * />
73
127
  * ```
74
128
  */
75
- export declare function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, open, onOpenChange, defaultOpen, shellHost, position, panelWidth, panelHeight, style, className, launcherIconSrc, }: DuctShellProps): React.ReactElement | null;
129
+ export declare function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, onPageContext, open, onOpenChange, defaultOpen, shellHost, position, panelWidth, panelHeight, style, className, launcherIconSrc, readyCheck, }: DuctShellProps): React.ReactElement | null;
76
130
  export interface DuctShellButtonProps {
77
131
  shellId: string;
78
132
  children?: React.ReactNode;
@@ -1,10 +1,40 @@
1
1
  // ============================================================
2
- // @shoryasethia/duct-sdk — DuctShell React Component
2
+ // @duct-sdk/sdk — DuctShell React Component
3
3
  // Floating launcher + iframe panel with postMessage bridge
4
4
  // ============================================================
5
5
  "use client";
6
6
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
7
- import { useEffect, useRef, useCallback, useState, } from "react";
7
+ import React, { useEffect, useRef, useCallback, useState, } from "react";
8
+ /**
9
+ * Hook that polls the shell status endpoint once on mount.
10
+ * Use when you need to conditionally render UI based on shell liveness.
11
+ */
12
+ export function useShellStatus(shellId, shellHost) {
13
+ const [result, setResult] = React.useState({ status: 'loading', manifestReady: false });
14
+ React.useEffect(() => {
15
+ if (!shellId)
16
+ return;
17
+ const host = (shellHost ?? DUCT_SHELL_HOST_DEFAULT).replace(/\/$/, '');
18
+ let cancelled = false;
19
+ fetch(`${host}/api/shell-status/${shellId}`)
20
+ .then((r) => r.json())
21
+ .then((data) => {
22
+ if (!cancelled) {
23
+ setResult({
24
+ status: (data.status ?? 'live'),
25
+ manifestReady: data.manifestReady ?? true,
26
+ widget: data.widget,
27
+ });
28
+ }
29
+ })
30
+ .catch(() => {
31
+ if (!cancelled)
32
+ setResult({ status: 'live', manifestReady: true });
33
+ });
34
+ return () => { cancelled = true; };
35
+ }, [shellId, shellHost]);
36
+ return result;
37
+ }
8
38
  // ----------------------------------------------------------------
9
39
  // DuctShell — floating launcher + panel
10
40
  // ----------------------------------------------------------------
@@ -32,14 +62,32 @@ const DUCT_LAUNCHER_ICON_LOCAL_FALLBACK = "/assets/logo.png";
32
62
  * />
33
63
  * ```
34
64
  */
35
- export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, open, onOpenChange, defaultOpen = false, shellHost = DUCT_SHELL_HOST_DEFAULT, position = "bottom-right", panelWidth = 420, panelHeight = 640, style, className, launcherIconSrc, }) {
65
+ 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, }) {
36
66
  const iframeRef = useRef(null);
37
67
  const [isReady, setIsReady] = useState(false);
38
68
  const [isOpen, setIsOpen] = useState(defaultOpen);
39
69
  const [isAnimating, setIsAnimating] = useState(false);
40
70
  const [iconCandidateIndex, setIconCandidateIndex] = useState(0);
41
71
  const [iconLoadFailed, setIconLoadFailed] = useState(false);
72
+ // Dynamic panel size — overridden by DUCT_PANEL_SIZE message from shell (manifest widget config)
73
+ const [dynamicWidth, setDynamicWidth] = useState(undefined);
74
+ const [dynamicHeight, setDynamicHeight] = useState(undefined);
75
+ // Shell liveness — only checked when readyCheck=true
76
+ const [shellLive, setShellLive] = useState(!readyCheck);
42
77
  const pendingTokenRequests = useRef(new Map());
78
+ // When readyCheck is enabled, poll status once on mount
79
+ useEffect(() => {
80
+ if (!readyCheck || !shellId)
81
+ return;
82
+ const host = shellHost.replace(/\/$/, '');
83
+ fetch(`${host}/api/shell-status/${shellId}`)
84
+ .then((r) => r.json())
85
+ .then((data) => {
86
+ if (data.status === 'live')
87
+ setShellLive(true);
88
+ })
89
+ .catch(() => setShellLive(true)); // fail open
90
+ }, [readyCheck, shellId, shellHost]);
43
91
  const controlled = open !== undefined;
44
92
  const panelOpen = controlled ? open : isOpen;
45
93
  const shellUrl = buildShellUrl(shellHost, shellId, userContext);
@@ -110,16 +158,43 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, op
110
158
  pendingTokenRequests.current.delete(requestId);
111
159
  break;
112
160
  }
113
- case "DUCT_DEEPLINK_NAVIGATE": {
114
- const { url } = msg;
115
- if (onNavigate) {
116
- onNavigate(url);
161
+ case "DUCT_REQUEST_CONTEXT": {
162
+ // Page Context Protocol — shell is asking what the user is currently viewing.
163
+ const { requestId } = msg;
164
+ if (!onPageContext) {
165
+ postToShell({ type: "DUCT_PAGE_CONTEXT", requestId, context: null });
166
+ break;
117
167
  }
118
- else {
119
- window.location.href = url;
168
+ try {
169
+ const context = await onPageContext();
170
+ postToShell({ type: "DUCT_PAGE_CONTEXT", requestId, context });
171
+ }
172
+ catch {
173
+ postToShell({ type: "DUCT_PAGE_CONTEXT", requestId, context: null });
120
174
  }
175
+ break;
176
+ }
177
+ case "DUCT_DEEPLINK_NAVIGATE": {
178
+ const { url } = msg;
121
179
  postToShell({ type: "DUCT_NAVIGATE_CONFIRMED", url });
122
180
  closePanel();
181
+ // Delay navigation until after the close animation (220ms) so the panel
182
+ // slides away before the page changes — avoids a jarring simultaneous transition.
183
+ setTimeout(() => {
184
+ if (onNavigate) {
185
+ onNavigate(url);
186
+ }
187
+ else {
188
+ window.location.href = url;
189
+ }
190
+ }, 230);
191
+ break;
192
+ }
193
+ case "DUCT_PANEL_SIZE": {
194
+ if (msg.width !== undefined)
195
+ setDynamicWidth(msg.width);
196
+ if (msg.height !== undefined)
197
+ setDynamicHeight(msg.height);
123
198
  break;
124
199
  }
125
200
  case "DUCT_OPEN": {
@@ -131,7 +206,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, op
131
206
  break;
132
207
  }
133
208
  }
134
- }, [shellOrigin, userContext, onTokenRequest, postToShell, onNavigate, openPanel, closePanel]);
209
+ }, [shellOrigin, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel]);
135
210
  useEffect(() => {
136
211
  window.addEventListener("message", handleMessage);
137
212
  return () => window.removeEventListener("message", handleMessage);
@@ -165,15 +240,23 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, op
165
240
  console.error("[DuctShell] shellId prop is required");
166
241
  return null;
167
242
  }
243
+ // Hide entirely until readyCheck confirms the shell is live
244
+ if (!shellLive)
245
+ return null;
168
246
  const isRight = position === "bottom-right";
169
247
  const panelVisible = panelOpen || isAnimating;
170
- // Responsive: full-screen on small viewports
248
+ // Responsive: full-screen on small viewports.
249
+ // Dynamic size overrides prop-level size when the shell sends DUCT_PANEL_SIZE.
250
+ const resolvedWidth = dynamicWidth ?? panelWidth;
251
+ const resolvedHeight = dynamicHeight ?? panelHeight;
252
+ const widthVal = typeof resolvedWidth === "number" ? `${resolvedWidth}px` : resolvedWidth;
253
+ const heightVal = typeof resolvedHeight === "number" ? `${resolvedHeight}px` : resolvedHeight;
171
254
  const panelStyle = {
172
255
  position: "fixed",
173
256
  bottom: "80px",
174
257
  [isRight ? "right" : "left"]: "16px",
175
- width: `min(${panelWidth}px, calc(100vw - 32px))`,
176
- height: `min(${panelHeight}px, calc(100dvh - 96px))`,
258
+ width: `min(${widthVal}, calc(100vw - 32px))`,
259
+ height: `min(${heightVal}, calc(100dvh - 96px))`,
177
260
  zIndex: 9998,
178
261
  borderRadius: "16px",
179
262
  overflow: "hidden",
@@ -203,19 +286,19 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, op
203
286
  display: "flex",
204
287
  alignItems: "center",
205
288
  justifyContent: "center",
206
- backgroundColor: "#E8622A",
207
- boxShadow: "0 4px 16px rgba(232,98,42,0.40), 0 2px 8px rgba(0,0,0,0.12)",
289
+ backgroundColor: "#0C0B09",
290
+ boxShadow: "0 4px 16px rgba(0,0,0,0.40), 0 2px 8px rgba(0,0,0,0.20)",
208
291
  padding: 0,
209
292
  transition: "transform 150ms ease, box-shadow 150ms ease",
210
293
  };
211
294
  return (_jsxs(_Fragment, { children: [!panelOpen && (_jsx("button", { type: "button", style: buttonStyle, onClick: openPanel, "aria-label": "Open Duct Shell", className: className, onMouseEnter: (e) => {
212
295
  e.currentTarget.style.transform = "scale(1.07)";
213
296
  e.currentTarget.style.boxShadow =
214
- "0 6px 20px rgba(232,98,42,0.50), 0 2px 8px rgba(0,0,0,0.14)";
297
+ "0 6px 20px rgba(0,0,0,0.50), 0 2px 8px rgba(0,0,0,0.20)";
215
298
  }, onMouseLeave: (e) => {
216
299
  e.currentTarget.style.transform = "scale(1)";
217
300
  e.currentTarget.style.boxShadow =
218
- "0 4px 16px rgba(232,98,42,0.40), 0 2px 8px rgba(0,0,0,0.12)";
301
+ "0 4px 16px rgba(0,0,0,0.40), 0 2px 8px rgba(0,0,0,0.20)";
219
302
  }, children: !iconLoadFailed ? (_jsx("img", { src: currentIconSrc, alt: "Duct", width: 28, height: 28, onError: handleIconError, style: { width: "28px", height: "28px", objectFit: "contain" } })) : (_jsx("svg", { width: "28", height: "28", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: _jsx("path", { d: "M18 12c0-3.3-2.2-5.5-5.5-5.5C9 6.5 7 8.7 7 12s2 5.5 5.5 5.5c2 0 3.6-.8 4.6-2.2l-2.2-1.6c-.6.8-1.4 1.3-2.4 1.3-1.6 0-2.8-1.2-2.8-3s1.2-3 2.8-3c1 0 1.8.5 2.3 1.3L18 12z", fill: "white" }) })) })), _jsx("div", { style: panelStyle, "data-duct-shell": shellId, children: _jsx("iframe", { ref: iframeRef, src: shellUrl, title: "Duct Shell", sandbox: "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", allow: "clipboard-write", referrerPolicy: "no-referrer-when-downgrade", style: {
220
303
  width: "100%",
221
304
  height: "100%",
@@ -1,2 +1,6 @@
1
1
  export { DuctShell, DuctShellButton } from "./shell.js";
2
- export type { DuctShellProps, DuctShellButtonProps } from "./shell.js";
2
+ export type { DuctShellProps, DuctShellButtonProps, DuctPageContext } from "./shell.js";
3
+ export { useDuctPageContext } from "./use-page-context.js";
4
+ export type { UseDuctPageContextOptions } from "./use-page-context.js";
5
+ export { useShellStatus } from "./shell.js";
6
+ export type { ShellStatusResult } from "./shell.js";
@@ -2,3 +2,5 @@
2
2
  // @duct/sdk/react � React adapter exports
3
3
  // ============================================================
4
4
  export { DuctShell, DuctShellButton } from "./shell.js";
5
+ export { useDuctPageContext } from "./use-page-context.js";
6
+ export { useShellStatus } from "./shell.js";
@@ -1,4 +1,24 @@
1
1
  import React, { type CSSProperties } from "react";
2
+ export interface DuctPageContext {
3
+ route?: string;
4
+ /** Only `type` is required — use whatever key names your data model has */
5
+ entity?: {
6
+ type: string;
7
+ [key: string]: unknown;
8
+ };
9
+ errorState?: {
10
+ code?: string;
11
+ message?: string;
12
+ field?: string;
13
+ };
14
+ /** Only `type` is required — use whatever key your model uses for identifiers */
15
+ selection?: {
16
+ type: string;
17
+ [key: string]: unknown;
18
+ };
19
+ formState?: Record<string, unknown>;
20
+ meta?: Record<string, unknown>;
21
+ }
2
22
  export interface DuctShellProps {
3
23
  /** Your Duct shell ID (e.g., "shell_acme_prod") */
4
24
  shellId: string;
@@ -15,6 +35,17 @@ export interface DuctShellProps {
15
35
  onTokenRequest?: (shellId: string) => Promise<string>;
16
36
  /** Called when the shell requests navigation to a URL (deeplink handoff) */
17
37
  onNavigate?: (url: string) => void;
38
+ /**
39
+ * Page Context Protocol — called when the shell needs to understand what
40
+ * the user is currently viewing (triggered by deictic references like "this",
41
+ * "that order", "the error on screen"). Return structured data about the
42
+ * current page state so the shell can resolve on-screen references without
43
+ * screenshots or computer-use techniques.
44
+ *
45
+ * Alternatively, use the `useDuctPageContext` hook in page-level components
46
+ * when this component is in a layout that doesn't have access to page state.
47
+ */
48
+ onPageContext?: () => DuctPageContext | Promise<DuctPageContext>;
18
49
  /** Controlled open state */
19
50
  open?: boolean;
20
51
  /** Called whenever shell open state changes */
@@ -50,7 +81,36 @@ export interface DuctShellProps {
50
81
  * When omitted, the SDK tries cloud-hosted icon first, then local /assets/logo.png.
51
82
  */
52
83
  launcherIconSrc?: string;
84
+ /**
85
+ * When true, the launcher is hidden until the shell status endpoint confirms
86
+ * the shell is live. Prevents showing the button before `duct push` has been run.
87
+ * @default false
88
+ */
89
+ readyCheck?: boolean;
90
+ }
91
+ export interface ShellStatusResult {
92
+ status: 'live' | 'not_ready' | 'suspended' | 'loading';
93
+ manifestReady: boolean;
94
+ widget?: {
95
+ welcomeMessage?: string;
96
+ placeholder?: string;
97
+ theme?: string;
98
+ primaryColor?: string;
99
+ width?: number | string;
100
+ height?: number | string;
101
+ };
53
102
  }
103
+ /**
104
+ * Hook that polls the shell status endpoint once on mount.
105
+ * Use when you need to conditionally render UI based on shell liveness.
106
+ *
107
+ * @example
108
+ * ```tsx
109
+ * const { status } = useShellStatus('shell_acme_prod', 'https://shell.duct.sh');
110
+ * if (status !== 'live') return null;
111
+ * ```
112
+ */
113
+ export declare function useShellStatus(shellId: string, shellHost?: string): ShellStatusResult;
54
114
  /**
55
115
  * DuctShell — a self-contained floating launcher button + chat panel.
56
116
  *
@@ -72,7 +132,7 @@ export interface DuctShellProps {
72
132
  * />
73
133
  * ```
74
134
  */
75
- export declare function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, open, onOpenChange, defaultOpen, shellHost, position, panelWidth, panelHeight, style, className, launcherIconSrc, }: DuctShellProps): React.ReactElement | null;
135
+ export declare function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, onPageContext, open, onOpenChange, defaultOpen, shellHost, position, panelWidth, panelHeight, style, className, launcherIconSrc, readyCheck, }: DuctShellProps): React.ReactElement | null;
76
136
  export interface DuctShellButtonProps {
77
137
  shellId: string;
78
138
  children?: React.ReactNode;
@@ -4,7 +4,44 @@
4
4
  // ============================================================
5
5
  "use client";
6
6
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
7
- import { useEffect, useRef, useCallback, useState, } from "react";
7
+ import React, { useEffect, useRef, useCallback, useState, } from "react";
8
+ /**
9
+ * Hook that polls the shell status endpoint once on mount.
10
+ * Use when you need to conditionally render UI based on shell liveness.
11
+ *
12
+ * @example
13
+ * ```tsx
14
+ * const { status } = useShellStatus('shell_acme_prod', 'https://shell.duct.sh');
15
+ * if (status !== 'live') return null;
16
+ * ```
17
+ */
18
+ export function useShellStatus(shellId, shellHost) {
19
+ const [result, setResult] = React.useState({ status: 'loading', manifestReady: false });
20
+ React.useEffect(() => {
21
+ if (!shellId)
22
+ return;
23
+ const host = (shellHost ?? DUCT_SHELL_HOST_DEFAULT).replace(/\/$/, '');
24
+ let cancelled = false;
25
+ fetch(`${host}/api/shell-status/${shellId}`)
26
+ .then((r) => r.json())
27
+ .then((data) => {
28
+ if (!cancelled) {
29
+ setResult({
30
+ status: (data.status ?? 'live'),
31
+ manifestReady: data.manifestReady ?? true,
32
+ widget: data.widget,
33
+ });
34
+ }
35
+ })
36
+ .catch(() => {
37
+ // Fail open — show shell on network error
38
+ if (!cancelled)
39
+ setResult({ status: 'live', manifestReady: true });
40
+ });
41
+ return () => { cancelled = true; };
42
+ }, [shellId, shellHost]);
43
+ return result;
44
+ }
8
45
  // ----------------------------------------------------------------
9
46
  // DuctShell — floating launcher + panel
10
47
  // ----------------------------------------------------------------
@@ -32,14 +69,32 @@ const DUCT_LAUNCHER_ICON_LOCAL_FALLBACK = "/assets/logo.png";
32
69
  * />
33
70
  * ```
34
71
  */
35
- export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, open, onOpenChange, defaultOpen = false, shellHost = DUCT_SHELL_HOST_DEFAULT, position = "bottom-right", panelWidth = 420, panelHeight = 640, style, className, launcherIconSrc, }) {
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, }) {
36
73
  const iframeRef = useRef(null);
37
74
  const [isReady, setIsReady] = useState(false);
38
75
  const [isOpen, setIsOpen] = useState(defaultOpen);
39
76
  const [isAnimating, setIsAnimating] = useState(false);
40
77
  const [iconCandidateIndex, setIconCandidateIndex] = useState(0);
41
78
  const [iconLoadFailed, setIconLoadFailed] = useState(false);
79
+ // Dynamic panel size — overridden by DUCT_PANEL_SIZE message from shell (manifest widget config)
80
+ const [dynamicWidth, setDynamicWidth] = useState(undefined);
81
+ const [dynamicHeight, setDynamicHeight] = useState(undefined);
82
+ // Shell liveness — only checked when readyCheck=true
83
+ const [shellLive, setShellLive] = useState(!readyCheck);
42
84
  const pendingTokenRequests = useRef(new Map());
85
+ // When readyCheck is enabled, poll status once on mount
86
+ useEffect(() => {
87
+ if (!readyCheck || !shellId)
88
+ return;
89
+ const host = shellHost.replace(/\/$/, '');
90
+ fetch(`${host}/api/shell-status/${shellId}`)
91
+ .then((r) => r.json())
92
+ .then((data) => {
93
+ if (data.status === 'live')
94
+ setShellLive(true);
95
+ })
96
+ .catch(() => setShellLive(true)); // fail open
97
+ }, [readyCheck, shellId, shellHost]);
43
98
  const controlled = open !== undefined;
44
99
  const panelOpen = controlled ? open : isOpen;
45
100
  const shellUrl = buildShellUrl(shellHost, shellId, userContext);
@@ -110,16 +165,46 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, op
110
165
  pendingTokenRequests.current.delete(requestId);
111
166
  break;
112
167
  }
113
- case "DUCT_DEEPLINK_NAVIGATE": {
114
- const { url } = msg;
115
- if (onNavigate) {
116
- onNavigate(url);
168
+ case "DUCT_REQUEST_CONTEXT": {
169
+ // Page Context Protocol — shell is asking what the user is currently viewing.
170
+ // Call onPageContext if provided; respond with null when not wired up so the
171
+ // shell doesn't hang. useDuctPageContext is the alternative for page-level components.
172
+ const { requestId } = msg;
173
+ if (!onPageContext) {
174
+ postToShell({ type: "DUCT_PAGE_CONTEXT", requestId, context: null });
175
+ break;
176
+ }
177
+ try {
178
+ const context = await onPageContext();
179
+ postToShell({ type: "DUCT_PAGE_CONTEXT", requestId, context });
117
180
  }
118
- else {
119
- window.location.href = url;
181
+ catch {
182
+ postToShell({ type: "DUCT_PAGE_CONTEXT", requestId, context: null });
120
183
  }
184
+ break;
185
+ }
186
+ case "DUCT_DEEPLINK_NAVIGATE": {
187
+ const { url } = msg;
121
188
  postToShell({ type: "DUCT_NAVIGATE_CONFIRMED", url });
122
189
  closePanel();
190
+ // Delay navigation until after the close animation (220ms) so the panel
191
+ // slides away before the page changes — avoids a jarring simultaneous transition.
192
+ setTimeout(() => {
193
+ if (onNavigate) {
194
+ onNavigate(url);
195
+ }
196
+ else {
197
+ window.location.href = url;
198
+ }
199
+ }, 230);
200
+ break;
201
+ }
202
+ case "DUCT_PANEL_SIZE": {
203
+ // Shell communicates its preferred dimensions from manifest widget config.
204
+ if (msg.width !== undefined)
205
+ setDynamicWidth(msg.width);
206
+ if (msg.height !== undefined)
207
+ setDynamicHeight(msg.height);
123
208
  break;
124
209
  }
125
210
  case "DUCT_OPEN": {
@@ -131,7 +216,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, op
131
216
  break;
132
217
  }
133
218
  }
134
- }, [shellOrigin, userContext, onTokenRequest, postToShell, onNavigate, openPanel, closePanel]);
219
+ }, [shellOrigin, userContext, onTokenRequest, onPageContext, postToShell, onNavigate, openPanel, closePanel]);
135
220
  useEffect(() => {
136
221
  window.addEventListener("message", handleMessage);
137
222
  return () => window.removeEventListener("message", handleMessage);
@@ -165,15 +250,24 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, op
165
250
  console.error("[DuctShell] shellId prop is required");
166
251
  return null;
167
252
  }
253
+ // Hide entirely until readyCheck confirms the shell is live
254
+ if (!shellLive)
255
+ return null;
168
256
  const isRight = position === "bottom-right";
169
257
  const panelVisible = panelOpen || isAnimating;
170
- // Responsive: full-screen on small viewports
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;
171
265
  const panelStyle = {
172
266
  position: "fixed",
173
267
  bottom: "80px",
174
268
  [isRight ? "right" : "left"]: "16px",
175
- width: `min(${panelWidth}px, calc(100vw - 32px))`,
176
- height: `min(${panelHeight}px, calc(100dvh - 96px))`,
269
+ width: `min(${widthVal}, calc(100vw - 32px))`,
270
+ height: `min(${heightVal}, calc(100dvh - 96px))`,
177
271
  zIndex: 9998,
178
272
  borderRadius: "16px",
179
273
  overflow: "hidden",
@@ -203,19 +297,19 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, op
203
297
  display: "flex",
204
298
  alignItems: "center",
205
299
  justifyContent: "center",
206
- backgroundColor: "#E8622A",
207
- boxShadow: "0 4px 16px rgba(232,98,42,0.40), 0 2px 8px rgba(0,0,0,0.12)",
300
+ backgroundColor: "#0C0B09",
301
+ boxShadow: "0 4px 16px rgba(0,0,0,0.40), 0 2px 8px rgba(0,0,0,0.20)",
208
302
  padding: 0,
209
303
  transition: "transform 150ms ease, box-shadow 150ms ease",
210
304
  };
211
305
  return (_jsxs(_Fragment, { children: [!panelOpen && (_jsx("button", { type: "button", style: buttonStyle, onClick: openPanel, "aria-label": "Open Duct Shell", className: className, onMouseEnter: (e) => {
212
306
  e.currentTarget.style.transform = "scale(1.07)";
213
307
  e.currentTarget.style.boxShadow =
214
- "0 6px 20px rgba(232,98,42,0.50), 0 2px 8px rgba(0,0,0,0.14)";
308
+ "0 6px 20px rgba(0,0,0,0.50), 0 2px 8px rgba(0,0,0,0.20)";
215
309
  }, onMouseLeave: (e) => {
216
310
  e.currentTarget.style.transform = "scale(1)";
217
311
  e.currentTarget.style.boxShadow =
218
- "0 4px 16px rgba(232,98,42,0.40), 0 2px 8px rgba(0,0,0,0.12)";
312
+ "0 4px 16px rgba(0,0,0,0.40), 0 2px 8px rgba(0,0,0,0.20)";
219
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: {
220
314
  width: "100%",
221
315
  height: "100%",
@@ -0,0 +1,32 @@
1
+ import type { DuctPageContext } from "../../core/types.js";
2
+ export interface UseDuctPageContextOptions {
3
+ /**
4
+ * The Duct shell host URL (e.g. "https://shell.duct.sh" or "http://localhost:3000").
5
+ * When provided, the hook validates event.origin against this value — only the
6
+ * Duct iframe can request page context, blocking arbitrary cross-origin access.
7
+ * When omitted, the hook accepts requests from any origin (useful in dev/test).
8
+ */
9
+ shellHost?: string;
10
+ }
11
+ /**
12
+ * useDuctPageContext — company-side hook for the Page Context Protocol.
13
+ *
14
+ * Listens for DUCT_REQUEST_CONTEXT postMessages from the Duct shell iframe.
15
+ * When one arrives, calls your resolver and sends the result back as DUCT_PAGE_CONTEXT.
16
+ *
17
+ * The resolver may be async (e.g. pulling live data from a store or API).
18
+ * If it throws, the hook responds with `context: null` so the shell doesn't hang.
19
+ *
20
+ * The hook uses a ref for the resolver so it always calls the latest closure
21
+ * without needing to remove/re-add the event listener on every render.
22
+ *
23
+ * SECURITY: Never include passwords, tokens, card numbers, or other sensitive fields
24
+ * in `formState`. The shell forwards this data to Duct's routing service. Only include
25
+ * fields that describe visible, non-sensitive form state (e.g. a selected option, a search
26
+ * term, a draft title). Duct strips known sensitive field names server-side, but
27
+ * defense-in-depth starts here.
28
+ *
29
+ * @param resolver — function that returns the current page context
30
+ * @param options — configuration including optional shellHost for origin validation
31
+ */
32
+ export declare function useDuctPageContext(resolver: () => DuctPageContext | Promise<DuctPageContext>, options?: UseDuctPageContextOptions): void;