cowork 0.1.0: Tuanjie Cowork on magpie's Agents page (#239)
Adds @magpie-community/agent-cowork 0.1.0 (Tuanjie Cowork on magpie's Agents page) and its registry entry. The agent writes the one key defaultChatModelTitle in ~/.codely/ide-settings.json. seed.mjs copies magpie's catalog into Cowork's store, and prunes, relabels and removes only the entry ids recorded in settings.json.magpie-seeded.
Re-reviewed at cbe10c949940b75c6ac2b4cdcc2fe9a92ae6830c against the three earlier change requests (items 1-8, adoption by address, prune hold, relabel and selection).
What was run at cbe10c949940b75c6ac2b4cdcc2fe9a92ae6830c (it merges cleanly onto main b074782):
- bun test packages/cowork: 50 pass. node --test: 50 pass. node scripts/mutate.mjs: all mutations caught. bun scripts/check.mjs cowork: exit 0.
- seed.mjs in a sandbox HOME against a fake /v1/models on a random port, with the owner's fixture: custom-provider (a/one "One on my endpoint"), a user provider my-magpie at magpie's address (a/two "My Two", my-local "My Local"), and defaultChatModelTitle "My Two".
- First run: +1 (a/three). Neither of the user's entries was touched or renamed. The record holds only magpie:a/three, and the selection is unchanged.
- A user-added magpie:my-own survived seeding, --prune and --remove ("left 1 you added under it yourself").
- Catalog shrunk to [a/one] with a/three selected: plain run held the entry ("pass --prune"), --check reported "1 held". --prune dropped a/four but kept the selected a/three.
- An unreadable ide-settings.json makes the run refuse to write anything (exit 2).
- magpie (main 4dfd88206) in a sandbox via scripts/try.sh: magpie ls lists Tuanjie Cowork. magpie cowork fakeco/fake-model wrote only defaultChatModelTitle. magpie cowork default restored the file byte for byte.
Not run: Cowork itself (Windows). The author sent a real message through Cowork on magpie at 92c9b22 and d79a60f (logs quoted in the PR).
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 cuddlesgiggles
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,123 @@
|
||||
# magpie-agent-cowork
|
||||
|
||||
把 **团结 Cowork**(Tuanjie Cowork,本地 agent 是 `codely.exe`)接成 magpie 的一个 agent:
|
||||
在 magpie 里给 Cowork 选一个模型,Cowork 就用 magpie 网关上那个模型说话——用的是你已经在
|
||||
magpie 里登进去的那些订阅的额度,Cowork 自己不用另登录。
|
||||
|
||||
```
|
||||
magpie cowork workbuddy/deepseek-v4.1-flash # 换 Cowork 的聊天模型
|
||||
magpie cowork # 看它现在用哪个
|
||||
magpie cowork default # 把 Cowork 交还给它自己原来的选择
|
||||
```
|
||||
|
||||
装:
|
||||
|
||||
```sh
|
||||
magpie plugin add @magpie-community/agent-cowork
|
||||
```
|
||||
|
||||
`seed.mjs` 需要 Node 18 以上(用了顶层 await 和全局 `fetch`),magpie 自己带的那套不影响它。
|
||||
机器上没有 `node` 就用 Cowork 自带的那个——它不在 PATH 上,位置跟着安装目录变:
|
||||
|
||||
```sh
|
||||
"<安装目录>\cli\bin\win32-x64\node.exe" seed.mjs
|
||||
```
|
||||
|
||||
## 适用前提
|
||||
|
||||
这个包读的是 Windows 上 Cowork 桌面应用的存储布局,键名出自安装包 2026-10-14 那一版。成立的前提是三条:
|
||||
|
||||
- **Cowork 的主目录在默认位置 `~/.codely`。** 设置里的 Codely Home Location 能把它搬走,搬成功时 Cowork 把
|
||||
新位置写进系统环境变量 `CODELY_CLI_HOME`。`seed.mjs` 跟着这个变量走,但只认里面有 `ide-settings.json` 的
|
||||
目录——终端 `codely` 自己那份 `~/.codely-cli` 没有它,指过去就是把清单写进没人读的库。两个候选都不像
|
||||
Cowork 的家时它停住报错、不替你新建;硬指用 `--store <主目录>/settings.json`。**插件那一半没有这个余地**:
|
||||
`cowork.agent.js` 的 `config` 写死在 `~/.codely/ide-settings.json`,只跟着用户主目录,agent 契约也不允许
|
||||
一个插件写第二个文件。所以搬过主目录的机器上 `magpie cowork <模型>` 写的文件 Cowork 读不到、切换静默失效——
|
||||
这类机器用 `seed.mjs` 搬清单、在 Cowork 里点模型;要还能用命令行切,就把主目录搬回默认位置。
|
||||
- **管的是桌面应用,不是终端里的 `codely`。** 后者用 `~/.codely-cli`,模型记在 `model-config.json`,文件和
|
||||
形状都和桌面应用不一样,本插件不动它。
|
||||
- **Windows。** macOS、Linux 上这三份文件放在哪没有依据;其它版本的 Cowork 也没有依据说键名仍是
|
||||
`defaultChatModelTitle` / `customModels` / `customModelProviders`。
|
||||
|
||||
## 先跑一次 seed
|
||||
|
||||
Cowork 的模型清单在 `~/.codely/settings.json`,它当前用哪个模型记在 `~/.codely/ide-settings.json`
|
||||
的 `defaultChatModelTitle`。这个值是清单里那条模型的**名字**(`displayName`),不是请求体里的 `model`
|
||||
字符串——所以 `seed.mjs` 把它写进清单的每条模型都用模型 id 当名字,否则 `magpie cowork <模型>` 写进去
|
||||
的字符串 Cowork 认不出来,会静默退回原来的模型。
|
||||
|
||||
改名只发生在**它记录的条目**上:某条是它写的、你后来在 Cowork 里换了名字,下次 seed 会把名字改回模型
|
||||
id(不改的话 `magpie cowork <模型 id>` 选不中它);如果这条正好是 Cowork 当前选中的,`defaultChatModelTitle`
|
||||
在同一次运行里跟着改成新的名字,不留悬空选择,输出也会说明。记录里没有的条目——你自己加的、自己起名的,
|
||||
包括你在 `magpie` 那家 provider 下自己加的——一个字都不改。`ide-settings.json` 读不出来时它整次停住
|
||||
(退出码 2),不会把「读不到」当成「没选」再去改名或删条目。
|
||||
|
||||
插件本身只维护 `ide-settings.json` 这一个文件——magpie 的 agent 插件按契约只能碰一个配置文件,
|
||||
而清单那个文件里是数组,magpie 的写入器碰到 `customModels: []` 会写成 `{"0": {…}}`,Cowork 读不了。
|
||||
所以模型清单由包里的 `seed.mjs` 从 magpie 的 `/v1/models` 一次性搬过去。装完之后它在 magpie 的插件目录
|
||||
`~/.config/magpie/plugins/node_modules/@magpie-community/agent-cowork/`(设了 `XDG_CONFIG_HOME` 的把
|
||||
`~/.config` 换成它):
|
||||
|
||||
```sh
|
||||
cd ~/.config/magpie/plugins/node_modules/@magpie-community/agent-cowork
|
||||
node seed.mjs # 第一次写之前把原文件留成 settings.json.pre-magpie,只留这一次
|
||||
node seed.mjs --check # 只报漂移,不写;有漂移(含被扣下的条目)时退出码 1
|
||||
node seed.mjs --prune # 允许删掉记录里已不在 magpie 目录中的条目(见下)
|
||||
node seed.mjs --remove # 摘掉记录里属于本包的条目;那家 provider 只在没人用时才删
|
||||
```
|
||||
|
||||
**跑之前先退出 Cowork。** `ide-settings.json` 有两个写者:magpie 切模型时写它,Cowork 自己在运行中也会
|
||||
写回它。Cowork 开着的时候切模型,它下一次保存就可能
|
||||
把刚写进去的名字盖回去。所以:退了 Cowork 再 seed,切完模型再启动;已经在开着的情况下切过,就
|
||||
`cat` 一下确认那个名字还在。
|
||||
|
||||
**它只动自己写过的东西**:哪些条目是它写的记在同目录的 `settings.json.magpie-seeded`(一个 entry id
|
||||
数组)。改名、删除与 `--remove` 要同时满足两条——那条在这份记录里,**且**它挂在包自己建的那家
|
||||
`magpie` provider 下。你自己的 provider 就算地址也填的 magpie、就算被旧版记录误认领过,也不会被删、
|
||||
也不会被改名;你手动加在 `magpie` 那家下面、名字自己起的条目同样不在记录里,`--prune` 和 `--remove`
|
||||
都不碰。记录丢了但 `settings.json.pre-magpie` 还在(= 我们确实写过这个库)时,`seed.mjs` 会按形状
|
||||
认领一次:只认挂在 `magpie` 下、名字正好等于模型 id、而且 magpie 现在仍提供的条目;`--remove` 在
|
||||
记录缺失时不猜,会要求先跑一次 `seed.mjs` 把记录补回来。**卸掉插件不会自动跑 `--remove`**——magpie
|
||||
没有这个钩子,卸完要自己跑一次,否则那家 provider 和它下面的 magpie 条目会留在 Cowork 里。
|
||||
|
||||
**这类模型不认模型 id**:某个模型在 Cowork 里的条目名字不是模型 id(通常是它只存在于你自己的 provider 下、
|
||||
名字还是你起的)。`magpie cowork <模型 id>` 写进去的是 id,而 Cowork 按它显示的名字找条目,找不到就退回
|
||||
原来的模型(不报错)。seed 会列出它们:能当参数的给出 `magpie cowork "<名字>"`;名字里带 `/`(会被
|
||||
magpie 当成 `供应商/模型` 去校验)、以 `-` 开头(会被当成 flag)、或者正好叫 `default`(会把 agent
|
||||
复位)的,则让你回 Cowork 里点。能传的名字直接用 Cowork 显示的名字切,例如
|
||||
`magpie cowork "GLM-5.3-Flash · zcode"`——magpie 对不在目录里的写法是原样写入的;只有形如
|
||||
`供应商/模型` 的写法会被当成目录引用去校验(供应商是 magpie 的 provider、模型又不在目录里就报错),
|
||||
其余字符串照写。带 `/` 的名字就在 Cowork 里选,或者在 `magpie` 那家 provider 下加一条以模型 id
|
||||
命名的条目。
|
||||
|
||||
**目录里没有的条目不删**:magpie 的目录会因为某个账号正在恢复、magpie 刚启动而临时变短,照着删就会
|
||||
删掉你正在用的那条。所以记录里有、当前目录里没有的条目一律先留着,只报
|
||||
`N recorded entries aren't in the catalog right now; pass --prune to drop them`;`--check` 仍把它算作
|
||||
漂移(退出码 1)。要删请显式加 `--prune`;就算加了,`defaultChatModelTitle` 指的那一条也永远不删。
|
||||
`--remove` 如果正好摘掉 Cowork 当前选中的模型,会明确说出来,你在 Cowork 里重选一个即可。
|
||||
|
||||
搬完之后,magpie 自己那批条目用 `magpie cowork <模型 id>` 就能直接切,不用回 Cowork 的模型列表里点;
|
||||
你自己 provider 下的条目用它们显示的名字切(见上)。
|
||||
|
||||
**这一步得你手动跑,而且目录变了要再跑**:agent 插件按契约只能写 Cowork 的一个配置文件,模型清单在
|
||||
另一个文件里、还是数组,插件搬不了。magpie 的目录本身会变,所以 `--check` 留了个能用退出码判断的
|
||||
口子——目录新增、有被扣下的条目、provider 地址变了都算漂移,退 1;文件读不出来退 2 且不写。挂个
|
||||
定时任务就行。**没搬进去的模型不会报错**:用 `magpie cowork <模型 id>` 切到它,title 写进去了,但
|
||||
Cowork 找不到同名条目,会退回自己原来的模型。这是这条路线最难看的一点,目前只能靠「切之前先
|
||||
`--check`」避开。
|
||||
|
||||
改动生效的时机:Cowork 启动时读这个文件,所以重启 Cowork 或新开一个会话才用新模型。
|
||||
|
||||
## 装完怎么确认
|
||||
|
||||
```sh
|
||||
magpie ls # 应当有一行 Tuanjie Cowork,右边是它当前的模型和配置路径
|
||||
magpie cowork <某个模型>
|
||||
cat ~/.codely/ide-settings.json # defaultChatModelTitle 应当已经变成那个模型(搬过主目录的看那个目录)
|
||||
```
|
||||
|
||||
然后在 Cowork 里发一句话,回话应当来自那个模型。若它回的是别的模型,说明那个名字在 Cowork 的清单里
|
||||
没有对应条目——再跑一次 `node seed.mjs`。
|
||||
|
||||
图标取自 Cowork 安装包里的 `app/resource/dist/branding/logo_dark.png`,缩到 112px 后内联成 data URI
|
||||
(和 `@magpie-community/agent-kimi-desktop` 一样的做法,好处是不依赖仓库先建好),同图另存一份 `icon.png` 随包发。
|
||||
@@ -0,0 +1,19 @@
|
||||
// 团结 Cowork starts a session on the model named by defaultChatModelTitle in
|
||||
// ~/.codely/ide-settings.json — the model's own string, which is also what it
|
||||
// puts in the request body. magpie keeps that one field in step, so the model
|
||||
// changes without opening Cowork's picker. The models have to exist in Cowork's
|
||||
// store (~/.codely/settings.json) first; `node seed.mjs` in this package puts
|
||||
// them there from magpie's catalog, because magpie's own writer can only reach
|
||||
// one file per agent and would turn an empty customModels list into an object.
|
||||
export const agent = {
|
||||
id: "cowork",
|
||||
name: "Tuanjie Cowork",
|
||||
// the app icon, straight out of the vendor package (branding/logo_dark.png), shrunk to 112px
|
||||
icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHAAAABwCAYAAADG4PRLAAANlElEQVR42u2de3wV1RHHv7t7SUiAJISIiFaRWoEqUCpUKCJPofLQVoFWQYUKWK1iQeRRS1HbKqhg8UlFECxQLKLWQosoUKQUxWd9K9IqVkElkJCQQJLd0z9ml7tcQl537ys58/ns55N7cx97z+/M/GbmnDkDWrRo0aJFixYtWrRo0aKlIYlRj3+bGfHY0XCnzqS0KnnequcTtl6IH7gzgVXAcqDNcV6jJYmA87QrG7gdKAKUe+0DbgGa+LTU1MOWHDzn16grgY99wFW4l/f4PWCkNqvJwXMh3+PzgE0+oMpdp8V77EQAuQ7o5nt/SAOZGJ5rAyzygVUB2D6gIi/b9/9y4EGgtebH+JlLj7cygRkut1WmYdVd/tfuAX4BpFXyPVpiEBZcCrx7HDBqc0WC/iYwTJvV2PFcV+BvEcA5dQSvKiCfBjprsxocz50E3O9yViSPBXn5P/cQcBeQp4GsO881Am50OSpac6nqyI+7gGt892RpfqwZzw0FXouBuayrWd0GDND8WL257Ag8mUDgqgNyuZui02Y14se3cDmnNMY8Fw0/ehPpgJuqy64med4g0l8mMB74NM48FwQ/fuym7mgo/Bg5U/sBW6tIfyXr5fg8YuWm8HrWd370A/ctYFnErLZTALjKzGqFD9RH6+OylembjVnALKDQ96ODAc4wFJZZ89dbprwnOLPq+JatprmpvpROy0Way1HAjpjwXG2AC/K9VfPjO8DwVFy2ikx/9QReiElYYJoK09Wi9DTFLyco+ncP/6+y14NiaG/FlLEKy/J9jhmrsGOtmwJMCSD9Gncq8IdaLPPU0lxa4cfD+io2P65QHyh+2N/VLKsSbXOfu+IihfpI8fwix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1i3D64VektrjuZxm8OlumP9HWLza3V9jHm1Sg+M5XDM5yzWb+E7sTZIgpOaNPy4nHo0/Tmml+P0MOcW+4GXFrg2KXRsVB15R7H5RMecmxYl5uvFHFK13biVmrXd87QLO7aR45gFF0avSluCJuYouHSJ6RBCL1jv51JPWO7VtfuXEpIfS5UMUwwfGsrlHvW9+lZj2c5GtdAwj6PY6Da79XFUNICcQqwaQlhVLntsBXNGQGkBWZlaNiBasJSnUgjUrwvNG99KFs4HVSdwEeQW6CXJKtiH/V0Qbcku3Ia++E1oj4EY3exHPBsn+79gFXOO7J0vXVNberJ6E9N8rjzE/+j/3EHA3kKfNZXDdQLsCf49B2BFpLp8COmngYsePw4F3AzCrkcC94XKv5rk48GMmMN1NXdWlU6j/tXuASUB6fUt/pQI/nob0L6xpT/rI3rYPAidrc5l4fjzPTWkdjx8j01/rgG4NKf2VCmk5gCuBjyM00m8u3wNGap5L7rRcNvAboMgH3D7gFt8yj6F5Lvn5sR2wClm6aqN5LnXDjnptLo0GdJSmo+e2Fi1atGjRokWLFi1atGhJdfk//sgkKiQwVuwAAAAASUVORK5CYII=",
|
||||
config: "~/.codely/ide-settings.json",
|
||||
format: "json",
|
||||
model: "defaultChatModelTitle",
|
||||
// Cowork has no command on PATH; the profile folder its agent writes says it is installed
|
||||
dir: "~/.codely",
|
||||
notice: "Cowork reads this when it starts / Cowork 启动时读取,重启或新开一个会话才用新模型。",
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.5 KiB |
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "@magpie-community/agent-cowork",
|
||||
"version": "0.1.0",
|
||||
"description": "Tuanjie Cowork (codely) as a magpie agent: magpie cowork <model> switches the model it chats with",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"cowork.agent.js",
|
||||
"seed.mjs",
|
||||
"icon.png",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"keywords": [
|
||||
"magpie",
|
||||
"magpie-agent",
|
||||
"magpie-plugin",
|
||||
"cowork",
|
||||
"tuanjie",
|
||||
"codely",
|
||||
"llm-gateway"
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/cowork"
|
||||
},
|
||||
"magpie": {
|
||||
"agent": "./cowork.agent.js",
|
||||
"icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHAAAABwCAYAAADG4PRLAAANlElEQVR42u2de3wV1RHHv7t7SUiAJISIiFaRWoEqUCpUKCJPofLQVoFWQYUKWK1iQeRRS1HbKqhg8UlFECxQLKLWQosoUKQUxWd9K9IqVkElkJCQQJLd0z9ml7tcQl537ys58/ns55N7cx97z+/M/GbmnDkDWrRo0aJFixYtWrRo0aKlIYlRj3+bGfHY0XCnzqS0KnnequcTtl6IH7gzgVXAcqDNcV6jJYmA87QrG7gdKAKUe+0DbgGa+LTU1MOWHDzn16grgY99wFW4l/f4PWCkNqvJwXMh3+PzgE0+oMpdp8V77EQAuQ7o5nt/SAOZGJ5rAyzygVUB2D6gIi/b9/9y4EGgtebH+JlLj7cygRkut1WmYdVd/tfuAX4BpFXyPVpiEBZcCrx7HDBqc0WC/iYwTJvV2PFcV+BvEcA5dQSvKiCfBjprsxocz50E3O9yViSPBXn5P/cQcBeQp4GsO881Am50OSpac6nqyI+7gGt892RpfqwZzw0FXouBuayrWd0GDND8WL257Ag8mUDgqgNyuZui02Y14se3cDmnNMY8Fw0/ehPpgJuqy64med4g0l8mMB74NM48FwQ/fuym7mgo/Bg5U/sBW6tIfyXr5fg8YuWm8HrWd370A/ctYFnErLZTALjKzGqFD9RH6+OylembjVnALKDQ96ODAc4wFJZZ89dbprwnOLPq+JatprmpvpROy0Way1HAjpjwXG2AC/K9VfPjO8DwVFy2ikx/9QReiElYYJoK09Wi9DTFLyco+ncP/6+y14NiaG/FlLEKy/J9jhmrsGO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id/ZCWL81VjznTe5yYAFwhwtiMMdzxgBAf39229d24Dagv29GmoF8r2cyHUdWDiaMkFWE1i3D64VektrjuZxm8OlumP9HWLza3V9jHm1Sg+M5XDM5yzWb+E7sTZIgpOaNPy4nHo0/Tmml+P0MOcW+4GXFrg2KXRsVB15R7H5RMecmxYl5uvFHFK13biVmrXd87QLO7aR45gFF0avSluCJuYouHSJ6RBCL1jv51JPWO7VtfuXEpIfS5UMUwwfGsrlHvW9+lZj2c5GtdAwj6PY6Da79XFUNICcQqwaQlhVLntsBXNGQGkBWZlaNiBasJSnUgjUrwvNG99KFs4HVSdwEeQW6CXJKtiH/V0Qbcku3Ia++E1oj4EY3exHPBsn+79gFXOO7J0vXVNberJ6E9N8rjzE/+j/3EHA3kKfNZXDdQLsCf49B2BFpLp8COmngYsePw4F3AzCrkcC94XKv5rk48GMmMN1NXdWlU6j/tXuASUB6fUt/pQI/nob0L6xpT/rI3rYPAidrc5l4fjzPTWkdjx8j01/rgG4NKf2VCmk5gCuBjyM00m8u3wNGap5L7rRcNvAboMgH3D7gFt8yj6F5Lvn5sR2wClm6aqN5LnXDjnptLo0GdJSmo+e2Fi1atGjRokWLFi1atGhJdfk//sgkKiQwVuwAAAAASUVORK5CYII="
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node --test",
|
||||
"mutate": "node scripts/mutate.mjs",
|
||||
"seed": "node seed.mjs"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
// Every mutation of the package has to turn a test red. If one stays green,
|
||||
// that test was never checking anything.
|
||||
import { cpSync, mkdirSync, rmSync, readFileSync, writeFileSync } from "node:fs"
|
||||
import { join, dirname } from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { spawnSync } from "node:child_process"
|
||||
|
||||
const SRC = dirname(dirname(fileURLToPath(import.meta.url)))
|
||||
const SCRATCH = join(dirname(SRC), ".mut-cowork")
|
||||
|
||||
const MUTATIONS = [
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (taken.has(m.id)) continue",
|
||||
to: "if (false) continue",
|
||||
why: "adds a catalog model Cowork already has, so two entries share one title",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const droppable = models.filter((m) => m && m.providerId === PROVIDER_ID && seeded.has(m.id) && !ids.has(m.model) &&",
|
||||
to: "const droppable = models.filter((m) => m && seeded.has(m.id) && !ids.has(m.model) &&",
|
||||
why: "prunes a model under the user's own provider because a stale record named it",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const droppable = models.filter((m) => m && m.providerId === PROVIDER_ID && seeded.has(m.id) && !ids.has(m.model) &&",
|
||||
to: "const droppable = models.filter((m) => m && m.providerId === PROVIDER_ID && !ids.has(m.model) &&",
|
||||
why: "prunes every magpie entry missing from the catalog, including ones the user added",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const pruned = opts.prune ? droppable.map((m) => m.id) : []",
|
||||
to: "const pruned = droppable.map((m) => m.id)",
|
||||
why: "a catalog that is short for a moment empties the picker without --prune",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "m.id !== selected && m.model !== selected && m.displayName !== selected",
|
||||
to: "true",
|
||||
why: "prunes the model Cowork is on right now, which falls back silently",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!m || m.providerId !== PROVIDER_ID || !seeded.has(m.id) || m.displayName === m.model) return m",
|
||||
to: "return m",
|
||||
why: "leaves a pretty label as the picker title, so the string magpie writes matches nothing",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!m || m.providerId !== PROVIDER_ID || !seeded.has(m.id) || m.displayName === m.model) return m",
|
||||
to: "if (!m || m.displayName === m.model) return m",
|
||||
why: "renames entries the user named, dangling their saved selection",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!m || m.providerId !== PROVIDER_ID || !seeded.has(m.id) || m.displayName === m.model) return m",
|
||||
to: "if (!m || m.providerId !== PROVIDER_ID || m.displayName === m.model) return m",
|
||||
why: "renames an entry of theirs that an old record still lists",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (at === -1) providers.push(provider(baseUrl))",
|
||||
to: "if (false) providers.push(provider(baseUrl))",
|
||||
why: "never adds the provider that points Cowork at magpie",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "supportsMultimodal: !!(m.modalities && (m.modalities.input || []).includes(\"image\")),",
|
||||
to: "supportsMultimodal: false,",
|
||||
why: "tells Cowork no magpie model takes images",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "roles: [\"model\"],",
|
||||
to: "roles: [],",
|
||||
why: "drops the role Cowork's own store gives every usable model",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "return v && !v.startsWith(\"--\") ? v : dflt",
|
||||
to: "return v ? v : dflt",
|
||||
why: "reads the next flag as --gateway's value, so it fetches --check/v1/models",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const ours = (m) => m && m.providerId === PROVIDER_ID && seeded.has(m.id)",
|
||||
to: "const ours = (m) => m && seeded.has(m.id)",
|
||||
why: "--remove eats what the user made in Cowork, because the record predates the fix",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "return existsSync(storePath) && !existsSync(bakPath)",
|
||||
to: "return existsSync(storePath)",
|
||||
why: "a second run overwrites the original store with an already-seeded one",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "displayName: m.id,",
|
||||
to: "displayName: m.magpie_label || m.id,",
|
||||
why: "same, for the entries the package adds itself",
|
||||
},
|
||||
{
|
||||
file: "cowork.agent.js",
|
||||
from: "icon: \"data:image/png;base64,",
|
||||
to: "icon: \"data:image/jpeg;base64,",
|
||||
why: "ships the icon under a mime the Agents page won't render",
|
||||
},
|
||||
{
|
||||
file: "cowork.agent.js",
|
||||
from: "model: \"defaultChatModelTitle\",",
|
||||
to: "model: \"chatModelTitle\",",
|
||||
why: "writes a field name Cowork never reads",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const candidates = env.CODELY_CLI_HOME ? [at(env.CODELY_CLI_HOME), join(home, \".codely\")] : [join(home, \".codely\")]",
|
||||
to: "const candidates = [join(home, \".codely\")]",
|
||||
why: "seeds the old place after the user moved Cowork's home, so nothing ever sees the models",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "return candidates.find((d) => existsSync(join(d, \"ide-settings.json\"))) || candidates[candidates.length - 1]",
|
||||
to: "return candidates[0]",
|
||||
why: "takes the terminal CLI's own home for Cowork's, because a stale CODELY_CLI_HOME points there",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!storeFlag && (!existsSync(home) || (!existsSync(storePath) && !existsSync(titlePath)))) {",
|
||||
to: "if (false) {",
|
||||
why: "invents a Cowork home and still prints a success line",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "(!existsSync(storePath) && !existsSync(titlePath))",
|
||||
to: "(!existsSync(storePath) || !existsSync(titlePath))",
|
||||
why: "refuses the first store in a home Cowork did create",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const storePath = storeFlag ? expand(storeFlag) : join(home, \"settings.json\")",
|
||||
to: "const storePath = storeFlag ? expand(storeFlag) : join(homedir(), \".codely\", \"settings.json\")",
|
||||
why: "works out the home and then throws the answer away",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!storeFlag) console.log(`store: ${storePath}`)",
|
||||
to: "if (false) console.log(storePath)",
|
||||
why: "seeds a home the user never asked for and never says which one it picked",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "return here.length > 0 && !here.some((x) => (x.displayName ?? x.model) === m.id || (x.providerId === PROVIDER_ID && seeded.has(x.id)))",
|
||||
to: "return false",
|
||||
why: "a switch to a model only under the user's provider falls back in silence again",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "return here.length > 0 && !here.some((x) => (x.displayName ?? x.model) === m.id || (x.providerId === PROVIDER_ID && seeded.has(x.id)))",
|
||||
to: "return here.length > 0 && !here.some((x) => (x.displayName ?? x.model) === m.id)",
|
||||
why: "scolds an entry the same run puts back on its id",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!rows.length) return \"\"",
|
||||
to: "return \"\"",
|
||||
why: "works the list out and then never tells anyone",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: ".filter((m) => m && m.providerId === PROVIDER_ID && m.displayName === m.model && ids.has(m.model))",
|
||||
to: ".filter((m) => m && m.providerId === PROVIDER_ID && ids.has(m.model))",
|
||||
why: "adoption claims an entry the user renamed, so --remove would take it out",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: ".filter((m) => m && m.providerId === PROVIDER_ID && m.displayName === m.model && ids.has(m.model))",
|
||||
to: ".filter((m) => m && m.providerId === PROVIDER_ID && m.displayName === m.model)",
|
||||
why: "adoption claims a model magpie no longer offers, making a stale entry ours to prune",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "} catch {\n return { ok: false, value: null }",
|
||||
to: "} catch {\n return { ok: true, value: null }",
|
||||
why: "an unreadable selection looks like no selection, so it can be renamed or pruned",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!ide || typeof ide !== \"object\" || Array.isArray(ide)) return { ok: false, value: null }",
|
||||
to: "if (false) return { ok: false, value: null }",
|
||||
why: "a selection file that is a list or scalar is read as no selection",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (title != null && typeof title !== \"string\") return { ok: false, value: null }",
|
||||
to: "if (false) return { ok: false, value: null }",
|
||||
why: "a non-string title is compared against entry names and never matches",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!store || typeof store !== \"object\" || Array.isArray(store)) {",
|
||||
to: "if (false) {",
|
||||
why: "a store JSON that isn't an object crashes or is spread into a new file",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const cliable = (name) => Boolean(name) && name !== \"default\" && !name.startsWith(\"-\") && !name.includes(\"/\")",
|
||||
to: "const cliable = (name) => Boolean(name) && name !== \"default\" && !name.startsWith(\"-\")",
|
||||
why: "suggests a provider/model name as a bare argument, which magpie reads as a reference",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const cliable = (name) => Boolean(name) && name !== \"default\" && !name.startsWith(\"-\") && !name.includes(\"/\")",
|
||||
to: "const cliable = (name) => Boolean(name) && !name.startsWith(\"-\") && !name.includes(\"/\")",
|
||||
why: "suggests \"default\" as a model name, which resets the agent",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const cliable = (name) => Boolean(name) && name !== \"default\" && !name.startsWith(\"-\") && !name.includes(\"/\")",
|
||||
to: "const cliable = (name) => Boolean(name) && name !== \"default\" && !name.includes(\"/\")",
|
||||
why: "suggests a name with a leading dash, which magpie reads as a flag",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const drift = added.length > 0 || droppable.length > 0 || relabeled > 0 || providerMissing || providerMoved",
|
||||
to: "const drift = added.length > 0 || relabeled > 0 || providerMissing || providerMoved",
|
||||
why: "--check calls a store in step while --prune would still drop entries from it",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "process.exit(drift ? 1 : 0)",
|
||||
to: "process.exit(changed ? 1 : 0)",
|
||||
why: "--check exits 0 while a recorded entry is missing from the catalog",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const before = at === -1 ? null : providers[at]",
|
||||
to: "const before = null",
|
||||
why: "a provider that points at an old gateway is reported as in step",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const selected = readTitle()\n if (!selected.ok) {",
|
||||
to: "const selected = readTitle()\n if (false) {",
|
||||
why: "writes the store while Cowork's selection can't be read",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (adopt) {\n console.error(`no ${listPath}",
|
||||
to: "if (false) {\n console.error(`no ${listPath}",
|
||||
why: "--remove guesses from a missing record instead of refusing",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (adopted) writeList(nextSeeded)",
|
||||
to: "if (false) writeList(nextSeeded)",
|
||||
why: "a rebuilt record is never saved, so a later --remove refuses forever",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!Array.isArray(store.customModels) && \"customModels\" in store) {",
|
||||
to: "if (false) {",
|
||||
why: "writes over a customModels Cowork (or another agent) mangled into an object",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (!Array.isArray(store.customModelProviders) && \"customModelProviders\" in store) {",
|
||||
to: "if (false) {",
|
||||
why: "replaces a mangled provider list and drops providers the user made",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "} else if (selected.value && gone.some((m) => [m.displayName, m.model, m.id].includes(selected.value))) {",
|
||||
to: "} else if (false) {",
|
||||
why: "--remove takes out the model Cowork is on without saying why it will fall back",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "const held = droppable.filter((m) => !pruned.includes(m.id)).map((m) => m.id)",
|
||||
to: "const held = []",
|
||||
why: "records that --prune would drop something but never says so",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (seeded === null && existsSync(listPath)) {",
|
||||
to: "if (false) {",
|
||||
why: "guesses after an unreadable record instead of stopping",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (adopt) {\n seeded = adoptSeeded(store, catalog)",
|
||||
to: "if (false) {\n seeded = adoptSeeded(store, catalog)",
|
||||
why: "skips rebuilding a missing record, so its entries are never managed again",
|
||||
},
|
||||
{
|
||||
file: "seed.mjs",
|
||||
from: "if (m.displayName === selected) renamed = m.model",
|
||||
to: "if (false) renamed = m.model",
|
||||
why: "renames the entry Cowork is on and leaves the selection pointing at the old name",
|
||||
},
|
||||
]
|
||||
|
||||
rmSync(SCRATCH, { recursive: true, force: true })
|
||||
mkdirSync(SCRATCH, { recursive: true })
|
||||
for (const f of ["package.json", "cowork.agent.js", "seed.mjs", "test"]) {
|
||||
cpSync(join(SRC, f), join(SCRATCH, f), { recursive: true })
|
||||
}
|
||||
|
||||
let loose = 0
|
||||
for (const m of MUTATIONS) {
|
||||
const p = join(SCRATCH, m.file)
|
||||
const original = readFileSync(p, "utf8")
|
||||
if (!original.includes(m.from)) {
|
||||
console.log(`ANCHOR GONE ${m.file}: ${m.from}`)
|
||||
loose++
|
||||
continue
|
||||
}
|
||||
writeFileSync(p, original.replace(m.from, m.to), "utf8")
|
||||
const r = spawnSync(process.execPath, ["--test"], { cwd: SCRATCH, encoding: "utf8" })
|
||||
const red = r.status !== 0
|
||||
if (!red) loose++
|
||||
console.log(`${red ? "RED " : "GREEN (no guard!)"} ${m.file}: ${m.why}`)
|
||||
writeFileSync(p, original, "utf8")
|
||||
}
|
||||
rmSync(SCRATCH, { recursive: true, force: true })
|
||||
console.log(loose ? `\n${loose} mutation(s) survived` : "\nall mutations caught")
|
||||
process.exit(loose ? 1 : 0)
|
||||
@@ -0,0 +1,422 @@
|
||||
#!/usr/bin/env node
|
||||
// One-time wiring for Cowork: copy magpie's model catalog into the store Cowork
|
||||
// reads its models from (~/.codely/settings.json). Cowork picks a model by the
|
||||
// name it shows in its list, so the entries written here are named by the magpie
|
||||
// model id — that is the string `magpie cowork <model>` puts in ide-settings.json.
|
||||
// What this package wrote is recorded in a sidecar next to the store: an entry's
|
||||
// `providerId` being "magpie" is not the same question, because a user can add
|
||||
// their own model under that provider in Cowork and nothing entitles us to prune it.
|
||||
import { readFileSync, writeFileSync, existsSync, copyFileSync, renameSync } from "node:fs"
|
||||
import { homedir } from "node:os"
|
||||
import { join, dirname } from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
|
||||
export const PROVIDER_ID = "magpie"
|
||||
|
||||
export function expand(p) {
|
||||
return p.startsWith("~") ? join(homedir(), p.slice(1)) : p
|
||||
}
|
||||
|
||||
// Cowork's home is movable — Settings has a "Codely Home Location" picker that
|
||||
// writes CODELY_CLI_HOME after copying the data — and the terminal `codely` keeps
|
||||
// its own home (~/.codely-cli) whose models live in a different file with a
|
||||
// different shape. ide-settings.json is what marks the desktop app's home, so a
|
||||
// stale CODELY_CLI_HOME pointing at some other directory cannot move a seed into
|
||||
// a store nothing reads.
|
||||
export function codelyHome(env = process.env, home = homedir()) {
|
||||
const at = (p) => (p === "~" ? home : /^~[\\/]/.test(p) ? join(home, p.slice(1)) : p)
|
||||
const candidates = env.CODELY_CLI_HOME ? [at(env.CODELY_CLI_HOME), join(home, ".codely")] : [join(home, ".codely")]
|
||||
return candidates.find((d) => existsSync(join(d, "ide-settings.json"))) || candidates[candidates.length - 1]
|
||||
}
|
||||
|
||||
// The backup records the store once, before this script first writes it; a later
|
||||
// run must not replace it with an already-seeded store.
|
||||
export function backupNeeded(storePath, bakPath) {
|
||||
return existsSync(storePath) && !existsSync(bakPath)
|
||||
}
|
||||
|
||||
// --gateway <url> --store <path>; a flag with no value after it takes the default,
|
||||
// so `--check` on its own is never read as a value.
|
||||
export function opt(argv, name, dflt) {
|
||||
const i = argv.indexOf(`--${name}`)
|
||||
if (i === -1) return dflt
|
||||
const v = argv[i + 1]
|
||||
return v && !v.startsWith("--") ? v : dflt
|
||||
}
|
||||
|
||||
export function provider(baseUrl) {
|
||||
return {
|
||||
id: PROVIDER_ID,
|
||||
name: "magpie",
|
||||
baseUrl,
|
||||
apiKey: "magpie-cowork",
|
||||
authType: "openai",
|
||||
}
|
||||
}
|
||||
|
||||
export function entry(m) {
|
||||
return {
|
||||
id: `${PROVIDER_ID}:${m.id}`,
|
||||
model: m.id,
|
||||
providerId: PROVIDER_ID,
|
||||
// Cowork's picker shows this and stores it as the session's model title, and
|
||||
// the title is the one string magpie's agent plugin can write — so it has to
|
||||
// be the model id, not a prettier label, or the switch lands on nothing.
|
||||
displayName: m.id,
|
||||
authType: "openai",
|
||||
roles: ["model"],
|
||||
wireApi: "chat",
|
||||
contextLength: m.context_length || 8192,
|
||||
supportsMultimodal: !!(m.modalities && (m.modalities.input || []).includes("image")),
|
||||
}
|
||||
}
|
||||
|
||||
export function seedFile(storePath) {
|
||||
return `${storePath}.magpie-seeded`
|
||||
}
|
||||
|
||||
// null: no sidecar to read. An unreadable one is an error the caller refuses on,
|
||||
// because guessing is exactly what drops someone's own model.
|
||||
export function loadSeeded(path) {
|
||||
if (!existsSync(path)) return null
|
||||
try {
|
||||
const ids = JSON.parse(readFileSync(path, "utf8"))
|
||||
return Array.isArray(ids) ? new Set(ids) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// A store written by an older version of this script, before the record existed,
|
||||
// is adopted once: only entries under our own provider, titled by their model id
|
||||
// (the shape this script writes) and still offered by magpie. A provider that
|
||||
// merely points at magpie's address, or an entry the user named themselves, is
|
||||
// not ours to claim.
|
||||
export function adoptSeeded(store, catalog) {
|
||||
const models = Array.isArray(store.customModels) ? store.customModels : []
|
||||
const ids = new Set(catalog.map((m) => m.id))
|
||||
return new Set(models
|
||||
.filter((m) => m && m.providerId === PROVIDER_ID && m.displayName === m.model && ids.has(m.model))
|
||||
.map((m) => m.id))
|
||||
}
|
||||
|
||||
// null means "no selection", not "could not read it": renaming or pruning while
|
||||
// the title is unreadable would leave Cowork pointing at nothing.
|
||||
export function readTitleFile(path) {
|
||||
if (!existsSync(path)) return { ok: true, value: null }
|
||||
try {
|
||||
const ide = JSON.parse(readFileSync(path, "utf8"))
|
||||
if (!ide || typeof ide !== "object" || Array.isArray(ide)) return { ok: false, value: null }
|
||||
const title = ide.defaultChatModelTitle
|
||||
if (title != null && typeof title !== "string") return { ok: false, value: null }
|
||||
return { ok: true, value: title ?? null }
|
||||
} catch {
|
||||
return { ok: false, value: null }
|
||||
}
|
||||
}
|
||||
|
||||
// A value magpie's CLI can write as-is. A slash makes it a provider/model
|
||||
// reference, a leading dash makes it a flag, and "default" resets the agent.
|
||||
const cliable = (name) => Boolean(name) && name !== "default" && !name.startsWith("-") && !name.includes("/")
|
||||
|
||||
// The only words that tell a user their switch will fall back in silence, so they
|
||||
// are worth a test of their own.
|
||||
export function unreachableNote(rows) {
|
||||
if (!rows.length) return ""
|
||||
const byName = rows.filter((r) => cliable(r.name))
|
||||
const inCowork = rows.filter((r) => !cliable(r.name))
|
||||
const parts = [`${rows.length} catalog models are listed under names that aren't the model id —
|
||||
\`magpie cowork <model id>\` won't select those (Cowork matches the name it shows, not the id)`]
|
||||
if (byName.length) {
|
||||
const shown = byName.slice(0, 3).map((r) => `\`magpie cowork ${JSON.stringify(r.name)}\` (${r.id})`).join(", ")
|
||||
parts.push(`pass the name instead: ${shown}${byName.length > 3 ? ", …" : ""}`)
|
||||
}
|
||||
if (inCowork.length) {
|
||||
const shown = inCowork.slice(0, 3).map((r) => `${r.id} (${JSON.stringify(r.name)})`).join(", ")
|
||||
parts.push(`pick these in Cowork instead — a slash or leading dash makes magpie read the name as a reference or a flag, and "default" resets the agent: ${shown}${inCowork.length > 3 ? ", …" : ""}`)
|
||||
}
|
||||
return parts.join(";\n ")
|
||||
}
|
||||
|
||||
// store: Cowork's settings.json object. catalog: magpie's /v1/models data.
|
||||
// seeded: the entry ids this package wrote, from the record. opts.selected is the
|
||||
// model Cowork is on right now, opts.prune allows a shrinking catalog to remove
|
||||
// recorded entries. Nothing passed in is mutated.
|
||||
export function plan(store, catalog, baseUrl, seeded = new Set(), opts = {}) {
|
||||
const models = Array.isArray(store.customModels) ? store.customModels : []
|
||||
const providers = Array.isArray(store.customModelProviders) ? store.customModelProviders.slice() : []
|
||||
const ids = new Set(catalog.map((m) => m.id))
|
||||
const taken = new Set(models.map((m) => m && m.model))
|
||||
const selected = opts.selected ?? null
|
||||
|
||||
// An entry that magpie no longer lists is often a catalog that is momentarily
|
||||
// short — an account resting, magpie starting — and deleting it empties
|
||||
// Cowork's picker. Nothing missing is deleted unless --prune says so; the entry
|
||||
// Cowork is on is never deleted, even then.
|
||||
// A record left by the pre-release commits also named entries under the user's
|
||||
// own provider, because that version claimed models by address. Whatever the
|
||||
// record says, an entry that is not under our provider is not ours to delete.
|
||||
const droppable = models.filter((m) => m && m.providerId === PROVIDER_ID && seeded.has(m.id) && !ids.has(m.model) &&
|
||||
m.id !== selected && m.model !== selected && m.displayName !== selected)
|
||||
const pruned = opts.prune ? droppable.map((m) => m.id) : []
|
||||
const held = droppable.filter((m) => !pruned.includes(m.id)).map((m) => m.id)
|
||||
|
||||
// A catalog model whose entry is shown under another name is not selected by
|
||||
// `magpie cowork <model id>`: that writes the id, and Cowork looks up the name
|
||||
// it displays. Say which they are and the name to pass instead, rather than
|
||||
// letting the switch fall back in silence.
|
||||
const unreachable = catalog.filter((m) => {
|
||||
const here = models.filter((x) => x && x.model === m.id)
|
||||
return here.length > 0 && !here.some((x) => (x.displayName ?? x.model) === m.id || (x.providerId === PROVIDER_ID && seeded.has(x.id)))
|
||||
}).map((m) => ({
|
||||
id: m.id,
|
||||
name: models.find((x) => x && x.model === m.id && x.displayName && x.displayName !== m.id)?.displayName ?? m.id,
|
||||
}))
|
||||
|
||||
let relabeled = 0
|
||||
let renamed = null
|
||||
const dropped = new Set(pruned)
|
||||
const kept = models
|
||||
.filter((m) => !(m && dropped.has(m.id)))
|
||||
.map((m) => {
|
||||
// only entries we wrote, and only ones we recorded: a name the user chose in
|
||||
// Cowork is theirs, and renaming it would leave their selection pointing nowhere
|
||||
if (!m || m.providerId !== PROVIDER_ID || !seeded.has(m.id) || m.displayName === m.model) return m
|
||||
relabeled++
|
||||
if (m.displayName === selected) renamed = m.model
|
||||
return { ...m, displayName: m.model }
|
||||
})
|
||||
const added = []
|
||||
for (const m of catalog) {
|
||||
if (taken.has(m.id)) continue
|
||||
added.push(m.id)
|
||||
kept.push(entry(m))
|
||||
}
|
||||
|
||||
const at = providers.findIndex((p) => p && p.id === PROVIDER_ID)
|
||||
const before = at === -1 ? null : providers[at]
|
||||
if (at === -1) providers.push(provider(baseUrl))
|
||||
else providers[at] = provider(baseUrl)
|
||||
|
||||
const nextSeeded = new Set([...seeded].filter((id) => !pruned.includes(id)))
|
||||
for (const m of catalog) if (added.includes(m.id)) nextSeeded.add(`${PROVIDER_ID}:${m.id}`)
|
||||
const providerMissing = at === -1
|
||||
const providerMoved = before !== null && before.baseUrl !== baseUrl
|
||||
const changed = added.length > 0 || pruned.length > 0 || relabeled > 0 || providerMissing || providerMoved
|
||||
// --check reports drift even when a normal run would write nothing: entries
|
||||
// held back for --prune are still a difference from the catalog.
|
||||
const drift = added.length > 0 || droppable.length > 0 || relabeled > 0 || providerMissing || providerMoved
|
||||
return {
|
||||
next: { ...store, customModels: kept, customModelProviders: providers },
|
||||
added, pruned, held, relabeled, renamed, unreachable, seeded: [...nextSeeded], changed, drift,
|
||||
provider: providerMissing ? "add" : providerMoved ? "repoint" : null,
|
||||
}
|
||||
}
|
||||
|
||||
// The other way: take out exactly the recorded ids that are under our provider,
|
||||
// and the provider only once nothing is left under it.
|
||||
export function unplan(store, seeded = new Set()) {
|
||||
const models = Array.isArray(store.customModels) ? store.customModels : []
|
||||
const providers = Array.isArray(store.customModelProviders) ? store.customModelProviders : []
|
||||
const ours = (m) => m && m.providerId === PROVIDER_ID && seeded.has(m.id)
|
||||
const removed = models.filter(ours).map((m) => m.id)
|
||||
const left = models.filter((m) => !ours(m))
|
||||
const stillOurs = left.some((m) => m && m.providerId === PROVIDER_ID)
|
||||
const nextProviders = stillOurs ? providers : providers.filter((p) => !(p && p.id === PROVIDER_ID))
|
||||
return {
|
||||
next: { ...store, customModels: left, customModelProviders: nextProviders },
|
||||
removed,
|
||||
leftBehind: left.filter((m) => m && m.providerId === PROVIDER_ID).map((m) => m.id),
|
||||
changed: removed.length > 0 || nextProviders.length !== providers.length,
|
||||
}
|
||||
}
|
||||
|
||||
// Importing this file (the tests) must touch nothing: only `node seed.mjs` runs.
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
const argv = process.argv.slice(2)
|
||||
const flag = (n) => argv.includes(`--${n}`)
|
||||
if (flag("help")) {
|
||||
console.log("usage: node seed.mjs [--gateway http://127.0.0.1:3425] [--store <home>/settings.json] [--check | --remove | --prune]")
|
||||
console.log("without --store the home is CODELY_CLI_HOME when it holds an ide-settings.json, else ~/.codely")
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const gateway = opt(argv, "gateway", "http://127.0.0.1:3425").replace(/\/$/, "")
|
||||
const storeFlag = opt(argv, "store", null)
|
||||
const home = codelyHome()
|
||||
const storePath = storeFlag ? expand(storeFlag) : join(home, "settings.json")
|
||||
const listPath = seedFile(storePath)
|
||||
const bakPath = `${storePath}.pre-magpie`
|
||||
const titlePath = join(dirname(storePath), "ide-settings.json")
|
||||
|
||||
// A home Cowork has never run in is not one we get to guess: the store would
|
||||
// land where nothing reads it, or be overwritten on first launch, and the run
|
||||
// would still look like a success. --store is the user answering the question.
|
||||
if (!storeFlag && (!existsSync(home) || (!existsSync(storePath) && !existsSync(titlePath)))) {
|
||||
console.error(`Cowork has not run in ${home} — open it once, then re-run, or pass --store <home>/settings.json`)
|
||||
process.exit(2)
|
||||
}
|
||||
if (!storeFlag && home !== join(homedir(), ".codely")) {
|
||||
console.log(`Cowork's home is ${home}, not the default ~/.codely`)
|
||||
console.log("the plugin's own path is fixed at ~/.codely/ide-settings.json and cannot follow a moved home, so `magpie cowork <model>` won't reach Cowork — pick the model in Cowork instead")
|
||||
}
|
||||
// Naming the store is the only way a wrong guess at the home is noticed at all.
|
||||
if (!storeFlag) console.log(`store: ${storePath}`)
|
||||
|
||||
const readStore = () => {
|
||||
if (!existsSync(storePath)) return {}
|
||||
let store
|
||||
try {
|
||||
store = JSON.parse(readFileSync(storePath, "utf8"))
|
||||
} catch {
|
||||
console.error(`${storePath} isn't readable JSON — Cowork may be writing it right now; try again, or restore ${bakPath}`)
|
||||
process.exit(2)
|
||||
}
|
||||
if (!store || typeof store !== "object" || Array.isArray(store)) {
|
||||
console.error(`${storePath} isn't a settings object — Cowork may be writing it right now; try again, or restore ${bakPath}`)
|
||||
process.exit(2)
|
||||
}
|
||||
if (!Array.isArray(store.customModels) && "customModels" in store) {
|
||||
console.error(`${storePath}'s customModels is not a list; a magpie agent may have written it oddly — restore ${bakPath} if you have it, or fix the file by hand. Nothing was written.`)
|
||||
process.exit(2)
|
||||
}
|
||||
if (!Array.isArray(store.customModelProviders) && "customModelProviders" in store) {
|
||||
console.error(`${storePath}'s customModelProviders is not a list; refusing to replace it and drop providers you made — restore ${bakPath} if you have it, or fix the file by hand. Nothing was written.`)
|
||||
process.exit(2)
|
||||
}
|
||||
return store
|
||||
}
|
||||
const writeList = (ids) => {
|
||||
writeFileSync(`${listPath}.tmp`, `${JSON.stringify(ids, null, 1)}\n`, "utf8")
|
||||
renameSync(`${listPath}.tmp`, listPath)
|
||||
}
|
||||
const writeStore = (next, seeded) => {
|
||||
if (backupNeeded(storePath, bakPath)) {
|
||||
copyFileSync(storePath, bakPath)
|
||||
console.log(`a copy of the store from before this run: ${bakPath}`)
|
||||
}
|
||||
// Cowork writes this file too, so land each new one in a single move
|
||||
writeFileSync(`${storePath}.tmp`, `${JSON.stringify(next, null, 2)}\n`, "utf8")
|
||||
renameSync(`${storePath}.tmp`, storePath)
|
||||
// an empty record is kept: "nothing of ours" and "no record, guess" are
|
||||
// different answers, and only the first one is safe to act on
|
||||
writeList(seeded)
|
||||
}
|
||||
const readTitle = () => readTitleFile(titlePath)
|
||||
const heldNote = (n) => `${n} recorded entries aren't in the catalog right now; pass --prune to drop them`
|
||||
const writeTitle = (t) => {
|
||||
let ide = {}
|
||||
try {
|
||||
ide = JSON.parse(readFileSync(titlePath, "utf8"))
|
||||
} catch {
|
||||
console.error(`${titlePath} isn't readable JSON; leaving Cowork's selection alone — re-pick it once in Cowork`)
|
||||
return false
|
||||
}
|
||||
if (!ide || typeof ide !== "object" || Array.isArray(ide)) {
|
||||
console.error(`${titlePath} isn't a settings object; leaving Cowork's selection alone — re-pick it once in Cowork`)
|
||||
return false
|
||||
}
|
||||
ide.defaultChatModelTitle = t
|
||||
writeFileSync(`${titlePath}.tmp`, `${JSON.stringify(ide, null, 2)}\n`, "utf8")
|
||||
renameSync(`${titlePath}.tmp`, titlePath)
|
||||
return true
|
||||
}
|
||||
|
||||
const store = readStore()
|
||||
let seeded = loadSeeded(listPath)
|
||||
if (seeded === null && existsSync(listPath)) {
|
||||
console.error(`${listPath} isn't a readable list of entry ids; refusing to guess which entries magpie wrote`)
|
||||
process.exit(2)
|
||||
}
|
||||
// No record, but a store magpie has written before: seed may rebuild the
|
||||
// record once it sees the catalog, because adoption needs to know which models
|
||||
// magpie still offers. --remove has no such evidence, so it refuses instead.
|
||||
const adopt = seeded === null && existsSync(bakPath)
|
||||
|
||||
if (flag("remove")) {
|
||||
if (adopt) {
|
||||
console.error(`no ${listPath}, so this run can't tell which entries magpie wrote — run \`node seed.mjs\` once (magpie running) to rebuild it, then --remove. Nothing was written.`)
|
||||
process.exit(2)
|
||||
}
|
||||
const { next, removed, leftBehind, changed } = unplan(store, seeded ?? new Set())
|
||||
if (flag("check")) {
|
||||
console.log(changed ? `still seeded: ${removed.length} of magpie's models in ${storePath}` : "nothing of magpie's left in the store")
|
||||
process.exit(changed ? 1 : 0)
|
||||
}
|
||||
if (!changed) {
|
||||
console.log(`nothing of magpie's to remove${leftBehind.length ? ` (${leftBehind.length} entries under "${PROVIDER_ID}" weren't written by this script and stay)` : ""}`)
|
||||
process.exit(0)
|
||||
}
|
||||
const selected = readTitle()
|
||||
const gone = (Array.isArray(store.customModels) ? store.customModels : [])
|
||||
.filter((m) => m && removed.includes(m.id))
|
||||
writeStore(next, [])
|
||||
console.log(`took magpie out of ${storePath}: ${removed.length} models${leftBehind.length ? `, left ${leftBehind.length} you added under it yourself` : ""}`)
|
||||
if (!selected.ok) {
|
||||
console.log(`${titlePath} isn't readable JSON; if Cowork falls back after this, pick a model in it once`)
|
||||
} else if (selected.value && gone.some((m) => [m.displayName, m.model, m.id].includes(selected.value))) {
|
||||
console.log(`Cowork was on ${JSON.stringify(selected.value)}, which just went away — pick a model in Cowork or it falls back in silence`)
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
// A title that can't be read is not "no selection": renaming or pruning while
|
||||
// Cowork is on something would leave the app pointing at a name that's gone.
|
||||
const selected = readTitle()
|
||||
if (!selected.ok) {
|
||||
console.error(`${titlePath} isn't readable JSON; refusing to change the store while Cowork's selection can't be read — re-pick it once in Cowork, or restore the file. Nothing was written.`)
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const res = await fetch(`${gateway}/v1/models`)
|
||||
if (!res.ok) {
|
||||
console.error(`magpie's catalog came back ${res.status} from ${gateway}/v1/models — is magpie running?`)
|
||||
process.exit(2)
|
||||
}
|
||||
const catalog = (await res.json()).data
|
||||
if (!Array.isArray(catalog) || !catalog.length) {
|
||||
console.error("magpie's catalog is empty")
|
||||
process.exit(2)
|
||||
}
|
||||
let adopted = false
|
||||
if (adopt) {
|
||||
seeded = adoptSeeded(store, catalog)
|
||||
adopted = true
|
||||
console.log(seeded.size
|
||||
? `no ${listPath}: adopting the ${seeded.size} entries under "${PROVIDER_ID}" titled by their model id`
|
||||
: `no ${listPath}: nothing under "${PROVIDER_ID}" is titled by a catalog model id, so nothing is adopted`)
|
||||
}
|
||||
if (seeded === null) seeded = new Set()
|
||||
|
||||
const { next, added, pruned, held, relabeled, renamed, unreachable, provider, seeded: nextSeeded, changed, drift } =
|
||||
plan(store, catalog, `${gateway}/v1`, seeded, { prune: flag("prune"), selected: selected.value })
|
||||
|
||||
if (unreachable.length) console.log(unreachableNote(unreachable))
|
||||
|
||||
if (flag("check")) {
|
||||
if (drift) {
|
||||
const parts = []
|
||||
if (added.length) parts.push(`+${added.length} to add`)
|
||||
if (pruned.length + held.length) parts.push(`-${pruned.length + held.length} to drop${held.length ? ` (${held.length} held until --prune)` : ""}`)
|
||||
if (relabeled) parts.push(`~${relabeled} to relabel`)
|
||||
if (provider) parts.push(`provider to ${provider}`)
|
||||
console.log(`drift: ${parts.join(", ")}`)
|
||||
} else {
|
||||
console.log(`in step: ${catalog.length} catalog models, ${next.customModels.length} in Cowork, nothing to write`)
|
||||
}
|
||||
process.exit(drift ? 1 : 0)
|
||||
}
|
||||
if (!changed) {
|
||||
console.log(`in step: nothing to write (${next.customModels.length} models in Cowork)`)
|
||||
if (adopted) writeList(nextSeeded)
|
||||
if (held.length) console.log(heldNote(held.length))
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
writeStore(next, nextSeeded)
|
||||
if (renamed && writeTitle(renamed)) {
|
||||
console.log(`Cowork was on the entry we just renamed; its selection now says ${renamed}`)
|
||||
}
|
||||
console.log(`wrote ${storePath}: +${added.length} magpie models, -${pruned.length} stale, ~${relabeled} relabelled, ${next.customModels.length} total`)
|
||||
if (held.length) console.log(heldNote(held.length))
|
||||
}
|
||||
@@ -0,0 +1,819 @@
|
||||
import { test } from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { spawn, spawnSync } from "node:child_process"
|
||||
import { createServer } from "node:http"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
import { agent } from "../cowork.agent.js"
|
||||
import { adoptSeeded, backupNeeded, codelyHome, entry, loadSeeded, opt, plan, provider, readTitleFile, seedFile, unplan, unreachableNote, PROVIDER_ID } from "../seed.mjs"
|
||||
|
||||
const SEED = fileURLToPath(new URL("../seed.mjs", import.meta.url))
|
||||
|
||||
const GLM = {
|
||||
id: "group/auto-glm-5-3-flash",
|
||||
display_name: "GLM-5.3-Flash",
|
||||
magpie_label: "GLM-5.3-Flash · routing group",
|
||||
context_length: 1000000,
|
||||
modalities: { input: ["text", "image"] },
|
||||
}
|
||||
const TEXT = { id: "workbuddy/deepseek-v4.1-flash", display_name: "DeepSeek V4.1 Flash", context_length: 262144, modalities: { input: ["text"] } }
|
||||
const V1 = "http://127.0.0.1:3425/v1"
|
||||
|
||||
// spawnSync would block the event loop the catalog server runs on, so gateway
|
||||
// tests use the async spawn.
|
||||
const runSeed = (args, env = process.env) => new Promise((resolve) => {
|
||||
const child = spawn(process.execPath, [SEED, ...args], { env })
|
||||
let stdout = "", stderr = ""
|
||||
child.stdout.on("data", (d) => (stdout += d))
|
||||
child.stderr.on("data", (d) => (stderr += d))
|
||||
child.on("close", (status) => resolve({ status, stdout, stderr }))
|
||||
})
|
||||
|
||||
const catalogServer = async (t, models) => {
|
||||
const server = createServer((req, res) => {
|
||||
res.setHeader("content-type", "application/json")
|
||||
res.end(JSON.stringify({ data: models }))
|
||||
})
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))
|
||||
t.after(() => server.close())
|
||||
return `http://127.0.0.1:${server.address().port}`
|
||||
}
|
||||
|
||||
test("Cowork is pointed at the field it starts a session on", () => {
|
||||
assert.equal(agent.id, "cowork")
|
||||
assert.equal(agent.config, "~/.codely/ide-settings.json")
|
||||
assert.equal(agent.format, "json")
|
||||
assert.equal(agent.model, "defaultChatModelTitle")
|
||||
assert.equal(agent.dir, "~/.codely")
|
||||
})
|
||||
|
||||
test("carries the vendor's own icon, in the agent and in the package", () => {
|
||||
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"))
|
||||
assert.ok(agent.icon.startsWith("data:image/png;base64,"), "a PNG inlined, so it renders before the repo exists")
|
||||
assert.equal(pkg.magpie.icon, agent.icon)
|
||||
assert.ok(pkg.files.includes("icon.png"), "the same icon shipped as a file")
|
||||
})
|
||||
|
||||
test("a catalog model becomes the shape Cowork's own store uses", () => {
|
||||
assert.deepEqual(entry(GLM), {
|
||||
id: `${PROVIDER_ID}:group/auto-glm-5-3-flash`,
|
||||
model: "group/auto-glm-5-3-flash",
|
||||
providerId: PROVIDER_ID,
|
||||
displayName: "group/auto-glm-5-3-flash",
|
||||
authType: "openai",
|
||||
roles: ["model"],
|
||||
wireApi: "chat",
|
||||
contextLength: 1000000,
|
||||
supportsMultimodal: true,
|
||||
})
|
||||
assert.equal(entry(TEXT).supportsMultimodal, false)
|
||||
assert.equal(entry(GLM).displayName, entry(GLM).model, "the picker title is the one string magpie can write")
|
||||
})
|
||||
|
||||
test("the store keeps its own models and gets one entry per new catalog model", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: "custom-provider", name: "the user's own", baseUrl: "https://example.test/v1" }],
|
||||
customModels: [{ id: "custom-provider:mine", model: "mine", providerId: "custom-provider" }],
|
||||
migratedFromOldFormat: true,
|
||||
}
|
||||
const { next, added } = plan(store, [GLM, TEXT], V1)
|
||||
assert.equal(next.migratedFromOldFormat, true)
|
||||
assert.equal(next.customModels[0].id, "custom-provider:mine")
|
||||
assert.deepEqual(added, [GLM.id, TEXT.id])
|
||||
assert.ok(Array.isArray(next.customModels))
|
||||
assert.equal(next.customModels.length, 3)
|
||||
assert.equal(next.customModelProviders.length, 2)
|
||||
assert.deepEqual(next.customModelProviders[1], provider(V1))
|
||||
})
|
||||
|
||||
test("a model Cowork already has is not added twice, by any provider", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: "custom-provider", name: "x", baseUrl: V1 }],
|
||||
customModels: [{ id: "custom-provider:glm", model: GLM.id, providerId: "custom-provider" }],
|
||||
}
|
||||
const { next, added } = plan(store, [GLM], V1)
|
||||
assert.deepEqual(added, [])
|
||||
assert.equal(next.customModels.length, 1)
|
||||
})
|
||||
|
||||
test("an entry under the user's own provider keeps its name, and the tool names the title to pass", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: "custom-provider", name: "magpie", baseUrl: V1 }],
|
||||
customModels: [{ id: `custom-provider:${GLM.id}`, model: GLM.id, providerId: "custom-provider", displayName: "GLM-5.3-Flash · routing group" }],
|
||||
}
|
||||
const seeded = new Set([`custom-provider:${GLM.id}`])
|
||||
const { next, added, relabeled, unreachable, changed } = plan(store, [GLM], V1, seeded)
|
||||
assert.deepEqual(added, [], "no duplicate entry for a model Cowork can already reach")
|
||||
assert.equal(relabeled, 0, "a name under their provider stays theirs, even if a record lists it")
|
||||
assert.equal(next.customModels[0].displayName, "GLM-5.3-Flash · routing group")
|
||||
assert.equal(next.customModels[0].id, `custom-provider:${GLM.id}`, "its id stays, sessions may name it")
|
||||
assert.deepEqual(unreachable, [{ id: GLM.id, name: "GLM-5.3-Flash · routing group" }], "said out loud instead of a silent fallback")
|
||||
assert.equal(changed, true, "magpie's own provider is still missing")
|
||||
})
|
||||
|
||||
test("a model whose entry is already titled by its id is reachable under any provider", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: "custom-provider", baseUrl: V1 }],
|
||||
customModels: [{ id: `custom-provider:${GLM.id}`, model: GLM.id, providerId: "custom-provider", displayName: GLM.id }],
|
||||
}
|
||||
const { unreachable, relabeled, added } = plan(store, [GLM], V1, new Set())
|
||||
assert.deepEqual(unreachable, [])
|
||||
assert.equal(relabeled, 0)
|
||||
assert.deepEqual(added, [], "and still no second entry for the same model")
|
||||
})
|
||||
|
||||
test("a recorded entry of ours renamed in Cowork is relabelled, not scolded", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, baseUrl: V1 }],
|
||||
customModels: [{ id: `${PROVIDER_ID}:${GLM.id}`, model: GLM.id, providerId: PROVIDER_ID, displayName: "My Name" }],
|
||||
}
|
||||
const { unreachable, relabeled } = plan(store, [GLM], V1, new Set([`${PROVIDER_ID}:${GLM.id}`]), { selected: "My Name" })
|
||||
assert.equal(relabeled, 1)
|
||||
assert.deepEqual(unreachable, [], "the same run puts the id back, so the id selects it afterwards")
|
||||
})
|
||||
|
||||
test("an unrecorded entry the user added under magpie keeps its name and is named in the note", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, baseUrl: V1 }],
|
||||
customModels: [{ id: `${PROVIDER_ID}:${GLM.id}`, model: GLM.id, providerId: PROVIDER_ID, displayName: "My Name" }],
|
||||
}
|
||||
const { next, relabeled, unreachable } = plan(store, [GLM], V1, new Set())
|
||||
assert.equal(relabeled, 0)
|
||||
assert.equal(next.customModels[0].displayName, "My Name")
|
||||
assert.deepEqual(unreachable, [{ id: GLM.id, name: "My Name" }])
|
||||
})
|
||||
|
||||
test("the note gives the title to pass for models the id can't select, and stays quiet when none", () => {
|
||||
assert.equal(unreachableNote([]), "")
|
||||
const rows = [
|
||||
{ id: "a/one", name: "One" },
|
||||
{ id: "a/two", name: "Two" },
|
||||
{ id: "a/three", name: "Three" },
|
||||
{ id: "a/four", name: "Four" },
|
||||
]
|
||||
const n = unreachableNote(rows)
|
||||
assert.match(n, /listed under names that aren't the model id/, n)
|
||||
assert.ok(n.includes('`magpie cowork "One"` (a/one)') && n.includes('`magpie cowork "Three"` (a/three)'), n)
|
||||
assert.ok(!n.includes("Four"), "three rows is enough to go on")
|
||||
assert.match(n, /, …/, "and it says there are more")
|
||||
assert.equal(unreachableNote([rows[0]]).includes("…"), false, "no ellipsis for one")
|
||||
assert.match(n, /won't select those \(Cowork matches the name it shows, not the id\)/, "says why the id is not the title")
|
||||
})
|
||||
|
||||
test("a name magpie can't take on its command line is answered with pick it in Cowork", () => {
|
||||
const n = unreachableNote([
|
||||
{ id: "a/one", name: "One" },
|
||||
{ id: "b/two", name: "a/two" },
|
||||
{ id: "c/three", name: "default" },
|
||||
{ id: "d/four", name: "-x" },
|
||||
])
|
||||
assert.ok(n.includes('`magpie cowork "One"` (a/one)'), n)
|
||||
for (const name of ["a/two", "default", "-x"]) {
|
||||
assert.ok(!n.includes(`magpie cowork "${name}"`), `no command that magpie would misread: ${n}`)
|
||||
}
|
||||
assert.match(n, /pick these in Cowork instead/, n)
|
||||
assert.match(n, /a slash or leading dash makes magpie read the name as a reference or a flag/, n)
|
||||
})
|
||||
|
||||
test("an entry the user named themselves is never renamed, and magpie's write follows it", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: "custom-provider", baseUrl: V1 }],
|
||||
customModels: [{ id: `custom-provider:${GLM.id}`, model: GLM.id, providerId: "custom-provider", displayName: "My Two" }],
|
||||
}
|
||||
const { next, relabeled, renamed } = plan(store, [GLM], V1, new Set(), { selected: "My Two" })
|
||||
assert.equal(relabeled, 0)
|
||||
assert.equal(renamed, null)
|
||||
assert.equal(next.customModels[0].displayName, "My Two")
|
||||
})
|
||||
|
||||
test("renaming the entry Cowork is on moves the selection with it", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, baseUrl: V1, name: "magpie", apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [{ id: `${PROVIDER_ID}:${GLM.id}`, model: GLM.id, providerId: PROVIDER_ID, displayName: "GLM-5.3-Flash · routing group" }],
|
||||
}
|
||||
const { renamed } = plan(store, [GLM], V1, new Set([`${PROVIDER_ID}:${GLM.id}`]), { selected: "GLM-5.3-Flash · routing group" })
|
||||
assert.equal(renamed, GLM.id)
|
||||
})
|
||||
|
||||
test("a model the user wired to their own endpoint keeps its own name", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: "custom-provider", baseUrl: "https://their.own.test/v1" }],
|
||||
customModels: [{ id: `custom-provider:${GLM.id}`, model: GLM.id, providerId: "custom-provider", displayName: "mine" }],
|
||||
}
|
||||
const { next, relabeled, changed } = plan(store, [GLM], V1)
|
||||
assert.equal(relabeled, 0)
|
||||
assert.equal(changed, true, "magpie's own provider is still missing")
|
||||
assert.equal(next.customModels[0].displayName, "mine")
|
||||
})
|
||||
|
||||
test("a recorded model magpie no longer offers is dropped with --prune, and nothing else moves", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, name: "magpie", baseUrl: V1, apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [
|
||||
{ id: "custom-provider:mine", model: "mine", providerId: "custom-provider" },
|
||||
{ id: `${PROVIDER_ID}:gone`, model: "gone", providerId: PROVIDER_ID },
|
||||
{ id: `${PROVIDER_ID}:${TEXT.id}`, model: TEXT.id, providerId: PROVIDER_ID },
|
||||
],
|
||||
}
|
||||
const seeded = new Set([`${PROVIDER_ID}:gone`, `${PROVIDER_ID}:${TEXT.id}`])
|
||||
const { next, added, pruned } = plan(store, [TEXT], V1, seeded, { prune: true })
|
||||
assert.deepEqual(pruned, [`${PROVIDER_ID}:gone`])
|
||||
assert.deepEqual(added, [])
|
||||
assert.deepEqual(next.customModels.map((m) => m.id), ["custom-provider:mine", `${PROVIDER_ID}:${TEXT.id}`])
|
||||
assert.equal(seeded.has(`${PROVIDER_ID}:gone`), true, "the set handed in is not edited")
|
||||
})
|
||||
|
||||
test("a catalog shorter than the record holds its pruning until --prune", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, baseUrl: V1, name: "magpie", apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [
|
||||
{ id: `${PROVIDER_ID}:gone`, model: "gone", providerId: PROVIDER_ID, displayName: "gone" },
|
||||
{ id: `${PROVIDER_ID}:${TEXT.id}`, model: TEXT.id, providerId: PROVIDER_ID, displayName: TEXT.id },
|
||||
],
|
||||
}
|
||||
const seeded = new Set([`${PROVIDER_ID}:gone`, `${PROVIDER_ID}:${TEXT.id}`])
|
||||
const held = plan(store, [TEXT], V1, seeded)
|
||||
assert.deepEqual(held.pruned, [], "an account resting or magpie still starting must not empty the picker")
|
||||
assert.deepEqual(held.held, [`${PROVIDER_ID}:gone`])
|
||||
assert.equal(held.changed, false)
|
||||
assert.equal(held.drift, true, "--check still shows the difference from the catalog")
|
||||
const dropped = plan(store, [TEXT], V1, seeded, { prune: true })
|
||||
assert.deepEqual(dropped.pruned, [`${PROVIDER_ID}:gone`])
|
||||
assert.deepEqual(dropped.held, [])
|
||||
})
|
||||
|
||||
test("a recorded entry missing from the catalog is held even when the lengths match", () => {
|
||||
// the old guard compared catalog.length with the record size, so this pair
|
||||
// looked like no shrink at all and the missing entry was deleted unasked
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, baseUrl: V1, name: "magpie", apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [
|
||||
{ id: `${PROVIDER_ID}:a/one`, model: "a/one", providerId: PROVIDER_ID, displayName: "a/one" },
|
||||
{ id: `${PROVIDER_ID}:a/two`, model: "a/two", providerId: PROVIDER_ID, displayName: "a/two" },
|
||||
{ id: `${PROVIDER_ID}:a/three`, model: "a/three", providerId: PROVIDER_ID, displayName: "a/three" },
|
||||
],
|
||||
}
|
||||
const seeded = new Set([`${PROVIDER_ID}:a/one`, `${PROVIDER_ID}:a/three`])
|
||||
const catalog = [{ id: "a/one" }, { id: "a/two" }]
|
||||
const p = plan(store, catalog, V1, seeded)
|
||||
assert.deepEqual(p.added, [], "nothing new, so the only question is the missing entry")
|
||||
assert.deepEqual(p.pruned, [])
|
||||
assert.deepEqual(p.held, [`${PROVIDER_ID}:a/three`])
|
||||
assert.equal(p.changed, false)
|
||||
assert.equal(p.drift, true)
|
||||
assert.deepEqual(plan(store, catalog, V1, seeded, { prune: true }).pruned, [`${PROVIDER_ID}:a/three`])
|
||||
})
|
||||
|
||||
test("a short catalog never drops the selected entry", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, baseUrl: V1, name: "magpie", apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [{ id: `${PROVIDER_ID}:a/three`, model: "a/three", providerId: PROVIDER_ID, displayName: "a/three" }],
|
||||
}
|
||||
const seeded = new Set([`${PROVIDER_ID}:a/three`])
|
||||
for (const prune of [false, true]) {
|
||||
const p = plan(store, [{ id: "a/one" }], V1, seeded, { prune, selected: "a/three" })
|
||||
assert.deepEqual(p.pruned, [], `prune=${prune}: the catalog is short, the selection must survive`)
|
||||
assert.ok(p.next.customModels.some((m) => m.id === `${PROVIDER_ID}:a/three`), `prune=${prune}`)
|
||||
}
|
||||
})
|
||||
|
||||
test("the model Cowork is on is never pruned, even with --prune", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, baseUrl: V1, name: "magpie", apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [
|
||||
{ id: `${PROVIDER_ID}:gone`, model: "gone", providerId: PROVIDER_ID, displayName: "gone" },
|
||||
{ id: `${PROVIDER_ID}:${TEXT.id}`, model: TEXT.id, providerId: PROVIDER_ID, displayName: TEXT.id },
|
||||
],
|
||||
}
|
||||
const seeded = new Set([`${PROVIDER_ID}:gone`])
|
||||
const { pruned, next } = plan(store, [TEXT], V1, seeded, { prune: true, selected: "gone" })
|
||||
assert.deepEqual(pruned, [])
|
||||
assert.ok(next.customModels.some((m) => m.id === `${PROVIDER_ID}:gone`), "deleting it would drop the live session silently")
|
||||
})
|
||||
|
||||
test("a model the user added and named under magpie's own provider keeps that name", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, name: "magpie", baseUrl: V1, apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [{ id: `${PROVIDER_ID}:mine`, model: "mine", providerId: PROVIDER_ID, displayName: "My Fave" }],
|
||||
}
|
||||
const { relabeled, next } = plan(store, [GLM], V1, new Set())
|
||||
assert.equal(relabeled, 0, "it is under our provider, but we never wrote it")
|
||||
assert.equal(next.customModels.find((m) => m.model === "mine").displayName, "My Fave")
|
||||
})
|
||||
|
||||
test("a model the user added under magpie's own provider survives a shorter catalog", () => {
|
||||
const own = { id: "magpie:my-own", model: "my-own", providerId: PROVIDER_ID, displayName: "my-own" }
|
||||
const store = {
|
||||
customModelProviders: [{ id: PROVIDER_ID, name: "magpie", baseUrl: V1, apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [own, { id: `${PROVIDER_ID}:${TEXT.id}`, model: TEXT.id, providerId: PROVIDER_ID, displayName: TEXT.id }],
|
||||
}
|
||||
const seeded = new Set([`${PROVIDER_ID}:${TEXT.id}`])
|
||||
const { next, pruned, changed } = plan(store, [], V1, seeded, { prune: true })
|
||||
assert.deepEqual(pruned, [`${PROVIDER_ID}:${TEXT.id}`], "what we wrote and magpie dropped")
|
||||
assert.ok(next.customModels.some((m) => m.id === "magpie:my-own"), "what they added under it stays")
|
||||
assert.equal(changed, true)
|
||||
const out = unplan(next, seeded)
|
||||
assert.ok(out.next.customModels.some((m) => m.id === "magpie:my-own"))
|
||||
assert.ok(out.next.customModelProviders.some((p) => p.id === PROVIDER_ID), "the provider stays while their model still uses it")
|
||||
assert.deepEqual(out.leftBehind, ["magpie:my-own"])
|
||||
})
|
||||
|
||||
test("a store Cowork has not filled in yet still comes out with lists", () => {
|
||||
const { next } = plan({ customModels: [], customModelProviders: [] }, [GLM], V1)
|
||||
assert.ok(Array.isArray(next.customModels))
|
||||
assert.ok(Array.isArray(next.customModelProviders))
|
||||
assert.equal(next.customModels.length, 1)
|
||||
})
|
||||
|
||||
test("seeding twice writes nothing the second time", () => {
|
||||
const once = plan({}, [GLM, TEXT], V1)
|
||||
assert.equal(once.changed, true)
|
||||
assert.deepEqual(once.seeded, [`${PROVIDER_ID}:${GLM.id}`, `${PROVIDER_ID}:${TEXT.id}`])
|
||||
const twice = plan(once.next, [GLM, TEXT], V1, new Set(once.seeded))
|
||||
assert.equal(twice.changed, false)
|
||||
assert.deepEqual(twice.added, [])
|
||||
assert.deepEqual(twice.pruned, [])
|
||||
})
|
||||
|
||||
test("a provider that is missing or points elsewhere is drift of its own", () => {
|
||||
const first = plan({}, [GLM], V1)
|
||||
assert.equal(first.provider, "add")
|
||||
assert.equal(first.drift, true)
|
||||
const moved = plan(first.next, [GLM], "http://127.0.0.1:9999/v1", new Set(first.seeded))
|
||||
assert.deepEqual(moved.added, [])
|
||||
assert.equal(moved.provider, "repoint")
|
||||
assert.equal(moved.changed, true)
|
||||
assert.equal(moved.drift, true)
|
||||
const settled = plan(first.next, [GLM], V1, new Set(first.seeded))
|
||||
assert.equal(settled.provider, null)
|
||||
assert.equal(settled.changed, false)
|
||||
assert.equal(settled.drift, false)
|
||||
})
|
||||
|
||||
test("a selection that can't be read is not an empty selection", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-title-"))
|
||||
try {
|
||||
const title = join(dir, "ide-settings.json")
|
||||
assert.deepEqual(readTitleFile(title), { ok: true, value: null }, "no file is no selection")
|
||||
writeFileSync(title, "{ not json")
|
||||
assert.deepEqual(readTitleFile(title), { ok: false, value: null })
|
||||
writeFileSync(title, "[]")
|
||||
assert.deepEqual(readTitleFile(title), { ok: false, value: null }, "a list is not a settings object")
|
||||
writeFileSync(title, JSON.stringify({ defaultChatModelTitle: 7 }))
|
||||
assert.deepEqual(readTitleFile(title), { ok: false, value: null }, "a selection that isn't a string can't match an entry")
|
||||
writeFileSync(title, JSON.stringify({ defaultChatModelTitle: "x" }))
|
||||
assert.deepEqual(readTitleFile(title), { ok: true, value: "x" })
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("plan does not edit the store it was given", () => {
|
||||
const store = { customModelProviders: [], customModels: [{ id: "a", model: "a", providerId: "custom-provider" }] }
|
||||
const before = JSON.stringify(store)
|
||||
plan(store, [GLM], V1)
|
||||
assert.equal(JSON.stringify(store), before)
|
||||
})
|
||||
|
||||
test("a flag with nothing after it is not read as its value", () => {
|
||||
assert.equal(opt(["--check"], "gateway", V1), V1)
|
||||
assert.equal(opt(["--gateway", "http://127.0.0.1:9999", "--check"], "gateway", V1), "http://127.0.0.1:9999")
|
||||
assert.equal(opt(["--gateway", "--check"], "gateway", V1), V1)
|
||||
assert.equal(opt([], "store", "~/.codely/settings.json"), "~/.codely/settings.json")
|
||||
})
|
||||
|
||||
const OWN = { id: "custom-provider:mine", model: "mine", providerId: "custom-provider" }
|
||||
const OWN_STORE = {
|
||||
customModelProviders: [{ id: "custom-provider", name: "the user's own", baseUrl: "https://example.test/v1" }],
|
||||
customModels: [OWN],
|
||||
migratedFromOldFormat: true,
|
||||
}
|
||||
|
||||
test("what the package put in, it can take out again", () => {
|
||||
const p = plan(OWN_STORE, [GLM, TEXT], V1)
|
||||
assert.equal(p.next.customModels.length, 3)
|
||||
const { next, removed, changed } = unplan(p.next, new Set(p.seeded))
|
||||
assert.deepEqual(removed, [`${PROVIDER_ID}:${GLM.id}`, `${PROVIDER_ID}:${TEXT.id}`])
|
||||
assert.equal(changed, true)
|
||||
assert.deepEqual(next.customModels, OWN_STORE.customModels)
|
||||
assert.deepEqual(next.customModelProviders, OWN_STORE.customModelProviders)
|
||||
assert.equal(next.migratedFromOldFormat, true)
|
||||
})
|
||||
|
||||
test("taking magpie out of a store it never touched changes nothing", () => {
|
||||
const { next, removed, changed } = unplan(OWN_STORE)
|
||||
assert.equal(changed, false)
|
||||
assert.deepEqual(removed, [])
|
||||
assert.deepEqual(next.customModels, OWN_STORE.customModels)
|
||||
})
|
||||
|
||||
test("the backup is only ever taken from a store magpie has not written yet", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-backup-"))
|
||||
try {
|
||||
const store = join(dir, "settings.json"), bak = `${store}.pre-magpie`
|
||||
assert.equal(backupNeeded(store, bak), false, "no store, nothing to keep")
|
||||
writeFileSync(store, "{}")
|
||||
assert.equal(backupNeeded(store, bak), true, "first write keeps the original")
|
||||
writeFileSync(bak, "{}")
|
||||
assert.equal(backupNeeded(store, bak), false, "a second write must not replace the original with a seeded store")
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("--remove takes out what the sidecar recorded and nothing the user added", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-remove-"))
|
||||
try {
|
||||
const store = join(dir, "settings.json")
|
||||
const p = plan(OWN_STORE, [GLM, TEXT], V1)
|
||||
p.next.customModels.push({ id: "magpie:my-own", model: "my-own", providerId: PROVIDER_ID, displayName: "my-own" })
|
||||
writeFileSync(store, JSON.stringify(p.next))
|
||||
writeFileSync(seedFile(store), JSON.stringify(p.seeded))
|
||||
|
||||
const r = spawnSync(process.execPath, [SEED, "--remove", "--store", store], { encoding: "utf8" })
|
||||
assert.equal(r.status, 0, r.stderr)
|
||||
const after = JSON.parse(readFileSync(store, "utf8"))
|
||||
assert.deepEqual(after.customModels.map((m) => m.id), ["custom-provider:mine", "magpie:my-own"])
|
||||
assert.ok(after.customModelProviders.some((x) => x.id === PROVIDER_ID), "their model still uses that provider")
|
||||
assert.match(r.stdout, /left 1 you added under it yourself/)
|
||||
assert.equal(existsSync(`${store}.pre-magpie`), true)
|
||||
assert.deepEqual(JSON.parse(readFileSync(seedFile(store), "utf8")), [], "an empty record, not no record")
|
||||
|
||||
const again = spawnSync(process.execPath, [SEED, "--remove", "--store", store], { encoding: "utf8" })
|
||||
assert.equal(again.status, 0)
|
||||
assert.match(again.stdout, /nothing of magpie's to remove/)
|
||||
assert.ok(JSON.parse(readFileSync(store, "utf8")).customModels.some((m) => m.id === "magpie:my-own"),
|
||||
"a second run must not eat what the first one left")
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("--remove refuses a store whose record is missing instead of guessing from the backup", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-adopt-"))
|
||||
try {
|
||||
const store = join(dir, "settings.json")
|
||||
writeFileSync(store, JSON.stringify(plan(OWN_STORE, [GLM, TEXT], V1).next))
|
||||
const before = readFileSync(store, "utf8")
|
||||
writeFileSync(`${store}.pre-magpie`, "{}")
|
||||
const r = spawnSync(process.execPath, [SEED, "--remove", "--store", store], { encoding: "utf8" })
|
||||
assert.equal(r.status, 2)
|
||||
assert.match(r.stderr, /run `node seed\.mjs` once/)
|
||||
assert.equal(readFileSync(store, "utf8"), before, "nothing was written")
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("seed rebuilds a missing record from entries shaped like ours, and --remove keeps the rest", async (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-adopt-seed-"))
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }))
|
||||
const store = join(dir, "settings.json")
|
||||
const gateway = await catalogServer(t, [GLM, TEXT])
|
||||
// the store's provider already points at this gateway, so the only thing the
|
||||
// run has to do is rebuild the record
|
||||
const mixed = plan(OWN_STORE, [GLM], `${gateway}/v1`).next
|
||||
mixed.customModels.push(
|
||||
{ id: `${PROVIDER_ID}:mine`, model: "mine", providerId: PROVIDER_ID, displayName: "My Fave" },
|
||||
{ id: `${PROVIDER_ID}:pretty`, model: TEXT.id, providerId: PROVIDER_ID, displayName: "Pretty" },
|
||||
)
|
||||
writeFileSync(store, JSON.stringify(mixed))
|
||||
writeFileSync(`${store}.pre-magpie`, "{}")
|
||||
const seed = await runSeed(["--store", store, "--gateway", gateway])
|
||||
assert.equal(seed.status, 0, seed.stderr)
|
||||
assert.match(seed.stdout, /adopting the 1 entries under "magpie" titled by their model id/)
|
||||
assert.deepEqual(JSON.parse(readFileSync(seedFile(store), "utf8")), [`${PROVIDER_ID}:${GLM.id}`],
|
||||
"ours only, not the entry the user named")
|
||||
const out = await runSeed(["--store", store, "--remove"])
|
||||
assert.equal(out.status, 0, out.stderr)
|
||||
assert.deepEqual(JSON.parse(readFileSync(store, "utf8")).customModels.map((m) => m.id).sort(),
|
||||
["custom-provider:mine", `${PROVIDER_ID}:mine`, `${PROVIDER_ID}:pretty`].sort())
|
||||
})
|
||||
|
||||
test("relabelling the entry Cowork is on moves the saved title with it", async (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-relabel-"))
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }))
|
||||
const store = join(dir, "settings.json")
|
||||
const gateway = await catalogServer(t, [GLM])
|
||||
const id = `${PROVIDER_ID}:${GLM.id}`
|
||||
writeFileSync(store, JSON.stringify({
|
||||
customModelProviders: [{ id: PROVIDER_ID, baseUrl: `${gateway}/v1`, name: "magpie", apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [{ id, model: GLM.id, providerId: PROVIDER_ID, displayName: "Pretty Label" }],
|
||||
}))
|
||||
writeFileSync(seedFile(store), JSON.stringify([id]))
|
||||
writeFileSync(join(dir, "ide-settings.json"), JSON.stringify({ defaultChatModelTitle: "Pretty Label", other: true }))
|
||||
const r = await runSeed(["--store", store, "--gateway", gateway])
|
||||
assert.equal(r.status, 0, r.stderr)
|
||||
assert.equal(JSON.parse(readFileSync(store, "utf8")).customModels[0].displayName, GLM.id)
|
||||
const ide = JSON.parse(readFileSync(join(dir, "ide-settings.json"), "utf8"))
|
||||
assert.equal(ide.defaultChatModelTitle, GLM.id, "the selection follows the renamed entry")
|
||||
assert.equal(ide.other, true, "everything else in ide-settings.json is kept")
|
||||
assert.match(r.stdout, /selection now says/)
|
||||
})
|
||||
|
||||
test("a user's own entry under magpie survives a real seed run and a real --remove", async (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-own-magpie-"))
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }))
|
||||
const store = join(dir, "settings.json")
|
||||
const gateway = await catalogServer(t, [GLM])
|
||||
const own = { id: "magpie:my-own", model: "my-own", providerId: PROVIDER_ID, displayName: "My Own" }
|
||||
writeFileSync(store, JSON.stringify({
|
||||
customModelProviders: [
|
||||
{ id: "custom-provider", name: "their own", baseUrl: "https://their.own.test/v1" },
|
||||
{ id: PROVIDER_ID, name: "magpie", baseUrl: `${gateway}/v1`, apiKey: "magpie-cowork", authType: "openai" },
|
||||
],
|
||||
customModels: [{ id: "custom-provider:mine", model: "mine", providerId: "custom-provider" }, own],
|
||||
}))
|
||||
writeFileSync(join(dir, "ide-settings.json"), JSON.stringify({ defaultChatModelTitle: "My Own" }))
|
||||
|
||||
const seeded = await runSeed(["--store", store, "--gateway", gateway])
|
||||
assert.equal(seeded.status, 0, seeded.stderr)
|
||||
let after = JSON.parse(readFileSync(store, "utf8"))
|
||||
assert.ok(after.customModels.some((m) => m.id === "magpie:my-own" && m.displayName === "My Own"),
|
||||
"the next seed run must not drop what they added under magpie and named themselves")
|
||||
assert.ok(after.customModels.some((m) => m.id === `${PROVIDER_ID}:${GLM.id}`))
|
||||
assert.deepEqual(JSON.parse(readFileSync(seedFile(store), "utf8")), [`${PROVIDER_ID}:${GLM.id}`],
|
||||
"the record names only what this run wrote")
|
||||
|
||||
const removed = await runSeed(["--remove", "--store", store])
|
||||
assert.equal(removed.status, 0, removed.stderr)
|
||||
after = JSON.parse(readFileSync(store, "utf8"))
|
||||
assert.deepEqual(after.customModels.map((m) => m.id), ["custom-provider:mine", "magpie:my-own"])
|
||||
assert.ok(after.customModelProviders.some((p) => p.id === PROVIDER_ID), "their entry still uses the provider")
|
||||
assert.match(removed.stdout, /left 1 you added under it yourself/)
|
||||
assert.equal(JSON.parse(readFileSync(join(dir, "ide-settings.json"), "utf8")).defaultChatModelTitle, "My Own")
|
||||
})
|
||||
|
||||
test("a real run against a short catalog keeps the selected entry, with or without --prune", async (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-short-catalog-"))
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }))
|
||||
const store = join(dir, "settings.json")
|
||||
const gateway = await catalogServer(t, [{ id: "a/one" }])
|
||||
const id = `${PROVIDER_ID}:a/three`
|
||||
writeFileSync(store, JSON.stringify({
|
||||
customModelProviders: [{ id: PROVIDER_ID, name: "magpie", baseUrl: `${gateway}/v1`, apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [{ id, model: "a/three", providerId: PROVIDER_ID, displayName: "a/three" }],
|
||||
}))
|
||||
writeFileSync(seedFile(store), JSON.stringify([id]))
|
||||
writeFileSync(join(dir, "ide-settings.json"), JSON.stringify({ defaultChatModelTitle: "a/three" }))
|
||||
|
||||
for (const extra of [[], ["--prune"]]) {
|
||||
const r = await runSeed(["--store", store, "--gateway", gateway, ...extra])
|
||||
assert.equal(r.status, 0, r.stderr)
|
||||
const after = JSON.parse(readFileSync(store, "utf8"))
|
||||
assert.ok(after.customModels.some((m) => m.id === id), `extra=${extra}: the model Cowork is on must stay`)
|
||||
assert.equal(JSON.parse(readFileSync(join(dir, "ide-settings.json"), "utf8")).defaultChatModelTitle, "a/three")
|
||||
}
|
||||
})
|
||||
|
||||
test("--remove says when it takes out the model Cowork is on", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-remove-sel-"))
|
||||
try {
|
||||
const store = join(dir, "settings.json")
|
||||
const p = plan(OWN_STORE, [GLM], V1)
|
||||
writeFileSync(store, JSON.stringify(p.next))
|
||||
writeFileSync(seedFile(store), JSON.stringify(p.seeded))
|
||||
writeFileSync(join(dir, "ide-settings.json"), JSON.stringify({ defaultChatModelTitle: GLM.id }))
|
||||
const r = spawnSync(process.execPath, [SEED, "--remove", "--store", store], { encoding: "utf8" })
|
||||
assert.equal(r.status, 0, r.stderr)
|
||||
assert.match(r.stdout, /which just went away/, r.stdout)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a store whose lists were written as objects stops before anything is replaced", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-shape-"))
|
||||
try {
|
||||
for (const field of ["customModels", "customModelProviders"]) {
|
||||
const store = join(dir, `${field}.json`)
|
||||
const other = field === "customModels" ? "customModelProviders" : "customModels"
|
||||
writeFileSync(store, JSON.stringify({ [field]: { 0: { id: "x" } }, [other]: [] }))
|
||||
const before = readFileSync(store, "utf8")
|
||||
const r = spawnSync(process.execPath, [SEED, "--check", "--store", store], { encoding: "utf8" })
|
||||
assert.equal(r.status, 2)
|
||||
assert.match(r.stderr, new RegExp(`${field} is not a list`))
|
||||
assert.equal(readFileSync(store, "utf8"), before)
|
||||
}
|
||||
const nul = join(dir, "null.json")
|
||||
writeFileSync(nul, "null")
|
||||
const r = spawnSync(process.execPath, [SEED, "--check", "--store", nul], { encoding: "utf8" })
|
||||
assert.equal(r.status, 2)
|
||||
assert.match(r.stderr, /isn't a settings object/)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("--check exits 1 while a recorded entry is held back, and 1 again once --prune would drop it", async (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-check-"))
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }))
|
||||
const store = join(dir, "settings.json")
|
||||
const gateway = await catalogServer(t, [GLM])
|
||||
writeFileSync(store, JSON.stringify({
|
||||
customModelProviders: [{ id: PROVIDER_ID, baseUrl: `${gateway}/v1`, name: "magpie", apiKey: "magpie-cowork", authType: "openai" }],
|
||||
customModels: [
|
||||
{ id: `${PROVIDER_ID}:${GLM.id}`, model: GLM.id, providerId: PROVIDER_ID, displayName: GLM.id },
|
||||
{ id: `${PROVIDER_ID}:gone`, model: "gone", providerId: PROVIDER_ID, displayName: "gone" },
|
||||
],
|
||||
}))
|
||||
writeFileSync(seedFile(store), JSON.stringify([`${PROVIDER_ID}:${GLM.id}`, `${PROVIDER_ID}:gone`]))
|
||||
const r = await runSeed(["--store", store, "--check", "--gateway", gateway])
|
||||
assert.equal(r.status, 1, r.stderr)
|
||||
assert.match(r.stdout, /drift: -1 to drop \(1 held until --prune\)/)
|
||||
const pruned = await runSeed(["--store", store, "--check", "--gateway", gateway, "--prune"])
|
||||
assert.equal(pruned.status, 1)
|
||||
assert.match(pruned.stdout, /drift: -1 to drop\s*$/)
|
||||
})
|
||||
|
||||
test("an unreadable selection stops before the catalog is fetched", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-title-cli-"))
|
||||
try {
|
||||
const store = join(dir, "settings.json")
|
||||
writeFileSync(store, "{}")
|
||||
writeFileSync(join(dir, "ide-settings.json"), "{ not json")
|
||||
const r = spawnSync(process.execPath, [SEED, "--check", "--store", store, "--gateway", "http://127.0.0.1:9"], { encoding: "utf8" })
|
||||
assert.equal(r.status, 2)
|
||||
assert.match(r.stderr, /selection can't be read/)
|
||||
assert.doesNotMatch(r.stderr, /is magpie running/, "it stopped before going to the gateway")
|
||||
assert.equal(readFileSync(store, "utf8"), "{}")
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("with no record and no backup, a store we never wrote is left alone", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-noadopt-"))
|
||||
try {
|
||||
const store = join(dir, "settings.json")
|
||||
writeFileSync(store, JSON.stringify({
|
||||
customModelProviders: [{ id: PROVIDER_ID, name: "my-magpie", baseUrl: V1, apiKey: "k", authType: "openai" }],
|
||||
customModels: [
|
||||
{ id: "magpie:a/two", model: "a/two", providerId: PROVIDER_ID, displayName: "My Two" },
|
||||
{ id: "magpie:my-local", model: "my-local", providerId: PROVIDER_ID, displayName: "My Local" },
|
||||
],
|
||||
}))
|
||||
const r = spawnSync(process.execPath, [SEED, "--remove", "--store", store], { encoding: "utf8" })
|
||||
assert.equal(r.status, 0, r.stderr)
|
||||
assert.match(r.stdout, /nothing of magpie's to remove/)
|
||||
assert.equal(JSON.parse(readFileSync(store, "utf8")).customModels.length, 2)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a user provider pointed at magpie's address is never touched, seeded or pruned", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: "my-magpie", name: "my-magpie", baseUrl: V1, apiKey: "k", authType: "openai" }],
|
||||
customModels: [
|
||||
{ id: "my-magpie:a/two", model: "a/two", providerId: "my-magpie", displayName: "My Two" },
|
||||
{ id: "my-magpie:my-local", model: "my-local", providerId: "my-magpie", displayName: "My Local" },
|
||||
],
|
||||
}
|
||||
const first = plan(store, [{ id: "a/two" }, { id: "a/three" }], V1, new Set(), { selected: "My Two" })
|
||||
assert.deepEqual(first.pruned, [])
|
||||
assert.equal(first.relabeled, 0, "their names are theirs")
|
||||
assert.deepEqual(first.next.customModels.slice(0, 2).map((m) => m.displayName), ["My Two", "My Local"])
|
||||
assert.deepEqual(first.added, ["a/three"], "only the model missing from the store is appended, under our provider")
|
||||
const short = plan(first.next, [{ id: "a/one" }], V1, new Set(first.seeded), { selected: "My Two", prune: true })
|
||||
assert.deepEqual(short.pruned, [`${PROVIDER_ID}:a/three`], "what we wrote and magpie dropped, and nothing of theirs")
|
||||
assert.deepEqual(short.next.customModels.map((m) => m.id).sort(),
|
||||
[`${PROVIDER_ID}:a/one`, "my-magpie:a/two", "my-magpie:my-local"], "a/one is the new seed, their two are untouched")
|
||||
})
|
||||
|
||||
test("a record that names entries under someone else's provider cannot destroy them", () => {
|
||||
// the pre-release version recorded entries it had claimed by address; a store
|
||||
// carrying that record must still keep them through --prune and --remove
|
||||
const theirs = { id: "custom-provider:a/gone", model: "a/gone", providerId: "custom-provider", displayName: "Pretty" }
|
||||
const store = {
|
||||
customModelProviders: [{ id: "custom-provider", baseUrl: V1 }, { id: PROVIDER_ID, baseUrl: V1, apiKey: "magpie-cowork" }],
|
||||
customModels: [
|
||||
theirs,
|
||||
{ id: `${PROVIDER_ID}:a/two`, model: "a/two", providerId: PROVIDER_ID, displayName: "a/two" },
|
||||
{ id: `${PROVIDER_ID}:a/retired`, model: "a/retired", providerId: PROVIDER_ID, displayName: "a/retired" },
|
||||
],
|
||||
}
|
||||
const seeded = new Set(["custom-provider:a/gone", `${PROVIDER_ID}:a/two`, `${PROVIDER_ID}:a/retired`])
|
||||
const p = plan(store, [{ id: "a/two" }], V1, seeded, { prune: true })
|
||||
assert.deepEqual(p.pruned, [`${PROVIDER_ID}:a/retired`], "only our own retired entry goes")
|
||||
assert.equal(p.relabeled, 0, "their name is not ours to rewrite just because an old record listed it")
|
||||
assert.deepEqual(p.next.customModels.filter((m) => m.providerId === "custom-provider").map((m) => m.displayName), ["Pretty"])
|
||||
const { next, removed, changed } = unplan(store, seeded)
|
||||
assert.deepEqual(removed.sort(), [`${PROVIDER_ID}:a/retired`, `${PROVIDER_ID}:a/two`], "ours, both of them")
|
||||
assert.deepEqual(next.customModels, [theirs], "--remove leaves theirs alone")
|
||||
assert.equal(changed, true)
|
||||
})
|
||||
|
||||
test("adoption claims only entries shaped like ours, under our provider, still in the catalog", () => {
|
||||
const store = {
|
||||
customModelProviders: [{ id: "my-magpie", baseUrl: V1 }, { id: PROVIDER_ID, baseUrl: V1 }],
|
||||
customModels: [
|
||||
{ id: "my-magpie:a/two", model: "a/two", providerId: "my-magpie", displayName: "a/two" },
|
||||
{ id: "my-magpie:my-local", model: "my-local", providerId: "my-magpie", displayName: "my-local" },
|
||||
{ id: `${PROVIDER_ID}:a/two`, model: "a/two", providerId: PROVIDER_ID, displayName: "a/two" },
|
||||
{ id: `${PROVIDER_ID}:pretty`, model: "a/pretty", providerId: PROVIDER_ID, displayName: "Pretty Name" },
|
||||
{ id: `${PROVIDER_ID}:retired`, model: "retired", providerId: PROVIDER_ID, displayName: "retired" },
|
||||
{ id: `${PROVIDER_ID}:unlabeled`, model: "a/unlabeled", providerId: PROVIDER_ID },
|
||||
],
|
||||
}
|
||||
assert.deepEqual([...adoptSeeded(store, [{ id: "a/two" }, { id: "a/pretty" }])], ["magpie:a/two"],
|
||||
"not a provider that merely points at magpie, not a name the user chose, not a model magpie dropped, not an entry with no title")
|
||||
})
|
||||
|
||||
test("an unreadable record stops instead of guessing", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-record-"))
|
||||
try {
|
||||
const store = join(dir, "settings.json")
|
||||
writeFileSync(store, "{}")
|
||||
writeFileSync(seedFile(store), "{ not a list")
|
||||
assert.equal(loadSeeded(seedFile(store)), null)
|
||||
const r = spawnSync(process.execPath, [SEED, "--remove", "--store", store], { encoding: "utf8" })
|
||||
assert.equal(r.status, 2)
|
||||
assert.match(r.stderr, /refusing to guess/)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
const withHome = (dir, extra = {}) => {
|
||||
const env = { ...process.env, ...extra, USERPROFILE: dir, HOME: dir }
|
||||
if (!("CODELY_CLI_HOME" in extra)) delete env.CODELY_CLI_HOME
|
||||
return env
|
||||
}
|
||||
|
||||
test("the home Cowork's ide-settings.json sits in is the one seeded", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-home-"))
|
||||
try {
|
||||
const moved = join(dir, "moved"), cli = join(dir, ".codely-cli"), def = join(dir, ".codely")
|
||||
for (const d of [moved, cli, def]) mkdirSync(d, { recursive: true })
|
||||
writeFileSync(join(moved, "ide-settings.json"), "{}")
|
||||
assert.equal(codelyHome({ CODELY_CLI_HOME: moved }, dir), moved, "a moved home wins")
|
||||
assert.equal(codelyHome({ CODELY_CLI_HOME: `~/moved` }, dir), moved, "written with a ~ it still resolves")
|
||||
writeFileSync(join(def, "ide-settings.json"), "{}")
|
||||
assert.equal(codelyHome({ CODELY_CLI_HOME: cli }, dir), def, "the terminal CLI's own home is not Cowork's")
|
||||
assert.equal(codelyHome({}, dir), def)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("with no marker anywhere the default home is still the answer, uncreated", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-home2-"))
|
||||
try {
|
||||
const def = join(dir, ".codely")
|
||||
assert.equal(codelyHome({ CODELY_CLI_HOME: join(dir, "gone") }, dir), def)
|
||||
assert.equal(existsSync(def), false, "answering a question must not create the directory")
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a home Cowork has not run in stops instead of writing a store nothing reads", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-nohome-"))
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [SEED, "--check"], { encoding: "utf8", env: withHome(dir) })
|
||||
assert.equal(r.status, 2)
|
||||
assert.match(r.stderr, /has not run in/)
|
||||
assert.equal(existsSync(join(dir, ".codely")), false, "and the run creates nothing")
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("a home Cowork created but never filled in is a store we may write", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-first-"))
|
||||
try {
|
||||
mkdirSync(join(dir, ".codely"))
|
||||
writeFileSync(join(dir, ".codely", "ide-settings.json"), "{}")
|
||||
const r = spawnSync(process.execPath, [SEED, "--remove"], { encoding: "utf8", env: withHome(dir) })
|
||||
assert.equal(r.status, 0, r.stderr)
|
||||
assert.match(r.stdout, /nothing of magpie's to remove/)
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("CODELY_CLI_HOME moves the store and the record it reads with it", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "cowork-moved-"))
|
||||
try {
|
||||
const moved = join(dir, "D")
|
||||
mkdirSync(moved)
|
||||
const store = join(moved, "settings.json")
|
||||
const p = plan(OWN_STORE, [GLM], V1)
|
||||
writeFileSync(store, JSON.stringify(p.next))
|
||||
writeFileSync(join(moved, "ide-settings.json"), JSON.stringify({ defaultChatModelTitle: GLM.id }))
|
||||
writeFileSync(seedFile(store), JSON.stringify(p.seeded))
|
||||
|
||||
const r = spawnSync(process.execPath, [SEED, "--remove"], { encoding: "utf8", env: { ...withHome(dir), CODELY_CLI_HOME: moved } })
|
||||
assert.equal(r.status, 0, r.stderr)
|
||||
assert.match(r.stdout, /took magpie out of/, r.stdout)
|
||||
assert.ok(r.stdout.includes(store), `it names the store it took out: ${r.stdout}`)
|
||||
assert.ok(r.stdout.includes(`store: ${store}`), "it says which store it worked on before it says anything else")
|
||||
assert.deepEqual(JSON.parse(readFileSync(store, "utf8")).customModels, OWN_STORE.customModels)
|
||||
assert.equal(existsSync(join(dir, ".codely")), false, "the default home is left alone")
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
@@ -66,6 +66,8 @@
|
||||
"summary": { "en": "PiG (Pi in Go): add Magpie's endpoint and model catalog, choose models in PiG, and keep startup settings unchanged.", "zh": "为 PiG(Pi in Go)注入 Magpie 端点与模型列表,在 PiG 内选择模型,保持启动设置不变。" } },
|
||||
{ "package": "@magpie-community/agent-type4me", "name": "Type4Me", "kind": "agent", "community": true,
|
||||
"summary": { "en": "Type4Me (macOS voice input) on magpie's Agents page: pick one of magpie's models for its LLM post-processing, used from the next dictation.", "zh": "把 Type4Me(macOS 语音输入)加到 magpie 的 Agent 页:给它的 LLM 后处理选 magpie 的模型,下一次语音输入即生效。" } },
|
||||
{ "package": "@magpie-community/agent-cowork", "name": "Tuanjie Cowork", "kind": "agent", "community": true,
|
||||
"summary": { "en": "Tuanjie Cowork (codely) on magpie's Agents page: pick one of magpie's models and Cowork chats with it, on the subscriptions magpie already holds.", "zh": "把团结 Cowork(codely)加到 magpie 的 Agent 页:给它选一个 magpie 的模型,它聊天就走那个模型,用的是 magpie 里已登录的那些订阅的额度。" } },
|
||||
{ "package": "@magpie-community/middleware-reserve", "name": "Reserve", "kind": "middleware", "community": true,
|
||||
"summary": { "en": "Two routings that keep something in reserve: fill accounts up to a ceiling of their allowance, or use subscriptions before API keys.", "zh": "两种留余量的路由:账号用到额度上限就换下一个,或订阅账号优先于 API key。" } },
|
||||
{ "package": "@magpie-community/tools-calc", "name": "Calc", "kind": "tools", "community": true,
|
||||
|
||||
Reference in New Issue
Block a user