opencode-image 0.1.1 → 0.1.2

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
@@ -31,12 +31,14 @@ opencode 启动时会自动从 npm 安装插件到 `~/.cache/opencode/packages/o
31
31
  | `apiKey` | `PI_IMAGE_API_KEY` | **必填**。接口密钥,建议用环境变量而不是写进配置 |
32
32
  | `baseURL` | `PI_IMAGE_BASE_URL` 或内置默认 | OpenAI 兼容接口地址 |
33
33
  | `model` | `gpt-image-2` | 模型名 |
34
- | `outDir` | `<项目目录>/.opencode-images` | 图片输出目录,相对路径基于当前项目 |
34
+ | `outDir` | `<数据目录>/opencode-image` | 图片输出目录。默认全局,与项目/会话解耦;填相对路径(如 `.opencode-images`)则落到当前项目 |
35
35
  | `maxSize` | `1024` | 落盘图片最长边上限,超出等比缩小 |
36
- | `displayMaxSize` | `448` | 仅在对话里展示的尺寸,不影响落盘原图 |
36
+ | `displayMaxSize` | `0` | 对话里展示的最长边。`0` = 不缩放,**直接显示原图**(右键复制/另存拿到的就是原图) |
37
37
  | `serverPort` | `0` | 本地图片服务端口。`0` = 由项目目录派生(同一项目恒定,保证历史链接跨重启有效) |
38
38
  | `serverIdleMs` | `0` | 本地图片服务空闲关闭时间(毫秒),`0` = 不主动关闭 |
39
39
  | `updateCheck` | `true` | 首次出图时查一次 npm 最新版,落后则在工具输出末尾附升级提示 |
40
+ | `cacheDir` | `<系统临时目录>/opencode-image` | 对话里展示用的缩略图缓存目录 |
41
+ | `cacheLimit` | `50` | 缩略图缓存最多保留多少个文件,超出按最久未访问淘汰;`0` = 不限制 |
40
42
  | `timeoutMs` | `600000` | 单次请求超时 |
41
43
 
42
44
  ## 图片是怎么显示出来的
@@ -44,11 +46,20 @@ opencode 启动时会自动从 npm 安装插件到 `~/.cache/opencode/packages/o
44
46
  openCode(桌面端 / Web)**只在助手回复的 Markdown 正文里渲染图片**,工具输出一律按纯文本处理。
45
47
  而正文里的 `file://` 会被 Chromium 拦掉,所以插件做了这件事:
46
48
 
47
- 1. 图片落盘到 `outDir`
49
+ 1. 图片落盘到 `outDir`(默认是全局数据目录,不在项目里)
48
50
  2. 插件进程内起一个只绑 `127.0.0.1` 的 HTTP 服务
49
- 3. 工具输出第一行给出 `![alt](http://127.0.0.1:<port>/img/<id>?w=448)`
51
+ 3. 工具输出给出 `![alt](...)`(`displayMaxSize = 0` 时就是原图)
50
52
  4. 工具描述里强制模型把这行**原样抄进回复正文**
51
53
 
54
+ > **不支持「图片套链接」**:opencode 覆写了 marked 的 link renderer,取的是链接里的原始文本,
55
+ > `[![图](缩略图)](原图)` 里的图片不会被渲染。所以缩略图模式下改成两行:
56
+ > `![alt](缩略图)` + `[查看原图](原图)`。
57
+ >
58
+ > 显示原图还是缩略图只取决于 `displayMaxSize`:
59
+ > - `0`(默认)→ 直接显示原图,会话里右键 Copy / Save 拿到的就是原图
60
+ > - `> 0`(如 `448`)→ 会话里显示轻量缩略图,下面附带一个「查看原图」链接,
61
+ > 点击会用系统浏览器打开原图(opencode 把所有外链交给系统浏览器)
62
+
52
63
  **链接为什么跨重启还有效**:`id` 是「文件相对 `outDir` 的路径」的 base64url 编码,可逆且稳定;
53
64
  端口默认由项目目录派生(同一项目恒定)。所以服务**不需要任何内存登记表**,
54
65
  重启后历史消息里的旧链接仍能解析到同一个文件。
@@ -93,6 +104,51 @@ git commit -am "..." # npm version 要求工作区干净
93
104
  npm run release # = version patch + publish + 清掉本机缓存
94
105
  ```
95
106
 
107
+ ## 图片放在哪
108
+
109
+ 默认落在 **opencode 的数据目录**(`<XDG_DATA_HOME>/opencode/opencode-image/`,macOS/Linux 即
110
+ `~/.local/share/opencode/opencode-image/`),跟 `opencode.db` 同级。
111
+
112
+ 这样设计的原因:
113
+
114
+ - **不与项目/会话绑定**:换目录打开老会话、删掉项目、移动仓库,历史里的图都还在
115
+ - **不污染工作区**:不再出现在 git 变更里
116
+ - **全机一个服务**:根目录固定 → 端口由它派生 → 所有会话共用一个本地服务,而不是每个项目一个
117
+
118
+ 只有当你确实要让图片成为项目资产时,才把 `outDir` 设成项目内路径(如 `".opencode-images"`),
119
+ 或者让 agent 把图复制进仓库 —— 这与 Codex 的做法一致(Codex 默认存 `$CODEX_HOME/generated_images/`,
120
+ 需要在项目里用时再复制过去)。
121
+
122
+ ## 缓存与清理
123
+
124
+ 有两处"缓存",职责完全不同,别搞混:
125
+
126
+ | 是什么 | 在哪 | 删了会怎样 |
127
+ |---|---|---|
128
+ | **生成的图片本体** | `<数据目录>/opencode-image/`(`outDir` 可配;macOS/Linux 默认 `~/.local/share/opencode/opencode-image/`) | **会话里的图片会 404**。服务按路径解析,源文件没了就找不到 |
129
+ | **对话缩略图**(448px) | `<系统临时目录>/opencode-image/`(`cacheDir` 可配) | 无影响,下次打开会按需重新生成 |
130
+
131
+ 缩略图缓存文件名由「源文件路径 + 大小 + mtime + 目标宽度」哈希而成,所以同一张图不会重复生成,跨重启也能复用。
132
+ 超过 `cacheLimit`(默认 50 个)时按最久未访问淘汰,并在**下一次工具输出末尾**提醒你(含目录、数量、总大小、最旧一个存在了多久)——每进程只提醒一次,不刷屏。
133
+
134
+ 清理缩略图缓存(两种方式等价):
135
+
136
+ ```sh
137
+ npx opencode-image --clean-cache
138
+ # 如果你改过 cacheDir:
139
+ npx opencode-image --clean-cache --cache-dir /your/cache/dir
140
+ ```
141
+
142
+ 也可以直接在会话里让 agent 调用 `image_cache`:
143
+
144
+ - `image_cache(action="status")` —— 目录、数量、总大小、最旧一个多久了
145
+ - `image_cache(action="clean")` —— 清空缩略图缓存(不动 `outDir` 里的原图)
146
+
147
+ > **建议**:把输出目录加进项目 `.gitignore`,否则每画一张图都会出现在 git 变更里:
148
+ > ```
149
+ > .opencode-images/
150
+ > ```
151
+
96
152
  ## 环境变量
97
153
 
98
154
  ```bash
package/bin/cli.js CHANGED
@@ -4,6 +4,9 @@ import * as os from "node:os"
4
4
  import * as path from "node:path"
5
5
 
6
6
  const PACKAGE = "opencode-image"
7
+ const DEFAULT_CACHE_DIR = path.join(os.tmpdir(), "opencode-image")
8
+
9
+ const args = process.argv.slice(2)
7
10
 
8
11
  const version = (() => {
9
12
  try {
@@ -17,22 +20,38 @@ const version = (() => {
17
20
  const USAGE = `${PACKAGE} v${version}
18
21
 
19
22
  用法:
20
- npx ${PACKAGE} --update 清理 opencode 的插件缓存,然后重启 opencode 即可装上最新版
21
- npx ${PACKAGE} --version 显示版本
22
- npx ${PACKAGE} --help 显示帮助
23
+ npx ${PACKAGE} --update 清理 opencode 的插件缓存并重启 opencode,即可装上最新版
24
+ npx ${PACKAGE} --clean-cache 清理对话缩略图缓存(不影响生成的图片)
25
+ npx ${PACKAGE} --version 显示版本
26
+ npx ${PACKAGE} --help 显示帮助
27
+
28
+ 选项:
29
+ --cache-dir <path> 缩略图缓存目录,默认 <系统临时目录>/opencode-image
30
+ (如果你的配置里改过 cacheDir,用这个参数或 OPENCODE_IMAGE_CACHE_DIR 指过去)
23
31
 
24
32
  为什么需要 --update:
25
33
  opencode 对 npm 形式的插件不做版本检查——只要缓存目录里已经装过就直接复用。
26
34
  所以发布新版后必须清掉缓存,opencode 才会重新下载。详见 README「升级」一节。
27
35
  `
28
36
 
37
+ function flag(name) {
38
+ const index = args.indexOf(name)
39
+ return index >= 0 ? (args[index + 1] ?? "") : undefined
40
+ }
41
+
42
+ function humanBytes(bytes) {
43
+ if (bytes < 1024) return `${bytes} B`
44
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`
45
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`
46
+ }
47
+
29
48
  /** opencode 的插件缓存在 <cache>/packages/<spec>,spec 可能是 opencode-image 或 opencode-image@latest */
30
- function cacheRoot() {
31
- return process.env.OPENCODE_IMAGE_CACHE_ROOT ?? path.join(os.homedir(), ".cache", "opencode", "packages")
49
+ function pluginCacheRoot() {
50
+ return process.env.OPENCODE_IMAGE_PLUGIN_CACHE ?? path.join(os.homedir(), ".cache", "opencode", "packages")
32
51
  }
33
52
 
34
53
  function update() {
35
- const root = cacheRoot()
54
+ const root = pluginCacheRoot()
36
55
  if (!fs.existsSync(root)) {
37
56
  console.log(`缓存目录不存在,无需清理:${root}`)
38
57
  console.log("直接重启 opencode 即可。")
@@ -58,7 +77,33 @@ function update() {
58
77
  console.log(`✅ 已清理 ${targets.length} 个缓存目录,重启 opencode 后会重新下载最新版。`)
59
78
  }
60
79
 
61
- const args = process.argv.slice(2)
80
+ function cleanCache() {
81
+ const dir = flag("--cache-dir") ?? process.env.OPENCODE_IMAGE_CACHE_DIR ?? DEFAULT_CACHE_DIR
82
+ if (!fs.existsSync(dir)) {
83
+ console.log(`缩略图缓存目录不存在,无需清理:${dir}`)
84
+ return
85
+ }
86
+
87
+ let count = 0
88
+ let bytes = 0
89
+ for (const name of fs.readdirSync(dir)) {
90
+ if (!name.endsWith(".png")) continue
91
+ const file = path.join(dir, name)
92
+ try {
93
+ const stat = fs.statSync(file)
94
+ if (!stat.isFile()) continue
95
+ bytes += stat.size
96
+ count += 1
97
+ fs.rmSync(file, { force: true })
98
+ } catch {
99
+ // 单个文件删不掉就跳过,最后按实际删掉的数量汇报
100
+ }
101
+ }
102
+
103
+ console.log(`✅ 已清理缩略图缓存:${count} 个文件 / ${humanBytes(bytes)}`)
104
+ console.log(`目录:${dir}`)
105
+ console.log("生成的图片不受影响,会话里的图片仍能显示(需要时会重新生成缩略图)。")
106
+ }
62
107
 
63
108
  if (args.includes("--help") || args.includes("-h")) {
64
109
  console.log(USAGE)
@@ -75,5 +120,10 @@ if (args.includes("--update")) {
75
120
  process.exit(0)
76
121
  }
77
122
 
123
+ if (args.includes("--clean-cache")) {
124
+ cleanCache()
125
+ process.exit(0)
126
+ }
127
+
78
128
  console.log(USAGE)
79
129
  process.exit(1)
@@ -0,0 +1,44 @@
1
+ export declare const DEFAULT_CACHE_DIR: string;
2
+ export declare const DEFAULT_CACHE_LIMIT = 50;
3
+ export type CacheStats = {
4
+ dir: string;
5
+ count: number;
6
+ bytes: number;
7
+ /** 最旧一个预览文件已经存在了多久(毫秒);空缓存时为 undefined */
8
+ oldestMs?: number;
9
+ };
10
+ export declare function humanBytes(bytes: number): string;
11
+ export declare function humanAge(ms: number): string;
12
+ /**
13
+ * 对话里展示用的缩略图缓存。
14
+ *
15
+ * 文件名由「源文件绝对路径 + 文件大小 + mtime + 目标宽度」哈希而成,所以:
16
+ * - 同一个文件同一尺寸永远命中同一个文件名 → 不重复生成,跨重启也能复用
17
+ * - 源文件内容变了(mtime/size 变)就是新 key → 不会拿到过期缩略图
18
+ * - 缓存目录里只有我们自己的 *.png,清理时不会误伤其它文件
19
+ *
20
+ * 超过上限时按访问时间(mtime,命中时会 utimes 刷新)淘汰最旧的,并记一条待展示的通知。
21
+ */
22
+ export declare class PreviewCache {
23
+ private readonly dir;
24
+ private readonly limit;
25
+ private notice?;
26
+ constructor(dir: string, limit: number);
27
+ get directory(): string;
28
+ private target;
29
+ /** 命中则刷新访问时间并返回缓存文件;未命中返回 undefined */
30
+ hit(source: string, max: number): string | undefined;
31
+ /** 收下一个新生成的预览文件(从临时位置挪进缓存),并按需淘汰 */
32
+ put(source: string, max: number, generated: string): string;
33
+ stats(): CacheStats;
34
+ /** 一次性取走待展示的溢出通知 */
35
+ consumeNotice(): string | undefined;
36
+ /** 清空缓存目录里由本插件生成的预览文件 */
37
+ clean(): {
38
+ dir: string;
39
+ count: number;
40
+ bytes: number;
41
+ };
42
+ private entries;
43
+ private enforce;
44
+ }
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/index.ts
2
2
  import { tool } from "@opencode-ai/plugin";
3
- import * as fs4 from "node:fs";
4
- import * as path3 from "node:path";
3
+ import * as fs5 from "node:fs";
4
+ import * as path5 from "node:path";
5
5
 
6
6
  // src/api.ts
7
7
  function parseImageResponse(body) {
@@ -88,9 +88,137 @@ async function editImage(config, source, filename, prompt, signal) {
88
88
  return readImage(res, "POST /images/edits");
89
89
  }
90
90
 
91
- // src/image.ts
91
+ // src/cache.ts
92
92
  import * as fs from "node:fs";
93
+ import * as os from "node:os";
93
94
  import * as path from "node:path";
95
+ import { createHash } from "node:crypto";
96
+ var DEFAULT_CACHE_DIR = path.join(os.tmpdir(), "opencode-image");
97
+ var DEFAULT_CACHE_LIMIT = 50;
98
+ function humanBytes(bytes) {
99
+ if (bytes < 1024)
100
+ return `${bytes} B`;
101
+ if (bytes < 1024 * 1024)
102
+ return `${(bytes / 1024).toFixed(0)} KB`;
103
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
104
+ }
105
+ function humanAge(ms) {
106
+ const minutes = Math.floor(ms / 60000);
107
+ if (minutes < 1)
108
+ return "不到 1 分钟";
109
+ if (minutes < 60)
110
+ return `${minutes} 分钟`;
111
+ const hours = Math.floor(minutes / 60);
112
+ if (hours < 24)
113
+ return `${hours} 小时`;
114
+ return `${Math.floor(hours / 24)} 天`;
115
+ }
116
+
117
+ class PreviewCache {
118
+ dir;
119
+ limit;
120
+ notice;
121
+ constructor(dir, limit) {
122
+ this.dir = dir;
123
+ this.limit = limit;
124
+ }
125
+ get directory() {
126
+ return this.dir;
127
+ }
128
+ target(source, max) {
129
+ let stat;
130
+ try {
131
+ stat = fs.statSync(source);
132
+ } catch {
133
+ return;
134
+ }
135
+ const hash = createHash("sha1").update(`${path.resolve(source)}|${stat.size}|${Math.floor(stat.mtimeMs)}|${max}`).digest("hex").slice(0, 16);
136
+ return path.join(this.dir, `${hash}.png`);
137
+ }
138
+ hit(source, max) {
139
+ const file = this.target(source, max);
140
+ if (!file || !fs.existsSync(file))
141
+ return;
142
+ const now = new Date;
143
+ try {
144
+ fs.utimesSync(file, now, now);
145
+ } catch {}
146
+ return file;
147
+ }
148
+ put(source, max, generated) {
149
+ const file = this.target(source, max);
150
+ if (!file)
151
+ return generated;
152
+ fs.mkdirSync(this.dir, { recursive: true });
153
+ if (path.resolve(file) !== path.resolve(generated))
154
+ fs.renameSync(generated, file);
155
+ const now = new Date;
156
+ fs.utimesSync(file, now, now);
157
+ this.enforce();
158
+ return file;
159
+ }
160
+ stats() {
161
+ const entries = this.entries();
162
+ const bytes = entries.reduce((sum, entry) => sum + entry.size, 0);
163
+ if (entries.length === 0)
164
+ return { dir: this.dir, count: 0, bytes: 0 };
165
+ const oldest = Math.min(...entries.map((entry) => entry.mtimeMs));
166
+ return { dir: this.dir, count: entries.length, bytes, oldestMs: Date.now() - oldest };
167
+ }
168
+ consumeNotice() {
169
+ const notice = this.notice;
170
+ this.notice = undefined;
171
+ return notice;
172
+ }
173
+ clean() {
174
+ const entries = this.entries();
175
+ const bytes = entries.reduce((sum, entry) => sum + entry.size, 0);
176
+ for (const entry of entries)
177
+ fs.rmSync(entry.file, { force: true });
178
+ this.notice = undefined;
179
+ return { dir: this.dir, count: entries.length, bytes };
180
+ }
181
+ entries() {
182
+ try {
183
+ return fs.readdirSync(this.dir).filter((name) => name.endsWith(".png")).flatMap((name) => {
184
+ const file = path.join(this.dir, name);
185
+ try {
186
+ const stat = fs.statSync(file);
187
+ return stat.isFile() ? [{ file, size: stat.size, mtimeMs: stat.mtimeMs }] : [];
188
+ } catch {
189
+ return [];
190
+ }
191
+ });
192
+ } catch {
193
+ return [];
194
+ }
195
+ }
196
+ enforce() {
197
+ if (this.limit <= 0)
198
+ return;
199
+ const entries = this.entries();
200
+ if (entries.length <= this.limit)
201
+ return;
202
+ entries.sort((a, b) => a.mtimeMs - b.mtimeMs);
203
+ for (const entry of entries.slice(0, entries.length - this.limit)) {
204
+ fs.rmSync(entry.file, { force: true });
205
+ }
206
+ if (this.notice)
207
+ return;
208
+ const stats = this.stats();
209
+ this.notice = [
210
+ `[请转述给用户] 图片预览缓存已达上限(${this.limit} 个),已自动清理最旧的。`,
211
+ `目录:${stats.dir}`,
212
+ `当前:${stats.count} 个 / ${humanBytes(stats.bytes)}` + (stats.oldestMs === undefined ? "" : `,最旧一个存在了 ${humanAge(stats.oldestMs)}`),
213
+ `彻底清理:让 agent 调用 image_cache(action="clean"),或运行 npx opencode-image --clean-cache`
214
+ ].join(`
215
+ `);
216
+ }
217
+ }
218
+
219
+ // src/image.ts
220
+ import * as fs2 from "node:fs";
221
+ import * as path2 from "node:path";
94
222
  import sharp from "sharp";
95
223
  function fitInside(max) {
96
224
  return { width: max, height: max, fit: "inside", withoutEnlargement: true };
@@ -115,9 +243,9 @@ async function renderPreview(source, destination, max) {
115
243
  return destination;
116
244
  }
117
245
  async function persistImage(raw, destination, maxSize) {
118
- fs.mkdirSync(path.dirname(destination), { recursive: true });
246
+ fs2.mkdirSync(path2.dirname(destination), { recursive: true });
119
247
  const staging = `${destination}.${process.pid}-${Date.now()}.download`;
120
- fs.writeFileSync(staging, raw);
248
+ fs2.writeFileSync(staging, raw);
121
249
  try {
122
250
  const meta = await sharp(staging).metadata();
123
251
  const width = meta.width ?? 0;
@@ -127,16 +255,27 @@ async function persistImage(raw, destination, maxSize) {
127
255
  const pipeline = Math.max(width, height) > maxSize ? sharp(staging).resize(fitInside(maxSize)) : sharp(staging);
128
256
  await pipeline.png().toFile(destination);
129
257
  } finally {
130
- fs.rmSync(staging, { force: true });
258
+ fs2.rmSync(staging, { force: true });
131
259
  }
132
260
  return imageDimensions(destination);
133
261
  }
134
262
 
135
263
  // src/options.ts
264
+ import * as os2 from "node:os";
265
+ import * as path3 from "node:path";
266
+ function defaultImageDir(env = process.env, home = os2.homedir()) {
267
+ const base = env.XDG_DATA_HOME?.trim() || path3.join(home, ".local", "share");
268
+ return path3.join(base, "opencode", "opencode-image");
269
+ }
270
+ function resolveOutDir(directory, outDir) {
271
+ if (!outDir)
272
+ return defaultImageDir();
273
+ return path3.isAbsolute(outDir) ? outDir : path3.join(directory, outDir);
274
+ }
136
275
  var DEFAULT_BASE_URL = "https://pi-ai.roiscloud.com/v1";
137
276
  var DEFAULT_MODEL = "gpt-image-2";
138
277
  var DEFAULT_MAX_SIZE = 1024;
139
- var DEFAULT_DISPLAY_MAX_SIZE = 448;
278
+ var DEFAULT_DISPLAY_MAX_SIZE = 0;
140
279
  var DEFAULT_SERVER_PORT = 0;
141
280
  var DEFAULT_SERVER_IDLE_MS = 0;
142
281
  var DEFAULT_TIMEOUT_MS = 600000;
@@ -156,12 +295,14 @@ function resolveOptions(options) {
156
295
  serverPort: opts.serverPort ?? DEFAULT_SERVER_PORT,
157
296
  serverIdleMs: opts.serverIdleMs ?? DEFAULT_SERVER_IDLE_MS,
158
297
  updateCheck: opts.updateCheck ?? true,
298
+ cacheDir: opts.cacheDir ?? DEFAULT_CACHE_DIR,
299
+ cacheLimit: opts.cacheLimit ?? DEFAULT_CACHE_LIMIT,
159
300
  timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
160
301
  };
161
302
  }
162
303
 
163
304
  // src/update.ts
164
- import * as fs2 from "node:fs";
305
+ import * as fs3 from "node:fs";
165
306
  var REGISTRY = "https://registry.npmjs.org";
166
307
  var PACKAGE = "opencode-image";
167
308
  function parse(version) {
@@ -187,14 +328,14 @@ function isNewer(candidate, current) {
187
328
  function readOwnVersion() {
188
329
  try {
189
330
  const file = new URL("../package.json", import.meta.url);
190
- const pkg = JSON.parse(fs2.readFileSync(file, "utf8"));
331
+ const pkg = JSON.parse(fs3.readFileSync(file, "utf8"));
191
332
  return pkg.version;
192
333
  } catch {
193
334
  return;
194
335
  }
195
336
  }
196
337
  function upgradeHint(latest, current) {
197
- return `提示:${PACKAGE} 有新版本 ${latest}(当前 ${current})。升级:npx ${PACKAGE} --update 然后重启 opencode。`;
338
+ return `[请转述给用户] ${PACKAGE} 有新版本 ${latest}(当前 ${current})。升级:npx ${PACKAGE} --update 然后重启 opencode。`;
198
339
  }
199
340
  async function checkForUpdate(current, timeoutMs = 3000) {
200
341
  const controller = new AbortController;
@@ -218,11 +359,11 @@ async function checkForUpdate(current, timeoutMs = 3000) {
218
359
  }
219
360
 
220
361
  // src/server.ts
221
- import * as fs3 from "node:fs";
362
+ import * as fs4 from "node:fs";
222
363
  import * as http from "node:http";
223
- import * as os from "node:os";
224
- import * as path2 from "node:path";
225
- import { createHash, randomUUID } from "node:crypto";
364
+ import * as os3 from "node:os";
365
+ import * as path4 from "node:path";
366
+ import { createHash as createHash2, randomUUID } from "node:crypto";
226
367
  var MIME_BY_EXT = {
227
368
  ".png": "image/png",
228
369
  ".jpg": "image/jpeg",
@@ -230,28 +371,29 @@ var MIME_BY_EXT = {
230
371
  ".webp": "image/webp",
231
372
  ".gif": "image/gif"
232
373
  };
233
- var ID_PATTERN = /^\/img\/([A-Za-z0-9_-]{1,2048})$/;
374
+ var ID_PATTERN = /^\/img\/([A-Za-z0-9_-]{1,2048})(?:\/[^/]*)?$/;
234
375
  var APP_NAME = "opencode-image";
235
376
  function derivePort(key) {
236
- const digest = createHash("sha1").update(key).digest();
377
+ const digest = createHash2("sha1").update(key).digest();
237
378
  return 41000 + digest.readUInt16BE(0) % 4000;
238
379
  }
239
380
 
240
381
  class ImageServer {
241
382
  idleMs;
242
383
  configuredPort;
384
+ cache;
243
385
  server;
244
386
  port = 0;
245
387
  root;
246
388
  ready = false;
247
389
  owned = false;
248
390
  extra = new Map;
249
- previews = new Map;
250
391
  timer;
251
392
  starting;
252
- constructor(idleMs, configuredPort) {
393
+ constructor(idleMs, configuredPort, cache) {
253
394
  this.idleMs = idleMs;
254
395
  this.configuredPort = configuredPort;
396
+ this.cache = cache;
255
397
  }
256
398
  get baseURL() {
257
399
  return this.port ? `http://127.0.0.1:${this.port}` : "";
@@ -259,9 +401,9 @@ class ImageServer {
259
401
  idFor(file) {
260
402
  const root = this.root;
261
403
  if (root) {
262
- const relative2 = path2.relative(root, file);
263
- if (relative2 && !relative2.startsWith("..") && !path2.isAbsolute(relative2)) {
264
- return Buffer.from(relative2.split(path2.sep).join("/"), "utf8").toString("base64url");
404
+ const relative2 = path4.relative(root, file);
405
+ if (relative2 && !relative2.startsWith("..") && !path4.isAbsolute(relative2)) {
406
+ return Buffer.from(relative2.split(path4.sep).join("/"), "utf8").toString("base64url");
265
407
  }
266
408
  }
267
409
  for (const [id2, registered] of this.extra) {
@@ -273,10 +415,12 @@ class ImageServer {
273
415
  return id;
274
416
  }
275
417
  url(file, width) {
276
- return `${this.baseURL}/img/${this.idFor(file)}?w=${width}`;
418
+ const query = width > 0 ? `?w=${Math.round(width)}` : "";
419
+ const name = encodeURIComponent(path4.basename(file));
420
+ return `${this.baseURL}/img/${this.idFor(file)}/${name}${query}`;
277
421
  }
278
422
  async start(opts) {
279
- this.root = path2.resolve(opts.outDir);
423
+ this.root = path4.resolve(opts.outDir);
280
424
  if (this.ready) {
281
425
  this.arm();
282
426
  return;
@@ -302,17 +446,23 @@ class ImageServer {
302
446
  this.owned = false;
303
447
  this.ready = false;
304
448
  this.port = 0;
305
- for (const file of this.previews.values())
306
- fs3.rmSync(file, { force: true });
307
- this.previews.clear();
449
+ }
450
+ cacheStats() {
451
+ return this.cache.stats();
452
+ }
453
+ cleanCache() {
454
+ return this.cache.clean();
455
+ }
456
+ consumeCacheNotice() {
457
+ return this.cache.consumeNotice();
308
458
  }
309
459
  async listen(opts) {
310
- const port = this.configuredPort || derivePort(opts.directory);
460
+ const port = this.configuredPort || derivePort(path4.resolve(opts.outDir));
311
461
  const server = http.createServer((req, res) => void this.handle(req, res));
312
462
  server.unref();
313
- const failure = await new Promise((resolve2) => {
314
- server.once("error", resolve2);
315
- server.listen(port, "127.0.0.1", () => resolve2(undefined));
463
+ const failure = await new Promise((resolve3) => {
464
+ server.once("error", resolve3);
465
+ server.listen(port, "127.0.0.1", () => resolve3(undefined));
316
466
  });
317
467
  if (!failure) {
318
468
  this.server = server;
@@ -334,7 +484,7 @@ class ImageServer {
334
484
  if (!res.ok)
335
485
  return false;
336
486
  const body = await res.json();
337
- return body.app === APP_NAME && body.root === path2.resolve(outDir);
487
+ return body.app === APP_NAME && body.root === path4.resolve(outDir);
338
488
  } catch {
339
489
  return false;
340
490
  }
@@ -347,22 +497,20 @@ class ImageServer {
347
497
  this.timer = setTimeout(() => this.stop(), this.idleMs);
348
498
  this.timer.unref();
349
499
  }
350
- preview(source, max) {
351
- const key = `${source}@${max}`;
352
- const cached = this.previews.get(key);
353
- if (cached && fs3.existsSync(cached))
354
- return Promise.resolve(cached);
355
- const destination = path2.join(os.tmpdir(), `opencode-image-${process.pid}-${randomUUID()}.png`);
356
- return renderPreview(source, destination, max).then((file) => {
357
- if (file !== source)
358
- this.previews.set(key, file);
359
- return file;
360
- });
500
+ async preview(source, max) {
501
+ const hit = this.cache.hit(source, max);
502
+ if (hit)
503
+ return hit;
504
+ const staging = path4.join(os3.tmpdir(), `opencode-image-${process.pid}-${randomUUID()}.png`);
505
+ const rendered = await renderPreview(source, staging, max);
506
+ if (rendered === source)
507
+ return source;
508
+ return this.cache.put(source, max, rendered);
361
509
  }
362
510
  resolve(id) {
363
511
  const registered = this.extra.get(id);
364
512
  if (registered)
365
- return fs3.existsSync(registered) ? registered : undefined;
513
+ return fs4.existsSync(registered) ? registered : undefined;
366
514
  const root = this.root;
367
515
  if (!root)
368
516
  return;
@@ -372,17 +520,17 @@ class ImageServer {
372
520
  } catch {
373
521
  return;
374
522
  }
375
- if (!relative2 || relative2.includes("\x00") || path2.isAbsolute(relative2))
523
+ if (!relative2 || relative2.includes("\x00") || path4.isAbsolute(relative2))
376
524
  return;
377
- const target = path2.resolve(root, relative2);
378
- if (target === root || !target.startsWith(root + path2.sep))
525
+ const target = path4.resolve(root, relative2);
526
+ if (target === root || !target.startsWith(root + path4.sep))
379
527
  return;
380
528
  try {
381
- if (!fs3.statSync(target).isFile())
529
+ if (!fs4.statSync(target).isFile())
382
530
  return;
383
- const real = fs3.realpathSync(target);
384
- const realRoot = fs3.realpathSync(root);
385
- if (real !== realRoot && !real.startsWith(realRoot + path2.sep))
531
+ const real = fs4.realpathSync(target);
532
+ const realRoot = fs4.realpathSync(root);
533
+ if (real !== realRoot && !real.startsWith(realRoot + path4.sep))
386
534
  return;
387
535
  } catch {
388
536
  return;
@@ -410,9 +558,9 @@ class ImageServer {
410
558
  async send(file, width, res) {
411
559
  try {
412
560
  const target = width > 0 ? await this.preview(file, Math.round(width)) : file;
413
- const body = fs3.readFileSync(target);
561
+ const body = fs4.readFileSync(target);
414
562
  res.writeHead(200, {
415
- "content-type": MIME_BY_EXT[path2.extname(target).toLowerCase()] ?? "application/octet-stream",
563
+ "content-type": MIME_BY_EXT[path4.extname(target).toLowerCase()] ?? "application/octet-stream",
416
564
  "content-length": body.length,
417
565
  "cache-control": "private, max-age=86400"
418
566
  });
@@ -426,34 +574,30 @@ class ImageServer {
426
574
 
427
575
  // src/index.ts
428
576
  var z = tool.schema;
429
- function resolveOutDir(directory, outDir) {
430
- if (!outDir)
431
- return path3.join(directory, ".opencode-images");
432
- return path3.isAbsolute(outDir) ? outDir : path3.join(directory, outDir);
433
- }
434
577
  function resolveDestination(filename, outDir, ctx) {
435
578
  const dir = resolveOutDir(ctx.directory, outDir);
436
579
  if (filename) {
437
- const target = path3.isAbsolute(filename) ? filename : path3.join(dir, filename);
580
+ const target = path5.isAbsolute(filename) ? filename : path5.join(dir, filename);
438
581
  return `${target.replace(/\.[A-Za-z0-9]+$/, "")}.png`;
439
582
  }
440
583
  const stamp = new Date().toISOString().replace(/\..+$/, "").replace(/[:T]/g, "-");
441
584
  const suffix = Math.random().toString(36).slice(2, 6);
442
- return path3.join(dir, `image-${stamp}-${suffix}.png`);
585
+ return path5.join(dir, `image-${stamp}-${suffix}.png`);
443
586
  }
444
587
  function asAttachment(file) {
445
588
  return [
446
589
  {
447
590
  type: "file",
448
591
  mime: "image/png",
449
- filename: path3.basename(file),
450
- url: `data:image/png;base64,${fs4.readFileSync(file).toString("base64")}`
592
+ filename: path5.basename(file),
593
+ url: `data:image/png;base64,${fs5.readFileSync(file).toString("base64")}`
451
594
  }
452
595
  ];
453
596
  }
454
597
  var OpenCodeImagePlugin = async (_input, rawOptions) => {
455
598
  const options = resolveOptions(rawOptions);
456
- const server = new ImageServer(options.serverIdleMs, options.serverPort);
599
+ const cache = new PreviewCache(options.cacheDir, options.cacheLimit);
600
+ const server = new ImageServer(options.serverIdleMs, options.serverPort, cache);
457
601
  const selfVersion = readOwnVersion();
458
602
  let updateHint;
459
603
  let updateChecked = false;
@@ -468,8 +612,13 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
468
612
  const { width, height } = await imageDimensions(file);
469
613
  let display;
470
614
  try {
471
- await server.start({ directory: ctx.directory, outDir: resolveOutDir(ctx.directory, options.outDir) });
472
- display = `![${prompt.slice(0, 60)}](${server.url(file, options.displayMaxSize)})`;
615
+ await server.start({ outDir: resolveOutDir(ctx.directory, options.outDir) });
616
+ const alt = prompt.slice(0, 60);
617
+ const lines = [`![${alt}](${server.url(file, options.displayMaxSize)})`];
618
+ if (options.displayMaxSize > 0)
619
+ lines.push(`[查看原图](${server.url(file, 0)})`);
620
+ display = lines.join(`
621
+ `);
473
622
  } catch (error) {
474
623
  display = `[opencode-image: local image server unavailable, cannot render inline: ${String(error)}]`;
475
624
  }
@@ -482,6 +631,9 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
482
631
  ];
483
632
  if (notice)
484
633
  output.push(notice);
634
+ const cacheNotice = server.consumeCacheNotice();
635
+ if (cacheNotice)
636
+ output.push(cacheNotice);
485
637
  return {
486
638
  title: `${label}: ${prompt.slice(0, 60)}`,
487
639
  output: output.join(`
@@ -504,14 +656,14 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
504
656
  }
505
657
  };
506
658
  const edit = async (args, ctx) => {
507
- const source = path3.isAbsolute(args.image) ? args.image : path3.resolve(ctx.directory, args.image);
508
- if (!fs4.existsSync(source))
659
+ const source = path5.isAbsolute(args.image) ? args.image : path5.resolve(ctx.directory, args.image);
660
+ if (!fs5.existsSync(source))
509
661
  throw new Error(`image_edit: source image not found: ${source}`);
510
662
  ctx.metadata({ title: `Editing image: ${args.prompt.slice(0, 60)}` });
511
663
  const { signal, clear } = withTimeout(ctx.abort, options.timeoutMs);
512
664
  try {
513
665
  const upload = await toPngBuffer(source, options.maxSize);
514
- const remote = await editImage(options, upload, `${path3.basename(source, path3.extname(source))}.png`, args.prompt, signal);
666
+ const remote = await editImage(options, upload, `${path5.basename(source, path5.extname(source))}.png`, args.prompt, signal);
515
667
  const raw = await fetchImageBytes(remote, signal);
516
668
  const destination = resolveDestination(args.filename, options.outDir, ctx);
517
669
  await persistImage(raw, destination, options.maxSize);
@@ -523,7 +675,7 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
523
675
  return {
524
676
  tool: {
525
677
  image_generate: tool({
526
- description: "Generate a new image from a text prompt using an OpenAI-compatible image API. " + "The result includes a Markdown image line that you MUST copy verbatim into your reply text, " + "otherwise the user cannot see the picture. To iterate on a result, call image_edit with the returned path.",
678
+ description: "Generate a new image from a text prompt using an OpenAI-compatible image API. " + "The result starts with a Markdown image line (plus a separate 查看原图 link when displayMaxSize is set) that you MUST copy verbatim into your reply text, " + "If the output contains a line starting with [请转述给用户], relay that line to the user in your reply. " + "otherwise the user cannot see the picture. To iterate on a result, call image_edit with the returned path.",
527
679
  args: {
528
680
  prompt: z.string().describe("Detailed description of the image to generate"),
529
681
  filename: z.string().optional().describe("Optional output file name or path; defaults to a timestamped name")
@@ -531,14 +683,51 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
531
683
  execute: generate
532
684
  }),
533
685
  image_edit: tool({
534
- description: "Edit an existing image with a text instruction (image-to-image). Pass the exact path returned by a previous " + "image_generate or image_edit call to keep refining the same picture. " + "The result includes a Markdown image line that you MUST copy verbatim into your reply text, " + "otherwise the user cannot see the picture.",
686
+ description: "Edit an existing image with a text instruction (image-to-image). Pass the exact path returned by a previous " + "image_generate or image_edit call to keep refining the same picture. " + "The result starts with a Markdown image line (plus a separate 查看原图 link when displayMaxSize is set) that you MUST copy verbatim into your reply text, " + "If the output contains a line starting with [请转述给用户], relay that line to the user in your reply. " + "otherwise the user cannot see the picture.",
535
687
  args: {
536
688
  image: z.string().describe("Path to the source image, normally the file returned by image_generate/image_edit"),
537
689
  prompt: z.string().describe("What to change, e.g. 'make the hat red, keep everything else identical'"),
538
690
  filename: z.string().optional().describe("Optional output file name or path; defaults to a timestamped name")
539
691
  },
540
692
  execute: edit
693
+ }),
694
+ image_cache: tool({
695
+ description: "Inspect or clear the preview-thumbnail cache used for rendering images in the conversation. " + 'Use action="status" to report the cache directory, file count, total size and age of the oldest entry; ' + 'action="clean" to delete every cached preview (the generated images in outDir are NOT touched). ' + "This returns text only — do not turn it into a Markdown image line.",
696
+ args: {
697
+ action: z.enum(["status", "clean"]).describe("status = 查看缓存;clean = 清空缓存")
698
+ },
699
+ execute: async (args) => {
700
+ if (args.action === "clean") {
701
+ const removed = server.cleanCache();
702
+ return {
703
+ title: `已清理图片缓存(${removed.count} 个 / ${humanBytes(removed.bytes)})`,
704
+ output: [
705
+ `已清理 ${removed.count} 个预览文件,共 ${humanBytes(removed.bytes)}。`,
706
+ `缓存目录:${removed.dir}`,
707
+ `注意:这不影响 outDir 里的原图,会话里的图片仍能正常显示(需要时会重新生成缩略图)。`
708
+ ].join(`
709
+ `),
710
+ metadata: removed
711
+ };
712
+ }
713
+ const stats = server.cacheStats();
714
+ return {
715
+ title: `图片缓存:${stats.count} 个 / ${humanBytes(stats.bytes)}`,
716
+ output: [
717
+ `缓存目录:${stats.dir}`,
718
+ `文件数量:${stats.count}`,
719
+ `占用大小:${humanBytes(stats.bytes)}`,
720
+ `最旧一个:${stats.oldestMs === undefined ? "(空缓存)" : `已存在 ${humanAge(stats.oldestMs)}`}`,
721
+ `上限:${options.cacheLimit} 个(可通过 cacheLimit 配置,0 = 不限制)`
722
+ ].join(`
723
+ `),
724
+ metadata: stats
725
+ };
726
+ }
541
727
  })
728
+ },
729
+ dispose: async () => {
730
+ server.stop();
542
731
  }
543
732
  };
544
733
  };
package/dist/options.d.ts CHANGED
@@ -1,3 +1,12 @@
1
+ /** opencode 的数据目录(与 opencode.db 同级),图片默认落在这里而不是项目里 */
2
+ export declare function defaultImageDir(env?: NodeJS.ProcessEnv, home?: string): string;
3
+ /**
4
+ * 解析图片输出目录:
5
+ * - 未配置 → 全局数据目录,和项目/会话解耦
6
+ * - 相对路径 → 基于当前项目目录(例如 ".opencode-images" 就回到项目里)
7
+ * - 绝对路径 → 原样使用
8
+ */
9
+ export declare function resolveOutDir(directory: string, outDir?: string): string;
1
10
  /** 插件可配置项,通过 opencode 配置的 `plugin` 元组第二个元素传入 */
2
11
  export type PluginOptions = {
3
12
  /** OpenAI 兼容的图像接口地址,默认从 PI_IMAGE_BASE_URL 读取 */
@@ -6,11 +15,14 @@ export type PluginOptions = {
6
15
  apiKey?: string;
7
16
  /** 图像模型名 */
8
17
  model?: string;
9
- /** 图片输出目录;相对路径基于当前项目目录,默认 <project>/.opencode-images */
18
+ /**
19
+ * 图片输出目录。默认是全局数据目录(建议保持默认,跟项目/会话解耦);
20
+ * 填相对路径(如 ".opencode-images")会落在当前项目里。
21
+ */
10
22
  outDir?: string;
11
23
  /** 落盘图片的最长边上限(像素),超出会等比缩小 */
12
24
  maxSize?: number;
13
- /** 在对话里展示的图片最长边(像素);只影响展示,不影响落盘原图 */
25
+ /** 对话里展示时的最长边(像素)。0 = 不缩放,直接显示原图(默认,右键复制即原图) */
14
26
  displayMaxSize?: number;
15
27
  /** 本地图片服务端口;默认 0 = 由项目目录派生(同一项目恒定),需要避开占用时手动指定 */
16
28
  serverPort?: number;
@@ -18,13 +30,18 @@ export type PluginOptions = {
18
30
  serverIdleMs?: number;
19
31
  /** 首次出图时查一次 npm 最新版,落后则在工具输出末尾附升级提示。默认开启 */
20
32
  updateCheck?: boolean;
33
+ /** 对话里展示用的缩略图缓存目录,默认 <系统临时目录>/opencode-image */
34
+ cacheDir?: string;
35
+ /** 缩略图缓存最多保留多少个文件,超出按最久未访问淘汰;0 表示不限制 */
36
+ cacheLimit?: number;
21
37
  /** 单次图像请求超时(毫秒) */
22
38
  timeoutMs?: number;
23
39
  };
24
40
  export declare const DEFAULT_BASE_URL = "https://pi-ai.roiscloud.com/v1";
25
41
  export declare const DEFAULT_MODEL = "gpt-image-2";
26
42
  export declare const DEFAULT_MAX_SIZE = 1024;
27
- export declare const DEFAULT_DISPLAY_MAX_SIZE = 448;
43
+ /** 0 = 不缩放,直接把落盘的原图显示出来(右键复制/另存拿到的就是原图) */
44
+ export declare const DEFAULT_DISPLAY_MAX_SIZE = 0;
28
45
  /** 0 表示由项目目录派生端口,保证同一项目跨重启链接不变 */
29
46
  export declare const DEFAULT_SERVER_PORT = 0;
30
47
  export declare const DEFAULT_SERVER_IDLE_MS = 0;
@@ -39,6 +56,8 @@ export type ResolvedOptions = {
39
56
  serverPort: number;
40
57
  serverIdleMs: number;
41
58
  updateCheck: boolean;
59
+ cacheDir: string;
60
+ cacheLimit: number;
42
61
  timeoutMs: number;
43
62
  };
44
63
  /** 合并默认值、环境变量与用户配置;缺少 apiKey 时直接抛错 */
package/dist/server.d.ts CHANGED
@@ -1,6 +1,8 @@
1
+ import { PreviewCache } from "./cache.js";
1
2
  /**
2
- * 端口由项目目录派生:同一个项目永远是同一个端口,所以历史消息里的链接跨重启仍然有效;
3
- * 不同项目基本不会撞到同一个端口。需要覆盖时用 serverPort 配置项。
3
+ * 端口由「图片根目录」派生:同一个根目录永远同一个端口,所以历史消息里的链接跨重启仍然有效。
4
+ * 默认根目录是全局数据目录,因此全机通用一个端口、一个服务;
5
+ * 若把 outDir 指到项目里,则那个项目有自己稳定的端口。需要覆盖时用 serverPort 配置项。
4
6
  */
5
7
  export declare function derivePort(key: string): number;
6
8
  /**
@@ -19,6 +21,7 @@ export declare function derivePort(key: string): number;
19
21
  export declare class ImageServer {
20
22
  private readonly idleMs;
21
23
  private readonly configuredPort;
24
+ private readonly cache;
22
25
  private server?;
23
26
  private port;
24
27
  private root?;
@@ -26,17 +29,19 @@ export declare class ImageServer {
26
29
  private owned;
27
30
  /** outDir 之外的文件退回进程内随机 id(仅本次运行有效) */
28
31
  private extra;
29
- private previews;
30
32
  private timer?;
31
33
  private starting?;
32
- constructor(idleMs: number, configuredPort: number);
34
+ constructor(idleMs: number, configuredPort: number, cache: PreviewCache);
33
35
  get baseURL(): string;
34
36
  /** 生成稳定 id;outDir 内的文件跨重启一致 */
35
37
  idFor(file: string): string;
38
+ /**
39
+ * width > 0 时给出缩略图地址;width <= 0 时是原图地址(不带查询参数)。
40
+ * 末尾拼一段真实的文件名,纯粹为了让浏览器「另存为」时有个正常名字。
41
+ */
36
42
  url(file: string, width: number): string;
37
43
  /** 懒启动:首次需要时按派生端口监听;unref 后不阻塞宿主进程退出 */
38
44
  start(opts: {
39
- directory: string;
40
45
  outDir: string;
41
46
  }): Promise<void>;
42
47
  /**
@@ -44,6 +49,14 @@ export declare class ImageServer {
44
49
  * 默认不调用:历史消息里的图片会重新请求,提前关闭会 404。
45
50
  */
46
51
  stop(): void;
52
+ /** 缩略图缓存的统计 / 清理,透传给上层工具与展示通知 */
53
+ cacheStats(): import("./cache.js").CacheStats;
54
+ cleanCache(): {
55
+ dir: string;
56
+ count: number;
57
+ bytes: number;
58
+ };
59
+ consumeCacheNotice(): string | undefined;
47
60
  private listen;
48
61
  private servedByUs;
49
62
  private arm;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-image",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Image generation and editing tools for opencode, with inline rendering in the conversation.",
5
5
  "type": "module",
6
6
  "license": "MIT",