@mizuka-wu/magpie-plugin-ohmygame 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,165 @@
1
- # Temporary Holding Version
1
+ # magpie-plugin-ohmygame
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [English](#english)
4
+
5
+ 给 magpie 用的 OhMyGame 插件:在 magpie 的 Agents 页面里出现一个 **Oh My Game**,
6
+ 选中 magpie 的某个模型,OhMyGame 就用它;magpie 的 MCP hub 也会成为 OhMyGame
7
+ 自己的一条 MCP 连接。
8
+
9
+ - **模型**:把选中的 magpie 模型写进 OhMyGame 的 Pi 配置,并在
10
+ `model-visibility.json` 里注册 `magpie` provider,让 OhMyGame 的模型列表里
11
+ 真的出现它,而不是一个空 provider。
12
+ - **MCP**:把 magpie 的 MCP hub 写成 OhMyGame 自己的一条连接。OhMyGame 只把
13
+ 「连接」里的 MCP 交给会话,给它哪个 server、给几个,都在 magpie 侧决定。
14
+
15
+ 图标打包在 `assets/ohmygame.svg`,并以 `data:image/svg+xml` 内联,安装副本和市场
16
+ 副本都能显示。
17
+
18
+ ## 安装
19
+
20
+ 在 magpie 的 Plugins 页面按名字添加,或写进 `~/.config/magpie/plugins.json`:
21
+
22
+ ```json
23
+ { "spec": "@mizuka-wu/magpie-plugin-ohmygame@latest" }
24
+ ```
25
+
26
+ 然后到 Agents 页面给 `Oh My Game` 选一个 magpie 的模型。
27
+
28
+ **先打开一次 OhMyGame**:它启动时才会创建数据目录和凭据密钥,在那之前没有可写
29
+ 的连接存储,插件会退回到留一个可粘贴的片段。
30
+
31
+ ## 会写哪些文件
32
+
33
+ | 文件 | 谁来读 | 内容 |
34
+ | --- | --- | --- |
35
+ | `pi-agent/models.json` | Pi(`ModelRuntime`) | `providers.magpie`:`name` / `api` / `baseUrl` / `apiKey`,`models` 必须是定义**数组** |
36
+ | `pi-agent/settings.json` | Pi(`SettingsManager`) | `defaultProvider` / `defaultModel` |
37
+ | `model-visibility.json` | OhMyGame 自己的 daemon | `customProviders.magpie`,OhMyGame 列出的模型 |
38
+ | `data/connections.json` + `data/plugin-configuration.json` | OhMyGame 的 daemon | 一条 `magpie` 连接,定义按 OhMyGame 自己的方式加密存放 |
39
+
40
+ Pi 会用 schema 校验 `models.json`,**一条坏数据会让整个文件被拒**——结果不是少一
41
+ 个模型,而是 OhMyGame 一个 provider 都不剩。两条铁律因此落在 `lib/pi-models.mjs`
42
+ 里:
43
+
44
+ - provider 的 `models` 是定义数组,不能是以模型 id 为键的对象;
45
+ - `contextWindow` / `maxTokens` 必须是正整数,且输出不大于上下文窗口。magpie 的
46
+ 目录里有压根没报窗口的模型(某个 ASR 模型报 `0`),这里补齐而不是照抄。
47
+
48
+ `model-visibility.json` 里的模型只声明 `language`:图像输入由 Pi 从
49
+ `supportsImages` / `input` 读,而 `usages.image` 是图像**生成**设置,只有图像协议
50
+ 才合法。
51
+
52
+ ## 模型选择器
53
+
54
+ 插件实现了 magpie 的 `own` 钩子:把选中的模型作为 agent 选项返回,且不带
55
+ `direct` 标记,因此不会额外多出一个 provider 分区。还没选模型时给出默认的 Xiaomi
56
+ 模型。`connect` 再把同一个模型写进 OhMyGame 的 Pi 配置,键名是那些文件里的点号
57
+ 路径。
58
+
59
+ OhMyGame 里的 `magpie` provider 指向 magpie 的本地 gateway,用 magpie 写入的
60
+ agent key。插件不会通过自己的配置或模型选择器暴露这个 key。
61
+
62
+ ## MCP
63
+
64
+ **OhMyGame 不读任何 `mcp.json`。** 它只把「连接」里的 server 交给会话,并且会把
65
+ Pi 自己的 MCP adapter 从交给会话的 settings 里过滤掉(`dist/daemon/agent.js`)。
66
+ 所以 `models.json` 旁边那个 `mcp.json` 谁都不会读,插件也不再往那儿写。
67
+
68
+ 入口是连接,而插件会自己加一条,且按 OhMyGame daemon 的写法来:`data/connections.json`
69
+ 里一条索引,定义加密写进 `data/plugin-configuration.json`,用
70
+ `data/plugin-credentials.key` 做 AES-256-GCM(`iv | auth tag | 明文`,base64),
71
+ 键是 `connection:<id>/server`。OhMyGame 自己的 `ConnectionService` 能把它读回成
72
+ `connection-magpie`,看起来就和手动加的连接一样。
73
+
74
+ **只能在 OhMyGame 关闭时写。** 它的 daemon 把这两个文件都读进内存,任何变更都会
75
+ **整份回写**,落在下面的内容会被覆盖掉;而唯一能通知它重载的 `/connections` 路由
76
+ 需要 daemon token,那个 token 每次启动随机生成、只走 stdin,外部永远拿不到。所以
77
+ 插件在加载时试一次,把结果打进 magpie 日志,同时挂一个 `unref` 定时器,等 OhMyGame
78
+ 一关就补写——不需要粘贴。`data/external-mcp/app.json` 里有 app 的 pid,崩溃退出
79
+ 会留下残留记录,所以 pid 也会一并核验。
80
+
81
+ 连接的地址就是这个 agent 的 magpie MCP hub;本机来的调用不需要 key,所以不存任何
82
+ 密钥。地址跟着 Settings › Gateway address 走,端口变了就在**同一条**连接上改写,
83
+ 不会堆出第二条。
84
+
85
+ 如果存储还不存在(OhMyGame 从没打开过),或者不是本插件认得的形状,插件就不动
86
+ 它,改为写出可粘贴的片段,粘到 Settings › MCP connections › Add connection 的
87
+ JSON 标签里:
88
+
89
+ ```text
90
+ ~/Library/Application Support/ohmygame/magpie-mcp-connection.json
91
+ ```
92
+
93
+ **给 OhMyGame 哪些 server,由 magpie 决定。** 一条连接就够:hub 只交出 `agents`
94
+ 里含 `ohmygame` 的 server(`library.json` 的 `mcp[]`),所以某个 server 是只给
95
+ OhMyGame 还是与其他 agent 共享、要不要对它关掉,都是在 magpie 侧改一次,而不是在
96
+ OhMyGame 里再加一条连接。hub 交出三个入口工具 —— `find_tools` / `call_tool` /
97
+ `run_code`,其中 `find_tools` 不带查询就能列出当前挂在后面的工具,缺工具时先看它。
98
+
99
+ 反方向是 OhMyGame 自己的启动器,它每次启动都会重写,因此 App 搬家也不失效,可以给
100
+ 别的 agent 启动:
101
+
102
+ ```text
103
+ ~/Library/Application Support/ohmygame/bin/ohmygame-mcp
104
+ ```
105
+
106
+ 改完模型要重启 OhMyGame:它只在启动时读这些文件,daemon 会把读到的模型留在内存里。
107
+
108
+ ## 发布
109
+
110
+ 打 tag 就发布,版本号以 tag 为准(`package.json` 与 tag 不一致时 CI 会失败而不是
111
+ 硬发):
112
+
113
+ ```bash
114
+ npm version patch && git push --follow-tags
115
+ ```
116
+
117
+ 需要仓库 secret `NPM_TOKEN`。CI 会在 Node 20 / 22 / 24 上跑 `npm test`,用
118
+ `npm pack --dry-run` 检查发布清单,再以 `npm publish --provenance` 发布。
119
+
120
+ ## English
121
+
122
+ A magpie plugin for OhMyGame. It appears as the **Oh My Game** agent on magpie's
123
+ Agents page: pick one of magpie's models there and OhMyGame uses it, and magpie's
124
+ MCP hub becomes one of OhMyGame's own MCP connections.
125
+
126
+ - **Models.** The selected model is written into OhMyGame's Pi configuration, and
127
+ the `magpie` provider is registered in `model-visibility.json`, so OhMyGame
128
+ really lists it instead of showing an empty provider.
129
+ - **MCP.** magpie's MCP hub is written as one of OhMyGame's own connections, which
130
+ is the only MCP a session is given. Which servers OhMyGame gets, and how many,
131
+ stays magpie's decision.
132
+
133
+ To install, add it on magpie's Plugins page by name, or in
134
+ `~/.config/magpie/plugins.json`:
135
+
136
+ ```json
137
+ { "spec": "@mizuka-wu/magpie-plugin-ohmygame@latest" }
138
+ ```
139
+
140
+ Then pick a magpie model for the `Oh My Game` agent. **Open OhMyGame once first**:
141
+ it creates its data folder and credential key on start, and until then there is no
142
+ connection store to write, so the plugin falls back to leaving a snippet to paste.
143
+
144
+ Pi validates `models.json` against a schema and rejects the **whole file** on one
145
+ bad entry, which leaves OhMyGame with no provider at all rather than one broken
146
+ model. So a provider's `models` is an array of definitions, never an object keyed
147
+ by id, and `contextWindow` / `maxTokens` are positive integers with output no
148
+ greater than the window — magpie's catalog holds models that report no window at
149
+ all (an ASR model reports `0`), and those are filled in rather than passed through.
150
+
151
+ OhMyGame reads **no `mcp.json`**: it hands a session only the servers from its own
152
+ connections and filters Pi's own MCP adapter out of the settings it hands a session.
153
+ A connection is the way in, and the plugin adds one itself, in the shape its daemon
154
+ writes, but only while OhMyGame is closed — its daemon keeps that store in memory
155
+ and writes the whole file back on any change, and the one route that could be told
156
+ needs a token that is random per start and sent only over stdin. So the plugin tries
157
+ at load, says what it did in magpie's log, and keeps an unref'd timer until the app
158
+ closes; the connection lands then, with nothing to paste. Its address is this agent's
159
+ MCP hub, and magpie answers a call from this computer without a key, so none is
160
+ stored. A connection written while the app runs is not picked up at all, so the wait
161
+ is for its close, not for a restart. Restart OhMyGame after changing its model: it
162
+ reads those files once at start, and its daemon keeps the models it loaded in memory.
163
+
164
+ To publish, push a tag; the tag decides the version, and CI fails rather than
165
+ publishing a mismatch. Needs an `NPM_TOKEN` repository secret.
@@ -0,0 +1,21 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" role="img" aria-label="OhMyGame">
2
+ <defs>
3
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#58e3b7"/>
5
+ <stop offset="1" stop-color="#1877f2"/>
6
+ </linearGradient>
7
+ <linearGradient id="shine" x1="0" y1="0" x2="0" y2="1">
8
+ <stop offset="0" stop-color="#fff" stop-opacity=".82"/>
9
+ <stop offset="1" stop-color="#fff" stop-opacity=".12"/>
10
+ </linearGradient>
11
+ </defs>
12
+ <rect width="256" height="256" rx="58" fill="url(#bg)"/>
13
+ <path d="M64 128c0-35.3 28.7-64 64-64h32c22 0 40 18 40 40v28c0 30.9-25.1 56-56 56H88c-13.3 0-24-10.7-24-24v-36z" fill="url(#shine)"/>
14
+ <path d="M101 82v92M155 82v92" stroke="#153b70" stroke-width="18" stroke-linecap="round"/>
15
+ <path d="M78 128h100" stroke="#153b70" stroke-width="18" stroke-linecap="round"/>
16
+ <circle cx="101" cy="128" r="11" fill="#153b70"/>
17
+ <circle cx="155" cy="128" r="11" fill="#153b70"/>
18
+ <circle cx="101" cy="174" r="11" fill="#153b70"/>
19
+ <circle cx="155" cy="174" r="11" fill="#153b70"/>
20
+ <path d="M87 205h82" stroke="#fff" stroke-width="12" stroke-linecap="round" opacity=".7"/>
21
+ </svg>
package/index.mjs ADDED
@@ -0,0 +1,50 @@
1
+ import { syncOhMyGameAgent } from "./lib/ohmygame-agent.mjs";
2
+ import { ensureOhMyGameConnection } from "./lib/ohmygame-connection-store.mjs";
3
+ import { magpieGatewayUrl, magpieMcpHubUrl, magpieMcpServer, writeOhMyGameConnections } from "./lib/ohmygame-mcp.mjs";
4
+
5
+ // Best effort at load: OhMyGame's files are written again whenever Magpie picks
6
+ // a model for it, so a failure here is worth printing but never worth throwing.
7
+ // The plugin host sends console.error to stderr, which magpie keeps in its log.
8
+ export default async function magpieOhMyGame() {
9
+ const result = await syncOhMyGameAgent().catch((error) => {
10
+ console.error(`magpie-oh-my-game: could not sync OhMyGame's model files: ${error?.message ?? error}`);
11
+ return undefined;
12
+ });
13
+ if (result?.changed) console.error("magpie-oh-my-game: rewrote OhMyGame's model files; restart OhMyGame");
14
+
15
+ // Magpie's MCP reaches OhMyGame as one of its own connections, which is the
16
+ // only MCP a session is given. It is written into OhMyGame's store when the
17
+ // app is closed, and picked up as soon as it closes.
18
+ const gateway = await magpieGatewayUrl().catch(() => undefined);
19
+ if (gateway) {
20
+ const url = magpieMcpHubUrl(gateway);
21
+ const settled = await ensureOhMyGameConnection({ url, log: reportConnection }).catch((error) => {
22
+ console.error(`magpie-oh-my-game: could not add Magpie to OhMyGame's MCP connections: ${error?.message ?? error}`);
23
+ return { status: "unwritable" };
24
+ });
25
+ // The store is OhMyGame's own private state, so anything it does not
26
+ // recognize ends the automatic path; a snippet left where it is easy to
27
+ // find does not.
28
+ if (["absent", "unknown", "unwritable"].includes(settled?.status)) {
29
+ const paste = await writeOhMyGameConnections([magpieMcpServer({ gateway })]).catch(() => undefined);
30
+ if (paste) {
31
+ console.error(`magpie-oh-my-game: paste ${paste.filePath} into OhMyGame's Settings › MCP connections instead`);
32
+ }
33
+ }
34
+ }
35
+ return {};
36
+ }
37
+
38
+ const SAYS = {
39
+ installed: (result) => `added Magpie to OhMyGame's MCP connections (${result.connectionId}); start OhMyGame to use it`,
40
+ updated: (result) => `updated Magpie's MCP connection in OhMyGame to Magpie's current address (${result.connectionId})`,
41
+ running: () => "OhMyGame is open, so its MCP connection cannot be written yet: it keeps that store in memory and writes it back on any change.",
42
+ // Said once per address, whatever reloads the plugin in between.
43
+ waiting: () => "it will be added the next time OhMyGame is closed, without pasting anything",
44
+ unknown: () => "OhMyGame's connection store is not a shape this knows, so nothing was written to it",
45
+ };
46
+
47
+ function reportConnection(result) {
48
+ const said = SAYS[result.status]?.(result);
49
+ if (said) console.error(`magpie-oh-my-game: ${said}`);
50
+ }
@@ -0,0 +1,151 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { apiModelId, piModelEntries, toPiModel, toVisibilityModel } from "./pi-models.mjs";
5
+
6
+ const DEFAULT_OHMYGAME_DIR = path.join(os.homedir(), "Library", "Application Support", "ohmygame");
7
+
8
+ export function resolveOhMyGamePaths({
9
+ home = os.homedir(),
10
+ dataDir = DEFAULT_OHMYGAME_DIR,
11
+ } = {}) {
12
+ const root = expandPath(dataDir, home);
13
+ const piDir = path.join(root, "pi-agent");
14
+ return {
15
+ dataDir: root,
16
+ piDir,
17
+ models: path.join(piDir, "models.json"),
18
+ settings: path.join(piDir, "settings.json"),
19
+ visibility: path.join(root, "model-visibility.json"),
20
+ };
21
+ }
22
+
23
+ export async function readOhMyGameModelConfig(options = {}) {
24
+ const paths = resolveOhMyGamePaths(options);
25
+ return {
26
+ paths,
27
+ models: await readJson(paths.models),
28
+ settings: await readJson(paths.settings),
29
+ visibility: await readJson(paths.visibility),
30
+ };
31
+ }
32
+
33
+ export async function writeOhMyGameModelConfig({
34
+ models,
35
+ settings,
36
+ visibility,
37
+ ...options
38
+ }) {
39
+ const paths = resolveOhMyGamePaths(options);
40
+ await mkdir(paths.piDir, { recursive: true });
41
+ if (models !== undefined) await writeJsonAtomic(paths.models, models);
42
+ if (settings !== undefined) await writeJsonAtomic(paths.settings, settings);
43
+ if (visibility !== undefined) await writeJsonAtomic(paths.visibility, visibility);
44
+ return paths;
45
+ }
46
+
47
+ /**
48
+ * Puts Magpie's model in the two files OhMyGame reads its models from:
49
+ * pi-agent/models.json (Pi's provider config) and model-visibility.json
50
+ * (OhMyGame's own list of what a custom provider shows).
51
+ */
52
+ export async function syncOhMyGameAgent({
53
+ model,
54
+ gateway = {},
55
+ providerName = "magpie",
56
+ ...options
57
+ } = {}) {
58
+ const before = await readOhMyGameModelConfig(options);
59
+ const nextModels = structuredClone(before.models);
60
+ const nextSettings = structuredClone(before.settings);
61
+ const nextVisibility = structuredClone(before.visibility);
62
+ const declared = asProviderObject(nextModels.providers?.[providerName]);
63
+ const baseUrl = gateway.v1 ?? gateway.url ?? declared?.baseUrl;
64
+
65
+ // Each entry keeps the key it was listed under when `models` was keyed by the
66
+ // model id, so updating a model rewrites its entry instead of adding a twin.
67
+ const entries = declared ? piModelEntries(declared.models) : [];
68
+ if (model && (declared || baseUrl)) {
69
+ // Pi needs an api and a baseUrl before it will read a custom provider, so
70
+ // one is only started once Magpie's address is known.
71
+ if (!declared) {
72
+ nextModels.providers ??= {};
73
+ nextModels.providers[providerName] = { name: providerName, api: "openai-completions", baseUrl, models: [] };
74
+ }
75
+ const provider = nextModels.providers[providerName];
76
+ const id = apiModelId(model);
77
+ const at = entries.findIndex((one) => one.ref === id || one.entry.id === id);
78
+ const known = at >= 0 ? entries[at] : undefined;
79
+ const definition = toPiModel({ ...(known?.entry ?? {}), ...model, id: known?.entry?.id ?? id }, {
80
+ api: provider.api,
81
+ baseUrl,
82
+ });
83
+ if (at >= 0) entries[at] = { ...entries[at], entry: definition };
84
+ else entries.push({ entry: definition, ref: id });
85
+
86
+ nextSettings.defaultProvider = providerName;
87
+ nextSettings.defaultModel = definition.id;
88
+ if (Array.isArray(nextSettings.enabledModels) && !nextSettings.enabledModels.includes(definition.id)) {
89
+ nextSettings.enabledModels.push(definition.id);
90
+ }
91
+ }
92
+
93
+ const provider = asProviderObject(nextModels.providers?.[providerName]);
94
+ if (provider) {
95
+ // Pi takes `models` as an array; an older write keyed it, which it rejects.
96
+ provider.models = entries.map((one) => one.entry);
97
+ declareCustomProvider(nextVisibility, providerName, provider.models);
98
+ }
99
+
100
+ const paths = await writeOhMyGameModelConfig({
101
+ models: !sameJson(nextModels, before.models) ? nextModels : undefined,
102
+ settings: !sameJson(nextSettings, before.settings) ? nextSettings : undefined,
103
+ visibility: !sameJson(nextVisibility, before.visibility) ? nextVisibility : undefined,
104
+ ...options,
105
+ });
106
+ const changed = !sameJson(nextModels, before.models)
107
+ || !sameJson(nextSettings, before.settings)
108
+ || !sameJson(nextVisibility, before.visibility);
109
+ return { changed, paths, model, visibility: nextVisibility };
110
+ }
111
+
112
+ function asProviderObject(provider) {
113
+ return provider && typeof provider === "object" && !Array.isArray(provider) ? provider : undefined;
114
+ }
115
+
116
+ /** OhMyGame only lists a custom provider it has an entry for in model-visibility.json. */
117
+ function declareCustomProvider(visibility, providerName, models) {
118
+ visibility.version = 1;
119
+ visibility.hidden ??= {};
120
+ visibility.hidden[providerName] ??= [];
121
+ visibility.customProviders ??= {};
122
+ visibility.customProviders[providerName] = {
123
+ ...asProviderObject(visibility.customProviders[providerName]),
124
+ authentication: "api_key",
125
+ modelConfigurationVersion: 2,
126
+ models: piModelEntries(models).map((one) => toVisibilityModel(one.entry)),
127
+ };
128
+ }
129
+
130
+ function sameJson(left, right) {
131
+ return JSON.stringify(left) === JSON.stringify(right);
132
+ }
133
+
134
+ async function readJson(filePath) {
135
+ try {
136
+ return JSON.parse(await readFile(filePath, "utf8"));
137
+ } catch {
138
+ return {};
139
+ }
140
+ }
141
+
142
+ async function writeJsonAtomic(filePath, value) {
143
+ await mkdir(path.dirname(filePath), { recursive: true });
144
+ const temporary = `${filePath}.tmp-${process.pid}-${Date.now()}`;
145
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
146
+ await rename(temporary, filePath);
147
+ }
148
+
149
+ function expandPath(value, home) {
150
+ return value.startsWith("~") ? path.join(home, value.slice(1)) : value;
151
+ }
@@ -0,0 +1,301 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ /**
7
+ * OhMyGame's own connection store, written the way its daemon writes it.
8
+ *
9
+ * A connection is the only MCP a session gets: OhMyGame filters Pi's own MCP
10
+ * adapter out of the settings it hands a session, and reads no mcp.json. Its
11
+ * daemon is the only thing that normally adds one, and the token that route
12
+ * needs is random per start and sent only over stdin, so nothing outside the
13
+ * app can call it while OhMyGame runs.
14
+ *
15
+ * Everything it stores is readable by its owner: `data/connections.json` holds
16
+ * an index and `data/plugin-configuration.json` holds the server definition
17
+ * under `connection:<id>/server`, encrypted with AES-256-GCM keyed by
18
+ * `data/plugin-credentials.key`, base64 of the iv, the auth tag, the text. That
19
+ * key lives in the person's own private folder, so writing a connection here is
20
+ * the same trust level as the app itself having one.
21
+ *
22
+ * Only while OhMyGame is closed, though: its daemon keeps both files in memory
23
+ * and writes the whole store back on any change, which would drop what landed
24
+ * underneath it.
25
+ */
26
+
27
+ /** What OhMyGame calls a connection's MCP server, which also never changes. */
28
+ const CONNECTION_SERVER = "server";
29
+ const ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
30
+
31
+ export function resolveOhMyGameStorePaths({
32
+ home = os.homedir(),
33
+ dataDir = path.join(home, "Library", "Application Support", "ohmygame"),
34
+ } = {}) {
35
+ const root = expandPath(dataDir, home);
36
+ const data = path.join(root, "data");
37
+ return {
38
+ dataDir: root,
39
+ data,
40
+ connections: path.join(data, "connections.json"),
41
+ configuration: path.join(data, "plugin-configuration.json"),
42
+ credentials: path.join(data, "plugin-credentials.key"),
43
+ running: path.join(data, "external-mcp", "app.json"),
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Whether OhMyGame is open. It records its own pid on start and removes the
49
+ * record on quit, and leaves it behind if it crashed, so the pid is checked too.
50
+ */
51
+ export async function isOhMyGameRunning(options = {}) {
52
+ const paths = resolveOhMyGameStorePaths(options);
53
+ const record = await readJson(paths.running);
54
+ const pid = typeof record?.pid === "number" ? record.pid : undefined;
55
+ if (pid === undefined) return false;
56
+ try {
57
+ process.kill(pid, 0);
58
+ return true;
59
+ } catch (cause) {
60
+ return cause?.code === "EPERM";
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Adds Magpie's MCP connection to OhMyGame, or refreshes the one it added
66
+ * before. `installed`, `updated` or `already`; `running` while OhMyGame is open
67
+ * and would write the store over this, `absent` before it has been opened, and
68
+ * `unknown` for a store format this does not recognize.
69
+ */
70
+ export async function installOhMyGameConnection({
71
+ url,
72
+ displayName = "Magpie",
73
+ ...options
74
+ } = {}) {
75
+ if (!url) throw new Error("url is required");
76
+ const paths = resolveOhMyGameStorePaths(options);
77
+ if (await isOhMyGameRunning(paths)) return { status: "running", paths };
78
+
79
+ // The key is the one file OhMyGame makes just by starting, so it is what says
80
+ // the app has been opened. Both stores wait for a first change, so neither is
81
+ // here yet after an opening that added nothing, and OhMyGame reads an empty
82
+ // one as eagerly as it wrote it.
83
+ const key = await readFile(paths.credentials).catch(() => undefined);
84
+ if (!key) return { status: "absent", paths };
85
+ if (key.length !== 32) throw new Error("Unexpected plugin credential key");
86
+
87
+ const index = (await readJson(paths.connections)) ?? { version: 1, connections: {} };
88
+ const store = (await readJson(paths.configuration)) ?? { version: 1, plugins: {}, credentials: {} };
89
+ // OhMyGame reads either file eagerly and throws on a version it does not
90
+ // know, so a future format is left for it rather than written through.
91
+ if (index.version !== 1 || store.version !== 1) return { status: "unknown", paths };
92
+ const connections = index.connections ?? {};
93
+ const existing = findOurs(connections, store, key, url);
94
+ const template = { url };
95
+ if (existing && sameDefinition(store, key, existing, template)) {
96
+ return { status: "already", connectionId: existing, paths };
97
+ }
98
+
99
+ // OhMyGame rewrites the whole store on any change, so a half-written pair of
100
+ // files would leave a connection whose definition is missing and break its
101
+ // settings page. The definition goes first; a stray entry of ours alone is
102
+ // read by nothing.
103
+ const id = existing ?? freeId(slug(displayName), connections);
104
+ const next = structuredClone(store);
105
+ next.version = 1;
106
+ next.plugins ??= {};
107
+ next.credentials ??= {};
108
+ next.serverOverrides ??= {};
109
+ const ref = randomUUID();
110
+ const previous = next.serverOverrides[`connection:${id}/${CONNECTION_SERVER}`];
111
+ if (previous) delete next.credentials[previous];
112
+ next.serverOverrides[`connection:${id}/${CONNECTION_SERVER}`] = ref;
113
+ next.credentials[ref] = encrypt(key, JSON.stringify(template));
114
+ await writeJsonAtomic(paths.configuration, next);
115
+
116
+ const nextIndex = structuredClone(index);
117
+ nextIndex.version = 1;
118
+ nextIndex.connections ??= {};
119
+ // The name is theirs to change, so a refresh keeps the one it finds.
120
+ const held = nextIndex.connections[id];
121
+ nextIndex.connections[id] = {
122
+ id,
123
+ displayName: held?.displayName ?? displayName,
124
+ enabled: held?.enabled ?? true,
125
+ };
126
+ await writeJsonAtomic(paths.connections, nextIndex);
127
+ return { status: existing ? "updated" : "installed", connectionId: id, paths };
128
+ }
129
+
130
+ /**
131
+ * Magpie's connection as OhMyGame will start it: its id, and the definition it
132
+ * resolves to. Found by hub path, since its name is theirs to rename; `url`
133
+ * narrows it to the hub of one gateway.
134
+ */
135
+ export async function readOhMyGameConnection({ url, ...options } = {}) {
136
+ const paths = resolveOhMyGameStorePaths(options);
137
+ const [index, store, key] = await Promise.all([
138
+ readJson(paths.connections),
139
+ readJson(paths.configuration),
140
+ readFile(paths.credentials).catch(() => undefined),
141
+ ]);
142
+ if (!index || !store || !key) return undefined;
143
+ for (const [id, record] of Object.entries(index.connections ?? {})) {
144
+ const definition = definitionOf(store, key, id);
145
+ if (!definition) continue;
146
+ if (url === undefined || hubPathOf(definition.url) === hubPathOf(url)) {
147
+ return { id, record, definition };
148
+ }
149
+ }
150
+ return undefined;
151
+ }
152
+
153
+ /**
154
+ * Installs a connection and resolves at once. OhMyGame open is the one case
155
+ * that cannot be settled here — nothing outside the app can tell its daemon to
156
+ * reread, since the token that route needs never reaches this side — so a
157
+ * background timer keeps trying until it closes. Its timers are unref'd, and
158
+ * the promise settles now: magpie waits on what a plugin's load returns.
159
+ *
160
+ * `log` hears the first outcome and, from the background, the one that lands.
161
+ */
162
+ export async function ensureOhMyGameConnection({
163
+ url,
164
+ retryMs = 30_000,
165
+ maxWaitMs = 60 * 60_000,
166
+ log = () => {},
167
+ ...options
168
+ } = {}) {
169
+ const attempt = () => installOhMyGameConnection({ url, ...options });
170
+ // magpie reloads a plugin, and a second wait would write the same store twice,
171
+ // so one address waits once. The wait says nothing twice.
172
+ if (waits.has(url)) return { status: "waiting" };
173
+ const first = await attempt();
174
+ log(first);
175
+ if (first.status === "running") {
176
+ // Said once now, and once when it lands: an app left open all day is not
177
+ // news every half minute.
178
+ log({ status: "waiting", paths: first.paths });
179
+ waits.add(url);
180
+ retryUntilClosed({ url, attempt, retryMs, maxWaitMs, log });
181
+ }
182
+ return first;
183
+ }
184
+
185
+ const waits = new Set();
186
+
187
+ async function retryUntilClosed({ url, attempt, retryMs, maxWaitMs, log }) {
188
+ const deadline = Date.now() + maxWaitMs;
189
+ try {
190
+ while (Date.now() < deadline) {
191
+ await sleep(retryMs);
192
+ const next = await attempt().catch(() => undefined);
193
+ if (!next || next.status === "running") continue;
194
+ log(next);
195
+ return next;
196
+ }
197
+ } finally {
198
+ waits.delete(url);
199
+ }
200
+ }
201
+
202
+ function sleep(ms) {
203
+ return new Promise((resolve) => {
204
+ const timer = setTimeout(resolve, ms);
205
+ timer.unref?.();
206
+ });
207
+ }
208
+
209
+ /**
210
+ * The connection Magpie added before, if any: the one pointing at this same
211
+ * hub path on some other address. Its name is left out on purpose, since it is
212
+ * theirs to rename, and a hand-made connection of the same name that points
213
+ * somewhere else is theirs to keep.
214
+ */
215
+ function findOurs(connections, store, key, url) {
216
+ const path = hubPathOf(url);
217
+ if (!path) return undefined;
218
+ for (const id of Object.keys(connections)) {
219
+ const held = definitionOf(store, key, id);
220
+ if (held?.url && hubPathOf(held.url) === path) return id;
221
+ }
222
+ return undefined;
223
+ }
224
+
225
+ /** A hub's path, which is what stays put when only Magpie's address moves. */
226
+ function hubPathOf(url) {
227
+ try {
228
+ return new URL(url).pathname;
229
+ } catch {
230
+ return undefined;
231
+ }
232
+ }
233
+
234
+ function definitionOf(store, key, id) {
235
+ const ref = store.serverOverrides?.[`connection:${id}/${CONNECTION_SERVER}`];
236
+ if (!ref) return undefined;
237
+ const text = store.credentials?.[ref];
238
+ if (!text) return undefined;
239
+ try {
240
+ return JSON.parse(decrypt(key, text));
241
+ } catch {
242
+ return undefined;
243
+ }
244
+ }
245
+
246
+ function sameDefinition(store, key, id, template) {
247
+ const held = definitionOf(store, key, id);
248
+ return Boolean(held) && JSON.stringify(held) === JSON.stringify(template);
249
+ }
250
+
251
+ function freeId(base, connections) {
252
+ let id = base;
253
+ for (let index = 2; Object.hasOwn(connections, id); index++) id = `${base}-${index}`;
254
+ return id;
255
+ }
256
+
257
+ function slug(value) {
258
+ const id = String(value).toLowerCase()
259
+ .replace(/[^a-z0-9]+/g, "-")
260
+ .replace(/^-+|-+$/g, "")
261
+ .slice(0, 60)
262
+ .replace(/-+$/, "");
263
+ return ID.test(id) ? id : "connection";
264
+ }
265
+
266
+ function encrypt(key, value) {
267
+ const iv = randomBytes(12);
268
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
269
+ const data = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
270
+ return Buffer.concat([iv, cipher.getAuthTag(), data]).toString("base64");
271
+ }
272
+
273
+ function decrypt(key, value) {
274
+ const data = Buffer.from(value, "base64");
275
+ const decipher = createDecipheriv("aes-256-gcm", key, data.subarray(0, 12));
276
+ decipher.setAuthTag(data.subarray(12, 28));
277
+ return Buffer.concat([decipher.update(data.subarray(28)), decipher.final()]).toString("utf8");
278
+ }
279
+
280
+ async function writeJsonAtomic(filePath, value) {
281
+ await mkdir(path.dirname(filePath), { recursive: true });
282
+ const temporary = `${filePath}.${randomUUID()}.tmp`;
283
+ try {
284
+ await writeFile(temporary, JSON.stringify(value, null, 2), { mode: 0o600, flag: "wx" });
285
+ await rename(temporary, filePath);
286
+ } finally {
287
+ await unlink(temporary).catch(() => {});
288
+ }
289
+ }
290
+
291
+ async function readJson(filePath) {
292
+ try {
293
+ return JSON.parse(await readFile(filePath, "utf8"));
294
+ } catch {
295
+ return undefined;
296
+ }
297
+ }
298
+
299
+ function expandPath(value, home) {
300
+ return value.startsWith("~") ? path.join(home, value.slice(1)) : value;
301
+ }
@@ -0,0 +1,109 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ /**
6
+ * OhMyGame gives its agent MCP servers from its own connections, which it keeps
7
+ * encrypted (data/plugin-configuration.json, keyed by data/plugin-credentials.key)
8
+ * and reads only through its daemon. It filters Pi's own MCP adapter out of the
9
+ * settings it hands a session, so the mcp.json next to models.json is read by
10
+ * neither OhMyGame nor Pi there. This module builds what a person pastes into
11
+ * Settings › MCP connections › Add connection instead.
12
+ */
13
+ export function defaultOhMyGameMcpCommand(home = os.homedir()) {
14
+ return path.join(home, "Library", "Application Support", "ohmygame", "bin", "ohmygame-mcp");
15
+ }
16
+
17
+ /** OhMyGame's own MCP server, for another agent to start. */
18
+ export function ohMyGameMcpServer({
19
+ command = defaultOhMyGameMcpCommand(),
20
+ args = [],
21
+ name = "ohmygame",
22
+ } = {}) {
23
+ return { name, transport: "stdio", command, args };
24
+ }
25
+
26
+ /** Magpie's MCP hub for one agent, below the gateway's root rather than its `/v1`. */
27
+ export function magpieMcpHubUrl(gateway, agent = "ohmygame") {
28
+ const base = String(gateway ?? "").replace(/\/v1\/?$/, "").replace(/\/$/, "");
29
+ if (!base) throw new Error("gateway is required");
30
+ const address = /^[a-z][a-z0-9+.-]*:\/\//i.test(base) ? base : `http://${base}`;
31
+ return `${address}/mcp/magpie/hub/${agent}`;
32
+ }
33
+
34
+ /**
35
+ * Magpie's one MCP server, scoped to the models, tools and limits of this agent.
36
+ * Magpie answers a call that comes from this computer without a key, so a key is
37
+ * only sent when the gateway is somewhere else.
38
+ */
39
+ export function magpieMcpServer({ gateway, agent = "ohmygame", key, name = "magpie" } = {}) {
40
+ const url = magpieMcpHubUrl(gateway, agent);
41
+ const loopback = /^(?:127\.0\.0\.1|localhost|\[::1\])$/.test(new URL(url).hostname);
42
+ return {
43
+ name,
44
+ transport: "http",
45
+ url,
46
+ ...(!loopback && key ? { headers: { Authorization: `Bearer ${key}` } } : {}),
47
+ };
48
+ }
49
+
50
+ /**
51
+ * The shape OhMyGame's paste box takes: `{"mcpServers": …}`, or the servers on
52
+ * their own. Each entry needs a `url` or a `command`, never both. A key becomes
53
+ * a header, which OhMyGame stores encrypted with the connection.
54
+ */
55
+ export function ohMyGameConnections(servers = []) {
56
+ return {
57
+ mcpServers: Object.fromEntries(servers.map(({ name, url, command, args, env, headers }) => [
58
+ name,
59
+ {
60
+ ...(url ? { url } : { command, ...(args?.length ? { args } : {}) }),
61
+ ...(headers ? { headers } : {}),
62
+ ...(env ? { env } : {}),
63
+ },
64
+ ])),
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Writes a paste file next to the model files, since a connection is the only
70
+ * way in and Magpie's address moves whenever it picks another port. OhMyGame
71
+ * reads the files it knows by name and ignores anything else in this folder.
72
+ */
73
+ export async function writeOhMyGameConnections(servers, { filePath, ...options } = {}) {
74
+ const target = filePath ?? defaultConnectionsPath(options);
75
+ const json = `${JSON.stringify(ohMyGameConnections(servers), null, 2)}\n`;
76
+ if (await readFile(target, "utf8").catch(() => undefined) === json) {
77
+ return { filePath: target, json, changed: false };
78
+ }
79
+ await mkdir(path.dirname(target), { recursive: true });
80
+ const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
81
+ await writeFile(temporary, json, { mode: 0o600 });
82
+ await rename(temporary, target);
83
+ return { filePath: target, json, changed: true };
84
+ }
85
+
86
+ export function defaultConnectionsPath({ dataDir = defaultOhMyGameDataDir() } = {}) {
87
+ return path.join(dataDir, "magpie-mcp-connection.json");
88
+ }
89
+
90
+ /**
91
+ * Where Magpie is answering right now. Its plugin host passes the address in the
92
+ * environment; a run started without it reads what Magpie wrote at startup,
93
+ * since the port is not fixed.
94
+ */
95
+ export async function magpieGatewayUrl({
96
+ env = process.env,
97
+ configDir = path.join(os.homedir(), ".config", "magpie"),
98
+ } = {}) {
99
+ const given = env.MAGPIE_GATEWAY ?? env.MAGPIE_ADDR;
100
+ if (given) return given;
101
+ const text = await readFile(path.join(configDir, "gateway.json"), "utf8").catch(() => undefined);
102
+ if (!text) return undefined;
103
+ const address = JSON.parse(text)?.addr;
104
+ return typeof address === "string" && address ? `http://${address}` : undefined;
105
+ }
106
+
107
+ function defaultOhMyGameDataDir() {
108
+ return path.join(os.homedir(), "Library", "Application Support", "ohmygame");
109
+ }
@@ -0,0 +1,163 @@
1
+ import { constants } from "node:fs";
2
+ import { access, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { toPiModel, toVisibilityModel } from "./pi-models.mjs";
6
+
7
+ const DEFAULT_MAGPIE_CONFIG = path.join(os.homedir(), ".config", "magpie");
8
+ const SUPPORTED_APIS = new Set([
9
+ "openai-completions",
10
+ "openai-responses",
11
+ "anthropic-messages",
12
+ "google-generative-ai",
13
+ "google-vertex",
14
+ ]);
15
+
16
+ const API_BY_ENDPOINT = {
17
+ chat: "openai-completions",
18
+ responses: "openai-responses",
19
+ anthropic: "anthropic-messages",
20
+ };
21
+
22
+ export async function syncOhMyGameProvider({
23
+ provider,
24
+ magpieConfigDir = DEFAULT_MAGPIE_CONFIG,
25
+ ohmygameDataDir = path.join(os.homedir(), "Library", "Application Support", "ohmygame"),
26
+ api = "openai-completions",
27
+ baseUrl,
28
+ name,
29
+ models,
30
+ modelIds,
31
+ dryRun = false,
32
+ } = {}) {
33
+ if (!provider) throw new Error("provider is required");
34
+
35
+ const configured = await readMagpieProvider(magpieConfigDir, provider);
36
+ const endpoint = resolveEndpoint(configured, api);
37
+ const finalApi = SUPPORTED_APIS.has(api) ? api : endpoint.api;
38
+ const finalBaseUrl = baseUrl ?? endpoint.baseUrl;
39
+ if (!SUPPORTED_APIS.has(finalApi)) {
40
+ throw new Error(`Unsupported OhMyGame API: ${finalApi}`);
41
+ }
42
+ if (!finalBaseUrl) {
43
+ throw new Error(`No endpoint found for provider ${provider}`);
44
+ }
45
+
46
+ const modelDefinitions = models ?? await readCachedModels(magpieConfigDir, provider);
47
+ const selectedModels = modelDefinitions.filter((model) =>
48
+ !modelIds?.length || modelIds.includes(model.id)
49
+ );
50
+ const finalName = name ?? configured?.name ?? provider;
51
+
52
+ const plan = {
53
+ provider,
54
+ name: finalName,
55
+ api: finalApi,
56
+ baseUrl: finalBaseUrl,
57
+ models: selectedModels.map((model) => toPiModel(model, { api: finalApi, baseUrl: finalBaseUrl })),
58
+ };
59
+
60
+ if (dryRun) return { dryRun: true, changed: true, plan };
61
+
62
+ await ensureDirectory(path.dirname(path.join(ohmygameDataDir, "model-visibility.json")));
63
+ await ensureDirectory(path.dirname(path.join(ohmygameDataDir, "pi-agent", "models.json")));
64
+
65
+ const modelsPath = path.join(ohmygameDataDir, "pi-agent", "models.json");
66
+ const visibilityPath = path.join(ohmygameDataDir, "model-visibility.json");
67
+
68
+ const beforeModels = await readJsonc(modelsPath, {});
69
+ const beforeVisibility = await readJsonc(visibilityPath, { version: 1, hidden: {} });
70
+ const afterModels = structuredClone(beforeModels);
71
+ const afterVisibility = structuredClone(beforeVisibility);
72
+
73
+ afterModels.providers ??= {};
74
+ afterModels.providers[provider] = {
75
+ ...(beforeModels.providers?.[provider] ?? {}),
76
+ name: finalName,
77
+ api: finalApi,
78
+ baseUrl: finalBaseUrl,
79
+ models: plan.models,
80
+ };
81
+
82
+ afterVisibility.version = 1;
83
+ afterVisibility.hidden ??= {};
84
+ afterVisibility.hidden[provider] ??= [];
85
+ afterVisibility.customProviders ??= {};
86
+ afterVisibility.customProviders[provider] = {
87
+ ...(afterVisibility.customProviders[provider] ?? {}),
88
+ authentication: "api_key",
89
+ modelConfigurationVersion: 2,
90
+ models: plan.models.map(toVisibilityModel),
91
+ };
92
+
93
+ const changed = !jsonEqual(beforeModels, afterModels) || !jsonEqual(beforeVisibility, afterVisibility);
94
+ if (changed) {
95
+ await writeJsonAtomic(modelsPath, afterModels);
96
+ await writeJsonAtomic(visibilityPath, afterVisibility);
97
+ }
98
+
99
+ return { changed, plan, modelsPath, visibilityPath };
100
+ }
101
+
102
+ async function readMagpieProvider(configDir, providerId) {
103
+ const filePath = path.join(configDir, "providers.json");
104
+ const data = await readJsonc(filePath, { providers: [] });
105
+ const providers = Array.isArray(data.providers) ? data.providers : Object.values(data.providers ?? {});
106
+ return providers.find((entry) => entry?.id === providerId);
107
+ }
108
+
109
+ async function readCachedModels(configDir, providerId) {
110
+ const filePath = path.join(configDir, "plugin-providers.json");
111
+ const data = await readJsonc(filePath, {});
112
+ const source = data.providers?.[providerId] ?? data[providerId];
113
+ if (Array.isArray(source)) return source;
114
+ return source?.models ?? data.models ?? [];
115
+ }
116
+
117
+ function resolveEndpoint(provider, requestedApi) {
118
+ if (requestedApi === "anthropic-messages" && provider?.anthropic) {
119
+ return { api: "anthropic-messages", baseUrl: provider.anthropic };
120
+ }
121
+ if (requestedApi === "openai-responses" && provider?.responses) {
122
+ return { api: "openai-responses", baseUrl: provider.responses };
123
+ }
124
+ if (requestedApi === "openai-completions" && provider?.chat) {
125
+ return { api: "openai-completions", baseUrl: provider.chat };
126
+ }
127
+ for (const [field, value] of Object.entries(provider ?? {})) {
128
+ const api = API_BY_ENDPOINT[field];
129
+ if (api && typeof value === "string") return { api, baseUrl: value };
130
+ }
131
+ return { api: "openai-completions", baseUrl: undefined };
132
+ }
133
+
134
+ async function readJsonc(filePath, fallback) {
135
+ try {
136
+ await access(filePath, constants.R_OK);
137
+ } catch {
138
+ return structuredClone(fallback);
139
+ }
140
+ const text = await readFile(filePath, "utf8");
141
+ return JSON.parse(stripJsonComments(text));
142
+ }
143
+
144
+ async function writeJsonAtomic(filePath, value) {
145
+ await mkdir(path.dirname(filePath), { recursive: true });
146
+ const temporary = `${filePath}.tmp-${process.pid}-${Date.now()}`;
147
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
148
+ await rename(temporary, filePath);
149
+ }
150
+
151
+ async function ensureDirectory(directory) {
152
+ await mkdir(directory, { recursive: true });
153
+ }
154
+
155
+ function stripJsonComments(text) {
156
+ return text
157
+ .replace(/\/\*[\s\S]*?\*\//g, "")
158
+ .replace(/(^|[^:])\/\/.*$/gm, "$1");
159
+ }
160
+
161
+ function jsonEqual(left, right) {
162
+ return JSON.stringify(left) === JSON.stringify(right);
163
+ }
@@ -0,0 +1,103 @@
1
+ // Pi reads OhMyGame's pi-agent/models.json through a strict schema and fails the
2
+ // WHOLE file on one bad entry, which leaves OhMyGame with no provider at all.
3
+ // Two rules matter for Magpie: a provider's `models` is an ARRAY of definitions,
4
+ // and contextWindow / maxTokens are positive integers with output <= context.
5
+ // Magpie's catalog has models with no known window (an ASR model reports 0), so
6
+ // the numbers are clamped here rather than passed through.
7
+ export const DEFAULT_CONTEXT_WINDOW = 128_000;
8
+ export const DEFAULT_MAX_TOKENS = 16_384;
9
+
10
+ const SUPPORTED_APIS = new Set([
11
+ "openai-completions",
12
+ "openai-responses",
13
+ "anthropic-messages",
14
+ "google-generative-ai",
15
+ "google-vertex",
16
+ ]);
17
+
18
+ function tokenCount(value) {
19
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;
20
+ }
21
+
22
+ export function contextWindowOf(value, fallback = DEFAULT_CONTEXT_WINDOW) {
23
+ return tokenCount(value) ?? fallback;
24
+ }
25
+
26
+ export function maxTokensOf(value, contextWindow, fallback = DEFAULT_MAX_TOKENS) {
27
+ const count = tokenCount(value);
28
+ return count === undefined ? Math.min(fallback, contextWindow) : Math.min(count, contextWindow);
29
+ }
30
+
31
+ /** The id OhMyGame calls a model by: Magpie prints it as `magpie/<id>`. */
32
+ export function apiModelId(model) {
33
+ return String(model?.id ?? model ?? "").trim().replace(/^magpie\//, "");
34
+ }
35
+
36
+ /** One entry of a provider's `models` array in pi-agent/models.json. */
37
+ export function toPiModel(model, { api = "openai-completions", baseUrl } = {}) {
38
+ const id = apiModelId(model);
39
+ const name = String(model?.name ?? id).trim() || id;
40
+ const contextWindow = contextWindowOf(
41
+ model?.context ?? model?.contextWindow ?? model?.limit?.context,
42
+ );
43
+ const supportsImages = Boolean(
44
+ model?.images ?? model?.supportsImages ?? model?.capabilities?.input?.includes("image"),
45
+ );
46
+ const entry = {
47
+ id,
48
+ name,
49
+ api: SUPPORTED_APIS.has(model?.api) ? model.api : api,
50
+ contextWindow,
51
+ maxTokens: maxTokensOf(
52
+ model?.output ?? model?.maxTokens ?? model?.limit?.output,
53
+ contextWindow,
54
+ ),
55
+ reasoning: Boolean(model?.reasoning ?? model?.capabilities?.reasoning),
56
+ input: supportsImages ? ["text", "image"] : ["text"],
57
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
58
+ };
59
+ const modelBaseUrl = model?.baseUrl;
60
+ if (modelBaseUrl && modelBaseUrl !== baseUrl) entry.baseUrl = modelBaseUrl;
61
+ return entry;
62
+ }
63
+
64
+ /**
65
+ * The same model as OhMyGame lists it under customProviders in
66
+ * model-visibility.json. A model's `usages.image` is only valid with an image
67
+ * protocol, which a chat model has none of, so a language model is listed for
68
+ * language alone; Pi reads its image input from `supportsImages` / `input`.
69
+ */
70
+ export function toVisibilityModel(model) {
71
+ const supportsImages = Array.isArray(model?.input)
72
+ ? model.input.includes("image")
73
+ : Boolean(model?.supportsImages);
74
+ const contextWindow = contextWindowOf(model?.contextWindow);
75
+ return {
76
+ id: model.id,
77
+ name: model.name ?? model.id,
78
+ api: model.api,
79
+ contextWindow,
80
+ maxTokens: maxTokensOf(model?.maxTokens, contextWindow),
81
+ reasoning: Boolean(model?.reasoning),
82
+ supportsImages,
83
+ usages: { language: true },
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Pi takes `models` as an array; an older write keyed it by the model id. Each
89
+ * entry comes back with the `ref` it was listed under, so an entry keeps the id
90
+ * OhMyGame already knows it by instead of being added a second time.
91
+ */
92
+ export function piModelEntries(models) {
93
+ if (Array.isArray(models)) {
94
+ return models
95
+ .filter((entry) => entry && typeof entry === "object")
96
+ .map((entry) => ({ entry, ref: String(entry.id ?? "") }));
97
+ }
98
+ if (!models || typeof models !== "object") return [];
99
+ return Object.entries(models).map(([ref, entry]) => ({
100
+ entry: { id: ref, ...(entry ?? {}) },
101
+ ref,
102
+ }));
103
+ }
@@ -0,0 +1,62 @@
1
+ import { toPiModel } from "./lib/pi-models.mjs";
2
+
3
+ export const agent = {
4
+ id: "ohmygame",
5
+ name: "Oh My Game",
6
+ icon: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9Ik9oTXlHYW1lIj4KICA8ZGVmcz4KICAgIDxsaW5lYXJHcmFkaWVudCBpZD0iYmciIHgxPSIwIiB5MT0iMCIgeDI9IjEiIHkyPSIxIj4KICAgICAgPHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNThlM2I3Ii8+CiAgICAgIDxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzE4NzdmMiIvPgogICAgPC9saW5lYXJHcmFkaWVudD4KICAgIDxsaW5lYXJHcmFkaWVudCBpZD0ic2hpbmUiIHgxPSIwIiB5MT0iMCIgeDI9IjAiIHkyPSIxIj4KICAgICAgPHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjZmZmIiBzdG9wLW9wYWNpdHk9Ii44MiIvPgogICAgICA8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNmZmYiIHN0b3Atb3BhY2l0eT0iLjEyIi8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogIDwvZGVmcz4KICA8cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgcng9IjU4IiBmaWxsPSJ1cmwoI2JnKSIvPgogIDxwYXRoIGQ9Ik02NCAxMjhjMC0zNS4zIDI4LjctNjQgNjQtNjRoMzJjMjIgMCA0MCAxOCA0MCA0MHYyOGMwIDMwLjktMjUuMSA1Ni01NiA1Nkg4OGMtMTMuMyAwLTI0LTEwLjctMjQtMjR2LTM2eiIgZmlsbD0idXJsKCNzaGluZSkiLz4KICA8cGF0aCBkPSJNMTAxIDgydjkyTTE1NSA4MnY5MiIgc3Ryb2tlPSIjMTUzYjcwIiBzdHJva2Utd2lkdGg9IjE4IiBzdHJva2UtbGluZWNhcD0icm91bmQiLz4KICA8cGF0aCBkPSJNNzggMTI4aDEwMCIgc3Ryb2tlPSIjMTUzYjcwIiBzdHJva2Utd2lkdGg9IjE4IiBzdHJva2UtbGluZWNhcD0icm91bmQiLz4KICA8Y2lyY2xlIGN4PSIxMDEiIGN5PSIxMjgiIHI9IjExIiBmaWxsPSIjMTUzYjcwIi8+CiAgPGNpcmNsZSBjeD0iMTU1IiBjeT0iMTI4IiByPSIxMSIgZmlsbD0iIzE1M2I3MCIvPgogIDxjaXJjbGUgY3g9IjEwMSIgY3k9IjE3NCIgcj0iMTEiIGZpbGw9IiMxNTNiNzAiLz4KICA8Y2lyY2xlIGN4PSIxNTUiIGN5PSIxNzQiIHI9IjExIiBmaWxsPSIjMTUzYjcwIi8+CiAgPHBhdGggZD0iTTg3IDIwNWg4MiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjEyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIG9wYWNpdHk9Ii43Ii8+Cjwvc3ZnPgo=",
7
+ bin: "ohmygame",
8
+ dir: "~/Library/Application Support/ohmygame",
9
+ config: "~/Library/Application Support/ohmygame/pi-agent/models.json",
10
+ format: "json",
11
+ startup: {
12
+ config: "~/Library/Application Support/ohmygame/pi-agent/settings.json",
13
+ format: "json",
14
+ model: "defaultModel",
15
+ keys: { defaultProvider: "magpie" },
16
+ },
17
+ library: {
18
+ // Only the skills folder: OhMyGame gives its agent MCP from its own
19
+ // connections, which it keeps encrypted, and filters Pi's own MCP adapter
20
+ // out of the settings it hands a session. An mcp.json beside models.json
21
+ // is read by neither, so magpie writes no MCP here.
22
+ skills: "~/Library/Application Support/ohmygame/pi-agent/skills",
23
+ },
24
+ notice: "Restart OhMyGame after changing its model. Magpie's MCP connection is added to OhMyGame itself when it is next closed.",
25
+ };
26
+
27
+ const DEFAULT_MODEL_CATALOG = [
28
+ {
29
+ id: "xiaomi/mimo-v2.6-pro",
30
+ name: "MiMo-V2.6-Pro",
31
+ context: 1048576,
32
+ output: 131072,
33
+ },
34
+ ];
35
+
36
+ /**
37
+ * Magpie writes what this returns into OhMyGame's pi-agent/models.json, one
38
+ * file per dotted key. Pi reads a provider's `models` as an ARRAY of
39
+ * definitions and rejects the file outright otherwise, which is how OhMyGame
40
+ * ends up with no provider at all.
41
+ */
42
+ export function connect({ gateway = {}, model, models: offered = [] } = {}) {
43
+ const baseUrl = gateway.v1 ?? gateway.url;
44
+ const listed = offered.length ? offered : (model ? [model] : []);
45
+ const provider = { name: "magpie", api: "openai-completions" };
46
+ if (baseUrl) provider.baseUrl = baseUrl;
47
+ if (gateway.key) provider.apiKey = gateway.key;
48
+ provider.models = listed.map((entry) => toPiModel(entry, { baseUrl }));
49
+ return { "providers.magpie": provider };
50
+ }
51
+
52
+ /** The model list OhMyGame's picker shows: Magpie's id, without a `magpie/` prefix. */
53
+ export function own({ model } = {}) {
54
+ const selected = String(model?.id ?? model ?? "").trim();
55
+ const selectedId = selected.replace(/^magpie\//, "");
56
+ const catalog = selectedId && !DEFAULT_MODEL_CATALOG.some((entry) => entry.id === selectedId)
57
+ ? [{ id: selectedId, name: model?.name ?? selectedId }]
58
+ : DEFAULT_MODEL_CATALOG;
59
+ return catalog.map((entry) => ({ value: selected || entry.id, model: entry.id }));
60
+ }
61
+
62
+ export default { agent, connect, own };
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@mizuka-wu/magpie-plugin-ohmygame",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "OhMyGame for magpie — its models picked from magpie's, and magpie's MCP hub as one of OhMyGame's own connections",
5
+ "keywords": [
6
+ "magpie",
7
+ "magpie-plugin",
8
+ "magpie-agent",
9
+ "opencode-plugin",
10
+ "mcp",
11
+ "ohmygame",
12
+ "provider"
13
+ ],
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/mizuka-wu/magpie-plugin-ohmygame.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/mizuka-wu/magpie-plugin-ohmygame/issues"
21
+ },
22
+ "homepage": "https://github.com/mizuka-wu/magpie-plugin-ohmygame#readme",
23
+ "type": "module",
24
+ "main": "./index.mjs",
25
+ "exports": {
26
+ "./server": "./index.mjs",
27
+ ".": "./index.mjs"
28
+ },
29
+ "files": [
30
+ "index.mjs",
31
+ "ohmygame.agent.mjs",
32
+ "assets/ohmygame.svg",
33
+ "lib/ohmygame-agent.mjs",
34
+ "lib/pi-models.mjs",
35
+ "lib/ohmygame-connection-store.mjs",
36
+ "lib/ohmygame-mcp.mjs",
37
+ "lib/ohmygame-provider.mjs",
38
+ "README.md"
39
+ ],
40
+ "scripts": {
41
+ "test": "node --test",
42
+ "prepublishOnly": "npm test"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "magpie": {
48
+ "name": "Oh My Game",
49
+ "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9Ik9oTXlHYW1lIj4KICA8ZGVmcz4KICAgIDxsaW5lYXJHcmFkaWVudCBpZD0iYmciIHgxPSIwIiB5MT0iMCIgeDI9IjEiIHkyPSIxIj4KICAgICAgPHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNThlM2I3Ii8+CiAgICAgIDxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iIzE4NzdmMiIvPgogICAgPC9saW5lYXJHcmFkaWVudD4KICAgIDxsaW5lYXJHcmFkaWVudCBpZD0ic2hpbmUiIHgxPSIwIiB5MT0iMCIgeDI9IjAiIHkyPSIxIj4KICAgICAgPHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjZmZmIiBzdG9wLW9wYWNpdHk9Ii44MiIvPgogICAgICA8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNmZmYiIHN0b3Atb3BhY2l0eT0iLjEyIi8+CiAgICA8L2xpbmVhckdyYWRpZW50PgogIDwvZGVmcz4KICA8cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgcng9IjU4IiBmaWxsPSJ1cmwoI2JnKSIvPgogIDxwYXRoIGQ9Ik02NCAxMjhjMC0zNS4zIDI4LjctNjQgNjQtNjRoMzJjMjIgMCA0MCAxOCA0MCA0MHYyOGMwIDMwLjktMjUuMSA1Ni01NiA1Nkg4OGMtMTMuMyAwLTI0LTEwLjctMjQtMjR2LTM2eiIgZmlsbD0idXJsKCNzaGluZSkiLz4KICA8cGF0aCBkPSJNMTAxIDgydjkyTTE1NSA4MnY5MiIgc3Ryb2tlPSIjMTUzYjcwIiBzdHJva2Utd2lkdGg9IjE4IiBzdHJva2UtbGluZWNhcD0icm91bmQiLz4KICA8cGF0aCBkPSJNNzggMTI4aDEwMCIgc3Ryb2tlPSIjMTUzYjcwIiBzdHJva2Utd2lkdGg9IjE4IiBzdHJva2UtbGluZWNhcD0icm91bmQiLz4KICA8Y2lyY2xlIGN4PSIxMDEiIGN5PSIxMjgiIHI9IjExIiBmaWxsPSIjMTUzYjcwIi8+CiAgPGNpcmNsZSBjeD0iMTU1IiBjeT0iMTI4IiByPSIxMSIgZmlsbD0iIzE1M2I3MCIvPgogIDxjaXJjbGUgY3g9IjEwMSIgY3k9IjE3NCIgcj0iMTEiIGZpbGw9IiMxNTNiNzAiLz4KICA8Y2lyY2xlIGN4PSIxNTUiIGN5PSIxNzQiIHI9IjExIiBmaWxsPSIjMTUzYjcwIi8+CiAgPHBhdGggZD0iTTg3IDIwNWg4MiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjEyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIG9wYWNpdHk9Ii43Ii8+Cjwvc3ZnPgo=",
50
+ "agent": "./ohmygame.agent.mjs"
51
+ }
52
+ }