@duct-sdk/sdk 0.3.12 → 0.4.1

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 (63) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/adapters/next/receiver.d.ts +2 -6
  3. package/dist/adapters/next/receiver.js +20 -66
  4. package/dist/adapters/remix/receiver.d.ts +2 -6
  5. package/dist/adapters/remix/receiver.js +16 -33
  6. package/dist/adapters/sveltekit/receiver.d.ts +2 -6
  7. package/dist/adapters/sveltekit/receiver.js +13 -40
  8. package/dist/adapters/vite/receiver.d.ts +2 -4
  9. package/dist/adapters/vite/receiver.js +13 -30
  10. package/dist/cli/agents/api-agent.d.ts +3 -1
  11. package/dist/cli/agents/api-agent.js +22 -11
  12. package/dist/cli/agents/auth-agent.js +4 -4
  13. package/dist/cli/agents/pipeline.js +65 -7
  14. package/dist/cli/agents/route-agent.d.ts +3 -1
  15. package/dist/cli/agents/route-agent.js +17 -6
  16. package/dist/cli/detectors/topology.d.ts +1 -1
  17. package/dist/cli/detectors/topology.js +1 -1
  18. package/dist/cli/generators/config.js +77 -44
  19. package/dist/cli/generators/config.test.d.ts +1 -0
  20. package/dist/cli/generators/config.test.js +219 -0
  21. package/dist/cli/generators/normalize.d.ts +10 -0
  22. package/dist/cli/generators/normalize.js +49 -0
  23. package/dist/cli/generators/receiver.d.ts +2 -1
  24. package/dist/cli/generators/receiver.js +20 -201
  25. package/dist/cli/generators/token-route.d.ts +8 -0
  26. package/dist/cli/generators/token-route.js +235 -0
  27. package/dist/cli/generators/token-route.test.d.ts +1 -0
  28. package/dist/cli/generators/token-route.test.js +53 -0
  29. package/dist/cli/generators/wiring-snippets.d.ts +23 -0
  30. package/dist/cli/generators/wiring-snippets.js +233 -0
  31. package/dist/cli/generators/wiring-snippets.test.d.ts +1 -0
  32. package/dist/cli/generators/wiring-snippets.test.js +66 -0
  33. package/dist/cli/index.js +41 -1
  34. package/dist/cli/init.d.ts +1 -7
  35. package/dist/cli/init.js +100 -53
  36. package/dist/cli/output-paths.d.ts +10 -0
  37. package/dist/cli/output-paths.js +60 -0
  38. package/dist/cli/processors/curl-parser.test.d.ts +1 -0
  39. package/dist/cli/processors/curl-parser.test.js +24 -0
  40. package/dist/cli/processors/integration-audit.d.ts +23 -0
  41. package/dist/cli/processors/integration-audit.js +208 -0
  42. package/dist/cli/processors/integration-audit.test.d.ts +1 -0
  43. package/dist/cli/processors/integration-audit.test.js +154 -0
  44. package/dist/cli/processors/prisma-parser.js +1 -1
  45. package/dist/cli/processors/verify-discovery.d.ts +33 -0
  46. package/dist/cli/processors/verify-discovery.js +193 -0
  47. package/dist/cli/processors/verify-discovery.test.d.ts +1 -0
  48. package/dist/cli/processors/verify-discovery.test.js +153 -0
  49. package/dist/cli/processors/zod-extractor.js +1 -1
  50. package/dist/core/config.d.ts +26 -0
  51. package/dist/core/config.js +65 -28
  52. package/dist/core/endpoints.d.ts +2 -0
  53. package/dist/core/endpoints.js +10 -0
  54. package/dist/core/login-handoff.d.ts +41 -0
  55. package/dist/core/login-handoff.js +133 -0
  56. package/dist/core/login-handoff.test.d.ts +1 -0
  57. package/dist/core/login-handoff.test.js +31 -0
  58. package/dist/core/receiver.d.ts +33 -0
  59. package/dist/core/receiver.js +77 -0
  60. package/dist/core/types.d.ts +10 -0
  61. package/dist/server.d.ts +2 -0
  62. package/dist/server.js +2 -0
  63. package/package.json +2 -1
@@ -9,8 +9,10 @@ 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 { verifyDiscoveryAgainstFilesystem } from "../processors/verify-discovery.js";
12
13
  import { parseOpenApiSpec } from "../processors/openapi-parser.js";
13
14
  import { parseCurlCollection } from "../processors/curl-parser.js";
15
+ import { enrichAuthLoginHandoff } from "../../core/login-handoff.js";
14
16
  // ----------------------------------------------------------------
15
17
  // Default emitter (uses Node EventEmitter)
16
18
  // ----------------------------------------------------------------
@@ -58,9 +60,22 @@ function defaultAuth() {
58
60
  sessionFields: ["id", "email"],
59
61
  guestAllowed: true,
60
62
  tokenExpirySeconds: 300,
61
- tokenEndpoint: "/api/duct/token",
62
63
  };
63
64
  }
65
+ async function runAgentWithEmptyRetry(agentName, run, isEmpty, timeoutMs, emitter) {
66
+ let result = await withTimeout(() => run(false), timeoutMs, agentName);
67
+ if (!isEmpty(result)) {
68
+ return result;
69
+ }
70
+ emitter?.emitEvent({
71
+ type: "agent:start",
72
+ agent: agentName,
73
+ message: `${agentName} returned no results — retrying once…`,
74
+ progress: 15,
75
+ });
76
+ result = await withTimeout(() => run(true), timeoutMs, agentName);
77
+ return result;
78
+ }
64
79
  function defaultDeeplinks() {
65
80
  return [];
66
81
  }
@@ -104,6 +119,7 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
104
119
  let routes;
105
120
  let actions;
106
121
  let auth;
122
+ let shouldVerifyAgainstFilesystem = false;
107
123
  if (curlCollectionContent) {
108
124
  const [curlResult, authResult] = await Promise.all([
109
125
  (async () => {
@@ -162,9 +178,8 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
162
178
  auth = authResult;
163
179
  }
164
180
  else if (apiSpecContent) {
165
- // ── Spec mode: parse deterministically (no LLM needed for routes/actions) ──────
166
- // Auth agent still runs in parallel since it reads project source files.
167
- const [specResult, authResult] = await Promise.all([
181
+ // ── Spec mode: parse actions from OpenAPI; still discover UI routes via RouteAgent ──
182
+ const [specResult, authResult, routeResult] = await Promise.all([
168
183
  (async () => {
169
184
  emitter?.emitEvent({
170
185
  type: "agent:start",
@@ -215,13 +230,41 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
215
230
  return defaultAuth();
216
231
  }
217
232
  })(),
233
+ (async () => {
234
+ if (skipAgents.includes("routes"))
235
+ return defaultRoutes();
236
+ emitter?.emitEvent({
237
+ type: "agent:start",
238
+ agent: "RouteAgent",
239
+ message: "Discovering UI routes (OpenAPI spec does not include pages)…",
240
+ progress: 8,
241
+ });
242
+ try {
243
+ const result = await runAgentWithEmptyRetry("RouteAgent", (retry) => runRouteAgent(sandboxFs, readList?.routeFiles, { retry }), (value) => value.length === 0, agentTimeout, emitter);
244
+ emitter?.emitEvent({
245
+ type: "agent:complete",
246
+ agent: "RouteAgent",
247
+ message: `Found ${result.length} routes`,
248
+ result,
249
+ progress: 30,
250
+ });
251
+ return result;
252
+ }
253
+ catch (err) {
254
+ const error = err instanceof Error ? err : new Error(String(err));
255
+ emitter?.emitEvent({ type: "agent:error", agent: "RouteAgent", error, progress: 30 });
256
+ return defaultRoutes();
257
+ }
258
+ })(),
218
259
  ]);
219
- routes = specResult.routes;
260
+ routes = routeResult.length > 0 ? routeResult : specResult.routes;
220
261
  actions = specResult.actions;
221
262
  auth = authResult;
263
+ shouldVerifyAgainstFilesystem = true;
222
264
  }
223
265
  else {
224
266
  // ── Normal mode: full 3-agent parallel stage ────────────────────────────────
267
+ shouldVerifyAgainstFilesystem = true;
225
268
  const stage1Agents = [
226
269
  // Routes
227
270
  (async () => {
@@ -229,7 +272,7 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
229
272
  return defaultRoutes();
230
273
  emitter?.emitEvent({ type: "agent:start", agent: "RouteAgent", message: "Analyzing routes...", progress: 5 });
231
274
  try {
232
- const result = await withTimeout(() => runRouteAgent(sandboxFs, readList?.routeFiles), agentTimeout, "RouteAgent");
275
+ const result = await runAgentWithEmptyRetry("RouteAgent", (retry) => runRouteAgent(sandboxFs, readList?.routeFiles, { retry }), (value) => value.length === 0, agentTimeout, emitter);
233
276
  emitter?.emitEvent({
234
277
  type: "agent:complete",
235
278
  agent: "RouteAgent",
@@ -251,7 +294,7 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
251
294
  return defaultActions();
252
295
  emitter?.emitEvent({ type: "agent:start", agent: "ApiAgent", message: "Analyzing API endpoints...", progress: 5 });
253
296
  try {
254
- const result = await withTimeout(() => runApiAgent(sandboxFs, readList?.apiFiles), agentTimeout, "ApiAgent");
297
+ const result = await runAgentWithEmptyRetry("ApiAgent", (retry) => runApiAgent(sandboxFs, readList?.apiFiles, undefined, undefined, { retry }), (value) => value.length === 0, agentTimeout, emitter);
255
298
  emitter?.emitEvent({
256
299
  type: "agent:complete",
257
300
  agent: "ApiAgent",
@@ -292,6 +335,20 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
292
335
  ];
293
336
  [routes, actions, auth] = await Promise.all(stage1Agents);
294
337
  }
338
+ if (shouldVerifyAgainstFilesystem) {
339
+ const verification = await verifyDiscoveryAgainstFilesystem(sandboxFs, routes, actions);
340
+ routes = verification.routes;
341
+ actions = verification.actions;
342
+ if (verification.warnings.length > 0) {
343
+ emitter?.emitEvent({
344
+ type: "agent:complete",
345
+ message: `Filesystem verification: ${verification.downgradedRoutes + verification.downgradedActions} downgraded, ` +
346
+ `${verification.droppedRoutes + verification.droppedActions} dropped, ` +
347
+ `${verification.warnings.length} warning(s)`,
348
+ progress: 45,
349
+ });
350
+ }
351
+ }
295
352
  // Apply deterministic rules: enforce sideEffects from HTTP method,
296
353
  // derive sensitivityLevel from path/name keywords, and (in yesMode) auto-enable
297
354
  // agentAccessible on safe GET/HEAD with confidence ≥ 0.85.
@@ -344,6 +401,7 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
344
401
  }
345
402
  }
346
403
  const durationMs = Date.now() - startTime;
404
+ auth = enrichAuthLoginHandoff(auth, routes, deeplinks);
347
405
  const pipelineResult = {
348
406
  routes,
349
407
  actions,
@@ -12,4 +12,6 @@ export interface RouteScannerStrategy {
12
12
  * @param hintFiles - Optional pre-selected file paths from the file selector.
13
13
  * When provided, these are included first in the prompt as priority context.
14
14
  */
15
- export declare function runRouteAgent(sandboxFs: SandboxFS, hintFiles?: string[]): Promise<RouteManifest[]>;
15
+ export declare function runRouteAgent(sandboxFs: SandboxFS, hintFiles?: string[], options?: {
16
+ retry?: boolean;
17
+ }): Promise<RouteManifest[]>;
@@ -3,6 +3,7 @@
3
3
  // Analyzes project routes and produces RouteManifest[]
4
4
  // ============================================================
5
5
  import { callDuctLLM } from "./llm.js";
6
+ import { normalizeEvidenceArray } from "../processors/verify-discovery.js";
6
7
  // ── Next.js App Router ─────────────────────────────────────
7
8
  class NextAppRouterScanner {
8
9
  name = "NextAppRouter";
@@ -246,7 +247,7 @@ Confidence scoring rules:
246
247
  // ----------------------------------------------------------------
247
248
  // Prompt builder — uses RouteScannerStrategy
248
249
  // ----------------------------------------------------------------
249
- async function buildRoutePrompt(sandboxFs, hintFiles) {
250
+ async function buildRoutePrompt(sandboxFs, hintFiles, retryHint) {
250
251
  const lines = [];
251
252
  lines.push("Analyze this web project and identify all user-facing navigable routes.\n" +
252
253
  "Use the file structure and code snippets below to produce a RouteManifest array.\n");
@@ -323,6 +324,10 @@ For each user-facing route produce a RouteManifest entry:
323
324
 
324
325
  DO NOT include API routes (/api/...), auth callback routes, or static asset paths.
325
326
  DO NOT include _app, _document, layout-only files that don't produce a page.`);
327
+ if (retryHint) {
328
+ lines.push("");
329
+ lines.push(retryHint);
330
+ }
326
331
  return lines.join("\n");
327
332
  }
328
333
  // ----------------------------------------------------------------
@@ -333,8 +338,11 @@ DO NOT include _app, _document, layout-only files that don't produce a page.`);
333
338
  * @param hintFiles - Optional pre-selected file paths from the file selector.
334
339
  * When provided, these are included first in the prompt as priority context.
335
340
  */
336
- export async function runRouteAgent(sandboxFs, hintFiles) {
337
- const prompt = await buildRoutePrompt(sandboxFs, hintFiles);
341
+ export async function runRouteAgent(sandboxFs, hintFiles, options) {
342
+ const retryHint = options?.retry
343
+ ? "RETRY: Your previous pass returned zero routes. Re-read the snippets and include every user-facing page you can verify from file evidence."
344
+ : undefined;
345
+ const prompt = await buildRoutePrompt(sandboxFs, hintFiles, retryHint);
338
346
  const result = await callDuctLLM({
339
347
  agentName: "RouteAgent",
340
348
  systemPrompt: "You are an expert at analyzing Next.js, Remix, and React web application codebases. " +
@@ -364,9 +372,12 @@ export async function runRouteAgent(sandboxFs, hintFiles) {
364
372
  requiresAuth: r.requiresAuth ?? true,
365
373
  deeplinkable: r.deeplinkable ?? false,
366
374
  methods: r.methods,
367
- // Preserve confidence and evidence from LLM output
368
- ...(typeof r.confidence === "number" ? { confidence: Math.min(1, Math.max(0, r.confidence)) } : {}),
369
- ...(typeof r.evidence === "string" && r.evidence ? { evidence: r.evidence } : {}),
375
+ ...(typeof r.confidence === "number"
376
+ ? { confidence: Math.min(1, Math.max(0, r.confidence)) }
377
+ : {}),
378
+ ...(normalizeEvidenceArray(r.evidence).length > 0
379
+ ? { evidence: normalizeEvidenceArray(r.evidence) }
380
+ : {}),
370
381
  }));
371
382
  return routes;
372
383
  }
@@ -35,7 +35,7 @@ export interface TopoResult {
35
35
  */
36
36
  export declare function discoverTopology(projectRoot: string): Promise<TopoResult>;
37
37
  /**
38
- * Detect project topology for the selector pipeline (Phase 0).
38
+ * Detect project topology for the selector pipeline.
39
39
  *
40
40
  * Returns an enriched TopoResult with plural `apiRoots`, `routeRoots`,
41
41
  * `packageManager`, `projectRoot`, and `confidence` in addition to the
@@ -404,7 +404,7 @@ function buildApiRoots(framework, apiRoot) {
404
404
  // detectTopology — spec-compliant alias
405
405
  // ----------------------------------------------------------------
406
406
  /**
407
- * Detect project topology for the selector pipeline (Phase 0).
407
+ * Detect project topology for the selector pipeline.
408
408
  *
409
409
  * Returns an enriched TopoResult with plural `apiRoots`, `routeRoots`,
410
410
  * `packageManager`, `projectRoot`, and `confidence` in addition to the
@@ -2,6 +2,8 @@
2
2
  // @duct/sdk — Config File Generator
3
3
  // Generates duct.config.ts from a DuctConfig object
4
4
  // ============================================================
5
+ import { getDocsUrl } from "../../core/endpoints.js";
6
+ import { normalizeAuthSchema } from "./normalize.js";
5
7
  // ----------------------------------------------------------------
6
8
  // Helpers
7
9
  // ----------------------------------------------------------------
@@ -50,6 +52,19 @@ function formatStringArray(arr, indentSpaces) {
50
52
  // ----------------------------------------------------------------
51
53
  // Section generators
52
54
  // ----------------------------------------------------------------
55
+ function formatDiscoveryComment(evidence, confidence, indentSpaces) {
56
+ const parts = [];
57
+ if (typeof confidence === "number") {
58
+ parts.push(`confidence ${Math.round(confidence * 100)}%`);
59
+ }
60
+ if (evidence && evidence.length > 0) {
61
+ parts.push(`detected from ${evidence.join(", ")}`);
62
+ }
63
+ if (parts.length === 0)
64
+ return "";
65
+ const pad = " ".repeat(indentSpaces);
66
+ return `\n${pad} // ${parts.join(" · ")}`;
67
+ }
53
68
  function generateRoutes(routes, indentSpaces) {
54
69
  if (routes.length === 0) {
55
70
  return "routes: [],";
@@ -69,7 +84,7 @@ function generateRoutes(routes, indentSpaces) {
69
84
  return `${pad} {
70
85
  ${pad} path: ${JSON.stringify(route.path)},
71
86
  ${pad} name: ${JSON.stringify(route.name)},
72
- ${pad} description: ${JSON.stringify(route.description)},${params}${queryParams}
87
+ ${pad} description: ${JSON.stringify(route.description)},${formatDiscoveryComment(route.evidence, route.confidence, indentSpaces + 2)}${params}${queryParams}
73
88
  ${pad} uiStateHint: ${JSON.stringify(route.uiStateHint)},
74
89
  ${pad} requiresAuth: ${route.requiresAuth},
75
90
  ${pad} deeplinkable: ${route.deeplinkable},
@@ -88,10 +103,18 @@ function generateActions(actions, indentSpaces) {
88
103
  .map((p) => `${pad} { name: ${JSON.stringify(p.name)}, type: ${JSON.stringify(p.type)}, required: ${p.required}${p.description ? `, description: ${JSON.stringify(p.description)}` : ""} }`)
89
104
  .join(",\n")}\n${pad} ],`
90
105
  : `\n${pad} params: [],`;
106
+ const schemaLines = [
107
+ action.inputSchema
108
+ ? `\n${pad} inputSchema: ${jsonValue(action.inputSchema, indentSpaces + 4)},`
109
+ : "",
110
+ action.responseSchema
111
+ ? `\n${pad} responseSchema: ${jsonValue(action.responseSchema, indentSpaces + 4)},`
112
+ : "",
113
+ ].join("");
91
114
  return `${pad} {
92
115
  ${pad} id: ${JSON.stringify(action.id)},
93
116
  ${pad} name: ${JSON.stringify(action.name)},
94
- ${pad} description: ${JSON.stringify(action.description)},
117
+ ${pad} description: ${JSON.stringify(action.description)},${formatDiscoveryComment(action.evidence, action.confidence, indentSpaces + 2)}
95
118
  ${pad} method: ${JSON.stringify(action.method)},
96
119
  ${pad} path: ${JSON.stringify(action.path)},
97
120
  ${pad} // Set agentAccessible: true to expose this action to AI agents via the Duct Agent API.
@@ -103,7 +126,7 @@ ${pad} // sensitivityLevel controls the minimum auth required for agent acces
103
126
  ${pad} // "low" — any authenticated shell
104
127
  ${pad} // "medium" — requires user consent token
105
128
  ${pad} // "high" — requires user consent token; also respects allowedCallers restriction if set
106
- ${pad} sensitivityLevel: ${JSON.stringify(action.sensitivityLevel)},${params}
129
+ ${pad} sensitivityLevel: ${JSON.stringify(action.sensitivityLevel)},${params}${schemaLines}
107
130
  ${pad} requiresAuth: ${action.requiresAuth},${action.rateLimit !== undefined ? `\n${pad} rateLimit: ${action.rateLimit},` : ""}
108
131
  ${pad} }`;
109
132
  });
@@ -123,6 +146,12 @@ function generateAuth(auth, indentSpaces) {
123
146
  if (auth.customClaims && Object.keys(auth.customClaims).length > 0) {
124
147
  lines.push(`${pad} customClaims: ${jsonValue(auth.customClaims, indentSpaces + 2)},`);
125
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
+ }
126
155
  return `auth: {\n${lines.join("\n")}\n${pad}},`;
127
156
  }
128
157
  function generateDeeplinks(deeplinks, indentSpaces) {
@@ -171,6 +200,8 @@ function generateWidget(widget, indentSpaces) {
171
200
  lines.push(`${pad} primaryColor: ${JSON.stringify(widget.primaryColor)},`);
172
201
  if (widget.position)
173
202
  lines.push(`${pad} position: ${JSON.stringify(widget.position)},`);
203
+ if (widget.logoUrl)
204
+ lines.push(`${pad} logoUrl: ${JSON.stringify(widget.logoUrl)},`);
174
205
  if (widget.defaultOpen !== undefined)
175
206
  lines.push(`${pad} defaultOpen: ${widget.defaultOpen},`);
176
207
  if (widget.launcherText)
@@ -191,14 +222,15 @@ function generateWidget(widget, indentSpaces) {
191
222
  */
192
223
  export function generateManualTemplate(opts) {
193
224
  const { shellId, productName, baseUrl, authStrategy, framework, logoUrl } = opts;
194
- const tokenEndpoint = framework === "next-app" || framework === "next-pages"
195
- ? "/api/duct/token"
196
- : framework === "remix"
197
- ? "/api.duct.token"
198
- : framework === "sveltekit"
199
- ? "/api/duct/token"
200
- : "/api/duct/token";
201
- const logoLine = logoUrl ? `\n // logoUrl: ${JSON.stringify(logoUrl)},` : "";
225
+ const tokenEndpointPath = framework === "remix" ? "/api/duct/token" : "/api/duct/token";
226
+ const tokenEndpoint = normalizeAuthSchema({
227
+ strategy: authStrategy,
228
+ sessionFields: ["userId", "email"],
229
+ guestAllowed: false,
230
+ tokenExpirySeconds: 300,
231
+ tokenEndpoint: tokenEndpointPath,
232
+ }, baseUrl).tokenEndpoint;
233
+ const docsUrl = getDocsUrl();
202
234
  return `/**
203
235
  * Duct Shell Configuration — ${shellId}
204
236
  *
@@ -209,7 +241,7 @@ export function generateManualTemplate(opts) {
209
241
  *
210
242
  * to sync this manifest with Duct cloud.
211
243
  *
212
- * Docs: see your Duct deployment /docs (local default: http://localhost:3005/docs)
244
+ * Docs: ${docsUrl}/config
213
245
  */
214
246
 
215
247
  import { defineDuctConfig } from "@duct-sdk/sdk";
@@ -222,7 +254,7 @@ export default defineDuctConfig({
222
254
  product: {
223
255
  name: ${JSON.stringify(productName)},
224
256
  description: ${JSON.stringify(`${productName} — AI-powered interaction shell`)},
225
- baseUrl: ${JSON.stringify(baseUrl)},${logoLine}
257
+ baseUrl: ${JSON.stringify(baseUrl)},
226
258
  // apiBaseUrl: optional separate origin for action HTTP proxy (defaults to baseUrl)
227
259
  },
228
260
 
@@ -234,9 +266,9 @@ export default defineDuctConfig({
234
266
  sessionFields: ["userId", "email"],
235
267
  guestAllowed: false,
236
268
  // How long (seconds) a Duct-issued execution token is valid
237
- tokenExpirySeconds: 300,
238
- // Route on your server that mints Duct execution tokens
239
- tokenEndpoint: ${JSON.stringify(tokenEndpoint)},
269
+ tokenExpirySeconds: 300,${tokenEndpoint ? `
270
+ // Full URL where Duct requests delegated tokens for authenticated users
271
+ tokenEndpoint: ${JSON.stringify(tokenEndpoint)},` : ""}
240
272
  },
241
273
 
242
274
  // ── Routes ───────────────────────────────────────────────────
@@ -327,7 +359,8 @@ export default defineDuctConfig({
327
359
 
328
360
  // Shell widget appearance
329
361
  widget: {
330
- position: "bottom-right",
362
+ position: "bottom-right",${logoUrl ? `
363
+ logoUrl: ${JSON.stringify(logoUrl)},` : ""}
331
364
  },
332
365
  });
333
366
  `;
@@ -341,64 +374,64 @@ export default defineDuctConfig({
341
374
  * @returns A formatted TypeScript source string
342
375
  */
343
376
  export function generateConfigFile(config) {
377
+ const normalized = {
378
+ ...config,
379
+ auth: normalizeAuthSchema(config.auth, config.product.baseUrl),
380
+ };
344
381
  const i = " "; // 2-space indent
345
382
  const sections = [
346
383
  `${i}// Your Duct shell ID (assigned by Duct cloud)`,
347
- `${i}shellId: ${JSON.stringify(config.shellId)},`,
384
+ `${i}shellId: ${JSON.stringify(normalized.shellId)},`,
348
385
  "",
349
386
  `${i}// Product metadata — helps Duct understand your app`,
350
387
  `${i}product: {`,
351
- `${i} name: ${JSON.stringify(config.product.name)},`,
352
- `${i} description: ${JSON.stringify(config.product.description)},`,
353
- `${i} baseUrl: ${JSON.stringify(config.product.baseUrl)},`,
354
- ...(config.product.locale
355
- ? [`${i} locale: ${JSON.stringify(config.product.locale)},`]
388
+ `${i} name: ${JSON.stringify(normalized.product.name)},`,
389
+ `${i} description: ${JSON.stringify(normalized.product.description)},`,
390
+ `${i} baseUrl: ${JSON.stringify(normalized.product.baseUrl)},`,
391
+ ...(normalized.product.apiBaseUrl
392
+ ? [`${i} apiBaseUrl: ${JSON.stringify(normalized.product.apiBaseUrl)},`]
356
393
  : []),
357
- ...(config.product.industry
358
- ? [`${i} industry: ${JSON.stringify(config.product.industry)},`]
394
+ ...(normalized.product.locale
395
+ ? [`${i} locale: ${JSON.stringify(normalized.product.locale)},`]
396
+ : []),
397
+ ...(normalized.product.industry
398
+ ? [`${i} industry: ${JSON.stringify(normalized.product.industry)},`]
359
399
  : []),
360
400
  `${i}},`,
361
401
  "",
362
402
  `${i}// Authentication configuration`,
363
403
  `${i}// Duct uses this to request tokens and understand your session shape`,
364
- `${i}${generateAuth(config.auth, 2)}`,
404
+ `${i}${generateAuth(normalized.auth, 2)}`,
365
405
  "",
366
406
  `${i}// All navigable routes in your application`,
367
407
  `${i}// Duct uses these to understand where to send users via deeplinks`,
368
- `${i}${generateRoutes(config.routes, 2)}`,
408
+ `${i}${generateRoutes(normalized.routes, 2)}`,
369
409
  "",
370
410
  `${i}// API actions Duct can optionally expose to AI agents`,
371
411
  `${i}// Set agentAccessible: true for actions you want agents to invoke`,
372
- `${i}${generateActions(config.actions, 2)}`,
412
+ `${i}${generateActions(normalized.actions, 2)}`,
373
413
  "",
374
414
  `${i}// Deeplinks are signed URLs Duct issues to navigate your frontend to a specific state.`,
375
415
  `${i}// The shell generates the URL. Your receiver (duct/receiver.ts) validates and applies the state.`,
376
416
  `${i}// Expiry is enforced server-side. Replay attacks are blocked by token ID.`,
377
- `${i}${generateDeeplinks(config.deeplinks, 2)}`,
417
+ `${i}${generateDeeplinks(normalized.deeplinks, 2)}`,
378
418
  "",
379
419
  `${i}// Agent permission configuration`,
380
420
  `${i}// Controls what AI agents/shells can do in your shell`,
381
- `${i}${generateAgentPermissions(config.agentPermissions, 2)}`,
421
+ `${i}${generateAgentPermissions(normalized.agentPermissions, 2)}`,
382
422
  ];
383
423
  // Intershell network settings — only emit when explicitly set (non-default)
384
- const visibility = config.registry_visibility ?? 'private';
385
- const intershellEnabled = config.intershell_enabled ?? false;
386
- if (visibility !== 'private' || intershellEnabled !== false) {
424
+ const visibility = normalized.registry_visibility ?? "private";
425
+ const intershellEnabled = normalized.intershell_enabled ?? false;
426
+ if (visibility !== "private" || intershellEnabled !== false) {
387
427
  sections.push("", `${i}// Intershell network settings`, `${i}// intershell_enabled: master switch — allows other Duct shells to invoke this shell cross-shell.`, `${i}// registry_visibility: 'public' makes this shell discoverable in the Duct capability network.`, `${i}// Set both to true/public to join the open network; leave as defaults (false/'private') to stay isolated.`, `${i}intershell_enabled: ${intershellEnabled},`, `${i}registry_visibility: ${JSON.stringify(visibility)},`);
388
428
  }
389
- if (config.widget) {
390
- sections.push("", `${i}// Shell widget display configuration`, `${i}${generateWidget(config.widget, 2)}`);
391
- }
392
- let docsBase = 'http://localhost:3005/docs';
393
- if (config.product?.baseUrl) {
394
- try {
395
- const hostname = new URL(config.product.baseUrl).hostname;
396
- docsBase = `https://docs.${hostname.split('.').slice(-2).join('.')}`;
397
- }
398
- catch { /* invalid URL — use default */ }
429
+ if (normalized.widget) {
430
+ sections.push("", `${i}// Shell widget display configuration`, `${i}${generateWidget(normalized.widget, 2)}`);
399
431
  }
432
+ const docsBase = getDocsUrl();
400
433
  return `/**
401
- * Duct Shell Configuration — ${config.shellId}
434
+ * Duct Shell Configuration — ${normalized.shellId}
402
435
  *
403
436
  * This file is the manifest Duct uses to understand your product.
404
437
  * It defines what routes exist, what actions agents can invoke,
@@ -0,0 +1 @@
1
+ export {};