Skip to content

Commit 504e6ea

Browse files
refactor(agent-runtime): extract helpers from run-agent-step.ts (Commit
2.3) Extract helper functions from loopAgentSteps to improve readability and testability: - initializeAgentRun: Agent template resolution, run initialization, system prompt generation - buildInitialMessages: Initial message history construction - buildToolDefinitions: Tool definitions for token counting - prepareStepContext: Token counting and step prompt preparation - handleOutputSchemaRetry: Output schema validation and retry logic - extractErrorMessage, isPaymentRequiredError, getErrorStatusCode: Error handling utilities The main loopAgentSteps function is now organized into clear phases: 1. Initialize Agent Run 2. Build Initial Messages 3. Agent Step Loop 4. Finalize Run This refactoring maintains full backwards compatibility while reducing the cognitive load of understanding the agent execution flow. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
1 parent f4e0aa5 commit 504e6ea

File tree

3 files changed

+605
-273
lines changed

3 files changed

+605
-273
lines changed

REFACTORING_PLAN.md

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ This document outlines a prioritized refactoring plan for the 51 issues identifi
1515

1616
## Progress Tracker
1717

18-
> **Last Updated:** 2025-01-20 (Commits 2.1–2.2 Complete)
19-
> **Current Status:** Ready for Commit 2.3 (run-agent-step)
18+
> **Last Updated:** 2025-01-20 (Commits 2.1–2.3 Complete)
19+
> **Current Status:** Ready for Commit 2.4 (billing consolidation)
2020
2121
### Phase 1 Progress
2222
| Commit | Description | Status | Completed By |
@@ -32,7 +32,7 @@ This document outlines a prioritized refactoring plan for the 51 issues identifi
3232
|--------|-------------|--------|-------------|
3333
| 2.1 | Refactor use-send-message.ts | ✅ Complete | Codebuff |
3434
| 2.2 | Consolidate block utils + think tags | ✅ Complete | Codebuff |
35-
| 2.3 | Refactor loopAgentSteps | ⬜ Not Started | - |
35+
| 2.3 | Refactor loopAgentSteps | ✅ Complete | Codex CLI |
3636
| 2.4 | Consolidate billing duplication | ⬜ Not Started | - |
3737
| 2.5a | Extract multiline keyboard navigation | ⬜ Not Started | - |
3838
| 2.5b | Extract multiline editing handlers | ⬜ Not Started | - |
@@ -252,25 +252,59 @@ This document outlines a prioritized refactoring plan for the 51 issues identifi
252252

253253
---
254254

255-
### Commit 2.3: Refactor `loopAgentSteps` in `run-agent-step.ts`
255+
### Commit 2.3: Refactor `loopAgentSteps` in `run-agent-step.ts` ✅ COMPLETE
256256
**Files:** `packages/agent-runtime/src/run-agent-step.ts`
257257
**Est. Time:** 4-5 hours
258-
**Est. LOC Changed:** ~500-600
258+
**Actual Time:** ~3 hours
259+
**Est. LOC Changed:** ~500-600
260+
**Actual LOC Changed:** 521 insertions (new file), 112 deletions (run-agent-step.ts reduced from 966 → 854 lines)
259261

260262
> **Moved from Phase 1:** Let chat.tsx patterns establish before tackling runtime.
261263
262-
| Task | Description |
263-
|------|-------------|
264-
| Extract `processToolCalls()` | Tool call handling |
265-
| Extract `handleStreamEvents()` | Stream event processing |
266-
| Extract `validateStepResult()` | Step validation logic |
267-
| Create `AgentStepProcessor` class | Optional: OOP refactor |
268-
| Simplify main loop | Reduce to coordination only |
264+
| Task | Description | Status |
265+
|------|-------------|--------|
266+
| Extract `initializeAgentRun()` | Agent run setup (analytics, step warnings, message history) ||
267+
| Extract `buildInitialMessages()` | Message history building with system prompts ||
268+
| Extract `buildToolDefinitions()` | Tool definition preparation ||
269+
| Extract `prepareStepContext()` | Step context preparation (token counting, tool definitions) ||
270+
| Extract `handleOutputSchemaRetry()` | Output schema retry logic ||
271+
| Extract error utilities | `extractErrorMessage`, `isPaymentRequiredError`, `getErrorStatusCode` ||
272+
| Add phase-based organization | Clear Phase 1-4 comments in loopAgentSteps ||
273+
274+
**New Files Created:**
275+
- `packages/agent-runtime/src/agent-step-helpers.ts` (521 lines) - Extracted helpers:
276+
- `initializeAgentRun` - Agent run setup
277+
- `buildInitialMessages` - Message history building
278+
- `buildToolDefinitions` - Tool definition preparation
279+
- `prepareStepContext` - Step context preparation
280+
- `handleOutputSchemaRetry` - Output schema retry logic
281+
- `additionalToolDefinitions` - Tool definition caching
282+
- Error handling utilities
283+
284+
**Review Findings (from 4 CLI agents):**
285+
-~~Dead imports in run-agent-step.ts~~ → Fixed: removed cloneDeep, mapValues, callTokenCountAPI, additionalSystemPrompts, buildAgentToolSet, getToolSet, withSystemInstructionTags, buildUserMessageContent
286+
-~~Unsafe type casts in error utilities~~ → Fixed: added `hasStatusCode()` type guard for safe error property access
287+
-~~AI slop: excessive section dividers and verbose JSDoc~~ → Fixed: trimmed ~65 lines (module docstring, 5 section dividers, redundant JSDoc)
288+
- ✅ Extraction boundaries are well-chosen with clear responsibilities
289+
- ✅ Phase-based organization is excellent
290+
- ✅ cachedAdditionalToolDefinitions pattern is efficient
291+
292+
**Review Fixes Applied:**
293+
| Fix | Description |
294+
|-----|-------------|
295+
| Remove dead imports | Cleaned up 8 unused imports from run-agent-step.ts |
296+
| Add type guard | Created `hasStatusCode()` to replace unsafe `as` casts |
297+
| Trim AI slop | Reduced agent-step-helpers.ts from 525 → 460 lines |
298+
299+
**Test Results:**
300+
- 369 agent-runtime tests pass (all)
301+
- TypeScript compiles cleanly
269302

270303
**Dependencies:** Commits 1.1a, 1.1b (patterns)
271304
**Risk:** High - Core runtime, extensive testing required
272305
**Feature Flag:** `REFACTOR_AGENT_LOOP=true`
273-
**Rollback:** Revert and flag off
306+
**Rollback:** Revert and flag off
307+
**Commit:** `5f31dc9f8` (amended with review fixes)
274308

275309
---
276310

0 commit comments

Comments
 (0)