diff --git a/docs/spec/sidecar.md b/docs/spec/sidecar.md index 87f1e003..e62b90f2 100644 --- a/docs/spec/sidecar.md +++ b/docs/spec/sidecar.md @@ -350,11 +350,16 @@ mark the turn's total as partial rather than presenting a smaller number as complete. A turn that delegated nothing emits the historical payload unchanged. -`stream.done.treeUsage` reports the whole turn tree against the request's -`budgetTokens`: `{limit, spent, byAgent}` where `byAgent` is keyed by the -caller's agent labels (`"parent"`, `"0.1"`). It is absent when the request -carried no `budgetTokens` — "no limit" stays distinguishable from "spent -nothing". +`stream.done.treeUsage` reports what the whole turn tree spent: +`{spent, byAgent}` where `byAgent` is keyed by the caller's agent labels +(`"parent"`, `"0.1"`). It is always present on a turn, because the number is +for display: there is no limit in it and none is enforced. A turn that runs +long had more work, not a failure, and stopping it partway through would +throw away what the user already paid for. + +`budgetTokens` still bounds the parent run's own loop (see the loop limits +above), which is a per-run wall rather than a tree-wide gate. The two are +separate: the tree counter never compares its total against anything. Sub-agent delegation is ON BY DEFAULT: the sidecar advertises `delegate_subagent` and answers it with a bounded child CoreLoop running diff --git a/package.json b/package.json index 23b8a57e..23f09202 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/monorepo", - "version": "0.12.0", + "version": "0.12.1", "private": true, "type": "module", "packageManager": "pnpm@10.23.0", diff --git a/packages/agent-cli/ts/package.json b/packages/agent-cli/ts/package.json index c3ea5d15..238576dd 100644 --- a/packages/agent-cli/ts/package.json +++ b/packages/agent-cli/ts/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/agent-cli", - "version": "0.12.0", + "version": "0.12.1", "description": "Product-neutral command line for a Steerable host. Products supply the bin name and brand.", "license": "Apache-2.0", "homepage": "https://steerableframework.com/", diff --git a/packages/agent-client/ts/package.json b/packages/agent-client/ts/package.json index 3dcc7de4..7deee02a 100644 --- a/packages/agent-client/ts/package.json +++ b/packages/agent-client/ts/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/agent-client", - "version": "0.12.0", + "version": "0.12.1", "description": "In-process client for a Steerable host: HTTP-shaped requests, turn streams, and approval replies.", "license": "Apache-2.0", "homepage": "https://steerableframework.com/", diff --git a/packages/agent-harness/py/pyproject.toml b/packages/agent-harness/py/pyproject.toml index dea0756d..e4236c94 100644 --- a/packages/agent-harness/py/pyproject.toml +++ b/packages/agent-harness/py/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "steerable-agent-harness" -version = "0.12.0" +version = "0.12.1" description = "Steerable harness helpers for Python" license = { text = "Apache-2.0" } readme = "README.md" diff --git a/packages/agent-harness/ts/package.json b/packages/agent-harness/ts/package.json index 92c28703..229df0b6 100644 --- a/packages/agent-harness/ts/package.json +++ b/packages/agent-harness/ts/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/agent-harness", - "version": "0.12.0", + "version": "0.12.1", "description": "Steerable framework Tier 2 \u2014 TypeScript facade over the Python harness (policy, budget, retry, completion, tracing) used for cross-language conformance tests. Production code should depend on the Python harness.", "license": "Apache-2.0", "homepage": "https://steerableframework.com/", diff --git a/packages/agent-protocol/py/pyproject.toml b/packages/agent-protocol/py/pyproject.toml index 591e9b7d..f9f77ac5 100644 --- a/packages/agent-protocol/py/pyproject.toml +++ b/packages/agent-protocol/py/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "steerable-agent-protocol" -version = "0.12.0" +version = "0.12.1" description = "Steerable protocol schemas for Python" license = { text = "Apache-2.0" } readme = "README.md" diff --git a/packages/agent-protocol/ts/package.json b/packages/agent-protocol/ts/package.json index 774c0fac..facada1f 100644 --- a/packages/agent-protocol/ts/package.json +++ b/packages/agent-protocol/ts/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/agent-protocol", - "version": "0.12.0", + "version": "0.12.1", "description": "Steerable framework Tier 1 \u2014 wire-format types (SSEEvent, ChatMessage, ToolCall, ToolResult, AgentSession, HarnessTrace, sidecar JSON-RPC) shared by every Steerable client and server.", "license": "Apache-2.0", "homepage": "https://steerableframework.com/", diff --git a/packages/agent-runtime/py/README.md b/packages/agent-runtime/py/README.md index 13f6e77c..a6ecf924 100644 --- a/packages/agent-runtime/py/README.md +++ b/packages/agent-runtime/py/README.md @@ -37,14 +37,18 @@ release. Nothing in the single-agent path changed. `CREATE TABLE IF NOT EXISTS`, so an existing database upgrades in place on first open — no migration function, no data rewrite. A database written by a newer build still refuses to open. -- **`budgetTokens` now bounds the whole turn tree.** It used to limit each - loop separately; a parent plus three children could each spend the full - allowance. Every agent in the tree now debits one counter, and the first to - cross it fails there. A host that relied on per-child allowances gets a - tighter (correct) limit. -- **New `TreeBudget` / `SessionBudgetExceeded`** in `steerable_agent_runtime`. - `AgentPool(budget=...)` shares one counter across the pool; the parent loop's - usage is charged to the same counter by the host. +- **`budgetTokens` no longer bounds the turn tree.** It still caps the parent + run's own loop (unchanged from before the tree layer), but there is no longer + a shared tree limit: `TreeBudget` and `SessionBudgetExceeded` are gone, + replaced by `TreeSpend`, which only records. + - Why removed: a tree limit stopped a task partway through, leaving children + at `budget_exhausted` and needing a human to click resume. A turn that runs + long had more work, not a failure. Cost control belongs before a turn + starts (or on a period budget), not inside one already half done. + - What replaced it: `TreeSpend` — `record(usage, agent=...)` plus + `report() -> {spent, by_agent}` — so a host can still show what a turn cost + and which agent spent it. `AgentPool(spend=...)` shares one counter across + the pool; the parent's usage is recorded into the same counter by the host. - **`provider_factory` for sub-agent profiles now takes `(model, effort)`** instead of `(model)`. `None` for either knob means "inherit the parent's", never "clear it". A profile pinning neither does not rebuild the provider at diff --git a/packages/agent-runtime/py/pyproject.toml b/packages/agent-runtime/py/pyproject.toml index 9751b591..0061544a 100644 --- a/packages/agent-runtime/py/pyproject.toml +++ b/packages/agent-runtime/py/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "steerable-agent-runtime" -version = "0.12.0" +version = "0.12.1" description = "Steerable agent runtime: LLM, tool, storage, and transport adapters." license = { text = "Apache-2.0" } readme = "README.md" diff --git a/packages/agent-runtime/py/src/steerable_agent_runtime/__init__.py b/packages/agent-runtime/py/src/steerable_agent_runtime/__init__.py index 2632d359..a863a53d 100644 --- a/packages/agent-runtime/py/src/steerable_agent_runtime/__init__.py +++ b/packages/agent-runtime/py/src/steerable_agent_runtime/__init__.py @@ -83,7 +83,7 @@ lineage, resolve_fork_seq, ) -from .budget import SessionBudgetExceeded, TreeBudget, TreeBudgetReport +from .spend import TreeSpend, TreeSpendReport from .tree import AgentTree, TreeMember from .team_board import TaskItem, TeamTaskBoard from .cache_control import ( @@ -383,9 +383,8 @@ "ChildRegistry", "ChildNoticeHooks", "CHILD_NOTICE_KIND", - "SessionBudgetExceeded", - "TreeBudget", - "TreeBudgetReport", + "TreeSpend", + "TreeSpendReport", "render_child_notice", "ChildStatusView", "SpawnedChild", diff --git a/packages/agent-runtime/py/src/steerable_agent_runtime/budget.py b/packages/agent-runtime/py/src/steerable_agent_runtime/budget.py deleted file mode 100644 index cd0768ae..00000000 --- a/packages/agent-runtime/py/src/steerable_agent_runtime/budget.py +++ /dev/null @@ -1,124 +0,0 @@ -"""One token budget for a whole delegating turn tree. - -``steerable_agent_harness.budget`` budgets **one loop run**: it charges that -run's own requests and reports exhaustion to that run. That is the wrong scope -once a turn can delegate: a parent plus three children would each get the full -allowance, so a turn's real spend could be four times what the host asked for -and no single loop would ever notice. - -This module is the other scope — one counter shared by every agent in the tree. -Each request, whoever made it, charges the same state, and the first one to -cross the limit fails there. The alternative (handing each child a slice of -the remainder) was considered and rejected: a serial child given 1/(n+1) of -the budget hits its own wall while the tree still has room, which turns a -generous budget into a tight one. - -Attribution is kept alongside the total because "the turn spent 40k" is not -actionable when a host needs to know which child spent it. -""" - -from __future__ import annotations - -import threading -from dataclasses import dataclass, field - -from .llm import LLMUsage - -__all__ = ["SessionBudgetExceeded", "TreeBudget", "TreeBudgetReport"] - - -class SessionBudgetExceeded(Exception): - """Raised when a request would take the tree past its token limit. - - Named for the session, not for a child: the limit belongs to the whole - turn tree, and the agent that happens to cross it is not the one at fault. - """ - - -@dataclass(frozen=True, slots=True) -class TreeBudgetReport: - """The tree's spend at one point in time. - - ``by_agent`` keys are the caller's own agent labels (``"parent"``, - ``"0.1"`` …) — the budget does not know about lineage and must not guess - it, so it stores whatever key the caller passes. - """ - - limit: int - spent: int - by_agent: dict[str, int] - - @property - def remaining(self) -> int: - return max(self.limit - self.spent, 0) - - @property - def exhausted(self) -> bool: - return self.spent >= self.limit - - -@dataclass -class TreeBudget: - """A token limit shared by every agent in one turn tree. - - Thread-safe: the loop hands usage in from both the parent's event loop and - the worker thread that drives the native engine, so plain attribute - updates would race. - """ - - limit: int - _spent: int = field(default=0, init=False) - _by_agent: dict[str, int] = field(default_factory=dict, init=False) - _lock: threading.Lock = field(default_factory=threading.Lock, init=False) - - def charge(self, usage: LLMUsage | None, *, agent: str) -> int: - """Charge one request's usage; returns the tree's spend afterwards. - - ``usage=None`` charges nothing but still records the agent, so a host - can tell "this child ran and reported nothing" apart from "this child - never ran" — the distinction matters when the bill does not add up. - - Raises: - SessionBudgetExceeded: when the charge takes the tree past - ``limit``. The spend is recorded **before** raising, so the - report a caller shows still includes the request that broke it. - """ - if usage is None: - with self._lock: - self._by_agent.setdefault(agent, 0) - return self._spent - # Total, not prompt+completion: providers disagree about whether the - # total includes cache reads, and ``usage.total_tokens`` is the one - # number every provider reports consistently. - billed = max(usage.total_tokens, 0) - with self._lock: - self._spent += billed - self._by_agent[agent] = self._by_agent.get(agent, 0) + billed - spent = self._spent - if spent > self.limit: - raise SessionBudgetExceeded( - f"turn tree spent {spent} tokens against a {self.limit}-token " - f"budget (agent {agent!r} crossed it)" - ) - return spent - - @property - def remaining(self) -> int: - """Tokens left, floored at zero.""" - with self._lock: - return max(self.limit - self._spent, 0) - - @property - def exhausted(self) -> bool: - """True once the tree has spent its whole limit.""" - with self._lock: - return self._spent >= self.limit - - def report(self) -> TreeBudgetReport: - """A snapshot, safe to hand to a host mid-turn.""" - with self._lock: - return TreeBudgetReport( - limit=self.limit, - spent=self._spent, - by_agent=dict(self._by_agent), - ) diff --git a/packages/agent-runtime/py/src/steerable_agent_runtime/orchestration.py b/packages/agent-runtime/py/src/steerable_agent_runtime/orchestration.py index 37215e4c..095469bf 100644 --- a/packages/agent-runtime/py/src/steerable_agent_runtime/orchestration.py +++ b/packages/agent-runtime/py/src/steerable_agent_runtime/orchestration.py @@ -40,7 +40,7 @@ from steerable_agent_protocol.generated import ToolCall, ToolResult -from .budget import TreeBudget +from .spend import TreeSpend from .hooks import ChainHooks, CompletionAction, CompletionDraft, NoopHooks from .history import completed_turn_prefix from .llm import LLMMessage, LLMProvider @@ -533,7 +533,7 @@ def __init__( history_store: Any | None = None, parent_record_id: str | None = None, parent_projection: Callable[[], list[LLMMessage]] | None = None, - budget: TreeBudget | None = None, + spend: TreeSpend | None = None, parent_route: Callable[[], tuple[str | None, str | None]] | None = None, provider_factory: Callable[[str | None, str | None], LLMProvider] | None = None, tree: AgentTree | None = None, @@ -592,7 +592,7 @@ def __init__( else None ) #: The tree's shared token limit; ``None`` keeps per-run accounting. - self._budget = budget + self._spend = spend self._depth = _depth self._lineage = _lineage self._pool = AgentPool( @@ -603,7 +603,7 @@ def __init__( event_sink=event_sink, registry=registry, parent_record_id=parent_record_id, - budget=budget, + spend=spend, # Needed to write a fork seed's provenance into the child's record. history_store=history_store, tree=tree, @@ -681,7 +681,7 @@ def _child_loop( parent_projection=lambda: ( own_loop[0].history.projection if own_loop else [] ), - budget=self._budget, + spend=self._spend, # Same tree and board: a grandchild is as much a member of the # job as its parent, and the plan it reads must be the one the # root wrote. diff --git a/packages/agent-runtime/py/src/steerable_agent_runtime/pool.py b/packages/agent-runtime/py/src/steerable_agent_runtime/pool.py index be81eb19..b49fcdcd 100644 --- a/packages/agent-runtime/py/src/steerable_agent_runtime/pool.py +++ b/packages/agent-runtime/py/src/steerable_agent_runtime/pool.py @@ -41,7 +41,7 @@ from itertools import count from typing import Any -from .budget import SessionBudgetExceeded, TreeBudget, TreeBudgetReport +from .spend import TreeSpend from .engines import ( AcpEngineSpec, AcpOutcome, @@ -161,6 +161,10 @@ def __init__(self, child_id: str, loop: CoreLoop | None) -> None: #: Terminal flag set by close()/shutdown(): a closed child rejects #: sends even after its run has finished. self.closed = False + #: Set by ``shutdown`` only — the turn ended, not the child. Its row + #: then settles as ``cancelled`` (resumable) rather than ``closed``: + #: "the parent stopped waiting" is not "the user gave up on it". + self.pool_gone = False #: Model-visible record snapshot at the end of the last cleanly #: finished run (cooperative cancel included — the loop guarantees #: no dangling tool_calls). ``None`` before the first clean finish; @@ -244,7 +248,7 @@ def __init__( event_sink: Callable[[str, dict[str, Any]], None] | None = None, registry: ChildRegistry | None = None, parent_record_id: str | None = None, - budget: TreeBudget | None = None, + spend: TreeSpend | None = None, history_store: Any | None = None, tree: AgentTree | None = None, ) -> None: @@ -277,10 +281,10 @@ def __init__( #: (``:child:``). Absent for a parent that never had #: one (a bare test loop), in which case children go unregistered. self._parent_record_id = parent_record_id - #: One token limit for the whole tree. ``None`` means each run keeps - #: its own accounting, which is the pre-delegation behaviour — a pool - #: without a shared budget cannot charge siblings against each other. - self._budget = budget + #: Per-agent accumulation for the turn's usage report. ``None`` keeps + #: the pool's own accounting off, which is what a bare pool (tests, + #: hosts without a tree) gets — nothing is charged, nothing is capped. + self._spend = spend #: The record channel. Needed only to write a fork seed's provenance #: into the child's own record; ``None`` keeps the legacy behaviour #: (the seed is just the child's opening messages). @@ -368,14 +372,6 @@ def spawn( f"({len(live)} children running); wait for one to finish " "or close one before spawning again" ) - # A tree that already spent its budget must not start new work: the - # child would run until its own wall and then be refused anyway, which - # costs tokens for nothing. - if self._budget is not None and self._budget.exhausted: - raise OrchestrationBudgetExceeded( - f"the turn tree has spent {self._budget.report().spent} of its " - f"{self._budget.limit} tokens; no further children can start" - ) self._seq += 1 child_id = f"{self._lineage}.{self._seq}" if acp_engine is not None: @@ -741,16 +737,11 @@ async def _run_child( handle.outcome = ChildOutcome(handle.child_id, status, answer) usage = handle.loop.last_run_usage handle.usage = usage - # Charge the tree before announcing: a child that pushed the tree over - # its limit must be reported as having done so, not settled quietly - # and letting the parent discover it on the next spawn. - budget_exceeded: str | None = None - if self._budget is not None: - try: - self._budget.charge(usage, agent=handle.child_id) - except SessionBudgetExceeded as exc: - budget_exceeded = str(exc) - logger.warning("child %s crossed the tree budget: %s", handle.child_id, exc) + # Record the spend for attribution. Unbounded by design: a turn that + # runs long is a turn that had more work, not a failure, and stopping + # it mid-task costs the work already done. The host shows the number. + if self._spend is not None: + self._spend.record(usage, agent=handle.child_id) kind = "child_completed" if status == "completed" else "child_failed" self._emit( kind, @@ -762,7 +753,6 @@ async def _run_child( # read, and a parent computing turn cost needs it before the # stream closes. **({"usage": _usage_payload(usage)} if usage is not None else {}), - **({"budgetExceeded": budget_exceeded} if budget_exceeded else {}), }, ) await self._settle_child(handle, status=status, usage=usage) @@ -859,10 +849,21 @@ async def _settle_child( if self._registry is None or self._parent_record_id is None: return record_id = default_record_id(self._parent_record_id, handle.child_id) + # A closed child's row says `closed`, whatever the run it was in the + # middle of reports. Cancelling to close produces `cancelled` from the + # loop, and writing that would leave the row resumable again — the + # in-memory flag dies with the pool, the row does not. + # + # ``shutdown`` also marks handles closed, but that is the turn + # ending rather than the user giving up: those rows settle as + # ``cancelled`` (resumable) and `pool_gone` is what tells them apart. + final_status = ( + "closed" if handle.closed and not handle.pool_gone else registry_status(status) + ) try: wrote = await self._registry.finished( record_id, - status=registry_status(status), + status=final_status, usage=usage, usage_known=handle.usage_known, ) @@ -871,14 +872,14 @@ async def _settle_child( except Exception as exc: # noqa: BLE001 — bookkeeping never fails a run logger.warning("child %s registry settle failed: %s", handle.child_id, exc) - def budget_report(self) -> TreeBudgetReport | None: - """The tree budget's snapshot, or ``None`` when this pool has none. + def spend_report(self) -> TreeSpendReport | None: + """The tree's per-agent spend, or ``None`` when this pool has none. Exposed so a host can report the turn's real cost (parent plus every - child) without walking the registry, and can tell "no limit" from - "zero spent". + child) without walking the registry. There is no limit to compare + against: the number is for display. """ - return self._budget.report() if self._budget is not None else None + return self._spend.report() if self._spend is not None else None def children_usage(self) -> tuple[list[dict[str, Any]], int]: """Per-child bills for this turn's usage record, and the unknown count. @@ -1132,6 +1133,13 @@ async def close(self, child_id: str) -> bool: # so a peer's message reports an unknown member instead of resuming an # agent the owner already gave up on. self._leave_tree(child_id) + # The same promise has to reach the durable row, not just this + # process. `send` after close is refused by `_resume_from_registry` + # only because that row says `closed`; leaving it at its last run's + # status let a closed child be resumed by a later turn (or by another + # executor reading the same registry) — the in-memory flag dies with + # the pool, the row does not. + await self._mark_closed(handle) if handle.outcome is not None: return True self._cancel_handle(handle) @@ -1143,6 +1151,28 @@ async def close(self, child_id: str) -> bool: handle.task.cancel() return True + async def _mark_closed(self, handle: _ChildHandle) -> None: + """Write ``closed`` onto the child's row; best-effort like settling. + + A pool without a registry (tests, hosts without storage) keeps its + previous behaviour, and a storage failure must not turn a close into + an error — the in-process refusal still holds for this turn. + """ + if self._registry is None or self._parent_record_id is None: + return + record_id = default_record_id(self._parent_record_id, handle.child_id) + try: + wrote = await self._registry.finished( + record_id, + status="closed", + usage=handle.usage, + usage_known=handle.usage_known, + ) + if wrote: + self._registry.mark_settled(record_id) + except Exception as exc: # noqa: BLE001 — bookkeeping never fails a run + logger.warning("child %s registry close failed: %s", handle.child_id, exc) + def _cancel_handle(self, handle: _ChildHandle) -> None: """Ask one child to stop, whichever engine it runs on. @@ -1158,12 +1188,16 @@ def _cancel_handle(self, handle: _ChildHandle) -> None: async def shutdown(self) -> None: """Cooperatively cancel every live child; hard-cancel stragglers. - Terminal for the whole pool: every child is marked closed, so no - sends or resumes are accepted afterwards. + Terminal for the whole **pool**, not for its children: a child that + was still running when the turn ended stays resumable, so its row is + ``cancelled`` (the run was cut short), not ``closed`` (the user gave + up on it). ``close`` is the one that writes ``closed``, because that + is the only path where "never again" was actually asked for. """ live = [h for h in self._children.values() if h.outcome is None] for handle in self._children.values(): handle.closed = True + handle.pool_gone = True self._leave_tree(handle.child_id) for handle in live: self._cancel_handle(handle) diff --git a/packages/agent-runtime/py/src/steerable_agent_runtime/spend.py b/packages/agent-runtime/py/src/steerable_agent_runtime/spend.py new file mode 100644 index 00000000..0acbebc3 --- /dev/null +++ b/packages/agent-runtime/py/src/steerable_agent_runtime/spend.py @@ -0,0 +1,82 @@ +"""Per-agent token accounting for a delegating turn tree. + +The question this answers is "what did this turn cost, and which agent spent +it" — nothing more. There is no limit here and no way to add one: a turn that +runs long is a turn that had more work, and stopping it mid-task throws away +the work already paid for. A host that wants cost control puts the gate where +it belongs (before a turn starts, or on a period budget), not inside a task +that is already half done. + +Scope is the whole tree, not one loop. ``steerable_agent_harness.budget`` +accounts for a single run; once a turn delegates, a parent plus three children +would each report their own slice and no single number would describe the +turn. One counter shared by every member gives the host that number, and the +per-agent breakdown says which member spent it. + +Why an object rather than a dict the host already has: the loop hands usage in +from both the parent's event loop and the worker thread that drives the native +engine, so plain attribute updates would race. +""" + +from __future__ import annotations + +import threading +from dataclasses import dataclass, field + +from .llm import LLMUsage + +__all__ = ["TreeSpend", "TreeSpendReport"] + + +@dataclass(frozen=True, slots=True) +class TreeSpendReport: + """The tree's spend at one point in time. + + ``by_agent`` keys are the caller's own agent labels (``"parent"``, + ``"0.1"`` …) — this class does not know about lineage and must not guess + it, so it stores whatever key the caller passes. + """ + + spent: int + by_agent: dict[str, int] + + +@dataclass +class TreeSpend: + """Token accounting shared by every agent in one turn tree.""" + + _spent: int = field(default=0, init=False) + _by_agent: dict[str, int] = field(default_factory=dict, init=False) + _lock: threading.Lock = field(default_factory=threading.Lock, init=False) + + def record(self, usage: LLMUsage | None, *, agent: str) -> int: + """Add one run's usage; returns the tree's spend afterwards. + + ``usage=None`` adds nothing but still names the agent, so a host can + tell "this child ran and reported nothing" (an external engine that + bills nothing we can see) apart from "this child never ran". The + distinction is what keeps a partial total from reading as complete. + """ + if usage is None: + with self._lock: + self._by_agent.setdefault(agent, 0) + return self._spent + # Total, not prompt+completion: providers disagree about whether the + # total includes cache reads, and ``usage.total_tokens`` is the one + # number every provider reports consistently. + billed = max(usage.total_tokens, 0) + with self._lock: + self._spent += billed + self._by_agent[agent] = self._by_agent.get(agent, 0) + billed + return self._spent + + @property + def spent(self) -> int: + """Tokens spent by the whole tree so far.""" + with self._lock: + return self._spent + + def report(self) -> TreeSpendReport: + """A snapshot, safe to hand to a host mid-turn.""" + with self._lock: + return TreeSpendReport(spent=self._spent, by_agent=dict(self._by_agent)) diff --git a/packages/agent-runtime/py/tests/test_orchestration.py b/packages/agent-runtime/py/tests/test_orchestration.py index 6745bc9a..6642db82 100644 --- a/packages/agent-runtime/py/tests/test_orchestration.py +++ b/packages/agent-runtime/py/tests/test_orchestration.py @@ -15,6 +15,7 @@ import pytest from steerable_agent_runtime import ( + ChildRegistry, CoreLoop, LoopConfig, RouterToolExecutor, @@ -22,11 +23,13 @@ ) from steerable_agent_runtime.llm import LLMMessage, LLMStreamChunk from steerable_agent_runtime.orchestration import ( + AgentPool, ChildOutcome, OrchestrationConfig, OrchestrationExecutor, orchestration_tool_descriptors, ) +from steerable_agent_runtime.storage import InMemoryStorage from test_loop import collect, final_completion @@ -1100,6 +1103,57 @@ async def test_send_to_closed_child_fails_with_child_closed() -> None: assert _payload(listing)["children"][0]["status"] == "closed" +@pytest.mark.asyncio +async def test_a_later_turn_cannot_resume_a_child_closed_by_an_earlier_one() -> None: + """Close has to survive the pool that took it. + + The same-turn case above is caught by the handle's own flag. A later turn + builds a fresh pool with no handle at all, so the only thing standing + between `agent_send` and a closed child is the row — and the row used to + keep the status of its last run, which made an explicitly closed child + look merely finished. Observed: `delivery: "resumed"` after `agent_close`. + """ + store = InMemoryStorage() + registry = ChildRegistry(store) + + def loop_factory(child_id: str, tool_filter: frozenset[str] | None): + provider, _ = _content_provider({"child task": [{"content": "child answer"}]}) + return ( + CoreLoop(provider, RouterToolExecutor(ToolRouter()), LoopConfig()), + [], + ) + + def pool() -> AgentPool: + return AgentPool( + config=OrchestrationConfig(), + depth=0, + lineage="0", + loop_factory=loop_factory, + registry=registry, + parent_record_id="chat/p", + ) + + # Turn one: spawn, let it finish, then close it. + first = pool() + first.spawn("child task", None) + await first.wait("0.1", 5) + await first.close("0.1") + await first.shutdown() + + row = await store.get_child("chat/p:child:0.1") + assert row is not None + assert row.status == "closed" + + # Turn two: a new pool, no handle for 0.1. Resolving it can only consult + # the row, which is exactly the path that used to resume a closed child. + second = pool() + view = await registry.find_child("chat/p", "0.1") + await second.shutdown() + assert view is not None + assert view.record.status == "closed" + assert view.resumable is False + + @pytest.mark.asyncio async def test_resume_respects_the_parallel_cap() -> None: started = asyncio.Event() diff --git a/packages/agent-runtime/py/tests/test_pool_registry.py b/packages/agent-runtime/py/tests/test_pool_registry.py index a3d4a63b..46cbb9ea 100644 --- a/packages/agent-runtime/py/tests/test_pool_registry.py +++ b/packages/agent-runtime/py/tests/test_pool_registry.py @@ -266,3 +266,77 @@ def _spawn_of(child_id: str): profile="explore", engine="coreloop", ) + + +# --------------------------------------------------------------------------- +# close is durable, not just in-process +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_close_writes_closed_onto_the_row() -> None: + """Closing has to reach disk, or a later turn resumes a closed child. + + The in-memory ``closed`` flag lives on the handle, and the handle dies + with the pool. `agent_send` decides whether a child is resumable by + reading its **row**, so a close that only touched the handle left a + closed child looking merely finished — and the observed behaviour was + `delivery: "resumed"` after an explicit `agent_close`. + """ + store = InMemoryStorage() + registry = ChildRegistry(store) + pool = _pool(registry=registry, provider=_ScriptedProvider()) + + pool.spawn("look this up", None) + await pool.wait("0.1", 5) + assert (await store.get_child("chat/p:child:0.1")).status == "completed" + + await pool.close("0.1") + + assert (await store.get_child("chat/p:child:0.1")).status == "closed" + await pool.shutdown() + + +@pytest.mark.asyncio +async def test_closing_a_running_child_does_not_settle_it_as_cancelled() -> None: + """Close cancels the run, and that cancel must not overwrite the row. + + Cancelling to close produces ``cancelled`` from the loop. Writing that + back would leave the row resumable again — the exact state close is + supposed to end. + """ + gate = asyncio.Event() + store = InMemoryStorage() + registry = ChildRegistry(store) + pool = _pool(registry=registry, provider=_ScriptedProvider(gate=gate)) + + pool.spawn("still running", None) + await asyncio.sleep(0.05) + + await pool.close("0.1") + + row = await store.get_child("chat/p:child:0.1") + assert row is not None + assert row.status == "closed" + gate.set() + await pool.shutdown() + + +@pytest.mark.asyncio +async def test_a_closed_row_is_not_resumable() -> None: + """The point of the durable ``closed``: the resume path reads it.""" + store = InMemoryStorage() + registry = ChildRegistry(store) + pool = _pool(registry=registry, provider=_ScriptedProvider()) + + pool.spawn("one run", None) + await pool.wait("0.1", 5) + await pool.close("0.1") + await pool.shutdown() + + # A fresh pool is what a later turn builds; it has no handle for 0.1, so + # only the row can say the child is finished for good. + view = await registry.find_child("chat/p", "0.1") + assert view is not None + assert view.record.status == "closed" + assert view.resumable is False diff --git a/packages/agent-runtime/py/tests/test_tree_budget.py b/packages/agent-runtime/py/tests/test_tree_budget.py deleted file mode 100644 index 0a92c7d5..00000000 --- a/packages/agent-runtime/py/tests/test_tree_budget.py +++ /dev/null @@ -1,143 +0,0 @@ -"""One token budget for the whole turn tree. - -The failure this prevents: every loop in a delegating turn keeping its own -accounting, so a parent plus three children each spend the full allowance and -no single loop ever sees the tree go over. - -The rejected alternative is pinned too — handing each child a slice of the -remainder makes a serial child hit its own wall while the tree still has room, -which turns a generous budget into a tight one. -""" - -from __future__ import annotations - -import threading - -import pytest -from steerable_agent_runtime.budget import ( - SessionBudgetExceeded, - TreeBudget, -) -from steerable_agent_runtime.llm import LLMUsage - - -def _usage(total: int, *, prompt: int | None = None, completion: int | None = None) -> LLMUsage: - return LLMUsage( - prompt_tokens=prompt if prompt is not None else total, - completion_tokens=completion if completion is not None else 0, - total_tokens=total, - ) - - -def test_charging_accumulates_across_agents() -> None: - budget = TreeBudget(limit=100) - - budget.charge(_usage(30), agent="parent") - budget.charge(_usage(20), agent="0.1") - report = budget.report() - - assert report.spent == 50 - assert report.remaining == 50 - assert report.exhausted is False - - -def test_attribution_is_kept_per_agent() -> None: - """'The turn spent 40k' is not actionable; 'which child' is.""" - budget = TreeBudget(limit=1000) - - budget.charge(_usage(300), agent="0.1") - budget.charge(_usage(100), agent="0.2") - budget.charge(_usage(50), agent="parent") - - assert budget.report().by_agent == {"0.1": 300, "0.2": 100, "parent": 50} - - -def test_the_limit_is_a_tree_limit_not_a_per_child_limit() -> None: - """Two children each under the limit must still trip a shared one.""" - budget = TreeBudget(limit=100) - budget.charge(_usage(60), agent="0.1") - - with pytest.raises(SessionBudgetExceeded, match="crossed it"): - budget.charge(_usage(60), agent="0.2") - - -def test_the_overspending_request_is_included_in_the_report() -> None: - """A caller showing the report must see the request that broke the budget.""" - budget = TreeBudget(limit=100) - with pytest.raises(SessionBudgetExceeded): - budget.charge(_usage(150), agent="0.1") - - report = budget.report() - assert report.spent == 150 - assert report.exhausted is True - - -def test_exactly_reaching_the_limit_is_allowed() -> None: - budget = TreeBudget(limit=100) - budget.charge(_usage(100), agent="0.1") - assert budget.report().spent == 100 - assert budget.report().exhausted is True - - -def test_remaining_floors_at_zero() -> None: - budget = TreeBudget(limit=10) - with pytest.raises(SessionBudgetExceeded): - budget.charge(_usage(50), agent="0.1") - assert budget.remaining == 0 - - -def test_a_none_usage_records_the_agent_without_charging() -> None: - """'Ran and reported nothing' must be distinguishable from 'never ran'.""" - budget = TreeBudget(limit=100) - - budget.charge(None, agent="0.3") - - report = budget.report() - assert report.spent == 0 - assert report.by_agent == {"0.3": 0} - - -def test_negative_totals_do_not_refund() -> None: - """A bad provider report must not buy budget back.""" - budget = TreeBudget(limit=100) - budget.charge(_usage(40), agent="0.1") - budget.charge(_usage(-50), agent="0.1") - assert budget.report().spent == 40 - - -def test_concurrent_charges_do_not_lose_tokens() -> None: - """The loop feeds usage from two threads; a lost update would under-count.""" - budget = TreeBudget(limit=1_000_000) - per_thread = 200 - threads = 8 - - def run() -> None: - for _ in range(per_thread): - budget.charge(_usage(1), agent="0.1") - - workers = [threading.Thread(target=run) for _ in range(threads)] - for worker in workers: - worker.start() - for worker in workers: - worker.join() - - assert budget.report().spent == per_thread * threads - - -def test_the_rejected_slice_design_is_wrong_for_a_serial_child() -> None: - """Documents why slices were rejected, using the tree budget as the fix. - - With a 1/(n+1) slice, a child in an otherwise idle tree is capped at a - fraction of what is actually available. The tree budget has no such - notion: it charges what was spent and no more. - """ - limit = 100 - slices = 4 - slice_size = limit // (slices + 1) # the rejected scheme - budget = TreeBudget(limit=limit) - - # One child alone can use most of the tree, not just one slice. - budget.charge(_usage(limit - 10), agent="0.1") - - assert slice_size < limit - 10 - assert budget.report().remaining == 10 diff --git a/packages/agent-runtime/py/tests/test_tree_spend.py b/packages/agent-runtime/py/tests/test_tree_spend.py new file mode 100644 index 00000000..37706fcb --- /dev/null +++ b/packages/agent-runtime/py/tests/test_tree_spend.py @@ -0,0 +1,116 @@ +"""Token accounting for the whole turn tree. + +This answers "what did this turn cost, and which agent spent it" and nothing +else. It used to enforce a limit; that was removed on purpose, because a turn +that runs long is a turn that had more work, and stopping it mid-task throws +away the work already paid for. Cost control belongs before a turn starts, not +inside one that is half done. + +What survives is the scope: one counter shared by the parent and every child, +so the host reads one number for the turn instead of adding up loops, with the +per-agent split saying which member spent it. +""" + +from __future__ import annotations + +import threading + +from steerable_agent_runtime.spend import TreeSpend +from steerable_agent_runtime.llm import LLMUsage + + +def _usage(total: int, *, prompt: int | None = None, completion: int | None = None) -> LLMUsage: + return LLMUsage( + prompt_tokens=prompt if prompt is not None else total, + completion_tokens=completion if completion is not None else 0, + total_tokens=total, + ) + + +def test_recording_accumulates_across_agents() -> None: + spend = TreeSpend() + + spend.record(_usage(30), agent="parent") + spend.record(_usage(20), agent="0.1") + + assert spend.report().spent == 50 + + +def test_attribution_is_kept_per_agent() -> None: + """'The turn spent 40k' is not actionable; 'which child' is.""" + spend = TreeSpend() + + spend.record(_usage(300), agent="0.1") + spend.record(_usage(100), agent="0.2") + spend.record(_usage(50), agent="parent") + + assert spend.report().by_agent == {"0.1": 300, "0.2": 100, "parent": 50} + + +def test_there_is_no_limit_to_cross() -> None: + """The whole point of the change: a big turn is reported, not stopped. + + A previous design raised ``SessionBudgetExceeded`` here and left the child + stopped at ``budget_exhausted``, needing a human to click resume. That made + "let four agents finish the refactor" end at 80% with no error the user + could act on. + """ + spend = TreeSpend() + + spend.record(_usage(10_000_000), agent="0.1") + spend.record(_usage(10_000_000), agent="parent") + + assert spend.report().spent == 20_000_000 + assert spend.report().by_agent == {"0.1": 10_000_000, "parent": 10_000_000} + + +def test_a_none_usage_records_the_agent_without_adding_tokens() -> None: + """'Ran and reported nothing' must be distinguishable from 'never ran'.""" + spend = TreeSpend() + + spend.record(None, agent="0.3") + + report = spend.report() + assert report.spent == 0 + assert report.by_agent == {"0.3": 0} + + +def test_negative_totals_do_not_refund() -> None: + """A bad provider report must not make the turn look cheaper.""" + spend = TreeSpend() + spend.record(_usage(40), agent="0.1") + spend.record(_usage(-50), agent="0.1") + + assert spend.report().spent == 40 + + +def test_concurrent_records_do_not_lose_tokens() -> None: + """The loop feeds usage from two threads; a lost update would under-count.""" + spend = TreeSpend() + per_thread = 200 + threads = 8 + + def run() -> None: + for _ in range(per_thread): + spend.record(_usage(1), agent="0.1") + + workers = [threading.Thread(target=run) for _ in range(threads)] + for worker in workers: + worker.start() + for worker in workers: + worker.join() + + assert spend.report().spent == per_thread * threads + + +def test_the_report_is_a_snapshot() -> None: + """A host reading mid-turn must not see later records in an old report.""" + spend = TreeSpend() + spend.record(_usage(10), agent="0.1") + + snapshot = spend.report() + spend.record(_usage(90), agent="0.2") + + assert snapshot.spent == 10 + assert snapshot.by_agent == {"0.1": 10} + assert spend.report().spent == 100 diff --git a/packages/agent-runtime/py/tests/test_tree_budget_pool.py b/packages/agent-runtime/py/tests/test_tree_spend_pool.py similarity index 72% rename from packages/agent-runtime/py/tests/test_tree_budget_pool.py rename to packages/agent-runtime/py/tests/test_tree_spend_pool.py index 0820a9c3..d6f9bb83 100644 --- a/packages/agent-runtime/py/tests/test_tree_budget_pool.py +++ b/packages/agent-runtime/py/tests/test_tree_spend_pool.py @@ -1,11 +1,12 @@ -"""The pool charges the shared tree budget, and reports it. +"""The pool records each child's spend into the shared tree counter. Two behaviours matter here and only here: -- a child's usage reaches the tree counter (not just its own registry row); -- a tree with nothing left refuses to start a child, rather than letting it - run to its own wall and fail afterwards — the run would cost tokens for an - answer that gets thrown away. +- a child's usage reaches the tree counter (not just its own registry row), so + the host reads one number for the turn instead of adding up loops; +- nothing is refused for spending too much: the counter reports, it does not + gate. A previous design refused the next spawn once the tree overflowed, and + left children stopped mid-task at ``budget_exhausted``. """ from __future__ import annotations @@ -21,7 +22,7 @@ LoopConfig, RouterToolExecutor, ToolRouter, - TreeBudget, + TreeSpend, ) from steerable_agent_runtime.llm import LLMMessage, LLMStreamChunk, LLMUsage from steerable_agent_runtime.orchestration import ( @@ -35,7 +36,7 @@ class _UsageProvider: - """Reports a fixed token bill so the tree counter has something to charge.""" + """Reports a fixed token bill so the tree counter has something to record.""" name = "fake" model = "fake-model" @@ -59,7 +60,7 @@ async def _gen() -> AsyncIterator[LLMStreamChunk]: def _executor( - provider: Any, *, budget: TreeBudget | None, max_parallel: int = 4 + provider: Any, *, spend: TreeSpend | None, max_parallel: int = 4 ) -> OrchestrationExecutor: return OrchestrationExecutor( RouterToolExecutor(ToolRouter()), @@ -67,7 +68,7 @@ def _executor( OrchestrationConfig(max_parallel=max_parallel), registry=ChildRegistry(InMemoryStorage()), parent_record_id=PARENT, - budget=budget, + spend=spend, ) @@ -83,23 +84,23 @@ async def _spawn(executor: OrchestrationExecutor, task: str = "task") -> dict[st @pytest.mark.asyncio -async def test_a_child_charges_the_tree_budget() -> None: - budget = TreeBudget(limit=10_000) - executor = _executor(_UsageProvider(120), budget=budget) +async def test_a_child_records_into_the_tree_counter() -> None: + spend = TreeSpend() + executor = _executor(_UsageProvider(120), spend=spend) await _spawn(executor) await executor._pool.wait("0.1", 5) await executor.shutdown() - report = budget.report() + report = spend.report() assert report.spent >= 120 assert report.by_agent.get("0.1", 0) >= 120 @pytest.mark.asyncio -async def test_two_children_both_charge_the_same_counter() -> None: - budget = TreeBudget(limit=10_000) - executor = _executor(_UsageProvider(100), budget=budget, max_parallel=4) +async def test_two_children_share_one_counter() -> None: + spend = TreeSpend() + executor = _executor(_UsageProvider(100), spend=spend, max_parallel=4) for call_id in ("s1", "s2"): result = await executor.execute( @@ -111,17 +112,22 @@ async def test_two_children_both_charge_the_same_counter() -> None: await executor._pool.wait("0.2", 5) await executor.shutdown() - report = budget.report() + report = spend.report() # Both children are attributed separately, and the total is their sum. assert set(report.by_agent) >= {"0.1", "0.2"} assert report.spent >= 200 @pytest.mark.asyncio -async def test_an_exhausted_tree_refuses_a_new_child() -> None: - """Starting a child that cannot finish costs tokens for nothing.""" - budget = TreeBudget(limit=10) - executor = _executor(_UsageProvider(500), budget=budget) +async def test_a_huge_spend_does_not_refuse_the_next_child() -> None: + """Reporting is not gating: the turn keeps working and the host sees the bill. + + The old behaviour refused this spawn with ``orchestration_budget_exceeded`` + once the tree crossed its limit. That stopped a task the user had already + paid for partway through, for a limit nobody had asked to enforce. + """ + spend = TreeSpend() + executor = _executor(_UsageProvider(500_000), spend=spend) await _spawn(executor) await executor._pool.wait("0.1", 5) @@ -130,17 +136,17 @@ async def test_an_exhausted_tree_refuses_a_new_child() -> None: ToolCall(id="s2", name="agent_spawn", arguments={"task": "another"}), None, # type: ignore[arg-type] ) + await executor._pool.wait("0.2", 5) await executor.shutdown() - assert result.success is False - assert "orchestration_budget_exceeded" in (result.error or "") - assert "tokens" in (result.error or "") + assert result.success is True, result.error + assert spend.report().spent >= 1_000_000 @pytest.mark.asyncio -async def test_without_a_budget_nothing_is_charged_or_refused() -> None: - """A host that did not ask for a tree limit keeps the old behaviour.""" - executor = _executor(_UsageProvider(9_999), budget=None) +async def test_without_a_counter_nothing_is_recorded() -> None: + """A bare pool (tests, hosts without a tree) keeps working unchanged.""" + executor = _executor(_UsageProvider(9_999), spend=None) await _spawn(executor) await executor._pool.wait("0.1", 5) @@ -151,29 +157,22 @@ async def test_without_a_budget_nothing_is_charged_or_refused() -> None: await executor.shutdown() assert result.success is True + assert executor.pool.spend_report() is None @pytest.mark.asyncio -async def test_budget_report_is_none_without_a_budget() -> None: - """'No limit' must be distinguishable from 'nothing spent'.""" - executor = _executor(_UsageProvider(10), budget=None) - assert executor.pool.budget_report() is None - await executor.shutdown() - - -@pytest.mark.asyncio -async def test_budget_report_exposes_the_split_for_a_host() -> None: - budget = TreeBudget(limit=5_000) - executor = _executor(_UsageProvider(400), budget=budget) +async def test_spend_report_exposes_the_split_for_a_host() -> None: + spend = TreeSpend() + executor = _executor(_UsageProvider(400), spend=spend) await _spawn(executor) await executor._pool.wait("0.1", 5) - report = executor.pool.budget_report() + report = executor.pool.spend_report() await executor.shutdown() assert report is not None - assert report.limit == 5_000 + assert report.spent >= 400 assert report.by_agent.get("0.1", 0) >= 400 diff --git a/packages/agent-runtime/ts/package.json b/packages/agent-runtime/ts/package.json index 51cb5a8a..44fa2185 100644 --- a/packages/agent-runtime/ts/package.json +++ b/packages/agent-runtime/ts/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/agent-runtime", - "version": "0.12.0", + "version": "0.12.1", "description": "Steerable framework \u2014 official TypeScript production runtime. Owns the embedded Python sidecar lifecycle (spawn / ready handshake / health / bounded auto-restart / graceful drain) and exposes the CoreLoop-level API over the sidecar JSON-RPC surface. There is no TS CoreLoop; this package drives the same Rust CoreLoop the server uses (via the Python sidecar facade), so cross-language conformance holds by construction.", "license": "Apache-2.0", "homepage": "https://steerableframework.com/", diff --git a/packages/agent-shell/tauri/package.json b/packages/agent-shell/tauri/package.json index 4bdea9c6..e730bc81 100644 --- a/packages/agent-shell/tauri/package.json +++ b/packages/agent-shell/tauri/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/agent-shell-tauri", - "version": "0.12.0", + "version": "0.12.1", "description": "Reusable Tauri Rust host source for @steerable/agent-shell", "license": "Apache-2.0", "homepage": "https://steerableframework.com/", diff --git a/packages/agent-shell/ts/package.json b/packages/agent-shell/ts/package.json index e9814328..2e12463b 100644 --- a/packages/agent-shell/ts/package.json +++ b/packages/agent-shell/ts/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/agent-shell", - "version": "0.12.0", + "version": "0.12.1", "description": "Steerable framework \u2014 product-neutral Node HostRuntime and headless HTTP server shared by Tauri desktop and browser deployments; scenario packs extend it through @steerable/pack-sdk.", "license": "Apache-2.0", "homepage": "https://steerableframework.com/", diff --git a/packages/agent-shell/ts/src/sidecar/types.ts b/packages/agent-shell/ts/src/sidecar/types.ts index 641db56d..b923a806 100644 --- a/packages/agent-shell/ts/src/sidecar/types.ts +++ b/packages/agent-shell/ts/src/sidecar/types.ts @@ -618,11 +618,11 @@ export interface SidecarStreamDone { unknownUsageChildren?: number; }; /** - * R5: the whole turn tree's spend against `budgetTokens`. Absent when the - * host asked for no tree limit — "no limit" must stay distinguishable from - * "spent nothing". + * R5: the whole turn tree's spend, per agent. Always present on a + * delegating turn — there is no limit to compare it against, and none to + * be absent. */ - treeUsage?: { limit: number; spent: number; byAgent: Record }; + treeUsage?: { spent: number; byAgent: Record }; } /** One child's bill inside `stream.done`'s `usage.children`. */ diff --git a/packages/agent-shell/web/package.json b/packages/agent-shell/web/package.json index 6248a923..032f937d 100644 --- a/packages/agent-shell/web/package.json +++ b/packages/agent-shell/web/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/agent-shell-web", - "version": "0.12.0", + "version": "0.12.1", "type": "module", "description": "Steerable framework \u2014 product-neutral renderer SPA source for @steerable/agent-shell (React + Vite). Consumed by product web entry points via the `@/` alias (anchored at this package's src/) and the createProductViteConfig factory. Published as a source package (src/), plus the compiled vite.base config factory (vite.base.js + .d.ts) for Node-side config loading.", "license": "Apache-2.0", diff --git a/packages/agent-ui/ts/package.json b/packages/agent-ui/ts/package.json index af8409db..e817f95a 100644 --- a/packages/agent-ui/ts/package.json +++ b/packages/agent-ui/ts/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/agent-ui", - "version": "0.12.0", + "version": "0.12.1", "description": "Steerable framework Tier 4 \u2014 headless React hooks (useAgentSession, useChatStream, useToolCallStatus) and Tailwind-themed components (ChatPanel, MessageList, OrchestrationPlanCard, ToolCallRenderer, SSEStreamView) for embedding Steerable agents in any React app.", "license": "Apache-2.0", "homepage": "https://steerableframework.com/storybook/", diff --git a/packages/pack-sdk/ts/package.json b/packages/pack-sdk/ts/package.json index 0fe5970c..0c7761a7 100644 --- a/packages/pack-sdk/ts/package.json +++ b/packages/pack-sdk/ts/package.json @@ -1,6 +1,6 @@ { "name": "@steerable/pack-sdk", - "version": "0.12.0", + "version": "0.12.1", "type": "module", "description": "Scenario pack contract for @steerable/agent-shell (pure types, zero runtime). A scenario pack declares every extension a vertical scenario needs \u2014 services, tools, tables, skills, agent seeds, HTTP routes, renderer slots, branding \u2014 and the host composes the selected packs at build time.", "license": "Apache-2.0", diff --git a/packages/plugin-sdk/py/pyproject.toml b/packages/plugin-sdk/py/pyproject.toml index 9d801b8d..a6c35650 100644 --- a/packages/plugin-sdk/py/pyproject.toml +++ b/packages/plugin-sdk/py/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "steerable-plugin-sdk" -version = "0.12.0" +version = "0.12.1" description = "Pure-Python authoring and RPC SDK for Steerable tool plugins" license = { text = "Apache-2.0" } readme = "README.md" diff --git a/packages/sidecar/py/README.md b/packages/sidecar/py/README.md index 95073c2e..eaf740bb 100644 --- a/packages/sidecar/py/README.md +++ b/packages/sidecar/py/README.md @@ -50,9 +50,14 @@ Every change below is additive except where noted. - **`stream.done` gains fields, changes none.** `usage` grows `childPromptTokens` / `childCompletionTokens` / `childTotalTokens`, `children[]` (per-child split) and `unknownUsageChildren` (children whose - engine reports no tokens at all). `treeUsage: {limit, spent, byAgent}` is - present only when the request carried `budgetTokens`. -- **`budgetTokens` now bounds the whole turn tree**, not each loop. + engine reports no tokens at all). `treeUsage: {spent, byAgent}` carries the + whole turn tree's bill, always present — it is a display figure and compares + against nothing. +- **`budgetTokens` no longer bounds the turn tree.** It keeps its older job of + capping the parent run's own loop. The tree-wide limit was removed: it stopped + tasks partway through and left children at `budget_exhausted` waiting for a + human to resume, which costs more than the tokens it saves. The spend figure + above is what a host shows instead. - **`orchestration` accepts an object**: `{enabled, maxDepth, maxParallel, childMaxRounds, childMaxToolErrors, forkTurns}`. A bare boolean still means `1 / 4`, so an older client keeps working. diff --git a/packages/sidecar/py/pyproject.toml b/packages/sidecar/py/pyproject.toml index b1b734f2..70d4cb4d 100644 --- a/packages/sidecar/py/pyproject.toml +++ b/packages/sidecar/py/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "steerable-sidecar" -version = "0.12.0" +version = "0.12.1" description = "Steerable agent runtime sidecar — JSON-RPC over stdio." license = { text = "Apache-2.0" } readme = "README.md" diff --git a/packages/sidecar/py/src/steerable_sidecar/sidecar.py b/packages/sidecar/py/src/steerable_sidecar/sidecar.py index b01242f2..e62366d3 100644 --- a/packages/sidecar/py/src/steerable_sidecar/sidecar.py +++ b/packages/sidecar/py/src/steerable_sidecar/sidecar.py @@ -81,9 +81,8 @@ AgentTree, OrchestrationConfig, OrchestrationExecutor, - SessionBudgetExceeded, TeamTaskBoard, - TreeBudget, + TreeSpend, PluginLoadError, PluginStateError, PolicyDeniedError, @@ -2235,14 +2234,11 @@ def _amendment_sink(rule: Any) -> None: # agent.child notification stream, and a concurrent profile's # same-round delegations execute in parallel under the pool budget. loop_config = _build_loop_config(params) - # The tree budget is a second scope over the same number: `loop_config` - # budgets the parent run, this one budgets the parent plus every child - # it spawns. Both are created from `budgetTokens` so a host that asked - # for a limit gets one that the whole tree shares. Absent it, neither - # exists and behaviour is exactly as before. - tree_budget = ( - _tree_budget_from(params) if params.get("budgetTokens") is not None else None - ) + # Spend accounting for the whole turn tree: the parent plus every child + # it spawns. Always on, because the host shows it (R6's per-turn bill); + # it caps nothing. The per-run token wall, if the caller asked for one, + # is inside `loop_config` and stays a separate concern. + tree_spend = _tree_spend() # The parent loop is created after both executors (the loop needs the # executors, and a fork needs the loop's transcript). Both multi-agent # surfaces read the transcript through this holder, filled in once the @@ -2595,7 +2591,7 @@ def _subagent_provider_factory( parent_projection=parent_projection, parent_route=parent_route, provider_factory=_orchestration_provider_factory, - budget=tree_budget, + spend=tree_spend, tree=team_tree, team_board=team_board, ) @@ -2778,20 +2774,16 @@ def _subagent_provider_factory( pending_content.clear() if ( not parent_charged - and tree_budget is not None and event.kind == "completion" and event.data.get("status") != "executing" ): - # Charge the parent **before** the terminal event goes - # out: `stream.done` reports the tree's spend, and the - # parent is the largest part of it. Charging afterwards + # Record the parent's spend **before** the terminal event + # goes out: `stream.done` reports the tree's total, and the + # parent is the largest part of it. Recording afterwards # (in `finally`) reported a tree that had spent nothing # while the child's numbers were already in. parent_charged = True - try: - tree_budget.charge(loop.last_run_usage, agent="parent") - except SessionBudgetExceeded as exc: - logger.warning("parent crossed the tree budget: %s", exc) + tree_spend.record(loop.last_run_usage, agent="parent") await self._emit_loop_event( transport, stream_id, @@ -2799,11 +2791,7 @@ def _subagent_provider_factory( recorder.trace_id, model=params.get("model"), hooks=hooks, - tree_report=( - (lambda: _tree_report_of(tree_budget)) - if tree_budget is not None - else None - ), + tree_report=(lambda: _tree_report_of(tree_spend)), child_usage=( orchestration.pool.children_usage if orchestration is not None @@ -2839,15 +2827,12 @@ def _subagent_provider_factory( ) finally: # Backstop for the paths that never reach a terminal completion - # (cancel, exception): the tree limit covers the parent too, and - # after this point the pool is gone and nobody can charge it. The - # normal path already charged at the terminal event, so this does - # not double-count. - if tree_budget is not None and not parent_charged: - try: - tree_budget.charge(loop.last_run_usage, agent="parent") - except SessionBudgetExceeded as exc: - logger.warning("parent crossed the tree budget: %s", exc) + # (cancel, exception): the report covers the parent too, and after + # this point the pool is gone and nobody can record it. The normal + # path already recorded at the terminal event, so this does not + # double-count. + if not parent_charged: + tree_spend.record(loop.last_run_usage, agent="parent") reset_turn_chat_id(chat_token) self._coreloops.pop(stream_id, None) self._exec_controls.pop(stream_id, None) @@ -3946,15 +3931,16 @@ def _acp_permission_from_profile( return AcpPermissionPolicy(default=default, by_kind=by_kind) # type: ignore[arg-type] -def _tree_report_of(budget: TreeBudget) -> dict[str, Any]: +def _tree_report_of(spend: TreeSpend) -> dict[str, Any]: """The whole tree's spend as the wire object ``stream.done`` carries. ``byAgent`` keys are the caller's agent labels (``"parent"``, ``"0.1"``), which is what lets a host attribute a turn's bill without reading the - registry for every child. + registry for every child. There is no ``limit``: the number is reported + for display, not enforced against. """ - report = budget.report() - return {"limit": report.limit, "spent": report.spent, "byAgent": dict(report.by_agent)} + report = spend.report() + return {"spent": report.spent, "byAgent": dict(report.by_agent)} async def _deliver_to_loop(loop: CoreLoop, message: str) -> str: @@ -3971,29 +3957,14 @@ async def _deliver_to_loop(loop: CoreLoop, message: str) -> str: return "steered" -def _tree_budget_from(params: dict[str, Any]) -> TreeBudget: - """Build the turn tree's shared token limit from the request. +def _tree_spend() -> TreeSpend: + """One accounting object for the turn tree's spend. - Same ``budgetTokens`` the parent run uses, because a host that asks for a - limit means the turn — not "each loop separately". A value that is not a - positive integer is a request error, not a silent zero budget. + Always present, because the number is for display: a host showing "this + turn cost N tokens, of which the children spent M" needs the counter to + exist on every delegating turn, not only on turns that asked for a limit. """ - raw = params.get("budgetTokens") - try: - limit = int(raw) - except (TypeError, ValueError) as exc: - raise JsonRpcError( - "budgetTokens must be a positive integer", - code=-32602, - kind="invalid_params", - ) from exc - if limit <= 0: - raise JsonRpcError( - "budgetTokens must be a positive integer", - code=-32602, - kind="invalid_params", - ) - return TreeBudget(limit=limit) + return TreeSpend() def _build_loop_config(params: dict[str, Any]) -> LoopConfig: diff --git a/packages/sidecar/py/tests/test_e2e_tree_usage.py b/packages/sidecar/py/tests/test_e2e_tree_usage.py index 4cf928fa..d150784a 100644 --- a/packages/sidecar/py/tests/test_e2e_tree_usage.py +++ b/packages/sidecar/py/tests/test_e2e_tree_usage.py @@ -1,16 +1,17 @@ """E2E: `stream.done` reports the whole turn tree's token spend. -Layer choice: the tree budget is assembled inside the sidecar process (the -request's ``budgetTokens`` becomes one counter shared by the parent and every -child), so the honest observation point is the wire of a real -``python -m steerable_sidecar``. +Layer choice: the tree counter is assembled inside the sidecar process (one +per turn, shared by the parent and every child), so the honest observation +point is the wire of a real ``python -m steerable_sidecar``. What is proven through the real process: -- without ``budgetTokens`` there is no ``treeUsage`` at all — a host must be - able to tell "no limit" from "zero spent"; -- with it, ``stream.done`` carries the limit and the spend, attributed to the - parent, so a host can show the turn's real cost without walking the registry. +- every turn carries ``treeUsage`` with the spend attributed to the parent, so + a host can show the turn's real cost without walking the registry; +- there is no limit in the object, and none is enforced: a turn that spends a + lot is reported, not stopped. This used to be gated on the request's + ``budgetTokens``; the gate is gone because stopping a task partway through + costs the work already done. """ from __future__ import annotations @@ -24,7 +25,7 @@ def _greeting(_body: dict[str, Any], _index: int) -> list[dict[str, Any]]: """One short answer with a token bill attached. - The bill matters here: without one the tree has nothing to charge and + The bill matters here: without one the tree has nothing to record and `spent > 0` would be unprovable rather than wrong. """ return [ @@ -59,7 +60,7 @@ async def _run_turn( ) -async def test_stream_done_omits_tree_usage_without_budget_tokens( +async def test_stream_done_reports_the_tree_spend( e2e_gate: None, sidecar_factory: Any, mock_openai: Any ) -> None: mock = mock_openai(_greeting) @@ -69,38 +70,39 @@ async def test_stream_done_omits_tree_usage_without_budget_tokens( assert done["ok"] is True assert done["status"] == "completed" - # No limit was asked for, so there is nothing to report. A zeroed object - # here would read as "spent nothing", a different claim from "no budget". - assert "treeUsage" not in done + tree = done["treeUsage"] + # The parent's own request is recorded, so the spend is non-zero and + # attributed to the parent agent. + assert tree["spent"] > 0 + assert tree["byAgent"].get("parent", 0) > 0 -async def test_stream_done_reports_the_tree_limit_and_spend( +async def test_tree_usage_carries_no_limit( e2e_gate: None, sidecar_factory: Any, mock_openai: Any ) -> None: + """The number is for display; a limit field would imply enforcement. + + ``budgetTokens`` may still be present in the request (it bounds the single + run, a separate mechanism), but it must not surface as a tree-level cap — + nothing compares the spend against it. + """ mock = mock_openai(_greeting) client = await sidecar_factory() - done = await _run_turn(client, mock, budgetTokens=100_000) + done = await _run_turn(client, mock) - assert done["status"] == "completed" - tree = done["treeUsage"] - assert tree["limit"] == 100_000 - # The parent's own request is charged, so the spend is non-zero and - # attributed to the parent agent. - assert tree["spent"] > 0 - assert tree["byAgent"].get("parent", 0) > 0 + assert "limit" not in done["treeUsage"] -async def test_tree_usage_is_json_and_within_its_own_limit( +async def test_tree_usage_is_json( e2e_gate: None, sidecar_factory: Any, mock_openai: Any ) -> None: mock = mock_openai(_greeting) client = await sidecar_factory() - done = await _run_turn(client, mock, budgetTokens=100_000) + done = await _run_turn(client, mock) tree = done["treeUsage"] # It crossed the wire, so it is JSON by construction; assert it survives a # round trip unchanged rather than merely being serialisable. assert json.loads(json.dumps(tree)) == tree - assert tree["spent"] <= tree["limit"] diff --git a/packages/sidecar/py/tests/test_sidecar_coreloop.py b/packages/sidecar/py/tests/test_sidecar_coreloop.py index 80c0b361..5c570071 100644 --- a/packages/sidecar/py/tests/test_sidecar_coreloop.py +++ b/packages/sidecar/py/tests/test_sidecar_coreloop.py @@ -579,12 +579,12 @@ async def test_done_reports_unknown_children_even_when_none_billed() -> None: @pytest.mark.asyncio -async def test_done_carries_the_tree_budget_report_when_one_exists() -> None: - """`treeUsage` is the whole tree's spend; absent means "no limit asked for".""" - from steerable_agent_runtime import TreeBudget +async def test_done_carries_the_tree_spend_report() -> None: + """`treeUsage` is the whole tree's spend, attributed per agent; no limit.""" + from steerable_agent_runtime import TreeSpend - budget = TreeBudget(limit=5000) - budget.charge(LLMUsage(prompt_tokens=700, completion_tokens=0, total_tokens=700), agent="0.1") + spend = TreeSpend() + spend.record(LLMUsage(prompt_tokens=700, completion_tokens=0, total_tokens=700), agent="0.1") transport = _RecordingTransport() await Sidecar._emit_loop_event( @@ -594,13 +594,12 @@ async def test_done_carries_the_tree_budget_report_when_one_exists() -> None: "trace-1", model="fake", tree_report=lambda: { - "limit": budget.report().limit, - "spent": budget.report().spent, - "byAgent": budget.report().by_agent, + "spent": spend.report().spent, + "byAgent": spend.report().by_agent, }, ) tree = transport.events[0][1]["treeUsage"] - assert tree["limit"] == 5000 + assert "limit" not in tree assert tree["spent"] == 700 assert tree["byAgent"] == {"0.1": 700} diff --git a/uv.lock b/uv.lock index e1b650fc..be287f45 100644 --- a/uv.lock +++ b/uv.lock @@ -1714,7 +1714,7 @@ wheels = [ [[package]] name = "steerable-agent-harness" -version = "0.12.0" +version = "0.12.1" source = { editable = "packages/agent-harness/py" } dependencies = [ { name = "pydantic" }, @@ -1729,7 +1729,7 @@ requires-dist = [ [[package]] name = "steerable-agent-protocol" -version = "0.12.0" +version = "0.12.1" source = { editable = "packages/agent-protocol/py" } dependencies = [ { name = "pydantic" }, @@ -1740,7 +1740,7 @@ requires-dist = [{ name = "pydantic", specifier = ">=2.10.0" }] [[package]] name = "steerable-agent-runtime" -version = "0.12.0" +version = "0.12.1" source = { editable = "packages/agent-runtime/py" } dependencies = [ { name = "httpx", extra = ["socks"] }, @@ -1869,7 +1869,7 @@ dev = [ [[package]] name = "steerable-plugin-sdk" -version = "0.12.0" +version = "0.12.1" source = { editable = "packages/plugin-sdk/py" } dependencies = [ { name = "steerable-agent-harness" }, @@ -1884,7 +1884,7 @@ requires-dist = [ [[package]] name = "steerable-sidecar" -version = "0.12.0" +version = "0.12.1" source = { editable = "packages/sidecar/py" } dependencies = [ { name = "ag-ui-protocol" },