@cyfsh/adapters 0.2.0 → 0.3.1
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 +56 -16
- package/dist/adapters.d.ts.map +1 -1
- package/dist/adapters.js +1296 -85
- package/dist/adapters.js.map +1 -1
- package/dist/guard-generator.d.ts.map +1 -1
- package/dist/guard-generator.js +2 -1
- package/dist/guard-generator.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 +12 -5
- package/dist/sandbox-responder.js.map +1 -1
- package/dist/types.d.ts +26 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/adapters.js
CHANGED
|
@@ -1,9 +1,602 @@
|
|
|
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, artifactsDir) {
|
|
93
|
+
try {
|
|
94
|
+
if (workspacePath &&
|
|
95
|
+
fs.existsSync(workspacePath) &&
|
|
96
|
+
fs.statSync(workspacePath).isDirectory()) {
|
|
97
|
+
return { cwd: fs.realpathSync(workspacePath), workspaceExists: true };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// Fall through to isolated empty directory
|
|
102
|
+
}
|
|
103
|
+
const isolatedDir = path.join(artifactsDir, "isolated-cwd");
|
|
104
|
+
fs.mkdirSync(isolatedDir, { recursive: true });
|
|
105
|
+
return {
|
|
106
|
+
cwd: fs.existsSync(isolatedDir) ? fs.realpathSync(isolatedDir) : isolatedDir,
|
|
107
|
+
workspaceExists: false,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function buildConversationTurnPayload(request) {
|
|
111
|
+
const lines = [];
|
|
112
|
+
if (request.priorGuestTurns.length > 0) {
|
|
113
|
+
lines.push("<prior_guest_discussion>");
|
|
114
|
+
for (const turn of request.priorGuestTurns.slice(-16)) {
|
|
115
|
+
if (turn.blockedByGuard)
|
|
116
|
+
continue;
|
|
117
|
+
const speaker = turn.role === "guest"
|
|
118
|
+
? `Colleague (${turn.guestName ?? request.guestName})`
|
|
119
|
+
: "AI Assistant";
|
|
120
|
+
lines.push(`[${speaker}]:\n${turn.content}`);
|
|
121
|
+
}
|
|
122
|
+
lines.push("</prior_guest_discussion>", "");
|
|
123
|
+
}
|
|
124
|
+
lines.push(`[Colleague (${request.guestName})]:`, request.prompt);
|
|
125
|
+
return lines.join("\n");
|
|
126
|
+
}
|
|
127
|
+
function extractToolResultSnippet(rawContent) {
|
|
128
|
+
if (typeof rawContent === "string") {
|
|
129
|
+
return rawContent.trim();
|
|
130
|
+
}
|
|
131
|
+
if (Array.isArray(rawContent)) {
|
|
132
|
+
const parts = [];
|
|
133
|
+
for (const item of rawContent) {
|
|
134
|
+
if (typeof item === "object" && item !== null) {
|
|
135
|
+
const rec = item;
|
|
136
|
+
if (typeof rec["text"] === "string") {
|
|
137
|
+
parts.push(rec["text"]);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return parts.join("\n").trim();
|
|
142
|
+
}
|
|
143
|
+
return "";
|
|
144
|
+
}
|
|
145
|
+
function parseStructuredJsonRecords(records) {
|
|
146
|
+
const replyParts = [];
|
|
147
|
+
const thinkingParts = [];
|
|
148
|
+
const observations = [];
|
|
149
|
+
let finalResult = null;
|
|
150
|
+
let hitMaxTurns = false;
|
|
151
|
+
let resultError = "";
|
|
152
|
+
for (const obj of records) {
|
|
153
|
+
const recType = typeof obj["type"] === "string" ? obj["type"] : "";
|
|
154
|
+
if (recType === "result") {
|
|
155
|
+
const subtype = typeof obj["subtype"] === "string" ? obj["subtype"] : "";
|
|
156
|
+
const isError = obj["is_error"] === true || subtype.startsWith("error_");
|
|
157
|
+
if (subtype === "error_max_turns") {
|
|
158
|
+
hitMaxTurns = true;
|
|
159
|
+
}
|
|
160
|
+
const resStr = typeof obj["result"] === "string" ? obj["result"].trim() : "";
|
|
161
|
+
if (isError) {
|
|
162
|
+
resultError = resStr || subtype;
|
|
163
|
+
}
|
|
164
|
+
else if (resStr.length > 0) {
|
|
165
|
+
finalResult = resStr;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
else if (recType === "reasoning") {
|
|
169
|
+
for (const key of ["rawContent", "summary", "content"]) {
|
|
170
|
+
const arr = obj[key];
|
|
171
|
+
if (Array.isArray(arr)) {
|
|
172
|
+
for (const item of arr) {
|
|
173
|
+
if (typeof item === "object" && item !== null) {
|
|
174
|
+
const b = item;
|
|
175
|
+
const t = typeof b["text"] === "string"
|
|
176
|
+
? b["text"]
|
|
177
|
+
: typeof b["thinking"] === "string"
|
|
178
|
+
? b["thinking"]
|
|
179
|
+
: "";
|
|
180
|
+
if (t)
|
|
181
|
+
thinkingParts.push(t);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
else if ((recType === "assistant" && typeof obj["message"] === "object" && obj["message"] !== null) ||
|
|
188
|
+
(recType === "message" && obj["role"] === "assistant")) {
|
|
189
|
+
const msg = recType === "assistant"
|
|
190
|
+
? obj["message"]
|
|
191
|
+
: obj;
|
|
192
|
+
if (Array.isArray(msg["content"])) {
|
|
193
|
+
for (const block of msg["content"]) {
|
|
194
|
+
if (typeof block === "object" && block !== null) {
|
|
195
|
+
const b = block;
|
|
196
|
+
const bType = typeof b["type"] === "string" ? b["type"] : "";
|
|
197
|
+
if ((bType === "text" || bType === "output_text") &&
|
|
198
|
+
typeof b["text"] === "string") {
|
|
199
|
+
const textVal = b["text"].trim();
|
|
200
|
+
if (textVal)
|
|
201
|
+
replyParts.push(textVal);
|
|
202
|
+
}
|
|
203
|
+
else if ((bType === "thinking" || bType === "reasoning" || bType === "reasoning_text") &&
|
|
204
|
+
(typeof b["thinking"] === "string" || typeof b["text"] === "string")) {
|
|
205
|
+
thinkingParts.push(typeof b["thinking"] === "string" ? b["thinking"] : b["text"]);
|
|
206
|
+
}
|
|
207
|
+
else if (bType === "tool_use" && typeof b["name"] === "string") {
|
|
208
|
+
if (observations.length < 16) {
|
|
209
|
+
const inputPreview = JSON.stringify(b["input"] ?? {}).slice(0, 240);
|
|
210
|
+
observations.push(`[Tool Call: ${b["name"]}] ${inputPreview}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
else if (typeof msg["content"] === "string" && msg["content"].trim()) {
|
|
217
|
+
replyParts.push(msg["content"].trim());
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
else if (recType === "user" &&
|
|
221
|
+
typeof obj["message"] === "object" &&
|
|
222
|
+
obj["message"] !== null) {
|
|
223
|
+
const msg = obj["message"];
|
|
224
|
+
if (Array.isArray(msg["content"]) && observations.length < 16) {
|
|
225
|
+
for (const block of msg["content"]) {
|
|
226
|
+
if (typeof block === "object" && block !== null) {
|
|
227
|
+
const b = block;
|
|
228
|
+
if (b["type"] === "tool_result") {
|
|
229
|
+
const snippet = extractToolResultSnippet(b["content"]);
|
|
230
|
+
if (snippet && !snippet.includes("[CYFGuard]")) {
|
|
231
|
+
observations.push(`[Tool Result]: ${snippet.length > 1200 ? `${snippet.slice(0, 1200)}...` : snippet}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
else if (!recType && typeof obj["result"] === "string" && obj["result"].trim()) {
|
|
239
|
+
finalResult = obj["result"].trim();
|
|
240
|
+
}
|
|
241
|
+
else if (!recType && typeof obj["content"] === "string" && obj["content"].trim()) {
|
|
242
|
+
replyParts.push(obj["content"].trim());
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const joinedReply = replyParts.join("\n\n").trim();
|
|
246
|
+
return {
|
|
247
|
+
reply: (finalResult && finalResult.length > 0 ? finalResult : joinedReply).trim(),
|
|
248
|
+
thinking: thinkingParts.join("\n").trim(),
|
|
249
|
+
observations,
|
|
250
|
+
hitMaxTurns,
|
|
251
|
+
resultError,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
function sanitizeRelativeToolSummary(rawValue, workspaceRoot) {
|
|
255
|
+
const normVal = rawValue.replace(/\\/g, "/").trim();
|
|
256
|
+
const normWs = workspaceRoot.replace(/\\/g, "/").replace(/\/+$/, "").trim();
|
|
257
|
+
if (!normVal)
|
|
258
|
+
return "";
|
|
259
|
+
if (normWs) {
|
|
260
|
+
const lowerVal = normVal.toLowerCase();
|
|
261
|
+
const lowerWs = normWs.toLowerCase();
|
|
262
|
+
if (lowerVal === lowerWs)
|
|
263
|
+
return ".";
|
|
264
|
+
if (lowerVal.startsWith(`${lowerWs}/`)) {
|
|
265
|
+
return normVal.slice(normWs.length + 1);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
// Never expose absolute host home/system paths in live UI summaries
|
|
269
|
+
if (/^(?:[a-zA-Z]:\/|\/Users\/|\/home\/)/.test(normVal)) {
|
|
270
|
+
const parts = normVal.split("/").filter(Boolean);
|
|
271
|
+
return parts.slice(-2).join("/");
|
|
272
|
+
}
|
|
273
|
+
return normVal;
|
|
274
|
+
}
|
|
275
|
+
function summarizeStreamToolInput(input, workspaceRoot) {
|
|
276
|
+
if (typeof input !== "object" || input === null)
|
|
277
|
+
return "";
|
|
278
|
+
const rec = input;
|
|
279
|
+
const parts = [];
|
|
280
|
+
for (const key of ["pattern", "query", "glob"]) {
|
|
281
|
+
if (typeof rec[key] === "string" && rec[key].trim()) {
|
|
282
|
+
parts.push(rec[key].trim().slice(0, 60));
|
|
283
|
+
break;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
for (const key of ["file_path", "path", "target_file"]) {
|
|
287
|
+
if (typeof rec[key] === "string" && rec[key].trim()) {
|
|
288
|
+
const rel = sanitizeRelativeToolSummary(rec[key], workspaceRoot);
|
|
289
|
+
if (rel && rel !== ".")
|
|
290
|
+
parts.push(rel.slice(0, 80));
|
|
291
|
+
break;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
if (parts.length === 0 && typeof rec["command"] === "string" && rec["command"].trim()) {
|
|
295
|
+
parts.push(rec["command"].trim().slice(0, 60));
|
|
296
|
+
}
|
|
297
|
+
return parts.join(" in ");
|
|
298
|
+
}
|
|
299
|
+
function createClaudeStreamLineInspector(workspaceRoot, onStreamEvent) {
|
|
300
|
+
const executedTools = [];
|
|
301
|
+
const onLine = (line) => {
|
|
302
|
+
if (!line.startsWith("{"))
|
|
303
|
+
return false;
|
|
304
|
+
try {
|
|
305
|
+
const obj = JSON.parse(line);
|
|
306
|
+
const recType = typeof obj["type"] === "string" ? obj["type"] : "";
|
|
307
|
+
if (recType === "system" && obj["subtype"] === "init") {
|
|
308
|
+
const tools = Array.isArray(obj["tools"])
|
|
309
|
+
? obj["tools"].filter((t) => typeof t === "string")
|
|
310
|
+
: undefined;
|
|
311
|
+
onStreamEvent?.({ type: "init", tools });
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
if (recType === "assistant" &&
|
|
315
|
+
typeof obj["message"] === "object" &&
|
|
316
|
+
obj["message"] !== null) {
|
|
317
|
+
const msg = obj["message"];
|
|
318
|
+
if (Array.isArray(msg["content"])) {
|
|
319
|
+
for (const block of msg["content"]) {
|
|
320
|
+
if (typeof block !== "object" || block === null)
|
|
321
|
+
continue;
|
|
322
|
+
const b = block;
|
|
323
|
+
const bType = typeof b["type"] === "string" ? b["type"] : "";
|
|
324
|
+
if ((bType === "thinking" || bType === "reasoning") &&
|
|
325
|
+
(typeof b["thinking"] === "string" || typeof b["text"] === "string")) {
|
|
326
|
+
const txt = (typeof b["thinking"] === "string" ? b["thinking"] : b["text"]).trim();
|
|
327
|
+
if (txt) {
|
|
328
|
+
onStreamEvent?.({ type: "thinking", summary: txt });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
else if (bType === "tool_use" && typeof b["name"] === "string") {
|
|
332
|
+
const toolName = b["name"];
|
|
333
|
+
const inputSummary = summarizeStreamToolInput(b["input"], workspaceRoot);
|
|
334
|
+
const badge = inputSummary ? `${toolName} (${inputSummary})` : toolName;
|
|
335
|
+
executedTools.push(badge);
|
|
336
|
+
onStreamEvent?.({ type: "tool_call", toolName, inputSummary });
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
if (recType === "user" &&
|
|
343
|
+
typeof obj["message"] === "object" &&
|
|
344
|
+
obj["message"] !== null) {
|
|
345
|
+
const msg = obj["message"];
|
|
346
|
+
if (Array.isArray(msg["content"])) {
|
|
347
|
+
for (const block of msg["content"]) {
|
|
348
|
+
if (typeof block !== "object" || block === null)
|
|
349
|
+
continue;
|
|
350
|
+
const b = block;
|
|
351
|
+
if (b["type"] === "tool_result") {
|
|
352
|
+
const snippet = extractToolResultSnippet(b["content"]);
|
|
353
|
+
const blocked = snippet.includes("[CYFGuard]");
|
|
354
|
+
onStreamEvent?.({
|
|
355
|
+
type: "tool_result",
|
|
356
|
+
isError: blocked || b["is_error"] === true,
|
|
357
|
+
preview: snippet.slice(0, 240),
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return false;
|
|
363
|
+
}
|
|
364
|
+
// Terminal frame: `claude` / `codebuddy` `-p --output-format stream-json` has finished!
|
|
365
|
+
// Immediately trigger completion grace reaping so dangling OTel/HTTP sockets never hang until timeout!
|
|
366
|
+
if (recType === "result") {
|
|
367
|
+
return true;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
catch {
|
|
371
|
+
// Ignore malformed line
|
|
372
|
+
}
|
|
373
|
+
return false;
|
|
374
|
+
};
|
|
375
|
+
return { executedTools, onLine };
|
|
376
|
+
}
|
|
377
|
+
function createCodexStreamLineInspector(workspaceRoot, onStreamEvent) {
|
|
378
|
+
const executedTools = [];
|
|
379
|
+
const onLine = (line) => {
|
|
380
|
+
if (!line.startsWith("{"))
|
|
381
|
+
return false;
|
|
382
|
+
try {
|
|
383
|
+
const ev = JSON.parse(line);
|
|
384
|
+
const evType = typeof ev["type"] === "string" ? ev["type"] : "";
|
|
385
|
+
const item = typeof ev["item"] === "object" && ev["item"] !== null
|
|
386
|
+
? ev["item"]
|
|
387
|
+
: undefined;
|
|
388
|
+
if (evType === "item.completed" && item) {
|
|
389
|
+
if (item["type"] === "reasoning" && typeof item["text"] === "string" && item["text"].trim()) {
|
|
390
|
+
onStreamEvent?.({ type: "thinking", summary: item["text"].trim() });
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
else if (evType === "item.started" && item) {
|
|
394
|
+
const iType = typeof item["type"] === "string" ? item["type"] : "";
|
|
395
|
+
if (iType === "command_execution" || iType.includes("tool") || iType.includes("search")) {
|
|
396
|
+
const cmd = typeof item["command"] === "string"
|
|
397
|
+
? sanitizeRelativeToolSummary(item["command"], workspaceRoot).slice(0, 60)
|
|
398
|
+
: "";
|
|
399
|
+
const toolName = iType === "command_execution" ? "ReadShell" : iType;
|
|
400
|
+
executedTools.push(cmd ? `${toolName} (${cmd})` : toolName);
|
|
401
|
+
onStreamEvent?.({ type: "tool_call", toolName, inputSummary: cmd });
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
else if (evType === "turn.completed" || evType === "turn.failed") {
|
|
405
|
+
return true;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
catch {
|
|
409
|
+
// Ignore
|
|
410
|
+
}
|
|
411
|
+
return false;
|
|
412
|
+
};
|
|
413
|
+
return { executedTools, onLine };
|
|
414
|
+
}
|
|
415
|
+
function createOpenCodeStreamLineInspector(workspaceRoot, onStreamEvent) {
|
|
416
|
+
const executedTools = [];
|
|
417
|
+
const onLine = (line) => {
|
|
418
|
+
if (!line.startsWith("{"))
|
|
419
|
+
return false;
|
|
420
|
+
try {
|
|
421
|
+
const ev = JSON.parse(line);
|
|
422
|
+
const evType = typeof ev["type"] === "string" ? ev["type"] : "";
|
|
423
|
+
const part = typeof ev["part"] === "object" && ev["part"] !== null
|
|
424
|
+
? ev["part"]
|
|
425
|
+
: undefined;
|
|
426
|
+
if ((evType === "reasoning" || evType === "thinking") &&
|
|
427
|
+
part &&
|
|
428
|
+
typeof part["text"] === "string" &&
|
|
429
|
+
part["text"].trim()) {
|
|
430
|
+
onStreamEvent?.({ type: "thinking", summary: part["text"].trim() });
|
|
431
|
+
}
|
|
432
|
+
else if ((evType === "tool_use" || evType === "tool") && part) {
|
|
433
|
+
const toolName = typeof part["tool"] === "string"
|
|
434
|
+
? part["tool"]
|
|
435
|
+
: typeof part["name"] === "string"
|
|
436
|
+
? part["name"]
|
|
437
|
+
: "tool";
|
|
438
|
+
const state = typeof part["state"] === "object" && part["state"] !== null
|
|
439
|
+
? part["state"]
|
|
440
|
+
: undefined;
|
|
441
|
+
const inputSummary = summarizeStreamToolInput(state?.["input"] ?? part["input"], workspaceRoot);
|
|
442
|
+
executedTools.push(inputSummary ? `${toolName} (${inputSummary})` : toolName);
|
|
443
|
+
onStreamEvent?.({ type: "tool_call", toolName, inputSummary });
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
// Ignore
|
|
448
|
+
}
|
|
449
|
+
return false;
|
|
450
|
+
};
|
|
451
|
+
return { executedTools, onLine };
|
|
452
|
+
}
|
|
453
|
+
export { resolveSafeWorkingDir };
|
|
454
|
+
export function parseClaudeJsonOutput(rawStdout) {
|
|
455
|
+
const trimmed = rawStdout.trim();
|
|
456
|
+
if (!trimmed) {
|
|
457
|
+
return {
|
|
458
|
+
reply: "",
|
|
459
|
+
thinking: "",
|
|
460
|
+
observations: [],
|
|
461
|
+
hitMaxTurns: false,
|
|
462
|
+
resultError: "",
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
// Handle single JSON object (`claude -p --output-format json`) OR JSON array (`codebuddy -p --output-format json`)
|
|
466
|
+
if ((trimmed.startsWith("{") && !trimmed.includes("\n{")) ||
|
|
467
|
+
trimmed.startsWith("[")) {
|
|
468
|
+
try {
|
|
469
|
+
const parsed = JSON.parse(trimmed);
|
|
470
|
+
if (Array.isArray(parsed)) {
|
|
471
|
+
const objs = parsed.filter((item) => typeof item === "object" && item !== null);
|
|
472
|
+
return parseStructuredJsonRecords(objs);
|
|
473
|
+
}
|
|
474
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
475
|
+
return parseStructuredJsonRecords([parsed]);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
catch {
|
|
479
|
+
// Fall through to NDJSON line-by-line parsing
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const ndjsonRecords = [];
|
|
483
|
+
for (const rawLine of trimmed.split(/\r?\n/)) {
|
|
484
|
+
const line = rawLine.trim();
|
|
485
|
+
if (!line.startsWith("{"))
|
|
486
|
+
continue;
|
|
487
|
+
try {
|
|
488
|
+
const obj = JSON.parse(line);
|
|
489
|
+
if (typeof obj === "object" && obj !== null && !Array.isArray(obj)) {
|
|
490
|
+
ndjsonRecords.push(obj);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
// Ignore non-JSON log lines
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
if (ndjsonRecords.length > 0) {
|
|
498
|
+
return parseStructuredJsonRecords(ndjsonRecords);
|
|
499
|
+
}
|
|
500
|
+
return {
|
|
501
|
+
reply: trimmed,
|
|
502
|
+
thinking: "",
|
|
503
|
+
observations: [],
|
|
504
|
+
hitMaxTurns: false,
|
|
505
|
+
resultError: "",
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
function parseCodexExecOutput(rawStdout, lastMsgFilePath) {
|
|
509
|
+
const thinkingParts = [];
|
|
510
|
+
const agentMsgParts = [];
|
|
511
|
+
let lastErrorMsg = "";
|
|
512
|
+
for (const rawLine of rawStdout.split(/\r?\n/)) {
|
|
513
|
+
const line = rawLine.trim();
|
|
514
|
+
if (!line.startsWith("{"))
|
|
515
|
+
continue;
|
|
516
|
+
try {
|
|
517
|
+
const ev = JSON.parse(line);
|
|
518
|
+
const item = typeof ev["item"] === "object" && ev["item"] !== null
|
|
519
|
+
? ev["item"]
|
|
520
|
+
: undefined;
|
|
521
|
+
if (ev["type"] === "item.completed" && item) {
|
|
522
|
+
if (item["type"] === "reasoning" && typeof item["text"] === "string") {
|
|
523
|
+
thinkingParts.push(item["text"]);
|
|
524
|
+
}
|
|
525
|
+
else if (item["type"] === "agent_message" && typeof item["text"] === "string") {
|
|
526
|
+
agentMsgParts.push(item["text"]);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
else if (ev["type"] === "turn.failed" && typeof ev["error"] === "object" && ev["error"] !== null) {
|
|
530
|
+
const errObj = ev["error"];
|
|
531
|
+
if (typeof errObj["message"] === "string") {
|
|
532
|
+
lastErrorMsg = errObj["message"];
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
else if (ev["type"] === "error" && typeof ev["message"] === "string") {
|
|
536
|
+
lastErrorMsg = ev["message"];
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
catch {
|
|
540
|
+
// Ignore non-JSON line
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
let fileReply = "";
|
|
544
|
+
try {
|
|
545
|
+
if (fs.existsSync(lastMsgFilePath)) {
|
|
546
|
+
fileReply = fs.readFileSync(lastMsgFilePath, "utf8").trim();
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
// Ignore
|
|
551
|
+
}
|
|
552
|
+
finally {
|
|
553
|
+
try {
|
|
554
|
+
fs.rmSync(lastMsgFilePath, { force: true });
|
|
555
|
+
}
|
|
556
|
+
catch {
|
|
557
|
+
// Ignore
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
return {
|
|
561
|
+
reply: fileReply || agentMsgParts.join("\n\n").trim(),
|
|
562
|
+
thinking: thinkingParts.join("\n").trim(),
|
|
563
|
+
...(lastErrorMsg ? { errorSummary: lastErrorMsg } : {}),
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
function parseOpenCodeJsonOutput(rawStdout) {
|
|
567
|
+
const textParts = [];
|
|
568
|
+
const thinkingParts = [];
|
|
569
|
+
for (const rawLine of rawStdout.split(/\r?\n/)) {
|
|
570
|
+
const line = rawLine.trim();
|
|
571
|
+
if (!line.startsWith("{"))
|
|
572
|
+
continue;
|
|
573
|
+
try {
|
|
574
|
+
const ev = JSON.parse(line);
|
|
575
|
+
const part = typeof ev["part"] === "object" && ev["part"] !== null
|
|
576
|
+
? ev["part"]
|
|
577
|
+
: undefined;
|
|
578
|
+
const evType = typeof ev["type"] === "string" ? ev["type"] : "";
|
|
579
|
+
if (evType === "text" && part && typeof part["text"] === "string") {
|
|
580
|
+
textParts.push(part["text"]);
|
|
581
|
+
}
|
|
582
|
+
else if ((evType === "reasoning" || evType === "thinking") &&
|
|
583
|
+
part &&
|
|
584
|
+
typeof part["text"] === "string") {
|
|
585
|
+
thinkingParts.push(part["text"]);
|
|
586
|
+
}
|
|
587
|
+
else if (typeof ev["text"] === "string") {
|
|
588
|
+
textParts.push(ev["text"]);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
catch {
|
|
592
|
+
// Ignore non-JSON lines
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return {
|
|
596
|
+
reply: textParts.join("").trim() || rawStdout.trim(),
|
|
597
|
+
thinking: thinkingParts.join("\n").trim(),
|
|
598
|
+
};
|
|
599
|
+
}
|
|
7
600
|
class BaseEngineAdapter {
|
|
8
601
|
options;
|
|
9
602
|
activeProcesses = new Map();
|
|
@@ -26,89 +619,216 @@ class BaseEngineAdapter {
|
|
|
26
619
|
CYF_STRICT_NO_PRIVATE_MCP: "1",
|
|
27
620
|
};
|
|
28
621
|
}
|
|
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
|
-
|
|
54
|
-
|
|
55
|
-
|
|
622
|
+
buildSanitizedChildEnv(extraEnv) {
|
|
623
|
+
const merged = { ...process.env, ...extraEnv };
|
|
624
|
+
// Prevent nested-invocation lockouts when CYF is started from inside Claude Code
|
|
625
|
+
delete merged["CLAUDECODE"];
|
|
626
|
+
delete merged["CLAUDE_CODE_ENTRYPOINT"];
|
|
627
|
+
return merged;
|
|
628
|
+
}
|
|
629
|
+
spawnAndCollect(params) {
|
|
630
|
+
const idleTimeoutMs = params.idleTimeoutMs ?? this.options.turnTimeoutMs ?? 90_000;
|
|
631
|
+
const maxTotalTimeoutMs = params.maxTotalTimeoutMs ?? Math.max(Math.round(idleTimeoutMs * 2.5), 210_000);
|
|
632
|
+
const completionGraceMs = params.completionGraceMs ?? 220;
|
|
633
|
+
return new Promise((resolve, reject) => {
|
|
634
|
+
const child = spawn(params.target.command, [...params.target.prefixArgs, ...params.args], {
|
|
635
|
+
cwd: params.cwd,
|
|
636
|
+
env: this.buildSanitizedChildEnv(params.env),
|
|
637
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
638
|
+
shell: params.target.useShell,
|
|
639
|
+
windowsHide: true,
|
|
640
|
+
});
|
|
641
|
+
let stdout = "";
|
|
642
|
+
let stdoutLineBuffer = "";
|
|
643
|
+
let stderr = "";
|
|
644
|
+
let timedOut = false;
|
|
645
|
+
let completedViaTerminalFrame = false;
|
|
646
|
+
let settled = false;
|
|
647
|
+
let idleTimer = null;
|
|
648
|
+
let postKillTimer = null;
|
|
649
|
+
let completionGraceTimer = null;
|
|
650
|
+
const clearAllTimers = () => {
|
|
651
|
+
if (idleTimer) {
|
|
652
|
+
clearTimeout(idleTimer);
|
|
653
|
+
idleTimer = null;
|
|
654
|
+
}
|
|
655
|
+
clearTimeout(totalTimer);
|
|
656
|
+
if (postKillTimer) {
|
|
657
|
+
clearTimeout(postKillTimer);
|
|
658
|
+
postKillTimer = null;
|
|
659
|
+
}
|
|
660
|
+
if (completionGraceTimer) {
|
|
661
|
+
clearTimeout(completionGraceTimer);
|
|
662
|
+
completionGraceTimer = null;
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
const finish = (code) => {
|
|
666
|
+
if (settled)
|
|
667
|
+
return;
|
|
668
|
+
settled = true;
|
|
669
|
+
if (stdoutLineBuffer.trim() && params.onStdoutLine) {
|
|
670
|
+
try {
|
|
671
|
+
params.onStdoutLine(stdoutLineBuffer.trim());
|
|
672
|
+
}
|
|
673
|
+
catch {
|
|
674
|
+
// Ignore
|
|
675
|
+
}
|
|
676
|
+
stdoutLineBuffer = "";
|
|
677
|
+
}
|
|
678
|
+
clearAllTimers();
|
|
679
|
+
this.activeProcesses.delete(params.shareId);
|
|
680
|
+
resolve({
|
|
681
|
+
code: completedViaTerminalFrame && code === null ? 0 : code,
|
|
682
|
+
stdout,
|
|
683
|
+
stderr,
|
|
684
|
+
timedOut: completedViaTerminalFrame ? false : timedOut,
|
|
56
685
|
});
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
686
|
+
};
|
|
687
|
+
const killChild = () => {
|
|
688
|
+
if (!child.killed) {
|
|
689
|
+
try {
|
|
61
690
|
child.kill("SIGTERM");
|
|
62
691
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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"}`,
|
|
692
|
+
catch {
|
|
693
|
+
// Ignore
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
if (process.platform === "win32" && child.pid) {
|
|
697
|
+
try {
|
|
698
|
+
const tk = spawn("taskkill", ["/T", "/F", "/PID", String(child.pid)], {
|
|
699
|
+
stdio: "ignore",
|
|
700
|
+
windowsHide: true,
|
|
87
701
|
});
|
|
88
|
-
|
|
702
|
+
tk.unref();
|
|
89
703
|
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
resolve(sandboxResult);
|
|
93
|
-
return;
|
|
704
|
+
catch {
|
|
705
|
+
// Ignore
|
|
94
706
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
707
|
+
}
|
|
708
|
+
if (!postKillTimer) {
|
|
709
|
+
postKillTimer = setTimeout(() => {
|
|
710
|
+
finish(completedViaTerminalFrame ? 0 : null);
|
|
711
|
+
}, 1500);
|
|
712
|
+
}
|
|
713
|
+
};
|
|
714
|
+
const resetIdleTimer = () => {
|
|
715
|
+
if (settled || completedViaTerminalFrame)
|
|
716
|
+
return;
|
|
717
|
+
if (idleTimer)
|
|
718
|
+
clearTimeout(idleTimer);
|
|
719
|
+
idleTimer = setTimeout(() => {
|
|
720
|
+
if (!completedViaTerminalFrame) {
|
|
721
|
+
timedOut = true;
|
|
722
|
+
killChild();
|
|
723
|
+
}
|
|
724
|
+
}, idleTimeoutMs);
|
|
725
|
+
};
|
|
726
|
+
this.activeProcesses.set(params.shareId, killChild);
|
|
727
|
+
resetIdleTimer();
|
|
728
|
+
const totalTimer = setTimeout(() => {
|
|
729
|
+
if (!completedViaTerminalFrame) {
|
|
730
|
+
timedOut = true;
|
|
731
|
+
killChild();
|
|
732
|
+
}
|
|
733
|
+
}, maxTotalTimeoutMs);
|
|
734
|
+
child.stdout.on("data", (chunk) => {
|
|
735
|
+
const text = chunk.toString("utf8");
|
|
736
|
+
stdout += text;
|
|
737
|
+
resetIdleTimer();
|
|
738
|
+
if (params.onStdoutLine) {
|
|
739
|
+
stdoutLineBuffer += text;
|
|
740
|
+
const lines = stdoutLineBuffer.split(/\r?\n/);
|
|
741
|
+
stdoutLineBuffer = lines.pop() ?? "";
|
|
742
|
+
for (const rawLine of lines) {
|
|
743
|
+
const trimmed = rawLine.trim();
|
|
744
|
+
if (!trimmed)
|
|
745
|
+
continue;
|
|
746
|
+
let shouldCompleteNow = false;
|
|
747
|
+
try {
|
|
748
|
+
shouldCompleteNow = Boolean(params.onStdoutLine(trimmed));
|
|
749
|
+
}
|
|
750
|
+
catch {
|
|
751
|
+
// Ignore listener errors
|
|
752
|
+
}
|
|
753
|
+
if (shouldCompleteNow && !completedViaTerminalFrame) {
|
|
754
|
+
completedViaTerminalFrame = true;
|
|
755
|
+
if (idleTimer) {
|
|
756
|
+
clearTimeout(idleTimer);
|
|
757
|
+
idleTimer = null;
|
|
758
|
+
}
|
|
759
|
+
completionGraceTimer = setTimeout(() => {
|
|
760
|
+
if (!settled) {
|
|
761
|
+
killChild();
|
|
762
|
+
finish(0);
|
|
763
|
+
}
|
|
764
|
+
}, completionGraceMs);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
child.stderr.on("data", (chunk) => {
|
|
770
|
+
stderr += chunk.toString("utf8");
|
|
771
|
+
resetIdleTimer();
|
|
772
|
+
});
|
|
773
|
+
child.on("error", (err) => {
|
|
774
|
+
if (!settled) {
|
|
775
|
+
settled = true;
|
|
776
|
+
clearAllTimers();
|
|
777
|
+
this.activeProcesses.delete(params.shareId);
|
|
778
|
+
reject(err);
|
|
779
|
+
}
|
|
780
|
+
});
|
|
781
|
+
child.on("close", (code) => {
|
|
782
|
+
finish(code);
|
|
783
|
+
});
|
|
784
|
+
if (params.stdinPayload !== undefined) {
|
|
785
|
+
child.stdin.write(params.stdinPayload, "utf8");
|
|
109
786
|
}
|
|
787
|
+
child.stdin.end();
|
|
110
788
|
});
|
|
111
789
|
}
|
|
790
|
+
async executeGuestTurn(request) {
|
|
791
|
+
// Layer 1: Deterministic Fail-Closed Guard & Grey-Zone Permission Broker pre-check
|
|
792
|
+
const precheck = runSandboxResponder(request);
|
|
793
|
+
if (precheck.blockedByGuard || precheck.greyZoneEscalation) {
|
|
794
|
+
return precheck;
|
|
795
|
+
}
|
|
796
|
+
const mode = resolveEffectiveMode(this.options);
|
|
797
|
+
if (mode === "sandbox") {
|
|
798
|
+
return precheck;
|
|
799
|
+
}
|
|
800
|
+
const cliBinary = AGENT_ENGINE_CATALOG[this.engine].cliBinary;
|
|
801
|
+
const spawnTarget = resolveCliSpawnTarget(cliBinary);
|
|
802
|
+
const isZh = /[\u4e00-\u9fff]/.test(`${request.context.topic} ${request.prompt}`);
|
|
803
|
+
if (!spawnTarget) {
|
|
804
|
+
return {
|
|
805
|
+
blockedByGuard: false,
|
|
806
|
+
runtimeSource: "live-cli",
|
|
807
|
+
thinkingTrace: `[Live CLI Missing] Binary "${cliBinary}" not found in host PATH.`,
|
|
808
|
+
replyContent: isZh
|
|
809
|
+
? `未在发起人电脑 PATH 中检测到 \`${cliBinary}\` 命令行程序,请确认已安装 ${AGENT_ENGINE_CATALOG[this.engine].displayName} 后重试。`
|
|
810
|
+
: `CLI binary \`${cliBinary}\` was not found in the host's PATH. Please ensure ${AGENT_ENGINE_CATALOG[this.engine].displayName} is installed.`,
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
try {
|
|
814
|
+
const liveRes = await this.executeLiveCliTurn(request, spawnTarget);
|
|
815
|
+
return {
|
|
816
|
+
runtimeSource: "live-cli",
|
|
817
|
+
...liveRes,
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
catch (err) {
|
|
821
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
822
|
+
return {
|
|
823
|
+
blockedByGuard: false,
|
|
824
|
+
runtimeSource: "live-cli",
|
|
825
|
+
thinkingTrace: `[Live CLI Spawn Error (${cliBinary})] ${errMsg}`,
|
|
826
|
+
replyContent: isZh
|
|
827
|
+
? `调用本地 \`${cliBinary}\` 失败:${errMsg}`
|
|
828
|
+
: `Failed to invoke local \`${cliBinary}\`: ${errMsg}`,
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
}
|
|
112
832
|
async cancelActiveSession(shareId) {
|
|
113
833
|
const cancelFn = this.activeProcesses.get(shareId);
|
|
114
834
|
if (cancelFn) {
|
|
@@ -165,12 +885,152 @@ export class ClaudeCodeAdapter extends BaseEngineAdapter {
|
|
|
165
885
|
generatedFiles: bundle.files,
|
|
166
886
|
};
|
|
167
887
|
}
|
|
888
|
+
async executeLiveCliTurn(request, target) {
|
|
889
|
+
const { context } = request;
|
|
890
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
891
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
892
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
893
|
+
shareId: context.shareId,
|
|
894
|
+
workspacePath: safeWs.cwd,
|
|
895
|
+
permissionTier: context.permissionTier,
|
|
896
|
+
writableGlobs: context.writableGlobs,
|
|
897
|
+
}, true);
|
|
898
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
899
|
+
const systemEnvelopeFile = path.join(artifactsDir, "cyf-system-envelope.txt");
|
|
900
|
+
fs.writeFileSync(systemEnvelopeFile, systemPromptPayload, "utf8");
|
|
901
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
902
|
+
const allowedTools = context.permissionTier === "TIER_2_WORKTREE_SANDBOX"
|
|
903
|
+
? "Read,Glob,Grep,Edit,Write"
|
|
904
|
+
: "Read,Glob,Grep";
|
|
905
|
+
const cliArgs = [
|
|
906
|
+
"-p",
|
|
907
|
+
"--output-format",
|
|
908
|
+
"stream-json",
|
|
909
|
+
"--verbose",
|
|
910
|
+
"--max-turns",
|
|
911
|
+
safeWs.workspaceExists ? "10" : "2",
|
|
912
|
+
"--strict-mcp-config",
|
|
913
|
+
"--mcp-config",
|
|
914
|
+
bundle.emptyMcpConfigPath,
|
|
915
|
+
"--settings",
|
|
916
|
+
bundle.claudeSettingsPath,
|
|
917
|
+
`--tools=${safeWs.workspaceExists ? allowedTools : ""}`,
|
|
918
|
+
...(safeWs.workspaceExists ? [`--allowedTools=${allowedTools}`] : []),
|
|
919
|
+
"--permission-mode",
|
|
920
|
+
"dontAsk",
|
|
921
|
+
"--append-system-prompt-file",
|
|
922
|
+
systemEnvelopeFile,
|
|
923
|
+
];
|
|
924
|
+
if (usesNativeFork) {
|
|
925
|
+
cliArgs.push("--resume", context.rawSessionId, "--fork-session");
|
|
926
|
+
}
|
|
927
|
+
else {
|
|
928
|
+
cliArgs.push("--no-session-persistence");
|
|
929
|
+
}
|
|
930
|
+
const turnInput = usesNativeFork
|
|
931
|
+
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
932
|
+
: buildConversationTurnPayload(request);
|
|
933
|
+
const childEnv = this.buildBaseEnv(context, bundle.guardScriptPath);
|
|
934
|
+
const inspector = createClaudeStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
935
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
936
|
+
shareId: context.shareId,
|
|
937
|
+
target,
|
|
938
|
+
args: cliArgs,
|
|
939
|
+
cwd: safeWs.cwd,
|
|
940
|
+
env: childEnv,
|
|
941
|
+
stdinPayload: turnInput,
|
|
942
|
+
onStdoutLine: inspector.onLine,
|
|
943
|
+
});
|
|
944
|
+
if (code === 2) {
|
|
945
|
+
return {
|
|
946
|
+
blockedByGuard: true,
|
|
947
|
+
executedTools: inspector.executedTools,
|
|
948
|
+
guardInterception: {
|
|
949
|
+
ruleId: "SENSITIVE_FILE_ACCESS",
|
|
950
|
+
targetOrPattern: "claude PreToolUse Hook",
|
|
951
|
+
reason: stderr.trim() || "Blocked by Fail-Closed Hook (Exit Code 2).",
|
|
952
|
+
},
|
|
953
|
+
thinkingTrace: `[Claude Live Hook Exit 2] ${stderr.trim()}`,
|
|
954
|
+
replyContent: stderr.trim() || "Blocked by CYF Fail-Closed Guard (Exit Code 2).",
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
const parsed = parseClaudeJsonOutput(stdout);
|
|
958
|
+
if (parsed.reply) {
|
|
959
|
+
return {
|
|
960
|
+
blockedByGuard: false,
|
|
961
|
+
executedTools: inspector.executedTools,
|
|
962
|
+
thinkingTrace: parsed.thinking ||
|
|
963
|
+
`[Claude Code Live CLI (exit=${String(code)}, fork=${String(usesNativeFork)})]`,
|
|
964
|
+
replyContent: parsed.reply,
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
// If multi-turn workspace inspection hit max-turns or timed out after gathering observations, run a 1-turn synthesis pass
|
|
968
|
+
if ((parsed.hitMaxTurns || timedOut) &&
|
|
969
|
+
(parsed.observations.length > 0 || parsed.thinking.length > 0)) {
|
|
970
|
+
request.onStreamEvent?.({ type: "synthesizing" });
|
|
971
|
+
const synthInspector = createClaudeStreamLineInspector(safeWs.cwd);
|
|
972
|
+
const synthesisInput = [
|
|
973
|
+
turnInput,
|
|
974
|
+
"",
|
|
975
|
+
"<workspace_inspection_notes>",
|
|
976
|
+
...parsed.observations.slice(-10),
|
|
977
|
+
...(parsed.thinking ? [`[Prior Reasoning]:\n${parsed.thinking.slice(-2400)}`] : []),
|
|
978
|
+
"</workspace_inspection_notes>",
|
|
979
|
+
"",
|
|
980
|
+
"Instruction: Based on the workspace inspection notes and approved context above, write a complete, clear, and helpful response to the colleague now without calling any tools.",
|
|
981
|
+
].join("\n");
|
|
982
|
+
const synthRes = await this.spawnAndCollect({
|
|
983
|
+
shareId: context.shareId,
|
|
984
|
+
target,
|
|
985
|
+
args: [
|
|
986
|
+
"-p",
|
|
987
|
+
"--output-format",
|
|
988
|
+
"stream-json",
|
|
989
|
+
"--verbose",
|
|
990
|
+
"--max-turns",
|
|
991
|
+
"1",
|
|
992
|
+
"--strict-mcp-config",
|
|
993
|
+
"--mcp-config",
|
|
994
|
+
bundle.emptyMcpConfigPath,
|
|
995
|
+
"--tools=",
|
|
996
|
+
"--no-session-persistence",
|
|
997
|
+
"--append-system-prompt-file",
|
|
998
|
+
systemEnvelopeFile,
|
|
999
|
+
],
|
|
1000
|
+
cwd: safeWs.cwd,
|
|
1001
|
+
env: childEnv,
|
|
1002
|
+
stdinPayload: synthesisInput,
|
|
1003
|
+
idleTimeoutMs: 45_000,
|
|
1004
|
+
maxTotalTimeoutMs: 60_000,
|
|
1005
|
+
onStdoutLine: synthInspector.onLine,
|
|
1006
|
+
});
|
|
1007
|
+
const synthParsed = parseClaudeJsonOutput(synthRes.stdout);
|
|
1008
|
+
if (synthParsed.reply) {
|
|
1009
|
+
return {
|
|
1010
|
+
blockedByGuard: false,
|
|
1011
|
+
executedTools: inspector.executedTools,
|
|
1012
|
+
thinkingTrace: [parsed.thinking, synthParsed.thinking].filter(Boolean).join("\n") ||
|
|
1013
|
+
`[Claude Code Synthesized After Inspection]`,
|
|
1014
|
+
replyContent: synthParsed.reply,
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
const diag = timedOut
|
|
1019
|
+
? "Claude Code CLI timed out waiting for upstream model response."
|
|
1020
|
+
: parsed.resultError ||
|
|
1021
|
+
stderr.trim() ||
|
|
1022
|
+
`Claude CLI exited with code ${String(code)}`;
|
|
1023
|
+
return {
|
|
1024
|
+
blockedByGuard: false,
|
|
1025
|
+
thinkingTrace: `[Claude Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
1026
|
+
replyContent: diag,
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
168
1029
|
}
|
|
169
1030
|
/**
|
|
170
|
-
* 2. OpenAI Codex Adapter (`codex app-server` JSON-RPC 2.0)
|
|
171
|
-
* - Mode A/B/D: `
|
|
172
|
-
* - Mode C: `
|
|
173
|
-
* - Revocation: `turn/interrupt`
|
|
1031
|
+
* 2. OpenAI Codex Adapter (`codex app-server` JSON-RPC 2.0 & `codex exec` read-only sandbox)
|
|
1032
|
+
* - Mode A/B/D: `ephemeral: true` + `sandbox: "read-only"`
|
|
1033
|
+
* - Mode C: `fork` (explicitly avoiding single-writer lock on `thread/resume`)
|
|
174
1034
|
*/
|
|
175
1035
|
export class CodexAdapter extends BaseEngineAdapter {
|
|
176
1036
|
engine = "codex";
|
|
@@ -258,12 +1118,99 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
258
1118
|
},
|
|
259
1119
|
};
|
|
260
1120
|
}
|
|
1121
|
+
async executeLiveCliTurn(request, target) {
|
|
1122
|
+
const { context } = request;
|
|
1123
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1124
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
1125
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
1126
|
+
shareId: context.shareId,
|
|
1127
|
+
workspacePath: safeWs.cwd,
|
|
1128
|
+
permissionTier: context.permissionTier,
|
|
1129
|
+
writableGlobs: context.writableGlobs,
|
|
1130
|
+
}, true);
|
|
1131
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
1132
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
1133
|
+
const lastMsgFile = path.join(artifactsDir, `codex-last-${Date.now()}-${Math.random().toString(36).slice(2, 7)}.txt`);
|
|
1134
|
+
// Strip private MCP servers via `-c mcp_servers={}` and enforce OS read-only sandbox + ephemeral non-persistence
|
|
1135
|
+
const cliArgs = usesNativeFork
|
|
1136
|
+
? [
|
|
1137
|
+
"-c",
|
|
1138
|
+
"mcp_servers={}",
|
|
1139
|
+
"-c",
|
|
1140
|
+
"stream_max_retries=1",
|
|
1141
|
+
"-c",
|
|
1142
|
+
'model_reasoning_effort="medium"',
|
|
1143
|
+
"-c",
|
|
1144
|
+
'sandbox_mode="read-only"',
|
|
1145
|
+
"exec",
|
|
1146
|
+
"fork",
|
|
1147
|
+
context.rawSessionId,
|
|
1148
|
+
"--json",
|
|
1149
|
+
"--ephemeral",
|
|
1150
|
+
"--skip-git-repo-check",
|
|
1151
|
+
"-o",
|
|
1152
|
+
lastMsgFile,
|
|
1153
|
+
"-",
|
|
1154
|
+
]
|
|
1155
|
+
: [
|
|
1156
|
+
"-c",
|
|
1157
|
+
"mcp_servers={}",
|
|
1158
|
+
"-c",
|
|
1159
|
+
"stream_max_retries=1",
|
|
1160
|
+
"-c",
|
|
1161
|
+
'model_reasoning_effort="medium"',
|
|
1162
|
+
"exec",
|
|
1163
|
+
"--json",
|
|
1164
|
+
"--ephemeral",
|
|
1165
|
+
"--sandbox",
|
|
1166
|
+
"read-only",
|
|
1167
|
+
"--skip-git-repo-check",
|
|
1168
|
+
"-C",
|
|
1169
|
+
safeWs.cwd,
|
|
1170
|
+
"-o",
|
|
1171
|
+
lastMsgFile,
|
|
1172
|
+
"-",
|
|
1173
|
+
];
|
|
1174
|
+
const stdinPayload = [
|
|
1175
|
+
systemPromptPayload,
|
|
1176
|
+
"",
|
|
1177
|
+
usesNativeFork
|
|
1178
|
+
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
1179
|
+
: buildConversationTurnPayload(request),
|
|
1180
|
+
].join("\n");
|
|
1181
|
+
const codexInspector = createCodexStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
1182
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
1183
|
+
shareId: context.shareId,
|
|
1184
|
+
target,
|
|
1185
|
+
args: cliArgs,
|
|
1186
|
+
cwd: safeWs.cwd,
|
|
1187
|
+
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
1188
|
+
stdinPayload,
|
|
1189
|
+
completionGraceMs: 320,
|
|
1190
|
+
onStdoutLine: codexInspector.onLine,
|
|
1191
|
+
});
|
|
1192
|
+
const parsed = parseCodexExecOutput(stdout, lastMsgFile);
|
|
1193
|
+
if (parsed.reply) {
|
|
1194
|
+
return {
|
|
1195
|
+
blockedByGuard: false,
|
|
1196
|
+
executedTools: codexInspector.executedTools,
|
|
1197
|
+
thinkingTrace: parsed.thinking ||
|
|
1198
|
+
`[Codex Live CLI (exit=${String(code)}, sandbox=read-only, ephemeral=true)]`,
|
|
1199
|
+
replyContent: parsed.reply,
|
|
1200
|
+
};
|
|
1201
|
+
}
|
|
1202
|
+
const diag = timedOut
|
|
1203
|
+
? "Codex CLI timed out waiting for model response."
|
|
1204
|
+
: parsed.errorSummary || stderr.trim() || stdout.trim() || `Codex CLI exited with code ${String(code)}`;
|
|
1205
|
+
return {
|
|
1206
|
+
blockedByGuard: false,
|
|
1207
|
+
thinkingTrace: `[Codex Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
1208
|
+
replyContent: diag,
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
261
1211
|
}
|
|
262
1212
|
/**
|
|
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
|
|
1213
|
+
* 3. SST OpenCode Adapter (`opencode serve` REST/SSE + `opencode run --format json --archived`)
|
|
267
1214
|
*/
|
|
268
1215
|
export class OpenCodeAdapter extends BaseEngineAdapter {
|
|
269
1216
|
engine = "opencode";
|
|
@@ -353,10 +1300,83 @@ export class OpenCodeAdapter extends BaseEngineAdapter {
|
|
|
353
1300
|
generatedFiles: bundle.files,
|
|
354
1301
|
};
|
|
355
1302
|
}
|
|
1303
|
+
async executeLiveCliTurn(request, target) {
|
|
1304
|
+
const { context } = request;
|
|
1305
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1306
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
1307
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
1308
|
+
shareId: context.shareId,
|
|
1309
|
+
workspacePath: safeWs.cwd,
|
|
1310
|
+
permissionTier: context.permissionTier,
|
|
1311
|
+
writableGlobs: context.writableGlobs,
|
|
1312
|
+
}, true);
|
|
1313
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
1314
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
1315
|
+
const turnBody = usesNativeFork
|
|
1316
|
+
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
1317
|
+
: buildConversationTurnPayload(request);
|
|
1318
|
+
const fullPrompt = [systemPromptPayload, "", turnBody].join("\n");
|
|
1319
|
+
const cliArgs = [
|
|
1320
|
+
"run",
|
|
1321
|
+
"--format",
|
|
1322
|
+
"json",
|
|
1323
|
+
"--archived",
|
|
1324
|
+
"--thinking",
|
|
1325
|
+
"--standalone",
|
|
1326
|
+
];
|
|
1327
|
+
if (usesNativeFork) {
|
|
1328
|
+
cliArgs.push("--session", context.rawSessionId, "--fork");
|
|
1329
|
+
}
|
|
1330
|
+
if (fullPrompt.length > 4000) {
|
|
1331
|
+
const contextFile = path.join(artifactsDir, "cyf-opencode-context.md");
|
|
1332
|
+
fs.writeFileSync(contextFile, [systemPromptPayload, "", ...(usesNativeFork ? [] : [buildConversationTurnPayload({ ...request, prompt: "" })])].join("\n"), "utf8");
|
|
1333
|
+
cliArgs.push("--file", contextFile, `[Colleague (${request.guestName})]:\n${request.prompt}`);
|
|
1334
|
+
}
|
|
1335
|
+
else {
|
|
1336
|
+
cliArgs.push(fullPrompt);
|
|
1337
|
+
}
|
|
1338
|
+
const strictReadOnlyConfig = JSON.stringify({
|
|
1339
|
+
mcp: {},
|
|
1340
|
+
permission: {
|
|
1341
|
+
bash: "deny",
|
|
1342
|
+
edit: context.permissionTier === "TIER_2_WORKTREE_SANDBOX" ? "allow" : "deny",
|
|
1343
|
+
webfetch: "deny",
|
|
1344
|
+
},
|
|
1345
|
+
});
|
|
1346
|
+
const ocInspector = createOpenCodeStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
1347
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
1348
|
+
shareId: context.shareId,
|
|
1349
|
+
target,
|
|
1350
|
+
args: cliArgs,
|
|
1351
|
+
cwd: safeWs.cwd,
|
|
1352
|
+
env: {
|
|
1353
|
+
...this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
1354
|
+
OPENCODE_CONFIG_CONTENT: strictReadOnlyConfig,
|
|
1355
|
+
},
|
|
1356
|
+
onStdoutLine: ocInspector.onLine,
|
|
1357
|
+
});
|
|
1358
|
+
const parsed = parseOpenCodeJsonOutput(stdout);
|
|
1359
|
+
if (parsed.reply) {
|
|
1360
|
+
return {
|
|
1361
|
+
blockedByGuard: false,
|
|
1362
|
+
executedTools: ocInspector.executedTools,
|
|
1363
|
+
thinkingTrace: parsed.thinking ||
|
|
1364
|
+
`[OpenCode Live CLI (exit=${String(code)}, archived=true)]`,
|
|
1365
|
+
replyContent: parsed.reply,
|
|
1366
|
+
};
|
|
1367
|
+
}
|
|
1368
|
+
const diag = timedOut
|
|
1369
|
+
? "OpenCode CLI timed out waiting for model response."
|
|
1370
|
+
: stderr.trim() || stdout.trim() || `OpenCode CLI exited with code ${String(code)}`;
|
|
1371
|
+
return {
|
|
1372
|
+
blockedByGuard: false,
|
|
1373
|
+
thinkingTrace: `[OpenCode Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
1374
|
+
replyContent: diag,
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
356
1377
|
}
|
|
357
1378
|
/**
|
|
358
1379
|
* 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
1380
|
*/
|
|
361
1381
|
export class DshAdapter extends BaseEngineAdapter {
|
|
362
1382
|
engine = "dsh";
|
|
@@ -412,11 +1432,58 @@ export class DshAdapter extends BaseEngineAdapter {
|
|
|
412
1432
|
generatedFiles: bundle.files,
|
|
413
1433
|
};
|
|
414
1434
|
}
|
|
1435
|
+
async executeLiveCliTurn(request, target) {
|
|
1436
|
+
const { context } = request;
|
|
1437
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1438
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
1439
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
1440
|
+
shareId: context.shareId,
|
|
1441
|
+
workspacePath: safeWs.cwd,
|
|
1442
|
+
permissionTier: context.permissionTier,
|
|
1443
|
+
writableGlobs: context.writableGlobs,
|
|
1444
|
+
}, true);
|
|
1445
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
1446
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
1447
|
+
const cliArgs = [
|
|
1448
|
+
"--profile",
|
|
1449
|
+
"sdk",
|
|
1450
|
+
"--patch",
|
|
1451
|
+
bundle.dshPatchYamlPath,
|
|
1452
|
+
...(usesNativeFork ? ["--fork", context.rawSessionId] : []),
|
|
1453
|
+
];
|
|
1454
|
+
const stdinPayload = [
|
|
1455
|
+
systemPromptPayload,
|
|
1456
|
+
"",
|
|
1457
|
+
buildConversationTurnPayload(request),
|
|
1458
|
+
].join("\n");
|
|
1459
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
1460
|
+
shareId: context.shareId,
|
|
1461
|
+
target,
|
|
1462
|
+
args: cliArgs,
|
|
1463
|
+
cwd: safeWs.cwd,
|
|
1464
|
+
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
1465
|
+
stdinPayload,
|
|
1466
|
+
});
|
|
1467
|
+
const parsed = parseClaudeJsonOutput(stdout);
|
|
1468
|
+
if (parsed.reply) {
|
|
1469
|
+
return {
|
|
1470
|
+
blockedByGuard: false,
|
|
1471
|
+
thinkingTrace: parsed.thinking || `[Dsh Live CLI (exit=${String(code)})]`,
|
|
1472
|
+
replyContent: parsed.reply,
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
const diag = timedOut
|
|
1476
|
+
? "Dsh CLI timed out waiting for model response."
|
|
1477
|
+
: stderr.trim() || stdout.trim() || `Dsh CLI exited with code ${String(code)}`;
|
|
1478
|
+
return {
|
|
1479
|
+
blockedByGuard: false,
|
|
1480
|
+
thinkingTrace: `[Dsh Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
1481
|
+
replyContent: diag,
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
415
1484
|
}
|
|
416
1485
|
/**
|
|
417
1486
|
* 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
1487
|
*/
|
|
421
1488
|
export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
422
1489
|
engine = "codebuddy";
|
|
@@ -457,6 +1524,150 @@ export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
|
457
1524
|
generatedFiles: bundle.files,
|
|
458
1525
|
};
|
|
459
1526
|
}
|
|
1527
|
+
async executeLiveCliTurn(request, target) {
|
|
1528
|
+
const { context } = request;
|
|
1529
|
+
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1530
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
1531
|
+
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
1532
|
+
shareId: context.shareId,
|
|
1533
|
+
workspacePath: safeWs.cwd,
|
|
1534
|
+
permissionTier: context.permissionTier,
|
|
1535
|
+
writableGlobs: context.writableGlobs,
|
|
1536
|
+
}, true);
|
|
1537
|
+
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
1538
|
+
const systemEnvelopeFile = path.join(artifactsDir, "cyf-cb-system-envelope.txt");
|
|
1539
|
+
fs.writeFileSync(systemEnvelopeFile, systemPromptPayload, "utf8");
|
|
1540
|
+
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
1541
|
+
const allowedTools = context.permissionTier === "TIER_2_WORKTREE_SANDBOX"
|
|
1542
|
+
? "Read,Glob,Grep,Edit,Write"
|
|
1543
|
+
: "Read,Glob,Grep";
|
|
1544
|
+
// When workspace files exist, use `--append-system-prompt` so CodeBuddy retains native tool schemas;
|
|
1545
|
+
// when workspace does not exist (`--tools=""`), use `--system-prompt-file` so CodeBuddy doesn't hallucinate `<tool_calls>` XML!
|
|
1546
|
+
const effectiveEnvelope = safeWs.workspaceExists
|
|
1547
|
+
? systemPromptPayload
|
|
1548
|
+
: `${systemPromptPayload}\n\nNote: No local repository files are mounted for this share. Answer directly and concisely from the approved context above without attempting any file or tool calls.`;
|
|
1549
|
+
fs.writeFileSync(systemEnvelopeFile, effectiveEnvelope, "utf8");
|
|
1550
|
+
const promptFlagArgs = safeWs.workspaceExists && systemPromptPayload.length <= 6000
|
|
1551
|
+
? ["--append-system-prompt", systemPromptPayload]
|
|
1552
|
+
: ["--system-prompt-file", systemEnvelopeFile];
|
|
1553
|
+
const cliArgs = [
|
|
1554
|
+
"-p",
|
|
1555
|
+
"--output-format",
|
|
1556
|
+
"stream-json",
|
|
1557
|
+
"--verbose",
|
|
1558
|
+
"--max-turns",
|
|
1559
|
+
safeWs.workspaceExists ? "10" : "2",
|
|
1560
|
+
"--strict-mcp-config",
|
|
1561
|
+
"--mcp-config",
|
|
1562
|
+
bundle.emptyMcpConfigPath,
|
|
1563
|
+
"--no-session-persistence",
|
|
1564
|
+
"--settings",
|
|
1565
|
+
bundle.claudeSettingsPath,
|
|
1566
|
+
`--tools=${safeWs.workspaceExists ? allowedTools : ""}`,
|
|
1567
|
+
...(safeWs.workspaceExists ? [`--allowedTools=${allowedTools}`] : []),
|
|
1568
|
+
"--permission-mode",
|
|
1569
|
+
"dontAsk",
|
|
1570
|
+
...promptFlagArgs,
|
|
1571
|
+
...(usesNativeFork ? ["--resume", context.rawSessionId, "--fork-session"] : []),
|
|
1572
|
+
];
|
|
1573
|
+
const turnInput = usesNativeFork
|
|
1574
|
+
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
1575
|
+
: buildConversationTurnPayload(request);
|
|
1576
|
+
const childEnv = this.buildBaseEnv(context, bundle.guardScriptPath);
|
|
1577
|
+
const inspector = createClaudeStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
1578
|
+
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
1579
|
+
shareId: context.shareId,
|
|
1580
|
+
target,
|
|
1581
|
+
args: cliArgs,
|
|
1582
|
+
cwd: safeWs.cwd,
|
|
1583
|
+
env: childEnv,
|
|
1584
|
+
stdinPayload: turnInput,
|
|
1585
|
+
onStdoutLine: inspector.onLine,
|
|
1586
|
+
});
|
|
1587
|
+
if (code === 2) {
|
|
1588
|
+
return {
|
|
1589
|
+
blockedByGuard: true,
|
|
1590
|
+
executedTools: inspector.executedTools,
|
|
1591
|
+
guardInterception: {
|
|
1592
|
+
ruleId: "SENSITIVE_FILE_ACCESS",
|
|
1593
|
+
targetOrPattern: "codebuddy PreToolUse Hook",
|
|
1594
|
+
reason: stderr.trim() || "Blocked by Fail-Closed Hook (Exit Code 2).",
|
|
1595
|
+
},
|
|
1596
|
+
thinkingTrace: `[CodeBuddy Live Hook Exit 2] ${stderr.trim()}`,
|
|
1597
|
+
replyContent: stderr.trim() || "Blocked by CYF Fail-Closed Guard (Exit Code 2).",
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
const parsed = parseClaudeJsonOutput(stdout);
|
|
1601
|
+
if (parsed.reply) {
|
|
1602
|
+
return {
|
|
1603
|
+
blockedByGuard: false,
|
|
1604
|
+
executedTools: inspector.executedTools,
|
|
1605
|
+
thinkingTrace: parsed.thinking ||
|
|
1606
|
+
`[CodeBuddy Live CLI (exit=${String(code)}, fork=${String(usesNativeFork)})]`,
|
|
1607
|
+
replyContent: parsed.reply,
|
|
1608
|
+
};
|
|
1609
|
+
}
|
|
1610
|
+
// If multi-turn workspace inspection hit max-turns or timed out after gathering observations, run a 1-turn synthesis pass
|
|
1611
|
+
if ((parsed.hitMaxTurns || timedOut) &&
|
|
1612
|
+
(parsed.observations.length > 0 || parsed.thinking.length > 0)) {
|
|
1613
|
+
request.onStreamEvent?.({ type: "synthesizing" });
|
|
1614
|
+
const synthInspector = createClaudeStreamLineInspector(safeWs.cwd);
|
|
1615
|
+
const synthesisInput = [
|
|
1616
|
+
turnInput,
|
|
1617
|
+
"",
|
|
1618
|
+
"<workspace_inspection_notes>",
|
|
1619
|
+
...parsed.observations.slice(-10),
|
|
1620
|
+
...(parsed.thinking ? [`[Prior Reasoning]:\n${parsed.thinking.slice(-2400)}`] : []),
|
|
1621
|
+
"</workspace_inspection_notes>",
|
|
1622
|
+
"",
|
|
1623
|
+
"Instruction: Based on the workspace inspection notes and approved context above, write a complete, clear, and helpful response to the colleague now without calling any tools.",
|
|
1624
|
+
].join("\n");
|
|
1625
|
+
const synthRes = await this.spawnAndCollect({
|
|
1626
|
+
shareId: context.shareId,
|
|
1627
|
+
target,
|
|
1628
|
+
args: [
|
|
1629
|
+
"-p",
|
|
1630
|
+
"--output-format",
|
|
1631
|
+
"stream-json",
|
|
1632
|
+
"--verbose",
|
|
1633
|
+
"--max-turns",
|
|
1634
|
+
"1",
|
|
1635
|
+
"--strict-mcp-config",
|
|
1636
|
+
"--mcp-config",
|
|
1637
|
+
bundle.emptyMcpConfigPath,
|
|
1638
|
+
"--no-session-persistence",
|
|
1639
|
+
"--tools=",
|
|
1640
|
+
...promptFlagArgs,
|
|
1641
|
+
],
|
|
1642
|
+
cwd: safeWs.cwd,
|
|
1643
|
+
env: childEnv,
|
|
1644
|
+
stdinPayload: synthesisInput,
|
|
1645
|
+
idleTimeoutMs: 45_000,
|
|
1646
|
+
maxTotalTimeoutMs: 60_000,
|
|
1647
|
+
onStdoutLine: synthInspector.onLine,
|
|
1648
|
+
});
|
|
1649
|
+
const synthParsed = parseClaudeJsonOutput(synthRes.stdout);
|
|
1650
|
+
if (synthParsed.reply) {
|
|
1651
|
+
return {
|
|
1652
|
+
blockedByGuard: false,
|
|
1653
|
+
executedTools: inspector.executedTools,
|
|
1654
|
+
thinkingTrace: [parsed.thinking, synthParsed.thinking].filter(Boolean).join("\n") ||
|
|
1655
|
+
`[CodeBuddy Synthesized After Inspection]`,
|
|
1656
|
+
replyContent: synthParsed.reply,
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
const diag = timedOut
|
|
1661
|
+
? "CodeBuddy CLI timed out waiting for model response."
|
|
1662
|
+
: parsed.resultError ||
|
|
1663
|
+
stderr.trim() ||
|
|
1664
|
+
`CodeBuddy CLI exited with code ${String(code)}`;
|
|
1665
|
+
return {
|
|
1666
|
+
blockedByGuard: false,
|
|
1667
|
+
thinkingTrace: `[CodeBuddy Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
1668
|
+
replyContent: diag,
|
|
1669
|
+
};
|
|
1670
|
+
}
|
|
460
1671
|
}
|
|
461
1672
|
/**
|
|
462
1673
|
* Registry holding all 5 first-wave runtime adapters.
|