@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
@@ -0,0 +1,99 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk — useDuctPageContext hook
3
+ //
4
+ // Install this hook in page-level components to respond to the
5
+ // shell's DUCT_REQUEST_CONTEXT postMessage. When the shell detects
6
+ // a deictic reference ("this order", "the error on screen"), it asks
7
+ // the parent page for structured data about what the user is viewing.
8
+ //
9
+ // The hook validates the origin of the request so only the Duct
10
+ // shell iframe can trigger the resolver — not arbitrary third-party frames.
11
+ //
12
+ // Usage:
13
+ // import { useDuctPageContext } from "@duct-sdk/sdk/react";
14
+ //
15
+ // // In a page-level component — use your own key names, not hardcoded ones:
16
+ // useDuctPageContext(() => ({
17
+ // route: window.location.pathname,
18
+ // entity: { type: "your-entity-type", ...item }, // spread your record as-is
19
+ // }), { shellHost: process.env.NEXT_PUBLIC_DUCT_SHELL_HOST });
20
+ // ============================================================
21
+ "use client";
22
+ import { useEffect, useRef } from "react";
23
+ /**
24
+ * useDuctPageContext — company-side hook for the Page Context Protocol.
25
+ *
26
+ * Listens for DUCT_REQUEST_CONTEXT postMessages from the Duct shell iframe.
27
+ * When one arrives, calls your resolver and sends the result back as DUCT_PAGE_CONTEXT.
28
+ *
29
+ * The resolver may be async (e.g. pulling live data from a store or API).
30
+ * If it throws, the hook responds with `context: null` so the shell doesn't hang.
31
+ *
32
+ * The hook uses a ref for the resolver so it always calls the latest closure
33
+ * without needing to remove/re-add the event listener on every render.
34
+ *
35
+ * SECURITY: Never include passwords, tokens, card numbers, or other sensitive fields
36
+ * in `formState`. The shell forwards this data to Duct's routing service. Only include
37
+ * fields that describe visible, non-sensitive form state (e.g. a selected option, a search
38
+ * term, a draft title). Duct strips known sensitive field names server-side, but
39
+ * defense-in-depth starts here.
40
+ *
41
+ * @param resolver — function that returns the current page context
42
+ * @param options — configuration including optional shellHost for origin validation
43
+ */
44
+ export function useDuctPageContext(resolver, options = {}) {
45
+ const resolverRef = useRef(resolver);
46
+ resolverRef.current = resolver;
47
+ const shellHostRef = useRef(options.shellHost);
48
+ shellHostRef.current = options.shellHost;
49
+ // Warn once in non-production when shellHost is omitted — any cross-origin frame
50
+ // could then request the company's page context.
51
+ useEffect(() => {
52
+ if (!options.shellHost && process.env.NODE_ENV !== "production") {
53
+ console.error("[duct] useDuctPageContext: shellHost is not configured. " +
54
+ "Any cross-origin iframe can request your page context. " +
55
+ "Pass shellHost (e.g. process.env.NEXT_PUBLIC_DUCT_SHELL_HOST) to restrict " +
56
+ "requests to the Duct shell only.");
57
+ }
58
+ // eslint-disable-next-line react-hooks/exhaustive-deps
59
+ }, []); // warn once on mount
60
+ useEffect(() => {
61
+ function handleMessage(event) {
62
+ // Origin guard: only allow the configured shell host
63
+ const shellHost = shellHostRef.current;
64
+ if (shellHost) {
65
+ let expectedOrigin;
66
+ try {
67
+ expectedOrigin = new URL(shellHost).origin;
68
+ }
69
+ catch {
70
+ return; // invalid shellHost — fail closed
71
+ }
72
+ if (event.origin !== expectedOrigin)
73
+ return;
74
+ }
75
+ if (typeof event.data !== "object" ||
76
+ event.data === null ||
77
+ event.data.type !== "DUCT_REQUEST_CONTEXT") {
78
+ return;
79
+ }
80
+ const requestId = event.data.requestId;
81
+ if (typeof requestId !== "string" || !requestId)
82
+ return;
83
+ const source = event.source;
84
+ if (!source || typeof source.postMessage !== "function")
85
+ return;
86
+ // Respond asynchronously; use event.origin as targetOrigin so the response
87
+ // only reaches the exact frame that sent the request.
88
+ Promise.resolve(resolverRef.current())
89
+ .then((context) => {
90
+ source.postMessage({ type: "DUCT_PAGE_CONTEXT", requestId, context }, event.origin);
91
+ })
92
+ .catch(() => {
93
+ source.postMessage({ type: "DUCT_PAGE_CONTEXT", requestId, context: null }, event.origin);
94
+ });
95
+ }
96
+ window.addEventListener("message", handleMessage);
97
+ return () => window.removeEventListener("message", handleMessage);
98
+ }, []); // stable — resolver accessed via ref
99
+ }
@@ -8,7 +8,13 @@ export interface ApiScannerStrategy {
8
8
  /**
9
9
  * Run the API Agent to produce ActionManifest[] from the project's API layer.
10
10
  *
11
- * First checks for openapi.json/openapi.yaml (preferred).
12
- * Falls back to scanning API route handlers.
11
+ * Priority:
12
+ * 1. inlineSpecContent — spec passed directly from --api-spec flag (skips all discovery)
13
+ * 2. openapi.json / openapi.yaml at known paths
14
+ * 3. Filesystem scan of API route handlers
15
+ *
16
+ * @param hintFiles - Optional pre-selected file paths from the file selector.
17
+ * @param inlineSpecContent - Raw spec content passed via --api-spec (bypasses sandbox lookup).
18
+ * @param inlineSpecPath - Display path for the inline spec (used in prompt context).
13
19
  */
14
- export declare function runApiAgent(sandboxFs: SandboxFS): Promise<ActionManifest[]>;
20
+ export declare function runApiAgent(sandboxFs: SandboxFS, hintFiles?: string[], inlineSpecContent?: string, inlineSpecPath?: string): Promise<ActionManifest[]>;
@@ -3,6 +3,8 @@
3
3
  // Analyzes API routes/OpenAPI spec to produce ActionManifest[]
4
4
  // ============================================================
5
5
  import { callDuctLLM } from "./llm.js";
6
+ import { extractZodHintsFromFiles } from "../processors/zod-extractor.js";
7
+ import { parsePrismaSchema } from "../processors/prisma-parser.js";
6
8
  const MAX_LISTED_FILES = 60;
7
9
  const MAX_SNIPPET_FILES = 20;
8
10
  const SNIPPET_SIZE = 1800;
@@ -187,53 +189,61 @@ const API_SCANNER_STRATEGIES = [
187
189
  // ----------------------------------------------------------------
188
190
  // Output schema description
189
191
  // ----------------------------------------------------------------
190
- const ACTION_MANIFEST_SCHEMA = `
191
- Array of ActionManifest objects:
192
- [
193
- {
194
- "id": "get_orders", // snake_case unique ID
195
- "name": "Get Orders", // Human-readable name
196
- "description": "...", // What this action does
197
- "method": "GET", // HTTP method: GET|POST|PUT|PATCH|DELETE
198
- "path": "/api/orders", // API path
199
- "agentAccessible": false, // ALWAYS false by default — developer enables this
200
- "sideEffects": false, // true for POST/PUT/PATCH/DELETE
201
- "sensitivityLevel": "low", // "none"|"low"|"medium"|"high"|"critical"
202
- "params": [
203
- {
204
- "name": "page",
205
- "type": "number", // "string"|"number"|"boolean"|"object"|"array"
206
- "required": false,
207
- "description": "Page number"
208
- }
209
- ],
210
- "requiresAuth": true,
211
- "rateLimit": 60 // optional, requests per minute
212
- }
213
- ]
192
+ const ACTION_MANIFEST_SCHEMA = `
193
+ Array of ActionManifest objects:
194
+ [
195
+ {
196
+ "id": "get_orders", // snake_case unique ID
197
+ "name": "Get Orders", // Human-readable name
198
+ "description": "...", // What this action does
199
+ "method": "GET", // HTTP method: GET|POST|PUT|PATCH|DELETE
200
+ "path": "/api/orders", // API path
201
+ "agentAccessible": false, // ALWAYS false by default — developer enables this
202
+ "sideEffects": false, // true for POST/PUT/PATCH/DELETE
203
+ "sensitivityLevel": "low", // "none"|"low"|"medium"|"high"|"critical"
204
+ "params": [
205
+ {
206
+ "name": "page",
207
+ "type": "number", // "string"|"number"|"boolean"|"object"|"array"
208
+ "required": false,
209
+ "description": "Page number"
210
+ }
211
+ ],
212
+ "requiresAuth": true,
213
+ "rateLimit": 60, // optional, requests per minute
214
+ "confidence": 0.95, // Detection confidence 0.0–1.0
215
+ "evidence": "app/api/orders/route.ts:12" // File:line where this endpoint was found
216
+ }
217
+ ]
218
+
219
+ Confidence scoring rules:
220
+ - 1.0: explicit handler function with HTTP method decorator or export const GET/POST
221
+ - 0.85–0.99: clear route file, method obvious from file/export name
222
+ - 0.6–0.84: method inferred from surrounding code, path partially matched
223
+ - below 0.6: endpoint guessed from URL pattern or import, no direct handler found
214
224
  `.trim();
215
225
  // ----------------------------------------------------------------
216
226
  // Prompt builders
217
227
  // ----------------------------------------------------------------
218
228
  async function buildOpenAPIPrompt(openApiContent, filePath) {
219
- return `Analyze this OpenAPI specification and produce an ActionManifest array for all API endpoints.
220
-
221
- ## ${filePath}:
222
- \`\`\`json
223
- ${openApiContent.slice(0, 8000)}
224
- \`\`\`
225
-
226
- For each endpoint:
227
- - Use snake_case for the ID (e.g., GET /api/orders → "get_orders")
228
- - Set agentAccessible: false (the developer will enable this manually for safe endpoints)
229
- - Set sideEffects: true for POST, PUT, PATCH, DELETE
230
- - Infer sensitivityLevel from the path/description (e.g., /payment → "high", /profile → "medium", /public → "none")
231
- - Include all path/query/body parameters
232
-
233
- STRICTNESS RULES:
234
- - Do not invent operations that are not explicitly present in the OpenAPI spec.
235
- - Keep method + path exactly as declared in the spec.
236
- - Do not rename domain concepts (e.g., companies → products).
229
+ return `Analyze this OpenAPI specification and produce an ActionManifest array for all API endpoints.
230
+
231
+ ## ${filePath}:
232
+ \`\`\`json
233
+ ${openApiContent.slice(0, 8000)}
234
+ \`\`\`
235
+
236
+ For each endpoint:
237
+ - Use snake_case for the ID (e.g., GET /api/orders → "get_orders")
238
+ - Set agentAccessible: false (the developer will enable this manually for safe endpoints)
239
+ - Set sideEffects: true for POST, PUT, PATCH, DELETE
240
+ - Infer sensitivityLevel from the path/description (e.g., /payment → "high", /profile → "medium", /public → "none")
241
+ - Include all path/query/body parameters
242
+
243
+ STRICTNESS RULES:
244
+ - Do not invent operations that are not explicitly present in the OpenAPI spec.
245
+ - Keep method + path exactly as declared in the spec.
246
+ - Do not rename domain concepts (e.g., companies → products).
237
247
  - If an operation is ambiguous or missing from the spec, omit it instead of guessing.`;
238
248
  }
239
249
  function rankApiFile(file) {
@@ -266,6 +276,32 @@ function prioritizeApiFiles(files) {
266
276
  return a.localeCompare(b);
267
277
  });
268
278
  }
279
+ // Handler boundary patterns — lines that start a route handler definition
280
+ const HANDLER_START_RE = /^(?:export\s+(?:async\s+)?function|export\s+const\s+\w+\s*=\s*(?:async\s*)?\(|(?:router|app)\.\w+\s*\(|@(?:app|router)\.(?:get|post|put|patch|delete|route)\s*\()/;
281
+ /**
282
+ * Extract handler-level snippets from a source file.
283
+ * Finds export function / router.method() / FastAPI decorator boundaries
284
+ * and returns up to `maxHandlers` handlers, each capped at `charsPerHandler`.
285
+ * Falls back to simple prefix truncation when no boundaries are found.
286
+ */
287
+ function extractHandlerSnippets(content, maxHandlers, charsPerHandler) {
288
+ const lines = content.split("\n");
289
+ const handlerStarts = [];
290
+ for (let i = 0; i < lines.length; i++) {
291
+ if (HANDLER_START_RE.test(lines[i].trimStart())) {
292
+ handlerStarts.push(i);
293
+ }
294
+ }
295
+ if (handlerStarts.length === 0) {
296
+ return content.slice(0, charsPerHandler * 3);
297
+ }
298
+ const snippets = [];
299
+ for (const start of handlerStarts.slice(0, maxHandlers)) {
300
+ const block = lines.slice(start).join("\n");
301
+ snippets.push(block.slice(0, charsPerHandler));
302
+ }
303
+ return snippets.join("\n\n// ───\n\n");
304
+ }
269
305
  async function appendFileSnippets(lines, sandboxFs, files, maxFiles, snippetSize) {
270
306
  for (const apiFile of files.slice(0, maxFiles)) {
271
307
  const content = await sandboxFs.readFile(apiFile);
@@ -273,7 +309,7 @@ async function appendFileSnippets(lines, sandboxFs, files, maxFiles, snippetSize
273
309
  continue;
274
310
  lines.push(`\n### ${apiFile}:`);
275
311
  lines.push("```ts");
276
- lines.push(content.slice(0, snippetSize));
312
+ lines.push(extractHandlerSnippets(content, 15, snippetSize));
277
313
  lines.push("```");
278
314
  }
279
315
  }
@@ -315,11 +351,46 @@ async function detectApiRoots(sandboxFs) {
315
351
  // Deduplicate while preserving order
316
352
  return [...new Set(roots)];
317
353
  }
318
- async function buildFileSystemPrompt(sandboxFs) {
354
+ async function buildFileSystemPrompt(sandboxFs, hintFiles) {
319
355
  const lines = [];
320
356
  lines.push("Analyze these API route files and produce an ActionManifest array.\n");
321
357
  lines.push("Only include endpoints that are explicitly backed by code evidence in the snippets below.");
322
358
  lines.push("If evidence is missing or ambiguous, omit the action instead of guessing.\n");
359
+ // Phase 0.5: inject Prisma model field names so the agent can map CRUD params accurately.
360
+ const prismaSchema = await sandboxFs.readFile("prisma/schema.prisma");
361
+ if (prismaSchema) {
362
+ const { annotation } = parsePrismaSchema(prismaSchema);
363
+ if (annotation) {
364
+ lines.push("## Prisma schema — use these field names for CRUD action params and inputSchema:");
365
+ lines.push(annotation);
366
+ lines.push("");
367
+ }
368
+ }
369
+ // Pre-extract Zod schemas from hint files so agents get structured param info.
370
+ // This eliminates guessing field types from raw source snippets.
371
+ if (hintFiles && hintFiles.length > 0) {
372
+ const zodHints = await extractZodHintsFromFiles((p) => sandboxFs.readFile(p), hintFiles);
373
+ if (zodHints.size > 0) {
374
+ lines.push("## Pre-extracted Zod schema hints (use these for accurate inputSchema):");
375
+ for (const hint of zodHints.values()) {
376
+ lines.push(hint.annotation);
377
+ }
378
+ lines.push("");
379
+ }
380
+ }
381
+ // If the selector pre-identified targeted API files, include them first.
382
+ if (hintFiles && hintFiles.length > 0) {
383
+ lines.push("## Targeted API files:");
384
+ for (const f of hintFiles.slice(0, 30)) {
385
+ const content = await sandboxFs.readFile(f);
386
+ if (!content)
387
+ continue;
388
+ lines.push(`\n### ${f}:`);
389
+ lines.push("```ts");
390
+ lines.push(extractHandlerSnippets(content, 15, SNIPPET_SIZE));
391
+ lines.push("```");
392
+ }
393
+ }
323
394
  const apiRoots = await detectApiRoots(sandboxFs);
324
395
  if (apiRoots.some((r) => r !== "")) {
325
396
  lines.push(`Detected monorepo structure — scanning API roots: ${apiRoots.filter((r) => r !== "").join(", ")} plus project root.\n`);
@@ -448,26 +519,26 @@ async function buildFileSystemPrompt(sandboxFs) {
448
519
  await strategy.appendPromptContext(sandboxFs, lines);
449
520
  }
450
521
  }
451
- lines.push(`\n\nFor each API endpoint:
452
- - Derive the ID from the method + path in snake_case (e.g., GET /api/orders → "get_orders")
453
- - Derive the path from explicit handler evidence (including base path mounts in server entrypoints)
454
- - **agentAccessible**: Set to true ONLY for: safe GET methods, sensitivityLevel not "high"/"critical", and no side effects. Everything else defaults to false. Add a "// TODO: review agentAccessible" comment in the output's description for every action where you were uncertain.
455
- - Infer parameters from function signatures, TypeScript types, Zod/Yup schemas, and validation calls
456
- - **inputSchema**: Extract from Zod z.object({...}), Yup yup.object({...}), or TypeScript Request body type. If Prisma model is detected, infer from model fields. Fallback: omit inputSchema.
457
- - **sideEffects**: true for POST/PUT/PATCH/DELETE methods
458
- - **sensitivityLevel**: "high" for paths with password|secret|ssn|credit|billing; "medium" for email|phone|address|profile; "none"/"low" for public/read-only data
459
- - **requiresAuth**: true if handler calls auth(), session(), getServerSession(), or requires a token
460
-
461
- STRICTNESS RULES:
462
- - Include an action only when you can point to an explicit HTTP method + path pattern in the shown code.
463
- - Do not invent endpoints based on UI routes, naming assumptions, or business context.
464
- - Do not rename domains (e.g., companies to products) unless the source code explicitly does so.
465
- - Preserve method and path exactly as implemented (including :param style where used).
466
- - Skip: _next/*, /api/auth/* (NextAuth internal), /api/duct/* (Duct's own routes).
467
- - Strip Next.js route groups from paths: (app)/api/foo → /api/foo; (admin)/api/bar → /api/bar.
468
- - Apply rewrites from next.config.js: use the public-facing destination path, not the source.
469
- - If uncertain, omit the action.
470
-
522
+ lines.push(`\n\nFor each API endpoint:
523
+ - Derive the ID from the method + path in snake_case (e.g., GET /api/orders → "get_orders")
524
+ - Derive the path from explicit handler evidence (including base path mounts in server entrypoints)
525
+ - **agentAccessible**: Set to true ONLY for: safe GET methods, sensitivityLevel not "high"/"critical", and no side effects. Everything else defaults to false. Add a "// TODO: review agentAccessible" comment in the output's description for every action where you were uncertain.
526
+ - Infer parameters from function signatures, TypeScript types, Zod/Yup schemas, and validation calls
527
+ - **inputSchema**: Extract from Zod z.object({...}), Yup yup.object({...}), or TypeScript Request body type. If Prisma model is detected, infer from model fields. Fallback: omit inputSchema.
528
+ - **sideEffects**: true for POST/PUT/PATCH/DELETE methods
529
+ - **sensitivityLevel**: "high" for paths with password|secret|ssn|credit|billing; "medium" for email|phone|address|profile; "none"/"low" for public/read-only data
530
+ - **requiresAuth**: true if handler calls auth(), session(), getServerSession(), or requires a token
531
+
532
+ STRICTNESS RULES:
533
+ - Include an action only when you can point to an explicit HTTP method + path pattern in the shown code.
534
+ - Do not invent endpoints based on UI routes, naming assumptions, or business context.
535
+ - Do not rename domains (e.g., companies to products) unless the source code explicitly does so.
536
+ - Preserve method and path exactly as implemented (including :param style where used).
537
+ - Skip: _next/*, /api/auth/* (NextAuth internal), /api/duct/* (Duct's own routes).
538
+ - Strip Next.js route groups from paths: (app)/api/foo → /api/foo; (admin)/api/bar → /api/bar.
539
+ - Apply rewrites from next.config.js: use the public-facing destination path, not the source.
540
+ - If uncertain, omit the action.
541
+
471
542
  DO NOT include Next.js internal routes or static assets.`);
472
543
  return lines.join("\n");
473
544
  }
@@ -477,10 +548,31 @@ DO NOT include Next.js internal routes or static assets.`);
477
548
  /**
478
549
  * Run the API Agent to produce ActionManifest[] from the project's API layer.
479
550
  *
480
- * First checks for openapi.json/openapi.yaml (preferred).
481
- * Falls back to scanning API route handlers.
551
+ * Priority:
552
+ * 1. inlineSpecContent — spec passed directly from --api-spec flag (skips all discovery)
553
+ * 2. openapi.json / openapi.yaml at known paths
554
+ * 3. Filesystem scan of API route handlers
555
+ *
556
+ * @param hintFiles - Optional pre-selected file paths from the file selector.
557
+ * @param inlineSpecContent - Raw spec content passed via --api-spec (bypasses sandbox lookup).
558
+ * @param inlineSpecPath - Display path for the inline spec (used in prompt context).
482
559
  */
483
- export async function runApiAgent(sandboxFs) {
560
+ export async function runApiAgent(sandboxFs, hintFiles, inlineSpecContent, inlineSpecPath) {
561
+ // If spec was passed directly (--api-spec flag), use it without further discovery
562
+ if (inlineSpecContent) {
563
+ const prompt = await buildOpenAPIPrompt(inlineSpecContent, inlineSpecPath ?? "openapi.json");
564
+ const result = await callDuctLLM({
565
+ agentName: "ApiAgent",
566
+ systemPrompt: "You are an expert at analyzing OpenAPI specifications and API route handlers. " +
567
+ "You produce structured action manifests that describe every API operation.",
568
+ userPrompt: prompt,
569
+ outputSchema: ACTION_MANIFEST_SCHEMA,
570
+ maxTokens: 4096,
571
+ });
572
+ if (Array.isArray(result.parsed)) {
573
+ return sanitizeActions(result.parsed);
574
+ }
575
+ }
484
576
  // Check for OpenAPI spec first
485
577
  const openApiCandidates = [
486
578
  "openapi.json",
@@ -511,7 +603,7 @@ export async function runApiAgent(sandboxFs) {
511
603
  }
512
604
  }
513
605
  // Fall back to filesystem scanning
514
- const prompt = await buildFileSystemPrompt(sandboxFs);
606
+ const prompt = await buildFileSystemPrompt(sandboxFs, hintFiles);
515
607
  const result = await callDuctLLM({
516
608
  agentName: "ApiAgent",
517
609
  systemPrompt: "You are an expert at analyzing Next.js, Express, and tRPC API codebases. " +
@@ -565,8 +657,10 @@ function sanitizeActions(actions) {
565
657
  inputSchema: a.inputSchema,
566
658
  requiresAuth: a.requiresAuth ?? true,
567
659
  rateLimit: a.rateLimit,
568
- // Carry search hint forward if LLM provided one
569
660
  searchHint: a.searchHint,
661
+ // Preserve confidence and evidence from LLM output
662
+ ...(typeof a.confidence === "number" ? { confidence: Math.min(1, Math.max(0, a.confidence)) } : {}),
663
+ ...(typeof a.evidence === "string" && a.evidence ? { evidence: a.evidence } : {}),
570
664
  };
571
665
  })
572
666
  .filter((a) => isLikelyApiPath(a.path))
@@ -2,5 +2,6 @@ import type { SandboxFS } from "../fs/sandbox.js";
2
2
  import type { AuthSchema } from "../../core/types.js";
3
3
  /**
4
4
  * Run the Auth Agent to produce an AuthSchema from the project's auth configuration.
5
+ * @param hintFiles - Optional pre-selected auth file paths from the file selector.
5
6
  */
6
- export declare function runAuthAgent(sandboxFs: SandboxFS): Promise<AuthSchema>;
7
+ export declare function runAuthAgent(sandboxFs: SandboxFS, hintFiles?: string[]): Promise<AuthSchema>;
@@ -6,22 +6,22 @@ import { callDuctLLM } from "./llm.js";
6
6
  // ----------------------------------------------------------------
7
7
  // Output schema description
8
8
  // ----------------------------------------------------------------
9
- const AUTH_SCHEMA_SCHEMA = `
10
- Single AuthSchema object:
11
- {
12
- "strategy": "nextauth", // "nextauth"|"clerk"|"auth0"|"custom-jwt"|"session-cookie"|"none"|"unknown"
13
- "sessionFields": [ // Fields available in the session/token
14
- "id",
15
- "email",
16
- "name",
17
- "orgId",
18
- "role"
19
- ],
20
- "guestAllowed": false, // Whether unauthenticated users can use the shell
21
- "tokenExpirySeconds": 300, // How long Duct delegated tokens should live
22
- "tokenEndpoint": "/api/duct/token", // Optional: endpoint for token generation
23
- "customClaims": {} // Optional: extra claims to include in tokens
24
- }
9
+ const AUTH_SCHEMA_SCHEMA = `
10
+ Single AuthSchema object:
11
+ {
12
+ "strategy": "nextauth", // "nextauth"|"clerk"|"auth0"|"custom-jwt"|"session-cookie"|"none"|"unknown"
13
+ "sessionFields": [ // Fields available in the session/token
14
+ "id",
15
+ "email",
16
+ "name",
17
+ "orgId",
18
+ "role"
19
+ ],
20
+ "guestAllowed": false, // Whether unauthenticated users can use the shell
21
+ "tokenExpirySeconds": 300, // How long Duct delegated tokens should live
22
+ "tokenEndpoint": "/api/duct/token", // Optional: endpoint for token generation
23
+ "customClaims": {} // Optional: extra claims to include in tokens
24
+ }
25
25
  `.trim();
26
26
  // ----------------------------------------------------------------
27
27
  // File candidates for each auth system
@@ -69,9 +69,22 @@ const AUTH_FILE_CANDIDATES = [
69
69
  // ----------------------------------------------------------------
70
70
  // Prompt builder
71
71
  // ----------------------------------------------------------------
72
- async function buildAuthPrompt(sandboxFs) {
72
+ async function buildAuthPrompt(sandboxFs, hintFiles) {
73
73
  const lines = [];
74
74
  lines.push("Analyze this project's authentication configuration.\n");
75
+ // If the selector pre-identified targeted auth files, include them first.
76
+ if (hintFiles && hintFiles.length > 0) {
77
+ lines.push("## Targeted auth files:");
78
+ for (const f of hintFiles.slice(0, 10)) {
79
+ const content = await sandboxFs.readFile(f);
80
+ if (!content)
81
+ continue;
82
+ lines.push(`\n### ${f}:`);
83
+ lines.push("```ts");
84
+ lines.push(content.slice(0, 2000));
85
+ lines.push("```");
86
+ }
87
+ }
75
88
  // Read package.json for deps
76
89
  const pkg = await sandboxFs.readJSON("package.json");
77
90
  if (pkg) {
@@ -133,11 +146,11 @@ async function buildAuthPrompt(sandboxFs) {
133
146
  }
134
147
  }
135
148
  }
136
- lines.push(`\n\nBased on all the above:
137
- 1. Identify the auth strategy
138
- 2. List all fields available in the user session/token (look for callback functions that shape the session, JWT callbacks, useSession() patterns)
139
- 3. Determine if guest (unauthenticated) access is allowed
140
- 4. Suggest an appropriate token expiry (default 300 seconds for most apps)
149
+ lines.push(`\n\nBased on all the above:
150
+ 1. Identify the auth strategy
151
+ 2. List all fields available in the user session/token (look for callback functions that shape the session, JWT callbacks, useSession() patterns)
152
+ 3. Determine if guest (unauthenticated) access is allowed
153
+ 4. Suggest an appropriate token expiry (default 300 seconds for most apps)
141
154
  5. Suggest a token endpoint path if one should be created (default: /api/duct/token)`);
142
155
  return lines.join("\n");
143
156
  }
@@ -146,9 +159,10 @@ async function buildAuthPrompt(sandboxFs) {
146
159
  // ----------------------------------------------------------------
147
160
  /**
148
161
  * Run the Auth Agent to produce an AuthSchema from the project's auth configuration.
162
+ * @param hintFiles - Optional pre-selected auth file paths from the file selector.
149
163
  */
150
- export async function runAuthAgent(sandboxFs) {
151
- const prompt = await buildAuthPrompt(sandboxFs);
164
+ export async function runAuthAgent(sandboxFs, hintFiles) {
165
+ const prompt = await buildAuthPrompt(sandboxFs, hintFiles);
152
166
  const result = await callDuctLLM({
153
167
  agentName: "AuthAgent",
154
168
  systemPrompt: "You are an expert at analyzing authentication configurations in Next.js and React applications. " +