local-memory-store-utils.ts 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { createHash } from 'node:crypto';
  2. import { readdir, readFile, unlink } from 'node:fs/promises';
  3. import { LocalMemoryError, type LocalMemorySearchResult } from './types.js';
  4. export function appendWithSeparator(current: string, addition: string): string {
  5. if (!current.trim()) return addition;
  6. return `${current.replace(/\s*$/, '')}\n${addition}`;
  7. }
  8. export function applyEdit(
  9. current: string,
  10. oldString: string,
  11. newString: string,
  12. replaceAll: boolean,
  13. ): { content: string; replacements: number } {
  14. if (!oldString) throw new LocalMemoryError('OLD_STRING_EMPTY', 'old_string is required');
  15. const matches = current.split(oldString).length - 1;
  16. if (matches === 0) throw new LocalMemoryError('OLD_STRING_NOT_FOUND', 'old_string not found');
  17. if (!replaceAll && matches > 1) {
  18. throw new LocalMemoryError('OLD_STRING_AMBIGUOUS', 'old_string is ambiguous');
  19. }
  20. const content = replaceAll
  21. ? current.split(oldString).join(newString)
  22. : current.replace(oldString, newString);
  23. return { content, replacements: replaceAll ? matches : 1 };
  24. }
  25. export function searchLines(content: string, query: string): LocalMemorySearchResult[] {
  26. const lower = query.toLowerCase();
  27. if (!lower) return [];
  28. const lines = content.split(/\r?\n/);
  29. return lines.flatMap((line, index) =>
  30. line.toLowerCase().includes(lower)
  31. ? [{ lineNumber: index + 1, line, context: lines.slice(Math.max(0, index - 1), index + 2) }]
  32. : [],
  33. );
  34. }
  35. const TOPIC_HEADER_RE = /^---\ndescription: ([\s\S]*?)\n---\n\n/;
  36. export function parseTopic(content: string): { description: string; body: string } {
  37. const match = TOPIC_HEADER_RE.exec(content);
  38. if (!match) return { description: '', body: content };
  39. return { description: decodeURIComponent(match[1] ?? ''), body: content.slice(match[0].length) };
  40. }
  41. export function formatTopic(description: string, content: string): string {
  42. return `---\ndescription: ${encodeURIComponent(description)}\n---\n\n${content}`;
  43. }
  44. export function formatLocalDate(input: number | Date = Date.now()): string {
  45. const date = input instanceof Date ? input : new Date(input);
  46. const year = date.getFullYear();
  47. const month = String(date.getMonth() + 1).padStart(2, '0');
  48. const day = String(date.getDate()).padStart(2, '0');
  49. return `${year}-${month}-${day}`;
  50. }
  51. export function formatLocalDateTime(input: number | Date): string {
  52. const date = input instanceof Date ? input : new Date(input);
  53. const hours = String(date.getHours()).padStart(2, '0');
  54. const minutes = String(date.getMinutes()).padStart(2, '0');
  55. const seconds = String(date.getSeconds()).padStart(2, '0');
  56. return `${formatLocalDate(date)} ${hours}:${minutes}:${seconds}`;
  57. }
  58. export function assertSafeAgentName(agentName: string | undefined): string {
  59. const normalized = agentName?.trim();
  60. if (!normalized) throw new LocalMemoryError('AGENT_NAME_REQUIRED', 'agent_name is required');
  61. // Path-safety: the agent name becomes a path segment under agents/<name>/, so
  62. // reject anything that could escape that directory or break the path.
  63. if (
  64. normalized.includes('/') ||
  65. normalized.includes('\\') ||
  66. normalized.includes('..') ||
  67. // eslint-disable-next-line no-control-regex
  68. /[\u0000-\u001f]/.test(normalized)
  69. ) {
  70. throw new LocalMemoryError('INVALID_AGENT_NAME', `invalid agent_name: ${agentName}`);
  71. }
  72. return normalized;
  73. }
  74. export function assertDate(date: string): string {
  75. if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new LocalMemoryError('INVALID_DATE', 'invalid date');
  76. return date;
  77. }
  78. export function today(): string {
  79. return formatLocalDate();
  80. }
  81. export function formatTs(ts: number): string {
  82. return formatLocalDateTime(ts);
  83. }
  84. export function byteLength(content: string): number {
  85. return Buffer.byteLength(content, 'utf8');
  86. }
  87. export function firstLine(content: string): string | undefined {
  88. return content
  89. .split(/\r?\n/)
  90. .find((line) => line.trim().length > 0)
  91. ?.slice(0, 200);
  92. }
  93. export async function safeRead(filePath: string): Promise<string> {
  94. return readFile(filePath, 'utf8').catch((err: NodeJS.ErrnoException) => {
  95. if (err.code === 'ENOENT') return '';
  96. throw err;
  97. });
  98. }
  99. export async function safeReaddir(dir: string): Promise<string[]> {
  100. return readdir(dir).catch((err: NodeJS.ErrnoException) => {
  101. if (err.code === 'ENOENT') return [];
  102. throw err;
  103. });
  104. }
  105. export async function deleteIfExists(filePath: string): Promise<boolean> {
  106. return unlink(filePath)
  107. .then(() => true)
  108. .catch((err: NodeJS.ErrnoException) => {
  109. if (err.code === 'ENOENT') return false;
  110. throw err;
  111. });
  112. }
  113. export function sha256(content: string): string {
  114. return createHash('sha256').update(content).digest('hex');
  115. }