@duct-sdk/sdk 0.4.0 → 0.4.2

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,18 @@
2
2
 
3
3
  Public release notes for the Duct SDK. Versioning follows [semver](https://semver.org).
4
4
 
5
+ ## [0.4.2] — 2026-07-03
6
+
7
+ ### Fixed
8
+ - **`DuctShell` drag position after handoff** — panel drag position is now persisted in `localStorage` alongside the launcher bubble, so deeplink/sign-in navigations no longer reset a repositioned embed. Legacy `{ x, y }` bubble-only storage remains supported.
9
+
10
+ ## [0.4.1] — 2026-07-03
11
+
12
+ ### Added
13
+ - **`auth.loginRoutePath` and `auth.loginDeeplinkId`** — optional manifest fields that tell the shell where to send unauthenticated users before invoking `requiresAuth` actions.
14
+ - **`core/login-handoff.ts`** — `detectLoginRoutePath()`, `enrichAuthLoginHandoff()`, and `resolveLoginHandoff()` helpers shared with codegen.
15
+ - **`duct init` auto-wiring** — pipeline sets `loginRoutePath` (and `loginDeeplinkId` when a matching deeplink exists) from discovered routes.
16
+
5
17
  ## [0.4.0] — 2026-07-02
6
18
 
7
19
  ### Added
@@ -116,6 +116,46 @@ function ShellDragHandle({ onPointerDown, isDragging, isDark, label = "Drag to m
116
116
  : "0 8px 24px rgba(12,11,9,0.12)",
117
117
  }, children: label }))] }));
118
118
  }
119
+ function shellLayoutStorageKey(shellId) {
120
+ return `duct-shell-pos:${shellId}`;
121
+ }
122
+ /** Read persisted bubble/panel positions (supports legacy `{ x, y }` bubble-only blobs). */
123
+ function readStoredShellLayout(shellId) {
124
+ if (typeof window === "undefined")
125
+ return {};
126
+ try {
127
+ const raw = window.localStorage.getItem(shellLayoutStorageKey(shellId));
128
+ if (!raw)
129
+ return {};
130
+ const parsed = JSON.parse(raw);
131
+ if (!parsed || typeof parsed !== "object")
132
+ return {};
133
+ if ("x" in parsed && "y" in parsed) {
134
+ const legacy = parsed;
135
+ if (typeof legacy.x === "number" && typeof legacy.y === "number") {
136
+ return { bubble: { x: legacy.x, y: legacy.y } };
137
+ }
138
+ }
139
+ const layout = parsed;
140
+ const out = {};
141
+ if (layout.bubble && typeof layout.bubble.x === "number" && typeof layout.bubble.y === "number") {
142
+ out.bubble = layout.bubble;
143
+ }
144
+ if (layout.panel && typeof layout.panel.x === "number" && typeof layout.panel.y === "number") {
145
+ out.panel = layout.panel;
146
+ }
147
+ return out;
148
+ }
149
+ catch {
150
+ return {};
151
+ }
152
+ }
153
+ function writeStoredShellLayout(shellId, layout) {
154
+ try {
155
+ window.localStorage.setItem(shellLayoutStorageKey(shellId), JSON.stringify(layout));
156
+ }
157
+ catch { /* ignore quota / private mode */ }
158
+ }
119
159
  /** Keep a dragged panel visible inside the viewport. */
120
160
  function clampPanel(x, y, width, height) {
121
161
  if (typeof window === "undefined")
@@ -407,21 +447,35 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
407
447
  mq.addEventListener("change", handler);
408
448
  return () => mq.removeEventListener("change", handler);
409
449
  }, [theme]);
410
- // Restore a previously dragged bubble position.
450
+ // Restore bubble position saved from a prior visit (survives deeplink handoff navigations).
411
451
  useEffect(() => {
412
452
  if (!draggable || typeof window === "undefined")
413
453
  return;
414
- try {
415
- const raw = window.localStorage.getItem(`duct-shell-pos:${shellId}`);
416
- if (raw) {
417
- const parsed = JSON.parse(raw);
418
- if (typeof parsed.x === "number" && typeof parsed.y === "number") {
419
- setBubblePos(clampBubble(parsed.x, parsed.y));
420
- }
421
- }
454
+ const layout = readStoredShellLayout(shellId);
455
+ if (layout.bubble) {
456
+ setBubblePos(clampBubble(layout.bubble.x, layout.bubble.y));
422
457
  }
423
- catch { /* ignore corrupt storage */ }
424
458
  }, [shellId, draggable]);
459
+ // Restore or re-clamp panel position when dimensions change (e.g. manifest widget preset).
460
+ useEffect(() => {
461
+ if (!draggable || typeof window === "undefined")
462
+ return;
463
+ const dims = resolveShellDimensions({
464
+ preset: dynamicPreset ?? preset,
465
+ width: dynamicWidth ?? panelWidth,
466
+ height: dynamicHeight ?? panelHeight,
467
+ });
468
+ const w = typeof dims.width === "number" ? dims.width : panelWidth;
469
+ const h = typeof dims.height === "number" ? dims.height : panelHeight;
470
+ setPanelPos((prev) => {
471
+ if (prev)
472
+ return clampPanel(prev.x, prev.y, w, h);
473
+ const stored = readStoredShellLayout(shellId).panel;
474
+ if (!stored)
475
+ return null;
476
+ return clampPanel(stored.x, stored.y, w, h);
477
+ });
478
+ }, [shellId, draggable, dynamicPreset, preset, dynamicWidth, panelWidth, dynamicHeight, panelHeight]);
425
479
  // Launcher bubble: pointer stays default until the user actually drags (4px threshold).
426
480
  // A tap opens; a drag repositions — no separate handle or grab cursor on hover.
427
481
  const onBubblePointerDown = useCallback((e) => {
@@ -471,10 +525,7 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
471
525
  const pos = finalPos ?? bubbleDragPending.current;
472
526
  if (pos) {
473
527
  setBubblePos(pos);
474
- try {
475
- window.localStorage.setItem(`duct-shell-pos:${shellId}`, JSON.stringify(pos));
476
- }
477
- catch { /* ignore */ }
528
+ writeStoredShellLayout(shellId, { bubble: pos });
478
529
  }
479
530
  setPanelPos(null);
480
531
  }
@@ -519,11 +570,16 @@ export function DuctShell({ shellId, userContext, onTokenRequest, onNavigate, on
519
570
  window.removeEventListener("pointerup", onUp);
520
571
  panelDragState.current = null;
521
572
  setIsPanelDragging(false);
522
- cancelRafUpdate(panelDragRaf, panelDragPending, commitPanelPos);
573
+ const finalPos = cancelRafUpdate(panelDragRaf, panelDragPending, commitPanelPos);
574
+ if (finalPos) {
575
+ setPanelPos(finalPos);
576
+ const layout = readStoredShellLayout(shellId);
577
+ writeStoredShellLayout(shellId, { ...layout, panel: finalPos });
578
+ }
523
579
  };
524
580
  window.addEventListener("pointermove", onMove);
525
581
  window.addEventListener("pointerup", onUp);
526
- }, [draggable]);
582
+ }, [draggable, shellId]);
527
583
  if (!shellId) {
528
584
  console.error("[DuctShell] shellId prop is required");
529
585
  return null;
@@ -12,6 +12,7 @@ import { applyDeterministicRules } from "../processors/postprocess.js";
12
12
  import { verifyDiscoveryAgainstFilesystem } from "../processors/verify-discovery.js";
13
13
  import { parseOpenApiSpec } from "../processors/openapi-parser.js";
14
14
  import { parseCurlCollection } from "../processors/curl-parser.js";
15
+ import { enrichAuthLoginHandoff } from "../../core/login-handoff.js";
15
16
  // ----------------------------------------------------------------
16
17
  // Default emitter (uses Node EventEmitter)
17
18
  // ----------------------------------------------------------------
@@ -400,6 +401,7 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
400
401
  }
401
402
  }
402
403
  const durationMs = Date.now() - startTime;
404
+ auth = enrichAuthLoginHandoff(auth, routes, deeplinks);
403
405
  const pipelineResult = {
404
406
  routes,
405
407
  actions,
@@ -146,6 +146,12 @@ function generateAuth(auth, indentSpaces) {
146
146
  if (auth.customClaims && Object.keys(auth.customClaims).length > 0) {
147
147
  lines.push(`${pad} customClaims: ${jsonValue(auth.customClaims, indentSpaces + 2)},`);
148
148
  }
149
+ if (auth.loginDeeplinkId) {
150
+ lines.push(`${pad} loginDeeplinkId: ${JSON.stringify(auth.loginDeeplinkId)},`);
151
+ }
152
+ if (auth.loginRoutePath) {
153
+ lines.push(`${pad} loginRoutePath: ${JSON.stringify(auth.loginRoutePath)},`);
154
+ }
149
155
  return `auth: {\n${lines.join("\n")}\n${pad}},`;
150
156
  }
151
157
  function generateDeeplinks(deeplinks, indentSpaces) {
@@ -31,6 +31,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
31
31
  tokenExpirySeconds: z.ZodDefault<z.ZodNumber>;
32
32
  tokenEndpoint: z.ZodOptional<z.ZodString>;
33
33
  customClaims: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
34
+ loginDeeplinkId: z.ZodOptional<z.ZodString>;
35
+ loginRoutePath: z.ZodOptional<z.ZodString>;
34
36
  }, "strip", z.ZodTypeAny, {
35
37
  strategy: "none" | "nextauth" | "clerk" | "auth0" | "custom-jwt" | "session-cookie" | "unknown";
36
38
  sessionFields: string[];
@@ -38,6 +40,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
38
40
  tokenExpirySeconds: number;
39
41
  tokenEndpoint?: string | undefined;
40
42
  customClaims?: Record<string, string> | undefined;
43
+ loginDeeplinkId?: string | undefined;
44
+ loginRoutePath?: string | undefined;
41
45
  }, {
42
46
  strategy: "none" | "nextauth" | "clerk" | "auth0" | "custom-jwt" | "session-cookie" | "unknown";
43
47
  guestAllowed: boolean;
@@ -45,6 +49,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
45
49
  tokenExpirySeconds?: number | undefined;
46
50
  tokenEndpoint?: string | undefined;
47
51
  customClaims?: Record<string, string> | undefined;
52
+ loginDeeplinkId?: string | undefined;
53
+ loginRoutePath?: string | undefined;
48
54
  }>;
49
55
  routes: z.ZodDefault<z.ZodArray<z.ZodObject<{
50
56
  path: z.ZodString;
@@ -361,6 +367,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
361
367
  tokenExpirySeconds: number;
362
368
  tokenEndpoint?: string | undefined;
363
369
  customClaims?: Record<string, string> | undefined;
370
+ loginDeeplinkId?: string | undefined;
371
+ loginRoutePath?: string | undefined;
364
372
  };
365
373
  shellId: string;
366
374
  product: {
@@ -468,6 +476,8 @@ export declare const DuctConfigSchema: z.ZodObject<{
468
476
  tokenExpirySeconds?: number | undefined;
469
477
  tokenEndpoint?: string | undefined;
470
478
  customClaims?: Record<string, string> | undefined;
479
+ loginDeeplinkId?: string | undefined;
480
+ loginRoutePath?: string | undefined;
471
481
  };
472
482
  shellId: string;
473
483
  product: {
@@ -91,6 +91,12 @@ const AuthSchemaSchema = z.object({
91
91
  tokenExpirySeconds: z.number().positive().default(60),
92
92
  tokenEndpoint: z.string().url().optional(),
93
93
  customClaims: z.record(z.string()).optional(),
94
+ loginDeeplinkId: z
95
+ .string()
96
+ .min(1)
97
+ .regex(/^[a-z_][a-z0-9_]*$/, "loginDeeplinkId must be snake_case")
98
+ .optional(),
99
+ loginRoutePath: z.string().min(1).startsWith("/").optional(),
94
100
  });
95
101
  const StateFieldSchema = z.object({
96
102
  key: z.string().min(1),
@@ -0,0 +1,41 @@
1
+ export interface LoginRouteLike {
2
+ path: string;
3
+ }
4
+ export interface LoginDeeplinkLike {
5
+ id: string;
6
+ pathTemplate?: string;
7
+ targetRoute?: string;
8
+ }
9
+ export interface LoginAuthConfig {
10
+ guestAllowed?: boolean;
11
+ loginDeeplinkId?: string;
12
+ loginRoutePath?: string;
13
+ }
14
+ export interface LoginHandoffManifest {
15
+ baseUrl?: string;
16
+ auth?: LoginAuthConfig;
17
+ deeplinks?: LoginDeeplinkLike[];
18
+ routes?: LoginRouteLike[];
19
+ }
20
+ export interface LoginHandoffTarget {
21
+ deeplinkId: string;
22
+ url: string;
23
+ message: string;
24
+ }
25
+ export declare const DEFAULT_LOGIN_HANDOFF_MESSAGE = "You'll need to sign in first \u2014 I'll take you there now.";
26
+ /** Normalize dynamic route patterns to a static path prefix for navigation. */
27
+ export declare function normalizeRoutePathForLogin(path: string): string;
28
+ /**
29
+ * Pick the best login route path from a manifest route inventory.
30
+ * Used by `duct init` to populate `auth.loginRoutePath`.
31
+ */
32
+ export declare function detectLoginRoutePath(routes: LoginRouteLike[]): string | undefined;
33
+ /**
34
+ * Resolve where the shell should send an unauthenticated user to sign in.
35
+ * Priority: explicit deeplink id → explicit route path → deeplink heuristic → route heuristic.
36
+ */
37
+ export declare function resolveLoginHandoff(manifest: LoginHandoffManifest | null | undefined): LoginHandoffTarget | null;
38
+ /** True when the shell should treat the caller as unauthenticated. */
39
+ export declare function shellNeedsUserToken(manifest: LoginHandoffManifest | null | undefined, userToken?: string | null): boolean;
40
+ /** Attach login handoff fields discovered from routes/deeplinks during init. */
41
+ export declare function enrichAuthLoginHandoff<T extends LoginAuthConfig>(auth: T, routes: LoginRouteLike[], deeplinks?: LoginDeeplinkLike[]): T;
@@ -0,0 +1,133 @@
1
+ // ============================================================
2
+ // Login handoff — resolve where unauthenticated shell users sign in
3
+ // ============================================================
4
+ /** Route path segments that commonly represent a sign-in page. */
5
+ const LOGIN_ROUTE_RE = /^\/(login|signin|sign-in|auth\/signin|auth\/login|account\/login)(\/|$)/i;
6
+ const LOGIN_ID_RE = /login|sign[_-]?in/i;
7
+ export const DEFAULT_LOGIN_HANDOFF_MESSAGE = "You'll need to sign in first — I'll take you there now.";
8
+ /** Normalize dynamic route patterns to a static path prefix for navigation. */
9
+ export function normalizeRoutePathForLogin(path) {
10
+ const withoutQuery = path.split("?")[0] ?? path;
11
+ const staticPrefix = withoutQuery.split("[")[0].split(":")[0];
12
+ const trimmed = staticPrefix.replace(/\/+$/, "");
13
+ if (!trimmed)
14
+ return "/";
15
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
16
+ }
17
+ function isLoginPath(path) {
18
+ return LOGIN_ROUTE_RE.test(normalizeRoutePathForLogin(path));
19
+ }
20
+ function buildHandoffUrl(baseUrl, path) {
21
+ const trimmed = path.trim();
22
+ if (!trimmed)
23
+ return null;
24
+ if (/^https?:\/\//i.test(trimmed))
25
+ return trimmed;
26
+ if (trimmed.startsWith("/"))
27
+ return trimmed;
28
+ if (baseUrl) {
29
+ try {
30
+ return new URL(trimmed, baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`).pathname;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ return null;
37
+ }
38
+ /**
39
+ * Pick the best login route path from a manifest route inventory.
40
+ * Used by `duct init` to populate `auth.loginRoutePath`.
41
+ */
42
+ export function detectLoginRoutePath(routes) {
43
+ for (const route of routes) {
44
+ if (!route.path)
45
+ continue;
46
+ const normalized = normalizeRoutePathForLogin(route.path);
47
+ if (isLoginPath(normalized))
48
+ return normalized;
49
+ }
50
+ return undefined;
51
+ }
52
+ /**
53
+ * Resolve where the shell should send an unauthenticated user to sign in.
54
+ * Priority: explicit deeplink id → explicit route path → deeplink heuristic → route heuristic.
55
+ */
56
+ export function resolveLoginHandoff(manifest) {
57
+ if (!manifest)
58
+ return null;
59
+ const baseUrl = manifest.baseUrl;
60
+ const auth = manifest.auth;
61
+ const explicitDlId = auth?.loginDeeplinkId?.trim();
62
+ if (explicitDlId) {
63
+ const dl = manifest.deeplinks?.find((d) => d.id === explicitDlId);
64
+ const path = dl?.pathTemplate ?? dl?.targetRoute;
65
+ const url = path ? buildHandoffUrl(baseUrl, path) : null;
66
+ if (url) {
67
+ return {
68
+ deeplinkId: explicitDlId,
69
+ url,
70
+ message: DEFAULT_LOGIN_HANDOFF_MESSAGE,
71
+ };
72
+ }
73
+ }
74
+ const explicitRoute = auth?.loginRoutePath?.trim();
75
+ if (explicitRoute) {
76
+ const url = buildHandoffUrl(baseUrl, normalizeRoutePathForLogin(explicitRoute));
77
+ if (url) {
78
+ return {
79
+ deeplinkId: explicitDlId ?? "login_page",
80
+ url,
81
+ message: DEFAULT_LOGIN_HANDOFF_MESSAGE,
82
+ };
83
+ }
84
+ }
85
+ for (const dl of manifest.deeplinks ?? []) {
86
+ const path = dl.pathTemplate ?? dl.targetRoute ?? "";
87
+ if (LOGIN_ID_RE.test(dl.id) || isLoginPath(path)) {
88
+ const url = buildHandoffUrl(baseUrl, path);
89
+ if (url) {
90
+ return {
91
+ deeplinkId: dl.id,
92
+ url,
93
+ message: DEFAULT_LOGIN_HANDOFF_MESSAGE,
94
+ };
95
+ }
96
+ }
97
+ }
98
+ for (const route of manifest.routes ?? []) {
99
+ if (!route.path || !isLoginPath(route.path))
100
+ continue;
101
+ const url = buildHandoffUrl(baseUrl, normalizeRoutePathForLogin(route.path));
102
+ if (url) {
103
+ return {
104
+ deeplinkId: "login_page",
105
+ url,
106
+ message: DEFAULT_LOGIN_HANDOFF_MESSAGE,
107
+ };
108
+ }
109
+ }
110
+ return null;
111
+ }
112
+ /** True when the shell should treat the caller as unauthenticated. */
113
+ export function shellNeedsUserToken(manifest, userToken) {
114
+ if (manifest?.auth?.guestAllowed === true)
115
+ return false;
116
+ return !userToken?.trim();
117
+ }
118
+ /** Attach login handoff fields discovered from routes/deeplinks during init. */
119
+ export function enrichAuthLoginHandoff(auth, routes, deeplinks = []) {
120
+ const enriched = { ...auth };
121
+ if (!enriched.loginRoutePath) {
122
+ const detected = detectLoginRoutePath(routes);
123
+ if (detected)
124
+ enriched.loginRoutePath = detected;
125
+ }
126
+ if (!enriched.loginDeeplinkId) {
127
+ const dl = deeplinks.find((d) => LOGIN_ID_RE.test(d.id) ||
128
+ isLoginPath(d.pathTemplate ?? d.targetRoute ?? ""));
129
+ if (dl)
130
+ enriched.loginDeeplinkId = dl.id;
131
+ }
132
+ return enriched;
133
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,31 @@
1
+ import { describe, it } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { detectLoginRoutePath, enrichAuthLoginHandoff, resolveLoginHandoff, } from './login-handoff.js';
4
+ describe('detectLoginRoutePath', () => {
5
+ it('finds common login paths', () => {
6
+ assert.equal(detectLoginRoutePath([
7
+ { path: '/dashboard' },
8
+ { path: '/auth/signin' },
9
+ ]), '/auth/signin');
10
+ });
11
+ });
12
+ describe('enrichAuthLoginHandoff', () => {
13
+ it('adds loginRoutePath from routes', () => {
14
+ const auth = enrichAuthLoginHandoff({
15
+ strategy: 'nextauth',
16
+ sessionFields: ['userId'],
17
+ guestAllowed: false,
18
+ tokenExpirySeconds: 300,
19
+ }, [{ path: '/login' }]);
20
+ assert.equal(auth.loginRoutePath, '/login');
21
+ });
22
+ });
23
+ describe('resolveLoginHandoff', () => {
24
+ it('prefers explicit loginRoutePath', () => {
25
+ const target = resolveLoginHandoff({
26
+ baseUrl: 'https://app.example.com',
27
+ auth: { guestAllowed: false, loginRoutePath: '/sign-in' },
28
+ });
29
+ assert.equal(target?.url, '/sign-in');
30
+ });
31
+ });
@@ -124,6 +124,16 @@ export interface AuthSchema {
124
124
  tokenEndpoint?: string;
125
125
  /** Custom claims added to tokens */
126
126
  customClaims?: Record<string, string>;
127
+ /**
128
+ * Deeplink id for the sign-in page. When an unauthenticated user hits a
129
+ * requiresAuth action, the shell navigates here instead of showing an error.
130
+ */
131
+ loginDeeplinkId?: string;
132
+ /**
133
+ * App route path for sign-in (e.g. `/login`). Used when no login deeplink is
134
+ * declared — auto-detected from routes during `duct init` when possible.
135
+ */
136
+ loginRoutePath?: string;
127
137
  /** Agent detection confidence (0.0–1.0). */
128
138
  confidence?: number;
129
139
  /** Files and signals that led to this auth strategy being detected. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@duct-sdk/sdk",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
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",