@duct-sdk/sdk 0.1.7 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/adapters/next/index.d.ts +1 -1
- package/dist/adapters/next/shell.d.ts +55 -1
- package/dist/adapters/next/shell.js +100 -17
- package/dist/adapters/react/index.d.ts +5 -1
- package/dist/adapters/react/index.js +2 -0
- package/dist/adapters/react/shell.d.ts +61 -1
- package/dist/adapters/react/shell.js +110 -16
- package/dist/adapters/react/use-page-context.d.ts +32 -0
- package/dist/adapters/react/use-page-context.js +99 -0
- package/dist/cli/agents/api-agent.d.ts +9 -3
- package/dist/cli/agents/api-agent.js +163 -69
- package/dist/cli/agents/auth-agent.d.ts +2 -1
- package/dist/cli/agents/auth-agent.js +38 -24
- package/dist/cli/agents/deeplink-agent.js +71 -49
- package/dist/cli/agents/llm.d.ts +1 -1
- package/dist/cli/agents/llm.js +48 -15
- package/dist/cli/agents/pipeline.d.ts +16 -0
- package/dist/cli/agents/pipeline.js +18 -5
- package/dist/cli/agents/reviewer-agent.js +46 -46
- package/dist/cli/agents/route-agent.d.ts +3 -1
- package/dist/cli/agents/route-agent.js +70 -44
- package/dist/cli/detectors/topology.d.ts +26 -0
- package/dist/cli/detectors/topology.js +310 -0
- package/dist/cli/drift.d.ts +11 -0
- package/dist/cli/drift.js +147 -2
- package/dist/cli/fs/sandbox.d.ts +2 -0
- package/dist/cli/fs/sandbox.js +22 -8
- package/dist/cli/generators/config.d.ts +13 -0
- package/dist/cli/generators/config.js +200 -50
- package/dist/cli/generators/receiver.js +728 -601
- package/dist/cli/generators/shell.js +532 -490
- package/dist/cli/index.js +502 -19
- package/dist/cli/init.d.ts +11 -1
- package/dist/cli/init.js +367 -31
- package/dist/cli/processors/postprocess.d.ts +22 -0
- package/dist/cli/processors/postprocess.js +107 -0
- package/dist/cli/processors/prisma-parser.d.ts +35 -0
- package/dist/cli/processors/prisma-parser.js +117 -0
- package/dist/cli/processors/zod-extractor.d.ts +27 -0
- package/dist/cli/processors/zod-extractor.js +153 -0
- package/dist/cli/prompts/review.d.ts +32 -0
- package/dist/cli/prompts/review.js +240 -0
- package/dist/cli/selectors/index.d.ts +22 -0
- package/dist/cli/selectors/index.js +274 -0
- package/dist/core/config.d.ts +18 -18
- package/dist/core/endpoints.d.ts +1 -0
- package/dist/core/endpoints.js +4 -0
- package/dist/core/introspect.d.ts +47 -0
- package/dist/core/introspect.js +94 -0
- package/dist/core/status.d.ts +39 -0
- package/dist/core/status.js +40 -0
- package/dist/core/token.d.ts +36 -1
- package/dist/core/token.js +43 -2
- package/dist/core/types.d.ts +114 -0
- package/dist/index.d.ts +9 -2
- package/dist/index.js +6 -1
- package/package.json +84 -84
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export interface PrismaField {
|
|
2
|
+
name: string;
|
|
3
|
+
type: string;
|
|
4
|
+
isOptional: boolean;
|
|
5
|
+
isId: boolean;
|
|
6
|
+
isRelation: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface PrismaModel {
|
|
9
|
+
name: string;
|
|
10
|
+
fields: PrismaField[];
|
|
11
|
+
/** Best candidate for a human-readable label field (first non-id String) */
|
|
12
|
+
labelField?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface PrismaParseResult {
|
|
15
|
+
models: PrismaModel[];
|
|
16
|
+
/** Pre-formatted annotation string for injection into agent prompt */
|
|
17
|
+
annotation: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Parse Prisma model definitions from a schema.prisma file.
|
|
21
|
+
* Uses line-by-line parsing — handles standard Prisma syntax.
|
|
22
|
+
*/
|
|
23
|
+
export declare function parsePrismaSchema(source: string): PrismaParseResult;
|
|
24
|
+
/**
|
|
25
|
+
* Build dataModel entity candidates from parsed Prisma models.
|
|
26
|
+
* Called at push time to auto-populate `dataModel` in duct.config.ts.
|
|
27
|
+
*/
|
|
28
|
+
export declare function buildDataModelFromPrisma(models: PrismaModel[]): Array<{
|
|
29
|
+
id: string;
|
|
30
|
+
label: string;
|
|
31
|
+
discoveryAction: string;
|
|
32
|
+
fetchAction: string;
|
|
33
|
+
indexKey: string;
|
|
34
|
+
labelKey: string;
|
|
35
|
+
}>;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — Prisma Schema Parser (Phase 0.5)
|
|
3
|
+
// Parses prisma/schema.prisma model definitions (no LLM).
|
|
4
|
+
// Maps each model to a candidate dataModel entity and injects
|
|
5
|
+
// field names into the API Agent prompt so it recognises CRUD
|
|
6
|
+
// action params (e.g. title: z.string() maps to Post.title).
|
|
7
|
+
// ============================================================
|
|
8
|
+
// Prisma scalar types we care about for JSON Schema mapping
|
|
9
|
+
const PRISMA_SCALAR_TYPES = new Set([
|
|
10
|
+
"String", "Int", "Float", "Boolean", "DateTime", "Decimal", "BigInt", "Bytes", "Json",
|
|
11
|
+
]);
|
|
12
|
+
/**
|
|
13
|
+
* Parse Prisma model definitions from a schema.prisma file.
|
|
14
|
+
* Uses line-by-line parsing — handles standard Prisma syntax.
|
|
15
|
+
*/
|
|
16
|
+
export function parsePrismaSchema(source) {
|
|
17
|
+
const models = [];
|
|
18
|
+
const lines = source.split("\n");
|
|
19
|
+
let i = 0;
|
|
20
|
+
while (i < lines.length) {
|
|
21
|
+
const line = lines[i].trim();
|
|
22
|
+
// Match: model ModelName {
|
|
23
|
+
const modelMatch = /^model\s+(\w+)\s*\{/.exec(line);
|
|
24
|
+
if (!modelMatch) {
|
|
25
|
+
i++;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const modelName = modelMatch[1];
|
|
29
|
+
const fields = [];
|
|
30
|
+
i++;
|
|
31
|
+
// Parse fields until closing brace
|
|
32
|
+
while (i < lines.length) {
|
|
33
|
+
const fieldLine = lines[i].trim();
|
|
34
|
+
if (fieldLine === "}" || fieldLine.startsWith("}"))
|
|
35
|
+
break;
|
|
36
|
+
// Skip comments, blank lines, @@-level attributes
|
|
37
|
+
if (!fieldLine || fieldLine.startsWith("//") || fieldLine.startsWith("@@")) {
|
|
38
|
+
i++;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
// Field pattern: fieldName FieldType [?] [@attributes...]
|
|
42
|
+
// e.g.: id String @id @default(cuid())
|
|
43
|
+
// e.g.: title String
|
|
44
|
+
// e.g.: orders Order[]
|
|
45
|
+
const fieldMatch = /^(\w+)\s+(\w+)(\[\])?\s*(\?)?/.exec(fieldLine);
|
|
46
|
+
if (!fieldMatch) {
|
|
47
|
+
i++;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const fieldName = fieldMatch[1];
|
|
51
|
+
const fieldType = fieldMatch[2];
|
|
52
|
+
const isArray = Boolean(fieldMatch[3]);
|
|
53
|
+
const isOptional = Boolean(fieldMatch[4]);
|
|
54
|
+
const isRelation = !PRISMA_SCALAR_TYPES.has(fieldType);
|
|
55
|
+
const isId = /@id\b/.test(fieldLine);
|
|
56
|
+
// Skip array relations (one-to-many) — not useful as action params
|
|
57
|
+
if (isArray && isRelation) {
|
|
58
|
+
i++;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
fields.push({ name: fieldName, type: fieldType, isOptional, isId, isRelation });
|
|
62
|
+
i++;
|
|
63
|
+
}
|
|
64
|
+
if (fields.length > 0) {
|
|
65
|
+
// Find the best labelField: first non-id String field
|
|
66
|
+
const labelField = fields.find((f) => f.type === "String" && !f.isId && !f.isRelation)?.name;
|
|
67
|
+
models.push({ name: modelName, fields, labelField });
|
|
68
|
+
}
|
|
69
|
+
i++;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
models,
|
|
73
|
+
annotation: formatPrismaAnnotation(models),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function formatPrismaAnnotation(models) {
|
|
77
|
+
if (models.length === 0)
|
|
78
|
+
return "";
|
|
79
|
+
const lines = ["// PRISMA_MODELS — use these field names for CRUD action params:"];
|
|
80
|
+
for (const model of models) {
|
|
81
|
+
lines.push(`// Model "${model.name}":`);
|
|
82
|
+
const scalarFields = model.fields.filter((f) => !f.isRelation);
|
|
83
|
+
for (const field of scalarFields) {
|
|
84
|
+
const tag = field.isId ? " (id)" : field.isOptional ? " (optional)" : " (required)";
|
|
85
|
+
lines.push(`// ${field.name}: ${field.type}${tag}`);
|
|
86
|
+
}
|
|
87
|
+
if (model.labelField) {
|
|
88
|
+
lines.push(`// → label field: "${model.labelField}"`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return lines.join("\n");
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Build dataModel entity candidates from parsed Prisma models.
|
|
95
|
+
* Called at push time to auto-populate `dataModel` in duct.config.ts.
|
|
96
|
+
*/
|
|
97
|
+
export function buildDataModelFromPrisma(models) {
|
|
98
|
+
return models.map((model) => {
|
|
99
|
+
const snakeId = toSnakeCase(model.name);
|
|
100
|
+
const idField = model.fields.find((f) => f.isId)?.name ?? "id";
|
|
101
|
+
return {
|
|
102
|
+
id: snakeId,
|
|
103
|
+
label: model.name,
|
|
104
|
+
discoveryAction: `list_${snakeId}`,
|
|
105
|
+
fetchAction: `get_${snakeId}`,
|
|
106
|
+
indexKey: idField,
|
|
107
|
+
labelKey: model.labelField ?? idField,
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
function toSnakeCase(str) {
|
|
112
|
+
return str
|
|
113
|
+
.replace(/([A-Z])/g, "_$1")
|
|
114
|
+
.toLowerCase()
|
|
115
|
+
.replace(/^_/, "")
|
|
116
|
+
.replace(/_+/g, "_");
|
|
117
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface ZodField {
|
|
2
|
+
name: string;
|
|
3
|
+
type: "string" | "number" | "boolean" | "object" | "array" | "enum" | "unknown";
|
|
4
|
+
required: boolean;
|
|
5
|
+
enumValues?: string[];
|
|
6
|
+
}
|
|
7
|
+
export interface ExtractedZodSchema {
|
|
8
|
+
name?: string;
|
|
9
|
+
fields: ZodField[];
|
|
10
|
+
}
|
|
11
|
+
export interface FileSchemaHint {
|
|
12
|
+
filePath: string;
|
|
13
|
+
schemas: ExtractedZodSchema[];
|
|
14
|
+
/** Formatted annotation string for injection into agent prompt */
|
|
15
|
+
annotation: string;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Extract Zod schema hints from a list of API source files.
|
|
19
|
+
* Returns one FileSchemaHint per file that contains at least one z.object declaration.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* const hints = await extractZodHintsFromFiles(sandboxFs, readList.apiFiles);
|
|
24
|
+
* // Inject hints[n].annotation into the agent prompt alongside each file snippet.
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function extractZodHintsFromFiles(readFile: (path: string) => Promise<string | null>, filePaths: string[]): Promise<Map<string, FileSchemaHint>>;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — Zod Schema Extractor (Phase 1.5)
|
|
3
|
+
// Scans API source files for z.object({...}) patterns and
|
|
4
|
+
// converts them to JSON Schema annotations injected into agent
|
|
5
|
+
// prompts so agents receive structured param info directly.
|
|
6
|
+
// Covers 90%+ of Next.js API routes without LLM guesswork.
|
|
7
|
+
// ============================================================
|
|
8
|
+
// Maps Zod method names to JSON Schema-like types
|
|
9
|
+
const ZOD_TYPE_MAP = {
|
|
10
|
+
string: "string",
|
|
11
|
+
number: "number",
|
|
12
|
+
boolean: "boolean",
|
|
13
|
+
object: "object",
|
|
14
|
+
array: "array",
|
|
15
|
+
enum: "enum",
|
|
16
|
+
literal: "string",
|
|
17
|
+
date: "string",
|
|
18
|
+
bigint: "number",
|
|
19
|
+
coerce: "string",
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Parse z.object({...}) declarations from TypeScript source.
|
|
23
|
+
* Uses regex — intentionally naive but covers the common patterns.
|
|
24
|
+
*/
|
|
25
|
+
function parseZodObjects(source) {
|
|
26
|
+
const results = [];
|
|
27
|
+
// Match: [const VarName = ]z.object({ ... })
|
|
28
|
+
// We walk character-by-character to handle nested braces correctly.
|
|
29
|
+
const zodMarker = "z.object(";
|
|
30
|
+
let pos = 0;
|
|
31
|
+
while (pos < source.length) {
|
|
32
|
+
const idx = source.indexOf(zodMarker, pos);
|
|
33
|
+
if (idx === -1)
|
|
34
|
+
break;
|
|
35
|
+
// Try to find the variable name before z.object(
|
|
36
|
+
let varName;
|
|
37
|
+
const prefix = source.slice(Math.max(0, idx - 80), idx);
|
|
38
|
+
const varMatch = /(?:const|let|var)\s+(\w+)\s*(?:=\s*(?:\w+\s*\()?\s*)?$/.exec(prefix);
|
|
39
|
+
if (varMatch)
|
|
40
|
+
varName = varMatch[1];
|
|
41
|
+
// Find the matching closing paren for z.object(
|
|
42
|
+
// The structure is z.object({ fields... })
|
|
43
|
+
const openBrace = source.indexOf("{", idx + zodMarker.length);
|
|
44
|
+
if (openBrace === -1) {
|
|
45
|
+
pos = idx + 1;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
let depth = 0;
|
|
49
|
+
let closeBrace = -1;
|
|
50
|
+
for (let i = openBrace; i < source.length; i++) {
|
|
51
|
+
if (source[i] === "{")
|
|
52
|
+
depth++;
|
|
53
|
+
else if (source[i] === "}") {
|
|
54
|
+
depth--;
|
|
55
|
+
if (depth === 0) {
|
|
56
|
+
closeBrace = i;
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (closeBrace === -1) {
|
|
62
|
+
pos = idx + 1;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const fieldsStr = source.slice(openBrace + 1, closeBrace);
|
|
66
|
+
const fields = parseZodFields(fieldsStr);
|
|
67
|
+
if (fields.length > 0) {
|
|
68
|
+
results.push({ name: varName, fields });
|
|
69
|
+
}
|
|
70
|
+
pos = closeBrace + 1;
|
|
71
|
+
}
|
|
72
|
+
return results;
|
|
73
|
+
}
|
|
74
|
+
function parseZodFields(fieldsStr) {
|
|
75
|
+
const fields = [];
|
|
76
|
+
// Match: fieldName: z.type(...) with optional .optional() / .nullable()
|
|
77
|
+
// Handles: name: z.string(), age: z.number().optional(), status: z.enum([...])
|
|
78
|
+
const fieldRe = /(\w+)\s*:\s*z(?:\.coerce)?\.(\w+)\s*(?:\(([^)]*)\))?([^,}\n]*)/g;
|
|
79
|
+
let m;
|
|
80
|
+
while ((m = fieldRe.exec(fieldsStr)) !== null) {
|
|
81
|
+
const fieldName = m[1];
|
|
82
|
+
const zodMethod = m[2].toLowerCase();
|
|
83
|
+
const methodArgs = m[3] ?? "";
|
|
84
|
+
const chainStr = m[4] ?? "";
|
|
85
|
+
// Skip z.object(...) nested calls — the outer schema captures the parent
|
|
86
|
+
if (zodMethod === "object")
|
|
87
|
+
continue;
|
|
88
|
+
const type = ZOD_TYPE_MAP[zodMethod] ?? "unknown";
|
|
89
|
+
const isOptional = chainStr.includes(".optional()") ||
|
|
90
|
+
chainStr.includes(".nullable()") ||
|
|
91
|
+
chainStr.includes(".nullish()");
|
|
92
|
+
const field = { name: fieldName, type, required: !isOptional };
|
|
93
|
+
if (type === "enum") {
|
|
94
|
+
// Extract enum values from z.enum(["a", "b", "c"])
|
|
95
|
+
const enumContentMatch = /\[([^\]]*)\]/.exec(methodArgs + chainStr);
|
|
96
|
+
if (enumContentMatch) {
|
|
97
|
+
field.enumValues = enumContentMatch[1]
|
|
98
|
+
.split(",")
|
|
99
|
+
.map((v) => v.trim().replace(/^["'`]|["'`]$/g, ""))
|
|
100
|
+
.filter(Boolean);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
fields.push(field);
|
|
104
|
+
}
|
|
105
|
+
return fields;
|
|
106
|
+
}
|
|
107
|
+
function formatSchemaAnnotation(schemas, filePath) {
|
|
108
|
+
if (schemas.length === 0)
|
|
109
|
+
return "";
|
|
110
|
+
const lines = [`// EXTRACTED_SCHEMAS from ${filePath}:`];
|
|
111
|
+
for (const schema of schemas.slice(0, 5)) { // cap at 5 schemas per file
|
|
112
|
+
const label = schema.name ?? "anonymous";
|
|
113
|
+
lines.push(`// Schema "${label}":`);
|
|
114
|
+
for (const field of schema.fields) {
|
|
115
|
+
const optStr = field.required ? "required" : "optional";
|
|
116
|
+
const enumStr = field.enumValues?.length
|
|
117
|
+
? ` [${field.enumValues.slice(0, 6).join("|")}]`
|
|
118
|
+
: "";
|
|
119
|
+
lines.push(`// ${field.name}: ${field.type}${enumStr} (${optStr})`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return lines.join("\n");
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Extract Zod schema hints from a list of API source files.
|
|
126
|
+
* Returns one FileSchemaHint per file that contains at least one z.object declaration.
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```ts
|
|
130
|
+
* const hints = await extractZodHintsFromFiles(sandboxFs, readList.apiFiles);
|
|
131
|
+
* // Inject hints[n].annotation into the agent prompt alongside each file snippet.
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
export async function extractZodHintsFromFiles(readFile, filePaths) {
|
|
135
|
+
const hints = new Map();
|
|
136
|
+
for (const filePath of filePaths) {
|
|
137
|
+
// Only scan TypeScript/JavaScript files
|
|
138
|
+
if (!/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(filePath))
|
|
139
|
+
continue;
|
|
140
|
+
const source = await readFile(filePath);
|
|
141
|
+
if (!source || !source.includes("z.object("))
|
|
142
|
+
continue;
|
|
143
|
+
const schemas = parseZodObjects(source);
|
|
144
|
+
if (schemas.length === 0)
|
|
145
|
+
continue;
|
|
146
|
+
hints.set(filePath, {
|
|
147
|
+
filePath,
|
|
148
|
+
schemas,
|
|
149
|
+
annotation: formatSchemaAnnotation(schemas, filePath),
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
return hints;
|
|
153
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ActionManifest, RouteManifest, DeeplinkDefinition, AuthSchema } from "../../core/types.js";
|
|
2
|
+
import type { PipelineResult } from "../agents/pipeline.js";
|
|
3
|
+
export interface ReviewOptions {
|
|
4
|
+
/** Auto-approve all prompts — for CI / scripted use */
|
|
5
|
+
yes?: boolean;
|
|
6
|
+
/** Write unresolved decisions to duct-review.json instead of prompting */
|
|
7
|
+
noInteractive?: boolean;
|
|
8
|
+
/** Directory to write duct-review.json (defaults to cwd) */
|
|
9
|
+
cwd?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface ReviewedPipelineResult {
|
|
12
|
+
routes: RouteManifest[];
|
|
13
|
+
actions: ActionManifest[];
|
|
14
|
+
auth: AuthSchema;
|
|
15
|
+
deeplinks: DeeplinkDefinition[];
|
|
16
|
+
/** Actions the user explicitly rejected or marked never */
|
|
17
|
+
rejectedActions: ActionManifest[];
|
|
18
|
+
/** Decisions written to duct-review.json (noInteractive mode) */
|
|
19
|
+
reviewFilePath?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Interactive Review CLI.
|
|
23
|
+
*
|
|
24
|
+
* Decision rules:
|
|
25
|
+
* - Auto-approve: GET/HEAD with confidence ≥ 0.85 → no prompt
|
|
26
|
+
* - Always prompt: POST/PUT/PATCH/DELETE, confidence < 0.85, auth ambiguity
|
|
27
|
+
*
|
|
28
|
+
* Flags:
|
|
29
|
+
* - `--yes`: auto-approve everything, skip interactive review
|
|
30
|
+
* - `--no-interactive`: write unresolved decisions to duct-review.json
|
|
31
|
+
*/
|
|
32
|
+
export declare function runInteractiveReview(pipelineResult: PipelineResult, opts?: ReviewOptions): Promise<ReviewedPipelineResult>;
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — Interactive Review CLI
|
|
3
|
+
// Human-in-the-loop decision loop for detected actions/routes.
|
|
4
|
+
// ============================================================
|
|
5
|
+
import * as readline from "readline";
|
|
6
|
+
import * as fs from "fs/promises";
|
|
7
|
+
import * as path from "path";
|
|
8
|
+
import chalk from "chalk";
|
|
9
|
+
// ----------------------------------------------------------------
|
|
10
|
+
// Helpers
|
|
11
|
+
// ----------------------------------------------------------------
|
|
12
|
+
function confidenceColor(c) {
|
|
13
|
+
if (c >= 0.85)
|
|
14
|
+
return chalk.green(`${Math.round(c * 100)}%`);
|
|
15
|
+
if (c >= 0.6)
|
|
16
|
+
return chalk.yellow(`${Math.round(c * 100)}%`);
|
|
17
|
+
return chalk.red(`${Math.round(c * 100)}%`);
|
|
18
|
+
}
|
|
19
|
+
function methodColor(method) {
|
|
20
|
+
const colors = {
|
|
21
|
+
GET: chalk.green,
|
|
22
|
+
HEAD: chalk.green,
|
|
23
|
+
POST: chalk.blue,
|
|
24
|
+
PUT: chalk.yellow,
|
|
25
|
+
PATCH: chalk.yellow,
|
|
26
|
+
DELETE: chalk.red,
|
|
27
|
+
};
|
|
28
|
+
return (colors[method] ?? chalk.white)(method);
|
|
29
|
+
}
|
|
30
|
+
function shouldAutoApprove(action) {
|
|
31
|
+
const isSafeMethod = action.method === "GET";
|
|
32
|
+
const confidence = action.confidence ?? 0;
|
|
33
|
+
return isSafeMethod && confidence >= 0.85;
|
|
34
|
+
}
|
|
35
|
+
function requiresPrompt(action) {
|
|
36
|
+
const isSideEffect = action.method === "POST" ||
|
|
37
|
+
action.method === "PUT" ||
|
|
38
|
+
action.method === "PATCH" ||
|
|
39
|
+
action.method === "DELETE";
|
|
40
|
+
const lowConfidence = (action.confidence ?? 0) < 0.85;
|
|
41
|
+
return isSideEffect || lowConfidence;
|
|
42
|
+
}
|
|
43
|
+
// ----------------------------------------------------------------
|
|
44
|
+
// Single-action prompt (readline-based, not inquirer)
|
|
45
|
+
// ----------------------------------------------------------------
|
|
46
|
+
async function promptActionDecision(action, rl) {
|
|
47
|
+
const confidence = action.confidence ?? 0;
|
|
48
|
+
const evidence = action.evidence ?? "unknown source";
|
|
49
|
+
const method = methodColor(action.method);
|
|
50
|
+
const conf = confidenceColor(confidence);
|
|
51
|
+
const isSideEffect = action.sideEffects ||
|
|
52
|
+
action.method === "POST" ||
|
|
53
|
+
action.method === "PUT" ||
|
|
54
|
+
action.method === "PATCH" ||
|
|
55
|
+
action.method === "DELETE";
|
|
56
|
+
const reason = isSideEffect
|
|
57
|
+
? "side-effect action"
|
|
58
|
+
: `confidence ${Math.round(confidence * 100)}% < 85%`;
|
|
59
|
+
process.stdout.write(`\n ${chalk.bold("[DUCT]")} ${method} ${chalk.cyan(action.path)} — ${reason}\n` +
|
|
60
|
+
` ${chalk.gray(`Confidence: ${conf} | Evidence: ${chalk.dim(evidence)}`)}\n` +
|
|
61
|
+
` ${chalk.gray(`Mark agent-accessible? [y/N/never/explain]: `)}`);
|
|
62
|
+
return new Promise((resolve) => {
|
|
63
|
+
rl.once("line", (answer) => {
|
|
64
|
+
const trimmed = answer.trim().toLowerCase();
|
|
65
|
+
if (trimmed === "y" || trimmed === "yes") {
|
|
66
|
+
resolve("approve");
|
|
67
|
+
}
|
|
68
|
+
else if (trimmed === "never") {
|
|
69
|
+
resolve("never");
|
|
70
|
+
}
|
|
71
|
+
else if (trimmed === "explain") {
|
|
72
|
+
resolve("explain");
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
resolve("reject");
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
async function handleExplain(action) {
|
|
81
|
+
process.stdout.write(chalk.gray(`\n What does "${action.id}" do?\n` +
|
|
82
|
+
` ${action.description}\n\n` +
|
|
83
|
+
` Parameters:\n`));
|
|
84
|
+
for (const p of action.params) {
|
|
85
|
+
process.stdout.write(chalk.gray(` • ${p.name} (${p.type})${p.required ? " *required*" : ""}\n`));
|
|
86
|
+
}
|
|
87
|
+
if (action.inputSchema) {
|
|
88
|
+
process.stdout.write(chalk.gray(`\n Input schema: ${JSON.stringify(action.inputSchema, null, 2).slice(0, 200)}\n`));
|
|
89
|
+
}
|
|
90
|
+
process.stdout.write("\n");
|
|
91
|
+
}
|
|
92
|
+
// ----------------------------------------------------------------
|
|
93
|
+
// runInteractiveReview
|
|
94
|
+
// ----------------------------------------------------------------
|
|
95
|
+
/**
|
|
96
|
+
* Interactive Review CLI.
|
|
97
|
+
*
|
|
98
|
+
* Decision rules:
|
|
99
|
+
* - Auto-approve: GET/HEAD with confidence ≥ 0.85 → no prompt
|
|
100
|
+
* - Always prompt: POST/PUT/PATCH/DELETE, confidence < 0.85, auth ambiguity
|
|
101
|
+
*
|
|
102
|
+
* Flags:
|
|
103
|
+
* - `--yes`: auto-approve everything, skip interactive review
|
|
104
|
+
* - `--no-interactive`: write unresolved decisions to duct-review.json
|
|
105
|
+
*/
|
|
106
|
+
export async function runInteractiveReview(pipelineResult, opts = {}) {
|
|
107
|
+
const { yes = false, noInteractive = false, cwd = process.cwd() } = opts;
|
|
108
|
+
const approvedActions = [];
|
|
109
|
+
const rejectedActions = [];
|
|
110
|
+
const pendingDecisions = [];
|
|
111
|
+
// ---- --yes mode: approve everything ----
|
|
112
|
+
if (yes) {
|
|
113
|
+
for (const action of pipelineResult.actions) {
|
|
114
|
+
approvedActions.push({ ...action, agentAccessible: shouldAutoApprove(action) });
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
routes: pipelineResult.routes,
|
|
118
|
+
actions: approvedActions,
|
|
119
|
+
auth: pipelineResult.auth,
|
|
120
|
+
deeplinks: pipelineResult.deeplinks,
|
|
121
|
+
rejectedActions: [],
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// ---- --no-interactive mode: auto-approve where possible, collect rest ----
|
|
125
|
+
if (noInteractive) {
|
|
126
|
+
for (const action of pipelineResult.actions) {
|
|
127
|
+
if (shouldAutoApprove(action)) {
|
|
128
|
+
approvedActions.push({ ...action, agentAccessible: true });
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
// Auto-deny side-effects conservatively; write to review file for human review
|
|
132
|
+
approvedActions.push({ ...action, agentAccessible: false });
|
|
133
|
+
pendingDecisions.push({
|
|
134
|
+
type: "action",
|
|
135
|
+
id: action.id,
|
|
136
|
+
method: action.method,
|
|
137
|
+
path: action.path,
|
|
138
|
+
confidence: action.confidence ?? 0,
|
|
139
|
+
evidence: action.evidence,
|
|
140
|
+
reason: requiresPrompt(action)
|
|
141
|
+
? "Requires human review: side-effect or low confidence"
|
|
142
|
+
: "Pending",
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
// Write duct-review.json
|
|
147
|
+
const reviewFilePath = path.join(cwd, "duct-review.json");
|
|
148
|
+
const reviewContent = {
|
|
149
|
+
generatedAt: new Date().toISOString(),
|
|
150
|
+
pendingDecisions,
|
|
151
|
+
instructions: "Review each entry. Set `approved: true` for actions the AI agent should be able to invoke. Re-run `npx duct init` to apply.",
|
|
152
|
+
};
|
|
153
|
+
await fs.writeFile(reviewFilePath, JSON.stringify(reviewContent, null, 2) + "\n", "utf-8");
|
|
154
|
+
console.log(chalk.yellow(`\n [DUCT] --no-interactive mode: wrote ${pendingDecisions.length} pending decisions to duct-review.json\n`));
|
|
155
|
+
return {
|
|
156
|
+
routes: pipelineResult.routes,
|
|
157
|
+
actions: approvedActions,
|
|
158
|
+
auth: pipelineResult.auth,
|
|
159
|
+
deeplinks: pipelineResult.deeplinks,
|
|
160
|
+
rejectedActions,
|
|
161
|
+
reviewFilePath,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
// ---- Interactive mode ----
|
|
165
|
+
const actionsNeedingReview = pipelineResult.actions.filter(requiresPrompt);
|
|
166
|
+
const autoApprovedActions = pipelineResult.actions.filter((a) => !requiresPrompt(a));
|
|
167
|
+
if (actionsNeedingReview.length === 0) {
|
|
168
|
+
// Nothing to review — all actions are safe read-only with high confidence
|
|
169
|
+
console.log(chalk.green(`\n ✓ All ${pipelineResult.actions.length} actions auto-approved (GET/HEAD, confidence ≥ 85%)\n`));
|
|
170
|
+
return {
|
|
171
|
+
routes: pipelineResult.routes,
|
|
172
|
+
actions: pipelineResult.actions.map((a) => ({
|
|
173
|
+
...a,
|
|
174
|
+
agentAccessible: shouldAutoApprove(a),
|
|
175
|
+
})),
|
|
176
|
+
auth: pipelineResult.auth,
|
|
177
|
+
deeplinks: pipelineResult.deeplinks,
|
|
178
|
+
rejectedActions: [],
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
// Show auto-approved summary
|
|
182
|
+
if (autoApprovedActions.length > 0) {
|
|
183
|
+
console.log(chalk.bold(`\n ${chalk.green("✓")} ${autoApprovedActions.length} action${autoApprovedActions.length === 1 ? "" : "s"} auto-approved (GET/HEAD, confidence ≥ 85%)`));
|
|
184
|
+
for (const a of autoApprovedActions) {
|
|
185
|
+
console.log(chalk.gray(` ${methodColor(a.method)} ${a.path} ${confidenceColor(a.confidence ?? 0)}`));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// Start review loop
|
|
189
|
+
console.log(chalk.bold(`\n ${actionsNeedingReview.length} action${actionsNeedingReview.length === 1 ? "" : "s"} need your review:\n`));
|
|
190
|
+
console.log(chalk.gray(" Side-effect actions (POST/PUT/PATCH/DELETE) and low-confidence detections\n" +
|
|
191
|
+
" require confirmation before being marked as agent-accessible.\n" +
|
|
192
|
+
" y = approve N = deny never = deny + suppress explain = show details\n"));
|
|
193
|
+
const rl = readline.createInterface({
|
|
194
|
+
input: process.stdin,
|
|
195
|
+
output: process.stdout,
|
|
196
|
+
terminal: false,
|
|
197
|
+
});
|
|
198
|
+
// Add approved auto-approved actions
|
|
199
|
+
for (const a of autoApprovedActions) {
|
|
200
|
+
approvedActions.push({ ...a, agentAccessible: true });
|
|
201
|
+
}
|
|
202
|
+
for (const action of actionsNeedingReview) {
|
|
203
|
+
let decision = "reject";
|
|
204
|
+
// Re-prompt on "explain" until the user makes a final decision
|
|
205
|
+
while (true) {
|
|
206
|
+
decision = await promptActionDecision(action, rl);
|
|
207
|
+
if (decision === "explain") {
|
|
208
|
+
await handleExplain(action);
|
|
209
|
+
continue; // re-prompt
|
|
210
|
+
}
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
if (decision === "approve") {
|
|
214
|
+
approvedActions.push({ ...action, agentAccessible: true });
|
|
215
|
+
console.log(chalk.green(` ✓ ${action.id} — marked agent-accessible`));
|
|
216
|
+
}
|
|
217
|
+
else if (decision === "never") {
|
|
218
|
+
// Suppress but include in config with agentAccessible: false
|
|
219
|
+
approvedActions.push({ ...action, agentAccessible: false });
|
|
220
|
+
rejectedActions.push(action);
|
|
221
|
+
console.log(chalk.gray(` — ${action.id} — skipped (never)`));
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
// reject — include in config with agentAccessible: false
|
|
225
|
+
approvedActions.push({ ...action, agentAccessible: false });
|
|
226
|
+
rejectedActions.push(action);
|
|
227
|
+
console.log(chalk.gray(` — ${action.id} — not marked agent-accessible`));
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
rl.close();
|
|
231
|
+
const agentAccessibleCount = approvedActions.filter((a) => a.agentAccessible).length;
|
|
232
|
+
console.log(chalk.bold(`\n Review complete: ${agentAccessibleCount}/${pipelineResult.actions.length} actions marked agent-accessible\n`));
|
|
233
|
+
return {
|
|
234
|
+
routes: pipelineResult.routes,
|
|
235
|
+
actions: approvedActions,
|
|
236
|
+
auth: pipelineResult.auth,
|
|
237
|
+
deeplinks: pipelineResult.deeplinks,
|
|
238
|
+
rejectedActions,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { SandboxFS } from "../fs/sandbox.js";
|
|
2
|
+
import type { TopoResult } from "../detectors/topology.js";
|
|
3
|
+
/** Per-agent bounded file list, max MAX_FILES_PER_LIST entries each. */
|
|
4
|
+
export interface ReadList {
|
|
5
|
+
/** Files for the Route Agent — page files, layouts */
|
|
6
|
+
routeFiles: string[];
|
|
7
|
+
/** Files for the API Agent — route handlers, controllers */
|
|
8
|
+
apiFiles: string[];
|
|
9
|
+
/** Files for the Auth Agent — middleware, auth config, env examples */
|
|
10
|
+
authFiles: string[];
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Build a bounded ReadList per agent from the project's topology.
|
|
14
|
+
*
|
|
15
|
+
* Given a TopoResult, builds a bounded ReadList for each agent.
|
|
16
|
+
* Each list is capped at MAX_FILES_PER_LIST entries, ranked by file size
|
|
17
|
+
* (smaller first — more focused files).
|
|
18
|
+
*
|
|
19
|
+
* Falls back to the generic strategy for unknown stacks. Generic fallback
|
|
20
|
+
* detections should get confidence < 0.6 automatically.
|
|
21
|
+
*/
|
|
22
|
+
export declare function buildReadList(topo: TopoResult, sandboxFs: SandboxFS): Promise<ReadList>;
|