harness-sdk-python 0.40.8__py3-none-any.whl → 0.40.11__py3-none-any.whl

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.
harness_sdk/deepagents.py CHANGED
@@ -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()
harness_sdk/threads.py CHANGED
@@ -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
 
harness_sdk/wire.py CHANGED
@@ -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
@@ -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'
@@ -1,6 +1,6 @@
1
1
  harness_sdk/__init__.py,sha256=x-vDKSqkPGcjLZ3N2nWtM37RyS-KifXtfKBPy4IOnjE,2285
2
2
  harness_sdk/checkpoints.py,sha256=Iuum5x4KjsvJajDPP9TLFKcKQouOo-05jnCP3SJCD2s,30726
3
- harness_sdk/deepagents.py,sha256=sRsXNA5OhVE96jEKLUnGIKSLXp2ADheEaxu8pqwy_1c,25595
3
+ harness_sdk/deepagents.py,sha256=eKkNGgEXEFMUY9FDT-REKGHmkfbOofiw5oH3k7jt9lg,27346
4
4
  harness_sdk/deepagents_host.py,sha256=Psv66_Y0eJQu4sjBdGiwqrEdusY6kHXOotb1v35NNT8,9668
5
5
  harness_sdk/fenced_postgres.py,sha256=hbbrMR1WaqrHTNgd4wFrXfRrzQFGnyim-c8nZXgwWp4,13235
6
6
  harness_sdk/interest.py,sha256=KnmbTcF7fQha69Zuvu0_solI44Olp-eSv-qkltZ-hAU,5141
@@ -11,12 +11,12 @@ harness_sdk/parts.py,sha256=mHhYvmQx6J56Ah5K7dUZ4qUOlKk-L02AR64asSqOT5I,6400
11
11
  harness_sdk/prioritize.py,sha256=Li8IoI_ACiwbWDNa2DSDpNhoXY0utPhGevBQqQonsQc,4203
12
12
  harness_sdk/protocol.py,sha256=VxWOIg_2vitFGTJmpiD2wNNAJnwSgQFy69Hds-frfvs,1207
13
13
  harness_sdk/run_manager.py,sha256=nXxXJAGaTVKh_yv6_sF7DQ-V_wY0sIFV2AQBJOwOFNY,111859
14
- harness_sdk/threads.py,sha256=hpsS7GOZPVKfWFSMydJSdzzz5KY38pLWQQR-DkdoG2M,7151
14
+ harness_sdk/threads.py,sha256=eSe1c_xR7bobIKKFbuvNUSHFexTkzkd6FEpcmKyGVG0,8148
15
15
  harness_sdk/voice.py,sha256=XJakSJrjS-RVT1PIaDDxm1RZDp9QpLWCdX36k-UvGHA,25852
16
16
  harness_sdk/voice_thread.py,sha256=B616W1efohEd9RwWssrOkTne7Lu8s0kn07kMof1v_nI,6910
17
- harness_sdk/wire.py,sha256=m3hixpDPls413Ihr0tym5dlgsd334WaK0fISMpVMY3g,7978
17
+ harness_sdk/wire.py,sha256=Ln7uBcH2SS08U61ueLYX1M8il_4HMX27GmfRe7ZsnhI,8787
18
18
  harness_sdk/providers/__init__.py,sha256=PjVKflqdtYSipq0ISTNuIYKeCOm3KX8ov9XuNtBhFrs,75
19
19
  harness_sdk/providers/gpt_live.py,sha256=cuODSm3Kztemf51BIOuPwy1Wf-0pOhf1LPYzmSdCvl8,8453
20
- harness_sdk_python-0.40.8.dist-info/METADATA,sha256=LT6790AvckicSRK5HaY-Pwky1bxOwlT-q55la9xBZVc,4022
21
- harness_sdk_python-0.40.8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
22
- harness_sdk_python-0.40.8.dist-info/RECORD,,
20
+ harness_sdk_python-0.40.11.dist-info/METADATA,sha256=UoQQ4speHkz6mqGpuGFvYWgiz6uAO8ezu1oQ_u8P9-E,4023
21
+ harness_sdk_python-0.40.11.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
22
+ harness_sdk_python-0.40.11.dist-info/RECORD,,