900. Agent session state machine
Why it matters Production agents fail in odd orders: tool results arriving after a cancel, duplicate answers, timeouts. An explicit state machine makes those cases safe and testable.
Model an agent session as a state machine and replay its events.
States: "idle", "thinking", "waiting_tool", "done", "cancelled". Start in "idle". Allowed transitions:
- idle + "user_msg" -> thinking
- thinking + "tool_call" -> waiting_tool
- waiting_tool + "tool_result" -> thinking
- waiting_tool + "timeout" -> thinking (count it as a timeout)
- thinking + "answer" -> idle
- idle + "end" -> done
- any state except done and cancelled + "cancel" -> cancelled
Any other event in the current state is rejected: the state stays the same and the event's index (0-based) is recorded. Every event after done or cancelled is rejected.
Write run_session(events). events is a list of event strings (can be empty).
Return a dict {"state": final state, "rejected": list of indices, "tool_calls": number of accepted "tool_call" events, "timeouts": number of accepted "timeout" events}.
def run_session(events)Example 1
Input: run_session(['user_msg', 'tool_call', 'tool_result', 'answer', 'end'])
Output: {'state': 'done', 'rejected': [], 'tool_calls': 1, 'timeouts': 0}
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 6 tests to be accepted.
Hint 1
Store the transitions in a dict keyed by (state, event).
Hint 2
Handle terminal states and cancel before looking up the table.
Hint 3
Update counters only when an event is accepted.
Common mistakes
- Allowing cancel from done.
- Counting rejected tool calls.
- Changing state on a rejected event.
Understand the idea
Writing transitions as a table keyed by (state, event) keeps the logic in one place and makes every unexpected event an explicit rejection rather than a silent bug. Terminal states accept nothing, which prevents work after a user cancels. The counters only count accepted events, so a tool_call sent while idle is not billed as a call.
Shapes and data flow
List of strings in, dict out.