agent-profiler 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dudley Ablorh-Bryan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
Binary file
@@ -0,0 +1,111 @@
1
+ import { estimateTokens } from "../core/tokens.js";
2
+ function pickFirstString(values) {
3
+ for (const value of values) {
4
+ if (typeof value === "string" && value.trim().length > 0) {
5
+ return value;
6
+ }
7
+ }
8
+ return undefined;
9
+ }
10
+ function asRecord(value) {
11
+ if (value && typeof value === "object" && !Array.isArray(value)) {
12
+ return value;
13
+ }
14
+ return {};
15
+ }
16
+ function stringifyToolPayload(value) {
17
+ if (value === undefined || value === null)
18
+ return "";
19
+ if (typeof value === "string")
20
+ return value;
21
+ try {
22
+ return JSON.stringify(value);
23
+ }
24
+ catch {
25
+ return String(value);
26
+ }
27
+ }
28
+ function estimateTokensForRole(role, text) {
29
+ const estimatedInputTokens = role === "user_prompt" || role === "tool_call" || role === "shell_command"
30
+ ? estimateTokens(text)
31
+ : 0;
32
+ const estimatedOutputTokens = role === "assistant_output" ||
33
+ role === "tool_result" ||
34
+ role === "tool_failure" ||
35
+ role === "shell_output" ||
36
+ role === "file_edit" ||
37
+ role === "session_stop"
38
+ ? estimateTokens(text)
39
+ : 0;
40
+ return { estimatedInputTokens, estimatedOutputTokens };
41
+ }
42
+ export function normalizeCodexEvent(eventName, rawPayload) {
43
+ const payload = asRecord(rawPayload);
44
+ const cwd = pickFirstString([payload.cwd]);
45
+ const sessionId = pickFirstString([payload.session_id]);
46
+ const turnId = pickFirstString([payload.turn_id]);
47
+ const model = pickFirstString([payload.model]);
48
+ let role = "unknown";
49
+ let observableText = "";
50
+ switch (eventName) {
51
+ case "SessionStart": {
52
+ role = "session_start";
53
+ observableText = pickFirstString([payload.source]) ?? "";
54
+ break;
55
+ }
56
+ case "UserPromptSubmit": {
57
+ role = "user_prompt";
58
+ observableText = pickFirstString([payload.prompt]) ?? "";
59
+ break;
60
+ }
61
+ case "PreToolUse": {
62
+ role = "tool_call";
63
+ const toolName = pickFirstString([payload.tool_name]) ?? "";
64
+ observableText = [toolName, stringifyToolPayload(payload.tool_input)]
65
+ .filter(Boolean)
66
+ .join("\n");
67
+ break;
68
+ }
69
+ case "PostToolUse": {
70
+ const toolName = (pickFirstString([payload.tool_name]) ?? "").trim();
71
+ const responseStr = stringifyToolPayload(payload.tool_response);
72
+ observableText = [toolName, responseStr].filter(Boolean).join("\n");
73
+ const lower = toolName.toLowerCase();
74
+ if (toolName === "Bash" || lower === "bash") {
75
+ role = "shell_output";
76
+ }
77
+ else if (toolName === "apply_patch" ||
78
+ toolName === "Edit" ||
79
+ toolName === "Write") {
80
+ role = "file_edit";
81
+ }
82
+ else {
83
+ role = "tool_result";
84
+ }
85
+ break;
86
+ }
87
+ case "Stop": {
88
+ role = "session_stop";
89
+ observableText = pickFirstString([payload.last_assistant_message]) ?? "";
90
+ break;
91
+ }
92
+ default: {
93
+ observableText = stringifyToolPayload(rawPayload);
94
+ }
95
+ }
96
+ const { estimatedInputTokens, estimatedOutputTokens } = estimateTokensForRole(role, observableText);
97
+ return {
98
+ source: "codex",
99
+ sourceEvent: eventName,
100
+ repoPath: cwd,
101
+ sessionId,
102
+ turnId,
103
+ model,
104
+ role,
105
+ observableText,
106
+ estimatedInputTokens,
107
+ estimatedOutputTokens,
108
+ estimatedTotalTokens: estimatedInputTokens + estimatedOutputTokens,
109
+ rawPayload,
110
+ };
111
+ }
@@ -0,0 +1,98 @@
1
+ import { estimateTokens } from "../core/tokens.js";
2
+ const cursorRoleMap = {
3
+ beforeSubmitPrompt: "user_prompt",
4
+ afterAgentResponse: "assistant_output",
5
+ afterAgentThought: "assistant_output",
6
+ afterShellExecution: "shell_output",
7
+ afterFileEdit: "file_edit",
8
+ preToolUse: "tool_call",
9
+ postToolUse: "tool_result",
10
+ postToolUseFailure: "tool_failure",
11
+ beforeMCPExecution: "tool_call",
12
+ afterMCPExecution: "tool_result",
13
+ beforeShellExecution: "shell_command",
14
+ beforeReadFile: "tool_call",
15
+ start: "session_start",
16
+ sessionStart: "session_start",
17
+ stop: "session_stop",
18
+ sessionEnd: "session_stop",
19
+ preCompact: "unknown",
20
+ };
21
+ function pickFirstString(values) {
22
+ for (const value of values) {
23
+ if (typeof value === "string" && value.trim().length > 0) {
24
+ return value;
25
+ }
26
+ }
27
+ return undefined;
28
+ }
29
+ function asRecord(value) {
30
+ if (value && typeof value === "object" && !Array.isArray(value)) {
31
+ return value;
32
+ }
33
+ return {};
34
+ }
35
+ function stringifyJsonish(value) {
36
+ if (value === undefined || value === null)
37
+ return undefined;
38
+ if (typeof value === "string")
39
+ return value;
40
+ try {
41
+ const s = JSON.stringify(value);
42
+ return s.length > 0 ? s : undefined;
43
+ }
44
+ catch {
45
+ return String(value);
46
+ }
47
+ }
48
+ function extractObservableText(payload) {
49
+ const content = pickFirstString([
50
+ payload.prompt,
51
+ payload.response,
52
+ payload.output,
53
+ payload.stderr,
54
+ payload.stdout,
55
+ payload.command,
56
+ payload.text,
57
+ payload.message,
58
+ typeof payload.result === "string" ? payload.result : undefined,
59
+ ]);
60
+ if (content)
61
+ return content;
62
+ const toolResponse = stringifyJsonish(payload.tool_response ?? payload.toolResponse ?? payload.result);
63
+ if (toolResponse)
64
+ return toolResponse;
65
+ const toolInput = stringifyJsonish(payload.tool_input ?? payload.toolInput ?? payload.input ?? payload.args ?? payload.arguments);
66
+ if (toolInput)
67
+ return toolInput;
68
+ return JSON.stringify(payload);
69
+ }
70
+ export function normalizeCursorEvent(eventName, rawPayload) {
71
+ const payload = asRecord(rawPayload);
72
+ const role = cursorRoleMap[eventName] ?? "unknown";
73
+ const observableText = extractObservableText(payload);
74
+ const estimatedInputTokens = role === "user_prompt" || role === "tool_call" || role === "shell_command"
75
+ ? estimateTokens(observableText)
76
+ : 0;
77
+ const estimatedOutputTokens = role === "assistant_output" ||
78
+ role === "tool_result" ||
79
+ role === "tool_failure" ||
80
+ role === "shell_output" ||
81
+ role === "file_edit"
82
+ ? estimateTokens(observableText)
83
+ : 0;
84
+ return {
85
+ source: "cursor",
86
+ sourceEvent: eventName,
87
+ repoPath: pickFirstString([payload.repoPath, payload.workspacePath]),
88
+ sessionId: pickFirstString([payload.sessionId, payload.session]),
89
+ turnId: pickFirstString([payload.turnId, payload.turn]),
90
+ model: pickFirstString([payload.model, payload.modelName]),
91
+ role,
92
+ observableText,
93
+ estimatedInputTokens,
94
+ estimatedOutputTokens,
95
+ estimatedTotalTokens: estimatedInputTokens + estimatedOutputTokens,
96
+ rawPayload,
97
+ };
98
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,101 @@
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 } from "./commands/init.js";
6
+ import { getLastReport, runLast } from "./commands/last.js";
7
+ import { getStatusReport, runStatus } from "./commands/status.js";
8
+ const program = new Command();
9
+ program
10
+ .name("agent-profiler")
11
+ .description("Local-first profiling for AI coding agents.")
12
+ .version("0.1.0");
13
+ program
14
+ .command("init")
15
+ .description("Initialize Agent Profiler for a supported source.")
16
+ .argument("<source>", "supported: cursor | codex")
17
+ .option("--mode <mode>", "init mode: dev or prod", "dev")
18
+ .action((source, options) => {
19
+ const allowed = ["cursor", "codex"];
20
+ if (!allowed.includes(source)) {
21
+ console.error(`Unsupported source: ${source}`);
22
+ process.exitCode = 1;
23
+ return;
24
+ }
25
+ if (options.mode !== "dev" && options.mode !== "prod") {
26
+ console.error(`Unsupported mode: ${options.mode}`);
27
+ process.exitCode = 1;
28
+ return;
29
+ }
30
+ try {
31
+ runInit(source, options.mode);
32
+ }
33
+ catch (error) {
34
+ console.error("Failed to initialize Agent Profiler.");
35
+ console.error(error);
36
+ process.exitCode = 1;
37
+ }
38
+ });
39
+ program
40
+ .command("hook")
41
+ .description("Ingest a hook event from an adapter.")
42
+ .argument("<source>", "adapter source: cursor | codex")
43
+ .argument("<eventName>", "source event name")
44
+ .action(async (source, eventName) => {
45
+ const allowed = ["cursor", "codex"];
46
+ if (!allowed.includes(source)) {
47
+ console.error(`Unsupported source: ${source}`);
48
+ process.exitCode = 1;
49
+ return;
50
+ }
51
+ try {
52
+ await runHook(source, eventName);
53
+ }
54
+ catch (error) {
55
+ console.error("Failed to process hook event.");
56
+ console.error(error);
57
+ process.exitCode = 1;
58
+ }
59
+ });
60
+ program
61
+ .command("status")
62
+ .description("Show local Agent Profiler setup and ingest status.")
63
+ .option("--mode <mode>", "status mode: dev or prod", "dev")
64
+ .option("--json", "Output status as JSON")
65
+ .action((options) => {
66
+ if (options.mode !== "dev" && options.mode !== "prod") {
67
+ console.error(`Unsupported mode: ${options.mode}`);
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ if (options.json) {
72
+ console.log(JSON.stringify(getStatusReport(options.mode), null, 2));
73
+ return;
74
+ }
75
+ runStatus(options.mode);
76
+ });
77
+ program
78
+ .command("last")
79
+ .description("Generate a report for the most recent observed session.")
80
+ .option("--json", "Output last-session report as JSON")
81
+ .action((options) => {
82
+ if (options.json) {
83
+ console.log(JSON.stringify(getLastReport(), null, 2));
84
+ return;
85
+ }
86
+ runLast();
87
+ });
88
+ program
89
+ .command("audit")
90
+ .description("Audit profiler-related workspace signals.")
91
+ .command("context")
92
+ .description("Estimate always-on instruction/context token footprint.")
93
+ .option("--json", "Output context audit as JSON")
94
+ .action((options) => {
95
+ if (options.json) {
96
+ console.log(JSON.stringify(getAuditContextReport(), null, 2));
97
+ return;
98
+ }
99
+ runAuditContext();
100
+ });
101
+ void program.parseAsync(process.argv);
@@ -0,0 +1,46 @@
1
+ import { runContextAudit } from "../core/contextAudit.js";
2
+ function formatTokens(value) {
3
+ return `~${new Intl.NumberFormat("en-US").format(value)}`;
4
+ }
5
+ export function getAuditContextReport() {
6
+ const result = runContextAudit(process.cwd());
7
+ const recommendations = result.totalEstimatedTokens > 6000
8
+ ? [
9
+ "Move large reference docs from always-on rules into on-demand skills.",
10
+ "Keep always-on rules short, direct, and behavioral.",
11
+ "Trim long examples from core instruction files.",
12
+ ]
13
+ : [
14
+ "Context footprint is currently in a healthy range.",
15
+ "Re-run this audit after major rule or skill updates.",
16
+ ];
17
+ return {
18
+ totalEstimatedTokens: result.totalEstimatedTokens,
19
+ files: result.files,
20
+ recommendations,
21
+ };
22
+ }
23
+ export function runAuditContext() {
24
+ const report = getAuditContextReport();
25
+ const lines = [];
26
+ lines.push("Agent Profiler: Context Audit");
27
+ lines.push("");
28
+ lines.push("Estimated always-on / agent-adjacent context:");
29
+ lines.push(` ${formatTokens(report.totalEstimatedTokens)} tokens`);
30
+ lines.push("");
31
+ lines.push("Largest contributors:");
32
+ if (report.files.length === 0) {
33
+ lines.push(" none found");
34
+ }
35
+ else {
36
+ for (const file of report.files.slice(0, 8)) {
37
+ lines.push(` ${file.path.padEnd(40, " ")} ${formatTokens(file.estimatedTokens)}`);
38
+ }
39
+ }
40
+ lines.push("");
41
+ lines.push("Recommendations:");
42
+ report.recommendations.forEach((recommendation, index) => {
43
+ lines.push(` ${index + 1}. ${recommendation}`);
44
+ });
45
+ console.log(lines.join("\n"));
46
+ }
@@ -0,0 +1,76 @@
1
+ import crypto from "node:crypto";
2
+ import { normalizeCodexEvent } from "../adapters/codex.js";
3
+ import { normalizeCursorEvent } from "../adapters/cursor.js";
4
+ import { resolveHookWorkspacePath, resolveWorkspaceGitMeta, } from "../core/gitWorkspace.js";
5
+ import { deriveIngestFields, } from "../core/eventMetadata.js";
6
+ import { getDefaultDbPath, insertEvent, mergeInteractionSpan, openDb, } from "../core/db.js";
7
+ function readStdin() {
8
+ return new Promise((resolve, reject) => {
9
+ let data = "";
10
+ process.stdin.setEncoding("utf8");
11
+ process.stdin.on("data", (chunk) => {
12
+ data += chunk;
13
+ });
14
+ process.stdin.on("end", () => resolve(data));
15
+ process.stdin.on("error", reject);
16
+ });
17
+ }
18
+ function parseRawPayload(stdinText) {
19
+ const trimmed = stdinText.trim();
20
+ if (!trimmed)
21
+ return {};
22
+ try {
23
+ return JSON.parse(trimmed);
24
+ }
25
+ catch {
26
+ return { _unparsed: trimmed };
27
+ }
28
+ }
29
+ function normalizeEvent(source, eventName, rawPayload) {
30
+ if (source === "cursor") {
31
+ return normalizeCursorEvent(eventName, rawPayload);
32
+ }
33
+ if (source === "codex") {
34
+ return normalizeCodexEvent(eventName, rawPayload);
35
+ }
36
+ return {
37
+ source: "generic",
38
+ sourceEvent: eventName,
39
+ role: "unknown",
40
+ observableText: "",
41
+ estimatedInputTokens: 0,
42
+ estimatedOutputTokens: 0,
43
+ estimatedTotalTokens: 0,
44
+ rawPayload,
45
+ };
46
+ }
47
+ function hashPayload(payload) {
48
+ return crypto
49
+ .createHash("sha256")
50
+ .update(JSON.stringify(payload))
51
+ .digest("hex");
52
+ }
53
+ /** Codex Stop hook requires JSON on stdout; see OpenAI Codex hooks docs. */
54
+ function writeCodexHookAck(source, eventName) {
55
+ if (source !== "codex" || eventName !== "Stop")
56
+ return;
57
+ process.stdout.write(`${JSON.stringify({ continue: true })}\n`);
58
+ }
59
+ export async function runHook(source, eventName) {
60
+ const stdinText = await readStdin();
61
+ const rawPayload = parseRawPayload(stdinText);
62
+ const normalized = normalizeEvent(source, eventName, rawPayload);
63
+ const payloadHash = hashPayload(rawPayload);
64
+ const db = openDb(getDefaultDbPath());
65
+ try {
66
+ const workspacePath = resolveHookWorkspacePath(normalized.repoPath, rawPayload);
67
+ const workspaceGit = resolveWorkspaceGitMeta(workspacePath);
68
+ const derived = deriveIngestFields(source, eventName, rawPayload, stdinText, normalized);
69
+ const eventId = insertEvent(db, normalized, payloadHash, workspaceGit, derived);
70
+ mergeInteractionSpan(db, eventId, normalized, workspaceGit, derived);
71
+ }
72
+ finally {
73
+ db.close();
74
+ }
75
+ writeCodexHookAck(source, eventName);
76
+ }