Commit Graph

60 Commits

Author SHA1 Message Date
Jeffrey Quesnelle
8cccef5dea fix(delegation): correct the delegate_task text the model reads (#160256)
* fix(delegation): correct the delegate_task text the model reads

Text the model reads described behaviour the code does not have:

- The tool description sent durable work to
  terminal(background=True, notify=True). A background process ends
  with its session unless it is started with persist_on_release=True,
  so the advice now names that flag.
- The steer `message` parameter and the note a steer returns said the
  text is appended to the child's next tool result. It is delivered as
  a user message after the child's current tool calls.
- The note on a delegation that ran inside the call named
  background=true, a parameter delegate_task accepts and ignores.

The prompt-surface snapshot is regenerated: tools/delegate_task.json
and the tool token counts in surfaces.json.

* docs(delegation): config comments and example match the code

- delegation.api_key: an empty value means the parent's key, or the
  named provider's own. The comments said it falls back to
  OPENAI_API_KEY.
- delegation.orchestrator_enabled: false makes every child a leaf. The
  comments described it as a switch for role="orchestrator", a
  parameter delegate_task ignores.
- delegation.max_spawn_depth has a floor of 1 and no ceiling. The
  config example gave a range of 1-3.
- The bundled hermes-agent skill's concurrency reference gave a default
  of 3. It is 10, and the env var is read only when no config value is
  loaded.

* docs(delegation): name the provider branch in the api_key comment

With delegation.provider set, an empty delegation.api_key is not the
parent's key: the named provider resolves its own, and the spawn is
refused when it has none. The comment in config_defaults.py already says
so; this one now matches it.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* docs(delegation): steer_subagent docstring says how a steer arrives

The docstring said AIAgent.steer() appends the text to the child's last
tool result. The child receives it as a user message after its current
tool calls, as the note this function's caller returns now says.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* docs(skills): delegation facts in the hermes-agent background reference

The reference gave max_concurrent_children a default of 3, described
delegate_task(background=true) and a per-call leaf or orchestrator role,
and sent work that must outlive the process to terminal(background=True,
notify_on_complete=True).

The default is 10, top-level calls run in the background where the
session can receive a later message, nesting follows depth, and a
terminal job started with persist_on_release survives the session ending
but not a gateway or host shutdown.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* docs(agents): delegation defaults and dispatch in tools/AGENTS.md

The Delegation section said the parent waits unless background=true,
gave max_concurrent_children a default of 3 and max_spawn_depth a
default of 2, and sent work that must survive a restart to
terminal(background=True, notify_on_complete=True).

A top-level model call is backgrounded by the runtime where the session
can receive the result, the defaults are 10 and 1, and cronjob is the
tool for work that must survive a restart.

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>

* docs(delegation): max_spawn_depth default in a gateway comment

The comment on the delegate-chain walk bound gave
delegation.max_spawn_depth a default of 2. It is 1 (config_defaults.py).

---------

Co-authored-by: Bear Huddleston <196404565+BearHuddleston@users.noreply.github.com>
2026-11-25 22:16:36 -05:00
alt-glitch
43dc9a0a28 refactor(delegation): siblings read config from its owner, not back through the facade
The delegate_tool_* siblings imported names back from tools.delegate_tool
inside functions only so tests could patch `tools.delegate_tool.<name>`
(routes said so: "the facade is the patch seam"). That kept a facade <->
sibling import cycle and a function-level import at each read.

- child_run owns the heartbeat/stale-grace constants (only it reads them)
  and imports _get_child_timeout, _get_subagent_approval_callback,
  _get_worktree_isolation, _resolve_workspace_hint and terminal_tool's
  set_approval_callback at module top.
- config drops `_cfg()` (a loop back to its own `_load_config`) and the
  loop back for `_get_max_concurrent_children`, defined in the same file.
- routes, dispatch and continue import their config getters at module top.
- `_load_config` is read through `delegate_tool_config._load_config` by the
  facade, continue, results and process_registry_notifications, so one
  patch target reaches every reader, as the facade target did before.
- cronjob_tools, process_registry_notifications and subagent_lifecycle read
  these names from their owner; the facade stops importing the names its
  body never used, so a stale facade patch now fails instead of silently
  doing nothing.

Tests move their patches to the module whose code reads the name. Two
worktree tests that patched `_resolve_workspace_hint` on the facade relied
on it reaching both the facade's prompt build and child_run's worktree
setup, so they now patch both readers. Every delegate_tool* module imports
cleanly as the first import in a fresh interpreter.
2026-11-16 21:58:16 +05:30
Teknium
d1404197fc fix(delegate): an unstarted automatic attempt reports nothing, a late cancel beats the give-up, legacy expired rows prune
- An automatic attempt cancelled or failed closed before its run started is not an outcome: its entry carries
  unstarted_auto, so the completion is silent in the queue and the ledger. A cancel then reports nothing ever;
  a failed start stays owed and the next attempt (or its give-up) is the one report.
- _give_up's atomic UPDATE requires the record still owed (OWED_SQL): a cancel landing after the tick read an
  expired candidate wins and no failure is delivered.
- Expired-row retention treats a record without auto_promised as not owed (NOT COALESCE(..., 0)), so legacy
  rows are deleted again as on main.
2026-11-13 00:03:31 -08:00
Teknium
e7bbc97978 fix(delegate): each waiting child reports its give-up once, on its own row, whatever the pool or a crash does
Review of 6cf0425 reproduced four delivery defects:

- A grouped unit's give-up reused the batch's delegation_id and overwrote its durable completion, so a second
  child's report was claimed against an already-delivered row and suppressed. Each give-up now has its own
  ledger row, <unit>:auto:<subagent_id>, claimed and acked on its own.
- _give_up committed auto_gave_up before persisting the failure, and a tick skips gave-up records: a crash in
  between lost the only report. The mark and the pending completion row now commit in one transaction; the
  in-memory copy is queued after, and restart replay / the orphan sweep cover a lost copy.
- tick() returned early on a full pool or a spawn pause, so a deadline never settled while the pool stayed full.
  Capacity and the pause now gate only new starts.
- A detached batch's early per-task failure notice fired for a child promised an automatic resume. Skipped now;
  that child reports once, later.

completion_event() is split out of _push_completion_event so the give-up builds the same event shape.
2026-11-13 00:03:31 -08:00
Teknium
b5e91490d4 fix(delegate): an automatic continue only ever detaches
The scheduler has no turn to join a result into: where the parent
session cannot receive a detached result, or the background pool is
full, the continue is refused (attempt refunded) instead of running the
child inline inside the scheduler tick.
2026-11-13 00:03:31 -08:00
Teknium
34aa0029dc fix(delegate): recovered split-completion notices name their continuable children
Review finding: split-completion recovery omits continuation ids. Children stored the call-wide delegation
id while independent-completion ledger rows are keyed by unit id (<call>-k), so boot recovery joined unequal
keys. Each child now records the unit id its ledger row runs under, and recovery keys on it.
2026-11-11 22:10:25 -08:00
Teknium
4d61167263 fix(delegate): the durable claim gates every continue; resumable records review round
BearHuddleston's review of #154163:

- In-process continue ignored the durable claim's refusal: a second continue that
  fell through to the row (or one from another process) could run the same child
  too. The durable claim is now the single gate; a refused caller hands its
  in-process spec back.
- A continue that raised before record_start() (credential lease, heartbeat,
  registration, or a never-started queued child) left its row `claimed` by a live
  pid. The continued child carries its claim and every such exit releases it.
- claim() never reclaimed a dead owner's running/claimed row after boot recovery.
  It now runs the owner-liveness check and finishes the row the way boot recovery
  does, re-checking the same dead owner inside one BEGIN IMMEDIATE transaction.
- Boot recovery ran the pin git probes inside its open write transaction. The
  dead rows and their pin paths are planned first, lock-free; the write re-checks
  each row is still that owner's before finishing it.
- The durable session_id was never refreshed (compression.in_place: false moves a
  child to a new segment). record_stop stores the segment it stopped in, and a
  continue resolves the child's newest owned segment (stored_child_session), which
  also covers a crash before record_stop.
- The cross-profile pin scan applied the caller's max_resumable to every profile.
  Each profile's cap is now read under its own scope.

Also pins the should-fix finding (resumable isolated child's worktree pruned by its
own finalize), already fixed in f8923f30, with the reviewer's test for the
usage-limit (AUTO_AT) and provider-failure (ON_FIX) causes.
2026-11-11 22:10:25 -08:00
Eva
13d64710b4 fix(delegate): continue handle in sync results, no resume while stopping, keep ancestor ownership
Addresses review on #145331:
- Synchronous and fallback result entries carry the child's subagent_id, so a waited-for child can be continued.
- The retained record is "stopping" until the worker has exited and its close, kernel and Relay cleanup ran; continue
  refuses it with a retryable message. Ownership is checked outside the registry lock; the state check and claim are
  atomic under it.
- Retained records keep the trusted ancestor owner set (parent-ref chain, max 8 hops), merged across continuations, so
  a root can continue a finished grandchild and the original spawner keeps access. Foreign callers are still refused.
2026-11-11 22:10:25 -08:00
liuhao1024
76d4f14ec7 fix(desktop): join delegate cards by delegation id, not a repeated goal
Every delegate card ran its own fuzzy pass over the session's live
subagents (goal text, then task order), so two delegations sharing a
goal string re-adopted each other's workers: a settled card repainted
with a newer call's running child, and the transcript filled with
copies of the same task (#136532).

Native children already stamp the call's delegation id, and the
background dispatch handle already returns it; only the settled
combined result lacked it. Add it there, and make the card prefer the
exact (delegation id, task index) join. A row that knows its
delegation id no longer falls back to the fuzzy joins — an unmatched
live child is another call's worker, and a fuzzy join would only
misfile it. Old results without the id keep the previous behavior.

(cherry picked from commit dc4743cf8c26639ede247e9b5f3022a156e42899)
2026-11-06 19:39:15 -05:00
Teknium
fbec17e9e2 fix(delegation): background siblings outlive a parent stop; a gate-skipped child is released
Review findings "Background batches lose siblings on a foreground interrupt" and
"A sibling skipped by the gate is never detached or closed":

- _run_gated now takes honor_parent_interrupt and passes parent=None for a
  detached (background) unit, so stopping the parent's foreground turn no
  longer cancels siblings still waiting on the prompt-cache warm-up.
- A child the gate skips never reaches _run_single_child's finally, so it is
  detached from parent._active_children and closed before its entry is built.
  The same teardown runs for futures the parent-interrupt path cancels while
  they were still queued behind max_concurrent_children (never started).
- Document that the leader is always task 0 (docs + code comment).
2026-11-04 21:50:30 -08:00
Teknium
6d0686ba3c feat(delegation): opt-in prompt-cache warm-up gate for batch subagents
Sibling subagents in one tasks batch send byte-identical tools[] and system
prompt scaffold; only the goal (their first user turn) differs, plus the system
prompt tail when tasks carry different context. Started together, every
child's first request misses the provider prompt cache and pays the full prefix.

delegation.prefix_stagger_seconds (default 0 = off) now holds the siblings on
the first child's route until that child's first response starts streaming
(its request has written the cache), it finishes, or the cap elapses (max 60 s).
The wait ends as soon as the cache is readable, so opting in costs about one
time-to-first-token instead of a fixed (N-1)*S ramp. Routes Hermes does not
prompt-cache and siblings on a different model start without waiting, and a
sibling stopped during the wait is reported interrupted without starting.

Rebuilt on the split delegate_tool_* layout: the gate is its own sibling
(tools/delegate_tool_prefix_gate.py); dispatch only wraps run_child.
2026-11-04 21:50:30 -08:00
Teknium
2d0bf91f11 fix: every /bg entry point joins its background delegations in the run
The gateway /bg fix above covered messaging chats only. The shared-owner
/bg (prompt.background, used by the CLI, TUI and Desktop) and the classic
local CLI /bg run the same detached bg_* side agent, and on main a
background delegate_task there also leaves a completed ledger row pending
forever: nothing wakes or drains a bg_* session. Their side agents now
declare the channel stateless, so the batch runs inline and the result is
in the one answer /bg reports. The sync-fallback note names /bg.

Refs #140569.

Co-authored-by: milnerrad <302432023+milnerrad@users.noreply.github.com>
2026-11-01 21:11:06 -08:00
Victor Kyriazakos
fa2befeed7 fix(gateway): join delegations in the turn when interim messages are off
On a messaging chat with display.interim_assistant_messages off, a top-level
delegate_task still produced two messages: a "checks are running, I don't have
the findings yet" reply and, later, the real answer. Top-level model
delegations always run in the background (ea8a8b4af8), and the tool text tells
the model to "give a one-line status and END YOUR TURN" (c89f3b8800). That
status is the turn's final answer, not interim text, so no display setting
held it back.

New key delegation.gateway_mode: auto | inline | background (alias async).
auto (default) joins the children inside the turn on a messaging chat whose
resolved interim setting is off (global, display.platforms.<p> override or
platform default). The parent waits in the tool call, gets the results there
and sends one answer. API, local and webhook surfaces keep the background
path under auto. Chats with interim messages on are unchanged: same schema
bytes, same async dispatch.

How it works:
- The gateway resolves the mode from the turn's own profile-scoped config
  when it builds a session's agent (gateway/session_execution.py), and the
  agent's first tool build freezes it (like the one-shot pin).
- An inline session carries the joined delegate_task variant the one-shot
  path already uses: "results return in this tool call", no live-control
  parameters, no END YOUR TURN.
- Dispatch follows the delegate_task schema the session carries
  (session_joins_delegation), so schema and behaviour cannot disagree. The
  schema rides the session's tools[] pin: a config change applies from the
  next session (/new), as delegation.backend does, and a cache eviction or
  restart never flips a running chat.
- Inline children run on the existing synchronous path: attached to the
  parent, so /stop and an interrupting follow-up stop them; the per-child
  heartbeat keeps the parent's activity fresh for the inactivity watchdog;
  the async completion registry is not used. Nested and one-shot delegation
  are unchanged.

Refs #95522.
2026-10-28 19:35:16 -07:00
Teknium
9d558a14a1 fix(delegation): a one-shot-started session joins children on interactive turns
A `hermes chat -q` session resumed interactively keeps its pinned one-shot
delegate_task schema (children "are joined and return in this tool call", no
list/steer/stop) because tools[] must stay byte-stable, but dispatch decided
per admission and detached the children on the finite=False turn. Dispatch now
reads the agent's frozen one-shot pin (agent_is_oneshot) and joins inline.

Follow-up to #144177 (independent review D1).
2026-10-24 18:45:02 -07:00
Teknium
2463bdcbba feat(delegation): an unusable backend fails closed, an unroutable task is refused alone
A configured delegation.backend that is not installed or reports unavailable no
longer runs children on the default route: delegate_task returns a tool error
naming the backend and the fix. Within a batch, a task its backend cannot route
(enum miss, DelegationRouteError, unknown reasoning_effort, unoffered tier,
unresolvable credentials or profile) is refused alone: no child is built, its
result entry carries the error and route.refused, and its siblings run; the call
is a tool error only when every task is refused. A non-profile backend route
without its own fallback_providers inherits delegation.fallback_providers. Every
backend-routed result's route names the backend, and fallback_activated shows
when a fallback provider took over.
2026-10-22 14:37:10 -07:00
Teknium
71fa6e176a fix: async delegation completions name the inherited child model
With delegation.model blank (children inherit the parent model), the
completion header read creds["model"] (None) and printed "Model: ?".
Fall back to the model the built children actually run on.
2026-10-18 20:17:19 -07:00
Teknium
65bec86e37 Merge origin/main (#27: 19 commits to 517b5e10fe) into feat/unified-gateway-runtime
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 12:09:24 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
1e500ebce2 Merge origin/main (#16: 4,465 commits to 9dcab1e440) into feat/unified-gateway-runtime
99 conflicted files resolved in nine area lanes (Desktop composer, Desktop renderer/shared
client, Electron main, Ink, tui_gateway, gateway, state, CLI/config, cron/tools/CI). The
unified runtime's architecture wins where it deliberately replaced a mechanism (pool,
fallback lanes, claim poller, renderer queue); every orthogonal main change is kept, ported
into the <stem>_<topic> sibling that now owns relocated code.

Notable ports and repairs in this merge:
- tui_gateway/server.py relocated regions: atomic _attach_built_agent (#49852), slash ranking
  registry names, minted-key helpers methods_session.py calls, request_overrides, service tier.
- gateway/run_turn*.py: i18n accessors for the removed reply constants, first-contact
  internal/DM rule, rotated-compression persist, fast-mode tiers, prompt-pin rehydration.
- webhook: route_from_chat_id decodes main's opaque webhook:v2 chat ids (old ids still read).
- ws.py: main's per-connection dispatch queue with authority-first dispatch inside it.
- state: schema event for runtime revision renumbered to 31; worker mirrors updated for
  main's message uid/merge fields, on_contended lease arg, compression columns.
- config: branch's bot_chat_delivery_timeout removal renumbered v47 -> v50.
- Electron: primary-profile pin, redirect header scoping, remote fetchJsonForBackend, SSH
  teardown on profile delete, held-update dial gate restored (lost in earlier merges).
- Desktop: canonical clarify.request mapped to main's questions[] card; replay truncation vs
  snapshot_required; periodic secondary prune tick restored; DELETE already_absent restored.
- cron/tools: diagnostic category on cron failure notices restored; owner_holds_delivery
  ported onto the authority; admitted receipts can no longer be cancelled locally.
2026-10-06 14:24:24 -07:00
liuhao1024
5738723025 fix(delegation): surface the skipped home pin and prune the pinned root
Review follow-ups on the profile-home pinning (#91996):

- extract _parent_live_home() and log a WARNING when the parent exposes
  no _session_db: the ambient fallback is exactly the #91996 failure
  mode, so the skipped pin must be diagnosable instead of silent
- prune_stale_live_dirs now accepts the root and create_live_transcripts
  passes the same resolved root it writes to — previously retention
  always swept the ambient root, so stale dirs under a pinned home were
  never cleaned by its own dispatches
- module docstring documents the per-root retention scope
- new tests: no-_session_db parent warns and returns None, db-path
  parent pins, and a pinned-home dispatch prunes its own stale dir
  while leaving the ambient root alone
2026-10-02 21:49:36 -05:00
teknium1
25c1b008c8 feat(telemetry): wire memory, curator, delegation and backend call sites
- memory tool: one row per operation (a batch counts each op); gate/validation
  refusals are "rejected", store-level non-application "failed". Memory provider
  tools are counted in MemoryManager.handle_tool_call with the op read from the
  action arg or tool-name verb.
- curator: run_curator_review records one row per pass (dry run = skipped) with
  the before/after diff bucketed; a scheduled pass whose claim is held by another
  process counts as skipped. The home is captured before the review thread starts.
- delegate_task: _run_batch opens the call, each joined unit folds its results in,
  and the last unit emits the call's single row, so group-split background calls
  are not counted per unit.
- terminal / execute_code / browser: counted per call that reached the backend;
  the backend is resolved from the owning profile at call time (terminal plan
  env_type, code local/remote, browser CDP > Camofox > cloud provider > engine, or
  "extension" when the extension controller served the call). Guard refusals and
  Hermes' own _host_local commands are not counted.

Tests read rows back from the real store; each call-site group is red with its
source reverted.
2026-09-28 12:43:03 -07:00
teknium1
eec5bd6673 Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
4,048 upstream commits (Sep 16-23) composed onto the unified gateway runtime by six
per-domain conflict lanes (gateway, desktop/shared, cli/state, cron, bots/tui_gateway, ink).
Retired lanes stay retired (Desktop secondary pool + exit supervisor, deferred Bot Chat
pending queue, subprocess retry adoption); main's gateway.standalone, host-role claim,
clarify capability gate, config-read caches and idle gates ride on top.
2026-09-23 03:25:31 -07:00
funky-xamarin
21e3fa6b85 fix(delegation): retain recovery transcript locators 2026-09-20 09:52:22 -07:00
finn763
56a262cd06 fix(delegation): a one-child detached unit keeps its finished child on owner death
`recover_abandoned_delegations` only replays recorded children of a unit, and only
the >1-child join path ever called `record_unit_child` (c5594ec4b3 wired it into
`_run_children_parallel`). The single-child branch of `_execute_and_aggregate` ran
the child with no durable record at all, so a background `delegate_task` with one
goal — the default shape, and every ungrouped unit under `independent_completions` —
lost a finished child whenever the owner died between the child's return and the
durable completion write (OOM-kill on Linux, orphaning elsewhere, and everything
after the child returns is owner-lifetime: host-owned finalize, transcripts, manifest,
then the write). The parent got the bare "outcome unknown" and the work was gone (#116000).

`_record_finished_child` is now the one place that decides to durably record a finished
child of a detached unit; the join loop and the one-child branch both call it.
No new rows, no new consumer shape.

Tests: tests/tools/test_async_delegation.py::test_one_child_unit_keeps_its_finished_child_when_the_owner_dies
2026-09-20 09:52:22 -07:00
beardthelion
e24e66c6d0 fix(tools): do not join wedged delegate workers on the interrupt path
_run_children_parallel polled futures and fabricated interrupted entries
for pending children, but the executor's with exit then joined every
worker - a child parked in an uninterruptible call held the parent
thread forever, defeating the interrupt fast-path. Switch to an explicit
DaemonThreadPoolExecutor and shutdown(wait=not interrupted,
cancel_futures=interrupted) in a finally, matching the moa_loop shape;
abandoned children unwind on their own heartbeat and deferred-close
transport drain, and cancelled queued children never start.
2026-09-19 23:50:14 -07:00
teknium1
43c477571e Merge origin/main (61154b6f68) into feat/unified-gateway-runtime
1,446 upstream commits; 84 conflicted files resolved per family, porting
every post-branch main fix onto the cutover architecture rather than
dropping it or resurrecting replaced pre-cutover code:

- gateway/cron/kanban/a2a: #111988 hygiene bound, silence-marker rejection,
  UX copy, clarify-card retirement on explicit no-answer, Slack task-card
  publication_suppressed, webhook per-route coalescing (wrapping the durable
  admit_producer), kanban dead-worker last output + fingerprint boot witness,
  migrate-profile-identity control verb, SupervisedTickerThread, api-server
  terminal_run_status; config migration 45 kept from main, ours renumbered 46.
- hermes_cli/hermes_state/tools/tui_gateway: read_only SessionDB alongside
  explicit db_path, sessions_cmd observational flag, #111958 served-profile
  skips service install, #111999 usage source upsert repair, archived Bot Chat
  title release, find_canonical_owner, #111151 serves_routed_profile MCP scope,
  session_search after/before/exclude, server.py hunks into session_registry/
  agent_factory siblings, #111775 runtime_check resolve hook, Bot Chat
  silence rule on delivery reply.
- Desktop/apps/shared: pool modules stay deleted; SSH teardown fencing,
  default-profile + peer-window routing, per-session remote headers,
  server->client requests, generated gateway contract with our owner stamps
  and session.replay_gap retained.
- Ink: canonical WebSocket client kept; storedSid reconnect recovery, server
  request store, generated contract types, plain-language copy ported.
2026-09-16 13:20:14 -07:00
teknium1
23036e20a6 fix(ux): plain-language, actionable user-facing messages (core)
Squashed integration of the user-facing message audit for this surface set.
Full per-finding receipts: /tmp/ux-audit/lanes/*-receipt.md (campaign artifacts).
2026-09-15 04:12:13 -07:00
teknium1
45ab3ad57f fix(delegate_task): return a schema-invalid child's raw text instead of failing the task
When a child's final answer still missed its output_schema after the one
bounded retry, the result entry flipped to status=failed with the error
"Final answer does not satisfy the declared output_schema" — the completion
line printed ✗ and orchestrators read a finished audit as a failure. Five
audits of 413-4103 s were lost this way in the Sep 10-14 retrospective and
the parent had to mine the live transcripts; in four of them the "violation"
was a ```json fence around a valid array, which the candidate extractor
sliced to its first..last object.

Now: status stays completed, `summary` is the child's raw final text,
`schema_valid: false` + `schema_errors` carry the verdict and a `schema_note`
says the text is unvalidated; the sync completion line shows ⚠ with the
reason. The extractor tries the earliest-opening bracket span and keeps the
first that parses (fenced arrays validate). The OUTPUT CONTRACT the child
sees now says "ONLY the JSON value — no prose, no code fence" and what a miss
costs. One bounded retry is unchanged.
2026-09-15 03:45:41 -07:00
teknium1
60559d4e0e fix(delegation): late-attached children take the parent's soft/hard stop kind; dedupe the fallback replay
_attach_child now mirrors a pending parent stop with the same split
interrupt() uses for its own fan-out (hard -> hard_interrupt, soft ->
interrupt), so a redirect is not turned into a cancel on a child that was
attached late. _restore_parent_cancellation collapses to re-attaching the
rejected unit's children: the replay is the attach step's job now.

Test fixture: _Batch gained origin_session_history_delivery on main after
the salvaged PR was written.

Co-authored-by: illidan <noequal666@gmail.com>
2026-09-13 21:31:57 -07:00
illidan
946111cb11 fix(delegation): restore parent cancellation for rejected async units 2026-09-13 21:31:57 -07:00
Teknium
5977ef75fd fix: join finite gateway chat delegations in the admitted turn 2026-09-10 09:17:48 -07:00
Victor Kyriazakos
49ef015ca3 fix: join delegated work before finite chat exits 2026-09-10 05:02:41 -07:00
Teknium
d5926b2494 fix: persist API delegation units once without waking the model 2026-09-09 10:55:32 -07:00
liuhao1024
dffc0fa2d5 fix(gateway): require wake-capable session provenance for background delegate_task (#98619)
Rebuilt against the post-refactor owners: the chat-completions route now
lives in gateway/platforms/api_server_openai_routes.py, the wake gate in
tools/delegate_tool_dispatch.py, and session_context.py was reshaped —
the original patch aimed at code main no longer has.

Header-less OpenAI-compatible clients get a fingerprint-derived session
id bound as the api_server chat_id. delegate_task's background gate
treated ANY bound session id as wake-capable and dispatched detached
subagents, but for derived ids the wake self-post lands in a session
whose history the client never reloads — the result is undeliverable by
construction.

Bind a wake_capable provenance flag at session-bind time, DEFAULT-DENY
at the central boundary (set_session_vars and _bind_api_server_session
both treat an omitted declaration as denied; a binder that says nothing
grants no wake authority): "1" only from audited producers whose client
can address the id again (explicit X-Hermes-Session-Id — 403-gated on
API_SERVER_KEY — native /api/sessions/{id} routes, /v1/runs); "" for
fingerprint-derived ids. The delegate gate requires the flag (fail-closed,
captured pre-child-construction alongside origin_wake_sid) and keeps the
forced-sync fallback with its honest note.

Reported-and-investigated-by: shojikumaru (Sho + Alpha) via #98619
2026-09-09 10:55:32 -07:00
Teknium
869228cab4 feat(delegation): surface process accounting as top-level process_notes in the sync result; add live stress harness
Stress run with a real orchestrator subagent showed the per-task keys buried in results[] were not relayed
upward; the same prose lines now sit at the top of the sync delegate_task result. evals/subagent_process_handoff/
stress_handoff_live.py runs 12 real parent+child scenarios (handoff, orphan, unread, clean read, cap, exited refusal,
mixed fan-out, parent controlling the inherited process, sibling theft incl. adversarial, nested orchestrator,
5-way burst) and scores them against runtime accounting, never model prose.
2026-09-07 12:50:29 -07:00
Teknium
c89f3b8800 fix(delegation): one completion per call by default; queued units no longer stalled; tell the model results land between turns
Three orchestrator failures traced through the Sep 7 gpt-6-astra campaign sessions:

1. delegation.independent_completions (new, default false). #104299 made every
   ungrouped task its own completion message, so a 15-task call woke the
   orchestrator up to 15 times; one chain received 132 notices and answered
   130 of them with "already incorporated". A multi-task call now returns as
   ONE consolidated message unless the flag is on; `group` is inert until then.

2. Queued units were killed before they started. Units of one call share a
   pool slot but the executor was still sized by slots, so with 15 units live
   a new unit queued behind a full pool; the stale monitor's clock ran from
   dispatch, interrupted it at 450 s, and the child exited `interrupted 0.02s`
   when its thread finally came up (13 such lanes in one session). The
   executor now grows to the number of live units and the stall clock arms
   when the runner actually starts.

3. The tool text said "do not wait or poll — just continue" without saying
   that completions are delivered only BETWEEN turns. A model that never ends
   its turn (one 203-minute turn, 717 API calls) never received 40 finished
   results. Tool description, dispatch note and completion header now say to
   finish independent work, give a one-line status, and end the turn.
2026-09-07 06:46:54 -07:00
Teknium
14c3101256 merge main: notice rides the per-group unit (unit_id, n_here); drop the detached kwarg main removed 2026-09-06 12:09:49 -07:00
Teknium
d0090a147c Merge remote-tracking branch 'origin/main' into fix/async-batch-task-failure-notice
# Conflicts:
#	tools/delegate_tool_dispatch.py
2026-09-06 12:07:50 -07:00
Teknium
c5594ec4b3 fix(delegation): a crash mid-unit keeps the children that already finished
Since #104299 a background delegate_task call is split into completion units
(one per `group`, one per ungrouped task). A multi-child unit still joined on
all its children before anything was written durably, so an owner crash
between the first and last child lost the finished work and replayed the whole
unit as "outcome unknown" — the restart-granularity gap that #104233 (Xipong's
#76228/#76229 direction) solved with a second row per child.

Each finished child of a detached unit is now recorded on the unit's OWN row
(`record_unit_child` → result_json {results, partial}) as its future lands;
the real result overwrites it at finalize. `recover_abandoned_delegations`
replays recorded children with their real summaries and marks only the
unfinished ones unknown, naming the count. No new rows, no new consumer shape.
`task_indexes` is persisted so recovery knows a split unit's members.
2026-09-06 09:21:58 -07:00
Teknium
028fe2c4c8 feat(delegation): per-task completion groups — ungrouped subagents return as they finish
A background delegate_task call used to be ONE async unit: the runner joined on
every child and a single consolidated message re-entered the conversation when
the SLOWEST finished. Fifteen independent PR reviews therefore waited on the
fifteenth before the parent could act on the first.

Each task now carries an optional `group`. `_units_of` partitions the call's
children into units — one per distinct group, one per ungrouped task — and each
unit is dispatched to the async registry on its own, so its results re-enter the
conversation as soon as THAT unit is done. Tasks that must be compared or merged
share a group and still return together.

Capacity is unchanged: every unit of one call joins the first unit's pool slot
(`slot_key` in `async_delegation._dispatch`), so splitting never consumes more of
`delegation.max_concurrent_children` than the call did. Unit ids suffix the
call's id (`deleg_xxxx-1`, `-2`, …) so live transcripts stay under one dir; the
completion block names the group and notes that sibling units report separately;
`active_task_count` counts a unit's own tasks.
2026-09-06 07:17:30 -07:00
Teknium
0cb996d977 fix(delegation): number delegation batches per conversation, not per process
`format_batch_tag` handed out `set N` ordinals from one process-wide table,
so every conversation on a shared backend and every child's nested fan-out
advanced the same counter. A user's second wave of 15 lanes rendered as
`[set 20 · 13/15]`, which reads like 20 batches were spawned.

Scope the ordinal table by the parent conversation (`parent_agent.session_id`)
and thread the parent through the three render sites (batch header,
completion lines, child tree-line prefix via the shared session_ref). The
first fan-out in a conversation is `set 1`, the next `set 2`; sibling
conversations and nested child batches no longer inflate it.

Invariant test proven red on origin/main, green with the fix.
2026-09-06 05:03:20 -07:00
Teknium
6767c06d34 feat(delegation): a failed child of a still-running detached fan-out is surfaced to the parent immediately
Batches join on the slowest sibling before ONE consolidated block re-enters
(the design: one results block per fan-out). Failure is the case that
should not wait. In the 1,393-agent refactor run every wave-1 child died in
the 08:29 401 storm; the parent learned of it at 09:36, when the batch's
"unknown outcome" block finally arrived: 66 minutes of a dead wave with
nothing running, the single largest idle gap of the run.

_run_children_parallel, for DETACHED batches only (the sync path prints a
completion line the parent is already watching), pushes ONE
type="async_delegation" event with task_failure_notice=True and a
single-entry results list when a child ends in a failure status while
siblings are still pending. Same event shape and routing fields as the
batch result, so every drain/ownership/format path treats it identically;
the batch record is not finalized and its consolidated result still
arrives unchanged. The formatter renders
"[ASYNC DELEGATION TASK FAILED — <id>, task i/n]" with the task, status,
error and live transcript path, and says the batch result is still coming.
The TUI dedup key distinguishes a notice from the final result and from a
sibling's notice.

Live through the real detached dispatch (3 children, one fails at 0.1 s,
two succeed at 8 s): notice drained at t+0.3 s, batch final at t+8.4 s. On
main the parent hears nothing until t+8.4 s.

Tests (2): the notice reaches the queue with the record's routing fields
while the record stays running, and formats as an early warning; no notice
for a finished batch; dedup key differs from the final result.
Delegation/registry/notification suites (129 files) 1,344 passed.
2026-09-05 01:55:22 -07:00
Teknium
14791b4d4e simplify(compat): approval — drop 43 facade re-exports + _command_detection_variants late-bind seam, repoint 30 callers + 46 test files
tools/approval.py no longer re-exports sibling names (approval_context/prompt/floors/detection/
human_wait/smart/gateway_wait); it imports only what it uses. Siblings reference sibling-defined
names directly (module-attribute reads on tools.approval_context so patching the defining module
still works); only facade-owned state (_lock, _gateway_queues, _permanent_approved, _denied,
_denial_breaker_addendum, _gateway_notify_cb) is still read back through tools.approval.
approval_detection calls its own _command_detection_variants instead of late-binding through the facade.
2026-09-03 13:49:57 -07:00
Teknium
e83816a4d1 review-fix(comments): restore lost #NNNN rationale comments across non-test source (mechanical sweep, condensed, code unchanged)
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.
2026-09-03 09:44:26 -07:00
Teknium
2609eafb9b refactor(delegate): dispatch notes as a constant table; payload byte-identical 2026-09-02 19:56:03 -07:00
Teknium
9cf7c74030 refactor(delegate): module headers condensed (one-line docstrings, logger comment inline) 2026-09-02 19:43:56 -07:00
Teknium
defca3639a refactor(delegate): reflow comments/docstrings to 118 cols (word-identical, AST-identical) 2026-09-02 19:25:04 -07:00
Teknium
1283ccd855 refactor(delegate): docstring compaction by hand (every rule/why kept) 2026-09-02 19:16:07 -07:00
Teknium
eabec2ff50 refactor(delegate): AST-identical re-layout pass 2 2026-09-02 19:04:50 -07:00
Teknium
089d1aa296 refactor(delegate): dispatch — _Batch.run_child, one future-entry resolver, inline transcript finalize 2026-09-02 18:52:58 -07:00