Skip to content

Model backends#

A backend is how an agent talks to a model. It is a configuration choice: the graph and the science do not change with it. See Use a different model or backend for choosing one, and Installation for what each needs.

The adapters below are exported for direct use and for subclassing; a normal run selects one by name from config.yaml and never touches these classes.

adda.ClaudeAdapter #

Wraps claude-agent-sdk; runs one agent turn and returns assistant text.

The SDK handles its own tool-execution loop (Bash, Read, Write, Edit). This adapter converts a list of LangChain-style message dicts to the SDK format, runs the query, and assembles the final text response.

Parameters:

Name Type Description Default
model str

Claude model identifier.

required
system_prompt str

System prompt for the agent.

required
study_dir Path or None

Working directory passed to the SDK as cwd.

None
native_tools list[str]

Tool names to enable (e.g. ["Bash", "Read", "Write"]).

None
closure_tools dict[str, callable] or None

Extra Python callables exposed to the model as MCP tools.

None
Source code in src/adda/_src/backends/claude.py
 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
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
class ClaudeAdapter:
    """Wraps claude-agent-sdk; runs one agent turn and returns assistant text.

    The SDK handles its own tool-execution loop (Bash, Read, Write, Edit).
    This adapter converts a list of LangChain-style message dicts to the SDK
    format, runs the query, and assembles the final text response.

    Parameters
    ----------
    model : str
        Claude model identifier.
    system_prompt : str
        System prompt for the agent.
    study_dir : Path or None
        Working directory passed to the SDK as ``cwd``.
    native_tools : list[str]
        Tool names to enable (e.g. ``["Bash", "Read", "Write"]``).
    closure_tools : dict[str, callable] or None
        Extra Python callables exposed to the model as MCP tools.
    """

    # CLI tools the Claude SDK executes natively. A node's other declared tools
    # are injected as Python closures (MCP), not passed here.
    #: This backend has its own default system prompt that a node may keep.
    HAS_BASE_PROMPT = True
    base_prompt: str | None = None
    NATIVE_TOOLS = frozenset({
        "Bash", "Edit", "Read", "Write", "Glob", "Grep",
        # Bash's own SDK companions: poll a backgrounded shell / kill it. These
        # are SDK built-ins we previously omitted, so an agent that got a
        # backgroundTaskId (from auto-background on timeout) had no tool to act
        # on it. Granting them by declaration closes that awareness gap.
        "BashOutput", "KillShell",
        "Task", "WebFetch", "WebSearch",
    })

    @classmethod
    def select_native_tools(cls, agent_tools) -> list[str]:
        """Pick which of an agent's declared tools are native SDK CLI tools.

        Mirror of OpenAICompatibleAdapter.select_native_tools so the runtime
        can choose native tools generically for any backend (forward-compatible
        dispatch)."""
        picked = [t for t in agent_tools if t in cls.NATIVE_TOOLS]
        if DEFAULT_TOOLS in agent_tools:
            picked.append(DEFAULT_TOOLS)
        return picked

    def __init__(
        self,
        model: str,
        system_prompt: str,
        study_dir: Path | None = None,
        native_tools: list[str] | None = None,
        closure_tools: dict[str, Any] | None = None,
        extra_mcp_servers: dict | None = None,
        extra_allowed_tools: list[str] | None = None,
        persistent: bool = False,
        max_history_pairs: int = 5,
    ) -> None:
        self.model = model
        self.system_prompt = system_prompt
        self.study_dir = Path(study_dir) if study_dir else None
        # "Default" is a marker, not a tool name: the node takes the CLI's
        # whole default built-in set (see node_tools.py).
        self.use_default_tools: bool = DEFAULT_TOOLS in (native_tools or [])
        self.native_tools = [t for t in (native_tools or []) if t != DEFAULT_TOOLS]
        # Called once per init record with the tool names the CLI really
        # loaded; set by the runtime, never required.
        self.on_init_tools: Any = None
        self.closure_tools = dict(closure_tools or {})
        self.extra_mcp_servers: dict = dict(extra_mcp_servers or {})
        self.extra_allowed_tools: list[str] = list(extra_allowed_tools or [])
        # persistent and max_history_pairs kept for backward compatibility with
        # Agent subclasses and tests that read these attributes; not used
        # in the core invocation path (history is demand-driven via DelegationLog).
        self.persistent: bool = persistent
        self.max_history_pairs: int = max_history_pairs
        # Serialises calls on THIS adapter object; each delegation runs on its own copy().
        self._lock: threading.Lock = threading.Lock()
        # Set by an orchestrating node; when truthy, the generator is closed after
        # the next AssistantMessage so the session ends on a routing decision.
        self.route_watcher: Any = None
        # Populated after each ainvoke() with token counts from ResultMessage.
        self.last_usage: dict = {}
        self._attempt_usages: list[dict] | None = None
        # Populated after each ainvoke() with the CLI session id (spec 12
        # item 3: session-resumption plumbing, capture-only for now) --
        # ResultMessage's when the turn completed normally, else whatever
        # the last AssistantMessage carried.
        self.last_session_id: str | None = None
        self._session_id: str | None = None
        self._background_watch: Any = None
        self._session_token: str | None = None

    def _system_prompt_option(self):
        """What the CLI receives: the text alone (it REPLACES Claude Code's
        prompt), or, for a node with ``base_prompt: Default``, a preset that
        keeps Claude Code's prompt and appends the text."""
        text = self._render_system_prompt()
        if self.base_prompt == DEFAULT_PROMPT:
            return {"type": "preset", "preset": "claude_code",
                    **({"append": text} if text.strip() else {})}
        return text

    def _render_system_prompt(self) -> str:
        """The system prompt exactly as the model sees it: base prompt plus
        the ``<tools>`` catalog, with every tool the prose names rewritten to
        the qualified name the SDK exposes (catalog and prose must agree)."""
        from ..prompts.tool_catalog import system_prompt_with_catalog
        qualified = _qualify_closure_names(self.closure_tools)
        rendered = system_prompt_with_catalog(
            self.system_prompt, qualified, builtins_held=self.use_default_tools,
            # the closures by their own names: the catalog gets them qualified
            native=frozenset(self.closure_tools) | frozenset(
                self.NATIVE_TOOLS if self.use_default_tools
                else self.native_tools))
        return _qualify_prose(rendered, self.closure_tools)

    @property
    def plain_session(self) -> bool:
        """True when this adapter runs plain Claude Code: the CLI's own tools
        and system prompt, nothing of adda's. Its session gets the statement
        as typed and later turns resume it (``_turn_prompt``)."""
        return self.use_default_tools and self.base_prompt == DEFAULT_PROMPT

    @staticmethod
    def _record_turn_prompt(prompt: str, resume: str | None) -> None:
        """Every agent's input is on record: the turn's prompt opens its
        transcript (the stream records only what comes back)."""
        import hashlib

        from .base import append_transcript
        append_transcript({
            "type": "user", "text": prompt,
            "sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
            "resume": resume})

    def _turn_prompt(self, messages: list[dict]) -> tuple[str, str | None]:
        """``(prompt, resume)`` for this turn.

        An adda node gets the whole conversation flattened to one string,
        each turn labelled ``Human:`` / ``Assistant:``. A plain session gets
        its first user message byte for byte, and every later turn only the
        user text that follows the last assistant message, in the session
        this adapter already opened (``resume``).
        """
        if not self.plain_session:
            return _format_messages_as_prompt(messages), None
        texts = [_message_text(m) for m in messages]
        roles = [m.get("role", "user") for m in messages]
        users = [t for t, r in zip(texts, roles, strict=True) if r in ("human", "user")]
        if self._session_id is None:
            return users[0], None
        last_ai = max((i for i, r in enumerate(roles)
                       if r in ("ai", "assistant")), default=-1)
        return "\n\n".join(
            t for t, r in zip(texts[last_ai + 1:], roles[last_ai + 1:], strict=True)
            if r in ("human", "user")), self._session_id

    def _compute_allowed_tools(self, qualified_mcp_tools) -> list[str]:
        """All allowed tool names, ALWAYS as a list (never None).

        The SDK does ``list(options.allowed_tools)`` when building its command,
        which raises ``TypeError`` on ``None`` — so a tool-less agent (e.g. the
        one-shot problem-statement reviewer) must still get ``[]`` here, not
        ``None``. An empty list correctly means "no tools allowed".
        """
        return (
            list(qualified_mcp_tools)
            + list(self.native_tools)
            + list(self.extra_allowed_tools)
        )

    def copy(self) -> ClaudeAdapter:
        """An independent adapter for ONE delegation.

        Shares configuration; owns everything a delegation mutates: its own
        ``closure_tools`` (dispatch binds ReportEvals / Write / FollowUp to
        that delegation's id), its own ``_lock`` and its own per-call
        ``last_*`` state. Same-role delegations therefore run concurrently
        instead of queueing behind one shared lock.
        """
        import copy as _copy
        twin = _copy.copy(self)
        twin.closure_tools = dict(self.closure_tools)
        twin.native_tools = list(self.native_tools)
        twin.extra_allowed_tools = list(self.extra_allowed_tools)
        twin.extra_mcp_servers = dict(self.extra_mcp_servers)
        twin._lock = threading.Lock()
        twin.last_usage = {}
        twin._attempt_usages = None
        twin.last_session_id = None
        twin._session_id = None
        # The route watcher ends the NODE's own turn after Done/Handoff. A
        # copy runs a delegation or a wake, never that turn; watching the
        # node's route there broke every wake after a handoff at its first
        # message (empty reply, no error).
        twin.route_watcher = None
        return twin

    def interrupt(self) -> list[dict]:
        """SIGINT the work a Bash-tool shell of this adapter's CLI session
        runs, found by its session token; never the CLI itself nor an MCP
        server, so the turn goes on. Safe from any thread."""
        return _interrupt.interrupt_session(
            self._session_token, self.extra_mcp_servers)

    async def ainvoke(

        self, messages: list[dict], *, idle_timeout: float | None = None,
        resume: str | None = None,
    ) -> str:
        """Run one agent turn asynchronously; return assembled text.

        ``idle_timeout`` overrides the run-wide ``llm_stream_idle_timeout`` for
        THIS call only — used by short advisory side-calls (e.g. the verdict
        validator) that must not inherit a real agent turn's generous window.

        ``resume`` (spec 12 item 3): a CLI session id to resume rather than
        starting fresh -- ``messages`` then carries only the NEW turn (the
        prior conversation is loaded from the resumed session itself, not
        replayed here). ``fork_session=False`` always, so this continues the
        SAME session rather than branching a copy of it.
        """
        self._session_token = _interrupt.new_token()
        self._attempt_session_id = None
        _require_sdk()
        from claude_agent_sdk import (
            AssistantMessage,
            ClaudeAgentOptions,
            ResultMessage,
            SdkMcpTool,
            StreamEvent,
            SystemMessage,
            TextBlock,
            ToolUseBlock,
            UserMessage,
            create_sdk_mcp_server,
            query,
        )

        from ..prompts.tool_catalog import tool_summary

        # Build MCP server from closure_tools if any
        mcp_servers: dict = {}
        qualified_mcp_tools: list[str] = []
        if self.closure_tools:
            server_name = _CLOSURE_MCP_SERVER
            sdk_tools: list[Any] = []
            for tool_name, fn in self.closure_tools.items():
                schema = _infer_schema_from_callable(fn)

                async def _handler(args: dict, bound_fn: Any = fn) -> dict:
                    try:
                        result = bound_fn(**args)
                    except Exception as exc:
                        return {
                            "content": [
                                {"type": "text", "text": f"ERROR: {exc}"}
                            ],
                            "is_error": True,
                        }
                    return {
                        "content": [
                            {
                                "type": "text",
                                "text": (
                                    str(result) if result is not None else ""
                                ),
                            }
                        ]
                    }

                sdk_tools.append(
                    SdkMcpTool(
                        name=tool_name,
                        description=tool_summary(fn, tool_name),
                        input_schema=schema,
                        handler=_handler,
                    )
                )

            mcp_cfg = create_sdk_mcp_server(
                name=server_name, tools=sdk_tools or None
            )
            mcp_servers = {server_name: mcp_cfg}
            qualified_mcp_tools = list(_qualify_closure_names(self.closure_tools))

        # Plain Claude Code (Default tools + Default prompt): adda hands the
        # CLI nothing — no closure server, no MCP server, no hook.
        _plain = self.use_default_tools and self.base_prompt == DEFAULT_PROMPT
        if _plain:
            mcp_servers, qualified_mcp_tools = {}, []

        # Merge external stdio MCP servers declared by the Agent subclass.
        if self.extra_mcp_servers and not _plain:
            mcp_servers.update(self.extra_mcp_servers)

        _base_disallowed = ["WebSearch", "WebFetch", "Task", "ExitPlanMode"]
        # Under permission_mode="bypassPermissions" the allowed_tools allowlist
        # is NOT enforced — disallowed_tools is the only thing that binds. So a
        # native tool the agent never declared (e.g. Bash/Write for a read-only
        # reviewer) would otherwise be silently usable. Disallow every native
        # tool this agent did not declare, making its declared toolset binding.
        _ungranted_native = [
            t for t in self.NATIVE_TOOLS if t not in self.native_tools
        ]
        if self.use_default_tools:
            # Default has no floor. Only computed additions stay: a built-in
            # that shares its bare name with a closure this node declares
            # (the sandboxed Write replaces the native one) must not run.
            _base_disallowed, _ungranted_native = [], list(self.closure_tools)
        _effective_disallowed = [
            t for t in dict.fromkeys([*_base_disallowed, *_ungranted_native])
            if t not in self.extra_allowed_tools
        ]
        # The run's own ban (config.yaml runtime.disallowed_tools) binds
        # every agent, Default and plain ones too, and no grant lifts it.
        from ..runtime.settings import get_list as _get_list
        _effective_disallowed = list(dict.fromkeys(
            [*_effective_disallowed, *_get_list("disallowed_tools", [])]))

        # Non-blocking raw-oracle nudge: a PostToolUse hook that injects a
        # reminder (capped per delegation = per ainvoke) when a Bash/Write
        # call reaches the oracle directly instead of via get_evaluator().
        # Best-effort — if the SDK hook API is unavailable, run without it.
        _hooks = None
        try:
            if _plain:
                raise RuntimeError("plain Claude Code runs without adda hooks")
            from claude_agent_sdk import HookMatcher

            from ..runtime import features
            from .base import (
                OracleNudgeBudget,
                get_delegation_id,
                get_run_config_path,
                oracle_registered,
            )
            # Silent until an oracle is registered: pre-registration work (the
            # datagenerator wrapping/validating its raw source) has no
            # get_evaluator() to use, so nudging it is a false positive.
            # The nudge is a monitor intervention; the store notices the same
            # hook carries are store integrity and stay on in every arm.
            _nudge = OracleNudgeBudget(
                enabled=oracle_registered()
                and features.enabled("science_monitor"))
            # Expose on the adapter so the runtime can drain + log its
            # firings as direct evidence (see _record_intervention).
            _nudge.run_config_path = get_run_config_path()
            self._oracle_nudge = _nudge

            # The hook may run on another thread, so bind the delegation and
            # the run's debug dir now, while this thread still holds them.
            from ..infra import pending_notices as _pn
            _rc = get_run_config_path()
            _pn_dir = Path(_rc).parent if _rc else None
            _pn_did = get_delegation_id()
            _pn_key = _pn_did or getattr(self, "notice_key", None)

            # What a hook adds to the agent's context is the agent's input
            # too, so it goes on record beside the tool result it follows
            # (the CLI's own stream does not carry it).
            from .base import append_transcript, get_transcript_sink
            _hook_sink = get_transcript_sink()

            # The entry node's own Bash children are capped as "entry"; its
            # CLI only reports their exit code, so a watcher kill during the
            # call is named in a note after it (one wording: kill_reason).
            import time as _time

            from ..infra import watchdog_cleanup as _wc
            _bash_started: dict = {}

            def _entry_kill_note(input_data, tool_use_id):
                start = _bash_started.pop(tool_use_id, None)
                if (_pn_did is not None or start is None
                        or input_data.get("tool_name") != "Bash"):
                    return None
                reason = _wc.kill_reason_for_group(_wc.ENTRY, since=start)
                return _wc.kill_line(reason) if reason else None
            def _pattern_kill_note(input_data):
                """The advisory note after a Bash pkill/pgrep -f, for a
                session that holds KillOwnJobs."""
                from ..nodes.tools.routing.processes import (
                    PATTERN_KILL_NOTE,
                    is_pattern_kill,
                )
                if input_data.get("tool_name") != "Bash" or "KillOwnJobs" \
                        not in (getattr(self, "closure_tools", None) or {}):
                    return None
                cmd = (input_data.get("tool_input") or {}).get("command", "")
                return PATTERN_KILL_NOTE if is_pattern_kill(cmd) else None

            def _record_hook(event, tool_use_id, input_data, text):
                append_transcript({
                    "type": "hook_context", "event": event,
                    "tool_use_id": tool_use_id,
                    "tool": (input_data or {}).get("tool_name"),
                    "text": text}, path=_hook_sink)

            async def _oracle_hook(input_data, tool_use_id, context):
                msg = _pn.post_tool_context(
                    _nudge,
                    input_data.get("tool_name", ""),
                    input_data.get("tool_input") or {},
                    _pn_dir, _pn_key,
                )
                for hint in (
                        _background_wait_hint(
                            input_data.get("tool_response"),
                            getattr(self, "_cli_tools", None)),
                        _background_task_note(
                            input_data.get("tool_response"))):
                    if hint:
                        msg = f"{msg}\n\n{hint}" if msg else hint
                kill = _entry_kill_note(input_data, tool_use_id)
                if kill:
                    msg = f"{msg}\n\n{kill}" if msg else kill
                note = _pattern_kill_note(input_data)
                if note:
                    msg = f"{msg}\n\n{note}" if msg else note
                if not msg:
                    return {}
                msg = _qualify_prose(msg, self.closure_tools)
                _record_hook("PostToolUse", tool_use_id, input_data, msg)
                return {
                    "hookSpecificOutput": {
                        "hookEventName": "PostToolUse",
                        "additionalContext": msg,
                    }
                }

            async def _failure_hook(input_data, tool_use_id, context):
                # A call the CLI refused (its own validation, e.g. the
                # foreground-sleep block) ends here, not in PostToolUse.
                hint = _background_wait_hint(
                    input_data.get("error"),
                    getattr(self, "_cli_tools", None))
                kill = _entry_kill_note(input_data, tool_use_id)
                if kill:
                    hint = f"{hint}\n\n{kill}" if hint else kill
                note = _pattern_kill_note(input_data)
                if note:
                    hint = f"{hint}\n\n{note}" if hint else note
                if not hint:
                    return {}
                hint = _qualify_prose(hint, self.closure_tools)
                _record_hook("PostToolUseFailure", tool_use_id, input_data,
                             hint)
                return {
                    "hookSpecificOutput": {
                        "hookEventName": "PostToolUseFailure",
                        "additionalContext": hint,
                    }
                }

            _hooks = {"PostToolUse": [HookMatcher(hooks=[_oracle_hook])],
                      "PostToolUseFailure": [
                          HookMatcher(hooks=[_failure_hook])]}

            # The wind-down gate for the CLI's own tools. adda's tools
            # (mcp__*) are gated in _wrap_closure, so they are skipped here
            # and never counted twice.
            from ..infra import wind_down as _wd
            _wd_key = _pn_did or "entry"

            async def _wind_down_hook(input_data, tool_use_id, context):
                name = input_data.get("tool_name", "")
                if name == "Bash" and _pn_did is None:
                    _bash_started[tool_use_id] = _time.time()
                if name.startswith("mcp__"):
                    return {}
                why = _wd.check(_wd_key, name, can_call_done=_pn_did is None)
                if not why:
                    return {}
                _record_hook("PreToolUse", tool_use_id, input_data, why)
                return {"hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "deny",
                    "permissionDecisionReason": why}}

            _hooks["PreToolUse"] = [HookMatcher(hooks=[_wind_down_hook])]
        except Exception:  # noqa: BLE001 — nudge is best-effort, never fatal
            _hooks = None

        # Per-session env: the SDK MERGES this over the inherited environment
        # (PATH etc. preserved), so bare extra keys are safe. See
        # _build_session_env for what is injected and why.
        from .base import session_delegation_id
        _sess_env: dict = _build_session_env(
            plain=_plain, delegation_id=session_delegation_id(self))
        if self._session_token:
            _sess_env[_interrupt.SESSION_TOKEN_ENV] = self._session_token

        from ..runtime.settings import get_float
        _max_buf_mb = get_float("llm_max_buffer_mb", 30.0)
        _max_buf = int(_max_buf_mb * 1024 * 1024)

        # The SDK spawns the CLI with cwd=self.study_dir; if that directory
        # doesn't exist the subprocess dies with a cryptic CLIConnectionError
        # ("Working directory does not exist") mid-delegation. Create it
        # defensively so a missing worker workspace can never abort a run.
        if self.study_dir:
            try:
                self.study_dir.mkdir(parents=True, exist_ok=True)
            except Exception:  # noqa: BLE001 — best-effort; spawn surfaces real errors
                pass

        prompt_str, _next = self._turn_prompt(messages)
        if resume is None:
            resume = _next
        self._record_turn_prompt(prompt_str, resume)
        options = ClaudeAgentOptions(
            system_prompt=self._system_prompt_option(),
            model=self.model,
            cwd=str(self.study_dir) if self.study_dir else None,
            tools=({"type": "preset", "preset": "claude_code"}
                   if self.use_default_tools else self.native_tools or []),
            mcp_servers=mcp_servers if mcp_servers else {},
            allowed_tools=self._compute_allowed_tools(qualified_mcp_tools),
            disallowed_tools=_effective_disallowed,
            permission_mode="bypassPermissions",
            strict_mcp_config=bool(mcp_servers),
            # Hermetic session: load NO filesystem settings, so worker/critic
            # subprocesses don't inherit the developer's global ~/.claude hooks
            # (e.g. cbm-code-discovery-gate, which blocked legitimate Read calls
            # for workers AND the critic). Our own hooks are passed
            # programmatically via options.hooks below (audit/#1: fresh hooks).
            setting_sources=[],
            env=_sess_env,
            # Stream-message buffer ceiling. Default 1MB is far too small for a
            # literature reviewer whose tools return full PDFs — a single >1MB
            # MCP tool result overflowed it and FATALLY (non-retried) killed the
            # whole delegation (D003). 30MB clears realistic PDFs; non-PDF
            # results never approach it. A result still exceeding this is caught
            # gracefully below (turn cut short + marker), not a fatal crash.
            # Tune via F3DASM_LLM_MAX_BUFFER_MB.
            max_buffer_size=_max_buf,
            # Partial streaming → a fine-grained heartbeat: the stream emits a
            # StreamEvent sub-second while genuinely generating, so total
            # silence becomes a reliable stall signal and the
            # idle timeout can be bounded without false-positiving a
            # slow-but-working generation.
            include_partial_messages=True,
            **_thinking_options(self.model),
            **({"hooks": _hooks} if _hooks else {}),
            **(
                {"resume": resume, "fork_session": False}
                if resume is not None else {}
            ),
        )

        last_assistant = None
        last_result: Any = None
        _buffer_overflowed = False
        _deliberate_break = False
        _cap_stop = False
        # Background jobs the CLI still tracks (its own background_tasks_changed
        # list). A plain Claude Code session whose turn ends with one running
        # gets the job's completion as its next turn, as in an interactive CLI.
        _bg_tasks: list = []
        _msg_usage: dict[str, dict] = {}
        # The model id each API call's message_start names: the served id
        # even when the stream breaks before any AssistantMessage arrives.
        _served_seen: list[str | None] = [None]
        _cur_msg_id: list[str | None] = [None]
        _counted = [0]
        raise_if_stopped("model call", getattr(self, "abandon_event", None))
        gen = query(prompt=prompt_str, options=options)
        # Idle-stream timeout — turns a silent stream into a retryable
        # TimeoutError. Resets on EVERY stream message. Scoped to model
        # generation: while a tool runs the window stands down (see _phase).
        # MEASURED (the stream_evt instrumentation settled this): the bundled
        # CLI forwards NO ping events — only message lifecycle — so during a
        # mid-generation pause we get ZERO liveness signal. Two supercompressible
        # (Sonnet) runs captured LEGITIMATE (recovered) active-generation gaps of
        # 53.6s AND 252-256s (one mid-tool_use-block composition, one
        # tool_result→next message_start delay). So earlier 60s/180s windows
        # would guillotine legitimate slow generations. The observed ~256s legit
        # gap left only ~44s of headroom under the prior 300s default, and with
        # NO ping liveness signal a longer legit generation is indistinguishable
        # from a stall — so the default is 600s: ample margin over the measured
        # legit gaps while still catching a truly dead (silent-forever) stream in
        # ~10 min. A genuine runaway is the delegation watchdog's concern, not
        # this window's. Knobs (config.yaml runtime block; env overrides):
        # llm_stream_idle_timeout (0 disables); llm_tool_idle_timeout caps tool
        # execution (0 = uncapped).
        from ..runtime.settings import get_float as _get_float
        _idle = (idle_timeout if idle_timeout is not None
                 else _get_float("llm_stream_idle_timeout", 600.0))
        _tool_idle = _get_float("llm_tool_idle_timeout", 0.0)

        _phase = _ToolPhase(lambda: bool(_plain and _bg_tasks))

        from .base import append_transcript, capture_enabled

        def _record(msg: Any):
            # Full reasoning + tool-calls + tool-results; StreamEvent partials
            # are skipped (the assembled AssistantMessage carries the text).
            if isinstance(msg, AssistantMessage):
                texts, tools, thinking = [], [], []
                thinking_omitted = 0
                for b in msg.content:
                    if isinstance(b, TextBlock):
                        texts.append(b.text)
                    elif isinstance(b, ToolUseBlock):
                        tools.append({"name": b.name, "input": b.input,
                                      "tool_use_id": getattr(b, "id", None)})
                    else:
                        t = (getattr(b, "thinking", None)
                             or getattr(b, "text", None))
                        if t:
                            thinking.append(t)
                        elif hasattr(b, "thinking"):
                            # A thinking block that arrived with no text
                            # (display "omitted"): counted, so "the model
                            # thought but it was hidden" is distinguishable
                            # from "the model did not think".
                            thinking_omitted += 1
                return {"type": "assistant", "text": "".join(texts),
                        "tools": tools, "thinking": thinking,
                        "thinking_omitted": thinking_omitted,
                        "message_id": getattr(msg, "message_id", None)}
            if isinstance(msg, UserMessage):
                results = []
                for b in (getattr(msg, "content", None) or []):
                    results.append({
                        "tool_use_id": getattr(b, "tool_use_id", None),
                        "content": getattr(b, "content", b),
                    })
                return {"type": "tool_result", "results": results}
            if isinstance(msg, ResultMessage):
                return {"type": "result",
                        "usage": getattr(msg, "usage", None),
                        "model_usage": getattr(msg, "model_usage", None),
                        "cost_usd": getattr(msg, "total_cost_usd", None)}
            if isinstance(msg, SystemMessage):
                # SystemMessage used to be invisible here entirely (this
                # function returned None for anything it didn't recognize) —
                # so a real compact_boundary (the SDK's own context-
                # compaction event) left NO trace in debug/transcripts/,
                # the viewer, or any post-run analysis. Confirmed empirically
                # (a short forced-window test): a single short session
                # produced 50-119 SystemMessages, the overwhelming majority
                # subtype "thinking_tokens" — a per-token streaming heartbeat,
                # pure noise at transcript granularity (stream_evt already
                # covers liveness). Record everything ELSE verbatim,
                # including (especially) compact_boundary's own metadata.
                if msg.subtype in _SYSTEM_MESSAGE_NOISE_SUBTYPES:
                    return None
                return {"type": "system", "subtype": msg.subtype,
                        "data": msg.data}
            return None

        _capture = capture_enabled()
        # Partial-stream checkpointing: an agent that never completes a message
        # (infinite thinking / an unresolved turn) emits only StreamEvents and
        # would otherwise disclose nothing. Buffer the deltas and flush a
        # "partial" record every N events (and on any stream teardown) so the
        # transcript reveals what a stuck turn is doing in near-real-time.
        _PARTIAL_FLUSH_EVERY = 25
        _pbuf: list[str] = []
        _pcount = [0]

        def _extract_delta(ev: Any) -> str:
            if not isinstance(ev, dict):
                return ""
            d = ev.get("delta") or {}
            return (d.get("text") or d.get("thinking")
                    or d.get("partial_json") or "")

        def _flush_partial() -> None:
            if _pbuf:
                append_transcript({"type": "partial", "text": "".join(_pbuf),
                                   "events": _pcount[0]})
                _pbuf.clear()

        try:
            _stream = (
                _stream_with_idle_timeout(
                    gen, _idle,
                    tool_timeout=_tool_idle, classify=_phase,
                    wall_remaining=(
                        token_clock.wall_remaining if _plain else None),
                )
                if _idle > 0 else gen
            )
            # Measurement clock: the first event's gap below = time-to-first
            # stream event (≈ prefill latency).
            _last_evt = [time.monotonic()]
            async for msg in _stream:
                raise_if_stopped("model call", getattr(self, "abandon_event", None))
                if (_plain and not isinstance(msg, StreamEvent)
                        and token_clock.exhausted()):
                    # The wall deadline passes while a tool runs; only a
                    # message (the tool result) wakes this loop, so check on
                    # every one, not only on stream events.
                    token_clock.note_stop()
                    _cap_stop = True
                    break
                if isinstance(msg, UserMessage):
                    _note_background_results(msg)
                if (isinstance(msg, SystemMessage)
                        and msg.subtype == "background_tasks_changed"):
                    _bg_tasks[:] = (msg.data or {}).get("tasks") or []
                if isinstance(msg, StreamEvent):
                    _track_message_usage(
                        getattr(msg, "event", None), _msg_usage, _cur_msg_id)
                    _served_seen[0] = _start_model(
                        getattr(msg, "event", None)) or _served_seen[0]
                    _counted[0] += _count_output_tokens(
                        getattr(msg, "event", None), _cur_msg_id)
                    if _plain and token_clock.exhausted():
                        # Nothing is sent to the agent: the operator ends
                        # the session, as when a user presses Esc. Closing
                        # the stream (aclose below) takes the CLI down.
                        token_clock.note_stop()
                        _cap_stop = True
                        break
                elif isinstance(msg, AssistantMessage) \
                        and getattr(msg, "usage", None) \
                        and getattr(msg, "message_id", None):
                    _msg_usage.setdefault(msg.message_id, dict(msg.usage))
                if _capture:
                    if isinstance(msg, StreamEvent):
                        _pcount[0] += 1
                        _ev = getattr(msg, "event", {}) or {}
                        _et = _ev.get("type", "?") if isinstance(
                            _ev, dict) else "?"
                        _now = time.monotonic()
                        _gap = _now - _last_evt[0]
                        _last_evt[0] = _now
                        # Record every NON-delta event (ping, message_start/
                        # stop, content_block_start/stop, message_delta) and any
                        # delta after a >2s pause — so we can see whether the
                        # stream stays alive (pings) during silent/prefill
                        # phases and the true inter-event gap distribution.
                        # This is what settles whether a 60s silence is a dead
                        # stream or a legitimately-slow first token.
                        if _et != "content_block_delta" or _gap > 2.0:
                            append_transcript({
                                "type": "stream_evt", "evt": _et,
                                "gap_s": round(_gap, 2),
                                **_usage_fields(_ev)})
                        _d = _extract_delta(_ev)
                        if _d:
                            _pbuf.append(_d)
                        if _pcount[0] % _PARTIAL_FLUSH_EVERY == 0:
                            _flush_partial()
                    else:
                        # A complete message: flush any buffered partial first,
                        # then the structured record.
                        _flush_partial()
                        _rec = _record(msg)
                        if _rec is not None:
                            append_transcript(_rec)
                if isinstance(msg, SystemMessage) and msg.subtype == "init":
                    self._cli_tools = list((msg.data or {}).get("tools") or [])
                    self._attempt_session_id = (
                        (msg.data or {}).get("session_id")
                        or self._attempt_session_id)
                if isinstance(msg, AssistantMessage) and getattr(
                        msg, "session_id", None):
                    self._attempt_session_id = msg.session_id
                if (isinstance(msg, SystemMessage) and msg.subtype == "init"
                        and self.on_init_tools is not None):
                    # Unconditional like the compaction record below: which
                    # tools the CLI really loaded is a run-level fact.
                    try:
                        self.on_init_tools(list((msg.data or {}).get("tools") or []))
                    except Exception:  # noqa: BLE001 — a notice never fails a turn
                        pass
                if isinstance(msg, SystemMessage) and msg.subtype == "compact_boundary":
                    # Unconditional (not gated on _capture/debug mode): a
                    # compaction is a run-level fact an analyst should never
                    # have to enable debug transcripts to discover.
                    record_stream_diagnostic(
                        "CONTEXT_COMPACTED",
                        "The SDK compacted this session's context "
                        "mid-turn (compact_boundary).",
                        compaction_data=msg.data,
                    )
                if isinstance(msg, AssistantMessage):
                    last_assistant = msg
                    if self.route_watcher and self.route_watcher():
                        _deliberate_break = True
                        break
                elif isinstance(msg, ResultMessage):
                    last_result = msg
                    if not (_plain and _bg_tasks):
                        break
        except Exception as exc:  # noqa: BLE001
            _m = str(exc).lower()
            if "maximum buffer size" in _m or "exceeded maximum" in _m:
                # Graceful contour: a single tool result (e.g. a huge PDF)
                # overflowed the stream buffer. The old behavior was a fatal,
                # NON-retried crash that killed the whole delegation (D003).
                # Instead, end the turn with what we have + a marker so the
                # agent can retry the fetch smaller — the delegation survives.
                _buffer_overflowed = True
            else:
                raise
        finally:
            if _capture:
                _flush_partial()  # disclose a stuck/torn-down turn's tail
            self._settle_usage(last_result, _msg_usage, last_assistant,
                               counted=_counted[0], served=_served_seen[0])
            _watch = getattr(self, "_background_watch", None)
            if _watch is not None:
                # Depth 2: the CLI itself (depth 1) is not a background job.
                _watch.end(min_depth=2)
            aclose = getattr(gen, "aclose", None)
            if aclose:
                try:
                    await aclose()
                except Exception:
                    pass

        # A stream that ends with neither a ResultMessage NOR a deliberate
        # route_watcher break, and wasn't already explained by a buffer
        # overflow, is abnormal: the CLI session ended (or the SDK's async
        # generator was exhausted) without ever completing its turn — report
        # 7 (run 20260830T004106, Oscar): the last AssistantMessage carried
        # only a tool call (e.g. Bash/TaskOutput), no result ever arrived,
        # and the near-empty `text` this then returns reads as a malformed
        # report to _invoke_with_report_retry, which silently re-invokes
        # with the ORIGINAL task — restarting the delegation from scratch,
        # orphaning whatever the first attempt launched, with nothing
        # logged anywhere. This does not change that return behaviour (a
        # future decision, pending Elvis) — it only makes the fact visible.
        if (last_result is None and not _deliberate_break
                and not _buffer_overflowed and not _cap_stop):
            _last_tool = None
            if last_assistant is not None:
                for _b in last_assistant.content:
                    if isinstance(_b, ToolUseBlock):
                        _last_tool = _b.name
            record_stream_diagnostic(
                "STREAM_ENDED_WITHOUT_RESULT",
                "CLI stream ended without a ResultMessage or a deliberate "
                "route break — the turn may not have completed; its "
                "returned text can look like a malformed report and "
                "trigger a silent report-retry.",
                last_tool_in_flight=_last_tool,
                cli_session_id=getattr(last_assistant, "session_id", None),
            )

        text = ""
        if last_assistant is not None:
            for block in last_assistant.content:
                if isinstance(block, TextBlock):
                    text += block.text
        if _buffer_overflowed:
            _note = (
                f"[STREAM NOTE: a tool returned more than {_max_buf_mb:.0f} MB "
                "in a single result and overflowed the message buffer; that "
                "result was dropped and this turn was cut short (the delegation "
                "did NOT crash). Re-run the tool with a smaller/narrower request "
                "— fewer items, or a summary/extract instead of full text.]"
            )
            text = (text + "\n\n" + _note) if text else _note
        return text

    def _settle_usage(self, last_result: Any, _msg_usage: dict,
                      last_assistant: Any, counted: int = 0,
                      served: str | None = None) -> None:
        """Record this attempt's usage and session id. Runs from ainvoke's
        ``finally`` so a stream that RAISES (idle TimeoutError, API error)
        still reports the usage it had streamed; ``invoke`` sums the
        attempts."""
        # Capture token usage from ResultMessage for run-level accounting.
        if last_result is not None:
            self.last_usage = {
                **(last_result.usage or {}),
                **_cache_split(last_result.usage or {}),
                "total_cost_usd": last_result.total_cost_usd,
            }
        elif _msg_usage:
            # route_watcher broke the stream on the AssistantMessage that
            # closes the run (Done()) before the SDK's ResultMessage -- the
            # only carrier of the session's cumulative usage and cost -- ever
            # arrived. The strategizer's whole run is ONE long stream, so
            # taking just the last message's usage recorded ~1 output token
            # for the entire run (run 20260928T141126). Sum the per-API-call
            # usage the stream itself reported instead. total_cost_usd stays
            # None: cost is a session-level rollup no single message carries,
            # the same "unknown, not zero" convention openai_compatible uses.
            self.last_usage = {
                **_sum_message_usage(_msg_usage.values()),
                "total_cost_usd": None,
            }
        elif last_assistant is not None and getattr(last_assistant, "usage", None):
            # A backend/stream that never sent message_start/delta events or a
            # message id: the lone message's own (possibly stale) usage.
            self.last_usage = {
                **last_assistant.usage, "total_cost_usd": None,
            }
        else:
            self.last_usage = {}

        # Claude reports input_tokens WITHOUT cache tokens, so each count maps
        # one to one onto the telemetry schema.
        u = self.last_usage
        self.last_usage = {**u, **normalized_usage(
            fresh_input=u.get("input_tokens"),
            cache_read=u.get("cache_read_input_tokens"),
            cache_write=u.get("cache_creation_input_tokens"),
            output=u.get("output_tokens"))}
        # The model id the API actually served. The configured model may be
        # an alias ("haiku") that the CLI resolves; only the resolved id has
        # a price and says which model ran.
        _served = getattr(last_assistant, "model", None) or served
        if isinstance(_served, str) and _served:
            self.last_usage["model_resolved"] = _served
        if _msg_usage:
            # Claude's input_tokens excludes cache, so a call's whole prompt
            # is the three input counts together.
            self.last_usage.update(call_shape([
                (m.get("input_tokens") or 0)
                + (m.get("cache_read_input_tokens") or 0)
                + (m.get("cache_creation_input_tokens") or 0)
                for m in _msg_usage.values()]))
            # Per request, so cost pricing can tier each on its own prompt.
            self.last_usage["call_tokens"] = [
                [m.get("input_tokens") or 0,
                 m.get("cache_read_input_tokens") or 0,
                 m.get("cache_creation_input_tokens") or 0,
                 m.get("output_tokens") or 0]
                for m in _msg_usage.values()]

        if token_clock.enabled():
            # The stream counted each call as it ended; a call whose stream
            # events never arrived is counted here from the usage the CLI
            # reported for the whole attempt. A finished attempt with no
            # reported count raises; a failed one keeps its real error.
            out = self.last_usage.get("output_tokens")
            if out is None and last_result is not None:
                token_clock.record(uuid.uuid4().hex, None,
                                   "the Claude CLI result")
            if out and out > counted:
                token_clock.record(uuid.uuid4().hex, out - counted,
                                   "the Claude CLI result")

        self.last_session_id = (
            getattr(last_result, "session_id", None)
            or getattr(last_assistant, "session_id", None)
        )
        if self.plain_session and self.last_session_id:
            self._session_id = self.last_session_id
        if self._attempt_usages is not None:
            self._attempt_usages.append(dict(self.last_usage))

    def _invoke_resuming(
        self, messages: list[dict], *, idle_timeout: float | None,
        retry_max: int | None, resume: str | None,
    ) -> str:
        """``ainvoke`` with transient errors retried, continuing the session.

        The CLI retries API errors itself, so an error that reaches here (a
        CLI crash, a stream-idle timeout, an API error after the CLI's own
        retries) ends a session that may have run for hours. Sending the
        brief again would start that work from nothing. A retry instead
        resumes the failed attempt's session with RESUME_NOTICE. It starts
        again from the brief only when no session id was seen, or when the
        resume itself fails with a non-transient error (a session the CLI did
        not keep); RESUME_FAILED records that. Each LLM_RETRY row says which
        path the retry takes (``resumed``).
        """
        from .base import is_transient_error, retry_on_transient
        plan = {"messages": messages, "resume": resume, "sid": None}

        def attempt() -> str:
            try:
                return _run_async_safe(self.ainvoke(
                    plan["messages"], idle_timeout=idle_timeout,
                    resume=plan["resume"]))
            except Exception as exc:  # noqa: BLE001 — re-raised below
                plan["sid"] = (getattr(self, "_attempt_session_id", None)
                               or plan["sid"])
                if (plan["messages"] is messages
                        or is_transient_error(exc)):
                    raise
                record_stream_diagnostic(
                    "RESUME_FAILED",
                    "resuming the session after a dropped connection "
                    "failed; starting again from the brief",
                    session_id=plan["resume"],
                    error=f"{type(exc).__name__}: {str(exc)[:300]}")
            plan["messages"], plan["resume"], plan["sid"] = (
                messages, resume, None)
            return _run_async_safe(self.ainvoke(
                messages, idle_timeout=idle_timeout, resume=resume))

        def on_retry(n: int, max_n: int, exc: BaseException,
                     delay: float) -> None:
            sid = plan["sid"]
            if sid:
                plan["messages"] = [{"role": "user", "content": RESUME_NOTICE}]
                plan["resume"] = sid
            else:
                plan["messages"], plan["resume"] = messages, resume
            sink = getattr(self, "on_retry", None)
            if sink is not None:
                sink(n, max_n, exc, delay, resumed=bool(sid))

        run = getattr(self, "abandon_event", None)
        who = _usage_who()

        def one() -> str:
            return retry_on_transient(
                attempt, max_attempts=retry_max, on_retry=on_retry,
                sleep=lambda d: sleep_unless_stopped(d, "retry backoff", run))

        # A provider usage limit pauses the whole run (infra/usage_pause.py);
        # after the reset this SAME session continues with a short notice.
        for rnd in range(_USAGE_PAUSE_ROUNDS):
            last = rnd == _USAGE_PAUSE_ROUNDS - 1
            usage_pause.wait(who, run)
            try:
                text = usage_pause.injected_limit(who) or one()
            except Exception as exc:  # noqa: BLE001 — re-raised unless a limit
                if last or not (
                        usage_pause.is_limit_text(str(exc), strict=False)
                        and usage_pause.report_limit(str(exc), who)):
                    raise
            else:
                if last or not (usage_pause.is_limit_text(text)
                                and usage_pause.report_limit(text, who)):
                    return text
            usage_pause.wait(who, run)
            sid = (getattr(self, "_attempt_session_id", None)
                   or self.last_session_id)
            if sid:
                plan["messages"] = [{"role": "user",
                                     "content": usage_pause.resume_notice()}]
                plan["resume"] = sid
            else:
                plan["messages"], plan["resume"] = messages, resume
        raise AssertionError("unreachable: the last round returns or raises")

    def invoke(
        self, messages: list[dict], *,
        idle_timeout: float | None = None, retry_max: int | None = None,
        resume: str | None = None,
        on_session_start: Any = None,
        on_session_end: Any = None,
        background_watch: Any = None,
    ) -> str:
        """Synchronous wrapper around :meth:`ainvoke`.

        Acquires _lock to serialize concurrent callers of this adapter object
        (each delegation has its own copy(), so they do not contend). Transient API/network
        failures are retried with exponential backoff, continuing the failed
        session where one exists (see ``_invoke_resuming``).

        ``idle_timeout`` / ``retry_max`` override the run-wide stream-idle and
        retry budgets for THIS call only. A short advisory side-call (verdict
        validator) passes a tight idle + ``retry_max=1`` so a hung CLI stream
        aborts in ~that window instead of inheriting a real turn's
        5×600s budget (which once froze a whole run for ~89 min).

        ``resume``: see :meth:`ainvoke`.

        ``on_session_start``: called with no arguments the instant ``_lock``
        is actually acquired -- i.e. when this call's real work begins, not
        when it was merely requested. This is the point at which the call's real work begins,
        distinct from when it was asked to start.
        Best-effort: swallows any exception so a broken callback never
        breaks the real turn.

        ``on_session_end``: called as ``on_session_end(session_id, usage)``
        with THIS call's own session id and token usage while ``_lock`` is
        still held, once the turn is over (also when it raised, with
        whatever it produced: ``None`` / ``{}`` if nothing). Both are
        per-call output; a caller that needs ITS OWN values takes them from
        here rather than from ``last_session_id`` / ``last_usage``. Best-effort
        like ``on_session_start``.

        ``background_watch``: an ``infra.background_jobs.BackgroundJobWatch``.
        It takes its baseline here and its end snapshot inside ``ainvoke``
        just before the CLI is closed, while the CLI's children still live.
        """
        with self._lock:
            self._background_watch = background_watch
            if background_watch is not None:
                background_watch.start()
            if on_session_start is not None:
                try:
                    on_session_start()
                except Exception:  # noqa: BLE001
                    pass
            # Cleared so a turn that raises before ainvoke() sets them cannot
            # hand its caller the PREVIOUS call's values.
            self.last_session_id = None
            self.last_usage = {}
            self._attempt_usages = []
            try:
                with _interrupt.in_flight(self):
                    return self._invoke_resuming(
                        messages, idle_timeout=idle_timeout,
                        retry_max=retry_max, resume=resume)
            finally:
                self.last_usage = _combine_attempt_usage(self._attempt_usages)
                self._attempt_usages = None
                if on_session_end is not None:
                    try:
                        on_session_end(
                            self.last_session_id, dict(self.last_usage or {}))
                    except Exception:  # noqa: BLE001
                        pass
HAS_BASE_PROMPT = True class-attribute instance-attribute #
base_prompt: str | None = None class-attribute instance-attribute #
NATIVE_TOOLS = frozenset({'Bash', 'Edit', 'Read', 'Write', 'Glob', 'Grep', 'BashOutput', 'KillShell', 'Task', 'WebFetch', 'WebSearch'}) class-attribute instance-attribute #
model = model instance-attribute #
system_prompt = system_prompt instance-attribute #
study_dir = Path(study_dir) if study_dir else None instance-attribute #
use_default_tools: bool = DEFAULT_TOOLS in (native_tools or []) instance-attribute #
native_tools = [t for t in (native_tools or []) if t != DEFAULT_TOOLS] instance-attribute #
on_init_tools: Any = None instance-attribute #
closure_tools = dict(closure_tools or {}) instance-attribute #
extra_mcp_servers: dict = dict(extra_mcp_servers or {}) instance-attribute #
extra_allowed_tools: list[str] = list(extra_allowed_tools or []) instance-attribute #
persistent: bool = persistent instance-attribute #
max_history_pairs: int = max_history_pairs instance-attribute #
_lock: threading.Lock = threading.Lock() instance-attribute #
route_watcher: Any = None instance-attribute #
last_usage: dict = {} instance-attribute #
_attempt_usages: list[dict] | None = None instance-attribute #
last_session_id: str | None = None instance-attribute #
_session_id: str | None = None instance-attribute #
_background_watch: Any = None instance-attribute #
_session_token: str | None = None instance-attribute #
plain_session: bool property #

True when this adapter runs plain Claude Code: the CLI's own tools and system prompt, nothing of adda's. Its session gets the statement as typed and later turns resume it (_turn_prompt).

select_native_tools(agent_tools) -> list[str] classmethod #

Pick which of an agent's declared tools are native SDK CLI tools.

Mirror of OpenAICompatibleAdapter.select_native_tools so the runtime can choose native tools generically for any backend (forward-compatible dispatch).

Source code in src/adda/_src/backends/claude.py
674
675
676
677
678
679
680
681
682
683
684
@classmethod
def select_native_tools(cls, agent_tools) -> list[str]:
    """Pick which of an agent's declared tools are native SDK CLI tools.

    Mirror of OpenAICompatibleAdapter.select_native_tools so the runtime
    can choose native tools generically for any backend (forward-compatible
    dispatch)."""
    picked = [t for t in agent_tools if t in cls.NATIVE_TOOLS]
    if DEFAULT_TOOLS in agent_tools:
        picked.append(DEFAULT_TOOLS)
    return picked
_system_prompt_option() #

What the CLI receives: the text alone (it REPLACES Claude Code's prompt), or, for a node with base_prompt: Default, a preset that keeps Claude Code's prompt and appends the text.

Source code in src/adda/_src/backends/claude.py
733
734
735
736
737
738
739
740
741
def _system_prompt_option(self):
    """What the CLI receives: the text alone (it REPLACES Claude Code's
    prompt), or, for a node with ``base_prompt: Default``, a preset that
    keeps Claude Code's prompt and appends the text."""
    text = self._render_system_prompt()
    if self.base_prompt == DEFAULT_PROMPT:
        return {"type": "preset", "preset": "claude_code",
                **({"append": text} if text.strip() else {})}
    return text
_render_system_prompt() -> str #

The system prompt exactly as the model sees it: base prompt plus the <tools> catalog, with every tool the prose names rewritten to the qualified name the SDK exposes (catalog and prose must agree).

Source code in src/adda/_src/backends/claude.py
743
744
745
746
747
748
749
750
751
752
753
754
755
def _render_system_prompt(self) -> str:
    """The system prompt exactly as the model sees it: base prompt plus
    the ``<tools>`` catalog, with every tool the prose names rewritten to
    the qualified name the SDK exposes (catalog and prose must agree)."""
    from ..prompts.tool_catalog import system_prompt_with_catalog
    qualified = _qualify_closure_names(self.closure_tools)
    rendered = system_prompt_with_catalog(
        self.system_prompt, qualified, builtins_held=self.use_default_tools,
        # the closures by their own names: the catalog gets them qualified
        native=frozenset(self.closure_tools) | frozenset(
            self.NATIVE_TOOLS if self.use_default_tools
            else self.native_tools))
    return _qualify_prose(rendered, self.closure_tools)
_record_turn_prompt(prompt: str, resume: str | None) -> None staticmethod #

Every agent's input is on record: the turn's prompt opens its transcript (the stream records only what comes back).

Source code in src/adda/_src/backends/claude.py
764
765
766
767
768
769
770
771
772
773
774
@staticmethod
def _record_turn_prompt(prompt: str, resume: str | None) -> None:
    """Every agent's input is on record: the turn's prompt opens its
    transcript (the stream records only what comes back)."""
    import hashlib

    from .base import append_transcript
    append_transcript({
        "type": "user", "text": prompt,
        "sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
        "resume": resume})
_turn_prompt(messages: list[dict]) -> tuple[str, str | None] #

(prompt, resume) for this turn.

An adda node gets the whole conversation flattened to one string, each turn labelled Human: / Assistant:. A plain session gets its first user message byte for byte, and every later turn only the user text that follows the last assistant message, in the session this adapter already opened (resume).

Source code in src/adda/_src/backends/claude.py
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
def _turn_prompt(self, messages: list[dict]) -> tuple[str, str | None]:
    """``(prompt, resume)`` for this turn.

    An adda node gets the whole conversation flattened to one string,
    each turn labelled ``Human:`` / ``Assistant:``. A plain session gets
    its first user message byte for byte, and every later turn only the
    user text that follows the last assistant message, in the session
    this adapter already opened (``resume``).
    """
    if not self.plain_session:
        return _format_messages_as_prompt(messages), None
    texts = [_message_text(m) for m in messages]
    roles = [m.get("role", "user") for m in messages]
    users = [t for t, r in zip(texts, roles, strict=True) if r in ("human", "user")]
    if self._session_id is None:
        return users[0], None
    last_ai = max((i for i, r in enumerate(roles)
                   if r in ("ai", "assistant")), default=-1)
    return "\n\n".join(
        t for t, r in zip(texts[last_ai + 1:], roles[last_ai + 1:], strict=True)
        if r in ("human", "user")), self._session_id
_compute_allowed_tools(qualified_mcp_tools) -> list[str] #

All allowed tool names, ALWAYS as a list (never None).

The SDK does list(options.allowed_tools) when building its command, which raises TypeError on None — so a tool-less agent (e.g. the one-shot problem-statement reviewer) must still get [] here, not None. An empty list correctly means "no tools allowed".

Source code in src/adda/_src/backends/claude.py
798
799
800
801
802
803
804
805
806
807
808
809
810
def _compute_allowed_tools(self, qualified_mcp_tools) -> list[str]:
    """All allowed tool names, ALWAYS as a list (never None).

    The SDK does ``list(options.allowed_tools)`` when building its command,
    which raises ``TypeError`` on ``None`` — so a tool-less agent (e.g. the
    one-shot problem-statement reviewer) must still get ``[]`` here, not
    ``None``. An empty list correctly means "no tools allowed".
    """
    return (
        list(qualified_mcp_tools)
        + list(self.native_tools)
        + list(self.extra_allowed_tools)
    )
copy() -> ClaudeAdapter #

An independent adapter for ONE delegation.

Shares configuration; owns everything a delegation mutates: its own closure_tools (dispatch binds ReportEvals / Write / FollowUp to that delegation's id), its own _lock and its own per-call last_* state. Same-role delegations therefore run concurrently instead of queueing behind one shared lock.

Source code in src/adda/_src/backends/claude.py
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
def copy(self) -> ClaudeAdapter:
    """An independent adapter for ONE delegation.

    Shares configuration; owns everything a delegation mutates: its own
    ``closure_tools`` (dispatch binds ReportEvals / Write / FollowUp to
    that delegation's id), its own ``_lock`` and its own per-call
    ``last_*`` state. Same-role delegations therefore run concurrently
    instead of queueing behind one shared lock.
    """
    import copy as _copy
    twin = _copy.copy(self)
    twin.closure_tools = dict(self.closure_tools)
    twin.native_tools = list(self.native_tools)
    twin.extra_allowed_tools = list(self.extra_allowed_tools)
    twin.extra_mcp_servers = dict(self.extra_mcp_servers)
    twin._lock = threading.Lock()
    twin.last_usage = {}
    twin._attempt_usages = None
    twin.last_session_id = None
    twin._session_id = None
    # The route watcher ends the NODE's own turn after Done/Handoff. A
    # copy runs a delegation or a wake, never that turn; watching the
    # node's route there broke every wake after a handoff at its first
    # message (empty reply, no error).
    twin.route_watcher = None
    return twin
interrupt() -> list[dict] #

SIGINT the work a Bash-tool shell of this adapter's CLI session runs, found by its session token; never the CLI itself nor an MCP server, so the turn goes on. Safe from any thread.

Source code in src/adda/_src/backends/claude.py
839
840
841
842
843
844
def interrupt(self) -> list[dict]:
    """SIGINT the work a Bash-tool shell of this adapter's CLI session
    runs, found by its session token; never the CLI itself nor an MCP
    server, so the turn goes on. Safe from any thread."""
    return _interrupt.interrupt_session(
        self._session_token, self.extra_mcp_servers)
ainvoke(messages: list[dict], *, idle_timeout: float | None = None, resume: str | None = None) -> str async #

Run one agent turn asynchronously; return assembled text.

idle_timeout overrides the run-wide llm_stream_idle_timeout for THIS call only — used by short advisory side-calls (e.g. the verdict validator) that must not inherit a real agent turn's generous window.

resume (spec 12 item 3): a CLI session id to resume rather than starting fresh -- messages then carries only the NEW turn (the prior conversation is loaded from the resumed session itself, not replayed here). fork_session=False always, so this continues the SAME session rather than branching a copy of it.

Source code in src/adda/_src/backends/claude.py
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
async def ainvoke(

    self, messages: list[dict], *, idle_timeout: float | None = None,
    resume: str | None = None,
) -> str:
    """Run one agent turn asynchronously; return assembled text.

    ``idle_timeout`` overrides the run-wide ``llm_stream_idle_timeout`` for
    THIS call only — used by short advisory side-calls (e.g. the verdict
    validator) that must not inherit a real agent turn's generous window.

    ``resume`` (spec 12 item 3): a CLI session id to resume rather than
    starting fresh -- ``messages`` then carries only the NEW turn (the
    prior conversation is loaded from the resumed session itself, not
    replayed here). ``fork_session=False`` always, so this continues the
    SAME session rather than branching a copy of it.
    """
    self._session_token = _interrupt.new_token()
    self._attempt_session_id = None
    _require_sdk()
    from claude_agent_sdk import (
        AssistantMessage,
        ClaudeAgentOptions,
        ResultMessage,
        SdkMcpTool,
        StreamEvent,
        SystemMessage,
        TextBlock,
        ToolUseBlock,
        UserMessage,
        create_sdk_mcp_server,
        query,
    )

    from ..prompts.tool_catalog import tool_summary

    # Build MCP server from closure_tools if any
    mcp_servers: dict = {}
    qualified_mcp_tools: list[str] = []
    if self.closure_tools:
        server_name = _CLOSURE_MCP_SERVER
        sdk_tools: list[Any] = []
        for tool_name, fn in self.closure_tools.items():
            schema = _infer_schema_from_callable(fn)

            async def _handler(args: dict, bound_fn: Any = fn) -> dict:
                try:
                    result = bound_fn(**args)
                except Exception as exc:
                    return {
                        "content": [
                            {"type": "text", "text": f"ERROR: {exc}"}
                        ],
                        "is_error": True,
                    }
                return {
                    "content": [
                        {
                            "type": "text",
                            "text": (
                                str(result) if result is not None else ""
                            ),
                        }
                    ]
                }

            sdk_tools.append(
                SdkMcpTool(
                    name=tool_name,
                    description=tool_summary(fn, tool_name),
                    input_schema=schema,
                    handler=_handler,
                )
            )

        mcp_cfg = create_sdk_mcp_server(
            name=server_name, tools=sdk_tools or None
        )
        mcp_servers = {server_name: mcp_cfg}
        qualified_mcp_tools = list(_qualify_closure_names(self.closure_tools))

    # Plain Claude Code (Default tools + Default prompt): adda hands the
    # CLI nothing — no closure server, no MCP server, no hook.
    _plain = self.use_default_tools and self.base_prompt == DEFAULT_PROMPT
    if _plain:
        mcp_servers, qualified_mcp_tools = {}, []

    # Merge external stdio MCP servers declared by the Agent subclass.
    if self.extra_mcp_servers and not _plain:
        mcp_servers.update(self.extra_mcp_servers)

    _base_disallowed = ["WebSearch", "WebFetch", "Task", "ExitPlanMode"]
    # Under permission_mode="bypassPermissions" the allowed_tools allowlist
    # is NOT enforced — disallowed_tools is the only thing that binds. So a
    # native tool the agent never declared (e.g. Bash/Write for a read-only
    # reviewer) would otherwise be silently usable. Disallow every native
    # tool this agent did not declare, making its declared toolset binding.
    _ungranted_native = [
        t for t in self.NATIVE_TOOLS if t not in self.native_tools
    ]
    if self.use_default_tools:
        # Default has no floor. Only computed additions stay: a built-in
        # that shares its bare name with a closure this node declares
        # (the sandboxed Write replaces the native one) must not run.
        _base_disallowed, _ungranted_native = [], list(self.closure_tools)
    _effective_disallowed = [
        t for t in dict.fromkeys([*_base_disallowed, *_ungranted_native])
        if t not in self.extra_allowed_tools
    ]
    # The run's own ban (config.yaml runtime.disallowed_tools) binds
    # every agent, Default and plain ones too, and no grant lifts it.
    from ..runtime.settings import get_list as _get_list
    _effective_disallowed = list(dict.fromkeys(
        [*_effective_disallowed, *_get_list("disallowed_tools", [])]))

    # Non-blocking raw-oracle nudge: a PostToolUse hook that injects a
    # reminder (capped per delegation = per ainvoke) when a Bash/Write
    # call reaches the oracle directly instead of via get_evaluator().
    # Best-effort — if the SDK hook API is unavailable, run without it.
    _hooks = None
    try:
        if _plain:
            raise RuntimeError("plain Claude Code runs without adda hooks")
        from claude_agent_sdk import HookMatcher

        from ..runtime import features
        from .base import (
            OracleNudgeBudget,
            get_delegation_id,
            get_run_config_path,
            oracle_registered,
        )
        # Silent until an oracle is registered: pre-registration work (the
        # datagenerator wrapping/validating its raw source) has no
        # get_evaluator() to use, so nudging it is a false positive.
        # The nudge is a monitor intervention; the store notices the same
        # hook carries are store integrity and stay on in every arm.
        _nudge = OracleNudgeBudget(
            enabled=oracle_registered()
            and features.enabled("science_monitor"))
        # Expose on the adapter so the runtime can drain + log its
        # firings as direct evidence (see _record_intervention).
        _nudge.run_config_path = get_run_config_path()
        self._oracle_nudge = _nudge

        # The hook may run on another thread, so bind the delegation and
        # the run's debug dir now, while this thread still holds them.
        from ..infra import pending_notices as _pn
        _rc = get_run_config_path()
        _pn_dir = Path(_rc).parent if _rc else None
        _pn_did = get_delegation_id()
        _pn_key = _pn_did or getattr(self, "notice_key", None)

        # What a hook adds to the agent's context is the agent's input
        # too, so it goes on record beside the tool result it follows
        # (the CLI's own stream does not carry it).
        from .base import append_transcript, get_transcript_sink
        _hook_sink = get_transcript_sink()

        # The entry node's own Bash children are capped as "entry"; its
        # CLI only reports their exit code, so a watcher kill during the
        # call is named in a note after it (one wording: kill_reason).
        import time as _time

        from ..infra import watchdog_cleanup as _wc
        _bash_started: dict = {}

        def _entry_kill_note(input_data, tool_use_id):
            start = _bash_started.pop(tool_use_id, None)
            if (_pn_did is not None or start is None
                    or input_data.get("tool_name") != "Bash"):
                return None
            reason = _wc.kill_reason_for_group(_wc.ENTRY, since=start)
            return _wc.kill_line(reason) if reason else None
        def _pattern_kill_note(input_data):
            """The advisory note after a Bash pkill/pgrep -f, for a
            session that holds KillOwnJobs."""
            from ..nodes.tools.routing.processes import (
                PATTERN_KILL_NOTE,
                is_pattern_kill,
            )
            if input_data.get("tool_name") != "Bash" or "KillOwnJobs" \
                    not in (getattr(self, "closure_tools", None) or {}):
                return None
            cmd = (input_data.get("tool_input") or {}).get("command", "")
            return PATTERN_KILL_NOTE if is_pattern_kill(cmd) else None

        def _record_hook(event, tool_use_id, input_data, text):
            append_transcript({
                "type": "hook_context", "event": event,
                "tool_use_id": tool_use_id,
                "tool": (input_data or {}).get("tool_name"),
                "text": text}, path=_hook_sink)

        async def _oracle_hook(input_data, tool_use_id, context):
            msg = _pn.post_tool_context(
                _nudge,
                input_data.get("tool_name", ""),
                input_data.get("tool_input") or {},
                _pn_dir, _pn_key,
            )
            for hint in (
                    _background_wait_hint(
                        input_data.get("tool_response"),
                        getattr(self, "_cli_tools", None)),
                    _background_task_note(
                        input_data.get("tool_response"))):
                if hint:
                    msg = f"{msg}\n\n{hint}" if msg else hint
            kill = _entry_kill_note(input_data, tool_use_id)
            if kill:
                msg = f"{msg}\n\n{kill}" if msg else kill
            note = _pattern_kill_note(input_data)
            if note:
                msg = f"{msg}\n\n{note}" if msg else note
            if not msg:
                return {}
            msg = _qualify_prose(msg, self.closure_tools)
            _record_hook("PostToolUse", tool_use_id, input_data, msg)
            return {
                "hookSpecificOutput": {
                    "hookEventName": "PostToolUse",
                    "additionalContext": msg,
                }
            }

        async def _failure_hook(input_data, tool_use_id, context):
            # A call the CLI refused (its own validation, e.g. the
            # foreground-sleep block) ends here, not in PostToolUse.
            hint = _background_wait_hint(
                input_data.get("error"),
                getattr(self, "_cli_tools", None))
            kill = _entry_kill_note(input_data, tool_use_id)
            if kill:
                hint = f"{hint}\n\n{kill}" if hint else kill
            note = _pattern_kill_note(input_data)
            if note:
                hint = f"{hint}\n\n{note}" if hint else note
            if not hint:
                return {}
            hint = _qualify_prose(hint, self.closure_tools)
            _record_hook("PostToolUseFailure", tool_use_id, input_data,
                         hint)
            return {
                "hookSpecificOutput": {
                    "hookEventName": "PostToolUseFailure",
                    "additionalContext": hint,
                }
            }

        _hooks = {"PostToolUse": [HookMatcher(hooks=[_oracle_hook])],
                  "PostToolUseFailure": [
                      HookMatcher(hooks=[_failure_hook])]}

        # The wind-down gate for the CLI's own tools. adda's tools
        # (mcp__*) are gated in _wrap_closure, so they are skipped here
        # and never counted twice.
        from ..infra import wind_down as _wd
        _wd_key = _pn_did or "entry"

        async def _wind_down_hook(input_data, tool_use_id, context):
            name = input_data.get("tool_name", "")
            if name == "Bash" and _pn_did is None:
                _bash_started[tool_use_id] = _time.time()
            if name.startswith("mcp__"):
                return {}
            why = _wd.check(_wd_key, name, can_call_done=_pn_did is None)
            if not why:
                return {}
            _record_hook("PreToolUse", tool_use_id, input_data, why)
            return {"hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": why}}

        _hooks["PreToolUse"] = [HookMatcher(hooks=[_wind_down_hook])]
    except Exception:  # noqa: BLE001 — nudge is best-effort, never fatal
        _hooks = None

    # Per-session env: the SDK MERGES this over the inherited environment
    # (PATH etc. preserved), so bare extra keys are safe. See
    # _build_session_env for what is injected and why.
    from .base import session_delegation_id
    _sess_env: dict = _build_session_env(
        plain=_plain, delegation_id=session_delegation_id(self))
    if self._session_token:
        _sess_env[_interrupt.SESSION_TOKEN_ENV] = self._session_token

    from ..runtime.settings import get_float
    _max_buf_mb = get_float("llm_max_buffer_mb", 30.0)
    _max_buf = int(_max_buf_mb * 1024 * 1024)

    # The SDK spawns the CLI with cwd=self.study_dir; if that directory
    # doesn't exist the subprocess dies with a cryptic CLIConnectionError
    # ("Working directory does not exist") mid-delegation. Create it
    # defensively so a missing worker workspace can never abort a run.
    if self.study_dir:
        try:
            self.study_dir.mkdir(parents=True, exist_ok=True)
        except Exception:  # noqa: BLE001 — best-effort; spawn surfaces real errors
            pass

    prompt_str, _next = self._turn_prompt(messages)
    if resume is None:
        resume = _next
    self._record_turn_prompt(prompt_str, resume)
    options = ClaudeAgentOptions(
        system_prompt=self._system_prompt_option(),
        model=self.model,
        cwd=str(self.study_dir) if self.study_dir else None,
        tools=({"type": "preset", "preset": "claude_code"}
               if self.use_default_tools else self.native_tools or []),
        mcp_servers=mcp_servers if mcp_servers else {},
        allowed_tools=self._compute_allowed_tools(qualified_mcp_tools),
        disallowed_tools=_effective_disallowed,
        permission_mode="bypassPermissions",
        strict_mcp_config=bool(mcp_servers),
        # Hermetic session: load NO filesystem settings, so worker/critic
        # subprocesses don't inherit the developer's global ~/.claude hooks
        # (e.g. cbm-code-discovery-gate, which blocked legitimate Read calls
        # for workers AND the critic). Our own hooks are passed
        # programmatically via options.hooks below (audit/#1: fresh hooks).
        setting_sources=[],
        env=_sess_env,
        # Stream-message buffer ceiling. Default 1MB is far too small for a
        # literature reviewer whose tools return full PDFs — a single >1MB
        # MCP tool result overflowed it and FATALLY (non-retried) killed the
        # whole delegation (D003). 30MB clears realistic PDFs; non-PDF
        # results never approach it. A result still exceeding this is caught
        # gracefully below (turn cut short + marker), not a fatal crash.
        # Tune via F3DASM_LLM_MAX_BUFFER_MB.
        max_buffer_size=_max_buf,
        # Partial streaming → a fine-grained heartbeat: the stream emits a
        # StreamEvent sub-second while genuinely generating, so total
        # silence becomes a reliable stall signal and the
        # idle timeout can be bounded without false-positiving a
        # slow-but-working generation.
        include_partial_messages=True,
        **_thinking_options(self.model),
        **({"hooks": _hooks} if _hooks else {}),
        **(
            {"resume": resume, "fork_session": False}
            if resume is not None else {}
        ),
    )

    last_assistant = None
    last_result: Any = None
    _buffer_overflowed = False
    _deliberate_break = False
    _cap_stop = False
    # Background jobs the CLI still tracks (its own background_tasks_changed
    # list). A plain Claude Code session whose turn ends with one running
    # gets the job's completion as its next turn, as in an interactive CLI.
    _bg_tasks: list = []
    _msg_usage: dict[str, dict] = {}
    # The model id each API call's message_start names: the served id
    # even when the stream breaks before any AssistantMessage arrives.
    _served_seen: list[str | None] = [None]
    _cur_msg_id: list[str | None] = [None]
    _counted = [0]
    raise_if_stopped("model call", getattr(self, "abandon_event", None))
    gen = query(prompt=prompt_str, options=options)
    # Idle-stream timeout — turns a silent stream into a retryable
    # TimeoutError. Resets on EVERY stream message. Scoped to model
    # generation: while a tool runs the window stands down (see _phase).
    # MEASURED (the stream_evt instrumentation settled this): the bundled
    # CLI forwards NO ping events — only message lifecycle — so during a
    # mid-generation pause we get ZERO liveness signal. Two supercompressible
    # (Sonnet) runs captured LEGITIMATE (recovered) active-generation gaps of
    # 53.6s AND 252-256s (one mid-tool_use-block composition, one
    # tool_result→next message_start delay). So earlier 60s/180s windows
    # would guillotine legitimate slow generations. The observed ~256s legit
    # gap left only ~44s of headroom under the prior 300s default, and with
    # NO ping liveness signal a longer legit generation is indistinguishable
    # from a stall — so the default is 600s: ample margin over the measured
    # legit gaps while still catching a truly dead (silent-forever) stream in
    # ~10 min. A genuine runaway is the delegation watchdog's concern, not
    # this window's. Knobs (config.yaml runtime block; env overrides):
    # llm_stream_idle_timeout (0 disables); llm_tool_idle_timeout caps tool
    # execution (0 = uncapped).
    from ..runtime.settings import get_float as _get_float
    _idle = (idle_timeout if idle_timeout is not None
             else _get_float("llm_stream_idle_timeout", 600.0))
    _tool_idle = _get_float("llm_tool_idle_timeout", 0.0)

    _phase = _ToolPhase(lambda: bool(_plain and _bg_tasks))

    from .base import append_transcript, capture_enabled

    def _record(msg: Any):
        # Full reasoning + tool-calls + tool-results; StreamEvent partials
        # are skipped (the assembled AssistantMessage carries the text).
        if isinstance(msg, AssistantMessage):
            texts, tools, thinking = [], [], []
            thinking_omitted = 0
            for b in msg.content:
                if isinstance(b, TextBlock):
                    texts.append(b.text)
                elif isinstance(b, ToolUseBlock):
                    tools.append({"name": b.name, "input": b.input,
                                  "tool_use_id": getattr(b, "id", None)})
                else:
                    t = (getattr(b, "thinking", None)
                         or getattr(b, "text", None))
                    if t:
                        thinking.append(t)
                    elif hasattr(b, "thinking"):
                        # A thinking block that arrived with no text
                        # (display "omitted"): counted, so "the model
                        # thought but it was hidden" is distinguishable
                        # from "the model did not think".
                        thinking_omitted += 1
            return {"type": "assistant", "text": "".join(texts),
                    "tools": tools, "thinking": thinking,
                    "thinking_omitted": thinking_omitted,
                    "message_id": getattr(msg, "message_id", None)}
        if isinstance(msg, UserMessage):
            results = []
            for b in (getattr(msg, "content", None) or []):
                results.append({
                    "tool_use_id": getattr(b, "tool_use_id", None),
                    "content": getattr(b, "content", b),
                })
            return {"type": "tool_result", "results": results}
        if isinstance(msg, ResultMessage):
            return {"type": "result",
                    "usage": getattr(msg, "usage", None),
                    "model_usage": getattr(msg, "model_usage", None),
                    "cost_usd": getattr(msg, "total_cost_usd", None)}
        if isinstance(msg, SystemMessage):
            # SystemMessage used to be invisible here entirely (this
            # function returned None for anything it didn't recognize) —
            # so a real compact_boundary (the SDK's own context-
            # compaction event) left NO trace in debug/transcripts/,
            # the viewer, or any post-run analysis. Confirmed empirically
            # (a short forced-window test): a single short session
            # produced 50-119 SystemMessages, the overwhelming majority
            # subtype "thinking_tokens" — a per-token streaming heartbeat,
            # pure noise at transcript granularity (stream_evt already
            # covers liveness). Record everything ELSE verbatim,
            # including (especially) compact_boundary's own metadata.
            if msg.subtype in _SYSTEM_MESSAGE_NOISE_SUBTYPES:
                return None
            return {"type": "system", "subtype": msg.subtype,
                    "data": msg.data}
        return None

    _capture = capture_enabled()
    # Partial-stream checkpointing: an agent that never completes a message
    # (infinite thinking / an unresolved turn) emits only StreamEvents and
    # would otherwise disclose nothing. Buffer the deltas and flush a
    # "partial" record every N events (and on any stream teardown) so the
    # transcript reveals what a stuck turn is doing in near-real-time.
    _PARTIAL_FLUSH_EVERY = 25
    _pbuf: list[str] = []
    _pcount = [0]

    def _extract_delta(ev: Any) -> str:
        if not isinstance(ev, dict):
            return ""
        d = ev.get("delta") or {}
        return (d.get("text") or d.get("thinking")
                or d.get("partial_json") or "")

    def _flush_partial() -> None:
        if _pbuf:
            append_transcript({"type": "partial", "text": "".join(_pbuf),
                               "events": _pcount[0]})
            _pbuf.clear()

    try:
        _stream = (
            _stream_with_idle_timeout(
                gen, _idle,
                tool_timeout=_tool_idle, classify=_phase,
                wall_remaining=(
                    token_clock.wall_remaining if _plain else None),
            )
            if _idle > 0 else gen
        )
        # Measurement clock: the first event's gap below = time-to-first
        # stream event (≈ prefill latency).
        _last_evt = [time.monotonic()]
        async for msg in _stream:
            raise_if_stopped("model call", getattr(self, "abandon_event", None))
            if (_plain and not isinstance(msg, StreamEvent)
                    and token_clock.exhausted()):
                # The wall deadline passes while a tool runs; only a
                # message (the tool result) wakes this loop, so check on
                # every one, not only on stream events.
                token_clock.note_stop()
                _cap_stop = True
                break
            if isinstance(msg, UserMessage):
                _note_background_results(msg)
            if (isinstance(msg, SystemMessage)
                    and msg.subtype == "background_tasks_changed"):
                _bg_tasks[:] = (msg.data or {}).get("tasks") or []
            if isinstance(msg, StreamEvent):
                _track_message_usage(
                    getattr(msg, "event", None), _msg_usage, _cur_msg_id)
                _served_seen[0] = _start_model(
                    getattr(msg, "event", None)) or _served_seen[0]
                _counted[0] += _count_output_tokens(
                    getattr(msg, "event", None), _cur_msg_id)
                if _plain and token_clock.exhausted():
                    # Nothing is sent to the agent: the operator ends
                    # the session, as when a user presses Esc. Closing
                    # the stream (aclose below) takes the CLI down.
                    token_clock.note_stop()
                    _cap_stop = True
                    break
            elif isinstance(msg, AssistantMessage) \
                    and getattr(msg, "usage", None) \
                    and getattr(msg, "message_id", None):
                _msg_usage.setdefault(msg.message_id, dict(msg.usage))
            if _capture:
                if isinstance(msg, StreamEvent):
                    _pcount[0] += 1
                    _ev = getattr(msg, "event", {}) or {}
                    _et = _ev.get("type", "?") if isinstance(
                        _ev, dict) else "?"
                    _now = time.monotonic()
                    _gap = _now - _last_evt[0]
                    _last_evt[0] = _now
                    # Record every NON-delta event (ping, message_start/
                    # stop, content_block_start/stop, message_delta) and any
                    # delta after a >2s pause — so we can see whether the
                    # stream stays alive (pings) during silent/prefill
                    # phases and the true inter-event gap distribution.
                    # This is what settles whether a 60s silence is a dead
                    # stream or a legitimately-slow first token.
                    if _et != "content_block_delta" or _gap > 2.0:
                        append_transcript({
                            "type": "stream_evt", "evt": _et,
                            "gap_s": round(_gap, 2),
                            **_usage_fields(_ev)})
                    _d = _extract_delta(_ev)
                    if _d:
                        _pbuf.append(_d)
                    if _pcount[0] % _PARTIAL_FLUSH_EVERY == 0:
                        _flush_partial()
                else:
                    # A complete message: flush any buffered partial first,
                    # then the structured record.
                    _flush_partial()
                    _rec = _record(msg)
                    if _rec is not None:
                        append_transcript(_rec)
            if isinstance(msg, SystemMessage) and msg.subtype == "init":
                self._cli_tools = list((msg.data or {}).get("tools") or [])
                self._attempt_session_id = (
                    (msg.data or {}).get("session_id")
                    or self._attempt_session_id)
            if isinstance(msg, AssistantMessage) and getattr(
                    msg, "session_id", None):
                self._attempt_session_id = msg.session_id
            if (isinstance(msg, SystemMessage) and msg.subtype == "init"
                    and self.on_init_tools is not None):
                # Unconditional like the compaction record below: which
                # tools the CLI really loaded is a run-level fact.
                try:
                    self.on_init_tools(list((msg.data or {}).get("tools") or []))
                except Exception:  # noqa: BLE001 — a notice never fails a turn
                    pass
            if isinstance(msg, SystemMessage) and msg.subtype == "compact_boundary":
                # Unconditional (not gated on _capture/debug mode): a
                # compaction is a run-level fact an analyst should never
                # have to enable debug transcripts to discover.
                record_stream_diagnostic(
                    "CONTEXT_COMPACTED",
                    "The SDK compacted this session's context "
                    "mid-turn (compact_boundary).",
                    compaction_data=msg.data,
                )
            if isinstance(msg, AssistantMessage):
                last_assistant = msg
                if self.route_watcher and self.route_watcher():
                    _deliberate_break = True
                    break
            elif isinstance(msg, ResultMessage):
                last_result = msg
                if not (_plain and _bg_tasks):
                    break
    except Exception as exc:  # noqa: BLE001
        _m = str(exc).lower()
        if "maximum buffer size" in _m or "exceeded maximum" in _m:
            # Graceful contour: a single tool result (e.g. a huge PDF)
            # overflowed the stream buffer. The old behavior was a fatal,
            # NON-retried crash that killed the whole delegation (D003).
            # Instead, end the turn with what we have + a marker so the
            # agent can retry the fetch smaller — the delegation survives.
            _buffer_overflowed = True
        else:
            raise
    finally:
        if _capture:
            _flush_partial()  # disclose a stuck/torn-down turn's tail
        self._settle_usage(last_result, _msg_usage, last_assistant,
                           counted=_counted[0], served=_served_seen[0])
        _watch = getattr(self, "_background_watch", None)
        if _watch is not None:
            # Depth 2: the CLI itself (depth 1) is not a background job.
            _watch.end(min_depth=2)
        aclose = getattr(gen, "aclose", None)
        if aclose:
            try:
                await aclose()
            except Exception:
                pass

    # A stream that ends with neither a ResultMessage NOR a deliberate
    # route_watcher break, and wasn't already explained by a buffer
    # overflow, is abnormal: the CLI session ended (or the SDK's async
    # generator was exhausted) without ever completing its turn — report
    # 7 (run 20260830T004106, Oscar): the last AssistantMessage carried
    # only a tool call (e.g. Bash/TaskOutput), no result ever arrived,
    # and the near-empty `text` this then returns reads as a malformed
    # report to _invoke_with_report_retry, which silently re-invokes
    # with the ORIGINAL task — restarting the delegation from scratch,
    # orphaning whatever the first attempt launched, with nothing
    # logged anywhere. This does not change that return behaviour (a
    # future decision, pending Elvis) — it only makes the fact visible.
    if (last_result is None and not _deliberate_break
            and not _buffer_overflowed and not _cap_stop):
        _last_tool = None
        if last_assistant is not None:
            for _b in last_assistant.content:
                if isinstance(_b, ToolUseBlock):
                    _last_tool = _b.name
        record_stream_diagnostic(
            "STREAM_ENDED_WITHOUT_RESULT",
            "CLI stream ended without a ResultMessage or a deliberate "
            "route break — the turn may not have completed; its "
            "returned text can look like a malformed report and "
            "trigger a silent report-retry.",
            last_tool_in_flight=_last_tool,
            cli_session_id=getattr(last_assistant, "session_id", None),
        )

    text = ""
    if last_assistant is not None:
        for block in last_assistant.content:
            if isinstance(block, TextBlock):
                text += block.text
    if _buffer_overflowed:
        _note = (
            f"[STREAM NOTE: a tool returned more than {_max_buf_mb:.0f} MB "
            "in a single result and overflowed the message buffer; that "
            "result was dropped and this turn was cut short (the delegation "
            "did NOT crash). Re-run the tool with a smaller/narrower request "
            "— fewer items, or a summary/extract instead of full text.]"
        )
        text = (text + "\n\n" + _note) if text else _note
    return text
_settle_usage(last_result: Any, _msg_usage: dict, last_assistant: Any, counted: int = 0, served: str | None = None) -> None #

Record this attempt's usage and session id. Runs from ainvoke's finally so a stream that RAISES (idle TimeoutError, API error) still reports the usage it had streamed; invoke sums the attempts.

Source code in src/adda/_src/backends/claude.py
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
def _settle_usage(self, last_result: Any, _msg_usage: dict,
                  last_assistant: Any, counted: int = 0,
                  served: str | None = None) -> None:
    """Record this attempt's usage and session id. Runs from ainvoke's
    ``finally`` so a stream that RAISES (idle TimeoutError, API error)
    still reports the usage it had streamed; ``invoke`` sums the
    attempts."""
    # Capture token usage from ResultMessage for run-level accounting.
    if last_result is not None:
        self.last_usage = {
            **(last_result.usage or {}),
            **_cache_split(last_result.usage or {}),
            "total_cost_usd": last_result.total_cost_usd,
        }
    elif _msg_usage:
        # route_watcher broke the stream on the AssistantMessage that
        # closes the run (Done()) before the SDK's ResultMessage -- the
        # only carrier of the session's cumulative usage and cost -- ever
        # arrived. The strategizer's whole run is ONE long stream, so
        # taking just the last message's usage recorded ~1 output token
        # for the entire run (run 20260928T141126). Sum the per-API-call
        # usage the stream itself reported instead. total_cost_usd stays
        # None: cost is a session-level rollup no single message carries,
        # the same "unknown, not zero" convention openai_compatible uses.
        self.last_usage = {
            **_sum_message_usage(_msg_usage.values()),
            "total_cost_usd": None,
        }
    elif last_assistant is not None and getattr(last_assistant, "usage", None):
        # A backend/stream that never sent message_start/delta events or a
        # message id: the lone message's own (possibly stale) usage.
        self.last_usage = {
            **last_assistant.usage, "total_cost_usd": None,
        }
    else:
        self.last_usage = {}

    # Claude reports input_tokens WITHOUT cache tokens, so each count maps
    # one to one onto the telemetry schema.
    u = self.last_usage
    self.last_usage = {**u, **normalized_usage(
        fresh_input=u.get("input_tokens"),
        cache_read=u.get("cache_read_input_tokens"),
        cache_write=u.get("cache_creation_input_tokens"),
        output=u.get("output_tokens"))}
    # The model id the API actually served. The configured model may be
    # an alias ("haiku") that the CLI resolves; only the resolved id has
    # a price and says which model ran.
    _served = getattr(last_assistant, "model", None) or served
    if isinstance(_served, str) and _served:
        self.last_usage["model_resolved"] = _served
    if _msg_usage:
        # Claude's input_tokens excludes cache, so a call's whole prompt
        # is the three input counts together.
        self.last_usage.update(call_shape([
            (m.get("input_tokens") or 0)
            + (m.get("cache_read_input_tokens") or 0)
            + (m.get("cache_creation_input_tokens") or 0)
            for m in _msg_usage.values()]))
        # Per request, so cost pricing can tier each on its own prompt.
        self.last_usage["call_tokens"] = [
            [m.get("input_tokens") or 0,
             m.get("cache_read_input_tokens") or 0,
             m.get("cache_creation_input_tokens") or 0,
             m.get("output_tokens") or 0]
            for m in _msg_usage.values()]

    if token_clock.enabled():
        # The stream counted each call as it ended; a call whose stream
        # events never arrived is counted here from the usage the CLI
        # reported for the whole attempt. A finished attempt with no
        # reported count raises; a failed one keeps its real error.
        out = self.last_usage.get("output_tokens")
        if out is None and last_result is not None:
            token_clock.record(uuid.uuid4().hex, None,
                               "the Claude CLI result")
        if out and out > counted:
            token_clock.record(uuid.uuid4().hex, out - counted,
                               "the Claude CLI result")

    self.last_session_id = (
        getattr(last_result, "session_id", None)
        or getattr(last_assistant, "session_id", None)
    )
    if self.plain_session and self.last_session_id:
        self._session_id = self.last_session_id
    if self._attempt_usages is not None:
        self._attempt_usages.append(dict(self.last_usage))
_invoke_resuming(messages: list[dict], *, idle_timeout: float | None, retry_max: int | None, resume: str | None) -> str #

ainvoke with transient errors retried, continuing the session.

The CLI retries API errors itself, so an error that reaches here (a CLI crash, a stream-idle timeout, an API error after the CLI's own retries) ends a session that may have run for hours. Sending the brief again would start that work from nothing. A retry instead resumes the failed attempt's session with RESUME_NOTICE. It starts again from the brief only when no session id was seen, or when the resume itself fails with a non-transient error (a session the CLI did not keep); RESUME_FAILED records that. Each LLM_RETRY row says which path the retry takes (resumed).

Source code in src/adda/_src/backends/claude.py
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
def _invoke_resuming(
    self, messages: list[dict], *, idle_timeout: float | None,
    retry_max: int | None, resume: str | None,
) -> str:
    """``ainvoke`` with transient errors retried, continuing the session.

    The CLI retries API errors itself, so an error that reaches here (a
    CLI crash, a stream-idle timeout, an API error after the CLI's own
    retries) ends a session that may have run for hours. Sending the
    brief again would start that work from nothing. A retry instead
    resumes the failed attempt's session with RESUME_NOTICE. It starts
    again from the brief only when no session id was seen, or when the
    resume itself fails with a non-transient error (a session the CLI did
    not keep); RESUME_FAILED records that. Each LLM_RETRY row says which
    path the retry takes (``resumed``).
    """
    from .base import is_transient_error, retry_on_transient
    plan = {"messages": messages, "resume": resume, "sid": None}

    def attempt() -> str:
        try:
            return _run_async_safe(self.ainvoke(
                plan["messages"], idle_timeout=idle_timeout,
                resume=plan["resume"]))
        except Exception as exc:  # noqa: BLE001 — re-raised below
            plan["sid"] = (getattr(self, "_attempt_session_id", None)
                           or plan["sid"])
            if (plan["messages"] is messages
                    or is_transient_error(exc)):
                raise
            record_stream_diagnostic(
                "RESUME_FAILED",
                "resuming the session after a dropped connection "
                "failed; starting again from the brief",
                session_id=plan["resume"],
                error=f"{type(exc).__name__}: {str(exc)[:300]}")
        plan["messages"], plan["resume"], plan["sid"] = (
            messages, resume, None)
        return _run_async_safe(self.ainvoke(
            messages, idle_timeout=idle_timeout, resume=resume))

    def on_retry(n: int, max_n: int, exc: BaseException,
                 delay: float) -> None:
        sid = plan["sid"]
        if sid:
            plan["messages"] = [{"role": "user", "content": RESUME_NOTICE}]
            plan["resume"] = sid
        else:
            plan["messages"], plan["resume"] = messages, resume
        sink = getattr(self, "on_retry", None)
        if sink is not None:
            sink(n, max_n, exc, delay, resumed=bool(sid))

    run = getattr(self, "abandon_event", None)
    who = _usage_who()

    def one() -> str:
        return retry_on_transient(
            attempt, max_attempts=retry_max, on_retry=on_retry,
            sleep=lambda d: sleep_unless_stopped(d, "retry backoff", run))

    # A provider usage limit pauses the whole run (infra/usage_pause.py);
    # after the reset this SAME session continues with a short notice.
    for rnd in range(_USAGE_PAUSE_ROUNDS):
        last = rnd == _USAGE_PAUSE_ROUNDS - 1
        usage_pause.wait(who, run)
        try:
            text = usage_pause.injected_limit(who) or one()
        except Exception as exc:  # noqa: BLE001 — re-raised unless a limit
            if last or not (
                    usage_pause.is_limit_text(str(exc), strict=False)
                    and usage_pause.report_limit(str(exc), who)):
                raise
        else:
            if last or not (usage_pause.is_limit_text(text)
                            and usage_pause.report_limit(text, who)):
                return text
        usage_pause.wait(who, run)
        sid = (getattr(self, "_attempt_session_id", None)
               or self.last_session_id)
        if sid:
            plan["messages"] = [{"role": "user",
                                 "content": usage_pause.resume_notice()}]
            plan["resume"] = sid
        else:
            plan["messages"], plan["resume"] = messages, resume
    raise AssertionError("unreachable: the last round returns or raises")
invoke(messages: list[dict], *, idle_timeout: float | None = None, retry_max: int | None = None, resume: str | None = None, on_session_start: Any = None, on_session_end: Any = None, background_watch: Any = None) -> str #

Synchronous wrapper around :meth:ainvoke.

Acquires _lock to serialize concurrent callers of this adapter object (each delegation has its own copy(), so they do not contend). Transient API/network failures are retried with exponential backoff, continuing the failed session where one exists (see _invoke_resuming).

idle_timeout / retry_max override the run-wide stream-idle and retry budgets for THIS call only. A short advisory side-call (verdict validator) passes a tight idle + retry_max=1 so a hung CLI stream aborts in ~that window instead of inheriting a real turn's 5×600s budget (which once froze a whole run for ~89 min).

resume: see :meth:ainvoke.

on_session_start: called with no arguments the instant _lock is actually acquired -- i.e. when this call's real work begins, not when it was merely requested. This is the point at which the call's real work begins, distinct from when it was asked to start. Best-effort: swallows any exception so a broken callback never breaks the real turn.

on_session_end: called as on_session_end(session_id, usage) with THIS call's own session id and token usage while _lock is still held, once the turn is over (also when it raised, with whatever it produced: None / {} if nothing). Both are per-call output; a caller that needs ITS OWN values takes them from here rather than from last_session_id / last_usage. Best-effort like on_session_start.

background_watch: an infra.background_jobs.BackgroundJobWatch. It takes its baseline here and its end snapshot inside ainvoke just before the CLI is closed, while the CLI's children still live.

Source code in src/adda/_src/backends/claude.py
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
def invoke(
    self, messages: list[dict], *,
    idle_timeout: float | None = None, retry_max: int | None = None,
    resume: str | None = None,
    on_session_start: Any = None,
    on_session_end: Any = None,
    background_watch: Any = None,
) -> str:
    """Synchronous wrapper around :meth:`ainvoke`.

    Acquires _lock to serialize concurrent callers of this adapter object
    (each delegation has its own copy(), so they do not contend). Transient API/network
    failures are retried with exponential backoff, continuing the failed
    session where one exists (see ``_invoke_resuming``).

    ``idle_timeout`` / ``retry_max`` override the run-wide stream-idle and
    retry budgets for THIS call only. A short advisory side-call (verdict
    validator) passes a tight idle + ``retry_max=1`` so a hung CLI stream
    aborts in ~that window instead of inheriting a real turn's
    5×600s budget (which once froze a whole run for ~89 min).

    ``resume``: see :meth:`ainvoke`.

    ``on_session_start``: called with no arguments the instant ``_lock``
    is actually acquired -- i.e. when this call's real work begins, not
    when it was merely requested. This is the point at which the call's real work begins,
    distinct from when it was asked to start.
    Best-effort: swallows any exception so a broken callback never
    breaks the real turn.

    ``on_session_end``: called as ``on_session_end(session_id, usage)``
    with THIS call's own session id and token usage while ``_lock`` is
    still held, once the turn is over (also when it raised, with
    whatever it produced: ``None`` / ``{}`` if nothing). Both are
    per-call output; a caller that needs ITS OWN values takes them from
    here rather than from ``last_session_id`` / ``last_usage``. Best-effort
    like ``on_session_start``.

    ``background_watch``: an ``infra.background_jobs.BackgroundJobWatch``.
    It takes its baseline here and its end snapshot inside ``ainvoke``
    just before the CLI is closed, while the CLI's children still live.
    """
    with self._lock:
        self._background_watch = background_watch
        if background_watch is not None:
            background_watch.start()
        if on_session_start is not None:
            try:
                on_session_start()
            except Exception:  # noqa: BLE001
                pass
        # Cleared so a turn that raises before ainvoke() sets them cannot
        # hand its caller the PREVIOUS call's values.
        self.last_session_id = None
        self.last_usage = {}
        self._attempt_usages = []
        try:
            with _interrupt.in_flight(self):
                return self._invoke_resuming(
                    messages, idle_timeout=idle_timeout,
                    retry_max=retry_max, resume=resume)
        finally:
            self.last_usage = _combine_attempt_usage(self._attempt_usages)
            self._attempt_usages = None
            if on_session_end is not None:
                try:
                    on_session_end(
                        self.last_session_id, dict(self.last_usage or {}))
                except Exception:  # noqa: BLE001
                    pass

adda.OllamaAdapter #

Adapter for Ollama-served open-weight models.

Uses ChatOpenAI pointed at Ollama's local OpenAI-compatible endpoint (default http://localhost:11434/v1, overridable via base_url in config.yaml). Ollama needs no real auth, so the API key is the conventional placeholder "local".

Source code in src/adda/_src/backends/ollama.py
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
class OllamaAdapter(OpenAICompatibleAdapter):
    """Adapter for Ollama-served open-weight models.

    Uses ChatOpenAI pointed at Ollama's local OpenAI-compatible endpoint
    (default ``http://localhost:11434/v1``, overridable via ``base_url`` in
    config.yaml). Ollama needs no real auth, so the API key is
    the conventional placeholder ``"local"``.
    """

    DEFAULT_BASE_URL = "http://localhost:11434/v1"
    API_KEY = "local"
    API_KEY_ENV = None

    def _probe_context_window(self) -> int | None:
        """Ollama's SERVED window, which is not the model's trained length.

        ``/v1/models`` reports neither, so this uses Ollama's native
        ``/api/show``. The distinction matters more here than anywhere: a
        Modelfile\'s ``num_ctx`` is what the server will actually accept, and
        Ollama\'s default is far below what any of these models were trained
        for. Taking ``context_length`` from ``model_info`` would report the
        trained window, sail past the real limit, and produce exactly the
        server-side truncation this trimming exists to prevent — so the
        parameter wins and the trained length is only a fallback.
        """
        import re

        import requests
        root = self._base_url.rstrip("/")
        if root.endswith("/v1"):
            root = root[: -len("/v1")]
        try:
            r = requests.post(f"{root}/api/show",
                              json={"model": self.model}, timeout=5)
            r.raise_for_status()
            body = r.json()
        except Exception:
            return None
        # `parameters` is the Modelfile block, e.g. "num_ctx   262144"
        params = body.get("parameters")
        if isinstance(params, str):
            m = re.search(r"^\s*num_ctx\s+(\d+)", params, re.M)
            if m:
                return int(m.group(1))
        info = body.get("model_info")
        if isinstance(info, dict):
            for key, val in info.items():
                if key.endswith(".context_length") and isinstance(val, int):
                    return val
        return None
_turn_retry_max: int | None = None class-attribute instance-attribute #
model = model instance-attribute #
system_prompt = system_prompt instance-attribute #
study_dir = Path(study_dir) if study_dir else None instance-attribute #
native_tools: list[str] = list(native_tools or []) instance-attribute #
use_default_tools: bool = False instance-attribute #
on_init_tools: Any = None instance-attribute #
closure_tools: dict[str, Any] = dict(closure_tools or {}) instance-attribute #
_base_url = base_url or self.DEFAULT_BASE_URL instance-attribute #
_api_key = api_key if api_key is not None else self.API_KEY instance-attribute #
extra_mcp_servers: dict = dict(extra_mcp_servers or {}) instance-attribute #
extra_allowed_tools: list[str] = list(extra_allowed_tools or []) instance-attribute #
persistent: bool = persistent instance-attribute #
max_history_pairs: int = max_history_pairs instance-attribute #
_lock: threading.Lock = threading.Lock() instance-attribute #
_summary_cache: dict[str, str] = {} instance-attribute #
_agent: Any = None instance-attribute #
_bash_session: Any = None instance-attribute #
route_watcher: Any = None instance-attribute #
_oracle_nudge = OracleNudgeBudget() instance-attribute #
_notice_ctx: tuple = (None, None) instance-attribute #
last_usage: dict = {} instance-attribute #
last_session_id: str | None = None instance-attribute #
DEFAULT_BASE_URL = 'http://localhost:11434/v1' class-attribute instance-attribute #
API_KEY = 'local' class-attribute instance-attribute #
API_KEY_ENV = None class-attribute instance-attribute #
select_native_tools(agent_tools) -> list[str] classmethod #

Pick which of an agent's declared tools are NATIVE (CLI) tools.

OpenAI-compatible backends run every tool through LangChain, so a tool is native unless it is one of the Python closure tools the node injects separately. (ClaudeAdapter overrides this with its own CLI-tool set.)

Source code in src/adda/_src/backends/openai_compatible.py
901
902
903
904
905
906
907
908
909
910
911
912
913
@classmethod
def select_native_tools(cls, agent_tools) -> list[str]:
    """Pick which of an agent's declared tools are NATIVE (CLI) tools.

    OpenAI-compatible backends run every tool through LangChain, so a tool
    is native unless it is one of the Python closure tools the node injects
    separately. (ClaudeAdapter overrides this with its own CLI-tool set.)
    """
    picked = [t for t in agent_tools
              if t not in _CLOSURE_TOOL_NAMES and t != DEFAULT_TOOLS]
    if DEFAULT_TOOLS in agent_tools:
        picked += [t for t in DEFAULT_NATIVE_TOOLS if t not in picked]
    return picked
copy() -> OpenAICompatibleAdapter #

An independent adapter for ONE delegation (see ClaudeAdapter.copy): own closure_tools, _lock, built agent, oracle-nudge budget, summary cache and per-call last_* state.

Source code in src/adda/_src/backends/openai_compatible.py
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
def copy(self) -> OpenAICompatibleAdapter:
    """An independent adapter for ONE delegation (see ClaudeAdapter.copy):
    own ``closure_tools``, ``_lock``, built agent, oracle-nudge budget,
    summary cache and per-call ``last_*`` state."""
    import copy as _copy

    from .base import OracleNudgeBudget
    twin = _copy.copy(self)
    twin.closure_tools = dict(self.closure_tools)
    twin.native_tools = list(self.native_tools)
    twin.extra_allowed_tools = list(self.extra_allowed_tools)
    twin.extra_mcp_servers = dict(self.extra_mcp_servers)
    twin._lock = threading.Lock()
    twin._summary_cache = {}
    twin._agent = None
    twin._bash_session = None
    twin._oracle_nudge = OracleNudgeBudget()
    twin._notice_ctx = (None, None)
    twin.last_usage = {}
    twin.last_session_id = None
    return twin
interrupt() -> list[dict] #

SIGINT the shells this adapter started; the turn goes on.

Source code in src/adda/_src/backends/openai_compatible.py
1005
1006
1007
1008
def interrupt(self) -> list[dict]:
    """SIGINT the shells this adapter started; the turn goes on."""
    session = getattr(self, "_bash_session", None)
    return session.interrupt() if session is not None else []
_post_tool_context(tool_name: str, tool_input: dict) -> str | None #

Raw-oracle nudge plus queued campaign notices, same text the Claude backend's post-tool hook returns. Tool closures run on other threads, so the delegation context is the one bound at invoke time.

Source code in src/adda/_src/backends/openai_compatible.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
def _post_tool_context(self, tool_name: str, tool_input: dict) -> str | None:
    """Raw-oracle nudge plus queued campaign notices, same text the Claude
    backend's post-tool hook returns. Tool closures run on other threads,
    so the delegation context is the one bound at invoke time."""
    from ..infra.pending_notices import post_tool_context
    from ..runtime import features
    debug_dir, did = self._notice_ctx
    nudge = (self._oracle_nudge
             if features.enabled("science_monitor") else None)
    return post_tool_context(
        nudge, tool_name, tool_input, debug_dir,
        did or getattr(self, "notice_key", None))
_queued_notices() -> str | None #

What is queued for this agent (messages, campaign notices), as the post-tool text, or None. Drained, so each is shown once.

Source code in src/adda/_src/backends/openai_compatible.py
1023
1024
1025
1026
1027
1028
1029
1030
def _queued_notices(self) -> str | None:
    """What is queued for this agent (messages, campaign notices), as
    the post-tool text, or None. Drained, so each is shown once."""
    from ..infra.pending_notices import drain
    from ..nodes.notices import wrap_notice
    debug_dir, did = self._notice_ctx
    queued = drain(debug_dir, did or getattr(self, "notice_key", None))
    return wrap_notice("\n".join(queued), trailing="") if queued else None
_record_native_error(tool_name: str, message: str, args: dict) -> None #

Write a native tool's error result as an ERROR_RETURN row.

Source code in src/adda/_src/backends/openai_compatible.py
1032
1033
1034
1035
1036
1037
1038
1039
1040
def _record_native_error(self, tool_name: str, message: str,
                         args: dict) -> None:
    """Write a native tool's error result as an ERROR_RETURN row."""
    from .base import append_diagnostic
    debug_dir, did = self._notice_ctx
    if debug_dir is None:
        return
    append_diagnostic(debug_dir, did or "", "ERROR_RETURN", message,
                      tool=tool_name, args=args, fault="agent")
_build_tools() -> list[Any] #
Source code in src/adda/_src/backends/openai_compatible.py
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
def _build_tools(self) -> list[Any]:
    import functools

    from langchain_core.tools import StructuredTool

    from ..prompts.tool_catalog import tool_summary
    self._bash_session = _BashSession(self.study_dir)
    native_map = _native_tool_map(
        self.study_dir, self._post_tool_context, self._record_native_error,
        session=self._bash_session,
        # A callable, not thread-local state: LangGraph runs tools on its
        # own threads. _notice_ctx is set per invoke, on the invoking thread.
        delegation_id=lambda: (self._notice_ctx[1]
                               or getattr(self, "eval_delegation_id",
                                          None)),
        run_config=lambda: (
            str(self._notice_ctx[0] / "run_config.json")
            if self._notice_ctx[0] else None),
        abandon=self._abandon_flag, notices=self._queued_notices)
    tools: list[Any] = [
        native_map[name]
        for name in self.native_tools
        if name in native_map
    ]
    # _agent (and this tool list) is built once and cached forever
    # (see _invoke_once below) -- copy() deliberately returns self, so
    # every delegation to the same worker shares this one instance.
    # nodes/tools/routing.py reassigns closure_tools["Write"] to a
    # freshly-sandboxed closure before EACH delegation, expecting that
    # to take effect live. StructuredTool.from_function(fn, ...) below
    # would otherwise bake in whichever callable `fn` was THE FIRST
    # time this method ran, silently freezing every later delegation
    # to the first one's sandbox (confirmed for real: MathExpert on
    # Ollama, 3 separate _sandboxed_write ERROR_RETURNs all attributing
    # later delegations' writes to the first delegation's own folder —
    # BACKLOG #29). Indirect through a live dict lookup instead, so a
    # later closure_tools[name] reassignment is honoured immediately.
    for name, fn in self.closure_tools.items():
        def _dispatch(*args, _name=name, **kwargs):
            raise_if_stopped(_name, self._abandon_flag())
            return _with_notices(self.closure_tools[_name](*args, **kwargs),
                                 self._queued_notices)
        _dispatch = functools.wraps(fn)(_dispatch)
        # The one-line summary, not the docstring: the full text is
        # already in the system prompt's <tools> section, and
        # from_function's default would send it a second time.
        tools.append(StructuredTool.from_function(
            _dispatch, name=name, description=tool_summary(fn, name)))
    # Inject MCP-equivalent tools for declared extra_allowed_tools.
    if self.extra_allowed_tools:
        lit_tools = _make_literature_tools()
        allowed = set(self.extra_allowed_tools)
        tools += [_guard_native(t, self._record_native_error,
                                lambda: self._notice_ctx[1],
                                self._abandon_flag, self._queued_notices)
                  for t in lit_tools
                  if t.name in allowed]
    return tools
_build_agent() -> Any #
Source code in src/adda/_src/backends/openai_compatible.py
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
def _build_agent(self) -> Any:
    from langchain_core.messages import SystemMessage
    from langchain_openai import ChatOpenAI
    from langgraph.prebuilt import create_react_agent

    from ..prompts.tool_catalog import system_prompt_with_catalog
    max_output = self._resolve_max_output_tokens()
    llm = self._retrying(ChatOpenAI(
        model=self.model, base_url=self._base_url, api_key=self._api_key,
        max_tokens=max_output, max_retries=0,
    ))
    system = system_prompt_with_catalog(
        self.system_prompt, self.closure_tools,
        native=getattr(self, "native_tools", ()))
    return create_react_agent(
        llm,
        self._build_tools(),
        prompt=SystemMessage(content=system),
        pre_model_hook=self._context_hook(system),
    )
_retrying(llm: Any) -> Any #

llm with each call retried on a transient error.

Every retry is reported to on_retry (an LLM_RETRY row), the count starts again for each call, and the backoff ends at once on the run's stop signal. The client's own retries are off (max_retries=0): they are silent and cannot be stopped.

Source code in src/adda/_src/backends/openai_compatible.py
1122
1123
1124
1125
1126
1127
1128
1129
1130
def _retrying(self, llm: Any) -> Any:
    """``llm`` with each call retried on a transient error.

    Every retry is reported to ``on_retry`` (an LLM_RETRY row), the count
    starts again for each call, and the backoff ends at once on the run's
    stop signal. The client's own retries are off (``max_retries=0``):
    they are silent and cannot be stopped.
    """
    return _retrying_chat_model(llm, self._retry_call)
_retry_call(fn: Any) -> Any #

fn(), one model call, retried as _retrying describes.

Source code in src/adda/_src/backends/openai_compatible.py
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
def _retry_call(self, fn: Any) -> Any:
    """``fn()``, one model call, retried as ``_retrying`` describes."""
    from ..infra import usage_pause
    from ..infra.run_abandon import sleep_unless_stopped
    from .base import (
        get_delegation_id,
        get_diagnostic_label,
        retry_on_transient,
    )
    run = self._abandon_flag()
    who = get_delegation_id() or get_diagnostic_label() or "entry"
    while True:
        # A provider usage limit pauses the whole run
        # (infra/usage_pause.py); after the reset the SAME call is sent
        # again, so the loop and its history are untouched.
        usage_pause.wait(who, run)
        raise_if_stopped("model call", run)
        try:
            injected = usage_pause.injected_limit(who)
            if injected:
                raise RuntimeError(injected)
            return retry_on_transient(
                fn, max_attempts=self._turn_retry_max,
                on_retry=getattr(self, "on_retry", None),
                sleep=lambda d: sleep_unless_stopped(
                    d, "retry backoff", run))
        except Exception as exc:  # noqa: BLE001 — re-raised unless a limit
            if not (usage_pause.is_limit_text(str(exc), strict=False)
                    and usage_pause.report_limit(str(exc), who)):
                raise
_abandon_flag() -> Any #

The abandon flag of the run this adapter's node belongs to.

Source code in src/adda/_src/backends/openai_compatible.py
1163
1164
1165
def _abandon_flag(self) -> Any:
    """The abandon flag of the run this adapter's node belongs to."""
    return getattr(self, "abandon_event", None)
_resolve_context_window() -> tuple[int, str] #

(window, source) — explicit setting, then the server, then a declared default.

The source is returned, not just the number, because a run whose window came from a guess and a run whose window came from the server are not the same run. settings.py's precedence applies to the explicit channel, so a study can pin it and an ablation can sweep it.

Source code in src/adda/_src/backends/openai_compatible.py
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
def _resolve_context_window(self) -> tuple[int, str]:
    """``(window, source)`` — explicit setting, then the server, then a
    declared default.

    The source is returned, not just the number, because a run whose window
    came from a guess and a run whose window came from the server are not
    the same run. ``settings.py``'s precedence applies to the explicit
    channel, so a study can pin it and an ablation can sweep it.
    """
    cached = getattr(self, "_ctx_window", None)
    if cached is not None:
        return cached
    from ..runtime import settings
    explicit = settings.get_int("context_window", 0)
    if explicit > 0:
        out = (explicit, "setting")
    else:
        probed = self._probe_context_window()
        out = ((probed, "server") if probed
               else (context_budget.DEFAULT_CONTEXT_WINDOW, "default"))
    self._ctx_window = out
    return out
_resolve_max_output_tokens() -> int | None #

Cap on ONE reply, or None for deliberately uncapped.

This is NOT part of the context_trim feature, and that is on purpose. Trimming decides what the model SEES and is scaffolding whose value is an open question; this bounds what the server will DO and is a safety limit. Gating it on the same knob would mean the arm that answers "is trimming worth it" also removes the only thing stopping a turn generating for an hour, which is not the question being asked. A constant applied to both arms is not a confound.

The resolved number is logged, so a run whose reply was cut short is distinguishable from a run whose model simply stopped.

Source code in src/adda/_src/backends/openai_compatible.py
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
def _resolve_max_output_tokens(self) -> int | None:
    """Cap on ONE reply, or None for deliberately uncapped.

    This is NOT part of the ``context_trim`` feature, and that is on
    purpose. Trimming decides what the model SEES and is scaffolding whose
    value is an open question; this bounds what the server will DO and is
    a safety limit. Gating it on the same knob would mean the arm that
    answers "is trimming worth it" also removes the only thing stopping a
    turn generating for an hour, which is not the question being asked. A
    constant applied to both arms is not a confound.

    The resolved number is logged, so a run whose reply was cut short is
    distinguishable from a run whose model simply stopped.
    """
    from ..runtime import settings
    window, source = self._resolve_context_window()
    explicit = settings.get_int("max_output_tokens", 0)
    cap = context_budget.resolve_max_output_tokens(window, explicit)
    log.info(
        "max output tokens: %s (window %d from %s, setting %d)",
        cap if cap is not None else "uncapped", window, source, explicit,
    )
    return cap
_summarize(prompt: str) -> str #

One summary, from the model this run is already using.

Deliberately not a second, smaller model. A fixed summariser would remove one confound (summary quality no longer varies with the arm) and introduce two: a dependency the study does not otherwise have, and a capability the run itself never had. The interesting hypothesis on cheap models is that scaffolding compensates for capability, and a 27B run whose context is curated by a frontier model is not testing that.

Goes straight to the chat model, NOT through the agent: a summary produced by a tool-loop could call tools, and a pre_model_hook that re-enters the agent is a recursion, not a hook.

Source code in src/adda/_src/backends/openai_compatible.py
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
def _summarize(self, prompt: str) -> str:
    """One summary, from the model this run is already using.

    Deliberately not a second, smaller model. A fixed summariser would
    remove one confound (summary quality no longer varies with the arm)
    and introduce two: a dependency the study does not otherwise have, and
    a capability the run itself never had. The interesting hypothesis on
    cheap models is that scaffolding compensates for capability, and a
    27B run whose context is curated by a frontier model is not testing
    that.

    Goes straight to the chat model, NOT through the agent: a summary
    produced by a tool-loop could call tools, and a pre_model_hook that
    re-enters the agent is a recursion, not a hook.
    """
    from langchain_core.messages import HumanMessage
    from langchain_openai import ChatOpenAI
    llm = ChatOpenAI(
        model=self.model, base_url=self._base_url, api_key=self._api_key,
        max_tokens=self._resolve_max_output_tokens(), max_retries=0,
    )
    reply = self._retry_call(
        lambda: llm.invoke([HumanMessage(content=prompt)]))
    from ..infra import token_clock
    if token_clock.enabled():
        token_clock.record(
            f"summary:{id(reply)}",
            (getattr(reply, "usage_metadata", None) or {}).get(
                "output_tokens"),
            "the model server's summary response")
    return str(reply.content or "")
_context_hook(system_prompt: str) #

A pre_model_hook that keeps one turn inside the served window.

context_policy picks HOW. Both values manage the context; neither is "off", because an unmanaged context is not an experimental arm — it is the crash this subsystem was written to stop (Ollama evicts the original user turn and its renderer then rejects the request with 500 no user query found in messages).

compact (the default) replaces the middle of the conversation with a summary, so a delegation's RESULT survives even when its prose does not. trim drops those messages instead: free, deterministic, and blind to what it is throwing away. The trade is fidelity against determinism — a summary can quietly restate a number, a dropped message obviously cannot — and it is recorded per run so an analysis can condition on it rather than assume it.

The hook returns llm_input_messages, which changes only what is SENT. Graph state keeps every message, so the transcript on disk stays complete and a compacted run is still fully auditable.

Source code in src/adda/_src/backends/openai_compatible.py
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
def _context_hook(self, system_prompt: str):
    """A ``pre_model_hook`` that keeps one turn inside the served window.

    ``context_policy`` picks HOW. Both values manage the context; neither
    is "off", because an unmanaged context is not an experimental arm —
    it is the crash this subsystem was written to stop (Ollama evicts the
    original user turn and its renderer then rejects the request with
    ``500 no user query found in messages``).

    ``compact`` (the default) replaces the middle of the conversation with
    a summary, so a delegation's RESULT survives even when its prose does
    not. ``trim`` drops those messages instead: free, deterministic, and
    blind to what it is throwing away. The trade is fidelity against
    determinism — a summary can quietly restate a number, a dropped
    message obviously cannot — and it is recorded per run so an analysis
    can condition on it rather than assume it.

    The hook returns ``llm_input_messages``, which changes only what is
    SENT. Graph state keeps every message, so the transcript on disk stays
    complete and a compacted run is still fully auditable.
    """
    window, source = self._resolve_context_window()
    reserve = context_budget.estimate_tokens(system_prompt)
    policy = self._context_policy()

    seen: list = [None]

    def _hook(state):
        msgs = (state or {}).get("messages") or []
        if policy == "compact":
            kept, report = context_compaction.compact_to_budget(
                msgs, context_window=window, reserve_tokens=reserve,
                summarize=self._summarize, cache=self._summary_cache)
        else:
            kept, report = context_budget.trim_to_budget(
                msgs, context_window=window, reserve_tokens=reserve)
        # The hook re-runs on every model call and graph state keeps the
        # full history, so an unchanged compaction re-fires each turn.
        # Record a compaction once, and again only when it moves.
        marker = (report.dropped, report.truncated)
        if report.fired and marker != seen[0]:
            seen[0] = marker
            from .base import (
                append_transcript,
                debug_enabled,
                record_stream_diagnostic,
            )
            log.warning(
                "context %s fired: %d message(s) removed, %d truncated "
                "(%d -> %d est. tokens, budget %d, window %d from %s)",
                policy, report.dropped, report.truncated, report.before,
                report.after, report.budget, window, source,
            )
            summary = ""
            if policy == "compact":
                header = context_compaction.summary_header(report.dropped)
                for m in kept:
                    text = context_budget._text_of(m)
                    if text.startswith(header):
                        summary = text[len(header):]
                        break
            record_stream_diagnostic(
                "CONTEXT_COMPACTED",
                f"adda's {policy} context policy fired: "
                f"{report.dropped} message(s) dropped, "
                f"{report.truncated} truncated "
                f"({report.before} -> {report.after} est. tokens).",
                compaction_data={
                    "policy": policy, "window": window,
                    "window_source": source, **report.as_dict()},
            )
            if debug_enabled():
                append_transcript({
                    "type": "ContextCompaction",
                    "text": f"policy={policy} window={window} source={source}",
                    "trim": report.as_dict(),
                    "policy": policy,
                    "summary": summary,
                })
        return {"llm_input_messages": kept}

    return _hook
_context_policy() -> str staticmethod #

"compact" or "trim". An unknown value RAISES.

Silently falling back to a default would make a typo'd arm run as the baseline and report as a null result, which is the one failure an ablation cannot afford.

Source code in src/adda/_src/backends/openai_compatible.py
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
@staticmethod
def _context_policy() -> str:
    """``"compact"`` or ``"trim"``. An unknown value RAISES.

    Silently falling back to a default would make a typo'd arm run as the
    baseline and report as a null result, which is the one failure an
    ablation cannot afford.
    """
    from ..runtime import settings
    value = settings.get_str("context_policy", "compact").strip().lower()
    if value not in ("compact", "trim"):
        raise ValueError(
            f"context_policy must be 'compact' or 'trim', got {value!r}")
    return value
invoke(messages: list[dict], *, idle_timeout: float | None = None, retry_max: int | None = None, on_session_start: Any = None, on_session_end: Any = None, background_watch: Any = None) -> str #

Run one full agent turn; return final assistant text.

Acquires _lock to serialize concurrent callers of this adapter object (each delegation has its own copy(), so they do not contend). Transient API/network failures of each model call are retried with exponential backoff (see _retrying); the turn itself is never restarted.

idle_timeout / retry_max give short advisory side-calls a tight budget. idle_timeout is accepted for signature parity with the Claude backend (HTTP requests carry their own socket timeout, so it is not separately applied here); retry_max caps the attempts of each model call in this turn.

on_session_start: see ClaudeAdapter.invoke's docstring -- called the instant _lock is actually acquired, so a caller queued behind another same-role delegation learns when its wait is really over. Best-effort.

on_session_end: see ClaudeAdapter.invoke's docstring -- called as on_session_end(session_id, usage) under the lock, also when the turn raised (_capture_usage runs on the failure path too). This backend has no resumable sessions, so the id is always None.

Source code in src/adda/_src/backends/openai_compatible.py
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
def invoke(
    self, messages: list[dict], *,
    idle_timeout: float | None = None, retry_max: int | None = None,
    on_session_start: Any = None,
    on_session_end: Any = None,
    background_watch: Any = None,
) -> str:
    """Run one full agent turn; return final assistant text.

    Acquires _lock to serialize concurrent callers of this adapter object
    (each delegation has its own copy(), so they do not contend). Transient API/network
    failures of each model call are retried with exponential backoff (see
    ``_retrying``); the turn itself is never restarted.

    ``idle_timeout`` / ``retry_max`` give short advisory side-calls a tight
    budget. ``idle_timeout`` is accepted for signature parity with the
    Claude backend (HTTP requests carry their own socket timeout, so it is
    not separately applied here); ``retry_max`` caps the attempts of each
    model call in this turn.

    ``on_session_start``: see ClaudeAdapter.invoke's docstring -- called
    the instant ``_lock`` is actually acquired, so a caller queued
    behind another same-role delegation learns when its wait is really
    over. Best-effort.

    ``on_session_end``: see ClaudeAdapter.invoke's docstring -- called
    as ``on_session_end(session_id, usage)`` under the lock, also when
    the turn raised (``_capture_usage`` runs on the failure path too).
    This backend has no resumable sessions, so the id is always None.
    """
    with self._lock:
        if background_watch is not None:
            background_watch.start()
        if on_session_start is not None:
            try:
                on_session_start()
            except Exception:  # noqa: BLE001
                pass
        # Cleared so a turn that raises before _capture_usage() runs
        # cannot hand its caller the PREVIOUS call's values.
        self.last_session_id = None
        self.last_usage = {}
        try:
            # Retries happen per model call (_retrying), never here: a
            # retry of the whole turn restarts it from the brief.
            self._turn_retry_max = retry_max
            with _interrupt.in_flight(self):
                return self._invoke_once(messages)
        finally:
            self._turn_retry_max = None
            if background_watch is not None:
                background_watch.end(min_depth=1)
            if on_session_end is not None:
                try:
                    on_session_end(
                        self.last_session_id, dict(self.last_usage or {}))
                except Exception:  # noqa: BLE001
                    pass
_invoke_once(messages: list[dict]) -> str #

Core invoke logic — build agent if needed, run, return text.

Source code in src/adda/_src/backends/openai_compatible.py
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
def _invoke_once(self, messages: list[dict]) -> str:
    """Core invoke logic — build agent if needed, run, return text."""
    # One invoke == one delegation's worker run; reset the per-delegation
    # nudge cap. The cached agent's tool closures read this live.
    self._oracle_nudge.reset()
    from .base import get_delegation_id, get_run_config_path
    _rc = get_run_config_path()
    self._oracle_nudge.run_config_path = _rc
    self._notice_ctx = (Path(_rc).parent if _rc else None,
                        get_delegation_id())
    if self._agent is None:
        self._agent = self._build_agent()

    lc_msgs = _to_lc_messages(messages)
    # A request with no user turn is malformed, and some providers answer
    # it with an opaque 500 ("no user query found in messages") that names
    # nothing and looks intermittent. It is reachable here: BOTH
    # converters between graph state and this call — nodes.parsing's
    # _to_adapter_messages and _to_lc_messages above — keep only
    # Human/AI messages and silently discard every other role, so a
    # history carrying only system/tool messages filters to an empty
    # list. thread_id is fresh per invoke, so nothing server-side
    # backfills the missing turn either.
    #
    # This check tests for a NON-EMPTY user turn, not merely for a
    # HumanMessage. Testing the type alone is what let the reported 500
    # through: HumanMessage(content="") is a HumanMessage, so the guard
    # passed it, and the provider then rejected the request for having no
    # user query. An empty turn and a missing one are the same thing to
    # the server, so they are the same thing here.
    #
    # Fail here instead, naming what arrived and what survived. This is
    # an instrument as much as a guard: an attributable error is how the
    # question of which shape a real run reaches gets answered rather
    # than argued.
    from langchain_core.messages import HumanMessage as _HumanMessage
    if not any(isinstance(m, _HumanMessage)
               and str(m.content).strip() for m in lc_msgs):
        roles = [str(m.get("role", "user")) for m in messages]
        raise UserlessPayloadError(
            f"refusing to send a request with no user turn: "
            f"{len(messages)} message(s) in with role(s) {roles!r}, "
            f"{len(lc_msgs)} survived conversion. Two things are dropped "
            "by _to_adapter_messages and _to_lc_messages: roles other "
            "than user/human/ai/assistant, and turns whose content is "
            "empty after flattening. Empty content most often means a "
            "message carried only blocks with no readable payload."
        )
    cfg = {"configurable": {"thread_id": str(uuid.uuid4())}}

    # DEBUG: capture reasoning + tool-calls (parity with Claude).
    #
    # Streamed, and recorded AS IT GOES, for two reasons that only show
    # up on a real run. A batch write after invoke() returns means a
    # delegation in flight has no transcript at all — a literature
    # review that runs for half an hour is completely unobservable while
    # it is the thing you most want to watch. And if the call raises
    # (a provider error mid-turn), a write placed after it never
    # happens, so the delegation that failed leaves no trace of what it
    # did before dying — exactly the case where the transcript is worth
    # most. Observed on run 20260906T122744: D002 failed inside
    # langchain_openai and D003 ran 25+ minutes, and neither had a
    # single line on disk.
    from .base import append_transcript, capture_enabled
    _debug = capture_enabled()
    result = None
    seen = 0
    _turn_uid = uuid.uuid4().hex

    def _flush(state) -> None:
        """Append whatever messages are new since the last flush."""
        nonlocal seen
        msgs = (state or {}).get("messages") or []
        for _m in msgs[seen:]:
            append_transcript({
                "type": _m.__class__.__name__,
                "text": str(getattr(_m, "content", "")),
                "tools": getattr(_m, "tool_calls", None) or [],
            })
        seen = max(seen, len(msgs))

    # stream_mode="values" yields the whole state after each step, so the
    # last one seen is the final state invoke() would have returned — the
    # compiled graph's invoke() is itself that loop. Streaming is used on
    # BOTH paths (not just under --debug) so that a turn which dies
    # mid-loop still leaves its partial state behind: invoke() raises with
    # nothing in hand, and the tokens the server already generated for that
    # turn would be unrecoverable.
    try:
        raise_if_stopped("model call", self._abandon_flag())
        for state in self._agent.stream(
            {"messages": lc_msgs}, config=cfg, stream_mode="values",
        ):
            result = state
            self._count_output_tokens(state, len(lc_msgs), _turn_uid)
            if _debug:
                _flush(state)
            raise_if_stopped("model call", self._abandon_flag())
    except Exception:
        # A failed turn keeps everything captured up to the failure.
        if _debug and result is not None:
            _flush(result)
        self._capture_usage(lc_msgs, result)
        raise
    if result is None:
        result = {"messages": []}
    all_msgs = result["messages"]
    last = all_msgs[-1]

    self._capture_usage(lc_msgs, result)

    return str(last.content)
_count_output_tokens(state: dict, n_input: int, uid: str) -> None staticmethod #

Count each model call's output tokens on the run's token clock the moment its AI message appears. A call that carries no count raises: under that clock usage is never estimated.

Source code in src/adda/_src/backends/openai_compatible.py
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
@staticmethod
def _count_output_tokens(state: dict, n_input: int, uid: str) -> None:
    """Count each model call's output tokens on the run's token clock the
    moment its AI message appears. A call that carries no count raises:
    under that clock usage is never estimated."""
    from ..infra import token_clock
    if not token_clock.enabled():
        return
    for i, m in enumerate((state or {}).get("messages") or []):
        if i < n_input or getattr(m, "type", None) != "ai":
            continue
        meta = getattr(m, "usage_metadata", None) or {}
        token_clock.record(f"{uid}:{i}", meta.get("output_tokens"),
                           "the model server's response")
_capture_usage(lc_msgs: list, result: dict | None) -> None #

Set last_usage from every model call this turn produced.

Called on the success path AND from the failure path, because a turn that raises has still spent whatever the server generated before it died — dropping it undercounts by the whole turn, which on a run whose delegations fail is most of the run.

result["messages"] is the WHOLE graph state, i.e. the input messages we passed in (lc_msgs) followed by everything the agent loop generated this call. The model is invoked once per tool-calling round trip, so a strategizer turn that loops several times before its final reply produces several AI messages, each carrying its own usage_metadata — reading only the last one silently dropped every intermediate call's tokens.

Summing must stop at the input boundary: thread_id is fresh per invoke, so the graph never carries earlier turns' messages into this call, and lc_msgs is exactly the prefix the graph started from — the reducer only ever appends. Slicing at len(lc_msgs) therefore counts exactly the messages this invocation produced, never the history that seeded it; summing over the whole state instead would double-count that history on every call and inflate every total.

Only AI messages carry usage_metadata (tool/human messages don't), so anything without it contributes zero rather than raising.

Source code in src/adda/_src/backends/openai_compatible.py
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
def _capture_usage(self, lc_msgs: list, result: dict | None) -> None:
    """Set ``last_usage`` from every model call this turn produced.

    Called on the success path AND from the failure path, because a turn
    that raises has still spent whatever the server generated before it
    died — dropping it undercounts by the whole turn, which on a run whose
    delegations fail is most of the run.

    ``result["messages"]`` is the WHOLE graph state, i.e. the input
    messages we passed in (``lc_msgs``) followed by everything the agent
    loop generated this call. The model is invoked once per tool-calling
    round trip, so a strategizer turn that loops several times before its
    final reply produces several AI messages, each carrying its own
    ``usage_metadata`` — reading only the last one silently dropped every
    intermediate call's tokens.

    Summing must stop at the input boundary: ``thread_id`` is fresh per
    invoke, so the graph never carries earlier turns' messages into this
    call, and ``lc_msgs`` is exactly the prefix the graph started from —
    the reducer only ever appends. Slicing at ``len(lc_msgs)`` therefore
    counts exactly the messages this invocation produced, never the
    history that seeded it; summing over the whole state instead would
    double-count that history on every call and inflate every total.

    Only AI messages carry usage_metadata (tool/human messages don't), so
    anything without it contributes zero rather than raising.
    """
    new_msgs = ((result or {}).get("messages") or [])[len(lc_msgs):]
    total_in = total_out = total_cache_read = total_cache_creation = 0
    total_fresh = 0
    call_inputs: list[int] = []
    for _m in new_msgs:
        meta = getattr(_m, "usage_metadata", None)
        if not meta:
            continue
        call_inputs.append(meta.get("input_tokens", 0) or 0)
        total_in += meta.get("input_tokens", 0) or 0
        total_out += meta.get("output_tokens", 0) or 0
        details = meta.get("input_token_details") or {}
        total_cache_read += details.get("cache_read", 0) or 0
        total_cache_creation += details.get("cache_creation", 0) or 0
        # prompt_tokens is the WHOLE prompt, cached part included; the
        # schema's fresh_input is the rest. Per call, so one call's cache
        # figure can never offset another's.
        total_fresh += max(
            (meta.get("input_tokens", 0) or 0)
            - (details.get("cache_read", 0) or 0)
            - (details.get("cache_creation", 0) or 0), 0)
    self.last_usage = {
        **normalized_usage(
            fresh_input=total_fresh, cache_read=total_cache_read,
            cache_write=total_cache_creation, output=total_out),
        "input_tokens": total_in,
        "output_tokens": total_out,
        "cache_read_input_tokens": total_cache_read,
        "cache_creation_input_tokens": total_cache_creation,
        "total_cost_usd": None,  # not available from open-weight/self-hosted
        # input_tokens above is a sum over the turn's model calls; these
        # show what one call read: how many calls, the first, the largest.
        **call_shape(call_inputs),
    }
_probe_context_window() -> int | None #

Ollama's SERVED window, which is not the model's trained length.

/v1/models reports neither, so this uses Ollama's native /api/show. The distinction matters more here than anywhere: a Modelfile's num_ctx is what the server will actually accept, and Ollama's default is far below what any of these models were trained for. Taking context_length from model_info would report the trained window, sail past the real limit, and produce exactly the server-side truncation this trimming exists to prevent — so the parameter wins and the trained length is only a fallback.

Source code in src/adda/_src/backends/ollama.py
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
def _probe_context_window(self) -> int | None:
    """Ollama's SERVED window, which is not the model's trained length.

    ``/v1/models`` reports neither, so this uses Ollama's native
    ``/api/show``. The distinction matters more here than anywhere: a
    Modelfile\'s ``num_ctx`` is what the server will actually accept, and
    Ollama\'s default is far below what any of these models were trained
    for. Taking ``context_length`` from ``model_info`` would report the
    trained window, sail past the real limit, and produce exactly the
    server-side truncation this trimming exists to prevent — so the
    parameter wins and the trained length is only a fallback.
    """
    import re

    import requests
    root = self._base_url.rstrip("/")
    if root.endswith("/v1"):
        root = root[: -len("/v1")]
    try:
        r = requests.post(f"{root}/api/show",
                          json={"model": self.model}, timeout=5)
        r.raise_for_status()
        body = r.json()
    except Exception:
        return None
    # `parameters` is the Modelfile block, e.g. "num_ctx   262144"
    params = body.get("parameters")
    if isinstance(params, str):
        m = re.search(r"^\s*num_ctx\s+(\d+)", params, re.M)
        if m:
            return int(m.group(1))
    info = body.get("model_info")
    if isinstance(info, dict):
        for key, val in info.items():
            if key.endswith(".context_length") and isinstance(val, int):
                return val
    return None