Skip to content

📥 feat: Import Chat Uploads Into Attached Workspaces - #348

Merged
danny-avila merged 5 commits into
mainfrom
danny-avila/workspace-import-file
Oct 23, 2026
Merged

danny-avila merged 5 commits into
mainfrom
danny-avila/workspace-import-file

Conversation

@danny-avila

@danny-avila danny-avila commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Rollout order (read first)

import_file is on by default: the code bridge is experimental and lightly used, so a worker advertises it whenever it can actually perform it. That means workspace writes are enabled, LIBRECHAT_CODE_FILE_RELAY_UPSTREAM is configured, and the Code API offers it (EGRESS_GATEWAY_URL set, so grants can be minted). The Code API has no separate toggle; being able to mint grants is the only condition.

Update LibreChat first. LibreChat releases that predate LibreChat-AI/LibreChat#17376 reject a worker's whole status/capabilities when it lists an operation they don't recognize. #17376 makes LibreChat ignore unknown worker operations (forward-compatible) and is deployed to demo before workers update. Self-hosters on an older LibreChat should update LibreChat before updating workers.

Escape hatch: if a worker must serve an older LibreChat, opt out with LIBRECHAT_CODE_ALLOW_WORKSPACE_IMPORTS=false or run --no-workspace-imports. Any other value of that variable fails startup instead of silently choosing either way.

The opt-out is not stored in the saved setup profile. That profile schema rejects unknown keys, so adding a field would stop older workers from starting with a profile written by a newer setup. The environment variable still applies to workers launched from a profile.

Final contract

The contract is the one agreed for the LibreChat side, with two clarifications that only pin down behavior it left open: bytesWritten is 0 when unchanged: true, and Code API returns typed errors from /v1/workspace-tools/* before dispatch.

  • Operation. import_file, additive, BRIDGE_PROTOCOL_VERSION stays 1. A worker lists it in capabilities.workspaceTools.operations and in each eligible workspace's operations only when it can perform it. LibreChat sends it only when it is listed for the selected workspace.

  • Request (LibreChat to POST /v1/workspace-tools/requests or /execute, same envelope and auth as the other workspace operations):
    { protocolVersion: 1, operation: 'import_file', workspaceId, workspaceInstanceId?, worktree?, path, source: { storage_session_id: string, id: string }, bytes: number, sha256: string /* lowercase hex */, overwrite?: boolean /* default false */ }

    • path follows write_file's rules and may not contain a .git segment or end in / or ..
    • source uses raw Code API storage ids (21-character nanoids).
    • Callers never send egressGrant. A request that includes it is rejected with 400.
  • Result: { protocolVersion: 1, operation: 'import_file', workspaceId, path, created: boolean, unchanged?: boolean, bytesWritten: number, sha256: string }

    • New file: created: true, bytesWritten === bytes.
    • Same bytes already there: created: false, unchanged: true, bytesWritten: 0. Nothing is downloaded or written.
    • overwrite: true replacing different bytes: created: false, bytesWritten === bytes.
  • Errors ({ error, code }):

    Status Code When
    400 INVALID_WORKSPACE_TOOL_REQUEST Malformed request, raw ids not valid storage ids, or a caller-supplied egressGrant
    403 IMPORT_SOURCE_UNAUTHORIZED The caller does not own source
    503 IMPORT_UNAVAILABLE This Code API cannot mint grants (no egress gateway), or minting failed
    413 WRITE_LIMIT_EXCEEDED bytes is over the Code API or worker limit, or the target filesystem lacks free space
    409 EDIT_CONFLICT The target holds different bytes and overwrite !== true, or it changed during the import
    403 WRITE_DISABLED Writes are disabled for that workspace
    422 INVALID_PATH .git path, symlinked parent, or traversal
    422 INVALID_REQUEST Downloaded bytes did not match bytes or sha256
    503 WRITE_UNAVAILABLE The relay or storage was unavailable

    Code API returns INVALID_WORKSPACE_TOOL_REQUEST, IMPORT_SOURCE_UNAUTHORIZED, IMPORT_UNAVAILABLE and its own size check directly, before dispatch, including on the durable submit. The worker returns the other codes, plus WRITE_LIMIT_EXCEEDED for its own limit or free space. On a durable request, the worker's codes appear in the request status error.code.

Why

When a LibreChat chat runs on an attached personal-machine workspace (a BYOM bridge to a paired @librechat/code worker), files the user uploads in that chat never reach the workspace. Only programmatic Bash stages inputs, and only for the length of one run, in $LIBRECHAT_CODE_DATA_DIR. write_file takes only UTF-8 text up to 1 MiB, so zip files, images and PDFs cannot get there at all. Users expect an upload to appear in the workspace, binaries included.

How it works

  1. LibreChat sends import_file with the upload's storage source, its size, and its SHA-256.

  2. Code API checks that the caller owns the object. It applies the same rule as GET /download/:session_id/:fileId for a user-kind object:

    • the live session:<storage_session_id> key must equal the caller's own storage key;
    • an upload:<key><session><id> record must exist for that key, session and object.

    An expired session cache is refused. The caller's claim is never trusted. For durable requests, ownership is checked only when a new request ID is accepted, so a retry of an existing request returns its stored status even if the upload has since expired.

  3. Code API asks the egress gateway (POST /internal/egress-grants) for a grant that covers that one object only:

    • its input_files list holds just that object;
    • max_upload_bytes: 0 and max_output_files: 0, so nothing can be uploaded;
    • max_requests: 2, one download plus one retry;
    • it expires when the request's queue and execution budget run out, plus 30 seconds.

    The request relayed to the worker carries the grant, and source is replaced by the gateway's opaque session and object handles. A synchronous request revokes its grant when it finishes. A durable request lets its grant expire. Durable requests fingerprint the caller's request, so a retry with the same request ID returns the existing record and does not mint a second grant.

  4. The worker downloads the object through LIBRECHAT_CODE_FILE_RELAY_UPSTREAM, the same egress route programmatic inputs already use. It holds no storage credentials.

Worker behavior

  • Path rules. Same as write_file, with workspace and worktree confinement. It also refuses any .git segment, including aliases created by case folding, Unicode-ignorable characters, trailing dots or spaces, and the GIT~1 short name. It refuses a parent directory that is a symlink, a final path segment that is a symlink, and any path that resolves outside the root.
  • Existing target. The worker checks the target before downloading:
    • same SHA-256: returns unchanged: true;
    • different bytes without overwrite: true: returns EDIT_CONFLICT.
  • Writing the file.
    • Missing parent directories are created as 0755.
    • The free-space check needs room for the file plus 64 MiB.
    • The body is streamed into a temporary file in the target directory, never buffered whole. bytes is a hard cap while streaming.
    • The file gets mode 0644 and is synced; size and SHA-256 are then verified by re-reading the synced temporary file through its own descriptor (what gets installed, not just what arrived), and it is installed atomically.
    • Created parent directories are chmod'ed to 0755 explicitly, so a restrictive worker umask does not change them.
    • A create uses an exclusive link, so a file that appears meanwhile is never replaced. An overwrite rechecks the inspected inode immediately before its rename, the same check-then-rename write_file uses. Bridge mutations of one root are serialized, so only an out-of-band local writer could race that last step.
  • On failure. The worker removes the temporary file and any parent directories it created, so a failed or cancelled import leaves no trace and does not quarantine the workspace.
  • Timeouts. A transfer that stalls for 30 seconds fails. The assignment deadline bounds the whole import.

Security model

  • Ownership: checked by Code API using the existing download rule, before any grant exists.
  • Grant scope: one object, read-only, two reads, short-lived, revoked after synchronous use. The worker sees only opaque handles and the grant, never storage credentials or another object's id.
  • Paths: write_file confinement plus the .git, symlink and canonical-root checks above, enforced again at commit time.
  • Integrity: exact size and SHA-256 are verified before install, the install is atomic, the file is never executable, and there are no partial files.
  • Limits:
    • Code API: CODEAPI_BRIDGE_IMPORT_FILE_MAX_BYTES, default 100 MiB, checked before ownership or dispatch.
    • Worker: LIBRECHAT_CODE_IMPORT_FILE_MAX_BYTES / --import-file-max-bytes, default 100 MiB.
    • Worker: free-space check before writing.
  • Deny policy: import_file is a file write. It arms the same durable mutation guard as write_file. It is never advertised for a workspace without writes enabled, and such a workspace refuses it with WRITE_DISABLED. LibreChat treating the upload as consent is decided on its side; the worker and Code API policies still apply.

Compatibility

  • Additive: protocol version 1 is unchanged, and no existing request or result shape changes.

  • Code API: lists import_file in supportedWorkspaceToolOperations only when EGRESS_GATEWAY_URL is configured, because otherwise it cannot mint the grant.

  • Worker: advertises import_file only when all four hold:

    1. the operator has not opted out (LIBRECHAT_CODE_ALLOW_WORKSPACE_IMPORTS=false / --no-workspace-imports; on by default, see Rollout order);
    2. workspace writes are enabled;
    3. LIBRECHAT_CODE_FILE_RELAY_UPSTREAM is set;
    4. the Code API listed the operation (the existing two-step registration negotiation).

    An older Code API therefore never sees it, and a worker without a relay never offers it.

  • LibreChat: sends import_file only when it is advertised. Older workers and Code APIs keep their current behavior.

  • Parent directories: as with write_file, they are created only beneath a descriptor-held root (project roots). A legacy pathname-only root reports a missing parent instead.

Changes

  • packages/code/src/protocol.ts:
    • request and result types;
    • isWorkspaceImportFilePath, isBridgeWorkspaceImportFileRequest (caller form, never carries a grant) and isRelayedWorkspaceImportFileRequest (worker form, must carry one);
    • result validation and the capability allowlist;
    • a shared isWorkspaceMutationOperation, now used by both the worker and the store.
  • packages/code/src/workspace.ts: the confined, streaming, atomic import, and import_file advertisement on writable roots that have an importer.
  • packages/code/src/workspace-import.ts: HttpWorkspaceFileImporter, a bounded, stall-timed streaming download through the relay upstream that also reports free space.
  • relay.ts: now holds the grant header and object URL helpers that programmatic inputs and imports share.
  • cli.ts, workspace-instances.ts, linked-worktrees.ts: wiring, so conversation worktrees and linked-worktree lanes also support imports.
  • service/src/workspace-tools/import.ts: the ownership check, grant claims and the import service.
  • router.ts: validation, limits, authorization, grant minting and revocation, and the import execution budget (min(JOB_TIMEOUT, 5 min)). Disconnect listeners are installed before ownership and grant minting, and a caller that leaves meanwhile never reaches dispatch; its grant is revoked.
  • requests.ts: an optional prepare hook, so a durable request mints its grant once.
  • bridge/router.ts and bridge/enabled.ts: the capability offer.
  • config.ts: the size limit.
  • Docs: ADR 0014, the packages/code README, docs/remote-bridge, OpenAPI, and docker-compose.

Tests

  • packages/code/src/workspace-import.test.ts (a real LocalWorkspaceTools and HttpWorkspaceFileImporter against a local egress stub, plus a real BridgeWorker) covers:
    • protocol validation, including traversal, absolute paths, .git aliases, bad hashes, extra keys and the caller-grant split;
    • result validation;
    • advertisement rules;
    • binary import with 0755 parents and a 0644 file;
    • idempotent re-import with no second download;
    • conflict and overwrite (an executable target becomes 0644);
    • hash, oversize-stream, declared-length and short-stream mismatches, with parent directories rolled back;
    • the worker limit and the free-space limit;
    • symlinked parent, escaping symlink, symlink target, .git path and missing grant;
    • a refused grant and a stalled relay;
    • worker negotiation and guarded execution, and that a worker never advertises the operation to a Code API without it.
  • service/src/workspace-tools/import.test.ts (ioredis-mock, the real session ownership and session-key code, and real prepareSandboxEgress grant sealing) covers:
    • ownership acceptance;
    • rejection of another principal's object, a mixed session and object, a missing upload record and an expired session;
    • grant scope: one object, no uploads, two reads, TTL;
    • the synchronous route: relay, revocation, caller grant, foreign object, stolen request, oversize;
    • IMPORT_UNAVAILABLE when no grants can be minted;
    • the durable route with the real RedisWorkspaceRequests: one grant across idempotent retries, and a conflict before minting.
  • service/src/bridge/router.test.ts: registration offers import_file only when grants can be minted.
  • tests/compose-bridge-config.cjs: the API size-limit pass-through.

Add the additive `import_file` workspace operation so a chat's uploaded
files, binaries included, land in an attached BYOM workspace.

Code API verifies the caller owns the stored object with the download
route's session rule, mints a one-object, read-only, short-lived egress
grant, and relays opaque handles to the worker. The worker streams the
object through its file relay upstream into a same-directory temporary
file, enforces the declared size and SHA-256, refuses `.git` paths and
symlinked parents, and installs it atomically as 0644. Identical bytes
are an idempotent no-op; different bytes conflict unless `overwrite`.

The operation is negotiated: Code API offers it only with an egress
gateway, and workers advertise it only with writes enabled and a relay
upstream configured.
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review

Head: 3035b45

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T05:11:50.126728Z 24c61a5 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review

Head: 3035b45

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3035b45977

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1309 to +1310
if (target.state === 'different') {
await rename(temporary, installTarget);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make overwrite conditional on the inspected inode

When overwrite: true targets an existing file, another local process can replace that file after the preceding lstat(candidate) identity check but before this unconditional rename. The rename then silently overwrites the new inode rather than returning EDIT_CONFLICT, so a concurrent editor's save can be lost despite the operation's guarantee that it replaces only the inode it inspected. Use an atomic compare/exchange strategy or otherwise prevent a path replacement in this check-to-rename window.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Narrowed rather than changed, in 528c5ea. There is no portable atomic compare-and-rename (RENAME_EXCHANGE is Linux-only and not exposed by the root-access layer), and this is the same check-then-rename window write_file/edit_file already have. Bridge mutations of one root are serialized by Code API and the worker guard, so only an out-of-band local writer can race the last step. The inode recheck now runs immediately before the rename, and the docs/comments no longer claim a stronger guarantee.

Comment thread service/src/workspace-tools/router.ts Outdated
Comment on lines +229 to +232
let preparedImport: PreparedWorkspaceImport | undefined;
if (prepareImport != null) {
try {
preparedImport = await prepareImport();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Register disconnect cancellation before preparing the grant

In the synchronous /workspace-tools/execute import path, ownership lookup and the egress-gateway request are awaited before the request/response abort listeners are installed. If the client disconnects during either await, both events have already fired by the time the listeners are attached, so dispatchWorkspaceTool receives a live signal and can still mutate the workspace after the caller cancelled. Install the listeners before the first import-specific await and also check the already-aborted/closed state before dispatch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 528c5ea: abort listeners (plus an already-destroyed-socket check) are installed before ownership and grant minting, and a caller that left meanwhile returns before dispatch; its grant is still revoked in finally. Covered by a new disconnect test.

Comment on lines 730 to 733
if (entry == null) {
try {
await mkdir(current, 0o777);
await mkdir(current, mode);
created.push(current);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply the promised directory mode independently of umask

On POSIX systems the mode passed to mkdir/mkdirat is filtered through the process umask. A worker launched with a restrictive umask such as 0077 therefore creates import parents as 0700, not the documented 0755, which can make the imported path inaccessible to other workspace users or sandbox identities. As is already done for the imported file, explicitly chmod newly created import directories to 0755 before committing them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 528c5ea: directories created by an import are fchmod'ed to 0755 through a held descriptor before the file is staged; the e2e test now runs under umask 0077.

Comment thread packages/code/src/workspace.ts Outdated
Comment on lines +1261 to +1262
hash.update(chunk);
await writeImportChunk(handle, chunk, written);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Hash the staged file instead of only the incoming chunks

The SHA-256 is computed from the downloaded chunks before those bytes are independently written to a temporary file, and the later installation check verifies only the inode. Because that temporary file is visible inside the user-owned workspace during the transfer, another local process can modify already-written offsets or change the file after this digest check; the altered file is then installed while the result still reports the requested SHA-256. Re-read and hash the staged inode after writing, or otherwise prevent concurrent modification until installation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 528c5ea: the stream no longer drives the digest. After sync, size and SHA-256 are computed by re-reading the staged temporary file through its own descriptor, which is what gets installed. A new test rewrites staged bytes mid-transfer and expects INVALID_REQUEST with nothing installed.

Comment thread service/src/workspace-tools/router.ts Outdated
Comment on lines +189 to +193
if (request.operation === 'import_file' && options.imports != null) {
const imports = options.imports;
let sessionKey: string;
try {
sessionKey = await imports.authorize(req, request);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve durable idempotency before reauthorizing the source

Every durable import POST reauthorizes the upload before RedisWorkspaceRequests.submit can detect an existing request ID. If the initial response was lost and the upload or session record is deleted or expires before the client retries, the retry returns IMPORT_SOURCE_UNAUTHORIZED even though the matching durable request may still be queued, running, or completed and capable of mutating the workspace. Move this authorization into the new-record preparation path so a same-fingerprint retry can return the stored status without requiring the source to remain live.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 528c5ea: ownership is checked inside the durable prepare hook, which runs only for a new request ID, so a same-fingerprint retry returns the stored status even after the upload expires (covered in the durable test).

- Verify size and SHA-256 on the synced staged file, not just the stream.
- Set created parent directories to 0755 regardless of umask.
- Install disconnect listeners before ownership and grant minting, and
  never dispatch for a caller that already left.
- Authorize durable imports only for new request IDs so retries of an
  existing request stay idempotent after the upload expires.
- Gate worker advertisement behind LIBRECHAT_CODE_ALLOW_WORKSPACE_IMPORTS,
  since older LibreChat releases reject unknown operations.
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review

Head: 528c5ea

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 528c5eac5c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread packages/code/src/workspace-import.ts Outdated
Comment on lines +150 to +151
arm();
yield next.value;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pause the stall timer while processing each chunk

When writing a yielded chunk takes longer than stallTimeoutMs—for example on a slow or temporarily blocked network filesystem—the timer armed immediately before yield aborts the response while the consumer is writing, even if the source has already delivered the next or final chunk. The subsequent reader.read() then reports a source-transfer stall and rejects an otherwise valid import; arm the timer only while awaiting response headers or reader.read(), as the option contract specifies.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 400c032: the timer is armed only around reader.read() (and the header wait) and cleared before each yield, so consumer writes never count. Covered by a slow-consumer test.

async function removeCreatedDirectories(created: readonly string[]): Promise<boolean> {
for (const directory of [...created].reverse()) {
try {
await rmdir(directory);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Verify created directory identity before rollback

When an out-of-band local process removes or renames an import-created parent and creates a new empty directory at the same path before the import fails, this pathname-only rmdir deletes the other process's directory. Transfers can leave these paths exposed for minutes, and created stores no inode identity, so rollback cannot distinguish the original directory from a replacement; retain and verify directory identity (or a held descriptor) before removing it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 400c032: each created directory's dev/ino is recorded through its descriptor when its mode is set; rollback removes a directory only while it is still that inode, otherwise it reports a possibly committed mutation. Covered by a test that swaps the parent mid-import.

Comment thread service/src/workspace-tools/requests.ts Outdated
const registration = await this.bridge.prepareDurableWorkspaceTool({
...args, tenantId: args.owner.tenantId,
});
const request = args.prepare == null ? args.request : await args.prepare();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revoke grants when durable enqueue is rejected

For a new durable import, this callback mints the egress grant before the atomic queue submission, but returns only the rewritten request and discards the grant ID. If Redis fails, the queue is full, or a concurrent submission wins with the same request ID, no record uses this invocation's grant and no code revokes it, so repeated rejected submissions leave unused egress-ledger entries active until their potentially ten-minute expiry. Preserve the cleanup handle and revoke the grant unless the queue record actually adopts it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 400c032: the durable prepare hook now returns a release that revokes the grant, called when queue.submit throws or returns anything but accepted. Covered by a racing-submission test (only the adopted grant survives).

Comment thread packages/code/src/workspace.ts Outdated
throw new WorkspaceToolError('Workspace storage is unavailable', 'WRITE_UNAVAILABLE');
} finally {
await handle?.close().catch(() => undefined);
if (temporaryNeedsCleanup) await unlink(temporary).catch(() => undefined);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Surface temporary-file cleanup failures

When an import fails before installation and unlinking its staging file also fails—especially when the destination parent already existed—this catch suppresses the cleanup failure and rethrows the original error as though no mutation remained. The workspace can therefore retain a large, possibly already chmodded 0644 file containing upload bytes while the mutation guard is cleared; report the cleanup failure as a potentially committed mutation instead of silently ignoring it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 400c032: a staging unlink failure other than ENOENT now raises WRITE_UNAVAILABLE with mutationMayHaveCommitted, so the guard stays armed.

- Roll back a created parent only while it is still the inode the import
  created; otherwise report a possibly committed mutation.
- Report an unremovable staging file as a possibly committed mutation.
- Arm the stall timer only while waiting on the source, not during writes.
- Revoke a durable import's grant when the queue does not adopt it.
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review

Head: 400c032

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 400c03255e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

.toLowerCase()
.replace(/\p{Default_Ignorable_Code_Point}/gu, '')
.replace(/[. ]+$/, '');
return folded === '.git' || folded === 'git~1';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject NTFS alternate-stream aliases for .git

On Windows with NTFS, a path such as .git::$INDEX_ALLOCATION/config passes this predicate even though ::$INDEX_ALLOCATION aliases the .git directory. installImportedFile subsequently canonicalizes that parent with realpath and installs into the resulting .git path, allowing an import to modify Git metadata despite the explicit .git prohibition. Reject NTFS alternate-data-stream syntax, particularly the $INDEX_ALLOCATION directory alias.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 393c251: .git detection now compares only the part of a segment before any :, so .git::$INDEX_ALLOCATION, .GIT:stream and the git~1 variants are refused; ordinary names containing : on POSIX stay allowed. Tests added.

Compare only the part of each segment before an NTFS stream separator, so
`.git::$INDEX_ALLOCATION` and similar aliases are refused like `.git`.
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review — final review (pass 4 of 4): flag only blocking issues.

Head: 393c251

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 393c251de0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The code bridge is experimental, so import_file is now on whenever a worker
can perform it (writes enabled and a relay upstream configured). Operators
opt out with LIBRECHAT_CODE_ALLOW_WORKSPACE_IMPORTS=false or
--no-workspace-imports; any other value fails startup.
@danny-avila

Copy link
Copy Markdown
Collaborator Author

@codex review — final review (one extra pass after the default-on change): flag only blocking issues.

Head: 24c61a5

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 24c61a525f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danny-avila
danny-avila merged commit 6c5491c into main Oct 23, 2026
23 checks passed
ThabangEnv pushed a commit to ENVIRO365/code-interpreter that referenced this pull request Nov 6, 2026
Nine upstream commits since the 2026-10-22 sync at 0eb6c2d: pathname-root
hardening (LibreChat-AI#361/LibreChat-AI#364), extraction network and credential hardening (LibreChat-AI#359),
proxy-addr 2.0.8 pin (LibreChat-AI#338), Node 24.22.1 / Bun 1.4.4 runtime bumps with
launcher refresh (LibreChat-AI#347), workspace import fixes (LibreChat-AI#348/LibreChat-AI#360), worker command
diagnostics (LibreChat-AI#349). The fork-only diff against upstream is unchanged (18 files).
busla pushed a commit to aproorg/code-interpreter that referenced this pull request Nov 12, 2026
* fix: fail denied input downloads once per batch (LibreChat-AI#177)

* fix: preserve retries for transient egress ledger conflicts (LibreChat-AI#179)

* fix: distinguish retryable ledger contention from scope denials

* fix: preserve error classification through marker discovery and relay

* test: exercise classified denials through gateway configuration

* fix: honor bounded gateway retry hints during object downloads

* perf: reuse authorized input versions and make egress accounting atomic (LibreChat-AI#180)

* perf: reuse authorized input versions and make egress accounting atomic

* perf: resolve authorized input manifests once per execution

* test: preserve fetch signature in revocation fixture

* fix: isolate shared-grant failures and prevent ledger replay

* 🧹 fix: Evict Stale File-Object Index Entries (LibreChat-AI#182)

* fix: evict stale file-object index entries

Forget cached locators after successful deletion and missing-object downloads so replacement keys resolve immediately. Reuse exact resolver matching in the delete route to avoid prefix collisions.

Fixes LibreChat-AI#181

* fix: keep file-object deletion storage-authoritative

* fix: retire superseded upload objects

* fix: canonicalize replacement object keys

* fix: collapse legacy object-key siblings

* fix: recover reads from stale locators

* fix: namespace canonical object identities

* perf: enable authorized input reuse by default (LibreChat-AI#183)

* fix: honor requested input destinations (LibreChat-AI#184)

* fix: disambiguate legacy dotted object identities (LibreChat-AI#186)

* fix: helm egress deployment getting stuck on install (LibreChat-AI#176)

* fix: helm egress deployment getting stuck on install

* only wait for redis if the ledger is required

* Update helm/codeapi/templates/egress-gateway-deployment.yaml

Co-authored-by: Danny Avila <danacordially@gmail.com>

---------

Co-authored-by: Danny Avila <danacordially@gmail.com>

* feat: Add Trusted VM Command Policy (LibreChat-AI#187)

* 🛰️ feat: Add trusted VM command policy

* docs: clarify trusted VM socket boundary

* fix: Retry Clean Cancelled BYOM Settlements Through Stop Grace (LibreChat-AI#188)

A clean atomic workspace mutation rejection was settled with retries cut off at the original execution deadline. When Stop arrived near that deadline, process-tree termination finished after it, so the first settlement attempt was aborted immediately while Code API was still draining the cancellation. The client received ASSIGNMENT_EXPIRED and the durable mutation guard stayed armed.

Route clean workspace mutation rejections through the known-clean rejection recovery path: a transient-retrying heartbeat and settlement retries through the rejection acknowledgement grace, floored at the bridge cancellation settlement grace. Worker shutdown still fails closed. Share the grace constant from the protocol module so the bridge and worker stay aligned.

Closes LibreChat-AI#173

* fix: Release Unassigned Workspace Slots When Dispatch Cleanup Fails (LibreChat-AI#189)

Closes LibreChat-AI#170

* fix: Exit Cleanly When Native Executor Shuts Down Concurrently (LibreChat-AI#191)

* fix: Exit Cleanly When Native Executor Shuts Down Concurrently

A native BYOM worker under systemd KillMode=control-group receives SIGTERM
at the same time as its forked SRT executor. The child ignores IPC once it
is shutting down, so the parent's close handshake is left pending until the
child exits, which rejects it with 'Native executor is unavailable'. That
rejection escaped the CLI finally block and turned an idle administrative
stop into exit status 1.

Treat the close handshake as best-effort: the executor is terminated in
finally regardless, and the active command has already drained, so a lost
or stalled reply carries no mutation risk. Also make the child report exit
status 0 when its own SRT teardown succeeded.

Closes LibreChat-AI#190

* fix: Surface Explicit Executor Cleanup Failures During Close

Only a lost, refused, or stalled close handshake is benign at shutdown.
A negative close reply from the executor is a real cleanup failure and
still rejects so pool shutdown can aggregate it.

* fix: authenticate GitHub App Git operations (LibreChat-AI#192)

* fix: isolate file deletion rate limits (LibreChat-AI#193)

* feat: broker GitHub CLI authentication (LibreChat-AI#194)

* feat: Run PTC in Selected BYOM Workspaces (LibreChat-AI#195)

* feat: run PTC in selected BYOM workspaces

* fix: harden native workspace PTC replay

* fix: preserve replay isolation and bridge limits

* test: tolerate hosts without filesystem cloning

* test: surface copy-on-write clone faults

* fix: harden native workspace PTC admission

* fix: close native replay effect and finalization boundaries

* feat: Report Truncated Output Artifacts (LibreChat-AI#199)

* feat: report truncated output artifacts

* fix: classify omitted artifacts precisely

* fix: preserve artifact scan invariants

* fix: bound depth truncation probes

* fix: bound capped directory enumeration

* fix: constrain truncation probes across the job

* fix: stop exhausted artifact probes

* fix: cancel selected-workspace PTC across processes (LibreChat-AI#196)

* fix: cancel replay jobs across API and worker processes

* fix: drain worker cancellation watches promptly

* fix: close programmatic cancellation races

* fix: preserve cancellation response ordering

* fix: close distributed cancellation races

* fix: harden cancellation under concurrent load

* fix: make cancellation ownership durable through completion

* fix: recover durable replay outcomes across lost replies

* fix: return atomic cancellation outcomes with aligned retention

* fix: commit native results inside the workspace mutation fence

* fix: claim programmatic execution before stalled-job redelivery

* fix: classify capped artifact probe candidates (LibreChat-AI#206)

* feat: Report Deleted Code Session Files (LibreChat-AI#200)

* fix: report deleted persisted files

* fix: reconcile deletions across code runtimes

* fix: preserve protected session inputs

* fix: classify reserved runtime paths

* fix: preserve trusted jq path for PTC (LibreChat-AI#207)

* fix: isolate native PTC readiness and watchdog phases (LibreChat-AI#208)

* feat: Declare Named Worker Project Environments (LibreChat-AI#209)

* feat: declare named worker project environments

* fix: preserve environment trust and negotiated action boundaries

* Harden environment loading and executor identity

* Protect environment root traversal and exact config bytes

* Reject self-controlled environment root aliases

* Check filesystem identities at environment trust boundaries

* Validate environment containment across Linux mount aliases

* Handle stacked mounts conservatively without blocking unrelated paths

* fix: Allow Trusted Own-Root Environment Symlinks (LibreChat-AI#212)

* fix: Allow Trusted Own-Root Environment Symlinks

* fix: Check Alias Parent Ownership by Filesystem Identity

* fix: Enforce Parent Ownership Across Every Environment Path

* fix: Retain Quarantine After Failed Environment Setup (LibreChat-AI#213)

* fix: Retain Quarantine After Failed Environment Setup

* test: Run Native Environment Setup Lifecycle in CI

* fix: Document and Verify Local Setup Quarantine Recovery

* fix: Allow Lambda MicroVM metadata in hardened mode (LibreChat-AI#215)

* docs: add self-hosted worker setup runbook (LibreChat-AI#219)

* fix: bound memory buffering for streamed file uploads (LibreChat-AI#218)

* ci: Automate Auditable Main Releases (LibreChat-AI#216)

* fix: decouple repository release versions

* ci: automate releases after successful main builds

* fix: forward input-file limit into sandbox guests (LibreChat-AI#217)

* feat: Inspect Local Coding Projects (LibreChat-AI#221)

* feat: add bounded local project inventory

* fix: report incomplete Git metadata reads

* fix: preserve incomplete discovery and remote identities

* fix: finalize discovery budgets and nested remote identities

* fix(code): stop project traversal at filesystem budget boundaries

* fix: make automatic release tip check read-only (LibreChat-AI#225)

* feat: Discover Bounded Repository Instructions for Attached Workspaces (LibreChat-AI#226)

* Discover bounded repository instructions for opted-in workspaces

* Verify snapshot digests and cross-platform confinement

* feat: Register Selected Coding Projects (LibreChat-AI#222)

* feat(code): register explicitly selected project roots

* fix(code): reject shared Git metadata for selected projects

* fix(code): pin selected project identity through executor admission

* fix(code): preserve full filesystem identity precision

* Check selected project identity before replay staging

* Anchor replay copies to the verified working directory

* fix: Bind Selected Project Operations to Held Directory Descriptors

* test: Cover Selected Project PTC and Load Native Fixtures Before Platform Simulation

* fix: Keep Native Root Bindings Worker-Local and Verify Directory Ancestry

* fix: Anchor Project Admission and Preserve Search Permissions

* fix: Report workspace admission capacity without ambiguous timeout errors (LibreChat-AI#227)

* fix: Distinguish workspace admission capacity from execution expiry

* test: Preserve execution uncertainty while classifying blocked follow-ups

* fix: Classify admission expiry at the enqueue boundary

* ci: Fix Release Version Resolution for Untagged and Resumed Runs (LibreChat-AI#233)

* ci: Fix Release Version Resolution for Untagged and Resumed Runs

The release workflow resolved its version in one inline shell block under
`set -euo pipefail`, where two paths could not succeed.

Filtering tags through `grep` made a no-match fatal. On the ordinary untagged
tip of `main`, `git tag --points-at HEAD | grep -E '^v[0-9]+...'` exits 1, and
the step died before reaching its skip handling or `next-release-version.sh`, so
a deployable commit could not obtain a release version (LibreChat-AI#228). Selecting stable
tags now reads exit 1 as an empty answer while exit 2 and above still fail the
release, which also lets the missing-previous-tag case report its own error.

The rerun-resume path then rejected the tag it had itself chosen. With a stable
tag already pointing at `HEAD` and no release published, the version comes from
that tag, and the following existence check failed merely because the ref
existed (LibreChat-AI#229). It now compares the tag's commit against the release commit, so
only a tag on some other commit is a collision; `Create tag` already tolerates
a tag that exists.

The block moved into `.github/scripts/resolve-release-version.sh`, beside the
`next-release-version.sh` it calls, so `tests/release-version-resolution.sh` can
cover every path: automatic, resumed, skipped, dispatched, pushed-tag, and the
runs that must be refused, each against a throwaway repository with a stubbed
`gh`.

* fix: harden release resolver execution

---------

Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: Danny Avila <danny@librechat.ai>

* feat: Route GitHub App credentials per repository (LibreChat-AI#236)

* feat: Route GitHub App credentials per repository

* test: Make repository routing assertion deterministic

* fix: Harden repository credential routing

* fix: Bound shared GitHub credential refreshes

* fix: Bind GitHub credentials to admitted workspaces

* fix: Authenticate GitHub App bot identity lookup (LibreChat-AI#237)

* feat: Advertise Workspace Command Timeout Ceiling (LibreChat-AI#238)

* 🌳 feat: Provision Conversation-Scoped Code Worktrees (LibreChat-AI#239)

* feat: provision conversation-scoped code worktrees

* fix: isolate conversation checkout metadata

* docs: clarify isolated conversation checkouts

* fix: revalidate conversation checkout sources

* fix: preserve synchronous legacy execution startup

* fix: harden conversation worktree lifecycle

* test: use canonical workspace isolation keys

* fix: secure conversation worktree provisioning

* fix: preserve isolated workspace lifecycle

* fix: harden conversation worktree provisioning

* fix: fence worktree setup and credential routing

* fix: use kernel-backed provisioning locks

* fix: load worktree locking only when provisioned

* fix: retain conversation provisioning ownership through recovery

* fix: reserve provisioning before launching checkout writers

* fix: pin Git provisioning inputs and close instance admission gaps

* fix: Close native scratch directory streams (LibreChat-AI#240)

* feat(code): route trusted VM GitHub App tokens by checkout (LibreChat-AI#248)

* feat(code): route trusted VM GitHub App tokens by checkout

* fix(code): resolve checkout credentials within canonical root

* fix(code): reject cross-root credential aliases

* 🧹 fix: Await Job Cleanup and Measure Retained Resources (LibreChat-AI#249)

* 🧹 fix: Await Job Cleanup and Measure Retained Resources

* 📡 fix: Scrape Sandbox Runner Metrics in Helm

---------

Co-authored-by: Lia <lia@librechat.ai>

* feat: Allow Installation-Scoped GitHub Tokens for Trusted Workers (LibreChat-AI#263)

* feat(code): allow installation-scoped GitHub tokens on trusted workers

* fix(code): revalidate GitHub installation token grants

---------

Co-authored-by: Lia <lia@librechat.ai>

* ⏳ fix: Let BYOM Workspace Calls Queue Past Thirty Seconds (LibreChat-AI#264)

* ⏳ fix: Let BYOM Workspace Calls Queue Past Thirty Seconds

* fix: Recompute BYOM Reservation TTLs After Admission

---------

Co-authored-by: Lia <lia@librechat.ai>

* 🔐 feat: Recover Code API Machine Credentials After Outages (LibreChat-AI#260)

* 🔐 feat: Recover Code API Machine Credentials After Outages

* 🔐 fix: Protect Recovery Budgets and Persist Compose Enrollment

* 🛡️ fix: Limit Untrusted Code API Recovery Traffic

---------

Co-authored-by: Lia <lia@librechat.ai>

* ⏳ fix: Honor Workspace Queue Budgets Per Request (LibreChat-AI#265)

* fix: bound workspace queue admission per request

* fix: classify pre-enqueue admission expiry and document queue budgets

* fix: deduplicate files by destination before sandbox validation (LibreChat-AI#247)

* fix: deduplicate files by destination before sandbox validation

Some callers (e.g. LibreChat) send the same file more than once per
exec request when a user re-uploads a file in the same conversation.
The sandbox's validateExecuteFiles() rejects duplicate destinations,
which causes every tool call in that conversation to fail with:

  Error from sandbox: [bad_request] files contains duplicate destination "filename.pdf"

This surfaces to the end user as a confusing "sandbox is down" error
when the sandbox itself is fine - it is just rejecting the duplicate
file list.

Fix: add deduplicateFilesByDestination() and call it in getJob()
before validateExecuteFiles(). Keeps the first file for each
destination, silently drops subsequent duplicates, and logs a warning.

* fix: preserve validated destinations when deduplicating input files

* fix: protect submitted code from uploaded file collisions

---------

Co-authored-by: Lia <lia@librechat.ai>

* 🛤️ feat: Schedule Linked Worktrees as Their Own Workspace Lanes (LibreChat-AI#270)

* feat: Schedule Linked Worktrees as Their Own Workspace Lanes

* fix: Refuse quarantined-parent lanes before enqueue, forward lane policy, reset lane fences

- Check the parent checkout fence before the assignment is stored or queued.
- Forward the linked worktree policy to the forked native sandbox.
- Protect shared Git config, hooks and info even before they exist.
- Reset a lane fence with --reset-workspace-worktree.

* fix: Grant lanes an explicit Git write allowlist, hold checkouts on quarantined lanes, release stale lanes

- A lane writes only shared objects, refs, ref logs, LFS storage and its own
  worktree metadata; the checkout HEAD, index, operation state, config and
  hooks stay read-only without per-path denies.
- A checkout assignment waits on any quarantined lane beneath it.
- Lane registrations are released when their worktree disappears and capped
  at 32, dropping command roots and credential routes.

* fix: Refuse a checkout while a lane keeps a stuck fence; let lane probes read shared Git

- Code API indexes the lane fences enqueued beneath each checkout. A checkout
  reaches enqueue only once no lane holds a slot, so an indexed fence that
  still exists is stuck and the checkout is refused, surviving worker restarts.
- Replay probes of a lane may read its common Git directory (read-only).

* fix: Guard linked-worktree Git grants and unresolved actions

---------

Co-authored-by: Lia <lia@librechat.ai>

* 🛡️ fix: Guard Linked-Worktree Lanes Against Accidental Git Pruning (LibreChat-AI#272)

* feat: Schedule Linked Worktrees as Their Own Workspace Lanes

* fix: Refuse quarantined-parent lanes before enqueue, forward lane policy, reset lane fences

- Check the parent checkout fence before the assignment is stored or queued.
- Forward the linked worktree policy to the forked native sandbox.
- Protect shared Git config, hooks and info even before they exist.
- Reset a lane fence with --reset-workspace-worktree.

* fix: Grant lanes an explicit Git write allowlist, hold checkouts on quarantined lanes, release stale lanes

- A lane writes only shared objects, refs, ref logs, LFS storage and its own
  worktree metadata; the checkout HEAD, index, operation state, config and
  hooks stay read-only without per-path denies.
- A checkout assignment waits on any quarantined lane beneath it.
- Lane registrations are released when their worktree disappears and capped
  at 32, dropping command roots and credential routes.

* fix: Refuse a checkout while a lane keeps a stuck fence; let lane probes read shared Git

- Code API indexes the lane fences enqueued beneath each checkout. A checkout
  reaches enqueue only once no lane holds a slot, so an indexed fence that
  still exists is stuck and the checkout is refused, surviving worker restarts.
- Replay probes of a lane may read its common Git directory (read-only).

* fix: Guard linked-worktree Git grants and unresolved actions

* fix: Guard linked-worktree lanes against accidental Git pruning

* fix: Refuse Git Aliases and Allow Pathspec Flags in Worktree Lanes

* fix: Guard Worktree Git Against Indirect Pruning

* fix: Refuse Git Repository Dispatchers in Worktree Lanes

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
Co-authored-by: Lia <lia@librechat.ai>

* 🔓 fix: Let Linked-Worktree Lanes Commit When the Checkout Lives in the Worker Home (LibreChat-AI#274)

* fix: Grant lane Git reads entry by entry so write binds survive a read-denied home

A read grant on the whole common Git directory masked the write binds
beneath it whenever the checkout lived inside the worker home, which SRT
re-binds under a tmpfs (writes first, then reads). Lanes could not create
their own index.lock or ref locks. Grant each entry off the writable paths
instead, and add a real-SRT regression test with a Linux CI job.

* fix: Re-bind lane Git writes after the common read bind instead of granting entries

Per-entry read grants left the common Git directory as a writable tmpfs
placeholder inside the worker home (pack-refs could strand refs there) and
pinned replaced files to stale inodes. Grant the whole directory read-only
again and, on Linux, list each existing writable Git directory as a deeper
read-deny so SRT re-binds its write mount after the ancestor read bind.

* 🎯 feat: Diagnose Every Failing Workspace Edit and Negotiate Tolerant Matching (LibreChat-AI#271)

* 🎯 feat: Diagnose Every Failing Workspace Edit and Negotiate Tolerant Matching

A rejected edit batch now reports every failing edit by position: missing
edits name the nearest candidate line and flag elided, line-numbered,
whitespace-only or CRLF mismatches, and ambiguous edits give their match
count and line numbers. Two negotiated edit features add tolerant matching
(line-trimmed, indentation-flexible, whitespace-normalized) and replaceAll,
with per-edit match reporting only for requests that opt in.

* fix: Honor Edit Boundaries and Negotiated Capabilities

* fix: Preserve Matched Line Endings in Tolerant Edits

* fix: Reject Unrepresentable Tolerant Edit Boundaries

* fix: Require Tolerant Edit Boundary Line Breaks

* fix: Bound Edit Matching and Redact Edit-Only Diagnostics

* fix: Stream Workspace Replace-All Results Within Memory Bounds

* fix: Preserve Extra Blank Lines in Tolerant Edits

* fix: Honor Full Edit Wrappers and Linear Candidate Budgets

* fix: Retain Every Failed Edit Position in Bounded Diagnostics

---------

Co-authored-by: Lia <lia@librechat.ai>

* 🛡️ fix: Deny a Non-Lane Root's Own Git Metadata in the Native SRT Sandbox (LibreChat-AI#276)

* 🛡️ fix: Deny a Non-Lane Root's Own Git Metadata in the Native SRT Sandbox

A trusted-vm command in a native (non-lane) SRT workspace could write the
registered root's own `.git/hooks/*` and `.git/config`, planting a hook or a
`core.fsmonitor` / `filter.*` entry that then runs unsandboxed the next time
the user — or trusted worker code — invokes Git in that checkout.

The non-lane config relied on SRT's mandatory `.git/hooks` and `.git/config`
denies, which on Linux are computed from the worker *process's* current
directory (see `sandbox/linux-sandbox-utils.js`). The worker's cwd is its home
(the systemd user unit sets no WorkingDirectory), never the registered root, so
those denies landed elsewhere and the root's `.git` was writable. macOS was
unaffected because it applies global `**/.git/hooks/**` and `**/.git/config`
Seatbelt patterns.

`NativeSrtWorkspaceCommandSandbox` now adds explicit `denyWrite` entries for the
registered root's own Git metadata when `<root>/.git` is a directory (lanes are
untouched — they already keep the whole common Git directory read-only):

- `<root>/.git/hooks` and `<root>/.git/config` unconditionally;
- `<root>/.git/config.worktree` and `<root>/.git/commondir` where they exist;
- the same files for every submodule Git directory under `.git/modules/**`
  (including nested submodules) and every `.git/worktrees/*`.

`commondir` and `config.worktree` are denied only where present: Git reads them
strictly and SRT would otherwise mask an absent target with an empty `/dev/null`
bind Git cannot parse, breaking ordinary commands. Denied files that exist are
re-bound read-only, so `.git/config` stays readable (remotes keep working) while
writes fail; a benign `git commit` in the workspace is unaffected.

Tests: a live SRT test gated on `LIBRECHAT_CODE_LIVE_SRT_TESTS=1` runs the
sandbox with `process.cwd()` outside the root and asserts hooks, config, an
existing per-worktree config, a submodule config, and a linked-worktree
commondir cannot be tampered while a normal commit still succeeds; wired into
the Linux native-sandbox CI job. A fast unit test asserts the computed
`denyWrite` set. `packages/code/README.md` documents the guarantee and the
residual writable-`.git` vectors (whole-`.git` replacement, a fresh top-level
commondir, a nested repo) that the personal-machine SRT trust model accepts.

* 🔁 fix: Refresh Root Git Metadata Denies per Command and Fail Closed

The root's Git metadata denies were a snapshot taken at sandbox
initialization, but the worker is long-lived: a repository, submodule, or
linked worktree created on the host afterwards stayed writable until restart.
Ordinary root commands now recompute the set and pass it as a per-command
`denyWrite` override (every other filesystem field is the session policy),
the way SRT recomputes its own mandatory denies on every wrap. Native Windows
keeps the initialization snapshot because srt-win rejects per-command
allowRead/allowWrite.

Inspecting the metadata now treats only ENOENT/ENOTDIR as absence; any other
failure propagates, so an unreadable `.git` fails the command closed
(COMMAND_UNAVAILABLE) instead of silently dropping a deny.

Corrects the `config.worktree` comment: in a repository that already enables
`worktreeConfig`, a missing per-worktree config stays creatable, because
denying an absent file makes every Git command fail. The README lists it with
the other writable-workspace residuals.

* 🧷 test: Retain the Contention Lock Owner Through Garbage Collection (LibreChat-AI#283)

Co-authored-by: Lia <lia@librechat.ai>

* 🪟 feat: Preserve Command Output Heads and Tails (LibreChat-AI#275)

* 🪟 feat: Preserve Command Output Heads and Tails

* 🪟 fix: Retain Logical Command Output Suffixes

---------

Co-authored-by: Lia <lia@librechat.ai>

* ♻️ feat: Reuse Verified Environment Preparation (LibreChat-AI#286)

* feat: Reuse Verified Environment Preparation

* fix: Preserve Environment Setup Recovery Diagnostics

* 🧰 feat: Share Explicit Environment Tool Resources (LibreChat-AI#287)

* feat: Grant Explicit Shared Tool Cache Resources

* fix: Reject Replaced Tool Stores Before Dispatch

* test: Verify Protected Receipt Contents Across Native Platforms

* 📦 feat: Restore Isolated Dependency Snapshots (LibreChat-AI#288)

* feat: Restore Isolated Dependency Snapshots

* fix: Reject Dependency Hardlink and Control Path Aliases

* feat: Bound Managed Environment Storage (LibreChat-AI#289)

* 🔬 feat: Begin the OpenShell Backend Evaluation Track (LibreChat-AI#282)

Co-authored-by: Lia <lia@librechat.ai>

* feat: Retire Stale Linked Worktrees Automatically (LibreChat-AI#299)

* 🧹 feat: Retire Stale Linked Worktrees Automatically

Agents create one linked worktree per task under <checkout>/.worktrees and
nothing ever removed them. Each keeps its own dependencies and build output,
so a trusted-VM checkout accumulated 231 worktrees and filled its disk to 100%
three times, quarantining workspaces.

A worker with linked worktree lanes now retires stale worktrees in the
background: two minutes after start, every six hours, sooner while a backlog
remains, and before managed setup would be deferred for low disk space. A
worktree is retired only when it verifies as a linked worktree under
.worktrees, no request uses its lane or checkout, it has been idle for seven
days by both this worker's lane use and on-disk Git activity, it is clean,
unlocked, outside any merge/rebase/cherry-pick/revert/bisect, unquarantined,
and its work is published or merged: HEAD is contained in a remote-tracking
ref, or, with no live upstream (detached, never pushed, or upstream deleted
after merge), its commits are already in the remote's default branch by
content (patch-equivalent per git cherry, or identical content at every path
the branch changed). Squash-merged branches and abandoned review worktrees
therefore qualify; only local Git is consulted. Removal is
`git worktree remove` without --force followed by `git worktree prune`;
branches are kept so `git worktree add` restores any worktree.

Retirement is on by default. --no-worktree-retirement or
LIBRECHAT_CODE_WORKTREE_RETIREMENT=false disables it, and
--worktree-idle-days / LIBRECHAT_CODE_WORKTREE_IDLE_DAYS change the threshold.
LIBRECHAT_CODE_LOG_LEVEL=debug logs every kept worktree with its reason.

* fix: Fence Checkout Requests During Retirement and Never Cut Removal Short

- Checkout requests wait for an in-progress retirement of any lane beneath
  them, since root commands can reach .worktrees/*.
- Requests waiting on a retirement honor their own cancellation.
- git worktree remove runs without a timeout; a killed removal could leave a
  half-deleted worktree that no later pass can verify.
- Drop the repository-wide git worktree prune: remove already deletes the
  retired worktree's metadata, and prune would also expire other registered
  worktrees that are only temporarily unavailable.
- Read every .worktrees entry each pass instead of the first 4096.

* fix: Recheck Quarantine Under the Lane Reservation

A checkout or lane request that finished between inspection and the lane
reservation may have left an uncertain mutation quarantined. Re-read both
quarantine markers inside the reservation, immediately before removal.

* fix: Defer Retirement When the Checkout Was Used During Inspection

A checkout request can write ignored files inside .worktrees/<name> that
git status never reports, and finish before the lane reservation. Count
checkout request starts and finishes, capture the count before inspecting
each worktree, and keep the worktree for a later pass when it changed by the
time the reservation is held.

* test: Clone the Merge-Simulation Remote on main Regardless of init.defaultBranch

On CI the bare remote's HEAD names master, so the hosting clone had an empty
HEAD and `git merge --squash` refused to run.

* fix: Report Missing Workspace Paths as NOT_FOUND and Create Missing Parents on Write (LibreChat-AI#301)

* 🧭 fix: Report Missing Workspace Paths as NOT_FOUND and Create Missing Parents on Write

A missing file, directory or search scope no longer reports INVALID_PATH. When
every existing ancestor resolves to a directory inside the workspace, the
worker returns NOT_FOUND ("Workspace path does not exist"); escapes, symlinks,
files used as directories and other path-safety failures keep INVALID_PATH.

write_file creates missing parent directories beneath the workspace or lane
root, one verified level at a time, never through a symlink or an existing
file, and removes the directories it created if the write then fails.

Code API advertises the added code in registration and maps it to HTTP 422
like INVALID_PATH. A worker reports NOT_FOUND only to a Code API that
advertised it, and resends a refused settlement with INVALID_PATH, so older
Code API replicas keep accepting settlements.

* fix: Anchor Parent Creation to a Held Root, Sync It, and Surface Cleanup Failure

Parent directories are created only under a held root descriptor, where
mkdirat cannot follow a swapped path out of the root. A pathname-only root
creates nothing and reports the missing parent as NOT_FOUND.

Each created directory is synced into its parent before the write is
acknowledged, and a rejected write that cannot remove a directory it created
now reports a possible mutation instead of an atomic failure.

* fix: Recheck Ancestors Before NOT_FOUND and Sync Parent Cleanup

A miss is reported as NOT_FOUND only when the walk reached it through real
directories that still have the same identity afterwards; any symlink in the
chain stays INVALID_PATH. Cleanup syncs each removal into its parent and
treats any directory it could not durably remove as a possible mutation.

* fix: Keep Created Parents as a Committed Side Effect

Directories a write creates are no longer rolled back. Once one exists the
write finishes despite cancellation, and any later failure is reported as a
possible mutation. A raced EEXIST parent is synced too, and the NOT_FOUND
ancestry recheck now includes the workspace root.

* feat: Quote the Current Text Where a Missing Workspace Edit Belongs (LibreChat-AI#300)

* 📍 feat: Quote the Current Text Where a Missing Workspace Edit Belongs

A missing edit's diagnosis now ends with a bounded excerpt of the region
old_text most likely meant: the alignment where most of its distinctive lines
fall into place (found in one pass with bounded votes), else its unique first
line or closest line. Each of at most 8 rows is `<line>|<mark><text>`, with a
space for identical lines, `~` for whitespace-only differences and `!` for
changed text; lines are shortened to 160 characters and the excerpt to 1,600.

The excerpt is a final `; the current text at lines A-B (...) is "<json>"`
hint, so hosts that parse the existing grammar drop it and keep every other
hint. Excerpts are the first detail dropped to fit the 3,000-character
message bound and never shorten another edit's reason.

* 🧭 fix: Bound Every Alignment Offset and Anchor Excerpts Where old_text Starts

- Count every inspected anchor offset against the region vote budget, and stop
  at the first offset that would start before the file (offsets ascend), so a
  repetitive old_text cannot escape the bound.
- Start a first-line or closest-line excerpt at the line where old_text starts,
  not at its first non-blank line.
- Escape U+2028/U+2029 in quoted text, which JSON.stringify leaves raw, so each
  batch edit stays on one line for hosts that read the message line by line.

* 📏 fix: Bound Edit Excerpts by Their Encoded Error-Body Size

Code API returns the diagnostic inside a JSON error body, and LibreChat reads
that body through a 4,096-byte buffer, discarding a truncated one. A
3,000-character message with multibyte or escape-heavy excerpts could exceed
it. Excerpts are now limited to 1,600 bytes and granted only while the whole
message stays within 3,800 bytes, both measured as UTF-8 once JSON-encoded.

* 📐 fix: Shorten Edit Diagnostics by Encoded Size as Well as Length

Batch reasons that still exceed the bound after excerpts are declined are now
shortened against both the 3,000-character limit and the 3,800-byte encoded
budget, and a single edit's reason is shortened the same way instead of being
cut by character count. Multibyte closest-line quotes can no longer push the
Code API's error body past the 4,096 bytes hosts read.

* feat: Persist Workspace Admission Across API Restarts (LibreChat-AI#302)

* 🧾 feat: Persist Workspace Admission Across API Restarts

* 🧾 fix: Fence Durable Admission Recovery Across Replicas

* 🧾 fix: Fence Durable Capacity Acquisition Before Dispatch

* 🧾 fix: Retain Durable Quarantine Outcomes Across Restarts

* 🧾 fix: Preserve Durable Admission and Read Cancellation

---------

Co-authored-by: Lia <lia@librechat.ai>

* 📖 feat: Stream Bounded Workspace File Reads (LibreChat-AI#303)

* 📖 feat: Stream Bounded Workspace File Reads

* 🧹 fix: Settle Interrupted Reads Before Pending I/O Cleanup

* ⏱️ fix: Track Workspace Read Interruption Through Cleanup

* 🧪 test: Queue Descriptor I/O Consistently on Node 20

---------

Co-authored-by: Lia <lia@librechat.ai>

* 🗂️ fix: Guard Lane Worktree Registration (LibreChat-AI#304)

* 🗂️ fix: Guard Lane Worktree Registration

* test: Cover Linked Lane Worktree Registration Denials

---------

Co-authored-by: Lia <lia@librechat.ai>

* 🛡️ fix: Harden Sandbox Startup and Internal Transports (LibreChat-AI#305)

Co-authored-by: Lia <lia@librechat.ai>

* 🐳 ci: Publish Code API Images to GHCR (LibreChat-AI#307)

* 🐳 ci: Publish Code API Images to GHCR

Build one linux/amd64 image per Compose build on pushes to main that touch an
image input, tag it sha-<commit>, and move the main tags together once every
image has built. Pull requests build without pushing. Each image keeps a
registry build cache so the KVM sandbox runner does not recompile its runtime
packages on every push. README documents the tags and a Compose override for
pulling instead of building.

* 🏷️ fix: Build Every Main Commit and Promote the Newest Complete One

Give each main commit its own concurrency group so a queued run can no longer
be replaced and lose its sha tags. The promote job now serializes, resolves the
newest main commit that has every image, retries each retag, and finishes a
partial move on the next run. Report each pushed digest in the job summary and
document per-image digest pinning. Drop the disk cleanup step: a cold KVM
runner build peaked at about 17 GB of builder state with over 95 GB free.

* 🔒 fix: Write Commit Tags Once and Never Move main Backwards

Skip building any image whose sha tag for the commit already exists, so a
re-run that fails part-way cannot mix two builds under one commit. Promotion
retries tag inspections and refuses to move an image's main to an older commit
than it names, so a transient registry error can delay a promotion but not
reverse one. Note that the macOS override keeps building its own sandbox
target.

* 🧯 fix: Fail Closed When the Registry Cannot Answer

Read image revisions through one script that tells a missing tag (or one this
token may not read, and so may not write) apart from a registry that does not
answer. The write-once check and the promotion now fail on the latter instead
of treating it as a missing tag, so neither can rebuild over an existing tag or
move main backwards. Restore the disk cleanup on the KVM runner leg, since the
hosted runner only guarantees 14 GB free.

* fix: block sandbox descriptor passing into unix socket gc (LibreChat-AI#309)

* feat: replace tool-call sockets with anonymous pipes (LibreChat-AI#310)

* feat: replace job-visible tool-call sockets with anonymous pipes

* test: Observe Broker Cancellation Through TCP Peer

* fix: Align Bun 1.4.2 and Verify Packaged Pipe Runtime

* chore: Drop Node 20 Support

* fix: Bound Pipe Failure Paths and Package Launcher Runtime

* 🧵 fix: Replace Runtime Socketpairs With Anonymous Pipes (LibreChat-AI#312)

* fix: deny socketpairs with pipe-only Python runtime IPC

* test: document and verify Bun socketpair spawn denial

* fix: refresh mutable package-init images during runtime rollout

* test: render runtime rollout chart without optional dependencies

* fix: preserve offline package-init image policy

* 🌿 feat: Report Lane Git Branch And Head On Command Results (LibreChat-AI#311)

* feat: Report Lane Git Branch And Head On Command Results

The worker reads the checked-out branch and HEAD of the lane a command ran in and attaches them to execute_command results as laneGit. Code API validates the value and forwards it only when CODEAPI_BRIDGE_LANE_GIT is enabled and the worker advertised lane_git.

* fix: Address Review Findings on Lane Git Reporting

Compare a retried settlement with the stored one before replica-local lane Git sanitization, and skip the Git probe until lane_git is negotiated at registration.

* fix: Bound Lane Git Probe and Pass Flag Through Compose

Cap the post-command Git probe to the budget the command left, reserving settlement time, and pass CODEAPI_BRIDGE_LANE_GIT to the api and service-worker compose services.

* fix: Harden Lane Git Probe Bounds and Reported Values

Bound root resolution with the probe limit, enable the probe from the worker's active registration, require HEAD to peel to a commit, and reject Unicode control and format characters in branch names.

* fix: Trust Only Probed Lane Git and Use the Worker Deadline

Assign the lane Git worker on the normal startup path, budget the probe from the worker's assignment deadline, and drop any laneGit supplied by the command executor.

* fix: Reuse Settlement Reads and Preserve Branch Whitespace

Fold lane Git sanitization into the settle path's existing reads instead of a separate pre-pass, and strip only Git's trailing newline from probe output.

* fix: Report Null for Non-UTF-8 Branch Names

Read the lane branch as bytes and decode it strictly, so a ref name that is not valid UTF-8 is reported as null instead of a lossy copy.

* fix: Revalidate Source Git Metadata Before Probing

Probe a source or conversation checkout only while its .git is its own plain directory, so a command that rewrites .git to point at another repository cannot make the host-side probe report that repository's branch and head.

* fix: Reject Linked Refs Before Probing Source Git

Walk refs/ and require every entry to be a plain file or directory before the host-side probe runs, so a ref symlinked to another checkout cannot be followed.

* fix: Guard Linked Lane Refs and Report Full Branch Names

Check a linked lane's metadata HEAD and the shared refs before probing, read the branch from the full symbolic ref instead of --short, and avoid Dirent.parentPath so the refs walk works on Node 20.11.

* fix: Stop the Git Refs Walk When the Probe Aborts

Pass the probe signal into the source and linked worktree metadata checks and check it between directory operations, so an abandoned walk does not keep running after the command result is returned.

* fix: Report Lane Git Only From a Stable Branch Read

Read the branch before and after the head and omit laneGit when it changed in between, so a concurrent checkout cannot pair one branch with another branch's commit.

* fix: Own Object Storage and Pin the Head Before Probing

Require a link-free refs tree and object store with no alternates or reftable before the host-side probe, ignore replacement refs, and read the head from the branch ref the first read named.

* fix: Disable Transports and Lazy Fetch in the Lane Git Probe

Run the probe with no allowed protocols and lazy fetch disabled, so a rewritten .git/config cannot make a missing object trigger a fetch or a transport command on the host.

* fix: Relay Loopback Resolvers Into KVM Guests (LibreChat-AI#314)

* 🧭 fix: Relay Loopback Resolvers Into KVM Guests

The KVM launcher forwards the runner's /etc/resolv.conf into the libkrun guest.
Under Docker Compose that names the embedded resolver 127.0.0.11, but the TSI
guest kernel keeps loopback traffic on its own loopback device, so every
service-name lookup in the guest failed. Generated-file uploads and session
marker reads to egress_gateway were dropped with ConnectionRefused or
FailedToOpenSocket, while connections by IP worked.

When the runner has a loopback nameserver, relay it over UDP and TCP port 53
from the runner's own IPv4 address with socat and hand the guest that address
instead. Further loopback nameservers are dropped, routable resolvers such as
Kubernetes cluster DNS are forwarded unchanged, and startup fails if the relay
cannot listen or the runner has no routable address.

* 🧭 fix: Bound the Guest DNS Relay and Relay IPv6 Loopback

Give both relays an idle timeout and cap concurrent TCP children. socat 1.8
fails every UDP-RECVFROM child given max-children, so the UDP relay relies on its
short idle timeout. Treat a `::1` nameserver as loopback too, relaying it over
IPv6 from the same runner address instead of forwarding an address the guest
would only answer locally.

* 🧭 fix: Recognize Every Loopback Resolver Spelling

Classify nameservers as loopback by value rather than by the canonical `::1`
string: zero-padded or compressed IPv6 loopback and IPv4-mapped 127.0.0.0/8 are
relayed too, forwarding over IPv6 to the address exactly as written. Routable
IPv6 resolvers stay untouched.

* 🧭 fix: Parse Nameserver Addresses Before Loopback Detection

Replace string matching with real parsing. IPv6 addresses are expanded to their
eight groups (compressed zeros, dotted IPv4 tails), and IPv4 addresses are read
in the inet_aton(3) forms glibc accepts in resolv.conf. Then ::1 and
IPv4-mapped or plain 127.0.0.0/8 are relayed in any spelling. Mapped addresses
are relayed over IPv4 to their canonical form. Spellings of the same resolver
collapse into one relayed entry, and addresses glibc rejects are forwarded
unchanged.

* 🔒 Harden Runner Supervisors with Anonymous Pipes (LibreChat-AI#315)

* Harden runner supervisors with anonymous pipes and inherited seccomp

* Load hosted-app netfilter modules in native CI and retain diagnostics

* Keep relay idle on buffered pipe EOF and assert owned descriptor cleanup

* Preserve supervisor DNS resolution without descriptor-send syscalls

* test: check parent-side nsjail startup failure (LibreChat-AI#318)

* fix: resolve packaged pipe addon inside guests (LibreChat-AI#336)

* 🧭 feat: Add Guided Worker Setup And Saved Profiles (LibreChat-AI#339)

* 🧭 feat: Add Guided Worker Setup And Saved Profiles

* 🔒 fix: Keep Pairing Codes Out Of Terminal History

* 🔒 fix: Isolate Secret Prompt Editing State

---------

Co-authored-by: Lia <lia@librechat.ai>

* 🔑 feat: Recover Enrolled Worker Credentials On Startup (LibreChat-AI#341)

Co-authored-by: Lia <lia@librechat.ai>

* 🪪 feat: Add Key-Bound Browser Enrollment And Resumable Setup (LibreChat-AI#342)

* 🪪 feat: Add Key-Bound Browser Enrollment And Resumable Setup

* 🛡️ fix: Protect Setup State And Legacy Enrollment Fences

* 🔐 fix: Remove Completed Setup Secrets And Bind Pending State To Identity

* 🛡️ fix: Bind Setup Recovery State Across Startup Modes

* 🗝️ fix: Protect The Entire Setup Journal Namespace

---------

Co-authored-by: Lia <lia@librechat.ai>

* 📑 feat: Add Standalone File Extraction Service (LibreChat-AI#306)

* 📑 feat: Add Standalone File Extraction Service

* fix: Restrict Worker Control and Preserve Nested Document Text

* fix: Preserve Parser Policy Failures and Startup Restrictions

* fix: Reject Unsupported DOCX Content and Validate OPC XML Parts

* fix: Enforce Complete DOCX Content Structure

* fix: Extract Merged DOCX Cells Once

* fix: Reject Unmappable PDF Font Text

* fix: Normalize Optional PDF Font Encodings

---------

Co-authored-by: Lia <lia@librechat.ai>

* 🩺 fix: Diagnose Unavailable Worker Commands Safely (LibreChat-AI#349)

* fix: Diagnose Unavailable Worker Commands Without Logging Payloads

* fix: Preserve Diagnostic Correlation And Isolate Async Log Sinks

* fix: Preserve Failure Diagnostics Across Cleanup And Log Boundaries

* 🧹 test: Handle Descendant Adoption Races In Orphan Cleanup (LibreChat-AI#352)

* test: handle descendant adoption races in orphan cleanup

* test: bound asynchronous pipe descriptor cleanup wait

* 📥 feat: Import Chat Uploads Into Attached Workspaces (LibreChat-AI#348)

* 📥 feat: Import Chat Uploads Into Attached Workspaces

Add the additive `import_file` workspace operation so a chat's uploaded
files, binaries included, land in an attached BYOM workspace.

Code API verifies the caller owns the stored object with the download
route's session rule, mints a one-object, read-only, short-lived egress
grant, and relays opaque handles to the worker. The worker streams the
object through its file relay upstream into a same-directory temporary
file, enforces the declared size and SHA-256, refuses `.git` paths and
symlinked parents, and installs it atomically as 0644. Identical bytes
are an idempotent no-op; different bytes conflict unless `overwrite`.

The operation is negotiated: Code API offers it only with an egress
gateway, and workers advertise it only with writes enabled and a relay
upstream configured.

* 🛡️ fix: Harden Imports and Make Advertisement Opt-In

- Verify size and SHA-256 on the synced staged file, not just the stream.
- Set created parent directories to 0755 regardless of umask.
- Install disconnect listeners before ownership and grant minting, and
  never dispatch for a caller that already left.
- Authorize durable imports only for new request IDs so retries of an
  existing request stay idempotent after the upload expires.
- Gate worker advertisement behind LIBRECHAT_CODE_ALLOW_WORKSPACE_IMPORTS,
  since older LibreChat releases reject unknown operations.

* 🧹 fix: Tighten Import Cleanup, Stall Timing, and Durable Grants

- Roll back a created parent only while it is still the inode the import
  created; otherwise report a possibly committed mutation.
- Report an unremovable staging file as a possibly committed mutation.
- Arm the stall timer only while waiting on the source, not during writes.
- Revoke a durable import's grant when the queue does not adopt it.

* 🔒 fix: Refuse NTFS Stream Aliases of .git in Import Paths

Compare only the part of each segment before an NTFS stream separator, so
`.git::$INDEX_ALLOCATION` and similar aliases are refused like `.git`.

* ⚡ feat: Advertise Workspace Imports by Default With an Explicit Opt-Out

The code bridge is experimental, so import_file is now on whenever a worker
can perform it (writes enabled and a relay upstream configured). Operators
opt out with LIBRECHAT_CODE_ALLOW_WORKSPACE_IMPORTS=false or
--no-workspace-imports; any other value fails startup.

* 🔗 fix: Update Node Runtimes And Preserve Restored Modules (LibreChat-AI#347)

* 🔗 fix: Refresh Runtime Module Links After Upgrades

* fix: Preserve Canonical User Module Links

* test: Isolate Input-Cache Route Setup

* fix: Complete Runtime Module Link Migration Paths

* fix: Update Patched Node Runtimes And Align Rollout Defaults

---------

Co-authored-by: Lia <lia@librechat.ai>

* fix(codeapi): pin proxy-addr to 2.0.8 (#4534) (LibreChat-AI#338)

* fix(codeapi): pin proxy-addr to 2.0.8 (#4534)

Source: ClickHouse/ai@4215c459945b0de73db0f99d6d86d8b470b96572

* ci(codeapi): mirror upstream node runtime versions

Source: ClickHouse/ai@5f963906ee74d3247802b52ac2cdb8f85a9fcfda

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* 🔐 fix: Harden Extraction Network And Credential Boundaries (LibreChat-AI#359)

Co-authored-by: Lia <lia@librechat.ai>

* 🪜 fix: Create Missing Parents on Pathname-Only Roots So Imports Land (LibreChat-AI#360)

A root registered by path alone (--worker-dir, --workspace, --environment)
holds no descriptor, so write_file and import_file never created a missing
parent there and reported NOT_FOUND. Yet the worker advertised import_file
on every writable root, so LibreChat's first write of
.librechat/attachments/.gitignore failed on such roots and no chat upload
was ever copied.

A write or import whose parent is missing now borrows a root descriptor for
that one request and runs exactly as it does on a selected project root:
mkdirat anchored to the held fd, root ancestry checked per level, rollback
of directories an import created. A root the worker cannot hold by
descriptor is no longer advertised import_file.

* 🔒 fix: Refuse a Pathname Root That Changes Before It Is Held (LibreChat-AI#361)

A pathname-only root replaced between its identity capture and its open is
refused as INVALID_PATH instead of rerunning the mutation unanchored against
the replacement.

* chore(codeapi): import 🔒 fix: Refuse a Pathname Root That Changes Before It Is Held (LibreChat-AI#364)

Source: ClickHouse/ai@183de78d601012ae94f4887c06c06aee77c3bff3

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: danny-avila <110412045+danny-avila@users.noreply.github.com>

* 📦 feat: Add Verified npm Worker Releases (LibreChat-AI#377)

* 📦 feat: Add Verified npm Worker Releases

* ⌨️ feat: Use lc-code As The Primary CLI Command

---------

Co-authored-by: Lia <lia@librechat.ai>

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
Co-authored-by: Ignaz "Ian" Kraft <ignaz.k@live.de>
Co-authored-by: Danny Avila <danacordially@gmail.com>
Co-authored-by: Jackson Riding <99007683+jacksonriding@users.noreply.github.com>
Co-authored-by: lia-by-librechat[bot] <328778573+lia-by-librechat[bot]@users.noreply.github.com>
Co-authored-by: Lia <lia@librechat.ai>
Co-authored-by: proseer-lars <lars@proseertech.com>
Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
Co-authored-by: Dustin Healy <54083382+dustinhealy@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: danny-avila <110412045+danny-avila@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant