Skip to content

Commit 09f5a7a

Browse files
committed
support explicit multi-daemon socket profiles
1 parent 41de3e4 commit 09f5a7a

8 files changed

Lines changed: 52 additions & 11 deletions

File tree

‎.env.example‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ DISCRIPT_INTENTS=Guilds,GuildMessages,GuildMembers
1414

1515
# Optional execution profile. Direct mode is the default when omitted.
1616
# DISCRIPT_CONNECTION_MODE=direct
17+
# Optional explicit local daemon socket path. This lets clients connect without
18+
# sharing the daemon's Discord token and supports multiple daemon profiles.
19+
# DISCRIPT_SOCKET_PATH=/run/discript/discript.sock
1720

1821
# Daemon profile. Used when DISCRIPT_CONNECTION_MODE=daemon.
1922
# Use socket for local-only, mcp for MCP plus the local broker, or hybrid to

‎deploy/systemd/discript@.service‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
[Unit]
2+
Description=Discript Discord daemon (%i)
3+
After=network-online.target
4+
Wants=network-online.target
5+
6+
[Service]
7+
Type=simple
8+
User=root
9+
EnvironmentFile=/etc/discript/%i.env
10+
RuntimeDirectory=discript-%i
11+
ExecStart=/usr/bin/env node /opt/discript/bin/discript.mjs daemon start
12+
Restart=on-failure
13+
RestartSec=10
14+
KillSignal=SIGTERM
15+
TimeoutStopSec=30
16+
NoNewPrivileges=true
17+
PrivateTmp=true
18+
19+
[Install]
20+
WantedBy=multi-user.target

‎docs/developers/connection-modes.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,9 @@ The Gateway limits helper exposes Discord’s current `remaining`, `reset_after`
4141

4242
The implementation should select the lightest transport that satisfies the operation. A command must not open Gateway solely because it performs a normal REST mutation.
4343

44-
Use `discript daemon start` once, then pass `--broker` on Gateway-backed commands or scripts to reuse that connection. `--broker` is intentionally explicit so an agent can tell whether it is starting a new session or using the shared one. Broker requests have a bounded timeout and return structured `BROKER_TIMEOUT` or `BROKER_UNAVAILABLE` errors.
44+
Use `discript daemon start` once, then pass `--broker` on Gateway-backed commands or scripts to reuse that connection. Set `DISCRIPT_SOCKET_PATH` for an explicit, permission-protected socket; this lets local clients connect without the Discord token and supports multiple daemon profiles. Give each bot a distinct socket and MCP port profile; Linux deployments can use `deploy/systemd/discript@.service`. Leave it unset to retain the legacy token-derived endpoint. `--broker` is intentionally explicit so an agent can tell whether it is starting a new session or using the shared one. Broker requests have a bounded timeout and return structured `BROKER_TIMEOUT` or `BROKER_UNAVAILABLE` errors.
4545

46-
Starting a second daemon for the same token is rejected with `BROKER_ALREADY_RUNNING`; the existing broker endpoint is never removed during startup. A stale endpoint is cleaned up only after no active broker can connect, and bind-time races are reported as the same duplicate-start error.
46+
Starting a second daemon for the same explicit socket path is rejected with `BROKER_ALREADY_RUNNING`; use a distinct socket and MCP port profile for each bot. The existing broker endpoint is never removed during startup. A stale endpoint is cleaned up only after no active broker can connect, and bind-time races are reported as the same duplicate-start error.
4747

4848
Broker and MCP execution responses use the same request envelope. Successful executions contain `ok: true`, `requestId`, `exitCode: 0`, `value`, `warnings`, and `diagnostics`; failures retain the request ID and include a sanitized `code`, `error`, and exit code. This lets agents correlate local and remote execution without transport-specific parsing.
4949

‎docs/operations/configuration-reference.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ Precedence is: explicitly exported process environment, project `.env`, user `~/
66

77
## MCP server profile
88

9-
Set `DISCRIPT_CONNECTION_MODE=daemon` and `DISCRIPT_DAEMON_MODE=socket`, `mcp`, or `hybrid` to start the daemon. The daemon owns one Discord Gateway connection and its local socket broker. `mcp` and `hybrid` also start the configured MCP listener; `hybrid` is the explicit profile for local CLI-over-socket plus remote MCP clients. Use `DISCRIPT_MCP_TRANSPORT=http` or `https`, `DISCRIPT_MCP_PORT` for the primary listener, and `DISCRIPT_MCP_HTTP_PORT`/`DISCRIPT_MCP_HTTPS_PORT` for separate listeners and redirects. HTTPS requires `DISCRIPT_MCP_TLS_KEY_FILE` and `DISCRIPT_MCP_TLS_CERT_FILE`.
9+
Set `DISCRIPT_CONNECTION_MODE=daemon` and `DISCRIPT_DAEMON_MODE=socket`, `mcp`, or `hybrid` to start the daemon. Set `DISCRIPT_SOCKET_PATH` to an explicit Unix socket or Windows named-pipe endpoint for multi-daemon profiles; clients using that path do not need the Discord token. If unset, the legacy token-derived endpoint is used. The daemon owns one Discord Gateway connection and its local socket broker. `mcp` and `hybrid` also start the configured MCP listener; `hybrid` is the explicit profile for local CLI-over-socket plus remote MCP clients. Use `DISCRIPT_MCP_TRANSPORT=http` or `https`, `DISCRIPT_MCP_PORT` for the primary listener, and `DISCRIPT_MCP_HTTP_PORT`/`DISCRIPT_MCP_HTTPS_PORT` for separate listeners and redirects. HTTPS requires `DISCRIPT_MCP_TLS_KEY_FILE` and `DISCRIPT_MCP_TLS_CERT_FILE`.
10+
11+
For multiple Linux daemons, keep one profile per bot under `/etc/discript/<name>.env`, give each profile a distinct `DISCRIPT_SOCKET_PATH`, MCP ports, and credentials, and run the packaged `deploy/systemd/discript@.service` as `discript@<name>.service`. Use `/run/discript-<name>/` for sockets when using the template's `RuntimeDirectory`.
1012

1113
Select `DISCRIPT_MCP_AUTH_MODE=none`, `static`, `bearer-passthrough`, or `oauth2`. OAuth2 additionally requires issuer, resource, and introspection endpoint settings. `DISCRIPT_MCP_ALLOWED_ORIGINS` is a comma-separated CORS allowlist.
1214

‎src/cli.mjs‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -93,18 +93,20 @@ async function runMcpClient(action = 'inspect', options, stdout, positionals = [
9393
}
9494

9595
async function runBrokerCommand(command, options, stdout) {
96-
const token = loadConfig().token;
97-
if (!token) throw Object.assign(new Error('DISCORD_TOKEN is not set.'), { code: 'DISCORD_TOKEN_MISSING', exitCode: 4 });
98-
const result = await brokerRequest({ token, method: 'command', command, options });
96+
const config = loadConfig();
97+
const token = config.token;
98+
if (!token && !config.socketPath) throw Object.assign(new Error('DISCORD_TOKEN is not set.'), { code: 'DISCORD_TOKEN_MISSING', exitCode: 4 });
99+
const result = await brokerRequest({ token, endpoint: config.socketPath ?? undefined, method: 'command', command, options });
99100
if (!result.ok) throw Object.assign(new Error(result.error), { code: result.code, exitCode: result.exitCode ?? 1 });
100101
if (result.value !== undefined) writeResult(result.value, options, stdout);
101102
return result.value;
102103
}
103104

104105
async function runBrokerScript(source, options, stdout) {
105-
const token = loadConfig().token;
106-
if (!token) throw Object.assign(new Error('DISCORD_TOKEN is not set.'), { code: 'DISCORD_TOKEN_MISSING', exitCode: 4 });
107-
const result = await brokerRequest({ token, method: 'script', source, options });
106+
const config = loadConfig();
107+
const token = config.token;
108+
if (!token && !config.socketPath) throw Object.assign(new Error('DISCORD_TOKEN is not set.'), { code: 'DISCORD_TOKEN_MISSING', exitCode: 4 });
109+
const result = await brokerRequest({ token, endpoint: config.socketPath ?? undefined, method: 'script', source, options });
108110
if (!result.ok) throw Object.assign(new Error(result.error), { code: result.code, exitCode: result.exitCode ?? 1 });
109111
if (result.value !== undefined) writeResult(result.value, options, stdout);
110112
return result.value;
@@ -115,7 +117,7 @@ async function runDaemon(action, options, stdout) {
115117
const token = config.token;
116118
if (!token) throw Object.assign(new Error('DISCORD_TOKEN is not set.'), { code: 'DISCORD_TOKEN_MISSING', exitCode: 4 });
117119
if (action === 'start') {
118-
const broker = await withGatewayRetry(() => startGatewayBroker({ token }));
120+
const broker = await withGatewayRetry(() => startGatewayBroker({ token, ...(config.socketPath ? { endpoint: config.socketPath } : {}) }));
119121
const configuredMcpPort = options.mcp_port ?? (config.daemonMode === 'mcp' || config.daemonMode === 'hybrid' ? config.mcp.port : undefined);
120122
if (configuredMcpPort !== undefined && configuredMcpPort !== null) {
121123
const mcpPort = validateMcpPort(configuredMcpPort);
@@ -131,7 +133,7 @@ async function runDaemon(action, options, stdout) {
131133
stdout({ started: true, endpoint: broker.endpoint, ...(configuredMcpPort !== undefined && configuredMcpPort !== null ? { mcpPort: validateMcpPort(configuredMcpPort) } : {}) });
132134
return broker;
133135
}
134-
const result = await brokerRequest({ token, method: action === 'stop' ? 'shutdown' : 'status' });
136+
const result = await brokerRequest({ token, endpoint: config.socketPath ?? undefined, method: action === 'stop' ? 'shutdown' : 'status' });
135137
stdout(result);
136138
return result;
137139
}

‎src/config.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export function loadConfig(env = process.env) {
2929
capabilities,
3030
connectionMode,
3131
daemonMode,
32+
socketPath: stringValue(env.DISCRIPT_SOCKET_PATH, null),
3233
mcp: {
3334
transport: mcpTransport,
3435
host: stringValue(env.DISCRIPT_MCP_HOST, '127.0.0.1'),

‎tests/cli/daemon.test.mjs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,13 @@ describe('daemon CLI lifecycle', () => {
2323
expect(brokerRequest).toHaveBeenCalledTimes(2);
2424
expect(stdout).toHaveBeenCalledWith({ ok: true, ready: true });
2525
});
26+
27+
test('allows an explicit socket profile without a client token', async () => {
28+
delete process.env.DISCORD_TOKEN;
29+
process.env.DISCRIPT_CONNECTION_MODE = 'daemon';
30+
process.env.DISCRIPT_SOCKET_PATH = '/run/discript/test.sock';
31+
await run(['guilds', 'list'], { stdout: jest.fn(), stdin: { isTTY: true } });
32+
expect(brokerRequest).toHaveBeenLastCalledWith(expect.objectContaining({ endpoint: '/run/discript/test.sock', method: 'command' }));
33+
delete process.env.DISCRIPT_SOCKET_PATH;
34+
});
2635
});

‎tests/config.test.mjs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ describe('configuration', () => {
4444
})).daemonMode).toBe('hybrid');
4545
});
4646

47+
test('loads an explicit socket path for multi-daemon profiles', () => {
48+
expect(loadConfig({ DISCRIPT_SOCKET_PATH: '/run/discript/bot-a.sock' }).socketPath).toBe('/run/discript/bot-a.sock');
49+
});
50+
4751
test('redacts secrets for configuration inspection', () => {
4852
const config = loadConfig({ DISCORD_TOKEN: 'discord-secret', DISCRIPT_MCP_AUTH_TOKEN: 'mcp-secret', DISCRIPT_MCP_OAUTH_CLIENT_SECRET: 'oauth-secret', DISCRIPT_CLIENT_TOKEN: 'client-secret', DISCRIPT_CLIENT_HEADERS: '{"Authorization":"header-secret","X-Agent":"discript"}' });
4953
expect(redactedConfig(config)).toMatchObject({ token: '[redacted]', mcp: { authToken: '[redacted]' }, client: { token: '[redacted]' } });

0 commit comments

Comments
 (0)