@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
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;
|
|
@@ -294,6 +295,7 @@ interface TurnAttemptRow {
|
|
|
294
295
|
|
|
295
296
|
export class StateStore {
|
|
296
297
|
private readonly db: Database.Database;
|
|
298
|
+
private readonly queuedPromptDispatches = new Map<string, QueuedPromptRecord>();
|
|
297
299
|
readonly previews: TurnPreviewJournal;
|
|
298
300
|
readonly schedules: ScheduledTaskStore;
|
|
299
301
|
readonly provenance: ExecutionProvenanceStore;
|
|
@@ -303,6 +305,10 @@ export class StateStore {
|
|
|
303
305
|
this.previews = new TurnPreviewJournal(path.join(path.dirname(sqlitePath), "turn-previews"), onPreviewError);
|
|
304
306
|
fs.mkdirSync(path.dirname(sqlitePath), { recursive: true });
|
|
305
307
|
this.db = new Database(sqlitePath);
|
|
308
|
+
this.db.function("workspace_tool_heading", { deterministic: true }, (title: string | null, kind: string | null, command: string | null) => {
|
|
309
|
+
const heading = previewToolHeading({ title: title ?? "", kind: kind ?? "工具", command: command ?? undefined }, "命令");
|
|
310
|
+
return JSON.stringify({ ...heading, title: heading.title.slice(0, 240) });
|
|
311
|
+
});
|
|
306
312
|
this.db.pragma("journal_mode = WAL");
|
|
307
313
|
for (const migration of migrations) {
|
|
308
314
|
this.db.exec(migration);
|
|
@@ -648,6 +654,33 @@ export class StateStore {
|
|
|
648
654
|
return rows.map(mapQueuedPrompt);
|
|
649
655
|
}
|
|
650
656
|
|
|
657
|
+
// Keep the claimed prompt readable in Workspace while its chat entry is being published.
|
|
658
|
+
trackQueuedPromptDispatch(prompt: QueuedPromptRecord): () => void {
|
|
659
|
+
this.queuedPromptDispatches.set(prompt.promptId, prompt);
|
|
660
|
+
return () => {
|
|
661
|
+
if (this.queuedPromptDispatches.get(prompt.promptId) === prompt) this.queuedPromptDispatches.delete(prompt.promptId);
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
listQueuedPromptDispatches(localSessionId: string): QueuedPromptRecord[] {
|
|
666
|
+
return [...this.queuedPromptDispatches.values()].filter(prompt => prompt.localSessionId === localSessionId);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
getQueuedPrompt(localSessionId: string, promptId: string): QueuedPromptRecord | undefined {
|
|
670
|
+
const row = this.db.prepare("SELECT * FROM queued_prompts WHERE local_session_id = ? AND prompt_id = ?")
|
|
671
|
+
.get(localSessionId, promptId) as QueuedPromptRow | undefined;
|
|
672
|
+
return row ? mapQueuedPrompt(row) : undefined;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
updateQueuedPrompt(previous: QueuedPromptRecord, content: Pick<QueuedPromptRecord, "text" | "displayPrompt">): boolean {
|
|
676
|
+
const updated = this.db.prepare(`
|
|
677
|
+
UPDATE queued_prompts SET prompt_text = ?, display_prompt = ?
|
|
678
|
+
WHERE local_session_id = ? AND prompt_id = ? AND prompt_text = ? AND display_prompt IS ?
|
|
679
|
+
`).run(content.text, content.displayPrompt ?? null, previous.localSessionId, previous.promptId,
|
|
680
|
+
previous.text, previous.displayPrompt ?? null);
|
|
681
|
+
return updated.changes === 1;
|
|
682
|
+
}
|
|
683
|
+
|
|
651
684
|
hasQueuedPrompt(promptId: string): boolean {
|
|
652
685
|
return Boolean(this.db.prepare("SELECT 1 FROM queued_prompts WHERE prompt_id = ?").get(promptId));
|
|
653
686
|
}
|
|
@@ -687,6 +720,7 @@ export class StateStore {
|
|
|
687
720
|
if (!row) return undefined;
|
|
688
721
|
this.db.prepare("DELETE FROM queued_prompts WHERE prompt_id = ?").run(row.prompt_id);
|
|
689
722
|
if (!this.schedules.claimStart(row.prompt_id)) continue;
|
|
723
|
+
const prompt = mapQueuedPrompt(row);
|
|
690
724
|
if (this.schedules.getRun(row.prompt_id)) {
|
|
691
725
|
const existing = this.getTurnAttempt(row.prompt_id);
|
|
692
726
|
if (existing) {
|
|
@@ -698,15 +732,44 @@ export class StateStore {
|
|
|
698
732
|
executionGeneration: this.executionGeneration(localSessionId) });
|
|
699
733
|
} else {
|
|
700
734
|
this.createTurnAttempt({ attemptId: row.prompt_id, localSessionId, contextKey: row.context_key,
|
|
701
|
-
promptText: row.prompt_text,
|
|
735
|
+
promptText: row.prompt_text, localImagePaths: prompt.localImagePaths,
|
|
736
|
+
replyMessageId: row.reply_message_id ?? undefined });
|
|
702
737
|
}
|
|
703
738
|
}
|
|
704
|
-
return
|
|
739
|
+
return prompt;
|
|
705
740
|
}
|
|
706
741
|
});
|
|
707
742
|
return take();
|
|
708
743
|
}
|
|
709
744
|
|
|
745
|
+
claimQueuedPromptForImmediateSend(prompt: QueuedPromptRecord): boolean {
|
|
746
|
+
return this.db.transaction(() => {
|
|
747
|
+
const current = this.getQueuedPrompt(prompt.localSessionId, prompt.promptId);
|
|
748
|
+
if (!current || current.text !== prompt.text || current.displayPrompt !== prompt.displayPrompt) return false;
|
|
749
|
+
const run = this.schedules.getRun(prompt.promptId);
|
|
750
|
+
if (run) {
|
|
751
|
+
const attempt = this.getTurnAttempt(run.id);
|
|
752
|
+
if (attempt && (attempt.submissionState !== "not_submitted" || attempt.turnId)) return false;
|
|
753
|
+
if (!this.schedules.claimStart(run.id)) return false;
|
|
754
|
+
this.schedules.saveRun({ ...this.schedules.getRun(run.id)!, status: "submitting" });
|
|
755
|
+
}
|
|
756
|
+
this.db.prepare("DELETE FROM queued_prompts WHERE local_session_id = ? AND prompt_id = ?").run(prompt.localSessionId, prompt.promptId);
|
|
757
|
+
return true;
|
|
758
|
+
})();
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
restoreQueuedPromptAfterImmediateSend(prompt: QueuedPromptRecord): void {
|
|
762
|
+
this.db.transaction(() => {
|
|
763
|
+
const run = this.schedules.getRun(prompt.promptId);
|
|
764
|
+
if (run) {
|
|
765
|
+
if (run.status !== "submitting") return;
|
|
766
|
+
this.schedules.saveRun({ ...run, status: "queued", startedAt: undefined });
|
|
767
|
+
if (!this.schedules.canSubmit(run.id)) return;
|
|
768
|
+
}
|
|
769
|
+
if (!this.hasQueuedPrompt(prompt.promptId)) this.enqueuePrompt(prompt);
|
|
770
|
+
})();
|
|
771
|
+
}
|
|
772
|
+
|
|
710
773
|
cancelQueuedPrompt(promptId: string, localSessionId: string): QueuedPromptRecord | undefined {
|
|
711
774
|
const cancel = this.db.transaction(() => {
|
|
712
775
|
const row = this.db.prepare(`
|
|
@@ -721,6 +784,21 @@ export class StateStore {
|
|
|
721
784
|
return cancel();
|
|
722
785
|
}
|
|
723
786
|
|
|
787
|
+
cancelWorkspaceQueuedPrompt(promptId: string, localSessionId: string, request: string) {
|
|
788
|
+
return this.db.transaction(() => {
|
|
789
|
+
const fingerprint = JSON.stringify(["cancel-queued-prompt", localSessionId, promptId]);
|
|
790
|
+
const previous = this.workspaceRequest(request);
|
|
791
|
+
if (previous) {
|
|
792
|
+
if (previous.fingerprint !== fingerprint) throw new Error("该请求标识已用于另一项操作。");
|
|
793
|
+
return { cancelled: previous.status === "accepted", prompt: undefined };
|
|
794
|
+
}
|
|
795
|
+
this.beginWorkspaceRequest(request, localSessionId, fingerprint);
|
|
796
|
+
const prompt = this.cancelQueuedPrompt(promptId, localSessionId);
|
|
797
|
+
this.updateWorkspaceRequest(request, prompt ? "accepted" : "stale");
|
|
798
|
+
return { cancelled: Boolean(prompt), prompt };
|
|
799
|
+
})();
|
|
800
|
+
}
|
|
801
|
+
|
|
724
802
|
createTurnAttempt(input: {
|
|
725
803
|
attemptId: string;
|
|
726
804
|
localSessionId: string;
|
|
@@ -739,7 +817,11 @@ export class StateStore {
|
|
|
739
817
|
status?: Extract<TurnAttemptStatus, "accepted" | "running" | "recovering">;
|
|
740
818
|
createdAt?: string;
|
|
741
819
|
updatedAt?: string;
|
|
742
|
-
}): TurnAttemptRecord {
|
|
820
|
+
}, beforeCreate?: () => void): TurnAttemptRecord {
|
|
821
|
+
if (beforeCreate) return this.db.transaction(() => {
|
|
822
|
+
beforeCreate();
|
|
823
|
+
return this.createTurnAttempt(input);
|
|
824
|
+
})();
|
|
743
825
|
const createdAt = input.createdAt ?? new Date().toISOString();
|
|
744
826
|
const updatedAt = input.updatedAt ?? createdAt;
|
|
745
827
|
const status = input.status ?? (input.turnId ? "running" : "accepted");
|
|
@@ -1290,6 +1372,27 @@ export class StateStore {
|
|
|
1290
1372
|
})();
|
|
1291
1373
|
}
|
|
1292
1374
|
|
|
1375
|
+
listTaskMetadata(localSessionId: string, kind: string): { key: string; value: string }[] {
|
|
1376
|
+
return this.db.prepare("SELECT key, value FROM task_metadata WHERE local_session_id = ? AND kind = ? ORDER BY value")
|
|
1377
|
+
.all(localSessionId, kind) as { key: string; value: string }[];
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
getTaskMetadata(localSessionId: string, kind: string, key: string): string | undefined {
|
|
1381
|
+
const row = this.db.prepare("SELECT value FROM task_metadata WHERE local_session_id = ? AND kind = ? AND key = ?")
|
|
1382
|
+
.get(localSessionId, kind, key) as { value: string } | undefined;
|
|
1383
|
+
return row?.value;
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
setTaskMetadata(localSessionId: string, kind: string, key: string, value: string): void {
|
|
1387
|
+
this.db.prepare(`INSERT INTO task_metadata (local_session_id, kind, key, value) VALUES (?, ?, ?, ?)
|
|
1388
|
+
ON CONFLICT (local_session_id, kind, key) DO UPDATE SET value = excluded.value`).run(localSessionId, kind, key, value);
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
removeTaskMetadata(localSessionId: string, kind: string, key: string): boolean {
|
|
1392
|
+
return this.db.prepare("DELETE FROM task_metadata WHERE local_session_id = ? AND kind = ? AND key = ?")
|
|
1393
|
+
.run(localSessionId, kind, key).changes > 0;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1293
1396
|
workspaceRequest(id: string) {
|
|
1294
1397
|
return this.db.prepare(`SELECT local_session_id AS localSessionId, fingerprint, status, posted, message
|
|
1295
1398
|
FROM workspace_requests WHERE id = ?`).get(id) as
|
|
@@ -1306,6 +1409,10 @@ export class StateStore {
|
|
|
1306
1409
|
.run(status, Number(posted), message ?? null, id);
|
|
1307
1410
|
}
|
|
1308
1411
|
|
|
1412
|
+
markWorkspaceRequestPosted(id: string): void {
|
|
1413
|
+
this.db.prepare("UPDATE workspace_requests SET posted = 1 WHERE id = ?").run(id);
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1309
1416
|
workspaceTurnHead(task: SessionRecord): string | undefined {
|
|
1310
1417
|
if (task.lastTurnId && task.status !== "running" && task.status !== "starting"
|
|
1311
1418
|
&& this.db.prepare("SELECT 1 FROM turn_snapshots WHERE turn_id = ?").get(task.lastTurnId)) return task.lastTurnId;
|
|
@@ -1318,53 +1425,145 @@ export class StateStore {
|
|
|
1318
1425
|
workspaceTurnPage(localSessionId: string, head: string | undefined, before?: string, limit = 20): {
|
|
1319
1426
|
ids: string[]; more: boolean; beforeMissing: boolean;
|
|
1320
1427
|
} {
|
|
1428
|
+
const ids: string[] = [];
|
|
1429
|
+
let found = !before;
|
|
1430
|
+
for (const id of this.workspaceTurnChain(localSessionId, head)) {
|
|
1431
|
+
if (found) ids.push(id);
|
|
1432
|
+
if (id === before) found = true;
|
|
1433
|
+
if (ids.length > limit) break;
|
|
1434
|
+
}
|
|
1435
|
+
return { ids: ids.slice(0, limit), more: ids.length > limit, beforeMissing: !found };
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
workspaceTurnsAfter(localSessionId: string, head: string | undefined, after: string, limit: number): {
|
|
1439
|
+
ids: string[]; more: boolean; cursorMissing: boolean;
|
|
1440
|
+
} {
|
|
1441
|
+
if (after === head) return { ids: [], more: false, cursorMissing: false };
|
|
1442
|
+
// Walk the current branch from its head, retaining only the closest successors of the cursor.
|
|
1443
|
+
const nearest: string[] = [];
|
|
1444
|
+
for (const id of this.workspaceTurnChain(localSessionId, head)) {
|
|
1445
|
+
if (id === after) return { ids: nearest.slice(-limit).reverse(), more: nearest.length > limit, cursorMissing: false };
|
|
1446
|
+
if (nearest.length > limit) nearest.shift();
|
|
1447
|
+
nearest.push(id);
|
|
1448
|
+
}
|
|
1449
|
+
return { ids: [], more: false, cursorMissing: true };
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
workspaceConversationMetrics(localSessionId: string, head: string | undefined) {
|
|
1453
|
+
const readUsage = this.db.prepare(`SELECT json_extract(snapshot_json, '$.tokenUsageTotalCumulative') AS totalTokens
|
|
1454
|
+
FROM turn_snapshots WHERE turn_id = ? AND local_session_id = ?`);
|
|
1455
|
+
let turnCount = 0;
|
|
1456
|
+
let totalTokens: number | undefined;
|
|
1457
|
+
for (const id of this.workspaceTurnChain(localSessionId, head)) {
|
|
1458
|
+
turnCount++;
|
|
1459
|
+
if (totalTokens !== undefined || turnCount > 20) continue;
|
|
1460
|
+
// Use the latest published total from this task, including while its next turn is starting.
|
|
1461
|
+
const tokens = (readUsage.get(id, localSessionId) as { totalTokens?: unknown } | undefined)?.totalTokens;
|
|
1462
|
+
if (typeof tokens === "number" && Number.isSafeInteger(tokens) && tokens >= 0) totalTokens = tokens;
|
|
1463
|
+
}
|
|
1464
|
+
return { turnCount, totalTokens };
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
private *workspaceTurnChain(localSessionId: string, head: string | undefined): IterableIterator<string> {
|
|
1321
1468
|
const read = this.db.prepare(`SELECT s.local_session_id AS owner, p.turn_id AS linked, p.parent_turn_id AS parent
|
|
1322
1469
|
FROM turn_snapshots s LEFT JOIN turn_parent_links p ON p.turn_id = s.turn_id WHERE s.turn_id = ?`);
|
|
1323
1470
|
type Node = { owner: string; linked: string | null; parent: string | null };
|
|
1324
1471
|
let id = head;
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
let found = !before;
|
|
1328
|
-
while (id && !seen.has(id) && seen.size < 20_000 && ids.length <= limit) {
|
|
1472
|
+
const seen = new Set<string>(), backfilled = new Set<string>();
|
|
1473
|
+
while (id && !seen.has(id) && seen.size < 20_000) {
|
|
1329
1474
|
seen.add(id);
|
|
1330
1475
|
let node = read.get(id) as Node | undefined;
|
|
1331
1476
|
if (!node || seen.size === 1 && node.owner !== localSessionId && !this.hasTaskHistoryTurn(localSessionId, id)) break;
|
|
1332
|
-
if (
|
|
1477
|
+
if (!node.linked && !backfilled.has(node.owner)) {
|
|
1333
1478
|
this.backfillTurnParents(node.owner);
|
|
1479
|
+
backfilled.add(node.owner);
|
|
1334
1480
|
node = read.get(id) as Node;
|
|
1335
|
-
fallback = false;
|
|
1336
1481
|
}
|
|
1337
|
-
|
|
1338
|
-
if (id === before) found = true;
|
|
1482
|
+
yield id;
|
|
1339
1483
|
id = node.parent ?? (seen.size === 1 && node.owner === localSessionId
|
|
1340
1484
|
? this.findForkSourceTurnId(localSessionId) : undefined);
|
|
1341
1485
|
}
|
|
1342
|
-
return { ids: ids.slice(0, limit), more: ids.length > limit, beforeMissing: !found };
|
|
1343
1486
|
}
|
|
1344
1487
|
|
|
1345
1488
|
workspaceTurnText(turnId: string) {
|
|
1346
|
-
return this.db.prepare(`SELECT updated_at AS revision,
|
|
1489
|
+
return this.db.prepare(`SELECT updated_at AS revision, local_session_id AS ownerTask,
|
|
1347
1490
|
substr(json_extract(snapshot_json, '$.prompt'), 1, 24001) AS prompt,
|
|
1348
1491
|
snapshot_json -> '$.promptImagePaths' AS promptImages,
|
|
1349
|
-
|
|
1350
|
-
|
|
1492
|
+
json_extract(snapshot_json, '$.promptRequestId') AS promptRequestId,
|
|
1493
|
+
json_extract(snapshot_json, '$.finalResponse') AS answer,
|
|
1494
|
+
json_extract(snapshot_json, '$.assistantText') AS live,
|
|
1351
1495
|
substr(json_extract(snapshot_json, '$.error'), 1, 3000) AS error,
|
|
1352
1496
|
substr(json_extract(snapshot_json, '$.statusMessage'), 1, 3000) AS notice,
|
|
1353
1497
|
json_extract(snapshot_json, '$.status') AS status,
|
|
1354
1498
|
json_extract(snapshot_json, '$.startedAt') AS startedAt,
|
|
1499
|
+
json_extract(snapshot_json, '$.completedAt') AS completedAt,
|
|
1500
|
+
json_extract(snapshot_json, '$.durationMs') AS durationMs,
|
|
1501
|
+
json_extract(snapshot_json, '$.totalTokens') AS totalTokens,
|
|
1502
|
+
json_extract(snapshot_json, '$.cachedInputTokens') AS cachedInputTokens,
|
|
1503
|
+
json_extract(snapshot_json, '$.totalTokensIncludingCache') AS totalTokensIncludingCache,
|
|
1504
|
+
json_extract(snapshot_json, '$.modelCallCount') AS modelCallCount,
|
|
1505
|
+
json_extract(snapshot_json, '$.totalToolCount') AS totalToolCount,
|
|
1355
1506
|
json_extract(snapshot_json, '$.historyDetail') AS detail,
|
|
1356
|
-
(
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1507
|
+
coalesce(json_array_length(snapshot_json, '$.fileSummary'), 0) AS changeCount,
|
|
1508
|
+
snapshot_json -> '$.fileSummary' AS changeSummary,
|
|
1509
|
+
json_extract(snapshot_json, '$.previewTurnId') AS journalId,
|
|
1510
|
+
json_extract(snapshot_json, '$.continuedToTurnId') AS continuedToTurnId,
|
|
1511
|
+
coalesce(json_extract(snapshot_json, '$.activitiesTruncated'), 0) AS compact,
|
|
1512
|
+
(SELECT json_group_array(json_object('kind', kind, 'id', id, 'text', body, 'images', json(images),
|
|
1513
|
+
'heading', json(heading), 'toolKind', toolKind, 'status', status, 'startedAt', activityStart, 'completedAt', toolEnd) ORDER BY ordinal) FROM (
|
|
1514
|
+
SELECT key AS ordinal, json_extract(value, '$.kind') AS kind, json_extract(value, '$.id') AS id,
|
|
1515
|
+
json_extract(value, '$.text') AS body, value -> '$.localImagePaths' AS images,
|
|
1516
|
+
CASE WHEN json_extract(value, '$.kind') = 'tool' THEN workspace_tool_heading(json_extract(value, '$.tool.title'),
|
|
1517
|
+
json_extract(value, '$.tool.kind'), json_extract(value, '$.tool.command')) END AS heading,
|
|
1518
|
+
json_extract(value, '$.tool.kind') AS toolKind, json_extract(value, '$.tool.status') AS status,
|
|
1519
|
+
coalesce(json_extract(value, '$.tool.startedAt'), json_extract(value, '$.startedAt')) AS activityStart,
|
|
1520
|
+
json_extract(value, '$.tool.completedAt') AS toolEnd
|
|
1521
|
+
FROM json_each(snapshot_json, '$.activities'))) AS activities,
|
|
1522
|
+
(SELECT json_group_array(json_object('id', id, 'after', after, 'parts', json(parts))
|
|
1523
|
+
ORDER BY ordinal) FROM (
|
|
1524
|
+
SELECT item.key AS ordinal, json_extract(item.value, '$.itemId') AS id,
|
|
1525
|
+
json_extract(item.value, '$.afterActivityId') AS after,
|
|
1526
|
+
(SELECT json_group_array(json_object('index', section, 'text', snippet) ORDER BY section) FROM (
|
|
1527
|
+
SELECT part.key AS section, substr(part.value, 1, 512) AS snippet
|
|
1528
|
+
FROM json_each(item.value, '$.summary') AS part
|
|
1529
|
+
WHERE part.type = 'text' AND trim(part.value) != '')) AS parts
|
|
1530
|
+
FROM json_each(snapshot_json, '$.reasoningItems') AS item)) AS reasoning
|
|
1362
1531
|
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;
|
|
1532
|
+
revision: string; ownerTask: string; prompt: string | null; promptImages: string | null; promptRequestId: string | null; answer: string | null; live: string | null;
|
|
1533
|
+
error: string | null; notice: string | null; status: string; startedAt: number; completedAt: number | null;
|
|
1534
|
+
durationMs: number | null; detail: string | null;
|
|
1535
|
+
totalTokens: number | null; cachedInputTokens: number | null; totalTokensIncludingCache: number | null;
|
|
1536
|
+
modelCallCount: number | null; totalToolCount: number | null;
|
|
1537
|
+
changeCount: number; changeSummary: string | null; journalId: string | null; continuedToTurnId: string | null;
|
|
1538
|
+
compact: number; activities: string; reasoning: string;
|
|
1365
1539
|
} | undefined;
|
|
1366
1540
|
}
|
|
1367
1541
|
|
|
1542
|
+
workspaceTurnPlan(turnId: string): PlanStep[] {
|
|
1543
|
+
const row = this.db.prepare("SELECT snapshot_json -> '$.plan' AS plan FROM turn_snapshots WHERE turn_id = ?")
|
|
1544
|
+
.get(turnId) as { plan: string | null } | undefined;
|
|
1545
|
+
return row?.plan ? JSON.parse(row.plan) ?? [] : [];
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
workspaceTurnExecution(turnId: string) {
|
|
1549
|
+
return this.db.prepare(`SELECT
|
|
1550
|
+
json_extract(snapshot_json, '$.startedAt') AS startedAt,
|
|
1551
|
+
json_extract(snapshot_json, '$.model') AS model,
|
|
1552
|
+
json_extract(snapshot_json, '$.reasoningEffort') AS thinking,
|
|
1553
|
+
json_extract(snapshot_json, '$.totalTokens') AS totalTokens,
|
|
1554
|
+
json_extract(snapshot_json, '$.cachedInputTokens') AS cachedInputTokens,
|
|
1555
|
+
json_extract(snapshot_json, '$.totalTokensIncludingCache') AS totalTokensIncludingCache
|
|
1556
|
+
FROM turn_snapshots WHERE turn_id = ?`).get(turnId) as
|
|
1557
|
+
{ startedAt: number | null; model: string | null; thinking: string | null;
|
|
1558
|
+
totalTokens: number | null; cachedInputTokens: number | null; totalTokensIncludingCache: number | null } | undefined;
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
workspaceTurnAnswer(turnId: string): string | undefined {
|
|
1562
|
+
const row = this.db.prepare("SELECT json_extract(snapshot_json, '$.finalResponse') AS answer FROM turn_snapshots WHERE turn_id = ?")
|
|
1563
|
+
.get(turnId) as { answer: string | null } | undefined;
|
|
1564
|
+
return row?.answer ?? undefined;
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1368
1567
|
getTurnSnapshot(turnId: string): unknown {
|
|
1369
1568
|
const row = this.db
|
|
1370
1569
|
.prepare("SELECT snapshot_json FROM turn_snapshots WHERE turn_id = ?")
|
|
@@ -2475,6 +2674,10 @@ export class StateStore {
|
|
|
2475
2674
|
.run(canonical.local_session_id, duplicate.local_session_id);
|
|
2476
2675
|
this.db.prepare("DELETE FROM context_sessions WHERE local_session_id = ?")
|
|
2477
2676
|
.run(duplicate.local_session_id);
|
|
2677
|
+
this.db.prepare(`INSERT OR IGNORE INTO task_metadata (local_session_id, kind, key, value)
|
|
2678
|
+
SELECT ?, kind, key, value FROM task_metadata WHERE local_session_id = ?`)
|
|
2679
|
+
.run(canonical.local_session_id, duplicate.local_session_id);
|
|
2680
|
+
this.db.prepare("DELETE FROM task_metadata WHERE local_session_id = ?").run(duplicate.local_session_id);
|
|
2478
2681
|
this.db.prepare("DELETE FROM sessions WHERE local_session_id = ?")
|
|
2479
2682
|
.run(duplicate.local_session_id);
|
|
2480
2683
|
}
|