harness-sdk-python 0.40.13__tar.gz → 0.41.1__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 (90) hide show
  1. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/PKG-INFO +13 -25
  2. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/README.md +9 -22
  3. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/examples/local_origin.py +2 -0
  4. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/examples/runs_app.py +3 -37
  5. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/pyproject.toml +3 -3
  6. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/__init__.py +7 -1
  7. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/checkpoints.py +3 -2
  8. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/deepagents_host.py +0 -20
  9. harness_sdk_python-0.41.1/src/harness_sdk/drafts.py +87 -0
  10. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/fenced_postgres.py +3 -3
  11. harness_sdk_python-0.41.1/src/harness_sdk/host.py +134 -0
  12. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/interest.py +1 -4
  13. harness_sdk_python-0.41.1/src/harness_sdk/limits.py +40 -0
  14. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/messages.py +5 -0
  15. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/prioritize.py +5 -10
  16. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/run_manager.py +157 -23
  17. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/voice.py +43 -18
  18. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/voice_thread.py +3 -8
  19. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/wire.py +3 -1
  20. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/run_helpers.py +2 -2
  21. harness_sdk_python-0.41.1/tests/test_conformance.py +168 -0
  22. harness_sdk_python-0.41.1/tests/test_drafts.py +173 -0
  23. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_edit_dispatched.py +25 -0
  24. harness_sdk_python-0.41.1/tests/test_harness_host.py +225 -0
  25. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_input_required.py +22 -0
  26. harness_sdk_python-0.41.1/tests/test_limits.py +26 -0
  27. harness_sdk_python-0.41.1/tests/test_resend.py +53 -0
  28. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_rewind_during_run.py +67 -0
  29. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_settle.py +19 -0
  30. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_threads.py +4 -4
  31. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_voice_events.py +24 -3
  32. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/voice_helpers.py +2 -2
  33. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/.gitignore +0 -0
  34. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/examples/__init__.py +0 -0
  35. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/deepagents.py +0 -0
  36. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/langgraph.py +0 -0
  37. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/linear_thread.py +0 -0
  38. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/parts.py +0 -0
  39. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/protocol.py +0 -0
  40. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/providers/__init__.py +0 -0
  41. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/providers/gpt_live.py +0 -0
  42. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/src/harness_sdk/threads.py +0 -0
  43. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_admit_steer.py +0 -0
  44. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_applied_visibility.py +0 -0
  45. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_batches.py +0 -0
  46. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_branch_anchor.py +0 -0
  47. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_checkpoints.py +0 -0
  48. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_deepagents_approval.py +0 -0
  49. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_deepagents_files.py +0 -0
  50. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_deepagents_multi_approval.py +0 -0
  51. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_deepagents_outcome.py +0 -0
  52. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_deepagents_subagent_approval.py +0 -0
  53. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_deepagents_thread.py +0 -0
  54. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_deepagents_user_ids.py +0 -0
  55. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_deepagents_voice.py +0 -0
  56. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_dispatching.py +0 -0
  57. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_durability.py +0 -0
  58. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_edit_reload.py +0 -0
  59. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_enqueue.py +0 -0
  60. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_example_local_origin.py +0 -0
  61. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_fenced_postgres.py +0 -0
  62. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_gpt_live.py +0 -0
  63. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_imports.py +0 -0
  64. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_interest.py +0 -0
  65. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_langgraph.py +0 -0
  66. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_linear_thread.py +0 -0
  67. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_meta.py +0 -0
  68. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_mint_concurrency.py +0 -0
  69. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_outcomes.py +0 -0
  70. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_parts.py +0 -0
  71. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_placement.py +0 -0
  72. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_prepare_hooks.py +0 -0
  73. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_prioritize.py +0 -0
  74. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_prioritize_builtins.py +0 -0
  75. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_request_options.py +0 -0
  76. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_restore.py +0 -0
  77. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_run_admission.py +0 -0
  78. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_run_crash_sweep.py +0 -0
  79. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_run_eviction.py +0 -0
  80. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_run_id_bounds.py +0 -0
  81. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_run_ownership.py +0 -0
  82. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_run_sync.py +0 -0
  83. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_stale_redelivery.py +0 -0
  84. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_steer.py +0 -0
  85. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_stop_continue.py +0 -0
  86. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_stopping_window.py +0 -0
  87. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_undo.py +0 -0
  88. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_voice.py +0 -0
  89. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_voice_delegation.py +0 -0
  90. {harness_sdk_python-0.40.13 → harness_sdk_python-0.41.1}/tests/test_wire.py +0 -0
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: harness-sdk-python
3
- Version: 0.40.13
3
+ Version: 0.41.1
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.4
9
- Requires-Dist: statewire<0.27,>=0.26.0
8
+ Requires-Dist: pinboard-sdk>=0.18.5
9
+ Requires-Dist: statewire<0.28,>=0.27.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'
@@ -17,6 +17,7 @@ Provides-Extra: llm
17
17
  Requires-Dist: langchain-core>=0.3; extra == 'llm'
18
18
  Provides-Extra: postgres
19
19
  Requires-Dist: langgraph-checkpoint-postgres>=2.0.0; extra == 'postgres'
20
+ Requires-Dist: pinboard-sdk[postgres]>=0.18.5; extra == 'postgres'
20
21
  Provides-Extra: typesafe
21
22
  Requires-Dist: typesafe-sdk<0.8,>=0.7.5; extra == 'typesafe'
22
23
  Provides-Extra: voice
@@ -39,35 +40,22 @@ Extras: `uv add "harness-sdk-python[postgres]"`, `uv add "harness-sdk-python[dee
39
40
  ## Use
40
41
 
41
42
  ```python
42
- from statewire import Statewire, command
43
+ import asyncio
43
44
 
44
- from harness_sdk import HARNESS_PROTOCOL, RunManager, run_manager
45
+ from harness_sdk import harness_app, message_text
45
46
 
46
47
 
47
- class RunsHost(Statewire):
48
- protocols = (HARNESS_PROTOCOL,)
48
+ async def echo(messages):
49
+ for word in ["echo:", *message_text(messages[-1]).split()]:
50
+ await asyncio.sleep(0.05)
51
+ yield word + " "
49
52
 
50
- async def lifespan(self):
51
- self.state = {"messages": []}
52
- yield
53
53
 
54
- @run_manager()
55
- async def run(self, ctx: RunManager.RunContext):
56
- for message in ctx.messages:
57
- self.state["messages"].append({"id": message["id"]})
58
- ctx.applied()
59
- return RunManager.Complete()
60
-
61
- @command("run/send")
62
- async def run_send(self, params, *, ctx, auth_result):
63
- return await self.run.send(
64
- params,
65
- applied=ctx.applied,
66
- auth_result=auth_result,
67
- version=ctx.version,
68
- )
54
+ app = harness_app(echo)
69
55
  ```
70
56
 
57
+ `PINBOARD_DEV=1 uv run uvicorn app:app` serves threads at `/threads/<id>` for `useHarness`. `harness_app` wraps `HarnessHost`: subclass it to override `respond`, or put `@run_manager` on your own Statewire host; either way the host serves the `run/*` commands.
58
+
71
59
  ## Prioritize
72
60
 
73
61
  `run/send` takes `behavior`: `"steer"` folds the message into the live run, `"preempt"` stops the live run and runs the message next, `"queue"` runs it after the live run. The default `"auto"` asks `prioritize` while a run is live (no prioritizer, a failure, or an invalid answer steers) and queues otherwise.
@@ -13,35 +13,22 @@ Extras: `uv add "harness-sdk-python[postgres]"`, `uv add "harness-sdk-python[dee
13
13
  ## Use
14
14
 
15
15
  ```python
16
- from statewire import Statewire, command
16
+ import asyncio
17
17
 
18
- from harness_sdk import HARNESS_PROTOCOL, RunManager, run_manager
18
+ from harness_sdk import harness_app, message_text
19
19
 
20
20
 
21
- class RunsHost(Statewire):
22
- protocols = (HARNESS_PROTOCOL,)
21
+ async def echo(messages):
22
+ for word in ["echo:", *message_text(messages[-1]).split()]:
23
+ await asyncio.sleep(0.05)
24
+ yield word + " "
23
25
 
24
- async def lifespan(self):
25
- self.state = {"messages": []}
26
- yield
27
26
 
28
- @run_manager()
29
- async def run(self, ctx: RunManager.RunContext):
30
- for message in ctx.messages:
31
- self.state["messages"].append({"id": message["id"]})
32
- ctx.applied()
33
- return RunManager.Complete()
34
-
35
- @command("run/send")
36
- async def run_send(self, params, *, ctx, auth_result):
37
- return await self.run.send(
38
- params,
39
- applied=ctx.applied,
40
- auth_result=auth_result,
41
- version=ctx.version,
42
- )
27
+ app = harness_app(echo)
43
28
  ```
44
29
 
30
+ `PINBOARD_DEV=1 uv run uvicorn app:app` serves threads at `/threads/<id>` for `useHarness`. `harness_app` wraps `HarnessHost`: subclass it to override `respond`, or put `@run_manager` on your own Statewire host; either way the host serves the `run/*` commands.
31
+
45
32
  ## Prioritize
46
33
 
47
34
  `run/send` takes `behavior`: `"steer"` folds the message into the live run, `"preempt"` stops the live run and runs the message next, `"queue"` runs it after the live run. The default `"auto"` asks `prioritize` while a run is live (no prioritizer, a failure, or an invalid answer steers) and queues otherwise.
@@ -19,6 +19,8 @@ from urllib.parse import urlsplit
19
19
 
20
20
  _ENV = os.environ.get("ALLOWED_ORIGINS", "").split(",")
21
21
  EXTRA = {o.strip().rstrip("/") for o in _ENV if o.strip()}
22
+ # a Statewire host's allowed_origins: these origins attach there too
23
+ ALLOWED_ORIGINS = tuple(sorted(EXTRA))
22
24
  LOOPBACK = ("localhost", "127.0.0.1", "::1")
23
25
  LOCAL_FETCH_SITES = ("same-origin", "same-site", "none")
24
26
  LOCAL_CLIENT_HEADER = b"x-local-client"
@@ -21,12 +21,12 @@ from fastapi import FastAPI
21
21
  from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
22
22
  from pinboard import Worker
23
23
  from pinboard.durability import MemoryStateStore
24
- from statewire import Statewire, command, plain
24
+ from statewire import Statewire, plain
25
25
  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
29
+ from .local_origin import ALLOWED_ORIGINS, local_origin_only
30
30
 
31
31
 
32
32
  def select_model() -> str:
@@ -77,6 +77,7 @@ def user_text(message: dict[str, Any]) -> str:
77
77
 
78
78
  class RunsHost(Statewire):
79
79
  protocols = (Statewire.Protocol("harness-sdk"),)
80
+ allowed_origins = ALLOWED_ORIGINS
80
81
 
81
82
  async def lifespan(self):
82
83
  self.agent = build_agent()
@@ -157,41 +158,6 @@ class RunsHost(Statewire):
157
158
  with contextlib.suppress(Exception):
158
159
  await stream.aclose()
159
160
 
160
- @command("run/send")
161
- async def run_send(self, params, *, ctx, auth_result):
162
- return await self.run.send(
163
- params,
164
- applied=ctx.applied,
165
- auth_result=auth_result,
166
- version=ctx.version,
167
- )
168
-
169
- @command("run/dequeue")
170
- async def run_dequeue(self, params, *, auth_result):
171
- return await self.run.dequeue(params, auth_result=auth_result)
172
-
173
- @command("run/edit")
174
- async def run_edit(self, params, *, ctx, auth_result):
175
- return await self.run.edit(params, applied=ctx.applied, auth_result=auth_result)
176
-
177
- @command("run/reload")
178
- async def run_reload(self, params, *, ctx, auth_result):
179
- return await self.run.reload(
180
- params, applied=ctx.applied, auth_result=auth_result
181
- )
182
-
183
- @command("run/stop")
184
- async def run_stop(self, params=None, *, ctx, auth_result):
185
- return await self.run.stop(params, applied=ctx.applied, auth_result=auth_result)
186
-
187
- @command("run/continue")
188
- async def run_continue(self, params=None, *, ctx, auth_result):
189
- return await self.run.continue_run(applied=ctx.applied, auth_result=auth_result)
190
-
191
- @command("run/input")
192
- async def run_input(self, params, *, auth_result):
193
- return await self.run.input(params, auth_result=auth_result)
194
-
195
161
 
196
162
  worker = Worker(hosts={"/threads": RunsHost}, state_store=MemoryStateStore())
197
163
  app = FastAPI()
@@ -1,14 +1,14 @@
1
1
  [project]
2
2
  name = "harness-sdk-python"
3
- version = "0.40.13"
3
+ version = "0.41.1"
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.26.0,<0.27", "pinboard-sdk>=0.18.4"]
8
+ dependencies = ["statewire>=0.27.0,<0.28", "pinboard-sdk>=0.18.5"]
9
9
 
10
10
  [project.optional-dependencies]
11
- postgres = ["langgraph-checkpoint-postgres>=2.0.0"]
11
+ postgres = ["langgraph-checkpoint-postgres>=2.0.0", "pinboard-sdk[postgres]>=0.18.5"]
12
12
  voice = ["httpx>=0.27", "websockets>=13"]
13
13
  llm = ["langchain-core>=0.3"]
14
14
  typesafe = ["typesafe-sdk>=0.7.5,<0.8"]
@@ -16,8 +16,10 @@ from .checkpoints import (
16
16
  )
17
17
  from .deepagents import DeepagentsThread, deepagents_role
18
18
  from .deepagents_host import DeepagentsHost
19
+ from .drafts import ComposerDrafts
20
+ from .host import HarnessHost, harness_app
19
21
  from .interest import InterestError, check_request, covered, resolve
20
- from .messages import MAIN_NS, MessageTree
22
+ from .messages import MAIN_NS, MessageTree, message_text
21
23
  from .parts import PartsAssembler
22
24
  from .linear_thread import linear_thread
23
25
  from .run_manager import RunManager, RunManagerDescriptor, run_manager
@@ -46,11 +48,13 @@ __all__ = [
46
48
  "ThreadStore",
47
49
  "DuplicateThread",
48
50
  "UnknownThread",
51
+ "HarnessHost",
49
52
  "HarnessMessages",
50
53
  "INTEREST",
51
54
  "CheckpointIndex",
52
55
  "CheckpointStore",
53
56
  "CheckpointThread",
57
+ "ComposerDrafts",
54
58
  "DeepagentsHost",
55
59
  "DeepagentsThread",
56
60
  "InterestError",
@@ -73,12 +77,14 @@ __all__ = [
73
77
  "covered",
74
78
  "deepagents_role",
75
79
  "end_voice",
80
+ "harness_app",
76
81
  "langgraph_checkpoints",
77
82
  "langgraph_checkpointer",
78
83
  "langgraph_snapshot",
79
84
  "langgraph_state_snapshot",
80
85
  "langgraph_switch_values",
81
86
  "linear_thread",
87
+ "message_text",
82
88
  "resolve",
83
89
  "run_manager",
84
90
  "set_voice_mic",
@@ -186,10 +186,11 @@ class PostgresCheckpointIndex:
186
186
  try:
187
187
  import psycopg
188
188
  import psycopg_pool
189
- except ImportError as exc:
189
+ except ModuleNotFoundError as exc:
190
190
  raise ImportError(
191
191
  "harness_sdk.checkpoints.PostgresCheckpointIndex requires the "
192
- "'postgres' extra: pip install 'harness-sdk-python[postgres]'"
192
+ f"'postgres' extra ({exc.name} is missing): "
193
+ "pip install 'harness-sdk-python[postgres]'"
193
194
  ) from exc
194
195
  if not isinstance(
195
196
  conn, (psycopg.AsyncConnection, psycopg_pool.AsyncConnectionPool)
@@ -200,27 +200,7 @@ class DeepagentsHost(VoiceThread, HarnessMessages, Statewire):
200
200
  self._check_user_message(params)
201
201
  return await self.run.send(params, applied=ctx.applied, auth_result=auth_result, version=ctx.version)
202
202
 
203
- @command("run/dequeue")
204
- async def run_dequeue(self, params, *, auth_result):
205
- return await self.run.dequeue(params, auth_result=auth_result)
206
-
207
203
  @command("run/edit")
208
204
  async def run_edit(self, params, *, ctx, auth_result):
209
205
  self._check_user_message(params)
210
206
  return await self.run.edit(params, applied=ctx.applied, auth_result=auth_result)
211
-
212
- @command("run/reload")
213
- async def run_reload(self, params, *, ctx, auth_result):
214
- return await self.run.reload(params, applied=ctx.applied, auth_result=auth_result)
215
-
216
- @command("run/stop")
217
- async def run_stop(self, params=None, *, ctx, auth_result):
218
- return await self.run.stop(params, applied=ctx.applied, auth_result=auth_result)
219
-
220
- @command("run/continue")
221
- async def run_continue(self, params=None, *, ctx, auth_result):
222
- return await self.run.continue_run(applied=ctx.applied, auth_result=auth_result)
223
-
224
- @command("run/input")
225
- async def run_input(self, params, *, auth_result):
226
- return await self.run.input(params, auth_result=auth_result)
@@ -0,0 +1,87 @@
1
+ """Each user's composer draft on a thread: one text per user, the last write wins."""
2
+
3
+ from dataclasses import replace
4
+ from functools import cached_property
5
+ from typing import Any
6
+
7
+ from pinboard.trays import Tray, persistent, tray
8
+ from statewire import StatewireAttach, StatewireReject, command
9
+ from statewire.documents import Document
10
+ from statewire.limits import MAX_EPHEMERAL_DOCUMENT_BYTES
11
+ from statewire.ops import encode_envelope
12
+ from statewire.protocol import Subprotocol
13
+
14
+ from .protocol import HARNESS_PROTOCOL
15
+
16
+ DRAFT = "harness-sdk/draft"
17
+
18
+
19
+ class DraftTexts(Tray):
20
+ texts = persistent({}) # user -> nonempty draft text
21
+
22
+ def items(self):
23
+ yield from ()
24
+
25
+
26
+ class ComposerDrafts:
27
+ """Statewire mixin keeping each user's composer draft on the thread; ``draft_user`` names the user."""
28
+
29
+ protocols = (
30
+ replace(
31
+ HARNESS_PROTOCOL,
32
+ subprotocols=(*HARNESS_PROTOCOL.subprotocols, Subprotocol("draft", record="ephemeral")),
33
+ ),
34
+ )
35
+
36
+ def draft_user(self, auth_result: Any) -> str | None:
37
+ """The user an attach's draft belongs to, from its auth result; ``None`` keeps no draft."""
38
+ raise NotImplementedError(f"{type(self).__name__}.draft_user")
39
+
40
+ @tray(DraftTexts)
41
+ async def drafts(self, item, ctx):
42
+ raise RuntimeError("the draft tray admits no work items")
43
+
44
+ @drafts.on_activate
45
+ async def _hold_drafts(self, _id: str, drafts: DraftTexts):
46
+ self._drafts = drafts
47
+ yield
48
+
49
+ @cached_property
50
+ def _draft_documents(self) -> dict[str, tuple[str, Any]]:
51
+ return {}
52
+
53
+ def _user(self, auth_result: Any) -> str | None:
54
+ user = self.draft_user(auth_result)
55
+ if user is not None and not isinstance(user, str):
56
+ raise TypeError(f"draft_user must return a string or None, got {user!r}")
57
+ return user
58
+
59
+ def attaching(self, attach: StatewireAttach) -> None:
60
+ super().attaching(attach)
61
+ user = self._user(attach.caller.auth_result)
62
+ if user is None:
63
+ attach.mount(DRAFT, None, main=True)
64
+ return
65
+ text = self._drafts.texts.value.get(user, "")
66
+ self._draft_documents[attach.id] = (user, attach.mount(DRAFT, {"text": text}, main=True))
67
+
68
+ def detached(self, attach: StatewireAttach) -> None:
69
+ super().detached(attach)
70
+ self._draft_documents.pop(attach.id, None)
71
+
72
+ @command("set", protocol=DRAFT)
73
+ async def draft_set(self, text, *, auth_result):
74
+ if not isinstance(text, str):
75
+ raise StatewireReject("a draft is a string", code="invalid-draft")
76
+ user = self._user(auth_result)
77
+ if user is None:
78
+ raise StatewireReject("this attach keeps no draft", code="no-draft")
79
+ if len(encode_envelope(Document(DRAFT, {"text": text}, main=True).mount(0))) > MAX_EPHEMERAL_DOCUMENT_BYTES:
80
+ raise StatewireReject("draft too large", code="oversized-document")
81
+ texts = {other: saved for other, saved in self._drafts.texts.value.items() if other != user}
82
+ if text != "":
83
+ texts[user] = text
84
+ self._drafts.texts.value = texts
85
+ for owner, document in self._draft_documents.values():
86
+ if owner == user:
87
+ document["text"] = text
@@ -12,10 +12,10 @@ try:
12
12
  from psycopg.cursor_async import AsyncCursor
13
13
  from psycopg.rows import DictRow, dict_row
14
14
  from psycopg.sql import SQL, Identifier, Literal
15
- except ImportError as exc:
15
+ except ModuleNotFoundError as exc:
16
16
  raise ImportError(
17
- "harness_sdk.fenced_postgres requires the 'postgres' extra: "
18
- "pip install 'harness-sdk-python[postgres]'"
17
+ f"harness_sdk.fenced_postgres requires the 'postgres' extra ({exc.name} is "
18
+ "missing): pip install 'harness-sdk-python[postgres]'"
19
19
  ) from exc
20
20
 
21
21
  DEFAULT_FENCE_TABLE = "checkpoint_fence"
@@ -0,0 +1,134 @@
1
+ """HarnessHost: the default harness host. One thread on the main namespace,
2
+ its status mirrored from the run machine, the ``run/*`` commands, and a reply
3
+ per batch streamed from ``respond``. ``harness_app`` serves one on FastAPI.
4
+ """
5
+
6
+ import asyncio
7
+ import contextlib
8
+ import uuid
9
+ from typing import Any, AsyncIterator, Callable
10
+
11
+ from fastapi import FastAPI
12
+ from pinboard import Worker
13
+ from pinboard.durability import MemoryStateStore
14
+ from statewire import Statewire, plain
15
+
16
+ from .messages import MAIN_NS
17
+ from .protocol import HARNESS_PROTOCOL
18
+ from .run_manager import RunManager, run_manager
19
+ from .wire import HarnessMessages
20
+
21
+ Respond = Callable[[list[dict[str, Any]]], AsyncIterator[str]]
22
+
23
+
24
+ class HarnessHost(HarnessMessages, Statewire):
25
+ """Subclass and implement ``respond(messages)``: an async generator of text deltas for the reply to ``messages``."""
26
+
27
+ protocols = (HARNESS_PROTOCOL,)
28
+
29
+ def respond(self, messages: list[dict[str, Any]]) -> AsyncIterator[str]:
30
+ raise NotImplementedError(f"{type(self).__name__}.respond")
31
+
32
+ async def lifespan(self):
33
+ self.state = {"threads": {MAIN_NS: {"status": "idle"}}}
34
+ yield
35
+
36
+ def history(self) -> list[dict[str, Any]]:
37
+ """The head chain, root first, as plain messages."""
38
+ thread = self.tree.thread(MAIN_NS)
39
+ if thread.head is None:
40
+ return []
41
+ return [plain(thread.messages[i]) for i in thread.chain(thread.head)]
42
+
43
+ def append(self, message: dict[str, Any]) -> str:
44
+ """Add ``message`` after the head and move the head to it."""
45
+ self.tree.add(MAIN_NS, {**message, "parentId": self.tree.thread(MAIN_NS).head})
46
+ self.refresh_messages()
47
+ return message["id"]
48
+
49
+ async def get_message_meta(self, message_id: str | None) -> dict[str, Any] | None:
50
+ thread = self.tree.thread(MAIN_NS)
51
+ if message_id is None:
52
+ return {"isLeaf": thread.head is None}
53
+ message = thread.messages.get(message_id)
54
+ if message is None:
55
+ return None
56
+ return {
57
+ "parentId": message["parentId"],
58
+ "role": message["role"],
59
+ "isLeaf": thread.head == message_id,
60
+ "onActiveBranch": thread.head is not None and message_id in thread.chain(thread.head),
61
+ }
62
+
63
+ def run_status_changed(self, status: str) -> None:
64
+ super().run_status_changed(status)
65
+ self.state["threads"][MAIN_NS]["status"] = "streaming" if status in ("running", "stopping") else "idle"
66
+
67
+ @run_manager(capabilities=("files", "rewind"))
68
+ async def runs(self, ctx: RunManager.RunContext) -> Any:
69
+ batch: tuple[dict[str, Any], ...] | None = None
70
+ if not ctx.resume:
71
+ if ctx.has_rollback:
72
+ self.tree.set_head(MAIN_NS, ctx.rollback_to)
73
+ self.refresh_messages()
74
+ batch = ctx.messages
75
+ while True:
76
+ if batch is not None:
77
+ for message in batch:
78
+ self.append(message)
79
+ ctx.applied().dur()
80
+ await self._reply(ctx)
81
+ if ctx.stop_requested.is_set():
82
+ return RunManager.Stop(dispatch_queue=True)
83
+ batch = ctx.steering.take()
84
+ if not batch:
85
+ return RunManager.Complete()
86
+
87
+ async def _reply(self, ctx: RunManager.RunContext) -> None:
88
+ history = self.history()
89
+ reply_id = self.append(
90
+ {"id": f"a-{uuid.uuid4()}", "role": "assistant", "parts": [{"type": "text", "text": "", "state": "streaming"}]}
91
+ )
92
+ # refresh_messages swaps the stored object when a message mounts or unmounts: re-read it per write
93
+ part = lambda: self.tree.get(MAIN_NS, reply_id)["parts"][0] # noqa: E731
94
+ stream = self.respond(history)
95
+ stop = asyncio.ensure_future(ctx.stop_requested.wait())
96
+ step: asyncio.Future[str] | None = None
97
+ try:
98
+ while True:
99
+ step = asyncio.ensure_future(anext(stream))
100
+ await asyncio.wait({step, stop}, return_when=asyncio.FIRST_COMPLETED)
101
+ if not step.done():
102
+ return
103
+ try:
104
+ delta = step.result()
105
+ except StopAsyncIteration:
106
+ return
107
+ if not isinstance(delta, str):
108
+ raise TypeError(f"respond must yield str, got {delta!r}")
109
+ part()["text"] += delta
110
+ finally:
111
+ stop.cancel()
112
+ if step is not None and not step.done():
113
+ step.cancel()
114
+ with contextlib.suppress(asyncio.CancelledError):
115
+ await step
116
+ part()["state"] = "done"
117
+ if hasattr(stream, "aclose"):
118
+ await stream.aclose()
119
+
120
+
121
+ def harness_app(
122
+ respond: Respond | type[Statewire],
123
+ *,
124
+ state_store: Any = None,
125
+ ) -> FastAPI:
126
+ """A FastAPI app serving threads at ``/threads/{id}``: ``respond`` is a ``HarnessHost.respond`` function or a host class; ``state_store`` defaults to memory."""
127
+ host = (
128
+ respond
129
+ if isinstance(respond, type)
130
+ else type(respond.__name__, (HarnessHost,), {"respond": staticmethod(respond)})
131
+ )
132
+ app = FastAPI()
133
+ app.include_router(Worker(hosts={"/threads": host}, state_store=MemoryStateStore() if state_store is None else state_store))
134
+ return app
@@ -7,12 +7,9 @@ from typing import Any
7
7
 
8
8
  from statepatch import plain
9
9
 
10
+ from .limits import DEFAULT_WINDOW, MAX_WINDOW
10
11
  from .messages import MessageTree, Thread
11
12
 
12
- MAX_WINDOW = 200
13
- MAX_INTERESTS = 16
14
- DEFAULT_WINDOW = 50
15
-
16
13
 
17
14
  def head_request(window: int = DEFAULT_WINDOW) -> dict[str, Any]:
18
15
  """The head window of the main thread: every attach starts with it."""
@@ -0,0 +1,40 @@
1
+ # Generated by scripts/limits.mjs from packages/harness-sdk/core/src/limits.json; edit the JSON and rerun it.
2
+
3
+ # Messages in the head window an attach starts with, and a client's window step.
4
+ DEFAULT_WINDOW = 50
5
+ # Messages an interest request asks for on each side of its anchor (before, after), and the largest client window step.
6
+ MAX_WINDOW = 200
7
+ # Interest requests in one attach's context.
8
+ MAX_INTERESTS = 16
9
+ # Queued messages per lane (per client id on in-process transports).
10
+ MAX_QUEUED = 50
11
+ # User-message ID length in characters; the voice- prefix is reserved.
12
+ MAX_MESSAGE_ID_LENGTH = 256
13
+ # Run ID length in characters.
14
+ MAX_RUN_ID_LENGTH = 256
15
+ # Encoded user message.
16
+ MAX_MESSAGE_BYTES = 1 * 1024 * 1024
17
+ # Unique IDs per run.
18
+ MAX_RUN_IDS = 4096
19
+ # Voice start attempts per client id per window; failed starts and supersedes count.
20
+ MAX_VOICE_STARTS = 5
21
+ # Voice start attempts per instance per window, across client ids.
22
+ MAX_HOST_VOICE_STARTS = 20
23
+ # Voice start budget window (rolling, in memory).
24
+ VOICE_START_WINDOW = 60.0
25
+ # Voice buffered turns.
26
+ MAX_BUFFERED_TURNS = 512
27
+ # Voice pending delegated tasks.
28
+ MAX_PENDING_TASKS = 64
29
+ # Voice text in UTF-8: all buffered turns together, each task text, each SDP offer.
30
+ MAX_VOICE_TEXT_BYTES = 1 * 1024 * 1024
31
+ # Voice provider ID length in characters.
32
+ MAX_VOICE_ID_LENGTH = 256
33
+ # Voice seed tail in messages.
34
+ VOICE_SEED_LIMIT = 128
35
+ # Voice owner departure grace.
36
+ VOICE_DEPARTURE_GRACE = 10.0
37
+ # Voice final flush attempts.
38
+ VOICE_FINAL_FLUSH_ATTEMPTS = 3
39
+ # Voice final flush retry spacing.
40
+ VOICE_FINAL_FLUSH_RETRY = 0.2
@@ -12,6 +12,11 @@ MAIN_NS = "main"
12
12
  _ROLES = ("user", "assistant")
13
13
 
14
14
 
15
+ def message_text(message: dict[str, Any]) -> str:
16
+ """The message's text parts, joined by blank lines."""
17
+ return "\n\n".join(p["text"] for p in message["parts"] if p["type"] == "text")
18
+
19
+
15
20
  def iso(at: datetime) -> str:
16
21
  return at.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
17
22
 
@@ -4,6 +4,7 @@ import asyncio
4
4
  import json
5
5
  from typing import TYPE_CHECKING, Any, Awaitable, Callable, Mapping
6
6
 
7
+ from .messages import message_text
7
8
  from .run_manager import RunManager
8
9
 
9
10
  if TYPE_CHECKING:
@@ -20,18 +21,12 @@ CRITERIA = {
20
21
  Prioritize = Callable[[RunManager.PrioritizeRequest], Awaitable[str]]
21
22
 
22
23
 
23
- def _text(message: Mapping[str, Any]) -> str:
24
- return "\n\n".join(
25
- part["text"] for part in message["parts"] if part.get("type") == "text"
26
- )
27
-
28
-
29
24
  def _state(req: RunManager.PrioritizeRequest) -> dict[str, Any]:
30
25
  return {
31
- "current": [_text(m) for m in req.run.messages],
32
- "steering": [_text(m) for m in req.run.steer_queue],
33
- "queued": [_text(m) for m in req.queue],
34
- "message": _text(req.message),
26
+ "current": [message_text(m) for m in req.run.messages],
27
+ "steering": [message_text(m) for m in req.run.steer_queue],
28
+ "queued": [message_text(m) for m in req.queue],
29
+ "message": message_text(req.message),
35
30
  }
36
31
 
37
32