diff --git a/README.md b/README.md index 096aa726e..7744edd3e 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ magpie finds the subscriptions your agents are signed in to by reading their sig
-Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · OpenPencil · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot +Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · OpenPencil · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot
diff --git a/README.zh-CN.md b/README.zh-CN.md index 51d5e14d2..64f8bd9f0 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -78,7 +78,7 @@ magpie 通过读取智能体的登录信息(Claude Code 和 Codex 的文件、
-Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · OpenPencil · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot +Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · OpenPencil · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot
diff --git a/docs/reference.md b/docs/reference.md index 94113cd30..fe0d0a3f8 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -100,6 +100,7 @@ line; agents connected to magpie lose it when it quits. | Pi | `~/.pi/agent/settings.json` | model | | StepCode | `~/.stepcode/config.toml` (+ `models.json`; `$STEP_CODING_AGENT_DIR`, `$STEPCODE_CONFIG_DIR`) | model | | MothX | `~/.mothx/settings.json` (`$MOTHX_DIR`; `%APPDATA%\mothx` on Windows) | model, thinking (`defaultProvider`/`defaultModel`/`defaultThinkingLevel`; magpie as the provider `magpie` beside the user's own, `openai-chat` with `thinkingFormat: "openai"`) | +| PenguinHarness | `~/.penguin/data/default_project/.project_config.toml` (`$PENGUIN_HOME`, `$PENGUIN_PROJECT_ID`; the same on Windows) | model (`default_model`; magpie as `[providers.magpie]`, `openai-responses`, and its models as `[[models]]` entries of that provider) | | Aside | `~/.aside/u/0/settings.json` (+ `models.json`; the first account, the only one magpie wires) | model, effort, fast, standard, deep, visual, image | | OmO (omo-ai) | `~/.omo/agent/settings.json` (+ `models.json`; `$OMO_CODING_AGENT_DIR`, `$SENPI_CODING_AGENT_DIR`) | model | | Prime Agent | `~/.prime/agent/settings.json` (+ `models.json`; `$PRIME_AGENT_CODING_AGENT_DIR`) | model, thinking (Pi's fields; its key `magpie-prime-agent` names it, since its requests carry no User-Agent; the global settings alone, `allowedModels` and `subagentDefaultModel` left as they are) | @@ -150,7 +151,7 @@ line; agents connected to magpie lose it when it quits. | Alma | Alma's local API (`localhost:23001`, while Alma runs; alma-server's data in `$ALMA_DATA_DIR`, `$XDG_DATA_HOME/alma` or `~/.local/share/alma` on Linux) | model (Alma's default; magpie's models as a provider), and Image Generation's model when it is Auto: the one magpie draws with | | Lody | Its own confirmation dialog (`lody://provider/import`) | adds selected Claude, Codex, Pi, DSH, Kimi Code, Grok and Bub Providers on the local machine; no settings edited by magpie | -Provider-scoped agents (OpenCode, MiMo Code, DevEco Code, Pi, OmO, StepCode, MothX, Aside, Goose, Crush, omp, Hermes Agent) take `provider/model`. +Provider-scoped agents (OpenCode, MiMo Code, DevEco Code, Pi, OmO, StepCode, MothX, PenguinHarness, Aside, Goose, Crush, omp, Hermes Agent) take `provider/model`. Only agents that are installed or configured are shown. ### Notes on some agents @@ -165,6 +166,10 @@ The optional real CLI verification test is run with `MAGPIE_TEST_STEPCODE_BIN=/p MothX (oschina/mothx, formerly vibecoding) is configured via [`mothx.go`](../internal/agent/mothx.go). Magpie writes its provider `magpie` into `providers` in MothX's global `settings.json` (`$MOTHX_DIR`, else `%APPDATA%\mothx` on Windows, else `~/.mothx`) and sets `defaultProvider`, `defaultModel` and `defaultThinkingLevel`. The provider uses `openai-chat` with `thinkingFormat: "openai"`, so a thinking level goes out as `reasoning_effort` for every model; without it MothX guesses Qwen's or DeepSeek's thinking fields from a model id. What the user adds to magpie's block (headers, a `thinkingFormat` of their own) stays. The key `magpie-mothx` names it, and so does its User-Agent (`Vibecoding Client/`). A project's `.mothx/settings.json` overlays the global one and is left alone. MothX reads its settings at start-up, so restart open `mothx` sessions after a change. Disconnect puts `settings.json` back byte for byte when nothing else changed in it; when MothX or the user changed it meanwhile (its `/model` and `/statusline … global` write the whole file), Disconnect takes out only magpie's provider, its pick and a `providers` object it left empty. +#### PenguinHarness + +PenguinHarness (Prism-Shadow/penguin-harness, the `penguin` command, npm `@prismshadow/penguin-cli`) is configured via [`penguin.go`](../internal/agent/penguin.go). It keeps each Project's models in `//.project_config.toml`, the root being `$PENGUIN_HOME`, else `~/.penguin/data` on every system, and the Project the CLI works in `$PENGUIN_PROJECT_ID`, else `default_project`. Magpie writes `[providers.magpie]` (`openai-responses`, so a thinking level goes out as `reasoning.effort`; the key `magpie-penguin` names it), one `[[models]]` entry per model of magpie's with its name, window, reply cap, whether it reads images and its price, and points `default_model` at one. The user's own models, the command policy and the rest stay. Penguin's server reads the file again when it changes, so no restart is needed; a sync with nothing new leaves the file alone. A file magpie made is private (0600), as Penguin keeps its own, and goes again on Disconnect; otherwise Disconnect takes out magpie's provider, its entries and a vision model among them, and puts back the user's own default. Its User-Agent is the OpenAI SDK's, so usage names it by its key. Installed with `curl -fsSL https://penguin.ooo/install.sh | sh` (`irm https://penguin.ooo/install.ps1 | iex` on Windows); an install.sh tarball updates with `penguin update --yes`, an npm one with npm. + #### Reasonix Studio Reasonix Studio is detected from its desktop installation or a native Go diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index bf40f7a69..1a511788e 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -119,6 +119,7 @@ something else shows up as drift. - A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. An object or array `connect` returns is taken as its JSON text (`agentplug.keys`), so it is written in the order the plugin gave it, not sorted as a Go map would be: Kilo lists its effort variants in key order (#1890, `TestPluggedKeepsPluginOrder`). What each key held before the first write is stashed under `plugin::`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). Its `agent.library` (instructions, `mcp` with `mcpFormat`, skills) gives it the Library's three as well, written by `internal/library` as any agent's are ([library](library.md)); a `mcpFormat` outside `agentplug.MCPFormats`, or an `mcp` without one, keeps the plugin from loading. - StepCode config root resolves to the parent of an absolute `STEP_CODING_AGENT_DIR` (agent resources directory differs from config root; relative values ignored), or `STEPCODE_CONFIG_DIR` under home when native, defaulting to `~/.stepcode` ([`stepcode.go`](../../internal/agent/stepcode.go)). Project configs override global configs in StepCode, but magpie manages global configuration only (`config.toml` and `models.json`). Detection is strictly directory-only via `agentDir`, avoiding collision with Smallstep's bare `step` command on `PATH`. Wiring performs an atomic two-file edit (`models.json` provider block and `config.toml` top-level defaults/scope) backed by `stash.json`. Custom fields within `providers.magpie` are preserved during sync, and the original provider block is restored on disconnect. A renamed provider's `magpie//` entries in `enabledModels` follow it, a glob or a thinking level included, and the scope remembered for disconnect follows too; the user's other entries stay. Disconnect restores original defaults, preserves user native changes and custom scope edits, and removes newly created files only when empty. - MothX's folder is `$MOTHX_DIR` as it is (no `~`), else `%APPDATA%\mothx` on Windows, else `~/.mothx`; a WSL distro's is its `~/.mothx` ([`mothx.go`](../../internal/agent/mothx.go)). Its `thinkingFormat` is `openai` unless the user set one: with it empty, MothX picks Qwen's `enable_thinking`, DeepSeek's `thinking` or Doubao's levels by the model id, which for magpie's ids says nothing of the vendor that serves them. MothX's `/model` and `/statusline … global` rewrite the whole file, so Disconnect after one takes out magpie's provider, the pick and a `providers` left empty (MothX omits an empty one), and keeps the rest. +- PenguinHarness's file is `$PENGUIN_HOME` (else `~/.penguin/data`, on Windows too) `//.project_config.toml`, the Project `$PENGUIN_PROJECT_ID` when it is a folder's name (`agentenv.NotPaths`, so a relative name isn't dropped as a path), else `default_project`; a WSL distro's is its `~/.penguin/data/default_project` ([`penguin.go`](../../internal/agent/penguin.go)). Magpie's models are `[[models]]` array entries with `provider = "magpie"`, replaced together where the first one was by `edit.SetTOMLArrayTables`, which leaves the user's entries, the blank lines between them and the file's time alone when nothing changed (Penguin's server reads the file again on every mtime change). `default_model` is spelled `{ provider = …, model_id = … }` as Penguin's own writer (smol-toml) spells it; that writer rewrites the whole file, so Disconnect takes out magpie's provider, entries and a vision model on them rather than putting back a copy. A default naming no entry is refused by Penguin, so entries go in before `default_model` and out after it. - Zoo Code's provider profiles are in VS Code's secret storage, so magpie writes a settings file for it (`magpie-import.json` in Zoo Code's `globalStorage/zoocodeorganization.zoo-code/settings`, not magpie's folder, so a sync keeps an address the user moved it to) and points Zoo Code's `zoo-code.autoImportSettingsPath` at it in VS Code's `settings.json` and each profile's, a user's own path stashed and put back ([`zoocode.go`](../../internal/agent/zoocode.go)). Zoo Code imports it on each start (`importSettingsFromPath`), merging it over the user's profiles and making `magpie` the current one. Disconnect stops the import and deletes the file; the profile already imported stays in Zoo Code, where magpie can't reach it. - An agent is detected by its config file, its folder, or its command on magpie's PATH (`Detected`). That PATH is the login shell's plus the folders users' tools go in (`proc.UserPath`: `~/.local/bin`, npm's prefixes, the Node nvm's default alias resolves to (the highest installed when it names none), bun, Homebrew, ...), so a CLI a terminal doesn't find can still be found and listed: an npm install under a Node the terminal no longer uses. `/api/agents/cli` then gives where it is (`path`) and `offPath` when the login shell's PATH (`proc.LoginPath`) lacks its folder, and the Agents row says "Not on your terminal's PATH", its tip naming the file (悠悠哥 on Discord: Codex 0.162.1 listed with no codex on PATH and no `~/.codex`). An unknown login PATH says nothing. A folder another tool writes too doesn't count (`dirShared`): Pi's for omp, `~/.copilot` for the Copilot CLI, which GitHub Copilot's JetBrains and VS Code plugins also write, and Qoder's and Qoder CN's, which Qoder's JetBrains plugin fills, and `~/.cursor` for Cursor CLI, which the Cursor editor makes on its own (`TestCursorFolderFromTheEditorIsNotTheCLI`, @G_Z_Y on X); only `cli-config.json` or `cursor-agent` finds Cursor CLI. A config file another tool writes first counts only when `pathOwn` says it is the agent's: Qoder's `settings.json` holding `enabledPlugins` alone is the plugin's (`qoderPluginOnly`; #1495, `TestCopilotFolderFromAnIDEPluginIsNotTheCLI`, `TestQoderSettingsFromAnIDEPluginIsNotTheCLI`). The Qoder app (the desktop app, which runs Qoder's CLI as its agent with the same folder) is found by the `.qoder-app-status.json` it writes there (`sign`, `qoderApp`; #2138, `TestQoderAppIsQoder`), as its `settings.json` can be its bundled plugin's `enabledPlugins` alone. Only the GUI and `daemon install` widen the PATH so; `magpie serve`, `web`, `tui` and the CLI keep the one they were started with, so an agent's CLI (`cliBin`, which its version and `omp`'s max effort are read from) is looked for in those folders (`proc.FindTool`) on every system when it isn't on the PATH, not only on Windows (whqtian on Discord: omp under `~/.bun/bin` on Ubuntu read as no version and offered xhigh in place of max; `TestOmpVersionOffPath`). - Detection goes by an agent's folder, which an uninstall leaves behind, so an agent found by that alone is shown as gone (`CLIMissing`; #843, #2177, #2173): its CLI is on no PATH and in none of `proc.FindTool`'s folders nor where its own installer puts it (`~/.claude/local`, `~/.codex/packages/standalone`, `~/.opencode/bin`, Hermes' `hermes-agent` checkout), and nothing else that reads the folder is here (`cliHeld`): its desktop app (`HasApp`), an editor's extension (`~/./extensions/-*`: `anthropic.claude-code`, `openai.chatgpt`, `saoudrizwan.claude-dev`), Claude.app, OpenCode.app and Goose.app on a Mac, a JetBrains IDE's settings (its AI Assistant's agents and Cline's plugin) or Zed's `external_agents` (its Claude Code and Codex adapters). Where magpie can't tell (every shared folder, `cliShared`, on Windows, whose readers can be a Store app, a portable editor or a PATH only a shell profile sets, #1482, and there too one a desktop app of the agent's reads, `desktopApps`: DeepSeek Harness Desktop installs to any folder and puts its `dsh.cmd` in one the user picks, #2300, #2304; OpenCode and Goose off a Mac, Gemini, an agent detected its own way or by a command name other tools share, one with no install command but `cliOnly`'s Hermes), it is never gone. A gone row in the GUI shows "CLI not found" and none of its settings, nor Apply again; while connected it keeps its switch and Disconnect, and it folds under Not set up once not. Get started never offers it (`connectKind` is "no"). The TUI leaves it out and `magpie ls` says "CLI not found" (`TestCLIMissing*`, `agent-cli-missing.test.cjs`, `getting-started.test.cjs`). @@ -129,6 +130,7 @@ something else shows up as drift. ```sh go test -tags nogui ./internal/agent -run '^TestStepCode' go test -tags nogui ./internal/agent -run '^TestMothX' +go test -tags nogui ./internal/agent -run '^TestPenguin' go test -tags nogui ./internal/agent -run 'TestClaudeAutoModeReview|TestClaudeReviewedOnlyWhereMessagesReachClaude|TestT3CodeAutoModeReview|TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress' go test -tags nogui ./internal/agent go test -tags nogui ./internal/agent -run '^TestAir' diff --git a/internal/agent/agents.go b/internal/agent/agents.go index c16febfde..9c47c7c53 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -107,6 +107,7 @@ func builtins(home, cfg string) []*Agent { pi(home), stepcode(home), mothx(home), + penguin(home), aside(home), omo(home), primeAgent(home), diff --git a/internal/agent/cliupdate.go b/internal/agent/cliupdate.go index dcebb7e47..c50209f10 100644 --- a/internal/agent/cliupdate.go +++ b/internal/agent/cliupdate.go @@ -187,6 +187,21 @@ var cliSpecs = map[string]cliSpec{ // MothX: its npm installer package, which brings the native binary // for the platform as an optional dependency "mothx": {npm: []string{"mothx-installer"}}, + // PenguinHarness: its npm package, or install.sh's tarball in + // ~/.penguin (bin, lib, node; ~/.local/bin/penguin links there), which + // penguin update re-runs the installer for. On Windows its update + // refuses a tarball (update.ts planUpdate, "windows-installer"), so + // none is offered there. + "penguin": {npm: []string{"@prismshadow/penguin-cli"}, + self: func(bin, real string) []string { + if runtime.GOOS == "windows" { + return nil + } + if l := strings.ToLower(real); strings.Contains(l, "/.penguin/bin/") || strings.Contains(l, "/.penguin/lib/") { + return []string{bin, "update", "--yes"} + } + return nil + }}, // omo update, however it was installed: OmO's own updater, which moves // the engine it pins (senpi) with it "omo": {npm: []string{"omo-ai"}, diff --git a/internal/agent/install.go b/internal/agent/install.go index 526cc6891..13f42b427 100644 --- a/internal/agent/install.go +++ b/internal/agent/install.go @@ -80,6 +80,14 @@ var vendorInstall = map[string]func(goos string) []InstallCmd{ } return []InstallCmd{{Via: "script", Command: "curl -fsSL https://chatgpt.com/codex/install.sh | sh"}} }, + // PenguinHarness's (penguin.ooo; its README): a tarball in ~/.penguin + // that brings its own Node.js, which it needs at 24 or later + "penguin": func(goos string) []InstallCmd { + if goos == "windows" { + return []InstallCmd{{Via: "powershell", Command: "irm https://penguin.ooo/install.ps1 | iex"}} + } + return []InstallCmd{{Via: "script", Command: "curl -fsSL https://penguin.ooo/install.sh | sh"}} + }, "gemini": func(goos string) []InstallCmd { if goos == "windows" { return nil diff --git a/internal/agent/penguin.go b/internal/agent/penguin.go new file mode 100644 index 000000000..d9b74859e --- /dev/null +++ b/internal/agent/penguin.go @@ -0,0 +1,367 @@ +package agent + +// PenguinHarness (Prism-Shadow/penguin-harness, the penguin command; npm +// @prismshadow/penguin-cli) keeps each Project's models in one TOML file +// under its data root: $PENGUIN_HOME, else ~/.penguin/data on every system +// (core's resolveRoot, os.homedir()), the CLI's and the desktop app's +// alike. The CLI works in the Project $PENGUIN_PROJECT_ID, else +// default_project (client.ts), the one its server makes first, so the file +// is //.project_config.toml (projectConfigPath). Its +// shape (core state/project-config.ts, penguin 0.2.17): +// +// default_model = { provider = "magpie", model_id = "" } +// [providers.magpie] +// base_url = "http://127.0.0.1:3425/v1" +// client_type = "openai-responses" +// api_key = "magpie-penguin" +// [[models]] +// provider = "magpie" +// model_id = "" +// display_name = "…" +// context_window = … +// vision = true +// max_tokens = … +// [models.pricing] +// unit = "usd_per_mtok" +// cache_read = … +// cache_write = … +// output = … +// +// A model is the pair (provider, model_id); one without a base_url, client +// type or key of its own takes its group's, [providers.]. Its +// requests go through MMSP's client of that type: openai-responses posts +// base_url + /responses, with its thinking level as reasoning.effort, +// which openai-chat leaves out. The server reads the file again whenever +// its mtime moves (ProjectConfigService), so a change needs no restart; +// its own Models page and `penguin config model …` write the whole file +// back (smol-toml), every key magpie writes being one it knows. A +// default_model naming no entry is refused, so the entries go in before +// the default and out after it. + +import ( + "encoding/json" + "errors" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/edit" +) + +// penguinClient is how Penguin speaks to the gateway: OpenAI Responses, +// the one of its OpenAI clients that carries a thinking level. +const penguinClient = "openai-responses" + +// penguinConfig is what magpie reads of a Project's .project_config.toml. +type penguinConfig struct { + DefaultModel *penguinRef `toml:"default_model"` + VisionModel *penguinRef `toml:"vision_model"` + Models []struct { + Provider string `toml:"provider"` + ModelID string `toml:"model_id"` + DisplayName string `toml:"display_name"` + } `toml:"models"` +} + +type penguinRef struct { + Provider string `toml:"provider"` + ModelID string `toml:"model_id"` +} + +// value is the pair as the model field spells it: provider/model_id. +func (r *penguinRef) value() string { + if r == nil || r.ModelID == "" { + return "" + } + return r.Provider + "/" + r.ModelID +} + +// readPenguin is the config at path; a missing file is an empty one, and +// one that can't be read or parsed is an error. +func readPenguin(path string) (penguinConfig, error) { + var c penguinConfig + raw, err := edit.Read(path) + if err != nil || len(raw) == 0 { + return c, err + } + err = toml.Unmarshal(raw, &c) + return c, err +} + +// PenguinRoot is PenguinHarness's data root under home: $PENGUIN_HOME, +// else ~/.penguin/data. +func PenguinRoot(home string) string { return penguinRoot(here(home)) } + +// penguinRoot is the data root at a place; a WSL distro's variables +// aren't read, so it is ~/.penguin/data there. +func penguinRoot(at place) string { + if d := at.getenv("PENGUIN_HOME"); d != "" { + return d + } + return filepath.Join(at.home, ".penguin", "data") +} + +// penguinProject is the Project the CLI works in: $PENGUIN_PROJECT_ID, +// where it names a folder of the root, else default_project. +func penguinProject(at place) string { + if p := strings.TrimSpace(at.getenv("PENGUIN_PROJECT_ID")); p != "" && p != "." && p != ".." && !strings.ContainsAny(p, `/\`) { + return p + } + return "default_project" +} + +func penguin(home string) *Agent { return penguinIn(here(home)) } + +// penguinIn is PenguinHarness at a place: this machine's home, or a WSL +// distro's (see wsl.go), its provider naming the gateway as it reaches it +// from there. +func penguinIn(at place) *Agent { + root := penguinRoot(at) + path := filepath.Join(root, penguinProject(at), ".project_config.toml") + providerTable := "providers." + magpieID + stashKey := at.key("penguin.default") + absentKey := at.key("penguin.before.absent") + key := func() string { return agentKeyAt("penguin", at.gw()) } + get := func() string { c, _ := readPenguin(path); return c.DefaultModel.value() } + writeMagpie := func() error { + // Penguin keeps its config private (it holds API keys), so a file + // magpie starts is made the same way. + if _, err := os.Stat(path); os.IsNotExist(err) { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + if err := os.WriteFile(path, nil, 0o600); err != nil { + return err + } + } + kvs := []edit.KV{ + {Path: "base_url", Value: at.v1()}, + {Path: "client_type", Value: penguinClient}, + {Path: "api_key", Value: key()}, + } + // A sync with nothing new leaves the file, and its time, alone. + t, _ := edit.GetTOMLTable(path, providerTable) + same := t != nil + for _, kv := range kvs { + same = same && t[kv.Path] == kv.Value + } + if !same { + if err := kimiProvider(path, providerTable, kvs...); err != nil { + return err + } + } + return edit.SetTOMLArrayTables(path, "models", "provider", magpieID, penguinBlocks(magpieModels("penguin"))) + } + dropMagpie := func() error { + if err := edit.SetTOMLArrayTables(path, "models", "provider", magpieID, nil); err != nil { + return err + } + return edit.DelTOMLTable(path, providerTable) + } + // setRef points key (default_model, vision_model) at provider/model_id, + // or takes it out for "" + setRef := func(k, v string) error { + if v == "" { + return edit.DelTOMLTop(path, k) + } + p, m, _ := strings.Cut(v, "/") + // spelled as Penguin's own writer spells it + return edit.SetTOMLTop(path, edit.KV{Path: k, Value: edit.Raw( + "{ provider = " + penguinString(p) + ", model_id = " + penguinString(m) + " }")}) + } + // own reports whether Penguin has the entry v of the user's + own := func(v string) bool { + c, err := readPenguin(path) + if err != nil { + return false + } + for _, m := range c.Models { + if m.Provider != magpieID && m.Provider+"/"+m.ModelID == v { + return true + } + } + return false + } + return atomic(&Agent{ + ID: "penguin", Name: "PenguinHarness", Icon: "penguin-color", Bin: "penguin", + Aliases: []string{"penguin-harness", "penguinharness"}, Spelled: prefixed, + Dir: filepath.Dir(root), Path: path, + Sync: func() error { + t, err := edit.GetTOMLTable(path, providerTable) + if err != nil || t == nil { + return err + } + return writeMagpie() + }, + Check: func() string { + c, err := readPenguin(path) + if err != nil { + return err.Error() + } + if c.DefaultModel == nil || c.DefaultModel.Provider != magpieID { + return "" + } + found := false + for _, m := range c.Models { + found = found || m.Provider == magpieID && m.ModelID == c.DefaultModel.ModelID + } + if !found { + return "PenguinHarness's model " + c.DefaultModel.ModelID + " (.project_config.toml) is gone, so it no longer reaches magpie" + } + t, err := edit.GetTOMLTable(path, providerTable) + if err != nil { + return err.Error() + } + if t == nil { + return "PenguinHarness's [" + providerTable + "] (.project_config.toml) is gone, so it no longer reaches magpie" + } + return wiringOff("PenguinHarness", path, func(k string) (string, bool) { v, ok := t[k]; return v, ok }, + "base_url", at.v1(), "api_key", key()) + }, + // a file magpie made is taken away again once nothing is left in it + Restore: func() error { + if unstash(absentKey) != "1" { + return nil + } + raw, err := os.ReadFile(path) + if err != nil { + return nil + } + var now map[string]any + if toml.Unmarshal(raw, &now) != nil || len(now) > 0 { + return nil + } + if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + return nil + }, + Fields: []Field{{ + // default_model, as provider/model_id + Key: "model", Label: "model", + Get: get, + Set: func(v string) error { + cur := get() + if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { + if !usesMagpie(cur) { + kept := map[string]string{stashKey: cur} + if t, _ := edit.GetTOMLTable(path, providerTable); t == nil { + if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) { + kept[absentKey] = "1" + } else { + kept[absentKey] = "" + } + } + stash(kept) + } + if err := writeMagpie(); err != nil { + return err + } + return setRef("default_model", v) + } + if v != "" && !strings.Contains(strings.Trim(v, "/"), "/") { + return errors.New("expected provider/model_id, got " + strconv.Quote(v)) + } + if v == "" && usesMagpie(cur) { + // back to the default the user had, if Penguin still has it + if was := unstash(stashKey); was != "" && !usesMagpie(was) && own(was) { + v = was + } + } + if err := setRef("default_model", v); err != nil { + return err + } + // a vision model picked among magpie's in Penguin goes with them + if c, err := readPenguin(path); err == nil && c.VisionModel != nil && c.VisionModel.Provider == magpieID { + if err := setRef("vision_model", ""); err != nil { + return err + } + } + return dropMagpie() + }, + Options: func(cur map[string]string) []Option { + return append(penguinOwnOptions(path, cur["model"]), viaMagpie("penguin", magpieID+"/")...) + }, + }}, + }, path) +} + +// penguinOwnOptions are the models of the user's own in the Project's +// config, as provider/model_id, and the current pick when it is none of +// them. +func penguinOwnOptions(path, cur string) []Option { + c, _ := readPenguin(path) + seen := map[string]bool{} + var out []Option + for _, m := range c.Models { + v := m.Provider + "/" + m.ModelID + if m.Provider == "" || m.ModelID == "" || m.Provider == magpieID || seen[v] { + continue + } + seen[v] = true + o := Option{Value: v, Icon: modelIcon(m.Provider, m.ModelID)} + if m.DisplayName != "" && m.DisplayName != m.ModelID { + o.Note = m.DisplayName + } + out = append(out, o) + } + if cur != "" && !seen[cur] && !usesMagpie(cur) { + out = append([]Option{{Value: cur, Icon: modelIcon("", cur)}}, out...) + } + return group("PenguinHarness", out) +} + +// penguinBlocks are magpie's models as entries of Penguin's [[models]], +// each with what its own Models page records for one: the name, context +// window, cap on a reply, whether it takes images and its list price. +func penguinBlocks(ms []catalog.Model) []string { + out := make([]string, 0, len(ms)) + for _, m := range ms { + var b strings.Builder + line := func(k, v string) { b.WriteString(k + " = " + v + "\n") } + b.WriteString("[[models]]\n") + line("provider", penguinString(magpieID)) + line("model_id", penguinString(m.ID)) + if m.Name != "" && m.Name != m.ID { + line("display_name", penguinString(m.Name)) + } + if m.Context > 0 { + line("context_window", strconv.Itoa(m.Context)) + } + // Penguin takes a model for one that reads images unless told not + line("vision", strconv.FormatBool(m.Images)) + if n := maxTokens(m); n > 0 && m.Output > 0 { + line("max_tokens", strconv.Itoa(n)) + } + // its three buckets: cache_write is input not read from a cache + if p := m.Price; p != nil && (p.Input > 0 || p.Output > 0 || p.CacheRead > 0) { + b.WriteString("\n[models.pricing]\n") + line("unit", penguinString("usd_per_mtok")) + line("cache_read", penguinFloat(p.CacheRead)) + line("cache_write", penguinFloat(p.Input)) + line("output", penguinFloat(p.Output)) + } + out = append(out, b.String()) + } + return out +} + +// penguinString is s as a TOML basic string: JSON's escapes are all TOML's. +func penguinString(s string) string { + b, _ := json.Marshal(s) + return string(b) +} + +// penguinFloat is f as a TOML float. +func penguinFloat(f float64) string { + s := strconv.FormatFloat(f, 'f', -1, 64) + if !strings.ContainsAny(s, ".eE") { + s += ".0" + } + return s +} diff --git a/internal/agent/penguin_test.go b/internal/agent/penguin_test.go new file mode 100644 index 000000000..8cab64fe2 --- /dev/null +++ b/internal/agent/penguin_test.go @@ -0,0 +1,352 @@ +package agent + +import ( + "bytes" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + + "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/usage" +) + +// testdata/penguin/project_config.toml is the .project_config.toml +// PenguinHarness 0.2.17 wrote itself: its server's first run (the +// command_policy rules, an empty [providers]) and `penguin config model add` +// of a model of the user's own, made its default. +func penguinFixture(t *testing.T) string { + t.Helper() + b, err := os.ReadFile(filepath.Join("testdata", "penguin", "project_config.toml")) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func penguinOf(t *testing.T) *Agent { + t.Helper() + for _, x := range All() { + if x.ID == "penguin" { + return x + } + } + t.Fatal("no penguin in All()") + return nil +} + +// penguinFile is what magpie's checks read of the file at path. +type penguinFile struct { + DefaultModel map[string]string `toml:"default_model"` + Providers map[string]map[string]any `toml:"providers"` + Models []map[string]any `toml:"models"` + Policy struct { + Rules []map[string]any `toml:"rules"` + } `toml:"command_policy"` +} + +func readPenguinFile(t *testing.T, path string) penguinFile { + t.Helper() + var f penguinFile + if err := toml.Unmarshal([]byte(readFile(path)), &f); err != nil { + t.Fatalf("%v:\n%s", err, readFile(path)) + } + return f +} + +// PenguinHarness is wired in its Project's .project_config.toml: magpie as +// [providers.magpie] (OpenAI Responses, a key naming Penguin), its models +// as [[models]] entries of that provider, and default_model on one. The +// user's models, command policy and the rest stay; Disconnect puts the +// file back as Penguin wrote it. +func TestPenguin(t *testing.T) { + home := syncHome(t) + a := penguinOf(t) + root := filepath.Join(home, ".penguin", "data") + path := filepath.Join(root, "default_project", ".project_config.toml") + if a.Name != "PenguinHarness" || a.Icon != "penguin-color" || a.Bin != "penguin" || a.Dir != filepath.Join(home, ".penguin") || a.Path != path || a.Detected() { + t.Fatalf("%+v", a) + } + user := penguinFixture(t) + writeFile(t, path, user) + if !a.Detected() || a.Field("model").Get() != "custom/my-own" { + t.Fatalf("detected %v, model %q", a.Detected(), a.Field("model").Get()) + } + var vals []string + for _, o := range a.Field("model").Options(a.Values()) { + vals = append(vals, o.Value) + } + if !slices.Contains(vals, "custom/my-own") || !slices.Contains(vals, "magpie/relay/glm-4.6") { + t.Fatalf("options %v", vals) + } + + if err := a.Connect(); err != nil { + t.Fatal(err) + } + f := readPenguinFile(t, path) + if f.DefaultModel["provider"] != "magpie" || f.DefaultModel["model_id"] != "relay/glm-4.6" { + t.Fatalf("default_model %v:\n%s", f.DefaultModel, readFile(path)) + } + if !strings.HasPrefix(readFile(path), `default_model = { provider = "magpie", model_id = "relay/glm-4.6" }`+"\n") { + t.Fatalf("not spelled as Penguin spells it:\n%s", readFile(path)) + } + p := f.Providers["magpie"] + if p["base_url"] != gateway.URL()+"/v1" || p["client_type"] != "openai-responses" || p["api_key"] != "magpie-penguin" { + t.Fatalf("provider %v", p) + } + var mine, ours []map[string]any + for _, m := range f.Models { + if m["provider"] == "magpie" { + ours = append(ours, m) + } else { + mine = append(mine, m) + } + } + if len(mine) != 1 || mine[0]["model_id"] != "my-own" || mine[0]["api_key"] != "k1" || len(ours) == 0 { + t.Fatalf("models:\n%s", readFile(path)) + } + if ours[0]["model_id"] != "relay/glm-4.6" || ours[0]["context_window"] != int64(204800) || ours[0]["vision"] != false { + t.Fatalf("entry %v", ours[0]) + } + // every key is one Penguin's ModelEntry has + for k := range ours[0] { + if !slices.Contains([]string{"provider", "model_id", "display_name", "context_window", "vision", "max_tokens", "pricing"}, k) { + t.Fatalf("%s isn't a key of Penguin's: %v", k, ours[0]) + } + } + if len(f.Policy.Rules) != 9 { + t.Fatalf("command policy: %d rules", len(f.Policy.Rules)) + } + if c := a.Check(); c != "" { + t.Fatal(c) + } + if got := usage.AgentOf("penguin"); got != "penguin" { + t.Fatalf("usage: %q", got) + } + + // the shared key is off, and a sync mends it + if err := edit.SetTOMLKey(path, "providers.magpie", "api_key", gateway.Token); err != nil { + t.Fatal(err) + } + if a.Check() == "" { + t.Fatal("the shared key reads as Penguin's") + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if c := a.Check(); c != "" { + t.Fatal(c) + } + // a sync with nothing to change leaves the bytes and the time alone, + // which Penguin's server would otherwise read again + was, _ := os.ReadFile(path) + st, _ := os.Stat(path) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if now, _ := os.ReadFile(path); !bytes.Equal(now, was) { + t.Fatalf("a sync with nothing to change wrote:\n%s", now) + } + if st2, _ := os.Stat(path); !st2.ModTime().Equal(st.ModTime()) { + t.Fatal("a sync with nothing to change touched the file") + } + // an entry magpie gave is gone: Check says so + if err := edit.SetTOMLArrayTables(path, "models", "provider", "magpie", nil); err != nil { + t.Fatal(err) + } + if a.Check() == "" { + t.Fatal("a default naming no entry passed") + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if a.Wired() || a.Field("model").Get() != "custom/my-own" { + t.Fatalf("still connected: %q", a.Field("model").Get()) + } + if b := readFile(path); b != user { + t.Fatalf("not as Penguin wrote it:\n%s", b) + } +} + +// With no config (Penguin installed, its server never run), Connect makes +// one, private as Penguin keeps it, and Disconnect takes it away again. +func TestPenguinRoundTripNoFile(t *testing.T) { + home := syncHome(t) + t.Setenv("PENGUIN_HOME", filepath.Join(home, "pg")) + a := penguin(home) + for i := 0; i < 2; i++ { + if err := a.Connect(); err != nil { + t.Fatal(err) + } + if !a.Wired() || a.Check() != "" { + t.Fatalf("round %d: not connected:\n%s", i, readFile(a.Path)) + } + if st, err := os.Stat(a.Path); err != nil || runtime.GOOS != "windows" && st.Mode().Perm() != 0o600 { + t.Fatalf("round %d: %v %v", i, st.Mode(), err) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(a.Path); !os.IsNotExist(err) { + t.Fatalf("round %d: left:\n%s", i, readFile(a.Path)) + } + } +} + +// What Penguin's own writer does while it is connected stands: it writes +// the whole file back (smol-toml), a model the user added included, and +// a sync and Disconnect keep that model. +func TestPenguinKeepsWhatPenguinWrote(t *testing.T) { + home := syncHome(t) + a := penguin(home) + writeFile(t, a.Path, penguinFixture(t)) + if err := a.Connect(); err != nil { + t.Fatal(err) + } + // as `penguin config model add custom/another` leaves it: one more + // entry after magpie's + b := readFile(a.Path) + "\n[[models]]\nprovider = \"custom\"\nmodel_id = \"another\"\napi_key = \"k2\"\n" + writeFile(t, a.Path, b) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if got := readFile(a.Path); got != b { + t.Fatalf("sync changed what was current:\n%s", got) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + f := readPenguinFile(t, a.Path) + var ids []string + for _, m := range f.Models { + ids = append(ids, m["provider"].(string)+"/"+m["model_id"].(string)) + } + if !slices.Equal(ids, []string{"custom/my-own", "custom/another"}) || f.Providers["magpie"] != nil || f.DefaultModel["model_id"] != "my-own" { + t.Fatalf("after Disconnect:\n%s", readFile(a.Path)) + } + if strings.Contains(readFile(a.Path), "\n\n\n") { + t.Fatalf("blank lines left:\n%s", readFile(a.Path)) + } +} + +// $PENGUIN_HOME moves the data root, $PENGUIN_PROJECT_ID the Project, as +// Penguin's own resolveRoot and CLI read them; a Project that isn't a +// folder's name is default_project. A distro's Penguin is at its home. +func TestPenguinRootAndProject(t *testing.T) { + home := syncHome(t) + own := filepath.Join(home, "own") + t.Setenv("PENGUIN_HOME", own) + t.Setenv("PENGUIN_PROJECT_ID", "work") + if a := penguin(home); a.Path != filepath.Join(own, "work", ".project_config.toml") || a.Dir != home { + t.Fatalf("%s %s", a.Path, a.Dir) + } + for _, bad := range []string{"..", "../x", `a\b`, " "} { + t.Setenv("PENGUIN_PROJECT_ID", bad) + if a := penguin(home); a.Path != filepath.Join(own, "default_project", ".project_config.toml") { + t.Fatalf("%q: %s", bad, a.Path) + } + } + t.Setenv("PENGUIN_HOME", "") + t.Setenv("PENGUIN_PROJECT_ID", "") + if a := penguin(home); a.Dir != filepath.Join(home, ".penguin") { + t.Fatalf("default: %s", a.Dir) + } + t.Setenv("PENGUIN_HOME", own) + root := t.TempDir() + d := distro{Name: "Ubuntu", Root: root, Home: "/home/me", Has: map[string]bool{"dir:.penguin": true}, Mirrored: true, Running: true} + a := wslAgent(wslKindOf("penguin"), d) + if a.ID != "penguin@wsl:Ubuntu" || a.Path != filepath.Join(root, "home", "me", ".penguin", "data", "default_project", ".project_config.toml") { + t.Fatalf("%+v", a) + } +} + +// A model's entry carries what Penguin's Models page records: its name, +// window, reply cap, whether it reads images and its price in Penguin's +// three buckets, input not read from a cache being cache_write. +func TestPenguinBlocks(t *testing.T) { + bs := penguinBlocks([]catalog.Model{{ID: "p/m", Name: `M "1"`, Context: 1000, Output: 500, Images: true, + Price: &catalog.Price{Input: 3, Output: 15, CacheRead: 0.3}}}) + var f penguinFile + if err := toml.Unmarshal([]byte(bs[0]), &f); err != nil { + t.Fatalf("%v:\n%s", err, bs[0]) + } + m := f.Models[0] + pr, _ := m["pricing"].(map[string]any) + if m["display_name"] != `M "1"` || m["context_window"] != int64(1000) || m["max_tokens"] != int64(500) || m["vision"] != true || + pr["unit"] != "usd_per_mtok" || pr["cache_write"] != float64(3) || pr["cache_read"] != 0.3 || pr["output"] != float64(15) { + t.Fatalf("%v\n%s", m, bs[0]) + } +} + +// Its updates: npm's package, or for install.sh's tarball in ~/.penguin +// its own `penguin update --yes`, which Windows' Penguin refuses. +func TestPenguinUpdate(t *testing.T) { + self := cliSpecs["penguin"].self + got := self("/home/me/.local/bin/penguin", "/home/me/.penguin/bin/penguin") + if runtime.GOOS == "windows" { + if got != nil { + t.Fatalf("windows: %q", got) + } + } else if !slices.Equal(got, []string{"/home/me/.local/bin/penguin", "update", "--yes"}) { + t.Fatalf("tarball: %q", got) + } + if got := self("/usr/local/bin/penguin", "/usr/local/lib/node_modules/@prismshadow/penguin-cli/dist/bin.js"); got != nil { + t.Fatalf("npm taken for the tarball: %q", got) + } + if !slices.Equal(cliSpecs["penguin"].npm, []string{"@prismshadow/penguin-cli"}) { + t.Fatal(cliSpecs["penguin"].npm) + } + for goos, want := range map[string]string{"darwin": "curl -fsSL https://penguin.ooo/install.sh | sh", "linux": "curl -fsSL https://penguin.ooo/install.sh | sh", + "windows": "irm https://penguin.ooo/install.ps1 | iex"} { + if c := vendorInstall["penguin"](goos); len(c) != 1 || c[0].Command != want { + t.Fatalf("%s: %+v", goos, c) + } + } +} + +// Setting the model to none while on magpie's goes back to the user's own +// default if Penguin still has it, else leaves none; magpie's entries, +// provider and a vision model among them go either way. +func TestPenguinModelNone(t *testing.T) { + home := syncHome(t) + a := penguin(home) + writeFile(t, a.Path, penguinFixture(t)) + m := a.Field("model") + for _, gone := range []bool{false, true} { + if err := m.Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + if err := edit.SetTOMLTop(a.Path, edit.KV{Path: "vision_model", Value: edit.Raw(`{ provider = "magpie", model_id = "relay/glm-4.6" }`)}); err != nil { + t.Fatal(err) + } + if gone { + if err := edit.SetTOMLArrayTables(a.Path, "models", "provider", "custom", nil); err != nil { + t.Fatal(err) + } + } + if err := m.Set(""); err != nil { + t.Fatal(err) + } + want := "custom/my-own" + if gone { + want = "" + } + b := readFile(a.Path) + if m.Get() != want || strings.Contains(b, "magpie") { + t.Fatalf("gone %v: %q:\n%s", gone, m.Get(), b) + } + } + if err := m.Set("nope"); err == nil { + t.Fatal("a value with no provider was taken") + } +} diff --git a/internal/agent/sync_test.go b/internal/agent/sync_test.go index 8b3d56739..7b69f7057 100644 --- a/internal/agent/sync_test.go +++ b/internal/agent/sync_test.go @@ -41,6 +41,8 @@ func syncHome(t *testing.T) string { t.Setenv("SENPI_CODING_AGENT_DIR", "") t.Setenv("PRIME_AGENT_CODING_AGENT_DIR", "") t.Setenv("MOTHX_DIR", "") + t.Setenv("PENGUIN_HOME", "") + t.Setenv("PENGUIN_PROJECT_ID", "") t.Setenv("PI_CODING_AGENT_DIR", "") t.Setenv("PI_CONFIG_DIR", "") t.Setenv("OMP_PROFILE", "") diff --git a/internal/agent/testdata/penguin/project_config.toml b/internal/agent/testdata/penguin/project_config.toml new file mode 100644 index 000000000..9f35be61f --- /dev/null +++ b/internal/agent/testdata/penguin/project_config.toml @@ -0,0 +1,52 @@ +default_model = { provider = "custom", model_id = "my-own" } +[[command_policy.rules]] +name = "rm-recursive-force" +pattern = "(?:^|[\\s;&|(])(?:[^\\s;&|]*/)?rm(?=(?:\\s[^;&|]*)?\\s-(?:[a-zA-Z]*[rR][a-zA-Z]*|-recursive)(?:\\s|$))(?=(?:\\s[^;&|]*)?\\s-(?:[a-zA-Z]*[fF][a-zA-Z]*|-force)(?:\\s|$))" +description = "rm with recursive + force flags in one command (rm -rf and friends)" + +[[command_policy.rules]] +name = "mkfs" +pattern = "(?:^|[\\s;&|(])(?:[^\\s;&|]*/)?mkfs(?:\\.[a-zA-Z0-9]+)?(?![a-zA-Z0-9])" +description = "mkfs — formatting a filesystem destroys it wholesale" + +[[command_policy.rules]] +name = "dd-to-block-device" +pattern = "(?:^|[\\s;&|(])(?:[^\\s;&|]*/)?dd\\s[^;&|]*\\bof=[\"']?/dev/(?:sd|hd|vd|xvd|nvme|mmcblk|loop|disk|rdisk)[a-zA-Z0-9]*" +description = "dd writing directly to a block device (of=/dev/null stays allowed)" + +[[command_policy.rules]] +name = "fork-bomb" +pattern = ":\\s*\\(\\s*\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;\\s*:" +description = "the classic fork bomb — exhausts the process table in seconds" + +[[command_policy.rules]] +name = "overwrite-block-device" +pattern = ">\\s*[\"']?/dev/(?:sd|hd|vd|xvd|nvme|mmcblk|loop|disk|rdisk)[a-zA-Z0-9]*" +description = "shell redirection onto a block device (/dev/null stays allowed)" + +[[command_policy.rules]] +name = "windows-recursive-delete" +pattern = "(?:^|[\\s;&|(])(?:[^\\s;&|]*/)?(?i:remove-item)(?![a-zA-Z0-9])(?=(?:\\s[^;&|]*)?\\s-(?i:rec[a-z]*|r)(?:\\s|$))(?=(?:\\s[^;&|]*)?\\s-(?i:force|f)(?:\\s|$))|(?:^|[\\s;&|(])(?:[^\\s;&|]*/)?(?i:rmdir|rd|del|erase)(?![a-zA-Z0-9])(?=[^;&|]*/(?i:s)(?![a-zA-Z]))(?=[^;&|]*/(?i:q)(?![a-zA-Z]))" +description = "Windows recursive force delete (Remove-Item -Recurse -Force, rd /s /q)" + +[[command_policy.rules]] +name = "windows-format-volume" +pattern = "(?:^|[\\s;&|(])(?:[^\\s;&|]*/)?(?i:format)(?![a-zA-Z0-9-])(?=[^;&|]*\\s[a-zA-Z]:(?![a-zA-Z0-9]))|(?:^|[\\s;&|(])(?:[^\\s;&|]*/)?(?i:format-volume)(?![a-zA-Z0-9])" +description = "Windows volume format (format C:, Format-Volume) — destroys it wholesale" + +[[command_policy.rules]] +name = "windows-disk-overwrite" +pattern = "\\\\\\\\\\.\\\\(?i:physicaldrive)[0-9]+|(?:^|[\\s;&|(])(?:[^\\s;&|]*/)?(?i:clear-disk)(?![a-zA-Z0-9])" +description = "Windows raw disk overwrite (\\\\.\\PhysicalDriveN, Clear-Disk)" + +[[command_policy.rules]] +name = "windows-fork-bomb" +pattern = "%0\\s*\\|\\s*%0" +description = "the cmd fork bomb (%0|%0) — exhausts the process table in seconds" +[providers] +[[models]] +provider = "custom" +model_id = "my-own" +client_type = "openai-chat" +api_key = "k1" +base_url = "http://127.0.0.1:1/v1" diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index aec24d4de..999c81b59 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -538,6 +538,10 @@ var wslKinds = []wslKind{ {id: "mothx", name: "MothX", dir: ".mothx", bin: "mothx", in: mothxIn, restart: newNotice("{agent} in WSL {distro} reads its settings at start-up — restart open mothx sessions to use this."), asleep: wslOwnAsleep("mothx", "model")}, + // PenguinHarness's ~/.penguin/data in the distro: its PENGUIN_HOME + // there isn't read; its server reads the file again as it changes + {id: "penguin", name: "PenguinHarness", dir: ".penguin", bin: "penguin", in: penguinIn, + asleep: wslOwnAsleep("penguin", "model")}, {id: "reasonix", name: "Reasonix", bin: "reasonix", in: reasonixIn, version: true, accept: func(d distro) bool { v := d.Versions["reasonix"] diff --git a/internal/agent/wsl_more_test.go b/internal/agent/wsl_more_test.go index 9e7a863f5..c0391490e 100644 --- a/internal/agent/wsl_more_test.go +++ b/internal/agent/wsl_more_test.go @@ -42,6 +42,7 @@ var wslMore = []struct { {"snow", ".snow/profiles/magpie.json", "/v1"}, {"goose", ".config/goose/custom_providers/magpie.json", "/v1"}, {"mothx", ".mothx/settings.json", "/v1"}, + {"penguin", ".penguin/data/default_project/.project_config.toml", "/v1"}, {"reasonix", ".reasonix/config.toml", "/v1"}, } @@ -69,7 +70,7 @@ func moveHostDirs(t *testing.T) string { moved := t.TempDir() for _, v := range []string{"OPENCODE_CONFIG_DIR", "MIMOCODE_HOME", "DEVECO_CONFIG_DIR", "KIMI_CODE_HOME", "KIMI_SHARE_DIR", "PI_CODING_AGENT_DIR", "HERMES_HOME", "GROK_HOME", "FACTORY_HOME_OVERRIDE", "MINIMAX_DATA_DIR", "QODER_CONFIG_DIR", "QODERCN_CONFIG_DIR", "DSH_HOME", "MISTER_MORPH_CONFIG", - "CODEBUDDY_CONFIG_DIR", "CLINE_DIR", "CLINE_DATA_DIR", "ATOMCODE_HOME", "REASONIX_HOME", "SNOW_CONFIG_DIR", "MOTHX_DIR", "APPDATA"} { + "CODEBUDDY_CONFIG_DIR", "CLINE_DIR", "CLINE_DATA_DIR", "ATOMCODE_HOME", "REASONIX_HOME", "SNOW_CONFIG_DIR", "MOTHX_DIR", "PENGUIN_HOME", "APPDATA"} { t.Setenv(v, filepath.Join(moved, v)) } return moved @@ -195,7 +196,12 @@ func TestWSLMoreAgentsPick(t *testing.T) { if !mirrored && !strings.Contains(a.Notice(), "mirrored") { t.Errorf("%s: %s", c.id, a.Notice()) } - if mirrored && !strings.HasPrefix(a.Notice(), k.name+" in WSL Ubuntu ") { + // mirrored, only an agent that reads its config at start-up has + // something to say (PenguinHarness reads it again on a change) + if mirrored && k.restart != "" && !strings.HasPrefix(a.Notice(), k.name+" in WSL Ubuntu ") { + t.Errorf("%s: %s", c.id, a.Notice()) + } + if mirrored && k.restart == "" && a.Notice() != "" { t.Errorf("%s: %s", c.id, a.Notice()) } own := k.dir diff --git a/internal/agentenv/agentenv.go b/internal/agentenv/agentenv.go index 9048f1e7f..88cc892a2 100644 --- a/internal/agentenv/agentenv.go +++ b/internal/agentenv/agentenv.go @@ -48,6 +48,9 @@ var Vars = []string{ "STEP_CODING_AGENT_DIR", "STEPCODE_CONFIG_DIR", // MothX's config folder ($MOTHX_DIR/settings.json) "MOTHX_DIR", + // PenguinHarness's data root and the Project its CLI works in + // ($PENGUIN_HOME/$PENGUIN_PROJECT_ID/.project_config.toml) + "PENGUIN_HOME", "PENGUIN_PROJECT_ID", // omp "OMP_PROFILE", // Qoder's two builds, the global site's and China's @@ -122,6 +125,7 @@ var NotPaths = map[string]bool{ "PI_CONFIG_DIR": true, "OPENCODE_DB": true, "STEPCODE_CONFIG_DIR": true, "MAGPIE_ZED_BIN": true, "MAGPIE_ZED_PROCESS_NAMES": true, + "PENGUIN_PROJECT_ID": true, } // ClaudeProviders are Claude Code's switches that send its requests to a diff --git a/internal/edit/toml_array.go b/internal/edit/toml_array.go index 316ab62ed..552824c6c 100644 --- a/internal/edit/toml_array.go +++ b/internal/edit/toml_array.go @@ -32,7 +32,7 @@ func editTOMLArrayTable(path, name, key, value, block string) error { if err != nil { return err } - spans, err := namedTOMLArray(doc, name, key, value) + spans, err := namedTOMLArray(doc, name, key, value, false) if err != nil { return fmt.Errorf("%s: %w", path, err) } @@ -46,7 +46,7 @@ func editTOMLArrayTable(path, name, key, value, block string) error { if err != nil { return err } - matches, err := namedTOMLArray(newDoc, name, key, value) + matches, err := namedTOMLArray(newDoc, name, key, value, false) if err != nil || len(matches) == 0 || len(newDoc.root.keys) > 0 { return fmt.Errorf("replacement must declare one %s entry with %s = %q", name, key, value) } @@ -84,9 +84,96 @@ func editTOMLArrayTable(path, name, key, value, block string) error { return writeTOML(path, out) } +// SetTOMLArrayTables replaces every entry of the array table name whose key +// is value, with its child tables, by blocks: where the first of them was, +// else at the end of the file. Entries with another value stay as they are, +// and no blocks removes the matching ones. Each block is one complete entry, +// its header included, with key = value; anything else in one is an error. +func SetTOMLArrayTables(path, name, key, value string, blocks []string) error { + raw, err := Read(path) + if err != nil { + return err + } + if err := validateTOML(raw); err != nil { + return fmt.Errorf("%s: %w", path, err) + } + lines := splitLines(string(raw)) + doc, err := parseTOMLFile(lines) + if err != nil { + return err + } + spans, err := namedTOMLArray(doc, name, key, value, true) + if err != nil { + return fmt.Errorf("%s: %w", path, err) + } + var replacement []string + want := tomlHeaderParts(name) + for _, block := range blocks { + if err := validateTOML([]byte(block)); err != nil { + return fmt.Errorf("replacement: %w", err) + } + bl := splitLines(block) + newDoc, err := parseTOMLFile(bl) + if err != nil { + return err + } + matches, err := namedTOMLArray(newDoc, name, key, value, true) + if err != nil || len(matches) == 0 || len(newDoc.root.keys) > 0 || !newDoc.tables[0].array || + !slices.Equal(tomlHeaderParts(newDoc.tables[0].name), want) { + return fmt.Errorf("replacement must declare one %s entry with %s = %q", name, key, value) + } + for i, table := range newDoc.tables { + parts := tomlHeaderParts(table.name) + if i > 0 && (slices.Equal(parts, want) || !tomlDescendant(parts, want)) { + return fmt.Errorf("replacement contains another table") + } + } + if len(replacement) > 0 { + replacement = append(replacement, "") + } + replacement = append(replacement, trimBlank(bl)...) + } + if len(spans) == 0 { + if len(replacement) == 0 { + return nil + } + out := trimBlank(lines) + if len(out) > 0 { + out = append(out, "") + } + out = append(out, replacement...) + return writeTOML(path, append(out, "")) + } + var out []string + at := 0 + for i, span := range spans { + gap := lines[at:span.from] + // The blank lines between two entries replaced went with them, or + // every sync would add another. + if i == 0 || len(trimBlank(gap)) > 0 { + out = append(out, gap...) + } + if i == 0 { + if len(replacement) == 0 { + out = trimBlank(out) + } + out = append(out, replacement...) + } + at = span.to + } + out = append(out, lines[at:]...) + if joinLinesLike(out, string(raw)) == string(raw) { + return nil + } + return writeTOML(path, out) +} + type tomlArraySpan struct{ from, to int } -func namedTOMLArray(doc tomlFile, name, key, value string) ([]tomlArraySpan, error) { +// namedTOMLArray are the line spans of the entries of the array table name +// whose key is value, each followed by its child tables'; more than one such +// entry is an error unless all is set. +func namedTOMLArray(doc tomlFile, name, key, value string, all bool) ([]tomlArraySpan, error) { want := tomlHeaderParts(name) if len(want) == 0 { return nil, fmt.Errorf("invalid table name %q", name) @@ -114,7 +201,7 @@ func namedTOMLArray(doc tomlFile, name, key, value string) ([]tomlArraySpan, err if !matched { continue } - if len(spans) > 0 { + if len(spans) > 0 && !all { return nil, fmt.Errorf("multiple %s entries have %s = %q", name, key, value) } spans = append(spans, tomlArraySpan{table.from, tomlContentEnd(table)}) diff --git a/internal/edit/toml_array_test.go b/internal/edit/toml_array_test.go index 403490180..f4713cc7e 100644 --- a/internal/edit/toml_array_test.go +++ b/internal/edit/toml_array_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) func TestTOMLArrayTableEditsOnlyNamedEntry(t *testing.T) { @@ -109,3 +110,128 @@ func TestTOMLArrayTableInterleavedChildren(t *testing.T) { t.Fatalf("interleaved subtree: %s", got) } } + +// SetTOMLArrayTables replaces every matching entry in one place, keeps the +// others and what lies between them, and a second run with the same blocks +// leaves the file's bytes and time alone. +func TestTOMLArrayTablesReplaceEveryMatch(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + before := `default_model = { provider = "custom", model_id = "own" } + +[[models]] +provider = "magpie" +model_id = "old-1" + +[models.pricing] +output = 1.0 + +[[models]] +provider = "magpie" +model_id = "old-2" + +[[models]] +provider = "custom" +model_id = "own" +[models.pricing] +output = 2.0 + +[[models]] +provider = "magpie" +model_id = "old-3" +[[command_policy.rules]] +pattern = "rm" +` + if err := os.WriteFile(path, []byte(before), 0o600); err != nil { + t.Fatal(err) + } + blocks := []string{ + "[[models]]\nprovider = \"magpie\"\nmodel_id = \"new-1\"\n\n[models.pricing]\noutput = 3.0\n", + "[[models]]\nprovider = \"magpie\"\nmodel_id = \"new-2\"\n", + } + if err := SetTOMLArrayTables(path, "models", "provider", "magpie", blocks); err != nil { + t.Fatal(err) + } + want := `default_model = { provider = "custom", model_id = "own" } + +[[models]] +provider = "magpie" +model_id = "new-1" + +[models.pricing] +output = 3.0 + +[[models]] +provider = "magpie" +model_id = "new-2" + +[[models]] +provider = "custom" +model_id = "own" +[models.pricing] +output = 2.0 + +[[command_policy.rules]] +pattern = "rm" +` + got, _ := os.ReadFile(path) + if string(got) != want { + t.Fatalf("got:\n%s\nwant:\n%s", got, want) + } + old := time.Now().Add(-time.Hour).Truncate(time.Second) + if err := os.Chtimes(path, old, old); err != nil { + t.Fatal(err) + } + if err := SetTOMLArrayTables(path, "models", "provider", "magpie", blocks); err != nil { + t.Fatal(err) + } + got, _ = os.ReadFile(path) + if string(got) != want { + t.Fatalf("a second run changed the file:\n%s", got) + } + if st, err := os.Stat(path); err != nil || !st.ModTime().Equal(old) { + t.Fatalf("a second run wrote the file again: %v %v", st.ModTime(), err) + } + + if err := SetTOMLArrayTables(path, "models", "provider", "magpie", nil); err != nil { + t.Fatal(err) + } + want = `default_model = { provider = "custom", model_id = "own" } + +[[models]] +provider = "custom" +model_id = "own" +[models.pricing] +output = 2.0 + +[[command_policy.rules]] +pattern = "rm" +` + got, _ = os.ReadFile(path) + if string(got) != want { + t.Fatalf("after removal got:\n%s\nwant:\n%s", got, want) + } +} + +func TestTOMLArrayTablesAppendAndRefuse(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte("x = 1\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := SetTOMLArrayTables(path, "models", "provider", "magpie", []string{"[[models]]\nprovider = \"magpie\"\nmodel_id = \"a\"\n"}); err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(path); string(got) != "x = 1\n\n[[models]]\nprovider = \"magpie\"\nmodel_id = \"a\"\n" { + t.Fatalf("append got %q", got) + } + for _, bad := range []string{ + "[[models]]\nprovider = \"other\"\n", + "[[models]]\nprovider = \"magpie\"\n[[models]]\nprovider = \"magpie\"\n", + "[[models]]\nprovider = \"magpie\"\n[ui]\nx = 1\n", + "y = 2\n[[models]]\nprovider = \"magpie\"\n", + "[models]\nprovider = \"magpie\"\n", + } { + if err := SetTOMLArrayTables(path, "models", "provider", "magpie", []string{bad}); err == nil { + t.Errorf("block %q was taken", bad) + } + } +} diff --git a/internal/gui/assets/icons/penguin-color.svg b/internal/gui/assets/icons/penguin-color.svg new file mode 100644 index 000000000..0d48619e4 --- /dev/null +++ b/internal/gui/assets/icons/penguin-color.svg @@ -0,0 +1 @@ +