@keyou007/agent-bot 0.1.27-alpha.3 → 0.1.27-alpha.4
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 +18 -0
- package/README.md +77 -12
- package/README.zh.md +77 -12
- 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 +1935 -232
- package/assets/workspace.css +360 -35
- package/assets/workspace.js +2115 -249
- 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 +26 -14
- 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 +40 -10
- 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 +133 -117
- 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 +23 -269
- 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 +15 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +20 -5
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +881 -79
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +105 -0
- package/dist/local-files/WorkspaceTimeline.js.map +1 -0
- package/dist/presentation/OutboundRouter.js +13 -6
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +28 -21
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +229 -92
- 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 +51 -12
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +18 -4
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +145 -19
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +143 -36
- 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 +20 -0
- package/dist/utils/promptAttachments.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 +22 -8
- 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 +38 -10
- package/src/local-files/LiveMarkup.ts +103 -0
- package/src/local-files/LocalFileViewerServer.ts +120 -120
- 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 +23 -254
- package/src/local-files/WorkspaceFileEvents.ts +186 -0
- package/src/local-files/WorkspaceFiles.ts +72 -5
- package/src/local-files/WorkspaceImages.ts +10 -0
- package/src/local-files/WorkspacePage.ts +20 -5
- package/src/local-files/WorkspaceSessions.ts +811 -82
- package/src/local-files/WorkspaceTimeline.ts +109 -0
- package/src/presentation/OutboundRouter.ts +15 -4
- package/src/presentation/TurnStateReducer.ts +27 -18
- package/src/presentation/turnViewTypes.ts +2 -0
- package/src/proxy/ProxySessionController.ts +226 -77
- 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 +54 -9
- package/src/scheduling/types.ts +24 -4
- package/src/state/StateStore.ts +157 -20
- package/src/state/TurnPreviewJournal.ts +138 -34
- 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 +24 -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,9 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import type Database from "better-sqlite3";
|
|
3
|
+
import { appendDownloadedFiles, defaultResourcePromptFromCounts } from "../utils/promptAttachments.js";
|
|
3
4
|
import {
|
|
4
5
|
nextScheduleTime,
|
|
6
|
+
scheduleDisplayPrompt,
|
|
5
7
|
scheduleInputSchema,
|
|
6
8
|
type ScheduleInput,
|
|
7
9
|
type ScheduledJob,
|
|
@@ -17,6 +19,10 @@ const active = "'queued','dispatching','submitting','running','unknown'";
|
|
|
17
19
|
export class ScheduledTaskStore {
|
|
18
20
|
constructor(private readonly db: Database.Database) {}
|
|
19
21
|
|
|
22
|
+
getByRequest(request: string): ScheduledJob | undefined {
|
|
23
|
+
return this.get(`sched_${request.replaceAll("-", "")}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
20
26
|
create(
|
|
21
27
|
input: ScheduleInput,
|
|
22
28
|
target: Pick<
|
|
@@ -24,28 +30,51 @@ export class ScheduledTaskStore {
|
|
|
24
30
|
"localSessionId" | "contextKey" | "replyMessageId" | "ownerId"
|
|
25
31
|
>,
|
|
26
32
|
now = Date.now(),
|
|
33
|
+
enableRequest?: string,
|
|
34
|
+
upload?: { attachments?: ScheduledJob["attachments"]; fingerprint: string },
|
|
27
35
|
): ScheduledJob {
|
|
28
36
|
const spec = scheduleInputSchema.parse(input);
|
|
29
|
-
|
|
37
|
+
const id = `sched_${enableRequest ? enableRequest.replaceAll("-", "") : randomUUID().replaceAll("-", "").slice(0, 12)}`;
|
|
38
|
+
const existing = enableRequest ? this.get(id) : undefined;
|
|
39
|
+
if (existing) {
|
|
40
|
+
const matches = existing.creationFingerprint
|
|
41
|
+
? existing.creationFingerprint === upload?.fingerprint
|
|
42
|
+
: !upload?.attachments && JSON.stringify(existing.spec) === JSON.stringify(spec);
|
|
43
|
+
if (existing.localSessionId !== target.localSessionId || existing.ownerId !== target.ownerId || !matches) {
|
|
44
|
+
throw new Error("该请求标识已用于另一项计划。");
|
|
45
|
+
}
|
|
46
|
+
return existing;
|
|
47
|
+
}
|
|
48
|
+
if (!spec.prompt) {
|
|
49
|
+
const attachments = upload?.attachments;
|
|
50
|
+
if (!attachments || (!attachments.images.length && !attachments.files.length)) throw new Error("请输入 Prompt 或添加附件。");
|
|
51
|
+
spec.prompt = defaultResourcePromptFromCounts(attachments.images.length, attachments.files.length);
|
|
52
|
+
}
|
|
53
|
+
const nextRunAt = nextScheduleTime(spec, now);
|
|
54
|
+
if (nextRunAt === undefined) throw new Error("执行时间必须在将来。");
|
|
30
55
|
const job: ScheduledJob = {
|
|
31
|
-
id
|
|
56
|
+
id,
|
|
32
57
|
revision: 1,
|
|
33
|
-
status: "draft",
|
|
58
|
+
status: enableRequest ? "enabled" : "draft",
|
|
59
|
+
...(enableRequest ? { nextRunAt } : {}),
|
|
34
60
|
...target,
|
|
35
61
|
spec,
|
|
62
|
+
...(upload?.attachments ? { attachments: upload.attachments } : {}),
|
|
63
|
+
...(upload ? { creationFingerprint: upload.fingerprint } : {}),
|
|
36
64
|
createdAt: now,
|
|
37
65
|
updatedAt: now,
|
|
38
66
|
};
|
|
39
67
|
this.db
|
|
40
68
|
.prepare(
|
|
41
69
|
`INSERT INTO scheduled_jobs (id, local_session_id, context_key, status, next_run_at, revision, value_json)
|
|
42
|
-
VALUES (?, ?, ?, ?,
|
|
70
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
43
71
|
)
|
|
44
72
|
.run(
|
|
45
73
|
job.id,
|
|
46
74
|
job.localSessionId,
|
|
47
75
|
job.contextKey,
|
|
48
76
|
job.status,
|
|
77
|
+
job.nextRunAt ?? null,
|
|
49
78
|
job.revision,
|
|
50
79
|
JSON.stringify(job),
|
|
51
80
|
);
|
|
@@ -74,6 +103,13 @@ export class ScheduledTaskStore {
|
|
|
74
103
|
return rows.map((row) => JSON.parse(row.value_json) as ScheduledJob);
|
|
75
104
|
}
|
|
76
105
|
|
|
106
|
+
listForSession(localSessionId: string, ownerId: string, limit: number, offset: number): ScheduledJob[] {
|
|
107
|
+
const rows = this.db.prepare(`SELECT value_json FROM scheduled_jobs WHERE local_session_id = ?
|
|
108
|
+
AND status != 'deleted' AND json_extract(value_json, '$.ownerId') = ? ORDER BY rowid DESC LIMIT ? OFFSET ?`)
|
|
109
|
+
.all(localSessionId, ownerId, limit, offset) as JsonRow[];
|
|
110
|
+
return rows.map((row) => JSON.parse(row.value_json) as ScheduledJob);
|
|
111
|
+
}
|
|
112
|
+
|
|
77
113
|
due(now: number): ScheduledJob[] {
|
|
78
114
|
return (
|
|
79
115
|
this.db
|
|
@@ -138,15 +174,21 @@ export class ScheduledTaskStore {
|
|
|
138
174
|
revision: number,
|
|
139
175
|
input: ScheduleInput,
|
|
140
176
|
now = Date.now(),
|
|
177
|
+
status: "draft" | "enabled" | "paused" = "draft",
|
|
141
178
|
): ScheduledJob {
|
|
142
179
|
const spec = scheduleInputSchema.parse(input);
|
|
143
|
-
|
|
180
|
+
const nextRunAt = nextScheduleTime(spec, now);
|
|
181
|
+
if (nextRunAt === undefined)
|
|
144
182
|
throw new Error("执行时间必须在将来。");
|
|
145
183
|
return this.db.transaction(() => {
|
|
146
184
|
const job = this.require(id, revision);
|
|
185
|
+
if (!spec.prompt) {
|
|
186
|
+
if (!job.attachments) throw new Error("请输入 Prompt 或添加附件。");
|
|
187
|
+
spec.prompt = defaultResourcePromptFromCounts(job.attachments.images.length, job.attachments.files.length);
|
|
188
|
+
}
|
|
147
189
|
this.cancelPending(id, "计划已编辑,等待重新确认。");
|
|
148
190
|
return this.update(
|
|
149
|
-
{ ...job, spec, status: "
|
|
191
|
+
{ ...job, spec, notice: undefined, status, nextRunAt: status === "enabled" ? nextRunAt : undefined },
|
|
150
192
|
now,
|
|
151
193
|
);
|
|
152
194
|
})();
|
|
@@ -247,17 +289,20 @@ export class ScheduledTaskStore {
|
|
|
247
289
|
);
|
|
248
290
|
if (!inserted.changes) return undefined;
|
|
249
291
|
if (!detail) {
|
|
292
|
+
const files = job.attachments?.files ?? [];
|
|
293
|
+
const images = job.attachments?.images ?? [];
|
|
250
294
|
this.db
|
|
251
295
|
.prepare(
|
|
252
296
|
`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 (?, ?, ?, ?, ?,
|
|
297
|
+
display_prompt, local_image_paths_json, reply_message_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
254
298
|
)
|
|
255
299
|
.run(
|
|
256
300
|
run.id,
|
|
257
301
|
job.localSessionId,
|
|
258
302
|
job.contextKey,
|
|
259
|
-
job.spec.prompt,
|
|
260
|
-
`[定时任务:${job.spec.name} · ${new Date(scheduledFor).toISOString()}]\n${job
|
|
303
|
+
files.length ? appendDownloadedFiles(job.spec.prompt, files) : job.spec.prompt,
|
|
304
|
+
`[定时任务:${job.spec.name} · ${new Date(scheduledFor).toISOString()}]\n${scheduleDisplayPrompt(job)}`,
|
|
305
|
+
JSON.stringify(images),
|
|
261
306
|
job.replyMessageId ?? null,
|
|
262
307
|
new Date(now).toISOString(),
|
|
263
308
|
);
|
package/src/scheduling/types.ts
CHANGED
|
@@ -4,9 +4,11 @@ import { CronExpressionParser } from "cron-parser";
|
|
|
4
4
|
export const scheduleInputSchema = z
|
|
5
5
|
.object({
|
|
6
6
|
name: z.string().trim().min(1).max(120).default("定时任务"),
|
|
7
|
-
prompt: z.string().trim().
|
|
7
|
+
prompt: z.string().trim().max(24_000),
|
|
8
8
|
cron: z.string().trim().min(1).max(120).optional(),
|
|
9
9
|
at: z.string().trim().datetime({ offset: true }).optional(),
|
|
10
|
+
startsAt: z.string().trim().datetime({ offset: true }).optional(),
|
|
11
|
+
endsAt: z.string().trim().datetime({ offset: true }).optional(),
|
|
10
12
|
timeZone: z
|
|
11
13
|
.string()
|
|
12
14
|
.trim()
|
|
@@ -22,6 +24,10 @@ export const scheduleInputSchema = z
|
|
|
22
24
|
message: "请且仅指定 Cron 或带时区的 ISO 执行时间。",
|
|
23
25
|
});
|
|
24
26
|
}
|
|
27
|
+
if ((value.startsAt || value.endsAt) && !value.cron) context.addIssue({ code: "custom", message: "重复计划才支持指定起止时间。" });
|
|
28
|
+
if (value.startsAt && value.endsAt && Date.parse(value.startsAt) > Date.parse(value.endsAt)) {
|
|
29
|
+
context.addIssue({ code: "custom", message: "结束时间不能早于开始时间。" });
|
|
30
|
+
}
|
|
25
31
|
try {
|
|
26
32
|
new Intl.DateTimeFormat("en", { timeZone: value.timeZone }).format();
|
|
27
33
|
if (value.cron) {
|
|
@@ -82,11 +88,17 @@ export interface ScheduledJob {
|
|
|
82
88
|
replyMessageId?: string;
|
|
83
89
|
ownerId?: string;
|
|
84
90
|
spec: ScheduleSpec;
|
|
91
|
+
attachments?: ScheduledPromptAttachments;
|
|
92
|
+
creationFingerprint?: string;
|
|
85
93
|
nextRunAt?: number;
|
|
86
94
|
createdAt: number;
|
|
87
95
|
updatedAt: number;
|
|
88
96
|
notice?: string;
|
|
89
97
|
}
|
|
98
|
+
export interface ScheduledPromptAttachments {
|
|
99
|
+
images: string[];
|
|
100
|
+
files: Array<{ fileName: string; filePath: string }>;
|
|
101
|
+
}
|
|
90
102
|
export type ScheduledRunStatus =
|
|
91
103
|
| "queued"
|
|
92
104
|
| "dispatching"
|
|
@@ -118,24 +130,32 @@ export function nextScheduleTime(
|
|
|
118
130
|
const time = Date.parse(spec.at);
|
|
119
131
|
return time > after ? time : undefined;
|
|
120
132
|
}
|
|
121
|
-
|
|
122
|
-
currentDate: new Date(after),
|
|
133
|
+
const time = CronExpressionParser.parse(spec.cron!, {
|
|
134
|
+
currentDate: new Date(spec.startsAt ? Math.max(after, Date.parse(spec.startsAt) - 1) : after),
|
|
123
135
|
tz: spec.timeZone,
|
|
124
136
|
})
|
|
125
137
|
.next()
|
|
126
138
|
.getTime();
|
|
139
|
+
return !spec.endsAt || time <= Date.parse(spec.endsAt) ? time : undefined;
|
|
127
140
|
}
|
|
128
141
|
|
|
129
142
|
export function latestScheduleTime(spec: ScheduleSpec, now: number): number {
|
|
130
143
|
if (spec.at) return Date.parse(spec.at);
|
|
131
144
|
return CronExpressionParser.parse(spec.cron!, {
|
|
132
|
-
currentDate: new Date(now + 1),
|
|
145
|
+
currentDate: new Date((spec.endsAt ? Math.min(now, Date.parse(spec.endsAt)) : now) + 1),
|
|
133
146
|
tz: spec.timeZone,
|
|
134
147
|
})
|
|
135
148
|
.prev()
|
|
136
149
|
.getTime();
|
|
137
150
|
}
|
|
138
151
|
|
|
152
|
+
export function scheduleDisplayPrompt(job: ScheduledJob, prompt = job.spec.prompt): string {
|
|
153
|
+
const names = job.attachments?.files.map(file => file.fileName) ?? [];
|
|
154
|
+
const images = job.attachments?.images.length ?? 0;
|
|
155
|
+
const attachments = [...(images ? [`${images} 张图片`] : []), ...names];
|
|
156
|
+
return [prompt, ...(attachments.length ? [`附件:${attachments.join("、")}`] : [])].join("\n\n");
|
|
157
|
+
}
|
|
158
|
+
|
|
139
159
|
export function scheduleTime(
|
|
140
160
|
time: number | undefined,
|
|
141
161
|
timeZone: string,
|
package/src/state/StateStore.ts
CHANGED
|
@@ -9,7 +9,8 @@ import { migrations } from "./migrations.js";
|
|
|
9
9
|
import { ExecutionProvenanceStore } from "./ExecutionProvenanceStore.js";
|
|
10
10
|
import { InboundMessageStore } from "./InboundMessageStore.js";
|
|
11
11
|
import type { UpdateCheckSchedule, UpdateNotice } from "../updates/types.js";
|
|
12
|
-
import type { ConversationTurn, RuntimeExecutionSettings } from "../runtime/types.js";
|
|
12
|
+
import type { ConversationTurn, PlanStep, RuntimeExecutionSettings } from "../runtime/types.js";
|
|
13
|
+
import { previewToolHeading } from "../local-files/ToolCommandDisplay.js";
|
|
13
14
|
|
|
14
15
|
export interface PendingProviderSettings {
|
|
15
16
|
localSessionId: string;
|
|
@@ -303,6 +304,10 @@ export class StateStore {
|
|
|
303
304
|
this.previews = new TurnPreviewJournal(path.join(path.dirname(sqlitePath), "turn-previews"), onPreviewError);
|
|
304
305
|
fs.mkdirSync(path.dirname(sqlitePath), { recursive: true });
|
|
305
306
|
this.db = new Database(sqlitePath);
|
|
307
|
+
this.db.function("workspace_tool_heading", { deterministic: true }, (title: string | null, kind: string | null, command: string | null) => {
|
|
308
|
+
const heading = previewToolHeading({ title: title ?? "", kind: kind ?? "工具", command: command ?? undefined }, "命令");
|
|
309
|
+
return JSON.stringify({ ...heading, title: heading.title.slice(0, 240) });
|
|
310
|
+
});
|
|
306
311
|
this.db.pragma("journal_mode = WAL");
|
|
307
312
|
for (const migration of migrations) {
|
|
308
313
|
this.db.exec(migration);
|
|
@@ -648,6 +653,21 @@ export class StateStore {
|
|
|
648
653
|
return rows.map(mapQueuedPrompt);
|
|
649
654
|
}
|
|
650
655
|
|
|
656
|
+
getQueuedPrompt(localSessionId: string, promptId: string): QueuedPromptRecord | undefined {
|
|
657
|
+
const row = this.db.prepare("SELECT * FROM queued_prompts WHERE local_session_id = ? AND prompt_id = ?")
|
|
658
|
+
.get(localSessionId, promptId) as QueuedPromptRow | undefined;
|
|
659
|
+
return row ? mapQueuedPrompt(row) : undefined;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
updateQueuedPrompt(previous: QueuedPromptRecord, content: Pick<QueuedPromptRecord, "text" | "displayPrompt">): boolean {
|
|
663
|
+
const updated = this.db.prepare(`
|
|
664
|
+
UPDATE queued_prompts SET prompt_text = ?, display_prompt = ?
|
|
665
|
+
WHERE local_session_id = ? AND prompt_id = ? AND prompt_text = ? AND display_prompt IS ?
|
|
666
|
+
`).run(content.text, content.displayPrompt ?? null, previous.localSessionId, previous.promptId,
|
|
667
|
+
previous.text, previous.displayPrompt ?? null);
|
|
668
|
+
return updated.changes === 1;
|
|
669
|
+
}
|
|
670
|
+
|
|
651
671
|
hasQueuedPrompt(promptId: string): boolean {
|
|
652
672
|
return Boolean(this.db.prepare("SELECT 1 FROM queued_prompts WHERE prompt_id = ?").get(promptId));
|
|
653
673
|
}
|
|
@@ -687,6 +707,7 @@ export class StateStore {
|
|
|
687
707
|
if (!row) return undefined;
|
|
688
708
|
this.db.prepare("DELETE FROM queued_prompts WHERE prompt_id = ?").run(row.prompt_id);
|
|
689
709
|
if (!this.schedules.claimStart(row.prompt_id)) continue;
|
|
710
|
+
const prompt = mapQueuedPrompt(row);
|
|
690
711
|
if (this.schedules.getRun(row.prompt_id)) {
|
|
691
712
|
const existing = this.getTurnAttempt(row.prompt_id);
|
|
692
713
|
if (existing) {
|
|
@@ -698,10 +719,11 @@ export class StateStore {
|
|
|
698
719
|
executionGeneration: this.executionGeneration(localSessionId) });
|
|
699
720
|
} else {
|
|
700
721
|
this.createTurnAttempt({ attemptId: row.prompt_id, localSessionId, contextKey: row.context_key,
|
|
701
|
-
promptText: row.prompt_text,
|
|
722
|
+
promptText: row.prompt_text, localImagePaths: prompt.localImagePaths,
|
|
723
|
+
replyMessageId: row.reply_message_id ?? undefined });
|
|
702
724
|
}
|
|
703
725
|
}
|
|
704
|
-
return
|
|
726
|
+
return prompt;
|
|
705
727
|
}
|
|
706
728
|
});
|
|
707
729
|
return take();
|
|
@@ -721,6 +743,21 @@ export class StateStore {
|
|
|
721
743
|
return cancel();
|
|
722
744
|
}
|
|
723
745
|
|
|
746
|
+
cancelWorkspaceQueuedPrompt(promptId: string, localSessionId: string, request: string) {
|
|
747
|
+
return this.db.transaction(() => {
|
|
748
|
+
const fingerprint = JSON.stringify(["cancel-queued-prompt", localSessionId, promptId]);
|
|
749
|
+
const previous = this.workspaceRequest(request);
|
|
750
|
+
if (previous) {
|
|
751
|
+
if (previous.fingerprint !== fingerprint) throw new Error("该请求标识已用于另一项操作。");
|
|
752
|
+
return { cancelled: previous.status === "accepted", prompt: undefined };
|
|
753
|
+
}
|
|
754
|
+
this.beginWorkspaceRequest(request, localSessionId, fingerprint);
|
|
755
|
+
const prompt = this.cancelQueuedPrompt(promptId, localSessionId);
|
|
756
|
+
this.updateWorkspaceRequest(request, prompt ? "accepted" : "stale");
|
|
757
|
+
return { cancelled: Boolean(prompt), prompt };
|
|
758
|
+
})();
|
|
759
|
+
}
|
|
760
|
+
|
|
724
761
|
createTurnAttempt(input: {
|
|
725
762
|
attemptId: string;
|
|
726
763
|
localSessionId: string;
|
|
@@ -1290,6 +1327,27 @@ export class StateStore {
|
|
|
1290
1327
|
})();
|
|
1291
1328
|
}
|
|
1292
1329
|
|
|
1330
|
+
listTaskMetadata(localSessionId: string, kind: string): { key: string; value: string }[] {
|
|
1331
|
+
return this.db.prepare("SELECT key, value FROM task_metadata WHERE local_session_id = ? AND kind = ? ORDER BY value")
|
|
1332
|
+
.all(localSessionId, kind) as { key: string; value: string }[];
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
getTaskMetadata(localSessionId: string, kind: string, key: string): string | undefined {
|
|
1336
|
+
const row = this.db.prepare("SELECT value FROM task_metadata WHERE local_session_id = ? AND kind = ? AND key = ?")
|
|
1337
|
+
.get(localSessionId, kind, key) as { value: string } | undefined;
|
|
1338
|
+
return row?.value;
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
setTaskMetadata(localSessionId: string, kind: string, key: string, value: string): void {
|
|
1342
|
+
this.db.prepare(`INSERT INTO task_metadata (local_session_id, kind, key, value) VALUES (?, ?, ?, ?)
|
|
1343
|
+
ON CONFLICT (local_session_id, kind, key) DO UPDATE SET value = excluded.value`).run(localSessionId, kind, key, value);
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
removeTaskMetadata(localSessionId: string, kind: string, key: string): boolean {
|
|
1347
|
+
return this.db.prepare("DELETE FROM task_metadata WHERE local_session_id = ? AND kind = ? AND key = ?")
|
|
1348
|
+
.run(localSessionId, kind, key).changes > 0;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1293
1351
|
workspaceRequest(id: string) {
|
|
1294
1352
|
return this.db.prepare(`SELECT local_session_id AS localSessionId, fingerprint, status, posted, message
|
|
1295
1353
|
FROM workspace_requests WHERE id = ?`).get(id) as
|
|
@@ -1318,34 +1376,71 @@ export class StateStore {
|
|
|
1318
1376
|
workspaceTurnPage(localSessionId: string, head: string | undefined, before?: string, limit = 20): {
|
|
1319
1377
|
ids: string[]; more: boolean; beforeMissing: boolean;
|
|
1320
1378
|
} {
|
|
1379
|
+
const ids: string[] = [];
|
|
1380
|
+
let found = !before;
|
|
1381
|
+
for (const id of this.workspaceTurnChain(localSessionId, head)) {
|
|
1382
|
+
if (found) ids.push(id);
|
|
1383
|
+
if (id === before) found = true;
|
|
1384
|
+
if (ids.length > limit) break;
|
|
1385
|
+
}
|
|
1386
|
+
return { ids: ids.slice(0, limit), more: ids.length > limit, beforeMissing: !found };
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
workspaceTurnsAfter(localSessionId: string, head: string | undefined, after: string, limit: number): {
|
|
1390
|
+
ids: string[]; more: boolean; cursorMissing: boolean;
|
|
1391
|
+
} {
|
|
1392
|
+
if (after === head) return { ids: [], more: false, cursorMissing: false };
|
|
1393
|
+
// Walk the current branch from its head, retaining only the closest successors of the cursor.
|
|
1394
|
+
const nearest: string[] = [];
|
|
1395
|
+
for (const id of this.workspaceTurnChain(localSessionId, head)) {
|
|
1396
|
+
if (id === after) return { ids: nearest.slice(-limit).reverse(), more: nearest.length > limit, cursorMissing: false };
|
|
1397
|
+
if (nearest.length > limit) nearest.shift();
|
|
1398
|
+
nearest.push(id);
|
|
1399
|
+
}
|
|
1400
|
+
return { ids: [], more: false, cursorMissing: true };
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
workspaceConversationMetrics(localSessionId: string, head: string | undefined) {
|
|
1404
|
+
const readUsage = this.db.prepare(`SELECT json_extract(snapshot_json, '$.tokenUsageTotalCumulative') AS totalTokens
|
|
1405
|
+
FROM turn_snapshots WHERE turn_id = ? AND local_session_id = ?`);
|
|
1406
|
+
let turnCount = 0;
|
|
1407
|
+
let totalTokens: number | undefined;
|
|
1408
|
+
for (const id of this.workspaceTurnChain(localSessionId, head)) {
|
|
1409
|
+
turnCount++;
|
|
1410
|
+
if (totalTokens !== undefined || turnCount > 20) continue;
|
|
1411
|
+
// Use the latest published total from this task, including while its next turn is starting.
|
|
1412
|
+
const tokens = (readUsage.get(id, localSessionId) as { totalTokens?: unknown } | undefined)?.totalTokens;
|
|
1413
|
+
if (typeof tokens === "number" && Number.isSafeInteger(tokens) && tokens >= 0) totalTokens = tokens;
|
|
1414
|
+
}
|
|
1415
|
+
return { turnCount, totalTokens };
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
private *workspaceTurnChain(localSessionId: string, head: string | undefined): IterableIterator<string> {
|
|
1321
1419
|
const read = this.db.prepare(`SELECT s.local_session_id AS owner, p.turn_id AS linked, p.parent_turn_id AS parent
|
|
1322
1420
|
FROM turn_snapshots s LEFT JOIN turn_parent_links p ON p.turn_id = s.turn_id WHERE s.turn_id = ?`);
|
|
1323
1421
|
type Node = { owner: string; linked: string | null; parent: string | null };
|
|
1324
1422
|
let id = head;
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
let found = !before;
|
|
1328
|
-
while (id && !seen.has(id) && seen.size < 20_000 && ids.length <= limit) {
|
|
1423
|
+
const seen = new Set<string>(), backfilled = new Set<string>();
|
|
1424
|
+
while (id && !seen.has(id) && seen.size < 20_000) {
|
|
1329
1425
|
seen.add(id);
|
|
1330
1426
|
let node = read.get(id) as Node | undefined;
|
|
1331
1427
|
if (!node || seen.size === 1 && node.owner !== localSessionId && !this.hasTaskHistoryTurn(localSessionId, id)) break;
|
|
1332
|
-
if (
|
|
1428
|
+
if (!node.linked && !backfilled.has(node.owner)) {
|
|
1333
1429
|
this.backfillTurnParents(node.owner);
|
|
1430
|
+
backfilled.add(node.owner);
|
|
1334
1431
|
node = read.get(id) as Node;
|
|
1335
|
-
fallback = false;
|
|
1336
1432
|
}
|
|
1337
|
-
|
|
1338
|
-
if (id === before) found = true;
|
|
1433
|
+
yield id;
|
|
1339
1434
|
id = node.parent ?? (seen.size === 1 && node.owner === localSessionId
|
|
1340
1435
|
? this.findForkSourceTurnId(localSessionId) : undefined);
|
|
1341
1436
|
}
|
|
1342
|
-
return { ids: ids.slice(0, limit), more: ids.length > limit, beforeMissing: !found };
|
|
1343
1437
|
}
|
|
1344
1438
|
|
|
1345
1439
|
workspaceTurnText(turnId: string) {
|
|
1346
1440
|
return this.db.prepare(`SELECT updated_at AS revision,
|
|
1347
1441
|
substr(json_extract(snapshot_json, '$.prompt'), 1, 24001) AS prompt,
|
|
1348
1442
|
snapshot_json -> '$.promptImagePaths' AS promptImages,
|
|
1443
|
+
json_extract(snapshot_json, '$.promptRequestId') AS promptRequestId,
|
|
1349
1444
|
substr(json_extract(snapshot_json, '$.finalResponse'), 1, 48001) AS answer,
|
|
1350
1445
|
substr(json_extract(snapshot_json, '$.assistantText'), 1, 48001) AS live,
|
|
1351
1446
|
substr(json_extract(snapshot_json, '$.error'), 1, 3000) AS error,
|
|
@@ -1353,18 +1448,56 @@ export class StateStore {
|
|
|
1353
1448
|
json_extract(snapshot_json, '$.status') AS status,
|
|
1354
1449
|
json_extract(snapshot_json, '$.startedAt') AS startedAt,
|
|
1355
1450
|
json_extract(snapshot_json, '$.historyDetail') AS detail,
|
|
1356
|
-
(
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1451
|
+
coalesce(json_array_length(snapshot_json, '$.fileSummary'), 0) AS changeCount,
|
|
1452
|
+
snapshot_json -> '$.fileSummary' AS changeSummary,
|
|
1453
|
+
(coalesce(json_extract(snapshot_json, '$.activitiesTruncated'), 0)
|
|
1454
|
+
OR coalesce(json_array_length(snapshot_json, '$.activities'), 0) > 80) AS compact,
|
|
1455
|
+
(SELECT json_group_array(json_object('kind', kind, 'id', id, 'text', body, 'images', json(images),
|
|
1456
|
+
'heading', json(heading), 'toolKind', toolKind, 'status', status, 'startedAt', toolStart, 'completedAt', toolEnd) ORDER BY ordinal) FROM (
|
|
1457
|
+
SELECT key AS ordinal, json_extract(value, '$.kind') AS kind, json_extract(value, '$.id') AS id,
|
|
1458
|
+
substr(json_extract(value, '$.text'), 1, 4000) AS body, value -> '$.localImagePaths' AS images,
|
|
1459
|
+
CASE WHEN json_extract(value, '$.kind') = 'tool' THEN workspace_tool_heading(json_extract(value, '$.tool.title'),
|
|
1460
|
+
json_extract(value, '$.tool.kind'), json_extract(value, '$.tool.command')) END AS heading,
|
|
1461
|
+
json_extract(value, '$.tool.kind') AS toolKind, json_extract(value, '$.tool.status') AS status,
|
|
1462
|
+
json_extract(value, '$.tool.startedAt') AS toolStart, json_extract(value, '$.tool.completedAt') AS toolEnd
|
|
1463
|
+
FROM json_each(snapshot_json, '$.activities') ORDER BY key DESC LIMIT 80)) AS activities,
|
|
1464
|
+
(SELECT json_group_array(json_object('id', id, 'after', after, 'parts', json(parts))
|
|
1465
|
+
ORDER BY ordinal) FROM (
|
|
1466
|
+
SELECT item.key AS ordinal, json_extract(item.value, '$.itemId') AS id,
|
|
1467
|
+
json_extract(item.value, '$.afterActivityId') AS after,
|
|
1468
|
+
(SELECT json_group_array(json_object('index', section, 'text', snippet) ORDER BY section) FROM (
|
|
1469
|
+
SELECT part.key AS section, substr(part.value, 1, 512) AS snippet
|
|
1470
|
+
FROM json_each(item.value, '$.summary') AS part
|
|
1471
|
+
WHERE part.type = 'text' AND trim(part.value) != '' ORDER BY part.key DESC LIMIT 16)) AS parts
|
|
1472
|
+
FROM json_each(snapshot_json, '$.reasoningItems') AS item ORDER BY item.key DESC LIMIT 32)) AS reasoning
|
|
1362
1473
|
FROM turn_snapshots WHERE turn_id = ?`).get(turnId) as {
|
|
1363
|
-
revision: string; prompt: string | null; promptImages: string | null; answer: string | null; live: string | null;
|
|
1364
|
-
error: string | null; notice: string | null; status: string; startedAt: number; detail: string | null;
|
|
1474
|
+
revision: string; prompt: string | null; promptImages: string | null; promptRequestId: string | null; answer: string | null; live: string | null;
|
|
1475
|
+
error: string | null; notice: string | null; status: string; startedAt: number; detail: string | null;
|
|
1476
|
+
changeCount: number; changeSummary: string | null; compact: number; activities: string; reasoning: string;
|
|
1365
1477
|
} | undefined;
|
|
1366
1478
|
}
|
|
1367
1479
|
|
|
1480
|
+
workspaceTurnPlan(turnId: string): PlanStep[] {
|
|
1481
|
+
const row = this.db.prepare("SELECT snapshot_json -> '$.plan' AS plan FROM turn_snapshots WHERE turn_id = ?")
|
|
1482
|
+
.get(turnId) as { plan: string | null } | undefined;
|
|
1483
|
+
return row?.plan ? JSON.parse(row.plan) ?? [] : [];
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
workspaceTurnExecution(turnId: string) {
|
|
1487
|
+
return this.db.prepare(`SELECT
|
|
1488
|
+
json_extract(snapshot_json, '$.startedAt') AS startedAt,
|
|
1489
|
+
json_extract(snapshot_json, '$.model') AS model,
|
|
1490
|
+
json_extract(snapshot_json, '$.reasoningEffort') AS thinking
|
|
1491
|
+
FROM turn_snapshots WHERE turn_id = ?`).get(turnId) as
|
|
1492
|
+
{ startedAt: number | null; model: string | null; thinking: string | null } | undefined;
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
workspaceTurnAnswer(turnId: string): string | undefined {
|
|
1496
|
+
const row = this.db.prepare("SELECT json_extract(snapshot_json, '$.finalResponse') AS answer FROM turn_snapshots WHERE turn_id = ?")
|
|
1497
|
+
.get(turnId) as { answer: string | null } | undefined;
|
|
1498
|
+
return row?.answer ?? undefined;
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1368
1501
|
getTurnSnapshot(turnId: string): unknown {
|
|
1369
1502
|
const row = this.db
|
|
1370
1503
|
.prepare("SELECT snapshot_json FROM turn_snapshots WHERE turn_id = ?")
|
|
@@ -2475,6 +2608,10 @@ export class StateStore {
|
|
|
2475
2608
|
.run(canonical.local_session_id, duplicate.local_session_id);
|
|
2476
2609
|
this.db.prepare("DELETE FROM context_sessions WHERE local_session_id = ?")
|
|
2477
2610
|
.run(duplicate.local_session_id);
|
|
2611
|
+
this.db.prepare(`INSERT OR IGNORE INTO task_metadata (local_session_id, kind, key, value)
|
|
2612
|
+
SELECT ?, kind, key, value FROM task_metadata WHERE local_session_id = ?`)
|
|
2613
|
+
.run(canonical.local_session_id, duplicate.local_session_id);
|
|
2614
|
+
this.db.prepare("DELETE FROM task_metadata WHERE local_session_id = ?").run(duplicate.local_session_id);
|
|
2478
2615
|
this.db.prepare("DELETE FROM sessions WHERE local_session_id = ?")
|
|
2479
2616
|
.run(duplicate.local_session_id);
|
|
2480
2617
|
}
|