@cyfsh/adapters 0.3.0 → 0.3.2
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 +621 -77
- package/dist/adapters.js.map +1 -1
- package/dist/guard-generator.d.ts +1 -1
- package/dist/guard-generator.d.ts.map +1 -1
- package/dist/guard-generator.js +47 -20
- 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 +42 -17
- 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;
|
|
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;
|
|
183
450
|
};
|
|
451
|
+
return { executedTools, onLine };
|
|
184
452
|
}
|
|
185
|
-
|
|
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);
|
|
@@ -516,21 +899,28 @@ export class ClaudeCodeAdapter extends BaseEngineAdapter {
|
|
|
516
899
|
const systemEnvelopeFile = path.join(artifactsDir, "cyf-system-envelope.txt");
|
|
517
900
|
fs.writeFileSync(systemEnvelopeFile, systemPromptPayload, "utf8");
|
|
518
901
|
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
519
|
-
const
|
|
520
|
-
|
|
521
|
-
|
|
902
|
+
const isSelfOwner = context.permissionTier === "TIER_3_SELF_OWNER";
|
|
903
|
+
const allowedTools = isSelfOwner
|
|
904
|
+
? "Read,Glob,Grep,Edit,Write,Bash"
|
|
905
|
+
: context.permissionTier === "TIER_2_WORKTREE_SANDBOX"
|
|
906
|
+
? "Read,Glob,Grep,Edit,Write"
|
|
907
|
+
: "Read,Glob,Grep";
|
|
522
908
|
const cliArgs = [
|
|
523
909
|
"-p",
|
|
524
910
|
"--output-format",
|
|
525
|
-
"json",
|
|
911
|
+
"stream-json",
|
|
912
|
+
"--verbose",
|
|
913
|
+
"--max-turns",
|
|
914
|
+
safeWs.workspaceExists ? (isSelfOwner ? "20" : "10") : "2",
|
|
526
915
|
"--strict-mcp-config",
|
|
527
916
|
"--mcp-config",
|
|
528
917
|
bundle.emptyMcpConfigPath,
|
|
529
918
|
"--settings",
|
|
530
919
|
bundle.claudeSettingsPath,
|
|
531
|
-
`--tools=${allowedTools}`,
|
|
920
|
+
`--tools=${safeWs.workspaceExists ? allowedTools : ""}`,
|
|
921
|
+
...(safeWs.workspaceExists ? [`--allowedTools=${allowedTools}`] : []),
|
|
532
922
|
"--permission-mode",
|
|
533
|
-
"dontAsk",
|
|
923
|
+
isSelfOwner ? "acceptEdits" : "dontAsk",
|
|
534
924
|
"--append-system-prompt-file",
|
|
535
925
|
systemEnvelopeFile,
|
|
536
926
|
];
|
|
@@ -540,20 +930,25 @@ export class ClaudeCodeAdapter extends BaseEngineAdapter {
|
|
|
540
930
|
else {
|
|
541
931
|
cliArgs.push("--no-session-persistence");
|
|
542
932
|
}
|
|
933
|
+
const turnLabel = isSelfOwner ? `Owner (${request.guestName})` : `Colleague (${request.guestName})`;
|
|
543
934
|
const turnInput = usesNativeFork
|
|
544
|
-
? `[
|
|
935
|
+
? `[${turnLabel}]:\n${request.prompt}`
|
|
545
936
|
: buildConversationTurnPayload(request);
|
|
937
|
+
const childEnv = this.buildBaseEnv(context, bundle.guardScriptPath);
|
|
938
|
+
const inspector = createClaudeStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
546
939
|
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
547
940
|
shareId: context.shareId,
|
|
548
941
|
target,
|
|
549
942
|
args: cliArgs,
|
|
550
|
-
cwd:
|
|
551
|
-
env:
|
|
943
|
+
cwd: safeWs.cwd,
|
|
944
|
+
env: childEnv,
|
|
552
945
|
stdinPayload: turnInput,
|
|
946
|
+
onStdoutLine: inspector.onLine,
|
|
553
947
|
});
|
|
554
948
|
if (code === 2) {
|
|
555
949
|
return {
|
|
556
950
|
blockedByGuard: true,
|
|
951
|
+
executedTools: inspector.executedTools,
|
|
557
952
|
guardInterception: {
|
|
558
953
|
ruleId: "SENSITIVE_FILE_ACCESS",
|
|
559
954
|
targetOrPattern: "claude PreToolUse Hook",
|
|
@@ -567,14 +962,68 @@ export class ClaudeCodeAdapter extends BaseEngineAdapter {
|
|
|
567
962
|
if (parsed.reply) {
|
|
568
963
|
return {
|
|
569
964
|
blockedByGuard: false,
|
|
965
|
+
executedTools: inspector.executedTools,
|
|
570
966
|
thinkingTrace: parsed.thinking ||
|
|
571
967
|
`[Claude Code Live CLI (exit=${String(code)}, fork=${String(usesNativeFork)})]`,
|
|
572
968
|
replyContent: parsed.reply,
|
|
573
969
|
};
|
|
574
970
|
}
|
|
971
|
+
// If multi-turn workspace inspection hit max-turns or timed out after gathering observations, run a 1-turn synthesis pass
|
|
972
|
+
if ((parsed.hitMaxTurns || timedOut) &&
|
|
973
|
+
(parsed.observations.length > 0 || parsed.thinking.length > 0)) {
|
|
974
|
+
request.onStreamEvent?.({ type: "synthesizing" });
|
|
975
|
+
const synthInspector = createClaudeStreamLineInspector(safeWs.cwd);
|
|
976
|
+
const synthesisInput = [
|
|
977
|
+
turnInput,
|
|
978
|
+
"",
|
|
979
|
+
"<workspace_inspection_notes>",
|
|
980
|
+
...parsed.observations.slice(-10),
|
|
981
|
+
...(parsed.thinking ? [`[Prior Reasoning]:\n${parsed.thinking.slice(-2400)}`] : []),
|
|
982
|
+
"</workspace_inspection_notes>",
|
|
983
|
+
"",
|
|
984
|
+
"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.",
|
|
985
|
+
].join("\n");
|
|
986
|
+
const synthRes = await this.spawnAndCollect({
|
|
987
|
+
shareId: context.shareId,
|
|
988
|
+
target,
|
|
989
|
+
args: [
|
|
990
|
+
"-p",
|
|
991
|
+
"--output-format",
|
|
992
|
+
"stream-json",
|
|
993
|
+
"--verbose",
|
|
994
|
+
"--max-turns",
|
|
995
|
+
"1",
|
|
996
|
+
"--strict-mcp-config",
|
|
997
|
+
"--mcp-config",
|
|
998
|
+
bundle.emptyMcpConfigPath,
|
|
999
|
+
"--tools=",
|
|
1000
|
+
"--no-session-persistence",
|
|
1001
|
+
"--append-system-prompt-file",
|
|
1002
|
+
systemEnvelopeFile,
|
|
1003
|
+
],
|
|
1004
|
+
cwd: safeWs.cwd,
|
|
1005
|
+
env: childEnv,
|
|
1006
|
+
stdinPayload: synthesisInput,
|
|
1007
|
+
idleTimeoutMs: 45_000,
|
|
1008
|
+
maxTotalTimeoutMs: 60_000,
|
|
1009
|
+
onStdoutLine: synthInspector.onLine,
|
|
1010
|
+
});
|
|
1011
|
+
const synthParsed = parseClaudeJsonOutput(synthRes.stdout);
|
|
1012
|
+
if (synthParsed.reply) {
|
|
1013
|
+
return {
|
|
1014
|
+
blockedByGuard: false,
|
|
1015
|
+
executedTools: inspector.executedTools,
|
|
1016
|
+
thinkingTrace: [parsed.thinking, synthParsed.thinking].filter(Boolean).join("\n") ||
|
|
1017
|
+
`[Claude Code Synthesized After Inspection]`,
|
|
1018
|
+
replyContent: synthParsed.reply,
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
575
1022
|
const diag = timedOut
|
|
576
1023
|
? "Claude Code CLI timed out waiting for upstream model response."
|
|
577
|
-
:
|
|
1024
|
+
: parsed.resultError ||
|
|
1025
|
+
stderr.trim() ||
|
|
1026
|
+
`Claude CLI exited with code ${String(code)}`;
|
|
578
1027
|
return {
|
|
579
1028
|
blockedByGuard: false,
|
|
580
1029
|
thinkingTrace: `[Claude Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|
|
@@ -676,17 +1125,19 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
676
1125
|
async executeLiveCliTurn(request, target) {
|
|
677
1126
|
const { context } = request;
|
|
678
1127
|
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1128
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
679
1129
|
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
680
1130
|
shareId: context.shareId,
|
|
681
|
-
workspacePath:
|
|
1131
|
+
workspacePath: safeWs.cwd,
|
|
682
1132
|
permissionTier: context.permissionTier,
|
|
683
1133
|
writableGlobs: context.writableGlobs,
|
|
684
1134
|
}, true);
|
|
685
1135
|
const systemPromptPayload = buildRuntimeSystemEnvelope(context);
|
|
686
1136
|
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
1137
|
+
const isSelfOwner = context.permissionTier === "TIER_3_SELF_OWNER";
|
|
1138
|
+
const codexSandboxMode = isSelfOwner ? "workspace-write" : "read-only";
|
|
687
1139
|
const lastMsgFile = path.join(artifactsDir, `codex-last-${Date.now()}-${Math.random().toString(36).slice(2, 7)}.txt`);
|
|
688
|
-
|
|
689
|
-
// Strip private MCP servers via `-c mcp_servers={}` and enforce OS read-only sandbox + ephemeral non-persistence
|
|
1140
|
+
// Strip private MCP servers via `-c mcp_servers={}` and enforce OS sandbox + ephemeral non-persistence
|
|
690
1141
|
const cliArgs = usesNativeFork
|
|
691
1142
|
? [
|
|
692
1143
|
"-c",
|
|
@@ -694,7 +1145,9 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
694
1145
|
"-c",
|
|
695
1146
|
"stream_max_retries=1",
|
|
696
1147
|
"-c",
|
|
697
|
-
'
|
|
1148
|
+
'model_reasoning_effort="medium"',
|
|
1149
|
+
"-c",
|
|
1150
|
+
`sandbox_mode="${codexSandboxMode}"`,
|
|
698
1151
|
"exec",
|
|
699
1152
|
"fork",
|
|
700
1153
|
context.rawSessionId,
|
|
@@ -710,14 +1163,16 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
710
1163
|
"mcp_servers={}",
|
|
711
1164
|
"-c",
|
|
712
1165
|
"stream_max_retries=1",
|
|
1166
|
+
"-c",
|
|
1167
|
+
'model_reasoning_effort="medium"',
|
|
713
1168
|
"exec",
|
|
714
1169
|
"--json",
|
|
715
1170
|
"--ephemeral",
|
|
716
1171
|
"--sandbox",
|
|
717
|
-
|
|
1172
|
+
codexSandboxMode,
|
|
718
1173
|
"--skip-git-repo-check",
|
|
719
1174
|
"-C",
|
|
720
|
-
|
|
1175
|
+
safeWs.cwd,
|
|
721
1176
|
"-o",
|
|
722
1177
|
lastMsgFile,
|
|
723
1178
|
"-",
|
|
@@ -729,18 +1184,22 @@ export class CodexAdapter extends BaseEngineAdapter {
|
|
|
729
1184
|
? `[Colleague (${request.guestName})]:\n${request.prompt}`
|
|
730
1185
|
: buildConversationTurnPayload(request),
|
|
731
1186
|
].join("\n");
|
|
1187
|
+
const codexInspector = createCodexStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
732
1188
|
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
733
1189
|
shareId: context.shareId,
|
|
734
1190
|
target,
|
|
735
1191
|
args: cliArgs,
|
|
736
|
-
cwd:
|
|
1192
|
+
cwd: safeWs.cwd,
|
|
737
1193
|
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
738
1194
|
stdinPayload,
|
|
1195
|
+
completionGraceMs: 320,
|
|
1196
|
+
onStdoutLine: codexInspector.onLine,
|
|
739
1197
|
});
|
|
740
1198
|
const parsed = parseCodexExecOutput(stdout, lastMsgFile);
|
|
741
1199
|
if (parsed.reply) {
|
|
742
1200
|
return {
|
|
743
1201
|
blockedByGuard: false,
|
|
1202
|
+
executedTools: codexInspector.executedTools,
|
|
744
1203
|
thinkingTrace: parsed.thinking ||
|
|
745
1204
|
`[Codex Live CLI (exit=${String(code)}, sandbox=read-only, ephemeral=true)]`,
|
|
746
1205
|
replyContent: parsed.reply,
|
|
@@ -850,9 +1309,10 @@ export class OpenCodeAdapter extends BaseEngineAdapter {
|
|
|
850
1309
|
async executeLiveCliTurn(request, target) {
|
|
851
1310
|
const { context } = request;
|
|
852
1311
|
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1312
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
853
1313
|
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
854
1314
|
shareId: context.shareId,
|
|
855
|
-
workspacePath:
|
|
1315
|
+
workspacePath: safeWs.cwd,
|
|
856
1316
|
permissionTier: context.permissionTier,
|
|
857
1317
|
writableGlobs: context.writableGlobs,
|
|
858
1318
|
}, true);
|
|
@@ -881,28 +1341,34 @@ export class OpenCodeAdapter extends BaseEngineAdapter {
|
|
|
881
1341
|
else {
|
|
882
1342
|
cliArgs.push(fullPrompt);
|
|
883
1343
|
}
|
|
1344
|
+
const isSelfOwner = context.permissionTier === "TIER_3_SELF_OWNER";
|
|
884
1345
|
const strictReadOnlyConfig = JSON.stringify({
|
|
885
1346
|
mcp: {},
|
|
886
1347
|
permission: {
|
|
887
|
-
bash: "deny",
|
|
888
|
-
edit: context.permissionTier === "TIER_2_WORKTREE_SANDBOX"
|
|
889
|
-
|
|
1348
|
+
bash: isSelfOwner ? "allow" : "deny",
|
|
1349
|
+
edit: isSelfOwner || context.permissionTier === "TIER_2_WORKTREE_SANDBOX"
|
|
1350
|
+
? "allow"
|
|
1351
|
+
: "deny",
|
|
1352
|
+
webfetch: isSelfOwner ? "allow" : "deny",
|
|
890
1353
|
},
|
|
891
1354
|
});
|
|
1355
|
+
const ocInspector = createOpenCodeStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
892
1356
|
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
893
1357
|
shareId: context.shareId,
|
|
894
1358
|
target,
|
|
895
1359
|
args: cliArgs,
|
|
896
|
-
cwd:
|
|
1360
|
+
cwd: safeWs.cwd,
|
|
897
1361
|
env: {
|
|
898
1362
|
...this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
899
1363
|
OPENCODE_CONFIG_CONTENT: strictReadOnlyConfig,
|
|
900
1364
|
},
|
|
1365
|
+
onStdoutLine: ocInspector.onLine,
|
|
901
1366
|
});
|
|
902
1367
|
const parsed = parseOpenCodeJsonOutput(stdout);
|
|
903
1368
|
if (parsed.reply) {
|
|
904
1369
|
return {
|
|
905
1370
|
blockedByGuard: false,
|
|
1371
|
+
executedTools: ocInspector.executedTools,
|
|
906
1372
|
thinkingTrace: parsed.thinking ||
|
|
907
1373
|
`[OpenCode Live CLI (exit=${String(code)}, archived=true)]`,
|
|
908
1374
|
replyContent: parsed.reply,
|
|
@@ -978,9 +1444,10 @@ export class DshAdapter extends BaseEngineAdapter {
|
|
|
978
1444
|
async executeLiveCliTurn(request, target) {
|
|
979
1445
|
const { context } = request;
|
|
980
1446
|
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1447
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
981
1448
|
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
982
1449
|
shareId: context.shareId,
|
|
983
|
-
workspacePath:
|
|
1450
|
+
workspacePath: safeWs.cwd,
|
|
984
1451
|
permissionTier: context.permissionTier,
|
|
985
1452
|
writableGlobs: context.writableGlobs,
|
|
986
1453
|
}, true);
|
|
@@ -1002,7 +1469,7 @@ export class DshAdapter extends BaseEngineAdapter {
|
|
|
1002
1469
|
shareId: context.shareId,
|
|
1003
1470
|
target,
|
|
1004
1471
|
args: cliArgs,
|
|
1005
|
-
cwd:
|
|
1472
|
+
cwd: safeWs.cwd,
|
|
1006
1473
|
env: this.buildBaseEnv(context, bundle.guardScriptPath),
|
|
1007
1474
|
stdinPayload,
|
|
1008
1475
|
});
|
|
@@ -1069,9 +1536,10 @@ export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
|
1069
1536
|
async executeLiveCliTurn(request, target) {
|
|
1070
1537
|
const { context } = request;
|
|
1071
1538
|
const artifactsDir = this.resolveArtifactsDir(context);
|
|
1539
|
+
const safeWs = resolveSafeWorkingDir(context.workspacePath, artifactsDir);
|
|
1072
1540
|
const bundle = buildGuardArtifactBundle(artifactsDir, {
|
|
1073
1541
|
shareId: context.shareId,
|
|
1074
|
-
workspacePath:
|
|
1542
|
+
workspacePath: safeWs.cwd,
|
|
1075
1543
|
permissionTier: context.permissionTier,
|
|
1076
1544
|
writableGlobs: context.writableGlobs,
|
|
1077
1545
|
}, true);
|
|
@@ -1079,37 +1547,60 @@ export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
|
1079
1547
|
const systemEnvelopeFile = path.join(artifactsDir, "cyf-cb-system-envelope.txt");
|
|
1080
1548
|
fs.writeFileSync(systemEnvelopeFile, systemPromptPayload, "utf8");
|
|
1081
1549
|
const usesNativeFork = context.contextMode === "MODE_C_FULL_FORK";
|
|
1550
|
+
const isSelfOwner = context.permissionTier === "TIER_3_SELF_OWNER";
|
|
1551
|
+
const allowedTools = isSelfOwner
|
|
1552
|
+
? "Read,Glob,Grep,Edit,Write,Bash"
|
|
1553
|
+
: context.permissionTier === "TIER_2_WORKTREE_SANDBOX"
|
|
1554
|
+
? "Read,Glob,Grep,Edit,Write"
|
|
1555
|
+
: "Read,Glob,Grep";
|
|
1556
|
+
// When workspace files exist, use `--append-system-prompt` so CodeBuddy retains native tool schemas;
|
|
1557
|
+
// when workspace does not exist (`--tools=""`), use `--system-prompt-file` so CodeBuddy doesn't hallucinate `<tool_calls>` XML!
|
|
1558
|
+
const effectiveEnvelope = safeWs.workspaceExists
|
|
1559
|
+
? systemPromptPayload
|
|
1560
|
+
: `${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.`;
|
|
1561
|
+
fs.writeFileSync(systemEnvelopeFile, effectiveEnvelope, "utf8");
|
|
1562
|
+
const promptFlagArgs = safeWs.workspaceExists && systemPromptPayload.length <= 6000
|
|
1563
|
+
? ["--append-system-prompt", systemPromptPayload]
|
|
1564
|
+
: ["--system-prompt-file", systemEnvelopeFile];
|
|
1082
1565
|
const cliArgs = [
|
|
1083
1566
|
"-p",
|
|
1084
1567
|
"--output-format",
|
|
1085
|
-
"json",
|
|
1568
|
+
"stream-json",
|
|
1569
|
+
"--verbose",
|
|
1570
|
+
"--max-turns",
|
|
1571
|
+
safeWs.workspaceExists ? (isSelfOwner ? "20" : "10") : "2",
|
|
1086
1572
|
"--strict-mcp-config",
|
|
1087
1573
|
"--mcp-config",
|
|
1088
1574
|
bundle.emptyMcpConfigPath,
|
|
1089
1575
|
"--no-session-persistence",
|
|
1090
1576
|
"--settings",
|
|
1091
1577
|
bundle.claudeSettingsPath,
|
|
1092
|
-
|
|
1578
|
+
`--tools=${safeWs.workspaceExists ? allowedTools : ""}`,
|
|
1579
|
+
...(safeWs.workspaceExists ? [`--allowedTools=${allowedTools}`] : []),
|
|
1093
1580
|
"--permission-mode",
|
|
1094
|
-
"dontAsk",
|
|
1095
|
-
|
|
1096
|
-
systemEnvelopeFile,
|
|
1581
|
+
isSelfOwner ? "acceptEdits" : "dontAsk",
|
|
1582
|
+
...promptFlagArgs,
|
|
1097
1583
|
...(usesNativeFork ? ["--resume", context.rawSessionId, "--fork-session"] : []),
|
|
1098
1584
|
];
|
|
1585
|
+
const turnLabel = isSelfOwner ? `Owner (${request.guestName})` : `Colleague (${request.guestName})`;
|
|
1099
1586
|
const turnInput = usesNativeFork
|
|
1100
|
-
? `[
|
|
1587
|
+
? `[${turnLabel}]:\n${request.prompt}`
|
|
1101
1588
|
: buildConversationTurnPayload(request);
|
|
1589
|
+
const childEnv = this.buildBaseEnv(context, bundle.guardScriptPath);
|
|
1590
|
+
const inspector = createClaudeStreamLineInspector(safeWs.cwd, request.onStreamEvent);
|
|
1102
1591
|
const { code, stdout, stderr, timedOut } = await this.spawnAndCollect({
|
|
1103
1592
|
shareId: context.shareId,
|
|
1104
1593
|
target,
|
|
1105
1594
|
args: cliArgs,
|
|
1106
|
-
cwd:
|
|
1107
|
-
env:
|
|
1595
|
+
cwd: safeWs.cwd,
|
|
1596
|
+
env: childEnv,
|
|
1108
1597
|
stdinPayload: turnInput,
|
|
1598
|
+
onStdoutLine: inspector.onLine,
|
|
1109
1599
|
});
|
|
1110
1600
|
if (code === 2) {
|
|
1111
1601
|
return {
|
|
1112
1602
|
blockedByGuard: true,
|
|
1603
|
+
executedTools: inspector.executedTools,
|
|
1113
1604
|
guardInterception: {
|
|
1114
1605
|
ruleId: "SENSITIVE_FILE_ACCESS",
|
|
1115
1606
|
targetOrPattern: "codebuddy PreToolUse Hook",
|
|
@@ -1123,14 +1614,67 @@ export class CodeBuddyAdapter extends BaseEngineAdapter {
|
|
|
1123
1614
|
if (parsed.reply) {
|
|
1124
1615
|
return {
|
|
1125
1616
|
blockedByGuard: false,
|
|
1617
|
+
executedTools: inspector.executedTools,
|
|
1126
1618
|
thinkingTrace: parsed.thinking ||
|
|
1127
1619
|
`[CodeBuddy Live CLI (exit=${String(code)}, fork=${String(usesNativeFork)})]`,
|
|
1128
1620
|
replyContent: parsed.reply,
|
|
1129
1621
|
};
|
|
1130
1622
|
}
|
|
1623
|
+
// If multi-turn workspace inspection hit max-turns or timed out after gathering observations, run a 1-turn synthesis pass
|
|
1624
|
+
if ((parsed.hitMaxTurns || timedOut) &&
|
|
1625
|
+
(parsed.observations.length > 0 || parsed.thinking.length > 0)) {
|
|
1626
|
+
request.onStreamEvent?.({ type: "synthesizing" });
|
|
1627
|
+
const synthInspector = createClaudeStreamLineInspector(safeWs.cwd);
|
|
1628
|
+
const synthesisInput = [
|
|
1629
|
+
turnInput,
|
|
1630
|
+
"",
|
|
1631
|
+
"<workspace_inspection_notes>",
|
|
1632
|
+
...parsed.observations.slice(-10),
|
|
1633
|
+
...(parsed.thinking ? [`[Prior Reasoning]:\n${parsed.thinking.slice(-2400)}`] : []),
|
|
1634
|
+
"</workspace_inspection_notes>",
|
|
1635
|
+
"",
|
|
1636
|
+
"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.",
|
|
1637
|
+
].join("\n");
|
|
1638
|
+
const synthRes = await this.spawnAndCollect({
|
|
1639
|
+
shareId: context.shareId,
|
|
1640
|
+
target,
|
|
1641
|
+
args: [
|
|
1642
|
+
"-p",
|
|
1643
|
+
"--output-format",
|
|
1644
|
+
"stream-json",
|
|
1645
|
+
"--verbose",
|
|
1646
|
+
"--max-turns",
|
|
1647
|
+
"1",
|
|
1648
|
+
"--strict-mcp-config",
|
|
1649
|
+
"--mcp-config",
|
|
1650
|
+
bundle.emptyMcpConfigPath,
|
|
1651
|
+
"--no-session-persistence",
|
|
1652
|
+
"--tools=",
|
|
1653
|
+
...promptFlagArgs,
|
|
1654
|
+
],
|
|
1655
|
+
cwd: safeWs.cwd,
|
|
1656
|
+
env: childEnv,
|
|
1657
|
+
stdinPayload: synthesisInput,
|
|
1658
|
+
idleTimeoutMs: 45_000,
|
|
1659
|
+
maxTotalTimeoutMs: 60_000,
|
|
1660
|
+
onStdoutLine: synthInspector.onLine,
|
|
1661
|
+
});
|
|
1662
|
+
const synthParsed = parseClaudeJsonOutput(synthRes.stdout);
|
|
1663
|
+
if (synthParsed.reply) {
|
|
1664
|
+
return {
|
|
1665
|
+
blockedByGuard: false,
|
|
1666
|
+
executedTools: inspector.executedTools,
|
|
1667
|
+
thinkingTrace: [parsed.thinking, synthParsed.thinking].filter(Boolean).join("\n") ||
|
|
1668
|
+
`[CodeBuddy Synthesized After Inspection]`,
|
|
1669
|
+
replyContent: synthParsed.reply,
|
|
1670
|
+
};
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1131
1673
|
const diag = timedOut
|
|
1132
1674
|
? "CodeBuddy CLI timed out waiting for model response."
|
|
1133
|
-
:
|
|
1675
|
+
: parsed.resultError ||
|
|
1676
|
+
stderr.trim() ||
|
|
1677
|
+
`CodeBuddy CLI exited with code ${String(code)}`;
|
|
1134
1678
|
return {
|
|
1135
1679
|
blockedByGuard: false,
|
|
1136
1680
|
thinkingTrace: `[CodeBuddy Live CLI Diagnostic (exit=${String(code)})] ${diag}`,
|