mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-06 23:49:41 +02:00
* refactor: extract SSE event handlers into named class methods Replace ~80 inline addListener closures in connectSSE() with a declarative _SSE_HANDLER_MAP array that drives registration in a single loop. Each handler is now a named _on* method on CodemanApp, making them individually addressable for LLM navigation. Add SSE_EVENTS constant object in constants.js to eliminate magic event-type strings scattered across the frontend. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: fix inaccuracies in CLAUDE.md - Fix types barrel path: src/types.ts → src/types/index.ts - Update app.js line count: ~12K → ~11.5K - Correct route handler counts (113 → 111, per-group fixes) - Add code style, ESM gotcha, env vars, route test, lifecycle log docs - Add Node 22 CI note, test teardown timeout, port range Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs: add mobile screenshots and QR auth security writeup to README Add 3 mobile screenshots (landing, idle, active) and expand the mobile section with QR auth security design details and a touch-optimized interface subsection. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: bundle xterm-zerolag-input as vendor IIFE and add pre-commit hook Build and postinstall now bundle the local xterm-zerolag-input package as an IIFE at vendor/xterm-zerolag-input.js with global LocalEchoOverlay shim. Add git pre-commit hook that runs prettier --check on staged .ts files to catch format issues before CI. Also bump constants.js and app.js cache-bust versions to 0.3.0 and add tunnel upload URL display row in settings. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: add cloudflared install support and interactive launch menu - Add optional cloudflared dependency detection and installation across 6 distro families (macOS, Debian, Fedora, Arch, Alpine, SUSE) - Add tunnel systemd service setup helper - Replace post-install instructions with interactive launch menu (run now / systemd service / skip) - Uninstall now cleans up both codeman-web and codeman-tunnel services Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: gitignore readme-preview.mjs Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: WIP — SSE event constants, @fileoverview docs, CLAUDE.md compression - Migrate broadcast() string literals → SseEvent.* typed constants - Add @fileoverview with cross-domain references to all 13 type domain files - Add @fileoverview to frontend JS modules (constants, mobile, voice, etc.) - Add section dividers to route files for LLM scanability - Compress CLAUDE.md: flat file list → domain table, fix counts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: optimize codebase for LLM context window efficiency CLAUDE.md: 456 → 309 lines (32% reduction) - Merge Commands into compact table, remove redundant bash block - Convert Security section to dense table format - Merge Performance + Resource Limits, Debugging + Troubleshooting - Compress Tunnel, Memory Leak, Scripts, Screenshots sections - Remove Key Patterns that duplicate @fileoverview in source files Backend @fileoverview enhancements (10 priority files): - session.ts: key methods, events, cross-domain refs - respawn-controller.ts: state machine, idle detection layers - ralph-tracker.ts: exports, circuit breaker, events - ralph-loop.ts: lifecycle, persistence, events - subagent-watcher.ts: watched patterns, teammate detection - server.ts: coordination list, port interfaces - state-store.ts: dual-file persistence, migration - session-manager.ts: lifecycle methods, mutex guard - hooks-config.ts: hook events list, categories - sse-events.ts: category breakdown (~90 events, 17 categories) Frontend app.js: add 6 section dividers, update @fileoverview line refs Fix: escape glob `*/` in JSDoc that broke ESLint parser Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: address PR #29 review bugs - server.ts: replace hardcoded 'session:needsRefresh' with SseEvent constant - install.sh: fix Alpine cloudflared install for non-root (download to tmpfile first) - install.sh: replace Arch pacman (AUR-only) with direct binary download - index.html: bump all 8 remaining cache-bust versions from v0.2.9 to v0.3.0 - mobile-handlers.js: fix @dependency annotation (keyboard-accessory.js, not constants.js) - types/push.ts: fix layer number (4, not 5) - subagent-watcher.ts: fix watched pattern path to include {session} segment - constants.js: fix SSE_EVENTS count in @fileoverview (~73, not ~65) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
156 lines
5.7 KiB
TypeScript
156 lines
5.7 KiB
TypeScript
/**
|
|
* @fileoverview Shared helper functions for route modules.
|
|
*
|
|
* Contains pure functions extracted from server.ts and a session lookup helper
|
|
* that replaces ~43 inline not-found checks across route handlers.
|
|
*/
|
|
|
|
import { join } from 'node:path';
|
|
import { homedir } from 'node:os';
|
|
import { Session } from '../session.js';
|
|
import { ApiErrorCode, createErrorResponse } from '../types.js';
|
|
import { parseRalphLoopConfig, extractCompletionPhrase } from '../ralph-config.js';
|
|
import { SseEvent } from './sse-events.js';
|
|
import type { SessionPort } from './ports/session-port.js';
|
|
import type { EventPort } from './ports/event-port.js';
|
|
|
|
// Shared path constants used across route modules
|
|
export const CASES_DIR = join(homedir(), 'codeman-cases');
|
|
export const SETTINGS_PATH = join(homedir(), '.codeman', 'settings.json');
|
|
|
|
// Maximum hook data size (prevents oversized SSE broadcasts)
|
|
const MAX_HOOK_DATA_SIZE = 8 * 1024;
|
|
|
|
/**
|
|
* Look up a session by ID or throw a structured error.
|
|
* Replaces the pattern: `const session = sessions.get(id); if (!session) return createErrorResponse(...)`.
|
|
*/
|
|
export function findSessionOrFail(ctx: SessionPort, sessionId: string): Session {
|
|
const session = ctx.sessions.get(sessionId);
|
|
if (!session) {
|
|
throw Object.assign(new Error(`Session ${sessionId} not found`), {
|
|
statusCode: 404,
|
|
body: createErrorResponse(ApiErrorCode.NOT_FOUND, `Session ${sessionId} not found`),
|
|
});
|
|
}
|
|
return session;
|
|
}
|
|
|
|
/**
|
|
* Formats uptime in seconds to a human-readable string (e.g., "1d 2h 30m 15s").
|
|
*/
|
|
export function formatUptime(seconds: number): string {
|
|
const days = Math.floor(seconds / 86400);
|
|
const hours = Math.floor((seconds % 86400) / 3600);
|
|
const minutes = Math.floor((seconds % 3600) / 60);
|
|
const secs = Math.floor(seconds % 60);
|
|
|
|
const parts: string[] = [];
|
|
if (days > 0) parts.push(`${days}d`);
|
|
if (hours > 0) parts.push(`${hours}h`);
|
|
if (minutes > 0) parts.push(`${minutes}m`);
|
|
if (secs > 0 || parts.length === 0) parts.push(`${secs}s`);
|
|
|
|
return parts.join(' ');
|
|
}
|
|
|
|
/**
|
|
* Sanitizes hook event data before broadcasting via SSE.
|
|
* Extracts only relevant fields and limits total size to prevent
|
|
* oversized payloads from being broadcast to all connected clients.
|
|
*/
|
|
export function sanitizeHookData(data: Record<string, unknown> | null | undefined): Record<string, unknown> {
|
|
if (!data || typeof data !== 'object') return {};
|
|
|
|
// Only forward known safe fields from Claude Code hook stdin
|
|
const safeFields: Record<string, unknown> = {};
|
|
const allowedKeys = [
|
|
'hook_event_name',
|
|
'tool_name',
|
|
'tool_input',
|
|
'session_id',
|
|
'cwd',
|
|
'permission_mode',
|
|
'stop_hook_active',
|
|
'transcript_path',
|
|
];
|
|
|
|
for (const key of allowedKeys) {
|
|
if (key in data && data[key] !== undefined) {
|
|
safeFields[key] = data[key];
|
|
}
|
|
}
|
|
|
|
// For tool_input, extract only summary fields (not full file content)
|
|
if (safeFields.tool_input && typeof safeFields.tool_input === 'object') {
|
|
const input = safeFields.tool_input as Record<string, unknown>;
|
|
const summary: Record<string, unknown> = {};
|
|
if (input.command) summary.command = String(input.command).slice(0, 500);
|
|
if (input.file_path) summary.file_path = String(input.file_path).slice(0, 500);
|
|
if (input.description) summary.description = String(input.description).slice(0, 200);
|
|
if (input.query) summary.query = String(input.query).slice(0, 200);
|
|
if (input.url) summary.url = String(input.url).slice(0, 500);
|
|
if (input.pattern) summary.pattern = String(input.pattern).slice(0, 200);
|
|
if (input.prompt) summary.prompt = String(input.prompt).slice(0, 200);
|
|
safeFields.tool_input = summary;
|
|
}
|
|
|
|
// Final size check - drop if serialized data exceeds limit
|
|
const serialized = JSON.stringify(safeFields);
|
|
if (serialized.length > MAX_HOOK_DATA_SIZE) {
|
|
return { tool_name: safeFields.tool_name, _truncated: true };
|
|
}
|
|
|
|
return safeFields;
|
|
}
|
|
|
|
/**
|
|
* Auto-configure Ralph tracker for a session.
|
|
*
|
|
* Priority order:
|
|
* 1. .claude/ralph-loop.local.md (official Ralph Wiggum plugin state)
|
|
* 2. CLAUDE.md <promise> tags (fallback)
|
|
*
|
|
* The ralph-loop.local.md file has priority because it contains
|
|
* the exact configuration from an active Ralph loop session.
|
|
*/
|
|
export function autoConfigureRalph(session: Session, workingDir: string, ctx: EventPort): void {
|
|
// First, try to read the official Ralph Wiggum plugin state file
|
|
const ralphConfig = parseRalphLoopConfig(workingDir);
|
|
|
|
if (ralphConfig && ralphConfig.completionPromise) {
|
|
session.ralphTracker.enable();
|
|
session.ralphTracker.startLoop(ralphConfig.completionPromise, ralphConfig.maxIterations ?? undefined);
|
|
|
|
// Restore iteration count if available
|
|
if (ralphConfig.iteration > 0) {
|
|
// The tracker's cycleCount will be updated when we detect iteration patterns
|
|
// in the terminal output, but we can set maxIterations now
|
|
console.log(`[auto-detect] Ralph loop at iteration ${ralphConfig.iteration}/${ralphConfig.maxIterations ?? '∞'}`);
|
|
}
|
|
|
|
console.log(
|
|
`[auto-detect] Configured Ralph loop for session ${session.id} from ralph-loop.local.md: ${ralphConfig.completionPromise}`
|
|
);
|
|
ctx.broadcast(SseEvent.SessionRalphLoopUpdate, {
|
|
sessionId: session.id,
|
|
state: session.ralphTracker.loopState,
|
|
});
|
|
return;
|
|
}
|
|
|
|
// Fallback: try CLAUDE.md
|
|
const claudeMdPath = join(workingDir, 'CLAUDE.md');
|
|
const completionPhrase = extractCompletionPhrase(claudeMdPath);
|
|
|
|
if (completionPhrase) {
|
|
session.ralphTracker.enable();
|
|
session.ralphTracker.startLoop(completionPhrase);
|
|
console.log(`[auto-detect] Configured Ralph loop for session ${session.id} from CLAUDE.md: ${completionPhrase}`);
|
|
ctx.broadcast(SseEvent.SessionRalphLoopUpdate, {
|
|
sessionId: session.id,
|
|
state: session.ralphTracker.loopState,
|
|
});
|
|
}
|
|
}
|