@cmach_socket/opencode-qq-bot 2.0.2 → 2.2.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 +1 -1
- package/package.json +20 -19
- package/src/cleanup.ts +2 -0
- package/src/config/initial.ts +20 -5
- package/src/config/live.ts +23 -2
- package/src/config/registry.ts +54 -0
- package/src/index.ts +178 -302
- package/src/instance.ts +181 -42
- package/src/naplink/client.ts +30 -3
- package/src/panel/api.ts +81 -0
- package/src/panel/documents.ts +17 -14
- package/src/panel/server.ts +4 -0
- package/src/panel/tools.ts +32 -0
- package/src/panel/user-md.ts +218 -0
- package/src/runtime/claim.ts +20 -3
- package/src/runtime/events.ts +74 -0
- package/src/runtime/local.ts +336 -0
- package/src/runtime/napcat-owner.ts +108 -0
- package/src/runtime/share.ts +105 -0
- package/src/safe-object.ts +5 -0
- package/src/session/manager.ts +243 -5
- package/src/user/store.ts +11 -1
- package/web/dist/assets/index-BkGFsghB.js +9 -0
- package/web/dist/assets/index-DxbYpvI7.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-C5lRsdbz.css +0 -1
- package/web/dist/assets/index-siSfDOnC.js +0 -8
package/src/instance.ts
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* 进程内注册表:按 location 分槽位,另有一条共享运行时的发布通道。
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* OpenCode 会为每个用到的目录各加载一次插件,同一个进程里因此会有多个实例。
|
|
5
|
+
* 工具与钩子按 location 隔离:目录里的会话只能用这一侧注册的工具,
|
|
6
|
+
* 所以每个实例都要在自己那一侧注册一份。
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
8
|
+
* NapCat 连接只能有一条:运行时(连接、会话管理器这些)由抢到机器级锁的
|
|
9
|
+
* 实例搭好,再通过注册表发布给同一进程里的其它实例复用。
|
|
10
|
+
*
|
|
11
|
+
* 槽位按 location 绑定:同一目录重载时新实例接管旧实例,
|
|
12
|
+
* 其它目录的实例互不干扰。注册表挂在 globalThis 上,模块重载后依然有效。
|
|
10
13
|
*
|
|
11
14
|
* 接管时旧实例把在途状态留在注册表里,新实例取走并继续,
|
|
12
15
|
* 免得正在跑的那一轮在上游白跑、回复丢掉。
|
|
13
16
|
*/
|
|
14
17
|
|
|
18
|
+
import { createNapCatOwner, type NapCatConnection, type NapCatOwner } from "./runtime/napcat-owner"
|
|
15
19
|
import type { HandoverState } from "./session/manager"
|
|
16
20
|
|
|
17
21
|
export interface PluginInstance {
|
|
@@ -25,7 +29,7 @@ export interface InstanceLease {
|
|
|
25
29
|
setDispose(dispose: () => Promise<void>): void
|
|
26
30
|
/** Clears the slot only when this lease still owns it. */
|
|
27
31
|
release(): void
|
|
28
|
-
/**
|
|
32
|
+
/** 本实例是否已经被同一 location 的新实例接管。 */
|
|
29
33
|
superseded(): boolean
|
|
30
34
|
/**
|
|
31
35
|
* 把在途状态留给接管本实例的新实例。
|
|
@@ -36,17 +40,40 @@ export interface InstanceLease {
|
|
|
36
40
|
}
|
|
37
41
|
|
|
38
42
|
export interface InstanceClaim {
|
|
39
|
-
/**
|
|
43
|
+
/** 同一 location 下被接管的旧实例。 */
|
|
40
44
|
previous?: PluginInstance
|
|
41
|
-
/** 槽位已被其它工作目录占用时给出该目录,调用方应停止运行。 */
|
|
42
|
-
occupied?: string
|
|
43
45
|
lease: InstanceLease
|
|
44
46
|
}
|
|
45
47
|
|
|
48
|
+
/** 共享运行时的发布通道。 */
|
|
49
|
+
export interface RuntimeChannel<T> {
|
|
50
|
+
/** 当前的共享运行时;还没有持有者时是 undefined。 */
|
|
51
|
+
current(): T | undefined
|
|
52
|
+
/** 发布共享运行时:换代时旧运行时被顶掉。 */
|
|
53
|
+
publish(runtime: T): void
|
|
54
|
+
/** 撤销自己发布的运行时;别人发布的不会被清掉。 */
|
|
55
|
+
clear(runtime: T): void
|
|
56
|
+
/** 订阅运行时变化:发布或撤销时回调;返回退订函数。 */
|
|
57
|
+
subscribe(listener: (runtime: T | undefined) => void): () => void
|
|
58
|
+
}
|
|
59
|
+
|
|
46
60
|
interface Host {
|
|
47
|
-
|
|
48
|
-
|
|
61
|
+
/** location → 该 location 当前占用的实例。 */
|
|
62
|
+
slots: Map<string, { instance: PluginInstance }>
|
|
63
|
+
/** 上一任持有者留下的在途状态,由下一任持有者取走。 */
|
|
49
64
|
handover?: HandoverState[]
|
|
65
|
+
/** location → 同一 location 被接管时留下的在途状态。 */
|
|
66
|
+
locationHandover?: Map<string, HandoverState[]>
|
|
67
|
+
/** 共享运行时:持有者发布,其它 location 的实例复用。 */
|
|
68
|
+
runtime?: unknown
|
|
69
|
+
/** 运行时变化的通知列表。 */
|
|
70
|
+
listeners: Set<(runtime: unknown) => void>
|
|
71
|
+
/** 机器级锁释放的通知列表。 */
|
|
72
|
+
lockListeners: Set<() => void>
|
|
73
|
+
/** NapCat 连接的属主:同一进程里唯一。 */
|
|
74
|
+
napcatOwner?: unknown
|
|
75
|
+
/** 同一进程里活着的实例。 */
|
|
76
|
+
instances: Set<object>
|
|
50
77
|
}
|
|
51
78
|
|
|
52
79
|
const HOST_KEY = "__opencodeQQBotHost__"
|
|
@@ -54,69 +81,181 @@ const HOST_KEY = "__opencodeQQBotHost__"
|
|
|
54
81
|
function host(): Host {
|
|
55
82
|
const global = globalThis as Record<string, unknown>
|
|
56
83
|
const existing = global[HOST_KEY]
|
|
57
|
-
if (existing && typeof existing === "object")
|
|
58
|
-
|
|
84
|
+
if (existing && typeof existing === "object") {
|
|
85
|
+
// 模块热重载后旧结构可能缺字段,补齐再用。
|
|
86
|
+
const state = existing as Partial<Host>
|
|
87
|
+
state.slots ??= new Map()
|
|
88
|
+
state.listeners ??= new Set()
|
|
89
|
+
state.lockListeners ??= new Set()
|
|
90
|
+
state.instances ??= new Set()
|
|
91
|
+
return state as Host
|
|
92
|
+
}
|
|
93
|
+
const created: Host = {
|
|
94
|
+
slots: new Map(),
|
|
95
|
+
listeners: new Set(),
|
|
96
|
+
lockListeners: new Set(),
|
|
97
|
+
instances: new Set(),
|
|
98
|
+
}
|
|
59
99
|
global[HOST_KEY] = created
|
|
60
100
|
return created
|
|
61
101
|
}
|
|
62
102
|
|
|
63
103
|
/**
|
|
64
|
-
*
|
|
104
|
+
* 取走上一任留下的在途状态。
|
|
65
105
|
*
|
|
66
106
|
* 取走即清空,避免陈旧的状态被后来的实例误当成自己的。
|
|
107
|
+
*
|
|
108
|
+
* 运行时交接的在途状态是全局的:下一任持有者可能在别的 location。
|
|
109
|
+
* 同一 location 被接管时留下的状态只归那个 location,不会被别人捡走。
|
|
110
|
+
*
|
|
111
|
+
* @param location 取走状态的实例所属的 location 目录。
|
|
67
112
|
*/
|
|
68
|
-
export function takeHandover(): HandoverState[] {
|
|
113
|
+
export function takeHandover(location: string): HandoverState[] {
|
|
69
114
|
const state = host()
|
|
70
115
|
const handover = state.handover ?? []
|
|
116
|
+
const scoped = state.locationHandover?.get(location) ?? []
|
|
71
117
|
state.handover = undefined
|
|
72
|
-
|
|
118
|
+
state.locationHandover?.delete(location)
|
|
119
|
+
return [...handover, ...scoped]
|
|
73
120
|
}
|
|
74
121
|
|
|
75
122
|
/**
|
|
76
|
-
*
|
|
123
|
+
* 把在途状态留给下一任持有者。
|
|
77
124
|
*
|
|
78
|
-
*
|
|
125
|
+
* 持有者所在的 location 被卸载时,运行时整体换人:在途的那一轮还在上游跑,
|
|
126
|
+
* 状态得留下来给新的持有者接手。
|
|
127
|
+
*/
|
|
128
|
+
export function publishHandover(states: readonly HandoverState[]): void {
|
|
129
|
+
if (states.length === 0) return
|
|
130
|
+
const state = host()
|
|
131
|
+
state.handover = [...(state.handover ?? []), ...states]
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 占用当前 location 的实例槽位。
|
|
136
|
+
*
|
|
137
|
+
* @param location 实例所属的 location 目录。
|
|
79
138
|
* @param label 实例来源描述,通常是项目目录与 NapCat 地址,仅用于日志。
|
|
80
139
|
*/
|
|
81
|
-
export function claimInstance(
|
|
140
|
+
export function claimInstance(location: string, label: string): InstanceClaim {
|
|
82
141
|
const state = host()
|
|
83
|
-
const
|
|
84
|
-
if (active && active.directory !== directory) {
|
|
85
|
-
return {
|
|
86
|
-
occupied: active.directory,
|
|
87
|
-
lease: {
|
|
88
|
-
setDispose() {},
|
|
89
|
-
release() {},
|
|
90
|
-
superseded() {
|
|
91
|
-
return false
|
|
92
|
-
},
|
|
93
|
-
handover() {},
|
|
94
|
-
},
|
|
95
|
-
}
|
|
96
|
-
}
|
|
142
|
+
const slot = state.slots.get(location)
|
|
97
143
|
const instance: PluginInstance = { label }
|
|
98
|
-
state.
|
|
144
|
+
state.slots.set(location, { instance })
|
|
99
145
|
return {
|
|
100
|
-
previous:
|
|
146
|
+
previous: slot?.instance,
|
|
101
147
|
lease: {
|
|
102
148
|
setDispose(dispose) {
|
|
103
149
|
instance.dispose = dispose
|
|
104
150
|
},
|
|
105
151
|
release() {
|
|
106
|
-
if (state.
|
|
152
|
+
if (state.slots.get(location)?.instance === instance) state.slots.delete(location)
|
|
107
153
|
},
|
|
108
154
|
superseded() {
|
|
109
|
-
const
|
|
110
|
-
return
|
|
155
|
+
const current = state.slots.get(location)?.instance
|
|
156
|
+
return current !== undefined && current !== instance
|
|
111
157
|
},
|
|
112
158
|
handover(states) {
|
|
113
159
|
// 已经有新实例接管时,这轮状态留给它;正常卸载没有接手方,留着也没用。
|
|
114
|
-
const
|
|
115
|
-
if (!
|
|
160
|
+
const current = state.slots.get(location)?.instance
|
|
161
|
+
if (!current || current === instance) return
|
|
116
162
|
// 空状态不用覆盖:前面可能有别的实例已经留下了要交接的东西。
|
|
117
163
|
if (states.length === 0) return
|
|
118
|
-
|
|
164
|
+
// 同一 location 的在途状态只归这个 location:别的 location 不捡。
|
|
165
|
+
const scoped = state.locationHandover ?? new Map<string, HandoverState[]>()
|
|
166
|
+
state.locationHandover = scoped
|
|
167
|
+
scoped.set(location, [...(scoped.get(location) ?? []), ...states])
|
|
119
168
|
},
|
|
120
169
|
},
|
|
121
170
|
}
|
|
122
171
|
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* 共享运行时的发布通道。
|
|
175
|
+
*
|
|
176
|
+
* 拿到机器级锁的实例发布运行时,同进程里的其它实例订阅它并复用。
|
|
177
|
+
*/
|
|
178
|
+
export function runtimeChannel<T>(): RuntimeChannel<T> {
|
|
179
|
+
const state = host()
|
|
180
|
+
return {
|
|
181
|
+
current: () => state.runtime as T | undefined,
|
|
182
|
+
publish(runtime: T) {
|
|
183
|
+
state.runtime = runtime
|
|
184
|
+
for (const listener of [...state.listeners]) listener(runtime)
|
|
185
|
+
},
|
|
186
|
+
clear(runtime: T) {
|
|
187
|
+
// 只清自己发布的那份:别的持有者已经换人时不能把它的运行时撤掉。
|
|
188
|
+
if (state.runtime !== runtime) return
|
|
189
|
+
state.runtime = undefined
|
|
190
|
+
for (const listener of [...state.listeners]) listener(undefined)
|
|
191
|
+
},
|
|
192
|
+
subscribe(listener: (runtime: T | undefined) => void) {
|
|
193
|
+
const wrapped = listener as (runtime: unknown) => void
|
|
194
|
+
state.listeners.add(wrapped)
|
|
195
|
+
return () => {
|
|
196
|
+
state.listeners.delete(wrapped)
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* 订阅「机器级锁可能空出来了」的通知。
|
|
204
|
+
*
|
|
205
|
+
* 机器级锁是跨进程的文件锁:抢不到的一方只能按自己的节奏重试(默认 30 秒一轮)。
|
|
206
|
+
* 同一进程里的实例之间可以直接通气——锁空出来时立刻通知,
|
|
207
|
+
* 接管延迟从「最长一个重试周期」降到毫秒级。
|
|
208
|
+
*
|
|
209
|
+
* 跨进程的实例收不到这个通知,仍按自己的重试周期来。
|
|
210
|
+
*/
|
|
211
|
+
export function onLockReleased(listener: () => void): () => void {
|
|
212
|
+
const state = host()
|
|
213
|
+
state.lockListeners.add(listener)
|
|
214
|
+
return () => {
|
|
215
|
+
state.lockListeners.delete(listener)
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** 通知同进程里的其它实例:机器级锁可能已经空出来了,可以立刻去抢。 */
|
|
220
|
+
export function notifyLockReleased(): void {
|
|
221
|
+
const state = host()
|
|
222
|
+
for (const listener of [...state.lockListeners]) listener()
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* 取进程内的 NapCat 连接属主。
|
|
227
|
+
*
|
|
228
|
+
* 属主跟着进程走,不跟着模块走:模块热重载后仍是同一个属主,
|
|
229
|
+
* 连接才不会因为重新加载插件而被丢掉。
|
|
230
|
+
*/
|
|
231
|
+
export function napcatOwner<T extends NapCatConnection>(): NapCatOwner<T> {
|
|
232
|
+
const state = host()
|
|
233
|
+
state.napcatOwner ??= createNapCatOwner()
|
|
234
|
+
return state.napcatOwner as NapCatOwner<T>
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* 登记一个活着的实例。
|
|
239
|
+
*
|
|
240
|
+
* 持锁者卸载时要先看进程里还有没有别的实例:有就把连接交出去,没有才关掉。
|
|
241
|
+
* 交接期间还要靠它判断运行时能不能撤——撤了所有 location 的工具就都没了。
|
|
242
|
+
*
|
|
243
|
+
* @param token 用来区分实例的凭据,一般用实例自己的对象。
|
|
244
|
+
* @returns 注销函数。
|
|
245
|
+
*/
|
|
246
|
+
export function registerInstance(token: object): () => void {
|
|
247
|
+
const state = host()
|
|
248
|
+
state.instances.add(token)
|
|
249
|
+
return () => {
|
|
250
|
+
state.instances.delete(token)
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 除自己之外,同一进程里还有没有别的实例。 */
|
|
255
|
+
export function hasOtherInstance(token: object): boolean {
|
|
256
|
+
const state = host()
|
|
257
|
+
for (const instance of state.instances) {
|
|
258
|
+
if (instance !== token) return true
|
|
259
|
+
}
|
|
260
|
+
return false
|
|
261
|
+
}
|
package/src/naplink/client.ts
CHANGED
|
@@ -12,6 +12,9 @@ import { redactUrl } from "../sensitive"
|
|
|
12
12
|
|
|
13
13
|
const MEDIA_SEGMENT_TYPES = ["image", "video", "record", "audio", "file"] as const
|
|
14
14
|
|
|
15
|
+
/** SDK 事件监听器的类型。 */
|
|
16
|
+
type NapCatListener = Parameters<NapLink["on"]>[1]
|
|
17
|
+
|
|
15
18
|
type MediaSegmentType = (typeof MEDIA_SEGMENT_TYPES)[number]
|
|
16
19
|
|
|
17
20
|
interface MediaSegmentData {
|
|
@@ -147,6 +150,8 @@ export class QQClient {
|
|
|
147
150
|
private reconnectCount = 0
|
|
148
151
|
/** 最后一次重连的时间(毫秒)。 */
|
|
149
152
|
private lastReconnect: number | undefined
|
|
153
|
+
/** 自己订阅的消息事件:连接交出去时要摘掉。 */
|
|
154
|
+
private readonly subscriptions: Array<{ event: string; handler: NapCatListener }> = []
|
|
150
155
|
|
|
151
156
|
constructor(
|
|
152
157
|
private readonly config: NapcatConfig,
|
|
@@ -281,17 +286,39 @@ export class QQClient {
|
|
|
281
286
|
|
|
282
287
|
/** 订阅群消息事件。 */
|
|
283
288
|
onGroupMessage(handler: (event: GroupMessageEvent) => void): void {
|
|
284
|
-
this.
|
|
289
|
+
this.subscribe("message.group.normal", handler)
|
|
285
290
|
}
|
|
286
291
|
|
|
287
292
|
/** 订阅私聊消息事件(好友、临时会话等)。 */
|
|
288
293
|
onPrivateMessage(handler: (event: PrivateMessageEvent) => void): void {
|
|
289
|
-
this.
|
|
294
|
+
this.subscribe("message.private", handler)
|
|
290
295
|
}
|
|
291
296
|
|
|
292
297
|
/** 订阅通知类事件(撤回、进退群、戳一戳等)。 */
|
|
293
298
|
onNotice(handler: (event: NoticeEvent) => void): void {
|
|
294
|
-
this.
|
|
299
|
+
this.subscribe("notice", handler)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* 摘掉自己订阅的消息事件。
|
|
304
|
+
*
|
|
305
|
+
* 连接交给下一任持有者时用:上一任的回调留着就会重复消费同一条消息。
|
|
306
|
+
* 只摘自己订阅的,SDK 自己的连接监听不动。
|
|
307
|
+
*/
|
|
308
|
+
clearSubscriptions(): void {
|
|
309
|
+
for (const { event, handler } of this.subscriptions.splice(0)) {
|
|
310
|
+
try {
|
|
311
|
+
this.link.off(event, handler)
|
|
312
|
+
} catch (error) {
|
|
313
|
+
this.logger.warn("摘除 NapCat 事件订阅失败", error)
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** 订阅消息事件并记下来,方便交接时摘掉。 */
|
|
319
|
+
private subscribe(event: string, handler: NapCatListener): void {
|
|
320
|
+
this.link.on(event, handler)
|
|
321
|
+
this.subscriptions.push({ event, handler })
|
|
295
322
|
}
|
|
296
323
|
|
|
297
324
|
/** 机器人自己的 QQ 号,未连接时返回 undefined。 */
|
package/src/panel/api.ts
CHANGED
|
@@ -6,6 +6,8 @@ import { getCookie, setCookie } from "hono/cookie"
|
|
|
6
6
|
import { csrf } from "hono/csrf"
|
|
7
7
|
import { secureHeaders } from "hono/secure-headers"
|
|
8
8
|
import { streamSSE } from "hono/streaming"
|
|
9
|
+
import { isTargetAllowed } from "../access"
|
|
10
|
+
import { parseTargetKey } from "../chat"
|
|
9
11
|
import type { ConfigController } from "../config/live"
|
|
10
12
|
import { CONFIG_FIELDS, CONFIG_GROUPS } from "../config/fields"
|
|
11
13
|
import {
|
|
@@ -25,6 +27,8 @@ import {
|
|
|
25
27
|
import type { ModelProvider } from "./models"
|
|
26
28
|
import { collectStatus } from "./status"
|
|
27
29
|
import type { PanelRuntime } from "./runtime"
|
|
30
|
+
import type { ToolNameProvider } from "./tools"
|
|
31
|
+
import { listUserMd, readUserMdText, saveUserMd, userMdFilename } from "./user-md"
|
|
28
32
|
|
|
29
33
|
/**
|
|
30
34
|
* 面板的 HTTP 接口。
|
|
@@ -46,6 +50,8 @@ export interface PanelAppOptions {
|
|
|
46
50
|
runtime: PanelRuntime
|
|
47
51
|
/** 可用模型列表。 */
|
|
48
52
|
models: ModelProvider
|
|
53
|
+
/** 可用工具名:工具档案的 allow/deny 从这里选。 */
|
|
54
|
+
tools: ToolNameProvider
|
|
49
55
|
/** 前端构建产物目录;没有就不托管静态资源。 */
|
|
50
56
|
staticDir?: string
|
|
51
57
|
/** 面板触发重启时调用;不传表示当前环境不支持重启。 */
|
|
@@ -250,6 +256,69 @@ export function createPanelApp(options: PanelAppOptions): Hono {
|
|
|
250
256
|
return c.json({ ok: true, ...result })
|
|
251
257
|
})
|
|
252
258
|
|
|
259
|
+
// 用户档案:每个聊天一份,面板里可上传。
|
|
260
|
+
app.get("/api/user-md", async (c) => {
|
|
261
|
+
return c.json(await listUserMd(runtime))
|
|
262
|
+
})
|
|
263
|
+
|
|
264
|
+
// 下载档案原文:面板里显示的是掩码过的正文,这里给的是原文件。
|
|
265
|
+
app.get("/api/user-md/file", async (c) => {
|
|
266
|
+
const chat = c.req.query("chat") ?? ""
|
|
267
|
+
const target = parseTargetKey(chat)
|
|
268
|
+
if (!target) {
|
|
269
|
+
return c.json(
|
|
270
|
+
{
|
|
271
|
+
error: "validation_failed",
|
|
272
|
+
message: "用户档案校验不通过",
|
|
273
|
+
fields: [{ path: "chat", message: "聊天键必须是 group:<群号> 或 private:<账号>" }],
|
|
274
|
+
},
|
|
275
|
+
400,
|
|
276
|
+
)
|
|
277
|
+
}
|
|
278
|
+
// 和上传一样只认已放行的聊天:写不进去的聊天也读不出来。
|
|
279
|
+
if (!isTargetAllowed(runtime.config.access, target, runtime.config.ownerQQ)) {
|
|
280
|
+
return c.json(
|
|
281
|
+
{ error: "forbidden", message: "这个聊天还没放行:先在准入名单里放行,再下载档案" },
|
|
282
|
+
403,
|
|
283
|
+
)
|
|
284
|
+
}
|
|
285
|
+
const text = await readUserMdText(runtime, target)
|
|
286
|
+
if (text === undefined) {
|
|
287
|
+
return c.json({ error: "not_found", message: "这个聊天还没有 USER.md" }, 404)
|
|
288
|
+
}
|
|
289
|
+
return c.body(text, 200, {
|
|
290
|
+
"Content-Type": "text/markdown; charset=utf-8",
|
|
291
|
+
"Content-Disposition": `attachment; filename="${userMdFilename(target)}"`,
|
|
292
|
+
})
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
// 上传用户档案:整份覆盖,只写已放行的聊天。
|
|
296
|
+
app.put("/api/user-md", async (c) => {
|
|
297
|
+
const contentType = c.req.header("Content-Type") ?? ""
|
|
298
|
+
if (!contentType.toLowerCase().includes("application/json")) {
|
|
299
|
+
return c.json({ error: "unsupported_media_type", message: "只接受 JSON 请求体" }, 415)
|
|
300
|
+
}
|
|
301
|
+
const body = await readJson(c.req.raw)
|
|
302
|
+
try {
|
|
303
|
+
const { problems, result } = await saveUserMd(runtime, body)
|
|
304
|
+
if (!result) {
|
|
305
|
+
return c.json(
|
|
306
|
+
{ error: "validation_failed", message: "用户档案校验不通过", fields: problems },
|
|
307
|
+
400,
|
|
308
|
+
)
|
|
309
|
+
}
|
|
310
|
+
return c.json({ ok: true, ...result })
|
|
311
|
+
} catch (error) {
|
|
312
|
+
return c.json(
|
|
313
|
+
{
|
|
314
|
+
error: "write_failed",
|
|
315
|
+
message: error instanceof Error ? error.message : String(error),
|
|
316
|
+
},
|
|
317
|
+
500,
|
|
318
|
+
)
|
|
319
|
+
}
|
|
320
|
+
})
|
|
321
|
+
|
|
253
322
|
// 可用模型列表。
|
|
254
323
|
app.get("/api/models", async (c) => {
|
|
255
324
|
try {
|
|
@@ -262,6 +331,18 @@ export function createPanelApp(options: PanelAppOptions): Hono {
|
|
|
262
331
|
}
|
|
263
332
|
})
|
|
264
333
|
|
|
334
|
+
// 可用工具名:工具档案里的 allow/deny 按这份清单给下拉选项。
|
|
335
|
+
app.get("/api/tools", async (c) => {
|
|
336
|
+
try {
|
|
337
|
+
return c.json({ tools: await options.tools.list() })
|
|
338
|
+
} catch (error) {
|
|
339
|
+
return c.json(
|
|
340
|
+
{ error: "tools_failed", message: error instanceof Error ? error.message : String(error) },
|
|
341
|
+
502,
|
|
342
|
+
)
|
|
343
|
+
}
|
|
344
|
+
})
|
|
345
|
+
|
|
265
346
|
// 运行状态快照。
|
|
266
347
|
app.get("/api/status", async (c) => {
|
|
267
348
|
return c.json(await collectStatus(runtime))
|
package/src/panel/documents.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { mkdir, readFile, stat } from "node:fs/promises"
|
|
2
2
|
import { basename, dirname, join } from "node:path"
|
|
3
|
-
import { allowedTargets } from "../access"
|
|
3
|
+
import { allowedTargets, isTargetAllowed } from "../access"
|
|
4
4
|
import { parseTargetKey, targetKey } from "../chat"
|
|
5
5
|
import { backupFile, DIR_MODE, writeJsonAtomic } from "../fs/atomic"
|
|
6
6
|
import { knownSecrets } from "../known-secrets"
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
type ChatOverrideParseOptions,
|
|
13
13
|
} from "../overrides"
|
|
14
14
|
import { maskKnownSecrets } from "../sensitive"
|
|
15
|
-
import { copyToSafeMap, hasKey, isSafeKey, safeMap } from "../safe-object"
|
|
15
|
+
import { copyToSafeMap, hasKey, isPlainObject, isSafeKey, safeMap } from "../safe-object"
|
|
16
16
|
import { acquireStateLock, type StateLock } from "../state-lock"
|
|
17
17
|
import { defaultToolPolicy, parseToolPolicy, resolveToolProfilesPath } from "../tools/policy"
|
|
18
18
|
import type { PanelRuntime } from "./runtime"
|
|
@@ -117,11 +117,6 @@ function isProfileName(name: string): boolean {
|
|
|
117
117
|
return isSafeKey(name) && PROFILE_NAME.test(name)
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
-
/** 判断是不是普通对象(数组与 null 都不算)。 */
|
|
121
|
-
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
122
|
-
return !!value && typeof value === "object" && !Array.isArray(value)
|
|
123
|
-
}
|
|
124
|
-
|
|
125
120
|
/**
|
|
126
121
|
* 掩码文档里的已知凭证。
|
|
127
122
|
*
|
|
@@ -351,8 +346,9 @@ export async function saveChatOverrides(
|
|
|
351
346
|
const chats = isPlainObject(patch) ? patch : {}
|
|
352
347
|
const warnings: string[] = []
|
|
353
348
|
// 配置档名字来自 config/tool-profiles.json:写进去的档位必须真的存在。
|
|
354
|
-
|
|
355
|
-
const
|
|
349
|
+
// 直接读文件,不依赖运行时:面板比运行时先监听,不能因为还没接好就拒绝写入。
|
|
350
|
+
const { raw: policyRaw } = await readJsonFile(toolProfilesPath(runtime))
|
|
351
|
+
const profileNames = Object.keys(parseToolPolicy(policyRaw, () => undefined).profiles)
|
|
356
352
|
for (const key of Object.keys(body)) {
|
|
357
353
|
if (!(CHAT_OVERRIDE_KEYS as readonly string[]).includes(key)) {
|
|
358
354
|
warnings.push(`未知字段 ${key},已忽略`)
|
|
@@ -361,7 +357,8 @@ export async function saveChatOverrides(
|
|
|
361
357
|
|
|
362
358
|
for (const [key, entry] of Object.entries(chats)) {
|
|
363
359
|
const field = `chats.${key}`
|
|
364
|
-
|
|
360
|
+
const target = parseTargetKey(key)
|
|
361
|
+
if (!target) {
|
|
365
362
|
problems.push({ path: field, message: "聊天键必须是 group:<群号> 或 private:<账号>" })
|
|
366
363
|
continue
|
|
367
364
|
}
|
|
@@ -373,6 +370,15 @@ export async function saveChatOverrides(
|
|
|
373
370
|
delete base[key]
|
|
374
371
|
continue
|
|
375
372
|
}
|
|
373
|
+
// 覆盖只对已放行的聊天有效:和档案上传一样,没放行的聊天先放行再配。
|
|
374
|
+
// 删掉旧条目不受这条限制:清理不需要放行。
|
|
375
|
+
if (!isTargetAllowed(runtime.config.access, target, runtime.config.ownerQQ)) {
|
|
376
|
+
problems.push({
|
|
377
|
+
path: field,
|
|
378
|
+
message: "这个聊天还没放行:先在准入名单里放行,再配置会话覆盖",
|
|
379
|
+
})
|
|
380
|
+
continue
|
|
381
|
+
}
|
|
376
382
|
if (!isPlainObject(entry)) {
|
|
377
383
|
problems.push({ path: field, message: "会话覆盖必须是对象" })
|
|
378
384
|
continue
|
|
@@ -440,10 +446,7 @@ export async function saveChatOverrides(
|
|
|
440
446
|
if (normalized.profile && !profileNames.includes(normalized.profile)) {
|
|
441
447
|
problems.push({
|
|
442
448
|
path: `${field}.profile`,
|
|
443
|
-
message:
|
|
444
|
-
profileNames.length > 0
|
|
445
|
-
? `配置档 ${normalized.profile} 不存在`
|
|
446
|
-
: `读不到工具配置,无法确认配置档 ${normalized.profile} 是否存在`,
|
|
449
|
+
message: `配置档 ${normalized.profile} 不存在`,
|
|
447
450
|
})
|
|
448
451
|
continue
|
|
449
452
|
}
|
package/src/panel/server.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { createPanelApp } from "./api"
|
|
|
8
8
|
import { PanelAuth } from "./auth"
|
|
9
9
|
import type { ModelProvider } from "./models"
|
|
10
10
|
import type { PanelRuntime } from "./runtime"
|
|
11
|
+
import type { ToolNameProvider } from "./tools"
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* 面板的 HTTP 服务。
|
|
@@ -23,6 +24,8 @@ export interface PanelServerOptions {
|
|
|
23
24
|
runtime: PanelRuntime
|
|
24
25
|
/** 可用模型列表。 */
|
|
25
26
|
models: ModelProvider
|
|
27
|
+
/** 可用工具名。 */
|
|
28
|
+
tools: ToolNameProvider
|
|
26
29
|
/** 日志器。 */
|
|
27
30
|
logger: Logger
|
|
28
31
|
/** 跨重启复用的面板鉴权;令牌变化时自动换成新的。 */
|
|
@@ -156,6 +159,7 @@ export class PanelServer {
|
|
|
156
159
|
controller: this.options.controller,
|
|
157
160
|
runtime: this.options.runtime,
|
|
158
161
|
models: this.options.models,
|
|
162
|
+
tools: this.options.tools,
|
|
159
163
|
...(existsSync(panelStaticDir()) ? { staticDir: panelStaticDir() } : {}),
|
|
160
164
|
...(this.options.onRestart ? { onRestart: this.options.onRestart } : {}),
|
|
161
165
|
...(this.options.restartDelayMs !== undefined
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 可用于工具档案的工具名。
|
|
3
|
+
*
|
|
4
|
+
* 清单来自 OpenCode 的工具注册表(内置工具、插件工具与 MCP 工具),
|
|
5
|
+
* 插件只是借 `ctx.tool` 转述;工具的增减要重载插件才会同步。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** 工具名列表的来源。 */
|
|
9
|
+
export interface ToolNameProvider {
|
|
10
|
+
/** 取当前可用的工具名。 */
|
|
11
|
+
list(): Promise<string[]>
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** OpenCode 的工具接口:只用 list 一个方法。 */
|
|
15
|
+
interface ToolApiLike {
|
|
16
|
+
list(): Promise<ReadonlyArray<{ id?: string }>>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 把 OpenCode 的工具接口包成面板要的形状。
|
|
21
|
+
*
|
|
22
|
+
* @param api `ctx.tool`。
|
|
23
|
+
*/
|
|
24
|
+
export function createToolNameProvider(api: ToolApiLike): ToolNameProvider {
|
|
25
|
+
return {
|
|
26
|
+
async list(): Promise<string[]> {
|
|
27
|
+
const tools = await api.list()
|
|
28
|
+
const names = tools.map((tool) => tool.id ?? "").filter((id) => id !== "")
|
|
29
|
+
return [...new Set(names)].sort()
|
|
30
|
+
},
|
|
31
|
+
}
|
|
32
|
+
}
|