@teamvibe/poller 0.1.63 → 0.1.65

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.
@@ -1,5 +1,6 @@
1
1
  export type ErrorCategory = 'sqs' | 'brain' | 'auth' | 'session' | 'slack' | 'maintenance';
2
2
  export type ErrorSeverity = 'warn' | 'error';
3
+ export declare function emitEvent(eventType: string, channelId: string, metadata?: Record<string, unknown>): void;
3
4
  export declare function flush(): Promise<void>;
4
5
  export declare function startEventQueue(): void;
5
6
  export declare function stopEventQueue(): void;
@@ -10,16 +10,22 @@ let isFlushing = false;
10
10
  function dedupKey(channelId, category, message) {
11
11
  return `${channelId}:${category}:${message}`;
12
12
  }
13
+ function isErrorEvent(event) {
14
+ return event.eventType === 'poller.error';
15
+ }
13
16
  function enqueue(event) {
14
- // Dedup: collapse identical category+message within window
15
- const key = dedupKey(event.channelId, event.metadata.category, event.metadata.message);
16
- const now = Date.now();
17
- const windowStart = new Date(now - DEDUP_WINDOW_MS).toISOString();
18
- const existing = queue.find((e) => dedupKey(e.channelId, e.metadata.category, e.metadata.message) === key &&
19
- e.timestamp >= windowStart);
20
- if (existing) {
21
- existing.metadata.count += 1;
22
- return;
17
+ // Dedup only applies to error events
18
+ if (isErrorEvent(event)) {
19
+ const key = dedupKey(event.channelId, event.metadata.category, event.metadata.message);
20
+ const now = Date.now();
21
+ const windowStart = new Date(now - DEDUP_WINDOW_MS).toISOString();
22
+ const existing = queue.find((e) => isErrorEvent(e) &&
23
+ dedupKey(e.channelId, e.metadata.category, e.metadata.message) === key &&
24
+ e.timestamp >= windowStart);
25
+ if (existing && isErrorEvent(existing)) {
26
+ existing.metadata.count += 1;
27
+ return;
28
+ }
23
29
  }
24
30
  if (queue.length >= MAX_QUEUE_SIZE) {
25
31
  queue.shift(); // Drop oldest
@@ -47,6 +53,17 @@ async function flushOne(event) {
47
53
  return false;
48
54
  }
49
55
  }
56
+ export function emitEvent(eventType, channelId, metadata) {
57
+ if (!config.TEAMVIBE_API_URL || !config.TEAMVIBE_POLLER_TOKEN) {
58
+ return;
59
+ }
60
+ enqueue({
61
+ eventType,
62
+ channelId,
63
+ metadata,
64
+ timestamp: new Date().toISOString(),
65
+ });
66
+ }
50
67
  export async function flush() {
51
68
  if (queue.length === 0 || isFlushing)
52
69
  return;
@@ -26,6 +26,7 @@ export async function postMaintenanceReports(brainPath, channelId) {
26
26
  return;
27
27
  logger.info(`[MaintenanceReporter] Found ${jsonFiles.length} JSON report(s) in ${reportsDir}`);
28
28
  const postedFiles = [];
29
+ const removedFiles = [];
29
30
  for (const file of jsonFiles) {
30
31
  const filePath = join(reportsDir, file);
31
32
  try {
@@ -35,6 +36,7 @@ export async function postMaintenanceReports(brainPath, channelId) {
35
36
  logger.warn(`[MaintenanceReporter] Removing invalid report ${file}: missing operationType`);
36
37
  emitError('maintenance', `Removing invalid report ${file}: missing operationType`, { severity: 'warn' });
37
38
  await unlink(filePath).catch(() => { });
39
+ removedFiles.push(`reports/${file}`);
38
40
  continue;
39
41
  }
40
42
  const eventType = OPERATION_TO_EVENT_TYPE[report.operationType];
@@ -42,6 +44,7 @@ export async function postMaintenanceReports(brainPath, channelId) {
42
44
  logger.warn(`[MaintenanceReporter] Removing report ${file}: unknown operationType "${report.operationType}"`);
43
45
  emitError('maintenance', `Removing report ${file}: unknown operationType "${report.operationType}"`, { severity: 'warn' });
44
46
  await unlink(filePath).catch(() => { });
47
+ removedFiles.push(`reports/${file}`);
45
48
  continue;
46
49
  }
47
50
  const payload = {
@@ -73,12 +76,13 @@ export async function postMaintenanceReports(brainPath, channelId) {
73
76
  emitError('maintenance', `Error processing report ${file}: ${err instanceof Error ? err.message : String(err)}`, { severity: 'warn', channelId });
74
77
  }
75
78
  }
76
- // Remove posted JSON reports from git so they don't resurrect on next pull
77
- if (postedFiles.length > 0) {
79
+ // Remove posted/invalid JSON reports from git so they don't resurrect on next pull
80
+ const allRemovedFromGit = [...postedFiles, ...removedFiles];
81
+ if (allRemovedFromGit.length > 0) {
78
82
  try {
79
- await execFileAsync('git', ['rm', '--cached', '--ignore-unmatch', ...postedFiles], { cwd: brainPath });
80
- await execFileAsync('git', ['commit', '-m', 'chore: remove posted maintenance reports'], { cwd: brainPath });
81
- logger.info(`[MaintenanceReporter] Committed removal of ${postedFiles.length} posted report(s) from git`);
83
+ await execFileAsync('git', ['rm', '--cached', '--ignore-unmatch', ...allRemovedFromGit], { cwd: brainPath });
84
+ await execFileAsync('git', ['commit', '-m', 'chore: remove processed maintenance reports'], { cwd: brainPath });
85
+ logger.info(`[MaintenanceReporter] Committed removal of ${allRemovedFromGit.length} report(s) from git`);
82
86
  }
83
87
  catch (err) {
84
88
  logger.debug(`[MaintenanceReporter] Could not git-rm reports (may not be a git repo): ${err instanceof Error ? err.message : err}`);
package/dist/poller.js CHANGED
@@ -8,7 +8,7 @@ import { getBrainPath, ensureDirectories, ensureBaseBrain, pushBrainChanges } fr
8
8
  import { postMaintenanceReports } from './maintenance-reporter.js';
9
9
  import { initAuth, stopRefresh } from './auth-provider.js';
10
10
  import { registerBrain, startHeartbeatLoop, stopHeartbeatLoop } from './heartbeat-manager.js';
11
- import { startEventQueue, stopEventQueue, flush as flushEventQueue } from './event-queue.js';
11
+ import { startEventQueue, stopEventQueue, flush as flushEventQueue, emitEvent } from './event-queue.js';
12
12
  import { writeMessage, pickNextMessage, markProcessed, hasUnprocessed } from './inbox-manager.js';
13
13
  // Track active message processing
14
14
  const processingMessages = new Set();
@@ -64,6 +64,20 @@ async function runInboxLoop(threadId, kbPath, queueMessage, sessionLog) {
64
64
  if (result.success) {
65
65
  succeeded = true;
66
66
  sessionLog.info(`[Loop] Claude completed iteration #${iteration}`);
67
+ if (result.metrics) {
68
+ emitEvent('session.completed', queueMessage.teamvibe.channelId, {
69
+ threadId: queueMessage.thread_id,
70
+ total_cost_usd: result.metrics.total_cost_usd,
71
+ input_tokens: result.metrics.input_tokens,
72
+ output_tokens: result.metrics.output_tokens,
73
+ cache_read_input_tokens: result.metrics.cache_read_input_tokens,
74
+ cache_creation_input_tokens: result.metrics.cache_creation_input_tokens,
75
+ duration_ms: result.metrics.duration_ms,
76
+ duration_api_ms: result.metrics.duration_api_ms,
77
+ num_turns: result.metrics.num_turns,
78
+ model: result.metrics.model,
79
+ });
80
+ }
67
81
  if (queueMessage.teamvibe.brain?.brainId) {
68
82
  await pushBrainChanges(kbPath, queueMessage.teamvibe.brain.brainId, queueMessage.teamvibe.workspaceId);
69
83
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamvibe/poller",
3
- "version": "0.1.63",
3
+ "version": "0.1.65",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "bin": {