Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""A compaction whose session's last request is still cached asks for itssummaries at the end of that request, so the provider reads the history itsummarizes from cache.
Catches a replayed summary request that differs from the last turn's in itsinput prefix, tools, tool choice or instructions, a cache table that neverreaches the strategy, and a compaction that replays the very request a providerjust refused as too large. Only the assembled daemon has the loop, the cache table,the strategy and the summarizer together. When a summary is offered the cachedrequest, and when it is not, is `compaction.prepare`'s contract, checked in`apps/albedo/test/albedo/composition/compaction_prepare_test.gleam`; the lapseitself is `cache_ttl.lifetime`'s."""
import jsonimport unittest
from harness import ( Albedo, Provider, Reply, exclusive, python, text, system_prompt, conversation,)
LEAF = "Write the memory of one stretch of this conversation"NOTES = "Rewrite your compaction notes now"EVICTED = "<newly-evicted-history>"
def cache_table(seconds): """A local cache-table entry for the fixture host: a refresh TTL.""" return { "version": 1, "entries": [ { "id": "fixture", "match": {"host": "127.0.0.1"}, "policy": "refresh", "clock": "response", "tiers": [{"seconds": seconds, "write": 1.25}], "read": 0.1, "evidence": "measured", } ], }
def reply(request): sent = json.dumps(conversation(request)) if LEAF in sent: return text("replayed leaf") if NOTES in sent: return text("replayed notes") return text("ordinary answer")
@exclusiveclass SummaryReplayTests(unittest.TestCase): def setUp(self): self.provider = Provider(reply) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses") self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None)
def converse(self, ttl_seconds): (self.app.home / "cache-ttl.json").write_text( json.dumps(cache_table(ttl_seconds)) ) session = self.app.session() for prompt in ("older unit one", "older unit two", "newest unit"): self.app.prompt(session, prompt).close() self.app.idle(session) return session
def compact(self, session): before = len(self.provider.requests) response = self.app.compact(session, {"strategy": "coding-lcm"}) self.assertEqual(response["state"], "compacted") return [entry["request"] for entry in self.provider.requests[before:]]
def test_a_cached_request_is_replayed_with_the_summary_asked_at_its_end(self): session = self.converse(3600) turn = self.provider.requests[-1]["request"] calls = self.compact(session) replayed = [call for call in calls if LEAF in json.dumps(conversation(call))] self.assertEqual(len(replayed), 1, calls) leaf = replayed[0] # Everything the last turn sent comes first, unchanged, so the # provider reads it from cache; the request asked for the summary # with the turn's own tools and tool choice. self.assertEqual(leaf["input"][: len(turn["input"])], turn["input"]) self.assertIn(LEAF, json.dumps(leaf["input"][-1])) self.assertEqual(leaf.get("tools"), turn.get("tools")) self.assertEqual(leaf.get("tool_choice"), turn.get("tool_choice")) self.assertEqual(system_prompt(leaf), system_prompt(turn)) self.assertFalse( any(EVICTED in json.dumps(conversation(call)) for call in calls) ) notes = [call for call in calls if NOTES in json.dumps(conversation(call))] self.assertEqual(len(notes), 1, calls) self.assertEqual(notes[0]["input"][: len(turn["input"])], turn["input"]) self.app.prompt(session, "after fold").close() self.app.idle(session) shown = json.dumps(conversation(self.provider.requests[-1]["request"])) self.assertIn("replayed leaf", shown) self.assertIn("replayed notes", shown)
# One incompressible 400x400 picture, about 640 KB as base64.SHOW_NOISE = ( "import os, struct, zlib\n" "def chunk(kind, data):\n" " body = kind + data\n" " return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body))\n" "raw = b''.join(b'\\0' + os.urandom(1200) for _ in range(400))\n" "show_image(b'\\x89PNG\\r\\n\\x1a\\n'\n" " + chunk(b'IHDR', struct.pack('>IIBBBBB', 400, 400, 8, 2, 0, 0, 0))\n" " + chunk(b'IDAT', zlib.compress(raw, 0)) + chunk(b'IEND', b''))\n")
# What a provider with a request size limit takes of this fixture's pictures:# two fit, a third does not.BODY_LIMIT = 1_500_000
def pictures(request): return json.dumps(conversation(request)).count("data:image/png")
@exclusiveclass OverflowReplayTests(unittest.TestCase): def test_a_request_refused_for_its_size_is_compacted_without_replaying_it(self): refused = []
def reply(request): sent = json.dumps(conversation(request)) if len(sent) > BODY_LIMIT: refused.append(request) return Reply( "error", "too large", status=400, error_body={"error": {"code": "context_length_exceeded"}}, ) if LEAF in sent or NOTES in sent or EVICTED in sent: return text("summary of the early screenshots") if request["input"][-1].get("type") == "function_call_output": return text("looked at it") return python(SHOW_NOISE)
provider = Provider(reply) self.addCleanup(provider.close) with Albedo(provider, protocol="responses") as app: (app.home / "cache-ttl.json").write_text(json.dumps(cache_table(3600))) session = app.session() # The fixture's default window cannot hold a compaction's prompt. app.patch_session(session, {"context_window": 1_000_000}) route = f"/sessions/{session}/configuration" with app.api(route) as response: json.load(response) etag = response.headers["ETag"] app.api( route, {"selection": {"extensions": {"coding-lcm": True}}}, method="PATCH", headers={"If-Match": etag}, ).close() for prompt in ("first screenshot", "second screenshot", "third screenshot"): app.prompt(session, prompt).close() app.idle(session) # The last turn's picture is the one too many. A summary that # replayed that request, cached as it is, would be refused too. self.assertEqual(len(refused), 1) self.assertEqual(pictures(refused[0]), 3) summaries = [ call["request"] for call in provider.requests if EVICTED in json.dumps(conversation(call["request"])) ] self.assertTrue(summaries, "the refused request must be compacted") self.assertTrue(all(pictures(s) < 3 for s in summaries)) answers = [ entry for entry in app.history(session)["items"] if entry["kind"] == "assistant" ] self.assertIn("looked at it", json.dumps(answers[-1])) sent = json.dumps(conversation(provider.requests[-1]["request"])) self.assertIn("summary of the early screenshots", sent)
if __name__ == "__main__": unittest.main()