@duct-sdk/sdk 0.1.13 → 0.2.2

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/dist/cli/index.js CHANGED
@@ -324,7 +324,7 @@ program
324
324
  process.exit(1);
325
325
  }
326
326
  });
327
- // Mirror of buildDependsOnPlan() in services/shell-runtime/app/api/chat/route.ts — keep in sync.
327
+ // Topological order for action dependsOn chains (max depth 4).
328
328
  function buildDependsOnOrder(targetId, actions, visited = new Set()) {
329
329
  if (visited.has(targetId) || visited.size > 4)
330
330
  return [];
@@ -457,7 +457,7 @@ program
457
457
  console.log(chalk.gray(` • ${wf.name} (${stepNames})`));
458
458
  }
459
459
  console.log();
460
- // Embed into the manifest so agent-proxy stores them alongside actions
460
+ // Embed into the manifest so Duct stores them alongside actions
461
461
  config = { ...config, precomputedWorkflows };
462
462
  }
463
463
  const pushSpinner = ora("Pushing to Duct cloud...").start();
@@ -532,6 +532,13 @@ program
532
532
  process.exit(1);
533
533
  }
534
534
  pushSpinner.succeed(`Manifest synced for shell: ${chalk.cyan(shellId)}`);
535
+ // Keep .duct-manifest.json in sync so `duct scan --manifest-diff` always
536
+ // diffs against what was actually last pushed, not just what `duct init` wrote.
537
+ try {
538
+ const snapshotPath = path.resolve(cwd, ".duct-manifest.json");
539
+ await fs.writeFile(snapshotPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
540
+ }
541
+ catch { /* non-fatal — snapshot is a local convenience file */ }
535
542
  console.log(chalk.green("\n ◆ Manifest synced\n"));
536
543
  }
537
544
  catch (err) {
@@ -605,7 +612,7 @@ program
605
612
  console.log(chalk.gray(` Credentials saved to ${DUCT_AUTH_FILE} (mode 600)\n`));
606
613
  console.log(chalk.yellow(` ⚠ Keep this file private — it contains your API key.\n Add ${DUCT_AUTH_FILE} to your global .gitignore.\n`));
607
614
  // Best-effort: fetch and display provisioned shells for this account.
608
- // Account/identity endpoints live on the auth service, NOT agent-proxy.
615
+ // Account/identity endpoints use the auth base URL, not the API base URL.
609
616
  try {
610
617
  const authBase = getActiveAuthBase(auth);
611
618
  const shellsRes = await fetch(`${authBase}/v1/account/shells`, {
@@ -1069,6 +1076,137 @@ program
1069
1076
  }
1070
1077
  });
1071
1078
  // ----------------------------------------------------------------
1079
+ // duct promote --from <source> --to <target>
1080
+ // Copies the live manifest of the source shell to the target shell,
1081
+ // implementing the dev → staging → production promotion workflow.
1082
+ // ----------------------------------------------------------------
1083
+ program
1084
+ .command("promote")
1085
+ .description("Promote the live manifest of one shell to another (e.g. dev → prod)")
1086
+ .requiredOption("--from <shellId>", "Source shell ID to promote from")
1087
+ .requiredOption("--to <shellId>", "Target shell ID to promote to")
1088
+ .option("--yes", "Skip confirmation prompt", false)
1089
+ .action(async (opts) => {
1090
+ const spinner = ora("Authenticating…").start();
1091
+ try {
1092
+ // Load API key
1093
+ let apiKey = process.env["DUCT_API_KEY"];
1094
+ if (!apiKey) {
1095
+ const auth = await readAuth();
1096
+ apiKey = auth?.token;
1097
+ }
1098
+ if (!apiKey) {
1099
+ spinner.fail("Not logged in");
1100
+ console.log(chalk.yellow("\nRun `npx duct login` first.\n"));
1101
+ process.exit(1);
1102
+ }
1103
+ const auth = await readAuth();
1104
+ const manifestBases = getManifestApiBases(auth);
1105
+ // ── Step 1: Fetch source manifest ─────────────────────────
1106
+ spinner.text = `Fetching manifest from ${chalk.cyan(opts.from)}…`;
1107
+ let sourceManifest = null;
1108
+ for (const base of manifestBases) {
1109
+ const res = await fetch(`${base}/v1/shells/${opts.from}/manifest`, {
1110
+ method: "GET",
1111
+ headers: { Authorization: `Bearer ${apiKey}` },
1112
+ });
1113
+ if (res.ok) {
1114
+ const data = (await res.json());
1115
+ sourceManifest = (data.manifest ?? null);
1116
+ if (sourceManifest)
1117
+ break;
1118
+ }
1119
+ if (res.status === 404)
1120
+ continue;
1121
+ const body = await res.text();
1122
+ spinner.fail(`Failed to fetch source manifest`);
1123
+ console.error(chalk.red(`\n ${res.status} at ${base}: ${body}\n`));
1124
+ process.exit(1);
1125
+ }
1126
+ if (!sourceManifest) {
1127
+ spinner.fail(`Shell '${opts.from}' not found or has no manifest`);
1128
+ process.exit(1);
1129
+ }
1130
+ const actionCount = Array.isArray(sourceManifest["actions"])
1131
+ ? sourceManifest["actions"].length
1132
+ : 0;
1133
+ spinner.succeed(`Fetched manifest from ${chalk.cyan(opts.from)} (${actionCount} action${actionCount === 1 ? "" : "s"})`);
1134
+ // ── Step 2: Confirmation ───────────────────────────────────
1135
+ console.log(chalk.dim(`\n Promoting: ${chalk.cyan(opts.from)} → ${chalk.cyan(opts.to)}\n`));
1136
+ if (!opts.yes) {
1137
+ const { confirm } = await inquirer.prompt([
1138
+ {
1139
+ type: "confirm",
1140
+ name: "confirm",
1141
+ message: chalk.yellow(`Push the ${chalk.bold(opts.from)} manifest (${actionCount} actions) to ${chalk.bold(opts.to)}?`),
1142
+ default: false,
1143
+ },
1144
+ ]);
1145
+ if (!confirm) {
1146
+ console.log(chalk.gray("\nPromotion cancelled.\n"));
1147
+ process.exit(0);
1148
+ }
1149
+ }
1150
+ // ── Step 3: Push to target ─────────────────────────────────
1151
+ const pushSpinner = ora(`Pushing to ${chalk.cyan(opts.to)}…`).start();
1152
+ // Rewrite shellId in the manifest to match the target
1153
+ const promotedManifest = {
1154
+ ...sourceManifest,
1155
+ shellId: opts.to,
1156
+ };
1157
+ let pushed = false;
1158
+ let pushError = "";
1159
+ let pushHash = "";
1160
+ let pushChecksum = "";
1161
+ for (const base of manifestBases) {
1162
+ const res = await fetch(`${base}/v1/shells/${opts.to}/manifest`, {
1163
+ method: "PUT",
1164
+ headers: {
1165
+ "Content-Type": "application/json",
1166
+ Authorization: `Bearer ${apiKey}`,
1167
+ },
1168
+ body: JSON.stringify({ config: promotedManifest }),
1169
+ });
1170
+ if (res.ok) {
1171
+ const data = (await res.json());
1172
+ pushed = true;
1173
+ pushHash = data.push_hash ?? "";
1174
+ pushChecksum = (data.config_checksum ?? "").slice(0, 7);
1175
+ break;
1176
+ }
1177
+ const body = await res.text();
1178
+ pushError = `${res.status} at ${base}: ${body}`;
1179
+ if (res.status === 404)
1180
+ continue;
1181
+ break;
1182
+ }
1183
+ if (!pushed) {
1184
+ pushSpinner.fail(`Promote failed`);
1185
+ console.error(chalk.red(`\n${pushError || "No manifest API responded"}\n`));
1186
+ process.exit(1);
1187
+ }
1188
+ pushSpinner.succeed(`Manifest pushed to ${chalk.cyan(opts.to)}`);
1189
+ console.log(chalk.green("\n ◆ Promotion complete\n"));
1190
+ if (pushHash)
1191
+ console.log(chalk.dim(` Hash: ${chalk.cyan(pushHash)}`));
1192
+ if (pushChecksum)
1193
+ console.log(chalk.dim(` Checksum: ${pushChecksum}`));
1194
+ console.log(chalk.dim(`\n Tip: Run \`npx duct scan --shell-id ${opts.to}\` to verify the promoted shell.\n`));
1195
+ // Persist promoted manifest locally as snapshot so --update diffs correctly
1196
+ try {
1197
+ const snapshotPath = path.resolve(process.cwd(), ".duct-manifest.json");
1198
+ await fs.writeFile(snapshotPath, JSON.stringify(promotedManifest, null, 2) + "\n", "utf-8");
1199
+ }
1200
+ catch { /* non-fatal — snapshot is a local convenience */ }
1201
+ }
1202
+ catch (err) {
1203
+ spinner.fail("Promotion failed");
1204
+ const message = err instanceof Error ? err.message : String(err);
1205
+ console.error(chalk.red(`\nError: ${message}\n`));
1206
+ process.exit(1);
1207
+ }
1208
+ });
1209
+ // ----------------------------------------------------------------
1072
1210
  // Error handling
1073
1211
  // ----------------------------------------------------------------
1074
1212
  program.exitOverride();
package/dist/cli/init.js CHANGED
@@ -42,7 +42,7 @@ async function loadAuth() {
42
42
  * Fetch the company's provisioned shells from the Duct auth service.
43
43
  *
44
44
  * Account/identity endpoints live on the auth service (port 3001 locally,
45
- * auth.<host> in prod), NOT on the agent-proxy. Calling the wrong service
45
+ * auth.<host> in prod), NOT the API host. Calling the wrong base URL
46
46
  * was the root cause of a "No shells provisioned" false negative bug.
47
47
  */
48
48
  async function fetchAccountShells(apiKey, authBase) {
@@ -585,10 +585,9 @@ export async function runInit(opts = {}) {
585
585
  }
586
586
  console.log(chalk.gray(` Authenticated as ${auth.email} (${auth.slug})\n`));
587
587
  // Use saved auth endpoints (or production defaults).
588
- // Account/identity endpoints live on the auth service, not agent-proxy.
588
+ // Account/identity endpoints use the auth base URL.
589
589
  const ductAuthBase = getActiveAuthBase(auth);
590
590
  // Fetch company's provisioned shells from the auth service.
591
- // (Account/identity endpoints live on auth, not on agent-proxy.)
592
591
  let accountShells;
593
592
  try {
594
593
  accountShells = await fetchAccountShells(auth.token, ductAuthBase);
@@ -30,3 +30,28 @@ export interface ReviewedPipelineResult {
30
30
  * - `--no-interactive`: write unresolved decisions to duct-review.json
31
31
  */
32
32
  export declare function runInteractiveReview(pipelineResult: PipelineResult, opts?: ReviewOptions): Promise<ReviewedPipelineResult>;
33
+ export interface InteractiveReviewOptions {
34
+ /** Auto-approve everything (--yes / CI mode) */
35
+ yes: boolean;
36
+ /** Write manifest to duct-review.json instead of prompting (--no-interactive) */
37
+ noInteractive: boolean;
38
+ /** Working directory for writing duct-review.json (defaults to cwd) */
39
+ cwd?: string;
40
+ }
41
+ /**
42
+ * Interactive review for a generated manifest.
43
+ *
44
+ * Decision rules:
45
+ * - `options.yes` → return manifest unchanged, all actions approved
46
+ * - `options.noInteractive` → write to duct-review.json, return manifest unchanged
47
+ * - Otherwise:
48
+ * - GET + confidence ≥ 0.85 → auto-approve (prints "✓ Auto-approved: [id]")
49
+ * - POST / DELETE / PATCH / PUT → always prompt
50
+ * - confidence < 0.85 → prompt regardless of method
51
+ * - Shows evidence: "Detected from: [files]"
52
+ *
53
+ * @param manifest The generated DuctConfig-like manifest (any shape, operates on .actions[])
54
+ * @param options Review mode flags
55
+ * @returns The manifest with only approved actions
56
+ */
57
+ export declare function interactiveReview(manifest: any, options: InteractiveReviewOptions): Promise<any>;
@@ -45,7 +45,9 @@ function requiresPrompt(action) {
45
45
  // ----------------------------------------------------------------
46
46
  async function promptActionDecision(action, rl) {
47
47
  const confidence = action.confidence ?? 0;
48
- const evidence = action.evidence ?? "unknown source";
48
+ const evidence = Array.isArray(action.evidence)
49
+ ? action.evidence.join(", ")
50
+ : (action.evidence ?? "unknown source");
49
51
  const method = methodColor(action.method);
50
52
  const conf = confidenceColor(confidence);
51
53
  const isSideEffect = action.sideEffects ||
@@ -136,7 +138,7 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
136
138
  method: action.method,
137
139
  path: action.path,
138
140
  confidence: action.confidence ?? 0,
139
- evidence: action.evidence,
141
+ evidence: Array.isArray(action.evidence) ? action.evidence.join(", ") : action.evidence,
140
142
  reason: requiresPrompt(action)
141
143
  ? "Requires human review: side-effect or low confidence"
142
144
  : "Pending",
@@ -238,3 +240,107 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
238
240
  rejectedActions,
239
241
  };
240
242
  }
243
+ /**
244
+ * Interactive review for a generated manifest.
245
+ *
246
+ * Decision rules:
247
+ * - `options.yes` → return manifest unchanged, all actions approved
248
+ * - `options.noInteractive` → write to duct-review.json, return manifest unchanged
249
+ * - Otherwise:
250
+ * - GET + confidence ≥ 0.85 → auto-approve (prints "✓ Auto-approved: [id]")
251
+ * - POST / DELETE / PATCH / PUT → always prompt
252
+ * - confidence < 0.85 → prompt regardless of method
253
+ * - Shows evidence: "Detected from: [files]"
254
+ *
255
+ * @param manifest The generated DuctConfig-like manifest (any shape, operates on .actions[])
256
+ * @param options Review mode flags
257
+ * @returns The manifest with only approved actions
258
+ */
259
+ export async function interactiveReview(
260
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
261
+ manifest, options
262
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
263
+ ) {
264
+ const { yes, noInteractive, cwd = process.cwd() } = options;
265
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
266
+ const actions = Array.isArray(manifest?.actions) ? manifest.actions : [];
267
+ // ── --yes mode: return unchanged ─────────────────────────────
268
+ if (yes) {
269
+ return manifest;
270
+ }
271
+ // ── --no-interactive: write to duct-review.json ──────────────
272
+ if (noInteractive) {
273
+ const reviewContent = {
274
+ generatedAt: new Date().toISOString(),
275
+ pendingDecisions: actions
276
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
277
+ .filter((a) => {
278
+ const isSideEffect = ["POST", "PUT", "PATCH", "DELETE"].includes(a.method ?? "");
279
+ const lowConfidence = (a.confidence ?? 0) < 0.85;
280
+ return isSideEffect || lowConfidence;
281
+ })
282
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
283
+ .map((a) => ({
284
+ id: a.id,
285
+ method: a.method,
286
+ path: a.path,
287
+ confidence: a.confidence ?? 0,
288
+ evidence: Array.isArray(a.evidence) ? a.evidence.join(", ") : (a.evidence ?? ""),
289
+ reason: ["POST", "PUT", "PATCH", "DELETE"].includes(a.method ?? "")
290
+ ? "Side-effect action requires review"
291
+ : "Low confidence detection",
292
+ })),
293
+ instructions: "Review each entry. Set `approved: true` for actions to include. Re-run `npx duct init` to apply.",
294
+ };
295
+ const reviewFilePath = path.join(cwd, "duct-review.json");
296
+ await fs.writeFile(reviewFilePath, JSON.stringify(reviewContent, null, 2) + "\n", "utf-8");
297
+ console.log(chalk.yellow(`\n [DUCT] --no-interactive: wrote ${reviewContent.pendingDecisions.length} pending decisions to duct-review.json\n`));
298
+ return manifest;
299
+ }
300
+ // ── Interactive mode ─────────────────────────────────────────
301
+ const approved = [];
302
+ const rl = readline.createInterface({
303
+ input: process.stdin,
304
+ output: process.stdout,
305
+ terminal: false,
306
+ });
307
+ for (const action of actions) {
308
+ const method = action.method ?? "GET";
309
+ const confidence = action.confidence ?? 0;
310
+ const isSafeGet = method === "GET" && confidence >= 0.85;
311
+ const isSideEffect = ["POST", "PUT", "PATCH", "DELETE"].includes(method);
312
+ if (isSafeGet) {
313
+ approved.push(action);
314
+ process.stdout.write(chalk.green(` ✓ Auto-approved: `) +
315
+ chalk.cyan(`[${action.id ?? action.path}]`) +
316
+ chalk.gray(` ${method} ${action.path ?? ""} ${Math.round(confidence * 100)}%\n`));
317
+ continue;
318
+ }
319
+ // Must prompt
320
+ const evidenceStr = Array.isArray(action.evidence)
321
+ ? action.evidence.join(", ")
322
+ : (action.evidence ?? "unknown source");
323
+ const reason = isSideEffect
324
+ ? "side-effect action"
325
+ : `confidence ${Math.round(confidence * 100)}% < 85%`;
326
+ process.stdout.write(`\n ${chalk.bold("[DUCT]")} ${methodColor(method)} ${chalk.cyan(action.path ?? "")} — ${reason}\n` +
327
+ ` ${chalk.gray(`Confidence: ${confidenceColor(confidence)}`)}\n` +
328
+ ` ${chalk.gray(`Detected from: ${chalk.dim(evidenceStr)}`)}\n` +
329
+ ` ${chalk.gray(`Include action '${action.id ?? action.path}'` +
330
+ (action.description ? ` (${String(action.description).slice(0, 60)})` : "") +
331
+ `? [y/N]: `)}`);
332
+ const answer = await new Promise((resolve) => {
333
+ rl.once("line", (line) => resolve(line.trim().toLowerCase()));
334
+ });
335
+ if (answer === "y" || answer === "yes") {
336
+ approved.push(action);
337
+ console.log(chalk.green(` ✓ Included: ${action.id ?? action.path}`));
338
+ }
339
+ else {
340
+ console.log(chalk.gray(` — Excluded: ${action.id ?? action.path}`));
341
+ }
342
+ }
343
+ rl.close();
344
+ console.log(chalk.bold(`\n Review complete: ${approved.length}/${actions.length} actions included\n`));
345
+ return { ...manifest, actions: approved };
346
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Select files for Express / Fastify / Koa projects.
3
+ *
4
+ * Priority:
5
+ * 1. Route files: routes/...ts, src/routes/...ts
6
+ * 2. Middleware: middleware/...ts, src/middleware/...ts
7
+ * 3. Entry points: src/index.ts, index.ts, app.ts, server.ts
8
+ *
9
+ * @param projectRoot Absolute project root path
10
+ * @param maxFiles Maximum total files to return (default 30)
11
+ */
12
+ export declare function selectExpressFiles(projectRoot: string, maxFiles?: number): Promise<string[]>;
@@ -0,0 +1,117 @@
1
+ // ============================================================
2
+ // @duct/sdk — Express / Fastify File Selector
3
+ // Selects route files, middleware, and entry points for Express-like projects.
4
+ // ============================================================
5
+ import * as fs from "fs/promises";
6
+ import * as path from "path";
7
+ import { glob } from "glob";
8
+ async function fileExists(filePath) {
9
+ try {
10
+ await fs.access(filePath);
11
+ return true;
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }
17
+ async function globFiles(root, pattern) {
18
+ try {
19
+ const matches = await glob(pattern, {
20
+ cwd: root,
21
+ ignore: ["**/node_modules/**", "**/dist/**", "**/build/**"],
22
+ nodir: true,
23
+ absolute: false,
24
+ });
25
+ return matches.sort();
26
+ }
27
+ catch {
28
+ return [];
29
+ }
30
+ }
31
+ async function getFileSize(filePath) {
32
+ try {
33
+ const s = await fs.stat(filePath);
34
+ return s.size;
35
+ }
36
+ catch {
37
+ return 0;
38
+ }
39
+ }
40
+ async function limitFiles(root, files, maxFiles) {
41
+ if (files.length <= maxFiles)
42
+ return files;
43
+ const sized = await Promise.all(files.map(async (f) => ({ f, size: await getFileSize(path.join(root, f)) })));
44
+ sized.sort((a, b) => a.size - b.size);
45
+ return sized.slice(0, maxFiles).map((s) => s.f);
46
+ }
47
+ // ----------------------------------------------------------------
48
+ // Express selector — main export
49
+ // ----------------------------------------------------------------
50
+ /**
51
+ * Select files for Express / Fastify / Koa projects.
52
+ *
53
+ * Priority:
54
+ * 1. Route files: routes/...ts, src/routes/...ts
55
+ * 2. Middleware: middleware/...ts, src/middleware/...ts
56
+ * 3. Entry points: src/index.ts, index.ts, app.ts, server.ts
57
+ *
58
+ * @param projectRoot Absolute project root path
59
+ * @param maxFiles Maximum total files to return (default 30)
60
+ */
61
+ export async function selectExpressFiles(projectRoot, maxFiles = 30) {
62
+ const priority1 = [];
63
+ const priority2 = [];
64
+ const priority3 = [];
65
+ // ── Priority 1: Route files ──────────────────────────────────
66
+ const routePatterns = [
67
+ "routes/**/*.{ts,js}",
68
+ "src/routes/**/*.{ts,js}",
69
+ "api/**/*.{ts,js}",
70
+ "src/api/**/*.{ts,js}",
71
+ ];
72
+ for (const pat of routePatterns) {
73
+ const files = await globFiles(projectRoot, pat);
74
+ priority1.push(...files);
75
+ }
76
+ // ── Priority 2: Middleware ───────────────────────────────────
77
+ const middlewarePatterns = [
78
+ "middleware/**/*.{ts,js}",
79
+ "src/middleware/**/*.{ts,js}",
80
+ "middlewares/**/*.{ts,js}",
81
+ "src/middlewares/**/*.{ts,js}",
82
+ ];
83
+ for (const pat of middlewarePatterns) {
84
+ const files = await globFiles(projectRoot, pat);
85
+ priority2.push(...files);
86
+ }
87
+ // ── Priority 3: Entry points ─────────────────────────────────
88
+ const entryCandidates = [
89
+ "src/index.ts",
90
+ "src/index.js",
91
+ "index.ts",
92
+ "index.js",
93
+ "app.ts",
94
+ "app.js",
95
+ "server.ts",
96
+ "server.js",
97
+ "src/app.ts",
98
+ "src/app.js",
99
+ "src/server.ts",
100
+ "src/server.js",
101
+ ];
102
+ for (const candidate of entryCandidates) {
103
+ if (await fileExists(path.join(projectRoot, candidate))) {
104
+ priority3.push(candidate);
105
+ }
106
+ }
107
+ // ── Combine + deduplicate + limit ───────────────────────────
108
+ const seen = new Set();
109
+ const combined = [];
110
+ for (const f of [...priority1, ...priority2, ...priority3]) {
111
+ if (!seen.has(f)) {
112
+ seen.add(f);
113
+ combined.push(f);
114
+ }
115
+ }
116
+ return limitFiles(projectRoot, combined, maxFiles);
117
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Select files for FastAPI / Django projects.
3
+ *
4
+ * Priority:
5
+ * 1. Router files: routers/...py, api/...py
6
+ * 2. Model/schema files: models.py, schemas.py, models/...py
7
+ * 3. Entry points: main.py, app.py, urls.py (Django)
8
+ *
9
+ * @param projectRoot Absolute project root path
10
+ * @param maxFiles Maximum total files to return (default 30)
11
+ */
12
+ export declare function selectFastApiFiles(projectRoot: string, maxFiles?: number): Promise<string[]>;
@@ -0,0 +1,122 @@
1
+ // ============================================================
2
+ // @duct/sdk — FastAPI / Django File Selector
3
+ // Selects router files, models, and entry points for Python API projects.
4
+ // ============================================================
5
+ import * as fs from "fs/promises";
6
+ import * as path from "path";
7
+ import { glob } from "glob";
8
+ async function fileExists(filePath) {
9
+ try {
10
+ await fs.access(filePath);
11
+ return true;
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }
17
+ async function globFiles(root, pattern) {
18
+ try {
19
+ const matches = await glob(pattern, {
20
+ cwd: root,
21
+ ignore: ["**/__pycache__/**", "**/.venv/**", "**/venv/**", "**/dist/**"],
22
+ nodir: true,
23
+ absolute: false,
24
+ });
25
+ return matches.sort();
26
+ }
27
+ catch {
28
+ return [];
29
+ }
30
+ }
31
+ async function getFileSize(filePath) {
32
+ try {
33
+ const s = await fs.stat(filePath);
34
+ return s.size;
35
+ }
36
+ catch {
37
+ return 0;
38
+ }
39
+ }
40
+ async function limitFiles(root, files, maxFiles) {
41
+ if (files.length <= maxFiles)
42
+ return files;
43
+ const sized = await Promise.all(files.map(async (f) => ({ f, size: await getFileSize(path.join(root, f)) })));
44
+ sized.sort((a, b) => a.size - b.size);
45
+ return sized.slice(0, maxFiles).map((s) => s.f);
46
+ }
47
+ // ----------------------------------------------------------------
48
+ // FastAPI selector — main export
49
+ // ----------------------------------------------------------------
50
+ /**
51
+ * Select files for FastAPI / Django projects.
52
+ *
53
+ * Priority:
54
+ * 1. Router files: routers/...py, api/...py
55
+ * 2. Model/schema files: models.py, schemas.py, models/...py
56
+ * 3. Entry points: main.py, app.py, urls.py (Django)
57
+ *
58
+ * @param projectRoot Absolute project root path
59
+ * @param maxFiles Maximum total files to return (default 30)
60
+ */
61
+ export async function selectFastApiFiles(projectRoot, maxFiles = 30) {
62
+ const priority1 = [];
63
+ const priority2 = [];
64
+ const priority3 = [];
65
+ // ── Priority 1: Router / API files ──────────────────────────
66
+ const routerPatterns = [
67
+ "routers/**/*.py",
68
+ "router/**/*.py",
69
+ "api/**/*.py",
70
+ "src/api/**/*.py",
71
+ "app/api/**/*.py",
72
+ "endpoints/**/*.py",
73
+ "views/**/*.py", // Django
74
+ "urls.py", // Django root urls
75
+ "**/urls.py", // Django app-level urls
76
+ ];
77
+ for (const pat of routerPatterns) {
78
+ const files = await globFiles(projectRoot, pat);
79
+ priority1.push(...files);
80
+ }
81
+ // ── Priority 2: Model / Schema files ────────────────────────
82
+ const modelCandidates = [
83
+ "models.py",
84
+ "schemas.py",
85
+ "serializers.py", // Django REST
86
+ "src/models.py",
87
+ "src/schemas.py",
88
+ "app/models.py",
89
+ ];
90
+ for (const candidate of modelCandidates) {
91
+ if (await fileExists(path.join(projectRoot, candidate))) {
92
+ priority2.push(candidate);
93
+ }
94
+ }
95
+ const modelDirFiles = await globFiles(projectRoot, "models/**/*.py");
96
+ const schemasDirFiles = await globFiles(projectRoot, "schemas/**/*.py");
97
+ priority2.push(...modelDirFiles, ...schemasDirFiles);
98
+ // ── Priority 3: Entry points ─────────────────────────────────
99
+ const entryCandidates = [
100
+ "main.py",
101
+ "app.py",
102
+ "application.py",
103
+ "wsgi.py",
104
+ "asgi.py",
105
+ "manage.py", // Django
106
+ ];
107
+ for (const candidate of entryCandidates) {
108
+ if (await fileExists(path.join(projectRoot, candidate))) {
109
+ priority3.push(candidate);
110
+ }
111
+ }
112
+ // ── Combine + deduplicate + limit ───────────────────────────
113
+ const seen = new Set();
114
+ const combined = [];
115
+ for (const f of [...priority1, ...priority2, ...priority3]) {
116
+ if (!seen.has(f)) {
117
+ seen.add(f);
118
+ combined.push(f);
119
+ }
120
+ }
121
+ return limitFiles(projectRoot, combined, maxFiles);
122
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Generic fallback file selector.
3
+ *
4
+ * Returns the top `maxFiles` .ts/.js/.py files sorted by file size descending
5
+ * (larger files are more likely to contain route/handler definitions).
6
+ *
7
+ * @param projectRoot Absolute project root path
8
+ * @param maxFiles Maximum total files to return (default 30)
9
+ */
10
+ export declare function selectGenericFiles(projectRoot: string, maxFiles?: number): Promise<string[]>;