@loucompanion/forge-bridge 0.1.1-dev.7d43998c4521 → 0.1.1-dev.ac486debe210
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 -2
- package/dist/session/provider-cli/provider-cli.service.d.ts +48 -3
- package/dist/session/provider-cli/provider-cli.service.js +1241 -42
- package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
- package/dist/session/provider-cli/provider-usage.d.ts +25 -0
- package/dist/session/provider-cli/provider-usage.js +64 -0
- package/dist/session/session.service.js +51 -11
- package/dist/session/session.types.d.ts +18 -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 +1 -1
|
@@ -1,7 +1,253 @@
|
|
|
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, artifactRootFor } from "../phase-completion.js";
|
|
11
|
+
import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
|
|
12
|
+
const fakeWorkerModel = "server-local-fake-worker";
|
|
13
|
+
const execFileAsync = promisify(execFile);
|
|
14
|
+
const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
|
|
15
|
+
export class RoutingProviderCliService {
|
|
16
|
+
realProvider;
|
|
17
|
+
deterministicProvider;
|
|
18
|
+
constructor(realProvider = new ProcessBackedProviderCliService(), deterministicProvider = new DeterministicProviderCliService()) {
|
|
19
|
+
this.realProvider = realProvider;
|
|
20
|
+
this.deterministicProvider = deterministicProvider;
|
|
21
|
+
}
|
|
22
|
+
async runImplementation(context) {
|
|
23
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
24
|
+
? await this.deterministicProvider.runImplementation(context)
|
|
25
|
+
: await this.realProvider.runImplementation(context);
|
|
26
|
+
}
|
|
27
|
+
async runConflictResolve(context) {
|
|
28
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
29
|
+
? await this.deterministicProvider.runConflictResolve(context)
|
|
30
|
+
: await this.realProvider.runConflictResolve(context);
|
|
31
|
+
}
|
|
32
|
+
async runQa(context) {
|
|
33
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
34
|
+
? await this.deterministicProvider.runQa(context)
|
|
35
|
+
: await this.realProvider.runQa(context);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export class ProcessBackedProviderCliService {
|
|
39
|
+
processRunner;
|
|
40
|
+
git;
|
|
41
|
+
constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient()) {
|
|
42
|
+
this.processRunner = processRunner;
|
|
43
|
+
this.git = git;
|
|
44
|
+
}
|
|
45
|
+
async runImplementation(context) {
|
|
46
|
+
const { dispatch, worktree } = context;
|
|
47
|
+
const phase = completionPhaseFromDispatch(dispatch);
|
|
48
|
+
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
49
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
50
|
+
await fs.mkdir(metadataRoot, { recursive: true });
|
|
51
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
52
|
+
if (!laneCommand) {
|
|
53
|
+
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
54
|
+
}
|
|
55
|
+
const specBody = buildSpecBody(laneCommand, dispatch.workItem, phase);
|
|
56
|
+
const specPath = path.join(metadataRoot, "spec.md");
|
|
57
|
+
await fs.writeFile(specPath, specBody, "utf8");
|
|
58
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
59
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
|
|
60
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
61
|
+
worktreePath: worktree.worktreePath,
|
|
62
|
+
prompt: developCycle ? buildDevelopCyclePrompt(dispatch, phase) : buildImplementationPrompt(dispatch, phase),
|
|
63
|
+
completionTools
|
|
64
|
+
});
|
|
65
|
+
await context.emit({
|
|
66
|
+
role: "runner",
|
|
67
|
+
kind: "checkpoint",
|
|
68
|
+
content: `Starting provider CLI: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
|
|
69
|
+
eventType: "provider_cli_started"
|
|
70
|
+
});
|
|
71
|
+
await context.emit({
|
|
72
|
+
role: "runner",
|
|
73
|
+
kind: "checkpoint",
|
|
74
|
+
content: developCycle
|
|
75
|
+
? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
|
|
76
|
+
: `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
|
|
77
|
+
eventType: "completion_tools_configured"
|
|
78
|
+
});
|
|
79
|
+
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
80
|
+
const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, context.emit);
|
|
81
|
+
let result;
|
|
82
|
+
try {
|
|
83
|
+
liveCompletionEvents.start();
|
|
84
|
+
result = await this.processRunner.run({
|
|
85
|
+
command: command.command,
|
|
86
|
+
args: command.args,
|
|
87
|
+
cwd: worktree.worktreePath,
|
|
88
|
+
env: providerRedactionEnv(dispatch)
|
|
89
|
+
}, {
|
|
90
|
+
onStdoutLine: async (line) => {
|
|
91
|
+
const event = outputState.consume(line);
|
|
92
|
+
if (event) {
|
|
93
|
+
await context.emit(event);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}, context.signal);
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
await liveCompletionEvents.stop();
|
|
100
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
101
|
+
}
|
|
102
|
+
if (result.exitCode !== 0) {
|
|
103
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
104
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
105
|
+
}
|
|
106
|
+
await context.emit({
|
|
107
|
+
role: "runner",
|
|
108
|
+
kind: "checkpoint",
|
|
109
|
+
content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
|
|
110
|
+
eventType: "provider_cli_completed"
|
|
111
|
+
});
|
|
112
|
+
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
113
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
114
|
+
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle);
|
|
115
|
+
for (const artifact of completionArtifacts) {
|
|
116
|
+
if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
|
|
117
|
+
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
|
|
118
|
+
await emitPhaseCompletionEvent(context.emit, artifact);
|
|
119
|
+
await emitPhaseGateEvents(context.emit, artifact);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const completionArtifact = completionArtifacts[0];
|
|
123
|
+
if (outputState.finalMessage) {
|
|
124
|
+
await context.emit({
|
|
125
|
+
role: "assistant",
|
|
126
|
+
kind: "message",
|
|
127
|
+
content: outputState.finalMessage,
|
|
128
|
+
eventType: "provider_final_message"
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
await context.emit({
|
|
133
|
+
role: "assistant",
|
|
134
|
+
kind: "message",
|
|
135
|
+
content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
|
|
136
|
+
eventType: "provider_final_message"
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
|
|
141
|
+
spec: {
|
|
142
|
+
repoPath: worktree.worktreePath,
|
|
143
|
+
path: specPath,
|
|
144
|
+
body: specBody,
|
|
145
|
+
producedBy: "forge-lane-command",
|
|
146
|
+
status: "approved"
|
|
147
|
+
},
|
|
148
|
+
artifact: completionArtifact,
|
|
149
|
+
artifacts: completionArtifacts
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
async runQa(context) {
|
|
153
|
+
const { dispatch, worktree } = context;
|
|
154
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
155
|
+
worktreePath: worktree.worktreePath,
|
|
156
|
+
prompt: buildQaPrompt(dispatch)
|
|
157
|
+
});
|
|
158
|
+
const commandText = formatProviderCliCommand(command);
|
|
159
|
+
await context.emit({
|
|
160
|
+
role: "runner",
|
|
161
|
+
kind: "checkpoint",
|
|
162
|
+
content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
|
|
163
|
+
eventType: "provider_cli_started"
|
|
164
|
+
});
|
|
165
|
+
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
166
|
+
const result = await this.processRunner.run({
|
|
167
|
+
command: command.command,
|
|
168
|
+
args: command.args,
|
|
169
|
+
cwd: worktree.worktreePath,
|
|
170
|
+
env: providerRedactionEnv(dispatch)
|
|
171
|
+
}, {
|
|
172
|
+
onStdoutLine: async (line) => {
|
|
173
|
+
const event = outputState.consume(line);
|
|
174
|
+
if (event) {
|
|
175
|
+
await context.emit(event);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}, context.signal);
|
|
179
|
+
if (result.exitCode !== 0) {
|
|
180
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
181
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
182
|
+
}
|
|
183
|
+
await context.emit({
|
|
184
|
+
role: "runner",
|
|
185
|
+
kind: "checkpoint",
|
|
186
|
+
content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
|
|
187
|
+
eventType: "provider_cli_completed"
|
|
188
|
+
});
|
|
189
|
+
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
190
|
+
const summary = outputState.finalMessage || `${dispatch.execution.provider} CLI QA passed.`;
|
|
191
|
+
const qaArtifact = await writeQaArtifacts({
|
|
192
|
+
worktreePath: worktree.worktreePath,
|
|
193
|
+
workItemId: dispatch.workItem.id,
|
|
194
|
+
acceptanceCriteria: dispatch.workItem.acceptanceCriteria,
|
|
195
|
+
producedBy: `${dispatch.execution.provider}-cli`,
|
|
196
|
+
provider: dispatch.execution.provider,
|
|
197
|
+
model: dispatch.execution.model,
|
|
198
|
+
command: commandText,
|
|
199
|
+
summary
|
|
200
|
+
});
|
|
201
|
+
await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
|
|
202
|
+
return {
|
|
203
|
+
summary: `${dispatch.execution.provider} CLI QA passed.`,
|
|
204
|
+
artifact: qaArtifact,
|
|
205
|
+
artifacts: [qaArtifact]
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
async runConflictResolve(context) {
|
|
209
|
+
const { dispatch, worktree } = context;
|
|
210
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
211
|
+
worktreePath: worktree.worktreePath,
|
|
212
|
+
prompt: buildConflictResolvePrompt(dispatch, worktree.branchName)
|
|
213
|
+
});
|
|
214
|
+
await context.emit({
|
|
215
|
+
role: "runner",
|
|
216
|
+
kind: "checkpoint",
|
|
217
|
+
content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
|
|
218
|
+
eventType: "provider_cli_started"
|
|
219
|
+
});
|
|
220
|
+
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
221
|
+
const result = await this.processRunner.run({
|
|
222
|
+
command: command.command,
|
|
223
|
+
args: command.args,
|
|
224
|
+
cwd: worktree.worktreePath
|
|
225
|
+
}, {
|
|
226
|
+
onStdoutLine: async (line) => {
|
|
227
|
+
const event = outputState.consume(line);
|
|
228
|
+
if (event) {
|
|
229
|
+
await context.emit(event);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}, context.signal);
|
|
233
|
+
if (result.exitCode !== 0) {
|
|
234
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
235
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
236
|
+
}
|
|
237
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
238
|
+
await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
|
|
239
|
+
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
240
|
+
await context.emit({
|
|
241
|
+
role: "assistant",
|
|
242
|
+
kind: "message",
|
|
243
|
+
content: outputState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
|
|
244
|
+
eventType: "conflict_resolve_complete"
|
|
245
|
+
});
|
|
246
|
+
return {
|
|
247
|
+
summary: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
}
|
|
5
251
|
export class DeterministicProviderCliService {
|
|
6
252
|
git;
|
|
7
253
|
constructor(git = new GitClient()) {
|
|
@@ -9,15 +255,27 @@ export class DeterministicProviderCliService {
|
|
|
9
255
|
}
|
|
10
256
|
async runImplementation(context) {
|
|
11
257
|
const { dispatch, worktree } = context;
|
|
258
|
+
const phase = completionPhaseFromDispatch(dispatch);
|
|
259
|
+
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
12
260
|
const providerCommand = buildProviderCliCommand(dispatch);
|
|
13
261
|
const providerCommandText = formatProviderCliCommand(providerCommand);
|
|
14
|
-
const metadataRoot = path.join(worktree.
|
|
262
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
15
263
|
const artifactRoot = path.join(metadataRoot, "artifacts");
|
|
16
264
|
await fs.mkdir(artifactRoot, { recursive: true });
|
|
17
|
-
const
|
|
265
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
266
|
+
if (!laneCommand) {
|
|
267
|
+
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
268
|
+
}
|
|
269
|
+
const specBody = `${buildSpecBody(laneCommand, dispatch.workItem, phase)}
|
|
270
|
+
## Execution
|
|
271
|
+
|
|
272
|
+
- Provider: ${singleLine(dispatch.execution.provider)}
|
|
273
|
+
- Model: ${singleLine(dispatch.execution.model)}
|
|
274
|
+
- Command: ${providerCommandText}
|
|
275
|
+
`;
|
|
18
276
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
19
277
|
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-
|
|
278
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
21
279
|
const changesetPath = path.join(worktree.worktreePath, "FORGE_PHASE5_CHANGESET.md");
|
|
22
280
|
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
281
|
await fs.writeFile(changesetPath, changesetBody, "utf8");
|
|
@@ -29,61 +287,583 @@ export class DeterministicProviderCliService {
|
|
|
29
287
|
content: `Created bridge changeset at ${changesetPath}`,
|
|
30
288
|
eventType: "changeset"
|
|
31
289
|
});
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
290
|
+
const phases = developCycle
|
|
291
|
+
? ["implementation", "self_review", "validation"]
|
|
292
|
+
: [phase];
|
|
293
|
+
const completionArtifacts = [];
|
|
294
|
+
for (const completionPhase of phases) {
|
|
295
|
+
await writeCompletionArtifact({
|
|
296
|
+
worktreePath: worktree.worktreePath,
|
|
297
|
+
workItemId: dispatch.workItem.id,
|
|
298
|
+
phase: completionPhase,
|
|
299
|
+
producedBy: "forge-bridge",
|
|
300
|
+
redactionSecrets: exactRedactionSecrets(dispatch)
|
|
301
|
+
}, expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
|
|
302
|
+
const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
|
|
303
|
+
if (!completionArtifact) {
|
|
304
|
+
throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
|
|
305
|
+
}
|
|
306
|
+
completionArtifacts.push(completionArtifact);
|
|
307
|
+
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
|
|
308
|
+
await context.emit({
|
|
309
|
+
role: "assistant",
|
|
310
|
+
kind: "message",
|
|
311
|
+
content: `${completionPhase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
|
|
312
|
+
eventType: phaseCompleteEventType(completionPhase)
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
|
|
51
316
|
return {
|
|
52
|
-
summary: `forge-bridge completed ${worktree.branchName}.`,
|
|
317
|
+
summary: `forge-bridge completed ${worktree.branchName} (${developCycle ? "develop cycle" : phase}).`,
|
|
53
318
|
spec: {
|
|
54
|
-
repoPath: worktree.
|
|
319
|
+
repoPath: worktree.worktreePath,
|
|
55
320
|
path: specPath,
|
|
56
321
|
body: specBody,
|
|
57
|
-
producedBy: "forge-
|
|
322
|
+
producedBy: "forge-lane-command",
|
|
58
323
|
status: "approved"
|
|
59
324
|
},
|
|
60
|
-
artifact:
|
|
61
|
-
|
|
62
|
-
path: artifactPath,
|
|
63
|
-
verdictJson,
|
|
64
|
-
report,
|
|
65
|
-
producedBy: "forge-bridge",
|
|
66
|
-
status: "pass"
|
|
67
|
-
}
|
|
325
|
+
artifact: completionArtifacts[0],
|
|
326
|
+
artifacts: completionArtifacts
|
|
68
327
|
};
|
|
69
328
|
}
|
|
70
|
-
async runQa(
|
|
71
|
-
|
|
329
|
+
async runQa(context) {
|
|
330
|
+
const { dispatch, worktree } = context;
|
|
331
|
+
await context.emit({
|
|
72
332
|
role: "worker",
|
|
73
333
|
kind: "message",
|
|
74
334
|
content: `Running ${dispatch.execution.provider} QA checks through forge-bridge.`,
|
|
75
335
|
eventType: "qa_analysis"
|
|
76
336
|
});
|
|
77
|
-
|
|
337
|
+
const summary = "All checks passed. forge-bridge QA completed.";
|
|
338
|
+
const qaArtifact = await writeQaArtifacts({
|
|
339
|
+
worktreePath: worktree.worktreePath,
|
|
340
|
+
workItemId: dispatch.workItem.id,
|
|
341
|
+
acceptanceCriteria: dispatch.workItem.acceptanceCriteria,
|
|
342
|
+
producedBy: "forge-bridge",
|
|
343
|
+
provider: dispatch.execution.provider,
|
|
344
|
+
model: dispatch.execution.model,
|
|
345
|
+
command: "forge-bridge deterministic QA",
|
|
346
|
+
summary
|
|
347
|
+
});
|
|
348
|
+
await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
|
|
349
|
+
await context.emit({
|
|
78
350
|
role: "assistant",
|
|
79
351
|
kind: "message",
|
|
80
|
-
content:
|
|
352
|
+
content: summary,
|
|
81
353
|
eventType: "qa_complete"
|
|
82
354
|
});
|
|
355
|
+
await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
|
|
356
|
+
return {
|
|
357
|
+
summary: "forge-bridge QA passed.",
|
|
358
|
+
artifact: qaArtifact,
|
|
359
|
+
artifacts: [qaArtifact]
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
async runConflictResolve(context) {
|
|
363
|
+
const { dispatch, worktree } = context;
|
|
364
|
+
await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
|
|
365
|
+
await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
|
|
366
|
+
await context.emit({
|
|
367
|
+
role: "assistant",
|
|
368
|
+
kind: "message",
|
|
369
|
+
content: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
|
|
370
|
+
eventType: "conflict_resolve_complete"
|
|
371
|
+
});
|
|
372
|
+
return {
|
|
373
|
+
summary: `forge-bridge resolved conflicts for ${worktree.branchName}.`
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
function phaseCompleteEventType(phase) {
|
|
378
|
+
return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
|
|
379
|
+
}
|
|
380
|
+
function deterministicCompletionPayload(phase, dispatch, changesetBody) {
|
|
381
|
+
const changesetHash = sha256(changesetBody);
|
|
382
|
+
const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
|
|
383
|
+
if (phase === "implementation") {
|
|
384
|
+
return {
|
|
385
|
+
status: "pass",
|
|
386
|
+
summary: "forge-bridge produced a deterministic implementation changeset.",
|
|
387
|
+
plan: [{ step: "Create deterministic changeset", status: "done" }],
|
|
388
|
+
changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
|
|
389
|
+
tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
|
|
390
|
+
docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
|
|
391
|
+
acceptance_criteria: [
|
|
392
|
+
{
|
|
393
|
+
criterion,
|
|
394
|
+
evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
|
|
395
|
+
status: "satisfied"
|
|
396
|
+
}
|
|
397
|
+
],
|
|
398
|
+
known_gaps: [],
|
|
399
|
+
next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
if (phase === "self_review") {
|
|
403
|
+
return {
|
|
404
|
+
status: "pass",
|
|
405
|
+
summary: "forge-bridge fake worker completed deterministic self-review.",
|
|
406
|
+
reviewed_diff: true,
|
|
407
|
+
findings: [],
|
|
408
|
+
security_review: {
|
|
409
|
+
status: "pass",
|
|
410
|
+
notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
|
|
411
|
+
},
|
|
412
|
+
edge_case_review: {
|
|
413
|
+
status: "pass",
|
|
414
|
+
notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
|
|
415
|
+
},
|
|
416
|
+
design_review: {
|
|
417
|
+
status: "not_applicable",
|
|
418
|
+
screenshots: [],
|
|
419
|
+
notes: "No UI changes."
|
|
420
|
+
},
|
|
421
|
+
deterministic_comparison: {
|
|
422
|
+
status: "pass",
|
|
423
|
+
command_or_tool: "git diff --stat HEAD~1..HEAD",
|
|
424
|
+
notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
|
|
425
|
+
},
|
|
426
|
+
fixes_applied: [],
|
|
427
|
+
remaining_risks: []
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
return {
|
|
431
|
+
status: "pass",
|
|
432
|
+
summary: "forge-bridge fake worker completed deterministic validation.",
|
|
433
|
+
commands: [
|
|
434
|
+
{
|
|
435
|
+
command: "git status --short && git diff --check",
|
|
436
|
+
exit_code: 0,
|
|
437
|
+
status: "pass",
|
|
438
|
+
summary: "Deterministic validation command completed for the fake-worker changeset."
|
|
439
|
+
}
|
|
440
|
+
],
|
|
441
|
+
acceptance_criteria: [
|
|
442
|
+
{
|
|
443
|
+
criterion,
|
|
444
|
+
evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
|
|
445
|
+
status: "satisfied"
|
|
446
|
+
}
|
|
447
|
+
],
|
|
448
|
+
build_status: "pass",
|
|
449
|
+
test_status: "pass",
|
|
450
|
+
lint_status: "not_applicable",
|
|
451
|
+
design_status: "not_applicable",
|
|
452
|
+
drift_checks: [
|
|
453
|
+
{
|
|
454
|
+
command_or_tool: "git diff --check",
|
|
455
|
+
status: "pass",
|
|
456
|
+
summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
|
|
457
|
+
}
|
|
458
|
+
],
|
|
459
|
+
ready_for_dev_test: true
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
const qaArtifactFileNames = {
|
|
463
|
+
plan: "qa.plan.json",
|
|
464
|
+
evidence: "qa.evidence.json",
|
|
465
|
+
findings: "qa.findings.json",
|
|
466
|
+
verdict: "qa.verdict.json",
|
|
467
|
+
report: "qa.report.md"
|
|
468
|
+
};
|
|
469
|
+
async function writeQaArtifacts(request) {
|
|
470
|
+
const artifactRoot = artifactRootFor(request.worktreePath, request.workItemId);
|
|
471
|
+
await fs.mkdir(artifactRoot, { recursive: true });
|
|
472
|
+
const criterion = request.acceptanceCriteria.trim() || "Forge QA evidence exists";
|
|
473
|
+
const relativeEvidencePath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.evidence);
|
|
474
|
+
const relativeFindingsPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.findings);
|
|
475
|
+
const relativeReportPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.report);
|
|
476
|
+
const planJson = jsonText({
|
|
477
|
+
schema_version: 1,
|
|
478
|
+
phase: "qa",
|
|
479
|
+
checklist: [
|
|
480
|
+
"Review the validated work item against acceptance criteria.",
|
|
481
|
+
"Run relevant provider QA verification.",
|
|
482
|
+
"Confirm no in-scope QA findings remain."
|
|
483
|
+
],
|
|
484
|
+
acceptance_criteria: [criterion]
|
|
485
|
+
});
|
|
486
|
+
const evidenceJson = jsonText({
|
|
487
|
+
schema_version: 1,
|
|
488
|
+
phase: "qa",
|
|
489
|
+
commands: [
|
|
490
|
+
{
|
|
491
|
+
command: request.command,
|
|
492
|
+
exit_code: 0,
|
|
493
|
+
status: "pass",
|
|
494
|
+
summary: `${request.provider} QA completed successfully.`
|
|
495
|
+
}
|
|
496
|
+
],
|
|
497
|
+
browser_checks: [],
|
|
498
|
+
notes: request.summary
|
|
499
|
+
});
|
|
500
|
+
const findingsJson = jsonText({
|
|
501
|
+
schema_version: 1,
|
|
502
|
+
phase: "qa",
|
|
503
|
+
findings: [],
|
|
504
|
+
candidate_bugs: []
|
|
505
|
+
});
|
|
506
|
+
const verdictJson = jsonText({
|
|
507
|
+
schema_version: 1,
|
|
508
|
+
phase: "qa",
|
|
509
|
+
status: "pass",
|
|
510
|
+
summary: request.summary,
|
|
511
|
+
tested_acceptance_criteria: [criterion],
|
|
512
|
+
finding_ids: [],
|
|
513
|
+
candidate_bug_ids: [],
|
|
514
|
+
blocker_reason: null,
|
|
515
|
+
evidence_path: relativeEvidencePath,
|
|
516
|
+
findings_path: relativeFindingsPath,
|
|
517
|
+
report_path: relativeReportPath
|
|
518
|
+
});
|
|
519
|
+
const report = `# QA report\n\n${request.summary}\n\n- Provider: ${singleLine(request.provider)}\n- Model: ${singleLine(request.model)}\n- Command: ${singleLine(request.command)}\n`;
|
|
520
|
+
await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.plan), planJson, "utf8");
|
|
521
|
+
await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.evidence), evidenceJson, "utf8");
|
|
522
|
+
await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.findings), findingsJson, "utf8");
|
|
523
|
+
const verdictPath = path.join(artifactRoot, qaArtifactFileNames.verdict);
|
|
524
|
+
await fs.writeFile(verdictPath, verdictJson, "utf8");
|
|
525
|
+
await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.report), report, "utf8");
|
|
526
|
+
return {
|
|
527
|
+
repoPath: request.worktreePath,
|
|
528
|
+
path: verdictPath,
|
|
529
|
+
verdictJson,
|
|
530
|
+
report,
|
|
531
|
+
producedBy: request.producedBy,
|
|
532
|
+
status: "pass",
|
|
533
|
+
phase: "qa"
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
|
|
537
|
+
const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
|
|
538
|
+
await emit({
|
|
539
|
+
role: "tool",
|
|
540
|
+
kind: "tool_result",
|
|
541
|
+
content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
|
|
542
|
+
eventType: "qa_artifact_recorded"
|
|
543
|
+
});
|
|
544
|
+
await emit({
|
|
545
|
+
role: "hook",
|
|
546
|
+
kind: "checkpoint",
|
|
547
|
+
content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
|
|
548
|
+
eventType: "phase_gate"
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
function qaArtifactRelativePath(workItemId, fileName) {
|
|
552
|
+
return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
|
|
553
|
+
}
|
|
554
|
+
function jsonText(value) {
|
|
555
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
556
|
+
}
|
|
557
|
+
async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
|
|
558
|
+
const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
|
|
559
|
+
await emit({
|
|
560
|
+
role: "tool",
|
|
561
|
+
kind: "tool_result",
|
|
562
|
+
content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
|
|
563
|
+
eventType: "completion_tool_artifact_recorded"
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
async function emitPhaseCompletionEvent(emit, artifact) {
|
|
567
|
+
const phase = completionPhaseFromArtifact(artifact);
|
|
568
|
+
await emit({
|
|
569
|
+
role: "assistant",
|
|
570
|
+
kind: "message",
|
|
571
|
+
content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
|
|
572
|
+
eventType: phaseCompleteEventType(phase)
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
async function emitPhaseGateEvents(emit, artifact) {
|
|
576
|
+
const phase = completionPhaseFromArtifact(artifact);
|
|
577
|
+
const status = (artifact.status ?? "").trim().toLowerCase() || "unknown";
|
|
578
|
+
await emit({
|
|
579
|
+
role: "hook",
|
|
580
|
+
kind: "checkpoint",
|
|
581
|
+
content: `phase_gate: ${phase} artifact accepted with status ${status}.`,
|
|
582
|
+
eventType: "phase_gate"
|
|
583
|
+
});
|
|
584
|
+
if (status !== "pass") {
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
const progression = phase === "implementation"
|
|
588
|
+
? "phase_progression: implementation -> self_review"
|
|
589
|
+
: phase === "self_review"
|
|
590
|
+
? "phase_progression: self_review -> validation"
|
|
591
|
+
: "phase_progression: validation -> QA ready";
|
|
592
|
+
await emit({
|
|
593
|
+
role: "hook",
|
|
594
|
+
kind: "checkpoint",
|
|
595
|
+
content: progression,
|
|
596
|
+
eventType: "phase_gate"
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
function completionPhaseFromArtifact(artifact) {
|
|
600
|
+
const phase = artifact.phase?.trim();
|
|
601
|
+
return phase === "self_review" || phase === "validation" || phase === "implementation"
|
|
602
|
+
? phase
|
|
603
|
+
: "implementation";
|
|
604
|
+
}
|
|
605
|
+
class LiveCompletionArtifactEmitter {
|
|
606
|
+
worktreePath;
|
|
607
|
+
workItemId;
|
|
608
|
+
emit;
|
|
609
|
+
phases;
|
|
610
|
+
emitted = new Set();
|
|
611
|
+
timer = null;
|
|
612
|
+
pending = Promise.resolve();
|
|
613
|
+
constructor(worktreePath, workItemId, phase, developCycle, emit) {
|
|
614
|
+
this.worktreePath = worktreePath;
|
|
615
|
+
this.workItemId = workItemId;
|
|
616
|
+
this.emit = emit;
|
|
617
|
+
this.phases = developCycle
|
|
618
|
+
? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
|
|
619
|
+
: [phase];
|
|
620
|
+
}
|
|
621
|
+
start() {
|
|
622
|
+
void this.pollQueued();
|
|
623
|
+
this.timer = setInterval(() => {
|
|
624
|
+
void this.pollQueued();
|
|
625
|
+
}, 250);
|
|
626
|
+
}
|
|
627
|
+
async stop() {
|
|
628
|
+
if (this.timer) {
|
|
629
|
+
clearInterval(this.timer);
|
|
630
|
+
this.timer = null;
|
|
631
|
+
}
|
|
632
|
+
await this.pollQueued();
|
|
633
|
+
}
|
|
634
|
+
hasEmitted(phase) {
|
|
635
|
+
return this.emitted.has(phase);
|
|
636
|
+
}
|
|
637
|
+
pollQueued() {
|
|
638
|
+
this.pending = this.pending
|
|
639
|
+
.then(() => this.poll())
|
|
640
|
+
.catch(() => undefined);
|
|
641
|
+
return this.pending;
|
|
642
|
+
}
|
|
643
|
+
async poll() {
|
|
644
|
+
for (const phase of this.phases) {
|
|
645
|
+
if (this.emitted.has(phase)) {
|
|
646
|
+
continue;
|
|
647
|
+
}
|
|
648
|
+
const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, phase);
|
|
649
|
+
if (!artifact) {
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
this.emitted.add(phase);
|
|
653
|
+
await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
|
|
654
|
+
await emitPhaseCompletionEvent(this.emit, artifact);
|
|
655
|
+
await emitPhaseGateEvents(this.emit, artifact);
|
|
656
|
+
if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle) {
|
|
663
|
+
if (!developCycle) {
|
|
664
|
+
const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
|
|
665
|
+
if (!artifact) {
|
|
666
|
+
throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
|
|
667
|
+
}
|
|
668
|
+
return [artifact];
|
|
669
|
+
}
|
|
670
|
+
const artifacts = [];
|
|
671
|
+
for (const expectedPhase of ["implementation", "self_review", "validation"]) {
|
|
672
|
+
const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
|
|
673
|
+
if (!artifact) {
|
|
674
|
+
if (artifacts.length === 0) {
|
|
675
|
+
throw new Error("Provider CLI completed but did not call the Forge implementation completion tool.");
|
|
676
|
+
}
|
|
677
|
+
const previous = artifacts[artifacts.length - 1];
|
|
678
|
+
if ((previous.status ?? "").trim().toLowerCase() === "pass") {
|
|
679
|
+
throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
|
|
680
|
+
}
|
|
681
|
+
return artifacts;
|
|
682
|
+
}
|
|
683
|
+
artifacts.push(artifact);
|
|
684
|
+
if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
685
|
+
return artifacts;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return artifacts;
|
|
689
|
+
}
|
|
690
|
+
function providerRedactionEnv(dispatch) {
|
|
691
|
+
const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
|
|
692
|
+
return Object.keys(env).length > 0 ? env : undefined;
|
|
693
|
+
}
|
|
694
|
+
function exactRedactionSecrets(dispatch) {
|
|
695
|
+
return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
|
|
696
|
+
}
|
|
697
|
+
async function emitProviderUsageEvent(emit, dispatch, outputState) {
|
|
698
|
+
const usage = outputState.usage;
|
|
699
|
+
if (hasUsage(usage)) {
|
|
700
|
+
await emit(buildProviderUsageEvent(dispatch, usage));
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
function estimatedDeterministicUsage() {
|
|
704
|
+
return addUsage(emptyUsage("estimated"), {
|
|
705
|
+
inputTokens: 1000,
|
|
706
|
+
outputTokens: 400,
|
|
707
|
+
source: "estimated"
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
export class StreamingProviderProcessRunner {
|
|
711
|
+
async run(request, handlers = {}, signal) {
|
|
712
|
+
const launch = await resolveProviderProcessLaunch(request.command, request.args);
|
|
713
|
+
return await new Promise((resolve, reject) => {
|
|
714
|
+
const child = spawn(launch.command, launch.args, {
|
|
715
|
+
cwd: request.cwd,
|
|
716
|
+
env: request.env ? { ...process.env, ...request.env } : undefined,
|
|
717
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
718
|
+
windowsHide: true
|
|
719
|
+
});
|
|
720
|
+
let stdout = "";
|
|
721
|
+
let stderr = "";
|
|
722
|
+
let settled = false;
|
|
723
|
+
const cleanup = () => {
|
|
724
|
+
signal?.removeEventListener("abort", abort);
|
|
725
|
+
};
|
|
726
|
+
const fail = (error) => {
|
|
727
|
+
if (settled) {
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
settled = true;
|
|
731
|
+
cleanup();
|
|
732
|
+
reject(error);
|
|
733
|
+
};
|
|
734
|
+
const abort = () => {
|
|
735
|
+
try {
|
|
736
|
+
child.kill("SIGTERM");
|
|
737
|
+
}
|
|
738
|
+
catch {
|
|
739
|
+
// Best effort; close/error will settle the promise.
|
|
740
|
+
}
|
|
741
|
+
};
|
|
742
|
+
if (signal?.aborted) {
|
|
743
|
+
abort();
|
|
744
|
+
}
|
|
745
|
+
else {
|
|
746
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
747
|
+
}
|
|
748
|
+
child.on("error", fail);
|
|
749
|
+
const readers = [
|
|
750
|
+
readProcessLines(child.stdout, (line) => {
|
|
751
|
+
stdout += `${line}\n`;
|
|
752
|
+
return handlers.onStdoutLine?.(line);
|
|
753
|
+
}),
|
|
754
|
+
readProcessLines(child.stderr, (line) => {
|
|
755
|
+
stderr += `${line}\n`;
|
|
756
|
+
return handlers.onStderrLine?.(line);
|
|
757
|
+
})
|
|
758
|
+
];
|
|
759
|
+
child.on("close", (code) => {
|
|
760
|
+
Promise.allSettled(readers).then((readerResults) => {
|
|
761
|
+
const rejected = readerResults.find((result) => result.status === "rejected");
|
|
762
|
+
if (rejected?.status === "rejected") {
|
|
763
|
+
fail(rejected.reason);
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
if (settled) {
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
settled = true;
|
|
770
|
+
cleanup();
|
|
771
|
+
resolve({
|
|
772
|
+
exitCode: code ?? 1,
|
|
773
|
+
stdout,
|
|
774
|
+
stderr
|
|
775
|
+
});
|
|
776
|
+
}).catch(fail);
|
|
777
|
+
});
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
async function resolveProviderProcessLaunch(command, args) {
|
|
782
|
+
if (process.platform !== "win32") {
|
|
783
|
+
return { command, args };
|
|
784
|
+
}
|
|
785
|
+
const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
|
|
786
|
+
if (cursorDirect) {
|
|
787
|
+
return cursorDirect;
|
|
788
|
+
}
|
|
789
|
+
const resolved = await resolveWindowsCommand(command);
|
|
790
|
+
return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
|
|
791
|
+
}
|
|
792
|
+
async function resolveWindowsCommand(command) {
|
|
793
|
+
if (path.isAbsolute(command)) {
|
|
794
|
+
return command;
|
|
795
|
+
}
|
|
796
|
+
try {
|
|
797
|
+
const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
|
|
798
|
+
return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
|
|
799
|
+
}
|
|
800
|
+
catch {
|
|
801
|
+
return null;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
export function chooseWindowsCommandCandidate(candidates) {
|
|
805
|
+
const normalized = candidates
|
|
806
|
+
.map((candidate) => candidate.trim())
|
|
807
|
+
.filter((candidate) => candidate.length > 0);
|
|
808
|
+
if (normalized.length === 0) {
|
|
809
|
+
return null;
|
|
810
|
+
}
|
|
811
|
+
const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
|
|
812
|
+
for (const extension of preferredExtensions) {
|
|
813
|
+
const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
|
|
814
|
+
if (candidate) {
|
|
815
|
+
return candidate;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
return normalized[0];
|
|
819
|
+
}
|
|
820
|
+
export function buildWindowsLaunchCommand(commandPath, args) {
|
|
821
|
+
const extension = path.extname(commandPath).toLowerCase();
|
|
822
|
+
if (extension === ".ps1") {
|
|
823
|
+
return {
|
|
824
|
+
command: powershellExecutable(),
|
|
825
|
+
args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", commandPath, ...args]
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
if (extension === ".cmd" || extension === ".bat") {
|
|
83
829
|
return {
|
|
84
|
-
|
|
830
|
+
command: process.env.ComSpec ?? "cmd.exe",
|
|
831
|
+
args: ["/d", "/s", "/c", windowsCommandLine(commandPath, args)]
|
|
85
832
|
};
|
|
86
833
|
}
|
|
834
|
+
return { command: commandPath, args };
|
|
835
|
+
}
|
|
836
|
+
function powershellExecutable() {
|
|
837
|
+
const systemRoot = process.env.SystemRoot;
|
|
838
|
+
return systemRoot
|
|
839
|
+
? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
|
|
840
|
+
: "powershell.exe";
|
|
841
|
+
}
|
|
842
|
+
function windowsCommandLine(command, args) {
|
|
843
|
+
return [command, ...args].map(quoteWindowsCommandLineArg).join(" ");
|
|
844
|
+
}
|
|
845
|
+
function quoteWindowsCommandLineArg(value) {
|
|
846
|
+
if (value.length > 0 && !/[\s"]/.test(value)) {
|
|
847
|
+
return value;
|
|
848
|
+
}
|
|
849
|
+
return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
|
|
850
|
+
}
|
|
851
|
+
async function fileExists(inputPath) {
|
|
852
|
+
return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
|
|
853
|
+
}
|
|
854
|
+
async function readProcessLines(stream, onLine) {
|
|
855
|
+
const reader = readline.createInterface({ input: stream });
|
|
856
|
+
try {
|
|
857
|
+
for await (const line of reader) {
|
|
858
|
+
await onLine(line);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
finally {
|
|
862
|
+
reader.close();
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
function isFakeWorkerModel(model) {
|
|
866
|
+
return model.trim().toLowerCase() === fakeWorkerModel;
|
|
87
867
|
}
|
|
88
868
|
function sha256(content) {
|
|
89
869
|
return crypto.createHash("sha256").update(content).digest("hex");
|
|
@@ -97,15 +877,434 @@ function yamlQuotedScalar(value) {
|
|
|
97
877
|
function singleLine(value) {
|
|
98
878
|
return value.replace(/\s+/g, " ").trim();
|
|
99
879
|
}
|
|
100
|
-
export function buildProviderCliCommand(dispatch) {
|
|
880
|
+
export function buildProviderCliCommand(dispatch, run) {
|
|
101
881
|
const provider = dispatch.execution.provider.trim();
|
|
102
882
|
const normalizedProvider = provider.toLowerCase();
|
|
103
883
|
const model = dispatch.execution.model.trim();
|
|
104
884
|
if (normalizedProvider === "codex") {
|
|
105
|
-
|
|
885
|
+
const args = ["exec"];
|
|
886
|
+
if (run?.completionTools) {
|
|
887
|
+
args.push(...codexMcpConfigArgs(run.completionTools));
|
|
888
|
+
}
|
|
889
|
+
args.push("--model", model);
|
|
890
|
+
if (run) {
|
|
891
|
+
args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
|
|
892
|
+
if (run.worktreePath) {
|
|
893
|
+
args.push("--cd", run.worktreePath);
|
|
894
|
+
}
|
|
895
|
+
args.push(run.prompt ?? "");
|
|
896
|
+
}
|
|
897
|
+
return { command: "codex", args };
|
|
106
898
|
}
|
|
107
899
|
if (normalizedProvider === "cursor") {
|
|
108
|
-
|
|
900
|
+
const args = ["--print", "--output-format", "stream-json", "--model", model];
|
|
901
|
+
if (run?.worktreePath) {
|
|
902
|
+
args.push("--workspace", run.worktreePath);
|
|
903
|
+
}
|
|
904
|
+
if (run?.prompt) {
|
|
905
|
+
args.push("--yolo", "--approve-mcps", "--trust", run.prompt);
|
|
906
|
+
}
|
|
907
|
+
return { command: "cursor-agent", args };
|
|
908
|
+
}
|
|
909
|
+
const args = ["--model", model];
|
|
910
|
+
if (run?.prompt) {
|
|
911
|
+
args.push(run.prompt);
|
|
912
|
+
}
|
|
913
|
+
return { command: provider, args };
|
|
914
|
+
}
|
|
915
|
+
function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
916
|
+
return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
|
|
917
|
+
|
|
918
|
+
Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
|
|
919
|
+
${phaseWorkInstruction(phase)}
|
|
920
|
+
Use the repository's existing conventions. Run relevant tests when practical.
|
|
921
|
+
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
|
|
922
|
+
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
923
|
+
|
|
924
|
+
${completionPromptForPhase(phase)}
|
|
925
|
+
|
|
926
|
+
Finish with a concise summary of changed files and verification after calling the completion tool.`;
|
|
927
|
+
}
|
|
928
|
+
function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
929
|
+
return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
|
|
930
|
+
|
|
931
|
+
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.
|
|
932
|
+
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.
|
|
933
|
+
Use the repository's existing conventions. Run relevant tests when practical.
|
|
934
|
+
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
|
|
935
|
+
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
936
|
+
|
|
937
|
+
${completionPromptForDevelopCycle(phase)}
|
|
938
|
+
|
|
939
|
+
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.`;
|
|
940
|
+
}
|
|
941
|
+
function phaseWorkInstruction(phase) {
|
|
942
|
+
if (phase === "self_review") {
|
|
943
|
+
return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
|
|
944
|
+
}
|
|
945
|
+
if (phase === "validation") {
|
|
946
|
+
return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
|
|
947
|
+
}
|
|
948
|
+
return "Implement the work item and keep the change focused.";
|
|
949
|
+
}
|
|
950
|
+
function buildQaPrompt(dispatch) {
|
|
951
|
+
return `You are Forge's QA lane running locally.
|
|
952
|
+
|
|
953
|
+
Review the implementation for work item ${dispatch.workItem.id}: ${dispatch.workItem.title}
|
|
954
|
+
Run relevant verification when practical and finish with a concise QA verdict.`;
|
|
955
|
+
}
|
|
956
|
+
function buildConflictResolvePrompt(dispatch, branchName) {
|
|
957
|
+
const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
|
|
958
|
+
return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
|
|
959
|
+
|
|
960
|
+
The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
|
|
961
|
+
Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
|
|
962
|
+
Keep the original work item intent intact:
|
|
963
|
+
- Work item: ${dispatch.workItem.id}
|
|
964
|
+
- Title: ${dispatch.workItem.title}
|
|
965
|
+
- Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
|
|
966
|
+
|
|
967
|
+
Finish with a concise summary of the conflicts resolved and verification performed.`;
|
|
968
|
+
}
|
|
969
|
+
async function cleanupCompletionTools(completionTools, emit) {
|
|
970
|
+
try {
|
|
971
|
+
await completionTools.cleanup();
|
|
972
|
+
}
|
|
973
|
+
catch (error) {
|
|
974
|
+
await emit({
|
|
975
|
+
role: "runner",
|
|
976
|
+
kind: "checkpoint",
|
|
977
|
+
content: `Forge completion tool cleanup failed and was ignored: ${clip(messageFromError(error), 600)}`,
|
|
978
|
+
eventType: "completion_tools_cleanup_failed"
|
|
979
|
+
}).catch(() => undefined);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
async function commitWorktreeChanges(git, worktreePath, workItemId) {
|
|
983
|
+
await git.run(worktreePath, ["add", "-A"]);
|
|
984
|
+
await git.run(worktreePath, ["reset", "--", ".forge"]).catch(() => "");
|
|
985
|
+
const changedFiles = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
|
|
986
|
+
.split(/\r?\n/)
|
|
987
|
+
.map((line) => line.trim())
|
|
988
|
+
.filter(Boolean);
|
|
989
|
+
if (changedFiles.length > 0) {
|
|
990
|
+
await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
|
|
991
|
+
}
|
|
992
|
+
else {
|
|
993
|
+
await git.run(worktreePath, ["commit", "--allow-empty", "-m", `provider cli completed for ${workItemId.slice(0, 8)}`]);
|
|
994
|
+
}
|
|
995
|
+
const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
996
|
+
return { commitSha, changedFiles };
|
|
997
|
+
}
|
|
998
|
+
function messageFromError(error) {
|
|
999
|
+
return error instanceof Error ? error.message : String(error);
|
|
1000
|
+
}
|
|
1001
|
+
function clip(value, maxLength) {
|
|
1002
|
+
if (value.length <= maxLength) {
|
|
1003
|
+
return value;
|
|
1004
|
+
}
|
|
1005
|
+
return `${value.slice(0, maxLength)}...`;
|
|
1006
|
+
}
|
|
1007
|
+
function createProviderOutputState(provider) {
|
|
1008
|
+
return provider.trim().toLowerCase() === "cursor"
|
|
1009
|
+
? new CursorStreamJsonState()
|
|
1010
|
+
: new CodexJsonState();
|
|
1011
|
+
}
|
|
1012
|
+
class CursorStreamJsonState {
|
|
1013
|
+
sessionId = null;
|
|
1014
|
+
finalMessage = null;
|
|
1015
|
+
emittedSession = false;
|
|
1016
|
+
accumulatedUsage = null;
|
|
1017
|
+
get sessionLabel() {
|
|
1018
|
+
return this.sessionId ? `session ${this.sessionId}` : null;
|
|
1019
|
+
}
|
|
1020
|
+
get usage() {
|
|
1021
|
+
return this.accumulatedUsage;
|
|
1022
|
+
}
|
|
1023
|
+
consume(line) {
|
|
1024
|
+
const event = parseJsonLine(line);
|
|
1025
|
+
if (!event) {
|
|
1026
|
+
return null;
|
|
1027
|
+
}
|
|
1028
|
+
const type = stringField(event, "type");
|
|
1029
|
+
if (type === "system" && stringField(event, "subtype") === "init") {
|
|
1030
|
+
this.sessionId = stringField(event, "session_id");
|
|
1031
|
+
if (this.sessionId && !this.emittedSession) {
|
|
1032
|
+
this.emittedSession = true;
|
|
1033
|
+
return {
|
|
1034
|
+
role: "runner",
|
|
1035
|
+
kind: "checkpoint",
|
|
1036
|
+
content: `Cursor session started: ${this.sessionId}.`,
|
|
1037
|
+
eventType: "provider_thread_started"
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
if (type === "assistant") {
|
|
1042
|
+
const text = assistantMessageText(event);
|
|
1043
|
+
if (text) {
|
|
1044
|
+
this.finalMessage = clip(text, 4000);
|
|
1045
|
+
return {
|
|
1046
|
+
role: "assistant",
|
|
1047
|
+
kind: "message",
|
|
1048
|
+
content: this.finalMessage,
|
|
1049
|
+
eventType: "provider_message"
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
if (type === "tool_call") {
|
|
1054
|
+
const subtype = stringField(event, "subtype");
|
|
1055
|
+
const toolCall = objectField(event, "tool_call");
|
|
1056
|
+
if (subtype === "started") {
|
|
1057
|
+
const summary = formatCursorToolCallStarted(toolCall);
|
|
1058
|
+
if (summary) {
|
|
1059
|
+
return {
|
|
1060
|
+
role: "worker",
|
|
1061
|
+
kind: "checkpoint",
|
|
1062
|
+
content: summary,
|
|
1063
|
+
eventType: "provider_tool_call"
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
if (subtype === "completed") {
|
|
1068
|
+
const completed = formatCursorToolCallCompleted(toolCall);
|
|
1069
|
+
if (completed) {
|
|
1070
|
+
return {
|
|
1071
|
+
role: "worker",
|
|
1072
|
+
kind: completed.kind,
|
|
1073
|
+
content: completed.content,
|
|
1074
|
+
eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
if (type === "result" && stringField(event, "subtype") === "success") {
|
|
1080
|
+
const result = stringField(event, "result");
|
|
1081
|
+
if (result) {
|
|
1082
|
+
this.finalMessage = clip(result, 4000);
|
|
1083
|
+
}
|
|
1084
|
+
this.accumulateUsage(event);
|
|
1085
|
+
}
|
|
1086
|
+
if (type === "error" || (type === "result" && event.is_error === true)) {
|
|
1087
|
+
return {
|
|
1088
|
+
role: "runner",
|
|
1089
|
+
kind: "error",
|
|
1090
|
+
content: clip(line.trim(), 1000),
|
|
1091
|
+
eventType: "provider_cli_error"
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
return null;
|
|
1095
|
+
}
|
|
1096
|
+
accumulateUsage(event) {
|
|
1097
|
+
const usage = objectField(event, "usage");
|
|
1098
|
+
const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
|
|
1099
|
+
if (Object.keys(usage).length === 0 && durationMs === 0) {
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
|
|
1103
|
+
inputTokens: readUsageNumber(usage, "inputTokens"),
|
|
1104
|
+
outputTokens: readUsageNumber(usage, "outputTokens"),
|
|
1105
|
+
cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
|
|
1106
|
+
cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
|
|
1107
|
+
providerDurationMs: durationMs > 0 ? durationMs : null,
|
|
1108
|
+
source: "provider_reported"
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
function formatCursorToolCallStarted(toolCall) {
|
|
1113
|
+
const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
|
|
1114
|
+
const readPath = stringField(readArgs, "path");
|
|
1115
|
+
if (readPath) {
|
|
1116
|
+
return `Reading ${readPath}`;
|
|
1117
|
+
}
|
|
1118
|
+
const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
|
|
1119
|
+
const writePath = stringField(writeArgs, "path");
|
|
1120
|
+
if (writePath) {
|
|
1121
|
+
return `Writing ${writePath}`;
|
|
1122
|
+
}
|
|
1123
|
+
const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
|
|
1124
|
+
const command = stringField(shellArgs, "command");
|
|
1125
|
+
if (command) {
|
|
1126
|
+
return `Shell command started: ${clip(command, 500)}`;
|
|
1127
|
+
}
|
|
1128
|
+
const fn = objectField(toolCall, "function");
|
|
1129
|
+
const name = stringField(fn, "name");
|
|
1130
|
+
if (name) {
|
|
1131
|
+
return `Tool call started: ${name}`;
|
|
1132
|
+
}
|
|
1133
|
+
return null;
|
|
1134
|
+
}
|
|
1135
|
+
function formatCursorToolCallCompleted(toolCall) {
|
|
1136
|
+
const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
|
|
1137
|
+
const writePath = stringField(writeArgs, "path");
|
|
1138
|
+
const writeResult = objectField(objectField(objectField(toolCall, "writeToolCall"), "result"), "success");
|
|
1139
|
+
const writtenPath = stringField(writeResult, "path") ?? writePath;
|
|
1140
|
+
if (writtenPath) {
|
|
1141
|
+
return {
|
|
1142
|
+
kind: "file_edit",
|
|
1143
|
+
content: `Wrote ${writtenPath}`
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
|
|
1147
|
+
const readPath = stringField(readArgs, "path");
|
|
1148
|
+
if (readPath) {
|
|
1149
|
+
const readResult = objectField(objectField(objectField(toolCall, "readToolCall"), "result"), "success");
|
|
1150
|
+
const totalLines = readResult.totalLines;
|
|
1151
|
+
const lineSummary = typeof totalLines === "number" ? ` (${totalLines} lines)` : "";
|
|
1152
|
+
return {
|
|
1153
|
+
kind: "checkpoint",
|
|
1154
|
+
content: `Read ${readPath}${lineSummary}`
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
|
|
1158
|
+
const command = stringField(shellArgs, "command");
|
|
1159
|
+
if (command) {
|
|
1160
|
+
return {
|
|
1161
|
+
kind: "checkpoint",
|
|
1162
|
+
content: `Shell command completed: ${clip(command, 500)}`
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
const fn = objectField(toolCall, "function");
|
|
1166
|
+
const name = stringField(fn, "name");
|
|
1167
|
+
if (name) {
|
|
1168
|
+
return {
|
|
1169
|
+
kind: "checkpoint",
|
|
1170
|
+
content: `Tool call completed: ${name}`
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
return null;
|
|
1174
|
+
}
|
|
1175
|
+
function assistantMessageText(event) {
|
|
1176
|
+
const message = objectField(event, "message");
|
|
1177
|
+
const content = message.content;
|
|
1178
|
+
if (!Array.isArray(content)) {
|
|
1179
|
+
return null;
|
|
1180
|
+
}
|
|
1181
|
+
const parts = content
|
|
1182
|
+
.map((entry) => {
|
|
1183
|
+
if (!entry || typeof entry !== "object") {
|
|
1184
|
+
return null;
|
|
1185
|
+
}
|
|
1186
|
+
const block = entry;
|
|
1187
|
+
return stringField(block, "text");
|
|
1188
|
+
})
|
|
1189
|
+
.filter((text) => Boolean(text));
|
|
1190
|
+
if (parts.length === 0) {
|
|
1191
|
+
return null;
|
|
1192
|
+
}
|
|
1193
|
+
return parts.join("");
|
|
1194
|
+
}
|
|
1195
|
+
function parseJsonLine(line) {
|
|
1196
|
+
const trimmed = line.trim();
|
|
1197
|
+
if (!trimmed.startsWith("{")) {
|
|
1198
|
+
return null;
|
|
1199
|
+
}
|
|
1200
|
+
let parsed;
|
|
1201
|
+
try {
|
|
1202
|
+
parsed = JSON.parse(trimmed);
|
|
1203
|
+
}
|
|
1204
|
+
catch {
|
|
1205
|
+
return null;
|
|
1206
|
+
}
|
|
1207
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
1208
|
+
? parsed
|
|
1209
|
+
: null;
|
|
1210
|
+
}
|
|
1211
|
+
class CodexJsonState {
|
|
1212
|
+
threadId = null;
|
|
1213
|
+
finalMessage = null;
|
|
1214
|
+
emittedThread = false;
|
|
1215
|
+
accumulatedUsage = null;
|
|
1216
|
+
get sessionLabel() {
|
|
1217
|
+
return this.threadId ? `thread ${this.threadId}` : null;
|
|
1218
|
+
}
|
|
1219
|
+
get usage() {
|
|
1220
|
+
return this.accumulatedUsage;
|
|
1221
|
+
}
|
|
1222
|
+
consume(line) {
|
|
1223
|
+
const event = parseJsonLine(line);
|
|
1224
|
+
if (!event) {
|
|
1225
|
+
return null;
|
|
1226
|
+
}
|
|
1227
|
+
const type = stringField(event, "type") ?? "";
|
|
1228
|
+
if (type === "thread.started") {
|
|
1229
|
+
this.threadId = stringField(event, "thread_id");
|
|
1230
|
+
if (this.threadId && !this.emittedThread) {
|
|
1231
|
+
this.emittedThread = true;
|
|
1232
|
+
return {
|
|
1233
|
+
role: "runner",
|
|
1234
|
+
kind: "checkpoint",
|
|
1235
|
+
content: `Codex thread started: ${this.threadId}.`,
|
|
1236
|
+
eventType: "provider_thread_started"
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
if (type === "turn.completed") {
|
|
1241
|
+
this.accumulateUsage(event);
|
|
1242
|
+
return {
|
|
1243
|
+
role: "runner",
|
|
1244
|
+
kind: "checkpoint",
|
|
1245
|
+
content: "Codex turn completed.",
|
|
1246
|
+
eventType: "provider_turn_completed"
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
if (type === "turn.failed" || type === "error") {
|
|
1250
|
+
return {
|
|
1251
|
+
role: "runner",
|
|
1252
|
+
kind: "error",
|
|
1253
|
+
content: clip(line.trim(), 1000),
|
|
1254
|
+
eventType: "provider_cli_error"
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
if (type === "item.completed" || type === "item.updated") {
|
|
1258
|
+
const item = objectField(event, "item");
|
|
1259
|
+
const itemType = stringField(item, "type");
|
|
1260
|
+
if (itemType === "agent_message") {
|
|
1261
|
+
const text = stringField(item, "text");
|
|
1262
|
+
if (text) {
|
|
1263
|
+
this.finalMessage = clip(text, 4000);
|
|
1264
|
+
return {
|
|
1265
|
+
role: "assistant",
|
|
1266
|
+
kind: "message",
|
|
1267
|
+
content: this.finalMessage,
|
|
1268
|
+
eventType: "provider_message"
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
if (itemType === "command_execution") {
|
|
1273
|
+
const command = stringField(item, "command");
|
|
1274
|
+
const status = stringField(item, "status");
|
|
1275
|
+
if (command) {
|
|
1276
|
+
return {
|
|
1277
|
+
role: "worker",
|
|
1278
|
+
kind: "checkpoint",
|
|
1279
|
+
content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
|
|
1280
|
+
eventType: "provider_command"
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
return null;
|
|
109
1286
|
}
|
|
110
|
-
|
|
1287
|
+
accumulateUsage(event) {
|
|
1288
|
+
const usage = objectField(event, "usage");
|
|
1289
|
+
if (Object.keys(usage).length === 0) {
|
|
1290
|
+
return;
|
|
1291
|
+
}
|
|
1292
|
+
this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
|
|
1293
|
+
inputTokens: readUsageNumber(usage, "input_tokens"),
|
|
1294
|
+
outputTokens: readUsageNumber(usage, "output_tokens"),
|
|
1295
|
+
cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
|
|
1296
|
+
reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
|
|
1297
|
+
source: "provider_reported"
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
function objectField(source, key) {
|
|
1302
|
+
const value = source[key];
|
|
1303
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
1304
|
+
? value
|
|
1305
|
+
: {};
|
|
1306
|
+
}
|
|
1307
|
+
function stringField(source, key) {
|
|
1308
|
+
const value = source[key];
|
|
1309
|
+
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
111
1310
|
}
|