Commit Graph

85 Commits

Author SHA1 Message Date
Teknium
b04f5a38bb docs(api): note browser-extension control's removal; point at browser.cdp_url
The API-server section now says the controller protocol is gone and that browser_exec over CDP
(`browser.cdp_url` / `/browser connect`) is how to drive your own browser; the integration
guide's endpoint list and link follow, and the metrics table marks `extension` as a legacy label.
2026-10-23 01:42:31 -07:00
Teknium
0b69853adf docs(browser): browser_exec is the only browser path; Camofox is a plugin
Rewrite the browser feature page, configuration, tools/toolsets/env-var/pm
references, docker, windows, bot-screen, termux/installation and the secondary
developer-guide/integration/feature pages (EN + zh-Hans): drop agent-browser,
the built-in browser_* tools, browser.backend and /browser use; document
browser.executable_path / browser.user_data_dir / browser.chromium_args and the
AGENT_BROWSER_* migration; point Camofox users to 'hermes plugins install camofox'.
2026-10-23 01:41:25 -07:00
Teknium
8397dafbcc fix(api_server): a budget-exhausted chat turn reports "length", not "cancelled"
When a turn hits agent.max_turns, Hermes still makes one toolless call and
returns the agent's wrap-up of what it found. /v1/chat/completions mapped that
result (completed=false, not interrupted, no error) through the not-completed
fallback to finish_reason "cancelled" with hermes.error_code "agent_error", a
code reserved for user interrupts (f48d09563b). An integration that treats
"cancelled" as an abort discards a usable answer.

Budget exits (turn_exit_reason max_iterations_reached(...) / budget_exhausted)
now report finish_reason "length" with hermes.error_code
"iteration_budget_exhausted", streaming and non-streaming. Interrupted turns
keep "cancelled"; real failures keep "error". /v1/responses already reports
status "incomplete" for this case and is unchanged.
2026-10-22 12:49:48 -07:00
unsupportedpastels
f17021fbec docs(api-server): say how an Idempotency-Key conflict arrives per mode
The section said every conflict answers HTTP 409 admission_conflict. That
holds for Responses (JSON and streaming: the refusal is decided before the
stream opens) and for non-streaming Chat Completions. Streaming Chat
Completions admits inside the spawned agent task after the SSE response
has been prepared with status 200, so the refusal is the last chunk
(finish_reason "error", error.message "admission_conflict") followed by
[DONE]. The conflict statements now point at one per-mode description.

The replay paragraph also said an unreplayable retained admission always
gets admission_conflict. A Responses claim stored without its answer (as
an older release recorded it) gets 409 unknown_execution instead; the page
now names it and says it is not a reason to resend under a new key.

Refs #134889 (LC-16)
Refs #140208
2026-10-17 13:59:27 -04:00
unsupportedpastels
e6d5bbdb0d docs(api-server): list the Idempotency-Key conflict fields per endpoint
The exact-retry paragraph gave one shared field list that included
`tools`, implying a Chat Completions retry that changes only `tools` gets
409. Under session authority the Chat admission identity is the payload
{text, api_turn_v1.history, settings} (gateway/session_api_turn.py), and
`settings` is `_SETTING_KEYS`, which has no `tools`, `tool_choice` or
`stream`, so such a retry replays the original answer. Responses does
fingerprint `tools` (`_RESPONSES_FINGERPRINT_KEYS`).

Split the list by endpoint, say that `X-Hermes-Session-Id` takes Chat
history from the session, and state that delivery mode is outside the
identity on both endpoints, not only Responses.

Refs #134889 (LC-16)
Refs #140208
2026-10-17 13:59:27 -04:00
unsupportedpastels
5af27c1a15 docs(api-server): what an Idempotency-Key covers after a session delete
The API server page said only that Idempotency-Key responses are cached
for 5 minutes, which is the legacy in-memory path, and only for
non-streaming requests. Under the canonical session authority a key is a
durable admission identity, and what happens to it after
DELETE /api/sessions/{id} differs per endpoint.

A new "Idempotency keys" section states it: a key names one admission
scoped to the API profile and credential; an exact retry repeats the
turn-defining fields and declared target (Responses JSON and streaming
retries share one identity), and changing either answers 409
admission_conflict. Replay needs the retained request identity plus a
replay record or rebuildable terminal admission; without it the key
still never reruns while its admission evidence remains. Deletion
tombstones become prunable after 7 days and are removed only by a prune
pass, after which a Chat Completions key can name new work. Responses
replay can end earlier through bounded identity retention (current
default in a note) or response deletion. An explicit
X-Hermes-Session-Id is never remapped; a header-less chat that opens
like a deleted one gets a new session. The CORS bullet now links to it.

Documents the behaviour of #140232 (GW-12) and #140233 (LC-16); merge
after both.

Refs #134889 (LC-16)
Refs #140208
2026-10-17 13:59:27 -04:00
Teknium
77ee16fbfa docs(api-server): resolve-unknown repeat replays its receipt; refusal status codes
- An exact repeat of a committed unknown-run resolution returns the same
  receipt (200), as resolve_unknown_session_input and
  test_http_resolve_unknown_releases_follower_once_without_replaying_head
  already do; only a stale/non-integer generation or a run that is not unknown
  is 409 stale_generation. Malformed bodies are now 400 invalid_params.
- POST /v1/runs and the run controls: refused admissions keep no reservation;
  draining/retiring and a locked state database answer 503 with Retry-After;
  ownership/generation/identity refusals stay 409.
- Hosted-room homes resolve a member's unknown run on their next poll; older
  room homes do not know the status (release note for N85).

Review: ahrazzle B2-25
2026-10-11 19:31:34 -07:00
Teknium
e3dcd1ea20 fix(api): poll a paused canonical run as unknown, not terminal interrupted
Mechanism: run_projection mapped an admission in status `unknown` (claimed
before an authority-owner restart, outcome unknown) to `interrupted`, which is
in TERMINAL_STATUSES and documented as terminal. Stop refuses that run with
409 unknown_execution and followers stay queued until resolve-unknown, so a
poller stopped at a paused head and could not tell it needed resolution.

Fix: project `unknown` as `unknown` (non-terminal); the docs name the status
in the run-status paragraph and the resolve-unknown section.

Red on r12-base:
tests/gateway/test_api_unknown_resolution.py::test_http_poll_reports_unknown_head_as_non_terminal_until_resolved
polls GET /v1/runs/{id}, reads admission_id/execution_generation from that
body, resolves, checks the follower runs once, then polls terminal.

Patch by abundantbeing (issue comment 6103536385), applied as posted.

Co-authored-by: abundantbeing <222723615+abundantbeing@users.noreply.github.com>
Review: JoaoMarcos44 B31
Review: abundantbeing C-ab-5
Review: abundantbeing C-ab-6
Review: abundantbeing C-ab-7
(cherry picked from commit 9afa467d765ebc798b827b0f1b876c7e29e6deac)
2026-10-11 07:34:29 -07: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
Austin Pickett
7cadfaa668 fix(api_server): honour include_compacted on /api/sessions/{id}/messages
The gateway REST messages endpoint parsed limit/offset/order but never
read include_compacted, so clients always got the live post-compaction
transcript. Parse it like the dashboard router and pass it through to
SessionDB.get_messages.

Fixes #101939
2026-09-29 16:30:33 -04:00
teknium1
df0e4a9235 Merge origin/main (#13: 12 commits to 801a9022a7) into feat/unified-gateway-runtime
Conflict: tui_gateway/server.py — main edited _live_session_payload, which this
branch moved to tui_gateway/session_registry.py. Resolved to the branch side and
ported main's inline_images parameter (88039d73b3) into the moved function:
methods_session.py (auto-merged) now passes inline_images= on the live-reattach
resume path, which would otherwise raise TypeError.
2026-09-27 17:28:37 -07:00
Brooklyn Nicholson
9cd114b499 feat(web): inline_images=false on GET /api/sessions/{id}/messages
The REST pages carry message content verbatim so the desktop's
extractEmbeddedImages can pull data URIs out of the text; a client reading
over a network had no way to ask for less (26.33 MiB per page read on the
measured conversation). inline_images=false (default true) routes content
through the same _coerce_message_text(image_urls=False) projection
session.resume uses, rendering [image] in place of the data URI so both
history surfaces agree by construction. Documented in the api-server
reference.

Fixes https://github.com/NousResearch/hermes-agent/issues/116511
2026-09-27 19:06:26 -05:00
teknium1
c6dc7ab120 Merge remote-tracking branch 'origin/main' into feat/unified-gateway-runtime
Merge #8: 2,771 commits from main (4b05f764fa). Ports main's moved code into the
unified runtime (run.py/run_turn.py splits, tui_gateway server, backup/restore
split), keeps the detached-daemon Desktop lifecycle, and adapts main's new tests
to the owner/authority contracts (canonical session deletes, retired-id
tombstones, zero-writer browsing, hermes_yaml, platforms() markers).
2026-09-27 02:30:04 -07:00
luyifan
5af9ac8ed1 fix(api): classify failed tool stream events
(cherry picked from commit 5ab0a5ee26e61d4e96d65e1dacdc2b2e1e524f1b)
2026-09-25 21:30:22 +05:30
kshitijk4poor
eea4419ddc fix(api_server): honour platforms.api_server.tool_progress_events for Chat Completions SSE (#12020)
Strict OpenAI clients reject the named hermes.tool.progress SSE frames. Setting
tool_progress_events: false under platforms.api_server (loaded into
PlatformConfig.extra by from_dict) now drops them; default stays on.
Reimplements the intent of #42640 against the adapter config actually read in
production. Overlaps #49069 (erikerosev).

Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
2026-09-25 14:27:23 +05:30
teknium1
b0aa41586e Merge commit '09fbc27a4a93' into fix/106742-thread-resolution
# Conflicts:
#	apps/desktop/electron/backend-dial-claim.test.ts
#	apps/desktop/electron/gateway-file-download-transport.test.ts
#	apps/desktop/electron/pool-limits.test.ts
#	apps/desktop/electron/pool-spawn-coordinator.test.ts
#	apps/desktop/electron/quit-guard.test.ts
#	apps/desktop/src/app/chat/composer/controls.test.tsx
#	apps/desktop/src/components/notifications.test.tsx
#	apps/desktop/src/plugins/hermes-bots/group-chat-view.inline-code.test.tsx
#	apps/desktop/src/sdk/profile-routing.test.ts
#	apps/desktop/src/store/gateway-spawn-priority.test.ts
#	apps/desktop/src/store/profile.test.ts
#	gateway/run.py
#	gateway/run_turn.py
#	gateway/status.py
#	hermes_cli/dashboard_auth/ws_tickets.py
#	hermes_cli/web_routers/sessions.py
#	tests/agent/test_secret_scope_tier1_migration.py
#	tests/cron/test_bot_chat_delivery_child_env.py
#	tests/cron/test_bot_chat_warning_replay.py
#	tests/cron/test_codex_execution_paths.py
#	tests/cron/test_cron_bot_chat_delivery.py
#	tests/cron/test_cron_empty_payload.py
#	tests/cron/test_cron_mcp_toolset_empty_block.py
#	tests/cron/test_cron_memory_contract.py
#	tests/cron/test_cron_no_agent.py
#	tests/cron/test_cron_request_overrides.py
#	tests/cron/test_cron_workdir.py
#	tests/cron/test_run_one_job.py
#	tests/cron/test_scheduler.py
#	tests/cron/test_sessiondb_init_hang.py
#	tests/desktop/test_bots_chat_live_append.py
#	tests/gateway/test_api_server_runs_extraction.py
#	tests/gateway/test_approval_prompt_redaction.py
#	tests/gateway/test_auto_reset_clean_context.py
#	tests/gateway/test_auto_reset_evicts_cached_agent.py
#	tests/gateway/test_compression_deferred_soft_result.py
#	tests/gateway/test_compression_session_id_persistence.py
#	tests/gateway/test_control_socket_windows_live.py
#	tests/gateway/test_fallback_chain_reload.py
#	tests/gateway/test_model_switch_after_auto_reset.py
#	tests/gateway/test_session_hygiene.py
#	tests/gateway/test_warning_wiring_conservation.py
#	tests/hermes_cli/test_backup.py
#	tests/hermes_cli/test_chat_q_exit_clear.py
#	tests/hermes_cli/test_cli_preloaded_skills.py
#	tests/hermes_cli/test_cron.py
#	tests/hermes_cli/test_ensure_gateway_service.py
#	tests/hermes_cli/test_kanban_gateway_restart_handoff.py
#	tests/hermes_cli/test_observational_sessiondb_modes.py
#	tests/hermes_cli/test_profiles_sidebar_cache.py
#	tests/hermes_cli/test_sessions_export_md_cli.py
#	tests/hermes_cli/test_single_query_session_finalize.py
#	tests/hermes_cli/test_web_server.py
#	tests/hermes_state/test_hermes_state.py
#	tests/tools/test_bot_live_owner_delivery.py
#	tests/tools/test_bot_mode_dm.py
#	tests/tools/test_bot_retry_policy.py
#	tests/tools/test_bot_turn_lock.py
#	tests/tui_gateway/test_bot_live_owner_delivery.py
#	tests/tui_gateway/test_compute_host_turn_protocol.py
#	tui_gateway/server.py
#	ui-tui/src/__tests__/createSlashHandler.test.ts
#	ui-tui/src/__tests__/submissionCore.test.ts
#	ui-tui/src/app/useSessionLifecycle.ts
2026-09-23 07:47:09 -07:00
teknium1
eb8960fead fix(api_server): keep one memory provider per session across requests (#120116)
The api_server platform builds a fresh AIAgent per request (per-request
callbacks, model route, ephemeral prompt), so the memory provider was
re-initialised on every request. External providers deliver recall as the
PREVIOUS turn's background prefetch held on the provider instance, so a
continued session (X-Hermes-Session-Id, previous_response_id, declared
session key) never received automatic recall, and for hindsight
local_embedded each init also restarted the embedded daemon, killing the
retain still in flight. Pre-existing: the same probe fails on main before
the hindsight catalog migration (526d135a96, bundled provider).

ApiServerMemorySessions parks the session's initialised MemoryManager
between requests (exclusive check-out/check-in, keyed by profile home +
session id, LRU/idle eviction under the owning profile's scope) and
AIAgent(memory_manager=...) adopts it instead of loading and initialising
the provider again. /v1/chat/completions, /v1/responses, session chat and
/v1/runs all go through the same two seams (_create_agent, turn finally).
2026-09-23 05:41:31 -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
teknium1
6d335529ea fix(api_server): stamp the drain boundary on restart too; one HTTP-level invariant; docs
- request_restart() opens the same drain window as stop() (new turns refused,
  in-flight work awaited), so pollers of GET /v1/runs/{id} need the
  shutdown_requested_at marker from that moment as well; the marker is idempotent
  so stop() re-marking after the restart wait is a no-op.
- Collapse the three adapter-level tests into one invariant that drives the real
  GET /v1/runs/{id} route: live run keeps status=running but carries the marker
  (durably), a status set after the boundary inherits it, a terminal run never does.
- Shutdown-path fakes gain _mark_api_runs_shutdown_requested (the real mixin method
  where the fake already borrows _api_server_hook, a 0-stub where it has no adapter).
- Document the field on the runs API page.

Refs #115133.
2026-09-20 12:13:44 -07:00
teknium1
d19963782b fix(api-server): anchor the Responses current turn on this turn's user row, not a history prefix match
`_response_messages_turn_start_index` located the current turn by matching
`result["messages"]` against `conversation_history + [user]` row by row. The
loop repairs host-fed history before its first call (consecutive assistant or
user rows merge, orphan tool results drop) and compaction rewrites it, so the
transcript legitimately stops sharing a prefix with the client history; the
match then returned 0 and the WHOLE transcript was treated as the current
turn: earlier turns' function_call / function_call_output items were replayed
as this turn's `output` / `run.completed` turn_messages, and the stored
`previous_response_id` chain grew by another copy of the history every turn.

Anchor on the loop's canonical current-turn user index instead
(`agent.turn_context.reanchor_current_turn_user_idx`: last user row that
says this turn's text, else the last user-originated row), and keep the
semantic prefix match only for suffix-only results without a user row
(mocked/legacy paths). The boundary logic moves to the topical sibling
`api_server_turn_boundary.py`; the routes mixin delegates.

The dedupe test that asserted "divergent transcript => append history +
transcript" encoded the duplication itself; it now asserts the fallback for
the case it actually exists for (a suffix-only result).

Fixes #89891
Co-authored-by: heyf <tonyheyifan@gmail.com>
2026-09-19 12:11:23 -07:00
Teknium
3df8ad0d7f Merge pull request #115903 from NousResearch/fix/boa-res-R2-app-server-interim
fix(api-server): codex commentary reaches streaming clients on session SSE, /v1/runs and /v1/responses (#67580, salvage #67593 #67613)
2026-09-19 11:14:10 -07:00
teknium1
12cc17fd76 chore: merge origin/main (resolve gateway/platforms/api_server.py, gateway/platforms/api_server_openai_routes.py) 2026-09-19 10:54:05 -07:00
teknium1
6b415f8754 chore: merge origin/main (resolve gateway/platforms/api_server_openai_routes.py) 2026-09-19 10:51:28 -07:00
teknium1
6b5a8fad38 fix(api_server): emit the run record's runtime in the canonical _sanitize_runtime_metadata shape
/v1/runs published a thinner {provider, model} twin under the same wire key that
/v1/chat/completions, /v1/responses and the session chat stream fill via
_sanitize_runtime_metadata (route_source, requested, cleaned ids). Route the served pair through
the same classmethod so one concept has one schema; requested comes from the run's
requested_model/requested_provider overrides, route_source from the model_routes/raw/global
vocabulary the other endpoints use. Doc example updated.
2026-09-19 10:14:38 -07:00
Tranquil-Flow
1b02df86e3 fix(api_server): GET /v1/runs/{id} reports the served fallback runtime and cache-read tokens
GET /v1/runs/{run_id} and the run.completed SSE event only echoed the
requested model and three token counters. After a fallback_providers
switch the run record still named the requested model and usage had no
cache figures, so a supervisor polling /v1/runs for cost attribution
booked the whole run to the wrong provider at the wrong price, with
cache reads counted as full-price input.

agent.provider / agent.model still hold the fallback pair when
run_conversation() returns (the primary is restored only at the start of
the next turn), and agent.session_cache_read_tokens has the cache reads.
Surface them on the completed run status and the terminal event:

- usage gains cache_read_tokens / cache_write_tokens (_USAGE_FIELDS)
- _run_agent_sync returns the served {provider, model} as a third value
  and _finish stamps it as `runtime` on both the pollable status and the
  run.completed event (the persisted idempotent record inherits it).

Ported onto the refactored _run_agent_sync / _finish shape from #102161;
the served pair is read from the agent (the reporter's diff in #102101)
rather than the turn record, so a run whose result dict lacks the keys is
still attributed. Tests trimmed to two invariants.

Fixes #102101
2026-09-19 10:14:38 -07:00
teknium1
0a846a2e2d feat(api-server): reasoning on non-streaming replies; echoed reasoning input items are ignored
Follow-up to the streaming reasoning commit for #99552 covering the atoms it left open:

- Non-streaming `/v1/chat/completions` returns the turn's reasoning as
  `choices[0].message.reasoning_content`; non-streaming `/v1/responses` emits a
  completed `reasoning` output item ahead of the message (and ahead of that step's
  `function_call` items), so `GET /v1/responses/{id}` replays it too. The text is read
  from the assistant messages the agent already persisted (`build_assistant_message`
  stores it under `reasoning`) instead of re-accumulating `reasoning_callback` deltas:
  in non-stream mode the agent fires the callback per provider delta AND once more with
  the full text as the post-response fallback, so accumulating would double it.
- The Responses input parser skips `{type: "reasoning"}` items in `input` and
  `conversation_history`. Responses SDK clients replay a prior response's `output`
  list as the next `input`; before, the item became an empty `user` message (in
  `input`) or a 400 (in `conversation_history`).
- The streaming `response.completed` envelope carries the full reasoning item
  (`id`, `status: completed`) rather than a `{type, summary}` stub, matching the
  `output_item.done` item and the non-streaming shape.

Live (real route handlers, real AIAgent, fake OpenAI SSE model replaying
`delta.reasoning_content`): before — non-stream chat had no `reasoning_content`,
non-stream responses output was `[message]`, a chained turn echoing the output list
stored an empty user turn and the model saw a repaired placeholder; after — chat
`reasoning_content` equals the streamed text exactly, responses/GET output is
`[reasoning, message]`, the chained turn's model input is `[user, assistant, user]`.
2026-09-19 09:48:35 -07:00
teknium1
70cee9e092 feat(api-server): stream model reasoning on /v1/chat/completions and /v1/responses
OpenAI-compatible clients (Open WebUI, opencode, LibreChat, the Vercel AI SDK)
saw only answer text from the API server: the streaming writers never wired the
agent's structured ``reasoning_callback``, so reasoning deltas that every native
surface already renders were dropped at the transport boundary (#99552).

- `_spawn_stream_agent` passes a `reasoning_callback` (via `_run_agent` /
  `_create_agent`) that tags deltas `("__reasoning__", text)` on the stream queue,
  keeping them distinct from answer text. The lossy 500-char `reasoning.available`
  progress preview is deliberately not used.
- `/v1/chat/completions`: reasoning rides `choices[0].delta.reasoning_content`
  (the DeepSeek-style field those clients render as a thinking block).
- `/v1/responses`: each thinking burst is a spec-native `reasoning` output item
  (`output_item.added`, `reasoning_summary_part.added`,
  `reasoning_summary_text.delta/done`, `reasoning_summary_part.done`,
  `output_item.done`), closed before the next message/function_call item opens
  and echoed in `response.completed` output; `sequence_number` stays monotonic.
- `GET /v1/capabilities` advertises `features.reasoning_streaming: true`.
- Docs: api-server page documents the wire fields and the capability flag.

Gating is unchanged: nothing is emitted unless the model produces reasoning under
the resolved `reasoning_config` (`model_options.reasoning.enabled: false` opts out).
2026-09-19 09:48:35 -07:00
teknium1
01f3f90ad4 chore: stack on #115797 to resolve api_server.py / api_server_openai_routes.py conflict
api_server.py keeps both interim_assistant_callback (#115903) and reasoning_callback (#115797) in every _create_agent/_run_agent slot.
api_server_openai_routes.py keeps both _ResponsesStream method sets and both __commentary__/__reasoning__ tag branches; emit_commentary closes any open reasoning item first.
2026-09-19 03:35:41 -07:00
teknium1
67173a73cc fix(api-server): /v1/runs emits message.interim; display.interim_assistant_messages gates all surfaces
POST /v1/runs + GET /v1/runs/{id}/events now carries mid-turn assistant
commentary as `message.interim` {text, already_streamed} — the same
contract the TUI gateway emits — so Runs clients can tell an active,
tool-heavy Codex turn from a stalled one instead of seeing only tool.*
events until run.completed (#67580).

APIServerAdapter._create_agent applies the same
`display.interim_assistant_messages` gate the messaging gateway and the
TUI apply (resolve_display_setting, per-platform override honoured):
when off, no callback is installed and nothing leaves the agent on any
of the three streaming surfaces. Dedup of repeated commentary stays in
agent/stream_delivery.py, where every surface already relies on it.

Tests: /v1/runs event contract; session SSE + /v1/responses item shape
plus the display gate (both red on the base commit). Docs: event
payloads on all three surfaces.

Co-authored-by: RoySRose <sungwook0115.kim@gmail.com>
2026-09-19 00:59:21 -07:00
teknium1
004c8a51f0 feat(api-server): reasoning on non-streaming replies; echoed reasoning input items are ignored
Follow-up to the streaming reasoning commit for #99552 covering the atoms it left open:

- Non-streaming `/v1/chat/completions` returns the turn's reasoning as
  `choices[0].message.reasoning_content`; non-streaming `/v1/responses` emits a
  completed `reasoning` output item ahead of the message (and ahead of that step's
  `function_call` items), so `GET /v1/responses/{id}` replays it too. The text is read
  from the assistant messages the agent already persisted (`build_assistant_message`
  stores it under `reasoning`) instead of re-accumulating `reasoning_callback` deltas:
  in non-stream mode the agent fires the callback per provider delta AND once more with
  the full text as the post-response fallback, so accumulating would double it.
- The Responses input parser skips `{type: "reasoning"}` items in `input` and
  `conversation_history`. Responses SDK clients replay a prior response's `output`
  list as the next `input`; before, the item became an empty `user` message (in
  `input`) or a 400 (in `conversation_history`).
- The streaming `response.completed` envelope carries the full reasoning item
  (`id`, `status: completed`) rather than a `{type, summary}` stub, matching the
  `output_item.done` item and the non-streaming shape.

Live (real route handlers, real AIAgent, fake OpenAI SSE model replaying
`delta.reasoning_content`): before — non-stream chat had no `reasoning_content`,
non-stream responses output was `[message]`, a chained turn echoing the output list
stored an empty user turn and the model saw a repaired placeholder; after — chat
`reasoning_content` equals the streamed text exactly, responses/GET output is
`[reasoning, message]`, the chained turn's model input is `[user, assistant, user]`.
2026-09-19 00:46:31 -07:00
teknium1
064756ca45 feat(api-server): opt-in cap on tool outputs in the stored /v1/responses history
The persisted conversation_history snapshot embeds the cumulative transcript
with every tool output verbatim, so a few large tool outputs made a single
response_store.db write ~677 KB (2.7x the configured rotation threshold)
while the response.completed payload for the same turn was already trimmed.

Add gateway.api_server.history_tool_output_max_chars (default 0 = store
verbatim, current behaviour). When set, tool rows and string tool-call
arguments longer than N chars are cut to the head plus the same
"...[K more chars]" marker _trim_tool_items uses, in a copied row, before the
snapshot is stored; user/assistant text and the agent's own in-memory
transcript are untouched. Opt-in rather than default because the stored
history is exactly what the model is replayed on the next chained turn.

Live (200 KB tool output, temp HERMES_HOME): stored row 200,659 B off ->
4,681 B with the cap at 4000.
2026-09-19 00:44:22 -07:00
teknium1
b957782917 feat(api-server): stream model reasoning on /v1/chat/completions and /v1/responses
OpenAI-compatible clients (Open WebUI, opencode, LibreChat, the Vercel AI SDK)
saw only answer text from the API server: the streaming writers never wired the
agent's structured ``reasoning_callback``, so reasoning deltas that every native
surface already renders were dropped at the transport boundary (#99552).

- `_spawn_stream_agent` passes a `reasoning_callback` (via `_run_agent` /
  `_create_agent`) that tags deltas `("__reasoning__", text)` on the stream queue,
  keeping them distinct from answer text. The lossy 500-char `reasoning.available`
  progress preview is deliberately not used.
- `/v1/chat/completions`: reasoning rides `choices[0].delta.reasoning_content`
  (the DeepSeek-style field those clients render as a thinking block).
- `/v1/responses`: each thinking burst is a spec-native `reasoning` output item
  (`output_item.added`, `reasoning_summary_part.added`,
  `reasoning_summary_text.delta/done`, `reasoning_summary_part.done`,
  `output_item.done`), closed before the next message/function_call item opens
  and echoed in `response.completed` output; `sequence_number` stays monotonic.
- `GET /v1/capabilities` advertises `features.reasoning_streaming: true`.
- Docs: api-server page documents the wire fields and the capability flag.

Gating is unchanged: nothing is emitted unless the model produces reasoning under
the resolved `reasoning_config` (`model_options.reasoning.enabled: false` opts out).
2026-09-18 23:58:24 -07:00
teknium1
2fbcd8b0ea docs(website): link pages by relative Markdown path so they open on GitHub (#114428)
Mechanical `check_doc_links.py --fix` pass over website/docs (hand-authored
and generated pages) and the zh-Hans mirror: 1,868 route-style links
(`](/section/page#anchor)`, `](/docs/...)`) become `](../section/page.md#anchor)`.
Every target was asserted to exist on disk; anchors and query strings are
preserved; fenced code blocks and inline-code examples are untouched.

Two dead targets found by the converter were fixed by hand first:
memory-providers.md linked `/user-guide/plugins` (page is
`user-guide/features/plugins`), and the zh-Hans learning-path still linked the
removed `rl-training` page — ported the EN treatment (external Atropos link).

Docusaurus build after: EN locale 0 unresolved Markdown links, 0 broken links,
0 broken anchors.
2026-09-18 14:27:04 -07:00
teknium1
5811653914 fix(api): a run admitted but not yet started settles interrupted at shutdown
The salvaged mark-then-interrupt path covers every run whose agent exists.
A run whose executor task was created but has not taken its first tick has
no agent to interrupt: _execute_run would re-persist `running` over the
shutdown mark and start a full turn that outlives the gateway (only forced
to `interrupted` when it finally returned). Check the shutdown set before
the `running` transition and finish immediately.

Docs: `interrupted` joins the terminal status vocabulary for /v1/runs.

Co-authored-by: Mark Rockminster <markrockminster@M1-U-48-128.local>
2026-09-18 09:24:21 -07:00
teknium1
1958b2a146 Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
# Conflicts:
#	apps/desktop/src/sdk/index.ts
#	apps/desktop/src/store/profile.test.ts
#	cron/bot_chat_delivery.py
#	cron/scheduler_delivery.py
#	gateway/run.py
#	tests/cron/test_bot_chat_pending.py
#	tests/cron/test_cron_bot_chat_delivery.py
#	tests/tools/test_bot_live_owner_delivery.py
#	tests/tools/test_bot_turn_lock.py
#	tests/tui_gateway/test_bot_relay_methods.py
#	tools/bot_live_delivery.py
#	tui_gateway/methods_bot_relay.py
#	tui_gateway/transport.py
2026-09-16 17:10:42 -07:00
teknium1
8d11af8497 docs(api-server): scope the concurrent-run cap to the routes that enforce it
The doc claimed the cap covers 'every endpoint that starts' a run, but
POST /api/jobs/{id}/run and /api/cron/fire start agent runs through the
cron scheduler, outside _run_agent, and are neither counted nor
429-guarded. Name the covered routes and say cron-triggered runs are
governed by cron's own limits so operators don't rely on a cap that
isn't applied there.
2026-09-16 17:05:32 -07:00
John Paul Soliva
9934972e21 fix(api-server): the session-chat routes spend the concurrent-run budget without respecting it
POST /api/sessions/{id}/chat and its /stream variant run their turn through _run_agent, so each
one already counts toward gateway.api_server.max_concurrent_runs. Neither ever called
_concurrency_limited_response, so the two routes could never be refused while their turns pushed
every other caller — /v1/chat/completions, /v1/responses, /v1/runs — into HTTP 429. A gateway at
its cap therefore refused the endpoints that check it and admitted the ones that do not.

Cross-machine agent DMs land on exactly these routes (hermes peer dm posts the turn to
/api/sessions/{id}/chat), so on a fleet gateway N simultaneous DMs started N full agent turns
regardless of the configured cap, each one an agent in its own executor thread.

Both routes now take the same guard the other run-starting routes take, before the session is
prepared. One table asserts the contract for the whole class: every route that starts a turn
answers 429 with Retry-After at the cap and starts no turn, and is admitted under it.

Docs: the cap's scope in the API server guide named only the OpenAI-compatible and Runs
endpoints, which is what the code did.
2026-09-16 17:05:32 -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
05fac10a75 docs(api-server): MCP trust-gate consent surfaces as approval.request on /v1/runs
Document that an untrusted-server write-capable MCP tool now parks a run in
waiting_for_approval and is resolved through POST /v1/runs/{id}/approval,
the same bridge dangerous-command approvals already use.

Part of #111526
2026-09-15 19:06:27 -07:00
teknium1
339fa6d918 fix(gateway): bounded redacted result preview on tool.completed run events
Slims the salvaged preview helper (drop the try/except around json.dumps —
default=str cannot raise on tool results) and documents the tool.completed
SSE shape. Adds the control test that the multimodal envelope dict is still
classified as a success, so the dict passthrough only widens the failure
detection to real structured results.

The idea of carrying the tool result on tool.completed for /v1/runs
consumers was first proposed in #22362; that PR's executor half
(result=function_result) is already on main, and its wire half is landed
here in redacted, bounded form instead of the raw payload.

Salvages #111821 (@KoNit-K), part of #111815.

Co-authored-by: kidrauhl123 <105764349+kidrauhl123@users.noreply.github.com>
2026-09-15 18:42:10 -07:00
teknium1
0a6c7b7fa3 fix(agent,gateway): report interrupted and unfinished turns truthfully
An interrupted turn left `finalize_turn` with a diagnostic `final_response`
("Operation interrupted: waiting for model response") and no failure, so the
result said `completed=True` — the only producer that did; `turn_recovery`
and `codex_runtime` already return `completed=False` for an interrupt and the
gateway stream gate documents that contract. `completed` now also requires
`not interrupted`.

The API server then hard-coded the terminal status: the session chat stream
emitted `assistant.completed {completed: true, interrupted: false}` and
`run.completed` for every turn that did not raise, and `/v1/runs` booked any
non-`failed` result as `completed` — including an interrupt that did not come
through `/stop` and a turn that ran out of iteration budget. Automation that
reads the run status or the terminal event saw unfinished work as delivered,
and `partial: true` could sit next to `completed: true` in one payload.

`api_server_runs.terminal_run_status()` is now the single mapping for both
surfaces: interrupted -> `cancelled`, failed/partial/`completed=False` ->
`failed` (with `turn_exit_reason` and the fallback text as `output`),
otherwise `completed`; the terminal event is always `run.<status>` and a
late `pending_steer` rides on every terminal status instead of only on
`completed`.

CLI exit codes (`-q` quiet mode, `-z` one-shot) are deliberately unchanged
here: `hermes -z` returning 0 whenever text was produced was a stated design
choice (093f567f0d) and scripts depend on it, so that flip needs a
maintainer decision.

Fixes the gateway/producer half of #111770; slimmer redo of #111785 by
@KoNit-K (same mapping idea, one helper instead of three ladders).

Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
2026-09-15 18:21:44 -07:00
teknium1
c5c71ea1ad fix(docs): document the 10 s SSE keepalive comment for custom parsers 2026-09-15 18:18:30 -07:00
unsupportedpastels
129c0ab02c fix(api): resolve unknown runs with durable owner scope
API callers need to acknowledge an interrupted admission after gateway
restart without switching to another client. Expose the authority's
existing generation-fenced resolution through POST /v1/runs/{run_id}/resolve-unknown,
leaving ordinary stop and A2A semantics unchanged.

Persist the existing opaque owner scope inside the canonical admission
payload, so ownership and admission share one transaction even without
an Idempotency-Key. Recover ownership only through exact validated scope
matching after existing lookups miss. Preserve profile, credential, and
room-grant boundaries; historical ownerless rows remain fail-closed.

run_owner_scope is the same sha256(profile, api_key) digest already
persisted in run_idempotency.scope (_run_idempotency_scope); it is now
also carried inside the admission payload_json, so a run admitted
without an Idempotency-Key still has a durable owner after restart.

Keep private scope out of model preparation and public projections. No
schema change, synthetic replay keys, separate owner TTL, or auth redesign.

Regression coverage includes fresh adapters, keyed and non-keyed runs,
foreign-owner refusal, stale generations, rollback atomicity, duplicate
request semantics, and private-field isolation. Independently verified
503 tests across 70 API/state/hosted-room files, retries disabled; Ruff
and whitespace checks passed. Independent review found no blockers.
2026-09-12 17:44:12 -07:00
Teknium
f48d09563b fix: preserve API content identity history and terminal outcomes 2026-09-10 05:16:53 -07:00
Teknium
290191e475 Merge remote-tracking branch 'origin/main' into feat/unified-gateway-runtime
# Conflicts:
#	gateway/platforms/api_server.py
#	gateway/platforms/api_server_openai_routes.py
#	gateway/run_turn_runner.py
2026-09-09 12:37:49 -07:00
Teknium
d5926b2494 fix: persist API delegation units once without waking the model 2026-09-09 10:55:32 -07:00
Teknium
789caca24f docs: API runs and X-Hermes-Session-Id cannot bind a session owned by another surface (409 permission_denied) 2026-09-09 09:49:14 -07:00
Teknium
f35358a60f fix: resolve API prompts through canonical pending controls 2026-09-08 18:43:50 -07:00
Teknium
33c78d189e docs: describe browser session continuation preflight 2026-09-07 06:00:05 -07:00
Teknium
7a86397a46 fix(api_server): fail closed on unstamped runs; claim session-chat-stream run owner (#93689)
Port the run-ownership invariants from PR #93747 onto main's `_run_owners`
model in gateway/platforms/api_server_runs.py:

- `_request_owns_run` no longer admits run state that exists without an
  owner stamp. Under gateway.multiplex_profiles every served profile holds
  a valid key, so the "backward compatibility" branch made the boundary
  allow-all whenever provenance was missing. Unstamped state now fails
  closed; only an in-memory owner match or a durable idempotency record
  under the caller's own scope admits a run.
- POST /api/sessions/{id}/chat/stream claims `_run_owners` at the run mint,
  inside the request's profile scope, so its run is confined to the
  creating profile like /v1/runs.
- Owner release is tied to "no run-keyed state survives"
  (`_release_run_owner_if_forgotten`) and runs at every retirement point
  (task finally, SSE stream close, both sweep loops, chat-stream finally),
  not only the terminal-status sweep — no stranded entries, no stateful id
  ever left unowned.

Docs: note that runs are per-profile scoped (replaces the now-false
visibility admonition proposed in PR #92822).

Fixes #93689
Fixes #90415
Supersedes #93747, #93704, #92822

Co-authored-by: RickyYii <237135932+RickyYii@users.noreply.github.com>
Co-authored-by: liuhao1024 <11816344+liuhao1024@users.noreply.github.com>
2026-09-02 06:17:47 -07:00