brain-framework 21.1.0__tar.gz → 21.3.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.
Files changed (73) hide show
  1. {brain_framework-21.1.0 → brain_framework-21.3.0}/PKG-INFO +2 -2
  2. {brain_framework-21.1.0 → brain_framework-21.3.0}/README.md +1 -1
  3. {brain_framework-21.1.0 → brain_framework-21.3.0}/THIRD_PARTY_NOTICES.md +27 -27
  4. {brain_framework-21.1.0 → brain_framework-21.3.0}/pyproject.toml +2 -2
  5. {brain_framework-21.1.0 → brain_framework-21.3.0}/pyproject.toml.orig +2 -2
  6. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/__init__.py +1 -1
  7. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/assistants.py +98 -71
  8. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/channels.py +14 -24
  9. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/cli.py +59 -40
  10. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/collect.py +135 -44
  11. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/graph.py +2 -2
  12. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/health.py +14 -11
  13. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/history.py +1 -1
  14. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/index.py +29 -13
  15. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/markdown.py +2 -1
  16. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/models.py +52 -24
  17. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/pages.py +48 -50
  18. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/records.py +28 -9
  19. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/replies.py +5 -1
  20. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/retrieve.py +91 -31
  21. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/runtime.py +6 -18
  22. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-maintain/SKILL.md +1 -1
  23. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-maintain/references/integrations.md +4 -6
  24. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/SKILL.md +1 -1
  25. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/evidence.md +6 -19
  26. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/learn.md +1 -1
  27. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/links.md +4 -4
  28. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/retrieval.md +2 -2
  29. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/scripts/evidence.py +48 -6
  30. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/templates/concept.md +1 -1
  31. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/starter/evals/retrieval.yaml +4 -1
  32. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/storage.py +16 -0
  33. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/update.py +34 -17
  34. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/validate.py +15 -11
  35. {brain_framework-21.1.0 → brain_framework-21.3.0}/LICENSE +0 -0
  36. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/__main__.py +0 -0
  37. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/config.py +0 -0
  38. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/evaluate.py +0 -0
  39. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/install.py +0 -0
  40. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/links.py +0 -0
  41. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/mcp.py +0 -0
  42. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/messages.py +0 -0
  43. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/ontology.py +0 -0
  44. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/py.typed +0 -0
  45. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/schemas.py +0 -0
  46. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/README.md +0 -0
  47. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/SKILL.md +0 -0
  48. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/references/actions.md +0 -0
  49. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/references/context.md +0 -0
  50. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/references/handoff.md +0 -0
  51. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/scripts/check-handoff.py +0 -0
  52. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/scripts/new-action.py +0 -0
  53. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-action/templates/action.md +0 -0
  54. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-maintain/references/conflicts.md +0 -0
  55. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-maintain/references/operations.md +0 -0
  56. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/SKILL.md +0 -0
  57. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/references/discovery.md +0 -0
  58. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/references/import.md +0 -0
  59. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/references/scan.md +0 -0
  60. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-setup/scripts/inventory.py +0 -0
  61. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/consolidate.md +0 -0
  62. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/decisions.md +0 -0
  63. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/review.md +0 -0
  64. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/references/share.md +0 -0
  65. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/scripts/guarded-write.py +0 -0
  66. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/skills/bf-use/templates/project.md +0 -0
  67. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/starter/AGENTS.md +0 -0
  68. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/starter/concepts/index.md +0 -0
  69. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/starter/concepts/welcome.md +0 -0
  70. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/starter/gitignore +0 -0
  71. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/usage.py +0 -0
  72. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/watch.py +0 -0
  73. {brain_framework-21.1.0 → brain_framework-21.3.0}/src/bf/watch_settings.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: brain-framework
3
- Version: 21.1.0
3
+ Version: 21.3.0
4
4
  Summary: 🧠 Brain Framework: from information to informed actions.
5
5
  Keywords: ai,ai-agents,agent-memory,context-engineering,knowledge-management,local-first,mcp,model-context-protocol,python,second-brain
6
6
  Author: Médéric Hurier
@@ -218,7 +218,7 @@ Use the brain with [Claude Code](https://code.claude.com/docs/en/overview), [Cod
218
218
 
219
219
  > Use the bf CLI. Find why we chose a single product page. Read the source, cite its ref and tell me the project's next action.
220
220
 
221
- It should cite `projects/new-website.md#decision` and name “Draft the product page.” For ongoing use, install the packaged skills into your host's skills folder, such as `~/.claude/skills` for Claude Code:
221
+ It should cite `projects/new-website.md#decision` and name “Draft the product page.” For ongoing use, install the packaged skills into the folder your host discovers (`~/.agents/skills` below; Claude Code uses `~/.claude/skills`):
222
222
 
223
223
  ```bash
224
224
  bf skills ~/.agents/skills
@@ -188,7 +188,7 @@ Use the brain with [Claude Code](https://code.claude.com/docs/en/overview), [Cod
188
188
 
189
189
  > Use the bf CLI. Find why we chose a single product page. Read the source, cite its ref and tell me the project's next action.
190
190
 
191
- It should cite `projects/new-website.md#decision` and name “Draft the product page.” For ongoing use, install the packaged skills into your host's skills folder, such as `~/.claude/skills` for Claude Code:
191
+ It should cite `projects/new-website.md#decision` and name “Draft the product page.” For ongoing use, install the packaged skills into the folder your host discovers (`~/.agents/skills` below; Claude Code uses `~/.claude/skills`):
192
192
 
193
193
  ```bash
194
194
  bf skills ~/.agents/skills
@@ -72,15 +72,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
72
72
  SOFTWARE.
73
73
  ```
74
74
 
75
- ## anyio 4.15.1
75
+ ## anyio 4.16.0
76
76
 
77
77
  Source: <https://github.com/agronholm/anyio>
78
78
 
79
79
  License: `MIT`
80
80
 
81
- Evidence: `anyio-4.15.1.dist-info/licenses/LICENSE`
81
+ Evidence: `anyio-4.16.0.dist-info/licenses/LICENSE`
82
82
 
83
- ### anyio-4.15.1.dist-info/licenses/LICENSE
83
+ ### anyio-4.16.0.dist-info/licenses/LICENSE
84
84
 
85
85
  ```text
86
86
  The MIT License (MIT)
@@ -173,15 +173,15 @@ documentation is licensed as follows:
173
173
  DEALINGS IN THE SOFTWARE.
174
174
  ```
175
175
 
176
- ## click 8.5.0
176
+ ## click 8.5.1
177
177
 
178
178
  Source: <https://github.com/pallets/click/>
179
179
 
180
180
  License: `BSD-3-Clause`
181
181
 
182
- Evidence: `click-8.5.0.dist-info/licenses/LICENSE.txt`
182
+ Evidence: `click-8.5.1.dist-info/licenses/LICENSE.txt`
183
183
 
184
- ### click-8.5.0.dist-info/licenses/LICENSE.txt
184
+ ### click-8.5.1.dist-info/licenses/LICENSE.txt
185
185
 
186
186
  ```text
187
187
  Copyright 2014 Pallets
@@ -872,15 +872,15 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
872
872
  IN THE SOFTWARE.
873
873
  ```
874
874
 
875
- ## opentelemetry-api 1.45.1
875
+ ## opentelemetry-api 1.45.2
876
876
 
877
877
  Source: <https://github.com/open-telemetry/opentelemetry-python>
878
878
 
879
879
  License: `Apache-2.0`
880
880
 
881
- Evidence: `opentelemetry_api-1.45.1.dist-info/licenses/LICENSE`
881
+ Evidence: `opentelemetry_api-1.45.2.dist-info/licenses/LICENSE`
882
882
 
883
- ### opentelemetry_api-1.45.1.dist-info/licenses/LICENSE
883
+ ### opentelemetry_api-1.45.2.dist-info/licenses/LICENSE
884
884
 
885
885
  ```text
886
886
  Apache License
@@ -1126,15 +1126,15 @@ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
1126
1126
  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1127
1127
  ```
1128
1128
 
1129
- ## pydantic 2.14.1
1129
+ ## pydantic 2.14.3
1130
1130
 
1131
1131
  Source: <https://github.com/pydantic/pydantic>
1132
1132
 
1133
1133
  License: `MIT`
1134
1134
 
1135
- Evidence: `pydantic-2.14.1.dist-info/licenses/LICENSE`
1135
+ Evidence: `pydantic-2.14.3.dist-info/licenses/LICENSE`
1136
1136
 
1137
- ### pydantic-2.14.1.dist-info/licenses/LICENSE
1137
+ ### pydantic-2.14.3.dist-info/licenses/LICENSE
1138
1138
 
1139
1139
  ```text
1140
1140
  The MIT License (MIT)
@@ -1160,15 +1160,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1160
1160
  SOFTWARE.
1161
1161
  ```
1162
1162
 
1163
- ## pydantic-core 2.50.1
1163
+ ## pydantic-core 2.50.4
1164
1164
 
1165
1165
  Source: <https://github.com/pydantic/pydantic/tree/main/pydantic-core>
1166
1166
 
1167
1167
  License: `MIT`
1168
1168
 
1169
- Evidence: `pydantic_core-2.50.1.dist-info/licenses/LICENSE`
1169
+ Evidence: `pydantic_core-2.50.4.dist-info/licenses/LICENSE`
1170
1170
 
1171
- ### pydantic_core-2.50.1.dist-info/licenses/LICENSE
1171
+ ### pydantic_core-2.50.4.dist-info/licenses/LICENSE
1172
1172
 
1173
1173
  ```text
1174
1174
  The MIT License (MIT)
@@ -1266,15 +1266,15 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1266
1266
  SOFTWARE.
1267
1267
  ```
1268
1268
 
1269
- ## python-multipart 0.0.32
1269
+ ## python-multipart 0.0.33
1270
1270
 
1271
1271
  Source: <https://github.com/Kludex/python-multipart>
1272
1272
 
1273
1273
  License: `Apache-2.0`
1274
1274
 
1275
- Evidence: `python_multipart-0.0.32.dist-info/licenses/LICENSE.txt`
1275
+ Evidence: `python_multipart-0.0.33.dist-info/licenses/LICENSE.txt`
1276
1276
 
1277
- ### python_multipart-0.0.32.dist-info/licenses/LICENSE.txt
1277
+ ### python_multipart-0.0.33.dist-info/licenses/LICENSE.txt
1278
1278
 
1279
1279
  ```text
1280
1280
  Apache License
@@ -1635,15 +1635,15 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1635
1635
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1636
1636
  ```
1637
1637
 
1638
- ## sse-starlette 3.6.0
1638
+ ## sse-starlette 3.7.0
1639
1639
 
1640
1640
  Source: <https://github.com/sysid/sse-starlette>
1641
1641
 
1642
1642
  License: `BSD-3-Clause`
1643
1643
 
1644
- Evidence: `sse_starlette-3.6.0.dist-info/licenses/LICENSE`
1644
+ Evidence: `sse_starlette-3.7.0.dist-info/licenses/LICENSE`
1645
1645
 
1646
- ### sse_starlette-3.6.0.dist-info/licenses/LICENSE
1646
+ ### sse_starlette-3.7.0.dist-info/licenses/LICENSE
1647
1647
 
1648
1648
  ```text
1649
1649
  Copyright © 2020, [sysid](https://sysid.github.io/).
@@ -1749,7 +1749,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1749
1749
  THE SOFTWARE.
1750
1750
  ```
1751
1751
 
1752
- ## typer 0.27.3
1752
+ ## typer 0.28.0
1753
1753
 
1754
1754
  Source: <https://github.com/fastapi/typer>
1755
1755
 
@@ -1757,9 +1757,9 @@ License: `MIT`
1757
1757
 
1758
1758
  The distribution vendors code adapted from Click in `typer/_click/`; its bundled `BSD-3-Clause` license is included below.
1759
1759
 
1760
- Evidence: `typer-0.27.3.dist-info/licenses/LICENSE`
1760
+ Evidence: `typer-0.28.0.dist-info/licenses/LICENSE`
1761
1761
 
1762
- ### typer-0.27.3.dist-info/licenses/LICENSE
1762
+ ### typer-0.28.0.dist-info/licenses/LICENSE
1763
1763
 
1764
1764
  ```text
1765
1765
  The MIT License (MIT)
@@ -2112,15 +2112,15 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2112
2112
  PERFORMANCE OF THIS SOFTWARE.
2113
2113
  ```
2114
2114
 
2115
- ## typing-inspection 0.4.4
2115
+ ## typing-inspection 0.4.5
2116
2116
 
2117
2117
  Source: <https://github.com/pydantic/typing-inspection>
2118
2118
 
2119
2119
  License: `MIT`
2120
2120
 
2121
- Evidence: `typing_inspection-0.4.4.dist-info/licenses/LICENSE`
2121
+ Evidence: `typing_inspection-0.4.5.dist-info/licenses/LICENSE`
2122
2122
 
2123
- ### typing_inspection-0.4.4.dist-info/licenses/LICENSE
2123
+ ### typing_inspection-0.4.5.dist-info/licenses/LICENSE
2124
2124
 
2125
2125
  ```text
2126
2126
  MIT License
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "brain-framework"
3
- version = "21.1.0"
3
+ version = "21.3.0"
4
4
  description = "🧠 Brain Framework: from information to informed actions."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.14"
@@ -170,5 +170,5 @@ dev = [
170
170
  "ruff>=0.16.6",
171
171
  "ty>=0.0.70,<0.1",
172
172
  "validate-pyproject[all]>=0.25",
173
- "zensical>=0.0.59,<0.1",
173
+ "zensical>=0.1.0,<0.2",
174
174
  ]
@@ -1,7 +1,7 @@
1
1
  # https://packaging.python.org/en/latest/specifications/pyproject-toml/
2
2
  [project]
3
3
  name = "brain-framework"
4
- version = "21.1.0"
4
+ version = "21.3.0"
5
5
  description = "🧠 Brain Framework: from information to informed actions."
6
6
  readme = "README.md"
7
7
  requires-python = ">=3.14"
@@ -74,7 +74,7 @@ dev = [
74
74
  "ty>=0.0.70,<0.1",
75
75
  # The extra validates classifiers offline instead of downloading them or skipping the check.
76
76
  "validate-pyproject[all]>=0.25",
77
- "zensical>=0.0.59,<0.1",
77
+ "zensical>=0.1.0,<0.2",
78
78
  ]
79
79
 
80
80
  [tool.ruff]
@@ -2,7 +2,7 @@
2
2
 
3
3
  import os
4
4
 
5
- __version__ = "21.1.0"
5
+ __version__ = "21.3.0"
6
6
 
7
7
 
8
8
  def main() -> None:
@@ -48,6 +48,7 @@ from bf.models import (
48
48
  decode,
49
49
  digest,
50
50
  encode,
51
+ reason,
51
52
  retried,
52
53
  timestamp,
53
54
  )
@@ -84,10 +85,6 @@ class StreamStoppedError(Error):
84
85
  """A stream worker ended outside shutdown: its input would silently stop being accepted, so watch stops."""
85
86
 
86
87
 
87
- def _reason(error: BaseException, fallback: str = "assistant files are inaccessible") -> str:
88
- return str(error) if isinstance(error, Error) else fallback
89
-
90
-
91
88
  def prepare(
92
89
  store: Store,
93
90
  name: str,
@@ -143,8 +140,8 @@ def prepare(
143
140
 
144
141
  def read_failure(channel: str, error: BaseException) -> str:
145
142
  """A failed read poll, worded alike by bf update and watch, naming the channel's read log."""
146
- reason = _reason(error, "its files are inaccessible").removeprefix(f"channel {channel}: ")
147
- return f"channel {channel}: read failed: {reason}; see {log_path(f'channel.{channel}.read')}"
143
+ cause = reason(error, "its files are inaccessible").removeprefix(f"channel {channel}: ")
144
+ return f"channel {channel}: read failed: {cause}; see {log_path(f'channel.{channel}.read')}"
148
145
 
149
146
 
150
147
  def _oversized(store: Store, work: Work) -> str:
@@ -291,11 +288,62 @@ def _exposed(work: Work) -> AbstractContextManager[None]:
291
288
  return exposing(BF_TRIGGER=work.kind, BF_SCHEDULE=_schedule(work), BF_START=work.start, BF_END=work.end)
292
289
 
293
290
 
291
+ def _recorded(
292
+ work: Work, reply: str, wake: Requested | None, metadata: dict[str, JsonValue]
293
+ ) -> tuple[Record, list[Outgoing]]:
294
+ """The record and deliveries an answer makes. The error never quotes the output."""
295
+ try:
296
+ record = Record(
297
+ id=datetime.fromisoformat(work.end).astimezone(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + work.id[-8:],
298
+ title=reply_title(work.assistant, reply),
299
+ text=reply,
300
+ time=work.end,
301
+ attributes={
302
+ "observed": work.end,
303
+ "trigger": work.kind,
304
+ "job": work.id,
305
+ "window": {"start": work.start, "end": work.end},
306
+ **({"input": work.text} if work.text else {}),
307
+ **({"output": metadata} if metadata else {}),
308
+ **({"wake": wake.model_dump()} if wake else {}),
309
+ **(
310
+ {
311
+ "channel": work.origin.channel,
312
+ "sender": work.origin.message.sender,
313
+ "conversation": work.origin.message.conversation,
314
+ }
315
+ if work.origin
316
+ else {}
317
+ ),
318
+ },
319
+ )
320
+ replies = (
321
+ [
322
+ Outgoing(
323
+ id=digest(f"{work.id}:{route.channel}:{route.conversation}".encode())[:32],
324
+ text=reply,
325
+ conversation=route.conversation,
326
+ reply_to=route.reply_to,
327
+ )
328
+ for route in work.routes
329
+ ]
330
+ if reply.strip()
331
+ else []
332
+ )
333
+ except ValidationError:
334
+ # Pydantic's message quotes the invalid input: report the cause, never the content.
335
+ raise Error(
336
+ "assistant output cannot become a record: it holds invalid Unicode or more than 2 MiB outside its "
337
+ f"message; see {log_path(work.assistant)}"
338
+ ) from None
339
+ return record, replies
340
+
341
+
294
342
  def _attempt(store: Store, work: Work, runner: Runner, argv: list[str], stdin: bytes) -> bytes:
295
- """Run the harness once, telling it why it runs; an answer that does not parse fails the attempt."""
343
+ """Run the harness once, telling it why it runs; an answer that cannot be parsed or recorded fails the attempt."""
296
344
  with _exposed(work):
297
345
  raw = runner(argv, work.settings, store, work.assistant, stdin)
298
- _answer(raw, work)
346
+ _recorded(work, *_answer(raw, work))
299
347
  return raw
300
348
 
301
349
 
@@ -318,8 +366,8 @@ def _gate(store: Store, work: Work, runner: Runner) -> list[JsonValue] | None:
318
366
  f"see {log_path(name)}"
319
367
  ) from None
320
368
  except (Error, OSError, UnicodeError) as error:
321
- reason = str(error) if isinstance(error, Error) else f"gate of schedule {schedule} failed; see {log_path(name)}"
322
- raise GateError(reason) from error
369
+ cause = reason(error, f"gate of schedule {schedule} failed; see {log_path(name)}")
370
+ raise GateError(cause) from error
323
371
  events: list[JsonValue] = [event.model_dump(exclude_defaults=True) for event in reply.events]
324
372
  if len(encode(events)) > GATE_EVENT_BYTES:
325
373
  # Saved events are reused on every retry: an oversized set would fail each prompt the same way.
@@ -401,7 +449,6 @@ def _execute(store: Store, key: str, runner: Runner) -> dict[str, object]:
401
449
  argv, stdin = expanded(store, work, queue)
402
450
  if not queue.claim(key):
403
451
  raise Error("assistant job is no longer pending; inspect bf queue")
404
- queue.lifecycle("assistant.started", work.assistant, {"job": key, "kind": work.kind})
405
452
  queue.answer(key, _attempt(store, work, runner, argv, stdin))
406
453
  row = queue.get(key)
407
454
  if row["state"] == "answered":
@@ -410,43 +457,7 @@ def _execute(store: Store, key: str, runner: Runner) -> dict[str, object]:
410
457
  raise Error("assistant returned no response to an incoming message; inspect the saved answer")
411
458
  if work.kind in {"schedule", "wake"} and not reply and not metadata:
412
459
  return _quiet(store, queue, work, key, wake)
413
- record = Record(
414
- id=datetime.fromisoformat(work.end).astimezone(UTC).strftime("%Y%m%dT%H%M%SZ") + "-" + work.id[-8:],
415
- title=reply_title(work.assistant, reply),
416
- text=reply,
417
- time=work.end,
418
- attributes={
419
- "observed": work.end,
420
- "trigger": work.kind,
421
- "job": key,
422
- "window": {"start": work.start, "end": work.end},
423
- **({"input": work.text} if work.text else {}),
424
- **({"output": metadata} if metadata else {}),
425
- **({"wake": wake.model_dump()} if wake else {}),
426
- **(
427
- {
428
- "channel": work.origin.channel,
429
- "sender": work.origin.message.sender,
430
- "conversation": work.origin.message.conversation,
431
- }
432
- if work.origin
433
- else {}
434
- ),
435
- },
436
- )
437
- replies = (
438
- [
439
- Outgoing(
440
- id=digest(f"{key}:{route.channel}:{route.conversation}".encode())[:32],
441
- text=reply,
442
- conversation=route.conversation,
443
- reply_to=route.reply_to,
444
- )
445
- for route in work.routes
446
- ]
447
- if reply.strip()
448
- else []
449
- )
460
+ record, replies = _recorded(work, reply, wake, metadata)
450
461
  queue.prepare(work, record, replies, wake)
451
462
  row = queue.get(key)
452
463
  saved = Prepared.model_validate_json(str(row["prepared"]))
@@ -486,14 +497,16 @@ def _execute(store: Store, key: str, runner: Runner) -> dict[str, object]:
486
497
  else "assistant execution or saved reply failed; inspect its local log"
487
498
  )
488
499
  if current["state"] not in {"complete", "cancelled"}:
489
- # A harness that never started cannot have acted: its job fails plainly instead of uncertainly. A
490
- # failed gate retries by itself: no harness ran.
500
+ # A harness that never started cannot have acted: its job fails plainly instead of uncertainly, and
501
+ # retries like a failed attempt when the run is idempotent. A failed gate retries by itself: no
502
+ # harness ran.
503
+ idempotent = retried(work.settings.idempotent, work.kind)
491
504
  queue.fail(
492
505
  key,
493
506
  message,
494
507
  uncertain=current["state"] == "running" and not isinstance(error, NotStartedError),
495
- idempotent=retried(work.settings.idempotent, work.kind),
496
- retry=isinstance(error, GateError),
508
+ idempotent=idempotent,
509
+ retry=isinstance(error, GateError) or (idempotent and isinstance(error, NotStartedError)),
497
510
  )
498
511
  with suppress(Error, OSError):
499
512
  append_log(store, work.assistant, message)
@@ -526,6 +539,10 @@ def deliver(
526
539
  key, name = str(delivery["id"]), str(delivery["channel"])
527
540
  lock = f".delivery-{digest(key.encode())}"
528
541
  with collecting(store, lock):
542
+ # Read it again under the lock: another process may have sent, failed or rescheduled it meanwhile.
543
+ delivery = queue.delivery(job=job, key=key, names=names)
544
+ if delivery is None:
545
+ return False
529
546
  try:
530
547
  try:
531
548
  command = Send.model_validate_json(str(delivery["command"]))
@@ -547,16 +564,18 @@ def deliver(
547
564
  receipt = channels.send(store, name, command, message, runner=runner)
548
565
  queue.delivered(key, name, message, receipt)
549
566
  except (Error, OSError, UnicodeError) as error:
550
- reason = str(error) if isinstance(error, Error) else "channel send failed; inspect its local log"
567
+ cause = reason(error, "channel send failed; inspect its local log")
551
568
  attempts = int(str(delivery["attempts"])) + 1
552
- # A send command that never started sent nothing, so it retries like an idempotent one.
553
- outcome, reason, due = retry_policy(
554
- command.idempotent or isinstance(error, NotStartedError),
569
+ # A send command that never started sent nothing, so it retries like an idempotent one. A misrouted
570
+ # send may have posted elsewhere: it waits for inspection even on an idempotent channel.
571
+ outcome, cause, due = retry_policy(
572
+ (command.idempotent and not isinstance(error, channels.MisroutedError))
573
+ or isinstance(error, NotStartedError),
555
574
  delivery["job"] is not None,
556
575
  attempts,
557
- reason,
576
+ cause,
558
577
  )
559
- queue.delivery_failed(key, reason, outcome=outcome, due=due)
578
+ queue.delivery_failed(key, cause, outcome=outcome, due=due)
560
579
  except BaseException:
561
580
  # Ctrl-C or SIGTERM ends this process: record the send now, not at the next recovery pass.
562
581
  with suppress(Error, OSError):
@@ -630,9 +649,7 @@ def manual(
630
649
  raise Error("answer saved but delivery is unresolved; inspect bf queue before retrying")
631
650
  result["status"] = "ran"
632
651
  except (Error, OSError, UnicodeError) as error:
633
- result.update(
634
- status="failed", error=str(error) if isinstance(error, Error) else "assistant files are inaccessible"
635
- )
652
+ result.update(status="failed", error=reason(error, "assistant files are inaccessible"))
636
653
  return {"ok": result["status"] == "ran", "dry_run": dry_run, "assistants": [result]}
637
654
 
638
655
 
@@ -701,7 +718,7 @@ def schedule(
701
718
  "assistant": name,
702
719
  "schedule": slot.removeprefix("schedule:"),
703
720
  "status": "failed",
704
- "error": _reason(error),
721
+ "error": reason(error, "assistant files are inaccessible"),
705
722
  }
706
723
  )
707
724
  return keys, failures
@@ -822,7 +839,12 @@ def _cycle(store: Store, names: set[str], at: datetime, runner: Runner) -> list[
822
839
  )
823
840
  except (Error, OSError, UnicodeError, ValueError) as error:
824
841
  results.append(
825
- {"assistant": queue.get(key)["assistant"], "job": key, "status": "failed", "error": _reason(error)}
842
+ {
843
+ "assistant": queue.get(key)["assistant"],
844
+ "job": key,
845
+ "status": "failed",
846
+ "error": reason(error, "assistant files are inaccessible"),
847
+ }
826
848
  )
827
849
  failed: set[str] = set()
828
850
  while (delivery := queue.delivery(names=names, skip=tried)) is not None:
@@ -835,7 +857,12 @@ def _cycle(store: Store, names: set[str], at: datetime, runner: Runner) -> list[
835
857
  except (Error, OSError, UnicodeError, ValueError) as error:
836
858
  failed.add(key)
837
859
  results.append(
838
- {"assistant": delivery["assistant"], "delivery": key, "status": "failed", "error": _reason(error)}
860
+ {
861
+ "assistant": delivery["assistant"],
862
+ "delivery": key,
863
+ "status": "failed",
864
+ "error": reason(error, "assistant files are inaccessible"),
865
+ }
839
866
  )
840
867
  results.extend(
841
868
  {
@@ -887,8 +914,8 @@ def cycle(
887
914
  ]
888
915
  return _cycle(store, names, at, runner)
889
916
  except (Error, OSError, UnicodeError, ValueError) as error:
890
- reason = _reason(error, "the assistant queue or brain files are inaccessible")
891
- return [{"assistant": name, "status": "failed", "error": reason} for name in sorted(names)]
917
+ cause = reason(error, "the assistant queue or brain files are inaccessible")
918
+ return [{"assistant": name, "status": "failed", "error": cause} for name in sorted(names)]
892
919
 
893
920
 
894
921
  class Dispatcher:
@@ -1022,9 +1049,9 @@ class Dispatcher:
1022
1049
  connected=connected,
1023
1050
  )
1024
1051
  except (Error, OSError, UnicodeError) as error:
1025
- reason = str(error) if isinstance(error, Error) else "stream transport failed; inspect its local log"
1052
+ cause = reason(error, "stream transport failed; inspect its local log")
1026
1053
  with suppress(Error, OSError):
1027
- self.queue.set_progress(f"health:channel:{channel}", {"error": reason, "at": now()})
1054
+ self.queue.set_progress(f"health:channel:{channel}", {"error": cause, "at": now()})
1028
1055
  if self.stopped.wait(delay):
1029
1056
  break
1030
1057
  delay = min(delay * 2, 60)
@@ -1055,7 +1082,7 @@ class Dispatcher:
1055
1082
  config = load(self.store)
1056
1083
  except (Error, OSError, UnicodeError) as error:
1057
1084
  # Running work continues; nothing new starts until bf.yaml loads again.
1058
- self._record("dispatcher", _reason(error, "bf.yaml is inaccessible"))
1085
+ self._record("dispatcher", reason(error, "bf.yaml is inaccessible"))
1059
1086
  return
1060
1087
  errors = []
1061
1088
  # Each section fails on its own: a full queue refusing a schedule never keeps queued work from draining.
@@ -1063,7 +1090,7 @@ class Dispatcher:
1063
1090
  try:
1064
1091
  section()
1065
1092
  except (Error, OSError, UnicodeError, ValueError) as error:
1066
- errors.append(_reason(error, "assistant queue inaccessible"))
1093
+ errors.append(reason(error, "assistant queue inaccessible"))
1067
1094
  self._record("dispatcher", "; ".join(errors))
1068
1095
 
1069
1096
  def _harvest(self) -> None:
@@ -1088,7 +1115,7 @@ class Dispatcher:
1088
1115
  # Worded as bf update words it, so bf status reads the same whichever ran the poll.
1089
1116
  self._record(name, read_failure(name.split(":")[2], error))
1090
1117
  else:
1091
- self._record(name, _reason(error, "runtime worker failed"))
1118
+ self._record(name, reason(error, "runtime worker failed"))
1092
1119
 
1093
1120
  def _jobs(self) -> None:
1094
1121
  waiting = self._waiting()
@@ -4,21 +4,19 @@ from __future__ import annotations
4
4
 
5
5
  import os
6
6
  import selectors
7
- import signal
8
7
  import subprocess
9
8
  import time
10
9
  from collections.abc import Callable
11
10
  from contextlib import suppress
12
- from datetime import UTC, datetime
13
11
  from threading import Event
14
12
 
15
13
  from pydantic import ValidationError
16
14
 
17
- from bf.collect import PROGRAM_ENV, Runner, arguments, executable, run, starting
15
+ from bf.collect import Runner, _now, arguments, ended, executable, program_env, run, starting, stop
18
16
  from bf.config import load
19
- from bf.history import append_log, environment
17
+ from bf.history import append_log
20
18
  from bf.messages import Batch, Message, Outgoing, Receipt
21
- from bf.models import Command, Error, Send, Stream, decode, encode, explain, local, timestamp
19
+ from bf.models import Command, Error, Send, Stream, decode, encode, explain, timestamp
22
20
  from bf.storage import Store
23
21
 
24
22
  # Envelope keys a validation error may name; a provider's output controls any other key.
@@ -33,6 +31,10 @@ class BatchOverflowError(Error):
33
31
  """A read window holds more messages than one batch carries; a shorter window may fit."""
34
32
 
35
33
 
34
+ class MisroutedError(Error):
35
+ """A send receipt names another conversation: the message may have reached the wrong place, so never retry it."""
36
+
37
+
36
38
  def _invalid(error: Error | ValidationError) -> str:
37
39
  """Which envelope field failed and why, never its value."""
38
40
  return f": {explain(error, _FIELDS)}" if isinstance(error, ValidationError) else ""
@@ -83,7 +85,9 @@ def send(store: Store, name: str, command: Send, message: Outgoing, *, runner: R
83
85
  except (Error, ValidationError) as error:
84
86
  raise Error(f"channel {name}: send must return a JSON id and conversation receipt") from error
85
87
  if message.conversation and receipt.conversation != message.conversation:
86
- raise Error(f"channel {name}: send receipt names a different conversation; inspect delivery before retrying")
88
+ raise MisroutedError(
89
+ f"channel {name}: send receipt names a different conversation; inspect delivery before retrying"
90
+ )
87
91
  return receipt
88
92
 
89
93
 
@@ -104,9 +108,7 @@ def stream(
104
108
  `connected` runs once, when BF wrote the resume frame and the adapter still runs ESTABLISHED seconds after starting.
105
109
  Every run ends with one timed log entry naming its outcome and, when the adapter exited on its own, its status.
106
110
  """
107
- # Like `run`: inherited values of the variables BF sets never reach an adapter.
108
- env = {key: value for key, value in environment().items() if key not in PROGRAM_ENV}
109
- env["BF_BRAIN"] = str(store.root)
111
+ env = program_env(store)
110
112
  argv = arguments(store, command, resume.get("since", ""), "")
111
113
  argv[0] = executable(store, argv[0], env)
112
114
  child: subprocess.Popen[bytes] | None = None
@@ -213,28 +215,16 @@ def stream(
213
215
  break
214
216
  errors.extend(chunk)
215
217
  del errors[:-_STDERR]
216
- with suppress(ProcessLookupError):
217
- os.killpg(child.pid, signal.SIGKILL)
218
- child.wait()
218
+ stop(child)
219
219
  for pipe in (child.stdin, child.stdout, child.stderr):
220
220
  if pipe is not None:
221
221
  pipe.close()
222
222
  if code is not None:
223
- outcome += f"; adapter {_ended(code)}"
223
+ outcome += f"; adapter {ended(code)}"
224
224
  with suppress(Error, OSError):
225
225
  append_log(
226
226
  store,
227
227
  f"channel.{name}.stream",
228
- f"{local(timestamp(datetime.now(UTC).isoformat()))} {outcome} after {time.monotonic() - started:.1f}s",
228
+ f"{_now()} {outcome} after {time.monotonic() - started:.1f}s",
229
229
  bytes(errors),
230
230
  )
231
-
232
-
233
- def _ended(code: int) -> str:
234
- if code >= 0:
235
- return f"exited with status {code}"
236
- try:
237
- return f"was killed by {signal.Signals(-code).name}"
238
- except ValueError:
239
- # Real-time signals between SIGRTMIN and SIGRTMAX have no name.
240
- return f"was killed by signal {-code}"