hob-bot 0.0.0-stage → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/README.zh-CN.md +112 -0
- package/bin/hob.mjs +7 -0
- package/dist/web/assets/index-D88l35PH.css +1 -0
- package/dist/web/assets/index-DUs8nN3E.js +218 -0
- package/dist/web/favicon.ico +0 -0
- package/dist/web/fonts/inter-latin.woff2 +0 -0
- package/dist/web/fonts/jetbrains-mono-latin.woff2 +0 -0
- package/dist/web/icons/apple-touch-icon-180.png +0 -0
- package/dist/web/icons/favicon-32.png +0 -0
- package/dist/web/icons/icon-192.png +0 -0
- package/dist/web/icons/icon-512.png +0 -0
- package/dist/web/icons/icon-maskable-512.png +0 -0
- package/dist/web/index.html +32 -0
- package/dist/web/manifest.webmanifest +16 -0
- package/dist/web/sw.js +131 -0
- package/package.json +62 -4
- package/server/src/actions.ts +230 -0
- package/server/src/boot.ts +85 -0
- package/server/src/bus.ts +21 -0
- package/server/src/config.ts +123 -0
- package/server/src/cron-text.ts +49 -0
- package/server/src/delegations.ts +113 -0
- package/server/src/files.ts +142 -0
- package/server/src/http.ts +802 -0
- package/server/src/ids.ts +19 -0
- package/server/src/image.ts +218 -0
- package/server/src/imports.ts +302 -0
- package/server/src/jobs.ts +730 -0
- package/server/src/main.ts +69 -0
- package/server/src/memory.ts +272 -0
- package/server/src/models.ts +358 -0
- package/server/src/overview.ts +116 -0
- package/server/src/pages.ts +54 -0
- package/server/src/password.ts +23 -0
- package/server/src/pi.ts +273 -0
- package/server/src/prompt.ts +227 -0
- package/server/src/providers.ts +532 -0
- package/server/src/push.ts +285 -0
- package/server/src/router-tools.ts +549 -0
- package/server/src/router.ts +841 -0
- package/server/src/routines.ts +129 -0
- package/server/src/runtime.ts +104 -0
- package/server/src/search.ts +91 -0
- package/server/src/secrets.ts +46 -0
- package/server/src/settings.ts +452 -0
- package/server/src/skills.ts +150 -0
- package/server/src/store.ts +324 -0
- package/server/src/text.ts +14 -0
- package/server/src/time.ts +42 -0
- package/server/src/transcript.ts +272 -0
- package/server/src/worker-tools.ts +129 -0
- package/shared/command.ts +42 -0
- package/shared/files.ts +141 -0
- package/shared/media.ts +17 -0
- package/shared/model-note.ts +32 -0
- package/shared/page-shell.ts +108 -0
- package/shared/search.ts +19 -0
- package/shared/skills.ts +37 -0
- package/shared/sprites.ts +422 -0
- package/shared/thinking.ts +118 -0
- package/shared/types.ts +631 -0
- package/vendor/lore-pi-extension/README.md +28 -0
- package/vendor/lore-pi-extension/api.ts +140 -0
- package/vendor/lore-pi-extension/formatters.ts +204 -0
- package/vendor/lore-pi-extension/hooks.ts +195 -0
- package/vendor/lore-pi-extension/index.ts +25 -0
- package/vendor/lore-pi-extension/package.json +23 -0
- package/vendor/lore-pi-extension/skills.ts +447 -0
- package/vendor/lore-pi-extension/tools.ts +344 -0
- package/vendor/lore-pi-extension/uri.ts +67 -0
- package/vendor/lore-pi-extension/vendor/skill-workcopy/index.d.mts +266 -0
- package/vendor/lore-pi-extension/vendor/skill-workcopy/index.mjs +1328 -0
- package/vendor/lore-pi-extension/vendor/skill-workcopy/skills-sync.d.mts +33 -0
- package/vendor/lore-pi-extension/vendor/skill-workcopy/skills-sync.mjs +202 -0
|
@@ -0,0 +1,841 @@
|
|
|
1
|
+
import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
|
|
2
|
+
import { parseStreamingJson } from "@earendil-works/pi-ai/utils/json-parse";
|
|
3
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { mkdirSync } from "node:fs";
|
|
5
|
+
import { dirname } from "node:path";
|
|
6
|
+
import type { AgentSession, AgentSessionEvent, SessionEntry, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { SessionManager as SessionManagerImpl } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import type {
|
|
9
|
+
Assistant,
|
|
10
|
+
AssistantSummary,
|
|
11
|
+
Bootstrap,
|
|
12
|
+
Iso,
|
|
13
|
+
Item,
|
|
14
|
+
ItemsPage,
|
|
15
|
+
PageLive,
|
|
16
|
+
Profile,
|
|
17
|
+
SendMessageBody,
|
|
18
|
+
} from "../../shared/types.ts";
|
|
19
|
+
import type { HobRuntime } from "./runtime.ts";
|
|
20
|
+
import { refreshSystemPrompt } from "./pi.ts";
|
|
21
|
+
import { conversationPick, defaultWorkRef, jobModel, nameOf, noteOf, thinkingForPick, thinkingLevelsOf, fitThinking, usableRefs, NO_MODEL_NOTE, NoModelError } from "./models.ts";
|
|
22
|
+
import { buildRouterTools } from "./router-tools.ts";
|
|
23
|
+
import { MEMORY_WRITE_TOOLS, memoryNoteText } from "./memory.ts";
|
|
24
|
+
import { buildSystemPrompt, type PromptModel } from "./prompt.ts";
|
|
25
|
+
import { availableSkills } from "./skills.ts";
|
|
26
|
+
|
|
27
|
+
export const ITEM_TYPE = "hob.item";
|
|
28
|
+
export const USER_TYPE = "hob.user";
|
|
29
|
+
export const EVENT_TYPE = "hob.event";
|
|
30
|
+
|
|
31
|
+
/** 会话条目的 id 和 at 由会话文件给出,写卡片时不用传。 */
|
|
32
|
+
/** 事件附带的信息,落在会话的事件条目上:routine 给回复挂「⏱ 名字」,cont 见 walk。 */
|
|
33
|
+
export interface EventDetails {
|
|
34
|
+
routine?: { id: string; name: string };
|
|
35
|
+
cont?: true;
|
|
36
|
+
delegationId?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type NewItem = Item extends infer T ? (T extends Item ? Omit<T, "id" | "at"> : never) : never;
|
|
40
|
+
|
|
41
|
+
interface RouterState {
|
|
42
|
+
assistantId: string;
|
|
43
|
+
session?: AgentSession;
|
|
44
|
+
manager?: SessionManager;
|
|
45
|
+
opening?: Promise<void>;
|
|
46
|
+
idleTimer?: NodeJS.Timeout;
|
|
47
|
+
/** 还有几轮在跑(事件那一轮也要算),用来判断忙闲和等空闲 */
|
|
48
|
+
running: number;
|
|
49
|
+
/** 正在流式的助手消息:条目 id 和 GET /items 推导出来的一致;shown 表示已经在对话里露过面 */
|
|
50
|
+
streaming?: { itemId: string; shown: boolean };
|
|
51
|
+
/** 这一轮最后一次有动静的时间,看门狗用它判断“没响应” */
|
|
52
|
+
lastEventAt: number;
|
|
53
|
+
stallTimer?: NodeJS.Timeout;
|
|
54
|
+
/** 已经因为没响应被叫停:这一轮的错误不再写一条重复的 note */
|
|
55
|
+
stalled: boolean;
|
|
56
|
+
/** 记忆提供者换了:跑着的这一轮结束就释放会话,下一轮按新提供者重新打开 */
|
|
57
|
+
releaseAfterTurn?: boolean;
|
|
58
|
+
/** 还在跑的记忆写入工具:参数只在 tool_execution_start 里有,按 toolCallId 存着给 note 用 */
|
|
59
|
+
memoryWriteArgs: Map<string, Record<string, unknown>>;
|
|
60
|
+
currentDelegationId?: string;
|
|
61
|
+
delegationReply?: string[];
|
|
62
|
+
terminatingTools?: Set<string>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function readEntries(file: string): SessionEntry[] {
|
|
66
|
+
if (!existsSync(file)) return [];
|
|
67
|
+
const out: SessionEntry[] = [];
|
|
68
|
+
for (const line of readFileSync(file, "utf8").split("\n")) {
|
|
69
|
+
if (!line.trim()) continue;
|
|
70
|
+
try {
|
|
71
|
+
const entry = JSON.parse(line) as { type?: string };
|
|
72
|
+
if (entry.type && entry.type !== "session") out.push(entry as SessionEntry);
|
|
73
|
+
} catch {
|
|
74
|
+
// 半行忽略
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function messageText(content: unknown): string {
|
|
81
|
+
if (typeof content === "string") return content.trim();
|
|
82
|
+
if (!Array.isArray(content)) return "";
|
|
83
|
+
return content
|
|
84
|
+
.filter((block): block is { type: "text"; text: string } => Boolean(block) && block.type === "text")
|
|
85
|
+
.map((block) => block.text)
|
|
86
|
+
.join("")
|
|
87
|
+
.trim();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** 模型服务的报错压成一句:「my-proxy API error (429): {"message":"…"}」→「模型服务返回 429:…」。 */
|
|
91
|
+
export function briefModelError(raw: string | undefined): string {
|
|
92
|
+
if (!raw) return "模型服务出错";
|
|
93
|
+
const code = raw.match(/\((\d{3})\)/)?.[1];
|
|
94
|
+
const detail = raw.match(/"message"\s*:\s*"([^"]+)"/)?.[1] ?? raw.replace(/\s+/g, " ");
|
|
95
|
+
const short = detail.length > 120 ? `${detail.slice(0, 119)}…` : detail;
|
|
96
|
+
return code ? `模型服务返回 ${code}:${short}` : short;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 从会话条目按顺序推导对话条目:用户消息来自 hob.user 自定义条目(不走 pi 的 user 消息,
|
|
101
|
+
* 事件消息也是 user 角色但不该出气泡),助手文本来自 assistant 消息,卡片来自 hob.item。
|
|
102
|
+
*
|
|
103
|
+
* 事件之后的第一条标 lead(新一轮回复,前端拉开间距);事件带 cont 表示任务的图片已经先开了这一组,回复接着图片走。
|
|
104
|
+
* 返回值里的 lead 是“下一条该不该标”,实时推送的条目用它,和刷新后推导的一致。
|
|
105
|
+
*/
|
|
106
|
+
function walk(entries: SessionEntry[]): { items: Item[]; lead: boolean } {
|
|
107
|
+
const items: Item[] = [];
|
|
108
|
+
let assistantIndex = 0;
|
|
109
|
+
let routine: { id: string; name: string } | undefined;
|
|
110
|
+
let lead = false;
|
|
111
|
+
const push = (item: Item) => {
|
|
112
|
+
items.push(lead ? { ...item, lead: true } : item);
|
|
113
|
+
lead = false;
|
|
114
|
+
};
|
|
115
|
+
for (const entry of entries) {
|
|
116
|
+
if (entry.type === "custom" && entry.customType === USER_TYPE) {
|
|
117
|
+
const data = (entry.data ?? {}) as { text?: string; quote?: { itemId: string; text: string }; files?: string[]; from?: { assistantId: string; name: string; delegationId: string } };
|
|
118
|
+
items.push({
|
|
119
|
+
kind: "user",
|
|
120
|
+
id: entry.id,
|
|
121
|
+
at: entry.timestamp,
|
|
122
|
+
text: data.text ?? "",
|
|
123
|
+
...(data.quote ? { quote: data.quote } : {}),
|
|
124
|
+
...(data.files?.length ? { files: data.files } : {}),
|
|
125
|
+
...(data.from ? { from: data.from } : {}),
|
|
126
|
+
});
|
|
127
|
+
lead = false;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (entry.type === "custom" && entry.customType === ITEM_TYPE) {
|
|
131
|
+
// 旧版本把别的助手的审批转述进主助手的对话(relay);现在审批只在提问的助手那里,历史里的转述卡不再显示
|
|
132
|
+
if ((entry.data as { kind?: string; relay?: boolean } | undefined)?.relay) continue;
|
|
133
|
+
push({ ...(entry.data as object), id: entry.id, at: entry.timestamp } as Item);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (entry.type === "custom_message" && entry.customType === EVENT_TYPE) {
|
|
137
|
+
const details = entry.details as EventDetails | undefined;
|
|
138
|
+
routine = details?.routine;
|
|
139
|
+
lead = !details?.cont;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
143
|
+
assistantIndex += 1;
|
|
144
|
+
const text = messageText(entry.message.content);
|
|
145
|
+
if (!text) continue;
|
|
146
|
+
push({
|
|
147
|
+
kind: "assistant",
|
|
148
|
+
id: `a-${assistantIndex}`,
|
|
149
|
+
at: entry.timestamp,
|
|
150
|
+
text,
|
|
151
|
+
...(routine ? { routine } : {}),
|
|
152
|
+
});
|
|
153
|
+
routine = undefined;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { items, lead };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function deriveItems(entries: SessionEntry[]): Item[] {
|
|
160
|
+
return walk(entries).items;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export class RouterManager {
|
|
164
|
+
private routers = new Map<string, RouterState>();
|
|
165
|
+
private livePages = new Map<string, Map<string, { page: PageLive; timer?: NodeJS.Timeout; last: number }>>();
|
|
166
|
+
private liveJson = new Map<string, string>();
|
|
167
|
+
|
|
168
|
+
private liveUpdate(assistantId: string, callId: string, args: Record<string, unknown>, flush = false): void {
|
|
169
|
+
let pages = this.livePages.get(assistantId);
|
|
170
|
+
if (!pages) this.livePages.set(assistantId, pages = new Map());
|
|
171
|
+
let live = pages.get(callId);
|
|
172
|
+
if (!live) {
|
|
173
|
+
live = { page: { assistantId, callId, html: "", state: "writing" }, last: 0 };
|
|
174
|
+
pages.set(callId, live);
|
|
175
|
+
}
|
|
176
|
+
live.page = { ...live.page, ...(typeof args.title === "string" ? { title: args.title } : {}), ...(typeof args.summary === "string" ? { summary: args.summary } : {}), ...(typeof args.html === "string" ? { html: args.html } : {}) };
|
|
177
|
+
const emit = () => { live!.timer = undefined; live!.last = Date.now(); this.bus.emit({ type: "page-live", ...live!.page }); };
|
|
178
|
+
if (flush || Date.now() - live.last >= 200) {
|
|
179
|
+
if (live.timer) clearTimeout(live.timer);
|
|
180
|
+
emit();
|
|
181
|
+
} else if (!live.timer) live.timer = setTimeout(emit, 200 - (Date.now() - live.last));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private liveFinish(assistantId: string, callId: string, path?: string, error?: string): void {
|
|
185
|
+
const pages = this.livePages.get(assistantId);
|
|
186
|
+
const live = pages?.get(callId);
|
|
187
|
+
if (!live) return;
|
|
188
|
+
this.liveUpdate(assistantId, callId, {}, true);
|
|
189
|
+
live.page = { ...live.page, state: path ? "done" : "failed", ...(path ? { path } : { error: error || "页面生成中断" }) };
|
|
190
|
+
this.bus.emit({ type: "page-live", ...live.page });
|
|
191
|
+
this.liveJson.delete(callId);
|
|
192
|
+
// 失败也不留:模型拿到错误通常会重写一页,留着的失败占位卡会一直钉在对话底部
|
|
193
|
+
pages!.delete(callId);
|
|
194
|
+
}
|
|
195
|
+
/** 测试可改小:不给就看设置里的“回复多久无响应视为受阻” */
|
|
196
|
+
stallOverrideMs?: number;
|
|
197
|
+
|
|
198
|
+
constructor(private readonly runtime: HobRuntime) {}
|
|
199
|
+
|
|
200
|
+
private get store() {
|
|
201
|
+
return this.runtime.store;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
private get bus() {
|
|
205
|
+
return this.runtime.bus;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
private assistant(assistantId: string): Assistant {
|
|
209
|
+
const assistant = this.store.assistant(assistantId);
|
|
210
|
+
if (!assistant) throw new Error(`助手不存在:${assistantId}`);
|
|
211
|
+
return assistant;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private entries(assistantId: string): SessionEntry[] {
|
|
215
|
+
const state = this.routers.get(assistantId);
|
|
216
|
+
if (state?.manager) return state.manager.getEntries();
|
|
217
|
+
return readEntries(this.store.routerFile(assistantId));
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async ensure(assistantId: string): Promise<RouterState> {
|
|
221
|
+
const assistant = this.assistant(assistantId);
|
|
222
|
+
let state = this.routers.get(assistantId);
|
|
223
|
+
if (!state) {
|
|
224
|
+
state = { assistantId, running: 0, lastEventAt: Date.now(), stalled: false, memoryWriteArgs: new Map() };
|
|
225
|
+
this.routers.set(assistantId, state);
|
|
226
|
+
}
|
|
227
|
+
if (state.session) return state;
|
|
228
|
+
state.opening ??= this.openSession(state, assistant).catch((error: unknown) => {
|
|
229
|
+
state!.opening = undefined;
|
|
230
|
+
throw error;
|
|
231
|
+
});
|
|
232
|
+
await state.opening;
|
|
233
|
+
return state;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private async openSession(state: RouterState, assistant: Assistant): Promise<void> {
|
|
237
|
+
// 提示词里要写模型的显示名和定位,所以先把注册表拉一遍
|
|
238
|
+
await this.runtime.models.get();
|
|
239
|
+
const pick = conversationPick(this.runtime.settings.settings.models, assistant);
|
|
240
|
+
const opened = await this.runtime.pi.open({
|
|
241
|
+
file: this.store.routerFile(assistant.id),
|
|
242
|
+
cwd: this.store.home,
|
|
243
|
+
model: pick.ref,
|
|
244
|
+
thinking: thinkingForPick(pick, this.runtime.models),
|
|
245
|
+
memory: this.runtime.settings.memory().provider,
|
|
246
|
+
systemPrompt: () => {
|
|
247
|
+
const { timezone, aboutYou } = this.runtime.settings.settings.general;
|
|
248
|
+
return buildSystemPrompt(this.store, assistant.id, {
|
|
249
|
+
timezone,
|
|
250
|
+
aboutYou,
|
|
251
|
+
memory: this.runtime.settings.memory().provider,
|
|
252
|
+
models: this.promptModels(assistant.id),
|
|
253
|
+
skills: availableSkills(this.runtime.home, undefined, this.runtime.settings.settings.skills?.disabled, this.runtime.settings.memory().provider === "lore" ? this.runtime.pi.loreSkillPaths : []),
|
|
254
|
+
thinkingChoice: this.runtime.settings.settings.models.thinkingChoice,
|
|
255
|
+
});
|
|
256
|
+
},
|
|
257
|
+
tools: buildRouterTools(this.runtime, assistant.id).map((tool) => tool.name),
|
|
258
|
+
customTools: buildRouterTools(this.runtime, assistant.id),
|
|
259
|
+
});
|
|
260
|
+
state.session = opened.session;
|
|
261
|
+
state.manager = opened.manager;
|
|
262
|
+
state.opening = undefined;
|
|
263
|
+
opened.session.subscribe((event) => this.onSessionEvent(state, assistant.id, event));
|
|
264
|
+
this.touch(assistant.id);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** 这个助手能派、当前可用的模型(提示词里那一节)。 */
|
|
268
|
+
private promptModels(assistantId: string): PromptModel[] {
|
|
269
|
+
const assistant = this.store.assistant(assistantId);
|
|
270
|
+
if (!assistant) return [];
|
|
271
|
+
const settings = this.runtime.settings.settings.models;
|
|
272
|
+
const catalog = this.runtime.models;
|
|
273
|
+
const def = defaultWorkRef(settings, assistant, catalog);
|
|
274
|
+
return usableRefs(settings, assistant, catalog).map((ref) => {
|
|
275
|
+
const entry = settings.roster.find((item) => item.ref === ref);
|
|
276
|
+
return {
|
|
277
|
+
name: nameOf(ref, catalog),
|
|
278
|
+
ref,
|
|
279
|
+
note: entry ? noteOf(entry, catalog) : "",
|
|
280
|
+
thinking: jobModel({ settings, assistant, catalog, requested: { model: ref } }).model.thinking,
|
|
281
|
+
levels: thinkingLevelsOf(catalog.find(ref)),
|
|
282
|
+
isDefault: ref === def,
|
|
283
|
+
};
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** 换了对话模型或思考档:下一轮生效,不重建会话(上下文保留)。 */
|
|
288
|
+
private async applyConversationModel(state: RouterState): Promise<void> {
|
|
289
|
+
if (!state.session) return;
|
|
290
|
+
const assistant = this.assistant(state.assistantId);
|
|
291
|
+
const pick = conversationPick(this.runtime.settings.settings.models, assistant);
|
|
292
|
+
const model = await this.runtime.pi.model(pick.ref);
|
|
293
|
+
// 用拿到的模型本身算档:换服务商后名单缓存是空的,按缓存查会把思考档收成 off
|
|
294
|
+
const thinking = fitThinking(getSupportedThinkingLevels(model), pick.thinking);
|
|
295
|
+
const current = state.session.model;
|
|
296
|
+
if (current?.provider !== model.provider || current?.id !== model.id) {
|
|
297
|
+
await state.session.setModel(model);
|
|
298
|
+
}
|
|
299
|
+
if (state.session.thinkingLevel !== thinking) state.session.setThinkingLevel(thinking);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* 实时条目:助手消息在 message_start 就定好 id(会话条目还没落盘,它是第 assistantCount()+1 条),
|
|
304
|
+
* 第一段文字到了才露面,message_end 之后等条目落盘再按条目发一次最终版。
|
|
305
|
+
* 这样前端拿到的 id、时间、内容和 GET /items 推导出来的一样。
|
|
306
|
+
*/
|
|
307
|
+
private onSessionEvent(state: RouterState, assistantId: string, event: AgentSessionEvent): void {
|
|
308
|
+
this.progress(state);
|
|
309
|
+
if (event.type === "message_start" && event.message.role === "custom" && event.message.customType === EVENT_TYPE) {
|
|
310
|
+
const details = event.message.details as EventDetails | undefined;
|
|
311
|
+
if (details?.delegationId) {
|
|
312
|
+
state.currentDelegationId = details.delegationId;
|
|
313
|
+
state.delegationReply = [];
|
|
314
|
+
state.terminatingTools = new Set();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if (event.type === "turn_end" && event.message.role === "assistant" && state.currentDelegationId) {
|
|
318
|
+
const text = messageText(event.message.content);
|
|
319
|
+
if (text) state.delegationReply?.push(text);
|
|
320
|
+
const failed = event.message.stopReason === "error" || event.message.stopReason === "aborted";
|
|
321
|
+
if (failed || !event.toolResults.length || event.toolResults.every((tool) => state.terminatingTools?.has(tool.toolCallId))) {
|
|
322
|
+
const id = state.currentDelegationId;
|
|
323
|
+
const reply = state.delegationReply?.join("\n") || (failed ? event.message.errorMessage || "目标助手处理失败" : "(没有回复)");
|
|
324
|
+
state.currentDelegationId = undefined;
|
|
325
|
+
state.delegationReply = undefined;
|
|
326
|
+
state.terminatingTools = undefined;
|
|
327
|
+
this.runtime.delegations.turnEnded(id, reply, failed);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (event.type === "tool_execution_start") {
|
|
331
|
+
if (MEMORY_WRITE_TOOLS.has(event.toolName)) state.memoryWriteArgs.set(event.toolCallId, event.args ?? {});
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
if (event.type === "tool_execution_end") {
|
|
335
|
+
if (event.toolName === "show_page") {
|
|
336
|
+
const result = event.result as { details?: { path?: string }; content?: { text?: string }[] } | undefined;
|
|
337
|
+
this.liveFinish(assistantId, event.toolCallId, event.isError ? undefined : result?.details?.path, result?.content?.[0]?.text);
|
|
338
|
+
}
|
|
339
|
+
if (state.currentDelegationId && (event.result as { terminate?: boolean } | undefined)?.terminate) state.terminatingTools?.add(event.toolCallId);
|
|
340
|
+
const args = state.memoryWriteArgs.get(event.toolCallId);
|
|
341
|
+
state.memoryWriteArgs.delete(event.toolCallId);
|
|
342
|
+
void this.onMemoryWrite(assistantId, event, args);
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
if (event.type === "message_start" && event.message.role === "assistant") {
|
|
346
|
+
state.streaming = { itemId: `a-${this.assistantCount(assistantId) + 1}`, shown: false };
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (event.type === "message_update" && (event.assistantMessageEvent.type === "toolcall_start" || event.assistantMessageEvent.type === "toolcall_delta" || event.assistantMessageEvent.type === "toolcall_end")) {
|
|
350
|
+
const update = event.assistantMessageEvent;
|
|
351
|
+
const part = update.partial.content[update.contentIndex];
|
|
352
|
+
if (part?.type === "toolCall" && part.name === "show_page") {
|
|
353
|
+
if (update.type === "toolcall_start") this.liveJson.set(part.id, "");
|
|
354
|
+
if (update.type === "toolcall_delta") this.liveJson.set(part.id, (this.liveJson.get(part.id) ?? "") + update.delta);
|
|
355
|
+
const args = Object.keys(part.arguments).length ? part.arguments : parseStreamingJson(this.liveJson.get(part.id));
|
|
356
|
+
this.liveUpdate(assistantId, part.id, args);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if ((event.type === "message_end" && event.message.role === "assistant" && ["error", "aborted", "length"].includes(event.message.stopReason)) || event.type === "agent_end") {
|
|
360
|
+
const reason = event.type === "message_end" && event.message.role === "assistant" ? event.message.errorMessage : undefined;
|
|
361
|
+
for (const [id, live] of this.livePages.get(assistantId) ?? []) if (live.page.state === "writing") this.liveFinish(assistantId, id, undefined, reason || "页面生成中断");
|
|
362
|
+
}
|
|
363
|
+
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
|
|
364
|
+
state.streaming ??= { itemId: `a-${this.assistantCount(assistantId) + 1}`, shown: false };
|
|
365
|
+
const streaming = state.streaming;
|
|
366
|
+
if (!streaming.shown) {
|
|
367
|
+
streaming.shown = true;
|
|
368
|
+
this.bus.emit({
|
|
369
|
+
type: "item",
|
|
370
|
+
assistantId,
|
|
371
|
+
item: {
|
|
372
|
+
kind: "assistant",
|
|
373
|
+
id: streaming.itemId,
|
|
374
|
+
at: new Date().toISOString(),
|
|
375
|
+
text: "",
|
|
376
|
+
streaming: true,
|
|
377
|
+
...(walk(this.entries(assistantId)).lead ? { lead: true } : {}),
|
|
378
|
+
},
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
this.bus.emit({ type: "delta", assistantId, itemId: streaming.itemId, text: event.assistantMessageEvent.delta });
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
if (event.type === "message_end" && event.message.role === "assistant") {
|
|
385
|
+
const streaming = state.streaming;
|
|
386
|
+
state.streaming = undefined;
|
|
387
|
+
const text = messageText(event.message.content).trim();
|
|
388
|
+
if (!text) return;
|
|
389
|
+
// pi 在 message_end 之后才把消息写进会话文件,等一拍再按条目发,内容和 id 才和刷新后一致
|
|
390
|
+
setTimeout(() => this.emitSettledAssistant(assistantId, text, streaming?.itemId), 0);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** 记忆插件写成功了 → 对话里出一行「记忆已更新 · …」。 */
|
|
395
|
+
private async onMemoryWrite(
|
|
396
|
+
assistantId: string,
|
|
397
|
+
event: { toolName: string; result?: unknown; isError?: boolean },
|
|
398
|
+
args: Record<string, unknown> | undefined,
|
|
399
|
+
): Promise<void> {
|
|
400
|
+
if (!MEMORY_WRITE_TOOLS.has(event.toolName) || event.isError) return;
|
|
401
|
+
const details = (event.result as { details?: { ok?: boolean } } | undefined)?.details;
|
|
402
|
+
if (details?.ok === false) return;
|
|
403
|
+
const text = memoryNoteText(args);
|
|
404
|
+
await this.addItem(assistantId, { kind: "note", icon: "memory", text: text ? `记忆已更新 · ${text}` : "记忆已更新" });
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
private emitSettledAssistant(assistantId: string, text: string, expectedId?: string): void {
|
|
408
|
+
const list = deriveItems(this.entries(assistantId)).filter((item) => item.kind === "assistant");
|
|
409
|
+
const item = list.find((entry) => entry.id === expectedId) ?? list.filter((entry) => entry.text === text).pop();
|
|
410
|
+
if (item) this.bus.emit({ type: "item", assistantId, item });
|
|
411
|
+
this.touch(assistantId);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
private assistantCount(assistantId: string): number {
|
|
415
|
+
return this.entries(assistantId).filter(
|
|
416
|
+
(entry) => entry.type === "message" && entry.message.role === "assistant",
|
|
417
|
+
).length;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** 一轮开始了:清掉上一轮的“已停”标记并起看门狗。 */
|
|
421
|
+
private armStall(state: RouterState): void {
|
|
422
|
+
state.stalled = false;
|
|
423
|
+
this.progress(state);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** 这一轮还有动静:重置看门狗。没有事件就说明模型憋住了。 */
|
|
427
|
+
private stallMs(): number {
|
|
428
|
+
return this.stallOverrideMs ?? this.runtime.settings.settings.work.routerStallMinutes * 60_000;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
private progress(state: RouterState): void {
|
|
432
|
+
state.lastEventAt = Date.now();
|
|
433
|
+
if (state.stallTimer) clearTimeout(state.stallTimer);
|
|
434
|
+
state.stallTimer = setTimeout(() => void this.onStall(state), this.stallMs());
|
|
435
|
+
state.stallTimer.unref?.();
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
private clearStall(state: RouterState): void {
|
|
439
|
+
if (state.stallTimer) clearTimeout(state.stallTimer);
|
|
440
|
+
state.stallTimer = undefined;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** 一轮里长时间没有事件(模型憋着不出字):停下这一轮,并明说可以再发一次。 */
|
|
444
|
+
private async onStall(state: RouterState): Promise<void> {
|
|
445
|
+
state.stallTimer = undefined;
|
|
446
|
+
if (Date.now() - state.lastEventAt < this.stallMs()) {
|
|
447
|
+
this.progress(state);
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (state.running === 0 && !state.session?.isStreaming) return;
|
|
451
|
+
state.stalled = true;
|
|
452
|
+
// 不 await:模型的那次请求可能收不了尾,但这行提示必须先出来
|
|
453
|
+
void state.session?.abort().catch(() => undefined);
|
|
454
|
+
const assistant = this.store.assistant(state.assistantId);
|
|
455
|
+
await this.addItem(state.assistantId, {
|
|
456
|
+
kind: "note",
|
|
457
|
+
icon: "info",
|
|
458
|
+
text: `${assistant?.name ?? state.assistantId} 无响应,已停止,可重新发送`,
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** 空闲 30 分钟释放 Router 内存,下次用再打开 router.jsonl。 */
|
|
463
|
+
private touch(assistantId: string): void {
|
|
464
|
+
const state = this.routers.get(assistantId);
|
|
465
|
+
if (!state?.session) return;
|
|
466
|
+
if (state.idleTimer) clearTimeout(state.idleTimer);
|
|
467
|
+
state.idleTimer = setTimeout(() => {
|
|
468
|
+
if (!state.session || state.session.isStreaming) return;
|
|
469
|
+
this.close(state);
|
|
470
|
+
}, 30 * 60 * 1000);
|
|
471
|
+
state.idleTimer.unref?.();
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
private close(state: RouterState): void {
|
|
475
|
+
if (state.idleTimer) clearTimeout(state.idleTimer);
|
|
476
|
+
state.idleTimer = undefined;
|
|
477
|
+
state.session?.dispose();
|
|
478
|
+
state.session = undefined;
|
|
479
|
+
state.manager = undefined;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* 记忆提供者或能派的模型换了:空闲的 Router 立刻释放,下一轮从 router.jsonl 重新打开
|
|
484
|
+
* (上下文还在,插件和 start_job 的模型说明按新设置来);正在回复的等这一轮跑完再释放。
|
|
485
|
+
*/
|
|
486
|
+
releaseSessions(): void {
|
|
487
|
+
for (const state of this.routers.values()) {
|
|
488
|
+
state.releaseAfterTurn = true;
|
|
489
|
+
this.maybeRelease(state);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** 助手没了(并回 Hob):关掉它的会话,内存里也不留 —— 它的目录随后会被移进归档。 */
|
|
494
|
+
forget(assistantId: string): void {
|
|
495
|
+
const state = this.routers.get(assistantId);
|
|
496
|
+
if (!state) return;
|
|
497
|
+
this.close(state);
|
|
498
|
+
this.routers.delete(assistantId);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
private maybeRelease(state: RouterState): void {
|
|
502
|
+
if (!state.releaseAfterTurn) return;
|
|
503
|
+
if (state.running > 0 || state.session?.isStreaming) return;
|
|
504
|
+
state.releaseAfterTurn = false;
|
|
505
|
+
this.close(state);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** 新条目的时间取会话条目自己的时间,和 GET /items 推导出来的一致。 */
|
|
509
|
+
private entryAt(state: RouterState, id: string): string {
|
|
510
|
+
return state.manager?.getEntries().find((entry) => entry.id === id)?.timestamp ?? new Date().toISOString();
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// ---------- 事件与条目 ----------
|
|
514
|
+
async addItem(assistantId: string, item: NewItem): Promise<Item> {
|
|
515
|
+
const state = await this.ensure(assistantId);
|
|
516
|
+
const lead = walk(this.entries(assistantId)).lead;
|
|
517
|
+
const id = state.manager!.appendCustomEntry(ITEM_TYPE, item);
|
|
518
|
+
const full = { ...item, ...(lead ? { lead: true } : {}), id, at: this.entryAt(state, id) } as Item;
|
|
519
|
+
this.bus.emit({ type: "item", assistantId, item: full });
|
|
520
|
+
return full;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
currentDelegation(assistantId: string): string | undefined {
|
|
524
|
+
return this.routers.get(assistantId)?.currentDelegationId;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
async addForwarded(assistantId: string, text: string, delegationId: string, sourceId = "hob"): Promise<Item> {
|
|
528
|
+
const state = await this.ensure(assistantId);
|
|
529
|
+
const from = { assistantId: sourceId, name: this.store.assistant(sourceId)?.name ?? sourceId, delegationId };
|
|
530
|
+
const id = state.manager!.appendCustomEntry(USER_TYPE, { text, from });
|
|
531
|
+
const item: Item = { kind: "user", id, at: this.entryAt(state, id), text, from };
|
|
532
|
+
this.bus.emit({ type: "item", assistantId, item });
|
|
533
|
+
return item;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async event(assistantId: string, text: string, details?: EventDetails): Promise<void> {
|
|
537
|
+
await this.ensure(assistantId);
|
|
538
|
+
void this.pushEvent(assistantId, text, details).catch(() => undefined);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** 事件进 Router 上下文(custom message,不进气泡);这一轮跑完才返回。 */
|
|
542
|
+
private async pushEvent(
|
|
543
|
+
assistantId: string,
|
|
544
|
+
text: string,
|
|
545
|
+
details: EventDetails | undefined,
|
|
546
|
+
): Promise<boolean> {
|
|
547
|
+
const state = await this.ensure(assistantId);
|
|
548
|
+
const session = state.session!;
|
|
549
|
+
const message = { customType: EVENT_TYPE, content: `[hob-event] ${text}`, display: false, details };
|
|
550
|
+
this.touch(assistantId);
|
|
551
|
+
state.running += 1;
|
|
552
|
+
this.armStall(state);
|
|
553
|
+
this.publishBusy(state);
|
|
554
|
+
refreshSystemPrompt(session);
|
|
555
|
+
try {
|
|
556
|
+
await this.applyConversationModel(state);
|
|
557
|
+
if (session.isStreaming) {
|
|
558
|
+
await session.sendCustomMessage(message, { deliverAs: "followUp" });
|
|
559
|
+
await session.waitForIdle();
|
|
560
|
+
} else {
|
|
561
|
+
await session.sendCustomMessage(message, { triggerTurn: true });
|
|
562
|
+
await this.reportTurnError(state);
|
|
563
|
+
}
|
|
564
|
+
return true;
|
|
565
|
+
} catch (error) {
|
|
566
|
+
await this.fail(state, error);
|
|
567
|
+
return false;
|
|
568
|
+
} finally {
|
|
569
|
+
state.running = Math.max(0, state.running - 1);
|
|
570
|
+
this.clearStall(state);
|
|
571
|
+
this.publishBusy(state);
|
|
572
|
+
this.maybeRelease(state);
|
|
573
|
+
this.touch(assistantId);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/** 忙闲变了告诉前端(“正在想”要看它)。 */
|
|
578
|
+
private publishBusy(state: RouterState): void {
|
|
579
|
+
const assistant = this.store.assistant(state.assistantId);
|
|
580
|
+
if (assistant) this.bus.emit({ type: "assistant", assistant: this.summary(assistant) });
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* 模型出错(限流、额度、网络)引擎不抛异常,只在最后一条助手消息上记 stopReason=error,重试完就停。
|
|
585
|
+
* 不说一声的话对话里什么都没有,看着像助手不理人:这里补一行灰字。
|
|
586
|
+
*/
|
|
587
|
+
private async reportTurnError(state: RouterState): Promise<void> {
|
|
588
|
+
const last = state.session?.messages.findLast((message) => message.role === "assistant");
|
|
589
|
+
if (!last || last.role !== "assistant" || last.stopReason !== "error") return;
|
|
590
|
+
await this.addItem(state.assistantId, { kind: "note", icon: "info", text: `回复失败:${briefModelError(last.errorMessage)}。发送任意消息即可重试。` });
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
private async fail(state: RouterState, error: unknown): Promise<void> {
|
|
594
|
+
if (state.stalled) return;
|
|
595
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
596
|
+
await this.addItem(state.assistantId, { kind: "note", icon: "info", text: `发生错误:${message}` });
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// ---------- 对话操作 ----------
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* 现在能不能开对话会话:没有服务商 / 没有勾模型时返回一句人话,
|
|
603
|
+
* 让 send 重出一条说明而不是报错崩掉。
|
|
604
|
+
*/
|
|
605
|
+
private async modelGap(assistantId: string): Promise<string | undefined> {
|
|
606
|
+
const assistant = this.store.assistant(assistantId);
|
|
607
|
+
if (!assistant) return NO_MODEL_NOTE;
|
|
608
|
+
let ref: string;
|
|
609
|
+
try {
|
|
610
|
+
ref = conversationPick(this.runtime.settings.settings.models, assistant).ref;
|
|
611
|
+
} catch (error) {
|
|
612
|
+
if (error instanceof NoModelError) return NO_MODEL_NOTE;
|
|
613
|
+
throw error;
|
|
614
|
+
}
|
|
615
|
+
await this.runtime.models.get();
|
|
616
|
+
return this.runtime.models.find(ref) ? undefined : NO_MODEL_NOTE;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* 没有模型时也要把话完整接住:用户那句和一条说明都进对话(不需要模型,只开会话文件)。
|
|
621
|
+
* 配好模型之后再发话就接着聊。
|
|
622
|
+
*/
|
|
623
|
+
private sendWithoutModel(assistantId: string, body: SendMessageBody, note: string): Item {
|
|
624
|
+
const file = this.store.routerFile(assistantId);
|
|
625
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
626
|
+
// 会话文件先建空:引擎看到空文件会马上写头,之后的条目才落盘(不然只存在内存里,刷新就没了)
|
|
627
|
+
if (!existsSync(file)) writeFileSync(file, "");
|
|
628
|
+
const manager = SessionManagerImpl.open(file, dirname(file), this.store.home);
|
|
629
|
+
const data = {
|
|
630
|
+
text: body.text,
|
|
631
|
+
...(body.quote ? { quote: body.quote } : {}),
|
|
632
|
+
...(body.files?.length ? { files: body.files } : {}),
|
|
633
|
+
};
|
|
634
|
+
const id = manager.appendCustomEntry(USER_TYPE, data);
|
|
635
|
+
const item: Item = { kind: "user", id, at: new Date().toISOString(), ...data };
|
|
636
|
+
this.bus.emit({ type: "item", assistantId, item });
|
|
637
|
+
const noteId = manager.appendCustomEntry(ITEM_TYPE, { kind: "note", icon: "info", text: note });
|
|
638
|
+
this.bus.emit({
|
|
639
|
+
type: "item",
|
|
640
|
+
assistantId,
|
|
641
|
+
item: { kind: "note", id: noteId, at: new Date().toISOString(), icon: "info", text: note },
|
|
642
|
+
});
|
|
643
|
+
return item;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
async send(assistantId: string, body: SendMessageBody): Promise<Item> {
|
|
647
|
+
const gap = await this.modelGap(assistantId);
|
|
648
|
+
if (gap) return this.sendWithoutModel(assistantId, body, gap);
|
|
649
|
+
const state = await this.ensure(assistantId);
|
|
650
|
+
const data = {
|
|
651
|
+
text: body.text,
|
|
652
|
+
...(body.quote ? { quote: body.quote } : {}),
|
|
653
|
+
...(body.files?.length ? { files: body.files } : {}),
|
|
654
|
+
};
|
|
655
|
+
const id = state.manager!.appendCustomEntry(USER_TYPE, data);
|
|
656
|
+
const item: Item = {
|
|
657
|
+
kind: "user",
|
|
658
|
+
id,
|
|
659
|
+
at: this.entryAt(state, id),
|
|
660
|
+
text: body.text,
|
|
661
|
+
...(body.quote ? { quote: body.quote } : {}),
|
|
662
|
+
...(body.files?.length ? { files: body.files } : {}),
|
|
663
|
+
};
|
|
664
|
+
this.bus.emit({ type: "item", assistantId, item });
|
|
665
|
+
|
|
666
|
+
const lines = [body.text];
|
|
667
|
+
if (body.quote) lines.unshift(`(引用我之前的话:「${body.quote.text}」)`);
|
|
668
|
+
if (body.files?.length) lines.push(`附件:${body.files.join("、")}`);
|
|
669
|
+
const promptText = lines.join("\n");
|
|
670
|
+
|
|
671
|
+
this.touch(assistantId);
|
|
672
|
+
state.running += 1;
|
|
673
|
+
this.armStall(state);
|
|
674
|
+
this.publishBusy(state);
|
|
675
|
+
void (async () => {
|
|
676
|
+
try {
|
|
677
|
+
await this.applyConversationModel(state);
|
|
678
|
+
refreshSystemPrompt(state.session!);
|
|
679
|
+
if (state.session!.isStreaming) await state.session!.steer(promptText);
|
|
680
|
+
else {
|
|
681
|
+
await state.session!.prompt(promptText);
|
|
682
|
+
await this.reportTurnError(state);
|
|
683
|
+
}
|
|
684
|
+
} catch (error) {
|
|
685
|
+
await this.fail(state, error);
|
|
686
|
+
} finally {
|
|
687
|
+
state.running = Math.max(0, state.running - 1);
|
|
688
|
+
this.clearStall(state);
|
|
689
|
+
this.publishBusy(state);
|
|
690
|
+
this.maybeRelease(state);
|
|
691
|
+
this.touch(assistantId);
|
|
692
|
+
}
|
|
693
|
+
})();
|
|
694
|
+
return item;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
async stop(assistantId: string): Promise<void> {
|
|
698
|
+
const state = this.routers.get(assistantId);
|
|
699
|
+
if (state?.session) await state.session.abort();
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
isBusy(assistantId: string): boolean {
|
|
703
|
+
const state = this.routers.get(assistantId);
|
|
704
|
+
// 只看助手自己在不在回复:任务不阻塞对话,任务的进度在任务卡上,不再算进来(不然任务跑多久「…」就挂多久)
|
|
705
|
+
return (state?.running ?? 0) > 0 || (state?.session?.isStreaming ?? false);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** 等到这个助手没有在跑的回复,并且会话条目已经落定(测试和冒烟用)。 */
|
|
709
|
+
async waitIdle(assistantId: string, timeoutMs = 15_000): Promise<void> {
|
|
710
|
+
const started = Date.now();
|
|
711
|
+
let stable = 0;
|
|
712
|
+
let lastCount = -1;
|
|
713
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
714
|
+
while (Date.now() - started < timeoutMs) {
|
|
715
|
+
const state = this.routers.get(assistantId);
|
|
716
|
+
const busy = (state?.running ?? 0) > 0 || (state?.session?.isStreaming ?? false);
|
|
717
|
+
const count = state?.manager?.getEntryCount() ?? -1;
|
|
718
|
+
if (!busy) {
|
|
719
|
+
stable = count === lastCount ? stable + 1 : 0;
|
|
720
|
+
if (stable >= 2) return;
|
|
721
|
+
} else {
|
|
722
|
+
stable = 0;
|
|
723
|
+
}
|
|
724
|
+
lastCount = count;
|
|
725
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
items(assistantId: string, options: { before?: string; limit?: number } = {}): ItemsPage {
|
|
730
|
+
const all = deriveItems(this.entries(assistantId));
|
|
731
|
+
const limit = Math.max(1, Math.min(options.limit ?? 50, 200));
|
|
732
|
+
let list = all;
|
|
733
|
+
if (options.before) {
|
|
734
|
+
const index = all.findIndex((item) => item.id === options.before);
|
|
735
|
+
if (index !== -1) list = all.slice(0, index);
|
|
736
|
+
}
|
|
737
|
+
const page = list.slice(-limit);
|
|
738
|
+
const jobIds = new Set(page.filter((item) => item.kind === "job").map((item) => (item as { jobId: string }).jobId));
|
|
739
|
+
const draftIds = new Set(
|
|
740
|
+
page.filter((item) => item.kind === "draft").map((item) => (item as { draftId: string }).draftId),
|
|
741
|
+
);
|
|
742
|
+
const approvalIds = new Set(
|
|
743
|
+
page.filter((item) => item.kind === "question").map((item) => (item as { approvalId: string }).approvalId),
|
|
744
|
+
);
|
|
745
|
+
const ids = new Set(page.filter((item) => item.kind === "delegation").map((item) => (item as { delegationId: string }).delegationId));
|
|
746
|
+
const delegations = this.store.delegations().filter((item) => ids.has(item.id));
|
|
747
|
+
for (const delegation of delegations) {
|
|
748
|
+
for (const id of delegation.jobIds) jobIds.add(id);
|
|
749
|
+
for (const id of delegation.approvalIds ?? []) approvalIds.add(id);
|
|
750
|
+
}
|
|
751
|
+
for (const approval of this.store.approvals()) if (approval.jobId && jobIds.has(approval.jobId)) approvalIds.add(approval.id);
|
|
752
|
+
return {
|
|
753
|
+
...(!options.before ? { pageLive: [...(this.livePages.get(assistantId)?.values() ?? [])].map((live) => live.page) } : {}),
|
|
754
|
+
items: page,
|
|
755
|
+
approvals: this.store.approvals().filter((approval) => approvalIds.has(approval.id)),
|
|
756
|
+
jobs: this.store.jobs().filter((job) => jobIds.has(job.id)),
|
|
757
|
+
drafts: this.store.drafts().filter((draft) => draftIds.has(draft.id)),
|
|
758
|
+
delegations,
|
|
759
|
+
hasMore: list.length > page.length,
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
read(assistantId: string): void {
|
|
764
|
+
this.store.saveState(assistantId, { readAt: new Date().toISOString() });
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
unread(assistantId: string): number {
|
|
768
|
+
const readAt = this.store.state(assistantId).readAt;
|
|
769
|
+
if (!readAt) return 0;
|
|
770
|
+
return deriveItems(this.entries(assistantId)).filter(
|
|
771
|
+
(item) => item.kind === "assistant" && item.at > readAt,
|
|
772
|
+
).length;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
last(assistantId: string): { text: string; at: Iso } | undefined {
|
|
776
|
+
const items = deriveItems(this.entries(assistantId));
|
|
777
|
+
for (let i = items.length - 1; i >= 0; i -= 1) {
|
|
778
|
+
const item = items[i];
|
|
779
|
+
if (item.kind === "user" || item.kind === "assistant" || item.kind === "note") {
|
|
780
|
+
return { text: item.text, at: item.at };
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
return undefined;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
summary(assistant: Assistant): AssistantSummary {
|
|
787
|
+
const last = this.last(assistant.id);
|
|
788
|
+
return {
|
|
789
|
+
...assistant,
|
|
790
|
+
...(last ? { last } : {}),
|
|
791
|
+
unread: this.unread(assistant.id),
|
|
792
|
+
busy: this.isBusy(assistant.id),
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
profile(assistantId: string): Profile {
|
|
797
|
+
const assistant = this.assistant(assistantId);
|
|
798
|
+
return {
|
|
799
|
+
assistant: this.summary(assistant),
|
|
800
|
+
rules: this.store.rules(assistantId),
|
|
801
|
+
routines: this.store.routines().filter((routine) => routine.assistantId === assistantId),
|
|
802
|
+
worklog: this.store.worklog(assistantId),
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
bootstrap(): Bootstrap {
|
|
807
|
+
const jobCutoff = new Date(Date.now() - 24 * 3600 * 1000).toISOString();
|
|
808
|
+
return {
|
|
809
|
+
assistants: this.store.assistants().map((assistant) => this.summary(assistant)),
|
|
810
|
+
jobs: this.store
|
|
811
|
+
.jobs()
|
|
812
|
+
.filter((job) => job.status === "running" || job.status === "queued" || job.status === "waiting" || (job.endedAt ?? job.createdAt) > jobCutoff),
|
|
813
|
+
routines: this.store.routines(),
|
|
814
|
+
approvals: this.store.approvals().filter((approval) => approval.status === "pending"),
|
|
815
|
+
delegations: this.store.delegations(),
|
|
816
|
+
settings: this.runtime.settings.get(),
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/** 进程退出或测试收尾:释放所有 Router 会话。 */
|
|
821
|
+
disposeAll(): void {
|
|
822
|
+
for (const state of this.routers.values()) {
|
|
823
|
+
if (state.idleTimer) clearTimeout(state.idleTimer);
|
|
824
|
+
state.session?.dispose();
|
|
825
|
+
}
|
|
826
|
+
this.routers.clear();
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/** 直接走事件的 followUp 队列,实际收到这条消息时才开始关联任务。 */
|
|
830
|
+
async relay(targetAssistantId: string, text: string, delegationId: string): Promise<void> {
|
|
831
|
+
const success = await this.pushEvent(targetAssistantId, `转自 Hob:${text}`, { delegationId });
|
|
832
|
+
if (!success || !this.store.delegation(delegationId)?.turnFinished) {
|
|
833
|
+
this.runtime.delegations.turnEnded(delegationId, "目标助手处理失败或转交被中断", true);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/** 审批答案回到 Router(router 来源的审批,答案作为事件进入上下文)。 */
|
|
838
|
+
async answerEvent(assistantId: string, text: string): Promise<void> {
|
|
839
|
+
await this.event(assistantId, text);
|
|
840
|
+
}
|
|
841
|
+
}
|