Files
EJClaw/src/utils.ts
Eyejoker 5ea3439c5f refactor: extract shared utilities, protocol constants, and retry loop
Phase 3: provider-retry.ts — shared Claude rotation loop (SSOT)
  - retryClaudeWithRotation extracted from message-agent-executor + task-scheduler
  - ~200 lines of duplicated retry logic removed

Phase 4: types.ts — AgentOutputPhase + VisiblePhase unified
Phase 5: types.ts — AgentConfig extended with claudeThinking/claudeThinkingBudget

Utilities (utils.ts):
  - getErrorMessage: 14 occurrences of instanceof Error pattern → 1 function
  - readJsonFile/writeJsonFile: 19 occurrences of JSON+fs pattern → 2 functions
  - fetchWithTimeout: 3 occurrences of AbortController pattern → 1 function
  - formatElapsedKorean: deduplicated from task-watch-status + message-turn-controller

Protocol (agent-protocol.ts):
  - OUTPUT_START/END_MARKER centralized (runners keep local copies with SSOT reference)
  - IMAGE_TAG_RE, IPC constants documented

Runner: show "대화 요약 중..." progress message during auto-compact

Net: -137 lines, 354/354 tests passing
2026-03-25 04:59:49 +09:00

70 lines
2.3 KiB
TypeScript

/**
* Shared utilities (SSOT).
*
* Small helpers that were previously copy-pasted across 10+ files.
*/
import fs from 'fs';
// ── Error handling ──────────────────────────────────────────────
/** Extract a human-readable message from an unknown caught value. */
export function getErrorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
// ── JSON file I/O ───────────────────────────────────────────────
/** Read and parse a JSON file. Returns null on any failure. */
export function readJsonFile<T = unknown>(filePath: string): T | null {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf-8')) as T;
} catch {
return null;
}
}
/** Write data as JSON to a file. */
export function writeJsonFile(
filePath: string,
data: unknown,
pretty = false,
): void {
fs.writeFileSync(
filePath,
JSON.stringify(data, null, pretty ? 2 : undefined),
);
}
// ── Fetch with timeout ──────────────────────────────────────────
/** Wrapper around fetch() that aborts after timeoutMs. */
export async function fetchWithTimeout(
url: string,
init: RequestInit,
timeoutMs: number,
): Promise<Response> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(url, { ...init, signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
// ── Time formatting ─────────────────────────────────────────────
/** Format milliseconds as Korean elapsed time (e.g. "1시간 2분 30초"). */
export function formatElapsedKorean(ms: number): string {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const parts: string[] = [];
if (hours > 0) parts.push(`${hours}시간`);
if (minutes > 0) parts.push(`${minutes}`);
parts.push(`${seconds}`);
return parts.join(' ');
}