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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

## [1.6.0] - 2026-11-25

### Changed
- The Gemini API now accepts both `/v1` and `/v1beta`, preserves JSON schemas
for structured responses and function parameters, and keeps multiple
candidates separate in JSON and streaming responses.
- Added setup instructions for the optional Microsoft Copilot SDK 2.0.2 client.

### Security
- Restricted credentialed upstream HTTP calls to fixed Copilot HTTPS endpoints
and bounded inference request sizes and JSON complexity.
- Updated `rustls` and `zip` to patched versions. The Codex catalog helper no
longer prints the proxy API key; rerun Codex setup after rotating the key.

## [1.5.4] - 2026-10-13

### Changed
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ghc-proxy"
version = "1.5.4"
version = "1.6.0"
edition = "2021"
description = "GitHub Copilot API Proxy - Provides OpenAI and Anthropic compatible endpoints via GitHub Copilot (Rust port of ghc-tunnel)"
license = "MIT"
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ file.
query so per-model context windows come from the live Copilot catalog.
- **Anthropic-compatible** `/v1/messages` endpoint (direct passthrough when the
upstream model supports it, otherwise translated through chat completions).
- **Gemini-compatible** `/v1beta/models/{model}:generateContent`,
- **Gemini-compatible** `/v1/models/{model}:generateContent`,
`:streamGenerateContent`, and `:countTokens` endpoints (translated through chat
completions). `generationConfig` parameters with an OpenAI counterpart are
completions; `/v1beta` is also supported). `generationConfig` parameters with an OpenAI counterpart are
carried across — `temperature`, `topP`, `maxOutputTokens`, `stopSequences`,
`candidateCount`, `seed`, the penalties, and `responseMimeType`/`responseSchema`
`candidateCount`, `seed`, the penalties, and `responseMimeType` with `responseJsonSchema` or `responseSchema`
as `response_format`. `topK` and `safetySettings` have no counterpart and are
dropped, which the dashboard states rather than leaving you to assume they
took effect.
Expand Down Expand Up @@ -245,6 +245,10 @@ the read-only dashboard endpoints stay open.

## Example Usage

To use the proxy from a GitHub Copilot SDK v2 application, see the
[Python client setup](docs/api.md#github-copilot-sdk-v2). The Rust server
does not need the SDK installed.

### OpenAI SDK

```python
Expand Down
38 changes: 36 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ the value limit receive HTTP 400; exceeding the byte limit returns HTTP 413.
| `GET /openapi.json` | OpenAPI v3 specification of the LLM endpoints |
| `GET /v1/responses` (Upgrade) | Responses API over WebSocket |

All three Gemini POST actions also accept `/v1/models/{model}:…`. A GET to
`/v1/models/{model}` still returns OpenAI model metadata.

## Responses over WebSocket

Several models advertise `ws:/responses` in `supported_endpoints` alongside
Expand Down Expand Up @@ -304,6 +307,34 @@ resp = client.chat.completions.create(
print(resp.choices[0].message.content)
```

## GitHub Copilot SDK v2

For a Python client, install the [pinned optional dependency](../examples/copilot-sdk/requirements.txt)
in a fresh virtual environment: `python -m pip install microsoft-copilot-sdk==2.0.2`.
This replaces the deprecated `github-copilot-sdk` distribution; do not install
both in the same environment. It is not a dependency of the Rust server.

In your SDK v2 `create_session` call, keep your application's permission handler
and pass these provider settings. Set `model` to an ID from the proxy's
`GET /v1/models` that supports `/chat/completions`:

```python
github = {"capi": {"enabled": False}}
inference = {
"default_provider": "local",
"providers": [{
"name": "local",
"type": "openai",
"wire_api": "completions",
"base_url": "http://127.0.0.1:8314/v1",
"api_key": "not-needed", # Supply your local proxy key if configured.
}],
}
```

This configures the SDK runtime's inference provider, not the runtime
connection itself. See the [upstream BYOK guide](https://github.com/microsoft/copilot-sdk/blob/main/docs/auth/byok.md).

## Anthropic SDK

```python
Expand All @@ -325,15 +356,18 @@ them through chat completions transparently.
## Gemini

```bash
curl "http://127.0.0.1:8314/v1beta/models/gemini-2.5-pro:generateContent" \
curl "http://127.0.0.1:8314/v1/models/gemini-2.5-pro:generateContent" \
-H "Content-Type: application/json" \
-d '{"contents": [{"role": "user", "parts": [{"text": "Hello!"}]}]}'
```

The model is taken from the URL path and translated per your
[mappings](configuration.md#model-mappings). Gemini requests are translated
through chat completions, so any Copilot model works. Streaming uses the
`:streamGenerateContent` action and emits `data:` SSE lines.
`:streamGenerateContent` action and emits `data:` SSE lines. Multiple candidates
retain their indexes in both JSON and SSE. `generationConfig.responseJsonSchema`
with `responseMimeType: application/json` and function declarations'
`parametersJsonSchema` are forwarded as JSON Schemas.

## Authentication

Expand Down
2 changes: 1 addition & 1 deletion docs/headroom-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ it, or install directly from a checkout of this repository:

```bash
python -m pip install "headroom-ai[proxy,code,ml,memory,relevance]>=0.36.2,<0.41"
python -m pip install ./headroom_ghc_plugin-1.5.4-py3-none-any.whl
python -m pip install ./headroom_ghc_plugin-1.6.0-py3-none-any.whl
# Source checkout alternative: python -m pip install ./plugins/headroom-ghc
python -m headroom.cli copilot-auth login
```
Expand Down
2 changes: 2 additions & 0 deletions examples/copilot-sdk/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Optional Python client for the Copilot SDK example in docs/api.md.
microsoft-copilot-sdk==2.0.2
2 changes: 1 addition & 1 deletion plugins/headroom-ghc/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "headroom-ghc-plugin"
version = "1.5.4"
version = "1.6.0"
description = "In-process GitHub Copilot transport compatibility for Headroom"
requires-python = ">=3.10"
license = "MIT"
Expand Down
2 changes: 1 addition & 1 deletion plugins/headroom-ghc/src/headroom_ghc_plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from starlette.requests import Request
from starlette.responses import JSONResponse

PLUGIN_VERSION = "1.5.4"
PLUGIN_VERSION = "1.6.0"
_NANO_AIU_PER_CREDIT = 1_000_000_000
_CAPTURE_LIMIT = 8 * 1024 * 1024
_PROJECT_PREFIX = re.compile(r"^/p/[^/]+(?P<path>/.*)$")
Expand Down
8 changes: 4 additions & 4 deletions scripts/migrate-headroom-ghc-plugin.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ $Repo = Join-Path $UserHome 'ghc-proxy'
$ServicesDir = Join-Path $UserHome '.headroom\services'
$Python = Join-Path $UserHome 'headroom\Scripts\python.exe'
$HeadroomWheel = Join-Path $Repo 'target\headroom-upgrade-0.40.0\headroom_ai-0.40.0-cp310-abi3-win_amd64.whl'
$PluginWheel = Join-Path $Repo 'target\headroom-upgrade-0.40.0\headroom_ghc_plugin-1.5.4-py3-none-any.whl'
$PluginWheel = Join-Path $Repo 'target\headroom-upgrade-0.40.0\headroom_ghc_plugin-1.6.0-py3-none-any.whl'
$Installer = Join-Path $ServicesDir 'install-proxy-services.ps1'
$RollbackScript = Join-Path $Repo 'scripts\rollback-headroom-ghc-plugin.ps1'
$CurrentPublish = Join-Path $ServicesDir 'ProxyServiceHost\bin\Release\net10.0\win-x64\publish'
Expand Down Expand Up @@ -81,7 +81,7 @@ try {
Tee-Object -FilePath $Log -Append
Assert-LastExitCode 'Headroom installation'

Write-MigrationLog 'Installing ghc extension 1.5.4 from the local wheel'
Write-MigrationLog 'Installing ghc extension 1.6.0 from the local wheel'
& $Python -m pip install --force-reinstall --no-deps $PluginWheel 2>&1 |
Tee-Object -FilePath $Log -Append
Assert-LastExitCode 'Plugin installation'
Expand All @@ -90,7 +90,7 @@ try {
& $Python -m pip check 2>&1 | Tee-Object -FilePath $Log -Append
Assert-LastExitCode 'pip check'

& $Python -c "import headroom, importlib.metadata as m; assert headroom.__version__ == '0.40.0'; assert m.version('headroom-ghc-plugin') == '1.5.4'; assert any(e.name == 'ghc' for e in m.entry_points(group='headroom.proxy_extension'))"
& $Python -c "import headroom, importlib.metadata as m; assert headroom.__version__ == '0.40.0'; assert m.version('headroom-ghc-plugin') == '1.6.0'; assert any(e.name == 'ghc' for e in m.entry_points(group='headroom.proxy_extension'))"
Assert-LastExitCode 'Package verification'

Write-MigrationLog 'Re-provisioning the single Headroom Windows service'
Expand All @@ -104,7 +104,7 @@ try {
if (-not $health.ready -or $health.version -ne '0.40.0' -or -not $plugin.ready) {
throw 'Post-migration health validation failed.'
}
if ($plugin.version -ne '1.5.4' -or $plugin.openai_target -match '8314' -or $plugin.anthropic_target -match '8314') {
if ($plugin.version -ne '1.6.0' -or $plugin.openai_target -match '8314' -or $plugin.anthropic_target -match '8314') {
throw 'The in-process plugin version or upstream target is incorrect.'
}
if (-not $usage.token_based_billing -or $models.data.Count -lt 1) {
Expand Down
126 changes: 112 additions & 14 deletions src/gemini.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,9 @@ pub fn gemini_to_openai(req: &Value, model: &str, stream: bool) -> Value {
.and_then(Value::as_str);
if mime == Some("application/json") {
let schema = gc
.get("responseSchema")
.get("responseJsonSchema")
.or_else(|| gc.get("response_json_schema"))
.or_else(|| gc.get("responseSchema"))
.or_else(|| gc.get("response_schema"));
out.insert(
"response_format".into(),
Expand All @@ -243,7 +245,10 @@ pub fn gemini_to_openai(req: &Value, model: &str, stream: bool) -> Value {
"function": {
"name": decl.get("name").cloned().unwrap_or(Value::Null),
"description": decl.get("description").cloned().unwrap_or(Value::Null),
"parameters": decl.get("parameters").cloned().unwrap_or(json!({"type": "object"}))
"parameters": decl.get("parametersJsonSchema")
.or_else(|| decl.get("parameters_json_schema"))
.or_else(|| decl.get("parameters"))
.cloned().unwrap_or_else(|| json!({"type": "object"}))
}
}));
}
Expand All @@ -261,6 +266,7 @@ pub fn map_finish_reason(reason: Option<&str>) -> &'static str {
Some("stop") | Some("tool_calls") => "STOP",
Some("length") => "MAX_TOKENS",
Some("content_filter") => "SAFETY",
Some("OTHER") => "OTHER",
_ => "STOP",
}
}
Expand Down Expand Up @@ -298,10 +304,9 @@ fn usage_to_gemini(usage: &Value) -> Value {
/// Converts an OpenAI chat-completion response into a Gemini
/// `generateContent` response.
pub fn openai_to_gemini(resp: &Value) -> Value {
let mut parts: Vec<Value> = Vec::new();
let mut finish: Option<String> = None;

for choice in arr(resp, "choices") {
let mut candidates = Vec::new();
for (position, choice) in arr(resp, "choices").into_iter().enumerate() {
let mut parts: Vec<Value> = Vec::new();
if let Some(message) = choice.get("message") {
if let Some(text) = message.get("content").and_then(|c| c.as_str()) {
if !text.is_empty() {
Expand All @@ -326,23 +331,60 @@ pub fn openai_to_gemini(resp: &Value) -> Value {
}
}
}
if let Some(fr) = choice.get("finish_reason").and_then(|f| f.as_str()) {
finish = Some(fr.to_string());
}
candidates.push(json!({
"content": {"role": "model", "parts": parts},
"finishReason": map_finish_reason(choice["finish_reason"].as_str()),
"index": choice["index"].as_u64().unwrap_or(position as u64)
}));
}

let usage = resp.get("usage").cloned().unwrap_or(json!({}));
json!({
"candidates": [{
"content": {"role": "model", "parts": parts},
"finishReason": map_finish_reason(finish.as_deref()),
"index": 0
}],
"candidates": candidates,
"usageMetadata": usage_to_gemini(&usage),
"modelVersion": resp.get("model").cloned().unwrap_or(Value::Null)
})
}

/// Upstream can interleave choices or send usage separately after they finish.
#[derive(Default)]
pub(crate) struct StreamCandidates {
finishes: std::collections::BTreeMap<u64, Option<String>>,
}

impl StreamCandidates {
pub(crate) fn observe(&mut self, chunk: &Value, model: &Value) -> Option<Value> {
let mut deltas = Vec::new();
for (position, choice) in chunk["choices"].as_array()?.iter().enumerate() {
let index = choice["index"].as_u64().unwrap_or(position as u64);
let finish = self.finishes.entry(index).or_default();
if let Some(reason) = choice["finish_reason"].as_str() {
*finish = Some(reason.to_owned());
}
if let Some(text) = choice["delta"]["content"]
.as_str()
.filter(|t| !t.is_empty())
{
deltas.push(
json!({"index":index,"content":{"role":"model","parts":[{"text":text}]}}),
);
}
}
(!deltas.is_empty()).then(|| json!({"candidates":deltas,"modelVersion":model}))
}

pub(crate) fn finish(mut self, interrupted: bool, usage: &Value, model: &Value) -> Value {
if self.finishes.is_empty() {
self.finishes.insert(0, None);
}
let candidates: Vec<_> = self.finishes.into_iter().map(|(index, reason)| {
let reason = reason.as_deref().or(interrupted.then_some("OTHER"));
json!({"index":index,"content":{"role":"model","parts":[]},"finishReason":map_finish_reason(reason)})
}).collect();
json!({"candidates":candidates,"usageMetadata":usage_to_gemini(usage),"modelVersion":model})
}
}

/// Builds a single Gemini streaming chunk from a text delta.
pub fn gemini_stream_text_chunk(text: &str, model: &Value) -> Value {
json!({
Expand Down Expand Up @@ -494,6 +536,62 @@ mod tests {
assert_eq!(out["tools"][0]["function"]["name"], "get_weather");
}

#[test]
fn sdk_json_schemas_survive_translation() {
let schema =
json!({"type":"object","properties":{"label":{"type":"string"}},"required":["label"]});
let out = gemini_to_openai(
&json!({
"generationConfig":{"responseMimeType":"application/json","responseJsonSchema":schema},
"tools":[{"functionDeclarations":[{"name":"label","parametersJsonSchema":schema}]}]
}),
"m",
false,
);
assert_eq!(out["response_format"]["json_schema"]["schema"], schema);
assert_eq!(out["tools"][0]["function"]["parameters"], schema);
}

#[test]
fn multiple_choices_remain_independent_in_json_and_streams() {
let out = openai_to_gemini(&json!({"choices":[
{"index":1,"message":{"content":"second"},"finish_reason":"length"},
{"index":0,"message":{"content":"first"},"finish_reason":"stop"}
]}));
let candidates = out["candidates"].as_array().unwrap();
assert_eq!(candidates.len(), 2);
assert_eq!(candidates[0]["index"], 1);
assert_eq!(
candidates[0]["content"]["parts"],
json!([{"text":"second"}])
);
assert_eq!(candidates[0]["finishReason"], "MAX_TOKENS");
assert_eq!(candidates[1]["content"]["parts"], json!([{"text":"first"}]));

let mut stream = StreamCandidates::default();
let model = json!("m");
let event = stream
.observe(
&json!({"choices":[
{"index":1,"delta":{"content":"second"},"finish_reason":"length"},
{"index":0,"delta":{"content":"first"}}
]}),
&model,
)
.unwrap();
assert_eq!(event["candidates"][0]["index"], 1);
assert_eq!(
event["candidates"][1]["content"]["parts"][0]["text"],
"first"
);
assert!(stream.observe(&json!({"choices":[]}), &model).is_none());
let end = stream.finish(true, &json!({"total_tokens":5}), &model);
assert_eq!(end["candidates"][0]["index"], 0);
assert_eq!(end["candidates"][0]["finishReason"], "OTHER");
assert_eq!(end["candidates"][1]["finishReason"], "MAX_TOKENS");
assert_eq!(end["usageMetadata"]["totalTokenCount"], 5);
}

#[test]
fn model_turn_with_function_call() {
let req = json!({
Expand Down
Loading
Loading