@loucompanion/forge-bridge 0.1.1-dev.242bb53ef13f → 0.1.1-dev.2bc1e7f19b3a
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 +406 -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 +86 -0
- package/dist/session/phase-completion.js +1018 -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 +46 -1
- package/dist/session/provider-cli/provider-cli.service.js +962 -37
- package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
- package/dist/session/session.service.js +55 -11
- package/dist/session/session.types.d.ts +14 -0
- package/dist/session/session.types.js +58 -1
- package/dist/shared/cursor-agent/cursor-agent.launch.d.ts +9 -0
- package/dist/shared/cursor-agent/cursor-agent.launch.js +66 -0
- 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 +104 -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 +2 -2
|
@@ -1,7 +1,224 @@
|
|
|
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 { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
|
|
9
|
+
import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
|
|
10
|
+
import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDevelopCycle, completionPromptForPhase, completionRedactionEnv, expectedCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDevelopCycleCompletion, writeCompletionArtifact } from "../phase-completion.js";
|
|
11
|
+
const fakeWorkerModel = "server-local-fake-worker";
|
|
12
|
+
const execFileAsync = promisify(execFile);
|
|
13
|
+
export class RoutingProviderCliService {
|
|
14
|
+
realProvider;
|
|
15
|
+
deterministicProvider;
|
|
16
|
+
constructor(realProvider = new ProcessBackedProviderCliService(), deterministicProvider = new DeterministicProviderCliService()) {
|
|
17
|
+
this.realProvider = realProvider;
|
|
18
|
+
this.deterministicProvider = deterministicProvider;
|
|
19
|
+
}
|
|
20
|
+
async runImplementation(context) {
|
|
21
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
22
|
+
? await this.deterministicProvider.runImplementation(context)
|
|
23
|
+
: await this.realProvider.runImplementation(context);
|
|
24
|
+
}
|
|
25
|
+
async runConflictResolve(context) {
|
|
26
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
27
|
+
? await this.deterministicProvider.runConflictResolve(context)
|
|
28
|
+
: await this.realProvider.runConflictResolve(context);
|
|
29
|
+
}
|
|
30
|
+
async runQa(dispatch, emit, signal) {
|
|
31
|
+
return isFakeWorkerModel(dispatch.execution.model)
|
|
32
|
+
? await this.deterministicProvider.runQa(dispatch, emit, signal)
|
|
33
|
+
: await this.realProvider.runQa(dispatch, emit, signal);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export class ProcessBackedProviderCliService {
|
|
37
|
+
processRunner;
|
|
38
|
+
git;
|
|
39
|
+
constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient()) {
|
|
40
|
+
this.processRunner = processRunner;
|
|
41
|
+
this.git = git;
|
|
42
|
+
}
|
|
43
|
+
async runImplementation(context) {
|
|
44
|
+
const { dispatch, worktree } = context;
|
|
45
|
+
const phase = completionPhaseFromDispatch(dispatch);
|
|
46
|
+
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
47
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
48
|
+
await fs.mkdir(metadataRoot, { recursive: true });
|
|
49
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
50
|
+
if (!laneCommand) {
|
|
51
|
+
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
52
|
+
}
|
|
53
|
+
const specBody = buildSpecBody(laneCommand, dispatch.workItem, phase);
|
|
54
|
+
const specPath = path.join(metadataRoot, "spec.md");
|
|
55
|
+
await fs.writeFile(specPath, specBody, "utf8");
|
|
56
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
57
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
|
|
58
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
59
|
+
worktreePath: worktree.worktreePath,
|
|
60
|
+
prompt: developCycle ? buildDevelopCyclePrompt(dispatch, phase) : buildImplementationPrompt(dispatch, phase),
|
|
61
|
+
completionTools
|
|
62
|
+
});
|
|
63
|
+
await context.emit({
|
|
64
|
+
role: "runner",
|
|
65
|
+
kind: "checkpoint",
|
|
66
|
+
content: `Starting provider CLI: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
|
|
67
|
+
eventType: "provider_cli_started"
|
|
68
|
+
});
|
|
69
|
+
await context.emit({
|
|
70
|
+
role: "runner",
|
|
71
|
+
kind: "checkpoint",
|
|
72
|
+
content: developCycle
|
|
73
|
+
? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
|
|
74
|
+
: `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
|
|
75
|
+
eventType: "completion_tools_configured"
|
|
76
|
+
});
|
|
77
|
+
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
78
|
+
let result;
|
|
79
|
+
try {
|
|
80
|
+
result = await this.processRunner.run({
|
|
81
|
+
command: command.command,
|
|
82
|
+
args: command.args,
|
|
83
|
+
cwd: worktree.worktreePath,
|
|
84
|
+
env: providerRedactionEnv(dispatch)
|
|
85
|
+
}, {
|
|
86
|
+
onStdoutLine: async (line) => {
|
|
87
|
+
const event = outputState.consume(line);
|
|
88
|
+
if (event) {
|
|
89
|
+
await context.emit(event);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}, context.signal);
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
96
|
+
}
|
|
97
|
+
if (result.exitCode !== 0) {
|
|
98
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
99
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
100
|
+
}
|
|
101
|
+
await context.emit({
|
|
102
|
+
role: "runner",
|
|
103
|
+
kind: "checkpoint",
|
|
104
|
+
content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
|
|
105
|
+
eventType: "provider_cli_completed"
|
|
106
|
+
});
|
|
107
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
108
|
+
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle);
|
|
109
|
+
for (const artifact of completionArtifacts) {
|
|
110
|
+
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
|
|
111
|
+
await emitPhaseCompletionEvent(context.emit, artifact);
|
|
112
|
+
}
|
|
113
|
+
const completionArtifact = completionArtifacts[0];
|
|
114
|
+
if (outputState.finalMessage) {
|
|
115
|
+
await context.emit({
|
|
116
|
+
role: "assistant",
|
|
117
|
+
kind: "message",
|
|
118
|
+
content: outputState.finalMessage,
|
|
119
|
+
eventType: "provider_final_message"
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
await context.emit({
|
|
124
|
+
role: "assistant",
|
|
125
|
+
kind: "message",
|
|
126
|
+
content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
|
|
127
|
+
eventType: "provider_final_message"
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
|
|
132
|
+
spec: {
|
|
133
|
+
repoPath: worktree.worktreePath,
|
|
134
|
+
path: specPath,
|
|
135
|
+
body: specBody,
|
|
136
|
+
producedBy: "forge-lane-command",
|
|
137
|
+
status: "approved"
|
|
138
|
+
},
|
|
139
|
+
artifact: completionArtifact,
|
|
140
|
+
artifacts: completionArtifacts
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
async runQa(dispatch, emit, signal) {
|
|
144
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
145
|
+
prompt: buildQaPrompt(dispatch)
|
|
146
|
+
});
|
|
147
|
+
await emit({
|
|
148
|
+
role: "runner",
|
|
149
|
+
kind: "checkpoint",
|
|
150
|
+
content: `Starting provider CLI QA: ${formatProviderCliCommand(command)}`,
|
|
151
|
+
eventType: "provider_cli_started"
|
|
152
|
+
});
|
|
153
|
+
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
154
|
+
const result = await this.processRunner.run({
|
|
155
|
+
command: command.command,
|
|
156
|
+
args: command.args,
|
|
157
|
+
cwd: process.cwd()
|
|
158
|
+
}, {
|
|
159
|
+
onStdoutLine: async (line) => {
|
|
160
|
+
const event = outputState.consume(line);
|
|
161
|
+
if (event) {
|
|
162
|
+
await emit(event);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}, signal);
|
|
166
|
+
if (result.exitCode !== 0) {
|
|
167
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
168
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
169
|
+
}
|
|
170
|
+
await emit({
|
|
171
|
+
role: "runner",
|
|
172
|
+
kind: "checkpoint",
|
|
173
|
+
content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
|
|
174
|
+
eventType: "provider_cli_completed"
|
|
175
|
+
});
|
|
176
|
+
return {
|
|
177
|
+
summary: `${dispatch.execution.provider} CLI QA passed.`
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
async runConflictResolve(context) {
|
|
181
|
+
const { dispatch, worktree } = context;
|
|
182
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
183
|
+
worktreePath: worktree.worktreePath,
|
|
184
|
+
prompt: buildConflictResolvePrompt(dispatch, worktree.branchName)
|
|
185
|
+
});
|
|
186
|
+
await context.emit({
|
|
187
|
+
role: "runner",
|
|
188
|
+
kind: "checkpoint",
|
|
189
|
+
content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
|
|
190
|
+
eventType: "provider_cli_started"
|
|
191
|
+
});
|
|
192
|
+
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
193
|
+
const result = await this.processRunner.run({
|
|
194
|
+
command: command.command,
|
|
195
|
+
args: command.args,
|
|
196
|
+
cwd: worktree.worktreePath
|
|
197
|
+
}, {
|
|
198
|
+
onStdoutLine: async (line) => {
|
|
199
|
+
const event = outputState.consume(line);
|
|
200
|
+
if (event) {
|
|
201
|
+
await context.emit(event);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}, context.signal);
|
|
205
|
+
if (result.exitCode !== 0) {
|
|
206
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
207
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
208
|
+
}
|
|
209
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
210
|
+
await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
|
|
211
|
+
await context.emit({
|
|
212
|
+
role: "assistant",
|
|
213
|
+
kind: "message",
|
|
214
|
+
content: outputState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
|
|
215
|
+
eventType: "conflict_resolve_complete"
|
|
216
|
+
});
|
|
217
|
+
return {
|
|
218
|
+
summary: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
}
|
|
5
222
|
export class DeterministicProviderCliService {
|
|
6
223
|
git;
|
|
7
224
|
constructor(git = new GitClient()) {
|
|
@@ -9,15 +226,27 @@ export class DeterministicProviderCliService {
|
|
|
9
226
|
}
|
|
10
227
|
async runImplementation(context) {
|
|
11
228
|
const { dispatch, worktree } = context;
|
|
229
|
+
const phase = completionPhaseFromDispatch(dispatch);
|
|
230
|
+
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
12
231
|
const providerCommand = buildProviderCliCommand(dispatch);
|
|
13
232
|
const providerCommandText = formatProviderCliCommand(providerCommand);
|
|
14
|
-
const metadataRoot = path.join(worktree.
|
|
233
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
15
234
|
const artifactRoot = path.join(metadataRoot, "artifacts");
|
|
16
235
|
await fs.mkdir(artifactRoot, { recursive: true });
|
|
17
|
-
const
|
|
236
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
237
|
+
if (!laneCommand) {
|
|
238
|
+
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
239
|
+
}
|
|
240
|
+
const specBody = `${buildSpecBody(laneCommand, dispatch.workItem, phase)}
|
|
241
|
+
## Execution
|
|
242
|
+
|
|
243
|
+
- Provider: ${singleLine(dispatch.execution.provider)}
|
|
244
|
+
- Model: ${singleLine(dispatch.execution.model)}
|
|
245
|
+
- Command: ${providerCommandText}
|
|
246
|
+
`;
|
|
18
247
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
19
248
|
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-
|
|
249
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
21
250
|
const changesetPath = path.join(worktree.worktreePath, "FORGE_PHASE5_CHANGESET.md");
|
|
22
251
|
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
252
|
await fs.writeFile(changesetPath, changesetBody, "utf8");
|
|
@@ -29,42 +258,42 @@ export class DeterministicProviderCliService {
|
|
|
29
258
|
content: `Created bridge changeset at ${changesetPath}`,
|
|
30
259
|
eventType: "changeset"
|
|
31
260
|
});
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
261
|
+
const phases = developCycle
|
|
262
|
+
? ["implementation", "self_review", "validation"]
|
|
263
|
+
: [phase];
|
|
264
|
+
const completionArtifacts = [];
|
|
265
|
+
for (const completionPhase of phases) {
|
|
266
|
+
await writeCompletionArtifact({
|
|
267
|
+
worktreePath: worktree.worktreePath,
|
|
268
|
+
workItemId: dispatch.workItem.id,
|
|
269
|
+
phase: completionPhase,
|
|
270
|
+
producedBy: "forge-bridge",
|
|
271
|
+
redactionSecrets: exactRedactionSecrets(dispatch)
|
|
272
|
+
}, expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
|
|
273
|
+
const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
|
|
274
|
+
if (!completionArtifact) {
|
|
275
|
+
throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
|
|
276
|
+
}
|
|
277
|
+
completionArtifacts.push(completionArtifact);
|
|
278
|
+
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
|
|
279
|
+
await context.emit({
|
|
280
|
+
role: "assistant",
|
|
281
|
+
kind: "message",
|
|
282
|
+
content: `${completionPhase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
|
|
283
|
+
eventType: phaseCompleteEventType(completionPhase)
|
|
284
|
+
});
|
|
285
|
+
}
|
|
51
286
|
return {
|
|
52
|
-
summary: `forge-bridge completed ${worktree.branchName}.`,
|
|
287
|
+
summary: `forge-bridge completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}).`,
|
|
53
288
|
spec: {
|
|
54
|
-
repoPath: worktree.
|
|
289
|
+
repoPath: worktree.worktreePath,
|
|
55
290
|
path: specPath,
|
|
56
291
|
body: specBody,
|
|
57
|
-
producedBy: "forge-
|
|
292
|
+
producedBy: "forge-lane-command",
|
|
58
293
|
status: "approved"
|
|
59
294
|
},
|
|
60
|
-
artifact:
|
|
61
|
-
|
|
62
|
-
path: artifactPath,
|
|
63
|
-
verdictJson,
|
|
64
|
-
report,
|
|
65
|
-
producedBy: "forge-bridge",
|
|
66
|
-
status: "pass"
|
|
67
|
-
}
|
|
295
|
+
artifact: completionArtifacts[0],
|
|
296
|
+
artifacts: completionArtifacts
|
|
68
297
|
};
|
|
69
298
|
}
|
|
70
299
|
async runQa(dispatch, emit) {
|
|
@@ -84,6 +313,321 @@ export class DeterministicProviderCliService {
|
|
|
84
313
|
summary: "forge-bridge QA passed."
|
|
85
314
|
};
|
|
86
315
|
}
|
|
316
|
+
async runConflictResolve(context) {
|
|
317
|
+
const { dispatch, worktree } = context;
|
|
318
|
+
await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
|
|
319
|
+
await context.emit({
|
|
320
|
+
role: "assistant",
|
|
321
|
+
kind: "message",
|
|
322
|
+
content: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
|
|
323
|
+
eventType: "conflict_resolve_complete"
|
|
324
|
+
});
|
|
325
|
+
return {
|
|
326
|
+
summary: `forge-bridge resolved conflicts for ${worktree.branchName}.`
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
function phaseCompleteEventType(phase) {
|
|
331
|
+
return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
|
|
332
|
+
}
|
|
333
|
+
function deterministicCompletionPayload(phase, dispatch, changesetBody) {
|
|
334
|
+
const changesetHash = sha256(changesetBody);
|
|
335
|
+
const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
|
|
336
|
+
if (phase === "implementation") {
|
|
337
|
+
return {
|
|
338
|
+
status: "pass",
|
|
339
|
+
summary: "forge-bridge produced a deterministic implementation changeset.",
|
|
340
|
+
plan: [{ step: "Create deterministic changeset", status: "done" }],
|
|
341
|
+
changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
|
|
342
|
+
tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
|
|
343
|
+
docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
|
|
344
|
+
acceptance_criteria: [
|
|
345
|
+
{
|
|
346
|
+
criterion,
|
|
347
|
+
evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
|
|
348
|
+
status: "satisfied"
|
|
349
|
+
}
|
|
350
|
+
],
|
|
351
|
+
known_gaps: [],
|
|
352
|
+
next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
if (phase === "self_review") {
|
|
356
|
+
return {
|
|
357
|
+
status: "pass",
|
|
358
|
+
summary: "forge-bridge fake worker completed deterministic self-review.",
|
|
359
|
+
reviewed_diff: true,
|
|
360
|
+
findings: [],
|
|
361
|
+
security_review: {
|
|
362
|
+
status: "pass",
|
|
363
|
+
notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
|
|
364
|
+
},
|
|
365
|
+
edge_case_review: {
|
|
366
|
+
status: "pass",
|
|
367
|
+
notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
|
|
368
|
+
},
|
|
369
|
+
design_review: {
|
|
370
|
+
status: "not_applicable",
|
|
371
|
+
screenshots: [],
|
|
372
|
+
notes: "No UI changes."
|
|
373
|
+
},
|
|
374
|
+
deterministic_comparison: {
|
|
375
|
+
status: "pass",
|
|
376
|
+
command_or_tool: "git diff --stat HEAD~1..HEAD",
|
|
377
|
+
notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
|
|
378
|
+
},
|
|
379
|
+
fixes_applied: [],
|
|
380
|
+
remaining_risks: []
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
return {
|
|
384
|
+
status: "pass",
|
|
385
|
+
summary: "forge-bridge fake worker completed deterministic validation.",
|
|
386
|
+
commands: [
|
|
387
|
+
{
|
|
388
|
+
command: "git status --short && git diff --check",
|
|
389
|
+
exit_code: 0,
|
|
390
|
+
status: "pass",
|
|
391
|
+
summary: "Deterministic validation command completed for the fake-worker changeset."
|
|
392
|
+
}
|
|
393
|
+
],
|
|
394
|
+
acceptance_criteria: [
|
|
395
|
+
{
|
|
396
|
+
criterion,
|
|
397
|
+
evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
|
|
398
|
+
status: "satisfied"
|
|
399
|
+
}
|
|
400
|
+
],
|
|
401
|
+
build_status: "pass",
|
|
402
|
+
test_status: "pass",
|
|
403
|
+
lint_status: "not_applicable",
|
|
404
|
+
design_status: "not_applicable",
|
|
405
|
+
drift_checks: [
|
|
406
|
+
{
|
|
407
|
+
command_or_tool: "git diff --check",
|
|
408
|
+
status: "pass",
|
|
409
|
+
summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
|
|
410
|
+
}
|
|
411
|
+
],
|
|
412
|
+
ready_for_dev_test: true
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
|
|
416
|
+
const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
|
|
417
|
+
await emit({
|
|
418
|
+
role: "tool",
|
|
419
|
+
kind: "tool_result",
|
|
420
|
+
content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
|
|
421
|
+
eventType: "completion_tool_artifact_recorded"
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
async function emitPhaseCompletionEvent(emit, artifact) {
|
|
425
|
+
const phase = completionPhaseFromArtifact(artifact);
|
|
426
|
+
await emit({
|
|
427
|
+
role: "assistant",
|
|
428
|
+
kind: "message",
|
|
429
|
+
content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
|
|
430
|
+
eventType: phaseCompleteEventType(phase)
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
function completionPhaseFromArtifact(artifact) {
|
|
434
|
+
const phase = artifact.phase?.trim();
|
|
435
|
+
return phase === "self_review" || phase === "validation" || phase === "implementation"
|
|
436
|
+
? phase
|
|
437
|
+
: "implementation";
|
|
438
|
+
}
|
|
439
|
+
async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle) {
|
|
440
|
+
if (!developCycle) {
|
|
441
|
+
const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
|
|
442
|
+
if (!artifact) {
|
|
443
|
+
throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
|
|
444
|
+
}
|
|
445
|
+
return [artifact];
|
|
446
|
+
}
|
|
447
|
+
const artifacts = [];
|
|
448
|
+
for (const expectedPhase of ["implementation", "self_review", "validation"]) {
|
|
449
|
+
const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
|
|
450
|
+
if (!artifact) {
|
|
451
|
+
if (artifacts.length === 0) {
|
|
452
|
+
throw new Error("Provider CLI completed but did not call the Forge implementation completion tool.");
|
|
453
|
+
}
|
|
454
|
+
const previous = artifacts[artifacts.length - 1];
|
|
455
|
+
if ((previous.status ?? "").trim().toLowerCase() === "pass") {
|
|
456
|
+
throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
|
|
457
|
+
}
|
|
458
|
+
return artifacts;
|
|
459
|
+
}
|
|
460
|
+
artifacts.push(artifact);
|
|
461
|
+
if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
462
|
+
return artifacts;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return artifacts;
|
|
466
|
+
}
|
|
467
|
+
function providerRedactionEnv(dispatch) {
|
|
468
|
+
const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
|
|
469
|
+
return Object.keys(env).length > 0 ? env : undefined;
|
|
470
|
+
}
|
|
471
|
+
function exactRedactionSecrets(dispatch) {
|
|
472
|
+
return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
|
|
473
|
+
}
|
|
474
|
+
export class StreamingProviderProcessRunner {
|
|
475
|
+
async run(request, handlers = {}, signal) {
|
|
476
|
+
const launch = await resolveProviderProcessLaunch(request.command, request.args);
|
|
477
|
+
return await new Promise((resolve, reject) => {
|
|
478
|
+
const child = spawn(launch.command, launch.args, {
|
|
479
|
+
cwd: request.cwd,
|
|
480
|
+
env: request.env ? { ...process.env, ...request.env } : undefined,
|
|
481
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
482
|
+
windowsHide: true
|
|
483
|
+
});
|
|
484
|
+
let stdout = "";
|
|
485
|
+
let stderr = "";
|
|
486
|
+
let settled = false;
|
|
487
|
+
const cleanup = () => {
|
|
488
|
+
signal?.removeEventListener("abort", abort);
|
|
489
|
+
};
|
|
490
|
+
const fail = (error) => {
|
|
491
|
+
if (settled) {
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
settled = true;
|
|
495
|
+
cleanup();
|
|
496
|
+
reject(error);
|
|
497
|
+
};
|
|
498
|
+
const abort = () => {
|
|
499
|
+
try {
|
|
500
|
+
child.kill("SIGTERM");
|
|
501
|
+
}
|
|
502
|
+
catch {
|
|
503
|
+
// Best effort; close/error will settle the promise.
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
if (signal?.aborted) {
|
|
507
|
+
abort();
|
|
508
|
+
}
|
|
509
|
+
else {
|
|
510
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
511
|
+
}
|
|
512
|
+
child.on("error", fail);
|
|
513
|
+
const readers = [
|
|
514
|
+
readProcessLines(child.stdout, (line) => {
|
|
515
|
+
stdout += `${line}\n`;
|
|
516
|
+
return handlers.onStdoutLine?.(line);
|
|
517
|
+
}),
|
|
518
|
+
readProcessLines(child.stderr, (line) => {
|
|
519
|
+
stderr += `${line}\n`;
|
|
520
|
+
return handlers.onStderrLine?.(line);
|
|
521
|
+
})
|
|
522
|
+
];
|
|
523
|
+
child.on("close", (code) => {
|
|
524
|
+
Promise.allSettled(readers).then((readerResults) => {
|
|
525
|
+
const rejected = readerResults.find((result) => result.status === "rejected");
|
|
526
|
+
if (rejected?.status === "rejected") {
|
|
527
|
+
fail(rejected.reason);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
if (settled) {
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
settled = true;
|
|
534
|
+
cleanup();
|
|
535
|
+
resolve({
|
|
536
|
+
exitCode: code ?? 1,
|
|
537
|
+
stdout,
|
|
538
|
+
stderr
|
|
539
|
+
});
|
|
540
|
+
}).catch(fail);
|
|
541
|
+
});
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
async function resolveProviderProcessLaunch(command, args) {
|
|
546
|
+
if (process.platform !== "win32") {
|
|
547
|
+
return { command, args };
|
|
548
|
+
}
|
|
549
|
+
const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
|
|
550
|
+
if (cursorDirect) {
|
|
551
|
+
return cursorDirect;
|
|
552
|
+
}
|
|
553
|
+
const resolved = await resolveWindowsCommand(command);
|
|
554
|
+
return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
|
|
555
|
+
}
|
|
556
|
+
async function resolveWindowsCommand(command) {
|
|
557
|
+
if (path.isAbsolute(command)) {
|
|
558
|
+
return command;
|
|
559
|
+
}
|
|
560
|
+
try {
|
|
561
|
+
const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
|
|
562
|
+
return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
|
|
563
|
+
}
|
|
564
|
+
catch {
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
export function chooseWindowsCommandCandidate(candidates) {
|
|
569
|
+
const normalized = candidates
|
|
570
|
+
.map((candidate) => candidate.trim())
|
|
571
|
+
.filter((candidate) => candidate.length > 0);
|
|
572
|
+
if (normalized.length === 0) {
|
|
573
|
+
return null;
|
|
574
|
+
}
|
|
575
|
+
const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
|
|
576
|
+
for (const extension of preferredExtensions) {
|
|
577
|
+
const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
|
|
578
|
+
if (candidate) {
|
|
579
|
+
return candidate;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
return normalized[0];
|
|
583
|
+
}
|
|
584
|
+
export function buildWindowsLaunchCommand(commandPath, args) {
|
|
585
|
+
const extension = path.extname(commandPath).toLowerCase();
|
|
586
|
+
if (extension === ".ps1") {
|
|
587
|
+
return {
|
|
588
|
+
command: powershellExecutable(),
|
|
589
|
+
args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", commandPath, ...args]
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
if (extension === ".cmd" || extension === ".bat") {
|
|
593
|
+
return {
|
|
594
|
+
command: process.env.ComSpec ?? "cmd.exe",
|
|
595
|
+
args: ["/d", "/s", "/c", windowsCommandLine(commandPath, args)]
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
return { command: commandPath, args };
|
|
599
|
+
}
|
|
600
|
+
function powershellExecutable() {
|
|
601
|
+
const systemRoot = process.env.SystemRoot;
|
|
602
|
+
return systemRoot
|
|
603
|
+
? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
|
|
604
|
+
: "powershell.exe";
|
|
605
|
+
}
|
|
606
|
+
function windowsCommandLine(command, args) {
|
|
607
|
+
return [command, ...args].map(quoteWindowsCommandLineArg).join(" ");
|
|
608
|
+
}
|
|
609
|
+
function quoteWindowsCommandLineArg(value) {
|
|
610
|
+
if (value.length > 0 && !/[\s"]/.test(value)) {
|
|
611
|
+
return value;
|
|
612
|
+
}
|
|
613
|
+
return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
|
|
614
|
+
}
|
|
615
|
+
async function fileExists(inputPath) {
|
|
616
|
+
return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
|
|
617
|
+
}
|
|
618
|
+
async function readProcessLines(stream, onLine) {
|
|
619
|
+
const reader = readline.createInterface({ input: stream });
|
|
620
|
+
try {
|
|
621
|
+
for await (const line of reader) {
|
|
622
|
+
await onLine(line);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
finally {
|
|
626
|
+
reader.close();
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
function isFakeWorkerModel(model) {
|
|
630
|
+
return model.trim().toLowerCase() === fakeWorkerModel;
|
|
87
631
|
}
|
|
88
632
|
function sha256(content) {
|
|
89
633
|
return crypto.createHash("sha256").update(content).digest("hex");
|
|
@@ -97,15 +641,396 @@ function yamlQuotedScalar(value) {
|
|
|
97
641
|
function singleLine(value) {
|
|
98
642
|
return value.replace(/\s+/g, " ").trim();
|
|
99
643
|
}
|
|
100
|
-
export function buildProviderCliCommand(dispatch) {
|
|
644
|
+
export function buildProviderCliCommand(dispatch, run) {
|
|
101
645
|
const provider = dispatch.execution.provider.trim();
|
|
102
646
|
const normalizedProvider = provider.toLowerCase();
|
|
103
647
|
const model = dispatch.execution.model.trim();
|
|
104
648
|
if (normalizedProvider === "codex") {
|
|
105
|
-
|
|
649
|
+
const args = ["exec"];
|
|
650
|
+
if (run?.completionTools) {
|
|
651
|
+
args.push(...codexMcpConfigArgs(run.completionTools));
|
|
652
|
+
}
|
|
653
|
+
args.push("--model", model);
|
|
654
|
+
if (run) {
|
|
655
|
+
args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
|
|
656
|
+
if (run.worktreePath) {
|
|
657
|
+
args.push("--cd", run.worktreePath);
|
|
658
|
+
}
|
|
659
|
+
args.push(run.prompt ?? "");
|
|
660
|
+
}
|
|
661
|
+
return { command: "codex", args };
|
|
106
662
|
}
|
|
107
663
|
if (normalizedProvider === "cursor") {
|
|
108
|
-
|
|
664
|
+
const args = ["--print", "--output-format", "stream-json", "--model", model];
|
|
665
|
+
if (run?.worktreePath) {
|
|
666
|
+
args.push("--workspace", run.worktreePath);
|
|
667
|
+
}
|
|
668
|
+
if (run?.prompt) {
|
|
669
|
+
args.push("--yolo", "--approve-mcps", "--trust", run.prompt);
|
|
670
|
+
}
|
|
671
|
+
return { command: "cursor-agent", args };
|
|
672
|
+
}
|
|
673
|
+
const args = ["--model", model];
|
|
674
|
+
if (run?.prompt) {
|
|
675
|
+
args.push(run.prompt);
|
|
676
|
+
}
|
|
677
|
+
return { command: provider, args };
|
|
678
|
+
}
|
|
679
|
+
function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
680
|
+
return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
|
|
681
|
+
|
|
682
|
+
Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
|
|
683
|
+
${phaseWorkInstruction(phase)}
|
|
684
|
+
Use the repository's existing conventions. Run relevant tests when practical.
|
|
685
|
+
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
|
|
686
|
+
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
687
|
+
|
|
688
|
+
${completionPromptForPhase(phase)}
|
|
689
|
+
|
|
690
|
+
Finish with a concise summary of changed files and verification after calling the completion tool.`;
|
|
691
|
+
}
|
|
692
|
+
function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
693
|
+
return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
|
|
694
|
+
|
|
695
|
+
Read .forge/work-items/${dispatch.workItem.id}/spec.md, implement the work item, self-review the diff, then validate it in this same provider session.
|
|
696
|
+
Start in the ${phase.replace(/_/g, " ")} phase. Do not stop after implementation if it passes; continue through self-review and validation using the next instruction returned by each completion tool.
|
|
697
|
+
Use the repository's existing conventions. Run relevant tests when practical.
|
|
698
|
+
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
|
|
699
|
+
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
700
|
+
|
|
701
|
+
${completionPromptForDevelopCycle(phase)}
|
|
702
|
+
|
|
703
|
+
Finish with a concise summary of changed files and verification after the validation completion tool has accepted the work, or after the current phase tool records a non-pass blocker.`;
|
|
704
|
+
}
|
|
705
|
+
function phaseWorkInstruction(phase) {
|
|
706
|
+
if (phase === "self_review") {
|
|
707
|
+
return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
|
|
708
|
+
}
|
|
709
|
+
if (phase === "validation") {
|
|
710
|
+
return "Run the validation commands and deterministic drift checks needed to prove the work is ready for Dev Test.";
|
|
711
|
+
}
|
|
712
|
+
return "Implement the work item and keep the change focused.";
|
|
713
|
+
}
|
|
714
|
+
function buildQaPrompt(dispatch) {
|
|
715
|
+
return `You are Forge's QA lane running locally.
|
|
716
|
+
|
|
717
|
+
Review the implementation for work item ${dispatch.workItem.id}: ${dispatch.workItem.title}
|
|
718
|
+
Run relevant verification when practical and finish with a concise QA verdict.`;
|
|
719
|
+
}
|
|
720
|
+
function buildConflictResolvePrompt(dispatch, branchName) {
|
|
721
|
+
const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
|
|
722
|
+
return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
|
|
723
|
+
|
|
724
|
+
The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
|
|
725
|
+
Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
|
|
726
|
+
Keep the original work item intent intact:
|
|
727
|
+
- Work item: ${dispatch.workItem.id}
|
|
728
|
+
- Title: ${dispatch.workItem.title}
|
|
729
|
+
- Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
|
|
730
|
+
|
|
731
|
+
Finish with a concise summary of the conflicts resolved and verification performed.`;
|
|
732
|
+
}
|
|
733
|
+
async function cleanupCompletionTools(completionTools, emit) {
|
|
734
|
+
try {
|
|
735
|
+
await completionTools.cleanup();
|
|
736
|
+
}
|
|
737
|
+
catch (error) {
|
|
738
|
+
await emit({
|
|
739
|
+
role: "runner",
|
|
740
|
+
kind: "checkpoint",
|
|
741
|
+
content: `Forge completion tool cleanup failed and was ignored: ${clip(messageFromError(error), 600)}`,
|
|
742
|
+
eventType: "completion_tools_cleanup_failed"
|
|
743
|
+
}).catch(() => undefined);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
async function commitWorktreeChanges(git, worktreePath, workItemId) {
|
|
747
|
+
await git.run(worktreePath, ["add", "-A"]);
|
|
748
|
+
await git.run(worktreePath, ["reset", "--", ".forge"]).catch(() => "");
|
|
749
|
+
const changedFiles = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
|
|
750
|
+
.split(/\r?\n/)
|
|
751
|
+
.map((line) => line.trim())
|
|
752
|
+
.filter(Boolean);
|
|
753
|
+
if (changedFiles.length > 0) {
|
|
754
|
+
await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
|
|
109
755
|
}
|
|
110
|
-
|
|
756
|
+
else {
|
|
757
|
+
await git.run(worktreePath, ["commit", "--allow-empty", "-m", `provider cli completed for ${workItemId.slice(0, 8)}`]);
|
|
758
|
+
}
|
|
759
|
+
const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
760
|
+
return { commitSha, changedFiles };
|
|
761
|
+
}
|
|
762
|
+
function messageFromError(error) {
|
|
763
|
+
return error instanceof Error ? error.message : String(error);
|
|
764
|
+
}
|
|
765
|
+
function clip(value, maxLength) {
|
|
766
|
+
if (value.length <= maxLength) {
|
|
767
|
+
return value;
|
|
768
|
+
}
|
|
769
|
+
return `${value.slice(0, maxLength)}...`;
|
|
770
|
+
}
|
|
771
|
+
function createProviderOutputState(provider) {
|
|
772
|
+
return provider.trim().toLowerCase() === "cursor"
|
|
773
|
+
? new CursorStreamJsonState()
|
|
774
|
+
: new CodexJsonState();
|
|
775
|
+
}
|
|
776
|
+
class CursorStreamJsonState {
|
|
777
|
+
sessionId = null;
|
|
778
|
+
finalMessage = null;
|
|
779
|
+
emittedSession = false;
|
|
780
|
+
get sessionLabel() {
|
|
781
|
+
return this.sessionId ? `session ${this.sessionId}` : null;
|
|
782
|
+
}
|
|
783
|
+
consume(line) {
|
|
784
|
+
const event = parseJsonLine(line);
|
|
785
|
+
if (!event) {
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
788
|
+
const type = stringField(event, "type");
|
|
789
|
+
if (type === "system" && stringField(event, "subtype") === "init") {
|
|
790
|
+
this.sessionId = stringField(event, "session_id");
|
|
791
|
+
if (this.sessionId && !this.emittedSession) {
|
|
792
|
+
this.emittedSession = true;
|
|
793
|
+
return {
|
|
794
|
+
role: "runner",
|
|
795
|
+
kind: "checkpoint",
|
|
796
|
+
content: `Cursor session started: ${this.sessionId}.`,
|
|
797
|
+
eventType: "provider_thread_started"
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
if (type === "assistant") {
|
|
802
|
+
const text = assistantMessageText(event);
|
|
803
|
+
if (text) {
|
|
804
|
+
this.finalMessage = clip(text, 4000);
|
|
805
|
+
return {
|
|
806
|
+
role: "assistant",
|
|
807
|
+
kind: "message",
|
|
808
|
+
content: this.finalMessage,
|
|
809
|
+
eventType: "provider_message"
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
if (type === "tool_call") {
|
|
814
|
+
const subtype = stringField(event, "subtype");
|
|
815
|
+
const toolCall = objectField(event, "tool_call");
|
|
816
|
+
if (subtype === "started") {
|
|
817
|
+
const summary = formatCursorToolCallStarted(toolCall);
|
|
818
|
+
if (summary) {
|
|
819
|
+
return {
|
|
820
|
+
role: "worker",
|
|
821
|
+
kind: "checkpoint",
|
|
822
|
+
content: summary,
|
|
823
|
+
eventType: "provider_tool_call"
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
if (subtype === "completed") {
|
|
828
|
+
const completed = formatCursorToolCallCompleted(toolCall);
|
|
829
|
+
if (completed) {
|
|
830
|
+
return {
|
|
831
|
+
role: "worker",
|
|
832
|
+
kind: completed.kind,
|
|
833
|
+
content: completed.content,
|
|
834
|
+
eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
if (type === "result" && stringField(event, "subtype") === "success") {
|
|
840
|
+
const result = stringField(event, "result");
|
|
841
|
+
if (result) {
|
|
842
|
+
this.finalMessage = clip(result, 4000);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
if (type === "error" || (type === "result" && event.is_error === true)) {
|
|
846
|
+
return {
|
|
847
|
+
role: "runner",
|
|
848
|
+
kind: "error",
|
|
849
|
+
content: clip(line.trim(), 1000),
|
|
850
|
+
eventType: "provider_cli_error"
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
return null;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
function formatCursorToolCallStarted(toolCall) {
|
|
857
|
+
const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
|
|
858
|
+
const readPath = stringField(readArgs, "path");
|
|
859
|
+
if (readPath) {
|
|
860
|
+
return `Reading ${readPath}`;
|
|
861
|
+
}
|
|
862
|
+
const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
|
|
863
|
+
const writePath = stringField(writeArgs, "path");
|
|
864
|
+
if (writePath) {
|
|
865
|
+
return `Writing ${writePath}`;
|
|
866
|
+
}
|
|
867
|
+
const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
|
|
868
|
+
const command = stringField(shellArgs, "command");
|
|
869
|
+
if (command) {
|
|
870
|
+
return `Shell command started: ${clip(command, 500)}`;
|
|
871
|
+
}
|
|
872
|
+
const fn = objectField(toolCall, "function");
|
|
873
|
+
const name = stringField(fn, "name");
|
|
874
|
+
if (name) {
|
|
875
|
+
return `Tool call started: ${name}`;
|
|
876
|
+
}
|
|
877
|
+
return null;
|
|
878
|
+
}
|
|
879
|
+
function formatCursorToolCallCompleted(toolCall) {
|
|
880
|
+
const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
|
|
881
|
+
const writePath = stringField(writeArgs, "path");
|
|
882
|
+
const writeResult = objectField(objectField(objectField(toolCall, "writeToolCall"), "result"), "success");
|
|
883
|
+
const writtenPath = stringField(writeResult, "path") ?? writePath;
|
|
884
|
+
if (writtenPath) {
|
|
885
|
+
return {
|
|
886
|
+
kind: "file_edit",
|
|
887
|
+
content: `Wrote ${writtenPath}`
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
|
|
891
|
+
const readPath = stringField(readArgs, "path");
|
|
892
|
+
if (readPath) {
|
|
893
|
+
const readResult = objectField(objectField(objectField(toolCall, "readToolCall"), "result"), "success");
|
|
894
|
+
const totalLines = readResult.totalLines;
|
|
895
|
+
const lineSummary = typeof totalLines === "number" ? ` (${totalLines} lines)` : "";
|
|
896
|
+
return {
|
|
897
|
+
kind: "checkpoint",
|
|
898
|
+
content: `Read ${readPath}${lineSummary}`
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
|
|
902
|
+
const command = stringField(shellArgs, "command");
|
|
903
|
+
if (command) {
|
|
904
|
+
return {
|
|
905
|
+
kind: "checkpoint",
|
|
906
|
+
content: `Shell command completed: ${clip(command, 500)}`
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
const fn = objectField(toolCall, "function");
|
|
910
|
+
const name = stringField(fn, "name");
|
|
911
|
+
if (name) {
|
|
912
|
+
return {
|
|
913
|
+
kind: "checkpoint",
|
|
914
|
+
content: `Tool call completed: ${name}`
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
return null;
|
|
918
|
+
}
|
|
919
|
+
function assistantMessageText(event) {
|
|
920
|
+
const message = objectField(event, "message");
|
|
921
|
+
const content = message.content;
|
|
922
|
+
if (!Array.isArray(content)) {
|
|
923
|
+
return null;
|
|
924
|
+
}
|
|
925
|
+
const parts = content
|
|
926
|
+
.map((entry) => {
|
|
927
|
+
if (!entry || typeof entry !== "object") {
|
|
928
|
+
return null;
|
|
929
|
+
}
|
|
930
|
+
const block = entry;
|
|
931
|
+
return stringField(block, "text");
|
|
932
|
+
})
|
|
933
|
+
.filter((text) => Boolean(text));
|
|
934
|
+
if (parts.length === 0) {
|
|
935
|
+
return null;
|
|
936
|
+
}
|
|
937
|
+
return parts.join("");
|
|
938
|
+
}
|
|
939
|
+
function parseJsonLine(line) {
|
|
940
|
+
const trimmed = line.trim();
|
|
941
|
+
if (!trimmed.startsWith("{")) {
|
|
942
|
+
return null;
|
|
943
|
+
}
|
|
944
|
+
let parsed;
|
|
945
|
+
try {
|
|
946
|
+
parsed = JSON.parse(trimmed);
|
|
947
|
+
}
|
|
948
|
+
catch {
|
|
949
|
+
return null;
|
|
950
|
+
}
|
|
951
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
952
|
+
? parsed
|
|
953
|
+
: null;
|
|
954
|
+
}
|
|
955
|
+
class CodexJsonState {
|
|
956
|
+
threadId = null;
|
|
957
|
+
finalMessage = null;
|
|
958
|
+
emittedThread = false;
|
|
959
|
+
get sessionLabel() {
|
|
960
|
+
return this.threadId ? `thread ${this.threadId}` : null;
|
|
961
|
+
}
|
|
962
|
+
consume(line) {
|
|
963
|
+
const event = parseJsonLine(line);
|
|
964
|
+
if (!event) {
|
|
965
|
+
return null;
|
|
966
|
+
}
|
|
967
|
+
const type = stringField(event, "type") ?? "";
|
|
968
|
+
if (type === "thread.started") {
|
|
969
|
+
this.threadId = stringField(event, "thread_id");
|
|
970
|
+
if (this.threadId && !this.emittedThread) {
|
|
971
|
+
this.emittedThread = true;
|
|
972
|
+
return {
|
|
973
|
+
role: "runner",
|
|
974
|
+
kind: "checkpoint",
|
|
975
|
+
content: `Codex thread started: ${this.threadId}.`,
|
|
976
|
+
eventType: "provider_thread_started"
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
if (type === "turn.completed") {
|
|
981
|
+
return {
|
|
982
|
+
role: "runner",
|
|
983
|
+
kind: "checkpoint",
|
|
984
|
+
content: "Codex turn completed.",
|
|
985
|
+
eventType: "provider_turn_completed"
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
if (type === "turn.failed" || type === "error") {
|
|
989
|
+
return {
|
|
990
|
+
role: "runner",
|
|
991
|
+
kind: "error",
|
|
992
|
+
content: clip(line.trim(), 1000),
|
|
993
|
+
eventType: "provider_cli_error"
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
if (type === "item.completed" || type === "item.updated") {
|
|
997
|
+
const item = objectField(event, "item");
|
|
998
|
+
const itemType = stringField(item, "type");
|
|
999
|
+
if (itemType === "agent_message") {
|
|
1000
|
+
const text = stringField(item, "text");
|
|
1001
|
+
if (text) {
|
|
1002
|
+
this.finalMessage = clip(text, 4000);
|
|
1003
|
+
return {
|
|
1004
|
+
role: "assistant",
|
|
1005
|
+
kind: "message",
|
|
1006
|
+
content: this.finalMessage,
|
|
1007
|
+
eventType: "provider_message"
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
if (itemType === "command_execution") {
|
|
1012
|
+
const command = stringField(item, "command");
|
|
1013
|
+
const status = stringField(item, "status");
|
|
1014
|
+
if (command) {
|
|
1015
|
+
return {
|
|
1016
|
+
role: "worker",
|
|
1017
|
+
kind: "checkpoint",
|
|
1018
|
+
content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
|
|
1019
|
+
eventType: "provider_command"
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
return null;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
function objectField(source, key) {
|
|
1028
|
+
const value = source[key];
|
|
1029
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
1030
|
+
? value
|
|
1031
|
+
: {};
|
|
1032
|
+
}
|
|
1033
|
+
function stringField(source, key) {
|
|
1034
|
+
const value = source[key];
|
|
1035
|
+
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
111
1036
|
}
|