@omnidim-ai/mcp-server 0.2.9 → 0.4.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/src/helpers.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { renderWordmark } from "./banner.js";
2
+
1
3
  export const PACKAGE_NAME = "@omnidim-ai/mcp-server";
2
4
 
3
5
  const bold = (s: string): string => `\x1b[1m${s}\x1b[0m`;
@@ -54,6 +56,14 @@ export async function printAnimatedSetupBanner(): Promise<void> {
54
56
  printSetupBanner();
55
57
  return;
56
58
  }
59
+ // Wide TTY: show the full branded wordmark instead of the spinner line.
60
+ const wordmark = renderWordmark(process.stdout.columns);
61
+ if (wordmark) {
62
+ process.stdout.write("\n" + wordmark + "\n\n");
63
+ process.stdout.write(` ${bold("OmniDimension")} ${dim("·")} ${italic("Voice AI")}\n`);
64
+ process.stdout.write(SUBTITLE + "\n\n");
65
+ return;
66
+ }
57
67
  process.stdout.write("\n");
58
68
  process.stdout.write("\x1b[?25l");
59
69
  try {
@@ -149,3 +159,32 @@ export function trimLargeResponse(data: unknown): { text: string; note?: string
149
159
  note: `[Response truncated. Full size: ${full.length} chars.]`,
150
160
  };
151
161
  }
162
+
163
+ const NAMED_STATUSES = new Set([400, 401, 403, 404, 409, 422, 429, 500, 502, 503]);
164
+
165
+ // Map a thrown tool-call error to a low-cardinality category for telemetry.
166
+ // Duck-typed on the axios error shape so this stays testable without axios.
167
+ // Returns a status/network/timeout category, never a URL, body, or input.
168
+ export function classifyToolError(error: unknown): string {
169
+ if (error && typeof error === "object") {
170
+ const e = error as {
171
+ isAxiosError?: boolean;
172
+ code?: unknown;
173
+ name?: unknown;
174
+ response?: { status?: unknown };
175
+ };
176
+ if (e.name === "ZodError") return "validation";
177
+ if (e.isAxiosError) {
178
+ const status = e.response?.status;
179
+ if (typeof status === "number") {
180
+ if (NAMED_STATUSES.has(status)) return `http_${status}`;
181
+ if (status >= 500) return "http_5xx";
182
+ if (status >= 400) return "http_4xx";
183
+ return `http_${status}`;
184
+ }
185
+ if (e.code === "ECONNABORTED" || e.code === "ETIMEDOUT") return "timeout";
186
+ return "network";
187
+ }
188
+ }
189
+ return "unknown";
190
+ }
package/src/index.ts CHANGED
@@ -8,7 +8,7 @@ import { isInteractive, printInteractiveHelp, startupBanner, trimLargeResponse }
8
8
 
9
9
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
10
10
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
- import { beginSession, endSession, emitSessionEnd, recordToolCall } from "./telemetry.js";
11
+ import { beginSession, emitSessionCrash, emitSessionEnd, endSession, recordToolError, recordToolResult } from "./telemetry.js";
12
12
  import {
13
13
  CallToolRequestSchema,
14
14
  ListToolsRequestSchema,
@@ -783,6 +783,7 @@ async function executeApiTool(
783
783
  const argsToParse = (typeof toolArgs === 'object' && toolArgs !== null) ? toolArgs : {};
784
784
  validatedArgs = zodSchema.parse(argsToParse);
785
785
  } catch (error: unknown) {
786
+ recordToolResult(toolName, 'validation');
786
787
  if (error instanceof ZodError) {
787
788
  const validationErrorMessage = `Invalid arguments for tool '${toolName}': ${error.errors.map(e => `${e.path.join('.')} (${e.code}): ${e.message}`).join(', ')}`;
788
789
  return { content: [{ type: 'text', text: validationErrorMessage }] };
@@ -964,6 +965,7 @@ async function executeApiTool(
964
965
  }
965
966
  }
966
967
  else if (definition.securityRequirements?.length > 0) {
968
+ recordToolResult(toolName, 'no_api_key');
967
969
  return {
968
970
  content: [{
969
971
  type: 'text',
@@ -1026,16 +1028,18 @@ async function executeApiTool(
1026
1028
  }
1027
1029
 
1028
1030
  // Return formatted response
1029
- return {
1030
- content: [
1031
- {
1032
- type: "text",
1033
- text: `API Response (Status: ${response.status}):\n${responseText}`
1034
- }
1035
- ],
1031
+ recordToolResult(toolName, 'ok');
1032
+ return {
1033
+ content: [
1034
+ {
1035
+ type: "text",
1036
+ text: `API Response (Status: ${response.status}):\n${responseText}`
1037
+ }
1038
+ ],
1036
1039
  };
1037
1040
 
1038
1041
  } catch (error: unknown) {
1042
+ recordToolError(toolName, error);
1039
1043
  // Handle errors during execution
1040
1044
  let errorMessage: string;
1041
1045
 
@@ -1073,6 +1077,10 @@ async function main() {
1073
1077
  const { runTelemetryCommand } = await import("./telemetry-cli.js");
1074
1078
  process.exit(await runTelemetryCommand(process.argv[3]));
1075
1079
  }
1080
+ if (process.argv[2] === "doctor") {
1081
+ const { runDoctor } = await import("./doctor.js");
1082
+ process.exit(await runDoctor());
1083
+ }
1076
1084
  if (isInteractive()) {
1077
1085
  printInteractiveHelp(SERVER_VERSION);
1078
1086
  process.exit(0);
@@ -1083,6 +1091,7 @@ async function main() {
1083
1091
  console.error(startupBanner(SERVER_VERSION, toolDefinitionMap.size));
1084
1092
  beginSession();
1085
1093
  } catch (error) {
1094
+ try { await emitSessionCrash(error); } catch { /* telemetry must never mask the crash */ }
1086
1095
  console.error("Error during server startup:", error);
1087
1096
  process.exit(1);
1088
1097
  }
@@ -1105,8 +1114,22 @@ async function cleanup() {
1105
1114
  process.on('SIGINT', cleanup);
1106
1115
  process.on('SIGTERM', cleanup);
1107
1116
 
1117
+ // A crash never runs the graceful-shutdown path, so flush a session_crash
1118
+ // (with the session's tool-call summary) before exiting.
1119
+ process.on('uncaughtException', async (error) => {
1120
+ try { await emitSessionCrash(error); } catch { /* never mask the crash */ }
1121
+ console.error("Uncaught exception:", error);
1122
+ process.exit(1);
1123
+ });
1124
+ process.on('unhandledRejection', async (reason) => {
1125
+ try { await emitSessionCrash(reason); } catch { /* never mask the crash */ }
1126
+ console.error("Unhandled rejection:", reason);
1127
+ process.exit(1);
1128
+ });
1129
+
1108
1130
  // Start the server
1109
- main().catch((error) => {
1131
+ main().catch(async (error) => {
1132
+ try { await emitSessionCrash(error); } catch { /* never mask the crash */ }
1110
1133
  console.error("Fatal error in main execution:", error);
1111
1134
  process.exit(1);
1112
1135
  });
package/src/logger.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ const LOG_DIR = join(homedir(), ".config", "omnidim", "logs");
6
+ export const LOG_PATH = join(LOG_DIR, "mcp.log");
7
+ const MAX_BYTES = 256 * 1024;
8
+
9
+ // The log is local-only but the user may paste it into a public issue, so
10
+ // strip anything token-shaped before writing. The API key is never passed
11
+ // here, but an upstream library's error message can occasionally echo one.
12
+ export function scrubSecrets(s: string): string {
13
+ return s
14
+ .replace(/sk_[A-Za-z0-9_-]{6,}/g, "sk_[redacted]")
15
+ .replace(/(bearer\s+)[A-Za-z0-9._-]{8,}/gi, "$1[redacted]")
16
+ .replace(
17
+ /("?(?:api[_-]?key|authorization|token)"?\s*[:=]\s*"?)[A-Za-z0-9._-]{8,}/gi,
18
+ "$1[redacted]",
19
+ );
20
+ }
21
+
22
+ export interface LogFields {
23
+ kind: "tool_error" | "setup" | "crash";
24
+ [key: string]: unknown;
25
+ }
26
+
27
+ export function appendLog(fields: LogFields): void {
28
+ try {
29
+ mkdirSync(LOG_DIR, { recursive: true });
30
+ const line = scrubSecrets(JSON.stringify({ ts: new Date().toISOString(), ...fields }));
31
+ appendFileSync(LOG_PATH, line + "\n", { mode: 0o600 });
32
+ trimIfLarge();
33
+ } catch {
34
+ // logging must never affect the user experience
35
+ }
36
+ }
37
+
38
+ // Keep the newest half when the file grows past the cap, so the log can't
39
+ // grow without bound on a long-lived or repeatedly-failing install.
40
+ function trimIfLarge(): void {
41
+ try {
42
+ if (!existsSync(LOG_PATH) || statSync(LOG_PATH).size <= MAX_BYTES) return;
43
+ const lines = readFileSync(LOG_PATH, "utf8").split("\n");
44
+ writeFileSync(LOG_PATH, lines.slice(Math.floor(lines.length / 2)).join("\n"), { mode: 0o600 });
45
+ } catch {
46
+ // ignore
47
+ }
48
+ }
49
+
50
+ export function readLogTail(maxLines = 25): string[] {
51
+ try {
52
+ if (!existsSync(LOG_PATH)) return [];
53
+ return readFileSync(LOG_PATH, "utf8").trimEnd().split("\n").filter(Boolean).slice(-maxLines);
54
+ } catch {
55
+ return [];
56
+ }
57
+ }
package/src/setup.ts CHANGED
@@ -1,14 +1,20 @@
1
- import { execFileSync } from "node:child_process";
2
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { join } from "node:path";
5
1
  import { createInterface, Interface as ReadlineInterface } from "node:readline/promises";
6
2
 
7
3
  import axios from "axios";
8
4
 
5
+ import { buildTargets, describeInstallError } from "./clients.js";
9
6
  import { CREDENTIALS_PATH, readApiKey, writeApiKey } from "./credentials.js";
10
7
  import { printAnimatedSetupBanner } from "./helpers.js";
11
- import { emitInstall, isTelemetryDisabled } from "./telemetry.js";
8
+ import { appendLog } from "./logger.js";
9
+ import {
10
+ emitInstall,
11
+ emitSetupClientResult,
12
+ emitSetupFinished,
13
+ emitSetupKeyResult,
14
+ emitSetupStarted,
15
+ isTelemetryDisabled,
16
+ type SetupKeyOutcome,
17
+ } from "./telemetry.js";
12
18
 
13
19
  const PROD_API = "https://backend.omnidim.io/api/v1";
14
20
 
@@ -29,80 +35,6 @@ export function pickClosingLine(): string {
29
35
  return CLOSING_LINES[Math.floor(Math.random() * CLOSING_LINES.length)];
30
36
  }
31
37
 
32
- interface ClientTarget {
33
- name: string;
34
- configPath: string;
35
- install: (apiKey: string) => void;
36
- }
37
-
38
- const TARGETS: ClientTarget[] = [
39
- {
40
- name: "Claude Code",
41
- configPath: join(homedir(), ".claude.json"),
42
- install: installClaudeCode,
43
- },
44
- {
45
- name: "Claude Desktop",
46
- configPath: join(
47
- homedir(),
48
- "Library",
49
- "Application Support",
50
- "Claude",
51
- "claude_desktop_config.json",
52
- ),
53
- install: (key) => upsertJsonConfig(TARGETS[1].configPath, key),
54
- },
55
- {
56
- name: "Cursor",
57
- configPath: join(homedir(), ".cursor", "mcp.json"),
58
- install: (key) => upsertJsonConfig(TARGETS[2].configPath, key),
59
- },
60
- {
61
- name: "Windsurf",
62
- configPath: join(homedir(), ".codeium", "windsurf", "mcp_config.json"),
63
- install: (key) => upsertJsonConfig(TARGETS[3].configPath, key),
64
- },
65
- ];
66
-
67
- function upsertJsonConfig(configPath: string, apiKey: string): void {
68
- const config = existsSync(configPath)
69
- ? (JSON.parse(readFileSync(configPath, "utf8")) as Record<string, unknown>)
70
- : {};
71
- const servers = ((config.mcpServers as Record<string, unknown>) ?? {}) as Record<string, unknown>;
72
- servers.omnidim = {
73
- command: "npx",
74
- args: ["-y", "@omnidim-ai/mcp-server"],
75
- env: { OMNIDIM_API_KEY: apiKey },
76
- };
77
- config.mcpServers = servers;
78
- writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
79
- }
80
-
81
- function installClaudeCode(apiKey: string): void {
82
- try {
83
- execFileSync("claude", ["mcp", "remove", "omnidim", "--scope", "user"], { stdio: "ignore" });
84
- } catch {
85
- // not registered, fine
86
- }
87
- try {
88
- // Name before the variadic -e so commander doesn't gobble it as an env value.
89
- execFileSync(
90
- "claude",
91
- [
92
- "mcp", "add", "omnidim",
93
- "--scope", "user",
94
- "-e", `OMNIDIM_API_KEY=${apiKey}`,
95
- "--", "npx", "-y", "@omnidim-ai/mcp-server",
96
- ],
97
- { stdio: ["ignore", "pipe", "pipe"] },
98
- );
99
- } catch (e) {
100
- const err = e as { stderr?: Buffer; stdout?: Buffer; message: string };
101
- const detail = (err.stderr ?? err.stdout ?? Buffer.from("")).toString().trim();
102
- throw new Error(detail || err.message);
103
- }
104
- }
105
-
106
38
  // Echoes `*` per input char so pasted keys never land in scrollback.
107
39
  function readMaskedLine(prompt: string): Promise<string> {
108
40
  process.stdout.write(prompt);
@@ -164,7 +96,26 @@ function readMaskedLine(prompt: string): Promise<string> {
164
96
  });
165
97
  }
166
98
 
167
- async function validateApiKey(apiKey: string): Promise<string | null> {
99
+ type KeyFailureReason = "rejected_401" | "network_error" | "unexpected";
100
+
101
+ type KeyCheck = { ok: true } | { ok: false; reason: KeyFailureReason; message: string };
102
+
103
+ // Maps the last key-check failure to the telemetry outcome. `null` means the
104
+ // user never submitted a key (only empty input), i.e. a genuine abort.
105
+ export function keyOutcomeFromReason(reason: KeyFailureReason | null): SetupKeyOutcome {
106
+ switch (reason) {
107
+ case "rejected_401":
108
+ return "rejected_401";
109
+ case "network_error":
110
+ return "network_error";
111
+ case "unexpected":
112
+ return "server_error";
113
+ default:
114
+ return "aborted";
115
+ }
116
+ }
117
+
118
+ async function validateApiKey(apiKey: string): Promise<KeyCheck> {
168
119
  try {
169
120
  const res = await axios.get(`${PROD_API}/agents`, {
170
121
  params: { pagesize: 1 },
@@ -172,16 +123,17 @@ async function validateApiKey(apiKey: string): Promise<string | null> {
172
123
  timeout: 10_000,
173
124
  validateStatus: () => true,
174
125
  });
175
- if (res.status === 200) return null;
176
- if (res.status === 401) return "Uh oh! Key rejected";
177
- return `unexpected status ${res.status}`;
126
+ if (res.status === 200) return { ok: true };
127
+ if (res.status === 401) return { ok: false, reason: "rejected_401", message: "Uh oh! Key rejected" };
128
+ return { ok: false, reason: "unexpected", message: `unexpected status ${res.status}` };
178
129
  } catch (e) {
179
- return e instanceof Error ? e.message : "network error";
130
+ return { ok: false, reason: "network_error", message: e instanceof Error ? e.message : "network error" };
180
131
  }
181
132
  }
182
133
 
183
134
  export async function runSetup(): Promise<number> {
184
135
  await printAnimatedSetupBanner();
136
+ void emitSetupStarted();
185
137
 
186
138
  let rl: ReadlineInterface | null = null;
187
139
  try {
@@ -192,23 +144,25 @@ export async function runSetup(): Promise<number> {
192
144
  if (saved) {
193
145
  process.stdout.write(` Saved key found at ${dim(CREDENTIALS_PATH)}\n`);
194
146
  process.stdout.write(` ${dim("checking...")}\n`);
195
- const err = await validateApiKey(saved);
196
- if (err === null) {
147
+ const check = await validateApiKey(saved);
148
+ if (check.ok) {
197
149
  rl = createInterface({ input: process.stdin, output: process.stdout });
198
150
  const ans = (await rl.question(" Reuse this key? [Y/n] ")).trim().toLowerCase();
199
151
  rl.close();
200
152
  rl = null;
201
153
  if (ans !== "n" && ans !== "no") {
202
154
  apiKey = saved;
155
+ void emitSetupKeyResult("reused");
203
156
  process.stdout.write(` ${teal("●")} using saved key\n\n`);
204
157
  }
205
158
  } else {
206
- process.stdout.write(red(` saved key: ${err}\n`));
159
+ process.stdout.write(red(` saved key: ${check.message}\n`));
207
160
  }
208
161
  }
209
162
 
210
163
  if (!apiKey) {
211
164
  process.stdout.write(` Get a key at ${dim("omnidim.io/api-management")}\n`);
165
+ let lastReason: KeyFailureReason | null = null;
212
166
  for (let i = 0; i < 3 && !apiKey; i++) {
213
167
  const input = (await readMaskedLine(" API key: ")).trim();
214
168
  if (!input) {
@@ -216,24 +170,28 @@ export async function runSetup(): Promise<number> {
216
170
  continue;
217
171
  }
218
172
  process.stdout.write(` ${dim("checking...")}\n`);
219
- const err = await validateApiKey(input);
220
- if (err === null) {
173
+ const check = await validateApiKey(input);
174
+ if (check.ok) {
221
175
  apiKey = input;
222
176
  break;
223
177
  }
224
- process.stdout.write(red(` ${err}, try again\n`));
178
+ lastReason = check.reason;
179
+ process.stdout.write(red(` ${check.message}, try again\n`));
225
180
  }
226
181
  if (!apiKey) {
182
+ void emitSetupKeyResult(keyOutcomeFromReason(lastReason));
227
183
  process.stdout.write(red("\n three failed attempts, aborting.\n"));
228
184
  return 1;
229
185
  }
230
186
 
187
+ void emitSetupKeyResult("entered");
231
188
  const path = writeApiKey(apiKey);
232
189
  process.stdout.write(` ${teal("●")} key saved to ${dim(path)}\n\n`);
233
190
  }
234
191
 
235
- const detected = TARGETS.filter((t) => existsSync(t.configPath));
192
+ const detected = buildTargets().filter((t) => t.detect());
236
193
  if (detected.length === 0) {
194
+ void emitSetupFinished(0, 0);
237
195
  process.stdout.write(` ${dim("no MCP clients detected. Add manually:")}\n`);
238
196
  process.stdout.write(` claude mcp add omnidim -- npx -y @omnidim-ai/mcp-server\n\n`);
239
197
  return 0;
@@ -244,20 +202,32 @@ export async function runSetup(): Promise<number> {
244
202
 
245
203
  rl = createInterface({ input: process.stdin, output: process.stdout });
246
204
  const ans = (await rl.question("\n Install for all? [Y/n] ")).trim().toLowerCase();
247
- if (ans === "n" || ans === "no") return 0;
205
+ if (ans === "n" || ans === "no") {
206
+ void emitSetupFinished(0, 0);
207
+ return 0;
208
+ }
248
209
 
210
+ let installed = 0;
211
+ let failed = 0;
249
212
  for (const t of detected) {
250
213
  try {
251
214
  t.install(apiKey);
215
+ installed++;
216
+ void emitSetupClientResult(t.id, "installed");
252
217
  process.stdout.write(` ${teal("●")} installed for ${t.name}\n`);
253
218
  } catch (e) {
219
+ failed++;
220
+ const detail = describeInstallError(e);
221
+ void emitSetupClientResult(t.id, "failed", detail);
254
222
  const msg = e instanceof Error ? e.message : String(e);
223
+ appendLog({ kind: "setup", step: "client_install", client: t.id, code: detail.error_code, message: msg });
255
224
  process.stdout.write(red(` failed for ${t.name}: ${msg}\n`));
256
225
  process.stdout.write(
257
226
  dim(` add manually: claude mcp add omnidim -- npx -y @omnidim-ai/mcp-server\n`),
258
227
  );
259
228
  }
260
229
  }
230
+ void emitSetupFinished(installed, failed);
261
231
  if (isTelemetryDisabled()) {
262
232
  process.stdout.write(`\n ${dim("Telemetry off")}\n`);
263
233
  } else {
package/src/telemetry.ts CHANGED
@@ -3,6 +3,9 @@ import { homedir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
5
 
6
+ import { classifyToolError } from "./helpers.js";
7
+ import { appendLog } from "./logger.js";
8
+
6
9
  const ENDPOINT = "https://mcp.omnidim.io/api/telemetry/event";
7
10
  const CONFIG_DIR = join(homedir(), ".config", "omnidim");
8
11
  const INSTALL_ID_PATH = join(CONFIG_DIR, "install-id");
@@ -101,6 +104,28 @@ async function send(event: string, extra: Record<string, unknown> = {}): Promise
101
104
  }
102
105
  }
103
106
 
107
+ export interface SanitizedError {
108
+ error_class: string;
109
+ error_code: string;
110
+ }
111
+
112
+ // Reduce any thrown value to two low-cardinality, non-identifying fields.
113
+ // Never returns a message, stack, path, or payload, since those can carry
114
+ // usernames and file paths. Node's documented errno strings (ENOENT,
115
+ // EACCES, ...) and the error constructor name are safe to keep.
116
+ export function sanitizeError(error: unknown): SanitizedError {
117
+ if (error && typeof error === "object") {
118
+ const e = error as { name?: unknown; code?: unknown; constructor?: { name?: string } };
119
+ const rawName =
120
+ typeof e.name === "string" && e.name ? e.name : e.constructor?.name ?? "Error";
121
+ const error_class = /^[A-Za-z][A-Za-z0-9]{0,39}$/.test(rawName) ? rawName : "Error";
122
+ const error_code =
123
+ typeof e.code === "string" && /^[A-Z][A-Z0-9_]{1,31}$/.test(e.code) ? e.code : "unknown";
124
+ return { error_class, error_code };
125
+ }
126
+ return { error_class: "Error", error_code: "unknown" };
127
+ }
128
+
104
129
  export async function emitInstall(): Promise<void> {
105
130
  await send("install");
106
131
  }
@@ -109,31 +134,139 @@ export async function emitSessionStart(): Promise<void> {
109
134
  await send("session_start");
110
135
  }
111
136
 
112
- interface SessionEndPayload {
137
+ export type SetupKeyOutcome =
138
+ | "reused"
139
+ | "entered"
140
+ | "rejected_401"
141
+ | "network_error"
142
+ | "server_error"
143
+ | "aborted";
144
+
145
+ export async function emitSetupStarted(): Promise<void> {
146
+ await send("setup_started");
147
+ }
148
+
149
+ export async function emitSetupKeyResult(outcome: SetupKeyOutcome): Promise<void> {
150
+ await send("setup_key_result", { outcome });
151
+ }
152
+
153
+ export async function emitSetupClientResult(
154
+ client: string,
155
+ outcome: "installed" | "failed",
156
+ error?: SanitizedError & { exit_code?: number },
157
+ ): Promise<void> {
158
+ await send("setup_client_result", { client, outcome, ...(error ?? {}) });
159
+ }
160
+
161
+ export async function emitSetupFinished(
162
+ clientsInstalled: number,
163
+ clientsFailed: number,
164
+ ): Promise<void> {
165
+ await send("setup_finished", {
166
+ clients_installed: clientsInstalled,
167
+ clients_failed: clientsFailed,
168
+ });
169
+ }
170
+
171
+ interface ToolUsage {
172
+ tool: string;
173
+ count: number;
174
+ ok: number;
175
+ errors: Array<{ code: string; count: number }>;
176
+ }
177
+
178
+ export interface SessionSummary {
113
179
  duration_s: number;
114
- tools_called: Array<{ tool: string; count: number }>;
180
+ tools_called: ToolUsage[];
181
+ tool_errors_total: number;
115
182
  }
116
183
 
117
- export async function emitSessionEnd(payload: SessionEndPayload): Promise<void> {
118
- await send("session_end", { ...payload });
184
+ interface ToolStat {
185
+ count: number;
186
+ ok: number;
187
+ errors: Map<string, number>;
119
188
  }
120
189
 
121
- const toolCounts = new Map<string, number>();
190
+ const toolStats = new Map<string, ToolStat>();
122
191
  let sessionStartMs: number | null = null;
192
+ // Guards against one session reporting twice (a crash racing graceful
193
+ // shutdown), which would otherwise log an empty ghost event.
194
+ let terminated = false;
195
+
196
+ // outcome is "ok" for a successful call, otherwise a category code
197
+ // ("http_401", "network", "timeout", "validation", "upstream_html",
198
+ // "no_api_key", "unknown"). Never a tool's input or output.
199
+ export function recordToolResult(name: string, outcome: string): void {
200
+ let stat = toolStats.get(name);
201
+ if (!stat) {
202
+ stat = { count: 0, ok: 0, errors: new Map() };
203
+ toolStats.set(name, stat);
204
+ }
205
+ stat.count += 1;
206
+ if (outcome === "ok") {
207
+ stat.ok += 1;
208
+ } else {
209
+ stat.errors.set(outcome, (stat.errors.get(outcome) ?? 0) + 1);
210
+ }
211
+ }
123
212
 
124
- export function recordToolCall(name: string): void {
125
- toolCounts.set(name, (toolCounts.get(name) ?? 0) + 1);
213
+ // Catch-path helper: classify the error, count it in the session summary,
214
+ // and append the real (local-only) message to the diagnostics log.
215
+ export function recordToolError(name: string, error: unknown): void {
216
+ const code = classifyToolError(error);
217
+ recordToolResult(name, code);
218
+ appendLog({
219
+ kind: "tool_error",
220
+ tool: name,
221
+ code,
222
+ message: error instanceof Error ? error.message : String(error),
223
+ });
126
224
  }
127
225
 
128
226
  export function beginSession(): void {
129
227
  sessionStartMs = Date.now();
228
+ terminated = false;
130
229
  void emitSessionStart();
131
230
  }
132
231
 
133
- export function endSession(): SessionEndPayload {
232
+ function drainSession(): SessionSummary {
134
233
  const duration_s = sessionStartMs ? Math.round((Date.now() - sessionStartMs) / 1000) : 0;
135
- const tools_called = Array.from(toolCounts.entries()).map(([tool, count]) => ({ tool, count }));
234
+ let tool_errors_total = 0;
235
+ const tools_called: ToolUsage[] = Array.from(toolStats.entries()).map(([tool, stat]) => {
236
+ const errors = Array.from(stat.errors.entries()).map(([code, count]) => {
237
+ tool_errors_total += count;
238
+ return { code, count };
239
+ });
240
+ return { tool, count: stat.count, ok: stat.ok, errors };
241
+ });
136
242
  sessionStartMs = null;
137
- toolCounts.clear();
138
- return { duration_s, tools_called };
243
+ toolStats.clear();
244
+ return { duration_s, tools_called, tool_errors_total };
245
+ }
246
+
247
+ export function endSession(): SessionSummary {
248
+ return drainSession();
249
+ }
250
+
251
+ export async function emitSessionEnd(payload: SessionSummary): Promise<void> {
252
+ if (terminated) return;
253
+ terminated = true;
254
+ await send("session_end", { ...payload });
255
+ }
256
+
257
+ // Fires on a crash so the session still terminates with a record carrying
258
+ // its tool-call summary; a clean session_end never runs on a crash path.
259
+ export async function emitSessionCrash(error: unknown): Promise<void> {
260
+ if (terminated) return;
261
+ terminated = true;
262
+ const active = sessionStartMs !== null;
263
+ const summary = drainSession();
264
+ const phase = active ? "runtime" : "startup";
265
+ appendLog({
266
+ kind: "crash",
267
+ phase,
268
+ ...sanitizeError(error),
269
+ message: error instanceof Error ? error.message : String(error),
270
+ });
271
+ await send("session_crash", { phase, ...sanitizeError(error), ...summary });
139
272
  }