harness-sdk-python 0.40.8__tar.gz → 0.40.11__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 (81) hide show
  1. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/PKG-INFO +2 -2
  2. harness_sdk_python-0.40.11/examples/local_origin.py +60 -0
  3. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/examples/runs_app.py +4 -1
  4. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/pyproject.toml +2 -2
  5. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/deepagents.py +53 -20
  6. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/threads.py +26 -3
  7. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/wire.py +20 -7
  8. harness_sdk_python-0.40.11/tests/test_deepagents_subagent_approval.py +193 -0
  9. harness_sdk_python-0.40.11/tests/test_example_local_origin.py +114 -0
  10. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_threads.py +78 -9
  11. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/.gitignore +0 -0
  12. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/README.md +0 -0
  13. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/examples/__init__.py +0 -0
  14. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/__init__.py +0 -0
  15. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/checkpoints.py +0 -0
  16. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/deepagents_host.py +0 -0
  17. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/fenced_postgres.py +0 -0
  18. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/interest.py +0 -0
  19. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/langgraph.py +0 -0
  20. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/linear_thread.py +0 -0
  21. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/messages.py +0 -0
  22. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/parts.py +0 -0
  23. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/prioritize.py +0 -0
  24. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/protocol.py +0 -0
  25. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/providers/__init__.py +0 -0
  26. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/providers/gpt_live.py +0 -0
  27. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/run_manager.py +0 -0
  28. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/voice.py +0 -0
  29. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/src/harness_sdk/voice_thread.py +0 -0
  30. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/run_helpers.py +0 -0
  31. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_admit_steer.py +0 -0
  32. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_applied_visibility.py +0 -0
  33. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_batches.py +0 -0
  34. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_branch_anchor.py +0 -0
  35. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_checkpoints.py +0 -0
  36. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_deepagents_approval.py +0 -0
  37. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_deepagents_files.py +0 -0
  38. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_deepagents_multi_approval.py +0 -0
  39. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_deepagents_outcome.py +0 -0
  40. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_deepagents_thread.py +0 -0
  41. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_deepagents_user_ids.py +0 -0
  42. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_deepagents_voice.py +0 -0
  43. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_dispatching.py +0 -0
  44. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_durability.py +0 -0
  45. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_edit_dispatched.py +0 -0
  46. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_edit_reload.py +0 -0
  47. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_enqueue.py +0 -0
  48. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_fenced_postgres.py +0 -0
  49. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_gpt_live.py +0 -0
  50. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_imports.py +0 -0
  51. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_input_required.py +0 -0
  52. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_interest.py +0 -0
  53. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_langgraph.py +0 -0
  54. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_linear_thread.py +0 -0
  55. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_meta.py +0 -0
  56. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_mint_concurrency.py +0 -0
  57. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_outcomes.py +0 -0
  58. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_parts.py +0 -0
  59. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_placement.py +0 -0
  60. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_prepare_hooks.py +0 -0
  61. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_prioritize.py +0 -0
  62. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_prioritize_builtins.py +0 -0
  63. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_request_options.py +0 -0
  64. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_restore.py +0 -0
  65. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_rewind_during_run.py +0 -0
  66. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_run_admission.py +0 -0
  67. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_run_crash_sweep.py +0 -0
  68. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_run_eviction.py +0 -0
  69. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_run_id_bounds.py +0 -0
  70. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_run_ownership.py +0 -0
  71. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_run_sync.py +0 -0
  72. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_settle.py +0 -0
  73. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_steer.py +0 -0
  74. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_stop_continue.py +0 -0
  75. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_stopping_window.py +0 -0
  76. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_undo.py +0 -0
  77. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_voice.py +0 -0
  78. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_voice_delegation.py +0 -0
  79. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_voice_events.py +0 -0
  80. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/tests/test_wire.py +0 -0
  81. {harness_sdk_python-0.40.8 → harness_sdk_python-0.40.11}/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.11
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
8
  Requires-Dist: pinboard-sdk>=0.18.0
9
- Requires-Dist: statewire<0.24,>=0.23.6
9
+ Requires-Dist: statewire<0.25,>=0.24.0
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.11"
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.0,<0.25", "pinboard-sdk>=0.18.0"]
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()
@@ -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
@@ -0,0 +1,193 @@
1
+ """DeepagentsThread approvals raised inside a ``task`` subagent: the interrupt
2
+ reaches the main namespace, but it parks the subagent's call it names, and
3
+ the answer resumes the subagent in its parked message."""
4
+
5
+ import copy
6
+ import uuid
7
+ from uuid import uuid4
8
+
9
+ import pytest
10
+
11
+ pytest.importorskip("deepagents")
12
+
13
+ from langchain_core.language_models.chat_models import BaseChatModel
14
+ from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage
15
+ from langchain_core.outputs import ChatGeneration, ChatResult
16
+ from langgraph.checkpoint.memory import InMemorySaver
17
+ from pinboard import Worker
18
+ from pinboard.testing import MemoryStateStore
19
+ from statewire_helpers import apply_ops, statewire_client, stream_of
20
+ from test_deepagents_thread import Ctx, chain, run_turn, user
21
+ from voice_helpers import NEGOTIATION, VoiceDriver
22
+
23
+ from harness_sdk import DeepagentsHost, MemoryCheckpointIndex
24
+ from harness_sdk.deepagents import DeepagentsThread
25
+ from harness_sdk.messages import MAIN_NS, MessageTree
26
+
27
+ pytestmark = pytest.mark.anyio
28
+ NOTES = {"file_path": "/notes.md", "content": "the notes"}
29
+
30
+
31
+ class Delegating(BaseChatModel):
32
+ """"delegate X" calls ``task`` with X; the subagent's "write ..." calls
33
+ ``write_file``; a tool result is echoed as the answer."""
34
+
35
+ @property
36
+ def _llm_type(self):
37
+ return "delegating"
38
+
39
+ def bind_tools(self, tools, **kwargs):
40
+ return self
41
+
42
+ def _generate(self, messages: list[BaseMessage], stop=None, run_manager=None, **kwargs) -> ChatResult:
43
+ last = messages[-1]
44
+ mid = f"ai-{uuid.uuid4().hex[:6]}"
45
+ call_id = f"call-{uuid.uuid4().hex[:6]}"
46
+ if isinstance(last, ToolMessage):
47
+ reply = AIMessage(id=mid, content=f"answer: {last.content}")
48
+ elif isinstance(last, HumanMessage) and last.text.startswith("delegate"):
49
+ args = {"description": last.text[len("delegate "):], "subagent_type": "general-purpose"}
50
+ reply = AIMessage(id=mid, content="", tool_calls=[{"name": "task", "args": args, "id": call_id, "type": "tool_call"}])
51
+ else:
52
+ reply = AIMessage(id=mid, content="", tool_calls=[{"name": "write_file", "args": NOTES, "id": call_id, "type": "tool_call"}])
53
+ return ChatResult(generations=[ChatGeneration(message=reply)])
54
+
55
+
56
+ def create_agent(checkpointer):
57
+ from deepagents import create_deep_agent
58
+
59
+ return create_deep_agent(model=Delegating(), checkpointer=checkpointer, interrupt_on={"write_file": True})
60
+
61
+
62
+ async def build(saver=None, index=None):
63
+ agent = create_agent(saver or InMemorySaver())
64
+ thread = DeepagentsThread(agent, index=index or MemoryCheckpointIndex(), thread_id="t1", tree=MessageTree(), threads={})
65
+ await thread.boot()
66
+ return agent, thread
67
+
68
+
69
+ def parked(thread):
70
+ """The main reply's ``task`` part, the subagent namespace it links, and the subagent reply's ``write_file`` part."""
71
+ task = thread.tree.get(MAIN_NS, thread.tree.thread(MAIN_NS).head)["parts"][0]
72
+ ns = task["metadata"]["ns"]
73
+ write = thread.tree.get(ns, thread.tree.thread(ns).head)["parts"][0]
74
+ return task, ns, write
75
+
76
+
77
+ def answer(tool_id, decision):
78
+ return (({"id": tool_id, "type": "tool-approval", "toolCallId": tool_id}, {"decision": decision}, None),)
79
+
80
+
81
+ async def test_a_subagent_approval_parks_the_call_it_names():
82
+ agent, thread = await build()
83
+ await run_turn(agent, thread, Ctx(messages=(user("delegate write the notes"),)))
84
+ task, ns, write = parked(thread)
85
+ assert task["toolName"] == "task" and task["state"] == "streaming"
86
+ assert write["toolName"] == "write_file" and write["input"] == NOTES
87
+ assert write["state"] == "pendingApproval"
88
+ assert thread.interrupt == {"toolCallIds": [write["toolInvocationId"]]}
89
+
90
+
91
+ @pytest.mark.parametrize(("decision", "written"), [("approve", True), ("reject", False)])
92
+ async def test_the_answer_resumes_the_subagent_in_its_parked_message(decision, written):
93
+ agent, thread = await build()
94
+ sent = user("delegate write the notes")
95
+ await run_turn(agent, thread, Ctx(messages=(sent,)))
96
+ _task, ns, write = parked(thread)
97
+ sub_chain = chain(thread, ns)
98
+
99
+ await run_turn(agent, thread, Ctx(trigger="input-resume", input_outcomes=answer(write["toolInvocationId"], decision)))
100
+ assert thread.interrupt is None
101
+ assert chain(thread, ns) == sub_chain
102
+ task, _ns, write = parked(thread)
103
+ text = thread.tree.get(ns, sub_chain[-1])["parts"][1]
104
+ assert write["state"] == "done" and write.get("isError", False) is not written
105
+ assert text["text"] == f"answer: {write['output']}"
106
+ assert task["state"] == "done" and task["output"] == text["text"]
107
+ assert len(chain(thread)) == 2
108
+ files = (await agent.aget_state(thread.config())).values.get("files") or {}
109
+ assert ("/notes.md" in files) is written
110
+
111
+
112
+ async def test_a_redelivered_subagent_answer_resumes_from_the_persisted_rows():
113
+ saver, index = InMemorySaver(), MemoryCheckpointIndex()
114
+ agent, thread = await build(saver, index)
115
+ await run_turn(agent, thread, Ctx(messages=(user("delegate write the notes"),)))
116
+ _task, ns, write = parked(thread)
117
+ persisted = copy.deepcopy(index)
118
+
119
+ agent, rebooted = await build(saver, persisted)
120
+ outcomes = answer(write["toolInvocationId"], "approve")
121
+ await run_turn(agent, rebooted, Ctx(trigger="input-resume", input_outcomes=outcomes))
122
+ task, _ns, write = parked(rebooted)
123
+ assert write["state"] == "done" and not write.get("isError", False)
124
+ assert task["state"] == "done"
125
+ assert "/notes.md" in (await agent.aget_state(rebooted.config())).values["files"]
126
+
127
+
128
+ class _Interrupt:
129
+ def __init__(self, id, value):
130
+ self.id, self.value = id, value
131
+
132
+
133
+ async def test_approvals_from_two_subagents_at_once_fail_the_turn():
134
+ _agent, thread = await build()
135
+ hitl = {"action_requests": [{"name": "write_file", "args": NOTES}]}
136
+ interrupts = (_Interrupt("i1", hitl), _Interrupt("i2", hitl))
137
+ thread.append_event(("tools:a",), "updates", {"__interrupt__": interrupts[:1]})
138
+ thread.append_event(("tools:b",), "updates", {"__interrupt__": interrupts[1:]})
139
+ with pytest.raises(ValueError, match="more than one agent"):
140
+ thread.append_event((), "updates", {"__interrupt__": interrupts})
141
+ assert thread.interrupt is None
142
+
143
+
144
+ async def test_a_second_interrupt_in_the_turn_fails_it_instead_of_replacing_the_first():
145
+ agent, thread = await build()
146
+ await run_turn(agent, thread, Ctx(messages=(user("delegate write the notes"),)))
147
+ parked_ids = thread.interrupt
148
+ hitl = {"action_requests": [{"name": "write_file", "args": NOTES}]}
149
+ with pytest.raises(ValueError, match="more than one agent"):
150
+ thread.append_event((), "updates", {"__interrupt__": (_Interrupt("other", hitl),)})
151
+ assert thread.interrupt == parked_ids
152
+
153
+
154
+ async def test_resume_answers_the_parked_call_even_when_the_task_call_shares_its_id():
155
+ agent, thread = await build()
156
+ await run_turn(agent, thread, Ctx(messages=(user("delegate write the notes"),)))
157
+ task, ns, write = parked(thread)
158
+ # a provider reusing ids: the main reply's task part carries the parked call's id
159
+ head = thread.tree.get(MAIN_NS, thread.tree.thread(MAIN_NS).head)
160
+ head["parts"][0]["toolInvocationId"] = write["toolInvocationId"]
161
+ assert thread._parked_path(MAIN_NS, {write["toolInvocationId"]}) == [MAIN_NS, ns]
162
+
163
+
164
+ def make_host():
165
+ class Host(DeepagentsHost):
166
+ checkpointer = InMemorySaver()
167
+ index = MemoryCheckpointIndex()
168
+
169
+ def build_agent(self, checkpointer):
170
+ return create_agent(checkpointer)
171
+
172
+ return Host
173
+
174
+
175
+ async def test_the_host_requests_one_approval_for_the_subagent_call():
176
+ async with statewire_client(make_host(), worker=Worker(state_store=MemoryStateStore())) as (app, client):
177
+ async with stream_of(app, client_id="c1", headers=NEGOTIATION) as stream:
178
+ snapshot = await stream.next_event()
179
+ drv = VoiceDriver(client, stream, app, client_id="c1", protocol="harness-sdk")
180
+ apply_ops(drv.replica, copy.deepcopy(snapshot))
181
+ drv.fold(snapshot)
182
+ message = {"id": "u1", "role": "user", "parts": [{"type": "text", "text": "delegate write the notes"}]}
183
+ drv.post("run/send", {"runId": uuid4().hex, "message": message, "runAnchorMessageId": None, "behavior": "queue"})
184
+ await drv.wait_status("input-required")
185
+ host = (await app.state.pinboard_host.directory.get("t1")).instance
186
+ _task, _ns, write = parked(host.messages)
187
+ (request,) = drv.run["inputRequests"]
188
+ assert request["type"] == "tool-approval" and request["toolCallId"] == write["toolInvocationId"]
189
+
190
+ drv.post("run/input", {"requestId": request["id"], "response": {"decision": "approve"}})
191
+ await drv.wait_status("ready")
192
+ task, _ns, write = parked(host.messages)
193
+ assert task["state"] == "done" and write["state"] == "done"
@@ -0,0 +1,114 @@
1
+ """The local-Origin guard every Python example server copies (examples/**/local_origin.py)."""
2
+
3
+ import importlib.util
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+ from starlette.applications import Starlette
8
+ from starlette.responses import PlainTextResponse
9
+ from starlette.routing import Route, WebSocketRoute
10
+ from starlette.testclient import TestClient
11
+ from starlette.websockets import WebSocket, WebSocketDisconnect
12
+
13
+ ROOT = Path(__file__).resolve().parents[3]
14
+ COPIES = [
15
+ ROOT / "examples/harness-sdk/deepagents/backend/local_origin.py",
16
+ ROOT / "examples/pinboard/fleet/backend/local_origin.py",
17
+ ROOT / "examples/pinboard/durability/backend/local_origin.py",
18
+ ROOT / "python/harness-sdk-python/examples/local_origin.py",
19
+ ROOT / "python/statewire/statewire/examples/local_origin.py",
20
+ ]
21
+
22
+
23
+ def test_copies_match():
24
+ texts = {path.read_text() for path in COPIES}
25
+ assert len(texts) == 1
26
+
27
+
28
+ @pytest.fixture(params=COPIES, ids=lambda p: str(p.parent.relative_to(ROOT)))
29
+ def client(request, monkeypatch):
30
+ monkeypatch.setenv("ALLOWED_ORIGINS", "http://192.168.1.20:5173/")
31
+ spec = importlib.util.spec_from_file_location("local_origin_copy", request.param)
32
+ module = importlib.util.module_from_spec(spec)
33
+ spec.loader.exec_module(module)
34
+
35
+ async def ws(socket: WebSocket) -> None:
36
+ await socket.accept()
37
+ await socket.send_text("hi")
38
+ await socket.close()
39
+
40
+ app = Starlette(
41
+ routes=[
42
+ Route("/", lambda _: PlainTextResponse("ok"), methods=["GET", "POST"]),
43
+ WebSocketRoute("/ws", ws),
44
+ ]
45
+ )
46
+ app.add_middleware(module.local_origin_only)
47
+ with TestClient(app) as test_client:
48
+ yield test_client
49
+
50
+
51
+ @pytest.mark.parametrize(
52
+ "origin",
53
+ ["https://evil.example", "null", "http://localhost.evil.example", "file://"],
54
+ )
55
+ def test_refuses_other_origins(client, origin):
56
+ response = client.get("/", headers={"origin": origin})
57
+ assert response.status_code == 403
58
+ with pytest.raises(WebSocketDisconnect) as closed:
59
+ with client.websocket_connect("/ws", headers={"origin": origin}):
60
+ pass
61
+ assert closed.value.code == 1008
62
+
63
+
64
+ @pytest.mark.parametrize(
65
+ "origin",
66
+ [
67
+ "http://localhost:5950",
68
+ "http://127.0.0.1:8950",
69
+ "http://[::1]:3000",
70
+ "http://192.168.1.20:5173",
71
+ ],
72
+ )
73
+ def test_passes_local_and_listed(client, origin):
74
+ headers = {"origin": origin}
75
+ assert client.get("/", headers=headers).text == "ok"
76
+ with client.websocket_connect("/ws", headers=headers) as socket:
77
+ assert socket.receive_text() == "hi"
78
+
79
+
80
+ @pytest.mark.parametrize(
81
+ "headers",
82
+ [
83
+ {},
84
+ {"sec-fetch-site": "cross-site"},
85
+ {"sec-fetch-site": "cross-site", "x-local-client": "1"},
86
+ {"origin": "https://evil.example", "x-local-client": "1"},
87
+ ],
88
+ ids=["bare", "cross-site", "cross-site-with-header", "evil-with-header"],
89
+ )
90
+ def test_refuses_originless_without_proof(client, headers):
91
+ assert client.get("/", headers=headers).status_code == 403
92
+ assert client.post("/", headers=headers).status_code == 403
93
+ with pytest.raises(WebSocketDisconnect) as closed:
94
+ with client.websocket_connect("/ws", headers=headers):
95
+ pass
96
+ assert closed.value.code == 1008
97
+
98
+
99
+ @pytest.mark.parametrize(
100
+ "headers",
101
+ [
102
+ {"sec-fetch-site": "same-origin"},
103
+ {"sec-fetch-site": "same-site"},
104
+ {"sec-fetch-site": "none"},
105
+ {"x-local-client": "1"},
106
+ {"pinboard-attestation": "token"},
107
+ {"pinboard-proxy-secret": "secret"},
108
+ ],
109
+ ids=lambda h: ",".join(f"{k}={v}" for k, v in h.items()),
110
+ )
111
+ def test_passes_originless_with_proof(client, headers):
112
+ assert client.get("/", headers=headers).text == "ok"
113
+ with client.websocket_connect("/ws", headers=headers) as socket:
114
+ assert socket.receive_text() == "hi"
@@ -6,7 +6,7 @@ from contextlib import asynccontextmanager
6
6
  import httpx
7
7
  import pytest
8
8
  from fastapi import FastAPI
9
- from pinboard import PinboardAPI, PinboardHost, Worker, route
9
+ from pinboard import AuthRejected, PinboardAPI, PinboardHost, Worker, route
10
10
  from pinboard.testing import MemoryStateStore
11
11
  from run_helpers import RunDriver, Script, add, make_host
12
12
  from statewire.protocol import VERSION, Offer, VersionRange, headers as protocol_headers
@@ -34,10 +34,17 @@ class Toucher(PinboardAPI):
34
34
  return {"status": response.status_code}
35
35
 
36
36
 
37
+ class OpenThreads(HarnessThreads):
38
+ """A list every attacher may read and edit, as a single-user test host."""
39
+
40
+ async def authorize(self, conn):
41
+ return None
42
+
43
+
37
44
  @asynccontextmanager
38
- async def thread_list():
45
+ async def thread_list(cls=OpenThreads):
39
46
  worker = Worker()
40
- lists = PinboardHost(HarnessThreads, worker=worker, namespace="/threads")
47
+ lists = PinboardHost(cls, worker=worker, namespace="/threads")
41
48
  callers = PinboardHost(Toucher, worker=worker, namespace="/callers")
42
49
  app = FastAPI()
43
50
  app.include_router(worker)
@@ -58,16 +65,16 @@ def ids(state):
58
65
  return [t["id"] for t in state["threads"]]
59
66
 
60
67
 
61
- async def attached(app, client_id="c1"):
62
- stream = stream_of(app, client_id=client_id, headers=NEGOTIATION)
68
+ async def attached(app, client_id="c1", headers=None):
69
+ stream = stream_of(app, client_id=client_id, headers={**NEGOTIATION, **(headers or {})})
63
70
  await stream.__aenter__()
64
71
  snapshot = await stream.next_event()
65
72
  state = apply_ops({}, snapshot)
66
73
  return stream, state
67
74
 
68
75
 
69
- async def snapshot(app, client_id):
70
- stream, state = await attached(app, client_id)
76
+ async def snapshot(app, client_id, headers=None):
77
+ stream, state = await attached(app, client_id, headers)
71
78
  await stream.__aexit__(None, None, None)
72
79
  return state
73
80
 
@@ -180,14 +187,52 @@ async def test_touch_refuses_unattested_callers_and_bad_bodies():
180
187
  assert ids(await snapshot(app, "c1")) == []
181
188
 
182
189
 
190
+ async def test_default_list_refuses_attaches_but_takes_touches():
191
+ async with thread_list(HarnessThreads) as (app, client):
192
+ await touch(client, "a", title="First")
193
+ response = await client.get("/threads/t1/stream", headers={CLIENT_ID_HEADER: "c1"})
194
+ assert response.status_code == 403, response.text
195
+
196
+
197
+ MEMBERS = {"alice": {"t1"}, "bob": {"w2"}} # the list under test is workspace t1
198
+
199
+
200
+ class WorkspaceThreads(HarnessThreads):
201
+ """One list per workspace: admits members of the list's workspace."""
202
+
203
+ async def authorize(self, conn):
204
+ user = conn.headers.get("x-test-user")
205
+ if self.workspace_id not in MEMBERS.get(user, set()):
206
+ raise AuthRejected("not a member of this workspace", status_code=403)
207
+ return user
208
+
209
+
210
+ async def test_authorize_admits_workspace_members_only():
211
+ async with thread_list(WorkspaceThreads) as (app, client):
212
+ await touch(client, "a", title="First")
213
+ for user in ("bob", None):
214
+ headers = {CLIENT_ID_HEADER: "c1", **({"x-test-user": user} if user else {})}
215
+ refused = await client.get("/threads/t1/stream", headers=headers)
216
+ assert refused.status_code == 403, refused.text
217
+ state = await snapshot(app, "c1", headers={"x-test-user": "alice"})
218
+ assert ids(state) == ["a"]
219
+
220
+
221
+ def test_thread_list_attribute_is_refused():
222
+ with pytest.raises(TypeError, match="workspace_id"):
223
+
224
+ class Old(HarnessMessages):
225
+ thread_list = "/thread-lists/default"
226
+
227
+
183
228
  @asynccontextmanager
184
229
  async def listed_host(script):
185
230
  class Host(HarnessMessages, make_host(script)):
186
231
  protocols = (HARNESS_PROTOCOL,)
187
- thread_list = "/thread-lists/l1"
232
+ workspace_id = "l1"
188
233
 
189
234
  worker = Worker(state_store=MemoryStateStore())
190
- lists = PinboardHost(HarnessThreads, worker=worker, namespace="/thread-lists")
235
+ lists = PinboardHost(OpenThreads, worker=worker, namespace="/thread-lists")
191
236
  hosts = PinboardHost(Host, worker=worker, namespace="/threads")
192
237
  app = FastAPI()
193
238
  app.include_router(worker)
@@ -250,6 +295,30 @@ async def test_host_reports_activity_on_every_status_transition():
250
295
  await activities(app, ("error", "Hello there"))
251
296
 
252
297
 
298
+ async def listing(app, workspace_id, client_id):
299
+ stream = SSEStream(app, f"/thread-lists/{workspace_id}/stream", headers={**NEGOTIATION, CLIENT_ID_HEADER: client_id})
300
+ await stream.__aenter__()
301
+ try:
302
+ return apply_ops({}, await stream.next_event())
303
+ finally:
304
+ await stream.__aexit__(None, None, None)
305
+
306
+
307
+ async def test_a_thread_lists_itself_only_in_its_workspace():
308
+ script = Script()
309
+ async with listed_host(script) as (app, drv, host):
310
+ drv.post("run/send", add("m1", behavior="queue"))
311
+ call = await script.next_call()
312
+ await drv.wait_status("running")
313
+ await activities(app, ("running", None))
314
+ assert ids(await listing(app, "w2", "x1")) == []
315
+ call.applied()
316
+ call.finish(RunManager.Complete())
317
+ await drv.wait_status("ready")
318
+ await activities(app, ("idle", None))
319
+ assert ids(await listing(app, "w2", "x2")) == []
320
+
321
+
253
322
  def test_first_user_text_reads_the_head_chain():
254
323
  tree = MessageTree()
255
324
  tree.add("main", {"id": "u1", "parentId": None, "role": "user", "parts": [{"type": "text", "text": " Hello "}, {"type": "text", "text": "x" * 100}]})