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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ Developer documentation (`docs-dev/`, not published):

## Status

Done: Claude Code and Codex clients, a local OpenAI-compatible API that answers with Claude, ChatGPT and Gemini subscriptions through their CLIs, Overview drawn as the live request path with its fallbacks, step-by-step "Check now", mitmproxy service with headroom fallback, headroom service with its options in Settings,
Done: Claude Code and Codex clients, a local OpenAI-compatible API that answers with Claude, ChatGPT and Gemini subscriptions through their CLIs (with function calling for Claude and Codex), Overview drawn as the live request path with its fallbacks, step-by-step "Check now", mitmproxy service with headroom fallback, headroom service with its options in Settings,
statistics with expandable recent requests, approved tool installation/update checks and RTK client connections, settings,
start at login. Illustrated documentation builds into GitHub Pages on release. GitHub CI validates every push; version tags publish deb/rpm releases. Not yet: package installation smoke tests, Cursor client, macOS.
Planned headroom improvements: diagnostics, quotas, detailed savings, CCR inspection and tuning; see [the roadmap](docs-dev/roadmap.md).
Expand Down
13 changes: 13 additions & 0 deletions docs-dev/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ port>/v1`. Codex talks plain HTTP and WebSocket to it, so no certificate is invo
| `subscriptions/cli.ts` | Headless runs of Claude Code (`-p`, stream-json), Codex CLI (`exec --json`) and Gemini CLI (`--output-format json`): argument building, transcript of a chat, output parsing, error kinds (login, limit, missing, timeout), API keys stripped from the environment |
| `subscriptions/logins.ts` | `Subscriptions`: per tool installed/version/login state and models (`codex debug models`), and the app's own logins in `<userData>/subscriptions/<id>` (link + pasted code; Gemini in a pseudo-terminal through Python's `pty`) |
| `subscriptions/server.ts` | `ApiServer`: OpenAI-compatible `/v1/models` and `/v1/chat/completions` (JSON and SSE) on 127.0.0.1 with a bearer key, at most four tool processes at once; `/docs` and `/openapi.json` without the key (live models in the spec only with it); every request must carry a `Host` of 127.0.0.1, localhost or [::1] on our port, against DNS rebinding |
| `subscriptions/bridge.ts` | `ToolBridge`: function calling (`tools`) through an MCP server per tool process at `/mcp/<token>`; holds the model's calls until the caller sends their results, stops idle sessions |
| `subscriptions/openapi.ts` | OpenAPI 3.1 description (current models as `model` examples) and the Swagger UI page, which loads swagger-ui-dist from jsDelivr pinned with SRI hashes |
| `subscriptions/api.ts` | `SubscriptionApi`: settings (`api` in `state.json`), start/stop, key, cached subscription checks for the API tab |
| `status.ts` | `StatusMonitor` (polling, combined health; `refresh(onStep)` reports each component for a manual check) and the status-line functions for each card |
Expand Down Expand Up @@ -150,6 +151,18 @@ Gemini CLI get `HTTPS_PROXY`, `NODE_EXTRA_CA_CERTS` and `NO_PROXY` in their envi
sending credentials to a foreign listener) and, for the HTTPS proxy, the CA file exists; otherwise the request goes
direct. The API never starts or waits for the proxy.

Function calling goes through the tools' MCP support (`bridge.ts`). A request with `tools` starts the CLI with one MCP
server, `client`, served by the API itself at `/mcp/<token>` (streamable HTTP, JSON responses; the random token in
the path is the only credential, as the CLI cannot send the API key). Claude Code gets it through `--mcp-config` with
`--allowedTools mcp__client` (its built-in tools stay off with `--tools ""`); Codex through
`-c mcp_servers={client={url=…,default_tools_approval_mode="approve"}}`, since `codex exec` never asks. A `tools/call`
is held open (server-sent event response, headers sent at once) and returned to the HTTP caller as `tool_calls`, after
150 ms for more calls of the same step. The caller's next request with `role: "tool"` results whose ids belong to a
waiting session answers those MCP calls, and the same process continues; any other request starts a new session from
the written-out conversation. A session idle for 10 minutes, a cancelled request or API shutdown kills the process;
at most 8 sessions wait at once (the oldest idle one goes). The process may run for up to 2 hours. Gemini CLI is not
wired up yet: requests with `tools` for it get 400.

"Your own login" leaves `CLAUDE_CONFIG_DIR`/`CODEX_HOME`/`GEMINI_CLI_HOME` alone; "the app's login" points them at
`<userData>/subscriptions/<id>`. The app never logs the user's own tool login in or out, and writes Gemini's
`security.auth.selectedType` only in its own folder. Installing a missing CLI runs `npm install --global --prefix
Expand Down
17 changes: 15 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ print(reply.choices[0].message.content)
| Endpoint | What |
|---|---|
| `GET /v1/models` | Models of the installed, logged-in subscriptions |
| `POST /v1/chat/completions` | An answer, at once or streamed (`"stream": true`) |
| `POST /v1/chat/completions` | An answer, at once or streamed (`"stream": true`), with function calling for Claude and Codex |
| `GET /docs` | Swagger UI: browse the API and try requests from the browser |
| `GET /openapi.json` | The OpenAPI 3.1 description, for code generators and API clients |

Expand All @@ -105,7 +105,20 @@ integrity-checked), so it needs internet access; `openapi.json` does not.
account; `gemini/auto`, `gemini/pro`, `gemini/flash`, `gemini/flash-lite`. Just `claude`, `codex` or `gemini` uses
the tool's default (for Codex, the first model it lists).

**Limits.** Text only: tool (function) calls, images and audio are refused with an error. `temperature`,
### Function calling

Programs that act through functions (agents, CAD and editor plugins, anything that sends `tools`) work with `claude/…`
and `codex/…` models, the same way as with the OpenAI API: the answer ends with `finish_reason: "tool_calls"`, the
program runs the functions and sends the conversation again with one `role: "tool"` message per call.

Behind it, the tool gets the program's functions as its only MCP server, which the app serves itself, so the model calls
them the way it was trained to. The tool process waits while the program runs a function and carries on with the
result, so each next step takes a second or two instead of a new start. If the program does not send the results
within 10 minutes, the app stops that process; a later request then starts a new one from the whole conversation.
Functions run in the program that sent them, never on this computer by the tool. Gemini models answer requests with
`tools` with an error for now.

**Limits.** Text only: images and audio are refused with an error. `temperature`,
`max_tokens` and similar options are accepted but ignored, because the tools do not take them. Claude Code streams
its answer as it writes; Codex and Gemini CLI send it in one piece at the end. Token counts come from the tools
(Gemini CLI reports none).
Expand Down
8 changes: 6 additions & 2 deletions src/main/subscriptions/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { ApiServer, newKey } from './server'

/** How long a subscription check (versions, logins, Codex's models) stays fresh. */
const INFO_TTL_MS = 60_000
/** Longest agent loop (a request with functions and its follow-ups) one tool process may run. */
const SESSION_TIMEOUT_MS = 2 * 60 * 60_000

/** Checks the API settings from the API tab; returns an error message or null. */
export function validateApiSettings(s: ApiSettings, taken: { port: number; what: string }[]): string | null {
Expand Down Expand Up @@ -44,14 +46,16 @@ export class SubscriptionApi extends EventEmitter {
version: deps.version,
models: async () => (await this.subscriptionInfos()).flatMap((s) =>
s.program && s.loggedIn !== false ? [{ id: s.id, owner: s.id }, ...s.models.map((m) => ({ id: m.id, owner: s.id }))] : []),
answer: async (id, model, messages, onDelta, signal) => {
answer: async (id, model, messages, onDelta, signal, mcpUrl) => {
const program = await this.deps.subscriptions.program(id)
if (!program) throw new Error(`${id} is not installed`)
const source = this.deps.prefs().sources[id]
return ask(id, {
program, model: model || (await this.defaultModel(id)), messages, onDelta, signal,
env: await this.deps.subscriptions.environment(id, source),
proxy: (await this.deps.route?.(id)) ?? null
proxy: (await this.deps.route?.(id)) ?? null,
// With the caller's functions the process lives for the whole agent loop; the bridge stops it when idle.
...(mcpUrl ? { mcpUrl, timeoutMs: SESSION_TIMEOUT_MS } : {})
})
}
})
Expand Down
136 changes: 136 additions & 0 deletions src/main/subscriptions/bridge.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { afterEach, describe, expect, it } from 'vitest'
import { ToolBridge } from './bridge'
import type { Answer } from './cli'
import { ApiServer, type AnswerFn } from './server'

const KEY = 'adp-test-key'
let server: ApiServer | null = null

afterEach(async () => {
await server?.stop()
server = null
})

/** A tool's MCP client: one JSON-RPC request to the bridge, its result (read from JSON or a server-sent event). */
async function rpc(url: string, method: string, params: object = {}): Promise<Record<string, unknown>> {
const res = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params })
})
const text = await res.text()
const json = text.startsWith('event:') ? text.split('\n').find((l) => l.startsWith('data: '))!.slice(6) : text
return (JSON.parse(json) as { result: Record<string, unknown> }).result
}

const done = (text: string): Answer => ({ text, usage: { inputTokens: 3, outputTokens: 2 }, finish: 'stop' })

async function start(answer: AnswerFn): Promise<string> {
server = new ApiServer({ key: () => KEY, answer, models: async () => [] })
await server.start(0)
return `http://127.0.0.1:${server.port}/v1/chat/completions`
}

const post = (url: string, body: object): Promise<Response> =>
fetch(url, { method: 'POST', headers: { authorization: `Bearer ${KEY}`, 'content-type': 'application/json' }, body: JSON.stringify(body) })

const weather = { type: 'function', function: { name: 'get_weather', description: 'Weather in a city', parameters: { type: 'object', properties: { city: { type: 'string' } } } } }
const ask = { role: 'user', content: 'Weather in Kyiv?' }

/** A tool that lists the functions, calls get_weather and answers with its result. */
const agent: AnswerFn = async (_id, _model, _messages, _onDelta, _signal, mcpUrl) => {
if (!mcpUrl) return done('no functions')
await rpc(mcpUrl, 'initialize', { protocolVersion: '2025-06-18' })
const { tools } = await rpc(mcpUrl, 'tools/list') as { tools: { name: string; inputSchema: object }[] }
const result = await rpc(mcpUrl, 'tools/call', { name: tools[0].name, arguments: { city: 'Kyiv' } }) as { content: { text: string }[] }
return done(`Weather: ${result.content[0].text}`)
}

describe('function calling through the bridge', () => {
it('returns the model\'s call to the caller and carries on with its result', async () => {
const url = await start(agent)
const first = await (await post(url, { model: 'codex', tools: [weather], messages: [ask] })).json() as {
choices: { message: { content: string | null; tool_calls: { id: string; type: string; function: { name: string; arguments: string } }[] }; finish_reason: string }[]
}
expect(first.choices[0].finish_reason).toBe('tool_calls')
const call = first.choices[0].message.tool_calls[0]
expect(call).toMatchObject({ type: 'function', function: { name: 'get_weather', arguments: '{"city":"Kyiv"}' } })
expect(server!.bridge.size).toBe(1)

const second = await (await post(url, {
model: 'codex', tools: [weather],
messages: [ask, { role: 'assistant', content: null, tool_calls: [call] }, { role: 'tool', tool_call_id: call.id, content: 'sunny' }]
})).json() as { choices: { message: { content: string }; finish_reason: string }[] }
expect(second.choices[0]).toMatchObject({ message: { content: 'Weather: sunny' }, finish_reason: 'stop' })
expect(server!.bridge.size).toBe(0)
})

it('streams the call as a tool_calls chunk', async () => {
const url = await start(agent)
const text = await (await post(url, { model: 'claude', stream: true, tools: [weather], messages: [ask] })).text()
const chunks = text.split('\n\n').filter((e) => e.startsWith('data: {')).map((e) => JSON.parse(e.slice(6)) as { choices: { delta: { tool_calls?: { function: { name: string } }[] }; finish_reason: string | null }[] })
expect(chunks.some((c) => c.choices[0].delta.tool_calls?.[0].function.name === 'get_weather')).toBe(true)
expect(chunks.at(-1)!.choices[0].finish_reason).toBe('tool_calls')
expect(text.trim().endsWith('data: [DONE]')).toBe(true)
})

it('starts over from the written-out conversation when no session waits for the results', async () => {
const seen: string[] = []
const url = await start(async (_id, _model, messages) => {
seen.push(...messages.map((m) => m.role))
return done('ok')
})
const res = await post(url, {
model: 'claude', tools: [weather],
messages: [ask, { role: 'assistant', content: null, tool_calls: [{ id: 'call_old', type: 'function', function: { name: 'get_weather', arguments: '{}' } }] },
{ role: 'tool', tool_call_id: 'call_old', content: 'rain' }]
})
expect(res.status).toBe(200)
expect(seen).toEqual(['user', 'assistant', 'tool'])
})

it('refuses functions for Gemini and malformed tools', async () => {
const url = await start(agent)
expect((await post(url, { model: 'gemini', tools: [weather], messages: [ask] })).status).toBe(400)
expect((await post(url, { model: 'claude', tools: [{ type: 'function', function: { name: 'bad name' } }], messages: [ask] })).status).toBe(400)
// tool_choice "none" offers no functions: a plain answer.
const plain = await (await post(url, { model: 'gemini', tools: [weather], tool_choice: 'none', messages: [ask] })).json() as { choices: { message: { content: string } }[] }
expect(plain.choices[0].message.content).toBe('no functions')
})

it('refuses MCP requests for sessions that do not exist', async () => {
await start(agent)
expect((await fetch(`http://127.0.0.1:${server!.port}/mcp/nope`, { method: 'POST', body: '{}' })).status).toBe(404)
})
})

describe('ToolBridge', () => {
it('stops a session whose caller does not bring the results back', async () => {
let signal: AbortSignal | null = null
server = new ApiServer({
key: () => KEY, models: async () => [], bridgeIdleMs: 100,
answer: async (...args) => { signal = args[4]; return agent(...args) }
})
await server.start(0)
const res = await post(`http://127.0.0.1:${server.port}/v1/chat/completions`, { model: 'codex', tools: [weather], messages: [ask] })
expect(((await res.json()) as { choices: { finish_reason: string }[] }).choices[0].finish_reason).toBe('tool_calls')
expect(server.bridge.size).toBe(1)
await new Promise((resolve) => setTimeout(resolve, 300))
expect(server.bridge.size).toBe(0)
expect(signal!.aborted).toBe(true)
})

it('stops every session on stopAll', async () => {
const bridge = new ToolBridge(() => '')
let signal: AbortSignal | null = null
const step = bridge.start([{ name: 'f', description: '', parameters: { type: 'object' } }], (_url, _delta, s) => {
signal = s
return new Promise<Answer>(() => {})
}, () => {}, new AbortController().signal)
expect(bridge.size).toBe(1)
bridge.stopAll()
expect(signal!.aborted).toBe(true)
expect(bridge.size).toBe(0)
await expect(step).rejects.toThrow('stopped')
})
})
Loading
Loading