-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathdiagnostics.ts
More file actions
216 lines (194 loc) · 6.03 KB
/
diagnostics.ts
File metadata and controls
216 lines (194 loc) · 6.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
import { AsyncLocalStorage } from 'node:async_hooks';
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
type DiagnosticLevel = 'info' | 'warn' | 'error' | 'debug';
type DiagnosticEvent = {
ts: string;
level: DiagnosticLevel;
phase: string;
session?: string;
requestId?: string;
command?: string;
durationMs?: number;
data?: Record<string, unknown>;
};
type DiagnosticsScopeOptions = {
session?: string;
requestId?: string;
command?: string;
debug?: boolean;
logPath?: string;
traceLogPath?: string;
};
type DiagnosticsScope = DiagnosticsScopeOptions & {
diagnosticId: string;
events: DiagnosticEvent[];
};
const diagnosticsStorage = new AsyncLocalStorage<DiagnosticsScope>();
const SENSITIVE_KEY_RE = /(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i;
const SENSITIVE_VALUE_RE = /(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;
export function createRequestId(): string {
return crypto.randomBytes(8).toString('hex');
}
function createDiagnosticId(): string {
return `${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}`;
}
export async function withDiagnosticsScope<T>(
options: DiagnosticsScopeOptions,
fn: () => Promise<T> | T,
): Promise<T> {
const scope: DiagnosticsScope = {
...options,
diagnosticId: createDiagnosticId(),
events: [],
};
return await diagnosticsStorage.run(scope, fn);
}
export function getDiagnosticsMeta(): {
diagnosticId?: string;
requestId?: string;
session?: string;
command?: string;
debug?: boolean;
} {
const scope = diagnosticsStorage.getStore();
if (!scope) return {};
return {
diagnosticId: scope.diagnosticId,
requestId: scope.requestId,
session: scope.session,
command: scope.command,
debug: scope.debug,
};
}
export function emitDiagnostic(event: {
level?: DiagnosticLevel;
phase: string;
durationMs?: number;
data?: Record<string, unknown>;
}): void {
const scope = diagnosticsStorage.getStore();
if (!scope) return;
const payload: DiagnosticEvent = {
ts: new Date().toISOString(),
level: event.level ?? 'info',
phase: event.phase,
session: scope.session,
requestId: scope.requestId,
command: scope.command,
durationMs: event.durationMs,
data: event.data ? redactDiagnosticData(event.data) : undefined,
};
scope.events.push(payload);
if (!scope.debug) return;
const line = `[agent-device][diag] ${JSON.stringify(payload)}\n`;
try {
if (scope.logPath) {
fs.appendFile(scope.logPath, line, () => {});
}
if (scope.traceLogPath) {
fs.appendFile(scope.traceLogPath, line, () => {});
}
if (!scope.logPath && !scope.traceLogPath) process.stderr.write(line);
} catch {
// Best-effort diagnostics should not break request flow.
}
}
export async function withDiagnosticTimer<T>(
phase: string,
fn: () => Promise<T> | T,
data?: Record<string, unknown>,
): Promise<T> {
const start = Date.now();
try {
const result = await fn();
emitDiagnostic({
level: 'info',
phase,
durationMs: Date.now() - start,
data,
});
return result;
} catch (error) {
emitDiagnostic({
level: 'error',
phase,
durationMs: Date.now() - start,
data: {
...(data ?? {}),
error: error instanceof Error ? error.message : String(error),
},
});
throw error;
}
}
export function flushDiagnosticsToSessionFile(options: { force?: boolean } = {}): string | null {
const scope = diagnosticsStorage.getStore();
if (!scope) return null;
if (!options.force && !scope.debug) return null;
if (scope.events.length === 0) return null;
try {
const sessionDir = sanitizePathPart(scope.session ?? 'default');
const dayDir = new Date().toISOString().slice(0, 10);
const baseDir = path.join(os.homedir(), '.agent-device', 'logs', sessionDir, dayDir);
fs.mkdirSync(baseDir, { recursive: true });
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filePath = path.join(baseDir, `${timestamp}-${scope.diagnosticId}.ndjson`);
const lines = scope.events.map((entry) => JSON.stringify(redactDiagnosticData(entry)));
fs.writeFileSync(filePath, `${lines.join('\n')}\n`);
scope.events = [];
return filePath;
} catch {
return null;
}
}
export function redactDiagnosticData<T>(input: T): T {
return redactValue(input, new WeakSet<object>()) as T;
}
function redactValue(value: unknown, seen: WeakSet<object>, keyHint?: string): unknown {
if (value === null || value === undefined) return value;
if (typeof value === 'string') return redactString(value, keyHint);
if (typeof value !== 'object') return value;
if (seen.has(value as object)) return '[Circular]';
seen.add(value as object);
if (Array.isArray(value)) {
return value.map((entry) => redactValue(entry, seen));
}
const output: Record<string, unknown> = {};
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
if (SENSITIVE_KEY_RE.test(key)) {
output[key] = '[REDACTED]';
continue;
}
output[key] = redactValue(entry, seen, key);
}
return output;
}
function redactString(value: string, keyHint?: string): string {
const trimmed = value.trim();
if (!trimmed) return value;
if (keyHint && SENSITIVE_KEY_RE.test(keyHint)) return '[REDACTED]';
if (SENSITIVE_VALUE_RE.test(trimmed)) return '[REDACTED]';
const maskedUrl = redactUrl(trimmed);
if (maskedUrl) return maskedUrl;
if (trimmed.length > 400) return `${trimmed.slice(0, 200)}...<truncated>`;
return trimmed;
}
function redactUrl(value: string): string | null {
try {
const parsed = new URL(value);
if (parsed.search) parsed.search = '?REDACTED';
if (parsed.username || parsed.password) {
parsed.username = 'REDACTED';
parsed.password = 'REDACTED';
}
return parsed.toString();
} catch {
return null;
}
}
function sanitizePathPart(value: string): string {
return value.replace(/[^a-zA-Z0-9._-]/g, '_');
}