@xzzpig/pi-subagents 0.25.0 → 0.25.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/CHANGELOG.md +186 -327
- package/FORK-CHANGELOG.md +456 -0
- package/README.md +5 -0
- package/bundle/{chunk-YWXILP5N.js → chunk-6F3YET5B.js} +3 -1
- package/bundle/{chunk-IJWITCC6.js → chunk-6FREVFTI.js} +1 -1
- package/bundle/{chunk-OSVXFWPG.js → chunk-E3EQ7USM.js} +1 -1
- package/bundle/{chunk-IKFKH5EL.js → chunk-FQPV4O6C.js} +25 -189
- package/bundle/{chunk-IUDEI6FJ.js → chunk-MMJQMPOK.js} +37 -0
- package/bundle/{chunk-KCJFGKVK.js → chunk-MQ5X2OJ2.js} +6 -6
- package/bundle/{chunk-6MNRKUHY.js → chunk-VRG6TEPW.js} +1 -1
- package/bundle/{chunk-5YEOWNSD.js → chunk-YDZFAQAV.js} +307 -273
- package/bundle/index.js +1 -1
- package/node_modules/@xzzpig/pi-components/CHANGELOG.md +4 -0
- package/node_modules/@xzzpig/pi-components/README.md +22 -0
- package/node_modules/@xzzpig/pi-components/dist/src/diff.d.ts +74 -0
- package/node_modules/@xzzpig/pi-components/dist/src/diff.js +355 -0
- package/node_modules/@xzzpig/pi-components/package.json +4 -0
- package/package.json +2 -1
- package/src/runs/foreground/execution.js +21 -69
- package/src/runs/foreground/fork-tool-result-handler.d.ts +60 -0
- package/src/runs/foreground/fork-tool-result-handler.js +83 -0
- package/src/shared/fleet-transcript-reader.d.ts +13 -0
- package/src/shared/fleet-transcript-reader.js +43 -0
- package/src/tui/fleet-native-transcript.js +1 -1
- package/src/tui/fleet-transcript.d.ts +1 -57
- package/src/tui/fleet-transcript.js +4 -370
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fork-only tool-result handler for a foreground subagent run.
|
|
3
|
+
*
|
|
4
|
+
* Why this file exists: upstream `execution.ts` has no `handleToolResult`; the
|
|
5
|
+
* fork added ~60 lines of tool-result bookkeeping (budget blocking, mutating
|
|
6
|
+
* failure escalation, supervisor progress publication) inside the run closure.
|
|
7
|
+
* It only reads/writes state the run already owns, so the handler lives here and
|
|
8
|
+
* the upstream run keeps one factory call.
|
|
9
|
+
*
|
|
10
|
+
* `handledToolResultIds` is bounded so a long run cannot grow it without limit;
|
|
11
|
+
* the oldest id is evicted first, which only risks re-processing results the
|
|
12
|
+
* child itself re-sends, never dropping a live one.
|
|
13
|
+
*/
|
|
14
|
+
import { extractTextFromContent } from "../../shared/utils.js";
|
|
15
|
+
import { didMutatingToolFail, recordMutatingFailure, resetMutatingFailureState, shouldEscalateMutatingFailures, summarizeRecentMutatingFailures, } from "../shared/long-running-guard.js";
|
|
16
|
+
import { isToolBudgetBlockedMessage, toolBudgetState } from "../shared/tool-budget.js";
|
|
17
|
+
const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
|
|
18
|
+
export function createToolResultHandler(deps) {
|
|
19
|
+
const { result, progress, options, agentName, handledToolResultIds, pendingToolResultsByCallId, pendingToolState, mutatingFailures, mutatingFailureWindowMs, controlConfig, appendRecentOutput, fireUpdate, emitNeedsAttention, } = deps;
|
|
20
|
+
return (message, completion, now) => {
|
|
21
|
+
const rawCallId = completion.toolCallId ?? message.toolCallId;
|
|
22
|
+
const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
|
|
23
|
+
if (callId) {
|
|
24
|
+
if (handledToolResultIds.has(callId))
|
|
25
|
+
return;
|
|
26
|
+
if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
|
|
27
|
+
const oldest = handledToolResultIds.values().next().value;
|
|
28
|
+
if (typeof oldest === "string")
|
|
29
|
+
handledToolResultIds.delete(oldest);
|
|
30
|
+
}
|
|
31
|
+
handledToolResultIds.add(callId);
|
|
32
|
+
}
|
|
33
|
+
result.messages.push(message);
|
|
34
|
+
const resultText = extractTextFromContent(message.content);
|
|
35
|
+
const keyedSnapshot = callId ? pendingToolResultsByCallId.get(callId) : undefined;
|
|
36
|
+
if (callId && keyedSnapshot)
|
|
37
|
+
pendingToolResultsByCallId.delete(callId);
|
|
38
|
+
const toolSnapshot = keyedSnapshot ?? pendingToolState.current;
|
|
39
|
+
if (!keyedSnapshot || pendingToolState.current === keyedSnapshot)
|
|
40
|
+
pendingToolState.current = undefined;
|
|
41
|
+
// The result event's own tool name is authoritative; the snapshot is a fallback.
|
|
42
|
+
const resultToolName = completion.toolName ?? message.toolName;
|
|
43
|
+
const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0
|
|
44
|
+
? resultToolName
|
|
45
|
+
: undefined) ?? toolSnapshot?.tool;
|
|
46
|
+
const budgetBlocked = Boolean(options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool));
|
|
47
|
+
if (options.toolBudget && budgetBlocked) {
|
|
48
|
+
result.toolBudgetBlocked = true;
|
|
49
|
+
result.toolBudget = toolBudgetState(options.toolBudget, Math.max(progress.toolCount, options.toolBudget.hard + 1), blockedTool);
|
|
50
|
+
}
|
|
51
|
+
appendRecentOutput(progress, resultText.split("\n").slice(-10));
|
|
52
|
+
// Pi 1.2+: a successful contact_supervisor progress_update call carries
|
|
53
|
+
// its text back through the result message. Publish the matching
|
|
54
|
+
// snapshot's text so the widget shows the latest successful update.
|
|
55
|
+
const messageToolName = message.toolName;
|
|
56
|
+
if (message.isError !== true && messageToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
|
|
57
|
+
progress.progressText = toolSnapshot.progressText;
|
|
58
|
+
progress.progressUpdatedAt = now;
|
|
59
|
+
}
|
|
60
|
+
if (toolSnapshot?.mutates && !budgetBlocked && message.role === "toolResult" && didMutatingToolFail(message)) {
|
|
61
|
+
recordMutatingFailure(mutatingFailures, {
|
|
62
|
+
tool: toolSnapshot.tool,
|
|
63
|
+
path: toolSnapshot.path,
|
|
64
|
+
error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
|
|
65
|
+
ts: now,
|
|
66
|
+
}, mutatingFailureWindowMs);
|
|
67
|
+
if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
|
|
68
|
+
emitNeedsAttention(now, {
|
|
69
|
+
message: `${agentName} needs attention after repeated mutating tool failures`,
|
|
70
|
+
reason: "tool_failures",
|
|
71
|
+
currentTool: toolSnapshot.tool,
|
|
72
|
+
currentPath: toolSnapshot.path,
|
|
73
|
+
currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
|
|
74
|
+
recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
else if (toolSnapshot?.mutates) {
|
|
79
|
+
resetMutatingFailureState(mutatingFailures);
|
|
80
|
+
}
|
|
81
|
+
fireUpdate();
|
|
82
|
+
};
|
|
83
|
+
}
|
|
@@ -49,3 +49,16 @@ export interface FleetTranscriptReadOptions {
|
|
|
49
49
|
export declare function objectValue(value: unknown): Record<string, unknown> | undefined;
|
|
50
50
|
export declare function safeTranscriptEvent(event: FleetTranscriptEvent): FleetTranscriptEvent;
|
|
51
51
|
export declare function readFleetTranscript(filePath: string, options: FleetTranscriptReadOptions): FleetTranscript;
|
|
52
|
+
export interface TranscriptRecordRead {
|
|
53
|
+
readFailed?: true;
|
|
54
|
+
records: Array<Record<string, unknown>>;
|
|
55
|
+
truncated: boolean;
|
|
56
|
+
warning?: string;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Shared trusted-root-guarded tail reader that returns raw parsed JSONL
|
|
60
|
+
* records instead of fleet events. Both the legacy rail renderer and the
|
|
61
|
+
* native-component renderer ingest through this single validation path, so
|
|
62
|
+
* symlink refusal and path-escape rejection cannot diverge between them.
|
|
63
|
+
*/
|
|
64
|
+
export declare function readTranscriptRecords(filePath: string, options: FleetTranscriptReadOptions): TranscriptRecordRead;
|
|
@@ -331,3 +331,46 @@ export function readFleetTranscript(filePath, options) {
|
|
|
331
331
|
...(warnings.length ? { warning: safeDisplayText(warnings.join(" ")) } : {}),
|
|
332
332
|
};
|
|
333
333
|
}
|
|
334
|
+
/**
|
|
335
|
+
* Shared trusted-root-guarded tail reader that returns raw parsed JSONL
|
|
336
|
+
* records instead of fleet events. Both the legacy rail renderer and the
|
|
337
|
+
* native-component renderer ingest through this single validation path, so
|
|
338
|
+
* symlink refusal and path-escape rejection cannot diverge between them.
|
|
339
|
+
*/
|
|
340
|
+
export function readTranscriptRecords(filePath, options) {
|
|
341
|
+
const validated = validateTranscriptPath(filePath, options.trustedRoots);
|
|
342
|
+
if (!validated.resolvedPath) {
|
|
343
|
+
return { records: [], truncated: false, readFailed: true, ...(validated.warning ? { warning: safeDisplayText(validated.warning) } : {}) };
|
|
344
|
+
}
|
|
345
|
+
const maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS);
|
|
346
|
+
const tail = readTailLines(validated.resolvedPath, Math.max(1024, options.maxBytes ?? DEFAULT_MAX_BYTES));
|
|
347
|
+
const selected = tail.lines.slice(-maxRecords);
|
|
348
|
+
const records = [];
|
|
349
|
+
let malformed = 0;
|
|
350
|
+
for (const line of selected) {
|
|
351
|
+
if (!line.trim())
|
|
352
|
+
continue;
|
|
353
|
+
try {
|
|
354
|
+
const parsed = JSON.parse(line);
|
|
355
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
356
|
+
records.push(parsed);
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
malformed++;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
malformed++;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
const warnings = [
|
|
367
|
+
tail.warning,
|
|
368
|
+
malformed > 0 ? `Skipped ${malformed} malformed transcript record${malformed === 1 ? "" : "s"}.` : undefined,
|
|
369
|
+
].filter((value) => Boolean(value));
|
|
370
|
+
return {
|
|
371
|
+
records,
|
|
372
|
+
...(tail.warning ? { readFailed: true } : {}),
|
|
373
|
+
truncated: tail.truncated || tail.lines.length > maxRecords,
|
|
374
|
+
...(warnings.length ? { warning: safeDisplayText(warnings.join(" ")) } : {}),
|
|
375
|
+
};
|
|
376
|
+
}
|
|
@@ -1,63 +1,7 @@
|
|
|
1
1
|
import { type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { type MarkdownTheme } from "@earendil-works/pi-tui";
|
|
3
|
+
import { type FleetTranscript } from "../shared/fleet-transcript-reader.ts";
|
|
3
4
|
type Theme = ExtensionContext["ui"]["theme"];
|
|
4
|
-
export type FleetTranscriptEvent = {
|
|
5
|
-
kind: "assistant";
|
|
6
|
-
text: string;
|
|
7
|
-
model?: string;
|
|
8
|
-
timestamp?: number;
|
|
9
|
-
} | {
|
|
10
|
-
kind: "user";
|
|
11
|
-
text: string;
|
|
12
|
-
timestamp?: number;
|
|
13
|
-
} | {
|
|
14
|
-
kind: "tool";
|
|
15
|
-
toolCallId?: string;
|
|
16
|
-
name: string;
|
|
17
|
-
args?: string;
|
|
18
|
-
argsPayload?: string;
|
|
19
|
-
output?: string;
|
|
20
|
-
outputTruncated?: boolean;
|
|
21
|
-
status: "running" | "complete" | "error";
|
|
22
|
-
error?: string;
|
|
23
|
-
startedAt?: number;
|
|
24
|
-
endedAt?: number;
|
|
25
|
-
timestamp?: number;
|
|
26
|
-
} | {
|
|
27
|
-
kind: "notice";
|
|
28
|
-
text: string;
|
|
29
|
-
tone: "muted" | "warning" | "error";
|
|
30
|
-
timestamp?: number;
|
|
31
|
-
};
|
|
32
|
-
export interface FleetTranscript {
|
|
33
|
-
path: string;
|
|
34
|
-
events: FleetTranscriptEvent[];
|
|
35
|
-
truncated: boolean;
|
|
36
|
-
warning?: string;
|
|
37
|
-
/** The path was refused or the file could not be read, as opposed to a read that only skipped records. */
|
|
38
|
-
readFailed?: true;
|
|
39
|
-
}
|
|
40
|
-
export interface FleetTranscriptReadOptions {
|
|
41
|
-
trustedRoots: string[];
|
|
42
|
-
trustedFiles?: string[];
|
|
43
|
-
trustedFileRoot?: string;
|
|
44
|
-
maxRecords?: number;
|
|
45
|
-
maxBytes?: number;
|
|
46
|
-
}
|
|
47
|
-
export declare function readFleetTranscript(filePath: string, options: FleetTranscriptReadOptions): FleetTranscript;
|
|
48
|
-
export interface TranscriptRecordRead {
|
|
49
|
-
readFailed?: true;
|
|
50
|
-
records: Array<Record<string, unknown>>;
|
|
51
|
-
truncated: boolean;
|
|
52
|
-
warning?: string;
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Shared trusted-root-guarded tail reader that returns raw parsed JSONL
|
|
56
|
-
* records instead of fleet events. Both the legacy rail renderer and the
|
|
57
|
-
* native-component renderer ingest through this single validation path, so
|
|
58
|
-
* symlink refusal and path-escape rejection cannot diverge between them.
|
|
59
|
-
*/
|
|
60
|
-
export declare function readTranscriptRecords(filePath: string, options: FleetTranscriptReadOptions): TranscriptRecordRead;
|
|
61
5
|
export declare function renderFleetTranscript(transcript: FleetTranscript, width: number, theme: Theme, markdownTheme: MarkdownTheme, options?: {
|
|
62
6
|
expandedTools?: boolean;
|
|
63
7
|
}): string[];
|
|
@@ -1,377 +1,11 @@
|
|
|
1
|
-
import * as fs from "node:fs";
|
|
2
|
-
import * as path from "node:path";
|
|
3
1
|
import { getLanguageFromPath, highlightCode } from "@earendil-works/pi-coding-agent";
|
|
4
2
|
import { Markdown, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
5
3
|
import { safeTerminalText as safeDisplayText } from "../shared/display-text.js";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
4
|
+
// Fork: the reader (records, validation, event parsing) lives in the shared
|
|
5
|
+
// module; this file only renders a transcript. Keeping the two copies in sync
|
|
6
|
+
// was the fork's largest remaining duplication.
|
|
7
|
+
import { objectValue, safeTranscriptEvent, } from "../shared/fleet-transcript-reader.js";
|
|
10
8
|
const TOOL_PREVIEW_LINES = 7;
|
|
11
|
-
function sanitizeJsonDisplayValue(value) {
|
|
12
|
-
if (typeof value === "string") {
|
|
13
|
-
const safe = safeDisplayText(value);
|
|
14
|
-
return { value: safe, changed: safe !== value };
|
|
15
|
-
}
|
|
16
|
-
if (Array.isArray(value)) {
|
|
17
|
-
const sanitized = value.map(sanitizeJsonDisplayValue);
|
|
18
|
-
return {
|
|
19
|
-
value: sanitized.map((entry) => entry.value),
|
|
20
|
-
changed: sanitized.some((entry) => entry.changed),
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
if (value && typeof value === "object") {
|
|
24
|
-
let changed = false;
|
|
25
|
-
const sanitized = Object.create(null);
|
|
26
|
-
for (const [key, nested] of Object.entries(value)) {
|
|
27
|
-
const safeKey = safeDisplayText(key);
|
|
28
|
-
const safeValue = sanitizeJsonDisplayValue(nested);
|
|
29
|
-
sanitized[safeKey] = safeValue.value;
|
|
30
|
-
changed ||= safeKey !== key || safeValue.changed;
|
|
31
|
-
}
|
|
32
|
-
return { value: changed ? sanitized : value, changed };
|
|
33
|
-
}
|
|
34
|
-
return { value, changed: false };
|
|
35
|
-
}
|
|
36
|
-
function safeToolArgsPayload(payload) {
|
|
37
|
-
try {
|
|
38
|
-
const sanitized = sanitizeJsonDisplayValue(JSON.parse(payload));
|
|
39
|
-
return sanitized.changed ? JSON.stringify(sanitized.value) : safeDisplayText(payload);
|
|
40
|
-
}
|
|
41
|
-
catch {
|
|
42
|
-
return safeDisplayText(payload);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
function objectValue(value) {
|
|
46
|
-
return value && typeof value === "object" && !Array.isArray(value)
|
|
47
|
-
? value
|
|
48
|
-
: undefined;
|
|
49
|
-
}
|
|
50
|
-
function stringValue(value) {
|
|
51
|
-
return typeof value === "string" && value.trim() ? value : undefined;
|
|
52
|
-
}
|
|
53
|
-
function numberValue(value) {
|
|
54
|
-
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
55
|
-
}
|
|
56
|
-
function pathWithin(base, candidate) {
|
|
57
|
-
const resolvedBase = path.resolve(base);
|
|
58
|
-
const resolvedCandidate = path.resolve(candidate);
|
|
59
|
-
return resolvedCandidate === resolvedBase || resolvedCandidate.startsWith(`${resolvedBase}${path.sep}`);
|
|
60
|
-
}
|
|
61
|
-
function errorMessage(error) {
|
|
62
|
-
return error instanceof Error ? error.message : String(error);
|
|
63
|
-
}
|
|
64
|
-
function isNotFoundError(error) {
|
|
65
|
-
return Boolean(objectValue(error)?.code === "ENOENT");
|
|
66
|
-
}
|
|
67
|
-
function validateTranscriptPath(filePath, trustedRoots, trustedFiles = [], trustedFileRoot) {
|
|
68
|
-
if (trustedRoots.length === 0 && (!trustedFileRoot || trustedFiles.length === 0))
|
|
69
|
-
return { warning: `Transcript preview has no trusted root: ${filePath}` };
|
|
70
|
-
const resolvedPath = path.resolve(filePath);
|
|
71
|
-
const recordedCandidate = trustedFileRoot
|
|
72
|
-
&& pathWithin(trustedFileRoot, resolvedPath)
|
|
73
|
-
&& trustedFiles.some((file) => path.resolve(file) === resolvedPath);
|
|
74
|
-
if (!trustedRoots.some((root) => pathWithin(root, resolvedPath)) && !recordedCandidate) {
|
|
75
|
-
return { warning: `Transcript is outside trusted roots: ${filePath}` };
|
|
76
|
-
}
|
|
77
|
-
let stat;
|
|
78
|
-
try {
|
|
79
|
-
stat = fs.lstatSync(resolvedPath);
|
|
80
|
-
}
|
|
81
|
-
catch (error) {
|
|
82
|
-
if (isNotFoundError(error))
|
|
83
|
-
return {};
|
|
84
|
-
return { warning: `Transcript could not be inspected: ${errorMessage(error)}` };
|
|
85
|
-
}
|
|
86
|
-
if (stat.isSymbolicLink())
|
|
87
|
-
return { warning: `Transcript preview refused a symlink: ${filePath}` };
|
|
88
|
-
if (!stat.isFile())
|
|
89
|
-
return { warning: `Transcript path is not a file: ${filePath}` };
|
|
90
|
-
try {
|
|
91
|
-
const realPath = fs.realpathSync(resolvedPath);
|
|
92
|
-
const realRoots = trustedRoots
|
|
93
|
-
.filter((root) => fs.existsSync(root))
|
|
94
|
-
.map((root) => fs.realpathSync(root));
|
|
95
|
-
if (!realRoots.some((root) => pathWithin(root, realPath)) && !isTrustedRecordedSessionFile(realPath, trustedFiles, trustedFileRoot)) {
|
|
96
|
-
return { warning: `Transcript resolves outside trusted roots: ${filePath}` };
|
|
97
|
-
}
|
|
98
|
-
return { resolvedPath: realPath };
|
|
99
|
-
}
|
|
100
|
-
catch (error) {
|
|
101
|
-
return { warning: `Transcript path could not be resolved: ${errorMessage(error)}` };
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
function isCompleteRecord(line) {
|
|
105
|
-
if (!line?.trim())
|
|
106
|
-
return false;
|
|
107
|
-
try {
|
|
108
|
-
return objectValue(JSON.parse(line)) !== undefined;
|
|
109
|
-
}
|
|
110
|
-
catch {
|
|
111
|
-
return false;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
function readTailLines(filePath, maxBytes) {
|
|
115
|
-
let fd;
|
|
116
|
-
try {
|
|
117
|
-
const noFollow = typeof fs.constants.O_NOFOLLOW === "number" ? fs.constants.O_NOFOLLOW : 0;
|
|
118
|
-
fd = fs.openSync(filePath, fs.constants.O_RDONLY | noFollow);
|
|
119
|
-
const stat = fs.fstatSync(fd);
|
|
120
|
-
if (!stat.isFile())
|
|
121
|
-
return { lines: [], truncated: false, warning: `Transcript path is not a file: ${filePath}` };
|
|
122
|
-
if (stat.size === 0)
|
|
123
|
-
return { lines: [], truncated: false };
|
|
124
|
-
const bytesToRead = Math.min(stat.size, maxBytes);
|
|
125
|
-
const start = stat.size - bytesToRead;
|
|
126
|
-
const buffer = Buffer.alloc(bytesToRead);
|
|
127
|
-
const bytesRead = fs.readSync(fd, buffer, 0, bytesToRead, start);
|
|
128
|
-
const content = buffer.subarray(0, bytesRead).toString("utf-8");
|
|
129
|
-
const endsWithNewline = content.endsWith("\n");
|
|
130
|
-
let lines = content.split(/\r?\n/);
|
|
131
|
-
if (start > 0 && lines.length > 0)
|
|
132
|
-
lines = lines.slice(1);
|
|
133
|
-
if (lines.at(-1) === "")
|
|
134
|
-
lines = lines.slice(0, -1);
|
|
135
|
-
else if (!endsWithNewline && !isCompleteRecord(lines.at(-1)))
|
|
136
|
-
lines = lines.slice(0, -1);
|
|
137
|
-
return { lines, truncated: start > 0 };
|
|
138
|
-
}
|
|
139
|
-
catch (error) {
|
|
140
|
-
return { lines: [], truncated: false, warning: `Transcript could not be read: ${errorMessage(error)}` };
|
|
141
|
-
}
|
|
142
|
-
finally {
|
|
143
|
-
if (fd !== undefined)
|
|
144
|
-
fs.closeSync(fd);
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
function clipMessage(text) {
|
|
148
|
-
if (text.length <= MAX_MESSAGE_CHARS)
|
|
149
|
-
return text;
|
|
150
|
-
return `${text.slice(0, MAX_MESSAGE_CHARS)}\n\n… message truncated`;
|
|
151
|
-
}
|
|
152
|
-
function safeTranscriptEvent(event) {
|
|
153
|
-
if (event.kind === "assistant") {
|
|
154
|
-
return {
|
|
155
|
-
...event,
|
|
156
|
-
text: safeDisplayText(event.text),
|
|
157
|
-
...(event.model ? { model: safeDisplayText(event.model) } : {}),
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
if (event.kind === "user" || event.kind === "notice") {
|
|
161
|
-
return { ...event, text: safeDisplayText(event.text) };
|
|
162
|
-
}
|
|
163
|
-
return {
|
|
164
|
-
...event,
|
|
165
|
-
name: safeDisplayText(event.name),
|
|
166
|
-
...(event.args !== undefined ? { args: safeDisplayText(event.args) } : {}),
|
|
167
|
-
...(event.argsPayload !== undefined ? { argsPayload: safeToolArgsPayload(event.argsPayload) } : {}),
|
|
168
|
-
...(event.output !== undefined ? { output: safeDisplayText(event.output) } : {}),
|
|
169
|
-
...(event.error !== undefined ? { error: safeDisplayText(event.error) } : {}),
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
function findTool(events, toolCallId, name) {
|
|
173
|
-
if (toolCallId) {
|
|
174
|
-
for (let index = events.length - 1; index >= 0; index--) {
|
|
175
|
-
const event = events[index];
|
|
176
|
-
if (event?.kind === "tool" && event.toolCallId === toolCallId)
|
|
177
|
-
return event;
|
|
178
|
-
}
|
|
179
|
-
return undefined;
|
|
180
|
-
}
|
|
181
|
-
for (let index = events.length - 1; index >= 0; index--) {
|
|
182
|
-
const event = events[index];
|
|
183
|
-
if (event?.kind !== "tool")
|
|
184
|
-
continue;
|
|
185
|
-
const tool = event;
|
|
186
|
-
if ((!name || tool.name === name) && !tool.resultSeen)
|
|
187
|
-
return tool;
|
|
188
|
-
}
|
|
189
|
-
return undefined;
|
|
190
|
-
}
|
|
191
|
-
function appendTextEvent(events, kind, text, metadata) {
|
|
192
|
-
const clipped = clipMessage(text.trim());
|
|
193
|
-
if (!clipped)
|
|
194
|
-
return;
|
|
195
|
-
const previous = events.at(-1);
|
|
196
|
-
if (previous?.kind === kind && previous.text === clipped)
|
|
197
|
-
return;
|
|
198
|
-
events.push({ kind, text: clipped, ...metadata });
|
|
199
|
-
}
|
|
200
|
-
function parseTranscriptLines(lines, conversationStarted = false) {
|
|
201
|
-
const events = [];
|
|
202
|
-
let malformed = 0;
|
|
203
|
-
let explicitTruncation = false;
|
|
204
|
-
let assistantSeen = conversationStarted;
|
|
205
|
-
for (const line of lines) {
|
|
206
|
-
if (!line.trim())
|
|
207
|
-
continue;
|
|
208
|
-
let record;
|
|
209
|
-
try {
|
|
210
|
-
record = objectValue(JSON.parse(line));
|
|
211
|
-
}
|
|
212
|
-
catch {
|
|
213
|
-
malformed++;
|
|
214
|
-
continue;
|
|
215
|
-
}
|
|
216
|
-
if (!record) {
|
|
217
|
-
malformed++;
|
|
218
|
-
continue;
|
|
219
|
-
}
|
|
220
|
-
const recordType = stringValue(record.recordType);
|
|
221
|
-
const timestamp = numberValue(record.ts);
|
|
222
|
-
if (recordType === "truncated") {
|
|
223
|
-
explicitTruncation = true;
|
|
224
|
-
continue;
|
|
225
|
-
}
|
|
226
|
-
if (recordType === "tool_start") {
|
|
227
|
-
const name = stringValue(record.toolName) ?? "tool";
|
|
228
|
-
events.push({
|
|
229
|
-
kind: "tool",
|
|
230
|
-
...(stringValue(record.toolCallId) ? { toolCallId: stringValue(record.toolCallId) } : {}),
|
|
231
|
-
name,
|
|
232
|
-
...(stringValue(record.argsPreview) ? { args: stringValue(record.argsPreview) } : {}),
|
|
233
|
-
...(stringValue(record.argsPayload) ? { argsPayload: stringValue(record.argsPayload) } : {}),
|
|
234
|
-
status: "running",
|
|
235
|
-
...(timestamp !== undefined ? { timestamp, startedAt: timestamp } : {}),
|
|
236
|
-
});
|
|
237
|
-
continue;
|
|
238
|
-
}
|
|
239
|
-
if (recordType === "tool_end") {
|
|
240
|
-
const tool = findTool(events, stringValue(record.toolCallId), stringValue(record.toolName));
|
|
241
|
-
if (tool && !tool.resultSeen)
|
|
242
|
-
tool.status = record.isError === true ? "error" : "complete";
|
|
243
|
-
if (tool && timestamp !== undefined && tool.endedAt === undefined)
|
|
244
|
-
tool.endedAt = timestamp;
|
|
245
|
-
continue;
|
|
246
|
-
}
|
|
247
|
-
if (recordType === "stderr") {
|
|
248
|
-
const text = stringValue(record.text);
|
|
249
|
-
if (text)
|
|
250
|
-
events.push({ kind: "notice", text: clipMessage(text), tone: "error", ...(timestamp !== undefined ? { timestamp } : {}) });
|
|
251
|
-
continue;
|
|
252
|
-
}
|
|
253
|
-
if (recordType !== "message")
|
|
254
|
-
continue;
|
|
255
|
-
const message = objectValue(record.message);
|
|
256
|
-
const role = stringValue(record.role) ?? stringValue(message?.role);
|
|
257
|
-
const text = stringValue(record.text) ?? stringValue(message?.text) ?? stringValue(message?.content);
|
|
258
|
-
if (role === "toolResult" || role === "tool_result") {
|
|
259
|
-
const toolCallId = stringValue(record.toolCallId) ?? stringValue(message?.toolCallId);
|
|
260
|
-
const name = stringValue(record.toolName) ?? stringValue(message?.toolName) ?? "tool";
|
|
261
|
-
const failed = record.isError === true || message?.isError === true;
|
|
262
|
-
let tool = findTool(events, toolCallId, name);
|
|
263
|
-
if (!tool) {
|
|
264
|
-
tool = {
|
|
265
|
-
kind: "tool",
|
|
266
|
-
...(toolCallId ? { toolCallId } : {}),
|
|
267
|
-
name,
|
|
268
|
-
status: failed ? "error" : "complete",
|
|
269
|
-
...(timestamp !== undefined ? { timestamp } : {}),
|
|
270
|
-
};
|
|
271
|
-
events.push(tool);
|
|
272
|
-
}
|
|
273
|
-
if (!tool.resultSeen) {
|
|
274
|
-
tool.resultSeen = true;
|
|
275
|
-
tool.status = failed ? "error" : "complete";
|
|
276
|
-
if (timestamp !== undefined && tool.endedAt === undefined)
|
|
277
|
-
tool.endedAt = timestamp;
|
|
278
|
-
if (text && (!failed || tool.output === undefined)) {
|
|
279
|
-
tool.output = clipMessage(text);
|
|
280
|
-
tool.outputTruncated = record.outputTruncated === true || text.includes("… payload truncated") || text.includes("[Showing lines");
|
|
281
|
-
}
|
|
282
|
-
if (failed && text)
|
|
283
|
-
tool.error = clipMessage(text.split(/\r?\n/).find((candidate) => candidate.trim()) ?? text);
|
|
284
|
-
}
|
|
285
|
-
continue;
|
|
286
|
-
}
|
|
287
|
-
if (role === "assistant") {
|
|
288
|
-
assistantSeen = true;
|
|
289
|
-
// The transcript writer records the assistant message's provider-local id, which can itself contain a slash.
|
|
290
|
-
const rawModel = stringValue(record.model) ?? stringValue(message?.model);
|
|
291
|
-
const provider = stringValue(message?.provider);
|
|
292
|
-
const model = rawModel && provider ? `${provider}/${rawModel}` : rawModel;
|
|
293
|
-
if (text)
|
|
294
|
-
appendTextEvent(events, "assistant", text, {
|
|
295
|
-
...(model ? { model } : {}),
|
|
296
|
-
...(timestamp !== undefined ? { timestamp } : {}),
|
|
297
|
-
});
|
|
298
|
-
continue;
|
|
299
|
-
}
|
|
300
|
-
if (role === "user" && assistantSeen && text) {
|
|
301
|
-
appendTextEvent(events, "user", text, timestamp !== undefined ? { timestamp } : {});
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
for (const event of events) {
|
|
305
|
-
if (event.kind === "tool")
|
|
306
|
-
delete event.resultSeen;
|
|
307
|
-
}
|
|
308
|
-
return { events: events.map(safeTranscriptEvent), malformed, explicitTruncation };
|
|
309
|
-
}
|
|
310
|
-
export function readFleetTranscript(filePath, options) {
|
|
311
|
-
const validated = validateTranscriptPath(filePath, options.trustedRoots, options.trustedFiles, options.trustedFileRoot);
|
|
312
|
-
if (!validated.resolvedPath) {
|
|
313
|
-
return { path: filePath, events: [], truncated: false, readFailed: true, ...(validated.warning ? { warning: safeDisplayText(validated.warning) } : {}) };
|
|
314
|
-
}
|
|
315
|
-
const maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS);
|
|
316
|
-
const tail = readTailLines(validated.resolvedPath, Math.max(1024, options.maxBytes ?? DEFAULT_MAX_BYTES));
|
|
317
|
-
const recordsOmitted = tail.truncated || tail.lines.length > maxRecords;
|
|
318
|
-
const selectedLines = tail.lines.slice(-maxRecords);
|
|
319
|
-
const parsed = parseTranscriptLines(selectedLines, recordsOmitted);
|
|
320
|
-
const warnings = [
|
|
321
|
-
tail.warning,
|
|
322
|
-
parsed.malformed > 0 ? `Skipped ${parsed.malformed} malformed transcript record${parsed.malformed === 1 ? "" : "s"}.` : undefined,
|
|
323
|
-
].filter((value) => Boolean(value));
|
|
324
|
-
return {
|
|
325
|
-
path: filePath,
|
|
326
|
-
events: parsed.events,
|
|
327
|
-
truncated: tail.truncated || tail.lines.length > maxRecords || parsed.explicitTruncation,
|
|
328
|
-
...(tail.warning ? { readFailed: true } : {}),
|
|
329
|
-
...(warnings.length ? { warning: safeDisplayText(warnings.join(" ")) } : {}),
|
|
330
|
-
};
|
|
331
|
-
}
|
|
332
|
-
/**
|
|
333
|
-
* Shared trusted-root-guarded tail reader that returns raw parsed JSONL
|
|
334
|
-
* records instead of fleet events. Both the legacy rail renderer and the
|
|
335
|
-
* native-component renderer ingest through this single validation path, so
|
|
336
|
-
* symlink refusal and path-escape rejection cannot diverge between them.
|
|
337
|
-
*/
|
|
338
|
-
export function readTranscriptRecords(filePath, options) {
|
|
339
|
-
const validated = validateTranscriptPath(filePath, options.trustedRoots);
|
|
340
|
-
if (!validated.resolvedPath) {
|
|
341
|
-
return { records: [], truncated: false, readFailed: true, ...(validated.warning ? { warning: safeDisplayText(validated.warning) } : {}) };
|
|
342
|
-
}
|
|
343
|
-
const maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS);
|
|
344
|
-
const tail = readTailLines(validated.resolvedPath, Math.max(1024, options.maxBytes ?? DEFAULT_MAX_BYTES));
|
|
345
|
-
const selected = tail.lines.slice(-maxRecords);
|
|
346
|
-
const records = [];
|
|
347
|
-
let malformed = 0;
|
|
348
|
-
for (const line of selected) {
|
|
349
|
-
if (!line.trim())
|
|
350
|
-
continue;
|
|
351
|
-
try {
|
|
352
|
-
const parsed = JSON.parse(line);
|
|
353
|
-
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
354
|
-
records.push(parsed);
|
|
355
|
-
}
|
|
356
|
-
else {
|
|
357
|
-
malformed++;
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
catch {
|
|
361
|
-
malformed++;
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
const warnings = [
|
|
365
|
-
tail.warning,
|
|
366
|
-
malformed > 0 ? `Skipped ${malformed} malformed transcript record${malformed === 1 ? "" : "s"}.` : undefined,
|
|
367
|
-
].filter((value) => Boolean(value));
|
|
368
|
-
return {
|
|
369
|
-
records,
|
|
370
|
-
...(tail.warning ? { readFailed: true } : {}),
|
|
371
|
-
truncated: tail.truncated || tail.lines.length > maxRecords,
|
|
372
|
-
...(warnings.length ? { warning: safeDisplayText(warnings.join(" ")) } : {}),
|
|
373
|
-
};
|
|
374
|
-
}
|
|
375
9
|
function statusGlyph(event, theme) {
|
|
376
10
|
if (event.status === "running")
|
|
377
11
|
return theme.fg("warning", "●");
|