@loucompanion/forge-bridge 0.1.1-dev.7d43998c4521 → 0.1.1-dev.af36c7fa102b
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 +1 -0
- package/dist/bridge/bridge.service.js +16 -3
- package/dist/bridge/bridge.types.d.ts +7 -0
- package/dist/cli/cli.service.d.ts +27 -2
- package/dist/cli/cli.service.js +399 -16
- package/dist/cli/local-config.d.ts +4 -1
- package/dist/cli/local-config.js +42 -7
- package/dist/session/index.d.ts +2 -0
- package/dist/session/index.js +1 -0
- package/dist/session/internals.d.ts +4 -2
- package/dist/session/internals.js +2 -1
- package/dist/session/phase-completion.d.ts +54 -0
- package/dist/session/phase-completion.js +692 -0
- package/dist/session/provider-cli/index.d.ts +2 -2
- package/dist/session/provider-cli/index.js +1 -1
- package/dist/session/provider-cli/provider-cli.base.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.service.d.ts +45 -1
- package/dist/session/provider-cli/provider-cli.service.js +602 -10
- package/dist/session/provider-cli/provider-cli.types.d.ts +1 -0
- package/dist/session/session.service.js +52 -10
- package/dist/session/session.types.d.ts +11 -0
- package/dist/session/session.types.js +47 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.d.ts +11 -0
- package/dist/worktree/artifact-injector.js +107 -0
- package/dist/worktree/dependency-warmer.d.ts +32 -0
- package/dist/worktree/dependency-warmer.js +297 -0
- package/dist/worktree/index.d.ts +2 -0
- package/dist/worktree/index.js +1 -0
- package/dist/worktree/worktree.service.d.ts +4 -0
- package/dist/worktree/worktree.service.js +173 -11
- package/dist/worktree/worktree.types.d.ts +5 -1
- package/package.json +1 -1
|
@@ -1,7 +1,216 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { execFile, spawn } from "node:child_process";
|
|
5
|
+
import readline from "node:readline";
|
|
6
|
+
import { promisify } from "node:util";
|
|
4
7
|
import { GitClient } from "../../shared/git/git.js";
|
|
8
|
+
import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
|
|
9
|
+
import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForPhase, prepareCompletionToolRuntime, readCompletionArtifact } from "../phase-completion.js";
|
|
10
|
+
const fakeWorkerModel = "server-local-fake-worker";
|
|
11
|
+
const execFileAsync = promisify(execFile);
|
|
12
|
+
export class RoutingProviderCliService {
|
|
13
|
+
realProvider;
|
|
14
|
+
deterministicProvider;
|
|
15
|
+
constructor(realProvider = new ProcessBackedProviderCliService(), deterministicProvider = new DeterministicProviderCliService()) {
|
|
16
|
+
this.realProvider = realProvider;
|
|
17
|
+
this.deterministicProvider = deterministicProvider;
|
|
18
|
+
}
|
|
19
|
+
async runImplementation(context) {
|
|
20
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
21
|
+
? await this.deterministicProvider.runImplementation(context)
|
|
22
|
+
: await this.realProvider.runImplementation(context);
|
|
23
|
+
}
|
|
24
|
+
async runConflictResolve(context) {
|
|
25
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
26
|
+
? await this.deterministicProvider.runConflictResolve(context)
|
|
27
|
+
: await this.realProvider.runConflictResolve(context);
|
|
28
|
+
}
|
|
29
|
+
async runQa(dispatch, emit, signal) {
|
|
30
|
+
return isFakeWorkerModel(dispatch.execution.model)
|
|
31
|
+
? await this.deterministicProvider.runQa(dispatch, emit, signal)
|
|
32
|
+
: await this.realProvider.runQa(dispatch, emit, signal);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export class ProcessBackedProviderCliService {
|
|
36
|
+
processRunner;
|
|
37
|
+
git;
|
|
38
|
+
constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient()) {
|
|
39
|
+
this.processRunner = processRunner;
|
|
40
|
+
this.git = git;
|
|
41
|
+
}
|
|
42
|
+
async runImplementation(context) {
|
|
43
|
+
const { dispatch, worktree } = context;
|
|
44
|
+
const phase = completionPhaseFromDispatch(dispatch);
|
|
45
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
46
|
+
await fs.mkdir(metadataRoot, { recursive: true });
|
|
47
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
48
|
+
if (!laneCommand) {
|
|
49
|
+
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
50
|
+
}
|
|
51
|
+
const specBody = buildSpecBody(laneCommand, dispatch.workItem, phase);
|
|
52
|
+
const specPath = path.join(metadataRoot, "spec.md");
|
|
53
|
+
await fs.writeFile(specPath, specBody, "utf8");
|
|
54
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
55
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
|
|
56
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
57
|
+
worktreePath: worktree.worktreePath,
|
|
58
|
+
prompt: buildImplementationPrompt(dispatch, phase),
|
|
59
|
+
completionTools
|
|
60
|
+
});
|
|
61
|
+
await context.emit({
|
|
62
|
+
role: "runner",
|
|
63
|
+
kind: "checkpoint",
|
|
64
|
+
content: `Starting provider CLI: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
|
|
65
|
+
eventType: "provider_cli_started"
|
|
66
|
+
});
|
|
67
|
+
await context.emit({
|
|
68
|
+
role: "runner",
|
|
69
|
+
kind: "checkpoint",
|
|
70
|
+
content: `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
|
|
71
|
+
eventType: "completion_tools_configured"
|
|
72
|
+
});
|
|
73
|
+
const codexState = new CodexJsonState();
|
|
74
|
+
let result;
|
|
75
|
+
try {
|
|
76
|
+
result = await this.processRunner.run({
|
|
77
|
+
command: command.command,
|
|
78
|
+
args: command.args,
|
|
79
|
+
cwd: worktree.worktreePath
|
|
80
|
+
}, {
|
|
81
|
+
onStdoutLine: async (line) => {
|
|
82
|
+
const event = codexState.consume(line);
|
|
83
|
+
if (event) {
|
|
84
|
+
await context.emit(event);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}, context.signal);
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
91
|
+
}
|
|
92
|
+
if (result.exitCode !== 0) {
|
|
93
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
94
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
95
|
+
}
|
|
96
|
+
await context.emit({
|
|
97
|
+
role: "runner",
|
|
98
|
+
kind: "checkpoint",
|
|
99
|
+
content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${codexState.threadId ? ` thread ${codexState.threadId}` : ""}.`,
|
|
100
|
+
eventType: "provider_cli_completed"
|
|
101
|
+
});
|
|
102
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
103
|
+
const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, phase);
|
|
104
|
+
if (!completionArtifact) {
|
|
105
|
+
throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
|
|
106
|
+
}
|
|
107
|
+
if (codexState.finalMessage) {
|
|
108
|
+
await context.emit({
|
|
109
|
+
role: "assistant",
|
|
110
|
+
kind: "message",
|
|
111
|
+
content: codexState.finalMessage,
|
|
112
|
+
eventType: "implementation_complete"
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
await context.emit({
|
|
117
|
+
role: "assistant",
|
|
118
|
+
kind: "message",
|
|
119
|
+
content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
|
|
120
|
+
eventType: "implementation_complete"
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${phase}, ${committed.commitSha.slice(0, 12)}).`,
|
|
125
|
+
spec: {
|
|
126
|
+
repoPath: worktree.worktreePath,
|
|
127
|
+
path: specPath,
|
|
128
|
+
body: specBody,
|
|
129
|
+
producedBy: "forge-lane-command",
|
|
130
|
+
status: "approved"
|
|
131
|
+
},
|
|
132
|
+
artifact: completionArtifact
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
async runQa(dispatch, emit, signal) {
|
|
136
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
137
|
+
prompt: buildQaPrompt(dispatch)
|
|
138
|
+
});
|
|
139
|
+
await emit({
|
|
140
|
+
role: "runner",
|
|
141
|
+
kind: "checkpoint",
|
|
142
|
+
content: `Starting provider CLI QA: ${formatProviderCliCommand(command)}`,
|
|
143
|
+
eventType: "provider_cli_started"
|
|
144
|
+
});
|
|
145
|
+
const codexState = new CodexJsonState();
|
|
146
|
+
const result = await this.processRunner.run({
|
|
147
|
+
command: command.command,
|
|
148
|
+
args: command.args,
|
|
149
|
+
cwd: process.cwd()
|
|
150
|
+
}, {
|
|
151
|
+
onStdoutLine: async (line) => {
|
|
152
|
+
const event = codexState.consume(line);
|
|
153
|
+
if (event) {
|
|
154
|
+
await emit(event);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}, signal);
|
|
158
|
+
if (result.exitCode !== 0) {
|
|
159
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
160
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
161
|
+
}
|
|
162
|
+
await emit({
|
|
163
|
+
role: "runner",
|
|
164
|
+
kind: "checkpoint",
|
|
165
|
+
content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${codexState.threadId ? ` thread ${codexState.threadId}` : ""}.`,
|
|
166
|
+
eventType: "provider_cli_completed"
|
|
167
|
+
});
|
|
168
|
+
return {
|
|
169
|
+
summary: `${dispatch.execution.provider} CLI QA passed.`
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
async runConflictResolve(context) {
|
|
173
|
+
const { dispatch, worktree } = context;
|
|
174
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
175
|
+
worktreePath: worktree.worktreePath,
|
|
176
|
+
prompt: buildConflictResolvePrompt(dispatch, worktree.branchName)
|
|
177
|
+
});
|
|
178
|
+
await context.emit({
|
|
179
|
+
role: "runner",
|
|
180
|
+
kind: "checkpoint",
|
|
181
|
+
content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
|
|
182
|
+
eventType: "provider_cli_started"
|
|
183
|
+
});
|
|
184
|
+
const codexState = new CodexJsonState();
|
|
185
|
+
const result = await this.processRunner.run({
|
|
186
|
+
command: command.command,
|
|
187
|
+
args: command.args,
|
|
188
|
+
cwd: worktree.worktreePath
|
|
189
|
+
}, {
|
|
190
|
+
onStdoutLine: async (line) => {
|
|
191
|
+
const event = codexState.consume(line);
|
|
192
|
+
if (event) {
|
|
193
|
+
await context.emit(event);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}, context.signal);
|
|
197
|
+
if (result.exitCode !== 0) {
|
|
198
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
199
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
200
|
+
}
|
|
201
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
202
|
+
await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
|
|
203
|
+
await context.emit({
|
|
204
|
+
role: "assistant",
|
|
205
|
+
kind: "message",
|
|
206
|
+
content: codexState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
|
|
207
|
+
eventType: "conflict_resolve_complete"
|
|
208
|
+
});
|
|
209
|
+
return {
|
|
210
|
+
summary: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
}
|
|
5
214
|
export class DeterministicProviderCliService {
|
|
6
215
|
git;
|
|
7
216
|
constructor(git = new GitClient()) {
|
|
@@ -9,15 +218,26 @@ export class DeterministicProviderCliService {
|
|
|
9
218
|
}
|
|
10
219
|
async runImplementation(context) {
|
|
11
220
|
const { dispatch, worktree } = context;
|
|
221
|
+
const phase = completionPhaseFromDispatch(dispatch);
|
|
12
222
|
const providerCommand = buildProviderCliCommand(dispatch);
|
|
13
223
|
const providerCommandText = formatProviderCliCommand(providerCommand);
|
|
14
|
-
const metadataRoot = path.join(worktree.
|
|
224
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
15
225
|
const artifactRoot = path.join(metadataRoot, "artifacts");
|
|
16
226
|
await fs.mkdir(artifactRoot, { recursive: true });
|
|
17
|
-
const
|
|
227
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
228
|
+
if (!laneCommand) {
|
|
229
|
+
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
230
|
+
}
|
|
231
|
+
const specBody = `${buildSpecBody(laneCommand, dispatch.workItem, phase)}
|
|
232
|
+
## Execution
|
|
233
|
+
|
|
234
|
+
- Provider: ${singleLine(dispatch.execution.provider)}
|
|
235
|
+
- Model: ${singleLine(dispatch.execution.model)}
|
|
236
|
+
- Command: ${providerCommandText}
|
|
237
|
+
`;
|
|
18
238
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
19
239
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
20
|
-
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-
|
|
240
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
21
241
|
const changesetPath = path.join(worktree.worktreePath, "FORGE_PHASE5_CHANGESET.md");
|
|
22
242
|
const changesetBody = `# Forge Phase 5 bridge changeset\n\nWork item: ${dispatch.workItem.id}\nTitle: ${dispatch.workItem.title}\nBranch: ${worktree.branchName}\nProvider: ${singleLine(dispatch.execution.provider)}\nModel: ${singleLine(dispatch.execution.model)}\nCommand: ${providerCommandText}\n\nThis deterministic file is written by forge-bridge run-once through the shared session/worktree service path.\n`;
|
|
23
243
|
await fs.writeFile(changesetPath, changesetBody, "utf8");
|
|
@@ -51,14 +271,14 @@ export class DeterministicProviderCliService {
|
|
|
51
271
|
return {
|
|
52
272
|
summary: `forge-bridge completed ${worktree.branchName}.`,
|
|
53
273
|
spec: {
|
|
54
|
-
repoPath: worktree.
|
|
274
|
+
repoPath: worktree.worktreePath,
|
|
55
275
|
path: specPath,
|
|
56
276
|
body: specBody,
|
|
57
|
-
producedBy: "forge-
|
|
277
|
+
producedBy: "forge-lane-command",
|
|
58
278
|
status: "approved"
|
|
59
279
|
},
|
|
60
280
|
artifact: {
|
|
61
|
-
repoPath: worktree.
|
|
281
|
+
repoPath: worktree.worktreePath,
|
|
62
282
|
path: artifactPath,
|
|
63
283
|
verdictJson,
|
|
64
284
|
report,
|
|
@@ -84,6 +304,188 @@ export class DeterministicProviderCliService {
|
|
|
84
304
|
summary: "forge-bridge QA passed."
|
|
85
305
|
};
|
|
86
306
|
}
|
|
307
|
+
async runConflictResolve(context) {
|
|
308
|
+
const { dispatch, worktree } = context;
|
|
309
|
+
await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
|
|
310
|
+
await context.emit({
|
|
311
|
+
role: "assistant",
|
|
312
|
+
kind: "message",
|
|
313
|
+
content: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
|
|
314
|
+
eventType: "conflict_resolve_complete"
|
|
315
|
+
});
|
|
316
|
+
return {
|
|
317
|
+
summary: `forge-bridge resolved conflicts for ${worktree.branchName}.`
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
export class StreamingProviderProcessRunner {
|
|
322
|
+
async run(request, handlers = {}, signal) {
|
|
323
|
+
const launch = await resolveProviderProcessLaunch(request.command, request.args);
|
|
324
|
+
return await new Promise((resolve, reject) => {
|
|
325
|
+
const child = spawn(launch.command, launch.args, {
|
|
326
|
+
cwd: request.cwd,
|
|
327
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
328
|
+
windowsHide: true
|
|
329
|
+
});
|
|
330
|
+
let stdout = "";
|
|
331
|
+
let stderr = "";
|
|
332
|
+
let settled = false;
|
|
333
|
+
const cleanup = () => {
|
|
334
|
+
signal?.removeEventListener("abort", abort);
|
|
335
|
+
};
|
|
336
|
+
const fail = (error) => {
|
|
337
|
+
if (settled) {
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
settled = true;
|
|
341
|
+
cleanup();
|
|
342
|
+
reject(error);
|
|
343
|
+
};
|
|
344
|
+
const abort = () => {
|
|
345
|
+
try {
|
|
346
|
+
child.kill("SIGTERM");
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
// Best effort; close/error will settle the promise.
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
if (signal?.aborted) {
|
|
353
|
+
abort();
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
357
|
+
}
|
|
358
|
+
child.on("error", fail);
|
|
359
|
+
const readers = [
|
|
360
|
+
readProcessLines(child.stdout, (line) => {
|
|
361
|
+
stdout += `${line}\n`;
|
|
362
|
+
return handlers.onStdoutLine?.(line);
|
|
363
|
+
}),
|
|
364
|
+
readProcessLines(child.stderr, (line) => {
|
|
365
|
+
stderr += `${line}\n`;
|
|
366
|
+
return handlers.onStderrLine?.(line);
|
|
367
|
+
})
|
|
368
|
+
];
|
|
369
|
+
child.on("close", (code) => {
|
|
370
|
+
Promise.allSettled(readers).then((readerResults) => {
|
|
371
|
+
const rejected = readerResults.find((result) => result.status === "rejected");
|
|
372
|
+
if (rejected?.status === "rejected") {
|
|
373
|
+
fail(rejected.reason);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
if (settled) {
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
settled = true;
|
|
380
|
+
cleanup();
|
|
381
|
+
resolve({
|
|
382
|
+
exitCode: code ?? 1,
|
|
383
|
+
stdout,
|
|
384
|
+
stderr
|
|
385
|
+
});
|
|
386
|
+
}).catch(fail);
|
|
387
|
+
});
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
async function resolveProviderProcessLaunch(command, args) {
|
|
392
|
+
if (process.platform !== "win32") {
|
|
393
|
+
return { command, args };
|
|
394
|
+
}
|
|
395
|
+
const resolved = await resolveWindowsCommand(command);
|
|
396
|
+
return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
|
|
397
|
+
}
|
|
398
|
+
async function resolveWindowsCommand(command) {
|
|
399
|
+
if (path.isAbsolute(command)) {
|
|
400
|
+
return command;
|
|
401
|
+
}
|
|
402
|
+
const cursorScript = await resolveCursorAgentPowerShellScript(command);
|
|
403
|
+
if (cursorScript) {
|
|
404
|
+
return cursorScript;
|
|
405
|
+
}
|
|
406
|
+
try {
|
|
407
|
+
const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
|
|
408
|
+
return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
|
|
409
|
+
}
|
|
410
|
+
catch {
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
async function resolveCursorAgentPowerShellScript(command) {
|
|
415
|
+
const normalized = command.trim().toLowerCase();
|
|
416
|
+
if (normalized !== "cursor-agent" && normalized !== "agent") {
|
|
417
|
+
return null;
|
|
418
|
+
}
|
|
419
|
+
const localAppData = process.env.LOCALAPPDATA;
|
|
420
|
+
if (!localAppData) {
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
const script = path.join(localAppData, "cursor-agent", "cursor-agent.ps1");
|
|
424
|
+
return await fileExists(script) ? script : null;
|
|
425
|
+
}
|
|
426
|
+
export function chooseWindowsCommandCandidate(candidates) {
|
|
427
|
+
const normalized = candidates
|
|
428
|
+
.map((candidate) => candidate.trim())
|
|
429
|
+
.filter((candidate) => candidate.length > 0);
|
|
430
|
+
if (normalized.length === 0) {
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
|
|
434
|
+
for (const extension of preferredExtensions) {
|
|
435
|
+
const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
|
|
436
|
+
if (candidate) {
|
|
437
|
+
return candidate;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return normalized[0];
|
|
441
|
+
}
|
|
442
|
+
export function buildWindowsLaunchCommand(commandPath, args) {
|
|
443
|
+
const extension = path.extname(commandPath).toLowerCase();
|
|
444
|
+
if (extension === ".ps1") {
|
|
445
|
+
return {
|
|
446
|
+
command: powershellExecutable(),
|
|
447
|
+
args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", commandPath, ...args]
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
if (extension === ".cmd" || extension === ".bat") {
|
|
451
|
+
return {
|
|
452
|
+
command: process.env.ComSpec ?? "cmd.exe",
|
|
453
|
+
args: ["/d", "/s", "/c", windowsCommandLine(commandPath, args)]
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
return { command: commandPath, args };
|
|
457
|
+
}
|
|
458
|
+
function powershellExecutable() {
|
|
459
|
+
const systemRoot = process.env.SystemRoot;
|
|
460
|
+
return systemRoot
|
|
461
|
+
? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
|
|
462
|
+
: "powershell.exe";
|
|
463
|
+
}
|
|
464
|
+
function windowsCommandLine(command, args) {
|
|
465
|
+
return [command, ...args].map(quoteWindowsCommandLineArg).join(" ");
|
|
466
|
+
}
|
|
467
|
+
function quoteWindowsCommandLineArg(value) {
|
|
468
|
+
if (value.length > 0 && !/[\s"]/.test(value)) {
|
|
469
|
+
return value;
|
|
470
|
+
}
|
|
471
|
+
return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
|
|
472
|
+
}
|
|
473
|
+
async function fileExists(inputPath) {
|
|
474
|
+
return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
|
|
475
|
+
}
|
|
476
|
+
async function readProcessLines(stream, onLine) {
|
|
477
|
+
const reader = readline.createInterface({ input: stream });
|
|
478
|
+
try {
|
|
479
|
+
for await (const line of reader) {
|
|
480
|
+
await onLine(line);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
finally {
|
|
484
|
+
reader.close();
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
function isFakeWorkerModel(model) {
|
|
488
|
+
return model.trim().toLowerCase() === fakeWorkerModel;
|
|
87
489
|
}
|
|
88
490
|
function sha256(content) {
|
|
89
491
|
return crypto.createHash("sha256").update(content).digest("hex");
|
|
@@ -97,15 +499,205 @@ function yamlQuotedScalar(value) {
|
|
|
97
499
|
function singleLine(value) {
|
|
98
500
|
return value.replace(/\s+/g, " ").trim();
|
|
99
501
|
}
|
|
100
|
-
export function buildProviderCliCommand(dispatch) {
|
|
502
|
+
export function buildProviderCliCommand(dispatch, run) {
|
|
101
503
|
const provider = dispatch.execution.provider.trim();
|
|
102
504
|
const normalizedProvider = provider.toLowerCase();
|
|
103
505
|
const model = dispatch.execution.model.trim();
|
|
104
506
|
if (normalizedProvider === "codex") {
|
|
105
|
-
|
|
507
|
+
const args = ["exec"];
|
|
508
|
+
if (run?.completionTools) {
|
|
509
|
+
args.push(...codexMcpConfigArgs(run.completionTools));
|
|
510
|
+
}
|
|
511
|
+
args.push("--model", model);
|
|
512
|
+
if (run) {
|
|
513
|
+
args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
|
|
514
|
+
if (run.worktreePath) {
|
|
515
|
+
args.push("--cd", run.worktreePath);
|
|
516
|
+
}
|
|
517
|
+
args.push(run.prompt ?? "");
|
|
518
|
+
}
|
|
519
|
+
return { command: "codex", args };
|
|
106
520
|
}
|
|
107
521
|
if (normalizedProvider === "cursor") {
|
|
108
|
-
|
|
522
|
+
const args = ["--model", model];
|
|
523
|
+
if (run?.prompt) {
|
|
524
|
+
args.push("--yolo");
|
|
525
|
+
args.push(run.prompt);
|
|
526
|
+
}
|
|
527
|
+
return { command: "cursor-agent", args };
|
|
528
|
+
}
|
|
529
|
+
const args = ["--model", model];
|
|
530
|
+
if (run?.prompt) {
|
|
531
|
+
args.push(run.prompt);
|
|
109
532
|
}
|
|
110
|
-
return { command: provider, args
|
|
533
|
+
return { command: provider, args };
|
|
534
|
+
}
|
|
535
|
+
function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
536
|
+
return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
|
|
537
|
+
|
|
538
|
+
Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
|
|
539
|
+
${phaseWorkInstruction(phase)}
|
|
540
|
+
Use the repository's existing conventions. Run relevant tests when practical.
|
|
541
|
+
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
|
|
542
|
+
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
543
|
+
|
|
544
|
+
${completionPromptForPhase(phase)}
|
|
545
|
+
|
|
546
|
+
Finish with a concise summary of changed files and verification after calling the completion tool.`;
|
|
547
|
+
}
|
|
548
|
+
function phaseWorkInstruction(phase) {
|
|
549
|
+
if (phase === "self_review") {
|
|
550
|
+
return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
|
|
551
|
+
}
|
|
552
|
+
if (phase === "validation") {
|
|
553
|
+
return "Run the validation commands and deterministic drift checks needed to prove the work is ready for Dev Test.";
|
|
554
|
+
}
|
|
555
|
+
return "Implement the work item and keep the change focused.";
|
|
556
|
+
}
|
|
557
|
+
function buildQaPrompt(dispatch) {
|
|
558
|
+
return `You are Forge's QA lane running locally.
|
|
559
|
+
|
|
560
|
+
Review the implementation for work item ${dispatch.workItem.id}: ${dispatch.workItem.title}
|
|
561
|
+
Run relevant verification when practical and finish with a concise QA verdict.`;
|
|
562
|
+
}
|
|
563
|
+
function buildConflictResolvePrompt(dispatch, branchName) {
|
|
564
|
+
const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
|
|
565
|
+
return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
|
|
566
|
+
|
|
567
|
+
The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
|
|
568
|
+
Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
|
|
569
|
+
Keep the original work item intent intact:
|
|
570
|
+
- Work item: ${dispatch.workItem.id}
|
|
571
|
+
- Title: ${dispatch.workItem.title}
|
|
572
|
+
- Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
|
|
573
|
+
|
|
574
|
+
Finish with a concise summary of the conflicts resolved and verification performed.`;
|
|
575
|
+
}
|
|
576
|
+
async function cleanupCompletionTools(completionTools, emit) {
|
|
577
|
+
try {
|
|
578
|
+
await completionTools.cleanup();
|
|
579
|
+
}
|
|
580
|
+
catch (error) {
|
|
581
|
+
await emit({
|
|
582
|
+
role: "runner",
|
|
583
|
+
kind: "checkpoint",
|
|
584
|
+
content: `Forge completion tool cleanup failed and was ignored: ${clip(messageFromError(error), 600)}`,
|
|
585
|
+
eventType: "completion_tools_cleanup_failed"
|
|
586
|
+
}).catch(() => undefined);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
async function commitWorktreeChanges(git, worktreePath, workItemId) {
|
|
590
|
+
await git.run(worktreePath, ["add", "-A"]);
|
|
591
|
+
await git.run(worktreePath, ["reset", "--", ".forge"]).catch(() => "");
|
|
592
|
+
const changedFiles = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
|
|
593
|
+
.split(/\r?\n/)
|
|
594
|
+
.map((line) => line.trim())
|
|
595
|
+
.filter(Boolean);
|
|
596
|
+
if (changedFiles.length > 0) {
|
|
597
|
+
await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
|
|
598
|
+
}
|
|
599
|
+
else {
|
|
600
|
+
await git.run(worktreePath, ["commit", "--allow-empty", "-m", `provider cli completed for ${workItemId.slice(0, 8)}`]);
|
|
601
|
+
}
|
|
602
|
+
const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
603
|
+
return { commitSha, changedFiles };
|
|
604
|
+
}
|
|
605
|
+
function messageFromError(error) {
|
|
606
|
+
return error instanceof Error ? error.message : String(error);
|
|
607
|
+
}
|
|
608
|
+
function clip(value, maxLength) {
|
|
609
|
+
if (value.length <= maxLength) {
|
|
610
|
+
return value;
|
|
611
|
+
}
|
|
612
|
+
return `${value.slice(0, maxLength)}...`;
|
|
613
|
+
}
|
|
614
|
+
class CodexJsonState {
|
|
615
|
+
threadId = null;
|
|
616
|
+
finalMessage = null;
|
|
617
|
+
emittedThread = false;
|
|
618
|
+
consume(line) {
|
|
619
|
+
const trimmed = line.trim();
|
|
620
|
+
if (!trimmed.startsWith("{")) {
|
|
621
|
+
return null;
|
|
622
|
+
}
|
|
623
|
+
let parsed;
|
|
624
|
+
try {
|
|
625
|
+
parsed = JSON.parse(trimmed);
|
|
626
|
+
}
|
|
627
|
+
catch {
|
|
628
|
+
return null;
|
|
629
|
+
}
|
|
630
|
+
if (!parsed || typeof parsed !== "object") {
|
|
631
|
+
return null;
|
|
632
|
+
}
|
|
633
|
+
const event = parsed;
|
|
634
|
+
const type = typeof event.type === "string" ? event.type : "";
|
|
635
|
+
if (type === "thread.started") {
|
|
636
|
+
this.threadId = stringField(event, "thread_id");
|
|
637
|
+
if (this.threadId && !this.emittedThread) {
|
|
638
|
+
this.emittedThread = true;
|
|
639
|
+
return {
|
|
640
|
+
role: "runner",
|
|
641
|
+
kind: "checkpoint",
|
|
642
|
+
content: `Codex thread started: ${this.threadId}.`,
|
|
643
|
+
eventType: "provider_thread_started"
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
if (type === "turn.completed") {
|
|
648
|
+
return {
|
|
649
|
+
role: "runner",
|
|
650
|
+
kind: "checkpoint",
|
|
651
|
+
content: "Codex turn completed.",
|
|
652
|
+
eventType: "provider_turn_completed"
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
if (type === "turn.failed" || type === "error") {
|
|
656
|
+
return {
|
|
657
|
+
role: "runner",
|
|
658
|
+
kind: "error",
|
|
659
|
+
content: clip(trimmed, 1000),
|
|
660
|
+
eventType: "provider_cli_error"
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
if (type === "item.completed" || type === "item.updated") {
|
|
664
|
+
const item = objectField(event, "item");
|
|
665
|
+
const itemType = stringField(item, "type");
|
|
666
|
+
if (itemType === "agent_message") {
|
|
667
|
+
const text = stringField(item, "text");
|
|
668
|
+
if (text) {
|
|
669
|
+
this.finalMessage = clip(text, 4000);
|
|
670
|
+
return {
|
|
671
|
+
role: "assistant",
|
|
672
|
+
kind: "message",
|
|
673
|
+
content: this.finalMessage,
|
|
674
|
+
eventType: "provider_message"
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
if (itemType === "command_execution") {
|
|
679
|
+
const command = stringField(item, "command");
|
|
680
|
+
const status = stringField(item, "status");
|
|
681
|
+
if (command) {
|
|
682
|
+
return {
|
|
683
|
+
role: "worker",
|
|
684
|
+
kind: "checkpoint",
|
|
685
|
+
content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
|
|
686
|
+
eventType: "provider_command"
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
return null;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
function objectField(source, key) {
|
|
695
|
+
const value = source[key];
|
|
696
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
697
|
+
? value
|
|
698
|
+
: {};
|
|
699
|
+
}
|
|
700
|
+
function stringField(source, key) {
|
|
701
|
+
const value = source[key];
|
|
702
|
+
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
111
703
|
}
|
|
@@ -3,6 +3,7 @@ import type { WorktreeHandle } from "../../worktree/worktree.types.js";
|
|
|
3
3
|
export interface ProviderCliRunContext {
|
|
4
4
|
readonly dispatch: RunOnceDispatchPacket;
|
|
5
5
|
readonly worktree: WorktreeHandle;
|
|
6
|
+
readonly signal?: AbortSignal;
|
|
6
7
|
emit(event: RunnerDispatchEvent): Promise<void>;
|
|
7
8
|
}
|
|
8
9
|
export interface ProviderCliRunResult {
|