Skip to content
Open
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ run the benchmarks with Freehand.
| Amazon Bedrock | `freehand login bedrock` (Claude) or `freehand login bedrock-openai`, with a Bedrock API key and a region |
| Azure OpenAI, Claude in Microsoft Foundry | `freehand login azure` or `freehand login azure-claude`, with an API key, the resource and the deployment |
| Google Vertex AI | `pip install 'freehand-ai[vertex]'` and `gcloud auth application-default login`, then `freehand login vertex` (Gemini) or `freehand login vertex-claude`, with the project |
| Apple Intelligence on PCC (experimental, macOS 27) | `fm serve` in Terminal, then [connect](docs/apple-fm.md) |
| Any OpenAI-compatible Chat Completions API | `freehand --provider openai-chat --api-base <url> --api-key-env <VAR>` |
| A gateway such as LiteLLM, for GPT, Claude and Gemini behind one key | [docs/gateway.md](docs/gateway.md) |

Expand Down
72 changes: 72 additions & 0 deletions docs/apple-fm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Apple Intelligence through `fm serve` (experimental)

macOS 27 ships `fm`, Apple's Foundation Models command-line tool. `fm serve` runs a local OpenAI-compatible Chat
Completions server, so Freehand reaches Apple's model on **Private Cloud Compute (PCC)** through its ordinary
`openai-chat` provider. Freehand needs no extra provider, dependency or sign-in: the Mac's Apple Account is used.

PCC is a mid-size model with a 32,768-token context and a daily quota. It suits interactive use, not benchmarks or
long autonomous runs.

## Use it

1. In **Terminal.app**, start the server and leave it running:

```bash
fm serve # listens on 127.0.0.1:1976
```

PCC answers only when the server was started from Terminal.app. Started from another app (an editor's terminal,
the Freehand desktop app, a launch agent), the server still runs but rejects `pcc` with HTTP 503: "Private Cloud
Compute is not available in this context. Please use the Terminal app." Any client can use a server started
from Terminal, including Freehand running elsewhere.

2. Connect Freehand:
- **Browser or desktop app:** Settings → Models → Add a connection → **Apple Intelligence**. This sets
the model to `pcc` and the context window to 32,768. The option appears only on macOS.
- **Command line:**

```bash
freehand --provider openai-chat --api-base http://127.0.0.1:1976/v1 --model pcc
```

Add `"context_window": 32768` to the session's settings to see context use against the right window.
`curl -s 127.0.0.1:1976/health` shows whether `pcc` is available and whether its quota is near or at the limit.
## What Freehand sends and gets back
- Tools are native: `fm serve` accepts `tools` and returns `tool_calls`, including several in one reply. The model
sees the same system prompt and `bash` tool as with any other Chat Completions service.
- **Reasoning effort:** `low`, `medium` and `high` are forwarded as `reasoning_effort`. `fm` rejects other levels with
HTTP 400, so Freehand sends nothing for them and the server uses its default.
- **Output limit:** `fm serve` ignores `max_tokens`.
- **Usage:** token counts are reported (and cached-token counts). There is no price, so no cost is shown.
- **Images:** `data:` URLs in `image_url` parts work.
- **Context overflow:** `fm` reports it as a server error: HTTP 500 without streaming, or an `error` event after
HTTP 200 when streaming. Either way the message is "The session's transcript exceeded the model's context size."
Freehand ends the turn as *context full* and does not resend the request: each retry would count against the
daily quota. Nothing is trimmed or compacted on the model's behalf, unless you turned compaction on yourself.

## Spike findings (macOS 27.2.1, build 26B131)

| Question | Finding |
| --- | --- |
| Server mode | `fm serve [--host] [--port] [--socket]`: `GET /health`, `GET /v1/models`, `POST /v1/chat/completions` |
| PCC from a subprocess | Only if the `fm` process belongs to Terminal.app; otherwise "not available in this context" |
| Tools | Native `tools` / `tool_calls`; parallel calls returned; tool results as `role: "tool"` messages |
| Streaming | SSE, with `stream_options.include_usage`. A request without `stream` is streamed too |
| `reasoning_effort` | `pcc` only: `low`/`medium`/`high`; other values → 400. `system` rejects the field |
| `max_tokens`, `temperature` | Accepted; `max_tokens` has no effect |
| Context window | `pcc`: 32,446 prompt tokens accepted, ~33,200 rejected → 32,768 |
| Overflow | 500 `server_error`, "The session's transcript exceeded the model's context size." |
| Guardrail | 500 `server_error`, "The model's safety guardrails were triggered." |
| Unknown model | 400 `invalid_request_error`, lists `system, pcc` |
| Quota | `/health` reports `approaching_limit` / `limit_reached`; the error at the limit was not observed |

`fm respond` (one-shot, `--schema`, `--resume`) was not needed: the server covers tools and history directly.

## Limits and risks

- `fm` is a user tool, not a documented API; its flags and output may change between macOS releases.
- A guardrail refusal arrives as HTTP 500 and is retried like other server errors before it is shown.
- The quota-limit response has not been captured yet, so how Freehand reports it is untested.
2 changes: 1 addition & 1 deletion scripts/model-icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
ICON_URL = "https://cdn.jsdelivr.net/npm/{package}@{version}/icons/{slug}.svg"
CATALOG_URL = "https://models.dev/api.json"
# what the pages ask for besides model names: a service's brand (serviceBrand in web/app.js)
SERVICE_WORDS = ["openai", "claude", "moonshot", "ollama", "lmstudio"]
SERVICE_WORDS = ["openai", "claude", "moonshot", "ollama", "lmstudio", "apple"]


def fetch(url: str, timeout: float = 60) -> bytes:
Expand Down
6 changes: 6 additions & 0 deletions src/freehand/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import os
from pathlib import Path
import re
import sys
from typing import Any
import uuid
import urllib.error
Expand Down Expand Up @@ -149,6 +150,11 @@ def overview() -> dict:
"api_base": "http://localhost:11434/v1", "auth": "none"}},
{"id": "lmstudio", "name": "LM Studio (local)", "config": {"provider": providers.CHAT,
"api_base": "http://localhost:1234/v1", "auth": "none"}},
# `fm serve` (macOS 27) on its default port. PCC answers only when that server was started from
# Terminal.app; its 32,768-token window was measured, models.dev does not list it.
*([{"id": "applefm", "name": "Apple Intelligence", "config": {"provider": providers.CHAT,
"api_base": "http://127.0.0.1:1976/v1", "auth": "none", "model": "pcc", "context_window": 32768}}]
if sys.platform == "darwin" else []),
]
return {"active": data["active_connection"], "items": items, "presets": presets}

Expand Down
2 changes: 1 addition & 1 deletion src/freehand/model-icons.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/freehand/runtime/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,8 @@ def _chat_effort(effort: Any, host: str, slug: str) -> dict[str, Any]:
if slug.startswith(("mistral-medium-26", "mistral-medium-3")):
return {"reasoning_effort": "none" if off else eff}
return {}
if slug == "pcc": # Apple's `fm serve`: other levels -> 400
return {"reasoning_effort": eff} if eff in ("low", "medium", "high") else {}
if host.endswith("groq.com") and slug.startswith(("gpt-oss", "qwen3")):
if off:
return {"reasoning_effort": "none"} if slug.startswith("qwen3") else {}
Expand Down
2 changes: 1 addition & 1 deletion src/freehand/web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5261,7 +5261,7 @@ function brandTile(names, initial) {
// people know it by), a mainland endpoint its maker's
// Kimi's coloured mark has a black K lost on a dark page: Moonshot's one-colour mark takes the text's colour
const serviceBrand = (id) => ({ chatgpt: "openai", anthropic: "claude", kimi: "moonshot", "kimi-cn": "moonshot",
vertex: "vertexai" })[id]
vertex: "vertexai", applefm: "apple" })[id]
|| String(id || "").replace(/-cn$/, "");
// a service's tile: its brand, with the service named on it for styles that want it
function serviceTile(id, initial) {
Expand Down
1 change: 1 addition & 0 deletions src/freehand/web/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"Override context_window": "覆盖上下文窗口", "Override max_output_tokens": "覆盖输出 Token 上限",
"Override request_extra": "覆盖请求参数", "Custom compatible service": "自定义兼容服务",
"ChatGPT sign-in": "ChatGPT 登录", "Ollama (local)": "Ollama(本地)", "LM Studio (local)": "LM Studio(本地)",
"Apple Intelligence": "Apple 智能",
"Current connection": "当前连接", "Gateway": "网关",
"Through your gateway": "通过你的网关", "Authentication": "认证方式",
"Endpoint key": "接口密钥", "Available models": "可用模型",
Expand Down
6 changes: 4 additions & 2 deletions src/freehand/web/workbench.js
Original file line number Diff line number Diff line change
Expand Up @@ -1301,8 +1301,9 @@
if (!active(body)) return;
body.classList.add("models-simple");
const ordered = [...data.presets.filter((p) => p.id === "chatgpt"),
...data.presets.filter((p) => !["chatgpt", "custom", "ollama", "lmstudio"].includes(p.id)),
...["ollama", "lmstudio", "custom"].map((id) => data.presets.find((p) => p.id === id)).filter(Boolean)];
...data.presets.filter((p) => !["chatgpt", "custom", "ollama", "lmstudio", "applefm"].includes(p.id)),
...["ollama", "lmstudio", "applefm", "custom"].map((id) => data.presets.find((p) => p.id === id))
.filter(Boolean)];
// the service a connection is to; none for a gateway, which routes each model where its name says, whatever
// the endpoint left beside it
const serviceOf = (p) => p.config.gateway ? null : data.presets.find((x) => x.name === p.name)
Expand Down Expand Up @@ -1709,6 +1710,7 @@
const hint = preset.id === "copilot" ? tr("Your Copilot subscription, official SDK", "Copilot 订阅,官方 SDK")
: preset.id === "chatgpt" ? tr("Your ChatGPT plan, no key", "用 ChatGPT 订阅,无需密钥")
: ["ollama", "lmstudio"].includes(preset.id) ? tr("Runs on this computer", "在本机运行")
: preset.id === "applefm" ? tr("Private Cloud Compute, no key", "私有云计算,无需密钥")
: preset.id === "custom" ? tr("Any compatible endpoint", "任意兼容接口")
: preset.config.auth === "google" ? tr("Google Cloud sign-in, no key", "Google Cloud 登录,无需密钥")
: tr("API key", "API 密钥");
Expand Down
13 changes: 13 additions & 0 deletions tests/test_connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ def test_read_only_migration_and_legacy_settings_are_preserved(client):
assert session.new_config(client.hub.cwd, interactive=True)["model"] == "legacy"


def test_apple_fm_preset_saves_as_a_keyless_pcc_connection(client, monkeypatch):
monkeypatch.setattr(connections.sys, "platform", "linux")
assert "applefm" not in [p["id"] for p in state(client)["presets"]] # `fm` ships only with macOS
monkeypatch.setattr(connections.sys, "platform", "darwin")
preset = next(p for p in state(client)["presets"] if p["id"] == "applefm")
assert preset["config"]["api_base"] == "http://127.0.0.1:1976/v1" and preset["config"]["auth"] == "none"
cid = add(client, preset["name"], preset["config"], default=True)
row = next(p for p in state(client)["items"] if p["id"] == cid)
assert row["credential"]["ready"] and row["credential"]["source"] == "none"
cfg = session.new_config(client.hub.cwd, interactive=True)
assert (cfg["provider"], cfg["model"], cfg["context_window"]) == ("openai-chat", "pcc", 32768)


def test_same_model_in_two_connections_is_not_ambiguous(client):
a = add(client, "A", {"provider": "openai-chat", "api_base": "https://a.example/v1", "model": "shared"},
key="fake-a")
Expand Down
2 changes: 1 addition & 1 deletion tests/test_model_icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def test_the_bundled_icons_are_served_to_the_page_without_the_network(tmp_path,


# what the pages ask for besides model names: a service's brand (serviceBrand in web/app.js)
@pytest.mark.parametrize("word", ["openai", "claude", "moonshot", "ollama", "lmstudio", "vertexai",
@pytest.mark.parametrize("word", ["openai", "claude", "moonshot", "ollama", "lmstudio", "apple", "vertexai",
*sorted({k.removesuffix("-cn") for k in session.SERVICES} - {"kimi", "vertex"})])
def test_every_service_offered_has_a_bundled_brand(word):
slug = modelicons.icon_for(word)
Expand Down
13 changes: 13 additions & 0 deletions tests/test_provider_conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,19 @@ def test_minimax_direct_chat_effort(model, host, effort):
assert "thinking" not in body


@pytest.mark.parametrize("effort", ["low", "medium", "high", "xhigh", "max", "off", "none", None])
def test_apple_pcc_chat_effort(effort):
# `fm serve` takes low/medium/high for pcc and answers anything else with HTTP 400; the on-device
# model takes no effort at all.
body = providers.Chat().body(_dummy_agent("pcc", "http://127.0.0.1:1976/v1", effort=effort))
if effort in ("low", "medium", "high"):
assert body["reasoning_effort"] == effort
else:
assert "reasoning_effort" not in body
assert "reasoning_effort" not in providers.Chat().body(_dummy_agent("system", "http://127.0.0.1:1976/v1",
effort=effort))


def test_minimax_m4_keeps_gateway_routing_and_request_overrides():
chat = providers.Chat()
router = _dummy_agent("minimax/minimax-m4", "https://openrouter.ai/api/v1", effort="xhigh")
Expand Down