@duct-sdk/sdk 0.1.6
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 +92 -0
- package/dist/adapters/next/index.d.ts +4 -0
- package/dist/adapters/next/index.js +5 -0
- package/dist/adapters/next/receiver.d.ts +44 -0
- package/dist/adapters/next/receiver.js +162 -0
- package/dist/adapters/next/shell.d.ts +88 -0
- package/dist/adapters/next/shell.js +255 -0
- package/dist/adapters/react/index.d.ts +2 -0
- package/dist/adapters/react/index.js +4 -0
- package/dist/adapters/react/shell.d.ts +88 -0
- package/dist/adapters/react/shell.js +255 -0
- package/dist/adapters/remix/index.d.ts +2 -0
- package/dist/adapters/remix/index.js +4 -0
- package/dist/adapters/remix/receiver.d.ts +44 -0
- package/dist/adapters/remix/receiver.js +153 -0
- package/dist/adapters/sveltekit/index.d.ts +2 -0
- package/dist/adapters/sveltekit/index.js +4 -0
- package/dist/adapters/sveltekit/receiver.d.ts +56 -0
- package/dist/adapters/sveltekit/receiver.js +154 -0
- package/dist/adapters/vite/index.d.ts +2 -0
- package/dist/adapters/vite/index.js +4 -0
- package/dist/adapters/vite/receiver.d.ts +82 -0
- package/dist/adapters/vite/receiver.js +164 -0
- package/dist/assets/logo.d.ts +1 -0
- package/dist/assets/logo.js +1 -0
- package/dist/cli/agents/api-agent.d.ts +14 -0
- package/dist/cli/agents/api-agent.js +656 -0
- package/dist/cli/agents/auth-agent.d.ts +6 -0
- package/dist/cli/agents/auth-agent.js +198 -0
- package/dist/cli/agents/deeplink-agent.d.ts +6 -0
- package/dist/cli/agents/deeplink-agent.js +263 -0
- package/dist/cli/agents/llm.d.ts +33 -0
- package/dist/cli/agents/llm.js +276 -0
- package/dist/cli/agents/pipeline.d.ts +51 -0
- package/dist/cli/agents/pipeline.js +236 -0
- package/dist/cli/agents/reviewer-agent.d.ts +11 -0
- package/dist/cli/agents/reviewer-agent.js +442 -0
- package/dist/cli/agents/route-agent.d.ts +13 -0
- package/dist/cli/agents/route-agent.js +346 -0
- package/dist/cli/detectors/auth.d.ts +18 -0
- package/dist/cli/detectors/auth.js +273 -0
- package/dist/cli/detectors/framework.d.ts +22 -0
- package/dist/cli/detectors/framework.js +242 -0
- package/dist/cli/drift.d.ts +39 -0
- package/dist/cli/drift.js +247 -0
- package/dist/cli/fs/sandbox.d.ts +77 -0
- package/dist/cli/fs/sandbox.js +295 -0
- package/dist/cli/generators/config.d.ts +7 -0
- package/dist/cli/generators/config.js +255 -0
- package/dist/cli/generators/receiver.d.ts +12 -0
- package/dist/cli/generators/receiver.js +683 -0
- package/dist/cli/generators/shell.d.ts +18 -0
- package/dist/cli/generators/shell.js +672 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +603 -0
- package/dist/cli/init.d.ts +26 -0
- package/dist/cli/init.js +835 -0
- package/dist/core/action.d.ts +37 -0
- package/dist/core/action.js +140 -0
- package/dist/core/config.d.ts +514 -0
- package/dist/core/config.js +221 -0
- package/dist/core/endpoints.d.ts +17 -0
- package/dist/core/endpoints.js +128 -0
- package/dist/core/token.d.ts +70 -0
- package/dist/core/token.js +174 -0
- package/dist/core/types.d.ts +450 -0
- package/dist/core/types.js +11 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +9 -0
- package/package.json +84 -0
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — LLM Helper
|
|
3
|
+
// Supports Anthropic, OpenAI, Gemini, Groq, OpenRouter,
|
|
4
|
+
// and the Duct hosted endpoint.
|
|
5
|
+
//
|
|
6
|
+
// Provider is auto-detected from available env vars, or set
|
|
7
|
+
// explicitly via LLM_PROVIDER. Model name is never hardcoded —
|
|
8
|
+
// always set LLM_MODEL in your environment.
|
|
9
|
+
// ============================================================
|
|
10
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
11
|
+
import { getActiveApiBase, getConfiguredDashboard, } from "../../core/endpoints.js";
|
|
12
|
+
// ----------------------------------------------------------------
|
|
13
|
+
// Provider resolution
|
|
14
|
+
// ----------------------------------------------------------------
|
|
15
|
+
function resolveProvider() {
|
|
16
|
+
const explicitProvider = process.env["LLM_PROVIDER"]?.toLowerCase();
|
|
17
|
+
const model = process.env["LLM_MODEL"];
|
|
18
|
+
const keys = {
|
|
19
|
+
anthropic: process.env["ANTHROPIC_API_KEY"],
|
|
20
|
+
openai: process.env["OPENAI_API_KEY"],
|
|
21
|
+
gemini: process.env["GEMINI_API_KEY"],
|
|
22
|
+
groq: process.env["GROQ_API_KEY"],
|
|
23
|
+
openrouter: process.env["OPENROUTER_API_KEY"],
|
|
24
|
+
duct: process.env["DUCT_API_KEY"],
|
|
25
|
+
};
|
|
26
|
+
// Explicit provider wins
|
|
27
|
+
if (explicitProvider) {
|
|
28
|
+
const key = keys[explicitProvider];
|
|
29
|
+
if (!key) {
|
|
30
|
+
throw new Error(`LLM_PROVIDER is set to "${explicitProvider}" but the corresponding API key is missing.\n\n` +
|
|
31
|
+
providerKeyHint(explicitProvider));
|
|
32
|
+
}
|
|
33
|
+
if (!model && explicitProvider !== "duct") {
|
|
34
|
+
throw new Error(`LLM_MODEL is not set.\n\nSet LLM_MODEL to the model name you want to use with ${explicitProvider}.\n` +
|
|
35
|
+
`Example: LLM_MODEL=your-preferred-model`);
|
|
36
|
+
}
|
|
37
|
+
return { provider: explicitProvider, apiKey: key, model: model ?? "" };
|
|
38
|
+
}
|
|
39
|
+
// Auto-detect: first key that's set wins (duct → anthropic → openai → gemini → groq → openrouter)
|
|
40
|
+
const autoOrder = ["duct", "anthropic", "openai", "gemini", "groq", "openrouter"];
|
|
41
|
+
for (const p of autoOrder) {
|
|
42
|
+
const key = keys[p];
|
|
43
|
+
if (key) {
|
|
44
|
+
if (!model && p !== "duct") {
|
|
45
|
+
throw new Error(`LLM_MODEL is not set.\n\nAuto-detected provider "${p}" from your environment, but LLM_MODEL is required.\n` +
|
|
46
|
+
`Set LLM_MODEL to the model name you want to use.\nExample: LLM_MODEL=your-preferred-model`);
|
|
47
|
+
}
|
|
48
|
+
return { provider: p, apiKey: key, model: model ?? "" };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const dashboardUrl = getConfiguredDashboard();
|
|
52
|
+
throw new Error(`No API key configured for the Duct agent pipeline.\n\n` +
|
|
53
|
+
`Set one of the following environment variables:\n` +
|
|
54
|
+
` ANTHROPIC_API_KEY — Anthropic Claude\n` +
|
|
55
|
+
` OPENAI_API_KEY — OpenAI\n` +
|
|
56
|
+
` GEMINI_API_KEY — Google Gemini\n` +
|
|
57
|
+
` GROQ_API_KEY — Groq\n` +
|
|
58
|
+
` OPENROUTER_API_KEY — OpenRouter\n` +
|
|
59
|
+
` DUCT_API_KEY — Duct hosted AI endpoint (requires Duct hosted LLM API)\n\n` +
|
|
60
|
+
`Also set LLM_MODEL to the model you want to use (e.g. LLM_MODEL=your-preferred-model).\n` +
|
|
61
|
+
`For local development, prefer ANTHROPIC_API_KEY/OPENAI_API_KEY/etc.\n` +
|
|
62
|
+
`Dashboard: ${dashboardUrl}`);
|
|
63
|
+
}
|
|
64
|
+
function providerKeyHint(provider) {
|
|
65
|
+
const hints = {
|
|
66
|
+
anthropic: "Set ANTHROPIC_API_KEY",
|
|
67
|
+
openai: "Set OPENAI_API_KEY",
|
|
68
|
+
gemini: "Set GEMINI_API_KEY",
|
|
69
|
+
groq: "Set GROQ_API_KEY",
|
|
70
|
+
openrouter: "Set OPENROUTER_API_KEY",
|
|
71
|
+
duct: "Set DUCT_API_KEY",
|
|
72
|
+
};
|
|
73
|
+
return hints[provider] ?? "";
|
|
74
|
+
}
|
|
75
|
+
// ----------------------------------------------------------------
|
|
76
|
+
// callDuctLLM — public entry point
|
|
77
|
+
// ----------------------------------------------------------------
|
|
78
|
+
/**
|
|
79
|
+
* Call an LLM for the Duct agent pipeline.
|
|
80
|
+
*
|
|
81
|
+
* Provider is resolved in this order:
|
|
82
|
+
* 1. LLM_PROVIDER env var (explicit)
|
|
83
|
+
* 2. First available API key: DUCT_API_KEY → ANTHROPIC_API_KEY → OPENAI_API_KEY
|
|
84
|
+
* → GEMINI_API_KEY → GROQ_API_KEY → OPENROUTER_API_KEY
|
|
85
|
+
*
|
|
86
|
+
* Model name is always taken from LLM_MODEL — never hardcoded.
|
|
87
|
+
*
|
|
88
|
+
* @throws {Error} If no API key or LLM_MODEL is configured
|
|
89
|
+
*/
|
|
90
|
+
export async function callDuctLLM(options) {
|
|
91
|
+
const { agentName, systemPrompt, userPrompt, outputSchema, maxTokens = 4096, maxRetries = 3, } = options;
|
|
92
|
+
const { provider, apiKey, model } = resolveProvider();
|
|
93
|
+
const fullSystemPrompt = `${systemPrompt}
|
|
94
|
+
|
|
95
|
+
You are the ${agentName} agent in the Duct SDK pipeline. Your job is to analyze a codebase and produce structured output.
|
|
96
|
+
|
|
97
|
+
IMPORTANT OUTPUT RULES:
|
|
98
|
+
1. Respond with ONLY valid JSON — no markdown, no prose, no code fences
|
|
99
|
+
2. Your output must exactly match this schema:
|
|
100
|
+
${outputSchema}
|
|
101
|
+
3. Be thorough but concise. Prefer accuracy over completeness.
|
|
102
|
+
4. If you're uncertain about a value, use a sensible default rather than omitting it.`;
|
|
103
|
+
let lastError = null;
|
|
104
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
105
|
+
try {
|
|
106
|
+
switch (provider) {
|
|
107
|
+
case "anthropic":
|
|
108
|
+
return await callAnthropic({ apiKey, model, systemPrompt: fullSystemPrompt, userPrompt, maxTokens });
|
|
109
|
+
case "openai":
|
|
110
|
+
return await callOpenAICompatible({ apiKey, model, systemPrompt: fullSystemPrompt, userPrompt, maxTokens, baseUrl: "https://api.openai.com/v1" });
|
|
111
|
+
case "gemini":
|
|
112
|
+
return await callGemini({ apiKey, model, systemPrompt: fullSystemPrompt, userPrompt, maxTokens });
|
|
113
|
+
case "groq":
|
|
114
|
+
return await callOpenAICompatible({ apiKey, model, systemPrompt: fullSystemPrompt, userPrompt, maxTokens, baseUrl: "https://api.groq.com/openai/v1" });
|
|
115
|
+
case "openrouter":
|
|
116
|
+
return await callOpenAICompatible({ apiKey, model, systemPrompt: fullSystemPrompt, userPrompt, maxTokens, baseUrl: process.env["OPENROUTER_BASE_URL"] ?? "https://openrouter.ai/api/v1" });
|
|
117
|
+
case "duct":
|
|
118
|
+
return await callDuctEndpoint({ apiKey, agentName, systemPrompt: fullSystemPrompt, userPrompt, maxTokens });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
123
|
+
if (attempt < maxRetries) {
|
|
124
|
+
await sleep(Math.pow(2, attempt - 1) * 1000);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
throw new Error(`${agentName} failed after ${maxRetries} attempts: ${lastError?.message ?? "Unknown error"}`);
|
|
130
|
+
}
|
|
131
|
+
// ----------------------------------------------------------------
|
|
132
|
+
// Anthropic
|
|
133
|
+
// ----------------------------------------------------------------
|
|
134
|
+
async function callAnthropic(options) {
|
|
135
|
+
const client = new Anthropic({ apiKey: options.apiKey });
|
|
136
|
+
const message = await client.messages.create({
|
|
137
|
+
model: options.model,
|
|
138
|
+
max_tokens: options.maxTokens,
|
|
139
|
+
system: options.systemPrompt,
|
|
140
|
+
messages: [{ role: "user", content: options.userPrompt }],
|
|
141
|
+
});
|
|
142
|
+
const textBlock = message.content.find((b) => b.type === "text");
|
|
143
|
+
if (!textBlock || textBlock.type !== "text") {
|
|
144
|
+
throw new Error("Anthropic returned no text content");
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
text: textBlock.text.trim(),
|
|
148
|
+
parsed: parseJSONResponse(textBlock.text.trim()),
|
|
149
|
+
inputTokens: message.usage.input_tokens,
|
|
150
|
+
outputTokens: message.usage.output_tokens,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
// ----------------------------------------------------------------
|
|
154
|
+
// OpenAI-compatible (OpenAI, Groq, OpenRouter)
|
|
155
|
+
// ----------------------------------------------------------------
|
|
156
|
+
async function callOpenAICompatible(options) {
|
|
157
|
+
const response = await fetch(`${options.baseUrl}/chat/completions`, {
|
|
158
|
+
method: "POST",
|
|
159
|
+
headers: {
|
|
160
|
+
"Content-Type": "application/json",
|
|
161
|
+
"Authorization": `Bearer ${options.apiKey}`,
|
|
162
|
+
},
|
|
163
|
+
body: JSON.stringify({
|
|
164
|
+
model: options.model,
|
|
165
|
+
max_tokens: options.maxTokens,
|
|
166
|
+
messages: [
|
|
167
|
+
{ role: "system", content: options.systemPrompt },
|
|
168
|
+
{ role: "user", content: options.userPrompt },
|
|
169
|
+
],
|
|
170
|
+
response_format: { type: "json_object" },
|
|
171
|
+
}),
|
|
172
|
+
});
|
|
173
|
+
if (!response.ok) {
|
|
174
|
+
const body = await response.text();
|
|
175
|
+
throw new Error(`OpenAI-compatible API error (${response.status}): ${body}`);
|
|
176
|
+
}
|
|
177
|
+
const data = await response.json();
|
|
178
|
+
const text = (data.choices[0]?.message?.content ?? "").trim();
|
|
179
|
+
return {
|
|
180
|
+
text,
|
|
181
|
+
parsed: parseJSONResponse(text),
|
|
182
|
+
inputTokens: data.usage?.prompt_tokens ?? 0,
|
|
183
|
+
outputTokens: data.usage?.completion_tokens ?? 0,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
// ----------------------------------------------------------------
|
|
187
|
+
// Gemini
|
|
188
|
+
// ----------------------------------------------------------------
|
|
189
|
+
async function callGemini(options) {
|
|
190
|
+
const url = `https://generativelanguage.googleapis.com/v1beta/models/${options.model}:generateContent?key=${options.apiKey}`;
|
|
191
|
+
const response = await fetch(url, {
|
|
192
|
+
method: "POST",
|
|
193
|
+
headers: { "Content-Type": "application/json" },
|
|
194
|
+
body: JSON.stringify({
|
|
195
|
+
system_instruction: { parts: [{ text: options.systemPrompt }] },
|
|
196
|
+
contents: [{ parts: [{ text: options.userPrompt }] }],
|
|
197
|
+
generationConfig: {
|
|
198
|
+
maxOutputTokens: options.maxTokens,
|
|
199
|
+
responseMimeType: "application/json",
|
|
200
|
+
},
|
|
201
|
+
}),
|
|
202
|
+
});
|
|
203
|
+
if (!response.ok) {
|
|
204
|
+
const body = await response.text();
|
|
205
|
+
throw new Error(`Gemini API error (${response.status}): ${body}`);
|
|
206
|
+
}
|
|
207
|
+
const data = await response.json();
|
|
208
|
+
const text = (data.candidates[0]?.content?.parts[0]?.text ?? "").trim();
|
|
209
|
+
return {
|
|
210
|
+
text,
|
|
211
|
+
parsed: parseJSONResponse(text),
|
|
212
|
+
inputTokens: data.usageMetadata?.promptTokenCount ?? 0,
|
|
213
|
+
outputTokens: data.usageMetadata?.candidatesTokenCount ?? 0,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
// ----------------------------------------------------------------
|
|
217
|
+
// Duct hosted endpoint
|
|
218
|
+
// ----------------------------------------------------------------
|
|
219
|
+
async function callDuctEndpoint(options) {
|
|
220
|
+
const ductApiBase = getActiveApiBase();
|
|
221
|
+
const response = await fetch(`${ductApiBase}/v1/agent/complete`, {
|
|
222
|
+
method: "POST",
|
|
223
|
+
headers: {
|
|
224
|
+
"Content-Type": "application/json",
|
|
225
|
+
"Authorization": `Bearer ${options.apiKey}`,
|
|
226
|
+
"X-Duct-Agent": options.agentName,
|
|
227
|
+
},
|
|
228
|
+
body: JSON.stringify({
|
|
229
|
+
system: options.systemPrompt,
|
|
230
|
+
user: options.userPrompt,
|
|
231
|
+
max_tokens: options.maxTokens,
|
|
232
|
+
}),
|
|
233
|
+
});
|
|
234
|
+
if (!response.ok) {
|
|
235
|
+
const body = await response.text();
|
|
236
|
+
throw new Error(`Duct API error (${response.status}): ${body}`);
|
|
237
|
+
}
|
|
238
|
+
const data = await response.json();
|
|
239
|
+
const text = (data.text ?? data.content ?? "").trim();
|
|
240
|
+
return {
|
|
241
|
+
text,
|
|
242
|
+
parsed: parseJSONResponse(text),
|
|
243
|
+
inputTokens: data.usage?.input_tokens ?? 0,
|
|
244
|
+
outputTokens: data.usage?.output_tokens ?? 0,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
// ----------------------------------------------------------------
|
|
248
|
+
// Helpers
|
|
249
|
+
// ----------------------------------------------------------------
|
|
250
|
+
function parseJSONResponse(text) {
|
|
251
|
+
let cleaned = text.trim();
|
|
252
|
+
if (cleaned.startsWith("```")) {
|
|
253
|
+
cleaned = cleaned
|
|
254
|
+
.replace(/^```(?:json)?\s*/i, "")
|
|
255
|
+
.replace(/\s*```\s*$/, "")
|
|
256
|
+
.trim();
|
|
257
|
+
}
|
|
258
|
+
try {
|
|
259
|
+
return JSON.parse(cleaned);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
const jsonMatch = cleaned.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
|
|
263
|
+
if (jsonMatch) {
|
|
264
|
+
try {
|
|
265
|
+
return JSON.parse(jsonMatch[0]);
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
// Fall through
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
throw new Error(`LLM returned invalid JSON. First 500 chars: ${cleaned.slice(0, 500)}`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function sleep(ms) {
|
|
275
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
276
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { EventEmitter } from "events";
|
|
2
|
+
import type { SandboxFS } from "../fs/sandbox.js";
|
|
3
|
+
import type { RouteManifest, ActionManifest, AuthSchema, DeeplinkDefinition, ReviewResult } from "../../core/types.js";
|
|
4
|
+
export interface PipelineOptions {
|
|
5
|
+
/** Override specific agents */
|
|
6
|
+
skipAgents?: Array<"routes" | "actions" | "auth" | "deeplinks" | "review">;
|
|
7
|
+
/** Custom event emitter for progress events */
|
|
8
|
+
emitter?: PipelineEmitter;
|
|
9
|
+
/** Timeout in ms per agent (default: 120_000) */
|
|
10
|
+
agentTimeout?: number;
|
|
11
|
+
}
|
|
12
|
+
export interface PipelineResult {
|
|
13
|
+
routes: RouteManifest[];
|
|
14
|
+
actions: ActionManifest[];
|
|
15
|
+
auth: AuthSchema;
|
|
16
|
+
deeplinks: DeeplinkDefinition[];
|
|
17
|
+
review: ReviewResult;
|
|
18
|
+
confidenceScore: number;
|
|
19
|
+
/** Duration in ms */
|
|
20
|
+
durationMs: number;
|
|
21
|
+
}
|
|
22
|
+
export type PipelineEventType = "start" | "agent:start" | "agent:complete" | "agent:error" | "complete" | "error";
|
|
23
|
+
export interface PipelineEvent {
|
|
24
|
+
type: PipelineEventType;
|
|
25
|
+
agent?: string;
|
|
26
|
+
message?: string;
|
|
27
|
+
result?: unknown;
|
|
28
|
+
error?: Error;
|
|
29
|
+
progress?: number;
|
|
30
|
+
}
|
|
31
|
+
export type PipelineEventHandler = (event: PipelineEvent) => void;
|
|
32
|
+
export interface PipelineEmitter {
|
|
33
|
+
emitEvent(event: PipelineEvent): void;
|
|
34
|
+
}
|
|
35
|
+
export declare class DuctPipelineEmitter extends EventEmitter {
|
|
36
|
+
emitEvent(event: PipelineEvent): void;
|
|
37
|
+
on(eventName: string | symbol, listener: (...args: any[]) => void): this;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Run the full 5-agent pipeline to analyze a project and produce a DuctConfig.
|
|
41
|
+
*
|
|
42
|
+
* Pipeline stages:
|
|
43
|
+
* 1. Routes + API + Auth agents run in parallel
|
|
44
|
+
* 2. Deeplink agent runs with routes + actions results
|
|
45
|
+
* 3. Reviewer agent runs with all results
|
|
46
|
+
*
|
|
47
|
+
* @param sandboxFs - Sandboxed filesystem for the project
|
|
48
|
+
* @param opts - Pipeline options
|
|
49
|
+
* @returns PipelineResult with all agent outputs
|
|
50
|
+
*/
|
|
51
|
+
export declare function runAgentPipeline(sandboxFs: SandboxFS, opts?: PipelineOptions): Promise<PipelineResult>;
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// ============================================================
|
|
2
|
+
// @duct/sdk — Agent Pipeline Orchestrator
|
|
3
|
+
// Runs the 5-agent pipeline to analyze a codebase
|
|
4
|
+
// ============================================================
|
|
5
|
+
import { EventEmitter } from "events";
|
|
6
|
+
import { runRouteAgent } from "./route-agent.js";
|
|
7
|
+
import { runApiAgent } from "./api-agent.js";
|
|
8
|
+
import { runAuthAgent } from "./auth-agent.js";
|
|
9
|
+
import { runDeeplinkAgent } from "./deeplink-agent.js";
|
|
10
|
+
import { runReviewerAgent } from "./reviewer-agent.js";
|
|
11
|
+
// ----------------------------------------------------------------
|
|
12
|
+
// Default emitter (uses Node EventEmitter)
|
|
13
|
+
// ----------------------------------------------------------------
|
|
14
|
+
export class DuctPipelineEmitter extends EventEmitter {
|
|
15
|
+
emitEvent(event) {
|
|
16
|
+
super.emit("event", event);
|
|
17
|
+
}
|
|
18
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
19
|
+
on(eventName, listener) {
|
|
20
|
+
return super.on(eventName, listener);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
// ----------------------------------------------------------------
|
|
24
|
+
// Agent runner with timeout
|
|
25
|
+
// ----------------------------------------------------------------
|
|
26
|
+
async function withTimeout(fn, timeoutMs, agentName) {
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
const timer = setTimeout(() => {
|
|
29
|
+
reject(new Error(`${agentName} timed out after ${timeoutMs / 1000}s. ` +
|
|
30
|
+
"Your project may be very large. Try running with --no-agents to use the blank template."));
|
|
31
|
+
}, timeoutMs);
|
|
32
|
+
fn()
|
|
33
|
+
.then((result) => {
|
|
34
|
+
clearTimeout(timer);
|
|
35
|
+
resolve(result);
|
|
36
|
+
})
|
|
37
|
+
.catch((err) => {
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
reject(err);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
// ----------------------------------------------------------------
|
|
44
|
+
// Default values for skipped agents
|
|
45
|
+
// ----------------------------------------------------------------
|
|
46
|
+
function defaultRoutes() {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
function defaultActions() {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
function defaultAuth() {
|
|
53
|
+
return {
|
|
54
|
+
strategy: "unknown",
|
|
55
|
+
sessionFields: ["id", "email"],
|
|
56
|
+
guestAllowed: true,
|
|
57
|
+
tokenExpirySeconds: 300,
|
|
58
|
+
tokenEndpoint: "/api/duct/token",
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function defaultDeeplinks() {
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
function defaultReview() {
|
|
65
|
+
return {
|
|
66
|
+
passed: true,
|
|
67
|
+
confidenceScore: 0.5,
|
|
68
|
+
issues: [
|
|
69
|
+
{
|
|
70
|
+
code: "REVIEW_SKIPPED",
|
|
71
|
+
severity: "info",
|
|
72
|
+
message: "Review agent was skipped",
|
|
73
|
+
suggestion: "Run duct init without --no-agents for full analysis",
|
|
74
|
+
},
|
|
75
|
+
],
|
|
76
|
+
suggestions: [],
|
|
77
|
+
summary: "Review skipped.",
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
// ----------------------------------------------------------------
|
|
81
|
+
// runAgentPipeline
|
|
82
|
+
// ----------------------------------------------------------------
|
|
83
|
+
/**
|
|
84
|
+
* Run the full 5-agent pipeline to analyze a project and produce a DuctConfig.
|
|
85
|
+
*
|
|
86
|
+
* Pipeline stages:
|
|
87
|
+
* 1. Routes + API + Auth agents run in parallel
|
|
88
|
+
* 2. Deeplink agent runs with routes + actions results
|
|
89
|
+
* 3. Reviewer agent runs with all results
|
|
90
|
+
*
|
|
91
|
+
* @param sandboxFs - Sandboxed filesystem for the project
|
|
92
|
+
* @param opts - Pipeline options
|
|
93
|
+
* @returns PipelineResult with all agent outputs
|
|
94
|
+
*/
|
|
95
|
+
export async function runAgentPipeline(sandboxFs, opts = {}) {
|
|
96
|
+
const { skipAgents = [], emitter, agentTimeout = 120_000, } = opts;
|
|
97
|
+
const startTime = Date.now();
|
|
98
|
+
emitter?.emitEvent({ type: "start", message: "Starting Duct agent pipeline...", progress: 0 });
|
|
99
|
+
// ---- Stage 1: Parallel agents ----
|
|
100
|
+
let routes;
|
|
101
|
+
let actions;
|
|
102
|
+
let auth;
|
|
103
|
+
const stage1Agents = [
|
|
104
|
+
// Routes
|
|
105
|
+
(async () => {
|
|
106
|
+
if (skipAgents.includes("routes"))
|
|
107
|
+
return defaultRoutes();
|
|
108
|
+
emitter?.emitEvent({ type: "agent:start", agent: "RouteAgent", message: "Analyzing routes...", progress: 5 });
|
|
109
|
+
try {
|
|
110
|
+
const result = await withTimeout(() => runRouteAgent(sandboxFs), agentTimeout, "RouteAgent");
|
|
111
|
+
emitter?.emitEvent({
|
|
112
|
+
type: "agent:complete",
|
|
113
|
+
agent: "RouteAgent",
|
|
114
|
+
message: `Found ${result.length} routes`,
|
|
115
|
+
result,
|
|
116
|
+
progress: 30,
|
|
117
|
+
});
|
|
118
|
+
return result;
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
122
|
+
emitter?.emitEvent({ type: "agent:error", agent: "RouteAgent", error, progress: 30 });
|
|
123
|
+
return defaultRoutes();
|
|
124
|
+
}
|
|
125
|
+
})(),
|
|
126
|
+
// API/Actions
|
|
127
|
+
(async () => {
|
|
128
|
+
if (skipAgents.includes("actions"))
|
|
129
|
+
return defaultActions();
|
|
130
|
+
emitter?.emitEvent({ type: "agent:start", agent: "ApiAgent", message: "Analyzing API endpoints...", progress: 5 });
|
|
131
|
+
try {
|
|
132
|
+
const result = await withTimeout(() => runApiAgent(sandboxFs), agentTimeout, "ApiAgent");
|
|
133
|
+
emitter?.emitEvent({
|
|
134
|
+
type: "agent:complete",
|
|
135
|
+
agent: "ApiAgent",
|
|
136
|
+
message: `Found ${result.length} actions`,
|
|
137
|
+
result,
|
|
138
|
+
progress: 30,
|
|
139
|
+
});
|
|
140
|
+
return result;
|
|
141
|
+
}
|
|
142
|
+
catch (err) {
|
|
143
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
144
|
+
emitter?.emitEvent({ type: "agent:error", agent: "ApiAgent", error, progress: 30 });
|
|
145
|
+
return defaultActions();
|
|
146
|
+
}
|
|
147
|
+
})(),
|
|
148
|
+
// Auth
|
|
149
|
+
(async () => {
|
|
150
|
+
if (skipAgents.includes("auth"))
|
|
151
|
+
return defaultAuth();
|
|
152
|
+
emitter?.emitEvent({ type: "agent:start", agent: "AuthAgent", message: "Analyzing auth configuration...", progress: 5 });
|
|
153
|
+
try {
|
|
154
|
+
const result = await withTimeout(() => runAuthAgent(sandboxFs), agentTimeout, "AuthAgent");
|
|
155
|
+
emitter?.emitEvent({
|
|
156
|
+
type: "agent:complete",
|
|
157
|
+
agent: "AuthAgent",
|
|
158
|
+
message: `Detected auth: ${result.strategy}`,
|
|
159
|
+
result,
|
|
160
|
+
progress: 30,
|
|
161
|
+
});
|
|
162
|
+
return result;
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
166
|
+
emitter?.emitEvent({ type: "agent:error", agent: "AuthAgent", error, progress: 30 });
|
|
167
|
+
return defaultAuth();
|
|
168
|
+
}
|
|
169
|
+
})(),
|
|
170
|
+
];
|
|
171
|
+
[routes, actions, auth] = await Promise.all(stage1Agents);
|
|
172
|
+
emitter?.emitEvent({ type: "agent:complete", message: "Stage 1 complete (routes, actions, auth)", progress: 60 });
|
|
173
|
+
// ---- Stage 2: Deeplink agent ----
|
|
174
|
+
let deeplinks;
|
|
175
|
+
if (skipAgents.includes("deeplinks")) {
|
|
176
|
+
deeplinks = defaultDeeplinks();
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
emitter?.emitEvent({ type: "agent:start", agent: "DeeplinkAgent", message: "Proposing deeplinks...", progress: 65 });
|
|
180
|
+
try {
|
|
181
|
+
deeplinks = await withTimeout(() => runDeeplinkAgent(routes, actions), agentTimeout, "DeeplinkAgent");
|
|
182
|
+
emitter?.emitEvent({
|
|
183
|
+
type: "agent:complete",
|
|
184
|
+
agent: "DeeplinkAgent",
|
|
185
|
+
message: `Proposed ${deeplinks.length} deeplinks`,
|
|
186
|
+
result: deeplinks,
|
|
187
|
+
progress: 80,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
catch (err) {
|
|
191
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
192
|
+
emitter?.emitEvent({ type: "agent:error", agent: "DeeplinkAgent", error, progress: 80 });
|
|
193
|
+
deeplinks = defaultDeeplinks();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// ---- Stage 3: Reviewer agent ----
|
|
197
|
+
let review;
|
|
198
|
+
if (skipAgents.includes("review")) {
|
|
199
|
+
review = defaultReview();
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
emitter?.emitEvent({ type: "agent:start", agent: "ReviewerAgent", message: "Reviewing configuration...", progress: 85 });
|
|
203
|
+
try {
|
|
204
|
+
review = await withTimeout(() => runReviewerAgent({ routes, actions, auth, deeplinks }), agentTimeout, "ReviewerAgent");
|
|
205
|
+
emitter?.emitEvent({
|
|
206
|
+
type: "agent:complete",
|
|
207
|
+
agent: "ReviewerAgent",
|
|
208
|
+
message: review.summary,
|
|
209
|
+
result: review,
|
|
210
|
+
progress: 100,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
215
|
+
emitter?.emitEvent({ type: "agent:error", agent: "ReviewerAgent", error, progress: 100 });
|
|
216
|
+
review = defaultReview();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const durationMs = Date.now() - startTime;
|
|
220
|
+
const pipelineResult = {
|
|
221
|
+
routes,
|
|
222
|
+
actions,
|
|
223
|
+
auth,
|
|
224
|
+
deeplinks,
|
|
225
|
+
review,
|
|
226
|
+
confidenceScore: review.confidenceScore,
|
|
227
|
+
durationMs,
|
|
228
|
+
};
|
|
229
|
+
emitter?.emitEvent({
|
|
230
|
+
type: "complete",
|
|
231
|
+
message: `Pipeline complete in ${(durationMs / 1000).toFixed(1)}s`,
|
|
232
|
+
result: pipelineResult,
|
|
233
|
+
progress: 100,
|
|
234
|
+
});
|
|
235
|
+
return pipelineResult;
|
|
236
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { RouteManifest, ActionManifest, AuthSchema, DeeplinkDefinition, ReviewResult } from "../../core/types.js";
|
|
2
|
+
export interface ReviewAgentInput {
|
|
3
|
+
routes: RouteManifest[];
|
|
4
|
+
actions: ActionManifest[];
|
|
5
|
+
auth: AuthSchema;
|
|
6
|
+
deeplinks: DeeplinkDefinition[];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Run the Reviewer Agent to validate and score the pipeline output.
|
|
10
|
+
*/
|
|
11
|
+
export declare function runReviewerAgent(input: ReviewAgentInput): Promise<ReviewResult>;
|