agent-profiler 0.1.0 → 1.0.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/README.md +66 -0
- package/dist/cli.js +5 -4
- package/dist/commands/init.js +4 -0
- package/dist/commands/status.js +36 -9
- package/dist/core/db.js +164 -28
- package/dist/core/gitWorkspace.js +46 -5
- package/dist/core/packageMeta.js +20 -0
- package/dist/core/schema.sql +8 -0
- package/package.json +57 -3
- package/agent-profiler-0.1.0.tgz +0 -0
- package/docs/agent-profiler-mvp-handoff.md +0 -980
- package/google-home.png +0 -0
- package/src/adapters/codex.ts +0 -131
- package/src/adapters/cursor.ts +0 -115
- package/src/cli.ts +0 -109
- package/src/commands/auditContext.ts +0 -62
- package/src/commands/hook.ts +0 -104
- package/src/commands/init.ts +0 -324
- package/src/commands/last.ts +0 -326
- package/src/commands/status.ts +0 -345
- package/src/core/contextAudit.ts +0 -102
- package/src/core/db.ts +0 -491
- package/src/core/eventMetadata.ts +0 -184
- package/src/core/gitWorkspace.ts +0 -92
- package/src/core/normalize.ts +0 -29
- package/src/core/profile.ts +0 -35
- package/src/core/schema.sql +0 -56
- package/src/core/tokens.ts +0 -4
- package/src/types/better-sqlite3.d.ts +0 -26
- package/tsconfig.json +0 -15
package/google-home.png
DELETED
|
Binary file
|
package/src/adapters/codex.ts
DELETED
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
import { estimateTokens } from "../core/tokens.js";
|
|
2
|
-
import type { AgentEventRole, NormalizedAgentEvent } from "../core/normalize.js";
|
|
3
|
-
|
|
4
|
-
function pickFirstString(values: unknown[]): string | undefined {
|
|
5
|
-
for (const value of values) {
|
|
6
|
-
if (typeof value === "string" && value.trim().length > 0) {
|
|
7
|
-
return value;
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
return undefined;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
function asRecord(value: unknown): Record<string, unknown> {
|
|
14
|
-
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
15
|
-
return value as Record<string, unknown>;
|
|
16
|
-
}
|
|
17
|
-
return {};
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function stringifyToolPayload(value: unknown): string {
|
|
21
|
-
if (value === undefined || value === null) return "";
|
|
22
|
-
if (typeof value === "string") return value;
|
|
23
|
-
try {
|
|
24
|
-
return JSON.stringify(value);
|
|
25
|
-
} catch {
|
|
26
|
-
return String(value);
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function estimateTokensForRole(role: AgentEventRole, text: string): {
|
|
31
|
-
estimatedInputTokens: number;
|
|
32
|
-
estimatedOutputTokens: number;
|
|
33
|
-
} {
|
|
34
|
-
const estimatedInputTokens =
|
|
35
|
-
role === "user_prompt" || role === "tool_call" || role === "shell_command"
|
|
36
|
-
? estimateTokens(text)
|
|
37
|
-
: 0;
|
|
38
|
-
|
|
39
|
-
const estimatedOutputTokens =
|
|
40
|
-
role === "assistant_output" ||
|
|
41
|
-
role === "tool_result" ||
|
|
42
|
-
role === "tool_failure" ||
|
|
43
|
-
role === "shell_output" ||
|
|
44
|
-
role === "file_edit" ||
|
|
45
|
-
role === "session_stop"
|
|
46
|
-
? estimateTokens(text)
|
|
47
|
-
: 0;
|
|
48
|
-
|
|
49
|
-
return { estimatedInputTokens, estimatedOutputTokens };
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function normalizeCodexEvent(
|
|
53
|
-
eventName: string,
|
|
54
|
-
rawPayload: unknown,
|
|
55
|
-
): NormalizedAgentEvent {
|
|
56
|
-
const payload = asRecord(rawPayload);
|
|
57
|
-
const cwd = pickFirstString([payload.cwd]);
|
|
58
|
-
const sessionId = pickFirstString([payload.session_id]);
|
|
59
|
-
const turnId = pickFirstString([payload.turn_id]);
|
|
60
|
-
const model = pickFirstString([payload.model]);
|
|
61
|
-
|
|
62
|
-
let role: AgentEventRole = "unknown";
|
|
63
|
-
let observableText = "";
|
|
64
|
-
|
|
65
|
-
switch (eventName) {
|
|
66
|
-
case "SessionStart": {
|
|
67
|
-
role = "session_start";
|
|
68
|
-
observableText = pickFirstString([payload.source]) ?? "";
|
|
69
|
-
break;
|
|
70
|
-
}
|
|
71
|
-
case "UserPromptSubmit": {
|
|
72
|
-
role = "user_prompt";
|
|
73
|
-
observableText = pickFirstString([payload.prompt]) ?? "";
|
|
74
|
-
break;
|
|
75
|
-
}
|
|
76
|
-
case "PreToolUse": {
|
|
77
|
-
role = "tool_call";
|
|
78
|
-
const toolName = pickFirstString([payload.tool_name]) ?? "";
|
|
79
|
-
observableText = [toolName, stringifyToolPayload(payload.tool_input)]
|
|
80
|
-
.filter(Boolean)
|
|
81
|
-
.join("\n");
|
|
82
|
-
break;
|
|
83
|
-
}
|
|
84
|
-
case "PostToolUse": {
|
|
85
|
-
const toolName = (pickFirstString([payload.tool_name]) ?? "").trim();
|
|
86
|
-
const responseStr = stringifyToolPayload(payload.tool_response);
|
|
87
|
-
observableText = [toolName, responseStr].filter(Boolean).join("\n");
|
|
88
|
-
const lower = toolName.toLowerCase();
|
|
89
|
-
if (toolName === "Bash" || lower === "bash") {
|
|
90
|
-
role = "shell_output";
|
|
91
|
-
} else if (
|
|
92
|
-
toolName === "apply_patch" ||
|
|
93
|
-
toolName === "Edit" ||
|
|
94
|
-
toolName === "Write"
|
|
95
|
-
) {
|
|
96
|
-
role = "file_edit";
|
|
97
|
-
} else {
|
|
98
|
-
role = "tool_result";
|
|
99
|
-
}
|
|
100
|
-
break;
|
|
101
|
-
}
|
|
102
|
-
case "Stop": {
|
|
103
|
-
role = "session_stop";
|
|
104
|
-
observableText = pickFirstString([payload.last_assistant_message]) ?? "";
|
|
105
|
-
break;
|
|
106
|
-
}
|
|
107
|
-
default: {
|
|
108
|
-
observableText = stringifyToolPayload(rawPayload);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
const { estimatedInputTokens, estimatedOutputTokens } = estimateTokensForRole(
|
|
113
|
-
role,
|
|
114
|
-
observableText,
|
|
115
|
-
);
|
|
116
|
-
|
|
117
|
-
return {
|
|
118
|
-
source: "codex",
|
|
119
|
-
sourceEvent: eventName,
|
|
120
|
-
repoPath: cwd,
|
|
121
|
-
sessionId,
|
|
122
|
-
turnId,
|
|
123
|
-
model,
|
|
124
|
-
role,
|
|
125
|
-
observableText,
|
|
126
|
-
estimatedInputTokens,
|
|
127
|
-
estimatedOutputTokens,
|
|
128
|
-
estimatedTotalTokens: estimatedInputTokens + estimatedOutputTokens,
|
|
129
|
-
rawPayload,
|
|
130
|
-
};
|
|
131
|
-
}
|
package/src/adapters/cursor.ts
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
import { estimateTokens } from "../core/tokens.js";
|
|
2
|
-
import type { AgentEventRole, NormalizedAgentEvent } from "../core/normalize.js";
|
|
3
|
-
|
|
4
|
-
const cursorRoleMap: Record<string, AgentEventRole> = {
|
|
5
|
-
beforeSubmitPrompt: "user_prompt",
|
|
6
|
-
afterAgentResponse: "assistant_output",
|
|
7
|
-
afterAgentThought: "assistant_output",
|
|
8
|
-
afterShellExecution: "shell_output",
|
|
9
|
-
afterFileEdit: "file_edit",
|
|
10
|
-
preToolUse: "tool_call",
|
|
11
|
-
postToolUse: "tool_result",
|
|
12
|
-
postToolUseFailure: "tool_failure",
|
|
13
|
-
beforeMCPExecution: "tool_call",
|
|
14
|
-
afterMCPExecution: "tool_result",
|
|
15
|
-
beforeShellExecution: "shell_command",
|
|
16
|
-
beforeReadFile: "tool_call",
|
|
17
|
-
start: "session_start",
|
|
18
|
-
sessionStart: "session_start",
|
|
19
|
-
stop: "session_stop",
|
|
20
|
-
sessionEnd: "session_stop",
|
|
21
|
-
preCompact: "unknown",
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
function pickFirstString(values: unknown[]): string | undefined {
|
|
25
|
-
for (const value of values) {
|
|
26
|
-
if (typeof value === "string" && value.trim().length > 0) {
|
|
27
|
-
return value;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
return undefined;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function asRecord(value: unknown): Record<string, unknown> {
|
|
34
|
-
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
35
|
-
return value as Record<string, unknown>;
|
|
36
|
-
}
|
|
37
|
-
return {};
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function stringifyJsonish(value: unknown): string | undefined {
|
|
41
|
-
if (value === undefined || value === null) return undefined;
|
|
42
|
-
if (typeof value === "string") return value;
|
|
43
|
-
try {
|
|
44
|
-
const s = JSON.stringify(value);
|
|
45
|
-
return s.length > 0 ? s : undefined;
|
|
46
|
-
} catch {
|
|
47
|
-
return String(value);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function extractObservableText(payload: Record<string, unknown>): string {
|
|
52
|
-
const content = pickFirstString([
|
|
53
|
-
payload.prompt,
|
|
54
|
-
payload.response,
|
|
55
|
-
payload.output,
|
|
56
|
-
payload.stderr,
|
|
57
|
-
payload.stdout,
|
|
58
|
-
payload.command,
|
|
59
|
-
payload.text,
|
|
60
|
-
payload.message,
|
|
61
|
-
typeof payload.result === "string" ? payload.result : undefined,
|
|
62
|
-
]);
|
|
63
|
-
|
|
64
|
-
if (content) return content;
|
|
65
|
-
|
|
66
|
-
const toolResponse = stringifyJsonish(
|
|
67
|
-
payload.tool_response ?? payload.toolResponse ?? payload.result,
|
|
68
|
-
);
|
|
69
|
-
if (toolResponse) return toolResponse;
|
|
70
|
-
|
|
71
|
-
const toolInput = stringifyJsonish(
|
|
72
|
-
payload.tool_input ?? payload.toolInput ?? payload.input ?? payload.args ?? payload.arguments,
|
|
73
|
-
);
|
|
74
|
-
if (toolInput) return toolInput;
|
|
75
|
-
|
|
76
|
-
return JSON.stringify(payload);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export function normalizeCursorEvent(
|
|
80
|
-
eventName: string,
|
|
81
|
-
rawPayload: unknown,
|
|
82
|
-
): NormalizedAgentEvent {
|
|
83
|
-
const payload = asRecord(rawPayload);
|
|
84
|
-
const role = cursorRoleMap[eventName] ?? "unknown";
|
|
85
|
-
const observableText = extractObservableText(payload);
|
|
86
|
-
|
|
87
|
-
const estimatedInputTokens =
|
|
88
|
-
role === "user_prompt" || role === "tool_call" || role === "shell_command"
|
|
89
|
-
? estimateTokens(observableText)
|
|
90
|
-
: 0;
|
|
91
|
-
|
|
92
|
-
const estimatedOutputTokens =
|
|
93
|
-
role === "assistant_output" ||
|
|
94
|
-
role === "tool_result" ||
|
|
95
|
-
role === "tool_failure" ||
|
|
96
|
-
role === "shell_output" ||
|
|
97
|
-
role === "file_edit"
|
|
98
|
-
? estimateTokens(observableText)
|
|
99
|
-
: 0;
|
|
100
|
-
|
|
101
|
-
return {
|
|
102
|
-
source: "cursor",
|
|
103
|
-
sourceEvent: eventName,
|
|
104
|
-
repoPath: pickFirstString([payload.repoPath, payload.workspacePath]),
|
|
105
|
-
sessionId: pickFirstString([payload.sessionId, payload.session]),
|
|
106
|
-
turnId: pickFirstString([payload.turnId, payload.turn]),
|
|
107
|
-
model: pickFirstString([payload.model, payload.modelName]),
|
|
108
|
-
role,
|
|
109
|
-
observableText,
|
|
110
|
-
estimatedInputTokens,
|
|
111
|
-
estimatedOutputTokens,
|
|
112
|
-
estimatedTotalTokens: estimatedInputTokens + estimatedOutputTokens,
|
|
113
|
-
rawPayload,
|
|
114
|
-
};
|
|
115
|
-
}
|
package/src/cli.ts
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { Command } from "commander";
|
|
3
|
-
import { getAuditContextReport, runAuditContext } from "./commands/auditContext.js";
|
|
4
|
-
import { runHook } from "./commands/hook.js";
|
|
5
|
-
import { runInit, type InitSource } from "./commands/init.js";
|
|
6
|
-
import { getLastReport, runLast } from "./commands/last.js";
|
|
7
|
-
import { getStatusReport, runStatus } from "./commands/status.js";
|
|
8
|
-
|
|
9
|
-
const program = new Command();
|
|
10
|
-
|
|
11
|
-
program
|
|
12
|
-
.name("agent-profiler")
|
|
13
|
-
.description("Local-first profiling for AI coding agents.")
|
|
14
|
-
.version("0.1.0");
|
|
15
|
-
|
|
16
|
-
program
|
|
17
|
-
.command("init")
|
|
18
|
-
.description("Initialize Agent Profiler for a supported source.")
|
|
19
|
-
.argument("<source>", "supported: cursor | codex")
|
|
20
|
-
.option("--mode <mode>", "init mode: dev or prod", "dev")
|
|
21
|
-
.action((source: string, options: { mode?: string }) => {
|
|
22
|
-
const allowed: InitSource[] = ["cursor", "codex"];
|
|
23
|
-
if (!allowed.includes(source as InitSource)) {
|
|
24
|
-
console.error(`Unsupported source: ${source}`);
|
|
25
|
-
process.exitCode = 1;
|
|
26
|
-
return;
|
|
27
|
-
}
|
|
28
|
-
if (options.mode !== "dev" && options.mode !== "prod") {
|
|
29
|
-
console.error(`Unsupported mode: ${options.mode}`);
|
|
30
|
-
process.exitCode = 1;
|
|
31
|
-
return;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
try {
|
|
35
|
-
runInit(source as InitSource, options.mode);
|
|
36
|
-
} catch (error) {
|
|
37
|
-
console.error("Failed to initialize Agent Profiler.");
|
|
38
|
-
console.error(error);
|
|
39
|
-
process.exitCode = 1;
|
|
40
|
-
}
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
program
|
|
44
|
-
.command("hook")
|
|
45
|
-
.description("Ingest a hook event from an adapter.")
|
|
46
|
-
.argument("<source>", "adapter source: cursor | codex")
|
|
47
|
-
.argument("<eventName>", "source event name")
|
|
48
|
-
.action(async (source: string, eventName: string) => {
|
|
49
|
-
const allowed: InitSource[] = ["cursor", "codex"];
|
|
50
|
-
if (!allowed.includes(source as InitSource)) {
|
|
51
|
-
console.error(`Unsupported source: ${source}`);
|
|
52
|
-
process.exitCode = 1;
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
try {
|
|
57
|
-
await runHook(source as InitSource, eventName);
|
|
58
|
-
} catch (error) {
|
|
59
|
-
console.error("Failed to process hook event.");
|
|
60
|
-
console.error(error);
|
|
61
|
-
process.exitCode = 1;
|
|
62
|
-
}
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
program
|
|
66
|
-
.command("status")
|
|
67
|
-
.description("Show local Agent Profiler setup and ingest status.")
|
|
68
|
-
.option("--mode <mode>", "status mode: dev or prod", "dev")
|
|
69
|
-
.option("--json", "Output status as JSON")
|
|
70
|
-
.action((options: { json?: boolean; mode?: string }) => {
|
|
71
|
-
if (options.mode !== "dev" && options.mode !== "prod") {
|
|
72
|
-
console.error(`Unsupported mode: ${options.mode}`);
|
|
73
|
-
process.exitCode = 1;
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
if (options.json) {
|
|
77
|
-
console.log(JSON.stringify(getStatusReport(options.mode), null, 2));
|
|
78
|
-
return;
|
|
79
|
-
}
|
|
80
|
-
runStatus(options.mode);
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
program
|
|
84
|
-
.command("last")
|
|
85
|
-
.description("Generate a report for the most recent observed session.")
|
|
86
|
-
.option("--json", "Output last-session report as JSON")
|
|
87
|
-
.action((options: { json?: boolean }) => {
|
|
88
|
-
if (options.json) {
|
|
89
|
-
console.log(JSON.stringify(getLastReport(), null, 2));
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
runLast();
|
|
93
|
-
});
|
|
94
|
-
|
|
95
|
-
program
|
|
96
|
-
.command("audit")
|
|
97
|
-
.description("Audit profiler-related workspace signals.")
|
|
98
|
-
.command("context")
|
|
99
|
-
.description("Estimate always-on instruction/context token footprint.")
|
|
100
|
-
.option("--json", "Output context audit as JSON")
|
|
101
|
-
.action((options: { json?: boolean }) => {
|
|
102
|
-
if (options.json) {
|
|
103
|
-
console.log(JSON.stringify(getAuditContextReport(), null, 2));
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
runAuditContext();
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
void program.parseAsync(process.argv);
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
import { runContextAudit } from "../core/contextAudit.js";
|
|
2
|
-
|
|
3
|
-
function formatTokens(value: number): string {
|
|
4
|
-
return `~${new Intl.NumberFormat("en-US").format(value)}`;
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export type AuditContextReport = {
|
|
8
|
-
totalEstimatedTokens: number;
|
|
9
|
-
files: Array<{ path: string; estimatedTokens: number }>;
|
|
10
|
-
recommendations: string[];
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
export function getAuditContextReport(): AuditContextReport {
|
|
14
|
-
const result = runContextAudit(process.cwd());
|
|
15
|
-
const recommendations =
|
|
16
|
-
result.totalEstimatedTokens > 6000
|
|
17
|
-
? [
|
|
18
|
-
"Move large reference docs from always-on rules into on-demand skills.",
|
|
19
|
-
"Keep always-on rules short, direct, and behavioral.",
|
|
20
|
-
"Trim long examples from core instruction files.",
|
|
21
|
-
]
|
|
22
|
-
: [
|
|
23
|
-
"Context footprint is currently in a healthy range.",
|
|
24
|
-
"Re-run this audit after major rule or skill updates.",
|
|
25
|
-
];
|
|
26
|
-
|
|
27
|
-
return {
|
|
28
|
-
totalEstimatedTokens: result.totalEstimatedTokens,
|
|
29
|
-
files: result.files,
|
|
30
|
-
recommendations,
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export function runAuditContext(): void {
|
|
35
|
-
const report = getAuditContextReport();
|
|
36
|
-
|
|
37
|
-
const lines: string[] = [];
|
|
38
|
-
lines.push("Agent Profiler: Context Audit");
|
|
39
|
-
lines.push("");
|
|
40
|
-
lines.push("Estimated always-on / agent-adjacent context:");
|
|
41
|
-
lines.push(` ${formatTokens(report.totalEstimatedTokens)} tokens`);
|
|
42
|
-
lines.push("");
|
|
43
|
-
lines.push("Largest contributors:");
|
|
44
|
-
|
|
45
|
-
if (report.files.length === 0) {
|
|
46
|
-
lines.push(" none found");
|
|
47
|
-
} else {
|
|
48
|
-
for (const file of report.files.slice(0, 8)) {
|
|
49
|
-
lines.push(
|
|
50
|
-
` ${file.path.padEnd(40, " ")} ${formatTokens(file.estimatedTokens)}`,
|
|
51
|
-
);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
lines.push("");
|
|
56
|
-
lines.push("Recommendations:");
|
|
57
|
-
report.recommendations.forEach((recommendation, index) => {
|
|
58
|
-
lines.push(` ${index + 1}. ${recommendation}`);
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
console.log(lines.join("\n"));
|
|
62
|
-
}
|
package/src/commands/hook.ts
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import crypto from "node:crypto";
|
|
2
|
-
import { normalizeCodexEvent } from "../adapters/codex.js";
|
|
3
|
-
import { normalizeCursorEvent } from "../adapters/cursor.js";
|
|
4
|
-
import {
|
|
5
|
-
resolveHookWorkspacePath,
|
|
6
|
-
resolveWorkspaceGitMeta,
|
|
7
|
-
} from "../core/gitWorkspace.js";
|
|
8
|
-
import {
|
|
9
|
-
deriveIngestFields,
|
|
10
|
-
type TelemetryHookSource,
|
|
11
|
-
} from "../core/eventMetadata.js";
|
|
12
|
-
import {
|
|
13
|
-
getDefaultDbPath,
|
|
14
|
-
insertEvent,
|
|
15
|
-
mergeInteractionSpan,
|
|
16
|
-
openDb,
|
|
17
|
-
} from "../core/db.js";
|
|
18
|
-
import type { InitSource } from "./init.js";
|
|
19
|
-
import type { NormalizedAgentEvent } from "../core/normalize.js";
|
|
20
|
-
|
|
21
|
-
function readStdin(): Promise<string> {
|
|
22
|
-
return new Promise((resolve, reject) => {
|
|
23
|
-
let data = "";
|
|
24
|
-
process.stdin.setEncoding("utf8");
|
|
25
|
-
process.stdin.on("data", (chunk: string) => {
|
|
26
|
-
data += chunk;
|
|
27
|
-
});
|
|
28
|
-
process.stdin.on("end", () => resolve(data));
|
|
29
|
-
process.stdin.on("error", reject);
|
|
30
|
-
});
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function parseRawPayload(stdinText: string): unknown {
|
|
34
|
-
const trimmed = stdinText.trim();
|
|
35
|
-
if (!trimmed) return {};
|
|
36
|
-
try {
|
|
37
|
-
return JSON.parse(trimmed);
|
|
38
|
-
} catch {
|
|
39
|
-
return { _unparsed: trimmed };
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function normalizeEvent(
|
|
44
|
-
source: InitSource,
|
|
45
|
-
eventName: string,
|
|
46
|
-
rawPayload: unknown,
|
|
47
|
-
): NormalizedAgentEvent {
|
|
48
|
-
if (source === "cursor") {
|
|
49
|
-
return normalizeCursorEvent(eventName, rawPayload);
|
|
50
|
-
}
|
|
51
|
-
if (source === "codex") {
|
|
52
|
-
return normalizeCodexEvent(eventName, rawPayload);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
return {
|
|
56
|
-
source: "generic",
|
|
57
|
-
sourceEvent: eventName,
|
|
58
|
-
role: "unknown",
|
|
59
|
-
observableText: "",
|
|
60
|
-
estimatedInputTokens: 0,
|
|
61
|
-
estimatedOutputTokens: 0,
|
|
62
|
-
estimatedTotalTokens: 0,
|
|
63
|
-
rawPayload,
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function hashPayload(payload: unknown): string {
|
|
68
|
-
return crypto
|
|
69
|
-
.createHash("sha256")
|
|
70
|
-
.update(JSON.stringify(payload))
|
|
71
|
-
.digest("hex");
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** Codex Stop hook requires JSON on stdout; see OpenAI Codex hooks docs. */
|
|
75
|
-
function writeCodexHookAck(source: InitSource, eventName: string): void {
|
|
76
|
-
if (source !== "codex" || eventName !== "Stop") return;
|
|
77
|
-
process.stdout.write(`${JSON.stringify({ continue: true })}\n`);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export async function runHook(source: InitSource, eventName: string): Promise<void> {
|
|
81
|
-
const stdinText = await readStdin();
|
|
82
|
-
const rawPayload = parseRawPayload(stdinText);
|
|
83
|
-
const normalized = normalizeEvent(source, eventName, rawPayload);
|
|
84
|
-
const payloadHash = hashPayload(rawPayload);
|
|
85
|
-
|
|
86
|
-
const db = openDb(getDefaultDbPath());
|
|
87
|
-
try {
|
|
88
|
-
const workspacePath = resolveHookWorkspacePath(normalized.repoPath, rawPayload);
|
|
89
|
-
const workspaceGit = resolveWorkspaceGitMeta(workspacePath);
|
|
90
|
-
const derived = deriveIngestFields(
|
|
91
|
-
source as TelemetryHookSource,
|
|
92
|
-
eventName,
|
|
93
|
-
rawPayload,
|
|
94
|
-
stdinText,
|
|
95
|
-
normalized,
|
|
96
|
-
);
|
|
97
|
-
const eventId = insertEvent(db, normalized, payloadHash, workspaceGit, derived);
|
|
98
|
-
mergeInteractionSpan(db, eventId, normalized, workspaceGit, derived);
|
|
99
|
-
} finally {
|
|
100
|
-
db.close();
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
writeCodexHookAck(source, eventName);
|
|
104
|
-
}
|