diff --git a/DECISIONS.md b/DECISIONS.md index 2b633096..8082c305 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -20436,3 +20436,34 @@ nothing until it is signed by `start_autonomy`; deleting a job stops runs. **Rejected:** a separate permission for editing jobs (one switch is what the owner's list names); comparing a pause's other fields with the stored job (it would need the store in the pure policy table). + +## 2026-11-23 — TD-5299: background delegates, scoped to the turn (Class B) + +**Decision:** `delegate` gains `background` and `label`. A background +child is a `WorkerJob` on the parent session (`worker_jobs.py`), run as a +task through the same `run_child_task` as a foreground child. The loop +puts each settled worker's note in at the tool-batch boundary a steer +joins, and at turn end waits (no model call) while a worker is alive or +its note is owed. `_emit_turn_complete` stops any worker still alive, so +none outlives its turn. Two events (`worker_jobs`, `worker_result`), one +client verb (`worker_stop`, open to a phone since it only stops), and two +Class A builtins (`delegate_output`, `delegate_stop`). Defaults: +`max_running` 2, `max_per_turn` 8, `max_iterations` 24, `max_minutes` 30, +`max_usd` 5.0 and never more than a `max_running` share of what the spend +cap has left. + +**Rationale:** scoping to the turn keeps approvals, caps, Stop and the +session state machine as they are (owner decision row 17). This revises +two records on purpose. TD-4602 rejected timeline events for child steps: +a background call's `tool_result` returns at spawn, so the transcript +needs `worker_result` to ride on. TD-5195 rejected a model fan-out with +`delegate`: the shared limit, forced worktrees, prefixed call ids and Stop +answer each fault it listed. A background worker honours the session caps +even under skip-all, which is stricter than a foreground child, because it +is the closest an interactive session comes to an unattended run. + +**Rejected:** workers that outlive the turn (design 4.8, later); refusing +at capacity instead of queueing (a small model handles "it starts when a +slot frees" better than "try again"); starting a writer from the latest +checkpoint instead of `HEAD` (it would need the checkpoint code reviewed; +the spawn note says uncommitted edits are not in the child's worktree). diff --git a/core/scripts/generate_protocol_fixtures.py b/core/scripts/generate_protocol_fixtures.py index f7101754..c10c350a 100644 --- a/core/scripts/generate_protocol_fixtures.py +++ b/core/scripts/generate_protocol_fixtures.py @@ -319,7 +319,11 @@ ValidateApiKey, VerifyResult, VerifyStarted, + WorkerJobInfo, + WorkerJobs, + WorkerResult, WorkerStep, + WorkerStop, WorktreeState, build_hello_ack, build_pair_ok, @@ -670,6 +674,7 @@ "dismiss_schedule_proposal": DismissScheduleProposal( session_id="sess-1", proposal_id="sp_0123456789ab" ), + "worker_stop": WorkerStop(session_id="sess-1", worker_id="w-1"), # What a paired phone may change (TD-5279): on for an hour. "set_phone_permission": SetPhonePermission( capability="mcp_servers", enabled=True, expires_in_seconds=3600 @@ -1638,6 +1643,35 @@ "schedule_proposal_decision": ScheduleProposalDecision( session_id="sess-1", seq=8, proposal_id="sp_0123456789ab", decision="saved", job_id="job-1" ), + # A background worker running and one settled (TD-5299). + "worker_jobs": WorkerJobs( + session_id="sess-1", + seq=9, + workers=[ + WorkerJobInfo( + worker_id="w-1", + label="fix the date parser", + kind="worker", + task="Fix the date parser and run its tests.", + state="running", + calls=3, + cost_usd=0.0123, + started_at=1795400000.0, + branch="tst/child-1", + worktree_path="/work/.worktrees/child-1", + last_step="pytest tests/test_dates.py", + ) + ], + ), + "worker_result": WorkerResult( + session_id="sess-1", + seq=10, + worker_id="w-1", + state="done", + summary="Fixed the parser; 12 tests pass.", + transcript=[WorkerStep(kind="reply", text="Fixed the parser; 12 tests pass.")], + branch="tst/child-1", + ), "phone_change": PhoneChange( device_name="Pixel", capability="mcp_servers", diff --git a/core/tests/test_delegate_background.py b/core/tests/test_delegate_background.py new file mode 100644 index 00000000..eeb7f2a3 --- /dev/null +++ b/core/tests/test_delegate_background.py @@ -0,0 +1,315 @@ +"""TD-5299: ``delegate`` in the background, scoped to the turn. + +The call returns before the child's first model call; the parent keeps +working; a settled worker's summary reaches the parent model as a note; +the turn does not end while a worker is alive. Stop ends every worker, +``delegate_stop`` one. A writer always gets its own worktree. Each worker +has its own ceilings and honours the session's caps even under skip-all. +""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from tests.test_classifier import WS, boundary, classify, fired_as, req +from tests.test_delegate import _parent_dispatcher, _workspace +from tests.test_dispatch import make_config, start_loop, wait_for_turn +from tests.test_workflow import _parent, _Provider, _repo_parent, _task_of, _text +from tests.test_worktree import git +from tstd.autonomy import DecisionClass +from tstd.config import DelegateBackgroundConfig +from tstd.mock import MockProvider, Script +from tstd.protocol import ToolResult as ToolResultEvent +from tstd.protocol import WorkerJobInfo, WorkerJobs, WorkerResult +from tstd.provider import ChatCompletionRequest +from tstd.router import TierRouter +from tstd.session import Session +from tstd.tools.delegate import handle_delegate +from tstd.tools.delegate_background import delegate_output, delegate_stop +from tstd.tools.results import HandlerRefusal +from tstd.worker_restore import restore_workers + + +def _settings(parent: Session, **over: object) -> None: + runtime = parent.delegate_runtime + assert runtime is not None + runtime.config.delegate.background = DelegateBackgroundConfig(**over) # type: ignore[attr-defined] + + +async def _settled(parent: Session, n: int = 1, within: float = 5.0) -> None: + async def done() -> None: + while sum(1 for j in parent.workers.all() if not j.live) < n: + await parent.workers.wait_change() + + await asyncio.wait_for(done(), within) + + +async def _bg(parent: Session, task: str, **kw: object) -> str: + out = await handle_delegate( + parent, task=task, background=True, tool_call_id=f"c-{task[:6]}", **kw + ) + return out.text + + +async def test_it_returns_before_the_child_runs_and_its_note_is_owed(tmp_path: Path) -> None: + hold = asyncio.Event() + provider = _Provider(lambda _r: _text("Read it: hello."), hold=hold) + parent = _parent(_workspace(tmp_path), provider) + text = await _bg(parent, "read notes.md", kind="research", label="read the notes") + assert text.startswith("Started worker w-1 (read the notes).") + assert "reads your files as they are" in text + [job] = parent.workers.all() + assert job.live and provider.finished == [] + assert parent.workers.owed() + hold.set() + await _settled(parent) + assert job.state == "done" and "hello" in job.summary + [note] = parent.workers.take_notes() + assert note.startswith("[Worker w-1 (read the notes) finished.") + assert not parent.workers.owed() + results = [e for e in parent.event_log.all_events if isinstance(e, WorkerResult)] + assert [r.worker_id for r in results] == ["w-1"] and results[0].transcript + assert any(isinstance(e, WorkerJobs) for e in parent.event_log.all_events) + + +async def test_more_than_max_running_wait_in_a_queue(tmp_path: Path) -> None: + hold = asyncio.Event() + provider = _Provider(lambda _r: _text("done"), hold=hold) + parent = _parent(_workspace(tmp_path), provider) + _settings(parent, max_running=1) + await _bg(parent, "first look", kind="research") + await _bg(parent, "second look", kind="research") + await asyncio.sleep(0.05) + states = [j.state for j in parent.workers.all()] + assert states == ["running", "queued"] + hold.set() + await _settled(parent, 2) + assert [j.state for j in parent.workers.all()] == ["done", "done"] + + +async def test_delegate_stop_ends_one_and_its_sibling_runs_on(tmp_path: Path) -> None: + gate = asyncio.Event() + + def answer(request: ChatCompletionRequest) -> Script: + return _text("first done" if "first" in _task_of(request) else "second done") + + provider = _Provider(answer, hold=gate) + parent = _parent(_workspace(tmp_path), provider) + await _bg(parent, "first look", kind="research") + await _bg(parent, "second look", kind="research") + await asyncio.sleep(0.05) + out = await delegate_stop(session=parent, worker_id="w-1") + assert "w-1" in out and "stopped" in out + gate.set() + await _settled(parent, 2) + first, second = parent.workers.all() + assert (first.state, second.state) == ("stopped", "done") + with pytest.raises(HandlerRefusal) as refused: + await delegate_stop(session=parent, worker_id="w-1") + assert refused.value.code == "worker_not_found" + listed = await delegate_output(session=parent) + assert "w-1" in listed and "w-2" in listed + + +async def test_nobody_watching_and_too_many_are_refused(tmp_path: Path) -> None: + provider = _Provider(lambda _r: _text("x")) + parent = _parent(_workspace(tmp_path), provider) + for attribute in ("autonomy", "scheduled_run"): + setattr(parent, attribute, True) + with pytest.raises(HandlerRefusal) as refused: + await _bg(parent, "look", kind="research") + assert refused.value.code == "delegate_background_unattended" + assert "foreground" in refused.value.message + setattr(parent, attribute, False) + parent.run_permissions = SimpleNamespace(on_ask="deny_and_continue") # type: ignore[assignment] + with pytest.raises(HandlerRefusal): + await _bg(parent, "look", kind="research") + parent.run_permissions = None + _settings(parent, max_per_turn=1) + await _bg(parent, "look", kind="research") + with pytest.raises(HandlerRefusal) as limit: + await _bg(parent, "again", kind="research") + assert limit.value.code == "delegate_background_limit" + parent.workers.begin_turn() + await _bg(parent, "next turn", kind="research") + await _settled(parent, 2) + + +async def test_a_child_cannot_start_or_read_workers(tmp_path: Path) -> None: + provider = _Provider(lambda _r: _text("x")) + parent = _parent(_workspace(tmp_path), provider) + parent.delegate_depth = 1 + with pytest.raises(HandlerRefusal) as refused: + await _bg(parent, "look", kind="research") + assert refused.value.code == "delegate_nested" + + +def _writer(request: ChatCompletionRequest) -> Script: + if request.messages[-1].role == "tool": + return _text("Wrote it.") + return Script( + kind="tool_call", + tool_name="fs_write", + tool_arguments=json.dumps({"path": "a.txt", "content": "a body\n"}), + ) + + +async def test_a_writer_always_gets_its_own_worktree(tmp_path: Path) -> None: + provider = _Provider(_writer) + repo, parent = _repo_parent(tmp_path, provider) + text = await _bg(parent, "write a.txt") + assert "its own worktree on branch" in text + await _settled(parent) + [job] = parent.workers.all() + assert job.state == "done" and job.branch is not None + assert not (repo / "a.txt").exists() + assert git(repo, "show", f"{job.branch}:a.txt") == "a body\n" + + +async def test_a_writer_where_there_can_be_no_worktree_is_told_to_run_in_front( + tmp_path: Path, +) -> None: + provider = _Provider(_writer) + parent = _parent(_workspace(tmp_path), provider) + with pytest.raises(HandlerRefusal) as refused: + await _bg(parent, "write a.txt") + assert "foreground" in refused.value.message + assert parent.workers.all() == [] + + +def _busy(_request: ChatCompletionRequest) -> Script: + return Script(kind="tool_call", tool_name="fs_list", tool_arguments=json.dumps({"path": "."})) + + +async def test_a_worker_stops_at_its_own_call_ceiling(tmp_path: Path) -> None: + parent = _parent(_workspace(tmp_path), _Provider(_busy)) + _settings(parent, max_iterations=2) + await _bg(parent, "keep listing", kind="research") + await _settled(parent) + [job] = parent.workers.all() + assert job.state == "stopped" and "delegate.background.max_iterations" in (job.stopped or "") + assert job.calls == 2 + + +async def test_under_skip_all_a_worker_still_honours_the_session_caps(tmp_path: Path) -> None: + dispatcher = _parent_dispatcher(_workspace(tmp_path)) + dispatcher.skip_all_fn = lambda: True + parent = _parent( + Path(dispatcher.workspace or tmp_path), _Provider(_busy), dispatcher=dispatcher + ) + parent.boundary_config.caps.max_iterations = 2 + await _bg(parent, "keep listing", kind="research") + await _settled(parent) + [job] = parent.workers.all() + assert job.state == "stopped" and "iteration" in (job.stopped or "") + + +async def test_a_restart_interrupts_live_workers_once(tmp_path: Path) -> None: + session = Session(str(tmp_path)) + running = WorkerJobInfo( + worker_id="w-3", + label="fix it", + kind="worker", + task="fix it", + state="running", + started_at=1.0, + ) + done = running.model_copy(update={"worker_id": "w-2", "state": "done"}) + events = [WorkerJobs(session_id="s", workers=[done, running], seq=1)] + assert await restore_workers(session, events) == 1 + states = {j.id: j.state for j in session.workers.all()} + assert states == {"w-2": "done", "w-3": "interrupted"} + [note] = session.workers.take_notes() + assert "w-3" in note and "interrupted by a restart" in note + new = session.workers.new(call_id="c", label="", kind="research", task="t", agent=None) + assert new.id == "w-4" + + +def test_the_read_and_stop_tools_are_class_a_only_as_builtins() -> None: + for name in ("delegate_output", "delegate_stop"): + decision = classify(boundary(), req(tool_name=name)) + assert decision.decision_class is DecisionClass.A and fired_as(decision, "delegate-job") + for no_grant in ( + req(tool_name=name, provenance="mcp:srv"), + req(tool_name=name, reads=(WS / "a",)), + req(tool_name=name, is_mutation=True), + ): + assert not fired_as(classify(boundary(), no_grant), "delegate-job") + + +class _SlowWorker(MockProvider): + """The child answers only after the parent's next reply is in.""" + + async def chat_completion(self, request: ChatCompletionRequest): # type: ignore[no-untyped-def] + if request.model == "test-worker": + await asyncio.sleep(0.4) + return await super().chat_completion(request) + + +async def test_the_turn_waits_for_its_worker_and_hears_the_note(tmp_path: Path) -> None: + """Through the real loop: the parent ends its reply with a worker alive; + the turn stays open, the note arrives, the model answers, then it ends.""" + ws = _workspace(tmp_path) + session = Session(str(ws)) + dispatcher = _parent_dispatcher(ws) + mock = _SlowWorker( + sequences={ + "test-brain": [ + Script( + kind="tool_call", + tool_name="delegate", + tool_arguments=json.dumps( + {"task": "Read notes.md", "kind": "research", "background": True} + ), + ), + Script(kind="stream", content="Started it; waiting."), + Script(kind="stream", content="The worker says hello."), + ], + "test-worker": [Script(kind="text", content="notes.md says hello from notes.")], + } + ) + runner = await start_loop( + session, + TierRouter(), + mock, + make_config(), + registry=dispatcher.registry, + dispatcher=dispatcher, + ) + try: + await session.add_user_message("Look in the background") + await wait_for_turn(session, 1, _timeout=8.0) + finally: + await runner.cancel() + # The parent was called again after its "waiting" reply, with the note + # last. The router picks that call's tier, as for any message. + parent_calls = [c for c in mock.calls if "Read notes.md" not in str(c.messages[1].content)] + assert len(parent_calls) == 3 + last = parent_calls[-1].messages[-1] + assert last.role == "user" and "[Worker w-1" in str(last.content) + assert "hello from notes" in str(last.content) + replies = [m.content for m in parent_calls[-1].messages if m.role == "assistant"] + assert "Started it; waiting." in replies + results = [e for e in session.event_log.all_events if isinstance(e, ToolResultEvent)] + assert "Started worker w-1" in results[0].output + assert [j.state for j in session.workers.all()] == ["done"] + + +async def test_stop_ends_every_worker_and_leaves_no_worktree_folder(tmp_path: Path) -> None: + hold = asyncio.Event() + provider = _Provider(_writer, hold=hold) + repo, parent = _repo_parent(tmp_path, provider) + await _bg(parent, "write a.txt") + await asyncio.sleep(0.05) + [job] = parent.workers.all() + folder = Path(job.worktree_path or "") + assert await asyncio.to_thread(folder.is_dir) + await parent.workers.stop_all("the turn was stopped") + assert job.state == "stopped" and job.stopped == "the turn was stopped" + assert not await asyncio.to_thread(folder.exists) + assert len(git(repo, "worktree", "list").splitlines()) == 1 diff --git a/core/tests/test_plan_mode.py b/core/tests/test_plan_mode.py index c5523140..6088590c 100644 --- a/core/tests/test_plan_mode.py +++ b/core/tests/test_plan_mode.py @@ -169,6 +169,9 @@ def test_every_builtin_is_decided_and_only_readers_run() -> None: "ask_user", "browser_screenshot", "consult", + # TD-5299: a background worker's record, and ending one. + "delegate_output", + "delegate_stop", "desktop_screenshot", "exit_plan_mode", "fs_grep", diff --git a/core/tstd/autonomy/classifier.py b/core/tstd/autonomy/classifier.py index f7bf02ff..bc9d08dc 100644 --- a/core/tstd/autonomy/classifier.py +++ b/core/tstd/autonomy/classifier.py @@ -768,6 +768,9 @@ class default only when no rule matches. # TD-5137: reads a background job's buffer. ``shell_job_stop`` is not # here: it kills a process, and planning changes nothing. "shell_job_output", + # TD-5299: a background worker's record; stopping one ends work, too. + "delegate_output", + "delegate_stop", } | LSP_READ_TOOLS | GITHUB_READ_TOOLS @@ -1003,6 +1006,26 @@ def _rule_session_search(req: DecisionRequest, _boundary: Boundary) -> bool: ) +def _rule_delegate_job(req: DecisionRequest, _boundary: Boundary) -> bool: + """``delegate_output`` / ``delegate_stop`` on the session's own workers (TD-5299). + + The worker was started by a ``delegate`` call that was classified like + any other: reading it reads the daemon's record, and stopping it ends + only work this session started. No path, host or write. Only the + builtins match. + """ + return ( + req.tool_name in ("delegate_output", "delegate_stop") + and req.provenance is None + and req.side_effect_class == "auto" + and req.actuates is None + and not req.is_mutation + and not req.reads + and not req.writes + and not req.hosts + ) + + def _rule_shell_job(req: DecisionRequest, _boundary: Boundary) -> bool: """``shell_job_output`` / ``shell_job_stop`` on the session's own jobs (TD-5137). @@ -1340,6 +1363,12 @@ def _rule_outside_writable(req: DecisionRequest, boundary: Boundary) -> bool: decision_class=DecisionClass.A, match=_rule_session_search, ), + Rule( + id="delegate-job", + description="delegate_output and delegate_stop touch only this session's own workers", + decision_class=DecisionClass.A, + match=_rule_delegate_job, + ), Rule( id="shell-job", description="shell_job_output and shell_job_stop touch only this session's own jobs", diff --git a/core/tstd/config.py b/core/tstd/config.py index 48a9f125..89b61469 100644 --- a/core/tstd/config.py +++ b/core/tstd/config.py @@ -926,6 +926,24 @@ class CompactionConfig(BaseModel): DEFAULT_CHILD_MAX_ITERATIONS = 8 +class DelegateBackgroundConfig(BaseModel): + """Limits for a ``delegate`` child started with ``background: true`` (TD-5299). + + A background worker belongs to its turn: the turn waits for it. Each + worker has its own call, time and spend ceiling, and always honours + the session's caps, skip-all or not. ``max_running`` is how many run at + once in one session; more wait their turn in a queue. + """ + + model_config = ConfigDict(extra="forbid") + + max_running: int = Field(default=2, ge=1, le=8) + max_per_turn: int = Field(default=8, ge=1, le=32) + max_iterations: int = Field(default=24, ge=1, le=64) + max_minutes: int = Field(default=30, ge=1, le=240) + max_usd: float = Field(default=5.0, gt=0) + + class DelegateConfig(BaseModel): """Limits for a ``delegate`` child (TD-5265). @@ -939,6 +957,7 @@ class DelegateConfig(BaseModel): model_config = ConfigDict(extra="forbid") max_iterations: int = Field(default=DEFAULT_CHILD_MAX_ITERATIONS, ge=1, le=64) + background: DelegateBackgroundConfig = Field(default_factory=DelegateBackgroundConfig) def _default_consult_tiers() -> list[TierName]: diff --git a/core/tstd/config.yaml b/core/tstd/config.yaml index 518bd024..250d8eae 100644 --- a/core/tstd/config.yaml +++ b/core/tstd/config.yaml @@ -227,6 +227,14 @@ consult: # caps, so a larger number here cannot outrun them. delegate: max_iterations: 8 + # A worker started with background: true (TD-5299). The turn waits for + # it; it stops at its own limits and always honours the session's caps. + background: + max_running: 2 # at once per session; more wait in a queue + max_per_turn: 8 + max_iterations: 24 + max_minutes: 30 + max_usd: 5.0 # and never more than its share of what the session cap leaves # How many calls one model server answers at once, across every chat, # worker and scheduled run (TD-5269). null is no limit. A model served on diff --git a/core/tstd/config_help.py b/core/tstd/config_help.py index c23d3eab..502331b2 100644 --- a/core/tstd/config_help.py +++ b/core/tstd/config_help.py @@ -73,6 +73,17 @@ "ModelConfig.model_concurrency": "How many calls one model server answers at once, " "across every chat, worker and scheduled run.", "ModelConfig.delegate": "Limits for a child the agent delegates part of a task to.", + "DelegateConfig.background": ( + "Limits for a child started in the background. The turn waits for it." + ), + "DelegateBackgroundConfig.max_running": "Background children running at once in a chat.", + "DelegateBackgroundConfig.max_per_turn": "Background children one turn may start.", + "DelegateBackgroundConfig.max_iterations": "Model calls one background child may make.", + "DelegateBackgroundConfig.max_minutes": "Minutes one background child may run.", + "DelegateBackgroundConfig.max_usd": ( + "Dollars one background child may spend, and never more than its share of " + "what the spend cap leaves." + ), "ModelConfig.search": "Where web_search sends queries, and how web_fetch reads pages.", "ModelConfig.local_servers": "Model servers on this computer that Add a model's search " "asks for their models. Loopback only; no key is sent.", diff --git a/core/tstd/daemon.py b/core/tstd/daemon.py index 1c56e9aa..f6928b30 100644 --- a/core/tstd/daemon.py +++ b/core/tstd/daemon.py @@ -473,6 +473,7 @@ UserTurn, ValidateApiKey, VerifyResult, + WorkerStop, build_error, parse_client_message, scrub_wire_json, @@ -619,6 +620,7 @@ transcribe_audio, voice_has_endpoint, ) +from .worker_restore import restore_workers from .workspace_pins import load_workspace_pins, save_workspace_pins from .workspace_trust import ( TrustStore, @@ -4465,6 +4467,19 @@ async def _not_asked(_urls: list[str]) -> dict[str, bool]: if isinstance(msg, SaveJob): return await self._handle_save_job(msg) + if isinstance(msg, WorkerStop): + found = self.session_registry.get(msg.session_id) + if found is None or not await found.workers.stop( + msg.worker_id, "stopped from the window" + ): + return build_error( + "worker_not_found", + "That worker is not running.", + session_id=msg.session_id, + in_reply_to=msg.type, + ) + return None + if isinstance(msg, DismissScheduleProposal): found = self.session_registry.get(msg.session_id) if found is None or await settle_schedule(found, msg.proposal_id, "dismissed") is None: @@ -5008,6 +5023,8 @@ async def _revive_session( await expire_restored_schedule(sess, loaded.events) # TD-5137: so did its background shell jobs. await sess.shell_jobs.expire_restored(loaded.events) + # TD-5299: and its background workers. + await restore_workers(sess, loaded.events) await self._seal_cut_review(sess, loaded.events) await self._emit_working_context(sess, config_source(sess), unless_logged=True) log.info( diff --git a/core/tstd/loop.py b/core/tstd/loop.py index 958ec520..088dfe35 100644 --- a/core/tstd/loop.py +++ b/core/tstd/loop.py @@ -174,6 +174,7 @@ from .tools.delegate_named import with_named_workers, with_worker_mentions from .tools.dispatch import build_decision_request, canonicalize_path_fields from .tools.tool_search import TOOL_SEARCH_NAME +from .worker_turn import inject_worker_notes, owes_the_turn, wait_for_workers from .workspace_trust import trusted_imports from .worktree_config import config_home, refresh_config @@ -608,9 +609,13 @@ async def _emit_turn_complete( ) -> None: """Emit a ``turn_complete`` event with cost and duration. + TD-5299: no background worker outlives its turn; any still alive here + (the turn failed or paused out) is stopped first. + ``failed``/``error_code`` make a failed turn machine-visible so the UI can key tailored copy off the provider's typed code (TD-1008). """ + await session.workers.stop_all("the turn ended") duration = time.time() - turn_start await session.event_log.add( TurnComplete( @@ -1961,7 +1966,11 @@ def _read_tool_definitions() -> None: return tools_version = tool_registry.version # A child cannot delegate or run a workflow (TD-5195): one level only. - unusable = {"delegate", "workflow"} if session.delegate_depth >= 1 else set() + unusable = ( + {"delegate", "workflow", "delegate_output", "delegate_stop"} + if session.delegate_depth >= 1 + else set() + ) if tool_dispatcher is None or not tool_dispatcher.has_handler(TOOL_SEARCH_NAME): unusable.add(TOOL_SEARCH_NAME) all_tool_definitions = [ @@ -2104,6 +2113,9 @@ def counter_for(tier_cfg: TierConfig) -> CalibratedTokenCounter: # TD-5112: a message sent from here to turn_complete joins this # turn at its next tool-batch boundary. session.open_steering(queued.id) + # TD-5299: a fresh count of background workers for this turn. + session.workers.begin_turn() + session.steer_arrived.clear() # TD-5134: user_prompt hooks see the message before anything acts # on it; a block keeps it out of the conversation. if session.config is not None: @@ -2674,6 +2686,9 @@ def counter_for(tier_cfg: TierConfig) -> CalibratedTokenCounter: claude_global_fallback=config.steering.claude_global_fallback, ) last_batch = [] + session.steer_arrived.clear() + # TD-5299: a background worker that settled meanwhile. + steered += await inject_worker_notes(session, messages) if session.loaded_skills != skills_before: # A /skill in the steer: the prompt was assembled at # 2b, before it loaded, so the call that reads the @@ -3008,6 +3023,26 @@ def counter_for(tier_cfg: TierConfig) -> CalibratedTokenCounter: # 2h. No tool calls (or no dispatcher): the model ended the # turn. The done-check may send it back to work (TD-5124). + # TD-5299: not while a background worker is alive or its + # note is owed. Wait for it with no model call, then go on. + if owes_the_turn(session): + await wait_for_workers(session) + if session.cancel_requested: + break + if session.stop_turn_requested: + await _finish_stopped_turn(session, tier, turn_start, tracker) + break + session.steer_arrived.clear() + joined = await inject_steers( + session, + messages, + step=turn_step, + after_tool_call_ids=[], + claude_global_fallback=config.steering.claude_global_fallback, + ) + joined += await inject_worker_notes(session, messages) + if joined: + continue checked = await stop_check.at_turn_end(messages) if checked == "retry": continue diff --git a/core/tstd/phone_verbs.py b/core/tstd/phone_verbs.py index f9485a8b..35f4bb91 100644 --- a/core/tstd/phone_verbs.py +++ b/core/tstd/phone_verbs.py @@ -204,6 +204,7 @@ "transcribe", "user_message", "validate_api_key", + "worker_stop", } ) diff --git a/core/tstd/protocol.py b/core/tstd/protocol.py index eed412f1..aa43fad4 100644 --- a/core/tstd/protocol.py +++ b/core/tstd/protocol.py @@ -2057,6 +2057,17 @@ class ListJobTemplates(ClientMessage): type: Literal["list_job_templates"] = "list_job_templates" +class WorkerStop(ClientMessage): + """Stop one background worker of a session (TD-5299). Its siblings run on. + + An id that is not running is ``worker_not_found``. + """ + + type: Literal["worker_stop"] = "worker_stop" + session_id: str + worker_id: str = Field(min_length=1) + + class DismissScheduleProposal(ClientMessage): """Dismiss the agent's schedule proposal; nothing is scheduled (TD-5263). @@ -3164,6 +3175,63 @@ class ShellJobs(DaemonEvent): jobs: list[ShellJobInfo] = Field(default_factory=list, max_length=64) +WorkerState = Literal[ + "queued", "running", "awaiting_approval", "done", "failed", "stopped", "interrupted" +] + + +class WorkerJobInfo(BaseModel): + """One background ``delegate`` worker, as the window lists it (TD-5299). + + A worker belongs to the turn that started it: the turn does not end + while one is alive. ``interrupted`` is set only when a daemon restart + ended it. ``started_at`` and ``ended_at`` are Unix seconds. + """ + + worker_id: str = Field(min_length=1, max_length=16) + label: str = Field(max_length=80) + kind: str + agent: str | None = None + task: str = Field(max_length=300) + state: WorkerState = "queued" + stopped: str | None = None + calls: int = 0 + cost_usd: float = 0.0 + started_at: float + ended_at: float | None = None + branch: str | None = None + worktree_path: str | None = None + last_step: str = Field(default="", max_length=200) + + +class WorkerJobs(DaemonEvent): + """The session's background workers, after any of them changed (TD-5299). + + Each event carries the whole list, so the newest one is the truth. + """ + + type: Literal["worker_jobs"] = "worker_jobs" + session_id: str + workers: list[WorkerJobInfo] = Field(default_factory=list, max_length=64) + + +class WorkerResult(DaemonEvent): + """A background worker settled: its summary and its steps, for the window. + + The parent model is given the summary as a note; the steps never reach + it, as with a foreground ``delegate`` (TD-5299). + """ + + type: Literal["worker_result"] = "worker_result" + session_id: str + worker_id: str + state: WorkerState + summary: str + transcript: list[WorkerStep] = Field(default_factory=list) + branch: str | None = None + stopped: str | None = None + + class WorktreeState(DaemonEvent): """A session's worktree changed (TD-5126): made, set up, or closed. @@ -5337,6 +5405,7 @@ class GoogleStatus(DaemonEvent): | ListJobTemplates | SaveJobTemplate | DismissScheduleProposal + | WorkerStop | DeleteJobTemplate | GetSessionJobSource | Transcribe @@ -5410,6 +5479,8 @@ class GoogleStatus(DaemonEvent): | SteeringProposal | ScheduleProposal | ScheduleProposalDecision + | WorkerJobs + | WorkerResult | SteeringDecision | SessionList | PolicyRules @@ -5608,6 +5679,7 @@ class GoogleStatus(DaemonEvent): "list_job_templates", "save_job_template", "dismiss_schedule_proposal", + "worker_stop", "delete_job_template", "get_session_job_source", "transcribe", @@ -5681,6 +5753,8 @@ class GoogleStatus(DaemonEvent): "steering_proposal", "schedule_proposal", "schedule_proposal_decision", + "worker_jobs", + "worker_result", "steering_decision", "session_list", "policy_rules", diff --git a/core/tstd/session.py b/core/tstd/session.py index 8cbae28d..2c14951f 100644 --- a/core/tstd/session.py +++ b/core/tstd/session.py @@ -42,13 +42,17 @@ ShellJobInfo, TaskListItem, ToolResult, + WorkerJobInfo, + WorkerResult, ) from .protocol import SessionState as SessionStateEvent from .protocol import ShellJobs as ShellJobsEvent +from .protocol import WorkerJobs as WorkerJobsEvent from .provider import ChatMessage from .questions import PendingQuestion, resolve_all from .shell_jobs import ShellJobs from .task_list import follow_branch +from .worker_jobs import WorkerJobs from .workspace_trust import TrustStore, WorkspaceConfigView from .worktree import SessionWorktree @@ -407,6 +411,11 @@ def __init__(self, workspace_path: str) -> None: # TD-5137: background shell jobs. The session owns them, so ending # it (``cancel``) kills them; each change logs ``shell_jobs``. self.shell_jobs = ShellJobs(self._log_shell_jobs) + # TD-5299: background ``delegate`` workers, which belong to the turn + # that started them. Cancel and Stop end them; each change logs + # ``worker_jobs``. ``steer_arrived`` wakes a turn waiting on them. + self.workers = WorkerJobs(self._log_workers, self._log_worker_result) + self.steer_arrived = asyncio.Event() # TD-5124: the goal ``/goal`` set, checked when the model ends a # turn until a check passes; rebuilt from the log on revive. And # how many checks have judged it, for ``/goal`` on its own. @@ -786,12 +795,19 @@ async def cancel(self, reason: str = "cancelled by user") -> None: await self.close_cu_session() # The session ended, so its background jobs end with it (TD-5137). await self.shell_jobs.stop_all() + await self.workers.stop_all("the session was cancelled") # Wake a loop parked in wait_for_resume so it observes cancellation. self._resume_event.set() async def _log_shell_jobs(self, jobs: list[ShellJobInfo]) -> None: await self.event_log.add(ShellJobsEvent(session_id=self.id, jobs=jobs, seq=1)) + async def _log_workers(self, workers: list[WorkerJobInfo]) -> None: + await self.event_log.add(WorkerJobsEvent(session_id=self.id, workers=workers, seq=1)) + + async def _log_worker_result(self, result: WorkerResult) -> None: + await self.event_log.add(result.model_copy(update={"session_id": self.id})) + async def stop_turn(self) -> None: """Abort the in-flight turn. The session and its transcript stay. @@ -957,8 +973,14 @@ async def request_approval( ) if self._state != "awaiting_approval": await self.set_state("awaiting_approval", reason=reason) - - return await self._await_approval_resolution(tool_call_id, fut) + if worker is None: + return await self._await_approval_resolution(tool_call_id, fut) + # TD-5299: a background worker shows as waiting on its card. + await self.workers.asking(worker.id, True) + try: + return await self._await_approval_resolution(tool_call_id, fut) + finally: + await self.workers.asking(worker.id, False) def _approval_sandbox(self, tool_name: str, arguments: dict[str, Any]) -> Any: """What a shell call on this card would run in (TD-5294).""" @@ -1280,6 +1302,7 @@ async def add_user_message( # A message with its own run rules (TD-5118) never steers: the # running turn keeps its own, so the rules would not apply. queued = replace(queued, steer_into=self._steer_turn) + self.steer_arrived.set() self._open_turns += 1 try: async with self._queue_lock: diff --git a/core/tstd/tools/delegate.py b/core/tstd/tools/delegate.py index adbccc11..ffcdd17f 100644 --- a/core/tstd/tools/delegate.py +++ b/core/tstd/tools/delegate.py @@ -29,6 +29,7 @@ import asyncio import contextlib import json +import time import uuid from collections.abc import Awaitable, Callable from dataclasses import dataclass, replace @@ -64,6 +65,7 @@ WORKER_CHILD_TOOLS, DelegateKind, TranscriptRecorder, + WorkerLimits, cap_worker_summary, child_preamble, resolve_kind, @@ -167,6 +169,14 @@ class ChildTask: parent_call_id: str = "" index: int | None = None label: str = "" + # TD-5299: a background worker's worktree (opened at spawn, so a writer + # that cannot have one is refused there), its own ceilings, the list + # its steps go to as it runs, and a callback after each model call + # with that call's cost. + opened: SessionWorktree | None = None + limits: WorkerLimits | None = None + steps: list[WorkerStep] | None = None + progress: Callable[[float], Awaitable[None]] | None = None @dataclass(frozen=True) @@ -207,7 +217,10 @@ def register_delegate_tools(registry: ToolRegistry) -> None: "worktree: true runs the child in its own git worktree from " "the last commit (your uncommitted edits are not in it); " "its changes come back on a branch for you to merge. " - "agent runs a named worker the user defined instead of a kind." + "agent runs a named worker the user defined instead of a kind. " + "background: true starts the child and returns at once so you can keep " + "working; its result arrives as a note when it finishes, and a child " + "that writes gets its own worktree. Use it for slow pieces, not to wait on." ), parameters={ "type": "object", @@ -242,6 +255,18 @@ def register_delegate_tools(registry: ToolRegistry) -> None: "Default false: it works in your files." ), }, + "background": { + "type": "boolean", + "description": ( + "Start the child and return its id at once (TD-5299). Keep " + "working; its result arrives as a note when it finishes." + ), + }, + "label": { + "type": "string", + "maxLength": 60, + "description": "A short name for a background child.", + }, }, "required": ["task"], }, @@ -258,6 +283,12 @@ def register_delegate_handlers(dispatcher: ToolDispatcher) -> None: if dispatcher.registry.get("delegate") is None: raise KeyError("delegate tool must be registered before its handler") dispatcher.register_handler("delegate", handle_delegate) + # TD-5299: imported here, the background module imports this one. + from .delegate_background import delegate_output, delegate_stop + + for name, handler in (("delegate_output", delegate_output), ("delegate_stop", delegate_stop)): + if dispatcher.registry.get(name) is not None: + dispatcher.register_handler(name, handler) def worker_child_registry( @@ -292,21 +323,26 @@ async def handle_delegate( kind: str | None = None, worktree: bool | str = False, agent: str | None = None, + background: bool = False, + label: str = "", tool_call_id: str = "", ) -> HandlerOutput: """``delegate`` handler — run a one-level worker, research or named child.""" parent, _runtime = bound_runtime(session, "delegate") - done = await run_child_task( - parent, - ChildTask( - task=task, - context=context, - kind=kind, - agent=agent, - worktree=worktree, - call_id=tool_call_id, - ), + spec = ChildTask( + task=task, + context=context, + kind=kind, + agent=agent, + worktree=worktree, + call_id=tool_call_id, + label=label, ) + if background: + from .delegate_background import spawn + + return HandlerOutput(text=await spawn(parent, spec)) + done = await run_child_task(parent, spec) return HandlerOutput(text=done.summary, transcript=done.steps) @@ -346,8 +382,12 @@ async def run_child_task(parent: Session, spec: ChildTask) -> ChildDone: worker_tier(runtime.config, named) resolved = resolve_kind(spec.kind, plan_mode=plan_mode) writes = named.writes if named is not None else resolved == "worker" - steps: list[WorkerStep] = [] - own_tree = await open_child_tree(parent, spec.worktree, forced=spec.isolate_writer and writes) + steps: list[WorkerStep] = spec.steps if spec.steps is not None else [] + own_tree = spec.opened + if own_tree is None: + own_tree = await open_child_tree( + parent, spec.worktree, forced=spec.isolate_writer and writes + ) try: end = await _child_loop( parent=parent, @@ -364,6 +404,8 @@ async def run_child_task(parent: Session, spec: ChildTask) -> ChildDone: parent_call_id=spec.parent_call_id, index=spec.index, label=spec.label, + limits=spec.limits, + progress=spec.progress, ) except HandlerRefusal as e: await close_child_tree(own_tree, spec.task, steps) @@ -440,6 +482,8 @@ async def _child_loop( parent_call_id: str = "", index: int | None = None, label: str = "", + limits: WorkerLimits | None = None, + progress: Callable[[float], Awaitable[None]] | None = None, ) -> _ChildEnd: """:func:`run_worker_child`'s loop, also saying why it stopped early.""" parent, runtime = bound_runtime(parent, "delegate") @@ -591,17 +635,24 @@ def stop(why: str) -> _ChildEnd: # call id in front keeps their approvals apart. prefix = call_id or uuid.uuid4().hex[:12] - child_max = runtime.config.delegate.max_iterations + child_max = runtime.config.delegate.max_iterations if limits is None else limits.max_calls + spent = 0.0 for _ in range(child_max): if parent.cancel_requested or parent.stop_turn_requested: return stop( "parent cancelled" if parent.cancel_requested else "parent stopped the turn" ) + if limits is not None: + # TD-5299: a background worker's own ceilings. + if time.monotonic() >= limits.deadline: + return stop("worker time limit (delegate.background.max_minutes)") + if spent >= limits.max_usd: + return stop(f"worker spend ceiling (${limits.max_usd:.2f})") # The count is every child's calls, not this child's alone (TD-5195). used = runtime.iterations + runtime.child_calls - violation = _child_cap_violation( - parent, tracker, runtime.session_start, used, _skip_all(parent_dispatcher) - ) + # A background worker honours every session cap, skip-all or not. + skip_all = limits is None and _skip_all(parent_dispatcher) + violation = _child_cap_violation(parent, tracker, runtime.session_start, used, skip_all) if violation is not None: return stop(violation) runtime.child_calls += 1 @@ -623,9 +674,13 @@ def stop(why: str) -> _ChildEnd: ) if isinstance(resp, ProviderError): return stop(resp.message) + cost = 0.0 if resp.usage is not None: - tracker.record(acting, resp.usage, worker_cfg, source=source) + cost = tracker.record(acting, resp.usage, worker_cfg, source=source) await parent.event_log.add(tracker.emit_cost_update(parent.id)) + spent += cost + if progress is not None: + await progress(cost) tool_calls = resp.message.tool_calls or [] content = resp.message.content or "" @@ -677,7 +732,8 @@ def stop(why: str) -> _ChildEnd: content = _tool_message_content(r) if r.images else r.output messages.append(ChatMessage(role="tool", content=content, tool_call_id=tc.id)) - return stop(f"the child used all {child_max} of its model calls (delegate.max_iterations)") + key = "delegate.max_iterations" if limits is None else "delegate.background.max_iterations" + return stop(f"the child used all {child_max} of its model calls ({key})") def _skip_all(dispatcher: ToolDispatcher) -> bool: diff --git a/core/tstd/tools/delegate_background.py b/core/tstd/tools/delegate_background.py new file mode 100644 index 00000000..fb60bc4e --- /dev/null +++ b/core/tstd/tools/delegate_background.py @@ -0,0 +1,242 @@ +"""``delegate`` in the background, and the tools that read and stop it (TD-5299). + +``delegate`` with ``background: true`` starts the child as a task the +session owns and answers at once. A child that can write always gets its +own worktree, opened here, so the parent can keep editing its own files; +where there can be none the call is refused with a hint to run it in the +foreground. The worker belongs to its turn (``worker_jobs``). + +``delegate_output`` reads a worker's progress and ``delegate_stop`` ends +one. Both touch only the daemon's record of this session's own workers. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import time +from dataclasses import replace + +from ..session import Session +from ..worker_jobs import WorkerJob +from .delegate import ChildTask, bound_runtime, run_child_task +from .delegate_child import WorkerLimits, resolve_kind +from .delegate_named import resolve_named_worker +from .delegate_worktree import close_child_tree, open_child_tree +from .registry import Tool, ToolRegistry +from .results import HandlerRefusal + +DELEGATE_OUTPUT_TOOL = Tool( + name="delegate_output", + description=( + "Read a background worker's progress: its state, calls, spend, last steps and, " + "once it settled, its summary. Omit worker_id to list them all. You do not need " + "to poll: a settled worker's result arrives as a note on its own." + ), + parameters={ + "type": "object", + "properties": { + "worker_id": {"type": "string", "description": "e.g. w-2. Omit for all."}, + "wait_secs": {"type": "integer", "minimum": 0, "maximum": 30}, + }, + "additionalProperties": False, + }, + side_effect_class="auto", + parallel_safe=True, + mutates=False, +) + +DELEGATE_STOP_TOOL = Tool( + name="delegate_stop", + description="Stop one background worker and get back what it had. Others keep running.", + parameters={ + "type": "object", + "properties": {"worker_id": {"type": "string"}}, + "required": ["worker_id"], + "additionalProperties": False, + }, + side_effect_class="auto", + parallel_safe=False, + mutates=False, +) + +_STEPS_SHOWN = 4 +_STEP_CHARS = 500 + + +def register_delegate_job_tools(registry: ToolRegistry) -> None: + registry.register(DELEGATE_OUTPUT_TOOL) + registry.register(DELEGATE_STOP_TOOL) + + +def _unattended(parent: Session) -> bool: + from .ask_user import denies_every_ask + + return parent.autonomy or parent.scheduled_run or denies_every_ask(parent) + + +async def spawn(parent: Session, spec: ChildTask) -> str: + """Start *spec* in the background and say how to follow it.""" + _, runtime = bound_runtime(parent, "delegate") + settings = runtime.config.delegate.background + if _unattended(parent): + raise HandlerRefusal( + "delegate_background_unattended", + "Refused: nobody is watching this run, so a background worker cannot be " + "started. Run it in the foreground (background: false).", + ) + jobs = parent.workers + if jobs.spawned_this_turn >= settings.max_per_turn: + raise HandlerRefusal( + "delegate_background_limit", + f"Refused: this turn already started {settings.max_per_turn} background " + "workers (delegate.background.max_per_turn).", + ) + router = parent.router + plan_mode = router is not None and router.plan_mode + named = None + if spec.agent is not None: + named = await resolve_named_worker( + parent.workspace_path, spec.agent, kind=spec.kind, plan_mode=plan_mode + ) + kind = resolve_kind(spec.kind, plan_mode=plan_mode) + writes = named.writes if named is not None else kind == "worker" + tree = None + if writes: + try: + tree = await open_child_tree(parent, True, forced=True) + except HandlerRefusal as e: + raise HandlerRefusal( + e.code, + f"{e.message} A background worker that writes needs its own worktree; " + "run this one in the foreground (background: false) instead.", + ) from e + job = jobs.new( + call_id=spec.call_id, + label=spec.label, + kind=kind, + task=spec.task, + agent=named.name if named is not None else None, + ) + if tree is not None: + job.branch = tree.branch + job.worktree_path = str(tree.path) + tracker = parent.cost_tracker + spent = tracker.session_cost() if tracker is not None else 0.0 + left = max(0.0, parent.boundary_config.caps.spend_usd - spent) + limits = WorkerLimits( + max_calls=settings.max_iterations, + max_usd=min(settings.max_usd, left / settings.max_running), + deadline=time.monotonic() + settings.max_minutes * 60, + ) + + async def progress(cost: float) -> None: + job.calls += 1 + job.cost_usd += cost + await jobs.changed(job, progress=True) + + ready = replace( + spec, opened=tree, limits=limits, steps=job.steps, progress=progress, isolate_writer=True + ) + job.handle = asyncio.create_task(_run(parent, job, ready, settings.max_running)) + await jobs.changed(job) + where = ( + f" It works in its own worktree on branch {tree.branch}, from your last commit: " + "your uncommitted edits are not in it." + if tree is not None + else " It reads your files as they are, even ones you are halfway through editing." + ) + return ( + f"Started worker {job.id} ({job.label}).{where} Its result will arrive as a note. " + "Read progress with delegate_output; stop it with delegate_stop." + ) + + +async def _run(parent: Session, job: WorkerJob, spec: ChildTask, max_running: int) -> None: + """The worker's task: wait for a slot, run, settle. Never raises.""" + jobs = parent.workers + started = False + try: + while jobs.running_count() >= max_running: + await jobs.wait_change() + job.state = "running" + await jobs.changed(job) + started = True + done = await run_child_task(parent, spec) + job.stopped = done.stopped + if done.branch is None: + job.branch = None + await jobs.settle(job, "stopped" if done.stopped else "done", done.summary) + except asyncio.CancelledError: + # Stop, cancel or delegate_stop. Once started, run_child_task + # settled the worktree; a queued worker's is settled here. + if not started and spec.opened is not None: + await asyncio.shield(close_child_tree(spec.opened, spec.task, job.steps)) + await jobs.settle(job, "stopped", _had(job)) + except HandlerRefusal as e: + await jobs.settle(job, "failed", e.message) + except Exception as e: + if not started and spec.opened is not None: + await close_child_tree(spec.opened, spec.task, job.steps) + await jobs.settle(job, "failed", f"The worker failed: {e}") + + +def _had(job: WorkerJob) -> str: + replies = [s.text for s in job.steps if s.kind == "reply"] + why = job.stopped or "stopped" + return replies[-1] if replies else f"Worker stopped: {why}." + + +def _describe(job: WorkerJob, *, steps: bool) -> str: + head = ( + f"{job.id} ({job.label}): {job.state}" + f"{f' ({job.stopped})' if job.stopped else ''}; " + f"{job.calls} calls, ${job.cost_usd:.4f}" + f"{f'; branch {job.branch}' if job.branch else ''}" + ) + if not steps: + return head + lines = [head] + for step in job.steps[-_STEPS_SHOWN:]: + text = " ".join(step.text.split())[:_STEP_CHARS] + lines.append(f" {step.kind}{f' {step.tool}' if step.tool else ''}: {text}") + if not job.live: + lines.append(f"Summary:\n{job.summary}") + return "\n".join(lines) + + +async def delegate_output( + *, session: object, tool_call_id: str = "", worker_id: str | None = None, wait_secs: int = 0 +) -> str: + """One worker's progress, or the list. Waits up to *wait_secs* for a change.""" + if not isinstance(session, Session): + raise HandlerRefusal("delegate_no_session", "Error: delegate_output requires a session") + jobs = session.workers + if worker_id is None: + listed = [_describe(j, steps=False) for j in jobs.all()] + return "\n".join(listed) if listed else "No background workers in this session." + job = jobs.get(worker_id) + if job is None: + raise HandlerRefusal("worker_not_found", f"There is no worker {worker_id!r}.") + if job.live and wait_secs > 0: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(jobs.wait_change(), timeout=min(wait_secs, 30)) + if not job.live: + # Read here, so the loop does not hand the model the same result again. + job.delivered = True + return _describe(job, steps=True) + + +async def delegate_stop(*, session: object, tool_call_id: str = "", worker_id: str) -> str: + """Stop one worker; its siblings run on.""" + if not isinstance(session, Session): + raise HandlerRefusal("delegate_no_session", "Error: delegate_stop requires a session") + jobs = session.workers + job = jobs.get(worker_id) + if job is None or not await jobs.stop(worker_id, "delegate_stop"): + state = "" if job is None else f" It is already {job.state}." + raise HandlerRefusal( + "worker_not_found", f"There is no running worker {worker_id!r}.{state}" + ) + job.delivered = True + return _describe(job, steps=True) diff --git a/core/tstd/tools/delegate_child.py b/core/tstd/tools/delegate_child.py index eedd1805..1ad6db0f 100644 --- a/core/tstd/tools/delegate_child.py +++ b/core/tstd/tools/delegate_child.py @@ -15,6 +15,7 @@ from __future__ import annotations +from dataclasses import dataclass from typing import Literal from ..context.tokens import HeuristicTokenCounter, TokenCounter @@ -177,3 +178,17 @@ def add( truncated=len(kept) < len(text), ) ) + + +@dataclass(frozen=True) +class WorkerLimits: + """A background worker's own ceilings, fixed at spawn (TD-5299). + + The session's caps still bound it, and are checked even under + skip-all: a background worker is the nearest thing an interactive + session has to an unattended run. + """ + + max_calls: int + max_usd: float + deadline: float # time.monotonic() diff --git a/core/tstd/tools/registry.py b/core/tstd/tools/registry.py index 08786c7f..56b9ca65 100644 --- a/core/tstd/tools/registry.py +++ b/core/tstd/tools/registry.py @@ -696,6 +696,7 @@ def create_registry( from .browser import register_browser_tools from .consult import register_consult_tool from .delegate import register_delegate_tools + from .delegate_background import register_delegate_job_tools from .desktop import register_desktop_tools from .exit_plan import register_exit_plan_tool from .plugins import load_plugins @@ -719,6 +720,7 @@ def create_registry( register_browser_tools(registry, candidate_selection=candidate_selection) register_skill_tools(registry) register_delegate_tools(registry) + register_delegate_job_tools(registry) # TD-5195: always listed; it refuses while Ultracode is off. register_workflow_tool(registry) register_consult_tool(registry) diff --git a/core/tstd/worker_jobs.py b/core/tstd/worker_jobs.py new file mode 100644 index 00000000..cd416254 --- /dev/null +++ b/core/tstd/worker_jobs.py @@ -0,0 +1,268 @@ +"""Background ``delegate`` workers a session owns, for one turn (TD-5299). + +``delegate`` with ``background: true`` starts the child as a task and +returns at once; the parent keeps working. A worker belongs to the turn +that started it: the loop does not end the turn while one is alive, and +when one settles its summary reaches the parent model as a note before +its next call. Stop and cancel end every worker, as they end a +foreground child (TD-5195). + +This module only keeps the records. The tools package starts the tasks, +so the session can import it without pulling the tools in. Every change +logs one ``worker_jobs`` event with the whole list, which the window +shows; a settled worker also logs ``worker_result`` with its steps. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import time +from collections.abc import Awaitable, Callable, Sequence +from dataclasses import dataclass, field + +from .protocol import WorkerJobInfo, WorkerResult, WorkerState, WorkerStep + +#: Settled workers kept in the list beside the live ones. +MAX_SETTLED = 16 +#: Snapshot events for progress (calls, spend, last step) are at most this often. +_PROGRESS_SECS = 1.0 +_LIVE: frozenset[WorkerState] = frozenset({"queued", "running", "awaiting_approval"}) + +Emit = Callable[[list[WorkerJobInfo]], Awaitable[None]] +EmitResult = Callable[[WorkerResult], Awaitable[None]] + + +def _cut(text: str, limit: int) -> str: + flat = " ".join(text.split()) + return flat if len(flat) <= limit else flat[: limit - 1].rstrip() + "…" + + +@dataclass +class WorkerJob: + """One background worker.""" + + id: str + call_id: str + label: str + kind: str + task: str + agent: str | None = None + state: WorkerState = "queued" + stopped: str | None = None + calls: int = 0 + cost_usd: float = 0.0 + started_at: float = field(default_factory=time.time) + ended_at: float | None = None + branch: str | None = None + worktree_path: str | None = None + summary: str = "" + steps: list[WorkerStep] = field(default_factory=list) + delivered: bool = False + handle: asyncio.Task[None] | None = None + _shown_at: float = 0.0 + + @property + def live(self) -> bool: + return self.state in _LIVE + + def info(self) -> WorkerJobInfo: + last = self.steps[-1].text if self.steps else "" + return WorkerJobInfo( + worker_id=self.id, + label=_cut(self.label, 80), + kind=self.kind, + agent=self.agent, + task=_cut(self.task, 300), + state=self.state, + stopped=self.stopped, + calls=self.calls, + cost_usd=round(self.cost_usd, 6), + started_at=self.started_at, + ended_at=self.ended_at, + branch=self.branch, + worktree_path=self.worktree_path, + last_step=_cut(last, 200), + ) + + def note(self) -> str: + """What the parent model is told when this worker settles.""" + head = f"[Worker {self.id} ({_cut(self.label, 60)})" + if self.state == "done": + body = f"{head} finished. Summary:\n{self.summary}]" + elif self.state == "interrupted": + tidy = f" {self.summary}" if self.summary else "" + body = f"{head} was interrupted by a restart. Nothing was re-run.{tidy}]" + else: + why = self.stopped or self.state + body = f"{head} {self.state}: {why}. What it had:\n{self.summary}]" + return body + + +@dataclass +class WorkerJobs: + """A session's background workers and the turn's spawn count.""" + + emit: Emit + emit_result: EmitResult + _jobs: dict[str, WorkerJob] = field(default_factory=dict) + _next: int = 1 + _changed: asyncio.Event = field(default_factory=asyncio.Event) + spawned_this_turn: int = 0 + + def new( + self, *, call_id: str, label: str, kind: str, task: str, agent: str | None + ) -> WorkerJob: + job = WorkerJob( + id=f"w-{self._next}", + call_id=call_id, + label=label or _cut(task, 60), + kind=kind, + task=task, + agent=agent, + ) + self._next += 1 + self._jobs[job.id] = job + self.spawned_this_turn += 1 + self._trim() + return job + + def get(self, worker_id: str) -> WorkerJob | None: + return self._jobs.get(worker_id) + + def by_call(self, call_id: str) -> WorkerJob | None: + return next((j for j in self._jobs.values() if j.call_id == call_id), None) + + def all(self) -> list[WorkerJob]: + return list(self._jobs.values()) + + def live(self) -> list[WorkerJob]: + return [j for j in self._jobs.values() if j.live] + + def running_count(self) -> int: + return sum(1 for j in self._jobs.values() if j.state in ("running", "awaiting_approval")) + + def owed(self) -> bool: + """Some worker is alive, or settled and its note not yet given.""" + return any(j.live or not j.delivered for j in self._jobs.values()) + + def take_notes(self) -> list[str]: + """The notes for every settled worker not yet told, marking them told.""" + notes: list[str] = [] + for job in self._jobs.values(): + if not job.live and not job.delivered: + job.delivered = True + notes.append(job.note()) + return notes + + def begin_turn(self) -> None: + self.spawned_this_turn = 0 + + async def changed(self, job: WorkerJob, *, progress: bool = False) -> None: + """Log the list; a progress tick is throttled per worker.""" + now = time.monotonic() + if progress and now - job._shown_at < _PROGRESS_SECS: + return + job._shown_at = now + await self.emit([j.info() for j in self._jobs.values()]) + self._changed.set() + + async def settle(self, job: WorkerJob, state: WorkerState, summary: str) -> None: + """Mark *job* ended, log the list and its result, and wake the loop.""" + job.state = state + job.summary = summary + job.ended_at = time.time() + await self.changed(job) + await self.emit_result( + WorkerResult( + session_id="", + worker_id=job.id, + state=state, + summary=summary, + transcript=list(job.steps), + branch=job.branch, + stopped=job.stopped, + seq=1, + ) + ) + + async def asking(self, call_id: str, waiting: bool) -> None: + """A worker's approval card opened (or closed).""" + job = self.by_call(call_id) + if job is None or not job.live: + return + job.state = "awaiting_approval" if waiting else "running" + await self.changed(job) + + async def wait_change(self) -> None: + """Until some worker changes. Cleared on return.""" + await self._changed.wait() + self._changed.clear() + + def clear_change(self) -> None: + self._changed.clear() + + async def stop(self, worker_id: str, why: str = "stopped") -> bool: + """Stop one live worker and wait for it to settle. False when none.""" + job = self._jobs.get(worker_id) + if job is None or not job.live: + return False + await self._end(job, why) + return True + + async def stop_all(self, why: str = "the turn ended") -> None: + for job in self.live(): + await self._end(job, why) + + async def _end(self, job: WorkerJob, why: str) -> None: + job.stopped = job.stopped or why + task = job.handle + if task is not None and not task.done(): + task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await task + if job.live: + # It never started, or its task ended without settling. + await self.settle(job, "stopped", job.summary or f"Worker stopped: {why}.") + + def restore(self, last: Sequence[WorkerJobInfo]) -> list[WorkerJob]: + """After a restart: the last list, with every live worker interrupted. + + Returns the interrupted ones, for the caller to settle their + worktrees and log. Nothing is re-run. + """ + cut: list[WorkerJob] = [] + for info in last: + job = WorkerJob( + id=info.worker_id, + call_id="", + label=info.label, + kind=info.kind, + task=info.task, + agent=info.agent, + state=info.state, + stopped=info.stopped, + calls=info.calls, + cost_usd=info.cost_usd, + started_at=info.started_at, + ended_at=info.ended_at, + branch=info.branch, + worktree_path=info.worktree_path, + delivered=True, + ) + if job.live: + job.state = "interrupted" + job.stopped = "the daemon restarted" + job.ended_at = time.time() + job.delivered = False + cut.append(job) + self._jobs[job.id] = job + number = info.worker_id.removeprefix("w-") + if number.isdigit(): + self._next = max(self._next, int(number) + 1) + return cut + + def _trim(self) -> None: + settled = [j for j in self._jobs.values() if not j.live and j.delivered] + for job in settled[: max(0, len(settled) - MAX_SETTLED)]: + del self._jobs[job.id] diff --git a/core/tstd/worker_restore.py b/core/tstd/worker_restore.py new file mode 100644 index 00000000..727ab14e --- /dev/null +++ b/core/tstd/worker_restore.py @@ -0,0 +1,62 @@ +"""After a restart: background workers that were running are interrupted (TD-5299). + +A worker is a task in the daemon and dies with it. On revive the last +``worker_jobs`` list comes back with every live worker marked +``interrupted``. A worker that had its own worktree has what was in the +folder committed on its branch and the folder removed, as a settled child's +would be. Nothing is re-run: that would spend without the person asking. +The next turn's first model call is told. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Sequence +from pathlib import Path + +from .git_raw import GitRawError, run_git +from .logging import get_logger +from .protocol import DaemonEvent, WorkerJobs +from .session import Session +from .tools.shell import sanitized_env +from .worktree import commit_all + +log = get_logger("tstd.worker_restore") + + +async def _settle_folder(path: Path, task: str) -> str: + env = sanitized_env() + if not await asyncio.to_thread(path.is_dir): + return "" + try: + line = task.strip().splitlines()[0][:72] if task.strip() else "delegated task" + await commit_all(path, f"{line}\n\nTST Desk delegate, interrupted by a restart.", env) + rc, out, _err = await run_git( + path, "rev-parse", "--path-format=absolute", "--git-common-dir", env=env + ) + if rc != 0: + return f"The worker's worktree at {path} could not be tidied." + top = Path(out.decode().strip()).parent + await run_git(top, "worktree", "remove", "--force", "--force", str(path), env=env) + except (GitRawError, OSError, TimeoutError) as e: + return f"The worker's worktree at {path} could not be tidied: {e}" + return "What it had changed is committed on its branch; the folder was removed." + + +async def restore_workers(session: Session, events: Sequence[DaemonEvent]) -> int: + """Mark the old daemon's live workers interrupted. Returns how many.""" + last = next((e for e in reversed(events) if isinstance(e, WorkerJobs)), None) + if last is None: + return 0 + cut = session.workers.restore(last.workers) + for job in cut: + if job.worktree_path: + job.summary = await _settle_folder(Path(job.worktree_path), job.task) + job.worktree_path = None + if cut: + await session.workers.changed(cut[0]) + log.info( + "background workers interrupted by a restart", + extra={"extra_fields": {"session_id": session.id, "workers": len(cut)}}, + ) + return len(cut) diff --git a/core/tstd/worker_turn.py b/core/tstd/worker_turn.py new file mode 100644 index 00000000..1d917646 --- /dev/null +++ b/core/tstd/worker_turn.py @@ -0,0 +1,60 @@ +"""How a turn waits for its background workers (TD-5299). + +A background ``delegate`` worker belongs to the turn that started it. When +one settles, its note goes in before the parent's next model call, at the +same tool-batch boundary a steer joins (TD-5112). When the parent model +stops calling tools while a worker is alive, the turn does not end: the +loop waits, with no model call, for a worker to settle, a steer, or Stop, +then gives the model the note and calls it again. +""" + +from __future__ import annotations + +import asyncio +import contextlib + +from .provider import ChatMessage +from .session import Session + + +async def inject_worker_notes(session: Session, messages: list[ChatMessage]) -> int: + """Append a note for every settled worker the model has not heard about.""" + notes = session.workers.take_notes() + for note in notes: + messages.append(ChatMessage(role="user", content=note, steer=True)) + if notes: + await session.conversation_changed() + return len(notes) + + +def owes_the_turn(session: Session) -> bool: + """Whether the turn must stay open: a worker is alive or its note is owed.""" + return session.workers.owed() + + +async def wait_for_workers(session: Session) -> None: + """Until a worker settles, a steer arrives, or the turn is stopped. + + Returns at once when a note is already owed or nothing is alive. + """ + jobs = session.workers + while True: + if any(not j.live and not j.delivered for j in jobs.all()) or not jobs.live(): + return + if session.steer_arrived.is_set() or session.stop_turn_requested: + return + if session.cancel_requested: + return + waits = [ + asyncio.ensure_future(jobs.wait_change()), + asyncio.ensure_future(session.steer_arrived.wait()), + asyncio.ensure_future(session.wait_for_turn_abort()), + ] + try: + await asyncio.wait(waits, return_when=asyncio.FIRST_COMPLETED) + finally: + for wait in waits: + wait.cancel() + for wait in waits: + with contextlib.suppress(asyncio.CancelledError): + await wait diff --git a/docs/architecture.md b/docs/architecture.md index cc99a30e..ed7e7e1a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -717,6 +717,7 @@ Every message in `ClientMessageT`. "Session" says whether the message carries a | `list_job_runs` | — | List one job's run history, newest first. Acked with `job_runs`. A slot skipped for lateness is `status` `missed` with `trigger` `schedule`. A run parked on an approval card is `status` `waiting`; that same line becomes `ok` or `failed` when the session finishes. A slot skipped because the previous run is still parked is `missed`. A retried slot sets `attempt` and `attempts` on each try; both are null for Run now and for a job that does not retry. A fire started because another job ended ok is `trigger` `chained`, with `scheduled_for` null and `note` naming the parent. Unknown id is `job_not_found`. Does not run the job (TD-3811, TD-3813, TD-3814, TD-3815, TD-3817). | | `list_job_templates` | — | List built-in and user job templates. Acked with `job_templates`. Does not create a job or the template file (TD-3816). | | `dismiss_schedule_proposal` | yes | Dismiss the agent's schedule proposal (`proposal_id`); nothing is scheduled. Logged as `schedule_proposal_decision` (`dismissed`). An id that is not open is `proposal_not_found` (TD-5263). | +| `worker_stop` | yes | Stop one background `delegate` worker (`worker_id`) of the session; its siblings run on. One that is not running is `worker_not_found` (TD-5299). | | `save_job_template` | — | Store the current job form as a new template. Create only; the daemon assigns the id. An empty instruction is allowed. A secret-shaped field or an unknown preset is `template_invalid`. Acked with `job_templates`. Does not create a job (TD-3816). | | `delete_job_template` | — | Remove a user template by id. A built-in is `template_builtin` and is not removed. Unknown id is `template_not_found`. Acked with `job_templates` (TD-3816). | | `get_session_job_source` | yes | Read one chat into a job draft: workspace, preset, engine, and the earliest remaining user message. Acked with `session_job_source`. Unknown id is `session_not_found`. Does not create a job (TD-3816). | @@ -764,6 +765,8 @@ are stamped by a session's event log, `connection` events fix it at 1, and `ping | `worktree_state` | session | The session's git worktree changed: made, set up, or closed (TD-5126). `worktree` is the state now (`branch`, `path`, `main_dirty`, `setup`, `setup_note`), null once the session works in the folder it was opened on; `note` says what happened in a sentence (a setup failure, a merge, or why no worktree could be made). The window refreshes the session list on it. | | `task_list` | session | The session's whole task list after the native loop's `task_list` tool changed it: items, each with `content` and a `status` of `pending`, `in_progress` or `done` (TD-5122). The newest one is the list; an empty list clears it. The Plan pane and the task strip above the composer (what the phone shows) read it. Logged again as soon as the log window rotates the last one out, and on attach if it is missing, so a restart and a late window always find it. | | `shell_jobs` | session | The session's background shell jobs after any of them changed (TD-5137): each with `job_id`, `command`, a `status` of `running`, `exited` (with `exit_code`), `stopped` (by `shell_stop`, or killed because the session ended) or `lost` (the daemon restarted while it ran), and `started_at` / `ended_at` in Unix seconds. The newest one is the list. The daemon owns the jobs; the Plan pane lists them. Logged when a job starts (`shell` with `background: true`, or `on_timeout: "background"` at a timeout), exits, or is stopped, and on revive when the old daemon's jobs are marked `lost`. | +| `worker_jobs` | session | The session's background `delegate` workers after any changed (TD-5299): each with `worker_id` (`w-N`), `label`, `kind`, `agent`, `task` (cut to 300), a `state` of `queued`, `running`, `awaiting_approval`, `done`, `failed`, `stopped` (with why in `stopped`) or `interrupted` (a restart ended it), `calls`, `cost_usd`, `branch` and `worktree_path` when it has its own worktree, `last_step`, and `started_at` / `ended_at`. The newest one is the list; progress ticks are at most one a second per worker. A worker belongs to the turn that started it. | +| `worker_result` | session | A background worker settled (TD-5299): its `state`, `summary`, `branch`, `stopped`, and the `transcript` of its steps for the window. The parent model gets the summary as a note; the steps never reach it. | | `stop_check` | session | The done-check ran because the model ended an interactive turn (TD-5124): the workspace's `stop_check.checks` and the session's `/goal`, each item with its `source` (`workspace` or `goal`), `via` (`shell` or `worker`), `passed`, `decided` and a capped `detail`. `outcome` is `passed` (the turn ends), `retry` (the failure went back to the model as a user message and the turn goes on; `attempt` counts from 1), `failed` (still failing after `max_retries` tries: the turn ends with `turn_complete.error_code` `stop_check_failed`) or `unchecked` (no item failed but one could not be judged, such as a declined command, so the turn ends and nothing went back; when one item failed and another could not be judged, the failure decides and only it goes back). A `$` check's command also logs its own `tool_call` and `tool_result`. The window shows the check on the assistant's reply. Not emitted for unattended runs, which poll their charter's definition of done, delegate children, or a turn that ends while read-only plan mode (TD-5123) is on. | | `hook_run` | session | One hook ran (TD-5134): `hook_id` (`::`), `source` (`user` or `workspace`), `event` (`session_start`, `user_prompt`, `before_tool`, `after_tool`, `stop`), `command`, `result` (`ok`, `context`, `block`, `ask`, `error`, `timeout`), `exit_code`, `reason`, `context`, the start of its `output`, `duration_ms`, and the `tool_name` and `tool_call_id` for a tool hook. The audit writer stores every one in `hook_runs`. | | `hooks_state` | session | Response to `get_hooks`: each active hook with its command, `timeout_seconds`, `tools` globs and `last` run, plus the workspace config's trust state and why a workspace `hooks` block was set aside. | diff --git a/docs/configuration.md b/docs/configuration.md index 7d708f06..b23b8392 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -906,10 +906,31 @@ returns a summary (TD-4602). |---|---|---|---| | `max_iterations` | int, 1 to 64 | `8` | Model calls one child may make. A child that reaches it stops and returns what it has, saying it used them all. Eight suits a lookup; raise it for children that edit several files and run a test. A child's calls count against the session's own `caps` (iterations, spend, time) together with its parent's and its siblings', so a larger number here cannot outrun them. | +**In the background (TD-5299).** `delegate` with `background: true` starts the child and +returns at once, so the agent keeps working. The child belongs to the turn that started it: the +turn does not end while one is alive. When one finishes, its summary reaches the agent as a note +before its next step; if the agent has nothing left to do, the turn waits for the child without +calling the model. Stop ends every child. A child that can write always gets its own git worktree +(a workspace with no commit refuses it and says to run it in the foreground). The Plan pane lists +each child with Stop; `delegate_output` and `delegate_stop` let the agent read and end one. A +background child always honours the session's caps, even with approvals skipped, and stops at its +own limits under `background`: + +| Key | Type | Default | Effect | +|---|---|---|---| +| `background.max_running` | int, 1 to 8 | `2` | Children running at once in one chat. More wait in a queue and start when one finishes. | +| `background.max_per_turn` | int, 1 to 32 | `8` | Children one turn may start; past it the call is refused. | +| `background.max_iterations` | int, 1 to 64 | `24` | Model calls one background child may make. | +| `background.max_minutes` | int, 1 to 240 | `30` | Minutes one background child may run. | +| `background.max_usd` | number above 0 | `5.0` | Dollars one background child may spend. It also never gets more than its share (`max_running`) of what the session's spend cap has left when it starts. | + ```yaml delegate: max_iterations: 8 + background: + max_running: 2 + max_usd: 5.0 ``` ### `model_concurrency` diff --git a/docs/tst-desk-backlog.md b/docs/tst-desk-backlog.md index a85727e6..7d48da38 100644 --- a/docs/tst-desk-backlog.md +++ b/docs/tst-desk-backlog.md @@ -14694,3 +14694,46 @@ computer with nobody watching. **Notes:** fields sent with a pause take effect only when the job is resumed, which needs the permission from a phone. + +--- + +### TD-5299 — A delegated child can run in the background, for the rest of the turn + +A `delegate` call blocked the agent until the child finished, so a slow +piece (run the suite and fix what fails, research an API) held everything +else up. `delegate` now takes `background: true`: the child starts as a +task the session owns and the call returns at once. The child belongs to +its turn (owner decision row 17: scoped to the turn, one level, no agent +teams). Design: section 4.3 of the 2026-11-20 sub-tasks note. + +- [x] A background call returns before the child's first model call, and + the parent keeps working (`test_delegate_background.py`). +- [x] A settled worker's summary reaches the parent model as a note at the + next tool-batch boundary; when the parent stops calling tools with a + worker alive, the turn waits with no model call and then hands it the + note (`test_the_turn_waits_for_its_worker_and_hears_the_note`, through + the real loop). +- [x] More than `delegate.background.max_running` wait in a queue; + `max_per_turn` refuses past it. +- [x] Stop, cancel and the end of the turn end every worker; + `delegate_stop` (and the window's Stop, `worker_stop`) end one, and + its sibling runs on. A stopped writer leaves no worktree folder. +- [x] A writer always gets its own worktree; where there can be none the + call is refused with a hint to run it in the foreground. +- [x] Each worker has its own call, time and spend ceiling and honours the + session's caps even under skip-all. +- [x] Refused from a child, an autonomy run, a scheduled run and a + deny-and-continue run. A child cannot call `delegate_output` or + `delegate_stop`; both are Class A only as builtins and allowed in + plan mode. +- [x] A restart marks live workers `interrupted`, commits what a worker's + worktree held to its branch and removes the folder, re-runs nothing, + and the next turn is told. +- [x] The Plan pane lists workers with Stop and a settled worker's steps + (`workers-store.test.ts`). + +**Size:** 5 · **Depends on:** TD-4602, TD-5195, TD-5268, TD-5269 · **Status:** Done + +**Notes:** the optional per-worker `check` from the design note and +steering a running child (4.4) are not in this story. A child's card is +tagged by TD-5268 and its worker shows `awaiting_approval` while it waits. diff --git a/ui/src/lib/client.ts b/ui/src/lib/client.ts index 898938b3..552cf3d4 100644 --- a/ui/src/lib/client.ts +++ b/ui/src/lib/client.ts @@ -104,6 +104,8 @@ const KNOWN_EVENT_TYPES = new Set([ "phone_change", // TD-5279 "schedule_proposal", // TD-5263 "schedule_proposal_decision", + "worker_jobs", // TD-5299 + "worker_result", "mcp_import_preview", // TD-5253 "machine_list", // TD-5015 "api_key_validated", // TD-1101 diff --git a/ui/src/lib/components/AppShell.svelte b/ui/src/lib/components/AppShell.svelte index ff81cb1d..7706e84f 100644 --- a/ui/src/lib/components/AppShell.svelte +++ b/ui/src/lib/components/AppShell.svelte @@ -90,6 +90,7 @@ import { startGrok } from '../grok.svelte.js'; import { startTaskLists } from '../task-list-store.svelte.js'; import { startShellJobs } from '../shell-jobs-store.svelte.js'; + import { startWorkers } from '../workers-store.svelte.js'; import { startGoals } from '../goal-store.svelte.js'; import { startVoice } from '../voice.svelte.js'; import { modelSlot, resolveShortcut, sessionSlot } from '../shortcuts'; @@ -251,6 +252,7 @@ const offGrok = startGrok(); const offTaskLists = startTaskLists(); const offShellJobs = startShellJobs(); + const offWorkers = startWorkers(); const offGoals = startGoals(); const offVoice = startVoice(); let offUpdates = () => {}; @@ -299,6 +301,7 @@ offGrok(); offTaskLists(); offShellJobs(); + offWorkers(); offGoals(); offVoice(); offUpdates(); diff --git a/ui/src/lib/components/PlanPane.svelte b/ui/src/lib/components/PlanPane.svelte index 58275b49..3c19203a 100644 --- a/ui/src/lib/components/PlanPane.svelte +++ b/ui/src/lib/components/PlanPane.svelte @@ -9,6 +9,8 @@ import { pinnedPlanFor, taskListFor } from '../task-list-store.svelte.js'; import { jobStateLabel, shellJobsFor } from '../shell-jobs-store.svelte.js'; import Markdown from './chat/Markdown.svelte'; + import WorkersList from './WorkersList.svelte'; + import { workersFor } from '../workers-store.svelte.js'; let comment = $state(''); @@ -30,9 +32,14 @@ // this only lists what its newest `shell_jobs` event says. let jobs = $derived(shellJobsFor(session.sessionId)); let runningJobs = $derived(jobs.filter((job) => job.status === 'running').length); + // TD-5299: background delegate workers. + let workerCount = $derived(workersFor(session.sessionId).length);
+ {#if session.sessionId !== null} + + {/if} {#if jobs.length > 0}

Background jobs · {runningJobs} running

@@ -63,7 +70,7 @@ {:else if remoteName !== null} {:else if !hasPlan} - {#if jobs.length === 0} + {#if jobs.length === 0 && workerCount === 0} + // Background delegate workers (TD-5299). The daemon owns them; this lists + // its newest `worker_jobs`, offers Stop on a live one, and shows a settled + // one's steps from `worker_result`. + import { formatWorkerTranscript } from '../worker-transcript'; + import { + isLive, + resultFor, + stopWorker, + workerStateLabel, + workersFor, + } from '../workers-store.svelte.js'; + + interface Props { + sessionId: string; + } + + let { sessionId }: Props = $props(); + + let list = $derived(workersFor(sessionId)); + let live = $derived(list.filter(isLive).length); + + +{#if list.length > 0} +
+

Background workers · {live} running

+
    + {#each list as worker (worker.worker_id)} + {@const result = resultFor(sessionId, worker.worker_id)} +
  • +
    + {workerStateLabel(worker)} + {worker.label} + {worker.calls} calls · ${worker.cost_usd.toFixed(2)} + {#if isLive(worker)} + + {/if} +
    + {#if isLive(worker) && worker.last_step} +

    {worker.last_step}

    + {/if} + {#if worker.branch} +

    Branch {worker.branch}

    + {/if} + {#if result !== undefined && result.transcript.length > 0} +
    + Steps +
    {formatWorkerTranscript(result.transcript)}
    +
    + {/if} +
  • + {/each} +
+
+{/if} + + diff --git a/ui/src/lib/protocol-fixtures.json b/ui/src/lib/protocol-fixtures.json index d94888e8..bae8a249 100644 --- a/ui/src/lib/protocol-fixtures.json +++ b/ui/src/lib/protocol-fixtures.json @@ -836,6 +836,11 @@ "session_id": "sess-1", "proposal_id": "sp_0123456789ab" }, + "worker_stop": { + "type": "worker_stop", + "session_id": "sess-1", + "worker_id": "w-1" + }, "set_phone_permission": { "type": "set_phone_permission", "capability": "mcp_servers", @@ -2451,6 +2456,48 @@ "decision": "saved", "job_id": "job-1" }, + "worker_jobs": { + "type": "worker_jobs", + "seq": 9, + "session_id": "sess-1", + "workers": [ + { + "worker_id": "w-1", + "label": "fix the date parser", + "kind": "worker", + "agent": null, + "task": "Fix the date parser and run its tests.", + "state": "running", + "stopped": null, + "calls": 3, + "cost_usd": 0.0123, + "started_at": 1795400000.0, + "ended_at": null, + "branch": "tst/child-1", + "worktree_path": "/work/.worktrees/child-1", + "last_step": "pytest tests/test_dates.py" + } + ] + }, + "worker_result": { + "type": "worker_result", + "seq": 10, + "session_id": "sess-1", + "worker_id": "w-1", + "state": "done", + "summary": "Fixed the parser; 12 tests pass.", + "transcript": [ + { + "kind": "reply", + "text": "Fixed the parser; 12 tests pass.", + "tool": null, + "status": null, + "truncated": false + } + ], + "branch": "tst/child-1", + "stopped": null + }, "phone_change": { "type": "phone_change", "seq": 1, diff --git a/ui/src/lib/protocol.ts b/ui/src/lib/protocol.ts index 6f4cdda4..c9d08c22 100644 --- a/ui/src/lib/protocol.ts +++ b/ui/src/lib/protocol.ts @@ -347,6 +347,13 @@ export interface ImportMcpServers extends ClientMessage { servers: McpImportChoice[]; } +/** Stop one background worker (TD-5299). Its siblings run on. */ +export interface WorkerStop extends ClientMessage { + type: "worker_stop"; + session_id: string; + worker_id: string; +} + /** Dismiss the agent's schedule proposal (TD-5263). Nothing is scheduled. */ export interface DismissScheduleProposal extends ClientMessage { type: "dismiss_schedule_proposal"; @@ -1513,6 +1520,7 @@ export type ClientMessageUnion = | RemoveRemoteDevice | SetPhonePermission | DismissScheduleProposal + | WorkerStop | PreviewMcpImport | ImportMcpServers | AddMachine @@ -3192,6 +3200,52 @@ export interface ShellJobs extends DaemonEvent { jobs: ShellJobInfo[]; } +export type WorkerState = + | "queued" + | "running" + | "awaiting_approval" + | "done" + | "failed" + | "stopped" + | "interrupted"; + +/** One background `delegate` worker (TD-5299). It belongs to the turn that started it. */ +export interface WorkerJobInfo { + worker_id: string; + label: string; + kind: string; + agent?: string | null; + task: string; + state: WorkerState; + stopped?: string | null; + calls: number; + cost_usd: number; + started_at: number; + ended_at?: number | null; + branch?: string | null; + worktree_path?: string | null; + last_step: string; +} + +/** The session's background workers after one changed. The newest event is the list. */ +export interface WorkerJobs extends DaemonEvent { + type: "worker_jobs"; + session_id: string; + workers: WorkerJobInfo[]; +} + +/** A background worker settled: its summary and steps, for the window only. */ +export interface WorkerResult extends DaemonEvent { + type: "worker_result"; + session_id: string; + worker_id: string; + state: WorkerState; + summary: string; + transcript: WorkerStep[]; + branch?: string | null; + stopped?: string | null; +} + /** A session's worktree changed: made, set up, or closed (TD-5126). */ export interface WorktreeState extends DaemonEvent { type: "worktree_state"; @@ -3620,6 +3674,8 @@ export type DaemonEventUnion = | PhoneChange | ScheduleProposal | ScheduleProposalDecision + | WorkerJobs + | WorkerResult | McpImportPreview | MachineList | ApiKeyValidated diff --git a/ui/src/lib/workers-store.svelte.ts b/ui/src/lib/workers-store.svelte.ts new file mode 100644 index 00000000..03774a61 --- /dev/null +++ b/ui/src/lib/workers-store.svelte.ts @@ -0,0 +1,67 @@ +// Background delegate workers per session (TD-5299), from the daemon's +// `worker_jobs` and `worker_result` events. The daemon owns them; the +// window lists them, shows a settled worker's steps, and sends Stop. + +import { onEvent, sendToDaemon } from "./connection-status.svelte.js"; +import type { DaemonEventUnion, WorkerJobInfo, WorkerResult } from "./protocol"; + +export const workers = $state({ + bySession: {} as Record, + results: {} as Record, +}); + +const NONE: readonly WorkerJobInfo[] = []; +const LIVE = new Set(["queued", "running", "awaiting_approval"]); + +export function workersFor(sessionId: string | null): readonly WorkerJobInfo[] { + if (sessionId === null) return NONE; + return workers.bySession[sessionId] ?? NONE; +} + +export function isLive(worker: WorkerJobInfo): boolean { + return LIVE.has(worker.state); +} + +/** "running", "waiting for you", "done", "stopped (why)": one line per worker. */ +export function workerStateLabel(worker: WorkerJobInfo): string { + if (worker.state === "awaiting_approval") return "waiting for you"; + if (worker.state === "stopped" && worker.stopped) return `stopped (${worker.stopped})`; + return worker.state; +} + +export function resultFor(sessionId: string, workerId: string): WorkerResult | undefined { + return workers.results[`${sessionId}/${workerId}`]; +} + +/** Stop one worker. False when nothing was sent. */ +export function stopWorker(sessionId: string, workerId: string): boolean { + return sendToDaemon({ type: "worker_stop", session_id: sessionId, worker_id: workerId }); +} + +let started = false; + +export function startWorkers(): () => void { + if (started) return () => {}; + started = true; + const off = onEvent(reduce); + return () => { + started = false; + off(); + }; +} + +export function resetWorkers(): void { + started = false; + workers.bySession = {}; + workers.results = {}; +} + +function reduce(event: DaemonEventUnion): void { + if (event.type === "worker_jobs") { + workers.bySession[event.session_id] = event.workers ?? []; + return; + } + if (event.type === "worker_result") { + workers.results[`${event.session_id}/${event.worker_id}`] = event; + } +} diff --git a/ui/src/lib/workers-store.test.ts b/ui/src/lib/workers-store.test.ts new file mode 100644 index 00000000..4a86fd58 --- /dev/null +++ b/ui/src/lib/workers-store.test.ts @@ -0,0 +1,73 @@ +// TD-5299: the window lists background workers from the daemon's newest +// `worker_jobs`, keeps each settled worker's steps, and only sends Stop. + +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const connection = vi.hoisted(() => { + const handlers = new Set<(event: unknown) => void>(); + return { handlers, sent: [] as unknown[] }; +}); + +vi.mock("./connection-status.svelte.js", () => ({ + onEvent: (handler: (event: unknown) => void) => { + connection.handlers.add(handler); + return () => connection.handlers.delete(handler); + }, + sendToDaemon: (msg: unknown) => (connection.sent.push(msg), true), +})); + +import fixtures from "./protocol-fixtures.json"; +import type { WorkerJobs, WorkerResult } from "./protocol"; +import { + isLive, + resetWorkers, + resultFor, + startWorkers, + stopWorker, + workerStateLabel, + workersFor, +} from "./workers-store.svelte.js"; + +function emit(event: unknown): void { + for (const handler of connection.handlers) handler(event); +} + +beforeEach(() => { + connection.sent.length = 0; + connection.handlers.clear(); + resetWorkers(); + startWorkers(); +}); + +describe("workers store", () => { + it("the newest list is the truth, per session", () => { + const jobs = fixtures.worker_jobs as WorkerJobs; + emit(jobs); + const [worker] = workersFor("sess-1"); + expect(worker.worker_id).toBe("w-1"); + expect(isLive(worker)).toBe(true); + expect(workersFor("other")).toEqual([]); + emit({ ...jobs, workers: [{ ...worker, state: "done" }] }); + expect(isLive(workersFor("sess-1")[0])).toBe(false); + }); + + it("keeps a settled worker's steps for the window", () => { + emit(fixtures.worker_result as WorkerResult); + expect(resultFor("sess-1", "w-1")?.transcript.length).toBe(1); + }); + + it("says why a worker stopped and when it waits for you", () => { + const base = (fixtures.worker_jobs as WorkerJobs).workers[0]; + expect(workerStateLabel({ ...base, state: "awaiting_approval" })).toBe("waiting for you"); + expect(workerStateLabel({ ...base, state: "stopped", stopped: "delegate_stop" })).toBe( + "stopped (delegate_stop)", + ); + }); + + it("Stop only sends the person's request", () => { + expect(stopWorker("sess-1", "w-1")).toBe(true); + expect(connection.sent).toEqual([ + { type: "worker_stop", session_id: "sess-1", worker_id: "w-1" }, + ]); + }); +});