@cyfsh/adapters 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters.d.ts +39 -15
- package/dist/adapters.d.ts.map +1 -1
- package/dist/adapters.js +768 -88
- package/dist/adapters.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/sandbox-responder.d.ts.map +1 -1
- package/dist/sandbox-responder.js +55 -25
- package/dist/sandbox-responder.js.map +1 -1
- package/dist/types.d.ts +17 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/adapters.js
CHANGED
|
@@ -1,9 +1,324 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
2
3
|
import os from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { AGENT_ENGINE_CATALOG } from "@cyfsh/protocol";
|
|
5
6
|
import { buildGuardArtifactBundle } from "./guard-generator.js";
|
|
6
7
|
import { buildRuntimeSystemEnvelope, runSandboxResponder, } from "./sandbox-responder.js";
|
|
8
|
+
/**
|
|
9
|
+
* Resolves a CLI binary across PATH, unwrapping Windows `.cmd` npm shims into direct
|
|
10
|
+
* `.exe` or `node <entrypoint>` invocations (`shell: false`) to prevent Node 22 `EINVAL`
|
|
11
|
+
* and `cmd.exe` argument mangling.
|
|
12
|
+
*/
|
|
13
|
+
export function resolveCliSpawnTarget(binaryName, customPathEnv) {
|
|
14
|
+
if (path.isAbsolute(binaryName) && fs.existsSync(binaryName)) {
|
|
15
|
+
return unwrapCmdShimIfNeeded(binaryName);
|
|
16
|
+
}
|
|
17
|
+
const rawPath = customPathEnv ?? process.env["PATH"] ?? process.env["Path"] ?? "";
|
|
18
|
+
if (!rawPath) {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
const pathDirs = rawPath.split(path.delimiter).filter(Boolean);
|
|
22
|
+
const extensions = process.platform === "win32"
|
|
23
|
+
? [".exe", ".cmd", ".bat", ".ps1"]
|
|
24
|
+
: [""];
|
|
25
|
+
for (const dir of pathDirs) {
|
|
26
|
+
for (const ext of extensions) {
|
|
27
|
+
const candidate = path.join(dir, `${binaryName}${ext}`);
|
|
28
|
+
try {
|
|
29
|
+
const stat = fs.statSync(candidate);
|
|
30
|
+
if (stat.isFile()) {
|
|
31
|
+
return unwrapCmdShimIfNeeded(candidate);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// Ignore inaccessible PATH directory
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
function unwrapCmdShimIfNeeded(resolvedBinaryPath) {
|
|
42
|
+
const lower = resolvedBinaryPath.toLowerCase();
|
|
43
|
+
if (process.platform !== "win32" || (!lower.endsWith(".cmd") && !lower.endsWith(".bat"))) {
|
|
44
|
+
return { command: resolvedBinaryPath, prefixArgs: [], useShell: false };
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const cmdText = fs.readFileSync(resolvedBinaryPath, "utf8");
|
|
48
|
+
const dp0 = path.dirname(resolvedBinaryPath);
|
|
49
|
+
const matches = cmdText.matchAll(/"%(?:~dp0|dp0%)[\\/]?([^"\r\n]+)"/gi);
|
|
50
|
+
for (const match of matches) {
|
|
51
|
+
const rel = match[1]?.trim();
|
|
52
|
+
if (!rel)
|
|
53
|
+
continue;
|
|
54
|
+
// Skip node.exe itself in `"%dp0%\node.exe" "%dp0%\node_modules\..."` so we pick the real CLI target
|
|
55
|
+
if (/^(?:node|iojs)(?:\.exe)?$/i.test(path.basename(rel))) {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const innerPath = path.resolve(dp0, rel);
|
|
59
|
+
if (fs.existsSync(innerPath) && fs.statSync(innerPath).isFile()) {
|
|
60
|
+
if (innerPath.toLowerCase().endsWith(".exe")) {
|
|
61
|
+
return { command: innerPath, prefixArgs: [], useShell: false };
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
command: process.execPath,
|
|
65
|
+
prefixArgs: [innerPath],
|
|
66
|
+
useShell: false,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// Fall back to shell execution if .cmd wrapper cannot be inspected
|
|
73
|
+
}
|
|
74
|
+
return { command: resolvedBinaryPath, prefixArgs: [], useShell: true };
|
|
75
|
+
}
|
|
76
|
+
function resolveEffectiveMode(options) {
|
|
77
|
+
const envMode = process.env["CYF_RUNTIME_MODE"]?.trim().toLowerCase();
|
|
78
|
+
if (envMode === "sandbox")
|
|
79
|
+
return "sandbox";
|
|
80
|
+
if (envMode === "live")
|
|
81
|
+
return "live";
|
|
82
|
+
if (options.executionMode === "sandbox")
|
|
83
|
+
return "sandbox";
|
|
84
|
+
if (options.executionMode === "live")
|
|
85
|
+
return "live";
|
|
86
|
+
// In automated Vitest / test runs without explicit `executionMode: "live"`, keep tests deterministic
|
|
87
|
+
if (process.env["VITEST"] === "true" || process.env["NODE_ENV"] === "test") {
|
|
88
|
+
return "sandbox";
|
|
89
|
+
}
|
|
90
|
+
return "live";
|
|
91
|
+
}
|
|
92
|
+
function resolveSafeWorkingDir(workspacePath) {
|
|
93
|
+
try {
|
|
94
|
+
if (workspacePath && fs.existsSync(workspacePath) && fs.statSync(workspacePath).isDirectory()) {
|
|
95
|
+
return workspacePath;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// Fall through
|
|
100
|
+
}
|
|
101
|
+
return process.cwd();
|
|
102
|
+
}
|
|
103
|
+
function buildConversationTurnPayload(request) {
|
|
104
|
+
const lines = [];
|
|
105
|
+
if (request.priorGuestTurns.length > 0) {
|
|
106
|
+
lines.push("<prior_guest_discussion>");
|
|
107
|
+
for (const turn of request.priorGuestTurns.slice(-16)) {
|
|
108
|
+
if (turn.blockedByGuard)
|
|
109
|
+
continue;
|
|
110
|
+
const speaker = turn.role === "guest"
|
|
111
|
+
? `Colleague (${turn.guestName ?? request.guestName})`
|
|
112
|
+
: "AI Assistant";
|
|
113
|
+
lines.push(`[${speaker}]:\n${turn.content}`);
|
|
114
|
+
}
|
|
115
|
+
lines.push("</prior_guest_discussion>", "");
|
|
116
|
+
}
|
|
117
|
+
lines.push(`[Colleague (${request.guestName})]:`, request.prompt);
|
|
118
|
+
return lines.join("\n");
|
|
119
|
+
}
|
|
120
|
+
function parseStructuredJsonRecords(records) {
|
|
121
|
+
const replyParts = [];
|
|
122
|
+
const thinkingParts = [];
|
|
123
|
+
let finalResult = null;
|
|
124
|
+
for (const obj of records) {
|
|
125
|
+
const recType = typeof obj["type"] === "string" ? obj["type"] : "";
|
|
126
|
+
if (recType === "result" && typeof obj["result"] === "string") {
|
|
127
|
+
finalResult = obj["result"].trim();
|
|
128
|
+
}
|
|
129
|
+
else if (recType === "reasoning") {
|
|
130
|
+
for (const key of ["rawContent", "summary", "content"]) {
|
|
131
|
+
const arr = obj[key];
|
|
132
|
+
if (Array.isArray(arr)) {
|
|
133
|
+
for (const item of arr) {
|
|
134
|
+
if (typeof item === "object" && item !== null) {
|
|
135
|
+
const b = item;
|
|
136
|
+
const t = typeof b["text"] === "string"
|
|
137
|
+
? b["text"]
|
|
138
|
+
: typeof b["thinking"] === "string"
|
|
139
|
+
? b["thinking"]
|
|
140
|
+
: "";
|
|
141
|
+
if (t)
|
|
142
|
+
thinkingParts.push(t);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
else if ((recType === "assistant" && typeof obj["message"] === "object" && obj["message"] !== null) ||
|
|
149
|
+
(recType === "message" && obj["role"] === "assistant")) {
|
|
150
|
+
const msg = recType === "assistant"
|
|
151
|
+
? obj["message"]
|
|
152
|
+
: obj;
|
|
153
|
+
if (Array.isArray(msg["content"])) {
|
|
154
|
+
for (const block of msg["content"]) {
|
|
155
|
+
if (typeof block === "object" && block !== null) {
|
|
156
|
+
const b = block;
|
|
157
|
+
const bType = typeof b["type"] === "string" ? b["type"] : "";
|
|
158
|
+
if ((bType === "text" || bType === "output_text") &&
|
|
159
|
+
typeof b["text"] === "string") {
|
|
160
|
+
replyParts.push(b["text"]);
|
|
161
|
+
}
|
|
162
|
+
else if ((bType === "thinking" || bType === "reasoning" || bType === "reasoning_text") &&
|
|
163
|
+
(typeof b["thinking"] === "string" || typeof b["text"] === "string")) {
|
|
164
|
+
thinkingParts.push(typeof b["thinking"] === "string" ? b["thinking"] : b["text"]);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
else if (typeof msg["content"] === "string") {
|
|
170
|
+
replyParts.push(msg["content"]);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
else if (!recType && typeof obj["result"] === "string") {
|
|
174
|
+
finalResult = obj["result"].trim();
|
|
175
|
+
}
|
|
176
|
+
else if (!recType && typeof obj["content"] === "string") {
|
|
177
|
+
replyParts.push(obj["content"]);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
reply: (finalResult ?? replyParts.join("\n\n")).trim(),
|
|
182
|
+
thinking: thinkingParts.join("\n").trim(),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function parseClaudeJsonOutput(rawStdout) {
|
|
186
|
+
const trimmed = rawStdout.trim();
|
|
187
|
+
if (!trimmed)
|
|
188
|
+
return { reply: "", thinking: "" };
|
|
189
|
+
// Handle single JSON object (`claude -p --output-format json`) OR JSON array (`codebuddy -p --output-format json`)
|
|
190
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
191
|
+
try {
|
|
192
|
+
const parsed = JSON.parse(trimmed);
|
|
193
|
+
if (Array.isArray(parsed)) {
|
|
194
|
+
const objs = parsed.filter((item) => typeof item === "object" && item !== null);
|
|
195
|
+
const res = parseStructuredJsonRecords(objs);
|
|
196
|
+
if (res.reply)
|
|
197
|
+
return res;
|
|
198
|
+
}
|
|
199
|
+
else if (typeof parsed === "object" && parsed !== null) {
|
|
200
|
+
const res = parseStructuredJsonRecords([parsed]);
|
|
201
|
+
if (res.reply)
|
|
202
|
+
return res;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
// Fall through to NDJSON line-by-line parsing
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const ndjsonRecords = [];
|
|
210
|
+
for (const rawLine of trimmed.split(/\r?\n/)) {
|
|
211
|
+
const line = rawLine.trim();
|
|
212
|
+
if (!line.startsWith("{"))
|
|
213
|
+
continue;
|
|
214
|
+
try {
|
|
215
|
+
const obj = JSON.parse(line);
|
|
216
|
+
if (typeof obj === "object" && obj !== null && !Array.isArray(obj)) {
|
|
217
|
+
ndjsonRecords.push(obj);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
// Ignore non-JSON log lines
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const res = parseStructuredJsonRecords(ndjsonRecords);
|
|
225
|
+
return {
|
|
226
|
+
reply: res.reply || trimmed,
|
|
227
|
+
thinking: res.thinking,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
function parseCodexExecOutput(rawStdout, lastMsgFilePath) {
|
|
231
|
+
const thinkingParts = [];
|
|
232
|
+
const agentMsgParts = [];
|
|
233
|
+
let lastErrorMsg = "";
|
|
234
|
+
for (const rawLine of rawStdout.split(/\r?\n/)) {
|
|
235
|
+
const line = rawLine.trim();
|
|
236
|
+
if (!line.startsWith("{"))
|
|
237
|
+
continue;
|
|
238
|
+
try {
|
|
239
|
+
const ev = JSON.parse(line);
|
|
240
|
+
const item = typeof ev["item"] === "object" && ev["item"] !== null
|
|
241
|
+
? ev["item"]
|
|
242
|
+
: undefined;
|
|
243
|
+
if (ev["type"] === "item.completed" && item) {
|
|
244
|
+
if (item["type"] === "reasoning" && typeof item["text"] === "string") {
|
|
245
|
+
thinkingParts.push(item["text"]);
|
|
246
|
+
}
|
|
247
|
+
else if (item["type"] === "agent_message" && typeof item["text"] === "string") {
|
|
248
|
+
agentMsgParts.push(item["text"]);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
else if (ev["type"] === "turn.failed" && typeof ev["error"] === "object" && ev["error"] !== null) {
|
|
252
|
+
const errObj = ev["error"];
|
|
253
|
+
if (typeof errObj["message"] === "string") {
|
|
254
|
+
lastErrorMsg = errObj["message"];
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
else if (ev["type"] === "error" && typeof ev["message"] === "string") {
|
|
258
|
+
lastErrorMsg = ev["message"];
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
// Ignore non-JSON line
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
let fileReply = "";
|
|
266
|
+
try {
|
|
267
|
+
if (fs.existsSync(lastMsgFilePath)) {
|
|
268
|
+
fileReply = fs.readFileSync(lastMsgFilePath, "utf8").trim();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
// Ignore
|
|
273
|
+
}
|
|
274
|
+
finally {
|
|
275
|
+
try {
|
|
276
|
+
fs.rmSync(lastMsgFilePath, { force: true });
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
// Ignore
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return {
|
|
283
|
+
reply: fileReply || agentMsgParts.join("\n\n").trim(),
|
|
284
|
+
thinking: thinkingParts.join("\n").trim(),
|
|
285
|
+
...(lastErrorMsg ? { errorSummary: lastErrorMsg } : {}),
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function parseOpenCodeJsonOutput(rawStdout) {
|
|
289
|
+
const textParts = [];
|
|
290
|
+
const thinkingParts = [];
|
|
291
|
+
for (const rawLine of rawStdout.split(/\r?\n/)) {
|
|
292
|
+
const line = rawLine.trim();
|
|
293
|
+
if (!line.startsWith("{"))
|
|
294
|
+
continue;
|
|
295
|
+
try {
|
|
296
|
+
const ev = JSON.parse(line);
|
|
297
|
+
const part = typeof ev["part"] === "object" && ev["part"] !== null
|
|
298
|
+
? ev["part"]
|
|
299
|
+
: undefined;
|
|
300
|
+
const evType = typeof ev["type"] === "string" ? ev["type"] : "";
|
|
301
|
+
if (evType === "text" && part && typeof part["text"] === "string") {
|
|
302
|
+
textParts.push(part["text"]);
|
|
303
|
+
}
|
|
304
|
+
else if ((evType === "reasoning" || evType === "thinking") &&
|
|
305
|
+
part &&
|
|
306
|
+
typeof part["text"] === "string") {
|
|
307
|
+
thinkingParts.push(part["text"]);
|
|
308
|
+
}
|
|
309
|
+
else if (typeof ev["text"] === "string") {
|
|
310
|
+
textParts.push(ev["text"]);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
// Ignore non-JSON lines
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
reply: textParts.join("").trim() || rawStdout.trim(),
|
|
319
|
+
thinking: thinkingParts.join("\n").trim(),
|
|
320
|
+
};
|
|
321
|
+
}
|
|
7
322
|
class BaseEngineAdapter {
|
|
8
323
|
options;
|
|
9
324
|
activeProcesses = new Map();
|
|
@@ -26,89 +341,112 @@ class BaseEngineAdapter {
|
|
|
26
341
|
CYF_STRICT_NO_PRIVATE_MCP: "1",
|
|
27
342
|
};
|
|
28
343
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
cwd: spec.cwd,
|
|
54
|
-
env: { ...process.env, ...spec.env },
|
|
55
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
56
|
-
});
|
|
57
|
-
let stdout = "";
|
|
58
|
-
let stderr = "";
|
|
59
|
-
const killHandle = () => {
|
|
60
|
-
if (!child.killed) {
|
|
344
|
+
buildSanitizedChildEnv(extraEnv) {
|
|
345
|
+
const merged = { ...process.env, ...extraEnv };
|
|
346
|
+
// Prevent nested-invocation lockouts when CYF is started from inside Claude Code
|
|
347
|
+
delete merged["CLAUDECODE"];
|
|
348
|
+
delete merged["CLAUDE_CODE_ENTRYPOINT"];
|
|
349
|
+
return merged;
|
|
350
|
+
}
|
|
351
|
+
spawnAndCollect(params) {
|
|
352
|
+
const timeoutMs = this.options.turnTimeoutMs ?? 65_000;
|
|
353
|
+
return new Promise((resolve, reject) => {
|
|
354
|
+
const child = spawn(params.target.command, [...params.target.prefixArgs, ...params.args], {
|
|
355
|
+
cwd: params.cwd,
|
|
356
|
+
env: this.buildSanitizedChildEnv(params.env),
|
|
357
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
358
|
+
shell: params.target.useShell,
|
|
359
|
+
windowsHide: true,
|
|
360
|
+
});
|
|
361
|
+
let stdout = "";
|
|
362
|
+
let stderr = "";
|
|
363
|
+
let timedOut = false;
|
|
364
|
+
let settled = false;
|
|
365
|
+
const killChild = () => {
|
|
366
|
+
if (!child.killed) {
|
|
367
|
+
try {
|
|
61
368
|
child.kill("SIGTERM");
|
|
62
369
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
child.stdout.on("data", (chunk) => {
|
|
66
|
-
stdout += chunk.toString("utf8");
|
|
67
|
-
});
|
|
68
|
-
child.stderr.on("data", (chunk) => {
|
|
69
|
-
stderr += chunk.toString("utf8");
|
|
70
|
-
});
|
|
71
|
-
child.on("error", () => {
|
|
72
|
-
this.activeProcesses.delete(request.context.shareId);
|
|
73
|
-
resolve(sandboxResult);
|
|
74
|
-
});
|
|
75
|
-
child.on("close", (code) => {
|
|
76
|
-
this.activeProcesses.delete(request.context.shareId);
|
|
77
|
-
if (code === 2) {
|
|
78
|
-
resolve({
|
|
79
|
-
blockedByGuard: true,
|
|
80
|
-
guardInterception: {
|
|
81
|
-
ruleId: "SENSITIVE_FILE_ACCESS",
|
|
82
|
-
targetOrPattern: spec.binary,
|
|
83
|
-
reason: stderr.trim() || "Blocked by PreToolUse Fail-Closed Hook (Exit 2).",
|
|
84
|
-
},
|
|
85
|
-
thinkingTrace: `[Live CLI Exit 2] ${stderr.trim()}`,
|
|
86
|
-
replyContent: `[CYF Guard] 底层运行时守卫拦截了受限操作:${stderr.trim() || "Exit Code 2"}`,
|
|
87
|
-
});
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
const trimmed = stdout.trim();
|
|
91
|
-
if (!trimmed) {
|
|
92
|
-
resolve(sandboxResult);
|
|
93
|
-
return;
|
|
370
|
+
catch {
|
|
371
|
+
// Ignore
|
|
94
372
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
this.activeProcesses.set(params.shareId, killChild);
|
|
376
|
+
const timer = setTimeout(() => {
|
|
377
|
+
timedOut = true;
|
|
378
|
+
killChild();
|
|
379
|
+
}, timeoutMs);
|
|
380
|
+
child.stdout.on("data", (chunk) => {
|
|
381
|
+
stdout += chunk.toString("utf8");
|
|
382
|
+
});
|
|
383
|
+
child.stderr.on("data", (chunk) => {
|
|
384
|
+
stderr += chunk.toString("utf8");
|
|
385
|
+
});
|
|
386
|
+
child.on("error", (err) => {
|
|
387
|
+
clearTimeout(timer);
|
|
388
|
+
this.activeProcesses.delete(params.shareId);
|
|
389
|
+
if (!settled) {
|
|
390
|
+
settled = true;
|
|
391
|
+
reject(err);
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
child.on("close", (code) => {
|
|
395
|
+
clearTimeout(timer);
|
|
396
|
+
this.activeProcesses.delete(params.shareId);
|
|
397
|
+
if (!settled) {
|
|
398
|
+
settled = true;
|
|
399
|
+
resolve({ code, stdout, stderr, timedOut });
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
if (params.stdinPayload !== undefined) {
|
|
403
|
+
child.stdin.write(params.stdinPayload, "utf8");
|
|
109
404
|
}
|
|
405
|
+
child.stdin.end();
|
|
110
406
|
});
|
|
111
407
|
}
|
|
408
|
+
async executeGuestTurn(request) {
|
|
409
|
+
// Layer 1: Deterministic Fail-Closed Guard & Grey-Zone Permission Broker pre-check
|
|
410
|
+
const precheck = runSandboxResponder(request);
|
|
411
|
+
if (precheck.blockedByGuard || precheck.greyZoneEscalation) {
|
|
412
|
+
return precheck;
|
|
413
|
+
}
|
|
414
|
+
const mode = resolveEffectiveMode(this.options);
|
|
415
|
+
if (mode === "sandbox") {
|
|
416
|
+
return precheck;
|
|
417
|
+
}
|
|
418
|
+
const cliBinary = AGENT_ENGINE_CATALOG[this.engine].cliBinary;
|
|
419
|
+
const spawnTarget = resolveCliSpawnTarget(cliBinary);
|
|
420
|
+
const isZh = /[\u4e00-\u9fff]/.test(`${request.context.topic} ${request.prompt}`);
|
|
421
|
+
if (!spawnTarget) {
|
|
422
|
+
return {
|
|
423
|
+
blockedByGuard: false,
|
|
424
|
+
runtimeSource: "live-cli",
|
|
425
|
+
thinkingTrace: `[Live CLI Missing] Binary "${cliBinary}" not found in host PATH.`,
|
|
426
|
+
replyContent: isZh
|
|
427
|
+
? `未在发起人电脑 PATH 中检测到 \`${cliBinary}\` 命令行程序,请确认已安装 ${AGENT_ENGINE_CATALOG[this.engine].displayName} 后重试。`
|
|
428
|
+
: `CLI binary \`${cliBinary}\` was not found in the host's PATH. Please ensure ${AGENT_ENGINE_CATALOG[this.engine].displayName} is installed.`,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
try {
|
|
432
|
+
const liveRes = await this.executeLiveCliTurn(request, spawnTarget);
|
|
433
|
+
return {
|
|
434
|
+
runtimeSource: "live-cli",
|
|
435
|
+
...liveRes,
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
catch (err) {
|
|
439
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
440
|
+
return {
|
|
441
|
+
blockedByGuard: false,
|
|
442
|
+
runtimeSource: "live-cli",
|
|
443
|
+
thinkingTrace: `[Live CLI Spawn Error (${cliBinary})] ${errMsg}`,
|
|
444
|
+
replyContent: isZh
|
|
445
|
+
? `调用本地 \`${cliBinary}\` 失败:${errMsg}`
|
|
446
|
+
: `Failed to invoke local \`${cliBinary}\`: ${errMsg}`,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
}
|
|
112
450
|
async cancelActiveSession(shareId) {
|
|
113
451
|
const cancelFn = this.activeProcesses.get(shareId);
|
|
114
452
|
if (cancelFn) {
|
|
@@ -165,12 +503,89 @@ export class ClaudeCodeAdapter extends BaseEngineAdapter {
|
|
|
165
503
|
generatedFiles: bundle.files,
|
|
166
504
|
};
|
|
167
505
|
}
|
|
506
|
+
async executeLiveCliTurn(request, target) {
|
|
507
|
+
const { context } = request;
|
|
508
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
509
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
510
|
+
shareId: context.shareId,
|
|
511
|
+
workspacePath: context.workspacePath,
|
|
512
|
+
permissionTier: context.permissionTier,
|
|
513
|
+
writableGlobs: context.writableGlobs,
|
|
514
|
+
}, true);
|
|
515
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
516
|
+
const systemEnvelopeFile = path.join(artifactsDir, "cyf-system-envelope.txt");
|
|
517
|
+
fs.writeFileSync(systemEnvelopeFile, systemPromptPayload, "utf8");
|
|
518
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
519
|
+
const allowedTools = context.permissionTier === "TIER_2_WORKTREE_SANDBOX"
|
|
520
|
+
? "Read,Glob,Grep,Edit,Write"
|
|
521
|
+
: "Read,Glob,Grep";
|
|
522
|
+
const cliArgs = [
|
|
523
|
+
"-p",
|
|
524
|
+
"--output-format",
|
|
525
|
+
"json",
|
|
526
|
+
"--strict-mcp-config",
|
|
527
|
+
"--mcp-config",
|
|
528
|
+
bundle.emptyMcpConfigPath,
|
|
529
|
+
"--settings",
|
|
530
|
+
bundle.claudeSettingsPath,
|
|
531
|
+
`--tools=${allowedTools}`,
|
|
532
|
+
"--permission-mode",
|
|
533
|
+
"dontAsk",
|
|
534
|
+
"--append-system-prompt-file",
|
|
535
|
+
systemEnvelopeFile,
|
|
536
|
+
];
|
|
537
|
+
if (usesNativeFork) {
|
|
538
|
+
cliArgs.push("--resume", context.rawSessionId, "--fork-session");
|
|
539
|
+
}
|
|
540
|
+
else {
|
|
541
|
+
cliArgs.push("--no-session-persistence");
|
|
542
|
+
}
|
|
543
|
+
const turnInput = usesNativeFork
|
|
544
|
+
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
545
|
+
: buildConversationTurnPayload(request);
|
|
546
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
547
|
+
shareId: context.shareId,
|
|
548
|
+
target,
|
|
549
|
+
args: cliArgs,
|
|
550
|
+
cwd: resolveSafeWorkingDir(context.workspacePath),
|
|
551
|
+
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
552
|
+
stdinPayload: turnInput,
|
|
553
|
+
});
|
|
554
|
+
if (code === 2) {
|
|
555
|
+
return {
|
|
556
|
+
blockedByGuard: true,
|
|
557
|
+
guardInterception: {
|
|
558
|
+
ruleId: "SENSITIVE_FILE_ACCESS",
|
|
559
|
+
targetOrPattern: "claude PreToolUse Hook",
|
|
560
|
+
reason: stderr.trim() || "Blocked by Fail-Closed Hook (Exit Code 2).",
|
|
561
|
+
},
|
|
562
|
+
thinkingTrace: `[Claude Live Hook Exit 2] ${stderr.trim()}`,
|
|
563
|
+
replyContent: stderr.trim() || "Blocked by CYF Fail-Closed Guard (Exit Code 2).",
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
const parsed = parseClaudeJsonOutput(stdout);
|
|
567
|
+
if (parsed.reply) {
|
|
568
|
+
return {
|
|
569
|
+
blockedByGuard: false,
|
|
570
|
+
thinkingTrace: parsed.thinking ||
|
|
571
|
+
`[Claude Code Live CLI (exit=${String(code)}, fork=${String(usesNativeFork)})]`,
|
|
572
|
+
replyContent: parsed.reply,
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
const diag = timedOut
|
|
576
|
+
? "Claude Code CLI timed out waiting for upstream model response."
|
|
577
|
+
: stderr.trim() || stdout.trim() || `Claude CLI exited with code ${String(code)}`;
|
|
578
|
+
return {
|
|
579
|
+
blockedByGuard: false,
|
|
580
|
+
thinkingTrace: `[Claude Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
581
|
+
replyContent: diag,
|
|
582
|
+
};
|
|
583
|
+
}
|
|
168
584
|
}
|
|
169
585
|
/**
|
|
170
|
-
* 2. OpenAI Codex Adapter (`codex app-server` JSON-RPC 2.0)
|
|
171
|
-
* - Mode A/B/D: `
|
|
172
|
-
* - Mode C: `
|
|
173
|
-
* - Revocation: `turn/interrupt`
|
|
586
|
+
* 2. OpenAI Codex Adapter (`codex app-server` JSON-RPC 2.0 & `codex exec` read-only sandbox)
|
|
587
|
+
* - Mode A/B/D: `ephemeral: true` + `sandbox: "read-only"`
|
|
588
|
+
* - Mode C: `fork` (explicitly avoiding single-writer lock on `thread/resume`)
|
|
174
589
|
*/
|
|
175
590
|
export class CodexAdapter extends BaseEngineAdapter {
|
|
176
591
|
engine = "codex";
|
|
@@ -258,12 +673,91 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
258
673
|
},
|
|
259
674
|
};
|
|
260
675
|
}
|
|
676
|
+
async executeLiveCliTurn(request, target) {
|
|
677
|
+
const { context } = request;
|
|
678
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
679
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
680
|
+
shareId: context.shareId,
|
|
681
|
+
workspacePath: context.workspacePath,
|
|
682
|
+
permissionTier: context.permissionTier,
|
|
683
|
+
writableGlobs: context.writableGlobs,
|
|
684
|
+
}, true);
|
|
685
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
686
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
687
|
+
const lastMsgFile = path.join(artifactsDir, `codex-last-${Date.now()}-${Math.random().toString(36).slice(2, 7)}.txt`);
|
|
688
|
+
const safeCwd = resolveSafeWorkingDir(context.workspacePath);
|
|
689
|
+
// Strip private MCP servers via `-c mcp_servers={}` and enforce OS read-only sandbox + ephemeral non-persistence
|
|
690
|
+
const cliArgs = usesNativeFork
|
|
691
|
+
? [
|
|
692
|
+
"-c",
|
|
693
|
+
"mcp_servers={}",
|
|
694
|
+
"-c",
|
|
695
|
+
"stream_max_retries=1",
|
|
696
|
+
"-c",
|
|
697
|
+
'sandbox_mode="read-only"',
|
|
698
|
+
"exec",
|
|
699
|
+
"fork",
|
|
700
|
+
context.rawSessionId,
|
|
701
|
+
"--json",
|
|
702
|
+
"--ephemeral",
|
|
703
|
+
"--skip-git-repo-check",
|
|
704
|
+
"-o",
|
|
705
|
+
lastMsgFile,
|
|
706
|
+
"-",
|
|
707
|
+
]
|
|
708
|
+
: [
|
|
709
|
+
"-c",
|
|
710
|
+
"mcp_servers={}",
|
|
711
|
+
"-c",
|
|
712
|
+
"stream_max_retries=1",
|
|
713
|
+
"exec",
|
|
714
|
+
"--json",
|
|
715
|
+
"--ephemeral",
|
|
716
|
+
"--sandbox",
|
|
717
|
+
"read-only",
|
|
718
|
+
"--skip-git-repo-check",
|
|
719
|
+
"-C",
|
|
720
|
+
safeCwd,
|
|
721
|
+
"-o",
|
|
722
|
+
lastMsgFile,
|
|
723
|
+
"-",
|
|
724
|
+
];
|
|
725
|
+
const stdinPayload = [
|
|
726
|
+
systemPromptPayload,
|
|
727
|
+
"",
|
|
728
|
+
usesNativeFork
|
|
729
|
+
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
730
|
+
: buildConversationTurnPayload(request),
|
|
731
|
+
].join("\n");
|
|
732
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
733
|
+
shareId: context.shareId,
|
|
734
|
+
target,
|
|
735
|
+
args: cliArgs,
|
|
736
|
+
cwd: safeCwd,
|
|
737
|
+
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
738
|
+
stdinPayload,
|
|
739
|
+
});
|
|
740
|
+
const parsed = parseCodexExecOutput(stdout, lastMsgFile);
|
|
741
|
+
if (parsed.reply) {
|
|
742
|
+
return {
|
|
743
|
+
blockedByGuard: false,
|
|
744
|
+
thinkingTrace: parsed.thinking ||
|
|
745
|
+
`[Codex Live CLI (exit=${String(code)}, sandbox=read-only, ephemeral=true)]`,
|
|
746
|
+
replyContent: parsed.reply,
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
const diag = timedOut
|
|
750
|
+
? "Codex CLI timed out waiting for model response."
|
|
751
|
+
: parsed.errorSummary || stderr.trim() || stdout.trim() || `Codex CLI exited with code ${String(code)}`;
|
|
752
|
+
return {
|
|
753
|
+
blockedByGuard: false,
|
|
754
|
+
thinkingTrace: `[Codex Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
755
|
+
replyContent: diag,
|
|
756
|
+
};
|
|
757
|
+
}
|
|
261
758
|
}
|
|
262
759
|
/**
|
|
263
|
-
* 3. SST OpenCode Adapter (`opencode serve` REST/SSE + `opencode
|
|
264
|
-
* - Mode A/B/D: `POST /session` clean isolated session
|
|
265
|
-
* - Mode C: `POST /session/:id/fork`
|
|
266
|
-
* - ACP: `opencode acp` stdio with `session/request_permission` interception
|
|
760
|
+
* 3. SST OpenCode Adapter (`opencode serve` REST/SSE + `opencode run --format json --archived`)
|
|
267
761
|
*/
|
|
268
762
|
export class OpenCodeAdapter extends BaseEngineAdapter {
|
|
269
763
|
engine = "opencode";
|
|
@@ -353,10 +847,79 @@ export class OpenCodeAdapter extends BaseEngineAdapter {
|
|
|
353
847
|
generatedFiles: bundle.files,
|
|
354
848
|
};
|
|
355
849
|
}
|
|
850
|
+
async executeLiveCliTurn(request, target) {
|
|
851
|
+
const { context } = request;
|
|
852
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
853
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
854
|
+
shareId: context.shareId,
|
|
855
|
+
workspacePath: context.workspacePath,
|
|
856
|
+
permissionTier: context.permissionTier,
|
|
857
|
+
writableGlobs: context.writableGlobs,
|
|
858
|
+
}, true);
|
|
859
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
860
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
861
|
+
const turnBody = usesNativeFork
|
|
862
|
+
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
863
|
+
: buildConversationTurnPayload(request);
|
|
864
|
+
const fullPrompt = [systemPromptPayload, "", turnBody].join("\n");
|
|
865
|
+
const cliArgs = [
|
|
866
|
+
"run",
|
|
867
|
+
"--format",
|
|
868
|
+
"json",
|
|
869
|
+
"--archived",
|
|
870
|
+
"--thinking",
|
|
871
|
+
"--standalone",
|
|
872
|
+
];
|
|
873
|
+
if (usesNativeFork) {
|
|
874
|
+
cliArgs.push("--session", context.rawSessionId, "--fork");
|
|
875
|
+
}
|
|
876
|
+
if (fullPrompt.length > 4000) {
|
|
877
|
+
const contextFile = path.join(artifactsDir, "cyf-opencode-context.md");
|
|
878
|
+
fs.writeFileSync(contextFile, [systemPromptPayload, "", ...(usesNativeFork ? [] : [buildConversationTurnPayload({ ...request, prompt: "" })])].join("\n"), "utf8");
|
|
879
|
+
cliArgs.push("--file", contextFile, `[Colleague (${request.guestName})]:\n${request.prompt}`);
|
|
880
|
+
}
|
|
881
|
+
else {
|
|
882
|
+
cliArgs.push(fullPrompt);
|
|
883
|
+
}
|
|
884
|
+
const strictReadOnlyConfig = JSON.stringify({
|
|
885
|
+
mcp: {},
|
|
886
|
+
permission: {
|
|
887
|
+
bash: "deny",
|
|
888
|
+
edit: context.permissionTier === "TIER_2_WORKTREE_SANDBOX" ? "allow" : "deny",
|
|
889
|
+
webfetch: "deny",
|
|
890
|
+
},
|
|
891
|
+
});
|
|
892
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
893
|
+
shareId: context.shareId,
|
|
894
|
+
target,
|
|
895
|
+
args: cliArgs,
|
|
896
|
+
cwd: resolveSafeWorkingDir(context.workspacePath),
|
|
897
|
+
env: {
|
|
898
|
+
...this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
899
|
+
OPENCODE_CONFIG_CONTENT: strictReadOnlyConfig,
|
|
900
|
+
},
|
|
901
|
+
});
|
|
902
|
+
const parsed = parseOpenCodeJsonOutput(stdout);
|
|
903
|
+
if (parsed.reply) {
|
|
904
|
+
return {
|
|
905
|
+
blockedByGuard: false,
|
|
906
|
+
thinkingTrace: parsed.thinking ||
|
|
907
|
+
`[OpenCode Live CLI (exit=${String(code)}, archived=true)]`,
|
|
908
|
+
replyContent: parsed.reply,
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
const diag = timedOut
|
|
912
|
+
? "OpenCode CLI timed out waiting for model response."
|
|
913
|
+
: stderr.trim() || stdout.trim() || `OpenCode CLI exited with code ${String(code)}`;
|
|
914
|
+
return {
|
|
915
|
+
blockedByGuard: false,
|
|
916
|
+
thinkingTrace: `[OpenCode Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
917
|
+
replyContent: diag,
|
|
918
|
+
};
|
|
919
|
+
}
|
|
356
920
|
}
|
|
357
921
|
/**
|
|
358
922
|
* 4. DeepSeek Harness Adapter (`dsh --profile acp|sdk --patch cyf-dsh-guard-patch.yaml`)
|
|
359
|
-
* Dynamically overlays a Cordis guard YAML patch stripping high-risk tools & private MCPs.
|
|
360
923
|
*/
|
|
361
924
|
export class DshAdapter extends BaseEngineAdapter {
|
|
362
925
|
engine = "dsh";
|
|
@@ -412,11 +975,57 @@ export class DshAdapter extends BaseEngineAdapter {
|
|
|
412
975
|
generatedFiles: bundle.files,
|
|
413
976
|
};
|
|
414
977
|
}
|
|
978
|
+
async executeLiveCliTurn(request, target) {
|
|
979
|
+
const { context } = request;
|
|
980
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
981
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
982
|
+
shareId: context.shareId,
|
|
983
|
+
workspacePath: context.workspacePath,
|
|
984
|
+
permissionTier: context.permissionTier,
|
|
985
|
+
writableGlobs: context.writableGlobs,
|
|
986
|
+
}, true);
|
|
987
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
988
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
989
|
+
const cliArgs = [
|
|
990
|
+
"--profile",
|
|
991
|
+
"sdk",
|
|
992
|
+
"--patch",
|
|
993
|
+
bundle.dshPatchYamlPath,
|
|
994
|
+
...(usesNativeFork ? ["--fork", context.rawSessionId] : []),
|
|
995
|
+
];
|
|
996
|
+
const stdinPayload = [
|
|
997
|
+
systemPromptPayload,
|
|
998
|
+
"",
|
|
999
|
+
buildConversationTurnPayload(request),
|
|
1000
|
+
].join("\n");
|
|
1001
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
1002
|
+
shareId: context.shareId,
|
|
1003
|
+
target,
|
|
1004
|
+
args: cliArgs,
|
|
1005
|
+
cwd: resolveSafeWorkingDir(context.workspacePath),
|
|
1006
|
+
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
1007
|
+
stdinPayload,
|
|
1008
|
+
});
|
|
1009
|
+
const parsed = parseClaudeJsonOutput(stdout);
|
|
1010
|
+
if (parsed.reply) {
|
|
1011
|
+
return {
|
|
1012
|
+
blockedByGuard: false,
|
|
1013
|
+
thinkingTrace: parsed.thinking || `[Dsh Live CLI (exit=${String(code)})]`,
|
|
1014
|
+
replyContent: parsed.reply,
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
const diag = timedOut
|
|
1018
|
+
? "Dsh CLI timed out waiting for model response."
|
|
1019
|
+
: stderr.trim() || stdout.trim() || `Dsh CLI exited with code ${String(code)}`;
|
|
1020
|
+
return {
|
|
1021
|
+
blockedByGuard: false,
|
|
1022
|
+
thinkingTrace: `[Dsh Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
1023
|
+
replyContent: diag,
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
415
1026
|
}
|
|
416
1027
|
/**
|
|
417
1028
|
* 5. Tencent Cloud CodeBuddy Adapter
|
|
418
|
-
* Builds `codebuddy --serve --strict-mcp-config --no-session-persistence`
|
|
419
|
-
* pure in-memory zero-footprint guest runtime specification.
|
|
420
1029
|
*/
|
|
421
1030
|
export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
422
1031
|
engine = "codebuddy";
|
|
@@ -457,6 +1066,77 @@ export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
|
457
1066
|
generatedFiles: bundle.files,
|
|
458
1067
|
};
|
|
459
1068
|
}
|
|
1069
|
+
async executeLiveCliTurn(request, target) {
|
|
1070
|
+
const { context } = request;
|
|
1071
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1072
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
1073
|
+
shareId: context.shareId,
|
|
1074
|
+
workspacePath: context.workspacePath,
|
|
1075
|
+
permissionTier: context.permissionTier,
|
|
1076
|
+
writableGlobs: context.writableGlobs,
|
|
1077
|
+
}, true);
|
|
1078
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
1079
|
+
const systemEnvelopeFile = path.join(artifactsDir, "cyf-cb-system-envelope.txt");
|
|
1080
|
+
fs.writeFileSync(systemEnvelopeFile, systemPromptPayload, "utf8");
|
|
1081
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
1082
|
+
const cliArgs = [
|
|
1083
|
+
"-p",
|
|
1084
|
+
"--output-format",
|
|
1085
|
+
"json",
|
|
1086
|
+
"--strict-mcp-config",
|
|
1087
|
+
"--mcp-config",
|
|
1088
|
+
bundle.emptyMcpConfigPath,
|
|
1089
|
+
"--no-session-persistence",
|
|
1090
|
+
"--settings",
|
|
1091
|
+
bundle.claudeSettingsPath,
|
|
1092
|
+
"--tools=Read,Glob,Grep",
|
|
1093
|
+
"--permission-mode",
|
|
1094
|
+
"dontAsk",
|
|
1095
|
+
"--system-prompt-file",
|
|
1096
|
+
systemEnvelopeFile,
|
|
1097
|
+
...(usesNativeFork ? ["--resume", context.rawSessionId, "--fork-session"] : []),
|
|
1098
|
+
];
|
|
1099
|
+
const turnInput = usesNativeFork
|
|
1100
|
+
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
1101
|
+
: buildConversationTurnPayload(request);
|
|
1102
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
1103
|
+
shareId: context.shareId,
|
|
1104
|
+
target,
|
|
1105
|
+
args: cliArgs,
|
|
1106
|
+
cwd: resolveSafeWorkingDir(context.workspacePath),
|
|
1107
|
+
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
1108
|
+
stdinPayload: turnInput,
|
|
1109
|
+
});
|
|
1110
|
+
if (code === 2) {
|
|
1111
|
+
return {
|
|
1112
|
+
blockedByGuard: true,
|
|
1113
|
+
guardInterception: {
|
|
1114
|
+
ruleId: "SENSITIVE_FILE_ACCESS",
|
|
1115
|
+
targetOrPattern: "codebuddy PreToolUse Hook",
|
|
1116
|
+
reason: stderr.trim() || "Blocked by Fail-Closed Hook (Exit Code 2).",
|
|
1117
|
+
},
|
|
1118
|
+
thinkingTrace: `[CodeBuddy Live Hook Exit 2] ${stderr.trim()}`,
|
|
1119
|
+
replyContent: stderr.trim() || "Blocked by CYF Fail-Closed Guard (Exit Code 2).",
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
const parsed = parseClaudeJsonOutput(stdout);
|
|
1123
|
+
if (parsed.reply) {
|
|
1124
|
+
return {
|
|
1125
|
+
blockedByGuard: false,
|
|
1126
|
+
thinkingTrace: parsed.thinking ||
|
|
1127
|
+
`[CodeBuddy Live CLI (exit=${String(code)}, fork=${String(usesNativeFork)})]`,
|
|
1128
|
+
replyContent: parsed.reply,
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
const diag = timedOut
|
|
1132
|
+
? "CodeBuddy CLI timed out waiting for model response."
|
|
1133
|
+
: stderr.trim() || stdout.trim() || `CodeBuddy CLI exited with code ${String(code)}`;
|
|
1134
|
+
return {
|
|
1135
|
+
blockedByGuard: false,
|
|
1136
|
+
thinkingTrace: `[CodeBuddy Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
1137
|
+
replyContent: diag,
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
460
1140
|
}
|
|
461
1141
|
/**
|
|
462
1142
|
* Registry holding all 5 first-wave runtime adapters.
|