* feat: resolve executing agent ids in MCP header templates
* test: preserve MCP config source literal types
* 🪪 feat: Forward the Active Agent Id in Request Header Placeholders
A gateway in front of LibreChat sees the user, the conversation and the
message, but not which agent is running — so it cannot attribute spend per
agent, apply per-agent limits, or tell agent traffic from plain chat. Adds
`{{LIBRECHAT_AGENT_ID}}` as its own namespace beside the user / body / OpenID
ones, resolving wherever the existing request placeholders already work.
The value is the primary agent's, derived once per run, so subagent steps and
auxiliary calls (summarization, titles, activity labels, memory extraction)
forward the id of the turn they belong to rather than their own. Only
persisted agents resolve: ephemeral ids embed user-authored preset text that
is unsafe in a header value, so ephemeral runs and non-agent requests resolve
to an empty value rather than forwarding literal template text.
No behaviour change unless the placeholder is configured. The MCP surface
(#14303) is not covered — its connection classification derives from
`ALLOWED_BODY_FIELDS`, so a new namespace needs a follow-up.
(cherry picked from commit 8a3f1016f0)
* test: cover shared provider and MCP agent header resolution
* docs: clarify absent agent placeholder resolution
* fix: preserve agent header boundaries across transport lifecycles
* fix: retain Google header provenance during agent resolution
---------
Co-authored-by: Jiří Krejčí <51734696+krejcji@users.noreply.github.com>
* 🚪 fix: Refuse Interactive MCP Sign-in on Remote Agent API Runs
A run started through the remote agent API (API key or OIDC bearer) has no
signed-in browser reading its response. When one of the agent's MCP servers
needed OAuth, the run still published LibreChat's sign-in prompt into the
OpenAI-compatible response and waited up to two minutes for a sign-in the
caller could not complete.
The remote auth middleware now marks the response it admits. The prompt
emitters refuse to write to a marked response, and tool loading skips the
turn-start wait when no reader exists. Background Responses keep their
prompts: those go to the generation stream the owner follows in LibreChat.
* 🧭 refactor: Pass the Unattended Fact Explicitly and Release Unattended Callers From Shared Sign-in
Review feedback on the first commit:
- The response registry coupled the auth middleware to MCP through module
state. The remote controllers now supply `unattended` as an argument
(chat completions always; Responses through the runtime's tool context,
foreground only) and it is passed through tool loading to the manager and
the prompt transports. The registry and the middleware side effect are gone.
- A remote run that reached a server while its owner had a sign-in open in a
browser joined that recovery and waited for the person. The manager now
guards an unattended caller at its two entry points: the first sign-in
prompt, from the caller's own flow or from a recovery it waits on, ends that
caller's wait with a typed error and leaves a shared recovery running for
its other waiters. A recovery announces a sign-in request so waiters that
registered no prompt handler are released too.
* 🧪 test: Cover Unattended Sign-in Through the Real MCP SDK
The shared-sign-in tests replaced the production OAuth handler with a
synthetic listener, so they did not exercise the SDK lifecycle whose
cancellation and shared-recovery behaviour the change depends on.
They now run against the real Streamable HTTP test server, the real
connection factory handler and the real flow manager: an unattended tool
call alone, alongside the owner's open sign-in, joining a recovery that
then stops being silent, recovering through a silent refresh, and opening
a connection that needs sign-in. The synthetic-handler versions are removed.
* 🧷 fix: Promote Unapplied Steers to Durable Queued Turns at Run End
A steer the server accepted (202) but the run never applied was handed back
in FINAL as `pendingSteers` and re-owned by the browser as a tab-local queued
message. A reload, closed tab, or a predecessor race before the drain lost it.
At terminal publication, a normally completed run now promotes such steers
into server-owned agent queued turns (parent: the ended response, epoch: the
ended generation's createdAt, chained behind any turn already queued against
that epoch). The job store hands the parked copy over atomically
(`promoteSteerLeftover`: parked item removed, receipt settled `recovered`), so
status recovery, lost-ACK retries and legacy recovery starts cannot queue the
same words again. FINAL reports the receipts in `promotedSteers`; the client
adopts them as server rows instead of converting the steer locally.
Promotion is opt-in per steer (`promoteLeftover`, sent only by clients that
adopt receipts and only for steers with no tab-only context), so older
clients keep the legacy path unchanged, and older servers simply never
report `promotedSteers`.
* 🔒 fix: Settle a Promoted Steer's Hand-Off at Admission, Not Only at FINAL
The job-store hand-off of a promoted steer now returns an outcome and stamps
the receipt with the owning queued turn, so it is idempotent for that turn.
The queued-turn resolver repeats it before admitting a promoted turn: it
completes a hand-off a crash interrupted, and cancels the turn when the
parked copy was discarded or recovered elsewhere, so the words never run
twice. At FINAL, a row whose hand-off was refused and whose retirement cannot
be confirmed is withheld from `pendingSteers` and left for that admission
check. The conservative reconcile frame keeps `promotedSteers`, and the
client adopts it there before sweeping local chips.
* 🔏 fix: Give Promoted Steers Durable Ownership, Their Run's Queue Lineage and Approval Mode
A turn promoted from an unapplied steer now records its source on its own
row: the steer's ids, the generation that accepted it, and a mark set only
once the job store handed the parked copy to that row. Admission runs a
promoted turn on that mark or on a hand-off the job store confirms now;
without proof (the store's evidence expired, or the host cannot ask) the
turn is held for review instead of running.
- Hand-off replies that are lost no longer cancel the row. The row stays as
the client's handle and its admission settles ownership, so a committed
hand-off can no longer leave the steer with no runnable copy.
- A replayed promotion never hands the parked copy to a row that was
cancelled or failed.
- Promoted turns join the queue lineage of the generation that accepted
the steer, so a sibling still queued behind that run no longer strands
them with a predecessor mismatch.
- The steer request carries the sender's code approval mode onto the
promoted turn; an unreadable mode keeps the steer on the client path.
- A steer whose quotes its owner stripped stays on the client path.
- The queued-turn receipt names the promoted steer by both ids, and the
receipt list retires a pane's local copies even when it missed FINAL.
* 🚧 fix: Fence Promoted Turns to Workers That Prove Steer Ownership
A promoted row without an approval mode was published under the v1 queued
turn capability, so during a rolling deploy a worker that predates the
ownership check could claim it and run an unsettled row while the parked
steer was still recoverable elsewhere.
Promoted rows now publish under a new agent_queued_turn_v3 capability and a
v3 delivery identity, always reserved before insertion. A replica that
projects an older version can neither publish the reserved delivery nor
claim it, and enqueue refuses a promoted row without a reservation.
* 🪦 fix: Keep a Dead Promoted Turn Answering for Words It Held
A pane that learns of a promoted steer from the receipt list dropped the
mapping for every dead row. A row quarantined as ADMISSION_INDETERMINATE can
still settle as admitted, and a row that died after it was proven the sole
owner of the words is their only surface, so in both cases the pane kept a
chip whose recovery could never run.
The receipt now says whether the turn owned its steer's words, and a dead
receipt keeps answering for them when it did or when its admission is
indeterminate. A replayed promotion applies the same rule to a settled row.
* 🧾 fix: Find Promoted Turns by the Steer a Pane Holds, Join Root Lineages, Redact Hand-off Errors
- A promoted turn's request id is now derived from the client steer id, and a
pane asks for the receipts of the steers it still holds a local copy of
(recovery rows and failed chips). A promoted turn that already ran is only
listed when asked for by name, so a pane that missed FINAL now finds it
and retires its copy. A client steer id too long to key a queued turn is
not promoted.
- The lineage lookup includes a generation admitted from a root queued turn,
which has a parent and no epoch. The promoted turn joins that lineage
without an epoch instead of opening a second one.
- A failed hand-off at admission reports a fixed message. The job store's
own error text stays out of the dead-letter record a client can read, and
promotion logs carry safe error metadata instead of error text.
* 🔢 fix: Ask for Held Steers First Under the Receipt Lookup Limit
The receipt list answers for at most 100 request ids, and a pane's server
rows were listed ahead of the steers it still holds, so a full server queue
could push every held steer out of the request. A promoted turn that had
already run was then never found.
Held steers now come first. An active server row is listed whether or not
it is asked for, while a settled promoted turn is found only by name.
* perf: Validate Agent Models Against Their Own Endpoint Catalog
* perf: Share In-Flight Model List Fetches
* test: Cover Agent Model Validation Across Endpoints
* test: Check Agent Model Catalog Parity With the Real Loaders
Bound model-facing Flux images to the 5 MiB base64 budget for standard and finetuned generation. Preserve original image data for attachment storage under the existing resolution policy.
Fixes#6954.
* fix: Keep the Provider Message on Classified Rate Limit Errors
* fix: Honor maxProviderErrorChars for Classified Generation Errors
* test: Cover Classified Gateway Errors in the Mock Harness
* test: Cover a Zero Provider Detail Limit on Generation Errors
* refactor: Resolve Classified Provider Errors in the TypeScript Backend
* fix: Redact Provider Details Before Truncating Them
* 🔐 fix: Authorize Restored MCP Tools Before Agent Revert Writes Them
Reverting wrote the version snapshot, including its mcpServerNames, before
filterAuthorizedTools ran. Agent-scoped MCP access is granted from that index,
so a restored server vouched for itself and an editor without access to it
could re-attach it. A snapshot without mcpServerNames also left the current
index in place, keeping agent-scoped access to servers no tool used.
The handler now authorizes the restored tools against the agent as it stands,
treating only its current tools as existing, and passes the authorized tools
and rebuilt index to revertAgentVersion so the restore is one write pinned to
the revision it was checked against. revertAgentVersion always rewrites the
index for the restored tools.
* 🔐 fix: Exclude the Target Agent's Own Grant When Authorizing a Revert
Moves the restore authorization into authorizeAgentRestore in packages/api,
leaving the revert controller as wiring.
A newly restored MCP tool whose server the user reaches only through agents
must now be reachable through an agent other than the one being reverted,
checked fresh against the database. The target's current or cached index
(including one left stale by an earlier revert) no longer vouches for it.
Prior server names are matched through their normalized aliases, and only for
tools the agent already had. When nothing resolves, the pre-restore index is
kept instead of deriving names from tool keys.
A revision-filtered restore that misses is reported as a 409 conflict.
The route spec restores the real ~/config so the MCP registry is consulted
rather than reported unavailable.
* 🔐 fix: Check Newly Restored MCP Servers Against Live Grants
The restore gate now runs for every approved MCP tool, not only consumeOnly
ones. A tool the agent doesn't already have, on a DB-backed server, is
admitted when a current tool still uses that server, or on a live direct
server grant, or through another viewable agent. A grant the registry still
caches after revocation no longer becomes durable through the restored index.
Admission is memoized per server. A snapshot tools array that sanitizes to
nothing restores an explicit empty set. Active-server matching no longer
reuses the index fallback, so a stale entry is never read as in use.
* 🔐 fix: Treat Legacy Cached DB Configs as User-Sourced in the Restore Gate
A config cached before an upgrade may carry a dbId without source. The
restore gate now uses isUserSourced, so such configs get the live access
check instead of passing as operator-managed.
* 🔐 fix: Recheck Unindexed Existing MCP Tools in the Restore Gate
Holding a tool no longer exempts it from the live check. Only a current tool
whose server the agent's index already lists skips it. Otherwise an unindexed
tool on a legacy agent could pass on a revoked grant the registry still
caches, and the restore would add its server to the index.
* ⚡ perf: Run Restore Admission Checks for Distinct Servers Concurrently
filterAuthorizedTools now starts every admission check during its single pass
and awaits them together, so each distinct DB-backed server no longer adds a
serial lookup wave to the revert. Tool order is preserved and server names
are recorded only for admitted tools.
* fix: Skip Attachments Deleted by Storage Retention Instead of Failing the Turn
A file that storage retention removed from an earlier message made every
later turn of the conversation fail, because the encoders rethrew the
storage miss and the user has no way to remove an attachment from history.
History replay now passes a handler to the encoders, which leave missing
files out of the request and report them; the message's file context tells
the model which files were deleted and were not read. Current-turn
attachments keep the strict error, since the user can remove and re-upload
them. Code Interpreter priming names files missing from storage in the
tool context and only requires resource recovery for other failures.
* refactor: Keep Code Reupload Failure Policy in packages/api
Tally priming reupload failures in createCodeReuploadFailures so the
decision that a file deleted from storage is named instead of requiring
resource recovery lives in TypeScript, and add mock e2e scenarios for a
follow-up after an attachment is deleted from storage.
* fix: Classify Code Files as Deleted Only at the Storage Read
A 404 from the Code API upload was counted as a source file deleted from
storage, which skipped resource recovery. openCodeFileSource marks a miss
where the stored object is read, and only that error counts as deleted.
Move the history replay of attachments with tolerated misses into
replayMessageAttachments so BaseClient only calls it.
* fix: Name Local Code Files Whose Stream Reports a Missing Object
Local storage returns a read stream that raises ENOENT only once read, so
openCodeFileSource now holds a stream until its first chunk or error and
names a miss there. The missing-files context assignment moves into
setMissingCodeFilesContext so both tool loaders only call it.
* fix: Close a Held Code File Stream When Priming Is Cancelled
openCodeFileSource waits for a source stream's first chunk; when that
wait fails, as on cancellation, the caller never receives the stream, so
destroy it before rethrowing instead of leaking its file descriptor.
* fix: Accept Content-Array Outputs in Responses function_call_output
The Open Responses spec allows function_call_output.output to be a string or
an array of input_text, input_image and input_file parts, but request
validation refused anything that was not a string. Validate the array parts
and convert them with the same part mapping the message path uses, so the
replayed tool result keeps its text and images in order.
* fix: Inspect Tool-Output Media Against File Policies
Image URLs and file names in a function_call_output content array reached the
model without the file-policy fragments the same parts get in a message.
Collect those fragments for both item types in packages/api and call that
from the Responses controller.
* test: Cover Content-Array Tool Outputs in the Responses API
- Let agents use Langfuse prompts by production label or pinned version,
with the existing permission and usage checks.
- Add a configuration switch, disabled by default. Preserve saved links
while disabled, without resolving them or falling back to inline text.
- Share source-specific production and exact selections across agent
links and the prompt service. Reject source mismatches.
- Add revision lists for the Agent Builder version picker. Resolve
Langfuse instructions on each initialization without caching.
- Improve disabled and unavailable states and test source changes,
revision loading, and permission failures.
* perf: Serve JWT Bearer User Lookups From the Auth User Cache
* perf: Batch Agent Permission Reads on the File Access Path
* perf: Remember a Loaded Google Service Key Across Endpoint Config Reads
* perf: Run Independent Startup, Tool, Skill and Erasure Reads Concurrently
* fix: Drop JWT User Cache Writes That Race a User Mutation
Confirm each cache write with a second read and evict when the user changed,
so an in-flight lookup cannot repopulate an entry a credential change just
evicted. The cache mode now arrives through the loader dependencies.
* refactor: Move Agent Skill Access Reads Into packages/api
The chat-completions and Responses controllers call loadSkillAccess instead of
orchestrating the three reads in CJS. The preview route spec mocks the batched
file access helper the middleware now calls.
* test: Cover Agent File Access, JWT Bursts and Remote Skill Reads End to End
* fix: Serve a Cached JWT User Only While Its updatedAt Is Current
A cache hit now reads the stored updatedAt and deletion fence instead of the
fence alone, so a document cached from a read that raced a user mutation is
never served, even when the write landed after that mutation's eviction.
* refactor: Move Startup Migration Checks Into packages/api
* refactor: Inject the Startup Migration Checks Instead of Mongoose Models
* fix: Serve Cached OpenID Users Only While Their updatedAt Is Current
Moves the freshness check into getCurrentCachedAuthUserDoc and uses it on the
OpenID bearer path as well as the local JWT one, so a document cached from a
read that raced a credential or role change is never served there either.
Fixesberry-13/LibreChat#432
* fix: Compare Authorization Fields on Every Auth Cache Hit
updatedAt has millisecond resolution, so the freshness read also compares the
token retirement stamps, role, tenant and two-factor state.
* fix: Annotate the Auth Freshness Projection for Isolated Declarations
* perf: Reuse the OpenID Cache Freshness Read for Deletion Admission
A cache hit already proved the deletion fence is clear, so only users read from
the database take the separate fence query.
* refactor: Keep the OpenID Cache Freshness and Fence Decisions in packages/api
* test: Exercise JWT Cache Freshness Against Real User Methods in MongoDB
* fix: Stamp the JWT User Lookup So the Cache Write Fence Applies
* fix: Reload a Google Service Key File When It Changes or Disappears
The availability check remembers a loaded key only while the file's mtime and
size are unchanged, and fetches URL sources every time as before.
* fix: Recheck a Service Key File After a Permission Change
* fix: Keep the Snapshot When the Terminal Write Settled for Reconciliation
* fix: Promote a Reconciled Compaction Snapshot to the Terminal Row
* fix: Anchor and Envelope the Reconciled Snapshot by Its Claim
* test: Cover the Abandoned Compaction Settling After Its Run in E2E
* fix: Withhold the Disconnect Snapshot of Any Durably Settled Turn
* fix: Promote Only a Same-Epoch Reconciled Snapshot and Settle Stopped Compactions
* fix: Plan the Disconnect Snapshot in packages/api and Check the Response Row Before Promoting
* fix: Read the Disconnect Snapshot Rows in the Response Conversation
* fix: Check the Anchor-Derived Error Row Before Promoting a Reconciled Snapshot
* fix: Log a Failed Disconnect Snapshot Plan Instead of Rejecting the Listener
* fix: Let a Reconciled Compaction Promote After an Earlier Live Snapshot
* refactor: Decide the Repeat Disconnect Write in the Snapshot Plan
* refactor: Report Failed Snapshot Row Reads Through the Plan
* fix: Stamp a Promoted Disconnect Snapshot and Read Its Rows Together
* fix: Derive the Compaction Error Row ID Through the Shared Helper
* fix: Plan a Saved Live Compaction Snapshot Again Once Its Turn Settles
* refactor: Queue Disconnect Snapshots and Settle Them in packages/api
* fix: Never Count the Compaction Anchor as Its Own Terminal Row
* fix: Settle Disconnect Snapshots Before Terminal Cleanup Releases the Turn
* fix: Return approved tool and generation error text instead of raw exceptions
* fix: Redact generation error text without the data-schemas helper
* fix: Redact credentials and emails from shown generation errors
* refactor: Move the Wolfram status policy into packages/api
* test: Fix the Wolfram probe constructor and jest summary match
* test: Match the jest pass count through color codes
* fix: Redact credentials a tool input error echoes from its arguments
* fix: Drop free-text fields from typed generation errors under a content policy
* fix: Keep only the code and numeric fields of typed errors under a content policy
* fix: Harden Timer Sweeps, SSE Writes, and Violation Counters
Guard SSE writes against ended or destroyed responses through one helper, catch and single-flight the job store and TTL cache cleanup timers, serialize in-process counter updates, cap the violation log, prune stale OAuth failure records, batch the active-job lookup, and count Redis keys with DBSIZE.
* refactor: Drop the redundant violation log entry copy
* refactor: Log single-flight sweep failures from the API package
* test: Cover active generation listing and client disconnect mid-stream
* refactor: Configure violation log retention and move title timeout into the API package
* feat: Configure OAuth failure retention through mcpSettings
* fix: Prune OAuth failures promptly under short retention
* fix(agents): skip the empty-memory notice for agents that cannot use memory
Since #16301 formatMemoryContext('') returns the bare memory instructions sentence, and
prepareRuntimeAgent applied it to the primary agent whenever the user had no saved memories.
An agent with no memory tools and no automatic memory extraction can neither read nor write
memory, so the sentence told the model nothing it could act on, yet it reached the model as
per-turn context. The empty-store notice is now added only when the agent has memory tools or
automatic extraction is on. Saved memories are still injected as before.
* fix(agents): distinguish relocated context from user input
* fix(agents): narrow runtime context types
---------
Co-authored-by: shars <32410570+Shabonasar@users.noreply.github.com>
Co-authored-by: Lia <lia@librechat.ai>
* 🏷️ fix: Resolve endpoints.all Title Settings per Field and Fold Ollama Endpoint Names
Conversation titles picked `endpoints.all` as a whole block, so any `all`
block (even one holding only streamRate, headers or activity label keys)
hid every per-endpoint titleConvo, titleModel, titleMethod, titleEndpoint
and title prompt. `resolveTitleConfig` resolves each field from `all`,
then the named endpoint, then the custom endpoint entry, keeping
titleEndpoint and titleModel as one choice from the first layer that sets
either.
Config overrides merged `endpoints.custom` by exact name while the runtime
serves names through `normalizeEndpointName`, so an override `ollama`
survived beside the YAML `Ollama` and split the endpoint between two
baseURLs and keys. The merge key now folds the same way (the YAML spelling
is kept), merge-key issues, issue attribution and secret preservation use
the same identity, and the effective config serves
`modelSpecs.addedEndpoints`, `modelSpecs.list[].preset.endpoint` and
`endpoints.agents.allowedProviders` in served names without repeats.
A stored document that already names one endpoint in two spellings is
combined at merge in document order, so requests keep the host and key
of the first item instead of moving to the YAML entry; omit-to-keep
secret preservation reads the same combined entry. A new write naming
both spellings is rejected as a duplicate.
An agent saved as `Ollama` now runs on the served `ollama`: the model
catalog lookup (`resolveModelCatalogKey`) falls back to the served name,
and `initializeAgent` folds the provider before the allowedProviders
check and provider setup.
* 🏷️ fix: Report Per-Field endpoints.all Title Resolution in the Admin Config Meta
resolveTitleConfig resolves endpoints.all title settings one field at a time, so GET /api/admin/config/meta now reports rules.titleResolution as 'field'. meta.spec ties the reported value to resolveTitleConfig: with endpoints.all = { streamRate: 1 } and openAI.titleModel = 'x', the rule is 'field' exactly when the endpoint's titleModel survives.
* 🧪 test: Expect Segments on the Folded duplicate_merge_key Write Issue
Admin config write issues carry segments since #17322; the folded Ollama/ollama duplicate test now asserts them.
* 🏷️ fix: Match Folded Custom Endpoint Names in Admin Config Change Ops
The changes endpoint from dev matched entry keys exactly, while the config
merge, merge-key issues and secret preservation fold `Ollama`/`ollama` into
one custom endpoint. An upsertEntry `ollama` over a stored `Ollama` copied the
stored key, appended a second entry and failed as duplicate_merge_key;
removeEntry `ollama` left a stored `Ollama` in place; a rename onto another
spelling passed entry_exists; and the librechat.yaml entry check missed
`ollama` against the YAML `Ollama`.
- data-schemas: `getConfigEntryIdentity` folds a key by its override path;
`getConfigEntryMatcher` backs upsertEntry, removeEntry, rename, written-path
attribution and the stored-counterpart lookup; issue locations use the same
identity. A rename of an entry stored in two spellings moves the one entry
the runtime merge combines (`combineFoldedConfigEntries`).
- api: the YAML-entry rename guard and the per-batch duplicate check compare
entries by the same identity.
- Tests: unit coverage for each op across spellings, and handler integration
tests against MongoDB for upsert with secret preservation (single and
two-spelling documents), removal, entry_exists, inherited_entry and
duplicate changes in one batch.
* 🙈 feat: Let Config Profiles Hide librechat.yaml MCP Servers and Remove Their Fields
Config profiles are the `__base__`, role, group and user documents written through `/api/admin/config`. A profile can tombstone `mcpServers.<name>`, and the merge then removes that server from the principal's resolved `mcpConfig`.
* 🛡️ fix: Apply MCP Hiding to Server Instructions, Failed Removals and the Startup Audit
- Server instructions bound for the model now leave out librechat.yaml servers hidden from the acting user, including one a model spec pins. `applyContextToAgent` passes the request user through `formatInstructionsForContext`, which drops the user's hidden set from the user-less catalog it reads.
- A config-tier candidate that removes a librechat.yaml value (a field, or a key of a record such as `headers`) and fails inspection now stands as a failed config-source entry instead of falling back to the librechat.yaml base that still carries the removed value. A failed change that removes nothing still falls back, and an entry with no transport (fields written over a hidden server) keeps the documented librechat.yaml fallback.
- The startup tombstone report reads every tenant's profiles in the system tenant scope, so it also runs from entry points without an outer system scope under strict tenant isolation, and names each profile's tenant.
* 🗂️ fix: Project the Startup MCP Tombstone Report Query and Run It Alongside Connections
* 🔑 fix: Keep Removed OAuth Headers Out of the MCP OAuth Callback
* 📝 docs: Note That Removed OAuth Headers Stay Out of MCP Sign-In
* 🔐 fix: Recheck the MCP OAuth Flow's Server Before Initiation Redirects
OAuth initiation redirected to a flow's stored authorization URL, or started
a new authorization from the flow's stored server URL, without resolving the
server again, so a principal whose profile hid the server after the flow was
created could still be sent to its authorization endpoint. The callback's
active-server check and its OAuth header fallback lived in the CJS route.
resolveMCPOAuthTarget (packages/api/src/mcp/oauth/target.ts) now owns both:
it resolves the server in the principal's current config with a strict read,
refuses a flow admitted for another server, a server the principal can no
longer use, or a redefined one, and selects the headers the flow sends (the
initiation snapshot, else the principal's config). Initiation calls it before
either redirect (404 or 400); the callback calls it before the exchange and
from the token-store fence.
* 📝 docs: Note That a Hidden MCP Server Ends OAuth Sign-Ins Already Started
* 🚩 feat: Publish the yamlMcpHide Admin Config Meta Flag
Profiles can hide librechat.yaml MCP servers and a hidden server is an
access boundary, so GET /api/admin/config/meta now reports
features.yamlMcpHide for the admin panel to gate its hide UI on. The
meta.spec probe checks the behaviour itself: the admin API stores an
mcpServers.<name> tombstone, the merged config drops the server, the
registry withholds it from principal lookups and checkout but not from
app-level lookups, process-backed servers stay, and an unreadable
principal config withholds every hideable server.
* 🧪 test: Align MCP Tombstone Specs With the Portable Config Store
The admin config handlers now write whole documents through
writeConfigDocument, so the end-to-end tombstone spec wires it in place
of the removed upsertConfig/patchConfigFields deps. A reset of a whole
MCP record now also prunes the parents it leaves empty.
* perf: Index Hot Lookups and Project the Remote Models List
checkBan reads the KeyvMongo logs collection by key on every request when
bans are enabled, BYOK requests read Key by user and name, and agent tool
loading reads Action by agent_id or assistant_id. None of those fields had
an index, so each read scanned its collection. The Key and Action schemas
gain indexes, and the KeyvMongo store builds a key index on first use
unless the deployment disables auto indexing.
The remote /v1/models routes loaded whole agent documents, including the
unbounded versions history, to read six fields. getAgentModelSummaries
loads only those fields.
* test: Authenticate the Models List Scenarios With an Agent API Key
* fix: Skip Re-Embedding Legacy File Search Files an Agent Already Holds
Files embedded before per-namespace tracking carry no embeddedEntities, so
lazy provisioning treated them as unembedded and embedded them a second
time on the first search after upgrading, duplicating every passage.
A legacy record in the agent's own file_search resources was embedded for
it, so trust its embedded flag there instead of re-queueing it.
* fix: Adopt Legacy Search Embeddings Only for Their Sole Holder
Trusting the embedded flag for every legacy File Search file left an agent
that inherited one querying a namespace without its vectors. Legacy files
held by no other agent now record the active agent as their namespace, a
one-time write, and are not embedded again; a file another agent also
holds keeps the per-namespace re-embed.
Adds an e2e scenario that reshapes an uploaded agent file into the v0.8.7
record and checks that search queries it without a second embed.
* test: Cover Legacy Search Files Shared With Another Agent
* test: Read the Stored File Id in Legacy Search Scenarios
* fix: Pin Legacy Search Adoption to Loaded Records and Wire Every Agent Init
file_id is not unique, so adoption now matches each record by its owner and
tenant as well, and only rewrites the records priming loaded. The added
conversation and client agent initializations receive the dependency too,
so their sole-holder legacy files are not embedded a second time.
* fix: Adopt Each Legacy Search Record in One Conditional Write
* fix: Count a Concurrent Same-Agent Adoption as Adopted
* fix: Run Legacy Search Adoption Beside the Liveness Probe and Fall Back on Failure
* fix: Keep Committed Legacy Search Adoptions When a Sibling Write Fails
* fix: Confirm Legacy Search Embeddings With RAG Before Adopting Them
Inferring the embedding agent from current File Search holders could adopt a
file for an agent whose namespace held none of its vectors, for example after
the agent that embedded it was deleted. Priming now asks RAG for one chunk of
each legacy file under the agent's entity_id and records the namespace only
on a hit; a miss or an unreachable RAG keeps the file queued for embedding.
The data-schemas method no longer scans agents and matches untenanted records
as untenanted. The fake RAG server answers these presence checks from the
embeds it stores.
* fix: Require the Entity's Own Chunks and Keep Confirmed Vectors
RAG also returns chunks owned by the requesting user, so a presence check now
counts only chunks recorded under the agent itself. Once vectors are
confirmed, the turn skips the re-embed even if recording the namespace fails.
* fix: Bound the Legacy Search Check and Keep the Fake RAG Query Shape
The RAG presence check now times out (fileConfig.legacySearchProbeTimeoutMs,
5s by default) and falls back to embedding, so a stalled RAG cannot hang
priming. The fake RAG server records presence checks in their own list and
keeps the file_search query records it already returned.
* fix: Check Any Unrecorded Namespace Before Embedding a Search File
A file another agent embedded first lists only that agent, so the agent
whose older vectors went unrecorded skipped the check and embedded a second
copy. Priming now asks RAG for every agent File Search file that records no
embedding for the active agent, and recording adds the namespace to the ones
already there.
* fix: Ask RAG for Several Chunks So a User Copy Cannot Hide the Agent's
RAG ranks chunks across every owner of a file_id and, once the top one is
authorized, returns them all. A copy of an agent file embedded for the
requesting user could rank first with k: 1 and hide the agent's own chunks,
so the presence check now asks for ten and checks every owner.
* fix: Confirm Setup Embeddings in Shared-File Runs and Log Safely
The run-file host primes an agent's setup files on its own, so it now
receives the RAG presence check and the namespace recorder too; without
them a shared-file run could embed a legacy setup file a second time.
Failed checks are logged with getSafeErrorMetadata rather than the raw
error, which carries the vector store's response body.
* fix: Price 1-Hour Prompt Cache Writes at the 1-Hour Rate
* test: Cover 1-Hour Cache Write Pricing End to End
* test: Price Cache Scenario on the Configured Mock Model
* fix: Accept a 1-Hour Cache Write Rate in Endpoint Token Configs
* fix: Keep Temporary Chats Out of Langfuse
* fix: Gate Forced-Ephemeral and Open Responses Turns From Langfuse
* fix: Treat Legacy and Chat Completion Temporary Turns as Untraced
---------
Co-authored-by: Joel Hirzel <joel.hirzel@eps.ch>
* refactor: Remove Unused Agent Helpers and Superseded Wrappers
* refactor: Remove Dead Auth, Middleware, Protection and Prompt Helpers
* refactor: Remove Dead MCP, File, Skill and Endpoint Code
* refactor: Remove Dead Stream, Telemetry, Utility and Type Exports
* chore: Drop Unused packages/api Dependencies From bun.lock
* refactor: Keep Published Compatibility and Deprecated packages/api Exports
* fix: Run the Erasure Cascade in Admin User Deletion
* refactor: Share Generation Stop Logic Between Self-Service and Admin Deletion
* refactor: Move Admin Erasure Dependency Assembly Into packages/api
* fix: Bind getCleanupJob When Waiting for Generation Persistence
* test: Pin the Deletion Fence Before Admin Generation Stop
* fix: Resolve the Erasure Target Config Fail Closed
* fix: Carry the Target Profile Into Admin Erasure Storage Cleanup
* fix: Keep the Erasure Target Contract Storage Neutral and Reuse the Loaded Identity
* fix: Refuse New Generations Once Account Deletion Has Begun
* fix: Enforce Account Deletion Admission Once in createJob and Narrow the Erasure File Type
* fix: Install the Admission Guard in Every Entrypoint and Purge Refused Jobs
* fix: Guarantee Refused Job Purge and Sanitize Admission Failures
* fix: Route Remote Admission Through createJob and Keep Refusal Cleanup Sanitized
* fix: Log Admission Cleanup Failures With Safe Error Metadata
* refactor: Check Account Deletion Before Creating a Generation and Drain Twice
* refactor: Order Admission Against the Deletion Marker Without a Grace Period
* fix: Sanitize Post-Commit Admission Retirement Failures
* fix: Wire Shared-Server MCP OAuth Cleanup Into Admin Erasure
* fix: Scope Admin Erasure Lookups to the Target Tenant and Await Shared-Link Cleanup
* fix: Resolve the Erasure Target Config Under the Target Tenant
* fix: Run Admin Erasure OAuth Fencing in the Target Tenant
* fix: Match the Split OAuth Invalidate and Disconnect Hooks in Admin Erasure
* refactor: Inject the Tenant Executor Into the Erasure Resolver
* 🧯 feat: Recover Conversations Whose Attachments Keep Failing
Once a branch carries a problem attachment, every turn resends it and
fails the same way. A failed response whose branch carries files now
offers "Retry without files" (re-asks the failed turn with no files as a
new version) and, when earlier turns carry files, "Branch without files"
(a copy up to the last good answer with every upload and code output
left out, with the failed message restored to the composer). File-shaped
errors say so in the card.
The edit view shows a user message's files as removable chips; "Update &
rerun" sends only the kept files and Save is disabled after a removal.
Fork is offered on a failed turn and gains a "Leave out files" option,
backed by a new `excludeFiles` fork option that drops `files`,
`attachments` and the conversation's `files` from the copy.
Bedrock rejects a request whose documents share a name, and history
resends every earlier document, so repeated names are now numbered
before formatting.
* 🧯 fix: Cover Steered Files, Hand Off the Whole Failed Turn, Name Replayed Documents Once
- Excluding files from a fork also strips attachments steered into a
response (`content[].files` on steer parts), which replay like uploads,
and the decision lives in `forkFileScope` in packages/api.
- The recovery card counts steered attachments as files, and reads the
specific code inside a generic `error` envelope, so a rate limit is not
offered files as the fix.
- "Branch without files" hands the failed turn to the copy's composer the
way a message is put back for editing: text through the in-memory
handoff, quotes, manual skills and the reasoning override through their
compose-time atoms.
- Document names are deduplicated over the formatted payload after the
steer stamp, so replayed steer documents are numbered too.
- Fork stays withheld on a failed response, whose copy would carry the
error as an ordinary answer; the card's branch action copies up to the
turn before.
- Remove-file buttons are natively disabled while the editor is locked.
* 🧯 fix: Keep Search Sources, Scope Root Retries, Skip Legacy Rate Limits
- A fork without files keeps metadata-only attachments (search sources,
file search results) and drops only file-backed ones; the recovery card
likewise counts only file-backed attachments as files.
- A turn sent at the root takes none of the conversation's file refs: its
siblings' uploads (an edited first message, or one retried without its
files) no longer come back through the unanchored-continuation fallback.
- Rows that carry a legacy LangChain model, key or rate-limit code are not
offered files as the fix.
* 🧯 fix: Align File Exclusion With Replay's File Shapes, Skip Assistants, Verify the Copy
- Shared `messageCarriesFiles` (with `isFileContentPart`,
`hasContentPartFiles`, `isFileAttachment`) in data-provider names every
shape historical replay reads a file by: uploads, file-backed
attachments, attached `files` on any content part, and `image_file`,
`file` or direct `file_id` locators. The fork drops all of them and the
recovery card detects all of them.
- Assistants conversations get no recovery actions: their upstream thread
keeps every attachment, and those endpoints offer no fork either.
- "Branch without files" checks the returned copy; a server that ignored
`excludeFiles` gets an error toast instead of a false recovery.
* 🧯 fix: Type Replay's Provider-Native File Locators for the Part Predicates