harness-sdk-python 0.40.13__py3-none-any.whl → 0.41.1__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/__init__.py +7 -1
- harness_sdk/checkpoints.py +3 -2
- harness_sdk/deepagents_host.py +0 -20
- harness_sdk/drafts.py +87 -0
- harness_sdk/fenced_postgres.py +3 -3
- harness_sdk/host.py +134 -0
- harness_sdk/interest.py +1 -4
- harness_sdk/limits.py +40 -0
- harness_sdk/messages.py +5 -0
- harness_sdk/prioritize.py +5 -10
- harness_sdk/run_manager.py +157 -23
- harness_sdk/voice.py +43 -18
- harness_sdk/voice_thread.py +3 -8
- harness_sdk/wire.py +3 -1
- {harness_sdk_python-0.40.13.dist-info → harness_sdk_python-0.41.1.dist-info}/METADATA +13 -25
- harness_sdk_python-0.41.1.dist-info/RECORD +25 -0
- harness_sdk_python-0.40.13.dist-info/RECORD +0 -22
- {harness_sdk_python-0.40.13.dist-info → harness_sdk_python-0.41.1.dist-info}/WHEEL +0 -0
harness_sdk/__init__.py
CHANGED
|
@@ -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",
|
harness_sdk/checkpoints.py
CHANGED
|
@@ -186,10 +186,11 @@ class PostgresCheckpointIndex:
|
|
|
186
186
|
try:
|
|
187
187
|
import psycopg
|
|
188
188
|
import psycopg_pool
|
|
189
|
-
except
|
|
189
|
+
except ModuleNotFoundError as exc:
|
|
190
190
|
raise ImportError(
|
|
191
191
|
"harness_sdk.checkpoints.PostgresCheckpointIndex requires the "
|
|
192
|
-
"'postgres' extra
|
|
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)
|
harness_sdk/deepagents_host.py
CHANGED
|
@@ -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)
|
harness_sdk/drafts.py
ADDED
|
@@ -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
|
harness_sdk/fenced_postgres.py
CHANGED
|
@@ -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
|
|
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"
|
harness_sdk/host.py
ADDED
|
@@ -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
|
harness_sdk/interest.py
CHANGED
|
@@ -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."""
|
harness_sdk/limits.py
ADDED
|
@@ -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
|
harness_sdk/messages.py
CHANGED
|
@@ -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
|
|
harness_sdk/prioritize.py
CHANGED
|
@@ -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": [
|
|
32
|
-
"steering": [
|
|
33
|
-
"queued": [
|
|
34
|
-
"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
|
|
harness_sdk/run_manager.py
CHANGED
|
@@ -83,7 +83,7 @@ from pinboard.durability import FenceLost
|
|
|
83
83
|
from pinboard.trays import Tray, TrayDescriptor, TrayCtx, TrayMapNamespace, inbox
|
|
84
84
|
from pinboard.trays import persistent, persistent_outbox, persistent_queue
|
|
85
85
|
from statepatch import observable
|
|
86
|
-
from statewire import StatewireReject
|
|
86
|
+
from statewire import StatewireReject, command
|
|
87
87
|
from statewire.api import (
|
|
88
88
|
_admission_key,
|
|
89
89
|
_release_admission,
|
|
@@ -92,12 +92,16 @@ from statewire.api import (
|
|
|
92
92
|
)
|
|
93
93
|
from statewire.ops import encode_envelope
|
|
94
94
|
|
|
95
|
+
from .limits import (
|
|
96
|
+
MAX_MESSAGE_BYTES,
|
|
97
|
+
MAX_MESSAGE_ID_LENGTH,
|
|
98
|
+
MAX_QUEUED,
|
|
99
|
+
MAX_RUN_ID_LENGTH,
|
|
100
|
+
MAX_RUN_IDS,
|
|
101
|
+
)
|
|
102
|
+
|
|
95
103
|
logger = logging.getLogger(__name__)
|
|
96
104
|
|
|
97
|
-
MAX_MESSAGE_ID_LENGTH = 256
|
|
98
|
-
MAX_RUN_ID_LENGTH = 256
|
|
99
|
-
MAX_MESSAGE_BYTES = 1 << 20
|
|
100
|
-
MAX_RUN_IDS = 4096
|
|
101
105
|
|
|
102
106
|
_ABSENT: Any = object()
|
|
103
107
|
_LEAF_SEND_VERSION = "2026-11-02"
|
|
@@ -307,6 +311,28 @@ def _check_rewind_gate(caps: Any, in_flight: bool, command: str) -> None:
|
|
|
307
311
|
raise _reject("capability-missing", "the rewind capability is not enabled")
|
|
308
312
|
|
|
309
313
|
|
|
314
|
+
def _check_fresh_send(
|
|
315
|
+
message_id: str,
|
|
316
|
+
source_meta: dict[str, Any] | None,
|
|
317
|
+
anchor: Any,
|
|
318
|
+
anchor_meta: dict[str, Any] | None,
|
|
319
|
+
thread_empty: bool,
|
|
320
|
+
delivered: bool,
|
|
321
|
+
) -> None:
|
|
322
|
+
"""A minting send's checks against its empty machine, run before the mint so a refused send mints no run."""
|
|
323
|
+
if source_meta is not None or delivered:
|
|
324
|
+
raise _reject("duplicate-id", f"message id {message_id} is already used")
|
|
325
|
+
if anchor is _ABSENT:
|
|
326
|
+
raise _reject("invalid-message", "runAnchorMessageId is required")
|
|
327
|
+
if anchor is None:
|
|
328
|
+
if not thread_empty:
|
|
329
|
+
raise _reject("wrong-anchor", "a null anchor asserts an empty thread")
|
|
330
|
+
elif anchor_meta is None:
|
|
331
|
+
raise _reject("unknown-id", f"anchor {anchor} names nothing")
|
|
332
|
+
elif not anchor_meta["onActiveBranch"]:
|
|
333
|
+
raise _reject("wrong-anchor", f"anchor {anchor} is off the active branch")
|
|
334
|
+
|
|
335
|
+
|
|
310
336
|
def _check_rewind_anchor(params: Any, source_meta: dict[str, Any]) -> None:
|
|
311
337
|
anchor = params.get("runAnchorMessageId", _ABSENT)
|
|
312
338
|
if anchor is _ABSENT:
|
|
@@ -432,7 +458,7 @@ class RunManager(Tray):
|
|
|
432
458
|
rewind, and input requests, driven by the tray pump; status is derived."""
|
|
433
459
|
|
|
434
460
|
capabilities: frozenset[str] = frozenset()
|
|
435
|
-
max_queued: int =
|
|
461
|
+
max_queued: int = MAX_QUEUED
|
|
436
462
|
max_redelivery_age: float | None = None
|
|
437
463
|
prepare_message: Callable[[dict[str, Any]], dict[str, Any]] | None = None
|
|
438
464
|
prepare_input: Callable[[dict[str, Any]], dict[str, Any]] | None = None
|
|
@@ -498,6 +524,7 @@ class RunManager(Tray):
|
|
|
498
524
|
self._idle = asyncio.Event()
|
|
499
525
|
self._verdict_waiters: dict[str, "asyncio.Future[dict[str, Any]]"] = {}
|
|
500
526
|
self._reroute: Callable[[list[Any]], Coroutine[Any, Any, None]] | None = None
|
|
527
|
+
self._delivered_ids: set[str] = set()
|
|
501
528
|
|
|
502
529
|
async def lifecycle(self) -> AsyncIterator[None]:
|
|
503
530
|
self._schedule = self.handler.__self__.schedule
|
|
@@ -895,6 +922,7 @@ class RunManager(Tray):
|
|
|
895
922
|
self._stop_staged = False
|
|
896
923
|
preempt, self._preempt = self._preempt, False
|
|
897
924
|
if outcome is not None and outcome["kind"] == "complete":
|
|
925
|
+
self._delivered_ids.update(self.dispatchedIds.value)
|
|
898
926
|
self.dispatchedIds.value = []
|
|
899
927
|
if self._staged_rewind is not None:
|
|
900
928
|
rewind, self._staged_rewind = self._staged_rewind, None
|
|
@@ -1118,9 +1146,13 @@ class RunManager(Tray):
|
|
|
1118
1146
|
def _reclaim(self, item: Any) -> None:
|
|
1119
1147
|
# a crash between the dispatch record and the source clear leaves both
|
|
1120
1148
|
for lane, message in zip(item["lanes"], item["record"]["messages"]):
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1149
|
+
self._drop_claimed(lane, message["id"])
|
|
1150
|
+
|
|
1151
|
+
def _drop_claimed(self, lane: str, message_id: str) -> None:
|
|
1152
|
+
# by id: a move after the claim may have put another item ahead of it
|
|
1153
|
+
queue = self._lane(lane)
|
|
1154
|
+
if any(entry["id"] == message_id for entry in queue.value):
|
|
1155
|
+
queue.value = [entry for entry in queue.value if entry["id"] != message_id]
|
|
1124
1156
|
|
|
1125
1157
|
def _ack_delivery(self) -> None:
|
|
1126
1158
|
pass # _finish_settle acks at the run's settle; a follow-on may be staged by now
|
|
@@ -1241,7 +1273,10 @@ class RunManager(Tray):
|
|
|
1241
1273
|
if isinstance(outcome, RunManager.Complete) and (
|
|
1242
1274
|
self.dispatching.value is not None or self._unconsumed()
|
|
1243
1275
|
):
|
|
1244
|
-
raise RuntimeError(
|
|
1276
|
+
raise RuntimeError(
|
|
1277
|
+
"run returned Complete with an unconfirmed batch: call "
|
|
1278
|
+
"ctx.applied().dur() once the batch is in the executor's thread"
|
|
1279
|
+
)
|
|
1245
1280
|
if (
|
|
1246
1281
|
isinstance(outcome, (RunManager.Stop, RunManager.Error))
|
|
1247
1282
|
and outcome.dispatch_queue
|
|
@@ -1294,6 +1329,7 @@ class RunManager(Tray):
|
|
|
1294
1329
|
self._advance()
|
|
1295
1330
|
|
|
1296
1331
|
def _cancel_run(self, ctx: "RunManager.RunContext") -> None:
|
|
1332
|
+
staged_before = self._staged_rewind
|
|
1297
1333
|
self.outcome.value = {
|
|
1298
1334
|
"kind": "cancel",
|
|
1299
1335
|
"epoch": self.epoch.value,
|
|
@@ -1320,6 +1356,9 @@ class RunManager(Tray):
|
|
|
1320
1356
|
self._resolve_stop_waiters()
|
|
1321
1357
|
self._publish_status()
|
|
1322
1358
|
self._settle_applied(fx)
|
|
1359
|
+
# a rewind that asked this run to stop reruns; one landing in the drain parks
|
|
1360
|
+
if staged_before is not None and self._staged_rewind is staged_before:
|
|
1361
|
+
self._schedule(self._advance)
|
|
1323
1362
|
if not self._in_flight():
|
|
1324
1363
|
self._idle.set()
|
|
1325
1364
|
|
|
@@ -1463,10 +1502,8 @@ class RunManager(Tray):
|
|
|
1463
1502
|
self.steerQueue.untake(self._pending_takes)
|
|
1464
1503
|
self._pending_takes = 0
|
|
1465
1504
|
return
|
|
1466
|
-
for lane, item in taken: # claimed
|
|
1467
|
-
|
|
1468
|
-
if queue.value and queue.peek()["id"] == item["id"]:
|
|
1469
|
-
queue.popleft()
|
|
1505
|
+
for lane, item in taken: # claimed items the dispatch never consumed
|
|
1506
|
+
self._drop_claimed(lane, item["id"])
|
|
1470
1507
|
for lane, item in reversed(taken):
|
|
1471
1508
|
self._lane(lane).insert(0, {k: v for k, v in item.items() if k != "~parent"})
|
|
1472
1509
|
|
|
@@ -1719,7 +1756,10 @@ class RunManager(Tray):
|
|
|
1719
1756
|
e.message_id
|
|
1720
1757
|
):
|
|
1721
1758
|
return self._park_dispatched_edit(e)
|
|
1722
|
-
|
|
1759
|
+
staged = self._staged_rewind
|
|
1760
|
+
if e.source_meta is not None or e.message_id in self._delivered_ids or (
|
|
1761
|
+
staged is not None and any(m["id"] == e.message_id for m in staged.messages)
|
|
1762
|
+
):
|
|
1723
1763
|
raise _reject("duplicate-id", f"message id {e.message_id} is already used")
|
|
1724
1764
|
if e.anchor is _ABSENT:
|
|
1725
1765
|
if e.minted:
|
|
@@ -1807,6 +1847,9 @@ class RunManager(Tray):
|
|
|
1807
1847
|
_check_rewind_gate(self.capabilities, self._in_flight(), "editing")
|
|
1808
1848
|
if e.source_meta is None:
|
|
1809
1849
|
raise _reject("unknown-id", f"message {e.message_id} is unknown")
|
|
1850
|
+
staged = self._staged_rewind
|
|
1851
|
+
if staged is not None and any(m["id"] == e.message_id for m in staged.messages):
|
|
1852
|
+
raise _reject("duplicate-id", f"message id {e.message_id} is already used")
|
|
1810
1853
|
self._check_anchor(e)
|
|
1811
1854
|
self._stage_rewind(
|
|
1812
1855
|
_Rewind(
|
|
@@ -1865,12 +1908,15 @@ class RunManager(Tray):
|
|
|
1865
1908
|
def _apply_edit(self, e: _Edit) -> Any:
|
|
1866
1909
|
# Run control is open to every attached caller; attach authorization is the
|
|
1867
1910
|
# gate. A finer security-gate system is planned.
|
|
1911
|
+
_check_rewind_gate(self.capabilities, self._in_flight(), "run/edit")
|
|
1868
1912
|
self._check_id_capacity((e.message["id"],))
|
|
1869
1913
|
staged = self._staged_rewind
|
|
1870
1914
|
if (
|
|
1871
|
-
staged is not None
|
|
1872
|
-
|
|
1873
|
-
|
|
1915
|
+
(staged is not None and any(m["id"] == e.message["id"] for m in staged.messages))
|
|
1916
|
+
or self._lane_of(e.message["id"]) is not None
|
|
1917
|
+
or self._is_dispatching(e.message["id"])
|
|
1918
|
+
or e.message["id"] in self._delivered_ids
|
|
1919
|
+
):
|
|
1874
1920
|
raise _reject(
|
|
1875
1921
|
"duplicate-id", f"message id {e.message['id']} is already used"
|
|
1876
1922
|
)
|
|
@@ -1888,6 +1934,7 @@ class RunManager(Tray):
|
|
|
1888
1934
|
def _apply_reload(self, e: _Reload) -> Any:
|
|
1889
1935
|
# Run control is open to every attached caller; attach authorization is the
|
|
1890
1936
|
# gate. A finer security-gate system is planned.
|
|
1937
|
+
_check_rewind_gate(self.capabilities, self._in_flight(), "run/reload")
|
|
1891
1938
|
if self._staged_rewind is not None:
|
|
1892
1939
|
raise _reject("wrong-state", "a rewind is already staged")
|
|
1893
1940
|
self._stage_rewind(
|
|
@@ -2255,6 +2302,9 @@ class RunManagerNamespace(TrayMapNamespace):
|
|
|
2255
2302
|
self._loading: "asyncio.Task[None] | None" = None
|
|
2256
2303
|
self._loaded = False
|
|
2257
2304
|
self._mounted: list[RunManager] = []
|
|
2305
|
+
# every id a completed run delivered: a resend's duplicate check reads it,
|
|
2306
|
+
# never a thread read that may predate the write
|
|
2307
|
+
self._delivered_ids: set[str] = set()
|
|
2258
2308
|
self._status_changed = getattr(api, "run_status_changed", None)
|
|
2259
2309
|
api.state["runs"] = []
|
|
2260
2310
|
api.state["status"] = "ready"
|
|
@@ -2367,7 +2417,12 @@ class RunManagerNamespace(TrayMapNamespace):
|
|
|
2367
2417
|
tray._publish_status()
|
|
2368
2418
|
return changed
|
|
2369
2419
|
|
|
2370
|
-
async def _machine(
|
|
2420
|
+
async def _machine(
|
|
2421
|
+
self,
|
|
2422
|
+
run_id: str,
|
|
2423
|
+
principal: Any,
|
|
2424
|
+
before_mint: Callable[[], None] | None = None,
|
|
2425
|
+
) -> tuple[RunManager, bool]:
|
|
2371
2426
|
await self._load_existing()
|
|
2372
2427
|
# No await between the live() check and the mint's publication, and no
|
|
2373
2428
|
# lock held across storage I/O: same-tick callers await the shared mint
|
|
@@ -2378,6 +2433,8 @@ class RunManagerNamespace(TrayMapNamespace):
|
|
|
2378
2433
|
pending = self._mint
|
|
2379
2434
|
minted = pending is None
|
|
2380
2435
|
if pending is None:
|
|
2436
|
+
if before_mint is not None:
|
|
2437
|
+
before_mint()
|
|
2381
2438
|
pending = self._api.create_task(self.get_or_create(run_id))
|
|
2382
2439
|
self._mint = pending
|
|
2383
2440
|
pending.add_done_callback(self._mint_settled)
|
|
@@ -2480,7 +2537,18 @@ class RunManagerNamespace(TrayMapNamespace):
|
|
|
2480
2537
|
message: dict[str, Any] | None = _validated_message(cls, params["message"])
|
|
2481
2538
|
message_id = message["id"]
|
|
2482
2539
|
source_meta = await self._api.get_message_meta(message_id)
|
|
2483
|
-
tray, minted = await self._machine(
|
|
2540
|
+
tray, minted = await self._machine(
|
|
2541
|
+
run_id,
|
|
2542
|
+
auth_result,
|
|
2543
|
+
lambda: _check_fresh_send(
|
|
2544
|
+
message_id,
|
|
2545
|
+
source_meta,
|
|
2546
|
+
anchor,
|
|
2547
|
+
anchor_meta,
|
|
2548
|
+
thread_empty,
|
|
2549
|
+
message_id in self._delivered_ids,
|
|
2550
|
+
),
|
|
2551
|
+
)
|
|
2484
2552
|
else:
|
|
2485
2553
|
message = source_meta = None
|
|
2486
2554
|
message_id = params["messageId"]
|
|
@@ -2780,6 +2848,53 @@ class RunManagerNamespace(TrayMapNamespace):
|
|
|
2780
2848
|
)
|
|
2781
2849
|
|
|
2782
2850
|
|
|
2851
|
+
def _run_commands(name: str) -> dict[str, Callable[..., Any]]:
|
|
2852
|
+
"""The ``run/*`` handlers forwarding to the machine at ``self.<name>``."""
|
|
2853
|
+
|
|
2854
|
+
async def send(self: Any, params: Any, *, ctx: Any, auth_result: Any) -> Any:
|
|
2855
|
+
return await getattr(self, name).send(
|
|
2856
|
+
params, applied=ctx.applied, auth_result=auth_result, version=ctx.version
|
|
2857
|
+
)
|
|
2858
|
+
|
|
2859
|
+
async def dequeue(self: Any, params: Any, *, auth_result: Any) -> Any:
|
|
2860
|
+
return await getattr(self, name).dequeue(params, auth_result=auth_result)
|
|
2861
|
+
|
|
2862
|
+
async def edit(self: Any, params: Any, *, ctx: Any, auth_result: Any) -> Any:
|
|
2863
|
+
return await getattr(self, name).edit(
|
|
2864
|
+
params, applied=ctx.applied, auth_result=auth_result
|
|
2865
|
+
)
|
|
2866
|
+
|
|
2867
|
+
async def reload(self: Any, params: Any, *, ctx: Any, auth_result: Any) -> Any:
|
|
2868
|
+
return await getattr(self, name).reload(
|
|
2869
|
+
params, applied=ctx.applied, auth_result=auth_result
|
|
2870
|
+
)
|
|
2871
|
+
|
|
2872
|
+
async def stop(self: Any, params: Any = None, *, ctx: Any, auth_result: Any) -> Any:
|
|
2873
|
+
return await getattr(self, name).stop(
|
|
2874
|
+
params, applied=ctx.applied, auth_result=auth_result
|
|
2875
|
+
)
|
|
2876
|
+
|
|
2877
|
+
async def continue_run(
|
|
2878
|
+
self: Any, params: Any = None, *, ctx: Any, auth_result: Any
|
|
2879
|
+
) -> Any:
|
|
2880
|
+
return await getattr(self, name).continue_run(
|
|
2881
|
+
applied=ctx.applied, auth_result=auth_result
|
|
2882
|
+
)
|
|
2883
|
+
|
|
2884
|
+
async def input(self: Any, params: Any, *, auth_result: Any) -> Any:
|
|
2885
|
+
return await getattr(self, name).input(params, auth_result=auth_result)
|
|
2886
|
+
|
|
2887
|
+
return {
|
|
2888
|
+
"run/send": send,
|
|
2889
|
+
"run/dequeue": dequeue,
|
|
2890
|
+
"run/edit": edit,
|
|
2891
|
+
"run/reload": reload,
|
|
2892
|
+
"run/stop": stop,
|
|
2893
|
+
"run/continue": continue_run,
|
|
2894
|
+
"run/input": input,
|
|
2895
|
+
}
|
|
2896
|
+
|
|
2897
|
+
|
|
2783
2898
|
class RunManagerDescriptor(TrayDescriptor):
|
|
2784
2899
|
namespace_cls = RunManagerNamespace
|
|
2785
2900
|
|
|
@@ -2789,6 +2904,7 @@ class RunManagerDescriptor(TrayDescriptor):
|
|
|
2789
2904
|
async def mount(api: Any, id: str, tray: RunManager):
|
|
2790
2905
|
ns: RunManagerNamespace = getattr(api, self.name)
|
|
2791
2906
|
tray._reroute = ns._restage
|
|
2907
|
+
tray._delivered_ids = ns._delivered_ids
|
|
2792
2908
|
ns._mount(tray)
|
|
2793
2909
|
unsubscribe = tray.status.subscribe(lambda _op: ns._mirror_status())
|
|
2794
2910
|
yield
|
|
@@ -2797,19 +2913,37 @@ class RunManagerDescriptor(TrayDescriptor):
|
|
|
2797
2913
|
|
|
2798
2914
|
self._on_activate.append(mount)
|
|
2799
2915
|
|
|
2916
|
+
def __set_name__(self, owner: type, name: str) -> None:
|
|
2917
|
+
"""Registers the ``run/*`` commands on ``owner``; a ``@command`` for the same method anywhere in its MRO wins."""
|
|
2918
|
+
super().__set_name__(owner, name)
|
|
2919
|
+
explicit = {
|
|
2920
|
+
getattr(fn, "_statewire_command_method", None)
|
|
2921
|
+
for base in owner.__mro__
|
|
2922
|
+
for fn in vars(base).values()
|
|
2923
|
+
if not getattr(fn, "_harness_run_command", False)
|
|
2924
|
+
}
|
|
2925
|
+
for method, fn in _run_commands(name).items():
|
|
2926
|
+
if method not in explicit:
|
|
2927
|
+
fn._harness_run_command = True # type: ignore[attr-defined]
|
|
2928
|
+
setattr(owner, f"_{name}_cmd_{method[4:]}", command(method)(fn))
|
|
2929
|
+
|
|
2800
2930
|
|
|
2801
2931
|
def run_manager(
|
|
2802
2932
|
*,
|
|
2803
2933
|
capabilities: Iterable[str] = (),
|
|
2804
|
-
max_queued: int =
|
|
2934
|
+
max_queued: int = MAX_QUEUED,
|
|
2805
2935
|
max_redelivery_age: float | None = None,
|
|
2806
2936
|
prepare_message: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
|
|
2807
2937
|
prepare_input: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
|
|
2808
2938
|
prioritize: "Callable[[RunManager.PrioritizeRequest], Awaitable[str] | str] | None" = None,
|
|
2809
2939
|
) -> Callable[[Callable[..., Coroutine[Any, Any, Any]]], RunManagerDescriptor]:
|
|
2810
2940
|
"""Declare the runs subsystem on a Statewire host: the decorated method is
|
|
2811
|
-
the run executor, ``self.<name>`` is the machine's command surface,
|
|
2812
|
-
each run lives in its own tray
|
|
2941
|
+
the run executor, ``self.<name>`` is the machine's command surface, the
|
|
2942
|
+
host serves the ``run/*`` commands, and each run lives in its own tray
|
|
2943
|
+
keyed by its runId. ``prepare_message`` refuses with
|
|
2944
|
+
``StatewireReject(message, payload={"reason": reason})`` and the caller
|
|
2945
|
+
sees that reason and message; an unexpected exception reaches it as "the
|
|
2946
|
+
command failed" and is logged on the host."""
|
|
2813
2947
|
caps = frozenset(capabilities)
|
|
2814
2948
|
unknown = caps - _CAPABILITIES
|
|
2815
2949
|
if unknown:
|
harness_sdk/voice.py
CHANGED
|
@@ -60,18 +60,25 @@ from pinboard.trays import Tray, TrayDescriptor, TrayMapNamespace
|
|
|
60
60
|
from statepatch import observable, plain
|
|
61
61
|
from statewire import StatewireReject
|
|
62
62
|
|
|
63
|
+
from .limits import (
|
|
64
|
+
MAX_BUFFERED_TURNS,
|
|
65
|
+
MAX_HOST_VOICE_STARTS,
|
|
66
|
+
MAX_PENDING_TASKS,
|
|
67
|
+
MAX_VOICE_ID_LENGTH,
|
|
68
|
+
MAX_VOICE_STARTS,
|
|
69
|
+
MAX_VOICE_TEXT_BYTES,
|
|
70
|
+
VOICE_DEPARTURE_GRACE,
|
|
71
|
+
VOICE_FINAL_FLUSH_ATTEMPTS,
|
|
72
|
+
VOICE_FINAL_FLUSH_RETRY,
|
|
73
|
+
VOICE_SEED_LIMIT,
|
|
74
|
+
VOICE_START_WINDOW,
|
|
75
|
+
)
|
|
76
|
+
|
|
63
77
|
logger = logging.getLogger(__name__)
|
|
64
78
|
|
|
65
|
-
_SEED_LIMIT = 128
|
|
66
79
|
_SEED_ROLES = ("user", "assistant", "system")
|
|
67
80
|
CLEAN_CLOSE_REASONS = ("close_requested", "remote_hangup")
|
|
68
81
|
NO_ANSWER = "That background work stopped before producing an answer."
|
|
69
|
-
MAX_BUFFERED_TURNS = 512
|
|
70
|
-
MAX_PENDING_TASKS = 64
|
|
71
|
-
MAX_VOICE_TEXT_BYTES = 1 << 20
|
|
72
|
-
MAX_VOICE_ID_LENGTH = 256
|
|
73
|
-
MAX_VOICE_STARTS = 5
|
|
74
|
-
VOICE_START_WINDOW = 60.0
|
|
75
82
|
|
|
76
83
|
|
|
77
84
|
def _event_id(value: Any, name: str) -> None:
|
|
@@ -102,15 +109,15 @@ def _capped_seed(seed: Any) -> "list[VoiceManager.SeedMessage]":
|
|
|
102
109
|
or not isinstance(message.get("text"), str)
|
|
103
110
|
):
|
|
104
111
|
raise TypeError(f"seed messages must be {{role, text}}, got {message!r}")
|
|
105
|
-
return seed[-
|
|
112
|
+
return seed[-VOICE_SEED_LIMIT:]
|
|
106
113
|
|
|
107
114
|
|
|
108
115
|
class VoiceManager(Tray):
|
|
109
116
|
"""One live voice session: the provider handle and the in-memory turn buffer; ended sessions flush and self-delete."""
|
|
110
117
|
|
|
111
|
-
departure_grace =
|
|
112
|
-
final_flush_attempts =
|
|
113
|
-
final_flush_retry =
|
|
118
|
+
departure_grace = VOICE_DEPARTURE_GRACE
|
|
119
|
+
final_flush_attempts = VOICE_FINAL_FLUSH_ATTEMPTS
|
|
120
|
+
final_flush_retry = VOICE_FINAL_FLUSH_RETRY
|
|
114
121
|
|
|
115
122
|
clientId = observable(None)
|
|
116
123
|
status = observable("connecting")
|
|
@@ -470,7 +477,8 @@ class VoiceManagerNamespace(TrayMapNamespace):
|
|
|
470
477
|
)
|
|
471
478
|
self._session: VoiceManager | None = None
|
|
472
479
|
self._starting = False
|
|
473
|
-
self._starts: deque[float] =
|
|
480
|
+
self._starts: dict[str, deque[float]] = {}
|
|
481
|
+
self._host_starts: deque[float] = deque()
|
|
474
482
|
api.state["voice"] = None
|
|
475
483
|
|
|
476
484
|
def live(self) -> VoiceManager | None:
|
|
@@ -513,12 +521,7 @@ class VoiceManagerNamespace(TrayMapNamespace):
|
|
|
513
521
|
and self._api.has_subscriber(session.clientId.value)
|
|
514
522
|
):
|
|
515
523
|
raise _reject("voice-active", "a voice session is already live")
|
|
516
|
-
|
|
517
|
-
while self._starts and self._starts[0] <= now - VOICE_START_WINDOW:
|
|
518
|
-
self._starts.popleft()
|
|
519
|
-
if len(self._starts) >= MAX_VOICE_STARTS:
|
|
520
|
-
raise _reject("voice-rate-limited", "voice start limit reached (5 attempts per 60 seconds)")
|
|
521
|
-
self._starts.append(now)
|
|
524
|
+
self._admit_start(ctx.caller.client_id)
|
|
522
525
|
self._starting = True
|
|
523
526
|
try:
|
|
524
527
|
if session is not None:
|
|
@@ -533,6 +536,28 @@ class VoiceManagerNamespace(TrayMapNamespace):
|
|
|
533
536
|
finally:
|
|
534
537
|
self._starting = False
|
|
535
538
|
|
|
539
|
+
def _admit_start(self, client_id: str) -> None:
|
|
540
|
+
# Every attempt counts, failures and supersedes included; the budget is in memory.
|
|
541
|
+
now = monotonic()
|
|
542
|
+
for starts in (self._host_starts, *self._starts.values()):
|
|
543
|
+
while starts and starts[0] <= now - VOICE_START_WINDOW:
|
|
544
|
+
starts.popleft()
|
|
545
|
+
self._starts = {key: starts for key, starts in self._starts.items() if starts}
|
|
546
|
+
mine = self._starts.get(client_id, deque())
|
|
547
|
+
if len(mine) >= MAX_VOICE_STARTS:
|
|
548
|
+
raise _reject(
|
|
549
|
+
"voice-rate-limited",
|
|
550
|
+
f"voice start limit reached ({MAX_VOICE_STARTS} attempts per {VOICE_START_WINDOW:g} seconds)",
|
|
551
|
+
)
|
|
552
|
+
if len(self._host_starts) >= MAX_HOST_VOICE_STARTS:
|
|
553
|
+
raise _reject(
|
|
554
|
+
"voice-rate-limited",
|
|
555
|
+
f"voice start limit reached for this host ({MAX_HOST_VOICE_STARTS} attempts per {VOICE_START_WINDOW:g} seconds)",
|
|
556
|
+
)
|
|
557
|
+
mine.append(now)
|
|
558
|
+
self._starts[client_id] = mine
|
|
559
|
+
self._host_starts.append(now)
|
|
560
|
+
|
|
536
561
|
def _owned_session(self, ctx: Any, command: str) -> VoiceManager:
|
|
537
562
|
session = self.live()
|
|
538
563
|
if session is None:
|
harness_sdk/voice_thread.py
CHANGED
|
@@ -13,18 +13,13 @@ from typing import Any
|
|
|
13
13
|
from statepatch import plain
|
|
14
14
|
from statewire import StatewireReject
|
|
15
15
|
|
|
16
|
-
from .messages import MAIN_NS, MessageTree
|
|
16
|
+
from .messages import MAIN_NS, MessageTree, message_text
|
|
17
17
|
|
|
18
18
|
VOICE_SOURCE = "voice"
|
|
19
19
|
DELEGATION_SOURCE = "voice_delegation"
|
|
20
20
|
DELEGATE_TOOL = "delegate"
|
|
21
21
|
|
|
22
22
|
|
|
23
|
-
def message_text(message: Any) -> str:
|
|
24
|
-
"""The text parts of a message joined by blank lines."""
|
|
25
|
-
return "\n\n".join(p["text"] for p in plain(message["parts"]) if p.get("type") == "text").strip()
|
|
26
|
-
|
|
27
|
-
|
|
28
23
|
def voice_seed(tree: MessageTree) -> list[dict[str, Any]]:
|
|
29
24
|
"""The main head chain as ``{role, text}`` seed messages; messages without text are skipped."""
|
|
30
25
|
thread = tree.threads.get(MAIN_NS)
|
|
@@ -33,7 +28,7 @@ def voice_seed(tree: MessageTree) -> list[dict[str, Any]]:
|
|
|
33
28
|
seed = []
|
|
34
29
|
for message_id in thread.chain(thread.head):
|
|
35
30
|
message = thread.messages[message_id]
|
|
36
|
-
text = message_text(message)
|
|
31
|
+
text = message_text(message).strip()
|
|
37
32
|
if text:
|
|
38
33
|
seed.append({"role": message["role"], "text": text})
|
|
39
34
|
return seed
|
|
@@ -111,7 +106,7 @@ def trailing_assistant_text(tree: MessageTree, ns: str, after_id: str) -> str:
|
|
|
111
106
|
message = thread.messages[message_id]
|
|
112
107
|
source = (plain(message.get("metadata")) or {}).get("source")
|
|
113
108
|
if message["role"] == "assistant" and source != VOICE_SOURCE:
|
|
114
|
-
texts.append(message_text(message))
|
|
109
|
+
texts.append(message_text(message).strip())
|
|
115
110
|
return "\n\n".join(t for t in texts if t)
|
|
116
111
|
|
|
117
112
|
|
harness_sdk/wire.py
CHANGED
|
@@ -12,13 +12,13 @@ from statepatch import plain
|
|
|
12
12
|
from statewire import StatewireAttach
|
|
13
13
|
|
|
14
14
|
from .interest import (
|
|
15
|
-
MAX_INTERESTS,
|
|
16
15
|
InterestError,
|
|
17
16
|
check_request,
|
|
18
17
|
covered,
|
|
19
18
|
head_request,
|
|
20
19
|
resolve,
|
|
21
20
|
)
|
|
21
|
+
from .limits import MAX_INTERESTS
|
|
22
22
|
from .messages import MAIN_NS, MessageTree
|
|
23
23
|
|
|
24
24
|
INTEREST = "harness-sdk/interest"
|
|
@@ -131,11 +131,13 @@ class HarnessMessages:
|
|
|
131
131
|
return {}
|
|
132
132
|
|
|
133
133
|
def attaching(self, attach: StatewireAttach) -> None:
|
|
134
|
+
super().attaching(attach)
|
|
134
135
|
interests = self._interests[attach.id] = _Interests(attach)
|
|
135
136
|
interests.requests = self._context_interests(attach.context("harness-sdk"))
|
|
136
137
|
self.refresh_messages()
|
|
137
138
|
|
|
138
139
|
def detached(self, attach: StatewireAttach) -> None:
|
|
140
|
+
super().detached(attach)
|
|
139
141
|
if self._interests.pop(attach.id, None) is not None:
|
|
140
142
|
self.refresh_messages()
|
|
141
143
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: harness-sdk-python
|
|
3
|
-
Version: 0.
|
|
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.
|
|
9
|
-
Requires-Dist: statewire<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
|
-
|
|
43
|
+
import asyncio
|
|
43
44
|
|
|
44
|
-
from harness_sdk import
|
|
45
|
+
from harness_sdk import harness_app, message_text
|
|
45
46
|
|
|
46
47
|
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
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.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
harness_sdk/__init__.py,sha256=KejXEVHqfmyCd0CAJ-8-Mwzbb4pl5CgVSbMOVHsTmiI,2457
|
|
2
|
+
harness_sdk/checkpoints.py,sha256=eM2UBpefEfRYmYn7l4CRQmCPFUHzNgDxCFJvGMEsgVc,30778
|
|
3
|
+
harness_sdk/deepagents.py,sha256=B_XR0CWgIIy111YsUh2cuC4OktDY3xmJYhLJElRiv_o,27503
|
|
4
|
+
harness_sdk/deepagents_host.py,sha256=G0jERK2wzsIcstQp2ReUps6JxgjDulphyFLnWYzPpy4,8814
|
|
5
|
+
harness_sdk/drafts.py,sha256=gcOLR5xaRCmwKehLqhxrayiFJijXHQUCHVCqPpb2Vto,3258
|
|
6
|
+
harness_sdk/fenced_postgres.py,sha256=0IO81hErXY4TwhF4slZp4e0Le-e6ekKHjvxV3F21KCs,13268
|
|
7
|
+
harness_sdk/host.py,sha256=w-XjYOq_x4sNCAqUrMfJCYgNBdkLN3Gz1pJGiZc91ZQ,5361
|
|
8
|
+
harness_sdk/interest.py,sha256=c3XvxbaYanlgIoUBvbQadonURG21vfus_35bynNx_GE,5471
|
|
9
|
+
harness_sdk/langgraph.py,sha256=35r1KSgrqK8KUPe6ELAGq3q5TuyeTeXwmkOnlbC5F9c,2682
|
|
10
|
+
harness_sdk/limits.py,sha256=3uD3jY3rUhBqiLcIOC7tHFT36xHYBhL9nOD6AmxbRLQ,1565
|
|
11
|
+
harness_sdk/linear_thread.py,sha256=laDRXKLFsMlyWS4snqNAM6t38wO26gevLWXRNivhHSM,1810
|
|
12
|
+
harness_sdk/messages.py,sha256=SlYGlasbHwRn85zcvg6iZy8Ln79vaGoab-7QAXqwfHM,7562
|
|
13
|
+
harness_sdk/parts.py,sha256=mHhYvmQx6J56Ah5K7dUZ4qUOlKk-L02AR64asSqOT5I,6400
|
|
14
|
+
harness_sdk/prioritize.py,sha256=adTsY7JeEfJQCwrBOpm26y0EdBCJ2gViUxZQYsL9Na0,4108
|
|
15
|
+
harness_sdk/protocol.py,sha256=VxWOIg_2vitFGTJmpiD2wNNAJnwSgQFy69Hds-frfvs,1207
|
|
16
|
+
harness_sdk/run_manager.py,sha256=gbbwo2g81nJ62dlDdVDFfHIoMIOxE0cK1MD4sElWZcI,120705
|
|
17
|
+
harness_sdk/threads.py,sha256=qny-srZYvIFcAKSOLlfboSQsIgWTLqG_saUqxHTfpEQ,8027
|
|
18
|
+
harness_sdk/voice.py,sha256=P3uOXtlSFFYUUVrm9lYlDnM6IfUDFOvts2TuLw2OeRE,26914
|
|
19
|
+
harness_sdk/voice_thread.py,sha256=vBD8uDIl6zTzmJTE_y3oxHnvpBQYp56RzbisUbUzm-w,6736
|
|
20
|
+
harness_sdk/wire.py,sha256=cSDfXhh85G2qflLHYxXkLQ86del1GLiwB2CHDEQv2wQ,8869
|
|
21
|
+
harness_sdk/providers/__init__.py,sha256=PjVKflqdtYSipq0ISTNuIYKeCOm3KX8ov9XuNtBhFrs,75
|
|
22
|
+
harness_sdk/providers/gpt_live.py,sha256=cuODSm3Kztemf51BIOuPwy1Wf-0pOhf1LPYzmSdCvl8,8453
|
|
23
|
+
harness_sdk_python-0.41.1.dist-info/METADATA,sha256=q_3zUDdh72jQaK8GdLcJYm-GKzw-4up6IHVf3vJbwS0,3850
|
|
24
|
+
harness_sdk_python-0.41.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
25
|
+
harness_sdk_python-0.41.1.dist-info/RECORD,,
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
harness_sdk/__init__.py,sha256=x-vDKSqkPGcjLZ3N2nWtM37RyS-KifXtfKBPy4IOnjE,2285
|
|
2
|
-
harness_sdk/checkpoints.py,sha256=Iuum5x4KjsvJajDPP9TLFKcKQouOo-05jnCP3SJCD2s,30726
|
|
3
|
-
harness_sdk/deepagents.py,sha256=B_XR0CWgIIy111YsUh2cuC4OktDY3xmJYhLJElRiv_o,27503
|
|
4
|
-
harness_sdk/deepagents_host.py,sha256=Psv66_Y0eJQu4sjBdGiwqrEdusY6kHXOotb1v35NNT8,9668
|
|
5
|
-
harness_sdk/fenced_postgres.py,sha256=hbbrMR1WaqrHTNgd4wFrXfRrzQFGnyim-c8nZXgwWp4,13235
|
|
6
|
-
harness_sdk/interest.py,sha256=9d6_L-3OaCv8aPtu6mmHTAaNFBo_7lI6k219kGKyoVA,5481
|
|
7
|
-
harness_sdk/langgraph.py,sha256=35r1KSgrqK8KUPe6ELAGq3q5TuyeTeXwmkOnlbC5F9c,2682
|
|
8
|
-
harness_sdk/linear_thread.py,sha256=laDRXKLFsMlyWS4snqNAM6t38wO26gevLWXRNivhHSM,1810
|
|
9
|
-
harness_sdk/messages.py,sha256=YdAgGghXdgNw0LWSuu54pqxF42hCscpOF5UtOP3S2ks,7368
|
|
10
|
-
harness_sdk/parts.py,sha256=mHhYvmQx6J56Ah5K7dUZ4qUOlKk-L02AR64asSqOT5I,6400
|
|
11
|
-
harness_sdk/prioritize.py,sha256=Li8IoI_ACiwbWDNa2DSDpNhoXY0utPhGevBQqQonsQc,4203
|
|
12
|
-
harness_sdk/protocol.py,sha256=VxWOIg_2vitFGTJmpiD2wNNAJnwSgQFy69Hds-frfvs,1207
|
|
13
|
-
harness_sdk/run_manager.py,sha256=krBEqBhHriqhHXgoQpzFSLJ2Zs7PQygOKQw3GYPKdvg,114956
|
|
14
|
-
harness_sdk/threads.py,sha256=qny-srZYvIFcAKSOLlfboSQsIgWTLqG_saUqxHTfpEQ,8027
|
|
15
|
-
harness_sdk/voice.py,sha256=XJakSJrjS-RVT1PIaDDxm1RZDp9QpLWCdX36k-UvGHA,25852
|
|
16
|
-
harness_sdk/voice_thread.py,sha256=B616W1efohEd9RwWssrOkTne7Lu8s0kn07kMof1v_nI,6910
|
|
17
|
-
harness_sdk/wire.py,sha256=Ln7uBcH2SS08U61ueLYX1M8il_4HMX27GmfRe7ZsnhI,8787
|
|
18
|
-
harness_sdk/providers/__init__.py,sha256=PjVKflqdtYSipq0ISTNuIYKeCOm3KX8ov9XuNtBhFrs,75
|
|
19
|
-
harness_sdk/providers/gpt_live.py,sha256=cuODSm3Kztemf51BIOuPwy1Wf-0pOhf1LPYzmSdCvl8,8453
|
|
20
|
-
harness_sdk_python-0.40.13.dist-info/METADATA,sha256=H1mFaSlg2pBUtPL_yXfGsqidCiXEB2rHLljZ7KlK8pU,4023
|
|
21
|
-
harness_sdk_python-0.40.13.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
22
|
-
harness_sdk_python-0.40.13.dist-info/RECORD,,
|
|
File without changes
|