opencode-image 0.1.1 → 0.1.3
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 +60 -4
- package/bin/cli.js +57 -7
- package/dist/cache.d.ts +44 -0
- package/dist/index.js +264 -69
- package/dist/options.d.ts +25 -3
- package/dist/server.d.ts +18 -5
- package/package.json +1 -1
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` |
|
|
34
|
+
| `outDir` | `<数据目录>/opencode-image` | 图片输出目录。默认全局,与项目/会话解耦;填相对路径(如 `.opencode-images`)则落到当前项目 |
|
|
35
35
|
| `maxSize` | `1024` | 落盘图片最长边上限,超出等比缩小 |
|
|
36
|
-
| `displayMaxSize` | `
|
|
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.
|
|
51
|
+
3. 工具输出给出 ``(`displayMaxSize = 0` 时就是原图)
|
|
50
52
|
4. 工具描述里强制模型把这行**原样抄进回复正文**
|
|
51
53
|
|
|
54
|
+
> **不支持「图片套链接」**:opencode 覆写了 marked 的 link renderer,取的是链接里的原始文本,
|
|
55
|
+
> `[](原图)` 里的图片不会被渲染。所以缩略图模式下改成两行:
|
|
56
|
+
> `` + `[查看原图](原图)`。
|
|
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
|
|
21
|
-
npx ${PACKAGE} --
|
|
22
|
-
npx ${PACKAGE} --
|
|
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
|
|
31
|
-
return process.env.
|
|
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 =
|
|
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
|
-
|
|
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)
|
package/dist/cache.d.ts
ADDED
|
@@ -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
|
|
4
|
-
import * as
|
|
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/
|
|
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
|
-
|
|
246
|
+
fs2.mkdirSync(path2.dirname(destination), { recursive: true });
|
|
119
247
|
const staging = `${destination}.${process.pid}-${Date.now()}.download`;
|
|
120
|
-
|
|
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
|
-
|
|
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 =
|
|
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,15 @@ 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
|
+
injectPrompt: opts.injectPrompt ?? true,
|
|
299
|
+
cacheDir: opts.cacheDir ?? DEFAULT_CACHE_DIR,
|
|
300
|
+
cacheLimit: opts.cacheLimit ?? DEFAULT_CACHE_LIMIT,
|
|
159
301
|
timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
160
302
|
};
|
|
161
303
|
}
|
|
162
304
|
|
|
163
305
|
// src/update.ts
|
|
164
|
-
import * as
|
|
306
|
+
import * as fs3 from "node:fs";
|
|
165
307
|
var REGISTRY = "https://registry.npmjs.org";
|
|
166
308
|
var PACKAGE = "opencode-image";
|
|
167
309
|
function parse(version) {
|
|
@@ -187,14 +329,14 @@ function isNewer(candidate, current) {
|
|
|
187
329
|
function readOwnVersion() {
|
|
188
330
|
try {
|
|
189
331
|
const file = new URL("../package.json", import.meta.url);
|
|
190
|
-
const pkg = JSON.parse(
|
|
332
|
+
const pkg = JSON.parse(fs3.readFileSync(file, "utf8"));
|
|
191
333
|
return pkg.version;
|
|
192
334
|
} catch {
|
|
193
335
|
return;
|
|
194
336
|
}
|
|
195
337
|
}
|
|
196
338
|
function upgradeHint(latest, current) {
|
|
197
|
-
return
|
|
339
|
+
return `[请转述给用户] ${PACKAGE} 有新版本 ${latest}(当前 ${current})。升级:npx ${PACKAGE} --update 然后重启 opencode。`;
|
|
198
340
|
}
|
|
199
341
|
async function checkForUpdate(current, timeoutMs = 3000) {
|
|
200
342
|
const controller = new AbortController;
|
|
@@ -218,11 +360,11 @@ async function checkForUpdate(current, timeoutMs = 3000) {
|
|
|
218
360
|
}
|
|
219
361
|
|
|
220
362
|
// src/server.ts
|
|
221
|
-
import * as
|
|
363
|
+
import * as fs4 from "node:fs";
|
|
222
364
|
import * as http from "node:http";
|
|
223
|
-
import * as
|
|
224
|
-
import * as
|
|
225
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
365
|
+
import * as os3 from "node:os";
|
|
366
|
+
import * as path4 from "node:path";
|
|
367
|
+
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
226
368
|
var MIME_BY_EXT = {
|
|
227
369
|
".png": "image/png",
|
|
228
370
|
".jpg": "image/jpeg",
|
|
@@ -230,28 +372,29 @@ var MIME_BY_EXT = {
|
|
|
230
372
|
".webp": "image/webp",
|
|
231
373
|
".gif": "image/gif"
|
|
232
374
|
};
|
|
233
|
-
var ID_PATTERN = /^\/img\/([A-Za-z0-9_-]{1,2048})
|
|
375
|
+
var ID_PATTERN = /^\/img\/([A-Za-z0-9_-]{1,2048})(?:\/[^/]*)?$/;
|
|
234
376
|
var APP_NAME = "opencode-image";
|
|
235
377
|
function derivePort(key) {
|
|
236
|
-
const digest =
|
|
378
|
+
const digest = createHash2("sha1").update(key).digest();
|
|
237
379
|
return 41000 + digest.readUInt16BE(0) % 4000;
|
|
238
380
|
}
|
|
239
381
|
|
|
240
382
|
class ImageServer {
|
|
241
383
|
idleMs;
|
|
242
384
|
configuredPort;
|
|
385
|
+
cache;
|
|
243
386
|
server;
|
|
244
387
|
port = 0;
|
|
245
388
|
root;
|
|
246
389
|
ready = false;
|
|
247
390
|
owned = false;
|
|
248
391
|
extra = new Map;
|
|
249
|
-
previews = new Map;
|
|
250
392
|
timer;
|
|
251
393
|
starting;
|
|
252
|
-
constructor(idleMs, configuredPort) {
|
|
394
|
+
constructor(idleMs, configuredPort, cache) {
|
|
253
395
|
this.idleMs = idleMs;
|
|
254
396
|
this.configuredPort = configuredPort;
|
|
397
|
+
this.cache = cache;
|
|
255
398
|
}
|
|
256
399
|
get baseURL() {
|
|
257
400
|
return this.port ? `http://127.0.0.1:${this.port}` : "";
|
|
@@ -259,9 +402,9 @@ class ImageServer {
|
|
|
259
402
|
idFor(file) {
|
|
260
403
|
const root = this.root;
|
|
261
404
|
if (root) {
|
|
262
|
-
const relative2 =
|
|
263
|
-
if (relative2 && !relative2.startsWith("..") && !
|
|
264
|
-
return Buffer.from(relative2.split(
|
|
405
|
+
const relative2 = path4.relative(root, file);
|
|
406
|
+
if (relative2 && !relative2.startsWith("..") && !path4.isAbsolute(relative2)) {
|
|
407
|
+
return Buffer.from(relative2.split(path4.sep).join("/"), "utf8").toString("base64url");
|
|
265
408
|
}
|
|
266
409
|
}
|
|
267
410
|
for (const [id2, registered] of this.extra) {
|
|
@@ -273,10 +416,12 @@ class ImageServer {
|
|
|
273
416
|
return id;
|
|
274
417
|
}
|
|
275
418
|
url(file, width) {
|
|
276
|
-
|
|
419
|
+
const query = width > 0 ? `?w=${Math.round(width)}` : "";
|
|
420
|
+
const name = encodeURIComponent(path4.basename(file));
|
|
421
|
+
return `${this.baseURL}/img/${this.idFor(file)}/${name}${query}`;
|
|
277
422
|
}
|
|
278
423
|
async start(opts) {
|
|
279
|
-
this.root =
|
|
424
|
+
this.root = path4.resolve(opts.outDir);
|
|
280
425
|
if (this.ready) {
|
|
281
426
|
this.arm();
|
|
282
427
|
return;
|
|
@@ -302,17 +447,23 @@ class ImageServer {
|
|
|
302
447
|
this.owned = false;
|
|
303
448
|
this.ready = false;
|
|
304
449
|
this.port = 0;
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
this.
|
|
450
|
+
}
|
|
451
|
+
cacheStats() {
|
|
452
|
+
return this.cache.stats();
|
|
453
|
+
}
|
|
454
|
+
cleanCache() {
|
|
455
|
+
return this.cache.clean();
|
|
456
|
+
}
|
|
457
|
+
consumeCacheNotice() {
|
|
458
|
+
return this.cache.consumeNotice();
|
|
308
459
|
}
|
|
309
460
|
async listen(opts) {
|
|
310
|
-
const port = this.configuredPort || derivePort(opts.
|
|
461
|
+
const port = this.configuredPort || derivePort(path4.resolve(opts.outDir));
|
|
311
462
|
const server = http.createServer((req, res) => void this.handle(req, res));
|
|
312
463
|
server.unref();
|
|
313
|
-
const failure = await new Promise((
|
|
314
|
-
server.once("error",
|
|
315
|
-
server.listen(port, "127.0.0.1", () =>
|
|
464
|
+
const failure = await new Promise((resolve3) => {
|
|
465
|
+
server.once("error", resolve3);
|
|
466
|
+
server.listen(port, "127.0.0.1", () => resolve3(undefined));
|
|
316
467
|
});
|
|
317
468
|
if (!failure) {
|
|
318
469
|
this.server = server;
|
|
@@ -334,7 +485,7 @@ class ImageServer {
|
|
|
334
485
|
if (!res.ok)
|
|
335
486
|
return false;
|
|
336
487
|
const body = await res.json();
|
|
337
|
-
return body.app === APP_NAME && body.root ===
|
|
488
|
+
return body.app === APP_NAME && body.root === path4.resolve(outDir);
|
|
338
489
|
} catch {
|
|
339
490
|
return false;
|
|
340
491
|
}
|
|
@@ -347,22 +498,20 @@ class ImageServer {
|
|
|
347
498
|
this.timer = setTimeout(() => this.stop(), this.idleMs);
|
|
348
499
|
this.timer.unref();
|
|
349
500
|
}
|
|
350
|
-
preview(source, max) {
|
|
351
|
-
const
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
const
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
return file;
|
|
360
|
-
});
|
|
501
|
+
async preview(source, max) {
|
|
502
|
+
const hit = this.cache.hit(source, max);
|
|
503
|
+
if (hit)
|
|
504
|
+
return hit;
|
|
505
|
+
const staging = path4.join(os3.tmpdir(), `opencode-image-${process.pid}-${randomUUID()}.png`);
|
|
506
|
+
const rendered = await renderPreview(source, staging, max);
|
|
507
|
+
if (rendered === source)
|
|
508
|
+
return source;
|
|
509
|
+
return this.cache.put(source, max, rendered);
|
|
361
510
|
}
|
|
362
511
|
resolve(id) {
|
|
363
512
|
const registered = this.extra.get(id);
|
|
364
513
|
if (registered)
|
|
365
|
-
return
|
|
514
|
+
return fs4.existsSync(registered) ? registered : undefined;
|
|
366
515
|
const root = this.root;
|
|
367
516
|
if (!root)
|
|
368
517
|
return;
|
|
@@ -372,17 +521,17 @@ class ImageServer {
|
|
|
372
521
|
} catch {
|
|
373
522
|
return;
|
|
374
523
|
}
|
|
375
|
-
if (!relative2 || relative2.includes("\x00") ||
|
|
524
|
+
if (!relative2 || relative2.includes("\x00") || path4.isAbsolute(relative2))
|
|
376
525
|
return;
|
|
377
|
-
const target =
|
|
378
|
-
if (target === root || !target.startsWith(root +
|
|
526
|
+
const target = path4.resolve(root, relative2);
|
|
527
|
+
if (target === root || !target.startsWith(root + path4.sep))
|
|
379
528
|
return;
|
|
380
529
|
try {
|
|
381
|
-
if (!
|
|
530
|
+
if (!fs4.statSync(target).isFile())
|
|
382
531
|
return;
|
|
383
|
-
const real =
|
|
384
|
-
const realRoot =
|
|
385
|
-
if (real !== realRoot && !real.startsWith(realRoot +
|
|
532
|
+
const real = fs4.realpathSync(target);
|
|
533
|
+
const realRoot = fs4.realpathSync(root);
|
|
534
|
+
if (real !== realRoot && !real.startsWith(realRoot + path4.sep))
|
|
386
535
|
return;
|
|
387
536
|
} catch {
|
|
388
537
|
return;
|
|
@@ -410,9 +559,9 @@ class ImageServer {
|
|
|
410
559
|
async send(file, width, res) {
|
|
411
560
|
try {
|
|
412
561
|
const target = width > 0 ? await this.preview(file, Math.round(width)) : file;
|
|
413
|
-
const body =
|
|
562
|
+
const body = fs4.readFileSync(target);
|
|
414
563
|
res.writeHead(200, {
|
|
415
|
-
"content-type": MIME_BY_EXT[
|
|
564
|
+
"content-type": MIME_BY_EXT[path4.extname(target).toLowerCase()] ?? "application/octet-stream",
|
|
416
565
|
"content-length": body.length,
|
|
417
566
|
"cache-control": "private, max-age=86400"
|
|
418
567
|
});
|
|
@@ -426,34 +575,30 @@ class ImageServer {
|
|
|
426
575
|
|
|
427
576
|
// src/index.ts
|
|
428
577
|
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
578
|
function resolveDestination(filename, outDir, ctx) {
|
|
435
579
|
const dir = resolveOutDir(ctx.directory, outDir);
|
|
436
580
|
if (filename) {
|
|
437
|
-
const target =
|
|
581
|
+
const target = path5.isAbsolute(filename) ? filename : path5.join(dir, filename);
|
|
438
582
|
return `${target.replace(/\.[A-Za-z0-9]+$/, "")}.png`;
|
|
439
583
|
}
|
|
440
584
|
const stamp = new Date().toISOString().replace(/\..+$/, "").replace(/[:T]/g, "-");
|
|
441
585
|
const suffix = Math.random().toString(36).slice(2, 6);
|
|
442
|
-
return
|
|
586
|
+
return path5.join(dir, `image-${stamp}-${suffix}.png`);
|
|
443
587
|
}
|
|
444
588
|
function asAttachment(file) {
|
|
445
589
|
return [
|
|
446
590
|
{
|
|
447
591
|
type: "file",
|
|
448
592
|
mime: "image/png",
|
|
449
|
-
filename:
|
|
450
|
-
url: `data:image/png;base64,${
|
|
593
|
+
filename: path5.basename(file),
|
|
594
|
+
url: `data:image/png;base64,${fs5.readFileSync(file).toString("base64")}`
|
|
451
595
|
}
|
|
452
596
|
];
|
|
453
597
|
}
|
|
454
598
|
var OpenCodeImagePlugin = async (_input, rawOptions) => {
|
|
455
599
|
const options = resolveOptions(rawOptions);
|
|
456
|
-
const
|
|
600
|
+
const cache = new PreviewCache(options.cacheDir, options.cacheLimit);
|
|
601
|
+
const server = new ImageServer(options.serverIdleMs, options.serverPort, cache);
|
|
457
602
|
const selfVersion = readOwnVersion();
|
|
458
603
|
let updateHint;
|
|
459
604
|
let updateChecked = false;
|
|
@@ -468,8 +613,13 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
|
|
|
468
613
|
const { width, height } = await imageDimensions(file);
|
|
469
614
|
let display;
|
|
470
615
|
try {
|
|
471
|
-
await server.start({
|
|
472
|
-
|
|
616
|
+
await server.start({ outDir: resolveOutDir(ctx.directory, options.outDir) });
|
|
617
|
+
const alt = prompt.slice(0, 60);
|
|
618
|
+
const lines = [`})`];
|
|
619
|
+
if (options.displayMaxSize > 0)
|
|
620
|
+
lines.push(`[查看原图](${server.url(file, 0)})`);
|
|
621
|
+
display = lines.join(`
|
|
622
|
+
`);
|
|
473
623
|
} catch (error) {
|
|
474
624
|
display = `[opencode-image: local image server unavailable, cannot render inline: ${String(error)}]`;
|
|
475
625
|
}
|
|
@@ -482,6 +632,9 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
|
|
|
482
632
|
];
|
|
483
633
|
if (notice)
|
|
484
634
|
output.push(notice);
|
|
635
|
+
const cacheNotice = server.consumeCacheNotice();
|
|
636
|
+
if (cacheNotice)
|
|
637
|
+
output.push(cacheNotice);
|
|
485
638
|
return {
|
|
486
639
|
title: `${label}: ${prompt.slice(0, 60)}`,
|
|
487
640
|
output: output.join(`
|
|
@@ -504,14 +657,14 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
|
|
|
504
657
|
}
|
|
505
658
|
};
|
|
506
659
|
const edit = async (args, ctx) => {
|
|
507
|
-
const source =
|
|
508
|
-
if (!
|
|
660
|
+
const source = path5.isAbsolute(args.image) ? args.image : path5.resolve(ctx.directory, args.image);
|
|
661
|
+
if (!fs5.existsSync(source))
|
|
509
662
|
throw new Error(`image_edit: source image not found: ${source}`);
|
|
510
663
|
ctx.metadata({ title: `Editing image: ${args.prompt.slice(0, 60)}` });
|
|
511
664
|
const { signal, clear } = withTimeout(ctx.abort, options.timeoutMs);
|
|
512
665
|
try {
|
|
513
666
|
const upload = await toPngBuffer(source, options.maxSize);
|
|
514
|
-
const remote = await editImage(options, upload, `${
|
|
667
|
+
const remote = await editImage(options, upload, `${path5.basename(source, path5.extname(source))}.png`, args.prompt, signal);
|
|
515
668
|
const raw = await fetchImageBytes(remote, signal);
|
|
516
669
|
const destination = resolveDestination(args.filename, options.outDir, ctx);
|
|
517
670
|
await persistImage(raw, destination, options.maxSize);
|
|
@@ -523,7 +676,7 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
|
|
|
523
676
|
return {
|
|
524
677
|
tool: {
|
|
525
678
|
image_generate: tool({
|
|
526
|
-
description: "Generate
|
|
679
|
+
description: "Generate an image from a text prompt. This is the only supported way to create images in this session: " + "the endpoint and API key are already configured inside this plugin, so NEVER call the image API yourself " + "(no curl, no scripts) and never read the API key out of opencode.json. " + "The first line of the output is a Markdown image line (plus a separate 查看原图 link when displayMaxSize > 0); " + "you MUST copy those lines verbatim into your reply text, otherwise the user cannot see the picture. " + "If the output contains a line starting with [请转述给用户], relay that line to the user as well. " + "To refine a result, call image_edit with the returned path instead of generating a new image.",
|
|
527
680
|
args: {
|
|
528
681
|
prompt: z.string().describe("Detailed description of the image to generate"),
|
|
529
682
|
filename: z.string().optional().describe("Optional output file name or path; defaults to a timestamped name")
|
|
@@ -531,14 +684,56 @@ var OpenCodeImagePlugin = async (_input, rawOptions) => {
|
|
|
531
684
|
execute: generate
|
|
532
685
|
}),
|
|
533
686
|
image_edit: tool({
|
|
534
|
-
description: "Edit an existing image with a text instruction (image-to-image).
|
|
687
|
+
description: "Edit an existing image with a text instruction (image-to-image). Prefer this over generating a new image " + "when the user wants to adjust a picture: pass the exact path returned by a previous image_generate or " + "image_edit call to keep refining the same one. " + "Same rules: never call the image API yourself and never read the API key; copy the Markdown image line " + "(and the 查看原图 link, if present) from the output verbatim into your reply, and relay any line starting " + "with [请转述给用户].",
|
|
535
688
|
args: {
|
|
536
689
|
image: z.string().describe("Path to the source image, normally the file returned by image_generate/image_edit"),
|
|
537
690
|
prompt: z.string().describe("What to change, e.g. 'make the hat red, keep everything else identical'"),
|
|
538
691
|
filename: z.string().optional().describe("Optional output file name or path; defaults to a timestamped name")
|
|
539
692
|
},
|
|
540
693
|
execute: edit
|
|
694
|
+
}),
|
|
695
|
+
image_cache: tool({
|
|
696
|
+
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.",
|
|
697
|
+
args: {
|
|
698
|
+
action: z.enum(["status", "clean"]).describe("status = 查看缓存;clean = 清空缓存")
|
|
699
|
+
},
|
|
700
|
+
execute: async (args) => {
|
|
701
|
+
if (args.action === "clean") {
|
|
702
|
+
const removed = server.cleanCache();
|
|
703
|
+
return {
|
|
704
|
+
title: `已清理图片缓存(${removed.count} 个 / ${humanBytes(removed.bytes)})`,
|
|
705
|
+
output: [
|
|
706
|
+
`已清理 ${removed.count} 个预览文件,共 ${humanBytes(removed.bytes)}。`,
|
|
707
|
+
`缓存目录:${removed.dir}`,
|
|
708
|
+
`注意:这不影响 outDir 里的原图,会话里的图片仍能正常显示(需要时会重新生成缩略图)。`
|
|
709
|
+
].join(`
|
|
710
|
+
`),
|
|
711
|
+
metadata: removed
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
const stats = server.cacheStats();
|
|
715
|
+
return {
|
|
716
|
+
title: `图片缓存:${stats.count} 个 / ${humanBytes(stats.bytes)}`,
|
|
717
|
+
output: [
|
|
718
|
+
`缓存目录:${stats.dir}`,
|
|
719
|
+
`文件数量:${stats.count}`,
|
|
720
|
+
`占用大小:${humanBytes(stats.bytes)}`,
|
|
721
|
+
`最旧一个:${stats.oldestMs === undefined ? "(空缓存)" : `已存在 ${humanAge(stats.oldestMs)}`}`,
|
|
722
|
+
`上限:${options.cacheLimit} 个(可通过 cacheLimit 配置,0 = 不限制)`
|
|
723
|
+
].join(`
|
|
724
|
+
`),
|
|
725
|
+
metadata: stats
|
|
726
|
+
};
|
|
727
|
+
}
|
|
541
728
|
})
|
|
729
|
+
},
|
|
730
|
+
"experimental.chat.system.transform": async (_input2, output) => {
|
|
731
|
+
if (!options.injectPrompt)
|
|
732
|
+
return;
|
|
733
|
+
output.system.push("Image generation/editing: always use the `image_generate` / `image_edit` tools provided by the " + "opencode-image plugin — the endpoint and API key are already configured there. Never call the image API " + "directly, never read the API key from config, and do not use the imagegen skill or its CLI. Copy the " + "Markdown image line from that tool's output verbatim into your reply so the user can see the picture.");
|
|
734
|
+
},
|
|
735
|
+
dispose: async () => {
|
|
736
|
+
server.stop();
|
|
542
737
|
}
|
|
543
738
|
};
|
|
544
739
|
};
|
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
|
-
/**
|
|
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,20 @@ export type PluginOptions = {
|
|
|
18
30
|
serverIdleMs?: number;
|
|
19
31
|
/** 首次出图时查一次 npm 最新版,落后则在工具输出末尾附升级提示。默认开启 */
|
|
20
32
|
updateCheck?: boolean;
|
|
33
|
+
/** 往系统提示里注入一条"用哪个工具生图"的规则。默认开启 */
|
|
34
|
+
injectPrompt?: boolean;
|
|
35
|
+
/** 对话里展示用的缩略图缓存目录,默认 <系统临时目录>/opencode-image */
|
|
36
|
+
cacheDir?: string;
|
|
37
|
+
/** 缩略图缓存最多保留多少个文件,超出按最久未访问淘汰;0 表示不限制 */
|
|
38
|
+
cacheLimit?: number;
|
|
21
39
|
/** 单次图像请求超时(毫秒) */
|
|
22
40
|
timeoutMs?: number;
|
|
23
41
|
};
|
|
24
42
|
export declare const DEFAULT_BASE_URL = "https://pi-ai.roiscloud.com/v1";
|
|
25
43
|
export declare const DEFAULT_MODEL = "gpt-image-2";
|
|
26
44
|
export declare const DEFAULT_MAX_SIZE = 1024;
|
|
27
|
-
|
|
45
|
+
/** 0 = 不缩放,直接把落盘的原图显示出来(右键复制/另存拿到的就是原图) */
|
|
46
|
+
export declare const DEFAULT_DISPLAY_MAX_SIZE = 0;
|
|
28
47
|
/** 0 表示由项目目录派生端口,保证同一项目跨重启链接不变 */
|
|
29
48
|
export declare const DEFAULT_SERVER_PORT = 0;
|
|
30
49
|
export declare const DEFAULT_SERVER_IDLE_MS = 0;
|
|
@@ -39,6 +58,9 @@ export type ResolvedOptions = {
|
|
|
39
58
|
serverPort: number;
|
|
40
59
|
serverIdleMs: number;
|
|
41
60
|
updateCheck: boolean;
|
|
61
|
+
injectPrompt: boolean;
|
|
62
|
+
cacheDir: string;
|
|
63
|
+
cacheLimit: number;
|
|
42
64
|
timeoutMs: number;
|
|
43
65
|
};
|
|
44
66
|
/** 合并默认值、环境变量与用户配置;缺少 apiKey 时直接抛错 */
|
package/dist/server.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { PreviewCache } from "./cache.js";
|
|
1
2
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
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;
|