@keyou007/agent-bot 0.1.27-alpha.3 → 0.1.27-alpha.5
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/CHANGELOG.md +32 -0
- package/README.md +102 -18
- package/README.zh.md +102 -18
- package/assets/agent-bot.ico +0 -0
- package/assets/roboto-mono-OFL.txt +93 -0
- package/assets/roboto-mono-latin.woff2 +0 -0
- package/assets/workspace-drafts.js +88 -0
- package/assets/workspace-sessions.js +2676 -243
- package/assets/workspace.css +553 -44
- package/assets/workspace.js +3429 -327
- package/dist/cli/SelfUpdateObserver.js +124 -0
- package/dist/cli/SelfUpdateObserver.js.map +1 -0
- package/dist/cli/SelfUpdateRunner.js +267 -70
- package/dist/cli/SelfUpdateRunner.js.map +1 -1
- package/dist/cli/SelfUpdater.js +54 -15
- package/dist/cli/SelfUpdater.js.map +1 -1
- package/dist/cli/controlProtocol.js.map +1 -1
- package/dist/cli/help.js +6 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli.js +85 -6
- package/dist/cli.js.map +1 -1
- package/dist/codex/CodexEventMapper.js +29 -5
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +3 -0
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/feishu/CardRenderer.js +45 -13
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/ConsoleFeishuClient.js +4 -0
- package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
- package/dist/feishu/FeishuMarkdown.js +2 -14
- package/dist/feishu/FeishuMarkdown.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +9 -0
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +51 -22
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +47 -12
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +11 -6
- package/dist/local-files/DiagramPreview.js.map +1 -1
- package/dist/local-files/GitDiffPreview.js +106 -14
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LiveMarkup.js +104 -0
- package/dist/local-files/LiveMarkup.js.map +1 -0
- package/dist/local-files/LocalFileViewerServer.js +141 -122
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownExport.js +54 -0
- package/dist/local-files/MarkdownExport.js.map +1 -0
- package/dist/local-files/PreviewCodeFont.js +11 -0
- package/dist/local-files/PreviewCodeFont.js.map +1 -0
- package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
- package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
- package/dist/local-files/ToolCommandDisplay.js +111 -0
- package/dist/local-files/ToolCommandDisplay.js.map +1 -0
- package/dist/local-files/TurnPreviewPage.js +53 -276
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WorkspaceFileEvents.js +206 -0
- package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +79 -3
- package/dist/local-files/WorkspaceFiles.js.map +1 -1
- package/dist/local-files/WorkspaceImages.js +43 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +24 -6
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +1153 -104
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +129 -0
- package/dist/local-files/WorkspaceTimeline.js.map +1 -0
- package/dist/presentation/OutboundRouter.js +15 -6
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +31 -22
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +335 -113
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/proxy/TaskMetadata.js +86 -0
- package/dist/proxy/TaskMetadata.js.map +1 -0
- package/dist/scheduling/ScheduleCards.js +10 -4
- package/dist/scheduling/ScheduleCards.js.map +1 -1
- package/dist/scheduling/ScheduleCommand.js +4 -0
- package/dist/scheduling/ScheduleCommand.js.map +1 -1
- package/dist/scheduling/ScheduledTaskStore.js +53 -12
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +19 -4
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +213 -23
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +157 -39
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/TurnToolText.js +172 -0
- package/dist/state/TurnToolText.js.map +1 -0
- package/dist/state/migrations.js +4 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +9 -6
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/terminal/TerminalPage.js +5 -0
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/updates/AutomaticUpdatePreparer.js +63 -12
- package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
- package/dist/updates/ManualUpdateController.js +7 -2
- package/dist/updates/ManualUpdateController.js.map +1 -1
- package/dist/utils/promptAttachments.js +22 -0
- package/dist/utils/promptAttachments.js.map +1 -0
- package/dist/utils/promptQuotes.js +47 -0
- package/dist/utils/promptQuotes.js.map +1 -0
- package/dist/utils/toolTimestamp.js +6 -0
- package/dist/utils/toolTimestamp.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +23 -2
- package/src/cli/SelfUpdateObserver.ts +111 -0
- package/src/cli/SelfUpdateRunner.ts +271 -85
- package/src/cli/SelfUpdater.ts +53 -16
- package/src/cli/controlProtocol.ts +1 -0
- package/src/cli/help.ts +6 -0
- package/src/cli.ts +71 -5
- package/src/codex/CodexEventMapper.ts +25 -5
- package/src/codex/CodexRuntime.ts +4 -0
- package/src/feishu/CardRenderer.ts +48 -13
- package/src/feishu/ConsoleFeishuClient.ts +6 -1
- package/src/feishu/FeishuMarkdown.ts +2 -14
- package/src/feishu/FeishuMessageClient.ts +10 -0
- package/src/feishu/FeishuTurnPresenter.ts +49 -16
- package/src/feishu/types.ts +1 -0
- package/src/index.ts +47 -12
- package/src/local-files/DiagramPreview.ts +11 -6
- package/src/local-files/GitDiffPreview.ts +107 -15
- package/src/local-files/LiveMarkup.ts +103 -0
- package/src/local-files/LocalFileViewerServer.ts +128 -125
- package/src/local-files/MarkdownExport.ts +54 -0
- package/src/local-files/PreviewCodeFont.ts +12 -0
- package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
- package/src/local-files/ToolCommandDisplay.ts +104 -0
- package/src/local-files/TurnPreviewPage.ts +58 -261
- package/src/local-files/WorkspaceFileEvents.ts +186 -0
- package/src/local-files/WorkspaceFiles.ts +72 -5
- package/src/local-files/WorkspaceImages.ts +35 -0
- package/src/local-files/WorkspacePage.ts +24 -6
- package/src/local-files/WorkspaceSessions.ts +1057 -111
- package/src/local-files/WorkspaceTimeline.ts +135 -0
- package/src/presentation/OutboundRouter.ts +18 -4
- package/src/presentation/TurnStateReducer.ts +30 -19
- package/src/presentation/turnViewTypes.ts +3 -1
- package/src/proxy/ProxySessionController.ts +336 -96
- package/src/proxy/TaskMetadata.ts +81 -0
- package/src/runtime/types.ts +2 -1
- package/src/scheduling/ScheduleCards.ts +10 -4
- package/src/scheduling/ScheduleCommand.ts +4 -0
- package/src/scheduling/ScheduledTaskStore.ts +56 -9
- package/src/scheduling/types.ts +27 -4
- package/src/state/StateStore.ts +227 -24
- package/src/state/TurnPreviewJournal.ts +155 -38
- package/src/state/TurnToolText.ts +156 -0
- package/src/state/migrations.ts +4 -0
- package/src/supervision/SafeRestartNotifier.ts +9 -6
- package/src/terminal/TerminalPage.ts +5 -0
- package/src/updates/AutomaticUpdatePreparer.ts +52 -11
- package/src/updates/ManualUpdateController.ts +8 -3
- package/src/utils/promptAttachments.ts +27 -0
- package/src/utils/promptQuotes.ts +48 -0
- package/src/utils/toolTimestamp.ts +5 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { agentBotHome, resolveUserPath } from "../config/paths.js";
|
|
7
|
+
import type { StateStore } from "../state/StateStore.js";
|
|
8
|
+
|
|
9
|
+
export const TASK_DIRECTORY_KIND = "directory";
|
|
10
|
+
export const taskDirectoryId = z.string().regex(/^[a-f0-9]{32}$/u);
|
|
11
|
+
const commandSchema = z.discriminatedUnion("operation", [
|
|
12
|
+
z.object({ kind: z.literal(TASK_DIRECTORY_KIND), operation: z.literal("list") }),
|
|
13
|
+
z.object({ kind: z.literal(TASK_DIRECTORY_KIND), operation: z.literal("add"),
|
|
14
|
+
directory: z.string().min(1).max(2048).regex(/^[^\x00-\x1f\x7f]+$/u), userDirectory: z.boolean() }),
|
|
15
|
+
z.object({ kind: z.literal(TASK_DIRECTORY_KIND), operation: z.literal("remove"), key: taskDirectoryId }),
|
|
16
|
+
]);
|
|
17
|
+
export type TaskMetadataCommand = z.infer<typeof commandSchema>;
|
|
18
|
+
|
|
19
|
+
const projectFiles = ["package.json", "pyproject.toml", "go.mod", "Cargo.toml", "pom.xml", "settings.gradle", "settings.gradle.kts"];
|
|
20
|
+
const excludedComponents = new Set([".git", ".tmp", "tmp", "temp", "node_modules", ".cache"]);
|
|
21
|
+
const MAX_DIRECTORIES = 32;
|
|
22
|
+
|
|
23
|
+
function physicalPath(directory: string): string {
|
|
24
|
+
try { return fs.realpathSync(directory); } catch { return directory; }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function inDirectory(parent: string, child: string): boolean {
|
|
28
|
+
const relative = path.relative(parent, child);
|
|
29
|
+
return relative === "" || (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(".." + path.sep));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function eligibleDirectory(directory: string): boolean {
|
|
33
|
+
const { root } = path.parse(directory);
|
|
34
|
+
if (directory === root || inDirectory(directory, os.homedir())) return false;
|
|
35
|
+
if (directory.slice(root.length).split(path.sep).some((part) => excludedComponents.has(part.toLowerCase()))) return false;
|
|
36
|
+
return ![os.tmpdir(), agentBotHome()].some((base) => inDirectory(physicalPath(path.resolve(base)), directory));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function projectDirectory(input: string, cwd: string, userDirectory: boolean): string {
|
|
40
|
+
const requested = resolveUserPath(input, cwd);
|
|
41
|
+
const directory = fs.realpathSync(requested);
|
|
42
|
+
if (!eligibleDirectory(requested) || !eligibleDirectory(directory) || !fs.statSync(directory).isDirectory()) {
|
|
43
|
+
throw new Error("请选择项目根目录或任务使用的用户目录。临时目录和运行数据目录不能登记。");
|
|
44
|
+
}
|
|
45
|
+
let marked: string | undefined;
|
|
46
|
+
for (let ancestor = directory; eligibleDirectory(ancestor); ancestor = path.dirname(ancestor)) {
|
|
47
|
+
const git = fs.lstatSync(path.join(ancestor, ".git"), { throwIfNoEntry: false });
|
|
48
|
+
if (git?.isDirectory() || git?.isFile()) return ancestor;
|
|
49
|
+
if (!marked && (fs.statSync(path.join(ancestor, ".vscode"), { throwIfNoEntry: false })?.isDirectory()
|
|
50
|
+
|| projectFiles.some((file) => fs.statSync(path.join(ancestor, file), { throwIfNoEntry: false })?.isFile()))) {
|
|
51
|
+
marked = ancestor;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (marked) return marked;
|
|
55
|
+
if (userDirectory) return directory;
|
|
56
|
+
throw new Error("未找到 Git 或项目根目录标记。若这是任务使用的用户目录,请指定 --user-directory。");
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function listTaskDirectories(store: StateStore, taskId: string) {
|
|
60
|
+
return store.listTaskMetadata(taskId, TASK_DIRECTORY_KIND)
|
|
61
|
+
.map(({ key, value }) => ({ id: key, name: path.basename(value), path: value }));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function recordTaskMetadata(store: StateStore, taskId: string, input: TaskMetadataCommand) {
|
|
65
|
+
const task = store.getSession(taskId);
|
|
66
|
+
if (!task) throw new Error("任务不存在。");
|
|
67
|
+
const command = commandSchema.parse(input);
|
|
68
|
+
if (command.operation === "add") {
|
|
69
|
+
const directory = projectDirectory(command.directory, task.cwd, command.userDirectory);
|
|
70
|
+
if (directory.length > 2048) throw new Error("目录路径太长。");
|
|
71
|
+
const normalized = process.platform === "win32" ? directory.toLowerCase() : directory;
|
|
72
|
+
const key = createHash("sha256").update(normalized).digest("hex").slice(0, 32);
|
|
73
|
+
if (!store.getTaskMetadata(taskId, command.kind, key) && listTaskDirectories(store, taskId).length >= MAX_DIRECTORIES) {
|
|
74
|
+
throw new Error(`每个任务最多可登记 ${MAX_DIRECTORIES} 个目录。`);
|
|
75
|
+
}
|
|
76
|
+
store.setTaskMetadata(taskId, command.kind, key, directory);
|
|
77
|
+
} else if (command.operation === "remove") {
|
|
78
|
+
if (!store.removeTaskMetadata(taskId, command.kind, command.key)) throw new Error("任务中没有该目录记录。");
|
|
79
|
+
}
|
|
80
|
+
return { directories: listTaskDirectories(store, taskId) };
|
|
81
|
+
}
|
package/src/runtime/types.ts
CHANGED
|
@@ -55,7 +55,7 @@ export interface ToolState {
|
|
|
55
55
|
startedAt?: number;
|
|
56
56
|
completedAt?: number;
|
|
57
57
|
imagePath?: string;
|
|
58
|
-
files?: Array<{ path: string; additions?: number; deletions?: number }>;
|
|
58
|
+
files?: Array<{ path: string; moveTo?: string; additions?: number; deletions?: number; patch?: string; patchTruncated?: true }>;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
export interface ApprovalRequest {
|
|
@@ -319,6 +319,7 @@ export interface AgentRuntime {
|
|
|
319
319
|
listRemoteSessions?(input?: { searchTerm?: string; cursor?: string; limit?: number }): Promise<RemoteSessionPage>;
|
|
320
320
|
readRemoteSession?(remoteSessionId: string, view?: "metadata" | "latest" | "latest-full"): Promise<RemoteSessionSummary>;
|
|
321
321
|
readRemoteSessionMetrics?(remoteSessionId: string): Promise<RemoteSessionMetrics>;
|
|
322
|
+
getSessionStorageBytes?(localSessionId: string): number | undefined;
|
|
322
323
|
readRemoteForkSource?(remoteSessionId: string): Promise<RemoteSessionSummary>;
|
|
323
324
|
listRemoteTurnSummaries?(remoteSessionId: string, input: { cursor?: string; limit: number }): Promise<RemoteTurnPage>;
|
|
324
325
|
readConversation?(remoteSessionId: string, throughTurnId?: string): AsyncIterable<ConversationTurn>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ScheduledJob, ScheduledRun } from "./types.js";
|
|
2
|
-
import { scheduleTime, nextScheduleTime } from "./types.js";
|
|
2
|
+
import { scheduleTime, nextScheduleTime, scheduleDisplayPrompt } from "./types.js";
|
|
3
3
|
|
|
4
4
|
const labels: Record<string, string> = {
|
|
5
5
|
draft: "待确认",
|
|
@@ -159,15 +159,18 @@ export function renderSchedule(
|
|
|
159
159
|
const time = job.spec.at
|
|
160
160
|
? `执行时间:${scheduleTime(Date.parse(job.spec.at), job.spec.timeZone)}`
|
|
161
161
|
: `周期:${escape(job.spec.cron!)}\n下次执行:${scheduleTime(job.nextRunAt ?? (job.status === "draft" ? nextScheduleTime(job.spec, Date.now()) : undefined), job.spec.timeZone)}`;
|
|
162
|
+
const boundaries = [job.spec.startsAt && `从 ${scheduleTime(Date.parse(job.spec.startsAt), job.spec.timeZone)} 起`,
|
|
163
|
+
job.spec.endsAt && `至 ${scheduleTime(Date.parse(job.spec.endsAt), job.spec.timeZone)}`].filter(Boolean);
|
|
164
|
+
const prompt = scheduleDisplayPrompt(job);
|
|
162
165
|
elements.push(
|
|
163
|
-
md(`${time}\n时区:${escape(job.spec.timeZone)}`),
|
|
166
|
+
md(`${time}\n时区:${escape(job.spec.timeZone)}${boundaries.length ? `\n${boundaries.join(" · ")}` : ""}`),
|
|
164
167
|
{
|
|
165
168
|
...md(
|
|
166
169
|
`最晚开始:计划时间后 ${job.spec.maxDelayMinutes} 分钟 · ${job.spec.catchUpMinutes ? `错过 ${job.spec.catchUpMinutes} 分钟内补跑最近一次` : "错过不补跑"}`,
|
|
167
170
|
),
|
|
168
171
|
text_size: "notation",
|
|
169
172
|
},
|
|
170
|
-
md(`**Prompt**\n${escape(
|
|
173
|
+
md(`**Prompt**\n${escape(prompt.slice(0, 2000))}${prompt.length > 2000 ? "…" : ""}`),
|
|
171
174
|
);
|
|
172
175
|
}
|
|
173
176
|
if (job.notice) elements.push(md(escape(job.notice)));
|
|
@@ -251,6 +254,7 @@ export function renderScheduleForm(
|
|
|
251
254
|
job?: ScheduledJob,
|
|
252
255
|
localSessionId?: string,
|
|
253
256
|
): Record<string, unknown> {
|
|
257
|
+
const longPrompt = (job?.spec.prompt.length ?? 0) > 1000;
|
|
254
258
|
const field = (
|
|
255
259
|
name: string,
|
|
256
260
|
label: string,
|
|
@@ -273,9 +277,11 @@ export function renderScheduleForm(
|
|
|
273
277
|
name: "schedule_form",
|
|
274
278
|
elements: [
|
|
275
279
|
field("name", "名称", job?.spec.name ?? "定时任务", true, 120),
|
|
276
|
-
field("prompt", "Prompt", job?.spec.prompt ?? "",
|
|
280
|
+
field("prompt", longPrompt ? "Prompt(留空保留原文)" : "Prompt", longPrompt ? "" : job?.spec.prompt ?? "", !longPrompt && !job?.attachments),
|
|
277
281
|
field("cron", "Cron(五段,与执行时间二选一)", job?.spec.cron ?? ""),
|
|
278
282
|
field("at", "执行时间(ISO 格式,含时区)", job?.spec.at ?? ""),
|
|
283
|
+
field("startsAt", "重复计划开始时间(ISO,可选)", job?.spec.startsAt ?? ""),
|
|
284
|
+
field("endsAt", "重复计划结束时间(ISO,可选)", job?.spec.endsAt ?? ""),
|
|
279
285
|
field(
|
|
280
286
|
"timeZone",
|
|
281
287
|
"时区",
|
|
@@ -32,6 +32,8 @@ export function parseScheduleCommand(args: string[]): ScheduleCommand {
|
|
|
32
32
|
"--prompt",
|
|
33
33
|
"--cron",
|
|
34
34
|
"--at",
|
|
35
|
+
"--starts-at",
|
|
36
|
+
"--ends-at",
|
|
35
37
|
"--timezone",
|
|
36
38
|
"--max-delay",
|
|
37
39
|
"--catch-up",
|
|
@@ -54,6 +56,8 @@ export function parseScheduleCommand(args: string[]): ScheduleCommand {
|
|
|
54
56
|
...(values["--name"] !== undefined ? { name: values["--name"] } : {}),
|
|
55
57
|
...(values["--cron"] !== undefined ? { cron: values["--cron"] } : {}),
|
|
56
58
|
...(values["--at"] !== undefined ? { at: values["--at"] } : {}),
|
|
59
|
+
...(values["--starts-at"] !== undefined ? { startsAt: values["--starts-at"] } : {}),
|
|
60
|
+
...(values["--ends-at"] !== undefined ? { endsAt: values["--ends-at"] } : {}),
|
|
57
61
|
...(values["--timezone"] !== undefined
|
|
58
62
|
? { timeZone: values["--timezone"] }
|
|
59
63
|
: {}),
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import type Database from "better-sqlite3";
|
|
3
|
+
import { appendDownloadedFiles, defaultResourcePromptFromCounts } from "../utils/promptAttachments.js";
|
|
4
|
+
import { appendPromptQuotes, promptQuoteInstruction } from "../utils/promptQuotes.js";
|
|
3
5
|
import {
|
|
4
6
|
nextScheduleTime,
|
|
7
|
+
scheduleDisplayPrompt,
|
|
5
8
|
scheduleInputSchema,
|
|
6
9
|
type ScheduleInput,
|
|
7
10
|
type ScheduledJob,
|
|
@@ -17,6 +20,10 @@ const active = "'queued','dispatching','submitting','running','unknown'";
|
|
|
17
20
|
export class ScheduledTaskStore {
|
|
18
21
|
constructor(private readonly db: Database.Database) {}
|
|
19
22
|
|
|
23
|
+
getByRequest(request: string): ScheduledJob | undefined {
|
|
24
|
+
return this.get(`sched_${request.replaceAll("-", "")}`);
|
|
25
|
+
}
|
|
26
|
+
|
|
20
27
|
create(
|
|
21
28
|
input: ScheduleInput,
|
|
22
29
|
target: Pick<
|
|
@@ -24,28 +31,51 @@ export class ScheduledTaskStore {
|
|
|
24
31
|
"localSessionId" | "contextKey" | "replyMessageId" | "ownerId"
|
|
25
32
|
>,
|
|
26
33
|
now = Date.now(),
|
|
34
|
+
enableRequest?: string,
|
|
35
|
+
upload?: { attachments?: ScheduledJob["attachments"]; fingerprint: string },
|
|
27
36
|
): ScheduledJob {
|
|
28
37
|
const spec = scheduleInputSchema.parse(input);
|
|
29
|
-
|
|
38
|
+
const id = `sched_${enableRequest ? enableRequest.replaceAll("-", "") : randomUUID().replaceAll("-", "").slice(0, 12)}`;
|
|
39
|
+
const existing = enableRequest ? this.get(id) : undefined;
|
|
40
|
+
if (existing) {
|
|
41
|
+
const matches = existing.creationFingerprint
|
|
42
|
+
? existing.creationFingerprint === upload?.fingerprint
|
|
43
|
+
: !upload?.attachments && JSON.stringify(existing.spec) === JSON.stringify(spec);
|
|
44
|
+
if (existing.localSessionId !== target.localSessionId || existing.ownerId !== target.ownerId || !matches) {
|
|
45
|
+
throw new Error("该请求标识已用于另一项计划。");
|
|
46
|
+
}
|
|
47
|
+
return existing;
|
|
48
|
+
}
|
|
49
|
+
if (!spec.prompt) {
|
|
50
|
+
const attachments = upload?.attachments;
|
|
51
|
+
if (!attachments || (!attachments.images.length && !attachments.files.length && !attachments.quotes?.length)) throw new Error("请输入 Prompt 或添加附件。");
|
|
52
|
+
spec.prompt = promptQuoteInstruction(attachments.quotes) || defaultResourcePromptFromCounts(attachments.images.length, attachments.files.length);
|
|
53
|
+
}
|
|
54
|
+
const nextRunAt = nextScheduleTime(spec, now);
|
|
55
|
+
if (nextRunAt === undefined) throw new Error("执行时间必须在将来。");
|
|
30
56
|
const job: ScheduledJob = {
|
|
31
|
-
id
|
|
57
|
+
id,
|
|
32
58
|
revision: 1,
|
|
33
|
-
status: "draft",
|
|
59
|
+
status: enableRequest ? "enabled" : "draft",
|
|
60
|
+
...(enableRequest ? { nextRunAt } : {}),
|
|
34
61
|
...target,
|
|
35
62
|
spec,
|
|
63
|
+
...(upload?.attachments ? { attachments: upload.attachments } : {}),
|
|
64
|
+
...(upload ? { creationFingerprint: upload.fingerprint } : {}),
|
|
36
65
|
createdAt: now,
|
|
37
66
|
updatedAt: now,
|
|
38
67
|
};
|
|
39
68
|
this.db
|
|
40
69
|
.prepare(
|
|
41
70
|
`INSERT INTO scheduled_jobs (id, local_session_id, context_key, status, next_run_at, revision, value_json)
|
|
42
|
-
VALUES (?, ?, ?, ?,
|
|
71
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
43
72
|
)
|
|
44
73
|
.run(
|
|
45
74
|
job.id,
|
|
46
75
|
job.localSessionId,
|
|
47
76
|
job.contextKey,
|
|
48
77
|
job.status,
|
|
78
|
+
job.nextRunAt ?? null,
|
|
49
79
|
job.revision,
|
|
50
80
|
JSON.stringify(job),
|
|
51
81
|
);
|
|
@@ -74,6 +104,13 @@ export class ScheduledTaskStore {
|
|
|
74
104
|
return rows.map((row) => JSON.parse(row.value_json) as ScheduledJob);
|
|
75
105
|
}
|
|
76
106
|
|
|
107
|
+
listForSession(localSessionId: string, ownerId: string, limit: number, offset: number): ScheduledJob[] {
|
|
108
|
+
const rows = this.db.prepare(`SELECT value_json FROM scheduled_jobs WHERE local_session_id = ?
|
|
109
|
+
AND status != 'deleted' AND json_extract(value_json, '$.ownerId') = ? ORDER BY rowid DESC LIMIT ? OFFSET ?`)
|
|
110
|
+
.all(localSessionId, ownerId, limit, offset) as JsonRow[];
|
|
111
|
+
return rows.map((row) => JSON.parse(row.value_json) as ScheduledJob);
|
|
112
|
+
}
|
|
113
|
+
|
|
77
114
|
due(now: number): ScheduledJob[] {
|
|
78
115
|
return (
|
|
79
116
|
this.db
|
|
@@ -138,15 +175,21 @@ export class ScheduledTaskStore {
|
|
|
138
175
|
revision: number,
|
|
139
176
|
input: ScheduleInput,
|
|
140
177
|
now = Date.now(),
|
|
178
|
+
status: "draft" | "enabled" | "paused" = "draft",
|
|
141
179
|
): ScheduledJob {
|
|
142
180
|
const spec = scheduleInputSchema.parse(input);
|
|
143
|
-
|
|
181
|
+
const nextRunAt = nextScheduleTime(spec, now);
|
|
182
|
+
if (nextRunAt === undefined)
|
|
144
183
|
throw new Error("执行时间必须在将来。");
|
|
145
184
|
return this.db.transaction(() => {
|
|
146
185
|
const job = this.require(id, revision);
|
|
186
|
+
if (!spec.prompt) {
|
|
187
|
+
if (!job.attachments) throw new Error("请输入 Prompt 或添加附件。");
|
|
188
|
+
spec.prompt = promptQuoteInstruction(job.attachments.quotes) || defaultResourcePromptFromCounts(job.attachments.images.length, job.attachments.files.length);
|
|
189
|
+
}
|
|
147
190
|
this.cancelPending(id, "计划已编辑,等待重新确认。");
|
|
148
191
|
return this.update(
|
|
149
|
-
{ ...job, spec, status: "
|
|
192
|
+
{ ...job, spec, notice: undefined, status, nextRunAt: status === "enabled" ? nextRunAt : undefined },
|
|
150
193
|
now,
|
|
151
194
|
);
|
|
152
195
|
})();
|
|
@@ -247,17 +290,21 @@ export class ScheduledTaskStore {
|
|
|
247
290
|
);
|
|
248
291
|
if (!inserted.changes) return undefined;
|
|
249
292
|
if (!detail) {
|
|
293
|
+
const files = job.attachments?.files ?? [];
|
|
294
|
+
const images = job.attachments?.images ?? [];
|
|
295
|
+
const prompt = appendPromptQuotes(job.spec.prompt, job.attachments?.quotes);
|
|
250
296
|
this.db
|
|
251
297
|
.prepare(
|
|
252
298
|
`INSERT INTO queued_prompts (prompt_id, local_session_id, context_key, prompt_text,
|
|
253
|
-
display_prompt, local_image_paths_json, reply_message_id, created_at) VALUES (?, ?, ?, ?, ?,
|
|
299
|
+
display_prompt, local_image_paths_json, reply_message_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
254
300
|
)
|
|
255
301
|
.run(
|
|
256
302
|
run.id,
|
|
257
303
|
job.localSessionId,
|
|
258
304
|
job.contextKey,
|
|
259
|
-
|
|
260
|
-
`[定时任务:${job.spec.name} · ${new Date(scheduledFor).toISOString()}]\n${job
|
|
305
|
+
files.length ? appendDownloadedFiles(prompt, files) : prompt,
|
|
306
|
+
`[定时任务:${job.spec.name} · ${new Date(scheduledFor).toISOString()}]\n${scheduleDisplayPrompt(job)}`,
|
|
307
|
+
JSON.stringify(images),
|
|
261
308
|
job.replyMessageId ?? null,
|
|
262
309
|
new Date(now).toISOString(),
|
|
263
310
|
);
|
package/src/scheduling/types.ts
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { CronExpressionParser } from "cron-parser";
|
|
3
|
+
import type { PromptQuote } from "../utils/promptQuotes.js";
|
|
3
4
|
|
|
4
5
|
export const scheduleInputSchema = z
|
|
5
6
|
.object({
|
|
6
7
|
name: z.string().trim().min(1).max(120).default("定时任务"),
|
|
7
|
-
prompt: z.string().trim().
|
|
8
|
+
prompt: z.string().trim().max(24_000),
|
|
8
9
|
cron: z.string().trim().min(1).max(120).optional(),
|
|
9
10
|
at: z.string().trim().datetime({ offset: true }).optional(),
|
|
11
|
+
startsAt: z.string().trim().datetime({ offset: true }).optional(),
|
|
12
|
+
endsAt: z.string().trim().datetime({ offset: true }).optional(),
|
|
10
13
|
timeZone: z
|
|
11
14
|
.string()
|
|
12
15
|
.trim()
|
|
@@ -22,6 +25,10 @@ export const scheduleInputSchema = z
|
|
|
22
25
|
message: "请且仅指定 Cron 或带时区的 ISO 执行时间。",
|
|
23
26
|
});
|
|
24
27
|
}
|
|
28
|
+
if ((value.startsAt || value.endsAt) && !value.cron) context.addIssue({ code: "custom", message: "重复计划才支持指定起止时间。" });
|
|
29
|
+
if (value.startsAt && value.endsAt && Date.parse(value.startsAt) > Date.parse(value.endsAt)) {
|
|
30
|
+
context.addIssue({ code: "custom", message: "结束时间不能早于开始时间。" });
|
|
31
|
+
}
|
|
25
32
|
try {
|
|
26
33
|
new Intl.DateTimeFormat("en", { timeZone: value.timeZone }).format();
|
|
27
34
|
if (value.cron) {
|
|
@@ -82,11 +89,18 @@ export interface ScheduledJob {
|
|
|
82
89
|
replyMessageId?: string;
|
|
83
90
|
ownerId?: string;
|
|
84
91
|
spec: ScheduleSpec;
|
|
92
|
+
attachments?: ScheduledPromptAttachments;
|
|
93
|
+
creationFingerprint?: string;
|
|
85
94
|
nextRunAt?: number;
|
|
86
95
|
createdAt: number;
|
|
87
96
|
updatedAt: number;
|
|
88
97
|
notice?: string;
|
|
89
98
|
}
|
|
99
|
+
export interface ScheduledPromptAttachments {
|
|
100
|
+
images: string[];
|
|
101
|
+
files: Array<{ fileName: string; filePath: string }>;
|
|
102
|
+
quotes?: PromptQuote[];
|
|
103
|
+
}
|
|
90
104
|
export type ScheduledRunStatus =
|
|
91
105
|
| "queued"
|
|
92
106
|
| "dispatching"
|
|
@@ -118,24 +132,33 @@ export function nextScheduleTime(
|
|
|
118
132
|
const time = Date.parse(spec.at);
|
|
119
133
|
return time > after ? time : undefined;
|
|
120
134
|
}
|
|
121
|
-
|
|
122
|
-
currentDate: new Date(after),
|
|
135
|
+
const time = CronExpressionParser.parse(spec.cron!, {
|
|
136
|
+
currentDate: new Date(spec.startsAt ? Math.max(after, Date.parse(spec.startsAt) - 1) : after),
|
|
123
137
|
tz: spec.timeZone,
|
|
124
138
|
})
|
|
125
139
|
.next()
|
|
126
140
|
.getTime();
|
|
141
|
+
return !spec.endsAt || time <= Date.parse(spec.endsAt) ? time : undefined;
|
|
127
142
|
}
|
|
128
143
|
|
|
129
144
|
export function latestScheduleTime(spec: ScheduleSpec, now: number): number {
|
|
130
145
|
if (spec.at) return Date.parse(spec.at);
|
|
131
146
|
return CronExpressionParser.parse(spec.cron!, {
|
|
132
|
-
currentDate: new Date(now + 1),
|
|
147
|
+
currentDate: new Date((spec.endsAt ? Math.min(now, Date.parse(spec.endsAt)) : now) + 1),
|
|
133
148
|
tz: spec.timeZone,
|
|
134
149
|
})
|
|
135
150
|
.prev()
|
|
136
151
|
.getTime();
|
|
137
152
|
}
|
|
138
153
|
|
|
154
|
+
export function scheduleDisplayPrompt(job: ScheduledJob, prompt = job.spec.prompt): string {
|
|
155
|
+
const names = job.attachments?.files.map(file => file.fileName) ?? [];
|
|
156
|
+
const images = job.attachments?.images.length ?? 0;
|
|
157
|
+
const quotes = job.attachments?.quotes?.length ?? 0;
|
|
158
|
+
const attachments = [...(images ? [`${images} 张图片`] : []), ...names, ...(quotes ? [`${quotes} 条引用或批注`] : [])];
|
|
159
|
+
return [prompt, ...(attachments.length ? [`附件:${attachments.join("、")}`] : [])].join("\n\n");
|
|
160
|
+
}
|
|
161
|
+
|
|
139
162
|
export function scheduleTime(
|
|
140
163
|
time: number | undefined,
|
|
141
164
|
timeZone: string,
|