@yahyahammad/venastine 0.3.8 → 0.3.9

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.
Files changed (128) hide show
  1. package/.env.example +19 -19
  2. package/CONFIG_ARCHITECTURE.md +2030 -2002
  3. package/LICENSE +201 -201
  4. package/README.md +1034 -1034
  5. package/agents/builtin/compactor.md +75 -75
  6. package/agents/builtin/explore.md +77 -77
  7. package/agents/builtin/pipeline-reviewer.md +100 -100
  8. package/agents/builtin/plan.md +106 -106
  9. package/agents/builtin/review.md +74 -74
  10. package/agents/manager.py +261 -261
  11. package/agents/subagent_tool.py +472 -472
  12. package/agents/tui_commands.py +238 -146
  13. package/bin/venastine.mjs +528 -528
  14. package/bin/venastine.py +71 -71
  15. package/cli_commands.py +838 -835
  16. package/config.yaml +13 -0
  17. package/config_edit.py +1301 -1301
  18. package/config_schema.py +971 -966
  19. package/config_update.py +749 -749
  20. package/core/agent_activity.py +256 -256
  21. package/core/ansi.py +452 -452
  22. package/core/approval.py +137 -137
  23. package/core/call_view.py +364 -364
  24. package/core/cancel.py +121 -121
  25. package/core/chatgpt_auth.py +747 -747
  26. package/core/claims_view.py +107 -107
  27. package/core/client.py +2715 -2715
  28. package/core/commands.py +460 -454
  29. package/core/compaction.py +1735 -1735
  30. package/core/config_loader.py +1982 -1982
  31. package/core/connect.py +686 -686
  32. package/core/events.py +123 -123
  33. package/core/file_mentions.py +280 -280
  34. package/core/interaction.py +411 -411
  35. package/core/loop.py +2566 -2566
  36. package/core/memory.py +482 -482
  37. package/core/pipeline_models.py +190 -190
  38. package/core/provider_errors.py +234 -234
  39. package/core/reasoning/authorization.py +130 -130
  40. package/core/reasoning/base.py +219 -219
  41. package/core/reasoning/confidence_scoring.py +484 -484
  42. package/core/reasoning/events.py +149 -149
  43. package/core/reasoning/orchestrator.py +1561 -1561
  44. package/core/reasoning/output_writer.py +345 -345
  45. package/core/reasoning/payload_validation.py +524 -524
  46. package/core/reasoning/pipeline_storage.py +427 -427
  47. package/core/reasoning/scholar.py +458 -458
  48. package/core/reasoning/source_corpus.py +433 -433
  49. package/core/reasoning/source_scoring.py +855 -855
  50. package/core/replay.py +315 -315
  51. package/core/shell_sessions.py +1553 -1553
  52. package/credentials.py +307 -307
  53. package/database.py +333 -333
  54. package/docs/PRIVACY.md +78 -78
  55. package/docs/SECURITY.md +108 -108
  56. package/docs/THIRD_PARTY_NOTICES.md +148 -148
  57. package/env_secrets.py +118 -118
  58. package/json_store.py +343 -343
  59. package/logging_setup.py +295 -295
  60. package/main.py +3433 -3433
  61. package/mcp_client/client.py +733 -733
  62. package/mcp_client/config.py +484 -484
  63. package/mcp_client/registration.py +343 -343
  64. package/memories/manager.py +147 -147
  65. package/memories/tui_commands.py +319 -239
  66. package/package.json +303 -303
  67. package/project_init/config_files.py +282 -282
  68. package/project_init/generator.py +728 -728
  69. package/project_init/manifest.py +418 -418
  70. package/project_init/tui_commands.py +147 -147
  71. package/prompts/critic_pass.md +24 -24
  72. package/prompts/revalidate.md +25 -25
  73. package/prompts/revise.md +17 -17
  74. package/prompts/source_grounding.md +66 -66
  75. package/prompts/system_prompts.py +316 -316
  76. package/providers.json.example +94 -94
  77. package/pyproject.toml +149 -149
  78. package/requirements.txt +295 -295
  79. package/safety/policy_enforcement.py +1082 -1082
  80. package/security/askpass.py +419 -419
  81. package/security/capability.py +207 -207
  82. package/security/confine.py +484 -484
  83. package/security/hosted.py +182 -182
  84. package/security/permissions.py +237 -237
  85. package/security/protected_paths.py +501 -501
  86. package/security/sandbox.py +4108 -4108
  87. package/skills/builtin/math/formal-specification.md +67 -67
  88. package/skills/builtin/math/numerical-methods.md +66 -66
  89. package/skills/builtin/research/experiment-design.md +62 -62
  90. package/skills/builtin/research/reproducibility.md +55 -55
  91. package/skills/builtin/research/source-evaluation.md +70 -70
  92. package/skills/builtin/research/statistical-inference.md +63 -63
  93. package/skills/builtin/research/technical-writing.md +59 -59
  94. package/skills/builtin/software/code-review.md +61 -61
  95. package/skills/builtin/software/debugging.md +61 -61
  96. package/skills/builtin/software/test-design.md +67 -67
  97. package/skills/tui_commands.py +110 -110
  98. package/storage.py +1338 -1338
  99. package/tools/base.py +465 -465
  100. package/tools/builtin/_math_common.py +667 -667
  101. package/tools/builtin/_net_common.py +267 -267
  102. package/tools/builtin/arxiv.py +681 -681
  103. package/tools/builtin/fetch_url.py +371 -371
  104. package/tools/builtin/file_ops.py +720 -720
  105. package/tools/builtin/geometry.py +184 -184
  106. package/tools/builtin/load_skill.py +76 -76
  107. package/tools/builtin/pin.py +227 -227
  108. package/tools/builtin/probability_stats.py +224 -224
  109. package/tools/builtin/project_docs.py +464 -464
  110. package/tools/builtin/remember.py +175 -175
  111. package/tools/builtin/shell.py +980 -980
  112. package/tools/builtin/todo.py +149 -149
  113. package/tools/builtin/web_search.py +328 -328
  114. package/tools/context.py +159 -159
  115. package/tools/isolation.py +387 -387
  116. package/tools/registry.py +1242 -1242
  117. package/tui/app.py +8318 -8307
  118. package/tui/app.tcss +747 -739
  119. package/tui/commands.py +26 -26
  120. package/tui/diffs.py +286 -286
  121. package/tui/history.py +128 -128
  122. package/tui/hosted_driver.py +102 -102
  123. package/tui/markdown.py +1329 -1329
  124. package/tui/meters.py +364 -364
  125. package/tui/ravens.py +146 -146
  126. package/tui/screens.py +1255 -1197
  127. package/tui/themes.py +599 -599
  128. package/tui/widgets.py +3813 -3796
@@ -1,234 +1,234 @@
1
- """
2
- core/provider_errors.py
3
-
4
- Which provider failures are worth another attempt, how long to wait before
5
- it, and the one line that describes a failure (batch 91).
6
-
7
- WHY THIS IS NOT IN core/client.py. AGENTS.md's ownership table gives
8
- client.py one call and provider format translation, and says in so many
9
- words that it does not own retry. The loop owns the attempt; this module
10
- answers the two questions the attempt asks -- "is this one worth another
11
- try?" and "how long do I wait?" -- and holds no state of its own.
12
-
13
- WHY NO SDK IS IMPORTED, HERE OR AT CALL TIME. core/client.py imports each SDK
14
- lazily inside api_initialization, so a harness configured for one provider
15
- never loads the other two -- and the suite installs FAKE openai, anthropic,
16
- google.genai and httpx modules before any test imports anything (the root
17
- conftest). An isinstance check against a real SDK class would load what
18
- client.py deliberately does not, and under test would be comparing against
19
- a fake. So an exception is read by the class names in its MRO and by the
20
- attributes the SDKs themselves define: `status_code` (openai / anthropic
21
- APIStatusError), an int `code` (google.genai errors.APIError), `body` (the
22
- error object an already-open stream carried) and `response.headers`.
23
-
24
- WHAT COUNTS AS TRANSIENT (owner decision, batch 91):
25
-
26
- * a connection failure or a timeout -- openai / anthropic
27
- APIConnectionError and APITimeoutError, an httpx transport error raised
28
- raw while a stream is being read (and by google-genai, whose transport
29
- httpx is since 2.x), a requests ConnectionError / Timeout (google-auth's
30
- token refresh; google-genai 1.0's transport), and the builtin ConnectionError /
31
- TimeoutError;
32
- * HTTP 408, 409, 429 and any 5xx -- the statuses the openai and anthropic
33
- SDKs already retry for themselves before a stream opens;
34
- * an error event inside a stream that had ALREADY opened with 200. The
35
- openai SDK raises its base APIError for it, with no status at all;
36
- anthropic raises APIStatusError carrying the 200 the stream opened with.
37
- Neither SDK retries it, and that is the gap this module exists for:
38
- OpenRouter delivered "The service is temporarily unavailable" and
39
- "Upstream idle timeout exceeded" exactly this way. Retried unless the
40
- error object itself names a 4xx code or a permanent error type.
41
-
42
- Everything else is NOT: a bad request, an auth failure or an unknown model
43
- fails identically on every attempt, and a harness error -- D21's
44
- RuntimeError, a ValueError from message translation -- is a bug, not
45
- weather, and retrying it would only delay the traceback.
46
- """
47
-
48
- from random import random
49
- from time import sleep
50
- from typing import Optional
51
-
52
- #: Beside any 5xx. The same set the openai and anthropic SDKs retry.
53
- RETRYABLE_STATUSES = frozenset({408, 409, 429})
54
-
55
- #: A server's retry-after is honoured up to this, as the SDKs do.
56
- RETRY_AFTER_CAP_S = 60.0
57
-
58
- #: Up to a quarter of the delay either way, so parallel siblings that failed
59
- #: together -- three children of one spawn batch, which is the case that
60
- #: prompted this -- do not all come back in the same instant.
61
- JITTER = 0.25
62
-
63
- #: A transcript line, not a traceback. Long enough for a provider's own
64
- #: sentence and the error object google-genai folds into its message.
65
- DESCRIBE_LIMIT = 500
66
-
67
- _CONNECTION_NAMES = frozenset({
68
- "APIConnectionError", "APITimeoutError", # openai, anthropic
69
- "TransportError", "TimeoutException", # httpx: raw mid-stream; google-genai
70
- "ConnectionError", "Timeout", # requests (google-auth); builtin
71
- "ChunkedEncodingError", # requests, a body cut off mid-read
72
- "TimeoutError", # builtin
73
- })
74
-
75
- #: Error types an open stream's error object can name. Listed in both
76
- #: directions rather than inferred from a suffix: openai's "server_error" and
77
- #: anthropic's "invalid_request_error" share one.
78
- _TRANSIENT_TYPES = frozenset({
79
- "overloaded_error", "api_error", "rate_limit_error", "server_error",
80
- })
81
- _PERMANENT_TYPES = frozenset({
82
- "invalid_request_error", "authentication_error", "permission_error",
83
- "not_found_error", "request_too_large",
84
- })
85
-
86
- #: A 200 that failed schema validation is a mismatch between the SDK and the
87
- #: response, and it will be the same response next time.
88
- _NEVER_TRANSIENT_NAMES = frozenset({"APIResponseValidationError"})
89
-
90
-
91
- def _names(exc: BaseException) -> set:
92
- return {cls.__name__ for cls in type(exc).__mro__}
93
-
94
-
95
- def _as_status(value) -> Optional[int]:
96
- if isinstance(value, str) and value.isdigit():
97
- value = int(value)
98
- if isinstance(value, int) and not isinstance(value, bool) \
99
- and 100 <= value < 600:
100
- return value
101
- return None
102
-
103
-
104
- def _retryable_status(status: int) -> bool:
105
- return status in RETRYABLE_STATUSES or status >= 500
106
-
107
-
108
- def _status(exc: BaseException, names: set) -> Optional[int]:
109
- """The HTTP status an exception carries, or None.
110
-
111
- `code` is read only on something named APIError, because google-genai
112
- is the one SDK that spells its status that way and the attribute name is
113
- far too common to trust anywhere else.
114
- """
115
- status = _as_status(getattr(exc, "status_code", None))
116
- if status is None and "APIError" in names:
117
- status = _as_status(getattr(exc, "code", None))
118
- return status
119
-
120
-
121
- def _body_verdict(body) -> Optional[bool]:
122
- """What an open stream's error object says, or None when it is silent.
123
-
124
- openai hands over the error object itself (`data["error"]`); anthropic
125
- hands over the whole event (`{"type": "error", "error": {...}}`), so the
126
- nested object is preferred when there is one.
127
- """
128
- if not isinstance(body, dict):
129
- return None
130
- error = body["error"] if isinstance(body.get("error"), dict) else body
131
- status = _as_status(error.get("code"))
132
- if status is not None:
133
- return _retryable_status(status)
134
- kind = error.get("type")
135
- if kind in _TRANSIENT_TYPES:
136
- return True
137
- if kind in _PERMANENT_TYPES:
138
- return False
139
- return None
140
-
141
-
142
- def is_transient(exc: BaseException) -> bool:
143
- """Would the same call plausibly succeed if simply made again?"""
144
- names = _names(exc)
145
- if names & _NEVER_TRANSIENT_NAMES:
146
- return False
147
- if names & _CONNECTION_NAMES:
148
- return True
149
- status = _status(exc, names)
150
- if status is not None and status != 200:
151
- return _retryable_status(status)
152
- if "APIError" in names:
153
- # An error event inside a stream that opened: no status (openai) or
154
- # the stream's own 200 (anthropic). The provider has said something
155
- # went wrong mid-generation; unless it also said the request itself
156
- # is at fault, that is the weather this retry is for.
157
- return open_stream_error_is_transient(getattr(exc, "body", None))
158
- return False
159
-
160
-
161
- def open_stream_error_is_transient(body) -> bool:
162
- """The open-stream rule above, for a caller holding only the error object.
163
-
164
- ROADMAP_v3 §83: the ChatGPT plan's `error` event and `response.failed`
165
- arrive as EVENTS -- the openai SDK raises only on a top-level `error`
166
- object, which neither has -- so `core/client.py` reads them and asks
167
- here, rather than keeping a second copy of the rule.
168
- """
169
- verdict = _body_verdict(body)
170
- return True if verdict is None else verdict
171
-
172
-
173
- def retry_after_s(exc: BaseException) -> Optional[float]:
174
- """A server's `retry-after`, in seconds, when the failure carried one.
175
-
176
- Only the delta-seconds form. The HTTP-date form is legal and rare enough
177
- on these APIs that a date parser here would be code with no caller; an
178
- unreadable value is simply ignored and the backoff decides.
179
- """
180
- headers = getattr(getattr(exc, "response", None), "headers", None)
181
- if headers is None:
182
- return None
183
- try:
184
- seconds = float(headers.get("retry-after"))
185
- except (AttributeError, TypeError, ValueError):
186
- return None
187
- if seconds < 0:
188
- return None
189
- return min(seconds, RETRY_AFTER_CAP_S)
190
-
191
-
192
- def backoff_delay(retry: int, base_s: float,
193
- retry_after: Optional[float] = None) -> float:
194
- """Seconds to wait before retry number `retry` (1-based).
195
-
196
- `base_s`, doubled for each retry after the first, with JITTER either way
197
- (owner decision: longer than the SDKs' own half-second start, so a
198
- temporary rate limit is not met with a burst of attempts).
199
-
200
- A server's retry-after can make the wait LONGER, never shorter: a
201
- `retry-after: 0` answering a rate limit is exactly the hammering the
202
- longer base exists to avoid.
203
- """
204
- delay = base_s * (2 ** (retry - 1))
205
- delay *= 1 + JITTER * (2 * random() - 1)
206
- if retry_after is not None:
207
- delay = max(delay, retry_after)
208
- return delay
209
-
210
-
211
- def wait(seconds: float) -> None:
212
- """Sleep before a retry.
213
-
214
- Through `sleep` bound HERE, so a test patches `core.provider_errors.sleep`
215
- and reaches nothing else -- AGENTS.md's `from time import monotonic`
216
- rule: patching the global `time` module froze textual's event loop and
217
- conftest's `settle` along with it, and the suite hung rather than failed.
218
- """
219
- sleep(seconds)
220
-
221
-
222
- def describe(exc: BaseException) -> str:
223
- """`Type: message`, on one line -- the ONE spelling of a failure.
224
-
225
- Shared by the transcript's log handler, the failure stored on a thread
226
- and the retry warning, so the three never describe the same exception
227
- three ways. Not redacted: every caller that shows or
228
- stores it redacts the whole line it is part of.
229
- """
230
- text = " ".join(str(exc).split())
231
- if len(text) > DESCRIBE_LIMIT:
232
- text = text[:DESCRIBE_LIMIT - 1].rstrip() + "…"
233
- name = type(exc).__name__
234
- return f"{name}: {text}" if text else name
1
+ """
2
+ core/provider_errors.py
3
+
4
+ Which provider failures are worth another attempt, how long to wait before
5
+ it, and the one line that describes a failure (batch 91).
6
+
7
+ WHY THIS IS NOT IN core/client.py. AGENTS.md's ownership table gives
8
+ client.py one call and provider format translation, and says in so many
9
+ words that it does not own retry. The loop owns the attempt; this module
10
+ answers the two questions the attempt asks -- "is this one worth another
11
+ try?" and "how long do I wait?" -- and holds no state of its own.
12
+
13
+ WHY NO SDK IS IMPORTED, HERE OR AT CALL TIME. core/client.py imports each SDK
14
+ lazily inside api_initialization, so a harness configured for one provider
15
+ never loads the other two -- and the suite installs FAKE openai, anthropic,
16
+ google.genai and httpx modules before any test imports anything (the root
17
+ conftest). An isinstance check against a real SDK class would load what
18
+ client.py deliberately does not, and under test would be comparing against
19
+ a fake. So an exception is read by the class names in its MRO and by the
20
+ attributes the SDKs themselves define: `status_code` (openai / anthropic
21
+ APIStatusError), an int `code` (google.genai errors.APIError), `body` (the
22
+ error object an already-open stream carried) and `response.headers`.
23
+
24
+ WHAT COUNTS AS TRANSIENT (owner decision, batch 91):
25
+
26
+ * a connection failure or a timeout -- openai / anthropic
27
+ APIConnectionError and APITimeoutError, an httpx transport error raised
28
+ raw while a stream is being read (and by google-genai, whose transport
29
+ httpx is since 2.x), a requests ConnectionError / Timeout (google-auth's
30
+ token refresh; google-genai 1.0's transport), and the builtin ConnectionError /
31
+ TimeoutError;
32
+ * HTTP 408, 409, 429 and any 5xx -- the statuses the openai and anthropic
33
+ SDKs already retry for themselves before a stream opens;
34
+ * an error event inside a stream that had ALREADY opened with 200. The
35
+ openai SDK raises its base APIError for it, with no status at all;
36
+ anthropic raises APIStatusError carrying the 200 the stream opened with.
37
+ Neither SDK retries it, and that is the gap this module exists for:
38
+ OpenRouter delivered "The service is temporarily unavailable" and
39
+ "Upstream idle timeout exceeded" exactly this way. Retried unless the
40
+ error object itself names a 4xx code or a permanent error type.
41
+
42
+ Everything else is NOT: a bad request, an auth failure or an unknown model
43
+ fails identically on every attempt, and a harness error -- D21's
44
+ RuntimeError, a ValueError from message translation -- is a bug, not
45
+ weather, and retrying it would only delay the traceback.
46
+ """
47
+
48
+ from random import random
49
+ from time import sleep
50
+ from typing import Optional
51
+
52
+ #: Beside any 5xx. The same set the openai and anthropic SDKs retry.
53
+ RETRYABLE_STATUSES = frozenset({408, 409, 429})
54
+
55
+ #: A server's retry-after is honoured up to this, as the SDKs do.
56
+ RETRY_AFTER_CAP_S = 60.0
57
+
58
+ #: Up to a quarter of the delay either way, so parallel siblings that failed
59
+ #: together -- three children of one spawn batch, which is the case that
60
+ #: prompted this -- do not all come back in the same instant.
61
+ JITTER = 0.25
62
+
63
+ #: A transcript line, not a traceback. Long enough for a provider's own
64
+ #: sentence and the error object google-genai folds into its message.
65
+ DESCRIBE_LIMIT = 500
66
+
67
+ _CONNECTION_NAMES = frozenset({
68
+ "APIConnectionError", "APITimeoutError", # openai, anthropic
69
+ "TransportError", "TimeoutException", # httpx: raw mid-stream; google-genai
70
+ "ConnectionError", "Timeout", # requests (google-auth); builtin
71
+ "ChunkedEncodingError", # requests, a body cut off mid-read
72
+ "TimeoutError", # builtin
73
+ })
74
+
75
+ #: Error types an open stream's error object can name. Listed in both
76
+ #: directions rather than inferred from a suffix: openai's "server_error" and
77
+ #: anthropic's "invalid_request_error" share one.
78
+ _TRANSIENT_TYPES = frozenset({
79
+ "overloaded_error", "api_error", "rate_limit_error", "server_error",
80
+ })
81
+ _PERMANENT_TYPES = frozenset({
82
+ "invalid_request_error", "authentication_error", "permission_error",
83
+ "not_found_error", "request_too_large",
84
+ })
85
+
86
+ #: A 200 that failed schema validation is a mismatch between the SDK and the
87
+ #: response, and it will be the same response next time.
88
+ _NEVER_TRANSIENT_NAMES = frozenset({"APIResponseValidationError"})
89
+
90
+
91
+ def _names(exc: BaseException) -> set:
92
+ return {cls.__name__ for cls in type(exc).__mro__}
93
+
94
+
95
+ def _as_status(value) -> Optional[int]:
96
+ if isinstance(value, str) and value.isdigit():
97
+ value = int(value)
98
+ if isinstance(value, int) and not isinstance(value, bool) \
99
+ and 100 <= value < 600:
100
+ return value
101
+ return None
102
+
103
+
104
+ def _retryable_status(status: int) -> bool:
105
+ return status in RETRYABLE_STATUSES or status >= 500
106
+
107
+
108
+ def _status(exc: BaseException, names: set) -> Optional[int]:
109
+ """The HTTP status an exception carries, or None.
110
+
111
+ `code` is read only on something named APIError, because google-genai
112
+ is the one SDK that spells its status that way and the attribute name is
113
+ far too common to trust anywhere else.
114
+ """
115
+ status = _as_status(getattr(exc, "status_code", None))
116
+ if status is None and "APIError" in names:
117
+ status = _as_status(getattr(exc, "code", None))
118
+ return status
119
+
120
+
121
+ def _body_verdict(body) -> Optional[bool]:
122
+ """What an open stream's error object says, or None when it is silent.
123
+
124
+ openai hands over the error object itself (`data["error"]`); anthropic
125
+ hands over the whole event (`{"type": "error", "error": {...}}`), so the
126
+ nested object is preferred when there is one.
127
+ """
128
+ if not isinstance(body, dict):
129
+ return None
130
+ error = body["error"] if isinstance(body.get("error"), dict) else body
131
+ status = _as_status(error.get("code"))
132
+ if status is not None:
133
+ return _retryable_status(status)
134
+ kind = error.get("type")
135
+ if kind in _TRANSIENT_TYPES:
136
+ return True
137
+ if kind in _PERMANENT_TYPES:
138
+ return False
139
+ return None
140
+
141
+
142
+ def is_transient(exc: BaseException) -> bool:
143
+ """Would the same call plausibly succeed if simply made again?"""
144
+ names = _names(exc)
145
+ if names & _NEVER_TRANSIENT_NAMES:
146
+ return False
147
+ if names & _CONNECTION_NAMES:
148
+ return True
149
+ status = _status(exc, names)
150
+ if status is not None and status != 200:
151
+ return _retryable_status(status)
152
+ if "APIError" in names:
153
+ # An error event inside a stream that opened: no status (openai) or
154
+ # the stream's own 200 (anthropic). The provider has said something
155
+ # went wrong mid-generation; unless it also said the request itself
156
+ # is at fault, that is the weather this retry is for.
157
+ return open_stream_error_is_transient(getattr(exc, "body", None))
158
+ return False
159
+
160
+
161
+ def open_stream_error_is_transient(body) -> bool:
162
+ """The open-stream rule above, for a caller holding only the error object.
163
+
164
+ ROADMAP_v3 §83: the ChatGPT plan's `error` event and `response.failed`
165
+ arrive as EVENTS -- the openai SDK raises only on a top-level `error`
166
+ object, which neither has -- so `core/client.py` reads them and asks
167
+ here, rather than keeping a second copy of the rule.
168
+ """
169
+ verdict = _body_verdict(body)
170
+ return True if verdict is None else verdict
171
+
172
+
173
+ def retry_after_s(exc: BaseException) -> Optional[float]:
174
+ """A server's `retry-after`, in seconds, when the failure carried one.
175
+
176
+ Only the delta-seconds form. The HTTP-date form is legal and rare enough
177
+ on these APIs that a date parser here would be code with no caller; an
178
+ unreadable value is simply ignored and the backoff decides.
179
+ """
180
+ headers = getattr(getattr(exc, "response", None), "headers", None)
181
+ if headers is None:
182
+ return None
183
+ try:
184
+ seconds = float(headers.get("retry-after"))
185
+ except (AttributeError, TypeError, ValueError):
186
+ return None
187
+ if seconds < 0:
188
+ return None
189
+ return min(seconds, RETRY_AFTER_CAP_S)
190
+
191
+
192
+ def backoff_delay(retry: int, base_s: float,
193
+ retry_after: Optional[float] = None) -> float:
194
+ """Seconds to wait before retry number `retry` (1-based).
195
+
196
+ `base_s`, doubled for each retry after the first, with JITTER either way
197
+ (owner decision: longer than the SDKs' own half-second start, so a
198
+ temporary rate limit is not met with a burst of attempts).
199
+
200
+ A server's retry-after can make the wait LONGER, never shorter: a
201
+ `retry-after: 0` answering a rate limit is exactly the hammering the
202
+ longer base exists to avoid.
203
+ """
204
+ delay = base_s * (2 ** (retry - 1))
205
+ delay *= 1 + JITTER * (2 * random() - 1)
206
+ if retry_after is not None:
207
+ delay = max(delay, retry_after)
208
+ return delay
209
+
210
+
211
+ def wait(seconds: float) -> None:
212
+ """Sleep before a retry.
213
+
214
+ Through `sleep` bound HERE, so a test patches `core.provider_errors.sleep`
215
+ and reaches nothing else -- AGENTS.md's `from time import monotonic`
216
+ rule: patching the global `time` module froze textual's event loop and
217
+ conftest's `settle` along with it, and the suite hung rather than failed.
218
+ """
219
+ sleep(seconds)
220
+
221
+
222
+ def describe(exc: BaseException) -> str:
223
+ """`Type: message`, on one line -- the ONE spelling of a failure.
224
+
225
+ Shared by the transcript's log handler, the failure stored on a thread
226
+ and the retry warning, so the three never describe the same exception
227
+ three ways. Not redacted: every caller that shows or
228
+ stores it redacts the whole line it is part of.
229
+ """
230
+ text = " ".join(str(exc).split())
231
+ if len(text) > DESCRIBE_LIMIT:
232
+ text = text[:DESCRIBE_LIMIT - 1].rstrip() + "…"
233
+ name = type(exc).__name__
234
+ return f"{name}: {text}" if text else name