@keyou007/agent-bot 0.1.25 → 0.1.27-alpha.0

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +12 -6
  3. package/README.zh.md +12 -6
  4. package/config.example.yaml +3 -2
  5. package/dist/cli/AutostartManager.js +1 -1
  6. package/dist/config/SettingsStore.js +10 -5
  7. package/dist/config/SettingsStore.js.map +1 -1
  8. package/dist/config/loadConfig.js +2 -1
  9. package/dist/config/loadConfig.js.map +1 -1
  10. package/dist/config/schema.js +5 -1
  11. package/dist/config/schema.js.map +1 -1
  12. package/dist/feishu/CardRenderer.js +5 -7
  13. package/dist/feishu/CardRenderer.js.map +1 -1
  14. package/dist/feishu/FeishuConnector.js +1 -1
  15. package/dist/feishu/FeishuConnector.js.map +1 -1
  16. package/dist/feishu/FeishuTurnPresenter.js +1 -1
  17. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  18. package/dist/feishu/SettingsCard.js +4 -3
  19. package/dist/feishu/SettingsCard.js.map +1 -1
  20. package/dist/index.js +3 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/presentation/TurnStateReducer.js +1 -1
  23. package/dist/presentation/TurnStateReducer.js.map +1 -1
  24. package/dist/proxy/ProxySessionController.js +191 -12
  25. package/dist/proxy/ProxySessionController.js.map +1 -1
  26. package/dist/state/StateStore.js +67 -3
  27. package/dist/state/StateStore.js.map +1 -1
  28. package/dist/terminal/TerminalCards.js +1 -1
  29. package/dist/terminal/TerminalPage.js +17 -14
  30. package/dist/terminal/TerminalPage.js.map +1 -1
  31. package/dist/terminal/TerminalServer.js +60 -66
  32. package/dist/terminal/TerminalServer.js.map +1 -1
  33. package/docs/technical-reference.md +14 -15
  34. package/docs/technical-reference.zh.md +14 -15
  35. package/npm-shrinkwrap.json +2 -2
  36. package/package.json +1 -1
  37. package/skills/agent-bot/SKILL.md +6 -3
  38. package/src/cli/AutostartManager.ts +1 -1
  39. package/src/config/SettingsStore.ts +12 -7
  40. package/src/config/loadConfig.ts +2 -1
  41. package/src/config/schema.ts +6 -1
  42. package/src/feishu/CardRenderer.ts +5 -7
  43. package/src/feishu/FeishuConnector.ts +1 -1
  44. package/src/feishu/FeishuTurnPresenter.ts +1 -1
  45. package/src/feishu/SettingsCard.ts +3 -2
  46. package/src/index.ts +3 -1
  47. package/src/presentation/TurnStateReducer.ts +1 -1
  48. package/src/proxy/ProxySessionController.ts +191 -12
  49. package/src/runtime/types.ts +1 -1
  50. package/src/state/ExecutionProvenanceStore.ts +1 -1
  51. package/src/state/StateStore.ts +71 -3
  52. package/src/terminal/TerminalCards.ts +1 -1
  53. package/src/terminal/TerminalPage.ts +17 -14
  54. package/src/terminal/TerminalServer.ts +54 -56
@@ -135,6 +135,7 @@ interface StartTurnOptions {
135
135
  preserveAttemptOnFailure?: boolean;
136
136
  approvedPlanTurnId?: string;
137
137
  responseContinuationTurnId?: string;
138
+ recoveryContinuationTurnId?: string;
138
139
  }
139
140
 
140
141
  interface PendingMessageReference {
@@ -210,9 +211,19 @@ const RESET_HISTORY_PAGE_SIZE = 10;
210
211
  const REMOTE_TURN_HISTORY_REFRESH_INTERVAL_MS = 30_000;
211
212
  const MAX_LLM_TURN_RETRIES = 3;
212
213
  const QUEUED_PROMPT_RETRY_DELAY_MS = 5_000;
213
- const RECOVERY_ACTIVITY_WINDOW_MS = 10 * 60 * 1_000;
214
+ const RECOVERY_ACTIVITY_WINDOW_MS = 20 * 60 * 1_000;
214
215
  const RECOVERY_RETRY_WINDOW_MS = 60_000;
215
216
  const RECOVERY_HEARTBEAT_INTERVAL_MS = 60 * 1_000;
217
+ const RECOVERY_CONTINUATION_PROMPT = "上一轮因主机或 Agent Bot 重启而中断。请在当前会话和工作目录中继续完成尚未完成的任务,遵守已有用户要求。先核实已有执行结果,保留已完成的工作,不要重复已完成的操作;不要重新执行整条原始指令。";
218
+ const RECOVERY_RESULTS = {
219
+ reattached: "已重新连接原轮次,正在继续监控执行;未重新执行原指令。",
220
+ submitted: "已恢复此前确认尚未提交的请求,并提交执行。",
221
+ completed: "重启恢复检查完成:原轮次已完成,未重新执行原指令。",
222
+ failed: "重启恢复检查完成:原轮次已失败,未重新执行原指令。请查看执行详情后发送消息继续。",
223
+ cancelled: "重启恢复检查完成:请求已提交,但原轮次已中断。为避免重复执行,未重新执行原指令,也未自动创建续跑轮次;请发送“继续”续跑。",
224
+ continuing: "原轮次已中断,正在原任务中自动继续;未重新执行原指令。",
225
+ unknown: "重启恢复检查未完成:原执行结果待核实,未重新执行原指令。请核实执行记录。",
226
+ } as const;
216
227
  const SHELL_COMMAND_JOB_POLL_INTERVAL_MS = 1_000;
217
228
  const SHELL_COMMAND_JOB_RELAUNCH_DELAY_MS = 5_000;
218
229
  const APP_SERVER_RELEASE_POLL_INTERVAL_MS = 500;
@@ -587,6 +598,8 @@ export class ProxySessionController {
587
598
  private readonly recoveryRetryTimers = new Map<string, NodeJS.Timeout>();
588
599
  private readonly recoveryRetryStartedAt = new Map<string, number>();
589
600
  private readonly recoveredLiveAttempts = new Set<string>();
601
+ private readonly recoveryResultNotices = new Set<string>();
602
+ private readonly recoverySupersededSessions = new Set<string>();
590
603
  private recoveryClosed = false;
591
604
  private readonly pendingMessageReferences = new Map<string, PendingMessageReference>();
592
605
  private readonly relatedReactionMessageIds = new Map<string, string[]>();
@@ -658,6 +671,10 @@ export class ProxySessionController {
658
671
  // For accepted messages, claim durable deduplication before acknowledgement so event
659
672
  // retries cannot add duplicate reactions.
660
673
  if (!this.store.claimInboundEvent(message.messageId, "message")) return;
674
+ if (!message.text.trim().startsWith("/")) {
675
+ const currentId = this.store.getUserContext(message.contextKey)?.currentSessionId;
676
+ if (currentId) this.recoverySupersededSessions.add(currentId);
677
+ }
661
678
  const acceptedAt = Date.now();
662
679
  const receivedAt = message.receivedAt ?? acceptedAt;
663
680
  const deliveryDelayMs = message.createdAt === undefined
@@ -1067,6 +1084,12 @@ export class ProxySessionController {
1067
1084
  const scopedAction = contextKey === resolvedAction.contextKey
1068
1085
  ? resolvedAction
1069
1086
  : { ...resolvedAction, contextKey };
1087
+ if (["settings_provider_select", "settings_model_select", "settings_thinking_select", "settings_permission_select",
1088
+ "model_select", "turn_cancel", "session_stop", "turn_reset"].includes(String(scopedAction.value.action ?? ""))) {
1089
+ const sessionId = String(scopedAction.value.sessionId ?? "")
1090
+ || this.store.getUserContext(contextKey)?.currentSessionId;
1091
+ if (sessionId && this.store.getSessionForContext(sessionId, contextKey)) this.recoverySupersededSessions.add(sessionId);
1092
+ }
1070
1093
  const replyTarget = isThreadContextKey(contextKey) && action.messageId
1071
1094
  ? { messageId: action.messageId, replyInThread: true as const }
1072
1095
  : undefined;
@@ -1453,6 +1476,8 @@ export class ProxySessionController {
1453
1476
  this.recoveryRetryTimers.clear();
1454
1477
  this.recoveryRetryStartedAt.clear();
1455
1478
  this.recoveredLiveAttempts.clear();
1479
+ this.recoveryResultNotices.clear();
1480
+ this.recoverySupersededSessions.clear();
1456
1481
  for (const schedule of this.appServerReleaseSchedules.values()) {
1457
1482
  if (schedule.timer) clearTimeout(schedule.timer);
1458
1483
  }
@@ -2548,9 +2573,16 @@ export class ProxySessionController {
2548
2573
  private async runStartupRecovery(): Promise<void> {
2549
2574
  await this.finishPersistedCancellationRequests();
2550
2575
  await this.recoverShellCommandJobs();
2576
+ const recoveryCutoff = Date.now() - RECOVERY_ACTIVITY_WINDOW_MS;
2577
+ const cutoff = new Date(recoveryCutoff).toISOString();
2578
+ for (const attempt of this.store.listRecentlyInterruptedTurnAttempts(cutoff)) {
2579
+ const session = this.store.getSession(attempt.localSessionId);
2580
+ if (session && this.canContinueAfterRestart(attempt, session)) {
2581
+ this.store.prepareInterruptedTurnAttemptRecovery(attempt.attemptId, cutoff);
2582
+ }
2583
+ }
2551
2584
  this.backfillTurnAttemptsForUpgrade();
2552
2585
  const attempts = this.store.listIncompleteTurnAttempts();
2553
- const recoveryCutoff = Date.now() - RECOVERY_ACTIVITY_WINDOW_MS;
2554
2586
  const recentAttempts = attempts.filter((attempt) => isRecoveryAttemptRecent(attempt, recoveryCutoff));
2555
2587
  if (recentAttempts.length > 0) {
2556
2588
  this.logger.warn(
@@ -2573,6 +2605,7 @@ export class ProxySessionController {
2573
2605
  if (!this.recoveryRetryTimers.has(attempt.attemptId)) this.recoveryRetryStartedAt.delete(attempt.attemptId);
2574
2606
  }
2575
2607
  }
2608
+ if (this.recoveryClosed) return;
2576
2609
  for (const pending of this.store.listPendingProviderSettings()) {
2577
2610
  await this.applyPendingProviderWhenIdle(pending.localSessionId);
2578
2611
  }
@@ -2581,6 +2614,9 @@ export class ProxySessionController {
2581
2614
 
2582
2615
  private async finishPersistedCancellationRequests(): Promise<void> {
2583
2616
  for (const attempt of this.store.listCancellationRequestedTurnAttempts()) {
2617
+ if (attempt.executionGeneration === this.store.executionGeneration(attempt.localSessionId)) {
2618
+ this.store.requestSessionExecutionStop(attempt.localSessionId);
2619
+ }
2584
2620
  const session = this.store.getSession(attempt.localSessionId);
2585
2621
  if (!attempt.turnId) {
2586
2622
  if (attempt.submissionState !== "not_submitted") {
@@ -2664,6 +2700,12 @@ export class ProxySessionController {
2664
2700
  const persistedTurnId = latest?.turnId;
2665
2701
  const pendingTurnId = persistedTurnId?.startsWith("pending_") ? persistedTurnId : undefined;
2666
2702
  const turnId = pendingTurnId ? undefined : persistedTurnId ?? session.lastTurnId;
2703
+ if (turnId && this.store.hasStoppedTurnAttemptForTurn(turnId)) {
2704
+ this.store.updateSession(session.localSessionId, { status: "ready" });
2705
+ continue;
2706
+ }
2707
+ const previousAttempt = turnId ? this.store.findLatestTurnAttemptByTurnId(turnId) : undefined;
2708
+ if (previousAttempt && !this.store.isLatestTurnAttempt(previousAttempt.attemptId)) continue;
2667
2709
  if (persistedTurnId && this.store.schedules.ownsTurn(persistedTurnId)) continue;
2668
2710
  if (turnId && this.store.schedules.ownsTurn(turnId)) continue;
2669
2711
  const replyTarget = snapshot?.replyTarget?.replyInThread ? snapshot.replyTarget : undefined;
@@ -2678,15 +2720,16 @@ export class ProxySessionController {
2678
2720
  turnId,
2679
2721
  status: turnId ? "running" : "accepted",
2680
2722
  submissionState: turnId ? "submitted" : "submission_unknown",
2681
- createdAt: latest?.updatedAt ?? session.updatedAt,
2682
- updatedAt: latest?.updatedAt ?? session.updatedAt,
2723
+ createdAt: previousAttempt?.createdAt ?? latest?.updatedAt ?? session.updatedAt,
2724
+ updatedAt: previousAttempt?.updatedAt ?? latest?.updatedAt ?? session.updatedAt,
2725
+ executionGeneration: previousAttempt?.executionGeneration,
2683
2726
  });
2684
2727
  }
2685
2728
  }
2686
2729
 
2687
2730
  private async expireStaleTurnAttempt(
2688
2731
  attempt: TurnAttemptRecord,
2689
- message = "执行中断已超过 10 分钟,未自动恢复。",
2732
+ message = "执行中断已超过 20 分钟,未自动恢复。",
2690
2733
  ): Promise<void> {
2691
2734
  if (attempt.submissionState !== "not_submitted") {
2692
2735
  await this.markAttemptUnknown(attempt, `${message} 原执行结果待核实,未自动重发。`);
@@ -2764,7 +2807,7 @@ export class ProxySessionController {
2764
2807
  const replyTarget = attempt.replyMessageId
2765
2808
  ? { messageId: attempt.replyMessageId, replyInThread: true as const } : undefined;
2766
2809
  await this.outbound.withReplyTarget(attempt.contextKey, replyTarget, async () => {
2767
- await this.outbound.sendText(attempt.contextKey, message);
2810
+ await this.notifyRecoveryResult(attempt, "unknown", message);
2768
2811
  if (writerConflict && session) await this.presentThreadWriterConflict(session, attempt.contextKey, error, false);
2769
2812
  });
2770
2813
  } catch (notificationError) {
@@ -2772,7 +2815,7 @@ export class ProxySessionController {
2772
2815
  }
2773
2816
  return;
2774
2817
  }
2775
- this.store.updateTurnAttempt(attemptId, { status: "recovering" });
2818
+ this.store.markTurnAttemptRecovering(attemptId);
2776
2819
  this.scheduleRecoveryRetry(attemptId, monitoredTurnId);
2777
2820
  }
2778
2821
 
@@ -2819,7 +2862,7 @@ export class ProxySessionController {
2819
2862
  );
2820
2863
  if (announce) {
2821
2864
  await this.outbound.withReplyTarget(contextKey, replyTarget, () =>
2822
- this.outbound.sendText(contextKey, "检测到任务在 Agent Bot 重启前尚未完成,正在自动恢复。"),
2865
+ this.outbound.sendText(contextKey, "检测到重启前存在未完成任务,正在核对远端执行状态并尝试恢复。"),
2823
2866
  ).catch((error: unknown) => {
2824
2867
  this.logger.warn(
2825
2868
  { error, attemptId: attempt.attemptId, contextKey },
@@ -2850,6 +2893,10 @@ export class ProxySessionController {
2850
2893
  }
2851
2894
  }
2852
2895
  const remoteTurnBelongsToAttempt = remoteTurnMatchesAttempt(remote, attempt);
2896
+ if (isPendingRecoveryContinuation(attempt)) {
2897
+ await this.submitRecoveryContinuation(attempt, session);
2898
+ return;
2899
+ }
2853
2900
  if (remote && remoteTurnBelongsToAttempt && remote.lastTurnStatus === "completed") {
2854
2901
  await this.reconcileRecoveredRemoteTurn(attempt, session, remote.lastTurnId);
2855
2902
  return;
@@ -2863,7 +2910,7 @@ export class ProxySessionController {
2863
2910
  return;
2864
2911
  }
2865
2912
  if (remote && isRemoteSessionActive(remote) && !remoteTurnBelongsToAttempt) {
2866
- this.store.updateTurnAttempt(attempt.attemptId, { status: "recovering" });
2913
+ this.store.markTurnAttemptRecovering(attempt.attemptId);
2867
2914
  if (announce) {
2868
2915
  await this.outbound.withReplyTarget(contextKey, replyTarget, () =>
2869
2916
  this.outbound.sendText(contextKey, "任务中检测到另一轮仍在执行;本次恢复将在它结束后重试。"),
@@ -2887,7 +2934,99 @@ export class ProxySessionController {
2887
2934
  if (job) await this.notifySchedule(job, `定时任务「${job.spec.name}」:${detail}`);
2888
2935
  }
2889
2936
 
2937
+ private canContinueAfterRestart(attempt: TurnAttemptRecord, source: SessionRecord): boolean {
2938
+ const current = this.store.getSession(source.localSessionId);
2939
+ if (!current) return false;
2940
+ const sourceTurnId = isPendingRecoveryContinuation(attempt) ? attempt.recoveredFromTurnId : attempt.turnId;
2941
+ const priorSettings = sourceTurnId ? this.store.provenance.forTurn(sourceTurnId, source.localSessionId)?.settings : undefined;
2942
+ return !this.recoveryClosed && Boolean(current.remoteSessionId) && current.status !== "closed"
2943
+ && current.remoteSessionId === source.remoteSessionId && current.lastTurnId === sourceTurnId
2944
+ && current.agentName === source.agentName && this.runtimes.forAgent(current.agentName).kind === "codex"
2945
+ && attempt.executionGeneration === this.store.executionGeneration(source.localSessionId)
2946
+ && !this.sessionResets.has(source.localSessionId) && !this.recoverySupersededSessions.has(source.localSessionId)
2947
+ && !this.store.getPendingProviderSettings(source.localSessionId)
2948
+ && !this.store.schedules.getRun(attempt.attemptId) && this.store.isLatestTurnAttempt(attempt.attemptId)
2949
+ && !this.store.hasUnknownTurnAttemptForSession(source.localSessionId)
2950
+ && !this.store.hasCancellationRequestedForSession(source.localSessionId)
2951
+ && this.store.countQueuedPrompts(source.localSessionId) === 0
2952
+ && [source, ...(priorSettings ? [priorSettings] : [])].every((settings) =>
2953
+ (["cwd", "agentName", "modelProvider", "model", "reasoningEffort", "permissionMode"] as const)
2954
+ .every((key) => settings[key] === undefined || settings[key] === current[key]));
2955
+ }
2956
+
2957
+ private async assertRecoveryContinuation(loaded: LoadedSession, attemptId: string): Promise<void> {
2958
+ const attempt = this.store.getTurnAttempt(attemptId);
2959
+ if (!attempt || !isPendingRecoveryContinuation(attempt) || !this.canContinueAfterRestart(attempt, loaded.record)) {
2960
+ throw new TurnStoppedBeforeSubmissionError();
2961
+ }
2962
+ const remote = await loaded.runtime.readRemoteSession?.(loaded.record.remoteSessionId!);
2963
+ if (!remote || remote.lastTurnId !== attempt.recoveredFromTurnId || remote.lastTurnStatus !== "interrupted"
2964
+ || isRemoteSessionActive(remote) || !this.canContinueAfterRestart(attempt, loaded.record)) {
2965
+ throw new TurnStoppedBeforeSubmissionError();
2966
+ }
2967
+ }
2968
+
2969
+ private async submitRecoveryContinuation(attempt: TurnAttemptRecord, source: SessionRecord): Promise<void> {
2970
+ try {
2971
+ await this.settingsOperations.run(source.localSessionId, async () => {
2972
+ if (!this.canContinueAfterRestart(attempt, source)) throw new TurnStoppedBeforeSubmissionError();
2973
+ const current = this.store.getSession(source.localSessionId)!;
2974
+ const loaded = await this.loadSession({ ...current, contextKey: attempt.contextKey });
2975
+ await this.assertRecoveryContinuation(loaded, attempt.attemptId);
2976
+ await this.notifyRecoveryResult(attempt, "continuing");
2977
+ const turnId = await this.startTurnNow(loaded, attempt.promptText,
2978
+ attempt.replyMessageId ? { messageId: attempt.replyMessageId, replyInThread: true } : undefined,
2979
+ undefined, {
2980
+ attemptId: attempt.attemptId, executionGeneration: attempt.executionGeneration,
2981
+ trigger: "recovery_continuation", parentSourceTurnId: attempt.recoveredFromTurnId,
2982
+ recoveryContinuationTurnId: attempt.recoveredFromTurnId,
2983
+ messageId: attempt.messageId, displayPrompt: "重启后自动继续未完成的任务",
2984
+ });
2985
+ this.store.rebindPendingTurnMessages(source.localSessionId, attempt.recoveredFromTurnId!, turnId);
2986
+ });
2987
+ } catch (error) {
2988
+ const current = this.store.getTurnAttempt(attempt.attemptId);
2989
+ if (current?.submissionState === "not_submitted") {
2990
+ this.store.updateTurnAttempt(attempt.attemptId, { status: error instanceof TurnStoppedBeforeSubmissionError ? "cancelled" : "failed" });
2991
+ await this.notifyRecoveryResult(attempt, "cancelled", error instanceof TurnStoppedBeforeSubmissionError
2992
+ ? "任务、指令或运行设置已变化,已取消本次自动续跑。"
2993
+ : "重启后的自动续跑未能启动,请检查 Agent 状态后发送消息继续。");
2994
+ }
2995
+ if (!(error instanceof TurnStoppedBeforeSubmissionError)) {
2996
+ this.logger.warn({ error, attemptId: attempt.attemptId }, "Failed to continue an interrupted task after restart.");
2997
+ }
2998
+ } finally {
2999
+ const latest = this.store.getSession(source.localSessionId);
3000
+ const active = this.runtimes.forAgent(source.agentName).getSession(source.localSessionId)?.activeTurnId;
3001
+ if (latest && latest.lastTurnId === attempt.recoveredFromTurnId && latest.status !== "closed" && !active) {
3002
+ this.store.updateSession(source.localSessionId, { status: "ready" });
3003
+ }
3004
+ if (!this.recoveryClosed) await this.scheduleNextQueuedPrompt(source.localSessionId);
3005
+ }
3006
+ }
3007
+
3008
+ private async notifyRecoveryResult(
3009
+ attempt: TurnAttemptRecord,
3010
+ result: keyof typeof RECOVERY_RESULTS,
3011
+ message: string = RECOVERY_RESULTS[result],
3012
+ ): Promise<void> {
3013
+ if (this.recoveryClosed || attempt.executionGeneration !== this.store.executionGeneration(attempt.localSessionId)) return;
3014
+ const key = `${attempt.attemptId}:${result}`;
3015
+ if (this.recoveryResultNotices.has(key)) return;
3016
+ this.recoveryResultNotices.add(key);
3017
+ const replyTarget = attempt.replyMessageId
3018
+ ? { messageId: attempt.replyMessageId, replyInThread: true as const } : undefined;
3019
+ try {
3020
+ await this.outbound.withReplyTarget(attempt.contextKey, replyTarget, () =>
3021
+ this.outbound.sendText(attempt.contextKey, message),
3022
+ );
3023
+ } catch (error) {
3024
+ this.logger.warn({ error, attemptId: attempt.attemptId, result }, "Failed to send the task recovery result.");
3025
+ }
3026
+ }
3027
+
2890
3028
  private async markAttemptUnknown(attempt: TurnAttemptRecord, message: string): Promise<void> {
3029
+ const recovering = this.recoveryRetryStartedAt.has(attempt.attemptId);
2891
3030
  clearTimeout(this.recoveryRetryTimers.get(attempt.attemptId));
2892
3031
  this.recoveryRetryTimers.delete(attempt.attemptId);
2893
3032
  this.recoveryRetryStartedAt.delete(attempt.attemptId);
@@ -2906,7 +3045,10 @@ export class ProxySessionController {
2906
3045
  if (!active) this.store.updateSession(session.localSessionId, { status: "ready" });
2907
3046
  }
2908
3047
  if (turnId) await this.outbound.onEvent({ type: "turn_status_unknown", sessionId: session.localSessionId, turnId, message });
2909
- else await this.outbound.sendText(attempt.contextKey, message);
3048
+ else if (!recovering || this.store.schedules.getRun(attempt.attemptId)) await this.outbound.sendText(attempt.contextKey, message);
3049
+ if (recovering && !this.store.schedules.getRun(attempt.attemptId)) {
3050
+ await this.notifyRecoveryResult(attempt, "unknown", message);
3051
+ }
2910
3052
  }
2911
3053
 
2912
3054
  private async reconcileRecoveredRemoteTurn(
@@ -2997,7 +3139,10 @@ export class ProxySessionController {
2997
3139
  turnId, startedAt: continued.startedAt });
2998
3140
  const synchronized = await loaded.runtime.synchronizeSession(session.localSessionId);
2999
3141
  this.recoveryRetryStartedAt.delete(attempt.attemptId);
3000
- if (synchronized.activeTurnId) this.recoveredLiveAttempts.add(attempt.attemptId);
3142
+ if (synchronized.activeTurnId === turnId) {
3143
+ this.recoveredLiveAttempts.add(attempt.attemptId);
3144
+ await this.notifyRecoveryResult(attempt, "reattached");
3145
+ }
3001
3146
  return;
3002
3147
  }
3003
3148
  const oldCardTurnId = attempt.pendingTurnId ?? attempt.turnId;
@@ -3033,6 +3178,7 @@ export class ProxySessionController {
3033
3178
  if (synchronized.activeTurnId) {
3034
3179
  this.recoveredLiveAttempts.add(attempt.attemptId);
3035
3180
  this.scheduleRecoveryRetry(attempt.attemptId, synchronized.activeTurnId);
3181
+ if (synchronized.activeTurnId === turnId) await this.notifyRecoveryResult(attempt, "reattached");
3036
3182
  }
3037
3183
  }
3038
3184
 
@@ -3087,6 +3233,7 @@ export class ProxySessionController {
3087
3233
  },
3088
3234
  );
3089
3235
  if (attempt.messageId) await this.bindMessageReactionToTurn(attempt.messageId, session.localSessionId, turnId);
3236
+ await this.notifyRecoveryResult(attempt, "submitted");
3090
3237
  }
3091
3238
 
3092
3239
  private async restorePersistedMessageReactions(): Promise<void> {
@@ -3094,6 +3241,8 @@ export class ProxySessionController {
3094
3241
  const terminalTurns = new Map<string, "completed" | "failed" | "cancelled">();
3095
3242
  for (const reaction of pending) {
3096
3243
  if (!reaction.turnId || !reaction.localSessionId) continue;
3244
+ const continuation = this.store.findIncompleteTurnAttemptForSession(reaction.localSessionId);
3245
+ if (continuation && isPendingRecoveryContinuation(continuation) && continuation.recoveredFromTurnId === reaction.turnId) continue;
3097
3246
  const session = this.store.getSession(reaction.localSessionId);
3098
3247
  if (session?.lastTurnId !== reaction.turnId) continue;
3099
3248
  if (session.lastTurnStatus === "completed" || session.lastTurnStatus === "failed" || session.lastTurnStatus === "cancelled") {
@@ -3139,6 +3288,7 @@ export class ProxySessionController {
3139
3288
  localImagePaths?: string[],
3140
3289
  displayPrompt?: string,
3141
3290
  ): Promise<void> {
3291
+ this.recoverySupersededSessions.add(record.localSessionId);
3142
3292
  const executionGeneration = this.store.executionGeneration(record.localSessionId);
3143
3293
  if (this.llmRetryingSessions.has(record.localSessionId) || this.planHandoffs.has(record.localSessionId)) {
3144
3294
  const queued = this.persistQueuedPrompt(record.localSessionId, contextKey, text, {
@@ -4440,6 +4590,7 @@ export class ProxySessionController {
4440
4590
 
4441
4591
  try {
4442
4592
  this.assertExecutionGeneration(loaded.record.localSessionId, executionGeneration);
4593
+ if (options.recoveryContinuationTurnId) await this.assertRecoveryContinuation(loaded, attemptId);
4443
4594
  if (options.approvedPlanTurnId && (this.planHandoffs.get(loaded.record.localSessionId) !== options.approvedPlanTurnId
4444
4595
  || this.sessionResets.has(loaded.record.localSessionId))) {
4445
4596
  throw new Error("方案执行已取消。");
@@ -5232,6 +5383,19 @@ export class ProxySessionController {
5232
5383
  if (event.type === "turn_started" && current?.lastTurnId && current.lastTurnId !== event.turnId
5233
5384
  && (saved || this.store.getTurnRuntimeOrigin(event.turnId))) return;
5234
5385
  }
5386
+ const recoveringAttempt = event.type === "turn_completed" || event.type === "turn_cancelled" || event.type === "turn_failed"
5387
+ ? this.store.findIncompleteTurnAttemptByTurnId(event.turnId) : undefined;
5388
+ const recoveryResultAttempt = recoveringAttempt && this.recoveryRetryStartedAt.has(recoveringAttempt.attemptId)
5389
+ && recoveringAttempt.status !== "cancelling"
5390
+ && recoveringAttempt.executionGeneration === this.store.executionGeneration(event.sessionId)
5391
+ ? recoveringAttempt : undefined;
5392
+ const recoverySource = recoveryResultAttempt ? this.store.getSession(event.sessionId) : undefined;
5393
+ const recoveryContinuation = event.type === "turn_cancelled" && recoveryResultAttempt && recoverySource
5394
+ && this.canContinueAfterRestart(recoveryResultAttempt, recoverySource)
5395
+ ? this.store.claimRecoveryContinuation(recoveryResultAttempt.attemptId, RECOVERY_CONTINUATION_PROMPT) : undefined;
5396
+ if (event.type === "turn_cancelled" && recoveryResultAttempt) {
5397
+ event = { ...event, message: recoveryContinuation ? RECOVERY_RESULTS.continuing : RECOVERY_RESULTS.cancelled };
5398
+ }
5235
5399
  if ("turnId" in event) {
5236
5400
  const recoveryAttempt = this.recoveryRetryStartedAt.size > 0
5237
5401
  ? this.store.findIncompleteTurnAttemptByTurnId(event.turnId) : undefined;
@@ -5301,7 +5465,7 @@ export class ProxySessionController {
5301
5465
  this.store.updateSession(event.sessionId, { status: "running" });
5302
5466
  this.store.updateRuntimeSession(event.sessionId, { lastTurnId: event.turnId, lastTurnStatus: "running" });
5303
5467
  } else if (event.type === "turn_completed" || event.type === "turn_cancelled" || event.type === "turn_failed") {
5304
- const attempt = this.store.findIncompleteTurnAttemptByTurnId(event.turnId);
5468
+ const attempt = this.store.findIncompleteTurnAttemptByTurnId(event.turnId) ?? recoveryResultAttempt;
5305
5469
  if (attempt) {
5306
5470
  clearTimeout(this.recoveryRetryTimers.get(attempt.attemptId));
5307
5471
  this.recoveryRetryTimers.delete(attempt.attemptId);
@@ -5353,6 +5517,15 @@ export class ProxySessionController {
5353
5517
  }
5354
5518
 
5355
5519
  if (event.type === "turn_completed" || event.type === "turn_cancelled" || event.type === "turn_failed") {
5520
+ if (recoveryContinuation && recoverySource) {
5521
+ await this.submitRecoveryContinuation(recoveryContinuation, recoverySource);
5522
+ if (presentationError) throw presentationError;
5523
+ return;
5524
+ }
5525
+ if (recoveryResultAttempt) {
5526
+ await this.notifyRecoveryResult(recoveryResultAttempt,
5527
+ event.type === "turn_completed" ? "completed" : event.type === "turn_failed" ? "failed" : "cancelled");
5528
+ }
5356
5529
  await this.refreshGoalCards(event.sessionId);
5357
5530
  const terminalStatus = event.type === "turn_completed"
5358
5531
  ? "completed"
@@ -5599,6 +5772,7 @@ export class ProxySessionController {
5599
5772
  }
5600
5773
 
5601
5774
  private async startNextQueuedPromptIfIdleNow(sessionId: string): Promise<void> {
5775
+ if (this.recoveryClosed) return;
5602
5776
  const executionGeneration = this.store.executionGeneration(sessionId);
5603
5777
  if (this.planHandoffs.has(sessionId) || this.sessionResets.has(sessionId)) return;
5604
5778
  if (this.store.hasUnknownTurnAttemptForSession(sessionId)) return;
@@ -10420,6 +10594,11 @@ function remoteTurnMatchesAttempt(remote: RemoteSessionSummary | undefined, atte
10420
10594
  return Boolean(attempt.turnId && remote?.lastTurnId === attempt.turnId);
10421
10595
  }
10422
10596
 
10597
+ function isPendingRecoveryContinuation(attempt: TurnAttemptRecord): boolean {
10598
+ return attempt.attemptId.startsWith("recovery_continuation:") && Boolean(attempt.recoveredFromTurnId)
10599
+ && !attempt.turnId && attempt.submissionState === "not_submitted" && isIncompleteTurnAttemptStatus(attempt.status);
10600
+ }
10601
+
10423
10602
  function isRecoveryAttemptRecent(attempt: TurnAttemptRecord, cutoff: number): boolean {
10424
10603
  const updatedAt = Date.parse(attempt.updatedAt);
10425
10604
  return Number.isFinite(updatedAt) && updatedAt >= cutoff;
@@ -112,7 +112,7 @@ export type AgentEvent =
112
112
  | { type: "approval_requested"; sessionId: string; turnId: string; request: ApprovalRequest }
113
113
  | { type: "approval_resolved"; sessionId: string; turnId: string; requestId: string; decision: ApprovalDecision; automatic?: boolean }
114
114
  | { type: "turn_completed"; sessionId: string; turnId: string; finalResponse: string; durationMs?: number; approvedPlan?: boolean }
115
- | { type: "turn_cancelled"; sessionId: string; turnId: string }
115
+ | { type: "turn_cancelled"; sessionId: string; turnId: string; message?: string }
116
116
  | { type: "turn_status_unknown"; sessionId: string; turnId: string; message: string }
117
117
  | { type: "turn_failed"; sessionId: string; turnId: string; message: string };
118
118
 
@@ -3,7 +3,7 @@ import type { RuntimeSession } from "../runtime/types.js";
3
3
  import { createId } from "../utils/id.js";
4
4
 
5
5
  export type ExecutionTrigger = "user" | "queue" | "schedule" | "recovery" | "retry"
6
- | "plan_handoff" | "response_continuation";
6
+ | "plan_handoff" | "response_continuation" | "recovery_continuation";
7
7
 
8
8
  export interface ExecutionProvenance {
9
9
  submissionId: string;
@@ -774,11 +774,48 @@ export class StateStore {
774
774
  return row ? mapTurnAttempt(row) : undefined;
775
775
  }
776
776
 
777
+ findLatestTurnAttemptByTurnId(turnId: string): TurnAttemptRecord | undefined {
778
+ const row = this.db.prepare("SELECT * FROM turn_attempts WHERE turn_id = ? ORDER BY rowid DESC LIMIT 1")
779
+ .get(turnId) as TurnAttemptRow | undefined;
780
+ return row ? mapTurnAttempt(row) : undefined;
781
+ }
782
+
783
+ isLatestTurnAttempt(attemptId: string): boolean {
784
+ return Boolean(this.db.prepare(`SELECT 1 FROM turn_attempts source WHERE source.attempt_id = ?
785
+ AND NOT EXISTS (SELECT 1 FROM turn_attempts newer
786
+ WHERE newer.local_session_id = source.local_session_id AND newer.rowid > source.rowid)`)
787
+ .get(attemptId));
788
+ }
789
+
790
+ claimRecoveryContinuation(attemptId: string, promptText: string): TurnAttemptRecord | undefined {
791
+ return this.db.transaction(() => {
792
+ const source = this.getTurnAttempt(attemptId);
793
+ if (!source?.turnId || source.submissionState !== "submitted" || !isIncompleteTurnAttemptStatus(source.status)
794
+ || source.executionGeneration !== this.executionGeneration(source.localSessionId)
795
+ || !this.isLatestTurnAttempt(attemptId) || this.countQueuedPrompts(source.localSessionId) > 0) return undefined;
796
+ const continuationId = `recovery_continuation:${source.localSessionId}:${source.turnId}`;
797
+ if (this.getTurnAttempt(continuationId)) return undefined;
798
+ // Commit the terminal source and its one-shot successor together, including across a second crash.
799
+ this.updateTurnAttempt(attemptId, { status: "cancelled" });
800
+ return this.createTurnAttempt({
801
+ attemptId: continuationId, localSessionId: source.localSessionId, contextKey: source.contextKey,
802
+ promptText, messageId: source.messageId, replyMessageId: source.replyMessageId,
803
+ recoveredFromTurnId: source.turnId, recoveryCount: 1, executionGeneration: source.executionGeneration,
804
+ });
805
+ })();
806
+ }
807
+
777
808
  hasTurnAttemptsForSession(localSessionId: string): boolean {
778
809
  return Boolean(this.db.prepare("SELECT 1 FROM turn_attempts WHERE local_session_id = ? LIMIT 1")
779
810
  .get(localSessionId));
780
811
  }
781
812
 
813
+ hasStoppedTurnAttemptForTurn(turnId: string): boolean {
814
+ return Boolean(this.db.prepare(`SELECT 1 FROM turn_attempts WHERE turn_id = ?
815
+ AND execution_generation < COALESCE((SELECT generation FROM task_execution_control
816
+ WHERE local_session_id = turn_attempts.local_session_id), 0) LIMIT 1`).get(turnId));
817
+ }
818
+
782
819
  findIncompleteTurnAttemptForSession(localSessionId: string): TurnAttemptRecord | undefined {
783
820
  const row = this.db.prepare(`
784
821
  SELECT * FROM turn_attempts
@@ -799,6 +836,37 @@ export class StateStore {
799
836
  return rows.map(mapTurnAttempt);
800
837
  }
801
838
 
839
+ listRecentlyInterruptedTurnAttempts(cutoff: string): TurnAttemptRecord[] {
840
+ const rows = this.db.prepare(`SELECT source.* FROM turn_attempts source
841
+ WHERE source.status = 'cancelled' AND source.turn_id IS NOT NULL
842
+ AND source.submission_state = 'submitted' AND source.updated_at >= ?
843
+ AND source.execution_generation = COALESCE((SELECT generation FROM task_execution_control
844
+ WHERE local_session_id = source.local_session_id), 0)
845
+ AND NOT EXISTS (SELECT 1 FROM turn_attempts newer
846
+ WHERE newer.local_session_id = source.local_session_id AND newer.rowid > source.rowid)
847
+ ORDER BY source.updated_at, source.rowid`).all(cutoff) as TurnAttemptRow[];
848
+ return rows.map(mapTurnAttempt);
849
+ }
850
+
851
+ prepareInterruptedTurnAttemptRecovery(attemptId: string, cutoff: string): TurnAttemptRecord | undefined {
852
+ return this.db.transaction(() => {
853
+ const source = this.getTurnAttempt(attemptId);
854
+ if (!source?.turnId || source.status !== "cancelled" || source.submissionState !== "submitted"
855
+ || source.updatedAt < cutoff || source.executionGeneration !== this.executionGeneration(source.localSessionId)
856
+ || !this.isLatestTurnAttempt(attemptId)) return undefined;
857
+ // Checking an interruption is not new execution activity; retain the original recovery deadline.
858
+ this.db.prepare("UPDATE turn_attempts SET status = 'recovering' WHERE attempt_id = ?").run(attemptId);
859
+ return this.getTurnAttempt(attemptId);
860
+ })();
861
+ }
862
+
863
+ markTurnAttemptRecovering(attemptId: string): void {
864
+ this.db.prepare(`UPDATE turn_attempts SET status = 'recovering' WHERE attempt_id = ?
865
+ AND status IN ('accepted', 'running', 'recovering')
866
+ AND execution_generation = COALESCE((SELECT generation FROM task_execution_control
867
+ WHERE local_session_id = turn_attempts.local_session_id), 0)`).run(attemptId);
868
+ }
869
+
802
870
  listCancellationRequestedTurnAttempts(): TurnAttemptRecord[] {
803
871
  const rows = this.db.prepare(`
804
872
  SELECT * FROM turn_attempts
@@ -862,8 +930,8 @@ export class StateStore {
862
930
  this.db.prepare(`
863
931
  UPDATE turn_attempts
864
932
  SET status = ?, updated_at = ?
865
- WHERE turn_id = ?
866
- `).run(status, new Date().toISOString(), turnId);
933
+ WHERE turn_id = ? AND status <> ?
934
+ `).run(status, new Date().toISOString(), turnId, status);
867
935
  const runs = this.db.prepare(`SELECT s.id FROM scheduled_runs s JOIN turn_attempts t ON t.attempt_id = s.id
868
936
  WHERE t.turn_id = ?`).all(turnId) as Array<{ id: string }>;
869
937
  for (const run of runs) this.schedules.finish(run.id, status);
@@ -882,7 +950,7 @@ export class StateStore {
882
950
  requestTurnAttemptCancellation(turnId: string): TurnAttemptRecord | undefined {
883
951
  const existing = this.findIncompleteTurnAttemptByTurnId(turnId);
884
952
  if (!existing) return undefined;
885
- this.updateTurnAttempt(existing.attemptId, { status: "cancelling" });
953
+ this.requestSessionExecutionStop(existing.localSessionId);
886
954
  return existing;
887
955
  }
888
956
 
@@ -10,7 +10,7 @@ export async function sendTerminalAuthorization(
10
10
  const card = new CardRenderer().renderTerminalAuthorization(view);
11
11
  if (isThreadContextKey(view.contextKey)) {
12
12
  if (!outbound.replyInteractiveCard || !view.commandCardMessageId) {
13
- throw new Error("无法向原话题发送终端授权卡,请重新打开命令卡片。");
13
+ throw new Error("无法向原话题发送终端管理卡,请重新打开命令卡片。");
14
14
  }
15
15
  return outbound.replyInteractiveCard(view.contextKey, { messageId: view.commandCardMessageId, replyInThread: true }, card);
16
16
  }
@@ -3,14 +3,15 @@ export function terminalPage(base: string, recovery = false): string {
3
3
  return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
4
  <title>AgentBot Terminal</title><link rel="stylesheet" href="${base}/assets/xterm.css"><link rel="stylesheet" href="${base}/assets/terminal.css">
5
5
  <script defer src="${base}/assets/xterm.js"></script><script defer src="${base}/assets/fit.js"></script><script defer src="${base}/assets/terminal.js"></script></head>
6
- <body data-base="${base}" data-recovery="${recovery}"><header><strong>AgentBot <span>Terminal</span></strong><div id="status" role="status">尚未连接</div><button id="connect">请求连接</button><button id="interrupt" disabled>Ctrl+C</button><button id="close" disabled>关闭终端</button></header>
7
- <section id="welcome"><h1>在浏览器中使用本机终端</h1><p>命令在 AgentBot 所在电脑上执行,拥有其系统用户权限。不会自动执行或接管原卡片中的命令。</p><p>点击请求连接,然后返回命令所在的飞书会话或话题,由 AgentBot 所有者核对验证码并授权。不要批准非本人发起的请求。</p><button id="welcome-connect" type="button">请求连接</button><p id="code"></p></section><div id="terminal"></div>
6
+ <body data-base="${base}" data-recovery="${recovery}"><header><strong>AgentBot <span>Terminal</span></strong><div id="status" role="status">尚未连接</div><button id="connect">连接</button><button id="interrupt" disabled>Ctrl+C</button><button id="close" disabled>关闭终端</button></header>
7
+ <section id="welcome"><h1>连接终端</h1><p>此终端拥有 AgentBot 所在电脑的系统用户权限。</p><label for="password">终端密码</label><div class="password-row"><input id="password" type="password" autocomplete="current-password" maxlength="256" autofocus><button id="welcome-connect" type="button">连接</button></div></section><div id="terminal"></div>
8
8
  <footer id="details">前台连接时不因空闲关闭;后台空闲 30 分钟或网页断开 3 分钟后自动关闭 Shell · 成功重连取消断开计时并重置空闲计时 · 可从原会话的终端管理卡打开或关闭终端</footer></body></html>`;
9
9
  }
10
10
 
11
11
  export const TERMINAL_CSS = `
12
12
  #welcome-connect{padding:10px 20px;font:inherit}
13
- :root{color-scheme:dark;font:14px system-ui,sans-serif;background:#10141b;color:#dbe4f1}*{box-sizing:border-box}body{margin:0;height:100dvh;display:flex;flex-direction:column}header{display:flex;gap:12px;align-items:center;padding:12px 18px;background:#191f2b;border-bottom:1px solid #303a4d;flex-wrap:wrap}header strong{font-size:17px}header strong span{font-weight:400;color:#9aacc7}#status{flex:1;color:#adbfdb;font-size:13px}button{background:#25334a;border:1px solid #415775;border-radius:7px;padding:8px 12px;color:#e5efff;cursor:pointer}button:hover{background:#304661}button:disabled{opacity:.45;cursor:default}#close{border-color:#86505a}#welcome{margin:40px auto;max-width:780px;padding:0 24px;line-height:1.8}h1{font-size:25px}#code{font-size:24px;letter-spacing:3px;color:#84c1ff}#terminal{flex:1;min-height:0;padding:12px 14px;display:none}.xterm{height:100%}footer{font-size:12px;color:#8f9eb7;padding:9px 18px;border-top:1px solid #293142}body.connected #welcome{display:none}body.connected #terminal{display:block}@media(max-width:650px){header{padding:10px;gap:8px}#status{min-width:100%}footer{padding:7px 10px}#terminal{padding:6px}}
13
+ #welcome{width:100%}.password-row{display:flex;gap:12px;margin-top:8px;max-width:440px}#password{min-width:0;flex:1;background:#191f2b;border:1px solid #415775;border-radius:6px;padding:10px 12px;color:inherit;font:inherit}#password:focus{outline:2px solid #84c1ff;outline-offset:2px}
14
+ :root{color-scheme:dark;font:14px system-ui,sans-serif;background:#10141b;color:#dbe4f1}*{box-sizing:border-box}body{margin:0;height:100dvh;display:flex;flex-direction:column}header{display:flex;gap:12px;align-items:center;padding:12px 18px;background:#191f2b;border-bottom:1px solid #303a4d;flex-wrap:wrap}header strong{font-size:17px}header strong span{font-weight:400;color:#9aacc7}#status{flex:1;color:#adbfdb;font-size:13px}button{background:#25334a;border:1px solid #415775;border-radius:7px;padding:8px 12px;color:#e5efff;cursor:pointer}button:hover{background:#304661}button:disabled{opacity:.45;cursor:default}#close{border-color:#86505a}#welcome{margin:40px auto;max-width:780px;padding:0 24px;line-height:1.8}h1{font-size:25px}#terminal{flex:1;min-height:0;padding:12px 14px;display:none}.xterm{height:100%}footer{font-size:12px;color:#8f9eb7;padding:9px 18px;border-top:1px solid #293142}body.connected #welcome{display:none}body.connected #terminal{display:block}@media(max-width:650px){header{padding:10px;gap:8px}#status{min-width:100%}footer{padding:7px 10px}#terminal{padding:6px}}
14
15
  `;
15
16
 
16
17
  export const TERMINAL_SCRIPT = String.raw`(() => {
@@ -18,6 +19,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
18
19
  const status = document.getElementById('status');
19
20
  const connect = document.getElementById('connect');
20
21
  const welcomeConnect = document.getElementById('welcome-connect');
22
+ const password = document.getElementById('password');
21
23
  const close = document.getElementById('close');
22
24
  const interrupt = document.getElementById('interrupt');
23
25
  const storageKey = 'agentbot-terminal:' + location.pathname;
@@ -48,10 +50,11 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
48
50
  }
49
51
  function buttons(retry = false) {
50
52
  for (const button of [connect, welcomeConnect]) {
51
- button.textContent = session ? '重新连接' : recovery ? '请求恢复连接' : '请求连接';
53
+ button.textContent = session ? '重新连接' : recovery ? '恢复连接' : '连接';
52
54
  button.disabled = busy || (!!session && !retry);
53
55
  }
54
56
  close.disabled = busy || !session;
57
+ password.disabled = busy;
55
58
  }
56
59
  function invalidate() {
57
60
  epoch++; clearTimeout(retryTimer); clearTimeout(socketTimer);
@@ -62,7 +65,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
62
65
  }
63
66
  function forget() {
64
67
  session = undefined; sessionStorage.removeItem(storageKey);
65
- document.getElementById('code').textContent = ''; buttons(true);
68
+ buttons(true);
66
69
  }
67
70
  function end(text) { stopped = true; invalidate(); forget(); status.textContent = text; }
68
71
  function fail(text) { stopped = true; invalidate(); status.textContent = text; buttons(true); }
@@ -158,7 +161,6 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
158
161
  const result = await post('status', current, controller);
159
162
  if (generation !== epoch || current !== session || stopped || !awake()) return;
160
163
  if (result.state === 'approved' || result.state === 'running') openSocket();
161
- else if (result.state === 'pending') { failures = 0; status.textContent = '等待原会话中的所有者授权'; buttons(); schedule(1500); }
162
164
  else end(result.message || '授权已失效,请重新请求连接');
163
165
  } catch (error) {
164
166
  if (generation !== epoch || current !== session || stopped || !awake()) return;
@@ -171,19 +173,21 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
171
173
  if (busy) return;
172
174
  stopped = false; failures = 0; invalidate();
173
175
  if (session) { status.textContent = '正在恢复已有终端授权…'; buttons(); check(); return; }
174
- busy = true; buttons(); status.textContent = '正在请求飞书授权…';
176
+ document.body.classList.remove('connected');
177
+ if (!password.value) { status.textContent = '请输入终端密码'; password.focus(); return; }
178
+ busy = true; buttons(); status.textContent = '正在验证密码…';
175
179
  try {
176
- document.body.classList.remove('connected');
177
180
  if (!globalThis.crypto?.getRandomValues) throw new Error('浏览器不支持安全随机数,请使用新版浏览器。');
178
181
  const browserKey = Array.from(crypto.getRandomValues(new Uint8Array(32)), (n) => n.toString(16).padStart(2,'0')).join('');
179
- const result = await post('request', {launch:location.pathname,browserKey});
180
- session = {requestId:result.requestId,browserKey,code:result.code}; sessionStorage.setItem(storageKey,JSON.stringify(session));
181
- document.getElementById('code').textContent = '验证码:' + result.code;
182
- status.textContent = awake() ? '等待原会话中的所有者授权' : '返回网页后将自动查询授权状态';
183
- } catch (error) { status.textContent = '请求授权失败:' + message(error); }
182
+ const result = await post('request', {launch:location.pathname,browserKey,password:password.value});
183
+ password.value = '';
184
+ session = {requestId:result.requestId,browserKey}; sessionStorage.setItem(storageKey,JSON.stringify(session));
185
+ status.textContent = '密码已验证,正在连接终端…';
186
+ } catch (error) { status.textContent = '连接失败:' + message(error); password.focus(); }
184
187
  finally { busy = false; buttons(!session); }
185
188
  check();
186
189
  };
190
+ password.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); welcomeConnect.click(); } });
187
191
  interrupt.onclick = () => { if (ws?.readyState === WebSocket.OPEN && !interrupt.disabled) ws.send(JSON.stringify({type:'input',data:String.fromCharCode(3)})); };
188
192
  close.onclick = async () => {
189
193
  if (busy || !session || !confirm('关闭该终端和 Shell?已脱离终端的后台进程可能继续运行。')) return;
@@ -208,6 +212,5 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
208
212
  window.addEventListener('offline', () => { offline = true; suspend(); });
209
213
  window.addEventListener('online', () => { offline = false; resume(); });
210
214
  window.addEventListener('focus', resume);
211
- if (session?.code) document.getElementById('code').textContent = '验证码:' + session.code;
212
215
  buttons(); check();
213
216
  })();`;