-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathClearcutLogger.ts
More file actions
280 lines (252 loc) · 7.6 KB
/
ClearcutLogger.ts
File metadata and controls
280 lines (252 loc) · 7.6 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
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import process from 'node:process';
import {DAEMON_CLIENT_NAME} from '../daemon/utils.js';
import {logger} from '../logger.js';
import type {zod, ShapeOutput} from '../third_party/index.js';
import type {LocalState, Persistence} from './persistence.js';
import {FilePersistence} from './persistence.js';
import {
McpClient,
type FlagUsage,
WatchdogMessageType,
OsType,
} from './types.js';
import {WatchdogClient} from './WatchdogClient.js';
const MS_PER_DAY = 24 * 60 * 60 * 1000;
export const PARAM_BLOCKLIST = new Set(['uid', 'reqid', 'msgid']);
const SUPPORTED_ZOD_TYPES = [
'ZodString',
'ZodNumber',
'ZodBoolean',
'ZodArray',
'ZodEnum',
] as const;
type ZodType = (typeof SUPPORTED_ZOD_TYPES)[number];
function isZodType(type: string): type is ZodType {
return SUPPORTED_ZOD_TYPES.includes(type as ZodType);
}
export function getZodType(zodType: zod.ZodTypeAny): ZodType {
const def = zodType._def;
const typeName = def.typeName;
if (
typeName === 'ZodOptional' ||
typeName === 'ZodDefault' ||
typeName === 'ZodNullable'
) {
return getZodType(def.innerType);
}
if (typeName === 'ZodEffects') {
return getZodType(def.schema);
}
if (isZodType(typeName)) {
return typeName;
}
throw new Error(`Unsupported zod type for tool parameter: ${typeName}`);
}
type LoggedToolCallArgValue = string | number | boolean;
export function transformArgName(zodType: ZodType, name: string): string {
if (zodType === 'ZodString') {
return `${name}_length`;
} else if (zodType === 'ZodArray') {
return `${name}_count`;
} else {
return name;
}
}
export function transformArgType(zodType: ZodType): string {
if (zodType === 'ZodString' || zodType === 'ZodArray') {
return 'number';
}
switch (zodType) {
case 'ZodNumber':
return 'number';
case 'ZodBoolean':
return 'boolean';
case 'ZodEnum':
return 'enum';
default:
throw new Error(`Unsupported zod type for tool parameter: ${zodType}`);
}
}
function transformValue(
zodType: ZodType,
value: unknown,
): LoggedToolCallArgValue {
if (zodType === 'ZodString') {
return (value as string).length;
} else if (zodType === 'ZodArray') {
return (value as unknown[]).length;
} else {
return value as LoggedToolCallArgValue;
}
}
function hasEquivalentType(zodType: ZodType, value: unknown): boolean {
if (zodType === 'ZodString') {
return typeof value === 'string';
} else if (zodType === 'ZodArray') {
return Array.isArray(value);
} else if (zodType === 'ZodNumber') {
return typeof value === 'number';
} else if (zodType === 'ZodBoolean') {
return typeof value === 'boolean';
} else if (zodType === 'ZodEnum') {
return (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean'
);
} else {
return false;
}
}
export function sanitizeParams(
params: ShapeOutput<zod.ZodRawShape>,
schema: zod.ZodRawShape,
): ShapeOutput<zod.ZodRawShape> {
const transformed: ShapeOutput<zod.ZodRawShape> = {};
for (const [name, value] of Object.entries(params)) {
if (PARAM_BLOCKLIST.has(name)) {
continue;
}
const zodType = getZodType(schema[name]);
if (!hasEquivalentType(zodType, value)) {
throw new Error(
`parameter ${name} has type ${zodType} but value ${value} is not of equivalent type`,
);
}
const transformedName = transformArgName(zodType, name);
const transformedValue = transformValue(zodType, value);
transformed[transformedName] = transformedValue;
}
return transformed;
}
function detectOsType(): OsType {
switch (process.platform) {
case 'win32':
return OsType.OS_TYPE_WINDOWS;
case 'darwin':
return OsType.OS_TYPE_MACOS;
case 'linux':
return OsType.OS_TYPE_LINUX;
default:
return OsType.OS_TYPE_UNSPECIFIED;
}
}
export class ClearcutLogger {
#persistence: Persistence;
#watchdog: WatchdogClient;
#mcpClient: McpClient;
constructor(options: {
appVersion: string;
logFile?: string;
persistence?: Persistence;
watchdogClient?: WatchdogClient;
clearcutEndpoint?: string;
clearcutForceFlushIntervalMs?: number;
clearcutIncludePidHeader?: boolean;
}) {
this.#persistence = options.persistence ?? new FilePersistence();
this.#watchdog =
options.watchdogClient ??
new WatchdogClient({
parentPid: process.pid,
appVersion: options.appVersion,
osType: detectOsType(),
logFile: options.logFile,
clearcutEndpoint: options.clearcutEndpoint,
clearcutForceFlushIntervalMs: options.clearcutForceFlushIntervalMs,
clearcutIncludePidHeader: options.clearcutIncludePidHeader,
});
this.#mcpClient = McpClient.MCP_CLIENT_UNSPECIFIED;
}
setClientName(clientName: string): void {
const lowerName = clientName.toLowerCase();
if (lowerName.includes('claude')) {
this.#mcpClient = McpClient.MCP_CLIENT_CLAUDE_CODE;
} else if (lowerName.includes('gemini')) {
this.#mcpClient = McpClient.MCP_CLIENT_GEMINI_CLI;
} else if (clientName === DAEMON_CLIENT_NAME) {
this.#mcpClient = McpClient.MCP_CLIENT_DT_MCP_CLI;
} else if (lowerName.includes('openclaw')) {
this.#mcpClient = McpClient.MCP_CLIENT_OPENCLAW;
} else if (lowerName.includes('codex')) {
this.#mcpClient = McpClient.MCP_CLIENT_CODEX;
} else if (lowerName.includes('antigravity')) {
this.#mcpClient = McpClient.MCP_CLIENT_ANTIGRAVITY;
} else {
this.#mcpClient = McpClient.MCP_CLIENT_OTHER;
}
}
async logToolInvocation(args: {
toolName: string;
success: boolean;
latencyMs: number;
}): Promise<void> {
this.#watchdog.send({
type: WatchdogMessageType.LOG_EVENT,
payload: {
mcp_client: this.#mcpClient,
tool_invocation: {
tool_name: args.toolName,
success: args.success,
latency_ms: args.latencyMs,
},
},
});
}
async logServerStart(flagUsage: FlagUsage): Promise<void> {
this.#watchdog.send({
type: WatchdogMessageType.LOG_EVENT,
payload: {
mcp_client: this.#mcpClient,
server_start: {
flag_usage: flagUsage,
},
},
});
}
async logDailyActiveIfNeeded(): Promise<void> {
try {
const state = await this.#persistence.loadState();
if (this.#shouldLogDailyActive(state)) {
let daysSince = -1;
if (state.lastActive) {
const lastActiveDate = new Date(state.lastActive);
const now = new Date();
const diffTime = Math.abs(now.getTime() - lastActiveDate.getTime());
daysSince = Math.ceil(diffTime / MS_PER_DAY);
}
this.#watchdog.send({
type: WatchdogMessageType.LOG_EVENT,
payload: {
mcp_client: this.#mcpClient,
daily_active: {
days_since_last_active: daysSince,
},
},
});
state.lastActive = new Date().toISOString();
await this.#persistence.saveState(state);
}
} catch (err) {
logger('Error in logDailyActiveIfNeeded:', err);
}
}
#shouldLogDailyActive(state: LocalState): boolean {
if (!state.lastActive) {
return true;
}
const lastActiveDate = new Date(state.lastActive);
const now = new Date();
// Compare UTC dates
const isSameDay =
lastActiveDate.getUTCFullYear() === now.getUTCFullYear() &&
lastActiveDate.getUTCMonth() === now.getUTCMonth() &&
lastActiveDate.getUTCDate() === now.getUTCDate();
return !isSameDay;
}
}