Commit Graph
45 Commits
Author SHA1 Message Date
weishu 4314aececd refactor: migrate from tsx to bun as TypeScript runtime
Remove tsx dependency and update all dev scripts and documentation to use bun
as the primary TypeScript runtime for development. Consolidate process detection
logic in daemon.ts to check for dev mode via src/index.ts regardless of runtime.
2025-12-25 22:13:58 +08:00
weishu 18e6310451 feat: implement web terminal feature with xterm.js and Socket.IO proxy
- Add CLI-side terminal management via Bun.Terminal with TerminalManager
- Implement server-side Socket.IO proxy for terminal I/O between web and CLI
- Create web terminal UI component with xterm.js and support for resize/reconnect
- Add terminal route and navigation button in session chat
- Include comprehensive terminal implementation plan and architecture docs
2025-12-25 21:57:18 +08:00
weishu 0762f0772f refactor: move directory creation before lock file operations. fix #6 2025-12-25 21:48:33 +08:00
weishu 21ed9fca2f docs: update Gemini default args to experimental-acp
Update HAPPY_GEMINI_ARGS default from --acp to --experimental-acp and add note about Gemini remote-only mode.
2025-12-25 16:56:26 +08:00
weishu 958e78dc6e refactor: rename HAPI_BOT_URL to HAPI_SERVER_URL
The project is no longer primarily a bot - it now provides HTTP API,
Socket.IO, SSE, and web app backend services. This rename reflects the
broader scope of server functionality.

Updates references in:
- cli/src/configuration.ts (core config)
- cli/src/ui/logger.ts (remote logging)
- cli/src/ui/doctor.ts (diagnostics)
- cli/src/commands/auth.ts (auth status)
- cli/src/daemon/daemon.integration.test.ts (test comments)
- README.md (quickstart docs)
- cli/README.md (CLI docs)
- cli/CLAUDE.md (dev docs)
2025-12-24 19:15:47 +08:00
weishu 31dfaebc85 chore: remove Windows ARM64 build support and add npm publish scripts
- Add publish-npm and publish-npm:dry-run scripts to root package.json (forwarding to cli)
- Remove Windows ARM64 (bun-windows-arm64) from DEFAULT_TARGETS in build-executable.ts
- Remove Windows ARM64 check from getPlatformDir in build-executable.ts
- Remove HAPI_TARGET_WIN32_ARM64 from bunBundle.d.ts type definitions
- Remove Windows ARM64 check from embeddedAssets.bun.ts
2025-12-24 18:51:49 +08:00
weishu 4497f437fd docs: rewrite daemon README with current codebase state
Complete documentation refresh covering:
- Version detection via CLI binary mtime (not package.json)
- Multi-Agent Support section with token authentication for claude/codex/gemini
- Directory creation approval flow for session spawning
- HTTP Control Server endpoints with Fastify + Zod schemas
- State persistence fields including startedWithCliMtimeMs
- Integration Testing section with test environment and key scenarios
- Typed shutdown sources (hapi-app, hapi-cli, os-signal, exception)
- MachineMetadata with new happyLibDir field
- WebSocket communication patterns and RPC methods
- Machine sync architecture with separated metadata and daemon state

Replaces CLAUDE.md with structured daemon documentation.
2025-12-24 18:16:01 +08:00
weishu b2eeb97d27 fix: handle abort signal before and during codex spawn
Add checks to gracefully handle abort signals:
- Check if abort is already signaled before attempting spawn
- Check if abort caused the spawn error instead of rejecting
2025-12-24 17:56:51 +08:00
weishu 2a10ce9675 feat: add support for user message events from Codex
Add sendUserMessage() method to ApiSessionClient and CodexSession to handle
user_message events from Codex. Updates CodexConversionResult type and
convertCodexEvent() to process user_message payloads, with test coverage.
2025-12-24 17:24:16 +08:00
weishu c09b870fe7 refactor(test): simplify keyboard input handling and extract type definitions
Remove reliance on key.name and key.sequence in favor of using input directly.
Extract TTY type definitions for clarity and add scoping constraints to prevent
variable shadowing. Update AGENTS.md documentation for accuracy.
2025-12-24 13:34:55 +08:00
weishu 1a23bfa430 refactor: remove custom executable support and simplify Claude CLI resolution
Remove support for custom executable paths and bundled Claude versions, including
deprecated environment variables HAPI_USE_BUNDLED_CLAUDE and HAPI_USE_GLOBAL_CLAUDE.
This simplifies the codebase to rely only on the global Claude CLI installation.

Updates Claude Code spawning logic to remove special handling for .js/.cjs files,
adds configurable BUN_BE_BUN environment variable handling, and streamlines path
resolution to throw an error when Claude Code CLI is not found on PATH.
2025-12-24 13:20:06 +08:00
weishu 8f804c57bf refactor: remove client-side session ID management
Remove proactive session ID generation and onSessionFound callback. Let Claude
handle session creation automatically via the SessionStart hook instead. This
simplifies the API contract and delegates session lifecycle management to Claude.
2025-12-24 10:35:20 +08:00
weishu a455cd8297 feat: add automatic CLI_API_TOKEN generation for the server
Implement secure auto-generation of CLI_API_TOKEN to eliminate mandatory
environment variable requirement. Token is generated once and persisted to
~/.hapi/settings.json for use by CLI on the same machine.

Changes:
- New cliApiToken.ts module with secure 256-bit token generation
- Configuration now accepts token from env, file, or generates on-demand
- Server displays prominently on first run, saves to settings
- CLI auth status command provides discovery hints for all scenarios
- Settings file parse errors fail fast to prevent data loss
2025-12-23 23:16:35 +08:00
weishu 706814653e fix: add friendly error messages for failed binary spawning
Added helpful error messages with cause preservation when spawning codex, gemini, or other CLI tools fails because the binary is not found in PATH. This follows the existing error handling pattern from claudeLocal.ts.
2025-12-23 20:20:51 +08:00
weishu bf7ae6fdd6 refactor(test): migrate useSwitchControls test from react-test-renderer to ink render 2025-12-23 18:43:09 +08:00
weishu 322c50e5a9 refactor(codex): extract config building and support CLI overrides in remote mode
This refactoring introduces CLI argument overrides for sandbox and approval policy settings in remote mode, allowing users to specify security constraints via `--sandbox` and `--ask-for-approval` flags.

Changes:
- Add `CodexCliOverrides` type and `parseCodexCliOverrides()` utility to parse CLI flags like `--sandbox`, `-s`, `--ask-for-approval`, `-a`, along with convenience flags (`--full-auto`, `--dangerously-bypass-approvals-and-sandbox`)
- Extract complex start config building logic into `buildCodexStartConfig()` function with proper approval policy and sandbox resolution based on permission mode
- Thread `codexCliOverrides` through the session/loop/launcher chain and apply overrides only when permission mode is 'default'
- Update `codexRemoteLauncher` to use the new config builder and display appropriate warnings based on whether overrides are present
- Add comprehensive tests for both parsing and config building functions
2025-12-23 18:43:01 +08:00
weishu 92996667d5 refactor: remove CommonJS ripgrep launcher and spawn binary directly
Replace the ripgrep_launcher.cjs intermediary with direct binary execution.
This simplifies the ripgrep module by spawning the binary directly instead
of going through a Node.js subprocess wrapper. Add platform-specific binary
path resolution to handle both Unix and Windows environments.
2025-12-23 18:09:12 +08:00
weishu 7f9145b6de feat: add token-based authentication to session hooks
Implement hook token validation to secure session start requests.
Each hook server generates a unique token that must be provided
in the x-hapi-hook-token header. Updates hook-forwarder command
to support both positional and named arguments for port and token.
2025-12-23 16:02:04 +08:00
weishu 61d3a1bed1 feat: implement session tracking via Claude hooks
Adds a dedicated hook server infrastructure to receive Claude SessionStart
notifications. This allows the CLI to track session ID changes (new sessions,
resume, compact, fork, etc.) without relying on file watchers.

Changes:
- Add SessionFound callback system to AgentSessionBase for session tracking
- Create hook server that listens for POST requests from Claude's hooks
- Generate temporary settings files with hook command configuration
- Implement session hook forwarder CLI command to relay hook data
- Integrate hook server into runClaude with proper cleanup
- Pass hookSettingsPath through local and remote execution paths
- Update SDK query builder to support --settings flag
2025-12-23 16:02:04 +08:00
weishu f81e585eef refactor(daemon): use mtime-based version detection instead of string comparison
Replace CLI version string comparison with file modification time (mtime) based detection. This provides a more reliable way to detect when the CLI binary has been updated, especially for bun-compiled executables where package.json may not be accessible.

Changes:
- Add getInstalledCliMtimeMs() utility to check CLI binary or package.json mtime
- Store startedWithCliMtimeMs in daemon state on startup
- Use mtime comparison in version check loop for daemon auto-restart
- Move version flag handling to early CLI startup before daemon initialization
- Fix machine active state merging to prefer newer activeAt timestamp

This improves daemon restart behavior when CLI is updated via package managers.
2025-12-23 13:14:15 +08:00
weishu 88cce9c28d refactor: remove CommonJS launchers and use claude command directly
Remove local Claude launcher scripts and refactor to invoke the global
claude command from PATH. This simplifies the launcher logic and removes
the need to maintain separate CommonJS entry points.

Changes:
- Delete cli/scripts/claude_local_launcher.cjs, claude_remote_launcher.cjs,
  and claude_version_utils.cjs
- Update claudeLocal to spawn 'claude' command directly instead of using
  a launcher script
- Remove runtimePath dependency and launcher existence checks
- Add DISABLE_AUTOUPDATER environment variable for local mode
- Improve error messages when claude command is not found
- Add shell option for Windows compatibility in process spawning
- Remove unused imports from claudeLocal and index files
2025-12-23 10:21:50 +08:00
weishu f132a7dc79 feat(codex): implement CLI argument passthrough for codex
Collect unknown CLI arguments from index.ts and pass them through the execution chain (runCodex → loop → CodexSession → codexLocalLauncher → codexLocal), similar to how claude already works. This enables users to pass CLI arguments like --model and --sandbox to the underlying codex process.

Filter out the 'resume' subcommand which is managed internally by hapi, while allowing other CLI arguments to pass through. Add warning log in remote mode when CLI args are ignored since remote mode uses message-based configuration instead. Include unit tests for the resume filtering logic.
2025-12-23 09:06:08 +08:00
weishu 0128792495 refactor: remove thinking state tracking from local launcher 2025-12-23 08:25:44 +08:00
weishu 93810689ad refactor(ui): extract switch controls logic into reusable hook and terminal restoration utility
Extracts duplicated exit/switch confirmation handling from CodexDisplay and RemoteModeDisplay into a custom useSwitchControls hook. Centralizes terminal state restoration (raw mode, keyboard protocol cleanup) into a restoreTerminalState utility function used across codex modules. Improves code reusability and maintainability.
2025-12-22 23:12:24 +08:00
weishu 360e3a9919 refactor: extract session and loop logic into reusable agent base classes 2025-12-22 23:12:24 +08:00
weishu 4290f539bd refactor(codex): extract session management and launcher logic into separate modules
Reorganized runCodex.ts to improve maintainability by extracting:
- CodexSession class for session lifecycle management
- CodexLocalLauncher and CodexRemoteLauncher for mode-specific initialization
- CodexEventConverter for MCP message handling and UI buffer updates
- CodexSessionScanner for resume file discovery
- emitReadyIfIdle utility for ready event emission

Added codexSessionId field to metadata schema for session tracking.
Updated UI components to work with refactored architecture.
2025-12-22 19:14:47 +08:00
weishu d057daabfe chore: migrate cli distribution from npm to bun executable
Migrate HAPI CLI from npm-based distribution to Bun single-executable format:
- Remove npm bin wrappers (bin/happy.mjs, bin/happy-mcp.mjs)
- Simplify package.json: remove npm publish config (exports, main, module, types, files, publishConfig)
- Update bin entry to point to TypeScript source (src/index.ts)
- Migrate shebang from Node to Bun (#!/usr/bin/env bun)
- Simplify build scripts: remove npm-specific steps (pkgroll, prepublishOnly, release-it)
- Update spawnHappyCLI to support compiled binaries and development TypeScript mode
- Update daemon/doctor diagnostics for new process detection logic
- Production: use `bun build --compile` for single-executable releases
- Development: run TypeScript directly via `bun src/index.ts` or `tsx src/index.ts`
2025-12-22 16:44:20 +08:00
weishu fd94a684dc fix(cli): improve error message categorization for better UX
- Connection errors (ECONNREFUSED, ETIMEDOUT, ENOTFOUND, "Network Error") show
  a friendly message with the server URL and network troubleshooting hints
- Authentication errors (401, 403, "unauthorized", "forbidden") suggest running
  `hapi auth login` to help users resolve auth issues
- Use case-insensitive matching (toLowerCase) to reliably catch error message
  variants
2025-12-22 12:34:52 +08:00
weishu dbcbc93ad0 feat: improve codex permission elicitation with parameter extraction and reason support
- Add robust parameter extraction helpers in codexMcpClient
- Implement buildElicitationResult to construct properly formatted MCP responses
- Support dynamic requested schemas with fallback handling
- Add reason/explanation tracking through permission decision flow
- Improve type safety with explicit extraction and validation
2025-12-22 09:27:20 +08:00
weishu ab06426773 feat: add source file execution and fix function name reference
- Add support for running CLI from TypeScript source when using tsx or similar tools
- Fix outdated happy__change_title reference to hapi__change_title in codex prompt
2025-12-21 23:13:14 +08:00
weishu 81852a3176 refactor: unify runtime directories and environment variables to HAPI_HOME
Consolidate CLI and server runtime directories from ~/.config/hapi/ (CLI) and ~/.hapi-server/ (Server) to a single ~/.hapi/ directory. Unify environment variables from HAPI_HOME_DIR (CLI) and HAPI_BOT_DATA_DIR (Server) to a single HAPI_HOME variable across both applications. Update all documentation and configuration references accordingly. Bump bun-types to 1.3.5.
2025-12-21 19:17:07 +08:00
weishu bf72e0dc3b chore: remove unused test fixtures and disable dead test case 2025-12-21 19:16:24 +08:00
weishu 4f03f29ac3 docs: rebrand Happy to HAPI and add component documentation
This commit rebrands the project from "Happy" to "HAPI" throughout the codebase, including documentation, comments, logs, and tool references. It also adds comprehensive README files for the server and web components, clarifies the monorepo structure in AGENTS.md and root README.md, and removes the outdated roadmap.md file.

Changes include:
- Rebrand references from Happy to HAPI in CLI, server, and web components
- MCP tool names updated from mcp__happy__ to mcp__hapi__
- Process/service names updated consistently
- New server/README.md with deployment and configuration guide
- New web/README.md with stack and development instructions
- Updated root README.md with quickstart guide
- Updated AGENTS.md with cleaner structure documentation
- Removed cli/roadmap.md (now superseded by documentation)
2025-12-21 18:49:04 +08:00
weishu 56ae2c85a2 feat(cli): add Agent Client Protocol (ACP) integration for external agent support
Implements comprehensive ACP backend enabling integration with ACP-compliant agents like Gemini. Includes stdio transport, message handling, permission flow, and registry for agent management. Adds new 'hapi gemini' command to launch ACP agent sessions.
2025-12-21 18:40:04 +08:00
weishu 1028547a3a feat(cli): add single executable with embedded web assets support
Implement support for bundling web assets into CLI single executable binaries.
When built with --with-web-assets, the executable includes the compiled web
application and serves it directly without file system access. A stub generator
creates empty manifests for normal builds to maintain compatibility.

Key changes:
- Add --with-web-assets flag to build-executable.ts with manifest validation
- Generate embeddedAssets.ts manifest from web/dist during build
- Serve embedded assets in web server with fallback to file system
- Add hapi server subcommand to start API + web server
- Include server sources in CLI tsconfig for compilation scope
- Add workspace-level build:single-exe scripts for production builds
2025-12-21 08:42:00 +08:00
weishu cf04937355 feat(cli): refactor embedded assets with Bun-specific and stub implementations
Split embedded assets loading into runtime-specific variants using package.json imports field. Bun-compiled binaries use the full implementation with file assets, while stub fallback provides clear error for non-Bun runtimes.
2025-12-20 23:46:02 +08:00
weishu 8ebd4f6ab9 feat: add git integration with file browsing and diff viewing
Add comprehensive git support across the stack:
- CLI: register git RPC handlers (status, diff numstat, diff file)
- Server: create git routes with proper session path resolution
- Web: add file browser, diff viewer, and git status visualization
- Add FileIcon component and git parser utilities
- Add TanStack Router routes for /files and /file pages
- Add git-themed CSS variables for light and dark modes
2025-12-20 23:00:26 +08:00
weishu 17eeba10d6 feat(cli): add Bun single executable binary support
Enables building hapi as standalone Bun-compiled executables for macOS,
Linux, and Windows (x64/arm64). Adds build script, bootstrap entry point,
runtime asset management, and automatic deployment of bundled tools
(ripgrep, difftastic). Includes MCP stdio bridge support and proper
environment handling for compiled binaries. Updates documentation with
build and installation instructions for single executable distribution.
2025-12-20 21:41:11 +08:00
weishu f0493ce68d feat(cli): add Bun compiled binary runtime asset management
Introduce runtime path abstraction for Bun-compiled binaries that extracts
assets to ~/.happy/runtime/{version} instead of using project paths. This
enables proper distribution of CLI as a self-contained binary with embedded
tools (ripgrep, difftastic) and scripts that are extracted at runtime.
2025-12-20 16:44:58 +08:00
weishu 80725a2d34 feat(cli): add Bun runtime support for ripgrep and CLI spawning
Replace hardcoded 'node' commands with process.execPath to support
Bun runtime alongside Node.js. Add runtime detection and entrypoint
resolution for Bun. Update documentation to reflect multi-runtime support.
2025-12-20 16:03:51 +08:00
weishu ac67718ec0 feat: implement AskUserQuestion tool with interactive UI and question flow
Add comprehensive support for the AskUserQuestion tool including:
- New footer component for handling user responses with multi-step question flow
- Type definitions and parsing utilities for question and answer formats
- View component for displaying questions and options
- Integration with permission system to capture user answers
- Support for single and multi-select questions with optional text input
- Haptic feedback and error handling for better UX
2025-12-18 23:24:41 +08:00
weishu 1b99c9422b fix: handle underscores in project path generation
Add underscore to the regex pattern in getProjectPath to ensure underscores
are replaced with hyphens, along with existing handling for slashes, colons,
and dots. Includes test case for paths with underscores.
2025-12-17 20:00:35 +08:00
weishu a696cafdd4 refactor: remove macOS caffeinate sleep prevention functionality 2025-12-17 15:59:50 +08:00
weishu c2b886896b feat: add interactive CLI token configuration with settings persistence
Implements comprehensive token management with intelligent priority resolution.
Token sources (highest to lowest priority): environment variable, settings file,
interactive prompt. Changes include:

- Updated home directory from ~/.happy to ~/.config/hapi (env var: HAPI_HOME_DIR)
- Added cliApiToken field to Settings interface for persistent storage
- Made cliApiToken mutable in Configuration class (private field with getter/setter)
- Created ui/tokenInit.ts module for token initialization with fallback prompt
- Enhanced auth command: login (interactive input), logout (clear token), status (show source)
- Updated doctor command to correctly identify token source and mask saved token in output
- Token initialization called early in startup flow to ensure availability before API use
2025-12-16 21:54:55 +08:00
weishu b4654acb92 init 2025-12-16 15:03:50 +08:00