harness-sdk-python 0.40.8__tar.gz → 0.40.12__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 (82) hide show
  1. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/PKG-INFO +3 -3
  2. harness_sdk_python-0.40.12/examples/local_origin.py +60 -0
  3. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/examples/runs_app.py +4 -1
  4. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/pyproject.toml +2 -2
  5. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/deepagents.py +53 -20
  6. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/run_manager.py +53 -0
  7. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/threads.py +26 -3
  8. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/wire.py +20 -7
  9. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/run_helpers.py +4 -0
  10. harness_sdk_python-0.40.12/tests/test_deepagents_subagent_approval.py +193 -0
  11. harness_sdk_python-0.40.12/tests/test_example_local_origin.py +114 -0
  12. harness_sdk_python-0.40.12/tests/test_stale_redelivery.py +183 -0
  13. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_threads.py +78 -9
  14. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/.gitignore +0 -0
  15. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/README.md +0 -0
  16. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/examples/__init__.py +0 -0
  17. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/__init__.py +0 -0
  18. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/checkpoints.py +0 -0
  19. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/deepagents_host.py +0 -0
  20. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/fenced_postgres.py +0 -0
  21. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/interest.py +0 -0
  22. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/langgraph.py +0 -0
  23. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/linear_thread.py +0 -0
  24. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/messages.py +0 -0
  25. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/parts.py +0 -0
  26. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/prioritize.py +0 -0
  27. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/protocol.py +0 -0
  28. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/providers/__init__.py +0 -0
  29. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/providers/gpt_live.py +0 -0
  30. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/voice.py +0 -0
  31. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/src/harness_sdk/voice_thread.py +0 -0
  32. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_admit_steer.py +0 -0
  33. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_applied_visibility.py +0 -0
  34. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_batches.py +0 -0
  35. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_branch_anchor.py +0 -0
  36. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_checkpoints.py +0 -0
  37. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_deepagents_approval.py +0 -0
  38. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_deepagents_files.py +0 -0
  39. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_deepagents_multi_approval.py +0 -0
  40. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_deepagents_outcome.py +0 -0
  41. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_deepagents_thread.py +0 -0
  42. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_deepagents_user_ids.py +0 -0
  43. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_deepagents_voice.py +0 -0
  44. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_dispatching.py +0 -0
  45. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_durability.py +0 -0
  46. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_edit_dispatched.py +0 -0
  47. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_edit_reload.py +0 -0
  48. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_enqueue.py +0 -0
  49. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_fenced_postgres.py +0 -0
  50. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_gpt_live.py +0 -0
  51. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_imports.py +0 -0
  52. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_input_required.py +0 -0
  53. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_interest.py +0 -0
  54. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_langgraph.py +0 -0
  55. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_linear_thread.py +0 -0
  56. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_meta.py +0 -0
  57. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_mint_concurrency.py +0 -0
  58. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_outcomes.py +0 -0
  59. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_parts.py +0 -0
  60. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_placement.py +0 -0
  61. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_prepare_hooks.py +0 -0
  62. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_prioritize.py +0 -0
  63. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_prioritize_builtins.py +0 -0
  64. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_request_options.py +0 -0
  65. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_restore.py +0 -0
  66. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_rewind_during_run.py +0 -0
  67. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_run_admission.py +0 -0
  68. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_run_crash_sweep.py +0 -0
  69. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_run_eviction.py +0 -0
  70. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_run_id_bounds.py +0 -0
  71. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_run_ownership.py +0 -0
  72. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_run_sync.py +0 -0
  73. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_settle.py +0 -0
  74. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_steer.py +0 -0
  75. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_stop_continue.py +0 -0
  76. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_stopping_window.py +0 -0
  77. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_undo.py +0 -0
  78. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_voice.py +0 -0
  79. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_voice_delegation.py +0 -0
  80. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_voice_events.py +0 -0
  81. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/test_wire.py +0 -0
  82. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.12}/tests/voice_helpers.py +0 -0
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: harness-sdk-python
3
- Version: 0.40.8
3
+ Version: 0.40.12
4
4
  Summary: RunManager: the harness-sdk runs subsystem for Python Statewire hosts
5
5
  Project-URL: Repository, https://github.com/assistant-ui/harness-sdk
6
6
  License-Expression: MIT
7
7
  Requires-Python: <4.0,>=3.12
8
- Requires-Dist: pinboard-sdk>=0.18.0
9
- Requires-Dist: statewire<0.24,>=0.23.6
8
+ Requires-Dist: pinboard-sdk>=0.18.4
9
+ Requires-Dist: statewire<0.25,>=0.24.3
10
10
  Provides-Extra: deepagents
11
11
  Requires-Dist: deepagents>=0.6.12; extra == 'deepagents'
12
12
  Requires-Dist: langchain-core>=0.3; extra == 'deepagents'
@@ -0,0 +1,60 @@
1
+ """Refuse browser requests from pages that are not on this machine.
2
+
3
+ Any page can open ``ws://127.0.0.1:<port>/...`` or send it requests.
4
+
5
+ - With an Origin header, it must be local or listed in ALLOWED_ORIGINS
6
+ (comma-separated).
7
+ - Without one, browsers send Sec-Fetch-Site; ``cross-site`` is refused.
8
+ - With neither (curl, server clients, older browsers), the request needs an
9
+ ``x-local-client`` header. A page can't add one without a CORS preflight,
10
+ which carries its Origin. The pinboard gateway's own requests carry
11
+ ``pinboard-*`` headers and pass the same way.
12
+
13
+ Every Python example backend carries this file;
14
+ python/harness-sdk-python/tests/test_example_local_origin.py tests each copy.
15
+ """
16
+
17
+ import os
18
+ from urllib.parse import urlsplit
19
+
20
+ _ENV = os.environ.get("ALLOWED_ORIGINS", "").split(",")
21
+ EXTRA = {o.strip().rstrip("/") for o in _ENV if o.strip()}
22
+ LOOPBACK = ("localhost", "127.0.0.1", "::1")
23
+ LOCAL_FETCH_SITES = ("same-origin", "same-site", "none")
24
+ LOCAL_CLIENT_HEADER = b"x-local-client"
25
+
26
+
27
+ def origin_allowed(origin: str) -> bool:
28
+ try:
29
+ url = urlsplit(origin)
30
+ local = url.scheme in ("http", "https") and url.hostname in LOOPBACK
31
+ except ValueError:
32
+ local = False
33
+ return local or origin.strip().rstrip("/") in EXTRA
34
+
35
+
36
+ def request_allowed(headers: list[tuple[bytes, bytes]]) -> bool:
37
+ values = {name.lower(): value for name, value in headers}
38
+ if b"origin" in values:
39
+ return origin_allowed(values[b"origin"].decode("latin-1"))
40
+ if b"sec-fetch-site" in values:
41
+ site = values[b"sec-fetch-site"].decode("latin-1").strip().lower()
42
+ return site in LOCAL_FETCH_SITES
43
+ return LOCAL_CLIENT_HEADER in values or any(
44
+ name.startswith(b"pinboard-") for name in values
45
+ )
46
+
47
+
48
+ def local_origin_only(app):
49
+ async def call(scope, receive, send):
50
+ if scope["type"] not in ("http", "websocket") or request_allowed(
51
+ scope.get("headers", [])
52
+ ):
53
+ return await app(scope, receive, send)
54
+ if scope["type"] == "websocket":
55
+ await receive()
56
+ return await send({"type": "websocket.close", "code": 1008})
57
+ await send({"type": "http.response.start", "status": 403, "headers": []})
58
+ await send({"type": "http.response.body", "body": b"origin not allowed"})
59
+
60
+ return call
@@ -2,7 +2,7 @@
2
2
 
3
3
  Run from python/harness-sdk-python:
4
4
 
5
- uv run --extra deepagents uvicorn examples.runs_app:app --port 8000
5
+ PINBOARD_DEV=1 uv run --extra deepagents uvicorn examples.runs_app:app --port 8000
6
6
 
7
7
  State is ``{"messages": [...]}`` in langchain format; rewind truncates the
8
8
  list. Threads live at /threads/{id}: ``GET .../stream`` (SSE), ``.../ws``,
@@ -26,6 +26,8 @@ from statewire.langgraph import append_langgraph_event
26
26
 
27
27
  from harness_sdk import RunManager, linear_thread, run_manager
28
28
 
29
+ from .local_origin import local_origin_only
30
+
29
31
 
30
32
  def select_model() -> str:
31
33
  if model := os.environ.get("DEEPAGENTS_MODEL"):
@@ -194,3 +196,4 @@ class RunsHost(Statewire):
194
196
  worker = Worker(hosts={"/threads": RunsHost}, state_store=MemoryStateStore())
195
197
  app = FastAPI()
196
198
  app.include_router(worker)
199
+ app.add_middleware(local_origin_only)
@@ -1,11 +1,11 @@
1
1
  [project]
2
2
  name = "harness-sdk-python"
3
- version = "0.40.8"
3
+ version = "0.40.12"
4
4
  description = "RunManager: the harness-sdk runs subsystem for Python Statewire hosts"
5
5
  readme = "README.md"
6
6
  license = "MIT"
7
7
  requires-python = ">=3.12,<4.0"
8
- dependencies = ["statewire>=0.23.6,<0.24", "pinboard-sdk>=0.18.0"]
8
+ dependencies = ["statewire>=0.24.3,<0.25", "pinboard-sdk>=0.18.4"]
9
9
 
10
10
  [project.optional-dependencies]
11
11
  postgres = ["langgraph-checkpoint-postgres>=2.0.0"]
@@ -117,6 +117,7 @@ class DeepagentsThread:
117
117
  self._touched: set[tuple[str, str]] = set()
118
118
  self._subagents: set[str] = set()
119
119
  self.interrupt: dict[str, Any] | None = None
120
+ self._raised: dict[Any, str] = {}
120
121
 
121
122
  async def boot(self) -> None:
122
123
  """Hydrate the tree from the index rows and the main branch window from the checkpointer."""
@@ -168,16 +169,17 @@ class DeepagentsThread:
168
169
  if ctx.trigger == "input-resume":
169
170
  from langgraph.types import Command
170
171
 
171
- tool_ids = {p.get("toolInvocationId") for p in plain(self.tree.get(MAIN_NS, thread.head)["parts"])}
172
- missing = [r["toolCallId"] for r, _response, _meta in ctx.input_outcomes if r["toolCallId"] not in tool_ids]
173
- if missing:
174
- raise KeyError(f"head {thread.head!r} holds no tool part for {missing!r}")
175
- self._mount(MAIN_NS, thread.head)
172
+ requested = [r["toolCallId"] for r, _response, _meta in ctx.input_outcomes]
173
+ path = self._parked_path(MAIN_NS, set(requested))
174
+ if path is None:
175
+ raise KeyError(f"head {thread.head!r} holds no tool part for {requested!r}")
176
+ for ns in path:
177
+ self._mount(ns, self.tree.thread(ns).head)
176
178
  if ctx.resume:
177
179
  return None, config
178
180
  # The middleware reads decisions positionally, in tool_calls order:
179
- # the head's tool parts carry that order, the outcomes may not.
180
- order = [p.get("toolInvocationId") for p in plain(self.tree.get(MAIN_NS, thread.head)["parts"])]
181
+ # the parked reply's tool parts carry that order, the outcomes may not.
182
+ order = [p.get("toolInvocationId") for p in plain(self._assemblers[path[-1]].parts)]
181
183
  outcomes = sorted(ctx.input_outcomes, key=lambda o: order.index(o[0]["toolCallId"]))
182
184
  decisions = [
183
185
  {"type": "approve"} if response and response.get("decision") == "approve" else {"type": "reject"}
@@ -225,6 +227,20 @@ class DeepagentsThread:
225
227
  self._changed()
226
228
  return ({"messages": turn} if turn else None), config
227
229
 
230
+ def _parked_path(self, ns: str, tool_ids: set[str]) -> list[str] | None:
231
+ """The namespaces from ``ns``'s head down to the reply whose parts pending
232
+ approval hold ``tool_ids``, through the ``task`` parts that link a subagent's thread."""
233
+ parts = plain(self.tree.get(ns, self.tree.thread(ns).head)["parts"])
234
+ if tool_ids <= {p.get("toolInvocationId") for p in parts if p.get("state") == "pendingApproval"}:
235
+ return [ns]
236
+ for part in parts:
237
+ sub = (part.get("metadata") or {}).get("ns") if part["type"] == "tool" else None
238
+ if sub in self.tree.threads:
239
+ path = self._parked_path(sub, tool_ids)
240
+ if path is not None:
241
+ return [ns, *path]
242
+ return None
243
+
228
244
  def _agent_ids(self) -> set[str]:
229
245
  # user messages mount on the main graph; a subagent runs on its own
230
246
  # LangGraph thread, so only main-namespace ids can collide
@@ -391,16 +407,31 @@ class DeepagentsThread:
391
407
  assembler.tool_result(message)
392
408
  self._changed()
393
409
  return
394
- if mode == "updates" and isinstance(event, dict) and "__interrupt__" in event and ns == MAIN_NS:
395
- assembler = self._assemblers.get(MAIN_NS)
396
- # no streamed message: still validate, so an unmatched interrupt fails the run
397
- parts = plain(assembler.parts) if assembler is not None else []
398
- tool_ids = _pending_tool_ids(parts, event["__interrupt__"])
399
- for tool_id in tool_ids:
400
- assert assembler is not None
401
- assembler.amend(tool_id, state="pendingApproval")
402
- self.interrupt = {"toolCallIds": tool_ids}
403
- self._changed()
410
+ if mode == "updates" and isinstance(event, dict) and "__interrupt__" in event:
411
+ if ns == MAIN_NS:
412
+ self._park(event["__interrupt__"])
413
+ elif _root_of(ns) not in self._subagents:
414
+ # a subagent's interrupt reaches the main namespace after its own, with the same id
415
+ for interrupt in event["__interrupt__"]:
416
+ self._raised.setdefault(getattr(interrupt, "id", None), ns)
417
+
418
+ def _park(self, interrupts: Any) -> None:
419
+ """Park the calls ``interrupts`` name, in the namespace that raised them."""
420
+ if self.interrupt is not None:
421
+ raise ValueError("unsupported interrupt: approvals from more than one agent at once")
422
+ namespaces = {self._raised.get(getattr(i, "id", None), MAIN_NS) for i in interrupts} or {MAIN_NS}
423
+ if len(namespaces) > 1:
424
+ raise ValueError(f"unsupported interrupt: approvals from more than one agent at once ({sorted(namespaces)})")
425
+ (ns,) = namespaces
426
+ assembler = self._assemblers.get(ns)
427
+ # no streamed message: still validate, so an unmatched interrupt fails the run
428
+ parts = plain(assembler.parts) if assembler is not None else []
429
+ tool_ids = _pending_tool_ids(parts, interrupts)
430
+ for tool_id in tool_ids:
431
+ assert assembler is not None
432
+ assembler.amend(tool_id, state="pendingApproval")
433
+ self.interrupt = {"toolCallIds": tool_ids}
434
+ self._changed()
404
435
 
405
436
  def _finish(self, ns: str, outcome: dict[str, Any] | None = None) -> None:
406
437
  assembler = self._assemblers.pop(ns, None)
@@ -421,11 +452,12 @@ class DeepagentsThread:
421
452
  await self._thread.ingest(langgraph_snapshot(captured))
422
453
  if self._input_checkpoint_seen:
423
454
  self._confirm_admission()
424
- for ns in self._turn_namespaces():
425
- if self.interrupt is None or ns != MAIN_NS:
455
+ # parked: every open namespace is on the path to the parked call
456
+ if self.interrupt is None:
457
+ for ns in self._turn_namespaces():
426
458
  self._finish(ns, outcome)
427
459
  for ns in self.tree.threads:
428
- if ns != MAIN_NS and _root_of(ns) not in self._subagents:
460
+ if ns != MAIN_NS and _root_of(ns) not in self._subagents and ns not in self._assemblers:
429
461
  self._thread_state(ns, status="idle")
430
462
  await self._persist()
431
463
  self._changed()
@@ -514,6 +546,7 @@ class DeepagentsThread:
514
546
  self._admission = None
515
547
  self._input_checkpoint_seen = False
516
548
  self.interrupt = None
549
+ self._raised = {}
517
550
  for ns in self._turn_namespaces():
518
551
  self._finish(ns, outcome)
519
552
  self._thread.abandon_plan()
@@ -65,6 +65,7 @@ projections.
65
65
  import asyncio
66
66
  import inspect
67
67
  import logging
68
+ import math
68
69
  from dataclasses import dataclass, field
69
70
  from typing import (
70
71
  Any,
@@ -432,6 +433,7 @@ class RunManager(Tray):
432
433
 
433
434
  capabilities: frozenset[str] = frozenset()
434
435
  max_queued: int = 50
436
+ max_redelivery_age: float | None = None
435
437
  prepare_message: Callable[[dict[str, Any]], dict[str, Any]] | None = None
436
438
  prepare_input: Callable[[dict[str, Any]], dict[str, Any]] | None = None
437
439
  prioritize: "Callable[[RunManager.PrioritizeRequest], Awaitable[str] | str] | None" = None
@@ -491,6 +493,7 @@ class RunManager(Tray):
491
493
  self._input_answers: dict[str, Any] = {}
492
494
  self._run_live: "RunManager.RunContext | None" = None
493
495
  self._fresh = False
496
+ self._redelivering = False
494
497
  self._closing = False
495
498
  self._idle = asyncio.Event()
496
499
  self._verdict_waiters: dict[str, "asyncio.Future[dict[str, Any]]"] = {}
@@ -1094,9 +1097,11 @@ class RunManager(Tray):
1094
1097
  item = recorded["item"]
1095
1098
  if self._fresh:
1096
1099
  self._fresh = False
1100
+ self._redelivering = False
1097
1101
  else:
1098
1102
  self.outbox.dispatch(item) # redelivery bumps the attempt
1099
1103
  self._reclaim(item)
1104
+ self._redelivering = True
1100
1105
  yield item
1101
1106
 
1102
1107
  def _reclaim(self, item: Any) -> None:
@@ -1144,7 +1149,46 @@ class RunManager(Tray):
1144
1149
  ctx.stop_requested.set()
1145
1150
  return ctx
1146
1151
 
1152
+ async def _stale_reason(self, item: Any, resume: bool) -> str | None:
1153
+ max_age = self.max_redelivery_age
1154
+ since = self._ledger.since
1155
+ if max_age is not None and since is not None:
1156
+ # pinboard's first-delivery time; a row from before it is stamped
1157
+ # at this redelivery, so its window starts at the upgrade
1158
+ age = self._domain.now() - since
1159
+ if age > max_age:
1160
+ return f"it was first dispatched {age / 3600:.1f}h ago"
1161
+ thread = self.handler.__self__
1162
+ record = item["record"]
1163
+ probes = [
1164
+ message["id"] if resume else message.get("~parent", _ABSENT)
1165
+ for message in record["messages"]
1166
+ ]
1167
+ if not resume:
1168
+ # an unapplied edit or reload records its rewound parent here
1169
+ probes.append(record.get("rollbackTo", _ABSENT))
1170
+ for probe in probes:
1171
+ if probe is _ABSENT or (probe is None and not resume):
1172
+ continue
1173
+ meta = await thread.get_message_meta(probe)
1174
+ if meta is not None and meta.get("onActiveBranch") is False:
1175
+ return f"message {probe!r} is no longer on the active branch"
1176
+ return None
1177
+
1178
+ def _guard_redelivery(self, item: Any, fn: Callable[..., Any]) -> Callable[..., Any]:
1179
+ async def guarded(ctx: "RunManager.RunContext") -> Any:
1180
+ reason = await self._stale_reason(item, ctx.resume)
1181
+ if reason is not None:
1182
+ logger.warning("run %r refused its redelivery: %s", self.id, reason)
1183
+ raise _reject("stale-redelivery", f"run not resumed: {reason}")
1184
+ return await fn(ctx)
1185
+
1186
+ return guarded
1187
+
1147
1188
  async def _run_item(self, item: Any, fn: Callable[..., Any]) -> Any:
1189
+ if self._redelivering:
1190
+ self._redelivering = False
1191
+ fn = self._guard_redelivery(item, fn)
1148
1192
  ctx = self._make_run_ctx(item)
1149
1193
  self._run_live = ctx
1150
1194
  task = asyncio.ensure_future(self._execute(ctx, fn))
@@ -2744,6 +2788,7 @@ def run_manager(
2744
2788
  *,
2745
2789
  capabilities: Iterable[str] = (),
2746
2790
  max_queued: int = 50,
2791
+ max_redelivery_age: float | None = None,
2747
2792
  prepare_message: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
2748
2793
  prepare_input: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
2749
2794
  prioritize: "Callable[[RunManager.PrioritizeRequest], Awaitable[str] | str] | None" = None,
@@ -2759,6 +2804,13 @@ def run_manager(
2759
2804
  raise ValueError("rewind-during-run requires the rewind capability")
2760
2805
  if max_queued < 1:
2761
2806
  raise ValueError("max_queued must be >= 1")
2807
+ if max_redelivery_age is not None and (
2808
+ isinstance(max_redelivery_age, bool)
2809
+ or not isinstance(max_redelivery_age, (int, float))
2810
+ or not math.isfinite(max_redelivery_age)
2811
+ or max_redelivery_age <= 0
2812
+ ):
2813
+ raise ValueError("max_redelivery_age must be a positive number of seconds or None")
2762
2814
  if prioritize is not None and not callable(prioritize):
2763
2815
  raise TypeError("prioritize must be callable")
2764
2816
 
@@ -2769,6 +2821,7 @@ def run_manager(
2769
2821
  {
2770
2822
  "capabilities": caps,
2771
2823
  "max_queued": max_queued,
2824
+ "max_redelivery_age": max_redelivery_age,
2772
2825
  "prepare_message": staticmethod(prepare_message)
2773
2826
  if prepare_message is not None
2774
2827
  else None,
@@ -1,5 +1,8 @@
1
- """HarnessThreads: a Statewire host serving one thread list over the
2
- ``harness-sdk-threads`` protocol; the list instance is the store's only writer.
1
+ """HarnessThreads: a Statewire host serving one workspace's thread list over the
2
+ ``harness-sdk-threads`` protocol. The instance id is the workspace id; threads
3
+ list themselves on their own workspace's instance (``HarnessMessages.workspace_id``),
4
+ and ``authorize`` admits callers with access to that workspace. The list
5
+ instance is the store's only writer.
3
6
 
4
7
  .. versionadded:: alpha
5
8
  """
@@ -115,13 +118,33 @@ def _thread_id(params: Any) -> str:
115
118
 
116
119
 
117
120
  class HarnessThreads(Statewire):
118
- """One thread list; ``thread_store()`` names its store (in-memory per instance by default).
121
+ """One workspace's thread list: the instance id is the workspace id. ``thread_store()`` names its store
122
+ (in-memory per instance by default).
119
123
 
120
124
  .. versionadded:: alpha
121
125
  """
122
126
 
123
127
  protocols = (HARNESS_THREADS_PROTOCOL,)
124
128
 
129
+ @property
130
+ def workspace_id(self) -> str:
131
+ """The workspace this list serves: its instance id."""
132
+ return self.id
133
+
134
+ async def authorize(self, conn: HTTPConnection) -> Any:
135
+ """The list's only gate: every attacher reads and edits every thread of the workspace. Override to admit
136
+ callers with access to ``self.workspace_id`` and return the caller's identity.
137
+
138
+ ``POST /touch`` keeps its own instance-only check.
139
+
140
+ .. versionchanged:: alpha
141
+ Refuses every attach (403) until overridden.
142
+ """
143
+ raise AuthRejected(
144
+ "HarnessThreads is closed until a subclass overrides authorize to admit the workspace's members",
145
+ status_code=403,
146
+ )
147
+
125
148
  def thread_store(self) -> ThreadStore:
126
149
  return MemoryThreadStore()
127
150
 
@@ -63,11 +63,23 @@ class _Interests:
63
63
  class HarnessMessages:
64
64
  """Statewire mixin: ``tree`` holds the messages; call ``refresh_messages()`` after the tree changes."""
65
65
 
66
- #: Path of the ``HarnessThreads`` instance this thread lists itself on, e.g. ``"/thread-lists/default"``. Alpha.
67
- thread_list: str | None = None
66
+ #: The workspace this thread belongs to; it lists itself only on that workspace's ``HarnessThreads`` instance,
67
+ #: ``{thread_lists}/{workspace_id}``. ``None`` keeps the thread off every list. Fix it per thread (a class
68
+ #: attribute, or a property over the thread's own record); never take it from an attacher. Alpha.
69
+ workspace_id: str | None = None
70
+ #: Namespace of the ``HarnessThreads`` host. Alpha.
71
+ thread_lists: str = "/thread-lists"
68
72
  _touching: "asyncio.Task[None] | None" = None
69
73
  _titled = False
70
74
 
75
+ def __init_subclass__(cls, **kwargs: Any) -> None:
76
+ super().__init_subclass__(**kwargs)
77
+ if "thread_list" in cls.__dict__:
78
+ raise TypeError(
79
+ f"{cls.__name__}.thread_list was removed: set workspace_id; the thread lists itself on "
80
+ f"{{thread_lists}}/{{workspace_id}}"
81
+ )
82
+
71
83
  @property
72
84
  def state_key(self) -> tuple[str, ...]:
73
85
  return (self.id,)
@@ -80,7 +92,7 @@ class HarnessMessages:
80
92
  self._touch(activity=_ACTIVITY[status])
81
93
 
82
94
  def _touch(self, **fields: str) -> None:
83
- if self.thread_list is None:
95
+ if self.workspace_id is None:
84
96
  return
85
97
  if not self._titled and (title := self.thread_list_title()) is not None:
86
98
  self._titled = True
@@ -95,12 +107,13 @@ class HarnessMessages:
95
107
  ) -> None:
96
108
  if after is not None:
97
109
  await asyncio.wait({after})
98
- response = await self.cluster.post(
99
- f"{self.thread_list}/touch", json={"threadId": self.id, **fields}
100
- )
110
+ if not self.workspace_id or "/" in self.workspace_id:
111
+ raise ValueError(f"workspace_id must be one path segment: {self.workspace_id!r}")
112
+ path = f"{self.thread_lists}/{self.workspace_id}/touch"
113
+ response = await self.cluster.post(path, json={"threadId": self.id, **fields})
101
114
  if response.status_code != 200:
102
115
  raise RuntimeError(
103
- f"{self.thread_list}/touch answered {response.status_code}: {response.text}"
116
+ f"{path} answered {response.status_code}: {response.text}"
104
117
  )
105
118
 
106
119
  @cached_property
@@ -74,6 +74,7 @@ def make_host(
74
74
  authorize=None,
75
75
  version=HARNESS_PROTOCOL.version,
76
76
  prioritize=None,
77
+ max_redelivery_age=None,
77
78
  ):
78
79
  class Host(Statewire):
79
80
  protocols = (
@@ -97,6 +98,7 @@ def make_host(
97
98
  @run_manager(
98
99
  capabilities=capabilities,
99
100
  max_queued=max_queued,
101
+ max_redelivery_age=max_redelivery_age,
100
102
  prepare_message=prepare_message,
101
103
  prepare_input=prepare_input,
102
104
  prioritize=prioritize,
@@ -334,6 +336,7 @@ async def run_host(
334
336
  version=HARNESS_PROTOCOL.version,
335
337
  prioritize=None,
336
338
  client_id=None,
339
+ max_redelivery_age=None,
337
340
  ):
338
341
  """``version`` is the negotiated protocol date the host passes to sends; None passes none."""
339
342
  host_cls = make_host(
@@ -345,6 +348,7 @@ async def run_host(
345
348
  authorize=authorize,
346
349
  version=version,
347
350
  prioritize=prioritize,
351
+ max_redelivery_age=max_redelivery_age,
348
352
  )
349
353
  worker = Worker(
350
354
  state_store=store if store is not None else MemoryStateStore()