morpheus-cli 0.9.9 → 0.9.11

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.
Files changed (40) hide show
  1. package/dist/http/api.js +1 -0
  2. package/dist/http/routers/link.js +25 -4
  3. package/dist/runtime/link-worker.js +49 -0
  4. package/dist/runtime/memory/sqlite.js +89 -6
  5. package/dist/runtime/oracle.js +7 -0
  6. package/dist/runtime/webhooks/dispatcher.js +24 -1
  7. package/dist/ui/assets/{AuditDashboard-ZPJ5Pfwi.js → AuditDashboard-CM1YN1uk.js} +1 -1
  8. package/dist/ui/assets/Chat-D4y-g6Tw.js +41 -0
  9. package/dist/ui/assets/{Chronos-buCS0uuh.js → Chronos-D1yAb4M5.js} +1 -1
  10. package/dist/ui/assets/{ConfirmationModal-Bud3Ur7D.js → ConfirmationModal-DxUHZgTy.js} +1 -1
  11. package/dist/ui/assets/{Dashboard-CR6pBg6o.js → Dashboard-BzxmcHaS.js} +1 -1
  12. package/dist/ui/assets/{DeleteConfirmationModal-Cz1jfXgq.js → DeleteConfirmationModal-CqNXT_YQ.js} +1 -1
  13. package/dist/ui/assets/Documents-DLFZdmim.js +7 -0
  14. package/dist/ui/assets/{Logs-BgDEdckr.js → Logs-B1Bpy9dB.js} +1 -1
  15. package/dist/ui/assets/{MCPManager-yupmREOG.js → MCPManager-BbUDMh5Q.js} +1 -1
  16. package/dist/ui/assets/{ModelPricing-CbKHyj9P.js → ModelPricing-DCl-2_eJ.js} +1 -1
  17. package/dist/ui/assets/{Notifications-DpabYsn5.js → Notifications-8Cqj-mNp.js} +1 -1
  18. package/dist/ui/assets/{SatiMemories-D75MAyPU.js → SatiMemories-CdHUe6di.js} +1 -1
  19. package/dist/ui/assets/{SessionAudit-B3N9C1NR.js → SessionAudit-CtVHK_IH.js} +1 -1
  20. package/dist/ui/assets/{Settings-B1qZ-teD.js → Settings-Clge45Z0.js} +1 -1
  21. package/dist/ui/assets/{Skills-BmqC0xkq.js → Skills-0k7A2T5_.js} +1 -1
  22. package/dist/ui/assets/{Smiths-DdAcvxg6.js → Smiths-gjgBMN1F.js} +1 -1
  23. package/dist/ui/assets/{Tasks-D7SrOMOn.js → Tasks-AQ3MrrMp.js} +1 -1
  24. package/dist/ui/assets/{TrinityDatabases-cyhanIXu.js → TrinityDatabases-CGna6IMX.js} +1 -1
  25. package/dist/ui/assets/{UsageStats-DOgOQ4YN.js → UsageStats-B7EzZlZe.js} +1 -1
  26. package/dist/ui/assets/{WebhookManager-D2TdZ5kD.js → WebhookManager-Bb7KiucS.js} +1 -1
  27. package/dist/ui/assets/{audit-CZVCVFw_.js → audit-CJ2Ms81U.js} +1 -1
  28. package/dist/ui/assets/{chronos-DWSd5JMm.js → chronos-Bm68OSy4.js} +1 -1
  29. package/dist/ui/assets/{config-C2GB18ML.js → config-C88yQ_CP.js} +1 -1
  30. package/dist/ui/assets/{index-BiMscUrn.js → index-BxN2w9sY.js} +6 -6
  31. package/dist/ui/assets/index-C3Ff736M.css +1 -0
  32. package/dist/ui/assets/{mcp-JmpcV6nl.js → mcp-BE_OVkBe.js} +1 -1
  33. package/dist/ui/assets/{skills-D2stQj7i.js → skills-Dt0qU4gH.js} +1 -1
  34. package/dist/ui/assets/{stats-cDmpngPQ.js → stats-Bmdps1LR.js} +1 -1
  35. package/dist/ui/index.html +2 -2
  36. package/dist/ui/sw.js +1 -1
  37. package/package.json +1 -1
  38. package/dist/ui/assets/Chat-BAivCJ5N.js +0 -41
  39. package/dist/ui/assets/Documents-CYW79d8T.js +0 -7
  40. package/dist/ui/assets/index-U7hzqcK_.css +0 -1
package/dist/http/api.js CHANGED
@@ -184,6 +184,7 @@ export function createApiRouter(oracle, chronosWorker) {
184
184
  provider: row.provider ?? null,
185
185
  model: row.model ?? null,
186
186
  audio_duration_seconds: row.audio_duration_seconds ?? null,
187
+ source: row.source ?? null,
187
188
  sati_memories_count: null,
188
189
  };
189
190
  });
@@ -79,6 +79,10 @@ export function createLinkRouter() {
79
79
  try {
80
80
  const config = ConfigManager.getInstance().getLinkConfig();
81
81
  const maxSizeMB = config.max_file_size_mb;
82
+ // Get expected size from header for validation
83
+ const expectedSize = req.headers['x-expected-size']
84
+ ? parseInt(req.headers['x-expected-size'], 10)
85
+ : null;
82
86
  // Configure multer with config max size
83
87
  const uploadWithConfig = multer({
84
88
  storage,
@@ -107,13 +111,30 @@ export function createLinkRouter() {
107
111
  if (!req.file) {
108
112
  return res.status(400).json({ error: 'No file uploaded' });
109
113
  }
110
- // Trigger immediate scan
111
- const result = await worker.tick();
114
+ // Validate file size if expected size was provided
115
+ if (expectedSize !== null) {
116
+ const actualSize = req.file.size;
117
+ const sizeDiff = Math.abs(actualSize - expectedSize);
118
+ const tolerance = expectedSize * 0.01; // 1% tolerance
119
+ if (sizeDiff > tolerance) {
120
+ // Delete the uploaded file
121
+ await fs.unlink(req.file.path).catch(() => { });
122
+ return res.status(400).json({
123
+ error: 'File size mismatch',
124
+ expected: expectedSize,
125
+ actual: actualSize,
126
+ });
127
+ }
128
+ }
129
+ // Process the document immediately (validates integrity + indexes)
130
+ const linkWorker = LinkWorker.getInstance();
131
+ const result = await linkWorker.processDocument(req.file.path);
112
132
  res.json({
113
- message: 'File uploaded successfully',
133
+ message: 'File uploaded and processed',
114
134
  filename: Buffer.from(req.file.originalname, 'latin1').toString('utf-8'),
115
135
  path: req.file.path,
116
- indexed: result.indexed,
136
+ indexed: result === 'indexed',
137
+ status: result,
117
138
  });
118
139
  }
119
140
  catch (err) {
@@ -1,6 +1,7 @@
1
1
  import { homedir } from 'os';
2
2
  import path from 'path';
3
3
  import fs from 'fs-extra';
4
+ import fsSync from 'fs';
4
5
  import { LinkRepository } from './link-repository.js';
5
6
  import { LinkSearch } from './link-search.js';
6
7
  import { hashFile, processDocument, isSupportedFormat } from './link-chunker.js';
@@ -151,11 +152,59 @@ export class LinkWorker {
151
152
  }
152
153
  return files;
153
154
  }
155
+ /**
156
+ * Validate file integrity by checking magic bytes.
157
+ */
158
+ async validateFileIntegrity(filePath) {
159
+ const ext = path.extname(filePath).toLowerCase();
160
+ try {
161
+ // Read first 8 bytes using synchronous fs (fs-extra doesn't support position option)
162
+ const buffer = Buffer.alloc(8);
163
+ const fd = fsSync.openSync(filePath, 'r');
164
+ fsSync.readSync(fd, buffer, 0, 8, 0);
165
+ fsSync.closeSync(fd);
166
+ if (buffer.length === 0) {
167
+ return { valid: false, error: 'Empty file' };
168
+ }
169
+ // Check magic bytes based on file type
170
+ if (ext === '.pdf') {
171
+ // PDF magic bytes: %PDF (25 50 44 46)
172
+ if (buffer[0] !== 0x25 || buffer[1] !== 0x50 || buffer[2] !== 0x44 || buffer[3] !== 0x46) {
173
+ return { valid: false, error: 'Invalid PDF file: missing magic bytes' };
174
+ }
175
+ }
176
+ else if (ext === '.docx') {
177
+ // DOCX is a ZIP file, check PK (50 4B)
178
+ if (buffer[0] !== 0x50 || buffer[1] !== 0x4B) {
179
+ return { valid: false, error: 'Invalid DOCX file: missing ZIP magic bytes' };
180
+ }
181
+ }
182
+ else if (ext === '.txt' || ext === '.md') {
183
+ // Text files - just check it's readable (first bytes should be valid UTF-8)
184
+ // Allow any bytes for text files, just check not empty
185
+ if (buffer.length === 0) {
186
+ return { valid: false, error: 'Empty file' };
187
+ }
188
+ }
189
+ return { valid: true };
190
+ }
191
+ catch (err) {
192
+ return { valid: false, error: `Failed to read file: ${err.message}` };
193
+ }
194
+ }
154
195
  /**
155
196
  * Process a single document: check hash, parse, chunk, embed.
156
197
  */
157
198
  async processDocument(filePath) {
158
199
  const existingDoc = this.repository.getDocumentByPath(filePath);
200
+ // Validate file integrity first
201
+ const integrity = await this.validateFileIntegrity(filePath);
202
+ if (!integrity.valid) {
203
+ if (existingDoc) {
204
+ this.repository.updateDocumentStatus(existingDoc.id, 'error', integrity.error);
205
+ }
206
+ return 'error';
207
+ }
159
208
  // Calculate file hash
160
209
  let fileHash;
161
210
  try {
@@ -193,6 +193,7 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
193
193
  'audio_duration_seconds',
194
194
  'agent',
195
195
  'duration_ms',
196
+ 'source',
196
197
  ];
197
198
  const integerColumns = new Set(['input_tokens', 'output_tokens', 'total_tokens', 'cache_read_tokens', 'duration_ms']);
198
199
  const realColumns = new Set(['audio_duration_seconds']);
@@ -226,6 +227,54 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
226
227
  console.warn(`[SQLite] model_pricing migration failed: ${error}`);
227
228
  }
228
229
  }
230
+ /**
231
+ * Removes orphaned ToolMessages and incomplete tool-call groups that can
232
+ * appear when the LIMIT clause truncates the message window mid-sequence.
233
+ *
234
+ * Messages arrive in DESC order (newest first). An orphaned ToolMessage at
235
+ * the end of this array means its parent AIMessage (with tool_calls) was
236
+ * outside the window. We also strip AIMessages whose tool_calls have no
237
+ * corresponding ToolMessage responses in the window.
238
+ */
239
+ sanitizeMessageWindow(messages) {
240
+ if (messages.length === 0)
241
+ return messages;
242
+ // Work in chronological order (reverse of DESC) for easier reasoning.
243
+ const chrono = [...messages].reverse();
244
+ // Drop leading ToolMessages that have no preceding AIMessage with matching tool_calls.
245
+ let startIdx = 0;
246
+ while (startIdx < chrono.length && chrono[startIdx] instanceof ToolMessage) {
247
+ startIdx++;
248
+ }
249
+ // Also drop a leading AIMessage that has tool_calls but whose ToolMessage
250
+ // responses were trimmed (they would have been before it in the DB).
251
+ if (startIdx < chrono.length && chrono[startIdx] instanceof AIMessage) {
252
+ const ai = chrono[startIdx];
253
+ if (ai.tool_calls && ai.tool_calls.length > 0) {
254
+ // Check if ALL tool_call responses exist after this AIMessage
255
+ const toolCallIds = ai.tool_calls.map((tc) => tc.id).filter(Boolean);
256
+ const remaining = chrono.slice(startIdx + 1);
257
+ let allFound = true;
258
+ for (let i = 0; i < toolCallIds.length; i++) {
259
+ const hasResponse = remaining.some((m) => m instanceof ToolMessage && m.tool_call_id === toolCallIds[i]);
260
+ if (!hasResponse) {
261
+ allFound = false;
262
+ break;
263
+ }
264
+ }
265
+ if (!allFound)
266
+ startIdx++;
267
+ }
268
+ }
269
+ if (startIdx === 0) {
270
+ // No sanitization needed — return original DESC order.
271
+ return messages;
272
+ }
273
+ // Return in the original DESC order (newest first), excluding trimmed messages.
274
+ const sanitized = chrono.slice(startIdx);
275
+ sanitized.reverse();
276
+ return sanitized;
277
+ }
229
278
  /**
230
279
  * Retrieves all messages for the current session from the database.
231
280
  * @returns Promise resolving to an array of BaseMessage objects
@@ -239,7 +288,7 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
239
288
  ORDER BY id DESC
240
289
  LIMIT ?`);
241
290
  const rows = stmt.all(this.sessionId, this.limit);
242
- return rows.map((row) => {
291
+ const mapped = rows.map((row) => {
243
292
  let msg;
244
293
  // Reconstruct usage metadata if present
245
294
  const usage_metadata = row.total_tokens != null ? {
@@ -303,6 +352,13 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
303
352
  }
304
353
  return msg;
305
354
  });
355
+ // Sanitize: the LIMIT clause may cut in the middle of a tool_calls/ToolMessage
356
+ // sequence, leaving orphaned ToolMessages without a preceding AIMessage that
357
+ // contains the corresponding tool_calls. LLM providers reject this.
358
+ // Messages are in DESC order (newest first) here — orphans appear at the tail.
359
+ // Remove trailing ToolMessages and AIMessages with tool_calls that have no
360
+ // matching ToolMessage response (i.e. incomplete tool-call groups at the boundary).
361
+ return this.sanitizeMessageWindow(mapped);
306
362
  }
307
363
  catch (error) {
308
364
  // Check if it's a database lock error
@@ -322,7 +378,7 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
322
378
  }
323
379
  try {
324
380
  const placeholders = sessionIds.map(() => '?').join(', ');
325
- const stmt = this.db.prepare(`SELECT id, session_id, type, content, created_at, input_tokens, output_tokens, total_tokens, cache_read_tokens, provider, model, agent, duration_ms, audio_duration_seconds
381
+ const stmt = this.db.prepare(`SELECT id, session_id, type, content, created_at, input_tokens, output_tokens, total_tokens, cache_read_tokens, provider, model, agent, duration_ms, audio_duration_seconds, source
326
382
  FROM messages
327
383
  WHERE session_id IN (${placeholders})
328
384
  ORDER BY id DESC
@@ -378,6 +434,7 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
378
434
  const audioDurationSeconds = usage?.audio_duration_seconds ?? null;
379
435
  const agent = anyMsg.agent_metadata?.agent ?? 'oracle';
380
436
  const durationMs = anyMsg.duration_ms ?? null;
437
+ const source = anyMsg.source_metadata?.source ?? null;
381
438
  // Handle special content serialization for Tools
382
439
  let finalContent = "";
383
440
  if (type === 'ai' && (message.tool_calls?.length ?? 0) > 0) {
@@ -400,8 +457,8 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
400
457
  ? message.content
401
458
  : JSON.stringify(message.content);
402
459
  }
403
- const stmt = this.db.prepare("INSERT INTO messages (session_id, type, content, created_at, input_tokens, output_tokens, total_tokens, cache_read_tokens, provider, model, audio_duration_seconds, agent, duration_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
404
- stmt.run(this.sessionId, type, finalContent, Date.now(), inputTokens, outputTokens, totalTokens, cacheReadTokens, provider, model, audioDurationSeconds, agent, durationMs);
460
+ const stmt = this.db.prepare("INSERT INTO messages (session_id, type, content, created_at, input_tokens, output_tokens, total_tokens, cache_read_tokens, provider, model, audio_duration_seconds, agent, duration_ms, source) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
461
+ stmt.run(this.sessionId, type, finalContent, Date.now(), inputTokens, outputTokens, totalTokens, cacheReadTokens, provider, model, audioDurationSeconds, agent, durationMs, source);
405
462
  // Verificar se a sessão tem título e definir automaticamente se necessário
406
463
  await this.setSessionTitleIfNeeded();
407
464
  }
@@ -428,7 +485,7 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
428
485
  async addMessages(messages) {
429
486
  if (messages.length === 0)
430
487
  return;
431
- const stmt = this.db.prepare("INSERT INTO messages (session_id, type, content, created_at, input_tokens, output_tokens, total_tokens, cache_read_tokens, provider, model, audio_duration_seconds, agent, duration_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
488
+ const stmt = this.db.prepare("INSERT INTO messages (session_id, type, content, created_at, input_tokens, output_tokens, total_tokens, cache_read_tokens, provider, model, audio_duration_seconds, agent, duration_ms, source) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
432
489
  const insertAll = this.db.transaction((msgs) => {
433
490
  for (const message of msgs) {
434
491
  let type;
@@ -455,7 +512,7 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
455
512
  else {
456
513
  finalContent = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
457
514
  }
458
- stmt.run(this.sessionId, type, finalContent, Date.now(), usage?.input_tokens ?? null, usage?.output_tokens ?? null, usage?.total_tokens ?? null, usage?.input_token_details?.cache_read ?? usage?.cache_read_tokens ?? null, anyMsg.provider_metadata?.provider ?? null, anyMsg.provider_metadata?.model ?? null, usage?.audio_duration_seconds ?? null, anyMsg.agent_metadata?.agent ?? 'oracle', anyMsg.duration_ms ?? null);
515
+ stmt.run(this.sessionId, type, finalContent, Date.now(), usage?.input_tokens ?? null, usage?.output_tokens ?? null, usage?.total_tokens ?? null, usage?.input_token_details?.cache_read ?? usage?.cache_read_tokens ?? null, anyMsg.provider_metadata?.provider ?? null, anyMsg.provider_metadata?.model ?? null, usage?.audio_duration_seconds ?? null, anyMsg.agent_metadata?.agent ?? 'oracle', anyMsg.duration_ms ?? null, anyMsg.source_metadata?.source ?? null);
459
516
  }
460
517
  });
461
518
  try {
@@ -1009,6 +1066,32 @@ export class SQLiteChatMessageHistory extends BaseListChatMessageHistory {
1009
1066
  WHERE channel = ? AND user_id = ?
1010
1067
  `).run(channel, userId);
1011
1068
  }
1069
+ /**
1070
+ * Returns the session_id from user_channel_sessions with the most recent updated_at
1071
+ * among the given channel names.
1072
+ */
1073
+ getMostRecentChannelSession(channels) {
1074
+ if (channels.length === 0)
1075
+ return null;
1076
+ const placeholders = channels.map(() => '?').join(', ');
1077
+ const result = this.db.prepare(`
1078
+ SELECT session_id FROM user_channel_sessions
1079
+ WHERE channel IN (${placeholders})
1080
+ ORDER BY updated_at DESC LIMIT 1
1081
+ `).get(...channels);
1082
+ return result ? result.session_id : null;
1083
+ }
1084
+ /**
1085
+ * Returns the most recent active/paused session, or null if none exists.
1086
+ */
1087
+ getMostRecentSession() {
1088
+ const session = this.db.prepare(`
1089
+ SELECT id FROM sessions
1090
+ WHERE status IN ('active', 'paused')
1091
+ ORDER BY started_at DESC LIMIT 1
1092
+ `).get();
1093
+ return session ? session.id : null;
1094
+ }
1012
1095
  /**
1013
1096
  * Closes the database connection.
1014
1097
  * Should be called when the history object is no longer needed.
@@ -225,6 +225,13 @@ export class Oracle {
225
225
  provider: isTelephonist ? this.config.audio?.provider : this.config.llm.provider,
226
226
  model: isTelephonist ? this.config.audio?.model : this.config.llm.model
227
227
  };
228
+ // Inject source metadata for automated origins (webhook, chronos)
229
+ if (taskContext?.origin_channel === 'webhook') {
230
+ userMessage.source_metadata = { source: 'webhook' };
231
+ }
232
+ else if (taskContext?.origin_channel === 'chronos') {
233
+ userMessage.source_metadata = { source: 'chronos' };
234
+ }
228
235
  // Attach extra usage (e.g. from Audio) to the user message to be persisted
229
236
  if (extraUsage) {
230
237
  userMessage.usage_metadata = extraUsage;
@@ -2,6 +2,7 @@ import { WebhookRepository } from './repository.js';
2
2
  import { TaskRepository } from '../tasks/repository.js';
3
3
  import { DisplayManager } from '../display.js';
4
4
  import { ChannelRegistry } from '../../channels/registry.js';
5
+ import { SQLiteChatMessageHistory } from '../memory/sqlite.js';
5
6
  const STALE_NOTIFICATION_THRESHOLD_MS = 2 * 60 * 1000; // 2 minutes
6
7
  export class WebhookDispatcher {
7
8
  static oracle = null;
@@ -29,10 +30,11 @@ export class WebhookDispatcher {
29
30
  return;
30
31
  }
31
32
  const message = this.buildPrompt(webhook.prompt, payload);
33
+ const sessionId = this.resolveSessionId(webhook);
32
34
  try {
33
35
  const response = await oracle.chat(message, undefined, false, {
34
36
  origin_channel: 'webhook',
35
- session_id: `webhook-${webhook.id}`,
37
+ session_id: sessionId,
36
38
  origin_message_id: notificationId,
37
39
  });
38
40
  // Check whether Oracle delegated a task for this notification.
@@ -57,6 +59,27 @@ export class WebhookDispatcher {
57
59
  await this.notifyChannels(webhook, result, 'failed');
58
60
  }
59
61
  }
62
+ /**
63
+ * Resolves the session ID for webhook execution.
64
+ * 1. Most recent channel session from webhook's notification_channels
65
+ * 2. Most recent active/paused session
66
+ * 3. Fallback to webhook-<id>
67
+ */
68
+ resolveSessionId(webhook) {
69
+ const history = new SQLiteChatMessageHistory({ sessionId: 'tmp' });
70
+ try {
71
+ const channels = webhook.notification_channels.filter(ch => ch !== 'ui');
72
+ if (channels.length > 0) {
73
+ const channelSession = history.getMostRecentChannelSession(channels);
74
+ if (channelSession)
75
+ return channelSession;
76
+ }
77
+ return history.getMostRecentSession() ?? `webhook-${webhook.id}`;
78
+ }
79
+ finally {
80
+ history.close();
81
+ }
82
+ }
60
83
  /**
61
84
  * Combines the user-authored webhook prompt with the received payload.
62
85
  */
@@ -1 +1 @@
1
- import{j as e,m as n}from"./vendor-motion-C3CZ8ZlO.js";import{L as O,r as B}from"./vendor-react-DikRIOlj.js";import{a as R}from"./audit-CZVCVFw_.js";import{Q as _,O as D,h as L,i as F,as as v,E as k,m as N,A as z,g as S,aw as I,k as U,J as A,ax as W,K as $,p as G,ai as P}from"./vendor-icons-NHF9HNeN.js";import"./vendor-utils-D4NnWbOU.js";import"./index-BiMscUrn.js";function u(r){return r===0?"$0.00":r<1e-4?"<$0.0001":r<.01?`$${r.toFixed(4)}`:`$${r.toFixed(2)}`}function m(r){return r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}k`:String(r)}function j(r){if(r<1e3)return`${r}ms`;if(r<6e4)return`${(r/1e3).toFixed(1)}s`;const i=Math.floor(r/6e4),l=Math.floor(r%6e4/1e3);return`${i}m ${l}s`}function V(r){return r?new Date(r).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function T(r,i){return i?`${Math.round(r/i*100)}%`:"0%"}function H({data:r}){const[i,l]=B.useState(null);if(!r.length)return e.jsx("p",{className:"text-xs text-gray-400 dark:text-matrix-secondary/50 py-4",children:"No activity in the last 30 days."});const s=Math.max(...r.map(a=>a.eventCount),1);return e.jsx("div",{className:"flex items-end gap-0.5 h-24 w-full relative",children:r.map((a,c)=>{const y=Math.max(4,Math.round(a.eventCount/s*88)),g=i===c;return e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-end group",onMouseEnter:()=>l(c),onMouseLeave:()=>l(null),children:[g&&e.jsxs("div",{className:"absolute -top-10 left-1/2 -translate-x-1/2 z-10 bg-gray-900 dark:bg-zinc-800 text-white text-[10px] rounded px-2 py-1 whitespace-nowrap pointer-events-none shadow-lg",children:[a.date,": ",a.eventCount," events · ",u(a.estimatedCostUsd)]}),e.jsx("div",{style:{height:y},className:`w-full rounded-t transition-colors ${g?"bg-blue-500 dark:bg-matrix-highlight":"bg-blue-300/70 dark:bg-matrix-highlight/40 group-hover:bg-blue-400 dark:group-hover:bg-matrix-highlight/60"}`})]},a.date)})})}function h({icon:r,label:i,value:l,sub:s,color:a="blue"}){const c={blue:"bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-200 dark:border-blue-800/40",green:"bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-matrix-highlight border-green-200 dark:border-green-800/40",amber:"bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 border-amber-200 dark:border-amber-800/40",purple:"bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-200 dark:border-purple-800/40",rose:"bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 border-rose-200 dark:border-rose-800/40",teal:"bg-teal-50 dark:bg-teal-900/20 text-teal-600 dark:text-teal-400 border-teal-200 dark:border-teal-800/40"};return e.jsxs("div",{className:`rounded-lg border p-4 flex gap-3 items-start ${c[a]}`,children:[e.jsx("div",{className:"mt-0.5 flex-shrink-0",children:r}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium opacity-70 uppercase tracking-wider mb-0.5",children:i}),e.jsx("p",{className:"text-xl font-bold font-mono leading-tight",children:l}),s&&e.jsx("div",{className:"text-[11px] opacity-60 mt-0.5 leading-snug",children:s})]})]})}function o({title:r,icon:i,children:l}){return e.jsxs("div",{className:"rounded-lg border border-gray-200 dark:border-matrix-primary overflow-hidden bg-white dark:bg-zinc-900 shadow-sm",children:[e.jsxs("div",{className:"px-4 py-3 bg-gray-50 dark:bg-zinc-900 border-b border-gray-200 dark:border-matrix-primary flex items-center gap-2",children:[e.jsx("span",{className:"text-gray-500 dark:text-matrix-secondary/70",children:i}),e.jsx("h2",{className:"text-sm font-semibold text-gray-700 dark:text-matrix-secondary uppercase tracking-wider",children:r})]}),e.jsx("div",{className:"p-4",children:l})]})}const J={oracle:"🔮",apoc:"🧑‍🔬",neo:"🥷",trinity:"👩‍💻",smith:"🕶️",chronos:"⏰",sati:"🧠",telephonist:"📞",link:"🕵️‍♂️",unknown:"?"},w={oracle:"bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300",apoc:"bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",neo:"bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300",trinity:"bg-teal-100 text-teal-700 dark:bg-teal-900/40 dark:text-teal-300",smith:"bg-gray-200 text-gray-700 dark:bg-gray-700/60 dark:text-gray-300",chronos:"bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300",sati:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",telephonist:"bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300",link:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300",unknown:"bg-gray-100 text-gray-500 dark:bg-zinc-800 dark:text-matrix-secondary/60"};function M({agent:r}){const i=w[r]??w.unknown;return e.jsxs("span",{className:`inline-flex items-center gap-1 text-[11px] font-semibold px-1.5 py-0.5 rounded ${i}`,children:[J[r]??"?"," ",r.toUpperCase()]})}function K({status:r}){const i={active:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-matrix-highlight",paused:"bg-gray-100 text-gray-600 dark:bg-zinc-800 dark:text-matrix-secondary",archived:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",deleted:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",unknown:"bg-gray-100 text-gray-500 dark:bg-zinc-800 dark:text-matrix-secondary/60"};return e.jsx("span",{className:`text-[10px] font-semibold uppercase px-1.5 py-0.5 rounded ${i[r]??i.unknown}`,children:r})}const Q={llm_call:e.jsx(v,{size:13}),tool_call:e.jsx(k,{size:13}),mcp_tool:e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M3.49994 11.7501L11.6717 3.57855C12.7762 2.47398 14.5672 2.47398 15.6717 3.57855C16.7762 4.68312 16.7762 6.47398 15.6717 7.57855M15.6717 7.57855L9.49994 13.7501M15.6717 7.57855C16.7762 6.47398 18.5672 6.47398 19.6717 7.57855C20.7762 8.68312 20.7762 10.474 19.6717 11.5785L12.7072 18.543C12.3167 18.9335 12.3167 19.5667 12.7072 19.9572L13.9999 21.2499",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M17.4999 9.74921L11.3282 15.921C10.2237 17.0255 8.43272 17.0255 7.32823 15.921C6.22373 14.8164 6.22373 13.0255 7.32823 11.921L13.4999 5.74939",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),memory_recovery:e.jsx(N,{size:13}),memory_persist:e.jsx(N,{size:13}),telephonist:e.jsx($,{size:13}),skill_loaded:e.jsx(A,{size:13}),chronos_job:e.jsx(S,{size:13}),task_created:e.jsx(P,{size:13}),task_completed:e.jsx(G,{size:13})},Z={llm_call:"text-blue-500 dark:text-blue-400",tool_call:"text-amber-500 dark:text-amber-400",mcp_tool:"text-purple-500 dark:text-purple-400",memory_recovery:"text-emerald-500 dark:text-emerald-400",memory_persist:"text-violet-500 dark:text-violet-400",telephonist:"text-rose-500 dark:text-rose-400",skill_loaded:"text-teal-500 dark:text-teal-400",chronos_job:"text-orange-500 dark:text-orange-400",task_created:"text-gray-500 dark:text-matrix-secondary",task_completed:"text-green-600 dark:text-matrix-highlight"};function q({eventType:r}){return r==="mcp_tool"?e.jsx("span",{className:"flex-shrink-0 text-purple-500 dark:text-purple-400",children:e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M3.49994 11.7501L11.6717 3.57855C12.7762 2.47398 14.5672 2.47398 15.6717 3.57855C16.7762 4.68312 16.7762 6.47398 15.6717 7.57855M15.6717 7.57855L9.49994 13.7501M15.6717 7.57855C16.7762 6.47398 18.5672 6.47398 19.6717 7.57855C20.7762 8.68312 20.7762 10.474 19.6717 11.5785L12.7072 18.543C12.3167 18.9335 12.3167 19.5667 12.7072 19.9572L13.9999 21.2499",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M17.4999 9.74921L11.3282 15.921C10.2237 17.0255 8.43272 17.0255 7.32823 15.921C6.22373 14.8164 6.22373 13.0255 7.32823 11.921L13.4999 5.74939",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})}):e.jsx(k,{size:13,className:"flex-shrink-0 text-amber-500 dark:text-amber-400"})}const X={llm_call:"bg-blue-400 dark:bg-blue-500",tool_call:"bg-amber-400 dark:bg-amber-500",mcp_tool:"bg-purple-400 dark:bg-purple-500",memory_recovery:"bg-emerald-400 dark:bg-emerald-500",memory_persist:"bg-violet-400 dark:bg-violet-500",telephonist:"bg-rose-400 dark:bg-rose-500",skill_loaded:"bg-teal-400 dark:bg-teal-500",chronos_job:"bg-orange-400 dark:bg-orange-500",task_created:"bg-gray-300 dark:bg-matrix-secondary/50",task_completed:"bg-green-400 dark:bg-matrix-highlight/70"},Y={hidden:{opacity:0},show:{opacity:1,transition:{staggerChildren:.04}}},x={hidden:{opacity:0,y:12},show:{opacity:1,y:0}},le=()=>{const{data:r,isLoading:i,mutate:l}=R();if(i)return e.jsxs("div",{className:"flex items-center justify-center h-64 gap-3 text-gray-400 dark:text-matrix-secondary",children:[e.jsx(_,{size:20,className:"animate-spin"}),e.jsx("span",{className:"text-sm font-mono",children:"Loading audit data…"})]});if(!r)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-2 text-gray-400 dark:text-matrix-secondary",children:[e.jsx(D,{size:24}),e.jsx("span",{className:"text-sm",children:"Failed to load audit data."})]});const{sessions:s,totals:a,byAgent:c,byModel:y,topTools:g,recentSessions:f,dailyActivity:p}=r,C=[["llm_call",a.llmCallCount],["tool_call",a.toolCallCount],["mcp_tool",a.mcpToolCount],["memory_recovery",a.memoryRecoveryCount],["memory_persist",a.memoryPersistCount],["telephonist",a.telephonistCount],["skill_loaded",a.skillCount],["chronos_job",a.chronosJobCount],["task_created",a.taskCreatedCount],["task_completed",a.taskCompletedCount]].filter(([,t])=>t>0).sort((t,d)=>d[1]-t[1]),E=Math.max(...C.map(([,t])=>t),1);return e.jsxs(n.div,{variants:Y,initial:"hidden",animate:"show",className:"space-y-6",children:[e.jsxs(n.div,{variants:x,className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-500/10 dark:bg-blue-500/20 border border-blue-200 dark:border-blue-800/40 flex items-center justify-center",children:e.jsx(L,{className:"w-5 h-5 text-blue-600 dark:text-blue-400"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-gray-900 dark:text-matrix-highlight",children:"Global Audit"}),e.jsxs("p",{className:"text-sm text-gray-500 dark:text-matrix-secondary/60 mt-0.5",children:[s.withAudit," sessions with audit data · ",a.totalEventCount.toLocaleString()," events total"]})]})]}),e.jsxs("button",{onClick:()=>l(),className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-gray-200 dark:border-matrix-primary text-sm text-gray-500 dark:text-matrix-secondary hover:bg-gray-50 dark:hover:bg-zinc-900 transition-colors",children:[e.jsx(_,{size:14})," Refresh"]})]}),e.jsxs(n.div,{variants:x,className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:[e.jsx(h,{icon:e.jsx(F,{size:16}),label:"Total Cost",value:u(a.estimatedCostUsd),color:"green"}),e.jsx(h,{icon:e.jsx(v,{size:16}),label:"LLM Calls",value:a.llmCallCount.toLocaleString(),color:"blue"}),e.jsx(h,{icon:e.jsx(k,{size:16}),label:"Tool Calls",value:(a.toolCallCount+a.mcpToolCount).toLocaleString(),sub:e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[a.toolCallCount," native"]}),e.jsx("br",{}),e.jsxs("span",{children:[a.mcpToolCount," MCP"]})]}),color:"amber"}),e.jsx(h,{icon:e.jsx(N,{size:16}),label:"Memory Hits",value:a.memoryRecoveryCount.toLocaleString(),color:"teal"}),e.jsx(h,{icon:e.jsx(z,{size:16}),label:"Total Tokens",value:m(a.totalInputTokens+a.totalOutputTokens),sub:e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:["↑",m(a.totalInputTokens)," in"]}),e.jsx("br",{}),e.jsxs("span",{children:["↓",m(a.totalOutputTokens)," out"]})]}),color:"purple"}),e.jsx(h,{icon:e.jsx(S,{size:16}),label:"Total Time",value:j(a.totalDurationMs),color:"rose"})]}),e.jsxs(n.div,{variants:x,className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs(o,{title:"Sessions",icon:e.jsx(I,{size:14}),children:[e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-4",children:[{label:"Total",value:s.total,cls:"text-gray-700 dark:text-matrix-secondary"},{label:"With Audit",value:s.withAudit,cls:"text-blue-600 dark:text-blue-400"},{label:"Active",value:s.active,cls:"text-green-600 dark:text-matrix-highlight"},{label:"Paused",value:s.paused,cls:"text-gray-500 dark:text-matrix-secondary"},{label:"Archived",value:s.archived,cls:"text-amber-600 dark:text-amber-400"},{label:"Deleted",value:s.deleted,cls:"text-red-500 dark:text-red-400"}].map(({label:t,value:d,cls:b})=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-gray-400 dark:text-matrix-secondary/50",children:t}),e.jsx("span",{className:`text-2xl font-bold font-mono ${b}`,children:d})]},t))}),s.total>0&&e.jsxs("div",{className:"h-2 rounded-full overflow-hidden flex gap-px",children:[s.active>0&&e.jsx("div",{className:"bg-green-400 dark:bg-matrix-highlight/70",style:{flex:s.active}}),s.paused>0&&e.jsx("div",{className:"bg-gray-300 dark:bg-matrix-primary/50",style:{flex:s.paused}}),s.archived>0&&e.jsx("div",{className:"bg-amber-400 dark:bg-amber-500/70",style:{flex:s.archived}}),s.deleted>0&&e.jsx("div",{className:"bg-red-400 dark:bg-red-500/70",style:{flex:s.deleted}})]})]}),e.jsxs(o,{title:"Activity — Last 30 Days",icon:e.jsx(U,{size:14}),children:[e.jsx(H,{data:p}),p.length>0&&e.jsxs("div",{className:"flex gap-4 mt-2 text-[11px] text-gray-400 dark:text-matrix-secondary/50 font-mono",children:[e.jsx("span",{children:p[0]?.date}),e.jsx("span",{className:"flex-1 text-right",children:p[p.length-1]?.date})]})]})]}),e.jsx(n.div,{variants:x,children:e.jsx(o,{title:"Events by Type",icon:e.jsx(z,{size:14}),children:e.jsx("div",{className:"space-y-2",children:C.map(([t,d])=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`flex-shrink-0 w-5 flex justify-center ${Z[t]??"text-gray-400"}`,children:Q[t]}),e.jsx("span",{className:"text-xs font-mono text-gray-600 dark:text-matrix-secondary w-32 flex-shrink-0",children:t}),e.jsx("div",{className:"flex-1 h-2 bg-gray-100 dark:bg-zinc-800 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${X[t]??"bg-gray-400"}`,style:{width:T(d,E)}})}),e.jsx("span",{className:"text-xs font-mono text-gray-500 dark:text-matrix-secondary w-16 text-right",children:d.toLocaleString()}),e.jsx("span",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/50 w-10 text-right",children:T(d,a.totalEventCount)})]},t))})})}),e.jsxs(n.div,{variants:x,className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(o,{title:"By Agent",icon:e.jsx(A,{size:14}),children:c.length===0?e.jsx("p",{className:"text-sm text-gray-400 dark:text-matrix-secondary/50",children:"No agent data."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-matrix-secondary/50 border-b border-gray-100 dark:border-matrix-primary/30",children:[e.jsx("th",{className:"pb-2 text-left",children:"Agent"}),e.jsx("th",{className:"pb-2 text-right",children:"LLM"}),e.jsx("th",{className:"pb-2 text-right",children:"Tools"}),e.jsx("th",{className:"pb-2 text-right",children:"Tokens"}),e.jsx("th",{className:"pb-2 text-right",children:"Time"}),e.jsx("th",{className:"pb-2 text-right",children:"Cost"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 dark:divide-matrix-primary/20",children:c.map(t=>e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-zinc-900/50",children:[e.jsx("td",{className:"py-1.5",children:e.jsx(M,{agent:t.agent})}),e.jsx("td",{className:"py-1.5 text-right text-gray-600 dark:text-matrix-secondary",children:t.llmCalls.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-gray-600 dark:text-matrix-secondary",children:t.toolCalls.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-gray-500 dark:text-matrix-secondary/70",children:["↑",m(t.inputTokens)," ↓",m(t.outputTokens)]}),e.jsx("td",{className:"py-1.5 text-right text-gray-500 dark:text-matrix-secondary/70",children:j(t.totalDurationMs)}),e.jsx("td",{className:"py-1.5 text-right font-semibold text-gray-700 dark:text-matrix-secondary",children:u(t.estimatedCostUsd)})]},t.agent))})]})})}),e.jsx(o,{title:"By Model",icon:e.jsx(v,{size:14}),children:y.length===0?e.jsx("p",{className:"text-sm text-gray-400 dark:text-matrix-secondary/50",children:"No model data."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-matrix-secondary/50 border-b border-gray-100 dark:border-matrix-primary/30",children:[e.jsx("th",{className:"pb-2 text-left",children:"Model"}),e.jsx("th",{className:"pb-2 text-right",children:"Calls"}),e.jsx("th",{className:"pb-2 text-right",children:"In"}),e.jsx("th",{className:"pb-2 text-right",children:"Out"}),e.jsx("th",{className:"pb-2 text-right",children:"Cost"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 dark:divide-matrix-primary/20",children:y.map(t=>e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-zinc-900/50",children:[e.jsxs("td",{className:"py-1.5",children:[e.jsx("div",{className:"text-gray-700 dark:text-matrix-secondary break-all leading-tight",children:t.model}),e.jsx("div",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/40",children:t.provider})]}),e.jsx("td",{className:"py-1.5 text-right text-gray-600 dark:text-matrix-secondary",children:t.calls.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-gray-500 dark:text-matrix-secondary/70",children:m(t.inputTokens)}),e.jsx("td",{className:"py-1.5 text-right text-gray-500 dark:text-matrix-secondary/70",children:m(t.outputTokens)}),e.jsx("td",{className:"py-1.5 text-right font-semibold text-gray-700 dark:text-matrix-secondary",children:u(t.estimatedCostUsd)})]},`${t.provider}/${t.model}`))})]})})})]}),g.length>0&&e.jsx(n.div,{variants:x,children:e.jsx(o,{title:"Top Tools",icon:e.jsx(k,{size:14}),children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-matrix-secondary/50 border-b border-gray-100 dark:border-matrix-primary/30",children:[e.jsx("th",{className:"pb-2 text-left",children:"Tool"}),e.jsx("th",{className:"pb-2 text-left",children:"Agent"}),e.jsx("th",{className:"pb-2 text-right",children:"Calls"}),e.jsx("th",{className:"pb-2 text-right",children:"Errors"}),e.jsx("th",{className:"pb-2 text-right",children:"Error rate"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 dark:divide-matrix-primary/20",children:g.map((t,d)=>{const b=t.count?t.errorCount/t.count:0;return e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-zinc-900/50",children:[e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(q,{eventType:t.event_type}),e.jsx("span",{className:"text-gray-700 dark:text-matrix-secondary break-all",children:t.tool_name})]})}),e.jsx("td",{className:"py-1.5",children:t.agent?e.jsx(M,{agent:t.agent}):e.jsx("span",{className:"text-gray-400",children:"—"})}),e.jsx("td",{className:"py-1.5 text-right text-gray-600 dark:text-matrix-secondary",children:t.count.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right",children:e.jsx("span",{className:t.errorCount>0?"text-red-500 dark:text-red-400":"text-gray-400 dark:text-matrix-secondary/50",children:t.errorCount})}),e.jsx("td",{className:"py-1.5 text-right",children:e.jsx("span",{className:b>.1?"text-red-500 dark:text-red-400":b>0?"text-amber-500 dark:text-amber-400":"text-gray-400 dark:text-matrix-secondary/50",children:t.count>0?`${Math.round(b*100)}%`:"—"})})]},d)})})]})})})}),e.jsx(n.div,{variants:x,children:e.jsx(o,{title:"Recent Sessions with Audit",icon:e.jsx(L,{size:14}),children:f.length===0?e.jsx("p",{className:"text-sm text-gray-400 dark:text-matrix-secondary/50",children:"No sessions with audit data yet."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-matrix-secondary/50 border-b border-gray-100 dark:border-matrix-primary/30",children:[e.jsx("th",{className:"pb-2 text-left",children:"Session"}),e.jsx("th",{className:"pb-2 text-left",children:"Status"}),e.jsx("th",{className:"pb-2 text-right",children:"Events"}),e.jsx("th",{className:"pb-2 text-right",children:"LLM"}),e.jsx("th",{className:"pb-2 text-right",children:"Duration"}),e.jsx("th",{className:"pb-2 text-right",children:"Cost"}),e.jsx("th",{className:"pb-2"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 dark:divide-matrix-primary/20",children:f.map(t=>e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-zinc-900/50",children:[e.jsxs("td",{className:"py-2",children:[e.jsx("div",{className:"text-gray-700 dark:text-matrix-secondary truncate max-w-[160px]",title:t.title??t.session_id,children:t.title??e.jsxs("span",{className:"text-gray-400 dark:text-matrix-secondary/40 font-mono text-[10px]",children:[t.session_id.slice(0,12),"…"]})}),t.started_at&&e.jsx("div",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/40",children:V(t.started_at)})]}),e.jsx("td",{className:"py-2",children:e.jsx(K,{status:t.status})}),e.jsx("td",{className:"py-2 text-right text-gray-600 dark:text-matrix-secondary",children:t.event_count.toLocaleString()}),e.jsx("td",{className:"py-2 text-right text-gray-500 dark:text-matrix-secondary/70",children:t.llmCallCount.toLocaleString()}),e.jsx("td",{className:"py-2 text-right text-gray-500 dark:text-matrix-secondary/70",children:j(t.totalDurationMs)}),e.jsx("td",{className:"py-2 text-right font-semibold text-gray-700 dark:text-matrix-secondary",children:u(t.estimatedCostUsd)}),e.jsx("td",{className:"py-2 text-right",children:e.jsx(O,{to:`/sessions/${t.session_id}/audit`,className:"inline-flex items-center gap-1 px-2 py-1 rounded border border-gray-200 dark:border-matrix-primary text-gray-400 dark:text-matrix-secondary hover:text-blue-600 dark:hover:text-matrix-highlight hover:border-blue-300 dark:hover:border-matrix-highlight/50 transition-colors",title:"View session audit",children:e.jsx(W,{size:11})})})]},t.session_id))})]})})})}),a.telephonistCount>0&&e.jsx(n.div,{variants:x,children:e.jsx(o,{title:"Audio / Telephonist",icon:e.jsx($,{size:14}),children:e.jsxs("div",{className:"flex flex-wrap gap-8",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-gray-400 dark:text-matrix-secondary/50 mb-0.5",children:"Calls"}),e.jsx("p",{className:"text-2xl font-bold font-mono text-rose-500 dark:text-rose-400",children:a.telephonistCount.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-gray-400 dark:text-matrix-secondary/50 mb-0.5",children:"Total Audio"}),e.jsx("p",{className:"text-2xl font-bold font-mono text-rose-500 dark:text-rose-400",children:a.totalAudioSeconds<60?`${a.totalAudioSeconds.toFixed(1)}s`:`${(a.totalAudioSeconds/60).toFixed(1)}m`})]})]})})})]})};export{le as AuditDashboard};
1
+ import{j as e,m as n}from"./vendor-motion-C3CZ8ZlO.js";import{L as O,r as B}from"./vendor-react-DikRIOlj.js";import{a as R}from"./audit-CJ2Ms81U.js";import{Q as _,O as D,h as L,i as F,as as v,E as k,m as N,A as z,g as S,aw as I,k as U,J as A,ax as W,K as $,p as G,ai as P}from"./vendor-icons-NHF9HNeN.js";import"./vendor-utils-D4NnWbOU.js";import"./index-BxN2w9sY.js";function u(r){return r===0?"$0.00":r<1e-4?"<$0.0001":r<.01?`$${r.toFixed(4)}`:`$${r.toFixed(2)}`}function m(r){return r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}k`:String(r)}function j(r){if(r<1e3)return`${r}ms`;if(r<6e4)return`${(r/1e3).toFixed(1)}s`;const i=Math.floor(r/6e4),l=Math.floor(r%6e4/1e3);return`${i}m ${l}s`}function V(r){return r?new Date(r).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function T(r,i){return i?`${Math.round(r/i*100)}%`:"0%"}function H({data:r}){const[i,l]=B.useState(null);if(!r.length)return e.jsx("p",{className:"text-xs text-gray-400 dark:text-matrix-secondary/50 py-4",children:"No activity in the last 30 days."});const s=Math.max(...r.map(a=>a.eventCount),1);return e.jsx("div",{className:"flex items-end gap-0.5 h-24 w-full relative",children:r.map((a,c)=>{const y=Math.max(4,Math.round(a.eventCount/s*88)),g=i===c;return e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-end group",onMouseEnter:()=>l(c),onMouseLeave:()=>l(null),children:[g&&e.jsxs("div",{className:"absolute -top-10 left-1/2 -translate-x-1/2 z-10 bg-gray-900 dark:bg-zinc-800 text-white text-[10px] rounded px-2 py-1 whitespace-nowrap pointer-events-none shadow-lg",children:[a.date,": ",a.eventCount," events · ",u(a.estimatedCostUsd)]}),e.jsx("div",{style:{height:y},className:`w-full rounded-t transition-colors ${g?"bg-blue-500 dark:bg-matrix-highlight":"bg-blue-300/70 dark:bg-matrix-highlight/40 group-hover:bg-blue-400 dark:group-hover:bg-matrix-highlight/60"}`})]},a.date)})})}function h({icon:r,label:i,value:l,sub:s,color:a="blue"}){const c={blue:"bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-200 dark:border-blue-800/40",green:"bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-matrix-highlight border-green-200 dark:border-green-800/40",amber:"bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400 border-amber-200 dark:border-amber-800/40",purple:"bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-200 dark:border-purple-800/40",rose:"bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 border-rose-200 dark:border-rose-800/40",teal:"bg-teal-50 dark:bg-teal-900/20 text-teal-600 dark:text-teal-400 border-teal-200 dark:border-teal-800/40"};return e.jsxs("div",{className:`rounded-lg border p-4 flex gap-3 items-start ${c[a]}`,children:[e.jsx("div",{className:"mt-0.5 flex-shrink-0",children:r}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium opacity-70 uppercase tracking-wider mb-0.5",children:i}),e.jsx("p",{className:"text-xl font-bold font-mono leading-tight",children:l}),s&&e.jsx("div",{className:"text-[11px] opacity-60 mt-0.5 leading-snug",children:s})]})]})}function o({title:r,icon:i,children:l}){return e.jsxs("div",{className:"rounded-lg border border-gray-200 dark:border-matrix-primary overflow-hidden bg-white dark:bg-zinc-900 shadow-sm",children:[e.jsxs("div",{className:"px-4 py-3 bg-gray-50 dark:bg-zinc-900 border-b border-gray-200 dark:border-matrix-primary flex items-center gap-2",children:[e.jsx("span",{className:"text-gray-500 dark:text-matrix-secondary/70",children:i}),e.jsx("h2",{className:"text-sm font-semibold text-gray-700 dark:text-matrix-secondary uppercase tracking-wider",children:r})]}),e.jsx("div",{className:"p-4",children:l})]})}const J={oracle:"🔮",apoc:"🧑‍🔬",neo:"🥷",trinity:"👩‍💻",smith:"🕶️",chronos:"⏰",sati:"🧠",telephonist:"📞",link:"🕵️‍♂️",unknown:"?"},w={oracle:"bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300",apoc:"bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",neo:"bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300",trinity:"bg-teal-100 text-teal-700 dark:bg-teal-900/40 dark:text-teal-300",smith:"bg-gray-200 text-gray-700 dark:bg-gray-700/60 dark:text-gray-300",chronos:"bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300",sati:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",telephonist:"bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300",link:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300",unknown:"bg-gray-100 text-gray-500 dark:bg-zinc-800 dark:text-matrix-secondary/60"};function M({agent:r}){const i=w[r]??w.unknown;return e.jsxs("span",{className:`inline-flex items-center gap-1 text-[11px] font-semibold px-1.5 py-0.5 rounded ${i}`,children:[J[r]??"?"," ",r.toUpperCase()]})}function K({status:r}){const i={active:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-matrix-highlight",paused:"bg-gray-100 text-gray-600 dark:bg-zinc-800 dark:text-matrix-secondary",archived:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",deleted:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",unknown:"bg-gray-100 text-gray-500 dark:bg-zinc-800 dark:text-matrix-secondary/60"};return e.jsx("span",{className:`text-[10px] font-semibold uppercase px-1.5 py-0.5 rounded ${i[r]??i.unknown}`,children:r})}const Q={llm_call:e.jsx(v,{size:13}),tool_call:e.jsx(k,{size:13}),mcp_tool:e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M3.49994 11.7501L11.6717 3.57855C12.7762 2.47398 14.5672 2.47398 15.6717 3.57855C16.7762 4.68312 16.7762 6.47398 15.6717 7.57855M15.6717 7.57855L9.49994 13.7501M15.6717 7.57855C16.7762 6.47398 18.5672 6.47398 19.6717 7.57855C20.7762 8.68312 20.7762 10.474 19.6717 11.5785L12.7072 18.543C12.3167 18.9335 12.3167 19.5667 12.7072 19.9572L13.9999 21.2499",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M17.4999 9.74921L11.3282 15.921C10.2237 17.0255 8.43272 17.0255 7.32823 15.921C6.22373 14.8164 6.22373 13.0255 7.32823 11.921L13.4999 5.74939",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),memory_recovery:e.jsx(N,{size:13}),memory_persist:e.jsx(N,{size:13}),telephonist:e.jsx($,{size:13}),skill_loaded:e.jsx(A,{size:13}),chronos_job:e.jsx(S,{size:13}),task_created:e.jsx(P,{size:13}),task_completed:e.jsx(G,{size:13})},Z={llm_call:"text-blue-500 dark:text-blue-400",tool_call:"text-amber-500 dark:text-amber-400",mcp_tool:"text-purple-500 dark:text-purple-400",memory_recovery:"text-emerald-500 dark:text-emerald-400",memory_persist:"text-violet-500 dark:text-violet-400",telephonist:"text-rose-500 dark:text-rose-400",skill_loaded:"text-teal-500 dark:text-teal-400",chronos_job:"text-orange-500 dark:text-orange-400",task_created:"text-gray-500 dark:text-matrix-secondary",task_completed:"text-green-600 dark:text-matrix-highlight"};function q({eventType:r}){return r==="mcp_tool"?e.jsx("span",{className:"flex-shrink-0 text-purple-500 dark:text-purple-400",children:e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M3.49994 11.7501L11.6717 3.57855C12.7762 2.47398 14.5672 2.47398 15.6717 3.57855C16.7762 4.68312 16.7762 6.47398 15.6717 7.57855M15.6717 7.57855L9.49994 13.7501M15.6717 7.57855C16.7762 6.47398 18.5672 6.47398 19.6717 7.57855C20.7762 8.68312 20.7762 10.474 19.6717 11.5785L12.7072 18.543C12.3167 18.9335 12.3167 19.5667 12.7072 19.9572L13.9999 21.2499",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M17.4999 9.74921L11.3282 15.921C10.2237 17.0255 8.43272 17.0255 7.32823 15.921C6.22373 14.8164 6.22373 13.0255 7.32823 11.921L13.4999 5.74939",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})}):e.jsx(k,{size:13,className:"flex-shrink-0 text-amber-500 dark:text-amber-400"})}const X={llm_call:"bg-blue-400 dark:bg-blue-500",tool_call:"bg-amber-400 dark:bg-amber-500",mcp_tool:"bg-purple-400 dark:bg-purple-500",memory_recovery:"bg-emerald-400 dark:bg-emerald-500",memory_persist:"bg-violet-400 dark:bg-violet-500",telephonist:"bg-rose-400 dark:bg-rose-500",skill_loaded:"bg-teal-400 dark:bg-teal-500",chronos_job:"bg-orange-400 dark:bg-orange-500",task_created:"bg-gray-300 dark:bg-matrix-secondary/50",task_completed:"bg-green-400 dark:bg-matrix-highlight/70"},Y={hidden:{opacity:0},show:{opacity:1,transition:{staggerChildren:.04}}},x={hidden:{opacity:0,y:12},show:{opacity:1,y:0}},le=()=>{const{data:r,isLoading:i,mutate:l}=R();if(i)return e.jsxs("div",{className:"flex items-center justify-center h-64 gap-3 text-gray-400 dark:text-matrix-secondary",children:[e.jsx(_,{size:20,className:"animate-spin"}),e.jsx("span",{className:"text-sm font-mono",children:"Loading audit data…"})]});if(!r)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-2 text-gray-400 dark:text-matrix-secondary",children:[e.jsx(D,{size:24}),e.jsx("span",{className:"text-sm",children:"Failed to load audit data."})]});const{sessions:s,totals:a,byAgent:c,byModel:y,topTools:g,recentSessions:f,dailyActivity:p}=r,C=[["llm_call",a.llmCallCount],["tool_call",a.toolCallCount],["mcp_tool",a.mcpToolCount],["memory_recovery",a.memoryRecoveryCount],["memory_persist",a.memoryPersistCount],["telephonist",a.telephonistCount],["skill_loaded",a.skillCount],["chronos_job",a.chronosJobCount],["task_created",a.taskCreatedCount],["task_completed",a.taskCompletedCount]].filter(([,t])=>t>0).sort((t,d)=>d[1]-t[1]),E=Math.max(...C.map(([,t])=>t),1);return e.jsxs(n.div,{variants:Y,initial:"hidden",animate:"show",className:"space-y-6",children:[e.jsxs(n.div,{variants:x,className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-500/10 dark:bg-blue-500/20 border border-blue-200 dark:border-blue-800/40 flex items-center justify-center",children:e.jsx(L,{className:"w-5 h-5 text-blue-600 dark:text-blue-400"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold text-gray-900 dark:text-matrix-highlight",children:"Global Audit"}),e.jsxs("p",{className:"text-sm text-gray-500 dark:text-matrix-secondary/60 mt-0.5",children:[s.withAudit," sessions with audit data · ",a.totalEventCount.toLocaleString()," events total"]})]})]}),e.jsxs("button",{onClick:()=>l(),className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-gray-200 dark:border-matrix-primary text-sm text-gray-500 dark:text-matrix-secondary hover:bg-gray-50 dark:hover:bg-zinc-900 transition-colors",children:[e.jsx(_,{size:14})," Refresh"]})]}),e.jsxs(n.div,{variants:x,className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:[e.jsx(h,{icon:e.jsx(F,{size:16}),label:"Total Cost",value:u(a.estimatedCostUsd),color:"green"}),e.jsx(h,{icon:e.jsx(v,{size:16}),label:"LLM Calls",value:a.llmCallCount.toLocaleString(),color:"blue"}),e.jsx(h,{icon:e.jsx(k,{size:16}),label:"Tool Calls",value:(a.toolCallCount+a.mcpToolCount).toLocaleString(),sub:e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:[a.toolCallCount," native"]}),e.jsx("br",{}),e.jsxs("span",{children:[a.mcpToolCount," MCP"]})]}),color:"amber"}),e.jsx(h,{icon:e.jsx(N,{size:16}),label:"Memory Hits",value:a.memoryRecoveryCount.toLocaleString(),color:"teal"}),e.jsx(h,{icon:e.jsx(z,{size:16}),label:"Total Tokens",value:m(a.totalInputTokens+a.totalOutputTokens),sub:e.jsxs(e.Fragment,{children:[e.jsxs("span",{children:["↑",m(a.totalInputTokens)," in"]}),e.jsx("br",{}),e.jsxs("span",{children:["↓",m(a.totalOutputTokens)," out"]})]}),color:"purple"}),e.jsx(h,{icon:e.jsx(S,{size:16}),label:"Total Time",value:j(a.totalDurationMs),color:"rose"})]}),e.jsxs(n.div,{variants:x,className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs(o,{title:"Sessions",icon:e.jsx(I,{size:14}),children:[e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-4",children:[{label:"Total",value:s.total,cls:"text-gray-700 dark:text-matrix-secondary"},{label:"With Audit",value:s.withAudit,cls:"text-blue-600 dark:text-blue-400"},{label:"Active",value:s.active,cls:"text-green-600 dark:text-matrix-highlight"},{label:"Paused",value:s.paused,cls:"text-gray-500 dark:text-matrix-secondary"},{label:"Archived",value:s.archived,cls:"text-amber-600 dark:text-amber-400"},{label:"Deleted",value:s.deleted,cls:"text-red-500 dark:text-red-400"}].map(({label:t,value:d,cls:b})=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-gray-400 dark:text-matrix-secondary/50",children:t}),e.jsx("span",{className:`text-2xl font-bold font-mono ${b}`,children:d})]},t))}),s.total>0&&e.jsxs("div",{className:"h-2 rounded-full overflow-hidden flex gap-px",children:[s.active>0&&e.jsx("div",{className:"bg-green-400 dark:bg-matrix-highlight/70",style:{flex:s.active}}),s.paused>0&&e.jsx("div",{className:"bg-gray-300 dark:bg-matrix-primary/50",style:{flex:s.paused}}),s.archived>0&&e.jsx("div",{className:"bg-amber-400 dark:bg-amber-500/70",style:{flex:s.archived}}),s.deleted>0&&e.jsx("div",{className:"bg-red-400 dark:bg-red-500/70",style:{flex:s.deleted}})]})]}),e.jsxs(o,{title:"Activity — Last 30 Days",icon:e.jsx(U,{size:14}),children:[e.jsx(H,{data:p}),p.length>0&&e.jsxs("div",{className:"flex gap-4 mt-2 text-[11px] text-gray-400 dark:text-matrix-secondary/50 font-mono",children:[e.jsx("span",{children:p[0]?.date}),e.jsx("span",{className:"flex-1 text-right",children:p[p.length-1]?.date})]})]})]}),e.jsx(n.div,{variants:x,children:e.jsx(o,{title:"Events by Type",icon:e.jsx(z,{size:14}),children:e.jsx("div",{className:"space-y-2",children:C.map(([t,d])=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:`flex-shrink-0 w-5 flex justify-center ${Z[t]??"text-gray-400"}`,children:Q[t]}),e.jsx("span",{className:"text-xs font-mono text-gray-600 dark:text-matrix-secondary w-32 flex-shrink-0",children:t}),e.jsx("div",{className:"flex-1 h-2 bg-gray-100 dark:bg-zinc-800 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all ${X[t]??"bg-gray-400"}`,style:{width:T(d,E)}})}),e.jsx("span",{className:"text-xs font-mono text-gray-500 dark:text-matrix-secondary w-16 text-right",children:d.toLocaleString()}),e.jsx("span",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/50 w-10 text-right",children:T(d,a.totalEventCount)})]},t))})})}),e.jsxs(n.div,{variants:x,className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(o,{title:"By Agent",icon:e.jsx(A,{size:14}),children:c.length===0?e.jsx("p",{className:"text-sm text-gray-400 dark:text-matrix-secondary/50",children:"No agent data."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-matrix-secondary/50 border-b border-gray-100 dark:border-matrix-primary/30",children:[e.jsx("th",{className:"pb-2 text-left",children:"Agent"}),e.jsx("th",{className:"pb-2 text-right",children:"LLM"}),e.jsx("th",{className:"pb-2 text-right",children:"Tools"}),e.jsx("th",{className:"pb-2 text-right",children:"Tokens"}),e.jsx("th",{className:"pb-2 text-right",children:"Time"}),e.jsx("th",{className:"pb-2 text-right",children:"Cost"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 dark:divide-matrix-primary/20",children:c.map(t=>e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-zinc-900/50",children:[e.jsx("td",{className:"py-1.5",children:e.jsx(M,{agent:t.agent})}),e.jsx("td",{className:"py-1.5 text-right text-gray-600 dark:text-matrix-secondary",children:t.llmCalls.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-gray-600 dark:text-matrix-secondary",children:t.toolCalls.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-gray-500 dark:text-matrix-secondary/70",children:["↑",m(t.inputTokens)," ↓",m(t.outputTokens)]}),e.jsx("td",{className:"py-1.5 text-right text-gray-500 dark:text-matrix-secondary/70",children:j(t.totalDurationMs)}),e.jsx("td",{className:"py-1.5 text-right font-semibold text-gray-700 dark:text-matrix-secondary",children:u(t.estimatedCostUsd)})]},t.agent))})]})})}),e.jsx(o,{title:"By Model",icon:e.jsx(v,{size:14}),children:y.length===0?e.jsx("p",{className:"text-sm text-gray-400 dark:text-matrix-secondary/50",children:"No model data."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-matrix-secondary/50 border-b border-gray-100 dark:border-matrix-primary/30",children:[e.jsx("th",{className:"pb-2 text-left",children:"Model"}),e.jsx("th",{className:"pb-2 text-right",children:"Calls"}),e.jsx("th",{className:"pb-2 text-right",children:"In"}),e.jsx("th",{className:"pb-2 text-right",children:"Out"}),e.jsx("th",{className:"pb-2 text-right",children:"Cost"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 dark:divide-matrix-primary/20",children:y.map(t=>e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-zinc-900/50",children:[e.jsxs("td",{className:"py-1.5",children:[e.jsx("div",{className:"text-gray-700 dark:text-matrix-secondary break-all leading-tight",children:t.model}),e.jsx("div",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/40",children:t.provider})]}),e.jsx("td",{className:"py-1.5 text-right text-gray-600 dark:text-matrix-secondary",children:t.calls.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-gray-500 dark:text-matrix-secondary/70",children:m(t.inputTokens)}),e.jsx("td",{className:"py-1.5 text-right text-gray-500 dark:text-matrix-secondary/70",children:m(t.outputTokens)}),e.jsx("td",{className:"py-1.5 text-right font-semibold text-gray-700 dark:text-matrix-secondary",children:u(t.estimatedCostUsd)})]},`${t.provider}/${t.model}`))})]})})})]}),g.length>0&&e.jsx(n.div,{variants:x,children:e.jsx(o,{title:"Top Tools",icon:e.jsx(k,{size:14}),children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-matrix-secondary/50 border-b border-gray-100 dark:border-matrix-primary/30",children:[e.jsx("th",{className:"pb-2 text-left",children:"Tool"}),e.jsx("th",{className:"pb-2 text-left",children:"Agent"}),e.jsx("th",{className:"pb-2 text-right",children:"Calls"}),e.jsx("th",{className:"pb-2 text-right",children:"Errors"}),e.jsx("th",{className:"pb-2 text-right",children:"Error rate"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 dark:divide-matrix-primary/20",children:g.map((t,d)=>{const b=t.count?t.errorCount/t.count:0;return e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-zinc-900/50",children:[e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(q,{eventType:t.event_type}),e.jsx("span",{className:"text-gray-700 dark:text-matrix-secondary break-all",children:t.tool_name})]})}),e.jsx("td",{className:"py-1.5",children:t.agent?e.jsx(M,{agent:t.agent}):e.jsx("span",{className:"text-gray-400",children:"—"})}),e.jsx("td",{className:"py-1.5 text-right text-gray-600 dark:text-matrix-secondary",children:t.count.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right",children:e.jsx("span",{className:t.errorCount>0?"text-red-500 dark:text-red-400":"text-gray-400 dark:text-matrix-secondary/50",children:t.errorCount})}),e.jsx("td",{className:"py-1.5 text-right",children:e.jsx("span",{className:b>.1?"text-red-500 dark:text-red-400":b>0?"text-amber-500 dark:text-amber-400":"text-gray-400 dark:text-matrix-secondary/50",children:t.count>0?`${Math.round(b*100)}%`:"—"})})]},d)})})]})})})}),e.jsx(n.div,{variants:x,children:e.jsx(o,{title:"Recent Sessions with Audit",icon:e.jsx(L,{size:14}),children:f.length===0?e.jsx("p",{className:"text-sm text-gray-400 dark:text-matrix-secondary/50",children:"No sessions with audit data yet."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs font-mono",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-gray-400 dark:text-matrix-secondary/50 border-b border-gray-100 dark:border-matrix-primary/30",children:[e.jsx("th",{className:"pb-2 text-left",children:"Session"}),e.jsx("th",{className:"pb-2 text-left",children:"Status"}),e.jsx("th",{className:"pb-2 text-right",children:"Events"}),e.jsx("th",{className:"pb-2 text-right",children:"LLM"}),e.jsx("th",{className:"pb-2 text-right",children:"Duration"}),e.jsx("th",{className:"pb-2 text-right",children:"Cost"}),e.jsx("th",{className:"pb-2"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 dark:divide-matrix-primary/20",children:f.map(t=>e.jsxs("tr",{className:"hover:bg-gray-50 dark:hover:bg-zinc-900/50",children:[e.jsxs("td",{className:"py-2",children:[e.jsx("div",{className:"text-gray-700 dark:text-matrix-secondary truncate max-w-[160px]",title:t.title??t.session_id,children:t.title??e.jsxs("span",{className:"text-gray-400 dark:text-matrix-secondary/40 font-mono text-[10px]",children:[t.session_id.slice(0,12),"…"]})}),t.started_at&&e.jsx("div",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/40",children:V(t.started_at)})]}),e.jsx("td",{className:"py-2",children:e.jsx(K,{status:t.status})}),e.jsx("td",{className:"py-2 text-right text-gray-600 dark:text-matrix-secondary",children:t.event_count.toLocaleString()}),e.jsx("td",{className:"py-2 text-right text-gray-500 dark:text-matrix-secondary/70",children:t.llmCallCount.toLocaleString()}),e.jsx("td",{className:"py-2 text-right text-gray-500 dark:text-matrix-secondary/70",children:j(t.totalDurationMs)}),e.jsx("td",{className:"py-2 text-right font-semibold text-gray-700 dark:text-matrix-secondary",children:u(t.estimatedCostUsd)}),e.jsx("td",{className:"py-2 text-right",children:e.jsx(O,{to:`/sessions/${t.session_id}/audit`,className:"inline-flex items-center gap-1 px-2 py-1 rounded border border-gray-200 dark:border-matrix-primary text-gray-400 dark:text-matrix-secondary hover:text-blue-600 dark:hover:text-matrix-highlight hover:border-blue-300 dark:hover:border-matrix-highlight/50 transition-colors",title:"View session audit",children:e.jsx(W,{size:11})})})]},t.session_id))})]})})})}),a.telephonistCount>0&&e.jsx(n.div,{variants:x,children:e.jsx(o,{title:"Audio / Telephonist",icon:e.jsx($,{size:14}),children:e.jsxs("div",{className:"flex flex-wrap gap-8",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-gray-400 dark:text-matrix-secondary/50 mb-0.5",children:"Calls"}),e.jsx("p",{className:"text-2xl font-bold font-mono text-rose-500 dark:text-rose-400",children:a.telephonistCount.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-gray-400 dark:text-matrix-secondary/50 mb-0.5",children:"Total Audio"}),e.jsx("p",{className:"text-2xl font-bold font-mono text-rose-500 dark:text-rose-400",children:a.totalAudioSeconds<60?`${a.totalAudioSeconds.toFixed(1)}s`:`${(a.totalAudioSeconds/60).toFixed(1)}m`})]})]})})})]})};export{le as AuditDashboard};
@@ -0,0 +1,41 @@
1
+ import{j as e,A as L,m as G}from"./vendor-motion-C3CZ8ZlO.js";import{c as X,r as o}from"./vendor-react-DikRIOlj.js";import{s as V,t as P,u as Q,v as Y,X as K,w as Z,x as ee,y as re,z as te,E as ae,q as U,G as q,r as H,I as F,m as se,M as ne,J as $,e as ie,g as oe,K as le,U as de,N as ce}from"./vendor-icons-NHF9HNeN.js";import{h as xe,g as me,i as he,c as A}from"./index-BxN2w9sY.js";import{M as ge,r as pe}from"./vendor-markdown-BN_Np5Ta.js";import{C as ue}from"./ConfirmationModal-DxUHZgTy.js";import"./vendor-utils-D4NnWbOU.js";function be(r){const i=Date.now()-r;return i<6e4?"just now":i<36e5?`${Math.floor(i/6e4)}m ago`:i<864e5?`${Math.floor(i/36e5)}h ago`:i<6048e5?`${Math.floor(i/864e5)}d ago`:new Date(r).toLocaleDateString()}const ye=({sessions:r,activeSessionId:i,onSelectSession:s,onCreateSession:d,onArchiveSession:u,onDeleteSession:x,onRenameSession:m,isOpen:b,toggleSidebar:g})=>{const j=X(),[p,f]=o.useState(null),[w,y]=o.useState(""),z=o.useRef(null);o.useEffect(()=>{p&&z.current&&z.current.focus()},[p]);const N=(l,C)=>{l.stopPropagation(),f(C.id),y(C.title||"Untitled Session")},E=l=>{l?.stopPropagation(),p&&w.trim()&&(m(p,w.trim()),f(null))},S=l=>{l?.stopPropagation(),f(null)},_=l=>{l.key==="Enter"?E():l.key==="Escape"&&S()};return b?e.jsxs("div",{className:"w-72 bg-white dark:bg-black border-r border-gray-300 dark:border-matrix-primary flex flex-col h-full shrink-0 transition-colors duration-300",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-gray-300 dark:border-matrix-primary shrink-0",children:[e.jsx("span",{className:"text-sm font-semibold text-gray-800 dark:text-matrix-highlight",children:"Sessions"}),e.jsx("button",{onClick:g,className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-matrix-primary/20 text-gray-400 dark:text-matrix-secondary/60 transition-colors",title:"Collapse sidebar",children:e.jsx(Q,{size:16})})]}),e.jsx("div",{className:"px-3 py-2.5 shrink-0",children:e.jsxs("button",{onClick:d,className:"w-full flex items-center justify-center gap-2 bg-azure-primary text-white dark:bg-matrix-highlight dark:text-black py-2 px-4 rounded-xl hover:bg-azure-secondary dark:hover:bg-matrix-secondary transition-colors text-sm font-medium shadow-sm",children:[e.jsx(P,{size:16}),"New Chat"]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-2 pb-3 space-y-0.5",children:[r.length===0&&e.jsx("div",{className:"text-center text-gray-400 dark:text-matrix-secondary/40 mt-12 text-sm px-4",children:"No sessions yet. Start a new chat!"}),r.map(l=>{const C=i===l.id,M=p===l.id;return e.jsxs("div",{onClick:()=>!M&&s(l.id),className:`
2
+ group relative flex items-center gap-2 px-3 py-2.5 rounded-xl cursor-pointer transition-all
3
+ ${C?"bg-azure-primary/10 dark:bg-matrix-primary/15 text-azure-primary dark:text-matrix-highlight":"hover:bg-gray-100 dark:hover:bg-matrix-primary/10 text-gray-700 dark:text-matrix-secondary"}
4
+ `,children:[e.jsx("div",{className:"flex-1 min-w-0",children:M?e.jsx("div",{onClick:v=>v.stopPropagation(),children:e.jsx("input",{ref:z,type:"text",value:w,onChange:v=>y(v.target.value),onKeyDown:_,className:"w-full text-sm px-1.5 py-0.5 bg-white dark:bg-black border border-azure-primary dark:border-matrix-highlight rounded-lg focus:outline-none dark:text-matrix-highlight"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-medium truncate leading-snug",children:l.title||"Untitled Session"}),e.jsx("div",{className:"text-xs text-gray-400 dark:text-matrix-secondary/50 mt-0.5",children:be(l.started_at)})]})}),e.jsx("div",{className:`flex items-center gap-0.5 shrink-0 transition-opacity ${C||M?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:v=>v.stopPropagation(),children:M?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:E,className:"p-1.5 rounded-lg text-emerald-600 hover:bg-emerald-50 dark:text-emerald-400 dark:hover:bg-emerald-900/20 transition-colors",title:"Save",children:e.jsx(Y,{size:13})}),e.jsx("button",{onClick:S,className:"p-1.5 rounded-lg text-red-500 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20 transition-colors",title:"Cancel",children:e.jsx(K,{size:13})})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:v=>N(v,l),className:"p-1.5 rounded-lg text-gray-400 hover:text-blue-500 hover:bg-blue-50 dark:text-matrix-secondary/50 dark:hover:text-blue-400 dark:hover:bg-blue-900/20 transition-colors",title:"Rename",children:e.jsx(Z,{size:13})}),e.jsx("button",{onClick:()=>j(`/sessions/${l.id}/audit`),className:"p-1.5 rounded-lg text-gray-400 hover:text-violet-500 hover:bg-violet-50 dark:text-matrix-secondary/50 dark:hover:text-violet-400 dark:hover:bg-violet-900/20 transition-colors",title:"Audit",children:e.jsx(ee,{size:13})}),e.jsx("button",{onClick:()=>u(l.id),className:"p-1.5 rounded-lg text-gray-400 hover:text-amber-500 hover:bg-amber-50 dark:text-matrix-secondary/50 dark:hover:text-amber-400 dark:hover:bg-amber-900/20 transition-colors",title:"Archive",children:e.jsx(re,{size:13})}),e.jsx("button",{onClick:()=>x(l.id),className:"p-1.5 rounded-lg text-gray-400 hover:text-red-500 hover:bg-red-50 dark:text-matrix-secondary/50 dark:hover:text-red-400 dark:hover:bg-red-900/20 transition-colors",title:"Delete",children:e.jsx(te,{size:13})})]})})]},l.id)})]})]}):e.jsxs("div",{className:"w-14 bg-white dark:bg-black border-r border-gray-300 dark:border-matrix-primary flex flex-col items-center py-3 gap-3 shrink-0 transition-colors duration-300",children:[e.jsx("button",{onClick:g,className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-matrix-primary/20 text-gray-400 dark:text-matrix-secondary/60 transition-colors",title:"Expand sidebar",children:e.jsx(V,{size:18})}),e.jsx("div",{className:"w-8 h-px bg-gray-200 dark:bg-matrix-primary/20"}),e.jsx("button",{onClick:d,className:"p-2.5 bg-azure-primary text-white dark:bg-matrix-highlight dark:text-black rounded-xl hover:bg-azure-secondary dark:hover:bg-matrix-secondary shadow-sm transition-colors",title:"New chat",children:e.jsx(P,{size:18})})]})};function J(r){if(r==null)return"";if(typeof r=="string")try{return JSON.stringify(JSON.parse(r),null,2)}catch{return r}try{return JSON.stringify(r,null,2)}catch{return String(r)}}const fe=({group:r})=>{const[i,s]=o.useState(!1),d=r.result!==null,u=r.result?.content??"",x=u.startsWith("Error")||u.startsWith("❌");return e.jsxs("div",{className:"rounded-lg border border-gray-300 dark:border-matrix-primary/70 bg-white dark:bg-black overflow-hidden text-sm mb-1",children:[e.jsxs("button",{onClick:()=>s(!i),className:"w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-gray-50 dark:hover:bg-zinc-900/60 transition-colors",children:[e.jsx(ae,{size:12,className:"text-amber-500 dark:text-amber-400/80 flex-shrink-0"}),e.jsx("span",{className:"flex-1 font-mono text-xs text-gray-600 dark:text-matrix-secondary/80 truncate",children:r.call.name}),d?x?e.jsx(U,{size:12,className:"text-red-500 dark:text-red-400 flex-shrink-0"}):e.jsx(q,{size:12,className:"text-emerald-500 dark:text-emerald-400 flex-shrink-0"}):e.jsx(H,{size:12,className:"text-gray-400 animate-spin flex-shrink-0"}),e.jsx(F,{size:12,className:`text-gray-400 dark:text-matrix-secondary/40 flex-shrink-0 transition-transform duration-200 ${i?"rotate-180":""}`})]}),e.jsx(L,{initial:!1,children:i&&e.jsx(G.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.15,ease:"easeInOut"},className:"overflow-hidden",children:e.jsxs("div",{className:"px-3 pb-2.5 pt-1 border-t border-gray-100 dark:border-matrix-primary/20 space-y-2",children:[Object.keys(r.call.args??{}).length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/40 uppercase tracking-wider mb-1",children:"args"}),e.jsx("pre",{className:"text-xs font-mono text-gray-600 dark:text-matrix-secondary/80 whitespace-pre-wrap break-all bg-gray-50 dark:bg-zinc-900 rounded-md p-2 border border-gray-100 dark:border-matrix-primary/20 max-h-36 overflow-y-auto",children:J(r.call.args)})]}),d&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/40 uppercase tracking-wider mb-1",children:"result"}),e.jsx("pre",{className:"text-xs font-mono text-gray-600 dark:text-matrix-secondary/80 whitespace-pre-wrap break-all bg-gray-50 dark:bg-zinc-900 rounded-md p-2 border border-gray-100 dark:border-matrix-primary/20 max-h-44 overflow-y-auto",children:J(u)})]})]})})})]})},ke={apoc_delegate:{label:"Apoc",emoji:"🧑‍🔬",colorClass:"text-amber-600 dark:text-amber-400",bgClass:"bg-amber-50 dark:bg-amber-900/10"},neo_delegate:{label:"Neo",emoji:"🥷",colorClass:"text-violet-600 dark:text-violet-400",bgClass:"bg-violet-50 dark:bg-violet-900/10"},trinity_delegate:{label:"Trinity",emoji:"👩‍💻",colorClass:"text-teal-600 dark:text-teal-400",bgClass:"bg-teal-50 dark:bg-teal-900/10"},smith_delegate:{label:"Smith",emoji:"🕶️",colorClass:"text-gray-500 dark:text-gray-400",bgClass:"bg-gray-50 dark:bg-zinc-900"},link_delegate:{label:"Link",emoji:"🕵️‍♂️",colorClass:"text-indigo-600 dark:text-indigo-400",bgClass:"bg-indigo-50 dark:bg-indigo-900/10"}};function R(r){return r?.task??r?.prompt??""}function je(r){if(typeof r!="string")return String(r);try{return JSON.stringify(JSON.parse(r),null,2)}catch{return r}}const ve=({group:r})=>{const[i,s]=o.useState(!1),d=ke[r.call.name]??{label:r.call.name,emoji:"🤖",colorClass:"text-gray-500",bgClass:"bg-gray-50 dark:bg-zinc-900"},u=r.result!==null,x=r.result?.content??"",m=x.startsWith("❌")||x.toLowerCase().startsWith("error"),b=R(r.call.args).slice(0,100),g=r.call.args?.smith??null;return e.jsxs("div",{className:`rounded-lg border border-gray-300 dark:border-matrix-primary/70 overflow-hidden text-sm mb-1 ${d.bgClass}`,children:[e.jsxs("button",{onClick:()=>s(!i),className:"w-full flex items-center gap-2.5 px-3 py-2 text-left hover:brightness-95 dark:hover:brightness-110 transition-all",children:[e.jsx("span",{className:"text-base flex-shrink-0 leading-none",children:d.emoji}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:`text-xs font-semibold ${d.colorClass}`,children:[d.label,g?` · ${g}`:""]}),b&&e.jsx("div",{className:"text-xs text-gray-500 dark:text-matrix-secondary/60 truncate mt-0.5",children:b})]}),u?m?e.jsx(U,{size:14,className:"text-red-500 dark:text-red-400 flex-shrink-0"}):e.jsx(q,{size:14,className:"text-emerald-500 dark:text-emerald-400 flex-shrink-0"}):e.jsx(H,{size:14,className:"text-gray-400 animate-spin flex-shrink-0"}),e.jsx(F,{size:13,className:`text-gray-400 dark:text-matrix-secondary/40 flex-shrink-0 transition-transform duration-200 ${i?"rotate-180":""}`})]}),e.jsx(L,{initial:!1,children:i&&e.jsx(G.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.18,ease:"easeInOut"},className:"overflow-hidden",children:e.jsxs("div",{className:"px-3 pb-2.5 pt-1 border-t border-gray-200 dark:border-matrix-primary/20 space-y-2",children:[R(r.call.args)&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/40 uppercase tracking-wider mb-1",children:"task"}),e.jsx("p",{className:"text-xs text-gray-600 dark:text-matrix-secondary/80 bg-white dark:bg-black rounded-md p-2 border border-gray-100 dark:border-matrix-primary/20 whitespace-pre-wrap",children:R(r.call.args)})]}),u&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-gray-400 dark:text-matrix-secondary/40 uppercase tracking-wider mb-1",children:"result"}),e.jsx("pre",{className:"text-xs font-mono text-gray-600 dark:text-matrix-secondary/80 whitespace-pre-wrap break-all bg-white dark:bg-black rounded-md p-2 border border-gray-100 dark:border-matrix-primary/20 max-h-56 overflow-y-auto",children:je(x)})]})]})})})]})};function we(r){return r==null||r===0?null:r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`}function W(r){return r>=1e3?`${(r/1e3).toFixed(1)}k`:String(r)}const Ne=({message:r})=>{const i=r.usage_metadata,s=i?.input_tokens??i?.prompt_tokens??0,d=i?.output_tokens??i?.completion_tokens??0,u=s>0||d>0,x=we(r.duration_ms),m=r.model,b=r.sati_memories_count??null;if(!u&&!x&&!m&&b==null)return null;const g=m?(m.includes(":")?m.split(":").pop():m)?.split("-").slice(0,4).join("-")??m:null;return e.jsxs("div",{className:"mt-2 pt-1.5 border-t border-gray-100 dark:border-matrix-primary/20 flex flex-wrap items-center gap-x-3 gap-y-0.5",children:[g&&e.jsx("span",{className:"text-[11px] font-mono text-gray-400 dark:text-matrix-secondary/40 truncate max-w-[180px]",title:m??"",children:g}),u&&e.jsxs("span",{className:"text-[11px] font-mono text-gray-400 dark:text-matrix-secondary/40",children:["↑",W(s)," ↓",W(d)]}),x&&e.jsx("span",{className:"text-[11px] font-mono text-gray-400 dark:text-matrix-secondary/40",children:x}),b!=null&&b>0&&e.jsxs("span",{className:"flex items-center gap-1 text-[11px] font-mono text-purple-400 dark:text-purple-400/70",children:[e.jsx(se,{size:10}),b]})]})},Se=[{name:"apoc",emoji:"🧑‍🔬",description:"Filesystem, shell & browser",color:"amber"},{name:"neo",emoji:"🥷",description:"MCP tool orchestration",color:"violet"},{name:"trinity",emoji:"👩‍💻",description:"Database specialist",color:"teal"},{name:"link",emoji:"🕵️‍♂️",description:"Document search & RAG",color:"gray"}],B={amber:"bg-amber-100 text-amber-800 border-amber-300 dark:bg-amber-900/30 dark:text-amber-300 dark:border-amber-700/60",purple:"bg-purple-100 text-purple-800 border-purple-300 dark:bg-purple-900/30 dark:text-purple-300 dark:border-purple-700/60",violet:"bg-violet-100 text-violet-800 border-violet-300 dark:bg-violet-900/30 dark:text-violet-300 dark:border-violet-700/60",teal:"bg-teal-100 text-teal-800 border-teal-300 dark:bg-teal-900/30 dark:text-teal-300 dark:border-teal-700/60",gray:"bg-zinc-100 text-zinc-700 border-zinc-300 dark:bg-zinc-800 dark:text-zinc-300 dark:border-zinc-600"};function Ce(r){const i=r.replace(/^```json\s*/i,"").replace(/\s*```$/,"");try{return JSON.stringify(JSON.parse(i),null,2)}catch{return i}}function ze(r){return r.session_id?.startsWith("sati-evaluation-")===!0||r.tool_name?.toLowerCase().includes("sati")===!0}const Ee=({message:r})=>{const[i,s]=o.useState(!1),d=ze(r),u=d?r.tool_name==="sati_evaluation_output"?"Sati · memory update":"Sati · analysis":r.tool_name??"tool result";return e.jsxs("details",{open:i,onToggle:x=>s(x.target.open),className:"w-full",children:[e.jsxs("summary",{className:"list-none cursor-pointer select-none flex items-center gap-2 text-xs text-gray-400 dark:text-matrix-secondary/40 hover:text-gray-500 dark:hover:text-matrix-secondary/60 transition-colors py-0.5",children:[e.jsx("div",{className:"flex-1 h-px bg-gray-200 dark:bg-matrix-primary/20"}),e.jsxs("span",{className:"flex items-center gap-1.5 whitespace-nowrap px-2",children:[e.jsx("span",{children:d?"🧠":"🔧"}),e.jsx("span",{children:u}),e.jsx(F,{size:11,className:`transition-transform duration-200 ${i?"rotate-180":""}`})]}),e.jsx("div",{className:"flex-1 h-px bg-gray-200 dark:bg-matrix-primary/20"})]}),i&&e.jsx("pre",{className:"mt-2 px-3 py-2.5 whitespace-pre-wrap break-all text-xs font-mono text-gray-600 dark:text-matrix-secondary/80 border border-gray-300 dark:border-matrix-primary/60 rounded-lg bg-gray-50 dark:bg-zinc-900 max-h-48 overflow-y-auto",children:Ce(r.content)})]})},Me={table:({children:r})=>e.jsx("div",{className:"my-2 overflow-x-auto rounded-lg border border-gray-200 dark:border-matrix-primary/60",children:e.jsx("table",{className:"min-w-full text-xs border-collapse",children:r})}),thead:({children:r})=>e.jsx("thead",{className:"bg-gray-100 dark:bg-zinc-900 text-gray-600 dark:text-matrix-secondary/70",children:r}),tbody:({children:r})=>e.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-matrix-primary/20",children:r}),tr:({children:r})=>e.jsx("tr",{className:"hover:bg-gray-50 dark:hover:bg-zinc-900/60 transition-colors",children:r}),th:({children:r})=>e.jsx("th",{className:"px-3 py-2 text-left font-semibold whitespace-nowrap border-b border-gray-200 dark:border-matrix-primary/40",children:r}),td:({children:r})=>e.jsx("td",{className:"px-3 py-2 text-gray-700 dark:text-matrix-secondary align-top",children:r})},Ae=({messages:r,onSendMessage:i,isLoading:s,activeSessionId:d,activeSession:u,onToggleSidebar:x})=>{const[m,b]=o.useState(""),[g,j]=o.useState([]),[p,f]=o.useState(null),[w,y]=o.useState(0),[z,N]=o.useState([]),E=o.useRef(null),S=o.useRef(null);o.useEffect(()=>{E.current?.scrollIntoView({behavior:"smooth"})},[r,s]),o.useEffect(()=>{const t=S.current;t&&(t.style.height="auto",t.style.height=t.scrollHeight+"px")},[m]),o.useEffect(()=>{xe.get("/smiths").then(t=>N(t.smiths.map(a=>({name:a.name,emoji:"🕶️",description:"Remote Smith agent",color:"gray"})))).catch(()=>{})},[]);const _=[...Se,...z],l=p?_.filter(t=>t.name.toLowerCase().startsWith(p.query.toLowerCase())):[],C=t=>{if(!p)return;const a=m.slice(0,p.startIdx),h=m.slice(p.startIdx+1+p.query.length),D=(a+h).replace(/ +/g," ").trim();b(D),j(k=>k.includes(t)?k:[...k,t]),f(null),y(0),setTimeout(()=>S.current?.focus(),0)},M=t=>{j(a=>a.filter(h=>h!==t))},v=t=>{const a=t.target.value;b(a);const h=t.target.selectionStart??a.length,k=a.slice(0,h).match(/@(\w*)$/);k?(f({query:k[1],startIdx:h-k[0].length}),y(0)):f(null)},T=()=>{if(!(m.trim()||g.length>0)||s)return;const a=[...g.map(h=>`@${h}`),m.trim()].filter(Boolean);i(a.join(" ")),b(""),j([]),f(null),S.current&&(S.current.style.height="auto")},n=t=>{if(p&&l.length>0){if(t.key==="ArrowDown"){t.preventDefault(),y(a=>(a+1)%l.length);return}if(t.key==="ArrowUp"){t.preventDefault(),y(a=>(a-1+l.length)%l.length);return}if(t.key==="Tab"||t.key==="Enter"){t.preventDefault(),C(l[w].name);return}if(t.key==="Escape"){t.preventDefault(),f(null);return}}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),T())},c=t=>_.find(a=>a.name===t)??{name:t,emoji:"🤖",description:"",color:"gray"};return e.jsxs("div",{className:"flex-1 flex flex-col h-full bg-white dark:bg-black overflow-hidden transition-colors duration-300",children:[x&&e.jsxs("div",{className:"md:hidden flex items-center gap-3 px-4 py-3 shrink-0 bg-white dark:bg-black border-b border-gray-300 dark:border-matrix-primary",children:[e.jsx("button",{onClick:x,className:"p-2 -ml-1 rounded-lg hover:bg-gray-100 dark:hover:bg-matrix-primary/20 text-gray-500 dark:text-matrix-secondary transition-colors","aria-label":"Open sessions",children:e.jsx(ne,{size:20})}),e.jsx("span",{className:"text-sm font-semibold text-gray-800 dark:text-matrix-highlight truncate flex-1",children:u?.title??(d?"Chat":"Morpheus")})]}),d?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 overflow-y-auto min-h-0 px-4 py-5 space-y-4",children:[me(r).map(t=>{const{message:a,toolGroups:h}=t;if(a.type==="tool")return e.jsx("div",{className:"px-2 py-0.5",children:e.jsx(Ee,{message:a})},t.index);const D=a.type==="human",k=a.source==="webhook"||a.source==="chronos",O=D&&!k;return e.jsxs("div",{className:`flex items-end gap-2.5 ${O?"justify-end":"justify-start"}`,children:[!O&&e.jsx("div",{className:"w-7 h-7 rounded-full flex-shrink-0 flex items-center justify-center bg-azure-primary/10 text-azure-primary dark:bg-matrix-primary/20 dark:text-matrix-highlight mb-0.5",children:k&&a.source==="webhook"?e.jsx(ie,{size:14}):k&&a.source==="chronos"?e.jsx(oe,{size:14}):e.jsx($,{size:14})}),e.jsxs("div",{className:`
5
+ max-w-[85%] md:max-w-[72%] min-w-0
6
+ ${O?"bg-azure-primary text-white dark:text-white/80 dark:bg-matrix-primary rounded-2xl rounded-br-sm px-4 py-2.5":"bg-gray-50 dark:bg-zinc-900 border border-gray-300 dark:border-matrix-primary/60 text-gray-800 dark:text-matrix-secondary rounded-2xl rounded-bl-sm px-4 py-3"}
7
+ `,children:[k&&e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wider border bg-amber-50 text-amber-700 border-amber-300 dark:bg-amber-900/30 dark:text-amber-300 dark:border-amber-700/60",children:a.source==="webhook"?"Webhook":"Chronos"})}),D&&e.jsxs(e.Fragment,{children:[a.audio_duration_seconds!=null&&e.jsxs("div",{className:"flex items-center gap-1 mb-1.5 text-white/70 dark:text-white/50",children:[e.jsx(le,{size:11}),e.jsxs("span",{className:"text-[10px] font-mono tracking-wide",children:["voice · ",a.audio_duration_seconds,"s"]})]}),e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap break-words",children:a.content})]}),a.type==="ai"&&e.jsxs(e.Fragment,{children:[h&&h.length>0&&e.jsx("div",{className:"mb-2.5 space-y-1",children:h.map(I=>he(I.call.name)?e.jsx(ve,{group:I},I.call.id):e.jsx(fe,{group:I},I.call.id))}),a.content&&e.jsx("div",{className:`
8
+ prose prose-sm dark:prose-invert max-w-none
9
+ prose-p:my-1.5 prose-p:leading-relaxed
10
+ prose-headings:my-2 prose-headings:font-semibold
11
+ prose-ul:my-1.5 prose-ol:my-1.5 prose-li:my-0.5
12
+ prose-pre:my-2 prose-pre:rounded-lg prose-pre:text-xs
13
+ prose-code:text-[0.8em] prose-code:px-1 prose-code:py-0.5 prose-code:rounded prose-code:font-mono
14
+ prose-table:my-0 prose-thead:border-0 prose-tbody:border-0
15
+ prose-tr:border-0 prose-th:p-0 prose-td:p-0
16
+ dark:prose-p:text-matrix-secondary
17
+ dark:prose-headings:text-matrix-highlight
18
+ dark:prose-strong:text-matrix-highlight
19
+ dark:prose-li:text-matrix-secondary
20
+ dark:prose-code:text-matrix-highlight dark:prose-code:bg-black/60
21
+ dark:prose-pre:bg-black dark:prose-pre:border dark:prose-pre:border-matrix-primary/30
22
+ `,children:e.jsx(ge,{remarkPlugins:[pe],components:Me,children:a.content})}),e.jsx(Ne,{message:a})]})]}),O&&e.jsx("div",{className:"w-7 h-7 rounded-full flex-shrink-0 flex items-center justify-center bg-gray-200 dark:bg-matrix-primary/30 text-gray-500 dark:text-matrix-secondary mb-0.5",children:e.jsx(de,{size:14})})]},t.index)}),s&&e.jsxs("div",{className:"flex items-end gap-2.5 justify-start",children:[e.jsx("div",{className:"w-7 h-7 rounded-full flex-shrink-0 flex items-center justify-center bg-azure-primary/10 text-azure-primary dark:bg-matrix-primary/20 dark:text-matrix-highlight mb-0.5",children:e.jsx($,{size:14})}),e.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 border border-gray-300 dark:border-matrix-primary/60 rounded-2xl rounded-bl-sm px-4 py-3 flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-azure-primary dark:bg-matrix-highlight animate-bounce",style:{animationDelay:"0ms"}}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-azure-primary dark:bg-matrix-highlight animate-bounce",style:{animationDelay:"160ms"}}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-azure-primary dark:bg-matrix-highlight animate-bounce",style:{animationDelay:"320ms"}})]})]}),e.jsx("div",{ref:E})]}),e.jsx("div",{className:"shrink-0 px-4 pt-3 pb-4 bg-white dark:bg-black border-t border-gray-300 dark:border-matrix-primary",children:e.jsxs("div",{className:"max-w-3xl mx-auto relative",children:[p&&l.length>0&&e.jsxs("div",{className:"absolute bottom-full left-0 right-0 mb-2 z-50 bg-white dark:bg-zinc-900 border border-gray-300 dark:border-matrix-primary rounded-xl shadow-xl overflow-hidden",children:[e.jsx("div",{className:"px-3 py-1.5 border-b border-gray-100 dark:border-matrix-primary/40 flex items-center gap-1.5",children:e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wider text-gray-400 dark:text-matrix-secondary/50",children:"Agents"})}),e.jsx("ul",{className:"max-h-52 overflow-y-auto py-1",children:l.map((t,a)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseDown:h=>{h.preventDefault(),C(t.name)},onMouseEnter:()=>y(a),className:`
23
+ w-full flex items-center gap-3 px-3 py-2 text-left transition-colors
24
+ ${a===w?"bg-azure-primary/10 dark:bg-matrix-primary/20":"hover:bg-gray-50 dark:hover:bg-matrix-primary/10"}
25
+ `,children:[e.jsx("span",{className:"text-base leading-none",children:t.emoji}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsxs("span",{className:"block text-sm font-medium text-gray-800 dark:text-matrix-highlight",children:["@",t.name]}),e.jsx("span",{className:"block text-xs text-gray-400 dark:text-matrix-secondary/50 truncate",children:t.description})]}),a===w&&e.jsx("kbd",{className:"flex-shrink-0 text-[10px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-black text-gray-500 dark:text-matrix-secondary/60 font-mono border border-gray-200 dark:border-matrix-primary/40",children:"Tab"})]})},t.name))})]}),g.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:g.map(t=>{const a=c(t),h=B[a.color]??B.gray;return e.jsxs("span",{className:`inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded-full text-xs font-medium border ${h}`,children:[e.jsx("span",{className:"leading-none",children:a.emoji}),e.jsxs("span",{children:["@",t]}),e.jsx("button",{type:"button",onClick:()=>M(t),className:"ml-0.5 rounded-full p-0.5 hover:bg-black/10 dark:hover:bg-white/10 transition-colors","aria-label":`Remove @${t}`,children:e.jsx(K,{size:10})})]},t)})}),e.jsxs("form",{onSubmit:t=>{t.preventDefault(),T()},className:"flex items-end gap-2",children:[e.jsx("textarea",{ref:S,value:m,onChange:v,onKeyDown:n,placeholder:"Message Morpheus… (type @ to mention an agent)",rows:1,disabled:s,className:`
26
+ flex-1 resize-none max-h-40 overflow-y-auto
27
+ bg-gray-100 dark:bg-zinc-900
28
+ border border-gray-300 dark:border-matrix-primary/60
29
+ rounded-xl px-4 py-3
30
+ text-sm leading-relaxed
31
+ text-gray-800 dark:text-matrix-secondary
32
+ placeholder-gray-400 dark:placeholder-matrix-secondary/40
33
+ focus:outline-none focus:ring-2 focus:ring-azure-primary dark:focus:ring-matrix-highlight focus:border-transparent
34
+ disabled:opacity-50
35
+ transition-all duration-200
36
+ `}),e.jsx("button",{type:"submit",disabled:!m.trim()&&g.length===0||s,className:"flex-shrink-0 p-3 rounded-xl bg-azure-primary text-white dark:bg-matrix-secondary dark:text-black hover:bg-azure-secondary dark:hover:bg-matrix-highlight disabled:opacity-40 disabled:cursor-not-allowed transition-colors shadow-sm",children:e.jsx(ce,{size:18})})]}),e.jsx("p",{className:"mt-1.5 text-center text-[11px] text-gray-300 dark:text-matrix-secondary/25 select-none",children:"Enter to send · Shift+Enter for newline · @ to mention an agent"})]})})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-5 p-8 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-azure-primary/10 dark:bg-matrix-primary/10 flex items-center justify-center",children:e.jsx($,{size:30,className:"text-azure-primary/60 dark:text-matrix-highlight/50"})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h3",{className:"text-base font-semibold text-gray-700 dark:text-matrix-highlight",children:"Morpheus is ready"}),e.jsx("p",{className:"text-sm text-gray-400 dark:text-matrix-secondary/60 max-w-[240px] leading-relaxed",children:"Select a session from the sidebar or start a new chat."})]})]})]})},Fe=()=>{const[r,i]=o.useState([]),[s,d]=o.useState(null),[u,x]=o.useState([]),[m,b]=o.useState({}),[g,j]=o.useState(()=>typeof window<"u"?window.innerWidth>=768:!0),p=s?m[s]??!1:!1,f=o.useRef(!1);o.useEffect(()=>{f.current=p},[p]);const w=o.useRef(s);o.useEffect(()=>{w.current=s},[s]),o.useEffect(()=>{if(!s)return;const n=setInterval(async()=>{if(!f.current)try{const t=(await A.getMessages(s)).filter(a=>a.type!=="system");x(a=>{if(t.length!==a.length)return t;const h=t.at(-1)?.created_at??0,D=a.at(-1)?.created_at??0;return h>D?t:a})}catch{}},3e3);return()=>clearInterval(n)},[s]);const[y,z]=o.useState({isOpen:!1,title:"",description:"",onConfirm:()=>{}}),N=async()=>{try{const n=await A.getSessions();return i(n),n}catch(n){return console.error("Failed to load sessions:",n),[]}};o.useEffect(()=>{N().then(n=>{if(!n.length)return;const c=sessionStorage.getItem("morpheus.chat.uiSessionId"),t=c&&n.find(a=>a.id===c)?c:n[0].id;d(t)})},[]),o.useEffect(()=>{s?(E(s),sessionStorage.setItem("morpheus.chat.uiSessionId",s)):x([])},[s]);const E=async n=>{try{const c=await A.getMessages(n);x(c.filter(t=>t.type!=="system"))}catch(c){console.error("Failed to load messages:",c)}},S=async()=>{try{const n=await A.createSession();await N(),d(n.id),window.innerWidth<768&&j(!1)}catch(n){console.error("Failed to create session:",n)}},_=n=>{d(n),window.innerWidth<768&&j(!1)},l=async n=>{if(!s)return;const c=s,t={type:"human",content:n};x(a=>[...a,t]),b(a=>({...a,[c]:!0}));try{await A.sendMessage(c,n),c===w.current&&await E(c),await N()}catch(a){console.error("Failed to send message:",a)}finally{b(a=>{const h={...a};return delete h[c],h})}},C=n=>{z({isOpen:!0,title:"Archive Session",description:"Are you sure you want to archive this session? It will be moved to the archives.",confirmJson:"Archive",onConfirm:async()=>{try{await A.archiveSession(n),s===n&&d(null),await N()}catch(c){console.error("Failed to archive session:",c)}}})},M=n=>{z({isOpen:!0,title:"Delete Session",description:"Are you sure you want to DELETE this session? This action cannot be undone.",confirmJson:"Delete",variant:"destructive",onConfirm:async()=>{try{await A.deleteSession(n),s===n&&d(null),await N()}catch(c){console.error("Failed to delete session:",c)}}})},v=async(n,c)=>{try{await A.renameSession(n,c),await N()}catch(t){console.error("Failed to rename session:",t)}},T=r.find(n=>n.id===s)??null;return e.jsxs("div",{className:"flex h-full w-full overflow-hidden bg-white dark:bg-black relative",children:[g&&e.jsx("div",{className:"fixed inset-0 bg-black/40 z-20 md:hidden",onClick:()=>j(!1)}),e.jsx("div",{className:`
37
+ fixed top-16 bottom-0 left-0 z-40 flex
38
+ md:relative md:inset-auto md:z-auto md:translate-x-0
39
+ transition-transform duration-300 ease-out
40
+ ${g?"translate-x-0":"-translate-x-full"}
41
+ `,children:e.jsx(ye,{sessions:r,activeSessionId:s,onSelectSession:_,onCreateSession:S,onArchiveSession:C,onDeleteSession:M,onRenameSession:v,isOpen:g,toggleSidebar:()=>j(!g)})}),e.jsx("div",{className:"flex-1 flex flex-col h-full overflow-hidden min-w-0",children:e.jsx(Ae,{messages:u,onSendMessage:l,isLoading:p,activeSessionId:s,activeSession:T,onToggleSidebar:()=>j(!g)})}),e.jsx(ue,{isOpen:y.isOpen,onClose:()=>z(n=>({...n,isOpen:!1})),onConfirm:y.onConfirm,title:y.title,description:y.description,confirmJson:y.confirmJson,variant:y.variant})]})};export{Fe as ChatPage};