Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions docs/system-specs/modules/subagent.md
Original file line number Diff line number Diff line change
Expand Up @@ -4950,7 +4950,11 @@ when the parent's own call already returned every member it carries:
it. A running, paged, grepped, over-cap or failed read, a stopped or failed
run, a missing or unknown outcome, and a caller with no resolvable session
answer plain text and mark nothing. The live done response includes
`outcome` and `stopped`, matching the disk fallback. The
`outcome` and `stopped`, matching the disk fallback, and `answer_finished`:
True when the run finished its whole answer (`_answer_finished`, a `result`,
not `partial`), the completion event's own test, so a stop that landed then
is read as one. Each done row of `GET /api/spawn` carries it too; a record
read back from disk does not. The
gateway applies every rule below to that mark too, so a read in a later turn
than the one that spawned the run flags nothing and its completion is still
delivered.
Expand Down Expand Up @@ -5194,7 +5198,7 @@ Blocking wait semantics:
- A member that is accepted but not started answers `queued: true` with `done: false`, and when the gate DEFERRED it (its own `reason_detail` sentence, sent only while the deferral is in force; the parent-wide `reason` label is last-writer-wins and not trusted for this) it SETTLES the wait: the call returns once every member is done, errored or deferral-held, so one gate-deferred member does not hold a dashboard parent's turn inside the tool for up to `max_wait`. A member queued only behind the concurrency cap (`concurrency_limit`) or waiting to resume is NOT settled: it drains with the wave, and the tool returns its result (a sub-agent parent still waits for its own slot grant afterwards, `_ResumeHold`, which follows its children). Done and queued members are not polled again; an error settles only the pass it was seen in, since it can be one failed poll of a running member. A queued member is reported ONCE, in the `{"status": "queued", "agents": {id: reason}}` record (the reason is its current wait, `queued_wait_text`), never as an `error` member too: a caller shown an error for accepted work dispatches it again. Its result arrives later as a completion event, and it is never marked collected. A queued member that already ran and waits to resume (`resuming: true`) is reported under `still_running` as `waiting_to_resume`, never as not started. "Held" is read off `queued: true` only, never off a 404's prose. The gateway sends `error` only on a finished row, so a final poll that answers `error` without `done: true` is a read that failed (a timeout, a 404, a 503): it says nothing about the child, which may still be running, so that member is reported under `still_running` as `unread`, never as an `error` entry, and is not marked collected.
- The call pings `POST /api/session-keepalive` every 30s, in every phase (submit, poll, the parent's slot hold), so the gateway's `is_responsive()` does not flag the (legitimately long-blocked) session as stale and SIGTERM the ACP subprocess mid-poll. The `wait` tool pings the same endpoint for the same reason but on a **5s** interval and with a body, because there the reply doubles as an early-end control channel (see `modules/learn-cron-dashboard.md` § Wait countdown and early end); this loop ignores the reply. Its body is the call's heartbeat: `tool_call_id` and `phase` (`mcp_caller.heartbeat_fields`) and, while polling, `subagent_ids`, the members it still waits on, so the parent's `spawn_sub_agents` call, a sub-agent call under the per-call silence timer (`acp-client.md`, "Per-call silence timer", 10 min by default), is judged by its children's own latest activity, and a child mid-tool, waiting on a person or not started yet counts as moving. While the batch is submitted or the parent waits for its slot it names no member, and the beat itself is the call's activity. `spawn_run` beats the same way, every 30s, while it submits its batch.
- `max_wait` defaults to 7200s (2 hours), clamped to `[60, 7200]`, and is configurable via the `KIROCREW_SPAWN_SUB_AGENTS_MAX_WAIT` environment variable. The deadline uses `time.monotonic()` and starts when the last submission step finishes.
- Returns a newline-separated list of per-agent JSON results (`status`: `completed`, or `error` for a run that finished badly), followed when they apply by the `still_running` envelope, the `queued` record of members not yet started, a `resume_pending` note and a `spawn_errors` record, all redacted for credentials, inside URLs too. A failed child's result entry
- Returns a newline-separated list of per-agent JSON results (`status`: `completed`; `stopped`, with a `note` in the completion event's words, for a run that was stopped: not a finished result, or a whole answer when the stop landed as it finished; or `error` for a run that finished badly), followed when they apply by the `still_running` envelope, the `queued` record of members not yet started, a `resume_pending` note and a `spawn_errors` record, all redacted for credentials, inside URLs too. A failed child's result entry
carries its retained transcript in a `text` field, summarized past
`COMPLETION_KEEP_DEFAULT_CHARS` to the same disk-path pointer a completed child's
result uses.
Expand Down Expand Up @@ -5682,7 +5686,11 @@ on demand instead of re-running the subagent. A run that FINISHED with an error
partial output) returns that retained output under an `[ENDED WITH ERROR · <reason>]`
header, the reason passed through the exfiltration-URL and credential redaction; a
non-finished error (a failed lookup or a transport error) still returns the error
line alone.
line alone. A run that was stopped (`stopped` true; a stop leaves `error` unset)
returns its retained output under a `[STOPPED · ...]` header in the completion
event's words (`subagent_ending.STOPPED_BEFORE_COMPLETING`, or
`STOPPED_AS_IT_FINISHED` when `answer_finished` is true), and `spawn_list` lists it
as `[stopped]` (`[stopped as it finished its answer]`) rather than `[done]`.

For a running in-memory record, `GET /api/spawn/{id}` keeps `done: false` and
returns the manager's bounded `streaming_text` as `result` alongside `turns`,
Expand Down
1 change: 1 addition & 0 deletions src/kiro_crew/dashboard/handlers/messaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@
api_spawn_stop_all,
)
from kiro_crew.dashboard.messaging_api.run_views import ( # noqa: F401
_answer_finished,
_apply_result_view,
_awaiting_spawn_approval,
_failover_fields,
Expand Down
16 changes: 16 additions & 0 deletions src/kiro_crew/dashboard/messaging_api/run_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,20 @@ def _failover_fields(info: object) -> dict[str, object]:
return {"failover_from": moved_from, "backend": backend_to_stored(ran_on)}


def _answer_finished(info: object) -> bool:
"""True when the run finished its whole answer, a stop that landed then included.
The completion event's own test (``_finished_answer`` in
``slack/gateway_runtime/subagent_report.py``), so ``spawn_status`` and
``spawn_sub_agents`` tell a stopped run's parent the answer is whole, as it does.
"""
return (
getattr(info, "_answer_finished", False) is True
and bool(getattr(info, "result", ""))
and not getattr(info, "partial", False)
)


def _worktree_field(path: object, base: object) -> dict[str, object]:
"""``{"worktree": {"path", "base"}}`` for an isolated run (``spawn_run`` ``isolate``), else ``{}``.
Expand Down Expand Up @@ -264,6 +278,7 @@ async def api_spawn_status(request: web.Request) -> web.Response:
if info.done:
data["outcome"] = info.outcome
data["stopped"] = info.user_stopped
data["answer_finished"] = _answer_finished(info)
data["elapsed"] = info.elapsed
data["credits"] = info.credits
# ``spawn_sub_agents`` flags a completed run that made no tool call,
Expand Down Expand Up @@ -479,6 +494,7 @@ async def api_spawn_list(request: web.Request) -> web.Response:
entry["result"] = _redact(info.result)
entry["error"] = _redact(info.error) if info.error else ""
entry["stopped"] = info.user_stopped
entry["answer_finished"] = _answer_finished(info)
entry["outcome"] = info.outcome
else:
entry["turns"] = info.turns
Expand Down
1 change: 1 addition & 0 deletions src/kiro_crew/mcp_listing_relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@
"slack/__init__.py",
"slack/features.py",
"spawn_label.py",
"subagent_ending.py",
"subagent_read_collected.py",
"subagent_standalone.py",
"subagent_wait_reasons.py",
Expand Down
6 changes: 5 additions & 1 deletion src/kiro_crew/mcp_tools/spawn.py
Original file line number Diff line number Diff line change
Expand Up @@ -983,7 +983,7 @@ def resource_status(name: str, args: dict[str, Any]) -> str:
__all__ = sorted(n for n in set(globals()) | set(_EXPORTS) if not n.startswith("_"))

if TYPE_CHECKING: # every owner-defined name in _EXPORTS, for type checkers and IDEs
from kiro_crew.mcp_tools.spawn_parts.listing import _queued_why # noqa: F401
from kiro_crew.mcp_tools.spawn_parts.listing import _queued_why, stopped_run_note # noqa: F401
from kiro_crew.mcp_tools.spawn_parts.schemas import ( # noqa: F401
_BRIEF_LIMIT,
_CORE,
Expand Down Expand Up @@ -1043,6 +1043,10 @@ def resource_status(name: str, args: dict[str, Any]) -> str:
from kiro_crew.platform import redact_via_context as redact # noqa: F401
from kiro_crew.security import redact_credentials, redact_exfiltration_urls # noqa: F401
from kiro_crew.spawn_label import SPAWN_LABEL_MAX_CHARS # noqa: F401
from kiro_crew.subagent_ending import ( # noqa: F401
STOPPED_AS_IT_FINISHED,
STOPPED_BEFORE_COMPLETING,
)
from kiro_crew.subagent_read_collected import post_mark_collected # noqa: F401
from kiro_crew.subagent_standalone import ( # noqa: F401
format_subagent_usage,
Expand Down
25 changes: 24 additions & 1 deletion src/kiro_crew/mcp_tools/spawn_parts/listing.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
)
from kiro_crew.platform import redact_via_context as redact
from kiro_crew.security import redact_credentials, redact_exfiltration_urls
from kiro_crew.subagent_ending import STOPPED_AS_IT_FINISHED, STOPPED_BEFORE_COMPLETING
from kiro_crew.subagent_standalone import ( # noqa: F401 -- visible_agent_names: the facade serves it
format_subagent_usage,
visible_agent_names,
Expand All @@ -36,6 +37,19 @@
from kiro_crew.mcp_shared import DeferredTool


def stopped_run_note(record: Mapping[str, Any]) -> str:
"""What a read of a stopped run says beside the output it kept.

The completion event's words (:mod:`kiro_crew.subagent_ending`). A stop leaves
``error`` unset on purpose, so without it the partial output reads as a result.
Exactly True ``answer_finished``: the stop landed as the run finished its whole
answer, which the parent may use.
"""
if record.get("answer_finished") is True:
return f"Stopped {STOPPED_AS_IT_FINISHED}"
return f"Stopped {STOPPED_BEFORE_COMPLETING}"


def _queued_why(record: Mapping[str, Any]) -> str:
"""Why a queued spawn waits, redacted (:func:`queued_wait_text`)."""
return redact(queued_wait_text(record))
Expand Down Expand Up @@ -87,7 +101,14 @@ def _redact(text: str) -> str:
# ("Check spawn_list", in ``mcp_tools.spawn``) -- it reads as work in progress when
# the truth is that a human has not approved it yet.
if a.get("done"):
status = "done"
# A stopped run is done, but its output is not a finished result
# unless the stop landed as it finished its answer (stopped_run_note).
# An error still wins, as in spawn_status and spawn_sub_agents.
if a.get("stopped") is True and not a.get("error"):
finished = a.get("answer_finished") is True
status = "stopped as it finished its answer" if finished else "stopped"
else:
status = "done"
elif a.get("awaiting_approval"):
status = "awaiting-approval"
else:
Expand Down Expand Up @@ -300,6 +321,8 @@ def spawn_status(name: str, args: dict[str, Any]) -> "str | DeferredTool":
reason, _ = redact_exfiltration_urls(str(d["error"]))
reason, _ = redact_credentials(reason)
out = f"[ENDED WITH ERROR · {reason}]\n{out}"
elif d.get("done") is True and d.get("stopped") is True:
out = f"[STOPPED · {stopped_run_note(d)}]\n{out}"
if (
spawn_params
or (isinstance(meta, dict) and meta)
Expand Down
8 changes: 7 additions & 1 deletion src/kiro_crew/mcp_tools/spawn_parts/wave.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from kiro_crew.context_management import COMPLETION_KEEP_DEFAULT_CHARS
from kiro_crew.mcp_caller import heartbeat_fields
from kiro_crew.mcp_shared import DEFERRED_STEP_WORKERS, DeferredTool
from kiro_crew.mcp_tools.spawn_parts.listing import _queued_why
from kiro_crew.mcp_tools.spawn_parts.listing import _queued_why, stopped_run_note
from kiro_crew.platform import redact_via_context as redact
from kiro_crew.subagent_read_collected import post_mark_collected
from kiro_crew.validation import (
Expand Down Expand Up @@ -704,6 +704,12 @@ def _collect(self) -> str:
"status": "completed",
"text": result_text,
}
if sa_st.get("stopped") is True:
# A stop leaves ``error`` unset, so it lands here. This call marks the
# child collected, so the completion event that says it was stopped is
# not injected either: the record has to say it.
record["status"] = "stopped"
record["note"] = stopped_run_note(sa_st)
# Exactly True: a status read that does not say (a run recovered
# from disk, a stopped or failed run) attaches nothing.
if sa_st.get("made_no_tool_calls") is True:
Expand Down
17 changes: 8 additions & 9 deletions src/kiro_crew/slack/gateway_runtime/subagent_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,11 @@ def _compose_subagent_completion(info: SubagentInfo, *, _flush_only: bool) -> _S
# run's own failure. Imported here: these functions run with the
# gateway's module globals.
from kiro_crew.preview_text import clip_preview
from kiro_crew.subagent_ending import SubagentEnding
from kiro_crew.subagent_ending import (
STOPPED_AS_IT_FINISHED,
STOPPED_BEFORE_COMPLETING,
SubagentEnding,
)

ending = info.ending
if ending is SubagentEnding.INTERRUPTED_BY_PARENT:
Expand Down Expand Up @@ -164,15 +168,10 @@ def _compose_subagent_completion(info: SubagentInfo, *, _flush_only: bool) -> _S
_origin = getattr(info, "_stop_origin", "") or "stopped by user"
_who = "Stopped by the user" if _origin == "stopped by user" else f"Stopped ({_origin})"
if _finished_answer:
detail = (
f"{_who} as it finished its answer. Do NOT retry it unprompted."
f"\n\nIts answer:\n{_finished_answer}"
)
detail = f"{_who} {STOPPED_AS_IT_FINISHED}\n\nIts answer:\n{_finished_answer}"
else:
detail = (
f"{_who} before completing. Do NOT treat this as "
"a finished result or retry it unprompted."
+ (f"\n\nPartial output:\n{_partial}" if _partial else "")
detail = f"{_who} {STOPPED_BEFORE_COMPLETING}" + (
f"\n\nPartial output:\n{_partial}" if _partial else ""
)
elif info.error:
detail = f"Error: {info.error}"
Expand Down
10 changes: 10 additions & 0 deletions src/kiro_crew/subagent_ending.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ def coarse(self) -> str:
}


#: What an ``INTERRUPTED_BY_PARENT`` ending is told as, after the subject that names
#: who stopped it ("Stopped by the user", "Stopped"). The parent's completion event
#: and the sub-agent read tools say it in these same words.
STOPPED_BEFORE_COMPLETING = (
"before completing. Do NOT treat this as a finished result or retry it unprompted."
)
#: The same, for a stop that landed as the run finished its whole answer.
STOPPED_AS_IT_FINISHED = "as it finished its answer. Do NOT retry it unprompted."


def classify_ending(
*, user_stopped: bool, error: str, deadline_ending: bool, partial: bool
) -> SubagentEnding:
Expand Down
Loading
Loading