@duct-sdk/sdk 0.5.13 → 0.6.0

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 (160) hide show
  1. package/CHANGELOG.md +385 -344
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -243
  4. package/dist/cli/add.d.ts +7 -0
  5. package/dist/cli/add.js +152 -0
  6. package/dist/cli/agent-prompt.d.ts +3 -0
  7. package/dist/cli/agent-prompt.js +39 -0
  8. package/dist/cli/api-sources.d.ts +26 -0
  9. package/dist/cli/api-sources.js +222 -0
  10. package/dist/cli/cloud.d.ts +133 -0
  11. package/dist/cli/cloud.js +298 -0
  12. package/dist/cli/config-loader.d.ts +14 -0
  13. package/dist/cli/config-loader.js +56 -7
  14. package/dist/cli/device-login.d.ts +17 -0
  15. package/dist/cli/device-login.js +75 -0
  16. package/dist/cli/drift.js +6 -6
  17. package/dist/cli/generators/any-stack.d.ts +3 -0
  18. package/dist/cli/generators/any-stack.js +97 -0
  19. package/dist/cli/generators/config.js +3 -2
  20. package/dist/cli/generators/receiver.js +7 -7
  21. package/dist/cli/generators/shell.js +12 -12
  22. package/dist/cli/generators/token-route.js +245 -245
  23. package/dist/cli/index.js +396 -611
  24. package/dist/cli/mcp-core.d.ts +42 -0
  25. package/dist/cli/mcp-core.js +161 -0
  26. package/dist/cli/mcp-setup.d.ts +4 -0
  27. package/dist/cli/mcp-setup.js +360 -0
  28. package/dist/cli/mcp.d.ts +2 -0
  29. package/dist/cli/mcp.js +457 -0
  30. package/dist/cli/migrate-intershell.js +5 -5
  31. package/dist/cli/policy-defaults.d.ts +37 -0
  32. package/dist/cli/policy-defaults.js +127 -0
  33. package/dist/cli/processors/integration-audit.js +2 -2
  34. package/dist/cli/processors/openapi-parser.d.ts +5 -0
  35. package/dist/cli/processors/openapi-parser.js +8 -3
  36. package/dist/cli/project-loader.d.ts +58 -0
  37. package/dist/cli/project-loader.js +198 -0
  38. package/dist/cli/project-writer.d.ts +23 -0
  39. package/dist/cli/project-writer.js +171 -0
  40. package/dist/cli/push.d.ts +43 -0
  41. package/dist/cli/push.js +276 -0
  42. package/dist/cli/safety-checks.d.ts +9 -0
  43. package/dist/cli/safety-checks.js +29 -0
  44. package/dist/cli/setup.d.ts +20 -0
  45. package/dist/cli/setup.js +349 -0
  46. package/dist/cli/shell-name.d.ts +8 -0
  47. package/dist/cli/shell-name.js +29 -0
  48. package/dist/cli/shells.d.ts +22 -0
  49. package/dist/cli/shells.js +122 -0
  50. package/dist/cli/split.d.ts +7 -0
  51. package/dist/cli/split.js +71 -0
  52. package/dist/cli/sync.d.ts +25 -0
  53. package/dist/cli/sync.js +120 -0
  54. package/dist/cli/test-runner.d.ts +21 -0
  55. package/dist/cli/test-runner.js +281 -0
  56. package/dist/core/compile.d.ts +43 -0
  57. package/dist/core/compile.js +510 -0
  58. package/dist/core/config.d.ts +464 -1
  59. package/dist/core/config.js +14 -14
  60. package/dist/core/login-handoff.d.ts +1 -1
  61. package/dist/core/login-handoff.js +1 -1
  62. package/dist/core/project.d.ts +1798 -0
  63. package/dist/core/project.js +278 -0
  64. package/dist/core/readiness-checks.js +2 -2
  65. package/dist/core/types.d.ts +1 -1
  66. package/dist/index.d.ts +2 -0
  67. package/dist/index.js +1 -0
  68. package/dist/project.d.ts +4 -0
  69. package/dist/project.js +8 -0
  70. package/dist/server.d.ts +2 -0
  71. package/dist/server.js +1 -0
  72. package/package.json +94 -95
  73. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  74. package/dist/adapters/react/page-context-guard.test.js +0 -15
  75. package/dist/cli/agents/api-agent.d.ts +0 -22
  76. package/dist/cli/agents/api-agent.js +0 -761
  77. package/dist/cli/agents/auth-agent.d.ts +0 -7
  78. package/dist/cli/agents/auth-agent.js +0 -212
  79. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  80. package/dist/cli/agents/deeplink-agent.js +0 -285
  81. package/dist/cli/agents/llm.d.ts +0 -33
  82. package/dist/cli/agents/llm.js +0 -309
  83. package/dist/cli/agents/pipeline.d.ts +0 -72
  84. package/dist/cli/agents/pipeline.js +0 -421
  85. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  86. package/dist/cli/agents/reviewer-agent.js +0 -450
  87. package/dist/cli/agents/route-agent.d.ts +0 -17
  88. package/dist/cli/agents/route-agent.js +0 -383
  89. package/dist/cli/config-loader.test.d.ts +0 -1
  90. package/dist/cli/config-loader.test.js +0 -63
  91. package/dist/cli/detectors/topology.d.ts +0 -46
  92. package/dist/cli/detectors/topology.js +0 -417
  93. package/dist/cli/generators/config.test.d.ts +0 -1
  94. package/dist/cli/generators/config.test.js +0 -222
  95. package/dist/cli/generators/shell.test.d.ts +0 -1
  96. package/dist/cli/generators/shell.test.js +0 -73
  97. package/dist/cli/generators/token-route.test.d.ts +0 -1
  98. package/dist/cli/generators/token-route.test.js +0 -53
  99. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  100. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  101. package/dist/cli/init.d.ts +0 -32
  102. package/dist/cli/init.js +0 -1336
  103. package/dist/cli/manifest-diff.test.d.ts +0 -1
  104. package/dist/cli/manifest-diff.test.js +0 -144
  105. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  106. package/dist/cli/processors/curl-parser.test.js +0 -24
  107. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  108. package/dist/cli/processors/integration-audit.test.js +0 -154
  109. package/dist/cli/processors/postprocess.d.ts +0 -22
  110. package/dist/cli/processors/postprocess.js +0 -107
  111. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  112. package/dist/cli/processors/prisma-parser.js +0 -117
  113. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  114. package/dist/cli/processors/verify-discovery.js +0 -193
  115. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  116. package/dist/cli/processors/verify-discovery.test.js +0 -153
  117. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  118. package/dist/cli/processors/zod-extractor.js +0 -153
  119. package/dist/cli/prompts/review.d.ts +0 -61
  120. package/dist/cli/prompts/review.js +0 -410
  121. package/dist/cli/selectors/express.d.ts +0 -12
  122. package/dist/cli/selectors/express.js +0 -117
  123. package/dist/cli/selectors/fastapi.d.ts +0 -12
  124. package/dist/cli/selectors/fastapi.js +0 -122
  125. package/dist/cli/selectors/generic.d.ts +0 -10
  126. package/dist/cli/selectors/generic.js +0 -74
  127. package/dist/cli/selectors/index.d.ts +0 -37
  128. package/dist/cli/selectors/index.js +0 -315
  129. package/dist/cli/selectors/next.d.ts +0 -12
  130. package/dist/cli/selectors/next.js +0 -130
  131. package/dist/core/config-policy.test.d.ts +0 -1
  132. package/dist/core/config-policy.test.js +0 -101
  133. package/dist/core/config-roundtrip.test.d.ts +0 -1
  134. package/dist/core/config-roundtrip.test.js +0 -180
  135. package/dist/core/endpoint-guard.test.d.ts +0 -1
  136. package/dist/core/endpoint-guard.test.js +0 -57
  137. package/dist/core/env-diagnostics.test.d.ts +0 -1
  138. package/dist/core/env-diagnostics.test.js +0 -31
  139. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  140. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  141. package/dist/core/evidence-bundle.test.d.ts +0 -1
  142. package/dist/core/evidence-bundle.test.js +0 -58
  143. package/dist/core/invariants.test.d.ts +0 -1
  144. package/dist/core/invariants.test.js +0 -217
  145. package/dist/core/login-handoff.test.d.ts +0 -1
  146. package/dist/core/login-handoff.test.js +0 -31
  147. package/dist/core/profile.test.d.ts +0 -1
  148. package/dist/core/profile.test.js +0 -95
  149. package/dist/core/readiness-checks.test.d.ts +0 -1
  150. package/dist/core/readiness-checks.test.js +0 -106
  151. package/dist/core/receipt.test.d.ts +0 -1
  152. package/dist/core/receipt.test.js +0 -75
  153. package/dist/core/sdk-entrypoint.test.d.ts +0 -1
  154. package/dist/core/sdk-entrypoint.test.js +0 -8
  155. package/dist/core/side-effects-review.test.d.ts +0 -1
  156. package/dist/core/side-effects-review.test.js +0 -28
  157. package/dist/core/token.conformance.test.d.ts +0 -1
  158. package/dist/core/token.conformance.test.js +0 -43
  159. package/dist/core/token.test.d.ts +0 -1
  160. package/dist/core/token.test.js +0 -66
@@ -1,7 +0,0 @@
1
- import type { SandboxFS } from "../fs/sandbox.js";
2
- import type { AuthSchema } from "../../core/types.js";
3
- /**
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.
6
- */
7
- export declare function runAuthAgent(sandboxFs: SandboxFS, hintFiles?: string[]): Promise<AuthSchema>;
@@ -1,212 +0,0 @@
1
- // ============================================================
2
- // @duct/sdk — Auth Agent
3
- // Analyzes auth configuration to produce AuthSchema
4
- // ============================================================
5
- import { callDuctLLM } from "./llm.js";
6
- // ----------------------------------------------------------------
7
- // Output schema description
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": "https://app.example.com/api/duct/token", // Optional: full URL for token generation
23
- "customClaims": {} // Optional: extra claims to include in tokens
24
- }
25
- `.trim();
26
- // ----------------------------------------------------------------
27
- // File candidates for each auth system
28
- // ----------------------------------------------------------------
29
- const AUTH_FILE_CANDIDATES = [
30
- // NextAuth
31
- "auth.ts",
32
- "auth.js",
33
- "auth.config.ts",
34
- "auth.config.js",
35
- "src/auth.ts",
36
- "src/auth.config.ts",
37
- "lib/auth.ts",
38
- "src/lib/auth.ts",
39
- "pages/api/auth/[...nextauth].ts",
40
- "pages/api/auth/[...nextauth].js",
41
- "app/api/auth/[...nextauth]/route.ts",
42
- "src/app/api/auth/[...nextauth]/route.ts",
43
- // Clerk
44
- "clerk.config.ts",
45
- "src/lib/clerk.ts",
46
- "lib/clerk.ts",
47
- // Auth0
48
- "lib/auth0.ts",
49
- "src/lib/auth0.ts",
50
- "pages/api/auth/[...auth0].ts",
51
- // Middleware (any framework)
52
- "middleware.ts",
53
- "middleware.js",
54
- "src/middleware.ts",
55
- "src/middleware.js",
56
- // Custom JWT
57
- "lib/jwt.ts",
58
- "src/lib/jwt.ts",
59
- "lib/token.ts",
60
- "src/lib/token.ts",
61
- "utils/auth.ts",
62
- "src/utils/auth.ts",
63
- // Iron session / session-cookie
64
- "lib/session.ts",
65
- "src/lib/session.ts",
66
- "lib/iron-session.ts",
67
- "src/lib/iron-session.ts",
68
- ];
69
- // ----------------------------------------------------------------
70
- // Prompt builder
71
- // ----------------------------------------------------------------
72
- async function buildAuthPrompt(sandboxFs, hintFiles) {
73
- const lines = [];
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
- }
88
- // Read package.json for deps
89
- const pkg = await sandboxFs.readJSON("package.json");
90
- if (pkg) {
91
- const allDeps = {
92
- ...(pkg.dependencies ?? {}),
93
- ...(pkg.devDependencies ?? {}),
94
- };
95
- const authDeps = Object.entries(allDeps)
96
- .filter(([name]) => name.includes("auth") ||
97
- name.includes("clerk") ||
98
- name.includes("jwt") ||
99
- name.includes("session") ||
100
- name.includes("iron") ||
101
- name.includes("passport"))
102
- .map(([name, version]) => `${name}@${version}`);
103
- if (authDeps.length > 0) {
104
- lines.push("## Auth-related dependencies:");
105
- for (const dep of authDeps) {
106
- lines.push(` - ${dep}`);
107
- }
108
- }
109
- }
110
- // Read auth config files
111
- let filesRead = 0;
112
- for (const candidate of AUTH_FILE_CANDIDATES) {
113
- if (filesRead >= 8)
114
- break;
115
- const content = await sandboxFs.readFile(candidate);
116
- if (content) {
117
- lines.push(`\n## ${candidate}:`);
118
- lines.push("```ts");
119
- lines.push(content.slice(0, 2000));
120
- lines.push("```");
121
- filesRead++;
122
- }
123
- }
124
- // Look for type definitions that describe the session
125
- const typeDirs = [
126
- "types",
127
- "src/types",
128
- "src/@types",
129
- "@types",
130
- ];
131
- for (const dir of typeDirs) {
132
- const exists = await sandboxFs.exists(dir);
133
- if (exists) {
134
- const files = await sandboxFs.findFiles(`${dir}/**/*.{ts,d.ts}`);
135
- for (const f of files.slice(0, 3)) {
136
- const content = await sandboxFs.readFile(f);
137
- if (content &&
138
- (content.includes("Session") ||
139
- content.includes("User") ||
140
- content.includes("Token"))) {
141
- lines.push(`\n## ${f} (type definitions):`);
142
- lines.push("```ts");
143
- lines.push(content.slice(0, 1500));
144
- lines.push("```");
145
- }
146
- }
147
- }
148
- }
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)
154
- 5. Suggest a token endpoint path if one should be created (default: /api/duct/token)`);
155
- return lines.join("\n");
156
- }
157
- // ----------------------------------------------------------------
158
- // runAuthAgent
159
- // ----------------------------------------------------------------
160
- /**
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.
163
- */
164
- export async function runAuthAgent(sandboxFs, hintFiles) {
165
- const prompt = await buildAuthPrompt(sandboxFs, hintFiles);
166
- const result = await callDuctLLM({
167
- agentName: "AuthAgent",
168
- systemPrompt: "You are an expert at analyzing authentication configurations in Next.js and React applications. " +
169
- "You understand NextAuth, Clerk, Auth0, custom JWT patterns, and session-cookie auth. " +
170
- "You produce structured auth schemas for the Duct platform.",
171
- userPrompt: prompt,
172
- outputSchema: AUTH_SCHEMA_SCHEMA,
173
- maxTokens: 2048,
174
- });
175
- const raw = result.parsed;
176
- // Sanitize and fill defaults
177
- const authSchema = {
178
- strategy: validateStrategy(raw.strategy),
179
- sessionFields: Array.isArray(raw.sessionFields)
180
- ? raw.sessionFields.filter((f) => typeof f === "string")
181
- : ["id", "email"],
182
- guestAllowed: raw.guestAllowed ?? true,
183
- tokenExpirySeconds: typeof raw.tokenExpirySeconds === "number"
184
- ? raw.tokenExpirySeconds
185
- : 300,
186
- ...(typeof raw.tokenEndpoint === "string" && raw.tokenEndpoint.trim()
187
- ? { tokenEndpoint: raw.tokenEndpoint.trim() }
188
- : {}),
189
- customClaims: typeof raw.customClaims === "object" && raw.customClaims !== null
190
- ? raw.customClaims
191
- : undefined,
192
- };
193
- return authSchema;
194
- }
195
- // ----------------------------------------------------------------
196
- // Helpers
197
- // ----------------------------------------------------------------
198
- function validateStrategy(strategy) {
199
- const valid = [
200
- "nextauth",
201
- "clerk",
202
- "auth0",
203
- "custom-jwt",
204
- "session-cookie",
205
- "none",
206
- "unknown",
207
- ];
208
- if (typeof strategy === "string" && valid.includes(strategy)) {
209
- return strategy;
210
- }
211
- return "unknown";
212
- }
@@ -1,6 +0,0 @@
1
- import type { RouteManifest, ActionManifest, DeeplinkDefinition } from "../../core/types.js";
2
- /**
3
- * Run the Deeplink Agent to propose DeeplinkDefinition[] from routes and actions.
4
- * Uses DeeplinkCandidateScorer to pre-filter routes before LLM call.
5
- */
6
- export declare function runDeeplinkAgent(routes: RouteManifest[], actions: ActionManifest[]): Promise<DeeplinkDefinition[]>;
@@ -1,285 +0,0 @@
1
- // ============================================================
2
- // @duct/sdk — Deeplink Agent
3
- // Proposes DeeplinkDefinition[] from routes and actions
4
- // ============================================================
5
- import { callDuctLLM } from "./llm.js";
6
- // ----------------------------------------------------------------
7
- // Output schema description
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
- ]
31
- `.trim();
32
- // ----------------------------------------------------------------
33
- // Prompt builder
34
- // ----------------------------------------------------------------
35
- function buildDeeplinkPrompt(routes, actions) {
36
- const lines = [];
37
- lines.push("Based on these routes and actions, propose useful deeplink targets for the Duct platform.\n");
38
- lines.push("## Available Routes:");
39
- for (const route of routes) {
40
- lines.push(`- ${route.path} — ${route.name} (${route.uiStateHint})`);
41
- if (route.description)
42
- lines.push(` Description: ${route.description}`);
43
- if (route.params.length > 0) {
44
- lines.push(` Path params: ${route.params.map((p) => p.name).join(", ")}`);
45
- }
46
- if (route.queryParams.length > 0) {
47
- lines.push(` Query params: ${route.queryParams.map((p) => p.name).join(", ")}`);
48
- }
49
- lines.push(` Requires auth: ${route.requiresAuth}, Deeplinkable: ${route.deeplinkable}`);
50
- }
51
- if (actions.length > 0) {
52
- lines.push("\n## Available Actions (API endpoints):");
53
- for (const action of actions.slice(0, 20)) {
54
- lines.push(`- ${action.id}: ${action.method} ${action.path} — ${action.description || action.name}`);
55
- }
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
-
81
- Target 3-10 deeplinks. Quality over quantity.`);
82
- return lines.join("\n");
83
- }
84
- // ----------------------------------------------------------------
85
- // StateFieldMapper
86
- // Maps deeplink stateFields to their session or action sources.
87
- // Called after LLM generation to auto-assign sessionSource.
88
- // ----------------------------------------------------------------
89
- const SESSION_FIELD_SOURCES = {
90
- userId: "user.id",
91
- id: "user.id",
92
- sub: "user.id",
93
- orgId: "user.orgId",
94
- organizationId: "user.orgId",
95
- email: "user.email",
96
- userEmail: "user.email",
97
- accountId: "user.id",
98
- tenantId: "user.orgId",
99
- };
100
- function mapStateFieldSources(fields, actionResponseFields) {
101
- return fields.map((field) => {
102
- // Skip if sessionSource is already set
103
- if (field.sessionSource)
104
- return field;
105
- // Check common session field mappings
106
- const sessionPath = SESSION_FIELD_SOURCES[field.key];
107
- if (sessionPath) {
108
- return { ...field, sessionSource: sessionPath };
109
- }
110
- // Check if an action response field covers this key
111
- const fromAction = actionResponseFields.get(field.key);
112
- if (fromAction) {
113
- // sessionSource not applicable — the value comes from action response, not session
114
- // Add a note in the description if not already there
115
- return {
116
- ...field,
117
- description: field.description
118
- ? field.description
119
- : `Value from ${fromAction} action response`,
120
- };
121
- }
122
- return field;
123
- });
124
- }
125
- /**
126
- * Score each (route, action) pair for deeplink worthiness.
127
- * Only routes with score >= 4 are passed to the LLM.
128
- *
129
- * Scoring:
130
- * +3 route.deeplinkable === true
131
- * +2 per route param that matches an action response field
132
- * +1 route.requiresAuth matches action.requiresAuth
133
- * +1 route.uiStateHint is 'detail' or 'form'
134
- */
135
- function scoreDeeplinkCandidates(routes, actions) {
136
- const scored = [];
137
- for (const route of routes) {
138
- // Collect all action response fields for matching
139
- let bestAction = null;
140
- let bestScore = 0;
141
- let bestReasons = [];
142
- // Try matching against each action, or score route alone
143
- const actionsToTry = actions.length > 0 ? actions : [null];
144
- for (const action of actionsToTry) {
145
- let score = 0;
146
- const reasons = [];
147
- if (route.deeplinkable) {
148
- score += 3;
149
- reasons.push("route is marked deeplinkable");
150
- }
151
- if (route.uiStateHint === "detail" || route.uiStateHint === "form") {
152
- score += 1;
153
- reasons.push(`UI hint is '${route.uiStateHint}'`);
154
- }
155
- if (action) {
156
- // Check param overlap with action response schema
157
- const responseProps = new Set(Object.keys(action.responseSchema?.properties ?? {}));
158
- for (const param of route.params) {
159
- const paramNorm = param.name.toLowerCase().replace(/_?id$/, "");
160
- const match = [...responseProps].some((k) => k.toLowerCase() === param.name.toLowerCase() || k.toLowerCase().includes(paramNorm));
161
- if (match) {
162
- score += 2;
163
- reasons.push(`param '${param.name}' matches action '${action.id}' response field`);
164
- }
165
- }
166
- if (route.requiresAuth === action.requiresAuth) {
167
- score += 1;
168
- reasons.push("auth requirements align");
169
- }
170
- }
171
- else {
172
- // Route with dynamic params even without action match
173
- if (route.params.length > 0) {
174
- score += 2;
175
- reasons.push(`has ${route.params.length} path param(s)`);
176
- }
177
- if (route.requiresAuth) {
178
- score += 1;
179
- reasons.push("is auth-gated (deeplink makes sense)");
180
- }
181
- }
182
- if (score > bestScore) {
183
- bestScore = score;
184
- bestAction = action;
185
- bestReasons = reasons;
186
- }
187
- }
188
- if (bestScore >= 4) {
189
- scored.push({ route, bestAction, score: bestScore, reasons: bestReasons });
190
- }
191
- }
192
- return scored.sort((a, b) => b.score - a.score);
193
- }
194
- // ----------------------------------------------------------------
195
- // runDeeplinkAgent
196
- // ----------------------------------------------------------------
197
- /**
198
- * Run the Deeplink Agent to propose DeeplinkDefinition[] from routes and actions.
199
- * Uses DeeplinkCandidateScorer to pre-filter routes before LLM call.
200
- */
201
- export async function runDeeplinkAgent(routes, actions) {
202
- // Score candidates — only routes with score >= 4 are passed to LLM
203
- const scored = scoreDeeplinkCandidates(routes, actions);
204
- const candidateRoutes = scored.length > 0
205
- ? scored.map((s) => s.route)
206
- : routes.filter((r) => r.deeplinkable || r.params.length > 0 || r.uiStateHint === "checkout");
207
- if (candidateRoutes.length === 0 && routes.length > 0) {
208
- // Use all routes if none are explicitly marked deeplinkable
209
- candidateRoutes.push(...routes.slice(0, 20));
210
- }
211
- const prompt = buildDeeplinkPrompt(candidateRoutes, actions);
212
- const result = await callDuctLLM({
213
- agentName: "DeeplinkAgent",
214
- systemPrompt: "You are an expert at designing deeplink architectures for web applications. " +
215
- "You understand how AI assistants should navigate users to specific application states. " +
216
- "You produce structured deeplink definitions for the Duct platform.",
217
- userPrompt: prompt,
218
- outputSchema: DEEPLINK_SCHEMA,
219
- maxTokens: 3000,
220
- });
221
- if (!Array.isArray(result.parsed)) {
222
- throw new Error(`DeeplinkAgent returned unexpected shape: expected array, got ${typeof result.parsed}`);
223
- }
224
- // Validate and sanitize
225
- const routePaths = new Set(routes.map((r) => r.path));
226
- // Build action response field index for StateFieldMapper
227
- const actionResponseFields = new Map(); // fieldKey → actionId
228
- for (const action of actions) {
229
- const props = action.responseSchema?.properties;
230
- if (props && typeof props === "object") {
231
- for (const key of Object.keys(props)) {
232
- if (!actionResponseFields.has(key)) {
233
- actionResponseFields.set(key, action.id);
234
- }
235
- }
236
- }
237
- }
238
- const normalizePath = (p) => p.replace(/\[([^\]]+)\]/g, ":$1");
239
- const deeplinks = result.parsed
240
- .filter((d) => {
241
- return (typeof d === "object" &&
242
- d !== null &&
243
- typeof d.id === "string" &&
244
- typeof d.targetRoute === "string");
245
- })
246
- .map((d) => ({
247
- id: d.id,
248
- name: d.name || d.id,
249
- description: d.description || "",
250
- targetRoute: d.targetRoute,
251
- stateFields: mapStateFieldSources(Array.isArray(d.stateFields) ? d.stateFields : [], actionResponseFields),
252
- expirySeconds: typeof d.expirySeconds === "number" ? d.expirySeconds : 300,
253
- requiresAuth: d.requiresAuth ?? true,
254
- intent: d.intent,
255
- }))
256
- .filter((d) => {
257
- // Validate target route exists (or normalize brackets)
258
- if (routePaths.has(d.targetRoute))
259
- return true;
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) };
284
- });
285
- }
@@ -1,33 +0,0 @@
1
- export interface LLMCallOptions {
2
- /** Agent name for logging */
3
- agentName: string;
4
- /** System prompt */
5
- systemPrompt: string;
6
- /** User prompt */
7
- userPrompt: string;
8
- /** Expected output JSON schema description */
9
- outputSchema: string;
10
- /** Max tokens for the response */
11
- maxTokens?: number;
12
- /** Max retry attempts */
13
- maxRetries?: number;
14
- }
15
- export interface LLMCallResult {
16
- text: string;
17
- parsed: unknown;
18
- inputTokens: number;
19
- outputTokens: number;
20
- }
21
- /**
22
- * Call an LLM for the Duct agent pipeline.
23
- *
24
- * Provider is resolved in this order:
25
- * 1. LLM_PROVIDER env var (explicit)
26
- * 2. First available API key: DUCT_API_KEY → ANTHROPIC_API_KEY → OPENAI_API_KEY
27
- * → GEMINI_API_KEY → GROQ_API_KEY → XAI_API_KEY (Grok) → OPENROUTER_API_KEY
28
- *
29
- * Model name is always taken from LLM_MODEL — never hardcoded.
30
- *
31
- * @throws {Error} If no API key or LLM_MODEL is configured
32
- */
33
- export declare function callDuctLLM(options: LLMCallOptions): Promise<LLMCallResult>;