File size: 7,988 Bytes
0e8028d
 
 
 
 
 
 
2719bf4
0e8028d
 
 
 
 
 
2719bf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8028d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
0e8028d
 
 
 
 
 
 
2719bf4
 
 
 
 
 
 
 
 
 
0e8028d
 
 
 
 
 
 
2719bf4
 
 
0e8028d
2719bf4
0e8028d
 
 
 
 
 
 
 
2719bf4
 
 
 
 
 
 
0e8028d
 
a8aea51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e8028d
 
2719bf4
 
 
0e8028d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2719bf4
0e8028d
 
 
 
2719bf4
0e8028d
2719bf4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""Explicit conversation selection; simulator state never enters this module."""

import copy
import json
from dataclasses import dataclass, field


SYSTEM = "You control one Borderland campaign. Use only public observations and legal actions. Escape is verified only by the engine. Issue exactly one tool call per decision. Use replace_notebook to preserve evidence within its displayed capacity. Blackout starts a fresh conversation with only your notebook and current public state."


def wire(value):
    return value.to_dict() if hasattr(value, "to_dict") else value


def actor_view(transition):
    data = wire(transition)
    return {key: copy.deepcopy(data[key]) for key in
            ("observation", "legal_actions", "error", "reward", "terminated",
             "truncated", "outcome", "context_reset") if key in data}


def actor_transition(transition):
    from borderland.domain import Action, ActionError, Observation, Phase, Transition

    public = actor_view(transition)
    observation = public.pop("observation")
    observation["phase"] = Phase(observation["phase"])
    actions = tuple(Action(**action) for action in public.pop("legal_actions"))
    error = public.pop("error", None)
    return Transition(Observation(**observation), actions,
                      error=None if error is None else ActionError(**error), **public)


def notebook_budget(notebook, selected_limit=None):
    field = "capacity_bytes" if "capacity_bytes" in notebook else "capacity_chars"
    capacity = notebook[field]
    return field, capacity if selected_limit is None else min(capacity, selected_limit)


def bounded_note(text, capacity, field):
    return text.encode("utf-8")[:capacity].decode("utf-8", errors="ignore") if field == "capacity_bytes" else text[:capacity]


@dataclass
class ContextSelector:
    condition: str = "full_history"
    recent_messages: int = 8
    notebook_chars: int = 768
    messages: list = field(default_factory=list)
    resets: int = 0
    _phase: int | None = None

    def __post_init__(self):
        if self.condition not in {"full_history", "recent", "bounded_notebook"}:
            raise ValueError("unknown context condition")
        if self.recent_messages < 1 or self.notebook_chars < 0:
            raise ValueError("invalid context bounds")

    def observe(self, transition):
        data = wire(transition)
        observation = data["observation"]
        phase = int(observation["phase"])
        boundary = phase == 6 and self._phase != 6
        self._phase = phase
        if boundary:
            self.messages.clear()
            self.resets += 1
        public = self._view(data)
        message = {"role": "user", "content": json.dumps(public, sort_keys=True)}
        if self.condition == "bounded_notebook":
            self.messages = [message]
        else:
            self.messages.append(message)
        return boundary

    def _view(self, transition):
        public = actor_view(transition)
        notebook = public["observation"]["notebook"]
        field, capacity = notebook_budget(notebook, self.notebook_chars)
        notebook[field] = capacity
        notebook["text"] = bounded_note(notebook["text"], capacity, field)
        if "used_bytes" in notebook:
            notebook["used_bytes"] = len(notebook["text"].encode("utf-8"))
        return public

    def assistant(self, message):
        retained = {key: copy.deepcopy(message[key]) for key in
                    ("role", "content", "reasoning_content", "tool_calls") if key in message}
        retained["role"] = "assistant"
        self.messages.append(retained)

    def tool(self, call_id, result):
        data = wire(result)
        if isinstance(data, dict) and "observation" in data:
            data = self._view(data)
        self.messages.append({"role": "tool", "tool_call_id": call_id,
                              "content": json.dumps(data, sort_keys=True)})

    def selected(self):
        selected = self.messages
        if self.condition == "recent" and len(selected) > self.recent_messages:
            start = len(selected) - self.recent_messages
            while start < len(selected) and selected[start]["role"] == "tool":
                start += 1
            selected = selected[start:]
        if self.condition == "bounded_notebook":
            memory = " Each decision receives only the current public state and saved notebook. Earlier observations and reasoning are unavailable. Save needed evidence before taking an action that replaces it."
        elif self.condition == "recent":
            memory = f" Only the most recent {self.recent_messages} conversation messages are retained before Blackout. Save evidence that may leave that window."
        else:
            memory = " Public conversation history is retained until the Blackout boundary."
        return [{"role": "system", "content": SYSTEM + memory}] + copy.deepcopy(selected)


class CampaignContext(ContextSelector):
    def __init__(self, records=()):
        super().__init__("full_history", notebook_chars=768)
        self.records = []
        self._record_bytes = set()
        for record in records:
            self._expose(record)

    def _expose(self, record):
        encoded = json.dumps(record, sort_keys=True, separators=(",", ":"))
        if encoded not in self._record_bytes:
            self._record_bytes.add(encoded)
            self.records.append(copy.deepcopy(record))

    def observe(self, transition):
        data = wire(transition)
        phase = int(data["observation"]["phase"])
        if phase == 6 and self._phase != 6:
            self.records.clear()
            self._record_bytes.clear()
        if phase == 3 and not data.get("error"):
            for record in data["observation"]["board"].get("records", []):
                self._expose(record)
        return super().observe(transition)

    def current_packet(self):
        current = copy.deepcopy(next(message for message in reversed(self.messages)
                                     if message["role"] == "user"))
        value = json.loads(current["content"])
        value["publicArchiveIndex"] = copy.deepcopy(self.records)
        current["content"] = json.dumps(value, sort_keys=True)
        return current


def scripted_notebook(observation, previous="", capacity=768):
    """Scripted compression of exposed public board records, explicitly not an LLM."""
    field, capacity = notebook_budget(observation["notebook"], capacity)
    def fits(text):
        return bounded_note(text, capacity, field) == text
    board = observation.get("board", {})
    try:
        facts = json.loads(previous) if previous.startswith("{") else {}
        if not isinstance(facts, dict):
            facts = {}
    except ValueError:
        facts = {}
    for key in ("live_sensor", "current_record", "current_claim", "record", "claim", "checks", "discovered_edges"):
        if board.get(key) is not None:
            facts[key] = board[key]
    if board.get("live_sensor") is not None and "latch" in board:
        facts["sensor_latch"] = board["latch"]
        facts["experimental_bus"] = ("west", "east")[board["live_sensor"] ^ (board["latch"] & 1)]
    for record in board.get("records", []):
        if record.get("authenticated"):
            records = facts.setdefault("authenticated_records", {})
            previous_record = records.get(record.get("subject"))
            if previous_record is None or record.get("issued_at", 0) > previous_record.get("issued_at", 0):
                records[record["subject"]] = record
    encoded = json.dumps(facts, sort_keys=True, separators=(",", ":"))
    if fits(encoded):
        return encoded
    for key in ("discovered_edges", "checks", "current_claim", "current_record", "claim", "record"):
        facts.pop(key, None)
        encoded = json.dumps(facts, sort_keys=True, separators=(",", ":"))
        if fits(encoded):
            return encoded
    return encoded if fits(encoded) else ""