Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 47,185 Bytes
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9653a0f
 
 
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b710f09
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9653a0f
 
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9653a0f
 
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60dfa87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5873600
 
 
 
 
 
 
60dfa87
 
 
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b710f09
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b710f09
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b710f09
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
"""One owned upstream episode behind a public seat API and loopback provider bridge.

Only the public listener is reachable by the agent. The episode runs in a child
process so finalization can cancel a blocked provider without leaving workers.
"""

from __future__ import annotations

import argparse
import copy
import hashlib
import json
import math
import os
import signal
import subprocess
import sys
import tempfile
import threading
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlsplit

from .provenance import (
    executor_runtime_identity,
    record_runtime_provenance,
    runtime_code_identity,
    validate_code_identity,
)

EXTERNAL_MODEL = "ci-external-seat"
TERMINAL = {"finished", "abandoned", "infrastructure_error"}
MAX_BODY = 2 * 1024 * 1024
# These are the pinned native sandbox's executable/posting handlers. Keep an
# unoffered real handler unavailable (notably the opt-in history tool), while
# retaining unknown names for native Sandbox.call's fixed-dispatch error path.
# No tool name is resolved with getattr or dispatched by the public service.
SANDBOX_TOOL_NAMES = frozenset({
    "read_file", "list_files", "edit_file", "run_tests", "send_message", "submit", "show_changes",
})


def atomic_json(path: Path, value: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile("w", dir=path.parent, delete=False) as stream:
        temporary = Path(stream.name)
        try:
            json.dump(value, stream, ensure_ascii=False, allow_nan=False)
            stream.write("\n")
            stream.flush()
            os.fsync(stream.fileno())
        except BaseException:
            temporary.unlink(missing_ok=True)
            raise
    temporary.replace(path)


class ProtocolError(ValueError):
    def __init__(self, message: str, status: int = 409):
        super().__init__(message)
        self.status = status


class UnboundedVirtualClient:
    """Keep the virtual seat wait unbounded, including native empty-retry clones.

    This wraps only the loopback client, not any real provider SDK client. A
    single original seat request may span many Pi generations and tool calls.
    """

    def __init__(self, client):
        self._delegate = client.with_options(timeout=None)

    def with_options(self, **options):
        options["timeout"] = None
        return UnboundedVirtualClient(self._delegate.with_options(**options))

    def __getattr__(self, name):
        return getattr(self._delegate, name)


def request_kind(body: dict) -> str:
    if body.get("tools"):
        return "tool"
    prompt = str((body.get("messages") or [{}])[-1].get("content", ""))
    if 'Reply with JSON only: {"answer":' in prompt or "Now reply with ONLY the JSON object" in prompt:
        return "final_answer"
    return "message"


def configure_anthropic_workspace(llm, *, replay: bool = False) -> str | None:
    """Scope an unscoped API key without changing any upstream source or model."""
    workspace = os.environ.get("ANTHROPIC_WORKSPACE_ID")
    if workspace and not replay:
        client = llm._client("anthropic")
        llm._clients["anthropic"] = client.with_options(default_headers={"anthropic-workspace-id": workspace})
    return workspace


def completed_native_refusal(audit):
    """Classify only a consumed original refusal after a trusted native finish."""
    accepted = [row for row in audit if row.get("event") == "accepted_response"]
    return bool(audit and accepted
                and audit[-1].get("event") == "terminal" and audit[-1].get("state") == "finished"
                and accepted[-1].get("stop_reason") == "refusal"
                and not any(row.get("event") == "failure" for row in audit)
                and sum(row.get("event") == "provider_request" for row in audit) == len(accepted))


def validate_native_refusal(value):
    """Only original Anthropic empty-response stop/category projection."""
    if (not isinstance(value, dict) or set(value) != {"api", "stop_reason", "category"}
            or value["api"] != "anthropic-messages" or value["stop_reason"] != "refusal"
            or value["category"] is not None and not isinstance(value["category"], str)):
        raise ProtocolError("Invalid native refusal metadata", 400)
    return copy.deepcopy(value)


def native_refusal_bridge(llm):
    """Restore original Anthropic metadata across the private virtual-seat API.

    The original _call_once still owns rendering, its one SDK request, parsing,
    and usage. Its existing compatibility echo seam exposes the SDK message;
    ContextVar scopes the reserved metadata to the exact external alias call.
    The original call_model owns no-retry/meta and original episode owns nudge.
    """
    import contextvars
    from contextlib import contextmanager

    @contextmanager
    def install():
        original_once, original_echo = llm._call_once, llm._compat_echo
        active = contextvars.ContextVar("native_refusal_alias_call", default=None)

        def echo(message, calls):
            result = original_echo(message, calls)
            bucket = active.get()
            if bucket is not None:
                value = getattr(message, "ci_native_refusal", None)
                if value is not None:
                    if bucket["metadata"] is not None:
                        raise ProtocolError("Duplicate native refusal metadata", 400)
                    bucket["metadata"] = validate_native_refusal(value)
            return result

        def once(model, *args, **kwargs):
            if model != EXTERNAL_MODEL:
                return original_once(model, *args, **kwargs)
            bucket = {"metadata": None}
            token = active.set(bucket)
            try:
                out, extra = original_once(model, *args, **kwargs)
                metadata = bucket["metadata"]
                if out["stop_reason"] == "refusal":
                    if metadata is None or out["text"] or out["tool_calls"]:
                        raise ProtocolError("Native refusal response projection differs", 400)
                    refusal = {"category": metadata["category"]}
                    out = {**out, "refusal": refusal}
                    extra = {**extra, "refusal": refusal}
                elif metadata is not None:
                    raise ProtocolError("Native refusal stop reason differs", 400)
                return out, extra
            finally:
                active.reset(token)

        llm._call_once, llm._compat_echo = once, echo
        try:
            yield
        finally:
            llm._call_once, llm._compat_echo = original_once, original_echo
    return install()


class EpisodeService:
    """State and accepted-action journal for exactly one trial."""

    def __init__(self, config: dict, evidence_dir: Path):
        self.config = copy.deepcopy(config)
        if type(config.get("native_refusal_transport", False)) is not bool:
            raise ValueError("native_refusal_transport must be an explicit boolean")
        # The original benchmark bounds rounds/tools/tokens/provider requests.
        # Its virtual seat can require many Pi calls, so impose no additional
        # whole-turn or episode deadline. Explicit fixture limits still work.
        self.config.setdefault("initial_request_timeout_sec", config.get("request_timeout_sec"))
        self.config.setdefault("request_timeout_sec", None)
        self.config.setdefault("episode_timeout_sec", None)
        self.config.setdefault("finalize_timeout_sec", None)
        if not isinstance(config.get("identity"), dict) or not config["identity"]:
            raise ValueError("A trusted task identity is required")
        if type(config.get("fixture", False)) is not bool:
            raise ValueError("fixture must be an explicit boolean")
        if config.get("execution_tape") and config.get("fixture") is not True:
            raise ValueError("execution_tape requires fixture=true")
        for key in ("initial_request_timeout_sec", "request_timeout_sec", "episode_timeout_sec", "finalize_timeout_sec"):
            value = self.config[key]
            if value is None:
                continue
            if not isinstance(value, (int, float)) or isinstance(value, bool) or not math.isfinite(value) or value <= 0:
                raise ValueError(f"{key} must be finite and positive")
        if config.get("replay_tape"):
            from .replay import CallTape
            tape = CallTape.load(Path(config["replay_tape"]))
            self.config["fixture"] = config.get("fixture", False) or tape.fixture
        if type(config.get("native_empty_tool_responses", False)) is not bool:
            raise ValueError("native_empty_tool_responses must be an explicit boolean")
        if type(config.get("native_passive_message_tools", False)) is not bool:
            raise ValueError("native_passive_message_tools must be an explicit boolean")
        self.directory = evidence_dir
        self.directory.mkdir(parents=True, exist_ok=True)
        self.condition = threading.Condition(threading.RLock())
        self.state = "starting"
        self.pending: dict | None = None
        self.accepted: dict[str, dict] = {}
        self.actions: list[dict] = []
        self.observations: list[dict] = []
        # Requests actually handed to the agent through /read (observations are recorded
        # when a request is created, before the agent reads it).
        self.delivered_request_ids: list[str] = []
        self.lifecycle: list[dict] = []
        self.transcript: dict | None = None
        self.original_reader_gate: dict | None = None
        self.private_readout_evidence: dict | None = None
        self.trusted_workspace: dict | None = None
        self.configuration = {
            "evaluated_model": os.environ.get("CI_EVALUATED_MODEL", config.get("evaluated_model", "gemini-3.8-flash")),
            "partner_models": config.get("partner_models", []),
            "protocol": config["identity"].get("protocol", "ci-harbor-v1"),
            "timeouts": {key: self.config[key] for key in (
                "initial_request_timeout_sec", "request_timeout_sec", "episode_timeout_sec", "finalize_timeout_sec",
            )},
        }
        if config.get("grading_protocol"):
            self.configuration["grading_protocol"] = config["grading_protocol"]
        if config.get("private_final_readout") is not None:
            from .private_final_answers import PROTOCOL
            if config["private_final_readout"] != {"protocol": PROTOCOL}:
                raise ValueError("Unknown private final readout protocol")
            self.configuration["final_readout_protocol"] = PROTOCOL
        if config.get("native_refusal_transport"):
            self.configuration["native_refusal_transport"] = True
        if config.get("runtime_lock_sha256"):
            self.configuration["runtime_lock_sha256"] = config["runtime_lock_sha256"]
        if config.get("public_client_sha256"):
            self.configuration["public_client_sha256"] = config["public_client_sha256"]
        integrity_policy = config.get("integrity_policy", "legacy-v1")
        if integrity_policy not in {"legacy-v1", "normalized-protected-v2"}:
            raise ValueError("Unsupported integrity policy")
        self.configuration["integrity_policy"] = integrity_policy
        # Hash the actual installed service package, not an operator version label.
        self.configuration = record_runtime_provenance(self.configuration, "service")
        self.deployment_code = copy.deepcopy(config.get("effective_code"))
        self.execution_runtime_code = None
        if self.deployment_code is not None:
            validate_code_identity(self.deployment_code)
            # Agent source/settings are common across tasks of one scaffold.
            # Optional executor/build details remain outside the grouping config.
            self.configuration["code_provenance"]["agent"] = self.deployment_code["components"]["agent"]
            if self.deployment_code["components"].get("verifier_entrypoint"):
                self.configuration["code_provenance"]["verifier_entrypoint"] = self.deployment_code["components"]["verifier_entrypoint"]
            if self.deployment_code["components"].get("execution_profile"):
                self.configuration["code_provenance"]["execution_profile"] = self.deployment_code["components"]["execution_profile"]
        distribution = config.get("runtime_distribution")
        component = (self.deployment_code or {}).get("components", {}).get("runtime_distribution")
        if distribution is not None or component is not None:
            if (not isinstance(distribution, dict) or set(distribution) != {"format", "archive_sha256"}
                    or distribution["format"] != "ci-private-runtime-tar-gzip-v1"
                    or not isinstance(distribution["archive_sha256"], str)
                    or len(distribution["archive_sha256"]) != 64
                    or any(c not in "0123456789abcdef" for c in distribution["archive_sha256"])):
                raise ValueError("Invalid compact runtime distribution")
            from .provenance import _files_identity, _hash
            validate_code_identity(component)
            if component != _files_identity({"runtime-distribution.json": _hash(distribution)}):
                raise ValueError("Runtime distribution differs from its effective code component")
            self.configuration["runtime_distribution"] = copy.deepcopy(distribution)
            self.configuration["code_provenance"]["runtime_distribution"] = copy.deepcopy(component)
        agent_configuration = config.get("agent_configuration")
        if os.environ.get("CI_AGENT_CONFIGURATION"):
            agent_configuration = json.loads(os.environ["CI_AGENT_CONFIGURATION"])
        if agent_configuration is not None:
            if not isinstance(agent_configuration, dict):
                raise ValueError("agent_configuration must be a JSON object")
            if agent_configuration.get("code_profile") is not None:
                profile = agent_configuration["code_profile"]
                validate_code_identity(profile)
                if profile["components"]["adapter"] != self.configuration["code_provenance"]["service"]:
                    raise ValueError("Declared code profile differs from actual service source")
            self.configuration["agent"] = agent_configuration
        self.worker: subprocess.Popen | None = None
        self.started = time.monotonic()
        self.closing = False
        self.cached_bridge: tuple[str, dict] | None = None
        self.worker_result = self.directory / ("worker-result-" + uuid.uuid4().hex + ".json")
        self.worker_configuration = self.worker_result.with_suffix(".configuration.json")
        self.worker_stop_lock = threading.Lock()
        self._transition("starting", "service_started")

    def _transition(self, state: str, reason: str) -> None:
        with self.condition:
            self.state = state
            self.lifecycle.append({"state": state, "reason": reason, "time": time.time()})
            atomic_json(self.directory / "lifecycle.json", {
                "state": self.state, "lifecycle": self.lifecycle,
                "observations": self.observations, "actions": self.actions,
            })
            self.condition.notify_all()

    def _terminal(self, state: str, reason: str) -> None:
        if self.state not in TERMINAL:
            self.pending = None
            self._transition(state, reason)

    def read(self, wait: float = 0) -> dict:
        if not 0 <= wait <= 30:
            raise ProtocolError("wait must be between 0 and 30", 400)
        with self.condition:
            self.condition.wait_for(lambda: self.pending is not None or self.state in TERMINAL, timeout=wait)
            if self.pending is not None and self.pending["request_id"] not in self.delivered_request_ids:
                self.delivered_request_ids.append(self.pending["request_id"])
            return {"state": self.state, "request": copy.deepcopy(self.pending)}

    def reply(self, payload: dict) -> dict:
        request_id = payload.get("request_id")
        if not isinstance(request_id, str) or not request_id:
            raise ProtocolError("request_id is required", 400)
        canonical = json.loads(json.dumps(payload, allow_nan=False))
        with self.condition:
            if request_id in self.accepted:
                previous = self.accepted[request_id]
                if canonical != previous["payload"]:
                    raise ProtocolError("Conflicting reply for an accepted request")
                return copy.deepcopy(previous["ack"])
            if self.state in TERMINAL or not self.pending or self.pending["request_id"] != request_id:
                raise ProtocolError("Stale request or no request pending")
            if payload.get("kind") != self.pending["kind"]:
                raise ProtocolError("Reply kind does not match the pending phase")
            if "native_refusal" in payload:
                if self.config.get("native_refusal_transport") is not True:
                    raise ProtocolError("Native refusal transport is not enabled", 400)
                required = {"request_id", "kind", "text", "native_refusal"}
                if payload["kind"] == "tool":
                    required.add("tool_calls")
                if set(payload) != required or payload["text"] != "" or payload.get("tool_calls", []) != []:
                    raise ProtocolError("Native refusal requires the exact empty response", 400)
                metadata = validate_native_refusal(payload["native_refusal"])
                result = {"text": "", "tool_calls": [], "native_refusal": metadata}
            elif payload["kind"] == "tool":
                calls = payload.get("tool_calls")
                if calls is None:
                    calls = [{"id": request_id + "_tool", "name": payload.get("name"), "input": payload.get("arguments")}]
                allowed = {t["function"]["name"] for t in self.pending["tools"]}
                if not isinstance(calls, list) or not calls and self.config.get("native_empty_tool_responses") is not True:
                    raise ProtocolError("Tool reply requires at least one call", 400)
                for call in calls:
                    if (not isinstance(call, dict) or not isinstance(call.get("name"), str) or not call["name"]
                            or not isinstance(call.get("input"), dict) or not isinstance(call.get("id"), str)
                            or (call["name"] in SANDBOX_TOOL_NAMES and call["name"] not in allowed)):
                        raise ProtocolError("Invalid tool call", 400)
                result = {"text": payload.get("text", ""), "tool_calls": calls}
                if not isinstance(result["text"], str):
                    raise ProtocolError("text must be a string", 400)
            elif "passive_tool_calls" in payload and self.config.get("native_passive_message_tools") is True:
                # This is response metadata from a no-tools native model call.
                # The bridge returns it to call_model; only the original caller
                # decides how to consume it. This service executes no tool.
                if (set(payload) != {"request_id", "kind", "text", "passive_tool_calls", "passive_finish_reason"}
                        or not isinstance(payload.get("text"), str)
                        or not isinstance(payload.get("passive_finish_reason"), str)
                        or payload.get("passive_finish_reason") not in {"stop", "tool_calls", "length"}):
                    raise ProtocolError("Invalid passive native response metadata", 400)
                calls = payload["passive_tool_calls"]
                if not isinstance(calls, list) or not calls:
                    raise ProtocolError("Passive native response requires nonempty tool metadata", 400)
                for call in calls:
                    if (not isinstance(call, dict) or not isinstance(call.get("id"), str) or not call["id"]
                            or not isinstance(call.get("name"), str) or not call["name"]
                            or not isinstance(call.get("input"), dict)):
                        raise ProtocolError("Invalid passive native tool metadata", 400)
                result = {"text": payload["text"], "tool_calls": copy.deepcopy(calls),
                          "passive_finish_reason": payload["passive_finish_reason"]}
            else:
                if set(payload) != {"request_id", "kind", "text"} or not isinstance(payload.get("text"), str):
                    raise ProtocolError("Reply requires request_id, kind, and text", 400)
                result = {"text": payload["text"], "tool_calls": []}
            ack = {"accepted": True, "request_id": request_id}
            self.accepted[request_id] = {"payload": canonical, "result": result, "ack": ack}
            self.actions.append({"payload": canonical, "accepted_at": time.time()})
            self.pending = None
            self._transition("processing", "reply_accepted")
            return copy.deepcopy(ack)

    def completion(self, body: dict, *, retry: bool = False) -> dict:
        if body.get("model") != EXTERNAL_MODEL or body.get("stream"):
            raise ProtocolError("Unsupported bridge model or streaming request", 400)
        messages = body.get("messages")
        if not isinstance(messages, list) or not messages or messages[0].get("role") != "system":
            raise ProtocolError("Bridge request has no system instruction", 400)
        digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
        with self.condition:
            if retry and self.cached_bridge and self.cached_bridge[0] == digest:
                return copy.deepcopy(self.cached_bridge[1])
            if self.state in TERMINAL:
                raise ProtocolError("Episode is terminal")
            if self.pending:
                raise ProtocolError("Another evaluated-seat request is already pending")
            kind = request_kind(body)
            if kind == "final_answer" and self.config.get("private_final_readout"):
                raise ProtocolError("Private final question reached the public bridge", 500)
            request_id = uuid.uuid4().hex
            self.pending = {
                "request_id": request_id, "kind": kind,
                "system": messages[0]["content"], "messages": copy.deepcopy(messages[1:]),
                "tools": copy.deepcopy(body.get("tools")),
                "max_tokens": body.get("max_tokens", body.get("max_completion_tokens")),
            }
            self.observations.append(copy.deepcopy(self.pending))
            self._transition("waiting_for_" + kind, "evaluated_request")
            self.condition.wait_for(
                lambda: request_id in self.accepted or self.state in TERMINAL,
                timeout=self.config["initial_request_timeout_sec"] if len(self.observations) == 1
                        else self.config["request_timeout_sec"],
            )
            if request_id not in self.accepted:
                self._terminal("abandoned", "unanswered_request_timeout")
                raise ProtocolError("Evaluated seat did not answer before its deadline", 410)
            result = self.accepted[request_id]["result"]
            message = {"role": "assistant", "content": result["text"]}
            if result["tool_calls"]:
                message["tool_calls"] = [{"id": call["id"], "type": "function", "function": {
                    "name": call["name"], "arguments": json.dumps(call["input"], allow_nan=False),
                }, **({"extra_content": call["extra_content"]} if call.get("extra_content") else {})} for call in result["tool_calls"]]
                if result["tool_calls"][0].get("provider_echo"):
                    echo = result["tool_calls"][0]["provider_echo"]
                    if set(echo) != {"reasoning_details"}:
                        raise ProtocolError("Unsupported provider echo metadata", 400)
                    message.update(copy.deepcopy(echo))
            if result.get("native_refusal") is not None:
                message["ci_native_refusal"] = copy.deepcopy(result["native_refusal"])
            response = {
                "id": "chatcmpl-" + request_id, "object": "chat.completion", "created": int(time.time()),
                "model": EXTERNAL_MODEL, "choices": [{"index": 0, "message": message,
                    "finish_reason": "refusal" if result.get("native_refusal") is not None else result.get("passive_finish_reason", "tool_calls" if result["tool_calls"] else "stop")}],
                "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
            }
            self.cached_bridge = digest, copy.deepcopy(response)
            return response

    def start_worker(self, internal_port: int) -> None:
        config_path = self.directory / "worker-config.json"
        worker_config = {**self.config, "bridge_url": f"http://127.0.0.1:{internal_port}/v1",
                         "worker_result": str(self.worker_result),
                         "worker_configuration": str(self.worker_configuration)}
        atomic_json(config_path, worker_config)
        environment = dict(os.environ)
        environment["CI_BRIDGE_KEY"] = "external-seat-local"
        log = (self.directory / "worker.log").open("wb")
        try:
            self.worker = subprocess.Popen(
                [sys.executable, "-m", "collab_harbor.service", "--worker", "--config", str(config_path)],
                env=environment, stdout=log, stderr=subprocess.STDOUT, start_new_session=True,
            )
        finally:
            log.close()
        threading.Thread(target=self._monitor, daemon=True).start()

    def _load_configuration(self) -> None:
        if self.worker_configuration.exists():
            configuration = json.loads(self.worker_configuration.read_text())
            if not isinstance(configuration, dict):
                raise ValueError("Worker configuration is not an object")
            self._merge_configuration(configuration)

    def _merge_configuration(self, configuration: dict) -> None:
        configuration = copy.deepcopy(configuration)
        if "execution_runtime_code" in configuration:
            self.execution_runtime_code = configuration.pop("execution_runtime_code")
        provenance = configuration.pop("code_provenance", None)
        self.configuration.update(configuration)
        if provenance:
            if provenance.pop("schema_version", None) != 1:
                raise ValueError("Invalid worker code provenance")
            for identity in provenance.values():
                validate_code_identity(identity)
            self.configuration.setdefault("code_provenance", {"schema_version": 1}).update(provenance)

    def _check_worker_result(self) -> bool:
        """Check a crash before attributing an unanswered request to the agent."""
        self._load_configuration()
        if self.worker_result.exists():
            result = json.loads(self.worker_result.read_text())
            self.private_readout_evidence = result.get("private_readout_evidence")
            if result.get("status") == "finished":
                self.transcript = result["transcript"]
                self.original_reader_gate = result.get("original_reader_gate")
                self.trusted_workspace = result.get("trusted_workspace")
                self._merge_configuration(result.get("configuration", {}))
                self._terminal("finished", "upstream_finished")
            else:
                self.original_reader_gate = result.get("reader_deferred")
                self._terminal("infrastructure_error", result.get("reason", "worker_error"))
            return True
        if self.worker is not None and self.worker.poll() is not None:
            self._terminal("infrastructure_error", "worker_exited_without_evidence")
            return True
        return False

    def _monitor(self) -> None:
        try:
            self._monitor_worker()
        except (OSError, ValueError, KeyError, TypeError):
            with self.condition:
                self._terminal("infrastructure_error", "invalid_worker_evidence")
        finally:
            if self.state != "finished":
                self.stop_worker()

    def _monitor_worker(self) -> None:
        while not self.closing:
            with self.condition:
                if self.state in TERMINAL:
                    break
                if self._check_worker_result():
                    break
                limit = self.config["episode_timeout_sec"]
                if limit is not None and time.monotonic() - self.started > limit:
                    self._terminal("abandoned" if self.pending else "infrastructure_error", "episode_timeout")
                    break
            time.sleep(0.05)

    def stop_worker(self) -> None:
        with self.worker_stop_lock:
            worker = self.worker
            if worker is not None and worker.poll() is None:
                try:
                    os.killpg(worker.pid, signal.SIGTERM)
                    worker.wait(timeout=2)
                except subprocess.TimeoutExpired:
                    os.killpg(worker.pid, signal.SIGKILL)
                    worker.wait(timeout=2)
                except ProcessLookupError:
                    pass

    def finalize(self) -> dict:
        limit = self.config["finalize_timeout_sec"]
        deadline = None if limit is None else time.monotonic() + limit
        with self.condition:
            while self.state not in TERMINAL:
                if self._check_worker_result():
                    break
                if self.pending:
                    self._terminal("abandoned", "agent_left_pending_request")
                    break
                remaining = None if deadline is None else deadline - time.monotonic()
                if remaining is not None and remaining <= 0:
                    self._terminal("infrastructure_error", "accepted_work_did_not_settle")
                    break
                self.condition.wait(timeout=0.1 if remaining is None else min(remaining, 0.1))
            self._load_configuration()
            envelope = {
                "schema_version": 1, "identity": self.config["identity"], "status": self.state,
                "configuration": self.configuration,
                "fixture": bool(self.config.get("fixture", False)), "transcript": self.transcript,
                "lifecycle": self.lifecycle, "terminal_reason": self.lifecycle[-1]["reason"],
                "partial_evidence": {"observations": self.observations, "actions": self.actions,
                                     "delivered_request_ids": self.delivered_request_ids},
                "adapter": {"bridge": "loopback OpenAI-compatible external seat", "evaluated_alias": EXTERNAL_MODEL,
                            **({"original_reader_gate": self.original_reader_gate} if self.original_reader_gate is not None else {}),
                            **({"private_final_readout": self.private_readout_evidence} if self.private_readout_evidence is not None else {}),
                            **({"trusted_workspace": self.trusted_workspace} if self.trusted_workspace is not None else {}),
                            **({"effective_task_code": self.deployment_code} if self.deployment_code is not None else {}),
                            **({"execution_runtime_code": self.execution_runtime_code}
                               if self.execution_runtime_code is not None else {})},
            }
            envelope = copy.deepcopy(envelope)
            atomic_json(self.directory / "final.json", envelope)
        self.stop_worker()
        return envelope


def handler(service: EpisodeService, *, internal: bool = False):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *_args) -> None:
            pass

        def respond(self, status: int, body: dict) -> None:
            data = json.dumps(body, ensure_ascii=False, allow_nan=False).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            try:
                self.wfile.write(data)
            except (BrokenPipeError, ConnectionResetError):
                pass

        def long_poll(self, produce) -> None:
            # Harbor's agent egress proxy drops a connection that receives no response headers within
            # ~15 s, and a valid read may wait up to 30 s: commit the 200 headers now, send the JSON body
            # when it is ready (the connection closes after it; no Content-Length).
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Connection", "close")
            self.end_headers()
            self.wfile.flush()
            try:
                body = produce()
            except (ValueError, ProtocolError) as error:
                body = {"error": str(error)}
            try:
                self.wfile.write(json.dumps(body, ensure_ascii=False, allow_nan=False).encode())
            except (BrokenPipeError, ConnectionResetError):
                pass
            self.close_connection = True

        def do_GET(self) -> None:
            parsed = urlsplit(self.path)
            try:
                if not internal and parsed.path == "/health":
                    self.respond(200, {"ok": True})
                elif not internal and parsed.path == "/read":
                    wait = float(parse_qs(parsed.query).get("wait", [0])[0])
                    if not 0 <= wait <= 30:
                        raise ProtocolError("wait must be between 0 and 30", 400)
                    self.long_poll(lambda: service.read(wait))
                else:
                    self.respond(404, {"error": "Unknown route"})
            except (ValueError, ProtocolError) as error:
                self.respond(getattr(error, "status", 400), {"error": str(error)})

        def do_POST(self) -> None:
            try:
                size = int(self.headers.get("Content-Length", "0"))
                if not 0 < size <= MAX_BODY:
                    raise ProtocolError("Invalid request size", 413)
                payload = json.loads(self.rfile.read(size))
                if not isinstance(payload, dict):
                    raise ProtocolError("Request must be a JSON object", 400)
                if internal and self.path == "/v1/chat/completions":
                    result = service.completion(payload, retry=int(self.headers.get("x-stainless-retry-count", "0")) > 0)
                elif internal and self.path == "/finalize":
                    result = service.finalize()
                elif not internal and self.path == "/reply":
                    result = service.reply(payload)
                else:
                    raise ProtocolError("Unknown route", 404)
                self.respond(200, result)
            except (ValueError, ProtocolError) as error:
                self.respond(getattr(error, "status", 400), {"error": str(error)})

    return Handler


def episode_worker(config: dict) -> None:
    """Import upstream only after registering the zero-cost loopback alias."""
    effort = json.loads(os.environ.get("HARNESS_OPENAI_EFFORT") or "{}")
    for model, level in config.get("openai_effort", {}).items():
        effort.setdefault(model, level)
    if effort:
        os.environ["HARNESS_OPENAI_EFFORT"] = json.dumps(effort)
    mapping = json.loads(os.environ.get("HARNESS_OPENAI_COMPAT") or "{}")
    mapping[EXTERNAL_MODEL] = {
        "base_url": config["bridge_url"], "api_key_env": "CI_BRIDGE_KEY",
        "model": EXTERNAL_MODEL, "price": [0, 0],
    }
    os.environ["HARNESS_OPENAI_COMPAT"] = json.dumps(mapping)
    os.environ.setdefault("HARNESS_USAGE_LOG", str(Path(config["worker_result"]).parent / "usage.jsonl"))
    os.environ.pop("HARNESS_DRY_RUN", None)
    result_path = Path(config["worker_result"])
    from contextlib import ExitStack

    resources = ExitStack()
    readout = None
    try:
        from contextlib import nullcontext

        from collab_intel.harness import episode, llm, sandbox

        from .replay import CallTape, ReplayMismatch, patch_model_calls
        from .sources import runtime_source

        source = resources.enter_context(runtime_source(Path(config["scenario_path"]), config.get("scenario_archive")))
        ep, _record, _path = episode.load_episode(source)
        workspace = configure_anthropic_workspace(llm, replay=bool(config.get("replay_tape")))
        bridge_client = llm._client("openai_compat", EXTERNAL_MODEL)
        bridge_limits = (config.get("initial_request_timeout_sec", config.get("request_timeout_sec")),
                         config.get("request_timeout_sec"))
        bridge_client.timeout = (None if None in bridge_limits else max(bridge_limits) + 15)
        bridge_client.max_retries = 1
        if None in bridge_limits:
            for key, client in list(llm._clients.items()):
                if client is bridge_client:
                    llm._clients[key] = UnboundedVirtualClient(bridge_client)
        harness_config = copy.deepcopy(llm.run_config([EXTERNAL_MODEL, *config["partner_models"]]))
        # This private transport port varies by trial. The agent's real provider
        # route belongs in agent_configuration and must still distinguish runs.
        harness_config["openai_compat"][EXTERNAL_MODEL]["base_url"] = "loopback://ci-external-seat/v1"
        runtime_configuration = {
            "harness_config": harness_config, "replay": bool(config.get("replay_tape")),
            "execution_replay_fixture": bool(config.get("execution_tape")),
            "provider_endpoints": {
                "anthropic": os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com"),
                "openai": os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1"),
            },
            "code_provenance": {"schema_version": 1, "episode_worker": runtime_code_identity(),
                                "upstream": runtime_code_identity(Path(episode.__file__).resolve().parents[2])},
        }
        if workspace:
            runtime_configuration["anthropic_workspace_id"] = workspace
        if ep.get("environment") == "sandbox" and config.get("execution_url") and not config.get("execution_tape"):
            executor = executor_runtime_identity(config["execution_url"])
            runtime_configuration["execution_runtime_code"] = executor
            expected_execution = (config.get("effective_code") or {}).get("components", {}).get("execution_profile")
            if executor["state"] == "reported" and executor["identity"] != expected_execution:
                # Unexpected actual source must not pool with the declared common
                # profile. Normally the build and runtime inventories are equal.
                runtime_configuration["code_provenance"]["executor_actual"] = executor["identity"]
        if config.get("worker_configuration"):
            atomic_json(Path(config["worker_configuration"]), runtime_configuration)
        execution_replay = None
        command_replay = None
        pytest_runner = None
        command_runner = None
        if ep.get("environment") == "sandbox":
            from .coding import RemotePytestRunner, ReplayPytestRunner
            if config.get("execution_tape"):
                if config.get("fixture") is not True:
                    raise RuntimeError("Execution replay is restricted to declared fixtures")
                execution_replay = ReplayPytestRunner(Path(config["execution_tape"]))
                pytest_runner = execution_replay
            else:
                if not config.get("execution_url"):
                    raise RuntimeError("Coding episode requires an isolated execution worker")
                pytest_runner = RemotePytestRunner(config["execution_url"])
            sandbox.PYTEST_RUNNER.set(pytest_runner)
        extended = config["identity"].get("protocol") == "ci-harbor-v2"
        execution_context, workspace_context, integrity_context = nullcontext(), nullcontext(None), nullcontext()
        if extended:
            from .checker_execution import checker_execution
            from .command_execution import RemoteCommandRunner, ReplayCommandRunner
            from .file_integrity import checker_integrity
            from .workspace_evidence import capture_workspace

            def reject_execution(*_args, **_kwargs):
                raise RuntimeError("A chat task attempted private code execution")

            if config.get("command_tape"):
                if config.get("fixture") is not True:
                    raise RuntimeError("Command replay requires a declared fixture")
                command_replay = ReplayCommandRunner(Path(config["command_tape"]))
                command_runner = command_replay
            elif config.get("execution_url") and not config.get("execution_tape"):
                command_runner = RemoteCommandRunner(config["execution_url"])
            execution_context = checker_execution(pytest_runner or reject_execution, command_runner=command_runner)
            workspace_context = capture_workspace()
            integrity_context = checker_integrity(config.get("integrity_policy", "legacy-v1"))
        if config.get("native_refusal_transport"):
            resources.enter_context(native_refusal_bridge(llm))
        tape = CallTape.load(Path(config["replay_tape"])) if config.get("replay_tape") else None
        original = llm.call_model
        dispatch = original
        if config.get("private_final_readout"):
            from .private_final_answers import PrivateFinalReadout

            readout = PrivateFinalReadout(llm, original, config)
            resources.callback(readout.close)
            dispatch = readout
            runtime_configuration["private_final_readout"] = readout.metadata
            if config.get("worker_configuration"):
                atomic_json(Path(config["worker_configuration"]), runtime_configuration)

        def delegate(request: dict, expected: dict) -> dict:
            actual = dispatch(**request)
            def comparable(calls):
                return [{"name": c["name"], "input": c["input"]} for c in calls]
            if actual["text"] != expected["text"] or comparable(actual["tool_calls"]) != comparable(expected["tool_calls"]):
                raise ReplayMismatch("External-seat transport returned a different reply")
            return expected

        aliases = {config.get("replay_model", "gemini-3.8-flash"): EXTERNAL_MODEL}
        context = patch_model_calls(tape.replayer(
            aliases=aliases, delegate=delegate, delegated_models={EXTERNAL_MODEL},
        )) if tape else patch_model_calls(dispatch) if readout else nullcontext()
        reader_gate_result = None
        reader_workspace = None
        if config.get("taking_over_reader_gate"):
            workspace_context = nullcontext(None)
        with context, execution_context, integrity_context, workspace_context as workspace_capture:
            if config.get("taking_over_reader_gate"):
                from .takeover_grader import run_live_gate
                transcript, reader_workspace, reader_gate_result = run_live_gate(episode, llm, source, config)
            elif config.get("stop_continuation"):
                from .continuation import run_original

                transcript = run_original(episode, llm, sandbox, config, source)
            else:
                transcript = episode.run_episode(
                    source, config["version"], EXTERNAL_MODEL,
                    config["partner_models"], seed=config["seed"],
                )
        if tape:
            tape.assert_consumed()
        if execution_replay:
            execution_replay.assert_consumed()
        if command_replay:
            command_replay.assert_consumed()
        atomic_json(result_path, {
            "status": "finished", "transcript": transcript,
            "configuration": runtime_configuration,
            **({"trusted_workspace": workspace_capture.bind(transcript)} if workspace_capture is not None else {}),
            **({"trusted_workspace": reader_workspace} if reader_workspace is not None else {}),
            **({"original_reader_gate": reader_gate_result} if reader_gate_result is not None else {}),
            **({"private_readout_evidence": readout.evidence()} if readout is not None else {}),
        })
    except BaseException as error:
        # Provider exception strings can contain request bodies. Keep the public
        # reason categorical; the private worker log retains the traceback.
        from .takeover_grader import recovery_evidence

        recovery = getattr(error, "reader_deferred", None) or recovery_evidence(result_path.parent)
        atomic_json(result_path, {"status": "infrastructure_error", "reason": type(error).__name__,
            **({"reader_deferred": recovery} if recovery is not None else {}),
            **({"private_readout_evidence": readout.evidence()} if readout is not None else {})})
        raise
    finally:
        resources.close()


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--config", type=Path, default=Path(os.environ.get("CI_TASK_CONFIG", "/private/task.json")))
    parser.add_argument("--worker", action="store_true")
    parser.add_argument("--public-host", default="0.0.0.0")
    parser.add_argument("--public-port", type=int, default=8000)
    parser.add_argument("--internal-port", type=int, default=8001)
    parser.add_argument("--evidence-dir", type=Path, default=Path("/evidence"))
    args = parser.parse_args(argv)
    config = json.loads(args.config.read_text())
    if args.worker:
        episode_worker(config)
        return
    service = EpisodeService(config, args.evidence_dir)
    public = ThreadingHTTPServer((args.public_host, args.public_port), handler(service))
    internal = ThreadingHTTPServer(("127.0.0.1", args.internal_port), handler(service, internal=True))
    threading.Thread(target=internal.serve_forever, daemon=True).start()
    service.start_worker(internal.server_port)

    def stop(_signum, _frame):
        with service.condition:
            service._terminal("infrastructure_error", "service_interrupted")
        service.stop_worker()
        raise SystemExit(130)

    signal.signal(signal.SIGTERM, stop)
    signal.signal(signal.SIGINT, stop)
    try:
        public.serve_forever()
    finally:
        service.closing = True
        service.stop_worker()
        public.server_close()
        internal.shutdown()
        internal.server_close()


if __name__ == "__main__":
    main()