@mindbase/opencode-core 0.0.0-stage → 0.1.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/package.json +12 -4
- package/src/attachmentTypes.ts +65 -0
- package/src/btw.ts +76 -0
- package/src/device-host.ts +387 -0
- package/src/index.ts +6 -0
- package/src/modelFallback.ts +184 -0
- package/src/modelVisibility.ts +35 -0
- package/src/projection.ts +1217 -0
- package/src/protocol.ts +534 -0
- package/src/replica-conversation.ts +714 -0
- package/src/toolFiles.ts +100 -0
- package/src/translator.ts +89 -0
- package/src/uiText.ts +61 -0
- package/src/worktrees.ts +143 -0
- package/tsconfig.json +12 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mindbase/opencode-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "OpenCode 会话投影与协议归一化共享核心(Gateway 与 VS Code 扩展共用)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.ts",
|
|
7
|
+
"types": "./src/index.ts",
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"@opencode/client": "2.4.2"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** OpenCode prompt attachment metadata. Bytes stay in a data/file/media URI. */
|
|
2
|
+
export interface ImageAttachment {
|
|
3
|
+
uri: string;
|
|
4
|
+
fileName: string;
|
|
5
|
+
mime: string;
|
|
6
|
+
bytes: number;
|
|
7
|
+
}
|
|
8
|
+
export interface DraftImage {
|
|
9
|
+
id: string;
|
|
10
|
+
sessionId: string;
|
|
11
|
+
fileName: string;
|
|
12
|
+
mime: string;
|
|
13
|
+
bytes: number;
|
|
14
|
+
status: "uploading" | "ready" | "error";
|
|
15
|
+
uri?: string;
|
|
16
|
+
thumbnail?: string;
|
|
17
|
+
}
|
|
18
|
+
export const IMAGE_MAX_BYTES = 20 * 1024 * 1024;
|
|
19
|
+
export const IMAGE_MAX_COUNT = 8;
|
|
20
|
+
export const IMAGE_MIMES = ["image/png", "image/jpeg", "image/webp", "image/gif"] as const;
|
|
21
|
+
|
|
22
|
+
function validUri(value: unknown): value is string {
|
|
23
|
+
if (typeof value !== "string" || !value || value.includes("\0")) return false;
|
|
24
|
+
if (/^data:image\/(?:png|jpeg|webp|gif);base64,/i.test(value)) return value.length <= Math.ceil(IMAGE_MAX_BYTES / 3) * 4 + 128;
|
|
25
|
+
if (/^file:/i.test(value)) return value.length <= 4096;
|
|
26
|
+
return /^media:[A-Za-z0-9_-]{1,256}$/.test(value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function readImageAttachments(raw: unknown): ImageAttachment[] {
|
|
30
|
+
if (!Array.isArray(raw)) return [];
|
|
31
|
+
return raw.slice(0, IMAGE_MAX_COUNT).filter((item): item is ImageAttachment =>
|
|
32
|
+
!!item && typeof item === "object" && validUri((item as { uri?: unknown }).uri) &&
|
|
33
|
+
typeof (item as { fileName?: unknown }).fileName === "string" && (item as { fileName: string }).fileName.length <= 255 &&
|
|
34
|
+
IMAGE_MIMES.includes((item as { mime?: unknown }).mime as typeof IMAGE_MIMES[number]) &&
|
|
35
|
+
Number.isSafeInteger((item as { bytes?: unknown }).bytes) && (item as { bytes: number }).bytes > 0 && (item as { bytes: number }).bytes <= IMAGE_MAX_BYTES
|
|
36
|
+
).map(({uri, fileName, mime, bytes}) => ({uri, fileName, mime, bytes}));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Full data URLs are transient; persisted drafts retain only file/media URIs. */
|
|
40
|
+
export function persistDraftImage(image: DraftImage): DraftImage {
|
|
41
|
+
if (image.uri?.startsWith("data:")) {
|
|
42
|
+
const { uri: _uri, ...rest } = image;
|
|
43
|
+
return { ...rest, status: "error" };
|
|
44
|
+
}
|
|
45
|
+
return { ...image };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function draftImages(raw: unknown): DraftImage[] {
|
|
49
|
+
if (!Array.isArray(raw)) return [];
|
|
50
|
+
return raw.slice(0, IMAGE_MAX_COUNT * 2).filter(item => !!item && typeof item === "object" &&
|
|
51
|
+
typeof (item as { id?: unknown }).id === "string" && typeof (item as { sessionId?: unknown }).sessionId === "string" &&
|
|
52
|
+
typeof (item as { fileName?: unknown }).fileName === "string" &&
|
|
53
|
+
IMAGE_MIMES.includes((item as { mime?: unknown }).mime as typeof IMAGE_MIMES[number]) &&
|
|
54
|
+
Number.isSafeInteger((item as { bytes?: unknown }).bytes) && (item as { bytes: number }).bytes > 0 && (item as { bytes: number }).bytes <= IMAGE_MAX_BYTES
|
|
55
|
+
).map(item => {
|
|
56
|
+
const image = item as DraftImage;
|
|
57
|
+
const uri = validUri(image.uri) && !image.uri.startsWith("data:") ? image.uri : undefined;
|
|
58
|
+
return {
|
|
59
|
+
id: image.id, sessionId: image.sessionId, fileName: image.fileName.slice(0,255), mime: image.mime, bytes: image.bytes,
|
|
60
|
+
status: image.status === "ready" && uri ? "ready" : "error",
|
|
61
|
+
...(uri ? {uri} : {}),
|
|
62
|
+
...(typeof image.thumbnail === "string" && image.thumbnail.length <= 65536 && /^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(image.thumbnail) ? {thumbnail:image.thumbnail} : {}),
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
}
|
package/src/btw.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 辅助会话(/btw)的旁路问答记录。
|
|
3
|
+
*
|
|
4
|
+
* 答案通过 session.generate 从当前会话上下文一次性生成,不写入对话时间线。
|
|
5
|
+
* 记录按会话分组保存在扩展 globalState,结构对齐官方 Web 的 btw 插件:
|
|
6
|
+
* { id, question, answer, agent, model, created, duration },失败原因单独标记。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type BtwFailure = "timeout" | "error" | "empty" | "interrupted";
|
|
10
|
+
|
|
11
|
+
export interface BtwChat {
|
|
12
|
+
id: string;
|
|
13
|
+
question: string;
|
|
14
|
+
answer?: string;
|
|
15
|
+
agent?: string;
|
|
16
|
+
model?: { providerId: string; modelId: string; variant?: string };
|
|
17
|
+
created: number;
|
|
18
|
+
duration?: number;
|
|
19
|
+
failure?: BtwFailure;
|
|
20
|
+
message?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const BTW_CHATS_KEY = "opencodeChat.btwChats.v1";
|
|
24
|
+
export const BTW_TIMEOUT_MS = 300_000;
|
|
25
|
+
export const BTW_MAX_PER_SESSION = 100;
|
|
26
|
+
|
|
27
|
+
export function isBtwFailure(value: unknown): value is BtwFailure {
|
|
28
|
+
return value === "timeout" || value === "error" || value === "empty" || value === "interrupted";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function normalizeChat(value: unknown): BtwChat | undefined {
|
|
32
|
+
if (!value || typeof value !== "object") return undefined;
|
|
33
|
+
const chat = value as Record<string, unknown>;
|
|
34
|
+
const id = typeof chat.id === "string" && chat.id ? chat.id : undefined;
|
|
35
|
+
const question = typeof chat.question === "string" ? chat.question : undefined;
|
|
36
|
+
if (!id || question === undefined) return undefined;
|
|
37
|
+
const model = chat.model && typeof chat.model === "object" ? chat.model as Record<string, unknown> : undefined;
|
|
38
|
+
return {
|
|
39
|
+
id,
|
|
40
|
+
question,
|
|
41
|
+
...(typeof chat.answer === "string" && chat.answer ? { answer: chat.answer } : {}),
|
|
42
|
+
...(typeof chat.agent === "string" && chat.agent ? { agent: chat.agent } : {}),
|
|
43
|
+
...(model && typeof model.providerId === "string" && typeof model.modelId === "string"
|
|
44
|
+
? {
|
|
45
|
+
model: {
|
|
46
|
+
providerId: model.providerId,
|
|
47
|
+
modelId: model.modelId,
|
|
48
|
+
...(typeof model.variant === "string" && model.variant ? { variant: model.variant } : {}),
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
: {}),
|
|
52
|
+
...(typeof chat.created === "number" && Number.isFinite(chat.created) ? { created: chat.created } : { created: 0 }),
|
|
53
|
+
...(typeof chat.duration === "number" && Number.isFinite(chat.duration) ? { duration: chat.duration } : {}),
|
|
54
|
+
...(isBtwFailure(chat.failure) ? { failure: chat.failure } : {}),
|
|
55
|
+
...(typeof chat.message === "string" && chat.message ? { message: chat.message } : {}),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Normalize a persisted {sessionId: chats} store, dropping malformed entries. */
|
|
60
|
+
export function normalizeBtwStore(value: unknown): Record<string, BtwChat[]> {
|
|
61
|
+
if (!value || typeof value !== "object") return {};
|
|
62
|
+
const store: Record<string, BtwChat[]> = {};
|
|
63
|
+
for (const [sessionId, chats] of Object.entries(value as Record<string, unknown>)) {
|
|
64
|
+
if (!sessionId || !Array.isArray(chats)) continue;
|
|
65
|
+
const normalized = chats.map(normalizeChat).filter((chat): chat is BtwChat => chat !== undefined);
|
|
66
|
+
if (normalized.length) store[sessionId] = normalized.slice(0, BTW_MAX_PER_SESSION);
|
|
67
|
+
}
|
|
68
|
+
return store;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function btwFailureLabel(failure: BtwFailure, message?: string): string {
|
|
72
|
+
if (failure === "timeout") return "模型响应超时。";
|
|
73
|
+
if (failure === "empty") return "模型没有返回文本。";
|
|
74
|
+
if (failure === "interrupted") return "已中断。";
|
|
75
|
+
return message ? `回答失败:${message}` : "回答失败。";
|
|
76
|
+
}
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { OpenCode, type OpenCodeClient, type V2Event } from "@opencode/client";
|
|
2
|
+
import { OpenCodeConversation } from "./projection.js";
|
|
3
|
+
import { modelsFromApi, agentsFromApi, permissionFromApi, formFromApi, type ModelChoice, type AgentChoice } from "./protocol.js";
|
|
4
|
+
import { Translator } from "./translator.js";
|
|
5
|
+
import { listWorktrees, removeWorktree } from "./worktrees.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 设备侧 Host 核心:一个设备一个实例,复用与 VS Code 扩展相同的会话投影
|
|
9
|
+
* (Conversation)与协议归一化(protocol.ts),把 opencode 事件翻译成
|
|
10
|
+
* webview 已有的 host.out 消息。MVP 覆盖聊天核心:会话列表/切换、发送、
|
|
11
|
+
* 流式输出、停止、模型/Agent/技能目录。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export interface DeviceHostOptions {
|
|
15
|
+
baseUrl: string;
|
|
16
|
+
password: string;
|
|
17
|
+
directory: string;
|
|
18
|
+
send: (payload: Record<string, unknown>) => void;
|
|
19
|
+
onError?: (error: unknown) => void;
|
|
20
|
+
/** 翻译缓存文件路径;不传则只在内存缓存。 */
|
|
21
|
+
translationCachePath?: string;
|
|
22
|
+
/** Agent 文件操作代理:由 Connector 反向 WSS 通道提供。 */
|
|
23
|
+
agentFiles?: (op: string, payload: Record<string, unknown>) => Promise<unknown>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const authHeaders = (password: string) => ({ authorization: "Basic " + Buffer.from(`opencode:${password}`).toString("base64") });
|
|
27
|
+
|
|
28
|
+
export class DeviceHost {
|
|
29
|
+
private client: OpenCodeClient;
|
|
30
|
+
private conversation: OpenCodeConversation;
|
|
31
|
+
private directory: string;
|
|
32
|
+
private currentSessionId?: string;
|
|
33
|
+
private models: ModelChoice[] = [];
|
|
34
|
+
private agents: AgentChoice[] = [];
|
|
35
|
+
private skills: Array<{ name: string; description: string; path: string }> = [];
|
|
36
|
+
private running = new Set<string>();
|
|
37
|
+
private inbox = new Map<string, Array<{ queueItemId: string; text: string }>>();
|
|
38
|
+
private sendFn: (payload: Record<string, unknown>) => void;
|
|
39
|
+
private abort = new AbortController();
|
|
40
|
+
private disposed = false;
|
|
41
|
+
private translator: Translator;
|
|
42
|
+
|
|
43
|
+
constructor(private readonly options: DeviceHostOptions) {
|
|
44
|
+
this.client = OpenCode.make({ baseUrl: options.baseUrl, headers: authHeaders(options.password) });
|
|
45
|
+
this.directory = options.directory;
|
|
46
|
+
this.conversation = new OpenCodeConversation(event => this.onProjected(event as unknown as { type: string; data: Record<string, unknown> }));
|
|
47
|
+
this.sendFn = options.send;
|
|
48
|
+
this.translator = new Translator({
|
|
49
|
+
generate: async (prompt: string) => {
|
|
50
|
+
const res = await this.client.experimental.generate.text({ prompt });
|
|
51
|
+
return String((res as { text?: string }).text ?? "");
|
|
52
|
+
},
|
|
53
|
+
cachePath: options.translationCachePath,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 浏览器重连后把输出通道切到新连接,并补发全量快照。 */
|
|
58
|
+
attach(send: (payload: Record<string, unknown>) => void): void {
|
|
59
|
+
this.sendFn = send;
|
|
60
|
+
this.disposed = false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 网关保留设备 Host 期间不再投递事件到旧浏览器。 */
|
|
64
|
+
detach(): void {
|
|
65
|
+
this.sendFn = () => {};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
dispose(): void {
|
|
69
|
+
this.disposed = true;
|
|
70
|
+
this.abort.abort();
|
|
71
|
+
this.detach();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 订阅设备事件流;断线由调用方重建实例。 */
|
|
75
|
+
async start(): Promise<void> {
|
|
76
|
+
void (async () => {
|
|
77
|
+
try {
|
|
78
|
+
for await (const event of this.client.event.subscribe({ signal: this.abort.signal })) {
|
|
79
|
+
if (this.disposed) return;
|
|
80
|
+
this.handleRawEvent(event as unknown as V2Event);
|
|
81
|
+
}
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (!this.disposed) this.options.onError?.(error);
|
|
84
|
+
}
|
|
85
|
+
})();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 浏览器重连时补发当前状态全量快照,覆盖断线期间丢失的事件。 */
|
|
89
|
+
async sendSnapshot(): Promise<void> {
|
|
90
|
+
await this.listSessions();
|
|
91
|
+
const sessionId = this.currentSessionId;
|
|
92
|
+
if (!sessionId) return;
|
|
93
|
+
this.sendFn({ type: "session_ready", sessionId, kind: "switched", title: "", slashCommands: [] });
|
|
94
|
+
await this.sendHistory(sessionId);
|
|
95
|
+
this.sendFn({ type: "queue_sync", sessionId, items: [...(this.inbox.get(sessionId) ?? [])] });
|
|
96
|
+
this.sendFn({ type: "status", status: this.running.has(sessionId) ? "running" : "idle", sessionId });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private handleRawEvent(event: V2Event): void {
|
|
100
|
+
const sessionId = ((event.data as Record<string, unknown> | undefined)?.sessionID
|
|
101
|
+
?? (event.data as Record<string, unknown> | undefined)?.sessionId
|
|
102
|
+
?? undefined) as string | undefined;
|
|
103
|
+
const type = String((event as unknown as { type: string }).type);
|
|
104
|
+
// 流式增量直接转发(webview 的 delta 通道不经过投影)
|
|
105
|
+
if (type === "session.text.delta") {
|
|
106
|
+
const data = event.data as { sessionID: string; assistantMessageID: string; delta?: string };
|
|
107
|
+
if (data.delta) this.sendFn({
|
|
108
|
+
type: "assistant_text_delta", sessionId: data.sessionID,
|
|
109
|
+
delta: data.delta, partId: data.assistantMessageID, streaming: true,
|
|
110
|
+
});
|
|
111
|
+
} else if (type === "session.reasoning.delta") {
|
|
112
|
+
const data = event.data as { sessionID: string; delta?: string };
|
|
113
|
+
if (data.delta) this.sendFn({
|
|
114
|
+
type: "assistant_reasoning_delta", sessionId: data.sessionID, delta: data.delta, streaming: true,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
if (sessionId && type.startsWith("session.inbox.")) {
|
|
118
|
+
const data = event.data as { item?: { id?: string; text?: string }; inboxID?: string };
|
|
119
|
+
const queue = this.inbox.get(sessionId) ?? [];
|
|
120
|
+
if (type === "session.inbox.enqueued") {
|
|
121
|
+
queue.push({ queueItemId: data.item?.id ?? data.inboxID ?? "", text: data.item?.text ?? "" });
|
|
122
|
+
} else {
|
|
123
|
+
const inboxId = data.item?.id ?? data.inboxID;
|
|
124
|
+
const index = queue.findIndex(entry => entry.queueItemId === inboxId);
|
|
125
|
+
if (index >= 0) queue.splice(index, 1);
|
|
126
|
+
}
|
|
127
|
+
this.inbox.set(sessionId, queue);
|
|
128
|
+
this.sendFn({ type: "queue_sync", sessionId, items: [...queue] });
|
|
129
|
+
}
|
|
130
|
+
// 其余事件交给投影(transcript/status/usage/标题/模型信息等)
|
|
131
|
+
this.conversation.applyEvent(event);
|
|
132
|
+
if (type === "permission.asked") {
|
|
133
|
+
const permission = permissionFromApi(event.data);
|
|
134
|
+
if (permission) this.sendFn({ type: "permission_request", ...permission });
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (type === "form.created") {
|
|
138
|
+
const form = formFromApi(event.data);
|
|
139
|
+
if (form) this.sendFn({ type: "form_request", sessionId, form });
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (sessionId && (type === "session.execution.started" || type === "session.inbox.enqueued")) {
|
|
143
|
+
this.running.add(sessionId);
|
|
144
|
+
this.sendFn({ type: "status", status: "running", sessionId });
|
|
145
|
+
}
|
|
146
|
+
if (sessionId && ["session.execution.succeeded", "session.execution.failed", "session.idle"].includes(type)) {
|
|
147
|
+
this.running.delete(sessionId);
|
|
148
|
+
this.sendFn({ type: "status", status: "completedSuccess", sessionId });
|
|
149
|
+
}
|
|
150
|
+
if (sessionId && type === "session.idle") {
|
|
151
|
+
this.sendFn({ type: "status", status: "completedSuccess", sessionId });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private onProjected(event: { type: string; data: Record<string, unknown> }): void {
|
|
156
|
+
const payload = { ...event.data, type: event.type } as Record<string, unknown>;
|
|
157
|
+
if (event.type === "transcript_sync") {
|
|
158
|
+
this.sendFn({ type: "conversation_sync", ...payload });
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
this.sendFn(payload);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async listSessions(): Promise<void> {
|
|
165
|
+
const res = await this.client.session.list({});
|
|
166
|
+
const sessions = (res.data ?? []).map(session => ({
|
|
167
|
+
sessionId: String(session.id),
|
|
168
|
+
title: session.title ?? "",
|
|
169
|
+
updatedAt: (session as unknown as { time?: { updated?: number } }).time?.updated,
|
|
170
|
+
}));
|
|
171
|
+
this.sendFn({ type: "sessions", sessions, hasMore: false });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async selectSession(sessionId: string): Promise<void> {
|
|
175
|
+
this.currentSessionId = sessionId;
|
|
176
|
+
this.conversation.resetSession(sessionId);
|
|
177
|
+
this.sendFn({ type: "view_reset" });
|
|
178
|
+
this.sendFn({
|
|
179
|
+
type: "session_ready", sessionId, kind: "switched",
|
|
180
|
+
title: "", slashCommands: [],
|
|
181
|
+
});
|
|
182
|
+
this.sendFn({ type: "status", status: "idle", sessionId });
|
|
183
|
+
await this.sendHistory(sessionId);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async sendHistory(sessionId: string): Promise<void> {
|
|
187
|
+
try {
|
|
188
|
+
const res = await this.client.message.list({ sessionID: sessionId, limit: 200, order: "desc" });
|
|
189
|
+
const messages = [...(res.data ?? [])].reverse();
|
|
190
|
+
const items = this.conversation.loadSnapshot(sessionId, messages as never);
|
|
191
|
+
this.sendFn({ type: "history", sessionId, items, truncated: false, renderSource: "snapshot" });
|
|
192
|
+
} catch (error) {
|
|
193
|
+
this.options.onError?.(error);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async newSession(): Promise<void> {
|
|
198
|
+
const res = await this.client.session.create({ parentID: null }, { headers: authHeaders(this.options.password) });
|
|
199
|
+
const sessionId = (res as unknown as { id?: string }).id ?? (res as unknown as { data?: { id?: string } }).data?.id;
|
|
200
|
+
if (!sessionId) throw new Error("创建会话失败");
|
|
201
|
+
await this.selectSession(sessionId);
|
|
202
|
+
this.sendFn({ type: "session_ready", sessionId, kind: "created", title: t2("新会话"), slashCommands: [] });
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async sendPrompt(
|
|
206
|
+
text: string,
|
|
207
|
+
extras?: {
|
|
208
|
+
attachments?: Array<{ uri: string; fileName?: string }>;
|
|
209
|
+
files?: Array<{ uri: string; name?: string }>;
|
|
210
|
+
skills?: string[];
|
|
211
|
+
delivery?: "steer" | "queue";
|
|
212
|
+
},
|
|
213
|
+
): Promise<void> {
|
|
214
|
+
const sessionId = this.currentSessionId;
|
|
215
|
+
if (!sessionId) throw new Error("当前没有会话");
|
|
216
|
+
const files: Array<{ uri: string; name?: string }> = [
|
|
217
|
+
...(extras?.files ?? []),
|
|
218
|
+
...(extras?.attachments ?? []).map(attachment => ({ uri: attachment.uri, name: attachment.fileName })),
|
|
219
|
+
];
|
|
220
|
+
await this.client.session.prompt({
|
|
221
|
+
sessionID: sessionId, text,
|
|
222
|
+
...(files.length ? { files } : {}),
|
|
223
|
+
...(extras?.skills?.length ? { skills: extras.skills.map(id => ({ id })) } : {}),
|
|
224
|
+
delivery: extras?.delivery ?? "steer",
|
|
225
|
+
});
|
|
226
|
+
this.sendFn({ type: "status", status: "running", sessionId });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async stop(): Promise<void> {
|
|
230
|
+
const sessionId = this.currentSessionId;
|
|
231
|
+
if (!sessionId) return;
|
|
232
|
+
await this.client.session.interrupt({ sessionID: sessionId });
|
|
233
|
+
this.sendFn({ type: "status", status: "stopping", sessionId });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async sendCatalogs(): Promise<void> {
|
|
237
|
+
const [models, providers, agents, skills] = await Promise.all([
|
|
238
|
+
this.client.model.list({ location: { directory: this.directory } }),
|
|
239
|
+
this.client.provider.list({ location: { directory: this.directory } }),
|
|
240
|
+
this.client.agent.list({ location: { directory: this.directory } }),
|
|
241
|
+
this.client.skill.list({ location: { directory: this.directory } }).catch(() => ({ data: [] })),
|
|
242
|
+
]);
|
|
243
|
+
this.models = modelsFromApi(models.data, providers.data);
|
|
244
|
+
this.agents = agentsFromApi(agents.data);
|
|
245
|
+
this.skills = (skills.data ?? []).map((skill: { name?: string; description?: string; path?: string }) => ({
|
|
246
|
+
name: skill.name ?? "", description: skill.description ?? "", path: skill.path ?? "",
|
|
247
|
+
}));
|
|
248
|
+
this.pushCatalogs();
|
|
249
|
+
this.sendFn({ type: "session_controls", sessionId: this.currentSessionId, mode: "build", thoughtEnabled: false });
|
|
250
|
+
void this.translateCatalogs();
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private pushCatalogs(): void {
|
|
254
|
+
this.sendFn({ type: "models", available: this.models, modelFallback: false, autoSwitchModel: false });
|
|
255
|
+
this.sendFn({ type: "agent_catalog", agents: this.agents });
|
|
256
|
+
this.sendFn({ type: "skill_catalog", sessionId: this.currentSessionId, skills: this.skills });
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** 异步翻译目录描述(失败保留原文),完成后覆盖推送。 */
|
|
260
|
+
private async translateCatalogs(): Promise<void> {
|
|
261
|
+
const descriptions = [
|
|
262
|
+
...this.agents.map(agent => agent.description ?? ""),
|
|
263
|
+
...this.skills.map(skill => skill.description ?? ""),
|
|
264
|
+
...this.models.flatMap(model => model.variants.map(variant => variant.description ?? "")),
|
|
265
|
+
].filter(Boolean);
|
|
266
|
+
if (!descriptions.length) return;
|
|
267
|
+
const translated = await this.translator.translate(descriptions);
|
|
268
|
+
if (this.disposed) return;
|
|
269
|
+
this.agents = this.agents.map(agent => ({
|
|
270
|
+
...agent, description: agent.description ? translated.get(agent.description) ?? agent.description : undefined,
|
|
271
|
+
}));
|
|
272
|
+
this.skills = this.skills.map(skill => ({
|
|
273
|
+
...skill, description: skill.description ? translated.get(skill.description) ?? skill.description : "",
|
|
274
|
+
}));
|
|
275
|
+
this.models = this.models.map(model => ({
|
|
276
|
+
...model,
|
|
277
|
+
variants: model.variants.map(variant => ({
|
|
278
|
+
...variant, description: variant.description ? translated.get(variant.description) ?? variant.description : undefined,
|
|
279
|
+
})),
|
|
280
|
+
}));
|
|
281
|
+
this.pushCatalogs();
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async selectModel(providerId: string, modelId: string): Promise<void> {
|
|
285
|
+
const sessionId = this.currentSessionId;
|
|
286
|
+
if (!sessionId) return;
|
|
287
|
+
await this.client.session.switchModel({
|
|
288
|
+
sessionID: sessionId,
|
|
289
|
+
model: { id: modelId, providerID: providerId },
|
|
290
|
+
});
|
|
291
|
+
this.sendFn({ type: "model_switched", sessionId, providerId, modelId });
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** 重连时若 visitor 被回收过,重建 SSE 订阅。 */
|
|
295
|
+
resubscribe(): void {
|
|
296
|
+
this.abort.abort();
|
|
297
|
+
this.abort = new AbortController();
|
|
298
|
+
void this.start();
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** 设备文件操作(Agent markdown 等)经反向 WSS 交给 Connector 执行。 */
|
|
302
|
+
async agentFiles(op: string, request: Record<string, unknown>): Promise<void> {
|
|
303
|
+
if (!this.options.agentFiles) throw new Error("设备未连接文件代理。");
|
|
304
|
+
try {
|
|
305
|
+
const data = await this.options.agentFiles(op, request);
|
|
306
|
+
this.sendFn({ type: "agent_files_result", id: request.id, ok: true, data });
|
|
307
|
+
} catch (error) {
|
|
308
|
+
this.sendFn({
|
|
309
|
+
type: "agent_files_result", id: request.id, ok: false,
|
|
310
|
+
error: error instanceof Error ? error.message : String(error),
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** 图片附件在设备侧还原为 opencode attachment 结构。 */
|
|
316
|
+
uploadImage(dataUrl: string, fileName: string, imageId?: string): void {
|
|
317
|
+
const sessionId = this.currentSessionId;
|
|
318
|
+
try {
|
|
319
|
+
const match = /^data:(image\/(?:png|jpeg|webp|gif));base64,([A-Za-z0-9+/=]+)$/.exec(String(dataUrl || ""));
|
|
320
|
+
if (!match) throw new Error("仅支持 PNG、JPEG、WebP、GIF。");
|
|
321
|
+
const bytes = Math.floor(match[2].length * 3 / 4);
|
|
322
|
+
const attachment = {
|
|
323
|
+
uri: dataUrl,
|
|
324
|
+
fileName: String(fileName || "image.png").replace(/[\\/\0\r\n]/g, "_").slice(0, 255),
|
|
325
|
+
mime: match[1],
|
|
326
|
+
bytes,
|
|
327
|
+
};
|
|
328
|
+
this.sendFn({ type: "image_ready", sessionId, imageId, attachment });
|
|
329
|
+
} catch (error) {
|
|
330
|
+
this.sendFn({
|
|
331
|
+
type: "image_failed", sessionId, imageId,
|
|
332
|
+
message: error instanceof Error ? error.message : String(error),
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async fileSearch(query: string): Promise<void> {
|
|
338
|
+
const res = await this.client.file.find({ location: { directory: this.directory }, query, type: "file", limit: 50 });
|
|
339
|
+
this.sendFn({ type: "file_search_result", query, items: res.data ?? [] });
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async listWorktrees(): Promise<void> {
|
|
343
|
+
try {
|
|
344
|
+
const worktrees = await listWorktrees(this.client, this.directory);
|
|
345
|
+
this.sendFn({ type: "worktrees", worktrees });
|
|
346
|
+
} catch (error) {
|
|
347
|
+
this.sendFn({ type: "worktrees", worktrees: [], notice: error instanceof Error ? error.message : String(error) });
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
async removeWorktree(target: string): Promise<void> {
|
|
352
|
+
const location = await this.client.location.get({ location: { directory: this.directory } });
|
|
353
|
+
const projectId = String((location as unknown as { project?: { id?: string } }).project?.id ?? "");
|
|
354
|
+
if (!projectId) throw new Error("无法定位当前项目。");
|
|
355
|
+
await removeWorktree(this.client, this.directory, projectId, target, false);
|
|
356
|
+
await this.listWorktrees();
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async mcpList(): Promise<void> {
|
|
360
|
+
const res = await this.client.mcp.list({ location: { directory: this.directory } });
|
|
361
|
+
this.sendFn({ type: "mcp_status", sessionId: this.currentSessionId, servers: res.data ?? [] });
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async mcpAdd(name: string, config: unknown): Promise<void> {
|
|
365
|
+
await this.client.experimental.mcp.add({
|
|
366
|
+
server: name, location: { directory: this.directory }, config: config as never,
|
|
367
|
+
});
|
|
368
|
+
await this.mcpList();
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async mcpRemove(name: string): Promise<void> {
|
|
372
|
+
await this.client.experimental.mcp.remove({ server: name, location: { directory: this.directory } });
|
|
373
|
+
await this.mcpList();
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async mcpConnect(name: string, connect: boolean): Promise<void> {
|
|
377
|
+
const input = { server: name, location: { directory: this.directory } };
|
|
378
|
+
if (connect) await this.client.experimental.mcp.connect(input);
|
|
379
|
+
else await this.client.experimental.mcp.disconnect(input);
|
|
380
|
+
await this.mcpList();
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
currentSession(): string | undefined { return this.currentSessionId; }
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** 网页端最小中文文案(避免引入完整 uiText)。 */
|
|
387
|
+
function t2(text: string): string { return text; }
|