-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathagentInvocationLogger.ts
More file actions
247 lines (215 loc) · 7.03 KB
/
Copy pathagentInvocationLogger.ts
File metadata and controls
247 lines (215 loc) · 7.03 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
import { createHash, randomUUID } from "crypto";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import pino from "pino";
const LOG_FILE_NAME = "agent-invocation.log";
const MAX_LOG_SIZE_MB = 5;
const MAX_LOG_SIZE_BYTES = MAX_LOG_SIZE_MB * 1024 * 1024;
const MAX_BACKUP_COUNT = 3;
const REDACTED_VALUE = "[redacted]";
const SENSITIVE_KEY_PATTERN = /(connection|token|secret|password|credential|auth|refresh)/i;
/**
* Outcome of an agent tool invocation
*/
export type InvocationOutcome = "completed" | "no-result" | "rejected";
/**
* Structure of an agent invocation log entry
*/
export interface AgentInvocationLogEntry {
timestamp: string;
toolId: string;
toolName: string;
connectionId: string | null;
prefillSummary: string;
outcome: InvocationOutcome;
invocationMode?: "one-way" | "two-way";
correlationId: string;
error?: string;
}
/**
* Get the log file path in userData directory
*/
export function getLogFilePath(): string {
return path.join(getUserDataPath(), LOG_FILE_NAME);
}
/**
* Get the userData path for the application
*/
function getUserDataPath(): string {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { app } = require("electron");
return app.getPath("userData");
} catch {
return path.join(os.tmpdir(), "powerplatform-toolbox-logs");
}
}
/**
* Rotate log file if it exceeds the maximum size
*/
function rotateLogIfNeeded(): void {
const logPath = getLogFilePath();
try {
if (!fs.existsSync(logPath)) {
return;
}
const stats = fs.statSync(logPath);
if (stats.size >= MAX_LOG_SIZE_BYTES) {
for (let i = MAX_BACKUP_COUNT - 1; i >= 0; i--) {
const oldPath = `${logPath}.${i === 0 ? "" : `.` + i}`;
const newPath = `${logPath}.${i + 1}`;
if (fs.existsSync(oldPath)) {
fs.renameSync(oldPath, newPath);
}
}
fs.renameSync(logPath, `${logPath}.1`);
}
} catch (error) {
console.error("Failed to rotate log file:", error instanceof Error ? error.message : String(error));
}
}
/**
* Read all log entries from the log file
*/
export function readLogEntries(): AgentInvocationLogEntry[] {
const logPath = getLogFilePath();
try {
const candidatePaths = [logPath, ...Array.from({ length: MAX_BACKUP_COUNT }, (_, idx) => `${logPath}.${idx + 1}`)];
const existingPaths = candidatePaths.filter((candidatePath) => fs.existsSync(candidatePath));
if (existingPaths.length === 0) {
return [];
}
const lines: string[] = [];
for (const existingPath of existingPaths) {
const content = fs.readFileSync(existingPath, { encoding: "utf-8" });
const parsedLines = content.split("\n").filter((line) => line.trim().length > 0);
lines.push(...parsedLines);
}
return lines
.map((line) => {
try {
const entry = JSON.parse(line) as AgentInvocationLogEntry;
return {
...entry,
correlationId: entry.correlationId || `log-${createHash("sha256").update(line).digest("hex").slice(0, 16)}`,
};
} catch {
return null;
}
})
.filter((entry): entry is AgentInvocationLogEntry => entry !== null)
.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
} catch (error) {
console.error("Failed to read log entries:", error instanceof Error ? error.message : String(error));
return [];
}
}
/**
* Clear all log entries (for testing/maintenance)
*/
export function clearLogEntries(): void {
const logPath = getLogFilePath();
try {
if (fs.existsSync(logPath)) {
fs.unlinkSync(logPath);
}
// Clear rotated logs
for (let i = 1; i <= MAX_BACKUP_COUNT; i++) {
const rotatedPath = `${logPath}.${i}`;
if (fs.existsSync(rotatedPath)) {
fs.unlinkSync(rotatedPath);
}
}
} catch (error) {
console.error("Failed to clear log entries:", error instanceof Error ? error.message : String(error));
}
}
/**
* Pino logger instance for agent invocations
*/
let logger: pino.Logger | null = null;
/**
* Get or create the pino logger instance
*/
function getLogger(): pino.Logger {
if (logger) {
return logger;
}
const logPath = getLogFilePath();
const dir = path.dirname(logPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
const destination = pino.destination({
dest: logPath,
sync: true,
});
logger = pino(
{
level: "info",
timestamp: pino.stdTimeFunctions.isoTime,
},
destination,
);
return logger;
}
/**
* Get summary of prefill data (first 200 chars of stringified JSON)
*/
function getPrefillSummary(prefillData: Record<string, unknown> | undefined): string {
if (!prefillData || Object.keys(prefillData).length === 0) {
return "{}";
}
try {
const str = JSON.stringify(redactSensitiveValue(prefillData));
return str.length > 200 ? str.slice(0, 200) + "..." : str;
} catch {
return "[unserializable]";
}
}
function redactSensitiveValue(value: unknown, key?: string): unknown {
if (key && SENSITIVE_KEY_PATTERN.test(key)) {
return REDACTED_VALUE;
}
if (Array.isArray(value)) {
return value.map((item) => redactSensitiveValue(item));
}
if (value && typeof value === "object") {
const record = value as Record<string, unknown>;
const redacted: Record<string, unknown> = {};
for (const [entryKey, entryValue] of Object.entries(record)) {
redacted[entryKey] = redactSensitiveValue(entryValue, entryKey);
}
return redacted;
}
return value;
}
/**
* Log an agent tool invocation using pino
*/
export function logInvocation(params: {
toolId: string;
toolName: string;
connectionId: string | null;
prefillData?: Record<string, unknown>;
outcome: InvocationOutcome;
invocationMode?: "one-way" | "two-way";
correlationId?: string;
error?: string;
}): void {
rotateLogIfNeeded();
const logEntry: AgentInvocationLogEntry = {
timestamp: new Date().toISOString(),
toolId: params.toolId,
toolName: params.toolName,
connectionId: params.connectionId ? REDACTED_VALUE : null,
prefillSummary: getPrefillSummary(params.prefillData),
outcome: params.outcome,
correlationId: params.correlationId ?? randomUUID(),
...(params.invocationMode ? { invocationMode: params.invocationMode } : {}),
...(params.error ? { error: params.error } : {}),
};
const activeLogger = getLogger();
activeLogger.info(logEntry, "agent-invocation");
}