mirror of
https://github.com/Alishahryar1/free-claude-code.git
synced 2026-07-10 00:14:16 +00:00
## Problem
Runtime modules were published as generic top-level packages like `api`,
`cli`, and `providers`. That shape is fragile for PyPI packaging and
weakens explicit ownership boundaries.
## Changes
| Before | After |
| --- | --- |
| Runtime code lived in root-level packages. | Runtime code lives under
`src/free_claude_code/`. |
| Console scripts targeted top-level modules. | Console scripts target
namespaced modules. |
| Tests and smoke helpers imported old package roots. | Tests and smoke
helpers import `free_claude_code.*`. |
| Packaging listed six root packages. | Packaging builds the single
namespaced package. |
| Contracts allowed old root package directories. | Contracts require
the src namespace and reject old root imports. |
<!-- greptile_comment -->
<details open><summary><h3>Greptile Summary</h3></summary>
This PR moves the runtime packages into the `src/free_claude_code`
namespace. The main changes are:
- Console scripts now point to `free_claude_code.*` entrypoints.
- Runtime imports, tests, and smoke helpers now use the namespaced
package.
- Packaging now builds the single `src/free_claude_code` package.
- Contract tests now reject old top-level runtime package roots and
imports.
</details>
<h3>Confidence Score: 5/5</h3>
This PR is safe to merge with minimal risk.
The changes are a broad but mostly mechanical namespace and
package-layout migration with updated packaging, tests, and contract
coverage.
No files require special attention.
<details><summary><h3><a href="https://www.greptile.com/trex"><img
alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="20" align="absmiddle"></a> T-Rex Logs</h3></summary>
**What T-Rex did**
- Reviewed the primary contract validation by examining the namespace
validation log, which documents the exact commands executed, the working
directory, exit codes, pytest output, wheel build output, install
output, and import/entrypoint resolution.
- Verified the wheel listing by inspecting the wheel listing artifact,
confirming the available wheel filenames for the namespace validation.
- Ran and inspected the isolated import/entrypoint validation harness
saved as package-installed-import-check.py to validate import resolution
and entrypoint exposure.
- Captured and noted the wheel filename record in
package-wheel-filename.txt to enable traceability of the observed
artifact.
<a
href="https://app.greptile.com/trex/runs/13810533/artifacts"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifactsDark.svg?v=4"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"><img
alt="View all artifacts"
src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"></picture></a>
<sub><a href="https://www.greptile.com/trex"><img alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="14" align="absmiddle"></a> Ran code and verified through
T-Rex</sub>
</details>
<details open><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| pyproject.toml | Updates packaging to build the single
`src/free_claude_code` package and retargets console scripts to
namespaced modules. |
| src/free_claude_code/config/env_template.py | Loads `.env.example`
from packaged resources with a source-checkout fallback after the
runtime package move. |
| src/free_claude_code/cli/entrypoints.py | Updates CLI entrypoint
imports to `free_claude_code.*` and continues to use the shared env
template loader. |
| src/free_claude_code/api/routes.py | Retargets API route dependencies
and handlers to the namespaced package without changing route behavior.
|
| src/free_claude_code/api/app.py | Updates app factory imports to the
namespaced package while preserving middleware, routers, and exception
handling. |
| src/free_claude_code/providers/runtime/factory.py | Updates lazy
provider factory imports to `free_claude_code.providers.*` under the new
package layout. |
| tests/contracts/test_import_boundaries.py | Adds contract coverage
requiring runtime packages to live under `src/free_claude_code` and
rejecting old top-level imports. |
| smoke/lib/child_process.py | Updates smoke child-process helpers to
import CLI entrypoints from the namespaced package. |
| README.md | Updates the project layout and extension guidance to refer
to `src/free_claude_code` and importable `free_claude_code.*` modules. |
| uv.lock | Reflects the package version bump associated with the
runtime packaging move. |
</details>
<details open><summary><h3>Sequence Diagram</h3></summary>
<a href="#gh-light-mode-only">
```mermaid
%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant User as User / CLI
participant Script as Console script
participant Pkg as free_claude_code package
participant API as free_claude_code.api
participant Runtime as free_claude_code.providers.runtime
participant Provider as Provider adapter
User->>Script: run fcc-server / free-claude-code
Script->>Pkg: load free_claude_code.cli.entrypoints:serve
Pkg->>API: create FastAPI app and routes
API->>Runtime: resolve configured provider
Runtime->>Provider: instantiate namespaced adapter
Provider-->>Runtime: stream/model responses
Runtime-->>API: provider result
API-->>User: Anthropic/OpenAI-compatible response
```
</a>
<a href="#gh-dark-mode-only">
```mermaid
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant User as User / CLI
participant Script as Console script
participant Pkg as free_claude_code package
participant API as free_claude_code.api
participant Runtime as free_claude_code.providers.runtime
participant Provider as Provider adapter
User->>Script: run fcc-server / free-claude-code
Script->>Pkg: load free_claude_code.cli.entrypoints:serve
Pkg->>API: create FastAPI app and routes
API->>Runtime: resolve configured provider
Runtime->>Provider: instantiate namespaced adapter
Provider-->>Runtime: stream/model responses
Runtime-->>API: provider result
API-->>User: Anthropic/OpenAI-compatible response
```
</a>
</details>
<sub>Reviews (2): Last reviewed commit: ["Fix documented package import
paths"](bfa9f2704c)
| [Re-trigger
Greptile](https://app.greptile.com/api/retrigger?id=42950471)</sub>
<!-- /greptile_comment -->
135 lines
4.7 KiB
Python
135 lines
4.7 KiB
Python
"""CLI event handling for a single queued node (transcript + session + errors)."""
|
|
|
|
from collections.abc import Awaitable, Callable
|
|
from typing import Any
|
|
|
|
from loguru import logger
|
|
|
|
from free_claude_code.core.trace import trace_event
|
|
|
|
from .cli_event_constants import TRANSCRIPT_EVENT_TYPES, get_status_for_event
|
|
from .managed_protocols import ManagedClaudeSessionManagerProtocol
|
|
from .safe_diagnostics import text_len_hint
|
|
from .session import SessionStore
|
|
from .transcript import TranscriptBuffer
|
|
from .trees import MessageState, MessageTree
|
|
|
|
|
|
async def handle_session_info_event(
|
|
event_data: dict[str, Any],
|
|
tree: MessageTree | None,
|
|
node_id: str,
|
|
captured_session_id: str | None,
|
|
temp_session_id: str | None,
|
|
*,
|
|
cli_manager: ManagedClaudeSessionManagerProtocol,
|
|
session_store: SessionStore,
|
|
save_tree_snapshot: Callable[[MessageTree], None] | None = None,
|
|
) -> tuple[str | None, str | None]:
|
|
"""Handle session_info event; return updated (captured_session_id, temp_session_id)."""
|
|
if event_data.get("type") != "session_info":
|
|
return captured_session_id, temp_session_id
|
|
|
|
real_session_id = event_data.get("session_id")
|
|
if not real_session_id or not temp_session_id:
|
|
return captured_session_id, temp_session_id
|
|
|
|
await cli_manager.register_real_session_id(temp_session_id, real_session_id)
|
|
trace_event(
|
|
stage="claude_cli",
|
|
event="claude_cli.session.registered",
|
|
source="claude_cli",
|
|
node_id=node_id,
|
|
temp_session_id=temp_session_id,
|
|
real_session_id=real_session_id,
|
|
tree_root_id=tree.root_id if tree else None,
|
|
)
|
|
if tree and real_session_id:
|
|
await tree.update_state(
|
|
node_id,
|
|
MessageState.IN_PROGRESS,
|
|
session_id=real_session_id,
|
|
)
|
|
if save_tree_snapshot is None:
|
|
session_store.save_tree_snapshot(tree.snapshot())
|
|
else:
|
|
save_tree_snapshot(tree)
|
|
|
|
return real_session_id, None
|
|
|
|
|
|
async def process_parsed_cli_event(
|
|
parsed: dict[str, Any],
|
|
transcript: TranscriptBuffer,
|
|
update_ui: Callable[..., Awaitable[None]],
|
|
last_status: str | None,
|
|
had_transcript_events: bool,
|
|
tree: MessageTree | None,
|
|
node_id: str,
|
|
captured_session_id: str | None,
|
|
*,
|
|
session_store: SessionStore,
|
|
save_tree_snapshot: Callable[[MessageTree], None] | None = None,
|
|
format_status: Callable[..., str],
|
|
propagate_error_to_children: Callable[[str, str, str], Awaitable[None]],
|
|
log_messaging_error_details: bool = False,
|
|
) -> tuple[str | None, bool]:
|
|
"""Process a single parsed CLI event. Returns (last_status, had_transcript_events)."""
|
|
ptype = parsed.get("type") or ""
|
|
|
|
if ptype in TRANSCRIPT_EVENT_TYPES:
|
|
transcript.apply(parsed)
|
|
had_transcript_events = True
|
|
|
|
status = get_status_for_event(ptype, parsed, format_status)
|
|
if status is not None:
|
|
await update_ui(status)
|
|
last_status = status
|
|
elif ptype == "block_stop":
|
|
await update_ui(last_status, force=True)
|
|
elif ptype == "complete":
|
|
if parsed.get("status") != "success":
|
|
return last_status, had_transcript_events
|
|
if not had_transcript_events:
|
|
transcript.apply({"type": "text_chunk", "text": "Done."})
|
|
trace_event(
|
|
stage="claude_cli",
|
|
event="turn.completed",
|
|
source="cli_event",
|
|
node_id=node_id,
|
|
claude_session_id=captured_session_id,
|
|
)
|
|
await update_ui(format_status("✅", "Complete"), force=True)
|
|
if tree and captured_session_id:
|
|
await tree.update_state(
|
|
node_id,
|
|
MessageState.COMPLETED,
|
|
session_id=captured_session_id,
|
|
)
|
|
if save_tree_snapshot is None:
|
|
session_store.save_tree_snapshot(tree.snapshot())
|
|
else:
|
|
save_tree_snapshot(tree)
|
|
elif ptype == "error":
|
|
error_msg = parsed.get("message", "Unknown error")
|
|
em = error_msg if isinstance(error_msg, str) else str(error_msg)
|
|
trace_event(
|
|
stage="claude_cli",
|
|
event="turn.failed",
|
|
source="cli_event",
|
|
node_id=node_id,
|
|
claude_session_id=captured_session_id,
|
|
cli_error_message=em,
|
|
)
|
|
if log_messaging_error_details:
|
|
logger.error("HANDLER: Error event received: {}", error_msg)
|
|
else:
|
|
logger.error(
|
|
"HANDLER: Error event received: message_chars={}",
|
|
text_len_hint(em),
|
|
)
|
|
await update_ui(format_status("❌", "Error"), force=True)
|
|
if tree:
|
|
await propagate_error_to_children(node_id, error_msg, "Parent task failed")
|
|
|
|
return last_status, had_transcript_events
|