46 lines
2.7 KiB
Python
46 lines
2.7 KiB
Python
"""/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session:
|
|
1. loop-inbox's claim_talk sends ClaudeOpening, with its pid.
|
|
2. The loop stops reading its terminal, and its make_way lists the ask as OpenInInbox with that pid. claim_talk
|
|
returns True once it reads that, and loop-inbox opens claude.
|
|
3. loop-inbox sends ClaudeEnded once claude exits, which the loop reads with answers.claude_ended. The loop also stops waiting
|
|
if loop-inbox's process is gone.
|
|
"""
|
|
import dataclasses
|
|
import pathlib
|
|
import typing
|
|
|
|
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, read_ask
|
|
from loop_state.waiting.listing import ask_file, shown
|
|
from loop_state.waiting.answers import ClaudeEnded, ClaudeOpening, send
|
|
from loop_effects.effects import Effects, POLL_SECONDS
|
|
from failure import Failure
|
|
|
|
# Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way.
|
|
MAKE_WAY_SECONDS = 10 * POLL_SECONDS
|
|
# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; picked on 2026-10-17 by a bench of three readers seated as the README's audience.
|
|
TALK = "/talk"
|
|
|
|
|
|
def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure:
|
|
"""loop-inbox's side of /talk, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS. False where the ask is gone or replaced, its state is no longer Asking (answered first, claude open on the loop's own terminal, or the loop made way for another loop-inbox), or the loop didn't make way in time."""
|
|
if unsent := send(folder, ask, ClaudeOpening(pid)):
|
|
return unsent
|
|
deadline = now() + MAKE_WAY_SECONDS
|
|
while now() < deadline:
|
|
current = read_ask(ask_file(folder, ask.session))
|
|
if current is None or current.id != ask.id:
|
|
return False
|
|
if current.state == OpenInInbox(pid):
|
|
return True
|
|
if not isinstance(current.state, Asking):
|
|
return False
|
|
sleep(0.1)
|
|
# Takes the claim back: a loop that reads it late waits for no claude, and one that made way late, or failed to show it had, ends its wait.
|
|
send(folder, ask, ClaudeEnded())
|
|
return False
|
|
|
|
|
|
def make_way(folder: pathlib.Path, ask: Ask, pid: int, effects: Effects) -> None:
|
|
"""The loop's side of /talk from loop-inbox, once it has stopped reading its terminal: lists ask as having claude open in the loop-inbox whose process is pid, which claim_talk waits for. A failure only warns: claim_talk then gives up, and the loop stops."""
|
|
shown(folder, dataclasses.replace(ask, state=OpenInInbox(pid)), effects)
|