{{ message }}
Repository navigation
Expand file tree
/
Copy pathparse_copilot_log.cjs
More file actions
329 lines (314 loc) · 14.5 KB
/
Copy pathparse_copilot_log.cjs
File metadata and controls
329 lines (314 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// @ts-check
/// <reference types="@actions/github-script" />
const { iterateJsonlEvents } = require("./jsonl_helpers.cjs");
/** @typedef {import("./types/agent_session").SessionEvent} SessionEvent */
const { createEngineLogParser, generateConversationMarkdown, generateInformationSection, buildStepSummaryDetailsSection, formatInitializationSummary, formatToolUse, AWF_INFRA_LINE_RE } = require("./log_parser_shared.cjs");
const { projectSessionResult, createSessionEvent, accumulateSessionUsage, isTokenCount, normalizeAgentSession, normalizeSessionUsage } = require("./agent_session.cjs");
const { normalizeCopilotSession } = require("./copilot_session.cjs");
const main = createEngineLogParser({
parserName: "Copilot",
parseFunction: parseCopilotLog,
supportsDirectories: true,
});
const AWF_TOKEN_WARNING_RE = /\[AWF TOKEN WARNING\][^\n\r]+/g;
/** @param {Array<any>} logEntries @returns {string[]} */
function extractAwfTokenWarnings(logEntries) {
/** @type {string[]} */
const warnings = [];
const seen = new Set();
const visit = value => {
if (typeof value === "string") {
for (const match of value.match(AWF_TOKEN_WARNING_RE) ?? []) {
const normalized = match.trim();
if (!seen.has(normalized)) {
seen.add(normalized);
warnings.push(normalized);
}
}
} else if (Array.isArray(value)) {
for (const item of value) visit(item);
} else if (value && typeof value === "object") {
for (const key of ["text", "message", "content", "system", "data"]) visit(value[key]);
}
};
for (const entry of logEntries) {
if (entry.type !== "user.message") visit(entry);
}
return warnings;
}
/**
* @param {string} logContent
* @returns {{markdown: string, logEntries: SessionEvent[], mcpFailures?: string[], maxTurnsHit?: boolean}}
*/
function parseCopilotLog(logContent) {
let logEntries;
try {
logEntries = JSON.parse(logContent);
if (!Array.isArray(logEntries)) throw new Error("Not a JSON array");
} catch {
logEntries = parseDebugLogFormat(logContent);
}
let canonicalLogEntries = normalizeCopilotSession(logEntries);
if (!canonicalLogEntries.length) canonicalLogEntries = normalizeCopilotSession(parsePrettyPrintFormat(logContent));
if (!canonicalLogEntries.length) {
return { markdown: buildStepSummaryDetailsSection("Agent Log Summary", "Log format not recognized as Copilot JSON array or JSONL."), logEntries: [] };
}
const conversationResult = generateConversationMarkdown(canonicalLogEntries, {
includeInformation: false,
formatToolCallback: (toolUse, toolResult) => formatToolUse(toolUse, toolResult, { includeDetailedParameters: false }),
formatInitCallback: initEntry =>
formatInitializationSummary(initEntry, {
includeSlashCommands: false,
modelInfoCallback: entry => {
if (!entry.model_info) return "";
const modelInfo = entry.model_info;
let markdown = "";
if (modelInfo.name) {
markdown += `**Model Name:** ${modelInfo.name}`;
if (modelInfo.vendor) markdown += ` (${modelInfo.vendor})`;
markdown += "\n\n";
}
if (modelInfo.billing) {
const billing = modelInfo.billing;
if (billing.is_premium === true) {
markdown += "**Premium Model:** Yes";
if (billing.multiplier && billing.multiplier !== 1) markdown += ` (${billing.multiplier}x cost multiplier)`;
markdown += "\n";
if (Array.isArray(billing.restricted_to) && billing.restricted_to.length) markdown += `**Required Plans:** ${billing.restricted_to.join(", ")}\n`;
markdown += "\n";
} else if (billing.is_premium === false) {
markdown += "**Premium Model:** No\n\n";
}
}
return markdown;
},
}),
});
let markdown = conversationResult.markdown;
const warnings = extractAwfTokenWarnings(canonicalLogEntries);
if (warnings.length) markdown += buildStepSummaryDetailsSection("Firewall Steering", warnings.map(warning => `- ${warning}\n`).join(""));
markdown += generateInformationSection(projectSessionResult(canonicalLogEntries), { additionalInfoCallback: () => "" });
return { markdown, logEntries: canonicalLogEntries };
}
/**
* Decode recognized CLI display framing without rewriting the payload text.
* @param {string} logContent
* @returns {SessionEvent[]}
*/
function parsePrettyPrintFormat(logContent) {
if (!/^[✗●✓] /m.test(logContent)) return [];
const lines = logContent.split("\n");
/** @type {SessionEvent[]} */
const entries = [];
/** @type {string[]} */
let text = [];
/** @type {Record<string, any>} */
const footer = {};
/** @type {Record<string, any>} */
const breakdown = {};
/** @type {Record<string, any>|undefined} */
let tokens;
let inModelBreakdown = false;
const flushText = () => {
if (text.length) entries.push({ type: "assistant.message", data: { content: text.join("") } });
text = [];
};
const count = value => {
const number = Number.parseFloat(value);
return Math.round(number * (/m$/i.test(value) ? 1000000 : /k$/i.test(value) ? 1000 : 1));
};
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (AWF_INFRA_LINE_RE.test(line)) continue;
const trimmed = line.trim();
const marker = line.match(/^([✗●✓]) (.*)$/);
if (marker) {
flushText();
inModelBreakdown = false;
let header = marker[2];
const mayWrap = /^\S+\s+\S/.test(header);
const rawContinuation = [];
const output = [];
while (index + 1 < lines.length) {
const next = lines[index + 1];
const continuation = next.match(/^\s*[└│] ?(.*)$/);
if (continuation || /^ {4}/.test(next)) {
rawContinuation.push(next);
output.push(continuation ? continuation[1] : next.slice(4));
index++;
} else if (mayWrap && /^ {2}\S/.test(next) && !output.length) {
rawContinuation.push(next);
header += "\n" + next.slice(2);
index++;
} else {
break;
}
}
const mcp = header.match(/^(\S+) (\S+) · /);
const namedTool =
/^(?:Bash|BashOutput|KillBash|Read|Write|Edit|MultiEdit|LS|Grep|Glob|TodoWrite|Task|WebFetch|WebSearch|AskUserQuestion|NotebookEdit|Skill|EnterPlanMode|ExitPlanMode|ListMcpResourcesTool|ReadMcpResourceTool)(?:\s|$)/.test(header);
// Preserve named tool layouts, without restricting which executables can run.
const shell = !mcp && !/^mcp__\S+/.test(header) && !namedTool;
const toolName = mcp ? mcp[2] : shell ? "bash" : header.match(/^\S+/)?.[0];
const source = { prettyPrint: { marker: marker[1], header: marker[2], continuation: rawContinuation } };
entries.push(
createSessionEvent(source, "tool.execution_start", {
toolName,
...(mcp ? { mcpServerName: mcp[1] } : {}),
...(shell && !mcp ? { command: header } : {}),
})
);
entries.push(
createSessionEvent(source, "tool.execution_complete", {
toolName,
...(mcp ? { mcpServerName: mcp[1] } : {}),
success: marker[1] !== "✗",
...(output.length ? { output: output.join("\n") } : {}),
})
);
continue;
}
if (/^Breakdown by AI model:/.test(trimmed)) {
flushText();
inModelBreakdown = true;
continue;
}
if (inModelBreakdown) {
const model = line.match(/^ +(\S+)\s+([\d.]+[km]?)\s+in,\s+([\d.]+[km]?)\s+out(?:,\s+([\d.]+[km]?)\s+cached)?/i);
if (model) {
entries.push({ type: "session.init", data: { sourceEngine: "copilot", model: model[1] } });
accumulateSessionUsage(breakdown, {
input_tokens: count(model[2]),
output_tokens: count(model[3]),
...(model[4] !== undefined ? { cache_read_input_tokens: count(model[4]) } : {}),
});
continue;
}
inModelBreakdown = false;
}
if (/^(?:Total usage est:|API time spent:|Total session time:|Total code changes:|Changes\s+[+-]?\d|Duration\s+\d|Tokens\s+[↑↓]|Resume\s{2,}copilot\s+--resume=|Turns:)/.test(trimmed)) {
flushText();
const tokenMatch = trimmed.match(/^Tokens\s+↑\s*([\d.]+[km]?)\s*[•·]\s*↓\s*([\d.]+[km]?)(?:\s*[•·]\s*([\d.]+[km]?)\s*\(cached\))?/i);
const inlineCached = trimmed.match(/^Tokens\s+↑\s*([\d.]+[km]?)\s*\(\s*([\d.]+[km]?)\s+cached(?:\s*,\s*([\d.]+[km]?)\s+written)?\s*\)\s*[•·]\s*↓\s*([\d.]+[km]?)/i);
if (tokenMatch) {
tokens = { input_tokens: count(tokenMatch[1]), output_tokens: count(tokenMatch[2]) };
if (tokenMatch[3] !== undefined) tokens.cache_read_input_tokens = count(tokenMatch[3]);
} else if (inlineCached) {
tokens = { input_tokens: count(inlineCached[1]), output_tokens: count(inlineCached[4]), cache_read_input_tokens: count(inlineCached[2]) };
if (inlineCached[3] !== undefined) tokens.cache_creation_input_tokens = count(inlineCached[3]);
}
const turns = trimmed.match(/^Turns:\s*(\d+)$/i);
if (turns && isTokenCount(Number(turns[1]))) footer.numTurns = Number(turns[1]);
const duration = trimmed.match(/^(?:Duration\s+|Total session time:\s*)([\d.]+(?:h|m|s)(?:\s+[\d.]+(?:h|m|s))*)$/);
if (duration) {
const milliseconds = [...duration[1].matchAll(/([\d.]+)(h|m|s)/g)].reduce((total, match) => total + Number(match[1]) * ({ h: 3600000, m: 60000, s: 1000 }[match[2]] ?? 0), 0);
if (Number.isFinite(milliseconds) && milliseconds >= 0) footer.durationMs = milliseconds;
}
const resume = trimmed.match(/^Resume\s{2,}copilot\s+--resume=(\S+)$/);
if (resume) entries.push({ type: "session.init", data: { sourceEngine: "copilot", sessionId: resume[1] } });
continue;
}
text.push(line + (index < lines.length - 1 ? "\n" : ""));
}
flushText();
const reportedUsage = normalizeSessionUsage(tokens ?? breakdown);
if (reportedUsage && Object.keys(reportedUsage).length) footer.usage = reportedUsage;
if (Object.keys(footer).length) entries.push({ type: "session.result", data: footer });
return entries;
}
/**
* Parse adjacent JSONL records and legacy/Rust structured debug blocks together
* so one damaged block never hides an independently parseable observation.
* @param {string} logContent
* @returns {Array<any>}
*/
function parseDebugLogFormat(logContent) {
/** @type {Array<any>} */
const entries = [];
/** @type {Record<string, any>} */
const usage = {};
const responses = new Set();
let requestId;
/** @type {{kind: string, lines: string[], timestamp?: string, requestId?: string}|undefined} */
let block;
const processBlock = (value, framing) => {
if (!value || typeof value !== "object") return;
const source = { ...value, ...(framing.timestamp && value.timestamp === undefined ? { timestamp: framing.timestamp } : {}), ...(framing.requestId && value.requestId === undefined ? { requestId: framing.requestId } : {}) };
if (framing.kind === "Tools") {
if (Array.isArray(value)) entries.push(createSessionEvent({ tools: value, ...(framing.timestamp ? { timestamp: framing.timestamp } : {}) }, "session.init", { sourceEngine: "copilot", tools: value }));
return;
}
if (framing.kind === "Got model info") {
entries.push(createSessionEvent(source, "session.init", { sourceEngine: "copilot", modelInfo: value }));
return;
}
if (value.object === "response") {
entries.push(...normalizeAgentSession([source], { sourceEngine: "copilot" }));
return;
}
if (typeof value.type === "string" || Array.isArray(value)) {
entries.push(...(Array.isArray(value) ? value : [value]));
return;
}
if (!Array.isArray(value.choices) && value.error === undefined) return;
if (typeof value.model === "string") entries.push(createSessionEvent(source, "session.init", { sourceEngine: "copilot", model: value.model }));
const identity = value.id ?? framing.requestId;
const duplicate = identity !== undefined && responses.has(identity);
if (identity !== undefined) responses.add(identity);
for (const event of normalizeAgentSession([source], { sourceEngine: "copilot" })) {
if (event.type !== "session.result") entries.push(event);
else if (!duplicate && event.data.usage) {
accumulateSessionUsage(usage, event.data.usage);
if (Object.keys(usage).length) entries.push(createSessionEvent(event, "session.result", { usage: { ...usage } }));
}
}
if (!duplicate && value.error !== undefined) entries.push(createSessionEvent(source, "session.result", { errors: [value.error] }));
};
for (const entry of iterateJsonlEvents(logContent, {
lineTransform: line => {
const debug = line.match(/^(?:(\d{4}-\d{2}-\d{2}T\S+)\s+)?\[DEBUG\]\s+(?:\[rust:[^\]]+\]\s+)?(.*)$/);
const clean = debug ? debug[2] : line;
const marker = debug && clean.match(/^(data|Tools|Got model info):\s*(.*)$/);
return marker ? marker[2] : clean;
},
})) {
const line = entry.rawLine.replace(/\r?\n$|\r$/, "");
const debug = line.match(/^(?:(\d{4}-\d{2}-\d{2}T\S+)\s+)?\[DEBUG\]\s+(?:\[rust:[^\]]+\]\s+)?(.*)$/);
const clean = debug ? debug[2] : line;
const response = clean.match(/^response \(Request-ID ([^)]+)\):/);
if (response) {
requestId = response[1];
block = undefined;
continue;
}
const marker = debug && clean.match(/^(data|Tools|Got model info):\s*(.*)$/);
if (marker) {
block = { kind: marker[1], lines: [], timestamp: debug[1], requestId: marker[1] === "data" ? requestId : undefined };
if (marker[1] === "data") requestId = undefined;
}
const parsed = entry.type === "json" ? entry.value : undefined;
if (!marker && parsed && block?.kind !== "Tools" && normalizeAgentSession(Array.isArray(parsed) ? parsed : [parsed]).length) {
entries.push(...(Array.isArray(parsed) ? parsed : [parsed]));
block = undefined;
continue;
}
if (!block) continue;
const payload = marker ? marker[2] : clean;
if (!marker && /^\d{4}-\d{2}-\d{2}T\S+\s+\[/.test(line) && !/^\s*[\[{"}\]]/.test(payload)) {
block = undefined;
continue;
}
if (payload || block.lines.length) block.lines.push(payload);
let value;
try {
value = JSON.parse(block.lines.join("\n"));
} catch {
// Recover at the next record or block marker, without fabricating a completion for truncated JSON.
continue;
}
processBlock(value, block);
block = undefined;
}
return entries;
}
module.exports = { main, parseCopilotLog, parsePrettyPrintFormat, parseDebugLogFormat };
You can’t perform that action at this time.
