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,324 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, appendFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import type {
|
|
4
|
+
Approval,
|
|
5
|
+
Assistant,
|
|
6
|
+
Delegation,
|
|
7
|
+
Draft,
|
|
8
|
+
Job,
|
|
9
|
+
Routine,
|
|
10
|
+
Rule,
|
|
11
|
+
WorklogEntry,
|
|
12
|
+
} from "../../shared/types.ts";
|
|
13
|
+
|
|
14
|
+
function writeJsonAtomic(path: string, value: unknown): void {
|
|
15
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
16
|
+
const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
17
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`);
|
|
18
|
+
renameSync(tmp, path);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function readJson<T>(path: string, fallback: T): T {
|
|
22
|
+
if (!existsSync(path)) return fallback;
|
|
23
|
+
try {
|
|
24
|
+
return JSON.parse(readFileSync(path, "utf8")) as T;
|
|
25
|
+
} catch {
|
|
26
|
+
return fallback;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function readJsonl<T>(path: string): T[] {
|
|
31
|
+
if (!existsSync(path)) return [];
|
|
32
|
+
const out: T[] = [];
|
|
33
|
+
for (const line of readFileSync(path, "utf8").split("\n")) {
|
|
34
|
+
if (!line.trim()) continue;
|
|
35
|
+
try {
|
|
36
|
+
out.push(JSON.parse(line) as T);
|
|
37
|
+
} catch {
|
|
38
|
+
// 半行(进程被杀)直接跳过,不污染整份日志
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 助手的本地状态(不属于前后端契约,只存未读位置)。 */
|
|
45
|
+
export interface AssistantState {
|
|
46
|
+
readAt?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* HOB_HOME 下的全部 JSON / JSONL 数据。文件都小,直接同步读写,写入走临时文件 + rename。
|
|
51
|
+
*/
|
|
52
|
+
export class Store {
|
|
53
|
+
constructor(readonly home: string) {}
|
|
54
|
+
|
|
55
|
+
init(): void {
|
|
56
|
+
for (const dir of ["assistants", "jobs", "uploads"]) {
|
|
57
|
+
mkdirSync(join(this.home, dir), { recursive: true });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ---------- 助手 ----------
|
|
62
|
+
private assistantDir(id: string): string {
|
|
63
|
+
return join(this.home, "assistants", id);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
assistants(): Assistant[] {
|
|
67
|
+
const root = join(this.home, "assistants");
|
|
68
|
+
if (!existsSync(root)) return [];
|
|
69
|
+
const out: Assistant[] = [];
|
|
70
|
+
for (const id of readdirSync(root)) {
|
|
71
|
+
const profile = this.assistant(id);
|
|
72
|
+
if (profile) out.push(profile);
|
|
73
|
+
}
|
|
74
|
+
return out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
assistant(id: string): Assistant | undefined {
|
|
78
|
+
const profile = readJson<Assistant | null>(join(this.assistantDir(id), "profile.json"), null);
|
|
79
|
+
if (!profile) return undefined;
|
|
80
|
+
// 旧档案没有这个字段
|
|
81
|
+
return { ...profile, instructions: profile.instructions ?? "" };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
saveAssistant(assistant: Assistant): void {
|
|
85
|
+
writeJsonAtomic(join(this.assistantDir(assistant.id), "profile.json"), assistant);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
deleteAssistant(id: string): void {
|
|
89
|
+
rmSync(this.assistantDir(id), { recursive: true, force: true });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* 并回 Hob:整个助手目录移进 archive/assistants/<id>-<时间>/。同盘 rename,不复制也不删数据,
|
|
94
|
+
* 归档里的 profile.json 就是它原来的档案。
|
|
95
|
+
*/
|
|
96
|
+
archiveAssistant(id: string, name: string): string {
|
|
97
|
+
const target = join(this.home, "archive", "assistants", name);
|
|
98
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
99
|
+
renameSync(this.assistantDir(id), target);
|
|
100
|
+
return target;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
state(id: string): AssistantState {
|
|
104
|
+
return readJson<AssistantState>(join(this.assistantDir(id), "state.json"), {});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
saveState(id: string, state: AssistantState): void {
|
|
108
|
+
writeJsonAtomic(join(this.assistantDir(id), "state.json"), state);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
routerFile(id: string): string {
|
|
112
|
+
return join(this.assistantDir(id), "router.jsonl");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
rules(id: string): Rule[] {
|
|
116
|
+
return readJson<Rule[]>(join(this.assistantDir(id), "rules.json"), []);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
saveRules(id: string, rules: Rule[]): void {
|
|
120
|
+
writeJsonAtomic(join(this.assistantDir(id), "rules.json"), rules);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
worklog(id: string, limit = 30): WorklogEntry[] {
|
|
124
|
+
return readJsonl<WorklogEntry>(join(this.assistantDir(id), "worklog.jsonl")).slice(-limit).reverse();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
addWorklog(id: string, entry: WorklogEntry): void {
|
|
128
|
+
const dir = this.assistantDir(id);
|
|
129
|
+
mkdirSync(dir, { recursive: true });
|
|
130
|
+
appendFileSync(join(dir, "worklog.jsonl"), `${JSON.stringify(entry)}\n`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ---------- 定时 ----------
|
|
134
|
+
private routinesFile(): string {
|
|
135
|
+
return join(this.home, "routines.json");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
routines(): Routine[] {
|
|
139
|
+
return readJson<Routine[]>(this.routinesFile(), []);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
routine(id: string): Routine | undefined {
|
|
143
|
+
return this.routines().find((r) => r.id === id);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
saveRoutine(routine: Routine): void {
|
|
147
|
+
const all = this.routines().filter((r) => r.id !== routine.id);
|
|
148
|
+
all.push(routine);
|
|
149
|
+
writeJsonAtomic(this.routinesFile(), all);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
deleteRoutine(id: string): void {
|
|
153
|
+
writeJsonAtomic(this.routinesFile(), this.routines().filter((r) => r.id !== id));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ---------- 审批 ----------
|
|
157
|
+
private approvalsFile(): string {
|
|
158
|
+
return join(this.home, "approvals.json");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
approvals(): Approval[] {
|
|
162
|
+
return readJson<Approval[]>(this.approvalsFile(), []);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
approval(id: string): Approval | undefined {
|
|
166
|
+
return this.approvals().find((a) => a.id === id);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
saveApproval(approval: Approval): void {
|
|
170
|
+
const all = this.approvals().filter((a) => a.id !== approval.id);
|
|
171
|
+
all.push(approval);
|
|
172
|
+
writeJsonAtomic(this.approvalsFile(), all);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ---------- 委派 ----------
|
|
176
|
+
delegations(): Delegation[] {
|
|
177
|
+
return readJson<Delegation[]>(join(this.home, "delegations.json"), []);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
delegation(id: string): Delegation | undefined {
|
|
181
|
+
return this.delegations().find((item) => item.id === id);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
saveDelegation(delegation: Delegation): void {
|
|
185
|
+
const all = this.delegations().filter((item) => item.id !== delegation.id);
|
|
186
|
+
all.push(delegation);
|
|
187
|
+
writeJsonAtomic(join(this.home, "delegations.json"), all);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ---------- 草稿 ----------
|
|
191
|
+
private draftsFile(): string {
|
|
192
|
+
return join(this.home, "drafts.json");
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
drafts(): Draft[] {
|
|
196
|
+
return readJson<Draft[]>(this.draftsFile(), []);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
draft(id: string): Draft | undefined {
|
|
200
|
+
return this.drafts().find((d) => d.id === id);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
saveDraft(draft: Draft): void {
|
|
204
|
+
const all = this.drafts().filter((d) => d.id !== draft.id);
|
|
205
|
+
all.push(draft);
|
|
206
|
+
writeJsonAtomic(this.draftsFile(), all);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---------- 任务 ----------
|
|
210
|
+
jobDir(id: string): string {
|
|
211
|
+
return join(this.home, "jobs", id);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
jobs(): Job[] {
|
|
215
|
+
const root = join(this.home, "jobs");
|
|
216
|
+
if (!existsSync(root)) return [];
|
|
217
|
+
const out: Job[] = [];
|
|
218
|
+
for (const id of readdirSync(root)) {
|
|
219
|
+
const job = readJson<Job | null>(join(root, id, "job.json"), null);
|
|
220
|
+
if (job) out.push(job);
|
|
221
|
+
}
|
|
222
|
+
return out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
job(id: string): Job | undefined {
|
|
226
|
+
return readJson<Job | null>(join(this.jobDir(id), "job.json"), null) ?? undefined;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
saveJob(job: Job): void {
|
|
230
|
+
writeJsonAtomic(join(this.jobDir(job.id), "job.json"), job);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
writeReport(jobId: string, text: string): string {
|
|
234
|
+
const path = join(this.jobDir(jobId), "report.md");
|
|
235
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
236
|
+
writeFileSync(path, text);
|
|
237
|
+
return path;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
workerFile(jobId: string): string {
|
|
241
|
+
return join(this.jobDir(jobId), "worker.jsonl");
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** 任务过程里超长输出的全文:落在任务目录下,页面按路径去拉。 */
|
|
245
|
+
writeStepOutput(jobId: string, stepId: string, text: string): string {
|
|
246
|
+
const safe = stepId.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
247
|
+
const path = join(this.jobDir(jobId), "steps", `${safe}.txt`);
|
|
248
|
+
if (existsSync(path)) return path;
|
|
249
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
250
|
+
writeFileSync(path, text);
|
|
251
|
+
return path;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 本机任务的默认工作目录:产出文件只能落在这里。 */
|
|
255
|
+
workDir(jobId: string): string {
|
|
256
|
+
const path = join(this.jobDir(jobId), "work");
|
|
257
|
+
mkdirSync(path, { recursive: true });
|
|
258
|
+
return path;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* 一次性迁移:老的 assistants/<id>/memories.json 每条追加成该助手 instructions 的一行,
|
|
263
|
+
* 然后删掉文件;草稿里的 memories 改名成 instructions。跑过一次就没有了,不是兼容层。
|
|
264
|
+
*/
|
|
265
|
+
migrateMemories(): void {
|
|
266
|
+
type OldDraft = Draft & { memories?: string[]; carry: Draft["carry"] & { memories?: number } };
|
|
267
|
+
const drafts = readJson<OldDraft[]>(this.draftsFile(), []);
|
|
268
|
+
if (drafts.some((draft) => !Array.isArray(draft.instructions))) {
|
|
269
|
+
writeJsonAtomic(
|
|
270
|
+
this.draftsFile(),
|
|
271
|
+
drafts.map(({ memories, carry: { memories: _carried, ...carry }, ...draft }) => ({
|
|
272
|
+
...draft,
|
|
273
|
+
instructions: draft.instructions ?? memories ?? [],
|
|
274
|
+
carry,
|
|
275
|
+
})),
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
const root = join(this.home, "assistants");
|
|
279
|
+
if (!existsSync(root)) return;
|
|
280
|
+
for (const id of readdirSync(root)) {
|
|
281
|
+
const file = join(root, id, "memories.json");
|
|
282
|
+
if (!existsSync(file)) continue;
|
|
283
|
+
const lines = readJson<{ text?: string }[]>(file, [])
|
|
284
|
+
.map((memory) => (memory?.text ?? "").trim())
|
|
285
|
+
.filter(Boolean);
|
|
286
|
+
const assistant = this.assistant(id);
|
|
287
|
+
if (assistant && lines.length) {
|
|
288
|
+
const current = assistant.instructions.trim();
|
|
289
|
+
this.saveAssistant({ ...assistant, instructions: [current, ...lines].filter(Boolean).join("\n") });
|
|
290
|
+
}
|
|
291
|
+
rmSync(file, { force: true });
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** 从已创建的草稿补全旧助手的详细职责,不覆盖已有值。 */
|
|
296
|
+
migrateAssistantDuties(): void {
|
|
297
|
+
const drafts = this.drafts();
|
|
298
|
+
for (const assistant of this.assistants()) {
|
|
299
|
+
if (assistant.dutyLong !== undefined) continue;
|
|
300
|
+
const draft = drafts.find((item) => item.status === "created" && item.createdAssistantId === assistant.id && item.dutyLong);
|
|
301
|
+
if (draft) this.saveAssistant({ ...assistant, dutyLong: draft.dutyLong });
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ---------- 首次启动 ----------
|
|
306
|
+
ensurePrimary(): Assistant {
|
|
307
|
+
const existing = this.assistant("hob");
|
|
308
|
+
if (existing) return existing;
|
|
309
|
+
const hob: Assistant = {
|
|
310
|
+
id: "hob",
|
|
311
|
+
name: "Hob",
|
|
312
|
+
duty: "主助手",
|
|
313
|
+
sprite: "hob",
|
|
314
|
+
primary: true,
|
|
315
|
+
pinned: true,
|
|
316
|
+
hidden: false,
|
|
317
|
+
notify: true,
|
|
318
|
+
instructions: "",
|
|
319
|
+
createdAt: new Date().toISOString(),
|
|
320
|
+
};
|
|
321
|
+
this.saveAssistant(hob);
|
|
322
|
+
return hob;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { isAbsolute, relative } from "node:path";
|
|
2
|
+
|
|
3
|
+
/** 左栏头像下的小字:去掉多余空白,超过 max 个字直接截断(不补省略号,放不下)。 */
|
|
4
|
+
export function clampDuty(value: string, max = 8): string {
|
|
5
|
+
const text = value.replace(/\s+/g, " ").trim();
|
|
6
|
+
return text.length > max ? text.slice(0, max).trim() : text;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** 活动流里的路径:在工作目录下的就显示相对路径。 */
|
|
10
|
+
export function showPath(path: string, cwd: string): string {
|
|
11
|
+
if (!path || !cwd || !isAbsolute(path)) return path;
|
|
12
|
+
const rel = relative(cwd, path);
|
|
13
|
+
return rel && !rel.startsWith("..") ? rel : path;
|
|
14
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// 时区相关的文字:提示词里的“现在时间”按 config.timezone 算,不看服务器系统时区。
|
|
2
|
+
|
|
3
|
+
/** "2026-11-01 09:10 周日" */
|
|
4
|
+
export function nowText(timezone: string, at: Date = new Date()): string {
|
|
5
|
+
const stamp = new Intl.DateTimeFormat("sv-SE", {
|
|
6
|
+
timeZone: timezone,
|
|
7
|
+
year: "numeric",
|
|
8
|
+
month: "2-digit",
|
|
9
|
+
day: "2-digit",
|
|
10
|
+
hour: "2-digit",
|
|
11
|
+
minute: "2-digit",
|
|
12
|
+
hour12: false,
|
|
13
|
+
}).format(at);
|
|
14
|
+
const weekday = new Intl.DateTimeFormat("zh-CN", { timeZone: timezone, weekday: "short" }).format(at);
|
|
15
|
+
return `${stamp} ${weekday}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** "11月1日":配置时区下的月日,不看服务器系统时区。 */
|
|
19
|
+
export function monthDayText(timezone: string, at: Date = new Date()): string {
|
|
20
|
+
return new Intl.DateTimeFormat("zh-CN", { timeZone: timezone, month: "long", day: "numeric" }).format(at);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** "11月1日 09:43":配置时区下的月日和时刻(报告里的结束时间用),不看服务器系统时区。 */
|
|
24
|
+
export function monthDayTimeText(timezone: string, at: Date = new Date()): string {
|
|
25
|
+
const clock = new Intl.DateTimeFormat("sv-SE", {
|
|
26
|
+
timeZone: timezone,
|
|
27
|
+
hour: "2-digit",
|
|
28
|
+
minute: "2-digit",
|
|
29
|
+
hour12: false,
|
|
30
|
+
}).format(at);
|
|
31
|
+
return `${monthDayText(timezone, at)} ${clock}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 时区名不合法就直接报错,不悄悄退回系统时区。 */
|
|
35
|
+
export function checkTimezone(timezone: string): string {
|
|
36
|
+
try {
|
|
37
|
+
new Intl.DateTimeFormat("sv-SE", { timeZone: timezone });
|
|
38
|
+
} catch {
|
|
39
|
+
throw new Error(`时区不合法:${timezone}(例:Europe/Berlin)`);
|
|
40
|
+
}
|
|
41
|
+
return timezone;
|
|
42
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// 任务过程(transcript):从任务的 worker.jsonl 推导步骤列表,实时事件和落盘推导共用一套拼装。
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { commandSummary } from "../../shared/command.ts";
|
|
4
|
+
import type { JobStep } from "../../shared/types.ts";
|
|
5
|
+
import { showPath } from "./text.ts";
|
|
6
|
+
|
|
7
|
+
/** transcript 里单步输出最多这么多字,超出的整段落盘,页面按路径去拉。 */
|
|
8
|
+
export const STEP_OUTPUT_LIMIT = 20 * 1024;
|
|
9
|
+
/** 实时事件里的单步输出最多这么多字(全文落盘,给路径)。 */
|
|
10
|
+
export const STEP_EVENT_LIMIT = 4 * 1024;
|
|
11
|
+
/** diff 只给看得清的一段,超长的改动不整段塞进接口。 */
|
|
12
|
+
const EDIT_TEXT_LIMIT = 4_000;
|
|
13
|
+
|
|
14
|
+
const AUTO_FOLLOW_UP = "你还没有调用 report";
|
|
15
|
+
|
|
16
|
+
function oneLine(value: string, max = 120): string {
|
|
17
|
+
const line = value.replace(/\s+/g, " ").trim();
|
|
18
|
+
return line.length > max ? `${line.slice(0, max - 1)}…` : line;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function tick(text: string): string {
|
|
22
|
+
return `\`${oneLine(text, 90)}\``;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function clip(value: string, max: number): string {
|
|
26
|
+
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function clipEdit(edits: unknown): { oldText: string; newText: string }[] {
|
|
30
|
+
if (!Array.isArray(edits)) return [];
|
|
31
|
+
return edits.map((edit) => ({
|
|
32
|
+
oldText: clip(String((edit as { oldText?: unknown })?.oldText ?? ""), EDIT_TEXT_LIMIT),
|
|
33
|
+
newText: clip(String((edit as { newText?: unknown })?.newText ?? ""), EDIT_TEXT_LIMIT),
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 只留详情页要看的那几个参数(write 的正文不整段传,只给长度)。 */
|
|
38
|
+
export function toolArgs(name: string, raw: Record<string, unknown>, cwd = ""): Record<string, unknown> {
|
|
39
|
+
const path = showPath(String(raw.path ?? ""), cwd);
|
|
40
|
+
switch (name) {
|
|
41
|
+
case "bash":
|
|
42
|
+
return { command: String(raw.command ?? "") };
|
|
43
|
+
case "read":
|
|
44
|
+
return {
|
|
45
|
+
path,
|
|
46
|
+
...(raw.offset !== undefined ? { offset: raw.offset } : {}),
|
|
47
|
+
...(raw.limit !== undefined ? { limit: raw.limit } : {}),
|
|
48
|
+
};
|
|
49
|
+
case "edit":
|
|
50
|
+
return { path, edits: clipEdit(raw.edits) };
|
|
51
|
+
case "write":
|
|
52
|
+
return { path, contentLength: String(raw.content ?? "").length };
|
|
53
|
+
case "grep":
|
|
54
|
+
return {
|
|
55
|
+
pattern: String(raw.pattern ?? ""),
|
|
56
|
+
...(path ? { path } : {}),
|
|
57
|
+
...(raw.glob ? { glob: String(raw.glob) } : {}),
|
|
58
|
+
};
|
|
59
|
+
case "find":
|
|
60
|
+
return { pattern: String(raw.pattern ?? ""), ...(path ? { path } : {}) };
|
|
61
|
+
case "ls":
|
|
62
|
+
return { path: path || "." };
|
|
63
|
+
default:
|
|
64
|
+
return raw;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 记忆插件的工具(本地记忆 / Lore):名字是英文的,显示成动作。 */
|
|
69
|
+
const MEMORY_TOOLS: Record<string, string> = {
|
|
70
|
+
memory_search: "搜索记忆",
|
|
71
|
+
memory_read: "读取记忆",
|
|
72
|
+
memory_write: "保存记忆",
|
|
73
|
+
memory_forget: "删除记忆",
|
|
74
|
+
memory_restore: "恢复记忆",
|
|
75
|
+
memory_status: "查看记忆状态",
|
|
76
|
+
lore_boot: "读取记忆",
|
|
77
|
+
lore_get_node: "读取记忆",
|
|
78
|
+
lore_search: "搜索记忆",
|
|
79
|
+
lore_create_node: "保存记忆",
|
|
80
|
+
lore_update_node: "保存记忆",
|
|
81
|
+
lore_move_node: "整理记忆",
|
|
82
|
+
lore_delete_node: "删除记忆",
|
|
83
|
+
lore_list_domains: "查看记忆状态",
|
|
84
|
+
lore_status: "查看记忆状态",
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** 一行中文:「运行 `npm test`」「修改 server/src/jobs.ts」「读取 README.md」。 */
|
|
88
|
+
export function toolTitle(name: string, args: Record<string, unknown>): string {
|
|
89
|
+
const path = String(args.path ?? "");
|
|
90
|
+
switch (name) {
|
|
91
|
+
case "bash":
|
|
92
|
+
return `运行 ${tick(commandSummary(String(args.command ?? "")))}`;
|
|
93
|
+
case "read":
|
|
94
|
+
return `读取 ${path}${readRange(args)}`;
|
|
95
|
+
case "edit":
|
|
96
|
+
return `修改 ${path}`;
|
|
97
|
+
case "write":
|
|
98
|
+
return `写入 ${path}`;
|
|
99
|
+
case "grep":
|
|
100
|
+
return `搜索 ${tick(String(args.pattern ?? ""))}`;
|
|
101
|
+
case "find":
|
|
102
|
+
return `查找 ${tick(String(args.pattern ?? ""))}`;
|
|
103
|
+
case "ls":
|
|
104
|
+
return `列出 ${path}`;
|
|
105
|
+
case "report":
|
|
106
|
+
return "提交结果";
|
|
107
|
+
case "ask_user":
|
|
108
|
+
return `询问用户:${oneLine(String(args.title ?? ""), 60)}`;
|
|
109
|
+
case "overview":
|
|
110
|
+
return `查看最近 ${Number(args.sinceHours ?? 24)} 小时的记录`;
|
|
111
|
+
case "generate_image":
|
|
112
|
+
return `生成图片:${oneLine(String(args.prompt ?? ""), 60)}`;
|
|
113
|
+
case "web_search":
|
|
114
|
+
return `联网搜索:${oneLine(String(args.query ?? ""), 60)}`;
|
|
115
|
+
case "web_fetch":
|
|
116
|
+
return `读取网页:${oneLine(String(args.url ?? ""), 60)}`;
|
|
117
|
+
default: {
|
|
118
|
+
const label = MEMORY_TOOLS[name];
|
|
119
|
+
if (!label) return name;
|
|
120
|
+
const target = String(args.uri ?? args.query ?? "");
|
|
121
|
+
return target ? `${label} ${tick(target)}` : label;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function readRange(args: Record<string, unknown>): string {
|
|
127
|
+
const offset = typeof args.offset === "number" ? args.offset : undefined;
|
|
128
|
+
const limit = typeof args.limit === "number" ? args.limit : undefined;
|
|
129
|
+
if (offset !== undefined && limit !== undefined) return ` · ${offset}–${offset + limit - 1} 行`;
|
|
130
|
+
if (offset !== undefined) return ` · 第 ${offset} 行起`;
|
|
131
|
+
if (limit !== undefined) return ` · 前 ${limit} 行`;
|
|
132
|
+
return "";
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function textOfContent(content: unknown): string {
|
|
136
|
+
if (typeof content === "string") return content;
|
|
137
|
+
if (!Array.isArray(content)) return "";
|
|
138
|
+
return content
|
|
139
|
+
.filter((block): block is { type: "text"; text: string } => Boolean(block) && block.type === "text")
|
|
140
|
+
.map((block) => block.text)
|
|
141
|
+
.join("");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface ToolStepInput {
|
|
145
|
+
id: string;
|
|
146
|
+
name: string;
|
|
147
|
+
args: Record<string, unknown>;
|
|
148
|
+
at?: string;
|
|
149
|
+
cwd?: string;
|
|
150
|
+
running?: boolean;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** 一次工具调用 → 一个步骤(还没有结果)。实时事件和落盘推导都用它,页面按 id 合并。 */
|
|
154
|
+
export function toolStep(input: ToolStepInput): JobStep {
|
|
155
|
+
const args = toolArgs(input.name, input.args, input.cwd ?? "");
|
|
156
|
+
return {
|
|
157
|
+
id: input.id,
|
|
158
|
+
kind: "tool",
|
|
159
|
+
at: input.at ?? new Date().toISOString(),
|
|
160
|
+
name: input.name,
|
|
161
|
+
title: toolTitle(input.name, args),
|
|
162
|
+
args,
|
|
163
|
+
...(input.running ? { running: true } : {}),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 把工具结果的全文装进步骤:超过 limit 就截断并落盘,给出「完整输出在 …」的路径。
|
|
169
|
+
* 没有 save 就只截断。
|
|
170
|
+
*/
|
|
171
|
+
export function withOutput(
|
|
172
|
+
step: JobStep,
|
|
173
|
+
full: string,
|
|
174
|
+
options: { limit: number; isError?: boolean; durationMs?: number; save?: (stepId: string, text: string) => string },
|
|
175
|
+
): JobStep {
|
|
176
|
+
const next: JobStep = { ...step, ...(options.isError ? { isError: true } : {}), ...(options.durationMs ? { durationMs: options.durationMs } : {}) };
|
|
177
|
+
delete next.running;
|
|
178
|
+
if (!full) return next;
|
|
179
|
+
if (full.length <= options.limit) return { ...next, output: full };
|
|
180
|
+
const path = options.save?.(step.id, full);
|
|
181
|
+
const note = `\n\n[输出共 ${full.length} 字,这里截到 ${options.limit} 字。${path ? `完整输出在 ${path}` : ""}]`;
|
|
182
|
+
return { ...next, output: full.slice(0, options.limit) + note, ...(path ? { outputPath: path } : {}) };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function stamp(value: unknown, fallback: unknown): string {
|
|
186
|
+
const ms = typeof value === "number" ? value : Date.parse(String(value ?? ""));
|
|
187
|
+
const at = Number.isFinite(ms) ? ms : Date.parse(String(fallback ?? ""));
|
|
188
|
+
return new Date(Number.isFinite(at) ? at : Date.now()).toISOString();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export interface DeriveOptions {
|
|
192
|
+
cwd?: string;
|
|
193
|
+
limit?: number;
|
|
194
|
+
/** 输出过长时落盘,返回路径 */
|
|
195
|
+
save?: (stepId: string, text: string) => string;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** 从任务会话文件推导整个过程:说明文字、思考摘要、工具调用(含结果)。 */
|
|
199
|
+
export function deriveSteps(file: string, options: DeriveOptions = {}): JobStep[] {
|
|
200
|
+
if (!existsSync(file)) return [];
|
|
201
|
+
const limit = options.limit ?? STEP_OUTPUT_LIMIT;
|
|
202
|
+
const steps: JobStep[] = [];
|
|
203
|
+
const toolIndex = new Map<string, number>();
|
|
204
|
+
let seenUser = false;
|
|
205
|
+
|
|
206
|
+
for (const line of readFileSync(file, "utf8").split("\n")) {
|
|
207
|
+
if (!line.trim()) continue;
|
|
208
|
+
let entry: any;
|
|
209
|
+
try {
|
|
210
|
+
entry = JSON.parse(line);
|
|
211
|
+
} catch {
|
|
212
|
+
continue; // 半行(进程被杀)跳过
|
|
213
|
+
}
|
|
214
|
+
if (entry?.type !== "message" || !entry.message) continue;
|
|
215
|
+
const message = entry.message;
|
|
216
|
+
const at = stamp(message.timestamp, entry.timestamp);
|
|
217
|
+
|
|
218
|
+
if (message.role === "assistant") {
|
|
219
|
+
const blocks: any[] = Array.isArray(message.content) ? message.content : [];
|
|
220
|
+
blocks.forEach((block, index) => {
|
|
221
|
+
if (block?.type === "thinking") {
|
|
222
|
+
const text = String(block.thinking ?? "").trim();
|
|
223
|
+
if (!text || block.redacted) return;
|
|
224
|
+
steps.push({ id: `k${message.timestamp}-${index}`, kind: "thinking", at, text });
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (block?.type === "text") {
|
|
228
|
+
const text = String(block.text ?? "").trim();
|
|
229
|
+
if (!text) return;
|
|
230
|
+
steps.push({ id: `t${message.timestamp}-${index}`, kind: "text", at, from: "assistant", text });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (block?.type === "toolCall") {
|
|
234
|
+
const step = toolStep({
|
|
235
|
+
id: String(block.id ?? `x${message.timestamp}-${index}`),
|
|
236
|
+
name: String(block.name ?? ""),
|
|
237
|
+
args: block.arguments ?? {},
|
|
238
|
+
at,
|
|
239
|
+
cwd: options.cwd ?? "",
|
|
240
|
+
running: true,
|
|
241
|
+
});
|
|
242
|
+
toolIndex.set(step.id, steps.length);
|
|
243
|
+
steps.push(step);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (message.role === "toolResult") {
|
|
250
|
+
const index = toolIndex.get(String(message.toolCallId ?? ""));
|
|
251
|
+
if (index === undefined) continue;
|
|
252
|
+
steps[index] = withOutput(steps[index], textOfContent(message.content), {
|
|
253
|
+
limit,
|
|
254
|
+
isError: Boolean(message.isError),
|
|
255
|
+
durationMs: typeof message.durationMs === "number" ? message.durationMs : undefined,
|
|
256
|
+
...(options.save ? { save: options.save } : {}),
|
|
257
|
+
});
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (message.role === "user") {
|
|
262
|
+
const text = textOfContent(message.content).trim();
|
|
263
|
+
if (!text || text.startsWith(AUTO_FOLLOW_UP)) continue;
|
|
264
|
+
if (!seenUser) {
|
|
265
|
+
seenUser = true; // 第一句是任务说明,详情头部已经有
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
steps.push({ id: `u${message.timestamp ?? at}`, kind: "text", at, from: "user", text });
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return steps;
|
|
272
|
+
}
|