* 🛬 fix: Settle Background Tool Results Before the Server Shuts Down
* 🛬 fix: Preserve Background Shutdown Results Through Fallback
* 🧪 test: Match Formatted Cluster Shutdown Wiring
---------
Co-authored-by: Lia <lia@librechat.ai>
* 📬 fix: Show Background Results Still Waiting for the Agent
The chat header listed a background task as completed as soon as its tool
finished, while its result could still be queued behind a busy turn and
arrive minutes later as a new agent turn. The header also read only the
process-local registry, so tasks on another replica were invisible.
The task index now reads the durable delivery store the agent's
check_background_task already uses: each finished task carries
delivery pending, delivered or failed, and finished results known only to
the store are listed too. The header marks results still on their way,
keeps them ahead of delivered ones, and polls them every 10 s.
* fix: Retain And Index Background Result Delivery States
* fix: Pass Background Delivery CI Checks
---------
Co-authored-by: Lia <lia@librechat.ai>
* feat: Attach or leave a workspace on a saved chat
A saved chat that recorded running without an attached environment could
never take one: `without_attached` is sealed for the life of the chat, and
the only transition was a move between attached environments. Switching an
existing chat to a coding agent therefore ended in a composer that could
send but never reach files or commands. A chat sealed to a machine that went
offline had the opposite dead end: Send stayed disabled with nothing on
offer but a reconnect hint, and the "Move the chat to continue without it"
copy promised a request the server rejected as `invalid`.
One transition mechanism now covers all three directions. `from` still
repeats the persisted decision, so a stale view cannot replace a decision it
has not seen, and only a decision the chat actually recorded can move:
- attach, from a recorded `without_attached` onto the environments its
agents use, with each target workspace revalidated on its worker;
- detach, an empty `to`, which clears the selections without polling the
machine the chat is leaving;
- move, unchanged, including its refusal to switch the workspace of an
environment the decision already covers.
The composer keeps the control visible while a chat runs without a
workspace, so that state is named and reversible, and offers "Continue
without workspace" whenever a sealed machine stops being usable. History is
untouched and no file is copied.
A send now also records the decision it was submitted under on its own
conversation. The server seals that pair for the rest of the chat, so a chat
that became saved mid-run held none while the stored one was already sealed:
the composer re-derived an agent default the seal refuses and reported
"Choose workspace" with Send disabled until the page was reloaded.
* 🎨 style: Format the Workspace Transition Hook Tests
* fix: Never seal a partial workspace decision, and gate the new directions
Two review findings on the transition mechanism.
A transition replaces the sealed decision whole, and the next turn resolves
every environment or none. The move path could not truncate before, because it
was offered only in `choose` state, which `aggregateState` reaches only when no
environment is unavailable, unsupported or missing: every environment was then
either carried over or selectable. Widening the gate to `!canSubmit` so an
unreachable machine could be left behind broke that invariant, and an
environment nothing can cover would have been dropped from a decision the
composer then sealed, blocking the next send and needing a second transition to
escape. A nonempty transition now requires every environment to be retained or
selectable; when one cannot be, only leaving attached execution is offered,
which is the escape.
The move protocol version becomes 2. Attach and detach travel on the same
owner-authorized endpoint as the move, so a client built against this change
would otherwise offer both to a deployment that only implements moves, where an
attach comes back `locked` and an empty target set `invalid`. The client already
compares the advertised number against the constant, so the bump is the gate.
`conversationMoves.enabled` still decides whether an owner may replace a sealed
decision at all.
* fix: Keep v1 moves working, and take the conversation updater from its owner
Two review findings on the previous head.
Bumping the move protocol wholesale made the client's exact-version check treat
a replica still advertising 1 as supporting nothing, so an attached chat whose
agent moved to another machine lost the relocation that replica already served
-- the previous head's own compatibility test pinned that regression. The
protocol is now two constants: version 1 is the move between attached
environments, version 2 adds attaching an environment to a chat that recorded
running without one and leaving attached execution behind. The server
advertises the highest it implements and the client keeps every lower
capability, so a v1 replica keeps its move while attach and detach wait for the
version that serves them. Where an environment cannot be covered and leaving is
not served either, no transition is offered and the composer reports the state.
Recording the submitted decision had made this hook a second Recoil writer of
the conversation atom, widening the surface that migration has to convert. The
host that owns the atom already holds its setter, so the hook receives it
instead of reaching through `~/store`.
* fix: Advertise attach and detach beside the move instead of above it
Raising the move protocol to 2 kept a client and server of the same build in
agreement, but not the two builds a rollout actually runs at once. The deployed
client compares the advertised number for equality against its own constant of
1, so a server advertising 2 tells every client already loaded in a browser that
moves are unsupported, and an attached chat whose agent changed machines loses
its relocation until that tab reloads.
The move version therefore stays 1, exactly as before this branch, and the two
new directions are advertised on their own field:
codeEnvironmentMoveVersion: 1 // move between attached environments
codeEnvironmentTransitionVersion: 2 // attach an environment, or leave one
Both come from `conversationMoves.enabled`, since all three are one owner
replacing one sealed decision. A client that predates this capability reads only
the move version and keeps working; a client that has it offers attach and
detach only where the second field appears, so it never sends a replica an
attach it refuses as `locked` or an empty target set it calls `invalid`.
* fix: Hold a send while a workspace decision is being replaced
Confirming an attach left Send enabled. The composer disables only the
workspace menu while the request is in flight, so a turn submitted right after
the confirmation started under the decision being replaced: it ran without the
workspace its owner had just chosen, and the replacement still landed, because
the stored decision the compare-and-swap expects was unchanged. The chat then
reported an environment its last turn never used, and nothing said so.
The server's own check has the same shape. It reads the conversation's
generation state, then revalidates each target workspace over the network, then
swaps; a turn that starts during that round trip is invisible to the check that
already ran. It now re-reads the generation state immediately before the swap,
leaving only the instant the compare-and-swap itself covers, which closes the
window for every client rather than just this one.
On the client the submission resolver refuses while a replacement is pending,
so the same signal disables the Send button and makes a programmatic send
return false. The workspace control stays reachable, so the state a chat is in
remains visible while it settles.
* fix: Fence Workspace Transitions and Reconcile Rejected Choices
Advance a private conversation revision after publishing an active generation and before reading its authoritative workspace decision. Transition CAS writes compare that revision, covering admission during the final idle-check window without expiring locks. Preserve tenant middleware and exclude private counter writes from chat activity and indexing.
Default existing undecided chats to no workspace, reconcile failed submissions from the server, scope pending guards to the affected chat, compare selection tuples without delimiter collisions, and opt attach/detach into deployment policy independently of existing moves. Retain legacy selection-only choices through first-send events.
* fix: Retain Failed Workspace Recovery and Skip Disabled Fences
Keep unconfirmed code-environment decisions in conversation-scoped Jotai state after authoritative reads fail, mutation observers reset, or navigation unmounts them. Expose a retry action and release submission only after a matching successful read. Ignore stale completions and reject mismatched conversation responses.
Reuse the owner-scoped conversation already loaded by each ingress when effective conversation moves are disabled. Retain the admitted revision fence for enabled moves, including move-only deployments. Cover failure/retry lifecycle and both policy branches at the helper and ingress levels.
* fix: Reuse the Atomic Admitted Snapshot Through Recovery
Return the admission revision and persisted decision from one Mongo findOneAndUpdate. Skip content indexing per internal query while retaining tenant middleware, private projection, and timestamps. Carry the returned snapshot through web and API initialization instead of validating against a stale pre-admission selection.
Keep first-send workspace choices in both the recovery preset and conversation template, and reconcile using the generated conversation ID from error or message data rather than requiring a saved submission snapshot. Cover single-query storage, indexing isolation, moved-machine validation, and first-send error recovery.
* fix: Reconcile Cancelled Turns and Keep Detach Reachable
Reconcile the submitted code decision before the local cancellation path finalizes streamed content or recovers a minimal submission. A cancel that beats the server rejection must not leave the attempted choice sealed locally; navigation must not update a different conversation.
Offer the authorized detach-only transition when a sealed conversation no longer has any attached agents, while ordinary chat stays sendable. Keep the selector visible for that transition and retain existing policy gates. Cover cancellation branches, no-attached-agent states, managed-only agents and the detach action.
* fix: Recover Workspace Transitions Across Navigation
* test: Verify Saved Workspace Transitions Against Current Dev
* test: Assert Explicit No-Workspace State in Native Journey
* test: Await Browser Settlement Before Switching Native Agents
* test: Settle URL Agent Selection Before Native Chat
* test: Wait for Worker Lease Expiry Before Offline Detach
---------
Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
* 🔕 perf: Back Off Idle Durable Agent Recovery Polls
* 🎛️ style: Format Queued-Turn Recovery Test
* fix: Preserve Durable Recovery Wakeups and Discovery Invariants
---------
Co-authored-by: Lia <lia@librechat.ai>
Update package repository and bugs URLs, GitHub links in docs, templates and comments, and image references (compose files, deployed-update, Helm values and renovate hints) from danny-avila to LibreChat-AI / librechat-ai. Covers the rag-api repository and its images, which moved to the organization. Sponsor links and the sealed star-history chart are unchanged.
* fix: constrain agent selector to 480px and 10 unsearched agents
The Agents panel selector dropdown now caps at 480px tall with the option
list scrolling inside, and lists at most 10 agents while the search field
is empty; typing lifts the cap so search still reaches every agent.
ControlCombobox gains optional popoverMaxHeight and unsearchedLimit props,
so every other selector keeps its current fixed 300px list.
* fix: make the agent selector cap configurable, viewport-safe, and selection-preserving
The unsearched list cap now reads interface.agentSelectorLimit from
librechat.yaml (default 10), the popover cap yields to Ariakit's
available height so a short viewport never pushes options offscreen,
and a selected agent ranking past the cut keeps the last slot instead
of disappearing until searched for.
* fix: forward agentSelectorLimit through the interface loader and guard it at the client
loadDefaultInterface whitelists interface fields, so the new knob never
reached /api/config without explicit forwarding; and values that bypass
interfaceSchema (raw yaml reads, principal-scoped admin overrides) are
normalized back into 1..100 at the client so a bad override cannot empty
the selector.
* feat: add GPT-6 Sol and Luna support
* fix: normalize Sol and Luna reasoning requests
* fix: align Sol and Luna effective Responses routing
* fix: honor server routing policy for model uploads
* test: await system grant indexes before writes
* fix: verify model upload policies against runtime initialization
---------
Co-authored-by: Lia <lia@librechat.ai>
* feat: add Claude Opus 5.5 support
* fix: preserve Opus 5.5 settings through provider adapters
* fix: preserve model-hidden settings when pruning parameters
---------
Co-authored-by: Lia <lia@librechat.ai>
* 🌊 fix: Prevent Agent Model Stream Idle Timeouts
* fix: Preserve Default Proxy Dispatcher Construction
* test: Assert Agent Transport Timeout Policy
* test: Cover Direct Model Dispatcher Reuse
* fix: Scope Agent Model Transport Timeouts
* fix: Enforce Agent Timeouts Across Direct and Summary Clients
* fix: Align Model Transport Adapter Types
---------
Co-authored-by: Lia <lia@librechat.ai>
* fix: preserve Insights with guarded ACL role updates
* test: settle ACL index builds before opening the transaction
* fix: replace ACL mask partitions with single-operator bit writes
* style: drop the now-unused RoleBits import
* fix: make ACL role replacement one atomic guarded write
* fix: export the permission write retry ceiling
* fix: retry ACL mutations per document and preserve atomic permissions
---------
Co-authored-by: Lia <lia@librechat.ai>
* ⚡ perf: Throttle Code Highlighting While a Message Streams
* fix: harden streamed code highlight throttling
* test: cover wall clock changes during highlighting
* style: tidy highlight regression test
* fix: restart highlight work across lifecycle changes
* style: avoid nested highlight timing ternary
* fix: propagate highlight throttle to startup config
* fix: share and validate highlight throttle
* fix: keep streamed code visible during highlighting
* test: stream highlight tool arguments
* fix: preserve highlights when cadence config resolves
* fix: reschedule highlights when cadence changes
* test: preserve default fake tool chunking
* fix: prevent stale streamed highlights
* test: open the tool pane before asserting streamed highlights
Every scenario in this file waited for highlight tokens without opening the
card. Dev's #16143 stopped passing a closed pane any code at all, so the four
runs polled a card that renders raw text and had nothing to find: the failed
traces show the disclosure at aria-expanded="false" for the whole run, with no
click against it and no tokens in the code element.
Highlighting is now asserted through the card's disclosure, which ProgressText
owns and which carries an aria-expanded state only once the card has input to
show, so waiting on it also waits for the first streamed argument chunk. The
open happens inside expectHighlightedCode, so a scenario cannot assert tokens
without it, and it lands while arguments are still streaming, which is the only
window where the throttle is under test at all.
* test: reopen the rebuilt card for the settled highlight
Opening the pane got the streaming assertions passing and the traces show 240
highlight spans mid-stream, so the throttle itself lands. The settled check
still failed because persisting the streamed message rebuilds the card, and a
rebuilt card starts closed while autoExpandTools is off: the disclosure goes
back to aria-expanded="false" and a closed pane renders raw text.
The settled and cancelled states now assert through the same open-then-wait
helper, so each one measures the card the reader would actually be looking at
instead of the tokens the streaming card happened to leave behind.
* test: leave a window to cancel a streaming highlight
With the settled assertions fixed, the cancellation scenario timed out on the
Stop button instead: it waited for a highlight before stopping, and the ~40
argument chunks it streams at 35 ms are gone in under two seconds, so the run
had already finished and there was nothing left to cancel. It failed on all
three attempts.
The card is now opened and the run stopped before any token is awaited, since
tokens after cancellation are what the scenario is about, and the cancel
variant streams its arguments at a wider cadence so the window does not depend
on how loaded the runner is. Only that label changes cadence; every other
scenario keeps the timing it had.
* fix: preserve initial highlights and honor shared-page cadence
---------
Co-authored-by: Lia <lia@librechat.ai>
* ✂️ fix: Name Tool Rounds From the Trace, and Match a Cut Response From Its End
* 🧵 fix: Join a Cut Model Call's Round Only When One Is Waiting
* 🏷️ fix: Read Labels From the End Only for the Response the Limit Cut
* 🪪 fix: Say a Tool Round Came From the Conversation Only When It Did
* 🧾 fix: Carry Where a Tool Round's Calls Came From
* 🫗 fix: Roll Back Incomplete Skill Archive Imports
A .zip or .skill import created the skill first and persisted its bundled
files one by one, keeping the skill and answering 201 when a file failed
validation, a size limit, storage, or its database row. The client never
read the internal `_importSummary`, so it showed "Skill created" and
navigated to a skill that silently lacked the resources SKILL.md names.
Import is now atomic: any failed bundled file rolls back the skill, its
file rows, the ACL grant, and the blobs already written to storage, and
the request answers 422 `skill_import_incomplete` with the failed paths
and reasons. The upload dialog stays open and lists them.
* fix: Localize Import Failure Reasons and Report Every Lost File
Addresses the first review round on the archive import rollback.
Failure reasons are now stable codes (`invalid_path`, `file_too_large`,
`archive_too_large`, `archive_entry_changed`, `persistence_failed`) that
the client localizes, so a non-English locale no longer sees English text
and storage or driver messages stay in the server log.
The decompression budget stops the scan mid-archive, and the entries it
never reached were missing from the response, telling the user they had
seen the whole failure set. Those paths are now reported too.
Rollback deletes stored blobs only once `deleteSkill` confirms the skill
is gone; otherwise the blobs stay and the request answers 500
`skill_import_rollback_failed`, because a surviving skill pointing at
deleted files is worse than unreferenced storage.
The failure list scrolls instead of overflowing the dialog, and a
response that resolves after the dialog was dismissed no longer
repopulates it for the next session.
* fix: Ignore Late Skill Import Successes
* fix: Make Skill Import Rollback Retryable
* fix: Propagate Incomplete Skill Cleanup
* fix: Settle Rollback Blob Cleanup
* test: Type Partial Cleanup Fixture
* fix: Preserve Settled Skill Cleanup Steps
* fix: Export Skill Cleanup Step Type
* fix: Reconcile Partially Deleted Skills
* fix: Reconcile Skill Rollback Caches
* style: format cleanup reconciliation changes
* fix: complete skill rollback cleanup
* chore: leave generated locale catalogs unchanged
* fix: preserve synced skill blob cleanup
* test: type synced blob cleanup mock
* fix: Validate Archive Paths and Bound Rollback Cleanup
---------
Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
* ⏳ fix: Keep BYOM tools queued across capacity windows
* ⏳ fix: Configure the admission budget and refresh queued credentials
Addresses the Codex review on #16060:
- Add `limits.maxQueueWaitMs` to the code environment config schema so a
deployment can shorten or disable the five-minute admission budget from
`librechat.yaml`; omission keeps the merged behavior, `0` surfaces the
first capacity expiry to the model. Resolved through
`resolveAttachedWorkspaceQueueWaitMs` and passed by ToolService, matching
how `maxCommandTimeoutMs` already flows.
- Accept an auth-header supplier in `executeWorkspaceTool` and mint it per
admission attempt, so a call queued past the Code API token TTL presents
fresh credentials instead of failing permanently with 401. The attached
Bash tool and the workspace file operations now pass suppliers.
- Recheck the deadline after a clamped wait and throw the saved rejection
rather than opening an admission window that could still be admitted
once the budget is spent.
* fix: Complete workspace admission wiring and caller regressions
* fix: Share protected edit retry budgets and schema limits
---------
Co-authored-by: Lia <lia@librechat.ai>
Since #15694 bounded each turn's attachments across history, a thread whose
history counts more than `fileLimit` model-bound files is refused on every turn,
including turns that attach nothing. Two kinds of file reached that count that
never belonged in the prompt.
Code outputs: priming clears an expired sandbox reference on the turn's copy of
the record so the file is re-provisioned, and a route-less record without a
reference was classified as prompt content, so it counted toward the limit and
could be encoded as media. Code outputs now stay tool-owned regardless of
reference liveness, through one predicate shared by admission, BaseClient
delivery and the child run-file encoder.
Tool-routed spreadsheets: with `textFallbackWithoutTools`, #16027 delivered the
fallback text until a tool held a copy. Run Code receives its copy only on its
first call, which a refused turn never makes, so the text counted on every later
turn. An enabled Run Code is a reader again for the types it can read; File
Search still reads only what its store holds.
* fix: Serialize MCP OAuth token refresh across replicas
`MCPTokenStorage.inflightRefreshes` coalesces refresh-token redemptions
inside one Node process. Behind a load balancer without session affinity,
one user's concurrent requests land on different replicas, each reads the
same not-yet-rotated refresh token and redeems it. RFC 9700 servers treat
the second redemption as replay and revoke the whole grant family, so the
user is asked to authorize the MCP server again.
`forceRefreshTokens` now takes a cross-replica refresh flight before
redeeming, using the same `FlowStateManager.acquireLease` primitive the
OAuth teardown fence uses under a distinct key. A replica that waited for
the flight adopts the tokens the holder rotated instead of redeeming
again; when the flight is still held after the wait window it falls back
to the unfenced redemption every earlier release performed.
* fix: Redeem unfenced when the refresh flight lease store fails
* fix: Fence MCP refresh waiters instead of redeeming unfenced
A waiter that could not take the cross-replica refresh flight fell through to
an unfenced redemption after 10s, while the holder's own stale abort does not
fire until 60s. A refresh taking 11 to 60 seconds therefore still let two
replicas redeem one refresh token, the replay this fence exists to prevent.
The waiter now polls until it either adopts the tokens the holder rotated or
acquires the flight, and fails as MCPTokenRefreshUnavailableError rather than
redeeming beside a live holder. `getTokens` callers defer connection recovery
on that error, and the stored credential is left intact for a later attempt.
The flight is keyed by the stored credential (tenant, user, server name)
rather than the caller's OAuth binding digest, so a rolling config change
cannot hand two replicas different locks over one stored token. The wait is
an operator lever, `oauthRefreshWaitTimeout`, clamped to half the stale
window. An adoption read that fails no longer gives up the held flight.
* fix: Annotate derived refresh-flight constants for isolatedDeclarations
* fix: Recapture the credential generation a peer published on adoption
* fix: Hold the MCP refresh flight until redemption settles
Four corrections to the cross-replica refresh flight.
The flight lease equalled the window that aborts a stalled redemption, on
the claim that an expired flight could never belong to a redemption still
able to reach the token endpoint. Aborting proves no such thing: the
request may have been processed with its response lost, and a stalled
event loop can delay the abort past its own deadline. The lease now
outlives the abort, so a peer cannot redeem a credential the provider has
already rotated. A live replica still releases on settle, so the margin is
paid only by one that died holding the flight.
The credential snapshot was taken after the first failed acquisition, so a
holder that stored and released in that gap was snapshotted post-rotation:
the next attempt saw an unchanged record and redeemed the credential it
should have adopted. It is taken before the first attempt now.
`oauthRefreshWaitTimeout` accepted zero while the runtime mapped every
non-positive value to the default, so the config validated and then
behaved contrary to its value. Zero is rejected at load.
Adoption announced a second credential change through
`handleOAuthRefreshSuccess`, whose `onOAuthCredentialsChanged` advances
authorization state after persistence this replica did not perform. That
retired the generation recaptured beside it and fenced the build against
its own tool publication. Adoption now updates the local token-flow cache
and recaptures, without announcing.
* fix: Check every held MCP refresh flight for a peer's rotation
Four corrections, two of them consequences of moving the credential
observation ahead of the first lease attempt.
That move created a storage read inside `beginRefreshFlight`, and its
failure reached a handler written for a lease-store outage, so a transient
read error became an unfenced redemption beside a live peer. The flight
now handles its own reads: losing the observation costs adoption and
nothing else, and only the lease store failing may redeem unfenced.
The observation was also never compared when the first acquisition
succeeded. A peer that rotated and released before this replica contended
left an acquisition that looked uncontended, and its fresh credential was
redeemed a second time. Every acquisition now runs one rotation check,
which also collapses two code paths into one.
`getTokens` already loads the refresh record to decide a refresh is
needed, so it is passed on as the observation baseline instead of read
again, and the read taken under the flight is reused as the credential
redeemed. Two reads on a latency-counted path where there were three.
`runSilentRefresh` collapsed contention into null, sending the 401 path to
interactive OAuth, so a slow peer prompted the user to authorize a server
whose credential was about to be valid. The retryable outcome now travels
through the silent-refresh layers and the connection defers, matched by
name as well as identity because these errors cross the package boundary.
* chore: Regenerate the Agents OpenAPI spec for repositoryInstructions
The drift check added by #15928 fails on dev: #16008 added
`repositoryInstructions` to the agent schema without regenerating the
committed spec, so every branch merging dev inherits the failure. This is
the remedy the check itself prescribes and carries no hand-written change.
Drop this commit if dev regenerates first.
* fix: preserve MCP refresh outcomes across replica boundaries
* fix: keep MCP adoption fenced through publication
* fix: anchor MCP refresh adoption to rejected credentials
* fix: Complete OAuth Adoption Adapters and Isolate Legacy Flow Readers
* fix: Preserve OAuth Request Identity Through Recovery and Discovery
* fix: Fence OAuth Adoption Against All Credential Writers
* fix: Gate Coordinated OAuth Rollout and Preserve Unauthenticated Identity
* fix: Preserve OAuth Coalescing Across the Staged Rollout
* style: Sort OAuth Timeout Constant Import
* fix: Invalidate Both OAuth Token Flow Protocols on Rotation
* test: Complete the Rollback Token Flow Fixture
---------
Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
* 🗣️ fix: Keep Provider Error Text on Unclassified Agent Failures
An upstream failure LangChain does not classify discarded the provider's own
message and answered with the generic upstream sentence plus a status, so a
gateway or privacy-proxy rejection lost the only account of what happened.
The provider text now rides along in the persisted payload as `message`,
withheld only where a content policy inspects the traffic — the same condition
`getUserFacingProviderError` and `getUserFacingRequestError` already decide by.
* fix: Harden Provider Error Detail Retention
---------
Co-authored-by: Danny Avila <danny@librechat.ai>
* 📭 fix: Deliver Attachment Text Until a File Tool Holds It
A `none`-routed upload had its extracted text withheld whenever a file tool was
enabled, on the assumption the tool would serve the file. A plain chat with the
File Search toggle runs an ephemeral agent, so the upload is filed under no tool
resource and never embedded: the text was withheld for a vector store that never
received the file, and the attachment reached nothing.
Withholding now requires the record to show the tool holds the file, which is the
same evidence deferred provisioning reads before queueing it. `resources.ts`
delegates to that shared predicate so the two cannot disagree again.
* test: Give the Code-Running Primary Agent a Sandbox Copy
---------
Co-authored-by: Lia <lia@librechat.ai>
* 🪜 feat: Trace Viewer Steps, Sequence Scale and Previews
* 🪜 fix: split tool-only rounds by run step; preview only a step's own roots
* 🪜 fix: keep windows and previews on the records they describe across pages, modes and failed wrappers
* 🪜 fix: keep step folds and previews honest across page boundaries and failed turns
* 🪜 fix: causal tie-breaks, final-only previews, span-shaped title runs, and truncating long names
* 🪜 fix: index previews in one pass, split agent handoffs, withhold parallel lanes
* 🪜 fix: skip the holes a streaming message leaves in its content
* 🪜 fix: reserve a round for compaction summaries; keep parallel-lane tools with their own model call
* 🪜 fix: record a handoff that starts with reasoning; look lanes up in a map
* 🪜 fix: per-lane leading steps, wrappers for turns without work yet, no final alignment for runs that ended early
* 🪜 fix: append to a step's per-tool bucket instead of copying it per call
* fix: Preserve Trace Preview Alignment Across Run Boundaries
* perf: Cache Trace Ancestors and Lane Branches
* 📪 feat: Send Per-Request MCP Headers Without Hiding the Tool Catalog
A `{{LIBRECHAT_BODY_*}}` placeholder in an MCP server's `headers` marks the
server request-scoped, and catalog discovery has no conversation to resolve it
against, so LibreChat skipped tool discovery and the server appeared with no
individual tools.
Operators can now declare those headers separately in `requestHeaders`, which
discovery omits and chat turns resolve and merge over `headers`.
* fix: normalize requestHeaders at each resolution entry point
Registering the new field in every consumer that enumerates header-bearing
config fields left five gaps: startup inspection, case-insensitive override,
the admin-configurable comparison surface, Graph token preprocessing, and
direct-bearer recovery.
Fold `requestHeaders` into `headers` at the entry of each resolution pipeline
instead, so Graph preprocessing, direct-bearer detection, `processMCPEnv` and
the transports keep reading one header map and never learn a second exists.
Catalog paths strip it at the same boundary, startup inspection included.
* fix: keep servers with chat-only headers off the shared app connection
A static `requestHeaders` map left a server eligible for app-level sharing, and
`ConnectionsRepository.loadConnection` handed the raw config to the factory, so
the shared session's own `initialize` and `tools/list` carried headers
documented as chat-only — and every later catalog read reused that session.
One session cannot serve both sides of the field. Exclude such configs from
`canUseAppConnection`, the single predicate both `connectAppServers` and the
repository's own app-level gate already consult, so the chat turn keeps its
headers on a user-scoped connection while catalog work never sees them.
* fix: normalize requestHeaders before the manager's bearer decisions
`createUserConnectionInternal` reads `usesDirectOpenIDBearerRecovery` and
`resolveDirectOpenIDBearerConfig` on the config it receives, while the merge sat
in `resolveRuntimeConfig`, a leaf helper below those calls. An `Authorization`
template declared in `requestHeaders` therefore never entered direct-bearer
mode: a `tools/list` 401 skipped the force-refresh and the connection was
returned with a stale bearer.
Normalize at the birth of that pipeline's config instead, ahead of all four
decisions, and make `getMCPAppToolsPublicationGeneration` normalize before
hashing. Connection paths hold a merged config while cache paths hold the
declared one, so without a canonical hash the two would address different
catalog slices.
* fix: Preserve MCP request header ownership across lifecycle boundaries
* fix: Narrow remote header identity before rebuilding config
* fix: Preserve request header precedence over catalog API keys
* docs: Synchronize generated agent API schemas
* fix: Ignore shadowed generated MCP user key requirements
---------
Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>
* 🔌 feat: OpenAPI spec and docs for the public Agents API
* 🔧 fix: address review on Agents API OpenAPI spec and docs:
- adapter: mark JSON request bodies as required
- openapi.js: move gate, config read and spec serving into packages/api
as an injected router factory; leave /api as wiring only
- docs: compute URLs in-browser and use a relative servers url so docs
work under a base path (e.g. /chat)
- build: copy the generated spec into dist so the multi-stage image ships it
- agents: reuse the enforced list envelope for the docs so the AgentList
schema cannot drift from the runtime cursor and strictness
* 🔧 fix: align Agents API OpenAPI contract with enforced runtime
Second review round on the public Agents API spec. Three cases where the
published contract described something the server does not do, so generated
clients would fail against the live API:
- Upload form: document the `purpose` field (enum: file_search, execute_code,
context) that POST /agents/{id}/files actually requires, instead of the
internal-only `tool_resource`; requests following the old form were rejected
with 400 because `purpose` was absent.
- Auth: drop the `apiKeyBearer` scheme from the management and skill endpoints.
They gate on OIDC/M2M via requireAgentManagementAuth and deliberately reject
the API-key fallback; the API key belongs to the out-of-scope
OpenAI-compatible endpoints and returns when those are documented.
- Skill update: document the 409 conflict PATCH /skills/{id} returns on a stale
expectedVersion. The agent update path collapses its internal 409 to 400, so
it correctly keeps no 409.
* 🔧 fix: serve docs on experimental server and document the 401
Third review round on the public Agents API spec.
- Experimental server: mount routes.openapi in api/server/experimental.js before its /api 404 handler. Without it, npm run backend:experimental returns 404 for /api/docs and /api/openapi.json even when openapi.enabled is true, because that server never mounted the router.
- Auth failure: document the 401 that requireAgentManagementAuth returns on a missing, expired, malformed, or unbound token. Its body is { "error": "Unauthorized" }, a flatter shape than the management error schema, so add a dedicated UnauthorizedError schema and a shared 401 response to the agent and skill contracts rather than reusing the standard error schema.
* 🔧 fix: document skill-update, auth-conflict, upload-limit, and watch-copy gaps
* 🔧 fix: added error shapes for permission denied and internal server errors in API responses docs
* fix: cover the auth-layer 500 shape and pin the account-deletion code
* fix: update OpenApiRouterDeps documentation and simplify request handling in isEnabled function
* 🔧 fix: gate the Swagger asset mount behind the OpenAPI toggle
* 🔧 fix: accept the malformed-JSON 400 envelope in the contract
* fix: accept the tenant-isolation 403 envelope in the contract
* fix: add description for content property in SkillFileUpdateRequest to clarify byte limit
* 🎚️ fix: Allow Opting Out of the MCP OAuth `resource` Parameter
Adds `mcpServers.<name>.oauth.send_resource_parameter`, defaulting to true, so
operators whose authorization server rejects RFC 8707 `resource` can complete
the MCP OAuth flow. Suppression applies at send time only: Protected Resource
Metadata is still discovered, still validated against the server URL
(RFC 9728 §3.3) and still recorded on the stored client binding.
* 🧹 chore: Drop Accidentally Tracked node_modules Symlinks
Worktree-local symlinks were committed because .gitignore matches node_modules/ as a directory, not as a symlink of that name. They pointed outside the repository, so CI dependency installation failed and every downstream check with it.
* 🧪 test: Cover the MCP OAuth `resource` Opt-Out at Token Exchange
The authorization_code exchange reads the decision from flow metadata rather than live config, so a code obtained without `resource` is never exchanged with one. Covers both the opted-out flow and a flow initiated before the field existed, which must keep sending the parameter.
* 💅 style: Apply Prettier to the Token Exchange Test
* 🔒 fix: Make the MCP OAuth `resource` Opt-Out Actually Take Effect
Addresses three Codex findings on the opt-out:
- `startAuthorization` copies the configured `authorization_url` verbatim, so a
`resource` an admin left in that URL survived into the request and Entra kept
rejecting the flow. Opting out now deletes the parameter on both authorize
paths instead of only declining to add one.
- `.omit()` let a user-managed submission carrying `send_resource_parameter`
parse successfully while discarding the field, so the opt-out was silently
ignored. It is now `z.never().optional()`, matching the documented contract
and the `audience` precedent.
- A pending flow built with `resource` could be replayed for the full pending
window after an operator set the option, reissuing the request they had just
reconfigured away from. `isCurrentServerOAuthFlow` now compares the captured
decision with live config. Stored tokens are unaffected, so changing the
option still does not force re-authentication.
* 🧯 fix: Suppress Inherited MCP OAuth `resource` and Stale Replays
Addresses two further Codex findings on the opt-out:
- The MCP SDK uses `token_endpoint` verbatim and the refresh paths post to the
resolved token URL as-is, so a `resource` an admin left in `token_url` (or one
on a discovered token endpoint) still reached the provider. The outbound URL is
now sanitized at the exchange and in all three refresh paths. Stored metadata
keeps its configured form so the client binding still matches.
- Pending-flow replay was only guarded inside MCPConnectionFactory, so the
browser initiate endpoint could still redirect to the stored URL. The shared
pending helper now takes optional live config and refuses a replay whose
captured decision no longer matches; the route passes it.
* 🪤 fix: Scope the MCP OAuth `resource` Opt-Out to Paths It Can Serve Correctly
The browser initiate route compared the pending flow against `resolveConfigServers`,
which deliberately omits unmodified YAML servers (see `mcp/context.ts`). For the very
config this option targets that read a captured `false` against `undefined`, reported
drift on every initiation, and then returned 400 because factory-written flow states
carry no `oauth` property to rebuild from. Reverted rather than patched: doing it right
needs effective-config resolution behind a `packages/api` helper, per the `/api`
wiring-only rule, and this sandbox cannot run that route suite.
Retained and corrected:
- The pending-flow guard no longer rides on `isCurrentServerOAuthFlow`, which also
gates reuse of a recent COMPLETED flow. It was invalidating already-issued tokens,
contradicting the promise that changing this option never forces re-authentication.
Now a PENDING-only predicate at the two replay sites.
- `ServerConfigsDB.sanitizeUserManagedOAuthConfig` strips `send_resource_parameter`, so
a DB-backed or imported user config cannot activate the admin-only opt-out.
---------
Co-authored-by: Lia <lia@librechat.ai>
types/assistants.ts held ~60 exports of which only ~11 were Assistants
API types. The rest were core message-content types and the Agent entity
types, so schemas.ts and agents.ts both imported foundational types from
a file named after the Assistants API.
Split into types/tools.ts (tool primitives, action naming) and
types/content.ts (message content parts, annotations, tool calls), moved
the Agent entity types into the existing types/agents.ts, and left a slim
Assistants-only types/assistants.ts.
No behavior change: every symbol keeps its public export from the package
barrel, so no consumer outside data-provider changes.
Co-authored-by: Lia <lia@librechat.ai>
* 🪃 fix: Remember the Last Code Approval Mode
The code approval dropdown reopened on "Ask before changes" after every new
chat and reload. `useCodeApprovalMode` derived its selection from
`conversation.codeApprovalMode ?? 'ask'`, and a new conversation never carries
that field: `buildDefaultConvo` runs the last setup through `parseConvo`, whose
agents schema does not pick `codeApprovalMode`, so the pick was dropped.
The menu now records each pick in a localStorage-backed Jotai atom, and the
hook seeds its default from it when the conversation carries no mode of its
own. The remembered value is a preference and not a grant: it passes the same
policy gate as a stored mode, so anything current policy no longer allows
falls back to `ask`, and sign-in/sign-out clears it so a shared browser does
not hand the next account a permissive default.
* 🎨 style: Format the Code Approval Preference Files
---------
Co-authored-by: Lia <lia@librechat.ai>
* 🧷 feat: Carry Ask User Answers Past Compaction
The user's answers to `ask_user_question` lived only in the tool result that
received them. A checkpoint summary, the tool-output pruner or a full context
window could remove that message, and the agent then asked again or acted on
a summary's paraphrase.
Every answered ask on the conversation branch is now rendered verbatim into
the run's dynamic instructions, on the first request and on every resume,
where the answer just given is read from the seeded content. Older answers
drop first past a token budget; the newest set is always kept.
New lever: `endpoints.agents.askUserQuestion.retainedAnswers` (`enabled`,
`maxTokens`), on by default with a 4096-token budget.
* 🧷 feat: Carry Ask User Answers Past Compaction
The user's answers to `ask_user_question` lived only in the tool result that
received them. A checkpoint summary, the tool-output pruner or a full context
window could remove that message, and the agent then asked again or acted on
a summary's paraphrase.
Every answered ask on the conversation branch is now quoted verbatim at the
top of the current user turn's prompt copy, in the user's own role: rebuilt
from the stored rows every turn, never persisted, excluded from the memory
copy, and counted in the prompt total with the active encoding. A warm
event-actor turn reads the branch on demand. Older answers drop first past a
token budget that includes separators; the newest set is always kept.
New lever: `endpoints.agents.askUserQuestion.retainedAnswers` (`enabled`,
`maxTokens`), on by default with a 4096-token budget.
* 🧷 refactor: Read The Warm Branch Inside The Module
The warm event-actor read lived as a conditional and a `getMessages` call in
the CJS client. The typed module now takes `historyLoaded`, the identity and
the query as dependencies, decides when to read, and owns the failure policy
for both the read and the block itself; the client passes plumbing only.
* 🧷 fix: Complete The Branch Behind A Summary Cut
`loadHistory` already stops its walk at a checkpoint summary, so the rows
`buildMessages` receives never held the answers this feature carries. The
module now detects a branch that stops short of its root, whatever cut it,
and completes it through the injected stored-row query, stored rows winning.
The block goes on the latest user-authored row so a continued generation
keeps it, and the render measures the whole block before reserving the
omission note, so a set is only dropped when something truly has to go.
* 🧷 fix: Reuse Loaded History And Read Every Ask Stamp
A post-compaction turn read the conversation twice: once in `loadHistory`,
which cuts at the checkpoint summary, and again in the module to complete
the branch. The loader now keeps the rows it read and the module prefers
them, querying only for a turn that made no history read.
Two stored shapes were missed: a pause record whose `args` is the bare
question string, now read as the legacy question, and a call whose input
failed validation, whose persisted error output is no longer quoted as an
answer.
* 🧷 fix: Keep The Block Off The Stored Row And Out Of Memory Copies
Array-form content is replaced instead of edited through the array the
stored row shares, the block's cost is measured as two fresh counts of the
same copy rather than against a possibly calibrated stored count, the
memory copy is only built when memory extraction will read it, the loaded
rows reach the agents client through a hook and are released once the block
exists, and the tool-call-id merge is gone: rows are unique by message id
and providers may reuse ids across turns.
* 🧷 refactor: Apply The Answers Block Inside The Module
The placement lookup, the prepend, the count delta and the memory-copy
decision lived in the client after the context kickoff. They now live in
`applyRetainedAnswers`, which receives the rows, the prompt copies, the
count map, the counter and the memory dependency; the client keeps one
call and passes plumbing.
* fix: Apply Retained Answers After Summary Replay 🧷
* perf: Count Retained Context Exactly Within Its Budget 🧮
* fix: Preserve Retained Counts Across Checkpoint Recounts 🧾
* fix: Isolate Retained Context Counting and Provenance 🧵
* fix: Replace Warm Retained Context and Verify Answer Provenance 🪪
* fix: Use Workspace-Compatible Array Traversal 🧭
* fix: Refresh Retained Context at the Warm Turn Boundary 🧲
* 🪂 feat: Opt-In Text Fallback for Files No Tool Can Read
An upload routed to tools (`llmDeliveryPath: none`) reaches nothing when the
agent handling the turn runs neither Run Code nor File Search, or runs one that
cannot read the type. With `fileConfig.endpoints.<endpoint>.textFallbackWithoutTools`
(also accepted at the top level and inherited from `default`), such a turn
delivers the text extracted at upload instead. The setting is off by default,
which keeps today's behavior.
- Upload: when the setting is on and an inferred `none` route finds no reading
tool, the built-in document parser or native text reader stores the text on
the file, best effort, under the extracted-text size cap and content policy.
- Turn: `resolveTurnLLMDeliveryPath` re-resolves each inferred route against
the tools the agent runs, and `applyTurnTextFallback` marks copies of the
records a turn loads, so endpoint filtering, limits, inspection, history
replay and steer media all see the text the turn delivers. The stored route
is never rewritten.
- Explicit destinations, records predating routing, and turns whose tools are
unknown are left as they are.
* 🧪 test: Resolve Custom Endpoint Fallback Under the Endpoint Name
Uploads route a custom endpoint agent by its saved provider, the endpoint name. initializeAgent marks turn copies before getProviderConfig swaps the provider for the backing client, and the endpoint keeps the name afterward, so the client and child encoders resolve the opt-in under the same endpoint. Cover both the initialization path and the post-initialization agent shape.
* ♻️ refactor: Share One Extracted-Text Storage Cap Across Uploads
The fallback defined its own copy of the 15 MiB cap context uploads already apply to extracted text. Export MAX_STORED_EXTRACTED_TEXT_BYTES from files/extract and use it in both places, documenting that it bounds what a MongoDB file document can hold rather than operator policy.
* 🧭 fix: Keep Fallback Text Wherever a Later Turn Can Deliver It
Extraction skipped uploads filed under a reading tool, so a handoff agent
without that tool, or the same agent after its tools or grants changed, had
no text to fall back to. Store fallback text for every inferred route on a
message attachment; files kept on an agent's tool resources never reach a
prompt and still skip it.
Turn marking only ran while the fallback was enabled, so a stored tool-routed
record whose type the endpoint now routes to text stayed marked `none` and
`extractFileContext` skipped it. applyTurnTextDelivery (renamed from
applyTurnTextFallback) now marks any stored `none` record with text that the
turn resolves to text, and returns early when no such record is loaded.
* 🚦 fix: Admit Every Attachment by the Route Its Turn Delivers
A record upload routed to tools that the current endpoint sends to the
provider stayed marked `none` on the turn copy, so admission skipped it while
BaseClient encoded its bytes, bypassing attachment count and size limits.
applyTurnDelivery (renamed from applyTurnTextDelivery) now gives every record
whose route upload inferred the route the turn resolves, before endpoint
filtering, limits and inspection, matching the run-file encoder.
hasInferredLLMDeliveryPath shares the inferred-route rule with the resolver.
Fallback extraction selected the document parser inside the CJS upload path.
resolveUploadFallbackText now takes the upload and picks parseDocument or
parseTextNative itself, with the extractors injectable, so process.js passes
request data only. Its tests run the real parser against the xlsx fixture and
the real native reader against temporary files.
* 🎚️ fix: Read Custom Endpoint Dialect From Config on Both Sides of Init
initializeAgent materializes turn routes before getProviderConfig swaps the
saved custom endpoint name in agent.provider for its backing client, so
routing read that name as a non-OpenAI dialect. Media a custom endpoint opted
into could then be materialized off the provider path, skipping admission,
while the finalized client still sent the bytes. resolveAgentDeliveryRouting
now reads the dialect with getCustomEndpointProvider, as upload does, which
holds before and after the swap.
The upload fallback plan now keys on the chosen-destination marker the turn
resolver reads, so an upload recorded as chosen, including every legacy
chooser upload, never pays for text a turn cannot deliver.
* 🛡️ fix: Apply Turn Routes Only While the Record Stays Admitted
Resolution while initializing and at delivery can disagree: delivery reads a
Responses API choice only the finished client config holds. Applying a route
that takes a record out of admission, off the model path or to text it never
stored, would then skip the limits for a file the client still sends.
applyTurnDelivery now applies a route only while the record stays model-bound;
admitting a record the turn leaves out cannot slip past a limit.
* 🕹️ feat: Run Declared Project Actions on Attached Workers (#15943)
* feat: use declared attached project actions
* Complete named action definitions and approval previews
* Sort named environment imports
* Sort native environment fixture imports
* 🔓 fix: Keep Code Approval Mode Selectable Mid-Run (#15938)
* 🔓 fix: Keep Code Approval Mode Selectable Mid-Run
The composer's code approval mode selector was disabled while a run streamed, and a mode picked during a run was reverted when the final or abort event merged the server conversation back. The selector now stays usable in flight and both merges retain a mid-run selection, which the next send carries.
* 🔓 fix: Retain Mid-Run Approval Mode Across Cache and Recovery
Stamp the live approval mode onto the submission conversation at send so the retention baseline matches what was read, keep a retained mode in the conversation query cache on final and cancel, and rebuild failed or aborted conversations from a preset that carries the mid-run pick.
* 🔓 fix: Scope Retained Approval Mode to the Submitted Conversation
Retention now requires the live conversation to be the one the run submitted, or the id the server assigned to a new chat, so navigating elsewhere mid-run cannot write that conversation's mode back. A single recovery helper rebuilds failed or aborted conversations from the retained preset and patches the detail cache for every recovery site.
* 🔓 refactor: Keep the Local Approval Mode on Every Server Merge
Replace per-path retention with one rule: a locally picked code approval mode is newer than any server copy of the same conversation, so the final and abort merges and the error recovery preset keep it. The selector writes the pick into the conversation's detail cache, which navigation rebuilds from, so the pick is conversation-scoped without reading the index-global atom from the SSE handlers.
* 🔓 fix: Prefer the Live Conversation When Caching the Final Merge
The final handler's detail-cache merge now takes the local approval mode from the open conversation when it is the one that finished, falling back to the cached record only for a conversation that is no longer on screen.
* 🔓 fix: Keep the Local Approval Mode Through Settled-Start Reconciliation
The resumable transport's settled-start reconciliation and replacement handoff wrote a fetched conversation straight into conversation state and the detail cache. Both now apply the same local-mode rule as the event handlers, treating a new chat's pending id as the settled conversation's own.
* 🔓 fix: Seed the Detail Record When a Mode Is Picked
A conversation that has its id but no detail record yet now gets one from the live conversation when a mode is picked, the same key the resumable transport seeds optimistically, so recovery and navigation find the pick. A chat with no id yet still keeps the pick in conversation state alone.
* ⬆️ chore: bump agents to 3.8.7 (#15947)
* 🧭 refactor: Settle Turn Delivery Routing Once in Agent Initialization
`initializeAgent` resolved the provider and its client options only after the
turn's files were loaded and admitted, and the two delivery readers each rebuilt
the attachment routing from the agent object at their own moment: `BaseClient`
took the custom-endpoint dialect from the already-swapped `agent.provider`, the
run-file encoder from whatever child config it was handed.
Move `getProviderConfig`/`getOptions` ahead of file discovery, where nothing in
between fed them, and settle one `deliveryRouting` value with every input final:
the file policy under the endpoint's own name, the dialect its config declares,
the Responses API decision the model call uses, and the transcription setting.
`InitializedAgent`, the child encoder and `BaseClient` consume that value;
`resolveTurnLLMDeliveryPath` is the one place a stored route is resolved again.
* fix: Preserve attachment reachability across handoffs and late steers
* test: Type the untrusted attachment reference fixture
---------
Co-authored-by: Ravi Kumar L <upman@users.noreply.github.com>
* feat: send video/audio to custom endpoints that opt in via supportedMimeTypes
The video and audio encoders only emitted OpenAI-format parts (video_url,
input_audio) for OpenRouter, and Google's media part for Google/Vertex. For
every other provider the file was validated and then silently dropped, so a
custom OpenAI-compatible endpoint (vLLM, LiteLLM, ...) never received the
attachment even though the wire format is identical to OpenRouter's.
Emit the OpenAI-format part for OpenAI-like providers when the endpoint's
fileConfig supportedMimeTypes explicitly allows the file's type. The inherited
default list does not count as opting in (isExplicitMimeConfig, keyed on
referential identity like the client's picker), so endpoints whose gateway
cannot handle media are unaffected.
* feat: let a configured custom endpoint pick and attach video/audio
The attach menu's Upload to Provider filter and the drag-drop viability check
only opened video/audio for Google and OpenRouter, or for a custom endpoint
with a fully permissive (.*) supportedMimeTypes. Honor any admin-configured
allowlist on a custom endpoint instead, so a finite list that includes
video/.* or audio/.* is enough, matching the server-side encoders.
* fix: canonicalize input_audio format from MIME type
The `input_audio.format` value was derived from the filename extension via
`filename.split('.').pop()`, which produces values providers reject:
- `clip.wave` (audio/wave) emitted `wave`, but the accepted format is `wav`
- a file with no extension (`recording`) emitted the whole filename, since
splitting a dotless string yields a single-element array, so the existing
non-empty guard never fired
- `clip.mpeg` (audio/mpeg) emitted `mpeg` rather than `mp3`
All of these pass MIME validation and then fail at the provider. Derive the
format from the MIME type instead, mirroring the canonicalization already in
STTService, and fall back to the filename extension only when it is itself a
supported format. Throws when neither source yields one rather than sending an
unsupported value.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: route opted-in custom endpoint media to the provider path
In unified upload mode an upload carries no tool resource, so its delivery path is
inferred by resolveDefaultLLMDeliveryPath. That resolver judged audio and video for any
named endpoint with isMediaSupportedProvider, which lists only Google, Vertex and
OpenRouter, so a custom endpoint that opted into media through supportedMimeTypes still
recorded video as none and audio as text, and the encoder branch was never reached.
The upload resolver already holds the endpoint's file config, so it now passes the
endpoint's supportedMimeTypes through, and an explicit match on an OpenAI-compatible or
custom endpoint counts as provider-capable, mirroring isConfiguredProviderMediaType on
the encoder side. The inherited default list is still not an opt-in, and known providers
whose encoders emit nothing for media are unchanged. BaseClient re-resolves per turn with
the same function, so the turn path follows.
* fix: scope the media opt-in to custom endpoints that run as OpenAI
The opt-in applied to the built-in openAI and azureOpenAI endpoints too, but the picker
and drag-drop only open media for custom endpoints, so that was a route the client could
not send to. It is now limited to endpoints that are not a known provider.
A custom endpoint may also declare provider: anthropic, in which case initialization runs
it as Anthropic and the encoders emit no media part for it. getCustomEndpointProvider
reads that declaration off the app config, the upload callers pass it as endpointProvider,
the agent encoder and BaseClient pass the agent's resolved provider, and an endpoint known
to run as something other than OpenAI keeps its previous route: video stays off the model
path and audio still reaches transcription.
* fix: reject unsupported provider audio during upload
---------
Co-authored-by: Renato Garita Figueiredo <renato.garitafigueiredo@uni-osnabrueck.de>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix: route Azure Astra through Responses API
* fix: keep Azure Astra deployment alias out of summarizer overrides
The Azure deployment alias in `modelKwargs.model` is spread after `model`
by langchain, so the SDK's same-provider summarizer, which copies the
agent's client options and overrides only `model`, still reached the Astra
deployment when configured with a different model. Hand the summarizer the
agent's kwargs without the alias whenever its model differs.
Also derive the Astra routing decision once, reuse the first-party OpenAI
predicate in the GPT-5.6 rule, pin the opt-out shape in the Azure spec, and
expect `firstPartyEndpoint` for canonical Azure hosts in the backward-compat
spec.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* fix: resolve Azure request URLs and summarizer deployments
* fix: honor explicit OpenAI summarization for Azure agents
* 🧭 fix: Degrade Unresolvable Azure Summarizers Without Failing the Run
Summarization target resolution for Azure agents threw inside createRun, so a
summarization setting that could not be resolved failed every agent run before
any model call, not just compaction. The documented `summarization.provider:
openAI` block with the `.env.example` default `OPENAI_API_KEY=user_provided`
broke all Azure agents, and a summary model missing from the Azure
configuration did the same.
- An explicit OpenAI summarizer without server credentials now disables
summarization for that Azure agent with a one-time warning instead of
throwing; the agent's own client is not a fallback because Azure Responses
shares the `openAI` provider.
- A summary model the Azure configuration cannot resolve warns once and keeps
the agent's client, as before this branch.
- A summary group without a base URL no longer inherits the agent group's
`azureOpenAIBasePath`, which sent the summary key and deployment to the
agent's resource.
- Serverless summary groups without a version send no empty `api-version`.
* 🧪 test: Assert No Summary Request Leaves a Disabled OpenAI Summarizer
* 🧯 fix: Disable Summaries Whose Azure Deployment Cannot Be Resolved
When the Azure configuration could not resolve a summary model, the summarizer
fell back to the agent's own client. On an Azure Responses agent that stripped
the deployment alias and sent the logical model name where Azure expects a
deployment, so every compaction failed; on a chat agent the URL-pinned
deployment silently served a different model than the one configured.
An unresolvable Azure summary target now disables summarization for that agent
with a one-time warning, matching the unreachable OpenAI target: the run
proceeds on context pruning and no summary request is sent.
* 🔑 fix: Treat an Empty Azure Summary Key as Unavailable
`azureBaseSchema` accepts `apiKey: ''`, and `mapModelToAzureConfig` passes it
through, so a summary group with an empty key kept summarization enabled and
built a client with no credential. The agent flow already rejects an empty
Azure key during initialization; the summary resolver now disables
summarization for that target with the same one-time warning as a
user-provided key or base URL.
* 🧭 fix: Resolve Azure Summaries From Every Supported Azure Configuration
Three Azure configuration shapes the summary resolver and URL builders did not
cover:
- Legacy `AZURE_*` environment credentials: without an `azureOpenAI` block the
resolver skipped Azure, so an Astra agent's summarizer reused the agent's
Responses client and sent the logical summary model where a deployment
belongs. The target now resolves from the environment the way
`initializeOpenAI` does (including `AZURE_USE_MODEL_AS_DEPLOYMENT_NAME`) and
is disabled when those credentials are user-provided or missing.
- `summarization.parameters` `baseURL` and `apiKey` overrides now apply to Azure
summary targets, as they already did for explicit OpenAI targets, through one
shared helper.
- A full Azure hostname used as the instance name (as `genAzureEndpoint`
accepts) is used as the host for both the default Responses URL and the chat
deployments path, instead of being suffixed into
`<host>.openai.azure.com`.
* 🔐 fix: Expand Summarizer Credential Placeholders and Bound Warnings
Admin-authored `summarization.parameters` `apiKey` and `baseURL` values were
forwarded verbatim, so `${SUMMARY_KEY}` reached the client as a literal key
while Azure groups and custom endpoints expand the same syntax. They are now
expanded once through `extractEnvVariable` (keeping its sensitive-variable
denylist) before resolution and before the parameters are layered over the
client, and a credential or base URL that still holds an unresolved
placeholder disables summarization like a missing one. Azure base URL
templates (`${INSTANCE_NAME}`, `${DEPLOYMENT_NAME}`) are not treated as
unresolved.
The one-time warning set is now keyed per tenant, so one tenant's report no
longer hides another's, and resets after 256 distinct entries so changing
configurations cannot grow it without bound.
* 🧩 fix: Keep Azure URL Templates Out of Summarizer Env Expansion
Expanding `summarization.parameters.baseURL` through `extractEnvVariable`
also replaced Azure's reserved `${INSTANCE_NAME}` and `${DEPLOYMENT_NAME}`
templates whenever the host environment happened to define those names, so a
template override could route compaction to the host's instance or deployment
instead of the summary group's. Expansion now skips those two templates and
leaves them for `constructAzureURL`, and the unresolved-placeholder check reads
the same segments.
The warning deduplication set now evicts the least recently seen entry at its
bound instead of clearing, so warnings for problems that are still recurring
are not all logged again at once.
* 🔀 fix: Reset Inherited API Mode for Custom-Endpoint Summarizers
A custom OpenAI-compatible summarization endpoint resolves to the same `openAI`
provider as an Azure Responses agent, so the SDK layered its overrides over the
agent's client options and kept the agent's `useResponsesApi`,
`firstPartyEndpoint`, reasoning and request kwargs. An Azure Astra agent
therefore sent its compaction to the gateway's `/responses` with Astra shaping.
When the resolved custom provider matches the agent's, those fields are now
replaced from the target's own configuration, and explicit summarization
parameters can still opt back in.
Azure's reserved `${INSTANCE_NAME}`/`${DEPLOYMENT_NAME}` URL templates are now
preserved only for Azure summarization targets, so an OpenAI or custom base URL
can reference environment variables with those names.
* fix: Resolve Azure Summary Identity, Transport, and Token Limits 🧭
* fix: Resolve Headers Before Building Summary Clients 📨
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Danny Avila <danny@librechat.ai>
* 🧷 fix: Skip Failed Summaries When Resolving the Conversation Checkpoint
* 🧷 fix: Keep a Failed Summary Out of the Model-Facing History Boundary
* 🧭 refactor: Own the Summary Checkpoint Predicate in packages/api
* 🧯 fix: Reject Unfinished Summaries Everywhere and Recount Stripped Turns
* 🧬 fix: Version Event-Actor Summary State So Legacy Prefixes Cannot Warm
* 🏷️ fix: Stamp Inherited Summaries Where Actor State Is Assembled
* ⚖️ fix: Drop Unusable Summaries While Building the Prompt
* 🧷 fix: Repoint Prompt Content Instead of Splicing Stored Parts
* 🧭 fix: Treat a Streamed Summary Without a Boundary as Unfinished
The server has stamped `failed` on an errored summarize round only since
#14546, and `summarizing` never reaches storage, so every round that errored
on v0.8.7 or rc2 was persisted as a plain summary holding its partial deltas.
The flag checks cannot tell that row from a checkpoint, so upgraded
conversations kept losing the history before it.
The aggregator settles it structurally, identically in every SDK release
that has shipped compaction (3.1.63 through 3.8.6): deltas stream `content`
blocks into the part, and only a completed round replaces the part with the
final block, which is the sole writer of `boundary`. A `content`-block summary
without a boundary therefore never finished. `isUsableSummaryPart` and the
shared `isCompactedLeaf` both apply that rule; bare-`text` rows predate the
aggregator and stay governed by the flags.
Fixtures that stand for completed summaries now carry the boundary a real
run writes, and the flag fixtures keep one so they still test the flags.
* 🔁 fix: Strip Unusable Summaries From Responses API Continuations
`previous_response_id` loads the stored conversation and hands each message's
`content` array straight to `formatAgentMessages`, whose summary scan takes
the last summary part carrying text as the history boundary. The chat client
strips unusable summaries before that scan; this entry point did not, so a
conversation continued through the Responses API still lost everything before
a failed round. The same packages/api helper now runs ahead of the formatter.
* 🧭 refactor: Own Event-Actor Summary Selection in packages/api
`getLatestEventActorSummary` decides which summary a warm continuation
carries forward, how a missing token count is recorded, and how the state is
stamped. That is compaction behavior, and every helper it relies on already
lives in `packages/api/src/agents`, so it moves beside `isUsableSummaryPart`
and the controller imports it.
* 🧪 test: Give the Finished Compaction Leaf the Boundary a Completed Round Writes
`isCompactedLeaf` now requires the boundary only a completed summary block carries, so the client fixture for a finished compaction needs one, and a boundaryless leaf joins the interrupted compactions that can be retried.
---------
Co-authored-by: Danny Avila <danny@librechat.ai>
* 🧭 fix: Let a Sealed Chat Follow Its Agent to a New Machine
A conversation's code-environment decision is sealed on its first turn, but the
environment an agent uses stays editable. Pointing an agent at a different
attached machine left every chat sealed to the old one with no valid move: the
client showed an unusable workspace chooser, and any other selection was
rejected by the server as locked. Forking copied the stale seal.
The owner can now move such a chat explicitly. The composer names the machine
the chat used and the one its agent uses now, and moving it goes through an
owner-scoped endpoint that compare-and-swaps the persisted decision after
validating the new workspace against the live worker. A move never switches the
workspace of an environment the decision already covers, never upgrades a chat
that continues without an attached environment, and is refused while a
generation is in flight.
A saved chat also no longer auto-selects a sole workspace for an environment its
decision never covered, which submitted a selection the server always rejected.
* fix: Hold Moves Through Terminal Saves and Move Every Target at Once
A terminal claim marks a generation complete before its response save lands,
and that save still writes the decision the run started with, so a move is now
refused until terminalPersistencePending clears.
The API advertises codeEnvironmentMoveVersion, and the client offers a move only
when it is present, so a new client never exposes an endpoint an older API lacks.
The move menu picks one workspace per new environment, with a sole workspace
preselected, and a single confirm sends the complete target set in one request,
so a partial move can no longer leave a half-migrated decision. A new machine
that advertises no workspace shows its unavailable state instead of an empty
section, and the confirm stays disabled.
* fix: Keep Runs From Rewriting Moved Decisions and Gate Moves by Policy
Every agent turn used to persist the decision it started with, so a run from any
ingress that settled after a move could write the old decision back: the chat
controller reads the conversation before its generation job exists, and
Responses API runs never enroll one. Runs now persist a decision only for a
conversation that does not store one yet, and a legacy row records only the mode
it inferred, so no admission or persistence order can revert a move.
Moves are now an operator setting, statefulCodeSessions.conversationMoves.enabled,
off by default. The API advertises codeEnvironmentMoveVersion and accepts moves
only where the effective policy enables them.
A saved chat carrying attached selections no longer auto-selects a sole workspace
even when selection-less decisions are not advertised, because the server seals
those selections either way.
* fix: Fence Moves Across Remote Runs and Let Moves Drop Unused Machines
A Responses API run is keyed by its response id, so the conversation stream
alone could not show it still working on a chat. A move is now refused while any
generation that can still act for the conversation exists, using the same
conversation-scoped enumeration conversation deletion drains.
A move now validates every workspace it persists, not only the added ones, so a
successful move never hands back a decision whose kept workspace is gone.
A chat sealed to machines its agents no longer all use could not be sent or
moved: the client trimmed the unused selection and the server rejected the
trimmed set as locked. A saved chat now treats that seal as unresolvable, offers
a move that drops the unused machine, and the server accepts drop-only moves.
* fix: Own the Decision Fallback in TypeScript and Settle Move Caches
The fields a run may persist when it never resolved a decision were chosen by a
branch in AgentClient; resolvePersistableCodeEnvironmentDecision now owns that
fallback too, under the same never-overwrite rule, and the CJS method only wires
the request into it.
Workspace choices made in the move menu belong to the chat they were made in, so
another relocatable chat targeting the same machine starts undecided.
A successful move cancels conversation, pinned, and list reads already in flight
before writing the moved decision, so a response from before the move cannot
restore the replaced decision in the cache.