llm-cli-gateway 2.12.1 → 2.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.md +132 -5
- package/dist/api-provider.d.ts +1 -0
- package/dist/api-provider.js +13 -0
- package/dist/async-job-manager.d.ts +34 -2
- package/dist/async-job-manager.js +344 -46
- package/dist/config.d.ts +34 -0
- package/dist/config.js +91 -0
- package/dist/doctor.d.ts +30 -2
- package/dist/doctor.js +78 -6
- package/dist/endpoint-exposure.js +15 -3
- package/dist/http-transport.d.ts +3 -0
- package/dist/http-transport.js +138 -8
- package/dist/index.d.ts +15 -0
- package/dist/index.js +221 -74
- package/dist/provider-login-guidance.d.ts +12 -0
- package/dist/provider-login-guidance.js +28 -0
- package/dist/provider-status.d.ts +12 -0
- package/dist/provider-status.js +14 -0
- package/dist/provider-tool-capabilities.d.ts +4 -1
- package/dist/provider-tool-capabilities.js +225 -11
- package/dist/resources.d.ts +6 -2
- package/dist/resources.js +72 -8
- package/dist/validation-normalizer.js +5 -4
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/setup/status.schema.json +65 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,29 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to the llm-cli-gateway project.
|
|
4
4
|
|
|
5
|
+
## [Unreleased]
|
|
6
|
+
|
|
7
|
+
## [2.12.2] - 2026-07-01: backpressure hardening and release-gate stability
|
|
8
|
+
|
|
9
|
+
### Security
|
|
10
|
+
|
|
11
|
+
- **HTTP/session and async-job backpressure hardening for issue #130.** HTTP MCP session initialization is now bounded before gateway session creation, including concurrent initialize bursts and `createGatewayServer()` / `server.connect()` failure cleanup. Async process/API jobs now share bounded global, per-provider, and queue caps; queued jobs are treated as in-progress by sync/deferred paths; direct sync and inline API execution are covered by the same limiter; and `/healthz` / `llm_process_health` expose prompt-free session, queue, limiter, and memory pressure metrics. The release includes deterministic regression coverage for HTTP initialize bursts, pending-initialize accounting, queued deferral behavior, and async job caps.
|
|
12
|
+
- **`llm_process_health` now redacts `base_url` userinfo.** The outbound-providers health block surfaces each API provider's `base_url`, which is config-supplied and may legally carry URL userinfo (`https://user:pass@host/v1`). Both the dedicated `xai` block and the generic `apiProviders` array now run `base_url` through `redactDiagnosticUrl` (stripping `username`/`password` and sensitive query params) before emitting it, matching the redaction already applied on the `doctor` and login-guidance surfaces. The live request path and circuit breakers are unaffected.
|
|
13
|
+
- **`redactDiagnosticUrl` now leaves clean URLs byte-identical.** When a URL has nothing to redact (no userinfo, no sensitive query/hash params), the helper returns the caller's exact bytes instead of the URL parser's canonicalized form (lowercased host, dropped default port, normalized path/encoding). This keeps non-secret `base_url` / public-URL values unchanged on every diagnostic surface (`doctor`, login-guidance, `llm_process_health`).
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- **Doctor, status, login-guidance, tool-capabilities, and resources now surface enabled API providers (Slice 6).** The five peripheral discovery surfaces were CLI-only; they now report enabled `[providers.<name>]` (kind:`api`) providers too, staying byte-identical when none are enabled:
|
|
18
|
+
- `doctor --json` gains an `api_providers` health block (per provider: kind, base_url, default_model, models, the key env var name, whether the key is present, and login guidance). The block is omitted entirely when no API providers are enabled. An opt-in `--probe-api-providers` flag adds a reachability result per provider; a normal `doctor` run spends no network or tokens (`reachable` stays null). The key value is never reported, only its presence. `setup/status.schema.json` is updated to match.
|
|
19
|
+
- `provider-status` gains `getApiProviderStatus` (enabled + key-present projection; no spawnable binary) and `provider-login-guidance` gains `getApiProviderLoginGuidance` (where to get the key, which env var, the base_url; keyless-local guidance for loopback providers).
|
|
20
|
+
- `provider_tool_capabilities` now builds real per-`api`-kind metadata on demand instead of the former unreachable defensive throw: API providers support model + sampling + (xai-responses) reasoning + continuity, and never expose allow/deny lists, MCP servers, local skills, or workspace/worktree controls. The capability filter enum, the `provider-tools://<id>` resource allowlist, and the capability-id set widen together to include enabled API provider names.
|
|
21
|
+
- `models://<api-provider>` resources are exposed for every enabled API provider, and `sessions://<api-provider>` for continuity-tracked kinds. The `CLI_TYPES` guard on the `provider-subcommands://` resources is unchanged, so API providers stay correctly excluded there.
|
|
22
|
+
- **`list_models` now surfaces enabled API providers (Slice 5).** When one or more `[providers.<name>]` API providers are enabled, `list_models` returns them under an `apiProviders` array (each tagged `providerKind:"api"` with `defaultModel` and the optional model allowlist), mirroring `list_available_models` and the `llm_process_health` outbound block. The `cli` filter accepts an enabled API provider name in addition to the six CLI providers. The field is omitted entirely when no API providers are enabled, so dormant output is byte-identical to before.
|
|
23
|
+
|
|
24
|
+
### CI
|
|
25
|
+
|
|
26
|
+
- **Lychee no longer fails release/security CI on GitHub's unauthenticated latest-release API.** The link-rot gate now excludes `https://api.github.com/repos/*/*/releases/latest`, matching the upstream-scan model where these advisory release metadata URLs are verified separately and GitHub Actions 403/rate-limit responses should not block an otherwise clean release.
|
|
27
|
+
|
|
5
28
|
## [2.12.1] - 2026-06-30: fast-uri transitive vulnerability remediation
|
|
6
29
|
|
|
7
30
|
### Security
|
package/README.md
CHANGED
|
@@ -234,7 +234,7 @@ Opt-in flags (all default off) live under `[cache_awareness]` in `~/.llm-cli-gat
|
|
|
234
234
|
|
|
235
235
|
- **Retry Logic**: Exponential backoff with circuit breaker for transient failures
|
|
236
236
|
- **Atomic File Writes**: Process-specific temp files with fsync for data integrity
|
|
237
|
-
- **
|
|
237
|
+
- **Host-protection backpressure**: bounded HTTP session lifecycle (max sessions + idle reaper), global and per-provider job-execution limits with a bounded FIFO queue, and a configurable per-job output cap (default 50MB). See [Host-protection limits](#host-protection-limits-http-and-limits).
|
|
238
238
|
- **NVM Path Caching**: Eliminates I/O overhead on every request
|
|
239
239
|
- **Long-Running Jobs**: Non-time-bound async execution via `*_request_async` + polling tools
|
|
240
240
|
|
|
@@ -665,6 +665,61 @@ Legacy environment variables (deprecated; emit a warning at startup):
|
|
|
665
665
|
- `LLM_GATEWAY_DEDUP_WINDOW_MS` — overrides `dedupWindowMs`.
|
|
666
666
|
- `LLM_GATEWAY_ACKNOWLEDGE_EPHEMERAL` — `1`/`true`/`yes` sets `acknowledgeEphemeral = true`.
|
|
667
667
|
|
|
668
|
+
##### Host-protection limits (`[http]` and `[limits]`)
|
|
669
|
+
|
|
670
|
+
The gateway bounds HTTP session growth and async/sync job execution so a burst of
|
|
671
|
+
clients or requests cannot drive unbounded memory, process, CPU, or provider-request
|
|
672
|
+
growth. All keys live in the same `~/.llm-cli-gateway/config.toml`; defaults are
|
|
673
|
+
conservative but chosen not to surprise local stdio development.
|
|
674
|
+
|
|
675
|
+
```toml
|
|
676
|
+
[http] # HTTP MCP transport session lifecycle
|
|
677
|
+
max_sessions = 100 # max concurrent live sessions; excess initialize returns HTTP 429
|
|
678
|
+
session_idle_ttl_ms = 1800000 # 30 min: reap a session idle longer than this (no client DELETE needed)
|
|
679
|
+
session_reaper_interval_ms = 60000 # 1 min: how often the idle reaper sweeps
|
|
680
|
+
|
|
681
|
+
[limits] # async + sync job-execution backpressure (per gateway process)
|
|
682
|
+
max_running_jobs = 32 # global concurrent running jobs (process CLI + HTTP API)
|
|
683
|
+
max_running_jobs_per_provider = 16 # per-provider concurrent running jobs
|
|
684
|
+
max_queued_jobs = 128 # bounded wait queue; a full queue rejects new work
|
|
685
|
+
queue_timeout_ms = 120000 # 2 min: max time a job waits in the queue before failing
|
|
686
|
+
completed_job_memory_ttl_ms = 3600000 # 1 h: in-memory retention for finished jobs (durable rows kept separately)
|
|
687
|
+
max_job_output_bytes = 52428800 # 50 MB: per-job stdout+stderr cap
|
|
688
|
+
```
|
|
689
|
+
|
|
690
|
+
Failure modes (all deterministic and safe to retry):
|
|
691
|
+
|
|
692
|
+
- **HTTP session cap reached**: the initialize request returns `429` with `Retry-After: 5` and a structured `{ error, code: "session_capacity", retryable: true }` body. No new session is created.
|
|
693
|
+
- **Idle HTTP session**: the reaper closes it (transport + gateway server) once idle past `session_idle_ttl_ms`, independent of the client sending `DELETE`. A session with an in-flight request is never reaped mid-request.
|
|
694
|
+
- **Job limiter saturated**: when the running limit is reached and the queue is full, `*_request` / `*_request_async` and the direct-sync fallback return a retryable `saturated` error (`structuredContent.errorCategory = "saturated"`, `retryable: true`). Nothing is spawned. When the queue has room the job waits (FIFO, per-provider fair) up to `queue_timeout_ms`, then fails with the same category.
|
|
695
|
+
- **Sync direct execution**: the `SYNC_DEADLINE_MS=0` and storeless/`backend="none"` paths acquire the same process permit before spawning, so no execution bypasses the limiter.
|
|
696
|
+
- **Output overflow**: a job whose combined stdout+stderr exceeds `max_job_output_bytes` is failed (exit code 126), its process terminated, its completion persisted, and its run slot released.
|
|
697
|
+
- **In-memory vs durable retention**: `completed_job_memory_ttl_ms` only ages finished jobs out of the in-memory map; the durable job store keeps its own (longer) `[persistence].retentionDays` retention, so results stay readable via `llm_job_result` / `llm_request_result` after in-memory eviction.
|
|
698
|
+
|
|
699
|
+
Live counters are exposed on `GET /healthz` (unauthenticated, HTTP transport) and via the `llm_process_health` tool `backpressure` block: session current/max/oldest-age/idle-TTL/saturation, running and queued job counts globally and per provider, limiter saturation counters, configured TTL/output caps, and parent-process RSS/heap. These surfaces report **counts, ages, and bytes only**, never prompt text, response content, tokens, session IDs, bearer/OAuth tokens, API keys, or machine secrets.
|
|
700
|
+
|
|
701
|
+
For production user services, pair the in-process limits above with systemd's
|
|
702
|
+
outer guardrails so an unexpected bug, provider CLI leak, or evaluation burst
|
|
703
|
+
cannot consume the host:
|
|
704
|
+
|
|
705
|
+
```bash
|
|
706
|
+
systemctl --user edit llm-cli-gateway.service
|
|
707
|
+
```
|
|
708
|
+
|
|
709
|
+
```ini
|
|
710
|
+
[Service]
|
|
711
|
+
MemoryMax=2G
|
|
712
|
+
TasksMax=512
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
Choose values for your workload: `MemoryMax` should cover the gateway process,
|
|
716
|
+
the configured `max_running_jobs` provider children, and normal output buffering;
|
|
717
|
+
`TasksMax` should exceed the process/thread count implied by `max_running_jobs`
|
|
718
|
+
plus the HTTP server and SQLite work, but still be far below host exhaustion. If
|
|
719
|
+
systemd terminates the service at those limits, durable jobs can be inspected
|
|
720
|
+
after restart and `llm_process_health.backpressure` should be used to tune
|
|
721
|
+
`[http]`, `[limits]`, `MemoryMax`, and `TasksMax` together.
|
|
722
|
+
|
|
668
723
|
##### Per-project isolation
|
|
669
724
|
|
|
670
725
|
By default, **all gateway data is global per user**, not per project. With no overrides, every Claude Code window — across every repo — spawns its own gateway subprocess but they all read and write the same files:
|
|
@@ -925,7 +980,7 @@ Async request tools accept the same approval strategy fields as their sync varia
|
|
|
925
980
|
|
|
926
981
|
##### `llm_job_status`
|
|
927
982
|
|
|
928
|
-
Return lifecycle status (`running`, `completed`, `failed`, `canceled`) and metadata for an async job.
|
|
983
|
+
Return lifecycle status (`queued`, `running`, `completed`, `failed`, `canceled`, `orphaned`) and metadata for an async job.
|
|
929
984
|
|
|
930
985
|
##### `llm_job_result`
|
|
931
986
|
|
|
@@ -1046,7 +1101,7 @@ List available models for each CLI.
|
|
|
1046
1101
|
|
|
1047
1102
|
**Parameters:**
|
|
1048
1103
|
|
|
1049
|
-
- `cli` (string, optional): Specific
|
|
1104
|
+
- `cli` (string, optional): Specific provider to list models for (`"claude"`, `"codex"`, `"gemini"`, `"grok"`, `"mistral"`, `"devin"`, or an enabled API provider name). When one or more `[providers.<name>]` API providers are enabled, the unfiltered response also carries an `apiProviders` array (each entry tagged `providerKind: "api"`); see [API providers (HTTP)](#api-providers-http).
|
|
1050
1105
|
|
|
1051
1106
|
**Response includes:**
|
|
1052
1107
|
|
|
@@ -1094,7 +1149,7 @@ inputs.
|
|
|
1094
1149
|
|
|
1095
1150
|
**Parameters:**
|
|
1096
1151
|
|
|
1097
|
-
- `cli` (string, optional): Provider filter (`"claude"`, `"codex"`, `"gemini"`, `"grok"`, `"mistral"`, `"devin"`,
|
|
1152
|
+
- `cli` (string, optional): Provider filter (`"claude"`, `"codex"`, `"gemini"`, `"grok"`, `"mistral"`, `"devin"`, `"grok_api"`, or an enabled API provider name)
|
|
1098
1153
|
- `includeSkills` (boolean, default `true`): Include bounded local skill discovery
|
|
1099
1154
|
- `includeProviderTools` (boolean, default `true`): Include provider-native tools extracted from discovered skills
|
|
1100
1155
|
- `includeUnsupported` (boolean, default `true`): Include explicit unsupported/degraded input records
|
|
@@ -1115,12 +1170,15 @@ Equivalent MCP resources:
|
|
|
1115
1170
|
- `provider-tools://grok_api`
|
|
1116
1171
|
- `provider-tools://mistral`
|
|
1117
1172
|
- `provider-tools://devin`
|
|
1173
|
+
- `provider-tools://<api-provider>` for each enabled `[providers.<name>]` API provider
|
|
1118
1174
|
|
|
1119
1175
|
`doctor --json` also emits a compact `provider_capabilities` block with the
|
|
1120
1176
|
same schema version, per-provider request tool names, supported feature names,
|
|
1121
1177
|
unsupported input names, config-surface counts, discovery counts, and resource
|
|
1122
1178
|
URIs. This block is intended for setup assistants that need a concise capability
|
|
1123
|
-
summary without local skill bodies or raw paths.
|
|
1179
|
+
summary without local skill bodies or raw paths. When API providers are enabled,
|
|
1180
|
+
`doctor --json` additionally emits an `api_providers` health block; see
|
|
1181
|
+
[API providers (HTTP)](#api-providers-http).
|
|
1124
1182
|
|
|
1125
1183
|
##### `cli_versions`
|
|
1126
1184
|
|
|
@@ -1163,6 +1221,73 @@ Plan or run an upgrade for one CLI.
|
|
|
1163
1221
|
}
|
|
1164
1222
|
```
|
|
1165
1223
|
|
|
1224
|
+
## API providers (HTTP)
|
|
1225
|
+
|
|
1226
|
+
In addition to the spawnable CLI tools, the gateway can route requests to first-class **HTTP/API providers** (OpenRouter and other OpenAI-compatible endpoints, the Anthropic Messages API, and the xAI Responses API). These use Node's built-in HTTP client (`node:https`, or `node:http` for loopback endpoints) rather than spawning a CLI, and they run through the same request/job/validation/flight-recorder machinery as the CLI tools, so they reach parity for sessions, async jobs, dedup, retries, usage/cost capture, and cross-LLM validation.
|
|
1227
|
+
|
|
1228
|
+
### Configuring a provider
|
|
1229
|
+
|
|
1230
|
+
API providers are declared as `[providers.<name>]` blocks in `~/.llm-cli-gateway/config.toml` (override with `LLM_GATEWAY_CONFIG`). The `<name>` becomes the provider's identity across every tool and resource and **must not** collide with a spawnable CLI name (`claude`, `codex`, `gemini`, `grok`, `mistral`, `devin`); a collision is rejected with a warning and the provider is disabled.
|
|
1231
|
+
|
|
1232
|
+
```toml
|
|
1233
|
+
# OpenRouter (OpenAI-compatible). The key is read from the named env var at
|
|
1234
|
+
# request time and is never written to config, logs, the flight recorder, or
|
|
1235
|
+
# the dedup key.
|
|
1236
|
+
[providers.openrouter]
|
|
1237
|
+
kind = "openai-compatible" # "openai-compatible" | "anthropic" | "xai-responses"
|
|
1238
|
+
base_url = "https://openrouter.ai/api/v1"
|
|
1239
|
+
api_key_env = "OPENROUTER_API_KEY" # env var NAME, not the key itself
|
|
1240
|
+
default_model = "x-ai/grok-2"
|
|
1241
|
+
models = ["x-ai/grok-2", "anthropic/claude-sonnet-4.6"] # optional allowlist: an explicit model must be listed (omit model to use default_model)
|
|
1242
|
+
usage_include = true # OpenRouter token/cost reporting (usage:{include:true})
|
|
1243
|
+
|
|
1244
|
+
# Keyless-local: an openai-compatible provider on a loopback base_url (Ollama,
|
|
1245
|
+
# llama.cpp) is enabled with no api_key_env at all.
|
|
1246
|
+
[providers.ollama]
|
|
1247
|
+
kind = "openai-compatible"
|
|
1248
|
+
base_url = "http://127.0.0.1:11434/v1"
|
|
1249
|
+
default_model = "qwen2.5"
|
|
1250
|
+
```
|
|
1251
|
+
|
|
1252
|
+
A provider is **enabled** when its `api_key_env` resolves to a non-empty value, OR it is a keyless-local `openai-compatible` provider on a loopback `base_url`. `base_url` must use `https` unless it targets localhost/loopback. A **schema-invalid** single `[providers.<name>]` block disables only itself (with a warning) and leaves the other providers untouched; a TOML **syntax** error anywhere in the file is different, it makes the whole config fall back to defaults.
|
|
1253
|
+
|
|
1254
|
+
The pre-existing `[providers.xai]` block keeps its dedicated `grok_api_request` tool and xAI identity. It is also exposed through the generic surface like any other enabled provider, so a configured xAI key registers **both** `grok_api_request` and the generic `api_xai_request` (and the `xai` entry appears in `apiProviders`, `models://xai`, etc.).
|
|
1255
|
+
|
|
1256
|
+
### Request tools
|
|
1257
|
+
|
|
1258
|
+
For each enabled provider, the gateway registers `api_<name>_request` (and `api_<name>_request_async` when async jobs are enabled). They accept the same shape as the CLI request tools:
|
|
1259
|
+
|
|
1260
|
+
- `prompt` (or the cache-aware `promptParts` `{ system?, tools?, context?, task }`, mutually exclusive), optional `system`
|
|
1261
|
+
- `model` (omit to use `default_model`; an explicit value is rejected if outside a configured `models` allowlist), `maxOutputTokens`, `temperature`, `topP`
|
|
1262
|
+
- `reasoningEffort` (`none|low|medium|high`): forwarded only by the `xai-responses` adapter; accepted but ignored by the other kinds
|
|
1263
|
+
- `timeoutMs`, `optimizePrompt`, `optimizeResponse`, `forceRefresh`, `correlationId`
|
|
1264
|
+
- `sessionId` / `createNewSession` for continuity on the synchronous `api_<name>_request` (see below); on the async variant they are currently inert
|
|
1265
|
+
|
|
1266
|
+
Responses (and the 50 MB output cap, dedup window, cancellation, retention) behave exactly as for the CLI tools, and HTTP requests are logged to the flight recorder with status/usage/cost like everything else.
|
|
1267
|
+
|
|
1268
|
+
### Continuity
|
|
1269
|
+
|
|
1270
|
+
Continuity is capability-typed per provider kind and never stores conversation content in the session record (the gateway's no-transcript-in-sessions invariant holds):
|
|
1271
|
+
|
|
1272
|
+
- **`xai-responses`** uses real server-side continuation: the gateway persists the provider's `previous_response_id` in session metadata and threads it back on resume, self-healing on a stale-handle 404.
|
|
1273
|
+
- **`openai-compatible`** and **`anthropic`** are stateless-resend: the session tracks active/owner state for principal isolation, but the caller resends prior context (no server-side conversation handle exists).
|
|
1274
|
+
|
|
1275
|
+
### Discovery surfaces
|
|
1276
|
+
|
|
1277
|
+
Enabled API providers appear, alongside the CLI providers, across the discovery surfaces. The model, capability, doctor, and resource surfaces below **omit** their API field entirely when no API providers are enabled, so their output is byte-identical to before; `llm_process_health` is the exception (it always carries an `apiProviders` array that is simply empty when none are enabled):
|
|
1278
|
+
|
|
1279
|
+
- **`list_models`** / **`list_available_models`**: an `apiProviders` array tagged `providerKind: "api"` with `defaultModel` and the optional allowlist, omitted entirely when no API providers are enabled.
|
|
1280
|
+
- **`llm_process_health`**: an always-present `outboundProviders.apiProviders` array (empty when none are enabled) carrying the same projection plus each provider's circuit-breaker state.
|
|
1281
|
+
- **`provider_tool_capabilities`**: per-`api`-kind capability metadata. Model + sampling + (for `xai-responses`) reasoning + continuity are supported; allow/deny tool lists, MCP servers, local skills, and workspace/worktree controls are not (those are CLI-only).
|
|
1282
|
+
- **`doctor --json`**: an `api_providers` health block (kind, `base_url`, `default_model`, models, the key env var name, whether the key is present, and login guidance), omitted entirely when none are enabled. The optional flag `doctor --json --probe-api-providers` adds a per-provider endpoint-reachability result (a bare `GET`, treating any HTTP response as reachable). The probe is **opt-in and off by default**: a normal `doctor` run opens no socket and spends no tokens (`reachable` stays `null`).
|
|
1283
|
+
- **MCP resources**: `models://<provider>` for every enabled provider and `sessions://<provider>` for continuity-tracked kinds, plus `provider-tools://<provider>`. The `provider-subcommands://` resources stay CLI-only (API providers have no subcommands).
|
|
1284
|
+
|
|
1285
|
+
The API key value is never emitted on any of these surfaces (only the env var name and a presence boolean). Because `base_url` is config-supplied and may legally carry URL userinfo, the diagnostic surfaces (`doctor`, login guidance) redact any embedded credentials before displaying it; the actual request path and the reachability probe still use the original configured URL.
|
|
1286
|
+
|
|
1287
|
+
### Security note
|
|
1288
|
+
|
|
1289
|
+
The resolved API key is excluded from `payloadJson`, the dedup key, logs, and the flight recorder. However, the **request prompt is persisted in plaintext** in the async job store (the SQLite file at `[persistence].path`, default `~/.llm-cli-gateway/logs.db`) and is not covered by secret redaction. This mirrors the CLI tools, whose prompt is persisted in `argsJson` whenever it is passed as a command argument (a few CLI paths instead stream the prompt over stdin and so do not persist it). Treat the job store as sensitive at rest. See [Security Considerations](#security-considerations).
|
|
1290
|
+
|
|
1166
1291
|
## Session Management
|
|
1167
1292
|
|
|
1168
1293
|
### How It Works
|
|
@@ -1418,6 +1543,8 @@ The gateway supports concurrent requests across different CLIs. Each request spa
|
|
|
1418
1543
|
## Security Considerations
|
|
1419
1544
|
|
|
1420
1545
|
- **Input Validation**: All prompts are validated (min 1 char, max 100k chars)
|
|
1546
|
+
- **API-provider keys**: For `[providers.<name>]` HTTP providers, the gateway reads the key from the named environment variable at request time only. The resolved key is excluded from the persisted `payloadJson`, the dedup key, logs, and the flight recorder, and is never surfaced on the discovery/diagnostic surfaces (which report only the env var name and a presence boolean). `base_url` userinfo is redacted on the diagnostic surfaces. See [API providers (HTTP)](#api-providers-http).
|
|
1547
|
+
- **Prompt persistence at rest**: Async job rows store the request **prompt in plaintext** (HTTP `payloadJson`, and CLI `argsJson` whenever the prompt is passed as a command argument rather than streamed over stdin); this is not covered by secret redaction. The SQLite job-store file (default `~/.llm-cli-gateway/logs.db`, configurable via `[persistence].path`) is `chmod`ed to `0o600` on non-Windows hosts; treat it as sensitive and scope/rotate it like any prompt log. Set `[persistence].backend = "none"` to disable the async job store entirely (the `*_request_async` / `llm_job_*` tools are then not registered).
|
|
1421
1548
|
- **Command Execution**: Uses `spawn` with separate arguments (not shell execution)
|
|
1422
1549
|
- **No Eval**: No dynamic code evaluation in our source (see "Socket alerts" below for the transitive `ajv` codegen case)
|
|
1423
1550
|
- **Sandboxing**: Consider running in containers for production use
|
package/dist/api-provider.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { Logger } from "./logger.js";
|
|
|
3
3
|
import { ApiHttpError } from "./api-http.js";
|
|
4
4
|
export type ApiProviderKind = "openai-compatible" | "anthropic" | "xai-responses";
|
|
5
5
|
export type ApiContinuity = "server-side-id" | "stateless-resend" | "none";
|
|
6
|
+
export declare function apiContinuityForKind(kind: ApiProviderKind): ApiContinuity;
|
|
6
7
|
export interface ApiChatMessage {
|
|
7
8
|
role: "system" | "user" | "assistant";
|
|
8
9
|
content: string;
|
package/dist/api-provider.js
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
import { createCircuitBreaker, withRetry } from "./retry.js";
|
|
2
2
|
import { logWarn, noopLogger } from "./logger.js";
|
|
3
3
|
import { ApiHttpError, buildEndpointUrl, isHttpTransient, postJson, DEFAULT_API_TIMEOUT_MS, } from "./api-http.js";
|
|
4
|
+
export function apiContinuityForKind(kind) {
|
|
5
|
+
switch (kind) {
|
|
6
|
+
case "xai-responses":
|
|
7
|
+
return "server-side-id";
|
|
8
|
+
case "openai-compatible":
|
|
9
|
+
case "anthropic":
|
|
10
|
+
return "stateless-resend";
|
|
11
|
+
default: {
|
|
12
|
+
const exhaustive = kind;
|
|
13
|
+
throw new Error(`Unknown api provider kind: ${String(exhaustive)}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
4
17
|
function numberOrUndefined(value) {
|
|
5
18
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
6
19
|
}
|
|
@@ -4,11 +4,31 @@ import { JobStore } from "./job-store.js";
|
|
|
4
4
|
import { type FlightRecorderLike } from "./flight-recorder.js";
|
|
5
5
|
import type { ValidationRunStore } from "./job-store.js";
|
|
6
6
|
import { type ApiProvider, type ApiRequest, type ApiUsage } from "./api-provider.js";
|
|
7
|
+
import { type JobLimitsConfig } from "./config.js";
|
|
7
8
|
export declare function extractApiHttpStatus(error: unknown): number | null;
|
|
8
9
|
export declare function extractApiErrorBody(error: unknown): string | undefined;
|
|
9
10
|
export type LlmCli = "claude" | "codex" | "gemini" | "grok" | "mistral" | "devin";
|
|
10
11
|
export type JobProvider = LlmCli | (string & {});
|
|
11
|
-
export type AsyncJobStatus = "running" | "completed" | "failed" | "canceled" | "orphaned";
|
|
12
|
+
export type AsyncJobStatus = "queued" | "running" | "completed" | "failed" | "canceled" | "orphaned";
|
|
13
|
+
export declare function isAsyncJobInProgress(status: AsyncJobStatus): boolean;
|
|
14
|
+
export declare class JobSaturationError extends Error {
|
|
15
|
+
readonly provider: string;
|
|
16
|
+
readonly detail: string;
|
|
17
|
+
readonly retryable = true;
|
|
18
|
+
constructor(provider: string, detail: string);
|
|
19
|
+
}
|
|
20
|
+
export interface JobLimiterSnapshot {
|
|
21
|
+
maxRunning: number;
|
|
22
|
+
maxRunningPerProvider: number;
|
|
23
|
+
maxQueued: number;
|
|
24
|
+
running: number;
|
|
25
|
+
queued: number;
|
|
26
|
+
runningByProvider: Record<string, number>;
|
|
27
|
+
queuedByProvider: Record<string, number>;
|
|
28
|
+
rejected: number;
|
|
29
|
+
timedOut: number;
|
|
30
|
+
saturated: boolean;
|
|
31
|
+
}
|
|
12
32
|
export interface AsyncJobFlightRecorderEntry {
|
|
13
33
|
model: string;
|
|
14
34
|
prompt: string;
|
|
@@ -76,7 +96,11 @@ export declare class AsyncJobManager {
|
|
|
76
96
|
private processMonitor;
|
|
77
97
|
private store;
|
|
78
98
|
private flightRecorder;
|
|
79
|
-
|
|
99
|
+
private readonly limits;
|
|
100
|
+
private readonly limiter;
|
|
101
|
+
private readonly completedJobMemoryTtlMs;
|
|
102
|
+
private readonly maxJobOutputBytes;
|
|
103
|
+
constructor(logger?: Logger, onJobComplete?: ((cli: JobProvider, durationMs: number, success: boolean) => void) | undefined, store?: JobStore | null, flightRecorder?: FlightRecorderLike, limits?: JobLimitsConfig);
|
|
80
104
|
private buildOrphanFlightResult;
|
|
81
105
|
checkStalledJobs(now?: number): void;
|
|
82
106
|
hasStore(): boolean;
|
|
@@ -98,6 +122,7 @@ export declare class AsyncJobManager {
|
|
|
98
122
|
}): StartJobOutcome;
|
|
99
123
|
private finalizeHttpJob;
|
|
100
124
|
private fireOnComplete;
|
|
125
|
+
private releaseJobPermit;
|
|
101
126
|
private writeFlightComplete;
|
|
102
127
|
private safeExtractUsage;
|
|
103
128
|
private httpUsage;
|
|
@@ -109,6 +134,8 @@ export declare class AsyncJobManager {
|
|
|
109
134
|
getJobOwner(jobId: string): string | null | undefined;
|
|
110
135
|
startJob(cli: LlmCli, args: string[], correlationId: string, cwd?: string, idleTimeoutMs?: number, outputFormat?: string, forceRefresh?: boolean, env?: Record<string, string>, onComplete?: () => void, flightRecorderEntry?: AsyncJobFlightRecorderEntry, extractUsage?: AsyncJobUsageExtractor, writeFlightStart?: boolean, stdin?: string): AsyncJobSnapshot;
|
|
111
136
|
startJobWithDedup(cli: LlmCli, args: string[], correlationId: string, opts?: StartJobOptions): StartJobOutcome;
|
|
137
|
+
private launchProcessJob;
|
|
138
|
+
private failQueuedJob;
|
|
112
139
|
getJobSnapshot(jobId: string): AsyncJobSnapshot | null;
|
|
113
140
|
getJobSnapshots(jobIds: string[]): Record<string, AsyncJobSnapshot | null>;
|
|
114
141
|
getJobResult(jobId: string, maxChars?: number): AsyncJobResult | null;
|
|
@@ -129,6 +156,11 @@ export declare class AsyncJobManager {
|
|
|
129
156
|
zombieJobs: number;
|
|
130
157
|
jobs: JobHealth[];
|
|
131
158
|
};
|
|
159
|
+
acquireProcessSlot(provider: string): Promise<{
|
|
160
|
+
release: () => void;
|
|
161
|
+
}>;
|
|
162
|
+
getLimiterSnapshot(): JobLimiterSnapshot;
|
|
163
|
+
getConfiguredLimits(): JobLimitsConfig;
|
|
132
164
|
getJobOutputFormat(jobId: string): string | undefined;
|
|
133
165
|
getJobCli(jobId: string): JobProvider | undefined;
|
|
134
166
|
private snapshot;
|