@cyfsh/adapters 0.3.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 +17 -1
- package/dist/adapters.d.ts.map +1 -1
- package/dist/adapters.js +595 -64
- 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 +8 -5
- package/dist/sandbox-responder.js.map +1 -1
- package/dist/types.d.ts +20 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/adapters.js
CHANGED
|
@@ -89,16 +89,23 @@ function resolveEffectiveMode(options) {
|
|
|
89
89
|
}
|
|
90
90
|
return "live";
|
|
91
91
|
}
|
|
92
|
-
function resolveSafeWorkingDir(workspacePath) {
|
|
92
|
+
function resolveSafeWorkingDir(workspacePath, artifactsDir) {
|
|
93
93
|
try {
|
|
94
|
-
if (workspacePath &&
|
|
95
|
-
|
|
94
|
+
if (workspacePath &&
|
|
95
|
+
fs.existsSync(workspacePath) &&
|
|
96
|
+
fs.statSync(workspacePath).isDirectory()) {
|
|
97
|
+
return { cwd: fs.realpathSync(workspacePath), workspaceExists: true };
|
|
96
98
|
}
|
|
97
99
|
}
|
|
98
100
|
catch {
|
|
99
|
-
// Fall through
|
|
101
|
+
// Fall through to isolated empty directory
|
|
100
102
|
}
|
|
101
|
-
|
|
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
|
+
};
|
|
102
109
|
}
|
|
103
110
|
function buildConversationTurnPayload(request) {
|
|
104
111
|
const lines = [];
|
|
@@ -117,14 +124,46 @@ function buildConversationTurnPayload(request) {
|
|
|
117
124
|
lines.push(`[Colleague (${request.guestName})]:`, request.prompt);
|
|
118
125
|
return lines.join("\n");
|
|
119
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
|
+
}
|
|
120
145
|
function parseStructuredJsonRecords(records) {
|
|
121
146
|
const replyParts = [];
|
|
122
147
|
const thinkingParts = [];
|
|
148
|
+
const observations = [];
|
|
123
149
|
let finalResult = null;
|
|
150
|
+
let hitMaxTurns = false;
|
|
151
|
+
let resultError = "";
|
|
124
152
|
for (const obj of records) {
|
|
125
153
|
const recType = typeof obj["type"] === "string" ? obj["type"] : "";
|
|
126
|
-
if (recType === "result"
|
|
127
|
-
|
|
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
|
+
}
|
|
128
167
|
}
|
|
129
168
|
else if (recType === "reasoning") {
|
|
130
169
|
for (const key of ["rawContent", "summary", "content"]) {
|
|
@@ -157,49 +196,283 @@ function parseStructuredJsonRecords(records) {
|
|
|
157
196
|
const bType = typeof b["type"] === "string" ? b["type"] : "";
|
|
158
197
|
if ((bType === "text" || bType === "output_text") &&
|
|
159
198
|
typeof b["text"] === "string") {
|
|
160
|
-
|
|
199
|
+
const textVal = b["text"].trim();
|
|
200
|
+
if (textVal)
|
|
201
|
+
replyParts.push(textVal);
|
|
161
202
|
}
|
|
162
203
|
else if ((bType === "thinking" || bType === "reasoning" || bType === "reasoning_text") &&
|
|
163
204
|
(typeof b["thinking"] === "string" || typeof b["text"] === "string")) {
|
|
164
205
|
thinkingParts.push(typeof b["thinking"] === "string" ? b["thinking"] : b["text"]);
|
|
165
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
|
+
}
|
|
166
213
|
}
|
|
167
214
|
}
|
|
168
215
|
}
|
|
169
|
-
else if (typeof msg["content"] === "string") {
|
|
170
|
-
replyParts.push(msg["content"]);
|
|
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
|
+
}
|
|
171
236
|
}
|
|
172
237
|
}
|
|
173
|
-
else if (!recType && typeof obj["result"] === "string") {
|
|
238
|
+
else if (!recType && typeof obj["result"] === "string" && obj["result"].trim()) {
|
|
174
239
|
finalResult = obj["result"].trim();
|
|
175
240
|
}
|
|
176
|
-
else if (!recType && typeof obj["content"] === "string") {
|
|
177
|
-
replyParts.push(obj["content"]);
|
|
241
|
+
else if (!recType && typeof obj["content"] === "string" && obj["content"].trim()) {
|
|
242
|
+
replyParts.push(obj["content"].trim());
|
|
178
243
|
}
|
|
179
244
|
}
|
|
245
|
+
const joinedReply = replyParts.join("\n\n").trim();
|
|
180
246
|
return {
|
|
181
|
-
reply: (finalResult
|
|
247
|
+
reply: (finalResult && finalResult.length > 0 ? finalResult : joinedReply).trim(),
|
|
182
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;
|
|
183
412
|
};
|
|
413
|
+
return { executedTools, onLine };
|
|
184
414
|
}
|
|
185
|
-
function
|
|
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) {
|
|
186
455
|
const trimmed = rawStdout.trim();
|
|
187
|
-
if (!trimmed)
|
|
188
|
-
return {
|
|
456
|
+
if (!trimmed) {
|
|
457
|
+
return {
|
|
458
|
+
reply: "",
|
|
459
|
+
thinking: "",
|
|
460
|
+
observations: [],
|
|
461
|
+
hitMaxTurns: false,
|
|
462
|
+
resultError: "",
|
|
463
|
+
};
|
|
464
|
+
}
|
|
189
465
|
// Handle single JSON object (`claude -p --output-format json`) OR JSON array (`codebuddy -p --output-format json`)
|
|
190
|
-
if (trimmed.startsWith("{")
|
|
466
|
+
if ((trimmed.startsWith("{") && !trimmed.includes("\n{")) ||
|
|
467
|
+
trimmed.startsWith("[")) {
|
|
191
468
|
try {
|
|
192
469
|
const parsed = JSON.parse(trimmed);
|
|
193
470
|
if (Array.isArray(parsed)) {
|
|
194
471
|
const objs = parsed.filter((item) => typeof item === "object" && item !== null);
|
|
195
|
-
|
|
196
|
-
if (res.reply)
|
|
197
|
-
return res;
|
|
472
|
+
return parseStructuredJsonRecords(objs);
|
|
198
473
|
}
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
if (res.reply)
|
|
202
|
-
return res;
|
|
474
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
475
|
+
return parseStructuredJsonRecords([parsed]);
|
|
203
476
|
}
|
|
204
477
|
}
|
|
205
478
|
catch {
|
|
@@ -221,10 +494,15 @@ function parseClaudeJsonOutput(rawStdout) {
|
|
|
221
494
|
// Ignore non-JSON log lines
|
|
222
495
|
}
|
|
223
496
|
}
|
|
224
|
-
|
|
497
|
+
if (ndjsonRecords.length > 0) {
|
|
498
|
+
return parseStructuredJsonRecords(ndjsonRecords);
|
|
499
|
+
}
|
|
225
500
|
return {
|
|
226
|
-
reply:
|
|
227
|
-
thinking:
|
|
501
|
+
reply: trimmed,
|
|
502
|
+
thinking: "",
|
|
503
|
+
observations: [],
|
|
504
|
+
hitMaxTurns: false,
|
|
505
|
+
resultError: "",
|
|
228
506
|
};
|
|
229
507
|
}
|
|
230
508
|
function parseCodexExecOutput(rawStdout, lastMsgFilePath) {
|
|
@@ -349,7 +627,9 @@ class BaseEngineAdapter {
|
|
|
349
627
|
return merged;
|
|
350
628
|
}
|
|
351
629
|
spawnAndCollect(params) {
|
|
352
|
-
const
|
|
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;
|
|
353
633
|
return new Promise((resolve, reject) => {
|
|
354
634
|
const child = spawn(params.target.command, [...params.target.prefixArgs, ...params.args], {
|
|
355
635
|
cwd: params.cwd,
|
|
@@ -359,9 +639,51 @@ class BaseEngineAdapter {
|
|
|
359
639
|
windowsHide: true,
|
|
360
640
|
});
|
|
361
641
|
let stdout = "";
|
|
642
|
+
let stdoutLineBuffer = "";
|
|
362
643
|
let stderr = "";
|
|
363
644
|
let timedOut = false;
|
|
645
|
+
let completedViaTerminalFrame = false;
|
|
364
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,
|
|
685
|
+
});
|
|
686
|
+
};
|
|
365
687
|
const killChild = () => {
|
|
366
688
|
if (!child.killed) {
|
|
367
689
|
try {
|
|
@@ -371,33 +693,93 @@ class BaseEngineAdapter {
|
|
|
371
693
|
// Ignore
|
|
372
694
|
}
|
|
373
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,
|
|
701
|
+
});
|
|
702
|
+
tk.unref();
|
|
703
|
+
}
|
|
704
|
+
catch {
|
|
705
|
+
// Ignore
|
|
706
|
+
}
|
|
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);
|
|
374
725
|
};
|
|
375
726
|
this.activeProcesses.set(params.shareId, killChild);
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
727
|
+
resetIdleTimer();
|
|
728
|
+
const totalTimer = setTimeout(() => {
|
|
729
|
+
if (!completedViaTerminalFrame) {
|
|
730
|
+
timedOut = true;
|
|
731
|
+
killChild();
|
|
732
|
+
}
|
|
733
|
+
}, maxTotalTimeoutMs);
|
|
380
734
|
child.stdout.on("data", (chunk) => {
|
|
381
|
-
|
|
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
|
+
}
|
|
382
768
|
});
|
|
383
769
|
child.stderr.on("data", (chunk) => {
|
|
384
770
|
stderr += chunk.toString("utf8");
|
|
771
|
+
resetIdleTimer();
|
|
385
772
|
});
|
|
386
773
|
child.on("error", (err) => {
|
|
387
|
-
clearTimeout(timer);
|
|
388
|
-
this.activeProcesses.delete(params.shareId);
|
|
389
774
|
if (!settled) {
|
|
390
775
|
settled = true;
|
|
776
|
+
clearAllTimers();
|
|
777
|
+
this.activeProcesses.delete(params.shareId);
|
|
391
778
|
reject(err);
|
|
392
779
|
}
|
|
393
780
|
});
|
|
394
781
|
child.on("close", (code) => {
|
|
395
|
-
|
|
396
|
-
this.activeProcesses.delete(params.shareId);
|
|
397
|
-
if (!settled) {
|
|
398
|
-
settled = true;
|
|
399
|
-
resolve({ code, stdout, stderr, timedOut });
|
|
400
|
-
}
|
|
782
|
+
finish(code);
|
|
401
783
|
});
|
|
402
784
|
if (params.stdinPayload !== undefined) {
|
|
403
785
|
child.stdin.write(params.stdinPayload, "utf8");
|
|
@@ -506,9 +888,10 @@ export class ClaudeCodeAdapter extends BaseEngineAdapter {
|
|
|
506
888
|
async executeLiveCliTurn(request, target) {
|
|
507
889
|
const { context } = request;
|
|
508
890
|
const artifactsDir = this.resolveArtifactsDir(context);
|
|
891
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
509
892
|
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
510
893
|
shareId: context.shareId,
|
|
511
|
-
workspacePath:
|
|
894
|
+
workspacePath: safeWs.cwd,
|
|
512
895
|
permissionTier: context.permissionTier,
|
|
513
896
|
writableGlobs: context.writableGlobs,
|
|
514
897
|
}, true);
|
|
@@ -522,13 +905,17 @@ export class ClaudeCodeAdapter extends BaseEngineAdapter {
|
|
|
522
905
|
const cliArgs = [
|
|
523
906
|
"-p",
|
|
524
907
|
"--output-format",
|
|
525
|
-
"json",
|
|
908
|
+
"stream-json",
|
|
909
|
+
"--verbose",
|
|
910
|
+
"--max-turns",
|
|
911
|
+
safeWs.workspaceExists ? "10" : "2",
|
|
526
912
|
"--strict-mcp-config",
|
|
527
913
|
"--mcp-config",
|
|
528
914
|
bundle.emptyMcpConfigPath,
|
|
529
915
|
"--settings",
|
|
530
916
|
bundle.claudeSettingsPath,
|
|
531
|
-
`--tools=${allowedTools}`,
|
|
917
|
+
`--tools=${safeWs.workspaceExists ? allowedTools : ""}`,
|
|
918
|
+
...(safeWs.workspaceExists ? [`--allowedTools=${allowedTools}`] : []),
|
|
532
919
|
"--permission-mode",
|
|
533
920
|
"dontAsk",
|
|
534
921
|
"--append-system-prompt-file",
|
|
@@ -543,17 +930,21 @@ export class ClaudeCodeAdapter extends BaseEngineAdapter {
|
|
|
543
930
|
const turnInput = usesNativeFork
|
|
544
931
|
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
545
932
|
: buildConversationTurnPayload(request);
|
|
933
|
+
const childEnv = this.buildBaseEnv(context, bundle.guardScriptPath);
|
|
934
|
+
const inspector = createClaudeStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
546
935
|
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
547
936
|
shareId: context.shareId,
|
|
548
937
|
target,
|
|
549
938
|
args: cliArgs,
|
|
550
|
-
cwd:
|
|
551
|
-
env:
|
|
939
|
+
cwd: safeWs.cwd,
|
|
940
|
+
env: childEnv,
|
|
552
941
|
stdinPayload: turnInput,
|
|
942
|
+
onStdoutLine: inspector.onLine,
|
|
553
943
|
});
|
|
554
944
|
if (code === 2) {
|
|
555
945
|
return {
|
|
556
946
|
blockedByGuard: true,
|
|
947
|
+
executedTools: inspector.executedTools,
|
|
557
948
|
guardInterception: {
|
|
558
949
|
ruleId: "SENSITIVE_FILE_ACCESS",
|
|
559
950
|
targetOrPattern: "claude PreToolUse Hook",
|
|
@@ -567,14 +958,68 @@ export class ClaudeCodeAdapter extends BaseEngineAdapter {
|
|
|
567
958
|
if (parsed.reply) {
|
|
568
959
|
return {
|
|
569
960
|
blockedByGuard: false,
|
|
961
|
+
executedTools: inspector.executedTools,
|
|
570
962
|
thinkingTrace: parsed.thinking ||
|
|
571
963
|
`[Claude Code Live CLI (exit=${String(code)}, fork=${String(usesNativeFork)})]`,
|
|
572
964
|
replyContent: parsed.reply,
|
|
573
965
|
};
|
|
574
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
|
+
}
|
|
575
1018
|
const diag = timedOut
|
|
576
1019
|
? "Claude Code CLI timed out waiting for upstream model response."
|
|
577
|
-
:
|
|
1020
|
+
: parsed.resultError ||
|
|
1021
|
+
stderr.trim() ||
|
|
1022
|
+
`Claude CLI exited with code ${String(code)}`;
|
|
578
1023
|
return {
|
|
579
1024
|
blockedByGuard: false,
|
|
580
1025
|
thinkingTrace: `[Claude Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
@@ -676,16 +1121,16 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
676
1121
|
async executeLiveCliTurn(request, target) {
|
|
677
1122
|
const { context } = request;
|
|
678
1123
|
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1124
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
679
1125
|
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
680
1126
|
shareId: context.shareId,
|
|
681
|
-
workspacePath:
|
|
1127
|
+
workspacePath: safeWs.cwd,
|
|
682
1128
|
permissionTier: context.permissionTier,
|
|
683
1129
|
writableGlobs: context.writableGlobs,
|
|
684
1130
|
}, true);
|
|
685
1131
|
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
686
1132
|
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
687
1133
|
const lastMsgFile = path.join(artifactsDir, `codex-last-${Date.now()}-${Math.random().toString(36).slice(2, 7)}.txt`);
|
|
688
|
-
const safeCwd = resolveSafeWorkingDir(context.workspacePath);
|
|
689
1134
|
// Strip private MCP servers via `-c mcp_servers={}` and enforce OS read-only sandbox + ephemeral non-persistence
|
|
690
1135
|
const cliArgs = usesNativeFork
|
|
691
1136
|
? [
|
|
@@ -694,6 +1139,8 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
694
1139
|
"-c",
|
|
695
1140
|
"stream_max_retries=1",
|
|
696
1141
|
"-c",
|
|
1142
|
+
'model_reasoning_effort="medium"',
|
|
1143
|
+
"-c",
|
|
697
1144
|
'sandbox_mode="read-only"',
|
|
698
1145
|
"exec",
|
|
699
1146
|
"fork",
|
|
@@ -710,6 +1157,8 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
710
1157
|
"mcp_servers={}",
|
|
711
1158
|
"-c",
|
|
712
1159
|
"stream_max_retries=1",
|
|
1160
|
+
"-c",
|
|
1161
|
+
'model_reasoning_effort="medium"',
|
|
713
1162
|
"exec",
|
|
714
1163
|
"--json",
|
|
715
1164
|
"--ephemeral",
|
|
@@ -717,7 +1166,7 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
717
1166
|
"read-only",
|
|
718
1167
|
"--skip-git-repo-check",
|
|
719
1168
|
"-C",
|
|
720
|
-
|
|
1169
|
+
safeWs.cwd,
|
|
721
1170
|
"-o",
|
|
722
1171
|
lastMsgFile,
|
|
723
1172
|
"-",
|
|
@@ -729,18 +1178,22 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
729
1178
|
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
730
1179
|
: buildConversationTurnPayload(request),
|
|
731
1180
|
].join("\n");
|
|
1181
|
+
const codexInspector = createCodexStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
732
1182
|
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
733
1183
|
shareId: context.shareId,
|
|
734
1184
|
target,
|
|
735
1185
|
args: cliArgs,
|
|
736
|
-
cwd:
|
|
1186
|
+
cwd: safeWs.cwd,
|
|
737
1187
|
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
738
1188
|
stdinPayload,
|
|
1189
|
+
completionGraceMs: 320,
|
|
1190
|
+
onStdoutLine: codexInspector.onLine,
|
|
739
1191
|
});
|
|
740
1192
|
const parsed = parseCodexExecOutput(stdout, lastMsgFile);
|
|
741
1193
|
if (parsed.reply) {
|
|
742
1194
|
return {
|
|
743
1195
|
blockedByGuard: false,
|
|
1196
|
+
executedTools: codexInspector.executedTools,
|
|
744
1197
|
thinkingTrace: parsed.thinking ||
|
|
745
1198
|
`[Codex Live CLI (exit=${String(code)}, sandbox=read-only, ephemeral=true)]`,
|
|
746
1199
|
replyContent: parsed.reply,
|
|
@@ -850,9 +1303,10 @@ export class OpenCodeAdapter extends BaseEngineAdapter {
|
|
|
850
1303
|
async executeLiveCliTurn(request, target) {
|
|
851
1304
|
const { context } = request;
|
|
852
1305
|
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1306
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
853
1307
|
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
854
1308
|
shareId: context.shareId,
|
|
855
|
-
workspacePath:
|
|
1309
|
+
workspacePath: safeWs.cwd,
|
|
856
1310
|
permissionTier: context.permissionTier,
|
|
857
1311
|
writableGlobs: context.writableGlobs,
|
|
858
1312
|
}, true);
|
|
@@ -889,20 +1343,23 @@ export class OpenCodeAdapter extends BaseEngineAdapter {
|
|
|
889
1343
|
webfetch: "deny",
|
|
890
1344
|
},
|
|
891
1345
|
});
|
|
1346
|
+
const ocInspector = createOpenCodeStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
892
1347
|
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
893
1348
|
shareId: context.shareId,
|
|
894
1349
|
target,
|
|
895
1350
|
args: cliArgs,
|
|
896
|
-
cwd:
|
|
1351
|
+
cwd: safeWs.cwd,
|
|
897
1352
|
env: {
|
|
898
1353
|
...this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
899
1354
|
OPENCODE_CONFIG_CONTENT: strictReadOnlyConfig,
|
|
900
1355
|
},
|
|
1356
|
+
onStdoutLine: ocInspector.onLine,
|
|
901
1357
|
});
|
|
902
1358
|
const parsed = parseOpenCodeJsonOutput(stdout);
|
|
903
1359
|
if (parsed.reply) {
|
|
904
1360
|
return {
|
|
905
1361
|
blockedByGuard: false,
|
|
1362
|
+
executedTools: ocInspector.executedTools,
|
|
906
1363
|
thinkingTrace: parsed.thinking ||
|
|
907
1364
|
`[OpenCode Live CLI (exit=${String(code)}, archived=true)]`,
|
|
908
1365
|
replyContent: parsed.reply,
|
|
@@ -978,9 +1435,10 @@ export class DshAdapter extends BaseEngineAdapter {
|
|
|
978
1435
|
async executeLiveCliTurn(request, target) {
|
|
979
1436
|
const { context } = request;
|
|
980
1437
|
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1438
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
981
1439
|
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
982
1440
|
shareId: context.shareId,
|
|
983
|
-
workspacePath:
|
|
1441
|
+
workspacePath: safeWs.cwd,
|
|
984
1442
|
permissionTier: context.permissionTier,
|
|
985
1443
|
writableGlobs: context.writableGlobs,
|
|
986
1444
|
}, true);
|
|
@@ -1002,7 +1460,7 @@ export class DshAdapter extends BaseEngineAdapter {
|
|
|
1002
1460
|
shareId: context.shareId,
|
|
1003
1461
|
target,
|
|
1004
1462
|
args: cliArgs,
|
|
1005
|
-
cwd:
|
|
1463
|
+
cwd: safeWs.cwd,
|
|
1006
1464
|
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
1007
1465
|
stdinPayload,
|
|
1008
1466
|
});
|
|
@@ -1069,9 +1527,10 @@ export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
|
1069
1527
|
async executeLiveCliTurn(request, target) {
|
|
1070
1528
|
const { context } = request;
|
|
1071
1529
|
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1530
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
1072
1531
|
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
1073
1532
|
shareId: context.shareId,
|
|
1074
|
-
workspacePath:
|
|
1533
|
+
workspacePath: safeWs.cwd,
|
|
1075
1534
|
permissionTier: context.permissionTier,
|
|
1076
1535
|
writableGlobs: context.writableGlobs,
|
|
1077
1536
|
}, true);
|
|
@@ -1079,37 +1538,56 @@ export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
|
1079
1538
|
const systemEnvelopeFile = path.join(artifactsDir, "cyf-cb-system-envelope.txt");
|
|
1080
1539
|
fs.writeFileSync(systemEnvelopeFile, systemPromptPayload, "utf8");
|
|
1081
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];
|
|
1082
1553
|
const cliArgs = [
|
|
1083
1554
|
"-p",
|
|
1084
1555
|
"--output-format",
|
|
1085
|
-
"json",
|
|
1556
|
+
"stream-json",
|
|
1557
|
+
"--verbose",
|
|
1558
|
+
"--max-turns",
|
|
1559
|
+
safeWs.workspaceExists ? "10" : "2",
|
|
1086
1560
|
"--strict-mcp-config",
|
|
1087
1561
|
"--mcp-config",
|
|
1088
1562
|
bundle.emptyMcpConfigPath,
|
|
1089
1563
|
"--no-session-persistence",
|
|
1090
1564
|
"--settings",
|
|
1091
1565
|
bundle.claudeSettingsPath,
|
|
1092
|
-
|
|
1566
|
+
`--tools=${safeWs.workspaceExists ? allowedTools : ""}`,
|
|
1567
|
+
...(safeWs.workspaceExists ? [`--allowedTools=${allowedTools}`] : []),
|
|
1093
1568
|
"--permission-mode",
|
|
1094
1569
|
"dontAsk",
|
|
1095
|
-
|
|
1096
|
-
systemEnvelopeFile,
|
|
1570
|
+
...promptFlagArgs,
|
|
1097
1571
|
...(usesNativeFork ? ["--resume", context.rawSessionId, "--fork-session"] : []),
|
|
1098
1572
|
];
|
|
1099
1573
|
const turnInput = usesNativeFork
|
|
1100
1574
|
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
1101
1575
|
: buildConversationTurnPayload(request);
|
|
1576
|
+
const childEnv = this.buildBaseEnv(context, bundle.guardScriptPath);
|
|
1577
|
+
const inspector = createClaudeStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
1102
1578
|
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
1103
1579
|
shareId: context.shareId,
|
|
1104
1580
|
target,
|
|
1105
1581
|
args: cliArgs,
|
|
1106
|
-
cwd:
|
|
1107
|
-
env:
|
|
1582
|
+
cwd: safeWs.cwd,
|
|
1583
|
+
env: childEnv,
|
|
1108
1584
|
stdinPayload: turnInput,
|
|
1585
|
+
onStdoutLine: inspector.onLine,
|
|
1109
1586
|
});
|
|
1110
1587
|
if (code === 2) {
|
|
1111
1588
|
return {
|
|
1112
1589
|
blockedByGuard: true,
|
|
1590
|
+
executedTools: inspector.executedTools,
|
|
1113
1591
|
guardInterception: {
|
|
1114
1592
|
ruleId: "SENSITIVE_FILE_ACCESS",
|
|
1115
1593
|
targetOrPattern: "codebuddy PreToolUse Hook",
|
|
@@ -1123,14 +1601,67 @@ export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
|
1123
1601
|
if (parsed.reply) {
|
|
1124
1602
|
return {
|
|
1125
1603
|
blockedByGuard: false,
|
|
1604
|
+
executedTools: inspector.executedTools,
|
|
1126
1605
|
thinkingTrace: parsed.thinking ||
|
|
1127
1606
|
`[CodeBuddy Live CLI (exit=${String(code)}, fork=${String(usesNativeFork)})]`,
|
|
1128
1607
|
replyContent: parsed.reply,
|
|
1129
1608
|
};
|
|
1130
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
|
+
}
|
|
1131
1660
|
const diag = timedOut
|
|
1132
1661
|
? "CodeBuddy CLI timed out waiting for model response."
|
|
1133
|
-
:
|
|
1662
|
+
: parsed.resultError ||
|
|
1663
|
+
stderr.trim() ||
|
|
1664
|
+
`CodeBuddy CLI exited with code ${String(code)}`;
|
|
1134
1665
|
return {
|
|
1135
1666
|
blockedByGuard: false,
|
|
1136
1667
|
thinkingTrace: `[CodeBuddy Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|