Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor([issue-1842]): use canonical estimateTokens for chars-per-token estimates

[._.]/ Adam Eivy4bdfc2a9f1af
diff --git a/server/index.js b/server/index.js
index 5a89ee7a2f..7e4dca4bf3 100644
--- a/server/index.js
+++ b/server/index.js
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { PATHS } from './lib/fileUtils.js';
import { PORTS } from './lib/ports.js';
+import { estimateTokens } from './lib/contextBudget.js';
import { existsSync } from 'fs';
import { createTailscaleServers } from '../lib/tailscale-https.js';
import { certPaths } from '../lib/certPaths.js';
@@ -261,7 +262,7 @@ const aiToolkitHooks = {
});
},
onRunCompleted: (metadata, output) => {
- const estimatedTokens = Math.ceil(output.length / 4);
+ const estimatedTokens = estimateTokens(output);
recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens).catch(err => {
console.error(`❌ Failed to record usage: ${err.message}`);
});
@@ -1044,6 +1045,10 @@ const closeServer = (server, label) => new Promise((resolve) => {
});
});
+// Hard ceiling on graceful shutdown: if Socket.IO/HTTP don't close within this
+// window, force-exit so PM2 isn't left waiting on a hung process.
+const GRACEFUL_SHUTDOWN_TIMEOUT_MS = 10000;
+
let shuttingDown = false;
const shutdown = async (signal) => {
if (shuttingDown) return;
@@ -1063,7 +1068,7 @@ const shutdown = async (signal) => {
const forceExitTimer = setTimeout(() => {
console.error('⚠️ Graceful shutdown timed out, forcing exit');
process.exit(1);
- }, 10000);
+ }, GRACEFUL_SHUTDOWN_TIMEOUT_MS);
await new Promise((resolve) => {
io.close((err) => {
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index f0524557dc..a512ff5021 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -10,6 +10,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
import { recordSession, recordMessages } from './usage.js';
import { bufferedSpawn } from '../lib/bufferedSpawn.js';
import { atomicWrite, ensureDir, pathExists, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { estimateTokens } from '../lib/contextBudget.js';
const RUNS_DIR = PATHS.runs;
@@ -130,9 +131,9 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
await atomicWrite(metaPath, metadata);
await writeFile(join(runDir, 'output.txt'), output || '');
- // Record usage for successful CoS agent runs (estimate ~4 chars per token)
+ // Record usage for successful CoS agent runs (token count is estimated)
if (exitCode === 0 && metadata.providerId && metadata.model) {
- const estimatedTokens = Math.ceil((output || '').length / 4);
+ const estimatedTokens = estimateTokens(output);
recordMessages(metadata.providerId, metadata.model, 1, estimatedTokens).catch(err => {
console.error(`❌ Failed to record usage: ${err.message}`);
});
diff --git a/server/services/digital-twin-export.js b/server/services/digital-twin-export.js
index c683c22f7d..b0749cd88b 100644
--- a/server/services/digital-twin-export.js
+++ b/server/services/digital-twin-export.js
@@ -9,6 +9,7 @@ import { getAllAccounts as getAllSocialAccounts } from './socialAccounts.js';
import { DIGITAL_TWIN_DIR, now } from './digital-twin-helpers.js';
import { loadMeta } from './digital-twin-meta.js';
import { getTraits } from './digital-twin-analysis.js';
+import { estimateTokens } from '../lib/contextBudget.js';
export function getExportFormats() {
return [
@@ -80,7 +81,7 @@ function exportAsSystemPrompt(docs) {
format: 'system_prompt',
content: output.trim(),
documentCount: docs.length,
- tokenEstimate: Math.ceil(output.length / 4)
+ tokenEstimate: estimateTokens(output)
};
}
@@ -98,7 +99,7 @@ function exportAsClaudeMd(docs) {
format: 'claude_md',
content: output.trim(),
documentCount: docs.length,
- tokenEstimate: Math.ceil(output.length / 4)
+ tokenEstimate: estimateTokens(output)
};
}
@@ -124,7 +125,7 @@ function exportAsJson(docs) {
format: 'json',
content: jsonString,
documentCount: docs.length,
- tokenEstimate: Math.ceil(jsonString.length / 4)
+ tokenEstimate: estimateTokens(jsonString)
};
}
@@ -138,7 +139,7 @@ function exportAsIndividual(docs) {
content: doc.content
})),
documentCount: docs.length,
- tokenEstimate: docs.reduce((sum, d) => sum + Math.ceil(d.content.length / 4), 0)
+ tokenEstimate: docs.reduce((sum, d) => sum + estimateTokens(d.content), 0)
};
}
@@ -276,7 +277,7 @@ async function exportAsLegacyPortrait(docs) {
documentCount: docs.length,
storyCount: stories.length,
goalCount: goals.length,
- tokenEstimate: Math.ceil(content.length / 4)
+ tokenEstimate: estimateTokens(content)
};
}
diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.js
index dff1e7c2b9..6bb16fd6c2 100644
--- a/server/services/memoryEmbeddings.js
+++ b/server/services/memoryEmbeddings.js
@@ -10,6 +10,11 @@ import { getProviderById } from './providers.js';
import { getConfig as getCosConfig } from './cos.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
import { readResponseJson } from '../lib/readResponseJson.js';
+import { estimateTokens, CHARS_PER_TOKEN } from '../lib/contextBudget.js';
+
+// Re-export the canonical token estimator so existing importers
+// (e.g. memoryRetriever.js) keep their `from './memoryEmbeddings.js'` path.
+export { estimateTokens };
const MODEL_LIST_TIMEOUT_MS = 10000;
const MODEL_LOAD_TIMEOUT_MS = 60000;
@@ -426,22 +431,12 @@ export async function generateQueryEmbedding(query, context = {}) {
return generateEmbedding(text);
}
-/**
- * Estimate token count for text (rough approximation)
- * Used for context budgeting
- */
-export function estimateTokens(text) {
- if (!text) return 0;
- // Rough estimate: ~4 chars per token for English text
- return Math.ceil(text.length / 4);
-}
-
/**
* Truncate text to fit within token budget
*/
export function truncateToTokens(text, maxTokens) {
if (!text) return '';
- const maxChars = maxTokens * 4;
+ const maxChars = maxTokens * CHARS_PER_TOKEN;
if (text.length <= maxChars) return text;
return text.substring(0, maxChars - 3) + '...';
}