@neatlogs/claude-code 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1121 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ getConfigPath: () => getConfigPath,
34
+ handleHook: () => handleHook,
35
+ loadConfig: () => loadConfig,
36
+ registerHooks: () => registerHooks,
37
+ updateConfig: () => updateConfig
38
+ });
39
+ module.exports = __toCommonJS(src_exports);
40
+
41
+ // src/hook-handler.ts
42
+ var import_fs5 = require("fs");
43
+
44
+ // src/config.ts
45
+ var import_fs = require("fs");
46
+ var import_os = require("os");
47
+ var import_path = require("path");
48
+ var CONFIG_PATH = (0, import_path.join)((0, import_os.homedir)(), ".config", "neatlogs", "config.json");
49
+ function loadConfig() {
50
+ let file = {};
51
+ try {
52
+ if ((0, import_fs.existsSync)(CONFIG_PATH)) {
53
+ file = JSON.parse((0, import_fs.readFileSync)(CONFIG_PATH, "utf-8"));
54
+ }
55
+ } catch (err) {
56
+ console.warn(`[neatlogs/claude-code] Failed to read config: ${err.message}`);
57
+ }
58
+ const systemUser = (() => {
59
+ try {
60
+ return (0, import_os.userInfo)().username;
61
+ } catch (err) {
62
+ console.warn(`[neatlogs/claude-code] Could not resolve OS username: ${err.message}`);
63
+ return "unknown";
64
+ }
65
+ })();
66
+ return {
67
+ apiKey: process.env["NEATLOGS_API_KEY"] ?? file.api_key ?? "",
68
+ endpoint: process.env["NEATLOGS_ENDPOINT"] ?? file.endpoint ?? "https://staging-cloud.neatlogs.com",
69
+ userId: process.env["NEATLOGS_USER_ID"] ?? file.user_id ?? systemUser,
70
+ debug: process.env["NEATLOGS_DEBUG"] === "true" ? true : file.debug ?? false
71
+ };
72
+ }
73
+ function getConfigPath() {
74
+ return CONFIG_PATH;
75
+ }
76
+ function updateConfig(patch) {
77
+ const dir = (0, import_path.dirname)(CONFIG_PATH);
78
+ (0, import_fs.mkdirSync)(dir, { recursive: true });
79
+ let existing = {};
80
+ try {
81
+ if ((0, import_fs.existsSync)(CONFIG_PATH)) {
82
+ existing = JSON.parse((0, import_fs.readFileSync)(CONFIG_PATH, "utf-8"));
83
+ }
84
+ } catch (err) {
85
+ console.warn(`[neatlogs/claude-code] Failed to read existing config: ${err.message}`);
86
+ }
87
+ (0, import_fs.writeFileSync)(CONFIG_PATH, JSON.stringify({ ...existing, ...patch }, null, 2) + "\n", "utf-8");
88
+ }
89
+
90
+ // src/trace-shipper.ts
91
+ var import_protobufjs = __toESM(require("protobufjs"), 1);
92
+
93
+ // src/package-info.ts
94
+ var PACKAGE_NAME = "@neatlogs/claude-code";
95
+ var PACKAGE_VERSION = "0.1.0";
96
+
97
+ // src/trace-shipper.ts
98
+ var OTLP_PROTO_JSON = {
99
+ nested: {
100
+ opentelemetry: { nested: { proto: { nested: {
101
+ common: { nested: { v1: { nested: {
102
+ AnyValue: {
103
+ oneofs: { value: { oneof: ["stringValue", "boolValue", "intValue", "doubleValue", "arrayValue", "kvlistValue", "bytesValue"] } },
104
+ fields: {
105
+ stringValue: { type: "string", id: 1 },
106
+ boolValue: { type: "bool", id: 2 },
107
+ intValue: { type: "int64", id: 3 },
108
+ doubleValue: { type: "double", id: 4 },
109
+ arrayValue: { type: "ArrayValue", id: 5 },
110
+ kvlistValue: { type: "KeyValueList", id: 6 },
111
+ bytesValue: { type: "bytes", id: 7 }
112
+ }
113
+ },
114
+ ArrayValue: { fields: { values: { rule: "repeated", type: "AnyValue", id: 1 } } },
115
+ KeyValueList: { fields: { values: { rule: "repeated", type: "KeyValue", id: 1 } } },
116
+ KeyValue: { fields: { key: { type: "string", id: 1 }, value: { type: "AnyValue", id: 2 } } },
117
+ InstrumentationScope: { fields: { name: { type: "string", id: 1 }, version: { type: "string", id: 2 } } }
118
+ } } } },
119
+ resource: { nested: { v1: { nested: {
120
+ Resource: { fields: { attributes: { rule: "repeated", type: "opentelemetry.proto.common.v1.KeyValue", id: 1 } } }
121
+ } } } },
122
+ trace: { nested: { v1: { nested: {
123
+ ResourceSpans: { fields: {
124
+ resource: { type: "opentelemetry.proto.resource.v1.Resource", id: 1 },
125
+ scopeSpans: { rule: "repeated", type: "ScopeSpans", id: 2 }
126
+ } },
127
+ ScopeSpans: { fields: {
128
+ scope: { type: "opentelemetry.proto.common.v1.InstrumentationScope", id: 1 },
129
+ spans: { rule: "repeated", type: "Span", id: 2 }
130
+ } },
131
+ Span: { fields: {
132
+ traceId: { type: "bytes", id: 1 },
133
+ spanId: { type: "bytes", id: 2 },
134
+ traceState: { type: "string", id: 3 },
135
+ parentSpanId: { type: "bytes", id: 4 },
136
+ name: { type: "string", id: 5 },
137
+ kind: { type: "SpanKind", id: 6 },
138
+ startTimeUnixNano: { type: "fixed64", id: 7 },
139
+ endTimeUnixNano: { type: "fixed64", id: 8 },
140
+ attributes: { rule: "repeated", type: "opentelemetry.proto.common.v1.KeyValue", id: 9 },
141
+ droppedAttributesCount: { type: "uint32", id: 10 },
142
+ events: { rule: "repeated", type: "SpanEvent", id: 11 },
143
+ droppedEventsCount: { type: "uint32", id: 12 },
144
+ links: { rule: "repeated", type: "SpanLink", id: 13 },
145
+ droppedLinksCount: { type: "uint32", id: 14 },
146
+ status: { type: "Status", id: 15 }
147
+ } },
148
+ SpanEvent: { fields: {
149
+ timeUnixNano: { type: "fixed64", id: 1 },
150
+ name: { type: "string", id: 2 },
151
+ attributes: { rule: "repeated", type: "opentelemetry.proto.common.v1.KeyValue", id: 3 }
152
+ } },
153
+ SpanLink: { fields: {
154
+ traceId: { type: "bytes", id: 1 },
155
+ spanId: { type: "bytes", id: 2 },
156
+ traceState: { type: "string", id: 3 },
157
+ attributes: { rule: "repeated", type: "opentelemetry.proto.common.v1.KeyValue", id: 4 }
158
+ } },
159
+ Status: { fields: { message: { type: "string", id: 2 }, code: { type: "StatusCode", id: 3 } } },
160
+ StatusCode: { values: { STATUS_CODE_UNSET: 0, STATUS_CODE_OK: 1, STATUS_CODE_ERROR: 2 } },
161
+ SpanKind: { values: {
162
+ SPAN_KIND_UNSPECIFIED: 0,
163
+ SPAN_KIND_INTERNAL: 1,
164
+ SPAN_KIND_SERVER: 2,
165
+ SPAN_KIND_CLIENT: 3,
166
+ SPAN_KIND_PRODUCER: 4,
167
+ SPAN_KIND_CONSUMER: 5
168
+ } }
169
+ } } } },
170
+ collector: { nested: { trace: { nested: { v1: { nested: {
171
+ ExportTraceServiceRequest: { fields: { resourceSpans: { rule: "repeated", type: "opentelemetry.proto.trace.v1.ResourceSpans", id: 1 } } }
172
+ } } } } } }
173
+ } } } }
174
+ }
175
+ };
176
+ var protoRoot = import_protobufjs.default.Root.fromJSON(OTLP_PROTO_JSON);
177
+ var ExportTraceServiceRequest = protoRoot.lookupType(
178
+ "opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest"
179
+ );
180
+ var SpanStatusCode = { UNSET: 0, OK: 1, ERROR: 2 };
181
+ function randomBytes(length) {
182
+ const out = new Uint8Array(length);
183
+ const crypto = globalThis.crypto;
184
+ if (crypto && typeof crypto.getRandomValues === "function") {
185
+ crypto.getRandomValues(out);
186
+ return out;
187
+ }
188
+ for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
189
+ return out;
190
+ }
191
+ function generateTraceId() {
192
+ return randomBytes(16);
193
+ }
194
+ function generateSpanId() {
195
+ return randomBytes(8);
196
+ }
197
+ function bytesToHex(bytes) {
198
+ return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
199
+ }
200
+ function hexToBytes(hex) {
201
+ const bytes = new Uint8Array(hex.length / 2);
202
+ for (let i = 0; i < hex.length; i += 2) {
203
+ bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
204
+ }
205
+ return bytes;
206
+ }
207
+ function nowNanoString() {
208
+ return (BigInt(Date.now()) * 1000000n).toString();
209
+ }
210
+ function msToNanoString(ms) {
211
+ return (BigInt(ms) * 1000000n).toString();
212
+ }
213
+ function attrString(key, value) {
214
+ if (value === void 0) return void 0;
215
+ return { key, value: { stringValue: value } };
216
+ }
217
+ function attrInt(key, value) {
218
+ if (value === void 0 || !Number.isFinite(value)) return void 0;
219
+ return { key, value: { intValue: String(Math.trunc(value)) } };
220
+ }
221
+ var TraceShipper = class {
222
+ apiKey;
223
+ endpoint;
224
+ debug;
225
+ maxRetries;
226
+ workflowName;
227
+ queue = [];
228
+ prefix = "[neatlogs/claude-code]";
229
+ constructor(opts) {
230
+ this.apiKey = opts.apiKey;
231
+ this.endpoint = opts.endpoint.endsWith("/") ? opts.endpoint.slice(0, -1) : opts.endpoint;
232
+ this.debug = opts.debug;
233
+ this.maxRetries = opts.maxRetries ?? 3;
234
+ this.workflowName = opts.workflowName || "";
235
+ }
236
+ enqueue(span) {
237
+ this.queue.push(span);
238
+ }
239
+ async flush() {
240
+ if (this.queue.length === 0) return;
241
+ if (!this.apiKey) {
242
+ if (this.debug) console.warn(`${this.prefix} No API key \u2014 skipping export`);
243
+ this.queue = [];
244
+ return;
245
+ }
246
+ const spans = this.queue.splice(0);
247
+ const payload = this.buildProtobuf(spans);
248
+ const url = `${this.endpoint}/v1/traces`;
249
+ if (this.debug) {
250
+ console.log(`${this.prefix} Shipping ${spans.length} spans to ${url}`);
251
+ }
252
+ for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
253
+ try {
254
+ const resp = await fetch(url, {
255
+ method: "POST",
256
+ headers: {
257
+ "Content-Type": "application/x-protobuf",
258
+ "x-api-key": this.apiKey
259
+ },
260
+ body: payload
261
+ });
262
+ if (resp.ok) {
263
+ if (this.debug) console.log(`${this.prefix} Shipped ${spans.length} spans`);
264
+ return;
265
+ }
266
+ if (resp.status === 401) {
267
+ console.warn(`${this.prefix} Invalid API key (401) \u2014 dropping ${spans.length} spans`);
268
+ return;
269
+ }
270
+ if (resp.status < 500 && resp.status !== 429) {
271
+ const text = await resp.text().catch(() => "");
272
+ console.warn(`${this.prefix} Server returned ${resp.status}: ${text} \u2014 dropping spans`);
273
+ return;
274
+ }
275
+ if (this.debug) {
276
+ console.warn(`${this.prefix} Attempt ${attempt}/${this.maxRetries} failed: HTTP ${resp.status}`);
277
+ }
278
+ } catch (err) {
279
+ if (this.debug) {
280
+ console.warn(`${this.prefix} Attempt ${attempt}/${this.maxRetries} error: ${err.message}`);
281
+ }
282
+ }
283
+ if (attempt < this.maxRetries) {
284
+ await new Promise((r) => setTimeout(r, 500 * Math.pow(2, attempt - 1)));
285
+ }
286
+ }
287
+ console.warn(`${this.prefix} Failed to ship ${spans.length} spans after ${this.maxRetries} attempts`);
288
+ }
289
+ async shutdown() {
290
+ await this.flush();
291
+ }
292
+ buildProtobuf(spans) {
293
+ const protoSpans = spans.map((span) => ({
294
+ traceId: span.traceId,
295
+ spanId: span.spanId,
296
+ parentSpanId: span.parentSpanId || void 0,
297
+ name: span.name,
298
+ kind: span.kind,
299
+ startTimeUnixNano: this.nanoStringToLong(span.startTimeUnixNano),
300
+ endTimeUnixNano: this.nanoStringToLong(span.endTimeUnixNano),
301
+ attributes: span.attributes.map((a) => ({
302
+ key: a.key,
303
+ value: a.value.intValue !== void 0 ? { intValue: this.nanoStringToLong(a.value.intValue) } : a.value
304
+ })),
305
+ status: span.status ? { code: span.status.code, message: span.status.message } : void 0
306
+ }));
307
+ const resourceAttributes = [
308
+ { key: "service.name", value: { stringValue: "neatlogs.claude-code" } },
309
+ { key: "service.version", value: { stringValue: PACKAGE_VERSION } }
310
+ ];
311
+ if (this.workflowName) {
312
+ resourceAttributes.push({ key: "neatlogs.workflow_name", value: { stringValue: this.workflowName } });
313
+ }
314
+ const message = {
315
+ resourceSpans: [{
316
+ resource: { attributes: resourceAttributes },
317
+ scopeSpans: [{
318
+ scope: { name: PACKAGE_NAME, version: PACKAGE_VERSION },
319
+ spans: protoSpans
320
+ }]
321
+ }]
322
+ };
323
+ const errMsg = ExportTraceServiceRequest.verify(message);
324
+ if (errMsg && this.debug) {
325
+ console.warn(`${this.prefix} Proto verification warning: ${errMsg}`);
326
+ }
327
+ return ExportTraceServiceRequest.encode(
328
+ ExportTraceServiceRequest.fromObject(message)
329
+ ).finish();
330
+ }
331
+ nanoStringToLong(nanoStr) {
332
+ const big = BigInt(nanoStr);
333
+ const low = Number(big & 0xFFFFFFFFn);
334
+ const high = Number(big >> 32n & 0xFFFFFFFFn);
335
+ return { low, high, unsigned: true };
336
+ }
337
+ };
338
+
339
+ // src/event-mapper.ts
340
+ var import_fs4 = require("fs");
341
+
342
+ // src/state.ts
343
+ var import_fs2 = require("fs");
344
+ var import_os2 = require("os");
345
+ var import_path2 = require("path");
346
+ var STATE_DIR = (0, import_path2.join)((0, import_os2.tmpdir)(), "neatlogs-claude-code");
347
+ function ensureStateDir() {
348
+ (0, import_fs2.mkdirSync)(STATE_DIR, { recursive: true });
349
+ }
350
+ function safeKey(key) {
351
+ return key.replace(/[^a-zA-Z0-9_\-]/g, "_");
352
+ }
353
+ function statePath(key) {
354
+ const sanitized = safeKey(key);
355
+ const full = (0, import_path2.join)(STATE_DIR, sanitized);
356
+ if (!full.startsWith(STATE_DIR)) {
357
+ throw new Error("Path traversal detected");
358
+ }
359
+ return full;
360
+ }
361
+ function writeState(key, value) {
362
+ ensureStateDir();
363
+ (0, import_fs2.writeFileSync)(statePath(key), value, "utf-8");
364
+ }
365
+ function readState(key) {
366
+ const filePath = statePath(key);
367
+ if (!(0, import_fs2.existsSync)(filePath)) return void 0;
368
+ return (0, import_fs2.readFileSync)(filePath, "utf-8");
369
+ }
370
+ function deleteState(key) {
371
+ const filePath = statePath(key);
372
+ if ((0, import_fs2.existsSync)(filePath)) {
373
+ (0, import_fs2.unlinkSync)(filePath);
374
+ }
375
+ }
376
+ function listStateFiles(prefix) {
377
+ if (!(0, import_fs2.existsSync)(STATE_DIR)) return [];
378
+ return (0, import_fs2.readdirSync)(STATE_DIR).filter((f) => f.startsWith(safeKey(prefix)));
379
+ }
380
+ function cleanupStateFiles(prefix) {
381
+ for (const file of listStateFiles(prefix)) {
382
+ (0, import_fs2.unlinkSync)((0, import_path2.join)(STATE_DIR, file));
383
+ }
384
+ }
385
+
386
+ // src/transcript.ts
387
+ var import_fs3 = require("fs");
388
+ function isToolResultContentBlock(value) {
389
+ return Boolean(
390
+ value && typeof value === "object" && "type" in value && value.type === "tool_result"
391
+ );
392
+ }
393
+ function isTopLevelUserPrompt(entry) {
394
+ if (entry.type !== "user") return false;
395
+ const content = entry.message?.content;
396
+ if (typeof content === "string") return true;
397
+ if (!Array.isArray(content)) return false;
398
+ return content.some((block) => !isToolResultContentBlock(block));
399
+ }
400
+ function isToolResultUserEntry(entry) {
401
+ if (entry.type !== "user") return false;
402
+ const content = entry.message?.content;
403
+ if (!Array.isArray(content)) return false;
404
+ return content.length > 0 && content.every((b) => isToolResultContentBlock(b));
405
+ }
406
+ function parseTranscript(transcriptPath) {
407
+ if (!(0, import_fs3.existsSync)(transcriptPath)) return void 0;
408
+ const content = (0, import_fs3.readFileSync)(transcriptPath, "utf-8");
409
+ const lines = content.split("\n").filter((l) => l.trim());
410
+ const summary = {
411
+ totalInputTokens: 0,
412
+ totalOutputTokens: 0,
413
+ totalCacheReadTokens: 0,
414
+ totalCacheCreationTokens: 0,
415
+ turnCount: 0,
416
+ toolsUsed: [],
417
+ hasThinking: false,
418
+ lastTurnTextBlocks: [],
419
+ llmCallPhases: []
420
+ };
421
+ const toolNames = /* @__PURE__ */ new Set();
422
+ let lastUsage;
423
+ let currentTurnTextBlocks = [];
424
+ let currentPhases = [];
425
+ let activePhase;
426
+ function finalizePhase() {
427
+ if (activePhase && (activePhase.text || activePhase.thinking || activePhase.toolCalls.length > 0)) {
428
+ currentPhases.push(activePhase);
429
+ }
430
+ activePhase = void 0;
431
+ }
432
+ function ensurePhase() {
433
+ if (!activePhase) {
434
+ activePhase = { text: "", thinking: "", toolCalls: [], inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, hasThinking: false };
435
+ }
436
+ return activePhase;
437
+ }
438
+ for (const line of lines) {
439
+ let entry;
440
+ try {
441
+ entry = JSON.parse(line);
442
+ } catch (err) {
443
+ if (process.env["NEATLOGS_DEBUG"] === "true") {
444
+ console.warn(`[neatlogs/claude-code] Skipping malformed transcript line: ${err.message}`);
445
+ }
446
+ continue;
447
+ }
448
+ if (entry.type === "system" && entry.subtype === "turn_duration") {
449
+ if (typeof entry.durationMs === "number") {
450
+ summary.totalDurationMs = (summary.totalDurationMs ?? 0) + entry.durationMs;
451
+ }
452
+ if (typeof entry.version === "string") summary.codeVersion = entry.version;
453
+ if (typeof entry.gitBranch === "string") summary.gitBranch = entry.gitBranch;
454
+ continue;
455
+ }
456
+ if (isTopLevelUserPrompt(entry)) {
457
+ currentTurnTextBlocks = [];
458
+ finalizePhase();
459
+ currentPhases = [];
460
+ }
461
+ if (isToolResultUserEntry(entry)) {
462
+ finalizePhase();
463
+ continue;
464
+ }
465
+ if (entry.type !== "assistant") continue;
466
+ const msg = entry.message;
467
+ if (!msg) continue;
468
+ summary.turnCount++;
469
+ if (typeof msg.model === "string") summary.model = msg.model;
470
+ if (typeof msg.stop_reason === "string") summary.stopReason = msg.stop_reason;
471
+ if (typeof entry.version === "string") summary.codeVersion = entry.version;
472
+ if (typeof entry.gitBranch === "string") summary.gitBranch = entry.gitBranch;
473
+ const usage = msg.usage;
474
+ if (usage) {
475
+ summary.totalInputTokens += usage.input_tokens ?? 0;
476
+ summary.totalOutputTokens += usage.output_tokens ?? 0;
477
+ summary.totalCacheReadTokens += usage.cache_read_input_tokens ?? 0;
478
+ summary.totalCacheCreationTokens += usage.cache_creation_input_tokens ?? 0;
479
+ if (typeof usage.service_tier === "string") summary.serviceTier = usage.service_tier;
480
+ lastUsage = usage;
481
+ }
482
+ const phase = ensurePhase();
483
+ const entryTimestamp = typeof entry.timestamp === "string" ? entry.timestamp : void 0;
484
+ if (entryTimestamp) {
485
+ if (!phase.startTimestamp) phase.startTimestamp = entryTimestamp;
486
+ phase.endTimestamp = entryTimestamp;
487
+ }
488
+ if (typeof msg.model === "string") phase.model = msg.model;
489
+ if (usage) {
490
+ phase.inputTokens += usage.input_tokens ?? 0;
491
+ phase.outputTokens += usage.output_tokens ?? 0;
492
+ phase.cacheReadTokens += usage.cache_read_input_tokens ?? 0;
493
+ phase.cacheWriteTokens += usage.cache_creation_input_tokens ?? 0;
494
+ }
495
+ const msgContent = msg.content;
496
+ if (Array.isArray(msgContent)) {
497
+ for (const block of msgContent) {
498
+ if (block.type === "tool_use" && typeof block.name === "string") {
499
+ toolNames.add(block.name);
500
+ phase.toolCalls.push({ id: block.id, name: block.name, input: block.input });
501
+ }
502
+ if (block.type === "thinking") {
503
+ summary.hasThinking = true;
504
+ phase.hasThinking = true;
505
+ if (typeof block.thinking === "string" && block.thinking.trim()) {
506
+ phase.thinking = phase.thinking ? phase.thinking + "\n" + block.thinking : block.thinking;
507
+ }
508
+ }
509
+ if (block.type === "text" && typeof block.text === "string" && block.text.trim()) {
510
+ currentTurnTextBlocks.push(block.text);
511
+ phase.text = phase.text ? phase.text + "\n" + block.text : block.text;
512
+ }
513
+ }
514
+ summary.lastTurnTextBlocks = [...currentTurnTextBlocks];
515
+ }
516
+ }
517
+ finalizePhase();
518
+ if (lastUsage) {
519
+ summary.lastTurnInputTokens = lastUsage.input_tokens;
520
+ summary.lastTurnOutputTokens = lastUsage.output_tokens;
521
+ summary.lastTurnCacheReadTokens = lastUsage.cache_read_input_tokens;
522
+ }
523
+ summary.toolsUsed = [...toolNames].sort();
524
+ if (summary.lastTurnTextBlocks.length > 0) {
525
+ summary.lastTurnFullOutput = summary.lastTurnTextBlocks.join("\n\n");
526
+ }
527
+ summary.llmCallPhases = currentPhases;
528
+ return summary;
529
+ }
530
+
531
+ // src/event-mapper.ts
532
+ function safeStringify(value) {
533
+ if (value === void 0 || value === null) return void 0;
534
+ try {
535
+ return JSON.stringify(value);
536
+ } catch (err) {
537
+ console.warn(`[neatlogs/claude-code] JSON.stringify failed: ${err.message}`);
538
+ return String(value);
539
+ }
540
+ }
541
+ function sessionTraceKey(sessionId) {
542
+ return `trace_${sessionId}`;
543
+ }
544
+ function turnSpanKey(sessionId) {
545
+ return `turn_${sessionId}`;
546
+ }
547
+ function subagentSpanKey(agentId) {
548
+ return `subagentspan_${agentId}`;
549
+ }
550
+ function saveSpanContext(key, ctx) {
551
+ writeState(key, JSON.stringify(ctx));
552
+ }
553
+ function readSpanContext(key) {
554
+ const raw = readState(key);
555
+ if (!raw) return void 0;
556
+ try {
557
+ return JSON.parse(raw);
558
+ } catch {
559
+ return void 0;
560
+ }
561
+ }
562
+ function getSessionTrace(sessionId) {
563
+ return readSpanContext(sessionTraceKey(sessionId));
564
+ }
565
+ function getTurnParent(payload) {
566
+ if (payload.agent_id) {
567
+ const sub = readSpanContext(subagentSpanKey(payload.agent_id));
568
+ if (sub) return sub;
569
+ }
570
+ return readSpanContext(turnSpanKey(payload.session_id));
571
+ }
572
+ function deriveWorkflowName(payload) {
573
+ if (payload.prompt) {
574
+ return payload.prompt.slice(0, 60).replace(/\n/g, " ").trim() || "claude-code";
575
+ }
576
+ return "claude-code";
577
+ }
578
+ function ensureSessionTrace(payload, config, shipper) {
579
+ const existing = getSessionTrace(payload.session_id);
580
+ if (existing) return existing;
581
+ const model = readState(`model_${payload.session_id}`) || void 0;
582
+ const workflowName = deriveWorkflowName(payload);
583
+ writeState(`workflow_${payload.session_id}`, workflowName);
584
+ const traceId = generateTraceId();
585
+ const spanId = generateSpanId();
586
+ const now = nowNanoString();
587
+ const rootSpan = {
588
+ traceId,
589
+ spanId,
590
+ name: workflowName,
591
+ kind: 1,
592
+ startTimeUnixNano: now,
593
+ endTimeUnixNano: now,
594
+ attributes: [
595
+ { key: "neatlogs.span.kind", value: { stringValue: "WORKFLOW" } },
596
+ attrString("neatlogs.llm.request_type", "generateText"),
597
+ attrString("neatlogs.llm.model_name", model),
598
+ attrString("neatlogs.llm.provider", "anthropic"),
599
+ attrString("neatlogs.user_id", config.userId),
600
+ attrString("neatlogs.session_id", payload.session_id),
601
+ attrString("neatlogs.workflow_name", workflowName),
602
+ attrString("neatlogs.input.value", payload.prompt),
603
+ attrString("cwd", payload.cwd),
604
+ { key: "neatlogs.sdk.name", value: { stringValue: PACKAGE_NAME } },
605
+ { key: "neatlogs.sdk.version", value: { stringValue: PACKAGE_VERSION } }
606
+ ].filter((a) => a !== void 0),
607
+ status: { code: SpanStatusCode.OK }
608
+ };
609
+ shipper.enqueue(rootSpan);
610
+ const ctx = { traceIdHex: bytesToHex(traceId), spanIdHex: bytesToHex(spanId) };
611
+ saveSpanContext(sessionTraceKey(payload.session_id), ctx);
612
+ return ctx;
613
+ }
614
+ function isoToNanoString(iso, fallback) {
615
+ const ms = new Date(iso).getTime();
616
+ if (!Number.isFinite(ms)) return fallback;
617
+ return msToNanoString(ms);
618
+ }
619
+ function createSpan(name, parent, startNano, endNano, attributes, status) {
620
+ const traceId = parent ? hexToBytes(parent.traceIdHex) : generateTraceId();
621
+ const spanId = generateSpanId();
622
+ return {
623
+ traceId,
624
+ spanId,
625
+ parentSpanId: parent ? hexToBytes(parent.spanIdHex) : void 0,
626
+ name,
627
+ kind: 1,
628
+ startTimeUnixNano: startNano,
629
+ endTimeUnixNano: endNano,
630
+ attributes: attributes.filter((a) => a !== void 0),
631
+ status
632
+ };
633
+ }
634
+ function mapHookEvent(payload, config, shipper) {
635
+ switch (payload.hook_event_name) {
636
+ case "SessionStart":
637
+ handleSessionStart(payload, config, shipper);
638
+ break;
639
+ case "UserPromptSubmit":
640
+ handleUserPromptSubmit(payload, config, shipper);
641
+ break;
642
+ case "PreToolUse":
643
+ if (payload.tool_use_id) {
644
+ writeState(`tool_${payload.tool_use_id}`, String(Date.now()));
645
+ }
646
+ break;
647
+ case "PostToolUse":
648
+ handlePostToolUse(payload, config, shipper);
649
+ break;
650
+ case "PostToolUseFailure":
651
+ handlePostToolUse(payload, config, shipper, payload.error ?? "Tool execution failed");
652
+ break;
653
+ case "SubagentStart":
654
+ handleSubagentStart(payload, config, shipper);
655
+ break;
656
+ case "SubagentStop":
657
+ handleSubagentStop(payload, config, shipper);
658
+ break;
659
+ case "PermissionDenied":
660
+ handlePermissionDenied(payload, config, shipper);
661
+ break;
662
+ case "Stop":
663
+ handleStop(payload, config, shipper);
664
+ break;
665
+ case "StopFailure":
666
+ handleStop(payload, config, shipper, { error: payload.error, errorDetails: payload.error_details });
667
+ break;
668
+ case "InstructionsLoaded":
669
+ handleInstructionsLoaded(payload);
670
+ break;
671
+ case "PostCompact":
672
+ handlePostCompact(payload, config, shipper);
673
+ break;
674
+ case "SessionEnd":
675
+ handleSessionEnd(payload, config, shipper);
676
+ break;
677
+ default:
678
+ if (config.debug) {
679
+ console.log(`[neatlogs/claude-code] Ignoring unhandled event: ${payload.hook_event_name}`);
680
+ }
681
+ }
682
+ }
683
+ function handleSessionStart(payload, config, shipper) {
684
+ writeState(`model_${payload.session_id}`, payload.model ?? "");
685
+ ensureSessionTrace(payload, config, shipper);
686
+ }
687
+ function handleUserPromptSubmit(payload, config, shipper) {
688
+ const sessionCtx = ensureSessionTrace(payload, config, shipper);
689
+ if (payload.prompt) {
690
+ const name = payload.prompt.slice(0, 60).replace(/\n/g, " ").trim() || "claude-code";
691
+ writeState(`workflow_${payload.session_id}`, name);
692
+ }
693
+ const now = nowNanoString();
694
+ const turnSpanId = generateSpanId();
695
+ const turnSpan = {
696
+ traceId: hexToBytes(sessionCtx.traceIdHex),
697
+ spanId: turnSpanId,
698
+ parentSpanId: hexToBytes(sessionCtx.spanIdHex),
699
+ name: payload.prompt?.slice(0, 80) || "turn",
700
+ kind: 1,
701
+ startTimeUnixNano: now,
702
+ endTimeUnixNano: now,
703
+ attributes: [
704
+ { key: "neatlogs.span.kind", value: { stringValue: "CHAIN" } },
705
+ attrString("neatlogs.input.value", payload.prompt),
706
+ attrString("cwd", payload.cwd)
707
+ ].filter((a) => a !== void 0)
708
+ };
709
+ shipper.enqueue(turnSpan);
710
+ const turnCtx = { traceIdHex: sessionCtx.traceIdHex, spanIdHex: bytesToHex(turnSpanId) };
711
+ saveSpanContext(turnSpanKey(payload.session_id), turnCtx);
712
+ writeState(`turnstart_${payload.session_id}`, String(Date.now()));
713
+ }
714
+ function handlePostToolUse(payload, config, shipper, error) {
715
+ ensureSessionTrace(payload, config, shipper);
716
+ const parent = getTurnParent(payload);
717
+ const endMs = Date.now();
718
+ const durationMs = payload.duration_ms ?? 0;
719
+ const startMs = durationMs > 0 ? endMs - durationMs : endMs;
720
+ const span = createSpan(
721
+ payload.tool_name ?? "tool",
722
+ parent,
723
+ msToNanoString(startMs),
724
+ msToNanoString(endMs),
725
+ [
726
+ attrString("neatlogs.span.kind", "TOOL"),
727
+ attrString("neatlogs.tool.name", payload.tool_name),
728
+ attrString("neatlogs.tool_call.id", payload.tool_use_id),
729
+ attrString("neatlogs.tool.input", safeStringify(payload.tool_input)),
730
+ attrString("neatlogs.tool.output", safeStringify(payload.tool_response)),
731
+ attrInt("neatlogs.llm.metrics.duration_ms", durationMs)
732
+ ],
733
+ error ? { code: SpanStatusCode.ERROR, message: error } : void 0
734
+ );
735
+ shipper.enqueue(span);
736
+ if (payload.permission_mode === "plan") {
737
+ const sessionCtx = getSessionTrace(payload.session_id);
738
+ if (sessionCtx) {
739
+ const markerNow = nowNanoString();
740
+ const marker = createSpan("neatlogs.trace.complete", sessionCtx, markerNow, markerNow, []);
741
+ shipper.enqueue(marker);
742
+ }
743
+ }
744
+ }
745
+ function handleSubagentStart(payload, config, shipper) {
746
+ ensureSessionTrace(payload, config, shipper);
747
+ const parent = getTurnParent(payload);
748
+ if (payload.agent_id) {
749
+ writeState(`subagent_${payload.agent_id}`, String(Date.now()));
750
+ }
751
+ const now = nowNanoString();
752
+ const traceId = parent ? hexToBytes(parent.traceIdHex) : generateTraceId();
753
+ const spanId = generateSpanId();
754
+ const span = {
755
+ traceId,
756
+ spanId,
757
+ parentSpanId: parent ? hexToBytes(parent.spanIdHex) : void 0,
758
+ name: payload.agent_type ?? "subagent",
759
+ kind: 1,
760
+ startTimeUnixNano: now,
761
+ endTimeUnixNano: now,
762
+ attributes: [
763
+ { key: "neatlogs.span.kind", value: { stringValue: "AGENT" } },
764
+ attrString("neatlogs.agent.name", payload.agent_type),
765
+ attrString("neatlogs.agent_id", payload.agent_id)
766
+ ].filter((a) => a !== void 0)
767
+ };
768
+ shipper.enqueue(span);
769
+ if (payload.agent_id) {
770
+ saveSpanContext(subagentSpanKey(payload.agent_id), {
771
+ traceIdHex: bytesToHex(traceId),
772
+ spanIdHex: bytesToHex(spanId)
773
+ });
774
+ }
775
+ }
776
+ function handleSubagentStop(payload, config, shipper) {
777
+ ensureSessionTrace(payload, config, shipper);
778
+ const endMs = Date.now();
779
+ const savedStartRaw = payload.agent_id ? readState(`subagent_${payload.agent_id}`) : void 0;
780
+ const savedStartMs = savedStartRaw ? parseInt(savedStartRaw, 10) : void 0;
781
+ const startMs = savedStartMs && Number.isFinite(savedStartMs) && savedStartMs <= endMs ? savedStartMs : endMs;
782
+ let agentInput;
783
+ if (payload.agent_transcript_path && (0, import_fs4.existsSync)(payload.agent_transcript_path)) {
784
+ const summary = parseTranscript(payload.agent_transcript_path);
785
+ if (summary?.lastTurnTextBlocks.length) {
786
+ agentInput = summary.lastTurnTextBlocks[0];
787
+ }
788
+ }
789
+ const parent = getTurnParent(payload);
790
+ const span = createSpan(
791
+ payload.agent_type ?? "subagent",
792
+ parent,
793
+ msToNanoString(startMs),
794
+ msToNanoString(endMs),
795
+ [
796
+ attrString("neatlogs.span.kind", "AGENT"),
797
+ attrString("neatlogs.agent.name", payload.agent_type),
798
+ attrString("neatlogs.agent_id", payload.agent_id),
799
+ attrString("neatlogs.input.value", agentInput),
800
+ attrString("neatlogs.output.value", payload.last_assistant_message),
801
+ attrInt("neatlogs.llm.metrics.duration_ms", endMs - startMs)
802
+ ]
803
+ );
804
+ shipper.enqueue(span);
805
+ if (payload.agent_id) {
806
+ deleteState(`subagent_${payload.agent_id}`);
807
+ deleteState(subagentSpanKey(payload.agent_id));
808
+ }
809
+ }
810
+ function handlePermissionDenied(payload, config, shipper) {
811
+ ensureSessionTrace(payload, config, shipper);
812
+ const parent = getTurnParent(payload);
813
+ const now = nowNanoString();
814
+ const span = createSpan(
815
+ payload.tool_name ?? "permission_denied",
816
+ parent,
817
+ now,
818
+ now,
819
+ [
820
+ attrString("neatlogs.span.kind", "TOOL"),
821
+ attrString("neatlogs.tool.name", payload.tool_name),
822
+ attrString("neatlogs.tool_call.id", payload.tool_use_id),
823
+ attrString("neatlogs.tool.input", safeStringify(payload.tool_input)),
824
+ attrString("neatlogs.tool.output", payload.reason ?? "Permission denied"),
825
+ attrString("error.message", payload.reason ?? "Permission denied")
826
+ ],
827
+ { code: SpanStatusCode.ERROR, message: payload.reason ?? "Permission denied" }
828
+ );
829
+ shipper.enqueue(span);
830
+ }
831
+ function handleStop(payload, config, shipper, extra) {
832
+ ensureSessionTrace(payload, config, shipper);
833
+ const turnParent = getTurnParent(payload);
834
+ let emittedLLMSpan = false;
835
+ if (payload.transcript_path) {
836
+ const summary = parseTranscript(payload.transcript_path);
837
+ if (config.debug) {
838
+ (0, import_fs4.appendFileSync)("/tmp/neatlogs-hook-debug.log", `[${(/* @__PURE__ */ new Date()).toISOString()}] handleStop: transcript_path=${payload.transcript_path}, summary=${!!summary}, phases=${summary?.llmCallPhases.length ?? 0}, hasThinking=${summary?.hasThinking}
839
+ `);
840
+ if (summary) {
841
+ for (let i = 0; i < Math.min(summary.llmCallPhases.length, 5); i++) {
842
+ const p = summary.llmCallPhases[i];
843
+ (0, import_fs4.appendFileSync)("/tmp/neatlogs-hook-debug.log", `[${(/* @__PURE__ */ new Date()).toISOString()}] phase[${i}]: text=${p.text.length} thinking=${p.thinking.length} tools=${p.toolCalls.length}
844
+ `);
845
+ }
846
+ }
847
+ }
848
+ if (summary && summary.llmCallPhases.length > 0) {
849
+ emitLLMPhaseSpans(payload, summary, shipper, turnParent, config);
850
+ emittedLLMSpan = true;
851
+ }
852
+ }
853
+ if (!emittedLLMSpan && payload.last_assistant_message) {
854
+ const model = readState(`model_${payload.session_id}`) || "claude";
855
+ const now = nowNanoString();
856
+ const span = createSpan(
857
+ model,
858
+ turnParent,
859
+ now,
860
+ now,
861
+ [
862
+ attrString("neatlogs.span.kind", "LLM"),
863
+ attrString("neatlogs.llm.request_type", "generateText"),
864
+ attrString("neatlogs.llm.model_name", model),
865
+ attrString("neatlogs.llm.provider", "anthropic"),
866
+ attrString("neatlogs.output.value", payload.last_assistant_message)
867
+ ]
868
+ );
869
+ shipper.enqueue(span);
870
+ }
871
+ if (extra?.error) {
872
+ const now = nowNanoString();
873
+ const span = createSpan(
874
+ "stop_failure",
875
+ turnParent,
876
+ now,
877
+ now,
878
+ [
879
+ attrString("neatlogs.span.kind", "CHAIN"),
880
+ attrString("error.message", extra.error),
881
+ attrString("error.details", extra.errorDetails)
882
+ ],
883
+ { code: SpanStatusCode.ERROR, message: extra.error }
884
+ );
885
+ shipper.enqueue(span);
886
+ }
887
+ const sessionCtx = getSessionTrace(payload.session_id);
888
+ if (sessionCtx) {
889
+ const now = nowNanoString();
890
+ const marker = createSpan(
891
+ "neatlogs.trace.complete",
892
+ sessionCtx,
893
+ now,
894
+ now,
895
+ []
896
+ );
897
+ shipper.enqueue(marker);
898
+ }
899
+ }
900
+ function handlePostCompact(payload, config, shipper) {
901
+ ensureSessionTrace(payload, config, shipper);
902
+ const parent = getTurnParent(payload) ?? getSessionTrace(payload.session_id);
903
+ const now = nowNanoString();
904
+ const span = createSpan(
905
+ "context_compaction",
906
+ parent,
907
+ now,
908
+ now,
909
+ [
910
+ attrString("neatlogs.span.kind", "CHAIN"),
911
+ attrString("neatlogs.input.value", payload.trigger),
912
+ attrString("neatlogs.output.value", payload.compact_summary)
913
+ ]
914
+ );
915
+ shipper.enqueue(span);
916
+ }
917
+ function handleInstructionsLoaded(payload) {
918
+ if (!payload.file_path || !payload.session_id) return;
919
+ if (!(0, import_fs4.existsSync)(payload.file_path)) return;
920
+ const content = (0, import_fs4.readFileSync)(payload.file_path, "utf-8");
921
+ const maxLen = 8192;
922
+ const truncated = content.length > maxLen ? content.slice(0, maxLen) + "\n...[truncated]" : content;
923
+ const fileKey = payload.file_path.replace(/[^a-zA-Z0-9_\-]/g, "_");
924
+ const header = `# ${payload.memory_type ?? "instructions"}: ${payload.file_path}
925
+ `;
926
+ writeState(`instr_${payload.session_id}_${fileKey}`, header + truncated);
927
+ }
928
+ function handleSessionEnd(payload, config, shipper) {
929
+ const sessionCtx = getSessionTrace(payload.session_id);
930
+ if (sessionCtx) {
931
+ const now = nowNanoString();
932
+ const marker = createSpan(
933
+ "neatlogs.trace.complete",
934
+ sessionCtx,
935
+ now,
936
+ now,
937
+ []
938
+ );
939
+ shipper.enqueue(marker);
940
+ }
941
+ deleteState(sessionTraceKey(payload.session_id));
942
+ deleteState(turnSpanKey(payload.session_id));
943
+ deleteState(`model_${payload.session_id}`);
944
+ deleteState(`workflow_${payload.session_id}`);
945
+ deleteState(`turnstart_${payload.session_id}`);
946
+ cleanupStateFiles(`instr_${payload.session_id}_`);
947
+ cleanupStateFiles(`tool_`);
948
+ cleanupStateFiles(`subagent_`);
949
+ }
950
+ function emitLLMPhaseSpans(_payload, summary, shipper, parent, config) {
951
+ if (config.debug) {
952
+ (0, import_fs4.appendFileSync)("/tmp/neatlogs-hook-debug.log", `[${(/* @__PURE__ */ new Date()).toISOString()}] emitLLMPhaseSpans: ${summary.llmCallPhases.length} phases, hasThinking=${summary.hasThinking}
953
+ `);
954
+ for (let i = 0; i < Math.min(summary.llmCallPhases.length, 5); i++) {
955
+ const p = summary.llmCallPhases[i];
956
+ (0, import_fs4.appendFileSync)("/tmp/neatlogs-hook-debug.log", `[${(/* @__PURE__ */ new Date()).toISOString()}] phase[${i}]: text=${p.text.length} thinking=${p.thinking.length} tools=${p.toolCalls.length}
957
+ `);
958
+ }
959
+ }
960
+ for (const phase of summary.llmCallPhases) {
961
+ const outputText = phase.text.trim();
962
+ if (!outputText && !phase.thinking) continue;
963
+ const model = phase.model ?? summary.model ?? "claude";
964
+ const now = nowNanoString();
965
+ const startNano = phase.startTimestamp ? isoToNanoString(phase.startTimestamp, now) : now;
966
+ const endNano = phase.endTimestamp ? isoToNanoString(phase.endTimestamp, startNano) : startNano;
967
+ const toolCallNames = phase.toolCalls.map((tc) => tc.name).join(", ");
968
+ const span = createSpan(
969
+ model,
970
+ parent,
971
+ startNano,
972
+ endNano,
973
+ [
974
+ attrString("neatlogs.span.kind", "LLM"),
975
+ attrString("neatlogs.llm.request_type", "generateText"),
976
+ attrString("neatlogs.llm.model_name", model),
977
+ attrString("neatlogs.llm.provider", "anthropic"),
978
+ attrInt("neatlogs.llm.token_count.prompt", phase.inputTokens),
979
+ attrInt("neatlogs.llm.token_count.completion", phase.outputTokens),
980
+ ...phase.cacheReadTokens > 0 ? [attrInt("neatlogs.llm.token_count.cached", phase.cacheReadTokens)] : [],
981
+ ...phase.cacheWriteTokens > 0 ? [attrInt("neatlogs.llm.token_count.cache_write", phase.cacheWriteTokens)] : [],
982
+ attrString("neatlogs.output.value", outputText),
983
+ ...phase.thinking ? [attrString("neatlogs.llm.thinking", phase.thinking)] : [],
984
+ ...toolCallNames ? [attrString("neatlogs.llm.tool_calls", toolCallNames)] : [],
985
+ ...phase.hasThinking ? [attrString("neatlogs.llm.has_thinking", "true")] : []
986
+ ]
987
+ );
988
+ shipper.enqueue(span);
989
+ }
990
+ }
991
+
992
+ // src/hook-handler.ts
993
+ var STDIN_TIMEOUT_MS = 5e3;
994
+ var DEBUG_LOG = "/tmp/neatlogs-hook-debug.log";
995
+ function debugLog(msg) {
996
+ (0, import_fs5.appendFileSync)(DEBUG_LOG, `[${(/* @__PURE__ */ new Date()).toISOString()}] ${msg}
997
+ `);
998
+ }
999
+ function readStdin() {
1000
+ return new Promise((resolve) => {
1001
+ if (process.stdin.isTTY) {
1002
+ resolve("");
1003
+ return;
1004
+ }
1005
+ const chunks = [];
1006
+ let resolved = false;
1007
+ function done(value) {
1008
+ if (resolved) return;
1009
+ resolved = true;
1010
+ clearTimeout(timeout);
1011
+ process.stdin.removeAllListeners();
1012
+ process.stdin.destroy();
1013
+ resolve(value);
1014
+ }
1015
+ const timeout = setTimeout(() => {
1016
+ done(chunks.length > 0 ? Buffer.concat(chunks).toString("utf-8") : "");
1017
+ }, STDIN_TIMEOUT_MS);
1018
+ process.stdin.on("data", (chunk) => chunks.push(chunk));
1019
+ process.stdin.on("end", () => done(Buffer.concat(chunks).toString("utf-8")));
1020
+ process.stdin.on("error", (err) => {
1021
+ console.warn(`[neatlogs/claude-code] stdin error: ${err.message}`);
1022
+ done(chunks.length > 0 ? Buffer.concat(chunks).toString("utf-8") : "");
1023
+ });
1024
+ });
1025
+ }
1026
+ async function handleHook() {
1027
+ const raw = await readStdin();
1028
+ if (!raw.trim()) return;
1029
+ let payload;
1030
+ try {
1031
+ payload = JSON.parse(raw);
1032
+ } catch (err) {
1033
+ console.warn(`[neatlogs/claude-code] Failed to parse hook payload: ${err.message}`);
1034
+ return;
1035
+ }
1036
+ if (!payload.session_id || !payload.hook_event_name) return;
1037
+ const config = loadConfig();
1038
+ if (config.debug) {
1039
+ debugLog(`Event: ${payload.hook_event_name} | Keys: ${Object.keys(payload).join(", ")}`);
1040
+ debugLog(`Payload: ${raw.slice(0, 2e3)}`);
1041
+ }
1042
+ if (!config.apiKey) {
1043
+ if (config.debug) debugLog("No API key \u2014 skipping");
1044
+ return;
1045
+ }
1046
+ const shipper = new TraceShipper({
1047
+ apiKey: config.apiKey,
1048
+ endpoint: config.endpoint,
1049
+ debug: config.debug,
1050
+ workflowName: payload.prompt?.slice(0, 60).replace(/\n/g, " ").trim() || readState(`workflow_${payload.session_id}`) || "claude-code"
1051
+ });
1052
+ mapHookEvent(payload, { userId: config.userId, debug: config.debug }, shipper);
1053
+ await shipper.flush();
1054
+ if (config.debug) {
1055
+ debugLog(`Flushed for ${payload.hook_event_name}`);
1056
+ }
1057
+ }
1058
+
1059
+ // src/setup.ts
1060
+ var import_fs6 = require("fs");
1061
+ var import_os3 = require("os");
1062
+ var import_path3 = require("path");
1063
+ var HOOK_EVENTS = [
1064
+ "SessionStart",
1065
+ "UserPromptSubmit",
1066
+ "PreToolUse",
1067
+ "PostToolUse",
1068
+ "PostToolUseFailure",
1069
+ "SubagentStart",
1070
+ "SubagentStop",
1071
+ "PermissionDenied",
1072
+ "Stop",
1073
+ "StopFailure",
1074
+ "SessionEnd",
1075
+ "PostCompact",
1076
+ "InstructionsLoaded"
1077
+ ];
1078
+ function getSettingsPath(scope, projectDir) {
1079
+ if (scope === "global") {
1080
+ return (0, import_path3.join)((0, import_os3.homedir)(), ".claude", "settings.json");
1081
+ }
1082
+ const base = projectDir ?? process.cwd();
1083
+ return (0, import_path3.join)(base, ".claude", "settings.json");
1084
+ }
1085
+ function resolveCommand() {
1086
+ return "neatlogs-claude-code hook";
1087
+ }
1088
+ function registerHooks(scope, projectDir) {
1089
+ const settingsPath = getSettingsPath(scope, projectDir);
1090
+ const dir = (0, import_path3.dirname)(settingsPath);
1091
+ (0, import_fs6.mkdirSync)(dir, { recursive: true });
1092
+ let settings = {};
1093
+ if ((0, import_fs6.existsSync)(settingsPath)) {
1094
+ try {
1095
+ settings = JSON.parse((0, import_fs6.readFileSync)(settingsPath, "utf-8"));
1096
+ } catch (err) {
1097
+ console.warn(`[neatlogs/claude-code] Failed to parse existing settings: ${err.message}`);
1098
+ }
1099
+ }
1100
+ const command = resolveCommand();
1101
+ const existingHooks = typeof settings.hooks === "object" && !Array.isArray(settings.hooks) ? settings.hooks : {};
1102
+ for (const event of HOOK_EVENTS) {
1103
+ const eventGroups = existingHooks[event] ?? [];
1104
+ const filtered = eventGroups.filter(
1105
+ (g) => !g.hooks.some((h) => h.command.includes("neatlogs-claude-code") || h.command.includes("neatlogs/claude-code"))
1106
+ );
1107
+ filtered.push({ matcher: "", hooks: [{ type: "command", command }] });
1108
+ existingHooks[event] = filtered;
1109
+ }
1110
+ settings.hooks = existingHooks;
1111
+ (0, import_fs6.writeFileSync)(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf-8");
1112
+ console.log(`[neatlogs/claude-code] Registered ${HOOK_EVENTS.length} hooks in ${settingsPath}`);
1113
+ }
1114
+ // Annotate the CommonJS export names for ESM import in node:
1115
+ 0 && (module.exports = {
1116
+ getConfigPath,
1117
+ handleHook,
1118
+ loadConfig,
1119
+ registerHooks,
1120
+ updateConfig
1121
+ });