Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

feat(providers): add ACLIDE Responses adapter (#1273)

Tashfeencf5067eb3906
diff --git a/client/src/components/keys/shared.tsx b/client/src/components/keys/shared.tsx
index 1827fc3a..0e9aee18 100644
--- a/client/src/components/keys/shared.tsx
+++ b/client/src/components/keys/shared.tsx
@@ -26,6 +26,7 @@ export function GetKeyLink({ url }: { url: string }) {
// form disables the key field and submits a sentinel the backend stores so
// routing treats the platform as configured.
export const PLATFORMS: { value: Platform; label: string; url: string; keyless?: boolean }[] = [
+ { value: 'aclide', label: 'ACLIDE (shared monthly credits)', url: 'https://aclide.com/en/dashboard/api-keys' },
{ value: 'google', label: 'Google AI Studio', url: 'https://aistudio.google.com/apikey' },
{ value: 'groq', label: 'Groq', url: 'https://console.groq.com/keys' },
{ value: 'cerebras', label: 'Cerebras', url: 'https://cloud.cerebras.ai' },
diff --git a/client/src/lib/routing.ts b/client/src/lib/routing.ts
index d67fbb6c..d83eb6ed 100644
--- a/client/src/lib/routing.ts
+++ b/client/src/lib/routing.ts
@@ -403,6 +403,7 @@ export const platformColors: Record<string, string> = {
groq: '#f55036',
cerebras: '#8b5cf6',
sail: '#0ea5e9',
+ aclide: '#6366f1',
electronhub: '#6366f1',
experiential: '#14b8a6',
router9: '#8b5cf6',
diff --git a/docs/aclide.md b/docs/aclide.md
new file mode 100644
index 00000000..69fa46e2
--- /dev/null
+++ b/docs/aclide.md
@@ -0,0 +1,29 @@
+# ACLIDE
+
+Add an ACLIDE key in **Keys**, or import `ACLIDE_API_KEY` from an environment
+file. Keys stay in the local encrypted key store, as with the other providers.
+
+- API base: `https://aclide.com/v1`
+- Key validation: authenticated `GET /models`
+- Inference: `POST /responses` (ACLIDE does **not** expose Chat Completions)
+- The adapter translates text/image input, function tools and tool results,
+ structured output and token usage into the router's Chat Completions format.
+- Streaming callers receive **buffered** role/content/tool/final chunks after
+ the Responses request completes; upstream token-by-token streaming is not
+ exposed by this adapter. Usage is included when requested.
+- HTTP errors retain upstream status and Retry-After. Empty completed responses,
+ nonterminal responses and unexpected model identities fail rather than being
+ reported as successful calls. Client cancellation and a whole-request timeout
+ also cover reading the response body.
+
+Checked 2026-09-19: the Free plan advertises **€20 of shared monthly usage
+credits**, renewed monthly without a payment card. These are ACLIDE's internal
+usage credits, not cash or a separate grant for each model. Availability and
+charges within that allowance depend on the model and account plan.
+
+Model rows are delivered through the signed live catalog, not database seeds.
+The existing Premium-immediate / Free-after-30-days release logic is unchanged.
+Adding a key therefore does not unlock fresh model rows for Free installations.
+
+Sources: [API documentation](https://aclide.com/en/documentation) and
+[pricing](https://aclide.com/en/pricing).
diff --git a/server/src/__tests__/providers/aclide.test.ts b/server/src/__tests__/providers/aclide.test.ts
new file mode 100644
index 00000000..290c910b
--- /dev/null
+++ b/server/src/__tests__/providers/aclide.test.ts
@@ -0,0 +1,138 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { AclideProvider } from '../../providers/aclide.js';
+import { getProvider } from '../../providers/index.js';
+import { AUTH_JSON_PROVIDER_MAP, detectPlatform } from '../../lib/key-parser.js';
+
+const model = 'z-ai/glm-4.7-flashx';
+const messages = [{ role: 'user' as const, content: 'Say OK' }];
+const completed = () => ({
+ id: 'resp_test', model, status: 'completed', created_at: 123,
+ output: [{ type: 'message', content: [{ type: 'output_text', text: 'OK' }] }],
+ usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15,
+ input_tokens_details: { cached_tokens: 2 }, output_tokens_details: { reasoning_tokens: 1 } },
+});
+const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });
+
+describe('ACLIDE Responses adapter', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it('registers the adapter and recognizes imported keys', () => {
+ expect(getProvider('aclide')).toBeInstanceOf(AclideProvider);
+ expect(detectPlatform('ACLIDE_')).toBe('aclide');
+ expect(AUTH_JSON_PROVIDER_MAP.aclide).toBe('aclide');
+ });
+
+ it('uses Responses, preserves zero options and normalizes usage', async () => {
+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json(completed()));
+ const result = await new AclideProvider().chatCompletion('test-key', messages, model,
+ { max_tokens: 512, temperature: 0, top_p: 0, reasoning_effort: 'low' });
+ const [url, init] = fetch.mock.calls[0];
+ expect(url).toBe('https://aclide.com/v1/responses');
+ expect(init?.headers).toMatchObject({ Authorization: 'Bearer test-key' });
+ expect(JSON.parse(String(init?.body))).toEqual({ model, input: messages, store: false, stream: false,
+ max_output_tokens: 512, temperature: 0, top_p: 0, reasoning: { effort: 'low' } });
+ expect(result.choices[0]).toEqual({ index: 0, message: { role: 'assistant', content: 'OK' }, finish_reason: 'stop' });
+ expect(result.usage).toEqual({ prompt_tokens: 10, completion_tokens: 5, total_tokens: 15,
+ prompt_tokens_details: { cached_tokens: 2 }, completion_tokens_details: { reasoning_tokens: 1 } });
+ expect(result._routed_via).toEqual({ platform: 'aclide', model });
+ });
+
+ it('preserves multimodal input, tool history and JSON schema', async () => {
+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ ...completed(), output: [
+ { type: 'function_call', call_id: 'call_2', name: 'weather', arguments: '{}' },
+ ] }));
+ const result = await new AclideProvider().chatCompletion('k', [
+ { role: 'system', content: 'Be helpful' },
+ { role: 'user', content: ['look', { text: 'here' }, { type: 'image_url', image_url: { url: 'https://example.com/test.png', detail: 'low' } }] },
+ { role: 'assistant', content: null, tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'weather', arguments: '{}' } }] },
+ { role: 'tool', tool_call_id: 'call_1', content: 'rain' },
+ ], model, { tools: [{ type: 'function', function: { name: 'weather', parameters: { type: 'object' }, strict: true } }],
+ tool_choice: { type: 'function', function: { name: 'weather' } }, parallel_tool_calls: false,
+ response_format: { type: 'json_schema', json_schema: { name: 'result', schema: { type: 'object' }, strict: true } },
+ });
+ const body = JSON.parse(String(fetch.mock.calls[0][1]?.body));
+ expect(body.input).toEqual([
+ { role: 'system', content: 'Be helpful' },
+ { role: 'user', content: [{ type: 'input_text', text: 'look' }, { type: 'input_text', text: 'here' },
+ { type: 'input_image', image_url: 'https://example.com/test.png', detail: 'low' }] },
+ { type: 'function_call', call_id: 'call_1', name: 'weather', arguments: '{}' },
+ { type: 'function_call_output', call_id: 'call_1', output: 'rain' },
+ ]);
+ expect(body.tools).toEqual([{ type: 'function', name: 'weather', parameters: { type: 'object' }, strict: true }]);
+ expect(body.tool_choice).toEqual({ type: 'function', name: 'weather' });
+ expect(body.parallel_tool_calls).toBe(false);
+ expect(body.text.format).toEqual({ type: 'json_schema', name: 'result', schema: { type: 'object' }, strict: true });
+ expect(result.choices[0].finish_reason).toBe('tool_calls');
+ });
+
+ it.each([
+ { model: 'wrong-model' }, { model: undefined }, { output: [] }, { status: 'queued' },
+ { status: 'failed', error: { message: 'outage' } },
+ { output: [{ type: 'function_call', name: 'missing_call_id' }] },
+ { status: 'incomplete', incomplete_details: { reason: 'unknown' } },
+ ])('rejects invalid/empty/substituted responses: %j', async override => {
+ vi.spyOn(global, 'fetch').mockResolvedValue(json({ ...completed(), ...override }));
+ await expect(new AclideProvider().chatCompletion('k', messages, model)).rejects.toMatchObject({ status: 502 });
+ });
+
+ it.each([['max_output_tokens', 'length'], ['content_filter', 'content_filter']])('maps %s to %s', async (reason, finish) => {
+ vi.spyOn(global, 'fetch').mockResolvedValue(json({ ...completed(), status: 'incomplete', incomplete_details: { reason } }));
+ expect((await new AclideProvider().chatCompletion('k', messages, model)).choices[0].finish_reason).toBe(finish);
+ });
+
+ it('maps refusal text without treating it as empty', async () => {
+ vi.spyOn(global, 'fetch').mockResolvedValue(json({ ...completed(), output: [{ type: 'message', content: [{ type: 'refusal', refusal: 'Cannot help.' }] }] }));
+ expect((await new AclideProvider().chatCompletion('k', messages, model)).choices[0].message.content).toBe('Cannot help.');
+ });
+
+ it('synthesizes indexed tool chunks and opt-in final usage', async () => {
+ vi.spyOn(global, 'fetch').mockImplementation(async () => json({ ...completed(), output: [
+ ...completed().output, { type: 'function_call', call_id: 'call_a', name: 'weather', arguments: '{}' },
+ ] }));
+ const chunks = [];
+ for await (const chunk of new AclideProvider().streamChatCompletion('k', messages, model, { stream_options: { include_usage: true } })) chunks.push(chunk);
+ expect(chunks[0].choices[0].delta).toEqual({ role: 'assistant' });
+ expect(chunks[2].choices[0].delta.tool_calls?.[0]).toMatchObject({ index: 0, id: 'call_a' });
+ expect(chunks.at(-2)?.choices[0].finish_reason).toBe('tool_calls');
+ expect(chunks.at(-1)).toMatchObject({ choices: [], usage: { total_tokens: 15 } });
+ const withoutUsage = [];
+ for await (const chunk of new AclideProvider().streamChatCompletion('k', messages, model)) withoutUsage.push(chunk);
+ expect(withoutUsage.every(chunk => chunk.usage === undefined)).toBe(true);
+ });
+
+ it('preserves rate-limit status/backoff for HTML errors', async () => {
+ vi.spyOn(global, 'fetch').mockResolvedValue(new Response('Unavailable', { status: 429, headers: { 'Retry-After': '25' } }));
+ await expect(new AclideProvider().chatCompletion('k', messages, model)).rejects.toMatchObject({ status: 429, retryAfterMs: 25_000 });
+ });
+
+ it('validates authenticated rosters and keeps temporary failures inconclusive', async () => {
+ vi.spyOn(global, 'fetch').mockResolvedValueOnce(json({ data: [{ id: model }] }))
+ .mockResolvedValueOnce(json({ error: { message: 'Invalid key' } }, 401))
+ .mockResolvedValueOnce(json({}, 503)).mockResolvedValueOnce(json({}));
+ const provider = new AclideProvider();
+ await expect(provider.validateKey('k')).resolves.toBe(true);
+ await expect(provider.validateKey('k')).resolves.toMatchObject({ valid: false, error: expect.stringContaining('Invalid key') });
+ await expect(provider.validateKey('k')).rejects.toMatchObject({ status: 503 });
+ await expect(provider.validateKey('k')).rejects.toMatchObject({ status: 502 });
+ });
+
+ it('cancels body reads on client disconnect or whole-request timeout', async () => {
+ vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => new Response(new ReadableStream({
+ start(controller) {
+ if (init?.signal?.aborted) controller.error(init.signal.reason);
+ else init?.signal?.addEventListener('abort', () => controller.error(init.signal?.reason), { once: true });
+ },
+ })));
+ const controller = new AbortController();
+ const pending = new AclideProvider().chatCompletion('k', messages, model, { signal: controller.signal });
+ controller.abort(new Error('client disconnected'));
+ await expect(pending).rejects.toThrow('client disconnected');
+ await expect(new AclideProvider().chatCompletion('k', messages, model, { timeoutMs: 10 })).rejects.toThrow();
+ });
+
+ it('rejects unsupported content instead of dropping it', async () => {
+ const fetch = vi.spyOn(global, 'fetch');
+ await expect(new AclideProvider().chatCompletion('k', [{ role: 'user', content: [{ type: 'input_audio', input_audio: {} }] }], model)).rejects.toThrow('content block');
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/__tests__/routes/keys.test.ts b/server/src/__tests__/routes/keys.test.ts
index f1f0ff5d..dd5ca20e 100644
--- a/server/src/__tests__/routes/keys.test.ts
+++ b/server/src/__tests__/routes/keys.test.ts
@@ -154,7 +154,7 @@ describe('Keys API', () => {
expect(status).toBe(400);
});
- it.each(['electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare'])('accepts a %s key without seeding gated model rows', async platform => {
+ it.each(['aclide', 'electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare'])('accepts a %s key without seeding gated model rows', async platform => {
const { status, body } = await request(app, 'POST', '/api/keys', {
platform, key: 'not-a-real-test-key-12345', label: 'Gateway test',
});
diff --git a/server/src/__tests__/services/provider-quota.test.ts b/server/src/__tests__/services/provider-quota.test.ts
index 78f9d635..8ddf27de 100644
--- a/server/src/__tests__/services/provider-quota.test.ts
+++ b/server/src/__tests__/services/provider-quota.test.ts
@@ -50,6 +50,7 @@ describe('provider-quota: pool inference', () => {
expect(inferQuotaPoolKey('septor', 'qwen3-coder-free')).toBe('septor::daily-free');
expect(inferQuotaPoolKey('septor', 'minimax-m2.5-free')).toBe('septor::daily-free');
for (const model of ['first-model', 'another-model']) {
+ expect(inferQuotaPoolKey('aclide', model)).toBe('aclide::monthly-credit');
expect(inferQuotaPoolKey('clod', model)).toBe('clod::daily-free');
expect(inferQuotaPoolKey('blaze', model)).toBe('blaze::daily-free');
expect(inferQuotaPoolKey('speechify', model)).toBe('speechify::monthly-characters');
diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.ts
index 795aac91..9449757a 100644
--- a/server/src/lib/key-parser.ts
+++ b/server/src/lib/key-parser.ts
@@ -38,6 +38,7 @@ export interface ParseResult {
}
export const PREFIX_MAP: Record<string, string> = {
+ ACLIDE_: 'aclide',
GOOGLE_: 'google',
GEMINI_: 'google',
GROQ_: 'groq',
@@ -131,6 +132,7 @@ export const AUTH_JSON_PROVIDER_MAP: Record<string, string> = {
google: 'google',
groq: 'groq',
sail: 'sail',
+ aclide: 'aclide',
'sail-research': 'sail',
sailresearch: 'sail',
electronhub: 'electronhub',
diff --git a/server/src/lib/sampling-params.ts b/server/src/lib/sampling-params.ts
index 5fcf7bd9..fed20215 100644
--- a/server/src/lib/sampling-params.ts
+++ b/server/src/lib/sampling-params.ts
@@ -242,6 +242,10 @@ export const GITHUB_MAX_OUTPUT_TOKENS = 400;
// silently no-op'ing the policy; the string-typed accessors below cast at the
// boundary since routes carry platform ids as plain strings.
export const PLATFORM_PARAM_POLICIES: Partial<Record<Platform, PlatformParamPolicy>> = {
+ // ACLIDE uses Responses; these Chat Completions parameters have no mapping.
+ aclide: {
+ drop: ['top_k', 'min_p', 'seed', 'presence_penalty', 'frequency_penalty', 'repetition_penalty', 'logit_bias', 'logprobs', 'top_logprobs'],
+ },
// Sail's stable Responses API accepts temperature/top_p, JSON Schema output,
// tools and reasoning effort. The remaining Chat Completions knobs are not
// supported and are intentionally omitted by the dedicated adapter.
diff --git a/server/src/providers/aclide.ts b/server/src/providers/aclide.ts
new file mode 100644
index 00000000..777450b8
--- /dev/null
+++ b/server/src/providers/aclide.ts
@@ -0,0 +1,180 @@
+import type { ChatCompletionChunk, ChatCompletionResponse, ChatMessage, ChatToolCall, Platform } from '@freellmapi/shared/types.js';
+import { BaseProvider, providerHttpError, type CompletionOptions, type KeyValidationResult } from './base.js';
+import { contentToString } from '../lib/content.js';
+import { providerTimeoutMs } from '../lib/provider-timeout.js';
+import { resolveMaxTokens } from '../lib/sampling-params.js';
+import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';
+
+const BASE_URL = 'https://aclide.com/v1';
+
+interface ResponseItem {
+ type?: string;
+ call_id?: string;
+ name?: string;
+ arguments?: string;
+ content?: { type?: string; text?: string; refusal?: string }[];
+ summary?: { text?: string }[];
+}
+
+interface AclideResponse {
+ id?: string;
+ model?: string;
+ created_at?: number;
+ status?: string;
+ output?: ResponseItem[];
+ error?: { message?: string } | null;
+ incomplete_details?: { reason?: string } | null;
+ usage?: {
+ input_tokens?: number;
+ output_tokens?: number;
+ total_tokens?: number;
+ input_tokens_details?: { cached_tokens?: number };
+ output_tokens_details?: { reasoning_tokens?: number };
+ };
+}
+
+function upstreamError(message: string): Error {
+ return Object.assign(new Error(`ACLIDE ${message}`), { status: 502 });
+}
+
+/** ACLIDE exposes Responses, NOT Chat Completions. Streaming clients receive
+ * buffered compatibility chunks after a terminal response, as with Sail.
+ * No model rows are seeded here: the signed catalog owns the release gate. */
+export class AclideProvider extends BaseProvider {
+ readonly platform: Platform = 'aclide';
+ readonly name = 'ACLIDE';
+
+ private headers(apiKey: string): Record<string, string> {
+ return { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' };
+ }
+
+ private input(messages: ChatMessage[]): Record<string, unknown>[] {
+ const input: Record<string, unknown>[] = [];
+ for (const message of messages) {
+ if (message.role === 'tool') {
+ if (!message.tool_call_id) throw new Error('ACLIDE tool messages require tool_call_id');
+ input.push({ type: 'function_call_output', call_id: message.tool_call_id, output: contentToString(message.content) });
+ continue;
+ }
+ let content: unknown = message.content ?? '';
+ if (Array.isArray(message.content)) {
+ content = message.content.map(part => {
+ if (typeof part === 'string' || typeof part.text === 'string') {
+ return { type: message.role === 'assistant' ? 'output_text' : 'input_text', text: typeof part === 'string' ? part : part.text };
+ }
+ if (part.type === 'image_url' && message.role === 'user') {
+ const image = part.image_url as { url?: string; detail?: string } | undefined;
+ if (typeof image?.url === 'string') return { type: 'input_image', image_url: image.url, ...(image.detail ? { detail: image.detail } : {}) };
+ }
+ // Never silently erase media the caller relied on.
+ throw new Error(`ACLIDE does not support this content block: ${part.type ?? 'unknown'}`);
+ });
+ }
+ if (contentToString(message.content) || !message.tool_calls?.length || Array.isArray(content) && content.length) {
+ input.push({ role: message.role, content });
+ }
+ for (const call of message.tool_calls ?? []) {
+ input.push({ type: 'function_call', call_id: call.id, name: call.function.name, arguments: call.function.arguments });
+ }
+ }
+ return input;
+ }
+
+ private body(messages: ChatMessage[], modelId: string, options?: CompletionOptions): Record<string, unknown> {
+ const maxOutput = resolveMaxTokens(this.platform, options?.max_tokens);
+ const format = options?.response_format;
+ const body: Record<string, unknown> = { model: modelId, input: this.input(messages), store: false, stream: false };
+ if (maxOutput !== undefined) body.max_output_tokens = maxOutput;
+ if (options?.temperature !== undefined) body.temperature = options.temperature;
+ if (options?.top_p !== undefined) body.top_p = options.top_p;
+ if (options?.reasoning_effort) body.reasoning = { effort: options.reasoning_effort };
+ if (options?.tools) body.tools = options.tools.map(tool => ({ type: 'function', ...tool.function }));
+ if (options?.tool_choice) body.tool_choice = typeof options.tool_choice === 'string'
+ ? options.tool_choice : { type: 'function', name: options.tool_choice.function.name };
+ if (options?.parallel_tool_calls !== undefined) body.parallel_tool_calls = options.parallel_tool_calls;
+ if (format) body.text = { format: format.type === 'json_schema'
+ ? { type: 'json_schema', ...format.json_schema } : { type: format.type } };
+ return body;
+ }
+
+ private record(res: Response, endpoint: string, context?: QuotaObservationContext, modelId?: string): void {
+ recordQuotaObservationsFromResponse(res, { ...context, platform: this.platform, modelId, endpoint });
+ }
+
+ async validateKey(apiKey: string, quotaContext?: QuotaObservationContext): Promise<KeyValidationResult> {
+ const res = await this.fetchWithTimeout(`${BASE_URL}/models`, { headers: this.headers(apiKey) },
+ providerTimeoutMs(this.platform, 30_000), { timeoutBounds: 'request' });
+ this.record(res, 'models', quotaContext);
+ if ([401, 403].includes(res.status)) return this.validationResult(res);
+ if (!res.ok) throw providerHttpError(res, 'ACLIDE key validation is temporarily inconclusive');
+ const roster = await res.json() as { data?: unknown };
+ if (!Array.isArray(roster.data)) throw upstreamError('returned an invalid model roster');
+ return true;
+ }
+
+ async chatCompletion(apiKey: string, messages: ChatMessage[], modelId: string,
+ options?: CompletionOptions, quotaContext?: QuotaObservationContext): Promise<ChatCompletionResponse> {
+ const res = await this.fetchWithTimeout(`${BASE_URL}/responses`, {
+ method: 'POST', headers: this.headers(apiKey), body: JSON.stringify(this.body(messages, modelId, options)),
+ }, options?.timeoutMs ?? providerTimeoutMs(this.platform, 120_000), { signal: options?.signal, timeoutBounds: 'request' });
+ this.record(res, 'responses', quotaContext, modelId);
+ // Preserve HTTP status/backoff even for a non-JSON error page.
+ if (!res.ok) {
+ const body = await res.text();
+ let detail: unknown = body;
+ try { detail = JSON.parse(body); } catch { /* Keep non-JSON diagnostics. */ }
+ throw providerHttpError(res, `ACLIDE error (HTTP ${res.status})`, detail);
+ }
+ const response = await res.json() as AclideResponse;
+ if (response.model !== modelId) throw upstreamError('returned a different or missing model identity');
+ if (!['completed', 'incomplete'].includes(response.status ?? '') || response.error) {
+ throw upstreamError(`response failed: ${response.error?.message ?? response.status ?? 'missing status'}`);
+ }
+ if (!Array.isArray(response.output)) throw upstreamError('returned no output items');
+ const parts = response.output.filter(item => item.type === 'message').flatMap(item => item.content ?? []);
+ const text = parts.filter(part => part.type === 'output_text').map(part => part.text ?? '').join('');
+ const refusal = parts.filter(part => part.type === 'refusal').map(part => part.refusal ?? '').join('');
+ const reasoning = response.output.filter(item => item.type === 'reasoning')
+ .flatMap(item => item.summary ?? []).map(part => part.text ?? '').join('');
+ const calls: ChatToolCall[] = response.output.filter(item => item.type === 'function_call').map(item => {
+ if (!item.call_id || !item.name || typeof item.arguments !== 'string') throw upstreamError('returned an invalid function call');
+ return { id: item.call_id, type: 'function', function: { name: item.name, arguments: item.arguments } };
+ });
+ const incomplete = response.status === 'incomplete';
+ if (!incomplete && !text && !refusal && !calls.length) throw upstreamError('returned an empty completion');
+ let finishReason = calls.length ? 'tool_calls' : 'stop';
+ if (incomplete) {
+ const reason = response.incomplete_details?.reason;
+ if (reason !== 'max_output_tokens' && reason !== 'content_filter') throw upstreamError('returned an unknown incomplete status');
+ finishReason = reason === 'max_output_tokens' ? 'length' : 'content_filter';
+ }
+ const usage = response.usage;
+ return {
+ id: response.id ?? this.makeId(), object: 'chat.completion', created: response.created_at ?? Math.floor(Date.now() / 1000), model: modelId,
+ choices: [{ index: 0, message: { role: 'assistant', content: text || refusal,
+ ...(reasoning ? { reasoning_content: reasoning } : {}), ...(calls.length ? { tool_calls: calls } : {}) }, finish_reason: finishReason }],
+ usage: {
+ prompt_tokens: usage?.input_tokens ?? 0, completion_tokens: usage?.output_tokens ?? 0,
+ total_tokens: usage?.total_tokens ?? (usage?.input_tokens ?? 0) + (usage?.output_tokens ?? 0),
+ ...(usage?.input_tokens_details ? { prompt_tokens_details: usage.input_tokens_details } : {}),
+ ...(usage?.output_tokens_details ? { completion_tokens_details: usage.output_tokens_details } : {}),
+ },
+ _routed_via: { platform: this.platform, model: modelId },
+ };
+ }
+
+ async *streamChatCompletion(apiKey: string, messages: ChatMessage[], modelId: string,
+ options?: CompletionOptions, quotaContext?: QuotaObservationContext): AsyncGenerator<ChatCompletionChunk> {
+ const result = await this.chatCompletion(apiKey, messages, modelId, options, quotaContext);
+ const base = { id: result.id, object: 'chat.completion.chunk' as const, created: result.created, model: result.model };
+ const choice = result.choices[0];
+ const { content, tool_calls: calls, reasoning_content: reasoning } = choice.message;
+ // Do not emit a role chunk until model identity and terminal status pass.
+ yield { ...base, choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] };
+ if (reasoning) yield { ...base, choices: [{ index: 0, delta: { reasoning_content: reasoning }, finish_reason: null }] };
+ if (content) yield { ...base, choices: [{ index: 0, delta: { content: contentToString(content) }, finish_reason: null }] };
+ if (calls?.length) yield { ...base, choices: [{ index: 0, delta: { tool_calls: calls.map((call, index) => ({ ...call, index })) }, finish_reason: null }] };
+ yield { ...base, choices: [{ index: 0, delta: {}, finish_reason: choice.finish_reason }] };
+ if (options?.stream_options?.include_usage) yield { ...base, choices: [], usage: result.usage };
+ }
+}
diff --git a/server/src/providers/index.ts b/server/src/providers/index.ts
index 057f51b6..69901970 100644
--- a/server/src/providers/index.ts
+++ b/server/src/providers/index.ts
@@ -9,6 +9,7 @@ import { ModelScopeProvider } from './modelscope.js';
import { PollinationsProvider } from './pollinations.js';
import { ZhipuProvider } from './zhipu.js';
import { SailProvider } from './sail.js';
+import { AclideProvider } from './aclide.js';
import { ElectronHubProvider } from './electronhub.js';
import { ExperientialProvider } from './experiential.js';
import { Router9Provider } from './router9.js';
@@ -54,6 +55,7 @@ register(new OpenAICompatProvider({
// usage beyond that grant is pay-as-you-go. Live-tested 2026-09-01. Model rows
// stay in Oracle so the existing Premium-now / Free-after-30-days gate applies.
register(new SailProvider());
+register(new AclideProvider());
// Free-plan grants are shared wallets, not free credits per model. Eligibility
// and tested model rows belong in Oracle, never in bundled DB migrations.
diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.ts
index f8d128b6..ec109ee4 100644
--- a/server/src/routes/keys.ts
+++ b/server/src/routes/keys.ts
@@ -30,6 +30,7 @@ export const keysRouter = Router();
// was dropped in V4 and re-added in V13 via the router.huggingface.co route.
// SambaNova was dropped in V23 (free tier permanently retired).
const PLATFORMS = [
+ 'aclide',
'google', 'groq', 'cerebras', 'sail', 'electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare', 'bai', 'radeon', 'nvidia', 'mistral',
'openrouter', 'github', 'cohere', 'cloudflare', 'zhipu', 'ollama',
'kilo', 'pollinations', 'llm7', 'huggingface', 'opencode', 'ovh', 'agnes', 'reka', 'siliconflow',
diff --git a/server/src/services/provider-quota.ts b/server/src/services/provider-quota.ts
index dff6a18b..6b125fec 100644
--- a/server/src/services/provider-quota.ts
+++ b/server/src/services/provider-quota.ts
@@ -116,6 +116,7 @@ export function inferPoolForPlatform(platform: Platform, modelId?: string | null
if (platform === 'groq') return 'groq::account';
if (platform === 'cerebras') return 'cerebras::shared';
if (platform === 'sail') return 'sail::monthly-credit';
+ if (platform === 'aclide') return 'aclide::monthly-credit';
if (platform === 'electronhub') return normalizedModelId.endsWith(':free') ? 'electronhub::daily-free' : 'electronhub::weekly-credit';
if (platform === 'experiential') return 'experiential::monthly-credit';
if (platform === 'router9') return 'router9::monthly-credit';
@@ -176,6 +177,7 @@ export function inferPoolForPlatform(platform: Platform, modelId?: string | null
}
function isSharedPool(platform: Platform): boolean {
+ if (platform === 'aclide') return true;
if (['electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare'].includes(platform)) return true;
return ['openrouter', 'google', 'groq', 'cerebras', 'sail', 'bai', 'radeon', 'sambanova', 'nvidia', 'mistral', 'github', 'cohere', 'cloudflare', 'zhipu', 'ollama', 'kilo', 'pollinations', 'llm7', 'huggingface', 'opencode', 'routeway', 'bazaarlink', 'ainative', 'aion', 'requesty', 'navy', 'nara', 'sealion', 'orcarouter', 'unorouter', 'xkiro', 'anyapi', 'modelscope', 'aihorde'].includes(platform);
}
diff --git a/shared/types.ts b/shared/types.ts
index 3305ec4e..6a215430 100644
--- a/shared/types.ts
+++ b/shared/types.ts
@@ -68,6 +68,8 @@ export type Platform =
// monthly when a payment method is attached; usage beyond the grant is
// pay-as-you-go. Background polling is required for its flex-only models.
| 'sail'
+ // Responses-only gateway; a shared monthly free allowance, not per model.
+ | 'aclide'
// Hosted gateways; model rows are delivered by the signed catalog only.
// ElectronHub renews weekly credits; Experiential renews monthly credits.
| 'electronhub'