Skip to content

Commit 68f85a4

Browse files
authored
fix: minor cleanup (#1217)
# Motivation <!-- Why is this change necessary? --> # Content <!-- Please include a summary of the change --> # Testing <!-- How was the change tested? --> # Please check the following before marking your PR as ready for review - [ ] I have added tests for my changes - [ ] I have updated the documentation or added new documentation as needed
1 parent 8388449 commit 68f85a4

File tree

6 files changed

+75
-113
lines changed

6 files changed

+75
-113
lines changed

src/codegen/cli/commands/claude/claude_session_api.py

Lines changed: 47 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212
from codegen.cli.utils.org import resolve_org_id
1313

1414

15-
1615
class ClaudeSessionAPIError(Exception):
1716
"""Exception raised for Claude session API errors."""
17+
1818
pass
1919

2020

@@ -25,14 +25,14 @@ def generate_session_id() -> str:
2525

2626
def create_claude_session(session_id: str, org_id: Optional[int] = None) -> Optional[str]:
2727
"""Create a new Claude Code session in the backend.
28-
28+
2929
Args:
3030
session_id: The session ID to register
3131
org_id: Organization ID (will be resolved if None)
32-
32+
3333
Returns:
3434
Agent run ID if successful, None if failed
35-
35+
3636
Raises:
3737
ClaudeSessionAPIError: If the API call fails
3838
"""
@@ -42,24 +42,21 @@ def create_claude_session(session_id: str, org_id: Optional[int] = None) -> Opti
4242
if resolved_org_id is None:
4343
console.print("⚠️ Could not resolve organization ID for session creation", style="yellow")
4444
return None
45-
45+
4646
# Get authentication token
4747
token = get_current_token()
4848
if not token:
4949
console.print("⚠️ No authentication token found for session creation", style="yellow")
5050
return None
51-
51+
5252
# Prepare API request
5353
url = f"{API_ENDPOINT.rstrip('/')}/v1/organizations/{resolved_org_id}/claude_code/session"
54-
headers = {
55-
"Authorization": f"Bearer {token}",
56-
"Content-Type": "application/json"
57-
}
54+
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
5855
payload = {"session_id": session_id}
59-
56+
6057
# Make API request
6158
response = requests.post(url, json=payload, headers=headers, timeout=30)
62-
59+
6360
if response.status_code == 200:
6461
try:
6562
result = response.json()
@@ -75,10 +72,10 @@ def create_claude_session(session_id: str, org_id: Optional[int] = None) -> Opti
7572
error_msg = f"{error_msg}: {error_detail}"
7673
except Exception:
7774
error_msg = f"{error_msg}: {response.text}"
78-
75+
7976
console.print(f"⚠️ Failed to create Claude session: {error_msg}", style="yellow")
8077
return None
81-
78+
8279
except requests.RequestException as e:
8380
console.print(f"⚠️ Network error creating Claude session: {e}", style="yellow")
8481
return None
@@ -87,44 +84,41 @@ def create_claude_session(session_id: str, org_id: Optional[int] = None) -> Opti
8784
return None
8885

8986

90-
def end_claude_session(session_id: str, status: str, org_id: Optional[int] = None) -> bool:
91-
"""End a Claude Code session in the backend.
92-
87+
def update_claude_session_status(session_id: str, status: str, org_id: Optional[int] = None) -> bool:
88+
"""Update a Claude Code session status in the backend.
89+
9390
Args:
94-
session_id: The session ID to end
95-
status: Completion status ("COMPLETE" or "ERROR")
91+
session_id: The session ID to update
92+
status: Session status ("COMPLETE", "ERROR", "ACTIVE", etc.)
9693
org_id: Organization ID (will be resolved if None)
97-
94+
9895
Returns:
9996
True if successful, False if failed
10097
"""
10198
try:
10299
# Resolve org_id
103100
resolved_org_id = resolve_org_id(org_id)
104101
if resolved_org_id is None:
105-
console.print("⚠️ Could not resolve organization ID for session completion", style="yellow")
102+
console.print("⚠️ Could not resolve organization ID for session status update", style="yellow")
106103
return False
107-
104+
108105
# Get authentication token
109106
token = get_current_token()
110107
if not token:
111-
console.print("⚠️ No authentication token found for session completion", style="yellow")
108+
console.print("⚠️ No authentication token found for session status update", style="yellow")
112109
return False
113-
110+
114111
# Prepare API request
115112
url = f"{API_ENDPOINT.rstrip('/')}/v1/organizations/{resolved_org_id}/claude_code/session/{session_id}/status"
116-
headers = {
117-
"Authorization": f"Bearer {token}",
118-
"Content-Type": "application/json"
119-
}
113+
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
120114
payload = {"status": status}
121-
115+
122116
# Make API request
123117
response = requests.post(url, json=payload, headers=headers, timeout=30)
124-
118+
125119
if response.status_code == 200:
126-
status_emoji = "✅" if status == "COMPLETE" else "❌"
127-
console.print(f"{status_emoji} Ended Claude session {session_id[:8]}... with status {status}", style="green")
120+
status_emoji = "✅" if status == "COMPLETE" else "🔄" if status == "ACTIVE" else "❌"
121+
console.print(f"{status_emoji} Updated Claude session {session_id[:8]}... status to {status}", style="green")
128122
return True
129123
else:
130124
error_msg = f"HTTP {response.status_code}"
@@ -133,26 +127,26 @@ def end_claude_session(session_id: str, status: str, org_id: Optional[int] = Non
133127
error_msg = f"{error_msg}: {error_detail}"
134128
except Exception:
135129
error_msg = f"{error_msg}: {response.text}"
136-
137-
console.print(f"⚠️ Failed to end Claude session: {error_msg}", style="yellow")
130+
131+
console.print(f"⚠️ Failed to update Claude session status: {error_msg}", style="yellow")
138132
return False
139-
133+
140134
except requests.RequestException as e:
141-
console.print(f"⚠️ Network error ending Claude session: {e}", style="yellow")
135+
console.print(f"⚠️ Network error updating Claude session status: {e}", style="yellow")
142136
return False
143137
except Exception as e:
144-
console.print(f"⚠️ Unexpected error ending Claude session: {e}", style="yellow")
138+
console.print(f"⚠️ Unexpected error updating Claude session status: {e}", style="yellow")
145139
return False
146140

147141

148142
def send_claude_session_log(session_id: str, log_entry: dict, org_id: Optional[int] = None) -> bool:
149143
"""Send a log entry to the Claude Code session log endpoint.
150-
144+
151145
Args:
152146
session_id: The session ID
153147
log_entry: The log entry to send (dict)
154148
org_id: Organization ID (will be resolved if None)
155-
149+
156150
Returns:
157151
True if successful, False if failed
158152
"""
@@ -162,24 +156,21 @@ def send_claude_session_log(session_id: str, log_entry: dict, org_id: Optional[i
162156
if resolved_org_id is None:
163157
console.print("⚠️ Could not resolve organization ID for log sending", style="yellow")
164158
return False
165-
159+
166160
# Get authentication token
167161
token = get_current_token()
168162
if not token:
169163
console.print("⚠️ No authentication token found for log sending", style="yellow")
170164
return False
171-
165+
172166
# Prepare API request
173167
url = f"{API_ENDPOINT.rstrip('/')}/v1/organizations/{resolved_org_id}/claude_code/session/{session_id}/log"
174-
headers = {
175-
"Authorization": f"Bearer {token}",
176-
"Content-Type": "application/json"
177-
}
168+
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
178169
payload = {"log": log_entry}
179-
170+
180171
# Make API request
181172
response = requests.post(url, json=payload, headers=headers, timeout=30)
182-
173+
183174
if response.status_code == 200:
184175
return True
185176
else:
@@ -189,10 +180,10 @@ def send_claude_session_log(session_id: str, log_entry: dict, org_id: Optional[i
189180
error_msg = f"{error_msg}: {error_detail}"
190181
except Exception:
191182
error_msg = f"{error_msg}: {response.text}"
192-
183+
193184
console.print(f"⚠️ Failed to send log entry: {error_msg}", style="yellow")
194185
return False
195-
186+
196187
except requests.RequestException as e:
197188
console.print(f"⚠️ Network error sending log entry: {e}", style="yellow")
198189
return False
@@ -203,25 +194,21 @@ def send_claude_session_log(session_id: str, log_entry: dict, org_id: Optional[i
203194

204195
def write_session_hook_data(session_id: str, org_id: Optional[int] = None) -> str:
205196
"""Write session data for Claude hook and create session via API.
206-
197+
207198
This function is called by the Claude hook to both write session data locally
208199
and create the session in the backend API.
209-
200+
210201
Args:
211202
session_id: The session ID
212203
org_id: Organization ID
213-
204+
214205
Returns:
215206
JSON string to write to the session file
216207
"""
217208
# Create session in backend API
218209
agent_run_id = create_claude_session(session_id, org_id)
219-
210+
220211
# Prepare session data
221-
session_data = {
222-
"session_id": session_id,
223-
"agent_run_id": agent_run_id,
224-
"org_id": resolve_org_id(org_id)
225-
}
226-
227-
return json.dumps(session_data, indent=2)
212+
session_data = {"session_id": session_id, "agent_run_id": agent_run_id, "org_id": resolve_org_id(org_id)}
213+
214+
return json.dumps(session_data, indent=2)

src/codegen/cli/commands/claude/config/claude_session_active_hook.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717
sys.path.insert(0, str(codegen_cli_dir))
1818

1919
try:
20-
from codegen.cli.commands.claude.claude_session_api import end_claude_session
20+
from codegen.cli.commands.claude.claude_session_api import update_claude_session_status
2121
except ImportError:
22-
end_claude_session = None
22+
update_claude_session_status = None
2323

2424

2525
def read_session_file() -> dict:
@@ -53,19 +53,15 @@ def main():
5353
except ValueError:
5454
org_id = None
5555

56-
if end_claude_session and session_id:
57-
end_claude_session(session_id, "ACTIVE", org_id)
56+
if update_claude_session_status and session_id:
57+
update_claude_session_status(session_id, "ACTIVE", org_id)
5858

5959
# Print minimal output
60-
print(json.dumps({
61-
"session_id": session_id,
62-
"status": "ACTIVE"
63-
}))
60+
print(json.dumps({"session_id": session_id, "status": "ACTIVE"}))
6461

6562
except Exception as e:
6663
print(json.dumps({"error": str(e)}))
6764

6865

6966
if __name__ == "__main__":
7067
main()
71-

src/codegen/cli/commands/claude/config/claude_session_hook.py

Lines changed: 9 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,14 @@
1111
import sys
1212
from pathlib import Path
1313

14+
from codegen.cli.commands.claude.claude_session_api import create_claude_session
15+
from codegen.cli.utils.org import resolve_org_id
16+
1417
# Add the codegen CLI to the path so we can import from it
1518
script_dir = Path(__file__).parent
1619
codegen_cli_dir = script_dir.parent.parent.parent
1720
sys.path.insert(0, str(codegen_cli_dir))
1821

19-
try:
20-
from codegen.cli.commands.claude.claude_session_api import create_claude_session
21-
from codegen.cli.utils.org import resolve_org_id
22-
except ImportError:
23-
# Fallback if imports fail - just write basic session data
24-
create_claude_session = None
25-
resolve_org_id = None
26-
2722

2823
def main():
2924
"""Main hook function called by Claude Code."""
@@ -44,10 +39,11 @@ def main():
4439
if not session_id:
4540
# Fallback: try to extract from input data
4641
session_id = input_data.get("session_id")
47-
42+
4843
if not session_id:
4944
# Generate a basic session ID if none available
5045
import uuid
46+
5147
session_id = str(uuid.uuid4())
5248

5349
# Get org_id from environment variable (set by main.py)
@@ -65,32 +61,21 @@ def main():
6561

6662
# Create session via API if available
6763
agent_run_id = None
68-
if create_claude_session and org_id:
64+
if org_id:
6965
agent_run_id = create_claude_session(session_id, org_id)
7066

7167
# Prepare session data
72-
session_data = {
73-
"session_id": session_id,
74-
"agent_run_id": agent_run_id,
75-
"org_id": org_id,
76-
"hook_event": input_data.get("hook_event_name"),
77-
"timestamp": input_data.get("timestamp")
78-
}
68+
session_data = {"session_id": session_id, "agent_run_id": agent_run_id, "org_id": org_id, "hook_event": input_data.get("hook_event_name"), "timestamp": input_data.get("timestamp")}
7969

8070
# Output the session data (this gets written to the session file by the hook command)
8171
print(json.dumps(session_data, indent=2))
8272

8373
except Exception as e:
8474
# If anything fails, at least output basic session data
8575
session_id = os.environ.get("CODEGEN_CLAUDE_SESSION_ID", "unknown")
86-
fallback_data = {
87-
"session_id": session_id,
88-
"error": str(e),
89-
"agent_run_id": None,
90-
"org_id": None
91-
}
76+
fallback_data = {"session_id": session_id, "error": str(e), "agent_run_id": None, "org_id": None}
9277
print(json.dumps(fallback_data, indent=2))
9378

9479

9580
if __name__ == "__main__":
96-
main()
81+
main()

src/codegen/cli/commands/claude/config/claude_session_stop_hook.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717
sys.path.insert(0, str(codegen_cli_dir))
1818

1919
try:
20-
from codegen.cli.commands.claude.claude_session_api import end_claude_session
20+
from codegen.cli.commands.claude.claude_session_api import update_claude_session_status
2121
except ImportError:
22-
end_claude_session = None
22+
update_claude_session_status = None
2323

2424

2525
def read_session_file() -> dict:
@@ -53,14 +53,11 @@ def main():
5353
except ValueError:
5454
org_id = None
5555

56-
if end_claude_session and session_id:
57-
end_claude_session(session_id, "COMPLETE", org_id)
56+
if update_claude_session_status and session_id:
57+
update_claude_session_status(session_id, "COMPLETE", org_id)
5858

5959
# Print minimal output to avoid noisy hooks
60-
print(json.dumps({
61-
"session_id": session_id,
62-
"status": "COMPLETE"
63-
}))
60+
print(json.dumps({"session_id": session_id, "status": "COMPLETE"}))
6461

6562
except Exception as e:
6663
# Ensure hook doesn't fail Claude if something goes wrong
@@ -69,4 +66,3 @@ def main():
6966

7067
if __name__ == "__main__":
7168
main()
72-

0 commit comments

Comments
 (0)