@duct-sdk/sdk 0.5.13 → 0.7.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.
- package/CHANGELOG.md +61 -0
- package/README.md +418 -264
- package/TOKEN_SPEC.md +243 -243
- package/dist/cli/action-confusion-format.d.ts +17 -0
- package/dist/cli/action-confusion-format.js +24 -0
- package/dist/cli/add.d.ts +7 -0
- package/dist/cli/add.js +152 -0
- package/dist/cli/agent-prompt.d.ts +3 -0
- package/dist/cli/agent-prompt.js +39 -0
- package/dist/cli/api-sources.d.ts +26 -0
- package/dist/cli/api-sources.js +222 -0
- package/dist/cli/cloud.d.ts +162 -0
- package/dist/cli/cloud.js +306 -0
- package/dist/cli/config-loader.d.ts +14 -0
- package/dist/cli/config-loader.js +56 -7
- package/dist/cli/device-login.d.ts +17 -0
- package/dist/cli/device-login.js +75 -0
- package/dist/cli/drift.js +6 -6
- package/dist/cli/generators/any-stack.d.ts +3 -0
- package/dist/cli/generators/any-stack.js +97 -0
- package/dist/cli/generators/config.js +3 -2
- package/dist/cli/generators/receiver.js +7 -7
- package/dist/cli/generators/shell.js +12 -12
- package/dist/cli/generators/token-route.js +245 -245
- package/dist/cli/generators/wiring-snippets.d.ts +0 -14
- package/dist/cli/generators/wiring-snippets.js +188 -305
- package/dist/cli/index.js +396 -611
- package/dist/cli/mcp-core.d.ts +42 -0
- package/dist/cli/mcp-core.js +161 -0
- package/dist/cli/mcp-setup.d.ts +4 -0
- package/dist/cli/mcp-setup.js +352 -0
- package/dist/cli/mcp.d.ts +2 -0
- package/dist/cli/mcp.js +457 -0
- package/dist/cli/migrate-intershell.js +5 -5
- package/dist/cli/policy-defaults.d.ts +37 -0
- package/dist/cli/policy-defaults.js +127 -0
- package/dist/cli/policy-replay-format.d.ts +9 -0
- package/dist/cli/policy-replay-format.js +46 -0
- package/dist/cli/processors/integration-audit.js +2 -2
- package/dist/cli/processors/openapi-parser.d.ts +5 -0
- package/dist/cli/processors/openapi-parser.js +8 -3
- package/dist/cli/project-loader.d.ts +58 -0
- package/dist/cli/project-loader.js +198 -0
- package/dist/cli/project-writer.d.ts +23 -0
- package/dist/cli/project-writer.js +171 -0
- package/dist/cli/push.d.ts +43 -0
- package/dist/cli/push.js +308 -0
- package/dist/cli/safety-checks.d.ts +9 -0
- package/dist/cli/safety-checks.js +29 -0
- package/dist/cli/setup.d.ts +20 -0
- package/dist/cli/setup.js +349 -0
- package/dist/cli/shell-name.d.ts +8 -0
- package/dist/cli/shell-name.js +29 -0
- package/dist/cli/shells.d.ts +22 -0
- package/dist/cli/shells.js +122 -0
- package/dist/cli/split.d.ts +7 -0
- package/dist/cli/split.js +71 -0
- package/dist/cli/sync.d.ts +25 -0
- package/dist/cli/sync.js +120 -0
- package/dist/cli/test-runner.d.ts +21 -0
- package/dist/cli/test-runner.js +281 -0
- package/dist/core/compile.d.ts +43 -0
- package/dist/core/compile.js +512 -0
- package/dist/core/config.d.ts +538 -19
- package/dist/core/config.js +22 -14
- package/dist/core/login-handoff.d.ts +1 -1
- package/dist/core/login-handoff.js +1 -1
- package/dist/core/project.d.ts +1864 -0
- package/dist/core/project.js +291 -0
- package/dist/core/readiness-checks.js +2 -2
- package/dist/core/types.d.ts +10 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/project.d.ts +4 -0
- package/dist/project.js +8 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +1 -0
- package/package.json +94 -95
- package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
- package/dist/adapters/react/page-context-guard.test.js +0 -15
- package/dist/cli/agents/api-agent.d.ts +0 -22
- package/dist/cli/agents/api-agent.js +0 -761
- package/dist/cli/agents/auth-agent.d.ts +0 -7
- package/dist/cli/agents/auth-agent.js +0 -212
- package/dist/cli/agents/deeplink-agent.d.ts +0 -6
- package/dist/cli/agents/deeplink-agent.js +0 -285
- package/dist/cli/agents/llm.d.ts +0 -33
- package/dist/cli/agents/llm.js +0 -309
- package/dist/cli/agents/pipeline.d.ts +0 -72
- package/dist/cli/agents/pipeline.js +0 -421
- package/dist/cli/agents/reviewer-agent.d.ts +0 -13
- package/dist/cli/agents/reviewer-agent.js +0 -450
- package/dist/cli/agents/route-agent.d.ts +0 -17
- package/dist/cli/agents/route-agent.js +0 -383
- package/dist/cli/config-loader.test.d.ts +0 -1
- package/dist/cli/config-loader.test.js +0 -63
- package/dist/cli/detectors/topology.d.ts +0 -46
- package/dist/cli/detectors/topology.js +0 -417
- package/dist/cli/generators/config.test.d.ts +0 -1
- package/dist/cli/generators/config.test.js +0 -222
- package/dist/cli/generators/shell.test.d.ts +0 -1
- package/dist/cli/generators/shell.test.js +0 -73
- package/dist/cli/generators/token-route.test.d.ts +0 -1
- package/dist/cli/generators/token-route.test.js +0 -53
- package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
- package/dist/cli/generators/wiring-snippets.test.js +0 -80
- package/dist/cli/init.d.ts +0 -32
- package/dist/cli/init.js +0 -1336
- package/dist/cli/manifest-diff.test.d.ts +0 -1
- package/dist/cli/manifest-diff.test.js +0 -144
- package/dist/cli/processors/curl-parser.test.d.ts +0 -1
- package/dist/cli/processors/curl-parser.test.js +0 -24
- package/dist/cli/processors/integration-audit.test.d.ts +0 -1
- package/dist/cli/processors/integration-audit.test.js +0 -154
- package/dist/cli/processors/postprocess.d.ts +0 -22
- package/dist/cli/processors/postprocess.js +0 -107
- package/dist/cli/processors/prisma-parser.d.ts +0 -35
- package/dist/cli/processors/prisma-parser.js +0 -117
- package/dist/cli/processors/verify-discovery.d.ts +0 -33
- package/dist/cli/processors/verify-discovery.js +0 -193
- package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
- package/dist/cli/processors/verify-discovery.test.js +0 -153
- package/dist/cli/processors/zod-extractor.d.ts +0 -27
- package/dist/cli/processors/zod-extractor.js +0 -153
- package/dist/cli/prompts/review.d.ts +0 -61
- package/dist/cli/prompts/review.js +0 -410
- package/dist/cli/selectors/express.d.ts +0 -12
- package/dist/cli/selectors/express.js +0 -117
- package/dist/cli/selectors/fastapi.d.ts +0 -12
- package/dist/cli/selectors/fastapi.js +0 -122
- package/dist/cli/selectors/generic.d.ts +0 -10
- package/dist/cli/selectors/generic.js +0 -74
- package/dist/cli/selectors/index.d.ts +0 -37
- package/dist/cli/selectors/index.js +0 -315
- package/dist/cli/selectors/next.d.ts +0 -12
- package/dist/cli/selectors/next.js +0 -130
- package/dist/core/config-policy.test.d.ts +0 -1
- package/dist/core/config-policy.test.js +0 -101
- package/dist/core/config-roundtrip.test.d.ts +0 -1
- package/dist/core/config-roundtrip.test.js +0 -180
- package/dist/core/endpoint-guard.test.d.ts +0 -1
- package/dist/core/endpoint-guard.test.js +0 -57
- package/dist/core/env-diagnostics.test.d.ts +0 -1
- package/dist/core/env-diagnostics.test.js +0 -31
- package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
- package/dist/core/evidence-bundle.conformance.test.js +0 -110
- package/dist/core/evidence-bundle.test.d.ts +0 -1
- package/dist/core/evidence-bundle.test.js +0 -58
- package/dist/core/invariants.test.d.ts +0 -1
- package/dist/core/invariants.test.js +0 -217
- package/dist/core/login-handoff.test.d.ts +0 -1
- package/dist/core/login-handoff.test.js +0 -31
- package/dist/core/profile.test.d.ts +0 -1
- package/dist/core/profile.test.js +0 -95
- package/dist/core/readiness-checks.test.d.ts +0 -1
- package/dist/core/readiness-checks.test.js +0 -106
- package/dist/core/receipt.test.d.ts +0 -1
- package/dist/core/receipt.test.js +0 -75
- package/dist/core/sdk-entrypoint.test.d.ts +0 -1
- package/dist/core/sdk-entrypoint.test.js +0 -8
- package/dist/core/side-effects-review.test.d.ts +0 -1
- package/dist/core/side-effects-review.test.js +0 -28
- package/dist/core/token.conformance.test.d.ts +0 -1
- package/dist/core/token.conformance.test.js +0 -43
- package/dist/core/token.test.d.ts +0 -1
- package/dist/core/token.test.js +0 -66
|
@@ -1,761 +0,0 @@
|
|
|
1
|
-
// ============================================================
|
|
2
|
-
// @duct/sdk — API Agent
|
|
3
|
-
// Analyzes API routes/OpenAPI spec to produce ActionManifest[]
|
|
4
|
-
// ============================================================
|
|
5
|
-
import { callDuctLLM } from "./llm.js";
|
|
6
|
-
import { extractZodHintsFromFiles } from "../processors/zod-extractor.js";
|
|
7
|
-
import { parsePrismaSchema } from "../processors/prisma-parser.js";
|
|
8
|
-
import { normalizeEvidenceArray } from "../processors/verify-discovery.js";
|
|
9
|
-
const MAX_LISTED_FILES = 60;
|
|
10
|
-
const MAX_SNIPPET_FILES = 20;
|
|
11
|
-
const SNIPPET_SIZE = 1800;
|
|
12
|
-
// ── SvelteKit endpoint scanner ──────────────────────────────
|
|
13
|
-
class SvelteKitEndpointScanner {
|
|
14
|
-
name = "SvelteKitEndpoints";
|
|
15
|
-
async detect(fs) {
|
|
16
|
-
return ((await fs.exists("src/routes")) &&
|
|
17
|
-
((await fs.exists("svelte.config.js")) || (await fs.exists("svelte.config.ts"))));
|
|
18
|
-
}
|
|
19
|
-
async appendPromptContext(fs, lines) {
|
|
20
|
-
if (!(await fs.exists("src/routes")))
|
|
21
|
-
return;
|
|
22
|
-
lines.push("\n## SvelteKit API Endpoints: src/routes/**/*.server.ts");
|
|
23
|
-
const serverFiles = await fs.findFiles("src/routes/**/*.server.ts");
|
|
24
|
-
const endpointFiles = serverFiles.filter((f) => f.includes("+server."));
|
|
25
|
-
lines.push(`Found ${endpointFiles.length} +server.ts endpoint files:`);
|
|
26
|
-
for (const f of endpointFiles.slice(0, MAX_LISTED_FILES))
|
|
27
|
-
lines.push(` - ${f}`);
|
|
28
|
-
for (const f of endpointFiles.slice(0, MAX_SNIPPET_FILES)) {
|
|
29
|
-
const content = await fs.readFile(f);
|
|
30
|
-
if (!content)
|
|
31
|
-
continue;
|
|
32
|
-
lines.push(`\n### ${f}:`);
|
|
33
|
-
lines.push("```ts");
|
|
34
|
-
lines.push(content.slice(0, SNIPPET_SIZE));
|
|
35
|
-
lines.push("```");
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
// ── FastAPI scanner ─────────────────────────────────────────
|
|
40
|
-
class FastAPIScanner {
|
|
41
|
-
name = "FastAPI";
|
|
42
|
-
async detect(fs) {
|
|
43
|
-
// Check requirements.txt or pyproject.toml for "fastapi"
|
|
44
|
-
const reqTxt = await fs.readFile("requirements.txt");
|
|
45
|
-
if (reqTxt && /fastapi/i.test(reqTxt))
|
|
46
|
-
return true;
|
|
47
|
-
const pyproject = await fs.readFile("pyproject.toml");
|
|
48
|
-
if (pyproject && /fastapi/i.test(pyproject))
|
|
49
|
-
return true;
|
|
50
|
-
// Check for main.py / app.py / src/main.py with a FastAPI import
|
|
51
|
-
for (const candidate of ["main.py", "app.py", "src/main.py"]) {
|
|
52
|
-
const content = await fs.readFile(candidate);
|
|
53
|
-
if (content && /from fastapi/i.test(content))
|
|
54
|
-
return true;
|
|
55
|
-
}
|
|
56
|
-
return false;
|
|
57
|
-
}
|
|
58
|
-
async appendPromptContext(fs, lines) {
|
|
59
|
-
lines.push("\n## FastAPI Backend");
|
|
60
|
-
lines.push("Note: Python .py files are read directly — route decorators identify endpoints.");
|
|
61
|
-
// Find all Python source files
|
|
62
|
-
const pyFiles = await fs.findFiles("**/*.py");
|
|
63
|
-
lines.push(`Found ${pyFiles.length} Python files:`);
|
|
64
|
-
for (const f of pyFiles.slice(0, MAX_LISTED_FILES))
|
|
65
|
-
lines.push(` - ${f}`);
|
|
66
|
-
// Show files that contain route decorators with snippets
|
|
67
|
-
const routePattern = /@(app|router)\.(get|post|put|patch|delete)\s*\(/i;
|
|
68
|
-
const routeFiles = pyFiles;
|
|
69
|
-
lines.push("\n### FastAPI route definitions (files containing @app.get / @router.post etc.):");
|
|
70
|
-
let shownCount = 0;
|
|
71
|
-
for (const f of routeFiles.slice(0, MAX_SNIPPET_FILES)) {
|
|
72
|
-
const content = await fs.readFile(f);
|
|
73
|
-
if (!content)
|
|
74
|
-
continue;
|
|
75
|
-
if (!routePattern.test(content))
|
|
76
|
-
continue;
|
|
77
|
-
lines.push(`\n#### ${f}:`);
|
|
78
|
-
lines.push("```python");
|
|
79
|
-
lines.push(content.slice(0, SNIPPET_SIZE));
|
|
80
|
-
lines.push("```");
|
|
81
|
-
shownCount++;
|
|
82
|
-
if (shownCount >= 10)
|
|
83
|
-
break;
|
|
84
|
-
}
|
|
85
|
-
if (shownCount === 0) {
|
|
86
|
-
lines.push("(No files with route decorators found — check file listing above)");
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
// ── Django scanner ──────────────────────────────────────────
|
|
91
|
-
class DjangoScanner {
|
|
92
|
-
name = "Django";
|
|
93
|
-
async detect(fs) {
|
|
94
|
-
// Django projects always have manage.py at the root
|
|
95
|
-
if (await fs.exists("manage.py"))
|
|
96
|
-
return true;
|
|
97
|
-
// Or check requirements.txt / pyproject.toml for "django"
|
|
98
|
-
const reqTxt = await fs.readFile("requirements.txt");
|
|
99
|
-
if (reqTxt && /\bdjango\b/i.test(reqTxt))
|
|
100
|
-
return true;
|
|
101
|
-
const pyproject = await fs.readFile("pyproject.toml");
|
|
102
|
-
if (pyproject && /\bdjango\b/i.test(pyproject))
|
|
103
|
-
return true;
|
|
104
|
-
return false;
|
|
105
|
-
}
|
|
106
|
-
async appendPromptContext(fs, lines) {
|
|
107
|
-
lines.push("\n## Django Backend");
|
|
108
|
-
lines.push("Note: Python .py files are read directly — urls.py files define the URL routing.");
|
|
109
|
-
// urls.py files contain path(), re_path(), include() — these define the routes
|
|
110
|
-
const urlFiles = await fs.findFiles("**/urls.py");
|
|
111
|
-
lines.push(`\nFound ${urlFiles.length} urls.py files:`);
|
|
112
|
-
for (const f of urlFiles.slice(0, MAX_LISTED_FILES))
|
|
113
|
-
lines.push(` - ${f}`);
|
|
114
|
-
lines.push("\n### Django URL configurations:");
|
|
115
|
-
for (const f of urlFiles.slice(0, MAX_SNIPPET_FILES)) {
|
|
116
|
-
const content = await fs.readFile(f);
|
|
117
|
-
if (!content)
|
|
118
|
-
continue;
|
|
119
|
-
lines.push(`\n#### ${f}:`);
|
|
120
|
-
lines.push("```python");
|
|
121
|
-
lines.push(content.slice(0, SNIPPET_SIZE));
|
|
122
|
-
lines.push("```");
|
|
123
|
-
}
|
|
124
|
-
// views.py files contain the handler implementations
|
|
125
|
-
const viewFiles = await fs.findFiles("**/views.py");
|
|
126
|
-
lines.push(`\nFound ${viewFiles.length} views.py files:`);
|
|
127
|
-
for (const f of viewFiles.slice(0, MAX_LISTED_FILES))
|
|
128
|
-
lines.push(` - ${f}`);
|
|
129
|
-
lines.push("\n### Django view handlers:");
|
|
130
|
-
for (const f of viewFiles.slice(0, 8)) {
|
|
131
|
-
const content = await fs.readFile(f);
|
|
132
|
-
if (!content)
|
|
133
|
-
continue;
|
|
134
|
-
lines.push(`\n#### ${f}:`);
|
|
135
|
-
lines.push("```python");
|
|
136
|
-
lines.push(content.slice(0, SNIPPET_SIZE));
|
|
137
|
-
lines.push("```");
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
// ── Rails scanner ───────────────────────────────────────────
|
|
142
|
-
class RailsScanner {
|
|
143
|
-
name = "Rails";
|
|
144
|
-
async detect(fs) {
|
|
145
|
-
// Rails projects always have a Gemfile containing "rails"
|
|
146
|
-
const gemfile = await fs.readFile("Gemfile");
|
|
147
|
-
if (gemfile && /\brails\b/i.test(gemfile))
|
|
148
|
-
return true;
|
|
149
|
-
// Or config/routes.rb exists
|
|
150
|
-
if (await fs.exists("config/routes.rb"))
|
|
151
|
-
return true;
|
|
152
|
-
return false;
|
|
153
|
-
}
|
|
154
|
-
async appendPromptContext(fs, lines) {
|
|
155
|
-
lines.push("\n## Rails Backend");
|
|
156
|
-
lines.push("Note: Ruby .rb files are read directly — config/routes.rb is the primary route manifest.");
|
|
157
|
-
// config/routes.rb is the canonical Rails route definition file
|
|
158
|
-
const routesContent = await fs.readFile("config/routes.rb");
|
|
159
|
-
if (routesContent) {
|
|
160
|
-
lines.push("\n### config/routes.rb (primary route file):");
|
|
161
|
-
lines.push("```ruby");
|
|
162
|
-
lines.push(routesContent.slice(0, SNIPPET_SIZE * 2));
|
|
163
|
-
lines.push("```");
|
|
164
|
-
}
|
|
165
|
-
// Scan for any additional route files (engines, namespaced route files)
|
|
166
|
-
const routeFiles = await fs.findFiles("config/routes/**/*.rb");
|
|
167
|
-
if (routeFiles.length > 0) {
|
|
168
|
-
lines.push(`\nFound ${routeFiles.length} additional route files:`);
|
|
169
|
-
for (const f of routeFiles.slice(0, MAX_LISTED_FILES))
|
|
170
|
-
lines.push(` - ${f}`);
|
|
171
|
-
for (const f of routeFiles.slice(0, 6)) {
|
|
172
|
-
const content = await fs.readFile(f);
|
|
173
|
-
if (!content)
|
|
174
|
-
continue;
|
|
175
|
-
lines.push(`\n#### ${f}:`);
|
|
176
|
-
lines.push("```ruby");
|
|
177
|
-
lines.push(content.slice(0, SNIPPET_SIZE));
|
|
178
|
-
lines.push("```");
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
/** All API scanner strategies, applied in addition to Next.js/Express scanning. */
|
|
184
|
-
const API_SCANNER_STRATEGIES = [
|
|
185
|
-
new SvelteKitEndpointScanner(),
|
|
186
|
-
new FastAPIScanner(),
|
|
187
|
-
new DjangoScanner(),
|
|
188
|
-
new RailsScanner(),
|
|
189
|
-
];
|
|
190
|
-
// ----------------------------------------------------------------
|
|
191
|
-
// Output schema description
|
|
192
|
-
// ----------------------------------------------------------------
|
|
193
|
-
const ACTION_MANIFEST_SCHEMA = `
|
|
194
|
-
Array of ActionManifest objects:
|
|
195
|
-
[
|
|
196
|
-
{
|
|
197
|
-
"id": "get_orders", // snake_case unique ID
|
|
198
|
-
"name": "Get Orders", // Human-readable name
|
|
199
|
-
"description": "...", // What this action does
|
|
200
|
-
"method": "GET", // HTTP method: GET|POST|PUT|PATCH|DELETE
|
|
201
|
-
"path": "/api/orders", // API path
|
|
202
|
-
"agentAccessible": false, // ALWAYS false by default — developer enables this
|
|
203
|
-
"sideEffects": false, // true for POST/PUT/PATCH/DELETE
|
|
204
|
-
"sensitivityLevel": "low", // "none"|"low"|"medium"|"high"|"critical"
|
|
205
|
-
"params": [
|
|
206
|
-
{
|
|
207
|
-
"name": "page",
|
|
208
|
-
"type": "number", // "string"|"number"|"boolean"|"object"|"array"
|
|
209
|
-
"required": false,
|
|
210
|
-
"description": "Page number"
|
|
211
|
-
}
|
|
212
|
-
],
|
|
213
|
-
"requiresAuth": true,
|
|
214
|
-
"rateLimit": 60, // optional, requests per minute
|
|
215
|
-
"confidence": 0.95, // Detection confidence 0.0–1.0
|
|
216
|
-
"evidence": "app/api/orders/route.ts:12" // File:line where this endpoint was found
|
|
217
|
-
}
|
|
218
|
-
]
|
|
219
|
-
|
|
220
|
-
Confidence scoring rules:
|
|
221
|
-
- 1.0: explicit handler function with HTTP method decorator or export const GET/POST
|
|
222
|
-
- 0.85–0.99: clear route file, method obvious from file/export name
|
|
223
|
-
- 0.6–0.84: method inferred from surrounding code, path partially matched
|
|
224
|
-
- below 0.6: endpoint guessed from URL pattern or import, no direct handler found
|
|
225
|
-
`.trim();
|
|
226
|
-
// ----------------------------------------------------------------
|
|
227
|
-
// Prompt builders
|
|
228
|
-
// ----------------------------------------------------------------
|
|
229
|
-
async function buildOpenAPIPrompt(openApiContent, filePath) {
|
|
230
|
-
return `Analyze this OpenAPI specification and produce an ActionManifest array for all API endpoints.
|
|
231
|
-
|
|
232
|
-
## ${filePath}:
|
|
233
|
-
\`\`\`json
|
|
234
|
-
${openApiContent.slice(0, 8000)}
|
|
235
|
-
\`\`\`
|
|
236
|
-
|
|
237
|
-
For each endpoint:
|
|
238
|
-
- Use snake_case for the ID (e.g., GET /api/orders → "get_orders")
|
|
239
|
-
- Set agentAccessible: false (the developer will enable this manually for safe endpoints)
|
|
240
|
-
- Set sideEffects: true for POST, PUT, PATCH, DELETE
|
|
241
|
-
- Infer sensitivityLevel from the path/description (e.g., /payment → "high", /profile → "medium", /public → "none")
|
|
242
|
-
- Include all path/query/body parameters
|
|
243
|
-
|
|
244
|
-
STRICTNESS RULES:
|
|
245
|
-
- Do not invent operations that are not explicitly present in the OpenAPI spec.
|
|
246
|
-
- Keep method + path exactly as declared in the spec.
|
|
247
|
-
- Do not rename domain concepts (e.g., companies → products).
|
|
248
|
-
- If an operation is ambiguous or missing from the spec, omit it instead of guessing.`;
|
|
249
|
-
}
|
|
250
|
-
function rankApiFile(file) {
|
|
251
|
-
const normalized = file.replace(/\\/g, "/").toLowerCase();
|
|
252
|
-
let score = 0;
|
|
253
|
-
if (/\/(app|pages|src\/app|src\/pages)\/api\//.test(normalized))
|
|
254
|
-
score += 70;
|
|
255
|
-
if (/\/(server|src\/server|backend)\/routes\//.test(normalized))
|
|
256
|
-
score += 65;
|
|
257
|
-
if (/\/routes\//.test(normalized))
|
|
258
|
-
score += 55;
|
|
259
|
-
if (/\/(api|controllers?)\//.test(normalized))
|
|
260
|
-
score += 35;
|
|
261
|
-
if (/route\.(ts|tsx|js|jsx|mjs|cjs)$/.test(normalized))
|
|
262
|
-
score += 20;
|
|
263
|
-
if (/(auth|session|token|profile|user|resource|entity|webhook|crud)/.test(normalized))
|
|
264
|
-
score += 10;
|
|
265
|
-
if (/(\.spec\.|\.test\.|\.mock\.|__tests__|fixtures|examples?)/.test(normalized))
|
|
266
|
-
score -= 80;
|
|
267
|
-
if (/\/(dist|build|coverage|\.next|out)\//.test(normalized))
|
|
268
|
-
score -= 100;
|
|
269
|
-
return score;
|
|
270
|
-
}
|
|
271
|
-
function prioritizeApiFiles(files) {
|
|
272
|
-
return [...new Set(files)]
|
|
273
|
-
.sort((a, b) => {
|
|
274
|
-
const scoreDiff = rankApiFile(b) - rankApiFile(a);
|
|
275
|
-
if (scoreDiff !== 0)
|
|
276
|
-
return scoreDiff;
|
|
277
|
-
return a.localeCompare(b);
|
|
278
|
-
});
|
|
279
|
-
}
|
|
280
|
-
// Handler boundary patterns — lines that start a route handler definition
|
|
281
|
-
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*\()/;
|
|
282
|
-
/**
|
|
283
|
-
* Extract handler-level snippets from a source file.
|
|
284
|
-
* Finds export function / router.method() / FastAPI decorator boundaries
|
|
285
|
-
* and returns up to `maxHandlers` handlers, each capped at `charsPerHandler`.
|
|
286
|
-
* Falls back to simple prefix truncation when no boundaries are found.
|
|
287
|
-
*/
|
|
288
|
-
function extractHandlerSnippets(content, maxHandlers, charsPerHandler) {
|
|
289
|
-
const lines = content.split("\n");
|
|
290
|
-
const handlerStarts = [];
|
|
291
|
-
for (let i = 0; i < lines.length; i++) {
|
|
292
|
-
if (HANDLER_START_RE.test(lines[i].trimStart())) {
|
|
293
|
-
handlerStarts.push(i);
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
if (handlerStarts.length === 0) {
|
|
297
|
-
return content.slice(0, charsPerHandler * 3);
|
|
298
|
-
}
|
|
299
|
-
const snippets = [];
|
|
300
|
-
for (const start of handlerStarts.slice(0, maxHandlers)) {
|
|
301
|
-
const block = lines.slice(start).join("\n");
|
|
302
|
-
snippets.push(block.slice(0, charsPerHandler));
|
|
303
|
-
}
|
|
304
|
-
return snippets.join("\n\n// ───\n\n");
|
|
305
|
-
}
|
|
306
|
-
async function appendFileSnippets(lines, sandboxFs, files, maxFiles, snippetSize) {
|
|
307
|
-
for (const apiFile of files.slice(0, maxFiles)) {
|
|
308
|
-
const content = await sandboxFs.readFile(apiFile);
|
|
309
|
-
if (!content)
|
|
310
|
-
continue;
|
|
311
|
-
lines.push(`\n### ${apiFile}:`);
|
|
312
|
-
lines.push("```ts");
|
|
313
|
-
lines.push(extractHandlerSnippets(content, 15, snippetSize));
|
|
314
|
-
lines.push("```");
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
/**
|
|
318
|
-
* Detect monorepo-style subdirectory prefixes for API scanning.
|
|
319
|
-
* Returns prefixes like ["backend/", "server/", "api/"] where API code likely lives.
|
|
320
|
-
* Always includes "" (root) as a fallback.
|
|
321
|
-
*/
|
|
322
|
-
async function detectApiRoots(sandboxFs) {
|
|
323
|
-
// Known backend subdirectory names in monorepos
|
|
324
|
-
const backendCandidates = ["backend", "server", "api", "services/api", "apps/api", "packages/api"];
|
|
325
|
-
// Known frontend subdirectory names (Next.js fullstack — APIs live inside frontend)
|
|
326
|
-
const frontendCandidates = ["frontend", "web", "client", "app", "apps/web", "packages/web"];
|
|
327
|
-
const roots = [];
|
|
328
|
-
// Check for a dedicated backend directory with route-like files
|
|
329
|
-
for (const dir of backendCandidates) {
|
|
330
|
-
if (await sandboxFs.exists(dir)) {
|
|
331
|
-
const hasRoutes = (await sandboxFs.exists(`${dir}/routes`)) ||
|
|
332
|
-
(await sandboxFs.exists(`${dir}/src/routes`)) ||
|
|
333
|
-
(await sandboxFs.exists(`${dir}/api`)) ||
|
|
334
|
-
(await sandboxFs.findFiles(`${dir}/**/*.{ts,js}`)).length > 0;
|
|
335
|
-
if (hasRoutes)
|
|
336
|
-
roots.push(`${dir}/`);
|
|
337
|
-
}
|
|
338
|
-
}
|
|
339
|
-
// Check for a frontend directory with Next.js API routes (fullstack Next.js in subdirectory)
|
|
340
|
-
for (const dir of frontendCandidates) {
|
|
341
|
-
if (await sandboxFs.exists(dir)) {
|
|
342
|
-
const hasNextApi = (await sandboxFs.exists(`${dir}/app/api`)) ||
|
|
343
|
-
(await sandboxFs.exists(`${dir}/src/app/api`)) ||
|
|
344
|
-
(await sandboxFs.exists(`${dir}/pages/api`)) ||
|
|
345
|
-
(await sandboxFs.exists(`${dir}/src/pages/api`));
|
|
346
|
-
if (hasNextApi)
|
|
347
|
-
roots.push(`${dir}/`);
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
// Always scan root as well
|
|
351
|
-
roots.push("");
|
|
352
|
-
// Deduplicate while preserving order
|
|
353
|
-
return [...new Set(roots)];
|
|
354
|
-
}
|
|
355
|
-
async function buildFileSystemPrompt(sandboxFs, hintFiles, retryHint) {
|
|
356
|
-
const lines = [];
|
|
357
|
-
lines.push("Analyze these API route files and produce an ActionManifest array.\n");
|
|
358
|
-
lines.push("Only include endpoints that are explicitly backed by code evidence in the snippets below.");
|
|
359
|
-
lines.push("If evidence is missing or ambiguous, omit the action instead of guessing.\n");
|
|
360
|
-
// Inject Prisma model field names so the agent can map CRUD params accurately.
|
|
361
|
-
const prismaSchema = await sandboxFs.readFile("prisma/schema.prisma");
|
|
362
|
-
if (prismaSchema) {
|
|
363
|
-
const { annotation } = parsePrismaSchema(prismaSchema);
|
|
364
|
-
if (annotation) {
|
|
365
|
-
lines.push("## Prisma schema — use these field names for CRUD action params and inputSchema:");
|
|
366
|
-
lines.push(annotation);
|
|
367
|
-
lines.push("");
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
// Pre-extract Zod schemas from hint files so agents get structured param info.
|
|
371
|
-
// This eliminates guessing field types from raw source snippets.
|
|
372
|
-
if (hintFiles && hintFiles.length > 0) {
|
|
373
|
-
const zodHints = await extractZodHintsFromFiles((p) => sandboxFs.readFile(p), hintFiles);
|
|
374
|
-
if (zodHints.size > 0) {
|
|
375
|
-
lines.push("## Pre-extracted Zod schema hints (use these for accurate inputSchema):");
|
|
376
|
-
for (const hint of zodHints.values()) {
|
|
377
|
-
lines.push(hint.annotation);
|
|
378
|
-
}
|
|
379
|
-
lines.push("");
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
// If the selector pre-identified targeted API files, include them first.
|
|
383
|
-
if (hintFiles && hintFiles.length > 0) {
|
|
384
|
-
lines.push("## Targeted API files:");
|
|
385
|
-
for (const f of hintFiles.slice(0, 30)) {
|
|
386
|
-
const content = await sandboxFs.readFile(f);
|
|
387
|
-
if (!content)
|
|
388
|
-
continue;
|
|
389
|
-
lines.push(`\n### ${f}:`);
|
|
390
|
-
lines.push("```ts");
|
|
391
|
-
lines.push(extractHandlerSnippets(content, 15, SNIPPET_SIZE));
|
|
392
|
-
lines.push("```");
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
const apiRoots = await detectApiRoots(sandboxFs);
|
|
396
|
-
if (apiRoots.some((r) => r !== "")) {
|
|
397
|
-
lines.push(`Detected monorepo structure — scanning API roots: ${apiRoots.filter((r) => r !== "").join(", ")} plus project root.\n`);
|
|
398
|
-
}
|
|
399
|
-
// Next.js App Router API routes
|
|
400
|
-
const appApiDirs = apiRoots.flatMap((root) => [`${root}app/api`, `${root}src/app/api`]);
|
|
401
|
-
for (const dir of appApiDirs) {
|
|
402
|
-
const exists = await sandboxFs.exists(dir);
|
|
403
|
-
if (exists) {
|
|
404
|
-
lines.push(`\n## App Router API routes: ${dir}/`);
|
|
405
|
-
const files = prioritizeApiFiles(await sandboxFs.findFiles(`${dir}/**/route.{ts,tsx,js,jsx,mjs,cjs}`));
|
|
406
|
-
lines.push(`Found ${files.length} route handler files (ranked):`);
|
|
407
|
-
for (const f of files.slice(0, MAX_LISTED_FILES)) {
|
|
408
|
-
lines.push(` - ${f}`);
|
|
409
|
-
}
|
|
410
|
-
await appendFileSnippets(lines, sandboxFs, files, MAX_SNIPPET_FILES, SNIPPET_SIZE);
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
// Next.js Pages Router API routes
|
|
414
|
-
const pagesApiDirs = apiRoots.flatMap((root) => [`${root}pages/api`, `${root}src/pages/api`]);
|
|
415
|
-
for (const dir of pagesApiDirs) {
|
|
416
|
-
const exists = await sandboxFs.exists(dir);
|
|
417
|
-
if (exists) {
|
|
418
|
-
lines.push(`\n## Pages Router API routes: ${dir}/`);
|
|
419
|
-
const files = prioritizeApiFiles(await sandboxFs.findFiles(`${dir}/**/*.{ts,tsx,js,jsx,mjs,cjs}`));
|
|
420
|
-
lines.push(`Found ${files.length} API files (ranked):`);
|
|
421
|
-
for (const f of files.slice(0, MAX_LISTED_FILES)) {
|
|
422
|
-
lines.push(` - ${f}`);
|
|
423
|
-
}
|
|
424
|
-
await appendFileSnippets(lines, sandboxFs, files, MAX_SNIPPET_FILES, SNIPPET_SIZE);
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
// Express/Koa/Fastify style route directories — include backend/server roots from monorepo detection
|
|
428
|
-
const expressRouteDirs = [
|
|
429
|
-
...apiRoots.flatMap((root) => [
|
|
430
|
-
`${root}routes`,
|
|
431
|
-
`${root}src/routes`,
|
|
432
|
-
`${root}src/server/routes`,
|
|
433
|
-
`${root}api/routes`,
|
|
434
|
-
]),
|
|
435
|
-
// Legacy fallbacks always scanned
|
|
436
|
-
"server/routes",
|
|
437
|
-
"backend/routes",
|
|
438
|
-
"src/backend/routes",
|
|
439
|
-
].filter((v, i, arr) => arr.indexOf(v) === i); // deduplicate
|
|
440
|
-
for (const dir of expressRouteDirs) {
|
|
441
|
-
const exists = await sandboxFs.exists(dir);
|
|
442
|
-
if (exists) {
|
|
443
|
-
lines.push(`\n## Server route modules: ${dir}/`);
|
|
444
|
-
const files = prioritizeApiFiles(await sandboxFs.findFiles(`${dir}/**/*.{ts,tsx,js,jsx,mjs,cjs}`));
|
|
445
|
-
lines.push(`Found ${files.length} route module files (ranked):`);
|
|
446
|
-
for (const f of files.slice(0, MAX_LISTED_FILES)) {
|
|
447
|
-
lines.push(` - ${f}`);
|
|
448
|
-
}
|
|
449
|
-
await appendFileSnippets(lines, sandboxFs, files, MAX_SNIPPET_FILES, SNIPPET_SIZE);
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
// Server entrypoints for mounted base paths (e.g., app.use('/api/auth', authRoutes))
|
|
453
|
-
const serverEntrypoints = prioritizeApiFiles([
|
|
454
|
-
"server.ts",
|
|
455
|
-
"server.js",
|
|
456
|
-
"app.ts",
|
|
457
|
-
"app.js",
|
|
458
|
-
"index.ts",
|
|
459
|
-
"index.js",
|
|
460
|
-
"src/server.ts",
|
|
461
|
-
"src/server.js",
|
|
462
|
-
"src/app.ts",
|
|
463
|
-
"src/app.js",
|
|
464
|
-
"backend/server.ts",
|
|
465
|
-
"backend/server.js",
|
|
466
|
-
]);
|
|
467
|
-
const existingEntrypoints = [];
|
|
468
|
-
for (const file of serverEntrypoints) {
|
|
469
|
-
if (await sandboxFs.exists(file)) {
|
|
470
|
-
existingEntrypoints.push(file);
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
if (existingEntrypoints.length > 0) {
|
|
474
|
-
lines.push("\n## Server entrypoints (base route mount context):");
|
|
475
|
-
await appendFileSnippets(lines, sandboxFs, existingEntrypoints, 6, 2200);
|
|
476
|
-
}
|
|
477
|
-
// tRPC routers
|
|
478
|
-
const trpcCandidates = [
|
|
479
|
-
"src/server/routers",
|
|
480
|
-
"server/routers",
|
|
481
|
-
"src/trpc",
|
|
482
|
-
"src/server/trpc",
|
|
483
|
-
];
|
|
484
|
-
for (const dir of trpcCandidates) {
|
|
485
|
-
const exists = await sandboxFs.exists(dir);
|
|
486
|
-
if (exists) {
|
|
487
|
-
lines.push(`\n## tRPC routers: ${dir}/`);
|
|
488
|
-
const files = await sandboxFs.findFiles(`${dir}/**/*.{ts,js}`);
|
|
489
|
-
for (const f of files.slice(0, 8)) {
|
|
490
|
-
const content = await sandboxFs.readFile(f);
|
|
491
|
-
if (content) {
|
|
492
|
-
lines.push(`\n### ${f}:`);
|
|
493
|
-
lines.push("```ts");
|
|
494
|
-
lines.push(content.slice(0, 1500));
|
|
495
|
-
lines.push("```");
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
// ── Next.js route groups and path rewrites ─────────────────
|
|
501
|
-
// Read next.config.js/ts to extract rewrites() that map external paths to internal handlers.
|
|
502
|
-
const nextConfigCandidates = ["next.config.js", "next.config.ts", "next.config.mjs"];
|
|
503
|
-
for (const configFile of nextConfigCandidates) {
|
|
504
|
-
const content = await sandboxFs.readFile(configFile);
|
|
505
|
-
if (content) {
|
|
506
|
-
lines.push(`\n## Next.js config (rewrites / route groups): ${configFile}`);
|
|
507
|
-
lines.push("```js");
|
|
508
|
-
lines.push(content.slice(0, 3000));
|
|
509
|
-
lines.push("```");
|
|
510
|
-
lines.push("IMPORTANT: If this config contains rewrites(), map rewritten external paths to their internal handler paths." +
|
|
511
|
-
" Use the external (public-facing) path in the action manifest, not the internal implementation path." +
|
|
512
|
-
" Route groups like (app) or (api) in folder names are purely organizational — strip them from the final path." +
|
|
513
|
-
" E.g., app/(app)/api/invoices/route.ts produces path /api/invoices, not /(app)/api/invoices.");
|
|
514
|
-
break;
|
|
515
|
-
}
|
|
516
|
-
}
|
|
517
|
-
// Run additional framework-specific scanners
|
|
518
|
-
for (const strategy of API_SCANNER_STRATEGIES) {
|
|
519
|
-
if (await strategy.detect(sandboxFs)) {
|
|
520
|
-
await strategy.appendPromptContext(sandboxFs, lines);
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
lines.push(`\n\nFor each API endpoint:
|
|
524
|
-
- Derive the ID from the method + path in snake_case (e.g., GET /api/orders → "get_orders")
|
|
525
|
-
- Derive the path from explicit handler evidence (including base path mounts in server entrypoints)
|
|
526
|
-
- **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.
|
|
527
|
-
- Infer parameters from function signatures, TypeScript types, Zod/Yup schemas, and validation calls
|
|
528
|
-
- **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.
|
|
529
|
-
- **sideEffects**: true for POST/PUT/PATCH/DELETE methods
|
|
530
|
-
- **sensitivityLevel**: "high" for paths with password|secret|ssn|credit|billing; "medium" for email|phone|address|profile; "none"/"low" for public/read-only data
|
|
531
|
-
- **requiresAuth**: true if handler calls auth(), session(), getServerSession(), or requires a token
|
|
532
|
-
|
|
533
|
-
STRICTNESS RULES:
|
|
534
|
-
- Include an action only when you can point to an explicit HTTP method + path pattern in the shown code.
|
|
535
|
-
- Do not invent endpoints based on UI routes, naming assumptions, or business context.
|
|
536
|
-
- Do not rename domains (e.g., companies to products) unless the source code explicitly does so.
|
|
537
|
-
- Preserve method and path exactly as implemented (including :param style where used).
|
|
538
|
-
- Skip: _next/*, /api/auth/* (NextAuth internal), /api/duct/* (Duct's own routes).
|
|
539
|
-
- Strip Next.js route groups from paths: (app)/api/foo → /api/foo; (admin)/api/bar → /api/bar.
|
|
540
|
-
- Apply rewrites from next.config.js: use the public-facing destination path, not the source.
|
|
541
|
-
- If uncertain, omit the action.
|
|
542
|
-
|
|
543
|
-
DO NOT include Next.js internal routes or static assets.`);
|
|
544
|
-
if (retryHint) {
|
|
545
|
-
lines.push("");
|
|
546
|
-
lines.push(retryHint);
|
|
547
|
-
}
|
|
548
|
-
return lines.join("\n");
|
|
549
|
-
}
|
|
550
|
-
// ----------------------------------------------------------------
|
|
551
|
-
// runApiAgent
|
|
552
|
-
// ----------------------------------------------------------------
|
|
553
|
-
/**
|
|
554
|
-
* Run the API Agent to produce ActionManifest[] from the project's API layer.
|
|
555
|
-
*
|
|
556
|
-
* Priority:
|
|
557
|
-
* 1. inlineSpecContent — spec passed directly from --api-spec flag (skips all discovery)
|
|
558
|
-
* 2. openapi.json / openapi.yaml at known paths
|
|
559
|
-
* 3. Filesystem scan of API route handlers
|
|
560
|
-
*
|
|
561
|
-
* @param hintFiles - Optional pre-selected file paths from the file selector.
|
|
562
|
-
* @param inlineSpecContent - Raw spec content passed via --api-spec (bypasses sandbox lookup).
|
|
563
|
-
* @param inlineSpecPath - Display path for the inline spec (used in prompt context).
|
|
564
|
-
*/
|
|
565
|
-
export async function runApiAgent(sandboxFs, hintFiles, inlineSpecContent, inlineSpecPath, options) {
|
|
566
|
-
// If spec was passed directly (--api-spec flag), use it without further discovery
|
|
567
|
-
if (inlineSpecContent) {
|
|
568
|
-
const prompt = await buildOpenAPIPrompt(inlineSpecContent, inlineSpecPath ?? "openapi.json");
|
|
569
|
-
const result = await callDuctLLM({
|
|
570
|
-
agentName: "ApiAgent",
|
|
571
|
-
systemPrompt: "You are an expert at analyzing OpenAPI specifications and API route handlers. " +
|
|
572
|
-
"You produce structured action manifests that describe every API operation.",
|
|
573
|
-
userPrompt: prompt,
|
|
574
|
-
outputSchema: ACTION_MANIFEST_SCHEMA,
|
|
575
|
-
maxTokens: 4096,
|
|
576
|
-
});
|
|
577
|
-
if (Array.isArray(result.parsed)) {
|
|
578
|
-
return sanitizeActions(result.parsed);
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
// Check for OpenAPI spec first
|
|
582
|
-
const openApiCandidates = [
|
|
583
|
-
"openapi.json",
|
|
584
|
-
"openapi.yaml",
|
|
585
|
-
"openapi.yml",
|
|
586
|
-
"swagger.json",
|
|
587
|
-
"swagger.yaml",
|
|
588
|
-
"public/openapi.json",
|
|
589
|
-
"api-spec.json",
|
|
590
|
-
"api-spec.yaml",
|
|
591
|
-
".well-known/openapi.json",
|
|
592
|
-
];
|
|
593
|
-
for (const candidate of openApiCandidates) {
|
|
594
|
-
const content = await sandboxFs.readFile(candidate);
|
|
595
|
-
if (content) {
|
|
596
|
-
const prompt = await buildOpenAPIPrompt(content, candidate);
|
|
597
|
-
const result = await callDuctLLM({
|
|
598
|
-
agentName: "ApiAgent",
|
|
599
|
-
systemPrompt: "You are an expert at analyzing OpenAPI specifications and API route handlers. " +
|
|
600
|
-
"You produce structured action manifests that describe every API operation.",
|
|
601
|
-
userPrompt: prompt,
|
|
602
|
-
outputSchema: ACTION_MANIFEST_SCHEMA,
|
|
603
|
-
maxTokens: 4096,
|
|
604
|
-
});
|
|
605
|
-
if (Array.isArray(result.parsed)) {
|
|
606
|
-
return sanitizeActions(result.parsed);
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
// Fall back to filesystem scanning
|
|
611
|
-
const retryHint = options?.retry
|
|
612
|
-
? "RETRY: Your previous pass returned zero actions. Re-read every snippet and include each endpoint you can tie to an explicit HTTP method + path in the code."
|
|
613
|
-
: undefined;
|
|
614
|
-
const prompt = await buildFileSystemPrompt(sandboxFs, hintFiles, retryHint);
|
|
615
|
-
const result = await callDuctLLM({
|
|
616
|
-
agentName: "ApiAgent",
|
|
617
|
-
systemPrompt: "You are an expert at analyzing Next.js, Express, and tRPC API codebases. " +
|
|
618
|
-
"You produce structured action manifests that describe every API endpoint.",
|
|
619
|
-
userPrompt: prompt,
|
|
620
|
-
outputSchema: ACTION_MANIFEST_SCHEMA,
|
|
621
|
-
maxTokens: 4096,
|
|
622
|
-
});
|
|
623
|
-
if (!Array.isArray(result.parsed)) {
|
|
624
|
-
throw new Error(`ApiAgent returned unexpected shape: expected array, got ${typeof result.parsed}`);
|
|
625
|
-
}
|
|
626
|
-
return sanitizeActions(result.parsed);
|
|
627
|
-
}
|
|
628
|
-
// ----------------------------------------------------------------
|
|
629
|
-
// Sanitizer
|
|
630
|
-
// ----------------------------------------------------------------
|
|
631
|
-
function sanitizeActions(actions) {
|
|
632
|
-
const dedupe = new Set();
|
|
633
|
-
return actions
|
|
634
|
-
.filter((a) => {
|
|
635
|
-
return (typeof a === "object" &&
|
|
636
|
-
a !== null &&
|
|
637
|
-
typeof a.id === "string" &&
|
|
638
|
-
typeof a.path === "string");
|
|
639
|
-
})
|
|
640
|
-
.map((a) => {
|
|
641
|
-
const method = validateMethod(a.method);
|
|
642
|
-
const path = normalizeActionPath(a.path);
|
|
643
|
-
const sensitivityLevel = validateSensitivityLevel(a.sensitivityLevel);
|
|
644
|
-
const sideEffects = a.sideEffects ?? ["POST", "PUT", "PATCH", "DELETE"].includes(method);
|
|
645
|
-
// agentAccessible inference: safe defaults
|
|
646
|
-
const inferredAgentAccessible = method === "GET" &&
|
|
647
|
-
!sideEffects &&
|
|
648
|
-
sensitivityLevel !== "high" &&
|
|
649
|
-
sensitivityLevel !== "critical";
|
|
650
|
-
const agentAccessible = a.agentAccessible === true ? inferredAgentAccessible : false;
|
|
651
|
-
const evidence = normalizeEvidenceArray(a.evidence);
|
|
652
|
-
let confidence = typeof a.confidence === "number"
|
|
653
|
-
? Math.min(1, Math.max(0, a.confidence))
|
|
654
|
-
: undefined;
|
|
655
|
-
if (!isLikelyApiPath(path)) {
|
|
656
|
-
evidence.push("warning: path does not start with /api/ — verify action proxy target");
|
|
657
|
-
confidence = Math.min(confidence ?? 0.7, 0.65);
|
|
658
|
-
}
|
|
659
|
-
return {
|
|
660
|
-
id: toSnakeCase(a.id || path),
|
|
661
|
-
name: a.name || a.id,
|
|
662
|
-
description: a.description || "",
|
|
663
|
-
method,
|
|
664
|
-
path,
|
|
665
|
-
agentAccessible,
|
|
666
|
-
sideEffects,
|
|
667
|
-
sensitivityLevel,
|
|
668
|
-
params: sanitizeParams(a.params),
|
|
669
|
-
responseSchema: a.responseSchema,
|
|
670
|
-
inputSchema: a.inputSchema,
|
|
671
|
-
requiresAuth: a.requiresAuth ?? true,
|
|
672
|
-
rateLimit: a.rateLimit,
|
|
673
|
-
searchHint: a.searchHint,
|
|
674
|
-
...(confidence !== undefined ? { confidence } : {}),
|
|
675
|
-
...(evidence.length > 0 ? { evidence } : {}),
|
|
676
|
-
};
|
|
677
|
-
})
|
|
678
|
-
.filter((a) => !isInternalRoute(a.path))
|
|
679
|
-
.filter((a) => {
|
|
680
|
-
const key = `${a.method}:${a.path}`;
|
|
681
|
-
if (dedupe.has(key))
|
|
682
|
-
return false;
|
|
683
|
-
dedupe.add(key);
|
|
684
|
-
return true;
|
|
685
|
-
});
|
|
686
|
-
}
|
|
687
|
-
function normalizeActionPath(pathValue) {
|
|
688
|
-
const trimmed = pathValue.trim();
|
|
689
|
-
if (!trimmed)
|
|
690
|
-
return "/";
|
|
691
|
-
let normalized = trimmed.replace(/\\\\/g, "/");
|
|
692
|
-
if (!normalized.startsWith("/")) {
|
|
693
|
-
normalized = `/${normalized}`;
|
|
694
|
-
}
|
|
695
|
-
normalized = normalized.replace(/\/+/g, "/");
|
|
696
|
-
return normalized;
|
|
697
|
-
}
|
|
698
|
-
/** Skip internal routes that should never be exposed as Duct actions. */
|
|
699
|
-
function isInternalRoute(pathValue) {
|
|
700
|
-
const p = pathValue.toLowerCase();
|
|
701
|
-
return (p.startsWith("/api/auth/") || // NextAuth internal
|
|
702
|
-
p.startsWith("/api/duct/") || // Duct's own receiver routes
|
|
703
|
-
p.startsWith("/_next/") || // Next.js internals
|
|
704
|
-
p === "/_next" ||
|
|
705
|
-
p.startsWith("/api/_") || // underscore-prefixed internal
|
|
706
|
-
false);
|
|
707
|
-
}
|
|
708
|
-
function isLikelyApiPath(pathValue) {
|
|
709
|
-
if (!pathValue.startsWith("/"))
|
|
710
|
-
return false;
|
|
711
|
-
if (/\s/.test(pathValue))
|
|
712
|
-
return false;
|
|
713
|
-
if (!/^[\w\-./:[\]{}]+$/.test(pathValue))
|
|
714
|
-
return false;
|
|
715
|
-
const normalized = pathValue.toLowerCase();
|
|
716
|
-
return normalized.startsWith("/api/") || normalized === "/api";
|
|
717
|
-
}
|
|
718
|
-
function sanitizeParams(params) {
|
|
719
|
-
if (!Array.isArray(params))
|
|
720
|
-
return [];
|
|
721
|
-
return params
|
|
722
|
-
.filter((param) => {
|
|
723
|
-
return (typeof param === "object" &&
|
|
724
|
-
param !== null &&
|
|
725
|
-
typeof param.name === "string" &&
|
|
726
|
-
param.name.trim().length > 0);
|
|
727
|
-
})
|
|
728
|
-
.map((param) => ({
|
|
729
|
-
name: param.name.trim(),
|
|
730
|
-
type: ["string", "number", "boolean", "object", "array"].includes(param.type)
|
|
731
|
-
? param.type
|
|
732
|
-
: "string",
|
|
733
|
-
required: Boolean(param.required),
|
|
734
|
-
description: param.description,
|
|
735
|
-
schema: param.schema,
|
|
736
|
-
}));
|
|
737
|
-
}
|
|
738
|
-
function validateSensitivityLevel(value) {
|
|
739
|
-
if (value === "none" ||
|
|
740
|
-
value === "low" ||
|
|
741
|
-
value === "medium" ||
|
|
742
|
-
value === "high" ||
|
|
743
|
-
value === "critical") {
|
|
744
|
-
return value;
|
|
745
|
-
}
|
|
746
|
-
return "low";
|
|
747
|
-
}
|
|
748
|
-
function toSnakeCase(str) {
|
|
749
|
-
return str
|
|
750
|
-
.toLowerCase()
|
|
751
|
-
.replace(/[^a-z0-9]/g, "_")
|
|
752
|
-
.replace(/_+/g, "_")
|
|
753
|
-
.replace(/^_|_$/g, "");
|
|
754
|
-
}
|
|
755
|
-
function validateMethod(method) {
|
|
756
|
-
const upper = (method || "GET").toUpperCase();
|
|
757
|
-
if (["GET", "POST", "PUT", "PATCH", "DELETE"].includes(upper)) {
|
|
758
|
-
return upper;
|
|
759
|
-
}
|
|
760
|
-
return "GET";
|
|
761
|
-
}
|