Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(web-studio): add DSH and per-protocol setup to gateway connect guide (#5705)

t0saki3ee75ed8b921
diff --git a/docs/en/guides/15-context-gateway.md b/docs/en/guides/15-context-gateway.md
index 2af85d88d..f86911d2b 100644
--- a/docs/en/guides/15-context-gateway.md
+++ b/docs/en/guides/15-context-gateway.md
@@ -465,7 +465,7 @@ Add a provider to pi's model configuration, `~/.pi/agent/models.json`:
"providers": {
"openviking": {
"baseUrl": "https://ov.example.com/v1",
- "apiKey": "OPENVIKING_GATEWAY_KEY",
+ "apiKey": "$OPENVIKING_GATEWAY_KEY",
"api": "openai-completions",
"models": [
{
@@ -477,7 +477,7 @@ Add a provider to pi's model configuration, `~/.pi/agent/models.json`:
}
```
-`apiKey` names the environment variable that holds your gateway key; export it before starting pi. The upstream must speak Chat Completions. Unless pi sends one of the headers listed in [How conversations are recognized](#how-conversations-are-recognized), the gateway matches its conversations from their history. If pi's own OpenViking extension is active, the gateway steps aside for those conversations; use one or the other.
+`apiKey` reads your gateway key from the `OPENVIKING_GATEWAY_KEY` environment variable; export it before starting pi. Keep the leading `$`: pi sends a bare string as the key itself. The upstream must speak Chat Completions. Unless pi sends one of the headers listed in [How conversations are recognized](#how-conversations-are-recognized), the gateway matches its conversations from their history. If pi's own OpenViking extension is active, the gateway steps aside for those conversations; use one or the other.
### Volcano Engine Ark and BytePlus ModelArk SDKs
diff --git a/docs/zh/guides/15-context-gateway.md b/docs/zh/guides/15-context-gateway.md
index b65bd22c7..ad5a3d02c 100644
--- a/docs/zh/guides/15-context-gateway.md
+++ b/docs/zh/guides/15-context-gateway.md
@@ -465,7 +465,7 @@ print(reply.choices[0].message.content)
"providers": {
"openviking": {
"baseUrl": "https://ov.example.com/v1",
- "apiKey": "OPENVIKING_GATEWAY_KEY",
+ "apiKey": "$OPENVIKING_GATEWAY_KEY",
"api": "openai-completions",
"models": [
{
@@ -477,7 +477,7 @@ print(reply.choices[0].message.content)
}
```
-`apiKey` 填的是保存网关密钥的环境变量名,启动 pi 前先导出它。上游必须使用 Chat Completions。除非 pi 发送了[网关如何识别对话](#网关如何识别对话)中列出的某个请求头,否则网关会根据历史匹配它的对话。如果 pi 自己的 OpenViking 扩展处于启用状态,网关会让出这些对话,两者选一个使用即可。
+`apiKey` 从环境变量 `OPENVIKING_GATEWAY_KEY` 读取网关密钥,启动 pi 前先导出它。开头的 `$` 不能省,pi 会把不带 `$` 的字符串直接当作密钥发送。上游必须使用 Chat Completions。除非 pi 发送了[网关如何识别对话](#网关如何识别对话)中列出的某个请求头,否则网关会根据历史匹配它的对话。如果 pi 自己的 OpenViking 扩展处于启用状态,网关会让出这些对话,两者选一个使用即可。
### 火山方舟与 BytePlus 方舟 SDK
diff --git a/web-studio/src/i18n/locales/en/context-gateway/connect.ts b/web-studio/src/i18n/locales/en/context-gateway/connect.ts
index dc78bcf03..235c59cf9 100644
--- a/web-studio/src/i18n/locales/en/context-gateway/connect.ts
+++ b/web-studio/src/i18n/locales/en/context-gateway/connect.ts
@@ -34,8 +34,11 @@ const connect = {
title: 'Add an upstream for {{protocols}} first',
description:
'None of the enabled upstreams speaks {{protocols}}. The gateway only forwards a request to an upstream that speaks the same protocol.',
+ descriptionPicked:
+ 'None of the enabled upstreams speaks {{protocols}}. The gateway only forwards a request to an upstream that speaks the same protocol. Add one, or set the client up with another protocol.',
action: 'Add upstream',
hint: 'No enabled upstream for this client yet',
+ protocolHint: 'No enabled upstream speaks this protocol yet',
},
placeholders: 'Replace the placeholders',
goodToKnow: 'Good to know',
@@ -142,7 +145,7 @@ const connect = {
opencode: {
name: 'OpenCode',
intro:
- 'Open-source coding agent for the terminal. Add the gateway as an OpenAI-compatible provider.',
+ 'Open-source coding agent for the terminal. Add the gateway as a custom provider, using the protocol your upstream speaks.',
steps: {
config:
'Add the provider to `~/.config/opencode/opencode.json`, merged with any settings already there.',
@@ -158,10 +161,11 @@ const connect = {
},
pi: {
name: 'pi',
- intro: 'Command-line coding agent. Add the gateway as a custom provider.',
+ intro:
+ 'Command-line coding agent. Add the gateway as a custom provider, using the protocol your upstream speaks.',
steps: {
config:
- "Add the provider to pi's model configuration, `~/.pi/agent/models.json`. `apiKey` is the name of the environment variable that holds the gateway key.",
+ "Add the provider to pi's model configuration, `~/.pi/agent/models.json`. `apiKey` reads the gateway key from an environment variable; keep the leading `$`, or pi sends the name itself as the key.",
key: 'Export that variable before you start pi.',
},
identity:
@@ -171,6 +175,28 @@ const connect = {
"If pi's own OpenViking extension is active, the gateway steps aside for those conversations. Use one or the other.",
},
},
+ dsh: {
+ name: 'DSH',
+ intro:
+ 'DeepSeek Harness, an open-source agent harness. Add the gateway as a custom model provider, using the protocol your upstream speaks.',
+ steps: {
+ config:
+ 'Add the provider to the profile configuration. `web` is the profile `dsh web` uses. If the file already has an `llm-pi-ai` entry, add `openviking` under its `providers` instead of a second entry.',
+ key: 'Put the gateway key in the environment DSH runs in. `apiKeyEnv` names this variable.',
+ start:
+ 'Start `dsh web` and pick `<model>` from the `openviking` provider in the model picker.',
+ },
+ identity:
+ 'Unless DSH sends one of the headers listed under “{{section}}”, the gateway matches its conversations by their history.',
+ notes: {
+ webUi:
+ 'You can also declare it in the Web UI under Settings → Models → Add model provider → Custom model API, which writes the same file.',
+ oneProtocol:
+ 'A DSH provider speaks one protocol. To use the gateway over several, declare one provider per protocol.',
+ plugin:
+ 'If the OpenViking plugin for DSH is installed in the same profile, the gateway steps aside for those conversations.',
+ },
+ },
ark: {
name: 'Volcano Engine Ark and BytePlus ModelArk SDKs',
intro:
diff --git a/web-studio/src/i18n/locales/zh-CN/context-gateway/connect.ts b/web-studio/src/i18n/locales/zh-CN/context-gateway/connect.ts
index 14afa099c..90de80d7d 100644
--- a/web-studio/src/i18n/locales/zh-CN/context-gateway/connect.ts
+++ b/web-studio/src/i18n/locales/zh-CN/context-gateway/connect.ts
@@ -33,8 +33,11 @@ const connect = {
title: '请先添加 {{protocols}} 上游',
description:
'已启用的上游都不支持 {{protocols}}。网关只会把请求转发给协议相同的上游。',
+ descriptionPicked:
+ '已启用的上游都不支持 {{protocols}}。网关只会把请求转发给协议相同的上游。请添加一个,或者换一种协议配置客户端。',
action: '添加上游',
hint: '还没有适用于这个客户端的已启用上游',
+ protocolHint: '还没有使用这种协议的已启用上游',
},
placeholders: '替换占位符',
goodToKnow: '注意事项',
@@ -134,7 +137,8 @@ const connect = {
},
opencode: {
name: 'OpenCode',
- intro: '开源的命令行编程 Agent。把网关添加为一个 OpenAI 兼容服务商即可。',
+ intro:
+ '开源的命令行编程 Agent。把网关添加为一个自定义服务商,协议选你的上游使用的那种。',
steps: {
config:
'在 `~/.config/opencode/opencode.json` 中添加这个服务商,与已有的设置合并。',
@@ -149,10 +153,11 @@ const connect = {
},
pi: {
name: 'pi',
- intro: '命令行编程 Agent。把网关添加为一个自定义服务商即可。',
+ intro:
+ '命令行编程 Agent。把网关添加为一个自定义服务商,协议选你的上游使用的那种。',
steps: {
config:
- '在 pi 的模型配置 `~/.pi/agent/models.json` 中添加这个服务商。`apiKey` 填的是保存网关密钥的环境变量名。',
+ '在 pi 的模型配置 `~/.pi/agent/models.json` 中添加这个服务商。`apiKey` 从环境变量读取网关密钥,开头的 `$` 不能省,否则 pi 会把变量名本身当作密钥发出去。',
key: '启动 pi 前先导出这个环境变量。',
},
identity:
@@ -162,6 +167,28 @@ const connect = {
'如果 pi 自己的 OpenViking 扩展处于启用状态,网关会让出这些对话,两者选一个使用即可。',
},
},
+ dsh: {
+ name: 'DSH',
+ intro:
+ 'DeepSeek 推出的开源 Agent 框架 DeepSeek Harness。把网关添加为一个自定义模型服务商,协议选你的上游使用的那种。',
+ steps: {
+ config:
+ '在 profile 配置中添加这个服务商,`dsh web` 使用的 profile 是 `web`。如果文件里已经有 `llm-pi-ai` 条目,就把 `openviking` 加到它的 `providers` 下,不要再写第二个条目。',
+ key: '在运行 DSH 的环境里设置网关密钥。`apiKeyEnv` 填的就是这个环境变量名。',
+ start:
+ '启动 `dsh web`,在模型选择器中选择 `openviking` 服务商下的 `<model>`。',
+ },
+ identity:
+ '除非 DSH 发送了“{{section}}”中列出的某个请求头,否则网关会根据历史匹配它的对话。',
+ notes: {
+ webUi:
+ '也可以在 Web UI 的 Settings → Models → Add model provider → Custom model API 中添加,它写入的是同一个文件。',
+ oneProtocol:
+ 'DSH 的一个服务商只使用一种协议。要通过多种协议使用网关,就为每种协议各声明一个服务商。',
+ plugin:
+ '如果同一个 profile 里装了 OpenViking 的 DSH 插件,网关会让出这些对话。',
+ },
+ },
ark: {
name: '火山方舟与 BytePlus 方舟 SDK',
intro:
diff --git a/web-studio/src/routes/context-gateway/-components/connect-client-guide.tsx b/web-studio/src/routes/context-gateway/-components/connect-client-guide.tsx
index dd75dc38e..eab2b984d 100644
--- a/web-studio/src/routes/context-gateway/-components/connect-client-guide.tsx
+++ b/web-studio/src/routes/context-gateway/-components/connect-client-guide.tsx
@@ -17,14 +17,16 @@ import {
} from '#/components/ui/card'
import { cn } from '#/lib/utils'
-import type { Upstream } from '../-lib/api'
+import type { Protocol, Upstream } from '../-lib/api'
import {
CLIENT_IDS,
- CLIENT_PROTOCOLS,
KEY_PLACEHOLDER,
MODEL_PLACEHOLDER,
SESSION_PLACEHOLDER,
+ activeProtocols,
clientSnippets,
+ defaultProtocol,
+ protocolChoices,
servingUpstreams,
} from '../-lib/client-guides'
import type { ClientId } from '../-lib/client-guides'
@@ -46,6 +48,7 @@ export const CLIENT_STEPS: Record<ClientId, string[]> = {
'open-webui': ['connection', 'headers', 'env'],
opencode: ['config', 'key', 'start'],
pi: ['config', 'key'],
+ dsh: ['config', 'key', 'start'],
ark: ['endpoints', 'python'],
}
@@ -57,6 +60,7 @@ const CLIENT_NOTES: Record<ClientId, string[]> = {
'open-webui': ['sharedMemory', 'tasks'],
opencode: ['plugin'],
pi: ['extension'],
+ dsh: ['webUi', 'oneProtocol', 'plugin'],
ark: ['routing'],
}
@@ -71,6 +75,8 @@ const MAX_LISTED_UPSTREAMS = 3
type ClientGuideProps = {
client: ClientId
+ /** Protocol from the URL; ignored unless the client supports it. */
+ protocol?: Protocol
/** Gateway address the snippets point at. */
baseUrl: string
/** Configured upstreams; leave undefined while loading so no warning shows. */
@@ -78,7 +84,12 @@ type ClientGuideProps = {
}
/** Client picker (deep-linked through `?client=`) and the selected client's setup. */
-export function ClientGuide({ client, baseUrl, upstreams }: ClientGuideProps) {
+export function ClientGuide({
+ client,
+ protocol,
+ baseUrl,
+ upstreams,
+}: ClientGuideProps) {
const { t } = useTranslation('contextGateway')
return (
<Card className="gap-0 py-0">
@@ -129,15 +140,30 @@ export function ClientGuide({ client, baseUrl, upstreams }: ClientGuideProps) {
)
})}
</nav>
- <ClientPanel client={client} baseUrl={baseUrl} upstreams={upstreams} />
+ <ClientPanel
+ client={client}
+ protocol={protocol}
+ baseUrl={baseUrl}
+ upstreams={upstreams}
+ />
</div>
</Card>
)
}
-function ClientPanel({ client, baseUrl, upstreams }: ClientGuideProps) {
+function ClientPanel({
+ client,
+ protocol,
+ baseUrl,
+ upstreams,
+}: ClientGuideProps) {
const { t } = useTranslation('contextGateway')
- const snippets = clientSnippets(client, { baseUrl })
+ // Without a valid pick, start from a protocol an upstream already serves.
+ const picked =
+ protocol && protocolChoices(client).includes(protocol)
+ ? protocol
+ : defaultProtocol(client, upstreams)
+ const snippets = clientSnippets(client, { baseUrl, protocol: picked })
const placeholders = PLACEHOLDERS.filter(([token]) =>
snippets.some((snippet) => snippet.code.includes(token)),
)
@@ -160,7 +186,11 @@ function ClientPanel({ client, baseUrl, upstreams }: ClientGuideProps) {
</p>
</div>
- <ProtocolRequirement client={client} upstreams={upstreams} />
+ <ProtocolRequirement
+ client={client}
+ protocol={picked}
+ upstreams={upstreams}
+ />
{placeholders.length ? (
<div className="grid gap-1.5 rounded-md border bg-muted/20 px-3 py-2.5 text-sm">
@@ -232,21 +262,26 @@ function ClientPanel({ client, baseUrl, upstreams }: ClientGuideProps) {
)
}
-/** The protocol a client calls, with the upstreams serving it or a warning when none does. */
+/**
+ * The protocols a client calls, with a picker when it is set up for one at a
+ * time, and the upstreams serving them or a warning when none does.
+ */
function ProtocolRequirement({
client,
+ protocol,
upstreams,
-}: Pick<ClientGuideProps, 'client' | 'upstreams'>) {
+}: Pick<ClientGuideProps, 'client' | 'upstreams'> & { protocol: Protocol }) {
const { t } = useTranslation('contextGateway')
- const protocols = CLIENT_PROTOCOLS[client]
- const serving = upstreams && servingUpstreams(client, upstreams)
+ const choices = protocolChoices(client)
+ const protocols = activeProtocols(client, protocol)
+ const serving = upstreams && servingUpstreams(client, upstreams, protocol)
const names = serving?.map((upstream) => upstream.name) ?? []
const listed = names
.slice(0, MAX_LISTED_UPSTREAMS)
.join(t('connect.guide.separator'))
const more = names.length - MAX_LISTED_UPSTREAMS
const protocolNames = protocols
- .map((protocol) => protocolLabel(t, protocol))
+ .map((item) => protocolLabel(t, item))
.join(' / ')
return (
@@ -255,9 +290,16 @@ function ProtocolRequirement({
<span className="text-muted-foreground">
{t('connect.guide.protocol')}
</span>
- {protocols.map((protocol) => (
- <ProtocolBadge key={protocol} protocol={protocol} />
- ))}
+ {choices.length ? (
+ <ProtocolPicker
+ client={client}
+ choices={choices}
+ protocol={protocol}
+ upstreams={upstreams}
+ />
+ ) : (
+ protocols.map((item) => <ProtocolBadge key={item} protocol={item} />)
+ )}
{names.length ? (
<span className="min-w-0 text-muted-foreground">
{more > 0
@@ -290,9 +332,12 @@ function ProtocolRequirement({
}
>
<p>
- {t('connect.guide.noUpstream.description', {
- protocols: protocolNames,
- })}
+ {t(
+ choices.length
+ ? 'connect.guide.noUpstream.descriptionPicked'
+ : 'connect.guide.noUpstream.description',
+ { protocols: protocolNames },
+ )}
</p>
</Notice>
) : null}
@@ -300,6 +345,67 @@ function ProtocolRequirement({
)
}
+/** Segmented links between a client's protocols, kept in `?protocol=`. */
+function ProtocolPicker({
+ client,
+ choices,
+ protocol,
+ upstreams,
+}: {
+ client: ClientId
+ choices: Protocol[]
+ protocol: Protocol
+ upstreams?: Upstream[]
+}) {
+ const { t } = useTranslation('contextGateway')
+ return (
+ <div
+ role="group"
+ aria-label={t('connect.guide.protocol')}
+ className="inline-flex flex-wrap rounded-md border p-0.5"
+ >
+ {choices.map((choice) => {
+ const active = choice === protocol
+ const missing =
+ upstreams !== undefined &&
+ servingUpstreams(client, upstreams, choice).length === 0
+ return (
+ <Link
+ key={choice}
+ to="/context-gateway/connect"
+ search={{ client, protocol: choice }}
+ replace
+ resetScroll={false}
+ aria-current={active ? 'true' : undefined}
+ title={
+ missing ? t('connect.guide.noUpstream.protocolHint') : undefined
+ }
+ className={cn(
+ 'flex items-center gap-1.5 rounded px-2.5 py-1 text-xs transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
+ active
+ ? 'bg-muted font-medium text-foreground'
+ : 'text-muted-foreground',
+ )}
+ >
+ {protocolLabel(t, choice)}
+ {missing ? (
+ <>
+ <TriangleAlertIcon
+ aria-hidden
+ className="size-3 text-amber-600 dark:text-amber-400"
+ />
+ <span className="sr-only">
+ {t('connect.guide.noUpstream.protocolHint')}
+ </span>
+ </>
+ ) : null}
+ </Link>
+ )
+ })}
+ </div>
+ )
+}
+
function StepNumber({ number }: { number: number }) {
return (
<span
diff --git a/web-studio/src/routes/context-gateway/-components/connect-page.test.tsx b/web-studio/src/routes/context-gateway/-components/connect-page.test.tsx
index c669ac5cf..9ee46aecf 100644
--- a/web-studio/src/routes/context-gateway/-components/connect-page.test.tsx
+++ b/web-studio/src/routes/context-gateway/-components/connect-page.test.tsx
@@ -276,6 +276,46 @@ describe('ConnectPage', () => {
)
})
+ it('switches the snippet and upstream check with the picked protocol', async () => {
+ const router = renderPage(
+ '/context-gateway/connect?client=pi&protocol=anthropic',
+ )
+ expect(await screen.findByRole('heading', { name: 'pi' })).toBeTruthy()
+ expect(
+ await screen.findByText('Add an upstream for Anthropic Messages first'),
+ ).toBeTruthy()
+ expect(
+ snippetTexts().some((code) => code.includes('"anthropic-messages"')),
+ ).toBe(true)
+
+ const picker = within(
+ screen.getByRole('group', { name: 'Calls the gateway with' }),
+ )
+ fireEvent.click(picker.getByRole('link', { name: 'Responses' }))
+ expect(
+ await screen.findByText('Available upstreams: Team Responses'),
+ ).toBeTruthy()
+ expect(router.state.location.search).toEqual({
+ client: 'pi',
+ protocol: 'responses',
+ })
+ expect(
+ snippetTexts().some((code) => code.includes('"openai-responses"')),
+ ).toBe(true)
+ expect(screen.queryByText(/^Add an upstream for/)).toBeNull()
+ })
+
+ it('starts a per-protocol client on a protocol an upstream serves', async () => {
+ api.listUpstreams.mockResolvedValue([UPSTREAMS[1]])
+ renderPage('/context-gateway/connect?client=dsh')
+ expect(
+ await screen.findByText('Available upstreams: Team Responses'),
+ ).toBeTruthy()
+ expect(
+ snippetTexts().some((code) => code.includes('api: openai-responses')),
+ ).toBe(true)
+ })
+
it('lists the upstreams that need the client’s own provider key', async () => {
renderPage()
expect(
diff --git a/web-studio/src/routes/context-gateway/-components/connect-page.tsx b/web-studio/src/routes/context-gateway/-components/connect-page.tsx
index b177dbcda..d56c5e3fc 100644
--- a/web-studio/src/routes/context-gateway/-components/connect-page.tsx
+++ b/web-studio/src/routes/context-gateway/-components/connect-page.tsx
@@ -47,10 +47,13 @@ const HEADER_SENDERS: Record<string, string> = {
const UPSTREAM_KEY_EXAMPLE = `${UPSTREAM_KEY_HEADER}: <provider-api-key>`
const PLUGIN_HEADER_EXAMPLE = 'X-OpenViking-Plugin: <plugin-name>'
-/** Gateway address and client setup guides (`?client=` picks the client). */
+/**
+ * Gateway address and client setup guides (`?client=` picks the client,
+ * `?protocol=` the protocol for clients set up per protocol).
+ */
export function ConnectPage() {
const { t, i18n } = useTranslation('contextGateway')
- const { client = CLIENT_IDS[0] } = route.useSearch()
+ const { client = CLIENT_IDS[0], protocol } = route.useSearch()
const info = useConnectionInfo()
const upstreams = useUpstreams()
@@ -81,6 +84,7 @@ export function ConnectPage() {
<AddressCard info={info.data} />
<ClientGuide
client={client}
+ protocol={protocol}
baseUrl={info.data.base_url}
upstreams={upstreams.data}
/>
diff --git a/web-studio/src/routes/context-gateway/-components/keys-secret-dialog.tsx b/web-studio/src/routes/context-gateway/-components/keys-secret-dialog.tsx
index 07155f557..8db794ea1 100644
--- a/web-studio/src/routes/context-gateway/-components/keys-secret-dialog.tsx
+++ b/web-studio/src/routes/context-gateway/-components/keys-secret-dialog.tsx
@@ -15,8 +15,8 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '#/components/ui/tabs'
import type { IssuedKey, Upstream } from '../-lib/api'
import {
- CLIENT_PROTOCOLS,
clientSnippets,
+ defaultProtocol,
servingUpstreams,
} from '../-lib/client-guides'
import type { ClientId } from '../-lib/client-guides'
@@ -154,9 +154,15 @@ export function KeysSecretDialog({
))}
</TabsList>
{SECRET_CLIENTS.map((client) => {
- const reachable = servingUpstreams(client, keyUpstreams)
+ const protocol = defaultProtocol(client, keyUpstreams)
+ const reachable = servingUpstreams(
+ client,
+ keyUpstreams,
+ protocol,
+ )
const snippets = clientSnippets(client, {
baseUrl,
+ protocol,
key: issued.key,
model: snippetModel(issued.models, reachable),
})
@@ -172,10 +178,7 @@ export function KeysSecretDialog({
{reachable.length === 0 ? (
<Notice tone="warning">
{t('keys.secret.noProtocol', {
- protocol: protocolLabel(
- t,
- CLIENT_PROTOCOLS[client][0],
- ),
+ protocol: protocolLabel(t, protocol),
client: t(`connect.clients.${client}.name`),
})}
</Notice>
diff --git a/web-studio/src/routes/context-gateway/-lib/client-guides.test.ts b/web-studio/src/routes/context-gateway/-lib/client-guides.test.ts
index e2f3bd7ab..a648cf7a6 100644
--- a/web-studio/src/routes/context-gateway/-lib/client-guides.test.ts
+++ b/web-studio/src/routes/context-gateway/-lib/client-guides.test.ts
@@ -1,9 +1,13 @@
import { describe, expect, it } from 'vitest'
+import type { Upstream } from './api'
import {
CLIENT_IDS,
clientSnippets,
+ defaultProtocol,
gatewayDocsUrl,
+ protocolChoices,
+ servingUpstreams,
shellQuote,
} from './client-guides'
@@ -94,6 +98,65 @@ describe('clientSnippets', () => {
)
})
+ it('reads the pi key from the environment and follows the picked protocol', () => {
+ const config = (protocol?: 'chat' | 'responses' | 'anthropic') =>
+ JSON.parse(
+ clientSnippets('pi', { baseUrl: base, protocol }).find(
+ (item) => item.id === 'config',
+ )!.code,
+ ).providers.openviking
+ expect(config()).toMatchObject({
+ baseUrl: 'https://ov.example.com/v1',
+ apiKey: '$OPENVIKING_GATEWAY_KEY',
+ api: 'openai-completions',
+ })
+ expect(config('responses')).toMatchObject({
+ baseUrl: 'https://ov.example.com/v1',
+ api: 'openai-responses',
+ })
+ expect(config('anthropic')).toMatchObject({
+ baseUrl: 'https://ov.example.com',
+ api: 'anthropic-messages',
+ })
+ })
+
+ it('declares a DSH provider per protocol', () => {
+ const config = (protocol: 'chat' | 'anthropic') =>
+ clientSnippets('dsh', { baseUrl: base, protocol }).find(
+ (item) => item.id === 'config',
+ )!.code
+ expect(config('chat')).toBe(
+ [
+ '- id: llm-pi-ai',
+ ' config:',
+ ' providers:',
+ ' openviking:',
+ ' api: openai-completions',
+ ' baseURL: "https://ov.example.com/v1"',
+ ' apiKeyEnv: OPENVIKING_GATEWAY_KEY',
+ ' models:',
+ ' - id: "<model>"',
+ ].join('\n'),
+ )
+ expect(config('anthropic')).toContain('api: anthropic-messages')
+ expect(config('anthropic')).toContain('baseURL: "https://ov.example.com"\n')
+ })
+
+ it('picks the OpenCode SDK package by protocol, always under /v1', () => {
+ const provider = (protocol: 'chat' | 'responses' | 'anthropic') =>
+ JSON.parse(
+ clientSnippets('opencode', { baseUrl: base, protocol }).find(
+ (item) => item.id === 'config',
+ )!.code,
+ ).provider.openviking
+ expect(provider('chat').npm).toBe('@ai-sdk/openai-compatible')
+ expect(provider('responses').npm).toBe('@ai-sdk/openai')
+ expect(provider('anthropic')).toMatchObject({
+ npm: '@ai-sdk/anthropic',
+ options: { baseURL: 'https://ov.example.com/v1' },
+ })
+ })
+
it('maps Ark-addressed clients to the native paths', () => {
expect(code('ark', 'endpoints')).toContain('https://ov.example.com/api/v3')
expect(code('ark', 'endpoints')).toContain(
@@ -116,3 +179,30 @@ it('links the docs in the UI language', () => {
'https://docs.openviking.ai/zh/guides/22-context-gateway-operations',
)
})
+
+describe('protocols', () => {
+ const upstream = (protocol: Upstream['protocol'], enabled = true): Upstream =>
+ ({ name: protocol, protocol, enabled }) as Upstream
+
+ it('offers a choice only to clients set up per protocol', () => {
+ expect(protocolChoices('pi')).toEqual(['chat', 'anthropic', 'responses'])
+ expect(protocolChoices('ark')).toEqual([])
+ expect(protocolChoices('claude-code')).toEqual([])
+ })
+
+ it('defaults to a protocol an enabled upstream speaks', () => {
+ expect(defaultProtocol('pi')).toBe('chat')
+ expect(
+ defaultProtocol('pi', [upstream('chat', false), upstream('anthropic')]),
+ ).toBe('anthropic')
+ })
+
+ it('narrows serving upstreams to the picked protocol', () => {
+ const upstreams = [upstream('anthropic'), upstream('responses')]
+ expect(servingUpstreams('dsh', upstreams)).toHaveLength(2)
+ expect(servingUpstreams('dsh', upstreams, 'chat')).toHaveLength(0)
+ expect(servingUpstreams('dsh', upstreams, 'anthropic')).toHaveLength(1)
+ // Ark reaches every protocol with one setup, whatever is picked.
+ expect(servingUpstreams('ark', upstreams, 'chat')).toHaveLength(2)
+ })
+})
diff --git a/web-studio/src/routes/context-gateway/-lib/client-guides.ts b/web-studio/src/routes/context-gateway/-lib/client-guides.ts
index 803d66955..f7d9d3518 100644
--- a/web-studio/src/routes/context-gateway/-lib/client-guides.ts
+++ b/web-studio/src/routes/context-gateway/-lib/client-guides.ts
@@ -8,6 +8,7 @@ export type ClientId =
| 'open-webui'
| 'opencode'
| 'pi'
+ | 'dsh'
| 'ark'
export const CLIENT_IDS: ClientId[] = [
@@ -17,32 +18,94 @@ export const CLIENT_IDS: ClientId[] = [
'open-webui',
'opencode',
'pi',
+ 'dsh',
'ark',
]
-/** Protocol each client calls; the gateway needs an enabled upstream for it. */
+/**
+ * Protocols each client can call, preferred first. The gateway needs an
+ * enabled upstream for the one the client is set up with.
+ */
export const CLIENT_PROTOCOLS: Record<ClientId, Protocol[]> = {
'claude-code': ['anthropic'],
codex: ['responses'],
chat: ['chat'],
'open-webui': ['chat'],
- opencode: ['chat'],
- pi: ['chat'],
+ opencode: ['chat', 'anthropic', 'responses'],
+ pi: ['chat', 'anthropic', 'responses'],
+ dsh: ['chat', 'anthropic', 'responses'],
ark: ['chat', 'responses', 'anthropic'],
}
-/** Enabled upstreams that speak a protocol the client calls. */
+/**
+ * Clients configured for one protocol at a time, so their snippets change with
+ * the protocol picked. The other multi-protocol clients reach all of theirs
+ * with one setup.
+ */
+const PICKS_PROTOCOL: ReadonlySet<ClientId> = new Set(['opencode', 'pi', 'dsh'])
+
+/** Protocols the user picks between for a client; empty when there is no choice. */
+export function protocolChoices(client: ClientId): Protocol[] {
+ return PICKS_PROTOCOL.has(client) ? CLIENT_PROTOCOLS[client] : []
+}
+
+/**
+ * Protocols the client's current setup calls: the picked one (or a valid
+ * default) for clients set up per protocol, else all of them.
+ */
+export function activeProtocols(
+ client: ClientId,
+ protocol?: Protocol,
+): Protocol[] {
+ const choices = protocolChoices(client)
+ if (!choices.length) return CLIENT_PROTOCOLS[client]
+ return [protocol && choices.includes(protocol) ? protocol : choices[0]]
+}
+
+/** Enabled upstreams that speak one of `protocols`. */
+function enabledFor(protocols: Protocol[], upstreams: Upstream[]): Upstream[] {
+ return upstreams.filter(
+ (upstream) => upstream.enabled && protocols.includes(upstream.protocol),
+ )
+}
+
+/**
+ * Enabled upstreams the client can reach: through any protocol it supports,
+ * or only through `protocol` when given.
+ */
export function servingUpstreams(
client: ClientId,
upstreams: Upstream[],
+ protocol?: Protocol,
): Upstream[] {
+ return enabledFor(
+ protocol ? activeProtocols(client, protocol) : CLIENT_PROTOCOLS[client],
+ upstreams,
+ )
+}
+
+/**
+ * Protocol to set a client up with when none was picked: the first it supports
+ * that some enabled upstream speaks, else its preferred one.
+ */
+export function defaultProtocol(
+ client: ClientId,
+ upstreams: Upstream[] = [],
+): Protocol {
const protocols = CLIENT_PROTOCOLS[client]
- return upstreams.filter(
- (upstream) => upstream.enabled && protocols.includes(upstream.protocol),
+ return (
+ protocols.find((protocol) => enabledFor([protocol], upstreams).length) ??
+ protocols[0]
)
}
-export type SnippetLanguage = 'bash' | 'toml' | 'json' | 'python' | 'text'
+export type SnippetLanguage =
+ | 'bash'
+ | 'toml'
+ | 'json'
+ | 'yaml'
+ | 'python'
+ | 'text'
/** One copyable block. `id` names its caption under `connect.snippets.*`. */
export type Snippet = {
@@ -56,6 +119,8 @@ export type Snippet = {
/** Values filled into snippets; missing ones become placeholders. */
export type GuideInput = {
baseUrl: string
+ /** Protocol for clients set up per protocol; defaults to the preferred one. */
+ protocol?: Protocol
key?: string
model?: string
}
@@ -77,6 +142,25 @@ function json(value: unknown): string {
return JSON.stringify(value, null, 2)
}
+/** `api` value pi and DSH (which builds on pi's model layer) use per protocol. */
+const PI_APIS: Record<Protocol, string> = {
+ chat: 'openai-completions',
+ responses: 'openai-responses',
+ anthropic: 'anthropic-messages',
+}
+
+/** Base URL for Anthropic SDKs, which append `/v1/messages` themselves. */
+function piBaseUrl(base: string, protocol: Protocol): string {
+ return protocol === 'anthropic' ? base : `${base}/v1`
+}
+
+/** AI SDK package OpenCode loads per protocol; every one takes `/v1`. */
+const OPENCODE_PACKAGES: Record<Protocol, string> = {
+ chat: '@ai-sdk/openai-compatible',
+ responses: '@ai-sdk/openai',
+ anthropic: '@ai-sdk/anthropic',
+}
+
function exportKey(key: string): Snippet {
return {
id: 'key',
@@ -87,7 +171,7 @@ function exportKey(key: string): Snippet {
const builders: Record<
ClientId,
- (base: string, key: string, model: string) => Snippet[]
+ (base: string, key: string, model: string, protocol: Protocol) => Snippet[]
> = {
'claude-code': (base, key) => [
{
@@ -171,7 +255,7 @@ const builders: Record<
},
{ id: 'env', language: 'bash', code: 'RAG_SYSTEM_CONTEXT=true' },
],
- opencode: (base, key, model) => [
+ opencode: (base, key, model, protocol) => [
{
id: 'config',
language: 'json',
@@ -179,7 +263,7 @@ const builders: Record<
code: json({
provider: {
openviking: {
- npm: '@ai-sdk/openai-compatible',
+ npm: OPENCODE_PACKAGES[protocol],
name: 'OpenViking',
options: { baseURL: `${base}/v1`, apiKey: `{env:${KEY_ENV}}` },
models: { [model]: {} },
@@ -189,16 +273,17 @@ const builders: Record<
},
exportKey(key),
],
- pi: (base, key, model) => [
+ pi: (base, key, model, protocol) => [
{
id: 'config',
language: 'json',
+ filename: '~/.pi/agent/models.json',
code: json({
providers: {
openviking: {
- baseUrl: `${base}/v1`,
- apiKey: KEY_ENV,
- api: 'openai-completions',
+ baseUrl: piBaseUrl(base, protocol),
+ apiKey: `$${KEY_ENV}`,
+ api: PI_APIS[protocol],
models: [{ id: model }],
},
},
@@ -206,6 +291,25 @@ const builders: Record<
},
exportKey(key),
],
+ dsh: (base, key, model, protocol) => [
+ {
+ id: 'config',
+ language: 'yaml',
+ filename: '~/.dsh/profiles/web/cordis.patch.yml',
+ code: [
+ '- id: llm-pi-ai',
+ ' config:',
+ ' providers:',
+ ' openviking:',
+ ` api: ${PI_APIS[protocol]}`,
+ ` baseURL: ${JSON.stringify(piBaseUrl(base, protocol))}`,
+ ` apiKeyEnv: ${KEY_ENV}`,
+ ' models:',
+ ` - id: ${JSON.stringify(model)}`,
+ ].join('\n'),
+ },
+ exportKey(key),
+ ],
ark: (base, key) => [
{
id: 'endpoints',
@@ -234,10 +338,12 @@ const builders: Record<
*/
export function clientSnippets(client: ClientId, input: GuideInput): Snippet[] {
const base = input.baseUrl.trim().replace(/\/+$/, '')
+ const [protocol] = activeProtocols(client, input.protocol)
return builders[client](
base,
input.key?.trim() || KEY_PLACEHOLDER,
input.model?.trim() || MODEL_PLACEHOLDER,
+ protocol,
)
}
diff --git a/web-studio/src/routes/context-gateway/-lib/search.test.ts b/web-studio/src/routes/context-gateway/-lib/search.test.ts
index c261b308d..f57f5e26a 100644
--- a/web-studio/src/routes/context-gateway/-lib/search.test.ts
+++ b/web-studio/src/routes/context-gateway/-lib/search.test.ts
@@ -31,15 +31,23 @@ it('reads the profile to duplicate', () => {
})
})
-it('keeps known clients and drops anything else', () => {
+it('keeps known clients and protocols and drops anything else', () => {
expect(parseConnectSearch({ client: 'codex' })).toStrictEqual({
client: 'codex',
- })
- expect(parseConnectSearch({ client: 'cursor' })).toStrictEqual({
+ protocol: undefined,
+ })
+ expect(
+ parseConnectSearch({ client: 'pi', protocol: 'anthropic' }),
+ ).toStrictEqual({ client: 'pi', protocol: 'anthropic' })
+ expect(
+ parseConnectSearch({ client: 'cursor', protocol: 'grpc' }),
+ ).toStrictEqual({ client: undefined, protocol: undefined })
+ expect(parseConnectSearch({ client: 3 })).toStrictEqual({
client: undefined,
+ protocol: undefined,
})
- expect(parseConnectSearch({ client: 3 })).toStrictEqual({
+ expect(parseConnectSearch({})).toStrictEqual({
client: undefined,
+ protocol: undefined,
})
- expect(parseConnectSearch({})).toStrictEqual({ client: undefined })
})
diff --git a/web-studio/src/routes/context-gateway/-lib/search.ts b/web-studio/src/routes/context-gateway/-lib/search.ts
index bd9665ec4..4ce214713 100644
--- a/web-studio/src/routes/context-gateway/-lib/search.ts
+++ b/web-studio/src/routes/context-gateway/-lib/search.ts
@@ -1,5 +1,7 @@
+import type { Protocol } from './api'
import { CLIENT_IDS } from './client-guides'
import type { ClientId } from './client-guides'
+import { PROTOCOLS } from './upstream-schema'
/*
* `validateSearch` parsers for the gateway pages. Each returns its key even
@@ -39,16 +41,22 @@ export function parseProfileEditorSearch(
return { from: typeof from === 'string' && from ? from : undefined }
}
-export type ConnectSearch = { client?: ClientId }
+export type ConnectSearch = { client?: ClientId; protocol?: Protocol }
-/** `/context-gateway/connect?client=codex`. */
+/**
+ * `/context-gateway/connect?client=pi&protocol=anthropic`. The page checks
+ * that the client supports the protocol.
+ */
export function parseConnectSearch(
search: Record<string, unknown>,
): ConnectSearch {
- const { client } = search
+ const { client, protocol } = search
return {
client: CLIENT_IDS.includes(client as ClientId)
? (client as ClientId)
: undefined,
+ protocol: PROTOCOLS.includes(protocol as Protocol)
+ ? (protocol as Protocol)
+ : undefined,
}
}