-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug.ts
More file actions
334 lines (291 loc) · 8.14 KB
/
debug.ts
File metadata and controls
334 lines (291 loc) · 8.14 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
330
331
332
333
334
/**
* Debug logging utilities for bashkit tools.
*
* Enable debug logging via environment variable:
* - BASHKIT_DEBUG=1 or BASHKIT_DEBUG=stderr - Human readable output to stderr
* - BASHKIT_DEBUG=json - JSON lines to stderr
* - BASHKIT_DEBUG=memory - In-memory array (retrieve via getDebugLogs())
* - BASHKIT_DEBUG=file:/path/to/trace.jsonl - Write to file
*/
import { AsyncLocalStorage } from "node:async_hooks";
import { appendFileSync } from "node:fs";
/** Debug event structure for tool execution tracing */
export interface DebugEvent {
/** Unique ID to correlate start/end events (e.g., "grep-1") */
id: string;
/** Timestamp in milliseconds */
ts: number;
/** Tool name */
tool: string;
/** Event type */
event: "start" | "end" | "error";
/** Input parameters (start events only, summarized) */
input?: unknown;
/** Output data (end events only, summarized) */
output?: unknown;
/** Key metrics like exitCode, matchCount, etc. */
summary?: Record<string, unknown>;
/** Duration in milliseconds (end events only) */
duration_ms?: number;
/** Parent event ID for nested tool calls (e.g., task → subagent tools) */
parent?: string;
/** Error message (error events only) */
error?: string;
}
type DebugMode = "off" | "stderr" | "json" | "memory" | "file";
interface DebugState {
mode: DebugMode;
filePath?: string;
logs: DebugEvent[];
counters: Map<string, number>;
}
// Global debug state
const state: DebugState = {
mode: "off",
logs: [],
counters: new Map(),
};
/** Per-async-context debug parent tracking */
interface DebugContext {
parentId: string;
depth: number;
}
const debugContext = new AsyncLocalStorage<DebugContext>();
// Truncation limits
const MAX_STRING_LENGTH = 4000;
const MAX_ARRAY_ITEMS = 20;
/**
* Initialize debug mode from environment variable.
* Called lazily on first debug operation.
*/
function initDebugMode(): void {
const envValue = process.env.BASHKIT_DEBUG;
if (!envValue) {
state.mode = "off";
return;
}
if (envValue === "1" || envValue === "stderr") {
state.mode = "stderr";
} else if (envValue === "json") {
state.mode = "json";
} else if (envValue === "memory") {
state.mode = "memory";
} else if (envValue.startsWith("file:")) {
state.mode = "file";
state.filePath = envValue.slice(5);
} else {
// Default to human-readable if unrecognized value
state.mode = "stderr";
}
}
// Initialize on module load
initDebugMode();
/**
* Checks if debug mode is enabled (any mode except "off").
*/
export function isDebugEnabled(): boolean {
return state.mode !== "off";
}
/**
* Generate a unique event ID for a tool call.
*/
function generateId(tool: string): string {
const count = (state.counters.get(tool) || 0) + 1;
state.counters.set(tool, count);
return `${tool}-${count}`;
}
/**
* Truncate a string to MAX_STRING_LENGTH with indicator.
*/
function truncateString(str: string): string {
if (str.length <= MAX_STRING_LENGTH) return str;
return `${str.slice(0, MAX_STRING_LENGTH)}... [truncated, ${str.length - MAX_STRING_LENGTH} more chars]`;
}
/**
* Summarize data for debug output.
* - Truncates strings to MAX_STRING_LENGTH chars
* - Limits arrays to MAX_ARRAY_ITEMS items
* - Recursively summarizes nested objects
*/
export function summarize(data: unknown, depth = 0): unknown {
// Prevent infinite recursion
if (depth > 5) return "[nested object]";
if (data === null || data === undefined) return data;
if (typeof data === "string") {
return truncateString(data);
}
if (typeof data === "number" || typeof data === "boolean") {
return data;
}
if (Array.isArray(data)) {
const truncated = data.length > MAX_ARRAY_ITEMS;
const items = data
.slice(0, MAX_ARRAY_ITEMS)
.map((item) => summarize(item, depth + 1));
if (truncated) {
return [...items, `[${data.length - MAX_ARRAY_ITEMS} more items]`];
}
return items;
}
if (typeof data === "object") {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(data)) {
result[key] = summarize(value, depth + 1);
}
return result;
}
return String(data);
}
/**
* Output a debug event according to current mode.
*/
function emitEvent(event: DebugEvent): void {
if (state.mode === "off") return;
switch (state.mode) {
case "memory":
state.logs.push(event);
break;
case "json":
process.stderr.write(`${JSON.stringify(event)}\n`);
break;
case "file":
if (state.filePath) {
appendFileSync(state.filePath, `${JSON.stringify(event)}\n`);
}
break;
case "stderr":
default:
formatHumanReadable(event);
break;
}
}
/**
* Format and output human-readable debug message.
*/
function formatHumanReadable(event: DebugEvent): void {
const ctx = debugContext.getStore();
const indent = " ".repeat(ctx?.depth ?? 0);
if (event.event === "start") {
const inputSummary = event.input
? Object.entries(event.input as Record<string, unknown>)
.map(([k, v]) => `${k}=${JSON.stringify(v)}`)
.slice(0, 3)
.join(" ")
: "";
process.stderr.write(
`${indent}[bashkit:${event.tool}] → ${inputSummary}\n`,
);
} else if (event.event === "end") {
const summaryStr = event.summary
? Object.entries(event.summary)
.map(([k, v]) => `${k}=${JSON.stringify(v)}`)
.join(" ")
: "";
process.stderr.write(
`${indent}[bashkit:${event.tool}] ← ${event.duration_ms}ms ${summaryStr}\n`,
);
} else if (event.event === "error") {
process.stderr.write(`${indent}[bashkit:${event.tool}] ✗ ${event.error}\n`);
}
}
/**
* Record the start of a tool execution.
* @returns Event ID to correlate with debugEnd/debugError
*/
export function debugStart(
tool: string,
input?: Record<string, unknown>,
): string {
if (state.mode === "off") return "";
const id = generateId(tool);
const ctx = debugContext.getStore();
const parent = ctx?.parentId;
const event: DebugEvent = {
id,
ts: Date.now(),
tool,
event: "start",
input: input ? summarize(input) : undefined,
parent,
};
emitEvent(event);
return id;
}
/**
* Record the successful end of a tool execution.
*/
export function debugEnd(
id: string,
tool: string,
options: {
output?: unknown;
summary?: Record<string, unknown>;
duration_ms: number;
},
): void {
if (state.mode === "off" || !id) return;
const event: DebugEvent = {
id,
ts: Date.now(),
tool,
event: "end",
output: options.output ? summarize(options.output) : undefined,
summary: options.summary,
duration_ms: options.duration_ms,
};
emitEvent(event);
}
/**
* Record an error during tool execution.
*/
export function debugError(
id: string,
tool: string,
error: string | Error,
): void {
if (state.mode === "off" || !id) return;
const event: DebugEvent = {
id,
ts: Date.now(),
tool,
event: "error",
error: error instanceof Error ? error.message : error,
};
emitEvent(event);
}
/**
* Run a function with a debug parent context.
* All tool calls within `fn` (including async continuations) will have
* their `parent` field set to `parentId`. Safe for parallel execution —
* each call gets its own isolated async context via AsyncLocalStorage.
*/
export function runWithDebugParent<T>(parentId: string, fn: () => T): T {
if (state.mode === "off" || !parentId) return fn();
const current = debugContext.getStore();
const depth = current ? current.depth + 1 : 1;
return debugContext.run({ parentId, depth }, fn);
}
/**
* Get all debug logs (memory mode only).
* @returns Array of debug events, or empty array if not in memory mode
*/
export function getDebugLogs(): DebugEvent[] {
return [...state.logs];
}
/**
* Clear all debug logs (memory mode).
* Call this between agent runs to reset the trace.
*/
export function clearDebugLogs(): void {
state.logs = [];
state.counters.clear();
}
/**
* Force re-initialization of debug mode from environment.
* Useful for testing or when environment changes.
*/
export function reinitDebugMode(): void {
state.logs = [];
state.counters.clear();
initDebugMode();
}