Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions .github/workflows/channel-gateway.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ on:
- 'package.json'
- 'package-lock.json'
- 'scripts/typecheck.mts'
- '.dockerignore'
- 'docker-compose.channels.yml'
- '.github/workflows/channel-gateway.yml'
push:
branches: [dev]
Expand All @@ -17,6 +19,8 @@ on:
- 'package.json'
- 'package-lock.json'
- 'scripts/typecheck.mts'
- '.dockerignore'
- 'docker-compose.channels.yml'
- '.github/workflows/channel-gateway.yml'
workflow_dispatch:

Expand Down Expand Up @@ -50,3 +54,71 @@ jobs:
run: npm run test:ci --workspace @librechat/channel-gateway
- name: Build gateway
run: npm run build --workspace @librechat/channel-gateway
- name: Build standalone image
run: docker build -f packages/channel-gateway/Dockerfile -t channel-gateway:ci .
- name: Verify standalone image and fail-closed startup
shell: bash
run: |
docker run --rm --entrypoint node channel-gateway:ci -e "const fs=require('node:fs');if(process.getuid()===0||!fs.existsSync('/app/main.cjs')||fs.existsSync('/app/node_modules'))process.exit(1)"
set +e
output=$(docker run --rm channel-gateway:ci 2>&1)
status=$?
set -e
if [ "$status" -eq 0 ]; then
echo 'Gateway unexpectedly started without a channel binding.'
exit 1
fi
if ! grep -q 'channel_gateway_startup_failed' <<< "$output"; then
echo 'Gateway did not report its expected safe startup failure.'
exit 1
fi
- name: Smoke-test isolated webhook process
run: |
docker run --rm -i --read-only --entrypoint node channel-gateway:ci - <<'NODE'
const http = require('node:http');
const { spawn } = require('node:child_process');
const { createHmac } = require('node:crypto');
const { setTimeout: delay } = require('node:timers/promises');
const bundle = {
channel: { channelId: 'fixture', tenantId: 'fixture', agentId: 'agent_fixture', createdBy: 'owner', type: 'slack', status: 'active', revision: 'fixture', slack: { teamId: 'T1', appId: 'A1', botUserId: 'U1' } },
gateway: { version: 1, transport: 'webhook', nativeSessions: false, lifecycleReactions: false, signatureToleranceSeconds: 300 },
credentials: { botToken: 'fixture', signingSecret: 'fixture-signing' }, agent: { id: 'agent_fixture' },
};
const backend = http.createServer((req, res) => {
if (req.url.endsWith('/runs/claim')) { req.resume(); res.writeHead(204); res.end(); return; }
res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(bundle));
});
backend.listen(0, '127.0.0.1', async () => {
const child = spawn(process.execPath, ['/app/main.cjs'], {
env: { ...process.env, LIBRECHAT_INTERNAL_URL: `http://127.0.0.1:${backend.address().port}`, CHANNEL_SERVICE_TOKEN: 'fixture', CHANNEL_TENANT_ID: 'fixture', CHANNEL_ID: 'fixture' },
stdio: 'ignore',
});
const exited = new Promise(resolve => child.once('exit', resolve));
const deadline = setTimeout(() => child.kill('SIGKILL'), 10000);
try {
let ready = false;
for (let attempt = 0; attempt < 50; attempt++) {
try { ready = (await fetch('http://127.0.0.1:8080/healthz', { signal: AbortSignal.timeout(500) })).ok; } catch {}
if (ready) break;
await delay(100);
}
if (!ready) throw new Error('Gateway did not become healthy');
const body = JSON.stringify({ type: 'url_verification', challenge: 'verified' });
const url = 'http://127.0.0.1:8080/slack/events/fixture/fixture';
const unsigned = await fetch(url, { method: 'POST', body });
if (unsigned.status !== 401) throw new Error('Unsigned challenge accepted');
const timestamp = String(Math.floor(Date.now() / 1000));
const signature = 'v0=' + createHmac('sha256', 'fixture-signing').update(`v0:${timestamp}:${body}`).digest('hex');
const signed = await fetch(url, { method: 'POST', body, headers: { 'x-slack-request-timestamp': timestamp, 'x-slack-signature': signature } });
if (signed.status !== 200 || (await signed.json()).challenge !== 'verified') throw new Error('Signed challenge rejected');

child.kill('SIGTERM');
if (await exited !== 0) throw new Error('Gateway did not exit cleanly');
console.log('Standalone gateway became healthy and stopped cleanly.');
} catch {
child.kill('SIGKILL'); process.exitCode = 1;
} finally {
clearTimeout(deadline); backend.closeAllConnections(); backend.close();
}
});
NODE
20 changes: 20 additions & 0 deletions docker-compose.channels.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
services:
channel-gateway:
profiles: [channels]
build:
context: .
dockerfile: packages/channel-gateway/Dockerfile
init: true
restart: unless-stopped
read_only: true
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
environment:
LIBRECHAT_INTERNAL_URL: http://api:${PORT:-3080}
CHANNEL_SERVICE_TOKEN: ${CHANNEL_SERVICE_TOKEN:-}
CHANNEL_TENANT_ID: ${CHANNEL_TENANT_ID:-}
CHANNEL_ID: ${CHANNEL_ID:-}
APP_TITLE: ${APP_TITLE:-LibreChat}
SLACK_APP_TOKEN: ${SLACK_APP_TOKEN:-}
stop_grace_period: 10s
2 changes: 2 additions & 0 deletions packages/api/src/channels/service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@ it('uses one policy snapshot and supplies the verified webhook credentials only
lifecycleReactions: true,
signatureToleranceSeconds: 60,
maxDeliveryParts: 1,
socketReconnectDelayMs: 100,
}));
deps.config = config;
const id = await createChannel();
Expand Down Expand Up @@ -378,6 +379,7 @@ it('uses one policy snapshot and supplies the verified webhook credentials only
nativeSessions: true,
lifecycleReactions: true,
signatureToleranceSeconds: 60,
socketReconnectDelayMs: 100,
});
expect(result.body.delivery).toEqual({ maxDeliveryParts: 1 });
expect(result.body.gateway).not.toHaveProperty('enabled');
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/endpoints/config/endpoints.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ describe('createEndpointsConfigService', () => {
nativeSessions: true,
lifecycleReactions: true,
signatureToleranceSeconds: 60,
socketReconnectDelayMs: 100,
};
const deps = createMockDeps({
loadDefaultEndpointsConfig: jest.fn().mockResolvedValue({
Expand Down
35 changes: 35 additions & 0 deletions packages/channel-gateway/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
FROM node:24.22.1-alpine AS build

ENV SCARF_ANALYTICS=false HUSKY=0
WORKDIR /build

COPY package.json package-lock.json ./
COPY api/package.json ./api/package.json
COPY client/package.json ./client/package.json
COPY packages/api/package.json ./packages/api/package.json
COPY packages/client/package.json ./packages/client/package.json
COPY packages/chat/package.json ./packages/chat/package.json
COPY packages/data-schemas/package.json ./packages/data-schemas/package.json
COPY packages/data-provider/package.json ./packages/data-provider/package.json
COPY packages/channel-gateway/package.json ./packages/channel-gateway/package.json
COPY vendor/code ./vendor/code
RUN npm ci --ignore-scripts --no-audit --workspace @librechat/channel-gateway --workspace librechat-data-provider --include-workspace-root=false

COPY packages/data-provider ./packages/data-provider
COPY packages/channel-gateway ./packages/channel-gateway
COPY scripts/typecheck.mts ./scripts/typecheck.mts
RUN npm run build --workspace librechat-data-provider \
&& npm run typecheck --workspace @librechat/channel-gateway \
&& npm run build --workspace @librechat/channel-gateway

FROM node:24.22.1-alpine AS runtime

ENV NODE_ENV=production PORT=8080 LISTEN_HOST=0.0.0.0
WORKDIR /app
COPY --from=build --chown=node:node /build/packages/channel-gateway/dist/main.cjs ./main.cjs
COPY --chown=node:node LICENSE ./LICENSE
USER node
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:'+process.env.PORT+'/healthz',{signal:AbortSignal.timeout(4000)}).then(r=>{if(!r.ok)process.exitCode=1}).catch(()=>{process.exitCode=1})"
CMD ["node", "main.cjs"]
81 changes: 76 additions & 5 deletions packages/channel-gateway/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,75 @@
# Slack transport adapters
# Slack Channel gateway

This private workspace contains transport, native presentation and private interaction adapters for Agent Channels. The executable consumer is the [standalone gateway runtime in #17618](https://github.com/LibreChat-AI/LibreChat/pull/17618), which composes these adapters with native presentation, HTTP and Socket Mode ingress, durable workers, process lifecycle and container packaging.
## Configure one server-owned policy

The adapter build produces seven internal modules:
Configure the application in `librechat.yaml`:

```yaml
endpoints:
agents:
channels:
enabled: true
transport: socket_mode
nativeSessions: false
lifecycleReactions: false
signatureToleranceSeconds: 300
socketReconnectDelayMs: 5000
```

Socket Mode, disabled optional native/lifecycle emission and a 300-second signature window are the defaults. The signature window accepts 1–300 seconds. Socket reconnect delay accepts 100–60,000 milliseconds and defaults to 5,000; consecutive failed attempts use linear backoff. For webhooks, set `transport: webhook` and `gatewayUrl` to the externally reachable HTTPS gateway base URL. Keep the private application service URL internal.

The gateway loads this versioned policy with its private channel bundle before opening its listener or selecting ingress. Deploy matching application and gateway versions: policy version 1 is required, and absent or unsupported versions fail closed. The four ingress/security/feature fields remain required; an older version-1 bundle may omit only the additive reconnect delay and receives its default. Configure `CHANNEL_SERVICE_TOKEN`, `CHANNEL_TENANT_ID`, `CHANNEL_ID`, `LIBRECHAT_INTERNAL_URL` and, for Socket Mode, `SLACK_APP_TOKEN` in the gateway environment. These are process bindings and secrets. `APP_TITLE`, listening settings, provider/service addresses and process request timeouts also remain deployment settings.

Remove legacy `SLACK_NATIVE_SESSIONS`, `SLACK_LIFECYCLE_REACTIONS` and `SLACK_SIGNATURE_TOLERANCE_SECS` environment variables; their presence now fails startup instead of overriding the server. Use the YAML fields above. `SLACK_TRANSPORT` is optional and only asserts the server-selected mode; a mismatch fails startup. Restart gateway replicas after changing ingress mode or the Slack app identity used by Socket Mode. A replica which observes a changed mode or Socket app binding rejects that delivery and becomes unhealthy. Workers read optional feature policy from the current private bundle, while already-frozen delivery plans retain their original operations.

## Install a webhook app

`/healthz` and `/readyz` share the actual readiness state: startup must complete, Socket Mode must be connected to its selected authenticated app when selected, and an observed ingress-policy mismatch makes the replica unready. `/livez` reports only that the HTTP process is alive. The container healthcheck uses `/healthz`.

1. Select webhook mode and set the gateway base URL in the application configuration. Create the Slack app and apply the generated bot capabilities; install it to obtain its bot token. Keep its signing secret private.
2. Activate the Agent Channel with the app/workspace/bot identity, bot token and signing secret, and configure the matching gateway service/tenant/channel bindings. The private bundle requires an active channel with usable signing credentials before webhook verification can succeed.
3. Start the gateway, then apply the generated Events API and interaction URLs to the Slack app. Installation challenges authenticate the original request bytes with that channel's signing secret before echoing the challenge. Missing, stale or tampered signatures cannot pass URL verification. Socket Mode instead requires the app-level token and matching authenticated app identity.

Native Stop remains available for an authenticated existing session even when optional native emission is disabled. The application accepts bounded future clock skew and durably pins each click's first observed target, lease epoch and cutoff, including no target. A retry cannot advance its cutoff or stop a newer run. Past occurrence times remain unchanged; clock skew does not establish a globally exact event order.

## Delivery recovery

The gateway preserves each frozen delivery operation and its receipt. A required operation whose provider result is unknown holds its actor lane: retrying blindly could post the same answer twice. Stopping a worker or requesting cancellation does not prove whether Slack accepted an earlier request.

### Reconcile a verified provider result

1. Pause gateway processing for the affected channel while investigating. Keep the channel enabled and preserve its actor link and source authority; disabling these is not a recovery bypass.
2. Inspect the frozen run plan and retained receipt. Verify in the provider that the exact operation reached the intended channel or thread. Record its message key or file ID, matching the retained attempt and any upload checkpoint. If the result cannot be verified, leave the receipt unknown and the lane held.
3. After the old lease expires, use `POST /api/channels/service/:channelId/runs/claim` with `{ "owner": "<dedicated recovery owner>" }`, normal private service authentication and tenant binding. Verify that the returned run ID is the run being investigated; claims select eligible work and do not take a target run ID. Use the returned current fence, renewing it through `POST /renew` as needed. An expired or replaced worker's fence cannot reconcile the run.
4. Submit the confirmed receipt through the private channel API. These endpoints confirm existing attempts; they do not send messages, replace the frozen plan, reset attempts or accept a retryable outcome.

All paths below are relative to `/api/channels/service/:channelId/runs/:runId`. Send the channel service bearer token and the configured tenant header, using the same internal service URL as the gateway. Preserve the complete fence returned by the claim.

For a delivery operation, `POST /delivery/reconcile`:

```json
{
"fence": { "runId": "<run ID>", "owner": "<current recovery owner>", "epoch": 1 },
"receipt": {
"operationId": "<frozen operation ID>",
"outcome": "confirmed",
"attempts": 1,
"externalMessageKey": "<provider channel ID>:<provider message timestamp>"
}
}
```

Replace every illustrative value with the actual current fence and retained attempt count; do not assume the example epoch is current. Supply `externalFileId` for a verified file operation as required by its frozen operation and checkpoint. Existing provider identities are immutable; reconciliation cannot replace them with a different message or file.

For a progress update, `POST /progress/reconcile` with the current `fence`, the retained progress `revision`, and a `receipt` containing `outcome: "confirmed"`, the retained `attempts` and verified `externalMessageKey`. The message identity remains fixed across progress revisions.

Once every required delivery operation is confirmed, `POST /commit` with the current `fence` to complete delivery and release the actor lane. Resume normal gateway processing afterward. If any required result remains uncertain, keep the run held rather than resending or recreating it. Optional exhausted effects follow the gateway's bounded recovery policy and do not justify replaying a required answer.

## Transport adapter boundary

The standalone process composes private transport adapters with native presentation, HTTP and Socket Mode ingress, durable workers and process lifecycle.

The production bundle incorporates these seven internal source modules:

| Module | Responsibility |
| ---------- | -------------------------------------------------------------------------------------------- |
Expand All @@ -14,9 +81,9 @@ The adapter build produces seven internal modules:
| `identity` | Actor-private account-link tickets and exact-account confirmation |
| `review` | Current actor/action validation, native forms and immutable saved-decision retry |

The application defaults `endpoints.agents.channels.enabled` to `false`. Enable the capability in a deployment that includes the matching executable consumer. These adapter artifacts are internal dependencies; deploying the runnable gateway also requires its entry point, presentation layer and durable worker.
The application defaults `endpoints.agents.channels.enabled` to `false`. Enable the capability in a deployment that includes the matching executable consumer. The deployed `main.cjs` bundle includes its entry point, presentation layer, durable worker and these internal modules.

## Consumer contract
### Consumer contract

Before opening ingress, fetch the private channel bundle, validate its versioned gateway policy and call `resolveGatewayConfig`. The server selects Socket Mode or webhook transport; an optional process transport assertion must match. Missing or unsupported policy fails closed. Application and gateway must both support policy version 1.

Expand All @@ -25,3 +92,7 @@ Webhook consumers pass the original bounded bytes and signature headers to `pars
Forward native Stop with its original occurrence time and complete actor/channel/thread scope. The application owns bounded clock-skew normalization and the durable first-observation target, epoch and cutoff. Retained observation identity follows the external actor/thread across account relinks and channel/agent revisions; it is separate from the versioned execution principal. A retry cannot select a later lane or run. The observation joins account-erasure admission and channel serialization fences; cancellation still requires current authority and the exact lease fence. Optional native-session emission does not revoke cancellation for an existing session.

The runnable consumer preserves canonical execution identities and frozen delivery receipts across restarts. An uncertain required provider write requires reconciliation rather than a blind repeat. The standalone runtime's HTTP/Socket, worker, process and container checks validate that composition in addition to the adapter tests here.

Socket connections use one gateway-owned supervision task. Connection loss immediately fails readiness; retries own every SDK startup result and require a fresh matching-app hello before ingress resumes. Shutdown aborts API requests and backoff, closes the SDK, lets the SDK close its WebSocket transport and drains supervision alongside the worker.

The private bundle also supplies the server’s `maxDeliveryParts` storage limit. New plans reserve required answer output first, group attachment attempts with their failure notice, and explicitly report shortening or omitted optional effects. Already persisted plans retain their frozen operations.
3 changes: 2 additions & 1 deletion packages/channel-gateway/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
"name": "@librechat/channel-gateway",
"version": "0.1.0",
"private": true,
"description": "Slack transport adapters for LibreChat Agent Channels",
"description": "Standalone Slack gateway for LibreChat Agent Channels",
"type": "module",
"scripts": {
"build": "tsdown",
"build:watch": "tsdown --watch",
"start": "node dist/main.cjs",
"typecheck": "node ../../scripts/typecheck.mts",
"test": "jest --watch",
"test:ci": "jest --ci --runInBand"
Expand Down
Loading
Loading