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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +111 -2
  3. package/README.zh-CN.md +112 -0
  4. package/bin/hob.mjs +7 -0
  5. package/dist/web/assets/index-D88l35PH.css +1 -0
  6. package/dist/web/assets/index-DUs8nN3E.js +218 -0
  7. package/dist/web/favicon.ico +0 -0
  8. package/dist/web/fonts/inter-latin.woff2 +0 -0
  9. package/dist/web/fonts/jetbrains-mono-latin.woff2 +0 -0
  10. package/dist/web/icons/apple-touch-icon-180.png +0 -0
  11. package/dist/web/icons/favicon-32.png +0 -0
  12. package/dist/web/icons/icon-192.png +0 -0
  13. package/dist/web/icons/icon-512.png +0 -0
  14. package/dist/web/icons/icon-maskable-512.png +0 -0
  15. package/dist/web/index.html +32 -0
  16. package/dist/web/manifest.webmanifest +16 -0
  17. package/dist/web/sw.js +131 -0
  18. package/package.json +62 -4
  19. package/server/src/actions.ts +230 -0
  20. package/server/src/boot.ts +85 -0
  21. package/server/src/bus.ts +21 -0
  22. package/server/src/config.ts +123 -0
  23. package/server/src/cron-text.ts +49 -0
  24. package/server/src/delegations.ts +113 -0
  25. package/server/src/files.ts +142 -0
  26. package/server/src/http.ts +802 -0
  27. package/server/src/ids.ts +19 -0
  28. package/server/src/image.ts +218 -0
  29. package/server/src/imports.ts +302 -0
  30. package/server/src/jobs.ts +730 -0
  31. package/server/src/main.ts +69 -0
  32. package/server/src/memory.ts +272 -0
  33. package/server/src/models.ts +358 -0
  34. package/server/src/overview.ts +116 -0
  35. package/server/src/pages.ts +54 -0
  36. package/server/src/password.ts +23 -0
  37. package/server/src/pi.ts +273 -0
  38. package/server/src/prompt.ts +227 -0
  39. package/server/src/providers.ts +532 -0
  40. package/server/src/push.ts +285 -0
  41. package/server/src/router-tools.ts +549 -0
  42. package/server/src/router.ts +841 -0
  43. package/server/src/routines.ts +129 -0
  44. package/server/src/runtime.ts +104 -0
  45. package/server/src/search.ts +91 -0
  46. package/server/src/secrets.ts +46 -0
  47. package/server/src/settings.ts +452 -0
  48. package/server/src/skills.ts +150 -0
  49. package/server/src/store.ts +324 -0
  50. package/server/src/text.ts +14 -0
  51. package/server/src/time.ts +42 -0
  52. package/server/src/transcript.ts +272 -0
  53. package/server/src/worker-tools.ts +129 -0
  54. package/shared/command.ts +42 -0
  55. package/shared/files.ts +141 -0
  56. package/shared/media.ts +17 -0
  57. package/shared/model-note.ts +32 -0
  58. package/shared/page-shell.ts +108 -0
  59. package/shared/search.ts +19 -0
  60. package/shared/skills.ts +37 -0
  61. package/shared/sprites.ts +422 -0
  62. package/shared/thinking.ts +118 -0
  63. package/shared/types.ts +631 -0
  64. package/vendor/lore-pi-extension/README.md +28 -0
  65. package/vendor/lore-pi-extension/api.ts +140 -0
  66. package/vendor/lore-pi-extension/formatters.ts +204 -0
  67. package/vendor/lore-pi-extension/hooks.ts +195 -0
  68. package/vendor/lore-pi-extension/index.ts +25 -0
  69. package/vendor/lore-pi-extension/package.json +23 -0
  70. package/vendor/lore-pi-extension/skills.ts +447 -0
  71. package/vendor/lore-pi-extension/tools.ts +344 -0
  72. package/vendor/lore-pi-extension/uri.ts +67 -0
  73. package/vendor/lore-pi-extension/vendor/skill-workcopy/index.d.mts +266 -0
  74. package/vendor/lore-pi-extension/vendor/skill-workcopy/index.mjs +1328 -0
  75. package/vendor/lore-pi-extension/vendor/skill-workcopy/skills-sync.d.mts +33 -0
  76. package/vendor/lore-pi-extension/vendor/skill-workcopy/skills-sync.mjs +202 -0
@@ -0,0 +1,549 @@
1
+ import { Type } from "@earendil-works/pi-ai";
2
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
4
+ import { basename } from "node:path";
5
+ import {
6
+ COLORS,
7
+ COLOR_IDS,
8
+ customSprite,
9
+ distinctSprite,
10
+ parseSprite,
11
+ PROP_IDS,
12
+ PROPS,
13
+ spriteId,
14
+ validateCustomProp,
15
+ } from "../../shared/sprites.ts";
16
+ import type { ColorId } from "../../shared/sprites.ts";
17
+ import type { Approval, ApprovalOption, CustomProp, Draft, Routine } from "../../shared/types.ts";
18
+ import { cronToChinese } from "./cron-text.ts";
19
+ import { newId } from "./ids.ts";
20
+ import { defaultWorkRef, jobModel, noteOf, thinkingLevelsOf, usableRefs } from "./models.ts";
21
+ import { overviewTool } from "./overview.ts";
22
+ import { pageTool } from "./pages.ts";
23
+ import { pushApproval } from "./push.ts";
24
+ import { searchTools } from "./search.ts";
25
+ import type { HobRuntime } from "./runtime.ts";
26
+ import { clampDuty } from "./text.ts";
27
+
28
+ type Tool = ToolDefinition<any, any>;
29
+
30
+ function ok(text: string) {
31
+ return { content: [{ type: "text" as const, text }], details: undefined };
32
+ }
33
+
34
+ /**
35
+ * 出了卡片就结束本轮:pi 的 terminate 让这一批工具结果之后不再请求模型,
36
+ * 用户不会再看到卡片后面补的一句废话。
37
+ */
38
+ function endTurn(text: string) {
39
+ return { content: [{ type: "text" as const, text }], details: undefined, terminate: true };
40
+ }
41
+
42
+ function fail(text: string) {
43
+ return { content: [{ type: "text" as const, text }], details: undefined, isError: true };
44
+ }
45
+
46
+ function fileMeta(path: string): string | undefined {
47
+ try {
48
+ if (!statSync(path).isFile()) return undefined;
49
+ if (!/\.(md|txt)$/i.test(path)) return undefined;
50
+ const text = readFileSync(path, "utf8");
51
+ const chars = text.replace(/\s/g, "").length;
52
+ const images = path.toLowerCase().endsWith(".md") ? (text.match(/!\[[^\]]*\]\([^)]*\)/g)?.length ?? 0) : 0;
53
+ return `${chars} 字${images ? ` · ${images} 张图` : ""}`;
54
+ } catch {
55
+ return undefined;
56
+ }
57
+ }
58
+
59
+ /** 一个助手的 Router 能用的全部工具。改状态的工具都写卡片 + 发事件。 */
60
+ export function buildRouterTools(runtime: HobRuntime, assistantId: string): Tool[] {
61
+ const { store, bus, router, jobs, routines } = runtime;
62
+ const assistant = () => {
63
+ const found = store.assistant(assistantId);
64
+ if (!found) throw new Error(`助手不存在:${assistantId}`);
65
+ return found;
66
+ };
67
+ const note = (icon: "memory" | "rule" | "routine" | "split" | "info", text: string) =>
68
+ router.addItem(assistantId, { kind: "note", icon, text });
69
+ const profileChanged = () => bus.emit({ type: "profile", assistantId });
70
+
71
+ // 能派的模型:写进 start_job 的参数说明,助手知道有哪些可选、哪个是默认
72
+ const modelSettings = runtime.settings.settings.models;
73
+ const usable = usableRefs(modelSettings, assistant(), runtime.models);
74
+ const defaultModel = defaultWorkRef(modelSettings, assistant(), runtime.models);
75
+ const modelList = usable.map((ref) => {
76
+ const entry = modelSettings.roster.find((item) => item.ref === ref);
77
+ const note = entry ? noteOf(entry, runtime.models) : "";
78
+ const levels = modelSettings.thinkingChoice === "fixed"
79
+ ? jobModel({ settings: modelSettings, assistant: assistant(), catalog: runtime.models, requested: { model: ref } }).model.thinking
80
+ : thinkingLevelsOf(runtime.models.find(ref)).join("、");
81
+ return `${ref}${ref === defaultModel ? "(默认)" : ""}${note ? ` · ${note}` : ""} · 思考档 ${levels}`;
82
+ });
83
+ const modelText = modelList.length ? modelList.join("\n") : "(现在没有可用的模型)";
84
+
85
+ const tools: Tool[] = [
86
+ {
87
+ name: "start_job",
88
+ label: "创建任务",
89
+ description:
90
+ "把需要动手的任务交给后台任务执行:读写文件、运行命令、修改内容都只能通过这个工具完成。立即返回任务 id,完成后会有一条事件回到对话。调用后这一轮就结束了:工具返回后不要再输出任何文字。" +
91
+ (modelList.length > 1
92
+ ? `可按任务难度和类型指定模型:${modelText};不确定就不填,使用默认值。`
93
+ : `模型用 ${modelText},不用指定。`),
94
+ promptSnippet: "把需要执行的任务交给后台任务。",
95
+ parameters: Type.Object({
96
+ title: Type.String({ description: "任务标题,短,如「查磁盘占用」" }),
97
+ instruction: Type.String({ description: "要做什么,写清楚目标和验收标准" }),
98
+ cwd: Type.Optional(
99
+ Type.String({
100
+ description:
101
+ "任务的工作目录;不给就用任务自己的工作目录。写代码、改项目这类任务传项目目录。",
102
+ }),
103
+ ),
104
+ files: Type.Optional(
105
+ Type.Array(Type.String(), {
106
+ description: "要交给任务的文件路径(用户发来的附件);图片会直接给模型看",
107
+ }),
108
+ ),
109
+ model: Type.Optional(Type.String({ description: `可选:${modelText}。不填就用默认。` })),
110
+ thinking: Type.Optional(
111
+ Type.String({ description: modelSettings.thinkingChoice === "fixed" ? "当前设置为固定思考档,此参数会被忽略,不要填。" : "可选:思考档以可分派模型列表里每个模型标的为准。不填用模型的默认思考档。" }),
112
+ ),
113
+ }),
114
+ execute: async (_id, params: any) => {
115
+ try {
116
+ const job = await jobs.start(assistantId, {
117
+ title: String(params.title),
118
+ instruction: String(params.instruction),
119
+ ...(params.cwd ? { cwd: String(params.cwd) } : {}),
120
+ ...(Array.isArray(params.files) && params.files.length ? { files: params.files.map(String) } : {}),
121
+ ...(params.model ? { model: String(params.model) } : {}),
122
+ ...(params.thinking ? { thinking: String(params.thinking) } : {}),
123
+ ...(router.currentDelegation(assistantId) ? { delegationId: router.currentDelegation(assistantId) } : {}),
124
+ });
125
+ if (job.status === "failed") return fail(`任务启动失败:${job.statusReason ?? "原因不明"}`);
126
+ return endTurn(
127
+ `任务「${job.title}」(${job.id})已启动,完成后会报告结果。任务卡已显示给用户。本轮到此结束:不要输出任何文字,不要再提这张卡。`,
128
+ );
129
+ } catch (error) {
130
+ return fail(error instanceof Error ? error.message : String(error));
131
+ }
132
+ },
133
+ },
134
+ {
135
+ name: "reply_job",
136
+ label: "补充任务说明",
137
+ description: "给正在运行的任务补充说明或纠正方向。",
138
+ parameters: Type.Object({
139
+ jobId: Type.String({ description: "任务 id" }),
140
+ text: Type.String({ description: "要补充的话" }),
141
+ }),
142
+ execute: async (_id, params: any) => {
143
+ try {
144
+ await jobs.reply(String(params.jobId), String(params.text));
145
+ return ok("已转交任务。");
146
+ } catch (error) {
147
+ return fail(error instanceof Error ? error.message : String(error));
148
+ }
149
+ },
150
+ },
151
+ {
152
+ name: "stop_job",
153
+ label: "停止任务",
154
+ description: "停止一个正在运行的任务。",
155
+ parameters: Type.Object({ jobId: Type.String({ description: "任务 id" }) }),
156
+ execute: async (_id, params: any) => {
157
+ try {
158
+ await jobs.stop(String(params.jobId));
159
+ return ok("已停止。");
160
+ } catch (error) {
161
+ return fail(error instanceof Error ? error.message : String(error));
162
+ }
163
+ },
164
+ },
165
+ {
166
+ name: "ask_user",
167
+ label: "询问用户",
168
+ description:
169
+ "在对话里出选择题卡片让用户确认(最多 3 个选项)。用于规则要求执行前确认、或者操作不可逆的时候。选完答案会作为事件回到对话。调用后这一轮就结束了:工具返回后不要再输出任何文字。",
170
+ parameters: Type.Object({
171
+ title: Type.String({ description: "问题,一句话" }),
172
+ detail: Type.Optional(Type.String({ description: "补充说明,写清后果" })),
173
+ options: Type.Array(
174
+ Type.Object({
175
+ label: Type.String({ description: "选项文字,如「暂不发布」" }),
176
+ always: Type.Optional(Type.Boolean({ description: "选中后将这句话记为规则" })),
177
+ }),
178
+ { description: "2 到 3 个选项", minItems: 2, maxItems: 3 },
179
+ ),
180
+ ruleText: Type.Optional(Type.String({ description: "always 选项要写进规则的文字,如「发布公众号」" })),
181
+ }),
182
+ execute: async (_id, params: any) => {
183
+ const labels: { label: string; always?: boolean }[] = Array.isArray(params.options) ? params.options : [];
184
+ if (labels.length < 2 || labels.length > 3) return fail("选项要 2 到 3 个。");
185
+ const options: ApprovalOption[] = labels.map((option, index) => ({
186
+ key: (["A", "B", "C"] as const)[index],
187
+ label: String(option.label),
188
+ ...(option.always ? { always: true } : {}),
189
+ }));
190
+ const approval: Approval = {
191
+ id: newId("q-"),
192
+ assistantId,
193
+ title: String(params.title),
194
+ ...(params.detail ? { detail: String(params.detail) } : {}),
195
+ options,
196
+ status: "pending",
197
+ source: "router",
198
+ ...(params.ruleText ? { ruleText: String(params.ruleText) } : {}),
199
+ createdAt: new Date().toISOString(),
200
+ };
201
+ store.saveApproval(approval);
202
+ const delegationId = router.currentDelegation(assistantId);
203
+ if (delegationId) runtime.delegations.addApproval(delegationId, approval.id);
204
+ await router.addItem(assistantId, { kind: "question", approvalId: approval.id });
205
+ bus.emit({ type: "approval", approval });
206
+ pushApproval({ push: runtime.push, store }, approval);
207
+ return endTurn("问题卡已显示给用户,等用户选。本轮到此结束:不要输出任何文字。");
208
+ },
209
+ },
210
+ {
211
+ name: "set_rule",
212
+ label: "记录规则",
213
+ description: "记录一条规则。mode=ask 表示执行前需要确认,mode=allow 表示直接执行。",
214
+ parameters: Type.Object({
215
+ text: Type.String({ description: "规则内容,如「发布公众号」" }),
216
+ mode: Type.Unsafe<"ask" | "allow">(Type.String({ description: "ask 或 allow" })),
217
+ }),
218
+ execute: async (_id, params: any) => {
219
+ const text = String(params.text).trim();
220
+ if (!text) return fail("规则内容为空。");
221
+ const mode = params.mode === "allow" ? "allow" : "ask";
222
+ const rules = store.rules(assistantId);
223
+ const existing = rules.find((rule) => rule.text === text);
224
+ // 答 always 审批时规则已经写好了(Actions 那行提示也已经出过),这里没改动就不重复出:
225
+ // 模型看到答案之后常会把同一句再记一遍,重复的提示行对用户没有信息量。
226
+ if (existing?.mode === mode) return ok("这条规则已经记着了,没有改动。");
227
+ if (existing) {
228
+ existing.mode = mode;
229
+ existing.changedAt = new Date().toISOString();
230
+ } else {
231
+ rules.push({ id: newId("r-"), text, mode, changedAt: new Date().toISOString() });
232
+ }
233
+ store.saveRules(assistantId, rules);
234
+ await note("rule", `已记入${assistant().name}的规则 · ${text}`);
235
+ profileChanged();
236
+ return ok("已记录规则。");
237
+ },
238
+ },
239
+ {
240
+ name: "remove_rule",
241
+ label: "删除规则",
242
+ description: "删除一条规则。",
243
+ parameters: Type.Object({ ruleId: Type.String({ description: "规则 id" }) }),
244
+ execute: async (_id, params: any) => {
245
+ const rules = store.rules(assistantId);
246
+ const kept = rules.filter((rule) => rule.id !== params.ruleId);
247
+ if (kept.length === rules.length) return fail("没有这条规则。");
248
+ store.saveRules(assistantId, kept);
249
+ await note("rule", "删除了一条规则");
250
+ profileChanged();
251
+ return ok("已删除。");
252
+ },
253
+ },
254
+ {
255
+ name: "create_routine",
256
+ label: "新增定时任务",
257
+ description: "新增一个定时任务。schedule 用 cron 表达式,如「0 9 * * *」每天 9 点;多个执行时间就传多个。",
258
+ parameters: Type.Object({
259
+ name: Type.String({ description: "定时任务名称,如「每日简报」" }),
260
+ instruction: Type.String({ description: "到点要执行的内容" }),
261
+ schedules: Type.Array(Type.String({ description: "cron 表达式" }), { description: "一个或多个" }),
262
+ }),
263
+ execute: async (_id, params: any) => {
264
+ try {
265
+ const routine = routines.create({
266
+ assistantId,
267
+ name: String(params.name),
268
+ instruction: String(params.instruction),
269
+ schedules: (params.schedules as string[]) ?? [],
270
+ });
271
+ await note("routine", `新增定时任务 · ${routine.name} · ${routine.schedules.map(cronToChinese).join("、")}`);
272
+ profileChanged();
273
+ return ok(`定时任务「${routine.name}」已创建。`);
274
+ } catch (error) {
275
+ return fail(error instanceof Error ? error.message : String(error));
276
+ }
277
+ },
278
+ },
279
+ {
280
+ name: "update_routine",
281
+ label: "修改定时任务",
282
+ description: "修改一个定时任务:名称、内容、执行时间(schedules 会整体替换)、启用状态。",
283
+ parameters: Type.Object({
284
+ routineId: Type.String(),
285
+ name: Type.Optional(Type.String()),
286
+ instruction: Type.Optional(Type.String()),
287
+ schedules: Type.Optional(Type.Array(Type.String())),
288
+ active: Type.Optional(Type.Boolean()),
289
+ }),
290
+ execute: async (_id, params: any) => {
291
+ try {
292
+ const routine = routines.update(String(params.routineId), {
293
+ ...(params.name ? { name: String(params.name) } : {}),
294
+ ...(params.instruction ? { instruction: String(params.instruction) } : {}),
295
+ ...(params.schedules ? { schedules: params.schedules as string[] } : {}),
296
+ ...(typeof params.active === "boolean" ? { active: params.active } : {}),
297
+ });
298
+ await note("routine", `修改定时任务 · ${routine.name} · ${routine.schedules.map(cronToChinese).join("、")}`);
299
+ profileChanged();
300
+ return ok("已修改。");
301
+ } catch (error) {
302
+ return fail(error instanceof Error ? error.message : String(error));
303
+ }
304
+ },
305
+ },
306
+ {
307
+ name: "delete_routine",
308
+ label: "删除定时任务",
309
+ description: "删除一个定时任务。",
310
+ parameters: Type.Object({ routineId: Type.String() }),
311
+ execute: async (_id, params: any) => {
312
+ try {
313
+ routines.remove(String(params.routineId));
314
+ await note("routine", "删除了一条定时任务");
315
+ profileChanged();
316
+ return ok("已删除。");
317
+ } catch (error) {
318
+ return fail(error instanceof Error ? error.message : String(error));
319
+ }
320
+ },
321
+ },
322
+ {
323
+ name: "send_file",
324
+ label: "发送文件",
325
+ description: "把任务产出的文件作为文件卡片发送到对话里。",
326
+ parameters: Type.Object({ path: Type.String({ description: "文件的绝对路径" }) }),
327
+ execute: async (_id, params: any) => {
328
+ const path = String(params.path);
329
+ if (!existsSync(path)) return fail(`文件不存在:${path}`);
330
+ const meta = fileMeta(path);
331
+ await router.addItem(assistantId, { kind: "file", path, name: basename(path), ...(meta ? { meta } : {}) });
332
+ return ok("已发送。");
333
+ },
334
+ },
335
+ {
336
+ name: "set_avatar",
337
+ label: "换头像",
338
+ description: "给自己换头像:换内置道具、换颜色,或用 prop_art 自画一件像素道具。主助手还可以传 assistant 给其他助手换。",
339
+ parameters: Type.Object({
340
+ sprite: Type.String({
341
+ description: `内置道具 id 之一(${PROP_IDS.filter((id) => id !== "hob").join(" ")}),或 custom(自画的,同时填 prop_art;已画过时不填 prop_art 就是换回那件)`,
342
+ }),
343
+ color: Type.Optional(
344
+ Type.String({ description: `可选:火苗颜色,${COLOR_IDS.join(" ")} 之一;不填用道具的默认色` }),
345
+ ),
346
+ prop_art: Type.Optional(
347
+ Type.Object({
348
+ art: Type.Array(Type.String(), {
349
+ description: "最多 16 行,每行恰好 16 个字符;从第 0 行起逐行盖在火苗上,. 表示不动,k 是描边色,其它字符查 pal;不能盖住火苗的两只眼睛",
350
+ }),
351
+ pal: Type.Record(Type.String(), Type.String(), {
352
+ description: "单个小写字母 → #rrggbb;不能用 o y e(火苗自己的色)和 k(描边固定),最多 6 种",
353
+ }),
354
+ dx: Type.Union([Type.Literal(0), Type.Literal(1), Type.Literal(2)], {
355
+ description: "火苗的横向位置:头顶的道具用 2,手边的用 0 或 1",
356
+ }),
357
+ }, {
358
+ description:
359
+ 'sprite 为 custom 时要画的那件。例:{ "art": ["....kkkk........", "...khhhhk.......", "....kkkk........"], "pal": { "h": "#ffc21a" }, "dx": 2 }',
360
+ }),
361
+ ),
362
+ assistant: Type.Optional(Type.String({ description: "仅主助手:要换头像的助手 id;不填是自己" })),
363
+ }),
364
+ execute: async (_id, params: any) => {
365
+ const target = store.assistant(String(params.assistant ?? assistantId));
366
+ if (!target) return fail(`没有这个助手:${params.assistant}`);
367
+ if (target.id !== assistantId && !assistant().primary) return fail("只有主助手能给其他助手换头像。");
368
+ const parsed = parseSprite(String(params.sprite ?? ""));
369
+ if (!parsed) {
370
+ return fail(
371
+ `sprite 要是内置道具 id 之一(${PROP_IDS.filter((id) => id !== "hob").join(" ")})或 custom,收到「${params.sprite}」。`,
372
+ );
373
+ }
374
+ const color = typeof params.color === "string" ? params.color : undefined;
375
+ if (color !== undefined && !Object.hasOwn(COLORS, color)) {
376
+ return fail(`color 要是 ${COLOR_IDS.join(" ")} 之一,收到「${color}」。`);
377
+ }
378
+ let sprite: string;
379
+ let prop: CustomProp | undefined;
380
+ if (parsed.prop === "custom") {
381
+ if (params.prop_art !== undefined) {
382
+ const checked = validateCustomProp(params.prop_art);
383
+ if (!checked.ok) return fail(`prop_art 画得不对:${checked.error};照着原因改好,再调用一次。`);
384
+ prop = checked.prop;
385
+ } else if (!target.prop) {
386
+ return fail("sprite 是 custom 但还没有画过的道具:要给 prop_art(art、pal、dx)画一件。");
387
+ }
388
+ sprite = customSprite((color ?? parsed.color) as ColorId);
389
+ } else {
390
+ if (params.prop_art !== undefined) return fail("sprite 是内置道具时不要传 prop_art;要自画一件就把 sprite 填 custom。");
391
+ sprite = spriteId(parsed.prop, (color ?? parsed.color) as ColorId);
392
+ }
393
+ const next = { ...target, sprite, ...(prop ? { prop } : {}) };
394
+ store.saveAssistant(next);
395
+ bus.emit({ type: "assistant", assistant: runtime.router.summary(next) });
396
+ const desc =
397
+ parsed.prop === "custom"
398
+ ? `自画道具 · ${COLORS[(color ?? parsed.color) as ColorId].name}`
399
+ : `${PROPS[parsed.prop].label} · ${COLORS[(color ?? parsed.color) as ColorId].name}`;
400
+ await note("info", `已换头像 · ${target.name} · ${desc}`);
401
+ return ok(`已换头像。`);
402
+ },
403
+ },
404
+ ];
405
+
406
+ if (runtime.settings.settings.general.showPage !== false) tools.push(pageTool(runtime, assistantId, true));
407
+
408
+ if (assistant().primary) {
409
+ tools.push(
410
+ overviewTool(runtime),
411
+ {
412
+ name: "propose_assistant",
413
+ label: "提议创建专属助手",
414
+ description:
415
+ "提议创建一个专属助手。会生成一张草稿卡,用户点「创建」后才会真正创建。用于同类任务反复出现时。调用后这一轮就结束了:工具返回后不要再输出任何文字。",
416
+ parameters: Type.Object({
417
+ name: Type.String({ description: "助手名字:职责加一个亲切的昵称,四五个字,如「运维小子」「写稿搭子」「代理管家」;不要只写「代理」「运维」这种光秃秃的词" }),
418
+ duty: Type.String({ description: "左栏头像下面那行小字,最多 8 个字,如「线上和机器」「模型和 agent」" }),
419
+ dutyLong: Type.String({ description: "草稿卡里的职责说明,两三句话,写完整一些" }),
420
+ sprite: Type.String({
421
+ description: `头像:内置道具 id 之一(${PROP_IDS.filter((id) => id !== "hob").join(" ")}),或 custom(同时填 prop_art,自己画一件)`,
422
+ }),
423
+ prop_art: Type.Optional(
424
+ Type.Object(
425
+ {
426
+ art: Type.Array(Type.String(), {
427
+ description: "最多 16 行,每行恰好 16 个字符;从第 0 行起逐行盖在火苗上,. 表示不动,k 是描边色,其它字符查 pal;不能盖住火苗的两只眼睛",
428
+ }),
429
+ pal: Type.Record(Type.String(), Type.String(), {
430
+ description: "单个小写字母 → #rrggbb;不能用 o y e(火苗自己的色)和 k(描边固定),最多 6 种",
431
+ }),
432
+ dx: Type.Union([Type.Literal(0), Type.Literal(1), Type.Literal(2)], {
433
+ description: "火苗的横向位置:头顶的道具用 2,手边的用 0 或 1",
434
+ }),
435
+ },
436
+ {
437
+ description:
438
+ 'sprite 为 custom 时要画的那件。例:{ "art": ["....kkkk........", "...khhhhk.......", "....kkkk........"], "pal": { "h": "#ffc21a" }, "dx": 2 }',
439
+ },
440
+ ),
441
+ ),
442
+ routines: Type.Optional(
443
+ Type.Array(
444
+ Type.Object({ name: Type.String(), instruction: Type.String(), schedule: Type.String() }),
445
+ { description: "建议包含的定时任务" },
446
+ ),
447
+ ),
448
+ askFirst: Type.Optional(Type.Array(Type.String(), { description: "执行前需确认的事项" })),
449
+ instructions: Type.Optional(
450
+ Type.Array(Type.String(), { description: "这个助手特有的做法(每项一行,写进新助手的补充说明)" }),
451
+ ),
452
+ conversations: Type.Optional(Type.Integer({ description: "需要迁移的对话段数,默认 0" })),
453
+ }),
454
+ execute: async (_id, params: any) => {
455
+ const checked = params.prop_art !== undefined ? validateCustomProp(params.prop_art) : undefined;
456
+ if (checked && !checked.ok) return fail(`prop_art 画得不对:${checked.error};照着原因改好,再调用一次。`);
457
+ const given = parseSprite(String(params.sprite ?? ""));
458
+ if (checked?.ok && given && given.prop !== "custom") {
459
+ return fail("sprite 填了内置道具就不要传 prop_art;要自画一件就把 sprite 填 custom。");
460
+ }
461
+ if (given?.prop === "custom" && !checked?.ok) {
462
+ return fail("sprite 是 custom 时要同时给 prop_art(art、pal、dx)画一件。");
463
+ }
464
+ const routinesInput: { name: string; instruction: string; schedule: string }[] =
465
+ params.routines ?? [];
466
+ const taken = store.assistants().map((a) => a.sprite);
467
+ // 自画的存画法(sprite 记成 custom);内置道具的照旧,和已有助手撞了就换个颜色
468
+ const sprite = checked?.ok ? distinctSprite("custom", taken) : given ? distinctSprite(String(params.sprite), taken) : "page";
469
+ const prop = checked?.ok ? checked.prop : undefined;
470
+ const draft: Draft = {
471
+ id: newId("d-"),
472
+ assistantId,
473
+ status: "pending",
474
+ name: String(params.name),
475
+ sprite,
476
+ ...(prop ? { prop } : {}),
477
+ duty: clampDuty(String(params.duty ?? "")),
478
+ dutyLong: String(params.dutyLong),
479
+ routines: routinesInput,
480
+ routinesText: routinesInput.map((item) => `${item.name} · ${cronToChinese(item.schedule)}`).join("、"),
481
+ askFirst: (params.askFirst as string[]) ?? [],
482
+ instructions: (params.instructions as string[]) ?? [],
483
+ carry: { conversations: Number(params.conversations ?? 0) },
484
+ createdAt: new Date().toISOString(),
485
+ };
486
+ store.saveDraft(draft);
487
+ await router.addItem(assistantId, { kind: "draft", draftId: draft.id });
488
+ bus.emit({ type: "draft", draft });
489
+ return endTurn(
490
+ "草稿卡已显示给用户,卡片里已有名称、职责、定时任务和补充说明。本轮到此结束:不要输出任何文字,不要再描述或总结这张卡。",
491
+ );
492
+ },
493
+ },
494
+ {
495
+ name: "message_assistant",
496
+ label: "转交其他助手",
497
+ description: "把一件事交给更合适的助手去办:对话里会出现一张委派卡,对方的回复和它派出的任务全部结束后,结果会作为一条事件回到这里,你再用一两句话告诉用户。调用后本轮结束,不要再输出文字。",
498
+ parameters: Type.Object({
499
+ assistantId: Type.String({ description: "目标助手 id" }),
500
+ text: Type.String({ description: "要转交的内容" }),
501
+ }),
502
+ execute: async (_id, params: any) => {
503
+ const targetId = String(params.assistantId);
504
+ const target = store.assistant(targetId);
505
+ if (!target) return fail(`没有这个助手:${targetId}`);
506
+ if (targetId === assistantId) return fail("不能转交给自己。");
507
+ try {
508
+ await runtime.delegations.start(targetId, String(params.text));
509
+ return endTurn(`已转交给「${target.name}」,结果会自动回到这里。`);
510
+ } catch (error) {
511
+ return fail(error instanceof Error ? error.message : String(error));
512
+ }
513
+ },
514
+ },
515
+ );
516
+ } else {
517
+ tools.push({
518
+ name: "hand_back_to_hob",
519
+ label: "交回 Hob",
520
+ description: "这件事不在你的职责范围内时,把它交回主助手 Hob,由它转给合适的助手或自己处理。text 写清楚用户要什么,reason 一句话说明为什么不归你。调用后本轮结束,不要再输出文字。",
521
+ parameters: Type.Object({ text: Type.String(), reason: Type.String() }),
522
+ execute: async (_id, params: any) => {
523
+ const text = String(params.text ?? "").trim();
524
+ const reason = String(params.reason ?? "").trim();
525
+ if (!text || !reason) return fail("请写清用户要求和交回原因。");
526
+ try {
527
+ const delegationId = router.currentDelegation(assistantId);
528
+ if (delegationId) {
529
+ runtime.delegations.returnToHob(delegationId, text, reason);
530
+ } else {
531
+ await router.ensure("hob");
532
+ const handbackId = newId("hb-");
533
+ await router.addItem(assistantId, { kind: "note", icon: "info", text: `已交回 Hob:${reason}`, handbackId });
534
+ await router.addForwarded("hob", text, handbackId, assistantId);
535
+ await router.event("hob", `转自「${assistant().name}」:${text}\n交回原因:${reason}`);
536
+ }
537
+ return endTurn("已交回 Hob,本轮结束,不要再输出文字。");
538
+ } catch (error) {
539
+ return fail(error instanceof Error ? error.message : String(error));
540
+ }
541
+ },
542
+ });
543
+ }
544
+
545
+ tools.push(...searchTools(runtime.home, () => runtime.settings.settings.search));
546
+ return tools;
547
+ }
548
+
549
+ export type { Routine };