File size: 12,239 Bytes
1794757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
from __future__ import annotations

import json

import httpx

from trenches_env.env import FogOfWarDiplomacyEnv
from trenches_env.models import ExternalSignal
from trenches_env.provider_runtime import ProviderDecisionRuntime
from trenches_env.source_ingestion import SourceHarvester


def test_configured_provider_runtime_drives_entity_action(monkeypatch) -> None:
    monkeypatch.setenv("TRENCHES_MODEL_PROVIDER_US", "openai")
    monkeypatch.setenv("TRENCHES_MODEL_NAME_US", "gpt-4.1")
    monkeypatch.setenv("TRENCHES_MODEL_API_KEY_ENV_US", "OPENAI_API_KEY")
    monkeypatch.setenv("OPENAI_API_KEY", "test-key")

    def handler(request: httpx.Request) -> httpx.Response:
        assert request.url.path.endswith("/chat/completions")
        payload = json.loads(request.content.decode("utf-8"))
        assert payload["model"] == "gpt-4.1"
        assert payload["tool_choice"]["function"]["name"] == "emit_action"
        return httpx.Response(
            200,
            json={
                "choices": [
                    {
                        "message": {
                            "tool_calls": [
                                {
                                    "function": {
                                        "name": "emit_action",
                                        "arguments": json.dumps(
                                            {
                                                "type": "negotiate",
                                                "target": "gulf",
                                                "summary": "Negotiate deconfliction around the shipping corridor.",
                                            }
                                        ),
                                    }
                                }
                            ]
                        }
                    }
                ]
            },
        )

    runtime = ProviderDecisionRuntime(client=httpx.Client(transport=httpx.MockTransport(handler)))
    env = FogOfWarDiplomacyEnv(
        source_harvester=SourceHarvester(auto_start=False),
        provider_runtime=runtime,
    )
    session = env.create_session(seed=7)

    actions = env.resolve_policy_actions(
        session,
        [
            ExternalSignal(
                source="test-feed",
                headline="Shipping risk rises near Hormuz.",
                region="gulf",
                tags=["shipping", "oil"],
                severity=0.4,
            )
        ],
        agent_ids=["us"],
    )

    assert actions["us"].type == "negotiate"
    assert actions["us"].target == "gulf"
    assert actions["us"].metadata["mode"] == "provider_inference"
    assert actions["us"].metadata["provider"] == "openai"


def test_invalid_provider_output_falls_back_to_heuristic_policy(monkeypatch) -> None:
    monkeypatch.setenv("TRENCHES_MODEL_PROVIDER_US", "openai")
    monkeypatch.setenv("TRENCHES_MODEL_NAME_US", "gpt-4.1")
    monkeypatch.setenv("TRENCHES_MODEL_API_KEY_ENV_US", "OPENAI_API_KEY")
    monkeypatch.setenv("OPENAI_API_KEY", "test-key")

    def handler(_: httpx.Request) -> httpx.Response:
        return httpx.Response(
            200,
            json={
                "choices": [
                    {
                        "message": {
                            "tool_calls": [
                                {
                                    "function": {
                                        "name": "emit_action",
                                        "arguments": json.dumps(
                                            {
                                                "type": "oversight_review",
                                                "summary": "Illegal action for US runtime.",
                                            }
                                        ),
                                    }
                                }
                            ]
                        }
                    }
                ]
            },
        )

    runtime = ProviderDecisionRuntime(client=httpx.Client(transport=httpx.MockTransport(handler)))
    env = FogOfWarDiplomacyEnv(
        source_harvester=SourceHarvester(auto_start=False),
        provider_runtime=runtime,
    )
    session = env.create_session(seed=7)

    actions = env.resolve_policy_actions(
        session,
        [
            ExternalSignal(
                source="test-feed",
                headline="Shipping risk rises near Hormuz.",
                region="gulf",
                tags=["shipping", "oil"],
                severity=0.4,
            )
        ],
        agent_ids=["us"],
    )

    assert actions["us"].type in {"defend", "negotiate", "intel_query", "hold", "mobilize", "sanction", "strike", "deceive"}
    assert actions["us"].metadata["mode"] == "heuristic_fallback"
    assert "provider_error" in actions["us"].metadata


def test_provider_runtime_retries_transient_failure_and_records_diagnostics(monkeypatch) -> None:
    monkeypatch.setenv("TRENCHES_MODEL_PROVIDER_US", "openai")
    monkeypatch.setenv("TRENCHES_MODEL_NAME_US", "gpt-4.1")
    monkeypatch.setenv("TRENCHES_MODEL_API_KEY_ENV_US", "OPENAI_API_KEY")
    monkeypatch.setenv("OPENAI_API_KEY", "test-key")

    attempts = {"count": 0}

    def handler(_: httpx.Request) -> httpx.Response:
        attempts["count"] += 1
        if attempts["count"] == 1:
            return httpx.Response(503, json={"error": "upstream overloaded"})
        return httpx.Response(
            200,
            json={
                "choices": [
                    {
                        "message": {
                            "tool_calls": [
                                {
                                    "function": {
                                        "name": "emit_action",
                                        "arguments": json.dumps(
                                            {
                                                "type": "defend",
                                                "target": "us",
                                                "summary": "Defend shipping lanes after transient provider recovery.",
                                            }
                                        ),
                                    }
                                }
                            ]
                        }
                    }
                ]
            },
        )

    runtime = ProviderDecisionRuntime(client=httpx.Client(transport=httpx.MockTransport(handler)), max_attempts=2)
    env = FogOfWarDiplomacyEnv(
        source_harvester=SourceHarvester(auto_start=False),
        provider_runtime=runtime,
    )
    session = env.create_session(seed=7)

    actions = env.resolve_policy_actions(
        session,
        [
            ExternalSignal(
                source="test-feed",
                headline="Shipping risk rises near Hormuz.",
                region="gulf",
                tags=["shipping", "oil"],
                severity=0.4,
            )
        ],
        agent_ids=["us"],
    )

    diagnostics = runtime.diagnostics(session.model_bindings)
    us_diagnostics = next(entry for entry in diagnostics if entry.agent_id == "us")

    assert attempts["count"] == 2
    assert actions["us"].type == "defend"
    assert actions["us"].metadata["provider_attempts"] == 2
    assert us_diagnostics.status == "healthy"
    assert us_diagnostics.request_count == 1
    assert us_diagnostics.success_count == 1
    assert us_diagnostics.error_count == 0
    assert us_diagnostics.consecutive_failures == 0
    assert us_diagnostics.last_success_at is not None
    assert us_diagnostics.last_error is None


def test_provider_runtime_diagnostics_capture_terminal_failure(monkeypatch) -> None:
    monkeypatch.setenv("TRENCHES_MODEL_PROVIDER_US", "openai")
    monkeypatch.setenv("TRENCHES_MODEL_NAME_US", "gpt-4.1")
    monkeypatch.setenv("TRENCHES_MODEL_API_KEY_ENV_US", "OPENAI_API_KEY")
    monkeypatch.setenv("OPENAI_API_KEY", "test-key")

    def handler(_: httpx.Request) -> httpx.Response:
        return httpx.Response(503, json={"error": "upstream overloaded"})

    runtime = ProviderDecisionRuntime(client=httpx.Client(transport=httpx.MockTransport(handler)), max_attempts=2)
    env = FogOfWarDiplomacyEnv(
        source_harvester=SourceHarvester(auto_start=False),
        provider_runtime=runtime,
    )
    session = env.create_session(seed=7)

    actions = env.resolve_policy_actions(
        session,
        [
            ExternalSignal(
                source="test-feed",
                headline="Shipping risk rises near Hormuz.",
                region="gulf",
                tags=["shipping", "oil"],
                severity=0.4,
            )
        ],
        agent_ids=["us"],
    )

    diagnostics = runtime.diagnostics(session.model_bindings)
    us_diagnostics = next(entry for entry in diagnostics if entry.agent_id == "us")

    assert actions["us"].metadata["mode"] == "heuristic_fallback"
    assert "provider returned HTTP 503" in actions["us"].metadata["provider_error"]
    assert us_diagnostics.status == "degraded"
    assert us_diagnostics.request_count == 1
    assert us_diagnostics.success_count == 0
    assert us_diagnostics.error_count == 1
    assert us_diagnostics.consecutive_failures == 1
    assert us_diagnostics.last_error is not None
    assert "provider returned HTTP 503" in us_diagnostics.last_error
    assert us_diagnostics.last_error_at is not None


def test_huggingface_provider_uses_router_endpoint_and_hf_token(monkeypatch) -> None:
    monkeypatch.setenv("TRENCHES_MODEL_PROVIDER_US", "huggingface")
    monkeypatch.setenv("TRENCHES_MODEL_NAME_US", "openai/gpt-oss-120b")
    monkeypatch.setenv("HF_TOKEN", "hf-test-token")
    monkeypatch.delenv("TRENCHES_MODEL_API_KEY_ENV_US", raising=False)
    monkeypatch.delenv("TRENCHES_HF_ROUTING_POLICY", raising=False)

    def handler(request: httpx.Request) -> httpx.Response:
        assert request.url.host == "router.huggingface.co"
        assert request.url.path.endswith("/chat/completions")
        assert request.headers["Authorization"] == "Bearer hf-test-token"
        payload = json.loads(request.content.decode("utf-8"))
        assert payload["model"] == "openai/gpt-oss-120b:fastest"
        assert payload["tool_choice"]["function"]["name"] == "emit_action"
        return httpx.Response(
            200,
            json={
                "choices": [
                    {
                        "message": {
                            "tool_calls": [
                                {
                                    "function": {
                                        "name": "emit_action",
                                        "arguments": json.dumps(
                                            {
                                                "type": "intel_query",
                                                "summary": "Query more shipping-route intelligence before changing posture.",
                                            }
                                        ),
                                    }
                                }
                            ]
                        }
                    }
                ]
            },
        )

    runtime = ProviderDecisionRuntime(client=httpx.Client(transport=httpx.MockTransport(handler)))
    env = FogOfWarDiplomacyEnv(
        source_harvester=SourceHarvester(auto_start=False),
        provider_runtime=runtime,
    )
    session = env.create_session(seed=7)

    actions = env.resolve_policy_actions(
        session,
        [
            ExternalSignal(
                source="test-feed",
                headline="Shipping risk rises near Hormuz.",
                region="gulf",
                tags=["shipping", "oil"],
                severity=0.4,
            )
        ],
        agent_ids=["us"],
    )

    assert session.model_bindings["us"].provider == "huggingface"
    assert session.model_bindings["us"].api_key_env == "HF_TOKEN"
    assert actions["us"].type == "intel_query"
    assert actions["us"].metadata["provider"] == "huggingface"