@keyou007/agent-bot 0.1.25-alpha.0 → 0.1.25-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +60 -5
- package/README.zh.md +60 -5
- package/config.example.yaml +1 -3
- package/dist/cli/controlProtocol.js.map +1 -1
- package/dist/cli/help.js +14 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli.js +32 -0
- package/dist/cli.js.map +1 -1
- package/dist/codex/CodexRuntime.js +15 -5
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/commands/CommandRouter.js +7 -0
- package/dist/commands/CommandRouter.js.map +1 -1
- package/dist/config/SettingsStore.js +341 -0
- package/dist/config/SettingsStore.js.map +1 -0
- package/dist/config/loadConfig.js +1 -2
- package/dist/config/loadConfig.js.map +1 -1
- package/dist/config/schema.js +0 -1
- package/dist/config/schema.js.map +1 -1
- package/dist/console/ConsoleTurnPresenter.js +3 -0
- package/dist/console/ConsoleTurnPresenter.js.map +1 -1
- package/dist/feishu/CardRenderer.js +32 -96
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/FeishuConnector.js +9 -0
- package/dist/feishu/FeishuConnector.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +35 -14
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +36 -23
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/feishu/LocalCardImage.js.map +1 -1
- package/dist/feishu/LocalImageMarkdown.js +59 -3
- package/dist/feishu/LocalImageMarkdown.js.map +1 -1
- package/dist/feishu/SettingsCard.js +199 -0
- package/dist/feishu/SettingsCard.js.map +1 -0
- package/dist/index.js +17 -6
- package/dist/index.js.map +1 -1
- package/dist/local-files/TurnPreviewPage.js +8 -4
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +21 -2
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/presentation/turnStatus.js +34 -0
- package/dist/presentation/turnStatus.js.map +1 -0
- package/dist/proxy/ProxySessionController.js +688 -153
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/runtime/submissionErrors.js +15 -0
- package/dist/runtime/submissionErrors.js.map +1 -0
- package/dist/scheduling/ScheduleCards.js +240 -0
- package/dist/scheduling/ScheduleCards.js.map +1 -0
- package/dist/scheduling/ScheduleCommand.js +67 -0
- package/dist/scheduling/ScheduleCommand.js.map +1 -0
- package/dist/scheduling/ScheduledTaskStore.js +226 -0
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -0
- package/dist/scheduling/TaskScheduler.js +132 -0
- package/dist/scheduling/TaskScheduler.js.map +1 -0
- package/dist/scheduling/types.js +89 -0
- package/dist/scheduling/types.js.map +1 -0
- package/dist/state/ExecutionProvenanceStore.js +58 -0
- package/dist/state/ExecutionProvenanceStore.js.map +1 -0
- package/dist/state/StateStore.js +145 -45
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/migrations.js +37 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +1 -1
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/docs/technical-reference.md +11 -8
- package/docs/technical-reference.zh.md +11 -8
- package/npm-shrinkwrap.json +24 -2
- package/package.json +2 -1
- package/skills/agent-bot/SKILL.md +33 -3
- package/src/cli/controlProtocol.ts +1 -0
- package/src/cli/help.ts +14 -0
- package/src/cli.ts +25 -0
- package/src/codex/CodexRuntime.ts +14 -5
- package/src/commands/CommandRouter.ts +7 -0
- package/src/commands/commandTypes.ts +2 -0
- package/src/config/SettingsStore.ts +588 -0
- package/src/config/loadConfig.ts +1 -2
- package/src/config/schema.ts +0 -1
- package/src/console/ConsoleTurnPresenter.ts +2 -0
- package/src/feishu/CardRenderer.ts +33 -110
- package/src/feishu/FeishuConnector.ts +9 -0
- package/src/feishu/FeishuMessageClient.ts +39 -17
- package/src/feishu/FeishuTurnPresenter.ts +33 -22
- package/src/feishu/LocalCardImage.ts +0 -1
- package/src/feishu/LocalImageMarkdown.ts +54 -3
- package/src/feishu/SettingsCard.ts +231 -0
- package/src/index.ts +17 -6
- package/src/local-files/TurnPreviewPage.ts +8 -4
- package/src/presentation/TurnStateReducer.ts +21 -2
- package/src/presentation/turnStatus.ts +38 -0
- package/src/presentation/turnViewTypes.ts +3 -0
- package/src/proxy/ProxySessionController.ts +628 -152
- package/src/runtime/submissionErrors.ts +15 -0
- package/src/runtime/types.ts +1 -0
- package/src/scheduling/ScheduleCards.ts +317 -0
- package/src/scheduling/ScheduleCommand.ts +76 -0
- package/src/scheduling/ScheduledTaskStore.ts +332 -0
- package/src/scheduling/TaskScheduler.ts +171 -0
- package/src/scheduling/types.ts +151 -0
- package/src/state/ExecutionProvenanceStore.ts +100 -0
- package/src/state/StateStore.ts +167 -44
- package/src/state/migrations.ts +37 -0
- package/src/supervision/SafeRestartNotifier.ts +1 -1
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type Database from "better-sqlite3";
|
|
2
|
+
import type { RuntimeSession } from "../runtime/types.js";
|
|
3
|
+
import { createId } from "../utils/id.js";
|
|
4
|
+
|
|
5
|
+
export type ExecutionTrigger = "user" | "queue" | "schedule" | "recovery" | "retry"
|
|
6
|
+
| "plan_handoff" | "response_continuation";
|
|
7
|
+
|
|
8
|
+
export interface ExecutionProvenance {
|
|
9
|
+
submissionId: string;
|
|
10
|
+
instructionId: string;
|
|
11
|
+
attemptId: string;
|
|
12
|
+
localSessionId: string;
|
|
13
|
+
turnId?: string;
|
|
14
|
+
trigger: ExecutionTrigger;
|
|
15
|
+
parentSourceTurnId?: string;
|
|
16
|
+
scheduledFor?: number;
|
|
17
|
+
submittedAt: number;
|
|
18
|
+
settings: Pick<RuntimeSession, "agentName" | "modelProvider" | "model" | "reasoningEffort" | "permissionMode" | "cwd">;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface ProvenanceRow {
|
|
22
|
+
submission_id: string;
|
|
23
|
+
instruction_id: string;
|
|
24
|
+
attempt_id: string;
|
|
25
|
+
local_session_id: string;
|
|
26
|
+
turn_id: string | null;
|
|
27
|
+
trigger: ExecutionTrigger;
|
|
28
|
+
parent_source_turn_id: string | null;
|
|
29
|
+
scheduled_for: number | null;
|
|
30
|
+
submitted_at: number;
|
|
31
|
+
agent_name: string;
|
|
32
|
+
model_provider: string | null;
|
|
33
|
+
model: string | null;
|
|
34
|
+
reasoning_effort: string | null;
|
|
35
|
+
permission_mode: RuntimeSession["permissionMode"];
|
|
36
|
+
cwd: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class ExecutionProvenanceStore {
|
|
40
|
+
constructor(private readonly db: Database.Database) {}
|
|
41
|
+
|
|
42
|
+
recordSubmission(input: Omit<ExecutionProvenance, "submissionId" | "submittedAt" | "turnId" | "instructionId">
|
|
43
|
+
& { instructionId?: string }): ExecutionProvenance {
|
|
44
|
+
const previous = this.latestForAttempt(input.attemptId);
|
|
45
|
+
const parent = input.parentSourceTurnId && input.trigger !== "user" && input.trigger !== "queue" && input.trigger !== "schedule"
|
|
46
|
+
? this.forTurn(input.parentSourceTurnId, input.localSessionId) : undefined;
|
|
47
|
+
const instructionId = previous?.instructionId ?? parent?.instructionId ?? input.instructionId ?? input.attemptId;
|
|
48
|
+
const scheduledFor = input.scheduledFor ?? previous?.scheduledFor ?? parent?.scheduledFor;
|
|
49
|
+
const submissionId = createId("submission");
|
|
50
|
+
// Explicit columns are the allowlist: never serialize a runtime session or prompt here.
|
|
51
|
+
const { agentName, modelProvider, model, reasoningEffort, permissionMode, cwd } = input.settings;
|
|
52
|
+
this.db.prepare(`INSERT INTO execution_provenance (
|
|
53
|
+
submission_id, instruction_id, attempt_id, local_session_id, trigger, parent_source_turn_id,
|
|
54
|
+
scheduled_for, submitted_at, agent_name, model_provider, model, reasoning_effort, permission_mode, cwd
|
|
55
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
|
|
56
|
+
submissionId, instructionId, input.attemptId, input.localSessionId, input.trigger, input.parentSourceTurnId ?? null,
|
|
57
|
+
scheduledFor ?? null, Date.now(), agentName, modelProvider ?? null, model ?? null, reasoningEffort ?? null, permissionMode, cwd,
|
|
58
|
+
);
|
|
59
|
+
return this.latestForAttempt(input.attemptId)!;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
bindTurn(submissionId: string, turnId: string): void {
|
|
63
|
+
this.db.prepare(`UPDATE execution_provenance SET turn_id = ? WHERE submission_id = ? AND turn_id IS NULL`)
|
|
64
|
+
.run(turnId, submissionId);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
bindLatestTurn(attemptId: string, turnId: string): void {
|
|
68
|
+
const latest = this.latestForAttempt(attemptId);
|
|
69
|
+
if (latest) this.bindTurn(latest.submissionId, turnId);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
latestForAttempt(attemptId: string): ExecutionProvenance | undefined {
|
|
73
|
+
return this.read(this.db.prepare(`SELECT * FROM execution_provenance WHERE attempt_id = ? ORDER BY rowid DESC LIMIT 1`)
|
|
74
|
+
.get(attemptId));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
forTurn(turnId: string, localSessionId: string): ExecutionProvenance | undefined {
|
|
78
|
+
return this.read(this.db.prepare(`SELECT * FROM execution_provenance WHERE turn_id = ? AND local_session_id = ?
|
|
79
|
+
ORDER BY rowid DESC LIMIT 1`).get(turnId, localSessionId));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
listForAttempt(attemptId: string): ExecutionProvenance[] {
|
|
83
|
+
return this.db.prepare(`SELECT * FROM execution_provenance WHERE attempt_id = ? ORDER BY rowid`).all(attemptId)
|
|
84
|
+
.map((row) => this.read(row)!);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private read(value: unknown): ExecutionProvenance | undefined {
|
|
88
|
+
if (!value) return undefined;
|
|
89
|
+
const row = value as ProvenanceRow;
|
|
90
|
+
return {
|
|
91
|
+
submissionId: row.submission_id, instructionId: row.instruction_id, attemptId: row.attempt_id,
|
|
92
|
+
localSessionId: row.local_session_id, turnId: row.turn_id ?? undefined, trigger: row.trigger,
|
|
93
|
+
parentSourceTurnId: row.parent_source_turn_id ?? undefined, scheduledFor: row.scheduled_for ?? undefined,
|
|
94
|
+
submittedAt: row.submitted_at, settings: {
|
|
95
|
+
agentName: row.agent_name, modelProvider: row.model_provider ?? undefined, model: row.model ?? undefined,
|
|
96
|
+
reasoningEffort: row.reasoning_effort ?? undefined, permissionMode: row.permission_mode, cwd: row.cwd,
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
package/src/state/StateStore.ts
CHANGED
|
@@ -4,7 +4,9 @@ import { compactTurnView } from "../presentation/TurnStateReducer.js";
|
|
|
4
4
|
import type { TurnViewState } from "../presentation/turnViewTypes.js";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import Database from "better-sqlite3";
|
|
7
|
+
import { ScheduledTaskStore } from "../scheduling/ScheduledTaskStore.js";
|
|
7
8
|
import { migrations } from "./migrations.js";
|
|
9
|
+
import { ExecutionProvenanceStore } from "./ExecutionProvenanceStore.js";
|
|
8
10
|
import type { UpdateCheckSchedule, UpdateNotice } from "../updates/types.js";
|
|
9
11
|
import type { ConversationTurn, RuntimeExecutionSettings } from "../runtime/types.js";
|
|
10
12
|
|
|
@@ -20,6 +22,17 @@ export interface PendingProviderSettings {
|
|
|
20
22
|
|
|
21
23
|
export type SessionStatus = "starting" | "ready" | "running" | "closed" | "failed";
|
|
22
24
|
|
|
25
|
+
// Scheduled queue entries survive a safe restart, but an in-flight submission must block it.
|
|
26
|
+
const RESTART_BLOCKING_WORK_SQL = `sessions.status = 'running'
|
|
27
|
+
OR EXISTS (
|
|
28
|
+
SELECT 1 FROM queued_prompts q WHERE q.local_session_id = sessions.local_session_id
|
|
29
|
+
AND NOT EXISTS (SELECT 1 FROM scheduled_runs r WHERE r.id = q.prompt_id)
|
|
30
|
+
)
|
|
31
|
+
OR EXISTS (
|
|
32
|
+
SELECT 1 FROM scheduled_jobs j JOIN scheduled_runs r ON r.job_id = j.id
|
|
33
|
+
WHERE j.local_session_id = sessions.local_session_id AND r.status IN ('dispatching','submitting','running')
|
|
34
|
+
)`;
|
|
35
|
+
|
|
23
36
|
export interface UserContextRecord {
|
|
24
37
|
contextKey: string;
|
|
25
38
|
defaultAgent: string;
|
|
@@ -162,7 +175,10 @@ export type TurnAttemptStatus =
|
|
|
162
175
|
| "completed"
|
|
163
176
|
| "failed"
|
|
164
177
|
| "cancelled"
|
|
165
|
-
| "interrupted"
|
|
178
|
+
| "interrupted"
|
|
179
|
+
| "unknown";
|
|
180
|
+
|
|
181
|
+
export type TurnSubmissionState = "not_submitted" | "submission_unknown" | "submitted";
|
|
166
182
|
|
|
167
183
|
export interface TurnAttemptRecord {
|
|
168
184
|
attemptId: string;
|
|
@@ -178,6 +194,8 @@ export interface TurnAttemptRecord {
|
|
|
178
194
|
recoveryCount: number;
|
|
179
195
|
retryCount: number;
|
|
180
196
|
status: TurnAttemptStatus;
|
|
197
|
+
submissionState: TurnSubmissionState;
|
|
198
|
+
executionGeneration: number;
|
|
181
199
|
createdAt: string;
|
|
182
200
|
updatedAt: string;
|
|
183
201
|
}
|
|
@@ -254,6 +272,7 @@ interface QueuedPromptRow {
|
|
|
254
272
|
}
|
|
255
273
|
|
|
256
274
|
interface TurnAttemptRow {
|
|
275
|
+
execution_generation: number;
|
|
257
276
|
attempt_id: string;
|
|
258
277
|
local_session_id: string;
|
|
259
278
|
context_key: string;
|
|
@@ -267,6 +286,7 @@ interface TurnAttemptRow {
|
|
|
267
286
|
recovery_count: number;
|
|
268
287
|
retry_count: number;
|
|
269
288
|
status: TurnAttemptStatus;
|
|
289
|
+
submission_state: TurnSubmissionState;
|
|
270
290
|
created_at: string;
|
|
271
291
|
updated_at: string;
|
|
272
292
|
}
|
|
@@ -274,6 +294,8 @@ interface TurnAttemptRow {
|
|
|
274
294
|
export class StateStore {
|
|
275
295
|
private readonly db: Database.Database;
|
|
276
296
|
readonly previews: TurnPreviewJournal;
|
|
297
|
+
readonly schedules: ScheduledTaskStore;
|
|
298
|
+
readonly provenance: ExecutionProvenanceStore;
|
|
277
299
|
|
|
278
300
|
constructor(sqlitePath: string, onPreviewError?: (error: unknown) => void) {
|
|
279
301
|
this.previews = new TurnPreviewJournal(path.join(path.dirname(sqlitePath), "turn-previews"), onPreviewError);
|
|
@@ -290,6 +312,9 @@ export class StateStore {
|
|
|
290
312
|
this.ensureChatContextColumns();
|
|
291
313
|
this.ensureTurnAttemptColumns();
|
|
292
314
|
this.ensureQueuedPromptColumns();
|
|
315
|
+
this.ensureRecentContextReceiptColumns();
|
|
316
|
+
this.schedules = new ScheduledTaskStore(this.db);
|
|
317
|
+
this.provenance = new ExecutionProvenanceStore(this.db);
|
|
293
318
|
this.initializeContextSessionMappings();
|
|
294
319
|
this.db.exec("DROP INDEX IF EXISTS idx_sessions_remote_session_id_unique");
|
|
295
320
|
this.reconcileDuplicateRemoteSessions();
|
|
@@ -585,8 +610,9 @@ export class StateStore {
|
|
|
585
610
|
localImagePaths?: string[];
|
|
586
611
|
messageId?: string;
|
|
587
612
|
replyMessageId?: string;
|
|
613
|
+
createdAt?: string;
|
|
588
614
|
}): QueuedPromptRecord {
|
|
589
|
-
const createdAt = new Date().toISOString();
|
|
615
|
+
const createdAt = input.createdAt ?? new Date().toISOString();
|
|
590
616
|
this.db.prepare(`
|
|
591
617
|
INSERT INTO queued_prompts (
|
|
592
618
|
prompt_id, local_session_id, context_key, prompt_text, display_prompt, local_image_paths_json,
|
|
@@ -619,6 +645,16 @@ export class StateStore {
|
|
|
619
645
|
return rows.map(mapQueuedPrompt);
|
|
620
646
|
}
|
|
621
647
|
|
|
648
|
+
hasQueuedPrompt(promptId: string): boolean {
|
|
649
|
+
return Boolean(this.db.prepare("SELECT 1 FROM queued_prompts WHERE prompt_id = ?").get(promptId));
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
peekQueuedPrompt(localSessionId: string): QueuedPromptRecord | undefined {
|
|
653
|
+
const row = this.db.prepare(`SELECT * FROM queued_prompts WHERE local_session_id = ?
|
|
654
|
+
ORDER BY created_at ASC, rowid ASC LIMIT 1`).get(localSessionId) as QueuedPromptRow | undefined;
|
|
655
|
+
return row ? mapQueuedPrompt(row) : undefined;
|
|
656
|
+
}
|
|
657
|
+
|
|
622
658
|
listQueuedPromptSessionIds(): string[] {
|
|
623
659
|
const rows = this.db.prepare(`
|
|
624
660
|
SELECT local_session_id, min(created_at) AS first_created_at, min(rowid) AS first_rowid
|
|
@@ -638,15 +674,32 @@ export class StateStore {
|
|
|
638
674
|
|
|
639
675
|
takeNextQueuedPrompt(localSessionId: string): QueuedPromptRecord | undefined {
|
|
640
676
|
const take = this.db.transaction(() => {
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
677
|
+
while (true) {
|
|
678
|
+
const row = this.db.prepare(`
|
|
679
|
+
SELECT * FROM queued_prompts
|
|
680
|
+
WHERE local_session_id = ?
|
|
681
|
+
ORDER BY created_at ASC, rowid ASC
|
|
682
|
+
LIMIT 1
|
|
683
|
+
`).get(localSessionId) as QueuedPromptRow | undefined;
|
|
684
|
+
if (!row) return undefined;
|
|
685
|
+
this.db.prepare("DELETE FROM queued_prompts WHERE prompt_id = ?").run(row.prompt_id);
|
|
686
|
+
if (!this.schedules.claimStart(row.prompt_id)) continue;
|
|
687
|
+
if (this.schedules.getRun(row.prompt_id)) {
|
|
688
|
+
const existing = this.getTurnAttempt(row.prompt_id);
|
|
689
|
+
if (existing) {
|
|
690
|
+
if (existing.submissionState !== "not_submitted" || existing.turnId) {
|
|
691
|
+
this.schedules.finish(row.prompt_id, "unknown", "存在无法安全重发的提交记录,未自动派发。");
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
this.updateTurnAttempt(row.prompt_id, { status: "accepted", pendingTurnId: null,
|
|
695
|
+
executionGeneration: this.executionGeneration(localSessionId) });
|
|
696
|
+
} else {
|
|
697
|
+
this.createTurnAttempt({ attemptId: row.prompt_id, localSessionId, contextKey: row.context_key,
|
|
698
|
+
promptText: row.prompt_text, replyMessageId: row.reply_message_id ?? undefined });
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
return mapQueuedPrompt(row);
|
|
702
|
+
}
|
|
650
703
|
});
|
|
651
704
|
return take();
|
|
652
705
|
}
|
|
@@ -658,6 +711,8 @@ export class StateStore {
|
|
|
658
711
|
`).get(promptId, localSessionId) as QueuedPromptRow | undefined;
|
|
659
712
|
if (!row) return undefined;
|
|
660
713
|
this.db.prepare("DELETE FROM queued_prompts WHERE prompt_id = ?").run(promptId);
|
|
714
|
+
const scheduled = this.schedules.getRun(promptId);
|
|
715
|
+
if (scheduled?.status === "queued") this.schedules.finish(promptId, "cancelled", "已取消排队。");
|
|
661
716
|
return mapQueuedPrompt(row);
|
|
662
717
|
});
|
|
663
718
|
return cancel();
|
|
@@ -676,6 +731,8 @@ export class StateStore {
|
|
|
676
731
|
recoveredFromTurnId?: string;
|
|
677
732
|
recoveryCount?: number;
|
|
678
733
|
retryCount?: number;
|
|
734
|
+
submissionState?: TurnSubmissionState;
|
|
735
|
+
executionGeneration?: number;
|
|
679
736
|
status?: Extract<TurnAttemptStatus, "accepted" | "running" | "recovering">;
|
|
680
737
|
createdAt?: string;
|
|
681
738
|
updatedAt?: string;
|
|
@@ -687,8 +744,8 @@ export class StateStore {
|
|
|
687
744
|
INSERT INTO turn_attempts (
|
|
688
745
|
attempt_id, local_session_id, context_key, prompt_text, local_image_paths_json,
|
|
689
746
|
message_id, reply_message_id, pending_turn_id, turn_id, recovered_from_turn_id,
|
|
690
|
-
recovery_count, retry_count, status, created_at, updated_at
|
|
691
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
747
|
+
recovery_count, retry_count, submission_state, status, created_at, updated_at, execution_generation
|
|
748
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
692
749
|
`).run(
|
|
693
750
|
input.attemptId,
|
|
694
751
|
input.localSessionId,
|
|
@@ -702,9 +759,11 @@ export class StateStore {
|
|
|
702
759
|
input.recoveredFromTurnId ?? null,
|
|
703
760
|
input.recoveryCount ?? 0,
|
|
704
761
|
input.retryCount ?? 0,
|
|
762
|
+
input.submissionState ?? (input.turnId ? "submitted" : "not_submitted"),
|
|
705
763
|
status,
|
|
706
764
|
createdAt,
|
|
707
765
|
updatedAt,
|
|
766
|
+
input.executionGeneration ?? this.executionGeneration(input.localSessionId),
|
|
708
767
|
);
|
|
709
768
|
return this.getTurnAttempt(input.attemptId)!;
|
|
710
769
|
}
|
|
@@ -759,6 +818,8 @@ export class StateStore {
|
|
|
759
818
|
recoveredFromTurnId: string | null;
|
|
760
819
|
recoveryCount: number;
|
|
761
820
|
retryCount: number;
|
|
821
|
+
submissionState: TurnSubmissionState;
|
|
822
|
+
executionGeneration: number;
|
|
762
823
|
status: TurnAttemptStatus;
|
|
763
824
|
}>,
|
|
764
825
|
): void {
|
|
@@ -769,7 +830,7 @@ export class StateStore {
|
|
|
769
830
|
this.db.prepare(`
|
|
770
831
|
UPDATE turn_attempts
|
|
771
832
|
SET message_id = ?, reply_message_id = ?, pending_turn_id = ?, turn_id = ?,
|
|
772
|
-
recovered_from_turn_id = ?, recovery_count = ?, retry_count = ?, status = ?, updated_at = ?
|
|
833
|
+
recovered_from_turn_id = ?, recovery_count = ?, retry_count = ?, submission_state = ?, execution_generation = ?, status = ?, updated_at = ?
|
|
773
834
|
WHERE attempt_id = ?
|
|
774
835
|
`).run(
|
|
775
836
|
value(patch.messageId, existing.messageId),
|
|
@@ -779,6 +840,8 @@ export class StateStore {
|
|
|
779
840
|
value(patch.recoveredFromTurnId, existing.recoveredFromTurnId),
|
|
780
841
|
patch.recoveryCount ?? existing.recoveryCount,
|
|
781
842
|
patch.retryCount ?? existing.retryCount,
|
|
843
|
+
patch.submissionState ?? (patch.turnId ? "submitted" : existing.submissionState),
|
|
844
|
+
patch.executionGeneration ?? existing.executionGeneration,
|
|
782
845
|
patch.status ?? existing.status,
|
|
783
846
|
new Date().toISOString(),
|
|
784
847
|
attemptId,
|
|
@@ -788,7 +851,7 @@ export class StateStore {
|
|
|
788
851
|
bindTurnAttempt(localSessionId: string, turnId: string): TurnAttemptRecord | undefined {
|
|
789
852
|
const attempt = this.findIncompleteTurnAttemptForSession(localSessionId);
|
|
790
853
|
if (!attempt || (attempt.turnId && attempt.turnId !== turnId)) return undefined;
|
|
791
|
-
this.updateTurnAttempt(attempt.attemptId, { turnId, status: "running" });
|
|
854
|
+
this.updateTurnAttempt(attempt.attemptId, { turnId, status: "running", submissionState: "submitted" });
|
|
792
855
|
return this.getTurnAttempt(attempt.attemptId);
|
|
793
856
|
}
|
|
794
857
|
|
|
@@ -801,6 +864,9 @@ export class StateStore {
|
|
|
801
864
|
SET status = ?, updated_at = ?
|
|
802
865
|
WHERE turn_id = ?
|
|
803
866
|
`).run(status, new Date().toISOString(), turnId);
|
|
867
|
+
const runs = this.db.prepare(`SELECT s.id FROM scheduled_runs s JOIN turn_attempts t ON t.attempt_id = s.id
|
|
868
|
+
WHERE t.turn_id = ?`).all(turnId) as Array<{ id: string }>;
|
|
869
|
+
for (const run of runs) this.schedules.finish(run.id, status);
|
|
804
870
|
}
|
|
805
871
|
|
|
806
872
|
findIncompleteTurnAttemptByTurnId(turnId: string): TurnAttemptRecord | undefined {
|
|
@@ -820,12 +886,6 @@ export class StateStore {
|
|
|
820
886
|
return existing;
|
|
821
887
|
}
|
|
822
888
|
|
|
823
|
-
restoreTurnAttemptAfterCancellationFailure(attempt: TurnAttemptRecord): void {
|
|
824
|
-
const current = this.getTurnAttempt(attempt.attemptId);
|
|
825
|
-
if (current?.status !== "cancelling") return;
|
|
826
|
-
this.updateTurnAttempt(attempt.attemptId, { status: attempt.status });
|
|
827
|
-
}
|
|
828
|
-
|
|
829
889
|
touchTurnAttempt(turnId: string, activityAt = new Date()): void {
|
|
830
890
|
const timestamp = activityAt.toISOString();
|
|
831
891
|
const throttleCutoff = new Date(activityAt.getTime() - 15_000).toISOString();
|
|
@@ -838,45 +898,85 @@ export class StateStore {
|
|
|
838
898
|
`).run(timestamp, turnId, throttleCutoff);
|
|
839
899
|
}
|
|
840
900
|
|
|
841
|
-
|
|
901
|
+
hasUnknownTurnAttemptForSession(localSessionId: string): boolean {
|
|
902
|
+
return Boolean(this.db.prepare("SELECT 1 FROM turn_attempts WHERE local_session_id = ? AND status = 'unknown' LIMIT 1")
|
|
903
|
+
.get(localSessionId));
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
hasCancellationRequestedForSession(localSessionId: string): boolean {
|
|
907
|
+
return Boolean(this.db.prepare("SELECT 1 FROM turn_attempts WHERE local_session_id = ? AND status = 'cancelling' LIMIT 1")
|
|
908
|
+
.get(localSessionId));
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
beginTurnAttemptSubmission(attemptId: string, recordProvenance?: () => void): void {
|
|
912
|
+
this.db.transaction(() => {
|
|
913
|
+
const result = this.db.prepare(`
|
|
914
|
+
UPDATE turn_attempts SET submission_state = 'submission_unknown', updated_at = ?
|
|
915
|
+
WHERE attempt_id = ? AND submission_state = 'not_submitted'
|
|
916
|
+
AND status IN ('accepted', 'recovering') AND turn_id IS NULL
|
|
917
|
+
AND execution_generation = COALESCE((SELECT generation FROM task_execution_control
|
|
918
|
+
WHERE local_session_id = turn_attempts.local_session_id), 0)
|
|
919
|
+
`).run(new Date().toISOString(), attemptId);
|
|
920
|
+
if (result.changes !== 1) throw new Error("Prompt submission is not provably safe; automatic replay refused.");
|
|
921
|
+
recordProvenance?.();
|
|
922
|
+
})();
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
executionGeneration(localSessionId: string): number {
|
|
926
|
+
const row = this.db.prepare("SELECT generation FROM task_execution_control WHERE local_session_id = ?")
|
|
927
|
+
.get(localSessionId) as { generation: number } | undefined;
|
|
928
|
+
return row?.generation ?? 0;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
requestSessionExecutionStop(localSessionId: string): void {
|
|
932
|
+
this.db.transaction(() => {
|
|
933
|
+
this.db.prepare(`INSERT INTO task_execution_control (local_session_id, generation) VALUES (?, 1)
|
|
934
|
+
ON CONFLICT(local_session_id) DO UPDATE SET generation = generation + 1`).run(localSessionId);
|
|
935
|
+
this.db.prepare(`UPDATE turn_attempts SET status = 'cancelling', updated_at = ?
|
|
936
|
+
WHERE local_session_id = ? AND status IN ('accepted', 'running', 'recovering', 'unknown')
|
|
937
|
+
AND attempt_id NOT IN (SELECT prompt_id FROM queued_prompts)`)
|
|
938
|
+
.run(new Date().toISOString(), localSessionId);
|
|
939
|
+
})();
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
prepareUnstartedTurnAttemptRetry(attemptId: string): TurnAttemptRecord | undefined {
|
|
842
943
|
const existing = this.getTurnAttempt(attemptId);
|
|
843
|
-
if (!existing
|
|
944
|
+
if (!existing || existing.turnId || existing.submissionState !== "not_submitted"
|
|
945
|
+
|| !isIncompleteTurnAttemptStatus(existing.status)) return undefined;
|
|
844
946
|
this.updateTurnAttempt(attemptId, {
|
|
845
947
|
pendingTurnId: null,
|
|
846
|
-
|
|
847
|
-
recoveredFromTurnId: recoveredFromTurnId ?? existing.turnId ?? existing.recoveredFromTurnId ?? null,
|
|
848
|
-
recoveryCount: existing.recoveryCount + 1,
|
|
948
|
+
retryCount: existing.retryCount + 1,
|
|
849
949
|
status: "recovering",
|
|
850
950
|
});
|
|
851
951
|
return this.getTurnAttempt(attemptId);
|
|
852
952
|
}
|
|
853
953
|
|
|
854
|
-
|
|
954
|
+
prepareTurnAttemptRecovery(attemptId: string, recoveredFromTurnId?: string): TurnAttemptRecord | undefined {
|
|
855
955
|
const existing = this.getTurnAttempt(attemptId);
|
|
856
|
-
if (!existing || existing.turnId
|
|
857
|
-
return undefined;
|
|
858
|
-
}
|
|
956
|
+
if (!existing || existing.turnId || existing.submissionState !== "not_submitted"
|
|
957
|
+
|| !isIncompleteTurnAttemptStatus(existing.status)) return undefined;
|
|
859
958
|
this.updateTurnAttempt(attemptId, {
|
|
860
|
-
|
|
861
|
-
turnId: null,
|
|
862
|
-
recoveredFromTurnId: failedTurnId,
|
|
863
|
-
retryCount: existing.retryCount + 1,
|
|
864
|
-
status: "recovering",
|
|
959
|
+
recoveredFromTurnId, recoveryCount: existing.recoveryCount + 1, status: "recovering",
|
|
865
960
|
});
|
|
866
961
|
return this.getTurnAttempt(attemptId);
|
|
867
962
|
}
|
|
868
963
|
|
|
869
|
-
|
|
964
|
+
prepareTurnAttemptRetry(attemptId: string, failedTurnId: string, verifiedContinuation = false): TurnAttemptRecord | undefined {
|
|
870
965
|
const existing = this.getTurnAttempt(attemptId);
|
|
871
|
-
if (!
|
|
966
|
+
if (!verifiedContinuation || !existing || existing.turnId !== failedTurnId
|
|
967
|
+
|| !isIncompleteTurnAttemptStatus(existing.status)) return undefined;
|
|
872
968
|
this.updateTurnAttempt(attemptId, {
|
|
873
|
-
pendingTurnId: null,
|
|
874
|
-
retryCount: existing.retryCount + 1,
|
|
875
|
-
status: "recovering",
|
|
969
|
+
pendingTurnId: null, turnId: null, recoveredFromTurnId: failedTurnId,
|
|
970
|
+
retryCount: existing.retryCount + 1, status: "recovering", submissionState: "not_submitted",
|
|
876
971
|
});
|
|
877
972
|
return this.getTurnAttempt(attemptId);
|
|
878
973
|
}
|
|
879
974
|
|
|
975
|
+
acknowledgeUnknownTurnAttempts(localSessionId: string): void {
|
|
976
|
+
this.db.prepare("UPDATE turn_attempts SET status = 'interrupted' WHERE local_session_id = ? AND status = 'unknown'")
|
|
977
|
+
.run(localSessionId);
|
|
978
|
+
}
|
|
979
|
+
|
|
880
980
|
rebindPendingTurnMessages(localSessionId: string, sourceTurnId: string, targetTurnId: string): void {
|
|
881
981
|
const now = new Date().toISOString();
|
|
882
982
|
const rebind = this.db.transaction(() => {
|
|
@@ -1857,10 +1957,7 @@ export class StateStore {
|
|
|
1857
1957
|
.prepare(`
|
|
1858
1958
|
SELECT COUNT(*) AS count
|
|
1859
1959
|
FROM sessions
|
|
1860
|
-
WHERE
|
|
1861
|
-
OR EXISTS (
|
|
1862
|
-
SELECT 1 FROM queued_prompts WHERE queued_prompts.local_session_id = sessions.local_session_id
|
|
1863
|
-
)
|
|
1960
|
+
WHERE ${RESTART_BLOCKING_WORK_SQL}
|
|
1864
1961
|
`)
|
|
1865
1962
|
.get() as { count: number };
|
|
1866
1963
|
const pending = this.db.prepare(`
|
|
@@ -1882,6 +1979,11 @@ export class StateStore {
|
|
|
1882
1979
|
};
|
|
1883
1980
|
}
|
|
1884
1981
|
|
|
1982
|
+
sessionBlocksSafeRestart(localSessionId: string): boolean {
|
|
1983
|
+
return Boolean(this.db.prepare(`SELECT 1 FROM sessions WHERE local_session_id = ? AND (${RESTART_BLOCKING_WORK_SQL})`)
|
|
1984
|
+
.get(localSessionId));
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1885
1987
|
findSessionByRemoteSessionId(
|
|
1886
1988
|
remoteSessionId: string,
|
|
1887
1989
|
contextKey?: string,
|
|
@@ -2322,9 +2424,18 @@ export class StateStore {
|
|
|
2322
2424
|
const existing = new Set(
|
|
2323
2425
|
(this.db.pragma("table_info(turn_attempts)") as Array<{ name: string }>).map((column) => column.name),
|
|
2324
2426
|
);
|
|
2427
|
+
if (!existing.has("submission_state")) {
|
|
2428
|
+
this.db.transaction(() => {
|
|
2429
|
+
this.db.exec("ALTER TABLE turn_attempts ADD COLUMN submission_state TEXT NOT NULL DEFAULT 'submission_unknown'");
|
|
2430
|
+
this.db.exec("UPDATE turn_attempts SET submission_state = 'submitted' WHERE turn_id IS NOT NULL");
|
|
2431
|
+
})();
|
|
2432
|
+
}
|
|
2325
2433
|
if (!existing.has("retry_count")) {
|
|
2326
2434
|
this.db.exec("ALTER TABLE turn_attempts ADD COLUMN retry_count INTEGER NOT NULL DEFAULT 0");
|
|
2327
2435
|
}
|
|
2436
|
+
if (!existing.has("execution_generation")) {
|
|
2437
|
+
this.db.exec("ALTER TABLE turn_attempts ADD COLUMN execution_generation INTEGER NOT NULL DEFAULT 0");
|
|
2438
|
+
}
|
|
2328
2439
|
}
|
|
2329
2440
|
|
|
2330
2441
|
private ensureQueuedPromptColumns(): void {
|
|
@@ -2335,6 +2446,16 @@ export class StateStore {
|
|
|
2335
2446
|
this.db.exec("ALTER TABLE queued_prompts ADD COLUMN display_prompt TEXT");
|
|
2336
2447
|
}
|
|
2337
2448
|
}
|
|
2449
|
+
|
|
2450
|
+
private ensureRecentContextReceiptColumns(): void {
|
|
2451
|
+
const existing = new Set(
|
|
2452
|
+
(this.db.pragma("table_info(recent_context_receipts)") as Array<{ name: string }>).map((column) => column.name),
|
|
2453
|
+
);
|
|
2454
|
+
if (!existing.has("prompt_message_id")) {
|
|
2455
|
+
// Old receipts have no provable source Prompt, so they cannot be stop boundaries.
|
|
2456
|
+
this.db.exec("ALTER TABLE recent_context_receipts ADD COLUMN prompt_message_id TEXT NOT NULL DEFAULT ''");
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2338
2459
|
}
|
|
2339
2460
|
|
|
2340
2461
|
const MAX_TASK_TITLE_LENGTH = 120;
|
|
@@ -2462,6 +2583,8 @@ function mapTurnAttempt(row: TurnAttemptRow): TurnAttemptRecord {
|
|
|
2462
2583
|
recoveredFromTurnId: row.recovered_from_turn_id ?? undefined,
|
|
2463
2584
|
recoveryCount: row.recovery_count,
|
|
2464
2585
|
retryCount: row.retry_count,
|
|
2586
|
+
submissionState: row.submission_state,
|
|
2587
|
+
executionGeneration: row.execution_generation,
|
|
2465
2588
|
status: row.status,
|
|
2466
2589
|
createdAt: row.created_at,
|
|
2467
2590
|
updatedAt: row.updated_at,
|
package/src/state/migrations.ts
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
1
|
export const migrations = [
|
|
2
|
+
`CREATE TABLE IF NOT EXISTS execution_provenance (
|
|
3
|
+
submission_id TEXT PRIMARY KEY, instruction_id TEXT NOT NULL, attempt_id TEXT NOT NULL,
|
|
4
|
+
local_session_id TEXT NOT NULL, turn_id TEXT, trigger TEXT NOT NULL, parent_source_turn_id TEXT,
|
|
5
|
+
scheduled_for INTEGER, submitted_at INTEGER NOT NULL, agent_name TEXT NOT NULL,
|
|
6
|
+
model_provider TEXT, model TEXT, reasoning_effort TEXT, permission_mode TEXT NOT NULL, cwd TEXT NOT NULL
|
|
7
|
+
);
|
|
8
|
+
CREATE INDEX IF NOT EXISTS idx_execution_provenance_attempt ON execution_provenance(attempt_id);
|
|
9
|
+
CREATE INDEX IF NOT EXISTS idx_execution_provenance_turn ON execution_provenance(turn_id, local_session_id);`,
|
|
10
|
+
`CREATE TABLE IF NOT EXISTS task_execution_control (
|
|
11
|
+
local_session_id TEXT PRIMARY KEY,
|
|
12
|
+
generation INTEGER NOT NULL DEFAULT 0
|
|
13
|
+
);`,
|
|
2
14
|
`
|
|
3
15
|
CREATE TABLE IF NOT EXISTS user_contexts (
|
|
4
16
|
context_key TEXT PRIMARY KEY,
|
|
@@ -223,4 +235,29 @@ export const migrations = [
|
|
|
223
235
|
value_json TEXT NOT NULL
|
|
224
236
|
);
|
|
225
237
|
`,
|
|
238
|
+
`
|
|
239
|
+
CREATE TABLE IF NOT EXISTS scheduled_jobs (
|
|
240
|
+
id TEXT PRIMARY KEY,
|
|
241
|
+
local_session_id TEXT NOT NULL,
|
|
242
|
+
context_key TEXT NOT NULL,
|
|
243
|
+
status TEXT NOT NULL,
|
|
244
|
+
next_run_at INTEGER,
|
|
245
|
+
revision INTEGER NOT NULL,
|
|
246
|
+
value_json TEXT NOT NULL
|
|
247
|
+
);
|
|
248
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_jobs_due ON scheduled_jobs(status, next_run_at);
|
|
249
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_jobs_context ON scheduled_jobs(context_key);
|
|
250
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_jobs_session ON scheduled_jobs(local_session_id);
|
|
251
|
+
CREATE TABLE IF NOT EXISTS scheduled_runs (
|
|
252
|
+
id TEXT PRIMARY KEY,
|
|
253
|
+
job_id TEXT NOT NULL,
|
|
254
|
+
occurrence_key TEXT NOT NULL,
|
|
255
|
+
status TEXT NOT NULL,
|
|
256
|
+
value_json TEXT NOT NULL,
|
|
257
|
+
UNIQUE(job_id, occurrence_key)
|
|
258
|
+
);
|
|
259
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_runs_status ON scheduled_runs(status);
|
|
260
|
+
CREATE INDEX IF NOT EXISTS idx_scheduled_runs_job ON scheduled_runs(job_id);
|
|
261
|
+
CREATE INDEX IF NOT EXISTS idx_turn_attempts_pending_turn ON turn_attempts(pending_turn_id);
|
|
262
|
+
`,
|
|
226
263
|
] as const;
|
|
@@ -142,7 +142,7 @@ export class SafeRestartNotifier {
|
|
|
142
142
|
const waitingTasks = status.phase === "cancelled"
|
|
143
143
|
? []
|
|
144
144
|
: this.store.listAllSessions()
|
|
145
|
-
.filter((session) =>
|
|
145
|
+
.filter((session) => this.store.sessionBlocksSafeRestart(session.localSessionId))
|
|
146
146
|
.map((session) => ({
|
|
147
147
|
id: session.remoteSessionId ?? session.localSessionId,
|
|
148
148
|
localSessionId: session.localSessionId,
|