himring-agent-hooks 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Himring, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.4
2
+ Name: himring-agent-hooks
3
+ Version: 0.1.0
4
+ Summary: Records the passages that Himring returned and the answer that a LiveKit or Pipecat agent gave, and sends them to Himring after the reply.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Dist: himring>=0.1.0,<0.2
8
+ Requires-Dist: livekit-agents>=1.8.11,<2 ; extra == 'livekit'
9
+ Requires-Dist: pipecat-ai>=1.15.0,<2 ; extra == 'pipecat'
10
+ Requires-Python: >=3.11
11
+ Provides-Extra: livekit
12
+ Provides-Extra: pipecat
13
+ Description-Content-Type: text/markdown
14
+
15
+ # himring-agent-hooks
16
+
17
+ This package records what a voice agent built on LiveKit or Pipecat said after it searched a [Himring](https://himring.ai) knowledge base, and it sends those answers to Himring so that Himring can judge them.
18
+
19
+ ```sh
20
+ pip install "himring-agent-hooks[livekit]"
21
+ pip install "himring-agent-hooks[pipecat]"
22
+ ```
23
+
24
+ The package needs Python 3.11 or later, and it calls Himring through the `himring` SDK.
25
+
26
+ ## Recording a conversation
27
+
28
+ ```python
29
+ from himring_agent_hooks import AnswerRecorder, HimringTarget
30
+ from himring_agent_hooks.livekit_hook import attach_livekit_session
31
+
32
+ recorder = AnswerRecorder(
33
+ HimringTarget(
34
+ base_url="https://api.himring.ai",
35
+ api_key="hk_live_...",
36
+ project_id="prj_...",
37
+ knowledge_base_id="kb_...",
38
+ )
39
+ )
40
+ conversation = recorder.conversation(end_user_id="caller-7", call_id="room-12")
41
+ attach_livekit_session(conversation, session)
42
+
43
+ found = await conversation.search("When do you open on Sunday?")
44
+ ```
45
+
46
+ The recorder sends answers in batches of at most 100, every 5 seconds by default or as soon as 100 answers are waiting. It retries a batch when Himring is unreachable or answers 429 or a 5xx status, and it waits as long as the `Retry-After` header asks, up to 60 seconds. The recorder also writes each answer to a spool directory that only your user can read, so that a later recorder can send what an agent left there when its process died.
47
+
48
+ Call `await recorder.close()` before the process exits, so that the recorder can send what it still holds.
49
+
50
+ ## License
51
+
52
+ MIT
@@ -0,0 +1,38 @@
1
+ # himring-agent-hooks
2
+
3
+ This package records what a voice agent built on LiveKit or Pipecat said after it searched a [Himring](https://himring.ai) knowledge base, and it sends those answers to Himring so that Himring can judge them.
4
+
5
+ ```sh
6
+ pip install "himring-agent-hooks[livekit]"
7
+ pip install "himring-agent-hooks[pipecat]"
8
+ ```
9
+
10
+ The package needs Python 3.11 or later, and it calls Himring through the `himring` SDK.
11
+
12
+ ## Recording a conversation
13
+
14
+ ```python
15
+ from himring_agent_hooks import AnswerRecorder, HimringTarget
16
+ from himring_agent_hooks.livekit_hook import attach_livekit_session
17
+
18
+ recorder = AnswerRecorder(
19
+ HimringTarget(
20
+ base_url="https://api.himring.ai",
21
+ api_key="hk_live_...",
22
+ project_id="prj_...",
23
+ knowledge_base_id="kb_...",
24
+ )
25
+ )
26
+ conversation = recorder.conversation(end_user_id="caller-7", call_id="room-12")
27
+ attach_livekit_session(conversation, session)
28
+
29
+ found = await conversation.search("When do you open on Sunday?")
30
+ ```
31
+
32
+ The recorder sends answers in batches of at most 100, every 5 seconds by default or as soon as 100 answers are waiting. It retries a batch when Himring is unreachable or answers 429 or a 5xx status, and it waits as long as the `Retry-After` header asks, up to 60 seconds. The recorder also writes each answer to a spool directory that only your user can read, so that a later recorder can send what an agent left there when its process died.
33
+
34
+ Call `await recorder.close()` before the process exits, so that the recorder can send what it still holds.
35
+
36
+ ## License
37
+
38
+ MIT
@@ -0,0 +1,71 @@
1
+ [project]
2
+ name = "himring-agent-hooks"
3
+ version = "0.1.0"
4
+ description = "Records the passages that Himring returned and the answer that a LiveKit or Pipecat agent gave, and sends them to Himring after the reply."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = ["himring>=0.1.0,<0.2"]
10
+
11
+ [project.optional-dependencies]
12
+ livekit = ["livekit-agents>=1.8.11,<2"]
13
+ pipecat = ["pipecat-ai>=1.15.0,<2"]
14
+
15
+ [build-system]
16
+ requires = ["uv_build==0.12.21"]
17
+ build-backend = "uv_build"
18
+
19
+ [tool.ruff]
20
+ line-length = 100
21
+ src = [
22
+ "src",
23
+ "tests",
24
+ ]
25
+ target-version = "py311"
26
+
27
+ [tool.ruff.lint]
28
+ select = [
29
+ "B",
30
+ "E",
31
+ "F",
32
+ "I",
33
+ "RUF",
34
+ "SIM",
35
+ "UP",
36
+ "S",
37
+ "ANN",
38
+ ]
39
+
40
+ [tool.ruff.lint.per-file-ignores]
41
+ "tests/**/*.py" = [
42
+ "S101",
43
+ "S603",
44
+ ]
45
+ "src/himring_agent_hooks/delivery.py" = ["S311"]
46
+
47
+ [tool.pyright]
48
+ include = [
49
+ "src",
50
+ "tests",
51
+ ]
52
+ pythonVersion = "3.11"
53
+ typeCheckingMode = "strict"
54
+ venvPath = "."
55
+ venv = ".venv"
56
+
57
+ [tool.pytest.ini_options]
58
+ addopts = "-ra -p no:cacheprovider"
59
+ testpaths = ["tests"]
60
+ tmp_path_retention_policy = "none"
61
+
62
+ [tool.uv.sources.himring]
63
+ path = "../../sdks/python"
64
+ editable = true
65
+
66
+ [dependency-groups]
67
+ dev = [
68
+ "pyright==1.1.414",
69
+ "pytest==9.1.1",
70
+ "ruff==0.16.10",
71
+ ]
@@ -0,0 +1,57 @@
1
+ [project]
2
+ name = "himring-agent-hooks"
3
+ version = "0.1.0"
4
+ description = "Records the passages that Himring returned and the answer that a LiveKit or Pipecat agent gave, and sends them to Himring after the reply."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = [
10
+ "himring>=0.1.0,<0.2",
11
+ ]
12
+
13
+ [project.optional-dependencies]
14
+ livekit = [
15
+ "livekit-agents>=1.8.11,<2",
16
+ ]
17
+ pipecat = [
18
+ "pipecat-ai>=1.15.0,<2",
19
+ ]
20
+
21
+ [build-system]
22
+ requires = ["uv_build==0.12.21"]
23
+ build-backend = "uv_build"
24
+
25
+ [tool.ruff]
26
+ line-length = 100
27
+ src = ["src", "tests"]
28
+ target-version = "py311"
29
+
30
+ [tool.ruff.lint]
31
+ select = ["B", "E", "F", "I", "RUF", "SIM", "UP", "S", "ANN"]
32
+
33
+ [tool.ruff.lint.per-file-ignores]
34
+ "tests/**/*.py" = ["S101", "S603"]
35
+ "src/himring_agent_hooks/delivery.py" = ["S311"]
36
+
37
+ [tool.pyright]
38
+ include = ["src", "tests"]
39
+ pythonVersion = "3.11"
40
+ typeCheckingMode = "strict"
41
+ venvPath = "."
42
+ venv = ".venv"
43
+
44
+ [tool.pytest.ini_options]
45
+ addopts = "-ra -p no:cacheprovider"
46
+ testpaths = ["tests"]
47
+ tmp_path_retention_policy = "none"
48
+
49
+ [tool.uv.sources]
50
+ himring = { path = "../../sdks/python", editable = true }
51
+
52
+ [dependency-groups]
53
+ dev = [
54
+ "pyright==1.1.414",
55
+ "pytest==9.1.1",
56
+ "ruff==0.16.10",
57
+ ]
@@ -0,0 +1,43 @@
1
+ from .conversation import QUESTIONS_PER_TURN_MAXIMUM, AnswerConversation, SearchResult
2
+ from .delivery import DEFAULT_DELIVERY_ATTEMPTS, HimringRequestError, HimringTarget
3
+ from .events import (
4
+ ANSWER_BATCH_BODY_BUDGET_BYTES,
5
+ ANSWER_EVENTS_PER_REQUEST_MAXIMUM,
6
+ ANSWER_MAXIMUM_LENGTH,
7
+ CITED_CHUNKS_MAXIMUM,
8
+ FOLLOW_UP_MAXIMUM_LENGTH,
9
+ HANDOFF_REASON_MAXIMUM_LENGTH,
10
+ AnswerEventDraft,
11
+ )
12
+ from .recorder import (
13
+ DEFAULT_BUFFER_MAXIMUM,
14
+ DEFAULT_CLOSE_TIMEOUT_SECONDS,
15
+ DEFAULT_FLUSH_INTERVAL_SECONDS,
16
+ AnswerRecorder,
17
+ RecorderSettings,
18
+ default_spool_directory,
19
+ )
20
+ from .spool_files import SPOOL_ORPHAN_AFTER_SECONDS
21
+
22
+ __all__ = [
23
+ "ANSWER_BATCH_BODY_BUDGET_BYTES",
24
+ "ANSWER_EVENTS_PER_REQUEST_MAXIMUM",
25
+ "ANSWER_MAXIMUM_LENGTH",
26
+ "CITED_CHUNKS_MAXIMUM",
27
+ "DEFAULT_BUFFER_MAXIMUM",
28
+ "DEFAULT_CLOSE_TIMEOUT_SECONDS",
29
+ "DEFAULT_DELIVERY_ATTEMPTS",
30
+ "DEFAULT_FLUSH_INTERVAL_SECONDS",
31
+ "FOLLOW_UP_MAXIMUM_LENGTH",
32
+ "HANDOFF_REASON_MAXIMUM_LENGTH",
33
+ "QUESTIONS_PER_TURN_MAXIMUM",
34
+ "SPOOL_ORPHAN_AFTER_SECONDS",
35
+ "AnswerConversation",
36
+ "AnswerEventDraft",
37
+ "AnswerRecorder",
38
+ "HimringRequestError",
39
+ "HimringTarget",
40
+ "RecorderSettings",
41
+ "SearchResult",
42
+ "default_spool_directory",
43
+ ]
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Awaitable, Callable, Iterable, Sequence
5
+ from dataclasses import dataclass, field
6
+ from typing import Protocol
7
+
8
+ from .events import ANSWER_MAXIMUM_LENGTH, AnswerEventDraft, bounded_long_text, now_timestamp
9
+
10
+ QUESTIONS_PER_TURN_MAXIMUM = 50
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class SearchResult:
15
+ question_id: str
16
+ chunk_ids: tuple[str, ...]
17
+ passages: tuple[dict[str, object], ...]
18
+
19
+
20
+ class ConversationHost(Protocol):
21
+ def record(self, drafts: Sequence[AnswerEventDraft]) -> None: ...
22
+
23
+ def search(
24
+ self, question: str, limit: int | None, end_user_id: str | None, call_id: str | None
25
+ ) -> Awaitable[SearchResult]: ...
26
+
27
+ def flush(self) -> Awaitable[None]: ...
28
+
29
+
30
+ @dataclass(slots=True)
31
+ class _Turn:
32
+ questions: dict[str, frozenset[str]] = field(default_factory=dict[str, frozenset[str]])
33
+ answer: str = ""
34
+
35
+
36
+ class AnswerConversation:
37
+ def __init__(
38
+ self,
39
+ host: ConversationHost,
40
+ logger: logging.Logger,
41
+ end_user_id: str | None = None,
42
+ call_id: str | None = None,
43
+ ) -> None:
44
+ self._host = host
45
+ self._logger = logger
46
+ self._end_user_id = end_user_id
47
+ self._call_id = call_id
48
+ self._current = _Turn()
49
+ self._answered: _Turn | None = None
50
+
51
+ async def search(self, question: str, limit: int | None = None) -> SearchResult:
52
+ result = await self._host.search(question, limit, self._end_user_id, self._call_id)
53
+ self.remember_search(result.question_id, result.chunk_ids)
54
+ return result
55
+
56
+ def remember_search(self, question_id: str, chunk_ids: Iterable[str]) -> None:
57
+ def remember() -> None:
58
+ if self._current.answer:
59
+ self._start_turn()
60
+ if len(self._current.questions) < QUESTIONS_PER_TURN_MAXIMUM:
61
+ self._current.questions[question_id] = frozenset(chunk_ids)
62
+
63
+ self._guarded("remember a search", remember)
64
+
65
+ def record_answer(self, text: str, cited_chunk_ids: Iterable[str] | None = None) -> None:
66
+ def record() -> None:
67
+ turn = self._current
68
+ piece = bounded_long_text(text, ANSWER_MAXIMUM_LENGTH)
69
+ if not turn.questions or piece is None:
70
+ return
71
+ joined = f"{turn.answer}\n{piece}" if turn.answer else piece
72
+ turn.answer = joined[:ANSWER_MAXIMUM_LENGTH]
73
+ occurred_at = now_timestamp()
74
+ cited = None if cited_chunk_ids is None else tuple(dict.fromkeys(cited_chunk_ids))
75
+ self._host.record(
76
+ [
77
+ AnswerEventDraft(
78
+ question_id=question_id,
79
+ answer=turn.answer,
80
+ occurred_at=occurred_at,
81
+ cited_chunk_ids=None
82
+ if cited is None
83
+ else tuple(chunk for chunk in cited if chunk in returned),
84
+ )
85
+ for question_id, returned in turn.questions.items()
86
+ ]
87
+ )
88
+ self._answered = turn
89
+
90
+ self._guarded("record an answer", record)
91
+
92
+ def record_user_message(self, text: str) -> None:
93
+ def record() -> None:
94
+ if not self._current.answer:
95
+ return
96
+ occurred_at = now_timestamp()
97
+ self._host.record(
98
+ [
99
+ AnswerEventDraft(
100
+ question_id=question_id, follow_up=text, occurred_at=occurred_at
101
+ )
102
+ for question_id in self._current.questions
103
+ ]
104
+ )
105
+ self._start_turn()
106
+
107
+ self._guarded("record a user message", record)
108
+
109
+ def record_thumbs_down(self, question_ids: Iterable[str] | None = None) -> None:
110
+ def record() -> None:
111
+ self._host.record(
112
+ [
113
+ AnswerEventDraft(question_id=question_id, thumbs_down=True)
114
+ for question_id in self._targets(question_ids, include_unanswered=False)
115
+ ]
116
+ )
117
+
118
+ self._guarded("record a thumbs-down", record)
119
+
120
+ def record_handoff(self, reason: str, question_ids: Iterable[str] | None = None) -> None:
121
+ def record() -> None:
122
+ self._host.record(
123
+ [
124
+ AnswerEventDraft(question_id=question_id, handoff_reason=reason)
125
+ for question_id in self._targets(question_ids, include_unanswered=True)
126
+ ]
127
+ )
128
+
129
+ self._guarded("record a handoff", record)
130
+
131
+ async def end(self) -> None:
132
+ await self._host.flush()
133
+
134
+ def _targets(self, question_ids: Iterable[str] | None, include_unanswered: bool) -> list[str]:
135
+ if question_ids is not None:
136
+ return list(question_ids)
137
+ current_counts = (
138
+ bool(self._current.questions) if include_unanswered else bool(self._current.answer)
139
+ )
140
+ turn = self._current if current_counts else self._answered
141
+ return [] if turn is None else list(turn.questions)
142
+
143
+ def _start_turn(self) -> None:
144
+ if self._current.answer:
145
+ self._answered = self._current
146
+ self._current = _Turn()
147
+
148
+ def _guarded(self, action: str, work: Callable[[], None]) -> None:
149
+ try:
150
+ work()
151
+ except Exception:
152
+ self._logger.warning("The answer recorder could not %s", action, exc_info=True)
@@ -0,0 +1,185 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import random
5
+ import threading
6
+ import time
7
+ import urllib.parse
8
+ from collections.abc import Callable, Sequence
9
+ from dataclasses import dataclass
10
+ from typing import Literal, TypeVar
11
+
12
+ from himring import Himring, HimringApiError
13
+
14
+ from .events import WireEvent
15
+ from .json_shapes import object_list, object_map
16
+
17
+ DEFAULT_REQUEST_TIMEOUT_SECONDS = 30.0
18
+ DEFAULT_DELIVERY_ATTEMPTS = 6
19
+ HTTP_OK_MINIMUM = 200
20
+ HTTP_OK_MAXIMUM = 299
21
+ HTTP_TOO_MANY_REQUESTS = 429
22
+ HTTP_SERVER_ERROR_MINIMUM = 500
23
+ NO_HTTP_STATUS = 0
24
+ RETRY_AFTER_CEILING_SECONDS = 60.0
25
+ BACKOFF_FIRST_SECONDS = 0.5
26
+ BACKOFF_CEILING_SECONDS = 30.0
27
+ ALLOWED_SCHEMES = frozenset({"http", "https"})
28
+
29
+ ResultT = TypeVar("ResultT")
30
+
31
+
32
+ class HimringRequestError(Exception):
33
+ def __init__(self, status: int, message: str) -> None:
34
+ super().__init__(message)
35
+ self.status = status
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class HimringTarget:
40
+ base_url: str
41
+ api_key: str
42
+ project_id: str
43
+ knowledge_base_id: str
44
+ request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS
45
+
46
+ def __post_init__(self) -> None:
47
+ scheme = urllib.parse.urlsplit(self.base_url).scheme
48
+ if scheme not in ALLOWED_SCHEMES:
49
+ raise ValueError("Give Himring's base URL with http or https.")
50
+
51
+
52
+ class HimringConnection:
53
+ def __init__(self, target: HimringTarget) -> None:
54
+ self.target = target
55
+ self._lock = threading.Lock()
56
+ self._client: Himring | None = None
57
+
58
+ def client(self) -> Himring:
59
+ with self._lock:
60
+ if self._client is None:
61
+ self._client = Himring(
62
+ api_key=self.target.api_key,
63
+ base_url=self.target.base_url,
64
+ timeout_seconds=self.target.request_timeout_seconds,
65
+ )
66
+ return self._client
67
+
68
+ async def call(self, work: Callable[[Himring], ResultT]) -> ResultT:
69
+ return await asyncio.to_thread(lambda: work(self.client()))
70
+
71
+ def close(self) -> None:
72
+ with self._lock:
73
+ client, self._client = self._client, None
74
+ if client is not None:
75
+ client.close()
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class DeliveryReply:
80
+ status: int
81
+ answer: object
82
+ retry_after_seconds: float | None
83
+ refused_before_sending: bool = False
84
+
85
+
86
+ def is_success(status: int) -> bool:
87
+ return HTTP_OK_MINIMUM <= status <= HTTP_OK_MAXIMUM
88
+
89
+
90
+ def reply_status_of(error: HimringApiError) -> int:
91
+ return NO_HTTP_STATUS if error.status is None else error.status
92
+
93
+
94
+ def _record_events(connection: HimringConnection, events: Sequence[WireEvent]) -> DeliveryReply:
95
+ target = connection.target
96
+ try:
97
+ answer = connection.client().record_answer_events(
98
+ project_id=target.project_id,
99
+ knowledge_base_id=target.knowledge_base_id,
100
+ origin="sdk",
101
+ events=events,
102
+ )
103
+ except HimringApiError as error:
104
+ if error.kind == "invalid_input":
105
+ return DeliveryReply(NO_HTTP_STATUS, None, None, refused_before_sending=True)
106
+ return DeliveryReply(reply_status_of(error), None, error.retry_after_seconds)
107
+ return DeliveryReply(HTTP_OK_MINIMUM, answer, None)
108
+
109
+
110
+ def _is_retryable(status: int) -> bool:
111
+ return status in (NO_HTTP_STATUS, HTTP_TOO_MANY_REQUESTS) or status >= HTTP_SERVER_ERROR_MINIMUM
112
+
113
+
114
+ def _retry_delay(reply: DeliveryReply, attempt: int) -> float:
115
+ if reply.retry_after_seconds is not None:
116
+ return min(reply.retry_after_seconds, RETRY_AFTER_CEILING_SECONDS)
117
+ ceiling = min(BACKOFF_CEILING_SECONDS, BACKOFF_FIRST_SECONDS * 2**attempt)
118
+ return random.uniform(0, ceiling)
119
+
120
+
121
+ def _unknown_question_ids(answer: object) -> tuple[str, ...]:
122
+ reply = object_map(answer)
123
+ results = None if reply is None else object_list(reply.get("results"))
124
+ unknown: list[str] = []
125
+ for entry in results or []:
126
+ fields = object_map(entry)
127
+ if fields is None:
128
+ continue
129
+ question_id = fields.get("question_id")
130
+ if fields.get("outcome") == "question_not_found" and isinstance(question_id, str):
131
+ unknown.append(question_id)
132
+ return tuple(unknown)
133
+
134
+
135
+ class Waker:
136
+ def __init__(self) -> None:
137
+ self._waiting: set[asyncio.Future[None]] = set()
138
+
139
+ async def pause(self, seconds: float) -> None:
140
+ waiter: asyncio.Future[None] = asyncio.get_running_loop().create_future()
141
+ self._waiting.add(waiter)
142
+ try:
143
+ await asyncio.wait({waiter}, timeout=seconds)
144
+ finally:
145
+ self._waiting.discard(waiter)
146
+
147
+ def wake_all(self) -> None:
148
+ for waiter in self._waiting:
149
+ if not waiter.done():
150
+ waiter.set_result(None)
151
+
152
+
153
+ @dataclass(frozen=True, slots=True)
154
+ class DeliveryOutcome:
155
+ kind: Literal["delivered", "refused", "gave_up", "deadline_passed"]
156
+ unknown_question_ids: tuple[str, ...] = ()
157
+ reason: str = ""
158
+
159
+
160
+ async def deliver_batch(
161
+ connection: HimringConnection,
162
+ events: Sequence[WireEvent],
163
+ *,
164
+ maximum_attempts: int,
165
+ deadline: Callable[[], float],
166
+ waker: Waker,
167
+ ) -> DeliveryOutcome:
168
+ batch = list(events)
169
+ attempt = 0
170
+ while True:
171
+ reply = await asyncio.to_thread(_record_events, connection, batch)
172
+ if is_success(reply.status):
173
+ return DeliveryOutcome("delivered", _unknown_question_ids(reply.answer))
174
+ attempt += 1
175
+ if reply.refused_before_sending:
176
+ return DeliveryOutcome("refused", reason="the client refused the batch")
177
+ reason = f"status {reply.status}" if reply.status else "no connection"
178
+ if not _is_retryable(reply.status):
179
+ return DeliveryOutcome("refused", reason=reason)
180
+ if attempt >= maximum_attempts:
181
+ return DeliveryOutcome("gave_up", reason=reason)
182
+ delay = _retry_delay(reply, attempt)
183
+ if time.monotonic() + delay > deadline():
184
+ return DeliveryOutcome("deadline_passed")
185
+ await waker.pause(delay)