@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
@@ -6,28 +6,28 @@ import { callDuctLLM } from "./llm.js";
6
6
  // ----------------------------------------------------------------
7
7
  // Output schema description
8
8
  // ----------------------------------------------------------------
9
- const DEEPLINK_SCHEMA = `
10
- Array of DeeplinkDefinition objects:
11
- [
12
- {
13
- "id": "view_order", // snake_case ID
14
- "name": "View Order", // Human-readable name
15
- "description": "...", // What happens when user follows this deeplink
16
- "targetRoute": "/orders/[id]", // Must match a route path from routes[]
17
- "stateFields": [ // State fields encoded in the deeplink JWT
18
- {
19
- "key": "orderId",
20
- "type": "string", // "string"|"number"|"boolean"|"object"
21
- "required": true,
22
- "description": "The order to view",
23
- "sessionSource": "user.id" // Optional: auto-populate from session
24
- }
25
- ],
26
- "expirySeconds": 300, // Token TTL (default 300)
27
- "requiresAuth": true, // Whether user must be authenticated
28
- "intent": "Show the user their specific order details" // For agent use
29
- }
30
- ]
9
+ const DEEPLINK_SCHEMA = `
10
+ Array of DeeplinkDefinition objects:
11
+ [
12
+ {
13
+ "id": "view_order", // snake_case ID
14
+ "name": "View Order", // Human-readable name
15
+ "description": "...", // What happens when user follows this deeplink
16
+ "targetRoute": "/orders/[id]", // Must match a route path from routes[]
17
+ "stateFields": [ // State fields encoded in the deeplink JWT
18
+ {
19
+ "key": "orderId",
20
+ "type": "string", // "string"|"number"|"boolean"|"object"
21
+ "required": true,
22
+ "description": "The order to view",
23
+ "sessionSource": "user.id" // Optional: auto-populate from session
24
+ }
25
+ ],
26
+ "expirySeconds": 300, // Token TTL (default 300)
27
+ "requiresAuth": true, // Whether user must be authenticated
28
+ "intent": "Show the user their specific order details" // For agent use
29
+ }
30
+ ]
31
31
  `.trim();
32
32
  // ----------------------------------------------------------------
33
33
  // Prompt builder
@@ -54,30 +54,30 @@ function buildDeeplinkPrompt(routes, actions) {
54
54
  lines.push(`- ${action.id}: ${action.method} ${action.path} — ${action.description || action.name}`);
55
55
  }
56
56
  }
57
- lines.push(`
58
- ## Instructions:
59
- Propose deeplinks for routes that are useful entry points for an AI assistant to send a user to.
60
- Good deeplink candidates:
61
- - Order/purchase detail pages (e.g., /orders/[id])
62
- - Product pages (e.g., /products/[slug])
63
- - Checkout flows (e.g., /checkout)
64
- - User profile/settings pages
65
- - Specific feature pages the user might want to navigate to after a conversation
66
- - Dashboard pages
67
-
68
- For each deeplink:
69
- 1. Only target routes marked as deeplinkable: true, OR routes with dynamic params (those are almost always deeplinkable)
70
- 2. Define state fields that need to be pre-loaded (e.g., orderId, productId)
71
- 3. Mark sessionSource for fields that can come from the user session automatically
72
- 4. Set requiresAuth based on the route's requiresAuth value
73
- 5. Write a clear intent description for the AI agent to understand when to use it
74
-
75
- Avoid deeplinks to:
76
- - Auth pages (login, signup)
77
- - Error pages
78
- - Static/generic pages without meaningful state
79
- - Pages the user would always navigate to themselves
80
-
57
+ lines.push(`
58
+ ## Instructions:
59
+ Propose deeplinks for routes that are useful entry points for an AI assistant to send a user to.
60
+ Good deeplink candidates:
61
+ - Order/purchase detail pages (e.g., /orders/[id])
62
+ - Product pages (e.g., /products/[slug])
63
+ - Checkout flows (e.g., /checkout)
64
+ - User profile/settings pages
65
+ - Specific feature pages the user might want to navigate to after a conversation
66
+ - Dashboard pages
67
+
68
+ For each deeplink:
69
+ 1. Only target routes marked as deeplinkable: true, OR routes with dynamic params (those are almost always deeplinkable)
70
+ 2. Define state fields that need to be pre-loaded (e.g., orderId, productId)
71
+ 3. Mark sessionSource for fields that can come from the user session automatically
72
+ 4. Set requiresAuth based on the route's requiresAuth value
73
+ 5. Write a clear intent description for the AI agent to understand when to use it
74
+
75
+ Avoid deeplinks to:
76
+ - Auth pages (login, signup)
77
+ - Error pages
78
+ - Static/generic pages without meaningful state
79
+ - Pages the user would always navigate to themselves
80
+
81
81
  Target 3-10 deeplinks. Quality over quantity.`);
82
82
  return lines.join("\n");
83
83
  }
@@ -235,6 +235,7 @@ export async function runDeeplinkAgent(routes, actions) {
235
235
  }
236
236
  }
237
237
  }
238
+ const normalizePath = (p) => p.replace(/\[([^\]]+)\]/g, ":$1");
238
239
  const deeplinks = result.parsed
239
240
  .filter((d) => {
240
241
  return (typeof d === "object" &&
@@ -256,8 +257,29 @@ export async function runDeeplinkAgent(routes, actions) {
256
257
  // Validate target route exists (or normalize brackets)
257
258
  if (routePaths.has(d.targetRoute))
258
259
  return true;
259
- const normalized = d.targetRoute.replace(/\[([^\]]+)\]/g, ":$1");
260
- return Array.from(routePaths).some((p) => p.replace(/\[([^\]]+)\]/g, ":$1") === normalized) || routes.length === 0;
260
+ const normalized = normalizePath(d.targetRoute);
261
+ return Array.from(routePaths).some((p) => normalizePath(p) === normalized) || routes.length === 0;
262
+ });
263
+ // When the LLM returned empty stateFields but the matched route has path params,
264
+ // synthesize StateField entries deterministically from the route's params array.
265
+ // This is the most common LLM omission — it knows the param names (they're in the prompt)
266
+ // but routinely forgets to populate stateFields for "obvious" routes.
267
+ return deeplinks.map((d) => {
268
+ if (d.stateFields.length > 0)
269
+ return d;
270
+ const matchedRoute = routes.find((r) => {
271
+ if (r.path === d.targetRoute)
272
+ return true;
273
+ return normalizePath(r.path) === normalizePath(d.targetRoute);
274
+ });
275
+ if (!matchedRoute || matchedRoute.params.length === 0)
276
+ return d;
277
+ const syntheticFields = matchedRoute.params.map((p) => ({
278
+ key: p.name,
279
+ type: "string",
280
+ required: p.required ?? true,
281
+ description: p.description || `${p.name} path parameter`,
282
+ }));
283
+ return { ...d, stateFields: mapStateFieldSources(syntheticFields, actionResponseFields) };
261
284
  });
262
- return deeplinks;
263
285
  }
@@ -24,7 +24,7 @@ export interface LLMCallResult {
24
24
  * Provider is resolved in this order:
25
25
  * 1. LLM_PROVIDER env var (explicit)
26
26
  * 2. First available API key: DUCT_API_KEY → ANTHROPIC_API_KEY → OPENAI_API_KEY
27
- * → GEMINI_API_KEY → GROQ_API_KEY → OPENROUTER_API_KEY
27
+ * → GEMINI_API_KEY → GROQ_API_KEY → XAI_API_KEY (Grok) → OPENROUTER_API_KEY
28
28
  *
29
29
  * Model name is always taken from LLM_MODEL — never hardcoded.
30
30
  *
@@ -1,11 +1,15 @@
1
1
  // ============================================================
2
2
  // @duct/sdk — LLM Helper
3
- // Supports Anthropic, OpenAI, Gemini, Groq, OpenRouter,
4
- // and the Duct hosted endpoint.
3
+ // Supports Anthropic, OpenAI, Gemini, Groq, Grok (xAI),
4
+ // OpenRouter, and the Duct hosted endpoint.
5
5
  //
6
6
  // Provider is auto-detected from available env vars, or set
7
7
  // explicitly via LLM_PROVIDER. Model name is never hardcoded —
8
8
  // always set LLM_MODEL in your environment.
9
+ //
10
+ // Note: "grok" is xAI's Grok (api.x.ai) — distinct from "groq"
11
+ // (api.groq.com). The xAI key follows xAI's official console
12
+ // naming convention: XAI_API_KEY.
9
13
  // ============================================================
10
14
  import Anthropic from "@anthropic-ai/sdk";
11
15
  import { getActiveApiBase, getConfiguredDashboard, } from "../../core/endpoints.js";
@@ -20,6 +24,7 @@ function resolveProvider() {
20
24
  openai: process.env["OPENAI_API_KEY"],
21
25
  gemini: process.env["GEMINI_API_KEY"],
22
26
  groq: process.env["GROQ_API_KEY"],
27
+ grok: process.env["XAI_API_KEY"],
23
28
  openrouter: process.env["OPENROUTER_API_KEY"],
24
29
  duct: process.env["DUCT_API_KEY"],
25
30
  };
@@ -36,8 +41,8 @@ function resolveProvider() {
36
41
  }
37
42
  return { provider: explicitProvider, apiKey: key, model: model ?? "" };
38
43
  }
39
- // Auto-detect: first key that's set wins (duct → anthropic → openai → gemini → groq → openrouter)
40
- const autoOrder = ["duct", "anthropic", "openai", "gemini", "groq", "openrouter"];
44
+ // Auto-detect: first key that's set wins (duct → anthropic → openai → gemini → groq → grok → openrouter)
45
+ const autoOrder = ["duct", "anthropic", "openai", "gemini", "groq", "grok", "openrouter"];
41
46
  for (const p of autoOrder) {
42
47
  const key = keys[p];
43
48
  if (key) {
@@ -54,7 +59,8 @@ function resolveProvider() {
54
59
  ` ANTHROPIC_API_KEY — Anthropic Claude\n` +
55
60
  ` OPENAI_API_KEY — OpenAI\n` +
56
61
  ` GEMINI_API_KEY — Google Gemini\n` +
57
- ` GROQ_API_KEY — Groq\n` +
62
+ ` GROQ_API_KEY — Groq (api.groq.com)\n` +
63
+ ` XAI_API_KEY — Grok / xAI (api.x.ai)\n` +
58
64
  ` OPENROUTER_API_KEY — OpenRouter\n` +
59
65
  ` DUCT_API_KEY — Duct hosted AI endpoint (requires Duct hosted LLM API)\n\n` +
60
66
  `Also set LLM_MODEL to the model you want to use (e.g. LLM_MODEL=your-preferred-model).\n` +
@@ -67,6 +73,7 @@ function providerKeyHint(provider) {
67
73
  openai: "Set OPENAI_API_KEY",
68
74
  gemini: "Set GEMINI_API_KEY",
69
75
  groq: "Set GROQ_API_KEY",
76
+ grok: "Set XAI_API_KEY (Grok uses xAI's official key naming)",
70
77
  openrouter: "Set OPENROUTER_API_KEY",
71
78
  duct: "Set DUCT_API_KEY",
72
79
  };
@@ -81,7 +88,7 @@ function providerKeyHint(provider) {
81
88
  * Provider is resolved in this order:
82
89
  * 1. LLM_PROVIDER env var (explicit)
83
90
  * 2. First available API key: DUCT_API_KEY → ANTHROPIC_API_KEY → OPENAI_API_KEY
84
- * → GEMINI_API_KEY → GROQ_API_KEY → OPENROUTER_API_KEY
91
+ * → GEMINI_API_KEY → GROQ_API_KEY → XAI_API_KEY (Grok) → OPENROUTER_API_KEY
85
92
  *
86
93
  * Model name is always taken from LLM_MODEL — never hardcoded.
87
94
  *
@@ -90,15 +97,15 @@ function providerKeyHint(provider) {
90
97
  export async function callDuctLLM(options) {
91
98
  const { agentName, systemPrompt, userPrompt, outputSchema, maxTokens = 4096, maxRetries = 3, } = options;
92
99
  const { provider, apiKey, model } = resolveProvider();
93
- const fullSystemPrompt = `${systemPrompt}
94
-
95
- You are the ${agentName} agent in the Duct SDK pipeline. Your job is to analyze a codebase and produce structured output.
96
-
97
- IMPORTANT OUTPUT RULES:
98
- 1. Respond with ONLY valid JSON — no markdown, no prose, no code fences
99
- 2. Your output must exactly match this schema:
100
- ${outputSchema}
101
- 3. Be thorough but concise. Prefer accuracy over completeness.
100
+ const fullSystemPrompt = `${systemPrompt}
101
+
102
+ You are the ${agentName} agent in the Duct SDK pipeline. Your job is to analyze a codebase and produce structured output.
103
+
104
+ IMPORTANT OUTPUT RULES:
105
+ 1. Respond with ONLY valid JSON — no markdown, no prose, no code fences
106
+ 2. Your output must exactly match this schema:
107
+ ${outputSchema}
108
+ 3. Be thorough but concise. Prefer accuracy over completeness.
102
109
  4. If you're uncertain about a value, use a sensible default rather than omitting it.`;
103
110
  let lastError = null;
104
111
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
@@ -112,6 +119,8 @@ ${outputSchema}
112
119
  return await callGemini({ apiKey, model, systemPrompt: fullSystemPrompt, userPrompt, maxTokens });
113
120
  case "groq":
114
121
  return await callOpenAICompatible({ apiKey, model, systemPrompt: fullSystemPrompt, userPrompt, maxTokens, baseUrl: "https://api.groq.com/openai/v1" });
122
+ case "grok":
123
+ return await callOpenAICompatible({ apiKey, model, systemPrompt: fullSystemPrompt, userPrompt, maxTokens, baseUrl: "https://api.x.ai/v1" });
115
124
  case "openrouter":
116
125
  return await callOpenAICompatible({ apiKey, model, systemPrompt: fullSystemPrompt, userPrompt, maxTokens, baseUrl: process.env["OPENROUTER_BASE_URL"] ?? "https://openrouter.ai/api/v1" });
117
126
  case "duct":
@@ -120,6 +129,10 @@ ${outputSchema}
120
129
  }
121
130
  catch (err) {
122
131
  lastError = err instanceof Error ? err : new Error(String(err));
132
+ // Fail fast on non-transient errors (auth failures, bad requests, JSON parse errors)
133
+ if (!isRetryableError(lastError)) {
134
+ throw lastError;
135
+ }
123
136
  if (attempt < maxRetries) {
124
137
  await sleep(Math.pow(2, attempt - 1) * 1000);
125
138
  continue;
@@ -274,3 +287,23 @@ function parseJSONResponse(text) {
274
287
  function sleep(ms) {
275
288
  return new Promise((resolve) => setTimeout(resolve, ms));
276
289
  }
290
+ /**
291
+ * Returns true for transient errors that are safe to retry.
292
+ * Auth errors (401/403) and bad-request (400) should fail immediately.
293
+ */
294
+ function isRetryableError(err) {
295
+ const msg = err.message.toLowerCase();
296
+ return (msg.includes("429") ||
297
+ msg.includes("502") ||
298
+ msg.includes("503") ||
299
+ msg.includes("504") ||
300
+ msg.includes("rate limit") ||
301
+ msg.includes("too many requests") ||
302
+ msg.includes("overloaded") ||
303
+ msg.includes("service unavailable") ||
304
+ msg.includes("timeout") ||
305
+ msg.includes("econnreset") ||
306
+ msg.includes("enotfound") ||
307
+ msg.includes("network") ||
308
+ msg.includes("socket"));
309
+ }
@@ -1,5 +1,7 @@
1
1
  import { EventEmitter } from "events";
2
2
  import type { SandboxFS } from "../fs/sandbox.js";
3
+ import type { PostProcessOptions } from "../processors/postprocess.js";
4
+ import type { ReadList } from "../selectors/index.js";
3
5
  import type { RouteManifest, ActionManifest, AuthSchema, DeeplinkDefinition, ReviewResult } from "../../core/types.js";
4
6
  export interface PipelineOptions {
5
7
  /** Override specific agents */
@@ -8,6 +10,20 @@ export interface PipelineOptions {
8
10
  emitter?: PipelineEmitter;
9
11
  /** Timeout in ms per agent (default: 120_000) */
10
12
  agentTimeout?: number;
13
+ /**
14
+ * Bounded file list from the file selector — when provided, agents
15
+ * prioritize these files over their own broad scans.
16
+ */
17
+ readList?: ReadList;
18
+ /**
19
+ * Raw content of an OpenAPI/Swagger spec file (from --api-spec flag).
20
+ * When provided, skips Route + API agents and parses the spec directly.
21
+ */
22
+ apiSpecContent?: string;
23
+ /** Path label for the spec file (used in prompt context). */
24
+ apiSpecPath?: string;
25
+ /** Options passed to the deterministic post-processing step. */
26
+ postProcess?: PostProcessOptions;
11
27
  }
12
28
  export interface PipelineResult {
13
29
  routes: RouteManifest[];
@@ -8,6 +8,7 @@ import { runApiAgent } from "./api-agent.js";
8
8
  import { runAuthAgent } from "./auth-agent.js";
9
9
  import { runDeeplinkAgent } from "./deeplink-agent.js";
10
10
  import { runReviewerAgent } from "./reviewer-agent.js";
11
+ import { applyDeterministicRules } from "../processors/postprocess.js";
11
12
  // ----------------------------------------------------------------
12
13
  // Default emitter (uses Node EventEmitter)
13
14
  // ----------------------------------------------------------------
@@ -93,7 +94,12 @@ function defaultReview() {
93
94
  * @returns PipelineResult with all agent outputs
94
95
  */
95
96
  export async function runAgentPipeline(sandboxFs, opts = {}) {
96
- const { skipAgents = [], emitter, agentTimeout = 120_000, } = opts;
97
+ const { skipAgents: skipAgentsInput = [], emitter, agentTimeout = 120_000, readList, apiSpecContent, apiSpecPath, postProcess = {}, } = opts;
98
+ // When an OpenAPI spec is provided, skip Route + API agents entirely —
99
+ // the spec is the authoritative source for both routes and actions.
100
+ const skipAgents = apiSpecContent
101
+ ? [...new Set([...skipAgentsInput, "routes", "actions"])]
102
+ : skipAgentsInput;
97
103
  const startTime = Date.now();
98
104
  emitter?.emitEvent({ type: "start", message: "Starting Duct agent pipeline...", progress: 0 });
99
105
  // ---- Stage 1: Parallel agents ----
@@ -107,7 +113,7 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
107
113
  return defaultRoutes();
108
114
  emitter?.emitEvent({ type: "agent:start", agent: "RouteAgent", message: "Analyzing routes...", progress: 5 });
109
115
  try {
110
- const result = await withTimeout(() => runRouteAgent(sandboxFs), agentTimeout, "RouteAgent");
116
+ const result = await withTimeout(() => runRouteAgent(sandboxFs, readList?.routeFiles), agentTimeout, "RouteAgent");
111
117
  emitter?.emitEvent({
112
118
  type: "agent:complete",
113
119
  agent: "RouteAgent",
@@ -127,9 +133,12 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
127
133
  (async () => {
128
134
  if (skipAgents.includes("actions"))
129
135
  return defaultActions();
130
- emitter?.emitEvent({ type: "agent:start", agent: "ApiAgent", message: "Analyzing API endpoints...", progress: 5 });
136
+ const apiMsg = apiSpecContent
137
+ ? `Parsing OpenAPI spec (${apiSpecPath ?? "openapi"})...`
138
+ : "Analyzing API endpoints...";
139
+ emitter?.emitEvent({ type: "agent:start", agent: "ApiAgent", message: apiMsg, progress: 5 });
131
140
  try {
132
- const result = await withTimeout(() => runApiAgent(sandboxFs), agentTimeout, "ApiAgent");
141
+ const result = await withTimeout(() => runApiAgent(sandboxFs, readList?.apiFiles, apiSpecContent, apiSpecPath), agentTimeout, "ApiAgent");
133
142
  emitter?.emitEvent({
134
143
  type: "agent:complete",
135
144
  agent: "ApiAgent",
@@ -151,7 +160,7 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
151
160
  return defaultAuth();
152
161
  emitter?.emitEvent({ type: "agent:start", agent: "AuthAgent", message: "Analyzing auth configuration...", progress: 5 });
153
162
  try {
154
- const result = await withTimeout(() => runAuthAgent(sandboxFs), agentTimeout, "AuthAgent");
163
+ const result = await withTimeout(() => runAuthAgent(sandboxFs, readList?.authFiles), agentTimeout, "AuthAgent");
155
164
  emitter?.emitEvent({
156
165
  type: "agent:complete",
157
166
  agent: "AuthAgent",
@@ -169,6 +178,10 @@ export async function runAgentPipeline(sandboxFs, opts = {}) {
169
178
  })(),
170
179
  ];
171
180
  [routes, actions, auth] = await Promise.all(stage1Agents);
181
+ // Apply deterministic rules: enforce sideEffects from HTTP method,
182
+ // derive sensitivityLevel from path/name keywords, and (in yesMode) auto-enable
183
+ // agentAccessible on safe GET/HEAD with confidence ≥ 0.85.
184
+ actions = applyDeterministicRules(actions, postProcess);
172
185
  emitter?.emitEvent({ type: "agent:complete", message: "Stage 1 complete (routes, actions, auth)", progress: 60 });
173
186
  // ---- Stage 2: Deeplink agent ----
174
187
  let deeplinks;
@@ -7,26 +7,26 @@ import { buildAction } from "../../core/action.js";
7
7
  // ----------------------------------------------------------------
8
8
  // Output schema
9
9
  // ----------------------------------------------------------------
10
- const REVIEW_RESULT_SCHEMA = `
11
- Single ReviewResult object:
12
- {
13
- "passed": true, // Overall pass/fail
14
- "confidenceScore": 0.87, // 0-1 confidence in the pipeline output
15
- "issues": [
16
- {
17
- "code": "ROUTE_MISSING_DESCRIPTION",
18
- "severity": "warning", // "error"|"warning"|"info"
19
- "message": "Route /dashboard has no description",
20
- "path": "routes[0].description",
21
- "suggestion": "Add a description explaining what the dashboard shows"
22
- }
23
- ],
24
- "suggestions": [
25
- "Consider adding a deeplink for the checkout page",
26
- "Enable agentAccessible on get_orders for a better agent experience"
27
- ],
28
- "summary": "Config looks good overall. 2 warnings found."
29
- }
10
+ const REVIEW_RESULT_SCHEMA = `
11
+ Single ReviewResult object:
12
+ {
13
+ "passed": true, // Overall pass/fail
14
+ "confidenceScore": 0.87, // 0-1 confidence in the pipeline output
15
+ "issues": [
16
+ {
17
+ "code": "ROUTE_MISSING_DESCRIPTION",
18
+ "severity": "warning", // "error"|"warning"|"info"
19
+ "message": "Route /dashboard has no description",
20
+ "path": "routes[0].description",
21
+ "suggestion": "Add a description explaining what the dashboard shows"
22
+ }
23
+ ],
24
+ "suggestions": [
25
+ "Consider adding a deeplink for the checkout page",
26
+ "Enable agentAccessible on get_orders for a better agent experience"
27
+ ],
28
+ "summary": "Config looks good overall. 2 warnings found."
29
+ }
30
30
  `.trim();
31
31
  // ----------------------------------------------------------------
32
32
  // Rule-based pre-checks
@@ -311,32 +311,32 @@ export async function runReviewerAgent(input) {
311
311
  // Run static rule-based checks first
312
312
  const staticIssues = await runStaticChecks(input);
313
313
  // Build LLM review prompt
314
- const prompt = `Review this Duct configuration for quality, completeness, and correctness.
315
-
316
- ## Routes (${input.routes.length} total):
317
- ${JSON.stringify(input.routes.slice(0, 15), null, 2)}
318
-
319
- ## Actions (${input.actions.length} total):
320
- ${JSON.stringify(input.actions.slice(0, 15), null, 2)}
321
-
322
- ## Auth:
323
- ${JSON.stringify(input.auth, null, 2)}
324
-
325
- ## Deeplinks (${input.deeplinks.length} total):
326
- ${JSON.stringify(input.deeplinks, null, 2)}
327
-
328
- ## Static Issues Already Found:
329
- ${staticIssues.map((i) => `- [${i.severity}] ${i.code}: ${i.message}`).join("\n") || "None"}
330
-
331
- Please review for:
332
- 1. Completeness — are important routes/actions likely missing?
333
- 2. Consistency — do deeplinks target valid routes? Do action IDs make sense?
334
- 3. Security — are any sensitive actions incorrectly marked agent-accessible?
335
- 4. Quality — are descriptions informative enough for an AI to understand intent?
336
- 5. Coverage — does the deeplink set cover the most important user journeys?
337
-
338
- Combine the static issues above with any new issues you find.
339
- Calculate a confidence score (0-1) based on how complete and correct this config appears.
314
+ const prompt = `Review this Duct configuration for quality, completeness, and correctness.
315
+
316
+ ## Routes (${input.routes.length} total):
317
+ ${JSON.stringify(input.routes.slice(0, 15), null, 2)}
318
+
319
+ ## Actions (${input.actions.length} total):
320
+ ${JSON.stringify(input.actions.slice(0, 15), null, 2)}
321
+
322
+ ## Auth:
323
+ ${JSON.stringify(input.auth, null, 2)}
324
+
325
+ ## Deeplinks (${input.deeplinks.length} total):
326
+ ${JSON.stringify(input.deeplinks, null, 2)}
327
+
328
+ ## Static Issues Already Found:
329
+ ${staticIssues.map((i) => `- [${i.severity}] ${i.code}: ${i.message}`).join("\n") || "None"}
330
+
331
+ Please review for:
332
+ 1. Completeness — are important routes/actions likely missing?
333
+ 2. Consistency — do deeplinks target valid routes? Do action IDs make sense?
334
+ 3. Security — are any sensitive actions incorrectly marked agent-accessible?
335
+ 4. Quality — are descriptions informative enough for an AI to understand intent?
336
+ 5. Coverage — does the deeplink set cover the most important user journeys?
337
+
338
+ Combine the static issues above with any new issues you find.
339
+ Calculate a confidence score (0-1) based on how complete and correct this config appears.
340
340
  Set passed: false if there are any "error" severity issues.`;
341
341
  let llmResult;
342
342
  try {
@@ -9,5 +9,7 @@ export interface RouteScannerStrategy {
9
9
  }
10
10
  /**
11
11
  * Run the Route Agent to produce a RouteManifest[] from the project structure.
12
+ * @param hintFiles - Optional pre-selected file paths from the file selector.
13
+ * When provided, these are included first in the prompt as priority context.
12
14
  */
13
- export declare function runRouteAgent(sandboxFs: SandboxFS): Promise<RouteManifest[]>;
15
+ export declare function runRouteAgent(sandboxFs: SandboxFS, hintFiles?: string[]): Promise<RouteManifest[]>;
@@ -205,43 +205,64 @@ async function detectFrontendRoots(sandboxFs) {
205
205
  // ----------------------------------------------------------------
206
206
  // Output schema description for the LLM
207
207
  // ----------------------------------------------------------------
208
- const ROUTE_MANIFEST_SCHEMA = `
209
- Array of RouteManifest objects:
210
- [
211
- {
212
- "path": "/dashboard", // Route path with Next.js brackets e.g. /orders/[id]
213
- "name": "Dashboard", // Human-readable name
214
- "description": "...", // What this page shows/does
215
- "params": [ // Dynamic path params
216
- {
217
- "name": "id",
218
- "type": "uuid", // "string" | "number" | "uuid" | "slug"
219
- "required": true,
220
- "description": "Order ID"
221
- }
222
- ],
223
- "queryParams": [ // URL query params
224
- {
225
- "name": "page",
226
- "type": "number",
227
- "required": false,
228
- "description": "Page number",
229
- "defaultValue": 1
230
- }
231
- ],
232
- "uiStateHint": "dashboard", // "form"|"list"|"detail"|"dashboard"|"modal"|"wizard"|"empty"|"error"|"auth"|"checkout"|"profile"|"settings"|"search"
233
- "requiresAuth": true,
234
- "deeplinkable": true // Whether Duct can deeplink here with state
235
- }
236
- ]
208
+ const ROUTE_MANIFEST_SCHEMA = `
209
+ Array of RouteManifest objects:
210
+ [
211
+ {
212
+ "path": "/dashboard", // Route path with Next.js brackets e.g. /orders/[id]
213
+ "name": "Dashboard", // Human-readable name
214
+ "description": "...", // What this page shows/does
215
+ "params": [ // Dynamic path params
216
+ {
217
+ "name": "id",
218
+ "type": "uuid", // "string" | "number" | "uuid" | "slug"
219
+ "required": true,
220
+ "description": "Order ID"
221
+ }
222
+ ],
223
+ "queryParams": [ // URL query params
224
+ {
225
+ "name": "page",
226
+ "type": "number",
227
+ "required": false,
228
+ "description": "Page number",
229
+ "defaultValue": 1
230
+ }
231
+ ],
232
+ "uiStateHint": "dashboard", // "form"|"list"|"detail"|"dashboard"|"modal"|"wizard"|"empty"|"error"|"auth"|"checkout"|"profile"|"settings"|"search"
233
+ "requiresAuth": true,
234
+ "deeplinkable": true, // Whether Duct can deeplink here with state
235
+ "confidence": 0.92, // Detection confidence 0.0–1.0. Lower for: dynamic routes inferred from patterns, no explicit auth check found, file missing
236
+ "evidence": "app/dashboard/page.tsx:1" // File path and line number where this route was detected
237
+ }
238
+ ]
239
+
240
+ Confidence scoring rules:
241
+ - 1.0: explicit file path maps directly to route, auth check is clear
242
+ - 0.85–0.99: clear file evidence, auth inferred from layout wrapper
243
+ - 0.6–0.84: route exists but auth is ambiguous, or param type is guessed
244
+ - below 0.6: route inferred from naming/pattern, not explicit file evidence
237
245
  `.trim();
238
246
  // ----------------------------------------------------------------
239
247
  // Prompt builder — uses RouteScannerStrategy
240
248
  // ----------------------------------------------------------------
241
- async function buildRoutePrompt(sandboxFs) {
249
+ async function buildRoutePrompt(sandboxFs, hintFiles) {
242
250
  const lines = [];
243
251
  lines.push("Analyze this web project and identify all user-facing navigable routes.\n" +
244
252
  "Use the file structure and code snippets below to produce a RouteManifest array.\n");
253
+ // If the selector pre-identified targeted files, include them first.
254
+ if (hintFiles && hintFiles.length > 0) {
255
+ lines.push("## Targeted route files:");
256
+ for (const f of hintFiles.slice(0, 30)) {
257
+ const content = await sandboxFs.readFile(f);
258
+ if (!content)
259
+ continue;
260
+ lines.push(`\n### ${f}:`);
261
+ lines.push("```tsx");
262
+ lines.push(content.slice(0, 1200));
263
+ lines.push("```");
264
+ }
265
+ }
245
266
  // Detect monorepo frontend roots — allows scanning frontend/ or web/ subdirectories
246
267
  const frontendRoots = await detectFrontendRoots(sandboxFs);
247
268
  if (frontendRoots.some((r) => r !== "")) {
@@ -289,18 +310,18 @@ async function buildRoutePrompt(sandboxFs) {
289
310
  break;
290
311
  }
291
312
  }
292
- lines.push(`
293
- ## Instructions
294
-
295
- For each user-facing route produce a RouteManifest entry:
296
- - **path**: Derive from file structure. Next.js: [param] stays as-is. Remix: convert dots to slashes. SvelteKit: +page.svelte filename is the segment.
297
- - **requiresAuth**: true if: (1) the page/layout calls auth(), getServerSession(), currentUser(), or equivalent; (2) middleware.ts matches the route path; (3) when uncertain, default true (fail-safe).
298
- - **uiStateHint**: Classify from component imports and page content. Priority: checkout > wizard > modal > form > list > detail > dashboard. Map: <Table>/<DataGrid> → list, <Form>/<Input> → form, <Modal>/<Dialog> → modal, <Wizard>/<Steps> → wizard.
299
- - **deeplinkable**: true when the route has at least one required path param AND requiresAuth is true (a signed deeplink JWT makes sense for authenticated detail pages).
300
- - **queryParams**: Extract from useSearchParams().get('...') / $page.url.searchParams.get('...') calls — infer type from usage context.
301
- - **params**: Typed from file path segment names ([id] → uuid/string, [slug] → slug).
302
-
303
- DO NOT include API routes (/api/...), auth callback routes, or static asset paths.
313
+ lines.push(`
314
+ ## Instructions
315
+
316
+ For each user-facing route produce a RouteManifest entry:
317
+ - **path**: Derive from file structure. Next.js: [param] stays as-is. Remix: convert dots to slashes. SvelteKit: +page.svelte filename is the segment.
318
+ - **requiresAuth**: true if: (1) the page/layout calls auth(), getServerSession(), currentUser(), or equivalent; (2) middleware.ts matches the route path; (3) when uncertain, default true (fail-safe).
319
+ - **uiStateHint**: Classify from component imports and page content. Priority: checkout > wizard > modal > form > list > detail > dashboard. Map: <Table>/<DataGrid> → list, <Form>/<Input> → form, <Modal>/<Dialog> → modal, <Wizard>/<Steps> → wizard.
320
+ - **deeplinkable**: true when the route has at least one required path param AND requiresAuth is true (a signed deeplink JWT makes sense for authenticated detail pages).
321
+ - **queryParams**: Extract from useSearchParams().get('...') / $page.url.searchParams.get('...') calls — infer type from usage context.
322
+ - **params**: Typed from file path segment names ([id] → uuid/string, [slug] → slug).
323
+
324
+ DO NOT include API routes (/api/...), auth callback routes, or static asset paths.
304
325
  DO NOT include _app, _document, layout-only files that don't produce a page.`);
305
326
  return lines.join("\n");
306
327
  }
@@ -309,9 +330,11 @@ DO NOT include _app, _document, layout-only files that don't produce a page.`);
309
330
  // ----------------------------------------------------------------
310
331
  /**
311
332
  * Run the Route Agent to produce a RouteManifest[] from the project structure.
333
+ * @param hintFiles - Optional pre-selected file paths from the file selector.
334
+ * When provided, these are included first in the prompt as priority context.
312
335
  */
313
- export async function runRouteAgent(sandboxFs) {
314
- const prompt = await buildRoutePrompt(sandboxFs);
336
+ export async function runRouteAgent(sandboxFs, hintFiles) {
337
+ const prompt = await buildRoutePrompt(sandboxFs, hintFiles);
315
338
  const result = await callDuctLLM({
316
339
  agentName: "RouteAgent",
317
340
  systemPrompt: "You are an expert at analyzing Next.js, Remix, and React web application codebases. " +
@@ -341,6 +364,9 @@ export async function runRouteAgent(sandboxFs) {
341
364
  requiresAuth: r.requiresAuth ?? true,
342
365
  deeplinkable: r.deeplinkable ?? false,
343
366
  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 } : {}),
344
370
  }));
345
371
  return routes;
346
372
  }