@nathapp/nax 0.40.0 → 0.41.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/dist/nax.js +1166 -277
- package/package.json +2 -2
- package/src/acceptance/fix-generator.ts +4 -35
- package/src/acceptance/generator.ts +27 -28
- package/src/acceptance/refinement.ts +72 -5
- package/src/acceptance/templates/cli.ts +47 -0
- package/src/acceptance/templates/component.ts +78 -0
- package/src/acceptance/templates/e2e.ts +43 -0
- package/src/acceptance/templates/index.ts +21 -0
- package/src/acceptance/templates/snapshot.ts +50 -0
- package/src/acceptance/templates/unit.ts +48 -0
- package/src/acceptance/types.ts +9 -1
- package/src/agents/acp/adapter.ts +644 -0
- package/src/agents/acp/cost.ts +79 -0
- package/src/agents/acp/index.ts +9 -0
- package/src/agents/acp/interaction-bridge.ts +126 -0
- package/src/agents/acp/parser.ts +166 -0
- package/src/agents/acp/spawn-client.ts +309 -0
- package/src/agents/acp/types.ts +22 -0
- package/src/agents/claude-complete.ts +3 -3
- package/src/agents/registry.ts +83 -0
- package/src/agents/types-extended.ts +23 -0
- package/src/agents/types.ts +17 -0
- package/src/cli/analyze.ts +6 -2
- package/src/cli/init-detect.ts +94 -8
- package/src/cli/init.ts +2 -2
- package/src/cli/plan.ts +23 -0
- package/src/config/defaults.ts +1 -0
- package/src/config/index.ts +1 -1
- package/src/config/runtime-types.ts +17 -0
- package/src/config/schema.ts +3 -1
- package/src/config/schemas.ts +9 -1
- package/src/config/types.ts +2 -0
- package/src/execution/executor-types.ts +6 -0
- package/src/execution/iteration-runner.ts +2 -0
- package/src/execution/lifecycle/acceptance-loop.ts +5 -2
- package/src/execution/lifecycle/run-initialization.ts +16 -4
- package/src/execution/lifecycle/run-setup.ts +4 -0
- package/src/execution/runner-completion.ts +11 -1
- package/src/execution/runner-execution.ts +8 -0
- package/src/execution/runner-setup.ts +4 -0
- package/src/execution/runner.ts +10 -0
- package/src/pipeline/stages/acceptance-setup.ts +4 -0
- package/src/pipeline/stages/execution.ts +33 -1
- package/src/pipeline/stages/routing.ts +18 -7
- package/src/pipeline/types.ts +10 -0
- package/src/tdd/orchestrator.ts +7 -0
- package/src/tdd/rectification-gate.ts +6 -0
- package/src/tdd/session-runner.ts +4 -0
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACP Agent Adapter — implements AgentAdapter interface via ACP session protocol.
|
|
3
|
+
*
|
|
4
|
+
* All methods use the createClient injectable as the transport layer.
|
|
5
|
+
* Session lifecycle (naming, persistence, ensure/close) is handled by
|
|
6
|
+
* thin wrapper functions on top of AcpClient/AcpSession.
|
|
7
|
+
*
|
|
8
|
+
* Session naming: nax-<gitRootHash8>-<feature>-<story>[-<role>]
|
|
9
|
+
* Persistence: nax/features/<feature>/acp-sessions.json sidecar
|
|
10
|
+
*
|
|
11
|
+
* See: docs/specs/acp-session-mode.md
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { getSafeLogger } from "../../logger";
|
|
17
|
+
import { buildDecomposePrompt, parseDecomposeOutput } from "../claude-decompose";
|
|
18
|
+
import { createSpawnAcpClient } from "./spawn-client";
|
|
19
|
+
|
|
20
|
+
import type {
|
|
21
|
+
AgentAdapter,
|
|
22
|
+
AgentCapabilities,
|
|
23
|
+
AgentResult,
|
|
24
|
+
AgentRunOptions,
|
|
25
|
+
CompleteOptions,
|
|
26
|
+
DecomposeOptions,
|
|
27
|
+
DecomposeResult,
|
|
28
|
+
PlanOptions,
|
|
29
|
+
PlanResult,
|
|
30
|
+
} from "../types";
|
|
31
|
+
import { CompleteError } from "../types";
|
|
32
|
+
import { estimateCostFromTokenUsage } from "./cost";
|
|
33
|
+
import type { AgentRegistryEntry } from "./types";
|
|
34
|
+
|
|
35
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
36
|
+
// Constants
|
|
37
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
38
|
+
|
|
39
|
+
const MAX_AGENT_OUTPUT_CHARS = 5000;
|
|
40
|
+
const MAX_RATE_LIMIT_RETRIES = 3;
|
|
41
|
+
const INTERACTION_TIMEOUT_MS = 5 * 60 * 1000; // 5 min for human to respond
|
|
42
|
+
|
|
43
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
44
|
+
// Agent registry
|
|
45
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
const AGENT_REGISTRY: Record<string, AgentRegistryEntry> = {
|
|
48
|
+
claude: {
|
|
49
|
+
binary: "claude",
|
|
50
|
+
displayName: "Claude Code (ACP)",
|
|
51
|
+
supportedTiers: ["fast", "balanced", "powerful"],
|
|
52
|
+
maxContextTokens: 200_000,
|
|
53
|
+
},
|
|
54
|
+
codex: {
|
|
55
|
+
binary: "codex",
|
|
56
|
+
displayName: "OpenAI Codex (ACP)",
|
|
57
|
+
supportedTiers: ["fast", "balanced"],
|
|
58
|
+
maxContextTokens: 128_000,
|
|
59
|
+
},
|
|
60
|
+
gemini: {
|
|
61
|
+
binary: "gemini",
|
|
62
|
+
displayName: "Gemini CLI (ACP)",
|
|
63
|
+
supportedTiers: ["fast", "balanced", "powerful"],
|
|
64
|
+
maxContextTokens: 1_000_000,
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const DEFAULT_ENTRY: AgentRegistryEntry = {
|
|
69
|
+
binary: "claude",
|
|
70
|
+
displayName: "ACP Agent",
|
|
71
|
+
supportedTiers: ["balanced"],
|
|
72
|
+
maxContextTokens: 128_000,
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
76
|
+
// ACP session interfaces
|
|
77
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
78
|
+
|
|
79
|
+
export interface AcpSessionResponse {
|
|
80
|
+
messages: Array<{ role: string; content: string }>;
|
|
81
|
+
stopReason: string;
|
|
82
|
+
cumulative_token_usage?: { input_tokens: number; output_tokens: number };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface AcpSession {
|
|
86
|
+
prompt(text: string): Promise<AcpSessionResponse>;
|
|
87
|
+
close(): Promise<void>;
|
|
88
|
+
cancelActivePrompt(): Promise<void>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface AcpClient {
|
|
92
|
+
start(): Promise<void>;
|
|
93
|
+
createSession(opts: { agentName: string; permissionMode: string; sessionName?: string }): Promise<AcpSession>;
|
|
94
|
+
/** Resume an existing named session. Returns null if the session is not found. */
|
|
95
|
+
loadSession?(sessionName: string): Promise<AcpSession | null>;
|
|
96
|
+
close(): Promise<void>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
100
|
+
// Injectable dependencies
|
|
101
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
102
|
+
|
|
103
|
+
export const _acpAdapterDeps = {
|
|
104
|
+
which(name: string): string | null {
|
|
105
|
+
return Bun.which(name);
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
async sleep(ms: number): Promise<void> {
|
|
109
|
+
await Bun.sleep(ms);
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Create an ACP client for the given command string.
|
|
114
|
+
* Default: spawn-based client (shells out to acpx CLI).
|
|
115
|
+
* Override in tests via: _acpAdapterDeps.createClient = mock(...)
|
|
116
|
+
*/
|
|
117
|
+
createClient(cmdStr: string, cwd?: string, timeoutSeconds?: number): AcpClient {
|
|
118
|
+
return createSpawnAcpClient(cmdStr, cwd, timeoutSeconds);
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
123
|
+
// Helpers
|
|
124
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
125
|
+
|
|
126
|
+
function resolveRegistryEntry(agentName: string): AgentRegistryEntry {
|
|
127
|
+
return AGENT_REGISTRY[agentName] ?? DEFAULT_ENTRY;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function isRateLimitError(err: unknown): boolean {
|
|
131
|
+
if (!(err instanceof Error)) return false;
|
|
132
|
+
const msg = err.message.toLowerCase();
|
|
133
|
+
return msg.includes("rate limit") || msg.includes("rate_limit") || msg.includes("429");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
137
|
+
// Session naming
|
|
138
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Build a deterministic ACP session name.
|
|
142
|
+
*
|
|
143
|
+
* Format: nax-<gitRootHash8>-<featureName>-<storyId>[-<sessionRole>]
|
|
144
|
+
*
|
|
145
|
+
* The workdir hash (first 8 chars of SHA-256) prevents cross-repo and
|
|
146
|
+
* cross-worktree session name collisions. Each git worktree has a distinct
|
|
147
|
+
* root path, so different worktrees of the same repo get different hashes.
|
|
148
|
+
*/
|
|
149
|
+
export function buildSessionName(
|
|
150
|
+
workdir: string,
|
|
151
|
+
featureName?: string,
|
|
152
|
+
storyId?: string,
|
|
153
|
+
sessionRole?: string,
|
|
154
|
+
): string {
|
|
155
|
+
const hash = createHash("sha256").update(workdir).digest("hex").slice(0, 8);
|
|
156
|
+
const sanitize = (s: string) =>
|
|
157
|
+
s
|
|
158
|
+
.replace(/[^a-z0-9]+/gi, "-")
|
|
159
|
+
.toLowerCase()
|
|
160
|
+
.replace(/^-+|-+$/g, "");
|
|
161
|
+
|
|
162
|
+
const parts = ["nax", hash];
|
|
163
|
+
if (featureName) parts.push(sanitize(featureName));
|
|
164
|
+
if (storyId) parts.push(sanitize(storyId));
|
|
165
|
+
if (sessionRole) parts.push(sanitize(sessionRole));
|
|
166
|
+
return parts.join("-");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
170
|
+
// Session lifecycle functions (createClient-backed)
|
|
171
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Ensure an ACP session exists: try to resume via loadSession, fall back to
|
|
175
|
+
* createSession. Returns the AcpSession ready for prompt() calls.
|
|
176
|
+
*/
|
|
177
|
+
export async function ensureAcpSession(
|
|
178
|
+
client: AcpClient,
|
|
179
|
+
sessionName: string,
|
|
180
|
+
agentName: string,
|
|
181
|
+
permissionMode: string,
|
|
182
|
+
): Promise<AcpSession> {
|
|
183
|
+
// Try to resume existing session first
|
|
184
|
+
if (client.loadSession) {
|
|
185
|
+
try {
|
|
186
|
+
const existing = await client.loadSession(sessionName);
|
|
187
|
+
if (existing) {
|
|
188
|
+
getSafeLogger()?.debug("acp-adapter", `Resumed existing session: ${sessionName}`);
|
|
189
|
+
return existing;
|
|
190
|
+
}
|
|
191
|
+
} catch {
|
|
192
|
+
// loadSession failed — fall through to createSession
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Create a new named session
|
|
197
|
+
getSafeLogger()?.debug("acp-adapter", `Creating new session: ${sessionName}`);
|
|
198
|
+
return client.createSession({ agentName, permissionMode, sessionName });
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Send a prompt turn to the session with timeout.
|
|
203
|
+
* If the timeout fires, attempts to cancel the active prompt and returns timedOut=true.
|
|
204
|
+
*/
|
|
205
|
+
export async function runSessionPrompt(
|
|
206
|
+
session: AcpSession,
|
|
207
|
+
prompt: string,
|
|
208
|
+
timeoutMs: number,
|
|
209
|
+
): Promise<{ response: AcpSessionResponse | null; timedOut: boolean }> {
|
|
210
|
+
const promptPromise = session.prompt(prompt);
|
|
211
|
+
const timeoutPromise = new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), timeoutMs));
|
|
212
|
+
|
|
213
|
+
const winner = await Promise.race([promptPromise, timeoutPromise]);
|
|
214
|
+
|
|
215
|
+
if (winner === "timeout") {
|
|
216
|
+
try {
|
|
217
|
+
await session.cancelActivePrompt();
|
|
218
|
+
} catch {
|
|
219
|
+
await session.close().catch(() => {});
|
|
220
|
+
}
|
|
221
|
+
return { response: null, timedOut: true };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return { response: winner as AcpSessionResponse, timedOut: false };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Close an ACP session — best-effort, swallows errors.
|
|
229
|
+
*/
|
|
230
|
+
export async function closeAcpSession(session: AcpSession): Promise<void> {
|
|
231
|
+
try {
|
|
232
|
+
await session.close();
|
|
233
|
+
} catch (err) {
|
|
234
|
+
getSafeLogger()?.warn("acp-adapter", "Failed to close session", { error: String(err) });
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
239
|
+
// ACP session sidecar persistence
|
|
240
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
241
|
+
|
|
242
|
+
/** Path to the ACP sessions sidecar file for a feature. */
|
|
243
|
+
function acpSessionsPath(workdir: string, featureName: string): string {
|
|
244
|
+
return join(workdir, "nax", "features", featureName, "acp-sessions.json");
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Persist a session name to the sidecar file. Best-effort — errors are swallowed. */
|
|
248
|
+
export async function saveAcpSession(
|
|
249
|
+
workdir: string,
|
|
250
|
+
featureName: string,
|
|
251
|
+
storyId: string,
|
|
252
|
+
sessionName: string,
|
|
253
|
+
): Promise<void> {
|
|
254
|
+
try {
|
|
255
|
+
const path = acpSessionsPath(workdir, featureName);
|
|
256
|
+
let data: Record<string, string> = {};
|
|
257
|
+
try {
|
|
258
|
+
const existing = await Bun.file(path).text();
|
|
259
|
+
data = JSON.parse(existing);
|
|
260
|
+
} catch {
|
|
261
|
+
// File doesn't exist yet — start fresh
|
|
262
|
+
}
|
|
263
|
+
data[storyId] = sessionName;
|
|
264
|
+
await Bun.write(path, JSON.stringify(data, null, 2));
|
|
265
|
+
} catch (err) {
|
|
266
|
+
getSafeLogger()?.warn("acp-adapter", "Failed to save session to sidecar", { error: String(err) });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Clear a session name from the sidecar file. Best-effort — errors are swallowed. */
|
|
271
|
+
export async function clearAcpSession(workdir: string, featureName: string, storyId: string): Promise<void> {
|
|
272
|
+
try {
|
|
273
|
+
const path = acpSessionsPath(workdir, featureName);
|
|
274
|
+
let data: Record<string, string> = {};
|
|
275
|
+
try {
|
|
276
|
+
const existing = await Bun.file(path).text();
|
|
277
|
+
data = JSON.parse(existing);
|
|
278
|
+
} catch {
|
|
279
|
+
return; // File doesn't exist — nothing to clear
|
|
280
|
+
}
|
|
281
|
+
delete data[storyId];
|
|
282
|
+
await Bun.write(path, JSON.stringify(data, null, 2));
|
|
283
|
+
} catch (err) {
|
|
284
|
+
getSafeLogger()?.warn("acp-adapter", "Failed to clear session from sidecar", { error: String(err) });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Read a persisted session name from the sidecar file. Returns null if not found. */
|
|
289
|
+
export async function readAcpSession(workdir: string, featureName: string, storyId: string): Promise<string | null> {
|
|
290
|
+
try {
|
|
291
|
+
const path = acpSessionsPath(workdir, featureName);
|
|
292
|
+
const existing = await Bun.file(path).text();
|
|
293
|
+
const data: Record<string, string> = JSON.parse(existing);
|
|
294
|
+
return data[storyId] ?? null;
|
|
295
|
+
} catch {
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
301
|
+
// Output helpers
|
|
302
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Extract combined assistant output text from a session response.
|
|
306
|
+
*/
|
|
307
|
+
function extractOutput(response: AcpSessionResponse | null): string {
|
|
308
|
+
if (!response) return "";
|
|
309
|
+
return response.messages
|
|
310
|
+
.filter((m) => m.role === "assistant")
|
|
311
|
+
.map((m) => m.content)
|
|
312
|
+
.join("\n")
|
|
313
|
+
.trim();
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Extract a question from agent output text, if present.
|
|
318
|
+
*/
|
|
319
|
+
function extractQuestion(output: string): string | null {
|
|
320
|
+
const text = output.trim();
|
|
321
|
+
if (!text) return null;
|
|
322
|
+
|
|
323
|
+
const sentences = text.split(/(?<=[.!?])\s+/);
|
|
324
|
+
const questionSentences = sentences.filter((s) => s.trim().endsWith("?"));
|
|
325
|
+
if (questionSentences.length > 0) {
|
|
326
|
+
const q = questionSentences[questionSentences.length - 1].trim();
|
|
327
|
+
if (q.length > 10) return q;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const lower = text.toLowerCase();
|
|
331
|
+
const markers = [
|
|
332
|
+
"please confirm",
|
|
333
|
+
"please specify",
|
|
334
|
+
"please provide",
|
|
335
|
+
"which would you",
|
|
336
|
+
"should i ",
|
|
337
|
+
"do you want",
|
|
338
|
+
"can you clarify",
|
|
339
|
+
];
|
|
340
|
+
for (const marker of markers) {
|
|
341
|
+
if (lower.includes(marker)) {
|
|
342
|
+
return text.slice(-200).trim();
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
350
|
+
// AcpAgentAdapter
|
|
351
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
352
|
+
|
|
353
|
+
export class AcpAgentAdapter implements AgentAdapter {
|
|
354
|
+
readonly name: string;
|
|
355
|
+
readonly displayName: string;
|
|
356
|
+
readonly binary: string;
|
|
357
|
+
readonly capabilities: AgentCapabilities;
|
|
358
|
+
|
|
359
|
+
constructor(agentName: string) {
|
|
360
|
+
const entry = resolveRegistryEntry(agentName);
|
|
361
|
+
this.name = agentName;
|
|
362
|
+
this.displayName = entry.displayName;
|
|
363
|
+
this.binary = entry.binary;
|
|
364
|
+
this.capabilities = {
|
|
365
|
+
supportedTiers: entry.supportedTiers,
|
|
366
|
+
maxContextTokens: entry.maxContextTokens,
|
|
367
|
+
features: new Set<"tdd" | "review" | "refactor" | "batch">(["tdd", "review", "refactor"]),
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async isInstalled(): Promise<boolean> {
|
|
372
|
+
const path = _acpAdapterDeps.which(this.binary);
|
|
373
|
+
return path !== null;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
buildCommand(_options: AgentRunOptions): string[] {
|
|
377
|
+
// ACP adapter uses createClient, not direct CLI invocation.
|
|
378
|
+
// Return a descriptive command for logging/display purposes only.
|
|
379
|
+
return ["acpx", this.name, "session"];
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
buildAllowedEnv(_options?: AgentRunOptions): Record<string, string | undefined> {
|
|
383
|
+
// createClient manages its own env; no separate env building needed.
|
|
384
|
+
return {};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async run(options: AgentRunOptions): Promise<AgentResult> {
|
|
388
|
+
const startTime = Date.now();
|
|
389
|
+
let lastError: Error | undefined;
|
|
390
|
+
|
|
391
|
+
getSafeLogger()?.debug("acp-adapter", `Starting run for ${this.name}`, {
|
|
392
|
+
model: options.modelDef.model,
|
|
393
|
+
workdir: options.workdir,
|
|
394
|
+
featureName: options.featureName,
|
|
395
|
+
storyId: options.storyId,
|
|
396
|
+
sessionRole: options.sessionRole,
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
for (let attempt = 0; attempt < MAX_RATE_LIMIT_RETRIES; attempt++) {
|
|
400
|
+
try {
|
|
401
|
+
const result = await this._runWithClient(options, startTime);
|
|
402
|
+
if (!result.success) {
|
|
403
|
+
getSafeLogger()?.warn("acp-adapter", `Run failed for ${this.name}`, { exitCode: result.exitCode });
|
|
404
|
+
}
|
|
405
|
+
return result;
|
|
406
|
+
} catch (err) {
|
|
407
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
408
|
+
lastError = error;
|
|
409
|
+
|
|
410
|
+
const shouldRetry = isRateLimitError(error) && attempt < MAX_RATE_LIMIT_RETRIES - 1;
|
|
411
|
+
if (!shouldRetry) break;
|
|
412
|
+
|
|
413
|
+
const backoffMs = 2 ** (attempt + 1) * 1000;
|
|
414
|
+
getSafeLogger()?.warn("acp-adapter", "Retrying after rate limit", {
|
|
415
|
+
backoffSeconds: backoffMs / 1000,
|
|
416
|
+
attempt: attempt + 1,
|
|
417
|
+
});
|
|
418
|
+
await _acpAdapterDeps.sleep(backoffMs);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const durationMs = Date.now() - startTime;
|
|
423
|
+
return {
|
|
424
|
+
success: false,
|
|
425
|
+
exitCode: 1,
|
|
426
|
+
output: lastError?.message ?? "Run failed",
|
|
427
|
+
rateLimited: isRateLimitError(lastError),
|
|
428
|
+
durationMs,
|
|
429
|
+
estimatedCost: 0,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private async _runWithClient(options: AgentRunOptions, startTime: number): Promise<AgentResult> {
|
|
434
|
+
const cmdStr = `acpx --model ${options.modelDef.model} ${this.name}`;
|
|
435
|
+
const client = _acpAdapterDeps.createClient(cmdStr, options.workdir, options.timeoutSeconds);
|
|
436
|
+
await client.start();
|
|
437
|
+
|
|
438
|
+
// 1. Resolve session name: explicit > sidecar > derived
|
|
439
|
+
let sessionName = options.acpSessionName;
|
|
440
|
+
if (!sessionName && options.featureName && options.storyId) {
|
|
441
|
+
sessionName = (await readAcpSession(options.workdir, options.featureName, options.storyId)) ?? undefined;
|
|
442
|
+
}
|
|
443
|
+
sessionName ??= buildSessionName(options.workdir, options.featureName, options.storyId, options.sessionRole);
|
|
444
|
+
|
|
445
|
+
// 2. Permission mode follows dangerouslySkipPermissions
|
|
446
|
+
const permissionMode = options.dangerouslySkipPermissions ? "approve-all" : "default";
|
|
447
|
+
|
|
448
|
+
// 3. Ensure session (resume existing or create new)
|
|
449
|
+
const session = await ensureAcpSession(client, sessionName, this.name, permissionMode);
|
|
450
|
+
|
|
451
|
+
// 4. Persist for plan→run continuity
|
|
452
|
+
if (options.featureName && options.storyId) {
|
|
453
|
+
await saveAcpSession(options.workdir, options.featureName, options.storyId, sessionName);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
let lastResponse: AcpSessionResponse | null = null;
|
|
457
|
+
let timedOut = false;
|
|
458
|
+
const totalTokenUsage = { input_tokens: 0, output_tokens: 0 };
|
|
459
|
+
|
|
460
|
+
try {
|
|
461
|
+
// 5. Multi-turn loop
|
|
462
|
+
let currentPrompt = options.prompt;
|
|
463
|
+
let turnCount = 0;
|
|
464
|
+
const MAX_TURNS = options.interactionBridge ? 10 : 1;
|
|
465
|
+
|
|
466
|
+
while (turnCount < MAX_TURNS) {
|
|
467
|
+
turnCount++;
|
|
468
|
+
getSafeLogger()?.debug("acp-adapter", `Session turn ${turnCount}/${MAX_TURNS}`, { sessionName });
|
|
469
|
+
|
|
470
|
+
const turnResult = await runSessionPrompt(session, currentPrompt, options.timeoutSeconds * 1000);
|
|
471
|
+
|
|
472
|
+
if (turnResult.timedOut) {
|
|
473
|
+
timedOut = true;
|
|
474
|
+
break;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
lastResponse = turnResult.response;
|
|
478
|
+
if (!lastResponse) break;
|
|
479
|
+
|
|
480
|
+
// Accumulate token usage
|
|
481
|
+
if (lastResponse.cumulative_token_usage) {
|
|
482
|
+
totalTokenUsage.input_tokens += lastResponse.cumulative_token_usage.input_tokens ?? 0;
|
|
483
|
+
totalTokenUsage.output_tokens += lastResponse.cumulative_token_usage.output_tokens ?? 0;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// Check for agent question → route to interaction bridge
|
|
487
|
+
const outputText = extractOutput(lastResponse);
|
|
488
|
+
const question = extractQuestion(outputText);
|
|
489
|
+
if (!question || !options.interactionBridge) break;
|
|
490
|
+
|
|
491
|
+
getSafeLogger()?.debug("acp-adapter", "Agent asked question, routing to interactionBridge", { question });
|
|
492
|
+
|
|
493
|
+
try {
|
|
494
|
+
const answer = await Promise.race([
|
|
495
|
+
options.interactionBridge.onQuestionDetected(question),
|
|
496
|
+
new Promise<never>((_, reject) =>
|
|
497
|
+
setTimeout(() => reject(new Error("interaction timeout")), INTERACTION_TIMEOUT_MS),
|
|
498
|
+
),
|
|
499
|
+
]);
|
|
500
|
+
currentPrompt = answer;
|
|
501
|
+
} catch (err) {
|
|
502
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
503
|
+
getSafeLogger()?.warn("acp-adapter", `InteractionBridge failed: ${msg}`);
|
|
504
|
+
break;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
if (turnCount >= MAX_TURNS) {
|
|
509
|
+
getSafeLogger()?.warn("acp-adapter", "Reached max turns limit", { sessionName, maxTurns: MAX_TURNS });
|
|
510
|
+
}
|
|
511
|
+
} finally {
|
|
512
|
+
// 6. Cleanup — always close session and client, then clear sidecar
|
|
513
|
+
await closeAcpSession(session);
|
|
514
|
+
await client.close().catch(() => {});
|
|
515
|
+
if (options.featureName && options.storyId) {
|
|
516
|
+
await clearAcpSession(options.workdir, options.featureName, options.storyId);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const durationMs = Date.now() - startTime;
|
|
521
|
+
|
|
522
|
+
if (timedOut) {
|
|
523
|
+
return {
|
|
524
|
+
success: false,
|
|
525
|
+
exitCode: 124,
|
|
526
|
+
output: `Session timed out after ${options.timeoutSeconds}s`,
|
|
527
|
+
rateLimited: false,
|
|
528
|
+
durationMs,
|
|
529
|
+
estimatedCost: 0,
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const success = lastResponse?.stopReason === "end_turn";
|
|
534
|
+
const output = extractOutput(lastResponse);
|
|
535
|
+
|
|
536
|
+
const estimatedCost =
|
|
537
|
+
totalTokenUsage.input_tokens > 0 || totalTokenUsage.output_tokens > 0
|
|
538
|
+
? estimateCostFromTokenUsage(totalTokenUsage, options.modelDef.model)
|
|
539
|
+
: 0;
|
|
540
|
+
|
|
541
|
+
return {
|
|
542
|
+
success,
|
|
543
|
+
exitCode: success ? 0 : 1,
|
|
544
|
+
output: output.slice(-MAX_AGENT_OUTPUT_CHARS),
|
|
545
|
+
rateLimited: false,
|
|
546
|
+
durationMs,
|
|
547
|
+
estimatedCost,
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
async complete(prompt: string, _options?: CompleteOptions): Promise<string> {
|
|
552
|
+
const model = _options?.model ?? "default";
|
|
553
|
+
const cmdStr = `acpx --model ${model} ${this.name}`;
|
|
554
|
+
const client = _acpAdapterDeps.createClient(cmdStr);
|
|
555
|
+
await client.start();
|
|
556
|
+
|
|
557
|
+
// complete() is one-shot — ephemeral session, no session name, no sidecar
|
|
558
|
+
const permissionMode = _options?.dangerouslySkipPermissions ? "approve-all" : "default";
|
|
559
|
+
|
|
560
|
+
let session: AcpSession | null = null;
|
|
561
|
+
try {
|
|
562
|
+
session = await client.createSession({ agentName: this.name, permissionMode });
|
|
563
|
+
const response = await session.prompt(prompt);
|
|
564
|
+
|
|
565
|
+
if (response.stopReason === "error") {
|
|
566
|
+
throw new CompleteError("complete() failed: stop reason is error");
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const text = response.messages
|
|
570
|
+
.filter((m) => m.role === "assistant")
|
|
571
|
+
.map((m) => m.content)
|
|
572
|
+
.join("\n")
|
|
573
|
+
.trim();
|
|
574
|
+
|
|
575
|
+
if (!text) {
|
|
576
|
+
throw new CompleteError("complete() returned empty output");
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
return text;
|
|
580
|
+
} finally {
|
|
581
|
+
if (session) {
|
|
582
|
+
await session.close().catch(() => {});
|
|
583
|
+
}
|
|
584
|
+
await client.close().catch(() => {});
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
async plan(options: PlanOptions): Promise<PlanResult> {
|
|
589
|
+
if (options.interactive) {
|
|
590
|
+
throw new Error("[acp-adapter] plan() interactive mode is not yet supported via ACP");
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const modelDef = options.modelDef ?? { provider: "anthropic", model: "default" };
|
|
594
|
+
// Timeout: from options, or config, or fallback to 600s
|
|
595
|
+
const timeoutSeconds =
|
|
596
|
+
options.timeoutSeconds ?? (options.config?.execution?.sessionTimeoutSeconds as number | undefined) ?? 600;
|
|
597
|
+
|
|
598
|
+
const result = await this.run({
|
|
599
|
+
prompt: options.prompt,
|
|
600
|
+
workdir: options.workdir,
|
|
601
|
+
modelTier: options.modelTier ?? "balanced",
|
|
602
|
+
modelDef,
|
|
603
|
+
timeoutSeconds,
|
|
604
|
+
dangerouslySkipPermissions: options.dangerouslySkipPermissions ?? false,
|
|
605
|
+
interactionBridge: options.interactionBridge,
|
|
606
|
+
featureName: options.featureName,
|
|
607
|
+
storyId: options.storyId,
|
|
608
|
+
sessionRole: options.sessionRole,
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
if (!result.success) {
|
|
612
|
+
throw new Error(`[acp-adapter] plan() failed: ${result.output}`);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
const specContent = result.output.trim();
|
|
616
|
+
if (!specContent) {
|
|
617
|
+
throw new Error("[acp-adapter] plan() returned empty spec content");
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
return { specContent };
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
async decompose(options: DecomposeOptions): Promise<DecomposeResult> {
|
|
624
|
+
const model = options.modelDef?.model;
|
|
625
|
+
const prompt = buildDecomposePrompt(options);
|
|
626
|
+
|
|
627
|
+
let output: string;
|
|
628
|
+
try {
|
|
629
|
+
output = await this.complete(prompt, { model, jsonMode: true });
|
|
630
|
+
} catch (err) {
|
|
631
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
632
|
+
throw new Error(`[acp-adapter] decompose() failed: ${msg}`, { cause: err });
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
let stories: ReturnType<typeof parseDecomposeOutput>;
|
|
636
|
+
try {
|
|
637
|
+
stories = parseDecomposeOutput(output);
|
|
638
|
+
} catch (err) {
|
|
639
|
+
throw new Error(`[acp-adapter] decompose() failed to parse stories: ${(err as Error).message}`, { cause: err });
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
return { stories };
|
|
643
|
+
}
|
|
644
|
+
}
|