diff --git a/README.md b/README.md index 777e36a..4678115 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,7 @@ it off puts the config back. | [aider](packages/aider) | [Aider](https://aider.chat): `~/.aider.conf.yml`, through litellm's `openai/` prefix | | [bub](packages/bub) | [Bub](https://bub.build): `~/.bub/config.yml`, as the `magpie:` provider (needs Bub 0.5.1 or later) | | [kilo](packages/kilo) | [Kilo Code](https://kilo.ai): `~/.config/kilo/kilo.jsonc`, through an OpenAI-compatible provider | +| [junie](packages/junie) | [Junie CLI](https://junie.jetbrains.com/): an explicit `/v1/models` seed for its full picker and Magpie's selected model as the launch default; no LiteLLM | | [kimi-desktop](packages/kimi-desktop) | Ordinary [Kimi desktop](https://www.kimi.com/) Work, through its authenticated local runtime; not Kimi Code CLI | | [pig](packages/pig) | [PiG](https://github.com/MichaelKinsy/PiG): injects Magpie's endpoint and model catalog into `~/.pig/agent/models.json`; choose the model in PiG, startup settings stay unchanged | | [type4me](packages/type4me) | [Type4Me](https://github.com/joewongjc/type4me), macOS voice input: `~/Library/Application Support/Type4Me/magpie-agent.json`, for its LLM post-processing | diff --git a/packages/junie/LICENSE b/packages/junie/LICENSE new file mode 100644 index 0000000..e6bc674 --- /dev/null +++ b/packages/junie/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 magpie-community contributors + +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. diff --git a/packages/junie/README.md b/packages/junie/README.md new file mode 100644 index 0000000..b23aefc --- /dev/null +++ b/packages/junie/README.md @@ -0,0 +1,113 @@ +# @magpie-community/agent-junie + +Junie CLI through Magpie's OpenAI-compatible gateway, without LiteLLM or a +background plugin runtime. This follows the community Cowork package: an +ordinary agent module plus an explicit catalog seed script. + +## Install and connect + +Install from Magpie's Plugins tab, or with the CLI: + +```sh +magpie plugin add @magpie-community/agent-junie +``` + +After installation, `seed.mjs` is at +`~/.config/magpie/plugins/node_modules/@magpie-community/agent-junie/seed.mjs`. +If `XDG_CONFIG_HOME` is set, replace `~/.config` with that directory. +The seed command requires Node.js 18 or later. With Junie closed, connect a +model and seed the catalog before starting Junie: + +```sh +magpie junie +JUNIE_SEED="${XDG_CONFIG_HOME:-$HOME/.config}/magpie/plugins/node_modules/@magpie-community/agent-junie/seed.mjs" +node "$JUNIE_SEED" --eco on +junie +``` + +The commands below use `JUNIE_SEED` set above. `magpie junie ` writes +`~/.junie/magpie/connection.json`: its `id` is Magpie's selected model ID, +`baseUrl` ends in `/v1/chat/completions`, and `apiKey` is the Junie agent's +gateway key. This connection file is outside Junie's model discovery folders. + +The seed script reads that connection's endpoint and key, fetches `/v1/models` +with Junie's User-Agent, and writes one native JSON profile per advertised +model into `~/.junie/magpie/models/`. Stable profile IDs are derived from the +gateway IDs; the original wire IDs are preserved inside the profiles. Their +display names end in `· Magpie` in Junie's `/model` picker. + +The script adds its discovery directory to `config.json`'s `model-locations`. +On every seed it sets `settings.json`'s `modelForLaunch` to the ordinary +profile for Magpie's selected model, clears an incompatible remembered +provider/Mix, and marks default-model onboarding complete. Junie stores +these settings as strings. The picker contains exactly the advertised models, +without an additional selected-model alias. + +To choose an individual catalog model as the launch default: + +```sh +node "$JUNIE_SEED" --model provider/model --eco on +``` + +You can also choose an individual model in Junie's `/model`. Running the seed +again copies Magpie's current selection back to the launch default, unless +you explicitly override it with `--model`. + +## Refresh and remove + +Run the seed script again when Magpie's catalog changes, then restart Junie. +Junie discovers the local profiles; it does not poll Magpie itself. There is +no background refresh process. Missing catalog entries are removed only if +the seed script owns their files. The new launch default must exist in the catalog. +An empty, invalid, partial or unavailable catalog leaves the existing files +in place. A user edit to a generated profile is reported instead of overwritten. + +```sh +node "$JUNIE_SEED" +node "$JUNIE_SEED" --remove +magpie junie default +``` + +`--remove` removes generated profiles and restores unchanged settings using +`~/.junie/magpie/seed-state.json`. Unrelated settings, native profiles and +new discovery folders remain. ECO cleanup deletes only the generated models' +preference entries, preserving later edits to native models across repeated seeds. +Run one seed command at a time, with Junie +closed, to avoid concurrent settings writes. The journal and generated +profiles contain gateway credentials and are created with private permissions. + +Magpie restores the separate connection file's managed keys when disconnected. +That file is not a model profile and does not appear in Junie's picker. +Disconnecting Magpie alone leaves the seeded profiles and discovery directory +installed. Run `seed.mjs --remove` first to remove them and restore the launch settings. + +## ECO mode and limitations + +`--eco on|off` saves per-model preferences in `ecoModePerModel` and +`acpEcoModePerModel`, preserving other models' preferences. Without this +option, existing preferences are kept and new profiles get an `on` preference. + +**Native ECO is unavailable for custom profiles in Junie 3893.6.** Saving +`on` does not enable it, and it is not equivalent to lowering reasoning +effort. In that build, `ModelOption.Custom` inherits an empty +`ecoModeEfforts` set, so the ECO availability gate rejects it. The ACP model +picker confirms that a custom model has no ECO option. This is a Junie +capability limit, not a setting the plugin can override. + +The agent module uses Junie's default `~/.junie` paths, including Library +instructions, MCP and skills. The seed script honors `JUNIE_HOME`; when +using a relocated Junie home, provide its `magpie/connection.json` first. +Project configuration and CLI flags can override user defaults. Keep Magpie +running while using the generated models. + +## Validation + +```sh +bun test packages/junie/junie.test.mjs +``` + +References: [custom models](https://junie.jetbrains.com/docs/custom-llm-models.html), +[configuration](https://junie.jetbrains.com/docs/junie-cli-configuration.html), +[Cowork seed](../cowork/seed.mjs), and the +[agent contract](https://github.com/yetone/magpie/blob/main/internal/agent/plugged.go). +The agent uses the [official Junie website icon](https://junie.jetbrains.com/favicons/favicon.svg). diff --git a/packages/junie/junie.agent.js b/packages/junie/junie.agent.js new file mode 100644 index 0000000..f9df7d3 --- /dev/null +++ b/packages/junie/junie.agent.js @@ -0,0 +1,28 @@ +// Keep the gateway and Magpie's selection outside Junie's model discovery. +// The seed script writes ordinary model profiles and the launch selector. +export const agent = { + id: "junie", + name: "Junie CLI", + icon: "https://junie.jetbrains.com/favicons/favicon.svg", + bin: "junie", + dir: "~/.junie", + config: "~/.junie/magpie/connection.json", + format: "json", + model: "id", + ua: ["junie"], + notice: "Re-run the package's seed.mjs after changing the model in Magpie or its catalog, then restart Junie. Native ECO is unavailable for custom profiles in Junie 3893.6.", + library: { + instructions: "~/.junie/AGENTS.md", + mcp: "~/.junie/mcp/mcp.json", + mcpFormat: "claude", + skills: "~/.junie/skills", + }, +} + +export function connect({ gateway }) { + return { + baseUrl: gateway.v1.replace(/\/$/, "") + "/chat/completions", + apiType: "OpenAICompletion", + apiKey: gateway.key, + } +} diff --git a/packages/junie/junie.test.mjs b/packages/junie/junie.test.mjs new file mode 100644 index 0000000..d2e9c5e --- /dev/null +++ b/packages/junie/junie.test.mjs @@ -0,0 +1,253 @@ +import { expect, test, afterEach } from "bun:test" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import http from "node:http" +import { once } from "node:events" +import { agent, connect } from "./junie.agent.js" +import { seed, removeSeed, catalog, profileID } from "./seed.mjs" + +const roots = [] +afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }) }) +const read = file => JSON.parse(fs.readFileSync(file, "utf8")) +const put = (file, value) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(value)) } +const gateway = { url: "http://127.0.0.1:3425", v1: "http://127.0.0.1:3425/v1", key: "test-agent-key" } +const models = [ + { id: "provider/alpha", display_name: "Alpha", context_length: 200000 }, + { id: "group/beta", display_name: "Beta", context_length: 0 }, +] + +function fixture({ fetchImpl = async () => Response.json({ data: models }), settings = {}, config = {} } = {}) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "junie-seed-test-")); roots.push(root) + const junieHome = path.join(root, ".junie") + const sourceFile = path.join(junieHome, "magpie", "connection.json") + const settingsFile = path.join(junieHome, "settings.json"), configFile = path.join(junieHome, "config.json") + const modelsDir = path.join(junieHome, "magpie", "models") + put(sourceFile, { id: models[0].id, ...connect({ gateway, model: { context: 200000 } }) }) + put(settingsFile, settings) + put(configFile, config) + return { junieHome, modelsDir, sourceFile, settingsFile, configFile, options: { junieHome, fetchImpl } } +} + +test("the agent writes connection metadata outside Junie's discovered profiles", async () => { + expect(agent).toMatchObject({ id: "junie", config: "~/.junie/magpie/connection.json", model: "id", format: "json" }) + expect(connect({ gateway, model: { context: 200000 } })).toEqual({ + baseUrl: "http://127.0.0.1:3425/v1/chat/completions", apiType: "OpenAICompletion", apiKey: "test-agent-key", + }) + expect(connect({ gateway: { ...gateway, v1: gateway.v1 + "/" }, model: { context: 0 } })).not.toHaveProperty("maxContextLength") + const pkg = await Bun.file(new URL("./package.json", import.meta.url)).json() + expect(pkg).not.toHaveProperty("main") + expect(pkg.magpie.agent).toBe("./junie.agent.js") + expect(agent.icon).toBe("https://junie.jetbrains.com/favicons/favicon.svg") + expect(pkg.magpie.icon).toBe(agent.icon) +}) + +test("profiles preserve wire IDs and omit unknown limits", () => { + const profiles = catalog({ data: models }, { baseUrl: gateway.v1 + "/chat/completions", apiKey: gateway.key }) + expect(profiles.get("provider/alpha")).toEqual({ + id: "provider/alpha", baseUrl: "http://127.0.0.1:3425/v1/chat/completions", apiType: "OpenAICompletion", + apiKey: "test-agent-key", displayName: "Alpha · Magpie", providerName: "Magpie", maxContextLength: 200000, + }) + expect(profiles.get("group/beta")).not.toHaveProperty("maxContextLength") + expect(profileID("provider/alpha")).toMatch(/^magpie-[a-f0-9]{24}$/) + expect(profileID("provider/alpha")).not.toBe(profileID("provider_alpha")) +}) + +test("seeds the full catalog, discovery folder, launch default and ECO preferences", async () => { + const f = fixture({ settings: { theme: "dark", providerForLaunch: "openai", mixForLaunch: "old" }, config: { brave: false, "model-locations": ["./other"] } }) + const originalProfile = fs.readFileSync(f.sourceFile, "utf8") + expect(await seed(f.options)).toMatchObject({ models: 2, selected: `custom:${profileID("provider/alpha")}`, eco: "unavailable_for_custom_profiles" }) + expect(fs.readdirSync(f.modelsDir).sort()).toEqual(models.map(m => profileID(m.id) + ".json").sort()) + expect(read(path.join(f.modelsDir, profileID(models[0].id) + ".json")).id).toBe("provider/alpha") + expect(read(f.configFile)).toEqual({ brave: false, "model-locations": ["./other", f.modelsDir] }) + const settings = read(f.settingsFile) + expect(settings.modelForLaunch).toBe(`custom:${profileID("provider/alpha")}`) + expect(settings.onboardingDefaultModelChosen).toBe("true") + expect(settings.theme).toBe("dark") + expect(settings).not.toHaveProperty("providerForLaunch") + expect(settings).not.toHaveProperty("mixForLaunch") + expect(JSON.parse(settings.ecoModePerModel)).toEqual(Object.fromEntries(models.map(m => [`custom:${profileID(m.id)}`, "on"]))) + expect(JSON.parse(settings.acpEcoModePerModel)).toEqual(JSON.parse(settings.ecoModePerModel)) + expect(fs.readFileSync(f.sourceFile, "utf8")).toBe(originalProfile) + expect(fs.existsSync(path.join(f.junieHome, "models", "magpie.json"))).toBe(false) + removeSeed(f.junieHome) + expect(read(f.settingsFile)).toEqual({ theme: "dark", providerForLaunch: "openai", mixForLaunch: "old" }) + expect(read(f.configFile)).toEqual({ brave: false, "model-locations": ["./other"] }) + expect(fs.readdirSync(f.modelsDir)).toEqual([]) + expect(fs.readFileSync(f.sourceFile, "utf8")).toBe(originalProfile) +}) + +test("copies Magpie's selection to the launch default on every sync and allows an explicit override", async () => { + const f = fixture() + await seed({ ...f.options, model: "group/beta", eco: "off" }) + expect(read(f.settingsFile).modelForLaunch).toBe(`custom:${profileID("group/beta")}`) + const settings = read(f.settingsFile) + settings.modelForLaunch = "my-native-model" + settings.ecoModePerModel = JSON.stringify({ unrelated: "off", [`custom:${profileID("group/beta")}`]: "off" }) + put(f.settingsFile, settings) + await seed(f.options) + expect(read(f.settingsFile).modelForLaunch).toBe(`custom:${profileID("provider/alpha")}`) + expect(JSON.parse(read(f.settingsFile).ecoModePerModel)).toMatchObject({ unrelated: "off", [`custom:${profileID("group/beta")}`]: "off" }) + put(f.sourceFile, { ...read(f.sourceFile), id: "group/beta" }) + await seed(f.options) + expect(read(f.settingsFile).modelForLaunch).toBe(`custom:${profileID("group/beta")}`) +}) + +test("preserves new native preferences and discovery folders when removing the seed", async () => { + const f = fixture({ settings: { modelForLaunch: "old-native" } }) + await seed(f.options) + put(f.settingsFile, { ...read(f.settingsFile), modelForLaunch: "new-native", theme: "light" }) + put(f.configFile, { ...read(f.configFile), "model-locations": [f.modelsDir, "./new-folder"] }) + removeSeed(f.junieHome) + expect(read(f.settingsFile)).toEqual({ modelForLaunch: "new-native", theme: "light" }) + expect(read(f.configFile)["model-locations"]).toEqual(["./new-folder"]) + expect(fs.readdirSync(f.modelsDir)).toEqual([]) +}) + +test("failed, invalid, empty and partial catalogs preserve the previous files", async () => { + let payload = { data: models }, status = 200 + const f = fixture({ fetchImpl: async () => Response.json(payload, { status }) }) + await seed(f.options) + const before = fs.readFileSync(f.settingsFile, "utf8") + for (const next of [{ data: [] }, { data: [models[0], models[0]] }, { data: [null] }, { data: models, has_more: true }]) { + payload = next + await expect(seed(f.options)).rejects.toThrow() + expect(fs.readFileSync(f.settingsFile, "utf8")).toBe(before) + expect(fs.readdirSync(f.modelsDir).length).toBe(2) + } + status = 503 + await expect(seed(f.options)).rejects.toThrow("HTTP 503") + expect(fs.readFileSync(f.settingsFile, "utf8")).toBe(before) +}) + +test("rejects an unavailable requested default before writing", async () => { + const f = fixture() + await expect(seed({ ...f.options, model: "absent/model" })).rejects.toThrow("absent") + expect(read(f.settingsFile)).toEqual({}) + expect(fs.existsSync(f.modelsDir)).toBe(false) +}) + +test("does not overwrite malformed settings or user edits to generated profiles", async () => { + const f = fixture({ settings: { ecoModePerModel: "broken-json" } }) + const before = fs.readFileSync(f.settingsFile, "utf8") + await expect(seed(f.options)).rejects.toThrow() + expect(fs.existsSync(f.modelsDir)).toBe(false) + expect(fs.readFileSync(f.settingsFile, "utf8")).toBe(before) + put(f.settingsFile, {}) + await seed(f.options) + const file = path.join(f.modelsDir, profileID("provider/alpha") + ".json") + put(file, { manual: true }) + await expect(seed(f.options)).rejects.toThrow("profile_changed") + expect(read(file)).toEqual({ manual: true }) + const current = fs.readFileSync(f.settingsFile, "utf8") + expect(() => removeSeed(f.junieHome)).toThrow("profile_changed") + expect(fs.readFileSync(f.settingsFile, "utf8")).toBe(current) +}) + +test("an interrupted default update does not claim a user's preceding native selection", async () => { + const f = fixture({ settings: { modelForLaunch: "original-native" } }) + await seed(f.options) + put(f.settingsFile, { ...read(f.settingsFile), modelForLaunch: "new-native" }) + const rename = fs.renameSync + try { + fs.renameSync = (from, to) => { + if (to === f.settingsFile) throw Error("interrupted_write") + return rename(from, to) + } + await expect(seed({ ...f.options, model: "group/beta" })).rejects.toThrow("interrupted_write") + } finally { fs.renameSync = rename } + removeSeed(f.junieHome) + expect(read(f.settingsFile).modelForLaunch).toBe("new-native") + expect(fs.readdirSync(f.modelsDir)).toEqual([]) +}) + +test("prunes obsolete generated profiles after selecting Magpie's current default and preserves unrelated profiles", async () => { + let rows = models + const f = fixture({ fetchImpl: async () => Response.json({ data: rows }) }) + await seed({ ...f.options, model: "group/beta" }) + const native = path.join(f.junieHome, "models", "mine.json") + put(native, { id: "mine" }) + rows = [models[0]] + await seed(f.options) + expect(read(f.settingsFile).modelForLaunch).toBe(`custom:${profileID("provider/alpha")}`) + expect(fs.readdirSync(f.modelsDir)).toEqual([profileID(models[0].id) + ".json"]) + removeSeed(f.junieHome) + expect(read(native)).toEqual({ id: "mine" }) +}) + +test("repeated sync is idempotent and removal recovers a previous seed journal", async () => { + const f = fixture({ settings: { modelForLaunch: "native", theme: "dark" } }) + await seed(f.options) + const before = fs.readFileSync(f.settingsFile, "utf8") + const journal = fs.readFileSync(path.join(f.junieHome, "magpie", "seed-state.json"), "utf8") + await seed(f.options) + expect(fs.readFileSync(f.settingsFile, "utf8")).toBe(before) + expect(fs.readFileSync(path.join(f.junieHome, "magpie", "seed-state.json"), "utf8")).toBe(journal) + removeSeed(f.junieHome) + removeSeed(f.junieHome) + expect(read(f.settingsFile)).toEqual({ modelForLaunch: "native", theme: "dark" }) +}) + +test("removal never restores a default that refers to a removed generated profile", async () => { + const f = fixture({ settings: { modelForLaunch: `custom:${profileID("provider/alpha")}` } }) + await seed(f.options) + put(f.sourceFile, { ...read(f.sourceFile), id: "group/beta" }) + await seed(f.options) + removeSeed(f.junieHome) + expect(read(f.settingsFile)).not.toHaveProperty("modelForLaunch") + expect(fs.readdirSync(f.modelsDir)).toEqual([]) +}) + +test("removal clears a matching generated launch default even if seeding never changed its value", async () => { + const f = fixture({ settings: { modelForLaunch: `custom:${profileID("provider/alpha")}` } }) + await seed(f.options) + removeSeed(f.junieHome) + expect(read(f.settingsFile)).not.toHaveProperty("modelForLaunch") + expect(fs.readdirSync(f.modelsDir)).toEqual([]) +}) + +test("removal preserves unrelated ECO edits across reseeding and removes all generated preferences", async () => { + const fields = ["ecoModePerModel", "acpEcoModePerModel"] + const f = fixture({ settings: Object.fromEntries(fields.map(field => [field, JSON.stringify({ native: "off" })])) }) + await seed(f.options) + const settings = read(f.settingsFile) + for (const field of fields) settings[field] = JSON.stringify({ ...JSON.parse(settings[field]), native: "on" }) + put(f.settingsFile, settings) + await seed({ ...f.options, eco: "off" }) + removeSeed(f.junieHome) + for (const field of fields) expect(JSON.parse(read(f.settingsFile)[field])).toEqual({ native: "on" }) +}) + +test("removal preserves ECO edits after the final seed without orphaned generated keys", async () => { + const fields = ["ecoModePerModel", "acpEcoModePerModel"] + const f = fixture() + await seed(f.options) + const settings = read(f.settingsFile) + for (const field of fields) settings[field] = JSON.stringify({ ...JSON.parse(settings[field]), native: "on" }) + put(f.settingsFile, settings) + removeSeed(f.junieHome) + for (const field of fields) expect(JSON.parse(read(f.settingsFile)[field])).toEqual({ native: "on" }) +}) + +test("removal retains preexisting empty ECO maps and drops maps first created by the seed", async () => { + const f = fixture({ settings: { ecoModePerModel: "{}" } }) + await seed(f.options) + removeSeed(f.junieHome) + expect(read(f.settingsFile)).toEqual({ ecoModePerModel: "{}" }) +}) + +test("reads /v1/models over HTTP with Junie's own credential and User-Agent", async () => { + const requests = [] + const server = http.createServer((req, res) => { + requests.push({ url: req.url, auth: req.headers.authorization, ua: req.headers["user-agent"] }) + res.setHeader("Content-Type", "application/json") + res.end(JSON.stringify({ data: models })) + }).listen(0, "127.0.0.1") + await once(server, "listening") + const f = fixture({ fetchImpl: globalThis.fetch }) + put(f.sourceFile, { ...read(f.sourceFile), baseUrl: `http://127.0.0.1:${server.address().port}/v1/chat/completions` }) + try { + expect(await seed(f.options)).toMatchObject({ models: 2 }) + expect(requests).toEqual([{ url: "/v1/models", auth: "Bearer test-agent-key", ua: "Junie" }]) + } finally { server.closeAllConnections(); server.close() } +}) diff --git a/packages/junie/package.json b/packages/junie/package.json new file mode 100644 index 0000000..255f594 --- /dev/null +++ b/packages/junie/package.json @@ -0,0 +1,17 @@ +{ + "name": "@magpie-community/agent-junie", + "version": "0.1.0", + "description": "Junie CLI with Magpie's full model catalog, launch defaults and ECO preferences", + "type": "module", + "files": ["junie.agent.js", "seed.mjs", "README.md", "LICENSE"], + "keywords": ["magpie", "magpie-agent", "junie", "jetbrains", "llm-gateway"], + "license": "MIT", + "engines": { "node": ">=18" }, + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/junie" + }, + "scripts": { "test": "bun test", "seed": "node seed.mjs" }, + "magpie": { "agent": "./junie.agent.js", "icon": "https://junie.jetbrains.com/favicons/favicon.svg" } +} diff --git a/packages/junie/seed.mjs b/packages/junie/seed.mjs new file mode 100644 index 0000000..3dc69dc --- /dev/null +++ b/packages/junie/seed.mjs @@ -0,0 +1,249 @@ +import fs from "node:fs" +import path from "node:path" +import os from "node:os" +import { randomUUID, createHash } from "node:crypto" +import { pathToFileURL } from "node:url" +import { parseArgs } from "node:util" + +function read(file) { + try { return fs.readFileSync(file, "utf8") } + catch (error) { if (error.code !== "ENOENT") throw error } +} + +function document(raw, name) { + const value = raw === undefined ? {} : JSON.parse(raw) + if (!value || typeof value !== "object" || Array.isArray(value)) throw Error(`${name}: expected an object`) + return value +} + +function write(file, raw, expected = read(file)) { + if (raw === expected) return + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }) + const temporary = `${file}.${randomUUID()}.tmp` + try { + fs.writeFileSync(temporary, raw, { flag: "wx", mode: 0o600 }) + if (read(file) !== expected) throw Error("configuration_changed") + fs.renameSync(temporary, file) + } finally { + if (fs.existsSync(temporary)) fs.unlinkSync(temporary) + } +} + +const same = (a, b) => JSON.stringify(a) === JSON.stringify(b) +const ECO_FIELDS = ["ecoModePerModel", "acpEcoModePerModel"] +const valueAt = (doc, key) => Object.hasOwn(doc, key) ? { value: doc[key] } : {} +const put = (doc, key, slot) => { + if (Object.hasOwn(slot, "value")) doc[key] = slot.value + else delete doc[key] +} + +// The journal is written before each effect. Both the previous and pending +// value are recognized after a crash; a third value belongs to the user. +class Files { + constructor(file) { + this.file = file + this.state = document(read(file), "journal") + this.state.profiles ??= {} + this.state.documents ??= {} + this.state.ecoFields ??= {} + } + + save() { write(this.file, JSON.stringify(this.state, null, 2) + "\n") } + + patch(file, changes) { + const raw = read(file), doc = document(raw, file) + const entries = this.state.documents[file] ??= {} + let changed = false + for (const [key, desired] of Object.entries(changes)) { + const current = valueAt(doc, key) + if (same(current, desired)) continue + const entry = entries[key] ??= { before: current } + entry.previous = entry.wrote + entry.wrote = desired + put(doc, key, desired) + changed = true + } + if (!changed) return + this.save() + write(file, JSON.stringify(doc, null, 2) + "\n", raw) + } + + ecoPreferences(file, selectors, eco, obsolete) { + const raw = read(file), doc = document(raw, file) + for (const field of ECO_FIELDS) { + const preferences = document(doc[field], field) + this.state.ecoFields[field] ??= Object.hasOwn(doc, field) + for (const selector of obsolete) delete preferences[selector] + for (const selector of selectors) { + if (eco !== undefined || !Object.hasOwn(preferences, selector)) preferences[selector] = eco ?? "on" + } + doc[field] = JSON.stringify(preferences) + } + // Only map presence is journaled. Native model preferences stay owned by + // Junie, including edits made between successive seeds. + this.save() + write(file, JSON.stringify(doc, null, 2) + "\n", raw) + } + + checkProfile(file) { + const current = read(file), entry = this.state.profiles[file] + if (current === undefined) return + if (!entry || (current !== entry.wrote && current !== entry.previous)) throw Error("profile_changed") + } + + profile(file, desired) { + this.checkProfile(file) + const raw = read(file) + if (raw === desired) return + this.state.profiles[file] = { previous: raw, wrote: desired } + this.save() + write(file, desired, raw) + } + + removeProfile(file) { + this.checkProfile(file) + if (read(file) !== undefined) fs.unlinkSync(file) + delete this.state.profiles[file] + this.save() + } + + restore({ settingsFile, modelsDir }) { + for (const file of Object.keys(this.state.profiles)) this.checkProfile(file) + const selectors = new Set(Object.keys(this.state.profiles).map(p => `custom:${path.basename(p, ".json")}`)) + for (const file of new Set([...Object.keys(this.state.documents), settingsFile])) { + const entries = this.state.documents[file] ?? {} + const raw = read(file), doc = document(raw, file) + for (const [key, entry] of Object.entries(entries)) { + const current = valueAt(doc, key) + if (same(current, entry.wrote) || same(current, entry.previous)) put(doc, key, entry.before) + // Other discovery locations added while connected remain in place. + else if (key === "model-locations" && Array.isArray(current.value) && !entry.before.value?.includes(modelsDir)) { + doc[key] = current.value.filter(p => p !== modelsDir) + } + } + if (file === settingsFile) { + // This also handles an unchanged default that needed no patch entry. + if (selectors.has(doc.modelForLaunch)) { + const before = entries.modelForLaunch?.before ?? {} + if (selectors.has(before.value)) delete doc.modelForLaunch + else put(doc, "modelForLaunch", before) + } + for (const [field, existed] of Object.entries(this.state.ecoFields)) { + if (!Object.hasOwn(doc, field)) continue + const preferences = document(doc[field], field) + for (const selector of selectors) delete preferences[selector] + if (!existed && !Object.keys(preferences).length) delete doc[field] + else doc[field] = JSON.stringify(preferences) + } + } + if (raw !== undefined) write(file, JSON.stringify(doc, null, 2) + "\n", raw) + } + for (const file of Object.keys(this.state.profiles)) this.removeProfile(file) + this.state = { profiles: {}, documents: {} } + this.save() + } +} + +export const profileID = id => "magpie-" + createHash("sha256").update(id).digest("hex").slice(0, 24) + +export function catalog(payload, source) { + if (!Array.isArray(payload?.data) || !payload.data.length || payload.has_more) throw Error("Invalid or empty gateway catalog") + const result = new Map() + for (const model of payload.data) { + if (typeof model?.id !== "string" || !model.id || result.has(model.id)) throw Error("Invalid or duplicate model ID") + const profile = { + id: model.id, + baseUrl: source.baseUrl, + apiType: "OpenAICompletion", + apiKey: source.apiKey, + displayName: `${model.magpie_label || model.display_name || model.id} · Magpie`, + providerName: "Magpie", + } + if (Number.isSafeInteger(model.context_length) && model.context_length > 0) profile.maxContextLength = model.context_length + result.set(model.id, profile) + } + return result +} + +function locations(junieHome) { + const root = path.resolve(junieHome) + return { + modelsDir: path.join(root, "magpie", "models"), + settingsFile: path.join(root, "settings.json"), + configFile: path.join(root, "config.json"), + stateFile: path.join(root, "magpie", "seed-state.json"), + } +} + +export async function seed({ junieHome, model, eco, fetchImpl = globalThis.fetch }) { + if (eco !== undefined && !["on", "off"].includes(eco)) throw Error("--eco must be on or off") + const at = locations(junieHome) + const source = document(read(path.join(junieHome, "magpie", "connection.json")), "connection.json") + if (source.apiType !== "OpenAICompletion" || typeof source.baseUrl !== "string" || + !source.baseUrl.endsWith("/chat/completions") || typeof source.id !== "string" || !source.id || typeof source.apiKey !== "string") { + throw Error("Connect Junie in Magpie before seeding its models") + } + const url = new URL(source.baseUrl.replace(/\/chat\/completions$/, "/models")) + if (!["http:", "https:"].includes(url.protocol)) throw Error("Unsupported gateway URL") + const response = await fetchImpl(url.href, { + headers: { Authorization: "Bearer " + source.apiKey, "User-Agent": "Junie", Accept: "application/json" }, + signal: AbortSignal.timeout(10000), redirect: "error", + }) + if (!response.ok) throw Error(`Gateway catalog returned HTTP ${response.status}`) + const models = catalog(await response.json(), source) + if (!models.has(model ?? source.id)) throw Error("The requested default model is absent from the gateway catalog") + const files = new Files(at.stateFile) + const settings = document(read(at.settingsFile), "settings.json") + const config = document(read(at.configFile), "config.json") + const discovery = config["model-locations"] ?? [] + if (!Array.isArray(discovery)) throw Error("model-locations must be an array") + const profiles = new Map([...models].map(([id, profile]) => [path.join(at.modelsDir, profileID(id) + ".json"), JSON.stringify(profile, null, 2) + "\n"])) + const selectors = [...models.keys()].map(id => `custom:${profileID(id)}`) + const selected = `custom:${profileID(model ?? source.id)}` + const changes = { + modelForLaunch: { value: selected }, + onboardingDefaultModelChosen: { value: "true" }, + providerForLaunch: {}, + mixForLaunch: {}, + } + for (const field of ECO_FIELDS) document(settings[field], field) + // Refuse collisions or user edits before any mutation. + for (const file of new Set([...profiles.keys(), ...Object.keys(files.state.profiles)])) files.checkProfile(file) + for (const [file, raw] of profiles) files.profile(file, raw) + const obsolete = Object.keys(files.state.profiles).filter(file => !profiles.has(file)) + if (!discovery.includes(at.modelsDir)) files.patch(at.configFile, { "model-locations": { value: [...discovery, at.modelsDir] } }) + files.patch(at.settingsFile, changes) + files.ecoPreferences(at.settingsFile, selectors, eco, obsolete.map(p => `custom:${path.basename(p, ".json")}`)) + for (const file of obsolete) files.removeProfile(file) + return { models: models.size, selected, eco: "unavailable_for_custom_profiles", modelsDir: at.modelsDir } +} + +export function removeSeed(junieHome) { + const at = locations(junieHome) + if (read(at.stateFile) === undefined) return + new Files(at.stateFile).restore(at) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + try { + const { values } = parseArgs({ options: { + model: { type: "string" }, eco: { type: "string" }, remove: { type: "boolean" }, help: { type: "boolean", short: "h" }, + } }) + if (values.help) console.log("Usage: node seed.mjs [--model provider/model] [--eco on|off] [--remove]\nSyncs Magpie's catalog into Junie. Native ECO is unavailable for custom profiles in Junie 3893.6.") + else { + const junieHome = process.env.JUNIE_HOME || path.join(os.homedir(), ".junie") + if (values.remove) { + if (values.model !== undefined || values.eco !== undefined) throw Error("--remove cannot be combined with --model or --eco") + removeSeed(junieHome) + console.log("Removed seeded profiles and restored unchanged launch settings. Magpie manages connection.json separately.") + } else { + const result = await seed({ junieHome, model: values.model, eco: values.eco }) + console.log(`Synced ${result.models} models to ${result.modelsDir}; launch model: ${result.selected}. Restart Junie to reload /model.`) + console.log("ECO preferences are saved. Native ECO is unavailable for custom profiles in Junie 3893.6; saving on does not enable it.") + } + } + } catch (error) { + console.error(error.message) + process.exitCode = 1 + } +} diff --git a/registry.json b/registry.json index 81734c6..bb37a56 100644 --- a/registry.json +++ b/registry.json @@ -99,6 +99,9 @@ "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/agent-opencodereview", "name": "Open Code Review", "kind": "agent", "community": true, "summary": { "en": "Open Code Review (Alibaba's ocr CLI) on magpie's Agents page: pick one of magpie's models and ocr review / ocr scan use it, read from the config on the next run.", "zh": "把 Open Code Review(阿里巴巴的 ocr CLI)加到 magpie 的 Agent 页:给它选 magpie 的模型,下一次 ocr review / ocr scan 即从配置中读到并生效。" } }, + { "package": "@magpie-community/agent-junie", "name": "Junie CLI", "kind": "agent", "community": true, + "icon": "https://junie.jetbrains.com/favicons/favicon.svg", + "summary": { "en": "An explicit seed copies Magpie's full model catalog into Junie CLI and uses Magpie's selected model as the launch default, without LiteLLM. Native ECO is unavailable for custom profiles in Junie 3893.6.", "zh": "手动 seed 向 Junie CLI 同步全部模型,并将 Magpie 所选模型设为启动默认模型,无需 LiteLLM。Junie 3893.6 的自定义 profile 不支持原生 ECO。" } }, { "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-search1api", "name": "Search1API", "icon": "https://s1.dev/icon.png", "kind": "tools", "community": true,