opencode-magpie-plugin 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,7 +55,7 @@ OpenCode V2
55
55
 
56
56
  ```jsonc
57
57
  {
58
- "plugins": ["opencode-magpie-plugin@0.3.1"]
58
+ "plugins": ["opencode-magpie-plugin@0.3.2"]
59
59
  }
60
60
  ```
61
61
 
@@ -123,7 +123,7 @@ Routing group(例如 `group/auto`)会跨多个服务路由,因此不按 `o
123
123
 
124
124
  本机模式先检查网关根路径的 `name: "magpie"`,再请求 `/v1/models`。远程模式直接请求配置的 API baseURL 下的 `models`,不探测站点根路径,以兼容只暴露 API 的反向代理。请求携带 `X-Magpie-Prices: 1` 读取可用的网关价格扩展。
125
125
 
126
- 目录映射保留模型的上下文窗口、最大输出、输入输出模态和 reasoning 档位。仅发现聊天目录;重复的无 provider 前缀别名、图片生成或其他非聊天专用模型不会注册为聊天模型。
126
+ 目录映射保留模型的上下文窗口、最大输出、输入输出模态和 reasoning 档位。网关未提供有效上下文窗口时,默认使用 256K(256,000 tokens)。仅发现聊天目录;重复的无 provider 前缀别名、视频或其他非聊天专用模型不会注册为聊天模型。图片模型不进入聊天目录,改由下方的生图工具使用。
127
127
 
128
128
  思考强度读取新版 `reasoning_levels`,并兼容已安装版本常见的 `supported_reasoning_levels`(`{ effort }` 对象或字符串列表)。只有网关实际声明的档位才会出现,可在 OpenCode 的模型变体控件中选择,或使用 `provider/model#high` 这样的引用。`default` 保留服务默认行为,不额外生成档位;网关未提供档位时不会凭模型名称猜测。
129
129
 
@@ -223,6 +223,11 @@ MAGPIE_ADDR=127.0.0.1:3426 opencode --standalone
223
223
 
224
224
  models.dev 缓存写入 `$XDG_CACHE_HOME/opencode-magpie-plugin/models.json`(默认 `~/.cache/opencode-magpie-plugin/models.json`)。首次可只读复用 Magpie、OpenCode 的 `models.json`;下载只写插件自己的目录。每次模型刷新检查缓存,超过 24 小时后台更新,缺价时可提前到 6 小时;同进程下载去重且失败后至少间隔 6 小时重试。首次下载和更新不阻塞模型发现,成功后下一次 30 秒刷新采用新目录;离线保留旧缓存。下载源为 `https://models.dev/api.json`,仍然零运行时依赖,基础价和 context 阶梯价一并传给 OpenCode。
225
225
 
226
+ ### 0.4.0
227
+
228
+ - 新增生图能力:插件注册 `magpie.image_list`(列出 Magpie 可用的生图模型)和 `magpie.image_gen`(经 Magpie `/v1/images/generations` 出图,结果以 `![image](路径)` 返回),以及 skill `magpie-image-generate`。生图前由 Agent 加载该 skill。
229
+ - 不传 `model` 时使用 Magpie 设置里选定的生图模型;图片保存在系统临时目录的 `magpie-images/` 下。
230
+
226
231
  ### 0.3.0
227
232
 
228
233
  - 新增 `options.remote.baseURL` 与 `options.remote.token`,支持远端 Magpie 网关及带路径前缀的反向代理。
package/dist/index.d.mts CHANGED
@@ -66,9 +66,44 @@ type ProviderEditor = {
66
66
  models: ModelInfo2[];
67
67
  }) => void;
68
68
  };
69
+ type ToolEditor = {
70
+ namespace: (entry: {
71
+ name: string;
72
+ description: string;
73
+ }) => void;
74
+ add: (tool: {
75
+ name: string;
76
+ description: string;
77
+ input: Record<string, unknown>;
78
+ options?: {
79
+ namespace?: string;
80
+ codemode?: boolean;
81
+ };
82
+ execute: (input: unknown, context: {
83
+ signal: AbortSignal;
84
+ }) => Promise<{
85
+ content: string;
86
+ }>;
87
+ }) => void;
88
+ };
89
+ type SkillEditor = {
90
+ add: (skill: {
91
+ id: string;
92
+ name: string;
93
+ description: string;
94
+ path: string;
95
+ content: string;
96
+ }) => void;
97
+ };
69
98
  type PluginContext = {
70
99
  /** Object-form plugin options from opencode.jsonc. Absent when the package is listed as a string. */
71
100
  options?: unknown;
101
+ tool?: {
102
+ transform: (callback: (editor: ToolEditor) => void) => Promise<Registration>;
103
+ };
104
+ skill?: {
105
+ transform: (callback: (editor: SkillEditor) => void) => Promise<Registration>;
106
+ };
72
107
  provider?: {
73
108
  transform: (callback: (editor: ProviderEditor) => void) => Promise<Registration>;
74
109
  reload: () => Promise<void>;
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { i as resolveModelPricingKey, n as getModelPricing } from "./model-pricing-BbteicIQ.mjs";
2
+ import { fileURLToPath } from "node:url";
2
3
  import { createHash, randomUUID } from "node:crypto";
3
4
  import { access, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
4
- import { homedir } from "node:os";
5
+ import { homedir, tmpdir } from "node:os";
5
6
  import { delimiter, dirname, join } from "node:path";
6
7
  import { spawn } from "node:child_process";
7
8
  import { constants } from "node:fs";
@@ -426,7 +427,7 @@ const buildInventory = (rows, baseURL, options = {}) => {
426
427
  name: displayName(row.display_name ?? modelID),
427
428
  cost,
428
429
  limit: {
429
- context: row.context_window || 128e3,
430
+ context: row.context_window || 256e3,
430
431
  output: row.max_output_tokens || 32e3
431
432
  },
432
433
  modalities: row.modalities,
@@ -682,6 +683,165 @@ const fetchModels = async (baseURL, token = "magpie") => {
682
683
  return body.data;
683
684
  };
684
685
 
686
+ //#endregion
687
+ //#region src/image.ts
688
+ /** The image models Magpie draws with: only a caller that asks (X-Magpie-Drawers) is told of them. */
689
+ const listImageModels = async (connection, signal) => {
690
+ await connection.ensure();
691
+ const response = await fetch(`${connection.baseURL}/models`, {
692
+ headers: {
693
+ Authorization: `Bearer ${connection.token}`,
694
+ "X-Magpie-Drawers": "1",
695
+ "X-Magpie-Agent": "opencode"
696
+ },
697
+ redirect: "error",
698
+ signal: AbortSignal.any([AbortSignal.timeout(15e3), ...signal ? [signal] : []])
699
+ });
700
+ if (!response.ok) throw new Error(`Magpie 模型列表失败:HTTP ${response.status}`);
701
+ const rows = ((await response.json().catch(() => void 0))?.data ?? []).flatMap((row) => row.kind === "image" && typeof row.id === "string" ? [{
702
+ id: row.id,
703
+ name: typeof row.display_name === "string" ? row.display_name : row.id
704
+ }] : []);
705
+ const ids = new Set(rows.map((row) => row.id));
706
+ return rows.filter((row) => !(row.id.startsWith("remote-magpie/") && ids.has(row.id.slice(14))));
707
+ };
708
+ const extension = (bytes) => bytes.subarray(0, 4).equals(Buffer.from([
709
+ 137,
710
+ 80,
711
+ 78,
712
+ 71
713
+ ])) ? ".png" : bytes.subarray(0, 3).equals(Buffer.from([
714
+ 255,
715
+ 216,
716
+ 255
717
+ ])) ? ".jpg" : bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP" ? ".webp" : bytes.subarray(0, 3).toString("latin1") === "GIF" ? ".gif" : ".png";
718
+ /** Draws one image through Magpie's /images/generations and keeps it in the temp folder. */
719
+ const drawImage = async (connection, input, signal) => {
720
+ await connection.ensure();
721
+ const response = await fetch(`${connection.baseURL}/images/generations`, {
722
+ method: "POST",
723
+ headers: {
724
+ Authorization: `Bearer ${connection.token}`,
725
+ "Content-Type": "application/json",
726
+ "X-Magpie-Agent": "opencode"
727
+ },
728
+ body: JSON.stringify({
729
+ ...input,
730
+ n: 1,
731
+ response_format: "b64_json"
732
+ }),
733
+ redirect: "error",
734
+ signal: AbortSignal.any([AbortSignal.timeout(10 * 6e4), ...signal ? [signal] : []])
735
+ });
736
+ const body = await response.json().catch(() => void 0);
737
+ if (!response.ok) throw new Error(body?.error?.message ?? `Magpie 生图失败:HTTP ${response.status}`);
738
+ const image = body?.data?.[0];
739
+ let bytes;
740
+ if (image?.b64_json) bytes = Buffer.from(image.b64_json, "base64");
741
+ else if (image?.url) {
742
+ const download = await fetch(image.url, {
743
+ redirect: "error",
744
+ signal
745
+ });
746
+ if (download.ok) bytes = Buffer.from(await download.arrayBuffer());
747
+ }
748
+ if (!bytes?.length) throw new Error("Magpie 没有返回图片。");
749
+ const folder = join(tmpdir(), "magpie-images");
750
+ await mkdir(folder, { recursive: true });
751
+ const path = join(folder, `image-${Date.now()}${extension(bytes)}`);
752
+ await writeFile(path, bytes);
753
+ return {
754
+ path,
755
+ model: body?.model ?? input.model
756
+ };
757
+ };
758
+ /** `![]()` for the saved file; a path with spaces or brackets goes in angle brackets so it still parses. */
759
+ const markdownImage = (path) => `![image](${/[\s()[\]]/.test(path) ? `<${path}>` : path})`;
760
+ const NAMESPACE = "magpie";
761
+ /** One call to the model's code mode: found with `search`, never listed in its context. */
762
+ const registerImageTools = (editor, connection) => {
763
+ editor.namespace({
764
+ name: NAMESPACE,
765
+ description: "Magpie image generation."
766
+ });
767
+ const options = {
768
+ namespace: NAMESPACE,
769
+ codemode: true
770
+ };
771
+ editor.add({
772
+ name: "image_list",
773
+ description: "List the image models Magpie can draw with, one provider/model id per line.",
774
+ input: {
775
+ type: "object",
776
+ properties: {},
777
+ additionalProperties: false
778
+ },
779
+ options,
780
+ execute: async (_input, context) => {
781
+ const models = await listImageModels(connection, context.signal);
782
+ return { content: models.length ? models.map((model) => `${model.id} ${model.name}`).join("\n") : "No image model is available in Magpie." };
783
+ }
784
+ });
785
+ editor.add({
786
+ name: "image_gen",
787
+ description: "Draw one image through Magpie and save it. Returns it as a Markdown image. Load skill magpie-image-generate first.",
788
+ input: {
789
+ type: "object",
790
+ properties: {
791
+ prompt: {
792
+ type: "string",
793
+ minLength: 1
794
+ },
795
+ model: {
796
+ type: "string",
797
+ description: "provider/model from image_list; omit for Magpie’s default."
798
+ },
799
+ size: {
800
+ type: "string",
801
+ description: "16:9, 9:16, 1:1 or WIDTHxHEIGHT."
802
+ },
803
+ quality: {
804
+ type: "string",
805
+ description: "low, medium, high or auto."
806
+ }
807
+ },
808
+ required: ["prompt"],
809
+ additionalProperties: false
810
+ },
811
+ options,
812
+ execute: async (input, context) => {
813
+ const { path, model } = await drawImage(connection, input, context.signal);
814
+ return { content: `${markdownImage(path)}${model ? `\n(${model})` : ""}` };
815
+ }
816
+ });
817
+ };
818
+ const IMAGE_SKILL_ID = "magpie-image-generate";
819
+ const SKILL = [
820
+ "# Magpie image generation",
821
+ "",
822
+ "Tools: `tools.magpie.image_list`, `tools.magpie.image_gen` (code mode).",
823
+ "",
824
+ "1. Pick the model. Use the one the user named; otherwise omit `model` and Magpie draws with its default. To see what exists, call `image_list` and copy an id from it.",
825
+ " Done when you hold a model id or have chosen the default.",
826
+ "2. Write the prompt: subject, style, composition, colours, and any text to render verbatim. Size `16:9`, `9:16`, `1:1` or `WIDTHxHEIGHT`; quality `low` for drafts, `high` for finals.",
827
+ " Some models take only an exact `WIDTHxHEIGHT` such as `1024x1024`: after a size error, retry with that.",
828
+ " Done when the prompt is non-empty.",
829
+ "3. Call `image_gen` once. It waits until the image is saved, which can take minutes, and returns a Markdown image `![image](<path>)`.",
830
+ " Done when you have that line.",
831
+ "4. Put the returned Markdown image in your reply body as it is. Copy the file into the project with the shell when the user wants it there. A failure message (quota, credits, a reset time) goes to the user as written.",
832
+ "",
833
+ "Each image spends the user’s credits: generate once per request."
834
+ ].join("\n");
835
+ const registerImageSkill = (editor, path) => {
836
+ editor.add({
837
+ id: IMAGE_SKILL_ID,
838
+ name: IMAGE_SKILL_ID,
839
+ description: "Magpie image generation: load before drawing or generating any image, picture, illustration or icon.",
840
+ path,
841
+ content: SKILL
842
+ });
843
+ };
844
+
685
845
  //#endregion
686
846
  //#region src/index.ts
687
847
  const plugin = {
@@ -717,6 +877,10 @@ const setupPlugin = async (ctx) => {
717
877
  "generate",
718
878
  "title"
719
879
  ]) await track(ctx.session.hook(name, normalizeOpenAICallIDs, { providerID: "openai" }));
880
+ if (ctx.tool && ctx.skill) {
881
+ await track(ctx.tool.transform((editor) => registerImageTools(editor, connection)));
882
+ await track(ctx.skill.transform((editor) => registerImageSkill(editor, fileURLToPath(new URL("./", import.meta.url)))));
883
+ }
720
884
  await track(ctx.session.hook("http.request", async (event) => {
721
885
  const url = new URL(event.request.url);
722
886
  if (url.origin !== apiURL.origin || !url.pathname.startsWith(`${apiURL.pathname.replace(/\/$/, "")}/`)) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-magpie-plugin",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Discover Magpie providers and models in OpenCode V2 with built-in pricing and automatic local gateway startup",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",