Files
puaros/packages/ipuaro/src/shared/utils/tokens.ts
imfozilbek 130a8c4f24 feat(ipuaro): implement v0.1.0 foundation
- Project setup with tsup, vitest, ESM support
- Domain entities: Session, Project
- Value objects: FileData, FileAST, FileMeta, ChatMessage, ToolCall, ToolResult, UndoEntry
- Service interfaces: IStorage, ILLMClient, ITool, IIndexer, IToolRegistry
- Shared: Config (zod), IpuaroError, utils (hash, tokens), Result type
- CLI with placeholder commands (start, init, index)
- 91 unit tests with 100% coverage
- Fix package scope @puaros -> @samiyev in CLAUDE.md
2025-11-29 23:08:38 +05:00

42 lines
956 B
TypeScript

/**
* Simple token estimation utilities.
* Uses approximation: ~4 characters per token for English text.
*/
const CHARS_PER_TOKEN = 4
/**
* Estimate token count for text.
*/
export function estimateTokens(text: string): number {
return Math.ceil(text.length / CHARS_PER_TOKEN)
}
/**
* Estimate token count for array of strings.
*/
export function estimateTokensForLines(lines: string[]): number {
return estimateTokens(lines.join("\n"))
}
/**
* Truncate text to approximate token limit.
*/
export function truncateToTokens(text: string, maxTokens: number): string {
const maxChars = maxTokens * CHARS_PER_TOKEN
if (text.length <= maxChars) {
return text
}
return `${text.slice(0, maxChars)}...`
}
/**
* Format token count for display.
*/
export function formatTokenCount(tokens: number): string {
if (tokens >= 1000) {
return `${(tokens / 1000).toFixed(1)}k`
}
return tokens.toString()
}