diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 86741908..ae28382a 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1031,6 +1031,21 @@ tool descriptions) was 9,443 tokens, read in 10 s; in a tool loop, each later tu the cache and read only the new part in 1-2 s. On Windows, Codex's sandbox rejected every shell command in that test until it was started with `-c 'windows.sandbox="unelevated"'` (a Codex setting, not Strata's). +**Codex's compaction (opt-in: `"codex_compaction_cache": true` in `strata-.json`).** When the context fills up (or +on `/compact`), Codex sends the conversation once more with a request to summarize it, and with `tools: []`. The template +writes the tools at the top of the prompt, so that prompt would share only its first few tokens with the conversation the +engine holds and be read again from the start, at its longest. With the option on, Strata keeps which Codex conversation +sent the last prompt other than a compaction (`session_id` and `thread_id` from `client_metadata["x-codex-turn-metadata"]`) +and the tools that prompt was rendered with; a request Codex marks `"request_kind": "compaction"`, from that same +conversation and without tools of its own, is rendered with them. Only the prompt: for the output parser and in the +response the request's tools stay what Codex sent, none, so a tool call the model writes comes back as a plain function +call without its namespace or custom-tool form. It is one entry, replaced by each such prompt; a compaction of another +conversation, a request without that metadata (Codex before 0.140) or a restart renders the request as sent, and so does +one that would not fit the context with the kept tools. Off by default: the prompt of a compaction differs from the +one the client sent. The author measured, with Codex CLI 0.160.0 and an engine that only counts the shared prompt start, +that a compaction after an 85,000-token conversation reused 84,895 of its 84,997 tokens and read 102; without it, 41 of +80,683. + ## Tools from MCP servers The chat page can give the model tools from [MCP](https://modelcontextprotocol.io) servers, as LM Studio and Claude diff --git a/serve/responses.py b/serve/responses.py index 7e3d8001..c7bc1545 100644 --- a/serve/responses.py +++ b/serve/responses.py @@ -358,6 +358,57 @@ def thread_title_events(req: dict, model: str): return events +# Codex's local compaction (the context is full, or /compact) sends its conversation again with `tools: []` +# (codex-rs/core/src/compact.rs: `Prompt { input, base_instructions, ..Default::default() }`). The template writes +# the tools at the top of the prompt, so that prompt shares almost nothing with the one the engine holds and the whole +# conversation is read again, at its longest. So the tools a Codex conversation's last prompt was rendered with are +# kept, and that conversation's compaction prompt is rendered with them. Only the prompt: the parser and the response +# get the request's own tools, which are none. Codex says what a request is and whose it is in +# client_metadata["x-codex-turn-metadata"] (a JSON string, Codex 0.140 and later): `request_kind` and the +# conversation's `session_id` and `thread_id` (a sub-agent shares its parent's session, not its thread; a fork gets +# its own). `prompt_cache_key` is not used: it groups requests for caching, and Codex gives sub-agents and ephemeral +# forks their parent's. A request without that metadata is rendered as sent and changes nothing. One entry, replaced +# by each prompt of a Codex conversation: nothing grows, and a compaction of any other conversation finds a different +# (session_id, thread_id) and renders its request as sent. Lost (a restart): the prompt is read again, as without it. +_kept_prompt_tools = (None, None) # ((session_id, thread_id), its prompt's tools as JSON or None) + + +def _codex_turn(req: dict): + """-> (request_kind, (session_id, thread_id)) from Codex's turn metadata; the conversation is None without both.""" + meta = req.get("client_metadata") + raw = meta.get("x-codex-turn-metadata") if isinstance(meta, dict) else None + try: + turn = json.loads(raw) if isinstance(raw, str) else None + except ValueError: + turn = None + if not isinstance(turn, dict): + return None, None + conversation = (turn.get("session_id"), turn.get("thread_id")) + return turn.get("request_kind"), conversation if all(isinstance(x, str) and x for x in conversation) else None + + +def prompt_tools(req: dict, tools): + """-> the tools the prompt is rendered with: request_tools' `tools`, or for a Codex compaction request without + tools the ones its own conversation's last prompt was rendered with (so its prompt starts as that one did).""" + kind, conversation = _codex_turn(req) + owner, kept = _kept_prompt_tools + if kind != "compaction" or conversation is None or owner != conversation or kept is None or req.get("tools"): + return tools + return json.loads(kept) # a fresh copy: the kept one is nobody's to change + + +def prompt_made(req: dict, tools): + """The prompt of `req` was rendered with `tools` and goes to the engine: a Codex request that is not a compaction + leaves its conversation and those tools for that conversation's compaction. A thread-title turn is another + session Codex sends beside the real one, and it does not replace this entry.""" + global _kept_prompt_tools + if (_turn_body(req) or {}).get("thread_source") == "thread_title": + return + kind, conversation = _codex_turn(req) + if conversation is not None and kind != "compaction": + _kept_prompt_tools = (conversation, json.dumps(tools) if tools else None) + + def text_format(req: dict): """`text.format` -> the chat path's response_format (None: plain text).""" text = req.get("text") diff --git a/serve/server.py b/serve/server.py index 876aab3f..f10bda9b 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2206,6 +2206,7 @@ class Service: self.literals = literal_tags(getattr(tokenizer, "control_tokens", ())) # texts that stay text inside a message self.fit_max_tokens = fit_max_tokens # --fit-max-tokens: clamp the output cap instead of 400 self.aliases: list[str] = [] # #297: other names of the model (the config's `aliases`) + self.codex_compaction_cache = False # #924 (opt-in): a Codex compaction is rendered with its conversation's tools self.codex_thread_titles = False # #923 (opt-in): answer Codex's thread-title turns without the engine self.sampling_defaults = dict(sampling_defaults or {}) # the run config's `sampling` block self.shared = {} # the web app's Chat settings for every client (POST /settings) @@ -4586,13 +4587,24 @@ def make_handler(svc: Service): except ValueError as e: raise ResponsesError(str(e), "stop") from None svc.load() + # #924 (opt-in): a Codex compaction request is rendered with its conversation's tools, so its prompt + # starts as the cached one did; the parser and the response keep the request's own tools + shown = responses_api.prompt_tools(req, tools) if svc.codex_compaction_cache else tools try: - ids, thinking, max_new = svc.prepare(messages, tools, kw, req.get("max_output_tokens") or 0) + try: + ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0) + except ValueError: + if shown is tools: + raise + shown = tools # too long with the kept tools: the request as sent + ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0) except ResponsesError: raise except ValueError as e: # too long for the context, an image without vision raise ResponsesError(str(e), "input", "context_length_exceeded" if "context" in str(e) else None) \ from None + if svc.codex_compaction_cache: + responses_api.prompt_made(req, shown) _debug_req("responses", req, messages, tools, max_new, thinking, len(ids)) include = req.get("include") if isinstance(req.get("include"), list) else [] asm = responses_api.Assembler(req, svc.model_for(req), len(ids), names, @@ -5121,6 +5133,7 @@ def main() -> int: sampling_defaults=sampling_defaults, fit_max_tokens=a.fit_max_tokens or cfg.get("fit_max_tokens") is True) svc.codex_thread_titles = cfg.get("codex_thread_titles") is True # #923: opt-in, off by default + svc.codex_compaction_cache = cfg.get("codex_compaction_cache") is True # #924: opt-in, off by default try: svc.set_aliases(cfg.get("aliases")) # #297: other names the model answers to except ValueError as e: diff --git a/serve/test_responses.py b/serve/test_responses.py index 0fafc964..64902702 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -14,9 +14,10 @@ import unittest from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve import responses # noqa: E402 from serve.frontend import ChatTemplate # noqa: E402 -from serve.responses import (ENCRYPTED_PREFIX, ResponsesError, collect, input_messages, request_tools, # noqa: E402 - template_kwargs, text_format, thread_title_events) +from serve.responses import (ENCRYPTED_PREFIX, ResponsesError, collect, input_messages, prompt_made, # noqa: E402 + prompt_tools, request_tools, template_kwargs, text_format, thread_title_events) from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 ROOT = Path(__file__).resolve().parents[1] @@ -138,6 +139,138 @@ class Parsing(unittest.TestCase): self.assertIsNone(text_format({"text": {"format": {"type": "text"}}})) +# ------------------------------------------------------------------------------------------------ Codex compaction +HISTORY = [{"role": "user", "content": "hi"}, + {"type": "function_call", "name": "exec_command", "arguments": "{}", "call_id": "c1"}, + {"type": "function_call_output", "call_id": "c1", "output": "ok"}] +COMPACT_PROMPT = "You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary." # Codex's default +OTHER_TOOLS = [{"type": "function", "name": "read_file", "description": "Reads a file.", + "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}] +A, B = ("019a-a", "019a-a"), ("019a-b", "019a-b") # (session_id, thread_id) of two root conversations + + +def codex_meta(kind, conversation=A): + """client_metadata as Codex 0.160 sends it: the turn metadata is a JSON string.""" + session, thread = conversation + return {"session_id": session, "thread_id": thread, "x-codex-turn-metadata": json.dumps( + {"session_id": session, "thread_id": thread, "request_kind": kind})} + + +def codex_request(kind, conversation=A, tools=None, last=COMPACT_PROMPT, meta=None): + """A Codex request; a compaction one is the conversation again with `tools: []` (codex-rs compact.rs). Every + conversation sends the same prompt_cache_key here: it is not what tells them apart.""" + req = {"instructions": "Be brief", "tools": tools or [], "tool_choice": "auto", "prompt_cache_key": "same", + "parallel_tool_calls": bool(tools), "input": HISTORY + ([{"role": "user", "content": last}] + if kind == "compaction" else [])} + req["client_metadata"] = codex_meta(kind, conversation) if meta is None else meta + return req + + +def tools_of(req): + """(the request's tools, the prompt's tools), as _responses_prepare gets them (the prompt then goes out).""" + tools = request_tools(req)[0] + shown = prompt_tools(req, tools) + prompt_made(req, shown) + return tools, shown + + +class CodexCompaction(unittest.TestCase): + def setUp(self): + responses._kept_prompt_tools = (None, None) + + def test_a_compaction_prompt_starts_as_its_conversations_last_prompt(self): + turn = codex_request("turn", tools=TOOLS) + before = TEMPLATE.render(input_messages(turn), tools=tools_of(turn)[1], add_generation_prompt=False) + req = codex_request("compaction") + own, shown = tools_of(req) + self.assertIsNone(own) # the request's tools: still none + self.assertEqual(shown, request_tools(turn)[0]) + self.assertTrue(TEMPLATE.render(input_messages(req), tools=shown).startswith(before)) + self.assertFalse(TEMPLATE.render(input_messages(req), tools=own).startswith(before)) # what it was + shown.clear() # the kept list is nobody's to change + self.assertEqual(tools_of(req)[1], request_tools(turn)[0]) + self.assertEqual(tools_of(req)[1], request_tools(turn)[0]) # a compaction leaves the entry as it was + + def test_another_conversation_never_gets_these_tools(self): + tools_of(codex_request("turn", A, TOOLS)) + b = tools_of(codex_request("turn", B, OTHER_TOOLS))[1] + self.assertIsNone(tools_of(codex_request("compaction", A))[1]) # one entry, B's: A reads again + self.assertEqual(tools_of(codex_request("compaction", B))[1], b) + for other in (("019a-b", "019a-sub"), # a sub-agent: the root's session, its own thread + ("019a-fork", "019a-fork")): # a fork, or an ephemeral fork (same prompt_cache_key) + self.assertIsNone(tools_of(codex_request("compaction", other))[1]) + self.assertEqual(tools_of(codex_request("compaction", B))[1], b) # and they changed nothing + tools_of(codex_request("turn", A, TOOLS)) + self.assertIsNone(tools_of(codex_request("compaction", B))[1]) # A's turn came last: B reads again + self.assertEqual(tools_of(codex_request("compaction", A))[1], request_tools({"tools": TOOLS})[0]) + + def test_requests_that_are_not_a_codex_compaction_are_rendered_as_sent(self): + tools_of(codex_request("turn", tools=TOOLS)) + self.assertEqual(tools_of({"input": "another chat"}), (None, None)) + self.assertEqual(tools_of({"input": COMPACT_PROMPT, "prompt_cache_key": "same"}), (None, None)) + self.assertEqual(tools_of(codex_request("compaction", meta={})), (None, None)) + self.assertEqual(tools_of(codex_request("compaction"))[1], request_tools({"tools": TOOLS})[0]) + self.assertEqual(tools_of(codex_request("turn")), (None, None)) # a turn of A without tools ... + self.assertIsNone(tools_of(codex_request("compaction"))[1]) # ... is what its compaction follows + + def test_the_compact_prompt_in_a_message_is_not_a_compaction(self): + tools_of(codex_request("turn", tools=TOOLS)) + quoted = {"input": HISTORY + [{"role": "user", "content": COMPACT_PROMPT}], "tools": []} + self.assertEqual(tools_of(quoted), (None, None)) # the compact prompt's words, without Codex saying so + turn = codex_request("turn", last=COMPACT_PROMPT) + turn["input"] = HISTORY + [{"role": "user", "content": "Explain this: " + COMPACT_PROMPT}] + self.assertEqual(tools_of(turn), (None, None)) # Codex says it is a turn: as sent + + def test_a_thread_title_turn_does_not_replace_the_kept_tools(self): + tools_of(codex_request("turn", tools=TOOLS)) + kept = responses._kept_prompt_tools + title = codex_request("turn", ("019a-title", "019a-title")) + meta = json.loads(title["client_metadata"]["x-codex-turn-metadata"]) + meta["thread_source"] = "thread_title" + title["client_metadata"]["x-codex-turn-metadata"] = json.dumps(meta) + prompt_made(title, None) + self.assertEqual(responses._kept_prompt_tools, kept) + self.assertEqual(tools_of(codex_request("compaction"))[1], request_tools({"tools": TOOLS})[0]) + + def test_a_custom_compact_prompt_is_a_compaction_when_codex_says_so(self): + first = tools_of(codex_request("turn", tools=TOOLS))[1] + self.assertEqual(tools_of(codex_request("compaction", last="Summarize it my way."))[1], first) + + def test_a_compaction_that_sends_tools_keeps_them(self): + tools_of(codex_request("turn", tools=TOOLS)) + own, shown = tools_of(codex_request("compaction", tools=OTHER_TOOLS)) + self.assertEqual(shown, own) + + def test_without_its_conversation_nothing_is_kept_or_used(self): + for meta in ({}, {"session_id": "019a-a", "thread_id": "019a-a"}, # only the flat keys + {"x-codex-turn-metadata": json.dumps({"request_kind": "turn"})}, + {"x-codex-turn-metadata": json.dumps({"request_kind": "turn", "session_id": "019a-a"})}, + {"x-codex-turn-metadata": json.dumps({"request_kind": "turn", "thread_id": "019a-a"})}): + tools_of(codex_request("turn", tools=TOOLS, meta=meta)) + self.assertEqual(responses._kept_prompt_tools, (None, None)) + tools_of(codex_request("turn", tools=TOOLS)) + kept = responses._kept_prompt_tools + compaction = {"x-codex-turn-metadata": json.dumps({"request_kind": "compaction"})} + self.assertEqual(tools_of(codex_request("compaction", meta=compaction)), (None, None)) + self.assertEqual(responses._kept_prompt_tools, kept) + + def test_malformed_metadata_is_no_error_and_no_reuse(self): + first = tools_of(codex_request("turn", tools=TOOLS))[1] + for meta in ("x", ["x"], {"x-codex-turn-metadata": None}, {"x-codex-turn-metadata": "{not json"}, + {"x-codex-turn-metadata": "[]"}, {"x-codex-turn-metadata": "\"compaction\""}, + {"x-codex-turn-metadata": {"request_kind": "compaction", "session_id": "019a-a", + "thread_id": "019a-a"}}, # an object: not what Codex sends + {"x-codex-turn-metadata": json.dumps({"request_kind": "compaction", "session_id": 1, + "thread_id": 1})}, + {"x-codex-turn-metadata": json.dumps({"request_kind": "compaction", "session_id": "", + "thread_id": ""})}): + self.assertEqual(tools_of(codex_request("compaction", meta=meta)), (None, None), meta) + self.assertEqual(tools_of(codex_request("compaction"))[1], first) # A's entry was not touched + odd = {"x-codex-turn-metadata": json.dumps({"request_kind": ["compaction"], "session_id": "019a-a", + "thread_id": "019a-a"})} + self.assertEqual(tools_of(codex_request("compaction", meta=odd)), (None, None)) # not a compaction: as sent + + # ------------------------------------------------------------------------------------------------ over HTTP class Server(unittest.TestCase): script = ANSWER @@ -439,5 +572,91 @@ class ThreadTitle(Server): self.assertNotIn('"title"', json.dumps(r["output"])) +class CodexCompactionOverHttp(Server): + # the compaction answer is tool calls the conversation's tools would make a namespace call and a custom call + script = [CALL, "\n\n\n\n\nhi\n" + "\n\n\n\n\n\n" + "*** Begin Patch\n\n\n"] + tools = TOOLS + [{"type": "namespace", "name": "multi_agent_v1", "description": "Agents.", "tools": [ + {"type": "function", "name": "spawn_agent", "parameters": {"type": "object", "properties": { + "message": {"type": "string"}}}}]}, {"type": "custom", "name": "apply_patch", "description": "Edit files."}] + + def setUp(self): + super().setUp() + responses._kept_prompt_tools = (None, None) + self.svc.codex_compaction_cache = True # opt-in (#924) + self.parser_tools = [] + run = self.svc.run + + def recorded(ids, thinking, tools, *rest): + self.parser_tools.append(tools) + return run(ids, thinking, tools, *rest) + self.svc.run = recorded + + def compaction(self, meta, output="before", between=None, **extra): + """Codex's turn, (`between`,) then its compaction request: (the compaction prompt, its status and response).""" + self.engine.turns, self.engine.script = 0, self.engine.scripts[0] + user = {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "what is in a.txt?"}]} + turn = {"model": "m", "instructions": "You are a coding agent.", "input": [user], "tools": self.tools, + "include": ["reasoning.encrypted_content"], "client_metadata": codex_meta("turn")} + code, r = self.post(turn) + self.assertEqual(code, 200, r) + self.first_prompt = self.tok.decode(self.engine.last_prompt) + call = r["output"][-1] + if between: + between() + code, r = self.post({**turn, "tools": [], "parallel_tool_calls": False, "client_metadata": meta, "input": [ + user, *r["output"], {"type": "function_call_output", "call_id": call["call_id"], "output": output}, + {"type": "message", "role": "user", "content": [{"type": "input_text", "text": COMPACT_PROMPT}]}], + **extra}) + return self.tok.decode(self.engine.last_prompt), code, r + + def test_the_kept_tools_shape_only_the_prompt(self): + prompt, code, r = self.compaction(codex_meta("compaction")) + self.assertEqual(code, 200, r) + self.assertTrue(prompt.startswith(self.first_prompt + CALL + "<|im_end|>")) # the cached conversation + self.assertIn("multi_agent_v1.spawn_agent", prompt[:prompt.index("<|im_end|>")]) + self.assertEqual(self.parser_tools[-1], None) # the parser gets the request's tools: none + self.assertEqual(r["tools"], []) + # the calls come back as for any request without tools: no namespace, no custom tool + outputs = [(o["type"], o["name"], o.get("namespace")) for o in r["output"]] + self.assertEqual(outputs, [("function_call", "multi_agent_v1.spawn_agent", None), + ("function_call", "apply_patch", None)]) + # the same request without Codex's metadata (upstream's behaviour): the same answer, but its prompt starts + # differently, so the engine reads it from the start + plain, code, r2 = self.compaction({}) + self.assertEqual(code, 200, r2) + self.assertFalse(plain.startswith(self.first_prompt)) + self.assertNotIn("multi_agent_v1.spawn_agent", plain[:plain.index("<|im_end|>")]) + self.assertEqual(self.parser_tools[-1], None) + self.assertEqual([(o["type"], o["name"], o.get("namespace")) for o in r2["output"]], outputs) + + def test_a_compaction_too_long_with_the_kept_tools_is_rendered_as_sent(self): + long = "before\n" * 300 # a long tool output: the turn fits, its compaction barely + plain, code, r = self.compaction({}, long, max_output_tokens=64) + self.assertEqual(code, 200, r) + fits = len(self.engine.last_prompt) + 64 + 8 # the request as sent, its output, CTX_SLACK + shown, code, r = self.compaction(codex_meta("compaction"), long, max_output_tokens=64) + self.assertGreater(len(self.engine.last_prompt) + 64 + 8, fits) # with the kept tools it would not fit + self.engine.max_context = fits + again, code, r = self.compaction(codex_meta("compaction"), long, max_output_tokens=64) + self.assertEqual(code, 200, r) # as without the kept tools, not a context error + self.assertEqual(again, plain) + self.assertEqual(self.parser_tools[-1], None) + + + def test_a_request_that_fails_leaves_the_kept_tools_as_they_were(self): + before, code, r = self.compaction(codex_meta("compaction")) + self.assertEqual(code, 200, r) + + def fails(): # B's turn is too long: its prompt never reaches the engine + code, r = self.post({"model": "m", "input": "x" * 20000, "tools": TOOLS, + "client_metadata": codex_meta("turn", B)}) + self.assertEqual((code, r["error"]["code"]), (400, "context_length_exceeded")) + again, code, r = self.compaction(codex_meta("compaction"), between=fails) + self.assertEqual(code, 200, r) + self.assertEqual(again, before) # so A's compaction still starts as A's turn + + if __name__ == "__main__": unittest.main()