Compact a waiting worker's session shortly before its prompt cache expires
CI / tests (pull_request) Failing after 3m16s
CI / tests (pull_request) Failing after 3m16s
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import dataclasses
|
||||
import datetime
|
||||
import sys
|
||||
import typing
|
||||
import uuid
|
||||
@@ -6,7 +7,11 @@ import uuid
|
||||
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from claude_code.entries import AssistantTurn, Entry
|
||||
from claude_code.reply import Limited
|
||||
from claude_code.tokens import tokens_of
|
||||
from claude_code.transcript import human_turns, read_transcript
|
||||
from loop_claude.cycle.worker import run_worker
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.direct_message import tell
|
||||
@@ -16,6 +21,10 @@ ANSWER_QUESTION = "answer the question above"
|
||||
# TALK, what the human types at loop-claude's terminal to open claude for the question, and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
TALK = "/talk"
|
||||
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
|
||||
# While the human hasn't answered, the worker's session is compacted CACHE_MARGIN seconds before its hour-long prompt cache expires: compacting reads the context from the cache, while resuming after it expired writes the whole context again. Below COMPACT_FLOOR tokens of context, that write costs less than compacting. A five-minute cache expires within the margin, so it is left as it is. lilleman chose this on 2026-11-11.
|
||||
HOUR_CACHE = 3600
|
||||
CACHE_MARGIN = 600
|
||||
COMPACT_FLOOR = 60_000
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -57,12 +66,52 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, window:
|
||||
|
||||
def answered(answer_here: bool, session: WorkerSession, effects: Effects) -> str | Talked | Stop:
|
||||
"""The human's answer, as interrupt returns it."""
|
||||
answer = typed_answer(effects) if answer_here else TALK
|
||||
answer = waited_answer(session, effects) if answer_here else TALK
|
||||
if answer != TALK:
|
||||
return answer
|
||||
return human_typed(session.transcript_path, lambda: claude_open(session, effects)) or Talked()
|
||||
|
||||
|
||||
def waited_answer(session: WorkerSession, effects: Effects) -> str | Stop:
|
||||
"""typed_answer, compacting the worker's session where no answer has come shortly before its prompt cache expires. The claude TALK opens compacts an idle session itself."""
|
||||
entries = read_transcript(session.transcript_path)
|
||||
delay = None if isinstance(entries, Failure) else compaction_delay(entries, effects.now())
|
||||
if delay is None:
|
||||
return typed_answer(effects)
|
||||
stop_timer = effects.timer(delay, lambda: compact(session, effects))
|
||||
try:
|
||||
return typed_answer(effects)
|
||||
finally:
|
||||
# Waits for a compaction under way, so the worker doesn't resume the session while it is compacted.
|
||||
stop_timer()
|
||||
|
||||
|
||||
def compaction_delay(entries: list[Entry], now: float) -> float | None:
|
||||
"""Seconds from now until CACHE_MARGIN before the session's prompt cache expires. None where its context is under COMPACT_FLOOR tokens, its cache lasts five minutes, or the margin has begun."""
|
||||
turns = [entry for entry in entries if isinstance(entry, AssistantTurn) and entry.usage]
|
||||
if not turns or tokens_of(turns[-1].usage).context() < COMPACT_FLOOR:
|
||||
return None
|
||||
# A read refreshes the cache for the lifetime it was written with.
|
||||
written = next((tokens for turn in reversed(turns) if (tokens := tokens_of(turn.usage)).write_5m or tokens.write_1h), None)
|
||||
if written is None or not written.write_1h:
|
||||
return None
|
||||
try:
|
||||
last_read = datetime.datetime.fromisoformat(turns[-1].timestamp).timestamp()
|
||||
except ValueError:
|
||||
return None
|
||||
delay = last_read + HOUR_CACHE - CACHE_MARGIN - now
|
||||
return delay if delay > 0 else None
|
||||
|
||||
|
||||
def compact(session: WorkerSession, effects: Effects) -> None:
|
||||
"""Compacts the worker's session with `claude -p /compact`, saying how that went."""
|
||||
outcome = run_worker(session.root, claude_args(session.rung, ["-p", "/compact", "--resume", str(session.id), "--output-format", "stream-json", "--verbose"]), session.env, effects)
|
||||
if outcome is None:
|
||||
say("compacted the worker's claude session before its prompt cache expires; still waiting for an answer", effects)
|
||||
else:
|
||||
say(f"could not compact the worker's claude session: {outcome.said if isinstance(outcome, Limited) else outcome.reason}; still waiting for an answer", effects)
|
||||
|
||||
|
||||
def typed_answer(effects: Effects) -> str | Stop:
|
||||
"""The line typed at loop-claude's terminal, stripped. A Stop where they type no answer, or the input ends."""
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user